codex-compare: nestng-crm task (NestJS + Angular), frozen manifest, shared node_modules installer with Codex sandbox proof, optional-task guard
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
9e9895fc9e
commit
ba26e685bf
@@ -0,0 +1,71 @@
|
||||
# nestng-crm: notes for the orchestrator (never sent to Codex)
|
||||
|
||||
Written 2026-11-05 on the laptop (Windows 11, Node 22.16.0, npm 10.9.2, Python 3.9.13). Nothing here was run on the server.
|
||||
|
||||
## Pinned versions (exact, `package.json` and `package-lock.json` are in `seed/`)
|
||||
|
||||
backend (`seed/backend/package.json`): @nestjs/common, core, platform-express, testing 11.2.8; @nestjs/cli 11.0.24; @nestjs/schematics 11.1.0; class-validator 0.15.1;
|
||||
class-transformer 0.5.1; reflect-metadata 0.2.2; rxjs 7.8.2; jest 29.7.0; ts-jest 29.4.15; supertest 7.3.1; typescript 5.9.3; @types/express 5.0.6, jest 29.5.14,
|
||||
node 22.20.5, supertest 6.0.3. 579 packages after `npm ci`, node_modules about 214 MB, about 28,000 files.
|
||||
Scaffold is hand-made (no `nest new`, so no git init and no eslint/prettier): classic CommonJS tsconfig (no `module: nodenext`/`isolatedModules`, which make decorator
|
||||
metadata imports awkward), `nest build` to `dist/main.js`, no `incremental`. The seed has an EMPTY `AppModule`, a `main.ts` that listens on 3000 (the agent must add PORT and
|
||||
127.0.0.1), the jest config for unit tests (in package.json, `src/**/*.spec.ts`) and `test/jest-e2e.json` (`*.e2e-spec.ts`), and no tests.
|
||||
|
||||
frontend (`seed/frontend/package.json`): @angular/common, compiler, core, forms, platform-browser, router 20.3.35; @angular/build, cli 20.3.42; @angular/compiler-cli 20.3.35;
|
||||
rxjs 7.8.2; tslib 2.8.1; zone.js 0.15.1; typescript 5.9.3. 410 packages, node_modules about 218 MB, about 19,000 files.
|
||||
Angular 20, not the 22.x that is current on the registry (22.x needs Node >= 22.22.3; the laptop has 22.16 and Angular 20 accepts ^22.12). Standalone components, esbuild
|
||||
`@angular/build:application`, strict TS and strict templates, the dev server target exists, no `test` target (Karma/Jasmine removed), `cli.analytics=false`.
|
||||
|
||||
Lockfile digests (sha256): `seed/backend/package-lock.json` 23a3084dc848bf127f97696563cab0ec113358585df6245d270b1f123c7fd533,
|
||||
`seed/frontend/package-lock.json` 87f8dc2edd3bb892330bb23ea3675dc2e173cbafbd35865fccc9168a58bca72c (the manifest records them with the other seed files).
|
||||
`npm ci` on both from a clean directory works and the reference then passes 56/56 (checked 2026-11-05).
|
||||
|
||||
## Installing node_modules on the server (once, by the main session, network is available there)
|
||||
|
||||
One shared tree per project outside any workspace, for example `/data/leleka-e2e/codex-compare/node_modules-nestng/{backend,frontend}/node_modules`. Install from the
|
||||
frozen seed lockfiles, low priority, because the root NVMe stalls under sustained writes (about 430 MB, 47,000 small files, about 45 s on the laptop):
|
||||
|
||||
```sh
|
||||
for d in backend frontend; do
|
||||
mkdir -p $NM/$d && cp $TASKS/nestng-crm/seed/$d/package.json $TASKS/nestng-crm/seed/$d/package-lock.json $NM/$d/
|
||||
( cd $NM/$d && nice -n 19 ionice -c3 npm ci --ignore-scripts=false --no-audit --no-fund )
|
||||
done
|
||||
```
|
||||
|
||||
then `chmod -R a-w $NM` and record `find $NM -type f | sort | sha256sum`-style digest in the run metadata (it is not part of the task manifest). Node 22 itself: a pinned
|
||||
tarball (the version and its sha256 recorded) in the same directory, put on PATH for Codex's shell and for `accept.py` (`NESTNG_NODE_BIN=<dir with node and npm>`).
|
||||
Angular 20 needs Node >= 20.19 or >= 22.12; any 22.x LTS from this year is fine.
|
||||
|
||||
## What accept.py needs
|
||||
|
||||
* `python3 accept.py WORKSPACE`, stdlib only, 56 checks, prints `PASS`/`FAIL name :: detail` and `SUMMARY n/m`. Nothing in WORKSPACE is modified (the self-test confirms it).
|
||||
* node_modules: `WORKSPACE/<dir>/node_modules` if present, else `$NESTNG_NM_ROOT/<dir>/node_modules` (a directory holding `backend/node_modules` and `frontend/node_modules`).
|
||||
It symlinks them (junction on Windows) into a temp copy that excludes node_modules, dist, .angular, coverage, out-tsc, *.tsbuildinfo and .git. The runner's workspace copy of
|
||||
node_modules is therefore never copied or written.
|
||||
* Node and npm from PATH, or `$NESTNG_NODE_BIN`. It sets CI=1, NG_CLI_ANALYTICS=false, NG_DISABLE_VERSION_CHECK=1 for its own children.
|
||||
* The backend is started with `node dist/main.js` on a free port in `PORT`; a server that ignores PORT fails the whole REST group (35 checks).
|
||||
* Time on the laptop: reference 22-24 s; bare seed 79 s (30 s of waiting for a server that never listens on `PORT`). Worst case with a slow agent solution well below 300 s.
|
||||
On the server expect 2-3x the CPU-bound parts (ng build, tsc, jest).
|
||||
* Groups: 7 structure, 2 backend build/listen, 35 REST, 3 own tests (npm test, npm run test:e2e, >= 15 cases in total), 1 frontend build, 9 static frontend checks.
|
||||
* Does NOT check the UI in a browser (none on the server). A later laptop check with Playwright over the stored workspaces is possible (serve `frontend/dist/frontend/browser`
|
||||
with the backend on 3000 and a proxy), not written.
|
||||
|
||||
## Laptop timings (reference solution)
|
||||
|
||||
`npm run build` backend 3.7 s; `npm test` 5.9 s (15 tests); `npm run test:e2e` 5.4 s (15 tests); `ng build` production 5.4 s; whole accept.py 22 s (seed + overlay self-test: seed
|
||||
rc=1 79 s, overlay rc=0 22 s).
|
||||
|
||||
## Gotchas for the server and the Codex sandbox
|
||||
|
||||
* The runner must copy the seed FIRST, check SEEDTREE (`taskfile.workspace_lines`) and only then add the hard-linked node_modules; `workspace_lines` would otherwise hash 47,000
|
||||
files of node_modules (`cell.py` does it again after the run for `workspace.sha256`: exclude `node_modules`, `dist`, `.angular` there, or it reads 430 MB per cell).
|
||||
* Hard-linked files are shared: make the shared tree read-only (`chmod -R a-w`) so an agent cannot edit a package of every later cell. `cp -al` (hard links) writes no data.
|
||||
A symlinked node_modules also works with `accept.py`, but Angular/Jest under a symlink inside a Codex sandbox was not tried; hard links are what the prompt promises.
|
||||
* esbuild and the Angular CLI fetch platform-specific optional dependencies (`@esbuild/linux-x64`, `@parcel/watcher-linux-x64-glibc`, `lmdb` prebuilds for the Angular cache) at
|
||||
`npm ci` time from the registry. Install on the server (linux-x64), never copy the laptop's tree. Check `npm ls @esbuild/linux-x64` after the install.
|
||||
* The agent's `ng build` writes `frontend/.angular/cache` into its workspace (fine); jest/ts-jest write a cache under the OS temp dir: the Codex workspace-write sandbox allows
|
||||
the temp dir, but confirm once with a smoke cell. If `HOME` is not writable, `ng` may try to write `~/.angular-config.json` (analytics is disabled in the seed `angular.json`).
|
||||
* `ng serve` and `nest start --watch` need a listening port and file watching; Codex may start them. `cell.py` kills the process group at the end, accept.py uses a random port,
|
||||
so a leftover server on 3000 does not disturb the acceptance, but check that 3000 is free before the first cell (the agent's own tests use supertest, no port).
|
||||
* Round estimate 30-70 is the author's guess; the prompt is a single phase and the seed has no tests, so the agent must create about 15+ test cases.
|
||||
* After the main session freezes `MANIFEST.sha256` do not edit any file in this directory (including this one): `TASK`/`SEEDTREE` digests cover it.
|
||||
@@ -5,7 +5,7 @@
|
||||
# CMP_ARM=ours HOLDER JOB (inherits the sealed KAR memfd): the release package, `leleka up --foreground --kar-fd`, shipped configuration (KAR PLE, prefix cache auto / tail reply).
|
||||
# CMP_ARM=vanilla holder-free window payload (started by cmp_window.sh): vanilla Strata 0.2.6 launcher, shipped defaults (route tail skip and CPU prefill share ON).
|
||||
# CMP_VANILLA_LOSSY=0 turns both lossy defaults off (variant VANL instead of VAN).
|
||||
# CMP_TASKS ("ttt nestng-crm") CMP_REPS ("1") CMP_WALL (cell wall limit s, default 3000) CMP_ROUNDS (round cap, default 150) CMP_RUN (default $CMP/runs/main)
|
||||
# CMP_TASKS ("ttt nestng-crm") CMP_OPTIONAL (tasks dropped, with a note, when not ready) CMP_REPS ("1") CMP_WALL (cell wall limit s, default 3000) CMP_ROUNDS (round cap, default 150) CMP_RUN (default $CMP/runs/main)
|
||||
# CMP_TARBALL (ours; default the final release package)
|
||||
# Cells: cell.py of the codex-lossy-delta study (logging proxy, temperature 0 injected for BOTH arms, real Codex CLI, task acceptance); no AGENTS.md pad: the sessions are what a
|
||||
# user gets. Output: $RUN/<VARIANT>/<task>-r<rep>/ (cell.json, proxy/, acceptance.log ...), $RUN/<VARIANT>/stack-r<rep>/. Variants: LEL = Leleka, VAN = vanilla shipped, VANL = vanilla lossless.
|
||||
@@ -35,10 +35,21 @@ note() { echo "[$(date -u +%FT%TZ)] [DEV codex-compare] $*" >>/data/leleka-e2e/d
|
||||
# ---- guards ---------------------------------------------------------------------------------------------------------------------------------
|
||||
( cd "$CMP" && sha256sum --quiet -c INSTALL.sha256 ) || { echo "installed tools differ from INSTALL.sha256"; exit 3; }
|
||||
python3 -I "$CMP/delta/taskfile.py" check "$TASKS_ROOT" >"$RUN/tasks-check-$VAR-r$BLK.txt" 2>&1 || { echo "task files differ from their manifest"; cat "$RUN/tasks-check-$VAR-r$BLK.txt"; exit 3; }
|
||||
for t in $TASKS smoke-mini; do [ -f "$TASKS_ROOT/$t/task.md" ] || { echo "task $t is not installed in $TASKS_ROOT"; exit 3; }; done
|
||||
# a task listed in CMP_OPTIONAL that is not ready (not installed, or the Node toolchain not proven in the Codex sandbox) is DROPPED with a loud note instead of refusing the block
|
||||
nestng_ready() { [ -f "$TASKS_ROOT/nestng-crm/task.md" ] && [ -f "$CMP/toolchain/NESTNG_OK" ] && [ -d "$NM/backend/node_modules" ] && [ -d "$NM/frontend/node_modules" ]; }
|
||||
KEEP=""
|
||||
for t in $TASKS; do
|
||||
if [ "$t" = nestng-crm ] && ! nestng_ready; then
|
||||
case " ${CMP_OPTIONAL:-} " in *" $t "*) log "TASK DROPPED: $t is not ready (toolchain/NESTNG_OK missing)"; note "codex-compare block $VAR reps [$REPS]: task $t DROPPED (not ready); queue it again later"; continue;; esac
|
||||
echo "task $t is not ready (toolchain/NESTNG_OK, shared node_modules)"; exit 3
|
||||
fi
|
||||
[ -f "$TASKS_ROOT/$t/task.md" ] || { echo "task $t is not installed in $TASKS_ROOT"; exit 3; }
|
||||
KEEP="$KEEP $t"
|
||||
done
|
||||
TASKS=${KEEP# }
|
||||
[ -f "$TASKS_ROOT/smoke-mini/task.md" ] || { echo "task smoke-mini is not installed"; exit 3; }
|
||||
[ -x "$CODEX" ] || { echo "no codex binary"; exit 3; }
|
||||
[ -n "$NODE_BIN" ] && [ -x "$NODE_BIN/node" ] || { echo "no node toolchain under $CMP/toolchain"; exit 3; }
|
||||
case " $TASKS " in *" nestng-crm "*) for d in backend frontend; do [ -d "$NM/$d" ] || { echo "no shared node_modules $NM/$d"; exit 3; }; done;; esac
|
||||
STANDALONE=0; FD=${LELEKA_STRA169_KAR_FD:-}
|
||||
if [ "$ARM" = ours ]; then
|
||||
readlink "/proc/self/fd/$FD" 2>/dev/null | grep -q '^/memfd:' || { echo "ours needs the holder's sealed memfd"; exit 3; }
|
||||
@@ -87,7 +98,7 @@ run_cells() { # $1 upstream url, $2 upstream model, $3 engine log, $4 api key (
|
||||
for task in $list; do
|
||||
CELL=$RUN/$VAR/$task-r$rep; [ "$task" = smoke-mini ] && CELL=$RUN/$VAR/smoke-mini-r$((100 + rep))
|
||||
[ -f "$CELL/cell.json" ] && { log "cell $CELL already done: skipped"; continue; }
|
||||
link=""; [ "$task" = nestng-crm ] && link="--link-tree backend/node_modules=$NM/backend --link-tree frontend/node_modules=$NM/frontend"
|
||||
link=""; [ "$task" = nestng-crm ] && link="--link-tree backend/node_modules=$NM/backend/node_modules --link-tree frontend/node_modules=$NM/frontend/node_modules"
|
||||
t1=$(date +%s)
|
||||
E2E_API_KEY=${key:-none} CLD_CODEX=$CODEX timeout $((WALL + 900)) python3 -I "$CELLPY" --cell-dir "$CELL" --variant "$VAR" --task "$task" --rep "$([ "$task" = smoke-mini ] && echo $((100 + rep)) || echo $rep)" \
|
||||
--tasks-root "$TASKS_ROOT" --upstream "$url" --upstream-model "$model" --codex-bin "$CODEX" --wall-limit "$WALL" --max-rounds "$ROUNDS" \
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
#!/usr/bin/env bash
|
||||
# Install the shared node_modules of the nestng-crm task on rnr5090 (runs ON the server as a CPU-only queue job, after install-node.sh), then prove the toolchain in the
|
||||
# Codex sandbox (workspace-write, no network) on the bare seed. Writes codex-compare/toolchain/NESTNG_OK only when every step passed; cmp_codex_job.sh refuses nestng-crm without it.
|
||||
set -euo pipefail
|
||||
CMP=/data/leleka-e2e/codex-compare; NM=$CMP/nm; SEED=$CMP/tasks/nestng-crm/seed
|
||||
CODEX=/home/para/work/codex-e2e/bin/codex
|
||||
NOTES=/data/leleka-e2e/decode/notes.md
|
||||
note() { echo "[$(date -u +%FT%TZ)] [DEV codex-compare] $*" >>"$NOTES"; }
|
||||
NODE_BIN=$(ls -d "$CMP"/toolchain/node-v*-linux-x64/bin | tail -1)
|
||||
export PATH=$NODE_BIN:$PATH NG_CLI_ANALYTICS=false npm_config_cache=/tmp/cmp-npm-cache npm_config_update_notifier=false npm_config_fund=false npm_config_audit=false CI=1
|
||||
rm -f "$CMP/toolchain/NESTNG_OK"
|
||||
python3 -I "$CMP/delta/taskfile.py" check "$CMP/tasks"
|
||||
for d in backend frontend; do
|
||||
if [ ! -d "$NM/$d/node_modules" ]; then
|
||||
chmod -R u+w "$NM/$d" 2>/dev/null || true
|
||||
mkdir -p "$NM/$d"; cp "$SEED/$d/package.json" "$SEED/$d/package-lock.json" "$NM/$d/"
|
||||
( cd "$NM/$d" && nice -n 19 ionice -c3 npm ci --no-audit --no-fund ) > "$NM/install-$d.log" 2>&1 || { tail -20 "$NM/install-$d.log"; exit 4; }
|
||||
fi
|
||||
done
|
||||
( cd "$NM/frontend" && npm ls @esbuild/linux-x64 2>&1 | tail -3 )
|
||||
for d in backend frontend; do ( cd "$NM/$d" && find node_modules -type f -printf '%P %s\n' | sort | sha256sum | cut -c1-64 | sed "s|\$| $d file-list+sizes|" ); done | tee "$NM/DIGEST.txt"
|
||||
chmod -R a-w "$NM/backend" "$NM/frontend"
|
||||
# ---- the Codex sandbox on the bare seed: the same policy as the cells (workspace-write, no network), the same environment
|
||||
S=$CMP/_active/sbx-$(date -u +%Y%m%dT%H%M%S); mkdir -p "$S/ws" "$S/home"
|
||||
cp -r "$SEED/backend" "$SEED/frontend" "$S/ws/"
|
||||
cp -al "$NM/backend/node_modules" "$S/ws/backend/node_modules"; cp -al "$NM/frontend/node_modules" "$S/ws/frontend/node_modules"
|
||||
sed 's|@MODEL@|qwen-local|;s|@BASE_URL@|http://127.0.0.1:1|;s|@EFFORT@|medium|' "$CMP/config.toml.tmpl" > "$S/home/config.toml"
|
||||
cd "$S/ws"
|
||||
rc=0
|
||||
CODEX_HOME=$S/home "$CODEX" sandbox -c 'sandbox_mode="workspace-write"' -c 'sandbox_workspace_write.network_access=false' -- bash -c '
|
||||
set -e; node --version
|
||||
cd backend; npm run build; test -f dist/main.js; npx jest --passWithNoTests; echo BACKEND-OK
|
||||
cd ../frontend; npm run build; ls dist/*/browser | head -3; echo FRONTEND-OK' > "$S/sandbox.log" 2>&1 || rc=$?
|
||||
tail -12 "$S/sandbox.log"
|
||||
if [ $rc = 0 ] && grep -q BACKEND-OK "$S/sandbox.log" && grep -q FRONTEND-OK "$S/sandbox.log"; then
|
||||
{ node --version; cat "$NM/DIGEST.txt"; } > "$CMP/toolchain/NESTNG_OK"
|
||||
note "codex-compare: nestng-crm toolchain proven in the Codex sandbox (npm ci of both lockfiles, seed builds, rc=0); evidence $S/sandbox.log"
|
||||
else
|
||||
note "codex-compare: nestng-crm sandbox check FAILED rc=$rc; see $S/sandbox.log"; exit 5
|
||||
fi
|
||||
@@ -25,9 +25,9 @@ if [ -e _stage ]; then G=$HOME/work/leleka/garbage/codex-compare-stage-$(date -u
|
||||
mkdir -p _stage/delta _stage/tasks _stage/tools
|
||||
REMOTE
|
||||
STAGE=$R/_stage
|
||||
tar -C "$CODEX_DIR" --exclude=__pycache__ --exclude='reference' --exclude='selftest.py' --exclude='NOTES.md' -cf - tasks | ssh rnr5090 "tar -xf - -C $STAGE/tasks --strip-components=1"
|
||||
tar -C "$CODEX_DIR" --exclude=__pycache__ --exclude='reference' --exclude='selftest.py' -cf - tasks | ssh rnr5090 "tar -xf - -C $STAGE/tasks --strip-components=1"
|
||||
tar -C "$CODEX_DIR" --exclude=__pycache__ -cf - delta | ssh rnr5090 "tar -xf - -C $STAGE/delta --strip-components=1"
|
||||
tar -C "$HERE" --exclude=__pycache__ -cf - cmp_codex_job.sh cmp_window.sh cmp_report.py install-node.sh | ssh rnr5090 "tar -xf - -C $STAGE/tools"
|
||||
tar -C "$HERE" --exclude=__pycache__ -cf - cmp_codex_job.sh cmp_window.sh cmp_report.py install-node.sh install-nestng-deps.sh | ssh rnr5090 "tar -xf - -C $STAGE/tools"
|
||||
scp -q "$CODEX_DIR/config.toml.tmpl" "rnr5090:$STAGE/config.toml.tmpl"
|
||||
ssh rnr5090 bash -s "$R" <<'REMOTE'
|
||||
set -euo pipefail
|
||||
|
||||
@@ -15,7 +15,7 @@ import sys
|
||||
|
||||
BEGIN = "<!-- PROMPT BEGIN -->"
|
||||
END = "<!-- PROMPT END -->"
|
||||
SKIP_DIRS = {"__pycache__", "node_modules", ".angular"} # node_modules: hard-linked in by the runner (--link-tree), never part of a seed or a workspace digest
|
||||
SKIP_DIRS = {"__pycache__", "node_modules", ".angular", "dist"} # node_modules: hard-linked in by the runner (--link-tree), never part of a seed or a workspace digest
|
||||
|
||||
|
||||
def sha256_file(path):
|
||||
|
||||
@@ -126,6 +126,33 @@ PROMPT fixbug-ledger 08f5c2fd63c199fa24274a7d36099354b27b7e2bde1e126a833a3a97307
|
||||
SEEDTREE fixbug-ledger 41ba1db9dedeae30d1c189d70e45660639cb8e798bdf94dfb9a27e54bdb18c56
|
||||
TASK fixbug-ledger c6e7743467badd427a94bad605e972b9f19c78b3cd54b141501c1dee59417302
|
||||
REFERENCE fixbug-ledger 08eb07de9e7f22a9266478af9ed3643cf7bc956e32a867e903d69f2e7777f68c
|
||||
db1b70954e1a63c536507387e03bd4770621498344ea0a93bb7146c05afc16b9 nestng-crm/accept.py
|
||||
7594fbe27ca0a1a318f7146b741ffc6d49a1f356bca849cb1e6cd5324d88440a nestng-crm/seed/README.md
|
||||
bcb15e3049ff5d131762d2bfe3a6f917c3c64c83ac772467a4073975cd423b5b nestng-crm/seed/backend/nest-cli.json
|
||||
23a3084dc848bf127f97696563cab0ec113358585df6245d270b1f123c7fd533 nestng-crm/seed/backend/package-lock.json
|
||||
61084aa1cffbeaa5c511a592ee61f048a1cf26f44b00299b27e5174cb5aa9291 nestng-crm/seed/backend/package.json
|
||||
0472c27a52a21ebecbf6b339b052adcd4bc5e8ef02ffe8860f8782687d0ebe32 nestng-crm/seed/backend/src/app.module.ts
|
||||
e25d9bd8f80b6ffbcc8826ed1b407e747e4fbe346c5bab62cbe5837da4eeb189 nestng-crm/seed/backend/src/main.ts
|
||||
81e47b6032f112b49cc054a823dc9fadfbd88c56a02e7e2369722363433adbca nestng-crm/seed/backend/test/jest-e2e.json
|
||||
3a016b4ee9713cd16295128bad42e6077e5ecd8c2ed225caa7d1e0e3f1c7f03f nestng-crm/seed/backend/tsconfig.build.json
|
||||
00a3a37d6dad7a7b758564bd8d55e37de4b9c263a9d1072b8c7dfb4cdf053603 nestng-crm/seed/backend/tsconfig.json
|
||||
e8716af95fea94712bc6a2054125164fc808dce2f5658af653562188288adb46 nestng-crm/seed/frontend/angular.json
|
||||
87f8dc2edd3bb892330bb23ea3675dc2e173cbafbd35865fccc9168a58bca72c nestng-crm/seed/frontend/package-lock.json
|
||||
e2ecb11d8c51cbcf24f01744d3023b96a92251eebc54dac85336b756ba97f63a nestng-crm/seed/frontend/package.json
|
||||
08400dbcd6dd62da4bcd1daae84bfc4a6c2f995882cc033af8267e9af75b7347 nestng-crm/seed/frontend/src/app/app.config.ts
|
||||
1dfd8848c3f15bd203df7fba51f1b94f0765e5972baca0a9f99b391b64ffb6cf nestng-crm/seed/frontend/src/app/app.html
|
||||
e2ef74b4c1f7f52a30a417c6808f01b2a29e69bb0d20302527ae5001607f7180 nestng-crm/seed/frontend/src/app/app.routes.ts
|
||||
e511bd4ee0785273b2d2b252382922e189fec69dfbc660dac5581fd284262d7e nestng-crm/seed/frontend/src/app/app.ts
|
||||
d699b21284e03cf25dbd4022a9eca45f9fbcd460027e83f1de998c3aa98b860b nestng-crm/seed/frontend/src/index.html
|
||||
ecc610fb7d56c95a01a8aa6c274a63210d45b2944dd6b9a88b2c8f70b6351037 nestng-crm/seed/frontend/src/main.ts
|
||||
8996c8346765ab6f23928d29788bb2b6dd7d7baf0df0f8ed3ff584635f57afd6 nestng-crm/seed/frontend/src/styles.css
|
||||
fc4898318bf701861de6a406ede37e7e848aad322c022daa4cd9e93ecbcc9ea4 nestng-crm/seed/frontend/tsconfig.app.json
|
||||
fe90e111c2d5ecf01e050aac28a18db100967b1407c2d3c47149efb89466e47b nestng-crm/seed/frontend/tsconfig.json
|
||||
07926c531fbc3456b19e33157e4174e74550e8cc7858b41a95358618722d71b7 nestng-crm/task.md
|
||||
PROMPT nestng-crm 240f3cc6b5f179501efeb94589a7dc711983538db551a603a1820893112d4e62
|
||||
SEEDTREE nestng-crm 55378d7bb67c1f5f53d9977aaa7ec50a3aed37c4125ea21735bfce00966817e8
|
||||
TASK nestng-crm e63ee664874d74eb6c06c387118a4ddcf238528de3544178248d51975659cb9c
|
||||
REFERENCE nestng-crm f79ad58aaede28a21e6d413f8604287c01251e9682727b629a268ecc2d509dee
|
||||
2c01fffcdf4a1e959d9d3adbbd5965cf8d59e69dd330a3568966812b2f672432 refactor-shop/accept.py
|
||||
f4bf75da964c784234c685b44b41c98846c6c03d46f8277115cb756d224d5f4c refactor-shop/hidden/behaviour.py
|
||||
99546b78de332fc57d310eb3d0699b9d8110f662032e216c4ab886377e5588e2 refactor-shop/hidden/helpers_h.py
|
||||
|
||||
@@ -0,0 +1,527 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Acceptance for the NestJS + Angular CRM task (no network, no browser; Node.js on PATH).
|
||||
|
||||
accept.py WORKSPACE exit 0 = every check passed
|
||||
|
||||
Everything runs on a COPY of the workspace in a temp directory (the workspace itself is only read). node_modules are not copied: they are linked
|
||||
(symlink, on Windows a junction) from WORKSPACE/<dir>/node_modules, or, when the workspace has none (the self-test builds it from the seed alone), from
|
||||
$NESTNG_NM_ROOT/<dir>/node_modules. Node and npm come from PATH; $NESTNG_NODE_BIN (a directory) is put in front of it. Expected run time 30-120 s.
|
||||
|
||||
Groups: structure (read only) / backend build + black-box REST checks over HTTP / the agent's own tests / frontend build / static checks of the frontend.
|
||||
"""
|
||||
import glob
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
WS = os.path.abspath(sys.argv[1])
|
||||
NM_ROOT = os.environ.get("NESTNG_NM_ROOT", "")
|
||||
STAGES = ["lead", "qualified", "proposal", "won", "lost"]
|
||||
MIN_TESTS = 15
|
||||
results = []
|
||||
|
||||
|
||||
def check(name, ok, detail=""):
|
||||
results.append(bool(ok))
|
||||
print(("PASS " if ok else "FAIL ") + name + ("" if ok else " :: " + str(detail).replace("\n", " | ")[:300]), flush=True)
|
||||
|
||||
|
||||
def guarded(name, fn):
|
||||
"""Run fn() -> (ok, detail); an exception is a failed check, not a crash."""
|
||||
try:
|
||||
ok, detail = fn()
|
||||
except Exception as e: # noqa: BLE001
|
||||
ok, detail = False, "%s: %s" % (type(e).__name__, e)
|
||||
check(name, ok, detail)
|
||||
|
||||
|
||||
def read(path):
|
||||
try:
|
||||
with open(path, encoding="utf-8", errors="replace") as f:
|
||||
return f.read()
|
||||
except OSError:
|
||||
return ""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- environment
|
||||
ENV = dict(os.environ)
|
||||
if os.environ.get("NESTNG_NODE_BIN"):
|
||||
ENV["PATH"] = os.environ["NESTNG_NODE_BIN"] + os.pathsep + ENV.get("PATH", "")
|
||||
ENV.update({"CI": "1", "NG_CLI_ANALYTICS": "false", "NG_DISABLE_VERSION_CHECK": "1", "NO_COLOR": "1", "FORCE_COLOR": "0",
|
||||
"npm_config_update_notifier": "false", "npm_config_fund": "false", "npm_config_audit": "false"})
|
||||
NPM = shutil.which("npm", path=ENV["PATH"])
|
||||
NODE = shutil.which("node", path=ENV["PATH"])
|
||||
|
||||
|
||||
def run(cmd, cwd, timeout, env=None):
|
||||
p = subprocess.run(cmd, cwd=cwd, env=env or ENV, capture_output=True, text=True, timeout=timeout, errors="replace")
|
||||
return p.returncode, (p.stdout or "") + (p.stderr or "")
|
||||
|
||||
|
||||
def link_dir(target, link):
|
||||
try:
|
||||
os.symlink(target, link, target_is_directory=True)
|
||||
except (OSError, NotImplementedError):
|
||||
if os.name != "nt":
|
||||
raise
|
||||
subprocess.run(["cmd", "/c", "mklink", "/J", link, target], check=True, capture_output=True)
|
||||
|
||||
|
||||
def unlink_dir(link):
|
||||
"""Remove a link made by link_dir without touching what it points at."""
|
||||
try:
|
||||
os.unlink(link)
|
||||
except OSError:
|
||||
try:
|
||||
os.rmdir(link)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def free_port():
|
||||
with socket.socket() as s:
|
||||
s.bind(("127.0.0.1", 0))
|
||||
return s.getsockname()[1]
|
||||
|
||||
|
||||
def is_int(v):
|
||||
return isinstance(v, int) and not isinstance(v, bool)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 1. structure
|
||||
guarded("structure: backend/package.json with build, test and test:e2e scripts", lambda: (
|
||||
all(k in json.loads(read(os.path.join(WS, "backend", "package.json")) or "{}").get("scripts", {}) for k in ("build", "test", "test:e2e")), "scripts missing"))
|
||||
guarded("structure: frontend/package.json with a build script", lambda: (
|
||||
"build" in json.loads(read(os.path.join(WS, "frontend", "package.json")) or "{}").get("scripts", {}), "build script missing"))
|
||||
guarded("structure: backend/src/main.ts exists", lambda: (os.path.isfile(os.path.join(WS, "backend", "src", "main.ts")), "missing"))
|
||||
guarded("structure: backend has at least one test file", lambda: (
|
||||
len(glob.glob(os.path.join(WS, "backend", "src", "**", "*.spec.ts"), recursive=True) + glob.glob(os.path.join(WS, "backend", "test", "**", "*.ts"), recursive=True)) > 0, "no *.spec.ts / test/*.ts"))
|
||||
guarded("structure: frontend/proxy.conf.json maps /api to port 3000 on the loopback", lambda: (
|
||||
re.search(r"(127\.0\.0\.1|localhost):3000", json.dumps(json.loads(read(os.path.join(WS, "frontend", "proxy.conf.json")) or "{}").get("/api", {}))) is not None, "no /api proxy target"))
|
||||
guarded("structure: README.md exists and is not empty", lambda: (len(read(os.path.join(WS, "README.md")).strip()) > 20, "missing or empty"))
|
||||
guarded("structure: node and npm are available", lambda: (NPM is not None and NODE is not None, "node=%s npm=%s" % (NODE, NPM)))
|
||||
|
||||
# ---------------------------------------------------------------- temp copy of the workspace
|
||||
tmp = tempfile.mkdtemp(prefix="nestng-ws-")
|
||||
copy = os.path.join(tmp, "ws")
|
||||
links = []
|
||||
nm_ok = {}
|
||||
try:
|
||||
shutil.copytree(WS, copy, ignore=shutil.ignore_patterns("node_modules", "dist", ".angular", "coverage", "out-tsc", "*.tsbuildinfo", ".git"))
|
||||
for d in ("backend", "frontend"):
|
||||
src = os.path.join(WS, d, "node_modules")
|
||||
if not os.path.isdir(src) and NM_ROOT:
|
||||
src = os.path.join(NM_ROOT, d, "node_modules")
|
||||
nm_ok[d] = os.path.isdir(src) and os.path.isdir(os.path.join(copy, d))
|
||||
if nm_ok[d]:
|
||||
link = os.path.join(copy, d, "node_modules")
|
||||
link_dir(os.path.realpath(src), link)
|
||||
links.append(link)
|
||||
BE, FE = os.path.join(copy, "backend"), os.path.join(copy, "frontend")
|
||||
|
||||
# ------------------------------------------------------------ 2. backend build and start
|
||||
built = {"ok": False}
|
||||
|
||||
def backend_build():
|
||||
if not (NPM and nm_ok.get("backend")):
|
||||
return False, "no npm or no backend node_modules"
|
||||
rc, out = run([NPM, "run", "build"], BE, 240)
|
||||
built["ok"] = rc == 0 and os.path.isfile(os.path.join(BE, "dist", "main.js"))
|
||||
return built["ok"], "rc=%s dist/main.js=%s %s" % (rc, os.path.isfile(os.path.join(BE, "dist", "main.js")), out[-200:])
|
||||
|
||||
guarded("backend: npm run build succeeds and produces dist/main.js", backend_build)
|
||||
|
||||
port = free_port()
|
||||
server = None
|
||||
server_log = os.path.join(tmp, "server.log")
|
||||
if built["ok"]:
|
||||
env = dict(ENV)
|
||||
env["PORT"] = str(port)
|
||||
logf = open(server_log, "w")
|
||||
server = subprocess.Popen([NODE, os.path.join("dist", "main.js")], cwd=BE, env=env, stdout=logf, stderr=subprocess.STDOUT)
|
||||
up = False
|
||||
for _ in range(120):
|
||||
if server.poll() is not None:
|
||||
break
|
||||
try:
|
||||
socket.create_connection(("127.0.0.1", port), timeout=0.3).close()
|
||||
up = True
|
||||
break
|
||||
except OSError:
|
||||
time.sleep(0.25)
|
||||
else:
|
||||
up = False
|
||||
guarded("backend: node dist/main.js listens on 127.0.0.1:$PORT", lambda: (up, "not listening; log: " + read(server_log)[-200:]))
|
||||
|
||||
BASE = "http://127.0.0.1:%d" % port
|
||||
|
||||
def call(method, path, body=None):
|
||||
data = None if body is None else json.dumps(body).encode()
|
||||
req = urllib.request.Request(BASE + path, data=data, method=method, headers={"Content-Type": "application/json", "Accept": "application/json"})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=15) as r:
|
||||
raw, status = r.read(), r.status
|
||||
except urllib.error.HTTPError as e:
|
||||
raw, status = e.read(), e.code
|
||||
try:
|
||||
js = json.loads(raw.decode("utf-8")) if raw else None
|
||||
except ValueError:
|
||||
js = None
|
||||
return status, js
|
||||
|
||||
TAG = "zq%d" % (int(time.time()) % 100000)
|
||||
|
||||
def rest(name, fn):
|
||||
if not up:
|
||||
check(name, False, "the server is not running")
|
||||
else:
|
||||
guarded(name, fn)
|
||||
|
||||
def mk_company(name=None, **extra):
|
||||
s, j = call("POST", "/api/companies", dict({"name": name or TAG + "-co"}, **extra))
|
||||
assert s == 201 and is_int(j.get("id")), "create company: %s %s" % (s, j)
|
||||
return j
|
||||
|
||||
def mk_contact(name=None, **extra):
|
||||
s, j = call("POST", "/api/contacts", dict({"name": name or TAG + "-ct"}, **extra))
|
||||
assert s == 201 and is_int(j.get("id")), "create contact: %s %s" % (s, j)
|
||||
return j
|
||||
|
||||
def mk_deal(title=None, **extra):
|
||||
s, j = call("POST", "/api/deals", dict({"title": title or TAG + "-dl"}, **extra))
|
||||
assert s == 201 and is_int(j.get("id")), "create deal: %s %s" % (s, j)
|
||||
return j
|
||||
|
||||
# ---- companies
|
||||
def t_company_create():
|
||||
s, j = call("POST", "/api/companies", {"name": TAG + " Acme", "website": "https://acme.test", "industry": "Tools"})
|
||||
ok = s == 201 and is_int(j.get("id")) and j.get("name") == TAG + " Acme" and j.get("website") == "https://acme.test" and j.get("industry") == "Tools"
|
||||
return ok, "%s %s" % (s, j)
|
||||
|
||||
def t_company_name_required():
|
||||
a = call("POST", "/api/companies", {"website": "x"})[0]
|
||||
b = call("POST", "/api/companies", {"name": ""})[0]
|
||||
c = call("POST", "/api/companies", {"name": 12})[0]
|
||||
return (a, b, c) == (400, 400, 400), "statuses %s %s %s" % (a, b, c)
|
||||
|
||||
def t_company_get_list():
|
||||
c = mk_company()
|
||||
s, j = call("GET", "/api/companies/%d" % c["id"])
|
||||
s2, lst = call("GET", "/api/companies")
|
||||
ok = s == 200 and j.get("id") == c["id"] and s2 == 200 and isinstance(lst, list) and any(x.get("id") == c["id"] for x in lst)
|
||||
return ok, "%s %s %s" % (s, s2, type(lst))
|
||||
|
||||
def t_company_404():
|
||||
a = call("GET", "/api/companies/987654")[0]
|
||||
b = call("PUT", "/api/companies/987654", {"name": "x"})[0]
|
||||
c = call("DELETE", "/api/companies/987654")[0]
|
||||
return (a, b, c) == (404, 404, 404), "statuses %s %s %s" % (a, b, c)
|
||||
|
||||
def t_company_update():
|
||||
c = mk_company(industry="Old")
|
||||
s, j = call("PUT", "/api/companies/%d" % c["id"], {"name": c["name"] + "-x", "industry": "New"})
|
||||
s2, g = call("GET", "/api/companies/%d" % c["id"])
|
||||
ok = s == 200 and j.get("industry") == "New" and g.get("name") == c["name"] + "-x" and g.get("industry") == "New"
|
||||
return ok, "%s %s %s" % (s, j, g)
|
||||
|
||||
def t_company_update_invalid():
|
||||
c = mk_company()
|
||||
s = call("PUT", "/api/companies/%d" % c["id"], {"name": ""})[0]
|
||||
return s == 400, "status %s" % s
|
||||
|
||||
def t_company_search():
|
||||
mk_company(TAG + " Searchable Widgets")
|
||||
mk_company(TAG + " Other")
|
||||
s, j = call("GET", "/api/companies?q=" + TAG.upper() + "%20SEARCHABLE")
|
||||
ok = s == 200 and len(j) == 1 and j[0]["name"].endswith("Searchable Widgets")
|
||||
return ok, "%s %s" % (s, j)
|
||||
|
||||
def t_company_delete():
|
||||
c = mk_company()
|
||||
a = call("DELETE", "/api/companies/%d" % c["id"])[0]
|
||||
b = call("GET", "/api/companies/%d" % c["id"])[0]
|
||||
return (a, b) == (204, 404), "statuses %s %s" % (a, b)
|
||||
|
||||
# ---- contacts
|
||||
def t_contact_create():
|
||||
c = mk_company()
|
||||
s, j = call("POST", "/api/contacts", {"name": TAG + " Ann", "email": "ann@acme.test", "phone": "123", "companyId": c["id"]})
|
||||
ok = s == 201 and is_int(j.get("id")) and j.get("email") == "ann@acme.test" and j.get("phone") == "123" and j.get("companyId") == c["id"]
|
||||
return ok, "%s %s" % (s, j)
|
||||
|
||||
def t_contact_name_required():
|
||||
a = call("POST", "/api/contacts", {"email": "a@b.co"})[0]
|
||||
b = call("POST", "/api/contacts", {"name": ""})[0]
|
||||
return (a, b) == (400, 400), "statuses %s %s" % (a, b)
|
||||
|
||||
def t_contact_bad_email():
|
||||
s = call("POST", "/api/contacts", {"name": "Bob", "email": "not-an-email"})[0]
|
||||
return s == 400, "status %s" % s
|
||||
|
||||
def t_contact_unknown_company():
|
||||
s = call("POST", "/api/contacts", {"name": "Bob", "companyId": 987654})[0]
|
||||
return s == 400, "status %s" % s
|
||||
|
||||
def t_contact_search():
|
||||
mk_contact(TAG + " Searchable Ann", email="ann.%s@one.test" % TAG)
|
||||
mk_contact(TAG + " Bob", email="bob.%s@two.test" % TAG)
|
||||
s, byname = call("GET", "/api/contacts?q=" + TAG.upper() + "%20searchable")
|
||||
s2, byemail = call("GET", "/api/contacts?q=BOB." + TAG.upper() + "@TWO")
|
||||
ok = s == 200 and len(byname) == 1 and s2 == 200 and len(byemail) == 1 and byemail[0]["name"].endswith("Bob")
|
||||
return ok, "%s %s | %s %s" % (s, byname, s2, byemail)
|
||||
|
||||
def t_contact_update_clear_company():
|
||||
co = mk_company()
|
||||
ct = mk_contact(companyId=co["id"])
|
||||
s, j = call("PUT", "/api/contacts/%d" % ct["id"], {"phone": "999", "companyId": None})
|
||||
g = call("GET", "/api/contacts/%d" % ct["id"])[1]
|
||||
ok = s == 200 and j.get("phone") == "999" and j.get("companyId") is None and g.get("companyId") is None and g.get("phone") == "999"
|
||||
return ok, "%s %s %s" % (s, j, g)
|
||||
|
||||
def t_contact_404_delete():
|
||||
ct = mk_contact()
|
||||
a = call("GET", "/api/contacts/987654")[0]
|
||||
b = call("DELETE", "/api/contacts/%d" % ct["id"])[0]
|
||||
c = call("GET", "/api/contacts/%d" % ct["id"])[0]
|
||||
return (a, b, c) == (404, 204, 404), "statuses %s %s %s" % (a, b, c)
|
||||
|
||||
# ---- deals
|
||||
def t_deal_defaults():
|
||||
s, j = call("POST", "/api/deals", {"title": TAG + " Renewal"})
|
||||
ok = s == 201 and is_int(j.get("id")) and j.get("amount") == 0 and j.get("stage") == "lead" and j.get("companyId") is None and j.get("contactId") is None
|
||||
return ok, "%s %s" % (s, j)
|
||||
|
||||
def t_deal_full():
|
||||
co, ct = mk_company(), mk_contact()
|
||||
s, j = call("POST", "/api/deals", {"title": TAG + " Full", "amount": 1234.5, "stage": "proposal", "companyId": co["id"], "contactId": ct["id"]})
|
||||
ok = s == 201 and j.get("amount") == 1234.5 and j.get("stage") == "proposal" and j.get("companyId") == co["id"] and j.get("contactId") == ct["id"]
|
||||
return ok, "%s %s" % (s, j)
|
||||
|
||||
def t_deal_title_required():
|
||||
a = call("POST", "/api/deals", {"amount": 5})[0]
|
||||
b = call("POST", "/api/deals", {"title": ""})[0]
|
||||
return (a, b) == (400, 400), "statuses %s %s" % (a, b)
|
||||
|
||||
def t_deal_amount_not_number():
|
||||
a = call("POST", "/api/deals", {"title": "x", "amount": "lots"})[0]
|
||||
b = call("POST", "/api/deals", {"title": "x", "amount": -5})[0]
|
||||
return (a, b) == (400, 400), "statuses %s %s" % (a, b)
|
||||
|
||||
def t_deal_invalid_stage():
|
||||
s = call("POST", "/api/deals", {"title": "x", "stage": "maybe"})[0]
|
||||
return s == 400, "status %s" % s
|
||||
|
||||
def t_deal_unknown_refs():
|
||||
a = call("POST", "/api/deals", {"title": "x", "companyId": 987654})[0]
|
||||
b = call("POST", "/api/deals", {"title": "x", "contactId": 987654})[0]
|
||||
return (a, b) == (400, 400), "statuses %s %s" % (a, b)
|
||||
|
||||
def t_deal_move_stage():
|
||||
d = mk_deal(amount=10)
|
||||
s, j = call("PUT", "/api/deals/%d" % d["id"], {"stage": "qualified"})
|
||||
g = call("GET", "/api/deals/%d" % d["id"])[1]
|
||||
ok = s == 200 and j.get("stage") == "qualified" and g.get("stage") == "qualified" and g.get("title") == d["title"] and g.get("amount") == 10
|
||||
return ok, "%s %s %s" % (s, j, g)
|
||||
|
||||
def t_deal_put_invalid_stage():
|
||||
d = mk_deal()
|
||||
s = call("PUT", "/api/deals/%d" % d["id"], {"stage": "nope"})[0]
|
||||
g = call("GET", "/api/deals/%d" % d["id"])[1]
|
||||
return s == 400 and g.get("stage") == "lead", "status %s stage %s" % (s, g.get("stage"))
|
||||
|
||||
def t_deal_404():
|
||||
a = call("GET", "/api/deals/987654")[0]
|
||||
b = call("PUT", "/api/deals/987654", {"stage": "won"})[0]
|
||||
c = call("DELETE", "/api/deals/987654")[0]
|
||||
return (a, b, c) == (404, 404, 404), "statuses %s %s %s" % (a, b, c)
|
||||
|
||||
def t_deal_stage_filter():
|
||||
mk_deal(TAG + " f1", stage="won")
|
||||
mk_deal(TAG + " f2", stage="lost")
|
||||
s, j = call("GET", "/api/deals?stage=won")
|
||||
ok = s == 200 and len(j) >= 1 and all(d["stage"] == "won" for d in j) and any(d["title"] == TAG + " f1" for d in j) and not any(d["title"] == TAG + " f2" for d in j)
|
||||
return ok, "%s n=%s" % (s, None if j is None else len(j))
|
||||
|
||||
def t_deal_stage_bogus():
|
||||
s = call("GET", "/api/deals?stage=bogus")[0]
|
||||
return s == 400, "status %s" % s
|
||||
|
||||
def t_deal_q_and_stage():
|
||||
mk_deal(TAG + " Alpha one", stage="won")
|
||||
mk_deal(TAG + " Alpha two", stage="lost")
|
||||
mk_deal(TAG + " Beta", stage="won")
|
||||
s, j = call("GET", "/api/deals?stage=won&q=" + TAG.upper() + "%20alpha")
|
||||
s2, k = call("GET", "/api/deals?q=" + TAG.upper() + "%20ALPHA")
|
||||
ok = s == 200 and [d["title"] for d in j] == [TAG + " Alpha one"] and s2 == 200 and len(k) == 2
|
||||
return ok, "%s %s | %s %s" % (s, j, s2, k)
|
||||
|
||||
def t_deal_delete():
|
||||
d = mk_deal()
|
||||
a = call("DELETE", "/api/deals/%d" % d["id"])[0]
|
||||
b = call("GET", "/api/deals/%d" % d["id"])[0]
|
||||
c = call("DELETE", "/api/deals/%d" % d["id"])[0]
|
||||
return (a, b, c) == (204, 404, 404), "statuses %s %s %s" % (a, b, c)
|
||||
|
||||
# ---- pipeline and references
|
||||
def t_pipeline_shape():
|
||||
s, j = call("GET", "/api/pipeline")
|
||||
ok = s == 200 and isinstance(j, dict) and all(st in j and is_int(j[st].get("count")) and isinstance(j[st].get("amount"), (int, float)) for st in STAGES)
|
||||
return ok, "%s %s" % (s, j)
|
||||
|
||||
def t_pipeline_totals():
|
||||
before = call("GET", "/api/pipeline")[1]
|
||||
mk_deal(stage="proposal", amount=7.5)
|
||||
mk_deal(stage="proposal", amount=2.25)
|
||||
after = call("GET", "/api/pipeline")[1]
|
||||
ok = (after["proposal"]["count"] == before["proposal"]["count"] + 2 and abs(after["proposal"]["amount"] - before["proposal"]["amount"] - 9.75) < 1e-6
|
||||
and after["won"] == before["won"])
|
||||
return ok, "%s -> %s" % (before["proposal"], after["proposal"])
|
||||
|
||||
def t_pipeline_matches_list():
|
||||
pipe = call("GET", "/api/pipeline")[1]
|
||||
deals = call("GET", "/api/deals")[1]
|
||||
for st in STAGES:
|
||||
mine = [d for d in deals if d["stage"] == st]
|
||||
if pipe[st]["count"] != len(mine) or abs(pipe[st]["amount"] - sum(d["amount"] for d in mine)) > 1e-6:
|
||||
return False, "stage %s: %s vs %d deals" % (st, pipe[st], len(mine))
|
||||
return True, ""
|
||||
|
||||
def t_delete_company_clears_refs():
|
||||
co = mk_company()
|
||||
ct = mk_contact(companyId=co["id"])
|
||||
d = mk_deal(companyId=co["id"], contactId=ct["id"])
|
||||
s = call("DELETE", "/api/companies/%d" % co["id"])[0]
|
||||
c2 = call("GET", "/api/contacts/%d" % ct["id"])
|
||||
d2 = call("GET", "/api/deals/%d" % d["id"])
|
||||
ok = s == 204 and c2[0] == 200 and c2[1].get("companyId") is None and d2[0] == 200 and d2[1].get("companyId") is None and d2[1].get("contactId") == ct["id"]
|
||||
return ok, "%s %s %s" % (s, c2, d2)
|
||||
|
||||
def t_delete_contact_clears_refs():
|
||||
ct = mk_contact()
|
||||
d = mk_deal(contactId=ct["id"])
|
||||
s = call("DELETE", "/api/contacts/%d" % ct["id"])[0]
|
||||
d2 = call("GET", "/api/deals/%d" % d["id"])
|
||||
return s == 204 and d2[0] == 200 and d2[1].get("contactId") is None, "%s %s" % (s, d2)
|
||||
|
||||
def t_ids_unique_integers():
|
||||
ids = [mk_company()["id"] for _ in range(3)]
|
||||
return len(set(ids)) == 3 and all(is_int(i) for i in ids), "ids %s" % ids
|
||||
|
||||
for nm, fn in [
|
||||
("rest: POST /api/companies creates (201, integer id, fields)", t_company_create),
|
||||
("rest: company name is required (400)", t_company_name_required),
|
||||
("rest: GET company by id and in the list", t_company_get_list),
|
||||
("rest: unknown company id gives 404 on GET, PUT and DELETE", t_company_404),
|
||||
("rest: PUT /api/companies/:id updates and persists", t_company_update),
|
||||
("rest: PUT company with an empty name is 400", t_company_update_invalid),
|
||||
("rest: ?q= searches companies case-insensitively", t_company_search),
|
||||
("rest: DELETE company is 204, then 404", t_company_delete),
|
||||
("rest: POST /api/contacts creates with a company", t_contact_create),
|
||||
("rest: contact name is required (400)", t_contact_name_required),
|
||||
("rest: contact email must look like an email (400)", t_contact_bad_email),
|
||||
("rest: contact with an unknown companyId is 400", t_contact_unknown_company),
|
||||
("rest: ?q= searches contacts by name and by email", t_contact_search),
|
||||
("rest: PUT contact updates and companyId null clears it", t_contact_update_clear_company),
|
||||
("rest: contact 404 on unknown id, DELETE 204", t_contact_404_delete),
|
||||
("rest: POST /api/deals defaults (amount 0, stage lead, null refs)", t_deal_defaults),
|
||||
("rest: POST deal with all fields", t_deal_full),
|
||||
("rest: deal title is required (400)", t_deal_title_required),
|
||||
("rest: deal amount must be a number >= 0 (400)", t_deal_amount_not_number),
|
||||
("rest: deal with an invalid stage is 400", t_deal_invalid_stage),
|
||||
("rest: deal with unknown companyId or contactId is 400", t_deal_unknown_refs),
|
||||
("rest: PUT deal moves it to another stage", t_deal_move_stage),
|
||||
("rest: PUT deal with an invalid stage is 400 and changes nothing", t_deal_put_invalid_stage),
|
||||
("rest: deal 404 on unknown id for GET, PUT and DELETE", t_deal_404),
|
||||
("rest: GET /api/deals?stage= filters", t_deal_stage_filter),
|
||||
("rest: GET /api/deals?stage=bogus is 400", t_deal_stage_bogus),
|
||||
("rest: ?stage= and ?q= combine; q is case-insensitive", t_deal_q_and_stage),
|
||||
("rest: DELETE deal is 204, then 404", t_deal_delete),
|
||||
("rest: GET /api/pipeline has count and amount for all five stages", t_pipeline_shape),
|
||||
("rest: pipeline totals follow new deals", t_pipeline_totals),
|
||||
("rest: pipeline agrees with the deals list", t_pipeline_matches_list),
|
||||
("rest: deleting a company clears references, keeps deals", t_delete_company_clears_refs),
|
||||
("rest: deleting a contact clears the deal reference", t_delete_contact_clears_refs),
|
||||
("rest: ids are unique integers", t_ids_unique_integers),
|
||||
]:
|
||||
rest(nm, fn)
|
||||
|
||||
if server is not None:
|
||||
server.terminate()
|
||||
try:
|
||||
server.wait(10)
|
||||
except subprocess.TimeoutExpired:
|
||||
server.kill()
|
||||
|
||||
# ------------------------------------------------------------ 3. the agent's own backend tests
|
||||
def count_tests(out):
|
||||
m = re.search(r"Tests:\s+(?:(\d+) failed,\s*)?(?:(\d+) skipped,\s*)?(?:(\d+) todo,\s*)?(?:(\d+) passed,\s*)?(\d+) total", out)
|
||||
if not m:
|
||||
return 0, 0
|
||||
return int(m.group(4) or 0), int(m.group(1) or 0)
|
||||
|
||||
own = {"passed": 0}
|
||||
|
||||
def own_tests(script):
|
||||
def f():
|
||||
if not (NPM and nm_ok.get("backend")):
|
||||
return False, "no npm or no backend node_modules"
|
||||
rc, out = run([NPM, "run", script], BE, 240)
|
||||
passed, failed = count_tests(out)
|
||||
own["passed"] += passed if rc == 0 else 0
|
||||
return rc == 0 and failed == 0 and passed >= 1, "rc=%s passed=%s failed=%s %s" % (rc, passed, failed, out[-250:])
|
||||
return f
|
||||
|
||||
guarded("backend tests: npm test passes (>= 1 test)", own_tests("test"))
|
||||
guarded("backend tests: npm run test:e2e passes (>= 1 test)", own_tests("test:e2e"))
|
||||
check("backend tests: at least %d test cases pass in total" % MIN_TESTS, own["passed"] >= MIN_TESTS, "total passed %d" % own["passed"])
|
||||
|
||||
# ------------------------------------------------------------ 4. frontend build
|
||||
def frontend_build():
|
||||
if not (NPM and nm_ok.get("frontend")):
|
||||
return False, "no npm or no frontend node_modules"
|
||||
rc, out = run([NPM, "run", "build"], FE, 280)
|
||||
idx = glob.glob(os.path.join(FE, "dist", "**", "index.html"), recursive=True)
|
||||
return rc == 0 and len(idx) > 0, "rc=%s index.html=%d %s" % (rc, len(idx), out[-300:])
|
||||
|
||||
guarded("frontend: npm run build (production) succeeds and writes index.html", frontend_build)
|
||||
finally:
|
||||
for lk in links:
|
||||
unlink_dir(lk)
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
|
||||
# ---------------------------------------------------------------- 5. static checks of the frontend sources (read only, on the workspace)
|
||||
SRC = os.path.join(WS, "frontend", "src")
|
||||
files = [p for p in glob.glob(os.path.join(SRC, "**", "*"), recursive=True) if os.path.isfile(p) and p.endswith((".ts", ".html")) and not p.endswith(".spec.ts")]
|
||||
texts = {p: read(p) for p in files}
|
||||
alltext = "\n".join(texts.values())
|
||||
ts_text = "\n".join(t for p, t in texts.items() if p.endswith(".ts"))
|
||||
|
||||
guarded("frontend src: Router config with companies, contacts and deals routes", lambda: (
|
||||
re.search(r"\bRoutes\b", ts_text) is not None and all(re.search(r"""path\s*:\s*['"]%s['"]""" % r, ts_text) for r in ("companies", "contacts", "deals")), "routes not found"))
|
||||
guarded("frontend src: router outlet and provideRouter are used", lambda: (
|
||||
re.search(r"router-outlet|RouterOutlet", alltext) is not None and re.search(r"provideRouter|RouterModule", ts_text) is not None, "missing"))
|
||||
guarded("frontend src: HttpClient is provided and injected", lambda: (
|
||||
re.search(r"provideHttpClient|HttpClientModule", ts_text) is not None and re.search(r"inject\(\s*HttpClient\s*\)|:\s*HttpClient\b", ts_text) is not None, "missing"))
|
||||
guarded("frontend src: calls /api/companies, /api/contacts and /api/deals", lambda: (
|
||||
all(re.search(r"/api/" + r, ts_text) or (re.search(r"/api/\$\{", ts_text) and r in ts_text) for r in ("companies", "contacts", "deals")), "no calls to the API"))
|
||||
guarded("frontend src: create, update and delete requests are made", lambda: (
|
||||
all(re.search(pat, ts_text) for pat in (r"\.post\s*[<(]", r"\.(put|patch)\s*[<(]", r"\.delete\s*[<(]")), "post/put/delete missing"))
|
||||
guarded("frontend src: a board with one column per stage (all five stages and a loop)", lambda: (
|
||||
any(all(st in t for st in STAGES) and re.search(r"@for|\*ngFor|\.map\(|\.forEach\(", t) for t in texts.values()), "no file with all five stages and a loop"))
|
||||
guarded("frontend src: a search input", lambda: (
|
||||
re.search(r"<input[^>]*search", alltext, re.I) is not None, "no <input ... search ...>"))
|
||||
guarded("frontend src: forms use FormsModule or ReactiveFormsModule", lambda: (
|
||||
re.search(r"FormsModule|ReactiveFormsModule|FormBuilder|FormControl", ts_text) is not None, "no forms module"))
|
||||
guarded("frontend src: components for companies, contacts and deals exist", lambda: (
|
||||
re.search(r"@Component", ts_text) is not None and all(re.search(r"class\s+\w*" + r, ts_text, re.I) for r in ("Compan", "Contact", "Deal")), "components missing"))
|
||||
|
||||
print("SUMMARY %d/%d" % (sum(results), len(results)))
|
||||
sys.exit(0 if all(results) else 1)
|
||||
@@ -0,0 +1,25 @@
|
||||
# Reference solution notes (never installed on the server)
|
||||
|
||||
`overlay/` holds the files that, copied over `seed/`, make `accept.py` pass 56/56: the whole backend (`src/`, `test/crm.e2e-spec.ts`; 15 unit and 15 e2e tests) and the frontend
|
||||
(`src/app/*`, `proxy.conf.json`, `angular.json` with `proxyConfig`). It only adds or replaces files: the seed has no file that would have to be deleted.
|
||||
|
||||
## Running `selftest.py nestng-crm` (no edit of selftest.py is needed)
|
||||
|
||||
`selftest.py` builds the workspace from `seed/` (+ `reference/overlay/`) WITHOUT node_modules, so `accept.py` needs `NESTNG_NM_ROOT`, a directory that holds
|
||||
`backend/node_modules` and `frontend/node_modules` (made with `npm ci` from the two seed lockfiles; on the laptop it was `.../scratchpad/nestng-dev/ci`):
|
||||
|
||||
```sh
|
||||
NESTNG_NM_ROOT=/path/to/nm-root python3 scripts/e2e/codex/tasks/selftest.py nestng-crm
|
||||
# nestng-crm seed: ok rc=1 79.1s seed+overlay: ok rc=0 21.6s
|
||||
# selftest: all good
|
||||
```
|
||||
|
||||
On the server add `NESTNG_NODE_BIN=<dir of node and npm>` if node is not on PATH. selftest compares `workspace_lines` before and after the acceptance run: unchanged.
|
||||
|
||||
## What the main session has to add for the real runner (not in this task directory)
|
||||
|
||||
1. `cell.py`: after `copy_tree(seed, ws)` and the SEEDTREE check, hard-link the shared `backend/node_modules` and `frontend/node_modules` into `ws` (`cp -al`-style, no data copy);
|
||||
exclude `node_modules`, `dist`, `.angular` from the final `workspace.sha256` and from any digest of the workspace.
|
||||
2. `MANIFEST.sha256`: `python3 scripts/e2e/codex/tasks/freeze.py` (this task is picked up by `taskfile.task_ids`); read-only install on the server like the other tasks.
|
||||
3. Node on PATH in the Codex shell and for `accept.py` (`NESTNG_NODE_BIN`); the allowed acceptance run time of this task is up to 300 s (README says < 120 s for the others).
|
||||
4. Server `npm ci` of the shared trees: see `../NOTES.md`.
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { CompaniesController } from './companies/companies.controller';
|
||||
import { ContactsController } from './contacts/contacts.controller';
|
||||
import { DealsController } from './deals/deals.controller';
|
||||
import { PipelineController } from './pipeline/pipeline.controller';
|
||||
import { StoreService } from './common/store.service';
|
||||
|
||||
@Module({
|
||||
controllers: [CompaniesController, ContactsController, DealsController, PipelineController],
|
||||
providers: [StoreService],
|
||||
})
|
||||
export class AppModule {}
|
||||
@@ -0,0 +1,26 @@
|
||||
export const STAGES = ['lead', 'qualified', 'proposal', 'won', 'lost'] as const;
|
||||
export type Stage = (typeof STAGES)[number];
|
||||
|
||||
export interface Company {
|
||||
id: number;
|
||||
name: string;
|
||||
website: string | null;
|
||||
industry: string | null;
|
||||
}
|
||||
|
||||
export interface Contact {
|
||||
id: number;
|
||||
name: string;
|
||||
email: string | null;
|
||||
phone: string | null;
|
||||
companyId: number | null;
|
||||
}
|
||||
|
||||
export interface Deal {
|
||||
id: number;
|
||||
title: string;
|
||||
amount: number;
|
||||
stage: Stage;
|
||||
companyId: number | null;
|
||||
contactId: number | null;
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
import { ParseIdPipe, matches } from './parse-id.pipe';
|
||||
|
||||
describe('ParseIdPipe', () => {
|
||||
const pipe = new ParseIdPipe();
|
||||
|
||||
it('parses a positive integer', () => {
|
||||
expect(pipe.transform('42')).toBe(42);
|
||||
});
|
||||
|
||||
it.each(['abc', '-1', '1.5', ''])('rejects %p', (value) => {
|
||||
expect(() => pipe.transform(value)).toThrow(BadRequestException);
|
||||
});
|
||||
});
|
||||
|
||||
describe('matches', () => {
|
||||
it('is case-insensitive', () => {
|
||||
expect(matches('Acme Corp', 'acme')).toBe(true);
|
||||
expect(matches('Acme Corp', 'CORP')).toBe(true);
|
||||
});
|
||||
|
||||
it('matches everything for an empty query', () => {
|
||||
expect(matches('anything', '')).toBe(true);
|
||||
expect(matches(null, undefined)).toBe(true);
|
||||
});
|
||||
|
||||
it('does not match a missing text', () => {
|
||||
expect(matches(null, 'x')).toBe(false);
|
||||
});
|
||||
});
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
import { BadRequestException, PipeTransform } from '@nestjs/common';
|
||||
|
||||
/** The id in the path must be a positive integer; anything else is a 400 (an unknown but valid id is a 404 later). */
|
||||
export class ParseIdPipe implements PipeTransform<string, number> {
|
||||
transform(value: string): number {
|
||||
if (!/^\d+$/.test(value)) throw new BadRequestException('id must be a positive integer');
|
||||
return Number(value);
|
||||
}
|
||||
}
|
||||
|
||||
/** Case-insensitive substring match; an empty query matches everything. */
|
||||
export function matches(text: string | null | undefined, q: string | undefined): boolean {
|
||||
if (!q) return true;
|
||||
return (text ?? '').toLowerCase().includes(q.toLowerCase());
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { Company, Contact, Deal } from './models';
|
||||
|
||||
/** In-memory storage for all three resources; ids are integers that are never reused. */
|
||||
@Injectable()
|
||||
export class StoreService {
|
||||
companies = new Map<number, Company>();
|
||||
contacts = new Map<number, Contact>();
|
||||
deals = new Map<number, Deal>();
|
||||
private seq = { companies: 1, contacts: 1, deals: 1 };
|
||||
|
||||
nextId(kind: 'companies' | 'contacts' | 'deals'): number {
|
||||
return this.seq[kind]++;
|
||||
}
|
||||
|
||||
requireCompany(id: number): Company {
|
||||
const found = this.companies.get(id);
|
||||
if (!found) throw new NotFoundException(`company ${id} not found`);
|
||||
return found;
|
||||
}
|
||||
|
||||
requireContact(id: number): Contact {
|
||||
const found = this.contacts.get(id);
|
||||
if (!found) throw new NotFoundException(`contact ${id} not found`);
|
||||
return found;
|
||||
}
|
||||
|
||||
requireDeal(id: number): Deal {
|
||||
const found = this.deals.get(id);
|
||||
if (!found) throw new NotFoundException(`deal ${id} not found`);
|
||||
return found;
|
||||
}
|
||||
|
||||
/** A reference that is given (not null or undefined) must point at an existing record. */
|
||||
checkCompanyRef(id: number | null | undefined): void {
|
||||
if (id !== null && id !== undefined && !this.companies.has(id)) throw new BadRequestException(`companyId ${id} does not exist`);
|
||||
}
|
||||
|
||||
checkContactRef(id: number | null | undefined): void {
|
||||
if (id !== null && id !== undefined && !this.contacts.has(id)) throw new BadRequestException(`contactId ${id} does not exist`);
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
import { Body, Controller, Delete, Get, HttpCode, Param, Post, Put, Query } from '@nestjs/common';
|
||||
import { Company } from '../common/models';
|
||||
import { ParseIdPipe, matches } from '../common/parse-id.pipe';
|
||||
import { StoreService } from '../common/store.service';
|
||||
import { CreateCompanyDto, UpdateCompanyDto } from './company.dto';
|
||||
|
||||
@Controller('companies')
|
||||
export class CompaniesController {
|
||||
constructor(private readonly store: StoreService) {}
|
||||
|
||||
@Get()
|
||||
list(@Query('q') q?: string): Company[] {
|
||||
return [...this.store.companies.values()].filter((c) => matches(c.name, q));
|
||||
}
|
||||
|
||||
@Post()
|
||||
create(@Body() dto: CreateCompanyDto): Company {
|
||||
const company: Company = {
|
||||
id: this.store.nextId('companies'),
|
||||
name: dto.name,
|
||||
website: dto.website ?? null,
|
||||
industry: dto.industry ?? null,
|
||||
};
|
||||
this.store.companies.set(company.id, company);
|
||||
return company;
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
get(@Param('id', ParseIdPipe) id: number): Company {
|
||||
return this.store.requireCompany(id);
|
||||
}
|
||||
|
||||
@Put(':id')
|
||||
update(@Param('id', ParseIdPipe) id: number, @Body() dto: UpdateCompanyDto): Company {
|
||||
const company = this.store.requireCompany(id);
|
||||
if (dto.name !== undefined) company.name = dto.name;
|
||||
if (dto.website !== undefined) company.website = dto.website;
|
||||
if (dto.industry !== undefined) company.industry = dto.industry;
|
||||
return company;
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@HttpCode(204)
|
||||
remove(@Param('id', ParseIdPipe) id: number): void {
|
||||
this.store.requireCompany(id);
|
||||
this.store.companies.delete(id);
|
||||
for (const contact of this.store.contacts.values()) if (contact.companyId === id) contact.companyId = null;
|
||||
for (const deal of this.store.deals.values()) if (deal.companyId === id) deal.companyId = null;
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
import { IsNotEmpty, IsOptional, IsString, ValidateIf } from 'class-validator';
|
||||
|
||||
export class CreateCompanyDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
name!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
website?: string | null;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
industry?: string | null;
|
||||
}
|
||||
|
||||
export class UpdateCompanyDto {
|
||||
@ValidateIf((o: UpdateCompanyDto) => o.name !== undefined)
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
name?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
website?: string | null;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
industry?: string | null;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { INestApplication, ValidationPipe } from '@nestjs/common';
|
||||
|
||||
/** Shared by main.ts and the tests: global prefix and validation. */
|
||||
export function configureApp(app: INestApplication): void {
|
||||
app.setGlobalPrefix('api');
|
||||
app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }));
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
import { IsEmail, IsInt, IsNotEmpty, IsOptional, IsString, ValidateIf } from 'class-validator';
|
||||
|
||||
export class CreateContactDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
name!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsEmail()
|
||||
email?: string | null;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
phone?: string | null;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
companyId?: number | null;
|
||||
}
|
||||
|
||||
export class UpdateContactDto {
|
||||
@ValidateIf((o: UpdateContactDto) => o.name !== undefined)
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
name?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsEmail()
|
||||
email?: string | null;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
phone?: string | null;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
companyId?: number | null;
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
import { Body, Controller, Delete, Get, HttpCode, Param, Post, Put, Query } from '@nestjs/common';
|
||||
import { Contact } from '../common/models';
|
||||
import { ParseIdPipe, matches } from '../common/parse-id.pipe';
|
||||
import { StoreService } from '../common/store.service';
|
||||
import { CreateContactDto, UpdateContactDto } from './contact.dto';
|
||||
|
||||
@Controller('contacts')
|
||||
export class ContactsController {
|
||||
constructor(private readonly store: StoreService) {}
|
||||
|
||||
@Get()
|
||||
list(@Query('q') q?: string): Contact[] {
|
||||
return [...this.store.contacts.values()].filter((c) => matches(c.name, q) || matches(c.email, q));
|
||||
}
|
||||
|
||||
@Post()
|
||||
create(@Body() dto: CreateContactDto): Contact {
|
||||
this.store.checkCompanyRef(dto.companyId);
|
||||
const contact: Contact = {
|
||||
id: this.store.nextId('contacts'),
|
||||
name: dto.name,
|
||||
email: dto.email ?? null,
|
||||
phone: dto.phone ?? null,
|
||||
companyId: dto.companyId ?? null,
|
||||
};
|
||||
this.store.contacts.set(contact.id, contact);
|
||||
return contact;
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
get(@Param('id', ParseIdPipe) id: number): Contact {
|
||||
return this.store.requireContact(id);
|
||||
}
|
||||
|
||||
@Put(':id')
|
||||
update(@Param('id', ParseIdPipe) id: number, @Body() dto: UpdateContactDto): Contact {
|
||||
const contact = this.store.requireContact(id);
|
||||
this.store.checkCompanyRef(dto.companyId);
|
||||
if (dto.name !== undefined) contact.name = dto.name;
|
||||
if (dto.email !== undefined) contact.email = dto.email;
|
||||
if (dto.phone !== undefined) contact.phone = dto.phone;
|
||||
if (dto.companyId !== undefined) contact.companyId = dto.companyId;
|
||||
return contact;
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@HttpCode(204)
|
||||
remove(@Param('id', ParseIdPipe) id: number): void {
|
||||
this.store.requireContact(id);
|
||||
this.store.contacts.delete(id);
|
||||
for (const deal of this.store.deals.values()) if (deal.contactId === id) deal.contactId = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { IsIn, IsInt, IsNotEmpty, IsNumber, IsOptional, IsString, Min, ValidateIf } from 'class-validator';
|
||||
import { STAGES, Stage } from '../common/models';
|
||||
|
||||
export class CreateDealDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
title!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber({ allowNaN: false, allowInfinity: false })
|
||||
@Min(0)
|
||||
amount?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsIn(STAGES)
|
||||
stage?: Stage;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
companyId?: number | null;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
contactId?: number | null;
|
||||
}
|
||||
|
||||
export class UpdateDealDto {
|
||||
@ValidateIf((o: UpdateDealDto) => o.title !== undefined)
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
title?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber({ allowNaN: false, allowInfinity: false })
|
||||
@Min(0)
|
||||
amount?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsIn(STAGES)
|
||||
stage?: Stage;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
companyId?: number | null;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
contactId?: number | null;
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
import { BadRequestException, NotFoundException } from '@nestjs/common';
|
||||
import { StoreService } from '../common/store.service';
|
||||
import { CompaniesController } from '../companies/companies.controller';
|
||||
import { PipelineController } from '../pipeline/pipeline.controller';
|
||||
import { DealsController } from './deals.controller';
|
||||
|
||||
describe('DealsController', () => {
|
||||
let store: StoreService;
|
||||
let deals: DealsController;
|
||||
let companies: CompaniesController;
|
||||
let pipeline: PipelineController;
|
||||
|
||||
beforeEach(() => {
|
||||
store = new StoreService();
|
||||
deals = new DealsController(store);
|
||||
companies = new CompaniesController(store);
|
||||
pipeline = new PipelineController(store);
|
||||
});
|
||||
|
||||
it('creates a deal with defaults', () => {
|
||||
expect(deals.create({ title: 'First' })).toEqual({ id: 1, title: 'First', amount: 0, stage: 'lead', companyId: null, contactId: null });
|
||||
});
|
||||
|
||||
it('never reuses ids', () => {
|
||||
const a = deals.create({ title: 'a' });
|
||||
deals.remove(a.id);
|
||||
expect(deals.create({ title: 'b' }).id).toBe(2);
|
||||
});
|
||||
|
||||
it('rejects an unknown company reference', () => {
|
||||
expect(() => deals.create({ title: 'x', companyId: 99 })).toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it('throws NotFound for an unknown id', () => {
|
||||
expect(() => deals.get(5)).toThrow(NotFoundException);
|
||||
});
|
||||
|
||||
it('filters by stage and by text together', () => {
|
||||
deals.create({ title: 'Big Renewal', stage: 'won', amount: 10 });
|
||||
deals.create({ title: 'Small renewal', stage: 'lead', amount: 1 });
|
||||
deals.create({ title: 'Other', stage: 'won', amount: 5 });
|
||||
expect(deals.list('renewal', 'won').map((d) => d.title)).toEqual(['Big Renewal']);
|
||||
expect(() => deals.list(undefined, 'bogus')).toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it('summarises the pipeline for every stage', () => {
|
||||
deals.create({ title: 'a', stage: 'won', amount: 10 });
|
||||
deals.create({ title: 'b', stage: 'won', amount: 5.5 });
|
||||
deals.create({ title: 'c' });
|
||||
expect(pipeline.pipeline()).toEqual({
|
||||
lead: { count: 1, amount: 0 },
|
||||
qualified: { count: 0, amount: 0 },
|
||||
proposal: { count: 0, amount: 0 },
|
||||
won: { count: 2, amount: 15.5 },
|
||||
lost: { count: 0, amount: 0 },
|
||||
});
|
||||
});
|
||||
|
||||
it('clears the company reference of a deal when the company is deleted', () => {
|
||||
const company = companies.create({ name: 'Acme' });
|
||||
const deal = deals.create({ title: 'd', companyId: company.id });
|
||||
companies.remove(company.id);
|
||||
expect(deals.get(deal.id).companyId).toBeNull();
|
||||
});
|
||||
});
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
import { BadRequestException, Body, Controller, Delete, Get, HttpCode, Param, Post, Put, Query } from '@nestjs/common';
|
||||
import { Deal, STAGES, Stage } from '../common/models';
|
||||
import { ParseIdPipe, matches } from '../common/parse-id.pipe';
|
||||
import { StoreService } from '../common/store.service';
|
||||
import { CreateDealDto, UpdateDealDto } from './deal.dto';
|
||||
|
||||
@Controller('deals')
|
||||
export class DealsController {
|
||||
constructor(private readonly store: StoreService) {}
|
||||
|
||||
@Get()
|
||||
list(@Query('q') q?: string, @Query('stage') stage?: string): Deal[] {
|
||||
if (stage !== undefined && stage !== '' && !STAGES.includes(stage as Stage)) {
|
||||
throw new BadRequestException(`stage must be one of ${STAGES.join(', ')}`);
|
||||
}
|
||||
return [...this.store.deals.values()].filter((d) => matches(d.title, q) && (!stage || d.stage === stage));
|
||||
}
|
||||
|
||||
@Post()
|
||||
create(@Body() dto: CreateDealDto): Deal {
|
||||
this.store.checkCompanyRef(dto.companyId);
|
||||
this.store.checkContactRef(dto.contactId);
|
||||
const deal: Deal = {
|
||||
id: this.store.nextId('deals'),
|
||||
title: dto.title,
|
||||
amount: dto.amount ?? 0,
|
||||
stage: dto.stage ?? 'lead',
|
||||
companyId: dto.companyId ?? null,
|
||||
contactId: dto.contactId ?? null,
|
||||
};
|
||||
this.store.deals.set(deal.id, deal);
|
||||
return deal;
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
get(@Param('id', ParseIdPipe) id: number): Deal {
|
||||
return this.store.requireDeal(id);
|
||||
}
|
||||
|
||||
@Put(':id')
|
||||
update(@Param('id', ParseIdPipe) id: number, @Body() dto: UpdateDealDto): Deal {
|
||||
const deal = this.store.requireDeal(id);
|
||||
this.store.checkCompanyRef(dto.companyId);
|
||||
this.store.checkContactRef(dto.contactId);
|
||||
if (dto.title !== undefined) deal.title = dto.title;
|
||||
if (dto.amount !== undefined) deal.amount = dto.amount;
|
||||
if (dto.stage !== undefined) deal.stage = dto.stage;
|
||||
if (dto.companyId !== undefined) deal.companyId = dto.companyId;
|
||||
if (dto.contactId !== undefined) deal.contactId = dto.contactId;
|
||||
return deal;
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@HttpCode(204)
|
||||
remove(@Param('id', ParseIdPipe) id: number): void {
|
||||
this.store.requireDeal(id);
|
||||
this.store.deals.delete(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import 'reflect-metadata';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { AppModule } from './app.module';
|
||||
import { configureApp } from './configure-app';
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule);
|
||||
configureApp(app);
|
||||
const port = Number(process.env.PORT) || 3000;
|
||||
await app.listen(port, '127.0.0.1');
|
||||
}
|
||||
bootstrap();
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
import { STAGES, Stage } from '../common/models';
|
||||
import { StoreService } from '../common/store.service';
|
||||
|
||||
@Controller('pipeline')
|
||||
export class PipelineController {
|
||||
constructor(private readonly store: StoreService) {}
|
||||
|
||||
@Get()
|
||||
pipeline(): Record<Stage, { count: number; amount: number }> {
|
||||
const result = {} as Record<Stage, { count: number; amount: number }>;
|
||||
for (const stage of STAGES) result[stage] = { count: 0, amount: 0 };
|
||||
for (const deal of this.store.deals.values()) {
|
||||
result[deal.stage].count += 1;
|
||||
result[deal.stage].amount += deal.amount;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import request from 'supertest';
|
||||
import { AppModule } from '../src/app.module';
|
||||
import { configureApp } from '../src/configure-app';
|
||||
|
||||
describe('CRM API (e2e)', () => {
|
||||
let app: INestApplication;
|
||||
let http: ReturnType<INestApplication['getHttpServer']>;
|
||||
|
||||
beforeEach(async () => {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [AppModule] }).compile();
|
||||
app = moduleRef.createNestApplication();
|
||||
configureApp(app);
|
||||
await app.init();
|
||||
http = app.getHttpServer();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
const post = (path: string, body: object) => request(http).post(path).send(body);
|
||||
|
||||
describe('companies', () => {
|
||||
it('creates, reads, updates and deletes a company', async () => {
|
||||
const created = await post('/api/companies', { name: 'Acme', website: 'https://acme.test', industry: 'Tools' }).expect(201);
|
||||
expect(created.body).toEqual({ id: 1, name: 'Acme', website: 'https://acme.test', industry: 'Tools' });
|
||||
await request(http).get('/api/companies/1').expect(200).expect(created.body);
|
||||
const updated = await request(http).put('/api/companies/1').send({ industry: 'Hardware' }).expect(200);
|
||||
expect(updated.body).toMatchObject({ id: 1, name: 'Acme', industry: 'Hardware' });
|
||||
await request(http).delete('/api/companies/1').expect(204);
|
||||
await request(http).get('/api/companies/1').expect(404);
|
||||
});
|
||||
|
||||
it('requires a name', async () => {
|
||||
await post('/api/companies', { website: 'x' }).expect(400);
|
||||
await post('/api/companies', { name: '' }).expect(400);
|
||||
await post('/api/companies', { name: 5 }).expect(400);
|
||||
});
|
||||
|
||||
it('answers 404 for an unknown id', async () => {
|
||||
await request(http).get('/api/companies/99').expect(404);
|
||||
await request(http).put('/api/companies/99').send({ name: 'x' }).expect(404);
|
||||
await request(http).delete('/api/companies/99').expect(404);
|
||||
});
|
||||
|
||||
it('searches by name, case-insensitively', async () => {
|
||||
await post('/api/companies', { name: 'Acme Corp' });
|
||||
await post('/api/companies', { name: 'Globex' });
|
||||
const res = await request(http).get('/api/companies?q=ACME').expect(200);
|
||||
expect(res.body.map((c: { name: string }) => c.name)).toEqual(['Acme Corp']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('contacts', () => {
|
||||
it('creates, updates and deletes a contact', async () => {
|
||||
await post('/api/companies', { name: 'Acme' });
|
||||
const created = await post('/api/contacts', { name: 'Ann', email: 'ann@acme.test', phone: '123', companyId: 1 }).expect(201);
|
||||
expect(created.body).toEqual({ id: 1, name: 'Ann', email: 'ann@acme.test', phone: '123', companyId: 1 });
|
||||
const updated = await request(http).put('/api/contacts/1').send({ phone: '999', companyId: null }).expect(200);
|
||||
expect(updated.body).toMatchObject({ phone: '999', companyId: null });
|
||||
await request(http).delete('/api/contacts/1').expect(204);
|
||||
await request(http).get('/api/contacts/1').expect(404);
|
||||
});
|
||||
|
||||
it('validates name, email and company reference', async () => {
|
||||
await post('/api/contacts', {}).expect(400);
|
||||
await post('/api/contacts', { name: 'Bob', email: 'not-an-email' }).expect(400);
|
||||
await post('/api/contacts', { name: 'Bob', companyId: 42 }).expect(400);
|
||||
});
|
||||
|
||||
it('searches by name or email', async () => {
|
||||
await post('/api/contacts', { name: 'Ann', email: 'ann@one.test' });
|
||||
await post('/api/contacts', { name: 'Bob', email: 'bob@two.test' });
|
||||
const byName = await request(http).get('/api/contacts?q=an').expect(200);
|
||||
expect(byName.body).toHaveLength(1);
|
||||
const byEmail = await request(http).get('/api/contacts?q=TWO.test').expect(200);
|
||||
expect(byEmail.body.map((c: { name: string }) => c.name)).toEqual(['Bob']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('deals', () => {
|
||||
it('applies defaults', async () => {
|
||||
const res = await post('/api/deals', { title: 'Renewal' }).expect(201);
|
||||
expect(res.body).toEqual({ id: 1, title: 'Renewal', amount: 0, stage: 'lead', companyId: null, contactId: null });
|
||||
});
|
||||
|
||||
it('rejects bad input', async () => {
|
||||
await post('/api/deals', {}).expect(400);
|
||||
await post('/api/deals', { title: 'x', amount: 'lots' }).expect(400);
|
||||
await post('/api/deals', { title: 'x', amount: -1 }).expect(400);
|
||||
await post('/api/deals', { title: 'x', stage: 'maybe' }).expect(400);
|
||||
await post('/api/deals', { title: 'x', contactId: 7 }).expect(400);
|
||||
});
|
||||
|
||||
it('moves a deal between stages and rejects an invalid stage', async () => {
|
||||
await post('/api/deals', { title: 'Renewal', amount: 100 });
|
||||
await request(http).put('/api/deals/1').send({ stage: 'proposal' }).expect(200).expect((r) => expect(r.body.stage).toBe('proposal'));
|
||||
await request(http).put('/api/deals/1').send({ stage: 'nope' }).expect(400);
|
||||
});
|
||||
|
||||
it('filters by stage and q', async () => {
|
||||
await post('/api/deals', { title: 'Alpha deal', stage: 'won' });
|
||||
await post('/api/deals', { title: 'Beta deal', stage: 'won' });
|
||||
await post('/api/deals', { title: 'Alpha two', stage: 'lost' });
|
||||
const won = await request(http).get('/api/deals?stage=won').expect(200);
|
||||
expect(won.body).toHaveLength(2);
|
||||
const both = await request(http).get('/api/deals?stage=won&q=alpha').expect(200);
|
||||
expect(both.body.map((d: { title: string }) => d.title)).toEqual(['Alpha deal']);
|
||||
await request(http).get('/api/deals?stage=bogus').expect(400);
|
||||
});
|
||||
|
||||
it('answers 404 for an unknown id', async () => {
|
||||
await request(http).get('/api/deals/5').expect(404);
|
||||
await request(http).delete('/api/deals/5').expect(404);
|
||||
});
|
||||
});
|
||||
|
||||
describe('pipeline and references', () => {
|
||||
it('reports count and amount for every stage', async () => {
|
||||
await post('/api/deals', { title: 'a', amount: 10, stage: 'won' });
|
||||
await post('/api/deals', { title: 'b', amount: 2.5, stage: 'won' });
|
||||
await post('/api/deals', { title: 'c' });
|
||||
const res = await request(http).get('/api/pipeline').expect(200);
|
||||
expect(res.body).toEqual({
|
||||
lead: { count: 1, amount: 0 },
|
||||
qualified: { count: 0, amount: 0 },
|
||||
proposal: { count: 0, amount: 0 },
|
||||
won: { count: 2, amount: 12.5 },
|
||||
lost: { count: 0, amount: 0 },
|
||||
});
|
||||
});
|
||||
|
||||
it('clears references when a company or a contact is deleted, without deleting deals', async () => {
|
||||
await post('/api/companies', { name: 'Acme' });
|
||||
await post('/api/contacts', { name: 'Ann', companyId: 1 });
|
||||
await post('/api/deals', { title: 'd', companyId: 1, contactId: 1 });
|
||||
await request(http).delete('/api/contacts/1').expect(204);
|
||||
await request(http).get('/api/deals/1').expect(200).expect((r) => expect(r.body).toMatchObject({ companyId: 1, contactId: null }));
|
||||
await request(http).delete('/api/companies/1').expect(204);
|
||||
await request(http).get('/api/deals/1').expect(200).expect((r) => expect(r.body).toMatchObject({ companyId: null, contactId: null }));
|
||||
});
|
||||
|
||||
it('nulls the company of a contact when the company is deleted', async () => {
|
||||
await post('/api/companies', { name: 'Acme' });
|
||||
await post('/api/contacts', { name: 'Ann', companyId: 1 });
|
||||
await request(http).delete('/api/companies/1').expect(204);
|
||||
await request(http).get('/api/contacts/1').expect(200).expect((r) => expect(r.body.companyId).toBeNull());
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
{
|
||||
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
|
||||
"version": 1,
|
||||
"cli": {
|
||||
"analytics": false
|
||||
},
|
||||
"newProjectRoot": "projects",
|
||||
"projects": {
|
||||
"frontend": {
|
||||
"projectType": "application",
|
||||
"schematics": {},
|
||||
"root": "",
|
||||
"sourceRoot": "src",
|
||||
"prefix": "app",
|
||||
"architect": {
|
||||
"build": {
|
||||
"builder": "@angular/build:application",
|
||||
"options": {
|
||||
"browser": "src/main.ts",
|
||||
"polyfills": ["zone.js"],
|
||||
"tsConfig": "tsconfig.app.json",
|
||||
"assets": [],
|
||||
"styles": ["src/styles.css"]
|
||||
},
|
||||
"configurations": {
|
||||
"production": {
|
||||
"budgets": [
|
||||
{ "type": "initial", "maximumWarning": "1MB", "maximumError": "2MB" }
|
||||
],
|
||||
"outputHashing": "all"
|
||||
},
|
||||
"development": {
|
||||
"optimization": false,
|
||||
"extractLicenses": false,
|
||||
"sourceMap": true
|
||||
}
|
||||
},
|
||||
"defaultConfiguration": "production"
|
||||
},
|
||||
"serve": {
|
||||
"builder": "@angular/build:dev-server",
|
||||
"options": {
|
||||
"proxyConfig": "proxy.conf.json"
|
||||
},
|
||||
"configurations": {
|
||||
"production": { "buildTarget": "frontend:build:production" },
|
||||
"development": { "buildTarget": "frontend:build:development" }
|
||||
},
|
||||
"defaultConfiguration": "development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"/api": {
|
||||
"target": "http://127.0.0.1:3000",
|
||||
"secure": false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { Injectable, inject } from '@angular/core';
|
||||
import { Observable } from 'rxjs';
|
||||
import { Company, Contact, Deal } from './models';
|
||||
|
||||
type Resource = 'companies' | 'contacts' | 'deals';
|
||||
|
||||
/** Thin typed wrapper over the REST API of the backend (the dev server proxies /api to it). */
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class ApiService {
|
||||
private readonly http = inject(HttpClient);
|
||||
|
||||
private list<T>(resource: Resource, q: string): Observable<T[]> {
|
||||
let params = new HttpParams();
|
||||
if (q.trim()) params = params.set('q', q.trim());
|
||||
return this.http.get<T[]>(`/api/${resource}`, { params });
|
||||
}
|
||||
|
||||
companies(q = ''): Observable<Company[]> {
|
||||
return this.list<Company>('companies', q);
|
||||
}
|
||||
saveCompany(id: number | null, body: Partial<Company>): Observable<Company> {
|
||||
return id === null ? this.http.post<Company>('/api/companies', body) : this.http.put<Company>(`/api/companies/${id}`, body);
|
||||
}
|
||||
deleteCompany(id: number): Observable<void> {
|
||||
return this.http.delete<void>(`/api/companies/${id}`);
|
||||
}
|
||||
|
||||
contacts(q = ''): Observable<Contact[]> {
|
||||
return this.list<Contact>('contacts', q);
|
||||
}
|
||||
saveContact(id: number | null, body: Partial<Contact>): Observable<Contact> {
|
||||
return id === null ? this.http.post<Contact>('/api/contacts', body) : this.http.put<Contact>(`/api/contacts/${id}`, body);
|
||||
}
|
||||
deleteContact(id: number): Observable<void> {
|
||||
return this.http.delete<void>(`/api/contacts/${id}`);
|
||||
}
|
||||
|
||||
deals(q = ''): Observable<Deal[]> {
|
||||
return this.list<Deal>('deals', q);
|
||||
}
|
||||
saveDeal(id: number | null, body: Partial<Deal>): Observable<Deal> {
|
||||
return id === null ? this.http.post<Deal>('/api/deals', body) : this.http.put<Deal>(`/api/deals/${id}`, body);
|
||||
}
|
||||
deleteDeal(id: number): Observable<void> {
|
||||
return this.http.delete<void>(`/api/deals/${id}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { ApplicationConfig, provideBrowserGlobalErrorListeners, provideZoneChangeDetection } from '@angular/core';
|
||||
import { provideRouter } from '@angular/router';
|
||||
|
||||
import { routes } from './app.routes';
|
||||
|
||||
export const appConfig: ApplicationConfig = {
|
||||
providers: [
|
||||
provideBrowserGlobalErrorListeners(),
|
||||
provideZoneChangeDetection({ eventCoalescing: true }),
|
||||
provideRouter(routes),
|
||||
provideHttpClient(),
|
||||
],
|
||||
};
|
||||
@@ -0,0 +1,7 @@
|
||||
<h1>CRM</h1>
|
||||
<nav>
|
||||
<a routerLink="/deals" routerLinkActive="active">Deals</a>
|
||||
<a routerLink="/companies" routerLinkActive="active">Companies</a>
|
||||
<a routerLink="/contacts" routerLinkActive="active">Contacts</a>
|
||||
</nav>
|
||||
<router-outlet />
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Routes } from '@angular/router';
|
||||
import { CompaniesComponent } from './companies/companies';
|
||||
import { ContactsComponent } from './contacts/contacts';
|
||||
import { DealsComponent } from './deals/deals';
|
||||
|
||||
export const routes: Routes = [
|
||||
{ path: '', pathMatch: 'full', redirectTo: 'deals' },
|
||||
{ path: 'companies', component: CompaniesComponent },
|
||||
{ path: 'contacts', component: ContactsComponent },
|
||||
{ path: 'deals', component: DealsComponent },
|
||||
{ path: '**', redirectTo: 'deals' },
|
||||
];
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Component } from '@angular/core';
|
||||
import { RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router';
|
||||
|
||||
@Component({
|
||||
selector: 'app-root',
|
||||
imports: [RouterOutlet, RouterLink, RouterLinkActive],
|
||||
templateUrl: './app.html',
|
||||
})
|
||||
export class App {}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { Component, OnInit, inject, signal } from '@angular/core';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { ApiService } from '../api.service';
|
||||
import { Company } from '../models';
|
||||
|
||||
@Component({
|
||||
selector: 'app-companies',
|
||||
imports: [FormsModule],
|
||||
template: `
|
||||
<h2>Companies</h2>
|
||||
<input type="search" name="search" placeholder="Search companies" [ngModel]="query()" (ngModelChange)="search($event)" />
|
||||
|
||||
<form (ngSubmit)="save()">
|
||||
<input name="name" placeholder="Name" [(ngModel)]="form.name" required />
|
||||
<input name="website" placeholder="Website" [(ngModel)]="form.website" />
|
||||
<input name="industry" placeholder="Industry" [(ngModel)]="form.industry" />
|
||||
<button type="submit">{{ editingId() === null ? 'Add company' : 'Save company' }}</button>
|
||||
@if (editingId() !== null) {
|
||||
<button type="button" (click)="cancel()">Cancel</button>
|
||||
}
|
||||
</form>
|
||||
@if (error()) {
|
||||
<p class="error">{{ error() }}</p>
|
||||
}
|
||||
|
||||
<table>
|
||||
<thead><tr><th>Name</th><th>Website</th><th>Industry</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
@for (company of companies(); track company.id) {
|
||||
<tr>
|
||||
<td>{{ company.name }}</td>
|
||||
<td>{{ company.website }}</td>
|
||||
<td>{{ company.industry }}</td>
|
||||
<td>
|
||||
<button type="button" (click)="edit(company)">Edit</button>
|
||||
<button type="button" (click)="remove(company)">Delete</button>
|
||||
</td>
|
||||
</tr>
|
||||
} @empty {
|
||||
<tr><td colspan="4">No companies</td></tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
`,
|
||||
})
|
||||
export class CompaniesComponent implements OnInit {
|
||||
private readonly api = inject(ApiService);
|
||||
|
||||
readonly companies = signal<Company[]>([]);
|
||||
readonly query = signal('');
|
||||
readonly error = signal('');
|
||||
readonly editingId = signal<number | null>(null);
|
||||
form = { name: '', website: '', industry: '' };
|
||||
|
||||
ngOnInit(): void {
|
||||
this.load();
|
||||
}
|
||||
|
||||
load(): void {
|
||||
this.api.companies(this.query()).subscribe({
|
||||
next: (list) => this.companies.set(list),
|
||||
error: (err: HttpErrorResponse) => this.fail(err),
|
||||
});
|
||||
}
|
||||
|
||||
search(q: string): void {
|
||||
this.query.set(q);
|
||||
this.load();
|
||||
}
|
||||
|
||||
save(): void {
|
||||
const body = { name: this.form.name, website: this.form.website || null, industry: this.form.industry || null };
|
||||
this.api.saveCompany(this.editingId(), body).subscribe({
|
||||
next: () => {
|
||||
this.cancel();
|
||||
this.load();
|
||||
},
|
||||
error: (err: HttpErrorResponse) => this.fail(err),
|
||||
});
|
||||
}
|
||||
|
||||
edit(company: Company): void {
|
||||
this.editingId.set(company.id);
|
||||
this.form = { name: company.name, website: company.website ?? '', industry: company.industry ?? '' };
|
||||
}
|
||||
|
||||
cancel(): void {
|
||||
this.editingId.set(null);
|
||||
this.form = { name: '', website: '', industry: '' };
|
||||
this.error.set('');
|
||||
}
|
||||
|
||||
remove(company: Company): void {
|
||||
this.api.deleteCompany(company.id).subscribe({
|
||||
next: () => this.load(),
|
||||
error: (err: HttpErrorResponse) => this.fail(err),
|
||||
});
|
||||
}
|
||||
|
||||
private fail(err: HttpErrorResponse): void {
|
||||
this.error.set(`Request failed (${err.status})`);
|
||||
}
|
||||
}
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { Component, OnInit, inject, signal } from '@angular/core';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { ApiService } from '../api.service';
|
||||
import { Company, Contact } from '../models';
|
||||
|
||||
interface ContactForm {
|
||||
name: string;
|
||||
email: string;
|
||||
phone: string;
|
||||
companyId: number | null;
|
||||
}
|
||||
|
||||
const EMPTY: ContactForm = { name: '', email: '', phone: '', companyId: null };
|
||||
|
||||
@Component({
|
||||
selector: 'app-contacts',
|
||||
imports: [FormsModule],
|
||||
template: `
|
||||
<h2>Contacts</h2>
|
||||
<input type="search" name="search" placeholder="Search contacts" [ngModel]="query()" (ngModelChange)="search($event)" />
|
||||
|
||||
<form (ngSubmit)="save()">
|
||||
<input name="name" placeholder="Name" [(ngModel)]="form.name" required />
|
||||
<input name="email" placeholder="Email" [(ngModel)]="form.email" />
|
||||
<input name="phone" placeholder="Phone" [(ngModel)]="form.phone" />
|
||||
<select name="companyId" [(ngModel)]="form.companyId">
|
||||
<option [ngValue]="null">No company</option>
|
||||
@for (company of companies(); track company.id) {
|
||||
<option [ngValue]="company.id">{{ company.name }}</option>
|
||||
}
|
||||
</select>
|
||||
<button type="submit">{{ editingId() === null ? 'Add contact' : 'Save contact' }}</button>
|
||||
@if (editingId() !== null) {
|
||||
<button type="button" (click)="cancel()">Cancel</button>
|
||||
}
|
||||
</form>
|
||||
@if (error()) {
|
||||
<p class="error">{{ error() }}</p>
|
||||
}
|
||||
|
||||
<table>
|
||||
<thead><tr><th>Name</th><th>Email</th><th>Phone</th><th>Company</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
@for (contact of contacts(); track contact.id) {
|
||||
<tr>
|
||||
<td>{{ contact.name }}</td>
|
||||
<td>{{ contact.email }}</td>
|
||||
<td>{{ contact.phone }}</td>
|
||||
<td>{{ companyName(contact.companyId) }}</td>
|
||||
<td>
|
||||
<button type="button" (click)="edit(contact)">Edit</button>
|
||||
<button type="button" (click)="remove(contact)">Delete</button>
|
||||
</td>
|
||||
</tr>
|
||||
} @empty {
|
||||
<tr><td colspan="5">No contacts</td></tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
`,
|
||||
})
|
||||
export class ContactsComponent implements OnInit {
|
||||
private readonly api = inject(ApiService);
|
||||
|
||||
readonly contacts = signal<Contact[]>([]);
|
||||
readonly companies = signal<Company[]>([]);
|
||||
readonly query = signal('');
|
||||
readonly error = signal('');
|
||||
readonly editingId = signal<number | null>(null);
|
||||
form: ContactForm = { ...EMPTY };
|
||||
|
||||
ngOnInit(): void {
|
||||
this.api.companies().subscribe({ next: (list) => this.companies.set(list), error: (err: HttpErrorResponse) => this.fail(err) });
|
||||
this.load();
|
||||
}
|
||||
|
||||
load(): void {
|
||||
this.api.contacts(this.query()).subscribe({
|
||||
next: (list) => this.contacts.set(list),
|
||||
error: (err: HttpErrorResponse) => this.fail(err),
|
||||
});
|
||||
}
|
||||
|
||||
search(q: string): void {
|
||||
this.query.set(q);
|
||||
this.load();
|
||||
}
|
||||
|
||||
companyName(id: number | null): string {
|
||||
return this.companies().find((c) => c.id === id)?.name ?? '';
|
||||
}
|
||||
|
||||
save(): void {
|
||||
const body = { name: this.form.name, email: this.form.email || null, phone: this.form.phone || null, companyId: this.form.companyId };
|
||||
this.api.saveContact(this.editingId(), body).subscribe({
|
||||
next: () => {
|
||||
this.cancel();
|
||||
this.load();
|
||||
},
|
||||
error: (err: HttpErrorResponse) => this.fail(err),
|
||||
});
|
||||
}
|
||||
|
||||
edit(contact: Contact): void {
|
||||
this.editingId.set(contact.id);
|
||||
this.form = { name: contact.name, email: contact.email ?? '', phone: contact.phone ?? '', companyId: contact.companyId };
|
||||
}
|
||||
|
||||
cancel(): void {
|
||||
this.editingId.set(null);
|
||||
this.form = { ...EMPTY };
|
||||
this.error.set('');
|
||||
}
|
||||
|
||||
remove(contact: Contact): void {
|
||||
this.api.deleteContact(contact.id).subscribe({
|
||||
next: () => this.load(),
|
||||
error: (err: HttpErrorResponse) => this.fail(err),
|
||||
});
|
||||
}
|
||||
|
||||
private fail(err: HttpErrorResponse): void {
|
||||
this.error.set(`Request failed (${err.status})`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { Component, OnInit, computed, inject, signal } from '@angular/core';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { ApiService } from '../api.service';
|
||||
import { Company, Contact, Deal, STAGES, Stage } from '../models';
|
||||
|
||||
interface DealForm {
|
||||
title: string;
|
||||
amount: number;
|
||||
stage: Stage;
|
||||
companyId: number | null;
|
||||
contactId: number | null;
|
||||
}
|
||||
|
||||
const EMPTY: DealForm = { title: '', amount: 0, stage: 'lead', companyId: null, contactId: null };
|
||||
|
||||
@Component({
|
||||
selector: 'app-deals',
|
||||
imports: [FormsModule],
|
||||
template: `
|
||||
<h2>Deals</h2>
|
||||
<input type="search" name="search" placeholder="Search deals" [ngModel]="query()" (ngModelChange)="search($event)" />
|
||||
|
||||
<form (ngSubmit)="save()">
|
||||
<input name="title" placeholder="Title" [(ngModel)]="form.title" required />
|
||||
<input name="amount" type="number" min="0" placeholder="Amount" [(ngModel)]="form.amount" />
|
||||
<select name="stage" [(ngModel)]="form.stage">
|
||||
@for (stage of stages; track stage) {
|
||||
<option [ngValue]="stage">{{ stage }}</option>
|
||||
}
|
||||
</select>
|
||||
<select name="companyId" [(ngModel)]="form.companyId">
|
||||
<option [ngValue]="null">No company</option>
|
||||
@for (company of companies(); track company.id) {
|
||||
<option [ngValue]="company.id">{{ company.name }}</option>
|
||||
}
|
||||
</select>
|
||||
<select name="contactId" [(ngModel)]="form.contactId">
|
||||
<option [ngValue]="null">No contact</option>
|
||||
@for (contact of contacts(); track contact.id) {
|
||||
<option [ngValue]="contact.id">{{ contact.name }}</option>
|
||||
}
|
||||
</select>
|
||||
<button type="submit">{{ editingId() === null ? 'Add deal' : 'Save deal' }}</button>
|
||||
@if (editingId() !== null) {
|
||||
<button type="button" (click)="cancel()">Cancel</button>
|
||||
}
|
||||
</form>
|
||||
@if (error()) {
|
||||
<p class="error">{{ error() }}</p>
|
||||
}
|
||||
|
||||
<div class="board">
|
||||
@for (stage of stages; track stage) {
|
||||
<section class="column" [attr.data-stage]="stage">
|
||||
<h3>{{ stage }} ({{ byStage()[stage].length }})</h3>
|
||||
@for (deal of byStage()[stage]; track deal.id) {
|
||||
<article class="card">
|
||||
<strong>{{ deal.title }}</strong>
|
||||
<span>{{ deal.amount }}</span>
|
||||
<select [ngModel]="deal.stage" [name]="'move-' + deal.id" (ngModelChange)="move(deal, $event)">
|
||||
@for (target of stages; track target) {
|
||||
<option [ngValue]="target">{{ target }}</option>
|
||||
}
|
||||
</select>
|
||||
<button type="button" (click)="edit(deal)">Edit</button>
|
||||
<button type="button" (click)="remove(deal)">Delete</button>
|
||||
</article>
|
||||
}
|
||||
</section>
|
||||
}
|
||||
</div>
|
||||
`,
|
||||
})
|
||||
export class DealsComponent implements OnInit {
|
||||
private readonly api = inject(ApiService);
|
||||
|
||||
readonly stages = STAGES;
|
||||
readonly deals = signal<Deal[]>([]);
|
||||
readonly companies = signal<Company[]>([]);
|
||||
readonly contacts = signal<Contact[]>([]);
|
||||
readonly query = signal('');
|
||||
readonly error = signal('');
|
||||
readonly editingId = signal<number | null>(null);
|
||||
form: DealForm = { ...EMPTY };
|
||||
|
||||
readonly byStage = computed(() => {
|
||||
const groups: Record<Stage, Deal[]> = { lead: [], qualified: [], proposal: [], won: [], lost: [] };
|
||||
for (const deal of this.deals()) groups[deal.stage].push(deal);
|
||||
return groups;
|
||||
});
|
||||
|
||||
ngOnInit(): void {
|
||||
this.api.companies().subscribe({ next: (list) => this.companies.set(list), error: (err: HttpErrorResponse) => this.fail(err) });
|
||||
this.api.contacts().subscribe({ next: (list) => this.contacts.set(list), error: (err: HttpErrorResponse) => this.fail(err) });
|
||||
this.load();
|
||||
}
|
||||
|
||||
load(): void {
|
||||
this.api.deals(this.query()).subscribe({
|
||||
next: (list) => this.deals.set(list),
|
||||
error: (err: HttpErrorResponse) => this.fail(err),
|
||||
});
|
||||
}
|
||||
|
||||
search(q: string): void {
|
||||
this.query.set(q);
|
||||
this.load();
|
||||
}
|
||||
|
||||
move(deal: Deal, stage: Stage): void {
|
||||
this.api.saveDeal(deal.id, { stage }).subscribe({
|
||||
next: () => this.load(),
|
||||
error: (err: HttpErrorResponse) => this.fail(err),
|
||||
});
|
||||
}
|
||||
|
||||
save(): void {
|
||||
this.api.saveDeal(this.editingId(), { ...this.form, amount: Number(this.form.amount) || 0 }).subscribe({
|
||||
next: () => {
|
||||
this.cancel();
|
||||
this.load();
|
||||
},
|
||||
error: (err: HttpErrorResponse) => this.fail(err),
|
||||
});
|
||||
}
|
||||
|
||||
edit(deal: Deal): void {
|
||||
this.editingId.set(deal.id);
|
||||
this.form = { title: deal.title, amount: deal.amount, stage: deal.stage, companyId: deal.companyId, contactId: deal.contactId };
|
||||
}
|
||||
|
||||
cancel(): void {
|
||||
this.editingId.set(null);
|
||||
this.form = { ...EMPTY };
|
||||
this.error.set('');
|
||||
}
|
||||
|
||||
remove(deal: Deal): void {
|
||||
this.api.deleteDeal(deal.id).subscribe({
|
||||
next: () => this.load(),
|
||||
error: (err: HttpErrorResponse) => this.fail(err),
|
||||
});
|
||||
}
|
||||
|
||||
private fail(err: HttpErrorResponse): void {
|
||||
this.error.set(`Request failed (${err.status})`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
export const STAGES = ['lead', 'qualified', 'proposal', 'won', 'lost'] as const;
|
||||
export type Stage = (typeof STAGES)[number];
|
||||
|
||||
export interface Company {
|
||||
id: number;
|
||||
name: string;
|
||||
website: string | null;
|
||||
industry: string | null;
|
||||
}
|
||||
|
||||
export interface Contact {
|
||||
id: number;
|
||||
name: string;
|
||||
email: string | null;
|
||||
phone: string | null;
|
||||
companyId: number | null;
|
||||
}
|
||||
|
||||
export interface Deal {
|
||||
id: number;
|
||||
title: string;
|
||||
amount: number;
|
||||
stage: Stage;
|
||||
companyId: number | null;
|
||||
contactId: number | null;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
# CRM
|
||||
|
||||
`backend/` is a NestJS application, `frontend/` is an Angular application. Dependencies are already installed in each `node_modules`.
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/nest-cli",
|
||||
"collection": "@nestjs/schematics",
|
||||
"sourceRoot": "src",
|
||||
"compilerOptions": {
|
||||
"deleteOutDir": true
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,48 @@
|
||||
{
|
||||
"name": "backend",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"license": "UNLICENSED",
|
||||
"scripts": {
|
||||
"build": "nest build",
|
||||
"start": "nest start",
|
||||
"start:prod": "node dist/main.js",
|
||||
"test": "jest",
|
||||
"test:e2e": "jest --config ./test/jest-e2e.json"
|
||||
},
|
||||
"jest": {
|
||||
"moduleFileExtensions": [
|
||||
"js",
|
||||
"json",
|
||||
"ts"
|
||||
],
|
||||
"rootDir": "src",
|
||||
"testRegex": ".*\\.spec\\.ts$",
|
||||
"transform": {
|
||||
"^.+\\.(t|j)s$": "ts-jest"
|
||||
},
|
||||
"testEnvironment": "node"
|
||||
},
|
||||
"dependencies": {
|
||||
"@nestjs/common": "11.2.8",
|
||||
"@nestjs/core": "11.2.8",
|
||||
"@nestjs/platform-express": "11.2.8",
|
||||
"class-transformer": "0.5.1",
|
||||
"class-validator": "0.15.1",
|
||||
"reflect-metadata": "0.2.2",
|
||||
"rxjs": "7.8.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@nestjs/cli": "11.0.24",
|
||||
"@nestjs/schematics": "11.1.0",
|
||||
"@nestjs/testing": "11.2.8",
|
||||
"@types/express": "5.0.6",
|
||||
"@types/jest": "29.5.14",
|
||||
"@types/node": "22.20.5",
|
||||
"@types/supertest": "6.0.3",
|
||||
"jest": "29.7.0",
|
||||
"supertest": "7.3.1",
|
||||
"ts-jest": "29.4.15",
|
||||
"typescript": "5.9.3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
|
||||
@Module({})
|
||||
export class AppModule {}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { AppModule } from './app.module';
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule);
|
||||
await app.listen(3000);
|
||||
}
|
||||
bootstrap();
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"moduleFileExtensions": ["js", "json", "ts"],
|
||||
"rootDir": ".",
|
||||
"testEnvironment": "node",
|
||||
"testRegex": ".e2e-spec.ts$",
|
||||
"transform": { "^.+\\.(t|j)s$": "ts-jest" }
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"declaration": true,
|
||||
"removeComments": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
"experimentalDecorators": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"esModuleInterop": true,
|
||||
"target": "ES2022",
|
||||
"sourceMap": true,
|
||||
"outDir": "./dist",
|
||||
"baseUrl": "./",
|
||||
"skipLibCheck": true,
|
||||
"strictNullChecks": true,
|
||||
"noImplicitAny": true,
|
||||
"forceConsistentCasingInFileNames": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
{
|
||||
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
|
||||
"version": 1,
|
||||
"cli": {
|
||||
"analytics": false
|
||||
},
|
||||
"newProjectRoot": "projects",
|
||||
"projects": {
|
||||
"frontend": {
|
||||
"projectType": "application",
|
||||
"schematics": {},
|
||||
"root": "",
|
||||
"sourceRoot": "src",
|
||||
"prefix": "app",
|
||||
"architect": {
|
||||
"build": {
|
||||
"builder": "@angular/build:application",
|
||||
"options": {
|
||||
"browser": "src/main.ts",
|
||||
"polyfills": ["zone.js"],
|
||||
"tsConfig": "tsconfig.app.json",
|
||||
"assets": [],
|
||||
"styles": ["src/styles.css"]
|
||||
},
|
||||
"configurations": {
|
||||
"production": {
|
||||
"budgets": [
|
||||
{ "type": "initial", "maximumWarning": "1MB", "maximumError": "2MB" }
|
||||
],
|
||||
"outputHashing": "all"
|
||||
},
|
||||
"development": {
|
||||
"optimization": false,
|
||||
"extractLicenses": false,
|
||||
"sourceMap": true
|
||||
}
|
||||
},
|
||||
"defaultConfiguration": "production"
|
||||
},
|
||||
"serve": {
|
||||
"builder": "@angular/build:dev-server",
|
||||
"configurations": {
|
||||
"production": { "buildTarget": "frontend:build:production" },
|
||||
"development": { "buildTarget": "frontend:build:development" }
|
||||
},
|
||||
"defaultConfiguration": "development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"ng": "ng",
|
||||
"start": "ng serve",
|
||||
"build": "ng build"
|
||||
},
|
||||
"dependencies": {
|
||||
"@angular/common": "20.3.35",
|
||||
"@angular/compiler": "20.3.35",
|
||||
"@angular/core": "20.3.35",
|
||||
"@angular/forms": "20.3.35",
|
||||
"@angular/platform-browser": "20.3.35",
|
||||
"@angular/router": "20.3.35",
|
||||
"rxjs": "7.8.2",
|
||||
"tslib": "2.8.1",
|
||||
"zone.js": "0.15.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@angular/build": "20.3.42",
|
||||
"@angular/cli": "20.3.42",
|
||||
"@angular/compiler-cli": "20.3.35",
|
||||
"typescript": "5.9.3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { ApplicationConfig, provideBrowserGlobalErrorListeners, provideZoneChangeDetection } from '@angular/core';
|
||||
import { provideRouter } from '@angular/router';
|
||||
|
||||
import { routes } from './app.routes';
|
||||
|
||||
export const appConfig: ApplicationConfig = {
|
||||
providers: [
|
||||
provideBrowserGlobalErrorListeners(),
|
||||
provideZoneChangeDetection({ eventCoalescing: true }),
|
||||
provideRouter(routes),
|
||||
],
|
||||
};
|
||||
@@ -0,0 +1,2 @@
|
||||
<h1>CRM</h1>
|
||||
<router-outlet />
|
||||
@@ -0,0 +1,3 @@
|
||||
import { Routes } from '@angular/router';
|
||||
|
||||
export const routes: Routes = [];
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Component } from '@angular/core';
|
||||
import { RouterOutlet } from '@angular/router';
|
||||
|
||||
@Component({
|
||||
selector: 'app-root',
|
||||
imports: [RouterOutlet],
|
||||
templateUrl: './app.html',
|
||||
})
|
||||
export class App {}
|
||||
@@ -0,0 +1,12 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>CRM</title>
|
||||
<base href="/">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
</head>
|
||||
<body>
|
||||
<app-root></app-root>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,5 @@
|
||||
import { bootstrapApplication } from '@angular/platform-browser';
|
||||
import { appConfig } from './app/app.config';
|
||||
import { App } from './app/app';
|
||||
|
||||
bootstrapApplication(App, appConfig).catch((err) => console.error(err));
|
||||
@@ -0,0 +1 @@
|
||||
/* global styles */
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "./out-tsc/app",
|
||||
"types": []
|
||||
},
|
||||
"include": ["src/**/*.ts"],
|
||||
"exclude": ["src/**/*.spec.ts"]
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"compileOnSave": false,
|
||||
"compilerOptions": {
|
||||
"strict": true,
|
||||
"noImplicitOverride": true,
|
||||
"noPropertyAccessFromIndexSignature": true,
|
||||
"noImplicitReturns": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"skipLibCheck": true,
|
||||
"isolatedModules": true,
|
||||
"experimentalDecorators": true,
|
||||
"importHelpers": true,
|
||||
"target": "ES2022",
|
||||
"module": "preserve"
|
||||
},
|
||||
"angularCompilerOptions": {
|
||||
"enableI18nLegacyMessageIdFormat": false,
|
||||
"strictInjectionParameters": true,
|
||||
"strictInputAccessModifiers": true,
|
||||
"strictTemplates": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
id: nestng-crm
|
||||
title: Simple NestJS + Angular CRM
|
||||
kind: create
|
||||
expected_rounds: 30-70
|
||||
---
|
||||
# Simple NestJS + Angular CRM
|
||||
|
||||
Task for the vanilla Strata vs Leleka comparison with the real Codex CLI (written 2026-11-05). Single phase, two projects in one workspace.
|
||||
The seed is two freshly scaffolded projects (a Nest module with no controllers, an Angular 20 standalone app with an empty router) with exact-pinned
|
||||
`package.json` and `package-lock.json` files; `node_modules` is NOT part of the seed: the runner installs both trees once from the lockfiles (`NOTES.md`)
|
||||
and hard-links them into every workspace, because the agent has no network. Node.js 22 must be on the PATH of the Codex shell. No browser, no Karma.
|
||||
Acceptance (`accept.py`, 56 checks, 20-120 s): black-box REST checks over HTTP against `node dist/main.js`, the agent's own jest tests (>= 15 cases),
|
||||
the production `ng build`, static checks of the Angular sources. A browser check of the UI is NOT part of the acceptance (the server has no browser).
|
||||
|
||||
## Prompt
|
||||
<!-- PROMPT BEGIN -->
|
||||
Build a small CRM web application in the current directory. It has two parts that are already scaffolded here: a NestJS REST API in `backend/` and an Angular single-page app in `frontend/`. Both already have their package.json, tsconfig files and installed dependencies (`backend/node_modules`, `frontend/node_modules`). There is NO network and NO browser: you cannot install packages, so do not change the dependencies and use only what is installed (NestJS 11: @nestjs/common, core, platform-express, testing; class-validator, class-transformer; jest, ts-jest, supertest; Angular 20: common, core, forms, router, platform-browser with the esbuild application builder). Node.js 22 and npm are on the PATH.
|
||||
|
||||
Backend (`backend/`, TypeScript, NestJS, in-memory storage, no database):
|
||||
- Fixed commands: `npm run build` compiles to `dist/`; `node dist/main.js` starts the server on the port in the environment variable PORT (default 3000), bound to 127.0.0.1. Every route is under the `/api` prefix and speaks JSON.
|
||||
- Resources and fields: companies {id, name (required), website, industry}; contacts {id, name (required), email, phone, companyId}; deals {id, title (required), amount, stage, companyId, contactId}. Optional fields that were not given are returned as null. A deal's amount is a number >= 0 (default 0); its stage is exactly one of lead, qualified, proposal, won, lost (default lead). companyId and contactId are optional integers or null.
|
||||
- For each of /api/companies, /api/contacts, /api/deals: GET lists all records (a JSON array); POST creates a record and answers 201 with it, including an integer id (1, 2, 3, ..., never reused); GET /api/<resource>/:id returns one record; PUT /api/<resource>/:id updates the fields that are present in the body and answers 200 with the updated record (null clears companyId or contactId); DELETE /api/<resource>/:id answers 204. An unknown id gives 404 for GET, PUT and DELETE.
|
||||
- Validation, answered with 400 on POST and on PUT for the fields given: name or title missing, empty or not a string; amount not a number or negative; stage not one of the five values; email that is not a valid email address; companyId or contactId that is not an integer or that refers to a record that does not exist.
|
||||
- Search: GET /api/companies?q=text filters by name; GET /api/contacts?q=text by name or email; GET /api/deals?q=text by title. All are case-insensitive substring matches. GET /api/deals?stage=won filters by stage and combines with q; an invalid stage in the query is 400.
|
||||
- GET /api/pipeline returns {"lead": {"count": n, "amount": total}, "qualified": {...}, "proposal": {...}, "won": {...}, "lost": {...}}, all five stages always present, summing the deals of each stage.
|
||||
- Deleting a company must not delete anything else: it sets companyId to null on its contacts and deals. Deleting a contact sets contactId to null on its deals.
|
||||
- Tests: `npm test` runs jest unit tests (src/**/*.spec.ts) and `npm run test:e2e` runs end-to-end tests with supertest (test/*.e2e-spec.ts; the config is already there). Both must run offline and pass, and together they must cover every endpoint and the validation rules.
|
||||
|
||||
Frontend (`frontend/`, Angular 20, standalone components, TypeScript strict mode as scaffolded):
|
||||
- `npm run build` (the production build) must succeed without errors. There are no frontend tests.
|
||||
- `frontend/proxy.conf.json` proxies `/api` to http://127.0.0.1:3000 and `npm start` (ng serve) uses it.
|
||||
- Use the Angular Router with the routes /companies, /contacts and /deals (the empty path redirects to /deals) and a navigation bar linking to them. The app talks to the API with HttpClient at /api/....
|
||||
- Each of the companies, contacts and deals pages lists its records, has a search box that filters the list through the ?q= parameter, a form to create a record, a way to edit a record and a delete button. Contact and deal forms let the user pick the company (and the deal form the contact) from the existing records.
|
||||
- The deals page is a board with one column per stage (lead, qualified, proposal, won, lost) showing the deals of that stage, and each deal can be moved to another stage from the board (a select or buttons that send a PUT).
|
||||
|
||||
Work step by step. Verify your work before finishing: run both test commands, start the server and exercise it with curl or a small Node script, and run `npm run build` in both projects. Write a short README.md at the top level that says how to run everything. When all of this works, reply with a short summary of what you built and how you verified it.
|
||||
<!-- PROMPT END -->
|
||||
Reference in New Issue
Block a user