Compare commits
32 Commits
33e449f520
...
df62e13627
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
df62e13627
|
||
|
|
8224183679
|
||
|
|
a6e455311e
|
||
|
|
93811eda10
|
||
|
|
46dd2256f5
|
||
|
|
1256c7510f
|
||
|
|
3310f7fa22
|
||
|
|
5e95e35d26
|
||
|
|
8fc7c33cff
|
||
|
|
bd772087c4
|
||
|
|
18a377aea2
|
||
|
|
43e10b8c06
|
||
|
|
fe82362afa
|
||
|
|
1903e41088
|
||
|
|
9f7703c76f
|
||
|
|
04eb21a7d3
|
||
|
|
56e3f5f973
|
||
|
|
d65411b0d7
|
||
|
|
ea875e9193
|
||
|
|
fabf98790c
|
||
|
|
d081961341
|
||
|
|
44ecf98da6
|
||
|
|
594b170826
|
||
|
|
1a6f956fb8
|
||
|
|
2328ecca6a
|
||
|
|
2a3b25526f
|
||
|
|
8d82245c86
|
||
|
|
37c0970102
|
||
|
|
dd6fc394ea
|
||
|
|
bfd1c4986f
|
||
|
|
7f6f458949
|
||
|
|
caf6ca4008
|
1
.gitignore
vendored
1
.gitignore
vendored
@@ -71,3 +71,4 @@ docs/data-exports/
|
||||
|
||||
# Python cache
|
||||
__pycache__/
|
||||
docs/Team_Device Loader.xlsx
|
||||
|
||||
211
.gitlab-ci.yml
211
.gitlab-ci.yml
@@ -1,44 +1,20 @@
|
||||
# =============================================================================
|
||||
# GitLab CI/CD Pipeline — STEAM Security Dashboard
|
||||
# =============================================================================
|
||||
#
|
||||
# Pipeline stages:
|
||||
# 1. install — install dependencies for backend and frontend
|
||||
# 2. lint — run linters / static checks
|
||||
# 3. test — run backend (Jest) and frontend (react-scripts) tests
|
||||
# 4. build — produce the production frontend bundle
|
||||
# 5. deploy — deploy to staging (local) or production (SSH to 71.85.90.6)
|
||||
# 6. verify — post-deploy health checks
|
||||
#
|
||||
# Environments:
|
||||
# staging — dashboard-dev:3100 (auto-deploy on main/master)
|
||||
# production — 71.85.90.6:3001 (manual trigger, requires staging verification)
|
||||
#
|
||||
# Executor: shell (runs on dashboard-dev using system Node.js)
|
||||
# Executor: Docker (LXC 108 — 71.85.90.8)
|
||||
# Build/test jobs run in node:18 containers.
|
||||
# Deploy jobs run in alpine with SSH/rsync, targeting staging (71.85.90.9)
|
||||
# and production (71.85.90.6) via SSH.
|
||||
# =============================================================================
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Variables
|
||||
# ---------------------------------------------------------------------------
|
||||
variables:
|
||||
PROD_HOST: "71.85.90.6"
|
||||
PROD_USER: "root"
|
||||
PROD_DIR: "/home/cve-dashboard"
|
||||
STAGING_HOST: "71.85.90.9"
|
||||
STAGING_USER: "root"
|
||||
STAGING_DIR: "/home/cve-dashboard-staging"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Global cache — persists node_modules between pipeline runs
|
||||
# ---------------------------------------------------------------------------
|
||||
cache:
|
||||
key: ${CI_COMMIT_REF_SLUG}
|
||||
paths:
|
||||
- node_modules/
|
||||
- frontend/node_modules/
|
||||
policy: pull
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Stages
|
||||
# ---------------------------------------------------------------------------
|
||||
stages:
|
||||
- install
|
||||
- lint
|
||||
@@ -48,44 +24,45 @@ stages:
|
||||
- verify
|
||||
|
||||
# =============================================================================
|
||||
# STAGE 1: Install dependencies
|
||||
# STAGE 1: Install
|
||||
# =============================================================================
|
||||
|
||||
install-backend:
|
||||
stage: install
|
||||
image: node:18
|
||||
script:
|
||||
- npm ci --prefer-offline
|
||||
- npm ci
|
||||
cache:
|
||||
key: ${CI_COMMIT_REF_SLUG}
|
||||
key: backend-${CI_COMMIT_REF_SLUG}
|
||||
paths:
|
||||
- node_modules/
|
||||
policy: pull-push
|
||||
policy: push
|
||||
|
||||
install-frontend:
|
||||
stage: install
|
||||
image: node:18
|
||||
script:
|
||||
- cd frontend && npm ci --prefer-offline
|
||||
- cd frontend && npm ci
|
||||
cache:
|
||||
key: ${CI_COMMIT_REF_SLUG}
|
||||
key: frontend-${CI_COMMIT_REF_SLUG}
|
||||
paths:
|
||||
- frontend/node_modules/
|
||||
policy: pull-push
|
||||
policy: push
|
||||
|
||||
# =============================================================================
|
||||
# STAGE 2: Lint / static analysis
|
||||
# STAGE 2: Lint
|
||||
# =============================================================================
|
||||
|
||||
lint-frontend:
|
||||
stage: lint
|
||||
script:
|
||||
- cd frontend && npm ci --prefer-offline && npx eslint src/ --ignore-pattern '**/__tests__/**' --ignore-pattern '**/*.test.js' --max-warnings 10
|
||||
needs:
|
||||
- install-frontend
|
||||
|
||||
lint-backend:
|
||||
stage: lint
|
||||
image: node:18
|
||||
cache:
|
||||
key: backend-${CI_COMMIT_REF_SLUG}
|
||||
paths:
|
||||
- node_modules/
|
||||
policy: pull
|
||||
script:
|
||||
- npm ci --prefer-offline
|
||||
- test -d node_modules || npm ci
|
||||
- node -c backend/server.js
|
||||
- node -c backend/routes/*.js
|
||||
- node -c backend/helpers/*.js
|
||||
@@ -93,14 +70,35 @@ lint-backend:
|
||||
needs:
|
||||
- install-backend
|
||||
|
||||
lint-frontend:
|
||||
stage: lint
|
||||
image: node:18
|
||||
cache:
|
||||
key: frontend-${CI_COMMIT_REF_SLUG}
|
||||
paths:
|
||||
- frontend/node_modules/
|
||||
policy: pull
|
||||
script:
|
||||
- cd frontend && (test -d node_modules || npm ci) && npx eslint src/ --ignore-pattern '**/__tests__/**' --ignore-pattern '**/*.test.js' --max-warnings 25
|
||||
needs:
|
||||
- install-frontend
|
||||
|
||||
# =============================================================================
|
||||
# STAGE 3: Tests
|
||||
# STAGE 3: Test
|
||||
# =============================================================================
|
||||
|
||||
test-backend:
|
||||
stage: test
|
||||
image: node:18
|
||||
variables:
|
||||
DATABASE_URL: $DATABASE_URL
|
||||
cache:
|
||||
key: backend-${CI_COMMIT_REF_SLUG}
|
||||
paths:
|
||||
- node_modules/
|
||||
policy: pull
|
||||
script:
|
||||
- npm ci --prefer-offline
|
||||
- test -d node_modules || npm ci
|
||||
- ./node_modules/.bin/jest --ci --forceExit backend/__tests__/
|
||||
timeout: 5 minutes
|
||||
needs:
|
||||
@@ -108,9 +106,18 @@ test-backend:
|
||||
|
||||
test-frontend:
|
||||
stage: test
|
||||
image: node:18
|
||||
cache:
|
||||
- key: frontend-${CI_COMMIT_REF_SLUG}
|
||||
paths:
|
||||
- frontend/node_modules/
|
||||
policy: pull
|
||||
- key: backend-${CI_COMMIT_REF_SLUG}
|
||||
paths:
|
||||
- node_modules/
|
||||
policy: pull
|
||||
script:
|
||||
- npm ci --prefer-offline
|
||||
- cd frontend && npm ci --prefer-offline && CI=true npx react-scripts test --watchAll=false --ci
|
||||
- cd frontend && (test -d node_modules || npm ci) && cd .. && (test -d node_modules || npm ci) && cd frontend && CI=true npx react-scripts test --watchAll=false --ci
|
||||
timeout: 5 minutes
|
||||
needs:
|
||||
- install-frontend
|
||||
@@ -121,8 +128,14 @@ test-frontend:
|
||||
|
||||
build-frontend:
|
||||
stage: build
|
||||
image: node:18
|
||||
cache:
|
||||
key: frontend-${CI_COMMIT_REF_SLUG}
|
||||
paths:
|
||||
- frontend/node_modules/
|
||||
policy: pull
|
||||
script:
|
||||
- cd frontend && npm ci --prefer-offline && CI=false REACT_APP_API_BASE=/api REACT_APP_API_HOST="" npm run build
|
||||
- cd frontend && (test -d node_modules || npm ci) && CI=false REACT_APP_API_BASE=/api REACT_APP_API_HOST="" npm run build
|
||||
artifacts:
|
||||
paths:
|
||||
- frontend/build/
|
||||
@@ -132,26 +145,30 @@ build-frontend:
|
||||
- lint-frontend
|
||||
|
||||
# =============================================================================
|
||||
# STAGE 5: Deploy
|
||||
# STAGE 5: Deploy (SSH from container)
|
||||
# =============================================================================
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Staging — auto-deploys on main/master to dashboard-dev:3100
|
||||
# ---------------------------------------------------------------------------
|
||||
.deploy-base: &deploy-base
|
||||
image: alpine:latest
|
||||
before_script:
|
||||
- apk add --no-cache openssh-client rsync
|
||||
- mkdir -p ~/.ssh
|
||||
- echo "$SSH_PRIVATE_KEY" | base64 -d > ~/.ssh/id_ed25519
|
||||
- chmod 600 ~/.ssh/id_ed25519
|
||||
- echo -e "Host *\n StrictHostKeyChecking no\n UserKnownHostsFile /dev/null" > ~/.ssh/config
|
||||
|
||||
deploy-staging:
|
||||
<<: *deploy-base
|
||||
stage: deploy
|
||||
rules:
|
||||
- if: $CI_COMMIT_BRANCH == "main" || $CI_COMMIT_BRANCH == "master"
|
||||
when: on_success
|
||||
environment:
|
||||
name: staging
|
||||
url: http://localhost:3100
|
||||
url: http://71.85.90.9:3100
|
||||
script:
|
||||
- echo "Deploying to staging (dashboard-dev:3100)..."
|
||||
# Ensure staging directory exists
|
||||
- mkdir -p ${STAGING_DIR}
|
||||
# Sync code (exclude .git, node_modules, uploads, logs)
|
||||
- rsync -a --delete
|
||||
- echo "Deploying to staging (${STAGING_HOST})..."
|
||||
- rsync -az --delete
|
||||
--exclude='.git'
|
||||
--exclude='node_modules'
|
||||
--exclude='frontend/node_modules'
|
||||
@@ -160,26 +177,16 @@ deploy-staging:
|
||||
--exclude='*.log'
|
||||
--exclude='*.db'
|
||||
--exclude='.env'
|
||||
${CI_PROJECT_DIR}/ ${STAGING_DIR}/
|
||||
# Copy built frontend
|
||||
- cp -r ${CI_PROJECT_DIR}/frontend/build ${STAGING_DIR}/frontend/build
|
||||
# Install deps in staging
|
||||
- cd ${STAGING_DIR} && npm ci --prefer-offline
|
||||
- cd ${STAGING_DIR}/frontend && npm ci --prefer-offline
|
||||
# Ensure staging .env exists
|
||||
- |
|
||||
if [ ! -f "${STAGING_DIR}/backend/.env" ]; then
|
||||
cp ${CI_PROJECT_DIR}/backend/.env ${STAGING_DIR}/backend/.env
|
||||
sed -i 's/^PORT=.*/PORT=3100/' ${STAGING_DIR}/backend/.env
|
||||
grep -q "^PORT=" ${STAGING_DIR}/backend/.env || echo "PORT=3100" >> ${STAGING_DIR}/backend/.env
|
||||
fi
|
||||
# Run migrations
|
||||
- cd ${STAGING_DIR}/backend && node migrations/run-all.js
|
||||
# Restart staging service
|
||||
- sudo systemctl restart cve-backend-staging || sudo systemctl start cve-backend-staging || true
|
||||
./ ${STAGING_USER}@${STAGING_HOST}:${STAGING_DIR}/
|
||||
- rsync -az frontend/build/ ${STAGING_USER}@${STAGING_HOST}:${STAGING_DIR}/frontend/build/
|
||||
- ssh ${STAGING_USER}@${STAGING_HOST} "cd ${STAGING_DIR} && npm ci --prefer-offline"
|
||||
- ssh ${STAGING_USER}@${STAGING_HOST} "cd ${STAGING_DIR}/frontend && npm ci --prefer-offline"
|
||||
- ssh ${STAGING_USER}@${STAGING_HOST} "cd ${STAGING_DIR}/backend && node migrations/run-all.js"
|
||||
- ssh ${STAGING_USER}@${STAGING_HOST} "systemctl restart cve-backend-staging || systemctl start cve-backend-staging || true"
|
||||
- echo "Staging deploy complete."
|
||||
after_script:
|
||||
- |
|
||||
apk add --no-cache curl > /dev/null 2>&1
|
||||
ISSUES=$(git log --format=%B -1 | grep -oP '#\d+' | tr -d '#' | sort -u)
|
||||
for ISSUE in $ISSUES; do
|
||||
curl --silent --request POST \
|
||||
@@ -192,10 +199,8 @@ deploy-staging:
|
||||
- build-frontend
|
||||
- test-backend
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Production — manual trigger, SSH to 71.85.90.6
|
||||
# ---------------------------------------------------------------------------
|
||||
deploy-production:
|
||||
<<: *deploy-base
|
||||
stage: deploy
|
||||
rules:
|
||||
- if: $CI_COMMIT_BRANCH == "main" || $CI_COMMIT_BRANCH == "master"
|
||||
@@ -205,10 +210,8 @@ deploy-production:
|
||||
url: http://71.85.90.6:3001
|
||||
script:
|
||||
- echo "Deploying to production (${PROD_HOST})..."
|
||||
# Record current commit on prod for rollback
|
||||
- ssh ${PROD_USER}@${PROD_HOST} "cd ${PROD_DIR} && git rev-parse HEAD 2>/dev/null || echo none" > /tmp/prod-prev-commit
|
||||
- echo "Previous production commit:$(cat /tmp/prod-prev-commit)"
|
||||
# Sync code to production (exclude local-only files)
|
||||
- rsync -az --delete
|
||||
--exclude='.git'
|
||||
--exclude='node_modules'
|
||||
@@ -219,20 +222,17 @@ deploy-production:
|
||||
--exclude='*.db'
|
||||
--exclude='.env'
|
||||
--exclude='.compliance-staging'
|
||||
${CI_PROJECT_DIR}/ ${PROD_USER}@${PROD_HOST}:${PROD_DIR}/
|
||||
# Copy built frontend
|
||||
- rsync -az ${CI_PROJECT_DIR}/frontend/build/ ${PROD_USER}@${PROD_HOST}:${PROD_DIR}/frontend/build/
|
||||
# Install deps on production
|
||||
./ ${PROD_USER}@${PROD_HOST}:${PROD_DIR}/
|
||||
- rsync -az frontend/build/ ${PROD_USER}@${PROD_HOST}:${PROD_DIR}/frontend/build/
|
||||
- ssh ${PROD_USER}@${PROD_HOST} "cd ${PROD_DIR} && npm ci --prefer-offline"
|
||||
- ssh ${PROD_USER}@${PROD_HOST} "cd ${PROD_DIR}/frontend && npm ci --prefer-offline"
|
||||
# Run migrations
|
||||
- ssh ${PROD_USER}@${PROD_HOST} "cd ${PROD_DIR}/backend && node migrations/run-all.js"
|
||||
# Restart services — install systemd unit if not present
|
||||
- ssh ${PROD_USER}@${PROD_HOST} "test -f /etc/systemd/system/cve-backend.service" || scp ${CI_PROJECT_DIR}/deploy/cve-backend-production.service ${PROD_USER}@${PROD_HOST}:/etc/systemd/system/cve-backend.service
|
||||
- ssh ${PROD_USER}@${PROD_HOST} "test -f /etc/systemd/system/cve-backend.service || true"
|
||||
- ssh ${PROD_USER}@${PROD_HOST} "systemctl daemon-reload && systemctl enable cve-backend && systemctl restart cve-backend"
|
||||
- echo "Production deploy complete."
|
||||
after_script:
|
||||
- |
|
||||
apk add --no-cache curl > /dev/null 2>&1
|
||||
ISSUES=$(git log --format=%B -1 | grep -oP '#\d+' | tr -d '#' | sort -u)
|
||||
for ISSUE in $ISSUES; do
|
||||
curl --silent --request POST \
|
||||
@@ -246,23 +246,22 @@ deploy-production:
|
||||
- test-backend
|
||||
|
||||
# =============================================================================
|
||||
# STAGE 6: Post-deploy verification
|
||||
# STAGE 6: Verify
|
||||
# =============================================================================
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Staging health check
|
||||
# ---------------------------------------------------------------------------
|
||||
verify-staging:
|
||||
stage: verify
|
||||
image: alpine:latest
|
||||
rules:
|
||||
- if: $CI_COMMIT_BRANCH == "main" || $CI_COMMIT_BRANCH == "master"
|
||||
when: on_success
|
||||
script:
|
||||
- apk add --no-cache curl
|
||||
- echo "Verifying staging..."
|
||||
- sleep 3
|
||||
- |
|
||||
for i in 1 2 3 4 5; do
|
||||
STATUS=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:3100/api/health 2>/dev/null || echo "000")
|
||||
STATUS=$(curl -s -o /dev/null -w "%{http_code}" http://${STAGING_HOST}:3100/api/health 2>/dev/null || echo "000")
|
||||
if [ "$STATUS" = "200" ]; then
|
||||
echo "Staging health check passed (attempt $i)"
|
||||
break
|
||||
@@ -274,19 +273,28 @@ verify-staging:
|
||||
echo "FAILED: Staging health check failed after 5 attempts"
|
||||
exit 1
|
||||
fi
|
||||
- |
|
||||
COMP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" "http://${STAGING_HOST}:3100/api/compliance/items?page=1&limit=1" || echo "000")
|
||||
[ "$COMP_STATUS" != "200" ] && echo "WARN: Compliance items returned $COMP_STATUS" || true
|
||||
- |
|
||||
VCL_STATUS=$(curl -s -o /dev/null -w "%{http_code}" "http://${STAGING_HOST}:3100/api/compliance/vcl/stats" || echo "000")
|
||||
[ "$VCL_STATUS" != "200" ] && echo "WARN: VCL stats returned $VCL_STATUS" || true
|
||||
- echo "Staging verification passed."
|
||||
needs:
|
||||
- deploy-staging
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Production health check — rolls back on failure
|
||||
# ---------------------------------------------------------------------------
|
||||
verify-production:
|
||||
stage: verify
|
||||
image: alpine:latest
|
||||
rules:
|
||||
- if: $CI_COMMIT_BRANCH == "main" || $CI_COMMIT_BRANCH == "master"
|
||||
when: on_success
|
||||
script:
|
||||
- apk add --no-cache curl openssh-client
|
||||
- mkdir -p ~/.ssh
|
||||
- echo "$SSH_PRIVATE_KEY" | base64 -d > ~/.ssh/id_ed25519
|
||||
- chmod 600 ~/.ssh/id_ed25519
|
||||
- echo -e "Host *\n StrictHostKeyChecking no\n UserKnownHostsFile /dev/null" > ~/.ssh/config
|
||||
- echo "Verifying production..."
|
||||
- sleep 3
|
||||
- |
|
||||
@@ -304,7 +312,6 @@ verify-production:
|
||||
PREV_COMMIT=$(cat /tmp/prod-prev-commit 2>/dev/null || echo "")
|
||||
if [ -n "$PREV_COMMIT" ] && [ "$PREV_COMMIT" != "none" ]; then
|
||||
echo "Rolling back to $PREV_COMMIT..."
|
||||
# Re-sync the previous version
|
||||
ssh ${PROD_USER}@${PROD_HOST} "cd ${PROD_DIR} && git checkout ${PREV_COMMIT} --force 2>/dev/null" || true
|
||||
ssh ${PROD_USER}@${PROD_HOST} "cd ${PROD_DIR} && npm ci --prefer-offline"
|
||||
ssh ${PROD_USER}@${PROD_HOST} "systemctl restart cve-backend"
|
||||
@@ -314,6 +321,12 @@ verify-production:
|
||||
fi
|
||||
exit 1
|
||||
fi
|
||||
- |
|
||||
COMP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" "http://${PROD_HOST}:3001/api/compliance/items?page=1&limit=1" || echo "000")
|
||||
[ "$COMP_STATUS" != "200" ] && echo "WARN: Compliance items returned $COMP_STATUS" || true
|
||||
- |
|
||||
VCL_STATUS=$(curl -s -o /dev/null -w "%{http_code}" "http://${PROD_HOST}:3001/api/compliance/vcl/stats" || echo "000")
|
||||
[ "$VCL_STATUS" != "200" ] && echo "WARN: VCL stats returned $VCL_STATUS" || true
|
||||
- echo "Production verification passed."
|
||||
needs:
|
||||
- deploy-production
|
||||
|
||||
@@ -80,9 +80,62 @@ Python dependencies: `pandas>=2.0.0`, `openpyxl>=3.0.0` (install via apt or venv
|
||||
- Both `.env` files are gitignored; see `.env.example` files for templates.
|
||||
- React env vars are baked in at **build time** — you must rebuild (`npm run build`) after changing them.
|
||||
|
||||
## Code Style & Lint Rules
|
||||
|
||||
### Unused Variables
|
||||
|
||||
The frontend ESLint config enforces `no-unused-vars` as a warning. The CI pipeline fails if warnings exceed 25. To avoid lint failures:
|
||||
|
||||
- **Prefix intentionally-unused variables with `_`** — this suppresses the warning. The `varsIgnorePattern: "^_"` and `argsIgnorePattern: "^_"` rules are configured in `frontend/package.json`.
|
||||
- Common patterns:
|
||||
- `const [_unused, setFoo] = useState(...)` — destructured value you don't need
|
||||
- `const _legacyRef = useRef(...)` — kept for future use
|
||||
- `function handler(_event) { ... }` — required parameter signature but unused
|
||||
- **Do not leave variables unprefixed if unused.** Either use them, remove them, or prefix with `_`.
|
||||
- This applies to all frontend code written by the agent.
|
||||
|
||||
### Backend
|
||||
|
||||
No ESLint is configured for backend — the pipeline uses `node -c` syntax checking only. Keep code clean but there is no automated unused-var enforcement on the backend side.
|
||||
|
||||
## Ports
|
||||
|
||||
| Environment | URL | Notes |
|
||||
|---|---|---|
|
||||
| Production / Dev server | http://IP:3001 | Express serves API + static frontend build |
|
||||
| Production | http://71.85.90.6:3001 | Express serves API + static frontend build |
|
||||
| Staging | http://71.85.90.9:3100 | Auto-deploy on master push |
|
||||
| Local dev (frontend only) | http://localhost:3000 | React dev server with hot-reload, proxies API to :3001 |
|
||||
|
||||
## CI/CD Pipeline
|
||||
|
||||
### Infrastructure
|
||||
|
||||
| Role | Host | Notes |
|
||||
|---|---|---|
|
||||
| GitLab instance | steam-gitlab.charterlab.com | Self-hosted GitLab |
|
||||
| CI Runner (LXC 108) | 71.85.90.8 | Docker executor, Runner #6, project-locked |
|
||||
| Staging target | 71.85.90.9 | Auto-deploy on master, port 3100 |
|
||||
| Production target | 71.85.90.6 | Manual deploy trigger, port 3001 |
|
||||
|
||||
### Executor: Docker
|
||||
|
||||
The pipeline uses **Docker executor** on Runner #6. Jobs run in isolated containers:
|
||||
|
||||
- **Install / Lint / Test / Build stages**: `node:18` image
|
||||
- **Deploy stages**: `alpine:latest` image (installs `openssh-client` and `rsync` at runtime)
|
||||
|
||||
Deploy jobs SSH from inside the Alpine container to the target hosts using a base64-encoded `$SSH_PRIVATE_KEY` stored as a GitLab CI/CD variable.
|
||||
|
||||
### CI/CD Variables (project-level)
|
||||
|
||||
These are set in GitLab → Settings → CI/CD → Variables:
|
||||
|
||||
| Variable | Purpose |
|
||||
|---|---|
|
||||
| `DATABASE_URL` | PostgreSQL connection string for backend integration tests |
|
||||
| `SSH_PRIVATE_KEY` | Base64-encoded private key for deploy SSH access |
|
||||
| `GITLAB_PAT` | Project access token for issue comments and release creation |
|
||||
|
||||
### Pipeline file
|
||||
|
||||
The pipeline is defined in `.gitlab-ci.yml` at the project root. Stages: install → lint → test → build → deploy → verify.
|
||||
|
||||
50
CHANGELOG.md
50
CHANGELOG.md
@@ -6,27 +6,38 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and this
|
||||
|
||||
---
|
||||
|
||||
## [2.0.0] — 2026-05-19
|
||||
## [2.0.0] — 2026-05-26
|
||||
|
||||
### Breaking Changes
|
||||
|
||||
- **PostgreSQL migration** — database engine switched from SQLite to PostgreSQL. Requires running `deploy-postgres.sh`, data migration, and `DATABASE_URL` env var. SQLite is no longer supported.
|
||||
- **Multi-BU tenancy** — data is now scoped per business unit with per-user team assignments. Replaces the previous binary scope toggle.
|
||||
- **Raw Jira status display** — removed Open/In Progress/Closed status mapping; shows the actual Jira status field everywhere.
|
||||
|
||||
### Features
|
||||
|
||||
- **In-app notification system** — replaces Webex bot integration with native notifications
|
||||
- **Screenshot uploads** in feedback modal, Webex bot DM on issue close
|
||||
- **Jira integration overhaul**
|
||||
- Flexible Jira ticket creation — CVE/Vendor fields optional, source context tracking
|
||||
- Multi-item Jira ticket creation from Ivanti Queue (consolidation modal)
|
||||
- Issue type dropdown and Save to Dashboard from Jira lookup
|
||||
- Success toast after consolidated ticket creation
|
||||
- Improved Jira lookup error messages
|
||||
- **CCP Metrics page** — multi-vertical VCL upload and cross-org compliance reporting
|
||||
- Metric-first hierarchy restructure with Jira cross-project sync
|
||||
- Per-metric forecast burndown chart
|
||||
- Aggregated burndown forecast on overview page
|
||||
- Sub-team drill-down with intermediate view and per-team breakdowns
|
||||
- Non-Compliant stat clickable with metric breakdown buttons
|
||||
- Compliant/total counts on metric summary cards
|
||||
- Per-metric remediation plans
|
||||
- VCL metric calculations guide
|
||||
- **Exports page** — Jira Tickets, CCP Metrics, and Remediation Status export cards
|
||||
- **VCL compliance reporting** — exec report page, device metadata fields, bulk upload
|
||||
- **Aggregated burndown forecast** on CCP Metrics overview page
|
||||
- **Sub-team drill-down** — metric sub-team intermediate view with per-team breakdowns
|
||||
- **Metric breakdown panel** — Non-Compliant stat clickable, reveals metric breakdown buttons, compact grid with top 8 and show-all toggle
|
||||
- **Remediation plan and resolution date history tracking**
|
||||
- **Data management panel** — delete vertical, rollback upload, and reset all
|
||||
- **VCL vertical metadata** — inline-editable team fields on compliance routes
|
||||
- **Re-queue findings** from rejected FP submissions
|
||||
- **In-app notification system** — replaces Webex bot integration with native notifications
|
||||
- **Remediation plan and resolution date history tracking**
|
||||
- **FP submissions cleanup** — auto-clear approved, dismiss rejected, collapsible section
|
||||
- **Re-queue findings** from rejected FP submissions
|
||||
- **DECOM workflow type** — auto-note/hide on decom, show CVEs on CARD queue items
|
||||
- **Interactive configuration wizard** for deployment setup
|
||||
- **Unified setup script** (`configure.js`) merging deploy + config wizard
|
||||
@@ -34,12 +45,23 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and this
|
||||
- **Multi-select BU picker** replacing binary scope toggle
|
||||
- **Configurable IVANTI_MANAGED_BUS** env var for multi-tenant drift classification
|
||||
- **Pipeline-to-issue traceability** via `after_script` comments in CI/CD
|
||||
- **CI/CD pipeline** with feedback modal, Atlas `qualys_id` fallback, and health endpoint
|
||||
- **CI/CD pipeline** with health endpoint and automated deploy stages
|
||||
- **Docker Compose** and `deploy-postgres.sh` for production cutover
|
||||
- **Systemd service scripts** for start/stop management
|
||||
- **VCL vertical metadata** — inline-editable team fields on compliance routes
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- Fix Clear Completed button failing on queue items with Jira ticket links (FK violation)
|
||||
- Fix status badge background making text invisible
|
||||
- Fix calendar SLA dates not highlighting after Postgres migration
|
||||
- Fix document View link using localhost instead of relative URL
|
||||
- Validate library doc file types before sending to Ivanti API
|
||||
- Improve FP workflow error messages — include Ivanti API response body
|
||||
- Fix forecast chart bar order and snapshot month derivation
|
||||
- Fix forecast deduplication for multi-vertical metrics
|
||||
- Fix CCP Metrics page crash for non-Admin users
|
||||
- Fix CCP Metrics crash when donut chart has zero non-compliant devices
|
||||
- Fix duplicate failing metrics on same asset across compliance endpoints
|
||||
- Fix duplicate chart entries on compliance page when multiple verticals share a report_date
|
||||
- Fix requeue inserting Postgres array literal instead of JSON into `cves_json`
|
||||
@@ -51,21 +73,21 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and this
|
||||
- Fix requeue: fallback to `finding_ids_json` when queue items are deleted or absent
|
||||
- Sync FP submission `lifecycle_status` from Ivanti `currentState` on fetch
|
||||
- Fix History tab crash: coerce Ivanti note fields to strings before rendering
|
||||
- Fix archive bar chart: `fmtDate` now handles ISO datetime strings from PostgreSQL date columns
|
||||
- Fix Ivanti panel bugs: Invalid Date, wrong workflow count, crash on archive click, BU scope filtering
|
||||
- Fix archive bar chart: `fmtDate` now handles ISO datetime strings from PostgreSQL
|
||||
- Fix Ivanti panel bugs: Invalid Date, wrong workflow count, crash on archive click
|
||||
- Fix BU drift checker: derive `EXPECTED_BUS` from `IVANTI_BU_FILTER` env var
|
||||
- Fix null `bu_teams` in postgres migration, add retry logic to deploy script
|
||||
- Fix missing `created_by` column in `archer_tickets` table
|
||||
- Fix FP workflow counts donut scoped by BU
|
||||
- Fix `dotenv` loading in `db.js` so `DATABASE_URL` is available on import
|
||||
- Fix property test CI failure: mock db module before importing route
|
||||
|
||||
### Maintenance
|
||||
|
||||
- Track `package-lock.json` files for deterministic CI installs
|
||||
- Remove unused icon imports and unused imports to satisfy ESLint thresholds
|
||||
- Remove unused imports to satisfy ESLint thresholds
|
||||
- CI pipeline fixes: dependency installation, lint thresholds, test isolation
|
||||
- Auto-run migrations in pipeline
|
||||
- Strengthen migration registration hook
|
||||
- Documentation updates for PostgreSQL migration, systemd scripts, and reference manual
|
||||
|
||||
---
|
||||
|
||||
380
backend/__tests__/compliance-per-metric-metadata.test.js
Normal file
380
backend/__tests__/compliance-per-metric-metadata.test.js
Normal file
@@ -0,0 +1,380 @@
|
||||
/**
|
||||
* Unit Tests: PATCH /api/compliance/items/:hostname/metadata — Per-Metric Scoping
|
||||
*
|
||||
* Feature: remediation-plan-history (per-metric extension)
|
||||
*
|
||||
* Tests cover:
|
||||
* - Task 8.1: metric_id/metric_ids validation, precedence, non-empty/max 100 chars, active item check
|
||||
* - Task 8.2: Per-metric SELECT, INSERT history per metric, UPDATE only matching rows
|
||||
* - Task 8.3: Hostname-level behavior preserved with NULL metric_id in history
|
||||
*
|
||||
* Validates: Requirements 8, 11, 15
|
||||
*/
|
||||
|
||||
const http = require('http');
|
||||
const express = require('express');
|
||||
|
||||
// Mock auth middleware
|
||||
jest.mock('../middleware/auth', () => ({
|
||||
requireAuth: () => (req, res, next) => {
|
||||
req.user = { id: 1, username: 'testuser', group: 'Admin' };
|
||||
next();
|
||||
},
|
||||
requireGroup: () => (req, res, next) => next(),
|
||||
}));
|
||||
|
||||
// Mock audit log as a no-op
|
||||
jest.mock('../helpers/auditLog', () => jest.fn());
|
||||
|
||||
// Mock ivantiApi
|
||||
jest.mock('../helpers/ivantiApi', () => ({
|
||||
ivantiFormPost: jest.fn(),
|
||||
ivantiPost: jest.fn(),
|
||||
}));
|
||||
|
||||
// Mock driftChecker
|
||||
jest.mock('../helpers/driftChecker', () => ({
|
||||
loadConfig: jest.fn(() => ({})),
|
||||
compareSchemaToDrift: jest.fn(() => null),
|
||||
reconcileConfig: jest.fn(() => ({ changes: [] })),
|
||||
}));
|
||||
|
||||
// Mock the db pool
|
||||
const mockPool = {
|
||||
query: jest.fn(() => Promise.resolve({ rows: [], rowCount: 0 })),
|
||||
connect: jest.fn(),
|
||||
};
|
||||
jest.mock('../db', () => mockPool);
|
||||
|
||||
const { createComplianceRouter } = require('../routes/compliance');
|
||||
|
||||
// --- HTTP helper ---
|
||||
|
||||
function request(server, method, path, body) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const addr = server.address();
|
||||
const options = {
|
||||
hostname: '127.0.0.1',
|
||||
port: addr.port,
|
||||
path,
|
||||
method,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
};
|
||||
|
||||
const req = http.request(options, (res) => {
|
||||
const chunks = [];
|
||||
res.on('data', (chunk) => chunks.push(chunk));
|
||||
res.on('end', () => {
|
||||
const rawBody = Buffer.concat(chunks).toString();
|
||||
let json;
|
||||
try { json = JSON.parse(rawBody); } catch (e) { json = null; }
|
||||
resolve({ statusCode: res.statusCode, body: json });
|
||||
});
|
||||
});
|
||||
|
||||
req.on('error', reject);
|
||||
if (body) req.write(JSON.stringify(body));
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
// --- Setup ---
|
||||
|
||||
let app, server;
|
||||
|
||||
beforeAll((done) => {
|
||||
app = express();
|
||||
app.use(express.json());
|
||||
const mockUpload = { single: () => (req, res, next) => next() };
|
||||
app.use('/api/compliance', createComplianceRouter(mockUpload));
|
||||
server = app.listen(0, '127.0.0.1', done);
|
||||
});
|
||||
|
||||
afterAll((done) => {
|
||||
server.close(done);
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
// --- Task 8.1: Validation ---
|
||||
|
||||
describe('Task 8.1: metric_id/metric_ids validation', () => {
|
||||
it('returns 400 when metric_ids is not an array', async () => {
|
||||
const res = await request(server, 'PATCH', '/api/compliance/items/srv-001/metadata', {
|
||||
resolution_date: '2026-06-15',
|
||||
metric_ids: 'not-an-array',
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.body.error).toBe('metric_ids must be an array');
|
||||
});
|
||||
|
||||
it('returns 400 when metric_ids is empty array', async () => {
|
||||
const res = await request(server, 'PATCH', '/api/compliance/items/srv-001/metadata', {
|
||||
resolution_date: '2026-06-15',
|
||||
metric_ids: [],
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.body.error).toBe('metric_ids must contain at least one entry');
|
||||
});
|
||||
|
||||
it('returns 400 when metric_ids contains empty string', async () => {
|
||||
const res = await request(server, 'PATCH', '/api/compliance/items/srv-001/metadata', {
|
||||
resolution_date: '2026-06-15',
|
||||
metric_ids: ['2.1.1', ''],
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.body.error).toBe('metric_id cannot be empty');
|
||||
});
|
||||
|
||||
it('returns 400 when metric_id exceeds 100 characters', async () => {
|
||||
const longId = 'x'.repeat(101);
|
||||
const res = await request(server, 'PATCH', '/api/compliance/items/srv-001/metadata', {
|
||||
resolution_date: '2026-06-15',
|
||||
metric_ids: [longId],
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.body.error).toBe('metric_id exceeds 100 characters');
|
||||
});
|
||||
|
||||
it('returns 400 when single metric_id is empty string', async () => {
|
||||
const res = await request(server, 'PATCH', '/api/compliance/items/srv-001/metadata', {
|
||||
resolution_date: '2026-06-15',
|
||||
metric_id: '',
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.body.error).toBe('metric_id cannot be empty');
|
||||
});
|
||||
|
||||
it('returns 400 when single metric_id exceeds 100 characters', async () => {
|
||||
const longId = 'x'.repeat(101);
|
||||
const res = await request(server, 'PATCH', '/api/compliance/items/srv-001/metadata', {
|
||||
resolution_date: '2026-06-15',
|
||||
metric_id: longId,
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.body.error).toBe('metric_id exceeds 100 characters');
|
||||
});
|
||||
|
||||
it('returns 400 when metric_id does not correspond to active compliance_item', async () => {
|
||||
const mockClient = {
|
||||
query: jest.fn()
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }) // BEGIN
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }) // SELECT active metrics — none found
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }), // ROLLBACK
|
||||
release: jest.fn(),
|
||||
};
|
||||
mockPool.connect.mockResolvedValueOnce(mockClient);
|
||||
|
||||
const res = await request(server, 'PATCH', '/api/compliance/items/srv-001/metadata', {
|
||||
resolution_date: '2026-06-15',
|
||||
metric_ids: ['nonexistent-metric'],
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.body.error).toContain('Invalid metric_id: nonexistent-metric');
|
||||
});
|
||||
|
||||
it('uses metric_ids when both metric_id and metric_ids are provided', async () => {
|
||||
// metric_ids wins — should validate metric_ids, not metric_id
|
||||
const mockClient = {
|
||||
query: jest.fn()
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }) // BEGIN
|
||||
.mockResolvedValueOnce({ rows: [{ metric_id: '3.1.1', resolution_date: null, remediation_plan: null }], rowCount: 1 }) // SELECT active metrics
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 1 }) // INSERT history
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 1 }) // UPDATE
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }), // COMMIT
|
||||
release: jest.fn(),
|
||||
};
|
||||
mockPool.connect.mockResolvedValueOnce(mockClient);
|
||||
|
||||
const res = await request(server, 'PATCH', '/api/compliance/items/srv-001/metadata', {
|
||||
resolution_date: '2026-06-15',
|
||||
metric_id: '2.1.1', // should be ignored
|
||||
metric_ids: ['3.1.1'], // should be used
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
// Verify the SELECT query used metric_ids value ['3.1.1'], not metric_id '2.1.1'
|
||||
const selectCall = mockClient.query.mock.calls[1];
|
||||
expect(selectCall[1]).toEqual(['srv-001', ['3.1.1']]);
|
||||
});
|
||||
});
|
||||
|
||||
// --- Task 8.2: Per-metric scoping behavior ---
|
||||
|
||||
describe('Task 8.2: Per-metric SELECT, INSERT history, UPDATE matching rows', () => {
|
||||
it('selects current values per targeted metric and inserts history per metric', async () => {
|
||||
const mockClient = {
|
||||
query: jest.fn()
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }) // BEGIN
|
||||
.mockResolvedValueOnce({ rows: [
|
||||
{ metric_id: '2.1.1', resolution_date: '2026-01-01', remediation_plan: 'Plan A' },
|
||||
{ metric_id: '2.3.2', resolution_date: '2026-02-01', remediation_plan: 'Plan B' },
|
||||
], rowCount: 2 }) // SELECT active metrics with current values
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 1 }) // INSERT history for 2.1.1 resolution_date
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 1 }) // INSERT history for 2.1.1 remediation_plan
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 1 }) // INSERT history for 2.3.2 resolution_date
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 1 }) // INSERT history for 2.3.2 remediation_plan
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 2 }) // UPDATE matching rows
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }), // COMMIT
|
||||
release: jest.fn(),
|
||||
};
|
||||
mockPool.connect.mockResolvedValueOnce(mockClient);
|
||||
|
||||
const res = await request(server, 'PATCH', '/api/compliance/items/srv-001/metadata', {
|
||||
resolution_date: '2026-06-15',
|
||||
remediation_plan: 'New unified plan',
|
||||
metric_ids: ['2.1.1', '2.3.2'],
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.body.updated).toBe(2);
|
||||
|
||||
// Verify history inserts include metric_id
|
||||
const calls = mockClient.query.mock.calls;
|
||||
// Call [2] = INSERT history for 2.1.1 resolution_date
|
||||
expect(calls[2][0]).toContain('INSERT INTO compliance_item_history');
|
||||
expect(calls[2][1][1]).toBe('2.1.1'); // metric_id
|
||||
expect(calls[2][1][2]).toBe('2026-01-01'); // old_value
|
||||
expect(calls[2][1][3]).toBe('2026-06-15'); // new_value
|
||||
|
||||
// Call [3] = INSERT history for 2.1.1 remediation_plan
|
||||
expect(calls[3][1][1]).toBe('2.1.1');
|
||||
expect(calls[3][1][2]).toBe('Plan A'); // old_value
|
||||
expect(calls[3][1][3]).toBe('New unified plan'); // new_value
|
||||
|
||||
// Call [4] = INSERT history for 2.3.2 resolution_date
|
||||
expect(calls[4][1][1]).toBe('2.3.2');
|
||||
expect(calls[4][1][2]).toBe('2026-02-01'); // old_value
|
||||
|
||||
// Call [5] = INSERT history for 2.3.2 remediation_plan
|
||||
expect(calls[5][1][1]).toBe('2.3.2');
|
||||
expect(calls[5][1][2]).toBe('Plan B'); // old_value
|
||||
});
|
||||
|
||||
it('skips history insert when value is unchanged for a specific metric', async () => {
|
||||
const mockClient = {
|
||||
query: jest.fn()
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }) // BEGIN
|
||||
.mockResolvedValueOnce({ rows: [
|
||||
{ metric_id: '2.1.1', resolution_date: '2026-06-15', remediation_plan: null },
|
||||
], rowCount: 1 }) // SELECT — already has the target date
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 1 }) // UPDATE (no history inserts since value unchanged)
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }), // COMMIT
|
||||
release: jest.fn(),
|
||||
};
|
||||
mockPool.connect.mockResolvedValueOnce(mockClient);
|
||||
|
||||
const res = await request(server, 'PATCH', '/api/compliance/items/srv-001/metadata', {
|
||||
resolution_date: '2026-06-15',
|
||||
metric_ids: ['2.1.1'],
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
// No INSERT history calls — only BEGIN, SELECT, UPDATE, COMMIT
|
||||
const calls = mockClient.query.mock.calls;
|
||||
expect(calls.length).toBe(4);
|
||||
expect(calls[2][0]).toContain('UPDATE compliance_items');
|
||||
});
|
||||
|
||||
it('updates only matching rows with metric_id = ANY filter', async () => {
|
||||
const mockClient = {
|
||||
query: jest.fn()
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }) // BEGIN
|
||||
.mockResolvedValueOnce({ rows: [
|
||||
{ metric_id: '2.1.1', resolution_date: null, remediation_plan: null },
|
||||
], rowCount: 1 }) // SELECT
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 1 }) // INSERT history
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 1 }) // UPDATE
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }), // COMMIT
|
||||
release: jest.fn(),
|
||||
};
|
||||
mockPool.connect.mockResolvedValueOnce(mockClient);
|
||||
|
||||
const res = await request(server, 'PATCH', '/api/compliance/items/srv-001/metadata', {
|
||||
resolution_date: '2026-06-15',
|
||||
metric_id: '2.1.1',
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
// Verify UPDATE query includes metric_id = ANY filter
|
||||
const updateCall = mockClient.query.mock.calls[3];
|
||||
expect(updateCall[0]).toContain('metric_id = ANY');
|
||||
expect(updateCall[0]).toContain("status = 'active'");
|
||||
expect(updateCall[1]).toContain('srv-001');
|
||||
expect(updateCall[1]).toEqual(expect.arrayContaining([['2.1.1']]));
|
||||
});
|
||||
});
|
||||
|
||||
// --- Task 8.3: Hostname-level behavior preserved ---
|
||||
|
||||
describe('Task 8.3: Hostname-level behavior with NULL metric_id', () => {
|
||||
it('updates all active rows when no metric_id/metric_ids provided', async () => {
|
||||
const mockClient = {
|
||||
query: jest.fn()
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }) // BEGIN
|
||||
.mockResolvedValueOnce({ rows: [{ resolution_date: null, remediation_plan: null }], rowCount: 1 }) // SELECT current
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 1 }) // INSERT history
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 5 }) // UPDATE all active rows
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }), // COMMIT
|
||||
release: jest.fn(),
|
||||
};
|
||||
mockPool.connect.mockResolvedValueOnce(mockClient);
|
||||
|
||||
const res = await request(server, 'PATCH', '/api/compliance/items/srv-001/metadata', {
|
||||
resolution_date: '2026-06-15',
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.body.updated).toBe(5);
|
||||
|
||||
// Verify UPDATE does NOT include metric_id filter
|
||||
const updateCall = mockClient.query.mock.calls[3];
|
||||
expect(updateCall[0]).not.toContain('metric_id');
|
||||
expect(updateCall[0]).toContain("status = 'active'");
|
||||
});
|
||||
|
||||
it('inserts history with NULL metric_id when no metric scoping', async () => {
|
||||
const mockClient = {
|
||||
query: jest.fn()
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }) // BEGIN
|
||||
.mockResolvedValueOnce({ rows: [{ resolution_date: '2026-01-01', remediation_plan: 'Old plan' }], rowCount: 1 }) // SELECT current
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 1 }) // INSERT history (resolution_date)
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 1 }) // INSERT history (remediation_plan)
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 3 }) // UPDATE
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }), // COMMIT
|
||||
release: jest.fn(),
|
||||
};
|
||||
mockPool.connect.mockResolvedValueOnce(mockClient);
|
||||
|
||||
const res = await request(server, 'PATCH', '/api/compliance/items/srv-001/metadata', {
|
||||
resolution_date: '2026-06-15',
|
||||
remediation_plan: 'New plan',
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
|
||||
// Verify history INSERT includes NULL for metric_id
|
||||
const historyCall1 = mockClient.query.mock.calls[2];
|
||||
expect(historyCall1[0]).toContain('INSERT INTO compliance_item_history');
|
||||
expect(historyCall1[0]).toContain('NULL');
|
||||
});
|
||||
|
||||
it('returns 404 when hostname has no active items (hostname-level path)', async () => {
|
||||
const mockClient = {
|
||||
query: jest.fn()
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }) // BEGIN
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }) // SELECT current — empty
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }), // ROLLBACK
|
||||
release: jest.fn(),
|
||||
};
|
||||
mockPool.connect.mockResolvedValueOnce(mockClient);
|
||||
|
||||
const res = await request(server, 'PATCH', '/api/compliance/items/srv-001/metadata', {
|
||||
resolution_date: '2026-06-15',
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(404);
|
||||
expect(res.body.error).toBe('Device not found');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,216 @@
|
||||
/**
|
||||
* Bug Condition Exploration Property Test: Compliance Remediation Display Fix
|
||||
*
|
||||
* Spec: .kiro/specs/compliance-remediation-display-fix/ (bugfix)
|
||||
*
|
||||
* BUG CONDITION:
|
||||
* isBugCondition(row) = row.resolution_date != null OR row.remediation_plan != null
|
||||
* Any row with metadata set will lose it through groupByHostname() because the
|
||||
* function does not propagate resolution_date or remediation_plan into device objects.
|
||||
*
|
||||
* THIS TEST IS EXPECTED TO FAIL ON UNFIXED CODE.
|
||||
* Failure confirms the bug exists — resolution_date and remediation_plan are undefined
|
||||
* in the grouped device objects returned by groupByHostname().
|
||||
*
|
||||
* **Validates: Requirements 1.1, 1.2, 2.2**
|
||||
*/
|
||||
|
||||
const fc = require('fast-check');
|
||||
|
||||
// --- Mocks (must be installed BEFORE requiring the route module) ---
|
||||
|
||||
jest.mock('../middleware/auth', () => ({
|
||||
requireAuth: () => (req, res, next) => next(),
|
||||
requireGroup: () => (req, res, next) => next(),
|
||||
}));
|
||||
|
||||
jest.mock('../helpers/auditLog', () => jest.fn());
|
||||
|
||||
jest.mock('../helpers/driftChecker', () => ({
|
||||
loadConfig: jest.fn(() => ({})),
|
||||
compareSchemaToDrift: jest.fn(() => null),
|
||||
reconcileConfig: jest.fn(() => ({ changes: [] })),
|
||||
}));
|
||||
|
||||
jest.mock('../helpers/vclHelpers', () => ({
|
||||
isValidDateString: jest.fn(() => true),
|
||||
validateRemediationPlan: jest.fn(() => ({ valid: true })),
|
||||
computeVCLStats: jest.fn(() => ({})),
|
||||
categorizeNonCompliant: jest.fn(() => []),
|
||||
rankHeavyHitters: jest.fn(() => []),
|
||||
computeForecastBurndown: jest.fn(() => ({})),
|
||||
matchByHostname: jest.fn(() => []),
|
||||
computeBulkDiff: jest.fn(() => ({})),
|
||||
mapColumnHeaders: jest.fn(() => ({})),
|
||||
}));
|
||||
|
||||
const mockPool = {
|
||||
query: jest.fn(() => Promise.resolve({ rows: [], rowCount: 0 })),
|
||||
connect: jest.fn(() => Promise.resolve({
|
||||
query: jest.fn(() => Promise.resolve({ rows: [], rowCount: 0 })),
|
||||
release: jest.fn(),
|
||||
})),
|
||||
};
|
||||
jest.mock('../db', () => mockPool);
|
||||
|
||||
const { groupByHostname } = require('../routes/compliance');
|
||||
|
||||
// --- Generators ---
|
||||
|
||||
/** Generate a date string in YYYY-MM-DD format (avoid toISOString on shrunk invalid dates) */
|
||||
const arbDateString = fc.tuple(
|
||||
fc.integer({ min: 2020, max: 2030 }),
|
||||
fc.integer({ min: 1, max: 12 }),
|
||||
fc.integer({ min: 1, max: 28 })
|
||||
).map(([y, m, d]) => `${y}-${String(m).padStart(2, '0')}-${String(d).padStart(2, '0')}`);
|
||||
|
||||
/** Generate a non-empty remediation plan string */
|
||||
const arbRemediationPlan = fc.string({ minLength: 1, maxLength: 200 }).filter(s => s.trim().length > 0);
|
||||
|
||||
/** Generate a hostname (alphanumeric with dashes, realistic) */
|
||||
const arbHostname = fc.stringMatching(/^[A-Z][A-Z0-9\-]{2,20}$/);
|
||||
|
||||
/** Generate a metric_id like "7.1.1" or "3.2" */
|
||||
const arbMetricId = fc.tuple(
|
||||
fc.integer({ min: 1, max: 9 }),
|
||||
fc.integer({ min: 1, max: 9 }),
|
||||
fc.integer({ min: 1, max: 9 })
|
||||
).map(([a, b, c]) => `${a}.${b}.${c}`);
|
||||
|
||||
/**
|
||||
* Generate a compliance row with non-null resolution_date and/or remediation_plan.
|
||||
* This is the bug condition: rows that have metadata which should be propagated.
|
||||
*/
|
||||
const arbComplianceRowWithMetadata = fc.record({
|
||||
hostname: arbHostname,
|
||||
ip_address: fc.ipV4(),
|
||||
device_type: fc.constantFrom('Switch', 'Router', 'Firewall', 'Server'),
|
||||
team: fc.constantFrom('STEAM', 'ACCESS-ENG'),
|
||||
status: fc.constant('active'),
|
||||
metric_id: arbMetricId,
|
||||
metric_desc: fc.string({ minLength: 3, maxLength: 50 }),
|
||||
category: fc.constantFrom('Configuration', 'Patching', 'Access Control'),
|
||||
seen_count: fc.integer({ min: 1, max: 20 }),
|
||||
first_seen: arbDateString,
|
||||
last_seen: arbDateString,
|
||||
resolved_on: fc.constant(null),
|
||||
resolution_date: arbDateString,
|
||||
remediation_plan: arbRemediationPlan,
|
||||
});
|
||||
|
||||
// --- Property Test ---
|
||||
|
||||
describe('Bug Condition Exploration: resolution_date and remediation_plan in groupByHostname()', () => {
|
||||
it('Property 1: groupByHostname() should propagate resolution_date from rows to device objects', () => {
|
||||
fc.assert(
|
||||
fc.property(arbComplianceRowWithMetadata, (row) => {
|
||||
const rows = [row];
|
||||
const noteHostnames = new Set();
|
||||
const devices = groupByHostname(rows, noteHostnames);
|
||||
|
||||
// There should be exactly one device for the single hostname
|
||||
expect(devices).toHaveLength(1);
|
||||
const device = devices[0];
|
||||
|
||||
// BUG CONDITION: resolution_date should be propagated but is undefined on unfixed code
|
||||
expect(device.resolution_date).toBe(row.resolution_date);
|
||||
}),
|
||||
{ numRuns: 100 }
|
||||
);
|
||||
});
|
||||
|
||||
it('Property 2: groupByHostname() should propagate remediation_plan from rows to device objects', () => {
|
||||
fc.assert(
|
||||
fc.property(arbComplianceRowWithMetadata, (row) => {
|
||||
const rows = [row];
|
||||
const noteHostnames = new Set();
|
||||
const devices = groupByHostname(rows, noteHostnames);
|
||||
|
||||
expect(devices).toHaveLength(1);
|
||||
const device = devices[0];
|
||||
|
||||
// BUG CONDITION: remediation_plan should be propagated but is undefined on unfixed code
|
||||
expect(device.remediation_plan).toBe(row.remediation_plan);
|
||||
}),
|
||||
{ numRuns: 100 }
|
||||
);
|
||||
});
|
||||
|
||||
it('Property 3: groupByHostname() should pick first non-null resolution_date across multiple rows for same hostname', () => {
|
||||
fc.assert(
|
||||
fc.property(
|
||||
arbHostname,
|
||||
fc.array(arbMetricId, { minLength: 2, maxLength: 5 }),
|
||||
arbDateString,
|
||||
(hostname, metricIds, resolutionDate) => {
|
||||
// Create multiple rows for the same hostname, first row has resolution_date
|
||||
const rows = metricIds.map((mid, idx) => ({
|
||||
hostname,
|
||||
ip_address: '10.0.0.1',
|
||||
device_type: 'Switch',
|
||||
team: 'STEAM',
|
||||
status: 'active',
|
||||
metric_id: mid,
|
||||
metric_desc: `Metric ${mid}`,
|
||||
category: 'Configuration',
|
||||
seen_count: 1,
|
||||
first_seen: '2025-01-01',
|
||||
last_seen: '2025-06-01',
|
||||
resolved_on: null,
|
||||
resolution_date: idx === 0 ? resolutionDate : null,
|
||||
remediation_plan: null,
|
||||
}));
|
||||
|
||||
const noteHostnames = new Set();
|
||||
const devices = groupByHostname(rows, noteHostnames);
|
||||
|
||||
expect(devices).toHaveLength(1);
|
||||
const device = devices[0];
|
||||
|
||||
// The first non-null resolution_date should be propagated
|
||||
expect(device.resolution_date).toBe(resolutionDate);
|
||||
}
|
||||
),
|
||||
{ numRuns: 100 }
|
||||
);
|
||||
});
|
||||
|
||||
it('Property 4: groupByHostname() should pick first non-null remediation_plan across multiple rows for same hostname', () => {
|
||||
fc.assert(
|
||||
fc.property(
|
||||
arbHostname,
|
||||
fc.array(arbMetricId, { minLength: 2, maxLength: 5 }),
|
||||
arbRemediationPlan,
|
||||
(hostname, metricIds, plan) => {
|
||||
// Create multiple rows for the same hostname, first row has remediation_plan
|
||||
const rows = metricIds.map((mid, idx) => ({
|
||||
hostname,
|
||||
ip_address: '10.0.0.1',
|
||||
device_type: 'Switch',
|
||||
team: 'STEAM',
|
||||
status: 'active',
|
||||
metric_id: mid,
|
||||
metric_desc: `Metric ${mid}`,
|
||||
category: 'Configuration',
|
||||
seen_count: 1,
|
||||
first_seen: '2025-01-01',
|
||||
last_seen: '2025-06-01',
|
||||
resolved_on: null,
|
||||
resolution_date: null,
|
||||
remediation_plan: idx === 0 ? plan : null,
|
||||
}));
|
||||
|
||||
const noteHostnames = new Set();
|
||||
const devices = groupByHostname(rows, noteHostnames);
|
||||
|
||||
expect(devices).toHaveLength(1);
|
||||
const device = devices[0];
|
||||
|
||||
// The first non-null remediation_plan should be propagated
|
||||
expect(device.remediation_plan).toBe(plan);
|
||||
}
|
||||
),
|
||||
{ numRuns: 100 }
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,333 @@
|
||||
/**
|
||||
* Preservation Property Tests: Compliance Remediation Display Fix
|
||||
*
|
||||
* Spec: .kiro/specs/compliance-remediation-display-fix/ (bugfix)
|
||||
*
|
||||
* These tests verify that groupByHostname() correctly aggregates existing fields
|
||||
* on UNFIXED code. They should PASS on unfixed code — they capture baseline
|
||||
* behaviour that must be preserved through the fix.
|
||||
*
|
||||
* Properties tested:
|
||||
* P2.A — Each device.hostname appears exactly once in output
|
||||
* P2.B — device.failing_metrics contains no duplicate metric_ids
|
||||
* P2.C — device.seen_count >= every row's seen_count for that hostname
|
||||
* P2.D — device.first_seen <= every row's first_seen for that hostname
|
||||
* P2.E — device.last_seen >= every row's last_seen for that hostname
|
||||
* P2.F — device.has_notes matches noteHostnames membership
|
||||
*
|
||||
* **Validates: Requirements 3.3, 3.5**
|
||||
*/
|
||||
|
||||
const fc = require('fast-check');
|
||||
|
||||
// Mock dependencies required by the compliance module
|
||||
jest.mock('../middleware/auth', () => ({
|
||||
requireAuth: () => (req, res, next) => next(),
|
||||
requireGroup: () => (req, res, next) => next(),
|
||||
}));
|
||||
jest.mock('../helpers/auditLog', () => jest.fn());
|
||||
jest.mock('../db', () => ({
|
||||
query: jest.fn(() => Promise.resolve({ rows: [], rowCount: 0 })),
|
||||
connect: jest.fn(() => Promise.resolve({ query: jest.fn(), release: jest.fn() })),
|
||||
}));
|
||||
|
||||
const { groupByHostname } = require('../routes/compliance');
|
||||
|
||||
// --- Generators ---
|
||||
|
||||
/**
|
||||
* Generate a valid hostname string (alphanumeric + hyphens, 1-20 chars).
|
||||
*/
|
||||
const hostnameArb = fc.stringMatching(/^[A-Z][A-Z0-9\-]{0,14}$/);
|
||||
|
||||
/**
|
||||
* Generate a metric_id string like "7.1.1", "7.2.3", etc.
|
||||
*/
|
||||
const metricIdArb = fc.tuple(
|
||||
fc.integer({ min: 1, max: 9 }),
|
||||
fc.integer({ min: 1, max: 9 }),
|
||||
fc.integer({ min: 1, max: 9 })
|
||||
).map(([a, b, c]) => `${a}.${b}.${c}`);
|
||||
|
||||
/**
|
||||
* Generate a date string in YYYY-MM-DD format for first_seen/last_seen.
|
||||
*/
|
||||
const dateArb = fc.tuple(
|
||||
fc.integer({ min: 2023, max: 2025 }),
|
||||
fc.integer({ min: 1, max: 12 }),
|
||||
fc.integer({ min: 1, max: 28 })
|
||||
).map(([y, m, d]) => `${y}-${String(m).padStart(2, '0')}-${String(d).padStart(2, '0')}`);
|
||||
|
||||
/**
|
||||
* Generate a compliance row with resolution_date = null and remediation_plan = null
|
||||
* (non-bug-condition inputs — these are the rows that should work correctly on unfixed code).
|
||||
*/
|
||||
function complianceRowArb(hostname, metricId) {
|
||||
return fc.record({
|
||||
hostname: fc.constant(hostname),
|
||||
ip_address: fc.constantFrom('10.0.0.1', '10.0.0.2', '192.168.1.1', ''),
|
||||
device_type: fc.constantFrom('Switch', 'Router', 'Firewall', ''),
|
||||
team: fc.constantFrom('STEAM', 'ACCESS-ENG'),
|
||||
status: fc.constantFrom('active', 'resolved'),
|
||||
metric_id: fc.constant(metricId),
|
||||
metric_desc: fc.constantFrom('Password Complexity', 'Firmware Version', 'Logging Enabled'),
|
||||
category: fc.constantFrom('Configuration', 'Patching', 'Monitoring'),
|
||||
seen_count: fc.integer({ min: 1, max: 20 }),
|
||||
first_seen: dateArb,
|
||||
last_seen: dateArb,
|
||||
resolved_on: fc.constant(null),
|
||||
resolution_date: fc.constant(null),
|
||||
remediation_plan: fc.constant(null),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate an array of compliance rows with varying hostnames and metric_ids.
|
||||
* Ensures at least 1 row, with 1-4 hostnames and 1-5 metrics per hostname.
|
||||
*/
|
||||
const complianceRowsArb = fc.tuple(
|
||||
fc.array(hostnameArb, { minLength: 1, maxLength: 4 }),
|
||||
fc.array(metricIdArb, { minLength: 1, maxLength: 5 })
|
||||
).chain(([hostnames, metricIds]) => {
|
||||
// Ensure unique hostnames and metric_ids
|
||||
const uniqueHostnames = [...new Set(hostnames)];
|
||||
const uniqueMetricIds = [...new Set(metricIds)];
|
||||
|
||||
if (uniqueHostnames.length === 0 || uniqueMetricIds.length === 0) {
|
||||
// Fallback: generate at least one row
|
||||
return complianceRowArb('HOST-A', '1.1.1').map(row => [row]);
|
||||
}
|
||||
|
||||
// Generate rows: each hostname gets some subset of metric_ids
|
||||
// Some hostnames may share metric_ids (same metric failing on different devices)
|
||||
const rowArbs = [];
|
||||
for (const hostname of uniqueHostnames) {
|
||||
// Each hostname gets 1 to all metric_ids
|
||||
const metricsForHost = uniqueMetricIds.slice(0, Math.max(1, Math.ceil(Math.random() * uniqueMetricIds.length)));
|
||||
for (const metricId of metricsForHost) {
|
||||
rowArbs.push(complianceRowArb(hostname, metricId));
|
||||
}
|
||||
}
|
||||
|
||||
return fc.tuple(...rowArbs).map(rows => rows);
|
||||
});
|
||||
|
||||
/**
|
||||
* Better generator: explicitly controls the structure to ensure good coverage.
|
||||
* Generates 1-3 hostnames, each with 1-4 rows (possibly duplicate metric_ids to test dedup).
|
||||
*/
|
||||
const structuredRowsArb = fc.record({
|
||||
numHostnames: fc.integer({ min: 1, max: 3 }),
|
||||
numMetricsPerHost: fc.integer({ min: 1, max: 4 }),
|
||||
allowDuplicateMetrics: fc.boolean(),
|
||||
}).chain(({ numHostnames, numMetricsPerHost, allowDuplicateMetrics }) => {
|
||||
const hostnameArbs = fc.array(hostnameArb, { minLength: numHostnames, maxLength: numHostnames });
|
||||
const metricArbs = fc.array(metricIdArb, { minLength: numMetricsPerHost, maxLength: numMetricsPerHost });
|
||||
|
||||
return fc.tuple(hostnameArbs, metricArbs).chain(([hostnames, metrics]) => {
|
||||
const uniqueHostnames = [...new Set(hostnames)];
|
||||
if (uniqueHostnames.length === 0) return fc.constant([]);
|
||||
|
||||
const rowArbs = [];
|
||||
for (const hostname of uniqueHostnames) {
|
||||
const metricsToUse = allowDuplicateMetrics
|
||||
? metrics // May have duplicates
|
||||
: [...new Set(metrics)];
|
||||
|
||||
for (const metricId of metricsToUse) {
|
||||
rowArbs.push(complianceRowArb(hostname, metricId));
|
||||
}
|
||||
// Add an extra duplicate row for the first metric to test dedup
|
||||
if (allowDuplicateMetrics && metricsToUse.length > 0) {
|
||||
rowArbs.push(complianceRowArb(hostname, metricsToUse[0]));
|
||||
}
|
||||
}
|
||||
|
||||
if (rowArbs.length === 0) return fc.constant([]);
|
||||
return fc.tuple(...rowArbs).map(rows => rows);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
// =============================================================================
|
||||
// Property P2.A — Each device.hostname appears exactly once in output
|
||||
// =============================================================================
|
||||
//
|
||||
// **Validates: Requirements 3.3, 3.5**
|
||||
//
|
||||
describe('Property P2.A — Each device.hostname appears exactly once in output', () => {
|
||||
it('P2.A — groupByHostname produces one device per unique hostname', () => {
|
||||
fc.assert(
|
||||
fc.property(structuredRowsArb, (rows) => {
|
||||
if (rows.length === 0) return;
|
||||
|
||||
const noteHostnames = new Set();
|
||||
const devices = groupByHostname(rows, noteHostnames);
|
||||
|
||||
// Each hostname in the output should appear exactly once
|
||||
const outputHostnames = devices.map(d => d.hostname);
|
||||
const uniqueOutputHostnames = new Set(outputHostnames);
|
||||
expect(outputHostnames.length).toBe(uniqueOutputHostnames.size);
|
||||
|
||||
// Every hostname from input should appear in output
|
||||
const inputHostnames = new Set(rows.map(r => r.hostname));
|
||||
for (const hostname of inputHostnames) {
|
||||
expect(uniqueOutputHostnames.has(hostname)).toBe(true);
|
||||
}
|
||||
}),
|
||||
{ numRuns: 100 },
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
// =============================================================================
|
||||
// Property P2.B — device.failing_metrics contains no duplicate metric_ids
|
||||
// =============================================================================
|
||||
//
|
||||
// **Validates: Requirements 3.3, 3.5**
|
||||
//
|
||||
describe('Property P2.B — device.failing_metrics contains no duplicate metric_ids', () => {
|
||||
it('P2.B — groupByHostname deduplicates metrics by metric_id', () => {
|
||||
fc.assert(
|
||||
fc.property(structuredRowsArb, (rows) => {
|
||||
if (rows.length === 0) return;
|
||||
|
||||
const noteHostnames = new Set();
|
||||
const devices = groupByHostname(rows, noteHostnames);
|
||||
|
||||
for (const device of devices) {
|
||||
const metricIds = device.failing_metrics.map(m => m.metric_id);
|
||||
const uniqueMetricIds = new Set(metricIds);
|
||||
expect(metricIds.length).toBe(uniqueMetricIds.size);
|
||||
}
|
||||
}),
|
||||
{ numRuns: 100 },
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
// =============================================================================
|
||||
// Property P2.C — device.seen_count >= every row's seen_count for that hostname
|
||||
// =============================================================================
|
||||
//
|
||||
// **Validates: Requirements 3.3, 3.5**
|
||||
//
|
||||
describe('Property P2.C — device.seen_count >= every row seen_count for that hostname', () => {
|
||||
it('P2.C — groupByHostname picks the maximum seen_count across rows', () => {
|
||||
fc.assert(
|
||||
fc.property(structuredRowsArb, (rows) => {
|
||||
if (rows.length === 0) return;
|
||||
|
||||
const noteHostnames = new Set();
|
||||
const devices = groupByHostname(rows, noteHostnames);
|
||||
|
||||
for (const device of devices) {
|
||||
const rowsForHost = rows.filter(r => r.hostname === device.hostname);
|
||||
for (const row of rowsForHost) {
|
||||
expect(device.seen_count).toBeGreaterThanOrEqual(row.seen_count);
|
||||
}
|
||||
}
|
||||
}),
|
||||
{ numRuns: 100 },
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
// =============================================================================
|
||||
// Property P2.D — device.first_seen <= every row's first_seen for that hostname
|
||||
// =============================================================================
|
||||
//
|
||||
// **Validates: Requirements 3.3, 3.5**
|
||||
//
|
||||
describe('Property P2.D — device.first_seen <= every row first_seen for that hostname', () => {
|
||||
it('P2.D — groupByHostname picks the earliest first_seen across rows', () => {
|
||||
fc.assert(
|
||||
fc.property(structuredRowsArb, (rows) => {
|
||||
if (rows.length === 0) return;
|
||||
|
||||
const noteHostnames = new Set();
|
||||
const devices = groupByHostname(rows, noteHostnames);
|
||||
|
||||
for (const device of devices) {
|
||||
const rowsForHost = rows.filter(r => r.hostname === device.hostname);
|
||||
for (const row of rowsForHost) {
|
||||
if (row.first_seen && device.first_seen) {
|
||||
expect(device.first_seen <= row.first_seen).toBe(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}),
|
||||
{ numRuns: 100 },
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
// =============================================================================
|
||||
// Property P2.E — device.last_seen >= every row's last_seen for that hostname
|
||||
// =============================================================================
|
||||
//
|
||||
// **Validates: Requirements 3.3, 3.5**
|
||||
//
|
||||
describe('Property P2.E — device.last_seen >= every row last_seen for that hostname', () => {
|
||||
it('P2.E — groupByHostname picks the latest last_seen across rows', () => {
|
||||
fc.assert(
|
||||
fc.property(structuredRowsArb, (rows) => {
|
||||
if (rows.length === 0) return;
|
||||
|
||||
const noteHostnames = new Set();
|
||||
const devices = groupByHostname(rows, noteHostnames);
|
||||
|
||||
for (const device of devices) {
|
||||
const rowsForHost = rows.filter(r => r.hostname === device.hostname);
|
||||
for (const row of rowsForHost) {
|
||||
if (row.last_seen && device.last_seen) {
|
||||
expect(device.last_seen >= row.last_seen).toBe(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}),
|
||||
{ numRuns: 100 },
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
// =============================================================================
|
||||
// Property P2.F — device.has_notes matches noteHostnames membership
|
||||
// =============================================================================
|
||||
//
|
||||
// **Validates: Requirements 3.3, 3.5**
|
||||
//
|
||||
describe('Property P2.F — device.has_notes matches noteHostnames membership', () => {
|
||||
it('P2.F — groupByHostname sets has_notes based on noteHostnames Set', () => {
|
||||
fc.assert(
|
||||
fc.property(
|
||||
structuredRowsArb,
|
||||
fc.array(hostnameArb, { minLength: 0, maxLength: 3 }),
|
||||
(rows, noteHosts) => {
|
||||
if (rows.length === 0) return;
|
||||
|
||||
// Build noteHostnames set — include some from input, some random
|
||||
const inputHostnames = [...new Set(rows.map(r => r.hostname))];
|
||||
const noteHostnames = new Set([
|
||||
...noteHosts,
|
||||
// Include some actual hostnames from input to test true case
|
||||
...inputHostnames.slice(0, Math.ceil(inputHostnames.length / 2)),
|
||||
]);
|
||||
|
||||
const devices = groupByHostname(rows, noteHostnames);
|
||||
|
||||
for (const device of devices) {
|
||||
const expected = noteHostnames.has(device.hostname);
|
||||
expect(device.has_notes).toBe(expected);
|
||||
}
|
||||
},
|
||||
),
|
||||
{ numRuns: 100 },
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,576 @@
|
||||
/**
|
||||
* Bug Condition Exploration Property Test: Ivanti Queue Clear Completed FK Violation
|
||||
*
|
||||
* Spec: .kiro/specs/ivanti-queue-clear-completed-fix/ (bugfix)
|
||||
*
|
||||
* BUG CONDITION (from design.md):
|
||||
* isBugCondition(input) returns true when linkedItems.length > 0
|
||||
* — completed queue items have associated rows in jira_ticket_queue_items
|
||||
*
|
||||
* The current DELETE /completed handler issues a bare:
|
||||
* DELETE FROM ivanti_todo_queue WHERE user_id = $1 AND status = 'complete'
|
||||
* which fails with a FK violation when child rows exist in jira_ticket_queue_items.
|
||||
*
|
||||
* THIS TEST ENCODES THE EXPECTED (FIXED) BEHAVIOR:
|
||||
* The handler should delete junction table references first, then delete
|
||||
* completed queue items, all within a transaction, and return success.
|
||||
*
|
||||
* ON UNFIXED CODE, THIS TEST WILL FAIL:
|
||||
* The current handler does not use transactions or clean up junction rows.
|
||||
* When pool.query receives the bare DELETE and junction rows exist, the mock
|
||||
* simulates the FK violation error that PostgreSQL would throw.
|
||||
* The handler catches the error and returns 500 instead of the expected 200.
|
||||
*
|
||||
* COUNTEREXAMPLE:
|
||||
* "DELETE FROM ivanti_todo_queue fails with FK violation when junction rows
|
||||
* reference completed items"
|
||||
*
|
||||
* **Validates: Requirements 1.1**
|
||||
*/
|
||||
|
||||
const http = require('http');
|
||||
const express = require('express');
|
||||
const fc = require('fast-check');
|
||||
|
||||
// --- Mocks (must be installed BEFORE requiring the route module) ---
|
||||
|
||||
jest.mock('../middleware/auth', () => ({
|
||||
requireAuth: () => (req, _res, next) => {
|
||||
req.user = { id: 42, username: 'testuser', group: 'Admin' };
|
||||
next();
|
||||
},
|
||||
requireGroup: () => (_req, _res, next) => next(),
|
||||
}));
|
||||
|
||||
jest.mock('../helpers/auditLog', () => jest.fn());
|
||||
|
||||
// Programmable pg pool mock
|
||||
let queryHandler = () => Promise.resolve({ rows: [], rowCount: 0 });
|
||||
|
||||
const mockClient = {
|
||||
query: jest.fn((text, params) => queryHandler(text, params)),
|
||||
release: jest.fn(),
|
||||
};
|
||||
|
||||
const mockPool = {
|
||||
query: jest.fn((text, params) => queryHandler(text, params)),
|
||||
connect: jest.fn(() => Promise.resolve(mockClient)),
|
||||
};
|
||||
|
||||
jest.mock('../db', () => mockPool);
|
||||
|
||||
const createIvantiTodoQueueRouter = require('../routes/ivantiTodoQueue');
|
||||
|
||||
// --- HTTP helper ---
|
||||
|
||||
function request(server, method, urlPath) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const addr = server.address();
|
||||
const options = {
|
||||
hostname: '127.0.0.1',
|
||||
port: addr.port,
|
||||
path: urlPath,
|
||||
method,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
};
|
||||
const req = http.request(options, (res) => {
|
||||
const chunks = [];
|
||||
res.on('data', (chunk) => chunks.push(chunk));
|
||||
res.on('end', () => {
|
||||
const raw = Buffer.concat(chunks).toString();
|
||||
let body;
|
||||
try { body = JSON.parse(raw); } catch { body = raw; }
|
||||
resolve({ statusCode: res.statusCode, body });
|
||||
});
|
||||
});
|
||||
req.on('error', reject);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
// --- Generators ---
|
||||
|
||||
/**
|
||||
* Generate a non-empty array of completed queue item IDs (simulating items
|
||||
* that belong to the authenticated user and have status = 'complete').
|
||||
*/
|
||||
const completedItemIdsArb = fc.array(
|
||||
fc.integer({ min: 1, max: 10000 }),
|
||||
{ minLength: 1, maxLength: 10 }
|
||||
).map(ids => [...new Set(ids)]); // ensure unique IDs
|
||||
|
||||
/**
|
||||
* Generate junction table links for a subset of completed items.
|
||||
* At least one item MUST have a junction link (this is the bug condition).
|
||||
*/
|
||||
const junctionLinksArb = (itemIds) => {
|
||||
// Generate at least 1 junction link, up to 3 per item
|
||||
return fc.array(
|
||||
fc.record({
|
||||
jira_ticket_id: fc.integer({ min: 1, max: 5000 }),
|
||||
queue_item_id: fc.constantFrom(...itemIds),
|
||||
}),
|
||||
{ minLength: 1, maxLength: Math.min(itemIds.length * 3, 15) }
|
||||
);
|
||||
};
|
||||
|
||||
// --- Test Suite ---
|
||||
|
||||
describe('Bug Condition Exploration: FK Violation on Clear Completed With Junction Table Links', () => {
|
||||
let app;
|
||||
let server;
|
||||
|
||||
beforeAll((done) => {
|
||||
app = express();
|
||||
app.use(express.json());
|
||||
app.use('/api/ivanti/todo-queue', createIvantiTodoQueueRouter());
|
||||
server = app.listen(0, '127.0.0.1', done);
|
||||
});
|
||||
|
||||
afterAll((done) => {
|
||||
server.close(done);
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
mockClient.query.mockReset();
|
||||
mockClient.release.mockReset();
|
||||
mockPool.query.mockReset();
|
||||
mockPool.connect.mockReset();
|
||||
mockPool.connect.mockResolvedValue(mockClient);
|
||||
queryHandler = () => Promise.resolve({ rows: [], rowCount: 0 });
|
||||
});
|
||||
|
||||
/**
|
||||
* Property 1: Bug Condition - FK Violation on Clear Completed With Junction Table Links
|
||||
*
|
||||
* For any set of completed queue items where at least one has junction table links,
|
||||
* the FIXED handler should:
|
||||
* 1. Use a transaction (BEGIN/COMMIT)
|
||||
* 2. Delete junction table references first
|
||||
* 3. Delete the completed queue items
|
||||
* 4. Return 200 with { message, deleted: N }
|
||||
*
|
||||
* On UNFIXED code: The handler uses a bare pool.query DELETE which will receive
|
||||
* a FK violation error from our mock (simulating PostgreSQL behavior), causing
|
||||
* the handler to return 500. This test FAILS, confirming the bug exists.
|
||||
*
|
||||
* **Validates: Requirements 1.1**
|
||||
*/
|
||||
it('Property 1: completed items with junction links are deleted successfully (encodes expected fixed behavior)', async () => {
|
||||
await fc.assert(
|
||||
fc.asyncProperty(
|
||||
completedItemIdsArb,
|
||||
fc.context(),
|
||||
async (itemIds, ctx) => {
|
||||
// Generate junction links for these items
|
||||
const junctionLinks = itemIds.map(id => ({
|
||||
jira_ticket_id: id * 10,
|
||||
queue_item_id: id,
|
||||
}));
|
||||
|
||||
ctx.log(`Testing with ${itemIds.length} completed items, ${junctionLinks.length} junction links`);
|
||||
ctx.log(`Item IDs: ${JSON.stringify(itemIds)}`);
|
||||
|
||||
// Reset mocks for this iteration
|
||||
mockClient.query.mockReset();
|
||||
mockClient.release.mockReset();
|
||||
mockPool.query.mockReset();
|
||||
mockPool.connect.mockReset();
|
||||
mockPool.connect.mockResolvedValue(mockClient);
|
||||
|
||||
// Configure the query handler to simulate the bug condition:
|
||||
// - If the code uses pool.query with a bare DELETE on ivanti_todo_queue,
|
||||
// simulate the FK violation error (this is what the UNFIXED code does)
|
||||
// - If the code uses a transaction (BEGIN, SELECT, DELETE junction, DELETE queue, COMMIT),
|
||||
// simulate successful execution (this is what the FIXED code should do)
|
||||
const fkViolationError = new Error(
|
||||
'update or delete on table "ivanti_todo_queue" violates foreign key constraint ' +
|
||||
'"jira_ticket_queue_items_queue_item_id_fkey" on table "jira_ticket_queue_items"'
|
||||
);
|
||||
fkViolationError.code = '23503'; // PostgreSQL FK violation error code
|
||||
|
||||
// Handler for pool.query (unfixed code path)
|
||||
mockPool.query.mockImplementation((text, params) => {
|
||||
// The unfixed code issues a bare DELETE — simulate FK violation
|
||||
if (text.includes('DELETE FROM ivanti_todo_queue')) {
|
||||
return Promise.reject(fkViolationError);
|
||||
}
|
||||
return Promise.resolve({ rows: [], rowCount: 0 });
|
||||
});
|
||||
|
||||
// Handler for client.query (fixed code path — transaction-based)
|
||||
mockClient.query.mockImplementation((text, params) => {
|
||||
if (text === 'BEGIN') {
|
||||
return Promise.resolve({ rows: [], rowCount: 0 });
|
||||
}
|
||||
if (text.includes('SELECT') && text.includes('ivanti_todo_queue') && text.includes('complete')) {
|
||||
return Promise.resolve({
|
||||
rows: itemIds.map(id => ({ id })),
|
||||
rowCount: itemIds.length,
|
||||
});
|
||||
}
|
||||
if (text.includes('DELETE FROM jira_ticket_queue_items')) {
|
||||
return Promise.resolve({
|
||||
rows: [],
|
||||
rowCount: junctionLinks.length,
|
||||
});
|
||||
}
|
||||
if (text.includes('DELETE FROM ivanti_todo_queue')) {
|
||||
return Promise.resolve({
|
||||
rows: [],
|
||||
rowCount: itemIds.length,
|
||||
});
|
||||
}
|
||||
if (text === 'COMMIT') {
|
||||
return Promise.resolve({ rows: [], rowCount: 0 });
|
||||
}
|
||||
if (text === 'ROLLBACK') {
|
||||
return Promise.resolve({ rows: [], rowCount: 0 });
|
||||
}
|
||||
return Promise.resolve({ rows: [], rowCount: 0 });
|
||||
});
|
||||
|
||||
// Make the request
|
||||
const res = await request(server, 'DELETE', '/api/ivanti/todo-queue/completed');
|
||||
|
||||
// Assert EXPECTED (fixed) behavior:
|
||||
// The handler should return 200 with the correct deleted count
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.body.message).toBe('Completed items cleared.');
|
||||
expect(res.body.deleted).toBe(itemIds.length);
|
||||
}
|
||||
),
|
||||
{ numRuns: 20, verbose: 2 }
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
// --- Preservation Property Tests ---
|
||||
|
||||
/**
|
||||
* Property 2: Preservation - Clear Completed Without Junction Table Links
|
||||
*
|
||||
* Spec: .kiro/specs/ivanti-queue-clear-completed-fix/ (bugfix)
|
||||
*
|
||||
* PRESERVATION GOAL:
|
||||
* Verify that the UNFIXED code already handles non-bug-condition cases correctly.
|
||||
* These tests establish a baseline that must be preserved after the fix is applied.
|
||||
*
|
||||
* NON-BUG-CONDITION CASES:
|
||||
* - Completed items WITHOUT junction table links → DELETE succeeds, returns count
|
||||
* - No completed items exist → returns { deleted: 0 }
|
||||
* - Pending/in-progress items → never touched by the DELETE
|
||||
*
|
||||
* The current handler uses:
|
||||
* pool.query("DELETE FROM ivanti_todo_queue WHERE user_id = $1 AND status = 'complete'", [req.user.id])
|
||||
* This works correctly when no FK violations occur (no junction table references).
|
||||
*
|
||||
* EXPECTED OUTCOME: All tests PASS on unfixed code.
|
||||
*
|
||||
* **Validates: Requirements 3.1, 3.2, 3.3**
|
||||
*/
|
||||
|
||||
describe('Preservation: Clear Completed Without Junction Table Links', () => {
|
||||
let app;
|
||||
let server;
|
||||
|
||||
beforeAll((done) => {
|
||||
app = express();
|
||||
app.use(express.json());
|
||||
app.use('/api/ivanti/todo-queue', createIvantiTodoQueueRouter());
|
||||
server = app.listen(0, '127.0.0.1', done);
|
||||
});
|
||||
|
||||
afterAll((done) => {
|
||||
server.close(done);
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
mockClient.query.mockReset();
|
||||
mockClient.release.mockReset();
|
||||
mockPool.query.mockReset();
|
||||
mockPool.connect.mockReset();
|
||||
mockPool.connect.mockResolvedValue(mockClient);
|
||||
queryHandler = () => Promise.resolve({ rows: [], rowCount: 0 });
|
||||
});
|
||||
|
||||
/**
|
||||
* Property 2a: Completed items without junction links are all deleted
|
||||
*
|
||||
* For any random count of completed items (1–20) belonging to the user,
|
||||
* when none have junction table links, the DELETE succeeds and returns
|
||||
* the correct count.
|
||||
*
|
||||
* The fixed code uses a transaction (client.query) so we mock client.query
|
||||
* to simulate successful execution without FK violations.
|
||||
*
|
||||
* **Validates: Requirements 3.1**
|
||||
*/
|
||||
it('Property 2a: completed items without junction links are deleted and correct count returned', async () => {
|
||||
await fc.assert(
|
||||
fc.asyncProperty(
|
||||
fc.integer({ min: 1, max: 20 }),
|
||||
fc.context(),
|
||||
async (completedCount, ctx) => {
|
||||
ctx.log(`Testing with ${completedCount} completed items (no junction links)`);
|
||||
|
||||
// Reset mocks for this iteration
|
||||
mockClient.query.mockReset();
|
||||
mockClient.release.mockReset();
|
||||
mockPool.connect.mockReset();
|
||||
mockPool.connect.mockResolvedValue(mockClient);
|
||||
|
||||
// Generate item IDs
|
||||
const itemIds = Array.from({ length: completedCount }, (_, i) => i + 1);
|
||||
|
||||
// Mock client.query for the transaction-based handler
|
||||
mockClient.query.mockImplementation((text, params) => {
|
||||
if (text === 'BEGIN') return Promise.resolve({ rows: [], rowCount: 0 });
|
||||
if (text.includes('SELECT') && text.includes('ivanti_todo_queue') && text.includes('complete')) {
|
||||
return Promise.resolve({ rows: itemIds.map(id => ({ id })), rowCount: completedCount });
|
||||
}
|
||||
if (text.includes('DELETE FROM jira_ticket_queue_items')) {
|
||||
return Promise.resolve({ rows: [], rowCount: 0 }); // no junction links
|
||||
}
|
||||
if (text.includes('DELETE FROM ivanti_todo_queue')) {
|
||||
return Promise.resolve({ rows: [], rowCount: completedCount });
|
||||
}
|
||||
if (text === 'COMMIT') return Promise.resolve({ rows: [], rowCount: 0 });
|
||||
if (text === 'ROLLBACK') return Promise.resolve({ rows: [], rowCount: 0 });
|
||||
return Promise.resolve({ rows: [], rowCount: 0 });
|
||||
});
|
||||
|
||||
const res = await request(server, 'DELETE', '/api/ivanti/todo-queue/completed');
|
||||
|
||||
// Assert preservation behavior
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.body.message).toBe('Completed items cleared.');
|
||||
expect(res.body.deleted).toBe(completedCount);
|
||||
}
|
||||
),
|
||||
{ numRuns: 30, verbose: 2 }
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* Property 2b: When no completed items exist, returns deleted: 0
|
||||
*
|
||||
* When the user has no completed items, the SELECT returns empty rows
|
||||
* and the endpoint returns { message: 'Completed items cleared.', deleted: 0 }.
|
||||
*
|
||||
* **Validates: Requirements 3.2**
|
||||
*/
|
||||
it('Property 2b: no completed items returns deleted: 0', async () => {
|
||||
await fc.assert(
|
||||
fc.asyncProperty(
|
||||
fc.constant(null),
|
||||
fc.context(),
|
||||
async (_unused, ctx) => {
|
||||
ctx.log('Testing with 0 completed items');
|
||||
|
||||
// Reset mocks for this iteration
|
||||
mockClient.query.mockReset();
|
||||
mockClient.release.mockReset();
|
||||
mockPool.connect.mockReset();
|
||||
mockPool.connect.mockResolvedValue(mockClient);
|
||||
|
||||
// Mock client.query: SELECT returns empty rows (no completed items)
|
||||
mockClient.query.mockImplementation((text, params) => {
|
||||
if (text === 'BEGIN') return Promise.resolve({ rows: [], rowCount: 0 });
|
||||
if (text.includes('SELECT') && text.includes('ivanti_todo_queue') && text.includes('complete')) {
|
||||
return Promise.resolve({ rows: [], rowCount: 0 });
|
||||
}
|
||||
if (text === 'COMMIT') return Promise.resolve({ rows: [], rowCount: 0 });
|
||||
if (text === 'ROLLBACK') return Promise.resolve({ rows: [], rowCount: 0 });
|
||||
return Promise.resolve({ rows: [], rowCount: 0 });
|
||||
});
|
||||
|
||||
const res = await request(server, 'DELETE', '/api/ivanti/todo-queue/completed');
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.body.message).toBe('Completed items cleared.');
|
||||
expect(res.body.deleted).toBe(0);
|
||||
}
|
||||
),
|
||||
{ numRuns: 5, verbose: 2 }
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* Property 2c: Pending/in-progress items are never touched
|
||||
*
|
||||
* The SELECT query only fetches items with status = 'complete' for the user.
|
||||
* We verify the query text and parameters to ensure non-complete items
|
||||
* are never affected.
|
||||
*
|
||||
* **Validates: Requirements 3.3**
|
||||
*/
|
||||
it('Property 2c: DELETE only targets complete status for the authenticated user', async () => {
|
||||
await fc.assert(
|
||||
fc.asyncProperty(
|
||||
fc.integer({ min: 0, max: 15 }),
|
||||
fc.context(),
|
||||
async (completedCount, ctx) => {
|
||||
ctx.log(`Testing query targeting with ${completedCount} completed items`);
|
||||
|
||||
// Reset mocks for this iteration
|
||||
mockClient.query.mockReset();
|
||||
mockClient.release.mockReset();
|
||||
mockPool.connect.mockReset();
|
||||
mockPool.connect.mockResolvedValue(mockClient);
|
||||
|
||||
// Track the queries issued via client
|
||||
const queriesIssued = [];
|
||||
const itemIds = Array.from({ length: completedCount }, (_, i) => i + 1);
|
||||
|
||||
mockClient.query.mockImplementation((text, params) => {
|
||||
queriesIssued.push({ text, params });
|
||||
if (text === 'BEGIN') return Promise.resolve({ rows: [], rowCount: 0 });
|
||||
if (text.includes('SELECT') && text.includes('ivanti_todo_queue') && text.includes('complete')) {
|
||||
return Promise.resolve({ rows: itemIds.map(id => ({ id })), rowCount: completedCount });
|
||||
}
|
||||
if (text.includes('DELETE FROM jira_ticket_queue_items')) {
|
||||
return Promise.resolve({ rows: [], rowCount: 0 });
|
||||
}
|
||||
if (text.includes('DELETE FROM ivanti_todo_queue')) {
|
||||
return Promise.resolve({ rows: [], rowCount: completedCount });
|
||||
}
|
||||
if (text === 'COMMIT') return Promise.resolve({ rows: [], rowCount: 0 });
|
||||
if (text === 'ROLLBACK') return Promise.resolve({ rows: [], rowCount: 0 });
|
||||
return Promise.resolve({ rows: [], rowCount: 0 });
|
||||
});
|
||||
|
||||
const res = await request(server, 'DELETE', '/api/ivanti/todo-queue/completed');
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
|
||||
// Verify the SELECT query targets only complete status for user 42
|
||||
const selectQueries = queriesIssued.filter(q => q.text.includes('SELECT') && q.text.includes('complete'));
|
||||
expect(selectQueries.length).toBeGreaterThanOrEqual(1);
|
||||
|
||||
for (const q of selectQueries) {
|
||||
expect(q.text).toMatch(/status\s*=\s*'\s*complete\s*'/i);
|
||||
expect(q.text).toMatch(/user_id\s*=/i);
|
||||
expect(q.params).toContain(42);
|
||||
}
|
||||
}
|
||||
),
|
||||
{ numRuns: 20, verbose: 2 }
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* Property 2d: Other users' items remain untouched
|
||||
*
|
||||
* The SELECT query is parameterized with req.user.id (mocked as 42).
|
||||
* For any random count of completed items, the query only affects user 42's items.
|
||||
* We verify the user_id parameter is always the authenticated user's ID.
|
||||
*
|
||||
* **Validates: Requirements 3.1, 3.3**
|
||||
*/
|
||||
it('Property 2d: DELETE is scoped to the authenticated user only', async () => {
|
||||
await fc.assert(
|
||||
fc.asyncProperty(
|
||||
fc.integer({ min: 1, max: 10 }),
|
||||
fc.context(),
|
||||
async (completedCount, ctx) => {
|
||||
ctx.log(`Testing user isolation with ${completedCount} completed items`);
|
||||
|
||||
// Reset mocks for this iteration
|
||||
mockClient.query.mockReset();
|
||||
mockClient.release.mockReset();
|
||||
mockPool.connect.mockReset();
|
||||
mockPool.connect.mockResolvedValue(mockClient);
|
||||
|
||||
const queriesIssued = [];
|
||||
const itemIds = Array.from({ length: completedCount }, (_, i) => i + 1);
|
||||
|
||||
mockClient.query.mockImplementation((text, params) => {
|
||||
queriesIssued.push({ text, params });
|
||||
if (text === 'BEGIN') return Promise.resolve({ rows: [], rowCount: 0 });
|
||||
if (text.includes('SELECT') && text.includes('ivanti_todo_queue') && text.includes('complete')) {
|
||||
return Promise.resolve({ rows: itemIds.map(id => ({ id })), rowCount: completedCount });
|
||||
}
|
||||
if (text.includes('DELETE FROM jira_ticket_queue_items')) {
|
||||
return Promise.resolve({ rows: [], rowCount: 0 });
|
||||
}
|
||||
if (text.includes('DELETE FROM ivanti_todo_queue')) {
|
||||
return Promise.resolve({ rows: [], rowCount: completedCount });
|
||||
}
|
||||
if (text === 'COMMIT') return Promise.resolve({ rows: [], rowCount: 0 });
|
||||
if (text === 'ROLLBACK') return Promise.resolve({ rows: [], rowCount: 0 });
|
||||
return Promise.resolve({ rows: [], rowCount: 0 });
|
||||
});
|
||||
|
||||
const res = await request(server, 'DELETE', '/api/ivanti/todo-queue/completed');
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.body.deleted).toBe(completedCount);
|
||||
|
||||
// Verify the SELECT query is scoped to user 42
|
||||
const selectQueries = queriesIssued.filter(q => q.text.includes('SELECT') && q.text.includes('user_id'));
|
||||
for (const q of selectQueries) {
|
||||
expect(q.params).toContain(42); // req.user.id from mock
|
||||
}
|
||||
}
|
||||
),
|
||||
{ numRuns: 20, verbose: 2 }
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* Property 2e: Response shape is always { message: string, deleted: number }
|
||||
*
|
||||
* For any random count of completed items (including 0), the response
|
||||
* always has the correct shape with message as a string and deleted as a number.
|
||||
*
|
||||
* **Validates: Requirements 3.1, 3.2**
|
||||
*/
|
||||
it('Property 2e: response shape is { message: string, deleted: number }', async () => {
|
||||
await fc.assert(
|
||||
fc.asyncProperty(
|
||||
fc.integer({ min: 0, max: 50 }),
|
||||
fc.context(),
|
||||
async (completedCount, ctx) => {
|
||||
ctx.log(`Testing response shape with deleted count: ${completedCount}`);
|
||||
|
||||
// Reset mocks for this iteration
|
||||
mockClient.query.mockReset();
|
||||
mockClient.release.mockReset();
|
||||
mockPool.connect.mockReset();
|
||||
mockPool.connect.mockResolvedValue(mockClient);
|
||||
|
||||
const itemIds = Array.from({ length: completedCount }, (_, i) => i + 1);
|
||||
|
||||
mockClient.query.mockImplementation((text, params) => {
|
||||
if (text === 'BEGIN') return Promise.resolve({ rows: [], rowCount: 0 });
|
||||
if (text.includes('SELECT') && text.includes('ivanti_todo_queue') && text.includes('complete')) {
|
||||
return Promise.resolve({ rows: itemIds.map(id => ({ id })), rowCount: completedCount });
|
||||
}
|
||||
if (text.includes('DELETE FROM jira_ticket_queue_items')) {
|
||||
return Promise.resolve({ rows: [], rowCount: 0 });
|
||||
}
|
||||
if (text.includes('DELETE FROM ivanti_todo_queue')) {
|
||||
return Promise.resolve({ rows: [], rowCount: completedCount });
|
||||
}
|
||||
if (text === 'COMMIT') return Promise.resolve({ rows: [], rowCount: 0 });
|
||||
if (text === 'ROLLBACK') return Promise.resolve({ rows: [], rowCount: 0 });
|
||||
return Promise.resolve({ rows: [], rowCount: 0 });
|
||||
});
|
||||
|
||||
const res = await request(server, 'DELETE', '/api/ivanti/todo-queue/completed');
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(typeof res.body.message).toBe('string');
|
||||
expect(typeof res.body.deleted).toBe('number');
|
||||
expect(res.body.message).toBe('Completed items cleared.');
|
||||
expect(res.body.deleted).toBe(completedCount);
|
||||
}
|
||||
),
|
||||
{ numRuns: 25, verbose: 2 }
|
||||
);
|
||||
});
|
||||
});
|
||||
371
backend/__tests__/ivanti-queue-clear-completed-fix.test.js
Normal file
371
backend/__tests__/ivanti-queue-clear-completed-fix.test.js
Normal file
@@ -0,0 +1,371 @@
|
||||
/**
|
||||
* Unit tests for DELETE /api/ivanti/todo-queue/completed transaction logic
|
||||
*
|
||||
* Spec: .kiro/specs/ivanti-queue-clear-completed-fix/ (bugfix)
|
||||
*
|
||||
* Validates: Requirements 2.1, 2.2, 3.1, 3.2
|
||||
*
|
||||
* Tests verify:
|
||||
* - Correct query sequence within a transaction (BEGIN → SELECT → DELETE junction → DELETE queue → COMMIT)
|
||||
* - ROLLBACK is called when any query in the transaction fails
|
||||
* - Client is always released in the finally block (even on error)
|
||||
* - Empty completed set triggers early COMMIT and returns { deleted: 0 }
|
||||
* - Response shape is { message: 'Completed items cleared.', deleted: N }
|
||||
*/
|
||||
const http = require('http');
|
||||
const express = require('express');
|
||||
|
||||
// --- Mocks ---
|
||||
|
||||
jest.mock('../middleware/auth', () => ({
|
||||
requireAuth: () => (req, _res, next) => {
|
||||
req.user = { id: 7, username: 'testuser', group: 'Admin' };
|
||||
next();
|
||||
},
|
||||
requireGroup: () => (_req, _res, next) => next(),
|
||||
}));
|
||||
|
||||
jest.mock('../helpers/auditLog', () => jest.fn());
|
||||
|
||||
const mockClient = {
|
||||
query: jest.fn(),
|
||||
release: jest.fn(),
|
||||
};
|
||||
|
||||
const mockPool = {
|
||||
query: jest.fn(),
|
||||
connect: jest.fn(() => Promise.resolve(mockClient)),
|
||||
};
|
||||
|
||||
jest.mock('../db', () => mockPool);
|
||||
|
||||
const createIvantiTodoQueueRouter = require('../routes/ivantiTodoQueue');
|
||||
|
||||
// --- HTTP helper ---
|
||||
|
||||
function request(server, method, urlPath) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const addr = server.address();
|
||||
const options = {
|
||||
hostname: '127.0.0.1',
|
||||
port: addr.port,
|
||||
path: urlPath,
|
||||
method,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
};
|
||||
const req = http.request(options, (res) => {
|
||||
const chunks = [];
|
||||
res.on('data', (chunk) => chunks.push(chunk));
|
||||
res.on('end', () => {
|
||||
const raw = Buffer.concat(chunks).toString();
|
||||
let body;
|
||||
try { body = JSON.parse(raw); } catch { body = raw; }
|
||||
resolve({ statusCode: res.statusCode, body });
|
||||
});
|
||||
});
|
||||
req.on('error', reject);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
// --- Test Suite ---
|
||||
|
||||
describe('DELETE /api/ivanti/todo-queue/completed — Transaction Logic', () => {
|
||||
let app;
|
||||
let server;
|
||||
|
||||
beforeAll((done) => {
|
||||
app = express();
|
||||
app.use(express.json());
|
||||
app.use('/api/ivanti/todo-queue', createIvantiTodoQueueRouter());
|
||||
server = app.listen(0, '127.0.0.1', done);
|
||||
});
|
||||
|
||||
afterAll((done) => {
|
||||
server.close(done);
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
mockClient.query.mockReset();
|
||||
mockClient.release.mockReset();
|
||||
mockPool.connect.mockReset();
|
||||
mockPool.connect.mockResolvedValue(mockClient);
|
||||
});
|
||||
|
||||
/**
|
||||
* Test 1: Correct query sequence
|
||||
* Validates: Requirements 2.1, 2.2
|
||||
*
|
||||
* Verifies the handler issues queries in the correct order:
|
||||
* BEGIN → SELECT IDs → DELETE junction → DELETE queue → COMMIT
|
||||
*/
|
||||
it('executes queries in correct transaction order: BEGIN → SELECT → DELETE junction → DELETE queue → COMMIT', async () => {
|
||||
const completedIds = [10, 20, 30];
|
||||
|
||||
mockClient.query
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }) // BEGIN
|
||||
.mockResolvedValueOnce({ rows: completedIds.map(id => ({ id })), rowCount: 3 }) // SELECT
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 2 }) // DELETE junction
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 3 }) // DELETE queue
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }); // COMMIT
|
||||
|
||||
const res = await request(server, 'DELETE', '/api/ivanti/todo-queue/completed');
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
|
||||
// Verify query sequence
|
||||
const calls = mockClient.query.mock.calls;
|
||||
expect(calls.length).toBe(5);
|
||||
|
||||
// BEGIN
|
||||
expect(calls[0][0]).toBe('BEGIN');
|
||||
|
||||
// SELECT completed IDs
|
||||
expect(calls[1][0]).toContain('SELECT');
|
||||
expect(calls[1][0]).toContain('ivanti_todo_queue');
|
||||
expect(calls[1][0]).toContain('complete');
|
||||
expect(calls[1][1]).toEqual([7]); // user id
|
||||
|
||||
// DELETE junction table references
|
||||
expect(calls[2][0]).toContain('DELETE FROM jira_ticket_queue_items');
|
||||
expect(calls[2][0]).toContain('ANY');
|
||||
expect(calls[2][1]).toEqual([completedIds]);
|
||||
|
||||
// DELETE queue items
|
||||
expect(calls[3][0]).toContain('DELETE FROM ivanti_todo_queue');
|
||||
expect(calls[3][0]).toContain('ANY');
|
||||
expect(calls[3][1]).toEqual([completedIds]);
|
||||
|
||||
// COMMIT
|
||||
expect(calls[4][0]).toBe('COMMIT');
|
||||
});
|
||||
|
||||
/**
|
||||
* Test 2: ROLLBACK on error
|
||||
* Validates: Requirements 2.1
|
||||
*
|
||||
* Verifies ROLLBACK is called when any query in the transaction fails.
|
||||
*/
|
||||
describe('ROLLBACK on error', () => {
|
||||
it('calls ROLLBACK when SELECT query fails', async () => {
|
||||
mockClient.query
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }) // BEGIN
|
||||
.mockRejectedValueOnce(new Error('SELECT failed')); // SELECT throws
|
||||
|
||||
// After the catch, ROLLBACK is called
|
||||
mockClient.query.mockResolvedValueOnce({ rows: [], rowCount: 0 }); // ROLLBACK
|
||||
|
||||
const res = await request(server, 'DELETE', '/api/ivanti/todo-queue/completed');
|
||||
|
||||
expect(res.statusCode).toBe(500);
|
||||
expect(res.body).toEqual({ error: 'Internal server error.' });
|
||||
|
||||
const calls = mockClient.query.mock.calls;
|
||||
const rollbackCall = calls.find(c => c[0] === 'ROLLBACK');
|
||||
expect(rollbackCall).toBeDefined();
|
||||
});
|
||||
|
||||
it('calls ROLLBACK when DELETE junction query fails', async () => {
|
||||
mockClient.query
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }) // BEGIN
|
||||
.mockResolvedValueOnce({ rows: [{ id: 1 }, { id: 2 }], rowCount: 2 }) // SELECT
|
||||
.mockRejectedValueOnce(new Error('DELETE junction failed')); // DELETE junction throws
|
||||
|
||||
mockClient.query.mockResolvedValueOnce({ rows: [], rowCount: 0 }); // ROLLBACK
|
||||
|
||||
const res = await request(server, 'DELETE', '/api/ivanti/todo-queue/completed');
|
||||
|
||||
expect(res.statusCode).toBe(500);
|
||||
expect(res.body).toEqual({ error: 'Internal server error.' });
|
||||
|
||||
const calls = mockClient.query.mock.calls;
|
||||
const rollbackCall = calls.find(c => c[0] === 'ROLLBACK');
|
||||
expect(rollbackCall).toBeDefined();
|
||||
});
|
||||
|
||||
it('calls ROLLBACK when DELETE queue query fails', async () => {
|
||||
mockClient.query
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }) // BEGIN
|
||||
.mockResolvedValueOnce({ rows: [{ id: 5 }], rowCount: 1 }) // SELECT
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 1 }) // DELETE junction
|
||||
.mockRejectedValueOnce(new Error('DELETE queue failed')); // DELETE queue throws
|
||||
|
||||
mockClient.query.mockResolvedValueOnce({ rows: [], rowCount: 0 }); // ROLLBACK
|
||||
|
||||
const res = await request(server, 'DELETE', '/api/ivanti/todo-queue/completed');
|
||||
|
||||
expect(res.statusCode).toBe(500);
|
||||
expect(res.body).toEqual({ error: 'Internal server error.' });
|
||||
|
||||
const calls = mockClient.query.mock.calls;
|
||||
const rollbackCall = calls.find(c => c[0] === 'ROLLBACK');
|
||||
expect(rollbackCall).toBeDefined();
|
||||
});
|
||||
|
||||
it('calls ROLLBACK when COMMIT fails', async () => {
|
||||
mockClient.query
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }) // BEGIN
|
||||
.mockResolvedValueOnce({ rows: [{ id: 1 }], rowCount: 1 }) // SELECT
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 1 }) // DELETE junction
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 1 }) // DELETE queue
|
||||
.mockRejectedValueOnce(new Error('COMMIT failed')); // COMMIT throws
|
||||
|
||||
mockClient.query.mockResolvedValueOnce({ rows: [], rowCount: 0 }); // ROLLBACK
|
||||
|
||||
const res = await request(server, 'DELETE', '/api/ivanti/todo-queue/completed');
|
||||
|
||||
expect(res.statusCode).toBe(500);
|
||||
expect(res.body).toEqual({ error: 'Internal server error.' });
|
||||
|
||||
const calls = mockClient.query.mock.calls;
|
||||
const rollbackCall = calls.find(c => c[0] === 'ROLLBACK');
|
||||
expect(rollbackCall).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Test 3: Client always released
|
||||
* Validates: Requirements 2.1
|
||||
*
|
||||
* Verifies client.release() is always called in the finally block,
|
||||
* even when an error occurs.
|
||||
*/
|
||||
describe('client always released', () => {
|
||||
it('releases client after successful transaction', async () => {
|
||||
mockClient.query
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }) // BEGIN
|
||||
.mockResolvedValueOnce({ rows: [{ id: 1 }], rowCount: 1 }) // SELECT
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 1 }) // DELETE junction
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 1 }) // DELETE queue
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }); // COMMIT
|
||||
|
||||
await request(server, 'DELETE', '/api/ivanti/todo-queue/completed');
|
||||
|
||||
expect(mockClient.release).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('releases client after failed transaction (error in SELECT)', async () => {
|
||||
mockClient.query
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }) // BEGIN
|
||||
.mockRejectedValueOnce(new Error('DB error')); // SELECT throws
|
||||
|
||||
mockClient.query.mockResolvedValueOnce({ rows: [], rowCount: 0 }); // ROLLBACK
|
||||
|
||||
await request(server, 'DELETE', '/api/ivanti/todo-queue/completed');
|
||||
|
||||
expect(mockClient.release).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('releases client after failed transaction (error in DELETE)', async () => {
|
||||
mockClient.query
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }) // BEGIN
|
||||
.mockResolvedValueOnce({ rows: [{ id: 1 }, { id: 2 }], rowCount: 2 }) // SELECT
|
||||
.mockRejectedValueOnce(new Error('FK violation')); // DELETE junction throws
|
||||
|
||||
mockClient.query.mockResolvedValueOnce({ rows: [], rowCount: 0 }); // ROLLBACK
|
||||
|
||||
await request(server, 'DELETE', '/api/ivanti/todo-queue/completed');
|
||||
|
||||
expect(mockClient.release).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('releases client when empty completed set triggers early return', async () => {
|
||||
mockClient.query
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }) // BEGIN
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }) // SELECT (empty)
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }); // COMMIT
|
||||
|
||||
await request(server, 'DELETE', '/api/ivanti/todo-queue/completed');
|
||||
|
||||
expect(mockClient.release).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Test 4: Empty completed set
|
||||
* Validates: Requirements 3.1, 3.2
|
||||
*
|
||||
* When SELECT returns no completed items, the handler should:
|
||||
* - Issue COMMIT (not ROLLBACK)
|
||||
* - Return { message: 'Completed items cleared.', deleted: 0 }
|
||||
* - NOT issue any DELETE queries
|
||||
*/
|
||||
it('empty completed set triggers early COMMIT and returns { deleted: 0 }', async () => {
|
||||
mockClient.query
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }) // BEGIN
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }) // SELECT (empty)
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }); // COMMIT
|
||||
|
||||
const res = await request(server, 'DELETE', '/api/ivanti/todo-queue/completed');
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.body).toEqual({ message: 'Completed items cleared.', deleted: 0 });
|
||||
|
||||
// Verify query sequence: BEGIN → SELECT → COMMIT (no DELETEs)
|
||||
const calls = mockClient.query.mock.calls;
|
||||
expect(calls.length).toBe(3);
|
||||
expect(calls[0][0]).toBe('BEGIN');
|
||||
expect(calls[1][0]).toContain('SELECT');
|
||||
expect(calls[2][0]).toBe('COMMIT');
|
||||
|
||||
// No DELETE queries issued
|
||||
const deleteQueries = calls.filter(c => c[0].includes('DELETE'));
|
||||
expect(deleteQueries.length).toBe(0);
|
||||
});
|
||||
|
||||
/**
|
||||
* Test 5: Response shape preserved
|
||||
* Validates: Requirements 2.2, 3.1
|
||||
*
|
||||
* Verifies the response is always { message: 'Completed items cleared.', deleted: N }
|
||||
*/
|
||||
describe('response shape preserved', () => {
|
||||
it('returns correct shape with deleted count matching rowCount', async () => {
|
||||
mockClient.query
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }) // BEGIN
|
||||
.mockResolvedValueOnce({ rows: [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }], rowCount: 5 }) // SELECT
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 3 }) // DELETE junction
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 5 }) // DELETE queue
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }); // COMMIT
|
||||
|
||||
const res = await request(server, 'DELETE', '/api/ivanti/todo-queue/completed');
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.body).toEqual({
|
||||
message: 'Completed items cleared.',
|
||||
deleted: 5,
|
||||
});
|
||||
});
|
||||
|
||||
it('returns correct shape with single deleted item', async () => {
|
||||
mockClient.query
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }) // BEGIN
|
||||
.mockResolvedValueOnce({ rows: [{ id: 99 }], rowCount: 1 }) // SELECT
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }) // DELETE junction
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 1 }) // DELETE queue
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }); // COMMIT
|
||||
|
||||
const res = await request(server, 'DELETE', '/api/ivanti/todo-queue/completed');
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.body).toEqual({
|
||||
message: 'Completed items cleared.',
|
||||
deleted: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it('returns error shape on failure', async () => {
|
||||
mockClient.query
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }) // BEGIN
|
||||
.mockRejectedValueOnce(new Error('Something broke')); // SELECT throws
|
||||
|
||||
mockClient.query.mockResolvedValueOnce({ rows: [], rowCount: 0 }); // ROLLBACK
|
||||
|
||||
const res = await request(server, 'DELETE', '/api/ivanti/todo-queue/completed');
|
||||
|
||||
expect(res.statusCode).toBe(500);
|
||||
expect(res.body).toEqual({ error: 'Internal server error.' });
|
||||
});
|
||||
});
|
||||
});
|
||||
115
backend/__tests__/migrations-idempotency.integration.test.js
Normal file
115
backend/__tests__/migrations-idempotency.integration.test.js
Normal file
@@ -0,0 +1,115 @@
|
||||
// Migration Idempotency Integration Test
|
||||
// This test requires a running PostgreSQL instance with DATABASE_URL configured in backend/.env.
|
||||
// It runs ALL Postgres migrations twice (via run-all.js) to verify they are idempotent (safe to re-run),
|
||||
// then checks that key tables and columns exist.
|
||||
//
|
||||
// SKIPS AUTOMATICALLY when DATABASE_URL is not set (e.g., in CI environments without DB access).
|
||||
//
|
||||
// Run separately: npx jest backend/__tests__/migrations-idempotency.integration.test.js --forceExit
|
||||
|
||||
const { execSync } = require('child_process');
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
|
||||
const BACKEND_DIR = path.join(__dirname, '..');
|
||||
|
||||
// Load .env manually to check for DATABASE_URL without triggering db.js process.exit
|
||||
function loadEnvFile() {
|
||||
const envPath = path.join(BACKEND_DIR, '.env');
|
||||
if (!fs.existsSync(envPath)) return {};
|
||||
const content = fs.readFileSync(envPath, 'utf8');
|
||||
const vars = {};
|
||||
for (const line of content.split('\n')) {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed || trimmed.startsWith('#')) continue;
|
||||
const eqIdx = trimmed.indexOf('=');
|
||||
if (eqIdx === -1) continue;
|
||||
vars[trimmed.slice(0, eqIdx)] = trimmed.slice(eqIdx + 1);
|
||||
}
|
||||
return vars;
|
||||
}
|
||||
|
||||
const envVars = loadEnvFile();
|
||||
const hasDatabase = !!(process.env.DATABASE_URL || envVars.DATABASE_URL);
|
||||
|
||||
// Skip entire suite if no database is available
|
||||
const describeIfDb = hasDatabase ? describe : describe.skip;
|
||||
|
||||
let pool;
|
||||
|
||||
if (hasDatabase) {
|
||||
// Set DATABASE_URL in process.env so db.js picks it up
|
||||
if (!process.env.DATABASE_URL && envVars.DATABASE_URL) {
|
||||
process.env.DATABASE_URL = envVars.DATABASE_URL;
|
||||
}
|
||||
pool = require('../db');
|
||||
}
|
||||
|
||||
function runAllMigrations() {
|
||||
execSync('node migrations/run-all.js', {
|
||||
cwd: BACKEND_DIR,
|
||||
stdio: 'pipe',
|
||||
timeout: 30000,
|
||||
});
|
||||
}
|
||||
|
||||
afterAll(async () => {
|
||||
if (pool) await pool.end();
|
||||
});
|
||||
|
||||
describeIfDb('Migration Idempotency', () => {
|
||||
it('runs all migrations twice without errors (idempotent)', () => {
|
||||
// First run
|
||||
runAllMigrations();
|
||||
// Second run — should not throw if migrations are truly idempotent
|
||||
runAllMigrations();
|
||||
}, 30000);
|
||||
|
||||
it('key tables exist after migrations', async () => {
|
||||
const expectedTables = [
|
||||
'compliance_items',
|
||||
'compliance_item_history',
|
||||
'compliance_notes',
|
||||
'jira_tickets',
|
||||
'ivanti_fp_submissions',
|
||||
];
|
||||
|
||||
const { rows } = await pool.query(`
|
||||
SELECT table_name
|
||||
FROM information_schema.tables
|
||||
WHERE table_schema = 'public'
|
||||
AND table_name = ANY($1)
|
||||
`, [expectedTables]);
|
||||
|
||||
const foundTables = rows.map(r => r.table_name);
|
||||
for (const table of expectedTables) {
|
||||
expect(foundTables).toContain(table);
|
||||
}
|
||||
}, 30000);
|
||||
|
||||
it('compliance_item_history has expected columns', async () => {
|
||||
const expectedColumns = [
|
||||
'id',
|
||||
'hostname',
|
||||
'field_name',
|
||||
'old_value',
|
||||
'new_value',
|
||||
'change_reason',
|
||||
'changed_by',
|
||||
'changed_at',
|
||||
'metric_id',
|
||||
];
|
||||
|
||||
const { rows } = await pool.query(`
|
||||
SELECT column_name
|
||||
FROM information_schema.columns
|
||||
WHERE table_schema = 'public'
|
||||
AND table_name = 'compliance_item_history'
|
||||
`);
|
||||
|
||||
const foundColumns = rows.map(r => r.column_name);
|
||||
for (const col of expectedColumns) {
|
||||
expect(foundColumns).toContain(col);
|
||||
}
|
||||
}, 30000);
|
||||
});
|
||||
190
backend/__tests__/vendor-issue-type-dropdown.property.test.js
Normal file
190
backend/__tests__/vendor-issue-type-dropdown.property.test.js
Normal file
@@ -0,0 +1,190 @@
|
||||
/**
|
||||
* Property-Based Tests: Vendor Issue Type Dropdown
|
||||
*
|
||||
* Feature: vendor-issue-type-dropdown
|
||||
*
|
||||
* Tests the pure determination logic that decides which issue type list
|
||||
* to display based on the project key input.
|
||||
*
|
||||
* Validates: Requirements 1.2, 1.3, 1.4, 1.5, 2.1, 2.3, 3.4, 3.5, 4.1, 4.2, 6.3
|
||||
*/
|
||||
|
||||
const fc = require('fast-check');
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Replicate the pure functions from JiraPage.js for testing
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const VENDOR_PROJECT_KEYS = [
|
||||
'AA_ADTRAN',
|
||||
'AA_ADVA',
|
||||
'AA_CASA',
|
||||
'AA_CISCO',
|
||||
'AACOMMSCOP',
|
||||
'AA_COMMSCOP',
|
||||
'AA_HARMONI',
|
||||
'AA_JUNIPER',
|
||||
'AA_VECIMA',
|
||||
'AA_VIAVI',
|
||||
];
|
||||
|
||||
const VENDOR_ISSUE_TYPES = [
|
||||
'Epic',
|
||||
'Story',
|
||||
'Task',
|
||||
'Defect',
|
||||
'Production Defect/Incident Fix',
|
||||
'New Feature',
|
||||
'Spike',
|
||||
'Release Candidate',
|
||||
'Documentation',
|
||||
];
|
||||
|
||||
const STEAM_ISSUE_TYPES = [
|
||||
'Story',
|
||||
'Epic',
|
||||
'Program',
|
||||
'Project',
|
||||
'Reservation',
|
||||
'Automation Maintenance',
|
||||
];
|
||||
|
||||
function isVendorProject(projectKey, vendorKeys) {
|
||||
if (!projectKey || typeof projectKey !== 'string') return false;
|
||||
const normalized = projectKey.trim().toUpperCase();
|
||||
if (normalized.length === 0) return false;
|
||||
return vendorKeys.includes(normalized);
|
||||
}
|
||||
|
||||
function getIssueTypesForProject(projectKey, vendorKeys, vendorTypes, steamTypes) {
|
||||
return isVendorProject(projectKey, vendorKeys) ? vendorTypes : steamTypes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Simulates the project_key onChange logic: resets issue_type only on context switch.
|
||||
*/
|
||||
function simulateProjectKeyChange(oldKey, newKey, currentIssueType, vendorKeys) {
|
||||
const wasVendor = isVendorProject(oldKey, vendorKeys);
|
||||
const isNowVendor = isVendorProject(newKey, vendorKeys);
|
||||
return (wasVendor !== isNowVendor) ? '' : currentIssueType;
|
||||
}
|
||||
|
||||
// Helper: generate a vendor key with random casing and optional whitespace
|
||||
const arbVendorKey = fc.constantFrom(...VENDOR_PROJECT_KEYS).chain(key =>
|
||||
fc.oneof(
|
||||
fc.constant(key),
|
||||
fc.constant(key.toLowerCase()),
|
||||
fc.constant(` ${key} `),
|
||||
)
|
||||
);
|
||||
|
||||
// Helper: generate a string that does NOT match any vendor key after normalization
|
||||
const arbNonVendorKey = fc.string({ minLength: 0, maxLength: 50 }).filter(s => {
|
||||
const normalized = s.trim().toUpperCase();
|
||||
return !VENDOR_PROJECT_KEYS.includes(normalized);
|
||||
});
|
||||
|
||||
const arbNonVendorKeyNonEmpty = fc.string({ minLength: 1, maxLength: 30 }).filter(s => {
|
||||
const normalized = s.trim().toUpperCase();
|
||||
return !VENDOR_PROJECT_KEYS.includes(normalized) && normalized.length > 0;
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Property 1: Issue type list determination
|
||||
// ---------------------------------------------------------------------------
|
||||
describe('Feature: vendor-issue-type-dropdown, Property 1: Issue type list determination', () => {
|
||||
it('returns VENDOR_ISSUE_TYPES when project key matches a vendor key (case-insensitive, trimmed)', () => {
|
||||
fc.assert(
|
||||
fc.property(arbVendorKey, (key) => {
|
||||
const result = getIssueTypesForProject(key, VENDOR_PROJECT_KEYS, VENDOR_ISSUE_TYPES, STEAM_ISSUE_TYPES);
|
||||
expect(result).toBe(VENDOR_ISSUE_TYPES);
|
||||
}),
|
||||
{ numRuns: 100 }
|
||||
);
|
||||
});
|
||||
|
||||
it('returns STEAM_ISSUE_TYPES for any string that does not match a vendor key after normalization', () => {
|
||||
fc.assert(
|
||||
fc.property(arbNonVendorKey, (key) => {
|
||||
const result = getIssueTypesForProject(key, VENDOR_PROJECT_KEYS, VENDOR_ISSUE_TYPES, STEAM_ISSUE_TYPES);
|
||||
expect(result).toBe(STEAM_ISSUE_TYPES);
|
||||
}),
|
||||
{ numRuns: 100 }
|
||||
);
|
||||
});
|
||||
|
||||
it('returns STEAM_ISSUE_TYPES for null, undefined, and empty string', () => {
|
||||
const emptyInputs = fc.oneof(
|
||||
fc.constant(null),
|
||||
fc.constant(undefined),
|
||||
fc.constant(''),
|
||||
fc.constant(' '),
|
||||
);
|
||||
|
||||
fc.assert(
|
||||
fc.property(emptyInputs, (key) => {
|
||||
const result = getIssueTypesForProject(key, VENDOR_PROJECT_KEYS, VENDOR_ISSUE_TYPES, STEAM_ISSUE_TYPES);
|
||||
expect(result).toBe(STEAM_ISSUE_TYPES);
|
||||
}),
|
||||
{ numRuns: 100 }
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Property 2: Context switch resets issue type selection
|
||||
// ---------------------------------------------------------------------------
|
||||
describe('Feature: vendor-issue-type-dropdown, Property 2: Context switch resets issue type', () => {
|
||||
it('resets issue_type to empty when switching from vendor to non-vendor context', () => {
|
||||
const anyIssueType = fc.string({ minLength: 1, maxLength: 50 });
|
||||
|
||||
fc.assert(
|
||||
fc.property(arbVendorKey, arbNonVendorKeyNonEmpty, anyIssueType, (oldKey, newKey, issueType) => {
|
||||
const result = simulateProjectKeyChange(oldKey, newKey, issueType, VENDOR_PROJECT_KEYS);
|
||||
expect(result).toBe('');
|
||||
}),
|
||||
{ numRuns: 100 }
|
||||
);
|
||||
});
|
||||
|
||||
it('resets issue_type to empty when switching from non-vendor to vendor context', () => {
|
||||
const anyIssueType = fc.string({ minLength: 1, maxLength: 50 });
|
||||
|
||||
fc.assert(
|
||||
fc.property(arbNonVendorKeyNonEmpty, arbVendorKey, anyIssueType, (oldKey, newKey, issueType) => {
|
||||
const result = simulateProjectKeyChange(oldKey, newKey, issueType, VENDOR_PROJECT_KEYS);
|
||||
expect(result).toBe('');
|
||||
}),
|
||||
{ numRuns: 100 }
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Property 3: Same context preserves issue type selection
|
||||
// ---------------------------------------------------------------------------
|
||||
describe('Feature: vendor-issue-type-dropdown, Property 3: Same context preserves issue type', () => {
|
||||
it('preserves issue_type when both old and new keys resolve to STEAM context', () => {
|
||||
const anyIssueType = fc.string({ minLength: 0, maxLength: 50 });
|
||||
|
||||
fc.assert(
|
||||
fc.property(arbNonVendorKey, arbNonVendorKey, anyIssueType, (oldKey, newKey, issueType) => {
|
||||
const result = simulateProjectKeyChange(oldKey, newKey, issueType, VENDOR_PROJECT_KEYS);
|
||||
expect(result).toBe(issueType);
|
||||
}),
|
||||
{ numRuns: 100 }
|
||||
);
|
||||
});
|
||||
|
||||
it('preserves issue_type when both old and new keys resolve to vendor context', () => {
|
||||
const anyIssueType = fc.string({ minLength: 0, maxLength: 50 });
|
||||
|
||||
fc.assert(
|
||||
fc.property(arbVendorKey, arbVendorKey, anyIssueType, (oldKey, newKey, issueType) => {
|
||||
const result = simulateProjectKeyChange(oldKey, newKey, issueType, VENDOR_PROJECT_KEYS);
|
||||
expect(result).toBe(issueType);
|
||||
}),
|
||||
{ numRuns: 100 }
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -9,6 +9,11 @@
|
||||
|
||||
const https = require('https');
|
||||
const http = require('http');
|
||||
const dns = require('dns');
|
||||
|
||||
// Force IPv4-first DNS resolution — card.charter.com has both IPv4 and IPv6
|
||||
// records but IPv6 is unreachable from this network, causing timeouts.
|
||||
dns.setDefaultResultOrder('ipv4first');
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Configuration — read from process.env at module load
|
||||
@@ -57,12 +62,13 @@ function acquireToken(timeout) {
|
||||
port: fullUrl.port || (isHttps ? 443 : 80),
|
||||
path: fullUrl.pathname + fullUrl.search,
|
||||
method: 'POST',
|
||||
family: 4, // Force IPv4 — IPv6 is unreachable from this network
|
||||
headers: {
|
||||
'accept': 'application/json',
|
||||
'authorization': 'Basic ' + authString,
|
||||
'content-length': '0',
|
||||
},
|
||||
timeout: timeout || 15000,
|
||||
timeout: timeout || 30000,
|
||||
};
|
||||
|
||||
if (isHttps) {
|
||||
@@ -123,7 +129,7 @@ async function ensureToken(timeout) {
|
||||
// Generic request — supports GET and POST with Bearer auth + 401 retry
|
||||
// ---------------------------------------------------------------------------
|
||||
async function cardRequest(method, urlPath, body, options) {
|
||||
const timeout = (options && options.timeout) || 15000;
|
||||
const timeout = (options && options.timeout) || 30000;
|
||||
const skipAuth = (options && options.skipAuth) || false;
|
||||
|
||||
async function doRequest(bearerToken) {
|
||||
@@ -150,6 +156,7 @@ async function cardRequest(method, urlPath, body, options) {
|
||||
port: fullUrl.port || (isHttps ? 443 : 80),
|
||||
path: fullUrl.pathname + fullUrl.search,
|
||||
method,
|
||||
family: 4, // Force IPv4 — IPv6 is unreachable from this network
|
||||
headers,
|
||||
timeout,
|
||||
};
|
||||
@@ -288,6 +295,43 @@ async function redirectAsset(assetId, fromTeam, toTeam, updateToken) {
|
||||
return { status: res.status, body: res.body, ok: res.status >= 200 && res.status < 300 };
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a bare IP address to a full CARD asset ID by trying known suffixes.
|
||||
* Returns the first asset ID that returns a valid owner record, or null if none found.
|
||||
*/
|
||||
async function resolveAssetId(ip) {
|
||||
const SUFFIXES = ['CTEC', 'NATL', 'CHTR', 'COML', 'RESI', 'WIFI', 'VOIP'];
|
||||
const trimmedIp = (ip || '').trim();
|
||||
if (!trimmedIp) return null;
|
||||
|
||||
// If it already has a suffix (contains a dash followed by letters), use as-is
|
||||
if (/\d+-[A-Z]+$/i.test(trimmedIp)) {
|
||||
const result = await getOwner(trimmedIp);
|
||||
if (result.ok) return trimmedIp;
|
||||
}
|
||||
|
||||
// Try each suffix
|
||||
for (const suffix of SUFFIXES) {
|
||||
const candidate = `${trimmedIp}-${suffix}`;
|
||||
try {
|
||||
const result = await getOwner(candidate);
|
||||
if (result.ok) return candidate;
|
||||
} catch (_) {
|
||||
// Continue to next suffix
|
||||
}
|
||||
}
|
||||
|
||||
// Try bare IP as last resort
|
||||
try {
|
||||
const result = await getOwner(trimmedIp);
|
||||
if (result.ok) return trimmedIp;
|
||||
} catch (_) {
|
||||
// Not found
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
isConfigured,
|
||||
missingVars,
|
||||
@@ -302,4 +346,5 @@ module.exports = {
|
||||
declineAsset,
|
||||
redirectAsset,
|
||||
invalidateToken,
|
||||
resolveAssetId,
|
||||
};
|
||||
|
||||
42
backend/migrations/add_compliance_history_metric_id.js
Normal file
42
backend/migrations/add_compliance_history_metric_id.js
Normal file
@@ -0,0 +1,42 @@
|
||||
const pool = require('../db');
|
||||
|
||||
async function run() {
|
||||
console.log('Starting compliance_item_history metric_id column migration...');
|
||||
try {
|
||||
// Idempotent: only add column if it doesn't already exist
|
||||
const { rows } = await pool.query(`
|
||||
SELECT column_name
|
||||
FROM information_schema.columns
|
||||
WHERE table_name = 'compliance_item_history'
|
||||
AND column_name = 'metric_id'
|
||||
`);
|
||||
|
||||
if (rows.length === 0) {
|
||||
await pool.query(`
|
||||
ALTER TABLE compliance_item_history
|
||||
ADD COLUMN metric_id TEXT
|
||||
`);
|
||||
console.log('✓ metric_id column added to compliance_item_history');
|
||||
} else {
|
||||
console.log('✓ metric_id column already exists (skipped)');
|
||||
}
|
||||
|
||||
await pool.query(`
|
||||
CREATE INDEX IF NOT EXISTS idx_compliance_history_hostname_metric
|
||||
ON compliance_item_history(hostname, metric_id)
|
||||
`);
|
||||
console.log('✓ hostname/metric_id index created');
|
||||
|
||||
console.log('Migration complete.');
|
||||
} catch (err) {
|
||||
console.error('Migration failed:', err.message);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { run };
|
||||
|
||||
// Self-execute when run directly
|
||||
if (require.main === module) {
|
||||
run().then(() => process.exit(0)).catch(() => process.exit(1));
|
||||
}
|
||||
@@ -25,6 +25,7 @@ const POSTGRES_MIGRATIONS = [
|
||||
'add_flexible_jira_ticket_creation.js',
|
||||
'add_multi_item_jira_ticket.js',
|
||||
'drop_jira_status_check_constraint.js',
|
||||
'add_compliance_history_metric_id.js',
|
||||
];
|
||||
|
||||
async function runAll() {
|
||||
|
||||
@@ -15,6 +15,7 @@ const {
|
||||
confirmAsset,
|
||||
declineAsset,
|
||||
redirectAsset,
|
||||
resolveAssetId,
|
||||
} = require('../helpers/cardApi');
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -52,7 +53,14 @@ function handleCardError(err, res) {
|
||||
function createCardApiRouter() {
|
||||
const router = express.Router();
|
||||
|
||||
// GET /status
|
||||
/**
|
||||
* GET /status
|
||||
*
|
||||
* Returns whether the CARD API integration is configured.
|
||||
*
|
||||
* @response 200 - { configured: true }
|
||||
* @response 503 - { configured: false, error: string, missingVars: string[] }
|
||||
*/
|
||||
router.get('/status', requireAuth(), (req, res) => {
|
||||
if (!isConfigured) {
|
||||
return res.status(503).json({ configured: false, error: 'CARD API is not configured.', missingVars });
|
||||
@@ -60,7 +68,14 @@ function createCardApiRouter() {
|
||||
res.json({ configured: true });
|
||||
});
|
||||
|
||||
// GET /teams
|
||||
/**
|
||||
* GET /teams
|
||||
*
|
||||
* Returns the list of teams from the CARD API.
|
||||
*
|
||||
* @response 200 - Array of team objects from CARD
|
||||
* @response 503 - { error: string, missingVars: string[] } — CARD not configured
|
||||
*/
|
||||
router.get('/teams', requireAuth(), requireGroup('Admin', 'Standard_User'), async (req, res) => {
|
||||
if (!isConfigured) {
|
||||
return res.status(503).json({ error: 'CARD API is not configured.', missingVars });
|
||||
@@ -82,7 +97,19 @@ function createCardApiRouter() {
|
||||
}
|
||||
});
|
||||
|
||||
// GET /teams/:teamName/assets
|
||||
/**
|
||||
* GET /teams/:teamName/assets
|
||||
*
|
||||
* Returns paginated assets for a team filtered by disposition.
|
||||
*
|
||||
* @param {string} teamName - Team name (path parameter)
|
||||
* @query {string} disposition - Required. Asset disposition filter.
|
||||
* @query {number} [page] - Page number for pagination.
|
||||
* @query {number} [page_size=50] - Number of results per page.
|
||||
* @response 200 - { assets: object[], total: number, ... } from CARD
|
||||
* @response 400 - { error: string } — missing disposition
|
||||
* @response 503 - { error: string, missingVars: string[] } — CARD not configured
|
||||
*/
|
||||
router.get('/teams/:teamName/assets', requireAuth(), requireGroup('Admin', 'Standard_User'), async (req, res) => {
|
||||
if (!isConfigured) {
|
||||
return res.status(503).json({ error: 'CARD API is not configured.', missingVars });
|
||||
@@ -133,7 +160,15 @@ function createCardApiRouter() {
|
||||
}
|
||||
});
|
||||
|
||||
// GET /owner/:assetId
|
||||
/**
|
||||
* GET /owner/:assetId
|
||||
*
|
||||
* Returns the CARD owner record for a given asset ID.
|
||||
*
|
||||
* @param {string} assetId - CARD asset identifier (path parameter)
|
||||
* @response 200 - CARD owner/asset object
|
||||
* @response 503 - { error: string, missingVars: string[] } — CARD not configured
|
||||
*/
|
||||
router.get('/owner/:assetId', requireAuth(), requireGroup('Admin', 'Standard_User'), async (req, res) => {
|
||||
if (!isConfigured) {
|
||||
return res.status(503).json({ error: 'CARD API is not configured.', missingVars });
|
||||
@@ -156,22 +191,48 @@ function createCardApiRouter() {
|
||||
}
|
||||
});
|
||||
|
||||
// POST /queue/:queueItemId/confirm
|
||||
/**
|
||||
* POST /queue/:queueItemId/confirm
|
||||
*
|
||||
* Confirms ownership of a CARD asset for a queue item. Fetches the owner
|
||||
* record to obtain the update_token, then calls the CARD confirm endpoint.
|
||||
* Marks the queue item as complete on success.
|
||||
*
|
||||
* @param {string} queueItemId - Queue item ID (path parameter)
|
||||
* @body {string} teamName - Team name to confirm ownership for (required)
|
||||
* @body {string} assetId - CARD asset identifier (required)
|
||||
* @body {string} [comment] - Optional comment for the confirmation
|
||||
* @response 200 - { success: true, cardResponse: object }
|
||||
* @response 400 - { error: string } — missing fields or item not pending
|
||||
* @response 404 - { error: string } — queue item not found
|
||||
* @response 502 - { error: string } — CARD API failure
|
||||
* @response 503 - { error: string, missingVars: string[] } — CARD not configured
|
||||
*/
|
||||
router.post('/queue/:queueItemId/confirm', requireAuth(), requireGroup('Admin', 'Standard_User'), async (req, res) => {
|
||||
if (!isConfigured) {
|
||||
return res.status(503).json({ error: 'CARD API is not configured.', missingVars });
|
||||
}
|
||||
|
||||
const { queueItemId } = req.params;
|
||||
const { teamName, assetId, comment } = req.body;
|
||||
const { teamName, assetId: rawAssetId, comment } = req.body;
|
||||
|
||||
if (!teamName || typeof teamName !== 'string' || !teamName.trim()) {
|
||||
return res.status(400).json({ error: 'teamName is required.' });
|
||||
}
|
||||
if (!assetId || typeof assetId !== 'string' || !assetId.trim()) {
|
||||
if (!rawAssetId || typeof rawAssetId !== 'string' || !rawAssetId.trim()) {
|
||||
return res.status(400).json({ error: 'assetId is required.' });
|
||||
}
|
||||
|
||||
// Resolve bare IP to full CARD asset ID
|
||||
let assetId = rawAssetId.trim();
|
||||
if (!/\d+-[A-Z]+$/i.test(assetId)) {
|
||||
const resolved = await resolveAssetId(assetId);
|
||||
if (!resolved) {
|
||||
return res.status(404).json({ error: `Asset not found in CARD for IP: ${assetId}` });
|
||||
}
|
||||
assetId = resolved;
|
||||
}
|
||||
|
||||
try {
|
||||
const { rows } = await pool.query(
|
||||
'SELECT * FROM ivanti_todo_queue WHERE id = $1 AND user_id = $2 AND workflow_type = $3',
|
||||
@@ -232,22 +293,48 @@ function createCardApiRouter() {
|
||||
}
|
||||
});
|
||||
|
||||
// POST /queue/:queueItemId/decline
|
||||
/**
|
||||
* POST /queue/:queueItemId/decline
|
||||
*
|
||||
* Declines ownership of a CARD asset for a queue item. Fetches the owner
|
||||
* record to obtain the update_token, then calls the CARD decline endpoint.
|
||||
* Marks the queue item as complete on success.
|
||||
*
|
||||
* @param {string} queueItemId - Queue item ID (path parameter)
|
||||
* @body {string} teamName - Team name declining ownership (required)
|
||||
* @body {string} assetId - CARD asset identifier (required)
|
||||
* @body {string} [comment] - Optional comment for the decline
|
||||
* @response 200 - { success: true, cardResponse: object }
|
||||
* @response 400 - { error: string } — missing fields or item not pending
|
||||
* @response 404 - { error: string } — queue item not found
|
||||
* @response 502 - { error: string } — CARD API failure
|
||||
* @response 503 - { error: string, missingVars: string[] } — CARD not configured
|
||||
*/
|
||||
router.post('/queue/:queueItemId/decline', requireAuth(), requireGroup('Admin', 'Standard_User'), async (req, res) => {
|
||||
if (!isConfigured) {
|
||||
return res.status(503).json({ error: 'CARD API is not configured.', missingVars });
|
||||
}
|
||||
|
||||
const { queueItemId } = req.params;
|
||||
const { teamName, assetId, comment } = req.body;
|
||||
const { teamName, assetId: rawAssetId, comment } = req.body;
|
||||
|
||||
if (!teamName || typeof teamName !== 'string' || !teamName.trim()) {
|
||||
return res.status(400).json({ error: 'teamName is required.' });
|
||||
}
|
||||
if (!assetId || typeof assetId !== 'string' || !assetId.trim()) {
|
||||
if (!rawAssetId || typeof rawAssetId !== 'string' || !rawAssetId.trim()) {
|
||||
return res.status(400).json({ error: 'assetId is required.' });
|
||||
}
|
||||
|
||||
// Resolve bare IP to full CARD asset ID
|
||||
let assetId = rawAssetId.trim();
|
||||
if (!/\d+-[A-Z]+$/i.test(assetId)) {
|
||||
const resolved = await resolveAssetId(assetId);
|
||||
if (!resolved) {
|
||||
return res.status(404).json({ error: `Asset not found in CARD for IP: ${assetId}` });
|
||||
}
|
||||
assetId = resolved;
|
||||
}
|
||||
|
||||
try {
|
||||
const { rows } = await pool.query(
|
||||
'SELECT * FROM ivanti_todo_queue WHERE id = $1 AND user_id = $2 AND workflow_type = $3',
|
||||
@@ -308,14 +395,30 @@ function createCardApiRouter() {
|
||||
}
|
||||
});
|
||||
|
||||
// POST /queue/:queueItemId/redirect
|
||||
/**
|
||||
* POST /queue/:queueItemId/redirect
|
||||
*
|
||||
* Redirects a CARD asset from one team to another for a queue item. Fetches
|
||||
* the owner record to obtain the update_token, then calls the CARD redirect
|
||||
* endpoint. Marks the queue item as complete on success.
|
||||
*
|
||||
* @param {string} queueItemId - Queue item ID (path parameter)
|
||||
* @body {string} fromTeam - Current owning team (required)
|
||||
* @body {string} toTeam - Target team to redirect to (required)
|
||||
* @body {string} assetId - CARD asset identifier (required)
|
||||
* @response 200 - { success: true, cardResponse: object }
|
||||
* @response 400 - { error: string } — missing fields or item not pending
|
||||
* @response 404 - { error: string } — queue item not found
|
||||
* @response 502 - { error: string } — CARD API failure
|
||||
* @response 503 - { error: string, missingVars: string[] } — CARD not configured
|
||||
*/
|
||||
router.post('/queue/:queueItemId/redirect', requireAuth(), requireGroup('Admin', 'Standard_User'), async (req, res) => {
|
||||
if (!isConfigured) {
|
||||
return res.status(503).json({ error: 'CARD API is not configured.', missingVars });
|
||||
}
|
||||
|
||||
const { queueItemId } = req.params;
|
||||
const { fromTeam, toTeam, assetId } = req.body;
|
||||
const { fromTeam, toTeam, assetId: rawAssetId } = req.body;
|
||||
|
||||
if (!fromTeam || typeof fromTeam !== 'string' || !fromTeam.trim()) {
|
||||
return res.status(400).json({ error: 'fromTeam is required.' });
|
||||
@@ -323,10 +426,20 @@ function createCardApiRouter() {
|
||||
if (!toTeam || typeof toTeam !== 'string' || !toTeam.trim()) {
|
||||
return res.status(400).json({ error: 'toTeam is required.' });
|
||||
}
|
||||
if (!assetId || typeof assetId !== 'string' || !assetId.trim()) {
|
||||
if (!rawAssetId || typeof rawAssetId !== 'string' || !rawAssetId.trim()) {
|
||||
return res.status(400).json({ error: 'assetId is required.' });
|
||||
}
|
||||
|
||||
// Resolve bare IP to full CARD asset ID (e.g., 10.240.78.110 → 10.240.78.110-CTEC)
|
||||
let assetId = rawAssetId.trim();
|
||||
if (!/\d+-[A-Z]+$/i.test(assetId)) {
|
||||
const resolved = await resolveAssetId(assetId);
|
||||
if (!resolved) {
|
||||
return res.status(404).json({ error: `Asset not found in CARD for IP: ${assetId}` });
|
||||
}
|
||||
assetId = resolved;
|
||||
}
|
||||
|
||||
try {
|
||||
const { rows } = await pool.query(
|
||||
'SELECT * FROM ivanti_todo_queue WHERE id = $1 AND user_id = $2 AND workflow_type = $3',
|
||||
@@ -387,7 +500,266 @@ function createCardApiRouter() {
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* GET /owner-lookup/:ip
|
||||
*
|
||||
* Resolve an IP to a CARD asset ID and return the full owner record.
|
||||
* Used by the CARD Action Modal to display ownership state before
|
||||
* confirm/decline/redirect operations.
|
||||
*
|
||||
* @param {string} ip - IP address (path parameter)
|
||||
* @response 200 - { asset_id, ip, confirmed, unconfirmed, declined, candidate, update_token }
|
||||
* @response 404 - { error: string } — IP not found in CARD
|
||||
* @response 503 - { error: string } — CARD not configured
|
||||
*/
|
||||
router.get('/owner-lookup/:ip', requireAuth(), requireGroup('Admin', 'Standard_User'), async (req, res) => {
|
||||
if (!isConfigured) {
|
||||
return res.status(503).json({ error: 'CARD API is not configured.', missingVars });
|
||||
}
|
||||
|
||||
const ip = req.params.ip;
|
||||
if (!ip || !ip.trim()) {
|
||||
return res.status(400).json({ error: 'IP address is required.' });
|
||||
}
|
||||
|
||||
// Resolve to full asset ID
|
||||
const assetId = await resolveAssetId(ip.trim());
|
||||
if (!assetId) {
|
||||
return res.status(404).json({ error: `Asset not found in CARD for IP: ${ip}` });
|
||||
}
|
||||
|
||||
// Fetch full owner record
|
||||
try {
|
||||
const ownerResult = await getOwner(assetId);
|
||||
if (!ownerResult.ok) {
|
||||
return res.status(ownerResult.status).json({ error: `Failed to fetch owner: HTTP ${ownerResult.status}` });
|
||||
}
|
||||
|
||||
const data = JSON.parse(ownerResult.body);
|
||||
const owner = data.owner || {};
|
||||
|
||||
res.json({
|
||||
asset_id: assetId,
|
||||
ip: ip.trim(),
|
||||
confirmed: owner.confirmed || null,
|
||||
unconfirmed: owner.unconfirmed || null,
|
||||
declined: owner.declined || [],
|
||||
candidate: owner.candidate || [],
|
||||
update_token: owner.update_token || null,
|
||||
});
|
||||
} catch (err) {
|
||||
return handleCardError(err, res);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /enrich-batch
|
||||
*
|
||||
* Batch lookup IPs in CARD to extract Granite loader fields. Fetches team
|
||||
* assets (paginated, across confirmed and unconfirmed dispositions) and
|
||||
* matches against the provided IPs. Returns enrichment results for each IP.
|
||||
*
|
||||
* @body {string[]} ips - Non-empty array of IP address strings (max 200)
|
||||
* @body {string} [team="NTS-AEO-STEAM"] - Team name to search assets under
|
||||
* @response 200 - { results: object[], enriched_count: number, not_found_count: number, total: number }
|
||||
* Each result: { ip: string, found: boolean, equip_inst_id: string|null, hostname: string|null, site_name?: string|null, mgmt_ip_asn?: string|null, responsible_team?: string|null, equipment_class?: string, equip_template?: string|null, equip_status?: string|null, serial_number?: string|null, error?: string }
|
||||
* @response 400 - { error: string } — invalid or empty ips array, or exceeds 200
|
||||
* @response 503 - { error: string, missingVars: string[] } — CARD not configured
|
||||
*/
|
||||
router.post('/enrich-batch', requireAuth(), requireGroup('Admin', 'Standard_User'), async (req, res) => {
|
||||
if (!isConfigured) {
|
||||
return res.status(503).json({ error: 'CARD API is not configured.', missingVars });
|
||||
}
|
||||
|
||||
const { ips, team } = req.body || {};
|
||||
if (!Array.isArray(ips) || ips.length === 0) {
|
||||
return res.status(400).json({ error: 'ips must be a non-empty array of IP address strings.' });
|
||||
}
|
||||
if (ips.length > 200) {
|
||||
return res.status(400).json({ error: 'Maximum 200 IPs per request.' });
|
||||
}
|
||||
|
||||
// Build a set of IPs we're looking for
|
||||
const targetIps = new Set(ips.map(ip => (ip || '').trim()).filter(Boolean));
|
||||
const resultMap = {};
|
||||
|
||||
// Strategy: fetch team assets (paginated) and match against our target IPs.
|
||||
// The team assets endpoint returns the full enriched record with ncim_discovery,
|
||||
// card_flags, netops_granite_allips, etc.
|
||||
const teams = team ? [team] : ['NTS-AEO-STEAM', 'NTS-AEO-ACCESS-ENG'];
|
||||
const dispositions = ['confirmed', 'unconfirmed', 'candidate'];
|
||||
let foundCount = 0;
|
||||
|
||||
for (const teamName of teams) {
|
||||
if (foundCount >= targetIps.size) break;
|
||||
|
||||
for (const disposition of dispositions) {
|
||||
if (foundCount >= targetIps.size) break;
|
||||
|
||||
let page = 1;
|
||||
const pageSize = 200;
|
||||
let hasMore = true;
|
||||
|
||||
while (hasMore && foundCount < targetIps.size) {
|
||||
try {
|
||||
const result = await getTeamAssets(teamName, { disposition, page, pageSize });
|
||||
if (!result.ok) break;
|
||||
|
||||
const data = JSON.parse(result.body);
|
||||
const assets = data.assets || data.results || (Array.isArray(data) ? data : []);
|
||||
|
||||
if (assets.length === 0) {
|
||||
hasMore = false;
|
||||
break;
|
||||
}
|
||||
|
||||
// Match assets against target IPs
|
||||
for (const asset of assets) {
|
||||
const assetId = asset._id || '';
|
||||
// Extract IP from asset ID (e.g., "10.240.78.110-CTEC" → "10.240.78.110")
|
||||
const assetIp = assetId.replace(/-[A-Z]+$/i, '');
|
||||
|
||||
if (targetIps.has(assetIp) && !resultMap[assetIp]) {
|
||||
resultMap[assetIp] = extractGraniteFields(asset, assetIp);
|
||||
foundCount++;
|
||||
}
|
||||
}
|
||||
|
||||
// Check if there are more pages
|
||||
const total = data.total || data.count || 0;
|
||||
if (page * pageSize >= total || assets.length < pageSize) {
|
||||
hasMore = false;
|
||||
} else {
|
||||
page++;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`[card-api] enrich-batch: Error fetching ${teamName}/${disposition} page ${page}:`, err.message);
|
||||
hasMore = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Build results array in the same order as input IPs
|
||||
const results = [];
|
||||
let enrichedCount = 0;
|
||||
let notFoundCount = 0;
|
||||
|
||||
for (const ip of ips) {
|
||||
const trimmedIp = (ip || '').trim();
|
||||
if (!trimmedIp) {
|
||||
results.push({ ip: '', found: false, equip_inst_id: null, hostname: null, error: 'Invalid IP' });
|
||||
notFoundCount++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (resultMap[trimmedIp]) {
|
||||
results.push({ ip: trimmedIp, found: true, ...resultMap[trimmedIp] });
|
||||
enrichedCount++;
|
||||
} else {
|
||||
results.push({ ip: trimmedIp, found: false, equip_inst_id: null, hostname: null, error: 'IP not found in CARD team assets' });
|
||||
notFoundCount++;
|
||||
}
|
||||
}
|
||||
|
||||
res.json({ results, enriched_count: enrichedCount, not_found_count: notFoundCount, total: ips.length });
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract Granite-relevant fields from a CARD asset/owner record.
|
||||
* The owner endpoint returns: owner (confirmed/unconfirmed/etc), card_flags, tmp.
|
||||
* ncim_discovery is only available from the team assets endpoint.
|
||||
*/
|
||||
function extractGraniteFields(asset, ip) {
|
||||
// card_flags can be an array or nested in the response differently
|
||||
let flags = {};
|
||||
if (asset.card_flags) {
|
||||
flags = Array.isArray(asset.card_flags) ? (asset.card_flags[0] || {}) : asset.card_flags;
|
||||
}
|
||||
// Also check if flags are at the top level (owner endpoint format)
|
||||
if (!flags.CARD_HOSTNAME && asset.CARD_HOSTNAME) {
|
||||
flags = asset;
|
||||
}
|
||||
|
||||
const ncim = asset.ncim_discovery || [];
|
||||
const granite = asset.netops_granite_allips || [];
|
||||
const iseGranite = asset.ise_granite_equipment || [];
|
||||
const qualys = asset.qualys_hosts || [];
|
||||
const ivanti = asset.ivanti_assets || [];
|
||||
|
||||
// EQUIP_INST_ID — from ncim_discovery or granite (only available from team assets endpoint)
|
||||
let equip_inst_id = null;
|
||||
let site_name = null;
|
||||
let responsible_team = null;
|
||||
let hostname = null;
|
||||
|
||||
if (ncim.length > 0) {
|
||||
equip_inst_id = ncim[0].EQUIP_INST_ID || null;
|
||||
responsible_team = ncim[0].GRANITE_RESP_TEAM || ncim[0].RESPONSIBLE_TEAM || null;
|
||||
site_name = ncim[0].SITE_NAME || ncim[0].SITENAME || null;
|
||||
hostname = ncim[0].HOSTNAME || null;
|
||||
}
|
||||
|
||||
if (!equip_inst_id && Array.isArray(granite) && granite.length > 0) {
|
||||
equip_inst_id = granite[0].EQUIP_INST_ID || null;
|
||||
if (!site_name) site_name = granite[0].SITE_NAME || null;
|
||||
if (!responsible_team) responsible_team = granite[0].RESPONSIBLE_TEAM || null;
|
||||
}
|
||||
|
||||
if (!equip_inst_id && Array.isArray(iseGranite) && iseGranite.length > 0) {
|
||||
equip_inst_id = iseGranite[0].EQUIP_INST_ID || null;
|
||||
}
|
||||
|
||||
// Hostname from card_flags (primary source from owner endpoint)
|
||||
if (!hostname && flags.CARD_HOSTNAME) {
|
||||
const hostnames = Array.isArray(flags.CARD_HOSTNAME) ? flags.CARD_HOSTNAME : [flags.CARD_HOSTNAME];
|
||||
hostname = hostnames[0] || null;
|
||||
}
|
||||
if (!hostname && qualys.length > 0) hostname = qualys[0].HOSTNAME || null;
|
||||
if (!hostname && ivanti.length > 0) hostname = ivanti[0].hostName || null;
|
||||
|
||||
// ASN from card_flags
|
||||
const mgmt_ip_asn = flags.CARD_ASN || null;
|
||||
|
||||
// CLLI → can be used as site hint
|
||||
if (!site_name && flags.CARD_CLLI) {
|
||||
site_name = flags.CARD_CLLI; // CLLI code, not full site name — user may need to map
|
||||
}
|
||||
|
||||
// Equipment class — always S (Shelf) from CARD context
|
||||
const equipment_class = 'S';
|
||||
|
||||
// Device ID → maps to SERIALNUMBER in Granite
|
||||
const serial_number = flags.CARD_DEVICE_ID || null;
|
||||
|
||||
// Equip status from flags
|
||||
const equip_status = flags.status || null;
|
||||
|
||||
// Vendor/model from card_flags
|
||||
let equip_template = null;
|
||||
if (flags.CARD_VENDOR_MODEL && Array.isArray(flags.CARD_VENDOR_MODEL) && flags.CARD_VENDOR_MODEL.length > 0) {
|
||||
const vm = flags.CARD_VENDOR_MODEL[0];
|
||||
equip_template = typeof vm === 'string' ? vm : (vm.vendor_model || null);
|
||||
}
|
||||
|
||||
// Confirmed team from owner record
|
||||
const confirmed_team = asset.owner && asset.owner.confirmed
|
||||
? asset.owner.confirmed.name : null;
|
||||
|
||||
return {
|
||||
equip_inst_id: equip_inst_id ? String(equip_inst_id) : null,
|
||||
hostname,
|
||||
site_name,
|
||||
mgmt_ip_asn: mgmt_ip_asn ? String(mgmt_ip_asn) : null,
|
||||
responsible_team: responsible_team || confirmed_team || null,
|
||||
equipment_class,
|
||||
equip_template,
|
||||
equip_status,
|
||||
serial_number,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = createCardApiRouter;
|
||||
|
||||
@@ -227,6 +227,7 @@ function groupByHostname(rows, noteHostnames) {
|
||||
seen_count: row.seen_count || 1, first_seen: row.first_seen || null,
|
||||
last_seen: row.last_seen || null, resolved_on: row.resolved_on || null,
|
||||
has_notes: noteHostnames.has(row.hostname),
|
||||
resolution_date: null, remediation_plan: null,
|
||||
};
|
||||
}
|
||||
const dev = deviceMap[row.hostname];
|
||||
@@ -237,6 +238,11 @@ function groupByHostname(rows, noteHostnames) {
|
||||
if ((row.seen_count || 1) > dev.seen_count) dev.seen_count = row.seen_count;
|
||||
if (row.first_seen && (!dev.first_seen || row.first_seen < dev.first_seen)) dev.first_seen = row.first_seen;
|
||||
if (row.last_seen && (!dev.last_seen || row.last_seen > dev.last_seen)) dev.last_seen = row.last_seen;
|
||||
if (row.resolution_date && !dev.resolution_date) {
|
||||
const rd = row.resolution_date;
|
||||
dev.resolution_date = typeof rd === 'string' ? rd.slice(0, 10) : (rd instanceof Date ? rd.toISOString().slice(0, 10) : rd);
|
||||
}
|
||||
if (row.remediation_plan && !dev.remediation_plan) dev.remediation_plan = row.remediation_plan;
|
||||
}
|
||||
return Object.values(deviceMap).map(({ _seenMetricIds, ...dev }) => dev);
|
||||
}
|
||||
@@ -598,6 +604,7 @@ function createComplianceRouter(upload) {
|
||||
const { rows } = await pool.query(
|
||||
`SELECT DISTINCT ON (ci.hostname, ci.metric_id)
|
||||
ci.hostname, ci.ip_address, ci.device_type, ci.team, ci.metric_id, ci.metric_desc, ci.category, ci.status, ci.seen_count,
|
||||
ci.resolution_date, ci.remediation_plan,
|
||||
fu.report_date AS first_seen, lu.report_date AS last_seen, ru.report_date AS resolved_on
|
||||
FROM compliance_items ci
|
||||
LEFT JOIN compliance_uploads fu ON ci.first_seen_upload_id = fu.id
|
||||
@@ -665,7 +672,7 @@ function createComplianceRouter(upload) {
|
||||
let history = [];
|
||||
try {
|
||||
const { rows: historyRows } = await pool.query(
|
||||
`SELECT id, field_name, old_value, new_value, change_reason, changed_by, changed_at
|
||||
`SELECT id, metric_id, field_name, old_value, new_value, change_reason, changed_by, changed_at
|
||||
FROM compliance_item_history WHERE hostname = $1 ORDER BY changed_at DESC LIMIT 10`,
|
||||
[hostname]
|
||||
);
|
||||
@@ -943,13 +950,14 @@ function createComplianceRouter(upload) {
|
||||
|
||||
/**
|
||||
* PATCH /items/:hostname/metadata
|
||||
* Updates resolution_date and/or remediation_plan for all active compliance items matching a hostname.
|
||||
* Updates resolution_date and/or remediation_plan for active compliance items matching a hostname.
|
||||
* Supports optional per-metric scoping via metric_id (single) or metric_ids (array).
|
||||
* Records field-level change history in compliance_item_history for each modified field.
|
||||
*
|
||||
* @param hostname — the device hostname
|
||||
* @body { resolution_date?: string|null, remediation_plan?: string|null, change_reason?: string|null }
|
||||
* @body { resolution_date?: string|null, remediation_plan?: string|null, change_reason?: string|null, metric_id?: string, metric_ids?: string[] }
|
||||
* @response 200 { updated: number }
|
||||
* @response 400 { error } — invalid hostname, invalid date format, plan exceeds 2000 chars, change_reason exceeds 500 chars, or no fields provided
|
||||
* @response 400 { error } — invalid hostname, invalid date format, plan exceeds 2000 chars, change_reason exceeds 500 chars, no fields provided, or invalid metric_id
|
||||
* @response 404 { error } — device not found
|
||||
* @response 500 { error } — update failure
|
||||
*/
|
||||
@@ -957,7 +965,7 @@ function createComplianceRouter(upload) {
|
||||
const hostname = req.params.hostname;
|
||||
if (!hostname || hostname.length > 300) return res.status(400).json({ error: 'Invalid hostname' });
|
||||
|
||||
const { resolution_date, remediation_plan, change_reason } = req.body;
|
||||
const { resolution_date, remediation_plan, change_reason, metric_id, metric_ids } = req.body;
|
||||
|
||||
// Validate resolution_date: must be a valid ISO date string or null
|
||||
if (resolution_date !== undefined && resolution_date !== null) {
|
||||
@@ -979,6 +987,31 @@ function createComplianceRouter(upload) {
|
||||
return res.status(400).json({ error: 'Change reason exceeds 500 characters' });
|
||||
}
|
||||
|
||||
// Resolve metric scoping: metric_ids takes precedence over metric_id
|
||||
let resolvedMetricIds = null; // null means hostname-level (no metric scoping)
|
||||
if (metric_ids !== undefined) {
|
||||
if (!Array.isArray(metric_ids)) return res.status(400).json({ error: 'metric_ids must be an array' });
|
||||
if (metric_ids.length === 0) return res.status(400).json({ error: 'metric_ids must contain at least one entry' });
|
||||
for (let i = 0; i < metric_ids.length; i++) {
|
||||
const mid = metric_ids[i];
|
||||
if (!mid || typeof mid !== 'string' || mid.length === 0) {
|
||||
return res.status(400).json({ error: 'metric_id cannot be empty' });
|
||||
}
|
||||
if (mid.length > 100) {
|
||||
return res.status(400).json({ error: 'metric_id exceeds 100 characters' });
|
||||
}
|
||||
}
|
||||
resolvedMetricIds = metric_ids;
|
||||
} else if (metric_id !== undefined && metric_id !== null) {
|
||||
if (typeof metric_id !== 'string' || metric_id.length === 0) {
|
||||
return res.status(400).json({ error: 'metric_id cannot be empty' });
|
||||
}
|
||||
if (metric_id.length > 100) {
|
||||
return res.status(400).json({ error: 'metric_id exceeds 100 characters' });
|
||||
}
|
||||
resolvedMetricIds = [metric_id];
|
||||
}
|
||||
|
||||
const setClauses = [];
|
||||
const values = [];
|
||||
let paramIdx = 1;
|
||||
@@ -1000,69 +1033,148 @@ function createComplianceRouter(upload) {
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
|
||||
// Get current values before updating
|
||||
const { rows: currentRows } = await client.query(
|
||||
`SELECT DISTINCT ON (hostname) resolution_date, remediation_plan
|
||||
FROM compliance_items WHERE hostname = $1 AND status = 'active'
|
||||
ORDER BY hostname, id DESC LIMIT 1`,
|
||||
[hostname]
|
||||
);
|
||||
|
||||
if (currentRows.length === 0) {
|
||||
await client.query('ROLLBACK');
|
||||
client.release();
|
||||
return res.status(404).json({ error: 'Device not found' });
|
||||
}
|
||||
|
||||
const current = currentRows[0];
|
||||
const currentResDate = current.resolution_date
|
||||
? (typeof current.resolution_date === 'string' ? current.resolution_date : current.resolution_date.toISOString().slice(0, 10))
|
||||
: null;
|
||||
const currentPlan = current.remediation_plan || null;
|
||||
const reasonText = change_reason && change_reason.trim() ? change_reason.trim() : null;
|
||||
|
||||
// Insert history for each changed field
|
||||
if (resolution_date !== undefined) {
|
||||
const newVal = resolution_date || null;
|
||||
if (currentResDate !== newVal) {
|
||||
await client.query(
|
||||
`INSERT INTO compliance_item_history (hostname, field_name, old_value, new_value, change_reason, changed_by)
|
||||
VALUES ($1, 'resolution_date', $2, $3, $4, $5)`,
|
||||
[hostname, currentResDate, newVal, reasonText, req.user.username]
|
||||
);
|
||||
if (resolvedMetricIds !== null) {
|
||||
// --- Per-metric scoping path ---
|
||||
// Validate that each metric_id corresponds to an active compliance_item for this hostname
|
||||
const { rows: activeMetricRows } = await client.query(
|
||||
`SELECT metric_id, resolution_date, remediation_plan
|
||||
FROM compliance_items
|
||||
WHERE hostname = $1 AND metric_id = ANY($2) AND status = 'active'`,
|
||||
[hostname, resolvedMetricIds]
|
||||
);
|
||||
|
||||
const activeMetricMap = new Map();
|
||||
for (const row of activeMetricRows) {
|
||||
activeMetricMap.set(row.metric_id, row);
|
||||
}
|
||||
}
|
||||
if (remediation_plan !== undefined) {
|
||||
const newVal = remediation_plan || null;
|
||||
if (currentPlan !== newVal) {
|
||||
await client.query(
|
||||
`INSERT INTO compliance_item_history (hostname, field_name, old_value, new_value, change_reason, changed_by)
|
||||
VALUES ($1, 'remediation_plan', $2, $3, $4, $5)`,
|
||||
[hostname, currentPlan, newVal, reasonText, req.user.username]
|
||||
);
|
||||
|
||||
// Check for invalid metric_ids
|
||||
for (const mid of resolvedMetricIds) {
|
||||
if (!activeMetricMap.has(mid)) {
|
||||
await client.query('ROLLBACK');
|
||||
client.release();
|
||||
return res.status(400).json({ error: `Invalid metric_id: ${mid} — no active compliance item found` });
|
||||
}
|
||||
}
|
||||
|
||||
// Insert history per metric per changed field
|
||||
for (const mid of resolvedMetricIds) {
|
||||
const current = activeMetricMap.get(mid);
|
||||
const currentResDate = current.resolution_date
|
||||
? (typeof current.resolution_date === 'string' ? current.resolution_date : current.resolution_date.toISOString().slice(0, 10))
|
||||
: null;
|
||||
const currentPlan = current.remediation_plan || null;
|
||||
|
||||
if (resolution_date !== undefined) {
|
||||
const newVal = resolution_date || null;
|
||||
if (currentResDate !== newVal) {
|
||||
await client.query(
|
||||
`INSERT INTO compliance_item_history (hostname, metric_id, field_name, old_value, new_value, change_reason, changed_by)
|
||||
VALUES ($1, $2, 'resolution_date', $3, $4, $5, $6)`,
|
||||
[hostname, mid, currentResDate, newVal, reasonText, req.user.username]
|
||||
);
|
||||
}
|
||||
}
|
||||
if (remediation_plan !== undefined) {
|
||||
const newVal = remediation_plan || null;
|
||||
if (currentPlan !== newVal) {
|
||||
await client.query(
|
||||
`INSERT INTO compliance_item_history (hostname, metric_id, field_name, old_value, new_value, change_reason, changed_by)
|
||||
VALUES ($1, $2, 'remediation_plan', $3, $4, $5, $6)`,
|
||||
[hostname, mid, currentPlan, newVal, reasonText, req.user.username]
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Update only matching rows
|
||||
values.push(hostname);
|
||||
values.push(resolvedMetricIds);
|
||||
const result = await client.query(
|
||||
`UPDATE compliance_items SET ${setClauses.join(', ')} WHERE hostname = $${paramIdx} AND metric_id = ANY($${paramIdx + 1}) AND status = 'active'`,
|
||||
values
|
||||
);
|
||||
|
||||
await client.query('COMMIT');
|
||||
|
||||
logAudit({
|
||||
userId: req.user.id,
|
||||
username: req.user.username,
|
||||
action: 'compliance_metadata_update',
|
||||
entityType: 'compliance_item',
|
||||
entityId: hostname,
|
||||
details: { resolution_date, remediation_plan, change_reason: reasonText, metric_ids: resolvedMetricIds },
|
||||
ipAddress: req.ip,
|
||||
});
|
||||
|
||||
res.json({ updated: result.rowCount });
|
||||
} else {
|
||||
// --- Hostname-level path (backward compatible, NULL metric_id in history) ---
|
||||
// Get current values before updating (pick one representative row)
|
||||
const { rows: currentRows } = await client.query(
|
||||
`SELECT DISTINCT ON (hostname) resolution_date, remediation_plan
|
||||
FROM compliance_items WHERE hostname = $1 AND status = 'active'
|
||||
ORDER BY hostname, id DESC LIMIT 1`,
|
||||
[hostname]
|
||||
);
|
||||
|
||||
if (currentRows.length === 0) {
|
||||
await client.query('ROLLBACK');
|
||||
client.release();
|
||||
return res.status(404).json({ error: 'Device not found' });
|
||||
}
|
||||
|
||||
const current = currentRows[0];
|
||||
const currentResDate = current.resolution_date
|
||||
? (typeof current.resolution_date === 'string' ? current.resolution_date : current.resolution_date.toISOString().slice(0, 10))
|
||||
: null;
|
||||
const currentPlan = current.remediation_plan || null;
|
||||
|
||||
// Insert history for each changed field with NULL metric_id
|
||||
if (resolution_date !== undefined) {
|
||||
const newVal = resolution_date || null;
|
||||
if (currentResDate !== newVal) {
|
||||
await client.query(
|
||||
`INSERT INTO compliance_item_history (hostname, metric_id, field_name, old_value, new_value, change_reason, changed_by)
|
||||
VALUES ($1, NULL, 'resolution_date', $2, $3, $4, $5)`,
|
||||
[hostname, currentResDate, newVal, reasonText, req.user.username]
|
||||
);
|
||||
}
|
||||
}
|
||||
if (remediation_plan !== undefined) {
|
||||
const newVal = remediation_plan || null;
|
||||
if (currentPlan !== newVal) {
|
||||
await client.query(
|
||||
`INSERT INTO compliance_item_history (hostname, metric_id, field_name, old_value, new_value, change_reason, changed_by)
|
||||
VALUES ($1, NULL, 'remediation_plan', $2, $3, $4, $5)`,
|
||||
[hostname, currentPlan, newVal, reasonText, req.user.username]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Update all active items for hostname
|
||||
values.push(hostname);
|
||||
const result = await client.query(
|
||||
`UPDATE compliance_items SET ${setClauses.join(', ')} WHERE hostname = $${paramIdx} AND status = 'active'`,
|
||||
values
|
||||
);
|
||||
|
||||
await client.query('COMMIT');
|
||||
|
||||
logAudit({
|
||||
userId: req.user.id,
|
||||
username: req.user.username,
|
||||
action: 'compliance_metadata_update',
|
||||
entityType: 'compliance_item',
|
||||
entityId: hostname,
|
||||
details: { resolution_date, remediation_plan, change_reason: reasonText },
|
||||
ipAddress: req.ip,
|
||||
});
|
||||
|
||||
res.json({ updated: result.rowCount });
|
||||
}
|
||||
|
||||
// Update the items
|
||||
values.push(hostname);
|
||||
const result = await client.query(
|
||||
`UPDATE compliance_items SET ${setClauses.join(', ')} WHERE hostname = $${paramIdx}`,
|
||||
values
|
||||
);
|
||||
|
||||
await client.query('COMMIT');
|
||||
|
||||
logAudit({
|
||||
userId: req.user.id,
|
||||
username: req.user.username,
|
||||
action: 'compliance_metadata_update',
|
||||
entityType: 'compliance_item',
|
||||
entityId: hostname,
|
||||
details: { resolution_date, remediation_plan, change_reason: reasonText },
|
||||
ipAddress: req.ip,
|
||||
});
|
||||
|
||||
res.json({ updated: result.rowCount });
|
||||
} catch (err) {
|
||||
await client.query('ROLLBACK');
|
||||
console.error('[Compliance] PATCH /items/:hostname/metadata error:', err.message);
|
||||
@@ -1631,4 +1743,4 @@ function createComplianceRouter(upload) {
|
||||
return router;
|
||||
}
|
||||
|
||||
module.exports = { createComplianceRouter, bucketAgingItems, computeWaterfall, persistUpload };
|
||||
module.exports = { createComplianceRouter, bucketAgingItems, computeWaterfall, persistUpload, groupByHostname };
|
||||
|
||||
@@ -441,15 +441,43 @@ function createIvantiTodoQueueRouter() {
|
||||
* @error 500 Internal server error
|
||||
*/
|
||||
router.delete('/completed', requireAuth(), requireGroup('Admin', 'Standard_User'), async (req, res) => {
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
const result = await pool.query(
|
||||
"DELETE FROM ivanti_todo_queue WHERE user_id = $1 AND status = 'complete'",
|
||||
await client.query('BEGIN');
|
||||
|
||||
// Select completed item IDs for this user
|
||||
const { rows: completedRows } = await client.query(
|
||||
"SELECT id FROM ivanti_todo_queue WHERE user_id = $1 AND status = 'complete'",
|
||||
[req.user.id]
|
||||
);
|
||||
res.json({ message: 'Completed items cleared.', deleted: result.rowCount });
|
||||
|
||||
if (completedRows.length === 0) {
|
||||
await client.query('COMMIT');
|
||||
return res.json({ message: 'Completed items cleared.', deleted: 0 });
|
||||
}
|
||||
|
||||
const ids = completedRows.map(r => r.id);
|
||||
|
||||
// Delete junction table references first
|
||||
await client.query(
|
||||
'DELETE FROM jira_ticket_queue_items WHERE queue_item_id = ANY($1::int[])',
|
||||
[ids]
|
||||
);
|
||||
|
||||
// Delete the completed queue items
|
||||
const deleteResult = await client.query(
|
||||
'DELETE FROM ivanti_todo_queue WHERE id = ANY($1::int[])',
|
||||
[ids]
|
||||
);
|
||||
|
||||
await client.query('COMMIT');
|
||||
res.json({ message: 'Completed items cleared.', deleted: deleteResult.rowCount });
|
||||
} catch (err) {
|
||||
await client.query('ROLLBACK');
|
||||
console.error('Error clearing completed queue items:', err);
|
||||
res.status(500).json({ error: 'Internal server error.' });
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
69
backend/scripts/card-connectivity-test.js
Normal file
69
backend/scripts/card-connectivity-test.js
Normal file
@@ -0,0 +1,69 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* CARD API Connectivity Test
|
||||
* Tests: token acquisition → teams list → sample asset lookup
|
||||
*/
|
||||
require('dns').setDefaultResultOrder('ipv4first');
|
||||
require('dotenv').config({ path: require('path').join(__dirname, '..', '.env') });
|
||||
|
||||
const { isConfigured, missingVars, testConnection, getTeams } = require('../helpers/cardApi');
|
||||
|
||||
async function main() {
|
||||
console.log('=== CARD API Connectivity Test ===');
|
||||
console.log(`Timestamp: ${new Date().toISOString()}`);
|
||||
console.log(`Target: ${process.env.CARD_API_URL}`);
|
||||
console.log(`User: ${process.env.CARD_API_USER}`);
|
||||
console.log(`TLS Skip: ${process.env.CARD_SKIP_TLS}`);
|
||||
console.log('');
|
||||
|
||||
if (!isConfigured) {
|
||||
console.error('FAIL: CARD API not configured. Missing:', missingVars.join(', '));
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Step 1: Token acquisition
|
||||
console.log('1. Acquiring Bearer token...');
|
||||
const connResult = await testConnection();
|
||||
if (!connResult.ok) {
|
||||
console.error(' FAIL:', connResult.error);
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(' OK — token acquired:', connResult.token);
|
||||
|
||||
// Step 2: List teams
|
||||
console.log('2. Fetching teams (GET /api/v1/teams)...');
|
||||
const teamsResult = await getTeams();
|
||||
console.log(' Status:', teamsResult.status);
|
||||
if (!teamsResult.ok) {
|
||||
console.error(' FAIL:', teamsResult.body.substring(0, 300));
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
let teams;
|
||||
try {
|
||||
teams = JSON.parse(teamsResult.body);
|
||||
} catch (e) {
|
||||
console.error(' FAIL: Could not parse response:', teamsResult.body.substring(0, 200));
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (Array.isArray(teams)) {
|
||||
console.log(` OK — ${teams.length} teams found`);
|
||||
const sample = teams.slice(0, 8);
|
||||
sample.forEach(t => {
|
||||
const name = t.name || t.team_name || t.teamName || JSON.stringify(t).substring(0, 60);
|
||||
console.log(` • ${name}`);
|
||||
});
|
||||
} else {
|
||||
console.log(' Response structure:', Object.keys(teams).join(', '));
|
||||
console.log(' Preview:', JSON.stringify(teams).substring(0, 200));
|
||||
}
|
||||
|
||||
console.log('');
|
||||
console.log('=== RESULT: PASS — CARD API is reachable and authenticated ===');
|
||||
}
|
||||
|
||||
main().catch(err => {
|
||||
console.error('ERROR:', err.message);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -1,6 +1,10 @@
|
||||
// CVE Management Backend API
|
||||
// Install: npm install express pg multer cors dotenv bcryptjs cookie-parser
|
||||
|
||||
// Force IPv4-first DNS resolution globally — must be set before any network modules load.
|
||||
// card.charter.com has IPv6 AAAA records that are unreachable from this network.
|
||||
require('dns').setDefaultResultOrder('ipv4first');
|
||||
|
||||
require('dotenv').config();
|
||||
|
||||
const express = require('express');
|
||||
|
||||
@@ -533,6 +533,8 @@ A dedicated page for managing Jira Data Center tickets linked to CVE/vendor pair
|
||||
- **Sync** — refresh a single ticket's status and summary from Jira, or bulk-sync all tracked tickets via JQL search
|
||||
- **Create / Edit / Delete** — manage local ticket records linking Jira keys to CVE/vendor pairs
|
||||
|
||||
**Vendor-specific issue types:** The Issue Type dropdown in the creation modal is context-aware. When the Project Key field matches a recognized vendor project key (e.g., `AA_VECIMA`, `AA_CISCO`, `AA_ADTRAN`), the dropdown switches to vendor-specific issue types (Epic, Story, Task, Defect, Production Defect/Incident Fix, New Feature, Spike, Release Candidate, Documentation). For all other project keys — including the default from `JIRA_PROJECT_KEY` — the dropdown shows STEAM issue types (Story, Epic, Program, Project, Reservation, Automation Maintenance). Matching is case-insensitive and trims whitespace. Changing the project key such that the context switches (STEAM to vendor or vice versa) resets the selected issue type. The same behavior applies when creating a Jira ticket from the Ivanti Queue. The list of recognized vendor project keys is defined in `VENDOR_PROJECT_KEYS` in `frontend/src/components/pages/JiraPage.js`.
|
||||
|
||||
**Connection test (Admin)** — verify Jira API credentials and connectivity from the page header.
|
||||
|
||||
**Rate limit monitoring (Admin)** — view current burst and daily rate limit usage against Charter's posted limits (60/minute burst, 1 440/day).
|
||||
|
||||
@@ -28,7 +28,10 @@
|
||||
"extends": [
|
||||
"react-app",
|
||||
"react-app/jest"
|
||||
]
|
||||
],
|
||||
"rules": {
|
||||
"no-unused-vars": ["warn", { "vars": "all", "args": "after-used", "ignoreRestSiblings": true, "varsIgnorePattern": "^_", "argsIgnorePattern": "^_" }]
|
||||
}
|
||||
},
|
||||
"browserslist": {
|
||||
"production": [
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
/**
|
||||
* Property-Based Test: Section Header Count Accuracy
|
||||
*
|
||||
* Feature: queue-collapsible-sections, Property 4: Section Header Count Accuracy
|
||||
* **Validates: Requirements 3.1, 3.2**
|
||||
*
|
||||
* For every section in the grouped output, the items array length equals the count
|
||||
* that would be displayed in the header. The sum of all section item counts equals
|
||||
* the total input array length.
|
||||
*/
|
||||
import fc from 'fast-check';
|
||||
|
||||
// Replicate the grouping logic inline (utility file not yet extracted)
|
||||
function groupQueueItems(visibleItems) {
|
||||
const INVENTORY_TYPES = new Set(['CARD', 'GRANITE', 'DECOM']);
|
||||
const inventoryItems = [];
|
||||
const vendorMap = new Map();
|
||||
for (const item of visibleItems) {
|
||||
if (INVENTORY_TYPES.has(item.workflow_type)) {
|
||||
inventoryItems.push(item);
|
||||
} else {
|
||||
const vendor = item.vendor?.trim() || 'Unknown';
|
||||
if (!vendorMap.has(vendor)) vendorMap.set(vendor, []);
|
||||
vendorMap.get(vendor).push(item);
|
||||
}
|
||||
}
|
||||
const sections = [];
|
||||
if (inventoryItems.length > 0) {
|
||||
sections.push({ key: 'inventory', label: 'Inventory', type: 'inventory', items: inventoryItems });
|
||||
}
|
||||
const sortedVendors = [...vendorMap.entries()].sort((a, b) => a[0].localeCompare(b[0]));
|
||||
for (const [vendor, items] of sortedVendors) {
|
||||
sections.push({ key: `vendor:${vendor}`, label: vendor, type: 'vendor', items });
|
||||
}
|
||||
return sections;
|
||||
}
|
||||
|
||||
// Generator for queue items with realistic workflow types and vendor names
|
||||
const workflowTypeArb = fc.constantFrom('CARD', 'GRANITE', 'DECOM', 'FP', 'Archer');
|
||||
const vendorArb = fc.oneof(
|
||||
fc.constantFrom('Microsoft', 'Adobe', 'Cisco', 'Oracle', 'VMware', 'Apple'),
|
||||
fc.constant(''),
|
||||
fc.constant(null),
|
||||
fc.constant(undefined)
|
||||
);
|
||||
|
||||
const queueItemArb = fc.record({
|
||||
id: fc.uuid(),
|
||||
workflow_type: workflowTypeArb,
|
||||
vendor: vendorArb,
|
||||
hostname: fc.string({ minLength: 1, maxLength: 20 }),
|
||||
status: fc.constant('pending'),
|
||||
});
|
||||
|
||||
const queueItemsArb = fc.array(queueItemArb, { minLength: 1, maxLength: 50 });
|
||||
|
||||
describe('Queue Grouping — Property 4: Section Header Count Accuracy', () => {
|
||||
it('each section items.length is a positive integer (the displayed count)', () => {
|
||||
fc.assert(
|
||||
fc.property(queueItemsArb, (items) => {
|
||||
const sections = groupQueueItems(items);
|
||||
|
||||
for (const section of sections) {
|
||||
// items.length is the count that would be displayed in the header
|
||||
expect(Number.isInteger(section.items.length)).toBe(true);
|
||||
expect(section.items.length).toBeGreaterThan(0);
|
||||
}
|
||||
}),
|
||||
{ numRuns: 200 }
|
||||
);
|
||||
});
|
||||
|
||||
it('sum of all section item counts equals total input array length', () => {
|
||||
fc.assert(
|
||||
fc.property(queueItemsArb, (items) => {
|
||||
const sections = groupQueueItems(items);
|
||||
|
||||
const totalItemsInSections = sections.reduce(
|
||||
(sum, section) => sum + section.items.length,
|
||||
0
|
||||
);
|
||||
|
||||
expect(totalItemsInSections).toBe(items.length);
|
||||
}),
|
||||
{ numRuns: 200 }
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
/**
|
||||
* Property-Based Test: Empty Section Omission
|
||||
*
|
||||
* Feature: queue-collapsible-sections, Property 3: Empty Section Omission
|
||||
* **Validates: Requirements 1.6, 1.7**
|
||||
*
|
||||
* For any array of queue items (including empty arrays), the grouped output
|
||||
* contains no sections with zero items. If no CARD/GRANITE/DECOM items exist
|
||||
* in the input, no section with type 'inventory' appears in the output.
|
||||
*/
|
||||
import fc from 'fast-check';
|
||||
|
||||
// Inline the grouping logic since the utility file may not exist yet
|
||||
function groupQueueItems(visibleItems) {
|
||||
const INVENTORY_TYPES = new Set(['CARD', 'GRANITE', 'DECOM']);
|
||||
const inventoryItems = [];
|
||||
const vendorMap = new Map();
|
||||
for (const item of visibleItems) {
|
||||
if (INVENTORY_TYPES.has(item.workflow_type)) {
|
||||
inventoryItems.push(item);
|
||||
} else {
|
||||
const vendor = item.vendor?.trim() || 'Unknown';
|
||||
if (!vendorMap.has(vendor)) vendorMap.set(vendor, []);
|
||||
vendorMap.get(vendor).push(item);
|
||||
}
|
||||
}
|
||||
const sections = [];
|
||||
if (inventoryItems.length > 0) {
|
||||
sections.push({ key: 'inventory', label: 'Inventory', type: 'inventory', items: inventoryItems });
|
||||
}
|
||||
const sortedVendors = [...vendorMap.entries()].sort((a, b) => a[0].localeCompare(b[0]));
|
||||
for (const [vendor, items] of sortedVendors) {
|
||||
sections.push({ key: `vendor:${vendor}`, label: vendor, type: 'vendor', items });
|
||||
}
|
||||
return sections;
|
||||
}
|
||||
|
||||
// Generator for queue items with various workflow types and vendors
|
||||
const workflowTypeArb = fc.constantFrom('CARD', 'GRANITE', 'DECOM', 'FP', 'Archer');
|
||||
const vendorArb = fc.oneof(
|
||||
fc.constant(null),
|
||||
fc.constant(undefined),
|
||||
fc.constant(''),
|
||||
fc.constant(' '),
|
||||
fc.stringMatching(/^[A-Za-z][A-Za-z0-9 ]{0,14}$/)
|
||||
);
|
||||
|
||||
const queueItemArb = fc.record({
|
||||
id: fc.integer({ min: 1, max: 100000 }),
|
||||
workflow_type: workflowTypeArb,
|
||||
vendor: vendorArb,
|
||||
hostname: fc.stringMatching(/^[a-z]{3,10}$/),
|
||||
status: fc.constant('pending'),
|
||||
});
|
||||
|
||||
const queueItemsArb = fc.array(queueItemArb, { minLength: 0, maxLength: 50 });
|
||||
|
||||
describe('Queue Grouping — Property 3: Empty Section Omission', () => {
|
||||
it('no section in the output has zero items', () => {
|
||||
fc.assert(
|
||||
fc.property(queueItemsArb, (items) => {
|
||||
const sections = groupQueueItems(items);
|
||||
for (const section of sections) {
|
||||
expect(section.items.length).toBeGreaterThan(0);
|
||||
}
|
||||
}),
|
||||
{ numRuns: 200 }
|
||||
);
|
||||
});
|
||||
|
||||
it('if no inventory-type items exist, no inventory section appears', () => {
|
||||
// Generate arrays that explicitly exclude inventory types
|
||||
const nonInventoryTypeArb = fc.constantFrom('FP', 'Archer');
|
||||
const nonInventoryItemArb = fc.record({
|
||||
id: fc.integer({ min: 1, max: 100000 }),
|
||||
workflow_type: nonInventoryTypeArb,
|
||||
vendor: vendorArb,
|
||||
hostname: fc.stringMatching(/^[a-z]{3,10}$/),
|
||||
status: fc.constant('pending'),
|
||||
});
|
||||
const nonInventoryItemsArb = fc.array(nonInventoryItemArb, { minLength: 0, maxLength: 50 });
|
||||
|
||||
fc.assert(
|
||||
fc.property(nonInventoryItemsArb, (items) => {
|
||||
const sections = groupQueueItems(items);
|
||||
const inventorySection = sections.find(s => s.type === 'inventory');
|
||||
expect(inventorySection).toBeUndefined();
|
||||
}),
|
||||
{ numRuns: 200 }
|
||||
);
|
||||
});
|
||||
|
||||
it('if no CARD/GRANITE/DECOM items exist in a mixed array, no inventory section appears', () => {
|
||||
fc.assert(
|
||||
fc.property(queueItemsArb, (items) => {
|
||||
const INVENTORY_TYPES = new Set(['CARD', 'GRANITE', 'DECOM']);
|
||||
const hasInventoryItems = items.some(item => INVENTORY_TYPES.has(item.workflow_type));
|
||||
const sections = groupQueueItems(items);
|
||||
const inventorySection = sections.find(s => s.type === 'inventory');
|
||||
|
||||
if (!hasInventoryItems) {
|
||||
expect(inventorySection).toBeUndefined();
|
||||
} else {
|
||||
expect(inventorySection).toBeDefined();
|
||||
expect(inventorySection.items.length).toBeGreaterThan(0);
|
||||
}
|
||||
}),
|
||||
{ numRuns: 200 }
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* Property-Based Test: Section Ordering
|
||||
*
|
||||
* Feature: queue-collapsible-sections, Property 2: Section Ordering
|
||||
* **Validates: Requirements 1.3, 1.4**
|
||||
*
|
||||
* For any array of queue items, the Inventory section (if present) is always
|
||||
* the first element, and all vendor sections are sorted alphabetically by label.
|
||||
*/
|
||||
import fc from 'fast-check';
|
||||
|
||||
// Inline grouping logic (mirrors the implementation in IvantiTodoQueuePage)
|
||||
function groupQueueItems(visibleItems) {
|
||||
const INVENTORY_TYPES = new Set(['CARD', 'GRANITE', 'DECOM']);
|
||||
const inventoryItems = [];
|
||||
const vendorMap = new Map();
|
||||
for (const item of visibleItems) {
|
||||
if (INVENTORY_TYPES.has(item.workflow_type)) {
|
||||
inventoryItems.push(item);
|
||||
} else {
|
||||
const vendor = item.vendor?.trim() || 'Unknown';
|
||||
if (!vendorMap.has(vendor)) vendorMap.set(vendor, []);
|
||||
vendorMap.get(vendor).push(item);
|
||||
}
|
||||
}
|
||||
const sections = [];
|
||||
if (inventoryItems.length > 0) {
|
||||
sections.push({ key: 'inventory', label: 'Inventory', type: 'inventory', items: inventoryItems });
|
||||
}
|
||||
const sortedVendors = [...vendorMap.entries()].sort((a, b) => a[0].localeCompare(b[0]));
|
||||
for (const [vendor, items] of sortedVendors) {
|
||||
sections.push({ key: `vendor:${vendor}`, label: vendor, type: 'vendor', items });
|
||||
}
|
||||
return sections;
|
||||
}
|
||||
|
||||
// Generator for queue items with random workflow types and vendors
|
||||
const workflowTypeArb = fc.constantFrom('CARD', 'GRANITE', 'DECOM', 'FP', 'Archer');
|
||||
|
||||
const vendorArb = fc.oneof(
|
||||
fc.constant(null),
|
||||
fc.constant(undefined),
|
||||
fc.constant(''),
|
||||
fc.constant(' '),
|
||||
fc.stringMatching(/^[A-Za-z][A-Za-z0-9 ]{0,14}$/)
|
||||
);
|
||||
|
||||
const queueItemArb = fc.record({
|
||||
id: fc.integer({ min: 1, max: 100000 }),
|
||||
workflow_type: workflowTypeArb,
|
||||
vendor: vendorArb,
|
||||
hostname: fc.string({ minLength: 1, maxLength: 20 }),
|
||||
status: fc.constant('pending'),
|
||||
});
|
||||
|
||||
const queueItemsArb = fc.array(queueItemArb, { minLength: 0, maxLength: 50 });
|
||||
|
||||
describe('Queue Grouping — Property 2: Section Ordering', () => {
|
||||
it('Inventory section (if present) is always the first element', () => {
|
||||
fc.assert(
|
||||
fc.property(queueItemsArb, (items) => {
|
||||
const sections = groupQueueItems(items);
|
||||
|
||||
const inventoryIndex = sections.findIndex(s => s.type === 'inventory');
|
||||
|
||||
// If inventory section exists, it must be at index 0
|
||||
if (inventoryIndex !== -1) {
|
||||
expect(inventoryIndex).toBe(0);
|
||||
}
|
||||
}),
|
||||
{ numRuns: 500 }
|
||||
);
|
||||
});
|
||||
|
||||
it('Vendor sections are sorted alphabetically by label', () => {
|
||||
fc.assert(
|
||||
fc.property(queueItemsArb, (items) => {
|
||||
const sections = groupQueueItems(items);
|
||||
|
||||
const vendorSections = sections.filter(s => s.type === 'vendor');
|
||||
|
||||
// Each consecutive pair of vendor sections must be in alphabetical order
|
||||
for (let i = 1; i < vendorSections.length; i++) {
|
||||
const prev = vendorSections[i - 1].label;
|
||||
const curr = vendorSections[i].label;
|
||||
expect(prev.localeCompare(curr)).toBeLessThanOrEqual(0);
|
||||
}
|
||||
}),
|
||||
{ numRuns: 500 }
|
||||
);
|
||||
});
|
||||
});
|
||||
135
frontend/src/__tests__/queue-grouping.property.test.js
Normal file
135
frontend/src/__tests__/queue-grouping.property.test.js
Normal file
@@ -0,0 +1,135 @@
|
||||
/**
|
||||
* Property-Based Test: Grouping Correctness
|
||||
*
|
||||
* Feature: queue-collapsible-sections, Property 1: Grouping Correctness
|
||||
* **Validates: Requirements 1.1, 1.2, 1.5**
|
||||
*
|
||||
* For any array of visible queue items, every item with workflow_type CARD,
|
||||
* GRANITE, or DECOM appears in the Inventory section; every FP/Archer item
|
||||
* appears in the vendor section matching its vendor field (or "Unknown" if
|
||||
* null/empty); no item appears in more than one section; and total items
|
||||
* across all sections equals input length.
|
||||
*/
|
||||
import fc from 'fast-check';
|
||||
import { groupQueueItems } from '../utils/queueGrouping';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Arbitraries
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const INVENTORY_TYPES = ['CARD', 'GRANITE', 'DECOM'];
|
||||
const VENDOR_TYPES = ['FP', 'Archer'];
|
||||
const ALL_WORKFLOW_TYPES = [...INVENTORY_TYPES, ...VENDOR_TYPES];
|
||||
|
||||
// Generate vendor strings including edge cases: null, undefined, empty, whitespace-only, normal strings
|
||||
const vendorArbitrary = fc.oneof(
|
||||
fc.constant(null),
|
||||
fc.constant(undefined),
|
||||
fc.constant(''),
|
||||
fc.constant(' '),
|
||||
fc.stringMatching(/^[A-Za-z][A-Za-z0-9 ]{0,19}$/)
|
||||
);
|
||||
|
||||
// Generate a single queue item with a random workflow_type and vendor
|
||||
const queueItemArbitrary = fc.record({
|
||||
id: fc.integer({ min: 1, max: 100000 }),
|
||||
workflow_type: fc.constantFrom(...ALL_WORKFLOW_TYPES),
|
||||
vendor: vendorArbitrary,
|
||||
status: fc.constant('pending'),
|
||||
hostname: fc.string({ minLength: 1, maxLength: 20 }),
|
||||
});
|
||||
|
||||
// Generate arrays of queue items (0 to 50 items)
|
||||
const queueItemsArbitrary = fc.array(queueItemArbitrary, { minLength: 0, maxLength: 50 });
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Property Test
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('Queue Grouping — Property 1: Grouping Correctness', () => {
|
||||
it('every CARD/GRANITE/DECOM item appears in Inventory section', () => {
|
||||
fc.assert(
|
||||
fc.property(queueItemsArbitrary, (items) => {
|
||||
const sections = groupQueueItems(items);
|
||||
const inventorySection = sections.find(s => s.key === 'inventory');
|
||||
const inventoryItems = inventorySection ? inventorySection.items : [];
|
||||
|
||||
const expectedInventoryItems = items.filter(item =>
|
||||
INVENTORY_TYPES.includes(item.workflow_type)
|
||||
);
|
||||
|
||||
// Every inventory-type item must be in the inventory section
|
||||
for (const item of expectedInventoryItems) {
|
||||
expect(inventoryItems).toContain(item);
|
||||
}
|
||||
|
||||
// Inventory section should contain exactly the inventory-type items
|
||||
expect(inventoryItems.length).toBe(expectedInventoryItems.length);
|
||||
}),
|
||||
{ numRuns: 200 }
|
||||
);
|
||||
});
|
||||
|
||||
it('every FP/Archer item appears in a vendor section matching its vendor field (or "Unknown")', () => {
|
||||
fc.assert(
|
||||
fc.property(queueItemsArbitrary, (items) => {
|
||||
const sections = groupQueueItems(items);
|
||||
|
||||
const vendorSections = sections.filter(s => s.type === 'vendor');
|
||||
const allVendorItems = vendorSections.flatMap(s => s.items);
|
||||
|
||||
const expectedVendorItems = items.filter(item =>
|
||||
VENDOR_TYPES.includes(item.workflow_type)
|
||||
);
|
||||
|
||||
// Every vendor-type item must appear in a vendor section
|
||||
for (const item of expectedVendorItems) {
|
||||
expect(allVendorItems).toContain(item);
|
||||
|
||||
// Determine expected vendor key
|
||||
const expectedVendor = item.vendor?.trim() || 'Unknown';
|
||||
const expectedKey = `vendor:${expectedVendor}`;
|
||||
const matchingSection = sections.find(s => s.key === expectedKey);
|
||||
|
||||
expect(matchingSection).toBeDefined();
|
||||
expect(matchingSection.items).toContain(item);
|
||||
}
|
||||
|
||||
// Vendor sections should contain exactly the vendor-type items
|
||||
expect(allVendorItems.length).toBe(expectedVendorItems.length);
|
||||
}),
|
||||
{ numRuns: 200 }
|
||||
);
|
||||
});
|
||||
|
||||
it('no item appears in more than one section', () => {
|
||||
fc.assert(
|
||||
fc.property(queueItemsArbitrary, (items) => {
|
||||
const sections = groupQueueItems(items);
|
||||
|
||||
// Collect all items across all sections
|
||||
const allSectionItems = sections.flatMap(s => s.items);
|
||||
|
||||
// Use a Set to check for duplicates (by reference)
|
||||
const seen = new Set();
|
||||
for (const item of allSectionItems) {
|
||||
expect(seen.has(item)).toBe(false);
|
||||
seen.add(item);
|
||||
}
|
||||
}),
|
||||
{ numRuns: 200 }
|
||||
);
|
||||
});
|
||||
|
||||
it('total items across all sections equals input length', () => {
|
||||
fc.assert(
|
||||
fc.property(queueItemsArbitrary, (items) => {
|
||||
const sections = groupQueueItems(items);
|
||||
const totalInSections = sections.reduce((sum, s) => sum + s.items.length, 0);
|
||||
|
||||
expect(totalInSections).toBe(items.length);
|
||||
}),
|
||||
{ numRuns: 200 }
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,213 @@
|
||||
/**
|
||||
* Property-Based Test: Selection Independence from Collapse State
|
||||
*
|
||||
* Feature: queue-collapsible-sections, Property 5: Selection Independence from Collapse State
|
||||
* **Validates: Requirements 4.2, 4.4, 4.5**
|
||||
*
|
||||
* For any combination of selected items and collapse state, the set of selected
|
||||
* item IDs remains unchanged when sections are collapsed or expanded. Select All
|
||||
* always covers all visible items regardless of which sections are collapsed.
|
||||
*/
|
||||
import fc from 'fast-check';
|
||||
|
||||
// --- Pure logic under test (mirrors IvantiTodoQueuePage behavior) ---
|
||||
|
||||
/**
|
||||
* Toggle a section's collapse state. Only modifies collapsedSections,
|
||||
* never touches selectedIds.
|
||||
*/
|
||||
function toggleSection(collapsedSections, sectionKey) {
|
||||
return { ...collapsedSections, [sectionKey]: !collapsedSections[sectionKey] };
|
||||
}
|
||||
|
||||
/**
|
||||
* Select All — always selects all visible items regardless of collapse state.
|
||||
* The visibleItems array contains ALL pending items, not just those in expanded sections.
|
||||
*/
|
||||
function selectAll(visibleItems) {
|
||||
return new Set(visibleItems.map(item => item.id));
|
||||
}
|
||||
|
||||
// --- Generators ---
|
||||
|
||||
const WORKFLOW_TYPES = ['CARD', 'GRANITE', 'DECOM', 'FP', 'Archer'];
|
||||
const VENDORS = ['Microsoft', 'Adobe', 'Cisco', 'Unknown', 'Oracle', 'VMware'];
|
||||
|
||||
const queueItemArbitrary = fc.record({
|
||||
id: fc.integer({ min: 1, max: 100000 }),
|
||||
workflow_type: fc.constantFrom(...WORKFLOW_TYPES),
|
||||
vendor: fc.constantFrom(...VENDORS),
|
||||
status: fc.constant('pending'),
|
||||
});
|
||||
|
||||
// Generate arrays of queue items with unique IDs
|
||||
const queueItemsArbitrary = fc
|
||||
.array(queueItemArbitrary, { minLength: 1, maxLength: 50 })
|
||||
.map(items => {
|
||||
// Ensure unique IDs
|
||||
const seen = new Set();
|
||||
return items.filter(item => {
|
||||
if (seen.has(item.id)) return false;
|
||||
seen.add(item.id);
|
||||
return true;
|
||||
});
|
||||
})
|
||||
.filter(items => items.length > 0);
|
||||
|
||||
// Generate a subset of item IDs as the selected set
|
||||
const selectedIdsArbitrary = (items) =>
|
||||
fc.subarray(items.map(i => i.id), { minLength: 0 }).map(ids => new Set(ids));
|
||||
|
||||
// Generate section keys that would exist for a given set of items
|
||||
const sectionKeysForItems = (items) => {
|
||||
const keys = new Set();
|
||||
const INVENTORY_TYPES = new Set(['CARD', 'GRANITE', 'DECOM']);
|
||||
let hasInventory = false;
|
||||
for (const item of items) {
|
||||
if (INVENTORY_TYPES.has(item.workflow_type)) {
|
||||
hasInventory = true;
|
||||
} else {
|
||||
keys.add(`vendor:${item.vendor || 'Unknown'}`);
|
||||
}
|
||||
}
|
||||
if (hasInventory) keys.add('inventory');
|
||||
return [...keys];
|
||||
};
|
||||
|
||||
// Generate arbitrary collapse state for given section keys
|
||||
const collapsedSectionsArbitrary = (sectionKeys) =>
|
||||
fc.record(
|
||||
Object.fromEntries(sectionKeys.map(key => [key, fc.boolean()])),
|
||||
{ withDeletedKeys: true }
|
||||
);
|
||||
|
||||
// --- Tests ---
|
||||
|
||||
describe('Property 5: Selection Independence from Collapse State', () => {
|
||||
it('toggling collapse state does not alter the set of selected item IDs', () => {
|
||||
fc.assert(
|
||||
fc.property(
|
||||
queueItemsArbitrary.chain(items =>
|
||||
fc.tuple(
|
||||
fc.constant(items),
|
||||
selectedIdsArbitrary(items),
|
||||
fc.constant(sectionKeysForItems(items))
|
||||
)
|
||||
).chain(([items, selectedIds, sectionKeys]) =>
|
||||
fc.tuple(
|
||||
fc.constant(items),
|
||||
fc.constant(selectedIds),
|
||||
sectionKeys.length > 0
|
||||
? collapsedSectionsArbitrary(sectionKeys)
|
||||
: fc.constant({}),
|
||||
sectionKeys.length > 0
|
||||
? fc.array(fc.constantFrom(...sectionKeys), { minLength: 1, maxLength: 10 })
|
||||
: fc.constant([])
|
||||
)
|
||||
),
|
||||
([items, selectedIds, initialCollapsed, toggleSequence]) => {
|
||||
// Record the original selected IDs
|
||||
const originalSelectedIds = new Set(selectedIds);
|
||||
|
||||
// Apply a sequence of toggleSection calls
|
||||
let currentCollapsed = { ...initialCollapsed };
|
||||
for (const sectionKey of toggleSequence) {
|
||||
currentCollapsed = toggleSection(currentCollapsed, sectionKey);
|
||||
}
|
||||
|
||||
// The selectedIds set must remain completely unchanged
|
||||
// (toggleSection only modifies collapsedSections, never selectedIds)
|
||||
expect(selectedIds).toEqual(originalSelectedIds);
|
||||
expect(selectedIds.size).toBe(originalSelectedIds.size);
|
||||
for (const id of originalSelectedIds) {
|
||||
expect(selectedIds.has(id)).toBe(true);
|
||||
}
|
||||
}
|
||||
),
|
||||
{ numRuns: 200 }
|
||||
);
|
||||
});
|
||||
|
||||
it('Select All always covers all visible items regardless of collapse state', () => {
|
||||
fc.assert(
|
||||
fc.property(
|
||||
queueItemsArbitrary.chain(items =>
|
||||
fc.tuple(
|
||||
fc.constant(items),
|
||||
fc.constant(sectionKeysForItems(items))
|
||||
)
|
||||
).chain(([items, sectionKeys]) =>
|
||||
fc.tuple(
|
||||
fc.constant(items),
|
||||
sectionKeys.length > 0
|
||||
? collapsedSectionsArbitrary(sectionKeys)
|
||||
: fc.constant({})
|
||||
)
|
||||
),
|
||||
([visibleItems, collapsedSections]) => {
|
||||
// Regardless of which sections are collapsed, selectAll operates
|
||||
// on the full visibleItems array (all pending items)
|
||||
const allSelectedIds = selectAll(visibleItems);
|
||||
|
||||
// Every visible item must be in the selected set
|
||||
for (const item of visibleItems) {
|
||||
expect(allSelectedIds.has(item.id)).toBe(true);
|
||||
}
|
||||
|
||||
// The selected set size must equal the number of visible items
|
||||
expect(allSelectedIds.size).toBe(visibleItems.length);
|
||||
|
||||
// Verify this holds even after toggling all sections to collapsed
|
||||
let fullyCollapsed = { ...collapsedSections };
|
||||
const sectionKeys = Object.keys(collapsedSections);
|
||||
for (const key of sectionKeys) {
|
||||
fullyCollapsed = toggleSection(fullyCollapsed, key);
|
||||
}
|
||||
|
||||
// selectAll still returns all visible items — collapse state is irrelevant
|
||||
const afterCollapseSelectAll = selectAll(visibleItems);
|
||||
expect(afterCollapseSelectAll).toEqual(allSelectedIds);
|
||||
expect(afterCollapseSelectAll.size).toBe(visibleItems.length);
|
||||
}
|
||||
),
|
||||
{ numRuns: 200 }
|
||||
);
|
||||
});
|
||||
|
||||
it('selection count always equals total selected items across all sections regardless of collapse', () => {
|
||||
fc.assert(
|
||||
fc.property(
|
||||
queueItemsArbitrary.chain(items =>
|
||||
fc.tuple(
|
||||
fc.constant(items),
|
||||
selectedIdsArbitrary(items),
|
||||
fc.constant(sectionKeysForItems(items))
|
||||
)
|
||||
).chain(([items, selectedIds, sectionKeys]) =>
|
||||
fc.tuple(
|
||||
fc.constant(items),
|
||||
fc.constant(selectedIds),
|
||||
sectionKeys.length > 0
|
||||
? collapsedSectionsArbitrary(sectionKeys)
|
||||
: fc.constant({})
|
||||
)
|
||||
),
|
||||
([_items, selectedIds, collapsedSections]) => {
|
||||
// The selection count (selectedIds.size) is independent of collapse state.
|
||||
// Changing collapse state should never change the count.
|
||||
const countBefore = selectedIds.size;
|
||||
|
||||
// Toggle every section
|
||||
let currentCollapsed = { ...collapsedSections };
|
||||
const sectionKeys = Object.keys(collapsedSections);
|
||||
for (const key of sectionKeys) {
|
||||
currentCollapsed = toggleSection(currentCollapsed, key);
|
||||
// After each toggle, selection count must remain the same
|
||||
expect(selectedIds.size).toBe(countBefore);
|
||||
}
|
||||
}
|
||||
),
|
||||
{ numRuns: 200 }
|
||||
);
|
||||
});
|
||||
});
|
||||
346
frontend/src/components/CardActionModal.js
Normal file
346
frontend/src/components/CardActionModal.js
Normal file
@@ -0,0 +1,346 @@
|
||||
/**
|
||||
* CardActionModal — CARD Asset Action Modal
|
||||
*
|
||||
* Shows the full CARD owner record for an asset and allows
|
||||
* confirm/decline/redirect operations with full context.
|
||||
*/
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { X, Loader, AlertCircle, CheckCircle, ArrowRightLeft, XCircle } from 'lucide-react'; // ⚠️ CONVENTION: Removed unused `Shield` import to satisfy no-unused-vars lint rule
|
||||
|
||||
const API_BASE = process.env.REACT_APP_API_BASE || 'http://localhost:3001/api';
|
||||
|
||||
const OVERLAY = {
|
||||
position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.75)', backdropFilter: 'blur(4px)',
|
||||
zIndex: 10200, display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
};
|
||||
const MODAL = {
|
||||
background: 'linear-gradient(135deg, #1E293B, #0F172A)',
|
||||
borderRadius: '1rem', border: '1px solid rgba(124, 58, 237, 0.25)',
|
||||
width: '90vw', maxWidth: '600px', maxHeight: '85vh', overflow: 'auto',
|
||||
padding: '1.5rem', position: 'relative',
|
||||
};
|
||||
const SECTION = {
|
||||
background: 'rgba(15, 23, 42, 0.6)', border: '1px solid rgba(51, 65, 85, 0.5)',
|
||||
borderRadius: '0.5rem', padding: '0.75rem', marginBottom: '0.75rem',
|
||||
};
|
||||
const LABEL = { fontSize: '0.6rem', color: '#64748B', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: '0.2rem' };
|
||||
const VALUE = { fontSize: '0.75rem', color: '#E2E8F0', fontFamily: "'JetBrains Mono', monospace" };
|
||||
const TEAM_BADGE = (color) => ({
|
||||
display: 'inline-block', padding: '0.15rem 0.5rem', borderRadius: '0.25rem',
|
||||
fontSize: '0.7rem', fontWeight: '600', fontFamily: 'monospace',
|
||||
background: `${color}15`, border: `1px solid ${color}40`, color,
|
||||
});
|
||||
const INPUT = {
|
||||
width: '100%', boxSizing: 'border-box', background: 'rgba(15, 23, 42, 0.8)',
|
||||
border: '1px solid rgba(51, 65, 85, 0.6)', borderRadius: '0.375rem',
|
||||
color: '#E2E8F0', padding: '0.5rem 0.75rem', fontSize: '0.75rem',
|
||||
fontFamily: "'JetBrains Mono', monospace", outline: 'none',
|
||||
};
|
||||
const BTN = {
|
||||
padding: '0.5rem 1.25rem', borderRadius: '0.375rem', border: 'none',
|
||||
fontSize: '0.75rem', fontWeight: '600', cursor: 'pointer', transition: 'all 0.12s',
|
||||
};
|
||||
|
||||
export default function CardActionModal({ isOpen, onClose, item, initialAction, cardTeams, onSuccess }) {
|
||||
const [ownerData, setOwnerData] = useState(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState(null);
|
||||
const [action, setAction] = useState(initialAction || 'confirm');
|
||||
const [teamName, setTeamName] = useState('');
|
||||
const [fromTeam, setFromTeam] = useState('');
|
||||
const [toTeam, setToTeam] = useState('');
|
||||
const [comment, setComment] = useState('');
|
||||
const [executing, setExecuting] = useState(false);
|
||||
const [execError, setExecError] = useState(null);
|
||||
|
||||
// Fetch owner data when modal opens
|
||||
useEffect(() => {
|
||||
if (!isOpen || !item?.ip_address) return;
|
||||
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
setOwnerData(null);
|
||||
setExecError(null);
|
||||
|
||||
fetch(`${API_BASE}/card/owner-lookup/${encodeURIComponent(item.ip_address)}`, { credentials: 'include' })
|
||||
.then(r => {
|
||||
if (!r.ok) return r.json().then(d => { throw new Error(d.error || `HTTP ${r.status}`); });
|
||||
return r.json();
|
||||
})
|
||||
.then(data => {
|
||||
setOwnerData(data);
|
||||
// Pre-fill team fields based on owner data
|
||||
if (data.confirmed) {
|
||||
setTeamName(data.confirmed.name || '');
|
||||
setFromTeam(data.confirmed.name || '');
|
||||
} else if (data.unconfirmed) {
|
||||
setTeamName(data.unconfirmed.name || '');
|
||||
setFromTeam(data.unconfirmed.name || '');
|
||||
}
|
||||
setLoading(false);
|
||||
})
|
||||
.catch(err => {
|
||||
setError(err.message);
|
||||
setLoading(false);
|
||||
});
|
||||
}, [isOpen, item]);
|
||||
|
||||
// Reset action when initialAction changes
|
||||
useEffect(() => {
|
||||
if (initialAction) setAction(initialAction);
|
||||
}, [initialAction]);
|
||||
|
||||
const handleExecute = async () => {
|
||||
setExecuting(true);
|
||||
setExecError(null);
|
||||
|
||||
try {
|
||||
let url, body;
|
||||
|
||||
if (action === 'confirm') {
|
||||
url = `${API_BASE}/card/queue/${item.id}/confirm`;
|
||||
body = { teamName: teamName.trim(), assetId: item.ip_address, comment: comment.trim() };
|
||||
} else if (action === 'decline') {
|
||||
url = `${API_BASE}/card/queue/${item.id}/decline`;
|
||||
body = { teamName: teamName.trim(), assetId: item.ip_address, comment: comment.trim() };
|
||||
} else if (action === 'redirect') {
|
||||
url = `${API_BASE}/card/queue/${item.id}/redirect`;
|
||||
body = { fromTeam: fromTeam.trim(), toTeam: toTeam.trim(), assetId: item.ip_address };
|
||||
}
|
||||
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
setExecError(data.error || data.message || `${action} failed.`);
|
||||
setExecuting(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setExecuting(false);
|
||||
if (onSuccess) onSuccess(item.id, action);
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setExecError(err.message || 'Network error.');
|
||||
setExecuting(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
const canExecute = () => {
|
||||
if (action === 'confirm' || action === 'decline') return teamName.trim().length > 0;
|
||||
if (action === 'redirect') return fromTeam.trim().length > 0 && toTeam.trim().length > 0;
|
||||
return false;
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={OVERLAY} onClick={onClose}>
|
||||
<div style={MODAL} onClick={e => e.stopPropagation()}>
|
||||
{/* Header */}
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1rem' }}>
|
||||
<div>
|
||||
<h3 style={{ margin: 0, color: '#F8FAFC', fontSize: '0.95rem' }}>CARD Asset Action</h3>
|
||||
{ownerData && (
|
||||
<div style={{ fontSize: '0.7rem', color: '#7C3AED', fontFamily: 'monospace', marginTop: '0.2rem' }}>
|
||||
{ownerData.asset_id}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<button onClick={onClose} style={{ background: 'none', border: 'none', color: '#64748B', cursor: 'pointer' }}>
|
||||
<X style={{ width: '18px', height: '18px' }} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Loading */}
|
||||
{loading && (
|
||||
<div style={{ textAlign: 'center', padding: '2rem' }}>
|
||||
<Loader style={{ width: '20px', height: '20px', color: '#7C3AED', animation: 'spin 1s linear infinite' }} />
|
||||
<div style={{ fontSize: '0.75rem', color: '#64748B', marginTop: '0.5rem' }}>Loading CARD data...</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Error loading */}
|
||||
{error && (
|
||||
<div style={{ ...SECTION, borderColor: 'rgba(239, 68, 68, 0.4)' }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
|
||||
<AlertCircle style={{ width: '14px', height: '14px', color: '#EF4444' }} />
|
||||
<span style={{ fontSize: '0.75rem', color: '#FCA5A5' }}>{error}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Owner data display */}
|
||||
{ownerData && (
|
||||
<>
|
||||
{/* Ownership section */}
|
||||
<div style={SECTION}>
|
||||
<div style={LABEL}>Ownership</div>
|
||||
<div style={{ display: 'grid', gap: '0.5rem', marginTop: '0.3rem' }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
|
||||
<span style={{ fontSize: '0.65rem', color: '#64748B', width: '80px' }}>Confirmed:</span>
|
||||
{ownerData.confirmed ? (
|
||||
<span style={TEAM_BADGE('#10B981')}>{ownerData.confirmed.name}</span>
|
||||
) : (
|
||||
<span style={{ fontSize: '0.7rem', color: '#475569' }}>—</span>
|
||||
)}
|
||||
{ownerData.confirmed && (
|
||||
<span style={{ fontSize: '0.6rem', color: '#64748B' }}>
|
||||
(score: {ownerData.confirmed.score}, {ownerData.confirmed.datasource})
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
|
||||
<span style={{ fontSize: '0.65rem', color: '#64748B', width: '80px' }}>Unconfirmed:</span>
|
||||
{ownerData.unconfirmed ? (
|
||||
<span style={TEAM_BADGE('#F59E0B')}>{ownerData.unconfirmed.name}</span>
|
||||
) : (
|
||||
<span style={{ fontSize: '0.7rem', color: '#475569' }}>—</span>
|
||||
)}
|
||||
</div>
|
||||
{ownerData.candidate && ownerData.candidate.length > 0 && (
|
||||
<div style={{ display: 'flex', alignItems: 'flex-start', gap: '0.5rem' }}>
|
||||
<span style={{ fontSize: '0.65rem', color: '#64748B', width: '80px', flexShrink: 0 }}>Candidates:</span>
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.3rem' }}>
|
||||
{ownerData.candidate.map((c, i) => (
|
||||
<span key={i} style={TEAM_BADGE('#94A3B8')}>{c.name} ({c.score})</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{ownerData.declined && ownerData.declined.length > 0 && (
|
||||
<div style={{ display: 'flex', alignItems: 'flex-start', gap: '0.5rem' }}>
|
||||
<span style={{ fontSize: '0.65rem', color: '#64748B', width: '80px', flexShrink: 0 }}>Declined:</span>
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.3rem' }}>
|
||||
{ownerData.declined.map((d, i) => (
|
||||
<span key={i} style={TEAM_BADGE('#EF4444')}>{d.name}</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Queue item info */}
|
||||
<div style={SECTION}>
|
||||
<div style={LABEL}>Queue Item</div>
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0.3rem', marginTop: '0.3rem' }}>
|
||||
<div><span style={{ fontSize: '0.6rem', color: '#64748B' }}>Hostname: </span><span style={VALUE}>{item.hostname || '—'}</span></div>
|
||||
<div><span style={{ fontSize: '0.6rem', color: '#64748B' }}>IP: </span><span style={VALUE}>{item.ip_address || '—'}</span></div>
|
||||
<div><span style={{ fontSize: '0.6rem', color: '#64748B' }}>Finding: </span><span style={VALUE}>{item.finding_id || '—'}</span></div>
|
||||
<div><span style={{ fontSize: '0.6rem', color: '#64748B' }}>CVE: </span><span style={{ ...VALUE, fontSize: '0.65rem' }}>{item.cves_json ? JSON.parse(item.cves_json).slice(0, 2).join(', ') : '—'}</span></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Action section */}
|
||||
<div style={{ ...SECTION, borderColor: 'rgba(124, 58, 237, 0.3)' }}>
|
||||
<div style={LABEL}>Action</div>
|
||||
<div style={{ display: 'flex', gap: '0.5rem', marginTop: '0.4rem', marginBottom: '0.75rem' }}>
|
||||
{['confirm', 'decline', 'redirect'].map(a => (
|
||||
<button
|
||||
key={a}
|
||||
onClick={() => setAction(a)}
|
||||
style={{
|
||||
...BTN,
|
||||
padding: '0.35rem 0.75rem',
|
||||
background: action === a ? (a === 'confirm' ? 'rgba(16,185,129,0.15)' : a === 'decline' ? 'rgba(239,68,68,0.15)' : 'rgba(14,165,233,0.15)') : 'transparent',
|
||||
border: `1px solid ${action === a ? (a === 'confirm' ? '#10B981' : a === 'decline' ? '#EF4444' : '#0EA5E9') : '#334155'}`,
|
||||
color: action === a ? (a === 'confirm' ? '#10B981' : a === 'decline' ? '#EF4444' : '#0EA5E9') : '#64748B',
|
||||
}}
|
||||
>
|
||||
{a === 'confirm' && <CheckCircle style={{ width: '12px', height: '12px', marginRight: '0.3rem', display: 'inline' }} />}
|
||||
{a === 'decline' && <XCircle style={{ width: '12px', height: '12px', marginRight: '0.3rem', display: 'inline' }} />}
|
||||
{a === 'redirect' && <ArrowRightLeft style={{ width: '12px', height: '12px', marginRight: '0.3rem', display: 'inline' }} />}
|
||||
{a.charAt(0).toUpperCase() + a.slice(1)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Action-specific fields */}
|
||||
{(action === 'confirm' || action === 'decline') && (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
|
||||
<div>
|
||||
<label style={{ ...LABEL, display: 'block' }}>Team</label>
|
||||
<select style={INPUT} value={teamName} onChange={e => setTeamName(e.target.value)}>
|
||||
<option value="">Select team...</option>
|
||||
{/* Pre-populate with owner teams first */}
|
||||
{ownerData.confirmed && <option value={ownerData.confirmed.name}>{ownerData.confirmed.name} (confirmed)</option>}
|
||||
{ownerData.unconfirmed && <option value={ownerData.unconfirmed.name}>{ownerData.unconfirmed.name} (unconfirmed)</option>}
|
||||
{ownerData.candidate && ownerData.candidate.filter(c => c.name !== 'CARD-UNKNOWN').map(c => (
|
||||
<option key={c.name} value={c.name}>{c.name} (candidate, score: {c.score})</option>
|
||||
))}
|
||||
<option disabled>───────────</option>
|
||||
{cardTeams && cardTeams.filter(t => t !== ownerData.confirmed?.name && t !== ownerData.unconfirmed?.name).map(t => (
|
||||
<option key={t} value={t}>{t}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label style={{ ...LABEL, display: 'block' }}>Comment (optional)</label>
|
||||
<input style={INPUT} value={comment} onChange={e => setComment(e.target.value)} placeholder="Optional comment..." />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{action === 'redirect' && (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
|
||||
<div>
|
||||
<label style={{ ...LABEL, display: 'block' }}>From Team</label>
|
||||
<select style={INPUT} value={fromTeam} onChange={e => setFromTeam(e.target.value)}>
|
||||
<option value="">Select from team...</option>
|
||||
{ownerData.confirmed && <option value={ownerData.confirmed.name}>{ownerData.confirmed.name} (confirmed)</option>}
|
||||
{ownerData.unconfirmed && <option value={ownerData.unconfirmed.name}>{ownerData.unconfirmed.name} (unconfirmed)</option>}
|
||||
{cardTeams && cardTeams.map(t => (
|
||||
<option key={t} value={t}>{t}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label style={{ ...LABEL, display: 'block' }}>To Team</label>
|
||||
<select style={INPUT} value={toTeam} onChange={e => setToTeam(e.target.value)}>
|
||||
<option value="">Select to team...</option>
|
||||
{cardTeams && cardTeams.map(t => (
|
||||
<option key={t} value={t}>{t}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Execution error */}
|
||||
{execError && (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', padding: '0.5rem 0.75rem', background: 'rgba(239, 68, 68, 0.1)', border: '1px solid rgba(239, 68, 68, 0.3)', borderRadius: '0.375rem', marginBottom: '0.75rem' }}>
|
||||
<AlertCircle style={{ width: '13px', height: '13px', color: '#EF4444', flexShrink: 0 }} />
|
||||
<span style={{ fontSize: '0.7rem', color: '#FCA5A5' }}>{execError}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Footer */}
|
||||
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: '0.5rem', marginTop: '0.5rem' }}>
|
||||
<button onClick={onClose} style={{ ...BTN, background: '#334155', color: '#E2E8F0' }}>Cancel</button>
|
||||
<button
|
||||
onClick={handleExecute}
|
||||
disabled={!canExecute() || executing}
|
||||
style={{
|
||||
...BTN,
|
||||
background: canExecute() && !executing ? '#7C3AED' : '#1E293B',
|
||||
color: canExecute() && !executing ? '#fff' : '#475569',
|
||||
cursor: canExecute() && !executing ? 'pointer' : 'not-allowed',
|
||||
}}
|
||||
>
|
||||
{executing ? 'Executing...' : `Execute ${action.charAt(0).toUpperCase() + action.slice(1)}`}
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
578
frontend/src/components/LoaderModal.js
Normal file
578
frontend/src/components/LoaderModal.js
Normal file
@@ -0,0 +1,578 @@
|
||||
/**
|
||||
* LoaderModal — Granite Team_Device Loader Sheet Generator
|
||||
*
|
||||
* Generates a properly formatted xlsx for upload to SNIP XperLoad.
|
||||
* Supports queue-initiated mode (pre-populated devices) and standalone mode (paste IPs).
|
||||
*/
|
||||
|
||||
import React, { useState, useEffect, useCallback, useMemo } from 'react';
|
||||
import { FileSpreadsheet, Download, X, RefreshCw, Plus, Trash2, AlertCircle, ChevronDown, ChevronRight } from 'lucide-react';
|
||||
import {
|
||||
LOADER_COLUMNS,
|
||||
COLUMN_GROUPS,
|
||||
OPERATION_TYPES,
|
||||
getRequiredColumns,
|
||||
getColumnsByGroup,
|
||||
} from '../utils/graniteLoaderConfig';
|
||||
import { generateLoaderXlsx, generateFilename } from '../utils/graniteLoaderExport';
|
||||
|
||||
const API_BASE = process.env.REACT_APP_API_BASE || 'http://localhost:3001/api';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Styles
|
||||
// ---------------------------------------------------------------------------
|
||||
const OVERLAY = {
|
||||
position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.7)', zIndex: 9999,
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
};
|
||||
const MODAL = {
|
||||
background: '#1E293B', borderRadius: '0.75rem', border: '1px solid #334155',
|
||||
width: '90vw', maxWidth: '1100px', maxHeight: '90vh', display: 'flex', flexDirection: 'column',
|
||||
overflow: 'hidden',
|
||||
};
|
||||
const HEADER = {
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
|
||||
padding: '1rem 1.25rem', borderBottom: '1px solid #334155',
|
||||
};
|
||||
const BODY = { flex: 1, overflow: 'auto', padding: '1.25rem' };
|
||||
const FOOTER = {
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
|
||||
padding: '1rem 1.25rem', borderTop: '1px solid #334155',
|
||||
};
|
||||
const INPUT = {
|
||||
background: '#0F172A', border: '1px solid #334155', borderRadius: '0.375rem',
|
||||
color: '#E2E8F0', padding: '0.4rem 0.6rem', fontSize: '0.75rem', width: '100%',
|
||||
};
|
||||
const BTN = {
|
||||
padding: '0.5rem 1rem', borderRadius: '0.375rem', border: 'none',
|
||||
fontSize: '0.75rem', fontWeight: '600', cursor: 'pointer',
|
||||
};
|
||||
const BTN_PRIMARY = { ...BTN, background: '#7C3AED', color: '#fff' };
|
||||
const BTN_SECONDARY = { ...BTN, background: '#334155', color: '#E2E8F0' };
|
||||
const BTN_SUCCESS = { ...BTN, background: '#10B981', color: '#fff' };
|
||||
|
||||
export default function LoaderModal({ isOpen, onClose, initialDevices }) {
|
||||
// --- State ---
|
||||
const [operationType, setOperationType] = useState('Change');
|
||||
const [selectedColumns, setSelectedColumns] = useState(new Set());
|
||||
const [devices, setDevices] = useState([]);
|
||||
const [bulkDefaults, setBulkDefaults] = useState({});
|
||||
const [overrides, setOverrides] = useState({});
|
||||
const [editingCell, setEditingCell] = useState(null);
|
||||
const [editValue, setEditValue] = useState('');
|
||||
const [enriching, setEnriching] = useState(false);
|
||||
const [enrichErrors, setEnrichErrors] = useState([]);
|
||||
const [cardConfigured, setCardConfigured] = useState(false);
|
||||
const [pasteInput, setPasteInput] = useState('');
|
||||
const [expandedGroups, setExpandedGroups] = useState(new Set(['Identification', 'Responsible Org']));
|
||||
const [validationWarnings, setValidationWarnings] = useState([]);
|
||||
|
||||
// --- Initialize ---
|
||||
useEffect(() => {
|
||||
if (!isOpen) return;
|
||||
// Check CARD status
|
||||
fetch(`${API_BASE}/card/status`, { credentials: 'include' })
|
||||
.then(r => r.json())
|
||||
.then(d => setCardConfigured(d.configured === true))
|
||||
.catch(() => setCardConfigured(false));
|
||||
}, [isOpen]);
|
||||
|
||||
// Populate devices from initialDevices or reset
|
||||
useEffect(() => {
|
||||
if (!isOpen) return;
|
||||
if (initialDevices && initialDevices.length > 0) {
|
||||
setDevices(initialDevices.map(d => ({
|
||||
IPV4_ADDRESS: d.ip_address || '',
|
||||
EQUIP_NAME: d.hostname || '',
|
||||
})));
|
||||
} else {
|
||||
setDevices([]);
|
||||
}
|
||||
setOverrides({});
|
||||
setBulkDefaults({});
|
||||
setEnrichErrors([]);
|
||||
setValidationWarnings([]);
|
||||
}, [isOpen, initialDevices]);
|
||||
|
||||
// Auto-select required columns + useful defaults when operation type changes
|
||||
useEffect(() => {
|
||||
const required = getRequiredColumns(operationType);
|
||||
setSelectedColumns(prev => {
|
||||
const next = new Set(prev);
|
||||
required.forEach(id => next.add(id));
|
||||
// Always include these useful columns by default
|
||||
next.add('IPV4_ADDRESS');
|
||||
next.add('EQUIP_NAME');
|
||||
next.add('RESPONSIBLE_TEAM');
|
||||
return next;
|
||||
});
|
||||
}, [operationType]);
|
||||
|
||||
// --- Column selection ---
|
||||
const toggleColumn = useCallback((colId) => {
|
||||
const required = getRequiredColumns(operationType);
|
||||
if (required.includes(colId)) return; // Can't deselect required
|
||||
setSelectedColumns(prev => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(colId)) next.delete(colId);
|
||||
else next.add(colId);
|
||||
return next;
|
||||
});
|
||||
}, [operationType]);
|
||||
|
||||
const toggleGroup = useCallback((group) => {
|
||||
setExpandedGroups(prev => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(group)) next.delete(group);
|
||||
else next.add(group);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
// --- Ordered selected columns (canonical order) ---
|
||||
const orderedColumns = useMemo(() => {
|
||||
return LOADER_COLUMNS.filter(col => selectedColumns.has(col.id));
|
||||
}, [selectedColumns]);
|
||||
|
||||
// --- Resolve cell value (override > bulk default > device value > empty) ---
|
||||
const getCellValue = useCallback((rowIdx, colId) => {
|
||||
if (overrides[rowIdx] && overrides[rowIdx][colId] !== undefined) {
|
||||
return overrides[rowIdx][colId];
|
||||
}
|
||||
if (bulkDefaults[colId] !== undefined && bulkDefaults[colId] !== '') {
|
||||
return bulkDefaults[colId];
|
||||
}
|
||||
return devices[rowIdx]?.[colId] || '';
|
||||
}, [overrides, bulkDefaults, devices]);
|
||||
|
||||
// --- Cell editing ---
|
||||
const startEdit = (rowIdx, colId) => {
|
||||
setEditingCell({ rowIdx, colId });
|
||||
setEditValue(getCellValue(rowIdx, colId));
|
||||
};
|
||||
|
||||
const commitEdit = () => {
|
||||
if (!editingCell) return;
|
||||
const { rowIdx, colId } = editingCell;
|
||||
const currentBulk = bulkDefaults[colId] || '';
|
||||
const currentDevice = devices[rowIdx]?.[colId] || '';
|
||||
// Only store override if different from bulk default and device value
|
||||
if (editValue !== currentBulk || currentDevice) {
|
||||
setOverrides(prev => ({
|
||||
...prev,
|
||||
[rowIdx]: { ...(prev[rowIdx] || {}), [colId]: editValue },
|
||||
}));
|
||||
}
|
||||
setEditingCell(null);
|
||||
};
|
||||
|
||||
const clearOverride = (rowIdx, colId) => {
|
||||
setOverrides(prev => {
|
||||
const next = { ...prev };
|
||||
if (next[rowIdx]) {
|
||||
const row = { ...next[rowIdx] };
|
||||
delete row[colId];
|
||||
if (Object.keys(row).length === 0) delete next[rowIdx];
|
||||
else next[rowIdx] = row;
|
||||
}
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
// --- Bulk default ---
|
||||
const setBulkDefault = (colId, value) => {
|
||||
setBulkDefaults(prev => ({ ...prev, [colId]: value }));
|
||||
};
|
||||
|
||||
// --- Paste IPs (standalone mode) ---
|
||||
const loadPastedIps = () => {
|
||||
const lines = pasteInput.split(/[\n,]+/).map(s => s.trim()).filter(Boolean);
|
||||
const newDevices = lines.slice(0, 200).map(ip => ({ IPV4_ADDRESS: ip, EQUIP_NAME: '' }));
|
||||
setDevices(newDevices);
|
||||
setOverrides({});
|
||||
setPasteInput('');
|
||||
};
|
||||
|
||||
const addRow = () => {
|
||||
setDevices(prev => [...prev, { IPV4_ADDRESS: '', EQUIP_NAME: '' }]);
|
||||
};
|
||||
|
||||
const removeRow = (idx) => {
|
||||
setDevices(prev => prev.filter((_, i) => i !== idx));
|
||||
setOverrides(prev => {
|
||||
const next = {};
|
||||
Object.entries(prev).forEach(([k, v]) => {
|
||||
const ki = parseInt(k, 10);
|
||||
if (ki < idx) next[ki] = v;
|
||||
else if (ki > idx) next[ki - 1] = v;
|
||||
});
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
// --- CARD Enrichment ---
|
||||
const enrichFromCard = async () => {
|
||||
const ips = devices.map(d => d.IPV4_ADDRESS).filter(Boolean);
|
||||
if (ips.length === 0) return;
|
||||
|
||||
setEnriching(true);
|
||||
setEnrichErrors([]);
|
||||
|
||||
try {
|
||||
const resp = await fetch(`${API_BASE}/card/enrich-batch`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({ ips }),
|
||||
});
|
||||
|
||||
if (!resp.ok) {
|
||||
const err = await resp.json().catch(() => ({}));
|
||||
setEnrichErrors([{ ip: 'all', error: err.error || `HTTP ${resp.status}` }]);
|
||||
setEnriching(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const data = await resp.json();
|
||||
const errors = [];
|
||||
|
||||
// Map results back to devices
|
||||
setDevices(prev => prev.map((device, idx) => {
|
||||
const result = data.results.find(r => r.ip === device.IPV4_ADDRESS);
|
||||
if (!result || !result.found) {
|
||||
if (result) errors.push({ ip: result.ip, error: result.error || 'Not found' });
|
||||
return device;
|
||||
}
|
||||
|
||||
// Only populate fields that aren't already overridden by the user
|
||||
const updated = { ...device };
|
||||
const rowOverrides = overrides[idx] || {};
|
||||
|
||||
if (result.equip_inst_id && !rowOverrides.EQUIP_INST_ID && !device.EQUIP_INST_ID) {
|
||||
updated.EQUIP_INST_ID = result.equip_inst_id;
|
||||
}
|
||||
if (result.hostname && !rowOverrides.EQUIP_NAME && !device.EQUIP_NAME) {
|
||||
updated.EQUIP_NAME = result.hostname;
|
||||
}
|
||||
if (result.site_name && !rowOverrides.SITE_NAME && !device.SITE_NAME) {
|
||||
updated.SITE_NAME = result.site_name;
|
||||
}
|
||||
if (result.mgmt_ip_asn && !rowOverrides.MGMT_IP_ASN && !device.MGMT_IP_ASN) {
|
||||
updated.MGMT_IP_ASN = result.mgmt_ip_asn;
|
||||
}
|
||||
if (result.responsible_team && !rowOverrides.RESPONSIBLE_TEAM && !device.RESPONSIBLE_TEAM) {
|
||||
updated.RESPONSIBLE_TEAM = result.responsible_team;
|
||||
}
|
||||
if (result.equip_status && !rowOverrides.EQUIP_STATUS && !device.EQUIP_STATUS) {
|
||||
updated.EQUIP_STATUS = result.equip_status;
|
||||
}
|
||||
|
||||
return updated;
|
||||
}));
|
||||
|
||||
setEnrichErrors(errors);
|
||||
} catch (err) {
|
||||
setEnrichErrors([{ ip: 'all', error: err.message }]);
|
||||
}
|
||||
|
||||
setEnriching(false);
|
||||
};
|
||||
|
||||
// --- Validation ---
|
||||
const validate = () => {
|
||||
const required = getRequiredColumns(operationType);
|
||||
const warnings = [];
|
||||
|
||||
devices.forEach((_, rowIdx) => {
|
||||
required.forEach(colId => {
|
||||
if (colId === 'DELETE') return; // Auto-filled
|
||||
const val = getCellValue(rowIdx, colId);
|
||||
if (!val) {
|
||||
warnings.push({ rowIdx, colId });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
setValidationWarnings(warnings);
|
||||
return warnings;
|
||||
};
|
||||
|
||||
// --- Download ---
|
||||
const handleDownload = () => {
|
||||
const warnings = validate();
|
||||
|
||||
// Build final rows
|
||||
const finalRows = devices.map((_, rowIdx) => {
|
||||
const row = {};
|
||||
orderedColumns.forEach(col => {
|
||||
row[col.id] = getCellValue(rowIdx, col.id);
|
||||
});
|
||||
return row;
|
||||
});
|
||||
|
||||
// Determine team name for filename (from bulk default or first row)
|
||||
const teamName = bulkDefaults.RESPONSIBLE_TEAM || finalRows[0]?.RESPONSIBLE_TEAM || '';
|
||||
|
||||
const blob = generateLoaderXlsx({
|
||||
operationType,
|
||||
columnIds: orderedColumns.map(c => c.id),
|
||||
rows: finalRows,
|
||||
});
|
||||
|
||||
const filename = generateFilename(operationType, teamName);
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = filename;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
|
||||
// Keep warnings visible but don't block download
|
||||
if (warnings.length > 0) {
|
||||
// Warnings already displayed in UI
|
||||
}
|
||||
};
|
||||
|
||||
// --- Render ---
|
||||
if (!isOpen) return null;
|
||||
|
||||
const requiredCols = getRequiredColumns(operationType);
|
||||
const isStandalone = !initialDevices || initialDevices.length === 0;
|
||||
const missingCount = validationWarnings.length;
|
||||
const isCellWarning = (rowIdx, colId) => validationWarnings.some(w => w.rowIdx === rowIdx && w.colId === colId);
|
||||
const isOverridden = (rowIdx, colId) => overrides[rowIdx] && overrides[rowIdx][colId] !== undefined;
|
||||
|
||||
return (
|
||||
<div style={OVERLAY} onClick={onClose}>
|
||||
<div style={MODAL} onClick={e => e.stopPropagation()}>
|
||||
{/* Header */}
|
||||
<div style={HEADER}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
|
||||
<FileSpreadsheet style={{ width: '18px', height: '18px', color: '#7C3AED' }} />
|
||||
<span style={{ fontSize: '0.9rem', fontWeight: '700', color: '#E2E8F0' }}>Generate Granite Loader Sheet</span>
|
||||
<span style={{ fontSize: '0.7rem', color: '#64748B' }}>({devices.length} devices)</span>
|
||||
</div>
|
||||
<button onClick={onClose} style={{ background: 'none', border: 'none', color: '#64748B', cursor: 'pointer' }}>
|
||||
<X style={{ width: '18px', height: '18px' }} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Body */}
|
||||
<div style={BODY}>
|
||||
{/* Top controls row */}
|
||||
<div style={{ display: 'flex', gap: '1rem', alignItems: 'flex-end', marginBottom: '1rem', flexWrap: 'wrap' }}>
|
||||
<div>
|
||||
<label style={{ fontSize: '0.65rem', color: '#94A3B8', display: 'block', marginBottom: '0.2rem' }}>Operation</label>
|
||||
<select style={{ ...INPUT, width: '140px', cursor: 'pointer' }} value={operationType} onChange={e => setOperationType(e.target.value)}>
|
||||
{OPERATION_TYPES.map(op => <option key={op} value={op}>{op}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{cardConfigured && (
|
||||
<button style={{ ...BTN_SECONDARY, display: 'flex', alignItems: 'center', gap: '0.3rem' }} onClick={enrichFromCard} disabled={enriching || devices.length === 0}>
|
||||
<RefreshCw style={{ width: '12px', height: '12px', animation: enriching ? 'spin 1s linear infinite' : 'none' }} />
|
||||
{enriching ? 'Enriching...' : 'Enrich from CARD'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Standalone: paste IPs */}
|
||||
{isStandalone && devices.length === 0 && (
|
||||
<div style={{ marginBottom: '1rem', padding: '1rem', background: '#0F172A', borderRadius: '0.5rem', border: '1px solid #334155' }}>
|
||||
<label style={{ fontSize: '0.7rem', color: '#94A3B8', display: 'block', marginBottom: '0.3rem' }}>Paste IP addresses (one per line or comma-separated)</label>
|
||||
<textarea
|
||||
style={{ ...INPUT, height: '80px', resize: 'vertical', fontFamily: 'monospace' }}
|
||||
value={pasteInput}
|
||||
onChange={e => setPasteInput(e.target.value)}
|
||||
placeholder="10.240.78.110 10.240.78.111 172.16.5.20"
|
||||
/>
|
||||
<div style={{ marginTop: '0.5rem', display: 'flex', gap: '0.5rem' }}>
|
||||
<button style={BTN_PRIMARY} onClick={loadPastedIps} disabled={!pasteInput.trim()}>Load IPs</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Enrich errors */}
|
||||
{enrichErrors.length > 0 && (
|
||||
<div style={{ marginBottom: '0.75rem', padding: '0.5rem 0.75rem', background: 'rgba(239, 68, 68, 0.1)', border: '1px solid rgba(239, 68, 68, 0.3)', borderRadius: '0.375rem' }}>
|
||||
<div style={{ fontSize: '0.7rem', color: '#EF4444', display: 'flex', alignItems: 'center', gap: '0.3rem' }}>
|
||||
<AlertCircle style={{ width: '12px', height: '12px' }} />
|
||||
{enrichErrors.length === 1 && enrichErrors[0].ip === 'all'
|
||||
? enrichErrors[0].error
|
||||
: `${enrichErrors.length} device(s) not found in CARD`}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Column selection */}
|
||||
<div style={{ marginBottom: '1rem', padding: '0.75rem', background: '#0F172A', borderRadius: '0.5rem', border: '1px solid #334155' }}>
|
||||
<div style={{ fontSize: '0.7rem', color: '#94A3B8', marginBottom: '0.5rem', fontWeight: '600' }}>Columns</div>
|
||||
{COLUMN_GROUPS.map(group => {
|
||||
const cols = getColumnsByGroup(group);
|
||||
const selectedInGroup = cols.filter(c => selectedColumns.has(c.id)).length;
|
||||
const expanded = expandedGroups.has(group);
|
||||
return (
|
||||
<div key={group} style={{ marginBottom: '0.25rem' }}>
|
||||
<div
|
||||
style={{ display: 'flex', alignItems: 'center', gap: '0.3rem', cursor: 'pointer', padding: '0.2rem 0', userSelect: 'none' }}
|
||||
onClick={() => toggleGroup(group)}
|
||||
>
|
||||
{expanded ? <ChevronDown style={{ width: '12px', height: '12px', color: '#64748B' }} /> : <ChevronRight style={{ width: '12px', height: '12px', color: '#64748B' }} />}
|
||||
<span style={{ fontSize: '0.7rem', color: '#E2E8F0' }}>{group}</span>
|
||||
<span style={{ fontSize: '0.6rem', color: '#64748B' }}>({selectedInGroup} selected)</span>
|
||||
</div>
|
||||
{expanded && (
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.3rem', paddingLeft: '1.2rem', marginTop: '0.2rem' }}>
|
||||
{cols.map(col => {
|
||||
const isRequired = requiredCols.includes(col.id);
|
||||
const isChecked = selectedColumns.has(col.id);
|
||||
return (
|
||||
<label key={col.id} style={{ display: 'flex', alignItems: 'center', gap: '0.2rem', fontSize: '0.65rem', color: isRequired ? '#A78BFA' : '#94A3B8', cursor: isRequired ? 'default' : 'pointer' }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={isChecked}
|
||||
onChange={() => toggleColumn(col.id)}
|
||||
disabled={isRequired}
|
||||
style={{ accentColor: '#7C3AED' }}
|
||||
/>
|
||||
{col.label.length > 30 ? col.id : col.label}
|
||||
{isRequired && <span style={{ fontSize: '0.55rem', color: '#7C3AED' }}>*</span>}
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Bulk defaults */}
|
||||
{orderedColumns.length > 0 && devices.length > 0 && (
|
||||
<div style={{ marginBottom: '1rem', padding: '0.75rem', background: '#0F172A', borderRadius: '0.5rem', border: '1px solid #334155' }}>
|
||||
<div style={{ fontSize: '0.7rem', color: '#94A3B8', marginBottom: '0.5rem', fontWeight: '600' }}>Bulk Defaults (applies to all rows)</div>
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))', gap: '0.5rem' }}>
|
||||
{orderedColumns.filter(c => c.id !== 'DELETE').map(col => (
|
||||
<div key={col.id}>
|
||||
<label style={{ fontSize: '0.6rem', color: '#64748B', display: 'block', marginBottom: '0.15rem' }}>
|
||||
{col.id}
|
||||
</label>
|
||||
<input
|
||||
style={INPUT}
|
||||
value={bulkDefaults[col.id] || ''}
|
||||
onChange={e => setBulkDefault(col.id, e.target.value)}
|
||||
placeholder={`Default for all rows`}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Preview table */}
|
||||
{devices.length > 0 && orderedColumns.length > 0 && (
|
||||
<div style={{ border: '1px solid #334155', borderRadius: '0.5rem', overflow: 'auto', maxHeight: '300px' }}>
|
||||
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.7rem' }}>
|
||||
<thead>
|
||||
<tr style={{ position: 'sticky', top: 0, background: '#0F172A', zIndex: 1 }}>
|
||||
<th style={{ padding: '0.4rem', borderBottom: '1px solid #334155', color: '#64748B', textAlign: 'center', width: '30px' }}>#</th>
|
||||
{orderedColumns.map(col => (
|
||||
<th key={col.id} style={{ padding: '0.4rem 0.5rem', borderBottom: '1px solid #334155', color: '#94A3B8', textAlign: 'left', whiteSpace: 'nowrap' }}>
|
||||
{col.id}
|
||||
</th>
|
||||
))}
|
||||
<th style={{ padding: '0.4rem', borderBottom: '1px solid #334155', width: '30px' }}></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{devices.map((_, rowIdx) => (
|
||||
<tr key={rowIdx} style={{ borderBottom: '1px solid rgba(51, 65, 85, 0.5)' }}>
|
||||
<td style={{ padding: '0.3rem', textAlign: 'center', color: '#475569', fontSize: '0.6rem' }}>{rowIdx + 1}</td>
|
||||
{orderedColumns.map(col => {
|
||||
const value = getCellValue(rowIdx, col.id);
|
||||
const isEditing = editingCell?.rowIdx === rowIdx && editingCell?.colId === col.id;
|
||||
const hasOverride = isOverridden(rowIdx, col.id);
|
||||
const hasWarning = isCellWarning(rowIdx, col.id);
|
||||
|
||||
return (
|
||||
<td
|
||||
key={col.id}
|
||||
style={{
|
||||
padding: '0.2rem 0.4rem',
|
||||
position: 'relative',
|
||||
background: hasWarning ? 'rgba(239, 68, 68, 0.08)' : 'transparent',
|
||||
cursor: 'pointer',
|
||||
minWidth: '100px',
|
||||
}}
|
||||
onClick={() => !isEditing && startEdit(rowIdx, col.id)}
|
||||
>
|
||||
{isEditing ? (
|
||||
<input
|
||||
style={{ ...INPUT, padding: '0.2rem 0.4rem', fontSize: '0.7rem' }}
|
||||
value={editValue}
|
||||
onChange={e => setEditValue(e.target.value)}
|
||||
onBlur={commitEdit}
|
||||
onKeyDown={e => { if (e.key === 'Enter') commitEdit(); if (e.key === 'Escape') setEditingCell(null); }}
|
||||
autoFocus
|
||||
/>
|
||||
) : (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '0.2rem' }}>
|
||||
{hasOverride && <span style={{ color: '#F59E0B', fontSize: '0.5rem' }}>●</span>}
|
||||
<span style={{ color: value ? '#E2E8F0' : '#475569' }}>{value || '—'}</span>
|
||||
{hasOverride && (
|
||||
<button
|
||||
onClick={e => { e.stopPropagation(); clearOverride(rowIdx, col.id); }}
|
||||
style={{ background: 'none', border: 'none', color: '#64748B', cursor: 'pointer', fontSize: '0.55rem', padding: '0 0.2rem' }}
|
||||
title="Revert to bulk default"
|
||||
>↻</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
);
|
||||
})}
|
||||
<td style={{ padding: '0.2rem', textAlign: 'center' }}>
|
||||
<button onClick={() => removeRow(rowIdx)} style={{ background: 'none', border: 'none', color: '#64748B', cursor: 'pointer' }}>
|
||||
<Trash2 style={{ width: '11px', height: '11px' }} />
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Add row button */}
|
||||
{devices.length > 0 && (
|
||||
<button style={{ ...BTN_SECONDARY, marginTop: '0.5rem', display: 'flex', alignItems: 'center', gap: '0.3rem', fontSize: '0.65rem' }} onClick={addRow}>
|
||||
<Plus style={{ width: '11px', height: '11px' }} /> Add Row
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<div style={FOOTER}>
|
||||
<div style={{ fontSize: '0.7rem', color: '#64748B' }}>
|
||||
{missingCount > 0 && (
|
||||
<span style={{ color: '#F59E0B' }}>⚠ {missingCount} missing required field{missingCount > 1 ? 's' : ''}</span>
|
||||
)}
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: '0.5rem' }}>
|
||||
<button style={BTN_SECONDARY} onClick={onClose}>Cancel</button>
|
||||
<button
|
||||
style={{ ...BTN_SUCCESS, display: 'flex', alignItems: 'center', gap: '0.3rem' }}
|
||||
onClick={handleDownload}
|
||||
disabled={devices.length === 0 || orderedColumns.length === 0}
|
||||
>
|
||||
<Download style={{ width: '13px', height: '13px' }} />
|
||||
Download Loader Sheet
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -392,8 +392,13 @@ function MetricTable({ metrics, onSelectMetric }) {
|
||||
|
||||
return (
|
||||
<div style={{ ...CARD_STYLE, marginTop: '1.5rem' }}>
|
||||
<div style={{ fontSize: '0.7rem', color: '#94A3B8', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: '1rem' }}>
|
||||
Metrics Overview
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', marginBottom: '1rem' }}>
|
||||
<span style={{ fontSize: '0.7rem', color: '#94A3B8', textTransform: 'uppercase', letterSpacing: '0.05em' }}>
|
||||
Metrics Overview
|
||||
</span>
|
||||
<span style={{ fontSize: '0.6rem', color: '#64748B', background: 'rgba(100, 116, 139, 0.1)', padding: '0.15rem 0.4rem', borderRadius: '3px', fontWeight: '600' }}>
|
||||
LAST REPORT
|
||||
</span>
|
||||
</div>
|
||||
<div style={{ overflowX: 'auto' }}>
|
||||
<table style={TABLE_STYLE}>
|
||||
@@ -1422,8 +1427,13 @@ function ForecastBurndownChart({ metricId }) {
|
||||
|
||||
return (
|
||||
<div style={{ ...CARD_STYLE }}>
|
||||
<div style={{ fontSize: '0.7rem', color: '#94A3B8', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: '1rem' }}>
|
||||
Forecast Burndown — {metricId}
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', marginBottom: '1rem' }}>
|
||||
<span style={{ fontSize: '0.7rem', color: '#94A3B8', textTransform: 'uppercase', letterSpacing: '0.05em' }}>
|
||||
Forecast Burndown — {metricId}
|
||||
</span>
|
||||
<span style={{ fontSize: '0.6rem', color: '#10B981', background: 'rgba(16, 185, 129, 0.1)', padding: '0.15rem 0.4rem', borderRadius: '3px', fontWeight: '600' }}>
|
||||
LIVE
|
||||
</span>
|
||||
</div>
|
||||
<ResponsiveContainer width="100%" height={350}>
|
||||
<ComposedChart data={combinedData} margin={{ top: 35, right: 40, left: 10, bottom: 5 }}>
|
||||
|
||||
@@ -55,12 +55,69 @@ export default function ComplianceDetailPanel({ hostname, onClose, onNoteAdded,
|
||||
const [metaSaving, setMetaSaving] = useState(false);
|
||||
const [metaError, setMetaError] = useState(null);
|
||||
|
||||
const handleSaveMetadata = async (fields) => {
|
||||
// Per-metric metadata selection (separate from notes selector)
|
||||
const [metricSelection, setMetricSelection] = useState([]);
|
||||
// Track whether user has edited fields (to detect "Multiple values" untouched)
|
||||
const [resolutionDateEdited, setResolutionDateEdited] = useState(false);
|
||||
const [remediationPlanEdited, setRemediationPlanEdited] = useState(false);
|
||||
|
||||
// Compute shared values for selected metrics
|
||||
const computeSharedValues = useCallback((selectedIds, metrics) => {
|
||||
if (!metrics || selectedIds.length === 0) return { resolution_date: '', remediation_plan: '', resolutionMultiple: false, planMultiple: false };
|
||||
const selected = metrics.filter(m => selectedIds.includes(m.metric_id));
|
||||
if (selected.length === 0) return { resolution_date: '', remediation_plan: '', resolutionMultiple: false, planMultiple: false };
|
||||
|
||||
const dates = selected.map(m => m.resolution_date || '');
|
||||
const plans = selected.map(m => m.remediation_plan || '');
|
||||
|
||||
const allDatesMatch = dates.every(d => d === dates[0]);
|
||||
const allPlansMatch = plans.every(p => p === plans[0]);
|
||||
|
||||
return {
|
||||
resolution_date: allDatesMatch ? dates[0] : '',
|
||||
remediation_plan: allPlansMatch ? plans[0] : '',
|
||||
resolutionMultiple: !allDatesMatch,
|
||||
planMultiple: !allPlansMatch,
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Recompute displayed values when metric selection changes
|
||||
useEffect(() => {
|
||||
if (!detail || metricSelection.length === 0) return;
|
||||
const shared = computeSharedValues(metricSelection, detail.metrics);
|
||||
setResolutionDate(shared.resolution_date);
|
||||
setRemediationPlan(shared.remediation_plan);
|
||||
setResolutionDateEdited(false);
|
||||
setRemediationPlanEdited(false);
|
||||
}, [metricSelection, detail, computeSharedValues]);
|
||||
|
||||
// Determine if "Multiple values" placeholders should show
|
||||
const sharedInfo = detail ? computeSharedValues(metricSelection, detail.metrics) : { resolutionMultiple: false, planMultiple: false };
|
||||
|
||||
const handleSaveMetadata = async () => {
|
||||
setMetaSaving(true);
|
||||
setMetaError(null);
|
||||
try {
|
||||
const body = { ...fields };
|
||||
const body = {};
|
||||
|
||||
// Only include resolution_date if user edited it or it's not a "Multiple values" situation
|
||||
if (resolutionDateEdited || !sharedInfo.resolutionMultiple) {
|
||||
body.resolution_date = resolutionDate || null;
|
||||
}
|
||||
// Only include remediation_plan if user edited it or it's not a "Multiple values" situation
|
||||
if (remediationPlanEdited || !sharedInfo.planMultiple) {
|
||||
body.remediation_plan = remediationPlan || null;
|
||||
}
|
||||
|
||||
if (changeReason.trim()) body.change_reason = changeReason.trim();
|
||||
|
||||
// Per-metric scoping: omit metric_ids when all active metrics are selected (backward compat)
|
||||
const activeIds = (detail?.metrics || []).filter(m => m.status === 'active').map(m => m.metric_id);
|
||||
const allSelected = activeIds.length > 0 && activeIds.every(id => metricSelection.includes(id)) && metricSelection.length === activeIds.length;
|
||||
if (!allSelected && metricSelection.length > 0) {
|
||||
body.metric_ids = metricSelection;
|
||||
}
|
||||
|
||||
const res = await fetch(`${API_BASE}/compliance/items/${encodeURIComponent(hostname)}/metadata`, {
|
||||
method: 'PATCH',
|
||||
credentials: 'include',
|
||||
@@ -70,6 +127,8 @@ export default function ComplianceDetailPanel({ hostname, onClose, onNoteAdded,
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error || 'Failed to save metadata');
|
||||
setChangeReason('');
|
||||
setResolutionDateEdited(false);
|
||||
setRemediationPlanEdited(false);
|
||||
// Re-fetch to get updated history
|
||||
await fetchDetail();
|
||||
} catch (err) {
|
||||
@@ -88,13 +147,20 @@ export default function ComplianceDetailPanel({ hostname, onClose, onNoteAdded,
|
||||
if (!res.ok) throw new Error(data.error || 'Failed to load device');
|
||||
setDetail(data);
|
||||
|
||||
// Default selected metrics to first active failing metric
|
||||
// Default selected metrics to first active failing metric (for notes)
|
||||
const firstActive = (data.metrics || []).find(m => m.status === 'active');
|
||||
if (firstActive) setSelectedMetrics([firstActive.metric_id]);
|
||||
|
||||
// Populate metadata fields
|
||||
setResolutionDate(data.resolution_date || '');
|
||||
setRemediationPlan(data.remediation_plan || '');
|
||||
// Default metricSelection to ALL active metrics (for metadata editing)
|
||||
const allActiveIds = (data.metrics || []).filter(m => m.status === 'active').map(m => m.metric_id);
|
||||
setMetricSelection(allActiveIds);
|
||||
|
||||
// Populate metadata fields from shared values
|
||||
const shared = computeSharedValues(allActiveIds, data.metrics);
|
||||
setResolutionDate(shared.resolution_date);
|
||||
setRemediationPlan(shared.remediation_plan);
|
||||
setResolutionDateEdited(false);
|
||||
setRemediationPlanEdited(false);
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
@@ -249,18 +315,114 @@ export default function ComplianceDetailPanel({ hostname, onClose, onNoteAdded,
|
||||
</Section>
|
||||
)}
|
||||
|
||||
{/* Metric Selector for Metadata Editing */}
|
||||
{activeMetrics.length > 0 && (
|
||||
<Section title="Apply To Metrics" icon={<Shield style={{ width: '14px', height: '14px' }} />}>
|
||||
{activeMetrics.length > 1 && (() => {
|
||||
const allMetaSelected = activeMetrics.every(m => metricSelection.includes(m.metric_id)) && metricSelection.length === activeMetrics.length;
|
||||
return (
|
||||
<div style={{ marginBottom: '0.5rem' }}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '0.35rem' }}>
|
||||
<span style={{ fontSize: '0.68rem', fontFamily: 'monospace', color: '#64748B' }}>
|
||||
{metricSelection.length} of {activeMetrics.length} selected
|
||||
</span>
|
||||
<button
|
||||
onClick={() => {
|
||||
if (allMetaSelected) {
|
||||
setMetricSelection([activeMetrics[0].metric_id]);
|
||||
} else {
|
||||
setMetricSelection(activeMetrics.map(m => m.metric_id));
|
||||
}
|
||||
}}
|
||||
style={{
|
||||
background: 'none', border: 'none', cursor: 'pointer',
|
||||
fontSize: '0.68rem', fontFamily: 'monospace',
|
||||
color: TEAL, padding: 0,
|
||||
transition: 'opacity 0.15s',
|
||||
}}
|
||||
onMouseEnter={e => e.currentTarget.style.opacity = '0.7'}
|
||||
onMouseLeave={e => e.currentTarget.style.opacity = '1'}
|
||||
>
|
||||
{allMetaSelected ? 'Deselect All' : 'Select All'}
|
||||
</button>
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.35rem' }}>
|
||||
{activeMetrics.map(m => {
|
||||
const isSelected = metricSelection.includes(m.metric_id);
|
||||
const color = categoryColor(m.category);
|
||||
return (
|
||||
<button
|
||||
key={m.metric_id}
|
||||
onClick={() => {
|
||||
if (isSelected) {
|
||||
if (metricSelection.length > 1) {
|
||||
setMetricSelection(metricSelection.filter(id => id !== m.metric_id));
|
||||
}
|
||||
} else {
|
||||
setMetricSelection([...metricSelection, m.metric_id]);
|
||||
}
|
||||
}}
|
||||
style={{
|
||||
display: 'inline-flex', alignItems: 'center',
|
||||
padding: '0.25rem 0.5rem',
|
||||
background: isSelected ? `${color}25` : `${color}08`,
|
||||
border: `1px solid ${isSelected ? `${color}90` : `${color}30`}`,
|
||||
borderRadius: '0.25rem',
|
||||
color: isSelected ? color : `${color}90`,
|
||||
fontSize: '0.7rem', fontFamily: 'monospace', fontWeight: '600',
|
||||
cursor: (isSelected && metricSelection.length === 1) ? 'default' : 'pointer',
|
||||
transition: 'all 0.15s',
|
||||
opacity: (isSelected && metricSelection.length === 1) ? 0.85 : 1,
|
||||
}}
|
||||
>
|
||||
{m.metric_id}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
{activeMetrics.length === 1 && (
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.35rem' }}>
|
||||
{activeMetrics.map(m => {
|
||||
const color = categoryColor(m.category);
|
||||
return (
|
||||
<span
|
||||
key={m.metric_id}
|
||||
style={{
|
||||
display: 'inline-flex', alignItems: 'center',
|
||||
padding: '0.25rem 0.5rem',
|
||||
background: `${color}25`,
|
||||
border: `1px solid ${color}90`,
|
||||
borderRadius: '0.25rem',
|
||||
color: color,
|
||||
fontSize: '0.7rem', fontFamily: 'monospace', fontWeight: '600',
|
||||
opacity: 0.85,
|
||||
}}
|
||||
>
|
||||
{m.metric_id}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</Section>
|
||||
)}
|
||||
|
||||
{/* Resolution Date */}
|
||||
<Section title="Resolution Date" icon={<Calendar style={{ width: '14px', height: '14px' }} />}>
|
||||
<input
|
||||
type="date"
|
||||
value={resolutionDate}
|
||||
onChange={e => setResolutionDate(e.target.value)}
|
||||
onChange={e => { setResolutionDate(e.target.value); setResolutionDateEdited(true); }}
|
||||
placeholder={sharedInfo.resolutionMultiple ? 'Multiple values' : ''}
|
||||
style={{
|
||||
width: '100%',
|
||||
background: 'rgba(15,23,42,0.8)',
|
||||
border: '1px solid rgba(20,184,166,0.25)',
|
||||
borderRadius: '0.375rem',
|
||||
color: '#F8FAFC',
|
||||
color: sharedInfo.resolutionMultiple && !resolutionDateEdited ? '#64748B' : '#F8FAFC',
|
||||
padding: '0.5rem 0.625rem',
|
||||
fontSize: '0.8rem',
|
||||
fontFamily: 'monospace',
|
||||
@@ -268,6 +430,11 @@ export default function ComplianceDetailPanel({ hostname, onClose, onNoteAdded,
|
||||
}}
|
||||
onFocus={e => e.target.style.borderColor = `${TEAL}70`}
|
||||
/>
|
||||
{sharedInfo.resolutionMultiple && !resolutionDateEdited && (
|
||||
<div style={{ fontSize: '0.65rem', color: '#64748B', fontStyle: 'italic', marginTop: '0.25rem' }}>
|
||||
Multiple values — leave unchanged to preserve per-metric dates
|
||||
</div>
|
||||
)}
|
||||
</Section>
|
||||
|
||||
{/* Remediation Plan */}
|
||||
@@ -275,16 +442,16 @@ export default function ComplianceDetailPanel({ hostname, onClose, onNoteAdded,
|
||||
<textarea
|
||||
value={remediationPlan}
|
||||
onChange={e => {
|
||||
if (e.target.value.length <= 2000) setRemediationPlan(e.target.value);
|
||||
if (e.target.value.length <= 2000) { setRemediationPlan(e.target.value); setRemediationPlanEdited(true); }
|
||||
}}
|
||||
placeholder="Describe the remediation plan…"
|
||||
placeholder={sharedInfo.planMultiple ? 'Multiple values' : 'Describe the remediation plan…'}
|
||||
rows={4}
|
||||
style={{
|
||||
width: '100%', resize: 'vertical',
|
||||
background: 'rgba(15,23,42,0.8)',
|
||||
border: '1px solid rgba(20,184,166,0.25)',
|
||||
borderRadius: '0.375rem',
|
||||
color: '#F8FAFC',
|
||||
color: sharedInfo.planMultiple && !remediationPlanEdited ? '#64748B' : '#F8FAFC',
|
||||
padding: '0.5rem 0.625rem',
|
||||
fontSize: '0.8rem',
|
||||
outline: 'none',
|
||||
@@ -293,12 +460,17 @@ export default function ComplianceDetailPanel({ hostname, onClose, onNoteAdded,
|
||||
onFocus={e => e.target.style.borderColor = `${TEAL}70`}
|
||||
onBlur={e => e.target.style.borderColor = 'rgba(20,184,166,0.25)'}
|
||||
/>
|
||||
{sharedInfo.planMultiple && !remediationPlanEdited && (
|
||||
<div style={{ fontSize: '0.65rem', color: '#64748B', fontStyle: 'italic', marginTop: '0.25rem' }}>
|
||||
Multiple values — leave unchanged to preserve per-metric plans
|
||||
</div>
|
||||
)}
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: '0.4rem' }}>
|
||||
<span style={{ fontSize: '0.68rem', fontFamily: 'monospace', color: remediationPlan.length > 1900 ? '#F59E0B' : '#475569' }}>
|
||||
{remediationPlan.length}/2000
|
||||
</span>
|
||||
<button
|
||||
onClick={() => handleSaveMetadata({ resolution_date: resolutionDate || null, remediation_plan: remediationPlan || null })}
|
||||
onClick={() => handleSaveMetadata()}
|
||||
disabled={metaSaving}
|
||||
style={{
|
||||
display: 'inline-flex', alignItems: 'center', gap: '0.3rem',
|
||||
@@ -346,6 +518,10 @@ export default function ComplianceDetailPanel({ hostname, onClose, onNoteAdded,
|
||||
{detail.history && detail.history.length > 0 && (
|
||||
<Section title="Change History" icon={<Clock style={{ width: '14px', height: '14px' }} />}>
|
||||
{(() => {
|
||||
// Build metricMap from metrics array for chip coloring
|
||||
const metricMap = {};
|
||||
(detail.metrics || []).forEach(m => { metricMap[m.metric_id] = m.category; });
|
||||
|
||||
// Group entries by timestamp + user (entries saved together appear as one)
|
||||
const groups = [];
|
||||
for (const h of detail.history) {
|
||||
@@ -366,7 +542,19 @@ export default function ComplianceDetailPanel({ hostname, onClose, onNoteAdded,
|
||||
</span>
|
||||
</div>
|
||||
{group.entries.map(h => (
|
||||
<div key={h.id} style={{ marginBottom: '0.2rem' }}>
|
||||
<div key={h.id} style={{ marginBottom: '0.2rem', display: 'flex', alignItems: 'center', gap: '0.35rem', flexWrap: 'wrap' }}>
|
||||
{h.metric_id ? (
|
||||
<MetricChip metricId={h.metric_id} category={metricMap[h.metric_id] || ''} />
|
||||
) : (
|
||||
<span style={{
|
||||
fontSize: '0.68rem',
|
||||
color: '#64748B',
|
||||
fontStyle: 'italic',
|
||||
padding: '0.15rem 0.4rem',
|
||||
background: 'rgba(100,116,139,0.1)',
|
||||
borderRadius: '0.2rem',
|
||||
}}>All metrics</span>
|
||||
)}
|
||||
<span style={{ fontSize: '0.65rem', color: '#64748B' }}>
|
||||
{h.field_name === 'resolution_date' ? '📅 ' : '📋 '}
|
||||
</span>
|
||||
|
||||
@@ -93,6 +93,7 @@ function groupByMetricFamily(allEntries, team) {
|
||||
function VariantPill({ entry, label }) {
|
||||
const color = statusColor(entry.status);
|
||||
const isOk = entry.status === 'Meets/Exceeds Target';
|
||||
const hasRawCounts = entry.compliant != null && entry.total != null && entry.total > 0;
|
||||
return (
|
||||
<span style={{
|
||||
display: 'inline-flex',
|
||||
@@ -116,6 +117,9 @@ function VariantPill({ entry, label }) {
|
||||
)}
|
||||
{label && <span style={{ color: '#94A3B8' }}>{label}</span>}
|
||||
<span style={{ color, fontWeight: '600' }}>{pctDisplay(entry.compliance_pct)}</span>
|
||||
{hasRawCounts && (
|
||||
<span style={{ color: '#64748B', fontSize: '0.58rem' }}>({entry.compliant}/{entry.total})</span>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -877,7 +881,7 @@ function DeviceRow({ device, selected, onClick }) {
|
||||
|
||||
{/* Resolution Date */}
|
||||
<div style={{ fontFamily: 'monospace', fontSize: '0.72rem', color: '#94A3B8' }}>
|
||||
{device.resolution_date || '—'}
|
||||
{device.resolution_date ? device.resolution_date.slice(0, 10) : '—'}
|
||||
</div>
|
||||
|
||||
{/* Remediation Plan */}
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import React, { useState, useEffect, useCallback, useMemo } from 'react';
|
||||
import { ListTodo, RefreshCw, CheckSquare, Square, Loader, AlertCircle, X, Plus, CheckCircle } from 'lucide-react';
|
||||
import { ListTodo, RefreshCw, CheckSquare, Square, Loader, AlertCircle, X, Plus, CheckCircle, ChevronDown, ChevronRight, FileSpreadsheet } from 'lucide-react';
|
||||
import { useAuth } from '../../contexts/AuthContext';
|
||||
import ConsolidationModal from '../ConsolidationModal';
|
||||
import LoaderModal from '../LoaderModal';
|
||||
import { generateConsolidatedSummary, generateConsolidatedDescription, extractFirstCve, extractCommonVendor } from '../../utils/jiraConsolidation';
|
||||
import { groupQueueItems } from '../../utils/queueGrouping';
|
||||
import { VENDOR_PROJECT_KEYS, VENDOR_ISSUE_TYPES, STEAM_ISSUE_TYPES, isVendorProject, getIssueTypesForProject } from './JiraPage';
|
||||
|
||||
const API_BASE = process.env.REACT_APP_API_BASE || 'http://localhost:3001/api';
|
||||
|
||||
@@ -234,6 +237,45 @@ const STYLES = {
|
||||
width: '100%',
|
||||
outline: 'none',
|
||||
},
|
||||
sectionHeaderInventory: {
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: '0.5rem',
|
||||
padding: '0.5rem 0.75rem',
|
||||
marginTop: '0.5rem',
|
||||
borderBottom: '1px solid rgba(16, 185, 129, 0.2)',
|
||||
cursor: 'pointer',
|
||||
userSelect: 'none',
|
||||
fontFamily: 'monospace',
|
||||
fontSize: '0.7rem',
|
||||
fontWeight: 700,
|
||||
color: '#10B981',
|
||||
textTransform: 'uppercase',
|
||||
letterSpacing: '0.1em',
|
||||
},
|
||||
sectionHeaderVendor: {
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: '0.5rem',
|
||||
padding: '0.5rem 0.75rem',
|
||||
marginTop: '0.5rem',
|
||||
borderBottom: '1px solid rgba(148, 163, 184, 0.15)',
|
||||
cursor: 'pointer',
|
||||
userSelect: 'none',
|
||||
fontFamily: 'monospace',
|
||||
fontSize: '0.7rem',
|
||||
fontWeight: 700,
|
||||
color: '#94A3B8',
|
||||
textTransform: 'uppercase',
|
||||
letterSpacing: '0.1em',
|
||||
},
|
||||
sectionCount: {
|
||||
fontFamily: 'monospace',
|
||||
fontSize: '0.65rem',
|
||||
fontWeight: 600,
|
||||
color: '#64748B',
|
||||
marginLeft: '0.25rem',
|
||||
},
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -259,12 +301,16 @@ export default function IvantiTodoQueuePage() {
|
||||
|
||||
// Single-item Jira creation modal state (Requirement 2.4)
|
||||
const [showSingleJiraModal, setShowSingleJiraModal] = useState(false);
|
||||
const [showLoaderModal, setShowLoaderModal] = useState(false);
|
||||
const [singleJiraItem, setSingleJiraItem] = useState(null);
|
||||
const [singleJiraForm, setSingleJiraForm] = useState({ cve_id: '', vendor: '', summary: '', description: '', source_context: 'ivanti_queue' });
|
||||
const [singleJiraForm, setSingleJiraForm] = useState({ cve_id: '', vendor: '', summary: '', description: '', source_context: 'ivanti_queue', project_key: '', issue_type: '' });
|
||||
const [singleJiraError, setSingleJiraError] = useState(null);
|
||||
const [singleJiraSaving, setSingleJiraSaving] = useState(false);
|
||||
const [singleJiraSummaryError, setSingleJiraSummaryError] = useState(null);
|
||||
|
||||
// Collapse state for grouped sections (Requirement 2.2, 2.7)
|
||||
const [collapsedSections, setCollapsedSections] = useState({});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Data fetching
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -323,6 +369,21 @@ export default function IvantiTodoQueuePage() {
|
||||
return queueItems.filter((item) => item.status === 'pending');
|
||||
}, [queueItems]);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Grouped sections — hybrid Inventory + vendor grouping (Requirements 1.1–1.7)
|
||||
// ---------------------------------------------------------------------------
|
||||
const groupedSections = useMemo(() => groupQueueItems(visibleItems), [visibleItems]);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Toggle section collapse (Requirement 2.2, 2.7)
|
||||
// ---------------------------------------------------------------------------
|
||||
const toggleSection = useCallback((sectionKey) => {
|
||||
setCollapsedSections((prev) => ({
|
||||
...prev,
|
||||
[sectionKey]: !prev[sectionKey],
|
||||
}));
|
||||
}, []);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Selection mode toggle (Requirement 1.1, 1.5)
|
||||
// When deactivated, clear all selections
|
||||
@@ -422,6 +483,8 @@ export default function IvantiTodoQueuePage() {
|
||||
summary: generateConsolidatedSummary(items),
|
||||
description: generateConsolidatedDescription(items),
|
||||
source_context: 'ivanti_queue',
|
||||
project_key: '',
|
||||
issue_type: '',
|
||||
});
|
||||
setSingleJiraError(null);
|
||||
setSingleJiraSummaryError(null);
|
||||
@@ -627,158 +690,190 @@ export default function IvantiTodoQueuePage() {
|
||||
<span style={{ ...STYLES.tableHeaderLabel, width: '120px' }}>Host</span>
|
||||
</div>
|
||||
|
||||
{/* Queue item rows */}
|
||||
{visibleItems.map((item) => {
|
||||
const isSelected = selectedIds.has(item.id);
|
||||
const wfColor = getWorkflowColor(item.workflow_type);
|
||||
const cves = item.cves || [];
|
||||
const cveDisplay = cves.length > 0
|
||||
? cves.slice(0, 2).join(', ') + (cves.length > 2 ? ` +${cves.length - 2}` : '')
|
||||
: '';
|
||||
{/* Grouped sections with collapsible headers (Requirements 2.1, 2.3–2.6, 3.1, 3.2) */}
|
||||
{groupedSections.map((section) => {
|
||||
const isCollapsed = !!collapsedSections[section.key];
|
||||
|
||||
return (
|
||||
<div
|
||||
key={item.id}
|
||||
style={isSelected ? STYLES.queueItemSelected : STYLES.queueItem}
|
||||
onClick={selectionMode ? () => toggleItemSelection(item.id) : undefined}
|
||||
role={selectionMode ? 'button' : undefined}
|
||||
tabIndex={selectionMode ? 0 : undefined}
|
||||
onKeyDown={selectionMode ? (e) => { if (e.key === ' ' || e.key === 'Enter') { e.preventDefault(); toggleItemSelection(item.id); } } : undefined}
|
||||
>
|
||||
{/* Selection checkbox (Requirement 1.2) */}
|
||||
{selectionMode && (
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={isSelected}
|
||||
onChange={(e) => { e.stopPropagation(); toggleItemSelection(item.id); }}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
style={STYLES.checkbox}
|
||||
aria-label={`Select ${item.finding_title || item.finding_id}`}
|
||||
/>
|
||||
)}
|
||||
<div key={section.key}>
|
||||
{/* Section Header */}
|
||||
<div
|
||||
onClick={() => toggleSection(section.key)}
|
||||
style={section.type === 'inventory' ? STYLES.sectionHeaderInventory : STYLES.sectionHeaderVendor}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
toggleSection(section.key);
|
||||
}
|
||||
}}
|
||||
aria-expanded={!isCollapsed}
|
||||
aria-label={`${section.label} section, ${section.items.length} items`}
|
||||
>
|
||||
{isCollapsed
|
||||
? <ChevronRight style={{ width: '14px', height: '14px' }} />
|
||||
: <ChevronDown style={{ width: '14px', height: '14px' }} />
|
||||
}
|
||||
<span>{section.label}</span>
|
||||
<span style={STYLES.sectionCount}>({section.items.length})</span>
|
||||
</div>
|
||||
|
||||
{/* Finding info */}
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<div style={{
|
||||
fontFamily: 'monospace',
|
||||
fontSize: '0.75rem',
|
||||
fontWeight: 600,
|
||||
color: '#CBD5E1',
|
||||
overflow: 'hidden',
|
||||
textOverflow: 'ellipsis',
|
||||
whiteSpace: 'nowrap',
|
||||
}} title={item.finding_title || item.finding_id}>
|
||||
{item.finding_title || item.finding_id}
|
||||
</div>
|
||||
{cveDisplay && (
|
||||
<div style={{
|
||||
fontFamily: 'monospace',
|
||||
fontSize: '0.65rem',
|
||||
color: '#64748B',
|
||||
marginTop: '2px',
|
||||
overflow: 'hidden',
|
||||
textOverflow: 'ellipsis',
|
||||
whiteSpace: 'nowrap',
|
||||
}} title={cves.join(', ')}>
|
||||
{cveDisplay}
|
||||
{/* Section Body — only rendered when expanded */}
|
||||
{!isCollapsed && section.items.map((item) => {
|
||||
const isSelected = selectedIds.has(item.id);
|
||||
const wfColor = getWorkflowColor(item.workflow_type);
|
||||
const cves = item.cves || [];
|
||||
const cveDisplay = cves.length > 0
|
||||
? cves.slice(0, 2).join(', ') + (cves.length > 2 ? ` +${cves.length - 2}` : '')
|
||||
: '';
|
||||
|
||||
return (
|
||||
<div
|
||||
key={item.id}
|
||||
style={isSelected ? STYLES.queueItemSelected : STYLES.queueItem}
|
||||
onClick={selectionMode ? () => toggleItemSelection(item.id) : undefined}
|
||||
role={selectionMode ? 'button' : undefined}
|
||||
tabIndex={selectionMode ? 0 : undefined}
|
||||
onKeyDown={selectionMode ? (e) => { if (e.key === ' ' || e.key === 'Enter') { e.preventDefault(); toggleItemSelection(item.id); } } : undefined}
|
||||
>
|
||||
{/* Selection checkbox (Requirement 1.2) */}
|
||||
{selectionMode && (
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={isSelected}
|
||||
onChange={(e) => { e.stopPropagation(); toggleItemSelection(item.id); }}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
style={STYLES.checkbox}
|
||||
aria-label={`Select ${item.finding_title || item.finding_id}`}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Finding info */}
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<div style={{
|
||||
fontFamily: 'monospace',
|
||||
fontSize: '0.75rem',
|
||||
fontWeight: 600,
|
||||
color: '#CBD5E1',
|
||||
overflow: 'hidden',
|
||||
textOverflow: 'ellipsis',
|
||||
whiteSpace: 'nowrap',
|
||||
}} title={item.finding_title || item.finding_id}>
|
||||
{item.finding_title || item.finding_id}
|
||||
</div>
|
||||
{cveDisplay && (
|
||||
<div style={{
|
||||
fontFamily: 'monospace',
|
||||
fontSize: '0.65rem',
|
||||
color: '#64748B',
|
||||
marginTop: '2px',
|
||||
overflow: 'hidden',
|
||||
textOverflow: 'ellipsis',
|
||||
whiteSpace: 'nowrap',
|
||||
}} title={cves.join(', ')}>
|
||||
{cveDisplay}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Ticket link badge (Requirements 6.3, 6.4) */}
|
||||
{ticketLinks[item.id] && (
|
||||
<a
|
||||
href={ticketLinks[item.id].jira_url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
style={{
|
||||
fontFamily: 'monospace',
|
||||
fontSize: '0.6rem',
|
||||
fontWeight: 700,
|
||||
color: '#6EE7B7',
|
||||
background: 'rgba(16, 185, 129, 0.1)',
|
||||
border: '1px solid rgba(16, 185, 129, 0.3)',
|
||||
borderRadius: '999px',
|
||||
padding: '0.15rem 0.5rem',
|
||||
textDecoration: 'none',
|
||||
whiteSpace: 'nowrap',
|
||||
flexShrink: 0,
|
||||
display: 'inline-flex',
|
||||
alignItems: 'center',
|
||||
gap: '0.25rem',
|
||||
transition: 'all 0.2s',
|
||||
}}
|
||||
title={`Open ${ticketLinks[item.id].ticket_key} in Jira`}
|
||||
>
|
||||
{ticketLinks[item.id].ticket_key} ↗
|
||||
</a>
|
||||
)}
|
||||
|
||||
{/* Workflow type badge */}
|
||||
<div style={{
|
||||
width: '80px',
|
||||
textAlign: 'center',
|
||||
flexShrink: 0,
|
||||
}}>
|
||||
<span style={{
|
||||
fontFamily: 'monospace',
|
||||
fontSize: '0.6rem',
|
||||
fontWeight: 700,
|
||||
color: wfColor.col,
|
||||
background: `rgba(${wfColor.rgb}, 0.1)`,
|
||||
border: `1px solid rgba(${wfColor.rgb}, 0.3)`,
|
||||
borderRadius: '4px',
|
||||
padding: '0.15rem 0.4rem',
|
||||
textTransform: 'uppercase',
|
||||
}}>
|
||||
{item.workflow_type}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Vendor */}
|
||||
<div style={{
|
||||
width: '120px',
|
||||
flexShrink: 0,
|
||||
fontFamily: 'monospace',
|
||||
fontSize: '0.68rem',
|
||||
color: '#94A3B8',
|
||||
overflow: 'hidden',
|
||||
textOverflow: 'ellipsis',
|
||||
whiteSpace: 'nowrap',
|
||||
}} title={item.vendor}>
|
||||
{item.vendor || '—'}
|
||||
</div>
|
||||
|
||||
{/* Hostname / IP */}
|
||||
<div style={{
|
||||
width: '120px',
|
||||
flexShrink: 0,
|
||||
minWidth: 0,
|
||||
}}>
|
||||
{item.hostname && (
|
||||
<div style={{
|
||||
fontFamily: 'monospace',
|
||||
fontSize: '0.65rem',
|
||||
color: '#94A3B8',
|
||||
overflow: 'hidden',
|
||||
textOverflow: 'ellipsis',
|
||||
whiteSpace: 'nowrap',
|
||||
}} title={item.hostname}>
|
||||
{item.hostname}
|
||||
</div>
|
||||
)}
|
||||
{item.ip_address && (
|
||||
<div style={{
|
||||
fontFamily: 'monospace',
|
||||
fontSize: '0.62rem',
|
||||
color: '#10B981',
|
||||
marginTop: item.hostname ? '1px' : 0,
|
||||
}}>
|
||||
{item.ip_address}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Ticket link badge (Requirements 6.3, 6.4) */}
|
||||
{ticketLinks[item.id] && (
|
||||
<a
|
||||
href={ticketLinks[item.id].jira_url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
style={{
|
||||
fontFamily: 'monospace',
|
||||
fontSize: '0.6rem',
|
||||
fontWeight: 700,
|
||||
color: '#6EE7B7',
|
||||
background: 'rgba(16, 185, 129, 0.1)',
|
||||
border: '1px solid rgba(16, 185, 129, 0.3)',
|
||||
borderRadius: '999px',
|
||||
padding: '0.15rem 0.5rem',
|
||||
textDecoration: 'none',
|
||||
whiteSpace: 'nowrap',
|
||||
flexShrink: 0,
|
||||
display: 'inline-flex',
|
||||
alignItems: 'center',
|
||||
gap: '0.25rem',
|
||||
transition: 'all 0.2s',
|
||||
}}
|
||||
title={`Open ${ticketLinks[item.id].ticket_key} in Jira`}
|
||||
>
|
||||
{ticketLinks[item.id].ticket_key} ↗
|
||||
</a>
|
||||
)}
|
||||
|
||||
{/* Workflow type badge */}
|
||||
<div style={{
|
||||
width: '80px',
|
||||
textAlign: 'center',
|
||||
flexShrink: 0,
|
||||
}}>
|
||||
<span style={{
|
||||
fontFamily: 'monospace',
|
||||
fontSize: '0.6rem',
|
||||
fontWeight: 700,
|
||||
color: wfColor.col,
|
||||
background: `rgba(${wfColor.rgb}, 0.1)`,
|
||||
border: `1px solid rgba(${wfColor.rgb}, 0.3)`,
|
||||
borderRadius: '4px',
|
||||
padding: '0.15rem 0.4rem',
|
||||
textTransform: 'uppercase',
|
||||
}}>
|
||||
{item.workflow_type}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Vendor */}
|
||||
<div style={{
|
||||
width: '120px',
|
||||
flexShrink: 0,
|
||||
fontFamily: 'monospace',
|
||||
fontSize: '0.68rem',
|
||||
color: '#94A3B8',
|
||||
overflow: 'hidden',
|
||||
textOverflow: 'ellipsis',
|
||||
whiteSpace: 'nowrap',
|
||||
}} title={item.vendor}>
|
||||
{item.vendor || '—'}
|
||||
</div>
|
||||
|
||||
{/* Hostname / IP */}
|
||||
<div style={{
|
||||
width: '120px',
|
||||
flexShrink: 0,
|
||||
minWidth: 0,
|
||||
}}>
|
||||
{item.hostname && (
|
||||
<div style={{
|
||||
fontFamily: 'monospace',
|
||||
fontSize: '0.65rem',
|
||||
color: '#94A3B8',
|
||||
overflow: 'hidden',
|
||||
textOverflow: 'ellipsis',
|
||||
whiteSpace: 'nowrap',
|
||||
}} title={item.hostname}>
|
||||
{item.hostname}
|
||||
</div>
|
||||
)}
|
||||
{item.ip_address && (
|
||||
<div style={{
|
||||
fontFamily: 'monospace',
|
||||
fontSize: '0.62rem',
|
||||
color: '#10B981',
|
||||
marginTop: item.hostname ? '1px' : 0,
|
||||
}}>
|
||||
{item.ip_address}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
@@ -815,6 +910,20 @@ export default function IvantiTodoQueuePage() {
|
||||
<Plus style={{ width: '14px', height: '14px' }} />
|
||||
Create Jira Ticket
|
||||
</button>
|
||||
{(() => {
|
||||
const selectedItems = queueItems.filter(i => selectedIds.has(i.id));
|
||||
const hasCardGranite = selectedItems.some(i => ['CARD', 'GRANITE', 'DECOM'].includes(i.workflow_type));
|
||||
return hasCardGranite ? (
|
||||
<button
|
||||
onClick={() => setShowLoaderModal(true)}
|
||||
style={STYLES.btnSuccess}
|
||||
title="Generate Granite Team_Device Loader Sheet from selected items"
|
||||
>
|
||||
<FileSpreadsheet style={{ width: '14px', height: '14px' }} />
|
||||
Generate Loader Sheet
|
||||
</button>
|
||||
) : null;
|
||||
})()}
|
||||
<button
|
||||
onClick={cancelSelection}
|
||||
style={STYLES.btnCancel}
|
||||
@@ -876,6 +985,30 @@ export default function IvantiTodoQueuePage() {
|
||||
onChange={e => setSingleJiraForm(f => ({ ...f, description: e.target.value }))}
|
||||
/>
|
||||
</div>
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0.75rem' }}>
|
||||
<div>
|
||||
<label style={{ fontSize: '0.75rem', color: '#94A3B8', display: 'block', marginBottom: '0.25rem' }}>Project Key (optional)</label>
|
||||
<input style={STYLES.input} placeholder="Uses .env default" value={singleJiraForm.project_key} onChange={e => {
|
||||
const newKey = e.target.value.toUpperCase();
|
||||
const wasVendor = isVendorProject(singleJiraForm.project_key, VENDOR_PROJECT_KEYS);
|
||||
const isNowVendor = isVendorProject(newKey, VENDOR_PROJECT_KEYS);
|
||||
setSingleJiraForm(f => ({
|
||||
...f,
|
||||
project_key: newKey,
|
||||
issue_type: (wasVendor !== isNowVendor) ? '' : f.issue_type,
|
||||
}));
|
||||
}} />
|
||||
</div>
|
||||
<div>
|
||||
<label style={{ fontSize: '0.75rem', color: '#94A3B8', display: 'block', marginBottom: '0.25rem' }}>Issue Type</label>
|
||||
<select style={{ ...STYLES.input, cursor: 'pointer' }} value={singleJiraForm.issue_type} onChange={e => setSingleJiraForm(f => ({ ...f, issue_type: e.target.value }))}>
|
||||
<option value="">Story (default)</option>
|
||||
{getIssueTypesForProject(singleJiraForm.project_key, VENDOR_PROJECT_KEYS, VENDOR_ISSUE_TYPES, STEAM_ISSUE_TYPES).map(type => (
|
||||
<option key={type} value={type}>{type}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
style={{ ...STYLES.btnSuccess, justifyContent: 'center', marginTop: '0.5rem' }}
|
||||
onClick={submitSingleJira}
|
||||
@@ -897,6 +1030,13 @@ export default function IvantiTodoQueuePage() {
|
||||
onSuccess={handleConsolidationSuccess}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Granite Loader Sheet Modal */}
|
||||
<LoaderModal
|
||||
isOpen={showLoaderModal}
|
||||
onClose={() => setShowLoaderModal(false)}
|
||||
initialDevices={showLoaderModal ? queueItems.filter(i => selectedIds.has(i.id) && ['CARD', 'GRANITE', 'DECOM'].includes(i.workflow_type)).map(i => ({ ip_address: i.ip_address || '', hostname: i.hostname || '' })) : null}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -156,6 +156,61 @@ function getStatusColor(status) {
|
||||
return '#F59E0B';
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Vendor issue type configuration
|
||||
// ---------------------------------------------------------------------------
|
||||
// Add new vendor project keys here to enable vendor-specific issue types
|
||||
const VENDOR_PROJECT_KEYS = [
|
||||
'AA_ADTRAN',
|
||||
'AA_ADVA',
|
||||
'AA_CASA',
|
||||
'AA_CISCO',
|
||||
'AACOMMSCOP',
|
||||
'AA_COMMSCOP',
|
||||
'AA_HARMONI',
|
||||
'AA_JUNIPER',
|
||||
'AA_VECIMA',
|
||||
'AA_VIAVI',
|
||||
];
|
||||
|
||||
const VENDOR_ISSUE_TYPES = [
|
||||
'Epic',
|
||||
'Story',
|
||||
'Task',
|
||||
'Defect',
|
||||
'Production Defect/Incident Fix',
|
||||
'New Feature',
|
||||
'Spike',
|
||||
'Release Candidate',
|
||||
'Documentation',
|
||||
];
|
||||
|
||||
const STEAM_ISSUE_TYPES = [
|
||||
'Story',
|
||||
'Epic',
|
||||
'Program',
|
||||
'Project',
|
||||
'Reservation',
|
||||
'Automation Maintenance',
|
||||
];
|
||||
|
||||
/**
|
||||
* Determines whether a project key belongs to a vendor project.
|
||||
*/
|
||||
function isVendorProject(projectKey, vendorKeys) {
|
||||
if (!projectKey || typeof projectKey !== 'string') return false;
|
||||
const normalized = projectKey.trim().toUpperCase();
|
||||
if (normalized.length === 0) return false;
|
||||
return vendorKeys.includes(normalized);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the appropriate issue type list for a given project key.
|
||||
*/
|
||||
function getIssueTypesForProject(projectKey, vendorKeys, vendorTypes, steamTypes) {
|
||||
return isVendorProject(projectKey, vendorKeys) ? vendorTypes : steamTypes;
|
||||
}
|
||||
|
||||
const SOURCE_CONTEXT_CONFIG = {
|
||||
cve: { label: 'CVE', color: '#0EA5E9' },
|
||||
archer: { label: 'Archer', color: '#8B5CF6' },
|
||||
@@ -890,18 +945,24 @@ export default function JiraPage() {
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0.75rem' }}>
|
||||
<div>
|
||||
<label style={{ fontSize: '0.75rem', color: '#94A3B8', display: 'block', marginBottom: '0.25rem' }}>Project Key (optional)</label>
|
||||
<input style={STYLES.input} placeholder="Uses .env default" value={createJiraForm.project_key} onChange={e => setCreateJiraForm(f => ({ ...f, project_key: e.target.value.toUpperCase() }))} />
|
||||
<input style={STYLES.input} placeholder="Uses .env default" value={createJiraForm.project_key} onChange={e => {
|
||||
const newKey = e.target.value.toUpperCase();
|
||||
const wasVendor = isVendorProject(createJiraForm.project_key, VENDOR_PROJECT_KEYS);
|
||||
const isNowVendor = isVendorProject(newKey, VENDOR_PROJECT_KEYS);
|
||||
setCreateJiraForm(f => ({
|
||||
...f,
|
||||
project_key: newKey,
|
||||
issue_type: (wasVendor !== isNowVendor) ? '' : f.issue_type,
|
||||
}));
|
||||
}} />
|
||||
</div>
|
||||
<div>
|
||||
<label style={{ fontSize: '0.75rem', color: '#94A3B8', display: 'block', marginBottom: '0.25rem' }}>Issue Type</label>
|
||||
<select style={{ ...STYLES.input, cursor: 'pointer' }} value={createJiraForm.issue_type} onChange={e => setCreateJiraForm(f => ({ ...f, issue_type: e.target.value }))}>
|
||||
<option value="">Story (default)</option>
|
||||
<option value="Story">Story</option>
|
||||
<option value="Epic">Epic</option>
|
||||
<option value="Program">Program</option>
|
||||
<option value="Project">Project</option>
|
||||
<option value="Reservation">Reservation</option>
|
||||
<option value="Automation Maintenance">Automation Maintenance</option>
|
||||
{getIssueTypesForProject(createJiraForm.project_key, VENDOR_PROJECT_KEYS, VENDOR_ISSUE_TYPES, STEAM_ISSUE_TYPES).map(type => (
|
||||
<option key={type} value={type}>{type}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
@@ -915,4 +976,8 @@ export default function JiraPage() {
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Named exports for reuse by other pages (e.g., IvantiTodoQueuePage)
|
||||
export { VENDOR_PROJECT_KEYS, VENDOR_ISSUE_TYPES, STEAM_ISSUE_TYPES, isVendorProject, getIssueTypesForProject };
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React, { useState, useEffect, useCallback, useRef, useMemo } from 'react';
|
||||
import ReactDOM from 'react-dom';
|
||||
import { RefreshCw, Loader, AlertCircle, PieChart, ChevronUp, ChevronDown, ChevronsUpDown, Settings2, GripVertical, Eye, EyeOff, Filter, Download, RotateCcw, Trash2, X, ListTodo, Upload, FileText, Check, AlertTriangle, CornerUpRight, Edit3, Square, CheckSquare, MinusSquare, Search, Database, Plus } from 'lucide-react';
|
||||
import { RefreshCw, Loader, AlertCircle, PieChart, ChevronUp, ChevronDown, ChevronRight, ChevronsUpDown, Settings2, GripVertical, Eye, EyeOff, Filter, Download, RotateCcw, Trash2, X, ListTodo, Upload, FileText, Check, AlertTriangle, CornerUpRight, Edit3, Square, CheckSquare, MinusSquare, Search, Database, Plus, FileSpreadsheet } from 'lucide-react';
|
||||
import * as XLSX from 'xlsx';
|
||||
import { useAuth } from '../../contexts/AuthContext';
|
||||
import IvantiCountsChart from './IvantiCountsChart';
|
||||
@@ -8,6 +8,8 @@ import AnomalyBanner from './AnomalyBanner';
|
||||
import CveTooltip from '../CveTooltip';
|
||||
import RedirectModal from '../RedirectModal';
|
||||
import AtlasBadge from '../AtlasBadge';
|
||||
import LoaderModal from '../LoaderModal';
|
||||
import CardActionModal from '../CardActionModal';
|
||||
import ConsolidationModal from '../ConsolidationModal';
|
||||
import AtlasSlideOutPanel from '../AtlasSlideOutPanel';
|
||||
import AtlasIcon from '../AtlasIcon';
|
||||
@@ -1537,6 +1539,13 @@ function QueuePanel({ open, items, onClose, onUpdate, onDelete, onDeleteMany, on
|
||||
const [cardActionLoading, setCardActionLoading] = useState(false);
|
||||
const [cardActionError, setCardActionError] = useState(null);
|
||||
|
||||
// Granite Loader Sheet modal state
|
||||
const [showLoaderModal, setShowLoaderModal] = useState(false);
|
||||
|
||||
// CARD Action Modal state
|
||||
const [cardModalItem, setCardModalItem] = useState(null);
|
||||
const [cardModalAction, setCardModalAction] = useState('confirm');
|
||||
|
||||
// Create Jira modal state
|
||||
const [createJiraOpen, setCreateJiraOpen] = useState(false);
|
||||
const [createJiraForm, setCreateJiraForm] = useState({ summary: '', cve_id: '', vendor: '', source_context: 'ivanti_queue', description: '', project_key: '', issue_type: '' });
|
||||
@@ -1584,6 +1593,12 @@ function QueuePanel({ open, items, onClose, onUpdate, onDelete, onDeleteMany, on
|
||||
const [submissionsCollapsed, setSubmissionsCollapsed] = useState(() => localStorage.getItem('steam_submissions_collapsed') === 'true');
|
||||
const [dismissError, setDismissError] = useState(null);
|
||||
|
||||
// Collapsible section state for queue groups
|
||||
const [collapsedSections, setCollapsedSections] = useState({});
|
||||
const toggleSectionCollapse = (sectionKey) => {
|
||||
setCollapsedSections((prev) => ({ ...prev, [sectionKey]: !prev[sectionKey] }));
|
||||
};
|
||||
|
||||
const toggleSubmissionsCollapsed = () => {
|
||||
setSubmissionsCollapsed(prev => {
|
||||
const next = !prev;
|
||||
@@ -1618,14 +1633,13 @@ function QueuePanel({ open, items, onClose, onUpdate, onDelete, onDeleteMany, on
|
||||
setTimeout(() => setRedirectSuccess(null), 3000);
|
||||
};
|
||||
|
||||
// CARD action handlers
|
||||
// CARD action handlers — open the CardActionModal instead of inline form
|
||||
const openCardAction = (itemId, type) => {
|
||||
setCardAction({ itemId, type });
|
||||
setCardFormTeam('');
|
||||
setCardFormComment('');
|
||||
setCardFormFromTeam('');
|
||||
setCardFormToTeam('');
|
||||
setCardActionError(null);
|
||||
const targetItem = items.find(i => i.id === itemId);
|
||||
if (targetItem) {
|
||||
setCardModalItem(targetItem);
|
||||
setCardModalAction(type);
|
||||
}
|
||||
};
|
||||
|
||||
const closeCardAction = () => {
|
||||
@@ -1640,6 +1654,10 @@ function QueuePanel({ open, items, onClose, onUpdate, onDelete, onDeleteMany, on
|
||||
|
||||
const handleCardConfirmDecline = async (item, actionType) => {
|
||||
if (!cardFormTeam) return;
|
||||
if (!item.ip_address) {
|
||||
setCardActionError('No IP address on this queue item — cannot resolve CARD asset.');
|
||||
return;
|
||||
}
|
||||
setCardActionLoading(true);
|
||||
setCardActionError(null);
|
||||
try {
|
||||
@@ -1655,7 +1673,8 @@ function QueuePanel({ open, items, onClose, onUpdate, onDelete, onDeleteMany, on
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
setCardActionError(data.error || `${actionType} failed.`);
|
||||
const errorMsg = data.error || data.message || (typeof data === 'string' ? data : `${actionType} failed.`);
|
||||
setCardActionError(errorMsg);
|
||||
setCardActionLoading(false);
|
||||
return;
|
||||
}
|
||||
@@ -1670,6 +1689,10 @@ function QueuePanel({ open, items, onClose, onUpdate, onDelete, onDeleteMany, on
|
||||
|
||||
const handleCardRedirect = async (item) => {
|
||||
if (!cardFormFromTeam || !cardFormToTeam) return;
|
||||
if (!item.ip_address) {
|
||||
setCardActionError('No IP address on this queue item — cannot resolve CARD asset.');
|
||||
return;
|
||||
}
|
||||
setCardActionLoading(true);
|
||||
setCardActionError(null);
|
||||
try {
|
||||
@@ -1685,7 +1708,8 @@ function QueuePanel({ open, items, onClose, onUpdate, onDelete, onDeleteMany, on
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
setCardActionError(data.error || 'Redirect failed.');
|
||||
const errorMsg = data.error || data.message || (typeof data === 'string' ? data : JSON.stringify(data));
|
||||
setCardActionError(errorMsg);
|
||||
setCardActionLoading(false);
|
||||
return;
|
||||
}
|
||||
@@ -2353,13 +2377,26 @@ function QueuePanel({ open, items, onClose, onUpdate, onDelete, onDeleteMany, on
|
||||
</div>
|
||||
) : grouped.map(({ key, label, items: groupItems, isInventory, cardItems, graniteItems, decomItems }) => (
|
||||
<div key={key} style={{ marginBottom: '1.25rem' }}>
|
||||
{/* Group header */}
|
||||
<div style={{
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
|
||||
padding: '0.3rem 0', marginBottom: '0.375rem',
|
||||
borderBottom: `1px solid ${isInventory ? 'rgba(16,185,129,0.2)' : 'rgba(255,255,255,0.06)'}`,
|
||||
}}>
|
||||
<span style={{ fontFamily: 'monospace', fontSize: '0.68rem', fontWeight: '700', color: isInventory ? '#10B981' : '#94A3B8', textTransform: 'uppercase', letterSpacing: '0.1em' }}>
|
||||
{/* Group header — clickable to collapse/expand */}
|
||||
<div
|
||||
onClick={() => toggleSectionCollapse(key)}
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', gap: '0.375rem',
|
||||
padding: '0.3rem 0', marginBottom: '0.375rem',
|
||||
borderBottom: `1px solid ${isInventory ? 'rgba(16,185,129,0.2)' : 'rgba(255,255,255,0.06)'}`,
|
||||
cursor: 'pointer', userSelect: 'none',
|
||||
}}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); toggleSectionCollapse(key); } }}
|
||||
aria-expanded={!collapsedSections[key]}
|
||||
aria-label={`${label} section, ${groupItems.length} items`}
|
||||
>
|
||||
{collapsedSections[key]
|
||||
? <ChevronRight style={{ width: '12px', height: '12px', color: isInventory ? '#10B981' : '#64748B' }} />
|
||||
: <ChevronDown style={{ width: '12px', height: '12px', color: isInventory ? '#10B981' : '#64748B' }} />
|
||||
}
|
||||
<span style={{ fontFamily: 'monospace', fontSize: '0.68rem', fontWeight: '700', color: isInventory ? '#10B981' : '#94A3B8', textTransform: 'uppercase', letterSpacing: '0.1em', flex: 1 }}>
|
||||
{label}
|
||||
</span>
|
||||
<span style={{ fontFamily: 'monospace', fontSize: '0.62rem', color: '#334155' }}>
|
||||
@@ -2367,8 +2404,8 @@ function QueuePanel({ open, items, onClose, onUpdate, onDelete, onDeleteMany, on
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Items — Inventory section renders CARD then GRANITE then DECOM with optional sub-dividers */}
|
||||
{isInventory ? (
|
||||
{/* Items — only rendered when section is expanded */}
|
||||
{!collapsedSections[key] && (isInventory ? (
|
||||
<>
|
||||
{cardItems.map((item) => (
|
||||
<React.Fragment key={item.id}>
|
||||
@@ -2395,7 +2432,7 @@ function QueuePanel({ open, items, onClose, onUpdate, onDelete, onDeleteMany, on
|
||||
</>
|
||||
) : (
|
||||
groupItems.map((item) => renderQueueItem(item, { done: item.status === 'complete', selectedIds, toggleSelect, onUpdate, onDelete, setRedirectItem, canWrite }))
|
||||
)}
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
@@ -2792,6 +2829,33 @@ function QueuePanel({ open, items, onClose, onUpdate, onDelete, onDeleteMany, on
|
||||
+ Jira ({items.filter(i => selectedIds.has(i.id) && i.status === 'pending').length})
|
||||
</button>
|
||||
)}
|
||||
{/* Generate Loader Sheet — visible when CARD/GRANITE/DECOM items are selected or as standalone */}
|
||||
{(() => {
|
||||
const selectedCardGranite = items.filter(i => selectedIds.has(i.id) && ['CARD', 'GRANITE', 'DECOM'].includes(i.workflow_type));
|
||||
const hasCardGraniteItems = items.some(i => ['CARD', 'GRANITE', 'DECOM'].includes(i.workflow_type));
|
||||
const isEnabled = selectedCardGranite.length > 0 || hasCardGraniteItems;
|
||||
return isEnabled ? (
|
||||
<button
|
||||
onClick={() => setShowLoaderModal(true)}
|
||||
style={{
|
||||
flex: 1, padding: '0.45rem',
|
||||
background: 'rgba(124,58,237,0.1)',
|
||||
border: '1px solid rgba(124,58,237,0.35)',
|
||||
borderRadius: '0.375rem',
|
||||
color: '#A78BFA',
|
||||
fontFamily: 'monospace', fontSize: '0.72rem', fontWeight: '600',
|
||||
cursor: 'pointer',
|
||||
textTransform: 'uppercase', letterSpacing: '0.05em',
|
||||
transition: 'all 0.12s',
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '0.3rem',
|
||||
}}
|
||||
title="Generate Granite Team_Device Loader Sheet"
|
||||
>
|
||||
<FileSpreadsheet style={{ width: '12px', height: '12px' }} />
|
||||
Loader
|
||||
</button>
|
||||
) : null;
|
||||
})()}
|
||||
{selectedIds.size > 0 && (
|
||||
<button
|
||||
onClick={handleDeleteSelected}
|
||||
@@ -3097,6 +3161,31 @@ function QueuePanel({ open, items, onClose, onUpdate, onDelete, onDeleteMany, on
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Granite Loader Sheet Modal */}
|
||||
<LoaderModal
|
||||
isOpen={showLoaderModal}
|
||||
onClose={() => setShowLoaderModal(false)}
|
||||
initialDevices={showLoaderModal ? (() => {
|
||||
const selected = items.filter(i => selectedIds.has(i.id) && ['CARD', 'GRANITE', 'DECOM'].includes(i.workflow_type));
|
||||
if (selected.length > 0) return selected.map(i => ({ ip_address: i.ip_address || '', hostname: i.hostname || '' }));
|
||||
// Standalone: use all CARD/GRANITE/DECOM items
|
||||
return items.filter(i => ['CARD', 'GRANITE', 'DECOM'].includes(i.workflow_type)).map(i => ({ ip_address: i.ip_address || '', hostname: i.hostname || '' }));
|
||||
})() : null}
|
||||
/>
|
||||
|
||||
{/* CARD Action Modal */}
|
||||
<CardActionModal
|
||||
isOpen={!!cardModalItem}
|
||||
onClose={() => setCardModalItem(null)}
|
||||
item={cardModalItem}
|
||||
initialAction={cardModalAction}
|
||||
cardTeams={cardTeams}
|
||||
onSuccess={(itemId, _action) => {
|
||||
onUpdate(itemId, { status: 'complete' });
|
||||
setCardModalItem(null);
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
77
frontend/src/utils/graniteLoaderConfig.js
Normal file
77
frontend/src/utils/graniteLoaderConfig.js
Normal file
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* Granite Team_Device Loader column configuration.
|
||||
* Defines all 41 columns in canonical order, their groupings,
|
||||
* and which are required for each operation type.
|
||||
*/
|
||||
|
||||
export const LOADER_COLUMNS = [
|
||||
{ id: 'DELETE', label: 'DELETE', group: 'Identification', requiredFor: ['Delete'] },
|
||||
{ id: 'SET_CONFIRMED', label: 'SET_CONFIRMED', group: 'Identification', requiredFor: [] },
|
||||
{ id: 'EQUIPMENT_CLASS', label: 'EQUIPMENT CLASS', group: 'Identification', requiredFor: ['Add'] },
|
||||
{ id: 'EQUIP_INST_ID', label: 'EQUIP_INST_ID', group: 'Identification', requiredFor: ['Change', 'Move', 'Delete'] },
|
||||
{ id: 'SITE_NAME', label: 'SITE_NAME', group: 'Identification', requiredFor: ['Add', 'Move'] },
|
||||
{ id: 'EQUIP_NAME', label: 'EQUIP_NAME', group: 'Identification', requiredFor: ['Add'] },
|
||||
{ id: 'EQUIP_TEMPLATE', label: 'EQUIP_TEMPLATE', group: 'Identification', requiredFor: ['Add'] },
|
||||
{ id: 'EQUIP_STATUS', label: 'EQUIP_STATUS', group: 'Identification', requiredFor: ['Add'] },
|
||||
{ id: 'RESPONSIBLE_TEAM', label: 'UDA#RESPONSIBLE ORGANIZATION#RESPONSIBLE TEAM', group: 'Responsible Org', requiredFor: ['Add'] },
|
||||
{ id: 'IPV4_ADDRESS', label: 'UDA#IP_ADDRESSING#IPV4_ADDRESS', group: 'IP Addressing', requiredFor: ['Add'] },
|
||||
{ id: 'MAC_ADDRESS', label: 'UDA#IP_ADDRESSING#MAC ADDRESS', group: 'IP Addressing', requiredFor: [] },
|
||||
{ id: 'MGMT_IP_ASN', label: 'UDA#IP_ADDRESSING#MGMT_IP_ASN', group: 'IP Addressing', requiredFor: ['Add'] },
|
||||
{ id: 'SERIALNUMBER', label: 'SERIALNUMBER', group: 'Equipment Info', requiredFor: [] },
|
||||
{ id: 'EXCLUDED_DISCOVERY', label: 'UDA#AUTO DISCOVERY#EXCLUDED FROM DISCOVERY', group: 'Discovery', requiredFor: [] },
|
||||
{ id: 'EXCLUDED_REASON', label: 'UDA#AUTO DISCOVERY#EXCLUDED FROM DISCOVERY REASON', group: 'Discovery', requiredFor: [] },
|
||||
{ id: 'IPV6_ADDRESS', label: 'UDA#IP_ADDRESSING#IPV6_ADDRESS', group: 'IP Addressing', requiredFor: [] },
|
||||
{ id: 'ILOM_ADDRESS', label: 'UDA#IP_ADDRESSING#IPV4_ILOM_ADDRESS', group: 'IP Addressing', requiredFor: [] },
|
||||
{ id: 'APP_ID_ASSET_TAG', label: 'UDA#CHERWELL_CMDB#APP ID ASSET TAG', group: 'Cyber Metrics', requiredFor: [] },
|
||||
{ id: 'DEVICE_FUNCTION', label: 'UDA#CHERWELL_CMDB#DEVICE_FUNCTION', group: 'Cyber Metrics', requiredFor: [] },
|
||||
{ id: 'ENVIRONMENT', label: 'UDA#CHERWELL_CMDB#ENVIRONMENT', group: 'Cyber Metrics', requiredFor: [] },
|
||||
{ id: 'SECONDARY_MGMT_IP', label: 'UDA#IP_ADDRESSING#SECONDARY_MGMT_IP_ADDRESS', group: 'IP Addressing', requiredFor: [] },
|
||||
{ id: 'VIP', label: 'UDA#IP_ADDRESSING#VIP', group: 'IP Addressing', requiredFor: [] },
|
||||
{ id: 'FLOATING_IP', label: 'UDA#IP_ADDRESSING#FLOATING IP ADDRESS', group: 'IP Addressing', requiredFor: [] },
|
||||
{ id: 'SCAN_IP_1', label: 'UDA#IP_ADDRESSING#SCAN IP ADDRESS 1', group: 'IP Addressing', requiredFor: [] },
|
||||
{ id: 'SCAN_IP_2', label: 'UDA#IP_ADDRESSING#SCAN IP ADDRESS 2', group: 'IP Addressing', requiredFor: [] },
|
||||
{ id: 'SCAN_IP_3', label: 'UDA#IP_ADDRESSING#SCAN IP ADDRESS 3', group: 'IP Addressing', requiredFor: [] },
|
||||
{ id: 'EQUIP_MODEL', label: 'EQUIP_MODEL', group: 'Equipment Info', requiredFor: [] },
|
||||
{ id: 'EQUIP_COMMENTS', label: 'EQUIP_COMMENTS', group: 'Equipment Info', requiredFor: [] },
|
||||
{ id: 'EQUIP_PARTNUMBER', label: 'EQUIP_PARTNUMBER', group: 'Equipment Info', requiredFor: [] },
|
||||
{ id: 'OS', label: 'UDA#CONTROLLER CONFIG#OS', group: 'Equipment Info', requiredFor: [] },
|
||||
{ id: 'OS_VERSION', label: 'UDA#CONTROLLER CONFIG#OS VERSION', group: 'Equipment Info', requiredFor: [] },
|
||||
{ id: 'CPU_CORES', label: 'UDA#CONTROLLER CONFIG#TOTAL CPU CORES', group: 'Equipment Info', requiredFor: [] },
|
||||
{ id: 'RAM_GB', label: 'UDA#CONTROLLER CONFIG#RAM IN GB', group: 'Equipment Info', requiredFor: [] },
|
||||
{ id: 'STORAGE_GB', label: 'UDA#CONTROLLER CONFIG#STORAGE IN GB', group: 'Equipment Info', requiredFor: [] },
|
||||
{ id: 'ARCHER_ID', label: 'UDA#WIFI EQUIP INFO#ARCHER ID', group: 'Other', requiredFor: [] },
|
||||
{ id: 'INSTALL_LOCATION', label: 'UDA#WIFI EQUIP INFO#INSTALL LOCATION', group: 'Other', requiredFor: [] },
|
||||
{ id: 'SYSNAME', label: 'UDA#EQUIPMENT_INFO#SYSNAME', group: 'Other', requiredFor: [] },
|
||||
{ id: 'LATITUDE', label: 'UDA#WIFI EQUIP INFO#LATITUDE', group: 'Other', requiredFor: [] },
|
||||
{ id: 'LONGITUDE', label: 'UDA#WIFI EQUIP INFO#LONGITUDE', group: 'Other', requiredFor: [] },
|
||||
{ id: 'OSTYPE', label: 'UDA#EQUIP MIGRATION#OSTYPE', group: 'Other', requiredFor: [] },
|
||||
{ id: 'OSVERSION', label: 'UDA#EQUIP MIGRATION#OSVERSION', group: 'Other', requiredFor: [] },
|
||||
];
|
||||
|
||||
export const COLUMN_GROUPS = [
|
||||
'Identification',
|
||||
'Responsible Org',
|
||||
'IP Addressing',
|
||||
'Discovery',
|
||||
'Cyber Metrics',
|
||||
'Equipment Info',
|
||||
'Other',
|
||||
];
|
||||
|
||||
export const OPERATION_TYPES = ['Change', 'Add', 'Delete', 'Move'];
|
||||
|
||||
/**
|
||||
* Returns column IDs required for the given operation type.
|
||||
*/
|
||||
export function getRequiredColumns(operationType) {
|
||||
return LOADER_COLUMNS
|
||||
.filter(col => col.requiredFor.includes(operationType))
|
||||
.map(col => col.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns columns belonging to a specific group.
|
||||
*/
|
||||
export function getColumnsByGroup(group) {
|
||||
return LOADER_COLUMNS.filter(col => col.group === group);
|
||||
}
|
||||
82
frontend/src/utils/graniteLoaderExport.js
Normal file
82
frontend/src/utils/graniteLoaderExport.js
Normal file
@@ -0,0 +1,82 @@
|
||||
/**
|
||||
* Granite Team_Device Loader xlsx generation.
|
||||
* Produces a properly formatted xlsx file for upload to SNIP XperLoad.
|
||||
*/
|
||||
|
||||
import * as XLSX from 'xlsx';
|
||||
import { LOADER_COLUMNS } from './graniteLoaderConfig';
|
||||
|
||||
/**
|
||||
* Generate a Granite Loader Sheet xlsx file.
|
||||
*
|
||||
* @param {Object} config
|
||||
* @param {string} config.operationType - 'Change' | 'Add' | 'Delete' | 'Move'
|
||||
* @param {Array<string>} config.columnIds - selected column IDs (in any order; output uses canonical order)
|
||||
* @param {Array<Object>} config.rows - device rows, each keyed by column ID with string values
|
||||
* @returns {Blob} xlsx file as a Blob for browser download
|
||||
*/
|
||||
export function generateLoaderXlsx(config) {
|
||||
const { operationType, columnIds, rows } = config;
|
||||
|
||||
// Filter LOADER_COLUMNS to only selected columns, preserving canonical order
|
||||
const selectedColumns = LOADER_COLUMNS.filter(col => columnIds.includes(col.id));
|
||||
|
||||
// Build header row from canonical labels
|
||||
const headers = selectedColumns.map(col => col.label);
|
||||
|
||||
// Build data rows
|
||||
const dataRows = rows.map(row => {
|
||||
return selectedColumns.map(col => {
|
||||
// DELETE column auto-fill for Delete operations
|
||||
if (col.id === 'DELETE' && operationType === 'Delete') {
|
||||
return 'X';
|
||||
}
|
||||
|
||||
// Get the value from the row
|
||||
let value = row[col.id];
|
||||
|
||||
// EQUIPMENT CLASS defaults to "S" if not explicitly set
|
||||
if (col.id === 'EQUIPMENT_CLASS' && (value === undefined || value === null || value === '')) {
|
||||
value = 'S';
|
||||
}
|
||||
|
||||
// Convert null/undefined to empty string (not "null" or "undefined")
|
||||
if (value === null || value === undefined) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return String(value);
|
||||
});
|
||||
});
|
||||
|
||||
// Combine headers + data into array-of-arrays
|
||||
const aoa = [headers, ...dataRows];
|
||||
|
||||
// Create workbook and worksheet
|
||||
const ws = XLSX.utils.aoa_to_sheet(aoa);
|
||||
const wb = XLSX.utils.book_new();
|
||||
XLSX.utils.book_append_sheet(wb, ws, 'Load_Sheet');
|
||||
|
||||
// Write to array buffer
|
||||
const wbOut = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
|
||||
|
||||
// Return as Blob
|
||||
return new Blob([wbOut], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a descriptive filename for the loader sheet.
|
||||
*
|
||||
* @param {string} operationType - 'Change' | 'Add' | 'Delete' | 'Move'
|
||||
* @param {string} [teamName] - optional team name to include in filename
|
||||
* @returns {string} filename like "Loader_Change_NTS-AEO-STEAM_2026-05-27.xlsx"
|
||||
*/
|
||||
export function generateFilename(operationType, teamName) {
|
||||
const date = new Date().toISOString().slice(0, 10);
|
||||
const parts = ['Loader', operationType];
|
||||
if (teamName) {
|
||||
parts.push(teamName.replace(/[^a-zA-Z0-9_-]/g, '-'));
|
||||
}
|
||||
parts.push(date);
|
||||
return parts.join('_') + '.xlsx';
|
||||
}
|
||||
63
frontend/src/utils/queueGrouping.js
Normal file
63
frontend/src/utils/queueGrouping.js
Normal file
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* Queue grouping utility — extracts the hybrid Inventory + vendor grouping logic
|
||||
* from IvantiTodoQueuePage into a testable pure function.
|
||||
*
|
||||
* Spec: .kiro/specs/queue-collapsible-sections
|
||||
* Requirements: 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7
|
||||
*/
|
||||
|
||||
const INVENTORY_TYPES = new Set(['CARD', 'GRANITE', 'DECOM']);
|
||||
|
||||
/**
|
||||
* Groups visible queue items into the hybrid section layout.
|
||||
*
|
||||
* @param {Array} visibleItems - Queue items with status 'pending'
|
||||
* @returns {Array<{key: string, label: string, type: string, items: Array}>}
|
||||
*
|
||||
* Rules:
|
||||
* - Items with workflow_type CARD, GRANITE, or DECOM → Inventory section
|
||||
* - Items with workflow_type FP or Archer → grouped by vendor field
|
||||
* - Items with null/undefined/empty vendor → placed in "Unknown" vendor section
|
||||
* - Inventory section appears first (if non-empty)
|
||||
* - Vendor sections sorted alphabetically by label
|
||||
* - Sections with zero items are omitted from output
|
||||
*/
|
||||
export function groupQueueItems(visibleItems) {
|
||||
const inventoryItems = [];
|
||||
const vendorMap = new Map();
|
||||
|
||||
for (const item of visibleItems) {
|
||||
if (INVENTORY_TYPES.has(item.workflow_type)) {
|
||||
inventoryItems.push(item);
|
||||
} else {
|
||||
const vendor = item.vendor?.trim() || 'Unknown';
|
||||
if (!vendorMap.has(vendor)) vendorMap.set(vendor, []);
|
||||
vendorMap.get(vendor).push(item);
|
||||
}
|
||||
}
|
||||
|
||||
const sections = [];
|
||||
|
||||
if (inventoryItems.length > 0) {
|
||||
sections.push({
|
||||
key: 'inventory',
|
||||
label: 'Inventory',
|
||||
type: 'inventory',
|
||||
items: inventoryItems,
|
||||
});
|
||||
}
|
||||
|
||||
const sortedVendors = [...vendorMap.entries()]
|
||||
.sort((a, b) => a[0].localeCompare(b[0]));
|
||||
|
||||
for (const [vendor, items] of sortedVendors) {
|
||||
sections.push({
|
||||
key: `vendor:${vendor}`,
|
||||
label: vendor,
|
||||
type: 'vendor',
|
||||
items,
|
||||
});
|
||||
}
|
||||
|
||||
return sections;
|
||||
}
|
||||
Reference in New Issue
Block a user