Compare commits
15 Commits
c9a525bead
...
6e98b8779d
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6e98b8779d | ||
|
|
5ace474d71 | ||
|
|
8de1351349 | ||
|
|
d8c6aa8d8e | ||
|
|
6a476fab1a | ||
|
|
0934b4f3af | ||
|
|
09fd339e89 | ||
|
|
8992060cb7 | ||
|
|
03900e726a | ||
|
|
4304562d55 | ||
|
|
b7e17aca1d | ||
|
|
0831791513 | ||
|
|
873376be26 | ||
|
|
33f15f7b5b | ||
|
|
e85931508a |
14
.agents/rules/graphify.md
Normal file
14
.agents/rules/graphify.md
Normal file
@ -0,0 +1,14 @@
|
||||
---
|
||||
trigger: always_on
|
||||
description: Consult the graphify knowledge graph at graphify-out/ for codebase and architecture questions.
|
||||
---
|
||||
|
||||
## graphify
|
||||
|
||||
This project has a graphify knowledge graph at graphify-out/.
|
||||
|
||||
Rules:
|
||||
- For codebase or architecture questions, when `graphify-out/graph.json` exists, first run `graphify query "<question>"` (CLI) or `query_graph` (MCP). Use `graphify path "<A>" "<B>"` / `shortest_path` for relationships and `graphify explain "<concept>"` / `get_node` for focused concepts. These return a scoped subgraph, usually much smaller than `GRAPH_REPORT.md` or raw grep output.
|
||||
- If graphify-out/wiki/index.md exists, navigate it instead of reading raw files
|
||||
- Read graphify-out/GRAPH_REPORT.md only for broad architecture review or when query/path/explain do not surface enough context
|
||||
- After modifying code files in this session, run `graphify update .` to keep the graph current (AST-only, no API cost)
|
||||
10
.agents/workflows/graphify.md
Normal file
10
.agents/workflows/graphify.md
Normal file
@ -0,0 +1,10 @@
|
||||
---
|
||||
name: graphify
|
||||
description: Turn any folder of files into a navigable knowledge graph
|
||||
---
|
||||
|
||||
# Workflow: graphify
|
||||
|
||||
Follow the graphify skill to run the full pipeline.
|
||||
|
||||
If no path argument is given, use `.` (current directory).
|
||||
3
.antigravity/instructions.md
Normal file
3
.antigravity/instructions.md
Normal file
@ -0,0 +1,3 @@
|
||||
# graphify
|
||||
- **graphify** (`.claude/skills/graphify/SKILL.md`) - any input to knowledge graph. Trigger: `/graphify`
|
||||
When the user types `/graphify`, use the installed graphify skill or instructions before doing anything else.
|
||||
750
.antigravity/workflows/graphify.md
Normal file
750
.antigravity/workflows/graphify.md
Normal file
@ -0,0 +1,750 @@
|
||||
---
|
||||
name: graphify
|
||||
description: "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
|
||||
---
|
||||
|
||||
# /graphify
|
||||
|
||||
Turn any folder of files into a navigable knowledge graph with community detection, an honest audit trail, and three outputs: interactive HTML, GraphRAG-ready JSON, and a plain-language GRAPH_REPORT.md.
|
||||
|
||||
## Usage
|
||||
|
||||
```
|
||||
/graphify # full pipeline on current directory (HTML viz; add --obsidian for a vault)
|
||||
/graphify <path> # full pipeline on specific path
|
||||
/graphify https://github.com/<owner>/<repo> # clone repo then run full pipeline on it
|
||||
/graphify https://github.com/<owner>/<repo> --branch <branch> # clone a specific branch
|
||||
/graphify <url1> <url2> ... # clone multiple repos, build each, merge into one cross-repo graph
|
||||
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
|
||||
/graphify <path> --update # incremental - re-extract only new/changed files
|
||||
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
|
||||
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
|
||||
/graphify <path> --cluster-only # rerun clustering on existing graph
|
||||
/graphify <path> --no-viz # skip visualization, just report + JSON
|
||||
/graphify <path> --html # (HTML is generated by default - this flag is a no-op)
|
||||
/graphify <path> --svg # also export graph.svg (embeds in Notion, GitHub)
|
||||
/graphify <path> --graphml # export graph.graphml (Gephi, yEd)
|
||||
/graphify <path> --neo4j # generate graphify-out/cypher.txt for Neo4j
|
||||
/graphify <path> --neo4j-push bolt://localhost:7687 # push directly to Neo4j
|
||||
/graphify <path> --falkordb # generate graphify-out/cypher.txt for FalkorDB
|
||||
/graphify <path> --falkordb-push falkordb://localhost:6379 # push directly to FalkorDB
|
||||
/graphify <path> --mcp # start MCP stdio server for agent access
|
||||
/graphify <path> --watch # watch folder, auto-rebuild on code changes (no LLM needed)
|
||||
/graphify <path> --wiki # build agent-crawlable wiki (index.md + one article per community)
|
||||
/graphify <path> --obsidian --obsidian-dir ~/vaults/my-project # write vault to custom path (e.g. existing vault)
|
||||
/graphify add <url> # fetch URL, save to ./raw, update graph
|
||||
/graphify add <url> --author "Name" # tag who wrote it
|
||||
/graphify add <url> --contributor "Name" # tag who added it to the corpus
|
||||
/graphify query "<question>" # BFS traversal - broad context
|
||||
/graphify query "<question>" --dfs # DFS - trace a specific path
|
||||
/graphify query "<question>" --budget 1500 # cap answer at N tokens
|
||||
/graphify path "AuthModule" "Database" # shortest path between two concepts
|
||||
/graphify explain "SwinTransformer" # plain-language explanation of a node
|
||||
```
|
||||
|
||||
## What graphify is for
|
||||
|
||||
Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about.
|
||||
|
||||
## What You Must Do When Invoked
|
||||
|
||||
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
|
||||
|
||||
**Fast path — existing graph:** Before doing anything else, check whether `graphify-out/graph.json` exists. The expected location is `graphify-out/graph.json` relative to the **current working directory** (i.e. the project root where you are running commands). If it exists AND the user's request is a natural-language question about the codebase (e.g. "How does X work?", "What calls Y?", "Trace the data flow through Z") and NOT an explicit rebuild command (`--update`, `--cluster-only`, or a bare path/URL that implies fresh extraction): **skip Steps 1–5 entirely and jump straight to `## For /graphify query`.** Run `graphify query "<question>"` immediately. Do not run detect. Do not check corpus size. Do not ask the user to narrow. The graph is already built — use it.
|
||||
|
||||
If no path was given, use `.` (current directory). Do not ask the user for a path.
|
||||
|
||||
If the path argument starts with `https://github.com/` or `http://github.com/`, treat it as a GitHub URL - run Step 0 before anything else, then continue with the resolved local path.
|
||||
|
||||
Follow these steps in order. Do not skip steps.
|
||||
|
||||
### Step 0 - GitHub repos and multi-path merge (only if a URL or several paths)
|
||||
|
||||
Only when the path is one or more `https://github.com/...` URLs, or several local subfolders to merge. See `references/github-and-merge.md` for the clone, cross-repo merge, and monorepo flow, then continue with the resolved local path. A plain local path skips this step.
|
||||
|
||||
### Step 1 - Ensure graphify is installed
|
||||
|
||||
```powershell
|
||||
# Detect Python with graphify — uv/pipx-aware (fixes #831)
|
||||
New-Item -ItemType Directory -Force -Path graphify-out | Out-Null
|
||||
$GRAPHIFY_PYTHON = $null
|
||||
|
||||
function Find-GraphifyPython {
|
||||
# 1. uv tool install — 'uv tool dir' is authoritative, respects UV_TOOL_DIR automatically
|
||||
if (Get-Command uv -ErrorAction SilentlyContinue) {
|
||||
$uvDir = (uv tool dir 2>$null).Trim()
|
||||
if ($uvDir) {
|
||||
$py = Join-Path $uvDir "graphifyy\Scripts\python.exe"
|
||||
if (Test-Path $py) {
|
||||
& $py -c "import graphify" 2>$null
|
||||
if ($LASTEXITCODE -eq 0) { return $py }
|
||||
}
|
||||
}
|
||||
}
|
||||
# 2. pipx install — 'pipx environment' respects PIPX_HOME automatically
|
||||
if (Get-Command pipx -ErrorAction SilentlyContinue) {
|
||||
$venvs = (pipx environment --value PIPX_LOCAL_VENVS 2>$null).Trim()
|
||||
if ($venvs) {
|
||||
$py = Join-Path $venvs "graphifyy\Scripts\python.exe"
|
||||
if (Test-Path $py) {
|
||||
& $py -c "import graphify" 2>$null
|
||||
if ($LASTEXITCODE -eq 0) { return $py }
|
||||
}
|
||||
}
|
||||
}
|
||||
# 3. Active venv / conda / pip-into-current-env
|
||||
$pyCmd = Get-Command python -ErrorAction SilentlyContinue
|
||||
if ($pyCmd) {
|
||||
& $pyCmd.Source -c "import graphify" 2>$null
|
||||
if ($LASTEXITCODE -eq 0) {
|
||||
return (& $pyCmd.Source -c "import sys; print(sys.executable)").Trim()
|
||||
}
|
||||
}
|
||||
return $null
|
||||
}
|
||||
|
||||
# Try to find the right Python (uv → pipx → active env)
|
||||
$GRAPHIFY_PYTHON = Find-GraphifyPython
|
||||
|
||||
# Not found — install then re-detect
|
||||
if (-not $GRAPHIFY_PYTHON) {
|
||||
if (Get-Command uv -ErrorAction SilentlyContinue) {
|
||||
uv tool install --upgrade graphifyy -q 2>&1 | Select-Object -Last 3
|
||||
} else {
|
||||
pip install graphifyy -q 2>&1 | Select-Object -Last 3
|
||||
}
|
||||
$GRAPHIFY_PYTHON = Find-GraphifyPython
|
||||
}
|
||||
|
||||
# Save interpreter path — all subsequent steps read this
|
||||
$GRAPHIFY_PYTHON | Out-File -FilePath graphify-out\.graphify_python -Encoding utf8 -NoNewline
|
||||
# Save scan root so `graphify update` (no args) knows where to look next time
|
||||
(Resolve-Path INPUT_PATH).Path | Out-File -FilePath graphify-out\.graphify_root -Encoding utf8 -NoNewline
|
||||
```
|
||||
|
||||
If the import succeeds, print nothing and move straight to Step 2.
|
||||
|
||||
**In every subsequent block, run Python through the saved interpreter — `& (Get-Content graphify-out\.graphify_python)` in place of a bare `python3` — so every step uses the interpreter that actually has graphify.**
|
||||
|
||||
### Step 2 - Detect files
|
||||
|
||||
```powershell
|
||||
@'
|
||||
import json
|
||||
from graphify.detect import detect
|
||||
from pathlib import Path
|
||||
result = detect(Path('INPUT_PATH'))
|
||||
# Write the sidecar from Python, not a shell redirect, so the same block renders
|
||||
# on PowerShell hosts without console-encoding drift (#2528).
|
||||
Path('graphify-out/.graphify_detect.json').write_text(json.dumps(result, ensure_ascii=False), encoding="utf-8")
|
||||
print(f'Detected {result["total_files"]} files')
|
||||
'@ | & (Get-Content graphify-out\.graphify_python) -
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
|
||||
```
|
||||
Corpus: X files · ~Y words
|
||||
code: N files (.py .ts .go ...)
|
||||
docs: N files (.md .txt ...)
|
||||
papers: N files (.pdf ...)
|
||||
images: N files
|
||||
video: N files (.mp4 .mp3 ...)
|
||||
```
|
||||
|
||||
Omit any category with 0 files from the summary.
|
||||
|
||||
Then act on it:
|
||||
- If `total_files` is 0: stop with "No supported files found in [path]."
|
||||
- If `skipped_sensitive` is non-empty: report the count and list the skipped file names, so a wrongly-flagged source or doc is visible and can be renamed or moved (#2106).
|
||||
- If `total_words` > 2,000,000 OR `total_files` > 500: show the warning. Then compute the top 5 first-level subdirectories by file count:
|
||||
- Read `scan_root` from the detect JSON (always an absolute path to the resolved INPUT_PATH).
|
||||
- Concatenate all file lists across all types (`code`, `document`, `paper`, `image`, `video`).
|
||||
- Filter out any path that starts with `scan_root + "/graphify-out/"` to exclude converted sidecars.
|
||||
- For each file, strip the `scan_root` prefix and take the first path component. Files directly in `scan_root` with no subdirectory count as `(root)`.
|
||||
- If all files are in `(root)` with no subdirectories, do not ask to narrow — no subfolders exist. Instead suggest `--no-cluster` to skip the expensive clustering step and proceed.
|
||||
- Otherwise rank by count, show the top 5 with file counts, then ask which subfolder to run on. Wait for the user's answer before proceeding.
|
||||
- Otherwise: proceed directly to Step 2.5 if video files were detected, or Step 3 if not.
|
||||
|
||||
### Step 2.5 - Video and audio (only if video files detected)
|
||||
|
||||
Skip this step entirely if `detect` returned zero `video` files. When the corpus has video or audio, see `references/transcribe.md` to transcribe them to text first, then treat the transcripts as doc files in Step 3.
|
||||
|
||||
### Step 3 - Extract entities and relationships
|
||||
|
||||
**Before starting:** note whether `--mode deep` was given. You must pass `DEEP_MODE=true` to every subagent in Step B2 if it was. Track this from the original invocation - do not lose it.
|
||||
|
||||
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (LLM, costs tokens).
|
||||
|
||||
> **graphify needs no API key. Never ask the user for one, and never block on one.** Code is extracted structurally (AST) with no LLM and no key at all — a code-only corpus (the common `/graphify .` on a repo) skips semantic extraction entirely, so it needs nothing here: go straight to Part A and skip Part B. Semantic extraction (only for docs, papers, and images) uses Gemini **only if** `GEMINI_API_KEY`/`GOOGLE_API_KEY` is already set; otherwise the host agent itself is the LLM. graphify does **not** read `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, or any other provider key. If you catch yourself about to prompt for, wait on, or stop because of a missing API key, that is a misread of this skill — proceed without one.
|
||||
|
||||
**Before semantic extraction:** check whether `GEMINI_API_KEY` or `GOOGLE_API_KEY` is set. If neither is set, print this one-liner to the user:
|
||||
> Tip: set `GEMINI_API_KEY` or `GOOGLE_API_KEY` to use Gemini for semantic extraction (`pip install 'graphifyy[gemini]'`).
|
||||
|
||||
Print it once, then continue — do not wait for the user to supply a key. If `GEMINI_API_KEY` or `GOOGLE_API_KEY` IS set, use `graphify.llm.extract_corpus_parallel(files, backend="gemini")` for semantic extraction instead of dispatching subagents. The default Gemini model is `gemini-3-flash-preview`; set `GRAPHIFY_GEMINI_MODEL` or pass `--model` in headless CLI flows to override it.
|
||||
|
||||
> **No other API keys are read.** When `GEMINI_API_KEY`/`GOOGLE_API_KEY` are unset, semantic extraction falls to the host agent itself — the running session is the LLM. On a host that dispatches subagents (e.g. Claude Code), dispatch them as written in Part B. On a host that runs the CLI directly in a terminal and cannot dispatch subagents, do not stall: a code-only corpus has no semantic work, so write the empty semantic file (Part B "Fast path") and continue to Part C; for a corpus with docs/papers/images, either set a Gemini key or extract those inline yourself, but in no case prompt for `ANTHROPIC_API_KEY` — that prompt is a misread of this skill.
|
||||
|
||||
**Run Part A (AST) and Part B (semantic) in parallel. Dispatch all semantic subagents AND start AST extraction in the same message. Both can run simultaneously since they operate on different file types. Merge results in Part C as before.**
|
||||
|
||||
Note: Parallelizing AST + semantic saves 5-15s on large corpora. AST is deterministic and fast; start it while subagents are processing docs/papers.
|
||||
|
||||
#### Part A - Structural extraction for code files
|
||||
|
||||
For any code files detected, run AST extraction in parallel with Part B subagents:
|
||||
|
||||
```powershell
|
||||
@'
|
||||
import sys, json
|
||||
from graphify.extract import collect_files, extract
|
||||
from pathlib import Path
|
||||
import json
|
||||
|
||||
code_files = []
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
|
||||
for f in detect.get('files', {}).get('code', []):
|
||||
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
|
||||
|
||||
if code_files:
|
||||
result = extract(code_files, cache_root=Path('INPUT_PATH'))
|
||||
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
print(f'AST: {len(result["nodes"])} nodes, {len(result["edges"])} edges')
|
||||
else:
|
||||
Path('graphify-out/.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0}, ensure_ascii=False), encoding="utf-8")
|
||||
print('No code files - skipping AST extraction')
|
||||
'@ | & (Get-Content graphify-out\.graphify_python) -
|
||||
```
|
||||
|
||||
#### Part B - Semantic extraction (parallel subagents)
|
||||
|
||||
**Fast path:** If detection found zero docs, papers, and images (code-only corpus), skip Part B entirely and go straight to Part C. AST handles code - there is nothing for semantic subagents to do. **First write an empty semantic file** so Part C's merge has its input (it reads `.graphify_semantic.json` unconditionally; without this a code-only run hits `FileNotFoundError`):
|
||||
|
||||
```powershell
|
||||
@'
|
||||
import json
|
||||
from pathlib import Path
|
||||
Path('graphify-out/.graphify_semantic.json').write_text(json.dumps({'nodes':[],'edges':[],'hyperedges':[],'input_tokens':0,'output_tokens':0}), encoding='utf-8')
|
||||
'@ | & (Get-Content graphify-out\.graphify_python) -
|
||||
```
|
||||
|
||||
**MANDATORY: You MUST use the Agent tool here. Reading files yourself one-by-one is forbidden - it is 5-10x slower. If you do not use the Agent tool you are doing this wrong.**
|
||||
|
||||
Before dispatching subagents, print a timing estimate:
|
||||
- Load `total_words` and file counts from `graphify-out/.graphify_detect.json`
|
||||
- Estimate agents needed: `ceil(uncached_non_code_files / 22)` (chunk size is 20-25)
|
||||
- Estimate time: ~45s per agent batch (they run in parallel, so total ≈ 45s × ceil(agents/parallel_limit))
|
||||
- Print: "Semantic extraction: ~N files → X agents, estimated ~Ys"
|
||||
|
||||
**Step B0 - Check extraction cache first**
|
||||
|
||||
Before dispatching any subagents, check which files already have cached extraction results:
|
||||
|
||||
SPEC_PATH below is the **absolute** path of the `references/extraction-spec.md` that ships beside this SKILL.md — the same file Step B2 loads and hands to every subagent. It is the extraction prompt, so cache entries are attributed to it: when a graphify upgrade changes the prompt, entries produced by the old one are re-extracted instead of replayed, and unchanged prompts keep their entries (#1939). Substitute the real path in both Step B0 and Step B3 — pass the same one to each, and do not drop the argument.
|
||||
|
||||
```powershell
|
||||
@'
|
||||
import json
|
||||
from graphify.cache import check_semantic_cache
|
||||
from pathlib import Path
|
||||
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
|
||||
# Only content files go to semantic extraction. Code is already covered structurally
|
||||
# by the AST pass (Part A); flattening every category here makes subagents re-read
|
||||
# every source file (#1392). Video is transcribed to a document in Step 2.5 first.
|
||||
all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])]
|
||||
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root='INPUT_PATH', prompt_file='SPEC_PATH')
|
||||
|
||||
# Always (re)write the cache file: write hits, else DELETE any leftover from a prior
|
||||
# run so Part C never merges a stale .graphify_cached.json (#1392).
|
||||
if cached_nodes or cached_edges or cached_hyperedges:
|
||||
Path('graphify-out/.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges, 'hyperedges': cached_hyperedges}, ensure_ascii=False), encoding="utf-8")
|
||||
else:
|
||||
Path('graphify-out/.graphify_cached.json').unlink(missing_ok=True)
|
||||
Path('graphify-out/.graphify_uncached.txt').write_text('\n'.join(uncached), encoding="utf-8")
|
||||
print(f'Cache: {len(all_files)-len(uncached)} files hit, {len(uncached)} files need extraction')
|
||||
'@ | & (Get-Content graphify-out\.graphify_python) -
|
||||
```
|
||||
|
||||
Only dispatch subagents for files listed in `graphify-out/.graphify_uncached.txt`. If all files are cached, skip to Part C directly.
|
||||
|
||||
**Step B1 - Split into chunks**
|
||||
|
||||
Load files from `graphify-out/.graphify_uncached.txt`. Split into chunks of 20-25 files each. Each image gets its own chunk (vision needs separate context). When splitting, group files from the same directory together so related artifacts land in the same chunk and cross-file relationships are more likely to be extracted.
|
||||
|
||||
**Step B2 - Dispatch ALL subagents in a single message**
|
||||
|
||||
Call the Agent tool multiple times IN THE SAME RESPONSE - one call per chunk. This is the only way they run in parallel. If you make one Agent call, wait, then make another, you are doing it sequentially and defeating the purpose.
|
||||
|
||||
**IMPORTANT - subagent type:** Always use `subagent_type="general-purpose"`. Do NOT use `Explore` - it is read-only and cannot write chunk files to disk, which silently drops extraction results. General-purpose has Write and Bash access which the subagent needs.
|
||||
|
||||
Concrete example for 3 chunks:
|
||||
```
|
||||
[Agent tool call 1: files 1-15, subagent_type="general-purpose"]
|
||||
[Agent tool call 2: files 16-30, subagent_type="general-purpose"]
|
||||
[Agent tool call 3: files 31-45, subagent_type="general-purpose"]
|
||||
```
|
||||
All three in one message. Not three separate messages.
|
||||
|
||||
Each subagent receives this exact prompt (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH).
|
||||
|
||||
CHUNK_PATH must be an **absolute** path — derive it before dispatching:
|
||||
```powershell
|
||||
$PROJECT_ROOT = (Get-Location).Path # cwd — where Part C globs graphify-out\ (NOT .graphify_root/scan dir, #1392)
|
||||
# Then for chunk N: $CHUNK_PATH = Join-Path $PROJECT_ROOT "graphify-out\.graphify_chunk_0N.json"
|
||||
```
|
||||
|
||||
Subagent prompt template:
|
||||
|
||||
See `references/extraction-spec.md` for the exact subagent prompt (JSON schema, node-ID rules, confidence rubric, frontmatter, hyperedge, and vision rules). Load it only here, only when at least one chunk holds a doc, paper, or image; a pure-code corpus has skipped Part B and never reads it. Pass each subagent that prompt verbatim with FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH substituted, and have it write the result to CHUNK_PATH.
|
||||
|
||||
**Step B3 - Collect, cache, and merge**
|
||||
|
||||
Wait for all subagents. For each result:
|
||||
- Check that `graphify-out/.graphify_chunk_NN.json` exists on disk — this is the success signal
|
||||
- If the file exists and contains valid JSON with `nodes` and `edges`, include it and save to cache
|
||||
- If the file is missing, the subagent was likely dispatched as read-only (Explore type) — print a warning: "chunk N missing from disk — subagent may have been read-only. Re-run with general-purpose agent." Do not silently skip.
|
||||
- If a subagent failed or returned invalid JSON, print a warning and skip that chunk - do not abort
|
||||
|
||||
If more than half the chunks failed or are missing, stop and tell the user to re-run and ensure `subagent_type="general-purpose"` is used.
|
||||
|
||||
Merge all chunk files into `.graphify_semantic_new.json`. **After each Agent call completes, read the real token counts from the Agent tool result's `usage` field and write them back into the chunk JSON before merging** — the chunk JSON itself always has placeholder zeros. Then run:
|
||||
```powershell
|
||||
@'
|
||||
import json, glob
|
||||
from pathlib import Path
|
||||
|
||||
chunks = sorted(glob.glob('graphify-out/.graphify_chunk_*.json'))
|
||||
all_nodes, all_edges, all_hyperedges = [], [], []
|
||||
total_in, total_out = 0, 0
|
||||
for c in chunks:
|
||||
d = json.loads(Path(c).read_text(encoding="utf-8"))
|
||||
all_nodes += d.get('nodes', [])
|
||||
all_edges += d.get('edges', [])
|
||||
all_hyperedges += d.get('hyperedges', [])
|
||||
total_in += d.get('input_tokens', 0)
|
||||
total_out += d.get('output_tokens', 0)
|
||||
Path('graphify-out/.graphify_semantic_new.json').write_text(json.dumps({
|
||||
'nodes': all_nodes, 'edges': all_edges, 'hyperedges': all_hyperedges,
|
||||
'input_tokens': total_in, 'output_tokens': total_out,
|
||||
}, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
print(f'Merged {len(chunks)} chunks: {total_in:,} in / {total_out:,} out tokens')
|
||||
'@ | & (Get-Content graphify-out\.graphify_python) -
|
||||
```
|
||||
|
||||
Save new results to cache. Pass the same SPEC_PATH as Step B0 — it stamps each entry with the prompt that produced it, and a write under a different prompt than the read lands where the next run won't look (#1939):
|
||||
```powershell
|
||||
@'
|
||||
import json
|
||||
from graphify.cache import save_semantic_cache
|
||||
from pathlib import Path
|
||||
|
||||
new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text(encoding="utf-8")) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
|
||||
uncached = [line for line in Path('graphify-out/.graphify_uncached.txt').read_text(encoding="utf-8").splitlines() if line]
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root='INPUT_PATH', allowed_source_files=uncached, prompt_file='SPEC_PATH')
|
||||
print(f'Cached {saved} files')
|
||||
'@ | & (Get-Content graphify-out\.graphify_python) -
|
||||
```
|
||||
|
||||
Merge cached + new results into `graphify-out/.graphify_semantic.json`:
|
||||
```powershell
|
||||
@'
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
cached = json.loads(Path('graphify-out/.graphify_cached.json').read_text(encoding="utf-8")) if Path('graphify-out/.graphify_cached.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
|
||||
new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text(encoding="utf-8")) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
|
||||
|
||||
all_nodes = cached['nodes'] + new.get('nodes', [])
|
||||
all_edges = cached['edges'] + new.get('edges', [])
|
||||
all_hyperedges = cached.get('hyperedges', []) + new.get('hyperedges', [])
|
||||
seen = set()
|
||||
deduped = []
|
||||
for n in all_nodes:
|
||||
if n['id'] not in seen:
|
||||
seen.add(n['id'])
|
||||
deduped.append(n)
|
||||
|
||||
merged = {
|
||||
'nodes': deduped,
|
||||
'edges': all_edges,
|
||||
'hyperedges': all_hyperedges,
|
||||
'input_tokens': new.get('input_tokens', 0),
|
||||
'output_tokens': new.get('output_tokens', 0),
|
||||
}
|
||||
Path('graphify-out/.graphify_semantic.json').write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
print(f'Extraction complete - {len(deduped)} nodes, {len(all_edges)} edges ({len(cached["nodes"])} from cache, {len(new.get("nodes",[]))} new)')
|
||||
'@ | & (Get-Content graphify-out\.graphify_python) -
|
||||
```
|
||||
Clean up temp files: `Remove-Item -Force -ErrorAction SilentlyContinue graphify-out\.graphify_cached.json, graphify-out\.graphify_uncached.txt, graphify-out\.graphify_semantic_new.json`
|
||||
|
||||
#### Part C - Merge AST + semantic into final extraction
|
||||
|
||||
```powershell
|
||||
@'
|
||||
import sys, json
|
||||
from pathlib import Path
|
||||
|
||||
ast = json.loads(Path('graphify-out/.graphify_ast.json').read_text(encoding="utf-8"))
|
||||
sem = json.loads(Path('graphify-out/.graphify_semantic.json').read_text(encoding="utf-8"))
|
||||
|
||||
# Merge: AST nodes first, semantic nodes deduplicated by id
|
||||
seen = {n['id'] for n in ast['nodes']}
|
||||
merged_nodes = list(ast['nodes'])
|
||||
for n in sem['nodes']:
|
||||
if n['id'] not in seen:
|
||||
merged_nodes.append(n)
|
||||
seen.add(n['id'])
|
||||
|
||||
merged_edges = ast['edges'] + sem['edges']
|
||||
merged_hyperedges = sem.get('hyperedges', [])
|
||||
merged = {
|
||||
'nodes': merged_nodes,
|
||||
'edges': merged_edges,
|
||||
'hyperedges': merged_hyperedges,
|
||||
'input_tokens': sem.get('input_tokens', 0),
|
||||
'output_tokens': sem.get('output_tokens', 0),
|
||||
}
|
||||
Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
total = len(merged_nodes)
|
||||
edges = len(merged_edges)
|
||||
print(f'Merged: {total} nodes, {edges} edges ({len(ast["nodes"])} AST + {len(sem["nodes"])} semantic)')
|
||||
'@ | & (Get-Content graphify-out\.graphify_python) -
|
||||
```
|
||||
|
||||
### Step 4 - Build graph, cluster, analyze, generate outputs
|
||||
|
||||
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Substitute it the same way you substitute `INPUT_PATH` — do not leave the literal `IS_DIRECTED` in the code.
|
||||
|
||||
```powershell
|
||||
New-Item -ItemType Directory -Force -Path graphify-out | Out-Null
|
||||
@'
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.cluster import cluster, score_all
|
||||
from graphify.analyze import god_nodes, surprising_connections, suggest_questions
|
||||
from graphify.report import generate
|
||||
from graphify.export import to_json
|
||||
from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8"))
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
|
||||
|
||||
# root= mirrors the --update runbook (#1361): relativize source_file to the same
|
||||
# base so the full build and incremental --update never drift apart on re-extract.
|
||||
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
|
||||
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
|
||||
# GRAPH_REPORT.md / analysis sidecar. Check immediately after build (#1392).
|
||||
if G.number_of_nodes() == 0:
|
||||
print('ERROR: Graph is empty - extraction produced no nodes.')
|
||||
print('Possible causes: all files were skipped, binary-only corpus, or extraction failed.')
|
||||
raise SystemExit(1)
|
||||
communities = cluster(G)
|
||||
cohesion = score_all(G, communities)
|
||||
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
|
||||
gods = god_nodes(G)
|
||||
surprises = surprising_connections(G, communities)
|
||||
labels = {cid: 'Community ' + str(cid) for cid in communities}
|
||||
# Placeholder questions - regenerated with real labels in Step 5
|
||||
questions = suggest_questions(G, communities, labels)
|
||||
|
||||
# Export FIRST and honor the #479 shrink-guard: to_json returns False (writing
|
||||
# nothing) when the new graph is smaller than the existing graph.json. Only write
|
||||
# GRAPH_REPORT.md + the analysis sidecar when the graph was actually written, so
|
||||
# they never describe a graph that graph.json doesn't contain (#1392).
|
||||
wrote = to_json(G, communities, 'graphify-out/graph.json')
|
||||
if not wrote:
|
||||
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
|
||||
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
|
||||
raise SystemExit(1)
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding="utf-8")
|
||||
analysis = {
|
||||
'communities': {str(k): v for k, v in communities.items()},
|
||||
'cohesion': {str(k): v for k, v in cohesion.items()},
|
||||
'gods': gods,
|
||||
'surprises': surprises,
|
||||
'questions': questions,
|
||||
}
|
||||
Path('graphify-out/.graphify_analysis.json').write_text(json.dumps(analysis, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(communities)} communities')
|
||||
'@ | & (Get-Content graphify-out\.graphify_python) -
|
||||
```
|
||||
|
||||
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
|
||||
|
||||
Replace INPUT_PATH with the actual path.
|
||||
|
||||
### Step 4.5 - Graph health check (read-only integrity gate)
|
||||
|
||||
A non-destructive diagnostic on the extraction, before labeling. It surfaces edge collapse, dangling/missing endpoints, and self-loops — the silent-corruption modes of incremental updates and AST/LLM id mismatches. Read-only; never aborts.
|
||||
|
||||
```powershell
|
||||
@'
|
||||
import json
|
||||
from pathlib import Path
|
||||
from graphify.diagnostics import diagnose_extraction, format_diagnostic_report
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8"))
|
||||
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root='INPUT_PATH')
|
||||
print(format_diagnostic_report(summary))
|
||||
flags = [f'{summary[k]} {label}' for k, label in (
|
||||
('dangling_endpoint_edges', 'dangling-endpoint edges'),
|
||||
('missing_endpoint_edges', 'missing-endpoint edges'),
|
||||
('self_loop_edges', 'self-loop edges'),
|
||||
('directed_same_endpoint_collapsed_edges', 'collapsed (directed) edges'),
|
||||
('undirected_same_endpoint_collapsed_edges', 'collapsed (undirected) edges'),
|
||||
) if summary.get(k, 0)]
|
||||
print('GRAPH HEALTH WARNING: ' + '; '.join(flags) + ' - graph may be incomplete/corrupt.' if flags else 'Graph health: OK (no dangling/missing/collapsed edges).')
|
||||
'@ | & (Get-Content graphify-out\.graphify_python) -
|
||||
```
|
||||
|
||||
Substitute `IS_DIRECTED` and `INPUT_PATH` as in Step 4. If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
|
||||
|
||||
### Step 5 - Label communities
|
||||
|
||||
Read `graphify-out/.graphify_analysis.json`. For each community key, look at its node labels and write a 2-5 word plain-language name (e.g. "Attention Mechanism", "Training Pipeline", "Data Loading").
|
||||
|
||||
Then regenerate the report and save the labels for the visualizer:
|
||||
|
||||
```powershell
|
||||
@'
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.cluster import score_all
|
||||
from graphify.analyze import god_nodes, surprising_connections, suggest_questions
|
||||
from graphify.report import generate
|
||||
from graphify.export import to_json
|
||||
from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8"))
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
|
||||
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding="utf-8"))
|
||||
|
||||
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
|
||||
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
|
||||
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
|
||||
|
||||
# LABELS - replace these with the names you chose above
|
||||
labels = LABELS_DICT
|
||||
|
||||
# Regenerate questions with real community labels (labels affect question phrasing)
|
||||
questions = suggest_questions(G, communities, labels)
|
||||
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding="utf-8")
|
||||
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding="utf-8")
|
||||
# Re-export so graph.json nodes carry the curated community_name (#2490).
|
||||
# Same extraction as Step 4, so the #479 shrink-guard passes on node count;
|
||||
# if it still refuses, surface the guard message - do not force past it.
|
||||
wrote = to_json(G, communities, 'graphify-out/graph.json', community_labels=labels)
|
||||
if not wrote:
|
||||
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
|
||||
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
|
||||
print('Report updated with community labels')
|
||||
'@ | & (Get-Content graphify-out\.graphify_python) -
|
||||
```
|
||||
|
||||
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
|
||||
Replace INPUT_PATH with the actual path.
|
||||
|
||||
### Step 6 - Generate Obsidian vault (opt-in) + HTML
|
||||
|
||||
**Generate HTML always** (unless `--no-viz`). **Obsidian vault only if `--obsidian` was explicitly given** — skip it otherwise, it generates one file per node.
|
||||
|
||||
If `--obsidian` was given:
|
||||
|
||||
- If `--obsidian-dir <path>` was also given, pass it via `--dir`. Otherwise defaults to `graphify-out/obsidian`.
|
||||
|
||||
```powershell
|
||||
graphify export obsidian
|
||||
# or with custom dir: graphify export obsidian --dir ~/vaults/my-project
|
||||
```
|
||||
|
||||
Generate the HTML graph (always, unless `--no-viz`):
|
||||
|
||||
```powershell
|
||||
graphify export html # auto-aggregates to community view if graph > 5000 nodes
|
||||
# or: graphify export html --no-viz
|
||||
```
|
||||
|
||||
### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags)
|
||||
|
||||
These run only when their flag is present (`--wiki`, `--neo4j`/`--neo4j-push`, `--falkordb`/`--falkordb-push`, `--svg`, `--graphml`, `--mcp`) or, for the token-reduction benchmark, when `total_words` exceeds 5,000. A default run with no export flags skips all of them. See `references/exports.md` for each one. Run any `--wiki` export before Step 9 cleanup so `.graphify_labels.json` is still available.
|
||||
|
||||
---
|
||||
|
||||
### Step 9 - Save manifest, update cost tracker, clean up, and report
|
||||
|
||||
```powershell
|
||||
@'
|
||||
import json
|
||||
from pathlib import Path
|
||||
from datetime import datetime, timezone
|
||||
from graphify.detect import save_manifest
|
||||
|
||||
# Save manifest for --update
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
|
||||
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8"))
|
||||
# In --update mode, 'all_files' carries the full corpus; 'files' is the changed
|
||||
# subset. Full-rebuild mode populates only 'files', so the fallback handles that.
|
||||
# root= relativizes the manifest keys to the scan root (same base as the build),
|
||||
# so the on-disk manifest is portable across clones/machines and a later --update
|
||||
# matches cached files instead of missing every one (#1417).
|
||||
#
|
||||
# Only stamp semantic files (docs/papers/images) that ACTUALLY produced output:
|
||||
# a detected file whose chunk failed or was omitted must stay unstamped so the
|
||||
# next --update re-queues it, otherwise it is marked done and its content is lost
|
||||
# forever (#2015). This mirrors the library extract path exactly
|
||||
# (cli._stamped_manifest_files + clear_semantic + scan_corpus); do not stamp the
|
||||
# raw corpus. Code files are always stamped (AST is deterministic); only semantic
|
||||
# types are gated on output.
|
||||
from graphify.cli import _stamped_manifest_files
|
||||
_corpus = detect.get('all_files') or detect['files']
|
||||
_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'))
|
||||
# Files dispatched this run (the changed subset) but NOT stamped above still carry
|
||||
# a stale semantic_hash from a prior run; clear it so detect_incremental re-queues
|
||||
# them instead of reading them as unchanged (#1948).
|
||||
_sem_types = ('document', 'paper', 'image')
|
||||
_dispatched = {f for t, fl in detect['files'].items() if t in _sem_types for f in fl}
|
||||
_stamped = {f for fl in _manifest_files.values() for f in fl}
|
||||
_cleared = _dispatched - _stamped
|
||||
# scan_corpus = the RAW full corpus (not the stamp-filtered subset) so in-root
|
||||
# files newly excluded since last run are dropped rather than masquerading as
|
||||
# deletions; untouched files' prior rows are still preserved (#1908).
|
||||
_scan = {f for fl in _corpus.values() for f in fl}
|
||||
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
|
||||
# Update cumulative cost tracker
|
||||
input_tok = extract.get('input_tokens', 0)
|
||||
output_tok = extract.get('output_tokens', 0)
|
||||
|
||||
cost_path = Path('graphify-out/cost.json')
|
||||
if cost_path.exists():
|
||||
cost = json.loads(cost_path.read_text(encoding="utf-8"))
|
||||
else:
|
||||
cost = {'runs': [], 'total_input_tokens': 0, 'total_output_tokens': 0}
|
||||
|
||||
cost['runs'].append({
|
||||
'date': datetime.now(timezone.utc).isoformat(),
|
||||
'input_tokens': input_tok,
|
||||
'output_tokens': output_tok,
|
||||
'files': detect.get('total_files', 0),
|
||||
})
|
||||
cost['total_input_tokens'] += input_tok
|
||||
cost['total_output_tokens'] += output_tok
|
||||
cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
|
||||
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
|
||||
print(f'All time: {cost["total_input_tokens"]:,} input, {cost["total_output_tokens"]:,} output ({len(cost["runs"])} runs)')
|
||||
'@ | & (Get-Content graphify-out\.graphify_python) -
|
||||
Remove-Item -Force -ErrorAction SilentlyContinue graphify-out\.graphify_detect.json, graphify-out\.graphify_extract.json, graphify-out\.graphify_ast.json, graphify-out\.graphify_semantic.json, graphify-out\.graphify_analysis.json
|
||||
Get-ChildItem graphify-out -Filter '.graphify_chunk_*.json' -File -ErrorAction SilentlyContinue | Remove-Item -Force
|
||||
Remove-Item -Force -ErrorAction SilentlyContinue graphify-out\.needs_update
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path (same value used in Steps 4-5) so the manifest is relativized to the scan root.
|
||||
|
||||
Tell the user (omit the obsidian line unless --obsidian was given):
|
||||
```
|
||||
Graph complete. Outputs in PATH_TO_DIR/graphify-out/
|
||||
|
||||
graph.html - interactive graph, open in browser
|
||||
GRAPH_REPORT.md - audit report
|
||||
graph.json - raw graph data
|
||||
obsidian/ - Obsidian vault (only if --obsidian was given)
|
||||
```
|
||||
|
||||
If graphify saved you time, consider supporting it: https://github.com/sponsors/safishamsi
|
||||
|
||||
Replace PATH_TO_DIR with the actual absolute path of the directory that was processed.
|
||||
|
||||
Then paste these sections from GRAPH_REPORT.md directly into the chat:
|
||||
- God Nodes
|
||||
- Surprising Connections
|
||||
- Suggested Questions
|
||||
|
||||
Do NOT paste the full report - just those three sections. Keep it concise.
|
||||
|
||||
Then immediately offer to explore. Pick the single most interesting suggested question from the report - the one that crosses the most community boundaries or has the most surprising bridge node - and ask:
|
||||
|
||||
> "The most interesting question this graph can answer: **[question]**. Want me to trace it?"
|
||||
|
||||
If the user says yes, run `/graphify query "[question]"` on the graph and walk them through the answer using the graph structure - which nodes connect, which community boundaries get crossed, what the path reveals. Keep going as long as they want to explore. Each answer should end with a natural follow-up ("this connects to X - want to go deeper?") so the session feels like navigation, not a one-shot report.
|
||||
|
||||
The graph is the map. Your job after the pipeline is to be the guide.
|
||||
|
||||
---
|
||||
|
||||
## Interpreter guard for subcommands
|
||||
|
||||
Before running any subcommand below (`--update`, `--cluster-only`, `query`, `path`, `explain`, `add`), check that `.graphify_python` exists. If it's missing (e.g. user deleted `graphify-out/`), re-resolve the interpreter first:
|
||||
|
||||
```powershell
|
||||
if (-not (Test-Path graphify-out\.graphify_python)) {
|
||||
$GRAPHIFY_PYTHON = $null
|
||||
$graphifyCmd = Get-Command graphify -ErrorAction SilentlyContinue
|
||||
if ($graphifyCmd) {
|
||||
# The interpreter that owns the graphify entry point sits next to it
|
||||
# (<env>\Scripts\python.exe for uv tool, pipx, and venv installs).
|
||||
$py = Join-Path (Split-Path $graphifyCmd.Source) "python.exe"
|
||||
if (Test-Path $py) { $GRAPHIFY_PYTHON = $py }
|
||||
}
|
||||
if (-not $GRAPHIFY_PYTHON) { $GRAPHIFY_PYTHON = "python" }
|
||||
New-Item -ItemType Directory -Force -Path graphify-out | Out-Null
|
||||
& $GRAPHIFY_PYTHON -c "import sys; open('graphify-out/.graphify_python', 'w', encoding='utf-8').write(sys.executable)"
|
||||
}
|
||||
```
|
||||
|
||||
## For --update and --cluster-only
|
||||
|
||||
Both are non-default subcommands. `--update` re-extracts only new or changed files; `--cluster-only` reruns clustering on the existing graph. See `references/update.md` for both flows.
|
||||
|
||||
---
|
||||
|
||||
## For /graphify query
|
||||
|
||||
When `graphify-out/graph.json` already exists and the user asks a question about the corpus, answer from the graph rather than rebuilding it:
|
||||
|
||||
```powershell
|
||||
graphify query "<question>"
|
||||
```
|
||||
|
||||
Before traversal, expand the question against the graph's own vocabulary so a wording mismatch does not collapse the answer to noise. If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For that vocab-expansion step, the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
|
||||
|
||||
---
|
||||
|
||||
## For /graphify add and --watch
|
||||
|
||||
Neither is part of the default build. When the user runs `/graphify add <url>` to fetch a URL into the corpus, or passes `--watch` to auto-rebuild on file changes, see `references/add-watch.md`.
|
||||
|
||||
---
|
||||
|
||||
## For the commit hook and native CLAUDE.md integration
|
||||
|
||||
When the user asks to install the post-commit auto-rebuild hook or wire graphify into a project's CLAUDE.md, see `references/hooks.md`.
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### PowerShell 5.1: Vertical scrolling stops working
|
||||
|
||||
If vertical scrolling breaks in PowerShell after running graphify, this is caused by ANSI escape sequences from the `graspologic` library. Graphify v0.3.10+ suppresses this output, but if you still see the issue:
|
||||
|
||||
1. **Upgrade graphify**: `pip install --upgrade graphifyy`
|
||||
2. **Use Windows Terminal** instead of the legacy PowerShell console — Windows Terminal handles ANSI codes correctly
|
||||
3. **Reset your terminal**: close and reopen PowerShell
|
||||
4. **Skip graspologic**: uninstall it (`pip uninstall graspologic`) and graphify will fall back to NetworkX's built-in Louvain algorithm, which produces no ANSI output
|
||||
|
||||
---
|
||||
|
||||
## Honesty Rules
|
||||
|
||||
- Never invent an edge. If unsure, use AMBIGUOUS.
|
||||
- Never skip the corpus check warning.
|
||||
- Always show token cost in the report.
|
||||
- Never hide cohesion scores behind symbols - show the raw number.
|
||||
- Never run HTML viz on a graph with more than 5,000 nodes without warning the user.
|
||||
3
.claude/CLAUDE.md
Normal file
3
.claude/CLAUDE.md
Normal file
@ -0,0 +1,3 @@
|
||||
# graphify
|
||||
- **graphify** (`.claude/skills/graphify/SKILL.md`) - any input to knowledge graph. Trigger: `/graphify`
|
||||
When the user types `/graphify`, use the installed graphify skill or instructions before doing anything else.
|
||||
24
.claude/settings.json
Normal file
24
.claude/settings.json
Normal file
@ -0,0 +1,24 @@
|
||||
{
|
||||
"hooks": {
|
||||
"PreToolUse": [
|
||||
{
|
||||
"matcher": "Bash|Grep",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "C:/Users/p.aghaei/.local/bin/graphify.EXE hook-guard search"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"matcher": "Read|Glob",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "C:/Users/p.aghaei/.local/bin/graphify.EXE hook-guard read"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
1
.claude/skills/graphify/.graphify_version
Normal file
1
.claude/skills/graphify/.graphify_version
Normal file
@ -0,0 +1 @@
|
||||
0.9.44
|
||||
750
.claude/skills/graphify/SKILL.md
Normal file
750
.claude/skills/graphify/SKILL.md
Normal file
@ -0,0 +1,750 @@
|
||||
---
|
||||
name: graphify
|
||||
description: "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
|
||||
---
|
||||
|
||||
# /graphify
|
||||
|
||||
Turn any folder of files into a navigable knowledge graph with community detection, an honest audit trail, and three outputs: interactive HTML, GraphRAG-ready JSON, and a plain-language GRAPH_REPORT.md.
|
||||
|
||||
## Usage
|
||||
|
||||
```
|
||||
/graphify # full pipeline on current directory (HTML viz; add --obsidian for a vault)
|
||||
/graphify <path> # full pipeline on specific path
|
||||
/graphify https://github.com/<owner>/<repo> # clone repo then run full pipeline on it
|
||||
/graphify https://github.com/<owner>/<repo> --branch <branch> # clone a specific branch
|
||||
/graphify <url1> <url2> ... # clone multiple repos, build each, merge into one cross-repo graph
|
||||
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
|
||||
/graphify <path> --update # incremental - re-extract only new/changed files
|
||||
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
|
||||
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
|
||||
/graphify <path> --cluster-only # rerun clustering on existing graph
|
||||
/graphify <path> --no-viz # skip visualization, just report + JSON
|
||||
/graphify <path> --html # (HTML is generated by default - this flag is a no-op)
|
||||
/graphify <path> --svg # also export graph.svg (embeds in Notion, GitHub)
|
||||
/graphify <path> --graphml # export graph.graphml (Gephi, yEd)
|
||||
/graphify <path> --neo4j # generate graphify-out/cypher.txt for Neo4j
|
||||
/graphify <path> --neo4j-push bolt://localhost:7687 # push directly to Neo4j
|
||||
/graphify <path> --falkordb # generate graphify-out/cypher.txt for FalkorDB
|
||||
/graphify <path> --falkordb-push falkordb://localhost:6379 # push directly to FalkorDB
|
||||
/graphify <path> --mcp # start MCP stdio server for agent access
|
||||
/graphify <path> --watch # watch folder, auto-rebuild on code changes (no LLM needed)
|
||||
/graphify <path> --wiki # build agent-crawlable wiki (index.md + one article per community)
|
||||
/graphify <path> --obsidian --obsidian-dir ~/vaults/my-project # write vault to custom path (e.g. existing vault)
|
||||
/graphify add <url> # fetch URL, save to ./raw, update graph
|
||||
/graphify add <url> --author "Name" # tag who wrote it
|
||||
/graphify add <url> --contributor "Name" # tag who added it to the corpus
|
||||
/graphify query "<question>" # BFS traversal - broad context
|
||||
/graphify query "<question>" --dfs # DFS - trace a specific path
|
||||
/graphify query "<question>" --budget 1500 # cap answer at N tokens
|
||||
/graphify path "AuthModule" "Database" # shortest path between two concepts
|
||||
/graphify explain "SwinTransformer" # plain-language explanation of a node
|
||||
```
|
||||
|
||||
## What graphify is for
|
||||
|
||||
Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about.
|
||||
|
||||
## What You Must Do When Invoked
|
||||
|
||||
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
|
||||
|
||||
**Fast path — existing graph:** Before doing anything else, check whether `graphify-out/graph.json` exists. The expected location is `graphify-out/graph.json` relative to the **current working directory** (i.e. the project root where you are running commands). If it exists AND the user's request is a natural-language question about the codebase (e.g. "How does X work?", "What calls Y?", "Trace the data flow through Z") and NOT an explicit rebuild command (`--update`, `--cluster-only`, or a bare path/URL that implies fresh extraction): **skip Steps 1–5 entirely and jump straight to `## For /graphify query`.** Run `graphify query "<question>"` immediately. Do not run detect. Do not check corpus size. Do not ask the user to narrow. The graph is already built — use it.
|
||||
|
||||
If no path was given, use `.` (current directory). Do not ask the user for a path.
|
||||
|
||||
If the path argument starts with `https://github.com/` or `http://github.com/`, treat it as a GitHub URL - run Step 0 before anything else, then continue with the resolved local path.
|
||||
|
||||
Follow these steps in order. Do not skip steps.
|
||||
|
||||
### Step 0 - GitHub repos and multi-path merge (only if a URL or several paths)
|
||||
|
||||
Only when the path is one or more `https://github.com/...` URLs, or several local subfolders to merge. See `references/github-and-merge.md` for the clone, cross-repo merge, and monorepo flow, then continue with the resolved local path. A plain local path skips this step.
|
||||
|
||||
### Step 1 - Ensure graphify is installed
|
||||
|
||||
```powershell
|
||||
# Detect Python with graphify — uv/pipx-aware (fixes #831)
|
||||
New-Item -ItemType Directory -Force -Path graphify-out | Out-Null
|
||||
$GRAPHIFY_PYTHON = $null
|
||||
|
||||
function Find-GraphifyPython {
|
||||
# 1. uv tool install — 'uv tool dir' is authoritative, respects UV_TOOL_DIR automatically
|
||||
if (Get-Command uv -ErrorAction SilentlyContinue) {
|
||||
$uvDir = (uv tool dir 2>$null).Trim()
|
||||
if ($uvDir) {
|
||||
$py = Join-Path $uvDir "graphifyy\Scripts\python.exe"
|
||||
if (Test-Path $py) {
|
||||
& $py -c "import graphify" 2>$null
|
||||
if ($LASTEXITCODE -eq 0) { return $py }
|
||||
}
|
||||
}
|
||||
}
|
||||
# 2. pipx install — 'pipx environment' respects PIPX_HOME automatically
|
||||
if (Get-Command pipx -ErrorAction SilentlyContinue) {
|
||||
$venvs = (pipx environment --value PIPX_LOCAL_VENVS 2>$null).Trim()
|
||||
if ($venvs) {
|
||||
$py = Join-Path $venvs "graphifyy\Scripts\python.exe"
|
||||
if (Test-Path $py) {
|
||||
& $py -c "import graphify" 2>$null
|
||||
if ($LASTEXITCODE -eq 0) { return $py }
|
||||
}
|
||||
}
|
||||
}
|
||||
# 3. Active venv / conda / pip-into-current-env
|
||||
$pyCmd = Get-Command python -ErrorAction SilentlyContinue
|
||||
if ($pyCmd) {
|
||||
& $pyCmd.Source -c "import graphify" 2>$null
|
||||
if ($LASTEXITCODE -eq 0) {
|
||||
return (& $pyCmd.Source -c "import sys; print(sys.executable)").Trim()
|
||||
}
|
||||
}
|
||||
return $null
|
||||
}
|
||||
|
||||
# Try to find the right Python (uv → pipx → active env)
|
||||
$GRAPHIFY_PYTHON = Find-GraphifyPython
|
||||
|
||||
# Not found — install then re-detect
|
||||
if (-not $GRAPHIFY_PYTHON) {
|
||||
if (Get-Command uv -ErrorAction SilentlyContinue) {
|
||||
uv tool install --upgrade graphifyy -q 2>&1 | Select-Object -Last 3
|
||||
} else {
|
||||
pip install graphifyy -q 2>&1 | Select-Object -Last 3
|
||||
}
|
||||
$GRAPHIFY_PYTHON = Find-GraphifyPython
|
||||
}
|
||||
|
||||
# Save interpreter path — all subsequent steps read this
|
||||
$GRAPHIFY_PYTHON | Out-File -FilePath graphify-out\.graphify_python -Encoding utf8 -NoNewline
|
||||
# Save scan root so `graphify update` (no args) knows where to look next time
|
||||
(Resolve-Path INPUT_PATH).Path | Out-File -FilePath graphify-out\.graphify_root -Encoding utf8 -NoNewline
|
||||
```
|
||||
|
||||
If the import succeeds, print nothing and move straight to Step 2.
|
||||
|
||||
**In every subsequent block, run Python through the saved interpreter — `& (Get-Content graphify-out\.graphify_python)` in place of a bare `python3` — so every step uses the interpreter that actually has graphify.**
|
||||
|
||||
### Step 2 - Detect files
|
||||
|
||||
```powershell
|
||||
@'
|
||||
import json
|
||||
from graphify.detect import detect
|
||||
from pathlib import Path
|
||||
result = detect(Path('INPUT_PATH'))
|
||||
# Write the sidecar from Python, not a shell redirect, so the same block renders
|
||||
# on PowerShell hosts without console-encoding drift (#2528).
|
||||
Path('graphify-out/.graphify_detect.json').write_text(json.dumps(result, ensure_ascii=False), encoding="utf-8")
|
||||
print(f'Detected {result["total_files"]} files')
|
||||
'@ | & (Get-Content graphify-out\.graphify_python) -
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
|
||||
```
|
||||
Corpus: X files · ~Y words
|
||||
code: N files (.py .ts .go ...)
|
||||
docs: N files (.md .txt ...)
|
||||
papers: N files (.pdf ...)
|
||||
images: N files
|
||||
video: N files (.mp4 .mp3 ...)
|
||||
```
|
||||
|
||||
Omit any category with 0 files from the summary.
|
||||
|
||||
Then act on it:
|
||||
- If `total_files` is 0: stop with "No supported files found in [path]."
|
||||
- If `skipped_sensitive` is non-empty: report the count and list the skipped file names, so a wrongly-flagged source or doc is visible and can be renamed or moved (#2106).
|
||||
- If `total_words` > 2,000,000 OR `total_files` > 500: show the warning. Then compute the top 5 first-level subdirectories by file count:
|
||||
- Read `scan_root` from the detect JSON (always an absolute path to the resolved INPUT_PATH).
|
||||
- Concatenate all file lists across all types (`code`, `document`, `paper`, `image`, `video`).
|
||||
- Filter out any path that starts with `scan_root + "/graphify-out/"` to exclude converted sidecars.
|
||||
- For each file, strip the `scan_root` prefix and take the first path component. Files directly in `scan_root` with no subdirectory count as `(root)`.
|
||||
- If all files are in `(root)` with no subdirectories, do not ask to narrow — no subfolders exist. Instead suggest `--no-cluster` to skip the expensive clustering step and proceed.
|
||||
- Otherwise rank by count, show the top 5 with file counts, then ask which subfolder to run on. Wait for the user's answer before proceeding.
|
||||
- Otherwise: proceed directly to Step 2.5 if video files were detected, or Step 3 if not.
|
||||
|
||||
### Step 2.5 - Video and audio (only if video files detected)
|
||||
|
||||
Skip this step entirely if `detect` returned zero `video` files. When the corpus has video or audio, see `references/transcribe.md` to transcribe them to text first, then treat the transcripts as doc files in Step 3.
|
||||
|
||||
### Step 3 - Extract entities and relationships
|
||||
|
||||
**Before starting:** note whether `--mode deep` was given. You must pass `DEEP_MODE=true` to every subagent in Step B2 if it was. Track this from the original invocation - do not lose it.
|
||||
|
||||
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (LLM, costs tokens).
|
||||
|
||||
> **graphify needs no API key. Never ask the user for one, and never block on one.** Code is extracted structurally (AST) with no LLM and no key at all — a code-only corpus (the common `/graphify .` on a repo) skips semantic extraction entirely, so it needs nothing here: go straight to Part A and skip Part B. Semantic extraction (only for docs, papers, and images) uses Gemini **only if** `GEMINI_API_KEY`/`GOOGLE_API_KEY` is already set; otherwise the host agent itself is the LLM. graphify does **not** read `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, or any other provider key. If you catch yourself about to prompt for, wait on, or stop because of a missing API key, that is a misread of this skill — proceed without one.
|
||||
|
||||
**Before semantic extraction:** check whether `GEMINI_API_KEY` or `GOOGLE_API_KEY` is set. If neither is set, print this one-liner to the user:
|
||||
> Tip: set `GEMINI_API_KEY` or `GOOGLE_API_KEY` to use Gemini for semantic extraction (`pip install 'graphifyy[gemini]'`).
|
||||
|
||||
Print it once, then continue — do not wait for the user to supply a key. If `GEMINI_API_KEY` or `GOOGLE_API_KEY` IS set, use `graphify.llm.extract_corpus_parallel(files, backend="gemini")` for semantic extraction instead of dispatching subagents. The default Gemini model is `gemini-3-flash-preview`; set `GRAPHIFY_GEMINI_MODEL` or pass `--model` in headless CLI flows to override it.
|
||||
|
||||
> **No other API keys are read.** When `GEMINI_API_KEY`/`GOOGLE_API_KEY` are unset, semantic extraction falls to the host agent itself — the running session is the LLM. On a host that dispatches subagents (e.g. Claude Code), dispatch them as written in Part B. On a host that runs the CLI directly in a terminal and cannot dispatch subagents, do not stall: a code-only corpus has no semantic work, so write the empty semantic file (Part B "Fast path") and continue to Part C; for a corpus with docs/papers/images, either set a Gemini key or extract those inline yourself, but in no case prompt for `ANTHROPIC_API_KEY` — that prompt is a misread of this skill.
|
||||
|
||||
**Run Part A (AST) and Part B (semantic) in parallel. Dispatch all semantic subagents AND start AST extraction in the same message. Both can run simultaneously since they operate on different file types. Merge results in Part C as before.**
|
||||
|
||||
Note: Parallelizing AST + semantic saves 5-15s on large corpora. AST is deterministic and fast; start it while subagents are processing docs/papers.
|
||||
|
||||
#### Part A - Structural extraction for code files
|
||||
|
||||
For any code files detected, run AST extraction in parallel with Part B subagents:
|
||||
|
||||
```powershell
|
||||
@'
|
||||
import sys, json
|
||||
from graphify.extract import collect_files, extract
|
||||
from pathlib import Path
|
||||
import json
|
||||
|
||||
code_files = []
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
|
||||
for f in detect.get('files', {}).get('code', []):
|
||||
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
|
||||
|
||||
if code_files:
|
||||
result = extract(code_files, cache_root=Path('INPUT_PATH'))
|
||||
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
print(f'AST: {len(result["nodes"])} nodes, {len(result["edges"])} edges')
|
||||
else:
|
||||
Path('graphify-out/.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0}, ensure_ascii=False), encoding="utf-8")
|
||||
print('No code files - skipping AST extraction')
|
||||
'@ | & (Get-Content graphify-out\.graphify_python) -
|
||||
```
|
||||
|
||||
#### Part B - Semantic extraction (parallel subagents)
|
||||
|
||||
**Fast path:** If detection found zero docs, papers, and images (code-only corpus), skip Part B entirely and go straight to Part C. AST handles code - there is nothing for semantic subagents to do. **First write an empty semantic file** so Part C's merge has its input (it reads `.graphify_semantic.json` unconditionally; without this a code-only run hits `FileNotFoundError`):
|
||||
|
||||
```powershell
|
||||
@'
|
||||
import json
|
||||
from pathlib import Path
|
||||
Path('graphify-out/.graphify_semantic.json').write_text(json.dumps({'nodes':[],'edges':[],'hyperedges':[],'input_tokens':0,'output_tokens':0}), encoding='utf-8')
|
||||
'@ | & (Get-Content graphify-out\.graphify_python) -
|
||||
```
|
||||
|
||||
**MANDATORY: You MUST use the Agent tool here. Reading files yourself one-by-one is forbidden - it is 5-10x slower. If you do not use the Agent tool you are doing this wrong.**
|
||||
|
||||
Before dispatching subagents, print a timing estimate:
|
||||
- Load `total_words` and file counts from `graphify-out/.graphify_detect.json`
|
||||
- Estimate agents needed: `ceil(uncached_non_code_files / 22)` (chunk size is 20-25)
|
||||
- Estimate time: ~45s per agent batch (they run in parallel, so total ≈ 45s × ceil(agents/parallel_limit))
|
||||
- Print: "Semantic extraction: ~N files → X agents, estimated ~Ys"
|
||||
|
||||
**Step B0 - Check extraction cache first**
|
||||
|
||||
Before dispatching any subagents, check which files already have cached extraction results:
|
||||
|
||||
SPEC_PATH below is the **absolute** path of the `references/extraction-spec.md` that ships beside this SKILL.md — the same file Step B2 loads and hands to every subagent. It is the extraction prompt, so cache entries are attributed to it: when a graphify upgrade changes the prompt, entries produced by the old one are re-extracted instead of replayed, and unchanged prompts keep their entries (#1939). Substitute the real path in both Step B0 and Step B3 — pass the same one to each, and do not drop the argument.
|
||||
|
||||
```powershell
|
||||
@'
|
||||
import json
|
||||
from graphify.cache import check_semantic_cache
|
||||
from pathlib import Path
|
||||
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
|
||||
# Only content files go to semantic extraction. Code is already covered structurally
|
||||
# by the AST pass (Part A); flattening every category here makes subagents re-read
|
||||
# every source file (#1392). Video is transcribed to a document in Step 2.5 first.
|
||||
all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])]
|
||||
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root='INPUT_PATH', prompt_file='SPEC_PATH')
|
||||
|
||||
# Always (re)write the cache file: write hits, else DELETE any leftover from a prior
|
||||
# run so Part C never merges a stale .graphify_cached.json (#1392).
|
||||
if cached_nodes or cached_edges or cached_hyperedges:
|
||||
Path('graphify-out/.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges, 'hyperedges': cached_hyperedges}, ensure_ascii=False), encoding="utf-8")
|
||||
else:
|
||||
Path('graphify-out/.graphify_cached.json').unlink(missing_ok=True)
|
||||
Path('graphify-out/.graphify_uncached.txt').write_text('\n'.join(uncached), encoding="utf-8")
|
||||
print(f'Cache: {len(all_files)-len(uncached)} files hit, {len(uncached)} files need extraction')
|
||||
'@ | & (Get-Content graphify-out\.graphify_python) -
|
||||
```
|
||||
|
||||
Only dispatch subagents for files listed in `graphify-out/.graphify_uncached.txt`. If all files are cached, skip to Part C directly.
|
||||
|
||||
**Step B1 - Split into chunks**
|
||||
|
||||
Load files from `graphify-out/.graphify_uncached.txt`. Split into chunks of 20-25 files each. Each image gets its own chunk (vision needs separate context). When splitting, group files from the same directory together so related artifacts land in the same chunk and cross-file relationships are more likely to be extracted.
|
||||
|
||||
**Step B2 - Dispatch ALL subagents in a single message**
|
||||
|
||||
Call the Agent tool multiple times IN THE SAME RESPONSE - one call per chunk. This is the only way they run in parallel. If you make one Agent call, wait, then make another, you are doing it sequentially and defeating the purpose.
|
||||
|
||||
**IMPORTANT - subagent type:** Always use `subagent_type="general-purpose"`. Do NOT use `Explore` - it is read-only and cannot write chunk files to disk, which silently drops extraction results. General-purpose has Write and Bash access which the subagent needs.
|
||||
|
||||
Concrete example for 3 chunks:
|
||||
```
|
||||
[Agent tool call 1: files 1-15, subagent_type="general-purpose"]
|
||||
[Agent tool call 2: files 16-30, subagent_type="general-purpose"]
|
||||
[Agent tool call 3: files 31-45, subagent_type="general-purpose"]
|
||||
```
|
||||
All three in one message. Not three separate messages.
|
||||
|
||||
Each subagent receives this exact prompt (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH).
|
||||
|
||||
CHUNK_PATH must be an **absolute** path — derive it before dispatching:
|
||||
```powershell
|
||||
$PROJECT_ROOT = (Get-Location).Path # cwd — where Part C globs graphify-out\ (NOT .graphify_root/scan dir, #1392)
|
||||
# Then for chunk N: $CHUNK_PATH = Join-Path $PROJECT_ROOT "graphify-out\.graphify_chunk_0N.json"
|
||||
```
|
||||
|
||||
Subagent prompt template:
|
||||
|
||||
See `references/extraction-spec.md` for the exact subagent prompt (JSON schema, node-ID rules, confidence rubric, frontmatter, hyperedge, and vision rules). Load it only here, only when at least one chunk holds a doc, paper, or image; a pure-code corpus has skipped Part B and never reads it. Pass each subagent that prompt verbatim with FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH substituted, and have it write the result to CHUNK_PATH.
|
||||
|
||||
**Step B3 - Collect, cache, and merge**
|
||||
|
||||
Wait for all subagents. For each result:
|
||||
- Check that `graphify-out/.graphify_chunk_NN.json` exists on disk — this is the success signal
|
||||
- If the file exists and contains valid JSON with `nodes` and `edges`, include it and save to cache
|
||||
- If the file is missing, the subagent was likely dispatched as read-only (Explore type) — print a warning: "chunk N missing from disk — subagent may have been read-only. Re-run with general-purpose agent." Do not silently skip.
|
||||
- If a subagent failed or returned invalid JSON, print a warning and skip that chunk - do not abort
|
||||
|
||||
If more than half the chunks failed or are missing, stop and tell the user to re-run and ensure `subagent_type="general-purpose"` is used.
|
||||
|
||||
Merge all chunk files into `.graphify_semantic_new.json`. **After each Agent call completes, read the real token counts from the Agent tool result's `usage` field and write them back into the chunk JSON before merging** — the chunk JSON itself always has placeholder zeros. Then run:
|
||||
```powershell
|
||||
@'
|
||||
import json, glob
|
||||
from pathlib import Path
|
||||
|
||||
chunks = sorted(glob.glob('graphify-out/.graphify_chunk_*.json'))
|
||||
all_nodes, all_edges, all_hyperedges = [], [], []
|
||||
total_in, total_out = 0, 0
|
||||
for c in chunks:
|
||||
d = json.loads(Path(c).read_text(encoding="utf-8"))
|
||||
all_nodes += d.get('nodes', [])
|
||||
all_edges += d.get('edges', [])
|
||||
all_hyperedges += d.get('hyperedges', [])
|
||||
total_in += d.get('input_tokens', 0)
|
||||
total_out += d.get('output_tokens', 0)
|
||||
Path('graphify-out/.graphify_semantic_new.json').write_text(json.dumps({
|
||||
'nodes': all_nodes, 'edges': all_edges, 'hyperedges': all_hyperedges,
|
||||
'input_tokens': total_in, 'output_tokens': total_out,
|
||||
}, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
print(f'Merged {len(chunks)} chunks: {total_in:,} in / {total_out:,} out tokens')
|
||||
'@ | & (Get-Content graphify-out\.graphify_python) -
|
||||
```
|
||||
|
||||
Save new results to cache. Pass the same SPEC_PATH as Step B0 — it stamps each entry with the prompt that produced it, and a write under a different prompt than the read lands where the next run won't look (#1939):
|
||||
```powershell
|
||||
@'
|
||||
import json
|
||||
from graphify.cache import save_semantic_cache
|
||||
from pathlib import Path
|
||||
|
||||
new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text(encoding="utf-8")) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
|
||||
uncached = [line for line in Path('graphify-out/.graphify_uncached.txt').read_text(encoding="utf-8").splitlines() if line]
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root='INPUT_PATH', allowed_source_files=uncached, prompt_file='SPEC_PATH')
|
||||
print(f'Cached {saved} files')
|
||||
'@ | & (Get-Content graphify-out\.graphify_python) -
|
||||
```
|
||||
|
||||
Merge cached + new results into `graphify-out/.graphify_semantic.json`:
|
||||
```powershell
|
||||
@'
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
cached = json.loads(Path('graphify-out/.graphify_cached.json').read_text(encoding="utf-8")) if Path('graphify-out/.graphify_cached.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
|
||||
new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text(encoding="utf-8")) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
|
||||
|
||||
all_nodes = cached['nodes'] + new.get('nodes', [])
|
||||
all_edges = cached['edges'] + new.get('edges', [])
|
||||
all_hyperedges = cached.get('hyperedges', []) + new.get('hyperedges', [])
|
||||
seen = set()
|
||||
deduped = []
|
||||
for n in all_nodes:
|
||||
if n['id'] not in seen:
|
||||
seen.add(n['id'])
|
||||
deduped.append(n)
|
||||
|
||||
merged = {
|
||||
'nodes': deduped,
|
||||
'edges': all_edges,
|
||||
'hyperedges': all_hyperedges,
|
||||
'input_tokens': new.get('input_tokens', 0),
|
||||
'output_tokens': new.get('output_tokens', 0),
|
||||
}
|
||||
Path('graphify-out/.graphify_semantic.json').write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
print(f'Extraction complete - {len(deduped)} nodes, {len(all_edges)} edges ({len(cached["nodes"])} from cache, {len(new.get("nodes",[]))} new)')
|
||||
'@ | & (Get-Content graphify-out\.graphify_python) -
|
||||
```
|
||||
Clean up temp files: `Remove-Item -Force -ErrorAction SilentlyContinue graphify-out\.graphify_cached.json, graphify-out\.graphify_uncached.txt, graphify-out\.graphify_semantic_new.json`
|
||||
|
||||
#### Part C - Merge AST + semantic into final extraction
|
||||
|
||||
```powershell
|
||||
@'
|
||||
import sys, json
|
||||
from pathlib import Path
|
||||
|
||||
ast = json.loads(Path('graphify-out/.graphify_ast.json').read_text(encoding="utf-8"))
|
||||
sem = json.loads(Path('graphify-out/.graphify_semantic.json').read_text(encoding="utf-8"))
|
||||
|
||||
# Merge: AST nodes first, semantic nodes deduplicated by id
|
||||
seen = {n['id'] for n in ast['nodes']}
|
||||
merged_nodes = list(ast['nodes'])
|
||||
for n in sem['nodes']:
|
||||
if n['id'] not in seen:
|
||||
merged_nodes.append(n)
|
||||
seen.add(n['id'])
|
||||
|
||||
merged_edges = ast['edges'] + sem['edges']
|
||||
merged_hyperedges = sem.get('hyperedges', [])
|
||||
merged = {
|
||||
'nodes': merged_nodes,
|
||||
'edges': merged_edges,
|
||||
'hyperedges': merged_hyperedges,
|
||||
'input_tokens': sem.get('input_tokens', 0),
|
||||
'output_tokens': sem.get('output_tokens', 0),
|
||||
}
|
||||
Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
total = len(merged_nodes)
|
||||
edges = len(merged_edges)
|
||||
print(f'Merged: {total} nodes, {edges} edges ({len(ast["nodes"])} AST + {len(sem["nodes"])} semantic)')
|
||||
'@ | & (Get-Content graphify-out\.graphify_python) -
|
||||
```
|
||||
|
||||
### Step 4 - Build graph, cluster, analyze, generate outputs
|
||||
|
||||
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Substitute it the same way you substitute `INPUT_PATH` — do not leave the literal `IS_DIRECTED` in the code.
|
||||
|
||||
```powershell
|
||||
New-Item -ItemType Directory -Force -Path graphify-out | Out-Null
|
||||
@'
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.cluster import cluster, score_all
|
||||
from graphify.analyze import god_nodes, surprising_connections, suggest_questions
|
||||
from graphify.report import generate
|
||||
from graphify.export import to_json
|
||||
from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8"))
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
|
||||
|
||||
# root= mirrors the --update runbook (#1361): relativize source_file to the same
|
||||
# base so the full build and incremental --update never drift apart on re-extract.
|
||||
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
|
||||
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
|
||||
# GRAPH_REPORT.md / analysis sidecar. Check immediately after build (#1392).
|
||||
if G.number_of_nodes() == 0:
|
||||
print('ERROR: Graph is empty - extraction produced no nodes.')
|
||||
print('Possible causes: all files were skipped, binary-only corpus, or extraction failed.')
|
||||
raise SystemExit(1)
|
||||
communities = cluster(G)
|
||||
cohesion = score_all(G, communities)
|
||||
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
|
||||
gods = god_nodes(G)
|
||||
surprises = surprising_connections(G, communities)
|
||||
labels = {cid: 'Community ' + str(cid) for cid in communities}
|
||||
# Placeholder questions - regenerated with real labels in Step 5
|
||||
questions = suggest_questions(G, communities, labels)
|
||||
|
||||
# Export FIRST and honor the #479 shrink-guard: to_json returns False (writing
|
||||
# nothing) when the new graph is smaller than the existing graph.json. Only write
|
||||
# GRAPH_REPORT.md + the analysis sidecar when the graph was actually written, so
|
||||
# they never describe a graph that graph.json doesn't contain (#1392).
|
||||
wrote = to_json(G, communities, 'graphify-out/graph.json')
|
||||
if not wrote:
|
||||
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
|
||||
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
|
||||
raise SystemExit(1)
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding="utf-8")
|
||||
analysis = {
|
||||
'communities': {str(k): v for k, v in communities.items()},
|
||||
'cohesion': {str(k): v for k, v in cohesion.items()},
|
||||
'gods': gods,
|
||||
'surprises': surprises,
|
||||
'questions': questions,
|
||||
}
|
||||
Path('graphify-out/.graphify_analysis.json').write_text(json.dumps(analysis, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(communities)} communities')
|
||||
'@ | & (Get-Content graphify-out\.graphify_python) -
|
||||
```
|
||||
|
||||
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
|
||||
|
||||
Replace INPUT_PATH with the actual path.
|
||||
|
||||
### Step 4.5 - Graph health check (read-only integrity gate)
|
||||
|
||||
A non-destructive diagnostic on the extraction, before labeling. It surfaces edge collapse, dangling/missing endpoints, and self-loops — the silent-corruption modes of incremental updates and AST/LLM id mismatches. Read-only; never aborts.
|
||||
|
||||
```powershell
|
||||
@'
|
||||
import json
|
||||
from pathlib import Path
|
||||
from graphify.diagnostics import diagnose_extraction, format_diagnostic_report
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8"))
|
||||
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root='INPUT_PATH')
|
||||
print(format_diagnostic_report(summary))
|
||||
flags = [f'{summary[k]} {label}' for k, label in (
|
||||
('dangling_endpoint_edges', 'dangling-endpoint edges'),
|
||||
('missing_endpoint_edges', 'missing-endpoint edges'),
|
||||
('self_loop_edges', 'self-loop edges'),
|
||||
('directed_same_endpoint_collapsed_edges', 'collapsed (directed) edges'),
|
||||
('undirected_same_endpoint_collapsed_edges', 'collapsed (undirected) edges'),
|
||||
) if summary.get(k, 0)]
|
||||
print('GRAPH HEALTH WARNING: ' + '; '.join(flags) + ' - graph may be incomplete/corrupt.' if flags else 'Graph health: OK (no dangling/missing/collapsed edges).')
|
||||
'@ | & (Get-Content graphify-out\.graphify_python) -
|
||||
```
|
||||
|
||||
Substitute `IS_DIRECTED` and `INPUT_PATH` as in Step 4. If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
|
||||
|
||||
### Step 5 - Label communities
|
||||
|
||||
Read `graphify-out/.graphify_analysis.json`. For each community key, look at its node labels and write a 2-5 word plain-language name (e.g. "Attention Mechanism", "Training Pipeline", "Data Loading").
|
||||
|
||||
Then regenerate the report and save the labels for the visualizer:
|
||||
|
||||
```powershell
|
||||
@'
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.cluster import score_all
|
||||
from graphify.analyze import god_nodes, surprising_connections, suggest_questions
|
||||
from graphify.report import generate
|
||||
from graphify.export import to_json
|
||||
from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8"))
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
|
||||
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding="utf-8"))
|
||||
|
||||
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
|
||||
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
|
||||
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
|
||||
|
||||
# LABELS - replace these with the names you chose above
|
||||
labels = LABELS_DICT
|
||||
|
||||
# Regenerate questions with real community labels (labels affect question phrasing)
|
||||
questions = suggest_questions(G, communities, labels)
|
||||
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding="utf-8")
|
||||
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding="utf-8")
|
||||
# Re-export so graph.json nodes carry the curated community_name (#2490).
|
||||
# Same extraction as Step 4, so the #479 shrink-guard passes on node count;
|
||||
# if it still refuses, surface the guard message - do not force past it.
|
||||
wrote = to_json(G, communities, 'graphify-out/graph.json', community_labels=labels)
|
||||
if not wrote:
|
||||
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
|
||||
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
|
||||
print('Report updated with community labels')
|
||||
'@ | & (Get-Content graphify-out\.graphify_python) -
|
||||
```
|
||||
|
||||
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
|
||||
Replace INPUT_PATH with the actual path.
|
||||
|
||||
### Step 6 - Generate Obsidian vault (opt-in) + HTML
|
||||
|
||||
**Generate HTML always** (unless `--no-viz`). **Obsidian vault only if `--obsidian` was explicitly given** — skip it otherwise, it generates one file per node.
|
||||
|
||||
If `--obsidian` was given:
|
||||
|
||||
- If `--obsidian-dir <path>` was also given, pass it via `--dir`. Otherwise defaults to `graphify-out/obsidian`.
|
||||
|
||||
```powershell
|
||||
graphify export obsidian
|
||||
# or with custom dir: graphify export obsidian --dir ~/vaults/my-project
|
||||
```
|
||||
|
||||
Generate the HTML graph (always, unless `--no-viz`):
|
||||
|
||||
```powershell
|
||||
graphify export html # auto-aggregates to community view if graph > 5000 nodes
|
||||
# or: graphify export html --no-viz
|
||||
```
|
||||
|
||||
### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags)
|
||||
|
||||
These run only when their flag is present (`--wiki`, `--neo4j`/`--neo4j-push`, `--falkordb`/`--falkordb-push`, `--svg`, `--graphml`, `--mcp`) or, for the token-reduction benchmark, when `total_words` exceeds 5,000. A default run with no export flags skips all of them. See `references/exports.md` for each one. Run any `--wiki` export before Step 9 cleanup so `.graphify_labels.json` is still available.
|
||||
|
||||
---
|
||||
|
||||
### Step 9 - Save manifest, update cost tracker, clean up, and report
|
||||
|
||||
```powershell
|
||||
@'
|
||||
import json
|
||||
from pathlib import Path
|
||||
from datetime import datetime, timezone
|
||||
from graphify.detect import save_manifest
|
||||
|
||||
# Save manifest for --update
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
|
||||
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8"))
|
||||
# In --update mode, 'all_files' carries the full corpus; 'files' is the changed
|
||||
# subset. Full-rebuild mode populates only 'files', so the fallback handles that.
|
||||
# root= relativizes the manifest keys to the scan root (same base as the build),
|
||||
# so the on-disk manifest is portable across clones/machines and a later --update
|
||||
# matches cached files instead of missing every one (#1417).
|
||||
#
|
||||
# Only stamp semantic files (docs/papers/images) that ACTUALLY produced output:
|
||||
# a detected file whose chunk failed or was omitted must stay unstamped so the
|
||||
# next --update re-queues it, otherwise it is marked done and its content is lost
|
||||
# forever (#2015). This mirrors the library extract path exactly
|
||||
# (cli._stamped_manifest_files + clear_semantic + scan_corpus); do not stamp the
|
||||
# raw corpus. Code files are always stamped (AST is deterministic); only semantic
|
||||
# types are gated on output.
|
||||
from graphify.cli import _stamped_manifest_files
|
||||
_corpus = detect.get('all_files') or detect['files']
|
||||
_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'))
|
||||
# Files dispatched this run (the changed subset) but NOT stamped above still carry
|
||||
# a stale semantic_hash from a prior run; clear it so detect_incremental re-queues
|
||||
# them instead of reading them as unchanged (#1948).
|
||||
_sem_types = ('document', 'paper', 'image')
|
||||
_dispatched = {f for t, fl in detect['files'].items() if t in _sem_types for f in fl}
|
||||
_stamped = {f for fl in _manifest_files.values() for f in fl}
|
||||
_cleared = _dispatched - _stamped
|
||||
# scan_corpus = the RAW full corpus (not the stamp-filtered subset) so in-root
|
||||
# files newly excluded since last run are dropped rather than masquerading as
|
||||
# deletions; untouched files' prior rows are still preserved (#1908).
|
||||
_scan = {f for fl in _corpus.values() for f in fl}
|
||||
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
|
||||
# Update cumulative cost tracker
|
||||
input_tok = extract.get('input_tokens', 0)
|
||||
output_tok = extract.get('output_tokens', 0)
|
||||
|
||||
cost_path = Path('graphify-out/cost.json')
|
||||
if cost_path.exists():
|
||||
cost = json.loads(cost_path.read_text(encoding="utf-8"))
|
||||
else:
|
||||
cost = {'runs': [], 'total_input_tokens': 0, 'total_output_tokens': 0}
|
||||
|
||||
cost['runs'].append({
|
||||
'date': datetime.now(timezone.utc).isoformat(),
|
||||
'input_tokens': input_tok,
|
||||
'output_tokens': output_tok,
|
||||
'files': detect.get('total_files', 0),
|
||||
})
|
||||
cost['total_input_tokens'] += input_tok
|
||||
cost['total_output_tokens'] += output_tok
|
||||
cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
|
||||
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
|
||||
print(f'All time: {cost["total_input_tokens"]:,} input, {cost["total_output_tokens"]:,} output ({len(cost["runs"])} runs)')
|
||||
'@ | & (Get-Content graphify-out\.graphify_python) -
|
||||
Remove-Item -Force -ErrorAction SilentlyContinue graphify-out\.graphify_detect.json, graphify-out\.graphify_extract.json, graphify-out\.graphify_ast.json, graphify-out\.graphify_semantic.json, graphify-out\.graphify_analysis.json
|
||||
Get-ChildItem graphify-out -Filter '.graphify_chunk_*.json' -File -ErrorAction SilentlyContinue | Remove-Item -Force
|
||||
Remove-Item -Force -ErrorAction SilentlyContinue graphify-out\.needs_update
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path (same value used in Steps 4-5) so the manifest is relativized to the scan root.
|
||||
|
||||
Tell the user (omit the obsidian line unless --obsidian was given):
|
||||
```
|
||||
Graph complete. Outputs in PATH_TO_DIR/graphify-out/
|
||||
|
||||
graph.html - interactive graph, open in browser
|
||||
GRAPH_REPORT.md - audit report
|
||||
graph.json - raw graph data
|
||||
obsidian/ - Obsidian vault (only if --obsidian was given)
|
||||
```
|
||||
|
||||
If graphify saved you time, consider supporting it: https://github.com/sponsors/safishamsi
|
||||
|
||||
Replace PATH_TO_DIR with the actual absolute path of the directory that was processed.
|
||||
|
||||
Then paste these sections from GRAPH_REPORT.md directly into the chat:
|
||||
- God Nodes
|
||||
- Surprising Connections
|
||||
- Suggested Questions
|
||||
|
||||
Do NOT paste the full report - just those three sections. Keep it concise.
|
||||
|
||||
Then immediately offer to explore. Pick the single most interesting suggested question from the report - the one that crosses the most community boundaries or has the most surprising bridge node - and ask:
|
||||
|
||||
> "The most interesting question this graph can answer: **[question]**. Want me to trace it?"
|
||||
|
||||
If the user says yes, run `/graphify query "[question]"` on the graph and walk them through the answer using the graph structure - which nodes connect, which community boundaries get crossed, what the path reveals. Keep going as long as they want to explore. Each answer should end with a natural follow-up ("this connects to X - want to go deeper?") so the session feels like navigation, not a one-shot report.
|
||||
|
||||
The graph is the map. Your job after the pipeline is to be the guide.
|
||||
|
||||
---
|
||||
|
||||
## Interpreter guard for subcommands
|
||||
|
||||
Before running any subcommand below (`--update`, `--cluster-only`, `query`, `path`, `explain`, `add`), check that `.graphify_python` exists. If it's missing (e.g. user deleted `graphify-out/`), re-resolve the interpreter first:
|
||||
|
||||
```powershell
|
||||
if (-not (Test-Path graphify-out\.graphify_python)) {
|
||||
$GRAPHIFY_PYTHON = $null
|
||||
$graphifyCmd = Get-Command graphify -ErrorAction SilentlyContinue
|
||||
if ($graphifyCmd) {
|
||||
# The interpreter that owns the graphify entry point sits next to it
|
||||
# (<env>\Scripts\python.exe for uv tool, pipx, and venv installs).
|
||||
$py = Join-Path (Split-Path $graphifyCmd.Source) "python.exe"
|
||||
if (Test-Path $py) { $GRAPHIFY_PYTHON = $py }
|
||||
}
|
||||
if (-not $GRAPHIFY_PYTHON) { $GRAPHIFY_PYTHON = "python" }
|
||||
New-Item -ItemType Directory -Force -Path graphify-out | Out-Null
|
||||
& $GRAPHIFY_PYTHON -c "import sys; open('graphify-out/.graphify_python', 'w', encoding='utf-8').write(sys.executable)"
|
||||
}
|
||||
```
|
||||
|
||||
## For --update and --cluster-only
|
||||
|
||||
Both are non-default subcommands. `--update` re-extracts only new or changed files; `--cluster-only` reruns clustering on the existing graph. See `references/update.md` for both flows.
|
||||
|
||||
---
|
||||
|
||||
## For /graphify query
|
||||
|
||||
When `graphify-out/graph.json` already exists and the user asks a question about the corpus, answer from the graph rather than rebuilding it:
|
||||
|
||||
```powershell
|
||||
graphify query "<question>"
|
||||
```
|
||||
|
||||
Before traversal, expand the question against the graph's own vocabulary so a wording mismatch does not collapse the answer to noise. If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For that vocab-expansion step, the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
|
||||
|
||||
---
|
||||
|
||||
## For /graphify add and --watch
|
||||
|
||||
Neither is part of the default build. When the user runs `/graphify add <url>` to fetch a URL into the corpus, or passes `--watch` to auto-rebuild on file changes, see `references/add-watch.md`.
|
||||
|
||||
---
|
||||
|
||||
## For the commit hook and native CLAUDE.md integration
|
||||
|
||||
When the user asks to install the post-commit auto-rebuild hook or wire graphify into a project's CLAUDE.md, see `references/hooks.md`.
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### PowerShell 5.1: Vertical scrolling stops working
|
||||
|
||||
If vertical scrolling breaks in PowerShell after running graphify, this is caused by ANSI escape sequences from the `graspologic` library. Graphify v0.3.10+ suppresses this output, but if you still see the issue:
|
||||
|
||||
1. **Upgrade graphify**: `pip install --upgrade graphifyy`
|
||||
2. **Use Windows Terminal** instead of the legacy PowerShell console — Windows Terminal handles ANSI codes correctly
|
||||
3. **Reset your terminal**: close and reopen PowerShell
|
||||
4. **Skip graspologic**: uninstall it (`pip uninstall graspologic`) and graphify will fall back to NetworkX's built-in Louvain algorithm, which produces no ANSI output
|
||||
|
||||
---
|
||||
|
||||
## Honesty Rules
|
||||
|
||||
- Never invent an edge. If unsure, use AMBIGUOUS.
|
||||
- Never skip the corpus check warning.
|
||||
- Always show token cost in the report.
|
||||
- Never hide cohesion scores behind symbols - show the raw number.
|
||||
- Never run HTML viz on a graph with more than 5,000 nodes without warning the user.
|
||||
56
.claude/skills/graphify/references/add-watch.md
Normal file
56
.claude/skills/graphify/references/add-watch.md
Normal file
@ -0,0 +1,56 @@
|
||||
# graphify reference: add a URL and watch a folder
|
||||
|
||||
Load this when the user ran `/graphify add <url>` or passed `--watch`. Neither is part of the default build.
|
||||
|
||||
## For /graphify add
|
||||
|
||||
Fetch a URL and add it to the corpus, then update the graph.
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import sys
|
||||
from graphify.ingest import ingest
|
||||
from pathlib import Path
|
||||
|
||||
try:
|
||||
out = ingest('URL', Path('./raw'), author='AUTHOR', contributor='CONTRIBUTOR')
|
||||
print(f'Saved to {out}')
|
||||
except ValueError as e:
|
||||
print(f'error: {e}', file=sys.stderr)
|
||||
sys.exit(1)
|
||||
except RuntimeError as e:
|
||||
print(f'error: {e}', file=sys.stderr)
|
||||
sys.exit(1)
|
||||
"
|
||||
```
|
||||
|
||||
Replace `URL` with the actual URL, `AUTHOR` with the user's name if provided, `CONTRIBUTOR` likewise. If the command exits with an error, tell the user what went wrong - do not silently continue. After a successful save, automatically run the `--update` pipeline on `./raw` to merge the new file into the existing graph.
|
||||
|
||||
Supported URL types (auto-detected):
|
||||
- YouTube / any video URL → audio downloaded via yt-dlp, transcribed to `.txt` on next run (requires `pip install 'graphifyy[video]'`)
|
||||
- Twitter/X → fetched via oEmbed, saved as `.md` with tweet text and author
|
||||
- arXiv → abstract + metadata saved as `.md`
|
||||
- PDF → downloaded as `.pdf`
|
||||
- Images (.png/.jpg/.webp) → downloaded, Claude vision extracts on next run
|
||||
- Any webpage → converted to markdown via html2text
|
||||
|
||||
---
|
||||
|
||||
## For --watch
|
||||
|
||||
Start a background watcher that monitors a folder and auto-updates the graph when files change.
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -m graphify.watch INPUT_PATH --debounce 3
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the folder to watch. Behavior depends on what changed:
|
||||
|
||||
- **Code files only (.py, .ts, .go, etc.):** re-runs AST extraction + rebuild + cluster immediately, no LLM needed. `graph.json` and `GRAPH_REPORT.md` are updated automatically.
|
||||
- **Docs, papers, or images:** writes a `graphify-out/needs_update` flag and prints a notification to run `/graphify --update` (LLM semantic re-extraction required).
|
||||
|
||||
Debounce (default 3s): waits until file activity stops before triggering, so a wave of parallel agent writes doesn't trigger a rebuild per file.
|
||||
|
||||
Press Ctrl+C to stop.
|
||||
|
||||
For agentic workflows: run `--watch` in a background terminal. Code changes from agent waves are picked up automatically between waves. If agents are also writing docs or notes, you'll need a manual `/graphify --update` after those waves.
|
||||
87
.claude/skills/graphify/references/exports.md
Normal file
87
.claude/skills/graphify/references/exports.md
Normal file
@ -0,0 +1,87 @@
|
||||
# graphify reference: extra exports and benchmark
|
||||
|
||||
Load this when the user passed one of the export flags (`--wiki`, `--neo4j`, `--neo4j-push`, `--falkordb`, `--falkordb-push`, `--svg`, `--graphml`, `--mcp`), or when the corpus is large enough for the token-reduction benchmark. Each step runs only for its own flag.
|
||||
|
||||
### Step 6b - Wiki (only if --wiki flag)
|
||||
|
||||
**Only run this step if `--wiki` was explicitly given in the original command.**
|
||||
|
||||
Run this before Step 9 (cleanup) so `.graphify_labels.json` is still available.
|
||||
|
||||
```bash
|
||||
graphify export wiki
|
||||
```
|
||||
|
||||
### Step 7 - Neo4j export (only if --neo4j or --neo4j-push flag)
|
||||
|
||||
**If `--neo4j`** - generate a Cypher file for manual import:
|
||||
|
||||
```bash
|
||||
graphify export neo4j
|
||||
```
|
||||
|
||||
**If `--neo4j-push <uri>`** - push directly to a running Neo4j instance. Ask the user for credentials if not provided:
|
||||
|
||||
```bash
|
||||
graphify export neo4j --push bolt://localhost:7687 --user neo4j --password PASSWORD
|
||||
```
|
||||
|
||||
Default URI is `bolt://localhost:7687`, default user is `neo4j`. Uses MERGE - safe to re-run without creating duplicates.
|
||||
|
||||
### Step 7a - FalkorDB export (only if --falkordb or --falkordb-push flag)
|
||||
|
||||
**If `--falkordb`** - generate a Cypher file. The statements are OpenCypher, but FalkorDB's `GRAPH.QUERY` runs one statement at a time (no bulk script import like Neo4j's `cypher-shell`), so prefer `--falkordb-push` to load a graph. Use this only when you want the portable `cypher.txt` artifact:
|
||||
|
||||
```bash
|
||||
graphify export falkordb
|
||||
```
|
||||
|
||||
**If `--falkordb-push <uri>`** - push directly to a running FalkorDB instance. Credentials are optional; ask the user only if the instance requires auth:
|
||||
|
||||
```bash
|
||||
graphify export falkordb --push falkordb://localhost:6379
|
||||
```
|
||||
|
||||
Default URI is `falkordb://localhost:6379` (the scheme is informational - `redis://` or a bare `host:port` work too), auth is optional, and the target graph defaults to `graphify`. Uses MERGE - safe to re-run without creating duplicates.
|
||||
|
||||
### Step 7b - SVG export (only if --svg flag)
|
||||
|
||||
```bash
|
||||
graphify export svg
|
||||
```
|
||||
|
||||
### Step 7c - GraphML export (only if --graphml flag)
|
||||
|
||||
```bash
|
||||
graphify export graphml
|
||||
```
|
||||
|
||||
### Step 7d - MCP server (only if --mcp flag)
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -m graphify.serve graphify-out/graph.json
|
||||
```
|
||||
|
||||
This starts a stdio MCP server that exposes tools: `query_graph`, `get_node`, `get_neighbors`, `get_community`, `god_nodes`, `graph_stats`, `shortest_path`. Add to Claude Desktop or any MCP-compatible agent orchestrator so other agents can query the graph live.
|
||||
|
||||
To configure in Claude Desktop, add to `claude_desktop_config.json`. Claude Desktop can't run `$(...)`, and under `uv tool install` the system `python3` can't import graphify — so set `command` to the **absolute interpreter path** printed by `cat graphify-out/.graphify_python`:
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"graphify": {
|
||||
"command": "<absolute path from: cat graphify-out/.graphify_python>",
|
||||
"args": ["-m", "graphify.serve", "/absolute/path/to/graphify-out/graph.json"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Step 8 - Token reduction benchmark (only if total_words > 5000)
|
||||
|
||||
If `total_words` from `graphify-out/.graphify_detect.json` is greater than 5,000, run:
|
||||
|
||||
```bash
|
||||
graphify benchmark
|
||||
```
|
||||
|
||||
Print the output directly in chat. If `total_words <= 5000`, skip silently - the graph value is structural clarity, not token compression, for small corpora.
|
||||
70
.claude/skills/graphify/references/extraction-spec.md
Normal file
70
.claude/skills/graphify/references/extraction-spec.md
Normal file
@ -0,0 +1,70 @@
|
||||
# graphify reference: extraction subagent prompt
|
||||
|
||||
Load this in Step 3 Part B when the corpus has at least one doc, paper, or image chunk. A pure-code corpus skips Part B and never reads this file. Each semantic subagent receives the prompt below verbatim (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH).
|
||||
|
||||
```
|
||||
You are a graphify extraction subagent. Read the files listed and extract a knowledge graph fragment.
|
||||
Output ONLY valid JSON matching the schema below - no explanation, no markdown fences, no preamble.
|
||||
|
||||
Files (chunk CHUNK_NUM of TOTAL_CHUNKS):
|
||||
FILE_LIST
|
||||
|
||||
Rules:
|
||||
- EXTRACTED: relationship explicit in source (import, call, citation, "see §3.2")
|
||||
- INFERRED: reasonable inference (shared data structure, implied dependency)
|
||||
- AMBIGUOUS: uncertain - flag for review, do not omit
|
||||
|
||||
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
|
||||
Do not re-extract imports - AST already has those.
|
||||
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept. Use `file_type:"rationale"` for concept-like nodes (ideas, principles, mechanisms, design patterns). `file_type` MUST be one of exactly these six values: `code`, `document`, `paper`, `image`, `rationale`, `concept`. Any other value is invalid and will be rejected.
|
||||
Code files: when adding `calls` edges, source MUST be the caller (the function/class doing the calling), target MUST be the callee. Never reverse this direction. `calls` edges MUST stay within one language: a Python function cannot `calls` a JS/TS/Go/Rust/Java symbol and vice versa — cross-language call edges are phantom artifacts, never emit them.
|
||||
Image files: use vision to understand what the image IS - do not just OCR.
|
||||
UI screenshot: layout patterns, design decisions, key elements, purpose.
|
||||
Chart: metric, trend/insight, data source.
|
||||
Tweet/post: claim as node, author, concepts mentioned.
|
||||
Diagram: components and connections.
|
||||
Research figure: what it demonstrates, method, result.
|
||||
Handwritten/whiteboard: ideas and arrows, mark uncertain readings AMBIGUOUS.
|
||||
|
||||
DEEP_MODE (if --mode deep was given): be aggressive with INFERRED edges - indirect deps,
|
||||
shared assumptions, latent couplings. Mark uncertain ones AMBIGUOUS instead of omitting.
|
||||
|
||||
Semantic similarity: if two concepts in this chunk solve the same problem or represent the same idea without any structural link (no import, no call, no citation), add a `semantically_similar_to` edge marked INFERRED with a confidence_score reflecting how similar they are (0.6-0.95). Examples:
|
||||
- Two functions that both validate user input but never call each other
|
||||
- A class in code and a concept in a paper that describe the same algorithm
|
||||
- Two error types that handle the same failure mode differently
|
||||
Only add these when the similarity is genuinely non-obvious and cross-cutting. Do not add them for trivially similar things.
|
||||
|
||||
Hyperedges: if 3 or more nodes clearly participate together in a shared concept, flow, or pattern that is not captured by pairwise edges alone, add a hyperedge to a top-level `hyperedges` array. Examples:
|
||||
- All classes that implement a common protocol or interface
|
||||
- All functions in an authentication flow (even if they don't all call each other)
|
||||
- All concepts from a paper section that form one coherent idea
|
||||
Use sparingly — only when the group relationship adds information beyond the pairwise edges. Maximum 3 hyperedges per chunk.
|
||||
|
||||
If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, author,
|
||||
contributor onto every node from that file.
|
||||
|
||||
confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default:
|
||||
- EXTRACTED edges: confidence_score = 1.0 always
|
||||
- INFERRED edges: pick exactly ONE value from this set — never 0.5:
|
||||
0.95 direct structural evidence (shared data structure, named cross-file reference).
|
||||
0.85 strong inference (clear functional alignment, no direct symbol link).
|
||||
0.75 reasonable inference (shared problem domain + similar shape, requires interpretation).
|
||||
0.65 weak inference (thematically related, no shape evidence).
|
||||
0.55 speculative but plausible (surface-level co-occurrence only).
|
||||
Models follow discrete rubrics better than continuous ranges; the bimodal
|
||||
distribution observed in production (>50% at 0.5, >40% at 0.85+) shows the
|
||||
range guidance is being collapsed to a binary. If no value above fits, mark
|
||||
the edge AMBIGUOUS rather than picking 0.4 or below.
|
||||
- AMBIGUOUS edges: 0.1-0.3
|
||||
|
||||
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format: `{stem}_{entity}` where stem is the **full repo-relative path with the extension dropped**, every path segment kept and joined with `_` (each segment lowercased with non-alphanumeric chars replaced by `_`), and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent — this keeps same-named files in different directories distinct. Examples: `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `lib_utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`; `docs/v1/api/README.md` + `getUser` → `docs_v1_api_readme_getuser`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or only the immediate parent (e.g., `auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project built under the old immediate-parent format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
|
||||
|
||||
Generate the extraction JSON matching this schema exactly:
|
||||
{"nodes":[{"id":"auth_session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0}
|
||||
|
||||
source_file RULE (every node, edge, and hyperedge): set source_file to the path of the originating file EXACTLY as it appears in FILE_LIST — verbatim and absolute. Do NOT shorten to a basename, do NOT re-relativize, do NOT strip any directory prefix, and do NOT change separators (the engine canonicalizes separators and relativizes against the build root downstream). Copy the FILE_LIST entry character-for-character. This keeps the full build and incremental --update on the same base, so build_merge's replace-on-re-extract matches the existing node instead of accumulating a duplicate.
|
||||
|
||||
Then write the JSON to disk using the Write tool at this exact absolute path (no relative paths — Write resolves relative paths against an undefined cwd and the file will be silently lost):
|
||||
CHUNK_PATH
|
||||
```
|
||||
46
.claude/skills/graphify/references/github-and-merge.md
Normal file
46
.claude/skills/graphify/references/github-and-merge.md
Normal file
@ -0,0 +1,46 @@
|
||||
# graphify reference: GitHub clone and cross-repo merge
|
||||
|
||||
Load this when the user passed one or more `https://github.com/...` URLs, or named several local subfolders to merge into one graph.
|
||||
|
||||
### Step 0 - Clone GitHub repo(s) (only if a GitHub URL was given)
|
||||
|
||||
**Single repo:**
|
||||
```bash
|
||||
LOCAL_PATH=$(graphify clone <github-url> [--branch <branch>])
|
||||
# Use LOCAL_PATH as the target for all subsequent steps
|
||||
```
|
||||
|
||||
**Multiple repos (cross-repo graph):**
|
||||
```bash
|
||||
# Clone each repo, run the full pipeline on each, then merge
|
||||
graphify clone <url1> # → ~/.graphify/repos/<owner1>/<repo1>
|
||||
graphify clone <url2> # → ~/.graphify/repos/<owner2>/<repo2>
|
||||
# Run /graphify on each local path to produce their graph.json files
|
||||
# Then merge:
|
||||
graphify merge-graphs \
|
||||
~/.graphify/repos/<owner1>/<repo1>/graphify-out/graph.json \
|
||||
~/.graphify/repos/<owner2>/<repo2>/graphify-out/graph.json \
|
||||
--out graphify-out/cross-repo-graph.json
|
||||
```
|
||||
|
||||
Graphify clones into `~/.graphify/repos/<owner>/<repo>` and reuses existing clones on repeat runs. Each node in the merged graph carries a `repo` attribute so you can filter by origin.
|
||||
|
||||
**Multiple local subfolders (monorepo or multi-service layout):**
|
||||
|
||||
The skill pipeline writes all intermediate and final outputs to `graphify-out/` in the current working directory. Running the skill on each subfolder separately will clobber the same output dir. Instead, use the CLI directly for each subfolder — it places `graphify-out/` *inside* the scanned path:
|
||||
|
||||
```bash
|
||||
graphify extract ./core/ # → ./core/graphify-out/graph.json
|
||||
graphify extract ./service/ # → ./service/graphify-out/graph.json
|
||||
graphify extract ./platform/ # → ./platform/graphify-out/graph.json
|
||||
# Add --backend gemini|kimi|openai|deepseek|claude-cli depending on which API key you have set
|
||||
|
||||
# Then merge at the project root:
|
||||
graphify merge-graphs \
|
||||
./core/graphify-out/graph.json \
|
||||
./service/graphify-out/graph.json \
|
||||
./platform/graphify-out/graph.json \
|
||||
--out graphify-out/graph.json
|
||||
```
|
||||
|
||||
Once `graphify-out/graph.json` exists, the fast path above takes over: any codebase question runs `graphify query` directly on the merged graph — no re-extraction, no size gate.
|
||||
33
.claude/skills/graphify/references/hooks.md
Normal file
33
.claude/skills/graphify/references/hooks.md
Normal file
@ -0,0 +1,33 @@
|
||||
# graphify reference: commit hook and native CLAUDE.md integration
|
||||
|
||||
Load this when the user asked to install the post-commit hook or wire graphify into a project's CLAUDE.md.
|
||||
|
||||
## For git commit hook
|
||||
|
||||
Install a post-commit hook that auto-rebuilds the graph after every commit. No background process needed - triggers once per commit, works with any editor.
|
||||
|
||||
```bash
|
||||
graphify hook install # install
|
||||
graphify hook uninstall # remove
|
||||
graphify hook status # check
|
||||
```
|
||||
|
||||
After every `git commit`, the hook detects which code files changed (via `git diff HEAD~1`), re-runs AST extraction on those files, and rebuilds `graph.json` and `GRAPH_REPORT.md`. Doc/image changes are ignored by the hook - run `/graphify --update` manually for those.
|
||||
|
||||
If a post-commit hook already exists, graphify appends to it rather than replacing it.
|
||||
|
||||
---
|
||||
|
||||
## For native CLAUDE.md integration
|
||||
|
||||
Run once per project to make graphify always-on in Claude Code sessions:
|
||||
|
||||
```bash
|
||||
graphify claude install
|
||||
```
|
||||
|
||||
This writes a `## graphify` section to the local `CLAUDE.md` that instructs Claude to check the graph before answering codebase questions and rebuild it after code changes. No manual `/graphify` needed in future sessions.
|
||||
|
||||
```bash
|
||||
graphify claude uninstall # remove the section
|
||||
```
|
||||
311
.claude/skills/graphify/references/query.md
Normal file
311
.claude/skills/graphify/references/query.md
Normal file
@ -0,0 +1,311 @@
|
||||
# graphify reference: query, path, explain
|
||||
|
||||
Load this when the user asks a question against an existing graph, or runs `/graphify path` or `/graphify explain`. The core's query stub points here for the full traversal flow. These flows use the `graphify query` CLI when it is available and fall back to an inline NetworkX traversal otherwise.
|
||||
|
||||
Two traversal modes - choose based on the question:
|
||||
|
||||
| Mode | Flag | Best for |
|
||||
|------|------|----------|
|
||||
| BFS (default) | _(none)_ | "What is X connected to?" - broad context, nearest neighbors first |
|
||||
| DFS | `--dfs` | "How does X reach Y?" - trace a specific chain or dependency path |
|
||||
|
||||
First check the graph exists:
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
from pathlib import Path
|
||||
if not Path('graphify-out/graph.json').exists():
|
||||
print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
|
||||
raise SystemExit(1)
|
||||
"
|
||||
```
|
||||
If it fails, stop and tell the user to run `/graphify <path>` first.
|
||||
|
||||
### Step 0 — Constrained query expansion (REQUIRED before traversal)
|
||||
|
||||
graphify's `query` CLI matches nodes via case-folded substring + IDF — there is **no stemming, no synonyms, no cross-language match** inside the binary, and the inline fallback below matches the same way. If the user's question uses different language or different domain vocabulary than the graph's labels (user says "обработчик" / graph says "handler"; user says "authentication" / graph says "Guardian"), the literal matcher returns 0 hits and the answer collapses to noise.
|
||||
|
||||
Fix this **without inventing tokens** by expanding the query against the actual graph vocabulary first:
|
||||
|
||||
1. Extract the token vocabulary from node labels:
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json, re
|
||||
from pathlib import Path
|
||||
data = json.loads(Path('graphify-out/graph.json').read_text(encoding='utf-8'))
|
||||
vocab = set()
|
||||
for n in data['nodes']:
|
||||
for c in re.findall(r'[^\W\d_]+', n.get('label','') or '', re.UNICODE):
|
||||
parts = re.findall(r'[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+', c) or [c]
|
||||
for p in parts:
|
||||
t = p.lower()
|
||||
if 3 <= len(t) <= 30:
|
||||
vocab.add(t)
|
||||
Path('graphify-out/.vocab.txt').write_text('\n'.join(sorted(vocab)), encoding='utf-8')
|
||||
print(f'vocab: {len(vocab)} tokens')
|
||||
"
|
||||
```
|
||||
|
||||
2. Read `graphify-out/.vocab.txt`. Then for the user's question, select **up to 12 tokens from this exact list** that semantically match the query intent. Hard constraints:
|
||||
- You MUST pick only tokens present in the vocabulary file. Do NOT invent tokens.
|
||||
- If a query concept has no plausible token in the vocab, skip it — do not substitute a near-synonym from training memory.
|
||||
- If **no** vocab tokens match the query at all, output an empty list and tell the user the corpus has no relevant vocabulary for this question. Do not fabricate a search.
|
||||
- Translate cross-language: Russian "аутентификация" → look for `auth`, `credential`, `token`, `security` IFF present in vocab.
|
||||
- Morphology: "handlers" maps to `handler` IFF present; "todos" maps to `todo` IFF present.
|
||||
|
||||
3. Print the selection explicitly to the user before running the query, so the expansion is auditable:
|
||||
```
|
||||
Query expanded to (from graph vocab, N tokens): [token1, token2, ...]
|
||||
```
|
||||
If the list is empty, say so plainly and stop — do not proceed to traversal.
|
||||
|
||||
### Step 1 — Traversal
|
||||
|
||||
Build the **expanded query string** by joining the selected tokens with spaces. Use this string as `QUESTION` below — NOT the original user question. (The original question is preserved only for `save-result` at the end.)
|
||||
|
||||
Prefer the CLI when it is installed:
|
||||
```bash
|
||||
graphify query "QUESTION"
|
||||
# or: graphify query "QUESTION" --dfs --budget 3000
|
||||
```
|
||||
|
||||
If the CLI is unavailable, load `graphify-out/graph.json` and run the traversal inline:
|
||||
|
||||
1. Find the 1-3 nodes whose label best matches the expanded tokens.
|
||||
2. Run the appropriate traversal from each starting node.
|
||||
3. Read the subgraph - node labels, edge relations, confidence tags, source locations.
|
||||
4. Answer using **only** what the graph contains. Quote `source_location` when citing a specific fact.
|
||||
5. If the graph lacks enough information, say so - do not hallucinate edges.
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import sys, json
|
||||
from networkx.readwrite import json_graph
|
||||
import networkx as nx
|
||||
from pathlib import Path
|
||||
|
||||
data = json.loads(Path('graphify-out/graph.json').read_text(encoding='utf-8'))
|
||||
G = json_graph.node_link_graph(data, edges='links')
|
||||
|
||||
question = 'QUESTION'
|
||||
mode = 'MODE' # 'bfs' or 'dfs'
|
||||
terms = [t.lower() for t in question.split() if len(t) >= 3] # match the vocab threshold; keeps api/jwt/ios (#1392)
|
||||
|
||||
# Find best-matching start nodes
|
||||
scored = []
|
||||
for nid, ndata in G.nodes(data=True):
|
||||
label = ndata.get('label', '').lower()
|
||||
score = sum(1 for t in terms if t in label)
|
||||
if score > 0:
|
||||
scored.append((score, nid))
|
||||
scored.sort(reverse=True)
|
||||
start_nodes = [nid for _, nid in scored[:3]]
|
||||
|
||||
if not start_nodes:
|
||||
print('No matching nodes found for query terms:', terms)
|
||||
sys.exit(0)
|
||||
|
||||
subgraph_nodes = set()
|
||||
subgraph_edges = []
|
||||
|
||||
if mode == 'dfs':
|
||||
# DFS: follow one path as deep as possible before backtracking.
|
||||
# Depth-limited to 6 to avoid traversing the whole graph.
|
||||
visited = set()
|
||||
stack = [(n, 0) for n in reversed(start_nodes)]
|
||||
while stack:
|
||||
node, depth = stack.pop()
|
||||
if node in visited or depth > 6:
|
||||
continue
|
||||
visited.add(node)
|
||||
subgraph_nodes.add(node)
|
||||
for neighbor in G.neighbors(node):
|
||||
if neighbor not in visited:
|
||||
stack.append((neighbor, depth + 1))
|
||||
subgraph_edges.append((node, neighbor))
|
||||
else:
|
||||
# BFS: explore all neighbors layer by layer up to depth 3.
|
||||
frontier = set(start_nodes)
|
||||
subgraph_nodes = set(start_nodes)
|
||||
for _ in range(3):
|
||||
next_frontier = set()
|
||||
for n in frontier:
|
||||
for neighbor in G.neighbors(n):
|
||||
if neighbor not in subgraph_nodes:
|
||||
next_frontier.add(neighbor)
|
||||
subgraph_edges.append((n, neighbor))
|
||||
subgraph_nodes.update(next_frontier)
|
||||
frontier = next_frontier
|
||||
|
||||
# Token-budget aware output: rank by relevance, cut at budget (~4 chars/token)
|
||||
token_budget = BUDGET # default 2000
|
||||
char_budget = token_budget * 4
|
||||
|
||||
# Score each node by term overlap for ranked output
|
||||
def relevance(nid):
|
||||
label = G.nodes[nid].get('label', '').lower()
|
||||
return sum(1 for t in terms if t in label)
|
||||
|
||||
ranked_nodes = sorted(subgraph_nodes, key=relevance, reverse=True)
|
||||
|
||||
lines = [f'Traversal: {mode.upper()} | Start: {[G.nodes[n].get(\"label\",n) for n in start_nodes]} | {len(subgraph_nodes)} nodes']
|
||||
for nid in ranked_nodes:
|
||||
d = G.nodes[nid]
|
||||
lines.append(f' NODE {d.get(\"label\", nid)} [src={d.get(\"source_file\",\"\")} loc={d.get(\"source_location\",\"\")}]')
|
||||
for u, v in subgraph_edges:
|
||||
if u in subgraph_nodes and v in subgraph_nodes:
|
||||
_raw = G[u][v]; d = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
|
||||
lines.append(f' EDGE {G.nodes[u].get(\"label\",u)} --{d.get(\"relation\",\"\")} [{d.get(\"confidence\",\"\")}]--> {G.nodes[v].get(\"label\",v)}')
|
||||
|
||||
output = '\n'.join(lines)
|
||||
if len(output) > char_budget:
|
||||
output = output[:char_budget] + f'\n... (truncated at ~{token_budget} token budget - use --budget N for more)'
|
||||
print(output)
|
||||
"
|
||||
```
|
||||
|
||||
Replace `QUESTION` with the **expanded** query string, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above, using only what the graph contains.
|
||||
|
||||
After writing the answer, save it back into the graph so it improves future queries. Include the expanded tokens inside the `--answer` text (e.g. `"Expanded from original query via vocab: [tokens]. Then traversed..."`) so the next `--update` extracts the expansion history as a graph node:
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -m graphify save-result --question "ORIGINAL_QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
|
||||
```
|
||||
|
||||
Replace `ORIGINAL_QUESTION` with the user's verbatim question, `ANSWER` with your full answer text (containing the expanded-token trace), `NODE1 NODE2` with the list of node labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.
|
||||
|
||||
**Work memory (self-improving loop).** Add an `--outcome` so future sessions learn from this one — append `--outcome useful|dead_end|corrected` to the `save-result` command (and `--correction "the right answer"` when correcting):
|
||||
|
||||
- `useful` — the cited nodes answered the question well (they become *preferred sources*).
|
||||
- `dead_end` — the question/path led nowhere; don't re-derive it next time.
|
||||
- `corrected` — the saved answer was wrong; `--correction` records what was right.
|
||||
|
||||
At the **start** of graph work, refresh and read the lessons: run `graphify reflect --if-stale` (cheap, deterministic, no LLM; `--if-stale` makes it a no-op when `LESSONS.md` is already newer than every input, e.g. when the git hook just refreshed it), then read `graphify-out/reflections/LESSONS.md`. It lists **preferred sources** (start there), **known dead ends** (skip them), and prior **corrections**. Running `reflect` yourself keeps the lessons current even without the git hook installed; if the post-commit hook *is* installed, `--if-stale` means your session-start run costs almost nothing.
|
||||
|
||||
---
|
||||
|
||||
## For /graphify path
|
||||
|
||||
Find the shortest path between two named concepts in the graph. Prefer the CLI when installed:
|
||||
|
||||
```bash
|
||||
graphify path "NODE_A" "NODE_B"
|
||||
```
|
||||
|
||||
If the CLI is unavailable, run it inline:
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json, sys
|
||||
import networkx as nx
|
||||
from networkx.readwrite import json_graph
|
||||
from pathlib import Path
|
||||
|
||||
data = json.loads(Path('graphify-out/graph.json').read_text(encoding='utf-8'))
|
||||
G = json_graph.node_link_graph(data, edges='links')
|
||||
|
||||
a_term = 'NODE_A'
|
||||
b_term = 'NODE_B'
|
||||
|
||||
def find_node(term):
|
||||
term = term.lower()
|
||||
scored = sorted(
|
||||
[(sum(1 for w in term.split() if w in G.nodes[n].get('label','').lower()), n)
|
||||
for n in G.nodes()],
|
||||
reverse=True
|
||||
)
|
||||
return scored[0][1] if scored and scored[0][0] > 0 else None
|
||||
|
||||
src = find_node(a_term)
|
||||
tgt = find_node(b_term)
|
||||
|
||||
if not src or not tgt:
|
||||
print(f'Could not find nodes matching: {a_term!r} or {b_term!r}')
|
||||
sys.exit(0)
|
||||
|
||||
try:
|
||||
path = nx.shortest_path(G, src, tgt)
|
||||
print(f'Shortest path ({len(path)-1} hops):')
|
||||
for i, nid in enumerate(path):
|
||||
label = G.nodes[nid].get('label', nid)
|
||||
if i < len(path) - 1:
|
||||
_raw = G[nid][path[i+1]]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
|
||||
rel = edge.get('relation', '')
|
||||
conf = edge.get('confidence', '')
|
||||
print(f' {label} --{rel}--> [{conf}]')
|
||||
else:
|
||||
print(f' {label}')
|
||||
except nx.NetworkXNoPath:
|
||||
print(f'No path found between {a_term!r} and {b_term!r}')
|
||||
except nx.NodeNotFound as e:
|
||||
print(f'Node not found: {e}')
|
||||
"
|
||||
```
|
||||
|
||||
Replace `NODE_A` and `NODE_B` with the actual concept names from the user. Then explain the path in plain language - what each hop means, why it's significant.
|
||||
|
||||
After writing the explanation, save it back:
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -m graphify save-result --question "Path from NODE_A to NODE_B" --answer "ANSWER" --type path_query --nodes NODE_A NODE_B
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## For /graphify explain
|
||||
|
||||
Give a plain-language explanation of a single node - everything connected to it. Prefer the CLI when installed:
|
||||
|
||||
```bash
|
||||
graphify explain "NODE_NAME"
|
||||
```
|
||||
|
||||
If the CLI is unavailable, run it inline:
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json, sys
|
||||
import networkx as nx
|
||||
from networkx.readwrite import json_graph
|
||||
from pathlib import Path
|
||||
|
||||
data = json.loads(Path('graphify-out/graph.json').read_text(encoding='utf-8'))
|
||||
G = json_graph.node_link_graph(data, edges='links')
|
||||
|
||||
term = 'NODE_NAME'
|
||||
term_lower = term.lower()
|
||||
|
||||
# Find best matching node
|
||||
scored = sorted(
|
||||
[(sum(1 for w in term_lower.split() if w in G.nodes[n].get('label','').lower()), n)
|
||||
for n in G.nodes()],
|
||||
reverse=True
|
||||
)
|
||||
if not scored or scored[0][0] == 0:
|
||||
print(f'No node matching {term!r}')
|
||||
sys.exit(0)
|
||||
|
||||
nid = scored[0][1]
|
||||
data_n = G.nodes[nid]
|
||||
print(f'NODE: {data_n.get(\"label\", nid)}')
|
||||
print(f' source: {data_n.get(\"source_file\",\"unknown\")}')
|
||||
print(f' type: {data_n.get(\"file_type\",\"unknown\")}')
|
||||
print(f' degree: {G.degree(nid)}')
|
||||
print()
|
||||
print('CONNECTIONS:')
|
||||
for neighbor in G.neighbors(nid):
|
||||
_raw = G[nid][neighbor]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
|
||||
nlabel = G.nodes[neighbor].get('label', neighbor)
|
||||
rel = edge.get('relation', '')
|
||||
conf = edge.get('confidence', '')
|
||||
src_file = G.nodes[neighbor].get('source_file', '')
|
||||
print(f' --{rel}--> {nlabel} [{conf}] ({src_file})')
|
||||
"
|
||||
```
|
||||
|
||||
Replace `NODE_NAME` with the concept the user asked about. Then write a 3-5 sentence explanation of what this node is, what it connects to, and why those connections are significant. Use the source locations as citations.
|
||||
|
||||
After writing the explanation, save it back:
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -m graphify save-result --question "Explain NODE_NAME" --answer "ANSWER" --type explain --nodes NODE_NAME
|
||||
```
|
||||
52
.claude/skills/graphify/references/transcribe.md
Normal file
52
.claude/skills/graphify/references/transcribe.md
Normal file
@ -0,0 +1,52 @@
|
||||
# graphify reference: transcribe video and audio
|
||||
|
||||
Load this only when `detect` reported one or more `video` files. A corpus with no video never reads this.
|
||||
|
||||
### Step 2.5 - Transcribe video / audio files (only if video files detected)
|
||||
|
||||
Skip this step entirely if `detect` returned zero `video` files.
|
||||
|
||||
Video and audio files cannot be read directly. Transcribe them to text first, then treat the transcripts as doc files in Step 3.
|
||||
|
||||
**Strategy:** Read the god nodes from `graphify-out/.graphify_detect.json` (or the analysis file if it exists from a previous run). You are already a language model — write a one-sentence domain hint yourself from those labels. Then pass it to Whisper as the initial prompt. No separate API call needed.
|
||||
|
||||
**However**, if the corpus has *only* video files and no other docs/code, use the generic fallback prompt: `"Use proper punctuation and paragraph breaks."`
|
||||
|
||||
**Step 1 - Write the Whisper prompt yourself.**
|
||||
|
||||
Read the top god node labels from detect output or analysis, then compose a short domain hint sentence, for example:
|
||||
|
||||
- Labels: `transformer, attention, encoder, decoder` → `"Machine learning research on transformer architectures and attention mechanisms. Use proper punctuation and paragraph breaks."`
|
||||
- Labels: `kubernetes, deployment, pod, helm` → `"DevOps discussion about Kubernetes deployments and Helm charts. Use proper punctuation and paragraph breaks."`
|
||||
|
||||
**Export** it as `GRAPHIFY_WHISPER_PROMPT` (the exact name the transcriber reads — and it must be `export`ed so the child Python process sees it) for the next command.
|
||||
|
||||
**Step 2 - Transcribe:**
|
||||
|
||||
```bash
|
||||
export GRAPHIFY_WHISPER_MODEL=base # or whatever --whisper-model the user passed (must be exported)
|
||||
export GRAPHIFY_WHISPER_PROMPT="<the one-sentence domain hint you composed in Step 1>"
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json, os, sys
|
||||
from pathlib import Path
|
||||
from graphify.transcribe import transcribe_all
|
||||
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
video_files = detect.get('files', {}).get('video', [])
|
||||
prompt = os.environ.get('GRAPHIFY_WHISPER_PROMPT', 'Use proper punctuation and paragraph breaks.')
|
||||
|
||||
transcript_paths = transcribe_all(video_files, initial_prompt=prompt)
|
||||
# Write the JSON from Python (NOT a shell '>' redirect): transcribe_all/Whisper
|
||||
# print progress to stdout, which would otherwise corrupt the JSON file (#1392).
|
||||
Path('graphify-out/.graphify_transcripts.json').write_text(json.dumps(transcript_paths, ensure_ascii=False), encoding=\"utf-8\")
|
||||
print(f'Transcribed {len(transcript_paths)} file(s)', file=sys.stderr)
|
||||
"
|
||||
```
|
||||
|
||||
After transcription:
|
||||
- Read the transcript paths from `graphify-out/.graphify_transcripts.json`
|
||||
- Add them to the docs list before dispatching semantic subagents in Step 3B
|
||||
- Print how many transcripts were created: `Transcribed N video file(s) -> treating as docs`
|
||||
- If transcription fails for a file, print a warning and continue with the rest
|
||||
|
||||
**Whisper model:** Default is `base`. If the user passed `--whisper-model <name>`, `export GRAPHIFY_WHISPER_MODEL=<name>` (it must be exported, not just assigned) before running the command above.
|
||||
210
.claude/skills/graphify/references/update.md
Normal file
210
.claude/skills/graphify/references/update.md
Normal file
@ -0,0 +1,210 @@
|
||||
# graphify reference: incremental update and cluster-only
|
||||
|
||||
Load this only when the user passed `--update` or `--cluster-only`. A first-time full build never reads this file.
|
||||
|
||||
## For --update (incremental re-extraction)
|
||||
|
||||
Use when you've added or modified files since the last run. Only re-extracts changed files - saves tokens and time.
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.detect import detect_incremental, save_manifest
|
||||
from pathlib import Path
|
||||
|
||||
result = detect_incremental(Path('INPUT_PATH'))
|
||||
new_total = result.get('new_total', 0)
|
||||
print(json.dumps(result, indent=2, ensure_ascii=False))
|
||||
Path('graphify-out/.graphify_incremental.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\")
|
||||
deleted = list(result.get('deleted_files', []))
|
||||
if new_total == 0 and not deleted:
|
||||
print('No files changed since last run. Nothing to update.')
|
||||
raise SystemExit(0)
|
||||
if deleted:
|
||||
print(f'{len(deleted)} deleted file(s) to prune.')
|
||||
if new_total > 0:
|
||||
print(f'{new_total} new/changed file(s) to re-extract.')
|
||||
"
|
||||
```
|
||||
|
||||
Then populate `.graphify_detect.json` so Steps 3A–6 (which read it unconditionally) see the right state for an incremental run. `files` carries the changed subset (drives Step 3A AST + Step 3B0 cache check on only what changed); `all_files` carries the full corpus for any step that needs corpus-wide context:
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json
|
||||
from pathlib import Path
|
||||
r = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding=\"utf-8\"))
|
||||
Path('graphify-out/.graphify_detect.json').write_text(json.dumps({
|
||||
'files': r.get('new_files', {}),
|
||||
'all_files': r.get('files', {}),
|
||||
'total_files': r.get('new_total', 0),
|
||||
'total_words': r.get('total_words', 0),
|
||||
'skipped_sensitive': r.get('skipped_sensitive', []),
|
||||
'needs_graph': True,
|
||||
}, ensure_ascii=False), encoding=\"utf-8\")
|
||||
"
|
||||
```
|
||||
|
||||
If new files exist, first check whether all changed files are code files:
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
result = json.loads(open('graphify-out/.graphify_incremental.json', encoding='utf-8').read()) if Path('graphify-out/.graphify_incremental.json').exists() else {}
|
||||
code_exts = {'.py','.ts','.js','.go','.rs','.java','.cpp','.c','.rb','.swift','.kt','.cs','.scala','.php','.cc','.cxx','.hpp','.h','.kts','.lua','.toc','.f','.F','.f90','.F90','.f95','.F95','.f03','.F03','.f08','.F08'}
|
||||
new_files = result.get('new_files', {})
|
||||
all_changed = [f for files in new_files.values() for f in files]
|
||||
code_only = all(Path(f).suffix.lower() in code_exts for f in all_changed)
|
||||
print('code_only:', code_only)
|
||||
"
|
||||
```
|
||||
|
||||
If `code_only` is True: print `[graphify update] Code-only changes detected - skipping semantic extraction (no LLM needed)`, run only Step 3A (AST) on the changed files, skip Step 3B entirely (no subagents), then go straight to merge and Steps 4–8.
|
||||
|
||||
If `code_only` is False (any changed file is a doc/paper/image/video): **first, if any changed file is in `new_files['video']`, run `references/transcribe.md` (Step 2.5) on those files, then rewrite `.graphify_detect.json` to move the resulting transcript paths into `files['document']` and drop `files['video']`** — otherwise raw `.mp4/.mp3` paths are fed to semantic subagents as unreadable media (#1392). Then run the full Steps 3A–3C pipeline as normal.
|
||||
|
||||
|
||||
If no new files exist (only deletions), create an empty extraction so the merge step can prune:
|
||||
|
||||
```bash
|
||||
if [ ! -f graphify-out/.graphify_extract.json ]; then
|
||||
echo '[graphify update] Only deletions -- creating empty extraction for merge.'
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json
|
||||
from pathlib import Path
|
||||
Path('graphify-out/.graphify_extract.json').write_text(json.dumps({'nodes':[],'edges':[],'hyperedges':[],'input_tokens':0,'output_tokens':0}), encoding='utf-8')
|
||||
"
|
||||
fi
|
||||
```
|
||||
|
||||
|
||||
Then:
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json
|
||||
from pathlib import Path
|
||||
from graphify.build import build_merge
|
||||
from graphify.detect import save_manifest
|
||||
|
||||
# Load new extraction and incremental state
|
||||
new_extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
incremental = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding=\"utf-8\"))
|
||||
deleted = list(incremental.get('deleted_files', []))
|
||||
# prune_sources is ONLY for genuinely DELETED files. Changed/re-extracted files are
|
||||
# handled by build_merge's replace-on-re-extract (#1344): every source_file in
|
||||
# new_chunks is dropped from the base before merge, so old/stale nodes don't survive.
|
||||
# Do NOT add `changed` here: with root= passed, prune_set relativizes to the same base
|
||||
# as the freshly merged nodes and would DELETE the re-extracted content (#1178 is moot
|
||||
# now that replace — not the dedup pass — reconciles changed files).
|
||||
prune = list(deleted) or None
|
||||
|
||||
# Use build_merge() — reads graph.json directly without NetworkX round-trip
|
||||
# so edge direction (calls, implements, imports) is always preserved (#801).
|
||||
# Pass root= so prune_sources (absolute paths from detect_incremental) are
|
||||
# relativized to match the graph's relative source_file values; without it
|
||||
# nothing is pruned and stale nodes accumulate on every update (#1361).
|
||||
# directed=IS_DIRECTED: replace IS_DIRECTED with True if --directed was given, else
|
||||
# False. Without it a --directed --update silently rebuilds undirected and collapses
|
||||
# reciprocal A<->B edges (#1392).
|
||||
G = build_merge(
|
||||
[new_extraction],
|
||||
graph_path='graphify-out/graph.json',
|
||||
prune_sources=prune,
|
||||
root='INPUT_PATH',
|
||||
directed=IS_DIRECTED,
|
||||
)
|
||||
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
|
||||
|
||||
# Write merged result back to .graphify_extract.json so Step 4 sees the full graph
|
||||
merged_out = {
|
||||
'nodes': [{'id': n, **d} for n, d in G.nodes(data=True)],
|
||||
'edges': [
|
||||
# Explicit source/target last so they win over any stale attrs in d.
|
||||
{**{k: val for k, val in d.items() if k not in ('_src', '_tgt', 'source', 'target')},
|
||||
'source': d.get('_src', u), 'target': d.get('_tgt', v)}
|
||||
for u, v, d in G.edges(data=True)
|
||||
],
|
||||
# G.graph["hyperedges"] holds hyperedges from both existing graph.json
|
||||
# and new_extraction (build_merge combines them). Falling back to
|
||||
# new_extraction only would silently drop prior-run hyperedges (#801).
|
||||
'hyperedges': list(G.graph.get('hyperedges', [])),
|
||||
'input_tokens': new_extraction.get('input_tokens', 0),
|
||||
'output_tokens': new_extraction.get('output_tokens', 0),
|
||||
}
|
||||
Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged_out, ensure_ascii=False), encoding=\"utf-8\")
|
||||
print(f'[graphify update] Merged extraction written ({len(merged_out[\"nodes\"])} nodes, {len(merged_out[\"edges\"])} edges)')
|
||||
|
||||
# Save manifest so next --update diffs against today's state, not the
|
||||
# prior run's baseline (prevents ghost-node reports on subsequent updates).
|
||||
# root= matches the build_merge call above so the manifest keys stay relative to
|
||||
# the scan root — portable across clones/machines, so --update keeps matching
|
||||
# cached files instead of missing every one after a move (#1417).
|
||||
#
|
||||
# Only stamp semantic files (docs/papers/images) that ACTUALLY produced output
|
||||
# THIS run (new_extraction is this run's fresh extraction, read above before the
|
||||
# merge overwrote the file): a changed doc whose chunk failed must stay unstamped
|
||||
# so the next --update re-queues it, otherwise it is marked done and its content
|
||||
# is lost forever (#2015). Mirrors the library extract path
|
||||
# (cli._stamped_manifest_files + clear_semantic + scan_corpus).
|
||||
from graphify.cli import _stamped_manifest_files
|
||||
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path('INPUT_PATH'))
|
||||
# Changed semantic files dispatched this run but NOT stamped had their chunk fail
|
||||
# or be omitted; clear any stale semantic_hash so they are re-queued (#1948).
|
||||
_sem_types = ('document', 'paper', 'image')
|
||||
_dispatched = {f for t, fl in incremental.get('new_files', {}).items() if t in _sem_types for f in fl}
|
||||
_stamped = {f for fl in _manifest_files.values() for f in fl}
|
||||
_cleared = _dispatched - _stamped
|
||||
# scan_corpus = the RAW full corpus so in-root files newly excluded since last run
|
||||
# are dropped rather than masquerading as deletions; untouched rows preserved (#1908).
|
||||
_scan = {f for fl in incremental['files'].values() for f in fl}
|
||||
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
print('[graphify update] Manifest saved.')
|
||||
"
|
||||
```
|
||||
|
||||
Then run Steps 4–8 on the merged graph as normal.
|
||||
|
||||
After Step 4, show the graph diff:
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json
|
||||
from graphify.analyze import graph_diff
|
||||
from graphify.build import build_from_json
|
||||
from networkx.readwrite import json_graph
|
||||
import networkx as nx
|
||||
from pathlib import Path
|
||||
|
||||
# Load old graph (before update) from backup written before merge
|
||||
old_data = json.loads(Path('graphify-out/.graphify_old.json').read_text(encoding=\"utf-8\")) if Path('graphify-out/.graphify_old.json').exists() else None
|
||||
new_extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
G_new = build_from_json(new_extract, directed=IS_DIRECTED)
|
||||
|
||||
if old_data:
|
||||
G_old = json_graph.node_link_graph(old_data, edges='links')
|
||||
diff = graph_diff(G_old, G_new)
|
||||
print(diff['summary'])
|
||||
if diff['new_nodes']:
|
||||
print('New nodes:', ', '.join(n['label'] for n in diff['new_nodes'][:5]))
|
||||
if diff['new_edges']:
|
||||
print('New edges:', len(diff['new_edges']))
|
||||
"
|
||||
```
|
||||
|
||||
Before the merge step, save the old graph: `cp graphify-out/graph.json graphify-out/.graphify_old.json`
|
||||
Clean up after: `rm -f graphify-out/.graphify_old.json`
|
||||
|
||||
---
|
||||
|
||||
## For --cluster-only
|
||||
|
||||
Skip Steps 1–3. Re-run clustering on the existing graph:
|
||||
|
||||
```bash
|
||||
graphify cluster-only .
|
||||
```
|
||||
|
||||
`graphify cluster-only .` is **self-contained**: it re-clusters, names communities, and regenerates `GRAPH_REPORT.md`, `graph.json`, and `graph.html` from the existing graph. **Do not re-run Steps 5–9** — they read intermediate files (`.graphify_extract.json`, `.graphify_detect.json`, `.graphify_analysis.json`) that a prior build's cleanup (Step 9) already deleted, so they raise `FileNotFoundError` (#1392). When it finishes, present the refreshed `GRAPH_REPORT.md` summary as usual.
|
||||
1
.gitattributes
vendored
Normal file
1
.gitattributes
vendored
Normal file
@ -0,0 +1 @@
|
||||
graphify-out/graph.json merge=graphify
|
||||
3
AGENTS.md
Normal file
3
AGENTS.md
Normal file
@ -0,0 +1,3 @@
|
||||
# graphify
|
||||
- **graphify** (`.claude/skills/graphify/SKILL.md`) - any input to knowledge graph. Trigger: `/graphify`
|
||||
When the user types `/graphify`, use the installed graphify skill or instructions before doing anything else.
|
||||
9
CLAUDE.md
Normal file
9
CLAUDE.md
Normal file
@ -0,0 +1,9 @@
|
||||
## graphify
|
||||
|
||||
This project has a knowledge graph at graphify-out/ with god nodes, community structure, and cross-file relationships.
|
||||
|
||||
Rules:
|
||||
- For codebase questions, first run `graphify query "<question>"` when graphify-out/graph.json exists. Use `graphify path "<A>" "<B>"` for relationships and `graphify explain "<concept>"` for focused concepts. These return a scoped subgraph, usually much smaller than GRAPH_REPORT.md or raw grep output.
|
||||
- If graphify-out/wiki/index.md exists, use it for broad navigation instead of raw source browsing.
|
||||
- Read graphify-out/GRAPH_REPORT.md only for broad architecture review or when query/path/explain do not surface enough context.
|
||||
- After modifying code, run `graphify update .` to keep the graph current (AST-only, no API cost).
|
||||
@ -28,6 +28,7 @@ model User {
|
||||
blogs Blog[]
|
||||
prescriptions Prescription[]
|
||||
partnerAccount PartnerAccount?
|
||||
paymentTransactions PaymentTransaction[]
|
||||
|
||||
@@map("users")
|
||||
}
|
||||
@ -160,6 +161,7 @@ model Product {
|
||||
reminders Reminder[]
|
||||
orderItems OrderItem[]
|
||||
advisorRules SmartAdvisorRule[]
|
||||
inventoryReservations InventoryReservation[]
|
||||
|
||||
@@index([categorySlug])
|
||||
@@index([suitableFor])
|
||||
@ -315,17 +317,74 @@ model Order {
|
||||
charityDonation Decimal @default(0.00) @map("charity_donation") @db.Decimal(15, 2)
|
||||
isRefill Boolean @default(false) @map("is_refill")
|
||||
refillIntervalDays Int? @map("refill_interval_days")
|
||||
status String @default("processing") @db.VarChar(30) // processing, shipped, delivered
|
||||
status String @default("processing") @db.VarChar(30) // pending_payment, processing, shipped, delivered, cancelled
|
||||
paymentMethod String? @default("card") @map("payment_method") @db.VarChar(30)
|
||||
shippingAddress String? @map("shipping_address") @db.Text
|
||||
trackingNumber String? @unique @map("tracking_number") @db.VarChar(100)
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
coupon Coupon? @relation(fields: [couponId], references: [id])
|
||||
orderItems OrderItem[]
|
||||
paymentTransactions PaymentTransaction[]
|
||||
inventoryReservations InventoryReservation[]
|
||||
|
||||
@@map("orders")
|
||||
}
|
||||
|
||||
model PaymentTransaction {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
userId String @map("user_id") @db.Uuid
|
||||
orderId String? @map("order_id") @db.Uuid
|
||||
amount Decimal @db.Decimal(15, 2) // in Tomans
|
||||
amountRials BigInt? @map("amount_rials")
|
||||
gateway String @default("zibal") @db.VarChar(50)
|
||||
trackId String? @unique @map("track_id") @db.VarChar(100)
|
||||
refNumber String? @map("ref_number") @db.VarChar(100)
|
||||
cardNumber String? @map("card_number") @db.VarChar(30)
|
||||
hashedCardNumber String? @map("hashed_card_number") @db.VarChar(100)
|
||||
status String @default("PENDING") @db.VarChar(30) // PENDING, PAID, FAILED, VERIFIED
|
||||
resultCode Int? @map("result_code")
|
||||
message String? @db.Text
|
||||
description String? @db.Text
|
||||
type String @default("ORDER") @db.VarChar(30) // ORDER, WALLET_TOPUP
|
||||
ipAddress String? @map("ip_address") @db.VarChar(50)
|
||||
userAgent String? @map("user_agent") @db.Text
|
||||
rawRequest Json? @map("raw_request")
|
||||
rawResponse Json? @map("raw_response")
|
||||
paidAt DateTime? @map("paid_at") @db.Timestamptz()
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
|
||||
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
order Order? @relation(fields: [orderId], references: [id], onDelete: SetNull)
|
||||
|
||||
@@index([userId])
|
||||
@@index([orderId])
|
||||
@@index([trackId])
|
||||
@@map("payment_transactions")
|
||||
}
|
||||
|
||||
model InventoryReservation {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
orderId String @map("order_id") @db.Uuid
|
||||
productId String @map("product_id") @db.Uuid
|
||||
quantity Int @default(1)
|
||||
expiresAt DateTime @map("expires_at") @db.Timestamptz()
|
||||
status String @default("ACTIVE") @db.VarChar(20) // ACTIVE, CONSUMED, RELEASED
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
|
||||
|
||||
order Order @relation(fields: [orderId], references: [id], onDelete: Cascade)
|
||||
product Product @relation(fields: [productId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([orderId])
|
||||
@@index([productId])
|
||||
@@index([status])
|
||||
@@index([expiresAt])
|
||||
@@map("inventory_reservations")
|
||||
}
|
||||
|
||||
model OrderItem {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
orderId String @map("order_id") @db.Uuid
|
||||
@ -550,3 +609,23 @@ model Setting {
|
||||
@@index([category])
|
||||
@@map("settings")
|
||||
}
|
||||
|
||||
model SmsLog {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
receptor String @db.VarChar(20)
|
||||
type String @db.VarChar(50) // OTP, ORDER_CONFIRMATION, SHIPPING_TRACKING, B2B_NOTIFICATION, PET_CARE_REMINDER, TEST, GENERIC
|
||||
patternId Int? @map("pattern_id")
|
||||
args String[] @default([])
|
||||
messageText String? @map("message_text") @db.Text
|
||||
status String @db.VarChar(20) // SUCCESS, FAILED, DISABLED
|
||||
recId String? @map("rec_id") @db.VarChar(50)
|
||||
errorMessage String? @map("error_message") @db.Text
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
|
||||
@@index([receptor])
|
||||
@@index([type])
|
||||
@@index([status])
|
||||
@@index([createdAt])
|
||||
@@map("sms_logs")
|
||||
}
|
||||
|
||||
|
||||
@ -27,6 +27,9 @@ import { TestimonialsModule } from './testimonials/testimonials.module';
|
||||
import { IngredientsModule } from './ingredients/ingredients.module';
|
||||
import { PrescriptionsModule } from './prescriptions/prescriptions.module';
|
||||
import { B2BModule } from './b2b/b2b.module';
|
||||
import { PaymentModule } from './payment/payment.module';
|
||||
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@ -40,6 +43,7 @@ import { B2BModule } from './b2b/b2b.module';
|
||||
PetsModule,
|
||||
OrdersModule,
|
||||
SettingsModule,
|
||||
PaymentModule,
|
||||
ThrottlerModule.forRoot([
|
||||
{
|
||||
ttl: 60000,
|
||||
@ -75,15 +79,18 @@ export class AppModule implements NestModule {
|
||||
|
||||
configure(consumer: MiddlewareConsumer) {
|
||||
consumer
|
||||
.apply((req: any, res: any, next: () => void) => {
|
||||
.apply((req: Request, res: Response, next: NextFunction) => {
|
||||
MetricsController.incrementRequestCount();
|
||||
|
||||
const url: string = req.originalUrl || req.url || '';
|
||||
const method: string = req.method || '';
|
||||
|
||||
// Exclude options, admin panel requests, static assets, and health metrics from visit counter
|
||||
const isAdminPath = url.includes('/admin') || url.includes('/api/admin');
|
||||
const isStaticAsset = url.match(/\.(js|css|png|jpg|jpeg|gif|ico|svg|woff2?|map)$/i);
|
||||
const isAdminPath =
|
||||
url.includes('/admin') || url.includes('/api/admin');
|
||||
const isStaticAsset = url.match(
|
||||
/\.(js|css|png|jpg|jpeg|gif|ico|svg|woff2?|map)$/i,
|
||||
);
|
||||
const isIgnoredMethod = method === 'OPTIONS' || method === 'HEAD';
|
||||
|
||||
if (!isAdminPath && !isStaticAsset && !isIgnoredMethod) {
|
||||
|
||||
@ -43,7 +43,17 @@ export class AuthService {
|
||||
await this.redisService.set(`otp:${phoneNumber}`, code, 120);
|
||||
|
||||
// Dispatch OTP via MeliPayamak Pattern SMS
|
||||
await this.smsService.sendOtp(phoneNumber, code);
|
||||
const smsSent = await this.smsService.sendOtp(phoneNumber, code);
|
||||
|
||||
if (!smsSent) {
|
||||
// Remove OTP from Redis if SMS failed to avoid phantom codes
|
||||
await this.redisService.del(`otp:${phoneNumber}`);
|
||||
throw new BadRequestException({
|
||||
message:
|
||||
'ارسال پیامک با خطا مواجه شد. لطفاً چند لحظه دیگر دوباره تلاش کنید.',
|
||||
error: 'SMS_DELIVERY_FAILED',
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
|
||||
@ -1,38 +1,646 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import * as https from 'https';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import { Prisma } from '@prisma/client';
|
||||
|
||||
export interface SendPatternSmsOptions {
|
||||
to: string;
|
||||
bodyId: number; // MeliPayamak Shared Pattern Body ID
|
||||
args: string[]; // Dynamic variables inside pattern
|
||||
type?: string; // OTP, ORDER_CONFIRMATION, SHIPPING_TRACKING, B2B_NOTIFICATION, PET_CARE_REMINDER, TEST, GENERIC
|
||||
}
|
||||
|
||||
interface MeliPayamakResponse {
|
||||
export interface SmsConfig {
|
||||
enabled: boolean;
|
||||
username: string;
|
||||
password: string;
|
||||
fromNumber?: string;
|
||||
otpBodyId: number;
|
||||
orderBodyId: number;
|
||||
shippingBodyId: number;
|
||||
b2bBodyId: number;
|
||||
petCareBodyId: number;
|
||||
}
|
||||
|
||||
export interface MeliPayamakPattern {
|
||||
id: number;
|
||||
title: string;
|
||||
body: string;
|
||||
status: number; // 0 = Pending, 1 = Approved, 2 = Needs Edit
|
||||
statusText?: string;
|
||||
assignedTo?: string[];
|
||||
}
|
||||
|
||||
export class SmsLogQuery {
|
||||
page?: number;
|
||||
limit?: number;
|
||||
search?: string;
|
||||
type?: string;
|
||||
status?: string;
|
||||
sortBy?: string;
|
||||
sortOrder?: 'asc' | 'desc';
|
||||
}
|
||||
|
||||
export interface MeliPayamakResponse {
|
||||
Value?: number;
|
||||
RetStatus?: number;
|
||||
StrRetStatus?: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class SmsService {
|
||||
private readonly logger = new Logger(SmsService.name);
|
||||
private readonly username = process.env.MELIPAYAMAK_USERNAME || '9364100228';
|
||||
private readonly password = process.env.MELIPAYAMAK_PASSWORD || '';
|
||||
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
/**
|
||||
* Get active SMS configuration from database (fallback to .env)
|
||||
*/
|
||||
async getSmsConfig(): Promise<SmsConfig> {
|
||||
try {
|
||||
const setting = await this.prisma.setting.findFirst({
|
||||
where: { category: 'sms' },
|
||||
});
|
||||
const dbConfig = (setting?.value as Record<string, unknown>) || {};
|
||||
|
||||
return {
|
||||
enabled:
|
||||
dbConfig.enabled !== undefined ? Boolean(dbConfig.enabled) : true,
|
||||
username:
|
||||
typeof dbConfig.username === 'string' && dbConfig.username
|
||||
? dbConfig.username
|
||||
: process.env.MELIPAYAMAK_USERNAME || '9364100228',
|
||||
password:
|
||||
typeof dbConfig.password === 'string' && dbConfig.password
|
||||
? dbConfig.password
|
||||
: process.env.MELIPAYAMAK_PASSWORD || '',
|
||||
fromNumber:
|
||||
typeof dbConfig.fromNumber === 'string' && dbConfig.fromNumber
|
||||
? dbConfig.fromNumber
|
||||
: process.env.MELIPAYAMAK_FROM_NUMBER || '',
|
||||
otpBodyId: Number(
|
||||
dbConfig.otpBodyId || process.env.MELIPAYAMAK_OTP_BODY_ID || '508079',
|
||||
),
|
||||
orderBodyId: Number(
|
||||
dbConfig.orderBodyId ||
|
||||
process.env.MELIPAYAMAK_ORDER_BODY_ID ||
|
||||
'508081',
|
||||
),
|
||||
shippingBodyId: Number(
|
||||
dbConfig.shippingBodyId ||
|
||||
process.env.MELIPAYAMAK_SHIPPING_BODY_ID ||
|
||||
'508082',
|
||||
),
|
||||
b2bBodyId: Number(
|
||||
dbConfig.b2bBodyId || process.env.MELIPAYAMAK_B2B_BODY_ID || '508083',
|
||||
),
|
||||
petCareBodyId: Number(
|
||||
dbConfig.petCareBodyId ||
|
||||
process.env.MELIPAYAMAK_PET_CARE_BODY_ID ||
|
||||
'0',
|
||||
),
|
||||
};
|
||||
} catch {
|
||||
return {
|
||||
enabled: true,
|
||||
username: process.env.MELIPAYAMAK_USERNAME || '9364100228',
|
||||
password: process.env.MELIPAYAMAK_PASSWORD || '',
|
||||
fromNumber: process.env.MELIPAYAMAK_FROM_NUMBER || '',
|
||||
otpBodyId: Number(process.env.MELIPAYAMAK_OTP_BODY_ID || '508079'),
|
||||
orderBodyId: Number(process.env.MELIPAYAMAK_ORDER_BODY_ID || '508081'),
|
||||
shippingBodyId: Number(
|
||||
process.env.MELIPAYAMAK_SHIPPING_BODY_ID || '508082',
|
||||
),
|
||||
b2bBodyId: Number(process.env.MELIPAYAMAK_B2B_BODY_ID || '508083'),
|
||||
petCareBodyId: Number(process.env.MELIPAYAMAK_PET_CARE_BODY_ID || '0'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper HTTP POST request to Payamak-Panel ASMX endpoints
|
||||
*/
|
||||
private async postAsmx(
|
||||
endpoint: string,
|
||||
params: Record<string, string | number>,
|
||||
): Promise<string> {
|
||||
const postData = Object.entries(params)
|
||||
.map(
|
||||
([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`,
|
||||
)
|
||||
.join('&');
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = https.request(
|
||||
`https://api.payamak-panel.com/post/SharedService.asmx/${endpoint}`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'Content-Length': Buffer.byteLength(postData),
|
||||
},
|
||||
},
|
||||
(res) => {
|
||||
let data = '';
|
||||
res.on('data', (chunk: Buffer | string) => (data += String(chunk)));
|
||||
res.on('end', () => resolve(data));
|
||||
},
|
||||
);
|
||||
|
||||
req.on('error', (err: Error) => reject(err));
|
||||
req.write(postData);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to write an SMS Log to PostgreSQL safely
|
||||
*/
|
||||
private async recordLog(entry: {
|
||||
receptor: string;
|
||||
type: string;
|
||||
patternId?: number;
|
||||
args?: string[];
|
||||
messageText?: string;
|
||||
status: string;
|
||||
recId?: string;
|
||||
errorMessage?: string;
|
||||
}): Promise<void> {
|
||||
try {
|
||||
await this.prisma.smsLog.create({
|
||||
data: {
|
||||
receptor: entry.receptor,
|
||||
type: entry.type || 'GENERIC',
|
||||
patternId: entry.patternId || null,
|
||||
args: entry.args || [],
|
||||
messageText: entry.messageText || null,
|
||||
status: entry.status,
|
||||
recId: entry.recId ? String(entry.recId) : null,
|
||||
errorMessage: entry.errorMessage || null,
|
||||
},
|
||||
});
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
this.logger.error(`[SMS Log Save Failed]: ${msg}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Query paginated SMS Logs with Search, Filter and Sorting
|
||||
*/
|
||||
async getSmsLogs(query: SmsLogQuery = {}) {
|
||||
const page = Math.max(1, Number(query.page) || 1);
|
||||
const limit = Math.max(1, Math.min(100, Number(query.limit) || 15));
|
||||
const skip = (page - 1) * limit;
|
||||
|
||||
const where: Prisma.SmsLogWhereInput = {};
|
||||
|
||||
if (query.search) {
|
||||
const s = query.search.trim();
|
||||
where.OR = [
|
||||
{ receptor: { contains: s, mode: 'insensitive' } },
|
||||
{ recId: { contains: s, mode: 'insensitive' } },
|
||||
{ errorMessage: { contains: s, mode: 'insensitive' } },
|
||||
];
|
||||
}
|
||||
|
||||
if (query.type && query.type !== 'ALL') {
|
||||
where.type = query.type;
|
||||
}
|
||||
|
||||
if (query.status && query.status !== 'ALL') {
|
||||
where.status = query.status;
|
||||
}
|
||||
|
||||
const sortField = query.sortBy || 'createdAt';
|
||||
const sortOrder = query.sortOrder === 'asc' ? 'asc' : 'desc';
|
||||
|
||||
const [logs, total, totalSuccess, totalFailed] = await Promise.all([
|
||||
this.prisma.smsLog.findMany({
|
||||
where,
|
||||
skip,
|
||||
take: limit,
|
||||
orderBy: { [sortField]: sortOrder },
|
||||
}),
|
||||
this.prisma.smsLog.count({ where }),
|
||||
this.prisma.smsLog.count({ where: { status: 'SUCCESS' } }),
|
||||
this.prisma.smsLog.count({ where: { status: 'FAILED' } }),
|
||||
]);
|
||||
|
||||
return {
|
||||
logs,
|
||||
total,
|
||||
page,
|
||||
limit,
|
||||
totalPages: Math.ceil(total / limit),
|
||||
stats: {
|
||||
total,
|
||||
success: totalSuccess,
|
||||
failed: totalFailed,
|
||||
successRate: total > 0 ? Math.round((totalSuccess / total) * 100) : 100,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete specific SMS log entry
|
||||
*/
|
||||
async deleteSmsLog(id: string) {
|
||||
return this.prisma.smsLog.delete({ where: { id } });
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all SMS logs
|
||||
*/
|
||||
async clearAllSmsLogs() {
|
||||
return this.prisma.smsLog.deleteMany();
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse XML response for GetSharedServiceBody into structured pattern array
|
||||
*/
|
||||
private parsePatternsXml(xml: string): MeliPayamakPattern[] {
|
||||
const patterns: MeliPayamakPattern[] = [];
|
||||
const itemRegex = /<SharedServiceBody>([\s\S]*?)<\/SharedServiceBody>/gi;
|
||||
let match: RegExpExecArray | null;
|
||||
|
||||
while ((match = itemRegex.exec(xml)) !== null) {
|
||||
const block = match[1];
|
||||
const idMatch = block.match(/<Id>(\d+)<\/Id>/i);
|
||||
const titleMatch = block.match(/<Title>([\s\S]*?)<\/Title>/i);
|
||||
const bodyMatch = block.match(/<Body>([\s\S]*?)<\/Body>/i);
|
||||
const statusMatch = block.match(/<Status>(-?\d+)<\/Status>/i);
|
||||
|
||||
if (idMatch) {
|
||||
const id = parseInt(idMatch[1], 10);
|
||||
const title = (titleMatch ? titleMatch[1] : '')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/&/g, '&');
|
||||
const body = (bodyMatch ? bodyMatch[1] : '')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/&/g, '&');
|
||||
const status = statusMatch ? parseInt(statusMatch[1], 10) : 0;
|
||||
|
||||
let statusText = 'در انتظار تایید';
|
||||
if (status === 1) statusText = 'تایید شده';
|
||||
else if (status === 2 || status === -1) statusText = 'نیاز به ویرایش';
|
||||
|
||||
patterns.push({ id, title, body, status, statusText });
|
||||
}
|
||||
}
|
||||
|
||||
return patterns;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch all registered patterns from MeliPayamak (with local cache sync)
|
||||
*/
|
||||
async getPatterns(): Promise<MeliPayamakPattern[]> {
|
||||
const config = await this.getSmsConfig();
|
||||
|
||||
let remotePatterns: MeliPayamakPattern[] = [];
|
||||
if (config.username && config.password) {
|
||||
try {
|
||||
const rawXml = await this.postAsmx('GetSharedServiceBody', {
|
||||
username: config.username,
|
||||
password: config.password,
|
||||
});
|
||||
remotePatterns = this.parsePatternsXml(rawXml);
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
this.logger.warn(
|
||||
`[SMS Patterns] Remote fetch failed: ${msg}. Using stored patterns.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Load local stored patterns from settings table
|
||||
const storedSetting = await this.prisma.setting.findFirst({
|
||||
where: { category: 'sms_patterns' },
|
||||
});
|
||||
const localPatterns: MeliPayamakPattern[] = Array.isArray(
|
||||
storedSetting?.value,
|
||||
)
|
||||
? (storedSetting.value as unknown as MeliPayamakPattern[])
|
||||
: [];
|
||||
|
||||
// Merge remote and local (remote takes precedence on ID match)
|
||||
const map = new Map<number, MeliPayamakPattern>();
|
||||
|
||||
// Add configured system patterns by default if map is empty
|
||||
const defaultConfigs: Array<{
|
||||
id: number;
|
||||
title: string;
|
||||
body: string;
|
||||
assigned: string;
|
||||
}> = [
|
||||
{
|
||||
id: config.otpBodyId,
|
||||
title: 'کد تایید ورود و ثبتنام (OTP)',
|
||||
body: 'کد ورود به کانینا: {0}',
|
||||
assigned: 'otp',
|
||||
},
|
||||
{
|
||||
id: config.orderBodyId,
|
||||
title: 'تایید و ثبت فاکتور سفارش',
|
||||
body: 'سفارش شما به شماره {0} با مبلغ {1} ثبت گردید.',
|
||||
assigned: 'order',
|
||||
},
|
||||
{
|
||||
id: config.shippingBodyId,
|
||||
title: 'ارسال کد رهگیری پستی',
|
||||
body: 'مرسوله سفارش {0} با کد رهگیری پستی {1} ارسال شد.',
|
||||
assigned: 'shipping',
|
||||
},
|
||||
{
|
||||
id: config.b2bBodyId,
|
||||
title: 'اطلاعرسانی درخواست B2B',
|
||||
body: 'همکار گرامی {0} درخواست شما دریافت شد.',
|
||||
assigned: 'b2b',
|
||||
},
|
||||
];
|
||||
|
||||
for (const d of defaultConfigs) {
|
||||
if (d.id > 0) {
|
||||
map.set(d.id, {
|
||||
id: d.id,
|
||||
title: d.title,
|
||||
body: d.body,
|
||||
status: 1,
|
||||
statusText: 'تایید شده',
|
||||
assignedTo: [d.assigned],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for (const lp of localPatterns) {
|
||||
if (lp && lp.id) map.set(lp.id, { ...lp });
|
||||
}
|
||||
|
||||
for (const rp of remotePatterns) {
|
||||
const existing = map.get(rp.id);
|
||||
map.set(rp.id, {
|
||||
...rp,
|
||||
assignedTo: existing?.assignedTo || [],
|
||||
});
|
||||
}
|
||||
|
||||
// Mark current bindings
|
||||
const result = Array.from(map.values()).map((p) => {
|
||||
const assigned: string[] = [];
|
||||
if (p.id === config.otpBodyId) assigned.push('کد تایید OTP');
|
||||
if (p.id === config.orderBodyId) assigned.push('تایید سفارش');
|
||||
if (p.id === config.shippingBodyId) assigned.push('کد رهگیری پست');
|
||||
if (p.id === config.b2bBodyId) assigned.push('همکاران B2B');
|
||||
if (p.id === config.petCareBodyId) assigned.push('یادآور سلامت پت');
|
||||
return { ...p, assignedTo: assigned };
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a new pattern to MeliPayamak
|
||||
*/
|
||||
async addPattern(
|
||||
title: string,
|
||||
body: string,
|
||||
blackListId: number = 0,
|
||||
): Promise<{ success: boolean; bodyId?: number; message: string }> {
|
||||
const config = await this.getSmsConfig();
|
||||
|
||||
if (!config.username || !config.password) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'مشخصات نام کاربری و رمز عبور سامانه پیامک تنظیم نشده است.',
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const rawXml = await this.postAsmx('SharedServiceBodyAdd', {
|
||||
username: config.username,
|
||||
password: config.password,
|
||||
title,
|
||||
body,
|
||||
blackListId,
|
||||
});
|
||||
|
||||
const match =
|
||||
rawXml.match(/<int.*?>(-?\d+)<\/int>/i) || rawXml.match(/>(-?\d+)</);
|
||||
const code = match ? parseInt(match[1], 10) : 0;
|
||||
|
||||
if (code > 0) {
|
||||
await this.saveLocalPattern({
|
||||
id: code,
|
||||
title,
|
||||
body,
|
||||
status: 0,
|
||||
statusText: 'در انتظار تایید',
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
bodyId: code,
|
||||
message: `الگو با موفقیت ثبت شد و شناسه اختصاصی ${code} دریافت گردید. (وضعیت: در انتظار تایید ناظر)`,
|
||||
};
|
||||
} else if (code === 0) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'نام کاربری یا کلمه عبور ملی پیامک اشتباه است.',
|
||||
};
|
||||
} else if (code === -2) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'شناسه لیست سیاه ویژه اشتباه است.',
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
success: false,
|
||||
message: `خطا در ثبت پترن با کد پاسخ: ${code}`,
|
||||
};
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
const generatedId = Math.floor(500000 + Math.random() * 90000);
|
||||
await this.saveLocalPattern({
|
||||
id: generatedId,
|
||||
title,
|
||||
body,
|
||||
status: 0,
|
||||
statusText: 'ثبت محلی (در انتظار اتصال سرور)',
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
bodyId: generatedId,
|
||||
message: `الگو به صورت محلی با شناسه موقت ${generatedId} ذخیره شد (${msg}).`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit an existing pattern in MeliPayamak
|
||||
*/
|
||||
async editPattern(
|
||||
bodyId: number,
|
||||
body: string,
|
||||
): Promise<{ success: boolean; message: string }> {
|
||||
const config = await this.getSmsConfig();
|
||||
|
||||
if (!config.username || !config.password) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'مشخصات نام کاربری و رمز عبور سامانه پیامک تنظیم نشده است.',
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const rawXml = await this.postAsmx('SharedServiceBodyEdit', {
|
||||
username: config.username,
|
||||
password: config.password,
|
||||
bodyId,
|
||||
body,
|
||||
});
|
||||
|
||||
const match =
|
||||
rawXml.match(/<int.*?>(-?\d+)<\/int>/i) || rawXml.match(/>(-?\d+)</);
|
||||
const code = match ? parseInt(match[1], 10) : 0;
|
||||
|
||||
if (code === 1) {
|
||||
await this.updateLocalPattern(bodyId, body);
|
||||
return {
|
||||
success: true,
|
||||
message:
|
||||
'ویرایش الگو با موفقیت انجام شد و منتظر تایید مجدد ناظر میباشد.',
|
||||
};
|
||||
} else if (code === -1) {
|
||||
await this.updateLocalPattern(bodyId, body);
|
||||
return {
|
||||
success: true,
|
||||
message:
|
||||
'متن الگو در سیستم بروز شد (توجه: فقط الگوهای در وضعیت نیاز به ویرایش در وبسرویس اصلاح میشوند).',
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
success: false,
|
||||
message: `خطا در ویرایش الگو با کد پاسخ: ${code}`,
|
||||
};
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
await this.updateLocalPattern(bodyId, body);
|
||||
return {
|
||||
success: true,
|
||||
message: `متن الگو در دیتابیس داخلی بروز شد (${msg}).`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private async saveLocalPattern(pattern: MeliPayamakPattern) {
|
||||
try {
|
||||
const setting = await this.prisma.setting.findFirst({
|
||||
where: { category: 'sms_patterns' },
|
||||
});
|
||||
const list: MeliPayamakPattern[] = Array.isArray(setting?.value)
|
||||
? (setting.value as unknown as MeliPayamakPattern[])
|
||||
: [];
|
||||
const updated = [pattern, ...list.filter((p) => p.id !== pattern.id)];
|
||||
|
||||
await this.prisma.setting.upsert({
|
||||
where: { key: 'sms_patterns_config' },
|
||||
update: {
|
||||
category: 'sms_patterns',
|
||||
value: updated as unknown as Prisma.InputJsonValue,
|
||||
},
|
||||
create: {
|
||||
key: 'sms_patterns_config',
|
||||
category: 'sms_patterns',
|
||||
value: updated as unknown as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
this.logger.error(`Failed to save local pattern: ${msg}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async updateLocalPattern(bodyId: number, newBody: string) {
|
||||
try {
|
||||
const setting = await this.prisma.setting.findFirst({
|
||||
where: { category: 'sms_patterns' },
|
||||
});
|
||||
const list: MeliPayamakPattern[] = Array.isArray(setting?.value)
|
||||
? (setting.value as unknown as MeliPayamakPattern[])
|
||||
: [];
|
||||
const updated = list.map((p) =>
|
||||
p.id === bodyId
|
||||
? {
|
||||
...p,
|
||||
body: newBody,
|
||||
status: 0,
|
||||
statusText: 'در انتظار تایید',
|
||||
}
|
||||
: p,
|
||||
);
|
||||
|
||||
await this.prisma.setting.upsert({
|
||||
where: { key: 'sms_patterns_config' },
|
||||
update: {
|
||||
category: 'sms_patterns',
|
||||
value: updated as unknown as Prisma.InputJsonValue,
|
||||
},
|
||||
create: {
|
||||
key: 'sms_patterns_config',
|
||||
category: 'sms_patterns',
|
||||
value: updated as unknown as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
this.logger.error(`Failed to update local pattern: ${msg}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send Pattern SMS using MeliPayamak Shared Service Line (Bypasses Blacklist)
|
||||
*/
|
||||
async sendPatternSms(options: SendPatternSmsOptions): Promise<boolean> {
|
||||
if (!this.username || !this.password) {
|
||||
this.logger.warn(
|
||||
`[SMS Simulated] MeliPayamak dispatch to ${options.to} (Pattern: ${options.bodyId}, Args: ${options.args.join(', ')})`,
|
||||
);
|
||||
return true;
|
||||
const config = await this.getSmsConfig();
|
||||
const msgType = options.type || 'GENERIC_PATTERN';
|
||||
|
||||
if (!config.enabled) {
|
||||
this.logger.warn(`[SMS Disabled] SMS dispatch skipped for ${options.to}`);
|
||||
await this.recordLog({
|
||||
receptor: options.to,
|
||||
type: msgType,
|
||||
patternId: options.bodyId,
|
||||
args: options.args,
|
||||
status: 'DISABLED',
|
||||
errorMessage: 'ارسال پیامک از پنل ادمین غیرفعال شده است.',
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!config.username || !config.password) {
|
||||
const err = 'مشخصات نام کاربری و رمز عبور سامانه پیامک تنظیم نشده است.';
|
||||
this.logger.error(`[SMS MISCONFIGURED] ${err}`);
|
||||
await this.recordLog({
|
||||
receptor: options.to,
|
||||
type: msgType,
|
||||
patternId: options.bodyId,
|
||||
args: options.args,
|
||||
status: 'FAILED',
|
||||
errorMessage: err,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const payload = JSON.stringify({
|
||||
username: this.username,
|
||||
password: this.password,
|
||||
username: config.username,
|
||||
password: config.password,
|
||||
text: options.args.join(';'),
|
||||
to: options.to,
|
||||
bodyId: options.bodyId,
|
||||
@ -49,8 +657,9 @@ export class SmsService {
|
||||
},
|
||||
(res) => {
|
||||
let data = '';
|
||||
res.on('data', (chunk) => (data += chunk));
|
||||
res.on('data', (chunk: Buffer | string) => (data += String(chunk)));
|
||||
res.on('end', () => {
|
||||
void (async () => {
|
||||
try {
|
||||
const json = JSON.parse(data) as MeliPayamakResponse;
|
||||
const val = json.Value ?? 0;
|
||||
@ -58,25 +667,63 @@ export class SmsService {
|
||||
this.logger.log(
|
||||
`[SMS Sent] Pattern SMS ${options.bodyId} dispatched to ${options.to} (RecId: ${val})`,
|
||||
);
|
||||
await this.recordLog({
|
||||
receptor: options.to,
|
||||
type: msgType,
|
||||
patternId: options.bodyId,
|
||||
args: options.args,
|
||||
status: 'SUCCESS',
|
||||
recId: String(val),
|
||||
});
|
||||
resolve(true);
|
||||
} else {
|
||||
const errMsg = `خطای درگاه ملی پیامک با کد بازگشتی: ${val}`;
|
||||
this.logger.error(
|
||||
`[SMS Error] Failed sending pattern SMS to ${options.to}. Code: ${val}`,
|
||||
`[SMS Error] Failed sending to ${options.to}. Code: ${val}`,
|
||||
);
|
||||
await this.recordLog({
|
||||
receptor: options.to,
|
||||
type: msgType,
|
||||
patternId: options.bodyId,
|
||||
args: options.args,
|
||||
status: 'FAILED',
|
||||
recId: String(val),
|
||||
errorMessage: errMsg,
|
||||
});
|
||||
resolve(false);
|
||||
}
|
||||
} catch {
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
await this.recordLog({
|
||||
receptor: options.to,
|
||||
type: msgType,
|
||||
patternId: options.bodyId,
|
||||
args: options.args,
|
||||
status: 'FAILED',
|
||||
errorMessage: `خطای پارس پاسخ سرور: ${data || msg}`,
|
||||
});
|
||||
resolve(false);
|
||||
}
|
||||
})();
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
req.on('error', (err) => {
|
||||
req.on('error', (err: Error) => {
|
||||
void (async () => {
|
||||
this.logger.error(
|
||||
`[SMS Exception] MeliPayamak HTTP Error: ${err.message}`,
|
||||
);
|
||||
await this.recordLog({
|
||||
receptor: options.to,
|
||||
type: msgType,
|
||||
patternId: options.bodyId,
|
||||
args: options.args,
|
||||
status: 'FAILED',
|
||||
errorMessage: `خطای شبکه: ${err.message}`,
|
||||
});
|
||||
resolve(false);
|
||||
})();
|
||||
});
|
||||
|
||||
req.write(payload);
|
||||
@ -85,73 +732,190 @@ export class SmsService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Send OTP Verification Code (Pattern 508079)
|
||||
* Test SMS Dispatch from Admin Panel
|
||||
*/
|
||||
async sendOtp(phone: string, otpCode: string): Promise<boolean> {
|
||||
const bodyId = parseInt(
|
||||
process.env.MELIPAYAMAK_OTP_BODY_ID || '508079',
|
||||
10,
|
||||
async testSms(
|
||||
targetPhone: string,
|
||||
testPatternId?: number,
|
||||
testArgs?: string[],
|
||||
): Promise<{
|
||||
success: boolean;
|
||||
message: string;
|
||||
rawResponse?: MeliPayamakResponse;
|
||||
}> {
|
||||
const config = await this.getSmsConfig();
|
||||
|
||||
if (!config.username || !config.password) {
|
||||
const msg = 'نام کاربری یا رمز عبور سامانه ملی پیامک تنظیم نشده است.';
|
||||
await this.recordLog({
|
||||
receptor: targetPhone,
|
||||
type: 'TEST',
|
||||
patternId: testPatternId,
|
||||
args: testArgs,
|
||||
status: 'FAILED',
|
||||
errorMessage: msg,
|
||||
});
|
||||
return { success: false, message: msg };
|
||||
}
|
||||
|
||||
const bodyId = testPatternId || config.otpBodyId || 508079;
|
||||
const args = testArgs && testArgs.length > 0 ? testArgs : ['123456'];
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const payload = JSON.stringify({
|
||||
username: config.username,
|
||||
password: config.password,
|
||||
text: args.join(';'),
|
||||
to: targetPhone,
|
||||
bodyId: bodyId,
|
||||
});
|
||||
|
||||
const req = https.request(
|
||||
'https://rest.payamak-panel.com/api/SendSMS/BaseServiceNumber',
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Length': Buffer.byteLength(payload),
|
||||
},
|
||||
},
|
||||
(res) => {
|
||||
let data = '';
|
||||
res.on('data', (chunk: Buffer | string) => (data += String(chunk)));
|
||||
res.on('end', () => {
|
||||
void (async () => {
|
||||
try {
|
||||
const json = JSON.parse(data) as MeliPayamakResponse;
|
||||
const val = json.Value ?? 0;
|
||||
if (json && (val > 15 || json.RetStatus === 1)) {
|
||||
await this.recordLog({
|
||||
receptor: targetPhone,
|
||||
type: 'TEST',
|
||||
patternId: bodyId,
|
||||
args,
|
||||
status: 'SUCCESS',
|
||||
recId: String(val),
|
||||
});
|
||||
resolve({
|
||||
success: true,
|
||||
message: `پیامک تستی پترن با موفقیت ارسال شد (شناسه پیگیری ملی پیامک: ${val})`,
|
||||
rawResponse: json,
|
||||
});
|
||||
} else {
|
||||
const errMsg = `خطای درگاه ملی پیامک: کد پاسخ بازگشتی ${val}`;
|
||||
await this.recordLog({
|
||||
receptor: targetPhone,
|
||||
type: 'TEST',
|
||||
patternId: bodyId,
|
||||
args,
|
||||
status: 'FAILED',
|
||||
recId: String(val),
|
||||
errorMessage: errMsg,
|
||||
});
|
||||
resolve({
|
||||
success: false,
|
||||
message: errMsg,
|
||||
rawResponse: json,
|
||||
});
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
const errMsg = `پاسخ نامعتبر از سرور ملی پیامک: ${data || msg}`;
|
||||
await this.recordLog({
|
||||
receptor: targetPhone,
|
||||
type: 'TEST',
|
||||
patternId: bodyId,
|
||||
args,
|
||||
status: 'FAILED',
|
||||
errorMessage: errMsg,
|
||||
});
|
||||
resolve({ success: false, message: errMsg });
|
||||
}
|
||||
})();
|
||||
});
|
||||
},
|
||||
);
|
||||
return this.sendPatternSms({
|
||||
to: phone,
|
||||
bodyId,
|
||||
args: [otpCode],
|
||||
|
||||
req.on('error', (err: Error) => {
|
||||
void (async () => {
|
||||
const errMsg = `خطای برقراری ارتباط با وبسرویس ملی پیامک: ${err.message}`;
|
||||
await this.recordLog({
|
||||
receptor: targetPhone,
|
||||
type: 'TEST',
|
||||
patternId: bodyId,
|
||||
args,
|
||||
status: 'FAILED',
|
||||
errorMessage: errMsg,
|
||||
});
|
||||
resolve({ success: false, message: errMsg });
|
||||
})();
|
||||
});
|
||||
|
||||
req.write(payload);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Send Order Confirmation SMS (Pattern 508081)
|
||||
* Send OTP Verification Code
|
||||
*/
|
||||
async sendOtp(phone: string, otpCode: string): Promise<boolean> {
|
||||
const config = await this.getSmsConfig();
|
||||
return this.sendPatternSms({
|
||||
to: phone,
|
||||
bodyId: config.otpBodyId,
|
||||
args: [otpCode],
|
||||
type: 'OTP',
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Send Order Confirmation SMS
|
||||
*/
|
||||
async sendOrderConfirmation(
|
||||
phone: string,
|
||||
orderNumber: string,
|
||||
amount: string,
|
||||
): Promise<boolean> {
|
||||
const bodyId = parseInt(
|
||||
process.env.MELIPAYAMAK_ORDER_BODY_ID || '508081',
|
||||
10,
|
||||
);
|
||||
const config = await this.getSmsConfig();
|
||||
return this.sendPatternSms({
|
||||
to: phone,
|
||||
bodyId,
|
||||
bodyId: config.orderBodyId,
|
||||
args: [orderNumber, amount],
|
||||
type: 'ORDER_CONFIRMATION',
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Send Shipping Status SMS with Tracking Code (Pattern 508082)
|
||||
* Send Shipping Status SMS with Tracking Code
|
||||
*/
|
||||
async sendShippingNotification(
|
||||
phone: string,
|
||||
orderNumber: string,
|
||||
trackingCode: string,
|
||||
): Promise<boolean> {
|
||||
const bodyId = parseInt(
|
||||
process.env.MELIPAYAMAK_SHIPPING_BODY_ID || '508082',
|
||||
10,
|
||||
);
|
||||
const config = await this.getSmsConfig();
|
||||
return this.sendPatternSms({
|
||||
to: phone,
|
||||
bodyId,
|
||||
bodyId: config.shippingBodyId,
|
||||
args: [orderNumber, trackingCode],
|
||||
type: 'SHIPPING_TRACKING',
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Send B2B Application Notification SMS (Pattern 508083)
|
||||
* Send B2B Application Notification SMS
|
||||
*/
|
||||
async sendB2bNotification(
|
||||
phone: string,
|
||||
applicantName: string,
|
||||
): Promise<boolean> {
|
||||
const bodyId = parseInt(
|
||||
process.env.MELIPAYAMAK_B2B_BODY_ID || '508083',
|
||||
10,
|
||||
);
|
||||
const config = await this.getSmsConfig();
|
||||
return this.sendPatternSms({
|
||||
to: phone,
|
||||
bodyId,
|
||||
bodyId: config.b2bBodyId,
|
||||
args: [applicantName],
|
||||
type: 'B2B_NOTIFICATION',
|
||||
});
|
||||
}
|
||||
|
||||
@ -163,14 +927,13 @@ export class SmsService {
|
||||
petName: string,
|
||||
reminderType: string,
|
||||
): Promise<boolean> {
|
||||
const bodyId = parseInt(
|
||||
process.env.MELIPAYAMAK_PET_CARE_BODY_ID || '0',
|
||||
10,
|
||||
);
|
||||
const config = await this.getSmsConfig();
|
||||
if (!config.petCareBodyId) return false;
|
||||
return this.sendPatternSms({
|
||||
to: phone,
|
||||
bodyId,
|
||||
bodyId: config.petCareBodyId,
|
||||
args: [petName, reminderType],
|
||||
type: 'PET_CARE_REMINDER',
|
||||
});
|
||||
}
|
||||
|
||||
@ -178,7 +941,24 @@ export class SmsService {
|
||||
* Generic text SMS dispatch
|
||||
*/
|
||||
async sendSms(phone: string, message: string): Promise<boolean> {
|
||||
const config = await this.getSmsConfig();
|
||||
if (!config.enabled) {
|
||||
await this.recordLog({
|
||||
receptor: phone,
|
||||
type: 'GENERIC_TEXT',
|
||||
messageText: message,
|
||||
status: 'DISABLED',
|
||||
errorMessage: 'ارسال پیامک غیرفعال است.',
|
||||
});
|
||||
return false;
|
||||
}
|
||||
this.logger.log(`[SMS Text Sent] To: ${phone}, Content: ${message}`);
|
||||
await this.recordLog({
|
||||
receptor: phone,
|
||||
type: 'GENERIC_TEXT',
|
||||
messageText: message,
|
||||
status: 'SUCCESS',
|
||||
});
|
||||
return Promise.resolve(true);
|
||||
}
|
||||
}
|
||||
|
||||
@ -227,6 +227,8 @@ export class OrdersService {
|
||||
refillIntervalDays: createOrderDto.refillIntervalDays || 60,
|
||||
trackingNumber,
|
||||
status: 'processing',
|
||||
paymentMethod: 'wallet',
|
||||
shippingAddress: createOrderDto.shippingAddress,
|
||||
orderItems: {
|
||||
create: orderItemsData,
|
||||
},
|
||||
@ -240,6 +242,10 @@ export class OrdersService {
|
||||
});
|
||||
}
|
||||
|
||||
const isOnline = createOrderDto.paymentMethod === 'online';
|
||||
const initialStatus = isOnline ? 'pending_payment' : 'processing';
|
||||
const reservationExpiry = new Date(Date.now() + 15 * 60 * 1000); // 15 minutes hold
|
||||
|
||||
const createdOrder = await this.prisma.order.create({
|
||||
data: {
|
||||
userId,
|
||||
@ -249,20 +255,31 @@ export class OrdersService {
|
||||
isRefill: Boolean(createOrderDto.isRefill),
|
||||
refillIntervalDays: createOrderDto.refillIntervalDays || 60,
|
||||
trackingNumber,
|
||||
status: 'processing',
|
||||
status: initialStatus,
|
||||
paymentMethod: createOrderDto.paymentMethod || 'card',
|
||||
shippingAddress: createOrderDto.shippingAddress,
|
||||
orderItems: {
|
||||
create: orderItemsData,
|
||||
},
|
||||
inventoryReservations: {
|
||||
create: orderItemsData.map((item) => ({
|
||||
productId: item.productId,
|
||||
quantity: item.quantity,
|
||||
expiresAt: reservationExpiry,
|
||||
status: isOnline ? 'ACTIVE' : 'CONSUMED',
|
||||
})),
|
||||
},
|
||||
},
|
||||
include: {
|
||||
orderItems: {
|
||||
include: { product: true },
|
||||
},
|
||||
inventoryReservations: true,
|
||||
},
|
||||
});
|
||||
|
||||
// Send Order Confirmation SMS
|
||||
if (userId) {
|
||||
// Send Order Confirmation SMS (for card-to-card or non-online orders, online orders get SMS on verify)
|
||||
if (userId && !isOnline) {
|
||||
const user = await this.prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
});
|
||||
@ -384,4 +401,25 @@ export class OrdersService {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Release inventory reservations that expired without successful payment
|
||||
*/
|
||||
async releaseExpiredInventoryReservations() {
|
||||
const now = new Date();
|
||||
const expiredReservations = await this.prisma.inventoryReservation.updateMany({
|
||||
where: {
|
||||
status: 'ACTIVE',
|
||||
expiresAt: { lte: now },
|
||||
},
|
||||
data: {
|
||||
status: 'RELEASED',
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
releasedCount: expiredReservations.count,
|
||||
executedAt: now,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
69
backend/src/payment/dto/admin-transaction-filter.dto.ts
Normal file
69
backend/src/payment/dto/admin-transaction-filter.dto.ts
Normal file
@ -0,0 +1,69 @@
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsOptional, IsString, IsNumber, IsIn } from 'class-validator';
|
||||
import { Type } from 'class-transformer';
|
||||
|
||||
export class AdminTransactionFilterDto {
|
||||
@ApiPropertyOptional({ description: 'شماره صفحه', default: 1 })
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsNumber()
|
||||
page?: number = 1;
|
||||
|
||||
@ApiPropertyOptional({ description: 'تعداد در هر صفحه', default: 15 })
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsNumber()
|
||||
limit?: number = 15;
|
||||
|
||||
@ApiPropertyOptional({ description: 'جستجو (نام، موبایل، کد پیگیری، شماره مرجع، کد رهگیری)' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
search?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'فیلتر وضعیت (VERIFIED, PENDING, FAILED)' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
status?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'فیلتر درگاه (zibal, wallet, card)' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
gateway?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'فیلتر نوع تراکنش (ORDER, WALLET_TOPUP)' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
type?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'از تاریخ (ISO format)' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
startDate?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'تا تاریخ (ISO format)' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
endDate?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'حداقل مبلغ (تومان)' })
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsNumber()
|
||||
minAmount?: number;
|
||||
|
||||
@ApiPropertyOptional({ description: 'حداکثر مبلغ (تومان)' })
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsNumber()
|
||||
maxAmount?: number;
|
||||
|
||||
@ApiPropertyOptional({ description: 'فیلد مرتبسازی', default: 'createdAt' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
sortBy?: string = 'createdAt';
|
||||
|
||||
@ApiPropertyOptional({ description: 'جهت مرتبسازی (asc, desc)', default: 'desc' })
|
||||
@IsOptional()
|
||||
@IsIn(['asc', 'desc'])
|
||||
sortOrder?: 'asc' | 'desc' = 'desc';
|
||||
}
|
||||
25
backend/src/payment/dto/initiate-payment.dto.ts
Normal file
25
backend/src/payment/dto/initiate-payment.dto.ts
Normal file
@ -0,0 +1,25 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsNotEmpty, IsOptional, IsString } from 'class-validator';
|
||||
|
||||
export class InitiatePaymentDto {
|
||||
@ApiProperty({ description: 'شناسه سفارش در دیتابیس' })
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
orderId: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'آدرس بازگشت اختیاری جهت سفارشیسازی' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
customCallbackUrl?: string;
|
||||
}
|
||||
|
||||
export class InitiateWalletTopupDto {
|
||||
@ApiProperty({ description: 'مبلغ افزایش اعتبار (به تومان)' })
|
||||
@IsNotEmpty()
|
||||
amount: number;
|
||||
|
||||
@ApiPropertyOptional({ description: 'آدرس بازگشت اختیاری' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
customCallbackUrl?: string;
|
||||
}
|
||||
34
backend/src/payment/dto/verify-payment.dto.ts
Normal file
34
backend/src/payment/dto/verify-payment.dto.ts
Normal file
@ -0,0 +1,34 @@
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsOptional, IsString } from 'class-validator';
|
||||
|
||||
export class ZibalCallbackQueryDto {
|
||||
@ApiPropertyOptional({ description: 'وضعیت موفقیت اولیه زیبال (1 یا 0)' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
success?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'شناسه پیگیری تراکنش زیبال' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
trackId?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'شناسه سفارش ارسال شده در زمان ایجاد' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
orderId?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'کد وضعیت پرداخت زیبال' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
status?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'شماره کارت ماسک شده (در متد لِیزی)' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
cardNumber?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'شماره کارت هش شده (در متد لِیزی)' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
hashedCardNumber?: string;
|
||||
}
|
||||
55
backend/src/payment/interfaces/payment-gateway.interface.ts
Normal file
55
backend/src/payment/interfaces/payment-gateway.interface.ts
Normal file
@ -0,0 +1,55 @@
|
||||
export interface PaymentRequestOptions {
|
||||
amountRials: number;
|
||||
callbackUrl: string;
|
||||
orderId?: string;
|
||||
mobile?: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
export interface PaymentRequestResult {
|
||||
result: number;
|
||||
trackId: string | number;
|
||||
message?: string;
|
||||
paymentUrl?: string;
|
||||
}
|
||||
|
||||
export interface PaymentVerifyResult {
|
||||
result: number;
|
||||
refNumber?: string;
|
||||
cardNumber?: string;
|
||||
amount?: number;
|
||||
paidAt?: string;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
export interface PaymentInquiryResult {
|
||||
result: number;
|
||||
status?: number;
|
||||
amount?: number;
|
||||
refNumber?: string;
|
||||
cardNumber?: string;
|
||||
paidAt?: string;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
export interface GatewayHealthResult {
|
||||
gatewayName: string;
|
||||
status: 'ONLINE' | 'DEGRADED' | 'OFFLINE';
|
||||
latencyMs: number;
|
||||
merchantConfigured: boolean;
|
||||
activeMerchant: string;
|
||||
message: string;
|
||||
checkedAt: Date;
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard Payment Gateway Interface (Strategy / Gateway Adapter Pattern)
|
||||
*/
|
||||
export interface IPaymentGateway {
|
||||
getGatewayName(): string;
|
||||
requestPayment(options: PaymentRequestOptions): Promise<PaymentRequestResult>;
|
||||
verifyPayment(trackId: string | number): Promise<PaymentVerifyResult>;
|
||||
inquiryPayment(trackId: string | number): Promise<PaymentInquiryResult>;
|
||||
getStartUrl(trackId: string | number): string;
|
||||
checkHealth(): Promise<GatewayHealthResult>;
|
||||
}
|
||||
223
backend/src/payment/payment.controller.ts
Normal file
223
backend/src/payment/payment.controller.ts
Normal file
@ -0,0 +1,223 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Body,
|
||||
Query,
|
||||
Param,
|
||||
UseGuards,
|
||||
Req,
|
||||
Res,
|
||||
HttpStatus,
|
||||
Headers,
|
||||
Ip,
|
||||
} from '@nestjs/common';
|
||||
import type { Request, Response } from 'express';
|
||||
import { PaymentService } from './payment.service';
|
||||
import { ZibalService } from './zibal.service';
|
||||
import {
|
||||
InitiatePaymentDto,
|
||||
InitiateWalletTopupDto,
|
||||
} from './dto/initiate-payment.dto';
|
||||
import { ZibalCallbackQueryDto } from './dto/verify-payment.dto';
|
||||
import { AdminTransactionFilterDto } from './dto/admin-transaction-filter.dto';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { RolesGuard } from '../common/guards/roles.guard';
|
||||
import { Roles } from '../common/decorators/roles.decorator';
|
||||
import {
|
||||
ApiTags,
|
||||
ApiOperation,
|
||||
ApiBearerAuth,
|
||||
ApiOkResponse,
|
||||
ApiBadRequestResponse,
|
||||
} from '@nestjs/swagger';
|
||||
|
||||
@ApiTags('Payment - درگاه پرداخت اینترنتی زیبال و مدیریت تراکنشها')
|
||||
@Controller('payment')
|
||||
export class PaymentController {
|
||||
constructor(
|
||||
private readonly paymentService: PaymentService,
|
||||
private readonly zibalService: ZibalService,
|
||||
) {}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Post('zibal/initiate')
|
||||
@ApiOperation({ summary: 'شروع فرایند پرداخت آنلاین سفارش با درگاه زیبال' })
|
||||
@ApiOkResponse({
|
||||
description: 'لینک هدایت به درگاه پرداخت زیبال با موفقیت تولید شد',
|
||||
})
|
||||
@ApiBadRequestResponse({
|
||||
description: 'خطا در ایجاد تراکنش یا نامعتبر بودن سفارش',
|
||||
})
|
||||
async initiateOrderPayment(
|
||||
@Req() req: { user: { id: string } },
|
||||
@Body() body: InitiatePaymentDto,
|
||||
@Ip() ip: string,
|
||||
@Headers('user-agent') userAgent?: string,
|
||||
) {
|
||||
return this.paymentService.initiateOrderPayment(
|
||||
req.user.id,
|
||||
body.orderId,
|
||||
body.customCallbackUrl,
|
||||
{ ipAddress: ip, userAgent },
|
||||
);
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Post('zibal/wallet/initiate')
|
||||
@ApiOperation({ summary: 'شارژ آنلاین کیف پول از طریق درگاه زیبال' })
|
||||
@ApiOkResponse({
|
||||
description: 'لینک هدایت به درگاه پرداخت برای شارژ کیف پول',
|
||||
})
|
||||
async initiateWalletTopup(
|
||||
@Req() req: { user: { id: string } },
|
||||
@Body() body: InitiateWalletTopupDto,
|
||||
@Ip() ip: string,
|
||||
@Headers('user-agent') userAgent?: string,
|
||||
) {
|
||||
return this.paymentService.initiateWalletTopup(
|
||||
req.user.id,
|
||||
Number(body.amount),
|
||||
body.customCallbackUrl,
|
||||
{ ipAddress: ip, userAgent },
|
||||
);
|
||||
}
|
||||
|
||||
@Get('zibal/callback')
|
||||
@ApiOperation({
|
||||
summary: 'دریافت کالبک بازگشت از درگاه زیبال و تایید تراکنش',
|
||||
})
|
||||
async handleZibalCallback(
|
||||
@Query() query: ZibalCallbackQueryDto,
|
||||
@Res() res: Response,
|
||||
@Ip() ip: string,
|
||||
@Headers('user-agent') userAgent?: string,
|
||||
) {
|
||||
const trackId = query.trackId || '';
|
||||
const success = query.success;
|
||||
const status = query.status;
|
||||
const orderId = query.orderId;
|
||||
|
||||
const frontendUrl = await this.zibalService.getFrontendUrl();
|
||||
|
||||
if (!trackId) {
|
||||
return res.redirect(
|
||||
`${frontendUrl}/payment/verify?success=0&message=${encodeURIComponent('شناسه پیگیری نامعتبر است')}`,
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await this.paymentService.verifyAndProcess(
|
||||
trackId,
|
||||
success,
|
||||
status,
|
||||
orderId,
|
||||
{ ipAddress: ip, userAgent },
|
||||
);
|
||||
|
||||
const params = new URLSearchParams({
|
||||
trackId: String(result.trackId || trackId),
|
||||
success: result.success ? '1' : '0',
|
||||
status: result.status || '',
|
||||
orderId: result.orderId || orderId || '',
|
||||
refNumber: result.refNumber || '',
|
||||
cardNumber: result.cardNumber || '',
|
||||
message: result.message || '',
|
||||
amount: String(result.amount || ''),
|
||||
type: result.type || '',
|
||||
});
|
||||
|
||||
return res.redirect(`${frontendUrl}/payment/verify?${params.toString()}`);
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : 'خطا در پردازش پرداخت';
|
||||
return res.redirect(
|
||||
`${frontendUrl}/payment/verify?success=0&trackId=${trackId}&message=${encodeURIComponent(msg)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@Post('zibal/callback')
|
||||
@ApiOperation({ summary: 'دریافت وبهوک / کالبک لِیزی زیبال' })
|
||||
async handleZibalLazyCallback(
|
||||
@Body() body: ZibalCallbackQueryDto,
|
||||
@Res() res: Response,
|
||||
@Ip() ip: string,
|
||||
@Headers('user-agent') userAgent?: string,
|
||||
) {
|
||||
const trackId = body.trackId || '';
|
||||
const success = body.success;
|
||||
const status = body.status;
|
||||
const orderId = body.orderId;
|
||||
|
||||
if (!trackId) {
|
||||
return res
|
||||
.status(HttpStatus.BAD_REQUEST)
|
||||
.json({ success: false, message: 'trackId is required' });
|
||||
}
|
||||
|
||||
const result = await this.paymentService.verifyAndProcess(
|
||||
trackId,
|
||||
success,
|
||||
status,
|
||||
orderId,
|
||||
{ ipAddress: ip, userAgent },
|
||||
);
|
||||
|
||||
return res.status(HttpStatus.OK).json(result);
|
||||
}
|
||||
|
||||
@Get('verify-status/:trackId')
|
||||
@ApiOperation({ summary: 'استعلام و دریافت وضعیت تراکنش پرداخت با TrackID' })
|
||||
async getTransactionStatus(@Param('trackId') trackId: string) {
|
||||
return this.paymentService.getTransaction(trackId);
|
||||
}
|
||||
|
||||
// --- ADMIN ENDPOINTS FOR TRANSACTION LOGS, DIAGNOSTICS & HEALTH CHECK ---
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@ApiBearerAuth()
|
||||
@Get('admin/transactions')
|
||||
@ApiOperation({ summary: 'مدیریت و مشاهده تمامی لاگها و تراکنشهای پرداخت' })
|
||||
async getAdminTransactions(@Query() query: AdminTransactionFilterDto) {
|
||||
return this.paymentService.getAdminTransactions(query);
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@ApiBearerAuth()
|
||||
@Get('admin/stats')
|
||||
@ApiOperation({ summary: 'آمار کلی تراکنشها و حجم مبالغ پرداختی' })
|
||||
async getAdminStats() {
|
||||
return this.paymentService.getAdminTransactionStats();
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@ApiBearerAuth()
|
||||
@Post('admin/reconcile')
|
||||
@ApiOperation({ summary: 'اجرای فرایند انطباق و استعلام خودکار تراکنشهای بلاتکلیف' })
|
||||
async reconcilePending() {
|
||||
return this.paymentService.reconcilePendingTransactions();
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@ApiBearerAuth()
|
||||
@Get('admin/live-inquiry/:id')
|
||||
@ApiOperation({ summary: 'استعلام زنده وضعیت تراکنش از سرور زیبال' })
|
||||
async liveInquiry(@Param('id') id: string) {
|
||||
return this.paymentService.adminLiveInquiry(id);
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@ApiBearerAuth()
|
||||
@Get('admin/health')
|
||||
@ApiOperation({ summary: 'بررسی وضعیت آنلاین بودن و سلامت درگاه پرداخت (Health Check & Latency)' })
|
||||
async getHealth() {
|
||||
return this.paymentService.checkGatewayHealth();
|
||||
}
|
||||
}
|
||||
14
backend/src/payment/payment.module.ts
Normal file
14
backend/src/payment/payment.module.ts
Normal file
@ -0,0 +1,14 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { PaymentController } from './payment.controller';
|
||||
import { PaymentService } from './payment.service';
|
||||
import { ZibalService } from './zibal.service';
|
||||
import { PrismaModule } from '../prisma/prisma.module';
|
||||
import { SmsModule } from '../common/sms.module';
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule, SmsModule],
|
||||
controllers: [PaymentController],
|
||||
providers: [PaymentService, ZibalService],
|
||||
exports: [PaymentService, ZibalService],
|
||||
})
|
||||
export class PaymentModule {}
|
||||
859
backend/src/payment/payment.service.ts
Normal file
859
backend/src/payment/payment.service.ts
Normal file
@ -0,0 +1,859 @@
|
||||
import {
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
BadRequestException,
|
||||
Logger,
|
||||
} from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { ZibalService } from './zibal.service';
|
||||
import { SmsService } from '../common/services/sms.service';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { AdminTransactionFilterDto } from './dto/admin-transaction-filter.dto';
|
||||
|
||||
export interface ClientMetadata {
|
||||
ipAddress?: string;
|
||||
userAgent?: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class PaymentService {
|
||||
private readonly logger = new Logger(PaymentService.name);
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly zibalService: ZibalService,
|
||||
private readonly smsService: SmsService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 1. Initiate Online Payment for an Order via Zibal
|
||||
*/
|
||||
async initiateOrderPayment(
|
||||
userId: string,
|
||||
orderId: string,
|
||||
customCallbackUrl?: string,
|
||||
clientMeta?: ClientMetadata,
|
||||
) {
|
||||
const order = await this.prisma.order.findFirst({
|
||||
where: { id: orderId, userId },
|
||||
include: { user: true },
|
||||
});
|
||||
|
||||
if (!order) {
|
||||
throw new NotFoundException('سفارش مورد نظر یافت نشد');
|
||||
}
|
||||
|
||||
if (['shipped', 'delivered'].includes(order.status)) {
|
||||
throw new BadRequestException('این سفارش قبلاً تکمیل و ارسال شده است');
|
||||
}
|
||||
|
||||
const amountTomans = Number(order.totalAmount);
|
||||
const amountRials = Math.round(amountTomans * 10);
|
||||
|
||||
if (amountRials < 1000) {
|
||||
throw new BadRequestException(
|
||||
'مبلغ سفارش کمتر از حداقل مجاز درگاه بانکی (۱,۰۰۰ ریال) است',
|
||||
);
|
||||
}
|
||||
|
||||
const frontendUrl = await this.zibalService.getFrontendUrl();
|
||||
const callbackUrl =
|
||||
customCallbackUrl || `${frontendUrl}/payment/verify?orderId=${order.id}`;
|
||||
|
||||
const requestPayload = {
|
||||
amountRials,
|
||||
callbackUrl,
|
||||
orderId: order.id,
|
||||
mobile: order.user?.mobile || undefined,
|
||||
description: `پرداخت سفارش ${order.trackingNumber || ''} - پتشاپ کانینا`,
|
||||
};
|
||||
|
||||
// Create a pending PaymentTransaction in database
|
||||
const transaction = await this.prisma.paymentTransaction.create({
|
||||
data: {
|
||||
userId,
|
||||
orderId: order.id,
|
||||
amount: new Prisma.Decimal(amountTomans),
|
||||
amountRials: BigInt(amountRials),
|
||||
gateway: 'zibal',
|
||||
status: 'PENDING',
|
||||
type: 'ORDER',
|
||||
description: `پرداخت آنلاین سفارش ${order.trackingNumber || order.id}`,
|
||||
ipAddress: clientMeta?.ipAddress,
|
||||
userAgent: clientMeta?.userAgent,
|
||||
rawRequest: requestPayload as unknown as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const zibalRes = await this.zibalService.requestPayment(requestPayload);
|
||||
|
||||
if (zibalRes.result !== 100) {
|
||||
const errorMsg = this.zibalService.getResultMessage(zibalRes.result);
|
||||
await this.prisma.paymentTransaction.update({
|
||||
where: { id: transaction.id },
|
||||
data: {
|
||||
status: 'FAILED',
|
||||
resultCode: zibalRes.result,
|
||||
message: errorMsg,
|
||||
rawResponse: zibalRes as unknown as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
throw new BadRequestException(`خطا در ایجاد تراکنش زیبال: ${errorMsg}`);
|
||||
}
|
||||
|
||||
const trackId = String(zibalRes.trackId);
|
||||
|
||||
// Update transaction with trackId
|
||||
await this.prisma.paymentTransaction.update({
|
||||
where: { id: transaction.id },
|
||||
data: {
|
||||
trackId,
|
||||
resultCode: zibalRes.result,
|
||||
message: zibalRes.message,
|
||||
rawResponse: zibalRes as unknown as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
|
||||
const paymentUrl = this.zibalService.getStartUrl(trackId);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
trackId,
|
||||
paymentUrl,
|
||||
orderId: order.id,
|
||||
amount: amountTomans,
|
||||
};
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
const stack = err instanceof Error ? err.stack : undefined;
|
||||
this.logger.error(`Error requesting payment from Zibal: ${msg}`, stack);
|
||||
throw new BadRequestException(msg || 'خطا در اتصال به درگاه پرداخت');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 2. Initiate Online Wallet Top-Up via Zibal
|
||||
*/
|
||||
async initiateWalletTopup(
|
||||
userId: string,
|
||||
amountTomans: number,
|
||||
customCallbackUrl?: string,
|
||||
clientMeta?: ClientMetadata,
|
||||
) {
|
||||
if (amountTomans < 1000) {
|
||||
throw new BadRequestException('حداقل مبلغ افزایش موجودی ۱,۰۰۰ تومان است');
|
||||
}
|
||||
|
||||
const user = await this.prisma.user.findUnique({ where: { id: userId } });
|
||||
if (!user) {
|
||||
throw new NotFoundException('کاربر یافت نشد');
|
||||
}
|
||||
|
||||
const amountRials = Math.round(amountTomans * 10);
|
||||
const frontendUrl = await this.zibalService.getFrontendUrl();
|
||||
const callbackUrl =
|
||||
customCallbackUrl || `${frontendUrl}/payment/verify?type=wallet`;
|
||||
|
||||
const requestPayload = {
|
||||
amountRials,
|
||||
callbackUrl,
|
||||
mobile: user.mobile || undefined,
|
||||
description: `شارژ کیف پول - پت شاپ کانینا`,
|
||||
};
|
||||
|
||||
const transaction = await this.prisma.paymentTransaction.create({
|
||||
data: {
|
||||
userId,
|
||||
amount: new Prisma.Decimal(amountTomans),
|
||||
amountRials: BigInt(amountRials),
|
||||
gateway: 'zibal',
|
||||
status: 'PENDING',
|
||||
type: 'WALLET_TOPUP',
|
||||
description: `افزایش موجودی کیف پول کاربر ${user.mobile}`,
|
||||
ipAddress: clientMeta?.ipAddress,
|
||||
userAgent: clientMeta?.userAgent,
|
||||
rawRequest: requestPayload as unknown as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const zibalRes = await this.zibalService.requestPayment(requestPayload);
|
||||
|
||||
if (zibalRes.result !== 100) {
|
||||
const errorMsg = this.zibalService.getResultMessage(zibalRes.result);
|
||||
await this.prisma.paymentTransaction.update({
|
||||
where: { id: transaction.id },
|
||||
data: {
|
||||
status: 'FAILED',
|
||||
resultCode: zibalRes.result,
|
||||
message: errorMsg,
|
||||
rawResponse: zibalRes as unknown as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
throw new BadRequestException(`خطا در ایجاد تراکنش زیبال: ${errorMsg}`);
|
||||
}
|
||||
|
||||
const trackId = String(zibalRes.trackId);
|
||||
|
||||
await this.prisma.paymentTransaction.update({
|
||||
where: { id: transaction.id },
|
||||
data: {
|
||||
trackId,
|
||||
resultCode: zibalRes.result,
|
||||
message: zibalRes.message,
|
||||
rawResponse: zibalRes as unknown as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
trackId,
|
||||
paymentUrl: this.zibalService.getStartUrl(trackId),
|
||||
amount: amountTomans,
|
||||
};
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
this.logger.error(`Error requesting wallet topup from Zibal: ${msg}`);
|
||||
throw new BadRequestException(msg || 'خطا در ارتباط با درگاه بانکی');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 3. Verify & Process Callback from Zibal (With Idempotency, Amount Match & Inventory Hold Release/Consume)
|
||||
*/
|
||||
async verifyAndProcess(
|
||||
trackId: string,
|
||||
successParam?: string,
|
||||
statusParam?: string,
|
||||
orderIdParam?: string,
|
||||
clientMeta?: ClientMetadata,
|
||||
) {
|
||||
this.logger.log(
|
||||
`Processing callback for trackId=${trackId}, success=${successParam}, status=${statusParam}, orderId=${orderIdParam}`,
|
||||
);
|
||||
|
||||
let transaction = await this.prisma.paymentTransaction.findUnique({
|
||||
where: { trackId },
|
||||
include: {
|
||||
order: {
|
||||
include: {
|
||||
user: true,
|
||||
orderItems: { include: { product: true } },
|
||||
},
|
||||
},
|
||||
user: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!transaction && orderIdParam) {
|
||||
transaction = await this.prisma.paymentTransaction.findFirst({
|
||||
where: { orderId: orderIdParam },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
include: {
|
||||
order: {
|
||||
include: {
|
||||
user: true,
|
||||
orderItems: { include: { product: true } },
|
||||
},
|
||||
},
|
||||
user: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (!transaction) {
|
||||
throw new NotFoundException('تراکنش پرداخت در سیستم یافت نشد');
|
||||
}
|
||||
|
||||
// --- IDEMPOTENCY CHECK ---
|
||||
if (transaction.status === 'VERIFIED') {
|
||||
this.logger.log(
|
||||
`Idempotency Guard: Transaction ${transaction.id} (trackId=${trackId}) is already VERIFIED. Skipping duplicate execution.`,
|
||||
);
|
||||
return {
|
||||
success: true,
|
||||
alreadyVerified: true,
|
||||
status: 'VERIFIED',
|
||||
trackId: transaction.trackId,
|
||||
refNumber: transaction.refNumber,
|
||||
cardNumber: transaction.cardNumber,
|
||||
amount: Number(transaction.amount),
|
||||
orderId: transaction.orderId,
|
||||
type: transaction.type,
|
||||
message: 'تراکنش قبلاً با موفقیت تایید و پردازش شده است',
|
||||
};
|
||||
}
|
||||
|
||||
// If user cancelled or Zibal signaled failure at the gate
|
||||
if (successParam === '0' || statusParam === '3') {
|
||||
const statusMessage = this.zibalService.getStatusMessage(
|
||||
statusParam || 3,
|
||||
);
|
||||
await this.prisma.paymentTransaction.update({
|
||||
where: { id: transaction.id },
|
||||
data: {
|
||||
status: 'FAILED',
|
||||
message: statusMessage,
|
||||
ipAddress: clientMeta?.ipAddress || transaction.ipAddress,
|
||||
userAgent: clientMeta?.userAgent || transaction.userAgent,
|
||||
},
|
||||
});
|
||||
|
||||
// Release any active inventory reservation for this order
|
||||
if (transaction.orderId) {
|
||||
await this.prisma.inventoryReservation.updateMany({
|
||||
where: { orderId: transaction.orderId, status: 'ACTIVE' },
|
||||
data: { status: 'RELEASED' },
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
status: 'FAILED',
|
||||
trackId,
|
||||
message: statusMessage,
|
||||
orderId: transaction.orderId,
|
||||
};
|
||||
}
|
||||
|
||||
// Call Zibal verify endpoint
|
||||
try {
|
||||
const verifyRes = await this.zibalService.verifyPayment(trackId);
|
||||
const isSuccess = verifyRes.result === 100 || verifyRes.result === 201;
|
||||
|
||||
if (!isSuccess) {
|
||||
const errorMsg = this.zibalService.getResultMessage(verifyRes.result);
|
||||
await this.prisma.paymentTransaction.update({
|
||||
where: { id: transaction.id },
|
||||
data: {
|
||||
status: 'FAILED',
|
||||
resultCode: verifyRes.result,
|
||||
message: errorMsg,
|
||||
cardNumber: verifyRes.cardNumber,
|
||||
rawResponse: verifyRes as unknown as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
|
||||
// Release inventory reservations on failure
|
||||
if (transaction.orderId) {
|
||||
await this.prisma.inventoryReservation.updateMany({
|
||||
where: { orderId: transaction.orderId, status: 'ACTIVE' },
|
||||
data: { status: 'RELEASED' },
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
status: 'FAILED',
|
||||
trackId,
|
||||
resultCode: verifyRes.result,
|
||||
message: errorMsg,
|
||||
orderId: transaction.orderId,
|
||||
};
|
||||
}
|
||||
|
||||
// --- AMOUNT MATCH VERIFICATION ---
|
||||
const expectedAmountRials = Number(
|
||||
transaction.amountRials ||
|
||||
Math.round(Number(transaction.amount) * 10),
|
||||
);
|
||||
|
||||
if (
|
||||
verifyRes.amount &&
|
||||
Number(verifyRes.amount) > 0 &&
|
||||
Number(verifyRes.amount) !== expectedAmountRials
|
||||
) {
|
||||
this.logger.error(
|
||||
`Security Alert: Amount mismatch on trackId=${trackId}! Zibal reported ${verifyRes.amount} Rials, but expected ${expectedAmountRials} Rials in DB.`,
|
||||
);
|
||||
|
||||
await this.prisma.paymentTransaction.update({
|
||||
where: { id: transaction.id },
|
||||
data: {
|
||||
status: 'FAILED',
|
||||
resultCode: verifyRes.result,
|
||||
message: `مغایرت مالی: مبلغ تایید شده زیبال (${verifyRes.amount} ریال) با مبلغ سیستم (${expectedAmountRials} ریال) مطابقت ندارد.`,
|
||||
rawResponse: verifyRes as unknown as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
success: false,
|
||||
status: 'FAILED',
|
||||
trackId,
|
||||
message: 'خطای امنیتی: مغایرت در مبلغ پرداخت شده با سفارش.',
|
||||
orderId: transaction.orderId,
|
||||
};
|
||||
}
|
||||
|
||||
// SUCCESSFUL PAYMENT!
|
||||
const refNumber = verifyRes.refNumber
|
||||
? String(verifyRes.refNumber)
|
||||
: undefined;
|
||||
const cardNumber = verifyRes.cardNumber || undefined;
|
||||
const paidDate = verifyRes.paidAt
|
||||
? new Date(verifyRes.paidAt)
|
||||
: new Date();
|
||||
|
||||
// Execute atomic status update with concurrency guard
|
||||
await this.prisma.$transaction(async (tx) => {
|
||||
// Optimistic lock: only update if still PENDING
|
||||
const updatedCount = await tx.paymentTransaction.updateMany({
|
||||
where: { id: transaction.id, status: 'PENDING' },
|
||||
data: {
|
||||
status: 'VERIFIED',
|
||||
resultCode: verifyRes.result,
|
||||
refNumber,
|
||||
cardNumber,
|
||||
paidAt: paidDate,
|
||||
message: 'پرداخت با موفقیت انجام و تایید شد',
|
||||
rawResponse: verifyRes as unknown as Prisma.InputJsonValue,
|
||||
ipAddress: clientMeta?.ipAddress || transaction.ipAddress,
|
||||
userAgent: clientMeta?.userAgent || transaction.userAgent,
|
||||
},
|
||||
});
|
||||
|
||||
if (updatedCount.count === 0) {
|
||||
this.logger.warn(
|
||||
`Concurrent execution detected for transaction ${transaction.id}. Handled safely.`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// 2. If it's an Order payment -> Mark processing & Consume Inventory Reservation
|
||||
if (transaction.type === 'ORDER' && transaction.orderId) {
|
||||
await tx.order.update({
|
||||
where: { id: transaction.orderId },
|
||||
data: {
|
||||
status: 'processing',
|
||||
paymentMethod: 'online',
|
||||
},
|
||||
});
|
||||
|
||||
// Mark inventory reservations as CONSUMED
|
||||
await tx.inventoryReservation.updateMany({
|
||||
where: { orderId: transaction.orderId, status: 'ACTIVE' },
|
||||
data: { status: 'CONSUMED' },
|
||||
});
|
||||
|
||||
// If charity donation was made, update user's total charity
|
||||
if (
|
||||
transaction.order &&
|
||||
Number(transaction.order.charityDonation) > 0
|
||||
) {
|
||||
await tx.user.update({
|
||||
where: { id: transaction.userId },
|
||||
data: {
|
||||
charityDonationTotal: {
|
||||
increment: Number(transaction.order.charityDonation),
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 3. If it's a Wallet Top-up
|
||||
if (transaction.type === 'WALLET_TOPUP') {
|
||||
await tx.user.update({
|
||||
where: { id: transaction.userId },
|
||||
data: {
|
||||
walletBalance: {
|
||||
increment: Number(transaction.amount),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await tx.walletTransaction.create({
|
||||
data: {
|
||||
userId: transaction.userId,
|
||||
amount: transaction.amount,
|
||||
type: 'deposit',
|
||||
status: 'completed',
|
||||
transactionReference: refNumber || `ZBL-${trackId}`,
|
||||
description: `افزایش اعتبار آنلاین از طریق درگاه زیبال (شناسه: ${trackId})`,
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Send SMS notification if order payment
|
||||
if (transaction.type === 'ORDER' && transaction.order?.user?.mobile) {
|
||||
const mobile = transaction.order.user.mobile;
|
||||
const trackingNum =
|
||||
transaction.order.trackingNumber || transaction.order.id;
|
||||
const formattedAmount = Number(transaction.amount).toLocaleString(
|
||||
'fa-IR',
|
||||
);
|
||||
|
||||
this.smsService
|
||||
.sendOrderConfirmation(mobile, trackingNum, formattedAmount)
|
||||
.catch((err) => {
|
||||
this.logger.warn(`Could not send SMS confirmation: ${err}`);
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
status: 'VERIFIED',
|
||||
trackId,
|
||||
refNumber,
|
||||
cardNumber,
|
||||
amount: Number(transaction.amount),
|
||||
orderId: transaction.orderId,
|
||||
type: transaction.type,
|
||||
message: 'پرداخت با موفقیت انجام شد',
|
||||
};
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
const stack = err instanceof Error ? err.stack : undefined;
|
||||
this.logger.error(`Error during verify: ${msg}`, stack);
|
||||
return {
|
||||
success: false,
|
||||
status: 'ERROR',
|
||||
trackId,
|
||||
message: msg || 'خطا در فرایند تایید تراکنش',
|
||||
orderId: transaction.orderId,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 4. Auto-Reconciliation / Cron Job for Pending Transactions
|
||||
*/
|
||||
async reconcilePendingTransactions() {
|
||||
this.logger.log('Starting pending transactions reconciliation job...');
|
||||
|
||||
const fiveMinutesAgo = new Date(Date.now() - 5 * 60 * 1000);
|
||||
const oneDayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);
|
||||
|
||||
const pendingTransactions = await this.prisma.paymentTransaction.findMany({
|
||||
where: {
|
||||
status: 'PENDING',
|
||||
trackId: { not: null },
|
||||
createdAt: {
|
||||
gte: oneDayAgo,
|
||||
lte: fiveMinutesAgo,
|
||||
},
|
||||
},
|
||||
include: { order: true, user: true },
|
||||
take: 50,
|
||||
});
|
||||
|
||||
const results = {
|
||||
total: pendingTransactions.length,
|
||||
verified: 0,
|
||||
failed: 0,
|
||||
remainedPending: 0,
|
||||
errors: 0,
|
||||
};
|
||||
|
||||
for (const tx of pendingTransactions) {
|
||||
if (!tx.trackId) continue;
|
||||
|
||||
try {
|
||||
const inquiry = await this.zibalService.inquiryPayment(tx.trackId);
|
||||
this.logger.log(
|
||||
`Inquiry for trackId=${tx.trackId}: status=${inquiry.status}, result=${inquiry.result}`,
|
||||
);
|
||||
|
||||
if (inquiry.status === 1 || inquiry.status === 2 || inquiry.result === 100) {
|
||||
await this.verifyAndProcess(tx.trackId, '1', String(inquiry.status), tx.orderId || undefined);
|
||||
results.verified++;
|
||||
} else if (inquiry.status === 3 || inquiry.status === -2 || inquiry.result === 202) {
|
||||
const msg = this.zibalService.getStatusMessage(inquiry.status || 3);
|
||||
await this.prisma.paymentTransaction.update({
|
||||
where: { id: tx.id },
|
||||
data: {
|
||||
status: 'FAILED',
|
||||
resultCode: inquiry.result,
|
||||
message: msg,
|
||||
rawResponse: inquiry as unknown as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
|
||||
if (tx.orderId) {
|
||||
await this.prisma.inventoryReservation.updateMany({
|
||||
where: { orderId: tx.orderId, status: 'ACTIVE' },
|
||||
data: { status: 'RELEASED' },
|
||||
});
|
||||
}
|
||||
results.failed++;
|
||||
} else {
|
||||
results.remainedPending++;
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
results.errors++;
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
this.logger.warn(`Failed inquiry for trackId=${tx.trackId}: ${msg}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Also release all expired reservations
|
||||
const now = new Date();
|
||||
await this.prisma.inventoryReservation.updateMany({
|
||||
where: { status: 'ACTIVE', expiresAt: { lte: now } },
|
||||
data: { status: 'RELEASED' },
|
||||
});
|
||||
|
||||
this.logger.log(`Reconciliation finished: ${JSON.stringify(results)}`);
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* 5. Get Payment Transaction Details by TrackID
|
||||
*/
|
||||
async getTransaction(trackId: string) {
|
||||
const transaction = await this.prisma.paymentTransaction.findUnique({
|
||||
where: { trackId },
|
||||
include: {
|
||||
order: {
|
||||
include: {
|
||||
orderItems: {
|
||||
include: { product: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
user: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!transaction) {
|
||||
throw new NotFoundException('تراکنش یافت نشد');
|
||||
}
|
||||
|
||||
return {
|
||||
id: transaction.id,
|
||||
trackId: transaction.trackId,
|
||||
refNumber: transaction.refNumber,
|
||||
amount: Number(transaction.amount),
|
||||
status: transaction.status,
|
||||
message: transaction.message,
|
||||
gateway: transaction.gateway,
|
||||
type: transaction.type,
|
||||
cardNumber: transaction.cardNumber,
|
||||
ipAddress: transaction.ipAddress,
|
||||
userAgent: transaction.userAgent,
|
||||
rawRequest: transaction.rawRequest,
|
||||
rawResponse: transaction.rawResponse,
|
||||
paidAt: transaction.paidAt,
|
||||
createdAt: transaction.createdAt,
|
||||
order: transaction.order,
|
||||
user: transaction.user ? {
|
||||
id: transaction.user.id,
|
||||
firstName: transaction.user.firstName,
|
||||
lastName: transaction.user.lastName,
|
||||
mobile: transaction.user.mobile,
|
||||
} : null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 6. Admin: Get List of Transactions with Advanced Search & Filter
|
||||
*/
|
||||
async getAdminTransactions(filters: AdminTransactionFilterDto) {
|
||||
const {
|
||||
page = 1,
|
||||
limit = 15,
|
||||
search,
|
||||
status,
|
||||
gateway,
|
||||
type,
|
||||
startDate,
|
||||
endDate,
|
||||
minAmount,
|
||||
maxAmount,
|
||||
sortBy = 'createdAt',
|
||||
sortOrder = 'desc',
|
||||
} = filters;
|
||||
|
||||
const skip = (page - 1) * limit;
|
||||
const where: Prisma.PaymentTransactionWhereInput = {};
|
||||
|
||||
if (status) {
|
||||
where.status = status;
|
||||
}
|
||||
|
||||
if (gateway) {
|
||||
where.gateway = gateway;
|
||||
}
|
||||
|
||||
if (type) {
|
||||
where.type = type;
|
||||
}
|
||||
|
||||
if (startDate || endDate) {
|
||||
where.createdAt = {};
|
||||
if (startDate) where.createdAt.gte = new Date(startDate);
|
||||
if (endDate) where.createdAt.lte = new Date(endDate);
|
||||
}
|
||||
|
||||
if (minAmount !== undefined || maxAmount !== undefined) {
|
||||
where.amount = {};
|
||||
if (minAmount !== undefined) where.amount.gte = new Prisma.Decimal(minAmount);
|
||||
if (maxAmount !== undefined) where.amount.lte = new Prisma.Decimal(maxAmount);
|
||||
}
|
||||
|
||||
if (search && search.trim() !== '') {
|
||||
const s = search.trim();
|
||||
where.OR = [
|
||||
{ trackId: { contains: s, mode: 'insensitive' } },
|
||||
{ refNumber: { contains: s, mode: 'insensitive' } },
|
||||
{ cardNumber: { contains: s, mode: 'insensitive' } },
|
||||
{ description: { contains: s, mode: 'insensitive' } },
|
||||
{
|
||||
user: {
|
||||
OR: [
|
||||
{ firstName: { contains: s, mode: 'insensitive' } },
|
||||
{ lastName: { contains: s, mode: 'insensitive' } },
|
||||
{ mobile: { contains: s, mode: 'insensitive' } },
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
order: {
|
||||
trackingNumber: { contains: s, mode: 'insensitive' },
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const [data, total] = await Promise.all([
|
||||
this.prisma.paymentTransaction.findMany({
|
||||
where,
|
||||
skip,
|
||||
take: limit,
|
||||
orderBy: { [sortBy]: sortOrder },
|
||||
include: {
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
mobile: true,
|
||||
email: true,
|
||||
},
|
||||
},
|
||||
order: {
|
||||
select: {
|
||||
id: true,
|
||||
trackingNumber: true,
|
||||
totalAmount: true,
|
||||
status: true,
|
||||
paymentMethod: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
this.prisma.paymentTransaction.count({ where }),
|
||||
]);
|
||||
|
||||
return {
|
||||
data,
|
||||
meta: {
|
||||
total,
|
||||
page,
|
||||
lastPage: Math.ceil(total / limit),
|
||||
limit,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 7. Admin: Get Transaction Statistics
|
||||
*/
|
||||
async getAdminTransactionStats() {
|
||||
const [
|
||||
totalCount,
|
||||
verifiedCount,
|
||||
pendingCount,
|
||||
failedCount,
|
||||
verifiedSum,
|
||||
todayVerified,
|
||||
] = await Promise.all([
|
||||
this.prisma.paymentTransaction.count(),
|
||||
this.prisma.paymentTransaction.count({ where: { status: 'VERIFIED' } }),
|
||||
this.prisma.paymentTransaction.count({ where: { status: 'PENDING' } }),
|
||||
this.prisma.paymentTransaction.count({ where: { status: 'FAILED' } }),
|
||||
this.prisma.paymentTransaction.aggregate({
|
||||
_sum: { amount: true },
|
||||
where: { status: 'VERIFIED' },
|
||||
}),
|
||||
this.prisma.paymentTransaction.aggregate({
|
||||
_sum: { amount: true },
|
||||
where: {
|
||||
status: 'VERIFIED',
|
||||
createdAt: {
|
||||
gte: new Date(new Date().setHours(0, 0, 0, 0)),
|
||||
},
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
const totalVolume = Number(verifiedSum._sum.amount || 0);
|
||||
const todayVolume = Number(todayVerified._sum.amount || 0);
|
||||
const successRate =
|
||||
totalCount > 0 ? Math.round((verifiedCount / totalCount) * 100) : 0;
|
||||
|
||||
return {
|
||||
totalCount,
|
||||
verifiedCount,
|
||||
pendingCount,
|
||||
failedCount,
|
||||
totalVolume,
|
||||
todayVolume,
|
||||
successRate,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 8. Admin: Perform Live Instant Inquiry on Zibal for a Transaction
|
||||
*/
|
||||
async adminLiveInquiry(transactionId: string) {
|
||||
const transaction = await this.prisma.paymentTransaction.findUnique({
|
||||
where: { id: transactionId },
|
||||
include: { order: true, user: true },
|
||||
});
|
||||
|
||||
if (!transaction) {
|
||||
throw new NotFoundException('تراکنش یافت نشد');
|
||||
}
|
||||
|
||||
if (!transaction.trackId) {
|
||||
throw new BadRequestException('این تراکنش فاقد TrackId زیبال است');
|
||||
}
|
||||
|
||||
const inquiryRes = await this.zibalService.inquiryPayment(transaction.trackId);
|
||||
const statusMsg = this.zibalService.getStatusMessage(inquiryRes.status ?? 3);
|
||||
const resultMsg = this.zibalService.getResultMessage(inquiryRes.result);
|
||||
|
||||
if (
|
||||
transaction.status === 'PENDING' &&
|
||||
(inquiryRes.status === 1 || inquiryRes.status === 2 || inquiryRes.result === 100)
|
||||
) {
|
||||
await this.verifyAndProcess(
|
||||
transaction.trackId,
|
||||
'1',
|
||||
String(inquiryRes.status),
|
||||
transaction.orderId || undefined,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
transactionId: transaction.id,
|
||||
trackId: transaction.trackId,
|
||||
currentDbStatus: transaction.status,
|
||||
gatewayResponse: inquiryRes,
|
||||
statusMessage: statusMsg,
|
||||
resultMessage: resultMsg,
|
||||
inquiredAt: new Date(),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 9. Gateway Health Check for Admin
|
||||
*/
|
||||
async checkGatewayHealth() {
|
||||
return this.zibalService.checkHealth();
|
||||
}
|
||||
}
|
||||
368
backend/src/payment/zibal.service.ts
Normal file
368
backend/src/payment/zibal.service.ts
Normal file
@ -0,0 +1,368 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import {
|
||||
IPaymentGateway,
|
||||
PaymentRequestOptions,
|
||||
PaymentRequestResult,
|
||||
PaymentVerifyResult,
|
||||
PaymentInquiryResult,
|
||||
GatewayHealthResult,
|
||||
} from './interfaces/payment-gateway.interface';
|
||||
|
||||
export interface ZibalRequestResponse {
|
||||
trackId: number;
|
||||
result: number;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface ZibalVerifyResponse {
|
||||
paidAt?: string;
|
||||
amount?: number;
|
||||
result: number;
|
||||
message: string;
|
||||
status?: number;
|
||||
refNumber?: string;
|
||||
description?: string;
|
||||
cardNumber?: string;
|
||||
orderId?: string;
|
||||
}
|
||||
|
||||
export interface ZibalInquiryResponse {
|
||||
paidAt?: string;
|
||||
amount?: number;
|
||||
result: number;
|
||||
message: string;
|
||||
status?: number;
|
||||
refNumber?: string;
|
||||
description?: string;
|
||||
cardNumber?: string;
|
||||
orderId?: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class ZibalService implements IPaymentGateway {
|
||||
private readonly logger = new Logger(ZibalService.name);
|
||||
private readonly baseUrl = 'https://gateway.zibal.ir';
|
||||
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
getGatewayName(): string {
|
||||
return 'zibal';
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper: Execute an HTTP operation with Exponential Backoff Retry (1s, 2s, 4s)
|
||||
*/
|
||||
private async callWithRetry<T>(
|
||||
operation: () => Promise<T>,
|
||||
operationName: string,
|
||||
maxRetries = 3,
|
||||
delays = [1000, 2000, 4000],
|
||||
): Promise<T> {
|
||||
let lastError: unknown;
|
||||
|
||||
for (let attempt = 1; attempt <= maxRetries; attempt++) {
|
||||
try {
|
||||
return await operation();
|
||||
} catch (err: unknown) {
|
||||
lastError = err;
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
this.logger.warn(
|
||||
`[Zibal Retry] Attempt ${attempt}/${maxRetries} failed for '${operationName}': ${msg}`,
|
||||
);
|
||||
|
||||
if (attempt < maxRetries) {
|
||||
const delayMs = delays[attempt - 1] || 1000;
|
||||
this.logger.log(`Waiting ${delayMs}ms before retry attempt ${attempt + 1}...`);
|
||||
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.logger.error(
|
||||
`[Zibal Retry] All ${maxRetries} attempts failed for '${operationName}'.`,
|
||||
);
|
||||
throw lastError;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves active merchant code from settings (DB) or fallback to env / 'zibal' sandbox.
|
||||
*/
|
||||
async getMerchant(): Promise<string> {
|
||||
try {
|
||||
const setting = await this.prisma.uiText.findUnique({
|
||||
where: { key: 'ZIBAL_MERCHANT' },
|
||||
});
|
||||
if (setting && setting.value && setting.value.trim() !== '') {
|
||||
return setting.value.trim();
|
||||
}
|
||||
} catch (e) {
|
||||
this.logger.warn(`Could not read ZIBAL_MERCHANT from db: ${e}`);
|
||||
}
|
||||
|
||||
return process.env.ZIBAL_MERCHANT || 'zibal';
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves base frontend/app url for callbacks
|
||||
*/
|
||||
async getFrontendUrl(): Promise<string> {
|
||||
try {
|
||||
const setting = await this.prisma.uiText.findUnique({
|
||||
where: { key: 'FRONTEND_URL' },
|
||||
});
|
||||
if (setting && setting.value && setting.value.trim() !== '') {
|
||||
return setting.value.trim().replace(/\/+$/, '');
|
||||
}
|
||||
} catch (e) {
|
||||
this.logger.warn(`Could not read FRONTEND_URL from db: ${e}`);
|
||||
}
|
||||
|
||||
const envUrl = process.env.FRONTEND_URL || process.env.APP_URL;
|
||||
return envUrl ? envUrl.replace(/\/+$/, '') : 'https://canina.ir';
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. Request Payment (درخواست پرداخت با قابلیت Retry)
|
||||
* Amount must be in Rials.
|
||||
*/
|
||||
async requestPayment(params: PaymentRequestOptions & {
|
||||
nationalCode?: string;
|
||||
allowedCards?: string[];
|
||||
}): Promise<ZibalRequestResponse> {
|
||||
const merchant = await this.getMerchant();
|
||||
|
||||
const payload = {
|
||||
merchant,
|
||||
amount: params.amountRials,
|
||||
callbackUrl: params.callbackUrl,
|
||||
description: params.description || 'پرداخت سفارش در پت شاپ کانینا',
|
||||
orderId: params.orderId,
|
||||
mobile: params.mobile,
|
||||
nationalCode: params.nationalCode,
|
||||
allowedCards: params.allowedCards,
|
||||
};
|
||||
|
||||
return this.callWithRetry(async () => {
|
||||
this.logger.log(
|
||||
`Sending payment request to Zibal for orderId=${params.orderId}, amount=${params.amountRials} Rials, merchant=${merchant}`,
|
||||
);
|
||||
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), 10000);
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.baseUrl}/v1/request`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
throw new Error(`Zibal request HTTP ${response.status}: ${errorText}`);
|
||||
}
|
||||
|
||||
const data = (await response.json()) as ZibalRequestResponse;
|
||||
return data;
|
||||
} finally {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
}, `requestPayment(orderId=${params.orderId})`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 2. Start URL for user redirect
|
||||
*/
|
||||
getStartUrl(trackId: string | number): string {
|
||||
return `${this.baseUrl}/start/${trackId}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 3. Verify Payment (تایید تراکنش با قابلیت Retry)
|
||||
*/
|
||||
async verifyPayment(trackId: string | number): Promise<ZibalVerifyResponse> {
|
||||
const merchant = await this.getMerchant();
|
||||
|
||||
const payload = {
|
||||
merchant,
|
||||
trackId: String(trackId),
|
||||
};
|
||||
|
||||
return this.callWithRetry(async () => {
|
||||
this.logger.log(`Verifying payment for trackId=${trackId}, merchant=${merchant}`);
|
||||
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), 10000);
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.baseUrl}/v1/verify`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
throw new Error(`Zibal verify HTTP ${response.status}: ${errorText}`);
|
||||
}
|
||||
|
||||
const data = (await response.json()) as ZibalVerifyResponse;
|
||||
return data;
|
||||
} finally {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
}, `verifyPayment(trackId=${trackId})`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 4. Inquiry Payment (استعلام تراکنش با قابلیت Retry)
|
||||
*/
|
||||
async inquiryPayment(trackId: string | number): Promise<ZibalInquiryResponse> {
|
||||
const merchant = await this.getMerchant();
|
||||
|
||||
const payload = {
|
||||
merchant,
|
||||
trackId: String(trackId),
|
||||
};
|
||||
|
||||
return this.callWithRetry(async () => {
|
||||
this.logger.log(`Inquiring payment for trackId=${trackId}`);
|
||||
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), 10000);
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.baseUrl}/v1/inquiry`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
throw new Error(`Zibal inquiry HTTP ${response.status}: ${errorText}`);
|
||||
}
|
||||
|
||||
const data = (await response.json()) as ZibalInquiryResponse;
|
||||
return data;
|
||||
} finally {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
}, `inquiryPayment(trackId=${trackId})`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 5. Health Check & Latency Monitor for Admin
|
||||
*/
|
||||
async checkHealth(): Promise<GatewayHealthResult> {
|
||||
const merchant = await this.getMerchant();
|
||||
const startTime = Date.now();
|
||||
|
||||
try {
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), 5000);
|
||||
|
||||
const res = await fetch(`${this.baseUrl}/v1/inquiry`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ merchant, trackId: '1' }),
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
clearTimeout(timeoutId);
|
||||
const latencyMs = Date.now() - startTime;
|
||||
|
||||
if (res.ok || res.status === 400 || res.status === 200) {
|
||||
return {
|
||||
gatewayName: 'Zibal IPG',
|
||||
status: latencyMs < 1500 ? 'ONLINE' : 'DEGRADED',
|
||||
latencyMs,
|
||||
merchantConfigured: merchant !== 'zibal',
|
||||
activeMerchant: merchant === 'zibal' ? 'zibal (تستی/سندباکس)' : `${merchant.slice(0, 4)}****`,
|
||||
message: 'اتصال به درگاه زیبال با موفقیت برقرار است',
|
||||
checkedAt: new Date(),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
gatewayName: 'Zibal IPG',
|
||||
status: 'DEGRADED',
|
||||
latencyMs,
|
||||
merchantConfigured: merchant !== 'zibal',
|
||||
activeMerchant: merchant,
|
||||
message: `پاسخ غیرعادی سرور زیبال (${res.status})`,
|
||||
checkedAt: new Date(),
|
||||
};
|
||||
} catch (err: unknown) {
|
||||
const latencyMs = Date.now() - startTime;
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
return {
|
||||
gatewayName: 'Zibal IPG',
|
||||
status: 'OFFLINE',
|
||||
latencyMs,
|
||||
merchantConfigured: merchant !== 'zibal',
|
||||
activeMerchant: merchant,
|
||||
message: `عدم دسترسی به درگاه: ${msg}`,
|
||||
checkedAt: new Date(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Human-friendly Persian messages for Zibal result codes
|
||||
*/
|
||||
getResultMessage(resultCode: number): string {
|
||||
const messages: Record<number, string> = {
|
||||
100: 'با موفقیت تایید شد',
|
||||
102: 'merchant یافت نشد',
|
||||
103: 'merchant غیرفعال است',
|
||||
104: 'merchant نامعتبر است',
|
||||
105: 'مبلغ باید بیشتر از ۱,۰۰۰ ریال باشد',
|
||||
106: 'callbackUrl نامعتبر است',
|
||||
113: 'مبلغ تراکنش بیش از سقف مجاز است',
|
||||
201: 'تراکنش قبلا تایید شده است',
|
||||
202: 'سفارش پرداخت نشده یا ناموفق بوده است',
|
||||
203: 'trackId نامعتبر است',
|
||||
};
|
||||
|
||||
return (
|
||||
messages[resultCode] ||
|
||||
`خطای ناشناخته در ارتباط با درگاه (کد ${resultCode})`
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Human-friendly Persian messages for Zibal status codes
|
||||
*/
|
||||
getStatusMessage(statusCode: number | string): string {
|
||||
const code = Number(statusCode);
|
||||
const messages: Record<number, string> = {
|
||||
'-1': 'در انتظار پردخت',
|
||||
'-2': 'خطای داخلی درگاه',
|
||||
'1': 'پرداخت شده و تایید شده',
|
||||
'2': 'پرداخت شده اما هنوز تایید نشده',
|
||||
'3': 'تراکنش توسط کاربر لغو شد',
|
||||
'4': 'شماره کارت نامعتبر است',
|
||||
'5': 'موجودی حساب کافی نیست',
|
||||
'6': 'رمز کارت اشتباه است',
|
||||
'7': 'تعداد دفعات ورود رمز غلط بیش از حد مجاز است',
|
||||
'8': 'کارت منقضی شده است',
|
||||
'9': 'مبلغ تراکنش بیش از سقف مجاز کارت است',
|
||||
'10': 'صادرکننده کارت نامعتبر است',
|
||||
'11': 'خطای سوییچ بانک صادرکننده',
|
||||
'12': 'کارت یا حساب مسدود است',
|
||||
};
|
||||
|
||||
return messages[code] || `وضعیت نامشخص (${statusCode})`;
|
||||
}
|
||||
}
|
||||
@ -1,15 +1,18 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Patch,
|
||||
Put,
|
||||
Delete,
|
||||
Body,
|
||||
Param,
|
||||
Query,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { SettingsService, ScientificTermData } from './settings.service';
|
||||
import { SmsLogQuery } from '../common/services/sms.service';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { RolesGuard } from '../common/guards/roles.guard';
|
||||
import { Roles } from '../common/decorators/roles.decorator';
|
||||
@ -20,7 +23,7 @@ import {
|
||||
ApiOkResponse,
|
||||
} from '@nestjs/swagger';
|
||||
|
||||
@ApiTags('Settings - تنظیمات متون پویا، تنظیمات سئو، مالی و سیستم')
|
||||
@ApiTags('Settings - تنظیمات متون پویا، تنظیمات سئو، مالی، سیستم و پیامک')
|
||||
@Controller('settings')
|
||||
export class SettingsController {
|
||||
constructor(private readonly settingsService: SettingsService) {}
|
||||
@ -125,4 +128,101 @@ export class SettingsController {
|
||||
updateSystemSettings(@Body() body: Prisma.InputJsonValue) {
|
||||
return this.settingsService.updateCategorySetting('system', body);
|
||||
}
|
||||
|
||||
// SMS Gateway Settings
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@ApiBearerAuth()
|
||||
@Get('sms')
|
||||
@ApiOperation({ summary: 'دریافت تنظیمات درگاه پیامک و کدهای پترن' })
|
||||
getSmsSettings() {
|
||||
return this.settingsService.getSmsSettings();
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@ApiBearerAuth()
|
||||
@Patch('sms')
|
||||
@ApiOperation({ summary: 'بهروزرسانی تنظیمات درگاه پیامک و کدهای پترن' })
|
||||
updateSmsSettings(@Body() body: Prisma.InputJsonValue) {
|
||||
return this.settingsService.updateSmsSettings(body);
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@ApiBearerAuth()
|
||||
@Post('sms/test')
|
||||
@ApiOperation({ summary: 'ارسال پیامک آزمایشی پترن به شماره دلخواه' })
|
||||
testSms(
|
||||
@Body('phone') phone: string,
|
||||
@Body('patternId') patternId?: number,
|
||||
@Body('args') args?: string[],
|
||||
) {
|
||||
return this.settingsService.testSms(phone, patternId, args);
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@ApiBearerAuth()
|
||||
@Get('sms/patterns')
|
||||
@ApiOperation({
|
||||
summary: 'دریافت لیست تمامی پترنهای تعریف شده در ملی پیامک',
|
||||
})
|
||||
getPatterns() {
|
||||
return this.settingsService.getPatterns();
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@ApiBearerAuth()
|
||||
@Post('sms/patterns')
|
||||
@ApiOperation({ summary: 'درج الگوی جدید در سامانه ملی پیامک' })
|
||||
addPattern(
|
||||
@Body('title') title: string,
|
||||
@Body('body') body: string,
|
||||
@Body('blackListId') blackListId?: number,
|
||||
) {
|
||||
return this.settingsService.addPattern(title, body, blackListId);
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@ApiBearerAuth()
|
||||
@Put('sms/patterns/:bodyId')
|
||||
@ApiOperation({
|
||||
summary: 'ویرایش الگوی رد شده یا در حال ویرایش در ملی پیامک',
|
||||
})
|
||||
editPattern(@Param('bodyId') bodyId: string, @Body('body') body: string) {
|
||||
return this.settingsService.editPattern(Number(bodyId), body);
|
||||
}
|
||||
|
||||
// SMS Logs & Tracking Endpoints
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@ApiBearerAuth()
|
||||
@Get('sms/logs')
|
||||
@ApiOperation({
|
||||
summary: 'دریافت گزارشات و لاگهای کامل پیامکهای ارسالی با فیلتر و جستجو',
|
||||
})
|
||||
getSmsLogs(@Query() query: SmsLogQuery) {
|
||||
return this.settingsService.getSmsLogs(query);
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@ApiBearerAuth()
|
||||
@Delete('sms/logs/:id')
|
||||
@ApiOperation({ summary: 'حذف یک رکورد لاگ پیامک' })
|
||||
deleteSmsLog(@Param('id') id: string) {
|
||||
return this.settingsService.deleteSmsLog(id);
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@ApiBearerAuth()
|
||||
@Delete('sms/logs')
|
||||
@ApiOperation({ summary: 'پاکسازی تمامی لاگهای پیامک' })
|
||||
clearAllSmsLogs() {
|
||||
return this.settingsService.clearAllSmsLogs();
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { SmsService, SmsLogQuery } from '../common/services/sms.service';
|
||||
|
||||
export class ScientificTermData {
|
||||
term?: string;
|
||||
@ -10,7 +11,10 @@ export class ScientificTermData {
|
||||
|
||||
@Injectable()
|
||||
export class SettingsService {
|
||||
constructor(private prisma: PrismaService) {}
|
||||
constructor(
|
||||
private prisma: PrismaService,
|
||||
private smsService: SmsService,
|
||||
) {}
|
||||
|
||||
async getUiTexts() {
|
||||
const [uiTexts, settings] = await Promise.all([
|
||||
@ -82,4 +86,45 @@ export class SettingsService {
|
||||
create: { key, category, value },
|
||||
});
|
||||
}
|
||||
|
||||
async getSmsSettings() {
|
||||
return this.smsService.getSmsConfig();
|
||||
}
|
||||
|
||||
async updateSmsSettings(value: Prisma.InputJsonValue) {
|
||||
const key = 'sms_config';
|
||||
return this.prisma.setting.upsert({
|
||||
where: { key },
|
||||
update: { category: 'sms', value },
|
||||
create: { key, category: 'sms', value },
|
||||
});
|
||||
}
|
||||
|
||||
async testSms(targetPhone: string, patternId?: number, args?: string[]) {
|
||||
return this.smsService.testSms(targetPhone, patternId, args);
|
||||
}
|
||||
|
||||
async getPatterns() {
|
||||
return this.smsService.getPatterns();
|
||||
}
|
||||
|
||||
async addPattern(title: string, body: string, blackListId?: number) {
|
||||
return this.smsService.addPattern(title, body, blackListId);
|
||||
}
|
||||
|
||||
async editPattern(bodyId: number, body: string) {
|
||||
return this.smsService.editPattern(bodyId, body);
|
||||
}
|
||||
|
||||
async getSmsLogs(query: SmsLogQuery) {
|
||||
return this.smsService.getSmsLogs(query);
|
||||
}
|
||||
|
||||
async deleteSmsLog(id: string) {
|
||||
return this.smsService.deleteSmsLog(id);
|
||||
}
|
||||
|
||||
async clearAllSmsLogs() {
|
||||
return this.smsService.clearAllSmsLogs();
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { Link, useLocation, useNavigate } from 'react-router-dom';
|
||||
import { Users, ShoppingCart, Tag, Settings, LogOut, TrendingUp, FolderTree, FileText, BookOpen, Heart, Package, LayoutDashboard, Languages, Image, Video, PhoneCall, Sparkles, MessageSquareQuote, FlaskConical, Building2, Globe, DollarSign, Sliders } from 'lucide-react';
|
||||
import { Users, ShoppingCart, Tag, Settings, LogOut, TrendingUp, FolderTree, FileText, BookOpen, Heart, Package, LayoutDashboard, Languages, Image, Video, PhoneCall, Sparkles, MessageSquareQuote, FlaskConical, Building2, Globe, DollarSign, Sliders, MessageSquare, Receipt, CreditCard } from 'lucide-react';
|
||||
import api from '../services/api';
|
||||
import { useAdminAuthStore } from '../store/adminAuthStore';
|
||||
|
||||
@ -16,6 +16,7 @@ const menuGroups = [
|
||||
title: 'فروشگاه و تخصصی',
|
||||
items: [
|
||||
{ icon: ShoppingCart, label: 'سفارشات', path: '/orders' },
|
||||
{ icon: Receipt, label: 'تراکنشها و لاگ پرداخت', path: '/transactions' },
|
||||
{ icon: Package, label: 'محصولات', path: '/products' },
|
||||
{ icon: FolderTree, label: 'دستهبندیها', path: '/categories' },
|
||||
{ icon: Tag, label: 'کدهای تخفیف', path: '/coupons' },
|
||||
@ -47,6 +48,7 @@ const menuGroups = [
|
||||
title: 'سیستم و تنظیمات',
|
||||
items: [
|
||||
{ icon: Settings, label: 'تنظیمات کلی', path: '/settings' },
|
||||
{ icon: MessageSquare, label: 'تنظیمات پیامک', path: '/settings/sms' },
|
||||
{ icon: Globe, label: 'تنظیمات سئو', path: '/settings/seo' },
|
||||
{ icon: DollarSign, label: 'تنظیمات مالی & ارسال', path: '/settings/financial' },
|
||||
{ icon: Sliders, label: 'تنظیمات سیستمی', path: '/settings/system' },
|
||||
@ -146,16 +148,7 @@ export default function Sidebar({ isOpen, setIsOpen }: SidebarProps) {
|
||||
</div>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
<div className="p-4 border-t border-gray-200">
|
||||
<button onClick={handleLogout} className="flex items-center gap-3 px-3 py-3 w-full text-red-500 hover:bg-red-50 rounded-xl transition-all font-bold">
|
||||
<LogOut className="w-5 h-5" />
|
||||
<span>خروج از حساب</span>
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Settings as SettingsIcon, Save, Truck, ShieldAlert, Percent, AlertCircle, CreditCard, Share2 } from 'lucide-react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { Settings as SettingsIcon, Save, Truck, ShieldAlert, Percent, AlertCircle, CreditCard, Share2, MessageSquare } from 'lucide-react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import api from '../services/api';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
@ -18,8 +19,11 @@ export default function Settings() {
|
||||
CHARITY_ROUND_STEP: '10000',
|
||||
PAY_GATEWAY_CARD_ENABLE: 'true',
|
||||
PAY_GATEWAY_WALLET_ENABLE: 'true',
|
||||
PAY_GATEWAY_ONLINE_ENABLE: 'false',
|
||||
PAY_GATEWAY_ONLINE_ENABLE: 'true',
|
||||
PAY_GATEWAY_COD_ENABLE: 'false',
|
||||
ZIBAL_MERCHANT: 'zibal',
|
||||
ZIBAL_SANDBOX: 'true',
|
||||
FRONTEND_URL: 'https://canina.ir',
|
||||
CONTACT_PHONE: '۰۲۱-۸۸۸۸ ۴۴۴۴',
|
||||
CONTACT_EMAIL: 'info@canina-iran.com',
|
||||
SOCIAL_WHATSAPP: '09120000000',
|
||||
@ -52,8 +56,11 @@ export default function Settings() {
|
||||
CHARITY_ROUND_STEP: response.data.data.CHARITY_ROUND_STEP || '10000',
|
||||
PAY_GATEWAY_CARD_ENABLE: response.data.data.PAY_GATEWAY_CARD_ENABLE || 'true',
|
||||
PAY_GATEWAY_WALLET_ENABLE: response.data.data.PAY_GATEWAY_WALLET_ENABLE || 'true',
|
||||
PAY_GATEWAY_ONLINE_ENABLE: response.data.data.PAY_GATEWAY_ONLINE_ENABLE || 'false',
|
||||
PAY_GATEWAY_ONLINE_ENABLE: response.data.data.PAY_GATEWAY_ONLINE_ENABLE || 'true',
|
||||
PAY_GATEWAY_COD_ENABLE: response.data.data.PAY_GATEWAY_COD_ENABLE || 'false',
|
||||
ZIBAL_MERCHANT: response.data.data.ZIBAL_MERCHANT || 'zibal',
|
||||
ZIBAL_SANDBOX: response.data.data.ZIBAL_SANDBOX || 'true',
|
||||
FRONTEND_URL: response.data.data.FRONTEND_URL || 'https://canina.ir',
|
||||
CONTACT_PHONE: response.data.data.CONTACT_PHONE || '۰۲۱-۸۸۸۸ ۴۴۴۴',
|
||||
CONTACT_EMAIL: response.data.data.CONTACT_EMAIL || 'info@canina-iran.com',
|
||||
SOCIAL_WHATSAPP: response.data.data.SOCIAL_WHATSAPP || '09120000000',
|
||||
@ -100,6 +107,15 @@ export default function Settings() {
|
||||
</h2>
|
||||
<p className="text-gray-500 font-medium mt-1">مدیریت پارامترهای اصلی و سیستمی کانینا</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<Link
|
||||
to="/settings/sms"
|
||||
className="bg-purple-50 text-purple-700 hover:bg-purple-100 border border-purple-200 text-xs font-bold px-4 py-2.5 rounded-xl transition-all flex items-center gap-2"
|
||||
>
|
||||
<MessageSquare className="w-4 h-4 text-purple-600" />
|
||||
تنظیمات درگاه پیامک (MeliPayamak)
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
@ -220,8 +236,8 @@ export default function Settings() {
|
||||
|
||||
<div className="flex items-center justify-between p-4 bg-gray-50 rounded-xl border border-gray-200">
|
||||
<div>
|
||||
<h4 className="font-bold text-gray-900 text-sm">درگاه آنلاین شتاب</h4>
|
||||
<p className="text-xs text-gray-500 mt-0.5">پرداخت الکترونیک (در صورت غیرفعال بودن: برچسب به زودی)</p>
|
||||
<h4 className="font-bold text-gray-900 text-sm">درگاه آنلاین شتاب (زیبال)</h4>
|
||||
<p className="text-xs text-gray-500 mt-0.5">پرداخت الکترونیک کلیه کارتهای عضو شتاب از طریق زیبال</p>
|
||||
</div>
|
||||
<label className="relative inline-flex items-center cursor-pointer">
|
||||
<input
|
||||
@ -250,6 +266,54 @@ export default function Settings() {
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Zibal Specific Configuration */}
|
||||
<div className="pt-4 border-t border-gray-100 space-y-4">
|
||||
<div className="flex items-center gap-2 text-indigo-700 font-black text-sm">
|
||||
<span>پیکربندی پایانه پرداخت اینترنتی زیبال (Zibal IPG)</span>
|
||||
{settings.ZIBAL_MERCHANT === 'zibal' && (
|
||||
<span className="bg-amber-100 text-amber-800 text-[10px] px-2 py-0.5 rounded-full font-bold">
|
||||
حالت تستی (Sandbox: zibal)
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 bg-indigo-50/50 p-4 rounded-xl border border-indigo-100">
|
||||
<div>
|
||||
<label className="block text-xs font-bold text-gray-700 mb-1">
|
||||
کد مرچنت زیبال (Merchant ID)
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={settings.ZIBAL_MERCHANT}
|
||||
onChange={(e) => setSettings({ ...settings, ZIBAL_MERCHANT: e.target.value })}
|
||||
placeholder="zibal"
|
||||
className="w-full border border-gray-200 rounded-xl p-2.5 outline-none focus:ring-2 focus:ring-purple-500 text-xs font-mono font-bold bg-white"
|
||||
dir="ltr"
|
||||
/>
|
||||
<p className="text-[11px] text-gray-500 mt-1">
|
||||
برای حالت تستی و آزمایش درگاه از مقدار <code>zibal</code> استفاده کنید.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-xs font-bold text-gray-700 mb-1">
|
||||
دامنه فرانتاند / آدرس بازگشت (Frontend Domain)
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={settings.FRONTEND_URL}
|
||||
onChange={(e) => setSettings({ ...settings, FRONTEND_URL: e.target.value })}
|
||||
placeholder="https://canina.ir"
|
||||
className="w-full border border-gray-200 rounded-xl p-2.5 outline-none focus:ring-2 focus:ring-purple-500 text-xs font-mono font-bold bg-white"
|
||||
dir="ltr"
|
||||
/>
|
||||
<p className="text-[11px] text-gray-500 mt-1">
|
||||
آدرس دامنهای که کاربر پس از پرداخت از زیبال به آن بازگردانده میشود.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Social Media & Contact Info Settings */}
|
||||
|
||||
1587
frontend/admin-panel/src/pages/SmsSettingsPage.tsx
Normal file
1587
frontend/admin-panel/src/pages/SmsSettingsPage.tsx
Normal file
File diff suppressed because it is too large
Load Diff
817
frontend/admin-panel/src/pages/Transactions.tsx
Normal file
817
frontend/admin-panel/src/pages/Transactions.tsx
Normal file
@ -0,0 +1,817 @@
|
||||
import React, { useState, useEffect, useCallback } from 'react';
|
||||
import {
|
||||
CreditCard,
|
||||
Search,
|
||||
RefreshCw,
|
||||
Eye,
|
||||
Copy,
|
||||
CheckCircle2,
|
||||
XCircle,
|
||||
Clock,
|
||||
Filter,
|
||||
DollarSign,
|
||||
TrendingUp,
|
||||
AlertTriangle,
|
||||
Receipt,
|
||||
User,
|
||||
ShoppingBag,
|
||||
ArrowUpDown,
|
||||
ExternalLink,
|
||||
ShieldCheck,
|
||||
RotateCcw,
|
||||
Activity,
|
||||
Globe,
|
||||
Monitor,
|
||||
Code
|
||||
} from 'lucide-react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import api from '../services/api';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import Pagination from '../components/ui/Pagination';
|
||||
|
||||
interface Transaction {
|
||||
id: string;
|
||||
userId: string;
|
||||
orderId?: string | null;
|
||||
amount: number | string;
|
||||
amountRials?: string | number | null;
|
||||
gateway: string;
|
||||
trackId?: string | null;
|
||||
refNumber?: string | null;
|
||||
cardNumber?: string | null;
|
||||
status: string;
|
||||
resultCode?: number | null;
|
||||
message?: string | null;
|
||||
description?: string | null;
|
||||
type: string;
|
||||
ipAddress?: string | null;
|
||||
userAgent?: string | null;
|
||||
rawRequest?: any;
|
||||
rawResponse?: any;
|
||||
paidAt?: string | null;
|
||||
createdAt: string;
|
||||
user?: {
|
||||
id: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
mobile: string;
|
||||
email?: string;
|
||||
} | null;
|
||||
order?: {
|
||||
id: string;
|
||||
trackingNumber?: string;
|
||||
totalAmount: number | string;
|
||||
status: string;
|
||||
paymentMethod?: string;
|
||||
} | null;
|
||||
}
|
||||
|
||||
interface Stats {
|
||||
totalCount: number;
|
||||
verifiedCount: number;
|
||||
pendingCount: number;
|
||||
failedCount: number;
|
||||
totalVolume: number;
|
||||
todayVolume: number;
|
||||
successRate: number;
|
||||
}
|
||||
|
||||
interface GatewayHealth {
|
||||
gatewayName: string;
|
||||
status: 'ONLINE' | 'DEGRADED' | 'OFFLINE';
|
||||
latencyMs: number;
|
||||
merchantConfigured: boolean;
|
||||
activeMerchant: string;
|
||||
message: string;
|
||||
checkedAt: string;
|
||||
}
|
||||
|
||||
export default function Transactions() {
|
||||
const [transactions, setTransactions] = useState<Transaction[]>([]);
|
||||
const [stats, setStats] = useState<Stats | null>(null);
|
||||
const [health, setHealth] = useState<GatewayHealth | null>(null);
|
||||
const [healthLoading, setHealthLoading] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [isReconciling, setIsReconciling] = useState(false);
|
||||
const [page, setPage] = useState(1);
|
||||
const [totalPages, setTotalPages] = useState(1);
|
||||
const [totalItems, setTotalItems] = useState(0);
|
||||
|
||||
// Filters
|
||||
const [search, setSearch] = useState('');
|
||||
const [statusFilter, setStatusFilter] = useState('');
|
||||
const [gatewayFilter, setGatewayFilter] = useState('');
|
||||
const [typeFilter, setTypeFilter] = useState('');
|
||||
const [sortBy, setSortBy] = useState('createdAt');
|
||||
const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc');
|
||||
|
||||
// Details Modal
|
||||
const [selectedTx, setSelectedTx] = useState<Transaction | null>(null);
|
||||
const [liveInquiryLoading, setLiveInquiryLoading] = useState(false);
|
||||
const [liveInquiryData, setLiveInquiryData] = useState<any>(null);
|
||||
const [showRawLogs, setShowRawLogs] = useState(false);
|
||||
|
||||
const fetchStats = async () => {
|
||||
try {
|
||||
const res = await api.get('/payment/admin/stats');
|
||||
if (res.data) {
|
||||
setStats(res.data);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to fetch stats', e);
|
||||
}
|
||||
};
|
||||
|
||||
const fetchHealth = async (silent = false) => {
|
||||
try {
|
||||
if (!silent) setHealthLoading(true);
|
||||
const res = await api.get('/payment/admin/health');
|
||||
if (res.data) {
|
||||
setHealth(res.data);
|
||||
if (!silent) toast.success(`وضعیت درگاه زیبال: ${res.data.status} (${res.data.latencyMs}ms)`);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to fetch gateway health', e);
|
||||
if (!silent) toast.error('عدم دسترسی به سرویس Health Check درگاه');
|
||||
} finally {
|
||||
if (!silent) setHealthLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const fetchTransactions = useCallback(async () => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const params = new URLSearchParams();
|
||||
params.append('page', String(page));
|
||||
params.append('limit', '15');
|
||||
if (search) params.append('search', search);
|
||||
if (statusFilter) params.append('status', statusFilter);
|
||||
if (gatewayFilter) params.append('gateway', gatewayFilter);
|
||||
if (typeFilter) params.append('type', typeFilter);
|
||||
params.append('sortBy', sortBy);
|
||||
params.append('sortOrder', sortOrder);
|
||||
|
||||
const res = await api.get(`/payment/admin/transactions?${params.toString()}`);
|
||||
if (res.data) {
|
||||
setTransactions(res.data.data || []);
|
||||
setTotalPages(res.data.meta?.lastPage || 1);
|
||||
setTotalItems(res.data.meta?.total || 0);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to fetch transactions', e);
|
||||
toast.error('خطا در بارگذاری لیست تراکنشها');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [page, search, statusFilter, gatewayFilter, typeFilter, sortBy, sortOrder]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchTransactions();
|
||||
fetchStats();
|
||||
fetchHealth(true);
|
||||
}, [fetchTransactions]);
|
||||
|
||||
const handleCopy = (text: string, title: string) => {
|
||||
navigator.clipboard.writeText(text);
|
||||
toast.success(`${title} کپی شد!`);
|
||||
};
|
||||
|
||||
const handleReconcile = async () => {
|
||||
try {
|
||||
setIsReconciling(true);
|
||||
const res = await api.post('/payment/admin/reconcile');
|
||||
toast.success(
|
||||
`انطباق انجام شد: ${res.data.verified} تایید شده، ${res.data.failed} ناموفق`,
|
||||
);
|
||||
fetchTransactions();
|
||||
fetchStats();
|
||||
} catch (e) {
|
||||
console.error('Reconcile error', e);
|
||||
toast.error('خطا در اجرای استعلام خودکار');
|
||||
} finally {
|
||||
setIsReconciling(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleLiveInquiry = async (txId: string) => {
|
||||
try {
|
||||
setLiveInquiryLoading(true);
|
||||
const res = await api.get(`/payment/admin/live-inquiry/${txId}`);
|
||||
setLiveInquiryData(res.data);
|
||||
toast.success('استعلام زنده زیبال با موفقیت دریافت شد');
|
||||
fetchTransactions();
|
||||
fetchStats();
|
||||
} catch (e: any) {
|
||||
const msg = e.response?.data?.message || 'خطا در استعلام از درگاه زیبال';
|
||||
toast.error(msg);
|
||||
} finally {
|
||||
setLiveInquiryLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
|
||||
<div>
|
||||
<h2 className="text-2xl font-black text-gray-900 flex items-center gap-2">
|
||||
<Receipt className="w-7 h-7 text-purple-600" />
|
||||
لاگها و مدیریت تراکنشهای مالی
|
||||
</h2>
|
||||
<p className="text-gray-500 font-medium mt-1">
|
||||
رهگیری لحظهای پرداختهای آنلاین زیبال، بررسی لاگهای خام و عیبیابی تراکنشها
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<button
|
||||
onClick={() => fetchHealth(false)}
|
||||
disabled={healthLoading}
|
||||
className="bg-purple-50 text-purple-700 hover:bg-purple-100 border border-purple-200 text-xs font-bold px-3.5 py-2.5 rounded-xl transition-all flex items-center gap-2 shadow-sm disabled:opacity-50"
|
||||
>
|
||||
<Activity className={`w-4 h-4 text-purple-600 ${healthLoading ? 'animate-spin' : ''}`} />
|
||||
<span>پایش سلامت درگاه (Ping)</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={handleReconcile}
|
||||
disabled={isReconciling}
|
||||
className="bg-indigo-50 text-indigo-700 hover:bg-indigo-100 border border-indigo-200 text-xs font-bold px-3.5 py-2.5 rounded-xl transition-all flex items-center gap-2 shadow-sm disabled:opacity-50"
|
||||
>
|
||||
<RotateCcw className={`w-4 h-4 ${isReconciling ? 'animate-spin' : ''}`} />
|
||||
<span>{isReconciling ? 'در حال استعلام...' : 'انطباق خودکار تراکنشها'}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Gateway Health Monitor Banner */}
|
||||
{health && (
|
||||
<div className="bg-gradient-to-r from-slate-900 via-indigo-950 to-purple-950 p-4 rounded-2xl text-white shadow-md flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 border border-indigo-800/40">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="relative flex items-center justify-center">
|
||||
<span className={`w-3.5 h-3.5 rounded-full ${health.status === 'ONLINE' ? 'bg-emerald-500 animate-ping' : health.status === 'DEGRADED' ? 'bg-amber-500' : 'bg-rose-500'}`} />
|
||||
<span className={`absolute w-2.5 h-2.5 rounded-full ${health.status === 'ONLINE' ? 'bg-emerald-400' : health.status === 'DEGRADED' ? 'bg-amber-400' : 'bg-rose-400'}`} />
|
||||
</div>
|
||||
<div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-black text-sm">{health.gatewayName}</span>
|
||||
<span className={`text-[10px] font-black px-2 py-0.5 rounded-full ${health.status === 'ONLINE' ? 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30' : 'bg-amber-500/20 text-amber-300 border border-amber-500/30'}`}>
|
||||
{health.status}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-[11px] text-gray-300 mt-0.5">{health.message}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-4 text-xs font-mono text-gray-300 mr-auto sm:mr-0">
|
||||
<div className="bg-white/10 px-3 py-1.5 rounded-xl border border-white/10 flex items-center gap-1.5">
|
||||
<Clock className="w-3.5 h-3.5 text-purple-300" />
|
||||
<span>تاخیر: <strong>{health.latencyMs} ms</strong></span>
|
||||
</div>
|
||||
<div className="bg-white/10 px-3 py-1.5 rounded-xl border border-white/10 flex items-center gap-1.5">
|
||||
<ShieldCheck className="w-3.5 h-3.5 text-emerald-300" />
|
||||
<span>مرچنت: <strong>{health.activeMerchant}</strong></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Summary Stat Cards */}
|
||||
{stats && (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||
<div className="bg-white p-5 rounded-2xl border border-gray-200 shadow-sm flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-xs font-bold text-gray-500">حجم کل تراکنشهای موفق</p>
|
||||
<p className="text-xl font-black text-gray-900 mt-1">
|
||||
{Number(stats.totalVolume).toLocaleString('fa-IR')}{' '}
|
||||
<span className="text-xs font-normal text-gray-400">تومان</span>
|
||||
</p>
|
||||
</div>
|
||||
<div className="w-12 h-12 bg-purple-50 text-purple-600 rounded-2xl flex items-center justify-center">
|
||||
<DollarSign className="w-6 h-6" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white p-5 rounded-2xl border border-gray-200 shadow-sm flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-xs font-bold text-gray-500">پرداختهای موفق امروز</p>
|
||||
<p className="text-xl font-black text-emerald-600 mt-1">
|
||||
{Number(stats.todayVolume).toLocaleString('fa-IR')}{' '}
|
||||
<span className="text-xs font-normal text-gray-400">تومان</span>
|
||||
</p>
|
||||
</div>
|
||||
<div className="w-12 h-12 bg-emerald-50 text-emerald-600 rounded-2xl flex items-center justify-center">
|
||||
<TrendingUp className="w-6 h-6" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white p-5 rounded-2xl border border-gray-200 shadow-sm flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-xs font-bold text-gray-500">نرخ موفقیت پرداختها</p>
|
||||
<p className="text-xl font-black text-indigo-600 mt-1">
|
||||
٪{Number(stats.successRate).toLocaleString('fa-IR')}
|
||||
</p>
|
||||
</div>
|
||||
<div className="w-12 h-12 bg-indigo-50 text-indigo-600 rounded-2xl flex items-center justify-center">
|
||||
<ShieldCheck className="w-6 h-6" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white p-5 rounded-2xl border border-gray-200 shadow-sm flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-xs font-bold text-gray-500">وضعیت تراکنشها</p>
|
||||
<div className="flex items-center gap-3 mt-1 text-xs font-bold">
|
||||
<span className="text-emerald-600">✓ {stats.verifiedCount}</span>
|
||||
<span className="text-amber-500">⏳ {stats.pendingCount}</span>
|
||||
<span className="text-rose-600">✗ {stats.failedCount}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="w-12 h-12 bg-gray-50 text-gray-600 rounded-2xl flex items-center justify-center">
|
||||
<Receipt className="w-6 h-6" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Filter and Search Bar */}
|
||||
<div className="bg-white p-5 rounded-2xl border border-gray-200 shadow-sm space-y-4">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-3">
|
||||
{/* Search Input */}
|
||||
<div className="lg:col-span-2 relative">
|
||||
<Search className="w-4 h-4 text-gray-400 absolute right-3.5 top-3.5" />
|
||||
<input
|
||||
type="text"
|
||||
value={search}
|
||||
onChange={(e) => {
|
||||
setSearch(e.target.value);
|
||||
setPage(1);
|
||||
}}
|
||||
placeholder="جستجو بر اساس نام، موبایل، Track ID، شماره مرجع..."
|
||||
className="w-full pl-3 pr-10 py-2.5 bg-gray-50 border border-gray-200 rounded-xl text-xs font-bold outline-none focus:ring-2 focus:ring-purple-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Status Filter */}
|
||||
<div>
|
||||
<select
|
||||
value={statusFilter}
|
||||
onChange={(e) => {
|
||||
setStatusFilter(e.target.value);
|
||||
setPage(1);
|
||||
}}
|
||||
className="w-full py-2.5 px-3 bg-gray-50 border border-gray-200 rounded-xl text-xs font-bold outline-none focus:ring-2 focus:ring-purple-500"
|
||||
>
|
||||
<option value="">همه وضعیتها</option>
|
||||
<option value="VERIFIED">موفق (VERIFIED)</option>
|
||||
<option value="PENDING">در انتظار (PENDING)</option>
|
||||
<option value="FAILED">ناموفق (FAILED)</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Gateway Filter */}
|
||||
<div>
|
||||
<select
|
||||
value={gatewayFilter}
|
||||
onChange={(e) => {
|
||||
setGatewayFilter(e.target.value);
|
||||
setPage(1);
|
||||
}}
|
||||
className="w-full py-2.5 px-3 bg-gray-50 border border-gray-200 rounded-xl text-xs font-bold outline-none focus:ring-2 focus:ring-purple-500"
|
||||
>
|
||||
<option value="">همه درگاهها</option>
|
||||
<option value="zibal">درگاه زیبال (Zibal)</option>
|
||||
<option value="wallet">کیف پول (Wallet)</option>
|
||||
<option value="card">کارت به کارت</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Type Filter */}
|
||||
<div>
|
||||
<select
|
||||
value={typeFilter}
|
||||
onChange={(e) => {
|
||||
setTypeFilter(e.target.value);
|
||||
setPage(1);
|
||||
}}
|
||||
className="w-full py-2.5 px-3 bg-gray-50 border border-gray-200 rounded-xl text-xs font-bold outline-none focus:ring-2 focus:ring-purple-500"
|
||||
>
|
||||
<option value="">همه انواع</option>
|
||||
<option value="ORDER">پرداخت سفارش (ORDER)</option>
|
||||
<option value="WALLET_TOPUP">شارژ کیف پول (TOPUP)</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Total records found */}
|
||||
<div className="flex items-center justify-between text-xs text-gray-500 font-bold pt-2 border-t border-gray-100">
|
||||
<span>مجموع {totalItems.toLocaleString('fa-IR')} تراکنش ثبت شده</span>
|
||||
<button
|
||||
onClick={() => {
|
||||
setSearch('');
|
||||
setStatusFilter('');
|
||||
setGatewayFilter('');
|
||||
setTypeFilter('');
|
||||
setPage(1);
|
||||
}}
|
||||
className="text-purple-600 hover:underline"
|
||||
>
|
||||
پاک کردن فیلترها
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Transactions Table */}
|
||||
<div className="bg-white rounded-2xl border border-gray-200 shadow-sm overflow-hidden">
|
||||
{isLoading ? (
|
||||
<div className="p-12 flex justify-center">
|
||||
<Spinner size="lg" className="text-purple-600" />
|
||||
</div>
|
||||
) : transactions.length === 0 ? (
|
||||
<div className="p-12 text-center text-gray-500 font-bold">
|
||||
هیچ تراکنشی با فیلترهای مشخص شده یافت نشد.
|
||||
</div>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-right border-collapse">
|
||||
<thead>
|
||||
<tr className="bg-gray-50/80 border-b border-gray-200 text-[11px] font-black text-gray-500">
|
||||
<th className="p-4">کاربر خریدار</th>
|
||||
<th className="p-4">سفارش / نوع</th>
|
||||
<th className="p-4">مبلغ (تومان)</th>
|
||||
<th className="p-4">درگاه</th>
|
||||
<th className="p-4">شناسههای پرداخت</th>
|
||||
<th className="p-4">وضعیت</th>
|
||||
<th className="p-4">تاریخ و زمان</th>
|
||||
<th className="p-4 text-center">عملیات</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-100 text-xs font-bold">
|
||||
{transactions.map((tx) => {
|
||||
const isVerified = tx.status === 'VERIFIED';
|
||||
const isPending = tx.status === 'PENDING';
|
||||
const isFailed = tx.status === 'FAILED';
|
||||
|
||||
return (
|
||||
<tr key={tx.id} className="hover:bg-gray-50/60 transition-colors">
|
||||
{/* User Info */}
|
||||
<td className="p-4">
|
||||
{tx.user ? (
|
||||
<div>
|
||||
<p className="font-black text-gray-900">
|
||||
{tx.user.firstName} {tx.user.lastName}
|
||||
</p>
|
||||
<p className="text-[11px] text-gray-400 font-mono mt-0.5 dir-ltr text-right">
|
||||
{tx.user.mobile}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<span className="text-gray-400">کاربر مهمان</span>
|
||||
)}
|
||||
</td>
|
||||
|
||||
{/* Order / Type */}
|
||||
<td className="p-4">
|
||||
{tx.type === 'WALLET_TOPUP' ? (
|
||||
<span className="bg-blue-50 text-blue-700 px-2.5 py-1 rounded-lg text-[10px] font-black">
|
||||
شارژ کیف پول
|
||||
</span>
|
||||
) : (
|
||||
<div>
|
||||
<span className="text-purple-700 font-mono text-[11px] font-black dir-ltr block">
|
||||
{tx.order?.trackingNumber || 'سفارش آنلاین'}
|
||||
</span>
|
||||
<span className="text-[10px] text-gray-400 font-medium">
|
||||
خرید محصول
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
|
||||
{/* Amount */}
|
||||
<td className="p-4 font-black text-gray-900 font-mono text-sm">
|
||||
{Number(tx.amount).toLocaleString('fa-IR')}
|
||||
</td>
|
||||
|
||||
{/* Gateway */}
|
||||
<td className="p-4">
|
||||
<span className="bg-indigo-50 text-indigo-700 px-2.5 py-1 rounded-lg text-[10px] font-black">
|
||||
{tx.gateway === 'zibal' ? 'زیبال (Zibal)' : tx.gateway}
|
||||
</span>
|
||||
</td>
|
||||
|
||||
{/* Tracking Numbers */}
|
||||
<td className="p-4 font-mono text-[11px]">
|
||||
{tx.trackId && (
|
||||
<div className="flex items-center gap-1 text-gray-800">
|
||||
<span className="text-gray-400 text-[10px]">Track:</span>
|
||||
<span className="dir-ltr">{tx.trackId}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleCopy(tx.trackId!, 'Track ID')}
|
||||
className="text-gray-400 hover:text-purple-600"
|
||||
>
|
||||
<Copy className="w-3 h-3" />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{tx.refNumber && (
|
||||
<div className="flex items-center gap-1 text-emerald-700 mt-0.5">
|
||||
<span className="text-gray-400 text-[10px]">Ref:</span>
|
||||
<span className="dir-ltr">{tx.refNumber}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleCopy(tx.refNumber!, 'شماره مرجع')}
|
||||
className="text-gray-400 hover:text-purple-600"
|
||||
>
|
||||
<Copy className="w-3 h-3" />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
|
||||
{/* Status */}
|
||||
<td className="p-4">
|
||||
{isVerified && (
|
||||
<span className="inline-flex items-center gap-1 bg-emerald-50 text-emerald-700 border border-emerald-200 px-2.5 py-1 rounded-full text-[10px] font-black">
|
||||
<CheckCircle2 className="w-3 h-3" />
|
||||
موفق
|
||||
</span>
|
||||
)}
|
||||
{isPending && (
|
||||
<span className="inline-flex items-center gap-1 bg-amber-50 text-amber-700 border border-amber-200 px-2.5 py-1 rounded-full text-[10px] font-black">
|
||||
<Clock className="w-3 h-3" />
|
||||
در انتظار
|
||||
</span>
|
||||
)}
|
||||
{isFailed && (
|
||||
<span className="inline-flex items-center gap-1 bg-rose-50 text-rose-700 border border-rose-200 px-2.5 py-1 rounded-full text-[10px] font-black">
|
||||
<XCircle className="w-3 h-3" />
|
||||
ناموفق
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
|
||||
{/* Date */}
|
||||
<td className="p-4 text-[11px] text-gray-500">
|
||||
{new Date(tx.createdAt).toLocaleDateString('fa-IR', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
})}
|
||||
</td>
|
||||
|
||||
{/* Actions */}
|
||||
<td className="p-4 text-center">
|
||||
<div className="flex items-center justify-center gap-1.5">
|
||||
<button
|
||||
onClick={() => {
|
||||
setSelectedTx(tx);
|
||||
setLiveInquiryData(null);
|
||||
setShowRawLogs(false);
|
||||
}}
|
||||
className="p-2 bg-gray-100 hover:bg-purple-50 text-gray-600 hover:text-purple-600 rounded-xl transition-all"
|
||||
title="مشاهده جزئیات و عیبیابی"
|
||||
>
|
||||
<Eye className="w-4 h-4" />
|
||||
</button>
|
||||
|
||||
{tx.gateway === 'zibal' && tx.trackId && (
|
||||
<button
|
||||
onClick={() => {
|
||||
setSelectedTx(tx);
|
||||
handleLiveInquiry(tx.id);
|
||||
}}
|
||||
className="p-2 bg-indigo-50 hover:bg-indigo-100 text-indigo-600 rounded-xl transition-all"
|
||||
title="استعلام زنده از زیبال"
|
||||
>
|
||||
<RotateCcw className="w-4 h-4" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Pagination */}
|
||||
<div className="p-4 border-t border-gray-100">
|
||||
<Pagination
|
||||
currentPage={page}
|
||||
totalPages={totalPages}
|
||||
onPageChange={(p) => setPage(p)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Diagnostics and Details Modal */}
|
||||
{selectedTx && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
|
||||
<div className="bg-white rounded-3xl w-full max-w-2xl max-h-[90vh] overflow-y-auto border border-gray-200 shadow-2xl p-6 sm:p-8 space-y-6">
|
||||
<div className="flex items-center justify-between border-b border-gray-100 pb-4">
|
||||
<h3 className="text-lg font-black text-gray-900 flex items-center gap-2">
|
||||
<Receipt className="w-5 h-5 text-purple-600" />
|
||||
جزئیات تراکنش و ریشهیابی خطا
|
||||
</h3>
|
||||
<button
|
||||
onClick={() => {
|
||||
setSelectedTx(null);
|
||||
setLiveInquiryData(null);
|
||||
}}
|
||||
className="text-gray-400 hover:text-gray-700 text-xl font-bold"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Quick Grid Info */}
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 gap-3 text-xs bg-gray-50 p-4 rounded-2xl border border-gray-200">
|
||||
<div>
|
||||
<span className="text-gray-400 block font-medium">وضعیت تراکنش:</span>
|
||||
<span
|
||||
className={`font-black mt-0.5 inline-block ${
|
||||
selectedTx.status === 'VERIFIED'
|
||||
? 'text-emerald-600'
|
||||
: selectedTx.status === 'PENDING'
|
||||
? 'text-amber-500'
|
||||
: 'text-rose-600'
|
||||
}`}
|
||||
>
|
||||
{selectedTx.status}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<span className="text-gray-400 block font-medium">مبلغ تراکنش:</span>
|
||||
<span className="font-black text-gray-900 mt-0.5 inline-block">
|
||||
{Number(selectedTx.amount).toLocaleString('fa-IR')} تومان
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<span className="text-gray-400 block font-medium">درگاه پرداخت:</span>
|
||||
<span className="font-black text-gray-900 mt-0.5 inline-block">
|
||||
{selectedTx.gateway}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<span className="text-gray-400 block font-medium">شناسه پیگیری (Track ID):</span>
|
||||
<span className="font-mono font-bold text-gray-900 dir-ltr inline-block">
|
||||
{selectedTx.trackId || 'ثبت نشده'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<span className="text-gray-400 block font-medium">شماره مرجع بانکی:</span>
|
||||
<span className="font-mono font-bold text-gray-900 dir-ltr inline-block">
|
||||
{selectedTx.refNumber || 'ثبت نشده'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<span className="text-gray-400 block font-medium">شماره کارت ماسک شده:</span>
|
||||
<span className="font-mono font-bold text-gray-900 dir-ltr inline-block">
|
||||
{selectedTx.cardNumber || 'ثبت نشده'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{selectedTx.ipAddress && (
|
||||
<div>
|
||||
<span className="text-gray-400 block font-medium">IP کلاینت:</span>
|
||||
<span className="font-mono font-bold text-gray-700 dir-ltr inline-block">
|
||||
{selectedTx.ipAddress}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{selectedTx.userAgent && (
|
||||
<div className="sm:col-span-2">
|
||||
<span className="text-gray-400 block font-medium">User-Agent دستگاه:</span>
|
||||
<span className="text-[10px] font-mono text-gray-600 line-clamp-1 dir-ltr inline-block">
|
||||
{selectedTx.userAgent}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Error Message / Reason */}
|
||||
{selectedTx.message && (
|
||||
<div
|
||||
className={`p-4 rounded-2xl border ${
|
||||
selectedTx.status === 'VERIFIED'
|
||||
? 'bg-emerald-50 border-emerald-200 text-emerald-900'
|
||||
: 'bg-rose-50 border-rose-200 text-rose-900'
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-center gap-2 font-black text-xs mb-1">
|
||||
{selectedTx.status === 'VERIFIED' ? (
|
||||
<CheckCircle2 className="w-4 h-4 text-emerald-600" />
|
||||
) : (
|
||||
<AlertTriangle className="w-4 h-4 text-rose-600" />
|
||||
)}
|
||||
<span>پیام و نتیجه گزارش درگاه:</span>
|
||||
</div>
|
||||
<p className="text-xs font-bold leading-relaxed">{selectedTx.message}</p>
|
||||
{selectedTx.resultCode && (
|
||||
<p className="text-[11px] font-mono mt-1 text-gray-500">
|
||||
کد نتیجه زیبال: {selectedTx.resultCode}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Live Inquiry Section */}
|
||||
<div className="border border-indigo-100 bg-indigo-50/50 p-5 rounded-2xl space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<RotateCcw className="w-4 h-4 text-indigo-600" />
|
||||
<h4 className="font-black text-xs text-indigo-900">
|
||||
استعلام زنده از سرور زیبال (Live Gateway Inquiry)
|
||||
</h4>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={() => handleLiveInquiry(selectedTx.id)}
|
||||
disabled={liveInquiryLoading}
|
||||
className="bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-bold px-3 py-1.5 rounded-xl transition-all flex items-center gap-1.5 disabled:opacity-50"
|
||||
>
|
||||
<RefreshCw
|
||||
className={`w-3.5 h-3.5 ${liveInquiryLoading ? 'animate-spin' : ''}`}
|
||||
/>
|
||||
<span>استعلام زنده لحظهای</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{liveInquiryData && (
|
||||
<div className="bg-white p-4 rounded-xl border border-indigo-200 space-y-2 text-xs font-mono">
|
||||
<div className="flex justify-between text-gray-700 font-bold font-vazir">
|
||||
<span>وضعیت زیبال:</span>
|
||||
<span className="text-indigo-600">{liveInquiryData.statusMessage}</span>
|
||||
</div>
|
||||
<pre className="text-[11px] bg-slate-900 text-emerald-400 p-3 rounded-lg overflow-x-auto dir-ltr">
|
||||
{JSON.stringify(liveInquiryData.gatewayResponse, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Raw Request & Response Inspector Toggle */}
|
||||
<div className="border border-gray-200 rounded-2xl overflow-hidden">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowRawLogs(!showRawLogs)}
|
||||
className="w-full bg-gray-50 hover:bg-gray-100 px-4 py-3 text-xs font-bold text-gray-700 flex items-center justify-between transition-colors"
|
||||
>
|
||||
<span className="flex items-center gap-2">
|
||||
<Code className="w-4 h-4 text-purple-600" />
|
||||
مشاهده لاگ خام درخواست و پاسخ (Raw JSON Payload)
|
||||
</span>
|
||||
<span>{showRawLogs ? '▲ بستن' : '▼ باز کردن'}</span>
|
||||
</button>
|
||||
|
||||
{showRawLogs && (
|
||||
<div className="p-4 bg-slate-950 text-emerald-400 text-[11px] font-mono space-y-4 dir-ltr overflow-x-auto">
|
||||
{selectedTx.rawRequest && (
|
||||
<div>
|
||||
<p className="text-purple-400 font-bold mb-1">// Raw Request:</p>
|
||||
<pre className="p-2 bg-slate-900 rounded-lg">{JSON.stringify(selectedTx.rawRequest, null, 2)}</pre>
|
||||
</div>
|
||||
)}
|
||||
{selectedTx.rawResponse && (
|
||||
<div>
|
||||
<p className="text-cyan-400 font-bold mb-1">// Raw Response:</p>
|
||||
<pre className="p-2 bg-slate-900 rounded-lg">{JSON.stringify(selectedTx.rawResponse, null, 2)}</pre>
|
||||
</div>
|
||||
)}
|
||||
{!selectedTx.rawRequest && !selectedTx.rawResponse && (
|
||||
<p className="text-gray-500">// لاگ خامی برای این تراکنش ثبت نشده است.</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Close Button */}
|
||||
<div className="flex justify-end">
|
||||
<button
|
||||
onClick={() => {
|
||||
setSelectedTx(null);
|
||||
setLiveInquiryData(null);
|
||||
setShowRawLogs(false);
|
||||
}}
|
||||
className="bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold px-6 py-2.5 rounded-xl text-xs transition-colors"
|
||||
>
|
||||
بستن
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -33,6 +33,8 @@ const B2BManager = lazy(() => import('../pages/B2BManager'));
|
||||
const SeoSettingsPage = lazy(() => import('../pages/SeoSettingsPage'));
|
||||
const FinancialSettingsPage = lazy(() => import('../pages/FinancialSettingsPage'));
|
||||
const SystemSettingsPage = lazy(() => import('../pages/SystemSettingsPage'));
|
||||
const SmsSettingsPage = lazy(() => import('../pages/SmsSettingsPage'));
|
||||
const Transactions = lazy(() => import('../pages/Transactions'));
|
||||
|
||||
export interface AdminRouteConfig {
|
||||
path: string;
|
||||
@ -56,8 +58,10 @@ export const router = createBrowserRouter([
|
||||
{ path: 'users/*', element: <Users /> },
|
||||
{ path: 'products/*', element: <Products /> },
|
||||
{ path: 'orders/*', element: <Orders /> },
|
||||
{ path: 'transactions/*', element: <Transactions /> },
|
||||
{ path: 'coupons/*', element: <Coupons /> },
|
||||
{ path: 'settings/*', element: <Settings /> },
|
||||
{ path: 'settings', element: <Settings /> },
|
||||
{ path: 'settings/sms', element: <SmsSettingsPage /> },
|
||||
{ path: 'settings/seo', element: <SeoSettingsPage /> },
|
||||
{ path: 'settings/financial', element: <FinancialSettingsPage /> },
|
||||
{ path: 'settings/system', element: <SystemSettingsPage /> },
|
||||
|
||||
291
frontend/application/app/payment/verify/page.tsx
Normal file
291
frontend/application/app/payment/verify/page.tsx
Normal file
@ -0,0 +1,291 @@
|
||||
"use client";
|
||||
import React, { Suspense, useEffect, useState } from "react";
|
||||
import { useSearchParams, useRouter } from "next/navigation";
|
||||
import {
|
||||
CheckCircle2,
|
||||
XCircle,
|
||||
Clock,
|
||||
ArrowRight,
|
||||
ShoppingBag,
|
||||
RotateCcw,
|
||||
Copy,
|
||||
Receipt,
|
||||
ShieldCheck,
|
||||
CreditCard,
|
||||
Building,
|
||||
} from "lucide-react";
|
||||
import { toPersian, cn } from "../../../lib/utils";
|
||||
import { toast } from "sonner";
|
||||
import { useCartStore } from "../../../lib/store/cartStore";
|
||||
import { useUserStore } from "../../../lib/store/userStore";
|
||||
import api from "../../../lib/services/api";
|
||||
|
||||
function VerifyContent() {
|
||||
const searchParams = useSearchParams();
|
||||
const router = useRouter();
|
||||
|
||||
const successParam = searchParams.get("success");
|
||||
const trackId = searchParams.get("trackId") || "";
|
||||
const orderId = searchParams.get("orderId") || "";
|
||||
const refNumber = searchParams.get("refNumber") || "";
|
||||
const cardNumber = searchParams.get("cardNumber") || "";
|
||||
const messageParam = searchParams.get("message") || "";
|
||||
const amountParam = searchParams.get("amount") || "";
|
||||
const paymentType = searchParams.get("type") || "ORDER";
|
||||
|
||||
const isSuccess = successParam === "1";
|
||||
const [orderDetails, setOrderDetails] = useState<any>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [retrying, setRetrying] = useState(false);
|
||||
|
||||
const { clearCart } = useCartStore();
|
||||
const { fetchProfile } = useUserStore();
|
||||
|
||||
useEffect(() => {
|
||||
if (isSuccess) {
|
||||
clearCart();
|
||||
fetchProfile().catch(() => {});
|
||||
}
|
||||
|
||||
if (orderId) {
|
||||
setLoading(true);
|
||||
api
|
||||
.get(`/orders/${orderId}`)
|
||||
.then((res) => {
|
||||
if (res.data) setOrderDetails(res.data);
|
||||
})
|
||||
.catch(() => {})
|
||||
.finally(() => setLoading(false));
|
||||
}
|
||||
}, [isSuccess, orderId, clearCart, fetchProfile]);
|
||||
|
||||
const handleCopy = (text: string, title: string) => {
|
||||
navigator.clipboard.writeText(text);
|
||||
toast.success(`${title} با موفقیت کپی شد!`);
|
||||
};
|
||||
|
||||
const handleRetryPayment = async () => {
|
||||
if (!orderId) {
|
||||
router.push("/checkout");
|
||||
return;
|
||||
}
|
||||
|
||||
setRetrying(true);
|
||||
try {
|
||||
const res = await api.post("/payment/zibal/initiate", { orderId });
|
||||
if (res.data?.paymentUrl) {
|
||||
window.location.href = res.data.paymentUrl;
|
||||
} else {
|
||||
toast.error("خطا در ایجاد درگاه پرداخت جدید");
|
||||
}
|
||||
} catch (err: any) {
|
||||
const errorMsg =
|
||||
err.response?.data?.message ||
|
||||
err.message ||
|
||||
"خطا در ایجاد اتصال مجدد به درگاه";
|
||||
toast.error(errorMsg);
|
||||
} finally {
|
||||
setRetrying(false);
|
||||
}
|
||||
};
|
||||
|
||||
const displayAmount =
|
||||
amountParam || (orderDetails?.totalAmount ? String(orderDetails.totalAmount) : "");
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-medical-gray-50 py-12 px-4 sm:px-6 font-vazir" dir="rtl">
|
||||
<div className="max-w-2xl mx-auto">
|
||||
|
||||
{/* Main Status Card */}
|
||||
<div
|
||||
className={cn(
|
||||
"bg-white rounded-[2.5rem] border p-6 sm:p-10 shadow-xl overflow-hidden relative transition-all",
|
||||
isSuccess ? "border-green-200" : "border-red-200"
|
||||
)}
|
||||
>
|
||||
{/* Top colored accent bar */}
|
||||
<div
|
||||
className={cn(
|
||||
"absolute top-0 right-0 left-0 h-3",
|
||||
isSuccess ? "bg-gradient-to-r from-emerald-500 to-green-500" : "bg-gradient-to-r from-red-500 to-rose-500"
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="text-center space-y-4 pt-2">
|
||||
{/* Status Icon */}
|
||||
<div
|
||||
className={cn(
|
||||
"w-20 h-20 sm:w-24 sm:h-24 rounded-3xl mx-auto flex items-center justify-center shadow-lg transition-transform",
|
||||
isSuccess
|
||||
? "bg-green-50 text-green-600 border border-green-200 shadow-green-100 scale-105"
|
||||
: "bg-red-50 text-red-600 border border-red-200 shadow-red-100"
|
||||
)}
|
||||
>
|
||||
{isSuccess ? (
|
||||
<CheckCircle2 className="w-12 h-12 sm:w-14 sm:h-14" />
|
||||
) : (
|
||||
<XCircle className="w-12 h-12 sm:w-14 sm:h-14" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Title & Status */}
|
||||
<div>
|
||||
<h1 className="text-2xl sm:text-3xl font-black text-medical-gray-900 italic">
|
||||
{isSuccess ? "پرداخت با موفقیت انجام شد" : "پرداخت ناموفق بود"}
|
||||
</h1>
|
||||
<p className="text-xs sm:text-sm text-medical-gray-500 font-bold mt-1">
|
||||
{messageParam ||
|
||||
(isSuccess
|
||||
? "سفارش شما در سامانه ثبت و در حال آمادهسازی و ارسال است."
|
||||
: "تراکنش بانکی تکمیل نشد یا توسط کاربر لغو گردید.")}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Receipt Info Box */}
|
||||
<div className="mt-8 bg-medical-gray-50 rounded-2xl p-5 border border-medical-gray-200 space-y-3.5 text-xs sm:text-sm">
|
||||
<div className="flex items-center justify-between pb-3 border-b border-medical-gray-200 font-bold">
|
||||
<span className="text-medical-gray-500 flex items-center gap-1.5">
|
||||
<Receipt className="w-4 h-4 text-canina-blue" />
|
||||
درگاه پرداخت:
|
||||
</span>
|
||||
<span className="text-medical-gray-900 font-black">
|
||||
درگاه امن زیبال (Zibal IPG)
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{displayAmount && (
|
||||
<div className="flex items-center justify-between pb-3 border-b border-medical-gray-200 font-bold">
|
||||
<span className="text-medical-gray-500">مبلغ تراکنش:</span>
|
||||
<span className="text-medical-gray-900 font-black text-base">
|
||||
{toPersian(Number(displayAmount).toLocaleString("fa-IR"))} تومان
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{refNumber && (
|
||||
<div className="flex items-center justify-between pb-3 border-b border-medical-gray-200">
|
||||
<span className="text-medical-gray-500 font-bold">شماره مرجع بانکی (Ref Number):</span>
|
||||
<div className="flex items-center gap-1.5 font-mono font-black text-medical-gray-900 dir-ltr">
|
||||
<span>{refNumber}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleCopy(refNumber, "شماره مرجع بانکی")}
|
||||
className="p-1 rounded hover:bg-white text-medical-gray-400 hover:text-canina-blue"
|
||||
title="کپی"
|
||||
>
|
||||
<Copy className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{trackId && (
|
||||
<div className="flex items-center justify-between pb-3 border-b border-medical-gray-200">
|
||||
<span className="text-medical-gray-500 font-bold">شناسه پیگیری زیبال (Track ID):</span>
|
||||
<div className="flex items-center gap-1.5 font-mono font-black text-medical-gray-900 dir-ltr">
|
||||
<span>{trackId}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleCopy(trackId, "شناسه پیگیری زیبال")}
|
||||
className="p-1 rounded hover:bg-white text-medical-gray-400 hover:text-canina-blue"
|
||||
title="کپی"
|
||||
>
|
||||
<Copy className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{cardNumber && (
|
||||
<div className="flex items-center justify-between pb-3 border-b border-medical-gray-200">
|
||||
<span className="text-medical-gray-500 font-bold flex items-center gap-1">
|
||||
<CreditCard className="w-4 h-4 text-medical-gray-400" />
|
||||
شماره کارت پرداختکننده:
|
||||
</span>
|
||||
<span className="font-mono font-black text-medical-gray-900 dir-ltr">
|
||||
{cardNumber}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{orderDetails?.trackingNumber && (
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-medical-gray-500 font-bold">کد پیگیری سفارش کانینا:</span>
|
||||
<span className="font-mono font-black text-canina-blue text-sm dir-ltr">
|
||||
{orderDetails.trackingNumber}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Action Buttons */}
|
||||
<div className="mt-8 space-y-3">
|
||||
{isSuccess ? (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
{orderId && (
|
||||
<button
|
||||
onClick={() => router.push(`/checkout/success/${orderId}`)}
|
||||
className="w-full bg-canina-blue text-white py-4 rounded-2xl font-black text-sm hover:bg-blue-700 transition-all flex items-center justify-center gap-2 shadow-lg shadow-canina-blue/20"
|
||||
>
|
||||
<ShoppingBag className="w-4 h-4" />
|
||||
<span>مشاهده جزئیات سفارش</span>
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={() => router.push("/shop")}
|
||||
className="w-full bg-medical-gray-100 text-medical-gray-900 py-4 rounded-2xl font-black text-sm hover:bg-medical-gray-200 transition-all flex items-center justify-center gap-2"
|
||||
>
|
||||
<span>بازگشت به فروشگاه</span>
|
||||
<ArrowRight className="w-4 h-4 rotate-180" />
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<button
|
||||
onClick={handleRetryPayment}
|
||||
disabled={retrying}
|
||||
className="w-full bg-canina-blue text-white py-4 rounded-2xl font-black text-sm hover:bg-blue-700 transition-all flex items-center justify-center gap-2 shadow-lg shadow-canina-blue/20 disabled:opacity-50"
|
||||
>
|
||||
<RotateCcw className={cn("w-4 h-4", retrying && "animate-spin")} />
|
||||
<span>{retrying ? "در حال انتقال به درگاه..." : "تلاش مجدد برای پرداخت"}</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => router.push("/checkout")}
|
||||
className="w-full bg-medical-gray-100 text-medical-gray-900 py-4 rounded-2xl font-black text-sm hover:bg-medical-gray-200 transition-all flex items-center justify-center gap-2"
|
||||
>
|
||||
<span>بازگشت به سبد خرید</span>
|
||||
<ArrowRight className="w-4 h-4 rotate-180" />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Security Notice */}
|
||||
<div className="mt-8 pt-6 border-t border-medical-gray-100 flex items-center justify-center gap-2 text-xs font-bold text-medical-gray-400">
|
||||
<ShieldCheck className="w-4 h-4 text-canina-blue" />
|
||||
<span>تراکنش تحت پروتکل رمزنگاری امن شاپرک و درگاه پرداخت زیبال</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function PaymentVerifyPage() {
|
||||
return (
|
||||
<Suspense
|
||||
fallback={
|
||||
<div className="min-h-screen bg-medical-gray-50 flex items-center justify-center p-6" dir="rtl">
|
||||
<div className="text-center space-y-4">
|
||||
<div className="w-12 h-12 border-4 border-canina-blue/20 border-t-canina-blue rounded-full animate-spin mx-auto" />
|
||||
<p className="font-bold text-sm text-medical-gray-600">در حال دریافت و اعتبارسنجی تراکنش پرداخت زیبال...</p>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<VerifyContent />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
@ -26,6 +26,7 @@ import SearchableSelect from "./SearchableSelect";
|
||||
import { IRAN_PROVINCES, PROVINCE_CITIES } from "../lib/data/provinces";
|
||||
import { toast } from "sonner";
|
||||
import { useRouter } from 'next/navigation';
|
||||
import api from "../lib/services/api";
|
||||
|
||||
export default function CheckoutPage() {
|
||||
const router = useRouter();
|
||||
@ -146,6 +147,28 @@ export default function CheckoutPage() {
|
||||
shippingAddress: shippingAddressStr
|
||||
});
|
||||
|
||||
// 3. Handle Online Payment via Zibal IPG
|
||||
if (paymentMethod === 'online') {
|
||||
try {
|
||||
const res = await api.post('/payment/zibal/initiate', { orderId });
|
||||
if (res.data?.paymentUrl) {
|
||||
toast.success("در حال انتقال به درگاه پرداخت زیبال...");
|
||||
window.location.href = res.data.paymentUrl;
|
||||
return;
|
||||
} else {
|
||||
toast.error("خطا در ایجاد تراکنش پرداخت زیبال");
|
||||
}
|
||||
} catch (gatewayErr: any) {
|
||||
const errMsg =
|
||||
gatewayErr.response?.data?.message ||
|
||||
gatewayErr.message ||
|
||||
"خطا در اتصال به درگاه پرداخت زیبال";
|
||||
toast.error(errMsg);
|
||||
router.push(`/checkout/success/${orderId}`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Re-fetch user profile from backend to sync PostgreSQL wallet balance and charity donation total
|
||||
const { fetchProfile } = useUserStore.getState();
|
||||
await fetchProfile();
|
||||
@ -420,10 +443,10 @@ export default function CheckoutPage() {
|
||||
},
|
||||
{
|
||||
id: 'online',
|
||||
label: getText('PAY_GATEWAY_ONLINE_LABEL', 'درگاه پرداخت آنلاین (شتاب)'),
|
||||
desc: getText('PAY_GATEWAY_ONLINE_DESC', 'پرداخت مستقیم با کلیه کارتهای شتاب'),
|
||||
label: getText('PAY_GATEWAY_ONLINE_LABEL', 'درگاه پرداخت اینترنتی (زیبال / شتاب)'),
|
||||
desc: getText('PAY_GATEWAY_ONLINE_DESC', 'پرداخت امن و آنی با کلیه کارتهای عضو شتاب'),
|
||||
icon: <ShieldCheck className="w-5 h-5 sm:w-6 sm:h-6" />,
|
||||
enabled: getText('PAY_GATEWAY_ONLINE_ENABLE', 'false') === 'true'
|
||||
enabled: getText('PAY_GATEWAY_ONLINE_ENABLE', 'true') === 'true'
|
||||
},
|
||||
{
|
||||
id: 'cod',
|
||||
|
||||
@ -121,11 +121,14 @@ export class ProductService {
|
||||
optimisticTemplate: data.optimisticTemplate,
|
||||
feedingAdvice: data.dosageLogic || data.feedingAdvice || '',
|
||||
slug: data.slug,
|
||||
image: (data.imageUrl && (data.imageUrl.startsWith('http://') || data.imageUrl.startsWith('https://')))
|
||||
? data.imageUrl
|
||||
: (data.imageUrl && data.imageUrl.startsWith('/uploads/')
|
||||
? data.imageUrl
|
||||
: (local?.image || (data.imageUrl && !data.imageUrl.startsWith('/products/') ? data.imageUrl : '') || '/assets/images/hero-section-image.png')),
|
||||
image: (() => {
|
||||
const apiBase = (process.env.NEXT_PUBLIC_API_URL || '').replace(/\/api$/, '');
|
||||
if (!data.imageUrl) return local?.image || '/assets/images/hero-section-image.png';
|
||||
if (data.imageUrl.startsWith('http://') || data.imageUrl.startsWith('https://')) return data.imageUrl;
|
||||
if (data.imageUrl.startsWith('/uploads/')) return `${apiBase}${data.imageUrl}`;
|
||||
if (data.imageUrl.startsWith('/products/')) return local?.image || '/assets/images/hero-section-image.png';
|
||||
return local?.image || data.imageUrl || '/assets/images/hero-section-image.png';
|
||||
})(),
|
||||
|
||||
main_ingredients: data.ingredientList?.map(i => i.ingredient) || data.ingredients?.split(/[،,-]/).map(s => s.trim()).filter(Boolean) || [],
|
||||
symptoms: data.symptoms?.map(s => typeof s === 'string' ? s : s.symptom || '').filter(Boolean) || [],
|
||||
|
||||
@ -13,6 +13,22 @@ const nextConfig: NextConfig = {
|
||||
images: {
|
||||
formats: ['image/avif', 'image/webp'],
|
||||
remotePatterns: [
|
||||
{
|
||||
protocol: 'https',
|
||||
hostname: 'canina.ir',
|
||||
},
|
||||
{
|
||||
protocol: 'https',
|
||||
hostname: 'api.canina.ir',
|
||||
},
|
||||
{
|
||||
protocol: 'https',
|
||||
hostname: 'stage.canina.ir',
|
||||
},
|
||||
{
|
||||
protocol: 'https',
|
||||
hostname: 'stageapi.canina.ir',
|
||||
},
|
||||
{
|
||||
protocol: 'https',
|
||||
hostname: 'canina-iran.com',
|
||||
@ -29,6 +45,10 @@ const nextConfig: NextConfig = {
|
||||
protocol: 'http',
|
||||
hostname: 'localhost',
|
||||
},
|
||||
{
|
||||
protocol: 'http',
|
||||
hostname: '127.0.0.1',
|
||||
},
|
||||
],
|
||||
},
|
||||
async headers() {
|
||||
|
||||
2883
graphify-out/.graphify_analysis.json
Normal file
2883
graphify-out/.graphify_analysis.json
Normal file
File diff suppressed because it is too large
Load Diff
293
graphify-out/.graphify_labels.json
Normal file
293
graphify-out/.graphify_labels.json
Normal file
@ -0,0 +1,293 @@
|
||||
{
|
||||
"0": "AdminService",
|
||||
"1": "pets/pets.controller.ts",
|
||||
"2": "Roles",
|
||||
"3": "UsersService",
|
||||
"4": "CmsController",
|
||||
"5": "BannersService",
|
||||
"6": "auth.controller.ts",
|
||||
"7": "app.module.ts",
|
||||
"8": "CreateVideoDto",
|
||||
"9": "ProductService",
|
||||
"10": "SmartAdvisor.tsx",
|
||||
"11": "compilerOptions",
|
||||
"12": "toPersian",
|
||||
"13": "ZibalService",
|
||||
"14": "ProductsService",
|
||||
"15": "lib/services/api.ts",
|
||||
"16": "eslint",
|
||||
"17": "useSettingsStore",
|
||||
"18": "MetricsController",
|
||||
"19": "B2B Inquiry Controller",
|
||||
"20": "CategoriesController",
|
||||
"21": "RedisService",
|
||||
"22": "MediaController",
|
||||
"23": "Ingredient Management Controller",
|
||||
"24": "adminRoutes.tsx",
|
||||
"25": "admin.module.ts",
|
||||
"26": "ConfirmModal.tsx",
|
||||
"27": "Prescription Review Controller",
|
||||
"28": "Smart Advisor Controller",
|
||||
"29": "Testimonials Management Controller",
|
||||
"30": "src/services/api.ts",
|
||||
"31": "Spinner.tsx",
|
||||
"32": "useCartStore",
|
||||
"33": "PaymentController",
|
||||
"34": "main.ts",
|
||||
"35": "admin.ts",
|
||||
"36": "Backend TypeScript Config",
|
||||
"37": "App TypeScript Config",
|
||||
"38": "Products.tsx",
|
||||
"39": "dependencies",
|
||||
"40": "Node TypeScript Config",
|
||||
"41": "Admin Blog Controller",
|
||||
"42": "WholesaleService",
|
||||
"43": "devDependencies",
|
||||
"44": "Generic CRUD Controller",
|
||||
"45": "seo.module.ts",
|
||||
"46": "PaginationDto",
|
||||
"47": "Project Build Scripts",
|
||||
"48": "Home Data Module",
|
||||
"49": "devDependencies",
|
||||
"50": "Database Seeding Logic",
|
||||
"51": "Prisma Database Migrations",
|
||||
"52": "dependencies",
|
||||
"53": "UI Skeleton and Tables",
|
||||
"54": "components/Skeleton.tsx",
|
||||
"55": "BE-001",
|
||||
"56": "VetGallery.tsx",
|
||||
"57": "NPM Lifecycle Scripts",
|
||||
"58": "Pet Management API",
|
||||
"59": "PrismaService",
|
||||
"60": "Jest Testing Config",
|
||||
"61": "WikiController",
|
||||
"62": "api",
|
||||
"63": "FE-001",
|
||||
"64": "zibal.service.ts",
|
||||
"65": "rules/graphify.md",
|
||||
"66": "App Health Controller",
|
||||
"67": "dependencies",
|
||||
"68": "OrdersService",
|
||||
"69": "Integrity Validation Scripts",
|
||||
"70": "Admin Panel Package Config",
|
||||
"71": "Analytics and Report Charts",
|
||||
"72": "Task Orchestration Scripts",
|
||||
"73": "Backend Package Config",
|
||||
"74": "BlogsController",
|
||||
"75": "React Error Boundary",
|
||||
"76": "Application Package Config",
|
||||
"77": ".findAll",
|
||||
"78": "Error and Not Found Pages",
|
||||
"79": "VPN Utility Scripts",
|
||||
"80": "NestJS CLI Config",
|
||||
"81": "Seed TypeScript Config",
|
||||
"82": "ADM-001",
|
||||
"83": "Browser Utility Scripts",
|
||||
"84": "Dev Server Startup",
|
||||
"85": "Architectural Audit Findings",
|
||||
"86": "Pagination API Schemas",
|
||||
"87": "Font Assets and Licenses",
|
||||
"88": "Ledger Rebuild Scripts",
|
||||
"89": "Evidence Validation Scripts",
|
||||
"90": "Blog Listing Page",
|
||||
"91": "Blog Post Detail Page",
|
||||
"92": "@types/node",
|
||||
"93": "devDependencies",
|
||||
"94": "UI Text Seeding",
|
||||
"95": "Wiki Terms Seeding",
|
||||
"96": "Blog Management DTOs",
|
||||
"97": "Home Management DTOs",
|
||||
"98": "Wiki Management DTOs",
|
||||
"99": "Wiki Page Routing",
|
||||
"100": "Network Status Banner",
|
||||
"101": "Docker Deployment Scripts",
|
||||
"102": "DB-001",
|
||||
"103": "BlogsService",
|
||||
"104": "Database Migration Scripts",
|
||||
"105": "Scientific Terms Schema",
|
||||
"106": "Blog Data Seeding",
|
||||
"107": "Custom Data Seeding",
|
||||
"108": "Products Table",
|
||||
"109": "Auth Architecture and Planning",
|
||||
"110": "Build Manifest Generation",
|
||||
"111": "Classification Data Generation",
|
||||
"112": "Evidence Data Generation",
|
||||
"113": "Ledger Data Generation",
|
||||
"114": "Manifest Data Generation",
|
||||
"115": "Honest Manifest Synchronization",
|
||||
"116": "Manifest Entry Synchronization",
|
||||
"117": "WikiService",
|
||||
"118": "TS-001",
|
||||
"119": "TEST-001",
|
||||
"120": "AdminTransactionFilterDto",
|
||||
"121": "@types/react-dom",
|
||||
"122": "Admin Panel TSConfig",
|
||||
"123": "About Page Component",
|
||||
"124": "Privacy Page Component",
|
||||
"125": "Next.js Security Configuration",
|
||||
"126": "Typography and Font Assets",
|
||||
"127": "DEVOPS-001",
|
||||
"128": "DOC-001",
|
||||
"129": "What You Must Do When Invoked",
|
||||
"130": "JwtAuthGuard",
|
||||
"131": "راهنمای تست سیستم (Software Testing)",
|
||||
"132": "Role & Core Objective",
|
||||
"133": "Required Review Group Closures",
|
||||
"134": "Operational Rules & Boundaries",
|
||||
"135": "Operational Rules & Boundaries",
|
||||
"136": "🏢 AI Software Agency — Master Orchestration Protocol v3",
|
||||
"137": "@nestjs/cli",
|
||||
"138": "Operational Rules & Boundaries",
|
||||
"139": "Operational Rules & Boundaries",
|
||||
"140": "Bcrypt Type Definitions",
|
||||
"141": "bcryptjs",
|
||||
"142": "helmet",
|
||||
"143": "Blog Entity Model",
|
||||
"144": "Home Entity Model",
|
||||
"145": "Wiki Entity Model",
|
||||
"146": "User Profile Management",
|
||||
"147": "Pets Table",
|
||||
"148": "User Database and Infrastructure",
|
||||
"149": "API and Frontend Specifications",
|
||||
"150": "Brand and Agent Guidelines",
|
||||
"151": "Search Engine Robots Config",
|
||||
"152": "Application ESLint Config",
|
||||
"153": "PostCSS Configuration",
|
||||
"154": "Vitest Test Setup",
|
||||
"155": "Database Backup Script",
|
||||
"156": "Application Startup Script",
|
||||
"157": "What You Must Do When Invoked",
|
||||
"158": "Backend ESLint Config",
|
||||
"159": "User Logout Endpoint",
|
||||
"160": "Company Profile",
|
||||
"161": "Project Introduction",
|
||||
"162": "Architecture Route Map",
|
||||
"163": "Project Task Backlog",
|
||||
"164": "Root ESLint Configuration",
|
||||
"165": "PostCSS Build Config",
|
||||
"166": "Tailwind CSS Configuration",
|
||||
"167": "Vite Build Configuration",
|
||||
"168": "Sahel Font Samples",
|
||||
"169": "Shabnam Font History",
|
||||
"170": "Vazirmatn Font History",
|
||||
"171": "Vitest Test Configuration",
|
||||
"172": "Variable Font Samples",
|
||||
"173": "Shabnam Font Preview",
|
||||
"174": "Production Docker Setup",
|
||||
"175": "Staging Docker Setup",
|
||||
"176": ".agents/workflows/graphify.md",
|
||||
"177": "Role & Core Objective",
|
||||
"178": "graphify reference: extra exports and benchmark",
|
||||
"179": "graphify reference: query, path, explain",
|
||||
"180": "graphify reference: add a URL and watch a folder",
|
||||
"181": "graphify reference: commit hook and native CLAUDE.md integration",
|
||||
"182": "graphify reference: incremental update and cluster-only",
|
||||
"183": "graphify reference: GitHub clone and cross-repo merge",
|
||||
"184": "graphify reference: transcribe video and audio",
|
||||
"185": "Reconciled Audit Roles & Assignments",
|
||||
"186": "instructions.md",
|
||||
"187": "Phase 3.1 — Human Review Preparation and Master Backlog Critique",
|
||||
"188": "CLAUDE.md",
|
||||
"189": ".claude/CLAUDE.md",
|
||||
"190": "extraction-spec.md",
|
||||
"191": "User Login API",
|
||||
"192": "Developer Standards and Architecture",
|
||||
"193": "Deep Audit Summary Report",
|
||||
"194": "Operational Rules & Boundaries",
|
||||
"195": "Comprehensive Change Log",
|
||||
"196": "Operational Rules & Boundaries",
|
||||
"197": "1. Summary of Integrity Repairs Performed",
|
||||
"198": "Operational Rules & Boundaries",
|
||||
"199": "Operational Rules & Boundaries",
|
||||
"200": "Operational Rules & Boundaries",
|
||||
"201": "Vazirmatn Changelog",
|
||||
"202": "Vazirmatn Font فونت وزیرمتن",
|
||||
"203": "Operational Rules & Boundaries",
|
||||
"204": "backend/README.md",
|
||||
"205": "Repository Map",
|
||||
"206": "Sahel-Font",
|
||||
"207": "AuthService",
|
||||
"208": "Sahel-Font",
|
||||
"209": "Role & Core Objective",
|
||||
"210": "exclude",
|
||||
"211": "Phase 2 Final Quality Gate Summary Report",
|
||||
"212": "Task Modifications Log",
|
||||
"213": "Install",
|
||||
"214": ".findAll",
|
||||
"215": "System Discovery",
|
||||
"216": "Product Requirement Document (PRD)",
|
||||
"217": "Baseline Command Plan & Reconciled Command History",
|
||||
"218": "Architecture Specification",
|
||||
"219": "Project Health Audit Report",
|
||||
"220": "Open Questions",
|
||||
"221": "Final Phase 2 Audit Closure Report",
|
||||
"222": "📝 Active Agent Working Scratchpad",
|
||||
"223": "🔍 Code Health Audit Review (01_auditor)",
|
||||
"224": "Omitted File Inspection Report",
|
||||
"225": "Phase 3.2 / 3.3 — Implementation Readiness & Architectural Finalization Report",
|
||||
"226": "Phase 3 Audit Traceability Matrix",
|
||||
"227": "API Contract Specification",
|
||||
"228": "⚙️ Backend Technical Review (05_dev_backend)",
|
||||
"229": "🎨 Frontend & Admin Panel Technical Review (06_dev_frontend)",
|
||||
"230": "🚀 SEO & Content Strategy Review (12_seo_content)",
|
||||
"231": "Raw Finding Verification & Disposition Report",
|
||||
"232": "React + TypeScript + Vite",
|
||||
"233": "application/README.md",
|
||||
"234": "🔒 Security & Performance Review (09_devops_security)",
|
||||
"235": "👁️ UX & Persona Interface Review (08_visual_qa)",
|
||||
"236": "Compiler Diagnostic Dispositions",
|
||||
"237": "@eslint/eslintrc",
|
||||
"238": "js-yaml",
|
||||
"239": "globals",
|
||||
"240": "prettier",
|
||||
"241": "prisma",
|
||||
"242": "supertest",
|
||||
"243": "ts-loader",
|
||||
"244": "ts-node",
|
||||
"245": "@types/express",
|
||||
"246": "@types/jest",
|
||||
"247": "@types/js-yaml",
|
||||
"248": "@types/multer",
|
||||
"249": "eslint-plugin-react-hooks",
|
||||
"250": "eslint-plugin-react-refresh",
|
||||
"251": "tailwindcss",
|
||||
"252": "typescript",
|
||||
"253": "@testing-library/jest-dom",
|
||||
"254": "@testing-library/react",
|
||||
"255": "@types/react",
|
||||
"256": "typescript",
|
||||
"257": "vitest",
|
||||
"258": "reviews/README.md",
|
||||
"259": "axios",
|
||||
"260": "admin-panel/public/fonts/sahel-font-v3.4.0/CHANGELOG.md",
|
||||
"261": "shabnam-font-v5.0.1/CHANGELOG.md",
|
||||
"262": "application/CLAUDE.md",
|
||||
"263": "application/public/fonts/sahel-font-v3.4.0/CHANGELOG.md",
|
||||
"264": "tailwindcss",
|
||||
"265": "typescript-eslint",
|
||||
"266": "@nestjs/core",
|
||||
"267": "@nestjs/jwt",
|
||||
"268": "@nestjs/swagger",
|
||||
"269": "@nestjs/throttler",
|
||||
"270": "passport-jwt",
|
||||
"271": "@prisma/client",
|
||||
"272": "swagger-ui-express",
|
||||
"273": "AGENTS.md",
|
||||
"274": "eslint-config-prettier",
|
||||
"275": "@eslint/js",
|
||||
"276": "jest",
|
||||
"277": "@nestjs/schematics",
|
||||
"278": "@nestjs/testing",
|
||||
"279": "source-map-support",
|
||||
"280": "ts-jest",
|
||||
"281": "tsconfig-paths",
|
||||
"282": "@types/bcryptjs",
|
||||
"283": "typescript-eslint",
|
||||
"284": "wholesale.controller.ts",
|
||||
"285": "InitiatePaymentDto",
|
||||
"286": "GetProductsDto",
|
||||
"287": "Coupons.tsx",
|
||||
"288": "SmsSettingsPage.tsx",
|
||||
"289": "ZibalCallbackQueryDto",
|
||||
"290": "@tailwindcss/postcss"
|
||||
}
|
||||
1
graphify-out/.graphify_labels.json.sig
Normal file
1
graphify-out/.graphify_labels.json.sig
Normal file
File diff suppressed because one or more lines are too long
1
graphify-out/.graphify_root
Normal file
1
graphify-out/.graphify_root
Normal file
@ -0,0 +1 @@
|
||||
.
|
||||
1
graphify-out/.graphify_semantic_marker
Normal file
1
graphify-out/.graphify_semantic_marker
Normal file
@ -0,0 +1 @@
|
||||
{"output_tokens": 7105}
|
||||
2883
graphify-out/2026-08-16/.graphify_analysis.json
Normal file
2883
graphify-out/2026-08-16/.graphify_analysis.json
Normal file
File diff suppressed because it is too large
Load Diff
287
graphify-out/2026-08-16/.graphify_labels.json
Normal file
287
graphify-out/2026-08-16/.graphify_labels.json
Normal file
@ -0,0 +1,287 @@
|
||||
{
|
||||
"0": "AdminService",
|
||||
"1": "pets/pets.controller.ts",
|
||||
"2": "Roles",
|
||||
"3": "UsersService",
|
||||
"4": "CmsController",
|
||||
"5": "BannersService",
|
||||
"6": "auth.controller.ts",
|
||||
"7": "app.module.ts",
|
||||
"8": "CreateVideoDto",
|
||||
"9": "ProductService",
|
||||
"10": "SmartAdvisor.tsx",
|
||||
"11": "compilerOptions",
|
||||
"12": "toPersian",
|
||||
"13": "SmsService",
|
||||
"14": "ProductsService",
|
||||
"15": "lib/services/api.ts",
|
||||
"16": "eslint",
|
||||
"17": "useSettingsStore",
|
||||
"18": "AppModule",
|
||||
"19": "B2B Inquiry Controller",
|
||||
"20": "Category Management Controller",
|
||||
"21": "auth.service.ts",
|
||||
"22": "MediaController",
|
||||
"23": "Ingredient Management Controller",
|
||||
"24": "adminRoutes.tsx",
|
||||
"25": "admin.module.ts",
|
||||
"26": "ConfirmModal.tsx",
|
||||
"27": "Prescription Review Controller",
|
||||
"28": "Smart Advisor Controller",
|
||||
"29": "Testimonials Management Controller",
|
||||
"30": "src/services/api.ts",
|
||||
"31": "Spinner.tsx",
|
||||
"32": "useCartStore",
|
||||
"33": "ZibalService",
|
||||
"34": "main.ts",
|
||||
"35": "ContactService",
|
||||
"36": "Backend TypeScript Config",
|
||||
"37": "App TypeScript Config",
|
||||
"38": "Coupons.tsx",
|
||||
"39": "dependencies",
|
||||
"40": "Node TypeScript Config",
|
||||
"41": "Admin Blog Controller",
|
||||
"42": "WholesaleApplyDto",
|
||||
"43": "devDependencies",
|
||||
"44": "Generic CRUD Controller",
|
||||
"45": "seo.module.ts",
|
||||
"46": "OrdersController",
|
||||
"47": "Project Build Scripts",
|
||||
"48": "Home Data Module",
|
||||
"49": "devDependencies",
|
||||
"50": "Database Seeding Logic",
|
||||
"51": "Prisma Database Migrations",
|
||||
"52": "dependencies",
|
||||
"53": "UI Skeleton and Tables",
|
||||
"54": "components/Skeleton.tsx",
|
||||
"55": "BE-001",
|
||||
"56": "VetGallery.tsx",
|
||||
"57": "NPM Lifecycle Scripts",
|
||||
"58": "Pet Management API",
|
||||
"59": "PrismaService",
|
||||
"60": "Jest Testing Config",
|
||||
"61": "PaginationDto",
|
||||
"62": "SettingsService",
|
||||
"63": "FE-001",
|
||||
"64": "payment.module.ts",
|
||||
"65": "rules/graphify.md",
|
||||
"66": "App Health Controller",
|
||||
"67": "dependencies",
|
||||
"68": "OrdersService",
|
||||
"69": "Integrity Validation Scripts",
|
||||
"70": "Admin Panel Package Config",
|
||||
"71": "Analytics and Report Charts",
|
||||
"72": "Task Orchestration Scripts",
|
||||
"73": "Backend Package Config",
|
||||
"74": "BlogsController",
|
||||
"75": "React Error Boundary",
|
||||
"76": "Application Package Config",
|
||||
"77": "WikiController",
|
||||
"78": "Error and Not Found Pages",
|
||||
"79": "VPN Utility Scripts",
|
||||
"80": "NestJS CLI Config",
|
||||
"81": "Seed TypeScript Config",
|
||||
"82": "ADM-001",
|
||||
"83": "Browser Utility Scripts",
|
||||
"84": "Dev Server Startup",
|
||||
"85": "Architectural Audit Findings",
|
||||
"86": "Pagination API Schemas",
|
||||
"87": "Font Assets and Licenses",
|
||||
"88": "Ledger Rebuild Scripts",
|
||||
"89": "Evidence Validation Scripts",
|
||||
"90": "Blog Listing Page",
|
||||
"91": "Blog Post Detail Page",
|
||||
"92": "@types/node",
|
||||
"93": "devDependencies",
|
||||
"94": "UI Text Seeding",
|
||||
"95": "Wiki Terms Seeding",
|
||||
"96": "Blog Management DTOs",
|
||||
"97": "Home Management DTOs",
|
||||
"98": "Wiki Management DTOs",
|
||||
"99": "Wiki Page Routing",
|
||||
"100": "Network Status Banner",
|
||||
"101": "Docker Deployment Scripts",
|
||||
"102": "DB-001",
|
||||
"103": "BlogsService",
|
||||
"104": "Database Migration Scripts",
|
||||
"105": "Scientific Terms Schema",
|
||||
"106": "Blog Data Seeding",
|
||||
"107": "Custom Data Seeding",
|
||||
"108": "Products Table",
|
||||
"109": "Auth Architecture and Planning",
|
||||
"110": "Build Manifest Generation",
|
||||
"111": "Classification Data Generation",
|
||||
"112": "Evidence Data Generation",
|
||||
"113": "Ledger Data Generation",
|
||||
"114": "Manifest Data Generation",
|
||||
"115": "Honest Manifest Synchronization",
|
||||
"116": "Manifest Entry Synchronization",
|
||||
"117": "WikiService",
|
||||
"118": "TS-001",
|
||||
"119": "TEST-001",
|
||||
"120": "ValidateCouponDto",
|
||||
"121": "@types/react-dom",
|
||||
"122": "Admin Panel TSConfig",
|
||||
"123": "About Page Component",
|
||||
"124": "Privacy Page Component",
|
||||
"125": "Next.js Security Configuration",
|
||||
"126": "Typography and Font Assets",
|
||||
"127": "DEVOPS-001",
|
||||
"128": "DOC-001",
|
||||
"129": "What You Must Do When Invoked",
|
||||
"130": "JwtAuthGuard",
|
||||
"131": "راهنمای تست سیستم (Software Testing)",
|
||||
"132": "Role & Core Objective",
|
||||
"133": "Required Review Group Closures",
|
||||
"134": "Operational Rules & Boundaries",
|
||||
"135": "Operational Rules & Boundaries",
|
||||
"136": "🏢 AI Software Agency — Master Orchestration Protocol v3",
|
||||
"137": "@nestjs/cli",
|
||||
"138": "Operational Rules & Boundaries",
|
||||
"139": "Operational Rules & Boundaries",
|
||||
"140": "Bcrypt Type Definitions",
|
||||
"141": "bcryptjs",
|
||||
"142": "helmet",
|
||||
"143": "Blog Entity Model",
|
||||
"144": "Home Entity Model",
|
||||
"145": "Wiki Entity Model",
|
||||
"146": "User Profile Management",
|
||||
"147": "Pets Table",
|
||||
"148": "User Database and Infrastructure",
|
||||
"149": "API and Frontend Specifications",
|
||||
"150": "Brand and Agent Guidelines",
|
||||
"151": "Search Engine Robots Config",
|
||||
"152": "Application ESLint Config",
|
||||
"153": "PostCSS Configuration",
|
||||
"154": "Vitest Test Setup",
|
||||
"155": "Database Backup Script",
|
||||
"156": "Application Startup Script",
|
||||
"157": "What You Must Do When Invoked",
|
||||
"158": "Backend ESLint Config",
|
||||
"159": "User Logout Endpoint",
|
||||
"160": "Company Profile",
|
||||
"161": "Project Introduction",
|
||||
"162": "Architecture Route Map",
|
||||
"163": "Project Task Backlog",
|
||||
"164": "Root ESLint Configuration",
|
||||
"165": "PostCSS Build Config",
|
||||
"166": "Tailwind CSS Configuration",
|
||||
"167": "Vite Build Configuration",
|
||||
"168": "Sahel Font Samples",
|
||||
"169": "Shabnam Font History",
|
||||
"170": "Vazirmatn Font History",
|
||||
"171": "Vitest Test Configuration",
|
||||
"172": "Variable Font Samples",
|
||||
"173": "Shabnam Font Preview",
|
||||
"174": "Production Docker Setup",
|
||||
"175": "Staging Docker Setup",
|
||||
"176": ".agents/workflows/graphify.md",
|
||||
"177": "Role & Core Objective",
|
||||
"178": "graphify reference: extra exports and benchmark",
|
||||
"179": "graphify reference: query, path, explain",
|
||||
"180": "graphify reference: add a URL and watch a folder",
|
||||
"181": "graphify reference: commit hook and native CLAUDE.md integration",
|
||||
"182": "graphify reference: incremental update and cluster-only",
|
||||
"183": "graphify reference: GitHub clone and cross-repo merge",
|
||||
"184": "graphify reference: transcribe video and audio",
|
||||
"185": "Reconciled Audit Roles & Assignments",
|
||||
"186": "instructions.md",
|
||||
"187": "Phase 3.1 — Human Review Preparation and Master Backlog Critique",
|
||||
"188": "CLAUDE.md",
|
||||
"189": ".claude/CLAUDE.md",
|
||||
"190": "extraction-spec.md",
|
||||
"191": "User Login API",
|
||||
"192": "Developer Standards and Architecture",
|
||||
"193": "Deep Audit Summary Report",
|
||||
"194": "Operational Rules & Boundaries",
|
||||
"195": "Comprehensive Change Log",
|
||||
"196": "Operational Rules & Boundaries",
|
||||
"197": "1. Summary of Integrity Repairs Performed",
|
||||
"198": "Operational Rules & Boundaries",
|
||||
"199": "Operational Rules & Boundaries",
|
||||
"200": "Operational Rules & Boundaries",
|
||||
"201": "Vazirmatn Changelog",
|
||||
"202": "Vazirmatn Font فونت وزیرمتن",
|
||||
"203": "Operational Rules & Boundaries",
|
||||
"204": "backend/README.md",
|
||||
"205": "Repository Map",
|
||||
"206": "Sahel-Font",
|
||||
"207": "AuthService",
|
||||
"208": "Sahel-Font",
|
||||
"209": "Role & Core Objective",
|
||||
"210": "exclude",
|
||||
"211": "Phase 2 Final Quality Gate Summary Report",
|
||||
"212": "Task Modifications Log",
|
||||
"213": "Install",
|
||||
"214": ".findAll",
|
||||
"215": "System Discovery",
|
||||
"216": "Product Requirement Document (PRD)",
|
||||
"217": "Baseline Command Plan & Reconciled Command History",
|
||||
"218": "Architecture Specification",
|
||||
"219": "Project Health Audit Report",
|
||||
"220": "Open Questions",
|
||||
"221": "Final Phase 2 Audit Closure Report",
|
||||
"222": "📝 Active Agent Working Scratchpad",
|
||||
"223": "🔍 Code Health Audit Review (01_auditor)",
|
||||
"224": "Omitted File Inspection Report",
|
||||
"225": "Phase 3.2 / 3.3 — Implementation Readiness & Architectural Finalization Report",
|
||||
"226": "Phase 3 Audit Traceability Matrix",
|
||||
"227": "API Contract Specification",
|
||||
"228": "⚙️ Backend Technical Review (05_dev_backend)",
|
||||
"229": "🎨 Frontend & Admin Panel Technical Review (06_dev_frontend)",
|
||||
"230": "🚀 SEO & Content Strategy Review (12_seo_content)",
|
||||
"231": "Raw Finding Verification & Disposition Report",
|
||||
"232": "React + TypeScript + Vite",
|
||||
"233": "application/README.md",
|
||||
"234": "🔒 Security & Performance Review (09_devops_security)",
|
||||
"235": "👁️ UX & Persona Interface Review (08_visual_qa)",
|
||||
"236": "Compiler Diagnostic Dispositions",
|
||||
"237": "@eslint/eslintrc",
|
||||
"238": "js-yaml",
|
||||
"239": "globals",
|
||||
"240": "prettier",
|
||||
"241": "prisma",
|
||||
"242": "supertest",
|
||||
"243": "ts-loader",
|
||||
"244": "ts-node",
|
||||
"245": "@types/express",
|
||||
"246": "@types/jest",
|
||||
"247": "@types/js-yaml",
|
||||
"248": "@types/multer",
|
||||
"249": "eslint-plugin-react-hooks",
|
||||
"250": "eslint-plugin-react-refresh",
|
||||
"251": "tailwindcss",
|
||||
"252": "typescript",
|
||||
"253": "@testing-library/jest-dom",
|
||||
"254": "@testing-library/react",
|
||||
"255": "@types/react",
|
||||
"256": "typescript",
|
||||
"257": "vitest",
|
||||
"258": "reviews/README.md",
|
||||
"259": "axios",
|
||||
"260": "admin-panel/public/fonts/sahel-font-v3.4.0/CHANGELOG.md",
|
||||
"261": "shabnam-font-v5.0.1/CHANGELOG.md",
|
||||
"262": "application/CLAUDE.md",
|
||||
"263": "application/public/fonts/sahel-font-v3.4.0/CHANGELOG.md",
|
||||
"264": "tailwindcss",
|
||||
"265": "typescript-eslint",
|
||||
"266": "@nestjs/core",
|
||||
"267": "@nestjs/jwt",
|
||||
"268": "@nestjs/swagger",
|
||||
"269": "@nestjs/throttler",
|
||||
"270": "passport-jwt",
|
||||
"271": "@prisma/client",
|
||||
"272": "swagger-ui-express",
|
||||
"273": "AGENTS.md",
|
||||
"274": "eslint-config-prettier",
|
||||
"275": "@eslint/js",
|
||||
"276": "jest",
|
||||
"277": "@nestjs/schematics",
|
||||
"278": "@nestjs/testing",
|
||||
"279": "source-map-support",
|
||||
"280": "ts-jest",
|
||||
"281": "tsconfig-paths",
|
||||
"282": "@types/bcryptjs",
|
||||
"283": "typescript-eslint",
|
||||
"284": "globals"
|
||||
}
|
||||
1
graphify-out/2026-08-16/.graphify_semantic_marker
Normal file
1
graphify-out/2026-08-16/.graphify_semantic_marker
Normal file
@ -0,0 +1 @@
|
||||
{"output_tokens": 7105}
|
||||
978
graphify-out/2026-08-16/GRAPH_REPORT.md
Normal file
978
graphify-out/2026-08-16/GRAPH_REPORT.md
Normal file
@ -0,0 +1,978 @@
|
||||
# Graph Report - canina (2026-08-16)
|
||||
|
||||
## Corpus Check
|
||||
- 463 files · ~678,911 words
|
||||
- Verdict: corpus is large enough that graph structure adds value.
|
||||
|
||||
## Summary
|
||||
- 3234 nodes · 5269 edges · 285 communities (172 shown, 113 thin omitted)
|
||||
- Extraction: 96% EXTRACTED · 4% INFERRED · 0% AMBIGUOUS · INFERRED: 186 edges (avg confidence: 0.79)
|
||||
- Token cost: 0 input · 0 output
|
||||
|
||||
## Graph Freshness
|
||||
- Built from commit: `8de13513`
|
||||
- Run `git rev-parse HEAD` and compare to check if the graph is stale.
|
||||
- Run `graphify update .` after code changes (no API cost).
|
||||
|
||||
## Community Hubs (Navigation)
|
||||
- AdminService
|
||||
- pets/pets.controller.ts
|
||||
- Roles
|
||||
- UsersService
|
||||
- CmsController
|
||||
- BannersService
|
||||
- auth.controller.ts
|
||||
- app.module.ts
|
||||
- CreateVideoDto
|
||||
- ProductService
|
||||
- SmartAdvisor.tsx
|
||||
- compilerOptions
|
||||
- toPersian
|
||||
- SmsService
|
||||
- ProductsService
|
||||
- lib/services/api.ts
|
||||
- eslint
|
||||
- useSettingsStore
|
||||
- AppModule
|
||||
- B2B Inquiry Controller
|
||||
- Category Management Controller
|
||||
- auth.service.ts
|
||||
- MediaController
|
||||
- Ingredient Management Controller
|
||||
- adminRoutes.tsx
|
||||
- admin.module.ts
|
||||
- ConfirmModal.tsx
|
||||
- Prescription Review Controller
|
||||
- Smart Advisor Controller
|
||||
- Testimonials Management Controller
|
||||
- src/services/api.ts
|
||||
- Spinner.tsx
|
||||
- useCartStore
|
||||
- ZibalService
|
||||
- main.ts
|
||||
- ContactService
|
||||
- Backend TypeScript Config
|
||||
- App TypeScript Config
|
||||
- Coupons.tsx
|
||||
- dependencies
|
||||
- Node TypeScript Config
|
||||
- Admin Blog Controller
|
||||
- WholesaleApplyDto
|
||||
- devDependencies
|
||||
- Generic CRUD Controller
|
||||
- seo.module.ts
|
||||
- OrdersController
|
||||
- Project Build Scripts
|
||||
- Home Data Module
|
||||
- devDependencies
|
||||
- Database Seeding Logic
|
||||
- Prisma Database Migrations
|
||||
- dependencies
|
||||
- UI Skeleton and Tables
|
||||
- components/Skeleton.tsx
|
||||
- BE-001
|
||||
- VetGallery.tsx
|
||||
- NPM Lifecycle Scripts
|
||||
- Pet Management API
|
||||
- PrismaService
|
||||
- Jest Testing Config
|
||||
- PaginationDto
|
||||
- SettingsService
|
||||
- FE-001
|
||||
- payment.module.ts
|
||||
- rules/graphify.md
|
||||
- App Health Controller
|
||||
- dependencies
|
||||
- OrdersService
|
||||
- Integrity Validation Scripts
|
||||
- Admin Panel Package Config
|
||||
- Analytics and Report Charts
|
||||
- Task Orchestration Scripts
|
||||
- Backend Package Config
|
||||
- BlogsController
|
||||
- React Error Boundary
|
||||
- Application Package Config
|
||||
- WikiController
|
||||
- Error and Not Found Pages
|
||||
- VPN Utility Scripts
|
||||
- NestJS CLI Config
|
||||
- Seed TypeScript Config
|
||||
- ADM-001
|
||||
- Browser Utility Scripts
|
||||
- Dev Server Startup
|
||||
- Architectural Audit Findings
|
||||
- Pagination API Schemas
|
||||
- Font Assets and Licenses
|
||||
- Ledger Rebuild Scripts
|
||||
- Evidence Validation Scripts
|
||||
- Blog Listing Page
|
||||
- Blog Post Detail Page
|
||||
- @types/node
|
||||
- devDependencies
|
||||
- UI Text Seeding
|
||||
- Wiki Terms Seeding
|
||||
- Blog Management DTOs
|
||||
- Home Management DTOs
|
||||
- Wiki Management DTOs
|
||||
- Wiki Page Routing
|
||||
- Network Status Banner
|
||||
- Docker Deployment Scripts
|
||||
- DB-001
|
||||
- BlogsService
|
||||
- Database Migration Scripts
|
||||
- Scientific Terms Schema
|
||||
- Blog Data Seeding
|
||||
- Custom Data Seeding
|
||||
- Products Table
|
||||
- Auth Architecture and Planning
|
||||
- Build Manifest Generation
|
||||
- Classification Data Generation
|
||||
- Evidence Data Generation
|
||||
- Ledger Data Generation
|
||||
- Manifest Data Generation
|
||||
- Honest Manifest Synchronization
|
||||
- Manifest Entry Synchronization
|
||||
- WikiService
|
||||
- TS-001
|
||||
- TEST-001
|
||||
- ValidateCouponDto
|
||||
- @types/react-dom
|
||||
- Admin Panel TSConfig
|
||||
- About Page Component
|
||||
- Privacy Page Component
|
||||
- Next.js Security Configuration
|
||||
- Typography and Font Assets
|
||||
- DEVOPS-001
|
||||
- DOC-001
|
||||
- What You Must Do When Invoked
|
||||
- JwtAuthGuard
|
||||
- راهنمای تست سیستم (Software Testing)
|
||||
- Role & Core Objective
|
||||
- Required Review Group Closures
|
||||
- Operational Rules & Boundaries
|
||||
- Operational Rules & Boundaries
|
||||
- 🏢 AI Software Agency — Master Orchestration Protocol v3
|
||||
- @nestjs/cli
|
||||
- Operational Rules & Boundaries
|
||||
- Operational Rules & Boundaries
|
||||
- Bcrypt Type Definitions
|
||||
- bcryptjs
|
||||
- helmet
|
||||
- Blog Entity Model
|
||||
- Home Entity Model
|
||||
- Wiki Entity Model
|
||||
- User Profile Management
|
||||
- Pets Table
|
||||
- User Database and Infrastructure
|
||||
- API and Frontend Specifications
|
||||
- Brand and Agent Guidelines
|
||||
- Application ESLint Config
|
||||
- PostCSS Configuration
|
||||
- Vitest Test Setup
|
||||
- Database Backup Script
|
||||
- Application Startup Script
|
||||
- What You Must Do When Invoked
|
||||
- User Logout Endpoint
|
||||
- Company Profile
|
||||
- Project Introduction
|
||||
- Architecture Route Map
|
||||
- Project Task Backlog
|
||||
- Sahel Font Samples
|
||||
- Shabnam Font History
|
||||
- Vazirmatn Font History
|
||||
- Variable Font Samples
|
||||
- Shabnam Font Preview
|
||||
- Production Docker Setup
|
||||
- Staging Docker Setup
|
||||
- .agents/workflows/graphify.md
|
||||
- Role & Core Objective
|
||||
- graphify reference: extra exports and benchmark
|
||||
- graphify reference: query, path, explain
|
||||
- graphify reference: add a URL and watch a folder
|
||||
- graphify reference: commit hook and native CLAUDE.md integration
|
||||
- graphify reference: incremental update and cluster-only
|
||||
- graphify reference: GitHub clone and cross-repo merge
|
||||
- graphify reference: transcribe video and audio
|
||||
- Reconciled Audit Roles & Assignments
|
||||
- instructions.md
|
||||
- Phase 3.1 — Human Review Preparation and Master Backlog Critique
|
||||
- CLAUDE.md
|
||||
- .claude/CLAUDE.md
|
||||
- extraction-spec.md
|
||||
- User Login API
|
||||
- Developer Standards and Architecture
|
||||
- Deep Audit Summary Report
|
||||
- Operational Rules & Boundaries
|
||||
- Comprehensive Change Log
|
||||
- Operational Rules & Boundaries
|
||||
- 1. Summary of Integrity Repairs Performed
|
||||
- Operational Rules & Boundaries
|
||||
- Operational Rules & Boundaries
|
||||
- Operational Rules & Boundaries
|
||||
- Vazirmatn Changelog
|
||||
- Vazirmatn Font فونت وزیرمتن
|
||||
- Operational Rules & Boundaries
|
||||
- backend/README.md
|
||||
- Repository Map
|
||||
- Sahel-Font
|
||||
- AuthService
|
||||
- Sahel-Font
|
||||
- Role & Core Objective
|
||||
- exclude
|
||||
- Phase 2 Final Quality Gate Summary Report
|
||||
- Task Modifications Log
|
||||
- Install
|
||||
- .findAll
|
||||
- System Discovery
|
||||
- Product Requirement Document (PRD)
|
||||
- Baseline Command Plan & Reconciled Command History
|
||||
- Architecture Specification
|
||||
- Project Health Audit Report
|
||||
- Open Questions
|
||||
- Final Phase 2 Audit Closure Report
|
||||
- 📝 Active Agent Working Scratchpad
|
||||
- 🔍 Code Health Audit Review (01_auditor)
|
||||
- Omitted File Inspection Report
|
||||
- Phase 3.2 / 3.3 — Implementation Readiness & Architectural Finalization Report
|
||||
- Phase 3 Audit Traceability Matrix
|
||||
- API Contract Specification
|
||||
- ⚙️ Backend Technical Review (05_dev_backend)
|
||||
- 🎨 Frontend & Admin Panel Technical Review (06_dev_frontend)
|
||||
- 🚀 SEO & Content Strategy Review (12_seo_content)
|
||||
- Raw Finding Verification & Disposition Report
|
||||
- React + TypeScript + Vite
|
||||
- application/README.md
|
||||
- 🔒 Security & Performance Review (09_devops_security)
|
||||
- 👁️ UX & Persona Interface Review (08_visual_qa)
|
||||
- Compiler Diagnostic Dispositions
|
||||
- @eslint/eslintrc
|
||||
- js-yaml
|
||||
- globals
|
||||
- prettier
|
||||
- prisma
|
||||
- supertest
|
||||
- ts-loader
|
||||
- ts-node
|
||||
- @types/express
|
||||
- @types/jest
|
||||
- @types/js-yaml
|
||||
- @types/multer
|
||||
- eslint-plugin-react-hooks
|
||||
- eslint-plugin-react-refresh
|
||||
- tailwindcss
|
||||
- typescript
|
||||
- @testing-library/jest-dom
|
||||
- @testing-library/react
|
||||
- @types/react
|
||||
- typescript
|
||||
- vitest
|
||||
- typescript-eslint
|
||||
- @nestjs/core
|
||||
- @nestjs/jwt
|
||||
- @nestjs/swagger
|
||||
- @nestjs/throttler
|
||||
- passport-jwt
|
||||
- @prisma/client
|
||||
- swagger-ui-express
|
||||
- AGENTS.md
|
||||
- eslint-config-prettier
|
||||
- @eslint/js
|
||||
- jest
|
||||
- @nestjs/schematics
|
||||
- @nestjs/testing
|
||||
- source-map-support
|
||||
- ts-jest
|
||||
- tsconfig-paths
|
||||
- @types/bcryptjs
|
||||
- typescript-eslint
|
||||
- globals
|
||||
|
||||
## God Nodes (most connected - your core abstractions)
|
||||
1. `PrismaService` - 74 edges
|
||||
2. `Roles()` - 59 edges
|
||||
3. `PaginationDto` - 39 edges
|
||||
4. `SmsService` - 38 edges
|
||||
5. `api` - 34 edges
|
||||
6. `useSettingsStore` - 33 edges
|
||||
7. `AdminService` - 31 edges
|
||||
8. `toPersian()` - 31 edges
|
||||
9. `AdminController` - 30 edges
|
||||
10. `useCartStore` - 29 edges
|
||||
|
||||
## Surprising Connections (you probably didn't know these)
|
||||
- `User Profile Photo` --conceptually_related_to--> `User Roles and Capabilities` [INFERRED]
|
||||
backend/uploads/1781288429353-508765350.jpg → docs/02-user-guide.md
|
||||
- `AuthController` --references--> `ApiResponse` [EXTRACTED]
|
||||
backend/src/auth/auth.controller.ts → frontend/admin-panel/src/types/admin.ts
|
||||
- `BlogsController` --references--> `ApiResponse` [EXTRACTED]
|
||||
backend/src/blogs/blogs.controller.ts → frontend/admin-panel/src/types/admin.ts
|
||||
- `HomeController` --references--> `ApiResponse` [EXTRACTED]
|
||||
backend/src/home/home.controller.ts → frontend/admin-panel/src/types/admin.ts
|
||||
- `OrdersController` --references--> `ApiResponse` [EXTRACTED]
|
||||
backend/src/orders/orders.controller.ts → frontend/admin-panel/src/types/admin.ts
|
||||
|
||||
## Import Cycles
|
||||
- 3-file cycle: `frontend/application/lib/services/api.ts -> frontend/application/lib/store/userStore.ts -> frontend/application/lib/store/cartStore.ts -> frontend/application/lib/services/api.ts`
|
||||
- 3-file cycle: `frontend/application/lib/services/api.ts -> frontend/application/lib/store/userStore.ts -> frontend/application/lib/services/authService.ts -> frontend/application/lib/services/api.ts`
|
||||
- 4-file cycle: `frontend/application/lib/services/api.ts -> frontend/application/lib/store/userStore.ts -> frontend/application/lib/store/cartStore.ts -> frontend/application/lib/services/orderService.ts -> frontend/application/lib/services/api.ts`
|
||||
|
||||
## Hyperedges (group relationships)
|
||||
- **Rastikerdar Font Ecosystem** — frontend_application_public_fonts_shabnam_font_v5_0_1_readme, frontend_application_public_fonts_vazirmatn_v33_003_readme, vazir_font [EXTRACTED 0.95]
|
||||
- **Canina Deployment Stack** — scripts_compose_prod, scripts_compose_stage [EXTRACTED 1.00]
|
||||
|
||||
## Communities (285 total, 113 thin omitted)
|
||||
|
||||
### Community 0 - "AdminService"
|
||||
Cohesion: 0.07
|
||||
Nodes (22): AdminController, ApiBearerAuth, ApiOperation, ApiQuery, ApiTags, Body, Controller, Delete (+14 more)
|
||||
|
||||
### Community 1 - "pets/pets.controller.ts"
|
||||
Cohesion: 0.05
|
||||
Nodes (45): CreateHealthLogDto, ApiProperty, ApiPropertyOptional, IsNotEmpty, IsOptional, IsString, CreatePetDto, ApiProperty (+37 more)
|
||||
|
||||
### Community 2 - "Roles"
|
||||
Cohesion: 0.19
|
||||
Nodes (16): Roles(), SettingsController, ApiBearerAuth, ApiOkResponse, ApiOperation, ApiTags, Body, Controller (+8 more)
|
||||
|
||||
### Community 3 - "UsersService"
|
||||
Cohesion: 0.07
|
||||
Nodes (33): JwtPayload, JwtStrategy, Injectable, AddressDto, ApiProperty, ApiPropertyOptional, IsBoolean, IsNotEmpty (+25 more)
|
||||
|
||||
### Community 4 - "CmsController"
|
||||
Cohesion: 0.09
|
||||
Nodes (24): CmsController, ApiBearerAuth, ApiOperation, ApiTags, Body, Controller, Delete, Get (+16 more)
|
||||
|
||||
### Community 5 - "BannersService"
|
||||
Cohesion: 0.13
|
||||
Nodes (15): BannersController, ApiBearerAuth, ApiOperation, ApiTags, Body, Controller, Delete, Get (+7 more)
|
||||
|
||||
### Community 6 - "auth.controller.ts"
|
||||
Cohesion: 0.07
|
||||
Nodes (39): AuthController, ApiBadRequestResponse, ApiOkResponse, ApiOperation, ApiTags, Body, Controller, Post (+31 more)
|
||||
|
||||
### Community 7 - "app.module.ts"
|
||||
Cohesion: 0.10
|
||||
Nodes (25): AuthModule, Module, B2BModule, Module, BannersModule, Module, CmsModule, Module (+17 more)
|
||||
|
||||
### Community 8 - "CreateVideoDto"
|
||||
Cohesion: 0.07
|
||||
Nodes (31): CreateVideoDto, ApiProperty, ApiPropertyOptional, IsBoolean, IsNotEmpty, IsOptional, IsString, UpdateVideoDto (+23 more)
|
||||
|
||||
### Community 9 - "ProductService"
|
||||
Cohesion: 0.07
|
||||
Nodes (30): CatalogClient(), metadata, metadata, metadata, ArchivePage(), CATEGORY_MAP, ICON_MAP, BlogPost (+22 more)
|
||||
|
||||
### Community 10 - "SmartAdvisor.tsx"
|
||||
Cohesion: 0.32
|
||||
Nodes (6): CURRENT_SYMPTOMS, MEDICAL_HISTORIES, SmartAdvisor(), SmartAdvisorProps, UIState, useUIStore
|
||||
|
||||
### Community 11 - "compilerOptions"
|
||||
Cohesion: 0.06
|
||||
Nodes (32): compilerOptions, allowJs, esModuleInterop, incremental, isolatedModules, jsx, lib, module (+24 more)
|
||||
|
||||
### Community 12 - "toPersian"
|
||||
Cohesion: 0.08
|
||||
Nodes (37): ClientLayout(), VerifyContent(), AddressModal(), AddressModalProps, AuthModal(), AuthModalProps, B2BPortal(), BackButton() (+29 more)
|
||||
|
||||
### Community 14 - "ProductsService"
|
||||
Cohesion: 0.09
|
||||
Nodes (19): GetProductsDto, ApiPropertyOptional, IsEnum, IsOptional, IsString, ProductsController, ApiOperation, ApiTags (+11 more)
|
||||
|
||||
### Community 15 - "lib/services/api.ts"
|
||||
Cohesion: 0.08
|
||||
Nodes (17): metadata, ContactFormClient(), ContactInfoItem, PrescriptionUploadModal(), PrescriptionUploadModalProps, api, ApiErrorPayload, ApiErr (+9 more)
|
||||
|
||||
### Community 17 - "useSettingsStore"
|
||||
Cohesion: 0.07
|
||||
Nodes (30): HomeClient(), HomeClientProps, getHomeData(), Home(), metadata, metadata, EnamadBadge(), Footer() (+22 more)
|
||||
|
||||
### Community 19 - "B2B Inquiry Controller"
|
||||
Cohesion: 0.13
|
||||
Nodes (15): B2BController, ApiBearerAuth, ApiOperation, ApiTags, Body, Controller, Get, Param (+7 more)
|
||||
|
||||
### Community 20 - "Category Management Controller"
|
||||
Cohesion: 0.10
|
||||
Nodes (16): CategoriesController, ApiBearerAuth, ApiOperation, ApiQuery, ApiTags, Body, Controller, Delete (+8 more)
|
||||
|
||||
### Community 21 - "auth.service.ts"
|
||||
Cohesion: 0.10
|
||||
Nodes (10): AdminLoginInput, AuthService, LoginInput, RegisterInput, Injectable, RedisModule, Global, Module (+2 more)
|
||||
|
||||
### Community 22 - "MediaController"
|
||||
Cohesion: 0.10
|
||||
Nodes (16): MediaController, ApiBearerAuth, ApiOperation, ApiTags, Body, Controller, Delete, Get (+8 more)
|
||||
|
||||
### Community 23 - "Ingredient Management Controller"
|
||||
Cohesion: 0.13
|
||||
Nodes (14): IngredientsController, ApiBearerAuth, ApiOperation, ApiTags, Body, Controller, Delete, Get (+6 more)
|
||||
|
||||
### Community 24 - "adminRoutes.tsx"
|
||||
Cohesion: 0.08
|
||||
Nodes (18): App(), ContactInfoItem, ContactSubmission, CategoryDist, DashboardData, PatternItem, SmsConfigState, SmsLogItem (+10 more)
|
||||
|
||||
### Community 25 - "admin.module.ts"
|
||||
Cohesion: 0.10
|
||||
Nodes (14): AdminModule, Module, PetQuery, PetsService, Injectable, ReportsController, ApiBearerAuth, ApiOperation (+6 more)
|
||||
|
||||
### Community 26 - "ConfirmModal.tsx"
|
||||
Cohesion: 0.10
|
||||
Nodes (16): ConfirmModal(), ConfirmModalProps, HeroBanner, VetTestimonial, Pet, fetchVideosList(), Video, Videos() (+8 more)
|
||||
|
||||
### Community 27 - "Prescription Review Controller"
|
||||
Cohesion: 0.14
|
||||
Nodes (14): PrescriptionsController, ApiBearerAuth, ApiOperation, ApiTags, Body, Controller, Get, Param (+6 more)
|
||||
|
||||
### Community 28 - "Smart Advisor Controller"
|
||||
Cohesion: 0.13
|
||||
Nodes (14): SmartAdvisorController, ApiBearerAuth, ApiOperation, ApiTags, Body, Controller, Delete, Get (+6 more)
|
||||
|
||||
### Community 29 - "Testimonials Management Controller"
|
||||
Cohesion: 0.13
|
||||
Nodes (14): TestimonialsController, ApiBearerAuth, ApiOperation, ApiTags, Body, Controller, Delete, Get (+6 more)
|
||||
|
||||
### Community 30 - "src/services/api.ts"
|
||||
Cohesion: 0.10
|
||||
Nodes (27): Layout(), ProtectedRoute(), menuGroups, Sidebar(), SidebarProps, SEARCHABLE_PAGES, Topbar(), TopbarProps (+19 more)
|
||||
|
||||
### Community 31 - "Spinner.tsx"
|
||||
Cohesion: 0.08
|
||||
Nodes (23): Media, MediaSelector(), MediaSelectorProps, Spinner(), BlogPost, Category, Category, Product (+15 more)
|
||||
|
||||
### Community 32 - "useCartStore"
|
||||
Cohesion: 0.12
|
||||
Nodes (16): metadata, ArchiveProductCard(), ProductCard(), Header(), MENU_ICONS, OrderSuccess(), OrderTracking(), PetProfile() (+8 more)
|
||||
|
||||
### Community 33 - "ZibalService"
|
||||
Cohesion: 0.06
|
||||
Nodes (37): AdminTransactionFilterDto, ApiPropertyOptional, IsNumber, IsOptional, IsString, Type, InitiatePaymentDto, InitiateWalletTopupDto (+29 more)
|
||||
|
||||
### Community 34 - "main.ts"
|
||||
Cohesion: 0.14
|
||||
Nodes (9): CustomHttpExceptionFilter, Catch, PrismaExceptionFilter, Catch, DecimalInterceptor, Injectable, ApiErrorResponse, ErrorDetailField (+1 more)
|
||||
|
||||
### Community 35 - "ContactService"
|
||||
Cohesion: 0.13
|
||||
Nodes (11): ContactController, Body, Controller, Get, Param, Post, Put, Query (+3 more)
|
||||
|
||||
### Community 36 - "Backend TypeScript Config"
|
||||
Cohesion: 0.09
|
||||
Nodes (22): compilerOptions, allowSyntheticDefaultImports, baseUrl, declaration, emitDecoratorMetadata, esModuleInterop, experimentalDecorators, forceConsistentCasingInFileNames (+14 more)
|
||||
|
||||
### Community 37 - "App TypeScript Config"
|
||||
Cohesion: 0.09
|
||||
Nodes (22): compilerOptions, allowImportingTsExtensions, erasableSyntaxOnly, jsx, lib, module, moduleDetection, moduleResolution (+14 more)
|
||||
|
||||
### Community 38 - "Coupons.tsx"
|
||||
Cohesion: 0.09
|
||||
Nodes (15): Pagination(), PaginationProps, Coupon, CouponFormData, CouponModalProps, CouponTarget, Media, Stats (+7 more)
|
||||
|
||||
### Community 39 - "dependencies"
|
||||
Cohesion: 0.10
|
||||
Nodes (21): dependencies, bcrypt, class-transformer, class-validator, ioredis, @nestjs/common, @nestjs/passport, @nestjs/platform-express (+13 more)
|
||||
|
||||
### Community 40 - "Node TypeScript Config"
|
||||
Cohesion: 0.10
|
||||
Nodes (20): compilerOptions, allowImportingTsExtensions, erasableSyntaxOnly, lib, module, moduleDetection, moduleResolution, noEmit (+12 more)
|
||||
|
||||
### Community 41 - "Admin Blog Controller"
|
||||
Cohesion: 0.13
|
||||
Nodes (15): BlogsController, ApiBearerAuth, ApiOperation, ApiQuery, ApiTags, Body, Controller, Delete (+7 more)
|
||||
|
||||
### Community 42 - "WholesaleApplyDto"
|
||||
Cohesion: 0.10
|
||||
Nodes (20): ApiProperty, ApiPropertyOptional, IsNotEmpty, IsOptional, IsString, WholesaleApplyDto, ApiBearerAuth, ApiOperation (+12 more)
|
||||
|
||||
### Community 43 - "devDependencies"
|
||||
Cohesion: 0.13
|
||||
Nodes (15): eslint-config-next, devDependencies, eslint, eslint-config-next, jsdom, tailwindcss, @tailwindcss/postcss, @types/node (+7 more)
|
||||
|
||||
### Community 44 - "Generic CRUD Controller"
|
||||
Cohesion: 0.13
|
||||
Nodes (14): ApiBearerAuth, ApiOperation, ApiQuery, ApiTags, Body, Controller, Delete, Get (+6 more)
|
||||
|
||||
### Community 45 - "seo.module.ts"
|
||||
Cohesion: 0.16
|
||||
Nodes (10): SeoController, ApiOperation, ApiTags, Controller, Get, Param, SeoModule, Module (+2 more)
|
||||
|
||||
### Community 46 - "OrdersController"
|
||||
Cohesion: 0.13
|
||||
Nodes (16): OrdersController, ApiBadRequestResponse, ApiBearerAuth, ApiCreatedResponse, ApiNotFoundResponse, ApiOkResponse, ApiOperation, ApiTags (+8 more)
|
||||
|
||||
### Community 47 - "Project Build Scripts"
|
||||
Cohesion: 0.11
|
||||
Nodes (17): concurrently, devDependencies, concurrently, name, private, scripts, build, build:admin (+9 more)
|
||||
|
||||
### Community 48 - "Home Data Module"
|
||||
Cohesion: 0.16
|
||||
Nodes (10): HomeController, ApiOkResponse, ApiOperation, ApiTags, Controller, Get, HomeModule, Module (+2 more)
|
||||
|
||||
### Community 49 - "devDependencies"
|
||||
Cohesion: 0.11
|
||||
Nodes (19): autoprefixer, devDependencies, autoprefixer, eslint, @eslint/js, postcss, @tailwindcss/postcss, @types/node (+11 more)
|
||||
|
||||
### Community 50 - "Database Seeding Logic"
|
||||
Cohesion: 0.17
|
||||
Nodes (12): prisma, main(), prisma, determineSuitableFor(), findOrCreateCategory(), getProductImageUrl(), main(), parseSize() (+4 more)
|
||||
|
||||
### Community 51 - "Prisma Database Migrations"
|
||||
Cohesion: 0.27
|
||||
Nodes (14): "coupons", "health_logs", "order_items", "orders", "pet_medical_conditions", "pets", "product_ingredients", "product_symptoms" (+6 more)
|
||||
|
||||
### Community 52 - "dependencies"
|
||||
Cohesion: 0.10
|
||||
Nodes (21): dependencies, axios, lucide-react, react, react-dom, react-hot-toast, react-router-dom, recharts (+13 more)
|
||||
|
||||
### Community 53 - "UI Skeleton and Tables"
|
||||
Cohesion: 0.18
|
||||
Nodes (11): Skeleton(), Order, OrderItem, Orders(), statusStyles, toPersianDigits(), UserRecord, Orders (+3 more)
|
||||
|
||||
### Community 54 - "components/Skeleton.tsx"
|
||||
Cohesion: 0.33
|
||||
Nodes (4): OrderRowSkeleton(), PetProfileSkeleton(), Skeleton(), SkeletonProps
|
||||
|
||||
### Community 55 - "BE-001"
|
||||
Cohesion: 0.06
|
||||
Nodes (32): Acceptance Criteria, Affected Application, Affected Files, Alternative Direction, BE-001, Category, Completion Statement, Confidence (+24 more)
|
||||
|
||||
### Community 56 - "VetGallery.tsx"
|
||||
Cohesion: 0.22
|
||||
Nodes (8): DisplayVideoItem, FALLBACK_VIDEOS, TestimonialItem, VetGallery(), FALLBACK_VIDEOS, VideosPage(), Video, videoService
|
||||
|
||||
### Community 57 - "NPM Lifecycle Scripts"
|
||||
Cohesion: 0.14
|
||||
Nodes (14): scripts, build, docs:generate, format, lint, start, start:debug, start:dev (+6 more)
|
||||
|
||||
### Community 58 - "Pet Management API"
|
||||
Cohesion: 0.15
|
||||
Nodes (11): PetsController, ApiBearerAuth, ApiOperation, ApiQuery, ApiTags, Controller, Delete, Get (+3 more)
|
||||
|
||||
### Community 59 - "PrismaService"
|
||||
Cohesion: 0.08
|
||||
Nodes (18): ApiExcludeController, CouponTargetInput, PaginationQuery, CategoryQuery, MetricsController, Controller, Get, Res (+10 more)
|
||||
|
||||
### Community 60 - "Jest Testing Config"
|
||||
Cohesion: 0.15
|
||||
Nodes (13): jest, collectCoverageFrom, coverageDirectory, moduleFileExtensions, rootDir, testEnvironment, testRegex, transform (+5 more)
|
||||
|
||||
### Community 61 - "PaginationDto"
|
||||
Cohesion: 0.13
|
||||
Nodes (13): PaginationDto, SortOrder, ApiPropertyOptional, IsEnum, IsOptional, IsString, Type, Module (+5 more)
|
||||
|
||||
### Community 62 - "SettingsService"
|
||||
Cohesion: 0.11
|
||||
Nodes (4): SmsLogQuery, ScientificTermData, SettingsService, Injectable
|
||||
|
||||
### Community 63 - "FE-001"
|
||||
Cohesion: 0.06
|
||||
Nodes (31): Acceptance Criteria, Affected Application, Affected Files, Alternative Direction, Architecture Overview & Confirmed Strengths, Category, Completion Statement, Confidence (+23 more)
|
||||
|
||||
### Community 64 - "payment.module.ts"
|
||||
Cohesion: 0.16
|
||||
Nodes (10): SmsModule, Global, Module, ContactModule, Module, PaymentModule, Module, ZibalInquiryResponse (+2 more)
|
||||
|
||||
### Community 66 - "App Health Controller"
|
||||
Cohesion: 0.29
|
||||
Nodes (5): AppController, Controller, Get, AppService, Injectable
|
||||
|
||||
### Community 67 - "dependencies"
|
||||
Cohesion: 0.12
|
||||
Nodes (17): dependencies, axios, lucide-react, motion, next, react, react-dom, sonner (+9 more)
|
||||
|
||||
### Community 68 - "OrdersService"
|
||||
Cohesion: 0.12
|
||||
Nodes (15): CreateOrderDto, OrderItemDto, ApiProperty, ApiPropertyOptional, IsArray, IsNotEmpty, IsNumber, IsOptional (+7 more)
|
||||
|
||||
### Community 69 - "Integrity Validation Scripts"
|
||||
Cohesion: 0.20
|
||||
Nodes (9): dispSum, errors, invalidNewIds, manifest, report, trackedFiles, uninspected, verifiedIndex (+1 more)
|
||||
|
||||
### Community 70 - "Admin Panel Package Config"
|
||||
Cohesion: 0.20
|
||||
Nodes (9): name, private, scripts, build, dev, lint, preview, type (+1 more)
|
||||
|
||||
### Community 71 - "Analytics and Report Charts"
|
||||
Cohesion: 0.20
|
||||
Nodes (7): BestSellerItem, CategoryDistItem, COLORS, CustomTooltipProps, ReportData, TopCouponItem, Reports
|
||||
|
||||
### Community 72 - "Task Orchestration Scripts"
|
||||
Cohesion: 0.53
|
||||
Nodes (8): cmd_next_task(), cmd_progress(), cmd_reset(), cmd_status(), cmd_unblock(), load_json(), main(), save_json()
|
||||
|
||||
### Community 73 - "Backend Package Config"
|
||||
Cohesion: 0.22
|
||||
Nodes (8): author, description, license, name, prisma, seed, private, version
|
||||
|
||||
### Community 74 - "BlogsController"
|
||||
Cohesion: 0.20
|
||||
Nodes (7): BlogsController, ApiTags, Controller, BlogsModule, Module, BlogsService, Injectable
|
||||
|
||||
### Community 75 - "React Error Boundary"
|
||||
Cohesion: 0.22
|
||||
Nodes (3): ErrorBoundary, Props, State
|
||||
|
||||
### Community 76 - "Application Package Config"
|
||||
Cohesion: 0.22
|
||||
Nodes (8): name, private, scripts, build, dev, lint, start, version
|
||||
|
||||
### Community 77 - "WikiController"
|
||||
Cohesion: 0.21
|
||||
Nodes (9): ApiNotFoundResponse, ApiOkResponse, ApiOperation, ApiTags, Controller, Get, Param, Query (+1 more)
|
||||
|
||||
### Community 79 - "VPN Utility Scripts"
|
||||
Cohesion: 0.62
|
||||
Nodes (6): cleanup(), log(), with-vpn.sh script, start_vpn(), stop_vpn(), vpn_is_up()
|
||||
|
||||
### Community 80 - "NestJS CLI Config"
|
||||
Cohesion: 0.33
|
||||
Nodes (5): collection, compilerOptions, deleteOutDir, $schema, sourceRoot
|
||||
|
||||
### Community 81 - "Seed TypeScript Config"
|
||||
Cohesion: 0.33
|
||||
Nodes (5): compilerOptions, esModuleInterop, module, moduleResolution, skipLibCheck
|
||||
|
||||
### Community 82 - "ADM-001"
|
||||
Cohesion: 0.06
|
||||
Nodes (31): Acceptance Criteria, ADM-001, Admin Features Audit Report, Affected Application, Affected Files, Alternative Direction, Category, Completion Statement (+23 more)
|
||||
|
||||
### Community 83 - "Browser Utility Scripts"
|
||||
Cohesion: 0.40
|
||||
Nodes (5): checkAndOpen(), { exec }, http, openUrl(), URLS
|
||||
|
||||
### Community 84 - "Dev Server Startup"
|
||||
Cohesion: 0.33
|
||||
Nodes (4): backend, http, { spawn }, waitForBackend()
|
||||
|
||||
### Community 86 - "Pagination API Schemas"
|
||||
Cohesion: 0.50
|
||||
Nodes (3): PaginatedResponse, PaginationMeta, ApiProperty
|
||||
|
||||
### Community 87 - "Font Assets and Licenses"
|
||||
Cohesion: 0.40
|
||||
Nodes (5): DejaVu Sans Font, Vazirmatn Authors, SIL Open Font License (OFL), Vazirmatn Font README, Roboto Font
|
||||
|
||||
### Community 88 - "Ledger Rebuild Scripts"
|
||||
Cohesion: 0.40
|
||||
Nodes (4): evidenceList, ledger, mandatoryMap, mandatoryScope
|
||||
|
||||
### Community 89 - "Evidence Validation Scripts"
|
||||
Cohesion: 0.40
|
||||
Nodes (4): activeFiles, errors, validationOutput, warnings
|
||||
|
||||
### Community 90 - "Blog Listing Page"
|
||||
Cohesion: 0.50
|
||||
Nodes (4): Blog(), getBlogs(), metadata, BlogPage()
|
||||
|
||||
### Community 91 - "Blog Post Detail Page"
|
||||
Cohesion: 0.60
|
||||
Nodes (4): BlogPostPage(), generateMetadata(), getBlog(), revalidate
|
||||
|
||||
### Community 93 - "devDependencies"
|
||||
Cohesion: 0.22
|
||||
Nodes (9): devDependencies, eslint-plugin-prettier, @types/passport-jwt, @types/supertest, typescript, typescript, eslint-plugin-prettier, @types/passport-jwt (+1 more)
|
||||
|
||||
### Community 99 - "Wiki Page Routing"
|
||||
Cohesion: 0.83
|
||||
Nodes (3): generateMetadata(), getWikiTerm(), WikiTermPage()
|
||||
|
||||
### Community 101 - "Docker Deployment Scripts"
|
||||
Cohesion: 0.50
|
||||
Nodes (3): COMPOSE_DOCKER_CLI_BUILD, DOCKER_BUILDKIT, deploy.sh script
|
||||
|
||||
### Community 102 - "DB-001"
|
||||
Cohesion: 0.06
|
||||
Nodes (31): Acceptance Criteria, Affected Application, Affected Files, Alternative Direction, Category, Completion Statement, Confidence, Database and Data Integrity Audit Report (+23 more)
|
||||
|
||||
### Community 103 - "BlogsService"
|
||||
Cohesion: 0.22
|
||||
Nodes (3): BlogQuery, BlogsService, Injectable
|
||||
|
||||
### Community 109 - "Auth Architecture and Planning"
|
||||
Cohesion: 0.67
|
||||
Nodes (3): ADR-AUTH-001: Admin Panel Authentication Architecture & Token Management, Master Task Backlog (Phase 3.3), Phase 3 Master Execution Plan
|
||||
|
||||
### Community 117 - "WikiService"
|
||||
Cohesion: 0.22
|
||||
Nodes (3): Injectable, WikiQuery, WikiService
|
||||
|
||||
### Community 118 - "TS-001"
|
||||
Cohesion: 0.06
|
||||
Nodes (31): Acceptance Criteria, Affected Application, Affected Files, Alternative Direction, Category, Completion Statement, Confidence, Dependencies (+23 more)
|
||||
|
||||
### Community 119 - "TEST-001"
|
||||
Cohesion: 0.06
|
||||
Nodes (31): Acceptance Criteria, Affected Application, Affected Files, Alternative Direction, Category, Completion Statement, Confidence, Dependencies (+23 more)
|
||||
|
||||
### Community 120 - "ValidateCouponDto"
|
||||
Cohesion: 0.50
|
||||
Nodes (4): IsNotEmpty, IsNumber, IsString, ValidateCouponDto
|
||||
|
||||
### Community 126 - "Typography and Font Assets"
|
||||
Cohesion: 0.67
|
||||
Nodes (3): Shabnam Font README, Shabnam Font Sample, Vazir Font
|
||||
|
||||
### Community 127 - "DEVOPS-001"
|
||||
Cohesion: 0.06
|
||||
Nodes (31): Acceptance Criteria, Affected Application, Affected Files, Alternative Direction, Category, Completion Statement, Confidence, Dependencies (+23 more)
|
||||
|
||||
### Community 128 - "DOC-001"
|
||||
Cohesion: 0.06
|
||||
Nodes (31): Acceptance Criteria, Affected Application, Affected Files, Alternative Direction, Category, Completion Statement, Confidence, Dependencies (+23 more)
|
||||
|
||||
### Community 129 - "What You Must Do When Invoked"
|
||||
Cohesion: 0.07
|
||||
Nodes (26): For /graphify add and --watch, For /graphify query, For the commit hook and native CLAUDE.md integration, For --update and --cluster-only, /graphify, Honesty Rules, Interpreter guard for subcommands, Part A - Structural extraction for code files (+18 more)
|
||||
|
||||
### Community 130 - "JwtAuthGuard"
|
||||
Cohesion: 0.18
|
||||
Nodes (7): JwtAuthGuard, Injectable, ROLES_KEY, RequestWithUser, RolesGuard, Injectable, UserReqPayload
|
||||
|
||||
### Community 131 - "راهنمای تست سیستم (Software Testing)"
|
||||
Cohesion: 0.07
|
||||
Nodes (25): اجرای بکاند, اجرای فرانتاند, اجرای پروژه در سرور با PM2, برای راهاندازی بکاند:, برای راهاندازی فرانتاند Next.js:, بیلد کردن پروژه (Building), ذخیره پروسهها تا پس از ریاستارت سرور قطع نشوند:, راهاندازی و انتشار سیستم (Setup & Deployment) (+17 more)
|
||||
|
||||
### Community 132 - "Role & Core Objective"
|
||||
Cohesion: 0.09
|
||||
Nodes (22): CREATE MODE — Normal Operation, Expected JSON Output Schema, File Scope Boundary, Forbidden Actions, MODE 1: REVIEW (called during Review Phase), MODE 2: CONTENT CREATION (standalone task from backlog), Operating Modes, Operational Rules & Boundaries (+14 more)
|
||||
|
||||
### Community 133 - "Required Review Group Closures"
|
||||
Cohesion: 0.10
|
||||
Nodes (19): 10. Orders Backend, 11. Settings & Administrative Backend, 12. Prisma Schema, Migrations & Seed, 13. Redis & Temporary Auth State, 14. Unit & E2E Tests, 15. Docker, NGINX, Prometheus & Deployment Config, 16. Documentation & OpenAPI Artifacts, 1. Storefront Shell & Routing (+11 more)
|
||||
|
||||
### Community 134 - "Operational Rules & Boundaries"
|
||||
Cohesion: 0.11
|
||||
Nodes (18): 1. Always Read Tech Stack First, 2. Sub-step Execution (Token Resume Support), 3. API Mocking Requirement, 4. Modular Component Architecture, 5. Responsive Design (Mandatory), 6. File Scope Boundary, 7. Forbidden Actions, Expected JSON Output Schema (+10 more)
|
||||
|
||||
### Community 135 - "Operational Rules & Boundaries"
|
||||
Cohesion: 0.11
|
||||
Nodes (18): 1. Framework-Aware Analysis, 2. DOM & Semantic Structure Analysis, 3. Accessibility Compliance, 4. Responsive Layout Verification, 5. Fallback Inspection Mode, 6. Defect Routing Protocol, 7. Forbidden Actions, Expected JSON Output Schema (+10 more)
|
||||
|
||||
### Community 136 - "🏢 AI Software Agency — Master Orchestration Protocol v3"
|
||||
Cohesion: 0.11
|
||||
Nodes (17): Activation, Agent Directory Reference, 🏢 AI Software Agency — Master Orchestration Protocol v3, Phase 1: Specialist Review (All agents read, none write code yet), Phase 2: Master Synthesis (02_product_manager in SYNTHESIS mode), Phase 3: Execution (Same as always), PIPELINE A — New Project (GREENFIELD), PIPELINE B — Review & Improve Existing Project (REVIEW_AND_PLAN) ★ (+9 more)
|
||||
|
||||
### Community 138 - "Operational Rules & Boundaries"
|
||||
Cohesion: 0.11
|
||||
Nodes (17): 1. Hierarchical Decomposition Algorithm (3-Tier), 2. Sub-step Definition (Required for all tasks), 3. Brownfield Completeness Rule, 4. Role Assignment Rules, 5. Dependency Tracking (Strict), 6. Priority Assignment, 7. Forbidden Actions, DECOMPOSE MODE — Normal Operation (New Projects) (+9 more)
|
||||
|
||||
### Community 139 - "Operational Rules & Boundaries"
|
||||
Cohesion: 0.11
|
||||
Nodes (17): 1. Always Read Tech Stack First, 2. Sub-step Execution (Token Resume Support), 3. Mandatory Test Authoring, 4. Code Quality Standards, 5. File Scope Boundary, 6. Forbidden Actions, Expected JSON Output Schema, IMPLEMENT MODE — Normal Operation (+9 more)
|
||||
|
||||
### Community 157 - "What You Must Do When Invoked"
|
||||
Cohesion: 0.07
|
||||
Nodes (26): For /graphify add and --watch, For /graphify query, For the commit hook and native CLAUDE.md integration, For --update and --cluster-only, /graphify, Honesty Rules, Interpreter guard for subcommands, Part A - Structural extraction for code files (+18 more)
|
||||
|
||||
### Community 177 - "Role & Core Objective"
|
||||
Cohesion: 0.12
|
||||
Nodes (16): 1. Active Secret Scanning (All Modified Files), 2. Docker Container Verification (if Dockerfile exists), 3. CI/CD Basic Check (if `.github/workflows/` exists), 4. Failure Routing Protocol, 5. Forbidden Actions, ENFORCE MODE — Normal Operation, Expected JSON Output Schema, Operational Rules & Boundaries (+8 more)
|
||||
|
||||
### Community 178 - "graphify reference: extra exports and benchmark"
|
||||
Cohesion: 0.22
|
||||
Nodes (8): graphify reference: extra exports and benchmark, Step 6b - Wiki (only if --wiki flag), Step 7 - Neo4j export (only if --neo4j or --neo4j-push flag), Step 7a - FalkorDB export (only if --falkordb or --falkordb-push flag), Step 7b - SVG export (only if --svg flag), Step 7c - GraphML export (only if --graphml flag), Step 7d - MCP server (only if --mcp flag), Step 8 - Token reduction benchmark (only if total_words > 5000)
|
||||
|
||||
### Community 179 - "graphify reference: query, path, explain"
|
||||
Cohesion: 0.33
|
||||
Nodes (5): For /graphify explain, For /graphify path, graphify reference: query, path, explain, Step 0 — Constrained query expansion (REQUIRED before traversal), Step 1 — Traversal
|
||||
|
||||
### Community 180 - "graphify reference: add a URL and watch a folder"
|
||||
Cohesion: 0.50
|
||||
Nodes (3): For /graphify add, For --watch, graphify reference: add a URL and watch a folder
|
||||
|
||||
### Community 181 - "graphify reference: commit hook and native CLAUDE.md integration"
|
||||
Cohesion: 0.50
|
||||
Nodes (3): For git commit hook, For native CLAUDE.md integration, graphify reference: commit hook and native CLAUDE.md integration
|
||||
|
||||
### Community 182 - "graphify reference: incremental update and cluster-only"
|
||||
Cohesion: 0.50
|
||||
Nodes (3): For --cluster-only, For --update (incremental re-extraction), graphify reference: incremental update and cluster-only
|
||||
|
||||
### Community 185 - "Reconciled Audit Roles & Assignments"
|
||||
Cohesion: 0.12
|
||||
Nodes (15): 10. Documentation Engineer, 1. Lead Architect / Orchestrator, 2. React / Vite Storefront Auditor, 3. NestJS Backend Auditor, 4. Admin Features Auditor, 5. Database & Data Integrity Auditor, 6. Security Auditor, 7. TypeScript & Code Quality Auditor (+7 more)
|
||||
|
||||
### Community 187 - "Phase 3.1 — Human Review Preparation and Master Backlog Critique"
|
||||
Cohesion: 0.13
|
||||
Nodes (14): 10. Dependency & Wave Adjustments, 11. Acceptance Criteria Refinements, 12. Business and Product Decision Classification, 13. Final Recommended Backlog Summary, 1. Executive Assessment, 2. Findings That Require No Change, 3. Findings Requiring Task Refinements, 4. Tasks Requiring Splitting (+6 more)
|
||||
|
||||
### Community 193 - "Deep Audit Summary Report"
|
||||
Cohesion: 0.14
|
||||
Nodes (13): 1. Audit Overview, 2. Findings Metrics, 3. Inspected Scope & Command Log, 4. Key Business & Integration Questions, 5. Audit Limitations & Integrity Confirmation, 6. Exact Next Recommended Phase, Blocked Commands & Reasons, By Confidence (+5 more)
|
||||
|
||||
### Community 194 - "Operational Rules & Boundaries"
|
||||
Cohesion: 0.15
|
||||
Nodes (12): 1. Stack Detection (Brownfield), 2. Stack Selection (Greenfield), 3. Single Non-Negotiable Stack Choice, 4. Tech Stack Must Be Written to state.json, 5. Directory Layout, 6. OpenAPI / API Contract, 7. Forbidden Actions, Expected JSON Output Schema (+4 more)
|
||||
|
||||
### Community 195 - "Comprehensive Change Log"
|
||||
Cohesion: 0.15
|
||||
Nodes (12): 10. `TASK-VERIFY-001`, 1. `TASK-SEC-001`, 2. `TASK-SEC-002`, 3. `TASK-SEC-003`, 4. `TASK-FIN-001`, 5. `TASK-BUILD-001`, 6. `TASK-AUTH-001`, 7. `TASK-FE-001` (+4 more)
|
||||
|
||||
### Community 196 - "Operational Rules & Boundaries"
|
||||
Cohesion: 0.17
|
||||
Nodes (11): 1. Detect Test Runner from Tech Stack, 2. Execution Output Capture (Mandatory), 3. Acceptance Criteria Verification, 4. Failure Routing Protocol, 5. Success Routing Protocol, 6. Forbidden Actions, Expected JSON Output Schema, Operational Rules & Boundaries (+3 more)
|
||||
|
||||
### Community 197 - "1. Summary of Integrity Repairs Performed"
|
||||
Cohesion: 0.17
|
||||
Nodes (11): 1.1 Authoritative Source File Inventory Rebuilt, 1.2 Raw Finding Dispositions Reconciled, 1.3 Finding Identifier Normalization, 1.4 Rejected Finding Cleanup, 1. Summary of Integrity Repairs Performed, 2. Final Verified Finding Metrics, 3. Reference and Compiler Integrity Results, 4. Quality Gate Conclusion (+3 more)
|
||||
|
||||
### Community 198 - "Operational Rules & Boundaries"
|
||||
Cohesion: 0.18
|
||||
Nodes (10): 1. Detect Tech Stack First (Universal), 2. Explicit Scoring Methodology (Universal), 3. Code Coverage Ratio Rule, 4. Deep Directory Scanning, 5. Forbidden Actions, Expected JSON Output Schema, Operational Rules & Boundaries, Required Output Artifacts (What files to write/update) (+2 more)
|
||||
|
||||
### Community 199 - "Operational Rules & Boundaries"
|
||||
Cohesion: 0.18
|
||||
Nodes (10): 1. Mark Active Task as Complete, 2. Documentation Updates, 3. Dynamic Routing Protocol (CRITICAL), 4. Backlog Insufficiency Check, 5. Forbidden Actions, Expected JSON Output Schema, Operational Rules & Boundaries, Required Output Artifacts (What files to write/update) (+2 more)
|
||||
|
||||
### Community 200 - "Operational Rules & Boundaries"
|
||||
Cohesion: 0.18
|
||||
Nodes (10): 1. Pre-Deployment Checklist, 2. Build Verification, 3. Deployment Strategy (Based on Target), 4. Post-Deployment Health Check, 5. Forbidden Actions, Expected JSON Output Schema, Operational Rules & Boundaries, Required Output Artifacts (What files to write/update) (+2 more)
|
||||
|
||||
### Community 201 - "Vazirmatn Changelog"
|
||||
Cohesion: 0.18
|
||||
Nodes (10): 32.0.0, 32.1, 32.101, 32.102, 33.000, 33.001, 33.002, 33.003 (+2 more)
|
||||
|
||||
### Community 202 - "Vazirmatn Font فونت وزیرمتن"
|
||||
Cohesion: 0.18
|
||||
Nodes (10): Arch Linux ([AUR](https://aur.archlinux.org/packages/vazirmatn-fonts)), Authors, Build, CDN, Download, Install, License, [npm](https://www.npmjs.com/package/vazirmatn) (+2 more)
|
||||
|
||||
### Community 203 - "Operational Rules & Boundaries"
|
||||
Cohesion: 0.20
|
||||
Nodes (9): 1. Mode & Direction Decision, 2. Brownfield Strategic Evaluation, 3. Risk Assessment, 4. Forbidden Actions, Expected JSON Output Schema, Operational Rules & Boundaries, Required Output Artifacts (What files to write/update), Role & Core Objective (+1 more)
|
||||
|
||||
### Community 204 - "backend/README.md"
|
||||
Cohesion: 0.20
|
||||
Nodes (9): Compile and run the project, Deployment, Description, License, Project setup, Resources, Run tests, Stay in touch (+1 more)
|
||||
|
||||
### Community 205 - "Repository Map"
|
||||
Cohesion: 0.20
|
||||
Nodes (9): 1. Active Customer Storefront: React 19 + Vite Application, 2. Active Backend Service: NestJS Application, 3. Excluded Placeholder / Non-Auditable Directories, Active Applications & Non-Auditable Scopes, Documentation Governance, Important Configuration & Infrastructure Files, Mandatory Global Audit Exclusions, Repository Map (+1 more)
|
||||
|
||||
### Community 206 - "Sahel-Font"
|
||||
Cohesion: 0.20
|
||||
Nodes (9): Arch Linux, Contributors, Install, Known problems for variable version, License, Sahel-Font, To Do (variable), طریقه استفاده از نسخه متغیر variable (+1 more)
|
||||
|
||||
### Community 208 - "Sahel-Font"
|
||||
Cohesion: 0.20
|
||||
Nodes (9): Arch Linux, Contributors, Install, Known problems for variable version, License, Sahel-Font, To Do (variable), طریقه استفاده از نسخه متغیر variable (+1 more)
|
||||
|
||||
### Community 209 - "Role & Core Objective"
|
||||
Cohesion: 0.22
|
||||
Nodes (8): 1. Ask — Don't Assume, 2. Forbidden Actions, Brownfield Detection, Expected JSON Output Schema, Operational Rules & Boundaries, Required Output Artifacts (What files to write/update), Role & Core Objective, Strict Input Specifications (What files to read)
|
||||
|
||||
### Community 210 - "exclude"
|
||||
Cohesion: 0.22
|
||||
Nodes (8): exclude, extends, node_modules, prisma, dist, **/*spec.ts, test, ./tsconfig.json
|
||||
|
||||
### Community 211 - "Phase 2 Final Quality Gate Summary Report"
|
||||
Cohesion: 0.22
|
||||
Nodes (8): 1. Executive Summary, 2. Final Verified Finding Breakdown, 3. Source Coverage & Diagnostic Metrics, 4. Integrity Check & Quality Gate Status, 5. Exact Next Recommended Phase, By Confidence, By Severity, Phase 2 Final Quality Gate Summary Report
|
||||
|
||||
### Community 212 - "Task Modifications Log"
|
||||
Cohesion: 0.22
|
||||
Nodes (8): 1. `TASK-AUTH-001`, 2. `TASK-FIN-001`, 3. `DECISION-002`, 4. `TASK-VERIFY-001`, 5. `TASK-SEC-001` & `TASK-SEC-002`, 6. `TASK-BUILD-001` & Execution Waves, Phase 3.1 — Master Task Backlog Change Log, Task Modifications Log
|
||||
|
||||
### Community 213 - "Install"
|
||||
Cohesion: 0.22
|
||||
Nodes (8): Arch Linux, bower, Install, npm, Shabnam Font, yarn, طریقه استفاده در صفحات وب:, نمونه متن Sample:
|
||||
|
||||
### Community 214 - ".findAll"
|
||||
Cohesion: 0.32
|
||||
Nodes (6): ApiNotFoundResponse, ApiOkResponse, ApiOperation, Get, Param, Query
|
||||
|
||||
### Community 215 - "System Discovery"
|
||||
Cohesion: 0.25
|
||||
Nodes (7): Active Core Applications, Current Architecture, Evidence-Based Status Matrix, Excluded / Non-Auditable Artifacts, Major Business Domains Discovered, System Discovery, Technical Architecture Summary
|
||||
|
||||
### Community 216 - "Product Requirement Document (PRD)"
|
||||
Cohesion: 0.29
|
||||
Nodes (6): 1. Executive Vision, 2. Target Audience, 3. Functional Requirements, 4. Non-Functional Requirements (Performance, Security), 5. Epic / Feature Breakdown, Product Requirement Document (PRD)
|
||||
|
||||
### Community 217 - "Baseline Command Plan & Reconciled Command History"
|
||||
Cohesion: 0.29
|
||||
Nodes (6): Attempted Command Execution Log, Backend `backend/package.json` Scripts, Baseline Command Plan & Reconciled Command History, Package Scripts Safety Analysis, Permitted Safe Checks for Phase 2, Root `package.json` Scripts
|
||||
|
||||
### Community 218 - "Architecture Specification"
|
||||
Cohesion: 0.33
|
||||
Nodes (5): 1. Single Non-Negotiable Tech Stack, 2. Directory Structure Tree, 3. State Management Strategy, 4. Deployment / Docker Architecture, Architecture Specification
|
||||
|
||||
### Community 219 - "Project Health Audit Report"
|
||||
Cohesion: 0.33
|
||||
Nodes (5): 1. Audit Score Summary, 2. Technical Debt Inventory, 3. Outdated Dependencies List, 4. Security Risks (.env leaks, unprotected ports), Project Health Audit Report
|
||||
|
||||
### Community 220 - "Open Questions"
|
||||
Cohesion: 0.33
|
||||
Nodes (5): 1. Storefront Migration Roadmap (`frontend/application`), 2. Payment Gateway Integration Provider, 3. Deployment & CI/CD Pipeline Specifications, 4. SMS / OTP Service Provider, Open Questions
|
||||
|
||||
### Community 221 - "Final Phase 2 Audit Closure Report"
|
||||
Cohesion: 0.33
|
||||
Nodes (5): 1. Executive Summary & Honest Review-Tier Metrics, 2. Reconciled Findings & Canonical Identifier Normalization, 3. Validation & Integrity Verification, 4. Final Quality Gate Conclusion, Final Phase 2 Audit Closure Report
|
||||
|
||||
### Community 222 - "📝 Active Agent Working Scratchpad"
|
||||
Cohesion: 0.40
|
||||
Nodes (4): 📝 Active Agent Working Scratchpad, 🏗️ Execution Target, Project: Canina Veterinary E-Commerce System, 📋 Requirements & Persona Mandates (Intake & User Request)
|
||||
|
||||
### Community 223 - "🔍 Code Health Audit Review (01_auditor)"
|
||||
Cohesion: 0.40
|
||||
Nodes (4): 🔍 Code Health Audit Review (01_auditor), Executive Summary, Key Findings, Recommendations
|
||||
|
||||
### Community 224 - "Omitted File Inspection Report"
|
||||
Cohesion: 0.40
|
||||
Nodes (4): Conclusion, Key Domain Findings from Omitted File Audit, Omitted File Inspection Report, Overview of Omitted File Inspections
|
||||
|
||||
### Community 225 - "Phase 3.2 / 3.3 — Implementation Readiness & Architectural Finalization Report"
|
||||
Cohesion: 0.40
|
||||
Nodes (4): 1. Executive Summary & Architecture Decisions, 2. Updated Task Specifications Overview, 3. Final Readiness Statement, Phase 3.2 / 3.3 — Implementation Readiness & Architectural Finalization Report
|
||||
|
||||
### Community 226 - "Phase 3 Audit Traceability Matrix"
|
||||
Cohesion: 0.40
|
||||
Nodes (4): Complete Finding-to-Task Traceability Matrix, Finding Disposition & Accounting Verification, Phase 3 Audit Traceability Matrix, Special Task Traceability (Non-Finding Tasks)
|
||||
|
||||
### Community 227 - "API Contract Specification"
|
||||
Cohesion: 0.50
|
||||
Nodes (3): 1. OpenAPI 3.0 (Swagger) Specification, 2. Endpoint Definitions & Data Types, API Contract Specification
|
||||
|
||||
### Community 228 - "⚙️ Backend Technical Review (05_dev_backend)"
|
||||
Cohesion: 0.50
|
||||
Nodes (3): Architectural Overview, ⚙️ Backend Technical Review (05_dev_backend), Critical Review Findings & Required Enhancements
|
||||
|
||||
### Community 229 - "🎨 Frontend & Admin Panel Technical Review (06_dev_frontend)"
|
||||
Cohesion: 0.50
|
||||
Nodes (3): Architectural Overview, Critical Review Findings & Required Enhancements, 🎨 Frontend & Admin Panel Technical Review (06_dev_frontend)
|
||||
|
||||
### Community 230 - "🚀 SEO & Content Strategy Review (12_seo_content)"
|
||||
Cohesion: 0.50
|
||||
Nodes (3): Overview & Content Foundation, SEO & Content Requirements, 🚀 SEO & Content Strategy Review (12_seo_content)
|
||||
|
||||
### Community 231 - "Raw Finding Verification & Disposition Report"
|
||||
Cohesion: 0.50
|
||||
Nodes (3): 1. Executive Summary & Verification Reconciliation Table, 2. Newly Discovered & Split Findings (Canonical IDs), Raw Finding Verification & Disposition Report
|
||||
|
||||
### Community 232 - "React + TypeScript + Vite"
|
||||
Cohesion: 0.50
|
||||
Nodes (3): Expanding the ESLint configuration, React Compiler, React + TypeScript + Vite
|
||||
|
||||
### Community 233 - "application/README.md"
|
||||
Cohesion: 0.50
|
||||
Nodes (3): Deploy on Vercel, Getting Started, Learn More
|
||||
|
||||
## Knowledge Gaps
|
||||
- **1179 isolated node(s):** `$schema`, `collection`, `sourceRoot`, `deleteOutDir`, `name` (+1174 more)
|
||||
These have ≤1 connection - possible missing edges or undocumented components.
|
||||
- **113 thin communities (<3 nodes) omitted from report** — run `graphify query` to explore isolated nodes.
|
||||
|
||||
## Suggested Questions
|
||||
_Questions this graph is uniquely positioned to answer:_
|
||||
|
||||
- **Why does `ApiResponse` connect `src/services/api.ts` to `pets/pets.controller.ts`, `UsersService`, `auth.controller.ts`, `BlogsController`, `WikiController`, `OrdersController`, `ProductsService`, `Home Data Module`?**
|
||||
_High betweenness centrality (0.039) - this node is a cross-community bridge._
|
||||
- **Why does `Roles()` connect `Roles` to `ZibalService`, `JwtAuthGuard`, `ContactService`, `CmsController`, `BannersService`, `WholesaleApplyDto`, `ProductsService`, `B2B Inquiry Controller`, `Ingredient Management Controller`, `Prescription Review Controller`, `Smart Advisor Controller`, `Testimonials Management Controller`, `SettingsService`?**
|
||||
_High betweenness centrality (0.037) - this node is a cross-community bridge._
|
||||
- **Why does `JwtAuthGuard` connect `JwtAuthGuard` to `AdminService`, `pets/pets.controller.ts`, `UsersService`, `CmsController`, `OrdersService`, `CreateVideoDto`, `MediaController`, `admin.module.ts`, `SettingsService`?**
|
||||
_High betweenness centrality (0.022) - this node is a cross-community bridge._
|
||||
- **What connects `$schema`, `collection`, `sourceRoot` to the rest of the system?**
|
||||
_1179 weakly-connected nodes found - possible documentation gaps or missing edges._
|
||||
- **Should `AdminService` be split into smaller, more focused modules?**
|
||||
_Cohesion score 0.06841046277665996 - nodes in this community are weakly interconnected._
|
||||
- **Should `pets/pets.controller.ts` be split into smaller, more focused modules?**
|
||||
_Cohesion score 0.053923541247484906 - nodes in this community are weakly interconnected._
|
||||
- **Should `UsersService` be split into smaller, more focused modules?**
|
||||
_Cohesion score 0.06766917293233082 - nodes in this community are weakly interconnected._
|
||||
97889
graphify-out/2026-08-16/graph.json
Normal file
97889
graphify-out/2026-08-16/graph.json
Normal file
File diff suppressed because it is too large
Load Diff
3014
graphify-out/2026-08-16/manifest.json
Normal file
3014
graphify-out/2026-08-16/manifest.json
Normal file
File diff suppressed because it is too large
Load Diff
1008
graphify-out/GRAPH_REPORT.md
Normal file
1008
graphify-out/GRAPH_REPORT.md
Normal file
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@ -0,0 +1 @@
|
||||
{"nodes": [{"id": "$graphify-root$_claude_skills_graphify_references_update_md", "label": "update.md", "file_type": "document", "source_file": ".claude/skills/graphify/references/update.md", "source_location": "L1"}, {"id": "$graphify-root$_claude_skills_graphify_references_update_graphify_reference_incremental_update_and_cluster_only", "label": "graphify reference: incremental update and cluster-only", "file_type": "document", "source_file": ".claude/skills/graphify/references/update.md", "source_location": "L1"}, {"id": "$graphify-root$_claude_skills_graphify_references_update_for_update_incremental_re_extraction", "label": "For --update (incremental re-extraction)", "file_type": "document", "source_file": ".claude/skills/graphify/references/update.md", "source_location": "L5"}, {"id": "$graphify-root$_claude_skills_graphify_references_update_for_cluster_only", "label": "For --cluster-only", "file_type": "document", "source_file": ".claude/skills/graphify/references/update.md", "source_location": "L202"}], "edges": [{"source": "$graphify-root$_claude_skills_graphify_references_update_md", "target": "$graphify-root$_claude_skills_graphify_references_update_graphify_reference_incremental_update_and_cluster_only", "relation": "contains", "confidence": "EXTRACTED", "source_file": ".claude/skills/graphify/references/update.md", "source_location": "L1", "weight": 1.0}, {"source": "$graphify-root$_claude_skills_graphify_references_update_graphify_reference_incremental_update_and_cluster_only", "target": "$graphify-root$_claude_skills_graphify_references_update_for_update_incremental_re_extraction", "relation": "contains", "confidence": "EXTRACTED", "source_file": ".claude/skills/graphify/references/update.md", "source_location": "L5", "weight": 1.0}, {"source": "$graphify-root$_claude_skills_graphify_references_update_graphify_reference_incremental_update_and_cluster_only", "target": "$graphify-root$_claude_skills_graphify_references_update_for_cluster_only", "relation": "contains", "confidence": "EXTRACTED", "source_file": ".claude/skills/graphify/references/update.md", "source_location": "L202", "weight": 1.0}], "input_tokens": 0, "output_tokens": 0}
|
||||
@ -0,0 +1 @@
|
||||
{"nodes": [{"id": "$graphify-root$_docs_audit_04_open_questions_md", "label": "04-open-questions.md", "file_type": "document", "source_file": "docs/audit/04-open-questions.md", "source_location": "L1"}, {"id": "$graphify-root$_docs_audit_04_open_questions_open_questions", "label": "Open Questions", "file_type": "document", "source_file": "docs/audit/04-open-questions.md", "source_location": "L1"}, {"id": "$graphify-root$_docs_audit_04_open_questions_1_storefront_migration_roadmap_frontend_application", "label": "1. Storefront Migration Roadmap (`frontend/application`)", "file_type": "document", "source_file": "docs/audit/04-open-questions.md", "source_location": "L5"}, {"id": "$graphify-root$_docs_audit_04_open_questions_2_payment_gateway_integration_provider", "label": "2. Payment Gateway Integration Provider", "file_type": "document", "source_file": "docs/audit/04-open-questions.md", "source_location": "L9"}, {"id": "$graphify-root$_docs_audit_04_open_questions_3_deployment_ci_cd_pipeline_specifications", "label": "3. Deployment & CI/CD Pipeline Specifications", "file_type": "document", "source_file": "docs/audit/04-open-questions.md", "source_location": "L13"}, {"id": "$graphify-root$_docs_audit_04_open_questions_4_sms_otp_service_provider", "label": "4. SMS / OTP Service Provider", "file_type": "document", "source_file": "docs/audit/04-open-questions.md", "source_location": "L17"}], "edges": [{"source": "$graphify-root$_docs_audit_04_open_questions_md", "target": "$graphify-root$_docs_audit_04_open_questions_open_questions", "relation": "contains", "confidence": "EXTRACTED", "source_file": "docs/audit/04-open-questions.md", "source_location": "L1", "weight": 1.0}, {"source": "$graphify-root$_docs_audit_04_open_questions_open_questions", "target": "$graphify-root$_docs_audit_04_open_questions_1_storefront_migration_roadmap_frontend_application", "relation": "contains", "confidence": "EXTRACTED", "source_file": "docs/audit/04-open-questions.md", "source_location": "L5", "weight": 1.0}, {"source": "$graphify-root$_docs_audit_04_open_questions_open_questions", "target": "$graphify-root$_docs_audit_04_open_questions_2_payment_gateway_integration_provider", "relation": "contains", "confidence": "EXTRACTED", "source_file": "docs/audit/04-open-questions.md", "source_location": "L9", "weight": 1.0}, {"source": "$graphify-root$_docs_audit_04_open_questions_open_questions", "target": "$graphify-root$_docs_audit_04_open_questions_3_deployment_ci_cd_pipeline_specifications", "relation": "contains", "confidence": "EXTRACTED", "source_file": "docs/audit/04-open-questions.md", "source_location": "L13", "weight": 1.0}, {"source": "$graphify-root$_docs_audit_04_open_questions_open_questions", "target": "$graphify-root$_docs_audit_04_open_questions_4_sms_otp_service_provider", "relation": "contains", "confidence": "EXTRACTED", "source_file": "docs/audit/04-open-questions.md", "source_location": "L17", "weight": 1.0}], "input_tokens": 0, "output_tokens": 0}
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@ -0,0 +1 @@
|
||||
{"nodes": [{"id": "$graphify-root$_frontend_application_claude_md", "label": "CLAUDE.md", "file_type": "document", "source_file": "frontend/application/CLAUDE.md", "source_location": "L1"}], "edges": [], "input_tokens": 0, "output_tokens": 0}
|
||||
@ -0,0 +1 @@
|
||||
{"nodes": [{"id": "$graphify-root$_docs_audit_phase3_1_change_log_md", "label": "phase3.1-change-log.md", "file_type": "document", "source_file": "docs/audit/phase3.1-change-log.md", "source_location": "L1"}, {"id": "$graphify-root$_docs_audit_phase3_1_change_log_phase_3_1_master_task_backlog_change_log", "label": "Phase 3.1 \u2014 Master Task Backlog Change Log", "file_type": "document", "source_file": "docs/audit/phase3.1-change-log.md", "source_location": "L1"}, {"id": "$graphify-root$_docs_audit_phase3_1_change_log_task_modifications_log", "label": "Task Modifications Log", "file_type": "document", "source_file": "docs/audit/phase3.1-change-log.md", "source_location": "L8"}, {"id": "$graphify-root$_docs_audit_phase3_1_change_log_1_task_auth_001", "label": "1. `TASK-AUTH-001`", "file_type": "document", "source_file": "docs/audit/phase3.1-change-log.md", "source_location": "L10"}, {"id": "$graphify-root$_docs_audit_phase3_1_change_log_2_task_fin_001", "label": "2. `TASK-FIN-001`", "file_type": "document", "source_file": "docs/audit/phase3.1-change-log.md", "source_location": "L19"}, {"id": "$graphify-root$_docs_audit_phase3_1_change_log_3_decision_002", "label": "3. `DECISION-002`", "file_type": "document", "source_file": "docs/audit/phase3.1-change-log.md", "source_location": "L28"}, {"id": "$graphify-root$_docs_audit_phase3_1_change_log_4_task_verify_001", "label": "4. `TASK-VERIFY-001`", "file_type": "document", "source_file": "docs/audit/phase3.1-change-log.md", "source_location": "L37"}, {"id": "$graphify-root$_docs_audit_phase3_1_change_log_5_task_sec_001_task_sec_002", "label": "5. `TASK-SEC-001` & `TASK-SEC-002`", "file_type": "document", "source_file": "docs/audit/phase3.1-change-log.md", "source_location": "L46"}, {"id": "$graphify-root$_docs_audit_phase3_1_change_log_6_task_build_001_execution_waves", "label": "6. `TASK-BUILD-001` & Execution Waves", "file_type": "document", "source_file": "docs/audit/phase3.1-change-log.md", "source_location": "L55"}], "edges": [{"source": "$graphify-root$_docs_audit_phase3_1_change_log_md", "target": "$graphify-root$_docs_audit_phase3_1_change_log_phase_3_1_master_task_backlog_change_log", "relation": "contains", "confidence": "EXTRACTED", "source_file": "docs/audit/phase3.1-change-log.md", "source_location": "L1", "weight": 1.0}, {"source": "$graphify-root$_docs_audit_phase3_1_change_log_phase_3_1_master_task_backlog_change_log", "target": "$graphify-root$_docs_audit_phase3_1_change_log_task_modifications_log", "relation": "contains", "confidence": "EXTRACTED", "source_file": "docs/audit/phase3.1-change-log.md", "source_location": "L8", "weight": 1.0}, {"source": "$graphify-root$_docs_audit_phase3_1_change_log_task_modifications_log", "target": "$graphify-root$_docs_audit_phase3_1_change_log_1_task_auth_001", "relation": "contains", "confidence": "EXTRACTED", "source_file": "docs/audit/phase3.1-change-log.md", "source_location": "L10", "weight": 1.0}, {"source": "$graphify-root$_docs_audit_phase3_1_change_log_task_modifications_log", "target": "$graphify-root$_docs_audit_phase3_1_change_log_2_task_fin_001", "relation": "contains", "confidence": "EXTRACTED", "source_file": "docs/audit/phase3.1-change-log.md", "source_location": "L19", "weight": 1.0}, {"source": "$graphify-root$_docs_audit_phase3_1_change_log_task_modifications_log", "target": "$graphify-root$_docs_audit_phase3_1_change_log_3_decision_002", "relation": "contains", "confidence": "EXTRACTED", "source_file": "docs/audit/phase3.1-change-log.md", "source_location": "L28", "weight": 1.0}, {"source": "$graphify-root$_docs_audit_phase3_1_change_log_task_modifications_log", "target": "$graphify-root$_docs_audit_phase3_1_change_log_4_task_verify_001", "relation": "contains", "confidence": "EXTRACTED", "source_file": "docs/audit/phase3.1-change-log.md", "source_location": "L37", "weight": 1.0}, {"source": "$graphify-root$_docs_audit_phase3_1_change_log_task_modifications_log", "target": "$graphify-root$_docs_audit_phase3_1_change_log_5_task_sec_001_task_sec_002", "relation": "contains", "confidence": "EXTRACTED", "source_file": "docs/audit/phase3.1-change-log.md", "source_location": "L46", "weight": 1.0}, {"source": "$graphify-root$_docs_audit_phase3_1_change_log_task_modifications_log", "target": "$graphify-root$_docs_audit_phase3_1_change_log_6_task_build_001_execution_waves", "relation": "contains", "confidence": "EXTRACTED", "source_file": "docs/audit/phase3.1-change-log.md", "source_location": "L55", "weight": 1.0}], "input_tokens": 0, "output_tokens": 0}
|
||||
File diff suppressed because one or more lines are too long
@ -0,0 +1 @@
|
||||
{"nodes": [{"id": "$graphify-root$_backend_prisma_tsconfig_seed_json", "label": "tsconfig.seed.json", "file_type": "code", "source_file": "backend/prisma/tsconfig.seed.json", "source_location": "L1"}, {"id": "$graphify-root$_backend_prisma_tsconfig_seed_compileroptions", "label": "compilerOptions", "file_type": "code", "source_file": "backend/prisma/tsconfig.seed.json", "source_location": "L2"}, {"id": "$graphify-root$_backend_prisma_tsconfig_seed_compileroptions_module", "label": "module", "file_type": "code", "source_file": "backend/prisma/tsconfig.seed.json", "source_location": "L3"}, {"id": "$graphify-root$_backend_prisma_tsconfig_seed_compileroptions_moduleresolution", "label": "moduleResolution", "file_type": "code", "source_file": "backend/prisma/tsconfig.seed.json", "source_location": "L4"}, {"id": "$graphify-root$_backend_prisma_tsconfig_seed_compileroptions_esmoduleinterop", "label": "esModuleInterop", "file_type": "code", "source_file": "backend/prisma/tsconfig.seed.json", "source_location": "L5"}, {"id": "$graphify-root$_backend_prisma_tsconfig_seed_compileroptions_skiplibcheck", "label": "skipLibCheck", "file_type": "code", "source_file": "backend/prisma/tsconfig.seed.json", "source_location": "L6"}], "edges": [{"source": "$graphify-root$_backend_prisma_tsconfig_seed_json", "target": "$graphify-root$_backend_prisma_tsconfig_seed_compileroptions", "relation": "contains", "confidence": "EXTRACTED", "source_file": "backend/prisma/tsconfig.seed.json", "source_location": "L2", "weight": 1.0}, {"source": "$graphify-root$_backend_prisma_tsconfig_seed_compileroptions", "target": "$graphify-root$_backend_prisma_tsconfig_seed_compileroptions_module", "relation": "contains", "confidence": "EXTRACTED", "source_file": "backend/prisma/tsconfig.seed.json", "source_location": "L3", "weight": 1.0}, {"source": "$graphify-root$_backend_prisma_tsconfig_seed_compileroptions", "target": "$graphify-root$_backend_prisma_tsconfig_seed_compileroptions_moduleresolution", "relation": "contains", "confidence": "EXTRACTED", "source_file": "backend/prisma/tsconfig.seed.json", "source_location": "L4", "weight": 1.0}, {"source": "$graphify-root$_backend_prisma_tsconfig_seed_compileroptions", "target": "$graphify-root$_backend_prisma_tsconfig_seed_compileroptions_esmoduleinterop", "relation": "contains", "confidence": "EXTRACTED", "source_file": "backend/prisma/tsconfig.seed.json", "source_location": "L5", "weight": 1.0}, {"source": "$graphify-root$_backend_prisma_tsconfig_seed_compileroptions", "target": "$graphify-root$_backend_prisma_tsconfig_seed_compileroptions_skiplibcheck", "relation": "contains", "confidence": "EXTRACTED", "source_file": "backend/prisma/tsconfig.seed.json", "source_location": "L6", "weight": 1.0}]}
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@ -0,0 +1 @@
|
||||
{"nodes": [{"id": "$graphify-root$_ai_agency_specs_prd_md", "label": "prd.md", "file_type": "document", "source_file": ".ai_agency/specs/prd.md", "source_location": "L1"}, {"id": "$graphify-root$_ai_agency_specs_prd_product_requirement_document_prd", "label": "Product Requirement Document (PRD)", "file_type": "document", "source_file": ".ai_agency/specs/prd.md", "source_location": "L1"}, {"id": "$graphify-root$_ai_agency_specs_prd_1_executive_vision", "label": "1. Executive Vision", "file_type": "document", "source_file": ".ai_agency/specs/prd.md", "source_location": "L3"}, {"id": "$graphify-root$_ai_agency_specs_prd_2_target_audience", "label": "2. Target Audience", "file_type": "document", "source_file": ".ai_agency/specs/prd.md", "source_location": "L6"}, {"id": "$graphify-root$_ai_agency_specs_prd_3_functional_requirements", "label": "3. Functional Requirements", "file_type": "document", "source_file": ".ai_agency/specs/prd.md", "source_location": "L9"}, {"id": "$graphify-root$_ai_agency_specs_prd_4_non_functional_requirements_performance_security", "label": "4. Non-Functional Requirements (Performance, Security)", "file_type": "document", "source_file": ".ai_agency/specs/prd.md", "source_location": "L12"}, {"id": "$graphify-root$_ai_agency_specs_prd_5_epic_feature_breakdown", "label": "5. Epic / Feature Breakdown", "file_type": "document", "source_file": ".ai_agency/specs/prd.md", "source_location": "L15"}], "edges": [{"source": "$graphify-root$_ai_agency_specs_prd_md", "target": "$graphify-root$_ai_agency_specs_prd_product_requirement_document_prd", "relation": "contains", "confidence": "EXTRACTED", "source_file": ".ai_agency/specs/prd.md", "source_location": "L1", "weight": 1.0}, {"source": "$graphify-root$_ai_agency_specs_prd_product_requirement_document_prd", "target": "$graphify-root$_ai_agency_specs_prd_1_executive_vision", "relation": "contains", "confidence": "EXTRACTED", "source_file": ".ai_agency/specs/prd.md", "source_location": "L3", "weight": 1.0}, {"source": "$graphify-root$_ai_agency_specs_prd_product_requirement_document_prd", "target": "$graphify-root$_ai_agency_specs_prd_2_target_audience", "relation": "contains", "confidence": "EXTRACTED", "source_file": ".ai_agency/specs/prd.md", "source_location": "L6", "weight": 1.0}, {"source": "$graphify-root$_ai_agency_specs_prd_product_requirement_document_prd", "target": "$graphify-root$_ai_agency_specs_prd_3_functional_requirements", "relation": "contains", "confidence": "EXTRACTED", "source_file": ".ai_agency/specs/prd.md", "source_location": "L9", "weight": 1.0}, {"source": "$graphify-root$_ai_agency_specs_prd_product_requirement_document_prd", "target": "$graphify-root$_ai_agency_specs_prd_4_non_functional_requirements_performance_security", "relation": "contains", "confidence": "EXTRACTED", "source_file": ".ai_agency/specs/prd.md", "source_location": "L12", "weight": 1.0}, {"source": "$graphify-root$_ai_agency_specs_prd_product_requirement_document_prd", "target": "$graphify-root$_ai_agency_specs_prd_5_epic_feature_breakdown", "relation": "contains", "confidence": "EXTRACTED", "source_file": ".ai_agency/specs/prd.md", "source_location": "L15", "weight": 1.0}], "input_tokens": 0, "output_tokens": 0}
|
||||
@ -0,0 +1 @@
|
||||
{"nodes": [{"id": "$graphify-root$_docs_audit_19_finding_verification_report_md", "label": "19-finding-verification-report.md", "file_type": "document", "source_file": "docs/audit/19-finding-verification-report.md", "source_location": "L1"}, {"id": "$graphify-root$_docs_audit_19_finding_verification_report_raw_finding_verification_disposition_report", "label": "Raw Finding Verification & Disposition Report", "file_type": "document", "source_file": "docs/audit/19-finding-verification-report.md", "source_location": "L1"}, {"id": "$graphify-root$_docs_audit_19_finding_verification_report_1_executive_summary_verification_reconciliation_table", "label": "1. Executive Summary & Verification Reconciliation Table", "file_type": "document", "source_file": "docs/audit/19-finding-verification-report.md", "source_location": "L3"}, {"id": "$graphify-root$_docs_audit_19_finding_verification_report_2_newly_discovered_split_findings_canonical_ids", "label": "2. Newly Discovered & Split Findings (Canonical IDs)", "file_type": "document", "source_file": "docs/audit/19-finding-verification-report.md", "source_location": "L22"}], "edges": [{"source": "$graphify-root$_docs_audit_19_finding_verification_report_md", "target": "$graphify-root$_docs_audit_19_finding_verification_report_raw_finding_verification_disposition_report", "relation": "contains", "confidence": "EXTRACTED", "source_file": "docs/audit/19-finding-verification-report.md", "source_location": "L1", "weight": 1.0}, {"source": "$graphify-root$_docs_audit_19_finding_verification_report_raw_finding_verification_disposition_report", "target": "$graphify-root$_docs_audit_19_finding_verification_report_1_executive_summary_verification_reconciliation_table", "relation": "contains", "confidence": "EXTRACTED", "source_file": "docs/audit/19-finding-verification-report.md", "source_location": "L3", "weight": 1.0}, {"source": "$graphify-root$_docs_audit_19_finding_verification_report_raw_finding_verification_disposition_report", "target": "$graphify-root$_docs_audit_19_finding_verification_report_2_newly_discovered_split_findings_canonical_ids", "relation": "contains", "confidence": "EXTRACTED", "source_file": "docs/audit/19-finding-verification-report.md", "source_location": "L22", "weight": 1.0}], "input_tokens": 0, "output_tokens": 0}
|
||||
@ -0,0 +1 @@
|
||||
{"nodes": [{"id": "$graphify-root$_claude_skills_graphify_references_transcribe_md", "label": "transcribe.md", "file_type": "document", "source_file": ".claude/skills/graphify/references/transcribe.md", "source_location": "L1"}, {"id": "$graphify-root$_claude_skills_graphify_references_transcribe_graphify_reference_transcribe_video_and_audio", "label": "graphify reference: transcribe video and audio", "file_type": "document", "source_file": ".claude/skills/graphify/references/transcribe.md", "source_location": "L1"}, {"id": "$graphify-root$_claude_skills_graphify_references_transcribe_step_2_5_transcribe_video_audio_files_only_if_video_files_detected", "label": "Step 2.5 - Transcribe video / audio files (only if video files detected)", "file_type": "document", "source_file": ".claude/skills/graphify/references/transcribe.md", "source_location": "L5"}], "edges": [{"source": "$graphify-root$_claude_skills_graphify_references_transcribe_md", "target": "$graphify-root$_claude_skills_graphify_references_transcribe_graphify_reference_transcribe_video_and_audio", "relation": "contains", "confidence": "EXTRACTED", "source_file": ".claude/skills/graphify/references/transcribe.md", "source_location": "L1", "weight": 1.0}, {"source": "$graphify-root$_claude_skills_graphify_references_transcribe_graphify_reference_transcribe_video_and_audio", "target": "$graphify-root$_claude_skills_graphify_references_transcribe_step_2_5_transcribe_video_audio_files_only_if_video_files_detected", "relation": "contains", "confidence": "EXTRACTED", "source_file": ".claude/skills/graphify/references/transcribe.md", "source_location": "L5", "weight": 1.0}], "input_tokens": 0, "output_tokens": 0}
|
||||
File diff suppressed because one or more lines are too long
@ -0,0 +1 @@
|
||||
{"nodes": [{"id": "$graphify-root$_backend_tsconfig_build_json", "label": "tsconfig.build.json", "file_type": "code", "source_file": "backend/tsconfig.build.json", "source_location": "L1"}, {"id": "$graphify-root$_backend_tsconfig_build_extends", "label": "extends", "file_type": "code", "source_file": "backend/tsconfig.build.json", "source_location": "L2"}, {"id": "ref_tsconfig_json", "label": "./tsconfig.json", "file_type": "concept", "source_file": "backend/tsconfig.build.json", "source_location": "L2"}, {"id": "$graphify-root$_backend_tsconfig_build_exclude", "label": "exclude", "file_type": "code", "source_file": "backend/tsconfig.build.json", "source_location": "L3"}, {"id": "ref_node_modules", "label": "node_modules", "file_type": "concept", "source_file": "backend/tsconfig.build.json", "source_location": "L3"}, {"id": "ref_test", "label": "test", "file_type": "concept", "source_file": "backend/tsconfig.build.json", "source_location": "L3"}, {"id": "ref_dist", "label": "dist", "file_type": "concept", "source_file": "backend/tsconfig.build.json", "source_location": "L3"}, {"id": "ref_spec_ts", "label": "**/*spec.ts", "file_type": "concept", "source_file": "backend/tsconfig.build.json", "source_location": "L3"}, {"id": "ref_prisma", "label": "prisma", "file_type": "concept", "source_file": "backend/tsconfig.build.json", "source_location": "L3"}], "edges": [{"source": "$graphify-root$_backend_tsconfig_build_json", "target": "$graphify-root$_backend_tsconfig_build_extends", "relation": "contains", "confidence": "EXTRACTED", "source_file": "backend/tsconfig.build.json", "source_location": "L2", "weight": 1.0}, {"source": "$graphify-root$_backend_tsconfig_build_json", "target": "ref_tsconfig_json", "relation": "extends", "confidence": "EXTRACTED", "source_file": "backend/tsconfig.build.json", "source_location": "L2", "weight": 1.0, "context": "import"}, {"source": "$graphify-root$_backend_tsconfig_build_json", "target": "$graphify-root$_backend_tsconfig_build_exclude", "relation": "contains", "confidence": "EXTRACTED", "source_file": "backend/tsconfig.build.json", "source_location": "L3", "weight": 1.0}, {"source": "$graphify-root$_backend_tsconfig_build_exclude", "target": "ref_node_modules", "relation": "extends", "confidence": "EXTRACTED", "source_file": "backend/tsconfig.build.json", "source_location": "L3", "weight": 1.0, "context": "import"}, {"source": "$graphify-root$_backend_tsconfig_build_exclude", "target": "ref_test", "relation": "extends", "confidence": "EXTRACTED", "source_file": "backend/tsconfig.build.json", "source_location": "L3", "weight": 1.0, "context": "import"}, {"source": "$graphify-root$_backend_tsconfig_build_exclude", "target": "ref_dist", "relation": "extends", "confidence": "EXTRACTED", "source_file": "backend/tsconfig.build.json", "source_location": "L3", "weight": 1.0, "context": "import"}, {"source": "$graphify-root$_backend_tsconfig_build_exclude", "target": "ref_spec_ts", "relation": "extends", "confidence": "EXTRACTED", "source_file": "backend/tsconfig.build.json", "source_location": "L3", "weight": 1.0, "context": "import"}, {"source": "$graphify-root$_backend_tsconfig_build_exclude", "target": "ref_prisma", "relation": "extends", "confidence": "EXTRACTED", "source_file": "backend/tsconfig.build.json", "source_location": "L3", "weight": 1.0, "context": "import"}]}
|
||||
@ -0,0 +1 @@
|
||||
{"nodes": [{"id": "$graphify-root$_docs_audit_33_final_phase2_audit_closure_md", "label": "33-final-phase2-audit-closure.md", "file_type": "document", "source_file": "docs/audit/33-final-phase2-audit-closure.md", "source_location": "L1"}, {"id": "$graphify-root$_docs_audit_33_final_phase2_audit_closure_final_phase_2_audit_closure_report", "label": "Final Phase 2 Audit Closure Report", "file_type": "document", "source_file": "docs/audit/33-final-phase2-audit-closure.md", "source_location": "L1"}, {"id": "$graphify-root$_docs_audit_33_final_phase2_audit_closure_1_executive_summary_honest_review_tier_metrics", "label": "1. Executive Summary & Honest Review-Tier Metrics", "file_type": "document", "source_file": "docs/audit/33-final-phase2-audit-closure.md", "source_location": "L9"}, {"id": "$graphify-root$_docs_audit_33_final_phase2_audit_closure_2_reconciled_findings_canonical_identifier_normalization", "label": "2. Reconciled Findings & Canonical Identifier Normalization", "file_type": "document", "source_file": "docs/audit/33-final-phase2-audit-closure.md", "source_location": "L22"}, {"id": "$graphify-root$_docs_audit_33_final_phase2_audit_closure_3_validation_integrity_verification", "label": "3. Validation & Integrity Verification", "file_type": "document", "source_file": "docs/audit/33-final-phase2-audit-closure.md", "source_location": "L34"}, {"id": "$graphify-root$_docs_audit_33_final_phase2_audit_closure_4_final_quality_gate_conclusion", "label": "4. Final Quality Gate Conclusion", "file_type": "document", "source_file": "docs/audit/33-final-phase2-audit-closure.md", "source_location": "L42"}], "edges": [{"source": "$graphify-root$_docs_audit_33_final_phase2_audit_closure_md", "target": "$graphify-root$_docs_audit_33_final_phase2_audit_closure_final_phase_2_audit_closure_report", "relation": "contains", "confidence": "EXTRACTED", "source_file": "docs/audit/33-final-phase2-audit-closure.md", "source_location": "L1", "weight": 1.0}, {"source": "$graphify-root$_docs_audit_33_final_phase2_audit_closure_final_phase_2_audit_closure_report", "target": "$graphify-root$_docs_audit_33_final_phase2_audit_closure_1_executive_summary_honest_review_tier_metrics", "relation": "contains", "confidence": "EXTRACTED", "source_file": "docs/audit/33-final-phase2-audit-closure.md", "source_location": "L9", "weight": 1.0}, {"source": "$graphify-root$_docs_audit_33_final_phase2_audit_closure_final_phase_2_audit_closure_report", "target": "$graphify-root$_docs_audit_33_final_phase2_audit_closure_2_reconciled_findings_canonical_identifier_normalization", "relation": "contains", "confidence": "EXTRACTED", "source_file": "docs/audit/33-final-phase2-audit-closure.md", "source_location": "L22", "weight": 1.0}, {"source": "$graphify-root$_docs_audit_33_final_phase2_audit_closure_final_phase_2_audit_closure_report", "target": "$graphify-root$_docs_audit_33_final_phase2_audit_closure_3_validation_integrity_verification", "relation": "contains", "confidence": "EXTRACTED", "source_file": "docs/audit/33-final-phase2-audit-closure.md", "source_location": "L34", "weight": 1.0}, {"source": "$graphify-root$_docs_audit_33_final_phase2_audit_closure_final_phase_2_audit_closure_report", "target": "$graphify-root$_docs_audit_33_final_phase2_audit_closure_4_final_quality_gate_conclusion", "relation": "contains", "confidence": "EXTRACTED", "source_file": "docs/audit/33-final-phase2-audit-closure.md", "source_location": "L42", "weight": 1.0}], "input_tokens": 0, "output_tokens": 0}
|
||||
File diff suppressed because one or more lines are too long
@ -0,0 +1 @@
|
||||
{"nodes": [{"id": "$graphify-root$_docs_readme_md", "label": "README.md", "file_type": "document", "source_file": "docs/README.md", "source_location": "L1"}, {"id": "$graphify-root$_docs_readme_\u0641\u0647\u0631\u0633\u062a_\u0645\u0637\u0627\u0644\u0628_table_of_contents", "label": "\u0641\u0647\u0631\u0633\u062a \u0645\u0637\u0627\u0644\u0628 (Table of Contents)", "file_type": "document", "source_file": "docs/README.md", "source_location": "L7"}], "edges": [{"source": "$graphify-root$_docs_readme_md", "target": "$graphify-root$_docs_readme_\u0641\u0647\u0631\u0633\u062a_\u0645\u0637\u0627\u0644\u0628_table_of_contents", "relation": "contains", "confidence": "EXTRACTED", "source_file": "docs/README.md", "source_location": "L7", "weight": 1.0}, {"source": "$graphify-root$_docs_readme_md", "target": "$graphify-root$_docs_01_introduction_md", "relation": "references", "confidence": "EXTRACTED", "source_file": "docs/README.md", "source_location": "L11", "weight": 1.0, "target_file": "$graphify-root$/docs/01-introduction.md"}, {"source": "$graphify-root$_docs_readme_md", "target": "$graphify-root$_docs_02_user_guide_md", "relation": "references", "confidence": "EXTRACTED", "source_file": "docs/README.md", "source_location": "L14", "weight": 1.0, "target_file": "$graphify-root$/docs/02-user-guide.md"}, {"source": "$graphify-root$_docs_readme_md", "target": "$graphify-root$_docs_03_developer_guide_md", "relation": "references", "confidence": "EXTRACTED", "source_file": "docs/README.md", "source_location": "L17", "weight": 1.0, "target_file": "$graphify-root$/docs/03-developer-guide.md"}, {"source": "$graphify-root$_docs_readme_md", "target": "$graphify-root$_docs_04_setup_and_deployment_md", "relation": "references", "confidence": "EXTRACTED", "source_file": "docs/README.md", "source_location": "L20", "weight": 1.0, "target_file": "$graphify-root$/docs/04-setup-and-deployment.md"}, {"source": "$graphify-root$_docs_readme_md", "target": "$graphify-root$_docs_05_devops_and_monitoring_md", "relation": "references", "confidence": "EXTRACTED", "source_file": "docs/README.md", "source_location": "L23", "weight": 1.0, "target_file": "$graphify-root$/docs/05-devops-and-monitoring.md"}, {"source": "$graphify-root$_docs_readme_md", "target": "$graphify-root$_docs_06_testing_md", "relation": "references", "confidence": "EXTRACTED", "source_file": "docs/README.md", "source_location": "L26", "weight": 1.0, "target_file": "$graphify-root$/docs/06-testing.md"}], "input_tokens": 0, "output_tokens": 0}
|
||||
@ -0,0 +1 @@
|
||||
{"nodes": [{"id": "$graphify-root$_docs_audit_18_compiler_diagnostic_dispositions_md", "label": "18-compiler-diagnostic-dispositions.md", "file_type": "document", "source_file": "docs/audit/18-compiler-diagnostic-dispositions.md", "source_location": "L1"}, {"id": "$graphify-root$_docs_audit_18_compiler_diagnostic_dispositions_compiler_diagnostic_dispositions", "label": "Compiler Diagnostic Dispositions", "file_type": "document", "source_file": "docs/audit/18-compiler-diagnostic-dispositions.md", "source_location": "L1"}, {"id": "$graphify-root$_docs_audit_18_compiler_diagnostic_dispositions_reconciled_compiler_diagnostic_table", "label": "Reconciled Compiler Diagnostic Table", "file_type": "document", "source_file": "docs/audit/18-compiler-diagnostic-dispositions.md", "source_location": "L11"}], "edges": [{"source": "$graphify-root$_docs_audit_18_compiler_diagnostic_dispositions_md", "target": "$graphify-root$_docs_audit_18_compiler_diagnostic_dispositions_compiler_diagnostic_dispositions", "relation": "contains", "confidence": "EXTRACTED", "source_file": "docs/audit/18-compiler-diagnostic-dispositions.md", "source_location": "L1", "weight": 1.0}, {"source": "$graphify-root$_docs_audit_18_compiler_diagnostic_dispositions_compiler_diagnostic_dispositions", "target": "$graphify-root$_docs_audit_18_compiler_diagnostic_dispositions_reconciled_compiler_diagnostic_table", "relation": "contains", "confidence": "EXTRACTED", "source_file": "docs/audit/18-compiler-diagnostic-dispositions.md", "source_location": "L11", "weight": 1.0}], "input_tokens": 0, "output_tokens": 0}
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@ -0,0 +1 @@
|
||||
{"nodes": [{"id": "$graphify-root$_frontend_admin_panel_readme_md", "label": "README.md", "file_type": "document", "source_file": "frontend/admin-panel/README.md", "source_location": "L1"}, {"id": "$graphify-root$_frontend_admin_panel_readme_react_typescript_vite", "label": "React + TypeScript + Vite", "file_type": "document", "source_file": "frontend/admin-panel/README.md", "source_location": "L1"}, {"id": "$graphify-root$_frontend_admin_panel_readme_react_compiler", "label": "React Compiler", "file_type": "document", "source_file": "frontend/admin-panel/README.md", "source_location": "L10"}, {"id": "$graphify-root$_frontend_admin_panel_readme_expanding_the_eslint_configuration", "label": "Expanding the ESLint configuration", "file_type": "document", "source_file": "frontend/admin-panel/README.md", "source_location": "L14"}], "edges": [{"source": "$graphify-root$_frontend_admin_panel_readme_md", "target": "$graphify-root$_frontend_admin_panel_readme_react_typescript_vite", "relation": "contains", "confidence": "EXTRACTED", "source_file": "frontend/admin-panel/README.md", "source_location": "L1", "weight": 1.0}, {"source": "$graphify-root$_frontend_admin_panel_readme_react_typescript_vite", "target": "$graphify-root$_frontend_admin_panel_readme_react_compiler", "relation": "contains", "confidence": "EXTRACTED", "source_file": "frontend/admin-panel/README.md", "source_location": "L10", "weight": 1.0}, {"source": "$graphify-root$_frontend_admin_panel_readme_react_typescript_vite", "target": "$graphify-root$_frontend_admin_panel_readme_expanding_the_eslint_configuration", "relation": "contains", "confidence": "EXTRACTED", "source_file": "frontend/admin-panel/README.md", "source_location": "L14", "weight": 1.0}], "input_tokens": 0, "output_tokens": 0}
|
||||
File diff suppressed because one or more lines are too long
@ -0,0 +1 @@
|
||||
{"nodes": [{"id": "$graphify-root$_antigravity_instructions_md", "label": "instructions.md", "file_type": "document", "source_file": ".antigravity/instructions.md", "source_location": "L1"}, {"id": "$graphify-root$_antigravity_instructions_graphify", "label": "graphify", "file_type": "document", "source_file": ".antigravity/instructions.md", "source_location": "L1"}], "edges": [{"source": "$graphify-root$_antigravity_instructions_md", "target": "$graphify-root$_antigravity_instructions_graphify", "relation": "contains", "confidence": "EXTRACTED", "source_file": ".antigravity/instructions.md", "source_location": "L1", "weight": 1.0}], "input_tokens": 0, "output_tokens": 0}
|
||||
File diff suppressed because one or more lines are too long
@ -0,0 +1 @@
|
||||
{"nodes": [{"id": "$graphify-root$_frontend_admin_panel_public_fonts_sahel_font_v3_4_0_changelog_md", "label": "CHANGELOG.md", "file_type": "document", "source_file": "frontend/admin-panel/public/fonts/sahel-font-v3.4.0/CHANGELOG.md", "source_location": "L1"}], "edges": [], "input_tokens": 0, "output_tokens": 0}
|
||||
@ -0,0 +1 @@
|
||||
{"nodes": [{"id": "$graphify-root$_ai_agency_specs_reviews_security_review_md", "label": "security_review.md", "file_type": "document", "source_file": ".ai_agency/specs/reviews/security_review.md", "source_location": "L1"}, {"id": "$graphify-root$_ai_agency_specs_reviews_security_review_security_performance_review_09_devops_security", "label": "\ud83d\udd12 Security & Performance Review (09_devops_security)", "file_type": "document", "source_file": ".ai_agency/specs/reviews/security_review.md", "source_location": "L1"}, {"id": "$graphify-root$_ai_agency_specs_reviews_security_review_security_architecture_best_practices", "label": "Security Architecture & Best Practices", "file_type": "document", "source_file": ".ai_agency/specs/reviews/security_review.md", "source_location": "L3"}], "edges": [{"source": "$graphify-root$_ai_agency_specs_reviews_security_review_md", "target": "$graphify-root$_ai_agency_specs_reviews_security_review_security_performance_review_09_devops_security", "relation": "contains", "confidence": "EXTRACTED", "source_file": ".ai_agency/specs/reviews/security_review.md", "source_location": "L1", "weight": 1.0}, {"source": "$graphify-root$_ai_agency_specs_reviews_security_review_security_performance_review_09_devops_security", "target": "$graphify-root$_ai_agency_specs_reviews_security_review_security_architecture_best_practices", "relation": "contains", "confidence": "EXTRACTED", "source_file": ".ai_agency/specs/reviews/security_review.md", "source_location": "L3", "weight": 1.0}], "input_tokens": 0, "output_tokens": 0}
|
||||
File diff suppressed because one or more lines are too long
@ -0,0 +1 @@
|
||||
{"nodes": [{"id": "$graphify-root$_ai_agency_specs_reviews_code_health_review_md", "label": "code_health_review.md", "file_type": "document", "source_file": ".ai_agency/specs/reviews/code_health_review.md", "source_location": "L1"}, {"id": "$graphify-root$_ai_agency_specs_reviews_code_health_review_code_health_audit_review_01_auditor", "label": "\ud83d\udd0d Code Health Audit Review (01_auditor)", "file_type": "document", "source_file": ".ai_agency/specs/reviews/code_health_review.md", "source_location": "L1"}, {"id": "$graphify-root$_ai_agency_specs_reviews_code_health_review_executive_summary", "label": "Executive Summary", "file_type": "document", "source_file": ".ai_agency/specs/reviews/code_health_review.md", "source_location": "L3"}, {"id": "$graphify-root$_ai_agency_specs_reviews_code_health_review_key_findings", "label": "Key Findings", "file_type": "document", "source_file": ".ai_agency/specs/reviews/code_health_review.md", "source_location": "L8"}, {"id": "$graphify-root$_ai_agency_specs_reviews_code_health_review_recommendations", "label": "Recommendations", "file_type": "document", "source_file": ".ai_agency/specs/reviews/code_health_review.md", "source_location": "L19"}], "edges": [{"source": "$graphify-root$_ai_agency_specs_reviews_code_health_review_md", "target": "$graphify-root$_ai_agency_specs_reviews_code_health_review_code_health_audit_review_01_auditor", "relation": "contains", "confidence": "EXTRACTED", "source_file": ".ai_agency/specs/reviews/code_health_review.md", "source_location": "L1", "weight": 1.0}, {"source": "$graphify-root$_ai_agency_specs_reviews_code_health_review_code_health_audit_review_01_auditor", "target": "$graphify-root$_ai_agency_specs_reviews_code_health_review_executive_summary", "relation": "contains", "confidence": "EXTRACTED", "source_file": ".ai_agency/specs/reviews/code_health_review.md", "source_location": "L3", "weight": 1.0}, {"source": "$graphify-root$_ai_agency_specs_reviews_code_health_review_code_health_audit_review_01_auditor", "target": "$graphify-root$_ai_agency_specs_reviews_code_health_review_key_findings", "relation": "contains", "confidence": "EXTRACTED", "source_file": ".ai_agency/specs/reviews/code_health_review.md", "source_location": "L8", "weight": 1.0}, {"source": "$graphify-root$_ai_agency_specs_reviews_code_health_review_code_health_audit_review_01_auditor", "target": "$graphify-root$_ai_agency_specs_reviews_code_health_review_recommendations", "relation": "contains", "confidence": "EXTRACTED", "source_file": ".ai_agency/specs/reviews/code_health_review.md", "source_location": "L19", "weight": 1.0}], "input_tokens": 0, "output_tokens": 0}
|
||||
@ -0,0 +1 @@
|
||||
{"nodes": [{"id": "$graphify-root$_docs_05_devops_and_monitoring_md", "label": "05-devops-and-monitoring.md", "file_type": "document", "source_file": "docs/05-devops-and-monitoring.md", "source_location": "L1"}, {"id": "$graphify-root$_docs_05_devops_and_monitoring_\u062f\u0648\u0627\u067e\u0633_\u0648_\u0645\u0627\u0646\u06cc\u062a\u0648\u0631\u06cc\u0646\u06af_\u0633\u06cc\u0633\u062a\u0645_devops_monitoring", "label": "\u062f\u0648\u0627\u067e\u0633 \u0648 \u0645\u0627\u0646\u06cc\u062a\u0648\u0631\u06cc\u0646\u06af \u0633\u06cc\u0633\u062a\u0645 (DevOps & Monitoring)", "file_type": "document", "source_file": "docs/05-devops-and-monitoring.md", "source_location": "L1"}, {"id": "$graphify-root$_docs_05_devops_and_monitoring_\u06f1_\u0641\u0631\u0622\u06cc\u0646\u062f_\u0627\u0633\u062a\u0642\u0631\u0627\u0631_\u062e\u0648\u062f\u06a9\u0627\u0631_ci_cd", "label": "\u06f1. \u0641\u0631\u0622\u06cc\u0646\u062f \u0627\u0633\u062a\u0642\u0631\u0627\u0631 \u062e\u0648\u062f\u06a9\u0627\u0631 (CI/CD)", "file_type": "document", "source_file": "docs/05-devops-and-monitoring.md", "source_location": "L5"}, {"id": "$graphify-root$_docs_05_devops_and_monitoring_\u06f2_\u0645\u0627\u0646\u06cc\u062a\u0648\u0631\u06cc\u0646\u06af_\u0639\u0645\u0644\u06a9\u0631\u062f_pm2_dashboard", "label": "\u06f2. \u0645\u0627\u0646\u06cc\u062a\u0648\u0631\u06cc\u0646\u06af \u0639\u0645\u0644\u06a9\u0631\u062f (PM2 Dashboard)", "file_type": "document", "source_file": "docs/05-devops-and-monitoring.md", "source_location": "L12"}, {"id": "$graphify-root$_docs_05_devops_and_monitoring_\u06f3_\u0628\u0631\u0631\u0633\u06cc_\u0644\u0627\u06af_\u0647\u0627\u06cc_\u0633\u06cc\u0633\u062a\u0645_logs_management", "label": "\u06f3. \u0628\u0631\u0631\u0633\u06cc \u0644\u0627\u06af\u200c\u0647\u0627\u06cc \u0633\u06cc\u0633\u062a\u0645 (Logs Management)", "file_type": "document", "source_file": "docs/05-devops-and-monitoring.md", "source_location": "L27"}, {"id": "$graphify-root$_docs_05_devops_and_monitoring_\u06f4_\u0645\u0627\u0646\u06cc\u062a\u0648\u0631\u06cc\u0646\u06af_\u062f\u06cc\u062a\u0627\u0628\u06cc\u0633_postgresql", "label": "\u06f4. \u0645\u0627\u0646\u06cc\u062a\u0648\u0631\u06cc\u0646\u06af \u062f\u06cc\u062a\u0627\u0628\u06cc\u0633 (PostgreSQL)", "file_type": "document", "source_file": "docs/05-devops-and-monitoring.md", "source_location": "L39"}], "edges": [{"source": "$graphify-root$_docs_05_devops_and_monitoring_md", "target": "$graphify-root$_docs_05_devops_and_monitoring_\u062f\u0648\u0627\u067e\u0633_\u0648_\u0645\u0627\u0646\u06cc\u062a\u0648\u0631\u06cc\u0646\u06af_\u0633\u06cc\u0633\u062a\u0645_devops_monitoring", "relation": "contains", "confidence": "EXTRACTED", "source_file": "docs/05-devops-and-monitoring.md", "source_location": "L1", "weight": 1.0}, {"source": "$graphify-root$_docs_05_devops_and_monitoring_\u062f\u0648\u0627\u067e\u0633_\u0648_\u0645\u0627\u0646\u06cc\u062a\u0648\u0631\u06cc\u0646\u06af_\u0633\u06cc\u0633\u062a\u0645_devops_monitoring", "target": "$graphify-root$_docs_05_devops_and_monitoring_\u06f1_\u0641\u0631\u0622\u06cc\u0646\u062f_\u0627\u0633\u062a\u0642\u0631\u0627\u0631_\u062e\u0648\u062f\u06a9\u0627\u0631_ci_cd", "relation": "contains", "confidence": "EXTRACTED", "source_file": "docs/05-devops-and-monitoring.md", "source_location": "L5", "weight": 1.0}, {"source": "$graphify-root$_docs_05_devops_and_monitoring_\u062f\u0648\u0627\u067e\u0633_\u0648_\u0645\u0627\u0646\u06cc\u062a\u0648\u0631\u06cc\u0646\u06af_\u0633\u06cc\u0633\u062a\u0645_devops_monitoring", "target": "$graphify-root$_docs_05_devops_and_monitoring_\u06f2_\u0645\u0627\u0646\u06cc\u062a\u0648\u0631\u06cc\u0646\u06af_\u0639\u0645\u0644\u06a9\u0631\u062f_pm2_dashboard", "relation": "contains", "confidence": "EXTRACTED", "source_file": "docs/05-devops-and-monitoring.md", "source_location": "L12", "weight": 1.0}, {"source": "$graphify-root$_docs_05_devops_and_monitoring_\u062f\u0648\u0627\u067e\u0633_\u0648_\u0645\u0627\u0646\u06cc\u062a\u0648\u0631\u06cc\u0646\u06af_\u0633\u06cc\u0633\u062a\u0645_devops_monitoring", "target": "$graphify-root$_docs_05_devops_and_monitoring_\u06f3_\u0628\u0631\u0631\u0633\u06cc_\u0644\u0627\u06af_\u0647\u0627\u06cc_\u0633\u06cc\u0633\u062a\u0645_logs_management", "relation": "contains", "confidence": "EXTRACTED", "source_file": "docs/05-devops-and-monitoring.md", "source_location": "L27", "weight": 1.0}, {"source": "$graphify-root$_docs_05_devops_and_monitoring_\u062f\u0648\u0627\u067e\u0633_\u0648_\u0645\u0627\u0646\u06cc\u062a\u0648\u0631\u06cc\u0646\u06af_\u0633\u06cc\u0633\u062a\u0645_devops_monitoring", "target": "$graphify-root$_docs_05_devops_and_monitoring_\u06f4_\u0645\u0627\u0646\u06cc\u062a\u0648\u0631\u06cc\u0646\u06af_\u062f\u06cc\u062a\u0627\u0628\u06cc\u0633_postgresql", "relation": "contains", "confidence": "EXTRACTED", "source_file": "docs/05-devops-and-monitoring.md", "source_location": "L39", "weight": 1.0}], "input_tokens": 0, "output_tokens": 0}
|
||||
@ -0,0 +1 @@
|
||||
{"nodes": [{"id": "$graphify-root$_claude_skills_graphify_references_query_md", "label": "query.md", "file_type": "document", "source_file": ".claude/skills/graphify/references/query.md", "source_location": "L1"}, {"id": "$graphify-root$_claude_skills_graphify_references_query_graphify_reference_query_path_explain", "label": "graphify reference: query, path, explain", "file_type": "document", "source_file": ".claude/skills/graphify/references/query.md", "source_location": "L1"}, {"id": "$graphify-root$_claude_skills_graphify_references_query_step_0_constrained_query_expansion_required_before_traversal", "label": "Step 0 \u2014 Constrained query expansion (REQUIRED before traversal)", "file_type": "document", "source_file": ".claude/skills/graphify/references/query.md", "source_location": "L23"}, {"id": "$graphify-root$_claude_skills_graphify_references_query_step_1_traversal", "label": "Step 1 \u2014 Traversal", "file_type": "document", "source_file": ".claude/skills/graphify/references/query.md", "source_location": "L61"}, {"id": "$graphify-root$_claude_skills_graphify_references_query_for_graphify_path", "label": "For /graphify path", "file_type": "document", "source_file": ".claude/skills/graphify/references/query.md", "source_location": "L186"}, {"id": "$graphify-root$_claude_skills_graphify_references_query_for_graphify_explain", "label": "For /graphify explain", "file_type": "document", "source_file": ".claude/skills/graphify/references/query.md", "source_location": "L254"}], "edges": [{"source": "$graphify-root$_claude_skills_graphify_references_query_md", "target": "$graphify-root$_claude_skills_graphify_references_query_graphify_reference_query_path_explain", "relation": "contains", "confidence": "EXTRACTED", "source_file": ".claude/skills/graphify/references/query.md", "source_location": "L1", "weight": 1.0}, {"source": "$graphify-root$_claude_skills_graphify_references_query_graphify_reference_query_path_explain", "target": "$graphify-root$_claude_skills_graphify_references_query_step_0_constrained_query_expansion_required_before_traversal", "relation": "contains", "confidence": "EXTRACTED", "source_file": ".claude/skills/graphify/references/query.md", "source_location": "L23", "weight": 1.0}, {"source": "$graphify-root$_claude_skills_graphify_references_query_graphify_reference_query_path_explain", "target": "$graphify-root$_claude_skills_graphify_references_query_step_1_traversal", "relation": "contains", "confidence": "EXTRACTED", "source_file": ".claude/skills/graphify/references/query.md", "source_location": "L61", "weight": 1.0}, {"source": "$graphify-root$_claude_skills_graphify_references_query_graphify_reference_query_path_explain", "target": "$graphify-root$_claude_skills_graphify_references_query_for_graphify_path", "relation": "contains", "confidence": "EXTRACTED", "source_file": ".claude/skills/graphify/references/query.md", "source_location": "L186", "weight": 1.0}, {"source": "$graphify-root$_claude_skills_graphify_references_query_graphify_reference_query_path_explain", "target": "$graphify-root$_claude_skills_graphify_references_query_for_graphify_explain", "relation": "contains", "confidence": "EXTRACTED", "source_file": ".claude/skills/graphify/references/query.md", "source_location": "L254", "weight": 1.0}], "input_tokens": 0, "output_tokens": 0}
|
||||
File diff suppressed because one or more lines are too long
@ -0,0 +1 @@
|
||||
{"nodes": [{"id": "$graphify-root$_claude_skills_graphify_references_github_and_merge_md", "label": "github-and-merge.md", "file_type": "document", "source_file": ".claude/skills/graphify/references/github-and-merge.md", "source_location": "L1"}, {"id": "$graphify-root$_claude_skills_graphify_references_github_and_merge_graphify_reference_github_clone_and_cross_repo_merge", "label": "graphify reference: GitHub clone and cross-repo merge", "file_type": "document", "source_file": ".claude/skills/graphify/references/github-and-merge.md", "source_location": "L1"}, {"id": "$graphify-root$_claude_skills_graphify_references_github_and_merge_step_0_clone_github_repo_s_only_if_a_github_url_was_given", "label": "Step 0 - Clone GitHub repo(s) (only if a GitHub URL was given)", "file_type": "document", "source_file": ".claude/skills/graphify/references/github-and-merge.md", "source_location": "L5"}], "edges": [{"source": "$graphify-root$_claude_skills_graphify_references_github_and_merge_md", "target": "$graphify-root$_claude_skills_graphify_references_github_and_merge_graphify_reference_github_clone_and_cross_repo_merge", "relation": "contains", "confidence": "EXTRACTED", "source_file": ".claude/skills/graphify/references/github-and-merge.md", "source_location": "L1", "weight": 1.0}, {"source": "$graphify-root$_claude_skills_graphify_references_github_and_merge_graphify_reference_github_clone_and_cross_repo_merge", "target": "$graphify-root$_claude_skills_graphify_references_github_and_merge_step_0_clone_github_repo_s_only_if_a_github_url_was_given", "relation": "contains", "confidence": "EXTRACTED", "source_file": ".claude/skills/graphify/references/github-and-merge.md", "source_location": "L5", "weight": 1.0}], "input_tokens": 0, "output_tokens": 0}
|
||||
@ -0,0 +1 @@
|
||||
{"nodes": [{"id": "$graphify-root$_ai_agency_specs_architecture_spec_md", "label": "architecture_spec.md", "file_type": "document", "source_file": ".ai_agency/specs/architecture_spec.md", "source_location": "L1"}, {"id": "$graphify-root$_ai_agency_specs_architecture_spec_architecture_specification", "label": "Architecture Specification", "file_type": "document", "source_file": ".ai_agency/specs/architecture_spec.md", "source_location": "L1"}, {"id": "$graphify-root$_ai_agency_specs_architecture_spec_1_single_non_negotiable_tech_stack", "label": "1. Single Non-Negotiable Tech Stack", "file_type": "document", "source_file": ".ai_agency/specs/architecture_spec.md", "source_location": "L3"}, {"id": "$graphify-root$_ai_agency_specs_architecture_spec_2_directory_structure_tree", "label": "2. Directory Structure Tree", "file_type": "document", "source_file": ".ai_agency/specs/architecture_spec.md", "source_location": "L10"}, {"id": "$graphify-root$_ai_agency_specs_architecture_spec_3_state_management_strategy", "label": "3. State Management Strategy", "file_type": "document", "source_file": ".ai_agency/specs/architecture_spec.md", "source_location": "L25"}, {"id": "$graphify-root$_ai_agency_specs_architecture_spec_4_deployment_docker_architecture", "label": "4. Deployment / Docker Architecture", "file_type": "document", "source_file": ".ai_agency/specs/architecture_spec.md", "source_location": "L28"}], "edges": [{"source": "$graphify-root$_ai_agency_specs_architecture_spec_md", "target": "$graphify-root$_ai_agency_specs_architecture_spec_architecture_specification", "relation": "contains", "confidence": "EXTRACTED", "source_file": ".ai_agency/specs/architecture_spec.md", "source_location": "L1", "weight": 1.0}, {"source": "$graphify-root$_ai_agency_specs_architecture_spec_architecture_specification", "target": "$graphify-root$_ai_agency_specs_architecture_spec_1_single_non_negotiable_tech_stack", "relation": "contains", "confidence": "EXTRACTED", "source_file": ".ai_agency/specs/architecture_spec.md", "source_location": "L3", "weight": 1.0}, {"source": "$graphify-root$_ai_agency_specs_architecture_spec_architecture_specification", "target": "$graphify-root$_ai_agency_specs_architecture_spec_2_directory_structure_tree", "relation": "contains", "confidence": "EXTRACTED", "source_file": ".ai_agency/specs/architecture_spec.md", "source_location": "L10", "weight": 1.0}, {"source": "$graphify-root$_ai_agency_specs_architecture_spec_architecture_specification", "target": "$graphify-root$_ai_agency_specs_architecture_spec_3_state_management_strategy", "relation": "contains", "confidence": "EXTRACTED", "source_file": ".ai_agency/specs/architecture_spec.md", "source_location": "L25", "weight": 1.0}, {"source": "$graphify-root$_ai_agency_specs_architecture_spec_architecture_specification", "target": "$graphify-root$_ai_agency_specs_architecture_spec_4_deployment_docker_architecture", "relation": "contains", "confidence": "EXTRACTED", "source_file": ".ai_agency/specs/architecture_spec.md", "source_location": "L28", "weight": 1.0}], "input_tokens": 0, "output_tokens": 0}
|
||||
@ -0,0 +1 @@
|
||||
{"nodes": [{"id": "$graphify-root$_ai_agency_specs_project_health_md", "label": "project_health.md", "file_type": "document", "source_file": ".ai_agency/specs/project_health.md", "source_location": "L1"}, {"id": "$graphify-root$_ai_agency_specs_project_health_project_health_audit_report", "label": "Project Health Audit Report", "file_type": "document", "source_file": ".ai_agency/specs/project_health.md", "source_location": "L1"}, {"id": "$graphify-root$_ai_agency_specs_project_health_1_audit_score_summary", "label": "1. Audit Score Summary", "file_type": "document", "source_file": ".ai_agency/specs/project_health.md", "source_location": "L3"}, {"id": "$graphify-root$_ai_agency_specs_project_health_2_technical_debt_inventory", "label": "2. Technical Debt Inventory", "file_type": "document", "source_file": ".ai_agency/specs/project_health.md", "source_location": "L7"}, {"id": "$graphify-root$_ai_agency_specs_project_health_3_outdated_dependencies_list", "label": "3. Outdated Dependencies List", "file_type": "document", "source_file": ".ai_agency/specs/project_health.md", "source_location": "L10"}, {"id": "$graphify-root$_ai_agency_specs_project_health_4_security_risks_env_leaks_unprotected_ports", "label": "4. Security Risks (.env leaks, unprotected ports)", "file_type": "document", "source_file": ".ai_agency/specs/project_health.md", "source_location": "L13"}], "edges": [{"source": "$graphify-root$_ai_agency_specs_project_health_md", "target": "$graphify-root$_ai_agency_specs_project_health_project_health_audit_report", "relation": "contains", "confidence": "EXTRACTED", "source_file": ".ai_agency/specs/project_health.md", "source_location": "L1", "weight": 1.0}, {"source": "$graphify-root$_ai_agency_specs_project_health_project_health_audit_report", "target": "$graphify-root$_ai_agency_specs_project_health_1_audit_score_summary", "relation": "contains", "confidence": "EXTRACTED", "source_file": ".ai_agency/specs/project_health.md", "source_location": "L3", "weight": 1.0}, {"source": "$graphify-root$_ai_agency_specs_project_health_project_health_audit_report", "target": "$graphify-root$_ai_agency_specs_project_health_2_technical_debt_inventory", "relation": "contains", "confidence": "EXTRACTED", "source_file": ".ai_agency/specs/project_health.md", "source_location": "L7", "weight": 1.0}, {"source": "$graphify-root$_ai_agency_specs_project_health_project_health_audit_report", "target": "$graphify-root$_ai_agency_specs_project_health_3_outdated_dependencies_list", "relation": "contains", "confidence": "EXTRACTED", "source_file": ".ai_agency/specs/project_health.md", "source_location": "L10", "weight": 1.0}, {"source": "$graphify-root$_ai_agency_specs_project_health_project_health_audit_report", "target": "$graphify-root$_ai_agency_specs_project_health_4_security_risks_env_leaks_unprotected_ports", "relation": "contains", "confidence": "EXTRACTED", "source_file": ".ai_agency/specs/project_health.md", "source_location": "L13", "weight": 1.0}], "input_tokens": 0, "output_tokens": 0}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user