From 58587d19a83cbddc36f9371f248139d3b368cfd7 Mon Sep 17 00:00:00 2001 From: s871077 Date: Fri, 11 Sep 2026 10:11:09 +0800 Subject: [PATCH 01/12] update --- .claude/settings.local.json | 5 +- .dockerignore | 38 +++ .github/workflows/cicd.yaml | 237 ++++++++++++++ Dockerfile | 86 +++++ Dockerfile.db | 16 + helm/Chart.yaml | 6 + helm/templates/_helpers.tpl | 56 ++++ helm/templates/db-secret.yaml | 13 + helm/templates/db-service.yaml | 40 +++ helm/templates/db-statefulset.yaml | 97 ++++++ helm/templates/server-deployment.yaml | 90 ++++++ helm/templates/server-ingress.yaml | 24 ++ helm/templates/server-secret.yaml | 28 ++ helm/templates/server-service.yaml | 15 + helm/values-dev.yaml | 34 ++ helm/values-prod.yaml | 34 ++ helm/values.yaml | 67 ++++ next.config.mjs | 6 +- prisma/generate-seed-sql.mjs | 149 +++++++++ prisma/prod/01-schema.sql | 75 +++++ prisma/seed.sql | 449 ++++++++++++++++++++++++++ src/app/layout.tsx | 34 +- src/app/login/page.tsx | 14 +- src/components/TopNav.tsx | 60 ++-- src/middleware.ts | 24 +- 25 files changed, 1643 insertions(+), 54 deletions(-) create mode 100644 .dockerignore create mode 100644 .github/workflows/cicd.yaml create mode 100644 Dockerfile create mode 100644 Dockerfile.db create mode 100644 helm/Chart.yaml create mode 100644 helm/templates/_helpers.tpl create mode 100644 helm/templates/db-secret.yaml create mode 100644 helm/templates/db-service.yaml create mode 100644 helm/templates/db-statefulset.yaml create mode 100644 helm/templates/server-deployment.yaml create mode 100644 helm/templates/server-ingress.yaml create mode 100644 helm/templates/server-secret.yaml create mode 100644 helm/templates/server-service.yaml create mode 100644 helm/values-dev.yaml create mode 100644 helm/values-prod.yaml create mode 100644 helm/values.yaml create mode 100644 prisma/generate-seed-sql.mjs create mode 100644 prisma/prod/01-schema.sql create mode 100644 prisma/seed.sql diff --git a/.claude/settings.local.json b/.claude/settings.local.json index c850e42..8edf04b 100644 --- a/.claude/settings.local.json +++ b/.claude/settings.local.json @@ -28,7 +28,10 @@ "Bash(git fetch:*)", "Bash(command:*)", "Bash(timeout:*)", - "Bash(git:*)" + "Bash(git:*)", + "Bash(/tmp/windows-amd64/helm.exe template:*)", + "Bash(echo \"exit=$?\")", + "Read(//tmp/**)" ] } } diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..387291a --- /dev/null +++ b/.dockerignore @@ -0,0 +1,38 @@ +# Version control +.git +.gitignore +.github + +# Dependencies / build output (rebuilt inside the image) +node_modules +.next +out +build + +# Deployment tooling — not needed in the build context +helm +DEPLOY.md +README.md + +# Local databases +prisma/dev.db +prisma/dev.db-journal +prisma/*.db + +# Secrets: .env holds file:./dev.db, and .env.local / .env.production hold REAL +# Entra secrets and the RDS password. Baking these into a layer would push them +# to JFrog. All runtime env comes from the k8s Secret instead. +.env +.env.* +!.env.production.example + +# Editor / tooling noise +.claude +.vscode +.idea +.DS_Store +*.tsbuildinfo +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* diff --git a/.github/workflows/cicd.yaml b/.github/workflows/cicd.yaml new file mode 100644 index 0000000..93d56ef --- /dev/null +++ b/.github/workflows/cicd.yaml @@ -0,0 +1,237 @@ +name: CI/CD (dev on branch, prod on tag) + +on: + push: + branches: + - dev # build & deploy for dev only + tags: + - "*" # build & deploy for prod only when a tag is pushed + +jobs: + setup: + runs-on: ubuntu-latest + outputs: + matrix: ${{ steps.pick.outputs.matrix }} + steps: + - name: Pick matrix config from ref type + id: pick + shell: bash + run: | + if [[ "${{ github.ref_type }}" == "tag" ]]; then + echo 'matrix={"include":[{"env":"prod","image_name_server":"it-cost-dashboard-server-prod","image_name_db":"it-cost-dashboard-db-prod","latest_tag":"latest-prod","release":"it-cost-dashboard-prod","namespace":"it-cost-dashboard-prod","chart":"./helm","values_file":"./helm/values-prod.yaml"}]}' >> "$GITHUB_OUTPUT" + else + echo 'matrix={"include":[{"env":"dev","image_name_server":"it-cost-dashboard-server-dev","image_name_db":"it-cost-dashboard-db-dev","latest_tag":"latest-dev","release":"it-cost-dashboard-dev","namespace":"it-cost-dashboard-dev","chart":"./helm","values_file":"./helm/values-dev.yaml"}]}' >> "$GITHUB_OUTPUT" + fi + + build-and-deploy: + needs: setup + runs-on: ubuntu-latest + + strategy: + matrix: ${{ fromJSON(needs.setup.outputs.matrix) }} + + # Per-environment group: a dev push must never cancel an in-flight prod + # deploy (the original used a hardcoded "prod" group for both refs). + concurrency: + group: deploy-${{ matrix.env }} + cancel-in-progress: true + + env: + # host/repo, e.g. jfrog.trendmicro.com/ameait-it-cost-dashboard + JFROG_REGISTRY: ${{ secrets.JFROG_REGISTRY }} + DOCKER_BUILDKIT: "1" + COMPOSE_DOCKER_CLI_BUILD: "1" + + steps: + - name: Checkout (with tags) + uses: actions/checkout@v4 + with: + fetch-depth: 0 # IMPORTANT to access tags + + - name: Verify tag is on prod branch (main) + id: guard + if: github.ref_type == 'tag' + shell: bash + run: | + git fetch origin main --quiet + if git merge-base --is-ancestor "${{ github.sha }}" origin/main; then + echo "Tag commit is on main. Proceeding with prod deploy." + else + echo "::error::Tag ${GITHUB_REF#refs/tags/} points at a commit not on main. Refusing prod deploy." + exit 1 + fi + + - name: Set up kubeconfig + run: | + echo "KUBECONFIG=${RUNNER_TEMP}/kubeconfig" >> "$GITHUB_ENV" + echo "${{ secrets.KUBE_CONFIG_DATA }}" | base64 -d > "${RUNNER_TEMP}/kubeconfig" + chmod 600 "${RUNNER_TEMP}/kubeconfig" + + - name: Login to JFrog + run: | + # JFROG_REGISTRY is host/repo but `docker login` takes only the host. + JFROG_HOST=$(echo "${JFROG_REGISTRY}" | cut -d'/' -f1) + echo "Logging in to ${JFROG_HOST}" + echo "${{ secrets.JFROG_IDENTITY_TOKEN }}" | docker login "${JFROG_HOST}" \ + -u "${{ secrets.JFROG_USERNAME }}" \ + --password-stdin + + - name: Determine ref type and release tag + id: refinfo + shell: bash + run: | + echo "GITHUB_REF=${GITHUB_REF}" + echo "GITHUB_REF_TYPE=${GITHUB_REF_TYPE:-${{ github.ref_type }}}" + if [[ "${{ github.ref_type }}" == "tag" ]]; then + echo "ref_type=tag" >> $GITHUB_OUTPUT + echo "release_tag=${GITHUB_REF#refs/tags/}" >> $GITHUB_OUTPUT + elif [[ "${{ github.ref_type }}" == "branch" ]]; then + echo "ref_type=branch" >> $GITHUB_OUTPUT + echo "release_tag=" >> $GITHUB_OUTPUT + else + echo "ref_type=unknown" >> $GITHUB_OUTPUT + echo "release_tag=" >> $GITHUB_OUTPUT + fi + + - name: Pre-build diagnostics + run: | + echo "Ref: ${GITHUB_REF}" + echo "Ref type: ${{ steps.refinfo.outputs.ref_type }}" + echo "Release tag: ${{ steps.refinfo.outputs.release_tag }}" + echo "Environment: ${{ matrix.env }}" + echo "Server image: ${JFROG_REGISTRY}/${{ matrix.image_name_server }}" + echo "DB image: ${JFROG_REGISTRY}/${{ matrix.image_name_db }}" + docker version + helm version + kubectl version --client + + - name: Build & Push server image + run: | + REF_TYPE="${{ steps.refinfo.outputs.ref_type }}" + RELEASE_TAG="${{ steps.refinfo.outputs.release_tag }}" + IMAGE="${JFROG_REGISTRY}/${{ matrix.image_name_server }}" + + BUILD_TAG_ARGS=( + -t "${IMAGE}:${{ matrix.latest_tag }}" + -t "${IMAGE}:${{ github.sha }}" + ) + if [[ "${REF_TYPE}" == "tag" && -n "${RELEASE_TAG}" ]]; then + BUILD_TAG_ARGS+=( -t "${IMAGE}:${RELEASE_TAG}" ) + fi + + # AUTH_SECRET is build-time only (Auth.js v5 initializes NextAuth() at + # module load during `next build`). The real secret comes from k8s. + docker build \ + -f Dockerfile \ + --build-arg AUTH_SECRET=build-placeholder-not-used-at-runtime \ + "${BUILD_TAG_ARGS[@]}" \ + . + + docker push "${IMAGE}:${{ matrix.latest_tag }}" + docker push "${IMAGE}:${{ github.sha }}" + if [[ "${REF_TYPE}" == "tag" && -n "${RELEASE_TAG}" ]]; then + docker push "${IMAGE}:${RELEASE_TAG}" + fi + + - name: Build & Push db image + run: | + REF_TYPE="${{ steps.refinfo.outputs.ref_type }}" + RELEASE_TAG="${{ steps.refinfo.outputs.release_tag }}" + IMAGE="${JFROG_REGISTRY}/${{ matrix.image_name_db }}" + + BUILD_TAG_ARGS=( + -t "${IMAGE}:${{ matrix.latest_tag }}" + -t "${IMAGE}:${{ github.sha }}" + ) + if [[ "${REF_TYPE}" == "tag" && -n "${RELEASE_TAG}" ]]; then + BUILD_TAG_ARGS+=( -t "${IMAGE}:${RELEASE_TAG}" ) + fi + + docker build \ + -f Dockerfile.db \ + "${BUILD_TAG_ARGS[@]}" \ + . + + docker push "${IMAGE}:${{ matrix.latest_tag }}" + docker push "${IMAGE}:${{ github.sha }}" + if [[ "${REF_TYPE}" == "tag" && -n "${RELEASE_TAG}" ]]; then + docker push "${IMAGE}:${RELEASE_TAG}" + fi + + - name: Ensure namespace exists + run: | + # `helm --atomic` against a missing namespace fails outright. + kubectl create namespace "${{ matrix.namespace }}" \ + --dry-run=client -o yaml | kubectl apply -f - + + # ---- DEV DEPLOY (branch dev only) ---- + # Deployed by commit SHA, not latest-dev: an immutable tag sidesteps the + # moving-tag + IfNotPresent stale-cache trap and makes `kubectl describe + # pod` show exactly which commit is live. + - name: Deploy DEV with Helm + if: github.ref_type == 'branch' && github.ref == 'refs/heads/dev' + run: | + kubectl get nodes + kubectl get ns + + helm upgrade --install "${{ matrix.release }}" "${{ matrix.chart }}" \ + -f "${{ matrix.values_file }}" \ + --namespace "${{ matrix.namespace }}" \ + --set server.image.repository="${JFROG_REGISTRY}/${{ matrix.image_name_server }}" \ + --set server.image.tag="${{ github.sha }}" \ + --set db.image.repository="${JFROG_REGISTRY}/${{ matrix.image_name_db }}" \ + --set db.image.tag="${{ github.sha }}" \ + --set-string secrets.authSecret="${{ secrets.AUTH_SECRET_DEV }}" \ + --set-string secrets.dbRootPassword="${{ secrets.DB_ROOT_PASSWORD_DEV }}" \ + --set-string secrets.localAdminPassword="${{ secrets.LOCAL_ADMIN_PASSWORD_DEV }}" \ + --wait --timeout 10m --atomic --debug + + # ---- PROD DEPLOY (tag push only) ---- + - name: Deploy PROD with Helm + if: github.ref_type == 'tag' + run: | + kubectl get nodes + kubectl get ns + + TAG="${GITHUB_REF#refs/tags/}" + if [[ -z "${TAG}" ]]; then + echo "No tag detected; aborting prod deploy." + exit 1 + fi + + helm upgrade --install "${{ matrix.release }}" "${{ matrix.chart }}" \ + -f "${{ matrix.values_file }}" \ + --namespace "${{ matrix.namespace }}" \ + --set server.image.repository="${JFROG_REGISTRY}/${{ matrix.image_name_server }}" \ + --set server.image.tag="${TAG}" \ + --set db.image.repository="${JFROG_REGISTRY}/${{ matrix.image_name_db }}" \ + --set db.image.tag="${TAG}" \ + --set-string secrets.authSecret="${{ secrets.AUTH_SECRET_PROD }}" \ + --set-string secrets.dbRootPassword="${{ secrets.DB_ROOT_PASSWORD_PROD }}" \ + --set-string secrets.localAdminPassword="${{ secrets.LOCAL_ADMIN_PASSWORD_PROD }}" \ + --wait --timeout 10m --atomic --debug + + # Strictly redundant with immutable image tags: Helm already rolled the + # pods and --atomic already verified health. Retained as belt-and-braces. + # Scoped to component=server so it does not bounce MySQL every push. + - name: Rollout restart (server only) + if: success() && (github.ref_type == 'branch' || github.ref_type == 'tag') + run: | + kubectl rollout restart deployment \ + -l "app.kubernetes.io/instance=${{ matrix.release }},app.kubernetes.io/component=server" \ + -n "${{ matrix.namespace }}" + + - name: Post-deploy diagnostics (if failure) + if: failure() + run: | + echo "----- Diagnostics -----" + kubectl get deploy,sts,po,svc,ing -n "${{ matrix.namespace }}" -o wide || true + echo "----- PVCs (a Pending PVC = missing gp3 StorageClass; invisible in pod logs) -----" + kubectl get pvc -n "${{ matrix.namespace }}" -o wide || true + echo "----- Events -----" + kubectl get events -n "${{ matrix.namespace }}" --sort-by=.lastTimestamp || true + for p in $(kubectl get po -n "${{ matrix.namespace }}" -o name); do + echo "### $p" + kubectl describe "$p" -n "${{ matrix.namespace }}" || true + kubectl logs "$p" -n "${{ matrix.namespace }}" --all-containers --tail=200 || true + done diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..652e555 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,86 @@ +# syntax=docker/dockerfile:1 +# +# Next.js 15 (standalone) + Prisma server image for the IT Cost Dashboard. +# +# Debian slim, NOT Alpine: better-sqlite3 (a devDependency native addon) ships +# glibc prebuilds and would otherwise compile from source, and Prisma's query +# engine needs the musl-specific binaryTarget on Alpine. ~40 MB more for two +# fewer traps. + +# --------------------------------------------------------------------------- +# Stage 1: deps — install node_modules once, including native addons. +# --------------------------------------------------------------------------- +FROM node:20-bookworm-slim AS deps +WORKDIR /app + +# python3/make/g++ are the better-sqlite3 source-build fallback; openssl is what +# the Prisma postinstall links its query engine against. All discarded with this +# stage. +RUN apt-get update && apt-get install -y --no-install-recommends \ + openssl ca-certificates python3 make g++ \ + && rm -rf /var/lib/apt/lists/* + +COPY package.json package-lock.json ./ +# No --ignore-scripts: Prisma's postinstall is what unpacks the query engine. +RUN npm ci + +# --------------------------------------------------------------------------- +# Stage 2: builder — prisma generate (prod/mysql schema) + next build. +# --------------------------------------------------------------------------- +FROM node:20-bookworm-slim AS builder +WORKDIR /app + +RUN apt-get update && apt-get install -y --no-install-recommends \ + openssl ca-certificates \ + && rm -rf /var/lib/apt/lists/* + +COPY --from=deps /app/node_modules ./node_modules +COPY . . + +# Auth.js v5 constructs NextAuth() at module init (src/auth.ts), which can throw +# without a secret while pre-rendering. This placeholder is build-time only — +# the real AUTH_SECRET arrives at runtime from the k8s Secret. +ARG AUTH_SECRET=build-placeholder-not-used-at-runtime +ENV AUTH_SECRET=${AUTH_SECRET} +ENV NEXT_TELEMETRY_DISABLED=1 +ENV NODE_ENV=production + +# No DATABASE_URL needed: every page is "use client" and fetches /api/* at +# runtime, and `await auth()` in the layout returns null harmlessly. +# build:prod == prisma generate --schema=prisma/prod/schema.prisma && next build +RUN npm run build:prod + +# --------------------------------------------------------------------------- +# Stage 3: runner — standalone output only, non-root. +# --------------------------------------------------------------------------- +FROM node:20-bookworm-slim AS runner +WORKDIR /app + +# openssl is required at runtime: the Prisma query engine links against it. +RUN apt-get update && apt-get install -y --no-install-recommends \ + openssl ca-certificates \ + && rm -rf /var/lib/apt/lists/* + +RUN groupadd --system --gid 1001 nodejs \ + && useradd --system --uid 1001 --gid nodejs nextjs + +# .next/standalone ships its own traced node_modules — do NOT copy the +# builder's. .next/static is NOT part of standalone and must come separately or +# every CSS/JS chunk 404s. config/ is read at runtime by lookupRole() +# (src/lib/authz.ts) via process.cwd() once SSO is re-enabled. +# NOTE: this repo has no public/ directory; adding a COPY for it would fail. +COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./ +COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static +COPY --from=builder --chown=nextjs:nodejs /app/config ./config + +USER nextjs + +ENV HOSTNAME=0.0.0.0 +ENV PORT=3000 +ENV NODE_ENV=production +ENV NEXT_TELEMETRY_DISABLED=1 + +EXPOSE 3000 + +# Standalone replaces `next start`. +CMD ["node", "server.js"] diff --git a/Dockerfile.db b/Dockerfile.db new file mode 100644 index 0000000..7d0d029 --- /dev/null +++ b/Dockerfile.db @@ -0,0 +1,16 @@ +# MySQL 8 with the production schema + demo seed data baked in. +# +# TRAP: /docker-entrypoint-initdb.d/* runs ONLY when the datadir is empty. On a +# redeploy against an existing gp3 PVC these scripts are skipped — existing data +# survives (correct) but schema changes are NOT applied. Future schema changes +# need `npm run prod:migrate` run as a separate Job; 01-schema.sql bootstraps +# the _prisma_migrations table so that stays possible. +FROM mysql:8 + +ENV MYSQL_DATABASE=it_cost_dashboard + +# MYSQL_ROOT_PASSWORD is deliberately NOT baked in — it arrives as a pod env var +# from the Helm-rendered k8s Secret. + +COPY prisma/prod/01-schema.sql /docker-entrypoint-initdb.d/01-schema.sql +COPY prisma/seed.sql /docker-entrypoint-initdb.d/02-seed.sql diff --git a/helm/Chart.yaml b/helm/Chart.yaml new file mode 100644 index 0000000..a47d961 --- /dev/null +++ b/helm/Chart.yaml @@ -0,0 +1,6 @@ +apiVersion: v2 +name: it-cost-dashboard +description: Global IT Cost Dashboard — Next.js server + MySQL 8 on self-built k8s +type: application +version: 0.1.0 +appVersion: "0.1.0" diff --git a/helm/templates/_helpers.tpl b/helm/templates/_helpers.tpl new file mode 100644 index 0000000..2474390 --- /dev/null +++ b/helm/templates/_helpers.tpl @@ -0,0 +1,56 @@ +{{/* Chart name, overridable. */}} +{{- define "it-cost-dashboard.name" -}} +{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }} +{{- end }} + +{{/* +Fully qualified app name. Kept short: it prefixes the StatefulSet name, which +in turn prefixes pod names and the generated PVC names. +*/}} +{{- define "it-cost-dashboard.fullname" -}} +{{- if .Values.fullnameOverride }} +{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }} +{{- else }} +{{- .Release.Name | trunc 63 | trimSuffix "-" }} +{{- end }} +{{- end }} + +{{- define "it-cost-dashboard.chart" -}} +{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }} +{{- end }} + +{{/* Labels applied to every object. */}} +{{- define "it-cost-dashboard.labels" -}} +helm.sh/chart: {{ include "it-cost-dashboard.chart" . }} +{{ include "it-cost-dashboard.selectorLabels" . }} +{{- if .Chart.AppVersion }} +app.kubernetes.io/version: {{ .Chart.AppVersion | quote }} +{{- end }} +app.kubernetes.io/managed-by: {{ .Release.Service }} +{{- end }} + +{{- define "it-cost-dashboard.selectorLabels" -}} +app.kubernetes.io/name: {{ include "it-cost-dashboard.name" . }} +app.kubernetes.io/instance: {{ .Release.Name }} +{{- end }} + +{{/* +Component-scoped labels. The workflow's rollout-restart selects on +app.kubernetes.io/component=server so it does not bounce MySQL. +Usage: {{ include "it-cost-dashboard.componentLabels" (dict "ctx" . "component" "server") }} +*/}} +{{- define "it-cost-dashboard.componentLabels" -}} +{{ include "it-cost-dashboard.labels" .ctx }} +app.kubernetes.io/component: {{ .component }} +{{- end }} + +{{- define "it-cost-dashboard.componentSelectorLabels" -}} +{{ include "it-cost-dashboard.selectorLabels" .ctx }} +app.kubernetes.io/component: {{ .component }} +{{- end }} + +{{/* ClusterIP Service name for MySQL — the DATABASE_URL host and the + wait-for-db initContainer target. */}} +{{- define "it-cost-dashboard.dbServiceName" -}} +{{- printf "%s-db" (include "it-cost-dashboard.fullname" .) }} +{{- end }} diff --git a/helm/templates/db-secret.yaml b/helm/templates/db-secret.yaml new file mode 100644 index 0000000..369d29f --- /dev/null +++ b/helm/templates/db-secret.yaml @@ -0,0 +1,13 @@ +apiVersion: v1 +kind: Secret +metadata: + name: {{ include "it-cost-dashboard.fullname" . }}-db-secret + labels: + {{- include "it-cost-dashboard.componentLabels" (dict "ctx" . "component" "db") | nindent 4 }} +type: Opaque +stringData: + # Supplied by the workflow: --set-string secrets.dbRootPassword=... + # Constrained to [A-Za-z0-9-]: it is interpolated verbatim into DATABASE_URL + # in server-secret.yaml and Helm cannot URL-encode. + MYSQL_ROOT_PASSWORD: {{ required "secrets.dbRootPassword is required" .Values.secrets.dbRootPassword | quote }} + MYSQL_DATABASE: {{ .Values.db.database | quote }} diff --git a/helm/templates/db-service.yaml b/helm/templates/db-service.yaml new file mode 100644 index 0000000..b6e0831 --- /dev/null +++ b/helm/templates/db-service.yaml @@ -0,0 +1,40 @@ +{{/* +Headless service: stable per-pod DNS for the StatefulSet +(-db-0.-db-headless). Required by the StatefulSet spec. +*/}} +apiVersion: v1 +kind: Service +metadata: + name: {{ include "it-cost-dashboard.fullname" . }}-db-headless + labels: + {{- include "it-cost-dashboard.componentLabels" (dict "ctx" . "component" "db") | nindent 4 }} +spec: + clusterIP: None + ports: + - name: mysql + port: {{ .Values.db.port }} + targetPort: mysql + protocol: TCP + selector: + {{- include "it-cost-dashboard.componentSelectorLabels" (dict "ctx" . "component" "db") | nindent 4 }} +--- +{{/* +Normal ClusterIP service. This is what DATABASE_URL and the wait-for-db +initContainer target — simpler than per-pod DNS and sufficient for a +single-primary MySQL. +*/}} +apiVersion: v1 +kind: Service +metadata: + name: {{ include "it-cost-dashboard.dbServiceName" . }} + labels: + {{- include "it-cost-dashboard.componentLabels" (dict "ctx" . "component" "db") | nindent 4 }} +spec: + type: ClusterIP + ports: + - name: mysql + port: {{ .Values.db.port }} + targetPort: mysql + protocol: TCP + selector: + {{- include "it-cost-dashboard.componentSelectorLabels" (dict "ctx" . "component" "db") | nindent 4 }} diff --git a/helm/templates/db-statefulset.yaml b/helm/templates/db-statefulset.yaml new file mode 100644 index 0000000..4b4e1a7 --- /dev/null +++ b/helm/templates/db-statefulset.yaml @@ -0,0 +1,97 @@ +{{/* +MySQL as a StatefulSet, not a Deployment: volumeClaimTemplates guarantees a +single writer on the gp3 volume, the pod name is stable, and the PVC survives +`helm uninstall` so an accidental teardown does not destroy data. +*/}} +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: {{ include "it-cost-dashboard.fullname" . }}-db + labels: + {{- include "it-cost-dashboard.componentLabels" (dict "ctx" . "component" "db") | nindent 4 }} +spec: + # Single-primary MySQL. NEVER raise this without real clustering — two pods + # would fight over one RWO volume / diverge. + replicas: 1 + serviceName: {{ include "it-cost-dashboard.fullname" . }}-db-headless + selector: + matchLabels: + {{- include "it-cost-dashboard.componentSelectorLabels" (dict "ctx" . "component" "db") | nindent 6 }} + template: + metadata: + labels: + {{- include "it-cost-dashboard.componentSelectorLabels" (dict "ctx" . "component" "db") | nindent 8 }} + spec: + {{- with .Values.imagePullSecrets }} + imagePullSecrets: + {{- toYaml . | nindent 8 }} + {{- end }} + containers: + - name: mysql + image: "{{ required "db.image.repository is required" .Values.db.image.repository }}:{{ required "db.image.tag is required" .Values.db.image.tag }}" + imagePullPolicy: {{ .Values.db.image.pullPolicy }} + ports: + - name: mysql + containerPort: {{ .Values.db.port }} + protocol: TCP + env: + - name: MYSQL_ROOT_PASSWORD + valueFrom: + secretKeyRef: + name: {{ include "it-cost-dashboard.fullname" . }}-db-secret + key: MYSQL_ROOT_PASSWORD + - name: MYSQL_DATABASE + valueFrom: + secretKeyRef: + name: {{ include "it-cost-dashboard.fullname" . }}-db-secret + key: MYSQL_DATABASE + # Generous initialDelay: the first boot runs both + # /docker-entrypoint-initdb.d scripts (schema + 430 seed rows) before + # opening TCP for real. + readinessProbe: + exec: + command: + - bash + - -c + - 'mysqladmin ping -u root -p"${MYSQL_ROOT_PASSWORD}" --silent' + initialDelaySeconds: 30 + periodSeconds: 10 + timeoutSeconds: 5 + failureThreshold: 12 + livenessProbe: + exec: + command: + - bash + - -c + - 'mysqladmin ping -u root -p"${MYSQL_ROOT_PASSWORD}" --silent' + initialDelaySeconds: 120 + periodSeconds: 20 + timeoutSeconds: 5 + failureThreshold: 6 + volumeMounts: + - name: mysql-data + mountPath: /var/lib/mysql + resources: + {{- toYaml .Values.db.resources | nindent 12 }} + {{- with .Values.nodeSelector }} + nodeSelector: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.tolerations }} + tolerations: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.affinity }} + affinity: + {{- toYaml . | nindent 8 }} + {{- end }} + volumeClaimTemplates: + - metadata: + name: mysql-data + spec: + accessModes: + - ReadWriteOnce + storageClassName: {{ .Values.db.storage.storageClassName }} + resources: + requests: + storage: {{ .Values.db.storage.size }} diff --git a/helm/templates/server-deployment.yaml b/helm/templates/server-deployment.yaml new file mode 100644 index 0000000..85b11f4 --- /dev/null +++ b/helm/templates/server-deployment.yaml @@ -0,0 +1,90 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ include "it-cost-dashboard.fullname" . }}-server + labels: + {{- include "it-cost-dashboard.componentLabels" (dict "ctx" . "component" "server") | nindent 4 }} +spec: + replicas: {{ .Values.replicaCount }} + selector: + matchLabels: + {{- include "it-cost-dashboard.componentSelectorLabels" (dict "ctx" . "component" "server") | nindent 6 }} + template: + metadata: + labels: + {{- include "it-cost-dashboard.componentSelectorLabels" (dict "ctx" . "component" "server") | nindent 8 }} + spec: + {{- with .Values.imagePullSecrets }} + imagePullSecrets: + {{- toYaml . | nindent 8 }} + {{- end }} + initContainers: + # Without this the server starts before MySQL, Prisma throws, the pod + # CrashLoopBackOffs, and `helm --atomic --wait` rolls the whole release + # back. + - name: wait-for-db + image: busybox:1.36 + command: + - sh + - -c + - | + until nc -z {{ include "it-cost-dashboard.dbServiceName" . }} {{ .Values.db.port }}; do + echo "waiting for {{ include "it-cost-dashboard.dbServiceName" . }}:{{ .Values.db.port }}..." + sleep 3 + done + echo "database is accepting connections" + containers: + - name: server + image: "{{ required "server.image.repository is required" .Values.server.image.repository }}:{{ required "server.image.tag is required" .Values.server.image.tag }}" + imagePullPolicy: {{ .Values.server.image.pullPolicy }} + ports: + - name: http + containerPort: {{ .Values.server.service.port }} + protocol: TCP + env: + - name: NODE_ENV + value: "production" + - name: NEXT_TELEMETRY_DISABLED + value: "1" + envFrom: + - secretRef: + name: {{ include "it-cost-dashboard.fullname" . }}-server-secret + # Readiness hits a DB-backed route on purpose: a pod only takes + # traffic once MySQL is reachable AND the schema is right. + # NOTE (SSO restore): /api/years will 307 to /login once the + # middleware is back on, which is non-2xx — add a public /api/health + # route and probe that instead. + readinessProbe: + httpGet: + path: /api/years + port: http + initialDelaySeconds: 10 + periodSeconds: 5 + timeoutSeconds: 3 + # 12 x 5s tolerates a slow first-boot seed. + failureThreshold: 12 + # Liveness deliberately differs: /login needs no DB, so a transient + # MySQL blip makes pods unready (traffic stops) without kubelet + # killing them in a restart storm. + livenessProbe: + httpGet: + path: /login + port: http + initialDelaySeconds: 30 + periodSeconds: 20 + timeoutSeconds: 5 + failureThreshold: 6 + resources: + {{- toYaml .Values.server.resources | nindent 12 }} + {{- with .Values.nodeSelector }} + nodeSelector: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.tolerations }} + tolerations: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.affinity }} + affinity: + {{- toYaml . | nindent 8 }} + {{- end }} diff --git a/helm/templates/server-ingress.yaml b/helm/templates/server-ingress.yaml new file mode 100644 index 0000000..12ccb32 --- /dev/null +++ b/helm/templates/server-ingress.yaml @@ -0,0 +1,24 @@ +{{- if .Values.ingress.enabled }} +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + name: {{ include "it-cost-dashboard.fullname" . }}-server + labels: + {{- include "it-cost-dashboard.componentLabels" (dict "ctx" . "component" "server") | nindent 4 }} + annotations: + nginx.ingress.kubernetes.io/proxy-body-size: "10m" +spec: + ingressClassName: {{ .Values.ingress.className }} + # HTTP only for now — no TLS block until certs are issued for these hosts. + rules: + - host: {{ required "ingress.host is required" .Values.ingress.host | quote }} + http: + paths: + - path: / + pathType: Prefix + backend: + service: + name: {{ include "it-cost-dashboard.fullname" . }}-server + port: + name: http +{{- end }} diff --git a/helm/templates/server-secret.yaml b/helm/templates/server-secret.yaml new file mode 100644 index 0000000..49fb01e --- /dev/null +++ b/helm/templates/server-secret.yaml @@ -0,0 +1,28 @@ +apiVersion: v1 +kind: Secret +metadata: + name: {{ include "it-cost-dashboard.fullname" . }}-server-secret + labels: + {{- include "it-cost-dashboard.componentLabels" (dict "ctx" . "component" "server") | nindent 4 }} +type: Opaque +stringData: + # Built in-template from the db root password + the db ClusterIP Service name. + # TRAP: Helm has no URL-encode function, so secrets.dbRootPassword must avoid + # URL-reserved characters (@ : / # ? % + & and space) — keep it [A-Za-z0-9-]. + DATABASE_URL: "mysql://root:{{ required "secrets.dbRootPassword is required" .Values.secrets.dbRootPassword }}@{{ include "it-cost-dashboard.dbServiceName" . }}:{{ .Values.db.port }}/{{ .Values.db.database }}" + + # Auth.js JWT signing key. Required at runtime even with SSO commented out. + AUTH_SECRET: {{ required "secrets.authSecret is required" .Values.secrets.authSecret | quote }} + AUTH_TRUST_HOST: "true" + + # Break-glass local login. Empty disables it entirely (src/auth.ts fails closed). + LOCAL_ADMIN_PASSWORD: {{ .Values.secrets.localAdminPassword | default "" | quote }} + + # --- SSO DISABLED FOR CICD TEST --- + # Kept present but optional. To restore SSO: supply these values from the + # per-env GitHub secrets and swap `| default ""` for `| required "..."`. + AUTH_MICROSOFT_ENTRA_ID_ID: {{ .Values.secrets.entraClientId | default "" | quote }} + AUTH_MICROSOFT_ENTRA_ID_SECRET: {{ .Values.secrets.entraClientSecret | default "" | quote }} + AUTH_MICROSOFT_ENTRA_ID_ISSUER: {{ .Values.secrets.entraIssuer | default "" | quote }} + AUTH_URL: {{ .Values.secrets.authUrl | default "" | quote }} + # --- END SSO DISABLED --- diff --git a/helm/templates/server-service.yaml b/helm/templates/server-service.yaml new file mode 100644 index 0000000..4931ab1 --- /dev/null +++ b/helm/templates/server-service.yaml @@ -0,0 +1,15 @@ +apiVersion: v1 +kind: Service +metadata: + name: {{ include "it-cost-dashboard.fullname" . }}-server + labels: + {{- include "it-cost-dashboard.componentLabels" (dict "ctx" . "component" "server") | nindent 4 }} +spec: + type: {{ .Values.server.service.type }} + ports: + - name: http + port: {{ .Values.server.service.port }} + targetPort: http + protocol: TCP + selector: + {{- include "it-cost-dashboard.componentSelectorLabels" (dict "ctx" . "component" "server") | nindent 4 }} diff --git a/helm/values-dev.yaml b/helm/values-dev.yaml new file mode 100644 index 0000000..3570965 --- /dev/null +++ b/helm/values-dev.yaml @@ -0,0 +1,34 @@ +# dev overrides. Image tags come from the workflow (--set ...image.tag=). + +replicaCount: 1 + +server: + image: + repository: jfrog.trendmicro.com/ameait-it-cost-dashboard/it-cost-dashboard-server-dev + resources: + requests: + cpu: 100m + memory: 256Mi + limits: + cpu: 500m + memory: 512Mi + +db: + image: + repository: jfrog.trendmicro.com/ameait-it-cost-dashboard/it-cost-dashboard-db-dev + storage: + size: 5Gi + storageClassName: gp3 + resources: + requests: + cpu: 100m + memory: 512Mi + limits: + cpu: 1 + memory: 1Gi + +ingress: + enabled: true + className: nginx + # TODO: point this at a hostname resolving to the ingress-nginx external IP. + host: it-cost-dashboard-dev.example.com diff --git a/helm/values-prod.yaml b/helm/values-prod.yaml new file mode 100644 index 0000000..f1b0c0d --- /dev/null +++ b/helm/values-prod.yaml @@ -0,0 +1,34 @@ +# prod overrides. Image tags come from the workflow (--set ...image.tag=). + +replicaCount: 2 + +server: + image: + repository: jfrog.trendmicro.com/ameait-it-cost-dashboard/it-cost-dashboard-server-prod + resources: + requests: + cpu: 250m + memory: 512Mi + limits: + cpu: 1 + memory: 1Gi + +db: + image: + repository: jfrog.trendmicro.com/ameait-it-cost-dashboard/it-cost-dashboard-db-prod + storage: + size: 20Gi + storageClassName: gp3 + resources: + requests: + cpu: 250m + memory: 1Gi + limits: + cpu: 2 + memory: 2Gi + +ingress: + enabled: true + className: nginx + # TODO: point this at a hostname resolving to the ingress-nginx external IP. + host: it-cost-dashboard.example.com diff --git a/helm/values.yaml b/helm/values.yaml new file mode 100644 index 0000000..097252b --- /dev/null +++ b/helm/values.yaml @@ -0,0 +1,67 @@ +# Base defaults. Per-environment overrides live in values-dev.yaml / +# values-prod.yaml; image TAGS are always supplied by the CI workflow via --set +# (immutable: commit SHA on dev, git tag on prod) and are never pinned here. + +replicaCount: 1 + +server: + image: + repository: "" + tag: "" + pullPolicy: IfNotPresent + service: + type: ClusterIP + port: 3000 + resources: + requests: + cpu: 100m + memory: 256Mi + limits: + cpu: 500m + memory: 512Mi + +db: + image: + repository: "" + tag: "" + pullPolicy: IfNotPresent + port: 3306 + database: it_cost_dashboard + storage: + size: 5Gi + storageClassName: gp3 + resources: + requests: + cpu: 100m + memory: 512Mi + limits: + cpu: 1 + memory: 1Gi + +ingress: + enabled: true + className: nginx + host: "" # required per-env + +secrets: + authSecret: "" # from GitHub secret AUTH_SECRET_ + # MySQL root password. MUST be [A-Za-z0-9-] only — it is interpolated into + # DATABASE_URL and Helm has no URL-encode function. + dbRootPassword: "" # from GitHub secret DB_ROOT_PASSWORD_ + # Optional; empty disables local login entirely (src/auth.ts fails closed). + localAdminPassword: "" + # --- SSO restore: set these (and swap `default ""` for `required` in + # templates/server-secret.yaml) when Entra ID is re-enabled --- + # entraClientId: "" + # entraClientSecret: "" + # entraIssuer: "" + # authUrl: "" + +# Pre-created manually, once per namespace (see the deploy notes). Not templated: +# the kubelet needs it independently of Helm. +imagePullSecrets: + - name: jfrog-registry-creds + +nodeSelector: {} +tolerations: [] +affinity: {} diff --git a/next.config.mjs b/next.config.mjs index 4678774..63d9f4e 100644 --- a/next.config.mjs +++ b/next.config.mjs @@ -1,4 +1,8 @@ /** @type {import('next').NextConfig} */ -const nextConfig = {}; +const nextConfig = { + // Emit .next/standalone (a self-contained server.js + traced node_modules) so + // the Docker runtime stage stays small and needs no `npm install`. + output: "standalone", +}; export default nextConfig; diff --git a/prisma/generate-seed-sql.mjs b/prisma/generate-seed-sql.mjs new file mode 100644 index 0000000..d05bdb7 --- /dev/null +++ b/prisma/generate-seed-sql.mjs @@ -0,0 +1,149 @@ +// Emits prisma/seed.sql — the plain-SQL twin of prisma/seed.ts, for baking into +// the MySQL image (see Dockerfile.db). 275 SubCostItem rows are not hand- +// writable, and the container has no Node/Prisma to run seed.ts with. +// +// node prisma/generate-seed-sql.mjs > prisma/seed.sql +// +// The constants and arithmetic below mirror prisma/seed.ts verbatim. If seed.ts +// changes, change them here too and regenerate. + +const REGIONS = ["AMEA IT", "EMEA IT", "NABU IT", "PH IT", "JP IT"]; +const YEARS = [2022, 2023, 2024, 2025, 2026]; + +const ITEMS = [ + { + name: "Cloud Hosting", + subs: [ + { name: "Compute (VMs)", base: 40000 }, + { name: "Storage", base: 18000 }, + { name: "Networking / Egress", base: 9000 }, + ], + }, + { + name: "Software Licenses", + subs: [ + { name: "Productivity Suite", base: 22000 }, + { name: "Design Tools", base: 8000 }, + ], + }, + { + name: "Security Tools", + subs: [ + { name: "Endpoint Protection", base: 15000 }, + { name: "SIEM", base: 20000 }, + { name: "Vulnerability Scanning", base: 6000 }, + ], + }, + { + name: "Support & Maintenance", + subs: [{ name: "Vendor Support Contract", base: 30000 }], + }, + { + name: "Network Infra", + subs: [ + { name: "Circuits / Bandwidth", base: 25000 }, + { name: "Hardware Refresh", base: 12000 }, + ], + }, +]; + +const REGION_WEIGHT = { + "NABU IT": 1.4, + "EMEA IT": 1.2, + "AMEA IT": 1.0, + "JP IT": 0.9, + "PH IT": 0.7, +}; + +const REGION_AI = { + "NABU IT": { base: 12, step: 6 }, + "EMEA IT": { base: 10, step: 5 }, + "AMEA IT": { base: 8, step: 5 }, + "JP IT": { base: 15, step: 4 }, + "PH IT": { base: 6, step: 4 }, +}; + +function yearFactor(year) { + return Math.pow(1.08, year - 2022); +} + +// Fixed so regenerating yields a byte-identical file (empty diff). +const TS = "2026-01-01 00:00:00.000"; + +function q(s) { + return `'${String(s).replace(/\\/g, "\\\\").replace(/'/g, "''")}'`; +} + +const yearRows = YEARS.map((y) => ` (${y})`); +const costRows = []; +const subRows = []; +const pctRows = []; + +let costId = 0; +let subId = 0; +let pctId = 0; + +for (const region of REGIONS) { + const weight = REGION_WEIGHT[region]; + for (const year of YEARS) { + const yf = yearFactor(year); + for (const item of ITEMS) { + costId += 1; + costRows.push( + ` (${costId},${q(item.name)},${q(region)},${year},${q(TS)},${q(TS)})` + ); + for (const s of item.subs) { + subId += 1; + const subCost = Math.round((s.base * weight * yf) / 100) * 100; + subRows.push(` (${subId},${q(s.name)},${subCost},${costId})`); + } + } + } +} + +for (const region of REGIONS) { + const ai = REGION_AI[region]; + for (const year of YEARS) { + pctId += 1; + const pct = Math.min(60, ai.base + (year - 2022) * ai.step); + pctRows.push(` (${pctId},${q(region)},${year},${pct})`); + } +} + +const out = []; +out.push("-- GENERATED FILE — do not edit by hand."); +out.push("-- Regenerate with: node prisma/generate-seed-sql.mjs > prisma/seed.sql"); +out.push( + `-- Rows: CostItem=${costId}, SubCostItem=${subId}, TrendAiPercentage=${pctId}, Year=${YEARS.length}` +); +out.push(""); +// Explicit IDs mean the FK targets are known up front; disabling the check lets +// the inserts run in any order and keeps the file order-independent. +out.push("SET FOREIGN_KEY_CHECKS=0;"); +out.push(""); +out.push("INSERT INTO `Year` (`year`) VALUES"); +out.push(yearRows.join(",\n") + ";"); +out.push(""); +out.push( + "INSERT INTO `CostItem` (`id`,`name`,`region`,`year`,`createdAt`,`updatedAt`) VALUES" +); +out.push(costRows.join(",\n") + ";"); +out.push(""); +out.push("INSERT INTO `SubCostItem` (`id`,`name`,`subCost`,`costItemId`) VALUES"); +out.push(subRows.join(",\n") + ";"); +out.push(""); +out.push( + "INSERT INTO `TrendAiPercentage` (`id`,`region`,`year`,`percentage`) VALUES" +); +out.push(pctRows.join(",\n") + ";"); +out.push(""); +// Explicit IDs leave AUTO_INCREMENT at 1 in some engines/versions; reset it or +// the first app-side insert collides with a seeded row. +out.push(`ALTER TABLE \`CostItem\` AUTO_INCREMENT = ${costId + 1};`); +out.push(`ALTER TABLE \`SubCostItem\` AUTO_INCREMENT = ${subId + 1};`); +out.push(`ALTER TABLE \`TrendAiPercentage\` AUTO_INCREMENT = ${pctId + 1};`); +out.push(""); +out.push("SET FOREIGN_KEY_CHECKS=1;"); +out.push(""); + +process.stdout.write(out.join("\n")); diff --git a/prisma/prod/01-schema.sql b/prisma/prod/01-schema.sql new file mode 100644 index 0000000..1f7b4b3 --- /dev/null +++ b/prisma/prod/01-schema.sql @@ -0,0 +1,75 @@ +-- Schema bootstrap for the containerized MySQL 8 pod (see Dockerfile.db). +-- Runs as /docker-entrypoint-initdb.d/01-schema.sql, i.e. ONLY on a first boot +-- against an empty datadir. +-- +-- Body below is verbatim from: +-- prisma/prod/migrations/20260729000000_init/migration.sql +-- Do not edit that file — it stays the source of truth. + +-- --------------------------------------------------------------------------- +-- Prisma migration bookkeeping. +-- The raw migration SQL creates no _prisma_migrations table, so a later +-- `npm run prod:migrate` would try to re-apply 20260729000000_init and fail +-- with "table already exists". Recording it as applied up front keeps future +-- migrations working against this volume. +-- --------------------------------------------------------------------------- +CREATE TABLE IF NOT EXISTS `_prisma_migrations` ( + `id` VARCHAR(36) NOT NULL, + `checksum` VARCHAR(64) NOT NULL, + `finished_at` DATETIME(3) NULL, + `migration_name` VARCHAR(255) NOT NULL, + `logs` TEXT NULL, + `rolled_back_at` DATETIME(3) NULL, + `started_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), + `applied_steps_count` INT UNSIGNED NOT NULL DEFAULT 0, + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +INSERT INTO `_prisma_migrations` + (`id`,`checksum`,`finished_at`,`migration_name`,`started_at`,`applied_steps_count`) +VALUES (UUID(),'bootstrapped-by-dockerfile-db',NOW(3),'20260729000000_init',NOW(3),1); + +-- CreateTable +CREATE TABLE `CostItem` ( + `id` INTEGER NOT NULL AUTO_INCREMENT, + `name` VARCHAR(191) NOT NULL, + `region` VARCHAR(191) NOT NULL, + `year` INTEGER NOT NULL, + `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), + `updatedAt` DATETIME(3) NOT NULL, + + INDEX `CostItem_region_year_idx`(`region`, `year`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `SubCostItem` ( + `id` INTEGER NOT NULL AUTO_INCREMENT, + `name` VARCHAR(191) NOT NULL, + `subCost` DOUBLE NOT NULL, + `costItemId` INTEGER NOT NULL, + + INDEX `SubCostItem_costItemId_idx`(`costItemId`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `TrendAiPercentage` ( + `id` INTEGER NOT NULL AUTO_INCREMENT, + `region` VARCHAR(191) NOT NULL, + `year` INTEGER NOT NULL, + `percentage` DOUBLE NOT NULL, + + UNIQUE INDEX `TrendAiPercentage_region_year_key`(`region`, `year`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `Year` ( + `year` INTEGER NOT NULL, + + PRIMARY KEY (`year`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- AddForeignKey +ALTER TABLE `SubCostItem` ADD CONSTRAINT `SubCostItem_costItemId_fkey` FOREIGN KEY (`costItemId`) REFERENCES `CostItem`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/prisma/seed.sql b/prisma/seed.sql new file mode 100644 index 0000000..988ad35 --- /dev/null +++ b/prisma/seed.sql @@ -0,0 +1,449 @@ +-- GENERATED FILE — do not edit by hand. +-- Regenerate with: node prisma/generate-seed-sql.mjs > prisma/seed.sql +-- Rows: CostItem=125, SubCostItem=275, TrendAiPercentage=25, Year=5 + +SET FOREIGN_KEY_CHECKS=0; + +INSERT INTO `Year` (`year`) VALUES + (2022), + (2023), + (2024), + (2025), + (2026); + +INSERT INTO `CostItem` (`id`,`name`,`region`,`year`,`createdAt`,`updatedAt`) VALUES + (1,'Cloud Hosting','AMEA IT',2022,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (2,'Software Licenses','AMEA IT',2022,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (3,'Security Tools','AMEA IT',2022,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (4,'Support & Maintenance','AMEA IT',2022,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (5,'Network Infra','AMEA IT',2022,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (6,'Cloud Hosting','AMEA IT',2023,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (7,'Software Licenses','AMEA IT',2023,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (8,'Security Tools','AMEA IT',2023,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (9,'Support & Maintenance','AMEA IT',2023,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (10,'Network Infra','AMEA IT',2023,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (11,'Cloud Hosting','AMEA IT',2024,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (12,'Software Licenses','AMEA IT',2024,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (13,'Security Tools','AMEA IT',2024,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (14,'Support & Maintenance','AMEA IT',2024,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (15,'Network Infra','AMEA IT',2024,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (16,'Cloud Hosting','AMEA IT',2025,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (17,'Software Licenses','AMEA IT',2025,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (18,'Security Tools','AMEA IT',2025,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (19,'Support & Maintenance','AMEA IT',2025,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (20,'Network Infra','AMEA IT',2025,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (21,'Cloud Hosting','AMEA IT',2026,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (22,'Software Licenses','AMEA IT',2026,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (23,'Security Tools','AMEA IT',2026,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (24,'Support & Maintenance','AMEA IT',2026,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (25,'Network Infra','AMEA IT',2026,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (26,'Cloud Hosting','EMEA IT',2022,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (27,'Software Licenses','EMEA IT',2022,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (28,'Security Tools','EMEA IT',2022,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (29,'Support & Maintenance','EMEA IT',2022,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (30,'Network Infra','EMEA IT',2022,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (31,'Cloud Hosting','EMEA IT',2023,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (32,'Software Licenses','EMEA IT',2023,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (33,'Security Tools','EMEA IT',2023,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (34,'Support & Maintenance','EMEA IT',2023,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (35,'Network Infra','EMEA IT',2023,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (36,'Cloud Hosting','EMEA IT',2024,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (37,'Software Licenses','EMEA IT',2024,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (38,'Security Tools','EMEA IT',2024,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (39,'Support & Maintenance','EMEA IT',2024,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (40,'Network Infra','EMEA IT',2024,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (41,'Cloud Hosting','EMEA IT',2025,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (42,'Software Licenses','EMEA IT',2025,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (43,'Security Tools','EMEA IT',2025,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (44,'Support & Maintenance','EMEA IT',2025,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (45,'Network Infra','EMEA IT',2025,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (46,'Cloud Hosting','EMEA IT',2026,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (47,'Software Licenses','EMEA IT',2026,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (48,'Security Tools','EMEA IT',2026,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (49,'Support & Maintenance','EMEA IT',2026,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (50,'Network Infra','EMEA IT',2026,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (51,'Cloud Hosting','NABU IT',2022,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (52,'Software Licenses','NABU IT',2022,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (53,'Security Tools','NABU IT',2022,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (54,'Support & Maintenance','NABU IT',2022,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (55,'Network Infra','NABU IT',2022,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (56,'Cloud Hosting','NABU IT',2023,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (57,'Software Licenses','NABU IT',2023,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (58,'Security Tools','NABU IT',2023,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (59,'Support & Maintenance','NABU IT',2023,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (60,'Network Infra','NABU IT',2023,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (61,'Cloud Hosting','NABU IT',2024,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (62,'Software Licenses','NABU IT',2024,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (63,'Security Tools','NABU IT',2024,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (64,'Support & Maintenance','NABU IT',2024,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (65,'Network Infra','NABU IT',2024,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (66,'Cloud Hosting','NABU IT',2025,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (67,'Software Licenses','NABU IT',2025,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (68,'Security Tools','NABU IT',2025,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (69,'Support & Maintenance','NABU IT',2025,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (70,'Network Infra','NABU IT',2025,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (71,'Cloud Hosting','NABU IT',2026,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (72,'Software Licenses','NABU IT',2026,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (73,'Security Tools','NABU IT',2026,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (74,'Support & Maintenance','NABU IT',2026,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (75,'Network Infra','NABU IT',2026,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (76,'Cloud Hosting','PH IT',2022,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (77,'Software Licenses','PH IT',2022,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (78,'Security Tools','PH IT',2022,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (79,'Support & Maintenance','PH IT',2022,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (80,'Network Infra','PH IT',2022,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (81,'Cloud Hosting','PH IT',2023,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (82,'Software Licenses','PH IT',2023,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (83,'Security Tools','PH IT',2023,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (84,'Support & Maintenance','PH IT',2023,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (85,'Network Infra','PH IT',2023,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (86,'Cloud Hosting','PH IT',2024,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (87,'Software Licenses','PH IT',2024,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (88,'Security Tools','PH IT',2024,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (89,'Support & Maintenance','PH IT',2024,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (90,'Network Infra','PH IT',2024,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (91,'Cloud Hosting','PH IT',2025,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (92,'Software Licenses','PH IT',2025,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (93,'Security Tools','PH IT',2025,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (94,'Support & Maintenance','PH IT',2025,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (95,'Network Infra','PH IT',2025,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (96,'Cloud Hosting','PH IT',2026,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (97,'Software Licenses','PH IT',2026,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (98,'Security Tools','PH IT',2026,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (99,'Support & Maintenance','PH IT',2026,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (100,'Network Infra','PH IT',2026,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (101,'Cloud Hosting','JP IT',2022,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (102,'Software Licenses','JP IT',2022,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (103,'Security Tools','JP IT',2022,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (104,'Support & Maintenance','JP IT',2022,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (105,'Network Infra','JP IT',2022,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (106,'Cloud Hosting','JP IT',2023,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (107,'Software Licenses','JP IT',2023,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (108,'Security Tools','JP IT',2023,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (109,'Support & Maintenance','JP IT',2023,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (110,'Network Infra','JP IT',2023,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (111,'Cloud Hosting','JP IT',2024,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (112,'Software Licenses','JP IT',2024,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (113,'Security Tools','JP IT',2024,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (114,'Support & Maintenance','JP IT',2024,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (115,'Network Infra','JP IT',2024,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (116,'Cloud Hosting','JP IT',2025,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (117,'Software Licenses','JP IT',2025,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (118,'Security Tools','JP IT',2025,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (119,'Support & Maintenance','JP IT',2025,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (120,'Network Infra','JP IT',2025,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (121,'Cloud Hosting','JP IT',2026,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (122,'Software Licenses','JP IT',2026,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (123,'Security Tools','JP IT',2026,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (124,'Support & Maintenance','JP IT',2026,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'), + (125,'Network Infra','JP IT',2026,'2026-01-01 00:00:00.000','2026-01-01 00:00:00.000'); + +INSERT INTO `SubCostItem` (`id`,`name`,`subCost`,`costItemId`) VALUES + (1,'Compute (VMs)',40000,1), + (2,'Storage',18000,1), + (3,'Networking / Egress',9000,1), + (4,'Productivity Suite',22000,2), + (5,'Design Tools',8000,2), + (6,'Endpoint Protection',15000,3), + (7,'SIEM',20000,3), + (8,'Vulnerability Scanning',6000,3), + (9,'Vendor Support Contract',30000,4), + (10,'Circuits / Bandwidth',25000,5), + (11,'Hardware Refresh',12000,5), + (12,'Compute (VMs)',43200,6), + (13,'Storage',19400,6), + (14,'Networking / Egress',9700,6), + (15,'Productivity Suite',23800,7), + (16,'Design Tools',8600,7), + (17,'Endpoint Protection',16200,8), + (18,'SIEM',21600,8), + (19,'Vulnerability Scanning',6500,8), + (20,'Vendor Support Contract',32400,9), + (21,'Circuits / Bandwidth',27000,10), + (22,'Hardware Refresh',13000,10), + (23,'Compute (VMs)',46700,11), + (24,'Storage',21000,11), + (25,'Networking / Egress',10500,11), + (26,'Productivity Suite',25700,12), + (27,'Design Tools',9300,12), + (28,'Endpoint Protection',17500,13), + (29,'SIEM',23300,13), + (30,'Vulnerability Scanning',7000,13), + (31,'Vendor Support Contract',35000,14), + (32,'Circuits / Bandwidth',29200,15), + (33,'Hardware Refresh',14000,15), + (34,'Compute (VMs)',50400,16), + (35,'Storage',22700,16), + (36,'Networking / Egress',11300,16), + (37,'Productivity Suite',27700,17), + (38,'Design Tools',10100,17), + (39,'Endpoint Protection',18900,18), + (40,'SIEM',25200,18), + (41,'Vulnerability Scanning',7600,18), + (42,'Vendor Support Contract',37800,19), + (43,'Circuits / Bandwidth',31500,20), + (44,'Hardware Refresh',15100,20), + (45,'Compute (VMs)',54400,21), + (46,'Storage',24500,21), + (47,'Networking / Egress',12200,21), + (48,'Productivity Suite',29900,22), + (49,'Design Tools',10900,22), + (50,'Endpoint Protection',20400,23), + (51,'SIEM',27200,23), + (52,'Vulnerability Scanning',8200,23), + (53,'Vendor Support Contract',40800,24), + (54,'Circuits / Bandwidth',34000,25), + (55,'Hardware Refresh',16300,25), + (56,'Compute (VMs)',48000,26), + (57,'Storage',21600,26), + (58,'Networking / Egress',10800,26), + (59,'Productivity Suite',26400,27), + (60,'Design Tools',9600,27), + (61,'Endpoint Protection',18000,28), + (62,'SIEM',24000,28), + (63,'Vulnerability Scanning',7200,28), + (64,'Vendor Support Contract',36000,29), + (65,'Circuits / Bandwidth',30000,30), + (66,'Hardware Refresh',14400,30), + (67,'Compute (VMs)',51800,31), + (68,'Storage',23300,31), + (69,'Networking / Egress',11700,31), + (70,'Productivity Suite',28500,32), + (71,'Design Tools',10400,32), + (72,'Endpoint Protection',19400,33), + (73,'SIEM',25900,33), + (74,'Vulnerability Scanning',7800,33), + (75,'Vendor Support Contract',38900,34), + (76,'Circuits / Bandwidth',32400,35), + (77,'Hardware Refresh',15600,35), + (78,'Compute (VMs)',56000,36), + (79,'Storage',25200,36), + (80,'Networking / Egress',12600,36), + (81,'Productivity Suite',30800,37), + (82,'Design Tools',11200,37), + (83,'Endpoint Protection',21000,38), + (84,'SIEM',28000,38), + (85,'Vulnerability Scanning',8400,38), + (86,'Vendor Support Contract',42000,39), + (87,'Circuits / Bandwidth',35000,40), + (88,'Hardware Refresh',16800,40), + (89,'Compute (VMs)',60500,41), + (90,'Storage',27200,41), + (91,'Networking / Egress',13600,41), + (92,'Productivity Suite',33300,42), + (93,'Design Tools',12100,42), + (94,'Endpoint Protection',22700,43), + (95,'SIEM',30200,43), + (96,'Vulnerability Scanning',9100,43), + (97,'Vendor Support Contract',45300,44), + (98,'Circuits / Bandwidth',37800,45), + (99,'Hardware Refresh',18100,45), + (100,'Compute (VMs)',65300,46), + (101,'Storage',29400,46), + (102,'Networking / Egress',14700,46), + (103,'Productivity Suite',35900,47), + (104,'Design Tools',13100,47), + (105,'Endpoint Protection',24500,48), + (106,'SIEM',32700,48), + (107,'Vulnerability Scanning',9800,48), + (108,'Vendor Support Contract',49000,49), + (109,'Circuits / Bandwidth',40800,50), + (110,'Hardware Refresh',19600,50), + (111,'Compute (VMs)',56000,51), + (112,'Storage',25200,51), + (113,'Networking / Egress',12600,51), + (114,'Productivity Suite',30800,52), + (115,'Design Tools',11200,52), + (116,'Endpoint Protection',21000,53), + (117,'SIEM',28000,53), + (118,'Vulnerability Scanning',8400,53), + (119,'Vendor Support Contract',42000,54), + (120,'Circuits / Bandwidth',35000,55), + (121,'Hardware Refresh',16800,55), + (122,'Compute (VMs)',60500,56), + (123,'Storage',27200,56), + (124,'Networking / Egress',13600,56), + (125,'Productivity Suite',33300,57), + (126,'Design Tools',12100,57), + (127,'Endpoint Protection',22700,58), + (128,'SIEM',30200,58), + (129,'Vulnerability Scanning',9100,58), + (130,'Vendor Support Contract',45400,59), + (131,'Circuits / Bandwidth',37800,60), + (132,'Hardware Refresh',18100,60), + (133,'Compute (VMs)',65300,61), + (134,'Storage',29400,61), + (135,'Networking / Egress',14700,61), + (136,'Productivity Suite',35900,62), + (137,'Design Tools',13100,62), + (138,'Endpoint Protection',24500,63), + (139,'SIEM',32700,63), + (140,'Vulnerability Scanning',9800,63), + (141,'Vendor Support Contract',49000,64), + (142,'Circuits / Bandwidth',40800,65), + (143,'Hardware Refresh',19600,65), + (144,'Compute (VMs)',70500,66), + (145,'Storage',31700,66), + (146,'Networking / Egress',15900,66), + (147,'Productivity Suite',38800,67), + (148,'Design Tools',14100,67), + (149,'Endpoint Protection',26500,68), + (150,'SIEM',35300,68), + (151,'Vulnerability Scanning',10600,68), + (152,'Vendor Support Contract',52900,69), + (153,'Circuits / Bandwidth',44100,70), + (154,'Hardware Refresh',21200,70), + (155,'Compute (VMs)',76200,71), + (156,'Storage',34300,71), + (157,'Networking / Egress',17100,71), + (158,'Productivity Suite',41900,72), + (159,'Design Tools',15200,72), + (160,'Endpoint Protection',28600,73), + (161,'SIEM',38100,73), + (162,'Vulnerability Scanning',11400,73), + (163,'Vendor Support Contract',57100,74), + (164,'Circuits / Bandwidth',47600,75), + (165,'Hardware Refresh',22900,75), + (166,'Compute (VMs)',28000,76), + (167,'Storage',12600,76), + (168,'Networking / Egress',6300,76), + (169,'Productivity Suite',15400,77), + (170,'Design Tools',5600,77), + (171,'Endpoint Protection',10500,78), + (172,'SIEM',14000,78), + (173,'Vulnerability Scanning',4200,78), + (174,'Vendor Support Contract',21000,79), + (175,'Circuits / Bandwidth',17500,80), + (176,'Hardware Refresh',8400,80), + (177,'Compute (VMs)',30200,81), + (178,'Storage',13600,81), + (179,'Networking / Egress',6800,81), + (180,'Productivity Suite',16600,82), + (181,'Design Tools',6000,82), + (182,'Endpoint Protection',11300,83), + (183,'SIEM',15100,83), + (184,'Vulnerability Scanning',4500,83), + (185,'Vendor Support Contract',22700,84), + (186,'Circuits / Bandwidth',18900,85), + (187,'Hardware Refresh',9100,85), + (188,'Compute (VMs)',32700,86), + (189,'Storage',14700,86), + (190,'Networking / Egress',7300,86), + (191,'Productivity Suite',18000,87), + (192,'Design Tools',6500,87), + (193,'Endpoint Protection',12200,88), + (194,'SIEM',16300,88), + (195,'Vulnerability Scanning',4900,88), + (196,'Vendor Support Contract',24500,89), + (197,'Circuits / Bandwidth',20400,90), + (198,'Hardware Refresh',9800,90), + (199,'Compute (VMs)',35300,91), + (200,'Storage',15900,91), + (201,'Networking / Egress',7900,91), + (202,'Productivity Suite',19400,92), + (203,'Design Tools',7100,92), + (204,'Endpoint Protection',13200,93), + (205,'SIEM',17600,93), + (206,'Vulnerability Scanning',5300,93), + (207,'Vendor Support Contract',26500,94), + (208,'Circuits / Bandwidth',22000,95), + (209,'Hardware Refresh',10600,95), + (210,'Compute (VMs)',38100,96), + (211,'Storage',17100,96), + (212,'Networking / Egress',8600,96), + (213,'Productivity Suite',21000,97), + (214,'Design Tools',7600,97), + (215,'Endpoint Protection',14300,98), + (216,'SIEM',19000,98), + (217,'Vulnerability Scanning',5700,98), + (218,'Vendor Support Contract',28600,99), + (219,'Circuits / Bandwidth',23800,100), + (220,'Hardware Refresh',11400,100), + (221,'Compute (VMs)',36000,101), + (222,'Storage',16200,101), + (223,'Networking / Egress',8100,101), + (224,'Productivity Suite',19800,102), + (225,'Design Tools',7200,102), + (226,'Endpoint Protection',13500,103), + (227,'SIEM',18000,103), + (228,'Vulnerability Scanning',5400,103), + (229,'Vendor Support Contract',27000,104), + (230,'Circuits / Bandwidth',22500,105), + (231,'Hardware Refresh',10800,105), + (232,'Compute (VMs)',38900,106), + (233,'Storage',17500,106), + (234,'Networking / Egress',8700,106), + (235,'Productivity Suite',21400,107), + (236,'Design Tools',7800,107), + (237,'Endpoint Protection',14600,108), + (238,'SIEM',19400,108), + (239,'Vulnerability Scanning',5800,108), + (240,'Vendor Support Contract',29200,109), + (241,'Circuits / Bandwidth',24300,110), + (242,'Hardware Refresh',11700,110), + (243,'Compute (VMs)',42000,111), + (244,'Storage',18900,111), + (245,'Networking / Egress',9400,111), + (246,'Productivity Suite',23100,112), + (247,'Design Tools',8400,112), + (248,'Endpoint Protection',15700,113), + (249,'SIEM',21000,113), + (250,'Vulnerability Scanning',6300,113), + (251,'Vendor Support Contract',31500,114), + (252,'Circuits / Bandwidth',26200,115), + (253,'Hardware Refresh',12600,115), + (254,'Compute (VMs)',45300,116), + (255,'Storage',20400,116), + (256,'Networking / Egress',10200,116), + (257,'Productivity Suite',24900,117), + (258,'Design Tools',9100,117), + (259,'Endpoint Protection',17000,118), + (260,'SIEM',22700,118), + (261,'Vulnerability Scanning',6800,118), + (262,'Vendor Support Contract',34000,119), + (263,'Circuits / Bandwidth',28300,120), + (264,'Hardware Refresh',13600,120), + (265,'Compute (VMs)',49000,121), + (266,'Storage',22000,121), + (267,'Networking / Egress',11000,121), + (268,'Productivity Suite',26900,122), + (269,'Design Tools',9800,122), + (270,'Endpoint Protection',18400,123), + (271,'SIEM',24500,123), + (272,'Vulnerability Scanning',7300,123), + (273,'Vendor Support Contract',36700,124), + (274,'Circuits / Bandwidth',30600,125), + (275,'Hardware Refresh',14700,125); + +INSERT INTO `TrendAiPercentage` (`id`,`region`,`year`,`percentage`) VALUES + (1,'AMEA IT',2022,8), + (2,'AMEA IT',2023,13), + (3,'AMEA IT',2024,18), + (4,'AMEA IT',2025,23), + (5,'AMEA IT',2026,28), + (6,'EMEA IT',2022,10), + (7,'EMEA IT',2023,15), + (8,'EMEA IT',2024,20), + (9,'EMEA IT',2025,25), + (10,'EMEA IT',2026,30), + (11,'NABU IT',2022,12), + (12,'NABU IT',2023,18), + (13,'NABU IT',2024,24), + (14,'NABU IT',2025,30), + (15,'NABU IT',2026,36), + (16,'PH IT',2022,6), + (17,'PH IT',2023,10), + (18,'PH IT',2024,14), + (19,'PH IT',2025,18), + (20,'PH IT',2026,22), + (21,'JP IT',2022,15), + (22,'JP IT',2023,19), + (23,'JP IT',2024,23), + (24,'JP IT',2025,27), + (25,'JP IT',2026,31); + +ALTER TABLE `CostItem` AUTO_INCREMENT = 126; +ALTER TABLE `SubCostItem` AUTO_INCREMENT = 276; +ALTER TABLE `TrendAiPercentage` AUTO_INCREMENT = 26; + +SET FOREIGN_KEY_CHECKS=1; diff --git a/src/app/layout.tsx b/src/app/layout.tsx index 9f4a200..01a2108 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -2,7 +2,9 @@ import type { Metadata } from "next"; import "./globals.css"; import TopNav from "@/components/TopNav"; import Sidebar from "@/components/Sidebar"; -import { auth } from "@/auth"; +// --- SSO DISABLED FOR CICD TEST --- +// import { auth } from "@/auth"; +// --- END SSO DISABLED --- export const metadata: Metadata = { title: "Global IT Cost Dashboard", @@ -14,19 +16,25 @@ export default async function RootLayout({ }: { children: React.ReactNode; }) { - const session = await auth(); + // --- SSO DISABLED FOR CICD TEST --- + // const session = await auth(); + // + // // Unauthenticated (e.g. the /login page) -> render a bare shell with no + // // sidebar/topnav so the sign-in screen shows on its own. + // if (!session?.user) { + // return ( + // + // {children} + // + // ); + // } + // + // const isAdmin = session.user.role === "admin"; - // Unauthenticated (e.g. the /login page) -> render a bare shell with no - // sidebar/topnav so the sign-in screen shows on its own. - if (!session?.user) { - return ( - - {children} - - ); - } - - const isAdmin = session.user.role === "admin"; + // Hardcoded so the sidebar/topnav still render — auth() would return null + // with SSO off and the whole UI chrome would vanish. + const isAdmin = true; + // --- END SSO DISABLED --- return ( diff --git a/src/app/login/page.tsx b/src/app/login/page.tsx index 248ca98..445c6e7 100644 --- a/src/app/login/page.tsx +++ b/src/app/login/page.tsx @@ -14,11 +14,13 @@ function errorMessage(code: string | undefined): string | null { } } +// --- SSO DISABLED FOR CICD TEST --- // Server action: kick off the Microsoft SSO flow. -async function microsoftLogin() { - "use server"; - await signIn("microsoft-entra-id", { redirectTo: "/" }); -} +// async function microsoftLogin() { +// "use server"; +// await signIn("microsoft-entra-id", { redirectTo: "/" }); +// } +// --- END SSO DISABLED --- // Server action: local username/password login. async function credentialsLogin(formData: FormData) { @@ -63,6 +65,7 @@ export default async function LoginPage({ )} + {/* --- SSO DISABLED FOR CICD TEST ---
+
+ +
{ "use server"; - await signOut({ redirectTo: "/" }); + await signIn("microsoft-entra-id"); }} >
- - ) : ( -
{ - "use server"; - await signIn("microsoft-entra-id"); - }} - > - -
- )} + --- END SSO DISABLED --- */} +
+ {user.name} +
); } diff --git a/src/middleware.ts b/src/middleware.ts index b1f2b0e..aeb0757 100644 --- a/src/middleware.ts +++ b/src/middleware.ts @@ -1,14 +1,18 @@ -import NextAuth from "next-auth"; -import { authConfig } from "@/auth.config"; +// --- SSO DISABLED FOR CICD TEST --- +// Original: protect the whole app with role-aware auth in the edge runtime. +// import NextAuth from "next-auth"; +// import { authConfig } from "@/auth.config"; +// +// export const { auth: middleware } = NextAuth(authConfig); -// Protect the whole app with role-aware auth. Runs in the edge runtime, so it -// uses the edge-safe authConfig (no node:fs / providers). The `authorized` -// callback there redirects unauthenticated users to /login and blocks normal -// users from admin pages / write APIs. -export const { auth: middleware } = NextAuth(authConfig); +// No-op replacement. The EMPTY MATCHER below is the actual kill switch — this +// function is never invoked, and every route (including the three admin pages) +// is open. +export function middleware() {} export const config = { - // Run on everything EXCEPT: the auth endpoints (must stay public so users can - // sign in), Next.js internals, and static asset requests (files with a dot). - matcher: ["/((?!api/auth|_next/static|_next/image|favicon.ico|.*\\.).*)"], + // Original matcher (restore with the lines above): + // matcher: ["/((?!api/auth|_next/static|_next/image|favicon.ico|.*\\.).*)"], + matcher: [], }; +// --- END SSO DISABLED --- From c38b41c6fde02dce7e0266e8154182af4801e720 Mon Sep 17 00:00:00 2001 From: s871077 Date: Fri, 11 Sep 2026 11:59:49 +0800 Subject: [PATCH 02/12] update runner --- .github/workflows/cicd.yaml | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/.github/workflows/cicd.yaml b/.github/workflows/cicd.yaml index 93d56ef..6c634f8 100644 --- a/.github/workflows/cicd.yaml +++ b/.github/workflows/cicd.yaml @@ -9,7 +9,10 @@ on: jobs: setup: - runs-on: ubuntu-latest + runs-on: + group: trend-emu-intranet + labels: + - "ubuntu-latest-intranet" outputs: matrix: ${{ steps.pick.outputs.matrix }} steps: @@ -25,8 +28,10 @@ jobs: build-and-deploy: needs: setup - runs-on: ubuntu-latest - + runs-on: + group: trend-emu-intranet + labels: + - "ubuntu-latest-intranet" strategy: matrix: ${{ fromJSON(needs.setup.outputs.matrix) }} From 067a627959e51c2e83c6c29f52ecd54990133de7 Mon Sep 17 00:00:00 2001 From: s871077 Date: Wed, 16 Sep 2026 16:08:30 +0800 Subject: [PATCH 03/12] add network debug in cicd.yaml --- .github/workflows/cicd.yaml | 67 +++++++++++++++++++++++++++++++++++++ .gitignore | 1 + 2 files changed, 68 insertions(+) diff --git a/.github/workflows/cicd.yaml b/.github/workflows/cicd.yaml index 6c634f8..eff9ae1 100644 --- a/.github/workflows/cicd.yaml +++ b/.github/workflows/cicd.yaml @@ -72,6 +72,73 @@ jobs: echo "${{ secrets.KUBE_CONFIG_DATA }}" | base64 -d > "${RUNNER_TEMP}/kubeconfig" chmod 600 "${RUNNER_TEMP}/kubeconfig" + # Temporary debug step: we cannot shell into this self-hosted runner + # directly, so this proves (or disproves) network reachability to the + # k8s API from inside the runner itself, ahead of the image build/push + # so we fail fast instead of waiting ~10 min for the helm timeout. + # Remove once the ACL/connectivity issue is confirmed fixed. + - name: "[DEBUG] Network path to k8s API (6443)" + run: | + set +e + echo "===== Runner identity / network info =====" + hostname -f 2>/dev/null || hostname + echo "--- Interfaces ---" + ip -brief addr show 2>/dev/null || ifconfig + echo "--- Default route ---" + ip route show 2>/dev/null || route -n + + echo + echo "===== K8s API endpoint (parsed from kubeconfig) =====" + KUBE_HOST=$(grep -m1 'server:' "${KUBECONFIG}" | sed -E 's#.*https?://([^:/]+).*#\1#') + KUBE_PORT=$(grep -m1 'server:' "${KUBECONFIG}" | sed -E 's#.*:([0-9]+)/?.*#\1#') + KUBE_PORT="${KUBE_PORT:-6443}" + echo "Host: ${KUBE_HOST}" + echo "Port: ${KUBE_PORT}" + + echo + echo "===== DNS resolution =====" + getent hosts "${KUBE_HOST}" || nslookup "${KUBE_HOST}" || dig +short "${KUBE_HOST}" + + RESOLVED_IPS=$(getent hosts "${KUBE_HOST}" | awk '{print $1}') + + echo + echo "===== Route to each resolved IP =====" + for ip in ${RESOLVED_IPS}; do + echo "-- ip route get ${ip} --" + ip route get "${ip}" 2>/dev/null || echo "(ip route not available)" + done + + echo + echo "===== TCP connect test per resolved IP (port ${KUBE_PORT}) =====" + for ip in ${RESOLVED_IPS}; do + if timeout 5 bash -c "cat < /dev/null > /dev/tcp/${ip}/${KUBE_PORT}" 2>/dev/null; then + echo "OK ${ip}:${KUBE_PORT} - TCP connect succeeded" + else + echo "FAIL ${ip}:${KUBE_PORT} - TCP connect timed out or refused" + fi + done + + echo + echo "===== TCP connect test via hostname (through NLB, port ${KUBE_PORT}) =====" + if timeout 5 bash -c "cat < /dev/null > /dev/tcp/${KUBE_HOST}/${KUBE_PORT}" 2>/dev/null; then + echo "OK ${KUBE_HOST}:${KUBE_PORT} - TCP connect succeeded" + else + echo "FAIL ${KUBE_HOST}:${KUBE_PORT} - TCP connect timed out or refused" + fi + + echo + echo "===== curl -v (expect HTTP 401/403 = reachable; a hang/timeout = blocked) =====" + curl -v -k --max-time 8 "https://${KUBE_HOST}:${KUBE_PORT}/version" + + echo + echo "===== traceroute (best effort, may be blocked itself) =====" + if command -v traceroute >/dev/null 2>&1; then + traceroute -T -p "${KUBE_PORT}" -w 2 -m 15 "${KUBE_HOST}" || true + else + echo "traceroute not installed on runner, skipping" + fi + set -e + - name: Login to JFrog run: | # JFROG_REGISTRY is host/repo but `docker login` takes only the host. diff --git a/.gitignore b/.gitignore index 8f42642..7a6bbd4 100644 --- a/.gitignore +++ b/.gitignore @@ -21,6 +21,7 @@ yarn-error.log* # local env files .env*.local +.env.production.example # production env (contains real RDS credentials) - use .env.production.example as template .env.production From a80878c2d738346cbf18f9f8a273351ea3c7e7c0 Mon Sep 17 00:00:00 2001 From: s871077 Date: Wed, 16 Sep 2026 17:35:10 +0800 Subject: [PATCH 04/12] Remove .env.production.example from repository --- .env.production.example | 38 -------------------------------------- 1 file changed, 38 deletions(-) delete mode 100644 .env.production.example diff --git a/.env.production.example b/.env.production.example deleted file mode 100644 index cbc6531..0000000 --- a/.env.production.example +++ /dev/null @@ -1,38 +0,0 @@ -# Production environment template (AWS RDS MySQL). -# Copy to .env.production on the EC2 host and fill in the real credentials. -# The real .env.production is gitignored so secrets never land in git. -# -# For Prisma CLI commands (migrate/seed), export these first: -# set -a && source .env.production && set +a -# -# Note: if the DB password contains URL-reserved characters, percent-encode them -# (e.g. "@" -> %40, "/" -> %2F, ":" -> %3A). -DATABASE_URL="mysql://USER:PASSWORD@it-cost-prod-db.c8hgbsblyypx.us-west-2.rds.amazonaws.com:3306/it_cost_dashboard" -DATABASE_PROVIDER="mysql" -NODE_ENV="production" - -# --- Microsoft Entra ID (Azure AD) SSO --- -# Next.js does NOT load .env.local in production, so prod auth vars MUST live here. -# Register the prod redirect URI in Azure: -# https:///api/auth/callback/microsoft-entra-id -AUTH_MICROSOFT_ENTRA_ID_ID="" -AUTH_MICROSOFT_ENTRA_ID_SECRET="" -AUTH_MICROSOFT_ENTRA_ID_ISSUER="https://login.microsoftonline.com//v2.0" -# 32-byte random string used to sign session cookies (generate: npx auth secret). -AUTH_SECRET="" -# Canonical public URL of the app. If TLS is terminated by a proxy/ALB in front -# of the app, set AUTH_TRUST_HOST=true instead of (or in addition to) AUTH_URL. -AUTH_URL="https://" -# AUTH_TRUST_HOST=true - -# --- Local break-glass admin + role model --- -# In addition to SSO, /login offers a username/password form for a local admin. -# A NON-EMPTY password ENABLES it; leave empty to disable local login entirely. -# This account always has the admin role and bypasses config/users.json (so you -# can still get in to fix a broken/empty allowlist). -LOCAL_ADMIN_USERNAME="admin" -LOCAL_ADMIN_PASSWORD="" - -# Role-based access is driven by the committed, hand-edited allowlist -# config/users.json (email -> "admin" | "user"). SSO emails NOT listed there -# cannot sign in (fail closed). Edit that file and re-login / restart to apply. From 06ed47f8cf00bdd486fbc51479d1b698d6b28180 Mon Sep 17 00:00:00 2001 From: s871077 Date: Fri, 18 Sep 2026 14:03:29 +0800 Subject: [PATCH 05/12] test --- .gitignore | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.gitignore b/.gitignore index 7a6bbd4..b5e593f 100644 --- a/.gitignore +++ b/.gitignore @@ -33,3 +33,5 @@ next-env.d.ts # prisma / sqlite /prisma/dev.db /prisma/dev.db-journal + +# test \ No newline at end of file From 9ce5bf8752132c8c170bdc20a019d14e6da1e0bc Mon Sep 17 00:00:00 2001 From: s871077 Date: Fri, 18 Sep 2026 17:19:37 +0800 Subject: [PATCH 06/12] test --- .github/workflows/cicd.yaml | 4 ++-- README.md | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/workflows/cicd.yaml b/.github/workflows/cicd.yaml index eff9ae1..3786e53 100644 --- a/.github/workflows/cicd.yaml +++ b/.github/workflows/cicd.yaml @@ -254,7 +254,7 @@ jobs: --set db.image.repository="${JFROG_REGISTRY}/${{ matrix.image_name_db }}" \ --set db.image.tag="${{ github.sha }}" \ --set-string secrets.authSecret="${{ secrets.AUTH_SECRET_DEV }}" \ - --set-string secrets.dbRootPassword="${{ secrets.DB_ROOT_PASSWORD_DEV }}" \ + --set-string secrets.dbRootPassword="${{ secrets.DB_PASSWORD_DEV }}" \ --set-string secrets.localAdminPassword="${{ secrets.LOCAL_ADMIN_PASSWORD_DEV }}" \ --wait --timeout 10m --atomic --debug @@ -279,7 +279,7 @@ jobs: --set db.image.repository="${JFROG_REGISTRY}/${{ matrix.image_name_db }}" \ --set db.image.tag="${TAG}" \ --set-string secrets.authSecret="${{ secrets.AUTH_SECRET_PROD }}" \ - --set-string secrets.dbRootPassword="${{ secrets.DB_ROOT_PASSWORD_PROD }}" \ + --set-string secrets.dbRootPassword="${{ secrets.DB_PASSWORD_PROD }}" \ --set-string secrets.localAdminPassword="${{ secrets.LOCAL_ADMIN_PASSWORD_PROD }}" \ --wait --timeout 10m --atomic --debug diff --git a/README.md b/README.md index 6011c63..bf7f9b7 100644 --- a/README.md +++ b/README.md @@ -1 +1,2 @@ Using the figma-console MCP tools, on the currently open Figma file (page "main") +test01 From a1cc1962a04ccf1ab974e1c571af1d05b9df1c6c Mon Sep 17 00:00:00 2001 From: s871077 Date: Mon, 21 Sep 2026 11:46:31 +0800 Subject: [PATCH 07/12] test --- .github/workflows/cicd.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/cicd.yaml b/.github/workflows/cicd.yaml index 3786e53..1ca163b 100644 --- a/.github/workflows/cicd.yaml +++ b/.github/workflows/cicd.yaml @@ -256,7 +256,7 @@ jobs: --set-string secrets.authSecret="${{ secrets.AUTH_SECRET_DEV }}" \ --set-string secrets.dbRootPassword="${{ secrets.DB_PASSWORD_DEV }}" \ --set-string secrets.localAdminPassword="${{ secrets.LOCAL_ADMIN_PASSWORD_DEV }}" \ - --wait --timeout 10m --atomic --debug + --wait --timeout 10m --debug # ---- PROD DEPLOY (tag push only) ---- - name: Deploy PROD with Helm From b30ca767a7de9294ed2c96144d2dd505110509da Mon Sep 17 00:00:00 2001 From: s871077 Date: Mon, 21 Sep 2026 15:19:36 +0800 Subject: [PATCH 08/12] test --- .github/workflows/cicd.yaml | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/.github/workflows/cicd.yaml b/.github/workflows/cicd.yaml index 1ca163b..3c247d9 100644 --- a/.github/workflows/cicd.yaml +++ b/.github/workflows/cicd.yaml @@ -236,6 +236,15 @@ jobs: kubectl create namespace "${{ matrix.namespace }}" \ --dry-run=client -o yaml | kubectl apply -f - + - name: Ensure JFrog pull secret exists + run: | + kubectl create secret docker-registry jfrog-registry-creds \ + --docker-server="$(echo "${JFROG_REGISTRY}" | cut -d'/' -f1)" \ + --docker-username="${{ secrets.JFROG_USERNAME }}" \ + --docker-password="${{ secrets.JFROG_IDENTITY_TOKEN }}" \ + --namespace "${{ matrix.namespace }}" \ + --dry-run=client -o yaml | kubectl apply -f - + # ---- DEV DEPLOY (branch dev only) ---- # Deployed by commit SHA, not latest-dev: an immutable tag sidesteps the # moving-tag + IfNotPresent stale-cache trap and makes `kubectl describe From d4241b6cd5beb647829c4899ca9fb534947aa062 Mon Sep 17 00:00:00 2001 From: s871077 Date: Mon, 21 Sep 2026 15:42:43 +0800 Subject: [PATCH 09/12] test --- .github/workflows/cicd.yaml | 2 +- helm/values-dev.yaml | 2 +- helm/values-prod.yaml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/cicd.yaml b/.github/workflows/cicd.yaml index 3c247d9..2251bb4 100644 --- a/.github/workflows/cicd.yaml +++ b/.github/workflows/cicd.yaml @@ -265,7 +265,7 @@ jobs: --set-string secrets.authSecret="${{ secrets.AUTH_SECRET_DEV }}" \ --set-string secrets.dbRootPassword="${{ secrets.DB_PASSWORD_DEV }}" \ --set-string secrets.localAdminPassword="${{ secrets.LOCAL_ADMIN_PASSWORD_DEV }}" \ - --wait --timeout 10m --debug + --wait --timeout 10m --atomic --debug # ---- PROD DEPLOY (tag push only) ---- - name: Deploy PROD with Helm diff --git a/helm/values-dev.yaml b/helm/values-dev.yaml index 3570965..6fd2abb 100644 --- a/helm/values-dev.yaml +++ b/helm/values-dev.yaml @@ -31,4 +31,4 @@ ingress: enabled: true className: nginx # TODO: point this at a hostname resolving to the ingress-nginx external IP. - host: it-cost-dashboard-dev.example.com + host: it-cost-dashboard-dev.trendmicro.com diff --git a/helm/values-prod.yaml b/helm/values-prod.yaml index f1b0c0d..976cde9 100644 --- a/helm/values-prod.yaml +++ b/helm/values-prod.yaml @@ -31,4 +31,4 @@ ingress: enabled: true className: nginx # TODO: point this at a hostname resolving to the ingress-nginx external IP. - host: it-cost-dashboard.example.com + host: it-cost-dashboard.trendmicro.com From 137a4a2a399ecd320840472e3076d2c381f50da3 Mon Sep 17 00:00:00 2001 From: s871077 Date: Mon, 21 Sep 2026 16:37:26 +0800 Subject: [PATCH 10/12] test --- helm/templates/server-ingress.yaml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/helm/templates/server-ingress.yaml b/helm/templates/server-ingress.yaml index 12ccb32..a28b15e 100644 --- a/helm/templates/server-ingress.yaml +++ b/helm/templates/server-ingress.yaml @@ -7,9 +7,13 @@ metadata: {{- include "it-cost-dashboard.componentLabels" (dict "ctx" . "component" "server") | nindent 4 }} annotations: nginx.ingress.kubernetes.io/proxy-body-size: "10m" + cert-manager.io/cluster-issuer: sectigo-acme spec: ingressClassName: {{ .Values.ingress.className }} - # HTTP only for now — no TLS block until certs are issued for these hosts. + tls: + - hosts: + - {{ .Values.ingress.host | quote }} + secretName: {{ include "it-cost-dashboard.fullname" . }}-server-tls rules: - host: {{ required "ingress.host is required" .Values.ingress.host | quote }} http: From 167eb0807d80c4d8d997273a2c3f32cc8a69d56b Mon Sep 17 00:00:00 2001 From: s871077 Date: Mon, 21 Sep 2026 18:42:32 +0800 Subject: [PATCH 11/12] turn on SSO --- .claude/settings.local.json | 3 +- .github/workflows/cicd.yaml | 6 +++ helm/templates/server-deployment.yaml | 10 ++--- helm/templates/server-secret.yaml | 18 ++++---- helm/values-prod.yaml | 2 +- helm/values.yaml | 12 +++--- src/app/api/health/route.ts | 18 ++++++++ src/app/layout.tsx | 34 ++++++--------- src/app/login/page.tsx | 12 ++---- src/auth.config.ts | 4 +- src/components/TopNav.tsx | 60 +++++++++++---------------- src/middleware.ts | 20 +++------ 12 files changed, 97 insertions(+), 102 deletions(-) create mode 100644 src/app/api/health/route.ts diff --git a/.claude/settings.local.json b/.claude/settings.local.json index 8edf04b..c146b54 100644 --- a/.claude/settings.local.json +++ b/.claude/settings.local.json @@ -31,7 +31,8 @@ "Bash(git:*)", "Bash(/tmp/windows-amd64/helm.exe template:*)", "Bash(echo \"exit=$?\")", - "Read(//tmp/**)" + "Read(//tmp/**)", + "Bash(tail:*)" ] } } diff --git a/.github/workflows/cicd.yaml b/.github/workflows/cicd.yaml index 2251bb4..a7193a1 100644 --- a/.github/workflows/cicd.yaml +++ b/.github/workflows/cicd.yaml @@ -265,6 +265,9 @@ jobs: --set-string secrets.authSecret="${{ secrets.AUTH_SECRET_DEV }}" \ --set-string secrets.dbRootPassword="${{ secrets.DB_PASSWORD_DEV }}" \ --set-string secrets.localAdminPassword="${{ secrets.LOCAL_ADMIN_PASSWORD_DEV }}" \ + --set-string secrets.entraClientId="${{ secrets.ENTRA_CLIENT_ID_DEV }}" \ + --set-string secrets.entraClientSecret="${{ secrets.ENTRA_CLIENT_SECRET_DEV }}" \ + --set-string secrets.entraIssuer="${{ secrets.ENTRA_ISSUER_DEV }}" \ --wait --timeout 10m --atomic --debug # ---- PROD DEPLOY (tag push only) ---- @@ -290,6 +293,9 @@ jobs: --set-string secrets.authSecret="${{ secrets.AUTH_SECRET_PROD }}" \ --set-string secrets.dbRootPassword="${{ secrets.DB_PASSWORD_PROD }}" \ --set-string secrets.localAdminPassword="${{ secrets.LOCAL_ADMIN_PASSWORD_PROD }}" \ + --set-string secrets.entraClientId="${{ secrets.ENTRA_CLIENT_ID_PROD }}" \ + --set-string secrets.entraClientSecret="${{ secrets.ENTRA_CLIENT_SECRET_PROD }}" \ + --set-string secrets.entraIssuer="${{ secrets.ENTRA_ISSUER_PROD }}" \ --wait --timeout 10m --atomic --debug # Strictly redundant with immutable image tags: Helm already rolled the diff --git a/helm/templates/server-deployment.yaml b/helm/templates/server-deployment.yaml index 85b11f4..d3447f5 100644 --- a/helm/templates/server-deployment.yaml +++ b/helm/templates/server-deployment.yaml @@ -50,13 +50,13 @@ spec: - secretRef: name: {{ include "it-cost-dashboard.fullname" . }}-server-secret # Readiness hits a DB-backed route on purpose: a pod only takes - # traffic once MySQL is reachable AND the schema is right. - # NOTE (SSO restore): /api/years will 307 to /login once the - # middleware is back on, which is non-2xx — add a public /api/health - # route and probe that instead. + # traffic once MySQL is reachable. /api/health is allow-listed in + # src/auth.config.ts, so the middleware lets it through unauthenticated + # instead of 307-ing it to /login (which would be non-2xx and would + # keep the pod permanently unready). readinessProbe: httpGet: - path: /api/years + path: /api/health port: http initialDelaySeconds: 10 periodSeconds: 5 diff --git a/helm/templates/server-secret.yaml b/helm/templates/server-secret.yaml index 49fb01e..d57d4ef 100644 --- a/helm/templates/server-secret.yaml +++ b/helm/templates/server-secret.yaml @@ -18,11 +18,13 @@ stringData: # Break-glass local login. Empty disables it entirely (src/auth.ts fails closed). LOCAL_ADMIN_PASSWORD: {{ .Values.secrets.localAdminPassword | default "" | quote }} - # --- SSO DISABLED FOR CICD TEST --- - # Kept present but optional. To restore SSO: supply these values from the - # per-env GitHub secrets and swap `| default ""` for `| required "..."`. - AUTH_MICROSOFT_ENTRA_ID_ID: {{ .Values.secrets.entraClientId | default "" | quote }} - AUTH_MICROSOFT_ENTRA_ID_SECRET: {{ .Values.secrets.entraClientSecret | default "" | quote }} - AUTH_MICROSOFT_ENTRA_ID_ISSUER: {{ .Values.secrets.entraIssuer | default "" | quote }} - AUTH_URL: {{ .Values.secrets.authUrl | default "" | quote }} - # --- END SSO DISABLED --- + # Microsoft Entra ID SSO. Required: a deploy fails loudly rather than shipping + # a build whose sign-in button 500s. + AUTH_MICROSOFT_ENTRA_ID_ID: {{ required "secrets.entraClientId is required" .Values.secrets.entraClientId | quote }} + AUTH_MICROSOFT_ENTRA_ID_SECRET: {{ required "secrets.entraClientSecret is required" .Values.secrets.entraClientSecret | quote }} + AUTH_MICROSOFT_ENTRA_ID_ISSUER: {{ required "secrets.entraIssuer is required" .Values.secrets.entraIssuer | quote }} + # Derived from the ingress host so the OAuth callback URL always matches what + # is registered in Entra. AUTH_TRUST_HOST alone would leave Auth.js depending + # on X-Forwarded-Proto; if that is ever wrong it builds an http:// callback and + # Entra rejects it with AADSTS50011 (http is invalid for non-localhost). + AUTH_URL: {{ printf "https://%s" (required "ingress.host is required" .Values.ingress.host) | quote }} diff --git a/helm/values-prod.yaml b/helm/values-prod.yaml index 976cde9..4db4e94 100644 --- a/helm/values-prod.yaml +++ b/helm/values-prod.yaml @@ -31,4 +31,4 @@ ingress: enabled: true className: nginx # TODO: point this at a hostname resolving to the ingress-nginx external IP. - host: it-cost-dashboard.trendmicro.com + host: it-cost-dashboard-prod.trendmicro.com diff --git a/helm/values.yaml b/helm/values.yaml index 097252b..6897857 100644 --- a/helm/values.yaml +++ b/helm/values.yaml @@ -50,12 +50,12 @@ secrets: dbRootPassword: "" # from GitHub secret DB_ROOT_PASSWORD_ # Optional; empty disables local login entirely (src/auth.ts fails closed). localAdminPassword: "" - # --- SSO restore: set these (and swap `default ""` for `required` in - # templates/server-secret.yaml) when Entra ID is re-enabled --- - # entraClientId: "" - # entraClientSecret: "" - # entraIssuer: "" - # authUrl: "" + # Microsoft Entra ID SSO. Supplied per-env by the CI workflow from GitHub + # secrets; server-secret.yaml marks them required, so a deploy fails loudly + # rather than shipping a build whose sign-in button 500s. + entraClientId: "" + entraClientSecret: "" + entraIssuer: "" # Pre-created manually, once per namespace (see the deploy notes). Not templated: # the kubelet needs it independently of Helm. diff --git a/src/app/api/health/route.ts b/src/app/api/health/route.ts new file mode 100644 index 0000000..5287f1c --- /dev/null +++ b/src/app/api/health/route.ts @@ -0,0 +1,18 @@ +import { NextResponse } from "next/server"; +import { prisma } from "@/lib/prisma"; + +// Public readiness endpoint (allow-listed in src/auth.config.ts). DB-backed on +// purpose: a pod should only take traffic once MySQL is actually reachable, +// which is what the old /api/years probe gave us before auth was restored. +// force-dynamic keeps Prisma from being invoked during `next build`, which runs +// without a DATABASE_URL in the Dockerfile builder stage. +export const dynamic = "force-dynamic"; + +export async function GET() { + try { + await prisma.$queryRaw`SELECT 1`; + return NextResponse.json({ status: "ok" }); + } catch { + return NextResponse.json({ status: "unavailable" }, { status: 503 }); + } +} diff --git a/src/app/layout.tsx b/src/app/layout.tsx index 01a2108..9f4a200 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -2,9 +2,7 @@ import type { Metadata } from "next"; import "./globals.css"; import TopNav from "@/components/TopNav"; import Sidebar from "@/components/Sidebar"; -// --- SSO DISABLED FOR CICD TEST --- -// import { auth } from "@/auth"; -// --- END SSO DISABLED --- +import { auth } from "@/auth"; export const metadata: Metadata = { title: "Global IT Cost Dashboard", @@ -16,25 +14,19 @@ export default async function RootLayout({ }: { children: React.ReactNode; }) { - // --- SSO DISABLED FOR CICD TEST --- - // const session = await auth(); - // - // // Unauthenticated (e.g. the /login page) -> render a bare shell with no - // // sidebar/topnav so the sign-in screen shows on its own. - // if (!session?.user) { - // return ( - // - // {children} - // - // ); - // } - // - // const isAdmin = session.user.role === "admin"; + const session = await auth(); - // Hardcoded so the sidebar/topnav still render — auth() would return null - // with SSO off and the whole UI chrome would vanish. - const isAdmin = true; - // --- END SSO DISABLED --- + // Unauthenticated (e.g. the /login page) -> render a bare shell with no + // sidebar/topnav so the sign-in screen shows on its own. + if (!session?.user) { + return ( + + {children} + + ); + } + + const isAdmin = session.user.role === "admin"; return ( diff --git a/src/app/login/page.tsx b/src/app/login/page.tsx index 445c6e7..be388e2 100644 --- a/src/app/login/page.tsx +++ b/src/app/login/page.tsx @@ -14,13 +14,11 @@ function errorMessage(code: string | undefined): string | null { } } -// --- SSO DISABLED FOR CICD TEST --- // Server action: kick off the Microsoft SSO flow. -// async function microsoftLogin() { -// "use server"; -// await signIn("microsoft-entra-id", { redirectTo: "/" }); -// } -// --- END SSO DISABLED --- +async function microsoftLogin() { + "use server"; + await signIn("microsoft-entra-id", { redirectTo: "/" }); +} // Server action: local username/password login. async function credentialsLogin(formData: FormData) { @@ -65,7 +63,6 @@ export default async function LoginPage({ )} - {/* --- SSO DISABLED FOR CICD TEST ---
-
- - + {user ? ( +
+ {user.name ?? user.email}
{ "use server"; - await signIn("microsoft-entra-id"); + await signOut({ redirectTo: "/" }); }} >
- --- END SSO DISABLED --- */} -
- {user.name} -
+
+ ) : ( +
{ + "use server"; + await signIn("microsoft-entra-id"); + }} + > + +
+ )} ); } diff --git a/src/middleware.ts b/src/middleware.ts index aeb0757..1a06aa8 100644 --- a/src/middleware.ts +++ b/src/middleware.ts @@ -1,18 +1,10 @@ -// --- SSO DISABLED FOR CICD TEST --- -// Original: protect the whole app with role-aware auth in the edge runtime. -// import NextAuth from "next-auth"; -// import { authConfig } from "@/auth.config"; -// -// export const { auth: middleware } = NextAuth(authConfig); +import NextAuth from "next-auth"; +import { authConfig } from "@/auth.config"; -// No-op replacement. The EMPTY MATCHER below is the actual kill switch — this -// function is never invoked, and every route (including the three admin pages) -// is open. -export function middleware() {} +// Edge-runtime gate for the whole app. Uses the edge-safe config only — +// src/auth.ts pulls in node:fs via lookupRole and must never be imported here. +export const { auth: middleware } = NextAuth(authConfig); export const config = { - // Original matcher (restore with the lines above): - // matcher: ["/((?!api/auth|_next/static|_next/image|favicon.ico|.*\\.).*)"], - matcher: [], + matcher: ["/((?!api/auth|_next/static|_next/image|favicon.ico|.*\\.).*)"], }; -// --- END SSO DISABLED --- From a79a01437ac1eb856efb6213a34a405411bcbfdf Mon Sep 17 00:00:00 2001 From: s871077 Date: Tue, 22 Sep 2026 10:39:17 +0800 Subject: [PATCH 12/12] fix SSO --- .claude/settings.local.json | 4 +++- helm/templates/server-ingress.yaml | 3 +++ src/auth.ts | 12 ++++++++++++ 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/.claude/settings.local.json b/.claude/settings.local.json index c146b54..0affde8 100644 --- a/.claude/settings.local.json +++ b/.claude/settings.local.json @@ -32,7 +32,9 @@ "Bash(/tmp/windows-amd64/helm.exe template:*)", "Bash(echo \"exit=$?\")", "Read(//tmp/**)", - "Bash(tail:*)" + "Bash(tail:*)", + "Bash(mkdir:*)", + "Bash(python3:*)" ] } } diff --git a/helm/templates/server-ingress.yaml b/helm/templates/server-ingress.yaml index a28b15e..4908f73 100644 --- a/helm/templates/server-ingress.yaml +++ b/helm/templates/server-ingress.yaml @@ -7,6 +7,9 @@ metadata: {{- include "it-cost-dashboard.componentLabels" (dict "ctx" . "component" "server") | nindent 4 }} annotations: nginx.ingress.kubernetes.io/proxy-body-size: "10m" + # Headroom for large request headers (chunked Auth.js session cookies). + nginx.ingress.kubernetes.io/proxy-buffer-size: "16k" + nginx.ingress.kubernetes.io/proxy-buffers-number: "4" cert-manager.io/cluster-issuer: sectigo-acme spec: ingressClassName: {{ .Values.ingress.className }} diff --git a/src/auth.ts b/src/auth.ts index 3a087c6..01d1c25 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -20,6 +20,18 @@ export const { handlers, auth, signIn, signOut } = NextAuth({ clientSecret: process.env.AUTH_MICROSOFT_ENTRA_ID_SECRET, // Tenant-specific issuer restricts sign-in to our organization only. issuer: process.env.AUTH_MICROSOFT_ENTRA_ID_ISSUER, + // The provider's default profile() pulls the Graph photo and inlines it as a + // base64 data-URI into user.image -> the `picture` JWT claim. Since sessions + // are JWTs, that becomes a multi-KB chunked session cookie whose combined + // Cookie header overflows nginx's proxy buffer -> 502 before the request ever + // reaches this app. We never render an avatar, so keep the token lean. + authorization: { params: { scope: "openid profile email" } }, + profile: (profile) => ({ + id: profile.sub, + name: profile.name, + email: profile.email, + image: null, + }), }), Credentials({ name: "Local account",