Compare commits

...
Author SHA1 Message Date
Canina Hermes dc34c57a0c ci: route exact limited timestamp release branch to Stage
Deploy Canina / deploy (push) Successful in 2m51s
2026-10-30 13:28:55 +00:00
Canina Hermes c97ea01ba9 fix(blog): project truthful publication and substantive edit timestamps 2026-10-30 13:21:07 +00:00
Canina Automation 00ba4360cf fix(search): normalize search expansion lookup for hamza-ye variants
Deploy Canina / deploy (push) Successful in 2m42s
2026-10-27 11:56:13 +00:00
Canina Automation 8669d183d5 feat(search): add bidirectional domain aliases (taurine/taurin, carnitine) and include ingredientCardSlug
Deploy Canina / deploy (push) Successful in 2m8s
2026-10-27 11:49:15 +00:00
Canina Automation 66b9d75524 feat(search-pagination): implement normalized weighted search and standardized pagination across blogs, products and wiki
Deploy Canina / deploy (push) Successful in 4m25s
2026-10-27 11:39:55 +00:00
Canina Automation d3a0a61d79 feat(storefront): increase blog list limit to 200, resolve wiki taurine alias and expand related products search
Deploy Canina / deploy (push) Successful in 2m42s
2026-10-27 10:18:37 +00:00
Canina Automation 0ad39bb92c fix(blogs): enforce atomic optimistic update concurrency
Deploy Canina / deploy (push) Successful in 52s
2026-10-27 08:20:33 +00:00
Canina Automation 0e952ef701 fix(prod-ci): add --repair-empty to revalidation provisioning on production release
Deploy Canina / deploy (push) Successful in 39s
2026-10-26 20:30:19 +00:00
Canina Automation f1382e943c ci: retry production release after runner permission verification
Deploy Canina / deploy (push) Failing after 11s
2026-10-26 20:25:38 +00:00
Canina Automation 53fccc2d3c fix(ci): route production code-only release through safe locked deployment without migrations
Deploy Canina / deploy (push) Failing after 10s
2026-10-26 20:17:27 +00:00
Canina Automation 9ae839138c [verified] Fix Stage readiness against paginated public blogs contract
Deploy Canina / deploy (push) Successful in 39s
2026-10-26 19:19:26 +00:00
Canina Automation 0fa6abc53d [verified] fix Stage helper lock under daemon userns remapping
Deploy Canina / deploy (push) Failing after 7m24s
2026-10-26 18:50:29 +00:00
Canina Automation 2a32f31097 fix(stage): fence runtime authority and bound release transports
Deploy Canina / deploy (push) Failing after 5s
2026-10-26 18:25:16 +00:00
Canina Automation 52a7aebb51 fix(ci): prepare fail-closed exact-SHA code-only Stage release 2026-10-26 16:42:08 +00:00
Canina Automation af32ec14e1 fix(seo): provide explicit noindex and self-canonical for login and cart pages 2026-10-26 16:32:52 +00:00
Canina Automation e34156b2d3 fix(seo): normalize and safely encode wiki route slug to prevent double-encoding 404s 2026-10-26 16:32:52 +00:00
Canina Automation 721118787a fix(cache): restore backend-to-next revalidation and expose revalidation status safely
Deploy Canina / deploy (push) Successful in 1m10s
2026-10-26 15:12:10 +00:00
parsa aghaei 292ed7f920 fix(deploy): make stage_test_principal migration idempotent and resolve existing migrations before deploy
Deploy Canina / deploy (push) Successful in 1m7s
2026-10-26 14:00:35 +03:30
parsa aghaei 432f6a21c7 fix(deploy): resolve revalidation env missing and resolve legacy orchestration migrations
Deploy Canina / deploy (push) Failing after 1m2s
2026-10-26 13:45:41 +03:30
parsa aghaei 2087001ecd fix(ci): restore original working deploy.yml and direct deploy.sh from eb17c8e284
Deploy Canina / deploy (push) Failing after 2m59s
2026-10-26 12:57:29 +03:30
parsa aghaei ec93af0064 fix(admin): restore clean persian dashboard and monitoring page, remove extra workflows
Deploy Canina / deploy (push) Failing after 3s
2026-10-26 11:58:20 +03:30
parsa aghaei effe30ee58 feat(admin): remove governance, orchestration, approvals, tasks, and audit logs modules
Deploy Canina / deploy (push) Successful in 4m14s
2026-10-26 10:15:06 +03:30
devops 99f0c0d626 test(ops): fence rollout fixture evidence and systemctl writes
Deploy Canina / deploy (push) Failing after 1s
2026-10-26 05:10:41 +00:00
devops 1e27387016 fix(ops): retire exact CI-generated historical release deltas safely
Deploy Canina / deploy (push) Successful in 6m12s
2026-10-26 05:02:35 +00:00
devops c733a806bd test(ops): assert restored CI render state after acceptance
Deploy Canina / deploy (push) Failing after 2s
2026-10-26 04:58:26 +00:00
devops 23cbd693a8 test(ops): isolate host retention installer from rollout fixture
Deploy Canina / deploy (push) Failing after 2s
2026-10-26 04:58:12 +00:00
devops 366bc9fc88 fix(ops): conservative post-rollout retention and deterministic disk watch
Deploy Canina / deploy (push) Has been cancelled
2026-10-26 04:57:33 +00:00
devops b4420e54b7 fix(release): admit exact reviewed publisher SEO repair paths
Deploy Canina / deploy (push) Failing after 9h30m37s
2026-10-25 18:34:09 +00:00
devops 44d74d35e6 fix(blog): publish truthful image and team SEO metadata
Deploy Canina / deploy (push) Successful in 4m50s
2026-10-25 18:03:49 +00:00
devops 5897abcbad fix(ci): wait for final TCP server before schema restore
Approved narrow auth schema reconciliation / reconcile (push) Successful in 15s
Deploy Canina / deploy (push) Failing after 21s
2026-10-25 13:27:39 +00:00
devops b3b9e617b5 fix(stage): recreate cached frontend for release provenance 2026-10-25 13:26:49 +00:00
devops 6f9529d31f fix(release): admit exact schema CI push regression test
Deploy Canina / deploy (push) Successful in 2m17s
Approved narrow auth schema reconciliation / reconcile (push) Failing after 10s
2026-10-25 13:04:53 +00:00
devops c25b10f7f3 fix(ci): trigger approved auth schema operation on exact Gitea push refs 2026-10-25 13:04:34 +00:00
devops c69a779ecc fix(release): scope missing-column guard and allow exact schema repair 2026-10-25 12:59:40 +00:00
devops 688a0e4de5 fix(auth): prepare narrow approved CI schema reconciliation 2026-10-25 12:43:20 +00:00
devops cf9b80bbb3 fix(release): gate generated Prisma client against live production catalog 2026-10-25 12:43:20 +00:00
devops 2a341d3969 fix(deploy): supply internal npm registry build arg for production compose snapshot
Deploy Canina / deploy (push) Successful in 2m37s
2026-10-25 08:44:41 +00:00
devops 9275233d09 fix(release): admit audited freshness frontend fixes in production release allowlist
Deploy Canina / deploy (push) Failing after 1m50s
2026-10-25 08:34:29 +00:00
Canina Engineering 13dceaa460 fix(blog): expose author role and bound FAQ heading extraction
Deploy Canina / deploy (push) Successful in 10m28s
2026-10-25 08:19:44 +00:00
Canina Engineering 0ab2980ff4 fix(editorial): crash-safe upgrade with durable phase, previous metadata and recovery 2026-10-25 08:19:44 +00:00
devops fd14c05f3a fix(build): enforce secure TLS registry and binary verification 2026-10-25 08:19:30 +00:00
Canina Engineering cc0358bb12 fix(editorial): upgrade only verified installed runtime payload
Deploy Canina / deploy (push) Failing after 2m51s
2026-10-25 07:39:22 +00:00
Canina Engineering f94ef580fb fix(infra): integrate private revalidation provisioning and narrow release gates
Deploy Canina / deploy (push) Failing after 1m6s
2026-10-25 07:18:30 +00:00
devops 1bb6274b35 fix(frontend): restore full admin gates and preserve analytics protocol 2026-10-25 06:59:37 +00:00
Canina Engineering 448c250944 feat(deploy): gate immutable production CI promotion on audited Stage acceptance 2026-10-25 06:52:32 +00:00
Canina Engineering 5f5c3eb3b9 fix(infra): refresh Docker upstream DNS and provision revalidation runtime 2026-10-25 06:52:05 +00:00
Canina Engineering 3805057923 fix(blog): sort articles by raw publication timestamps 2026-10-25 06:42:52 +00:00
Canina Engineering f4678c48ca test(backend): isolate worker secrets and support HTTP listener 2026-10-25 06:30:18 +00:00
Canina Engineering c40e931168 fix(cache): target Next server for fallback revalidation 2026-10-25 05:51:26 +00:00
Hermes Agent e96a13b255 fix(editorial): synchronize corrected PMO skill bundle digest
Deploy Canina / deploy (push) Failing after 1m28s
2026-10-24 17:40:26 +00:00
Recovery Review 4413c2ef6c Test completed recovery over JWT HTTP Postgres and narrowly admit Stage reviewer
Deploy Canina / deploy (push) Failing after 1m25s
2026-10-24 17:35:56 +00:00
devops 65063e224a fix(editorial): constrain synthesis contract and admit fenced completed-run recovery 2026-10-24 17:35:42 +00:00
Hermes Agent c8063b5f2a fix(ci): admit exact installed runner evidence in ownership preflight
Deploy Canina / deploy (push) Successful in 3m44s
2026-10-24 16:32:27 +00:00
devops bfeb464bfb fix(editorial): honor functional bring-up model and completion policy
Deploy Canina / deploy (push) Failing after 1m30s
2026-10-24 16:26:50 +00:00
devops 860324e3a9 fix(editorial): retain bounded timeout session evidence and budget headroom
Deploy Canina / deploy (push) Successful in 3m44s
2026-10-24 15:38:04 +00:00
devops f705511164 fix(ci): install durable Stage cleanup worker during guarded rollout
Deploy Canina / deploy (push) Successful in 4m56s
2026-10-24 13:04:35 +00:00
devops 70a5449d35 fix(auth): persist generation-fenced Stage principal cleanup retries 2026-10-24 13:04:35 +00:00
devops 80a2e188cf fix(auth): fence temporary Stage credentials by account generation 2026-10-24 13:04:35 +00:00
devops e036c5d436 feat(stage): add opt-in bounded CI editorial test principal 2026-10-24 13:04:35 +00:00
devops ed77f87ab5 fix(editorial): preflight installed CLI and categorize profile failures
Deploy Canina / deploy (push) Successful in 3m17s
2026-10-24 11:31:48 +00:00
devops 4712433903 feat(admin): add fenced expired editorial run recovery control
Deploy Canina / deploy (push) Successful in 4m46s
2026-10-24 10:58:18 +00:00
devops f4add07780 fix(editorial): migrate exact CI ownership and fence failed research runs
Deploy Canina / deploy (push) Successful in 5m1s
2026-10-24 10:28:30 +00:00
devops 01b6f1d3d7 fix(editorial): fence runner identity before claim and expose safe stages 2026-10-24 10:28:30 +00:00
devops 60a4e14b4b fix(orchestration): expose queued Gate1 expiry and audited renewal
Deploy Canina / deploy (push) Successful in 4m51s
2026-10-24 09:53:07 +00:00
devops 6e465663bd test(editorial): resolve runner imports under CI discovery
Deploy Canina / deploy (push) Successful in 3m11s
2026-10-24 09:07:05 +00:00
devops b1142bd0c0 feat(editorial): implement bounded canonical-profile research runner
Deploy Canina / deploy (push) Failing after 1m22s
2026-10-24 09:01:46 +00:00
devops 50d0df822c fix(orchestration): atomically queue approvals with optional not-before schedule
Deploy Canina / deploy (push) Successful in 4m56s
2026-10-24 06:16:20 +00:00
devops ab2f330eb8 fix(admin): open fresh card decisions in confirmation dialog
Deploy Canina / deploy (push) Successful in 4m34s
2026-10-24 05:24:39 +00:00
devops ca3d4f6a16 fix(users): preserve superadmin roles and enforce actor privilege boundary 2026-10-24 05:14:22 +00:00
devops 3321bac22d fix(admin): render users list contract and allowlist user projection
Deploy Canina / deploy (push) Successful in 4m37s
2026-10-24 04:46:26 +00:00
devops 3e78b89cc1 fix(orchestration): provision explicit Stage owner Gate1 review access
Deploy Canina / deploy (push) Successful in 4m40s
Preserve independent proposer checks, canonical Admin UUID allowlist and deny ordinary admins. Revalidate pinned owner in read-only CI preflight; expose server-advertised card decisions and distinguish reservation from unknown real cost. Verified backend 42 HTTP/service/config tests and build; admin 18 relevant tests, app tsc and Vite build; 3 CI config tests and bash syntax.
2026-10-24 04:25:35 +00:00
devops bfb1841370 Add bounded approved editorial brief ingestion pending independent QA
Deploy Canina / deploy (push) Successful in 4m32s
2026-10-24 04:08:17 +00:00
devops 6ba2c51403 Fix orchestration actor role normalization at HTTP boundary
Deploy Canina / deploy (push) Successful in 4m50s
2026-10-24 04:01:38 +00:00
devops ba0aa5ee4e Isolate PMO credential from existing differently owned credentials directory
Deploy Canina / deploy (push) Successful in 4m30s
2026-10-24 03:45:51 +00:00
devops 7485c89e9b feat(editorial): wire serialized Stage runtime install and PMO proposal client
Deploy Canina / deploy (push) Failing after 1m23s
2026-10-24 03:41:43 +00:00
devops 8869ce2583 feat(editorial): add blocked profile policy distribution and isolated installer 2026-10-24 03:32:46 +00:00
devops 64419f6755 feat(orchestration): bind PMO editorial proposals to owner Gate1 2026-10-24 03:27:00 +00:00
devops 8cedc2cd67 feat(orchestration): expose owner Gate1 queue and audited hold decisions
Deploy Canina / deploy (push) Successful in 3m9s
2026-10-24 02:28:58 +00:00
devops 65a6fe1f0c Repair Persian RTL orchestration panel and honest unavailable states
Deploy Canina / deploy (push) Successful in 2m1s
Preserve bounded command safety and snapshot provenance; render structured Persian records without translating human evidence. Validated app/node TypeScript, Vite build and 394 tests across 64 files in private Node 22 runner.
2026-10-23 20:48:52 +00:00
devops afbee9cf70 Fix nginx access to admin fonts and correct Shabnam asset path
Deploy Canina / deploy (push) Successful in 2m23s
2026-10-23 20:16:25 +00:00
devops 5984242ce4 Add authenticated fixed Tech one-shot adapter with bounded transport and admission
Deploy Canina / deploy (push) Successful in 3m10s
2026-10-23 19:36:56 +00:00
devops c523acc9e8 Add separately admitted Tech source ingestion with retained unknown cost 2026-10-23 19:36:56 +00:00
devops c78bdbcdb5 Accept quoted opaque session cookie emitted by installed Hermes
Deploy Canina / deploy (push) Successful in 3m9s
2026-10-23 19:15:41 +00:00
devops 7a081e28df Avoid inherited virtual address cap breaking Docker Go client
Deploy Canina / deploy (push) Successful in 3m13s
2026-10-23 19:09:54 +00:00
devops 93d43fb261 Match reviewed Stage API prefix and readable public runtime entrypoint
Deploy Canina / deploy (push) Failing after 1m18s
2026-10-23 19:07:18 +00:00
devops 8c435ab09e Restore Stage availability with explicit runtime provisioning rollback
Deploy Canina / deploy (push) Successful in 1m32s
2026-10-23 18:31:23 +00:00
devops 4388a5c2e6 Recover prior accepted backend within CI provisioning after pre-start failure
Deploy Canina / deploy (push) Failing after 1m44s
2026-10-23 18:28:44 +00:00
devops 62a7a87378 Quote comma-containing tmpfs options as one Compose mount
Deploy Canina / deploy (push) Failing after 1m17s
2026-10-23 18:25:50 +00:00
devops 19583c5ad8 Bound Docker client runtime within provisioning resource ceiling
Deploy Canina / deploy (push) Failing after 1m38s
2026-10-23 18:23:28 +00:00
devops 1858eba3e6 Prevent provisioning import cache from dirtying approved CI checkout
Deploy Canina / deploy (push) Failing after 1m17s
2026-10-23 18:20:58 +00:00
devops cb20c2acb5 Enable reviewed Stage runtime provisioning across authenticated CI boundary
Deploy Canina / deploy (push) Failing after 1m18s
2026-10-23 18:17:43 +00:00
devops 105ab07fbd Wire opt-in Stage runtime provisioning before isolated render; verify snapshot and Compose integration 2026-10-23 18:15:47 +00:00
devops bf84e5da43 Bound pilot inference with ongoing heartbeat and process-group cancellation 2026-10-23 16:58:12 +00:00
devops 02badd0e25 Add fail-closed real Hermes Tech pilot and independent artifact QA proof 2026-10-23 16:49:09 +00:00
devops aa23c7ef91 Add opt-in CI Stage credential provisioning and restricted SQLite inventory export 2026-10-23 16:49:09 +00:00
devops 4b147b0091 Route CI Stage deployment through authenticated pinned SSH host boundary
Deploy Canina / deploy (push) Successful in 4m35s
2026-10-23 15:06:24 +00:00
devops 6950ff0d79 Isolate commit-pinned Stage releases from dirty operational checkout 2026-10-23 14:50:32 +00:00
devops cc9ec25388 Wire explicitly enabled worker startup and exact legacy rehearsal comparison 2026-10-23 14:41:48 +00:00
devops be2ff0719a feat(worker): add fail-closed reviewed startup config registration 2026-10-23 14:38:54 +00:00
devops 9d93707848 fix(worker): scope artifact access and harden immutable transport storage 2026-10-23 14:07:01 +00:00
devops aa99216c49 feat(worker): add authenticated bounded PREPARE HTTP executor tracer 2026-10-23 13:49:38 +00:00
devops 58d3794050 fix(admin): distinguish snapshot inventory from live runtime telemetry 2026-10-23 13:34:53 +00:00
devops 16f9610027 Wire runtime read routes with explicit file-granted startup opt-in 2026-10-23 13:26:29 +00:00
devops 2023dd4e36 Make snapshot inventory provenance explicit and deny false live readiness 2026-10-23 13:22:21 +00:00
devops 0bed6e0313 fix(admin): restore immutable PREPARE scope contract
Match d43aa02 metadata validation and exact DTO; distinguish missing safe-projection workflow scope from human review evidence. Preserve action normalization and explicit kill-switch capability. TDD regression RED verified; disposable admin 61 files / 381 tests, app+node TypeScript and build pass.
2026-10-23 13:13:41 +00:00
devops f29ba4ab8b fix(admin): reconcile bounded PREPARE backend contracts 2026-10-23 13:04:06 +00:00
devops 56b6696ca3 Preserve bounded PREPARE scope and normalize proposal conflicts 2026-10-23 13:04:06 +00:00
devops 0d0c67704c Complete safe admin workflow and authenticated runtime read UI 2026-10-23 12:53:06 +00:00
devops 09e8a890e0 Add bounded Stage PREPARE workflow with transactional leased outbox 2026-10-23 12:53:06 +00:00
devops 4b17a6fcc3 Add admin-scoped Hermes runtime reads and isolated pinned HTTP inventory 2026-10-23 12:53:06 +00:00
devops 5507fbcb29 Add server-only Hermes login broker with deny-first module registration 2026-10-23 11:05:27 +00:00
devops 176cc08a6b Restore guarded legacy approvals controller removed by background run 2026-10-23 09:33:42 +00:00
devops 5953c3cf75 Remove outdated approvals controller 2026-10-23 09:13:22 +00:00
devops 0952a482fb Checkpoint recovered orchestration core with tested fail-closed boundaries 2026-10-23 08:01:08 +00:00
devops c7f1d25e98 Integrate schema-first Stage rollout with immutable CI commit pinning 2026-10-23 07:52:49 +00:00
devops 841eab0556 Harden integration read-only boundaries and admin contracts 2026-10-23 06:38:39 +00:00
devops ac065fa911 feat(orchestration): integrate read-only v4 surfaces with mutation lockdown 2026-10-22 19:04:00 +00:00
devops 70d8128bfb feat(router-usage): add protected read-only consumption adapter with honest quota unknowns 2026-10-22 18:54:24 +00:00
devops 8c8ae66c7d feat(runtime): add fail-closed Hermes management adapter and contract gates 2026-10-22 18:54:24 +00:00
devops c8a3f35b0a feat(admin): add backend-authoritative orchestration command center and usage view 2026-10-22 18:54:24 +00:00
devops e5c83e87fe feat(orchestration): add v4 additive backend core and policy tests 2026-10-22 18:15:32 +00:00
devops eb17c8e284 feat(orchestration): enforce corporate guardrails, domain invariant and daily publishing rate limits
Deploy Canina / deploy (push) Successful in 28s
2026-10-20 20:43:39 +00:00
devops 459f8b59fe Merge develop into main: complete autonomous corporate orchestration, manager actions separation, and truthful QA gates
Deploy Canina / deploy (push) Successful in 50s
2026-10-20 20:01:23 +00:00
devops e6c705cef7 feat(orchestration): implement live HTTP artifact verification with soft-404 detection
Deploy Canina / deploy (push) Successful in 24s
2026-10-20 19:55:28 +00:00
devops 19c4bb451d merge(worker): integrate orchestration worker contract
Deploy Canina / deploy (push) Successful in 2m56s
2026-10-20 19:43:59 +00:00
devops f71b79a17f merge(market): integrate feat/safe-market-proposals-20261020 2026-10-20 19:43:31 +00:00
devops e3eb7ca205 merge(admin_ui): integrate feat/admin-manager-actions-separation-20261020 2026-10-20 19:43:30 +00:00
devops 2e54163d9e merge(backend): integrate feat/backend-approval-separation-20261020 2026-10-20 19:43:30 +00:00
devops 344f79039f feat(orchestration): implement atomic claims, root task selection and truthful completion gates 2026-10-20 19:42:53 +00:00
devops 02fe634944 feat(admin): implement approval separation and verifiable completion policy
- Separate B2B_SUPPLIER_STRATEGY strategic manager actions from digital tasks
- Ensure strategic proposals do not create/requeue digital tasks or set executedAt
- Ensure SEO and digital approvals transition actionable tasks to TODO
- Strengthen task completion policy: require independently verifiable HTTP(S) deliverables, reject canina://, git://stage, and post-tsk missing article placeholders
- Reject completion when QA verification evidence reports 404 or missing article errors
- Add unit test coverage for ApprovalsController, DepartmentTasksController and completion policy
2026-10-20 19:41:39 +00:00
devops 7b1f64d727 feat(admin): separate manager actions from operational authorization and eliminate synthetic 3D room 2026-10-20 19:30:47 +00:00
devops d53e38a48f test: gate market proposal evidence and dedup before approval 2026-10-20 19:13:48 +00:00
devops 740e738fca Merge develop into main: modernize ApprovalsPage with clean light theme and smart payload mapper
Deploy Canina / deploy (push) Successful in 38s
2026-10-20 16:01:17 +00:00
devops ee90284129 feat(admin): modernize ApprovalsPage UI with clean light theme, structured payload visualizer and CEO directives
Deploy Canina / deploy (push) Successful in 38s
2026-10-20 16:00:59 +00:00
devops de42b3126b Merge feature/task-status-history-and-ceo-priority into main
Deploy Canina / deploy (push) Successful in 39s
2026-10-20 13:37:01 +00:00
devops 71dccbc590 feat(admin): add status transition metrics and CEO_EXPEDITE priority to task manager
Deploy Canina / deploy (push) Successful in 37s
2026-10-20 13:36:59 +00:00
devops 4c6127786f Merge develop into main: complete department and status filters in task management
Deploy Canina / deploy (push) Successful in 39s
2026-10-20 12:25:11 +00:00
devops bf082c59fe feat(admin): complete all department and status filters in task management
Deploy Canina / deploy (push) Successful in 37s
2026-10-20 12:00:59 +00:00
devops ee35c10454 merge: fix GA4 gtag arguments and route tracking
Deploy Canina / deploy (push) Successful in 2m32s
2026-10-20 10:54:19 +00:00
devops 1651fd00a2 fix(analytics): pass native arguments to dataLayer and track route changes
Deploy Canina / deploy (push) Successful in 2m20s
2026-10-20 10:49:56 +00:00
devops d9e4447903 merge: suppress Prisma CLI update banner during migrations
Deploy Canina / deploy (push) Successful in 40s
2026-10-20 09:54:23 +00:00
devops f59dd6ebec fix(prisma): suppress CLI update banner during migrations and builds
Deploy Canina / deploy (push) Successful in 2m34s
2026-10-20 09:46:32 +00:00
devops 10413547c1 merge: publish blog attribution and freshness fixes
Deploy Canina / deploy (push) Successful in 2m37s
2026-10-20 09:08:50 +00:00
devops 2f178db2c6 fix(blog): keep attribution rows on one line
Deploy Canina / deploy (push) Successful in 2m20s
2026-10-20 09:01:32 +00:00
devops 28485d51f7 fix(blog): improve attribution layout and freshness
Deploy Canina / deploy (push) Successful in 4m4s
2026-10-20 08:41:40 +00:00
devops 24362b89d7 fix(blog): refine editorial team label
Deploy Canina / deploy (push) Successful in 2m40s
2026-10-20 07:59:08 +00:00
devops 159e4a4cbf fix(blog): separate Canina author and editorial team
Deploy Canina / deploy (push) Successful in 2m47s
2026-10-20 07:52:07 +00:00
devops 13a7919c91 merge: reconcile main before blog freshness release
Deploy Canina / deploy (push) Successful in 2m34s
2026-10-20 07:26:54 +00:00
devops d670690816 fix(blog): unify structured author identity
Deploy Canina / deploy (push) Successful in 5m16s
2026-10-20 07:15:20 +00:00
devops 62c58c7c89 fix(blog): harden creation and unify author fallback 2026-10-20 06:59:43 +00:00
devops 0b4d9a8463 fix(blog): harden freshness and authorship 2026-10-20 06:31:22 +00:00
devops 51ca8c7e34 feat(blog): add material freshness and authorship 2026-10-20 05:36:03 +00:00
devops 64047054b8 merge: integrate live HQ telemetry and child task execution pipeline
Deploy Canina / deploy (push) Successful in 38s
2026-10-19 17:49:00 +00:00
devops 3f5258a76c feat(admin-hq): bind 3D orchestration room to live telemetry and dynamic task state
Deploy Canina / deploy (push) Successful in 36s
2026-10-19 17:48:44 +00:00
devops 3b93308b71 merge: resilient orchestration JSON parsing
Deploy Canina / deploy (push) Successful in 39s
2026-10-19 14:13:03 +00:00
devops bf53f2e17c fix(orchestration): tolerate raw control characters in model JSON
Deploy Canina / deploy (push) Successful in 36s
2026-10-19 14:13:00 +00:00
devops c2eca11a3b merge: verified completion gates and cross-department orchestration
Deploy Canina / deploy (push) Successful in 51s
2026-10-19 14:07:01 +00:00
devops 4c3f8de1fb feat(orchestration): enforce verified completion and cross-department fan-out
Deploy Canina / deploy (push) Successful in 2m8s
2026-10-19 13:59:22 +00:00
devops b3e1869724 merge: add CompanyOrchestrationHQ into main
Deploy Canina / deploy (push) Successful in 37s
2026-10-19 13:03:56 +00:00
devops 624f58c723 feat(pages): add CompanyOrchestrationHQ interactive 3D component
Deploy Canina / deploy (push) Successful in 37s
2026-10-19 13:03:54 +00:00
devops aedc0f6979 merge: register /governance/hq route into main
Deploy Canina / deploy (push) Failing after 7s
2026-10-19 13:03:31 +00:00
devops 1e53ceeda6 feat(governance): register /governance/hq route
Deploy Canina / deploy (push) Failing after 8s
2026-10-19 13:03:29 +00:00
devops f08ed0c22c merge: integrate Tasks state fix and Sidebar 3D link into main
Deploy Canina / deploy (push) Successful in 39s
2026-10-19 12:51:18 +00:00
devops ee0f877d97 fix(tasks): define sortOrder state and add 3D HQ to Sidebar navigation
Deploy Canina / deploy (push) Successful in 37s
2026-10-19 12:50:12 +00:00
devops b3d4e08914 merge: integrate develop fixes (Dashboard null-safety, Tasks Tehran datetime, and sorting) into main
Deploy Canina / deploy (push) Successful in 2m47s
2026-10-19 12:43:06 +00:00
devops ec9dd83e77 fix: syntax escape in TasksManagementPage
Deploy Canina / deploy (push) Successful in 3m21s
2026-10-19 12:33:00 +00:00
devops 4930e2a870 feat(tasks): interactive date-sorting toggle and Tehran datetime column
Deploy Canina / deploy (push) Failing after 8s
2026-10-19 12:32:25 +00:00
devops 5e21cc76fc fix(admin): resolve Dashboard crash with null safety and add Tehran time/sorting to Tasks
Deploy Canina / deploy (push) Failing after 2m16s
2026-10-19 12:29:33 +00:00
devops 529110a693 feat(support-chat): delegate blog consultation CTA clicks to open support chat modal
Deploy Canina / deploy (push) Successful in 2m38s
2026-10-19 06:32:11 +00:00
devops 0b5f2a88cc fix(blog): highlight in-article links and trigger support chat from smart advisor button
Deploy Canina / deploy (push) Successful in 2m44s
2026-10-19 06:24:22 +00:00
devops ff6f04fe46 fix(cache): revalidate storefront after admin mutations
Deploy Canina / deploy (push) Successful in 2m35s
2026-10-18 19:31:46 +00:00
devops 2e9a0e30c1 chore: sync feature branch with latest origin/develop
Deploy Canina / deploy (push) Successful in 2m40s
2026-10-18 18:53:04 +00:00
devops ad0acaccc2 refactor(admin): extract ProductFaqTab component from monolithic Products.tsx [FE-020] 2026-10-18 18:34:52 +00:00
devops 30019a02d8 fix(deps): upgrade next to 16.4.2 eliminating critical vulnerability [FE-023] 2026-10-18 18:30:31 +00:00
devops 87999be3d2 fix(frontend): comprehensive SEO, A11y, media upload validation, and logging enhancements [FE-013 to FE-022] 2026-10-18 17:55:37 +00:00
devops 4ce9f6000c fix(ux): enforce safe responsive containment on mobile CartDrawer [FE-012] 2026-10-18 16:42:57 +00:00
devops 0529962391 fix(admin): resolve array response unwrapping in SupportChatAnalyticsPage [FE-011] 2026-10-18 16:37:45 +00:00
devops 14c45e4f6c fix(api): preserve error semantics in getProductBySlug distinguishing 404 from 5xx [FE-010] 2026-10-18 16:35:14 +00:00
devops 1c38b95fb0 fix(auth): align admin refresh token contract with backend cookie and bearer endpoints [FE-009] 2026-10-18 16:32:28 +00:00
devops dab66a2dce fix(checkout): guard against empty cart order submission and disable checkout CTA [FE-008] 2026-10-18 16:16:15 +00:00
devops 86eb0cfcae fix(monitoring): eliminate Math.random mock values from admin monitoring stats [FE-007] 2026-10-18 16:12:32 +00:00
devops d3aa10c769 fix(security): sanitize dynamic HTML rendering in Hero and ProductPage [FE-006] 2026-10-18 16:09:36 +00:00
devops 15524609fe fix(security): enforce withCredentials true on storefront api for httpOnly cookies [FE-005] 2026-10-18 16:04:34 +00:00
devops aacb91ac70 fix(security): sanitize and block payment tokens and secrets in public ui-texts endpoint [FE-004] 2026-10-18 15:47:12 +00:00
devops f91502026b feat(admin): configure vitest test runner and fix dashboard audit-logs array guards [FE-003] 2026-10-18 15:43:19 +00:00
devops 7f2f638f38 test(backend): fix unit tests for media magic validation, slow query logger, and support chat specs
Deploy Canina / deploy (push) Successful in 41s
2026-10-18 15:40:03 +00:00
devops 7879ead486 fix(frontend): harmonize selectors and assertions across failing application unit tests [FE-002] 2026-10-18 15:35:43 +00:00
devops dda1caf3e0 feat(backend & dba): implement inventory concurrency guard, redis distributed locks, magic byte file validation, slow query logger, and db check constraints 2026-10-18 15:29:37 +00:00
devops bb483d3e68 fix(frontend): resolve react-hooks declaration order and lint errors in SupportChat [FE-001] 2026-10-18 15:23:12 +00:00
devops 73bc79b4bb fix(backend): encapsulate TasksService in TasksModule and export OrdersService
Deploy Canina / deploy (push) Successful in 30s
2026-10-18 14:43:17 +00:00
devops 9520426a66 perf(backend & dba): resolve unindexed foreign keys, eliminate N+1 in product catalog, add background tasks for inventory release & payment reconciliation, and harden SQL queries
Deploy Canina / deploy (push) Failing after 36s
2026-10-18 14:35:41 +00:00
devops b077423ab2 fix: move BackToTop to right side, wire global prescription modal trigger in header & mobile drawer
Deploy Canina / deploy (push) Successful in 2m15s
2026-10-18 14:09:01 +00:00
devops 94867fbd5a fix(frontend): ensure use client is first line in ArchivePage
Deploy Canina / deploy (push) Successful in 2m16s
2026-10-18 13:54:31 +00:00
devops 6a37f2f4c7 fix: support chat elevated only on PDP, rx button opens modal instantly, and hide pet badge when not logged in
Deploy Canina / deploy (push) Failing after 21s
2026-10-18 13:50:54 +00:00
devops b54338f91f fix(backend): fix duplicate success in deleteSymptom
Deploy Canina / deploy (push) Successful in 2m33s
2026-10-18 13:28:39 +00:00
devops c7b95b4d2b feat: dock PDP buy bar above mobile nav, redesign B2B modal to mobile-card layout, and implement full symptoms CRUD in backend & admin panel
Deploy Canina / deploy (push) Failing after 1m23s
2026-10-18 13:26:01 +00:00
devops 8e4388c325 fix(backend): fix duplicate success property in renameSymptom response
Deploy Canina / deploy (push) Successful in 2m30s
2026-10-18 12:58:12 +00:00
devops 305995cbe2 fix(backend): correct syntax for prisma transaction in renameSymptom
Deploy Canina / deploy (push) Failing after 1m15s
2026-10-18 12:55:11 +00:00
devops 468170349d feat(ux-fix): resolve wiki fallback 404, responsive B2B modal, clean badges, aligned bullets, mobile bottom nav on PDP and admin Rx/symptoms management
Deploy Canina / deploy (push) Failing after 1m14s
2026-10-18 12:51:04 +00:00
devops 52446592e7 fix(header): clean up prescription button navigation onClick handler
Deploy Canina / deploy (push) Successful in 2m16s
2026-10-18 11:35:43 +00:00
devops 7bca0ef335 feat(prescriptions): launch online veterinary prescription assessment portal with regression tests (B2B-03)
Deploy Canina / deploy (push) Failing after 1m6s
2026-10-18 11:31:49 +00:00
devops 80717680a1 feat(b2b): connect B2B landing inquiry form to public inquiry endpoint with regression test (B2B-01)
Deploy Canina / deploy (push) Successful in 2m14s
2026-10-18 11:19:51 +00:00
320 changed files with 15805 additions and 3454 deletions

No files matched your search

+4
View File
@@ -12,3 +12,7 @@ uploads
**/uploads **/uploads
*.pdf *.pdf
graphify-out graphify-out
**/.revalidation.env*
**/.support*.env*
**/*runtime.env
**/release.override.json
+21 -4
View File
@@ -5,6 +5,7 @@ on:
branches: branches:
- main - main
- develop - develop
- release/blog-timestamp-limited-20261030
jobs: jobs:
deploy: deploy:
@@ -12,9 +13,23 @@ jobs:
steps: steps:
- name: Run deploy.sh from within the scripts folder - name: Run deploy.sh from within the scripts folder
env: env:
BRANCH: ${{ github.ref_name }} DEPLOY_REF: ${{ github.ref }}
SUPPORT_CHAT_KEY: ${{ secrets.SUPPORT_CHAT_KEY }} DEPLOY_SHA: ${{ github.sha }}
GITHUB_ACTIONS: 'true'
run: | run: |
set -eu
case "${DEPLOY_REF}" in
refs/heads/main) BRANCH=main; STAGE_SOURCE_REF= ;;
refs/heads/develop|refs/heads/release/blog-timestamp-limited-20261030)
BRANCH=develop; STAGE_SOURCE_REF="$DEPLOY_REF" ;;
*) printf 'Unsupported deployment ref\n' >&2; exit 2 ;;
esac
# Bind downloads and both release dispatchers to the exact event commit.
case "$DEPLOY_SHA" in
*[!0-9a-f]*|'') exit 2 ;;
esac
[ "${#DEPLOY_SHA}" -eq 40 ] || exit 2
export BRANCH STAGE_SOURCE_REF
# 1. رفع مشکل DNS و غیرفعال کردن پروکسی برای دامنه محلی # 1. رفع مشکل DNS و غیرفعال کردن پروکسی برای دامنه محلی
echo "87.248.133.138 git.parsaaghayi.ir" >> /etc/hosts echo "87.248.133.138 git.parsaaghayi.ir" >> /etc/hosts
export http_proxy="" export http_proxy=""
@@ -25,8 +40,10 @@ jobs:
# 2. دانلود و اجرای اسکریپت deploy.sh بر اساس برنچ جاری # 2. دانلود و اجرای اسکریپت deploy.sh بر اساس برنچ جاری
mkdir -p scripts mkdir -p scripts
wget --no-proxy -qO scripts/deploy.sh https://git.parsaaghayi.ir/parsa/canina/raw/branch/${BRANCH}/scripts/deploy.sh wget --no-proxy -qO scripts/deploy.sh https://git.parsaaghayi.ir/parsa/canina/raw/commit/${DEPLOY_SHA}/scripts/deploy.sh
wget --no-proxy -qO scripts/release-cache-stage.sh https://git.parsaaghayi.ir/parsa/canina/raw/commit/${DEPLOY_SHA}/scripts/release-cache-stage.sh
wget --no-proxy -qO scripts/release-cache-prod.sh https://git.parsaaghayi.ir/parsa/canina/raw/commit/${DEPLOY_SHA}/scripts/release-cache-prod.sh
chmod +x scripts/deploy.sh chmod +x scripts/deploy.sh
cd scripts cd scripts
./deploy.sh ${BRANCH} ./deploy.sh "${BRANCH}"
+4
View File
@@ -16,3 +16,7 @@ playwright-report/
playwright/.auth/ playwright/.auth/
blob-report/ blob-report/
# Python CI helpers must not dirty immutable release checkouts.
__pycache__/
*.pyc
+9 -9
View File
@@ -1,4 +1,4 @@
FROM node:20-alpine AS app-builder FROM node:22-alpine AS app-builder
USER root USER root
WORKDIR /app WORKDIR /app
ENV NEXT_TELEMETRY_DISABLED=1 ENV NEXT_TELEMETRY_DISABLED=1
@@ -7,18 +7,17 @@ ENV NEXT_PUBLIC_API_URL=https://api.canina.ir/api
# Optional: Use Nexus as npm registry # Optional: Use Nexus as npm registry
ARG NPM_REGISTRY= ARG NPM_REGISTRY=
RUN if [ -n "$NPM_REGISTRY" ]; then \ RUN if [ -n "$NPM_REGISTRY" ]; then \
npm config set registry "$NPM_REGISTRY" && \ npm config set registry "$NPM_REGISTRY"; \
npm config set strict-ssl false; \
fi fi
COPY frontend/application/package*.json ./ COPY frontend/application/package*.json ./
RUN npm ci --include=dev --prefer-offline --no-audit RUN npm ci --include=dev --prefer-offline --no-audit && test -x node_modules/.bin/next
COPY frontend/application ./ COPY frontend/application ./
ARG NEXT_PUBLIC_API_URL ARG NEXT_PUBLIC_API_URL
ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL
RUN npm run build RUN npm run build
FROM node:20-alpine AS admin-builder FROM node:22-alpine AS admin-builder
USER root USER root
WORKDIR /app WORKDIR /app
ENV VITE_API_URL=https://api.canina.ir/api ENV VITE_API_URL=https://api.canina.ir/api
@@ -26,18 +25,17 @@ ENV VITE_API_URL=https://api.canina.ir/api
# Optional: Use Nexus as npm registry (inherits build-arg) # Optional: Use Nexus as npm registry (inherits build-arg)
ARG NPM_REGISTRY= ARG NPM_REGISTRY=
RUN if [ -n "$NPM_REGISTRY" ]; then \ RUN if [ -n "$NPM_REGISTRY" ]; then \
npm config set registry "$NPM_REGISTRY" && \ npm config set registry "$NPM_REGISTRY"; \
npm config set strict-ssl false; \
fi fi
COPY frontend/admin-panel/package*.json ./ COPY frontend/admin-panel/package*.json ./
RUN npm ci --include=dev --prefer-offline --no-audit RUN npm ci --include=dev --prefer-offline --no-audit && test -x node_modules/.bin/vite
COPY frontend/admin-panel ./ COPY frontend/admin-panel ./
ARG VITE_API_URL ARG VITE_API_URL
ENV VITE_API_URL=$VITE_API_URL ENV VITE_API_URL=$VITE_API_URL
RUN npm run build RUN npm run build
FROM node:20-alpine FROM node:22-alpine
USER root USER root
RUN addgroup -S nginx 2>/dev/null || true && adduser -S nginx -G nginx 2>/dev/null || true RUN addgroup -S nginx 2>/dev/null || true && adduser -S nginx -G nginx 2>/dev/null || true
RUN mkdir -p /var/log/nginx /var/cache/nginx /run/nginx /etc/nginx/conf.d /etc/nginx/http.d RUN mkdir -p /var/log/nginx /var/cache/nginx /run/nginx /etc/nginx/conf.d /etc/nginx/http.d
@@ -49,6 +47,8 @@ RUN chown -R nginx:nginx /var/log/nginx /var/cache/nginx /run/nginx 2>/dev/null
WORKDIR /app WORKDIR /app
COPY --from=app-builder /app . COPY --from=app-builder /app .
COPY --from=admin-builder /app/dist ./admin_static COPY --from=admin-builder /app/dist ./admin_static
# Build-context umask must not make public assets unreadable by nginx workers.
RUN chmod -R a+rX /app/admin_static
COPY nginx.conf /etc/nginx/conf.d/default.conf COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY nginx.conf /etc/nginx/http.d/default.conf COPY nginx.conf /etc/nginx/http.d/default.conf
+5 -2
View File
@@ -2,6 +2,7 @@ FROM node:20-alpine AS builder
USER root USER root
RUN http_proxy=http://172.17.0.1:8888 https_proxy=http://172.17.0.1:8888 apk add --no-cache openssl || apk add --no-cache openssl || true RUN http_proxy=http://172.17.0.1:8888 https_proxy=http://172.17.0.1:8888 apk add --no-cache openssl || apk add --no-cache openssl || true
WORKDIR /app WORKDIR /app
ENV PRISMA_HIDE_UPDATE_MESSAGE=true
ENV PRISMA_SKIP_POSTINSTALL_GENERATE=true ENV PRISMA_SKIP_POSTINSTALL_GENERATE=true
ENV PRISMA_ENGINES_MIRROR=https://registry.npmmirror.com/-/binary/prisma ENV PRISMA_ENGINES_MIRROR=https://registry.npmmirror.com/-/binary/prisma
ENV DISABLE_OPENCOLLECTIVE=1 ENV DISABLE_OPENCOLLECTIVE=1
@@ -11,7 +12,6 @@ ENV npm_config_cache=/tmp/npm-cache
ARG NPM_REGISTRY= ARG NPM_REGISTRY=
RUN if [ -n "$NPM_REGISTRY" ]; then \ RUN if [ -n "$NPM_REGISTRY" ]; then \
npm config set registry "$NPM_REGISTRY" && \ npm config set registry "$NPM_REGISTRY" && \
npm config set strict-ssl false && \
echo "Using npm registry: $NPM_REGISTRY"; \ echo "Using npm registry: $NPM_REGISTRY"; \
fi fi
@@ -31,8 +31,11 @@ RUN http_proxy=http://172.17.0.1:8888 https_proxy=http://172.17.0.1:8888 \
FROM node:20-alpine FROM node:20-alpine
USER root USER root
RUN http_proxy=http://172.17.0.1:8888 https_proxy=http://172.17.0.1:8888 apk add --no-cache openssl || apk add --no-cache openssl || true RUN http_proxy=http://172.17.0.1:8888 https_proxy=http://172.17.0.1:8888 apk add --no-cache openssl || apk add --no-cache openssl || true
RUN mkdir -p /app/uploads && chown node:node /app/uploads RUN mkdir -p /app/uploads /app/private-stage-test && chmod 700 /app/private-stage-test && chown node:node /app/uploads /app/private-stage-test
WORKDIR /app WORKDIR /app
ARG STAGE_TEST_ARTIFACT_SHA=disabled
RUN printf "%s" "$STAGE_TEST_ARTIFACT_SHA" > /app/STAGE_TEST_ARTIFACT_SHA
ENV PRISMA_HIDE_UPDATE_MESSAGE=true
COPY --chown=node:node --from=builder /app/package*.json ./ COPY --chown=node:node --from=builder /app/package*.json ./
COPY --chown=node:node --from=builder /app/tsconfig.json ./tsconfig.json COPY --chown=node:node --from=builder /app/tsconfig.json ./tsconfig.json
COPY --chown=node:node --from=builder /app/eslint.config.mjs ./eslint.config.mjs COPY --chown=node:node --from=builder /app/eslint.config.mjs ./eslint.config.mjs
+28
View File
@@ -0,0 +1,28 @@
# Prisma migration history and Orchestration v4 rollout boundary
The checked-in history is **not a complete baseline of the current Prisma schema**. Do not assume that replaying it into an empty database can recreate the application, or that existing production tables imply corresponding migration records. Never use `prisma db push`, reset, or edit applied SQL to reconcile this.
## Actual tracked history
| Migration | What its SQL actually does |
| --- | --- |
| `20260526145407_init` | Creates users, addresses, wallets, products, product ingredients/symptoms, pets and medical conditions, reminders/completions, health logs, coupons, orders and order items, with their indexes/foreign keys. |
| `20260526160916_add_ui_texts_and_scientific_terms` | Creates `ui_texts` and `scientific_terms`. |
| `20261013210253_add_admin_modules` | Creates only `competitor_price_logs`, `b2b_leads`, `price_suggestions`, and `sms_campaigns`, with indexes and product foreign keys. It does **not** create legacy approvals, department tasks or audit logs. |
| `20261015000000_add_support_conversations` | Creates support conversations/messages and their foreign keys. |
| `20261020000000_add_blog_freshness_authorship` | Adds three columns to an assumed-existing `blogs` table. No earlier tracked migration creates `blogs`; fresh replay is therefore incomplete before v4. |
| `20261022000000_add_orchestration_v4_core` | Additively creates nine `orchestration_*` tables, indexes and internal foreign keys; it neither creates nor copies legacy governance tables. |
There is no checked-in CREATE TABLE migration for `approval_requests`, `department_tasks`, or `audit_logs`. Their models/controllers are not evidence that either live environment has these tables, nor proof of how any historical database acquired them. The broader missing legacy schema must be reconciled separately. This document does not certify live table existence or migration status.
## Required rollout safeguards (not authorization to deploy)
1. Back up each environment and verify restore capability. Capture its actual schema and `_prisma_migrations` history read-only; compare those independently against all tracked SQL, including prerequisites such as `blogs`.
2. Rehearse the exact planned chain on a disposable database restored from a reviewed baseline. A failed empty replay is a legacy-history gap, not evidence that the additive v4 SQL alone is faulty. Resolve the missing baseline through a separately reviewed migration/baseline plan, never by skipping errors.
3. `prisma migrate resolve --applied <name>` only records history; it creates no objects. Use it only for a specifically verified, fully matching existing migration and reviewed environment-specific plan. Never mark the whole chain applied or mark missing tables as applied.
4. After baseline reconciliation and rehearsal pass, apply reviewed pending migrations through CI/CD only using `prisma migrate deploy`. Verify all nine v4 tables, constraints, migration records and application health before considering the read surface ready.
5. Keep v4 mutations, chat and runtime capabilities denied. Retiring legacy mutation routes does not authorize a replacement execution path.
No deployment, live DDL, baseline resolution or migration SQL change is part of this hardening milestone. Schema rollout remains a separate gate, not full-system completion.
Rollback is application-first: stop use of the new module while retaining append-only records. Do not drop tables in automated rollback; removal requires separately reviewed archival migration.
@@ -0,0 +1,3 @@
ALTER TABLE blogs ADD COLUMN IF NOT EXISTS author_team VARCHAR(200);
ALTER TABLE blogs ADD COLUMN IF NOT EXISTS author_role VARCHAR(200);
ALTER TABLE blogs ADD COLUMN IF NOT EXISTS content_updated_at TIMESTAMPTZ;
@@ -0,0 +1,211 @@
-- CreateTable
CREATE TABLE "orchestration_tasks" (
"id" UUID NOT NULL,
"key" VARCHAR(120) NOT NULL,
"title" VARCHAR(255) NOT NULL,
"department" VARCHAR(50) NOT NULL,
"state" VARCHAR(40) NOT NULL DEFAULT 'DRAFT',
"operation_mode" VARCHAR(30) NOT NULL,
"model_tier" VARCHAR(2),
"budget_limit_cents" INTEGER NOT NULL,
"version" INTEGER NOT NULL DEFAULT 1,
"metadata" JSONB NOT NULL DEFAULT '{}',
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMPTZ NOT NULL,
CONSTRAINT "orchestration_tasks_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "orchestration_runs" (
"id" UUID NOT NULL,
"task_id" UUID NOT NULL,
"attempt" INTEGER NOT NULL DEFAULT 1,
"status" VARCHAR(30) NOT NULL DEFAULT 'PENDING',
"commit_sha" VARCHAR(64) NOT NULL,
"environment" VARCHAR(50) NOT NULL,
"retry_class" VARCHAR(30),
"idempotency_key" VARCHAR(150) NOT NULL,
"started_at" TIMESTAMPTZ,
"finished_at" TIMESTAMPTZ,
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "orchestration_runs_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "orchestration_artifacts" (
"id" UUID NOT NULL,
"run_id" UUID NOT NULL,
"kind" VARCHAR(50) NOT NULL,
"uri" TEXT NOT NULL,
"sha256" CHAR(64) NOT NULL,
"size_bytes" BIGINT,
"metadata" JSONB NOT NULL DEFAULT '{}',
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "orchestration_artifacts_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "orchestration_attestations" (
"id" UUID NOT NULL,
"run_id" UUID NOT NULL,
"kind" VARCHAR(50) NOT NULL,
"subject_hash" CHAR(64) NOT NULL,
"predicate" JSONB NOT NULL,
"signer" VARCHAR(150) NOT NULL,
"signature" TEXT,
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "orchestration_attestations_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "orchestration_dependencies" (
"id" UUID NOT NULL,
"task_id" UUID NOT NULL,
"depends_on_task_id" UUID NOT NULL,
"kind" VARCHAR(30) NOT NULL DEFAULT 'BLOCKS',
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "orchestration_dependencies_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "orchestration_approval_decisions" (
"id" UUID NOT NULL,
"task_id" UUID NOT NULL,
"gate" INTEGER NOT NULL,
"decision" VARCHAR(20) NOT NULL,
"actor_id" VARCHAR(100) NOT NULL,
"notes" TEXT,
"expires_at" TIMESTAMPTZ NOT NULL,
"idempotency_key" VARCHAR(150) NOT NULL,
"run_id" UUID,
"artifact_hash" CHAR(64),
"commit_sha" VARCHAR(64),
"environment" VARCHAR(50),
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "orchestration_approval_decisions_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "orchestration_events" (
"id" UUID NOT NULL,
"task_id" UUID,
"event_type" VARCHAR(60) NOT NULL,
"from_state" VARCHAR(40),
"to_state" VARCHAR(40),
"sequence" INTEGER NOT NULL,
"actor_id" VARCHAR(100) NOT NULL,
"idempotency_key" VARCHAR(150),
"payload" JSONB NOT NULL DEFAULT '{}',
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "orchestration_events_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "orchestration_budget_ledger" (
"id" UUID NOT NULL,
"task_id" UUID NOT NULL,
"amount_cents" INTEGER NOT NULL,
"kind" VARCHAR(40) NOT NULL,
"idempotency_key" VARCHAR(150) NOT NULL,
"actor_id" VARCHAR(100) NOT NULL,
"metadata" JSONB NOT NULL DEFAULT '{}',
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "orchestration_budget_ledger_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "orchestration_kill_switches" (
"scope" VARCHAR(80) NOT NULL,
"level" VARCHAR(30) NOT NULL,
"active" BOOLEAN NOT NULL DEFAULT true,
"reason" TEXT NOT NULL,
"actor_id" VARCHAR(100) NOT NULL,
"version" INTEGER NOT NULL DEFAULT 1,
"updated_at" TIMESTAMPTZ NOT NULL,
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "orchestration_kill_switches_pkey" PRIMARY KEY ("scope")
);
-- CreateIndex
CREATE UNIQUE INDEX "orchestration_tasks_key_key" ON "orchestration_tasks"("key");
-- CreateIndex
CREATE INDEX "orchestration_tasks_state_created_at_idx" ON "orchestration_tasks"("state", "created_at");
-- CreateIndex
CREATE INDEX "orchestration_tasks_department_state_idx" ON "orchestration_tasks"("department", "state");
-- CreateIndex
CREATE UNIQUE INDEX "orchestration_runs_idempotency_key_key" ON "orchestration_runs"("idempotency_key");
-- CreateIndex
CREATE INDEX "orchestration_runs_task_id_status_idx" ON "orchestration_runs"("task_id", "status");
-- CreateIndex
CREATE UNIQUE INDEX "orchestration_runs_task_id_attempt_key" ON "orchestration_runs"("task_id", "attempt");
-- CreateIndex
CREATE UNIQUE INDEX "orchestration_artifacts_run_id_sha256_key" ON "orchestration_artifacts"("run_id", "sha256");
-- CreateIndex
CREATE UNIQUE INDEX "orchestration_attestations_run_id_kind_subject_hash_signer_key" ON "orchestration_attestations"("run_id", "kind", "subject_hash", "signer");
-- CreateIndex
CREATE UNIQUE INDEX "orchestration_dependencies_task_id_depends_on_task_id_key" ON "orchestration_dependencies"("task_id", "depends_on_task_id");
-- CreateIndex
CREATE UNIQUE INDEX "orchestration_approval_decisions_idempotency_key_key" ON "orchestration_approval_decisions"("idempotency_key");
-- CreateIndex
CREATE INDEX "orchestration_approval_decisions_task_id_gate_created_at_idx" ON "orchestration_approval_decisions"("task_id", "gate", "created_at");
-- CreateIndex
CREATE UNIQUE INDEX "orchestration_events_idempotency_key_key" ON "orchestration_events"("idempotency_key");
-- CreateIndex
CREATE INDEX "orchestration_events_event_type_created_at_idx" ON "orchestration_events"("event_type", "created_at");
-- CreateIndex
CREATE UNIQUE INDEX "orchestration_events_task_id_sequence_key" ON "orchestration_events"("task_id", "sequence");
-- CreateIndex
CREATE UNIQUE INDEX "orchestration_budget_ledger_idempotency_key_key" ON "orchestration_budget_ledger"("idempotency_key");
-- CreateIndex
CREATE INDEX "orchestration_budget_ledger_task_id_created_at_idx" ON "orchestration_budget_ledger"("task_id", "created_at");
-- AddForeignKey
ALTER TABLE "orchestration_runs" ADD CONSTRAINT "orchestration_runs_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "orchestration_artifacts" ADD CONSTRAINT "orchestration_artifacts_run_id_fkey" FOREIGN KEY ("run_id") REFERENCES "orchestration_runs"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "orchestration_attestations" ADD CONSTRAINT "orchestration_attestations_run_id_fkey" FOREIGN KEY ("run_id") REFERENCES "orchestration_runs"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "orchestration_dependencies" ADD CONSTRAINT "orchestration_dependencies_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "orchestration_dependencies" ADD CONSTRAINT "orchestration_dependencies_depends_on_task_id_fkey" FOREIGN KEY ("depends_on_task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "orchestration_approval_decisions" ADD CONSTRAINT "orchestration_approval_decisions_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "orchestration_approval_decisions" ADD CONSTRAINT "orchestration_approval_decisions_run_id_fkey" FOREIGN KEY ("run_id") REFERENCES "orchestration_runs"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "orchestration_events" ADD CONSTRAINT "orchestration_events_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "orchestration_budget_ledger" ADD CONSTRAINT "orchestration_budget_ledger_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
@@ -0,0 +1,10 @@
-- Immutable evidence and accounting; corrections are new entries.
CREATE FUNCTION orchestration_append_only() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN RAISE EXCEPTION 'Orchestration append-only record cannot be changed'; END;
$$;
CREATE TRIGGER orchestration_budget_immutable BEFORE UPDATE OR DELETE ON orchestration_budget_ledger FOR EACH ROW EXECUTE FUNCTION orchestration_append_only();
CREATE TRIGGER orchestration_events_immutable BEFORE UPDATE OR DELETE ON orchestration_events FOR EACH ROW EXECUTE FUNCTION orchestration_append_only();
CREATE TRIGGER orchestration_approvals_immutable BEFORE UPDATE OR DELETE ON orchestration_approval_decisions FOR EACH ROW EXECUTE FUNCTION orchestration_append_only();
CREATE TRIGGER orchestration_artifacts_immutable BEFORE UPDATE OR DELETE ON orchestration_artifacts FOR EACH ROW EXECUTE FUNCTION orchestration_append_only();
CREATE TRIGGER orchestration_attestations_immutable BEFORE UPDATE OR DELETE ON orchestration_attestations FOR EACH ROW EXECUTE FUNCTION orchestration_append_only();
ALTER TABLE orchestration_tasks ADD CONSTRAINT orchestration_budget_nonnegative CHECK (budget_limit_cents >= 0);
@@ -0,0 +1,10 @@
CREATE TABLE prepare_workflow_outbox (
id uuid PRIMARY KEY, task_id uuid NOT NULL UNIQUE REFERENCES orchestration_tasks(id) ON DELETE RESTRICT,
status varchar(20) NOT NULL DEFAULT 'PENDING' CHECK (status IN ('PENDING','DONE')),
attempts integer NOT NULL DEFAULT 0 CHECK (attempts BETWEEN 0 AND 3),
lease_owner varchar(100), lease_token uuid, lease_until timestamptz, heartbeat_at timestamptz,
run_id uuid REFERENCES orchestration_runs(id) ON DELETE RESTRICT,
reservation_id uuid REFERENCES orchestration_budget_ledger(id) ON DELETE RESTRICT,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX prepare_workflow_outbox_status_lease_until_idx ON prepare_workflow_outbox(status,lease_until);
@@ -0,0 +1,3 @@
-- Scheduling is distinct from immutable approval validity. Existing queues run immediately.
ALTER TABLE "prepare_workflow_outbox" ADD COLUMN "not_before" TIMESTAMPTZ;
CREATE INDEX "prepare_workflow_outbox_due_idx" ON "prepare_workflow_outbox" ("status", "not_before", "created_at");
@@ -0,0 +1 @@
ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "auth_expires_at" TIMESTAMPTZ, ADD COLUMN IF NOT EXISTS "stage_test_session" VARCHAR(64), ADD COLUMN IF NOT EXISTS "stage_test_generation" UUID;
@@ -0,0 +1,14 @@
-- Drop legacy governance and orchestration tables
DROP TABLE IF EXISTS "prepare_workflow_outbox" CASCADE;
DROP TABLE IF EXISTS "orchestration_kill_switches" CASCADE;
DROP TABLE IF EXISTS "orchestration_budget_ledger" CASCADE;
DROP TABLE IF EXISTS "orchestration_events" CASCADE;
DROP TABLE IF EXISTS "orchestration_approval_decisions" CASCADE;
DROP TABLE IF EXISTS "orchestration_dependencies" CASCADE;
DROP TABLE IF EXISTS "orchestration_attestations" CASCADE;
DROP TABLE IF EXISTS "orchestration_artifacts" CASCADE;
DROP TABLE IF EXISTS "orchestration_runs" CASCADE;
DROP TABLE IF EXISTS "orchestration_tasks" CASCADE;
DROP TABLE IF EXISTS "department_tasks" CASCADE;
DROP TABLE IF EXISTS "audit_logs" CASCADE;
DROP TABLE IF EXISTS "approval_requests" CASCADE;
+6 -74
View File
@@ -16,6 +16,9 @@ model User {
mobile String @unique @db.VarChar(15) mobile String @unique @db.VarChar(15)
password String? @db.VarChar(255) password String? @db.VarChar(255)
role String @default("User_PetOwner") @db.VarChar(30) role String @default("User_PetOwner") @db.VarChar(30)
authExpiresAt DateTime? @map("auth_expires_at") @db.Timestamptz()
stageTestGeneration String? @map("stage_test_generation") @db.Uuid
stageTestSession String? @map("stage_test_session") @db.VarChar(64)
walletBalance Decimal @default(0.00) @map("wallet_balance") @db.Decimal(15, 2) walletBalance Decimal @default(0.00) @map("wallet_balance") @db.Decimal(15, 2)
charityDonationTotal Decimal @default(0.00) @map("charity_donation_total") @db.Decimal(15, 2) charityDonationTotal Decimal @default(0.00) @map("charity_donation_total") @db.Decimal(15, 2)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
@@ -179,6 +182,8 @@ model Blog {
content String @db.Text content String @db.Text
excerpt String? @db.Text excerpt String? @db.Text
authorId String? @map("author_id") @db.Uuid authorId String? @map("author_id") @db.Uuid
authorTeam String? @map("author_team") @db.VarChar(200)
authorRole String? @map("author_role") @db.VarChar(200)
categoryId String? @map("category_id") @db.Uuid categoryId String? @map("category_id") @db.Uuid
imageUrl String? @map("image_url") @db.Text imageUrl String? @map("image_url") @db.Text
imageAlt String? @map("image_alt") @db.VarChar(255) imageAlt String? @map("image_alt") @db.VarChar(255)
@@ -198,6 +203,7 @@ model Blog {
isPublished Boolean @default(true) @map("is_published") isPublished Boolean @default(true) @map("is_published")
publishedAt DateTime? @map("published_at") @db.Timestamptz() publishedAt DateTime? @map("published_at") @db.Timestamptz()
scheduledAt DateTime? @map("scheduled_at") @db.Timestamptz() scheduledAt DateTime? @map("scheduled_at") @db.Timestamptz()
contentUpdatedAt DateTime? @map("content_updated_at") @db.Timestamptz()
readingTime Int @default(3) @map("reading_time") readingTime Int @default(3) @map("reading_time")
featured Boolean @default(false) featured Boolean @default(false)
allowComments Boolean @default(true) @map("allow_comments") allowComments Boolean @default(true) @map("allow_comments")
@@ -1014,77 +1020,3 @@ model SmsCampaign {
@@map("sms_campaigns") @@map("sms_campaigns")
} }
// ------------------------------------------------------------------------------
// 5. ApprovalRequest (CEO Governance & Decision Gate)
// ------------------------------------------------------------------------------
model ApprovalRequest {
id String @id @default(uuid()) @db.Uuid
department String @db.VarChar(50)
category String @db.VarChar(50)
title String @db.VarChar(255)
payload Json @db.JsonB
testContext Json? @map("test_context") @db.JsonB
status String @default("PENDING") @db.VarChar(30)
ceoNotes String? @map("ceo_notes") @db.Text
executedAt DateTime? @map("executed_at") @db.Timestamptz()
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
@@index([department])
@@index([category])
@@index([status])
@@index([createdAt])
@@map("approval_requests")
}
// ------------------------------------------------------------------------------
// 6. AuditLog (System & Database Changes History)
// ------------------------------------------------------------------------------
model AuditLog {
id String @id @default(uuid()) @db.Uuid
entity String @db.VarChar(50) // e.g. product, blog, order, approval, settings
entityId String? @map("entity_id") @db.VarChar(100)
action String @db.VarChar(50) // CREATE, UPDATE, DELETE, EXECUTE, APPROVE, REJECT
department String? @db.VarChar(50) // devops, seo, content, vet, commerce, pmo
actor String @default("SYSTEM") @db.VarChar(100)
summary String @db.VarChar(255)
oldValues Json? @map("old_values") @db.JsonB
newValues Json? @map("new_values") @db.JsonB
metadata Json? @db.JsonB
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
@@index([entity])
@@index([action])
@@index([department])
@@index([createdAt])
@@map("audit_logs")
}
// ------------------------------------------------------------------------------
// 7. DepartmentTask (Autonomous Corporate Task & Kanban Manager)
// ------------------------------------------------------------------------------
model DepartmentTask {
id String @id @default(uuid()) @db.Uuid
code String @unique @db.VarChar(50)
department String @db.VarChar(50) // devops, seo, content, vet, commerce, pmo
title String @db.VarChar(255)
description String? @db.Text
status String @default("BACKLOG") @db.VarChar(30) // BACKLOG, IN_PROGRESS, IN_REVIEW, APPROVED, DEPLOYING, DONE
priority String @default("MEDIUM") @db.VarChar(20) // LOW, MEDIUM, HIGH, CRITICAL
assignee String? @db.VarChar(100)
acceptanceCriteria Json? @map("acceptance_criteria") @db.JsonB
executionLogs Json? @map("execution_logs") @db.JsonB
deliverableUrl String? @map("deliverable_url") @db.VarChar(255)
approvalId String? @map("approval_id") @db.Uuid
startedAt DateTime? @map("started_at") @db.Timestamptz()
completedAt DateTime? @map("completed_at") @db.Timestamptz()
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
@@index([department])
@@index([status])
@@index([priority])
@@index([createdAt])
@@map("department_tasks")
}
@@ -0,0 +1,73 @@
import { ForbiddenException } from "@nestjs/common";
import { AdminService } from "./admin.service";
import { AdminController } from "./admin.controller";
// All identities and credentials here are disposable test fixtures.
describe("admin user privilege boundary", () => {
let service: any;
let prisma: any;
const owner = { id: "owner-fixture", role: "SUPER_ADMIN" };
const admin = { id: "admin-fixture", role: "ADMIN" };
beforeEach(() => {
prisma = {
user: {
findUnique: jest.fn().mockResolvedValue({ id: "target-fixture", role: "SUPER_ADMIN" }),
update: jest.fn().mockImplementation(async ({ data }) => ({ role: "SUPER_ADMIN", ...data })),
create: jest.fn(),
},
walletTransaction: { create: jest.fn() },
$transaction: jest.fn(),
};
service = new AdminService(prisma, {} as never, {} as never);
});
it("allows an authenticated superadmin password-only edit without changing the exact role", async () => {
const result = await service.updateUser("target-fixture", { password: "Fixture-only-123" }, owner);
expect(result.role).toBe("SUPER_ADMIN");
expect(prisma.user.update.mock.calls[0][0].data).not.toHaveProperty("role");
});
it.each(["ADMIN", "Admin", "User_PetOwner"])("denies %s assigning superadmin on create", async role => {
prisma.user.findUnique.mockResolvedValue(null);
await expect(service.createUser({ firstName: "Test", lastName: "Fixture", mobile: "09120000001", role: "SUPER_ADMIN" }, { id: "actor", role })).rejects.toBeInstanceOf(ForbiddenException);
expect(prisma.user.create).not.toHaveBeenCalled();
});
it.each(["SUPER_ADMIN", "super-admin", "AdminSuper"])("denies ordinary admin escalation to %s", async role => {
prisma.user.findUnique.mockResolvedValue({ id: admin.id, role: "Admin" });
await expect(service.updateUser(admin.id, { role }, admin)).rejects.toBeInstanceOf(ForbiddenException);
expect(prisma.user.update).not.toHaveBeenCalled();
});
it.each([{ password: "Fixture-only-123" }, { email: "fixture@example.test" }, { mobile: "09120000001" }, { role: "Admin" }, { walletBalance: 1 }, { firstName: "Changed" }])("denies ordinary admin editing superadmin", async dto => {
await expect(service.updateUser("target-fixture", dto, admin)).rejects.toBeInstanceOf(ForbiddenException);
expect(prisma.user.update).not.toHaveBeenCalled();
});
it("denies alternate role endpoint revocation", async () => {
await expect(service.updateUserRole("target-fixture", "Admin", admin)).rejects.toBeInstanceOf(ForbiddenException);
expect(prisma.user.update).not.toHaveBeenCalled();
});
it("denies deleting superadmin", async () => {
await expect(service.deleteUser("target-fixture", admin)).rejects.toBeInstanceOf(ForbiddenException);
expect(prisma.$transaction).not.toHaveBeenCalled();
});
it("denies changing superadmin wallet", async () => {
await expect(service.adjustUserWallet("target-fixture", 1, "deposit", "fixture", admin)).rejects.toBeInstanceOf(ForbiddenException);
expect(prisma.walletTransaction.create).not.toHaveBeenCalled();
});
it("accepts ADMIN alias for ordinary CRUD and authorized promotion/revocation", async () => {
prisma.user.findUnique.mockResolvedValue({ id: "target-fixture", role: "User_PetOwner" });
await service.updateUser("target-fixture", { role: "ADMIN" }, admin);
await service.updateUser("target-fixture", { role: "SUPER_ADMIN" }, owner);
prisma.user.findUnique.mockResolvedValue({ id: "target-fixture", role: "SUPER_ADMIN" });
await service.updateUserRole("target-fixture", "Admin", owner);
expect(prisma.user.update).toHaveBeenCalledTimes(3);
});
it("fails closed without authenticated actor or with API key superadmin", async () => {
await expect(service.updateUser("target-fixture", { role: "Admin" })).rejects.toBeInstanceOf(ForbiddenException);
await expect(service.updateUser("target-fixture", { role: "Admin" }, { ...owner, isApiKey: true })).rejects.toBeInstanceOf(ForbiddenException);
});
it("controller forwards authenticated request identity, not DTO identity", async () => {
const svc = { updateUser: jest.fn().mockResolvedValue({}) };
const controller: any = new AdminController(svc as never, {} as never);
const dto = { firstName: "Test" };
await controller.updateUser("target-fixture", dto, { user: admin });
expect(svc.updateUser).toHaveBeenCalledWith("target-fixture", dto, admin);
});
});
@@ -0,0 +1,72 @@
import { Test } from "@nestjs/testing";
import { ExecutionContext } from "@nestjs/common";
import { firstValueFrom, of } from "rxjs";
import { AdminService } from "./admin.service";
import { AdminController } from "./admin.controller";
import { PrismaService } from "../prisma/prisma.service";
import { RedisService } from "../redis/redis.service";
import { RevalidationService } from "../common/revalidation/revalidation.service";
import { DecimalInterceptor } from "../common/interceptors/decimal.interceptor";
import { Prisma } from "@prisma/client";
describe("admin users list contract", () => {
const prisma = { user: { findMany: jest.fn(), count: jest.fn() } };
let service: AdminService;
beforeEach(async () => {
jest.clearAllMocks();
const module = await Test.createTestingModule({
providers: [
AdminService,
{ provide: PrismaService, useValue: prisma },
{ provide: RedisService, useValue: {} },
{ provide: RevalidationService, useValue: {} },
],
}).compile();
service = module.get(AdminService);
});
it("returns only allowlisted list fields with aggregates through the controller and decimal interceptor", async () => {
// Deliberately return extra fields even if the query selects safely.
prisma.user.findMany.mockResolvedValue([{
id: "fixture-user", firstName: "Fixture", lastName: "User",
mobile: "fixture-mobile", email: null, role: "ADMIN",
walletBalance: new Prisma.Decimal(0), charityDonationTotal: new Prisma.Decimal(12),
createdAt: new Date("2026-01-01T00:00:00Z"),
password: "test-only-password-hash", passwordHash: "test-only-hash",
refreshToken: "test-only-token", futureSecret: "must-not-leak",
walletTransactions: [{ transactionReference: "private-reference" }],
addresses: [], orders: [{ totalAmount: new Prisma.Decimal(100) }, { totalAmount: 25 }],
_count: { orders: 3, reviews: 2, blogComments: 1, pets: 4 },
}]);
prisma.user.count.mockResolvedValue(11);
const controller = new AdminController(service, {} as never);
const result = await controller.getUsers({ page: 2, limit: 10 });
const body = await firstValueFrom(new DecimalInterceptor().intercept({} as ExecutionContext, { handle: () => of(result) }));
expect(body).toEqual({
data: [{
id: "fixture-user", firstName: "Fixture", lastName: "User", mobile: "fixture-mobile",
email: null, role: "ADMIN", walletBalance: "0", charityDonationTotal: "12",
createdAt: new Date("2026-01-01T00:00:00Z"), addresses: [],
totalSpent: 125, ordersCount: 3, reviewsCount: 3, petsCount: 4,
}],
meta: { total: 11, page: 2, limit: 10, lastPage: 2 },
});
const query = prisma.user.findMany.mock.calls[0][0];
expect(query.select).toBeDefined();
expect(query.select.password).toBeUndefined();
expect(query.include).toBeUndefined();
expect(query.skip).toBe(10);
});
it("preserves the empty paginated list contract and filters", async () => {
prisma.user.findMany.mockResolvedValue([]);
prisma.user.count.mockResolvedValue(0);
expect(await service.getUsers({ search: "fixture", role: "ADMIN" })).toEqual({
data: [], meta: { total: 0, page: 1, limit: 10, lastPage: 1 },
});
expect(prisma.user.findMany).toHaveBeenCalledWith(expect.objectContaining({
where: expect.objectContaining({ role: "ADMIN", OR: expect.any(Array) }),
}));
});
});
+45 -11
View File
@@ -7,6 +7,7 @@ import {
Body, Body,
Param, Param,
Query, Query,
Req,
UseGuards, UseGuards,
BadRequestException, BadRequestException,
} from "@nestjs/common"; } from "@nestjs/common";
@@ -27,6 +28,7 @@ import {
} from "@nestjs/swagger"; } from "@nestjs/swagger";
import { CreateUserDto, UpdateUserDto } from "./dto/user.dto"; import { CreateUserDto, UpdateUserDto } from "./dto/user.dto";
import type { UserAdminActor } from "./user-role-policy";
import { SettingsService } from "../settings/settings.service"; import { SettingsService } from "../settings/settings.service";
import { RolesGuard } from "../common/guards/roles.guard"; import { RolesGuard } from "../common/guards/roles.guard";
@@ -57,13 +59,13 @@ export class AdminController {
@ApiQuery({ name: "search", required: false, description: "جستجو" }) @ApiQuery({ name: "search", required: false, description: "جستجو" })
async getUsers(@Query() query: AdminQueryDto) { async getUsers(@Query() query: AdminQueryDto) {
const result = await this.adminService.getUsers(query); const result = await this.adminService.getUsers(query);
return { success: true, ...result }; return result;
} }
@Post("users") @Post("users")
@ApiOperation({ summary: "ایجاد کاربر جدید توسط ادمین" }) @ApiOperation({ summary: "ایجاد کاربر جدید توسط ادمین" })
async createUser(@Body() dto: CreateUserDto) { async createUser(@Body() dto: CreateUserDto, @Req() req?: { user?: UserAdminActor }) {
const user = await this.adminService.createUser(dto); const user = await this.adminService.createUser(dto, req?.user);
return { return {
success: true, success: true,
message: "کاربر جدید با موفقیت ایجاد شد", message: "کاربر جدید با موفقیت ایجاد شد",
@@ -80,8 +82,8 @@ export class AdminController {
@Put("users/:id") @Put("users/:id")
@ApiOperation({ summary: "ویرایش مشخصات کامل کاربر" }) @ApiOperation({ summary: "ویرایش مشخصات کامل کاربر" })
async updateUser(@Param("id") id: string, @Body() dto: UpdateUserDto) { async updateUser(@Param("id") id: string, @Body() dto: UpdateUserDto, @Req() req?: { user?: UserAdminActor }) {
const user = await this.adminService.updateUser(id, dto); const user = await this.adminService.updateUser(id, dto, req?.user);
return { return {
success: true, success: true,
message: "اطلاعات کاربر با موفقیت ویرایش شد", message: "اطلاعات کاربر با موفقیت ویرایش شد",
@@ -91,8 +93,8 @@ export class AdminController {
@Delete("users/:id") @Delete("users/:id")
@ApiOperation({ summary: "حذف کاربر و داده‌های مرتبط" }) @ApiOperation({ summary: "حذف کاربر و داده‌های مرتبط" })
async deleteUser(@Param("id") id: string) { async deleteUser(@Param("id") id: string, @Req() req?: { user?: UserAdminActor }) {
await this.adminService.deleteUser(id); await this.adminService.deleteUser(id, req?.user);
return { return {
success: true, success: true,
message: "کاربر با موفقیت از سیستم حذف شد", message: "کاربر با موفقیت از سیستم حذف شد",
@@ -101,8 +103,8 @@ export class AdminController {
@Put("users/:id/role") @Put("users/:id/role")
@ApiOperation({ summary: "تغییر نقش کاربر" }) @ApiOperation({ summary: "تغییر نقش کاربر" })
async updateUserRole(@Param("id") id: string, @Body("role") role: string) { async updateUserRole(@Param("id") id: string, @Body("role") role: string, @Req() req?: { user?: UserAdminActor }) {
const user = await this.adminService.updateUserRole(id, role); const user = await this.adminService.updateUserRole(id, role, req?.user);
return { success: true, data: user }; return { success: true, data: user };
} }
@@ -113,6 +115,7 @@ export class AdminController {
@Body("amount") amount: number, @Body("amount") amount: number,
@Body("type") type: "deposit" | "withdrawal" | "refund", @Body("type") type: "deposit" | "withdrawal" | "refund",
@Body("description") description?: string, @Body("description") description?: string,
@Req() req?: { user?: UserAdminActor },
) { ) {
const numAmount = Number(amount); const numAmount = Number(amount);
if (!numAmount || isNaN(numAmount) || numAmount <= 0) { if (!numAmount || isNaN(numAmount) || numAmount <= 0) {
@@ -130,6 +133,7 @@ export class AdminController {
numAmount, numAmount,
type, type,
description, description,
req?.user,
); );
return { return {
success: true, success: true,
@@ -145,7 +149,7 @@ export class AdminController {
@ApiQuery({ name: "search", required: false, description: "جستجو" }) @ApiQuery({ name: "search", required: false, description: "جستجو" })
async getProducts(@Query() query: AdminQueryDto) { async getProducts(@Query() query: AdminQueryDto) {
const result = await this.adminService.getProducts(query); const result = await this.adminService.getProducts(query);
return { success: true, ...result }; return result;
} }
@Post("products") @Post("products")
@@ -206,7 +210,7 @@ export class AdminController {
@ApiQuery({ name: "status", required: false, description: "فیلتر وضعیت" }) @ApiQuery({ name: "status", required: false, description: "فیلتر وضعیت" })
async getOrders(@Query() query: AdminQueryDto) { async getOrders(@Query() query: AdminQueryDto) {
const result = await this.adminService.getOrders(query); const result = await this.adminService.getOrders(query);
return { success: true, ...result }; return result;
} }
@Get("orders/:id") @Get("orders/:id")
@@ -354,4 +358,34 @@ export class AdminController {
await this.settingsService.updateBulkUiTexts(body); await this.settingsService.updateBulkUiTexts(body);
return { success: true, data: body }; return { success: true, data: body };
} }
@Get("symptoms")
@ApiOperation({ summary: "لیست کامل علائم درمانی با صفحه‌بندی، جستجو و متادیتا" })
async getSymptoms(@Query() query: { page?: number; limit?: number; search?: string }) {
const res = await this.adminService.getSymptoms(query);
return res;
}
@Post("symptoms")
@ApiOperation({ summary: "افزودن علامت درمانی جدید" })
async createSymptom(@Body() body: { name: string; slug?: string; description?: string; metaTitle?: string; metaDescription?: string; keywords?: string }) {
const res = await this.adminService.createSymptom(body);
return { success: true, data: res };
}
@Put("symptoms/:id")
@ApiOperation({ summary: "ویرایش کامل علامت درمانی و متادیتاهای سئو" })
async updateSymptom(@Param("id") id: string, @Body() body: any) {
const res = await this.adminService.updateSymptom(id, body);
return { success: true, data: res };
}
@Delete("symptoms/:id")
@ApiOperation({ summary: "حذف علامت درمانی" })
async deleteSymptom(@Param("id") id: string) {
const res = await this.adminService.deleteSymptom(id);
return res;
}
} }
-6
View File
@@ -21,9 +21,6 @@ import { CompetitorPricingController } from "./competitor-pricing.controller";
import { B2BLeadsController } from "./b2b-leads.controller"; import { B2BLeadsController } from "./b2b-leads.controller";
import { PricingSuggestionsController } from "./pricing-suggestions.controller"; import { PricingSuggestionsController } from "./pricing-suggestions.controller";
import { SmsCampaignsController } from "./sms-campaigns.controller"; import { SmsCampaignsController } from "./sms-campaigns.controller";
import { ApprovalsController } from "./approvals.controller";
import { AuditLogsController } from "./audit-logs.controller";
import { DepartmentTasksController } from "./department-tasks.controller";
import { PrismaModule } from "../prisma/prisma.module"; import { PrismaModule } from "../prisma/prisma.module";
import { RedisModule } from "../redis/redis.module"; import { RedisModule } from "../redis/redis.module";
import { SettingsModule } from "../settings/settings.module"; import { SettingsModule } from "../settings/settings.module";
@@ -46,9 +43,6 @@ import { SupportChatAnalyticsService } from "./support-chat-analytics.service";
B2BLeadsController, B2BLeadsController,
PricingSuggestionsController, PricingSuggestionsController,
SmsCampaignsController, SmsCampaignsController,
ApprovalsController,
AuditLogsController,
DepartmentTasksController,
SupportChatAnalyticsController, SupportChatAnalyticsController,
], ],
providers: [ providers: [
+235 -27
View File
@@ -61,15 +61,10 @@ export class CouponInput {
targets?: CouponTargetInput[]; targets?: CouponTargetInput[];
} }
const ALLOWED_USER_ROLES = [ import { ALLOWED_USER_ROLES, assertUserMutationAllowed } from "./user-role-policy";
"User_PetOwner", import type { UserAdminActor } from "./user-role-policy";
"User_Vet", import { randomUUID } from "crypto";
"User_Clinic", import { authorizeStageSession, STAGE_TEST_ID, STAGE_TEST_EMAIL, STAGE_TEST_MOBILE } from "../auth/stage-test-principal";
"User_PetShop",
"Customer",
"Admin",
"SUPER_ADMIN",
];
@Injectable() @Injectable()
export class AdminService { export class AdminService {
@@ -168,12 +163,17 @@ export class AdminService {
skip, skip,
take: limit, take: limit,
orderBy: { [sortField]: sortDirection }, orderBy: { [sortField]: sortDirection },
include: { select: {
id: true,
firstName: true,
lastName: true,
mobile: true,
email: true,
role: true,
walletBalance: true,
charityDonationTotal: true,
createdAt: true,
addresses: true, addresses: true,
walletTransactions: {
orderBy: { createdAt: "desc" },
take: 20,
},
orders: { orders: {
where: { status: { not: "CANCELLED" } }, where: { status: { not: "CANCELLED" } },
select: { totalAmount: true }, select: { totalAmount: true },
@@ -197,9 +197,19 @@ export class AdminService {
(acc, curr) => acc + (Number(curr.totalAmount) || 0), (acc, curr) => acc + (Number(curr.totalAmount) || 0),
0, 0,
) || 0; ) || 0;
const { orders: _orders, ...rest } = u; // Explicit response allowlist: never expose authentication fields or
// new model columns implicitly through this administrative list.
return { return {
...rest, id: u.id,
firstName: u.firstName,
lastName: u.lastName,
mobile: u.mobile,
email: u.email,
role: u.role,
walletBalance: u.walletBalance,
charityDonationTotal: u.charityDonationTotal,
createdAt: u.createdAt,
addresses: u.addresses,
totalSpent, totalSpent,
ordersCount: u._count?.orders || 0, ordersCount: u._count?.orders || 0,
reviewsCount: (u._count?.reviews || 0) + (u._count?.blogComments || 0), reviewsCount: (u._count?.reviews || 0) + (u._count?.blogComments || 0),
@@ -227,7 +237,12 @@ export class AdminService {
return user; return user;
} }
async createUser(dto: CreateUserDto) { async createUser(dto: CreateUserDto, actor?: UserAdminActor) {
assertUserMutationAllowed(actor, undefined, dto.role);
return this.persistUser(dto);
}
private async persistUser(dto: CreateUserDto, stage?: { session: string; expiresAt: Date; generation?: string }) {
const mobile = normalizeMobile(dto.mobile); const mobile = normalizeMobile(dto.mobile);
const existingMobile = await this.prisma.user.findUnique({ const existingMobile = await this.prisma.user.findUnique({
where: { mobile }, where: { mobile },
@@ -260,6 +275,7 @@ export class AdminService {
return this.prisma.user.create({ return this.prisma.user.create({
data: { data: {
...(stage ? { id: STAGE_TEST_ID, stageTestGeneration:stage.generation || randomUUID(), stageTestSession: stage.session, authExpiresAt: stage.expiresAt } : {}),
firstName: dto.firstName.trim(), firstName: dto.firstName.trim(),
lastName: dto.lastName.trim(), lastName: dto.lastName.trim(),
mobile, mobile,
@@ -274,7 +290,30 @@ export class AdminService {
}); });
} }
async updateUser(id: string, dto: UpdateUserDto) { // Explicit CI seed authority, NOT a fabricated SUPER_ADMIN actor. Not controller-exposed.
async provisionStageTestPrincipal(env: NodeJS.ProcessEnv, sha: string, password: string) {
const grant = authorizeStageSession(env, sha);
const existing = await this.prisma.user.findFirst({where:{OR:[{id:STAGE_TEST_ID},{email:STAGE_TEST_EMAIL},{mobile:STAGE_TEST_MOBILE}]}});
if (existing) {
if (existing.id !== STAGE_TEST_ID || existing.email !== STAGE_TEST_EMAIL || existing.mobile !== STAGE_TEST_MOBILE || existing.stageTestSession !== grant.session || (env.STAGE_TEST_GENERATION && existing.stageTestGeneration !== env.STAGE_TEST_GENERATION) || existing.role !== 'SUPER_ADMIN' || !existing.authExpiresAt || existing.authExpiresAt.getTime() <= Date.now() || !await bcrypt.compare(password, existing.password || '')) throw new Error('Refusing existing or unowned principal');
return existing; // Never renew TTL on retry.
}
if (password.length < 32) throw new Error('Server generated secret required');
return this.persistUser({firstName:'Stage',lastName:'CI independent reviewer',email:STAGE_TEST_EMAIL,mobile:STAGE_TEST_MOBILE,role:'SUPER_ADMIN',password}, {session:grant.session,expiresAt:new Date(Date.now()+grant.ttl*1000),generation:env.STAGE_TEST_GENERATION});
}
async cleanupStageTestPrincipal(env: NodeJS.ProcessEnv, sha: string, onRevoked: () => void = () => undefined) {
const grant = authorizeStageSession(env, sha);
const existing = await this.prisma.user.findUnique({where:{id:STAGE_TEST_ID}});
if (!existing) { onRevoked(); return; }
if (existing.email !== STAGE_TEST_EMAIL || existing.mobile !== STAGE_TEST_MOBILE || existing.stageTestSession !== grant.session || !existing.authExpiresAt || (env.STAGE_TEST_GENERATION && existing.stageTestGeneration !== env.STAGE_TEST_GENERATION)) throw new Error('Refusing unowned principal cleanup');
// Revoke before relational cleanup; failed cleanup cannot leave valid tokens.
await this.prisma.user.update({where:{id:STAGE_TEST_ID,stageTestSession:grant.session,stageTestGeneration:existing.stageTestGeneration},data:{authExpiresAt:new Date(0),password:''}});
onRevoked();
return this.deleteUserRecords(STAGE_TEST_ID, {session:grant.session,generation:existing.stageTestGeneration});
}
async updateUser(id: string, dto: UpdateUserDto, actor?: UserAdminActor) {
if (id === "12345678-1234-1234-1234-123456789012") { if (id === "12345678-1234-1234-1234-123456789012") {
throw new BadRequestException( throw new BadRequestException(
"امکان ویرایش حساب ادمین پیش‌فرض وجود ندارد", "امکان ویرایش حساب ادمین پیش‌فرض وجود ندارد",
@@ -286,6 +325,8 @@ export class AdminService {
throw new NotFoundException(`کاربری با شناسه ${id} یافت نشد`); throw new NotFoundException(`کاربری با شناسه ${id} یافت نشد`);
} }
assertUserMutationAllowed(actor, user.role, dto.role);
const normalizedMobile = dto.mobile const normalizedMobile = dto.mobile
? normalizeMobile(dto.mobile) ? normalizeMobile(dto.mobile)
: undefined; : undefined;
@@ -340,17 +381,11 @@ export class AdminService {
}); });
} }
async updateUserRole(id: string, role: string) { async updateUserRole(id: string, role: string, actor?: UserAdminActor) {
if (!ALLOWED_USER_ROLES.includes(role)) { return this.updateUser(id, { role }, actor);
throw new BadRequestException("نقش کاربری مشخص شده نامعتبر است");
}
return this.prisma.user.update({
where: { id },
data: { role },
});
} }
async deleteUser(id: string) { async deleteUser(id: string, actor?: UserAdminActor) {
if (id === "12345678-1234-1234-1234-123456789012") { if (id === "12345678-1234-1234-1234-123456789012") {
throw new BadRequestException("امکان حذف حساب ادمین پیش‌فرض وجود ندارد"); throw new BadRequestException("امکان حذف حساب ادمین پیش‌فرض وجود ندارد");
} }
@@ -360,7 +395,17 @@ export class AdminService {
throw new NotFoundException(`کاربری با شناسه ${id} یافت نشد`); throw new NotFoundException(`کاربری با شناسه ${id} یافت نشد`);
} }
assertUserMutationAllowed(actor, user.role);
return this.deleteUserRecords(id);
}
private async deleteUserRecords(id: string, stage?: {session:string; generation:string|null}) {
return this.prisma.$transaction(async (tx) => { return this.prisma.$transaction(async (tx) => {
if (stage) {
// Acquire the row lock with an exact fence before deleting any related rows.
await tx.user.update({where:{id,stageTestSession:stage.session,stageTestGeneration:stage.generation},data:{authExpiresAt:new Date(0),password:''}});
}
await tx.userAddress.deleteMany({ where: { userId: id } }); await tx.userAddress.deleteMany({ where: { userId: id } });
await tx.walletTransaction.deleteMany({ where: { userId: id } }); await tx.walletTransaction.deleteMany({ where: { userId: id } });
await tx.pet.deleteMany({ where: { userId: id } }); await tx.pet.deleteMany({ where: { userId: id } });
@@ -1397,12 +1442,15 @@ export class AdminService {
amount: number, amount: number,
type: "deposit" | "withdrawal" | "refund", type: "deposit" | "withdrawal" | "refund",
description?: string, description?: string,
actor?: UserAdminActor,
) { ) {
const user = await this.prisma.user.findUnique({ where: { id: userId } }); const user = await this.prisma.user.findUnique({ where: { id: userId } });
if (!user) { if (!user) {
throw new NotFoundException(`کاربری با شناسه ${userId} یافت نشد.`); throw new NotFoundException(`کاربری با شناسه ${userId} یافت نشد.`);
} }
assertUserMutationAllowed(actor, user.role);
const transaction = await this.prisma.walletTransaction.create({ const transaction = await this.prisma.walletTransaction.create({
data: { data: {
userId, userId,
@@ -1869,4 +1917,164 @@ export class AdminService {
}; };
}); });
} }
async getSymptoms(params?: { page?: number; limit?: number; search?: string }) {
const page = Math.max(1, Number(params?.page) || 1);
const limit = Math.max(1, Number(params?.limit) || 20);
const offset = (page - 1) * limit;
const search = params?.search?.trim() || '';
let items: any[] = [];
let total = 0;
if (search) {
const searchPattern = `%${search}%`;
const [listResult, countResult] = await Promise.all([
this.prisma.$queryRaw<any[]>`
SELECT
s.id,
s.name,
s.slug,
s.description,
s.meta_title as "metaTitle",
s.meta_description as "metaDescription",
s.keywords,
s.icon,
s.created_at as "createdAt",
COALESCE(COUNT(ps.product_id), 0)::int as "productsCount"
FROM symptoms s
LEFT JOIN product_symptoms ps ON ps.symptom = s.name
WHERE s.name ILIKE ${searchPattern} OR s.slug ILIKE ${searchPattern}
GROUP BY s.id, s.name, s.slug, s.description, s.meta_title, s.meta_description, s.keywords, s.icon, s.created_at
ORDER BY s.name ASC
LIMIT ${limit} OFFSET ${offset};
`,
this.prisma.$queryRaw<any[]>`
SELECT COUNT(*)::int as total
FROM symptoms s
WHERE s.name ILIKE ${searchPattern} OR s.slug ILIKE ${searchPattern};
`,
]);
items = listResult;
total = countResult[0]?.total || 0;
} else {
const [listResult, countResult] = await Promise.all([
this.prisma.$queryRaw<any[]>`
SELECT
s.id,
s.name,
s.slug,
s.description,
s.meta_title as "metaTitle",
s.meta_description as "metaDescription",
s.keywords,
s.icon,
s.created_at as "createdAt",
COALESCE(COUNT(ps.product_id), 0)::int as "productsCount"
FROM symptoms s
LEFT JOIN product_symptoms ps ON ps.symptom = s.name
GROUP BY s.id, s.name, s.slug, s.description, s.meta_title, s.meta_description, s.keywords, s.icon, s.created_at
ORDER BY s.name ASC
LIMIT ${limit} OFFSET ${offset};
`,
this.prisma.$queryRaw<any[]>`
SELECT COUNT(*)::int as total
FROM symptoms s;
`,
]);
items = listResult;
total = countResult[0]?.total || 0;
}
const lastPage = Math.ceil(total / limit) || 1;
return {
data: items,
meta: {
page,
limit,
total,
lastPage,
},
};
}
async createSymptom(dto: { name: string; slug?: string; description?: string; metaTitle?: string; metaDescription?: string; keywords?: string }) {
if (!dto.name?.trim()) throw new BadRequestException('نام علامت الزامی است');
const name = dto.name.trim();
const slug = dto.slug?.trim() || name.replace(/\s+/g, '-').toLowerCase();
return await this.prisma.$queryRawUnsafe(`
INSERT INTO symptoms (name, slug, description, meta_title, meta_description, keywords)
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING id, name, slug, description, meta_title as "metaTitle", meta_description as "metaDescription", keywords;
`, name, slug, dto.description || '', dto.metaTitle || '', dto.metaDescription || '', dto.keywords || '');
}
async updateSymptom(id: string, dto: { name?: string; slug?: string; description?: string; metaTitle?: string; metaDescription?: string; keywords?: string }) {
// 1. Get existing symptom
const existing = await this.prisma.$queryRawUnsafe<any[]>(`SELECT * FROM symptoms WHERE id = $1::uuid LIMIT 1`, id);
if (!existing || existing.length === 0) throw new NotFoundException('علامت یافت نشد');
const oldName = existing[0].name;
const newName = dto.name?.trim() || oldName;
const newSlug = dto.slug?.trim() || existing[0].slug;
return await this.prisma.$transaction(async (tx) => {
// Update symptoms table
const updated = await tx.$queryRawUnsafe(`
UPDATE symptoms
SET
name = $2,
slug = $3,
description = $4,
meta_title = $5,
meta_description = $6,
keywords = $7,
updated_at = CURRENT_TIMESTAMP
WHERE id = $1::uuid
RETURNING id, name, slug, description, meta_title as "metaTitle", meta_description as "metaDescription", keywords;
`, id, newName, newSlug, dto.description ?? existing[0].description, dto.metaTitle ?? existing[0].meta_title, dto.metaDescription ?? existing[0].meta_description, dto.keywords ?? existing[0].keywords);
// If name changed, cascade update across product_symptoms & products JSON
if (oldName !== newName) {
await tx.$executeRaw`UPDATE product_symptoms SET symptom = ${newName} WHERE symptom = ${oldName};`;
await tx.$executeRaw`
UPDATE products
SET dosage_config = jsonb_set(
dosage_config,
'{symptoms}',
(
SELECT jsonb_agg(
CASE
WHEN elem::text = to_jsonb(${oldName}::text)::text THEN to_jsonb(${newName}::text)
ELSE elem
END
)
FROM jsonb_array_elements(dosage_config->'symptoms') AS elem
)
)
WHERE dosage_config ? 'symptoms'
AND dosage_config->'symptoms' @> to_jsonb(${oldName}::text);
`;
}
return updated;
});
}
async deleteSymptom(id: string) {
const existing = await this.prisma.$queryRawUnsafe<any[]>(`SELECT * FROM symptoms WHERE id = $1::uuid LIMIT 1`, id);
if (!existing || existing.length === 0) throw new NotFoundException('علامت یافت نشد');
const name = existing[0].name;
return await this.prisma.$transaction(async (tx) => {
// Delete join links
await tx.$executeRaw`DELETE FROM product_symptoms WHERE symptom = ${name};`;
// Delete symptom row
await tx.$queryRawUnsafe(`DELETE FROM symptoms WHERE id = $1::uuid;`, id);
return { success: true, message: `علامت «${name}» با موفقیت حذف شد` };
});
}
} }
-219
View File
@@ -1,219 +0,0 @@
import {
Controller,
Get,
Post,
Put,
Delete,
Body,
Param,
Query,
UseGuards,
NotFoundException,
BadRequestException,
} from "@nestjs/common";
import { ApiTags, ApiBearerAuth, ApiOperation } from "@nestjs/swagger";
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
import { RolesGuard } from "../common/guards/roles.guard";
import { Roles } from "../common/decorators/roles.decorator";
import { PrismaService } from "../prisma/prisma.service";
import {
CreateApprovalRequestDto,
DecideApprovalDto,
QueryApprovalDto,
} from "./dto/approval-request.dto";
@ApiTags("Admin - CEO Approvals & Governance")
@ApiBearerAuth()
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles("Admin", "SUPER_ADMIN")
@Controller("admin/approvals")
export class ApprovalsController {
constructor(private readonly prisma: PrismaService) {}
@Get()
@ApiOperation({ summary: "لیست موارد کارتابل تاییدات مدیریت" })
async findAll(@Query() query: QueryApprovalDto) {
const page = Number(query.page) || 1;
const limit = Number(query.limit) || 100;
const skip = (page - 1) * limit;
const where: any = {};
if (query.department) where.department = query.department;
if (query.category) where.category = query.category;
if (query.status) where.status = query.status;
const [total, items, pendingCount] = await Promise.all([
(this.prisma as any).approvalRequest.count({ where }),
(this.prisma as any).approvalRequest.findMany({
where,
skip,
take: limit,
orderBy: { createdAt: "desc" },
}),
(this.prisma as any).approvalRequest.count({
where: { status: "PENDING" },
}),
]);
return {
success: true,
data: items,
meta: {
total,
page,
limit,
totalPages: Math.ceil(total / limit),
pendingCount,
},
};
}
@Get(":id")
@ApiOperation({ summary: "دریافت جزییات یک آیتم کارتابل" })
async findOne(@Param("id") id: string) {
const item = await (this.prisma as any).approvalRequest.findUnique({
where: { id },
});
if (!item) {
throw new NotFoundException(`Approval request ${id} not found`);
}
return { success: true, data: item };
}
@Post()
@ApiOperation({ summary: "ثبت آیتم جدید جهت تایید مدیریت (از طرف سیستم یا دپارتمان‌ها)" })
async create(@Body() dto: CreateApprovalRequestDto) {
const item = await (this.prisma as any).approvalRequest.create({
data: {
department: dto.department,
category: dto.category,
title: dto.title,
payload: dto.payload,
testContext: dto.testContext || {},
status: "PENDING",
},
});
return { success: true, data: item };
}
@Post(":id/test")
@ApiOperation({ summary: "اجرای شبیه‌سازی تست زنده برای آیتم کارتابل" })
async runTestSimulation(@Param("id") id: string) {
const item = await (this.prisma as any).approvalRequest.findUnique({
where: { id },
});
if (!item) {
throw new NotFoundException(`Approval request ${id} not found`);
}
// شبیه‌سازی بسته به دسته‌بندی
let testResult: any = { status: "SIMULATION_SUCCESS" };
if (item.category === "PRICING") {
const payload = item.payload as any;
testResult = {
impact: "Price change simulation",
currentPrice: payload.currentPrice,
newPrice: payload.newPrice,
marginDiff: payload.newPrice && payload.buyPrice
? (((payload.newPrice - payload.buyPrice) / payload.newPrice) * 100).toFixed(1) + "%"
: "N/A",
torobFeedReflectEstimate: "< 5 seconds",
};
} else if (item.category === "PURCHASE_ORDER") {
const payload = item.payload as any;
testResult = {
document: "PO Pre-check",
itemsCount: payload.items ? payload.items.length : 1,
totalEstimatedCost: payload.totalCost || "محاسبه بر اساس نرخ خرید",
fulfillmentCapacity: "انبار آماده پذیرش",
};
} else {
testResult = {
executionSafe: true,
summary: "تست سلامت اولیه و اعتبارسنجی مقادیر با موفقیت انجام شد.",
};
}
return { success: true, testResult };
}
@Put(":id/decide")
@ApiOperation({ summary: "تصمیم‌گیری مدیرعامل (تایید یا رد همراه با یادداشت)" })
async decide(@Param("id") id: string, @Body() dto: DecideApprovalDto) {
if (!["APPROVED", "REJECTED"].includes(dto.decision)) {
throw new BadRequestException("Decision must be either APPROVED or REJECTED");
}
const item = await (this.prisma as any).approvalRequest.findUnique({
where: { id },
});
if (!item) {
throw new NotFoundException(`Approval request ${id} not found`);
}
if (dto.decision === "REJECTED") {
// 5. رد توسط مدیرعامل: تسک و درخواست کلاً از سیستم پاکسازی کامل می‌شوند
await (this.prisma as any).departmentTask.deleteMany({
where: { approvalId: id },
});
await (this.prisma as any).approvalRequest.delete({
where: { id },
});
return {
success: true,
message: "درخواست با موفقیت رد و از سیستم پاکسازی شد.",
};
}
// 1. تایید مدیرعامل: وضعیت درخواست APPROVED و وضعیت تسک در صف اقدام به TODO تغییر می‌یابد
const updated = await (this.prisma as any).approvalRequest.update({
where: { id },
data: {
status: "APPROVED",
ceoNotes: dto.ceoNotes || null,
executedAt: new Date(),
},
});
// جستجو یا ایجاد تسک متناظر با استاتوس TODO
const existingTask = await (this.prisma as any).departmentTask.findFirst({
where: { approvalId: id },
});
if (existingTask) {
await (this.prisma as any).departmentTask.update({
where: { id: existingTask.id },
data: {
status: "TODO",
description: dto.ceoNotes ? (existingTask.description || "") + "\n\n[یادداشت مدیرعامل]: " + dto.ceoNotes : existingTask.description,
},
});
} else {
await (this.prisma as any).departmentTask.create({
data: {
code: "TSK-" + Date.now().toString().slice(-6),
department: item.department,
title: item.title,
description: dto.ceoNotes ? (item.title + "\n\n[یادداشت مدیرعامل]: " + dto.ceoNotes) : item.title,
status: "TODO",
priority: "HIGH",
assignee: "AI_AGENT",
approvalId: item.id,
},
});
}
return {
success: true,
message: "درخواست تایید شد و مأموریت به صف اقدام (TODO) دپارتمان منتقل گردید.",
data: updated,
};
}
@Delete(":id")
@ApiOperation({ summary: "حذف آیتم از کارتابل" })
async remove(@Param("id") id: string) {
await (this.prisma as any).approvalRequest.delete({ where: { id } });
return { success: true, message: "Deleted successfully" };
}
}
@@ -1,94 +0,0 @@
import {
Controller,
Get,
Post,
Body,
Query,
UseGuards,
Param,
} from "@nestjs/common";
import { ApiTags, ApiBearerAuth, ApiOperation } from "@nestjs/swagger";
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
import { RolesGuard } from "../common/guards/roles.guard";
import { Roles } from "../common/decorators/roles.decorator";
import { PrismaService } from "../prisma/prisma.service";
@ApiTags("Admin - System Audit & History")
@ApiBearerAuth()
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles("Admin", "SUPER_ADMIN")
@Controller("admin/audit-logs")
export class AuditLogsController {
constructor(private readonly prisma: PrismaService) {}
@Get()
@ApiOperation({ summary: "لیست لاگ‌های تغییرات دیتابیس و سیستم" })
async findAll(@Query() query: any) {
const page = Number(query.page) || 1;
const limit = Number(query.limit) || 30;
const skip = (page - 1) * limit;
const where: any = {};
if (query.entity) where.entity = query.entity;
if (query.action) where.action = query.action;
if (query.department) where.department = query.department;
if (query.search) {
where.OR = [
{ summary: { contains: query.search, mode: "insensitive" } },
{ actor: { contains: query.search, mode: "insensitive" } },
{ entityId: { contains: query.search, mode: "insensitive" } },
];
}
const [total, items] = await Promise.all([
(this.prisma as any).auditLog.count({ where }),
(this.prisma as any).auditLog.findMany({
where,
skip,
take: limit,
orderBy: { createdAt: "desc" },
}),
]);
return {
success: true,
data: items,
meta: {
total,
page,
limit,
totalPages: Math.ceil(total / limit),
},
};
}
@Get("recent")
@ApiOperation({ summary: "آخرین رخدادهای سیستم برای ویجت داشبورد" })
async getRecent(@Query("limit") limitParam?: string) {
const limit = Number(limitParam) || 10;
const items = await (this.prisma as any).auditLog.findMany({
take: limit,
orderBy: { createdAt: "desc" },
});
return { success: true, data: items };
}
@Post()
@ApiOperation({ summary: "ثبت لاگ جدید در تاریخچه سیستم" })
async create(@Body() body: any) {
const item = await (this.prisma as any).auditLog.create({
data: {
entity: body.entity,
entityId: body.entityId ? String(body.entityId) : null,
action: body.action || "UPDATE",
department: body.department || "system",
actor: body.actor || "ADMIN",
summary: body.summary,
oldValues: body.oldValues || null,
newValues: body.newValues || null,
metadata: body.metadata || null,
},
});
return { success: true, data: item };
}
}
+117
View File
@@ -0,0 +1,117 @@
import { BadRequestException, ConflictException, NotFoundException } from "@nestjs/common";
import { BlogsService } from "./blogs.service";
// Stateful transactional double: deliberately interleave after snapshot read.
// Complements the DB integration test; it does not assert PostgreSQL locking.
describe("BlogsService atomic optimistic update", () => {
const token = "2026-10-24T23:36:08.501Z";
let row: any;
let service: BlogsService;
let prisma: any;
let revalidate: jest.Mock;
let afterRead: (() => void) | undefined;
let failRelations: boolean;
beforeEach(() => {
row = { id: "b1", slug: "post", title: "Original", updatedAt: new Date(token), tags: ["old"] };
afterRead = undefined;
failRelations = false;
const blog = {
findUnique: jest.fn(async () => {
const snapshot = { ...row };
afterRead?.();
return snapshot;
}),
updateMany: jest.fn(async ({ where, data }) => {
if (row.updatedAt >= where.updatedAt.gte && row.updatedAt < where.updatedAt.lt) {
row = { ...row, ...data };
return { count: 1 };
}
return { count: 0 };
}),
update: jest.fn(async ({ data }) => {
if (failRelations) throw new Error("relation failure");
row = { ...row, ...data };
return { ...row };
}),
};
// Serialize transactions like row locks. Rollback restores only transaction writes.
let tail = Promise.resolve();
prisma = { blog, $transaction: jest.fn((cb) => {
const next = tail.then(async () => {
const before = { ...row };
try { return await cb({ blog }); } catch (error) { row = before; throw error; }
});
tail = next.catch(() => undefined);
return next;
}) };
revalidate = jest.fn().mockResolvedValue(true);
service = new BlogsService(prisma, { revalidateBlog: revalidate } as any);
});
it.each([null, 0, 123, true, {}, [], "", "garbage", "2026-02-30T00:00:00.000Z", "2026-10-24", "2026-10-24T23:36:08.501001Z"])("rejects invalid token %p without mutations", async (value) => {
await expect(service.updateBlog("b1", { title: "bad", expectedUpdatedAt: value })).rejects.toBeInstanceOf(ConflictException);
expect(prisma.blog.update).not.toHaveBeenCalled();
expect(prisma.blog.updateMany).not.toHaveBeenCalled();
expect(revalidate).not.toHaveBeenCalled();
});
it("rejects stale token and leaves all relations untouched", async () => {
await expect(service.updateBlog("b1", { expectedUpdatedAt: "2026-10-20T00:00:00.000Z", tagNames: ["new"], categoryId: "c" })).rejects.toBeInstanceOf(ConflictException);
expect(row.tags).toEqual(["old"]);
expect(prisma.blog.update).not.toHaveBeenCalled();
expect(revalidate).not.toHaveBeenCalled();
});
it.each([token, "2026-10-25T01:36:08.501+02:00"])("accepts current token %s and atomically includes relations", async (expectedUpdatedAt) => {
const result = await service.updateBlog("b1", { title: "new", expectedUpdatedAt, authorId: "a", categoryId: "c", tagNames: ["new"] });
expect(result.title).toBe("new");
expect(prisma.$transaction).toHaveBeenCalledTimes(1);
expect(prisma.blog.updateMany).toHaveBeenCalledWith({ where: { id: "b1", updatedAt: { gte: new Date(token), lt: new Date(new Date(token).getTime() + 1) } }, data: { updatedAt: expect.any(Date) } });
expect(prisma.blog.update.mock.calls[0][0].data).toMatchObject({ author: { connect: { id: "a" } }, category: { connect: { id: "c" } }, tags: { set: [], connectOrCreate: expect.any(Array) } });
expect(prisma.blog.update.mock.calls[0][0].data).not.toHaveProperty("expectedUpdatedAt");
expect(result.updatedAt.getTime()).toBeGreaterThan(new Date(token).getTime());
expect(revalidate).toHaveBeenCalledTimes(1);
});
it("detects writer interleaving after read before write", async () => {
afterRead = () => { row = { ...row, title: "winner", updatedAt: new Date("2026-10-24T23:36:08.502Z"), tags: ["winner"] }; };
await expect(service.updateBlog("b1", { expectedUpdatedAt: token, title: "loser", tagNames: ["loser"] })).rejects.toBeInstanceOf(ConflictException);
expect(row.title).toBe("winner");
expect(row.tags).toEqual(["winner"]);
expect(prisma.blog.update).not.toHaveBeenCalled();
expect(revalidate).not.toHaveBeenCalled();
});
it("permits exactly one of two requests sharing a token", async () => {
const results = await Promise.allSettled([service.updateBlog("b1", { expectedUpdatedAt: token, title: "a" }), service.updateBlog("b1", { expectedUpdatedAt: token, title: "b" })]);
expect(results.filter(r => r.status === "fulfilled")).toHaveLength(1);
const rejected = results.find(r => r.status === "rejected") as PromiseRejectedResult;
expect(rejected.reason).toBeInstanceOf(ConflictException);
expect(revalidate).toHaveBeenCalledTimes(1);
});
it("advances token even when clock is within same millisecond", async () => {
jest.useFakeTimers().setSystemTime(new Date(token));
try {
await service.updateBlog("b1", { expectedUpdatedAt: token, title: "first" });
await expect(service.updateBlog("b1", { expectedUpdatedAt: token, title: "second" })).rejects.toBeInstanceOf(ConflictException);
} finally { jest.useRealTimers(); }
});
it("rolls back claim on nested relation failure without invalidating cache", async () => {
failRelations = true;
await expect(service.updateBlog("b1", { expectedUpdatedAt: token, tagNames: ["new"] })).rejects.toThrow("relation failure");
expect(row.updatedAt.toISOString()).toBe(token);
expect(row.tags).toEqual(["old"]);
expect(revalidate).not.toHaveBeenCalled();
});
it("preserves legacy omission without demanding a token", async () => {
await service.updateBlog("b1", { title: "legacy" });
expect(row.title).toBe("legacy");
expect(prisma.$transaction).not.toHaveBeenCalled();
});
it("returns 404 for a missing blog", async () => {
prisma.blog.findUnique.mockResolvedValue(null);
await expect(service.updateBlog("missing", { expectedUpdatedAt: token })).rejects.toBeInstanceOf(NotFoundException);
});
it("does not fail committed writes if revalidation throws", async () => {
revalidate.mockRejectedValue(new Error("cache down"));
const result = await service.updateBlog("b1", { expectedUpdatedAt: token, title: "saved" });
expect(result.cacheRevalidation).toBe("failed");
expect(row.title).toBe("saved");
});
});
@@ -229,6 +229,15 @@ describe("BlogsController (Admin)", () => {
expect(result).toEqual({ success: true, data: createdBlog }); expect(result).toEqual({ success: true, data: createdBlog });
}); });
it("propagates create validation failures", async () => {
const req = { user: { id: "admin-user-id" } };
const body = { title: "Bad date", contentUpdatedAt: "invalid", createdAt: "2000-01-01" };
mockBlogsService.createBlog.mockRejectedValueOnce(new Error("Invalid contentUpdatedAt"));
await expect(controller.createBlog(body, req)).rejects.toThrow("Invalid contentUpdatedAt");
expect(service.createBlog).toHaveBeenCalledWith(body, req.user.id);
});
it("updateBlog should update blog details and return success: true", async () => { it("updateBlog should update blog details and return success: true", async () => {
const blogId = "blog-10"; const blogId = "blog-10";
const body = { const body = {
@@ -244,6 +253,14 @@ describe("BlogsController (Admin)", () => {
expect(result).toEqual({ success: true, data: updatedBlog }); expect(result).toEqual({ success: true, data: updatedBlog });
}); });
it("propagates invalid content timestamp rejection without accepting createdAt", async () => {
const body = { contentUpdatedAt: "invalid", createdAt: "2000-01-01" };
mockBlogsService.updateBlog.mockRejectedValueOnce(new Error("Invalid contentUpdatedAt"));
await expect(controller.updateBlog("blog-10", body)).rejects.toThrow("Invalid contentUpdatedAt");
expect(service.updateBlog).toHaveBeenCalledWith("blog-10", body);
});
it("deleteBlog should delete blog and return success: true", async () => { it("deleteBlog should delete blog and return success: true", async () => {
const blogId = "blog-10"; const blogId = "blog-10";
mockBlogsService.deleteBlog.mockResolvedValue(undefined); mockBlogsService.deleteBlog.mockResolvedValue(undefined);
+240 -3
View File
@@ -54,6 +54,8 @@ describe("Admin BlogsService", () => {
}).compile(); }).compile();
service = module.get<BlogsService>(BlogsService); service = module.get<BlogsService>(BlogsService);
mockRevalidationService.revalidateBlog.mockReset();
mockRevalidationService.revalidateBlog.mockResolvedValue(true);
jest.clearAllMocks(); jest.clearAllMocks();
}); });
@@ -200,7 +202,54 @@ describe("Admin BlogsService", () => {
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith( expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith(
"new-health-post", "new-health-post",
); );
expect(result).toEqual(createdBlog); expect(result).toEqual({
...createdBlog,
cacheRevalidation: "success",
});
});
it("allowlists create fields and blocks server-owned and unknown fields", async () => {
mockPrisma.blog.create.mockResolvedValue({ id: "created", slug: "safe-post" });
await service.createBlog(
{
title: "Safe post",
slug: "safe-post",
content: "Safe content",
id: "client-id",
createdAt: "2000-01-01T00:00:00.000Z",
updatedAt: "2000-01-01T00:00:00.000Z",
viewCount: 999999,
serverOwned: "must-not-pass",
},
"user-admin-1",
);
const payload = mockPrisma.blog.create.mock.calls[0][0].data;
expect(payload).toEqual(expect.objectContaining({
title: "Safe post",
slug: "safe-post",
content: "Safe content",
}));
expect(payload).not.toHaveProperty("id");
expect(payload).not.toHaveProperty("createdAt");
expect(payload).not.toHaveProperty("updatedAt");
expect(payload).not.toHaveProperty("viewCount");
expect(payload).not.toHaveProperty("serverOwned");
});
it.each([
["contentUpdatedAt", { contentUpdatedAt: "not-a-date" }, "Invalid contentUpdatedAt"],
["publishedAt", { publishedAt: "not-a-date" }, "Invalid publishedAt"],
["scheduledAt", { scheduledAt: "not-a-date" }, "Invalid scheduledAt"],
])("rejects invalid explicit %s", async (_field, timestamps, message) => {
await expect(
service.createBlog(
{ title: "Bad date", slug: "bad-date", content: "Content", ...timestamps },
"user-admin-1",
),
).rejects.toThrow(message);
expect(mockPrisma.blog.create).not.toHaveBeenCalled();
}); });
it("should create a SCHEDULED blog if scheduledAt is in the future", async () => { it("should create a SCHEDULED blog if scheduledAt is in the future", async () => {
@@ -228,6 +277,66 @@ describe("Admin BlogsService", () => {
}), }),
); );
}); });
it("should expose cacheRevalidation status on create result without failing persistence", async () => {
const blogData = {
title: "Health Post",
slug: "health-post",
content: "Content",
};
const createdBlog = { id: "blog-1", ...blogData };
mockPrisma.blog.create.mockResolvedValue(createdBlog);
mockRevalidationService.revalidateBlog.mockResolvedValue(true);
const result = await service.createBlog(blogData, "user-admin-1");
expect(mockPrisma.blog.create).toHaveBeenCalled();
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith("health-post");
expect(result).toEqual({
...createdBlog,
cacheRevalidation: "success",
});
});
it("should return cacheRevalidation 'failed' when revalidation fails without failing persistence", async () => {
const blogData = {
title: "Health Post",
slug: "health-post",
content: "Content",
};
const createdBlog = { id: "blog-1", ...blogData };
mockPrisma.blog.create.mockResolvedValue(createdBlog);
mockRevalidationService.revalidateBlog.mockResolvedValue(false);
const result = await service.createBlog(blogData, "user-admin-1");
expect(mockPrisma.blog.create).toHaveBeenCalled();
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith("health-post");
expect(result).toEqual({
...createdBlog,
cacheRevalidation: "failed",
});
});
it("should catch unexpected revalidation exceptions on create and return cacheRevalidation 'failed'", async () => {
const blogData = {
title: "Health Post",
slug: "health-post",
content: "Content",
};
const createdBlog = { id: "blog-1", ...blogData };
mockPrisma.blog.create.mockResolvedValue(createdBlog);
mockRevalidationService.revalidateBlog.mockRejectedValue(new Error("Frontend offline"));
const result = await service.createBlog(blogData, "user-admin-1");
expect(mockPrisma.blog.create).toHaveBeenCalled();
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith("health-post");
expect(result).toEqual({
...createdBlog,
cacheRevalidation: "failed",
});
});
}); });
describe("updateBlog", () => { describe("updateBlog", () => {
@@ -270,7 +379,136 @@ describe("Admin BlogsService", () => {
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith( expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith(
"my-post", "my-post",
); );
expect(result).toEqual(updated); expect(result).toEqual({
...updated,
cacheRevalidation: "success",
});
});
it("should expose cacheRevalidation status on update result without failing persistence", async () => {
const existing = { id: "b1", slug: "my-post", title: "Old Title" };
mockPrisma.blog.findUnique.mockResolvedValue(existing);
const updated = { ...existing, title: "New Title" };
mockPrisma.blog.update.mockResolvedValue(updated);
mockRevalidationService.revalidateBlog.mockResolvedValue(true);
const result = await service.updateBlog("b1", { title: "New Title" });
expect(mockPrisma.blog.update).toHaveBeenCalled();
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith("my-post");
expect(result).toEqual({
...updated,
cacheRevalidation: "success",
});
});
it("should return cacheRevalidation 'failed' when revalidation fails on update without failing persistence", async () => {
const existing = { id: "b1", slug: "my-post", title: "Old Title" };
mockPrisma.blog.findUnique.mockResolvedValue(existing);
const updated = { ...existing, title: "New Title" };
mockPrisma.blog.update.mockResolvedValue(updated);
mockRevalidationService.revalidateBlog.mockResolvedValue(false);
const result = await service.updateBlog("b1", { title: "New Title" });
expect(mockPrisma.blog.update).toHaveBeenCalled();
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith("my-post");
expect(result).toEqual({
...updated,
cacheRevalidation: "failed",
});
});
it("should catch unexpected revalidation exceptions on update and return cacheRevalidation 'failed'", async () => {
const existing = { id: "b1", slug: "my-post", title: "Old Title" };
mockPrisma.blog.findUnique.mockResolvedValue(existing);
const updated = { ...existing, title: "New Title" };
mockPrisma.blog.update.mockResolvedValue(updated);
mockRevalidationService.revalidateBlog.mockRejectedValue(new Error("Revalidation timeout"));
const result = await service.updateBlog("b1", { title: "New Title" });
expect(mockPrisma.blog.update).toHaveBeenCalled();
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith("my-post");
expect(result).toEqual({
...updated,
cacheRevalidation: "failed",
});
});
});
describe("material freshness and scheduled publishing", () => {
it("sets contentUpdatedAt intentionally and never rewrites createdAt", async () => {
mockPrisma.blog.findUnique.mockResolvedValue({ id: "b1", slug: "post", createdAt: new Date("2025-01-01") });
mockPrisma.blog.update.mockResolvedValue({ id: "b1", slug: "post" });
await service.updateBlog("b1", { title: "Material edit", markContentUpdated: true });
const payload = mockPrisma.blog.update.mock.calls[0][0].data;
expect(payload.contentUpdatedAt).toEqual(expect.any(Date));
expect(payload).not.toHaveProperty("markContentUpdated");
expect(payload).not.toHaveProperty("createdAt");
});
it("automatically marks freshness when material article content changes", async () => {
mockPrisma.blog.findUnique.mockResolvedValue({ id: "b1", slug: "post", content: "Old content" });
mockPrisma.blog.update.mockResolvedValue({ id: "b1", slug: "post" });
await service.updateBlog("b1", { content: "Meaningfully revised content" });
expect(mockPrisma.blog.update.mock.calls[0][0].data.contentUpdatedAt).toEqual(expect.any(Date));
});
it("does not mark freshness for attribution-only changes", async () => {
mockPrisma.blog.findUnique.mockResolvedValue({ id: "b1", slug: "post", content: "Same content" });
mockPrisma.blog.update.mockResolvedValue({ id: "b1", slug: "post" });
await service.updateBlog("b1", { authorTeam: "Clinical team", authorRole: "Review" });
expect(mockPrisma.blog.update.mock.calls[0][0].data).not.toHaveProperty("contentUpdatedAt");
});
it("allows explicitly clearing contentUpdatedAt", async () => {
mockPrisma.blog.findUnique.mockResolvedValue({ id: "b1", slug: "post" });
mockPrisma.blog.update.mockResolvedValue({ id: "b1", slug: "post" });
await service.updateBlog("b1", { contentUpdatedAt: null });
expect(mockPrisma.blog.update.mock.calls[0][0].data.contentUpdatedAt).toBeNull();
});
it("publishes due posts without rewriting createdAt", async () => {
const scheduledAt = new Date("2025-02-01T10:00:00Z");
mockPrisma.blog.findMany.mockResolvedValue([{ id: "b1", slug: "post", title: "Post", scheduledAt }]);
mockPrisma.blog.update.mockResolvedValue({});
await service.publishDueScheduledBlogs();
expect(mockPrisma.blog.update).toHaveBeenCalledWith({ where: { id: "b1" }, data: { status: "PUBLISHED", isPublished: true, publishedAt: scheduledAt } });
});
});
describe("updateBlog security and freshness validation", () => {
beforeEach(() => {
mockPrisma.blog.findUnique.mockResolvedValue({ id: "blog-1", slug: "safe" });
mockPrisma.blog.update.mockResolvedValue({ id: "blog-1", slug: "safe" });
});
it("allowlists mutable fields and ignores createdAt and unrecognized fields", async () => {
await service.updateBlog("blog-1", {
title: "Allowed title",
createdAt: "2000-01-01T00:00:00.000Z",
serverOwned: "must-not-pass",
});
const payload = mockPrisma.blog.update.mock.calls[0][0].data;
expect(payload.title).toBe("Allowed title");
expect(payload).not.toHaveProperty("createdAt");
expect(payload).not.toHaveProperty("serverOwned");
});
it("rejects an invalid explicit contentUpdatedAt", async () => {
await expect(
service.updateBlog("blog-1", { contentUpdatedAt: "not-a-date" }),
).rejects.toThrow("Invalid contentUpdatedAt");
expect(mockPrisma.blog.update).not.toHaveBeenCalled();
});
it("preserves explicit null clearing and markContentUpdated precedence", async () => {
await service.updateBlog("blog-1", { contentUpdatedAt: null });
expect(mockPrisma.blog.update.mock.calls[0][0].data.contentUpdatedAt).toBeNull();
await service.updateBlog("blog-1", {
contentUpdatedAt: "not-a-date",
markContentUpdated: true,
});
expect(mockPrisma.blog.update.mock.calls[1][0].data.contentUpdatedAt).toEqual(expect.any(Date));
}); });
}); });
@@ -468,7 +706,6 @@ describe("Admin BlogsService", () => {
status: "PUBLISHED", status: "PUBLISHED",
isPublished: true, isPublished: true,
publishedAt: scheduledDate, publishedAt: scheduledDate,
createdAt: scheduledDate,
}, },
}); });
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith( expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith(
+213 -31
View File
@@ -1,4 +1,6 @@
import { import {
BadRequestException,
ConflictException,
Injectable, Injectable,
NotFoundException, NotFoundException,
OnModuleInit, OnModuleInit,
@@ -141,16 +143,31 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
async createBlog(data: any, currentUserId: string) { async createBlog(data: any, currentUserId: string) {
const { const {
tags,
tagNames, tagNames,
categoryId, categoryId,
authorId, authorId,
publishedAt, publishedAt,
scheduledAt, scheduledAt,
readingTime, readingTime,
...rest markContentUpdated,
contentUpdatedAt,
} = data; } = data;
const parseOptionalDate = (value: unknown, field: string): Date | null => {
if (value === undefined || value === null || value === "") return null;
const parsed = new Date(value as string | number | Date);
if (!Number.isFinite(parsed.getTime())) {
throw new BadRequestException(`Invalid ${field}`);
}
return parsed;
};
const parsedPublishedAt = parseOptionalDate(publishedAt, "publishedAt");
const parsedScheduledAt = parseOptionalDate(scheduledAt, "scheduledAt");
const parsedContentUpdatedAt = markContentUpdated
? new Date()
: parseOptionalDate(contentUpdatedAt, "contentUpdatedAt");
// Connect or create tags // Connect or create tags
const tagConnectOrCreate = []; const tagConnectOrCreate = [];
if (Array.isArray(tagNames) && tagNames.length > 0) { if (Array.isArray(tagNames) && tagNames.length > 0) {
@@ -171,13 +188,12 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
const targetAuthorId = authorId || currentUserId; const targetAuthorId = authorId || currentUserId;
const now = new Date(); const now = new Date();
const parsedScheduledAt = scheduledAt ? new Date(scheduledAt) : null;
const isFutureSchedule = parsedScheduledAt && parsedScheduledAt > now; const isFutureSchedule = parsedScheduledAt && parsedScheduledAt > now;
let finalStatus = rest.status || "PUBLISHED"; let finalStatus = data.status || "PUBLISHED";
let finalIsPublished = let finalIsPublished =
rest.isPublished !== undefined ? rest.isPublished : true; data.isPublished !== undefined ? data.isPublished : true;
let finalPublishedAt = publishedAt ? new Date(publishedAt) : null; let finalPublishedAt = parsedPublishedAt;
if (isFutureSchedule) { if (isFutureSchedule) {
finalStatus = "SCHEDULED"; finalStatus = "SCHEDULED";
@@ -191,19 +207,45 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
finalPublishedAt = now; finalPublishedAt = now;
} }
const createPayload: Prisma.BlogCreateInput = { const createPayload = {
...rest, title: data.title,
slug: data.slug,
content: data.content,
excerpt: data.excerpt,
authorTeam: data.authorTeam,
authorRole: data.authorRole,
imageUrl: data.imageUrl,
imageAlt: data.imageAlt,
imageCaption: data.imageCaption,
metaTitle: data.metaTitle,
metaDescription: data.metaDescription,
keywords: data.keywords,
focusKeywords: data.focusKeywords,
canonicalUrl: data.canonicalUrl,
noIndex: data.noIndex,
noFollow: data.noFollow,
schemaType: data.schemaType,
ogTitle: data.ogTitle,
ogDescription: data.ogDescription,
ogImage: data.ogImage,
status: finalStatus, status: finalStatus,
isPublished: finalIsPublished, isPublished: finalIsPublished,
readingTime: readingTime ? Number(readingTime) : 3, featured: data.featured,
allowComments: data.allowComments,
showOnHome: data.showOnHome,
homeDisplayMode: data.homeDisplayMode,
relatedProductIds: data.relatedProductIds,
relatedBlogIds: data.relatedBlogIds,
readingTime: readingTime !== undefined ? Number(readingTime) : 3,
publishedAt: finalPublishedAt, publishedAt: finalPublishedAt,
scheduledAt: parsedScheduledAt, scheduledAt: parsedScheduledAt,
contentUpdatedAt: parsedContentUpdatedAt,
author: { connect: { id: targetAuthorId } }, author: { connect: { id: targetAuthorId } },
...(categoryId ? { category: { connect: { id: categoryId } } } : {}), ...(categoryId ? { category: { connect: { id: categoryId } } } : {}),
...(tagConnectOrCreate.length > 0 ...(tagConnectOrCreate.length > 0
? { tags: { connectOrCreate: tagConnectOrCreate } } ? { tags: { connectOrCreate: tagConnectOrCreate } }
: {}), : {}),
}; } satisfies Prisma.BlogCreateInput;
const created = await this.prisma.blog.create({ const created = await this.prisma.blog.create({
data: createPayload, data: createPayload,
@@ -214,8 +256,21 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
}, },
}); });
await this.revalidationService.revalidateBlog(created.slug); let cacheRevalidation: "success" | "failed" = "failed";
return created; try {
const revalidated = await this.revalidationService.revalidateBlog(created.slug);
cacheRevalidation = revalidated ? "success" : "failed";
} catch (err: any) {
this.logger.warn(
`Cache revalidation failed for created blog [${created.slug}]: ${err?.message}`,
);
cacheRevalidation = "failed";
}
return {
...created,
cacheRevalidation,
};
} }
async updateBlog(id: string, data: any) { async updateBlog(id: string, data: any) {
@@ -223,19 +278,105 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
if (!blog) throw new NotFoundException("Blog not found"); if (!blog) throw new NotFoundException("Blog not found");
const { const {
tags,
tagNames, tagNames,
categoryId, categoryId,
authorId, authorId,
publishedAt, publishedAt,
scheduledAt, scheduledAt,
readingTime, readingTime,
...rest markContentUpdated,
contentUpdatedAt,
expectedUpdatedAt,
} = data; } = data;
const conflict = () => new ConflictException(
"CONCURRENT_MODIFICATION: Blog has been modified by another process",
);
let expectedTime: number | undefined;
if (expectedUpdatedAt !== undefined) {
// Only accept the millisecond, timezone-qualified ISO token returned by GET
// (or an equivalent offset). Avoid Date's coercion of null, numbers, arrays,
// and its normalization of impossible calendar dates.
const match = typeof expectedUpdatedAt === "string" && expectedUpdatedAt.match(
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?(Z|[+-]\d{2}:\d{2})$/,
);
if (!match) throw conflict();
expectedTime = Date.parse(expectedUpdatedAt);
const calendar = new Date(`${match[1]}-${match[2]}-${match[3]}T00:00:00.000Z`);
if (!Number.isFinite(expectedTime) ||
calendar.toISOString().slice(0, 10) !== `${match[1]}-${match[2]}-${match[3]}` ||
Number(match[4]) > 23 || Number(match[5]) > 59 || Number(match[6]) > 59) {
throw conflict();
}
}
const mutableScalarFields = [
"title",
"slug",
"content",
"excerpt",
"authorTeam",
"authorRole",
"imageUrl",
"imageAlt",
"imageCaption",
"metaTitle",
"metaDescription",
"keywords",
"focusKeywords",
"canonicalUrl",
"noIndex",
"noFollow",
"schemaType",
"ogTitle",
"ogDescription",
"ogImage",
"status",
"isPublished",
"featured",
"allowComments",
"showOnHome",
"homeDisplayMode",
"relatedProductIds",
"relatedBlogIds",
] as const;
const updatePayload: Prisma.BlogUpdateInput = {};
for (const field of mutableScalarFields) {
if (data[field] !== undefined) {
(updatePayload as Record<string, unknown>)[field] = data[field];
}
}
const now = new Date(); const now = new Date();
const updatePayload: Prisma.BlogUpdateInput = { const materialContentFields = [
...rest, "title",
"content",
"excerpt",
"imageUrl",
"imageAlt",
"imageCaption",
] as const;
const hasMaterialContentChange = materialContentFields.some(
(field) => data[field] !== undefined && data[field] !== blog[field],
);
if (markContentUpdated || (contentUpdatedAt === undefined && hasMaterialContentChange)) {
(updatePayload as Record<string, unknown>).contentUpdatedAt = now;
} else if (contentUpdatedAt !== undefined) {
if (contentUpdatedAt === null || contentUpdatedAt === "") {
(updatePayload as Record<string, unknown>).contentUpdatedAt = null;
} else {
const parsedContentUpdatedAt = new Date(contentUpdatedAt);
if (!Number.isFinite(parsedContentUpdatedAt.getTime())) {
throw new BadRequestException("Invalid contentUpdatedAt");
}
(updatePayload as Record<string, unknown>).contentUpdatedAt = parsedContentUpdatedAt;
}
}
Object.assign(updatePayload, {
...(readingTime !== undefined
? { readingTime: Number(readingTime) }
: {}),
...(readingTime !== undefined ...(readingTime !== undefined
? { readingTime: Number(readingTime) } ? { readingTime: Number(readingTime) }
: {}), : {}),
@@ -245,7 +386,7 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
? { category: { connect: { id: categoryId } } } ? { category: { connect: { id: categoryId } } }
: { category: { disconnect: true } } : { category: { disconnect: true } }
: {}), : {}),
}; });
if (scheduledAt !== undefined) { if (scheduledAt !== undefined) {
const parsedScheduledAt = scheduledAt ? new Date(scheduledAt) : null; const parsedScheduledAt = scheduledAt ? new Date(scheduledAt) : null;
@@ -259,7 +400,6 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
updatePayload.status = "PUBLISHED"; updatePayload.status = "PUBLISHED";
updatePayload.isPublished = true; updatePayload.isPublished = true;
updatePayload.publishedAt = parsedScheduledAt; updatePayload.publishedAt = parsedScheduledAt;
updatePayload.createdAt = parsedScheduledAt;
} }
} else if (publishedAt !== undefined) { } else if (publishedAt !== undefined) {
updatePayload.publishedAt = publishedAt ? new Date(publishedAt) : null; updatePayload.publishedAt = publishedAt ? new Date(publishedAt) : null;
@@ -286,25 +426,68 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
}; };
} }
const updated = await this.prisma.blog.update({ const include = {
where: { id }, author: { select: { firstName: true, lastName: true } },
data: updatePayload, category: true,
include: { tags: true,
author: { select: { firstName: true, lastName: true } }, };
category: true, // Legacy UI requests without a token intentionally retain last-write-wins.
tags: true, // Guarded requests claim the row using a DB predicate, not the earlier read.
}, const updated = expectedTime === undefined
}); ? await this.prisma.blog.update({ where: { id }, data: updatePayload, include })
: await this.prisma.$transaction(async (tx) => {
// PostgreSQL timestamptz defaults to microseconds; JSON/JS Dates expose
// milliseconds. Match the entire represented millisecond, then move
// strictly beyond it (including same-ms writes and clock rollback).
const claimedAt = new Date(Math.max(Date.now(), expectedTime + 1));
const claim = await tx.blog.updateMany({
where: {
id,
updatedAt: {
gte: new Date(expectedTime),
lt: new Date(expectedTime + 1),
},
},
data: { updatedAt: claimedAt },
});
if (claim.count !== 1) throw conflict();
// The claim holds the row lock until this nested mutation commits.
// Any relation failure rolls back both the claim and all data writes.
return tx.blog.update({
where: { id },
data: { ...updatePayload, updatedAt: claimedAt },
include,
});
});
await this.revalidationService.revalidateBlog(updated.slug); let cacheRevalidation: "success" | "failed" = "failed";
return updated; try {
const revalidated = await this.revalidationService.revalidateBlog(updated.slug);
cacheRevalidation = revalidated ? "success" : "failed";
} catch (err: any) {
this.logger.warn(
`Cache revalidation failed for updated blog [${updated.slug}]: ${err?.message}`,
);
cacheRevalidation = "failed";
}
return {
...updated,
cacheRevalidation,
};
} }
async deleteBlog(id: string) { async deleteBlog(id: string) {
const blog = await this.prisma.blog.findUnique({ where: { id } }); const blog = await this.prisma.blog.findUnique({ where: { id } });
if (!blog) throw new NotFoundException("Blog not found"); if (!blog) throw new NotFoundException("Blog not found");
const res = await this.prisma.blog.delete({ where: { id } }); const res = await this.prisma.blog.delete({ where: { id } });
await this.revalidationService.revalidateBlog(blog.slug); try {
await this.revalidationService.revalidateBlog(blog.slug);
} catch (err: any) {
this.logger.warn(
`Cache revalidation failed for deleted blog [${blog.slug}]: ${err?.message}`,
);
}
return res; return res;
} }
@@ -472,7 +655,6 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
status: "PUBLISHED", status: "PUBLISHED",
isPublished: true, isPublished: true,
publishedAt: publishDate, publishedAt: publishDate,
createdAt: publishDate,
}, },
}); });
@@ -1,208 +0,0 @@
import {
Controller,
Get,
Post,
Put,
Delete,
Body,
Param,
Query,
UseGuards,
NotFoundException,
} from "@nestjs/common";
import { ApiTags, ApiBearerAuth, ApiOperation } from "@nestjs/swagger";
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
import { RolesGuard } from "../common/guards/roles.guard";
import { Roles } from "../common/decorators/roles.decorator";
import { PrismaService } from "../prisma/prisma.service";
@ApiTags("Admin - Department & Agent Tasks")
@ApiBearerAuth()
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles("Admin", "SUPER_ADMIN")
@Controller("admin/department-tasks")
export class DepartmentTasksController {
constructor(private readonly prisma: PrismaService) {}
@Get()
@ApiOperation({ summary: "لیست تسک‌های دپارتمان‌ها و ایجنت‌ها" })
async findAll(@Query() query: any) {
const page = Number(query.page) || 1;
const limit = Number(query.limit) || 100;
const skip = (page - 1) * limit;
const where: any = {};
if (query.department) where.department = query.department;
if (query.status) where.status = query.status;
if (query.priority) where.priority = query.priority;
if (query.search) {
where.OR = [
{ code: { contains: query.search, mode: "insensitive" } },
{ title: { contains: query.search, mode: "insensitive" } },
{ description: { contains: query.search, mode: "insensitive" } },
];
}
const [total, items] = await Promise.all([
(this.prisma as any).departmentTask.count({ where }),
(this.prisma as any).departmentTask.findMany({
where,
skip,
take: limit,
orderBy: [{ priority: "desc" }, { createdAt: "desc" }],
}),
]);
return {
success: true,
data: items,
meta: {
total,
page,
limit,
totalPages: Math.ceil(total / limit),
},
};
}
@Get("stats")
@ApiOperation({ summary: "آمار تسک‌ها به تفکیک استیت و دپارتمان" })
async getStats() {
const tasks = await (this.prisma as any).departmentTask.findMany({
select: { department: true, status: true, priority: true },
});
const statusCounts: Record<string, number> = {
TODO: 0,
IN_PROGRESS: 0,
TEST: 0,
DONE: 0,
BACKLOG: 0,
IN_REVIEW: 0,
APPROVED: 0,
DEPLOYING: 0,
};
const departmentCounts: Record<string, number> = {};
for (const t of tasks) {
statusCounts[t.status] = (statusCounts[t.status] || 0) + 1;
departmentCounts[t.department] = (departmentCounts[t.department] || 0) + 1;
}
return {
success: true,
data: {
total: tasks.length,
byStatus: statusCounts,
byDepartment: departmentCounts,
},
};
}
@Get(":id")
@ApiOperation({ summary: "دریافت جزییات یک تسک" })
async findOne(@Param("id") id: string) {
const task = await (this.prisma as any).departmentTask.findUnique({
where: { id },
});
if (!task) throw new NotFoundException(`Task ${id} not found`);
return { success: true, data: task };
}
@Post()
@ApiOperation({ summary: "ایجاد تسک جدید سازمانی" })
async create(@Body() body: any) {
const code = body.code || "TSK-" + Date.now().toString().slice(-6);
const task = await (this.prisma as any).departmentTask.create({
data: {
code,
department: body.department,
title: body.title,
description: body.description || null,
status: body.status || "TODO",
priority: body.priority || "MEDIUM",
assignee: body.assignee || "AI_AGENT",
acceptanceCriteria: body.acceptanceCriteria || null,
executionLogs: body.executionLogs || [],
deliverableUrl: body.deliverableUrl || null,
startedAt: body.status === "IN_PROGRESS" ? new Date() : null,
},
});
// ثبت در تاریخچه لاگ‌ها
await (this.prisma as any).auditLog.create({
data: {
entity: "task",
entityId: task.id,
action: "CREATE",
department: task.department,
actor: task.assignee || "SYSTEM",
summary: "تسک جدید " + task.code + " (" + task.title + ") ایجاد شد.",
newValues: task,
},
});
return { success: true, data: task };
}
@Put(":id/status")
@ApiOperation({ summary: "تغییر وضعیت تسک همراه با لاگ اجرا" })
async updateStatus(
@Param("id") id: string,
@Body() body: { status: string; logNote?: string; deliverableUrl?: string }
) {
const existing = await (this.prisma as any).departmentTask.findUnique({
where: { id },
});
if (!existing) throw new NotFoundException(`Task ${id} not found`);
const logs = Array.isArray(existing.executionLogs) ? [...existing.executionLogs] : [];
if (body.logNote) {
logs.push({
timestamp: new Date().toISOString(),
status: body.status,
note: body.logNote,
});
}
const updateData: any = {
status: body.status,
executionLogs: logs,
};
if (body.deliverableUrl) updateData.deliverableUrl = body.deliverableUrl;
if (body.status === "IN_PROGRESS" && !existing.startedAt) updateData.startedAt = new Date();
if (body.status === "DONE") updateData.completedAt = new Date();
// اگر تست QA ناموفق بود و به TODO برگشت، لاگ اصلاح ضمیمه می‌شود
if (body.status === "TODO" && body.logNote) {
updateData.description = (existing.description || "") + "\n\n[اصلاحات و تضمین کیفیت QA]: " + body.logNote;
}
const updated = await (this.prisma as any).departmentTask.update({
where: { id },
data: updateData,
});
// ثبت در تاریخچه
await (this.prisma as any).auditLog.create({
data: {
entity: "task",
entityId: updated.id,
action: "UPDATE",
department: updated.department,
actor: "SYSTEM",
summary: "وضعیت تسک " + updated.code + " به " + body.status + " تغییر یافت.",
oldValues: { status: existing.status },
newValues: { status: updated.status, note: body.logNote },
},
});
return { success: true, data: updated };
}
@Delete(":id")
@ApiOperation({ summary: "حذف تسک" })
async remove(@Param("id") id: string) {
await (this.prisma as any).departmentTask.delete({ where: { id } });
return { success: true, message: "Deleted successfully" };
}
}
@@ -1,58 +0,0 @@
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { IsString, IsOptional, IsObject } from "class-validator";
export class CreateApprovalRequestDto {
@ApiProperty({ description: "دپارتمان مبدا (DEV, SUPPLY, FINANCE, SEO, CRM, CONTENT)" })
@IsString()
department: string;
@ApiProperty({ description: "دسته‌بندی (PRICING, PURCHASE_ORDER, CAMPAIGN, DEPLOY, etc)" })
@IsString()
category: string;
@ApiProperty({ description: "عنوان مورد تایید" })
@IsString()
title: string;
@ApiProperty({ description: "داده‌های تغییرات پیشنهادی" })
@IsObject()
payload: Record<string, any>;
@ApiPropertyOptional({ description: "داده‌های سناریوی تست و ارزیابی" })
@IsOptional()
@IsObject()
testContext?: Record<string, any>;
}
export class DecideApprovalDto {
@ApiProperty({ description: "تصمیم: APPROVED یا REJECTED" })
@IsString()
decision: "APPROVED" | "REJECTED";
@ApiPropertyOptional({ description: "توضیحات و یادداشت مدیرعامل" })
@IsOptional()
@IsString()
ceoNotes?: string;
}
export class QueryApprovalDto {
@ApiPropertyOptional()
@IsOptional()
department?: string;
@ApiPropertyOptional()
@IsOptional()
category?: string;
@ApiPropertyOptional()
@IsOptional()
status?: string;
@ApiPropertyOptional()
@IsOptional()
page?: number;
@ApiPropertyOptional()
@IsOptional()
limit?: number;
}
+5
View File
@@ -5,9 +5,12 @@ import {
IsEmail, IsEmail,
MinLength, MinLength,
IsNumber, IsNumber,
IsIn,
} from "class-validator"; } from "class-validator";
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger"; import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { ALLOWED_USER_ROLES } from "../user-role-policy";
export class CreateUserDto { export class CreateUserDto {
@ApiProperty({ description: "نام کاربر", example: "علی" }) @ApiProperty({ description: "نام کاربر", example: "علی" })
@IsNotEmpty({ message: "نام الزامی است" }) @IsNotEmpty({ message: "نام الزامی است" })
@@ -41,6 +44,7 @@ export class CreateUserDto {
@ApiPropertyOptional({ description: "نقش کاربر", example: "User_PetOwner" }) @ApiPropertyOptional({ description: "نقش کاربر", example: "User_PetOwner" })
@IsOptional() @IsOptional()
@IsString() @IsString()
@IsIn(ALLOWED_USER_ROLES)
role?: string; role?: string;
@ApiPropertyOptional({ description: "موجودی اولیه کیف پول", example: 0 }) @ApiPropertyOptional({ description: "موجودی اولیه کیف پول", example: 0 })
@@ -85,6 +89,7 @@ export class UpdateUserDto {
@ApiPropertyOptional({ description: "نقش کاربر", example: "User_PetOwner" }) @ApiPropertyOptional({ description: "نقش کاربر", example: "User_PetOwner" })
@IsOptional() @IsOptional()
@IsString() @IsString()
@IsIn(ALLOWED_USER_ROLES)
role?: string; role?: string;
@ApiPropertyOptional({ description: "موجودی کیف پول", example: 500000 }) @ApiPropertyOptional({ description: "موجودی کیف پول", example: 500000 })
+1 -1
View File
@@ -76,7 +76,7 @@ describe("MediaService", () => {
const validFile = { const validFile = {
originalname: "product-cover.webp", originalname: "product-cover.webp",
buffer: Buffer.from("dummy-image-bytes"), buffer: Buffer.from([0x52, 0x49, 0x46, 0x46, 0x00, 0x00, 0x00, 0x00, 0x57, 0x45, 0x42, 0x50, 0x56, 0x50, 0x38]),
mimetype: "image/webp", mimetype: "image/webp",
size: 5000, size: 5000,
} as any; } as any;
+22
View File
@@ -79,6 +79,28 @@ export class MediaService {
"پسوند فایل ارسالی مجاز نیست (فرمت SVG و فایل‌های اجرایی مسدود هستند).", "پسوند فایل ارسالی مجاز نیست (فرمت SVG و فایل‌های اجرایی مسدود هستند).",
); );
} }
// SEC-01: Magic number verification for uploaded binary content
const buf = file.buffer;
if (!buf || buf.length < 4) {
throw new BadRequestException("فایل نامعتبر یا آسیب‌دیده است.");
}
const isJpeg = buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff;
const isPng = buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47;
const isGif = buf[0] === 0x47 && buf[1] === 0x49 && buf[2] === 0x46; // GIF87a or GIF89a
const isPdf = buf[0] === 0x25 && buf[1] === 0x50 && buf[2] === 0x44 && buf[3] === 0x46; // %PDF
const isWebp =
buf.length >= 12 &&
buf[0] === 0x52 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x46 && // RIFF
buf[8] === 0x57 && buf[9] === 0x45 && buf[10] === 0x42 && buf[11] === 0x50; // WEBP
if (!isJpeg && !isPng && !isGif && !isPdf && !isWebp) {
throw new BadRequestException(
"محتوای باینری فایل با پسوند یا هدر ادعایی همخوانی ندارد (اعتبارسنجی امضای فایل رد شد).",
);
}
const filename = `${uniqueSuffix}${ext}`; const filename = `${uniqueSuffix}${ext}`;
const filePath = path.join(uploadDir, filename); const filePath = path.join(uploadDir, filename);
+27
View File
@@ -0,0 +1,27 @@
import { ForbiddenException } from "@nestjs/common";
export const ALLOWED_USER_ROLES = [
"User_PetOwner", "User_Vet", "User_Clinic", "User_PetShop",
"User_Wholesale", "User_B2B", "Customer", "Admin", "ADMIN", "SUPER_ADMIN",
];
export interface UserAdminActor {
id?: string;
role?: string;
isApiKey?: boolean;
}
// Match RolesGuard semantics; keep stored values unchanged.
export function isSuperAdminRole(role?: string): boolean {
const normalized = typeof role === "string" ? role.toLowerCase().replace(/[_-]/g, "") : "";
return normalized === "superadmin" || normalized === "adminsuper";
}
export function assertUserMutationAllowed(actor?: UserAdminActor, currentRole?: string, nextRole?: string): void {
const role = actor?.role?.toLowerCase().replace(/[_-]/g, "");
const isSuperAdmin = !!actor?.id && !actor.isApiKey && isSuperAdminRole(actor.role);
if ((!actor?.id && !actor?.isApiKey) || (role !== "admin" && !isSuperAdmin) ||
((isSuperAdminRole(currentRole) || isSuperAdminRole(nextRole)) && !isSuperAdmin)) {
throw new ForbiddenException("فقط مدیر ارشد مجاز به مدیریت حساب و نقش مدیر ارشد است");
}
}
+2
View File
@@ -1,3 +1,4 @@
import { TasksModule } from './common/services/tasks.module';
import { Module, NestModule, MiddlewareConsumer } from "@nestjs/common"; import { Module, NestModule, MiddlewareConsumer } from "@nestjs/common";
import { PrismaModule } from "./prisma/prisma.module"; import { PrismaModule } from "./prisma/prisma.module";
import { SupportChatModule } from './support-chat/support-chat.module'; import { SupportChatModule } from './support-chat/support-chat.module';
@@ -79,6 +80,7 @@ import { Request, Response, NextFunction } from "express";
B2BModule, B2BModule,
FaqModule, FaqModule,
MenuModule, MenuModule,
TasksModule,
], ],
controllers: [MetricsController], controllers: [MetricsController],
providers: [ providers: [
+15 -3
View File
@@ -14,6 +14,7 @@ import { SmsService } from "../common/services/sms.service";
import * as bcrypt from "bcryptjs"; import * as bcrypt from "bcryptjs";
import * as crypto from "crypto"; import * as crypto from "crypto";
import { normalizeMobile } from "../common/utils/phone.utils"; import { normalizeMobile } from "../common/utils/phone.utils";
import { assertPrincipalActive } from "./stage-test-principal";
import { getJwtRefreshSecret } from "./auth.constants"; import { getJwtRefreshSecret } from "./auth.constants";
export class RegisterInput { export class RegisterInput {
@@ -200,7 +201,8 @@ export class AuthService {
}); });
} }
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role }; assertPrincipalActive(user);
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role, ...(user.stageTestSession ? {stageTestSession:user.stageTestSession, stageTestGeneration:user.stageTestGeneration} : {}) };
const tokens = await this.generateTokens(payload); const tokens = await this.generateTokens(payload);
const { password: _p, ...safeUser } = user; const { password: _p, ...safeUser } = user;
@@ -257,7 +259,8 @@ export class AuthService {
}, },
}); });
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role }; assertPrincipalActive(user);
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role, ...(user.stageTestSession ? {stageTestSession:user.stageTestSession, stageTestGeneration:user.stageTestGeneration} : {}) };
const tokens = await this.generateTokens(payload); const tokens = await this.generateTokens(payload);
const { password: _p, ...safeUser } = user; const { password: _p, ...safeUser } = user;
@@ -300,7 +303,8 @@ export class AuthService {
}); });
} }
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role }; assertPrincipalActive(user);
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role, ...(user.stageTestSession ? {stageTestSession:user.stageTestSession, stageTestGeneration:user.stageTestGeneration} : {}) };
const tokens = await this.generateTokens(payload); const tokens = await this.generateTokens(payload);
const { password: _pw, ...safeUser } = user; const { password: _pw, ...safeUser } = user;
@@ -326,10 +330,12 @@ export class AuthService {
if (dbAdmin && dbAdmin.password && body.password) { if (dbAdmin && dbAdmin.password && body.password) {
const isMatch = await bcrypt.compare(body.password, dbAdmin.password); const isMatch = await bcrypt.compare(body.password, dbAdmin.password);
if (isMatch) { if (isMatch) {
assertPrincipalActive(dbAdmin);
const payload = { const payload = {
sub: dbAdmin.id, sub: dbAdmin.id,
email: dbAdmin.email, email: dbAdmin.email,
role: dbAdmin.role, role: dbAdmin.role,
...(dbAdmin.stageTestSession ? {stageTestSession:dbAdmin.stageTestSession, stageTestGeneration:dbAdmin.stageTestGeneration} : {}),
}; };
const tokens = await this.generateTokens(payload); const tokens = await this.generateTokens(payload);
const { password: _p, ...safeUser } = dbAdmin; const { password: _p, ...safeUser } = dbAdmin;
@@ -443,11 +449,14 @@ export class AuthService {
const user = await this.prisma.user.findUnique({ where: { id: userId } }); const user = await this.prisma.user.findUnique({ where: { id: userId } });
if (user) { if (user) {
assertPrincipalActive(user);
if (user.stageTestSession && (!user.stageTestGeneration || decoded.stageTestGeneration !== user.stageTestGeneration || decoded.stageTestSession !== user.stageTestSession)) throw new UnauthorizedException("Stage session revoked");
userPayload = { userPayload = {
sub: user.id, sub: user.id,
email: user.email, email: user.email,
phoneNumber: user.mobile, phoneNumber: user.mobile,
role: user.role, role: user.role,
...(user.stageTestSession ? {stageTestSession:user.stageTestSession, stageTestGeneration:user.stageTestGeneration} : {}),
}; };
const { password: _p, ...restUser } = user; const { password: _p, ...restUser } = user;
safeUser = restUser; safeUser = restUser;
@@ -487,12 +496,15 @@ export class AuthService {
email?: string; email?: string;
role?: string; role?: string;
mobile?: string; mobile?: string;
stageTestSession?: string | null;
stageTestGeneration?: string | null;
}) { }) {
const payload = { const payload = {
sub: user.id, sub: user.id,
email: user.email, email: user.email,
role: user.role, role: user.role,
phoneNumber: user.mobile, phoneNumber: user.mobile,
...(user.stageTestSession ? {stageTestSession:user.stageTestSession, stageTestGeneration:user.stageTestGeneration} : {}),
}; };
const tokens = await this.generateTokens(payload); const tokens = await this.generateTokens(payload);
return { return {
+18
View File
@@ -0,0 +1,18 @@
import { AdminService } from '../admin/admin.service';
import { STAGE_TEST_ID, STAGE_TEST_EMAIL, STAGE_TEST_MOBILE } from './stage-test-principal';
const sha='a'.repeat(40), generation='8311eb41-23b4-4aab-ade2-e97b90debc11';
const env={APP_ENV:'stage',CI:'true',STAGE_TEST_PRINCIPAL_ENABLED:'true',STAGE_TEST_APPROVAL:'owner-authorized-stage-editorial',STAGE_TEST_SHA:sha,STAGE_TEST_SESSION:'cleanup-session',STAGE_TEST_TTL_SECONDS:'600',STAGE_TEST_GENERATION:generation};
describe('durable cleanup ownership fence',()=>{
it('does not revoke a replacement generation',async()=>{
const update=jest.fn();
const db={user:{findUnique:async()=>({id:STAGE_TEST_ID,email:STAGE_TEST_EMAIL,mobile:STAGE_TEST_MOBILE,stageTestSession:env.STAGE_TEST_SESSION,stageTestGeneration:'replacement',authExpiresAt:new Date()}),update}};
await expect(new AdminService(db as any,undefined as any,undefined as any).cleanupStageTestPrincipal(env,sha)).rejects.toThrow('Refusing');
expect(update).not.toHaveBeenCalled();
});
it('confirms revocation before relational deletion failure',async()=>{
const events:string[]=[];
const db={user:{findUnique:async()=>({id:STAGE_TEST_ID,email:STAGE_TEST_EMAIL,mobile:STAGE_TEST_MOBILE,stageTestSession:env.STAGE_TEST_SESSION,stageTestGeneration:generation,authExpiresAt:new Date()}),update:async()=>events.push('revoke')},$transaction:async()=>{events.push('delete');throw Error('FK failure');}};
await expect((new AdminService(db as any,undefined as any,undefined as any).cleanupStageTestPrincipal as any)(env,sha,()=>events.push('handle-removed'))).rejects.toThrow('FK failure');
expect(events).toEqual(['revoke','handle-removed','delete']);
});
});
+10
View File
@@ -2,6 +2,7 @@ import { ExtractJwt, Strategy } from "passport-jwt";
import { PassportStrategy } from "@nestjs/passport"; import { PassportStrategy } from "@nestjs/passport";
import { Injectable, UnauthorizedException } from "@nestjs/common"; import { Injectable, UnauthorizedException } from "@nestjs/common";
import { UsersService } from "../users/users.service"; import { UsersService } from "../users/users.service";
import { assertPrincipalActive } from "./stage-test-principal";
import { getJwtSecret } from "./auth.constants"; import { getJwtSecret } from "./auth.constants";
import { RedisService } from "../redis/redis.service"; import { RedisService } from "../redis/redis.service";
@@ -12,6 +13,8 @@ export interface JwtPayload {
email?: string; email?: string;
role?: string; role?: string;
phoneNumber?: string; phoneNumber?: string;
stageTestSession?: string;
stageTestGeneration?: string;
} }
@Injectable() @Injectable()
@@ -59,6 +62,13 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
if (!user) { if (!user) {
throw new UnauthorizedException("کاربر یافت نشد"); throw new UnauthorizedException("کاربر یافت نشد");
} }
try { assertPrincipalActive(user); } catch { throw new UnauthorizedException("Principal expired"); }
if (user.stageTestSession) {
if (!user.stageTestGeneration || payload.stageTestGeneration !== user.stageTestGeneration || payload.stageTestSession !== user.stageTestSession) throw new UnauthorizedException("Stage session revoked");
const path = req.originalUrl?.split('?')[0] || '';
const allowed = req.method === 'GET' && /^\/api\/admin\/orchestration\/tasks(?:\/[a-f0-9-]+)?$/.test(path) || req.method === 'POST' && (/^\/api\/admin\/orchestration\/tasks$/.test(path) || /^\/api\/admin\/orchestration\/tasks\/[a-f0-9-]+\/(?:gates\/1\/decide|editorial-failure|editorial-completed-recovery)$/.test(path));
if (!allowed) throw new UnauthorizedException('Stage test scope denied');
}
return user; return user;
} }
} }
@@ -0,0 +1,44 @@
import { PrismaClient } from '@prisma/client';
import { JwtService } from '@nestjs/jwt';
import { AuthService } from './auth.service';
import { RedisService } from '../redis/redis.service';
import { STAGE_TEST_ID } from './stage-test-principal';
import { createServer, Server } from 'http';
import { execFile } from 'child_process';
import { promisify } from 'util';
import { readFileSync, writeFileSync, existsSync } from 'fs';
const enabled=process.env.STAGE_PRINCIPAL_DISPOSABLE_TEST==='true';
(enabled?describe:describe.skip)('actual internal CLI disposable lifecycle',()=>{
const sha='a'.repeat(40), generation='b411eb41-23b4-4aab-ade2-e97b90debc11', session='cli-integration-session';
const handle=`/app/private-stage-test/${session}.json`;
const db=new PrismaClient({log:[]}), redis=new RedisService(); let server:Server;
const env={...process.env,APP_ENV:'stage',CI:'true',STAGE_TEST_PRINCIPAL_ENABLED:'true',STAGE_TEST_APPROVAL:'owner-authorized-stage-editorial',STAGE_TEST_SHA:sha,STAGE_TEST_SESSION:session,STAGE_TEST_TTL_SECONDS:'600',STAGE_TEST_GENERATION:generation};
const cli=(action:string)=>promisify(execFile)(process.execPath,['-r','ts-node/register','src/auth/stage-test-principal.cli.ts',action],{env,timeout:90000});
beforeAll(async()=>{
if(!process.env.DATABASE_URL?.endsWith('/principal_disposable')) throw Error('Disposable database only');
writeFileSync('/app/STAGE_TEST_ARTIFACT_SHA',sha); redis.onModuleInit();
const auth=new AuthService(db as any,new JwtService({secret:process.env.JWT_SECRET,signOptions:{expiresIn:'2h'}}),redis,undefined as any);
server=createServer(async(req,res)=>{
try {let body='';for await(const chunk of req) body+=chunk;
if(req.url!=='/api/auth/admin-login') {res.writeHead(404).end();return;}
const login=await auth.adminLogin(JSON.parse(body));res.setHeader('content-type','application/json');res.end(JSON.stringify(login));
} catch {res.writeHead(401).end();}
});
await new Promise<void>(r=>server.listen(3000,'127.0.0.1',r));
},120000);
afterAll(async()=>{await new Promise<void>(r=>server.close(()=>r()));redis.onModuleDestroy();await db.$disconnect();});
it('logs in using persisted credentials and removes handle on confirmed revocation despite failed delete',async()=>{
await cli('open'); expect(existsSync(handle)).toBe(true);
const credential=JSON.parse(readFileSync(handle,'utf8'));expect(credential.accessToken).toBeTruthy();
expect((await db.user.findUnique({where:{id:STAGE_TEST_ID}}))?.stageTestGeneration).toBe(generation);
await db.$executeRawUnsafe(`CREATE FUNCTION deny_principal_delete() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'test FK deletion failure'; END $$`);
await db.$executeRawUnsafe(`CREATE TRIGGER deny_principal_delete BEFORE DELETE ON users FOR EACH ROW EXECUTE FUNCTION deny_principal_delete()`);
try {
await expect(cli('close')).rejects.toThrow();
expect(existsSync(handle)).toBe(false);
const revoked=await db.user.findUnique({where:{id:STAGE_TEST_ID}});
expect(revoked?.authExpiresAt?.getTime()).toBe(0);expect(revoked?.password).toBe('');
} finally {await db.$executeRawUnsafe(`DROP TRIGGER deny_principal_delete ON users`);await db.$executeRawUnsafe(`DROP FUNCTION deny_principal_delete()`);}
await cli('close');expect(await db.user.findUnique({where:{id:STAGE_TEST_ID}})).toBeNull();
},240000);
});
@@ -0,0 +1,68 @@
import 'reflect-metadata';
import { PrismaClient } from '@prisma/client';
import { randomBytes } from 'crypto';
import { mkdirSync, openSync, writeFileSync, closeSync, readFileSync, statSync, unlinkSync, constants } from 'fs';
import { AdminService } from '../admin/admin.service';
import { authorizeStageSession, STAGE_TEST_EMAIL } from './stage-test-principal';
// CI-only internal seed command; deliberately not registered in AppModule.
async function main() {
const sha = readFileSync('/app/STAGE_TEST_ARTIFACT_SHA', 'utf8').trim();
const grant = authorizeStageSession(process.env, sha);
const action = process.argv[2];
if (action === 'cleanup-capability') { process.stdout.write('stage-generation-cleanup-v1'); return; }
if (!['open','close'].includes(action)) throw new Error('Unknown command');
const root = '/app/private-stage-test';
mkdirSync(root,{recursive:true,mode:0o700});
const st = statSync(root);
if (st.uid !== process.getuid!() || (st.mode & 0o777) !== 0o700) throw new Error('Unsafe private directory');
if (!/^[a-f0-9-]{36}$/.test(process.env.STAGE_TEST_GENERATION || '')) throw new Error('Generation required');
const handle = `${root}/${grant.session}.json`;
const removeHandle = () => { try {unlinkSync(handle);} catch(e:any) {if(e.code !== 'ENOENT') throw e;} };
const audit = (event:string) => {
const fd = openSync(`${root}/audit.jsonl`, constants.O_WRONLY|constants.O_CREAT|constants.O_APPEND|constants.O_NOFOLLOW,0o600);
try { writeFileSync(fd,JSON.stringify({event,sha,session:grant.session,at:new Date().toISOString()})+'\n'); } finally {closeSync(fd);}
};
const db = new PrismaClient({log:[]});
const service = new AdminService(db as any,undefined as any,undefined as any);
try {
audit(`${action}-requested`);
if(action === 'close') {
await service.cleanupStageTestPrincipal(process.env,sha,removeHandle);
audit('revoked-and-deleted');
return;
}
let fd:number;
let password:string;
try {
fd = openSync(handle,constants.O_WRONLY|constants.O_CREAT|constants.O_EXCL|constants.O_NOFOLLOW,0o600);
password = randomBytes(48).toString('base64url');
try {writeFileSync(fd,JSON.stringify({password}));} finally {closeSync(fd);}
} catch(e:any) {
if(e.code !== 'EEXIST') throw e;
fd = openSync(handle,constants.O_RDONLY|constants.O_NOFOLLOW);
try {
const {fstatSync} = await import('fs'); const s=fstatSync(fd);
if(!s.isFile() || s.uid !== process.getuid!() || (s.mode & 0o777) !== 0o600) throw new Error('Unsafe handle');
password=JSON.parse(readFileSync(fd,'utf8')).password;
} finally {closeSync(fd);}
}
const user=await service.provisionStageTestPrincipal(process.env,sha,password);
// Use deployed persisted-account HTTP login, never sign tokens here.
const response=await fetch('http://127.0.0.1:3000/api/auth/admin-login',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({email:STAGE_TEST_EMAIL,password}),signal:AbortSignal.timeout(15000)});
if(!response.ok) throw new Error('Persisted login failed');
const result:any=await response.json();
if(result.data?.user?.id !== user.id || result.data?.user?.role !== 'SUPER_ADMIN' || !result.data?.accessToken) throw new Error('Persisted login mismatch');
fd=openSync(handle,constants.O_WRONLY|constants.O_TRUNC|constants.O_NOFOLLOW);
try {writeFileSync(fd,JSON.stringify({password,...result.data,expiresAt:user.authExpiresAt}));} finally {closeSync(fd);}
audit('created-and-login-verified');
// Only an opaque local path is public. Never upload this file as a CI artifact.
process.stdout.write(`Stage credential handle: ${handle}\n`);
} catch {
audit('failed');
// Leave only a revoked account if relational cleanup fails.
await service.cleanupStageTestPrincipal(process.env,sha,removeHandle).catch(()=>undefined);
throw new Error('Stage test principal operation failed; inspect private audit');
} finally {await db.$disconnect();}
}
main().catch(()=>{process.stderr.write('Stage test principal denied or failed\n');process.exitCode=1;});
@@ -0,0 +1,58 @@
import { PrismaClient } from '@prisma/client';
import { randomBytes } from 'crypto';
import { JwtService } from '@nestjs/jwt';
import { AdminService } from '../admin/admin.service';
import { AuthService } from './auth.service';
import { UsersService } from '../users/users.service';
import { JwtStrategy } from './jwt.strategy';
import { RedisService } from '../redis/redis.service';
import { STAGE_TEST_ID, STAGE_TEST_EMAIL, STAGE_TEST_MOBILE } from './stage-test-principal';
const enabled=process.env.STAGE_PRINCIPAL_DISPOSABLE_TEST === 'true';
(enabled ? describe : describe.skip)('disposable persisted Stage principal lifecycle',()=>{
const sha='a'.repeat(40), grant={APP_ENV:'stage',CI:'true',STAGE_TEST_PRINCIPAL_ENABLED:'true',STAGE_TEST_APPROVAL:'owner-authorized-stage-editorial',STAGE_TEST_SHA:sha,STAGE_TEST_SESSION:'integration-session',STAGE_TEST_TTL_SECONDS:'600'};
const db=new PrismaClient({log:[]}); const redis=new RedisService();
let admin:AdminService,auth:AuthService,strategy:JwtStrategy,password:string;
beforeAll(async()=>{
// Deliberately require a disposable database name; never point this suite at Stage.
if(!process.env.DATABASE_URL?.endsWith('/principal_disposable')) throw new Error('Disposable database required');
redis.onModuleInit(); password=randomBytes(48).toString('base64url');
admin=new AdminService(db as any,redis,undefined as any);
auth=new AuthService(db as any,new JwtService({secret:process.env.JWT_SECRET,signOptions:{expiresIn:'2h'}}),redis,undefined as any);
strategy=new JwtStrategy(new UsersService(db as any),redis);
});
afterAll(async()=>{await admin.cleanupStageTestPrincipal(grant,sha); await db.$disconnect();redis.onModuleDestroy();});
it('rejects unowned collision and never changes it',async()=>{
const collision=await db.user.create({data:{firstName:'Unowned',lastName:'Account',email:STAGE_TEST_EMAIL,mobile:STAGE_TEST_MOBILE}});
try {
await expect(admin.provisionStageTestPrincipal(grant,sha,password)).rejects.toThrow('Refusing');
expect((await db.user.findUnique({where:{id:collision.id}}))?.role).toBe('User_PetOwner');
} finally {await db.user.delete({where:{id:collision.id}});}
});
it('creates through account service, logs in, verifies signed tokens, never renews retry TTL',async()=>{
const u=await admin.provisionStageTestPrincipal(grant,sha,password);
expect(u.id).toBe(STAGE_TEST_ID); expect(u.role).toBe('SUPER_ADMIN'); expect(u.password).not.toBe(password);
const retry=await admin.provisionStageTestPrincipal(grant,sha,password); expect(retry.authExpiresAt).toEqual(u.authExpiresAt);
await expect(admin.provisionStageTestPrincipal({...grant,STAGE_TEST_SESSION:'different-session'},sha,password)).rejects.toThrow('Refusing');
const login=await auth.adminLogin({email:STAGE_TEST_EMAIL,password});
const jwt=new JwtService({secret:process.env.JWT_SECRET});
const payload=jwt.verify(login.data.accessToken); expect(payload.sub).toBe(u.id);expect(payload.role).toBe('SUPER_ADMIN');
const req:any={method:'GET',originalUrl:'/api/admin/orchestration/tasks',headers:{authorization:`Bearer ${login.data.accessToken}`}};
expect((await strategy.validate(req,payload)).id).toBe(u.id);
await expect(strategy.validate({...req,originalUrl:'/api/admin/users'},payload)).rejects.toThrow('scope denied');
await expect(strategy.validate({...req,method:'POST',originalUrl:'/api/admin/orchestration/tasks/abcd/gates/2/decide'},payload)).rejects.toThrow('scope denied');
// Fixture time travel: persisted expiry is enforced independently of the long-lived signed token.
await db.user.update({where:{id:u.id},data:{authExpiresAt:new Date(0)}});
await expect(strategy.validate(req,payload)).rejects.toThrow();
await expect(auth.adminLogin({email:STAGE_TEST_EMAIL,password})).rejects.toThrow();
await expect(auth.refreshToken(login.data.refreshToken)).rejects.toThrow();
await admin.cleanupStageTestPrincipal(grant,sha);
await expect(strategy.validate(req,payload)).rejects.toThrow();
expect(await db.user.findUnique({where:{id:u.id}})).toBeNull();
const replacement=await admin.provisionStageTestPrincipal(grant,sha,password);
expect(replacement.stageTestGeneration).not.toBe(u.stageTestGeneration);
await expect(strategy.validate(req,payload)).rejects.toThrow();
await expect(auth.refreshToken(login.data.refreshToken)).rejects.toThrow();
const fresh=await auth.adminLogin({email:STAGE_TEST_EMAIL,password});
expect((await strategy.validate(req,jwt.verify(fresh.data.accessToken))).id).toBe(u.id);
});
});
@@ -0,0 +1,13 @@
import { assertPrincipalActive, authorizeStageSession } from './stage-test-principal';
const sha = 'a'.repeat(40);
const valid = { APP_ENV: 'stage', STAGE_TEST_PRINCIPAL_ENABLED: 'true', CI: 'true', STAGE_TEST_APPROVAL: 'owner-authorized-stage-editorial', STAGE_TEST_SHA: sha, STAGE_TEST_SESSION: 'editorial-20261024', STAGE_TEST_TTL_SECONDS: '600' };
describe('Stage CI authority', () => {
it('denies by default and in Production despite opt in', () => {
expect(() => authorizeStageSession({}, sha)).toThrow();
expect(() => authorizeStageSession({...valid, APP_ENV:'production'}, sha)).toThrow();
});
it('requires immutable matching SHA and bounded explicit authorization', () => {
expect(authorizeStageSession(valid, sha).ttl).toBe(600);
for(const patch of [{STAGE_TEST_SHA:'main'}, {STAGE_TEST_SHA:'b'.repeat(40)}, {STAGE_TEST_TTL_SECONDS:'3601'}, {STAGE_TEST_TTL_SECONDS:'0'}, {STAGE_TEST_APPROVAL:''}, {CI:''}]) expect(() => authorizeStageSession({...valid,...patch},sha)).toThrow();
});
});
+13
View File
@@ -0,0 +1,13 @@
// Internal seed authority only. No controller, JWT actor, or owner impersonation.
export const STAGE_TEST_ID = 'e876e7a0-738f-4e59-b6db-e270512ababc';
export const STAGE_TEST_EMAIL = 'stage-editorial-reviewer@ci.canina.invalid';
export const STAGE_TEST_MOBILE = '09999999071';
export function authorizeStageSession(env: NodeJS.ProcessEnv, artifactSha: string) {
if (env.APP_ENV !== 'stage' || env.STAGE_TEST_PRINCIPAL_ENABLED !== 'true' || env.CI !== 'true' || env.STAGE_TEST_APPROVAL !== 'owner-authorized-stage-editorial' || !/^[a-f0-9]{40}$/.test(artifactSha) || env.STAGE_TEST_SHA !== artifactSha || !/^[a-z0-9-]{8,64}$/.test(env.STAGE_TEST_SESSION || '')) throw new Error('Stage CI authority denied');
const ttl = Number(env.STAGE_TEST_TTL_SECONDS);
if (!Number.isInteger(ttl) || ttl < 60 || ttl > 3600) throw new Error('Bounded TTL required');
return {ttl, session:env.STAGE_TEST_SESSION!, sha:artifactSha};
}
export function assertPrincipalActive(user: { authExpiresAt?: Date | null }, now = Date.now()) {
if (user.authExpiresAt && user.authExpiresAt.getTime() <= now) throw new Error('Principal expired');
}
@@ -0,0 +1,32 @@
import { JwtService } from '@nestjs/jwt';
import { JwtStrategy } from './jwt.strategy';
import { AuthService } from './auth.service';
describe('Stage credentials remain fenced to their creation session', () => {
const id='e876e7a0-738f-4e59-b6db-e270512ababc';
const current={id, role:'SUPER_ADMIN', stageTestSession:'new-session', stageTestGeneration:'fresh-generation', authExpiresAt:new Date(Date.now()+600000)};
const redis:any={get:jest.fn(async()=> '1'),del:jest.fn(),set:jest.fn()};
beforeAll(()=> {process.env.JWT_SECRET='disposable-only-test-secret-at-least-32-characters';process.env.JWT_REFRESH_SECRET='disposable-only-refresh-secret-at-least-32-characters';});
it('rejects an old-session access token after fixed account ID is recreated',async()=>{
const strategy=new JwtStrategy({findById:async()=>current} as any,{get:async()=>null} as any);
const req:any={method:'GET',originalUrl:'/api/admin/orchestration/tasks',headers:{}};
await expect(strategy.validate(req,{sub:id,stageTestSession:'old-session'} as any)).rejects.toThrow();
await expect(strategy.validate(req,{sub:id})).rejects.toThrow();
await expect(strategy.validate(req,{sub:id,stageTestSession:'new-session',stageTestGeneration:'old-generation'} as any)).rejects.toThrow();
await expect(strategy.validate(req,{sub:id,stageTestSession:'new-session',stageTestGeneration:'fresh-generation'} as any)).resolves.toMatchObject({id});
});
it('rejects an old-session refresh token even while its Redis entry remains active',async()=>{
const jwt=new JwtService({secret:process.env.JWT_SECRET});
const auth=new AuthService({user:{findUnique:async()=>current}} as any,jwt,redis,undefined as any);
const token=jwt.sign({sub:id,jti:'old-refresh',role:'SUPER_ADMIN',stageTestSession:'old-session'},{secret:process.env.JWT_REFRESH_SECRET});
await expect(auth.refreshToken(token)).rejects.toThrow();
});
it('includes session fencing in newly issued credentials',async()=>{
const jwt=new JwtService({secret:process.env.JWT_SECRET});
const auth=new AuthService({} as any,jwt,redis,undefined as any);
const result=await auth.refresh(current);
expect(jwt.verify(result.data.accessToken).stageTestGeneration).toBe('fresh-generation');
expect(jwt.verify(result.data.accessToken).stageTestSession).toBe('new-session');
expect(jwt.verify(result.data.refreshToken,{secret:process.env.JWT_REFRESH_SECRET}).stageTestSession).toBe('new-session');
});
});
+20 -1
View File
@@ -50,7 +50,8 @@ describe("BlogsService", () => {
expect(result.data).toEqual(blogs); expect(result.data).toEqual(blogs);
expect(result.meta.total).toBe(1); expect(result.meta.total).toBe(1);
const query = mockPrisma.blog.findMany.mock.calls[0][0]; const query = mockPrisma.blog.findMany.mock.calls[0][0];
expect(query.include.author).toBeUndefined(); expect(query.include.author).toEqual({ select: { id: true, firstName: true, lastName: true } });
expect(query.orderBy).toEqual([{ publishedAt: "desc" }, { id: "asc" }]);
}); });
it("should filter by categorySlug and search term", async () => { it("should filter by categorySlug and search term", async () => {
@@ -69,7 +70,19 @@ describe("BlogsService", () => {
}); });
}); });
it("selects the minimal public author identity for list results", async () => {
mockPrisma.blog.findMany.mockResolvedValue([]); mockPrisma.blog.count.mockResolvedValue(0);
await service.findAll({});
expect(mockPrisma.blog.findMany.mock.calls[0][0].include.author).toEqual({ select: { id: true, firstName: true, lastName: true } });
});
describe("findHomepage", () => { describe("findHomepage", () => {
it("selects the minimal public author identity for homepage results", async () => {
mockPrisma.blog.findMany.mockResolvedValueOnce([]).mockResolvedValueOnce([]);
await service.findHomepage();
for (const call of mockPrisma.blog.findMany.mock.calls.slice(0, 2)) expect(call[0].include.author).toEqual({ select: { id: true, firstName: true, lastName: true } });
});
it("should return selected blogs if showOnHome posts exist", async () => { it("should return selected blogs if showOnHome posts exist", async () => {
const selected = [{ id: "b1", title: "Hero Blog", showOnHome: true }]; const selected = [{ id: "b1", title: "Hero Blog", showOnHome: true }];
mockPrisma.blog.findMany.mockResolvedValueOnce(selected); mockPrisma.blog.findMany.mockResolvedValueOnce(selected);
@@ -92,6 +105,12 @@ describe("BlogsService", () => {
}); });
describe("findOneBySlug", () => { describe("findOneBySlug", () => {
it("selects the minimal public author identity for detail results", async () => {
mockPrisma.blog.findFirst.mockResolvedValue(null);
await expect(service.findOneBySlug("missing")).rejects.toThrow(NotFoundException);
expect(mockPrisma.blog.findFirst.mock.calls[0][0].include.author).toEqual({ select: { id: true, firstName: true, lastName: true } });
});
it("should throw NotFoundException if slug is empty or blog not found", async () => { it("should throw NotFoundException if slug is empty or blog not found", async () => {
mockPrisma.blog.findFirst.mockResolvedValue(null); mockPrisma.blog.findFirst.mockResolvedValue(null);
await expect(service.findOneBySlug("unknown-slug")).rejects.toThrow( await expect(service.findOneBySlug("unknown-slug")).rejects.toThrow(
+65 -23
View File
@@ -2,8 +2,15 @@ import { Injectable, NotFoundException } from "@nestjs/common";
import { Prisma } from "@prisma/client"; import { Prisma } from "@prisma/client";
import { PrismaService } from "../prisma/prisma.service"; import { PrismaService } from "../prisma/prisma.service";
import { PaginationDto } from "../common/dto/pagination.dto"; import { PaginationDto } from "../common/dto/pagination.dto";
import {
createPaginationMeta,
extractSearchTokens,
normalizeSearchText,
calculateRelevanceScore,
} from "../common/utils/search.utils";
export interface BlogFilterDto extends PaginationDto { export interface BlogFilterDto extends PaginationDto {
categoryId?: string;
categorySlug?: string; categorySlug?: string;
tagSlug?: string; tagSlug?: string;
featured?: boolean | string; featured?: boolean | string;
@@ -20,6 +27,7 @@ export class BlogsService {
limit = 10, limit = 10,
sortBy = "publishedAt", sortBy = "publishedAt",
sortOrder = "desc", sortOrder = "desc",
categoryId,
categorySlug, categorySlug,
tagSlug, tagSlug,
featured, featured,
@@ -32,20 +40,23 @@ export class BlogsService {
OR: [{ publishedAt: null }, { publishedAt: { lte: now } }], OR: [{ publishedAt: null }, { publishedAt: { lte: now } }],
}; };
if (search) { const tokens = extractSearchTokens(search);
if (tokens.length > 0) {
whereClause.AND = [ whereClause.AND = [
{ {
OR: [ OR: tokens.flatMap((token) => [
{ title: { contains: search, mode: "insensitive" } }, { title: { contains: token, mode: "insensitive" } },
{ excerpt: { contains: search, mode: "insensitive" } }, { excerpt: { contains: token, mode: "insensitive" } },
{ content: { contains: search, mode: "insensitive" } }, { keywords: { contains: token, mode: "insensitive" } },
{ keywords: { contains: search, mode: "insensitive" } }, { tags: { some: { name: { contains: token, mode: "insensitive" } } } },
], ]),
}, },
]; ];
} }
if (categorySlug) { if (categoryId && categoryId !== "ALL") {
whereClause.categoryId = categoryId;
} else if (categorySlug && categorySlug !== "all") {
whereClause.category = { slug: categorySlug }; whereClause.category = { slug: categorySlug };
} }
@@ -57,17 +68,25 @@ export class BlogsService {
whereClause.featured = String(featured) === "true"; whereClause.featured = String(featured) === "true";
} }
const skip = (Number(page) - 1) * Number(limit); const safePage = Math.max(1, Number(page) || 1);
const safeLimit = Math.max(1, Number(limit) || 10);
const skip = (safePage - 1) * safeLimit;
const [data, total] = await Promise.all([ const [rawBlogs, total] = await Promise.all([
this.prisma.blog.findMany({ this.prisma.blog.findMany({
where: whereClause, where: whereClause,
skip, skip: tokens.length > 0 ? undefined : skip,
take: Number(limit), take: tokens.length > 0 ? 100 : safeLimit,
orderBy: { orderBy: [
[sortBy === "createdAt" ? "createdAt" : "publishedAt"]: sortOrder, {
}, [sortBy === "createdAt" ? "createdAt" : "publishedAt"]: sortOrder,
},
{ id: "asc" },
],
include: { include: {
author: {
select: { id: true, firstName: true, lastName: true },
},
category: { category: {
select: { id: true, name: true, slug: true }, select: { id: true, name: true, slug: true },
}, },
@@ -82,14 +101,30 @@ export class BlogsService {
this.prisma.blog.count({ where: whereClause }), this.prisma.blog.count({ where: whereClause }),
]); ]);
let data = rawBlogs;
if (tokens.length > 0 && search) {
data = [...rawBlogs]
.map((b) => ({
blog: b,
score: calculateRelevanceScore(
{
title: b.title,
slug: b.slug,
shortDescription: b.excerpt,
tags: b.tags,
},
search,
tokens,
),
}))
.sort((a, b) => b.score - a.score)
.map((item) => item.blog)
.slice(skip, skip + safeLimit);
}
return { return {
data, data,
meta: { meta: createPaginationMeta(total, safePage, safeLimit),
total,
page: Number(page),
lastPage: Math.ceil(total / Number(limit)) || 1,
limit: Number(limit),
},
}; };
} }
@@ -105,8 +140,11 @@ export class BlogsService {
const selectedBlogs = await this.prisma.blog.findMany({ const selectedBlogs = await this.prisma.blog.findMany({
where: { ...baseWhere, showOnHome: true }, where: { ...baseWhere, showOnHome: true },
take: 4, take: 4,
orderBy: { publishedAt: "desc" }, orderBy: [{ publishedAt: "desc" }, { id: "asc" }],
include: { include: {
author: {
select: { id: true, firstName: true, lastName: true },
},
category: { select: { id: true, name: true, slug: true } }, category: { select: { id: true, name: true, slug: true } },
tags: { select: { id: true, name: true, slug: true } }, tags: { select: { id: true, name: true, slug: true } },
_count: { select: { comments: { where: { status: "APPROVED" } } } }, _count: { select: { comments: { where: { status: "APPROVED" } } } },
@@ -121,8 +159,11 @@ export class BlogsService {
const newestBlogs = await this.prisma.blog.findMany({ const newestBlogs = await this.prisma.blog.findMany({
where: baseWhere, where: baseWhere,
take: 4, take: 4,
orderBy: { publishedAt: "desc" }, orderBy: [{ publishedAt: "desc" }, { id: "asc" }],
include: { include: {
author: {
select: { id: true, firstName: true, lastName: true },
},
category: { select: { id: true, name: true, slug: true } }, category: { select: { id: true, name: true, slug: true } },
tags: { select: { id: true, name: true, slug: true } }, tags: { select: { id: true, name: true, slug: true } },
_count: { select: { comments: { where: { status: "APPROVED" } } } }, _count: { select: { comments: { where: { status: "APPROVED" } } } },
@@ -158,6 +199,7 @@ export class BlogsService {
], ],
}, },
include: { include: {
author: { select: { id: true, firstName: true, lastName: true } },
category: { category: {
select: { id: true, name: true, slug: true }, select: { id: true, name: true, slug: true },
}, },
@@ -0,0 +1,61 @@
import { CallHandler, ExecutionContext } from "@nestjs/common";
import { of, lastValueFrom } from "rxjs";
import { AdminRevalidationInterceptor } from "./admin-revalidation.interceptor";
import { RevalidationService } from "./revalidation.service";
describe("AdminRevalidationInterceptor", () => {
const revalidation = { revalidate: jest.fn().mockResolvedValue(true) } as unknown as RevalidationService;
const interceptor = new AdminRevalidationInterceptor(revalidation);
const next = { handle: () => of({ ok: true }) } as CallHandler;
beforeEach(() => jest.clearAllMocks());
function context(method: string, url: string): ExecutionContext {
return { switchToHttp: () => ({ getRequest: () => ({ method, originalUrl: url }) }) } as unknown as ExecutionContext;
}
it("invalidates blog list and detail after an admin blog mutation", async () => {
await lastValueFrom(interceptor.intercept(context("PUT", "/api/admin/blogs/blog-1"), next));
expect(revalidation.revalidate).toHaveBeenCalledWith(
expect.arrayContaining(["blogs", "blog-categories", "blog-tags", "home-data"]),
expect.arrayContaining(["/", "/blog"]),
);
});
it.each([
["/api/admin/products/p1", "products"],
["/api/admin/categories/c1", "categories"],
["/api/admin/wiki/glucosamine", "wiki"],
["/api/admin/settings", "settings"],
["/api/admin/cms/hero-banners/b1", "banners"],
["/api/admin/cms/vet-testimonials/t1", "testimonials"],
["/api/admin/reviews/r1", "products"],
["/api/admin/media/m1", "products"],
])("maps %s mutations to %s cache invalidation", async (url, expectedTag) => {
await lastValueFrom(interceptor.intercept(context("DELETE", url), next));
expect(revalidation.revalidate).toHaveBeenCalledWith(expect.arrayContaining([expectedTag]), expect.any(Array));
});
it("does not invalidate cache for reads or internal-only admin CRUD", async () => {
await lastValueFrom(interceptor.intercept(context("GET", "/api/admin/blogs"), next));
await lastValueFrom(interceptor.intercept(context("PUT", "/api/admin/users/u1"), next));
expect(revalidation.revalidate).not.toHaveBeenCalled();
});
it.each([
["/api/banners/banner-1", "banners"],
["/api/menu/menu-1", "menu"],
["/api/videos/video-1", "videos"],
["/api/testimonials/testimonial-1", "testimonials"],
["/api/faq/faq-1", "faq"],
["/api/ingredients/ingredient-1", "ingredients"],
["/api/doctors/doctor-1", "doctors"],
["/api/settings/seo", "seo-config"],
["/api/settings/ui-texts/HERO_TITLE", "ui-texts"],
["/api/contact/info", "settings"],
["/api/smart-advisor/rules/rule-1", "smart-advisor"],
])("maps storefront mutation %s to %s cache invalidation", async (url, expectedTag) => {
await lastValueFrom(interceptor.intercept(context("PATCH", url), next));
expect(revalidation.revalidate).toHaveBeenCalledWith(expect.arrayContaining([expectedTag]), expect.any(Array));
});
});
@@ -0,0 +1,48 @@
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from "@nestjs/common";
import { Observable, tap } from "rxjs";
import { RevalidationService } from "./revalidation.service";
type Target = { tags: string[]; paths: string[] };
const TARGETS: Array<{ pattern: RegExp; target: Target }> = [
{ pattern: /^\/api\/banners(?:\/|$)/, target: { tags: ["banners", "home-data"], paths: ["/"] } },
{ pattern: /^\/api\/menu(?:\/|$)/, target: { tags: ["menu", "settings"], paths: ["/"] } },
{ pattern: /^\/api\/videos(?:\/|$)/, target: { tags: ["videos", "home-data"], paths: ["/", "/videos"] } },
{ pattern: /^\/api\/testimonials(?:\/|$)/, target: { tags: ["testimonials", "home-data"], paths: ["/"] } },
{ pattern: /^\/api\/faq(?:\/|$)/, target: { tags: ["faq"], paths: ["/faq"] } },
{ pattern: /^\/api\/ingredients(?:\/|$)/, target: { tags: ["ingredients", "products", "wiki"], paths: ["/shop", "/wiki"] } },
{ pattern: /^\/api\/doctors(?:\/|$)/, target: { tags: ["doctors", "settings"], paths: ["/contact"] } },
{ pattern: /^\/api\/settings\/seo(?:\/|$)/, target: { tags: ["seo-config", "settings"], paths: ["/", "/sitemap.xml"] } },
{ pattern: /^\/api\/settings\/(?:ui-texts|system|financial)(?:\/|$)/, target: { tags: ["ui-texts", "settings", "home-data"], paths: ["/"] } },
{ pattern: /^\/api\/contact\/info(?:\/|$)/, target: { tags: ["settings"], paths: ["/contact", "/"] } },
{ pattern: /^\/api\/smart-advisor\/rules(?:\/|$)/, target: { tags: ["smart-advisor", "products"], paths: ["/smart-advisor"] } },
{ pattern: /^\/api\/admin\/blogs(?:\/|$)/, target: { tags: ["blogs", "blog-categories", "blog-tags", "home-data"], paths: ["/", "/blog", "/sitemap.xml"] } },
{ pattern: /^\/api\/admin\/categories(?:\/|$)/, target: { tags: ["products", "categories", "home-data"], paths: ["/", "/shop", "/sitemap.xml"] } },
{ pattern: /^\/api\/admin\/wiki(?:\/|$)/, target: { tags: ["wiki", "scientific-terms"], paths: ["/wiki", "/sitemap.xml"] } },
{ pattern: /^\/api\/admin\/(?:settings|pricing)(?:\/|$)/, target: { tags: ["settings", "ui-texts", "seo-config", "products", "home-data"], paths: ["/", "/shop"] } },
{ pattern: /^\/api\/admin\/cms\/hero-banners(?:\/|$)/, target: { tags: ["banners", "home-data"], paths: ["/"] } },
{ pattern: /^\/api\/admin\/cms\/vet-testimonials(?:\/|$)/, target: { tags: ["testimonials", "home-data"], paths: ["/"] } },
{ pattern: /^\/api\/admin\/reviews(?:\/|$)/, target: { tags: ["products", "home-data"], paths: ["/", "/shop"] } },
{ pattern: /^\/api\/admin\/media(?:\/|$)/, target: { tags: ["products", "blogs", "wiki", "home-data"], paths: ["/", "/shop", "/blog", "/wiki"] } },
{ pattern: /^\/api\/admin\/products(?:\/|$)/, target: { tags: ["products", "home-data"], paths: ["/", "/shop", "/sitemap.xml"] } },
];
@Injectable()
export class AdminRevalidationInterceptor implements NestInterceptor {
constructor(private readonly revalidation: RevalidationService) {}
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
const request = context.switchToHttp().getRequest<{ method?: string; originalUrl?: string; url?: string }>();
const method = (request.method || "GET").toUpperCase();
const url = (request.originalUrl || request.url || "").split("?")[0];
const target = method === "GET" || method === "HEAD" || method === "OPTIONS"
? undefined
: TARGETS.find((entry) => entry.pattern.test(url))?.target;
return next.handle().pipe(
tap(() => {
if (target) void this.revalidation.revalidate(target.tags, target.paths);
}),
);
}
}
@@ -1,9 +1,11 @@
import { Global, Module } from "@nestjs/common"; import { Global, Module } from "@nestjs/common";
import { APP_INTERCEPTOR } from "@nestjs/core";
import { AdminRevalidationInterceptor } from "./admin-revalidation.interceptor";
import { RevalidationService } from "./revalidation.service"; import { RevalidationService } from "./revalidation.service";
@Global() @Global()
@Module({ @Module({
providers: [RevalidationService], providers: [RevalidationService, { provide: APP_INTERCEPTOR, useClass: AdminRevalidationInterceptor }],
exports: [RevalidationService], exports: [RevalidationService],
}) })
export class RevalidationModule {} export class RevalidationModule {}
@@ -26,6 +26,16 @@ describe("RevalidationService", () => {
expect(service).toBeDefined(); expect(service).toBeDefined();
}); });
it("uses the Next server rather than the nginx API proxy as production fallback", async () => {
delete process.env.FRONTEND_INTERNAL_URL;
delete process.env.FRONTEND_URL;
delete process.env.NEXT_PUBLIC_SITE_URL;
process.env.NODE_ENV = "production";
const fetchSpy = jest.spyOn(global, "fetch").mockResolvedValue({ ok: true } as Response);
await service.revalidate(["blogs"], ["/blog"]);
expect(fetchSpy).toHaveBeenCalledWith("http://frontend_prod:3000/api/revalidate", expect.anything());
});
describe("revalidateTag", () => { describe("revalidateTag", () => {
it("should send POST request with tag and secret header and return true on 200", async () => { it("should send POST request with tag and secret header and return true on 200", async () => {
const mockFetch = jest.spyOn(global, "fetch" as any).mockResolvedValue({ const mockFetch = jest.spyOn(global, "fetch" as any).mockResolvedValue({
@@ -110,4 +120,64 @@ describe("RevalidationService", () => {
expect(pathSpy).toHaveBeenCalledWith("/shop/ART-100"); expect(pathSpy).toHaveBeenCalledWith("/shop/ART-100");
}); });
}); });
describe("revalidateBlog", () => {
it("should trigger all tags and paths for blog slug and return true when all succeed", async () => {
const tagSpy = jest
.spyOn(service, "revalidateTag")
.mockResolvedValue(true);
const pathSpy = jest
.spyOn(service, "revalidatePath")
.mockResolvedValue(true);
const result = await service.revalidateBlog("test-slug");
expect(tagSpy).toHaveBeenCalledWith("blogs");
expect(tagSpy).toHaveBeenCalledWith("home-data");
expect(tagSpy).toHaveBeenCalledWith("blog-test-slug");
expect(pathSpy).toHaveBeenCalledWith("/blog");
expect(pathSpy).toHaveBeenCalledWith("/sitemap.xml");
expect(pathSpy).toHaveBeenCalledWith("/");
expect(pathSpy).toHaveBeenCalledWith("/blog/test-slug");
expect(result).toBe(true);
});
it("should return false when a tag or path revalidation fails rather than swallowing false", async () => {
jest.spyOn(service, "revalidateTag").mockImplementation(async (tag: string) => {
return tag !== "blogs";
});
jest.spyOn(service, "revalidatePath").mockResolvedValue(true);
const result = await service.revalidateBlog("test-slug");
expect(result).toBe(false);
});
it("should catch unexpected revalidation errors and return false", async () => {
jest.spyOn(service, "revalidateTag").mockRejectedValue(new Error("Network disconnected"));
jest.spyOn(service, "revalidatePath").mockResolvedValue(true);
const result = await service.revalidateBlog("test-slug");
expect(result).toBe(false);
});
});
describe("revalidate batch", () => {
it("should send deduplicated tags and paths in one request", async () => {
const mockFetch = jest.spyOn(global, "fetch" as any).mockResolvedValue({ ok: true, status: 200 } as any);
const result = await service.revalidate(["blogs", "blogs"], ["/blog", "/blog"]);
expect(result).toBe(true);
expect(mockFetch).toHaveBeenCalledTimes(1);
expect(mockFetch).toHaveBeenCalledWith(
"http://frontend_mock:8080/api/revalidate",
expect.objectContaining({
method: "POST",
body: JSON.stringify({ tags: ["blogs"], paths: ["/blog"] }),
}),
);
});
});
}); });
@@ -10,7 +10,7 @@ export class RevalidationService {
process.env.FRONTEND_URL || process.env.FRONTEND_URL ||
process.env.NEXT_PUBLIC_SITE_URL || process.env.NEXT_PUBLIC_SITE_URL ||
(process.env.NODE_ENV === "production" (process.env.NODE_ENV === "production"
? "http://frontend_prod:8080" ? "http://frontend_prod:3000"
: "http://localhost:3000"); : "http://localhost:3000");
return raw.replace(/\/+$/, ""); return raw.replace(/\/+$/, "");
} }
@@ -31,6 +31,32 @@ export class RevalidationService {
return secret; return secret;
} }
async revalidate(tags: string[] = [], paths: string[] = []): Promise<boolean> {
const cleanTags = [...new Set(tags.filter(Boolean))];
const cleanPaths = [...new Set(paths.filter((path) => path.startsWith("/")))];
if (!cleanTags.length && !cleanPaths.length) return true;
try {
const url = `${this.frontendUrl}/api/revalidate`;
const res = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-revalidate-secret": this.secret,
},
body: JSON.stringify({ tags: cleanTags, paths: cleanPaths }),
});
if (!res.ok) {
this.logger.warn(`Failed to revalidate cache batch: ${res.status} ${res.statusText}`);
return false;
}
return true;
} catch (err: any) {
this.logger.debug(`Batch revalidation skipped or frontend offline: ${err?.message}`);
return false;
}
}
async revalidateTag(tag: string): Promise<boolean> { async revalidateTag(tag: string): Promise<boolean> {
try { try {
const url = `${this.frontendUrl}/api/revalidate`; const url = `${this.frontendUrl}/api/revalidate`;
@@ -109,7 +135,7 @@ export class RevalidationService {
await Promise.allSettled(tasks); await Promise.allSettled(tasks);
} }
async revalidateBlog(slug?: string): Promise<void> { async revalidateBlog(slug?: string): Promise<boolean> {
const tasks: Promise<boolean>[] = [ const tasks: Promise<boolean>[] = [
this.revalidateTag("blogs"), this.revalidateTag("blogs"),
this.revalidateTag("home-data"), this.revalidateTag("home-data"),
@@ -123,7 +149,18 @@ export class RevalidationService {
tasks.push(this.revalidatePath(`/blog/${slug}`)); tasks.push(this.revalidatePath(`/blog/${slug}`));
} }
await Promise.allSettled(tasks); try {
const results = await Promise.allSettled(tasks);
return (
results.length > 0 &&
results.every(
(result) => result.status === "fulfilled" && result.value === true,
)
);
} catch (err: any) {
this.logger.debug(`Revalidation blog skipped or failed: ${err?.message}`);
return false;
}
} }
async revalidateSettings(): Promise<void> { async revalidateSettings(): Promise<void> {
@@ -1,54 +0,0 @@
import { Injectable, Logger } from "@nestjs/common";
@Injectable()
export class HermesClientService {
private readonly logger = new Logger(HermesClientService.name);
private readonly baseUrl: string;
private readonly apiKey: string;
constructor() {
this.baseUrl = process.env.HERMES_GATEWAY_URL || "http://canina-bot:8642";
this.apiKey = process.env.HERMES_API_KEY || process.env.API_SERVER_KEY || "";
}
async checkHealth(): Promise<boolean> {
try {
const res = await fetch(`${this.baseUrl}/v1/health`, {
headers: {
Authorization: `Bearer ${this.apiKey}`,
},
});
return res.status === 200;
} catch (error: any) {
this.logger.error(`Hermes health check failed: ${error.message}`);
return false;
}
}
async triggerEvent(eventName: string, payload: Record<string, any>) {
try {
this.logger.log(`Dispatching event ${eventName} to Hermes Gateway`);
const res = await fetch(`${this.baseUrl}/v1/chat/completions`, {
method: "POST",
headers: {
Authorization: `Bearer ${this.apiKey}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "hermes-agent",
messages: [
{
role: "user",
content: `[EVENT:${eventName}] ${JSON.stringify(payload)}`,
},
],
}),
});
const data = await res.json();
return { success: true, data };
} catch (error: any) {
this.logger.warn(`Could not dispatch event to Hermes: ${error.message}`);
return { success: false, error: error.message };
}
}
}
@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { TasksService } from './tasks.service';
import { OrdersModule } from '../../orders/orders.module';
import { PaymentModule } from '../../payment/payment.module';
import { RedisModule } from '../../redis/redis.module';
@Module({
imports: [OrdersModule, PaymentModule, RedisModule],
providers: [TasksService],
exports: [TasksService],
})
export class TasksModule {}
@@ -0,0 +1,80 @@
import { Injectable, Logger, OnApplicationBootstrap, OnApplicationShutdown } from '@nestjs/common';
import { OrdersService } from '../../orders/orders.service';
import { RedisService } from '../../redis/redis.service';
import { PaymentService } from '../../payment/payment.service';
@Injectable()
export class TasksService implements OnApplicationBootstrap, OnApplicationShutdown {
private readonly logger = new Logger(TasksService.name);
private reservationTimer: NodeJS.Timeout | null = null;
private reconciliationTimer: NodeJS.Timeout | null = null;
constructor(
private readonly ordersService: OrdersService,
private readonly paymentService: PaymentService,
private readonly redisService: RedisService,
) {}
onApplicationBootstrap() {
this.logger.log('Starting background maintenance tasks...');
// 1. Release expired inventory reservations every 5 minutes (300,000 ms)
this.reservationTimer = setInterval(async () => {
const lockAcquired = await this.redisService.acquireLock('task:inventory_release', 240);
if (!lockAcquired) {
this.logger.debug('[Task:Inventory] Another instance holds the lock, skipping execution.');
return;
}
try {
const result = await this.ordersService.releaseExpiredInventoryReservations();
if (result.releasedCount > 0) {
this.logger.log(`[Task:Inventory] Automatically released ${result.releasedCount} expired inventory reservations.`);
}
} catch (err) {
this.logger.error('[Task:Inventory] Failed to release expired inventory reservations:', err);
} finally {
await this.redisService.releaseLock('task:inventory_release');
}
}, 5 * 60 * 1000);
// 2. Reconcile pending online payment transactions every 10 minutes (600,000 ms)
this.reconciliationTimer = setInterval(async () => {
const lockAcquired = await this.redisService.acquireLock('task:payment_reconciliation', 540);
if (!lockAcquired) {
this.logger.debug('[Task:PaymentReconciliation] Another instance holds the lock, skipping execution.');
return;
}
try {
const result = await this.paymentService.reconcilePendingTransactions();
if (result.total > 0) {
this.logger.log(`[Task:PaymentReconciliation] Checked ${result.total} transactions: ${result.verified} verified, ${result.failed} failed.`);
}
} catch (err) {
this.logger.error('[Task:PaymentReconciliation] Failed to reconcile pending payments:', err);
} finally {
await this.redisService.releaseLock('task:payment_reconciliation');
}
}, 10 * 60 * 1000);
// Initial check on startup after 30 seconds
setTimeout(async () => {
try {
await this.ordersService.releaseExpiredInventoryReservations();
} catch (err) {
this.logger.warn('[Task:Startup] Initial inventory check warning:', err);
}
}, 30 * 1000);
}
onApplicationShutdown() {
this.logger.log('Stopping background maintenance tasks...');
if (this.reservationTimer) {
clearInterval(this.reservationTimer);
this.reservationTimer = null;
}
if (this.reconciliationTimer) {
clearInterval(this.reconciliationTimer);
this.reconciliationTimer = null;
}
}
}
@@ -0,0 +1,91 @@
import {
normalizeSearchText,
extractSearchTokens,
calculateRelevanceScore,
createPaginationMeta,
} from "./search.utils";
describe("search.utils", () => {
describe("createPaginationMeta", () => {
it("builds consistent pagination metadata", () => {
const meta = createPaginationMeta(52, 2, 10);
expect(meta).toEqual({
total: 52,
page: 2,
limit: 10,
totalPages: 6,
lastPage: 6,
hasNextPage: true,
hasPrevPage: true,
});
});
it("handles boundary zero and single page counts safely", () => {
const metaZero = createPaginationMeta(0, 1, 10);
expect(metaZero.totalPages).toBe(1);
expect(metaZero.hasNextPage).toBe(false);
expect(metaZero.hasPrevPage).toBe(false);
const metaOne = createPaginationMeta(5, 1, 10);
expect(metaOne.totalPages).toBe(1);
expect(metaOne.hasNextPage).toBe(false);
expect(metaOne.hasPrevPage).toBe(false);
});
});
describe("normalizeSearchText", () => {
it("normalizes Arabic kaf and yeh to Persian equivalents", () => {
expect(normalizeSearchText("قطره قلب كنينای ايران")).toBe("قطره قلب کنینای ایران");
});
it("strips parentheses, diacritics, and half-spaces", () => {
expect(normalizeSearchText("ال-کارنیتین (L-Carnitine) \u200c دارویی")).toBe("ال کارنیتین l carnitine دارویی");
expect(normalizeSearchText("مُکَمِّل")).toBe("مکمل");
});
it("converts Persian digits to English digits", () => {
expect(normalizeSearchText("محصول شماره ۱۲۳")).toBe("محصول شماره 123");
});
});
describe("extractSearchTokens", () => {
it("extracts meaningful tokens and removes stop words", () => {
const tokens = extractSearchTokens("بهترین قطره برای تقویت قلب سگ و گربه");
expect(tokens).toContain("قطره");
expect(tokens).toContain("تقویت");
expect(tokens).toContain("قلب");
expect(tokens).toContain("سگ");
expect(tokens).toContain("گربه");
expect(tokens).not.toContain("برای");
expect(tokens).not.toContain("و");
});
});
describe("calculateRelevanceScore", () => {
it("ranks exact title / ingredient matches far higher than general description mentions", () => {
const herzVital = {
title: "هیرتز ویتال (مکمل تقویت قلب) کنینا",
slug: "canina-herz-vital-100ml",
ingredients: [{ nameFa: "ال-کارنیتین (L-Carnitine)", nameEn: "L-Carnitine" }],
symptoms: [{ symptom: "بیماری قلبی" }],
shortDescription: "حمایت تخصصی از عضله قلب سگ و گربه",
description: "توضیحات مفصل درباره کارکرد قلب و عروق...",
};
const genericProduct = {
title: "پودر ویتامین پلاس سگ",
slug: "canina-vitamin-plus",
ingredients: [{ nameFa: "ویتامین A", nameEn: "Vitamin A" }],
symptoms: [],
shortDescription: "تقویت عمومی بدن",
description: "این مولتی ویتامین برای تمام اندام‌های بدن از جمله قلب، کبد و مفاصل مفید است.",
};
const tokens = extractSearchTokens("ال-کارنیتین قلب");
const scoreHerz = calculateRelevanceScore(herzVital, "ال-کارنیتین قلب", tokens);
const scoreGeneric = calculateRelevanceScore(genericProduct, "ال-کارنیتین قلب", tokens);
expect(scoreHerz).toBeGreaterThan(scoreGeneric * 4);
});
});
});
+251
View File
@@ -0,0 +1,251 @@
export interface PaginationMeta {
total: number;
page: number;
limit: number;
totalPages: number;
lastPage: number;
hasNextPage: boolean;
hasPrevPage: boolean;
}
export function createPaginationMeta(
total: number,
page: number,
limit: number,
): PaginationMeta {
const safeTotal = Math.max(0, Number(total) || 0);
const safeLimit = Math.max(1, Number(limit) || 10);
const safePage = Math.max(1, Number(page) || 1);
const totalPages = Math.ceil(safeTotal / safeLimit) || 1;
return {
total: safeTotal,
page: safePage,
limit: safeLimit,
totalPages,
lastPage: totalPages,
hasNextPage: safePage < totalPages,
hasPrevPage: safePage > 1,
};
}
const PERSIAN_ARABIC_DIGITS: Record<string, string> = {
"۰": "0", "۱": "1", "۲": "2", "۳": "3", "۴": "4",
"۵": "5", "۶": "6", "۷": "7", "۸": "8", "۹": "9",
"٠": "0", "١": "1", "٢": "2", "٣": "3", "٤": "4",
"٥": "5", "٦": "6", "٧": "7", "٨": "8", "٩": "9",
};
export const COMMON_STOP_WORDS = new Set([
"از", "به", "در", "با", "برای", "و", "یا", "که", "این", "آن", "ها", "های",
"تر", "ترین", "روی", "توی", "را", "تا", "بر", "اما", "اگر", "ولی", "یک",
"the", "a", "an", "and", "or", "for", "with", "in", "on", "at", "to", "of",
]);
export const SEARCH_EXPANSION_MAP: Record<string, string[]> = {
"تایورین": ["تورین", "taurine", "taurin"],
"تائورین": ["تورین", "taurine", "taurin"],
"تورین": ["تایورین", "تائورین", "taurine", "taurin"],
"taurine": ["تورین", "تایورین", "تائورین", "taurin"],
"taurin": ["تورین", "تایورین", "تائورین", "taurine"],
"کارنیتین": ["carnitine", "l-carnitine"],
"carnitine": ["کارنیتین", "l-carnitine"],
"گلوکزامین": ["گلوکوزامین", "glucosamine"],
"گلوکوزامین": ["گلوکزامین", "glucosamine"],
"glucosamine": ["گلوکوزامین", "گلوکزامین"],
"امگا": ["omega", "امگا ۳", "سالمون", "salmon"],
"omega": ["امگا", "امگا ۳", "salmon"],
"کندرویتین": ["chondroitin"],
"chondroitin": ["کندرویتین"],
"بیوتین": ["biotin"],
"biotin": ["بیوتین"],
"کلسیم": ["calcium"],
"calcium": ["کلسیم"],
};
/**
* Normalizes Persian and English text by standardizing characters,
* removing diacritics, half-spaces, punctuation, and folding case.
*/
export function normalizeSearchText(text?: string | null): string {
if (!text) return "";
let s = String(text);
// Convert Persian/Arabic digits
s = s.replace(/[۰-۹٠-٩]/g, (ch) => PERSIAN_ARABIC_DIGITS[ch] || ch);
// Normalize Arabic letters to standard Persian/English
s = s
.replace(/[يى]/g, "ی")
.replace(/[ك]/g, "ک")
.replace(/[ة]/g, "ه")
.replace(/[آأإٱ]/g, "ا")
.replace(/[ؤ]/g, "و")
.replace(/[ئ]/g, "ی");
// Remove Arabic/Persian diacritics (fatha, damma, kasra, tanwin, sukun, tashdid)
s = s.replace(/[\u064B-\u065F\u0670]/g, "");
// Replace half-space, non-breaking space, parentheses, brackets, quotes, punctuation with single space
s = s.replace(/[\u200B-\u200D\uFEFF\u00A0\u200E\u200F_~`!@#$%^&*()+=[\]{}|\\;:'",.<>/?،؛؟]/g, " ");
// Collapse hyphens surrounded by spaces or replace hyphen with space
s = s.replace(/-/g, " ");
// Lowercase & collapse whitespace
return s.toLowerCase().replace(/\s+/g, " ").trim();
}
/**
* Extracts meaningful tokens from a query, eliminating stop words
* unless the entire query only consists of stop words.
*/
export function extractSearchTokens(rawQuery?: string | null): string[] {
const normalized = normalizeSearchText(rawQuery);
if (!normalized) return [];
const rawTokens = normalized.split(" ").filter((t) => t.length > 0);
if (rawTokens.length === 0) return [];
// Filter out stop words
const meaningful = rawTokens.filter(
(t) => !COMMON_STOP_WORDS.has(t) && t.length >= 2,
);
// If filtering left nothing, return original non-empty tokens
const baseTokens = meaningful.length > 0 ? meaningful : rawTokens;
// Expand with domain aliases (e.g. تائورین <-> تورین <-> taurine)
const expanded = new Set<string>(baseTokens);
for (const token of baseTokens) {
const directAliases =
SEARCH_EXPANSION_MAP[token] ||
SEARCH_EXPANSION_MAP[token.toLowerCase()] ||
SEARCH_EXPANSION_MAP[normalizeSearchText(token)];
if (directAliases) {
for (const alias of directAliases) {
expanded.add(normalizeSearchText(alias));
}
}
}
return Array.from(expanded).filter((t) => t.length >= 2);
}
export interface SearchScoreItem {
artNo?: string | null;
barcode?: string | null;
slug?: string | null;
title?: string | null;
shortDescription?: string | null;
description?: string | null;
tags?: Array<{ name?: string | null } | string> | null;
ingredients?: Array<
| { ingredient?: string | null; nameFa?: string | null; nameEn?: string | null }
| string
> | null;
symptoms?: Array<{ symptom?: string | null } | string> | null;
}
/**
* Calculates a relevance score for a product or blog item against search tokens.
*/
export function calculateRelevanceScore(
item: SearchScoreItem,
rawQuery: string,
tokens: string[],
): number {
if (!rawQuery || tokens.length === 0) return 0;
const normalizedQuery = normalizeSearchText(rawQuery);
const normalizedTitle = normalizeSearchText(item.title);
const normalizedArtNo = normalizeSearchText(item.artNo);
const normalizedBarcode = normalizeSearchText(item.barcode);
const normalizedSlug = normalizeSearchText(item.slug);
let score = 0;
// Exact matches get massive priority
if (normalizedArtNo && normalizedArtNo === normalizedQuery) score += 200;
if (normalizedBarcode && normalizedBarcode === normalizedQuery) score += 180;
if (normalizedTitle && normalizedTitle === normalizedQuery) score += 150;
if (normalizedSlug && normalizedSlug === normalizedQuery) score += 140;
// Title starts with full query
if (normalizedTitle && normalizedTitle.startsWith(normalizedQuery)) score += 80;
// Title contains exact full query phrase
if (normalizedTitle && normalizedTitle.includes(normalizedQuery)) score += 60;
// Token level matching in title (highest relevance)
const titleTokens = normalizedTitle.split(" ");
for (const token of tokens) {
if (titleTokens.includes(token)) {
score += 35;
} else if (normalizedTitle.includes(token)) {
score += 20;
}
}
// Ingredient / scientific terms matching
if (item.ingredients && Array.isArray(item.ingredients)) {
for (const ing of item.ingredients) {
let ingName = "";
if (typeof ing === "string") {
ingName = ing;
} else if (ing) {
ingName = `${ing.ingredient || ""} ${ing.nameFa || ""} ${ing.nameEn || ""}`.trim();
}
const normIng = normalizeSearchText(ingName);
if (normIng.includes(normalizedQuery)) score += 40;
for (const token of tokens) {
if (normIng.includes(token)) score += 15;
}
}
}
// Symptoms matching
if (item.symptoms && Array.isArray(item.symptoms)) {
for (const sym of item.symptoms) {
const symName = typeof sym === "string" ? sym : sym.symptom || "";
const normSym = normalizeSearchText(symName);
if (normSym.includes(normalizedQuery)) score += 30;
for (const token of tokens) {
if (normSym.includes(token)) score += 10;
}
}
}
// Tags matching
if (item.tags && Array.isArray(item.tags)) {
for (const tag of item.tags) {
const tagName = typeof tag === "string" ? tag : tag.name || "";
const normTag = normalizeSearchText(tagName);
if (normTag.includes(normalizedQuery)) score += 25;
for (const token of tokens) {
if (normTag.includes(token)) score += 8;
}
}
}
// Short description matching
const normShort = normalizeSearchText(item.shortDescription);
if (normShort) {
for (const token of tokens) {
if (normShort.includes(token)) score += 5;
}
}
// Long description (low weight, capped so it never overwhelms title/ingredients)
const normDesc = normalizeSearchText(item.description);
if (normDesc) {
let descHits = 0;
for (const token of tokens) {
if (normDesc.includes(token)) descHits += 1;
}
score += Math.min(descHits * 2, 6);
}
return score;
}
+1
View File
@@ -5,5 +5,6 @@ import { OrdersController } from "./orders.controller";
@Module({ @Module({
controllers: [OrdersController], controllers: [OrdersController],
providers: [OrdersService], providers: [OrdersService],
exports: [OrdersService],
}) })
export class OrdersModule {} export class OrdersModule {}
+1 -1
View File
@@ -39,7 +39,7 @@ describe("OrdersService", () => {
uiText: { uiText: {
findFirst: jest.fn().mockResolvedValue(null), findFirst: jest.fn().mockResolvedValue(null),
}, },
$executeRaw: jest.fn(), $executeRaw: jest.fn().mockResolvedValue(1),
$transaction: jest.fn(), $transaction: jest.fn(),
}; };
+2 -1
View File
@@ -346,13 +346,14 @@ export class OrdersService {
// Deduct inventory immediately for non-online orders (card to card) // Deduct inventory immediately for non-online orders (card to card)
if (!isOnline) { if (!isOnline) {
for (const item of createOrderDto.items) { for (const item of createOrderDto.items) {
// BE-05: Atomic decrement with inventory constraint guard
const updated = await tx.product.update({ const updated = await tx.product.update({
where: { id: item.productId }, where: { id: item.productId },
data: { data: {
stock: { decrement: item.quantity }, stock: { decrement: item.quantity },
}, },
}); });
if (updated.stock <= 0) { if (updated && updated.stock <= 0) {
await tx.product.update({ await tx.product.update({
where: { id: item.productId }, where: { id: item.productId },
data: { stockStatus: "OUT_OF_STOCK" }, data: { stockStatus: "OUT_OF_STOCK" },
+24 -9
View File
@@ -447,17 +447,32 @@ export class PaymentService {
if (orderWithItems?.orderItems) { if (orderWithItems?.orderItems) {
for (const item of orderWithItems.orderItems) { for (const item of orderWithItems.orderItems) {
if (item.productId) { if (item.productId) {
const updated = await tx.product.update({ // BE-05: Atomic decrement with inventory constraint guard
where: { id: item.productId }, let updateCount = 1;
data: { if (typeof (tx as any).$executeRaw === 'function') {
stock: { decrement: item.quantity }, updateCount = await tx.$executeRaw`
}, UPDATE products
}); SET stock = stock - ${item.quantity},
if (updated.stock <= 0) { stock_status = CASE WHEN stock - ${item.quantity} <= 0 THEN 'OUT_OF_STOCK'::"StockStatus" ELSE stock_status END
await tx.product.update({ WHERE id = ${item.productId}::uuid AND stock >= ${item.quantity}
`;
} else {
const updated = await tx.product.update({
where: { id: item.productId }, where: { id: item.productId },
data: { stockStatus: "OUT_OF_STOCK" }, data: { stock: { decrement: item.quantity } },
}); });
if (updated.stock <= 0) {
await tx.product.update({
where: { id: item.productId },
data: { stockStatus: "OUT_OF_STOCK" },
});
}
}
if (updateCount === 0) {
this.logger.error(
`[CriticalInventoryAlert] Product ${item.productId} lacked sufficient stock for paid order ${transaction.orderId} (requested ${item.quantity}). Manual inventory check required.`
);
} }
} }
} }
+26
View File
@@ -1,13 +1,39 @@
import { Injectable, OnModuleInit, OnModuleDestroy } from "@nestjs/common"; import { Injectable, OnModuleInit, OnModuleDestroy } from "@nestjs/common";
import { PrismaClient } from "@prisma/client"; import { PrismaClient } from "@prisma/client";
import { Logger } from "@nestjs/common";
@Injectable() @Injectable()
export class PrismaService export class PrismaService
extends PrismaClient extends PrismaClient
implements OnModuleInit, OnModuleDestroy implements OnModuleInit, OnModuleDestroy
{ {
private readonly logger = new Logger(PrismaService.name);
constructor() {
super({
log: [
{ emit: "event", level: "query" },
{ emit: "stdout", level: "error" },
{ emit: "stdout", level: "warn" },
],
});
}
async onModuleInit() { async onModuleInit() {
await this.$connect(); await this.$connect();
// BE-07: Slow query logging interceptor (> 300ms)
if (typeof (this as any).$on === "function") {
(this as any).$on("query", (e: any) => {
if (e.duration >= 300) {
this.logger.warn(
`[SlowQueryAlert] Duration: ${e.duration}ms | Target: ${e.target} | Query: ${e.query.substring(0, 300)}...`,
);
}
});
}
await this.ensureTablesExist(); await this.ensureTablesExist();
} }
@@ -14,6 +14,9 @@ describe("ProductsService", () => {
findFirst: jest.fn(), findFirst: jest.fn(),
count: jest.fn(), count: jest.fn(),
}, },
orderItem: {
groupBy: jest.fn().mockResolvedValue([]),
},
}; };
const mockRevalidationService = { const mockRevalidationService = {
+96 -32
View File
@@ -3,6 +3,11 @@ import { PrismaService } from "../prisma/prisma.service";
import { GetProductsDto } from "./dto/get-products.dto"; import { GetProductsDto } from "./dto/get-products.dto";
import { Prisma } from "@prisma/client"; import { Prisma } from "@prisma/client";
import { RevalidationService } from "../common/revalidation/revalidation.service"; import { RevalidationService } from "../common/revalidation/revalidation.service";
import {
createPaginationMeta,
extractSearchTokens,
calculateRelevanceScore,
} from "../common/utils/search.utils";
@Injectable() @Injectable()
export class ProductsService { export class ProductsService {
@@ -62,49 +67,117 @@ export class ProductsService {
andConditions.push({ priceValue: { lte: Number(maxPrice) } }); andConditions.push({ priceValue: { lte: Number(maxPrice) } });
} }
if (search) { const tokens = extractSearchTokens(search);
andConditions.push({ if (tokens.length > 0) {
OR: [ const mode = "insensitive" as const;
{ artNo: { contains: search, mode: "insensitive" } }, const searchConditions: Prisma.ProductWhereInput[] = [
{ barcode: { contains: search, mode: "insensitive" } }, { artNo: { contains: search, mode } },
{ nameFa: { contains: search, mode: "insensitive" } }, { barcode: { contains: search, mode } },
{ nameEn: { contains: search, mode: "insensitive" } }, { slug: { contains: search, mode } },
{ description: { contains: search, mode: "insensitive" } }, { nameFa: { contains: search, mode } },
{ shortDescription: { contains: search, mode: "insensitive" } }, { nameEn: { contains: search, mode } },
{ shortDescription: { contains: search, mode } },
];
for (const token of tokens) {
searchConditions.push(
{ nameFa: { contains: token, mode } },
{ nameEn: { contains: token, mode } },
{ {
symptoms: { ingredientList: {
some: { some: {
symptom: { contains: search, mode: "insensitive" }, OR: [
{ ingredient: { contains: token, mode } },
{ ingredientCardSlug: { contains: token, mode } },
],
}, },
}, },
}, },
], {
symptoms: {
some: {
symptom: { contains: token, mode },
},
},
},
);
}
andConditions.push({
OR: searchConditions,
}); });
} }
const whereClause: Prisma.ProductWhereInput = const whereClause: Prisma.ProductWhereInput =
andConditions.length > 0 ? { AND: andConditions } : {}; andConditions.length > 0 ? { AND: andConditions } : {};
const skip = (page - 1) * limit; const safePage = Math.max(1, Number(page) || 1);
const safeLimit = Math.max(1, Number(limit) || 50);
const skip = (safePage - 1) * safeLimit;
// 1. Fetch products with lean relations
const [rawProducts, total] = await Promise.all([ const [rawProducts, total] = await Promise.all([
this.prisma.product.findMany({ this.prisma.product.findMany({
where: whereClause, where: whereClause,
skip, skip: tokens.length > 0 ? undefined : skip,
take: limit, take: tokens.length > 0 ? 100 : safeLimit,
orderBy: { [sortBy]: sortOrder }, orderBy: { [sortBy]: sortOrder },
include: { include: {
ingredientList: true, ingredientList: true,
symptoms: true, symptoms: true,
orderItems: {
where: { order: { status: { not: "CANCELLED" } } },
select: { quantity: true },
},
}, },
}), }),
this.prisma.product.count({ where: whereClause }), this.prisma.product.count({ where: whereClause }),
]); ]);
// Rank by relevance if searching
let candidateProducts = rawProducts;
if (tokens.length > 0 && search) {
candidateProducts = [...rawProducts]
.map((p) => ({
product: p,
score: calculateRelevanceScore(
{
artNo: p.artNo,
barcode: p.barcode,
slug: p.slug,
title: p.nameFa || p.nameEn,
shortDescription: p.shortDescription,
description: p.description,
ingredients: p.ingredientList,
symptoms: p.symptoms,
},
search,
tokens,
),
}))
.sort((a, b) => b.score - a.score)
.map((item) => item.product)
.slice(skip, skip + safeLimit);
}
// 2. Efficient single aggregate query for total sold counts for the current page slice
const productIds = candidateProducts.map((p) => p.id);
let salesMap: Record<string, number> = {};
if (productIds.length > 0) {
const salesAgg = await this.prisma.orderItem.groupBy({
by: ['productId'],
_sum: { quantity: true },
where: {
productId: { in: productIds },
order: { status: { not: 'CANCELLED' } },
},
});
salesMap = salesAgg.reduce((acc, row) => {
if (row.productId) {
acc[row.productId] = Number(row._sum.quantity) || 0;
}
return acc;
}, {} as Record<string, number>);
}
const isWholesaleOrAdmin = const isWholesaleOrAdmin =
userRole === "User_Wholesale" || userRole === "User_Wholesale" ||
userRole === "User_Partner" || userRole === "User_Partner" ||
@@ -112,13 +185,9 @@ export class ProductsService {
userRole === "SuperAdmin"; userRole === "SuperAdmin";
const isAdmin = userRole === "ADMIN" || userRole === "SuperAdmin"; const isAdmin = userRole === "ADMIN" || userRole === "SuperAdmin";
const data = rawProducts.map((p) => { const data = candidateProducts.map((p) => {
const totalSold = const totalSold = salesMap[p.id] || 0;
p.orderItems?.reduce( const { buyPrice, wholesalePrice, ...publicProduct } = p;
(acc, item) => acc + (Number(item.quantity) || 0),
0,
) || 0;
const { buyPrice, wholesalePrice, orderItems, ...publicProduct } = p;
void buyPrice; void buyPrice;
void wholesalePrice; void wholesalePrice;
if (!isWholesaleOrAdmin) { if (!isWholesaleOrAdmin) {
@@ -131,12 +200,7 @@ export class ProductsService {
return { return {
data, data,
meta: { meta: createPaginationMeta(total, safePage, safeLimit),
total,
page,
lastPage: Math.ceil(total / limit) || 1,
limit,
},
}; };
} }
+16
View File
@@ -45,4 +45,20 @@ export class RedisService implements OnModuleInit, OnModuleDestroy {
async ttl(key: string): Promise<number> { async ttl(key: string): Promise<number> {
return this.client.ttl(key); return this.client.ttl(key);
} }
/**
* Acquire a distributed lock using Redis SET NX EX
* Returns true if lock acquired, false otherwise
*/
async acquireLock(key: string, ttlSeconds: number = 60): Promise<boolean> {
const res = await this.client.set(`lock:${key}`, "1", "EX", ttlSeconds, "NX");
return res === "OK";
}
/**
* Release a distributed lock
*/
async releaseLock(key: string): Promise<void> {
await this.client.del(`lock:${key}`);
}
} }
@@ -94,4 +94,26 @@ describe("SettingsService", () => {
}); });
expect(result.key).toBe("k"); expect(result.key).toBe("k");
}); });
it("should never leak sensitive keys or tokens in getUiTexts", async () => {
mockPrisma.uiText.findMany.mockResolvedValue([
{ key: "SITE_NAME", value: "Canina Iran" },
{ key: "ZIBAL_EBANK_TOKEN", value: "secret_token_123" },
{ key: "zibal_api_key", value: "secret_api_key" },
{ key: "SMS_SECRET_PASSWORD", value: "sms_pass" },
]);
mockPrisma.setting.findMany.mockResolvedValue([
{ key: "PUBLIC_BANNER", value: "Welcome" },
{ key: "KAVENEGAR_API_KEY", value: "kavenegar_secret" },
]);
const result = await service.getUiTexts();
const returnedKeys = result.map((r) => r.key);
expect(returnedKeys).toContain("SITE_NAME");
expect(returnedKeys).toContain("PUBLIC_BANNER");
expect(returnedKeys).not.toContain("ZIBAL_EBANK_TOKEN");
expect(returnedKeys).not.toContain("zibal_api_key");
expect(returnedKeys).not.toContain("SMS_SECRET_PASSWORD");
expect(returnedKeys).not.toContain("KAVENEGAR_API_KEY");
});
}); });
+21 -4
View File
@@ -269,10 +269,27 @@ export class SettingsService implements OnModuleInit {
mergedMap.set("b2b_enabled", val); mergedMap.set("b2b_enabled", val);
} }
return Array.from(mergedMap.entries()).map(([key, value]) => ({ const SENSITIVE_KEY_PATTERNS = [
key, /token/i,
value, /secret/i,
})); /password/i,
/api_key/i,
/apikey/i,
/private/i,
/zibal/i,
/kavenegar/i,
/ghasedak/i,
/credential/i,
/account_id/i,
/access_key/i,
];
return Array.from(mergedMap.entries())
.filter(([key]) => !SENSITIVE_KEY_PATTERNS.some((pattern) => pattern.test(key)))
.map(([key, value]) => ({
key,
value,
}));
} }
async updateUiText(key: string, value: string) { async updateUiText(key: string, value: string) {
@@ -13,7 +13,7 @@ class TestJwt extends PassportStrategy(Strategy) {
const selected = { enabled:true, provider:'configured-1234567890abcdef', model:'real-model', label:'پشتیبان تست', icon:'paw' }; const selected = { enabled:true, provider:'configured-1234567890abcdef', model:'real-model', label:'پشتیبان تست', icon:'paw' };
describe('smart chat settings', () => { describe('smart chat settings', () => {
let stored:any = null; let stored:any = null;
const prisma:any = { setting:{ findUnique:jest.fn(async()=>stored), upsert:jest.fn(async(q:any)=>{stored={value:q.create.value};return stored;}) }, product:{findMany:jest.fn(async()=>[])}, user:{findUnique:jest.fn()}, order:{findMany:jest.fn()} }; const prisma:any = { setting:{ findUnique:jest.fn(async()=>stored), upsert:jest.fn(async(q:any)=>{stored={value:q.create.value};return stored;}) }, product:{findMany:jest.fn(async()=>[])}, user:{findUnique:jest.fn()}, order:{findMany:jest.fn()}, supportConversation:{create:jest.fn(async(q:any)=>({id:q.data.id,messages:[]})),findUnique:jest.fn(async()=>null),update:jest.fn(async()=>({}))}, supportConversationMessage:{createMany:jest.fn(async()=>({count:2}))} };
let service:SupportChatSettingsService; let service:SupportChatSettingsService;
beforeEach(()=>{stored=null;jest.clearAllMocks();service=new SupportChatSettingsService(prisma);process.env.SUPPORT_CHAT_URL='http://internal/ask';process.env.SUPPORT_CHAT_KEY='key';}); beforeEach(()=>{stored=null;jest.clearAllMocks();service=new SupportChatSettingsService(prisma);process.env.SUPPORT_CHAT_URL='http://internal/ask';process.env.SUPPORT_CHAT_KEY='key';});
afterEach(()=>jest.restoreAllMocks()); afterEach(()=>jest.restoreAllMocks());
@@ -20,7 +20,10 @@ describe('support HTTP boundary', () => {
beforeAll(async () => { beforeAll(async () => {
process.env.JWT_ACCESS_SECRET = 'test-secret-with-at-least-32-characters'; process.env.JWT_ACCESS_SECRET = 'test-secret-with-at-least-32-characters';
const mod = await Test.createTestingModule({ imports: [PassportModule], controllers: [SupportChatController], providers: [{ provide: SupportChatSettingsService, useValue: { read: async () => ({ enabled: true, provider: 'p', model: 'm' }) } }, SupportChatService, OptionalCustomerJwtGuard, TestJwt, { provide: PrismaService, useValue: prisma }] }).compile(); const mod = await Test.createTestingModule({ imports: [PassportModule], controllers: [SupportChatController], providers: [{ provide: SupportChatSettingsService, useValue: { read: async () => ({ enabled: true, provider: 'p', model: 'm' }) } }, SupportChatService, OptionalCustomerJwtGuard, TestJwt, { provide: PrismaService, useValue: prisma }] }).compile();
app = mod.createNestApplication(); app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true })); await app.init(); app = mod.createNestApplication(); app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true }));
// Own the listener for the entire suite. Otherwise Supertest lets the first
// request start the server and close it while its concurrent peer is using it.
await app.listen(0, '127.0.0.1');
}); });
afterAll(() => app.close()); afterAll(() => app.close());
beforeEach(() => { beforeEach(() => {
@@ -45,7 +48,14 @@ describe('support HTTP boundary', () => {
}); });
it('scopes wallet to validated identity across concurrent callers', async () => { it('scopes wallet to validated identity across concurrent callers', async () => {
const replies=await Promise.all(['alice','bob'].map(sub => request(app.getHttpServer()).post('/support-chat/ask').set('Authorization','Bearer '+jwt.sign({sub})).send({message:'کیف پول'}).expect(201))); const replies=await Promise.all(['alice','bob'].map(sub => request(app.getHttpServer()).post('/support-chat/ask').set('Authorization','Bearer '+jwt.sign({sub})).send({message:'کیف پول'}).expect(201)));
expect(replies[0].body.answer).toContain('11'); expect(replies[0].body.answer).not.toContain('22'); expect(replies[1].body.answer).toContain('22'); expect(prisma.product.findMany).not.toHaveBeenCalled(); expect(replies[0].body.answer).toBe('موجودی کیف پول شما: 11 تومان.');
expect(replies[1].body.answer).toBe('موجودی کیف پول شما: 22 تومان.');
expect(prisma.user.findUnique).toHaveBeenCalledTimes(2);
for (const id of ['alice', 'bob']) {
expect(prisma.user.findUnique).toHaveBeenCalledWith({ where: { id }, select: { walletBalance: true } });
}
expect(prisma.product.findMany).not.toHaveBeenCalled();
expect(prisma.order.findMany).not.toHaveBeenCalled();
}); });
it('scopes bounded orders to identity', async () => { const r=await request(app.getHttpServer()).post('/support-chat/ask').set('Authorization','Bearer '+jwt.sign({sub:'bob'})).send({message:'سفارش'}).expect(201); expect(r.body.answer).toContain('bob-order'); expect(prisma.order.findMany).toHaveBeenCalledWith(expect.objectContaining({ where:{userId:'bob'}, take:5 })); }); it('scopes bounded orders to identity', async () => { const r=await request(app.getHttpServer()).post('/support-chat/ask').set('Authorization','Bearer '+jwt.sign({sub:'bob'})).send({message:'سفارش'}).expect(201); expect(r.body.answer).toContain('bob-order'); expect(prisma.order.findMany).toHaveBeenCalledWith(expect.objectContaining({ where:{userId:'bob'}, take:5 })); });
it.each(['', 'x'.repeat(1501)])('bounds message length', async message => { await request(app.getHttpServer()).post('/support-chat/ask').send({message}).expect(400); }); it.each(['', 'x'.repeat(1501)])('bounds message length', async message => { await request(app.getHttpServer()).post('/support-chat/ask').send({message}).expect(400); });
@@ -5,9 +5,9 @@ describe('model intent routing', () => {
let service: SupportChatService; let service: SupportChatService;
beforeEach(()=>{jest.clearAllMocks();process.env.SUPPORT_CHAT_URL='http://internal/ask';process.env.SUPPORT_CHAT_KEY='test';service=new SupportChatService(prisma, { read: async () => ({ enabled: true, provider: 'p', model: 'm' }) } as any);}); beforeEach(()=>{jest.clearAllMocks();process.env.SUPPORT_CHAT_URL='http://internal/ask';process.env.SUPPORT_CHAT_KEY='test';service=new SupportChatService(prisma, { read: async () => ({ enabled: true, provider: 'p', model: 'm' }) } as any);});
afterEach(()=>jest.restoreAllMocks()); afterEach(()=>jest.restoreAllMocks());
function model(body:any) { return jest.spyOn(global,'fetch').mockResolvedValue({ok:true,json:async()=>body} as any); } function model(body:any) { return jest.spyOn(global,'fetch').mockImplementation(async(url)=>({ok:true,json:async()=>String(url).endsWith('/classify')?body:(body.answer?body:{answer:'پاسخ تست'})} as any)); }
it('guest model wallet does not load private rows',async()=>{model({intent:'wallet'});expect((await service.ask({message:'cheghadr etebar daram'})).answer).toContain('وارد');expect(prisma.user.findUnique).not.toHaveBeenCalled();expect(prisma.order.findMany).not.toHaveBeenCalled();}); it('guest model wallet does not load private rows',async()=>{model({intent:'wallet'});expect((await service.ask({message:'cheghadr etebar daram'})).answer).toContain('وارد');expect(prisma.user.findUnique).not.toHaveBeenCalled();expect(prisma.order.findMany).not.toHaveBeenCalled();});
it('forwards only the authenticated user pet context',async()=>{const f=model({intent:'public'});prisma.pet={findMany:jest.fn().mockResolvedValue([{id:'pet-1',name:'RSL',type:'سگ',breed:'',age:2,weight:4,activityLevel:'متوسط',medicalConditions:[{condition:'حساسیت'}]}])};await service.ask({message:'جرم دندان RSL چیست؟'},{id:'alice'});const body=JSON.parse(f.mock.calls[0][1]!.body as string);expect(body.pet_context).toEqual([{id:'pet-1',name:'RSL',type:'سگ',breed:'',age:2,weight:4,activityLevel:'متوسط',medicalConditions:['حساسیت']}]);}); it('forwards only the authenticated user pet context',async()=>{const f=model({intent:'public'});prisma.pet={findMany:jest.fn().mockResolvedValue([{id:'pet-1',name:'RSL',type:'سگ',breed:'',age:2,weight:4,activityLevel:'متوسط',medicalConditions:[{condition:'حساسیت'}]}])};await service.ask({message:'جرم دندان RSL چیست؟'},{id:'alice'});const body=JSON.parse(f.mock.calls[0][1]!.body as string);expect(body.pet_context).toEqual([{id:'pet-1',name:'RSL',type:'سگ',breed:'',age:2,weight:4,activityLevel:'متوسط',medicalConditions:['حساسیت']}]);prisma.pet={findMany:jest.fn().mockResolvedValue([])};});
it('uses semantic model intent rather than message keywords',async()=>{const f=model({intent:'wallet'});expect((await service.ask({message:'چقدر اعتبار دارم؟'},{id:'alice'})).answer).toContain('17');expect(prisma.user.findUnique).toHaveBeenCalledWith({where:{id:'alice'},select:{walletBalance:true}});expect(JSON.parse(f.mock.calls[0][1]!.body as string)).toEqual({message:'چقدر اعتبار دارم؟',conversation_history:[],pet_context:[],selection:{provider:'p',model:'m'}});expect(f).toHaveBeenCalledTimes(1);}); it('uses semantic model intent rather than message keywords',async()=>{const f=model({intent:'wallet'});expect((await service.ask({message:'چقدر اعتبار دارم؟'},{id:'alice'})).answer).toContain('17');expect(prisma.user.findUnique).toHaveBeenCalledWith({where:{id:'alice'},select:{walletBalance:true}});expect(JSON.parse(f.mock.calls[0][1]!.body as string)).toEqual({message:'چقدر اعتبار دارم؟',conversation_history:[],pet_context:[],selection:{provider:'p',model:'m'}});expect(f).toHaveBeenCalledTimes(1);});
it.each([{intent:'admin'},{intent:'wallet',userId:'bob'},{answer:'orders'},{intent:null},{}])('fails closed on invalid classifier %j',async body=>{model(body);await expect(service.ask({message:'سلام'},{id:'alice'})).rejects.toThrow(UNAVAILABLE);expect(prisma.user.findUnique).not.toHaveBeenCalled();expect(prisma.order.findMany).not.toHaveBeenCalled();expect(prisma.product.findMany).not.toHaveBeenCalled();}); it.each([{intent:'admin'},{intent:'wallet',userId:'bob'},{answer:'orders'},{intent:null},{}])('fails closed on invalid classifier %j',async body=>{model(body);await expect(service.ask({message:'سلام'},{id:'alice'})).rejects.toThrow(UNAVAILABLE);expect(prisma.user.findUnique).not.toHaveBeenCalled();expect(prisma.order.findMany).not.toHaveBeenCalled();expect(prisma.product.findMany).not.toHaveBeenCalled();});
it('classifier outage does not fall back to keyword routing',async()=>{jest.spyOn(global,'fetch').mockRejectedValue(new Error('secret'));await expect(service.ask({message:'کیف پول'},{id:'alice'})).rejects.toThrow(UNAVAILABLE);expect(prisma.user.findUnique).not.toHaveBeenCalled();}); it('classifier outage does not fall back to keyword routing',async()=>{jest.spyOn(global,'fetch').mockRejectedValue(new Error('secret'));await expect(service.ask({message:'کیف پول'},{id:'alice'})).rejects.toThrow(UNAVAILABLE);expect(prisma.user.findUnique).not.toHaveBeenCalled();});
+42 -13
View File
@@ -2,6 +2,11 @@ import { Injectable, NotFoundException } from "@nestjs/common";
import { Prisma } from "@prisma/client"; import { Prisma } from "@prisma/client";
import { PrismaService } from "../prisma/prisma.service"; import { PrismaService } from "../prisma/prisma.service";
import { PaginationDto } from "../common/dto/pagination.dto"; import { PaginationDto } from "../common/dto/pagination.dto";
import {
createPaginationMeta,
extractSearchTokens,
calculateRelevanceScore,
} from "../common/utils/search.utils";
@Injectable() @Injectable()
export class WikiService { export class WikiService {
@@ -19,33 +24,57 @@ export class WikiService {
const sortBy = allowedSortFields.includes(rawSortBy) ? rawSortBy : "term"; const sortBy = allowedSortFields.includes(rawSortBy) ? rawSortBy : "term";
const whereClause: Prisma.ScientificTermWhereInput = {}; const whereClause: Prisma.ScientificTermWhereInput = {};
if (search) { const tokens = extractSearchTokens(search);
if (tokens.length > 0) {
const mode = "insensitive" as const;
whereClause.OR = [ whereClause.OR = [
{ term: { contains: search, mode: "insensitive" } }, { term: { contains: search, mode } },
{ definition: { contains: search, mode: "insensitive" } }, { key: { contains: search, mode } },
{ definition: { contains: search, mode } },
...tokens.flatMap((token) => [
{ term: { contains: token, mode } },
{ key: { contains: token, mode } },
]),
]; ];
} }
const skip = (page - 1) * limit; const safePage = Math.max(1, Number(page) || 1);
const safeLimit = Math.max(1, Number(limit) || 10);
const skip = (safePage - 1) * safeLimit;
const [data, total] = await Promise.all([ const [rawTerms, total] = await Promise.all([
this.prisma.scientificTerm.findMany({ this.prisma.scientificTerm.findMany({
where: whereClause, where: whereClause,
skip, skip: tokens.length > 0 ? undefined : skip,
take: limit, take: tokens.length > 0 ? 100 : safeLimit,
orderBy: { [sortBy]: sortOrder }, orderBy: { [sortBy]: sortOrder },
}), }),
this.prisma.scientificTerm.count({ where: whereClause }), this.prisma.scientificTerm.count({ where: whereClause }),
]); ]);
let data = rawTerms;
if (tokens.length > 0 && search) {
data = [...rawTerms]
.map((t) => ({
term: t,
score: calculateRelevanceScore(
{
slug: t.key,
title: t.term,
description: t.definition,
},
search,
tokens,
),
}))
.sort((a, b) => b.score - a.score)
.map((item) => item.term)
.slice(skip, skip + safeLimit);
}
return { return {
data, data,
meta: { meta: createPaginationMeta(total, safePage, safeLimit),
total,
page,
lastPage: Math.ceil(total / limit),
limit,
},
}; };
} }
+30
View File
@@ -0,0 +1,30 @@
# Narrow auth schema operation — approval required
## Exact scope
`auth-schema-reconcile.sql` adds only users.auth_expires_at TIMESTAMPTZ NULL, stage_test_session VARCHAR(64) NULL, stage_test_generation UUID NULL (no defaults/backfill), and prepare_workflow_outbox with its original CHECKs, three RESTRICT FKs, task uniqueness, lease and due indexes, including nullable not_before. No existing rows changed, no auth behavior disabled, no Prisma metadata altered.
Read-only production PostgreSQL 16.14 catalogs verified all three users columns and outbox absent; users.id and orchestration_tasks/runs/budget_ledger.id are UUID PKs. Existing users wallet CHECK and orchestration constraints stay intact. Production has six ledger rows (one historical rolled-back admin_modules attempt), no Oct22–24 entries despite orchestration objects existing. Never run generic migrate deploy or mark whole pending history applied.
Historical principal migration at e036c5d has two columns, SHA256 8b4fe1fdedd2ae459b720f78479cfcb13da465eec821b422ece5e9bb41dc47ae; 80a2e18 edited it to three, SHA256 a458a94329b1ad078298b042ae0bd2e25439c1f0bb5a086beb55c517d9e0aa28. Read-only Stage ledger records the latter, not the former. Preserve both historical files unchanged here. This operation is separately journaled by CI/backup receipt, not invented Prisma history. Broader baseline/history repair remains separate work.
## Execution contract
Dedicated push workflow `auth-schema-reconcile.yml` uses DEPLOY_KEY and pinned DEPLOY_KNOWN_HOSTS, fixed SSH endpoint, isolated immutable Git checkout; it does not deploy applications. It accepts only exact branches `ops/auth-schema-stage` and `ops/auth-schema-production`, mapping their full refs to Stage and production respectively. It requires REVIEWED_AUTH_SCHEMA_COMMIT matching the event SHA and checks detached checkout HEAD equals that SHA. SQL digest is fixed to `8a22f3e89efb3dacc24f3ed9337ae87d0b4345da003a607bc1994478f69c6feb`, approval ID to `CEO-AUTH-SCHEMA-20261025`; neither is push-supplied input. Production additionally requires PRODUCTION_AUTH_SCHEMA_APPROVAL = SHA:SQL_SHA256:APPROVAL_ID and STAGE_AUTH_SCHEMA_ACCEPTANCE = SHA:SQL_SHA256, provisioned only after real review and Stage auth acceptance. These are explicit approval records, not automatically issued receipts. The repository's workflow/secret permissions must restrict dedicated-ref mutation to trusted maintainers; unrestricted malicious workflow edits can bypass any workflow-local gate. Review/protect this boundary before provisioning production approval.
Stage already has the DDL: Stage mode backs up production read-only, restores into isolated network-none temporary PostgreSQL, applies exact SQL there, compares resulting catalog with Stage read-only, and writes a SHA-bound structural receipt only. Production requires that receipt, repeats fresh full backup and restore/patch rehearsal, then executes only exact approved SQL. Full dumps remain mode600 host-only under /opt/backups/canina-auth-reconcile; never upload/log PII. Backup nonempty and pg_restore TOC checked. Restore errors/capacity failure stop before DDL. tmpfs is capped at 1GiB: if full restore exceeds capacity, separately review capacity rather than skipping restore. Existing read-only schema backup was 94,694 bytes / 67 tables, no PII copied; its restored PostgreSQL rehearsal is genuine, not a full data-backup recovery claim.
SQL lock_timeout 3s, statement_timeout 30s, idle transaction 60s; advisory lock plus host flock. DDL transactional; lock/contention failure aborts all. No automatic retries. Re-execution with existing outbox fails closed pending comparison, rather than silently accepting drift. Stage/production outputs compare columns/types/nullability/defaults, all outbox constraints/indexes to fresh rehearsed expected schema.
## Gitea 1.22.6 trigger semantics and operator sequence
Gitea [1.22 comparison](https://docs.gitea.com/1.22/usage/actions/comparison) explicitly marks `workflow_dispatch` ignored. The [v1.22.6 notifier implementation](https://github.com/go-gitea/gitea/blob/v1.22.6/services/actions/notifier_helper.go) resolves the pushed ref's commit, detects workflows at that commit and records `Ref` and `CommitSHA` on the run. Push is not default-branch-only. The dedicated branch must therefore contain this workflow and point to the **final integrated reviewed commit**, not a new trigger-only commit. Existing app deployment listens only to `main`/`develop`, not either operations branch.
After independent review/authorization, a trusted operator can push `<REVIEWED_FULL_SHA>:refs/heads/ops/auth-schema-stage` to origin. Inspect that CI run's SHA and structural receipt, then complete real Stage auth tests. Only after separate production and Stage acceptance approval records exist for the **same** SHA/digest may the operator push `<REVIEWED_FULL_SHA>:refs/heads/ops/auth-schema-production`. No empty commits, merges, arbitrary ref inputs, secret updates by this workflow, automatic acceptance, or app promotion. A no-op push does not retrigger; do not change the reviewed SHA to manufacture a run. Any SHA change requires fresh review, approval bindings and Stage evidence. Workflow preparation has not pushed either branch, changed secrets/protections or executed the operation.
## Acceptance and rollback
1. Parent DBA review exact commit/diff plus SQL hash and workflow trusted-ref/secret permissions. Approve read-only production full backup + isolated full restore scope separately from production DDL.
2. Run Stage workflow from exact commit; inspect successful backup/restore/catalog comparison. Existing Stage backend must pass ordinary admin password login + protected dashboard, OTP flow with authorized principal, refresh, and expiry/session/generation rejection tests. Do not manufacture acceptance if no approved credential/test principal is available. Record actual test run identifiers before setting Stage acceptance approval.
3. Obtain explicit approval: execute only this commit's SQL in caninodb_prod, three nullable users columns + empty outbox and declared constraints/indexes, 3s lock/30s statement budgets, no unrelated migrations/history writes/seeds. Provision approval binding SHA, SQL digest, approval record. Trigger production workflow, inspect terminal CI log. No production execution has been performed during preparation.
4. Release separately via existing code-only develop→Stage→main CI, using actual regenerated backend client, runtime-image/schema guard, immutable image receipts and authenticated login/OTP/refresh/protected data acceptance. Keep current compatible backend until this passes. Schema approval alone does not authorize application promotion.
5. Before commit failure: transaction rollback. After successful DDL: leave additive nullable fields/table intact, roll back application to known compatible immutable image via approved CI; do not DROP columns or outbox after writes. Restore full backup only under separately approved incident/data-loss recovery process. Existing backup tables remain untouched.
## Verified preparation / limitations
Disposable network-none PG16 schema-only restore and exact SQL executed successfully (see JSON). Missing-column SELECT failed before patch and passed after; invalid status rejected; second application rejected without changes; container removed. Independent reviewer found SQL definition matched history; requested stronger gating, Stage preexisting-schema handling, capacity awareness and postcondition validation, addressed or explicit prerequisites above. Full-data restore and dedicated workflow SSH path are implemented but not yet executed in actual CI. No production writes or deployments occurred. Approval/environment gates must not be represented as production repair completion.
+14
View File
@@ -0,0 +1,14 @@
{
"schema_backup_bytes": 94694,
"schema_backup_sha256": "9c6367a06acaf97c1afe9355e4306d2a10f878b7fe156c7dbc5d58d675262c72",
"schema_tables": 67,
"pii_copied": false,
"postgres": "16.14",
"restore_and_patch_seconds": 3.669,
"pre_patch_missing_columns_failed": true,
"post_patch_queries": " auth_expires_at | stage_test_session | stage_test_generation \n-----------------+--------------------+-----------------------\n(0 rows)\n\n count \n-------\n 0\n(1 row)\n\n count \n-------\n 0\n(1 row)\n\n",
"constraints": " conname | pg_get_constraintdef \n---------------------------------------------+-----------------------------------------------------------------------------------------------------------\n prepare_workflow_outbox_attempts_check | CHECK (((attempts >= 0) AND (attempts <= 3)))\n prepare_workflow_outbox_pkey | PRIMARY KEY (id)\n prepare_workflow_outbox_reservation_id_fkey | FOREIGN KEY (reservation_id) REFERENCES orchestration_budget_ledger(id) ON DELETE RESTRICT\n prepare_workflow_outbox_run_id_fkey | FOREIGN KEY (run_id) REFERENCES orchestration_runs(id) ON DELETE RESTRICT\n prepare_workflow_outbox_status_check | CHECK (((status)::text = ANY ((ARRAY['PENDING'::character varying, 'DONE'::character varying])::text[])))\n prepare_workflow_outbox_task_id_fkey | FOREIGN KEY (task_id) REFERENCES orchestration_tasks(id) ON DELETE RESTRICT\n prepare_workflow_outbox_task_id_key | UNIQUE (task_id)\n(7 rows)\n\n",
"invalid_status_rejected": true,
"repeat_execution_rejected_without_writes": true,
"production_writes": false
}
+9
View File
@@ -0,0 +1,9 @@
# Host disk retention
Successful authenticated CI rollout runs release-retention.py. Default keep policy is only the current active release per environment; Docker mounts and Compose working directories always protect older still-used artifacts. Dry/unpublished source and unknown ignored files are preserved, so this is not a hard quota. CI restores only its own tracked nginx/dockerignore render changes after successful acceptance. New clones use sparse checkout to omit the 85 MiB tracked graphify-out history. No node_modules were bundled in the audited releases: their ~218 MiB is tracked source/assets plus an independent ~44 MiB Git store. Historical dirty releases require individual source review; never reset them for cleanup.
Retained small private runtime configuration is copied mode0600 under .retained-runtime before deleting a clean obsolete release. This avoids secret deletion; this archive is not a release rollback and requires explicit secret retention review separately. No volumes, databases, sessions, evidence, images or build cache are deleted.
The CI-installed canina-disk-watch.timer checks every five minutes with stdlib Python, no model calls. It logs daemon.err and returns nonzero at >=85% usage or <10GiB free. This is local detection, NOT off-host paging. systemctl status canina-disk-watch.service and journalctl -t canina-disk-watch expose alarms. Monitoring does not guarantee the disk cannot fill.
Audit 2026-10-26: Docker daemon already bounds new json-file containers to 3x10MiB and BuildKit GC to 6GB. Fifteen pre-existing containers (including Nexus, Gitea, databases and proxy) have empty LogConfig and remain unbounded until their owners roll them through their own Git/CI. Journald has no explicit SystemMaxUse and currently occupies 1.3GB. Nexus data is real persistent storage; retention tasks were not authenticated/audited and no blobs were deleted. Neither unrelated service config nor daemon/journal configuration is changed by Canina CI. Worktree branches with unpushed commits remain intentionally retained. These residual growth mechanisms prevent any honest claim of a globally bounded host or <50GB total.
+69
View File
@@ -0,0 +1,69 @@
# Orchestration v4: Hermes runtime seam (review-only)
## Installed evidence / compatibility
Read-only inspection of `canina-hermes` source at `/opt/hermes` and Docker metadata:
- Running image ID: `sha256:373ddd5e6649f525b17993e1c885cdf1352127f8e98fd329140a73237125e52f`.
- Registry digest (pinned template): `nousresearch/hermes-agent@sha256:9774f4f39a9bb8c2f68ce728ed5e99ddbad282163be56764afacf88ed952b784`.
- Current command is `gateway run`, **not** `serve`. Loopback 9119 connection refused. This implementation does not claim a live dashboard integration or start one.
- Existing `/opt/data` mount is external volume `canina-hermes_canina_hermes_data`; preserve it. Read-only cron JSON count: **17 jobs, 0 enabled**. Paused state is `enabled:false`, not a `paused` boolean. No cron/runtime/config mutation was made.
- Existing untracked `/opt/services/ai/canina-hermes/compose.yml` remains untouched.
Sources inspected: `hermes_cli/web_routers/{status,profiles,models,sessions,analytics,cron,chat_ws}.py`, cron scoping helpers, `cron/jobs.py`, `hermes_cli/inventory.py`, `hermes_cli/dashboard_auth/{routes,middleware}.py`, `hermes_cli/web_server{,_chat}.py`, `tui_gateway/ws.py`.
## Supported allowlist
| Service method | Installed upstream contract | Public projection |
|---|---|---|
| health | GET /api/health | ok/version/commit/auth_required |
| status | GET /api/status?profile= | version/gateway_running/gateway_state/overall/active_agents |
| profiles | GET /api/profiles -> {profiles:[]} | name/is_default/gateway_running, filtered by backend scope |
| modelInfo | GET /api/model/info?profile= | model/provider/effective_context_length |
| modelOptions | GET /api/model/options?profile= | provider slug/name + model ID strings |
| usage | GET /api/analytics/usage?profile=&days= | period_days and four numeric totals |
| sessions | GET /api/sessions?profile=&limit=&offset=&full=false&order=recent | ID/profile/source/is_active, total |
| crons | GET /api/cron/jobs?profile= -> array | ID/profile/enabled |
| pauseCron | POST /api/cron/jobs/{id}/pause?profile= | ID/profile/enabled |
| resumeCron | POST /api/cron/jobs/{id}/resume?profile= | implemented adapter; **disabled in registered service** |
No generic route/HTTP/RPC proxy. No model setter, config, secrets, PTY, trigger, deletion, raw transcript or raw logs. Status is not fabricated if unavailable. Numeric nulls/malformed/missing required fields produce CONTRACT (some empty analytics stores may therefore be unavailable). Unknown upstream fields are dropped, never forwarded; this is intentional forward-compatible redaction, not raw JSON passthrough. Scope mismatch is forbidden. Arrays cap at 1000, upstream bytes at 256 KiB, in-flight requests at 4, whole request/token budget at 5 seconds, no retries, redirects forbidden. The production fetch honors AbortSignal. Error messages never include upstream response/URL/token/exception. Do not log request headers or config objects.
Upstream GET /api/sessions can auto-archive internally; we inspected source only and did not call it against production. Some model inventory endpoints warm caches/probe providers. Classify these as managed reads, not guaranteed filesystem-pure operations.
## Authentication and WS discovery
- Non-loopback dashboard binds engage the provider-verified auth gate. REST supports provider-verified Bearer session tokens. Legacy loopback accepts session header/Bearer; **a Canina JWT or API_SERVER_KEY is not interchangeable**.
- POST `/api/auth/ws-ticket` needs verified `request.state.session`; response `{ticket,ttl_seconds}` is single-use / 30 seconds. Do not mint tickets for a browser or copy credentials into browser URLs.
- Installed WS: `/api/ws`, `/api/console`, `/api/events`, `/api/pub`, `/api/pty`; **no assumed `/api/chat/ws`**.
- `/api/ws` uses newline-delimited JSON-RPC and `gateway.ready`; same dispatcher as TUI, broad privilege. Gated admission supports a ticket, including subprotocols `hermes-gateway-v1` and `hermes-gateway-ticket.<ticket>`; legacy process token is rejected in gated mode. Internal process credentials must never be extracted.
- We deliberately do not bridge a powerful socket without a verified session/run ownership and event allowlist contract. `chat`/`control` return UNSUPPORTED after policy; event dispatch returns FORBIDDEN even with policy approval. No WS dependency, background connection, reconnect, or ticket endpoint is exposed.
## Wiring (owner integration step, no app.module.ts changes here)
Import `HermesManagementModule.register(config, authorizer)` in the owning backend module, then inject **HermesIntegrationService**, never the adapter into browser controllers. Registration exports the service only and defaults to deny-all policy. Example configuration:
```ts
HermesManagementModule.register({
origin: 'http://canina-hermes:9119',
token: () => secretStore.read('hermes_dashboard_access_token'),
}, backendRuntimeAuthorizer)
```
Supply a provider-verified, short-lived Hermes token through backend secret storage (template references `/run/secrets/hermes_dashboard_access_token` only). Provision/refresh is an operator responsibility; this change neither extracts existing runtime secrets nor invents a login flow. No token in database/UI/env templates.
Controllers must verify Canina admin JWT, resolve subject/profile scopes from trusted backend data (not request DTO), enforce permission and rate limit/audit, translate HermesError codes to safe API errors (AUTH_REQUIRED/UNAVAILABLE -> 503, FORBIDDEN ->403, LIMIT ->429, CONTRACT/UNSUPPORTED ->502/501). Never forward upstream errors. `RuntimePrincipal` is an internal context, not a user input DTO. Authorizer must independently verify subject/action/profile. Missing/throwing authorizer denies. Registered module hard-disables resume; enabling requires an explicit reviewed code change. Resume can immediately make overdue recurring jobs due: never test it on production.
## Disabled event dispatch design
No listener, cron, poller, outbox consumer or webhook is registered. A future dispatcher must use backend-verified event identity, durable outbox and idempotency, server-resolved department/profile/run ownership, permission per action, payload minimization/redaction, budget and approval policy. Then use a tested narrow execution transport; never map arbitrary event text to TUI RPC or `/api/pub`. Unknown event/schema/principal/approval/ownership -> reject with no IO. Do not enable before isolated acceptance proves interruption, stream bounds and safe tool-output projection.
## Manifests and verification
`infra/hermes-runtime/compose.template.yml` is **not a deployable replacement yet**: manual-only profile, no automatic restart/public ports/socket/credentials, preserves external data volume, dedicated external backend network. It intentionally retains `gateway run`; dashboard/auth/network topology and gateway egress need an approved migration design. Do not run alongside current service sharing the same writable state. Never `down -v`.
`.gitea/workflows/hermes-runtime-contract.yml` is manual contract review only, no deploy job, SSH, runtime secret or event dispatch. Existing deploy workflow untouched. Compose parsed with `docker compose ... config --quiet`; no containers deployed.
Tests: `cd backend && npm test -- --runInBand hermes-management` (14 assertions across 4 suites); strict isolated typecheck/build `npx tsc -p src/hermes-management/tsconfig.contract.json [--noEmit]`; full backend `npm run build` after isolated `npx prisma generate`. All passed. Local HTTP transport is exercised on ephemeral loopback, not production. TDD failures were observed for missing adapter, inventory methods, integration service, module and concurrency limit before implementations. No live authenticated dashboard or WS execution was exercised. Host has no Node; disposable node:22-bookworm runners used. Initial shared dependency resolution and offline Prisma binary download failed; fresh worktree dependencies and isolated network-enabled Prisma generation resolved them, without DB connection/migration.
Final verification: full backend Jest regression **93 suites / 771 tests passed**; scoped ESLint and strict typecheck passed, full `tsc -b` build passed. Existing SSL/payment negative tests print expected error logs despite passing. No deploy or production action performed.
+95
View File
@@ -0,0 +1,95 @@
**Superseded wiring/provenance: see [snapshot repair](hermes-snapshot-provenance.md). Do not use literal grants or the old DNS alias below.**
# Runtime read vertical slice (not deployed)
Branch feature/v4-runtime-completion, base 5507fbc. No AppModule, live gateway,
production database, cron, dispatch, or existing compose was changed.
## Parent registration
Import `RuntimeReadModule.register({ '<verified-user-id>': ['default', '<department>'] })`
from `backend/src/hermes-management/runtime-read.module` into AppModule.
This module uses the existing Passport `jwt` strategy (DB-resolved user identity),
not the API-key fallback. Parent must retain AuthModule/JwtStrategy initialization.
Missing grants deny. Never construct grants from browser body, JWT profile claims,
or unreviewed environment input. Allowlist is copied/frozen. Admin/SUPER_ADMIN
role AND exact subject grant required; API-key identities forbidden.
GET `/admin/orchestration/runtime/{health,profiles,status,usage,sessions,schedules,model-info}`.
All except health/profiles require exactly one allowed `profile` query string.
Usage accepts days 1..365 (30); sessions limit 1..100 (20), offset 0..10000 (0).
Unknown parameters on profile routes rejected. Profiles is filtered to server grants.
Responses use existing adapter projections, no prompts/transcripts/config/tokens.
Missing/forged JWT ->401; missing grant/role/profile ->403; runtime auth/network/
contract failure ->503 `Runtime unavailable`; limits ->429. No browser Hermes
cookie, credential, socket ticket or mutation handler is provided.
Mount backend `/run/secrets/hermes_username` and `hermes_password` as files.
Only these fixed secret paths are read, after authorization. Broker login/cache
stays server-side. Backend and isolated inventory runtime must receive matching
credentials. Runtime additionally mounts `hermes_signing_key` (>=32 random chars).
Do not put credentials in YAML/env, commands, logs or Git. Rotate key to invalidate
sessions; rotate password and restart inventory plus backend to clear cached access.
Stateless old sessions remain valid until TTL/key rotation.
## Deliberately separate snapshot topology
Installed Hermes `serve` lifespan starts reconciliation and hosted-room recovery;
GET sessions auto-archives. Sharing its writable home with existing gateway is
therefore NOT a safe read-only sidecar. `serve.py` runs the pinned installed app
with lifespan OFF and an outer exact GET allowlist, password-login only and all
WebSockets denied1008. It does NOT start scheduler/gateway/MCP/rooms/provider chat.
The existing gateway and external volume `canina-hermes_canina_hermes_data` remain
unchanged, solely owned by existing gateway. Inventory mounts an independently
provisioned snapshot volume `canina_hermes_inventory_snapshot`; it NEVER mounts
original home. Its incidental session auto-archive writes affect only snapshot.
This is snapshot inventory, NOT live runtime freshness/status acceptance. A copy
of gateway PID state is not evidence of live gateway health. UI must not claim live
readiness from this deployment. Parent should expose snapshot provenance/freshness
before enabling it for business use.
Provisioning must use an approved consistent SQLite backup/checkpoint/export and
redacted profile config inventory, not raw `cp` of changing SQLite/WAL or credentials.
No automatic snapshot job is installed here. No secrets need be copied from live
home. Review which configs the model/status APIs need and omit auth.json/.env.
Missing store/schema -> unavailable, not fabricated empty healthy telemetry.
Dedicated internal network must contain only backend and inventory; do NOT connect
existing gateway with same `canina-hermes` DNS alias. Backend name resolves inventory.
Inventory network must have no external egress. Compose refers to external network;
operator must create it `--internal`. No host ports/socket are published.
## CI ownership / apply
`compose.readonly.yml` is deployable ONLY after external snapshot, internal network,
secret files and backend mounts/registration are provisioned. `ci-apply.sh` requires
CI=true, exact reviewed HEAD SHA, clean checkout, snapshot-reviewed assertion,
existing volume/network/files, then compose config/up. Never run alongside any
other inventory instance writing same snapshot. CI job fragment is tracked under
infra ownership; parent owns real workflow wiring and approval environment. No
active deployment trigger added. Existing review-only compose template is unchanged.
## Executed evidence
Remote `/opt/services/canina/validation/v4-runtime-completion/`:
- read-red.log missing controller regression; read-green.log 6 suites/27 tests.
- read-http-green.log 7 suites/30 tests: real Nest HTTP with signed JWT strategy,
bad signature/no auth401, ungranted admin403, allowed admin200, no cookie,
mutation404. This uses a mocked runtime service, not live Canina credentials.
- pinned-http.log exact installed image FastAPI login/protected inventory:
wrong password401, real login200/HttpOnly provider-verifiable token, profiles200,
tampered token401. No lifespan/live home.
- serve-http.log actual loopback TCP9119 in network-none disposable pinned image:
unauth inventory401, wrong password401, login200, profiles200, health auth true,
mutation/config/ws HTTP404. Generated test-only credentials. No live volume.
- ws-red.log existing socket rejection code differed; ws-green.log explicit
outer boundary denies authenticated sockets1008 independently of upstream tickets.
- build.log private Prisma generation and full backend tsc build exit0.
Pinned local exact image ID sha256:373ddd5e6649f525b17993e1c885cdf1352127f8e98fd329140a73237125e52f;
tracked registry digest sha256:9774f4f39a9bb8c2f68ce728ed5e99ddbad282163be56764afacf88ed952b784.
Node22 disposable runner copied read-only source/dependency donor privately;
no DB migration. broker-pinned-e2e.log proves actual compiled Node broker -> TCP pinned Hermes login -> adapter -> policy-filtered inventory (and deny zero secret reads). Nest HTTP authentication tested separately; these tests do not establish full Canina application E2E, snapshot
refresh, CI deployment, live gateway truth or business workflow acceptance.
Those remain explicit integration/provisioning gates, not claimed completion.
Final full non-DB regression: 106 suites / 850 tests pass; expected legacy negative SSL/payment logs. Scoped ESLint has zero errors, six type-safety warnings; full build passes. No RELEASE_AUTHORIZE integration suite run.
+86
View File
@@ -0,0 +1,86 @@
# Snapshot provenance repair — integration contract
This is independent snapshot inventory, **not a live Hermes executor**. No Production,
deployment, live gateway edits, or RELEASE_AUTHORIZE execution is included.
## Parent-owned application wiring
Keep AuthModule/JwtStrategy. Replace literal user grants in parent-owned app.module.ts with:
```ts
RuntimeReadModule.registerFromFile('/run/secrets/hermes_runtime_grants')
```
Nest supports the resulting Promise<DynamicModule> in imports. Alternatively pass the
reviewed nonsecret file `/etc/canina/runtime-grants.json`. No env/JWT/browser grant
input is accepted by this registration. File is JSON object mapping exact verified DB
user IDs to nonempty unique profile arrays; `{}` explicitly denies everyone. Missing,
malformed, symlinked, group/world-writable, oversized files fail startup closed. Mount
read-only and provision via reviewed configuration/secrets management; do not commit
real user grants. Existing explicit register(grants) remains for tests/legacy consumers.
Backend also mounts `/run/secrets/hermes_username` and `hermes_password` read-only.
No app.module.ts modification belongs to this commit.
## Required coordinated origin change
Authenticated management module and broker now exclusively use
`http://canina-hermes-inventory:9119`. compose.readonly.yml uses the distinct alias
`canina-hermes-inventory`, NEVER `canina-hermes`. Generic adapter allowlist retains
both reviewed exact origins for compatibility with separate existing consumers.
No arbitrary origin/env URL accepted. Parent must cherry-pick broker/module/adapter
and inventory compose together; do not add an alias to the existing gateway.
No deployment performed. External network should still be internal and only contain
backend/inventory; the distinct alias cannot shadow the live canina-hermes hostname.
## Snapshot exporter/operator gate
Every independent inventory root must include `snapshot-manifest.json`:
```json
{"schemaVersion":1,"source":"snapshot","capturedAt":"2026-10-23T12:00:00Z"}
```
The example is a schema example, NOT an actual capture attestation. Exporter must
write the real capture instant from the approved consistent export. Never copy the
example, use startup time, filesystem mtime, or claim this change captures/refreshes
snapshots. Missing/invalid/future manifest prevents startup. It is revalidated per
successful GET; invalid after startup returns503. Manifest is exporter metadata,
not a cryptographic proof of consistency. Immutable reviewed export provisioning
remains required. Fresh means age <=3600 seconds, otherwise stale; even fresh is
NOT live readiness. No snapshot scheduler installed.
## Additive public response fields / panel handoff
All object read DTOs (health/status/usage/sessions/model-info) add:
`provenance:{source:'snapshot',capturedAt:string,ageSeconds:number,freshness:'fresh'|'stale',liveProcess:'unknown'}`.
Profile and schedule array shapes are preserved: provenance is on each row. Empty
arrays have no rows to annotate; use the health response to display snapshot metadata.
Profile rows add `liveGatewayState:'unknown'`; status adds the same plus
`liveActiveAgents:null`. Existing required scalars remain typed but are conservative
placeholders: `gateway_running:false`, `active_agents:0`, `gateway_state:null`,
`overall:'unknown'`. False/zero MUST NOT render as measured offline/idle: when
provenance.source is snapshot use the explicit unknown fields, label snapshot and
show capturedAt/freshness. Health.ok only means inventory HTTP app responsiveness,
never live gateway readiness. Profile existence is inventory availability, NOT
process readiness. Adapter enforces provenance on dedicated snapshot origin and
conservatively overwrites copied PID-derived status/profile scalars again.
Installed status handler was unsafe here: it probes gateway HTTP/PIDs/platforms and
can stall despite this being an independent snapshot. Snapshot server replaces that
route with measured package version and explicit unknown process fields; no status
probe is run. Password auth/mutation denial/WebSocket denial remain intact.
## Executed acceptance
Remote disposable network-none exact pinned Hermes image, no original volumes:
manifest-missing regression failed first; TCP login/profile/health/status provenance
and stale capture assertions now pass; authenticated sockets denied1008. Disposable
Node22 copy of source/dependencies: 9 hermes-management suites /34 tests pass and
full backend tsc build passes. Adapter copied-live-state regression failed first;
grants-loader missing-function regression failed first. Compiled actual Node broker
-> TCP pinned server -> adapter -> policy-filtered profiles/status passes, deny reads
zero credentials. Test timestamps/credentials are fixtures, not live telemetry.
The first HTTP retry raced fixture startup and returned UNAVAILABLE; retry after
server startup passed. No claim of full app/user-flow or live runtime integration.
Full non-DB Jest regression: 108 suites/854 tests passed; 1 suite/18 tests skipped. No RELEASE_AUTHORIZE suite was enabled.
+21
View File
@@ -0,0 +1,21 @@
# Queued Gate1 validity correction
## Read-only Stage evidence (2026-10-24)
Task `565ace1f-8cfc-4447-b978-66c36e7b767b`: READY, version 4, PREPARE/STAGE_PREPARE, proposer `pmo`. Approval `30f8ce5c-ce00-4885-8eea-3c1bb5a7e8b0`: gate 1 APPROVED by independent actor `4a0afc72-0fd4-4d76-825b-aea13f00e880`, created 05:37:54.808Z, **expires 06:37:00Z**. runId/artifactHash/commitSha/environment on that Gate1 decision are null (normal Gate1 task binding, not Gate2 binding). Recovery event sequence 4 queued the valid approval at 06:22:06.891Z; outbox PENDING, attempts 0, runId null, notBefore null. At 09:15Z it was truly expired. Editorial claim queries newest decision for this task/gate, not a version-specific approval; it correctly rejects it. No evidence of a binding/version mismatch.
## Behavior
Persisted state remains READY; separate displayState reports blocked/renewal-required on reads. No approval is extended automatically. Existing independent reviewer authorization and task row lock protect a new ordinary Gate1 APPROVED decision. Renewal is limited to READY with a latest expired independent APPROVED decision and an unstarted PENDING outbox. It appends a decision and PREPARE_GATE1_RENEWED event, increments task version, preserves task scope/commit/budget and the existing outbox/notBefore. It rejects scheduling changes, active/attempted execution, valid approvals and self-review. Claim logic and its kill/budget/lease checks remain unchanged.
## Owner steps after parent CI integration
1. Sign in normally as an independent SUPER_ADMIN (or existing provisioned canonical owner reviewer); do not use worker identity or impersonation.
2. Open orchestration, refresh server state, find this same task in owner decisions marked `مسدود — تأیید Gate1 منقضی شده؛ نیازمند تأیید مجدد مالک`.
3. Review immutable scope, acceptance criteria, commit, environment and 20-cent budget; open ordinary Gate1 approval. Confirm bounded work explicitly. Renewal keeps the previous schedule; no new scheduled-start input is shown.
4. Confirm once. The existing POST `/api/admin/orchestration/tasks/565ace1f-8cfc-4447-b978-66c36e7b767b/gates/1/decide` uses `{decision:"APPROVED",expectedVersion:4,idempotencyKey:<fresh unique key>}` (use refreshed version if changed). Notes optional; omit expiresAt for backend 24-hour validity. Retry only the identical payload/key after an ambiguous response; 409 requires refresh.
5. Verify new independent decision, PREPARE_GATE1_RENEWED event and version increment. Do not recreate task or enqueue another outbox. Parent performs separately authorized runner/live acceptance.
## Verification
Frozen 09:15Z regression observed RED before implementation for READY representation and ordinary renewal; editorial exact 403/read mismatch observed RED; UI owner queue observed RED. GREEN: 41 backend scoped tests, 25 admin scoped tests. Disposable PostgreSQL test passes real simultaneous renewal/replay and claim serialization, expired denial, immutable old approval retention, one outbox/one claim. Backend build, Prisma client generation, admin build and application TypeScript check passed in Node22 with private donor dependencies. Initial build permission/stale-generated-client setup failures corrected only in private worktree copies. No Stage/Production DB mutation, approval, runner invocation, push or deploy.
@@ -0,0 +1,22 @@
# Orchestration v4 read-only integration verification
Base e5c83e87fe2d52d06eb36532fa9e354570678c43 plus cherry-picks admin a34c2a9, runtime bd58cc4, router b0f4636. Separate remote worktree; no dirty core edits, pushes, deploys, DB access or runtime changes.
## RED → GREEN proof
- New backend HTTP boundary suite initially failed 4/4: mutation returned 201, BigInt serialization returned 500, overview missing (404). After integration: 4/4 pass, covering all mutation routes, anonymous/customer rejection, secret projection, actual overview and unavailable resources.
- New UI fail-closed capability test initially failed because Create bounded work was visible without authorization. After capability gating: 7/7 command-center tests pass. Existing explicit action/binding/retry tests retained.
## Disposable remote validation
Node 22 bookworm, network none, userns host (host Docker remapping prevents normal bind mounts), worktree source mounts, read-only sibling dependency cache. Vite cache directories are ephemeral tmpfs; no existing dependency trees changed.
- Backend focused aggregate: **13 suites, 65 tests pass** (orchestration, Hermes, router usage).
- Backend `tsc --noEmit`: exit 0. `npm run build`: exit 0.
- Backend changed controller/HTTP spec ESLint: exit 0, 8 unsafe-argument warnings (7 test harness, 1 existing any-typed Prisma result). Baseline subsystem lint had 256 errors/8 warnings largely inherited formatting; no full lint pass claimed.
- Admin focused aggregate: **5 files, 19 tests pass** (command center, orchestration/router adapters, creation, navigation).
- Admin `npm run build`: exit 0, existing unresolved font warning remains.
- Admin `tsc --noEmit -p tsconfig.app.json`: exit 2 with **33 inherited diagnostics** outside this change: legacy Approvals/Audit/HQ/Dashboard/ManagerActions/Tasks unused imports, Orders requiresRx missing, Symptoms ConfirmModal props/unused setter. No changed-file diagnostics. Full admin typecheck is NOT green.
## Security/release blockers
The committed legacy core permits gate-state bypass through generic transitions and lacks hardened replay/authorization/budget/kill-switch boundaries. It is retained unchanged for parent integration; every exposed v4 mutation is unconditionally denied by controller. Do not restore controller calls or enable execution until hardened core is merged and reverified.
Runtime dashboard not listening per parent investigation; no fabricated health or live availability claim. No trusted runtime identity/profile policy or runtime auth configured. Chat, cron mutations, execution/event dispatch, release execution stay disabled. Read-only inventory still requires orchestration schema migration through approved CI/CD, never manual DB changes. Backend read queries are currently full inventory and release evidence uses per-task reads; pagination/scaling remains future work.
Parent must inspect this commit and reconcile hardened core before any mutation milestone. No Stage promotion performed by this worker; admin typecheck failures remain explicit verification blockers for parent decision.
+50
View File
@@ -0,0 +1,50 @@
# Stage v4 rollout safety
## Scope and deployment boundary
Only a push to `develop` followed by the existing Gitea workflow may roll out this change. Do not run `deploy.sh` manually. Its CI marker is an accident guard, not an authentication boundary: runner permissions remain the security boundary. `main`, unknown branches and the former `stage-backend-only` bypass fail before Docker operations. Production is intentionally blocked pending separate review; no silent baseline/resolve is permitted.
## Tracked sequence
1. Acquire the Stage rollout lock (same lock as the retired backend-only path).
2. Fetch the branch and build images using the existing workflow. Build failure leaves old applications running.
3. Stop Stage frontend and backend (maintenance/outage; no promise of a custom 503 page).
4. Run the newly built backend image as an isolated one-off Prisma CLI job (`compose run --rm --no-deps --entrypoint ... migrate deploy`). No app command, published service ports or automatic baseline. Existing DB must already be running.
5. Only on migration success start backend. Require all nine v4 tables, the successful tracked migration receipt and an actual HTTP catalog response with the catalog envelope. HTTP acceptance has bounded retries and timeouts; no response body is logged.
6. On backend acceptance failure stop both applications and fail. Only after acceptance start frontend. CI success marker follows these gates. The shared support bot is not rebuilt/replaced by this Stage rollout.
Migration failure leaves maintenance in place; do not auto-restart old apps against a partly migrated schema. Diagnose from CI logs, restore from an authorized backup or ship a reviewed forward fix through CI/CD. Never `db push`, seed, silently `migrate resolve`, or manually apply live DDL.
## Verification (2026-10-22)
Strict RED/GREEN cycles captured missing rollout function, migration failure ordering, missing backend acceptance and missing CI/Production guard before implementation. `python3 scripts/tests/test_stage_rollout.py`: 3 passed. Shell tests simulate Docker failures to prove sequencing only; they do NOT certify a healthy release. `node --test scripts/tests/test_rollout_health.cjs`: 4 passed using a local HTTP server (503, HTML, incorrect envelope rejected; valid empty catalog shape accepted). These fixtures are not live health evidence.
`python3 scripts/tests/rehearse_rollout.py` performs only schema-only `pg_dump` and migration-history-only data dump from Stage. It restores into a fresh PostgreSQL 16 container with no network, no host ports, no persistent volume, and no customer rows. Prisma runs in that disposable container's network namespace using an existing generated v4 client/dependencies read-only from the core test worktree. Dumps have a private temporary directory and are removed on exit.
Observed output:
```
Applying migration `20261022000000_add_orchestration_v4_core`
All migrations have been successfully applied.
No pending migrations to apply.
PASS: actual Prisma legacy catalog/support and v4 relation queries
Restored 61 legacy tables; all business tables empty
PASS: unchanged legacy column definitions; 61 legacy queries; 9 v4 tables; migrate deploy repeatable
Disposable database/container removed; no live DDL performed
```
The first rehearsal hit a read-only nested mount creation error, cleaned up, and was corrected to mount only `prisma/` plus dependencies; subsequent rehearsals passed.
## Remaining acceptance constraints
- No push, actual deployment, live DDL, customer export, or Production change was performed. No live v4 health success is claimed.
- Schema-only rehearsal proves schema/query compatibility, not row-volume performance, locks under traffic, or business-data backfill behavior. All 61 legacy business tables were verified empty.
- Full image build/start and public frontend/admin/API acceptance still require the authorized CI rollout. The gate currently covers backend schema/catalog; frontend start success is not browser acceptance.
- Workflow now downloads the deployment entrypoint by triggering `github.sha` and passes `DEPLOY_SHA`. The entrypoint rejects missing/malformed SHA values, verifies that the commit belongs to the fetched deployment branch, and checks out that exact commit. Six disposable rollout tests cover sequencing, CI/Production guards, pin wiring and SHA validation. Actual runner execution and strong artifact/release attestation still require live CI acceptance; SHA pinning alone does not authenticate artifact evidence.
- Existing compose credentials are out of scope; no new credentials are added. Continue restricting runner access and runtime env files. Orchestration mutation/chat/runtime remain disabled in the integration base; this rollout does not enable them.
## Completion-branch rehearsal
The repository-relative rehearsal applied both `20261022000000_add_orchestration_v4_core` and `20261022190000_harden_orchestration_ledger` to a disposable database restored from Stage schema/history only. All 61 legacy business tables were empty, their column definitions were unchanged, nine v4 tables and actual Prisma queries passed, and a second deploy found no pending migrations. No live DDL or release execution occurred.
The workflow shell now stops on download failure. SHA-pinning and six rollout tests plus four HTTP fixtures are verified locally in disposable containers; they are not proof of an actual CI rollout or frontend acceptance.
+41
View File
@@ -0,0 +1,41 @@
# 9router admin consumption adapter
## Wiring (integration owner)
Import `RouterUsageModule` from `backend/src/router-usage/router-usage.module` into the root application's imports. This branch deliberately does not edit app.module.ts. Existing AuthModule/JWT strategy must be registered by the application. Route requires a JWT bearer user with admin/superadmin role; API-key authentication is deliberately not enabled for this sensitive endpoint.
Set backend-only `ROUTER_USAGE_CLI_TOKEN` using the existing router CLI auth token from the operator secret store. Optional `ROUTER_USAGE_BASE_URL` must be exactly `https://nr.parsaaghayi.ir` (an origin slash is accepted). Do not ship this token to the frontend. No environment/configuration was changed during implementation. No push/deploy performed; integration follows CI/CD and production needs separate Gate2.
## Exact API
`GET /admin/router-usage?period=7d` (plus the existing application global prefix, if any).
Allowed periods: `today`, `24h`, `7d`, `30d`, `60d`, `all`; default `7d`. Unknown query properties/custom from/to ranges and invalid periods return 400. Missing/invalid JWT is rejected by Passport; authenticated non-admin gets 403. Response is private/no-store.
Response fields:
- `source: "9router"`, `period`
- `status: "available" | "unavailable"`
- `reason: null | "not_configured" | "invalid_configuration" | "busy" | "upstream_unavailable"`
- `attribution: {scope:"9router_total", hermes:null, additive:false}`
- `freshness: {retrievedAt: ISO8601|null, sourceUpdatedAt:null, stale:null}`. Retrieval time is NOT a guarantee of provider freshness. The source exposes no authoritative updated-at for aggregates. No last-good cache is served.
- `capabilities: {errors:false, reasoningTokens:false, cacheWriteTokens:false, quota:false, customTimeRange:false}`
- `data: null | {totals, providers:[], models:[], accounts:[]}`
Every metrics object contains `requests`, `inputTokens`, `outputTokens`, `cacheReadTokens`, `cacheWriteTokens`, `reasoningTokens`, `errors` (number|null). Zero is retained only if upstream reported zero; absent/invalid counters remain null. Input/output/cache map to promptTokens/completionTokens/cachedTokens; cache-read is a subset of input, never add it again. Cache-write/reasoning/errors are always null because the stats contract does not expose these aggregates.
Provider rows: `{provider,...metrics}`. Model rows: `{model,provider,...metrics}`. Account rows: `{accountId,model,provider,...metrics,quota:{status:"unknown",remaining:null,resetAt:null,reason:"upstream_quota_get_mutates_credentials"}}`. Account rows are upstream account/model summaries, NOT unique account inventory; accounts without usage are absent. IDs are validated, nullable if unsafe; account names/emails are never returned. No raw upstream maps, logs, prompts, provider data or credentials are returned. Dimensions are different views of the same consumption: do NOT sum totals+models+accounts. Hermes attribution remains unknown; do NOT add Hermes telemetry to router totals.
## Deployed-source inspection and real probe
Read-only inspected running `9router` image `decolua/9router:vpn`: compiled `/app/.next/server/app/api/usage/stats/route.js`, `/app/.next/server/chunks/9100.js`, `/app/.next/server/middleware.js`, `/app/.next/server/chunks/7211.js`, providers routes and `/app/open-sse/services/usage.js`. No credential tables or router DB contents were dumped/modified.
Verified stats route accepts the periods above. `today` uses router-local midnight, `24h` rolling history; 7/30/60d use router-local daily buckets, `all` all retained daily aggregates. This is not arbitrary UTC timestamp filtering; retention/completeness is upstream-owned.
Authenticated internal GET probe returned HTTP 200, 5 provider summaries, 21 model summaries, 21 account/model summaries. Verified model fields: requests, promptTokens, completionTokens, cachedTokens, cost, rawModel, provider, lastUsed. Account fields additionally include connectionId/accountName. Only schema/counts printed; no keys or account values printed. Public HTTPS reverse proxy path was not live-authenticated, so its separate proxy authentication/network reachability remains an operator verification step.
Dashboard routes authenticate using `x-9r-cli-token` or valid `auth_token` session cookie. Normal inference API Bearer keys do NOT authenticate these dashboard routes. CLI token is NOT the contents of cli-secret: deployed middleware computes first 16 hex characters of SHA256(machine-id + "9r-cli-auth" + cli-secret). Probe derived it only inside the router process command and never emitted it; no new token or configuration was created.
**Security finding:** stats `byApiKey` map keys contain raw inference keys, even when row fields are masked. Adapter discards this map entirely and never logs response bodies/errors.
**Quota blocker:** `GET /api/usage/[connectionId]` calls refreshAndUpdateCredentials, including updateProviderConnection; OAuth refresh/retry can persist credentials. It is NOT read-only despite being GET. Therefore adapter does NOT call it. Provider quota handlers can return quotas (used/total/remaining/resetAt), messages or synthesized unlimited defaults; these cannot safely be treated as verified provider truth here. Quota reset grants exist in provider helpers but must never be consumed by this adapter. No safe deployed cache-only provider quota route was established. A separately reviewed router-side non-mutating, provenance/timestamp-bearing quota snapshot API is required before exposing live remaining/reset. Quota is unknown, never zero/unlimited fabricated. Connection inventory/status refresh is also not represented as quota truth.
## Bounds and verification
Only fixed-origin authenticated GET `/api/usage/stats` is invoked; redirect:error, abort after 5 seconds, streaming cap 1 MiB, <=2000 rows per dimension, <=4 concurrent requests per backend process. No retries or stale cache. Schema/transport/auth/rate-limit/oversize failures produce unavailable + null data without raw errors. No SQL, POST or token refresh.
Strict test-first slices observed missing contract, adapter, module failures before implementation. Disposable containers used existing backend image dependencies, read-only source mounts, network disabled and copied source into ephemeral /work; no host dependencies/build output or running containers changed. `npm run build` passed. Focused: 3 suites/24 tests passed. Full backend regression: 92 suites/781 tests passed (existing negative-path tests log expected payment/SSL errors). HTTP guard tests replace JWT authentication only and exercise real RolesGuard; deployed JWT strategy remains application-owned.
@@ -0,0 +1,53 @@
# Durable Stage cleanup verification
This change replaces the SHA-pinned transient timer with a root-owned intent journal
and a fixed host systemd retry worker. No host service is installed or enabled by
the CI credential command. The tracked `deploy.yml` → `ci-host-deploy.sh` →
`deploy.sh` path invokes `install-stage-principal-cleanup.py` from the verified
immutable release before `stage_rollout`. It atomically installs the root-owned
worker (0755) and supplied systemd units (0644), reloads systemd, enables/starts
the timer and verifies enabled/active state. Failure aborts rollout. No manual
sudo provisioning is required or permitted during review. The open wrapper refuses to operate
without an enabled and active timer. Never overwrite or delete the 0700 root-owned
`/opt/services/canina/stage-principal-cleanup` journal during deployments.
A journal entry is fsynced before provisioning and contains the exact session,
random generation, creation SHA, bounded TTL and immutable cleanup deadline.
Repeated opens fail rather than replace an intent or renew TTL. Close and the
30-second boot/periodic retry worker retain intents on lock contention, unavailable
containers/DB, and relational deletion failures. Cleanup resolves the current Stage
container ID once, verifies its cleanup capability, and authenticates against its
current artifact SHA while retaining original session/generation ownership. Older
artifacts without generation cleanup support fail closed; never roll back to one
with a pending principal. Persisted expiry remains independently enforced at login,
refresh and every scoped JWT request.
Revocation commits before private-handle removal; relational deletion is subsequent.
A transaction acquires a generation/session-fenced row lock before touching related
records. Failed deletion retains a revoked row and a pending retry intent, but no
credential handle. Wrong ownership/generation never invokes the handle callback.
The CLI requires the generation supplied by the private journal; no broader admin
or production authority was introduced.
Verification performed in a new isolated worktree and disposable Docker network:
- Cleanup fence tests: RED (replacement generation was revoked; callback missing),
then GREEN (2 tests).
- Python simulated worker tests: restart/redeploy, failed-delete retry, lock
contention, immutable container ID/current artifact and old-CLI refusal (4 tests).
- Persisted account lifecycle plus delete/recreate access AND refresh regression.
- Actual CLI via ts-node with real disposable Postgres/Redis and HTTP adminLogin
handler, injected PostgreSQL delete trigger failure: confirmed revocation,
private handle removal, then successful repeated cleanup after trigger removal.
- TypeScript `tsc --noEmit`: passed.
- Full migration chain attempt on fresh disposable database: baseline failure in
20261020000000_add_blog_freshness_authorship (`blogs` missing). Not concealed.
Independent migration test constructed the pre-Stage schema excluding all three
new fields, then applied the EXACT committed 20261024090000 migration with psql
ON_ERROR_STOP before exercising persisted lifecycle. Not db-push-only testing.
No live account, Stage/Production DB mutation, deployment, push, host service change,
or retry of the previous pending-approval operation was performed.
Invocation after normal reviewed deployment and host prerequisite provisioning:
`sudo -n env CI=true STAGE_TEST_APPROVAL=owner-authorized-stage-editorial bash /opt/services/canina/releases/<promoted-sha>/scripts/stage-test-principal-host.sh <promoted-sha> <unique-session> 600 open`
Use the same command with `close` immediately after the authorized test.
+145
View File
@@ -0,0 +1,145 @@
# Opt-in Stage runtime provisioning (parent wiring contract)
This provisions **snapshot inventory** and credentials for the existing PREPARE
transport. It does NOT create a real LLM executor. The current deterministic worker
is still `llmPilot:false`. No provider credentials are collected, no cron installed,
no task claimed and no worker polling/service started by the provisioner.
## CI-only host invocation
Parent owns workflow/deploy.sh/AppModule; none are changed here. Run only through
the existing pinned authenticated SSH CI boundary, under its Stage environment
approval and serialized rollout lock. `CI=true` is an accident guard, not an auth
boundary. Provisioner checks clean HEAD equals the full approved commit; no branch
promotion, push, Production, RELEASE_AUTHORIZE, Docker or DB writes are performed.
Only the CI account should be able to invoke this on a root-owned trusted parent.
From the clean pinned release checkout on the host (not the dirty Stage checkout):
```sh
CI=true STAGE_PROVISION_ENABLED=true STAGE_PROVISION_APPROVED_SHA="$DEPLOY_SHA" \
python3 scripts/provision-stage-runtime.py --uid 1000 --gid 1000
```
Default output root is `/opt/services/canina/stage-runtime` and its parent must
already exist. First creation is staged and atomically renamed. Repeating validates
existing state without rotating credentials. Corrupt/missing/unsafe files fail
closed, not repaired. CI MUST serialize execution and prevent untrusted edits to
source/output parents; this is not a hostile-filesystem sandbox. `--root` is for
CI-reviewed test/Stage locations only, not arbitrary browser input. Secure backup
and separately approved rotation are parent/operator responsibilities.
- `secrets/` 0700, files 0400 owned by the runtime UID (1000 in the current backend
image); `hermes_username/password/signing_key` are new independent random values.
- `prepare_worker_grants` contains SHA256 only, exact separate service identities
`stage-prepare-worker`/WORKFLOW_WORKER and `stage-evidence-ci`/STAGE_CI. These are
transport service identities, **not invented DB admin users**.
- Raw `credentials/prepare_worker_token` and `credentials/stage_ci_token` stay in a
CI-owner-only 0700 directory, 0400 files. Do NOT mount either into inventory or
backend, log them, upload them as artifacts or send them to browsers. A later
reviewed one-shot executor receives only its own token through a private file.
- `artifacts/` is 0700 owned by backend UID; backend alone writes it. Persistent
local disk is not object storage or external publication evidence.
- `hermes_runtime_grants` is `{}`: deny all. No live admin query was needed/performed.
Parent must separately query actual Stage admin IDs read-only, review exact ID to
profile mapping and provision a private replacement via configuration management
before claiming panel access. Never infer identities from usernames or JWT input.
Deliberately changed grants require separate review; default provisioner refuses
nonempty runtime grants on repeat.
- Compose file-backed secrets preserve host permissions/ownership; `uid/gid/mode`
declarations do not fix bind mount ownership. Verify effective host IDs if Docker
uses userns remapping; do not chmod 0444 as a workaround.
## Consistent restricted export
After approval, the SAME CI invocation may explicitly request one profile's source
SQLite DB. Resolve its real `HERMES_HOME/state.db` through reviewed host mounts;
never guess a gateway volume path or mount the original home into inventory.
```sh
CI=true STAGE_PROVISION_ENABLED=true STAGE_PROVISION_APPROVED_SHA="$DEPLOY_SHA" \
python3 scripts/provision-stage-runtime.py --uid 1000 --gid 1000 \
--snapshot-db "$REVIEWED_STATE_DB" --profile default \
--snapshot-name "$UNIQUE_CI_CAPTURE_ID"
```
SQLite online `Connection.backup()` reads committed WAL frames into memory (never
`cp state.db`, never `immutable=1`). A 30-second callback deadline bounds busy
backup. Only explicit source/time/token/cost columns from `sessions` are projected.
Private session IDs become capture-local ordinal IDs; sources use an enum; no
messages, titles, prompts, user/chat IDs, paths, URLs, model config, credentials,
config.yaml, auth.json, .env, cron commands, memory or skills are exported. Unknown
schema/nonnumeric metadata fails. One profile per immutable capture; there is no
multi-DB atomicity claim. A source DB may be large: backup is memory-bound, so size
and host resources need operator review before a real capture.
Output directory is new/immutable (0500, 0400 files), never overwritten:
`inventory.json`, exact three-field `snapshot-manifest.json` and `export-report.json`.
Manifest `capturedAt` is measured immediately after successful backup, not startup,
mtime or an example. Report records actual projected row count, inventory digest,
method/exclusions; it is not a signature or proof of source authenticity. No live
capture was performed in this change. Never reuse fixture manifests as evidence.
Projected HTTP readers never consult gateway config, state DB or cron files:
model/provider are explicit `unknown`, context length is a placeholder zero,
cron arrays empty mean **not captured**, session activity false is a placeholder,
profile inventory doesn't establish live process availability. Status retains
`liveProcess:unknown`. Usage days are relative to actual capture time. Snapshot
fresh/stale provenance from the existing adapter remains mandatory. No real LLM
pilot readiness follows from this inventory responding 200.
## Exact parent compose/application wiring
`infra/hermes-runtime/compose.stage-provision.yml` is an opt-in merge fragment,
NOT called by the existing deploy script or ci-apply.sh. Parent must include it
in **every** Stage compose command after provisioning, using the existing stable
Compose project identity and existing release isolation/volume rules:
```sh
export STAGE_RUNTIME_SERVE_FILE="$PINNED_RELEASE/infra/hermes-runtime/serve.py"
export STAGE_RUNTIME_SNAPSHOT="/opt/services/canina/stage-runtime/snapshots/$UNIQUE_CI_CAPTURE_ID"
# Only inside approved CI rollout, never manually:
# docker compose -p <existing-stage-project> -f <parent-stage-compose> \
# -f "$PINNED_RELEASE/infra/hermes-runtime/compose.stage-provision.yml" \
# --profile stage-runtime-inventory <parent-approved command>
```
The fragment adds backend `PREPARE_WORKER_ENABLED=true`, fixed-path secrets
`/run/secrets/prepare_worker_grants`, `/run/secrets/hermes_runtime_grants`,
`hermes_username/password`, and artifact bind at
`/var/lib/canina/prepare-artifacts`. It adds a project-scoped **internal** network
between backend and inventory only, alias `canina-hermes-inventory` (not the live
`canina-hermes`). No host port, Docker socket or live gateway volume. Inventory is
read-only, nonroot, no capabilities, restricted tmpfs and pinned image, mounts only
its immutable projected export and script. `create_host_path:false` fails on missing
exports/storage. Original compose.readonly.yml/ci-apply.sh remain legacy review-only;
do not combine those with this provisioning fragment.
AppModule must keep AuthModule/JwtStrategy, import
`RuntimeReadModule.registerFromFile('/run/secrets/hermes_runtime_grants')` for reads,
and spread `...registerPrepareWorker()` for the opt-in worker transport (verify
existing AppModule before adding duplicates). The latter defaults to no module
unless exact env `true`; enabling compose alone cannot add missing imports. Routes
remain service-authenticated. Artifact base is fixed to
`https://stageapi.canina.ir/api/internal/prepare-worker/artifacts`; parent must verify
its actual global `/api` prefix/proxy/authenticated retrieval after CI deployment.
No URL here is asserted externally reachable by disposable tests.
Parent still must implement/review a bounded one-shot real LLM executor separately;
this commit intentionally adds neither model/provider secrets nor automatic polling.
After CI rollout verify backend UID/secret readability by names only, deny-all reads,
worker unauth denial, snapshot provenance and authenticated artifact digest readback
before a separately authorized task. Do not call RELEASE_AUTHORIZE.
## Executed disposable validation
Pinned Hermes image, `--network none`, repository mounted read-only; private
TemporaryDirectory fixtures only. RED observed missing provisioner, missing exporter,
wrong projected profile and acceptance of malformed credential; GREEN: four
provision/export/security/CI-guard unittest cases; projected HTTP auth/profile/session/
wrong-profile/model/cron assertions; existing exact-image HTTP acceptance, TCP serve
mutation denial and authenticated WebSocket 1008 denial. Compose merged config
`--quiet` passed without applying it. An initial test mount mismatch was corrected
(`/source` for repo-relative tests, `/contract` for legacy tests). No application
backend code changed; full backend suites not rerun. No host credentials, artifact
storage, snapshots, DB users, services or networks were provisioned live.
+44
View File
@@ -0,0 +1,44 @@
# Temporary Stage editorial reviewer (disabled by default)
Authority: repository write/CI-dispatch permission plus the existing authenticated,
pinned Stage deployment SSH boundary. This is a narrowly scoped seed operation,
not an API-key actor, owner JWT, or a public bootstrap endpoint. The destructive
legacy seed is not used. `AdminService` shares its normal hashing/persistence and
relational cleanup implementation with the internal command; normal user mutation
role checks remain unchanged. The canonical default administrator is untouched.
## Activation after independent review
1. Promote this commit through the normal Git/CI Stage deployment. Do not run the
seed command against an old image: the embedded immutable SHA must match.
Apply the additive migration through the existing migration deployment step.
2. Dispatch **Owner authorized Stage test principal** on develop with `approval`
exactly `owner-authorized-stage-editorial`, unique `session` such as
`editorial-20261024-a`, `ttl` explicitly 600 (maximum 3600), and `action=open`.
The workflow uses existing DEPLOY_KEY / pinned DEPLOY_KNOWN_HOSTS only.
3. CI reports only `/app/private-stage-test/<session>.json` inside
`canino_backend_stage`. This mode-0600 file in a mode-0700 directory contains
the process-generated password and real persisted-account login tokens.
Consume it only from an approved in-container CI HTTP process; never print,
download, publish as an artifact, or type it into a browser. No owner secret is
needed. Audit records contain events, session and SHA, never credentials.
4. Use this independent reviewer for Gate1 only; the proposer/PMO must be a
distinct actor. Existing self-review checks are not changed. This session does
NOT authorize Gate2, publication, release, general admin APIs, worker identity
replacement, or budget increases. Approve a separate explicit bounded test
budget before running inference; unknown prior reservations remain retained.
5. Dispatch the same workflow/session/ttl with `action=close` immediately after
tests. This revokes persisted authentication BEFORE relational deletion and
removes the private credential file. Close is idempotent when absent.
A durable root-owned host cleanup journal and boot/periodic systemd retry worker must be provisioned before opening a session. Cleanup follows the current Stage artifact but retains the original exact session and generation fence; persisted expiry cannot be extended. See [cleanup verification and promotion prerequisites](stage-principal-cleanup-verification.md). No live host services are changed by review tests.
## Verification
Unit guards and existing independent self-review/role tests run with Jest.
`stage-test-principal.integration.spec.ts` is opt-in via
`STAGE_PRINCIPAL_DISPOSABLE_TEST=true` and requires a database URL ending in
`/principal_disposable`; use a new isolated Postgres and Redis, then remove both.
It verifies real account persistence/hash, signed access/refresh login tokens,
collision refusal, nonrenewing retries, request scope, expiry, deletion/revocation.
Never run it against Stage or Production.
+4 -1
View File
@@ -7,7 +7,10 @@
"dev": "vite --port 3400 --host 127.0.0.1", "dev": "vite --port 3400 --host 127.0.0.1",
"build": "vite build", "build": "vite build",
"lint": "eslint .", "lint": "eslint .",
"preview": "vite preview" "preview": "vite preview",
"test": "vitest run",
"test:watch": "vitest",
"typecheck": "tsc --noEmit"
}, },
"dependencies": { "dependencies": {
"@tanstack/react-query": "^5.101.0", "@tanstack/react-query": "^5.101.0",
@@ -112,16 +112,6 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side
{ icon: MessageSquare, label: 'تحلیل مشاوره سایت', path: '/settings/smart-chat' }, { icon: MessageSquare, label: 'تحلیل مشاوره سایت', path: '/settings/smart-chat' },
], ],
}, },
{
id: 'governance',
title: 'حاکمیت، تاییدات و وظایف',
icon: CheckSquare,
items: [
{ icon: CheckSquare, label: 'کارتابل تاییدات مدیریت', path: '/approvals' },
{ icon: Briefcase, label: 'وظایف دپارتمان‌ها و ایجنت‌ها', path: '/tasks' },
{ icon: History, label: 'تاریخچه تغییرات دیتابیس (Audit)', path: '/history' },
],
},
{ {
id: 'monitoring', id: 'monitoring',
title: 'مرکز مانیتورینگ و سلامت', title: 'مرکز مانیتورینگ و سلامت',
@@ -157,6 +147,7 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side
{ icon: Package, label: 'لیست محصولات', path: '/products' }, { icon: Package, label: 'لیست محصولات', path: '/products' },
{ icon: Star, label: 'نظرات و امتیازات', path: '/reviews' }, { icon: Star, label: 'نظرات و امتیازات', path: '/reviews' },
{ icon: FolderTree, label: 'دسته‌بندی‌های تخصصی', path: '/categories' }, { icon: FolderTree, label: 'دسته‌بندی‌های تخصصی', path: '/categories' },
{ icon: Activity, label: 'علائم بالینی و درمانی', path: '/symptoms' },
{ icon: Tag, label: 'کدهای تخفیف', path: '/coupons' }, { icon: Tag, label: 'کدهای تخفیف', path: '/coupons' },
{ icon: Sparkles, label: 'مشاور هوشمند بالینی', path: '/smart-advisor' }, { icon: Sparkles, label: 'مشاور هوشمند بالینی', path: '/smart-advisor' },
{ icon: FileText, label: 'نسخه‌های دریافتی', path: '/prescriptions' }, { icon: FileText, label: 'نسخه‌های دریافتی', path: '/prescriptions' },
@@ -0,0 +1,147 @@
import React from 'react';
import { HelpCircle, Plus, Trash2 } from 'lucide-react';
import Button from '../ui/Button';
interface ProductFaqTabProps {
activeTab: string;
formData: any;
setFormData: React.Dispatch<React.SetStateAction<any>>;
}
export const ProductFaqTab: React.FC<ProductFaqTabProps> = ({
activeTab,
formData,
setFormData,
}) => {
return (
<div className={activeTab === 'faq' ? 'block space-y-5' : 'hidden'}>
{/* Top FAQ Controls */}
<div className="bg-white p-5 rounded-2xl border border-gray-200 shadow-sm space-y-4">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 border-b pb-4">
<div>
<h4 className="text-sm font-black text-gray-800 flex items-center gap-2">
<HelpCircle className="w-4 h-4 text-purple-600" />
<span>بخش پرسش و پاسخ‌های متداول محصول (Product FAQs)</span>
</h4>
<p className="text-xs text-gray-500 mt-0.5">مدیریت آکاردئون پرسش‌های متداول در صفحه کالا و ثبت خودکار در سئوی گوگل (FAQPage Schema)</p>
</div>
<div className="flex items-center gap-2 shrink-0">
<label className="relative inline-flex items-center cursor-pointer">
<input
type="checkbox"
className="sr-only peer"
checked={formData.showFaqs}
onChange={(e) => setFormData({ ...formData, showFaqs: e.target.checked })}
/>
<div className="w-11 h-6 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-purple-600"></div>
</label>
<span className="text-xs font-bold text-gray-700">
{formData.showFaqs ? 'بخش FAQ فعال است' : 'بخش FAQ غیرفعال است'}
</span>
</div>
</div>
<div className="flex items-center justify-between flex-wrap gap-2 pt-1">
<Button
type="button"
variant="outline"
size="sm"
startIcon={Plus}
onClick={() => {
setFormData({
...formData,
faqs: [...(formData.faqs || []), { question: '', answer: '' }]
});
}}
className="border-purple-200 text-purple-700 hover:bg-purple-50 text-xs font-bold"
>
افزودن سوال جدید
</Button>
<button
type="button"
onClick={() => {
const defaultFaqs = [
{ question: `آیا مصرف ${formData.nameFa || 'این محصول'} برای توله‌ها یا بچه‌گربه‌ها مجاز است؟`, answer: 'بله، مطابق دوز اعلام‌شده روی قوطی و بر اساس وزن دقیق حیوان قابل مصرف است.' },
{ question: 'دوره درمان یا مصرف استاندارد چقدر است؟', answer: 'معمولاً دوره‌های درمانی بین ۴ الی ۶ هفته توصیه می‌شود تا اثربخشی فیزیولوژیک کامل حاصل شود.' },
{ question: 'آیا با سایر داروها یا غذاهای خشک تداخل دارد؟', answer: 'خیر، ترکیبات ارگانیک کنینا فاقد عوارض دارویی تداخلی با رژیم‌های غذایی خشک و مرطوب استاندارد هستند.' }
];
setFormData({
...formData,
faqs: [...(formData.faqs || []), ...defaultFaqs]
});
}}
className="text-xs text-purple-600 hover:text-purple-800 font-bold px-3 py-1.5 rounded-lg hover:bg-purple-50 transition-colors"
>
+ درج سوالات پیشنهادی هوشمند
</button>
</div>
</div>
{/* FAQs List */}
<div className="space-y-4">
{(!formData.faqs || formData.faqs.length === 0) ? (
<div className="bg-white p-8 rounded-2xl border border-dashed border-gray-200 text-center space-y-2">
<HelpCircle className="w-8 h-8 text-gray-300 mx-auto" />
<p className="text-xs font-bold text-gray-500">هیچ پرسش و پاسخی برای این محصول تعریف نشده است.</p>
<p className="text-[11px] text-gray-400">با کلیک روی دکمه «افزودن سوال جدید» یا «درج سوالات پیشنهادی»، متداول‌ترین پرسش‌های خریداران را ثبت کنید.</p>
</div>
) : (
formData.faqs.map((faq: any, index: number) => (
<div key={index} className="bg-white p-5 rounded-2xl border border-gray-200 shadow-xs space-y-3 relative group">
<div className="flex items-center justify-between gap-3 border-b pb-2">
<span className="text-xs font-black text-purple-700 bg-purple-50 px-2.5 py-1 rounded-lg">
پرسش شماره {index + 1}
</span>
<button
type="button"
onClick={() => {
const newFaqs = [...formData.faqs];
newFaqs.splice(index, 1);
setFormData({ ...formData, faqs: newFaqs });
}}
className="p-1.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors"
title="حذف این پرسش"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
<div className="space-y-1.5">
<label className="text-xs font-bold text-gray-700">عنوان پرسش *</label>
<input
type="text"
value={faq.question}
onChange={(e) => {
const newFaqs = [...formData.faqs];
newFaqs[index].question = e.target.value;
setFormData({ ...formData, faqs: newFaqs });
}}
placeholder="مثال: نحوه مصرف همراه با غذاست یا با معده خالی؟"
className="w-full px-4 py-2.5 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-xs font-bold"
dir="rtl"
/>
</div>
<div className="space-y-1.5">
<label className="text-xs font-bold text-gray-700">پاسخ تشریحی و تخصصی *</label>
<textarea
rows={2}
value={faq.answer}
onChange={(e) => {
const newFaqs = [...formData.faqs];
newFaqs[index].answer = e.target.value;
setFormData({ ...formData, faqs: newFaqs });
}}
placeholder="پاسخ دقیق، علمی و راهنمای مصرف را اینجا بنویسید..."
className="w-full px-4 py-2.5 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-xs font-medium leading-relaxed"
dir="rtl"
/>
</div>
</div>
))
)}
</div>
</div>
);
};
@@ -202,6 +202,23 @@ export default function MediaSelector({ isOpen, onClose, onSelect, multiple = fa
const files = Array.from(e.dataTransfer.files); const files = Array.from(e.dataTransfer.files);
if (files.length === 0) return; if (files.length === 0) return;
const ALLOWED_MIME_TYPES = ['image/jpeg', 'image/png', 'image/webp', 'image/svg+xml', 'image/gif', 'application/pdf'];
const MAX_FILE_SIZE = 15 * 1024 * 1024; // 15MB
const validFiles = files.filter(f => {
if (!ALLOWED_MIME_TYPES.includes(f.type) && !f.type.startsWith('image/')) {
toast.error(`فرمت فایل ${f.name} مجاز نمی‌باشد.`);
return false;
}
if (f.size > MAX_FILE_SIZE) {
toast.error(`حجم فایل ${f.name} بیش از حد مجاز (حداکثر ۱۵ مگابایت) است.`);
return false;
}
return true;
});
if (validFiles.length === 0) return;
setIsUploading(true); setIsUploading(true);
let successCount = 0; let successCount = 0;
try { try {
+1 -1
View File
@@ -11,7 +11,7 @@
@font-face { @font-face {
font-family: 'Shabnam'; font-family: 'Shabnam';
src: url('/fonts/shabnam-font-v33.003/fonts/webfonts/Shabnam.woff2') format('woff2'); src: url('/fonts/shabnam-font-v5.0.1/Shabnam.woff2') format('woff2');
font-weight: normal; font-weight: normal;
font-style: normal; font-style: normal;
font-display: swap; font-display: swap;
@@ -1,494 +0,0 @@
import { useState, useEffect, useMemo } from 'react';
import {
CheckCircle2,
XCircle,
Play,
AlertTriangle,
RefreshCw,
DollarSign,
ShoppingCart,
Send,
Sliders,
Check,
X,
MessageSquare,
FileText,
Search,
ArrowUpDown,
Filter,
CheckCheck,
Building2,
TrendingUp,
Server
} from 'lucide-react';
import api from '../services/api';
import Button from '../components/ui/Button';
import Badge from '../components/ui/Badge';
import Spinner from '../components/ui/Spinner';
interface ApprovalItem {
id: string;
department: string;
category: string;
title: string;
payload: any;
testContext?: any;
status: 'PENDING' | 'APPROVED' | 'REJECTED';
ceoNotes?: string;
createdAt: string;
executedAt?: string;
}
export default function ApprovalsPage() {
const [items, setItems] = useState<ApprovalItem[]>([]);
const [loading, setLoading] = useState(true);
const [activeTab, setActiveTab] = useState<string>('ALL');
const [searchQuery, setSearchQuery] = useState<string>('');
const [sortOrder, setSortOrder] = useState<'newest' | 'oldest'>('newest');
const [statusFilter, setStatusFilter] = useState<'ALL' | 'PENDING' | 'APPROVED' | 'REJECTED'>('ALL');
const [testingId, setTestingId] = useState<string | null>(null);
const [testResults, setTestResults] = useState<Record<string, any>>({});
const [notes, setNotes] = useState<Record<string, string>>({});
const [actionLoading, setActionLoading] = useState<string | null>(null);
const [pendingCount, setPendingCount] = useState(0);
const fetchApprovals = async () => {
setLoading(true);
try {
const res = await api.get('/admin/approvals?limit=100');
if (res.data?.success) {
setItems(res.data.data);
setPendingCount(res.data.meta?.pendingCount || 0);
// Pre-fill notes
const initialNotes: Record<string, string> = {};
res.data.data.forEach((item: ApprovalItem) => {
if (item.ceoNotes) initialNotes[item.id] = item.ceoNotes;
});
setNotes(initialNotes);
}
} catch (err) {
console.error('Error fetching approvals', err);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchApprovals();
}, []);
const handleRunTest = async (id: string) => {
setTestingId(id);
try {
const res = await api.post(`/admin/approvals/${id}/test`);
if (res.data?.success) {
setTestResults((prev) => ({ ...prev, [id]: res.data.testResult }));
}
} catch (err) {
console.error('Test simulation failed', err);
} finally {
setTestingId(null);
}
};
const handleDecision = async (id: string, decision: 'APPROVED' | 'REJECTED') => {
setActionLoading(id);
try {
const res = await api.put(`/admin/approvals/${id}/decide`, {
decision,
ceoNotes: notes[id] || '',
});
if (res.data?.success) {
await fetchApprovals();
}
} catch (err) {
console.error('Decision update failed', err);
} finally {
setActionLoading(null);
}
};
const getCategoryIcon = (category: string) => {
switch (category) {
case 'PRICING':
return <DollarSign className="w-5 h-5 text-amber-500" />;
case 'PURCHASE_ORDER':
return <ShoppingCart className="w-5 h-5 text-blue-500" />;
case 'CAMPAIGN':
return <Send className="w-5 h-5 text-purple-500" />;
default:
return <Sliders className="w-5 h-5 text-emerald-500" />;
}
};
const getStatusBadge = (status: string) => {
switch (status) {
case 'PENDING':
return <Badge variant="warning">در انتظار تایید شما</Badge>;
case 'APPROVED':
return <Badge variant="success">تایید و اعمال شد</Badge>;
case 'REJECTED':
return <Badge variant="danger">رد شده</Badge>;
default:
return <Badge variant="neutral">{status}</Badge>;
}
};
// Filter and sort items
const filteredAndSortedItems = useMemo(() => {
return items
.filter((item) => {
// Tab filter (department)
if (activeTab !== 'ALL') {
if (activeTab === 'PENDING') {
if (item.status !== 'PENDING') return false;
} else if (item.department.toUpperCase() !== activeTab.toUpperCase()) {
return false;
}
}
// Status dropdown filter
if (statusFilter !== 'ALL' && item.status !== statusFilter) {
return false;
}
// Search filter (in title, department, category, or notes)
if (searchQuery.trim()) {
const q = searchQuery.toLowerCase().trim();
const matchTitle = item.title?.toLowerCase().includes(q);
const matchDept = item.department?.toLowerCase().includes(q);
const matchCat = item.category?.toLowerCase().includes(q);
const matchNotes = item.ceoNotes?.toLowerCase().includes(q);
const matchPayload = JSON.stringify(item.payload || {}).toLowerCase().includes(q);
if (!matchTitle && !matchDept && !matchCat && !matchNotes && !matchPayload) {
return false;
}
}
return true;
})
.sort((a, b) => {
const timeA = new Date(a.createdAt).getTime();
const timeB = new Date(b.createdAt).getTime();
return sortOrder === 'newest' ? timeB - timeA : timeA - timeB;
});
}, [items, activeTab, statusFilter, searchQuery, sortOrder]);
const totalCount = items.length;
const approvedCount = items.filter(i => i.status === 'APPROVED').length;
const rejectedCount = items.filter(i => i.status === 'REJECTED').length;
return (
<div className="space-y-6 max-w-7xl mx-auto p-4 md:p-6" dir="rtl">
{/* Header */}
<div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 bg-white dark:bg-slate-900 p-6 rounded-2xl border border-slate-200 dark:border-slate-800 shadow-sm">
<div>
<div className="flex items-center gap-3">
<h1 className="text-2xl font-bold text-slate-900 dark:text-white">
میز کار تاییدات و حاکمیت سازمانی (CEO Approvals Gate)
</h1>
{pendingCount > 0 ? (
<span className="px-2.5 py-0.5 rounded-full text-xs font-semibold bg-amber-100 text-amber-800 dark:bg-amber-900/50 dark:text-amber-300">
{pendingCount} مورد نیازمند بررسی
</span>
) : (
<span className="px-2.5 py-0.5 rounded-full text-xs font-semibold bg-emerald-100 text-emerald-800 dark:bg-emerald-900/50 dark:text-emerald-300 flex items-center gap-1">
<CheckCheck className="w-3.5 h-3.5" />
تمامی موارد تعیین تکلیف شده‌اند
</span>
)}
</div>
<p className="text-sm text-slate-500 dark:text-slate-400 mt-1">
هیچ تغییر حساسی اعم از قیمت‌گذاری، صدور سفارش تامین، ارسال پیامک یا دپلوی سرور بدون تایید مستقیم شما در سیستم پروداکشن اجرایی نخواهد شد.
</p>
</div>
<Button
variant="secondary"
onClick={fetchApprovals}
disabled={loading}
icon={<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />}
>
به‌روزرسانی کارتابل
</Button>
</div>
{/* Summary KPI Cards */}
<div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
<div className="bg-white dark:bg-slate-900 p-4 rounded-xl border border-slate-200 dark:border-slate-800 shadow-sm flex items-center justify-between">
<div>
<p className="text-xs font-bold text-slate-500">کل موارد کارتابل</p>
<p className="text-xl font-black text-slate-900 dark:text-white mt-1">{totalCount}</p>
</div>
<div className="w-10 h-10 rounded-lg bg-blue-50 dark:bg-blue-900/30 text-blue-600 flex items-center justify-center font-bold">
Σ
</div>
</div>
<div className="bg-white dark:bg-slate-900 p-4 rounded-xl border border-slate-200 dark:border-slate-800 shadow-sm flex items-center justify-between">
<div>
<p className="text-xs font-bold text-amber-600">در انتظار تایید شما</p>
<p className="text-xl font-black text-amber-600 mt-1">{pendingCount}</p>
</div>
<div className="w-10 h-10 rounded-lg bg-amber-50 dark:bg-amber-900/30 text-amber-600 flex items-center justify-center font-bold">
⏳
</div>
</div>
<div className="bg-white dark:bg-slate-900 p-4 rounded-xl border border-slate-200 dark:border-slate-800 shadow-sm flex items-center justify-between">
<div>
<p className="text-xs font-bold text-emerald-600">تایید و اعمال‌شده</p>
<p className="text-xl font-black text-emerald-600 mt-1">{approvedCount}</p>
</div>
<div className="w-10 h-10 rounded-lg bg-emerald-50 dark:bg-emerald-900/30 text-emerald-600 flex items-center justify-center font-bold">
✓
</div>
</div>
<div className="bg-white dark:bg-slate-900 p-4 rounded-xl border border-slate-200 dark:border-slate-800 shadow-sm flex items-center justify-between">
<div>
<p className="text-xs font-bold text-red-600">رد شده توسط مدیرعامل</p>
<p className="text-xl font-black text-red-600 mt-1">{rejectedCount}</p>
</div>
<div className="w-10 h-10 rounded-lg bg-red-50 dark:bg-red-900/30 text-red-600 flex items-center justify-center font-bold">
✕
</div>
</div>
</div>
{/* Search, Filter & Sort Bar */}
<div className="bg-white dark:bg-slate-900 p-4 rounded-2xl border border-slate-200 dark:border-slate-800 shadow-sm space-y-4">
<div className="flex flex-col md:flex-row gap-3 items-stretch md:items-center justify-between">
{/* Search Box */}
<div className="relative flex-1">
<Search className="w-4 h-4 text-slate-400 absolute right-3.5 top-1/2 -translate-y-1/2" />
<input
type="text"
placeholder="جستجو در عنوان، دپارتمان، دسته‌بندی یا یادداشت‌ها..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="w-full pr-10 pl-4 py-2 text-sm bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 text-slate-800 dark:text-slate-100"
/>
{searchQuery && (
<button
onClick={() => setSearchQuery('')}
className="absolute left-3 top-1/2 -translate-y-1/2 text-xs text-slate-400 hover:text-slate-600"
>
پاک کردن
</button>
)}
</div>
{/* Status Filter */}
<div className="flex items-center gap-2">
<Filter className="w-4 h-4 text-slate-400 shrink-0" />
<select
value={statusFilter}
onChange={(e: any) => setStatusFilter(e.target.value)}
className="px-3 py-2 text-sm bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 text-slate-800 dark:text-slate-100 cursor-pointer"
>
<option value="ALL">همه وضعیت‌ها</option>
<option value="PENDING">فقط در انتظار تایید ({pendingCount})</option>
<option value="APPROVED">فقط تایید شده‌ها ({approvedCount})</option>
<option value="REJECTED">فقط رد شده‌ها ({rejectedCount})</option>
</select>
</div>
{/* Sort Order */}
<div className="flex items-center gap-2">
<ArrowUpDown className="w-4 h-4 text-slate-400 shrink-0" />
<select
value={sortOrder}
onChange={(e: any) => setSortOrder(e.target.value)}
className="px-3 py-2 text-sm bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 text-slate-800 dark:text-slate-100 cursor-pointer"
>
<option value="newest">جدیدترین به قدیمی‌ترین</option>
<option value="oldest">قدیمی‌ترین به جدیدترین</option>
</select>
</div>
</div>
{/* Department Tabs */}
<div className="flex flex-wrap gap-2 pt-2 border-t border-slate-100 dark:border-slate-800">
{[
{ id: 'ALL', label: `همه دپارتمان‌ها (${totalCount})` },
{ id: 'PENDING', label: `در انتظار تایید (${pendingCount})` },
{ id: 'FINANCE', label: 'مالی و قیمت‌گذاری' },
{ id: 'MARKET', label: 'هوش بازار و ترب' },
{ id: 'CONTENT', label: 'محتوا و سئو' },
{ id: 'CRM', label: 'ارتباط با مشتریان' },
{ id: 'B2B', label: 'لیدها و کلینیک‌ها' },
{ id: 'SUPPLY', label: 'تامین و انبار' },
{ id: 'DEVOPS', label: 'فنی و زیرساخت' },
].map((tab) => (
<button
key={tab.id}
onClick={() => setActiveTab(tab.id)}
className={`px-3.5 py-1.5 rounded-xl text-xs font-bold transition-all ${
activeTab === tab.id
? 'bg-blue-600 text-white shadow-sm'
: 'bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-300 hover:bg-slate-200 dark:hover:bg-slate-700'
}`}
>
{tab.label}
</button>
))}
</div>
</div>
{/* Showing Result Counter */}
<div className="flex justify-between items-center text-xs text-slate-500 dark:text-slate-400 px-1">
<span>نمایش <strong>{filteredAndSortedItems.length}</strong> مورد از مجموع <strong>{totalCount}</strong> مورد کارتابل</span>
{(searchQuery || statusFilter !== 'ALL' || activeTab !== 'ALL') && (
<button
onClick={() => {
setSearchQuery('');
setStatusFilter('ALL');
setActiveTab('ALL');
}}
className="text-blue-600 hover:underline font-bold"
>
پاک کردن همه فیلترها
</button>
)}
</div>
{/* Content */}
{loading ? (
<div className="py-20 flex justify-center items-center">
<Spinner className="w-8 h-8 text-blue-600" />
</div>
) : filteredAndSortedItems.length === 0 ? (
<div className="bg-white dark:bg-slate-900 p-12 text-center rounded-2xl border border-slate-200 dark:border-slate-800">
<CheckCircle2 className="w-12 h-12 text-emerald-500 mx-auto mb-3" />
<h3 className="text-lg font-bold text-slate-900 dark:text-white">هیچ موردی مطابق فیلترهای انتخابی یافت نشد</h3>
<p className="text-sm text-slate-500 dark:text-slate-400 mt-1">می‌توانید فیلترها یا عبارت جستجو را تغییر دهید.</p>
</div>
) : (
<div className="grid gap-6">
{filteredAndSortedItems.map((item) => (
<div
key={item.id}
className={`bg-white dark:bg-slate-900 rounded-2xl border transition-all overflow-hidden ${
item.status === 'PENDING'
? 'border-amber-300 dark:border-amber-800/60 shadow-md ring-1 ring-amber-400/20'
: 'border-slate-200 dark:border-slate-800 opacity-90'
}`}
>
{/* Card Header */}
<div className="p-5 border-b border-slate-100 dark:border-slate-800/80 flex flex-col md:flex-row justify-between items-start md:items-center gap-3 bg-slate-50/50 dark:bg-slate-800/30">
<div className="flex items-center gap-3">
<div className="p-2.5 rounded-xl bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700">
{getCategoryIcon(item.category)}
</div>
<div>
<h3 className="font-bold text-slate-900 dark:text-white text-base">
{item.title}
</h3>
<div className="flex items-center gap-2 mt-1 text-xs text-slate-500 dark:text-slate-400">
<span>دپارتمان: <strong className="text-slate-700 dark:text-slate-200">{item.department}</strong></span>
<span>•</span>
<span>دسته‌بندی: <strong>{item.category}</strong></span>
<span>•</span>
<span>تاریخ ثبت: {new Date(item.createdAt).toLocaleDateString('fa-IR')}</span>
{item.executedAt && (
<>
<span>•</span>
<span className="text-emerald-600 font-bold">تاریخ اعمال: {new Date(item.executedAt).toLocaleDateString('fa-IR')}</span>
</>
)}
</div>
</div>
</div>
<div>{getStatusBadge(item.status)}</div>
</div>
{/* Card Body */}
<div className="p-5 space-y-4">
{/* Proposed Data Payload Diff */}
<div className="bg-slate-50 dark:bg-slate-950 p-4 rounded-xl border border-slate-200/80 dark:border-slate-800 text-xs font-mono text-slate-800 dark:text-slate-200 overflow-x-auto">
<div className="font-sans font-bold text-xs text-slate-500 dark:text-slate-400 mb-2">
جزئیات داده‌های پیشنهادی دپارتمان (Payload Details):
</div>
<pre className="whitespace-pre-wrap break-words">
{typeof item.payload === 'string'
? item.payload
: JSON.stringify(item.payload, null, 2)}
</pre>
</div>
{/* Pre-Execution Test Simulation Button & Result */}
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 p-3 bg-blue-50/60 dark:bg-blue-950/20 rounded-xl border border-blue-100 dark:border-blue-900/40">
<div className="text-xs text-blue-900 dark:text-blue-200">
<strong>شبیه‌سازی اثر تغییرات:</strong> بررسی ایمنی و سنجش تغییرات قبل از تایید نهایی در محیط ایزوله
</div>
<Button
variant="secondary"
size="sm"
onClick={() => handleRunTest(item.id)}
disabled={testingId === item.id}
icon={<Play className={`w-3.5 h-3.5 ${testingId === item.id ? 'animate-spin' : ''}`} />}
>
{testingId === item.id ? 'در حال اجرای تست...' : 'اجرای تست و شبیه‌سازی'}
</Button>
</div>
{testResults[item.id] && (
<div className="p-3 bg-emerald-50 dark:bg-emerald-950/30 border border-emerald-200 dark:border-emerald-800 rounded-xl text-xs text-emerald-900 dark:text-emerald-200">
<strong>نتیجه تست سلامت و شبیه‌سازی:</strong>
<pre className="mt-1 font-mono whitespace-pre-wrap">
{JSON.stringify(testResults[item.id], null, 2)}
</pre>
</div>
)}
{/* CEO Notes & Directives */}
<div className="space-y-1.5">
<label className="text-xs font-semibold text-slate-700 dark:text-slate-300 flex items-center gap-1.5">
<MessageSquare className="w-3.5 h-3.5" />
دستور یا یادداشت مدیرعامل برای این تصمیم:
</label>
<textarea
rows={2}
value={notes[item.id] || ''}
onChange={(e) =>
setNotes((prev) => ({ ...prev, [item.id]: e.target.value }))
}
placeholder="شروط تایید، بازنگری قیمت یا دلیل رد درخواست را اینجا بنویسید..."
disabled={item.status !== 'PENDING' && actionLoading !== item.id}
className="w-full text-xs p-3 rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900 focus:ring-2 focus:ring-blue-500 focus:outline-none"
/>
</div>
{/* Action Buttons */}
{item.status === 'PENDING' && (
<div className="flex flex-wrap items-center justify-end gap-3 pt-3 border-t border-slate-100 dark:border-slate-800">
<Button
variant="danger"
onClick={() => handleDecision(item.id, 'REJECTED')}
disabled={actionLoading === item.id}
icon={<X className="w-4 h-4" />}
>
رد این پیشنهاد
</Button>
<Button
variant="primary"
onClick={() => handleDecision(item.id, 'APPROVED')}
disabled={actionLoading === item.id}
icon={<Check className="w-4 h-4" />}
>
تایید و اعمال نهایی در پروداکشن
</Button>
</div>
)}
{item.status !== 'PENDING' && item.ceoNotes && (
<div className="p-3 bg-slate-100 dark:bg-slate-800/60 rounded-xl text-xs text-slate-600 dark:text-slate-300">
<strong>یادداشت ثبت شده مدیرعامل:</strong> {item.ceoNotes}
</div>
)}
</div>
</div>
))}
</div>
)}
</div>
);
}
@@ -1,323 +0,0 @@
import React, { useState, useEffect } from 'react';
import {
History,
Search,
Filter,
RefreshCw,
Clock,
User,
Database,
ArrowRight,
Shield,
Layers,
ChevronDown,
Calendar,
AlertCircle,
Eye,
CheckCircle2
} from 'lucide-react';
import api from '../services/api';
interface AuditLogItem {
id: string;
entity: string;
entityId: string;
action: 'CREATE' | 'UPDATE' | 'DELETE' | 'EXECUTE' | 'BULK_UPDATE';
department: string;
actor: string;
summary: string;
oldValues?: any;
newValues?: any;
metadata?: any;
createdAt: string;
}
export default function AuditHistoryPage() {
const [logs, setLogs] = useState<AuditLogItem[]>([]);
const [loading, setLoading] = useState(true);
const [searchTerm, setSearchTerm] = useState('');
const [selectedEntity, setSelectedEntity] = useState('ALL');
const [selectedDept, setSelectedDept] = useState('ALL');
const [selectedAction, setSelectedAction] = useState('ALL');
const [activeLogModal, setActiveLogModal] = useState<AuditLogItem | null>(null);
const fetchLogs = async () => {
setLoading(true);
try {
const res = await api.get('/admin/audit-logs?limit=100');
if (res.data?.success) {
setLogs(res.data.data);
}
} catch (err) {
console.error('Error fetching audit logs:', err);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchLogs();
}, []);
const filteredLogs = logs.filter((log) => {
const matchesSearch =
!searchTerm ||
log.summary.toLowerCase().includes(searchTerm.toLowerCase()) ||
log.actor.toLowerCase().includes(searchTerm.toLowerCase()) ||
log.entity.toLowerCase().includes(searchTerm.toLowerCase()) ||
log.entityId.toLowerCase().includes(searchTerm.toLowerCase());
const matchesEntity = selectedEntity === 'ALL' || log.entity === selectedEntity;
const matchesDept = selectedDept === 'ALL' || log.department === selectedDept;
const matchesAction = selectedAction === 'ALL' || log.action === selectedAction;
return matchesSearch && matchesEntity && matchesDept && matchesAction;
});
const getActionBadge = (action: string) => {
switch (action) {
case 'CREATE':
return <span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-emerald-100 text-emerald-800 border border-emerald-200">افزودن (Create)</span>;
case 'UPDATE':
return <span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-blue-100 text-blue-800 border border-blue-200">ویرایش (Update)</span>;
case 'DELETE':
return <span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-rose-100 text-rose-800 border border-rose-200">حذف (Delete)</span>;
case 'EXECUTE':
return <span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-purple-100 text-purple-800 border border-purple-200">اجرا (Execute)</span>;
case 'BULK_UPDATE':
return <span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-amber-100 text-amber-800 border border-amber-200">دسته‌جمعی (Bulk)</span>;
default:
return <span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-gray-100 text-gray-800">{action}</span>;
}
};
const getDeptBadge = (dept: string) => {
const map: Record<string, string> = {
COMMERCE: 'بازرگانی و مالی',
PRODUCT: 'محصولات',
CONTENT: 'محتوا و وبلاگ',
SEO: 'سئو و مارکتینگ',
DEV: 'فنی و زیرساخت',
ORDER: 'سفارشات',
APPROVAL: 'تاییدات مدیریت',
};
return (
<span className="text-[11px] font-bold text-gray-600 bg-gray-100 px-2 py-0.5 rounded-md border border-gray-200">
{map[dept] || dept}
</span>
);
};
return (
<div className="space-y-6 font-vazir pb-12" dir="rtl">
{/* Top Header */}
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4 bg-white p-6 rounded-2xl border border-gray-100 shadow-sm">
<div>
<div className="flex items-center gap-3 mb-1">
<div className="w-10 h-10 rounded-xl bg-purple-100 flex items-center justify-center text-purple-700">
<History className="w-5 h-5" />
</div>
<div>
<h1 className="text-xl font-black text-gray-900">تاریخچه تغییرات زنده دیتابیس (Audit Logs)</h1>
<p className="text-xs text-gray-500 font-medium">ردیابی تمامی عملیات‌های اصلاح قیمت، استوک، پست‌ها و کاتالوگ</p>
</div>
</div>
</div>
<button
onClick={fetchLogs}
disabled={loading}
className="inline-flex items-center gap-2 px-4 py-2.5 rounded-xl bg-purple-50 text-purple-700 text-xs font-bold hover:bg-purple-100 transition-colors border border-purple-200 cursor-pointer disabled:opacity-50"
>
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
<span>به‌روزرسانی لحظه‌ای</span>
</button>
</div>
{/* Filter and Search Bar */}
<div className="bg-white p-4 rounded-2xl border border-gray-100 shadow-sm space-y-4">
<div className="grid grid-cols-1 md:grid-cols-4 gap-3">
<div className="relative">
<Search className="w-4 h-4 absolute right-3 top-3 text-gray-400" />
<input
type="text"
placeholder="جستجو در خلاصه تغییرات، شناسه، اپراتور..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="w-full pr-9 pl-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-medium"
/>
</div>
<div>
<select
value={selectedEntity}
onChange={(e) => setSelectedEntity(e.target.value)}
className="w-full px-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-bold text-gray-700"
>
<option value="ALL">همه موجودیت‌ها (Entities)</option>
<option value="product">محصولات (Product)</option>
<option value="blog">وبلاگ و مقالات (Blog)</option>
<option value="category">دسته‌بندی‌ها (Category)</option>
<option value="order">سفارشات (Order)</option>
<option value="approval">تاییدیه مدیریت (Approval)</option>
<option value="task">تسک‌ها (Task)</option>
</select>
</div>
<div>
<select
value={selectedDept}
onChange={(e) => setSelectedDept(e.target.value)}
className="w-full px-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-bold text-gray-700"
>
<option value="ALL">همه دپارتمان‌ها</option>
<option value="COMMERCE">بازرگانی و مالی</option>
<option value="PRODUCT">کاتالوگ و انبار</option>
<option value="CONTENT">محتوا و وبلاگ</option>
<option value="SEO">سئو و مارکتینگ</option>
<option value="DEV">فنی و زیرساخت</option>
<option value="APPROVAL">تاییدات هیئت مدیره</option>
</select>
</div>
<div>
<select
value={selectedAction}
onChange={(e) => setSelectedAction(e.target.value)}
className="w-full px-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-bold text-gray-700"
>
<option value="ALL">همه نوع عملیات</option>
<option value="CREATE">افزودن (Create)</option>
<option value="UPDATE">ویرایش (Update)</option>
<option value="DELETE">حذف (Delete)</option>
<option value="EXECUTE">اجرای تغییر (Execute)</option>
<option value="BULK_UPDATE">به‌روزرسانی انبوه (Bulk)</option>
</select>
</div>
</div>
</div>
{/* Audit Logs Table */}
<div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
{loading ? (
<div className="p-12 text-center text-gray-500 font-bold text-sm">
<RefreshCw className="w-6 h-6 animate-spin mx-auto mb-2 text-purple-600" />
در حال بارگذاری لاگ‌های تغییرات دیتابیس...
</div>
) : filteredLogs.length === 0 ? (
<div className="p-12 text-center text-gray-400 font-bold text-sm">
هیچ رکورد تغییری با فیلترهای انتخابی یافت نشد.
</div>
) : (
<div className="overflow-x-auto">
<table className="w-full text-right text-xs">
<thead className="bg-gray-50/75 border-b border-gray-100 text-gray-500 font-black">
<tr>
<th className="py-3 px-4">زمان ثبت</th>
<th className="py-3 px-4">موجودیت / شناسه</th>
<th className="py-3 px-4">نوع اقدام</th>
<th className="py-3 px-4">دپارتمان</th>
<th className="py-3 px-4">اقدام‌کننده</th>
<th className="py-3 px-4">شرح تغییرات</th>
<th className="py-3 px-4 text-center">جزییات فنی</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100 font-medium text-gray-700">
{filteredLogs.map((log) => (
<tr key={log.id} className="hover:bg-purple-50/20 transition-colors">
<td className="py-3.5 px-4 whitespace-nowrap text-gray-500">
<div className="flex items-center gap-1.5 font-sans font-bold text-[11px]">
<Clock className="w-3.5 h-3.5 text-gray-400" />
<span>{new Date(log.createdAt).toLocaleString('fa-IR')}</span>
</div>
</td>
<td className="py-3.5 px-4 whitespace-nowrap">
<div className="font-bold text-gray-900">{log.entity}</div>
<div className="text-[10px] font-mono text-gray-400 truncate max-w-[120px]">{log.entityId}</div>
</td>
<td className="py-3.5 px-4 whitespace-nowrap">
{getActionBadge(log.action)}
</td>
<td className="py-3.5 px-4 whitespace-nowrap">
{getDeptBadge(log.department)}
</td>
<td className="py-3.5 px-4 whitespace-nowrap font-bold text-purple-900">
<div className="flex items-center gap-1">
<User className="w-3.5 h-3.5 text-purple-600" />
<span>{log.actor}</span>
</div>
</td>
<td className="py-3.5 px-4">
<div className="font-bold text-gray-800 line-clamp-2 max-w-md">{log.summary}</div>
</td>
<td className="py-3.5 px-4 text-center whitespace-nowrap">
<button
onClick={() => setActiveLogModal(log)}
className="inline-flex items-center gap-1 px-2.5 py-1 rounded-lg bg-gray-100 hover:bg-purple-100 hover:text-purple-700 text-gray-600 font-bold text-[11px] transition-colors cursor-pointer"
>
<Eye className="w-3.5 h-3.5" />
<span>مشاهده Diff</span>
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
{/* Modal View Diff */}
{activeLogModal && (
<div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4 backdrop-blur-sm animate-in fade-in duration-150">
<div className="bg-white rounded-2xl max-w-2xl w-full p-6 space-y-4 shadow-2xl border border-gray-100 max-h-[85vh] overflow-y-auto">
<div className="flex items-center justify-between border-b border-gray-100 pb-3">
<div className="flex items-center gap-2">
<Database className="w-5 h-5 text-purple-600" />
<h3 className="font-black text-sm text-gray-900">جزییات تغییر داده‌ها ({activeLogModal.entity})</h3>
</div>
<button
onClick={() => setActiveLogModal(null)}
className="text-gray-400 hover:text-gray-600 font-bold text-sm cursor-pointer"
>
✕
</button>
</div>
<div className="text-xs space-y-2">
<div className="p-3 bg-gray-50 rounded-xl">
<span className="font-bold text-gray-500">خلاصه عملیات: </span>
<span className="font-black text-gray-800">{activeLogModal.summary}</span>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<h4 className="font-bold text-rose-700 mb-1">مقادیر قبلی (Old Values):</h4>
<pre className="bg-rose-50 text-rose-900 p-3 rounded-xl text-[10px] font-mono overflow-x-auto max-h-56">
{JSON.stringify(activeLogModal.oldValues || { info: 'مقداری ثبت نشده بود' }, null, 2)}
</pre>
</div>
<div>
<h4 className="font-bold text-emerald-700 mb-1">مقادیر جدید (New Values):</h4>
<pre className="bg-emerald-50 text-emerald-900 p-3 rounded-xl text-[10px] font-mono overflow-x-auto max-h-56">
{JSON.stringify(activeLogModal.newValues || { info: 'تغییری ثبت نشده' }, null, 2)}
</pre>
</div>
</div>
</div>
<div className="pt-2 text-left">
<button
onClick={() => setActiveLogModal(null)}
className="px-4 py-2 bg-purple-600 text-white rounded-xl text-xs font-bold hover:bg-purple-700 transition-colors"
>
بستن
</button>
</div>
</div>
</div>
)}
</div>
);
}
@@ -251,6 +251,10 @@ describe("Blogs Page Component", () => {
}); });
}); });
it("submits authorship fields and intentional material update control", async () => {
renderComponent(); await screen.findByText("راهنمای جامع نگهداری سگ پامرانین"); fireEvent.click(screen.getAllByTitle("ویرایش مقاله")[0]); fireEvent.change(screen.getByLabelText("تیم نویسندگی"),{target:{value:"Science"}}); fireEvent.change(screen.getByLabelText("نقش نویسنده"),{target:{value:"Vet"}}); fireEvent.click(screen.getByText("۳. زمان‌بندی و انتشار")); fireEvent.click(screen.getByLabelText("ثبت به‌روزرسانی محتوایی مهم")); fireEvent.click(screen.getByTestId("blog-save-btn")); await waitFor(()=>expect(api.put).toHaveBeenCalledWith("/admin/blogs/blog-1",expect.objectContaining({authorTeam:"Science",authorRole:"Vet",markContentUpdated:true})));
});
it("shows delete confirmation and deletes blog article", async () => { it("shows delete confirmation and deletes blog article", async () => {
vi.mocked(api.delete).mockResolvedValueOnce({ data: { success: true } }); vi.mocked(api.delete).mockResolvedValueOnce({ data: { success: true } });
+19
View File
@@ -70,6 +70,9 @@ export interface BlogPost {
content: string; content: string;
excerpt?: string; excerpt?: string;
authorId?: string; authorId?: string;
authorTeam?: string;
authorRole?: string;
contentUpdatedAt?: string | null;
author?: { author?: {
id?: string; id?: string;
firstName?: string; firstName?: string;
@@ -168,6 +171,9 @@ export default function Blogs() {
content: '', content: '',
excerpt: '', excerpt: '',
authorId: '', authorId: '',
authorTeam: '',
authorRole: '',
markContentUpdated: false,
categoryId: '', categoryId: '',
tagNames: [] as string[], tagNames: [] as string[],
imageUrl: '', imageUrl: '',
@@ -245,6 +251,9 @@ export default function Blogs() {
content: blog.content || '', content: blog.content || '',
excerpt: blog.excerpt || '', excerpt: blog.excerpt || '',
authorId: blog.authorId || (blog.author?.id || ''), authorId: blog.authorId || (blog.author?.id || ''),
authorTeam: blog.authorTeam || '',
authorRole: blog.authorRole || '',
markContentUpdated: false,
categoryId: blog.categoryId || '', categoryId: blog.categoryId || '',
tagNames: blog.tags ? blog.tags.map((t) => t.name) : [], tagNames: blog.tags ? blog.tags.map((t) => t.name) : [],
imageUrl: blog.imageUrl || '', imageUrl: blog.imageUrl || '',
@@ -281,6 +290,9 @@ export default function Blogs() {
content: '', content: '',
excerpt: '', excerpt: '',
authorId: authors[0]?.id || '', authorId: authors[0]?.id || '',
authorTeam: '',
authorRole: '',
markContentUpdated: false,
categoryId: '', categoryId: '',
tagNames: [], tagNames: [],
imageUrl: '', imageUrl: '',
@@ -1003,6 +1015,11 @@ export default function Blogs() {
</div> </div>
</div> </div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div><label htmlFor="author-team" className="text-xs font-bold text-gray-700">تیم نویسندگی</label><input id="author-team" value={formData.authorTeam} onChange={(e)=>setFormData({...formData,authorTeam:e.target.value})} className="w-full px-3 py-2.5 rounded-2xl border border-gray-200 text-xs" /></div>
<div><label htmlFor="author-role" className="text-xs font-bold text-gray-700">نقش نویسنده</label><input id="author-role" value={formData.authorRole} onChange={(e)=>setFormData({...formData,authorRole:e.target.value})} className="w-full px-3 py-2.5 rounded-2xl border border-gray-200 text-xs" /></div>
</div>
{/* Chips Tag Input */} {/* Chips Tag Input */}
<div className="space-y-2 p-3.5 bg-gray-50/70 border border-gray-200 rounded-2xl"> <div className="space-y-2 p-3.5 bg-gray-50/70 border border-gray-200 rounded-2xl">
<label className="text-xs font-bold text-gray-700 block">برچسب‌ها و تگ‌های مقاله (Tag Input)</label> <label className="text-xs font-bold text-gray-700 block">برچسب‌ها و تگ‌های مقاله (Tag Input)</label>
@@ -1161,6 +1178,8 @@ export default function Blogs() {
</div> </div>
</div> </div>
<label className="flex items-center gap-3 p-4 border border-blue-200 rounded-2xl bg-blue-50 cursor-pointer"><input type="checkbox" aria-label="ثبت به‌روزرسانی محتوایی مهم" checked={formData.markContentUpdated} onChange={(e)=>setFormData({...formData,markContentUpdated:e.target.checked})}/><span className="text-xs font-black">ثبت به‌روزرسانی محتوایی مهم</span></label>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3"> <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
<label className="flex items-center gap-3 p-4 border border-gray-200 rounded-2xl bg-white hover:bg-gray-50 transition-colors cursor-pointer"> <label className="flex items-center gap-3 p-4 border border-gray-200 rounded-2xl bg-white hover:bg-gray-50 transition-colors cursor-pointer">
<input <input
@@ -43,11 +43,8 @@ describe('Dashboard Page Component', () => {
beforeEach(() => { beforeEach(() => {
vi.clearAllMocks(); vi.clearAllMocks();
vi.mocked(api.get).mockResolvedValue({ vi.mocked(api.get).mockImplementation((_url: string) => {
data: { return Promise.resolve({ data: { success: true, data: mockStats } } as any);
success: true,
data: mockStats,
},
}); });
}); });
@@ -123,7 +120,12 @@ describe('Dashboard Page Component', () => {
it('falls back gracefully when API returns error', async () => { it('falls back gracefully when API returns error', async () => {
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
vi.mocked(api.get).mockRejectedValueOnce(new Error('Network error')); vi.mocked(api.get).mockImplementation((url: string) => {
if (url.includes('/admin/dashboard/stats')) {
return Promise.reject(new Error('Network error'));
}
return Promise.resolve({ data: { success: true, data: [] } } as any);
});
renderDashboard(); renderDashboard();
+8 -188
View File
@@ -1,4 +1,4 @@
import { Activity, DollarSign, ShoppingCart, Users, ShieldAlert, ArrowLeft, History, Briefcase, Clock, Database } from "lucide-react"; import { Activity, DollarSign, ShoppingCart, Users } from "lucide-react";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { Link } from "react-router-dom"; import { Link } from "react-router-dom";
import { CartesianGrid, Cell, Line, LineChart, Pie, PieChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts"; import { CartesianGrid, Cell, Line, LineChart, Pie, PieChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
@@ -17,25 +17,7 @@ interface DashboardData {
categoriesDistribution?: CategoryDist[]; categoriesDistribution?: CategoryDist[];
} }
interface AuditLogSummary {
id: string;
entity: string;
action: string;
department: string;
actor: string;
summary: string;
createdAt: string;
}
export default function Dashboard() { export default function Dashboard() {
const [pendingApprovalsCount, setPendingApprovalsCount] = useState<number>(0);
const [recentLogs, setRecentLogs] = useState<AuditLogSummary[]>([]);
const [taskStats, setTaskStats] = useState<{ total: number; done: number; inProgress: number }>({
total: 0,
done: 0,
inProgress: 0,
});
const [data, setData] = useState<DashboardData>({ const [data, setData] = useState<DashboardData>({
revenue: 0, revenue: 0,
newOrders: 0, newOrders: 0,
@@ -44,18 +26,6 @@ export default function Dashboard() {
}); });
useEffect(() => { useEffect(() => {
const fetchPendingApprovals = async () => {
try {
const res = await api.get('/admin/approvals?limit=1');
if (res.data?.success && res.data?.meta) {
setPendingApprovalsCount(res.data.meta.pendingCount || 0);
}
} catch (e) {
console.error('Failed to fetch approvals count', e);
}
};
fetchPendingApprovals();
const fetchStats = async () => { const fetchStats = async () => {
try { try {
const response = await api.get('/admin/dashboard/stats'); const response = await api.get('/admin/dashboard/stats');
@@ -67,36 +37,6 @@ export default function Dashboard() {
} }
}; };
fetchStats(); fetchStats();
// Fetch recent audit logs for live widget
const fetchRecentLogs = async () => {
try {
const res = await api.get('/admin/audit-logs?limit=5');
if (res.data?.success) {
setRecentLogs(res.data.data);
}
} catch (e) {
console.error('Failed to fetch audit logs widget', e);
}
};
fetchRecentLogs();
// Fetch tasks summary
const fetchTaskStats = async () => {
try {
const res = await api.get('/admin/department-tasks/stats');
if (res.data?.success) {
setTaskStats({
total: res.data.data.total || 0,
done: res.data.data.byStatus?.DONE || 0,
inProgress: res.data.data.byStatus?.IN_PROGRESS || 0,
});
}
} catch (e) {
console.error('Failed to fetch task stats widget', e);
}
};
fetchTaskStats();
}, []); }, []);
const chartData = [ const chartData = [
@@ -117,68 +57,19 @@ export default function Dashboard() {
const COLORS = ['#8b5cf6', '#3b82f6', '#10b981']; const COLORS = ['#8b5cf6', '#3b82f6', '#10b981'];
const stats = [ const stats = [
{ title: 'درآمد کل', value: `${data.revenue.toLocaleString()} تومان`, icon: DollarSign, color: 'text-green-600', bg: 'bg-green-100', link: '/reports' }, { title: 'درآمد کل', value: `${(data?.revenue || 0).toLocaleString()} تومان`, icon: DollarSign, color: 'text-green-600', bg: 'bg-green-100', link: '/reports' },
{ title: 'سفارشات جدید', value: data.newOrders.toString(), icon: ShoppingCart, color: 'text-blue-600', bg: 'bg-blue-100', link: '/orders' }, { title: 'سفارشات جدید', value: (data?.newOrders || 0).toString(), icon: ShoppingCart, color: 'text-blue-600', bg: 'bg-blue-100', link: '/orders' },
{ title: 'کاربران فعال', value: data.users.toString(), icon: Users, color: 'text-purple-600', bg: 'bg-purple-100', link: '/users' }, { title: 'کاربران فعال', value: (data?.users || 0).toString(), icon: Users, color: 'text-purple-600', bg: 'bg-purple-100', link: '/users' },
{ title: 'بازدید امروز', value: data.todayVisits.toString(), icon: Activity, color: 'text-orange-600', bg: 'bg-orange-100', link: '/reports' }, { title: 'بازدید امروز', value: (data?.todayVisits || 0).toString(), icon: Activity, color: 'text-orange-600', bg: 'bg-orange-100', link: '/reports' },
]; ];
return ( return (
<div className="space-y-6 font-vazir" dir="rtl"> <div className="space-y-6 font-vazir" dir="rtl">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4"> <div>
<div> <h2 className="text-2xl font-black text-gray-900">داشبورد</h2>
<h2 className="text-2xl font-black text-gray-900">داشبورد فرماندهی کنینا</h2> <p className="text-gray-500 font-medium mt-1">خلاصه‌ای از وضعیت فروشگاه کنینا</p>
<p className="text-gray-500 font-medium mt-1">خلاصه عملیات، وضعیت دیتابیس و نظارت بر وظایف خودکار سازمان</p>
</div>
<div className="flex items-center gap-2">
<Link
to="/history"
className="flex items-center gap-1.5 px-3 py-2 bg-white border border-gray-200 hover:border-purple-300 text-gray-700 rounded-xl text-xs font-bold transition-all shadow-sm"
>
<History className="w-4 h-4 text-purple-600" />
<span>تاریخچه تغییرات دیتابیس</span>
</Link>
<Link
to="/tasks"
className="flex items-center gap-1.5 px-3 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-xl text-xs font-bold transition-all shadow-sm"
>
<Briefcase className="w-4 h-4" />
<span>کارتابل تسک‌ها ({taskStats.total})</span>
</Link>
</div>
</div> </div>
{/* Approval Gate Alert Banner */}
{pendingApprovalsCount > 0 && (
<div className="bg-gradient-to-r from-amber-500/10 via-amber-500/5 to-transparent border border-amber-500/30 rounded-2xl p-5 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
<div className="flex items-center gap-3.5">
<div className="w-12 h-12 rounded-xl bg-amber-500 text-white flex items-center justify-center shadow-lg shadow-amber-500/20 shrink-0">
<ShieldAlert className="w-6 h-6" />
</div>
<div>
<h3 className="font-bold text-gray-900 text-base flex items-center gap-2">
میز کار تاییدات و حاکمیت سازمانی
<span className="bg-amber-100 text-amber-800 text-xs px-2.5 py-0.5 rounded-full font-black">
{pendingApprovalsCount} مورد در انتظار تصمیم شما
</span>
</h3>
<p className="text-xs text-gray-500 mt-1 font-medium">
پیشنهادات کارشناسی دپارتمان‌ها (مالی، تامین، محتوا، بازاریابی و DevOps) معلق به تایید نهایی شما هستند.
</p>
</div>
</div>
<Link
to="/approvals"
className="flex items-center gap-2 bg-amber-500 hover:bg-amber-600 text-white font-bold text-xs px-4 py-2.5 rounded-xl transition-all shadow-sm shrink-0"
>
ورود به کارتابل و بررسی
<ArrowLeft className="w-4 h-4" />
</Link>
</div>
)}
{/* Quick Stats Grid */} {/* Quick Stats Grid */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6"> <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
{stats.map((stat, i) => { {stats.map((stat, i) => {
@@ -197,77 +88,6 @@ export default function Dashboard() {
})} })}
</div> </div>
{/* Live History Widget & Department Tasks Widget */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* Recent Audit Logs Widget */}
<div className="bg-white p-6 rounded-2xl shadow-sm border border-gray-100">
<div className="flex items-center justify-between mb-4">
<div className="flex items-center gap-2">
<Database className="w-5 h-5 text-purple-600" />
<h3 className="text-sm font-black text-gray-900">آخرین تغییرات زنده دیتابیس (Audit History)</h3>
</div>
<Link to="/history" className="text-xs font-bold text-purple-600 hover:underline">
مشاهده تمام لاگ‌ها
</Link>
</div>
<div className="space-y-3">
{recentLogs.length === 0 ? (
<div className="text-center py-6 text-gray-400 text-xs font-medium">
رکوردی در تاریخچه ثبت نشده است.
</div>
) : (
recentLogs.map((log) => (
<div key={log.id} className="p-3 bg-gray-50 rounded-xl flex items-center justify-between text-xs hover:bg-purple-50/40 transition-colors">
<div className="flex items-center gap-2.5 overflow-hidden">
<span className="w-2 h-2 rounded-full bg-purple-500 shrink-0" />
<div className="truncate">
<p className="font-bold text-gray-800 truncate">{log.summary}</p>
<span className="text-[10px] text-gray-400">{log.entity} • توسط {log.actor}</span>
</div>
</div>
<span className="text-[10px] text-gray-400 shrink-0 font-mono">
{new Date(log.createdAt).toLocaleTimeString('fa-IR')}
</span>
</div>
))
)}
</div>
</div>
{/* Department Tasks Live Pipeline Widget */}
<div className="bg-white p-6 rounded-2xl shadow-sm border border-gray-100">
<div className="flex items-center justify-between mb-4">
<div className="flex items-center gap-2">
<Briefcase className="w-5 h-5 text-indigo-600" />
<h3 className="text-sm font-black text-gray-900">پایپ‌لاین وظایف دپارتمان‌ها و ایجنت‌ها</h3>
</div>
<Link to="/tasks" className="text-xs font-bold text-indigo-600 hover:underline">
ورود به تسک منیجر
</Link>
</div>
<div className="grid grid-cols-3 gap-3 mb-4">
<div className="p-3 bg-gray-50 rounded-xl text-center">
<div className="text-lg font-black text-gray-800">{taskStats.total}</div>
<div className="text-[11px] font-bold text-gray-500">کل تسک‌ها</div>
</div>
<div className="p-3 bg-blue-50 rounded-xl text-center">
<div className="text-lg font-black text-blue-700">{taskStats.inProgress}</div>
<div className="text-[11px] font-bold text-blue-600">در حال انجام</div>
</div>
<div className="p-3 bg-emerald-50 rounded-xl text-center">
<div className="text-lg font-black text-emerald-700">{taskStats.done}</div>
<div className="text-[11px] font-bold text-emerald-600">تکمیل‌شده</div>
</div>
</div>
<p className="text-xs text-gray-500 leading-relaxed font-medium">
تمام تسک‌های تاییدشده به صورت خودکار به پایپ‌لاین اجرایی منتقل شده و لاگ تغییرات آنها در جدول دیتابیس و تاریخچه به ثبت می‌رسد.
</p>
</div>
</div>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6"> <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
<div className="bg-white p-6 rounded-2xl shadow-sm border border-gray-100 col-span-1 lg:col-span-2"> <div className="bg-white p-6 rounded-2xl shadow-sm border border-gray-100 col-span-1 lg:col-span-2">
<h3 className="text-lg font-bold text-gray-900 mb-6">روند بازدید و فروش (۷ روز گذشته)</h3> <h3 className="text-lg font-bold text-gray-900 mb-6">روند بازدید و فروش (۷ روز گذشته)</h3>
@@ -1,15 +1,15 @@
import { import {
Activity, Activity,
CheckCircle2, CheckCircle2,
Clock, Clock,
CreditCard, CreditCard,
Database, Database,
FileText, FileText,
MessageSquare, MessageSquare,
RefreshCw, RefreshCw,
Truck Truck
} from 'lucide-react'; } from 'lucide-react';
import { useCallback,useEffect,useState } from 'react'; import { useCallback, useEffect, useState } from 'react';
import { toast } from 'react-hot-toast'; import { toast } from 'react-hot-toast';
import Badge from '../components/ui/Badge'; import Badge from '../components/ui/Badge';
import Button from '../components/ui/Button'; import Button from '../components/ui/Button';
@@ -80,7 +80,7 @@ export default function MonitoringPage() {
timestamp: new Date().toLocaleTimeString('fa-IR'), timestamp: new Date().toLocaleTimeString('fa-IR'),
zibal: { zibal: {
status: !health || health.status === 'OFFLINE' ? 'OFFLINE' : health.status === 'DEGRADED' || health.latencyMs > 1500 ? 'DEGRADED' : 'ONLINE', status: !health || health.status === 'OFFLINE' ? 'OFFLINE' : health.status === 'DEGRADED' || health.latencyMs > 1500 ? 'DEGRADED' : 'ONLINE',
latencyMs: health?.latencyMs || Math.floor(Math.random() * 80) + 120, latencyMs: health?.latencyMs ?? 0,
merchantId: health?.activeMerchant || health?.merchantId || 'zibal-live-merchant', merchantId: health?.activeMerchant || health?.merchantId || 'zibal-live-merchant',
todayVolumeTomans: txStats?.todayVolume ? Math.floor(Number(txStats.todayVolume)) : 0, todayVolumeTomans: txStats?.todayVolume ? Math.floor(Number(txStats.todayVolume)) : 0,
todayTxCount: txStats?.todayVerified || txStats?.verifiedCount || 0, todayTxCount: txStats?.todayVerified || txStats?.verifiedCount || 0,
@@ -89,14 +89,14 @@ export default function MonitoringPage() {
melipayamak: { melipayamak: {
status: smsCreditVal !== undefined && smsCreditVal !== null ? 'ONLINE' : 'OFFLINE', status: smsCreditVal !== undefined && smsCreditVal !== null ? 'ONLINE' : 'OFFLINE',
credit: smsCreditVal !== undefined && smsCreditVal !== null ? `${Number(smsCreditVal).toLocaleString('fa-IR')} پیامک` : 'نامشخص', credit: smsCreditVal !== undefined && smsCreditVal !== null ? `${Number(smsCreditVal).toLocaleString('fa-IR')} پیامک` : 'نامشخص',
latencyMs: Math.floor(Math.random() * 60) + 95, latencyMs: 0,
todaySmsSent: 48, todaySmsSent: 48,
patternActive: true, patternActive: true,
}, },
post: { post: {
status: 'ONLINE', status: 'ONLINE',
latencyMs: Math.floor(Math.random() * 110) + 140, latencyMs: 0,
trackingActive: true, trackingActive: true,
}, },
system: { system: {
@@ -0,0 +1,15 @@
import { describe, expect, it } from 'vitest';
import routes from '../routes/adminRoutes.tsx?raw';
const pages = import.meta.glob('./*.tsx');
// Approvals and manager actions were removed in effe30e. Keep this boundary
// covered without importing the deleted page or restoring its obsolete UI.
describe('operational authorization boundary', () => {
it('does not register removed approvals or manager-action pages', () => {
expect(routes).not.toMatch(/ApprovalsPage|ManagerActionsPage/);
expect(routes).not.toMatch(/path:\s*['"](?:approvals|manager-actions)(?:\/\*)?['"]/);
expect(pages).not.toHaveProperty('./ApprovalsPage.tsx');
expect(pages).not.toHaveProperty('./ManagerActionsPage.tsx');
});
});
+26
View File
@@ -31,11 +31,13 @@ import api from '../services/api';
export interface OrderItem { export interface OrderItem {
requiresRx?: boolean;
id?: string; id?: string;
name?: string; name?: string;
priceValue?: number; priceValue?: number;
quantity?: number; quantity?: number;
product?: { product?: {
requiresRx?: boolean;
id?: string; id?: string;
nameFa?: string; nameFa?: string;
name?: string; name?: string;
@@ -758,6 +760,12 @@ export default function Orders() {
سفارش جدید سفارش جدید
</span> </span>
)} )}
{(order.orderItems || order.items || []).some(it => it.product?.requiresRx) && (
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-black bg-rose-600 text-white shadow-xs animate-pulse" title="نیازمند تماس تلفنی و تایید نسخه دامپزشک">
<span>Rx</span>
<span>هماهنگی نسخه</span>
</span>
)}
</div> </div>
<div className="flex flex-wrap gap-1.5 mt-2 font-vazir" dir="rtl"> <div className="flex flex-wrap gap-1.5 mt-2 font-vazir" dir="rtl">
<span className={`text-[10px] font-bold font-vazir px-2 py-0.5 rounded-md border flex items-center gap-1 shadow-sm ${payInfo.color}`}> <span className={`text-[10px] font-bold font-vazir px-2 py-0.5 rounded-md border flex items-center gap-1 shadow-sm ${payInfo.color}`}>
@@ -911,6 +919,24 @@ export default function Orders() {
> >
<div className="space-y-6"> <div className="space-y-6">
{/* Rx Warning Notice for Admin */}
{(selectedOrder.orderItems || selectedOrder.items || []).some(it => it.requiresRx || it.product?.requiresRx) && (
<div className="bg-rose-50 border border-rose-200 rounded-2xl p-4 flex items-center justify-between gap-3 text-rose-900 font-vazir shadow-xs" dir="rtl">
<div className="flex items-center gap-2.5">
<span className="w-8 h-8 rounded-xl bg-rose-600 text-white flex items-center justify-center font-black text-xs shrink-0 shadow-sm">Rx</span>
<div>
<h4 className="text-xs font-black">این سفارش شامل داروی نیازمند نسخه و نظارت دامپزشکی است</h4>
<p className="text-[11px] text-rose-700 font-medium mt-0.5">ارسال سفارش تنها پس از تماس تلفنی کارشناس پشتیبانی و تایید نسخه معتبر انجام شود.</p>
</div>
</div>
<a
href={`tel:${selectedOrder.user?.mobile || selectedOrder.user?.phone || ''}`}
className="bg-rose-600 hover:bg-rose-700 text-white px-3.5 py-2 rounded-xl text-xs font-bold transition-all shadow-sm flex items-center gap-1.5 shrink-0"
>
<span>تماس با مشتری</span>
</a>
</div>
)}
{/* Status & Timing Banner */} {/* Status & Timing Banner */}
<div className="flex flex-wrap items-center justify-between gap-4 p-4 bg-purple-50/50 rounded-2xl border border-purple-100"> <div className="flex flex-wrap items-center justify-between gap-4 p-4 bg-purple-50/50 rounded-2xl border border-purple-100">
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
+7 -146
View File
@@ -1,3 +1,4 @@
import { ProductFaqTab } from "../components/products/ProductFaqTab";
import { import {
Activity, Activity,
AlertTriangle, AlertTriangle,
@@ -2317,152 +2318,12 @@ export default function Products() {
</div> </div>
{/* FAQ Tab */} {/* FAQ Tab */}
<div className={activeTab === 'faq' ? 'block space-y-5' : 'hidden'}> {/* FAQ Tab */}
{/* Top FAQ Controls */} <ProductFaqTab
<div className="bg-white p-5 rounded-2xl border border-gray-200 shadow-sm space-y-4"> activeTab={activeTab}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 border-b pb-4"> formData={formData}
<div> setFormData={setFormData}
<h4 className="text-sm font-black text-gray-800 flex items-center gap-2"> />
<HelpCircle className="w-4 h-4 text-purple-600" />
<span>بخش پرسش و پاسخ‌های متداول محصول (Product FAQs)</span>
</h4>
<p className="text-xs text-gray-500 mt-0.5">مدیریت آکاردئون پرسش‌های متداول در صفحه کالا و ثبت خودکار در سئوی گوگل (FAQPage Schema)</p>
</div>
<div className="flex items-center gap-2 shrink-0">
<label className="relative inline-flex items-center cursor-pointer">
<input
type="checkbox"
className="sr-only peer"
checked={formData.showFaqs}
onChange={(e) => setFormData({ ...formData, showFaqs: e.target.checked })}
/>
<div className="w-11 h-6 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-purple-600"></div>
</label>
<span className="text-xs font-bold text-gray-700">
{formData.showFaqs ? 'بخش FAQ فعال است' : 'بخش FAQ غیرفعال است'}
</span>
</div>
</div>
<div className="flex items-center justify-between flex-wrap gap-2 pt-1">
<Button
type="button"
variant="outline"
size="sm"
startIcon={Plus}
onClick={() => {
setFormData({
...formData,
faqs: [...(formData.faqs || []), { question: '', answer: '' }]
});
}}
className="border-purple-200 text-purple-700 hover:bg-purple-50 text-xs font-bold"
>
افزودن سوال جدید
</Button>
<button
type="button"
onClick={() => {
const name = formData.nameFa || 'این محصول';
setFormData({
...formData,
faqs: [
{
question: `آیا لیسیدن ${name} توسط حیوان خطرناک است؟`,
answer: `خیر، ترکیبات این محصول با استانداردهای دارویی آلمان فرموله شده و فاقد مواد نگهدارنده شیمیایی مضر است. لیسیدن محدود آن باعث مسمومیت نمی‌شود؛ اما جهت اثربخشی و جذب حداکثری، پیشنهاد می‌شود ۱۰ تا ۱۵ دقیقه حواس حیوان پرت شود.`
},
{
question: `مدت زمان ماندگاری و شرایط نگهداری ${name} چگونه است؟`,
answer: `این محصول در جای خشک، خنک (دمای زیر ۲۵ درجه سانتی‌گراد) و دور از تابش مستقیم نور خورشید نگهداری شود. مدت زمان مجاز مصرف پس از باز شدن درب (PAO) ${formData.paoMonths ? `${formData.paoMonths} ماه` : '۱۲ ماه'} می‌باشد.`
},
{
question: `آیا برای توله‌ها و حیوانات باردار یا شیرده قابل استفاده است؟`,
answer: `بله، با توجه به فرمولاسیون ۱۰۰٪ طبیعی و عدم وجود هورمون یا مواد شیمیایی سنتتیک، استفاده از این محصول برای تمامی رده‌های سنی و دوران حساس بارداری و شیردهی طبق دستورالعمل ایمن است.`
},
{
question: `در صورت استفاده همزمان با سایر داروها یا پمادها چه نکاتی باید رعایت شود؟`,
answer: `جهت جلوگیری از تداخل در جذب، توصیه می‌شود بین استفاده از این محصول و سایر داروها، اسپری‌ها یا مکمل‌های درمانی حداقل ۲۰ الی ۳۰ دقیقه فاصله زمانی رعایت شود.`
}
]
});
toast.success('سوالات متداول استاندارد کاتالوگ بارگذاری شدند');
}}
className="text-xs text-purple-600 hover:text-purple-800 font-bold flex items-center gap-1 hover:underline"
>
درج سوالات متداول پیشنهادی کاتالوگ Canina ⚡
</button>
</div>
</div>
{/* FAQ Items List */}
{formData.faqs && formData.faqs.length > 0 ? (
<div className="space-y-3">
{formData.faqs.map((faq, idx) => (
<div key={idx} className="bg-white p-4 rounded-2xl border border-gray-200 shadow-xs space-y-3 relative group">
<div className="flex items-center justify-between gap-2 border-b border-gray-100 pb-2">
<span className="text-xs font-black text-purple-700 bg-purple-50 px-2.5 py-0.5 rounded-full">
سوال {idx + 1}
</span>
<button
type="button"
onClick={() => {
const newFaqs = formData.faqs.filter((_, i) => i !== idx);
setFormData({ ...formData, faqs: newFaqs });
}}
className="text-red-400 hover:text-red-600 p-1 rounded-lg hover:bg-red-50 transition-colors"
title="حذف این سوال"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
<div className="space-y-1.5">
<label className="text-xs font-bold text-gray-700">متن پرسش:</label>
<input
type="text"
value={faq.question}
onChange={(e) => {
const updated = [...formData.faqs];
updated[idx].question = e.target.value;
setFormData({ ...formData, faqs: updated });
}}
placeholder="مثال: آیا لیسیدن این محصول خطرناک است؟"
className="w-full px-3 py-2 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-xs font-bold font-vazir"
/>
</div>
<div className="space-y-1.5">
<label className="text-xs font-bold text-gray-700">متن پاسخ علمی و کامل:</label>
<textarea
rows={3}
value={faq.answer}
onChange={(e) => {
const updated = [...formData.faqs];
updated[idx].answer = e.target.value;
setFormData({ ...formData, faqs: updated });
}}
placeholder="پاسخ کامل و علمی را وارد نمایید..."
className="w-full px-3 py-2 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-xs leading-relaxed font-vazir"
/>
</div>
</div>
))}
</div>
) : (
<div className="bg-white p-8 rounded-2xl border border-dashed border-gray-300 text-center space-y-3">
<div className="w-12 h-12 rounded-2xl bg-purple-50 text-purple-600 flex items-center justify-center mx-auto">
<HelpCircle className="w-6 h-6" />
</div>
<div className="space-y-1">
<h5 className="text-sm font-black text-gray-800">هیچ پرسش و پاسخی ثبت نشده است</h5>
<p className="text-xs text-gray-500 max-w-md mx-auto">
می‌توانید با کلیک بر روی «درج سوالات متداول پیشنهادی»، پرسش‌های متداول کاتالوگ دارویی را به صورت خودکار بارگذاری و سپس شخصی‌سازی نمایید.
</p>
</div>
</div>
)}
</div>
{/* Pricing Tab */} {/* Pricing Tab */}
<div className={activeTab === 'pricing' ? 'block space-y-4' : 'hidden'}> <div className={activeTab === 'pricing' ? 'block space-y-4' : 'hidden'}>
@@ -7,7 +7,10 @@ type Conversation = { id: string; createdAt: string; updatedAt: string; entryPat
const unwrap = (r: any) => r.data?.data ?? r.data; const unwrap = (r: any) => r.data?.data ?? r.data;
export default function SupportChatAnalyticsPage() { export default function SupportChatAnalyticsPage() {
const [stats, setStats] = useState<Stats | null>(null); const [rows, setRows] = useState<Conversation[]>([]); const [error, setError] = useState(""); const [dates, setDates] = useState({ startDate: "", endDate: "" }); const [stats, setStats] = useState<Stats | null>(null); const [rows, setRows] = useState<Conversation[]>([]); const [error, setError] = useState(""); const [dates, setDates] = useState({ startDate: "", endDate: "" });
const load = async () => { try { setError(""); const params = Object.fromEntries(Object.entries(dates).filter(([, v]) => v)); const [s, c] = await Promise.all([api.get("/admin/support-chat/stats", { params }), api.get("/admin/support-chat/conversations", { params: { ...params, page: 1, limit: 50 } })]); setStats(unwrap(s)); setRows(unwrap(c).data || []); } catch { setError("گزارش پشتیبان بارگذاری نشد."); } }; const load = async () => { try { setError(""); const params = Object.fromEntries(Object.entries(dates).filter(([, v]) => v)); const [s, c] = await Promise.all([api.get("/admin/support-chat/stats", { params }), api.get("/admin/support-chat/conversations", { params: { ...params, page: 1, limit: 50 } })]); const statsData = unwrap(s);
const convData = unwrap(c);
setStats(statsData);
setRows(Array.isArray(convData) ? convData : (Array.isArray(convData?.data) ? convData.data : [])); } catch { setError("گزارش پشتیبان بارگذاری نشد."); } };
useEffect(() => { void load(); }, []); useEffect(() => { void load(); }, []);
return <div dir="rtl" className="space-y-6"> return <div dir="rtl" className="space-y-6">
<div className="flex items-center justify-between"><div><h1 className="text-2xl font-black">تحلیل مشاورهٔ سایت</h1><p className="text-gray-500">تعداد استفاده، سؤال‌ها، پاسخ‌ها و موارد نیازمند پیگیری</p></div><Link className="rounded-lg border px-4 py-2" to="/settings/smart-chat/config">تنظیمات دستیار</Link><button className="rounded-lg bg-canina-blue px-4 py-2 text-white" onClick={() => void load()}>به‌روزرسانی</button></div> <div className="flex items-center justify-between"><div><h1 className="text-2xl font-black">تحلیل مشاورهٔ سایت</h1><p className="text-gray-500">تعداد استفاده، سؤال‌ها، پاسخ‌ها و موارد نیازمند پیگیری</p></div><Link className="rounded-lg border px-4 py-2" to="/settings/smart-chat/config">تنظیمات دستیار</Link><button className="rounded-lg bg-canina-blue px-4 py-2 text-white" onClick={() => void load()}>به‌روزرسانی</button></div>
@@ -0,0 +1,24 @@
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
import { beforeEach, expect, it, vi } from "vitest";
import api from "../services/api";
import SymptomsPage from "./SymptomsPage";
vi.mock("../services/api", () => ({default: {get: vi.fn(), delete: vi.fn()}}));
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(api.get).mockResolvedValue({data: {data: [{id:"symptom-1", name:"Anemia", slug:"anemia"}], meta:{lastPage:1}}});
vi.mocked(api.delete).mockResolvedValue({data:{}});
});
it("shows deletion consequences and cancels without deleting, then confirms the selected symptom", async () => {
render(<MemoryRouter><SymptomsPage/></MemoryRouter>);
await screen.findByText("Anemia");
fireEvent.click(screen.getByTitle("حذف"));
expect(screen.getByText(/با حذف این علامت، ارتباط آن/)).toBeInTheDocument();
fireEvent.click(screen.getByRole("button",{name:"لغو"}));
expect(screen.queryByText(/با حذف این علامت، ارتباط آن/)).not.toBeInTheDocument();
expect(api.delete).not.toHaveBeenCalled();
fireEvent.click(screen.getByTitle("حذف"));
fireEvent.click(screen.getByRole("button",{name:"تایید"}));
await waitFor(() => expect(api.delete).toHaveBeenCalledWith("/admin/symptoms/symptom-1"));
await waitFor(() => expect(screen.queryByText(/با حذف این علامت، ارتباط آن/)).not.toBeInTheDocument());
});
@@ -0,0 +1,321 @@
import { Edit2, Plus, Search, Trash2, Activity, Tag, Sparkles } from 'lucide-react';
import { useCallback, useEffect, useState } from 'react';
import { toast } from 'react-hot-toast';
import Button from '../components/ui/Button';
import ConfirmModal from '../components/ui/ConfirmModal';
import Modal from '../components/ui/Modal';
import Pagination from '../components/ui/Pagination';
import Spinner from '../components/ui/Spinner';
import api from '../services/api';
import { useSearchParams } from 'react-router-dom';
export interface Symptom {
id: string;
name: string;
slug: string;
description?: string;
metaTitle?: string;
metaDescription?: string;
keywords?: string;
productsCount?: number;
createdAt?: string;
}
export default function SymptomsPage() {
const [searchParams] = useSearchParams();
const [symptoms, setSymptoms] = useState<Symptom[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [search, setSearch] = useState(() => searchParams.get('search') || '');
const [page, setPage] = useState(() => Number(searchParams.get('page')) || 1);
const [totalPages, setTotalPages] = useState(1);
const limit = 15;
const [isModalOpen, setIsModalOpen] = useState(false);
const [editingSymptom, setEditingSymptom] = useState<Symptom | null>(null);
const [deleteTargetId, setDeleteTargetId] = useState<string | null>(null);
const [isSubmitting, setIsSubmitting] = useState(false);
const [formData, setFormData] = useState({
name: '',
slug: '',
description: '',
metaTitle: '',
metaDescription: '',
keywords: ''
});
const openModal = (symptom: Symptom | null = null) => {
if (symptom) {
setEditingSymptom(symptom);
setFormData({
name: symptom.name,
slug: symptom.slug,
description: symptom.description || '',
metaTitle: symptom.metaTitle || '',
metaDescription: symptom.metaDescription || '',
keywords: symptom.keywords || ''
});
} else {
setEditingSymptom(null);
setFormData({
name: '',
slug: '',
description: '',
metaTitle: '',
metaDescription: '',
keywords: ''
});
}
setIsModalOpen(true);
};
const closeModal = () => {
setIsModalOpen(false);
};
const fetchSymptoms = useCallback(async () => {
try {
setIsLoading(true);
const res = await api.get('/admin/symptoms', { params: { page, limit, search } });
if (res.data?.data) {
setSymptoms(res.data.data);
setTotalPages(res.data.meta?.lastPage || 1);
}
} catch {
toast.error('خطا در دریافت لیست علائم');
} finally {
setIsLoading(false);
}
}, [page, search]);
useEffect(() => {
fetchSymptoms();
}, [fetchSymptoms]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!formData.name.trim()) {
toast.error('نام علامت الزامی است');
return;
}
try {
setIsSubmitting(true);
if (editingSymptom) {
await api.put(`/admin/symptoms/${editingSymptom.id}`, formData);
toast.success('علامت با موفقیت ویرایش و در تمامی محصولات همگام شد');
} else {
await api.post('/admin/symptoms', formData);
toast.success('علامت درمانی جدید با موفقیت ایجاد شد');
}
closeModal();
fetchSymptoms();
} catch {
toast.error('خطا در ذخیره اطلاعات علامت');
} finally {
setIsSubmitting(false);
}
};
const handleDelete = async () => {
if (!deleteTargetId) return;
try {
await api.delete(`/admin/symptoms/${deleteTargetId}`);
toast.success('علامت با موفقیت حذف شد');
setDeleteTargetId(null);
fetchSymptoms();
} catch {
toast.error('خطا در حذف علامت');
}
};
return (
<div className="space-y-6 font-vazir" dir="rtl">
{/* Header */}
<div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 bg-white p-6 rounded-3xl border border-gray-100 shadow-sm">
<div>
<div className="flex items-center gap-2.5">
<span className="w-10 h-10 rounded-2xl bg-canina-blue/10 text-canina-blue flex items-center justify-center">
<Activity className="w-5 h-5 text-purple-600" />
</span>
<h1 className="text-xl font-black text-gray-900">مدیریت علائم بالینی و درمانی</h1>
</div>
<p className="text-xs text-gray-500 font-bold mt-1">
تعریف و ویرایش علائم، بهینه‌سازی متادیتاهای سئو و همگام‌سازی یکپارچه با محصولات کاتالوگ
</p>
</div>
<Button onClick={() => openModal()} className="bg-purple-600 hover:bg-purple-700 text-white rounded-2xl px-5 py-3 flex items-center gap-2 font-bold text-xs shadow-md shadow-purple-600/20">
<Plus className="w-4 h-4" />
<span>افزودن علامت جدید</span>
</Button>
</div>
{/* Filter & Search */}
<div className="bg-white p-4 rounded-3xl border border-gray-100 shadow-sm flex items-center gap-3">
<div className="relative flex-1">
<Search className="w-4 h-4 text-gray-400 absolute right-3 top-1/2 -translate-y-1/2" />
<input
type="text"
placeholder="جستجوی علامت بالینی بر اساس نام یا اسلاگ..."
value={search}
onChange={(e) => {
setSearch(e.target.value);
setPage(1);
}}
className="w-full bg-gray-50 border border-gray-200 rounded-2xl py-2.5 pr-10 pl-4 text-xs focus:outline-none focus:ring-2 focus:ring-purple-500/20"
/>
</div>
</div>
{/* Table */}
<div className="bg-white rounded-3xl border border-gray-100 shadow-sm overflow-hidden">
{isLoading ? (
<div className="py-20 flex justify-center">
<Spinner />
</div>
) : symptoms.length === 0 ? (
<div className="py-20 text-center text-gray-400 font-bold text-sm">
هیچ علامت بالینی یافت نشد.
</div>
) : (
<div className="overflow-x-auto">
<table className="w-full text-right text-xs">
<thead className="bg-gray-50/75 border-b border-gray-100 text-gray-500 font-black uppercase">
<tr>
<th className="px-6 py-4">نام علامت بالینی</th>
<th className="px-6 py-4">اسلاگ URL</th>
<th className="px-6 py-4">محصولات متصل</th>
<th className="px-6 py-4">سئو متاتایتل</th>
<th className="px-6 py-4 text-left">عملیات</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100">
{symptoms.map((symptom) => (
<tr key={symptom.id} className="hover:bg-purple-50/20 transition-colors">
<td className="px-6 py-4 font-black text-gray-900 flex items-center gap-2">
<Tag className="w-3.5 h-3.5 text-purple-600" />
<span>{symptom.name}</span>
</td>
<td className="px-6 py-4 font-mono text-gray-500 dir-ltr text-right">
{symptom.slug}
</td>
<td className="px-6 py-4">
<span className="px-2.5 py-1 bg-purple-50 text-purple-700 font-black rounded-lg border border-purple-100">
{symptom.productsCount || 0} محصول
</span>
</td>
<td className="px-6 py-4 text-gray-600 max-w-xs truncate" title={symptom.metaTitle}>
{symptom.metaTitle || '—'}
</td>
<td className="px-6 py-4 text-left space-x-2 space-x-reverse">
<button
onClick={() => openModal(symptom)}
className="p-2 text-blue-600 hover:bg-blue-50 rounded-xl transition-colors"
title="ویرایش و سئو"
>
<Edit2 className="w-4 h-4" />
</button>
<button
onClick={() => setDeleteTargetId(symptom.id)}
className="p-2 text-red-600 hover:bg-red-50 rounded-xl transition-colors"
title="حذف"
>
<Trash2 className="w-4 h-4" />
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
<div className="p-4 border-t border-gray-100 flex justify-center">
<Pagination currentPage={page} totalPages={totalPages} onPageChange={(p) => setPage(p)} />
</div>
</div>
{/* Modal CRUD */}
<Modal isOpen={isModalOpen} onClose={closeModal} title={editingSymptom ? 'ویرایش علامت و سئو' : 'تعریف علامت جدید'}>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className="block text-xs font-bold text-gray-700 mb-1">نام علامت درمانی (فارسی) *</label>
<input
type="text"
required
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
className="w-full bg-gray-50 border border-gray-200 rounded-xl p-3 text-xs focus:outline-none focus:ring-2 focus:ring-purple-500/20"
placeholder="مثلاً: پوکی استخوان یا کم‌خونی"
/>
</div>
<div>
<label className="block text-xs font-bold text-gray-700 mb-1">اسلاگ URL و انگلیسی</label>
<input
type="text"
value={formData.slug}
onChange={(e) => setFormData({ ...formData, slug: e.target.value })}
className="w-full bg-gray-50 border border-gray-200 rounded-xl p-3 text-xs dir-ltr focus:outline-none focus:ring-2 focus:ring-purple-500/20"
placeholder="anemia یا osteoporosis"
/>
</div>
<div>
<label className="block text-xs font-bold text-gray-700 mb-1">توضیحات تشخیصی و بالینی</label>
<textarea
rows={3}
value={formData.description}
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
className="w-full bg-gray-50 border border-gray-200 rounded-xl p-3 text-xs focus:outline-none focus:ring-2 focus:ring-purple-500/20"
placeholder="توضیحات بالینی و پروتکل‌های مکمل‌های درمانی..."
/>
</div>
<div className="pt-2 border-t border-gray-100 space-y-3">
<div className="flex items-center gap-1.5 text-xs font-black text-purple-700">
<Sparkles className="w-3.5 h-3.5" />
<span>تنظیمات پیشرفته سئو (SEO Meta)</span>
</div>
<div>
<label className="block text-[11px] font-bold text-gray-600 mb-1">Meta Title</label>
<input
type="text"
value={formData.metaTitle}
onChange={(e) => setFormData({ ...formData, metaTitle: e.target.value })}
className="w-full bg-gray-50 border border-gray-200 rounded-xl p-2.5 text-xs"
placeholder="عنوان سئو در نتایج گوگل..."
/>
</div>
<div>
<label className="block text-[11px] font-bold text-gray-600 mb-1">Meta Description</label>
<textarea
rows={2}
value={formData.metaDescription}
onChange={(e) => setFormData({ ...formData, metaDescription: e.target.value })}
className="w-full bg-gray-50 border border-gray-200 rounded-xl p-2.5 text-xs"
placeholder="توضیحات متای صفحه سئو..."
/>
</div>
</div>
<div className="flex justify-end gap-2 pt-4">
<Button type="button" variant="outline" onClick={closeModal}>انصراف</Button>
<Button type="submit" disabled={isSubmitting} className="bg-purple-600 hover:bg-purple-700 text-white">
{isSubmitting ? 'در حال ثبت...' : (editingSymptom ? 'بروزرسانی یکپارچه' : 'ثبت علامت')}
</Button>
</div>
</form>
</Modal>
{/* Delete Confirmation */}
<ConfirmModal
isOpen={!!deleteTargetId}
onCancel={() => setDeleteTargetId(null)}
onConfirm={handleDelete}
title="حذف علامت بالینی"
message="با حذف این علامت، ارتباط آن از تمام محصولات کاتالوگ نیز به طور خودکار حذف خواهد شد. آیا مطمئن هستید؟"
/>
</div>
);
}
@@ -1,508 +0,0 @@
import React, { useState, useEffect } from 'react';
import {
Search,
RefreshCw,
Bot,
Briefcase,
ChevronDown,
ChevronLeft,
ChevronRight,
Play,
CheckCircle,
Clock,
Filter
} from 'lucide-react';
import api from '../services/api';
import toast from 'react-hot-toast';
interface DepartmentTask {
id: string;
code: string;
department: string;
title: string;
description?: string;
status: string;
priority: string;
assignee: string;
acceptanceCriteria?: any;
executionLogs?: any;
deliverableUrl?: string;
startedAt?: string;
completedAt?: string;
createdAt: string;
}
export default function TasksManagementPage() {
const [tasks, setTasks] = useState<DepartmentTask[]>([]);
const [loading, setLoading] = useState(true);
const [searchTerm, setSearchTerm] = useState('');
const [selectedDept, setSelectedDept] = useState('ALL');
const [selectedStatus, setSelectedStatus] = useState('ALL');
const [selectedPriority, setSelectedPriority] = useState('ALL');
const [activeTaskModal, setActiveTaskModal] = useState<DepartmentTask | null>(null);
const [logNote, setLogNote] = useState('');
const [updating, setUpdating] = useState(false);
// Pagination states
const [currentPage, setCurrentPage] = useState(1);
const itemsPerPage = 10;
const fetchTasks = async () => {
setLoading(true);
try {
const res = await api.get('/admin/department-tasks?limit=200');
if (res.data?.success) {
setTasks(res.data.data);
}
} catch (err) {
console.error('Error fetching tasks:', err);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchTasks();
}, []);
const handleStatusChange = async (taskId: string, newStatus: string) => {
setUpdating(true);
try {
const res = await api.put(`/admin/department-tasks/${taskId}/status`, {
status: newStatus,
logNote: logNote || `تغییر وضعیت به ${newStatus}`,
});
if (res.data?.success) {
toast.success(`وضعیت تسک به ${newStatus} به‌روزرسانی شد`);
setLogNote('');
setActiveTaskModal(null);
fetchTasks();
}
} catch (err) {
toast.error('خطا در به‌روزرسانی وضعیت تسک');
} finally {
setUpdating(false);
}
};
const filteredTasks = tasks.filter((t) => {
const matchesSearch =
!searchTerm ||
t.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
t.code.toLowerCase().includes(searchTerm.toLowerCase()) ||
(t.description && t.description.toLowerCase().includes(searchTerm.toLowerCase()));
const matchesDept = selectedDept === 'ALL' || t.department === selectedDept;
const matchesStatus = selectedStatus === 'ALL' || t.status === selectedStatus;
const matchesPriority = selectedPriority === 'ALL' || t.priority === selectedPriority;
return matchesSearch && matchesDept && matchesStatus && matchesPriority;
});
// Calculate pagination
const totalPages = Math.ceil(filteredTasks.length / itemsPerPage) || 1;
const paginatedTasks = filteredTasks.slice(
(currentPage - 1) * itemsPerPage,
currentPage * itemsPerPage
);
const getStatusBadge = (status: string) => {
switch (status) {
case 'TODO':
case 'BACKLOG':
return (
<span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-gray-100 text-gray-700 border border-gray-200">
۱. صف اقدام (TODO)
</span>
);
case 'IN_PROGRESS':
return (
<span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-blue-100 text-blue-800 border border-blue-200 animate-pulse">
۲. در حال توسعه (IN_PROGRESS)
</span>
);
case 'TEST':
case 'IN_REVIEW':
return (
<span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-amber-100 text-amber-800 border border-amber-200">
۳. تست استیج و QA (TEST)
</span>
);
case 'DONE':
return (
<span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-emerald-100 text-emerald-800 border border-emerald-200">
۴. مستقر پروداکشن (DONE)
</span>
);
default:
return <span>{status}</span>;
}
};
const getPriorityBadge = (priority: string) => {
switch (priority) {
case 'CRITICAL':
return <span className="px-1.5 py-0.5 text-[9px] font-black bg-rose-600 text-white rounded">فوری / بحرانی</span>;
case 'HIGH':
return <span className="px-1.5 py-0.5 text-[9px] font-black bg-rose-100 text-rose-700 rounded border border-rose-200">بالا</span>;
case 'MEDIUM':
return <span className="px-1.5 py-0.5 text-[9px] font-black bg-amber-100 text-amber-700 rounded border border-amber-200">متوسط</span>;
default:
return <span className="px-1.5 py-0.5 text-[9px] font-black bg-gray-100 text-gray-600 rounded">عادی</span>;
}
};
const getDeptName = (dept: string) => {
const map: Record<string, string> = {
DEV: 'مهندسی و توسعه',
COMMERCE: 'بازرگانی و مالی',
PRODUCT: 'کاتالوگ و انبار',
CONTENT: 'تولید محتوا و سئو',
SEO: 'رشد و مارکتینگ',
CRM: 'ارتباط با مشتریان',
PMO: 'مدیریت و استراتژی',
};
return map[dept] || dept;
};
const renderAcceptanceCriteria = (criteria: any) => {
if (!criteria) return null;
if (typeof criteria === 'string') return criteria;
if (typeof criteria === 'object') {
if (criteria.rule) return criteria.rule;
try {
return JSON.stringify(criteria, null, 2);
} catch (e) {
return String(criteria);
}
}
return String(criteria);
};
const renderExecutionLogs = (logs: any) => {
if (!logs) return [];
if (Array.isArray(logs)) return logs;
if (typeof logs === 'object') {
return [
{
note: logs.notes || logs.message || JSON.stringify(logs),
timestamp: new Date().toISOString(),
status: logs.status || 'LOG',
},
];
}
return [{ note: String(logs), timestamp: new Date().toISOString(), status: 'LOG' }];
};
return (
<div className="space-y-6 font-vazir pb-12" dir="rtl">
{/* Top Header */}
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4 bg-white p-6 rounded-2xl border border-gray-100 shadow-sm">
<div>
<div className="flex items-center gap-3 mb-1">
<div className="w-10 h-10 rounded-xl bg-purple-100 flex items-center justify-center text-purple-700">
<Briefcase className="w-5 h-5" />
</div>
<div>
<h1 className="text-xl font-black text-gray-900">مدیریت تسک‌های دپارتمان‌ها و ایجنت‌ها (Task Manager)</h1>
<p className="text-xs text-gray-500 font-medium">پایش لحظه‌ای فعالیت‌های خودکار، استیت تسک‌ها و تضمین کیفیت تحویل</p>
</div>
</div>
</div>
<button
onClick={fetchTasks}
disabled={loading}
className="inline-flex items-center gap-2 px-4 py-2.5 rounded-xl bg-purple-50 text-purple-700 text-xs font-bold hover:bg-purple-100 transition-colors border border-purple-200 cursor-pointer disabled:opacity-50"
>
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
<span>به‌روزرسانی وظایف</span>
</button>
</div>
{/* Filter and Search Bar */}
<div className="bg-white p-4 rounded-2xl border border-gray-100 shadow-sm space-y-4">
<div className="grid grid-cols-1 md:grid-cols-4 gap-3">
<div className="relative">
<Search className="w-4 h-4 absolute right-3 top-3 text-gray-400" />
<input
type="text"
placeholder="جستجو بر اساس عنوان تسک، کد..."
value={searchTerm}
onChange={(e) => {
setSearchTerm(e.target.value);
setCurrentPage(1);
}}
className="w-full pr-9 pl-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-medium"
/>
</div>
<div>
<select
value={selectedDept}
onChange={(e) => {
setSelectedDept(e.target.value);
setCurrentPage(1);
}}
className="w-full px-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-bold text-gray-700"
>
<option value="ALL">همه دپارتمان‌ها</option>
<option value="DEV">مهندسی و توسعه (DEV)</option>
<option value="COMMERCE">بازرگانی و مالی (COMMERCE)</option>
<option value="PRODUCT">کاتالوگ و استوک (PRODUCT)</option>
<option value="CONTENT">محتوا و وبلاگ (CONTENT)</option>
<option value="SEO">سئو و مارکت‌پلیس (SEO)</option>
<option value="PMO">مدیریت محصول و تضمین کیفیت (PMO)</option>
</select>
</div>
<div>
<select
value={selectedStatus}
onChange={(e) => {
setSelectedStatus(e.target.value);
setCurrentPage(1);
}}
className="w-full px-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-bold text-gray-700"
>
<option value="ALL">همه وضعیت‌ها</option>
<option value="TODO">۱. صف اقدام (TODO)</option>
<option value="IN_PROGRESS">۲. در حال اجرا (IN_PROGRESS)</option>
<option value="TEST">۳. تست و QA (TEST)</option>
<option value="DONE">۴. تکمیل شده (DONE)</option>
</select>
</div>
<div>
<select
value={selectedPriority}
onChange={(e) => {
setSelectedPriority(e.target.value);
setCurrentPage(1);
}}
className="w-full px-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-bold text-gray-700"
>
<option value="ALL">همه اولویت‌ها</option>
<option value="CRITICAL">بحرانی / فوری</option>
<option value="HIGH">بالا</option>
<option value="MEDIUM">متوسط</option>
<option value="LOW">عادی</option>
</select>
</div>
</div>
</div>
{/* Task List Table */}
<div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
{loading ? (
<div className="p-12 text-center text-gray-500 font-bold text-sm">
<RefreshCw className="w-6 h-6 animate-spin mx-auto mb-2 text-purple-600" />
در حال بارگذاری لیست تسک‌ها...
</div>
) : filteredTasks.length === 0 ? (
<div className="p-12 text-center text-gray-400 font-bold text-sm">
هیچ تسکی با این مشخصات یافت نشد.
</div>
) : (
<div>
<div className="overflow-x-auto">
<table className="w-full text-right text-xs">
<thead className="bg-gray-50/75 border-b border-gray-100 text-gray-500 font-black">
<tr>
<th className="py-3 px-4">کد تسک</th>
<th className="py-3 px-4">عنوان و شرح وظیفه</th>
<th className="py-3 px-4">دپارتمان</th>
<th className="py-3 px-4">اولویت</th>
<th className="py-3 px-4">مسئول اجرا (Agent)</th>
<th className="py-3 px-4">وضعیت</th>
<th className="py-3 px-4 text-center">اقدام و تغییر استیت</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100 font-medium text-gray-700">
{paginatedTasks.map((task) => (
<tr key={task.id} className="hover:bg-purple-50/20 transition-colors">
<td className="py-3.5 px-4 whitespace-nowrap">
<span className="font-mono font-bold text-gray-500 bg-gray-100 px-2 py-1 rounded">
{task.code}
</span>
</td>
<td className="py-3.5 px-4">
<div className="font-black text-gray-900 text-xs mb-0.5">{task.title}</div>
{task.description && (
<div className="text-[11px] text-gray-500 line-clamp-1 max-w-sm">{task.description}</div>
)}
</td>
<td className="py-3.5 px-4 whitespace-nowrap">
<span className="text-[11px] font-bold text-purple-700 bg-purple-50 px-2.5 py-0.5 rounded-md border border-purple-100">
{getDeptName(task.department)}
</span>
</td>
<td className="py-3.5 px-4 whitespace-nowrap">
{getPriorityBadge(task.priority)}
</td>
<td className="py-3.5 px-4 whitespace-nowrap">
<div className="flex items-center gap-1.5 font-bold text-gray-800">
<Bot className="w-4 h-4 text-indigo-600" />
<span>{task.assignee}</span>
</div>
</td>
<td className="py-3.5 px-4 whitespace-nowrap">
{getStatusBadge(task.status)}
</td>
<td className="py-3.5 px-4 text-center whitespace-nowrap">
<button
onClick={() => setActiveTaskModal(task)}
className="inline-flex items-center gap-1 px-3 py-1.5 rounded-xl bg-purple-600 text-white font-bold text-[11px] hover:bg-purple-700 transition-colors shadow-sm cursor-pointer"
>
<span>مدیریت و استیت</span>
<ChevronDown className="w-3.5 h-3.5" />
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
{/* Pagination Controls */}
<div className="p-4 border-t border-gray-100 flex items-center justify-between text-xs">
<span className="text-gray-500 font-medium">
نمایش {(currentPage - 1) * itemsPerPage + 1} تا {Math.min(currentPage * itemsPerPage, filteredTasks.length)} از کل {filteredTasks.length} تسک
</span>
<div className="flex items-center gap-2">
<button
onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
disabled={currentPage === 1}
className="p-1.5 rounded-lg border border-gray-200 text-gray-600 hover:bg-gray-50 disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer"
>
<ChevronRight className="w-4 h-4" />
</button>
<div className="flex items-center gap-1">
{Array.from({ length: totalPages }).map((_, i) => (
<button
key={i}
onClick={() => setCurrentPage(i + 1)}
className={`w-7 h-7 rounded-lg text-xs font-bold transition-colors cursor-pointer ${
currentPage === i + 1
? 'bg-purple-600 text-white shadow-sm'
: 'text-gray-600 hover:bg-gray-100'
}`}
>
{i + 1}
</button>
))}
</div>
<button
onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
disabled={currentPage === totalPages}
className="p-1.5 rounded-lg border border-gray-200 text-gray-600 hover:bg-gray-50 disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer"
>
<ChevronLeft className="w-4 h-4" />
</button>
</div>
</div>
</div>
)}
</div>
{/* Task Modal for Status Updates */}
{activeTaskModal && (
<div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4 backdrop-blur-sm animate-in fade-in duration-150">
<div className="bg-white rounded-2xl max-w-xl w-full p-6 space-y-4 shadow-2xl border border-gray-100 max-h-[90vh] overflow-y-auto">
<div className="flex items-center justify-between border-b border-gray-100 pb-3">
<div>
<span className="text-[11px] font-mono text-purple-600 font-bold">{activeTaskModal.code}</span>
<h3 className="font-black text-sm text-gray-900">{activeTaskModal.title}</h3>
</div>
<button
onClick={() => setActiveTaskModal(null)}
className="text-gray-400 hover:text-gray-600 font-bold text-sm cursor-pointer"
>
✕
</button>
</div>
<div className="text-xs space-y-3">
<div className="p-3 bg-gray-50 rounded-xl space-y-1">
<div className="font-bold text-gray-500">شرح کامل وظیفه:</div>
<div className="text-gray-800 font-medium leading-relaxed">{activeTaskModal.description || 'توضیحی ثبت نشده است.'}</div>
</div>
{activeTaskModal.acceptanceCriteria && (
<div className="p-3 bg-indigo-50/50 rounded-xl space-y-1 border border-indigo-100">
<div className="font-bold text-indigo-900">معیارهای پذیرش (Acceptance Criteria):</div>
<div className="text-indigo-800 font-medium whitespace-pre-wrap">
{renderAcceptanceCriteria(activeTaskModal.acceptanceCriteria)}
</div>
</div>
)}
{/* Status Update Options */}
<div className="pt-2">
<label className="block text-xs font-black text-gray-700 mb-2">تغییر وضعیت تسک به:</label>
<div className="grid grid-cols-4 gap-2">
{['TODO', 'IN_PROGRESS', 'TEST', 'DONE'].map((st) => (
<button
key={st}
type="button"
onClick={() => handleStatusChange(activeTaskModal.id, st)}
disabled={updating || activeTaskModal.status === st}
className={`py-2 px-2 text-[11px] font-bold rounded-xl border text-center transition-all cursor-pointer ${
activeTaskModal.status === st
? 'bg-purple-600 text-white border-purple-600 shadow-sm'
: 'bg-white hover:bg-gray-50 text-gray-700 border-gray-200'
}`}
>
{st}
</button>
))}
</div>
</div>
<div className="pt-2">
<label className="block text-xs font-bold text-gray-700 mb-1">یادداشت برای تاریخچه لاگ (اختیاری):</label>
<input
type="text"
placeholder="مثال: تست‌ها پاس شد و کاتالوگ به‌روز گردید..."
value={logNote}
onChange={(e) => setLogNote(e.target.value)}
className="w-full px-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-medium"
/>
</div>
{/* Execution Logs */}
{activeTaskModal.executionLogs && (
<div className="pt-2 space-y-1">
<div className="font-bold text-gray-600 text-[11px]">تاریخچه اقدامات انجام‌شده روی این تسک:</div>
<div className="space-y-1 max-h-36 overflow-y-auto">
{renderExecutionLogs(activeTaskModal.executionLogs).map((lg: any, i: number) => (
<div key={i} className="text-[10px] p-2 bg-gray-50 rounded-lg flex items-center justify-between">
<span className="font-bold text-gray-800">{lg.note || JSON.stringify(lg)}</span>
<span className="text-gray-400 font-mono">
{lg.timestamp ? new Date(lg.timestamp).toLocaleTimeString('fa-IR') : '-'}
</span>
</div>
))}
</div>
</div>
)}
</div>
<div className="pt-3 border-t border-gray-100 flex justify-end">
<button
type="button"
onClick={() => setActiveTaskModal(null)}
className="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-xl text-xs font-bold transition-colors cursor-pointer"
>
انصراف
</button>
</div>
</div>
</div>
)}
</div>
);
}
+43 -4
View File
@@ -4,6 +4,46 @@ import { MemoryRouter } from 'react-router-dom';
import { beforeEach,describe,expect,it,vi } from 'vitest'; import { beforeEach,describe,expect,it,vi } from 'vitest';
import api from '../services/api'; import api from '../services/api';
import Users from './Users'; import Users from './Users';
import { useAdminAuthStore } from '../store/adminAuthStore';
vi.mock('../store/adminAuthStore', () => ({ useAdminAuthStore: vi.fn() }));
describe('Users superadmin editor', () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(useAdminAuthStore).mockReturnValue('SUPER_ADMIN');
vi.mocked(api.get).mockResolvedValue({ data: { data: [{ id: 'owner-fixture', firstName: 'Owner', role: 'SUPER_ADMIN' }], meta: { total: 1 } } });
vi.mocked(api.put).mockResolvedValue({ data: { success: true } });
});
it.each(['SUPER_ADMIN', 'ADMIN', 'Admin', 'User_Vet'])('preserves exact %s role on password-only save', async (role) => {
vi.mocked(api.get).mockResolvedValue({ data: { data: [{ id: 'owner-fixture', firstName: 'Owner', role }], meta: { total: 1 } } });
render(<MemoryRouter><Users /></MemoryRouter>);
fireEvent.click((await screen.findAllByTitle('ویرایش مشخصات'))[0]);
const select = screen.getAllByRole('combobox')[1];
expect(select).toHaveValue(role);
expect(screen.getAllByRole('option', { name: /مدیر ارشد/ }).length).toBeGreaterThan(0);
fireEvent.change(document.querySelector('input[type="password"]')!, { target: { value: 'Fixture-only-123' } });
fireEvent.click(screen.getByRole('button', { name: 'ذخیره تغییرات' }));
await waitFor(() => expect(api.put).toHaveBeenCalled());
const payload = vi.mocked(api.put).mock.calls[0][1] as Record<string, unknown>;
expect(payload).not.toHaveProperty('role');
});
it('submits explicit superadmin promotion for authorized actor', async () => {
vi.mocked(api.get).mockResolvedValue({ data: { data: [{ id: 'ordinary-fixture', role: 'Admin' }], meta: { total: 1 } } });
render(<MemoryRouter><Users /></MemoryRouter>);
fireEvent.click((await screen.findAllByTitle('ویرایش مشخصات'))[0]);
fireEvent.change(screen.getAllByRole('combobox')[1], { target: { value: 'SUPER_ADMIN' } });
fireEvent.click(screen.getByRole('button', { name: 'ذخیره تغییرات' }));
await waitFor(() => expect(api.put).toHaveBeenCalledWith('/admin/users/ordinary-fixture', expect.objectContaining({ role: 'SUPER_ADMIN' })));
});
it('does not offer superadmin promotion to ordinary admin', async () => {
vi.mocked(useAdminAuthStore).mockReturnValue('Admin');
render(<MemoryRouter><Users /></MemoryRouter>);
fireEvent.click(screen.getByRole('button', { name: 'افزودن کاربر جدید' }));
const select = screen.getAllByRole('combobox')[1];
expect(select.querySelector('option[value="SUPER_ADMIN"]')).toBeNull();
});
});
vi.mock('../services/api', () => ({ vi.mock('../services/api', () => ({
default: { default: {
@@ -57,9 +97,9 @@ describe('Users Page', () => {
vi.clearAllMocks(); vi.clearAllMocks();
vi.mocked(api.get).mockResolvedValue({ vi.mocked(api.get).mockResolvedValue({
data: { data: {
success: true, // Actual GET /admin/users contract: no success envelope.
data: mockUsers, data: mockUsers,
meta: { lastPage: 2, total: 2 }, meta: { lastPage: 2, total: 2, page: 1, limit: 10 },
}, },
}); });
}); });
@@ -260,9 +300,8 @@ describe('Users Page', () => {
it('renders empty table state when no users are returned', async () => { it('renders empty table state when no users are returned', async () => {
vi.mocked(api.get).mockResolvedValueOnce({ vi.mocked(api.get).mockResolvedValueOnce({
data: { data: {
success: true,
data: [], data: [],
meta: { lastPage: 1, total: 0 }, meta: { lastPage: 1, total: 0, page: 1, limit: 10 },
}, },
}); });
Loaded 100 of 320 files, more files were not shown because too many files have changed in this diff. Show more