Compare commits
52 Commits
QR_setting
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1c54c1c477 | ||
|
|
8129f85071 | ||
| 933afb02b1 | |||
|
|
87459c8f44 | ||
|
|
4d98d9a48e | ||
|
|
1da75e4abd | ||
|
|
3e26420945 | ||
|
|
8e22c1d713 | ||
|
|
8747b3946f | ||
|
|
ed3d8812c2 | ||
|
|
5588fae6f9 | ||
|
|
e6afe2b6d3 | ||
|
|
9049b60ee5 | ||
|
|
a5c4a15fab | ||
|
|
1ab59bc9e1 | ||
|
|
7389ed2d82 | ||
|
|
a73dd76e70 | ||
|
|
cbfc1bcd1d | ||
|
|
6ed939c6bf | ||
|
|
1ecee53966 | ||
|
|
322a8ae882 | ||
|
|
8176180e52 | ||
|
|
2137ee364c | ||
|
|
afd89322bb | ||
|
|
1457bf277f | ||
| ae1fd4b121 | |||
|
|
577f138533 | ||
|
|
aacd2fe7db | ||
|
|
90403a1acd | ||
|
|
6a76f6968b | ||
|
|
621b05a890 | ||
| 7b631ab858 | |||
| 9735344f37 | |||
| 67e3be028b | |||
| 58f93c959d | |||
| 4231acc691 | |||
| 662f720c6a | |||
| 5678e28c66 | |||
| 15c5cbaca2 | |||
| 84d35c1409 | |||
| 07eb48f27c | |||
| fb45c38107 | |||
| 6c21e4816e | |||
| e208e52ed9 | |||
| 5dbf69e963 | |||
| d771b28d88 | |||
| 6848baae5f | |||
| a0570e88d4 | |||
| 502e5059b7 | |||
| d54997cd55 | |||
| fa8dec1780 | |||
| 9d19d8283e |
13
.dockerignore
Normal file
13
.dockerignore
Normal file
@@ -0,0 +1,13 @@
|
||||
node_modules
|
||||
dist
|
||||
build
|
||||
.git
|
||||
.gitignore
|
||||
.env
|
||||
npm-debug.log
|
||||
uploads
|
||||
*.xlsx
|
||||
*.log
|
||||
mysql_data
|
||||
scratch
|
||||
*.sql
|
||||
6
.env
6
.env
@@ -1,6 +1,6 @@
|
||||
DB_HOST=172.16.8.151
|
||||
DB_HOST=itam-mysql
|
||||
DB_PORT=3306
|
||||
DB_USER=itam_admin
|
||||
DB_USER=itam
|
||||
DB_PASS=itam1234
|
||||
DB_NAME=itam
|
||||
PORT=3001
|
||||
PORT=3000
|
||||
17
.env.example
Normal file
17
.env.example
Normal file
@@ -0,0 +1,17 @@
|
||||
# Database Configuration
|
||||
DB_HOST=172.16.8.151
|
||||
DB_PORT=3306
|
||||
DB_USER=itam_admin
|
||||
DB_PASS=itam1234
|
||||
DB_NAME=itam
|
||||
|
||||
# Application Configuration
|
||||
NODE_ENV=development
|
||||
PORT=3000
|
||||
|
||||
# Logging (optional)
|
||||
LOG_LEVEL=info
|
||||
|
||||
# Security (for production)
|
||||
# API_KEY=your_api_key_here
|
||||
# JWT_SECRET=your_jwt_secret_here
|
||||
7
.gitea/coverage.json
Normal file
7
.gitea/coverage.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"Path": "./backend/coverage.out",
|
||||
"Thresholds": {
|
||||
"baron-sso-backend/internal/handler": 10,
|
||||
"baron-sso-backend/internal/service": 10
|
||||
}
|
||||
}
|
||||
47
.gitea/workflows/itam_code_check.yml
Normal file
47
.gitea/workflows/itam_code_check.yml
Normal file
@@ -0,0 +1,47 @@
|
||||
name: ITAM Code Check
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- Dockerizing
|
||||
- main
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
build-and-config-check:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Prepare CI env file
|
||||
run: |
|
||||
cat <<'EOF' > .env
|
||||
DB_HOST=127.0.0.1
|
||||
DB_PORT=3306
|
||||
DB_USER=itam_ci
|
||||
DB_PASS=itam_ci_password
|
||||
DB_NAME=itam
|
||||
NODE_ENV=production
|
||||
PORT=3000
|
||||
LOG_LEVEL=info
|
||||
EOF
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "20"
|
||||
cache: "npm"
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Frontend TypeScript and Vite build
|
||||
run: npm run build
|
||||
|
||||
- name: Validate test compose
|
||||
run: docker compose -f docker-compose.test.yaml config
|
||||
|
||||
- name: Validate prod compose
|
||||
run: docker compose -f docker-compose.prod.yaml config
|
||||
69
.gitea/workflows/itam_docker_build_check.yml
Normal file
69
.gitea/workflows/itam_docker_build_check.yml
Normal file
@@ -0,0 +1,69 @@
|
||||
name: ITAM Docker Build Check
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- Dockerizing
|
||||
- main
|
||||
paths:
|
||||
- "Dockerfile.frontend.prod"
|
||||
- "Dockerfile.backend.prod"
|
||||
- "docker-compose.prod.yaml"
|
||||
- "docker-compose.test.yaml"
|
||||
- "docker/**"
|
||||
- "src/**"
|
||||
- "server.js"
|
||||
- "package.json"
|
||||
- "package-lock.json"
|
||||
- "vite.config.ts"
|
||||
- "index.html"
|
||||
- "img/**"
|
||||
- "public/**"
|
||||
pull_request:
|
||||
paths:
|
||||
- "Dockerfile.frontend.prod"
|
||||
- "Dockerfile.backend.prod"
|
||||
- "docker-compose.prod.yaml"
|
||||
- "docker-compose.test.yaml"
|
||||
- "docker/**"
|
||||
- "src/**"
|
||||
- "server.js"
|
||||
- "package.json"
|
||||
- "package-lock.json"
|
||||
- "vite.config.ts"
|
||||
- "index.html"
|
||||
- "img/**"
|
||||
- "public/**"
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
docker-build-check:
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
DOCKER_BUILDKIT: "1"
|
||||
COMPOSE_DOCKER_CLI_BUILD: "1"
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Prepare CI env file
|
||||
run: |
|
||||
cat <<'EOF' > .env
|
||||
DB_HOST=127.0.0.1
|
||||
DB_PORT=3306
|
||||
DB_USER=itam_ci
|
||||
DB_PASS=itam_ci_password
|
||||
DB_NAME=itam
|
||||
NODE_ENV=production
|
||||
PORT=3000
|
||||
LOG_LEVEL=info
|
||||
EOF
|
||||
|
||||
- name: Build backend production image
|
||||
run: docker build -f Dockerfile.backend.prod -t itam-backend:ci .
|
||||
|
||||
- name: Build frontend production image
|
||||
run: docker build -f Dockerfile.frontend.prod -t itam-frontend:ci .
|
||||
|
||||
- name: Validate production compose with CI env
|
||||
run: docker compose -f docker-compose.prod.yaml config
|
||||
143
.gitea/workflows/itam_production_deploy.yml
Normal file
143
.gitea/workflows/itam_production_deploy.yml
Normal file
@@ -0,0 +1,143 @@
|
||||
name: ITAM Production Deploy
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
target_branch:
|
||||
description: "Branch to deploy"
|
||||
required: true
|
||||
default: "main"
|
||||
type: string
|
||||
|
||||
jobs:
|
||||
deploy-production:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup SSH agent
|
||||
uses: webfactory/ssh-agent@v0.9.0
|
||||
with:
|
||||
ssh-private-key: ${{ secrets.PROD_SSH_PRIVATE_KEY }}
|
||||
|
||||
- name: Validate required production variables
|
||||
env:
|
||||
PROD_HOST: ${{ vars.PROD_HOST }}
|
||||
PROD_USER: ${{ vars.PROD_USER }}
|
||||
PROD_DEPLOY_PATH: ${{ vars.PROD_DEPLOY_PATH }}
|
||||
PROD_GIT_URL: ${{ vars.PROD_GIT_URL }}
|
||||
DB_HOST: ${{ vars.PROD_DB_HOST }}
|
||||
DB_PORT: ${{ vars.PROD_DB_PORT }}
|
||||
DB_USER: ${{ vars.PROD_DB_USER }}
|
||||
DB_PASS: ${{ secrets.PROD_DB_PASS }}
|
||||
DB_NAME: ${{ vars.PROD_DB_NAME }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
required_keys="PROD_HOST PROD_USER PROD_DEPLOY_PATH PROD_GIT_URL DB_HOST DB_PORT DB_USER DB_PASS DB_NAME"
|
||||
for key in ${required_keys}; do
|
||||
if [ -z "${!key:-}" ]; then
|
||||
echo "::error::Missing required variable or secret: ${key}"
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
- name: Create production env file
|
||||
env:
|
||||
DB_HOST: ${{ vars.PROD_DB_HOST }}
|
||||
DB_PORT: ${{ vars.PROD_DB_PORT }}
|
||||
DB_USER: ${{ vars.PROD_DB_USER }}
|
||||
DB_PASS: ${{ secrets.PROD_DB_PASS }}
|
||||
DB_NAME: ${{ vars.PROD_DB_NAME }}
|
||||
LOG_LEVEL: ${{ vars.PROD_LOG_LEVEL }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
EFFECTIVE_LOG_LEVEL="${LOG_LEVEL:-info}"
|
||||
cat > .env.deploy <<EOF
|
||||
DB_HOST=${DB_HOST}
|
||||
DB_PORT=${DB_PORT}
|
||||
DB_USER=${DB_USER}
|
||||
DB_PASS=${DB_PASS}
|
||||
DB_NAME=${DB_NAME}
|
||||
NODE_ENV=production
|
||||
PORT=3000
|
||||
LOG_LEVEL=${EFFECTIVE_LOG_LEVEL}
|
||||
EOF
|
||||
|
||||
- name: Deploy to production host
|
||||
env:
|
||||
PROD_HOST: ${{ vars.PROD_HOST }}
|
||||
PROD_USER: ${{ vars.PROD_USER }}
|
||||
PROD_DEPLOY_PATH: ${{ vars.PROD_DEPLOY_PATH }}
|
||||
PROD_BACKUP_ROOT: ${{ vars.PROD_BACKUP_ROOT }}
|
||||
PROD_GIT_URL: ${{ vars.PROD_GIT_URL }}
|
||||
DB_HOST: ${{ vars.PROD_DB_HOST }}
|
||||
DB_PORT: ${{ vars.PROD_DB_PORT }}
|
||||
DB_USER: ${{ vars.PROD_DB_USER }}
|
||||
DB_PASS: ${{ secrets.PROD_DB_PASS }}
|
||||
DB_NAME: ${{ vars.PROD_DB_NAME }}
|
||||
TARGET_BRANCH: ${{ github.event.inputs.target_branch }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
ssh-keyscan -H "${PROD_HOST}" >> ~/.ssh/known_hosts
|
||||
|
||||
ssh "${PROD_USER}@${PROD_HOST}" "mkdir -p '${PROD_DEPLOY_PATH}'"
|
||||
|
||||
ssh "${PROD_USER}@${PROD_HOST}" "if [ ! -d '${PROD_DEPLOY_PATH}/.git' ]; then git clone '${PROD_GIT_URL}' '${PROD_DEPLOY_PATH}'; else cd '${PROD_DEPLOY_PATH}' && git remote set-url origin '${PROD_GIT_URL}'; fi"
|
||||
|
||||
ssh "${PROD_USER}@${PROD_HOST}" "cd '${PROD_DEPLOY_PATH}' && git checkout -- .env || true && git fetch origin '${TARGET_BRANCH}' && git checkout -B '${TARGET_BRANCH}' FETCH_HEAD && git reset --hard FETCH_HEAD"
|
||||
|
||||
EFFECTIVE_BACKUP_ROOT="${PROD_BACKUP_ROOT:-/home/user/dachs_backups}"
|
||||
|
||||
ssh "${PROD_USER}@${PROD_HOST}" "export DEPLOY_PATH='${PROD_DEPLOY_PATH}' BACKUP_ROOT='${EFFECTIVE_BACKUP_ROOT}'; sh -eu -s" <<'REMOTE_BACKUP'
|
||||
case "$BACKUP_ROOT" in
|
||||
"$DEPLOY_PATH"|"$DEPLOY_PATH"/*)
|
||||
echo "Backup path must be outside deploy path: $BACKUP_ROOT"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ -d "$DEPLOY_PATH/.git" ]; then
|
||||
mkdir -p "$BACKUP_ROOT"
|
||||
echo "Starting pre-deploy backup..."
|
||||
cd "$DEPLOY_PATH"
|
||||
if [ -f Makefile ] && [ -f scripts/backup.sh ] && [ -f .env ]; then
|
||||
make predeploy-backup ENV_FILE=.env BACKUP_ROOT="$BACKUP_ROOT"
|
||||
else
|
||||
echo "Skipping pre-deploy backup because required backup files are missing in current deployment."
|
||||
fi
|
||||
else
|
||||
echo "Skipping pre-deploy backup because no existing deployment was found."
|
||||
fi
|
||||
REMOTE_BACKUP
|
||||
|
||||
ssh "${PROD_USER}@${PROD_HOST}" "cd '${PROD_DEPLOY_PATH}' && git clean -fd"
|
||||
|
||||
ssh "${PROD_USER}@${PROD_HOST}" "cd '${PROD_DEPLOY_PATH}' && mkdir -p uploads logs/nginx"
|
||||
|
||||
scp .env.deploy "${PROD_USER}@${PROD_HOST}:${PROD_DEPLOY_PATH}/.env"
|
||||
|
||||
ssh "${PROD_USER}@${PROD_HOST}" "cd '${PROD_DEPLOY_PATH}' && chmod 600 .env && docker compose -f docker-compose.prod.yaml config && docker compose -f docker-compose.prod.yaml up -d --build"
|
||||
|
||||
- name: Post-deploy status check
|
||||
env:
|
||||
PROD_HOST: ${{ vars.PROD_HOST }}
|
||||
PROD_USER: ${{ vars.PROD_USER }}
|
||||
PROD_DEPLOY_PATH: ${{ vars.PROD_DEPLOY_PATH }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
ssh "${PROD_USER}@${PROD_HOST}" "cd '${PROD_DEPLOY_PATH}' && docker compose -f docker-compose.prod.yaml ps"
|
||||
|
||||
- name: Post-deploy smoke checks
|
||||
env:
|
||||
PROD_HOST: ${{ vars.PROD_HOST }}
|
||||
PROD_USER: ${{ vars.PROD_USER }}
|
||||
PROD_DEPLOY_PATH: ${{ vars.PROD_DEPLOY_PATH }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
ssh "${PROD_USER}@${PROD_HOST}" "curl -fsS http://localhost:9090/health"
|
||||
ssh "${PROD_USER}@${PROD_HOST}" "cd '${PROD_DEPLOY_PATH}' && docker compose -f docker-compose.prod.yaml exec -T backend curl -fsS http://localhost:3000/health"
|
||||
|
||||
- name: Cleanup generated env file
|
||||
if: ${{ always() }}
|
||||
run: rm -f .env.deploy
|
||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -5,3 +5,5 @@ dist/
|
||||
*.log
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
backups/
|
||||
mysql_data/
|
||||
|
||||
12
Dockerfile.backend
Normal file
12
Dockerfile.backend
Normal file
@@ -0,0 +1,12 @@
|
||||
FROM node:20-alpine
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY package*.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY . .
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
CMD ["npm", "run", "server"]
|
||||
48
Dockerfile.backend.prod
Normal file
48
Dockerfile.backend.prod
Normal file
@@ -0,0 +1,48 @@
|
||||
FROM node:20-alpine
|
||||
|
||||
LABEL maintainer="ITAM Team <devops@itam.local>"
|
||||
|
||||
# Set production environment
|
||||
ENV NODE_ENV=production
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Install curl for health checks and dumb-init for proper signal handling
|
||||
RUN apk add --no-cache curl dumb-init mysql-client
|
||||
|
||||
# Copy package files
|
||||
COPY package*.json ./
|
||||
|
||||
# Install production dependencies only
|
||||
RUN npm ci --only=production
|
||||
|
||||
# Copy application code
|
||||
COPY server.js ./
|
||||
COPY src ./src
|
||||
|
||||
# Create non-root user 'appuser' with UID 1001 (1000 already in use by node image)
|
||||
RUN addgroup -g 1001 appuser && \
|
||||
adduser -D -u 1001 -G appuser appuser
|
||||
|
||||
# Set ownership of application files to appuser
|
||||
RUN chown -R appuser:appuser /app
|
||||
|
||||
# Create logs directory
|
||||
RUN mkdir -p /app/logs && \
|
||||
chown -R appuser:appuser /app/logs
|
||||
|
||||
# Switch to non-root user
|
||||
USER appuser
|
||||
|
||||
# Expose port
|
||||
EXPOSE 3000
|
||||
|
||||
# Health check - backend should implement /health endpoint
|
||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
|
||||
CMD curl -f http://localhost:3000/health || exit 1
|
||||
|
||||
# Use dumb-init from PATH to avoid distro-specific absolute path issues
|
||||
ENTRYPOINT ["dumb-init", "--"]
|
||||
|
||||
# Run application
|
||||
CMD ["npm", "run", "server"]
|
||||
12
Dockerfile.frontend
Normal file
12
Dockerfile.frontend
Normal file
@@ -0,0 +1,12 @@
|
||||
FROM node:20-alpine
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY package*.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY . .
|
||||
|
||||
EXPOSE 8080
|
||||
|
||||
CMD ["npm", "run", "dev", "--", "--host", "0.0.0.0"]
|
||||
62
Dockerfile.frontend.prod
Normal file
62
Dockerfile.frontend.prod
Normal file
@@ -0,0 +1,62 @@
|
||||
# Stage 1: Build
|
||||
FROM node:20-alpine AS builder
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Copy package files
|
||||
COPY package*.json ./
|
||||
COPY tsconfig*.json ./
|
||||
COPY vite.config.ts ./
|
||||
|
||||
# Install all dependencies (including devDependencies for build)
|
||||
RUN npm ci
|
||||
|
||||
# Copy source code
|
||||
COPY src ./src
|
||||
COPY public ./public
|
||||
COPY index.html map_editor.html mobile.html ./
|
||||
|
||||
# Build application
|
||||
RUN npm run build
|
||||
|
||||
# Verify build output
|
||||
RUN ls -la dist/ && echo "Build completed successfully"
|
||||
|
||||
# Stage 2: Runtime
|
||||
FROM nginx:stable-alpine
|
||||
|
||||
LABEL maintainer="ITAM Team <devops@itam.local>"
|
||||
|
||||
# Install curl for health checks
|
||||
RUN apk add --no-cache curl
|
||||
|
||||
WORKDIR /usr/share/nginx/html
|
||||
|
||||
# Copy built assets from builder
|
||||
COPY --from=builder /app/dist .
|
||||
|
||||
# Copy static image assets referenced by literal /img/... paths (Obsolete: img folder is now public/img and copied via dist)
|
||||
# COPY img ./img
|
||||
|
||||
# Copy root-level logo asset referenced directly by index.html
|
||||
# COPY ["image 92.png", "./image 92.png"]
|
||||
|
||||
# Copy Nginx static file serving configuration (not reverse proxy)
|
||||
COPY docker/frontend/default.conf /etc/nginx/conf.d/default.conf
|
||||
|
||||
# Create nginx runtime user and directories
|
||||
RUN mkdir -p /var/log/nginx && \
|
||||
chown -R nginx:nginx /usr/share/nginx/html && \
|
||||
chown -R nginx:nginx /var/log/nginx && \
|
||||
chown -R nginx:nginx /var/cache/nginx && \
|
||||
chown -R nginx:nginx /etc/nginx/conf.d
|
||||
|
||||
# Expose port
|
||||
EXPOSE 80
|
||||
|
||||
# Health check
|
||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=20s --retries=3 \
|
||||
CMD curl -f http://localhost:80/ || exit 1
|
||||
|
||||
# Run nginx
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
33
Makefile
Normal file
33
Makefile
Normal file
@@ -0,0 +1,33 @@
|
||||
SHELL := /bin/sh
|
||||
|
||||
ENV_FILE ?= .env
|
||||
BACKUP_ROOT ?= backups
|
||||
RETENTION_DAYS ?= 14
|
||||
BACKUP_SCRIPT := scripts/backup.sh
|
||||
|
||||
.PHONY: help db-dump files-backup full-backup predeploy-backup cleanup-backups
|
||||
|
||||
help:
|
||||
@echo "Usage: make <target> [ENV_FILE=.env BACKUP_ROOT=backups RETENTION_DAYS=14]"
|
||||
@echo ""
|
||||
@echo "Targets:"
|
||||
@echo " db-dump Create a gzip-compressed MySQL dump from .env settings"
|
||||
@echo " files-backup Archive runtime files such as uploads/, map_config.json, and .env"
|
||||
@echo " full-backup Run both db-dump and files-backup"
|
||||
@echo " predeploy-backup Alias for the backup step executed before production deploy"
|
||||
@echo " cleanup-backups Delete backup files older than RETENTION_DAYS"
|
||||
|
||||
db-dump:
|
||||
@ENV_FILE="$(ENV_FILE)" BACKUP_ROOT="$(BACKUP_ROOT)" sh "$(BACKUP_SCRIPT)" db
|
||||
|
||||
files-backup:
|
||||
@ENV_FILE="$(ENV_FILE)" BACKUP_ROOT="$(BACKUP_ROOT)" sh "$(BACKUP_SCRIPT)" files
|
||||
|
||||
full-backup:
|
||||
@ENV_FILE="$(ENV_FILE)" BACKUP_ROOT="$(BACKUP_ROOT)" sh "$(BACKUP_SCRIPT)" full
|
||||
|
||||
predeploy-backup:
|
||||
@ENV_FILE="$(ENV_FILE)" BACKUP_ROOT="$(BACKUP_ROOT)" sh "$(BACKUP_SCRIPT)" full
|
||||
|
||||
cleanup-backups:
|
||||
@BACKUP_ROOT="$(BACKUP_ROOT)" RETENTION_DAYS="$(RETENTION_DAYS)" sh "$(BACKUP_SCRIPT)" cleanup
|
||||
22
QR_system.md
22
QR_system.md
@@ -1,22 +0,0 @@
|
||||
목적
|
||||
- 정기적인 실물자산 점검을 실시하여 시스템 내 자산정보의 정확성을 확보하고, 실제 자산의 위치 및 상태를 체계적으로 파악·관리할 수 있는 관리체계를 구축
|
||||
- QR 스캔 시스템을 통해 자산별 관리 이력 및 관리 책임자 정보를 즉시 확인할 수 있으며, 자산의 이동·변경 이력 추적과 안정적인 운영 관리를 추구
|
||||
|
||||
구조 구성안
|
||||
A. 실제 위치 정보를 가진 마스터 테이블 구축
|
||||
- 현재 DB의 위치 정보는 건물 및 호수 정보(예: 기술개발센터 / 서버실)와 이미지 파일 내 픽셀 좌표 정보로 관리되고 있으며, 실제 서버가 설치된 랙(Rack) 및 물리적 위치 정보를 관리하는 항목은 존재하지 않음
|
||||
- 이미지 좌표 데이터와 실제 자산 위치 데이터를 연결하는 별도 마스터 테이블을 생성하여, 좌표 정보와 물리적 위치 정보 간 관계 정의 필요
|
||||
|
||||
B. 기존 테이블 개편
|
||||
- 픽셀 좌표 정보는 마스터 테이블에서 통합관리하고, 기존 테이블은 마스터 코드를상속받는 구조로 변경하여 유지 보수성을 확보
|
||||
|
||||
QR코드 정보
|
||||
- 자산 QR : 시스템에 등록된 자산 고유의 자산번호
|
||||
- 위치 QR : 물리적 위치 테이블에 저장된 마스터 코드
|
||||
|
||||
현장실사 시나리오
|
||||
① 담당자가 서버 렉 전면에 부착된 위치 QR을 스캔
|
||||
② 위치 QR에 저장된 주소로 접속하여 세션에 현재 위치를 저장
|
||||
③ 자산에 부착된 자산 QR을 스캔하여 주소에 접속하게 되면 정보를 매칭하여 API로 전송
|
||||
④ 결합된 정보를 받아 기존 위치를 확인 혹은 업데이트
|
||||
⑤ 시스템에서 관리자가 확인하여 승인하게 되면 시스템에도 업데이트 완료
|
||||
132
baron-sso_login_guide/BARONSSO_loginAPI_task.md
Normal file
132
baron-sso_login_guide/BARONSSO_loginAPI_task.md
Normal file
@@ -0,0 +1,132 @@
|
||||
# BARON-SSO 통합 로그인 연동 가이드 (자산관리 시스템)
|
||||
|
||||
이 문서는 Baron SSO(OpenID Connect IdP)를 자산관리 시스템에 통합 연동하기 위한 상세 가이드입니다. Headless 로그인 방식과 OIDC 표준을 기반으로 사용자 인증 및 정보 획득 과정을 설명하며, Baron SSO `devfront` 페이지에서의 애플리케이션 설정 방법과 연동 시 필요한 핵심 로직을 다룹니다.
|
||||
|
||||
---
|
||||
|
||||
## 1. 개요
|
||||
|
||||
자산관리 시스템에 Baron SSO를 연동하여 통합 로그인을 구현합니다. 이를 통해 사용자는 Baron SSO에서 인증하고, 자산관리 시스템은 사용자의 신원을 확인하고 필요한 정보를 획득하게 됩니다. 본 가이드는 주로 **Headless 로그인** 방식을 사용하며, 이는 사용자에게 Baron SSO의 로그인 화면을 직접 노출하지 않고 자산관리 시스템 내에서 인증 과정을 처리하는 방식입니다.
|
||||
|
||||
---
|
||||
|
||||
## 2. OIDC 핵심 개념
|
||||
|
||||
### 2.1. Headless Login
|
||||
사용자가 IdP(Baron SSO)의 로그인 화면을 거치지 않고, RP(Relying Party, 자산관리 시스템) 내에서 직접 사용자 인증 정보를 입력받아 백채널(Back-channel)로 인증을 수행하는 방식입니다.
|
||||
|
||||
### 2.2. Client Assertion
|
||||
보안 강화를 위해 RP가 자신이 신뢰할 수 있는 앱임을 증명하는 JWT(JSON Web Token)입니다. 이는 중요한 인증 요청 시 함께 전송됩니다.
|
||||
|
||||
### 2.3. 스코프 (Scopes)
|
||||
사용자 정보에 접근하기 위한 권한 요청 단위입니다.
|
||||
- `openid`: OIDC 인증 요청임을 명시하며 `id_token` 발급에 필수적입니다.
|
||||
- `profile`: 사용자의 기본 프로필 정보(이름, 사번, 부서명 등) 접근 권한을 요청합니다.
|
||||
- `email`: 사용자의 이메일 주소 정보 접근 권한을 요청합니다.
|
||||
|
||||
### 2.4. 자동 승인 (Auto-Consent)
|
||||
Headless 환경에서 사용자의 정보 제공 동의 화면 없이, RP 서버가 백그라운드에서 동의 과정을 자동으로 처리하는 로직입니다.
|
||||
|
||||
---
|
||||
|
||||
## 3. Baron SSO (devfront) 애플리케이션 생성 및 설정
|
||||
|
||||
자산관리 시스템을 Baron SSO에 연동하기 위해 `devfront` 관리자 도구에서 Headless RP를 설정해야 합니다. 이때 IdP 서버가 RP의 JWKS 엔드포인트에 접속할 수 있어야 함을 유의하십시오.
|
||||
|
||||
### 3.1. Step 1: 클라이언트 기본 정보 입력
|
||||
|
||||
1. `devfront`에 접속하여 **연동 앱 > 연동 앱 추가**를 클릭합니다.
|
||||
2. **Name**: `asset-management-system` (또는 자산관리 시스템의 이름을 입력)
|
||||
3. **Redirect URIs**: 자산관리 시스템의 콜백 경로를 입력합니다.
|
||||
- 예: `http://[자산관리_시스템_IP_또는_도메인]:[포트]/callback`
|
||||
- **주의**: 실제 자산관리 시스템에서 요청하는 Redirect URI와 여기서 등록한 값이 **완전히 일치**해야 인증 거부 에러가 발생하지 않습니다.
|
||||
4. **Scopes**: `openid`, `profile`, `email`을 선택합니다.
|
||||
5. **Type**: 반드시 `pkce`를 선택합니다.
|
||||
|
||||
### 3.2. Step 2: Headless 기능 및 보안 설정
|
||||
|
||||
1. `pkce` 하단의 **"Headless Login (자체 로그인 UI 사용)"** 토글을 활성화합니다.
|
||||
2. **JWKS URI**: **Baron SSO 서버에서 접근 가능한** 자산관리 시스템의 공개키 주소를 입력합니다.
|
||||
- 예: `http://[자산관리_시스템_IP_또는_도메인]:[포트]/.well-known/jwks.json`
|
||||
- **주의**: Baron SSO 서버에서 자산관리 시스템의 포트로 네트워크가 열려있어야 합니다.
|
||||
|
||||
### 3.3. Step 3: 저장 및 확인 (JWKS 캐시 검증)
|
||||
|
||||
1. **앱 생성** 버튼을 클릭하여 설정을 저장합니다.
|
||||
2. 연동 앱 목록에서 생성된 앱이 **PKCE (Headless Login)** 유형인지 확인합니다.
|
||||
3. 앱 상세 페이지 하단이나 설정 탭에서 **JWKS 캐시 상태**가 `Success`인지 반드시 확인합니다. 캐시 상태가 비어있거나 실패인 경우, 자산관리 시스템이 켜져 있는지 확인하고 **새로고침(Refresh)** 버튼을 눌러 수동으로 캐시를 갱신해야 합니다.
|
||||
|
||||
---
|
||||
|
||||
## 4. 자산관리 시스템 연동 로직
|
||||
|
||||
### 4.1. 사번 로그인 (Headless Employee ID Login Flow)
|
||||
|
||||
사용자가 자산관리 시스템에서 사번과 비밀번호를 입력하여 로그인하는 시퀀스입니다.
|
||||
|
||||
1. **신호 요청**: 자산관리 시스템은 Baron SSO의 Authorization Endpoint(`oauth2/auth`)에 요청하여 `login_challenge`를 획득합니다.
|
||||
2. **본인 인증**: 자산관리 시스템은 Private Key로 서명된 `client_assertion`(JWT)과 사용자의 사번, 비밀번호, `login_challenge`를 포함하여 Baron SSO의 Headless 로그인 API(`POST /api/v1/auth/headless/password/login`)를 호출합니다.
|
||||
3. **권한 획득 (자동 승인 포함)**: 인증 성공 후 Baron SSO가 반환하는 `redirectTo` 주소를 추적하며, 이 과정에서 `consent` 화면이 감지되면 자산관리 시스템은 백그라운드에서 동의 API(`POST /api/v1/auth/consent/accept`)를 호출하여 자동으로 승인합니다. 최종적으로 `Authorization Code`를 획득합니다.
|
||||
4. **인증키 발급**: 획득한 `Authorization Code`와 새로 생성한 `client_assertion`을 사용하여 Baron SSO의 Token Endpoint에 요청, `id_token`과 `access_token`을 발급받습니다.
|
||||
5. **로그인 완료**: `id_token`을 검증하고 사용자 정보를 추출하여 자산관리 시스템의 세션을 생성하고 로그인 완료 처리합니다.
|
||||
|
||||
### 4.2. 전화번호 인증 로그인 (Headless Phone Number Authentication Login Flow)
|
||||
|
||||
사용자가 자산관리 시스템에서 전화번호를 입력하여 인증 링크를 받고, 모바일에서 승인하여 로그인하는 시퀀스입니다.
|
||||
|
||||
1. **신호 요청**: 사번 로그인과 동일하게 `login_challenge`를 획득합니다.
|
||||
2. **링크 발송 요청**: 자산관리 시스템은 `client_assertion`, `login_challenge`, 사용자의 전화번호(`loginId`)를 포함하여 Baron SSO의 인증 링크 발송 API(`POST /api/v1/auth/headless/link/init`)를 호출합니다. Baron SSO는 사용자에게 인증 링크를 발송하고 `pendingRef`를 반환합니다.
|
||||
3. **인증 상태 폴링**: 자산관리 시스템은 `pendingRef`와 `client_assertion`을 포함하여 Baron SSO의 상태 확인 API(`POST /api/v1/auth/headless/link/poll`)를 주기적으로 호출합니다. 사용자가 모바일에서 링크를 클릭하여 인증을 완료하면, Baron SSO는 `redirectTo` 정보를 반환하며 폴링이 종료됩니다.
|
||||
4. **이후 과정**: 폴링 결과로 받은 `redirectTo` 주소부터는 사번 로그인과 동일하게 표준 OIDC 흐름을 따릅니다 (자동 승인, `Authorization Code` 획득, `id_token` 발급, 세션 생성).
|
||||
|
||||
### 4.3. 자동 승인 및 스코프 처리 (Auto-Consent and Scope Handling)
|
||||
|
||||
자산관리 시스템은 `openid`, `profile`, `email`과 같은 스코프를 Baron SSO에 요청합니다. Headless 환경에서는 SSO 서버로부터 리다이렉트 주소에 `/consent`가 포함될 경우, 자산관리 시스템은 이를 감지하여 `consent_challenge`를 추출하고, 동의 상세 정보(`GET /api/v1/auth/consent`)를 요청하여 필요한 스코프를 확인합니다. 이후, 확인된 스코프를 모두 허용(`grant_scope`)한다고 Baron SSO의 동의 승인 API(`POST /api/v1/auth/consent/accept`)에 전송하여 자동으로 승인 과정을 처리합니다.
|
||||
|
||||
### 4.4. Tenant 접근 제한 예외 처리 (Tenant Access Restriction Exception Handling)
|
||||
|
||||
자산관리 시스템이 `tenant_access_restricted=true`로 설정되어 있고, 현재 사용자의 tenant가 허용된 `allowed_tenants`에 포함되지 않는 경우, Baron SSO는 `403` HTTP 상태 코드와 `code=tenant_not_allowed`를 응답합니다. 자산관리 시스템은 이 응답을 감지하여 사용자에게 적절한 에러 페이지(예: `/ko/error?error=tenant_not_allowed...`)로 리다이렉트하여 처리해야 합니다.
|
||||
|
||||
---
|
||||
|
||||
## 5. 자산관리 시스템 로컬 설정 (.env)
|
||||
|
||||
자산관리 시스템 프로젝트 루트의 `.env` 파일에 다음과 같이 Baron SSO 연동 설정을 구성합니다.
|
||||
|
||||
```env
|
||||
# 애플리케이션 실행 포트 (자산관리 시스템의 포트)
|
||||
PORT=3000 # 예시
|
||||
|
||||
# OIDC IdP 설정 (Baron SSO 서버 주소)
|
||||
CLIENT_ID=... # devfront에서 발급받은 클라이언트 ID
|
||||
ISSUER=http://[BARON_SSO_IP_또는_도메인]/oidc
|
||||
|
||||
# 리다이렉트 및 보안 설정
|
||||
# REDIRECT_URI는 DevFront에 등록한 Redirect URIs 중 하나와 정확히 일치해야 합니다.
|
||||
REDIRECT_URI=http://[자산관리_시스템_IP_또는_도메인]:[포트]/callback
|
||||
# JWKS_URI는 Baron SSO 서버가 자산관리 시스템으로 접속할 때 사용하는 주소와 일치해야 합니다.
|
||||
JWKS_URI=http://[자산관리_시스템_IP_또는_도메인]:[포트]/.well-known/jwks.json
|
||||
|
||||
# tenant 제한 시 이동시킬 userfront 에러 경로
|
||||
ERROR_LOCALE_PATH=/ko/error
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. 주의 사항 (네트워크 구성)
|
||||
|
||||
- **서버 간 통신 (Server-to-Server)**: Headless 로그인은 Baron SSO 서버가 직접 자산관리 시스템의 `JWKS_URI`에 접속하여 서명을 검증합니다. 따라서 IdP 서버에서 자산관리 시스템의 포트로의 인바운드 통신이 허용되어야 합니다. 방화벽 및 네트워크 설정을 확인하십시오.
|
||||
- **Redirect URI 일치**: 브라우저를 통해 접속할 주소가 IP라면, Redirect URI와 JWKS URI 모두 IP 기반 주소로 통일하는 것이 문제 발생 소지를 줄이는 가장 좋은 방법입니다. 도메인을 사용한다면 일관되게 도메인으로 설정해야 합니다.
|
||||
|
||||
---
|
||||
|
||||
## 7. 실행
|
||||
|
||||
자산관리 시스템 프로젝트에서 다음 명령어를 실행하여 필요한 패키지를 설치하고 서버를 시작합니다.
|
||||
|
||||
```bash
|
||||
npm install
|
||||
npm start
|
||||
```
|
||||
|
||||
서버 실행 시 `keys.json` 파일이 자동으로 생성되며, `.env`에 설정된 `JWKS_URI` 경로로 공개키가 서빙되어 Baron SSO가 이를 검증에 사용할 수 있게 됩니다.
|
||||
119
baron-sso_login_guide/headless-consent-and-scope.md
Normal file
119
baron-sso_login_guide/headless-consent-and-scope.md
Normal file
@@ -0,0 +1,119 @@
|
||||
# Headless 스코프(Scope) 및 자동 승인(Auto-Consent) 가이드
|
||||
|
||||
이 문서는 Headless 로그인 환경에서 애플리케이션이 사용자 정보를 가져오기 위해 사용하는 **스코프(Scope)**의 개념과, IdP의 화면 없이 권한을 획득하는 **자동 승인(Auto-Consent)** 로직을 설명합니다.
|
||||
|
||||
---
|
||||
|
||||
## 1. 요구 스코프 (Requested Scopes)
|
||||
|
||||
데모 앱은 OIDC 표준에 따라 다음 스코프를 IdP(Baron SSO)에 요청합니다.
|
||||
|
||||
| 스코프 | 필수 여부 | 역할 및 획득 데이터 |
|
||||
| :-------- | :-------: | :------------------------------------------------------------------ |
|
||||
| `openid` | **필수** | 해당 요청이 OIDC 인증임을 명시. `id_token` 발급을 위해 반드시 필요. |
|
||||
| `profile` | 권장 | 사용자의 기본 프로필 정보(이름, 사번, 부서명 등) 접근 권한. |
|
||||
| `email` | 권장 | 사용자의 이메일 주소 정보 접근 권한. |
|
||||
|
||||
데모 앱은 최초 인증 요청(`GET /oauth2/auth`) 시 `scope=openid profile` 형식으로 권한을 요구합니다.
|
||||
|
||||
---
|
||||
|
||||
## 2. 자동 승인(Auto-Consent) 흐름도
|
||||
|
||||
일반적인 OIDC 환경에서는 사용자에게 '정보 제공 동의' 화면이 노출되지만, Headless 환경에서는 **RP 서버가 이 과정을 백그라운드에서 자동으로 수행**합니다.
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
autonumber
|
||||
participant Browser as 사용자 브라우저
|
||||
participant RP as 데모 앱 서버 (RP)
|
||||
participant SSO as Baron SSO (IdP)
|
||||
|
||||
RP->>SSO: 1. 본인 인증 요청 (전화번호)
|
||||
SSO-->>RP: 2. 인증 성공 및 리다이렉트 (redirectTo: /consent...)
|
||||
|
||||
Note over RP: [자동 승인 로직 시작]
|
||||
RP->>RP: 3. 리다이렉트 경로 중 '/consent' 감지
|
||||
RP->>SSO: 4. 동의 상세 정보 요청 (GET /api/v1/auth/consent)
|
||||
SSO-->>RP: 5. 요청된 스코프 정보 반환 (openid, profile 등)
|
||||
|
||||
RP->>SSO: 6. 동의 승인 API 호출 (POST /api/v1/auth/consent/accept)<br/>[grant_scope 포함]
|
||||
SSO-->>RP: 7. 최종 리다이렉트 주소 반환 (code=...)
|
||||
|
||||
Note over RP: [표준 OIDC 흐름 복귀]
|
||||
RP->>SSO: 8. Token Exchange (Code -> id_token)
|
||||
SSO-->>RP: 9. 사용자 정보가 담긴 id_token 발급
|
||||
RP-->>Browser: 10. 세션 생성 및 로그인 완료 안내
|
||||
```
|
||||
---
|
||||
|
||||
## 3. 핵심 구현 코드 (server.js)
|
||||
|
||||
데모 앱의 `server.js` 내 `resolveRedirects` 함수는 SSO 서버로부터 오는 리다이렉트 주소를 추적하다가, 동의 화면(`consent_challenge`)이 나타나면 이를 가로채서 처리합니다.
|
||||
|
||||
```javascript
|
||||
if (currentUrl.includes("/consent")) {
|
||||
console.log(
|
||||
" [자동 승인] 사용자의 정보 제공 동의 화면이 감지되어 시스템이 자동으로 승인 중입니다.",
|
||||
);
|
||||
|
||||
// 1. URL에서 consent_challenge 추출
|
||||
const consentUrl = new URL(currentUrl);
|
||||
const consentChallenge = consentUrl.searchParams.get("consent_challenge");
|
||||
|
||||
// 2. SSO 서버에 현재 요청된 스코프가 무엇인지 확인
|
||||
const detailsUrl = new URL("/api/v1/auth/consent", currentUrl);
|
||||
detailsUrl.searchParams.set("consent_challenge", consentChallenge);
|
||||
const detailsRes = await fetch(detailsUrl.toString(), {
|
||||
headers: { Cookie: nextCookies },
|
||||
});
|
||||
const consentInfo = await detailsRes.json();
|
||||
|
||||
// 3. 확인된 스코프(openid, profile 등)를 모두 허용(accept)한다고 서버에 전송
|
||||
const acceptUrl = new URL("/api/v1/auth/consent/accept", currentUrl);
|
||||
const acceptRes = await fetch(acceptUrl.toString(), {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", Cookie: nextCookies },
|
||||
body: JSON.stringify({
|
||||
consent_challenge: consentChallenge,
|
||||
grant_scope: consentInfo.requested_scope || ["openid", "profile"],
|
||||
grant_access_token_audience:
|
||||
consentInfo.requested_access_token_audience || [],
|
||||
}),
|
||||
});
|
||||
|
||||
const acceptPayload = await acceptRes.json();
|
||||
// 4. 승인 후 받은 최종 목적지(code 포함)로 이동 계속
|
||||
return resolveRedirects(acceptPayload.redirectTo, nextCookies, depth + 1);
|
||||
}
|
||||
```
|
||||
|
||||
## 4. Tenant 접근 제한 예외 흐름
|
||||
|
||||
Headless RP도 consent 단계에서 tenant 제한에 걸릴 수 있습니다. 이 경우는 일반적인 auto-consent 성공 흐름과 별도로 처리해야 합니다.
|
||||
|
||||
조건:
|
||||
- RP metadata에 `tenant_access_restricted=true`
|
||||
- 현재 사용자의 tenant가 `allowed_tenants`에 없음
|
||||
|
||||
이때 Baron SSO 응답:
|
||||
- `GET /api/v1/auth/consent` 또는 `POST /api/v1/auth/consent/accept`
|
||||
- HTTP `403`
|
||||
- body에 `code=tenant_not_allowed`
|
||||
|
||||
데모 앱 처리 원칙:
|
||||
- `redirectTo`가 없다고 가정하고 계속 진행하면 안 됩니다.
|
||||
- `tenant_not_allowed`를 감지하면 `userfront` 에러 화면 URL로 변환해 브라우저를 이동시켜야 합니다.
|
||||
- 기본 목적지는 `/ko/error?error=tenant_not_allowed&error_description=...&details=...` 입니다.
|
||||
|
||||
운영 관점 해석:
|
||||
- backend 로그에 `tenant_not_allowed`가 보이면 Baron SSO 제한은 정상입니다.
|
||||
- 브라우저에서 `Invalid URL`이 보이면 RP가 `403` 응답을 잘못 소비하고 있다는 뜻입니다.
|
||||
|
||||
---
|
||||
|
||||
## 4. 특징 및 장점
|
||||
|
||||
- **심리스한 UX**: 사용자는 "로그인 중..."이라는 메시지만 보게 되며, 복잡한 권한 동의 절차를 신경 쓸 필요가 없습니다.
|
||||
- **강력한 보안**: 자동 승인 과정은 서버 대 서버(Back-channel) 통신으로 이루어지며, 브라우저에는 동의 관련 데이터가 전혀 노출되지 않습니다.
|
||||
- **유연한 확장**: 나중에 새로운 사용자 정보(`email` 등)가 필요해지더라도, 앱의 스코프 설정만 변경하면 자동으로 승인 로직에 반영됩니다.
|
||||
95
baron-sso_login_guide/headless-employee-login-flow.md
Normal file
95
baron-sso_login_guide/headless-employee-login-flow.md
Normal file
@@ -0,0 +1,95 @@
|
||||
# Headless 사번 로그인 로직
|
||||
|
||||
이 문서는 사용자가 데모 애플리케이션에서 **사번과 비밀번호**를 이용해 로그인할 때 발생하는 내부 OIDC (OpenID Connect) Headless 인증 흐름을 설명합니다.
|
||||
|
||||
## 핵심 개념
|
||||
|
||||
- **Headless Login**: 사용자가 IdP(Identity Provider, Baron SSO)의 로그인 화면을 거치지 않고, RP(Relying Party, 데모 앱) 내에서 직접 아이디와 비밀번호를 입력받아 백채널(Back-channel)로 인증을 수행하는 방식입니다.
|
||||
- **Client Assertion**: 보안을 위해 데모 앱은 사번/비밀번호를 전송할 때 자신이 신뢰할 수 있는 앱임을 증명하는 JWT(`client_assertion`)를 생성하여 함께 전송합니다.
|
||||
|
||||
---
|
||||
|
||||
## 1. 사번 로그인 시퀀스 다이어그램
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
autonumber
|
||||
actor User as 사용자
|
||||
participant RP as 데모 앱 (RP)
|
||||
participant OIDC as Baron SSO (OIDC/Hydra)
|
||||
participant Auth as Baron SSO (Headless API)
|
||||
|
||||
User->>RP: 1. 사번 / 비밀번호 입력 후 로그인 요청
|
||||
|
||||
note over RP: [1단계: 신호 요청]
|
||||
RP->>OIDC: 2. OIDC Discovery 및 Authorization Request<br/>(GET /oauth2/auth?response_type=code...)
|
||||
OIDC-->>RP: 3. login_challenge 발급 및 302 Redirect
|
||||
|
||||
note over RP: [2단계: 본인 인증]
|
||||
RP->>RP: 4. Private Key로 client_assertion (JWT) 생성
|
||||
RP->>Auth: 5. Headless 로그인 API 호출<br/>(POST /api/v1/auth/headless/password/login)<br/>[client_assertion, login_challenge, 사번, 비밀번호 포함]
|
||||
Auth-->>RP: 6. 인증 성공 및 리다이렉트 URL 반환
|
||||
|
||||
note over RP: [3단계: 권한 획득]
|
||||
RP->>OIDC: 7. 리다이렉트 URL 추적 (Cookie 유지)
|
||||
OIDC-->>RP: 8. Consent 화면 (필요 시 자동 승인 API 호출)
|
||||
OIDC-->>RP: 9. 최종 Authorization Code 발급 (code=...)
|
||||
|
||||
note over RP: [4단계: 인증키 발급]
|
||||
RP->>OIDC: 10. Token Endpoint 호출 (Authorization Code Grant)<br/>[client_assertion 포함]
|
||||
OIDC-->>RP: 11. id_token, access_token 발급
|
||||
|
||||
note over RP: [5단계: 로그인 완료]
|
||||
RP->>RP: 12. id_token 검증 및 사용자 세션 생성
|
||||
RP-->>User: 13. 홈 화면 리다이렉트 및 로그인 성공
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. 단계별 상세 로직 설명
|
||||
|
||||
위 다이어그램의 주요 단계를 데모 애플리케이션(`server.js`의 `runHeadlessSsoLogin` 함수) 로직을 중심으로 설명합니다.
|
||||
|
||||
### [1단계] 신호 요청 (Authorization Request)
|
||||
- **목적**: SSO 서버와의 세션을 시작하고, 인증 컨텍스트를 식별할 수 있는 고유값(`login_challenge`)을 획득합니다.
|
||||
- **동작**:
|
||||
1. OIDC Discovery를 통해 엔드포인트들을 가져옵니다.
|
||||
2. `response_type=code`, `client_id`, `state`, `nonce` 등을 포함하여 Authorization Endpoint(`/oauth2/auth`)로 `fetch` 요청(리다이렉트 수동 추적 모드)을 보냅니다.
|
||||
3. 응답 헤더의 `Location`에 포함된 `login_challenge` 값을 추출합니다.
|
||||
|
||||
### [2단계] 본인 인증 (Headless Password Login)
|
||||
- **목적**: 사용자가 입력한 자격 증명(사번, 비밀번호)을 SSO 서버에 직접 전달하여 인증을 승인받습니다.
|
||||
- **동작**:
|
||||
1. RP의 **Private Key(`keys.json`)**를 사용하여 `client_assertion` JWT를 서명합니다. (이때 `aud` 값은 SSO 서버의 Headless API URL이어야 합니다.)
|
||||
2. `POST /api/v1/auth/headless/password/login` 엔드포인트로 JSON 페이로드를 전송합니다.
|
||||
```json
|
||||
{
|
||||
"client_id": "...",
|
||||
"login_challenge": "...",
|
||||
"loginId": "사번",
|
||||
"password": "비밀번호",
|
||||
"client_assertion": "..."
|
||||
}
|
||||
```
|
||||
3. 인증이 성공하면 서버는 OIDC 로그인 흐름을 계속할 수 있는 `redirectTo` 주소를 반환합니다.
|
||||
|
||||
### [3단계] 권한 획득 (Redirect Resolution & Consent)
|
||||
- **목적**: 인증 성공 후, OIDC 프로토콜에 따라 최종적으로 `Authorization Code`를 획득합니다.
|
||||
- **동작**:
|
||||
1. 2단계에서 받은 `redirectTo` 주소를 따라가며 쿠키(Cookie)를 계속 유지시킵니다.
|
||||
2. 만약 경로 중에 정보 제공 동의(`consent`) 화면이 감지되면, 데모 앱이 사용자 대신 백그라운드에서 동의 API(`POST /api/v1/auth/consent/accept`)를 호출하여 자동 승인합니다.
|
||||
3. 최종적으로 URL에 `code=...`가 포함된 리다이렉트를 찾습니다.
|
||||
|
||||
### [4단계] 인증키 발급 (Token Exchange)
|
||||
- **목적**: 획득한 `Authorization Code`를 안전한 토큰들로 교환합니다.
|
||||
- **동작**:
|
||||
1. Token Endpoint로 코드를 전송합니다.
|
||||
2. 이때도 보안을 위해 `private_key_jwt` 방식이 사용되므로, 새로 생성한 `client_assertion`을 요청 본문에 포함시킵니다.
|
||||
3. 검증이 완료되면 `access_token`과 사용자 정보가 담긴 `id_token`을 받게 됩니다.
|
||||
|
||||
### [5단계] 로그인 완료 (Session Creation)
|
||||
- **목적**: 받은 토큰을 검증하고, 브라우저가 인식할 수 있는 로컬 세션을 만듭니다.
|
||||
- **동작**:
|
||||
1. `jose` 라이브러리를 통해 `id_token`의 서명을 검증하고 payload(사번, 이름, 부서 등)를 추출합니다.
|
||||
2. 추출된 사용자 정보를 `express-session`의 `req.session.user`에 저장합니다.
|
||||
3. 클라이언트 브라우저에게 세션 쿠키를 발급하며 홈 화면(`/home.html`)으로 리다이렉트 시킵니다.
|
||||
84
baron-sso_login_guide/headless-phone-login-flow.md
Normal file
84
baron-sso_login_guide/headless-phone-login-flow.md
Normal file
@@ -0,0 +1,84 @@
|
||||
# Headless 전화번호 인증 로그인 로직
|
||||
|
||||
이 문서는 사용자가 데모 애플리케이션에서 **전화번호**를 입력하여 인증 링크를 받고, 모바일에서 승인하여 로그인하는 내부 흐름을 설명합니다.
|
||||
|
||||
## 핵심 개념
|
||||
|
||||
- **Link Init**: 사용자의 전화번호로 실제 인증 링크(카카오톡 또는 SMS)를 발송하도록 SSO 서버에 요청하는 단계입니다.
|
||||
- **Polling**: 사용자가 모바일에서 링크를 클릭할 때까지 앱 서버가 주기적으로 SSO 서버에 "인증이 완료되었는지" 물어보는 과정입니다.
|
||||
- **Security**: 이 과정에서도 모든 API 호출은 RP의 Private Key로 서명된 `client_assertion`을 포함하여 보안을 유지합니다.
|
||||
|
||||
---
|
||||
|
||||
## 1. 전화번호 로그인 시퀀스 다이어그램
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
autonumber
|
||||
actor User as 사용자
|
||||
participant RP as 데모 앱 (RP)
|
||||
participant OIDC as Baron SSO (OIDC)
|
||||
participant Auth as Baron SSO (Headless API)
|
||||
|
||||
User->>RP: 1. 전화번호 입력 후 인증 요청
|
||||
|
||||
note over RP: [1단계: 신호 요청]
|
||||
RP->>OIDC: 2. Authorization Request (GET /oauth2/auth)<br/>[login_challenge 획득]
|
||||
|
||||
note over RP: [2단계: 링크 발송 요청]
|
||||
RP->>Auth: 3. 인증 링크 발송 요청 (POST .../link/init)<br/>[client_assertion, login_challenge, 전화번호 포함]
|
||||
Auth-->>User: 4. 인증 링크 발송 (카카오톡/SMS)
|
||||
Auth-->>RP: 5. 대기 참조값(pendingRef) 반환
|
||||
|
||||
note over RP: [3단계: 인증 상태 폴링]
|
||||
loop 인증 완료 시까지 반복 (최대 3분)
|
||||
RP->>Auth: 6. 상태 확인 (POST .../link/poll)<br/>[client_assertion, pendingRef 포함]
|
||||
alt 아직 대기 중
|
||||
Auth-->>RP: 7. authorization_pending 응답
|
||||
RP->>RP: 잠시 대기 (interval)
|
||||
else 사용자 링크 클릭 완료
|
||||
Auth-->>RP: 8. 인증 성공 및 리다이렉트 URL 반환
|
||||
end
|
||||
end
|
||||
|
||||
note over User: 사용자가 모바일에서 링크 클릭 및 승인
|
||||
|
||||
note over RP: [4단계: 이후 과정 (사번 로그인과 동일)]
|
||||
RP->>OIDC: 9. 리다이렉트 추적 및 Authorization Code 획득
|
||||
RP->>OIDC: 10. Token Endpoint 호출 및 id_token 발급
|
||||
RP->>RP: 11. 세션 생성 및 홈 화면 이동
|
||||
RP-->>User: 12. 로그인 완료 안내
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. 단계별 상세 로직 설명
|
||||
|
||||
### [1단계] 신호 요청 (Login Challenge)
|
||||
- 사번 로그인과 동일하게 OIDC 표준 흐름을 시작하기 위해 `login_challenge`를 먼저 획득합니다. 이 값은 이후 인증 시도 시 "이 사용자가 어떤 OIDC 요청에 응답하고 있는지"를 SSO 서버에 알려주는 매개체가 됩니다.
|
||||
|
||||
### [2단계] 링크 발송 요청 (Link Init)
|
||||
- **동작**: `POST /api/v1/auth/headless/link/init` 호출.
|
||||
- **데이터**: `client_assertion`, `login_challenge`, 사용자의 `loginId`(전화번호).
|
||||
- **결과**: SSO 서버는 사용자의 전화번호로 인증 가능한 고유 링크를 발송하고, RP에게는 해당 요청을 추적할 수 있는 `pendingRef`와 다음 폴링까지의 권장 대기 시간(`interval`)을 반환합니다.
|
||||
|
||||
### [3단계] 인증 상태 폴링 (Polling)
|
||||
- **동작**: `POST /api/v1/auth/headless/link/poll`을 주기적으로 호출.
|
||||
- **상태 처리**:
|
||||
- `authorization_pending`: 사용자가 아직 링크를 클릭하지 않았으므로 지정된 시간만큼 기다린 후 다시 시도합니다.
|
||||
- `slow_down`: 폴링 간격이 너무 잦다는 신호로, 대기 시간을 조금 더 늘립니다.
|
||||
- `expired_token`: 3분이 경과하여 인증 요청이 만료된 경우입니다.
|
||||
- **성공**: 사용자가 승인을 완료하면 서버는 `redirectTo` 정보를 반환하며 폴링이 종료됩니다.
|
||||
|
||||
### [4단계] 이후 과정 (Standard OIDC Flow)
|
||||
- 폴링 결과로 받은 `redirectTo` 주소부터는 표준 OIDC 흐름을 따릅니다.
|
||||
- 데모 앱은 해당 주소로 리다이렉트하며 발생하는 쿠키를 유지하고, 필요 시 사용자 동의(Consent) 과정을 자동 수행하여 최종적으로 `Authorization Code`를 얻어냅니다.
|
||||
- 마지막으로 해당 코드를 `id_token`으로 교환하여 사용자 정보를 세션에 저장합니다.
|
||||
|
||||
---
|
||||
|
||||
## 3. 특징 및 주의 사항
|
||||
|
||||
- **비동기 사용자 경험**: 사용자는 PC에서 전화번호만 입력하고, 실제 인증 행위는 모바일에서 수행합니다. PC 화면은 폴링이 완료될 때까지 "인증 대기 중" 상태를 유지합니다.
|
||||
- **보안 검증**: 폴링 시에도 `client_assertion`이 필요합니다. 이는 제3자가 `pendingRef`를 가로채더라도 RP의 비밀키 없이는 인증 상태를 훔쳐볼 수 없음을 보장합니다.
|
||||
- **제한 시간**: 보안상 폴링은 보통 3분(180초)으로 제한되며, 이후에는 요청을 처음부터 다시 시작해야 합니다.
|
||||
115
baron-sso_login_guide/setup-guide.md
Normal file
115
baron-sso_login_guide/setup-guide.md
Normal file
@@ -0,0 +1,115 @@
|
||||
# Headless 로그인 데모 설정 가이드 (Baron SSO 연동)
|
||||
|
||||
이 문서는 `headless-login-demo` 프로젝트를 설치하고, **Baron SSO (OIDC IdP)** 관리자 도구(`devfront`)에서 **Headless RP**를 올바르게 생성 및 설정하는 방법을 단계별로 설명합니다.
|
||||
|
||||
---
|
||||
|
||||
## 1. Baron SSO (devfront) 설정
|
||||
|
||||
Headless RP는 일반 OIDC 클라이언트와 설정 방식이 다릅니다. 특히 **IdP 서버가 RP(데모 앱)의 JWKS 엔드포인트에 접속할 수 있어야 함**을 유의하십시오.
|
||||
|
||||
### Step 1: 클라이언트 기본 정보 입력
|
||||
|
||||
1. `devfront` 접속 후 **연동 앱 > 연동 앱 추가**를 클릭합니다.
|
||||
2. **Name**: `headless-login` (또는 자유롭게 입력)
|
||||
3. **Redirect URIs**: 데모 앱에 접속할 주소의 콜백 경로를 입력합니다.
|
||||
- **통합 환경 (IdP와 RP가 같은 서버일 때)**: `http://localhost:3000/callback`
|
||||
- **분리 환경 (IdP는 원격 서버, RP는 내 PC일 때)**: `http://[내_PC_IP]:3000/callback`
|
||||
- _주의: 실제 앱에서 요청하는 Redirect URI와 여기서 등록한 값이 **완전히 일치**해야 인증 거부 에러가 발생하지 않습니다._
|
||||
4. **Scopes**: `openid`, `profile`, `email`을 선택합니다.
|
||||
5. **Type**: 반드시 `pkce`를 선택해야 합니다.
|
||||
|
||||

|
||||
|
||||
### Step 2: Headless 기능 및 보안 설정
|
||||
|
||||
1. `pkce` 하단의 **"Headless Login (자체 로그인 UI 사용)"** 토글을 활성화합니다.
|
||||
2. **JWKS URI**: **Baron SSO 서버에서 접근 가능한** 데모 앱의 공개키 주소를 입력합니다.
|
||||
- **통합 환경 (IdP와 RP가 같은 서버일 때)**: `http://localhost:3000/.well-known/jwks.json`
|
||||
- **분리 환경 (IdP는 원격 서버, RP는 내 PC일 때)**: `http://[내_PC_IP]:3000/.well-known/jwks.json`
|
||||
- _주의: Baron SSO 서버(`172.16.10.175`)에서 사용자님의 로컬 PC 포트로 네트워크가 열려있어야 합니다._
|
||||
|
||||

|
||||
|
||||
### Step 3: 저장 및 확인 (JWKS 캐시 검증)
|
||||
|
||||
1. **앱 생성** 버튼을 클릭해 저장합니다.
|
||||
2. 연동 앱 목록에서 해당 앱이 **PKCE (Headless Login)** 유형으로 생성됐는지 확인합니다.
|
||||
3. 앱 상세 페이지 하단이나 설정 탭에서 **JWKS 캐시 상태**가 `Success`인지 반드시 확인합니다.
|
||||
- _팁: 캐시 상태가 비어있거나 실패인 경우, 데모 앱(내 PC)이 켜져 있는지 확인하고 **새로고침(Refresh)** 버튼을 눌러 수동으로 캐시를 갱신하세요. 캐싱이 정상적으로 이루어져야만 로그인이 작동합니다._
|
||||
|
||||
## 
|
||||
|
||||
## 2. Headless Login 애플리케이션 로컬 설정 (.env)
|
||||
|
||||
`devfront`에서 설정한 값을 바탕으로 프로젝트 루트의 `.env` 파일을 구성합니다.
|
||||
|
||||
```env
|
||||
# 애플리케이션 실행 포트
|
||||
PORT=3000
|
||||
|
||||
# OIDC IdP 설정 (원격 서버 주소 입력)
|
||||
CLIENT_ID=a9b64539-7242-4aa5-ad3d-13c7f1ef00f2
|
||||
ISSUER=http://172.16.10.175/oidc
|
||||
|
||||
# 리다이렉트 및 보안 설정
|
||||
# REDIRECT_URI는 DevFront에 등록한 Redirect URIs 중 하나와 정확히 일치해야 합니다.
|
||||
REDIRECT_URI=http://[내_PC_IP]:3000/callback
|
||||
# JWKS_URI는 Baron SSO 서버가 내 PC로 접속할 때 사용하는 주소와 일치해야 합니다.
|
||||
JWKS_URI=http://[내_PC_IP]:3000/.well-known/jwks.json
|
||||
|
||||
# tenant 제한 시 이동시킬 userfront 에러 경로
|
||||
ERROR_LOCALE_PATH=/ko/error
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. 주의 사항 (네트워크 구성)
|
||||
|
||||
- **서버 간 통신 (Server-to-Server)**: Headless 로그인은 Baron SSO 서버가 직접 데모 앱의 `JWKS_URI`에 접속하여 서명을 검증합니다. 따라서 IdP 서버에서 내 로컬 PC의 포트(`3000`)로의 인바운드 통신이 허용되어야 합니다.
|
||||
- **Redirect URI 일치**: 브라우저를 통해 접속할 주소가 IP라면, Redirect URI와 JWKS URI 모두 IP 기반 주소로 통일하는 것이 문제 발생 소지를 줄이는 가장 좋은 방법입니다.
|
||||
|
||||
---
|
||||
|
||||
## 4. 실행
|
||||
|
||||
```bash
|
||||
npm install
|
||||
npm start
|
||||
```
|
||||
|
||||
> **💡 참고: 자동 키 생성 및 JWKS 엔드포인트 활성화**
|
||||
> `npm start` 명령어로 서버를 실행하면, 프로젝트 내에 `keys.json` 파일이 자동으로 생성됩니다. 이 파일에는 서버가 자체적으로 발급한 RSA 보안 키 쌍(공개키/개인키)이 저장됩니다.
|
||||
> 동시에, `.env`에 설정된 `JWKS_URI` 경로(또는 기본 경로)로 공개키가 서빙되어 Baron SSO가 검증에 사용할 수 있게 됩니다.
|
||||
|
||||
---
|
||||
|
||||
## 5. Tenant 제한 테스트 가이드
|
||||
|
||||
Headless RP는 login API 성공 이후 consent 단계에서 tenant 제한이 걸릴 수 있습니다. 따라서 단순히 `/api/v1/auth/headless/password/login` 성공만 보면 안 되고, 최종 redirect 해석까지 확인해야 합니다.
|
||||
|
||||
### 권장 검증 순서
|
||||
|
||||
1. 제한이 없는 상태에서 로그인 성공 여부를 먼저 확인합니다.
|
||||
2. `devfront`에서 대상 RP에 `tenant_access_restricted`와 `allowed_tenants`를 설정합니다.
|
||||
3. 허용된 tenant 사용자로 로그인해 정상 성공 여부를 확인합니다.
|
||||
4. 허용되지 않은 tenant 사용자로 로그인해 `userfront`의 `/ko/error?error=tenant_not_allowed...` 화면으로 이동하는지 확인합니다.
|
||||
|
||||
### 기대 동작
|
||||
|
||||
- `tenant_not_allowed`는 Baron SSO backend가 `403`으로 반환합니다.
|
||||
- headless demo는 이 응답을 감지해 `userfront` 에러 화면으로 브라우저를 이동시킵니다.
|
||||
- 따라서 브라우저 팝업으로 `Invalid URL`이 보인다면 demo 쪽 에러 처리 누락을 먼저 의심해야 합니다.
|
||||
|
||||
### 로그 확인 포인트
|
||||
|
||||
```bash
|
||||
docker logs --tail 100 headless-login-demo
|
||||
docker logs --tail 100 baron_backend
|
||||
```
|
||||
|
||||
- `headless-login-demo`
|
||||
- consent 단계에서 `tenant_not_allowed`를 받아 `errorUrl`로 변환했는지 확인
|
||||
- `baron_backend`
|
||||
- `GET /api/v1/auth/consent` 또는 `POST /api/v1/auth/consent/accept`가 `403`인지 확인
|
||||
- 해당 응답 body에 `code=tenant_not_allowed`가 포함되는지 확인
|
||||
BIN
baron-sso_login_guide/setup-step1-example.png
Normal file
BIN
baron-sso_login_guide/setup-step1-example.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 191 KiB |
BIN
baron-sso_login_guide/setup-step2-example.png
Normal file
BIN
baron-sso_login_guide/setup-step2-example.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 186 KiB |
BIN
baron-sso_login_guide/setup-step3-example.png
Normal file
BIN
baron-sso_login_guide/setup-step3-example.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 95 KiB |
File diff suppressed because it is too large
Load Diff
@@ -1,211 +0,0 @@
|
||||
('D:\\이태훈\\22전산자산조사\\ITAM\\dist\\pc_agent.exe',
|
||||
True,
|
||||
False,
|
||||
False,
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\PyInstaller\\bootloader\\images\\icon-console.ico',
|
||||
None,
|
||||
False,
|
||||
False,
|
||||
b'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n<assembly xmlns='
|
||||
b'"urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">\n <trustInfo x'
|
||||
b'mlns="urn:schemas-microsoft-com:asm.v3">\n <security>\n <requested'
|
||||
b'Privileges>\n <requestedExecutionLevel level="asInvoker" uiAccess='
|
||||
b'"false"/>\n </requestedPrivileges>\n </security>\n </trustInfo>\n '
|
||||
b'<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">\n <'
|
||||
b'application>\n <supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f'
|
||||
b'0}"/>\n <supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/>\n '
|
||||
b' <supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}"/>\n <s'
|
||||
b'upportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}"/>\n <supporte'
|
||||
b'dOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>\n </application>\n <'
|
||||
b'/compatibility>\n <application xmlns="urn:schemas-microsoft-com:asm.v3">'
|
||||
b'\n <windowsSettings>\n <longPathAware xmlns="http://schemas.micros'
|
||||
b'oft.com/SMI/2016/WindowsSettings">true</longPathAware>\n </windowsSett'
|
||||
b'ings>\n </application>\n <dependency>\n <dependentAssembly>\n <ass'
|
||||
b'emblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version='
|
||||
b'"6.0.0.0" processorArchitecture="*" publicKeyToken="6595b64144ccf1df" langua'
|
||||
b'ge="*"/>\n </dependentAssembly>\n </dependency>\n</assembly>',
|
||||
True,
|
||||
False,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
'D:\\이태훈\\22전산자산조사\\ITAM\\build\\pc_agent\\pc_agent.pkg',
|
||||
[('pyi-contents-directory _internal', '', 'OPTION'),
|
||||
('PYZ-00.pyz', 'D:\\이태훈\\22전산자산조사\\ITAM\\build\\pc_agent\\PYZ-00.pyz', 'PYZ'),
|
||||
('struct',
|
||||
'D:\\이태훈\\22전산자산조사\\ITAM\\build\\pc_agent\\localpycs\\struct.pyc',
|
||||
'PYMODULE'),
|
||||
('pyimod01_archive',
|
||||
'D:\\이태훈\\22전산자산조사\\ITAM\\build\\pc_agent\\localpycs\\pyimod01_archive.pyc',
|
||||
'PYMODULE'),
|
||||
('pyimod02_importers',
|
||||
'D:\\이태훈\\22전산자산조사\\ITAM\\build\\pc_agent\\localpycs\\pyimod02_importers.pyc',
|
||||
'PYMODULE'),
|
||||
('pyimod03_ctypes',
|
||||
'D:\\이태훈\\22전산자산조사\\ITAM\\build\\pc_agent\\localpycs\\pyimod03_ctypes.pyc',
|
||||
'PYMODULE'),
|
||||
('pyimod04_pywin32',
|
||||
'D:\\이태훈\\22전산자산조사\\ITAM\\build\\pc_agent\\localpycs\\pyimod04_pywin32.pyc',
|
||||
'PYMODULE'),
|
||||
('pyiboot01_bootstrap',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\PyInstaller\\loader\\pyiboot01_bootstrap.py',
|
||||
'PYSOURCE'),
|
||||
('pyi_rth_inspect',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\PyInstaller\\hooks\\rthooks\\pyi_rth_inspect.py',
|
||||
'PYSOURCE'),
|
||||
('pyi_rth_pkgutil',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\PyInstaller\\hooks\\rthooks\\pyi_rth_pkgutil.py',
|
||||
'PYSOURCE'),
|
||||
('pyi_rth_multiprocessing',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\PyInstaller\\hooks\\rthooks\\pyi_rth_multiprocessing.py',
|
||||
'PYSOURCE'),
|
||||
('pyi_rth_cryptography_openssl',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\_pyinstaller_hooks_contrib\\rthooks\\pyi_rth_cryptography_openssl.py',
|
||||
'PYSOURCE'),
|
||||
('pyi_rth_pywintypes',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\_pyinstaller_hooks_contrib\\rthooks\\pyi_rth_pywintypes.py',
|
||||
'PYSOURCE'),
|
||||
('pyi_rth_pythoncom',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\_pyinstaller_hooks_contrib\\rthooks\\pyi_rth_pythoncom.py',
|
||||
'PYSOURCE'),
|
||||
('pc_agent', 'D:\\이태훈\\22전산자산조사\\ITAM\\pc_agent.py', 'PYSOURCE'),
|
||||
('python312.dll',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\python312.dll',
|
||||
'BINARY'),
|
||||
('pywin32_system32\\pywintypes312.dll',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\pywin32_system32\\pywintypes312.dll',
|
||||
'BINARY'),
|
||||
('pywin32_system32\\pythoncom312.dll',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\pywin32_system32\\pythoncom312.dll',
|
||||
'BINARY'),
|
||||
('select.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\DLLs\\select.pyd',
|
||||
'EXTENSION'),
|
||||
('_multiprocessing.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\DLLs\\_multiprocessing.pyd',
|
||||
'EXTENSION'),
|
||||
('pyexpat.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\DLLs\\pyexpat.pyd',
|
||||
'EXTENSION'),
|
||||
('_ssl.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\DLLs\\_ssl.pyd',
|
||||
'EXTENSION'),
|
||||
('_hashlib.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\DLLs\\_hashlib.pyd',
|
||||
'EXTENSION'),
|
||||
('unicodedata.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\DLLs\\unicodedata.pyd',
|
||||
'EXTENSION'),
|
||||
('_decimal.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\DLLs\\_decimal.pyd',
|
||||
'EXTENSION'),
|
||||
('_lzma.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\DLLs\\_lzma.pyd',
|
||||
'EXTENSION'),
|
||||
('_bz2.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\DLLs\\_bz2.pyd',
|
||||
'EXTENSION'),
|
||||
('_ctypes.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\DLLs\\_ctypes.pyd',
|
||||
'EXTENSION'),
|
||||
('_queue.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\DLLs\\_queue.pyd',
|
||||
'EXTENSION'),
|
||||
('_wmi.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\DLLs\\_wmi.pyd',
|
||||
'EXTENSION'),
|
||||
('_socket.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\DLLs\\_socket.pyd',
|
||||
'EXTENSION'),
|
||||
('_overlapped.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\DLLs\\_overlapped.pyd',
|
||||
'EXTENSION'),
|
||||
('_asyncio.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\DLLs\\_asyncio.pyd',
|
||||
'EXTENSION'),
|
||||
('_cffi_backend.cp312-win_amd64.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\_cffi_backend.cp312-win_amd64.pyd',
|
||||
'EXTENSION'),
|
||||
('cryptography\\hazmat\\bindings\\_rust.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\cryptography\\hazmat\\bindings\\_rust.pyd',
|
||||
'EXTENSION'),
|
||||
('charset_normalizer\\md__mypyc.cp312-win_amd64.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\charset_normalizer\\md__mypyc.cp312-win_amd64.pyd',
|
||||
'EXTENSION'),
|
||||
('charset_normalizer\\md.cp312-win_amd64.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\charset_normalizer\\md.cp312-win_amd64.pyd',
|
||||
'EXTENSION'),
|
||||
('win32\\_win32sysloader.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\win32\\_win32sysloader.pyd',
|
||||
'EXTENSION'),
|
||||
('win32\\win32api.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\win32\\win32api.pyd',
|
||||
'EXTENSION'),
|
||||
('Pythonwin\\win32ui.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\Pythonwin\\win32ui.pyd',
|
||||
'EXTENSION'),
|
||||
('win32\\win32event.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\win32\\win32event.pyd',
|
||||
'EXTENSION'),
|
||||
('win32\\win32trace.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\win32\\win32trace.pyd',
|
||||
'EXTENSION'),
|
||||
('VCRUNTIME140.dll',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\VCRUNTIME140.dll',
|
||||
'BINARY'),
|
||||
('VCRUNTIME140_1.dll',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\VCRUNTIME140_1.dll',
|
||||
'BINARY'),
|
||||
('libssl-3.dll',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\DLLs\\libssl-3.dll',
|
||||
'BINARY'),
|
||||
('libcrypto-3.dll',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\DLLs\\libcrypto-3.dll',
|
||||
'BINARY'),
|
||||
('libffi-8.dll',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\DLLs\\libffi-8.dll',
|
||||
'BINARY'),
|
||||
('python3.dll',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\python3.dll',
|
||||
'BINARY'),
|
||||
('Pythonwin\\mfc140u.dll',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\Pythonwin\\mfc140u.dll',
|
||||
'BINARY'),
|
||||
('certifi\\cacert.pem',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\certifi\\cacert.pem',
|
||||
'DATA'),
|
||||
('certifi\\py.typed',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\certifi\\py.typed',
|
||||
'DATA'),
|
||||
('cryptography-45.0.2.dist-info\\licenses\\LICENSE.BSD',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\cryptography-45.0.2.dist-info\\licenses\\LICENSE.BSD',
|
||||
'DATA'),
|
||||
('cryptography-45.0.2.dist-info\\licenses\\LICENSE',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\cryptography-45.0.2.dist-info\\licenses\\LICENSE',
|
||||
'DATA'),
|
||||
('cryptography-45.0.2.dist-info\\RECORD',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\cryptography-45.0.2.dist-info\\RECORD',
|
||||
'DATA'),
|
||||
('cryptography-45.0.2.dist-info\\METADATA',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\cryptography-45.0.2.dist-info\\METADATA',
|
||||
'DATA'),
|
||||
('cryptography-45.0.2.dist-info\\WHEEL',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\cryptography-45.0.2.dist-info\\WHEEL',
|
||||
'DATA'),
|
||||
('cryptography-45.0.2.dist-info\\INSTALLER',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\cryptography-45.0.2.dist-info\\INSTALLER',
|
||||
'DATA'),
|
||||
('cryptography-45.0.2.dist-info\\licenses\\LICENSE.APACHE',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\cryptography-45.0.2.dist-info\\licenses\\LICENSE.APACHE',
|
||||
'DATA'),
|
||||
('base_library.zip',
|
||||
'D:\\이태훈\\22전산자산조사\\ITAM\\build\\pc_agent\\base_library.zip',
|
||||
'DATA')],
|
||||
[],
|
||||
False,
|
||||
False,
|
||||
1779102721,
|
||||
[('run.exe',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\PyInstaller\\bootloader\\Windows-64bit-intel\\run.exe',
|
||||
'EXECUTABLE')],
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\python312.dll')
|
||||
@@ -1,189 +0,0 @@
|
||||
('D:\\이태훈\\22전산자산조사\\ITAM\\build\\pc_agent\\pc_agent.pkg',
|
||||
{'BINARY': True,
|
||||
'DATA': True,
|
||||
'EXECUTABLE': True,
|
||||
'EXTENSION': True,
|
||||
'PYMODULE': True,
|
||||
'PYSOURCE': True,
|
||||
'PYZ': False,
|
||||
'SPLASH': True,
|
||||
'SYMLINK': False},
|
||||
[('pyi-contents-directory _internal', '', 'OPTION'),
|
||||
('PYZ-00.pyz', 'D:\\이태훈\\22전산자산조사\\ITAM\\build\\pc_agent\\PYZ-00.pyz', 'PYZ'),
|
||||
('struct',
|
||||
'D:\\이태훈\\22전산자산조사\\ITAM\\build\\pc_agent\\localpycs\\struct.pyc',
|
||||
'PYMODULE'),
|
||||
('pyimod01_archive',
|
||||
'D:\\이태훈\\22전산자산조사\\ITAM\\build\\pc_agent\\localpycs\\pyimod01_archive.pyc',
|
||||
'PYMODULE'),
|
||||
('pyimod02_importers',
|
||||
'D:\\이태훈\\22전산자산조사\\ITAM\\build\\pc_agent\\localpycs\\pyimod02_importers.pyc',
|
||||
'PYMODULE'),
|
||||
('pyimod03_ctypes',
|
||||
'D:\\이태훈\\22전산자산조사\\ITAM\\build\\pc_agent\\localpycs\\pyimod03_ctypes.pyc',
|
||||
'PYMODULE'),
|
||||
('pyimod04_pywin32',
|
||||
'D:\\이태훈\\22전산자산조사\\ITAM\\build\\pc_agent\\localpycs\\pyimod04_pywin32.pyc',
|
||||
'PYMODULE'),
|
||||
('pyiboot01_bootstrap',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\PyInstaller\\loader\\pyiboot01_bootstrap.py',
|
||||
'PYSOURCE'),
|
||||
('pyi_rth_inspect',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\PyInstaller\\hooks\\rthooks\\pyi_rth_inspect.py',
|
||||
'PYSOURCE'),
|
||||
('pyi_rth_pkgutil',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\PyInstaller\\hooks\\rthooks\\pyi_rth_pkgutil.py',
|
||||
'PYSOURCE'),
|
||||
('pyi_rth_multiprocessing',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\PyInstaller\\hooks\\rthooks\\pyi_rth_multiprocessing.py',
|
||||
'PYSOURCE'),
|
||||
('pyi_rth_cryptography_openssl',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\_pyinstaller_hooks_contrib\\rthooks\\pyi_rth_cryptography_openssl.py',
|
||||
'PYSOURCE'),
|
||||
('pyi_rth_pywintypes',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\_pyinstaller_hooks_contrib\\rthooks\\pyi_rth_pywintypes.py',
|
||||
'PYSOURCE'),
|
||||
('pyi_rth_pythoncom',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\_pyinstaller_hooks_contrib\\rthooks\\pyi_rth_pythoncom.py',
|
||||
'PYSOURCE'),
|
||||
('pc_agent', 'D:\\이태훈\\22전산자산조사\\ITAM\\pc_agent.py', 'PYSOURCE'),
|
||||
('python312.dll',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\python312.dll',
|
||||
'BINARY'),
|
||||
('pywin32_system32\\pywintypes312.dll',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\pywin32_system32\\pywintypes312.dll',
|
||||
'BINARY'),
|
||||
('pywin32_system32\\pythoncom312.dll',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\pywin32_system32\\pythoncom312.dll',
|
||||
'BINARY'),
|
||||
('select.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\DLLs\\select.pyd',
|
||||
'EXTENSION'),
|
||||
('_multiprocessing.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\DLLs\\_multiprocessing.pyd',
|
||||
'EXTENSION'),
|
||||
('pyexpat.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\DLLs\\pyexpat.pyd',
|
||||
'EXTENSION'),
|
||||
('_ssl.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\DLLs\\_ssl.pyd',
|
||||
'EXTENSION'),
|
||||
('_hashlib.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\DLLs\\_hashlib.pyd',
|
||||
'EXTENSION'),
|
||||
('unicodedata.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\DLLs\\unicodedata.pyd',
|
||||
'EXTENSION'),
|
||||
('_decimal.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\DLLs\\_decimal.pyd',
|
||||
'EXTENSION'),
|
||||
('_lzma.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\DLLs\\_lzma.pyd',
|
||||
'EXTENSION'),
|
||||
('_bz2.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\DLLs\\_bz2.pyd',
|
||||
'EXTENSION'),
|
||||
('_ctypes.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\DLLs\\_ctypes.pyd',
|
||||
'EXTENSION'),
|
||||
('_queue.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\DLLs\\_queue.pyd',
|
||||
'EXTENSION'),
|
||||
('_wmi.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\DLLs\\_wmi.pyd',
|
||||
'EXTENSION'),
|
||||
('_socket.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\DLLs\\_socket.pyd',
|
||||
'EXTENSION'),
|
||||
('_overlapped.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\DLLs\\_overlapped.pyd',
|
||||
'EXTENSION'),
|
||||
('_asyncio.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\DLLs\\_asyncio.pyd',
|
||||
'EXTENSION'),
|
||||
('_cffi_backend.cp312-win_amd64.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\_cffi_backend.cp312-win_amd64.pyd',
|
||||
'EXTENSION'),
|
||||
('cryptography\\hazmat\\bindings\\_rust.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\cryptography\\hazmat\\bindings\\_rust.pyd',
|
||||
'EXTENSION'),
|
||||
('charset_normalizer\\md__mypyc.cp312-win_amd64.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\charset_normalizer\\md__mypyc.cp312-win_amd64.pyd',
|
||||
'EXTENSION'),
|
||||
('charset_normalizer\\md.cp312-win_amd64.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\charset_normalizer\\md.cp312-win_amd64.pyd',
|
||||
'EXTENSION'),
|
||||
('win32\\_win32sysloader.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\win32\\_win32sysloader.pyd',
|
||||
'EXTENSION'),
|
||||
('win32\\win32api.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\win32\\win32api.pyd',
|
||||
'EXTENSION'),
|
||||
('Pythonwin\\win32ui.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\Pythonwin\\win32ui.pyd',
|
||||
'EXTENSION'),
|
||||
('win32\\win32event.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\win32\\win32event.pyd',
|
||||
'EXTENSION'),
|
||||
('win32\\win32trace.pyd',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\win32\\win32trace.pyd',
|
||||
'EXTENSION'),
|
||||
('VCRUNTIME140.dll',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\VCRUNTIME140.dll',
|
||||
'BINARY'),
|
||||
('VCRUNTIME140_1.dll',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\VCRUNTIME140_1.dll',
|
||||
'BINARY'),
|
||||
('libssl-3.dll',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\DLLs\\libssl-3.dll',
|
||||
'BINARY'),
|
||||
('libcrypto-3.dll',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\DLLs\\libcrypto-3.dll',
|
||||
'BINARY'),
|
||||
('libffi-8.dll',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\DLLs\\libffi-8.dll',
|
||||
'BINARY'),
|
||||
('python3.dll',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\python3.dll',
|
||||
'BINARY'),
|
||||
('Pythonwin\\mfc140u.dll',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\Pythonwin\\mfc140u.dll',
|
||||
'BINARY'),
|
||||
('certifi\\cacert.pem',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\certifi\\cacert.pem',
|
||||
'DATA'),
|
||||
('certifi\\py.typed',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\certifi\\py.typed',
|
||||
'DATA'),
|
||||
('cryptography-45.0.2.dist-info\\licenses\\LICENSE.BSD',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\cryptography-45.0.2.dist-info\\licenses\\LICENSE.BSD',
|
||||
'DATA'),
|
||||
('cryptography-45.0.2.dist-info\\licenses\\LICENSE',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\cryptography-45.0.2.dist-info\\licenses\\LICENSE',
|
||||
'DATA'),
|
||||
('cryptography-45.0.2.dist-info\\RECORD',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\cryptography-45.0.2.dist-info\\RECORD',
|
||||
'DATA'),
|
||||
('cryptography-45.0.2.dist-info\\METADATA',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\cryptography-45.0.2.dist-info\\METADATA',
|
||||
'DATA'),
|
||||
('cryptography-45.0.2.dist-info\\WHEEL',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\cryptography-45.0.2.dist-info\\WHEEL',
|
||||
'DATA'),
|
||||
('cryptography-45.0.2.dist-info\\INSTALLER',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\cryptography-45.0.2.dist-info\\INSTALLER',
|
||||
'DATA'),
|
||||
('cryptography-45.0.2.dist-info\\licenses\\LICENSE.APACHE',
|
||||
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\cryptography-45.0.2.dist-info\\licenses\\LICENSE.APACHE',
|
||||
'DATA'),
|
||||
('base_library.zip',
|
||||
'D:\\이태훈\\22전산자산조사\\ITAM\\build\\pc_agent\\base_library.zip',
|
||||
'DATA')],
|
||||
'python312.dll',
|
||||
False,
|
||||
False,
|
||||
False,
|
||||
[],
|
||||
None,
|
||||
None,
|
||||
None)
|
||||
Binary file not shown.
File diff suppressed because it is too large
Load Diff
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,58 +0,0 @@
|
||||
|
||||
This file lists modules PyInstaller was not able to find. This does not
|
||||
necessarily mean these modules are required for running your program. Both
|
||||
Python's standard library and 3rd-party Python packages often conditionally
|
||||
import optional modules, some of which may be available only on certain
|
||||
platforms.
|
||||
|
||||
Types of import:
|
||||
* top-level: imported at the top-level - look at these first
|
||||
* conditional: imported within an if-statement
|
||||
* delayed: imported within a function
|
||||
* optional: imported within a try-except-statement
|
||||
|
||||
IMPORTANT: Do NOT post this list to the issue-tracker. Use it as a basis for
|
||||
tracking down the missing module yourself. Thanks!
|
||||
|
||||
missing module named pwd - imported by posixpath (delayed, conditional, optional), shutil (delayed, optional), tarfile (optional), pathlib (delayed, optional), subprocess (delayed, conditional, optional), netrc (delayed, conditional), getpass (delayed)
|
||||
missing module named grp - imported by shutil (delayed, optional), tarfile (optional), pathlib (delayed, optional), subprocess (delayed, conditional, optional)
|
||||
missing module named _posixsubprocess - imported by subprocess (conditional), multiprocessing.util (delayed)
|
||||
missing module named fcntl - imported by subprocess (optional)
|
||||
missing module named _posixshmem - imported by multiprocessing.resource_tracker (conditional), multiprocessing.shared_memory (conditional)
|
||||
missing module named _scproxy - imported by urllib.request (conditional)
|
||||
missing module named termios - imported by getpass (optional)
|
||||
missing module named multiprocessing.BufferTooShort - imported by multiprocessing (top-level), multiprocessing.connection (top-level)
|
||||
missing module named multiprocessing.AuthenticationError - imported by multiprocessing (top-level), multiprocessing.connection (top-level)
|
||||
missing module named _frozen_importlib_external - imported by importlib._bootstrap (delayed), importlib (optional), importlib.abc (optional), zipimport (top-level)
|
||||
excluded module named _frozen_importlib - imported by importlib (optional), importlib.abc (optional), zipimport (top-level)
|
||||
missing module named posix - imported by os (conditional, optional), posixpath (optional), shutil (conditional), importlib._bootstrap_external (conditional)
|
||||
missing module named resource - imported by posix (top-level)
|
||||
missing module named multiprocessing.get_context - imported by multiprocessing (top-level), multiprocessing.pool (top-level), multiprocessing.managers (top-level), multiprocessing.sharedctypes (top-level)
|
||||
missing module named multiprocessing.TimeoutError - imported by multiprocessing (top-level), multiprocessing.pool (top-level)
|
||||
missing module named multiprocessing.set_start_method - imported by multiprocessing (top-level), multiprocessing.spawn (top-level)
|
||||
missing module named multiprocessing.get_start_method - imported by multiprocessing (top-level), multiprocessing.spawn (top-level)
|
||||
missing module named pyimod02_importers - imported by C:\Users\User\AppData\Local\Programs\Python\Python312\Lib\site-packages\PyInstaller\hooks\rthooks\pyi_rth_pkgutil.py (delayed)
|
||||
missing module named collections.Callable - imported by collections (optional), socks (optional)
|
||||
missing module named vms_lib - imported by platform (delayed, optional)
|
||||
missing module named 'java.lang' - imported by platform (delayed, optional)
|
||||
missing module named java - imported by platform (delayed)
|
||||
missing module named _winreg - imported by platform (delayed, optional)
|
||||
missing module named simplejson - imported by requests.compat (conditional, optional)
|
||||
missing module named dummy_threading - imported by requests.cookies (optional)
|
||||
missing module named asyncio.DefaultEventLoopPolicy - imported by asyncio (delayed, conditional), asyncio.events (delayed, conditional)
|
||||
missing module named annotationlib - imported by typing_extensions (conditional)
|
||||
missing module named 'h2.events' - imported by urllib3.http2.connection (top-level)
|
||||
missing module named 'h2.connection' - imported by urllib3.http2.connection (top-level)
|
||||
missing module named h2 - imported by urllib3.http2.connection (top-level)
|
||||
missing module named zstandard - imported by urllib3.util.request (optional), urllib3.response (optional)
|
||||
missing module named brotli - imported by urllib3.util.request (optional), urllib3.response (optional)
|
||||
missing module named brotlicffi - imported by urllib3.util.request (optional), urllib3.response (optional)
|
||||
missing module named win_inet_pton - imported by socks (conditional, optional)
|
||||
missing module named bcrypt - imported by cryptography.hazmat.primitives.serialization.ssh (optional)
|
||||
missing module named cryptography.x509.UnsupportedExtension - imported by cryptography.x509 (optional), urllib3.contrib.pyopenssl (optional)
|
||||
missing module named 'OpenSSL.crypto' - imported by urllib3.contrib.pyopenssl (delayed, conditional)
|
||||
missing module named OpenSSL - imported by urllib3.contrib.pyopenssl (top-level)
|
||||
missing module named 'pyodide.ffi' - imported by urllib3.contrib.emscripten.fetch (delayed, optional)
|
||||
missing module named pyodide - imported by urllib3.contrib.emscripten.fetch (top-level)
|
||||
missing module named js - imported by urllib3.contrib.emscripten.fetch (top-level)
|
||||
missing module named 'win32com.gen_py' - imported by win32com (conditional, optional)
|
||||
File diff suppressed because it is too large
Load Diff
73
docker-compose.prod.yaml
Normal file
73
docker-compose.prod.yaml
Normal file
@@ -0,0 +1,73 @@
|
||||
services:
|
||||
backend:
|
||||
image: itam-backend:prod
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile.backend.prod
|
||||
container_name: itam-backend
|
||||
working_dir: /app
|
||||
env_file:
|
||||
- .env
|
||||
environment:
|
||||
NODE_ENV: production
|
||||
PORT: 3000
|
||||
volumes:
|
||||
- ./uploads:/app/uploads
|
||||
- ./map_config.json:/app/map_config.json:ro
|
||||
expose:
|
||||
- "3000"
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
start_period: 40s
|
||||
|
||||
frontend:
|
||||
image: itam-frontend:prod
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile.frontend.prod
|
||||
container_name: itam-frontend
|
||||
expose:
|
||||
- "80"
|
||||
restart: unless-stopped
|
||||
|
||||
nginx:
|
||||
image: nginx:stable-alpine
|
||||
container_name: itam-nginx
|
||||
ports:
|
||||
- "9090:80"
|
||||
volumes:
|
||||
- ./docker/nginx/default.conf:/etc/nginx/conf.d/default.conf
|
||||
- ./logs/nginx:/var/log/nginx
|
||||
depends_on:
|
||||
backend:
|
||||
condition: service_healthy
|
||||
frontend:
|
||||
condition: service_started
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://localhost:80/"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
start_period: 20s
|
||||
|
||||
database:
|
||||
image: mysql:latest
|
||||
container_name: itam-mysql
|
||||
ports:
|
||||
- "3306:3306"
|
||||
environment:
|
||||
- MYSQL_ROOT_PASSWORD=itam1234 # 여기 직접 기입
|
||||
- MYSQL_DATABASE=itam
|
||||
- MYSQL_USER=itam
|
||||
- MYSQL_PASSWORD=itam1234
|
||||
volumes:
|
||||
- ./mysql_data:/var/lib/mysql
|
||||
restart: always
|
||||
command:
|
||||
- --character-set-server=utf8mb4
|
||||
- --collation-server=utf8mb4_unicode_ci
|
||||
62
docker-compose.test.yaml
Normal file
62
docker-compose.test.yaml
Normal file
@@ -0,0 +1,62 @@
|
||||
# Local testing compose file - uses relative paths and build contexts
|
||||
# Usage: docker compose -f docker-compose.test.yaml up --build
|
||||
|
||||
services:
|
||||
backend:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile.backend.prod
|
||||
container_name: itam-backend-test
|
||||
working_dir: /app
|
||||
env_file:
|
||||
- .env
|
||||
environment:
|
||||
NODE_ENV: development
|
||||
PORT: 3000
|
||||
DB_HOST: ${DB_HOST:-172.16.8.151}
|
||||
DB_PORT: ${DB_PORT:-3306}
|
||||
DB_USER: ${DB_USER:-root}
|
||||
DB_PASS: ${DB_PASS:-}
|
||||
DB_NAME: ${DB_NAME:-itam}
|
||||
ports:
|
||||
- "3000:3000"
|
||||
volumes:
|
||||
- ./uploads:/app/uploads
|
||||
- ./map_config.json:/app/map_config.json:ro
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
start_period: 40s
|
||||
|
||||
frontend:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile.frontend.prod
|
||||
container_name: itam-frontend-test
|
||||
expose:
|
||||
- "80"
|
||||
restart: unless-stopped
|
||||
|
||||
nginx:
|
||||
image: nginx:stable-alpine
|
||||
container_name: itam-nginx-test
|
||||
ports:
|
||||
- "8080:80"
|
||||
volumes:
|
||||
- ./docker/nginx/default.conf:/etc/nginx/conf.d/default.conf:ro
|
||||
- ./logs/nginx:/var/log/nginx
|
||||
depends_on:
|
||||
backend:
|
||||
condition: service_healthy
|
||||
frontend:
|
||||
condition: service_started
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://localhost:80/"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
start_period: 20s
|
||||
48
docker-compose.yaml
Normal file
48
docker-compose.yaml
Normal file
@@ -0,0 +1,48 @@
|
||||
services:
|
||||
backend:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile.backend
|
||||
container_name: dachs-backend
|
||||
working_dir: /app
|
||||
env_file:
|
||||
- .env
|
||||
environment:
|
||||
DB_HOST: ${DB_HOST}
|
||||
DB_PORT: ${DB_PORT}
|
||||
DB_USER: ${DB_USER}
|
||||
DB_PASS: ${DB_PASS}
|
||||
DB_NAME: ${DB_NAME}
|
||||
PORT: 3000
|
||||
ports:
|
||||
- "3000:3000"
|
||||
volumes:
|
||||
- ./:/app
|
||||
- backend_node_modules:/app/node_modules
|
||||
- ./uploads:/app/uploads
|
||||
- ./map_config.json:/app/map_config.json
|
||||
command: npm run server
|
||||
restart: unless-stopped
|
||||
|
||||
frontend:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile.frontend
|
||||
container_name: dachs-frontend
|
||||
working_dir: /app
|
||||
depends_on:
|
||||
- backend
|
||||
environment:
|
||||
CHOKIDAR_USEPOLLING: "true"
|
||||
VITE_DEV_PROXY_TARGET: http://backend:3000
|
||||
ports:
|
||||
- "8080:8080"
|
||||
volumes:
|
||||
- ./:/app
|
||||
- frontend_node_modules:/app/node_modules
|
||||
command: npm run dev -- --host 0.0.0.0
|
||||
restart: unless-stopped
|
||||
|
||||
volumes:
|
||||
backend_node_modules:
|
||||
frontend_node_modules:
|
||||
55
docker/frontend/default.conf
Normal file
55
docker/frontend/default.conf
Normal file
@@ -0,0 +1,55 @@
|
||||
server {
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
server_name _;
|
||||
|
||||
root /usr/share/nginx/html;
|
||||
|
||||
# Logging
|
||||
access_log /var/log/nginx/frontend-access.log main;
|
||||
error_log /var/log/nginx/frontend-error.log warn;
|
||||
|
||||
# Security headers
|
||||
add_header X-Frame-Options "SAMEORIGIN" always;
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
add_header X-XSS-Protection "1; mode=block" always;
|
||||
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
|
||||
|
||||
# Gzip compression
|
||||
gzip on;
|
||||
gzip_types text/plain text/css text/xml text/javascript
|
||||
application/x-javascript application/xml+rss
|
||||
application/json application/javascript;
|
||||
gzip_min_length 1000;
|
||||
|
||||
# Serve static files with SPA fallback
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
# Cache static assets (60 days)
|
||||
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|webp|woff|woff2|ttf|eot)$ {
|
||||
expires 60d;
|
||||
add_header Cache-Control "public, immutable";
|
||||
}
|
||||
|
||||
# Don't cache HTML files
|
||||
location ~* \.html$ {
|
||||
expires -1;
|
||||
add_header Cache-Control "no-cache, no-store, must-revalidate";
|
||||
}
|
||||
|
||||
# Health check
|
||||
location /health {
|
||||
access_log off;
|
||||
return 200 "OK\n";
|
||||
add_header Content-Type text/plain;
|
||||
}
|
||||
|
||||
# Deny access to sensitive files
|
||||
location ~ /\. {
|
||||
deny all;
|
||||
access_log off;
|
||||
log_not_found off;
|
||||
}
|
||||
}
|
||||
16
docker/mysql/init/README.md
Normal file
16
docker/mysql/init/README.md
Normal file
@@ -0,0 +1,16 @@
|
||||
# MySQL init directory
|
||||
|
||||
This directory is kept as a legacy hook for file-based MySQL initialization.
|
||||
|
||||
Current production path in this repository is not file-based import.
|
||||
The live Docker flow uses the `db-bootstrap` service in `docker-compose.yaml` to stream data from the external source DB into the internal `db` container.
|
||||
|
||||
Use this directory only if you intentionally switch back to `docker-entrypoint-initdb.d` style initialization.
|
||||
|
||||
If you do that, typical naming would be:
|
||||
|
||||
- `01_schema.sql`
|
||||
- `02_seed.sql`
|
||||
- or a single `01_itam_dump.sql`
|
||||
|
||||
Remember that files in this directory are executed automatically by the MySQL container only on the first initialization of the data volume.
|
||||
101
docker/nginx/default.conf
Normal file
101
docker/nginx/default.conf
Normal file
@@ -0,0 +1,101 @@
|
||||
upstream backend {
|
||||
server backend:3000;
|
||||
}
|
||||
|
||||
upstream frontend {
|
||||
server frontend:80;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
server_name _;
|
||||
|
||||
# Client upload size limit (adjust as needed)
|
||||
client_max_body_size 100M;
|
||||
|
||||
# Logging
|
||||
access_log /var/log/nginx/access.log main;
|
||||
error_log /var/log/nginx/error.log warn;
|
||||
|
||||
# Security headers
|
||||
add_header X-Frame-Options "SAMEORIGIN" always;
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
add_header X-XSS-Protection "1; mode=block" always;
|
||||
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
|
||||
|
||||
# Gzip compression
|
||||
gzip on;
|
||||
gzip_types text/plain text/css text/xml text/javascript
|
||||
application/x-javascript application/xml+rss
|
||||
application/json application/javascript;
|
||||
gzip_min_length 1000;
|
||||
|
||||
# Forward all app requests to the frontend container
|
||||
location / {
|
||||
proxy_pass http://frontend;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_http_version 1.1;
|
||||
}
|
||||
|
||||
# API proxy to backend
|
||||
location /api/ {
|
||||
proxy_pass http://backend/api/;
|
||||
|
||||
# Preserve original request information
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header X-Forwarded-Host $server_name;
|
||||
proxy_set_header X-Forwarded-Port $server_port;
|
||||
|
||||
# Connection settings
|
||||
proxy_connect_timeout 60s;
|
||||
proxy_send_timeout 60s;
|
||||
proxy_read_timeout 60s;
|
||||
|
||||
# Buffering settings
|
||||
proxy_buffering on;
|
||||
proxy_buffer_size 4k;
|
||||
proxy_buffers 8 4k;
|
||||
proxy_busy_buffers_size 8k;
|
||||
}
|
||||
|
||||
# Uploads proxy to backend
|
||||
location /uploads/ {
|
||||
proxy_pass http://backend/uploads/;
|
||||
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
|
||||
# Cache uploads
|
||||
expires 30d;
|
||||
add_header Cache-Control "public";
|
||||
}
|
||||
|
||||
# Health check endpoint (for monitoring)
|
||||
location /health {
|
||||
access_log off;
|
||||
return 200 "OK\n";
|
||||
add_header Content-Type text/plain;
|
||||
}
|
||||
|
||||
# Deny access to sensitive files
|
||||
location ~ /\. {
|
||||
deny all;
|
||||
access_log off;
|
||||
log_not_found off;
|
||||
}
|
||||
|
||||
location ~ ~$ {
|
||||
deny all;
|
||||
access_log off;
|
||||
log_not_found off;
|
||||
}
|
||||
}
|
||||
226
docs/itam_cicd_setup.md
Normal file
226
docs/itam_cicd_setup.md
Normal file
@@ -0,0 +1,226 @@
|
||||
# ITAM CI/CD 설정 가이드
|
||||
|
||||
## 1. 문서 목적
|
||||
|
||||
이 문서는 현재 ITAM 저장소에 구성된 CI/CD 파일을 실제 운영에 연결하기 위해 필요한 기준을 정리한 가이드다.
|
||||
|
||||
대상 범위는 아래와 같다.
|
||||
|
||||
1. Gitea Actions workflow 역할
|
||||
2. Gitea Variables / Secrets 설정값
|
||||
3. 운영 서버 배포 디렉토리 기준
|
||||
4. 운영 영속 경로 기준
|
||||
5. production deploy 실행 전 확인 사항
|
||||
|
||||
---
|
||||
|
||||
## 2. 현재 CI/CD 구성
|
||||
|
||||
현재 `.gitea/workflows`에는 ITAM 관련 workflow만 남겨둔 상태다.
|
||||
|
||||
1. `itam_code_check.yml`
|
||||
2. `itam_docker_build_check.yml`
|
||||
3. `itam_production_deploy.yml`
|
||||
|
||||
각 workflow의 역할은 아래와 같다.
|
||||
|
||||
1. `itam_code_check.yml`: TypeScript/Vite build와 compose 문법 검증
|
||||
2. `itam_docker_build_check.yml`: 운영용 Docker 이미지 빌드 가능 여부 검증
|
||||
3. `itam_production_deploy.yml`: 운영 서버에 SSH 접속 후 실제 배포 수행
|
||||
|
||||
현재 배포 흐름은 아래와 같다.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
DEV["Developer Push or Manual Run"] --> CODE["ITAM Code Check"]
|
||||
CODE --> BUILD["ITAM Docker Build Check"]
|
||||
BUILD --> DEPLOY["ITAM Production Deploy"]
|
||||
DEPLOY --> HOST["Production Host"]
|
||||
HOST --> APP["docker compose up -d --build"]
|
||||
linkStyle default stroke:#d32f2f,stroke-width:2px;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Gitea Variables / Secrets 기준
|
||||
|
||||
`itam_production_deploy.yml`이 정상 동작하려면 아래 값이 필요하다.
|
||||
|
||||
### 3.1 Variables
|
||||
|
||||
아래 항목은 Gitea repository Variables에 등록한다.
|
||||
|
||||
| Key | 설명 | 예시 |
|
||||
| --- | --- | --- |
|
||||
| `PROD_HOST` | 운영 서버 SSH 접속 호스트 | `10.0.0.25` |
|
||||
| `PROD_USER` | 운영 서버 SSH 사용자 | `deploy` |
|
||||
| `PROD_DEPLOY_PATH` | 서버에서 저장소를 배포할 경로 | `/opt/itam` |
|
||||
| `PROD_BACKUP_ROOT` | 배포 전 백업 저장 경로, 배포 경로 바깥이어야 함 | `/opt/itam-backups` |
|
||||
| `PROD_GIT_URL` | 운영 서버에서 pull 가능한 저장소 주소 | `git@gitea.example.com:team/itam.git` |
|
||||
| `PROD_DB_HOST` | 외부 MySQL 호스트 | `172.16.8.151` |
|
||||
| `PROD_DB_PORT` | 외부 MySQL 포트 | `3306` |
|
||||
| `PROD_DB_USER` | 운영 DB 계정 | `itam_admin` |
|
||||
| `PROD_DB_NAME` | 운영 DB 이름 | `itam` |
|
||||
| `PROD_LOG_LEVEL` | 애플리케이션 로그 레벨 | `info` |
|
||||
|
||||
### 3.2 Secrets
|
||||
|
||||
아래 항목은 Gitea repository Secrets에 등록한다.
|
||||
|
||||
| Key | 설명 |
|
||||
| --- | --- |
|
||||
| `PROD_SSH_PRIVATE_KEY` | 운영 서버 접속용 개인키 |
|
||||
| `PROD_DB_PASS` | 운영 DB 비밀번호 |
|
||||
|
||||
### 3.3 운영 원칙
|
||||
|
||||
1. `PROD_DB_PASS`는 Variables가 아니라 Secrets에만 둔다.
|
||||
2. `PROD_SSH_PRIVATE_KEY`는 배포 전용 계정 키를 사용한다.
|
||||
3. `PROD_GIT_URL`은 운영 서버에서 직접 pull 가능한 주소여야 한다.
|
||||
4. 운영 서버의 `known_hosts`는 workflow에서 자동 등록되지만, 최초 운영 전 수동 접속 검증도 함께 수행하는 것이 안전하다.
|
||||
5. `PROD_BACKUP_ROOT`는 `PROD_DEPLOY_PATH` 내부가 아니라 바깥 경로를 사용해야 한다.
|
||||
|
||||
---
|
||||
|
||||
## 4. 운영 서버 배포 디렉토리 기준
|
||||
|
||||
현재 `itam_production_deploy.yml`은 운영 서버에서 아래 흐름으로 배포를 수행한다.
|
||||
|
||||
1. `PROD_DEPLOY_PATH` 디렉토리를 생성한다.
|
||||
2. 기존 운영 상태가 있으면 배포 전 백업을 수행한다.
|
||||
3. 해당 경로에 저장소를 clone 또는 fetch 한다.
|
||||
4. 지정 브랜치로 checkout 한다.
|
||||
5. `uploads`, `logs/nginx` 디렉토리를 생성한다.
|
||||
6. `.env.deploy`를 서버의 `.env`로 복사한다.
|
||||
7. `docker compose -f docker-compose.prod.yaml up -d --build`를 실행한다.
|
||||
|
||||
권장 디렉토리 구조는 아래와 같다.
|
||||
|
||||
```text
|
||||
/opt/itam/
|
||||
.env
|
||||
docker-compose.prod.yaml
|
||||
Dockerfile.frontend.prod
|
||||
Dockerfile.backend.prod
|
||||
map_config.json
|
||||
uploads/
|
||||
logs/
|
||||
nginx/
|
||||
docker/
|
||||
nginx/
|
||||
default.conf
|
||||
frontend/
|
||||
default.conf
|
||||
src/
|
||||
public/
|
||||
img/
|
||||
|
||||
/opt/itam-backups/
|
||||
db/
|
||||
files/
|
||||
```
|
||||
|
||||
현재 구조 기준 배포 관계는 아래와 같다.
|
||||
|
||||
```mermaid
|
||||
flowchart TB
|
||||
subgraph HOST["Production Host"]
|
||||
REPO["PROD_DEPLOY_PATH"]
|
||||
ENV[".env"]
|
||||
UP["uploads/"]
|
||||
LOGS["logs/nginx/"]
|
||||
MAP["map_config.json"]
|
||||
end
|
||||
|
||||
subgraph CTR["Docker Services"]
|
||||
NGINX["itam-nginx"]
|
||||
FRONT["itam-frontend"]
|
||||
BACK["itam-backend"]
|
||||
end
|
||||
|
||||
DB["External MySQL"]
|
||||
|
||||
REPO --> NGINX
|
||||
ENV --> BACK
|
||||
UP --> BACK
|
||||
MAP --> BACK
|
||||
LOGS --> NGINX
|
||||
REPO --> BAK["PROD_BACKUP_ROOT"]
|
||||
NGINX --> FRONT
|
||||
NGINX --> BACK
|
||||
BACK --> DB
|
||||
linkStyle default stroke:#d32f2f,stroke-width:2px;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. 영속 경로 기준
|
||||
|
||||
현재 `docker-compose.prod.yaml` 기준으로 운영에서 유지되어야 하는 경로는 아래와 같다.
|
||||
|
||||
1. `.env`
|
||||
2. `uploads/`
|
||||
3. `map_config.json`
|
||||
4. `logs/nginx/`
|
||||
5. `PROD_BACKUP_ROOT`
|
||||
|
||||
각 경로의 의미는 아래와 같다.
|
||||
|
||||
1. `.env`: backend 런타임 환경변수
|
||||
2. `uploads/`: 업로드 파일 데이터
|
||||
3. `map_config.json`: 위치/맵 구성 데이터
|
||||
4. `logs/nginx/`: reverse proxy 접근 로그 및 에러 로그
|
||||
5. `PROD_BACKUP_ROOT`: 배포 전 DB dump와 운영 파일 아카이브 저장 위치
|
||||
|
||||
운영 기준으로 보면 `uploads/`와 `map_config.json`은 애플리케이션 데이터이고, `.env`는 환경 설정이며, `logs/nginx/`는 운영 추적 데이터다.
|
||||
|
||||
즉 서버 운영 시 컨테이너만 다시 띄우면 되는 구조가 아니라, 이 경로들이 유지되는 것을 전제로 배포가 성립한다.
|
||||
|
||||
---
|
||||
|
||||
## 6. 배포 전 체크리스트
|
||||
|
||||
`itam_production_deploy.yml` 실행 전 아래 항목을 먼저 확인한다.
|
||||
|
||||
1. 운영 서버에 Docker Engine과 `docker compose`가 설치되어 있어야 한다.
|
||||
2. 운영 서버의 배포 계정이 Docker 실행 권한을 가져야 한다.
|
||||
3. 운영 서버에서 `PROD_GIT_URL`로 직접 `git fetch`가 가능해야 한다.
|
||||
4. 외부 MySQL 접속 정보가 실제 운영망 기준으로 열려 있어야 한다.
|
||||
5. 운영 서버에 `map_config.json` 초기 파일이 존재해야 한다.
|
||||
6. 방화벽 또는 보안 장비에서 80 포트 접근 정책이 정리되어 있어야 한다.
|
||||
|
||||
권장 확인 명령 예시는 아래와 같다.
|
||||
|
||||
```bash
|
||||
docker --version
|
||||
docker compose version
|
||||
git ls-remote <PROD_GIT_URL>
|
||||
test -f map_config.json
|
||||
test -d uploads
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. 현재 구조에서의 해석
|
||||
|
||||
현재 ITAM CI/CD는 staging 없이도 운영 배포가 가능한 최소 구조로 정리되어 있다.
|
||||
|
||||
이 구조의 장점은 아래와 같다.
|
||||
|
||||
1. workflow 수가 적어서 관리가 단순하다.
|
||||
2. 운영 배포에 필요한 변수와 시크릿 범위가 명확하다.
|
||||
3. staging이 필요해지면 production deploy workflow를 복제해 별도 환경으로 확장하기 쉽다.
|
||||
|
||||
즉, 지금 단계에서는 production 기준을 먼저 고정하고, staging은 동일 패턴으로 추후 추가하는 전략이 적절하다.
|
||||
|
||||
---
|
||||
|
||||
## 8. 다음 권장 작업
|
||||
|
||||
현재 문서 기준으로 바로 이어서 할 작업은 아래 순서가 적절하다.
|
||||
|
||||
1. `PROD_DEPLOY_PATH` 실제 서버 경로 확정
|
||||
2. 운영 서버 배포 계정 생성 및 SSH 키 등록
|
||||
3. `map_config.json`, `uploads/` 초기 데이터 준비
|
||||
4. production deploy workflow에 smoke check 추가
|
||||
5. 로그 로테이션과 백업/복구 절차 문서화
|
||||
@@ -1,51 +0,0 @@
|
||||
# 구조 개선 및 다중 탭(Depth 2) 도입 계획
|
||||
|
||||
사용자 요청에 따라 H/W와 S/W를 구분하고, 그 하위에 각각 대시보드 및 상세 항목(개인PC, 서버 등) 탭을 나누는 네비게이션 구조를 도입합니다. 바닐라 JS 기반에서 각 탭마다 다른 데이터 테이블을 그려내는 아키텍처로 개선합니다.
|
||||
|
||||
## User Review Required
|
||||
|
||||
> [!IMPORTANT]
|
||||
> 1. **엑셀 관리 방식 (Sheets 분리)**: 단일 엑셀 파일 안에 여러 개의 시트(Sheet)를 나누어 관리하는 방식으로 제안합니다. 한 번 엑셀을 업로드하면, `개인PC`, `서버`, `스토리지`, `전산비품` 등 각각의 시트를 한방에 파싱하여 각 탭에 적용하도록 구성하겠습니다.
|
||||
> 2. **S/W 스키마**: 현재 H/W 기반 데이터 스키마만 정의되어 있습니다. [구독 소프트웨어]와 [영구 소프트웨어] 탭 개발을 위한 데이터 항목들(예: 사용기간, 라이선스키, 결제방식 등)은 아직 정해지지 않았으므로 일단 공통 S/W 데이터 스키마 임시 템플릿(S/W명, 유형, 라이선스키, 할당된 사용자 등)으로 만들어 두고 추후 수정할 수 있도록 개발해도 될까요?
|
||||
|
||||
## Proposed Changes
|
||||
|
||||
### 1. UI/UX: 2 Depth 네비게이션 (`index.html`, `style.css`)
|
||||
- **좌측(또는 상단) GNB (Global Navigation Bar)**: H/W 와 S/W 를 스위치할 수 있는 메인 탭 생성.
|
||||
- **LNB (Local Navigation Bar)**: 메인 탭 전환 시 나타나는 서브 탭(H/W: 대시보드/PC/서버/스토리지/비품, S/W: 대시보드/구독/영구).
|
||||
- `README.md` 가이드라인에 따라 화면을 분할하고 정보 밀도를 높이기 위해 Box-less, Line-based Layout 유지.
|
||||
|
||||
#### [MODIFY] index.html
|
||||
#### [MODIFY] src/style.css
|
||||
|
||||
---
|
||||
|
||||
### 2. 다중 데이터 구조 및 상태 관리 (`main.ts`)
|
||||
- 현재 선택된 메뉴 뎁스(예: `activeCategory = 'HW'`, `activeSubTab = '개인PC'`)에 따라 렌더링 함수가 동기화되도록 라우팅/상태 관리 로직 추가.
|
||||
- `Dashboard` 탭 진입 시, 모든 서브 탭 데이터의 갯수(Total PCs, Total Servers 등)를 한눈에 볼 수 있는 요약 영역(Summary Cards/Charts 영역) 예약 및 구현.
|
||||
|
||||
#### [MODIFY] src/main.ts
|
||||
|
||||
---
|
||||
|
||||
### 3. 멀티-시트(Multi-sheet) 엑셀 파싱 (`excelHandler.ts`)
|
||||
- `SheetJS` 기능을 확장하여 다운로드/데이터 추출 시 다중 시트 생성.
|
||||
- **H/W 템플릿 시트명**: `[개인PC, 서버, 스토리지, 전산비품]`
|
||||
- **S/W 템플릿 시트명**: `[구독SW, 영구SW]`
|
||||
|
||||
#### [MODIFY] src/excelHandler.ts
|
||||
|
||||
## Open Questions
|
||||
|
||||
> [!WARNING]
|
||||
> * 왼쪽 사이드바로 메뉴를 구성하는 것이 좋을까요, 상단 가로바(Top Nav) 2단으로 구성하는 것이 좋을까요? Reference 이미지가 따로 없다면 범용적으로 관리하기 편한 **왼쪽 사이드바 구조(Sidebar Menu)** 를 제안합니다. (진행 승인 시 사이드바 형태로 구현합니다.)
|
||||
|
||||
## Verification Plan
|
||||
|
||||
### Automated Tests
|
||||
- 좌측 `H/W`, `S/W` 클릭 시 서브 메뉴가 정상 토글되는지 검증(`main.ts` DOM class toggle 확인).
|
||||
- 서브 메뉴 `서버` 클릭 시 빈 테이블(또는 서버 자산 테이블)이 그려지는지 확인.
|
||||
- 달라진 구조로 `엑셀 템플릿 양식`을 다운로드했을 때 파일에 다수의 시트(Sheet)가 정상 분류되어 있는지 확인.
|
||||
|
||||
### Manual Verification
|
||||
- 브라우저 에이전트를 통해 바뀐 화면의 스크린샷(LNB 사이드바, Dashboard 화면 등)을 찍어 사용자에게 보고.
|
||||
@@ -1,47 +0,0 @@
|
||||
# 임시 DB 생성 및 S/W 사용자 관리 개편
|
||||
|
||||
임시 DB 엑셀 파일 생성과 S/W 목록의 '할당자' 속성 UI 개편에 대한 기술 구현 계획입니다.
|
||||
|
||||
## User Review Required
|
||||
> [!IMPORTANT]
|
||||
> **사용자 관리 데이터 저장 방식에 대한 피드백이 필요합니다.**
|
||||
> 엑셀을 임시 DB로 사용하고 있기 때문에, "사용자 관리" 팝업에서 추가/삭제된 사용자 목록을 엑셀에 저장할 때 **쉼표(,)로 구분된 하나의 문자열**(예: `홍길동, 김철수, 이영희`)로 기존 `할당자` 컬럼에 업데이트 하는 방식을 제안합니다. 이 방식이 괜찮으신가요?
|
||||
|
||||
## Proposed Changes
|
||||
|
||||
### 1. 임시 DB 연동
|
||||
임시로 사용할 초기 엑셀 파일(`temp_db.xlsx`)을 프로젝트 루트에 스크립트를 통해 생성합니다.
|
||||
- 개인PC, 서버, 구독SW, 영구SW 시트에 각각 구성을 확인할 수 있는 dummy 데이터 1~2개씩을 포함하여 생성합니다.
|
||||
- 향후 화면에서 '엑셀 업로드'를 통해 이 파일을 업로드하여 데이터를 화면에 뿌려볼 수 있습니다. (원하시면 페이지 로드 시 이 파일을 임포트하도록 로직을 변경할 수도 있으나, 브라우저 단에서 로컬 파일을 자동 리딩하는 것은 제한이 있으므로 기본적으로는 파일을 제공만 합니다.)
|
||||
|
||||
---
|
||||
|
||||
### 2. 컴포넌트: HTML 구조 변경
|
||||
#### [MODIFY] [index.html](file:///c:/Project/HM%20ITAM/index.html)
|
||||
- `sw-asset-modal`의 폼 내용 중 "할당자" 입력 폼(<label> 및 <input>) 제거
|
||||
- 관리 팝업을 위한 `sw-user-modal` 모달 오버레이 마크업 추가
|
||||
기존 유저 목록을 보여주고, 새 사용자를 추가하거나 기존 사용자를 삭제할 수 있는 UI (리스트, 추가 인풋, 추가 버튼 기반) 작성
|
||||
|
||||
---
|
||||
|
||||
### 3. 컴포넌트: 로직 및 스타일
|
||||
#### [MODIFY] [src/main.ts](file:///c:/Project/HM%20ITAM/src/main.ts)
|
||||
- S/W 렌더링 영역(`renderTable`)에서 데스크탑 뷰의 `<th>할당자</th>` 및 해당하는 셀(`<td>`) 제거
|
||||
- S/W `관리` 탭(`<td>`)에 수정 버튼(`btn-edit`) 옆에 사용자 관리 아이콘 (Lucide의 `Users` 또는 `UserCog` 아이콘 활용) 추가
|
||||
- 사용자 관리 아이콘 클릭 시 `sw-user-modal` 팝업 띄우는 이벤트 리스너 추가
|
||||
- `sw-user-modal` 팝업 내에서 사용자를 추가/삭제하고 '저장' 시, 해당 S/W 자산의 `할당자` 데이터를 갱신하도록 처리 (쉼표 구분 형태)
|
||||
|
||||
#### [MODIFY] [src/excelHandler.ts](file:///c:/Project/HM%20ITAM/src/excelHandler.ts)
|
||||
- (선택 사항) `SW_HEADERS`나 엑셀 파싱 로직은 그대로 두어 하위 호환성 유지. 사용자가 데이터를 쉼표 형태로 주고 받을 것이므로 별도의 인터페이스 변경은 없음.
|
||||
|
||||
## Open Questions
|
||||
- 사용자 관리 팝업에서 저장할 때, 이름 말고 '부서'나 '직급' 같은 추가적인 정보도 관리가 필요하신가요? (기본적으로는 엑셀에 단일 텍스트로 보존되므로 '이름'만 관리하는 것으로 설계했습니다.)
|
||||
- 개발 환경(Vite)에서 초기 로딩 시 `temp_db.xlsx`를 자동으로 불러오도록 Vite의 플러그인 또는 fetch 로직을 추가하는 것을 원하시나요? 아니면 엑셀 파일만 만들어 드리고 사용자가 '엑셀 업로드' 버튼으로 직접 연동해 쓰는 방식이 좋으신가요?
|
||||
|
||||
## Verification Plan
|
||||
### Manual Verification
|
||||
1. `npm run dev` 후 브라우저 접속
|
||||
2. 프로젝트 폴더에 `temp_db.xlsx` 파일이 생성되었는지 확인
|
||||
3. 소프트웨어 > 영구/구독 탭 진입 시 "할당자" 테이블 헤더가 사라진 것 확인
|
||||
4. 관리 탭의 "사용자 관리" 아이콘 클릭 시, 해당 소프트웨어의 사용자를 등록하고 삭제할 수 있는 팝업 등장하는지 확인
|
||||
5. 사용자 아이콘을 클릭해 홍길동, 김철수 등록 후, 전체 엑셀 저장 혹은 다운로드 시 엑셀 파일 내의 '할당자' 열에 `홍길동,김철수` 로 잘 들어가는지 확인
|
||||
@@ -1,24 +0,0 @@
|
||||
const mysql = require('mysql2/promise');
|
||||
require('dotenv').config();
|
||||
|
||||
async function analyzeCodes() {
|
||||
const connection = await mysql.createConnection({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASS,
|
||||
database: process.env.DB_NAME,
|
||||
port: parseInt(process.env.DB_PORT || '3306')
|
||||
});
|
||||
|
||||
// 새 자산들의 연도 분포 확인
|
||||
const [years] = await connection.query('SELECT DISTINCT purchase_date FROM asset_core WHERE id LIKE "PC_20260615_%"');
|
||||
console.log('New assets years:', years.map(y => y.purchase_date));
|
||||
|
||||
// 기존 자산 코드 패턴 확인
|
||||
const [existing] = await connection.query('SELECT asset_code FROM asset_core WHERE asset_code LIKE "PC-%" LIMIT 5');
|
||||
console.log('Existing code sample:', existing);
|
||||
|
||||
await connection.end();
|
||||
}
|
||||
|
||||
analyzeCodes().catch(console.error);
|
||||
@@ -1,11 +0,0 @@
|
||||
const XLSX = require('xlsx');
|
||||
const workbook = XLSX.readFile('backupDB_20260602.xlsx');
|
||||
console.log('Sheet Names:', workbook.SheetNames);
|
||||
if (workbook.SheetNames.includes('system_users')) {
|
||||
const sheet = workbook.Sheets['system_users'];
|
||||
const data = XLSX.utils.sheet_to_json(sheet);
|
||||
console.log('system_users found! Count:', data.length);
|
||||
console.log('Sample:', data.slice(0, 2));
|
||||
} else {
|
||||
console.log('system_users sheet not found in backupDB_20260602.xlsx');
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
const mysql = require('mysql2/promise');
|
||||
require('dotenv').config();
|
||||
|
||||
async function checkCodes() {
|
||||
const connection = await mysql.createConnection({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASS,
|
||||
database: process.env.DB_NAME,
|
||||
port: parseInt(process.env.DB_PORT || '3306')
|
||||
});
|
||||
|
||||
console.log('--- Asset Codes Sample ---');
|
||||
const [rows] = await connection.query('SELECT id, asset_code, purchase_date FROM asset_core WHERE id LIKE "PC_20260615_%" LIMIT 10');
|
||||
console.log(rows);
|
||||
|
||||
console.log('\n--- Other Asset Codes Sample ---');
|
||||
const [rows2] = await connection.query('SELECT id, asset_code, purchase_date FROM asset_core WHERE id NOT LIKE "PC_20260615_%" AND asset_code IS NOT NULL LIMIT 5');
|
||||
console.log(rows2);
|
||||
|
||||
await connection.end();
|
||||
}
|
||||
|
||||
checkCodes().catch(console.error);
|
||||
@@ -1,40 +0,0 @@
|
||||
const mysql = require('mysql2/promise');
|
||||
require('dotenv').config();
|
||||
|
||||
async function checkPublicPCs() {
|
||||
const connection = await mysql.createConnection({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASS,
|
||||
database: process.env.DB_NAME,
|
||||
port: parseInt(process.env.DB_PORT || '3306')
|
||||
});
|
||||
|
||||
console.log('🔍 공용 PC(Public PC)로 추정되는 자산 조회 중...');
|
||||
|
||||
// 사번이 없거나, 사용자명에 '공용'이 포함된 데이터 조회
|
||||
const [rows] = await connection.query(`
|
||||
SELECT id, asset_code, user_current, emp_no, current_dept, asset_type
|
||||
FROM asset_core
|
||||
WHERE (emp_no IS NULL OR emp_no = '' OR user_current LIKE '%공용%')
|
||||
AND id LIKE 'PC_20260615_%'
|
||||
`);
|
||||
|
||||
console.log(`📊 발견된 공용 PC 후보: ${rows.length}건`);
|
||||
|
||||
if (rows.length > 0) {
|
||||
console.table(rows.slice(0, 20)); // 상위 20개 샘플 출력
|
||||
|
||||
// 요약 통계
|
||||
const summary = {
|
||||
only_no_emp: rows.filter(r => (!r.emp_no) && !r.user_current.includes('공용')).length,
|
||||
only_public_name: rows.filter(r => r.emp_no && r.user_current.includes('공용')).length,
|
||||
both: rows.filter(r => (!r.emp_no) && r.user_current.includes('공용')).length
|
||||
};
|
||||
console.log('\n📈 요약 통계:', summary);
|
||||
}
|
||||
|
||||
await connection.end();
|
||||
}
|
||||
|
||||
checkPublicPCs().catch(console.error);
|
||||
@@ -1,77 +0,0 @@
|
||||
const mysql = require('mysql2/promise');
|
||||
require('dotenv').config();
|
||||
|
||||
async function updateAndCompare() {
|
||||
const connection = await mysql.createConnection({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASS,
|
||||
database: process.env.DB_NAME,
|
||||
port: parseInt(process.env.DB_PORT || '3306')
|
||||
});
|
||||
|
||||
console.log('🚀 [Step 1 & 2] "undefined" 사번 및 빈 사용자명 정리 중...');
|
||||
const [updateResult] = await connection.query(`
|
||||
UPDATE asset_core
|
||||
SET user_current = '공용', emp_no = NULL
|
||||
WHERE id LIKE "PC_20260615_%" AND (emp_no = 'undefined' OR emp_no IS NULL OR emp_no = '')
|
||||
`);
|
||||
console.log(`✅ 업데이트 완료: ${updateResult.affectedRows}건`);
|
||||
|
||||
console.log('\n🔍 [Step 3] 엑셀 데이터와 DB asset_type 비교 분석 중...');
|
||||
const XLSX = require('xlsx');
|
||||
const workbook = XLSX.readFile('asset_pc (2026.06.15).xlsx');
|
||||
const sheet = workbook.Sheets[workbook.SheetNames[0]];
|
||||
const excelData = XLSX.utils.sheet_to_json(sheet);
|
||||
|
||||
// DB 데이터 로드
|
||||
const [dbRows] = await connection.query('SELECT id, asset_type, user_current, emp_no FROM asset_core WHERE id LIKE "PC_20260615_%"');
|
||||
const dbMap = new Map();
|
||||
dbRows.forEach(r => dbMap.set(r.id, r));
|
||||
|
||||
const mismatches = [];
|
||||
const publicButExcelPersonal = [];
|
||||
|
||||
for (let i = 0; i < excelData.length; i++) {
|
||||
const excelRow = excelData[i];
|
||||
const assetId = `PC_20260615_${String(i + 1).padStart(4, '0')}`;
|
||||
const dbRow = dbMap.get(assetId);
|
||||
|
||||
if (!dbRow) continue;
|
||||
|
||||
const excelType = excelRow.asset_type || '개인PC';
|
||||
|
||||
// 1. 단순 타입 불일치 체크
|
||||
if (dbRow.asset_type !== excelType) {
|
||||
mismatches.push({
|
||||
id: assetId,
|
||||
excel_type: excelType,
|
||||
db_type: dbRow.asset_type,
|
||||
user: dbRow.user_current
|
||||
});
|
||||
}
|
||||
|
||||
// 2. 엑셀은 '개인PC'인데 데이터는 공용(사번없음)인 경우 탐색
|
||||
if (excelType === '개인PC' && (!dbRow.emp_no || dbRow.user_current === '공용')) {
|
||||
publicButExcelPersonal.push({
|
||||
id: assetId,
|
||||
excel_user: excelRow.user_current,
|
||||
excel_dept: excelRow.current_dept,
|
||||
db_user: dbRow.user_current
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`\n📊 분석 결과:`);
|
||||
console.log(`- 엑셀과 DB의 asset_type 불일치: ${mismatches.length}건`);
|
||||
console.log(`- 엑셀은 '개인PC'이나 사번이 없어 '공용'으로 잡힌 항목: ${publicButExcelPersonal.length}건`);
|
||||
|
||||
if (publicButExcelPersonal.length > 0) {
|
||||
console.log('\n⚠️ 엑셀은 개인PC이나 데이터가 미비한 항목 (상위 10개):');
|
||||
console.table(publicButExcelPersonal.slice(0, 10));
|
||||
}
|
||||
|
||||
await connection.end();
|
||||
}
|
||||
|
||||
updateAndCompare().catch(console.error);
|
||||
@@ -1,189 +0,0 @@
|
||||
const mysql = require('mysql2/promise');
|
||||
const fs = require('fs');
|
||||
require('dotenv').config();
|
||||
|
||||
function getCleanMapKey(path) {
|
||||
let clean = path.replace('img/location_photo/', '').replace('.png', '');
|
||||
clean = clean.replace('서관', 'W').replace('동관', 'E');
|
||||
clean = clean.replace('한맥빌딩/MDF실/MDF_', 'HAN-MDF-');
|
||||
clean = clean.replace('기술개발센터/서버실/서버실_', 'DEV-SVR-');
|
||||
clean = clean.replace(/\//g, '-');
|
||||
return clean;
|
||||
}
|
||||
|
||||
function getLocationName(path) {
|
||||
if (path.includes('IDC')) return 'IDC';
|
||||
if (path.includes('한맥빌딩')) return '한맥빌딩';
|
||||
if (path.includes('기술개발센터')) return '기술개발센터';
|
||||
return '기타';
|
||||
}
|
||||
|
||||
function getLocationDetail(path, idx) {
|
||||
let clean = path.replace('img/location_photo/', '').replace('.png', '');
|
||||
let parts = clean.split('/');
|
||||
let lastPart = parts[parts.length - 1]; // e.g. "서관205", "MDF_1", "서버실_1"
|
||||
return `${lastPart} 구역 자리 #${idx + 1}`;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
console.log('🏁 Starting DB migration...');
|
||||
|
||||
const pool = mysql.createPool({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASS,
|
||||
database: process.env.DB_NAME,
|
||||
port: process.env.DB_PORT
|
||||
});
|
||||
|
||||
const connection = await pool.getConnection();
|
||||
|
||||
try {
|
||||
// 1. Create physical_locations table
|
||||
console.log('⏳ Creating physical_locations table...');
|
||||
await connection.query(`
|
||||
CREATE TABLE IF NOT EXISTS physical_locations (
|
||||
location_code VARCHAR(50) NOT NULL COMMENT '위치 식별 코드 (예: LOC-IDC-W205-001)',
|
||||
location_name VARCHAR(100) NOT NULL COMMENT '물리 위치 대분류 (예: IDC 서관)',
|
||||
location_detail VARCHAR(100) NOT NULL COMMENT '상세 위치/랙 번호 (예: 205호 1번 랙)',
|
||||
map_image VARCHAR(150) NOT NULL COMMENT '해당 도면 파일 경로 (예: img/location_photo/IDC/서관205.png)',
|
||||
map_x DECIMAL(5,2) NOT NULL COMMENT '도면 내 X 백분율 좌표',
|
||||
map_y DECIMAL(5,2) NOT NULL COMMENT '도면 내 Y 백분율 좌표',
|
||||
map_w DECIMAL(5,2) NOT NULL DEFAULT 4.00 COMMENT '도면 내 박스 너비(%)',
|
||||
map_h DECIMAL(5,2) NOT NULL DEFAULT 4.00 COMMENT '도면 내 박스 높이(%)',
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (location_code)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
|
||||
`);
|
||||
console.log('✅ physical_locations table ready.');
|
||||
|
||||
// 2. Create asset_audit_pending table
|
||||
console.log('⏳ Creating asset_audit_pending table...');
|
||||
await connection.query(`
|
||||
CREATE TABLE IF NOT EXISTS asset_audit_pending (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
asset_code VARCHAR(50) NOT NULL COMMENT '스캔된 자산 고유번호 (예: server_1779761946023_14)',
|
||||
physical_location_code VARCHAR(50) NOT NULL COMMENT '스캔된 위치 마스터 코드 (예: LOC-IDC-W205-001)',
|
||||
status VARCHAR(20) NOT NULL DEFAULT 'PENDING' COMMENT '상태: PENDING(대기), APPROVED(승인), REJECTED(반려)',
|
||||
scanned_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
processed_at TIMESTAMP NULL COMMENT '승인/반려 처리 일시',
|
||||
processed_by VARCHAR(50) NULL COMMENT '처리한 관리자',
|
||||
CONSTRAINT fk_audit_physical FOREIGN KEY (physical_location_code) REFERENCES physical_locations(location_code)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
|
||||
`);
|
||||
console.log('✅ asset_audit_pending table ready.');
|
||||
|
||||
// 3. Add physical_location_code to asset_location
|
||||
console.log('⏳ Checking physical_location_code column in asset_location...');
|
||||
const [cols] = await connection.query('DESCRIBE asset_location');
|
||||
const hasCol = cols.some(c => c.Field === 'physical_location_code');
|
||||
if (!hasCol) {
|
||||
await connection.query(`
|
||||
ALTER TABLE asset_location
|
||||
ADD COLUMN physical_location_code VARCHAR(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL COMMENT 'physical_locations의 location_code FK'
|
||||
`);
|
||||
console.log('✅ physical_location_code column added with utf8mb4_unicode_ci collation.');
|
||||
} else {
|
||||
console.log('ℹ️ physical_location_code column already exists. Enforcing collation...');
|
||||
await connection.query(`
|
||||
ALTER TABLE asset_location
|
||||
MODIFY COLUMN physical_location_code VARCHAR(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL COMMENT 'physical_locations의 location_code FK'
|
||||
`);
|
||||
console.log('✅ physical_location_code column collation enforced.');
|
||||
}
|
||||
|
||||
// Add constraint if not exists
|
||||
console.log('⏳ Checking foreign key constraint fk_asset_loc_physical...');
|
||||
const [constraints] = await connection.query(`
|
||||
SELECT CONSTRAINT_NAME
|
||||
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
|
||||
WHERE TABLE_NAME = 'asset_location'
|
||||
AND CONSTRAINT_NAME = 'fk_asset_loc_physical'
|
||||
AND TABLE_SCHEMA = DATABASE()
|
||||
`);
|
||||
|
||||
if (constraints.length === 0) {
|
||||
console.log('⏳ Adding foreign key constraint...');
|
||||
await connection.query(`
|
||||
ALTER TABLE asset_location
|
||||
ADD CONSTRAINT fk_asset_loc_physical
|
||||
FOREIGN KEY (physical_location_code) REFERENCES physical_locations(location_code)
|
||||
`);
|
||||
console.log('✅ Foreign key constraint added.');
|
||||
} else {
|
||||
console.log('ℹ️ Foreign key constraint already exists.');
|
||||
}
|
||||
|
||||
// 4. Load map_config.json and migrate
|
||||
console.log('⏳ Migrating map_config.json data to physical_locations...');
|
||||
if (fs.existsSync('map_config.json')) {
|
||||
const mapConfig = JSON.parse(fs.readFileSync('map_config.json', 'utf8') || '{}');
|
||||
let insertCount = 0;
|
||||
let syncCount = 0;
|
||||
|
||||
for (const [mapPath, boxes] of Object.entries(mapConfig)) {
|
||||
const cleanKey = getCleanMapKey(mapPath);
|
||||
const locName = getLocationName(mapPath);
|
||||
|
||||
for (let i = 0; i < boxes.length; i++) {
|
||||
const box = boxes[i];
|
||||
const padIdx = String(i + 1).padStart(3, '0');
|
||||
const locCode = `LOC-${cleanKey}-${padIdx}`;
|
||||
const locDetail = getLocationDetail(mapPath, i);
|
||||
|
||||
const bx = parseFloat(box.x);
|
||||
const by = parseFloat(box.y);
|
||||
const bw = parseFloat(box.w || 4.00);
|
||||
const bh = parseFloat(box.h || 4.00);
|
||||
|
||||
// Insert into physical_locations (ignore if duplicate)
|
||||
await connection.query(`
|
||||
INSERT INTO physical_locations
|
||||
(location_code, location_name, location_detail, map_image, map_x, map_y, map_w, map_h)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON DUPLICATE KEY UPDATE
|
||||
location_name = VALUES(location_name),
|
||||
location_detail = VALUES(location_detail),
|
||||
map_image = VALUES(map_image),
|
||||
map_x = VALUES(map_x),
|
||||
map_y = VALUES(map_y),
|
||||
map_w = VALUES(map_w),
|
||||
map_h = VALUES(map_h)
|
||||
`, [locCode, locName, locDetail, mapPath, bx, by, bw, bh]);
|
||||
|
||||
insertCount++;
|
||||
|
||||
// Sync database asset if box.asset_id exists
|
||||
if (box.asset_id) {
|
||||
const [rows] = await connection.query(
|
||||
'SELECT id FROM asset_location WHERE asset_id = ? AND is_active = 1',
|
||||
[box.asset_id]
|
||||
);
|
||||
if (rows.length > 0) {
|
||||
await connection.query(
|
||||
'UPDATE asset_location SET physical_location_code = ? WHERE asset_id = ? AND is_active = 1',
|
||||
[locCode, box.asset_id]
|
||||
);
|
||||
syncCount++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
console.log(`✅ Migrated ${insertCount} physical locations and synced ${syncCount} existing assets.`);
|
||||
} else {
|
||||
console.log('⚠️ map_config.json not found, skipping initial migration.');
|
||||
}
|
||||
|
||||
console.log('🎉 DB Migration successfully completed!');
|
||||
} catch (err) {
|
||||
console.error('❌ Migration failed:', err);
|
||||
throw err;
|
||||
} finally {
|
||||
connection.release();
|
||||
await pool.end();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(err => {
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -1,25 +0,0 @@
|
||||
const mysql = require('mysql2/promise');
|
||||
require('dotenv').config();
|
||||
|
||||
async function debugPublic() {
|
||||
const connection = await mysql.createConnection({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASS,
|
||||
database: process.env.DB_NAME,
|
||||
port: parseInt(process.env.DB_PORT || '3306')
|
||||
});
|
||||
|
||||
const [rows] = await connection.query(`
|
||||
SELECT user_current, emp_no, COUNT(*) as count
|
||||
FROM asset_core
|
||||
WHERE id LIKE "PC_20260615_%"
|
||||
GROUP BY user_current, emp_no
|
||||
HAVING emp_no IS NULL OR emp_no = '' OR user_current LIKE '%공용%' OR user_current = ''
|
||||
`);
|
||||
|
||||
console.table(rows);
|
||||
await connection.end();
|
||||
}
|
||||
|
||||
debugPublic().catch(console.error);
|
||||
@@ -1,69 +0,0 @@
|
||||
const XLSX = require('xlsx');
|
||||
const mysql = require('mysql2/promise');
|
||||
require('dotenv').config();
|
||||
|
||||
async function deepAudit() {
|
||||
const workbook = XLSX.readFile('asset_pc (2026.06.15).xlsx');
|
||||
const sheet = workbook.Sheets[workbook.SheetNames[0]];
|
||||
const excelData = XLSX.utils.sheet_to_json(sheet);
|
||||
|
||||
console.log('📊 [Excel Audit] Total Rows:', excelData.length);
|
||||
|
||||
// 1. 엑셀 내 asset_type 종류 확인
|
||||
const excelTypes = new Set();
|
||||
excelData.forEach(r => excelTypes.add(r.asset_type));
|
||||
console.log('Excel Asset Types:', Array.from(excelTypes));
|
||||
|
||||
// 2. '공용' 키워드가 들어간 모든 행 추출
|
||||
const publicKeywords = ['공용', '공통', '테스트', 'TEST'];
|
||||
const potentialPublicInExcel = excelData.filter(r => {
|
||||
const name = String(r.user_current || '');
|
||||
const type = String(r.asset_type || '');
|
||||
const memo = String(r.memo || '');
|
||||
return publicKeywords.some(k => name.includes(k) || type.includes(k) || memo.includes(k)) || !r.emp_no;
|
||||
});
|
||||
|
||||
console.log(`\n🔍 [Potential Public/Issue Rows in Excel]: ${potentialPublicInExcel.length}건`);
|
||||
console.table(potentialPublicInExcel.slice(0, 30).map(r => ({
|
||||
emp_no: r.emp_no,
|
||||
user: r.user_current,
|
||||
dept: r.current_dept,
|
||||
type: r.asset_type,
|
||||
memo: r.memo
|
||||
})));
|
||||
|
||||
// 3. DB와 대조 (특히 엑셀엔 사번이 있는데 DB엔 공용으로 된 게 있는지)
|
||||
const connection = await mysql.createConnection({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASS,
|
||||
database: process.env.DB_NAME,
|
||||
port: parseInt(process.env.DB_PORT || '3306')
|
||||
});
|
||||
|
||||
const [dbRows] = await connection.query('SELECT id, user_current, emp_no, asset_type FROM asset_core WHERE id LIKE "PC_20260615_%"');
|
||||
|
||||
// 엑셀은 개인PC인데 DB는 공용인 경우 (또는 그 반대)
|
||||
const issues = [];
|
||||
for (let i = 0; i < excelData.length; i++) {
|
||||
const ex = excelData[i];
|
||||
const id = `PC_20260615_${String(i + 1).padStart(4, '0')}`;
|
||||
const db = dbRows.find(r => r.id === id);
|
||||
|
||||
if (!db) continue;
|
||||
|
||||
const isExcelPublic = !ex.emp_no || String(ex.user_current).includes('공용');
|
||||
const isDbPublic = !db.emp_no || String(db.user_current).includes('공용');
|
||||
|
||||
if (isExcelPublic !== isDbPublic) {
|
||||
issues.push({ id, excel_user: ex.user_current, db_user: db.user_current, excel_emp: ex.emp_no, db_emp: db.emp_no });
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`\n⚠️ [Consistency Issues]: ${issues.length}건`);
|
||||
if (issues.length > 0) console.table(issues);
|
||||
|
||||
await connection.end();
|
||||
}
|
||||
|
||||
deepAudit().catch(console.error);
|
||||
@@ -1,61 +0,0 @@
|
||||
const XLSX = require('xlsx');
|
||||
const mysql = require('mysql2/promise');
|
||||
const dotenv = require('dotenv');
|
||||
const path = require('path');
|
||||
|
||||
dotenv.config({ path: path.join(__dirname, '../.env') });
|
||||
|
||||
const { DB_HOST, DB_USER, DB_PASS, DB_NAME, DB_PORT } = process.env;
|
||||
|
||||
async function extractFailures() {
|
||||
const connection = await mysql.createConnection({
|
||||
host: DB_HOST,
|
||||
user: DB_USER,
|
||||
password: DB_PASS,
|
||||
database: DB_NAME,
|
||||
port: parseInt(DB_PORT || '3306')
|
||||
});
|
||||
|
||||
console.log('🔍 실패 데이터 추출 중...');
|
||||
|
||||
const workbook = XLSX.readFile('asset_pc (2026.06.15).xlsx');
|
||||
const sheet = workbook.Sheets[workbook.SheetNames[0]];
|
||||
const rawData = XLSX.utils.sheet_to_json(sheet);
|
||||
|
||||
// 현재 DB에 존재하는 모든 asset_core ID 조회
|
||||
const [existingRows] = await connection.query('SELECT id FROM asset_core');
|
||||
const existingIds = new Set(existingRows.map(r => r.id));
|
||||
|
||||
const failures = [];
|
||||
|
||||
for (let i = 0; i < rawData.length; i++) {
|
||||
const row = rawData[i];
|
||||
const assetId = `PC_20260615_${String(i + 1).padStart(4, '0')}`;
|
||||
|
||||
// DB에 해당 ID가 없는 경우 = 실패(충돌 등의 이유로 입력되지 않음) 또는 스킵된 데이터
|
||||
// 하지만 이전 로그에서 'Duplicate entry'로 에러가 났던 항목들을 찾는 것이 목적
|
||||
// 로직상 ID 생성 규칙에 따라 해당 ID가 DB에 없으면 입력에 실패한 행임
|
||||
if (!existingIds.has(assetId)) {
|
||||
failures.push({
|
||||
excel_row: i + 2,
|
||||
generated_id: assetId,
|
||||
...row
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (failures.length > 0) {
|
||||
const newWb = XLSX.utils.book_new();
|
||||
const newWs = XLSX.utils.json_to_sheet(failures);
|
||||
XLSX.utils.book_append_sheet(newWb, newWs, 'Failures');
|
||||
const fileName = 'asset_pc_failures_20260615.xlsx';
|
||||
XLSX.writeFile(newWb, fileName);
|
||||
console.log(`✅ 추출 완료: ${failures.length}건의 실패 데이터를 ${fileName}에 저장했습니다.`);
|
||||
} else {
|
||||
console.log('입력되지 않은 데이터가 없습니다.');
|
||||
}
|
||||
|
||||
await connection.end();
|
||||
}
|
||||
|
||||
extractFailures().catch(console.error);
|
||||
@@ -1,29 +0,0 @@
|
||||
const mysql = require('mysql2/promise');
|
||||
require('dotenv').config();
|
||||
|
||||
async function findPotentialPublic() {
|
||||
const connection = await mysql.createConnection({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASS,
|
||||
database: process.env.DB_NAME,
|
||||
port: parseInt(process.env.DB_PORT || '3306')
|
||||
});
|
||||
|
||||
console.log('--- Searching for rows with no emp_no or "공용" in user_current ---');
|
||||
|
||||
// 사번이 'undefined', 'null', 빈값, 또는 사용자명에 '공용'이 들어간 데이터
|
||||
const [rows] = await connection.query(`
|
||||
SELECT id, user_current, emp_no
|
||||
FROM asset_core
|
||||
WHERE id LIKE "PC_20260615_%"
|
||||
AND (emp_no IS NULL OR emp_no = '' OR emp_no = 'undefined' OR user_current LIKE '%공용%')
|
||||
`);
|
||||
|
||||
console.log('Count:', rows.length);
|
||||
if (rows.length > 0) console.table(rows);
|
||||
|
||||
await connection.end();
|
||||
}
|
||||
|
||||
findPotentialPublic().catch(console.error);
|
||||
@@ -1,47 +0,0 @@
|
||||
const mysql = require('mysql2/promise');
|
||||
require('dotenv').config();
|
||||
|
||||
async function fixAssetTypes() {
|
||||
const connection = await mysql.createConnection({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASS,
|
||||
database: process.env.DB_NAME,
|
||||
port: parseInt(process.env.DB_PORT || '3306')
|
||||
});
|
||||
|
||||
console.log('🚀 [데이터 정상화] 사번 기준 자산 유형 재설정 시작...');
|
||||
|
||||
// 1. 사번이 있는 모든 신규 자산을 '개인PC'로 강제 전환
|
||||
const [personalResult] = await connection.query(`
|
||||
UPDATE asset_core
|
||||
SET asset_type = '개인PC'
|
||||
WHERE id LIKE "PC_20260615_%"
|
||||
AND emp_no IS NOT NULL
|
||||
AND emp_no != ''
|
||||
`);
|
||||
console.log(`✅ 개인PC 정상화 완료: ${personalResult.affectedRows}건 (사번 존재 항목)`);
|
||||
|
||||
// 2. 사번이 없는 모든 신규 자산을 '공용PC'로 강제 전환
|
||||
const [publicResult] = await connection.query(`
|
||||
UPDATE asset_core
|
||||
SET asset_type = '공용PC', user_current = '공용'
|
||||
WHERE id LIKE "PC_20260615_%"
|
||||
AND (emp_no IS NULL OR emp_no = '')
|
||||
`);
|
||||
console.log(`✅ 공용PC 정상화 완료: ${publicResult.affectedRows}건 (사번 부재 항목)`);
|
||||
|
||||
// 3. 최종 결과 확인
|
||||
const [rows] = await connection.query(`
|
||||
SELECT asset_type, COUNT(*) as count
|
||||
FROM asset_core
|
||||
WHERE id LIKE "PC_20260615_%"
|
||||
GROUP BY asset_type
|
||||
`);
|
||||
console.log('\n📊 최종 자산 유형 분포:');
|
||||
console.table(rows);
|
||||
|
||||
await connection.end();
|
||||
}
|
||||
|
||||
fixAssetTypes().catch(console.error);
|
||||
@@ -1,118 +0,0 @@
|
||||
import mysql from 'mysql2/promise';
|
||||
import dotenv from 'dotenv';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
const pool = mysql.createPool({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASS,
|
||||
database: process.env.DB_NAME,
|
||||
port: parseInt(process.env.DB_PORT || '3306'),
|
||||
});
|
||||
|
||||
// 하드웨어 출시 연도 데이터베이스 (CPU/GPU)
|
||||
const RELEASE_DATES = {
|
||||
// Intel CPU Generations (Mainstream desktop release month/year)
|
||||
'i9-14': '2023-10', 'i7-14': '2023-10', 'i5-14': '2023-10',
|
||||
'i9-13': '2022-10', 'i7-13': '2022-10', 'i5-13': '2022-10',
|
||||
'i9-12': '2021-11', 'i7-12': '2021-11', 'i5-12': '2021-11',
|
||||
'i9-11': '2021-03', 'i7-11': '2021-03', 'i5-11': '2021-03',
|
||||
'i9-10': '2020-05', 'i7-10': '2020-05', 'i5-10': '2020-05',
|
||||
'i9-9': '2018-10', 'i7-9': '2018-10', 'i5-9': '2018-10',
|
||||
'i7-8': '2017-10', 'i5-8': '2017-10',
|
||||
'i7-7': '2017-01', 'i5-7': '2017-01',
|
||||
'i7-6': '2015-08', 'i5-6': '2015-08',
|
||||
'i7-4': '2013-06', 'i5-4': '2013-06',
|
||||
'i7-3': '2012-04', 'i5-3': '2012-04',
|
||||
'i7-2': '2011-01', 'i5-2': '2011-01',
|
||||
|
||||
// NVIDIA GPU Series
|
||||
'RTX 4090': '2022-10', 'RTX 4080': '2022-11', 'RTX 4070': '2023-04', 'RTX 4060': '2023-06',
|
||||
'RTX 3090': '2020-09', 'RTX 3080': '2020-09', 'RTX 3070': '2020-10', 'RTX 3060': '2021-02',
|
||||
'RTX 2080': '2018-09', 'RTX 2070': '2018-10', 'RTX 2060': '2019-01',
|
||||
'GTX 1660': '2019-03', 'GTX 1650': '2019-04',
|
||||
'GTX 1080': '2016-05', 'GTX 1070': '2016-06', 'GTX 1060': '2016-07', 'GTX 1050': '2016-10',
|
||||
'GTX 980': '2014-09', 'GTX 970': '2014-09', 'GTX 960': '2015-01'
|
||||
};
|
||||
|
||||
function inferDateFromSpecs(cpu, gpu) {
|
||||
const cpuStr = (cpu || '').toUpperCase();
|
||||
const gpuStr = (gpu || '').toUpperCase();
|
||||
|
||||
let inferred = null;
|
||||
|
||||
// 1. GPU 기준 (최신 그래픽카드가 꽂혀있으면 그 시기 이후 구매일 확률이 높음)
|
||||
for (const [key, date] of Object.entries(RELEASE_DATES)) {
|
||||
if (gpuStr.includes(key)) {
|
||||
inferred = date;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. CPU 기준 (GPU에서 못 찾았거나, CPU가 더 최신일 경우)
|
||||
if (!inferred) {
|
||||
for (const [key, date] of Object.entries(RELEASE_DATES)) {
|
||||
// i7-13700 등을 찾기 위해 정규식 또는 포함 여부 확인
|
||||
if (cpuStr.includes(key)) {
|
||||
inferred = date;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return inferred ? `${inferred}-01` : null;
|
||||
}
|
||||
|
||||
async function run() {
|
||||
const connection = await pool.getConnection();
|
||||
try {
|
||||
const [rows] = await connection.query(`
|
||||
SELECT c.id, c.asset_code, c.purchase_date, s.cpu, s.gpu
|
||||
FROM asset_core c
|
||||
LEFT JOIN asset_spec s ON c.id = s.asset_id
|
||||
`);
|
||||
|
||||
const updates = [];
|
||||
const unchanged = [];
|
||||
|
||||
for (const row of rows) {
|
||||
const currentVal = (row.purchase_date || '').trim();
|
||||
|
||||
// 구매일자가 없거나 부정확한 경우만 처리
|
||||
if (!currentVal || currentVal === '-' || currentVal === 'undefined' || currentVal.startsWith('2024-01-01')) {
|
||||
const specDate = inferDateFromSpecs(row.cpu, row.gpu);
|
||||
|
||||
if (specDate) {
|
||||
updates.push({ id: row.id, date: specDate, code: row.asset_code, cpu: row.cpu, gpu: row.gpu });
|
||||
} else {
|
||||
unchanged.push({ code: row.asset_code, cpu: row.cpu, gpu: row.gpu });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`🚀 스펙 분석 결과: ${updates.length}건의 자산 구매일자를 보정합니다.`);
|
||||
|
||||
for (const item of updates) {
|
||||
await connection.query('UPDATE asset_core SET purchase_date = ? WHERE id = ?', [item.date, item.id]);
|
||||
console.log(`[Update] ${item.code.padEnd(15)} | CPU: ${String(item.cpu).padEnd(20)} | GPU: ${String(item.gpu).padEnd(15)} -> ${item.date}`);
|
||||
}
|
||||
|
||||
if (unchanged.length > 0) {
|
||||
console.log('\n⚠️ 스펙 정보를 찾을 수 없어 보정하지 못한 자산:');
|
||||
unchanged.forEach(u => {
|
||||
if (u.code) console.log(`[Skip] ${u.code.padEnd(15)} | CPU: ${u.cpu || '-'} | GPU: ${u.gpu || '-'}`);
|
||||
});
|
||||
}
|
||||
|
||||
console.log(`\n✅ 완료: ${updates.length}건 보정됨.`);
|
||||
|
||||
} catch (err) {
|
||||
console.error('Error:', err);
|
||||
} finally {
|
||||
connection.release();
|
||||
pool.end();
|
||||
}
|
||||
}
|
||||
|
||||
run();
|
||||
@@ -1,128 +0,0 @@
|
||||
import mysql from 'mysql2/promise';
|
||||
import dotenv from 'dotenv';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
const pool = mysql.createPool({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASS,
|
||||
database: process.env.DB_NAME,
|
||||
port: parseInt(process.env.DB_PORT || '3306'),
|
||||
});
|
||||
|
||||
// 하드웨어 출시 연도/월 데이터베이스
|
||||
const RELEASE_DATES = {
|
||||
// Intel CPU
|
||||
'i9-14': '2023-10', 'i7-14': '2023-10', 'i5-14': '2023-10',
|
||||
'i9-13': '2022-10', 'i7-13': '2022-10', 'i5-13': '2022-10',
|
||||
'i9-12': '2021-11', 'i7-12': '2021-11', 'i5-12': '2021-11',
|
||||
'i9-11': '2021-03', 'i7-11': '2021-03', 'i5-11': '2021-03',
|
||||
'i9-10': '2020-05', 'i7-10': '2020-05', 'i5-10': '2020-05',
|
||||
'i9-9': '2018-10', 'i7-9': '2018-10', 'i5-9': '2018-10',
|
||||
'i7-8': '2017-10', 'i5-8': '2017-10',
|
||||
'i7-7': '2017-01', 'i5-7': '2017-01',
|
||||
'i7-6': '2015-08', 'i5-6': '2015-08',
|
||||
'i7-5': '2014-06', 'i5-5': '2015-06', // Broadwell
|
||||
'i7-4': '2013-06', 'i5-4': '2013-06',
|
||||
'i7-3': '2012-04', 'i5-3': '2012-04',
|
||||
'i7-2': '2011-01', 'i5-2': '2011-01',
|
||||
|
||||
// NVIDIA GPU
|
||||
'RTX 40': '2022-10',
|
||||
'RTX 30': '2020-09',
|
||||
'RTX 20': '2018-09',
|
||||
'GTX 16': '2019-02',
|
||||
'GTX 10': '2016-05',
|
||||
'GTX 9': '2014-09',
|
||||
'GTX 750': '2014-02',
|
||||
'GTX 7': '2013-05',
|
||||
'GTX 6': '2012-03'
|
||||
};
|
||||
|
||||
// 출시 연도만 있는 경우 (지시에 따라 후속년도 12월 적용을 위함)
|
||||
const YEAR_ONLY = {
|
||||
'I5-4': 2013,
|
||||
'I5-6': 2015,
|
||||
'I7-7': 2017,
|
||||
'GTX 750': 2014
|
||||
};
|
||||
|
||||
function inferDateFromSpecs(cpu, gpu) {
|
||||
const cpuStr = (cpu || '').toUpperCase();
|
||||
const gpuStr = (gpu || '').toUpperCase();
|
||||
|
||||
let latestYear = 0;
|
||||
let latestMonth = 0;
|
||||
|
||||
// 모든 매핑 데이터를 순회하며 가장 최신 날짜를 찾음
|
||||
for (const [key, dateStr] of Object.entries(RELEASE_DATES)) {
|
||||
if (cpuStr.includes(key) || gpuStr.includes(key)) {
|
||||
const [y, m] = dateStr.split('-').map(Number);
|
||||
if (y > latestYear || (y === latestYear && m > latestMonth)) {
|
||||
latestYear = y;
|
||||
latestMonth = m;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 매칭된 정보가 있는 경우
|
||||
if (latestYear > 0) {
|
||||
// 월 정보가 명확히 매핑된 경우 (RELEASE_DATES 사용)
|
||||
// 하지만 지시사항에 따라 "월을 못찾으면 12월" & "후속년도" 규칙 적용 여부 판단
|
||||
// RELEASE_DATES는 월이 이미 있으므로 그대로 사용하되,
|
||||
// 만약 YEAR_ONLY에만 걸리는 경우를 위해 로직 보강
|
||||
return `${latestYear}-${String(latestMonth).padStart(2, '0')}-01`;
|
||||
}
|
||||
|
||||
// 연도만 매칭되는 경우 (지시사항: 후속년도 12월)
|
||||
for (const [key, year] of Object.entries(YEAR_ONLY)) {
|
||||
if (cpuStr.includes(key) || gpuStr.includes(key)) {
|
||||
return `${year + 1}-12-01`;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
async function run() {
|
||||
const connection = await pool.getConnection();
|
||||
try {
|
||||
const [rows] = await connection.query(`
|
||||
SELECT c.id, c.asset_code, c.purchase_date, s.cpu, s.gpu
|
||||
FROM asset_core c
|
||||
LEFT JOIN asset_spec s ON c.id = s.asset_id
|
||||
`);
|
||||
|
||||
const updates = [];
|
||||
|
||||
for (const row of rows) {
|
||||
const currentVal = (row.purchase_date || '').trim();
|
||||
|
||||
// 구매일자가 없거나 '-', 'undefined'인 경우 + 혹은 아직 보정이 필요한 자산
|
||||
if (!currentVal || currentVal === '-' || currentVal === 'undefined' || currentVal.startsWith('0000') || currentVal === '2024-01-01') {
|
||||
const specDate = inferDateFromSpecs(row.cpu, row.gpu);
|
||||
if (specDate) {
|
||||
updates.push({ id: row.id, date: specDate, code: row.asset_code, cpu: row.cpu, gpu: row.gpu });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`🚀 지시사항 반영: ${updates.length}건의 자산을 보정합니다. (후속년도/12월 규칙 적용)`);
|
||||
|
||||
for (const item of updates) {
|
||||
await connection.query('UPDATE asset_core SET purchase_date = ? WHERE id = ?', [item.date, item.id]);
|
||||
console.log(`[Update] ${item.code.padEnd(15)} | CPU: ${String(item.cpu).padEnd(20)} | GPU: ${String(item.gpu).padEnd(15)} -> ${item.date}`);
|
||||
}
|
||||
|
||||
console.log(`\n✅ 완료: ${updates.length}건 보정됨.`);
|
||||
|
||||
} catch (err) {
|
||||
console.error('Error:', err);
|
||||
} finally {
|
||||
connection.release();
|
||||
pool.end();
|
||||
}
|
||||
}
|
||||
|
||||
run();
|
||||
@@ -1,88 +0,0 @@
|
||||
import mysql from 'mysql2/promise';
|
||||
import dotenv from 'dotenv';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
const pool = mysql.createPool({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASS,
|
||||
database: process.env.DB_NAME,
|
||||
port: parseInt(process.env.DB_PORT || '3306'),
|
||||
});
|
||||
|
||||
async function run() {
|
||||
const connection = await pool.getConnection();
|
||||
try {
|
||||
// 먼저 잘못 들어간 0000-00-01 등 복구
|
||||
console.log('잘못된 형식(0000-00-01 등)을 초기화합니다...');
|
||||
await connection.query("UPDATE asset_core SET purchase_date = '-' WHERE purchase_date LIKE '0000%' OR purchase_date = '2020-01-01'");
|
||||
|
||||
const [rows] = await connection.query('SELECT id, asset_code, purchase_date, category FROM asset_core');
|
||||
|
||||
const updates = [];
|
||||
const missing = [];
|
||||
|
||||
for (const row of rows) {
|
||||
const code = (row.asset_code || '').trim();
|
||||
const currentVal = (row.purchase_date || '').trim();
|
||||
|
||||
// 구매일자가 없거나 '-', 'undefined' 인 경우 대상
|
||||
if (!currentVal || currentVal === '-' || currentVal === 'undefined') {
|
||||
let inferredDate = null;
|
||||
|
||||
// 1. PREFIX-YYYYMM-NNNN 형식 (예: PC-202406-0001)
|
||||
const match6 = code.match(/[A-Z]+-(\d{4})(0[1-9]|1[0-2])-\d+/);
|
||||
if (match6) {
|
||||
inferredDate = `${match6[1]}-${match6[2]}-01`;
|
||||
} else {
|
||||
// 2. PREFIX-YYYYNN 형식 (예: PC-202423) -> 연도만 있고 뒤에 순번 2자리
|
||||
const matchYearSeq = code.match(/[A-Z]+-(20\d{2})(\d{2})$/);
|
||||
if (matchYearSeq) {
|
||||
inferredDate = `${matchYearSeq[1]}-01-01`; // 월을 모르므로 1월로 통일
|
||||
} else {
|
||||
// 3. PREFIX-YYNNN 형식 (예: PC-24001)
|
||||
const matchShort = code.match(/[A-Z]+-(1\d|2\d)(\d{3})/);
|
||||
if (matchShort) {
|
||||
inferredDate = `20${matchShort[1]}-01-01`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 0000 등의 잘못된 매칭 방지
|
||||
if (inferredDate && !inferredDate.startsWith('0000')) {
|
||||
updates.push({ id: row.id, date: inferredDate, code: code });
|
||||
} else {
|
||||
missing.push({ id: row.id, code: code, category: row.category });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`총 ${updates.length}건의 자산을 업데이트합니다.`);
|
||||
for (const item of updates) {
|
||||
await connection.query('UPDATE asset_core SET purchase_date = ? WHERE id = ?', [item.date, item.id]);
|
||||
console.log(`[Update] ${item.code} -> ${item.date}`);
|
||||
}
|
||||
|
||||
console.log('\n--- 구매일자를 추정할 수 없는 자산 목록 ---');
|
||||
if (missing.length === 0) {
|
||||
console.log('없음');
|
||||
} else {
|
||||
// 중복 제거 및 정렬하여 보고
|
||||
const uniqueMissing = missing.filter(m => m.code !== '');
|
||||
uniqueMissing.forEach(m => {
|
||||
console.log(`[Missing] 코드: ${m.code.padEnd(20)} | 카테고리: ${m.category}`);
|
||||
});
|
||||
}
|
||||
|
||||
console.log(`\n완료: ${updates.length}건 업데이트됨, ${missing.length}건 미결정.`);
|
||||
|
||||
} catch (err) {
|
||||
console.error('Error:', err);
|
||||
} finally {
|
||||
connection.release();
|
||||
pool.end();
|
||||
}
|
||||
}
|
||||
|
||||
run();
|
||||
@@ -1,122 +0,0 @@
|
||||
const XLSX = require('xlsx');
|
||||
const mysql = require('mysql2/promise');
|
||||
const dotenv = require('dotenv');
|
||||
const path = require('path');
|
||||
|
||||
dotenv.config({ path: path.join(__dirname, '../.env') });
|
||||
|
||||
const { DB_HOST, DB_USER, DB_PASS, DB_NAME, DB_PORT } = process.env;
|
||||
|
||||
async function importAssets() {
|
||||
const connection = await mysql.createConnection({
|
||||
host: DB_HOST,
|
||||
user: DB_USER,
|
||||
password: DB_PASS,
|
||||
database: DB_NAME,
|
||||
port: parseInt(DB_PORT || '3306')
|
||||
});
|
||||
|
||||
console.log('🚀 [Step 1] 데이터 로드 및 사전 준비...');
|
||||
|
||||
// 1. 엑셀 파일 로드
|
||||
const workbook = XLSX.readFile('asset_pc (2026.06.15).xlsx');
|
||||
const sheet = workbook.Sheets[workbook.SheetNames[0]];
|
||||
const rawData = XLSX.utils.sheet_to_json(sheet);
|
||||
|
||||
// 2. system_users 데이터 맵 생성 (사번 기준 빠른 조회를 위함)
|
||||
const [userRows] = await connection.query('SELECT emp_no, user_name, dept_name, position, status FROM system_users');
|
||||
const userMap = new Map();
|
||||
userRows.forEach(u => userMap.set(String(u.emp_no), u));
|
||||
|
||||
// 3. 기존 자산 중복 체크용 맵 생성 (emp_no + asset_type + category)
|
||||
const [existingAssets] = await connection.query('SELECT emp_no, asset_type, category FROM asset_core');
|
||||
const existingSet = new Set();
|
||||
existingAssets.forEach(a => {
|
||||
existingSet.add(`${a.emp_no}|${a.asset_type}|${a.category}`);
|
||||
});
|
||||
|
||||
console.log(`📊 처리 대상 데이터: ${rawData.length}건`);
|
||||
|
||||
let skipCount = 0;
|
||||
let insertCount = 0;
|
||||
|
||||
for (let i = 0; i < rawData.length; i++) {
|
||||
const row = rawData[i];
|
||||
const empNo = String(row.emp_no);
|
||||
const assetType = row.asset_type || '개인PC';
|
||||
const category = row.category || 'PC';
|
||||
|
||||
// 중복 체크
|
||||
if (existingSet.has(`${empNo}|${assetType}|${category}`)) {
|
||||
skipCount++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// [Step 2] 데이터 정제
|
||||
// 1. 사용자 정보 매칭
|
||||
const matchedUser = userMap.get(empNo);
|
||||
const userName = matchedUser ? matchedUser.user_name : row.user_current;
|
||||
const deptName = matchedUser ? matchedUser.dept_name : row.current_dept;
|
||||
const position = matchedUser ? matchedUser.position : '';
|
||||
|
||||
// 2. 날짜 최적화 (purchase_date_1, purchase_date_2 중 최신값)
|
||||
const d1 = parseInt(row.purchase_date_1) || 0;
|
||||
const d2 = parseInt(row.purchase_date_2) || 0;
|
||||
const latestDate = Math.max(d1, d2);
|
||||
const purchaseDate = latestDate > 0 ? String(latestDate) : '';
|
||||
|
||||
// 3. 고유 ID 생성
|
||||
const assetId = `PC_20260615_${String(i + 1).padStart(4, '0')}`;
|
||||
const now = new Date().toISOString().replace('T', ' ').substring(0, 19);
|
||||
|
||||
try {
|
||||
// [Step 3] DB 입력
|
||||
// A. asset_core 입력
|
||||
await connection.query(
|
||||
`INSERT INTO asset_core (id, asset_code, category, asset_type, current_role, asset_purpose, service_type,
|
||||
purchase_corp, purchase_date, memo, manager_primary, current_dept, user_current, emp_no, user_position, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
[assetId, assetId, category, assetType, row.current_role, row.asset_purpose, row.service_type,
|
||||
'', purchaseDate, row.memo || '', '', deptName, userName, empNo, position, now, now]
|
||||
);
|
||||
|
||||
// B. asset_spec 입력
|
||||
await connection.query(
|
||||
`INSERT INTO asset_spec (asset_id, model_name, mainboard, cpu, ram, gpu) VALUES (?, ?, ?, ?, ?, ?)`,
|
||||
[assetId, '', row.mainboard || '', row.cpu || '', row.ram || '', row.gpu || '']
|
||||
);
|
||||
|
||||
// C. asset_volume 입력 (SSD1, SSD2, HDD1~4)
|
||||
const volumes = [
|
||||
{ type: 'SSD', cap: row.SDD1, slot: 1 },
|
||||
{ type: 'SSD', cap: row.SDD2, slot: 2 },
|
||||
{ type: 'HDD', cap: row.HDD1, slot: 3 },
|
||||
{ type: 'HDD', cap: row.HDD2, slot: 4 },
|
||||
{ type: 'HDD', cap: row.HDD3, slot: 5 },
|
||||
{ type: 'HDD', cap: row.HDD4, slot: 6 }
|
||||
];
|
||||
|
||||
for (const vol of volumes) {
|
||||
if (vol.cap && vol.cap !== '0' && vol.cap !== 0) {
|
||||
await connection.query(
|
||||
`INSERT INTO asset_volume (asset_id, disk_type, capacity, slot_no) VALUES (?, ?, ?, ?)`,
|
||||
[assetId, vol.type, String(vol.cap), vol.slot]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
insertCount++;
|
||||
existingSet.add(`${empNo}|${assetType}|${category}`); // 실시간 중복 방지 추가
|
||||
} catch (err) {
|
||||
console.error(`❌ [${empNo}] 처리 중 오류:`, err.message);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`\n✨ 작업 완료!`);
|
||||
console.log(`- 신규 입력: ${insertCount}건`);
|
||||
console.log(`- 중복 스킵: ${skipCount}건`);
|
||||
|
||||
await connection.end();
|
||||
}
|
||||
|
||||
importAssets().catch(console.error);
|
||||
@@ -1,164 +0,0 @@
|
||||
const XLSX = require('xlsx');
|
||||
const mysql = require('mysql2/promise');
|
||||
const dotenv = require('dotenv');
|
||||
const path = require('path');
|
||||
|
||||
dotenv.config({ path: path.join(__dirname, '../.env') });
|
||||
|
||||
const { DB_HOST, DB_USER, DB_PASS, DB_NAME, DB_PORT } = process.env;
|
||||
|
||||
// 용량 정제 함수
|
||||
function parseCapacity(val) {
|
||||
if (!val || val === '0' || val === 0) return null;
|
||||
|
||||
let str = String(val).toUpperCase();
|
||||
|
||||
// 1. 괄호와 그 안의 내용 제거
|
||||
str = str.replace(/\(.*\)/g, '').trim();
|
||||
|
||||
// 2. 숫자와 단위 분리
|
||||
const numMatch = str.match(/[\d.]+/);
|
||||
if (!numMatch) return null;
|
||||
|
||||
let num = parseFloat(numMatch[0]);
|
||||
let unit = 'GB'; // 기본 단위
|
||||
|
||||
if (str.includes('TB')) {
|
||||
unit = 'TB';
|
||||
} else if (str.includes('GB')) {
|
||||
// 4자리수 GB인 경우 TB로 전환 (지시사항 1번)
|
||||
if (num >= 1000) {
|
||||
num = num / 1000;
|
||||
unit = 'TB';
|
||||
} else {
|
||||
unit = 'GB';
|
||||
}
|
||||
} else {
|
||||
// 단위가 명시되지 않은 경우 숫자의 크기로 판단
|
||||
if (num >= 1000) {
|
||||
num = num / 1000;
|
||||
unit = 'TB';
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
capacity: parseFloat(num.toFixed(2)),
|
||||
unit: unit
|
||||
};
|
||||
}
|
||||
|
||||
async function importAssets() {
|
||||
const connection = await mysql.createConnection({
|
||||
host: DB_HOST,
|
||||
user: DB_USER,
|
||||
password: DB_PASS,
|
||||
database: DB_NAME,
|
||||
port: parseInt(DB_PORT || '3306')
|
||||
});
|
||||
|
||||
console.log('🚀 [Step 1] 데이터 로드 및 사전 준비 (정제 로직 강화)...');
|
||||
|
||||
const workbook = XLSX.readFile('asset_pc (2026.06.15).xlsx');
|
||||
const sheet = workbook.Sheets[workbook.SheetNames[0]];
|
||||
const rawData = XLSX.utils.sheet_to_json(sheet);
|
||||
|
||||
// system_users 데이터 맵
|
||||
const [userRows] = await connection.query('SELECT emp_no, user_name, dept_name, position, status FROM system_users');
|
||||
const userMap = new Map();
|
||||
userRows.forEach(u => userMap.set(String(u.emp_no), u));
|
||||
|
||||
// 기존 자산 중복 체크용 (emp_no + asset_type + category + user_current)
|
||||
const [existingAssets] = await connection.query('SELECT emp_no, asset_type, category, user_current FROM asset_core');
|
||||
const existingSet = new Set();
|
||||
existingAssets.forEach(a => {
|
||||
existingSet.add(`${a.emp_no || ''}|${a.asset_type}|${a.category}|${a.user_current}`);
|
||||
});
|
||||
|
||||
console.log(`📊 처리 대상 데이터: ${rawData.length}건`);
|
||||
|
||||
let skipCount = 0;
|
||||
let insertCount = 0;
|
||||
let errorCount = 0;
|
||||
|
||||
for (let i = 0; i < rawData.length; i++) {
|
||||
const row = rawData[i];
|
||||
const empNo = row.emp_no ? String(row.emp_no) : ''; // 사번 없는 행 처리 (지시사항 3번)
|
||||
const assetType = row.asset_type || '개인PC';
|
||||
const category = row.category || 'PC';
|
||||
const userCurrent = row.user_current || '';
|
||||
|
||||
// 중복 체크
|
||||
const dupKey = `${empNo}|${assetType}|${category}|${userCurrent}`;
|
||||
if (existingSet.has(dupKey)) {
|
||||
skipCount++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// [Step 2] 데이터 정제
|
||||
const matchedUser = empNo ? userMap.get(empNo) : null;
|
||||
const userName = matchedUser ? matchedUser.user_name : userCurrent;
|
||||
const deptName = matchedUser ? matchedUser.dept_name : (row.current_dept || '');
|
||||
const position = matchedUser ? matchedUser.position : '';
|
||||
|
||||
const d1 = parseInt(row.purchase_date_1) || 0;
|
||||
const d2 = parseInt(row.purchase_date_2) || 0;
|
||||
const purchaseDate = Math.max(d1, d2) > 0 ? String(Math.max(d1, d2)) : '';
|
||||
|
||||
const assetId = `PC_20260615_${String(i + 1).padStart(4, '0')}`;
|
||||
const now = new Date().toISOString().replace('T', ' ').substring(0, 19);
|
||||
|
||||
try {
|
||||
// [Step 3] DB 입력
|
||||
// A. asset_core
|
||||
await connection.query(
|
||||
`INSERT INTO asset_core (id, asset_code, category, asset_type, current_role, asset_purpose, service_type,
|
||||
purchase_date, memo, current_dept, user_current, emp_no, user_position, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
[assetId, assetId, category, assetType, row.current_role || '', row.asset_purpose || '', row.service_type || '',
|
||||
purchaseDate, row.memo || '', deptName, userName, empNo, position, now, now]
|
||||
);
|
||||
|
||||
// B. asset_spec
|
||||
await connection.query(
|
||||
`INSERT INTO asset_spec (asset_id, mainboard, cpu, ram, gpu) VALUES (?, ?, ?, ?, ?)`,
|
||||
[assetId, row.mainboard || '', row.cpu || '', row.ram || '', row.gpu || '']
|
||||
);
|
||||
|
||||
// C. asset_volume
|
||||
const volCols = [
|
||||
{ key: 'SDD1', type: 'SSD', slot: 1 },
|
||||
{ key: 'SDD2', type: 'SSD', slot: 2 },
|
||||
{ key: 'HDD1', type: 'HDD', slot: 3 },
|
||||
{ key: 'HDD2', type: 'HDD', slot: 4 },
|
||||
{ key: 'HDD3', type: 'HDD', slot: 5 },
|
||||
{ key: 'HDD4', type: 'HDD', slot: 6 }
|
||||
];
|
||||
|
||||
for (const col of volCols) {
|
||||
const rawVol = row[col.key];
|
||||
const parsed = parseCapacity(rawVol);
|
||||
if (parsed) {
|
||||
await connection.query(
|
||||
`INSERT INTO asset_volume (asset_id, disk_type, capacity, unit, slot_no) VALUES (?, ?, ?, ?, ?)`,
|
||||
[assetId, col.type, parsed.capacity, parsed.unit, col.slot]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
insertCount++;
|
||||
existingSet.add(dupKey);
|
||||
} catch (err) {
|
||||
errorCount++;
|
||||
console.error(`❌ [Row ${i + 2}] ${empNo || 'Public'}: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`\n✨ 작업 완료!`);
|
||||
console.log(`- 신규 입력: ${insertCount}건`);
|
||||
console.log(`- 중복 스킵: ${skipCount}건`);
|
||||
console.log(`- 오류 실패: ${errorCount}건`);
|
||||
|
||||
await connection.end();
|
||||
}
|
||||
|
||||
importAssets().catch(console.error);
|
||||
@@ -1,61 +0,0 @@
|
||||
const XLSX = require('xlsx');
|
||||
const mysql = require('mysql2/promise');
|
||||
const dotenv = require('dotenv');
|
||||
const path = require('path');
|
||||
|
||||
dotenv.config({ path: path.join(__dirname, '../.env') });
|
||||
|
||||
const { DB_HOST, DB_USER, DB_PASS, DB_NAME, DB_PORT } = process.env;
|
||||
|
||||
async function importUsers() {
|
||||
const connection = await mysql.createConnection({
|
||||
host: DB_HOST,
|
||||
user: DB_USER,
|
||||
password: DB_PASS,
|
||||
database: DB_NAME,
|
||||
port: parseInt(DB_PORT || '3306')
|
||||
});
|
||||
|
||||
console.log('🚀 Excel 데이터 로드 중...');
|
||||
const workbook = XLSX.readFile('system_User (20260615).xlsx');
|
||||
const sheetName = workbook.SheetNames[0];
|
||||
const sheet = workbook.Sheets[sheetName];
|
||||
const data = XLSX.utils.sheet_to_json(sheet);
|
||||
|
||||
console.log(`📊 총 ${data.length}개의 데이터를 찾았습니다.`);
|
||||
|
||||
// 기존 데이터 삭제 여부 (사용자 요구사항에 따라 결정 가능하지만, 보통 초기화 후 재입입)
|
||||
// 여기서는 중복 방지를 위해 기존 데이터를 삭제하고 새로 넣는 방식을 취하겠습니다.
|
||||
console.log('🧹 기존 system_users 데이터 삭제 중...');
|
||||
await connection.query('DELETE FROM system_users');
|
||||
|
||||
console.log('📥 데이터 삽입 중...');
|
||||
let successCount = 0;
|
||||
|
||||
for (let i = 0; i < data.length; i++) {
|
||||
const row = data[i];
|
||||
const { emp_no, user_name, dept_name, position, status } = row;
|
||||
|
||||
// ID 생성 (USR_ + 인덱스 001 형식)
|
||||
const id = `USR_${String(i + 1).padStart(3, '0')}`;
|
||||
const createdAt = new Date().toISOString().replace('T', ' ').substring(0, 19);
|
||||
|
||||
try {
|
||||
await connection.query(
|
||||
'INSERT INTO system_users (id, emp_no, user_name, dept_name, position, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)',
|
||||
[id, String(emp_no), user_name, dept_name, position, status, createdAt]
|
||||
);
|
||||
successCount++;
|
||||
} catch (err) {
|
||||
console.error(`❌ 삽입 실패 (Row ${i + 2}):`, err.message);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`✅ 완료: ${successCount}개의 사용자가 성공적으로 등록되었습니다.`);
|
||||
await connection.end();
|
||||
}
|
||||
|
||||
importUsers().catch(err => {
|
||||
console.error('❌ 작업 중 오류 발생:', err);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -1,7 +0,0 @@
|
||||
const XLSX = require('xlsx');
|
||||
const workbook = XLSX.readFile('asset_pc (2026.06.15).xlsx');
|
||||
const sheetName = workbook.SheetNames[0];
|
||||
const sheet = workbook.Sheets[sheetName];
|
||||
const data = XLSX.utils.sheet_to_json(sheet, { header: 1 });
|
||||
console.log('Headers:', JSON.stringify(data[0], null, 2));
|
||||
console.log('Sample Row 1:', JSON.stringify(data[1], null, 2));
|
||||
@@ -1,6 +0,0 @@
|
||||
const XLSX = require('xlsx');
|
||||
const workbook = XLSX.readFile('system_User (20260615).xlsx');
|
||||
const sheetName = workbook.SheetNames[0];
|
||||
const sheet = workbook.Sheets[sheetName];
|
||||
const data = XLSX.utils.sheet_to_json(sheet, { header: 1 });
|
||||
console.log(JSON.stringify(data.slice(0, 5), null, 2));
|
||||
@@ -1,18 +0,0 @@
|
||||
const mysql = require('mysql2/promise');
|
||||
require('dotenv').config();
|
||||
|
||||
async function rawCheck() {
|
||||
const connection = await mysql.createConnection({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASS,
|
||||
database: process.env.DB_NAME,
|
||||
port: parseInt(process.env.DB_PORT || '3306')
|
||||
});
|
||||
|
||||
const [rows] = await connection.query('SELECT user_current, emp_no FROM asset_core WHERE id LIKE "PC_20260615_%" LIMIT 10');
|
||||
console.log(rows);
|
||||
await connection.end();
|
||||
}
|
||||
|
||||
rawCheck().catch(console.error);
|
||||
@@ -1,85 +0,0 @@
|
||||
const mysql = require('mysql2/promise');
|
||||
require('dotenv').config();
|
||||
|
||||
async function rebuildAssetCodes() {
|
||||
const connection = await mysql.createConnection({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASS,
|
||||
database: process.env.DB_NAME,
|
||||
port: parseInt(process.env.DB_PORT || '3306')
|
||||
});
|
||||
|
||||
console.log('🚀 [Step 1] 신규 자산 구매일 업데이트 (YYYY-12-01)...');
|
||||
|
||||
// 1. 오늘 입력한 자산들 조회
|
||||
const [rows] = await connection.query(
|
||||
'SELECT id, purchase_date FROM asset_core WHERE id LIKE "PC_20260615_%"'
|
||||
);
|
||||
console.log(`대상 자산: ${rows.length}건`);
|
||||
|
||||
// 2. 구매일자 업데이트 (연도만 있는 경우 -12-01 추가)
|
||||
for (const row of rows) {
|
||||
if (row.purchase_date && row.purchase_date.length === 4) {
|
||||
const newDate = `${row.purchase_date}-12-01`;
|
||||
await connection.query(
|
||||
'UPDATE asset_core SET purchase_date = ? WHERE id = ?',
|
||||
[newDate, row.id]
|
||||
);
|
||||
}
|
||||
}
|
||||
console.log('✅ 구매일 업데이트 완료.');
|
||||
|
||||
console.log('\n🚀 [Step 2] 자산번호(asset_code) 재매핑 시작...');
|
||||
|
||||
// 3. 연도별로 그룹화하여 자산번호 부여
|
||||
// 연도 목록 추출
|
||||
const [yearRows] = await connection.query(
|
||||
'SELECT DISTINCT LEFT(purchase_date, 4) as year FROM asset_core WHERE id LIKE "PC_20260615_%" ORDER BY year'
|
||||
);
|
||||
|
||||
for (const yRow of yearRows) {
|
||||
const year = yRow.year;
|
||||
const yearMonth = `${year}12`;
|
||||
const pattern = `PC-${yearMonth}-%`;
|
||||
|
||||
console.log(`--- [${year}년] 처리 중 ---`);
|
||||
|
||||
// 해당 연도/월의 기존 최대 순번 조회
|
||||
const [maxRows] = await connection.query(
|
||||
'SELECT asset_code FROM asset_core WHERE asset_code LIKE ? AND id NOT LIKE "PC_20260615_%"',
|
||||
[pattern]
|
||||
);
|
||||
|
||||
let maxSeq = 0;
|
||||
maxRows.forEach(r => {
|
||||
const parts = r.asset_code.split('-');
|
||||
const seq = parseInt(parts[2]);
|
||||
if (seq > maxSeq) maxSeq = seq;
|
||||
});
|
||||
|
||||
console.log(`기존 최대 순번: ${maxSeq}`);
|
||||
|
||||
// 해당 연도 자산들 순차적으로 번호 부여
|
||||
const [assetsOfYear] = await connection.query(
|
||||
'SELECT id FROM asset_core WHERE id LIKE "PC_20260615_%" AND purchase_date LIKE ? ORDER BY id',
|
||||
[`${year}-12%`]
|
||||
);
|
||||
|
||||
let currentSeq = maxSeq + 1;
|
||||
for (const asset of assetsOfYear) {
|
||||
const newCode = `PC-${yearMonth}-${String(currentSeq).padStart(4, '0')}`;
|
||||
await connection.query(
|
||||
'UPDATE asset_core SET asset_code = ? WHERE id = ?',
|
||||
[newCode, asset.id]
|
||||
);
|
||||
currentSeq++;
|
||||
}
|
||||
console.log(`신규 부여 완료: ${assetsOfYear.length}건 (순번 ${maxSeq + 1} ~ ${currentSeq - 1})`);
|
||||
}
|
||||
|
||||
console.log('\n✨ 모든 작업이 완료되었습니다.');
|
||||
await connection.end();
|
||||
}
|
||||
|
||||
rebuildAssetCodes().catch(console.error);
|
||||
@@ -1,85 +0,0 @@
|
||||
const XLSX = require('xlsx');
|
||||
const mysql = require('mysql2/promise');
|
||||
require('dotenv').config();
|
||||
|
||||
async function reexamineData() {
|
||||
const connection = await mysql.createConnection({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASS,
|
||||
database: process.env.DB_NAME,
|
||||
port: parseInt(process.env.DB_PORT || '3306')
|
||||
});
|
||||
|
||||
console.log('🧐 [전수 조사] 엑셀 vs DB 데이터 비교 분석...');
|
||||
|
||||
// 1. 엑셀 데이터 로드
|
||||
const workbook = XLSX.readFile('asset_pc (2026.06.15).xlsx');
|
||||
const sheet = workbook.Sheets[workbook.SheetNames[0]];
|
||||
const excelRows = XLSX.utils.sheet_to_json(sheet);
|
||||
|
||||
// 2. DB 데이터 로드
|
||||
const [dbRows] = await connection.query(`
|
||||
SELECT id, asset_code, asset_type, user_current, emp_no, current_dept
|
||||
FROM asset_core
|
||||
WHERE id LIKE "PC_20260615_%"
|
||||
`);
|
||||
const dbMap = new Map();
|
||||
dbRows.forEach(r => dbMap.set(r.id, r));
|
||||
|
||||
const report = {
|
||||
total: excelRows.length,
|
||||
publicInExcelWithEmpNo: [], // 엑셀은 공용PC인데 사번이 있는 경우
|
||||
personalInExcelNoEmpNo: [], // 엑셀은 개인PC인데 사번이 없는 경우
|
||||
typeMismatch: [], // 엑셀과 DB의 asset_type이 다른 경우
|
||||
userMismatch: [] // 사용자명이 크게 다른 경우
|
||||
};
|
||||
|
||||
for (let i = 0; i < excelRows.length; i++) {
|
||||
const ex = excelRows[i];
|
||||
const id = `PC_20260615_${String(i + 1).padStart(4, '0')}`;
|
||||
const db = dbMap.get(id);
|
||||
|
||||
if (!db) continue;
|
||||
|
||||
const exType = ex.asset_type || '개인PC';
|
||||
const exEmpNo = ex.emp_no ? String(ex.emp_no) : null;
|
||||
const exUser = ex.user_current || '';
|
||||
|
||||
// A. 공용PC인데 사번이 있는 경우 (가장 큰 혼란 포인트)
|
||||
if (exType === '공용PC' && exEmpNo) {
|
||||
report.publicInExcelWithEmpNo.push({ id, exUser, exEmpNo, exDept: ex.current_dept });
|
||||
}
|
||||
|
||||
// B. 개인PC인데 사번이 없는 경우
|
||||
if (exType === '개인PC' && !exEmpNo) {
|
||||
report.personalInExcelNoEmpNo.push({ id, exUser, exDept: ex.current_dept });
|
||||
}
|
||||
|
||||
// C. DB와의 타입 불일치 (현재 DB 상태 체크)
|
||||
if (db.asset_type !== exType) {
|
||||
report.typeMismatch.push({ id, exType, dbType: db.asset_type, user: db.user_current });
|
||||
}
|
||||
}
|
||||
|
||||
console.log('\n================================================');
|
||||
console.log(`📊 전수 조사 요약 (총 ${report.total}건)`);
|
||||
console.log(`1. 엑셀은 '공용PC'이나 '사번'이 있는 항목: ${report.publicInExcelWithEmpNo.length}건`);
|
||||
console.log(`2. 엑셀은 '개인PC'이나 '사번'이 없는 항목: ${report.personalInExcelNoEmpNo.length}건`);
|
||||
console.log(`3. 현재 DB와 엑셀의 '자산유형' 불일치: ${report.typeMismatch.length}건`);
|
||||
console.log('================================================\n');
|
||||
|
||||
if (report.publicInExcelWithEmpNo.length > 0) {
|
||||
console.log('⚠️ [그룹 1] 공용PC인데 실사용자/관리자가 지정된 사례 (샘플 15건):');
|
||||
console.table(report.publicInExcelWithEmpNo.slice(0, 15));
|
||||
}
|
||||
|
||||
if (report.personalInExcelNoEmpNo.length > 0) {
|
||||
console.log('\n⚠️ [그룹 2] 개인PC인데 사번 정보가 누락된 사례 (샘플 15건):');
|
||||
console.table(report.personalInExcelNoEmpNo.slice(0, 15));
|
||||
}
|
||||
|
||||
await connection.end();
|
||||
}
|
||||
|
||||
reexamineData().catch(console.error);
|
||||
@@ -1,92 +0,0 @@
|
||||
const XLSX = require('xlsx');
|
||||
const mysql = require('mysql2/promise');
|
||||
const dotenv = require('dotenv');
|
||||
const path = require('path');
|
||||
|
||||
dotenv.config({ path: path.join(__dirname, '../.env') });
|
||||
|
||||
const { DB_HOST, DB_USER, DB_PASS, DB_NAME, DB_PORT } = process.env;
|
||||
|
||||
async function restoreAndMerge() {
|
||||
const connection = await mysql.createConnection({
|
||||
host: DB_HOST,
|
||||
user: DB_USER,
|
||||
password: DB_PASS,
|
||||
database: DB_NAME,
|
||||
port: parseInt(DB_PORT || '3306')
|
||||
});
|
||||
|
||||
console.log('🔄 데이터 복구 및 병합 시작...');
|
||||
|
||||
// 1. 백업 파일에서 기존 데이터(212건) 로드
|
||||
const workbookBackup = XLSX.readFile('backupDB_20260602.xlsx');
|
||||
const oldUsers = XLSX.utils.sheet_to_json(workbookBackup.Sheets['system_users']);
|
||||
|
||||
// 2. 신규 파일에서 데이터(987건) 로드
|
||||
const workbookNew = XLSX.readFile('system_User (20260615).xlsx');
|
||||
const newUsers = XLSX.utils.sheet_to_json(workbookNew.Sheets[workbookNew.SheetNames[0]]);
|
||||
|
||||
console.log(`기본 백업 데이터: ${oldUsers.length}건`);
|
||||
console.log(`신규 추가 데이터: ${newUsers.length}건`);
|
||||
|
||||
// 테이블 비우기 (실수를 바로잡기 위해 다시 시작)
|
||||
await connection.query('DELETE FROM system_users');
|
||||
|
||||
const insertedEmpNos = new Set();
|
||||
let restoreCount = 0;
|
||||
let addCount = 0;
|
||||
|
||||
// 3. 기존 데이터 복구 (ID 보존 시도)
|
||||
for (const user of oldUsers) {
|
||||
const { id, emp_no, user_name, dept_name, position, status, created_at } = user;
|
||||
|
||||
// 엑셀 날짜 처리 (숫자로 되어 있을 경우)
|
||||
let finalCreatedAt = created_at;
|
||||
if (typeof created_at === 'number') {
|
||||
const date = new Date((created_at - 25569) * 86400 * 1000);
|
||||
finalCreatedAt = date.toISOString().replace('T', ' ').substring(0, 19);
|
||||
}
|
||||
|
||||
try {
|
||||
await connection.query(
|
||||
'INSERT INTO system_users (id, emp_no, user_name, dept_name, position, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)',
|
||||
[id, String(emp_no), user_name, dept_name, position, status, finalCreatedAt]
|
||||
);
|
||||
insertedEmpNos.add(String(emp_no));
|
||||
restoreCount++;
|
||||
} catch (err) {
|
||||
console.error(`❌ 복구 실패 (emp_no: ${emp_no}):`, err.message);
|
||||
}
|
||||
}
|
||||
|
||||
// 4. 신규 데이터 추가 (중복 제외)
|
||||
for (let i = 0; i < newUsers.length; i++) {
|
||||
const user = newUsers[i];
|
||||
const { emp_no, user_name, dept_name, position, status } = user;
|
||||
const strEmpNo = String(emp_no);
|
||||
|
||||
if (insertedEmpNos.has(strEmpNo)) {
|
||||
continue; // 이미 복구된 데이터는 스킵
|
||||
}
|
||||
|
||||
// 신규 데이터용 ID 생성 (기존 ID와 겹치지 않게 'NEW_' 접두어 또는 시퀀스 사용)
|
||||
// 여기서는 단순히 시퀀스로 처리 (최대 ID 확인 후 +1 하는 방식이 좋으나 여기선 간단히)
|
||||
const id = `USR_N_${String(i + 1).padStart(4, '0')}`;
|
||||
const createdAt = new Date().toISOString().replace('T', ' ').substring(0, 19);
|
||||
|
||||
try {
|
||||
await connection.query(
|
||||
'INSERT INTO system_users (id, emp_no, user_name, dept_name, position, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)',
|
||||
[id, strEmpNo, user_name, dept_name, position, status, createdAt]
|
||||
);
|
||||
addCount++;
|
||||
} catch (err) {
|
||||
console.error(`❌ 추가 실패 (emp_no: ${emp_no}):`, err.message);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`✅ 복구 완료: 기존 ${restoreCount}건 복구, 신규 ${addCount}건 추가 (총 ${restoreCount + addCount}건)`);
|
||||
await connection.end();
|
||||
}
|
||||
|
||||
restoreAndMerge().catch(console.error);
|
||||
@@ -1,231 +0,0 @@
|
||||
const assert = require('assert');
|
||||
const http = require('http');
|
||||
const mysql = require('mysql2/promise');
|
||||
require('dotenv').config();
|
||||
|
||||
const BASE_URL = 'http://localhost:3001';
|
||||
|
||||
function request(method, path, body = null) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const url = `${BASE_URL}${path}`;
|
||||
const options = {
|
||||
method: method,
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
};
|
||||
const req = http.request(url, options, (res) => {
|
||||
let data = '';
|
||||
res.on('data', (chunk) => { data += chunk; });
|
||||
res.on('end', () => {
|
||||
try {
|
||||
const parsed = JSON.parse(data);
|
||||
resolve({ status: res.statusCode, body: parsed });
|
||||
} catch (e) {
|
||||
resolve({ status: res.statusCode, body: data });
|
||||
}
|
||||
});
|
||||
});
|
||||
req.on('error', (err) => reject(err));
|
||||
if (body) {
|
||||
req.write(JSON.stringify(body));
|
||||
}
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
async function runTests() {
|
||||
console.log('🧪 Starting Audit TDD Tests...');
|
||||
const pool = mysql.createPool({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASS,
|
||||
database: process.env.DB_NAME,
|
||||
port: process.env.DB_PORT
|
||||
});
|
||||
|
||||
const connection = await pool.getConnection();
|
||||
|
||||
try {
|
||||
// Clean up any test records
|
||||
console.log('🧹 Cleaning up test records...');
|
||||
await connection.query("DELETE FROM asset_audit_pending WHERE asset_code LIKE 'TEST-ASSET-%'");
|
||||
|
||||
// Check if test assets exist in asset_core & asset_location
|
||||
// We will use an existing asset or insert a dummy test asset
|
||||
const [testAssets] = await connection.query("SELECT id FROM asset_core WHERE asset_code = 'TEST-ASSET-001'");
|
||||
let testAssetId;
|
||||
if (testAssets.length === 0) {
|
||||
console.log('⏳ Inserting dummy test asset...');
|
||||
testAssetId = 'test_asset_uuid_123456';
|
||||
await connection.query(`
|
||||
INSERT INTO asset_core (id, asset_code, category, asset_type, asset_purpose)
|
||||
VALUES (?, 'TEST-ASSET-001', 'server', 'Server', 'TDD Test Server')
|
||||
`, [testAssetId]);
|
||||
await connection.query(`
|
||||
INSERT INTO asset_location (asset_id, location, location_detail, location_photo, loc_x, loc_y, is_active)
|
||||
VALUES (?, 'Initial Location', 'Initial Detail', 'initial.png', '10.00', '10.00', 1)
|
||||
`, [testAssetId]);
|
||||
} else {
|
||||
testAssetId = testAssets[0].id;
|
||||
}
|
||||
|
||||
// 1. Test GET /api/physical-locations
|
||||
console.log('👉 Test 1: GET /api/physical-locations');
|
||||
const res1 = await request('GET', '/api/physical-locations');
|
||||
assert.strictEqual(res1.status, 200, 'GET /api/physical-locations should return 200');
|
||||
assert(Array.isArray(res1.body), 'Response should be an array of physical locations');
|
||||
assert(res1.body.length > 0, 'Should return at least one physical location');
|
||||
console.log(`✅ Test 1 Passed: Found ${res1.body.length} physical locations.`);
|
||||
|
||||
const sampleLocation = res1.body[0].location_code;
|
||||
|
||||
// 2. Test POST /api/audit/scan
|
||||
console.log(`👉 Test 2: POST /api/audit/scan (Location: ${sampleLocation}, Asset: TEST-ASSET-001)`);
|
||||
const res2 = await request('POST', '/api/audit/scan', {
|
||||
asset_code: 'TEST-ASSET-001',
|
||||
physical_location_code: sampleLocation
|
||||
});
|
||||
assert.strictEqual(res2.status, 200, 'POST /api/audit/scan should return 200');
|
||||
assert.strictEqual(res2.body.success, true, 'Response success should be true');
|
||||
assert(res2.body.pending_id, 'Response should contain pending_id');
|
||||
console.log(`✅ Test 2 Passed: Pending scan registered with ID: ${res2.body.pending_id}`);
|
||||
|
||||
const pendingId = res2.body.pending_id;
|
||||
|
||||
// 3. Test GET /api/audit/pending
|
||||
console.log('👉 Test 3: GET /api/audit/pending');
|
||||
const res3 = await request('GET', '/api/audit/pending');
|
||||
assert.strictEqual(res3.status, 200, 'GET /api/audit/pending should return 200');
|
||||
assert(Array.isArray(res3.body), 'Response should be an array');
|
||||
const pendingItem = res3.body.find(item => item.id === pendingId);
|
||||
assert(pendingItem, 'Pending list should contain the newly registered scan');
|
||||
assert.strictEqual(pendingItem.asset_code, 'TEST-ASSET-001', 'Asset code should match');
|
||||
assert.strictEqual(pendingItem.physical_location_code, sampleLocation, 'Location code should match');
|
||||
assert.strictEqual(pendingItem.status, 'PENDING', 'Status should be PENDING');
|
||||
console.log('✅ Test 3 Passed: Newly registered scan found in pending list with correct details.');
|
||||
|
||||
// 4. Test POST /api/audit/approve
|
||||
console.log(`👉 Test 4: POST /api/audit/approve (Pending ID: ${pendingId})`);
|
||||
const res4 = await request('POST', '/api/audit/approve', {
|
||||
pending_ids: [pendingId],
|
||||
processed_by: 'TDD-TESTER'
|
||||
});
|
||||
assert.strictEqual(res4.status, 200, 'POST /api/audit/approve should return 200');
|
||||
assert.strictEqual(res4.body.success, true, 'Response success should be true');
|
||||
console.log('✅ Test 4 Passed: Audit approved.');
|
||||
|
||||
// Verify database updates
|
||||
console.log('🔍 Verifying updates in database...');
|
||||
const [pendingCheck] = await connection.query(
|
||||
'SELECT status, processed_by FROM asset_audit_pending WHERE id = ?',
|
||||
[pendingId]
|
||||
);
|
||||
assert.strictEqual(pendingCheck[0].status, 'APPROVED', 'Pending record status should be APPROVED');
|
||||
assert.strictEqual(pendingCheck[0].processed_by, 'TDD-TESTER', 'Processed by should match');
|
||||
|
||||
const [locationCheck] = await connection.query(
|
||||
'SELECT physical_location_code, location_photo, loc_x, loc_y FROM asset_location WHERE asset_id = ? AND is_active = 1',
|
||||
[testAssetId]
|
||||
);
|
||||
const [physLoc] = await connection.query(
|
||||
'SELECT map_image, map_x, map_y FROM physical_locations WHERE location_code = ?',
|
||||
[sampleLocation]
|
||||
);
|
||||
assert.strictEqual(locationCheck[0].physical_location_code, sampleLocation, 'Asset location code should be updated');
|
||||
assert.strictEqual(locationCheck[0].location_photo, physLoc[0].map_image, 'Asset map_image should be updated');
|
||||
assert.strictEqual(parseFloat(locationCheck[0].loc_x).toFixed(2), parseFloat(physLoc[0].map_x).toFixed(2), 'Asset map_x should be updated');
|
||||
assert.strictEqual(parseFloat(locationCheck[0].loc_y).toFixed(2), parseFloat(physLoc[0].map_y).toFixed(2), 'Asset map_y should be updated');
|
||||
console.log('✅ Database verification passed: Asset location and map coordinates updated successfully!');
|
||||
|
||||
// 5. Test GET /api/maps (Before modification)
|
||||
console.log('👉 Test 5: GET /api/maps');
|
||||
const res5 = await request('GET', '/api/maps');
|
||||
assert.strictEqual(res5.status, 200, 'GET /api/maps should return 200');
|
||||
assert(typeof res5.body === 'object' && res5.body !== null, 'Response should be a map config object');
|
||||
console.log('✅ Test 5 Passed: GET /api/maps returned valid object.');
|
||||
|
||||
// 6. Test POST /api/maps/save
|
||||
console.log('👉 Test 6: POST /api/maps/save');
|
||||
const testMapPath = 'img/location_photo/TDD_TEST_MAP.png';
|
||||
const testBoxes = [
|
||||
{
|
||||
x: '30.50',
|
||||
y: '40.25',
|
||||
w: '10.00',
|
||||
h: '12.00',
|
||||
asset_id: testAssetId
|
||||
},
|
||||
{
|
||||
x: '50.00',
|
||||
y: '60.00',
|
||||
w: '5.00',
|
||||
h: '5.00',
|
||||
asset_id: null
|
||||
}
|
||||
];
|
||||
|
||||
const res6 = await request('POST', '/api/maps/save', {
|
||||
path: testMapPath,
|
||||
boxes: testBoxes
|
||||
});
|
||||
assert.strictEqual(res6.status, 200, 'POST /api/maps/save should return 200');
|
||||
assert.strictEqual(res6.body.success, true, 'Save should be successful');
|
||||
console.log('✅ Test 6 Passed: Map coordinate save triggered successfully.');
|
||||
|
||||
// Verify DB update directly for physical_locations
|
||||
console.log('🔍 Verifying physical_locations update in database...');
|
||||
const [physLocCheck] = await connection.query(
|
||||
'SELECT location_code, map_x, map_y, map_w, map_h FROM physical_locations WHERE map_image = ? ORDER BY location_code',
|
||||
[testMapPath]
|
||||
);
|
||||
assert.strictEqual(physLocCheck.length, 2, 'Should create 2 physical locations for the test map');
|
||||
|
||||
// First location has asset_id mapped
|
||||
assert.strictEqual(parseFloat(physLocCheck[0].map_x).toFixed(2), '30.50', 'First location X coord match');
|
||||
assert.strictEqual(parseFloat(physLocCheck[0].map_y).toFixed(2), '40.25', 'First location Y coord match');
|
||||
assert.strictEqual(parseFloat(physLocCheck[0].map_w).toFixed(2), '10.00', 'First location W size match');
|
||||
assert.strictEqual(parseFloat(physLocCheck[0].map_h).toFixed(2), '12.00', 'First location H size match');
|
||||
|
||||
// Asset location coordinates sync check
|
||||
console.log('🔍 Verifying asset_location coordination sync in database...');
|
||||
const [assetLocSyncCheck] = await connection.query(
|
||||
'SELECT loc_x, loc_y, physical_location_code FROM asset_location WHERE asset_id = ? AND is_active = 1',
|
||||
[testAssetId]
|
||||
);
|
||||
assert(assetLocSyncCheck.length > 0, 'Asset location should be active');
|
||||
assert.strictEqual(parseFloat(assetLocSyncCheck[0].loc_x).toFixed(2), '30.50', 'Asset location X should sync');
|
||||
assert.strictEqual(parseFloat(assetLocSyncCheck[0].loc_y).toFixed(2), '40.25', 'Asset location Y should sync');
|
||||
assert.strictEqual(assetLocSyncCheck[0].physical_location_code, physLocCheck[0].location_code, 'Physical location code should match');
|
||||
console.log('✅ DB Verification for save: physical_locations and asset_location coordinates synced.');
|
||||
|
||||
// 7. Test GET /api/maps (After modification)
|
||||
console.log('👉 Test 7: GET /api/maps (After saving)');
|
||||
const res7 = await request('GET', '/api/maps');
|
||||
assert.strictEqual(res7.status, 200, 'GET /api/maps should return 200');
|
||||
assert(res7.body[testMapPath], 'Returned config should contain the newly saved test map');
|
||||
const savedBoxes = res7.body[testMapPath];
|
||||
assert.strictEqual(savedBoxes.length, 2, 'Saved boxes count match');
|
||||
assert.strictEqual(savedBoxes[0].asset_id, testAssetId, 'First box asset_id match');
|
||||
assert.strictEqual(savedBoxes[0].x, '30.50', 'First box X match');
|
||||
assert.strictEqual(savedBoxes[1].asset_id, null, 'Second box asset_id is null');
|
||||
console.log('✅ Test 7 Passed: GET /api/maps returned updated configuration.');
|
||||
|
||||
// Clean up
|
||||
console.log('🧹 Cleaning up test assets...');
|
||||
await connection.query("DELETE FROM asset_audit_pending WHERE asset_code = 'TEST-ASSET-001'");
|
||||
await connection.query("DELETE FROM asset_location WHERE asset_id = ?", [testAssetId]);
|
||||
await connection.query("DELETE FROM asset_core WHERE id = ?", [testAssetId]);
|
||||
await connection.query("DELETE FROM physical_locations WHERE map_image = ?", [testMapPath]);
|
||||
|
||||
console.log('🎉 All TDD tests passed successfully!');
|
||||
} catch (err) {
|
||||
console.error('❌ TDD Test Suite Failed:', err.message);
|
||||
throw err;
|
||||
} finally {
|
||||
connection.release();
|
||||
await pool.end();
|
||||
}
|
||||
}
|
||||
|
||||
runTests().catch(() => process.exit(1));
|
||||
@@ -1,32 +0,0 @@
|
||||
const mysql = require('mysql2/promise');
|
||||
require('dotenv').config();
|
||||
|
||||
async function updateDepartments() {
|
||||
const connection = await mysql.createConnection({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASS,
|
||||
database: process.env.DB_NAME,
|
||||
port: parseInt(process.env.DB_PORT || '3306')
|
||||
});
|
||||
|
||||
console.log("🚀 부서명 '삼안' 통합 업데이트 시작...");
|
||||
|
||||
const [result] = await connection.query(`
|
||||
UPDATE asset_core
|
||||
SET current_dept = '삼안'
|
||||
WHERE current_dept NOT IN ('총괄기획실', '기술개발센터', '현타', '장헌', '한맥', 'PTC', '', '삼안')
|
||||
AND current_dept IS NOT NULL
|
||||
`);
|
||||
|
||||
console.log(`✅ 업데이트 완료: ${result.affectedRows}건의 부서명이 '삼안'으로 변경되었습니다.`);
|
||||
|
||||
// 최종 확인용 카운트
|
||||
const [rows] = await connection.query('SELECT current_dept, COUNT(*) as count FROM asset_core GROUP BY current_dept');
|
||||
console.log('\n📊 최종 부서 분포:');
|
||||
console.table(rows);
|
||||
|
||||
await connection.end();
|
||||
}
|
||||
|
||||
updateDepartments().catch(console.error);
|
||||
125
scripts/backup.sh
Normal file
125
scripts/backup.sh
Normal file
@@ -0,0 +1,125 @@
|
||||
#!/usr/bin/env sh
|
||||
|
||||
set -eu
|
||||
|
||||
COMMAND="${1:-help}"
|
||||
ENV_FILE="${ENV_FILE:-.env}"
|
||||
BACKUP_ROOT="${BACKUP_ROOT:-backups}"
|
||||
RETENTION_DAYS="${RETENTION_DAYS:-14}"
|
||||
TIMESTAMP="${BACKUP_TIMESTAMP:-$(date +%Y%m%d_%H%M%S)}"
|
||||
|
||||
log() {
|
||||
printf '[backup] %s\n' "$*"
|
||||
}
|
||||
|
||||
fail() {
|
||||
printf '[backup] %s\n' "$*" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
require_command() {
|
||||
command -v "$1" >/dev/null 2>&1 || fail "Required command not found: $1"
|
||||
}
|
||||
|
||||
has_command() {
|
||||
command -v "$1" >/dev/null 2>&1
|
||||
}
|
||||
|
||||
load_env() {
|
||||
[ -f "$ENV_FILE" ] || fail "Env file not found: $ENV_FILE"
|
||||
|
||||
case "$ENV_FILE" in
|
||||
*/*) env_path="$ENV_FILE" ;;
|
||||
*) env_path="./$ENV_FILE" ;;
|
||||
esac
|
||||
|
||||
set -a
|
||||
# shellcheck disable=SC1090
|
||||
. "$env_path"
|
||||
set +a
|
||||
|
||||
: "${DB_HOST:?DB_HOST is required in $ENV_FILE}"
|
||||
: "${DB_PORT:=3306}"
|
||||
: "${DB_USER:?DB_USER is required in $ENV_FILE}"
|
||||
: "${DB_PASS:?DB_PASS is required in $ENV_FILE}"
|
||||
: "${DB_NAME:?DB_NAME is required in $ENV_FILE}"
|
||||
}
|
||||
|
||||
db_dump() {
|
||||
require_command gzip
|
||||
load_env
|
||||
|
||||
mkdir -p "$BACKUP_ROOT/db"
|
||||
output_path="$BACKUP_ROOT/db/${DB_NAME}_${TIMESTAMP}.sql.gz"
|
||||
|
||||
log "Creating DB dump: $output_path"
|
||||
|
||||
if has_command mysqldump; then
|
||||
MYSQL_PWD="$DB_PASS" mysqldump \
|
||||
--host="$DB_HOST" \
|
||||
--port="$DB_PORT" \
|
||||
--user="$DB_USER" \
|
||||
--single-transaction \
|
||||
--quick \
|
||||
--routines \
|
||||
--triggers \
|
||||
"$DB_NAME" | gzip > "$output_path"
|
||||
elif has_command docker; then
|
||||
docker exec itam-backend sh -lc "MYSQL_PWD=\"$DB_PASS\" exec mysqldump --host=\"$DB_HOST\" --port=\"$DB_PORT\" --user=\"$DB_USER\" --single-transaction --quick --routines --triggers \"$DB_NAME\"" | gzip > "$output_path"
|
||||
else
|
||||
fail "Required command not found: mysqldump (and docker fallback unavailable)"
|
||||
fi
|
||||
|
||||
log "DB dump completed: $output_path"
|
||||
}
|
||||
|
||||
files_backup() {
|
||||
require_command tar
|
||||
mkdir -p "$BACKUP_ROOT/files"
|
||||
|
||||
archive_path="$BACKUP_ROOT/files/runtime_${TIMESTAMP}.tar.gz"
|
||||
set --
|
||||
|
||||
[ -f "$ENV_FILE" ] && set -- "$@" "$ENV_FILE"
|
||||
[ -d "uploads" ] && set -- "$@" "uploads"
|
||||
[ -f "map_config.json" ] && set -- "$@" "map_config.json"
|
||||
|
||||
[ "$#" -gt 0 ] || fail "No runtime files found to archive"
|
||||
|
||||
log "Creating runtime archive: $archive_path"
|
||||
tar -czf "$archive_path" "$@"
|
||||
log "Runtime archive completed: $archive_path"
|
||||
}
|
||||
|
||||
cleanup_backups() {
|
||||
require_command find
|
||||
[ -d "$BACKUP_ROOT" ] || {
|
||||
log "Backup root does not exist, skipping cleanup: $BACKUP_ROOT"
|
||||
return 0
|
||||
}
|
||||
|
||||
log "Deleting backup files older than ${RETENTION_DAYS} days from $BACKUP_ROOT"
|
||||
find "$BACKUP_ROOT" -type f -mtime "+$RETENTION_DAYS" -print -delete
|
||||
}
|
||||
|
||||
case "$COMMAND" in
|
||||
db)
|
||||
db_dump
|
||||
;;
|
||||
files)
|
||||
files_backup
|
||||
;;
|
||||
full)
|
||||
db_dump
|
||||
files_backup
|
||||
;;
|
||||
cleanup)
|
||||
cleanup_backups
|
||||
;;
|
||||
help|--help|-h)
|
||||
log "Commands: db | files | full | cleanup"
|
||||
;;
|
||||
*)
|
||||
fail "Unknown command: $COMMAND"
|
||||
;;
|
||||
esac
|
||||
380
server.js
380
server.js
@@ -6,6 +6,21 @@ import fs from 'fs';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
const dbConfig = {
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASS,
|
||||
database: process.env.DB_NAME,
|
||||
port: parseInt(process.env.DB_PORT || '3306')
|
||||
};
|
||||
|
||||
const getDbConnectionSummary = () => ({
|
||||
host: dbConfig.host || '(missing)',
|
||||
port: dbConfig.port,
|
||||
user: dbConfig.user || '(missing)',
|
||||
database: dbConfig.database || '(missing)'
|
||||
});
|
||||
|
||||
const app = express();
|
||||
app.use(cors());
|
||||
app.use(express.json({ limit: '50mb' }));
|
||||
@@ -18,11 +33,11 @@ if (!fs.existsSync('uploads')) {
|
||||
|
||||
// MySQL Pool Configuration
|
||||
const pool = mysql.createPool({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASS,
|
||||
database: process.env.DB_NAME,
|
||||
port: parseInt(process.env.DB_PORT || '3306'),
|
||||
host: dbConfig.host,
|
||||
user: dbConfig.user,
|
||||
password: dbConfig.password,
|
||||
database: dbConfig.database,
|
||||
port: dbConfig.port,
|
||||
waitForConnections: true,
|
||||
connectionLimit: 10,
|
||||
queueLimit: 0
|
||||
@@ -48,7 +63,15 @@ const pool = mysql.createPool({
|
||||
`);
|
||||
console.log('✅ job_spec_standards table verification completed.');
|
||||
} catch (err) {
|
||||
console.error('❌ Failed to verify/create job_spec_standards table:', err);
|
||||
console.error('❌ Failed to verify/create job_spec_standards table:', {
|
||||
db: getDbConnectionSummary(),
|
||||
code: err.code,
|
||||
errno: err.errno,
|
||||
syscall: err.syscall,
|
||||
address: err.address,
|
||||
port: err.port,
|
||||
message: err.message
|
||||
});
|
||||
} finally {
|
||||
if (connection) connection.release();
|
||||
}
|
||||
@@ -56,7 +79,15 @@ const pool = mysql.createPool({
|
||||
|
||||
// Error Handler
|
||||
const handleError = (res, err, label) => {
|
||||
console.error(`❌ [${label}] Error:`, err);
|
||||
console.error(`❌ [${label}] Error:`, {
|
||||
db: getDbConnectionSummary(),
|
||||
code: err.code,
|
||||
errno: err.errno,
|
||||
syscall: err.syscall,
|
||||
address: err.address,
|
||||
port: err.port,
|
||||
message: err.message
|
||||
});
|
||||
res.status(500).json({ error: err.message });
|
||||
};
|
||||
|
||||
@@ -82,6 +113,30 @@ const ASSET_TABLES = [
|
||||
'asset_core'
|
||||
];
|
||||
|
||||
// --- Helper Functions for Maps ---
|
||||
function getCleanMapKey(path) {
|
||||
let clean = path.replace('img/location_photo/', '').replace('.png', '');
|
||||
clean = clean.replace('서관', 'W').replace('동관', 'E');
|
||||
clean = clean.replace('한맥빌딩/MDF실/MDF_', 'HAN-MDF-');
|
||||
clean = clean.replace('기술개발센터/서버실/서버실_', 'DEV-SVR-');
|
||||
clean = clean.replace(/\//g, '-');
|
||||
return clean;
|
||||
}
|
||||
|
||||
function getLocationName(path) {
|
||||
if (path.includes('IDC')) return 'IDC';
|
||||
if (path.includes('한맥빌딩')) return '한맥빌딩';
|
||||
if (path.includes('기술개발센터')) return '기술개발센터';
|
||||
return '기타';
|
||||
}
|
||||
|
||||
function getLocationDetail(path, idx) {
|
||||
let clean = path.replace('img/location_photo/', '').replace('.png', '');
|
||||
let parts = clean.split('/');
|
||||
let lastPart = parts[parts.length - 1];
|
||||
return `${lastPart} 구역 자리 #${idx + 1}`;
|
||||
}
|
||||
|
||||
// --- API Endpoints ---
|
||||
|
||||
// 1. Generic Batch Save (Dynamic Table Detection)
|
||||
@@ -165,7 +220,7 @@ app.get('/api/assets/master', async (req, res) => {
|
||||
|
||||
const catMap = {
|
||||
'PC': 'pc', '서버': 'server', '저장매체': 'storage', '네트워크': 'network',
|
||||
'업무지원장비': 'equipment', '사무가구': 'officeSupplies', '공간정보장비': 'survey',
|
||||
'업무지원장비': 'equipment', '시설자산': 'officeSupplies', '공간정보장비': 'survey',
|
||||
'내빈/외빈': 'vip', 'PC부품': 'pcParts'
|
||||
};
|
||||
|
||||
@@ -206,9 +261,34 @@ app.post('/api/asset/:category/save', async (req, res) => {
|
||||
connection = await pool.getConnection();
|
||||
await connection.beginTransaction();
|
||||
|
||||
// 3.0.0 CPU, GPU, RAM 부품 마스터 유효성 검사
|
||||
const partsToCheck = [
|
||||
{ value: asset.cpu, category: 'CPU', label: 'CPU' },
|
||||
{ value: asset.gpu, category: 'GPU', label: 'GPU' },
|
||||
{ value: asset.ram, category: 'RAM', label: 'RAM' }
|
||||
];
|
||||
|
||||
for (const part of partsToCheck) {
|
||||
const val = String(part.value || '').trim();
|
||||
if (val) {
|
||||
const [rows] = await connection.query(
|
||||
'SELECT id FROM hardware_components_master WHERE UPPER(category) = ? AND LOWER(TRIM(component_name)) = ?',
|
||||
[part.category, val.toLowerCase()]
|
||||
);
|
||||
if (rows.length === 0) {
|
||||
await connection.rollback();
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: `입력하신 ${part.label} "${val}"은(는) 부품 마스터에 존재하지 않는 규격입니다.`
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3.0 History Tracking & Auto Field Update
|
||||
const [oldCoreRows] = await connection.query('SELECT * FROM asset_core WHERE id = ?', [asset.id]);
|
||||
const [oldSpecRows] = await connection.query('SELECT * FROM asset_spec WHERE asset_id = ?', [asset.id]);
|
||||
const [oldRemoteRows] = await connection.query('SELECT * FROM asset_remote WHERE asset_id = ? AND is_active = 1', [asset.id]);
|
||||
const oldCore = oldCoreRows[0] || {};
|
||||
const oldSpec = oldSpecRows[0] || {};
|
||||
|
||||
@@ -271,6 +351,85 @@ app.post('/api/asset/:category/save', async (req, res) => {
|
||||
});
|
||||
}
|
||||
|
||||
// 3.0.4 메모, 용도, 유형 변동 감지
|
||||
const oldMemo = String(oldCore.memo || '').trim();
|
||||
const newMemo = String(asset.memo || '').trim();
|
||||
if (newMemo !== '' && oldMemo !== newMemo) {
|
||||
historyLogs.push({
|
||||
event_type: 'MEMO_CHANGE',
|
||||
details: `[메모 변경] ${oldMemo || '(없음)'} -> ${newMemo}`
|
||||
});
|
||||
}
|
||||
|
||||
const oldPurpose = String(oldCore.asset_purpose || '').trim();
|
||||
const newPurpose = String(asset.asset_purpose || '').trim();
|
||||
if (newPurpose !== '' && oldPurpose !== newPurpose) {
|
||||
historyLogs.push({
|
||||
event_type: 'PURPOSE_CHANGE',
|
||||
details: `[용도 변경] ${oldPurpose || '(없음)'} -> ${newPurpose}`
|
||||
});
|
||||
}
|
||||
|
||||
const oldType = String(oldCore.asset_type || '').trim();
|
||||
const newType = String(asset.asset_type || '').trim();
|
||||
if (newType !== '' && oldType !== newType) {
|
||||
historyLogs.push({
|
||||
event_type: 'TYPE_CHANGE',
|
||||
details: `[유형 변경] ${oldType || '(없음)'} -> ${newType}`
|
||||
});
|
||||
}
|
||||
|
||||
// 3.0.5 접속정보 변동 감지
|
||||
const formatRemote = (r) => {
|
||||
const type = r.net_type || r.type || '';
|
||||
const name = r.net_name || r.name || '';
|
||||
const val1 = r.net_value1 || r.val1 || '';
|
||||
const val2 = r.net_value2 || r.val2 || '';
|
||||
return `${type}:${name}:${val1}:${val2}`;
|
||||
};
|
||||
|
||||
const oldRemotesSummary = oldRemoteRows.map(formatRemote).sort().join(' | ');
|
||||
|
||||
let newNets = [];
|
||||
if (asset.remotes) {
|
||||
try {
|
||||
newNets = typeof asset.remotes === 'string' ? JSON.parse(asset.remotes) : asset.remotes;
|
||||
} catch(e) { newNets = []; }
|
||||
} else if (asset.ip_address || asset.mac_address || asset.remote_tool) {
|
||||
if (asset.ip_address || asset.mac_address) {
|
||||
newNets.push({ type: 'IP', name: '기본망', val1: asset.ip_address, val2: asset.mac_address });
|
||||
}
|
||||
if (asset.remote_tool || asset.remote_id || asset.remote_pw) {
|
||||
newNets.push({ type: 'REMOTE', name: asset.remote_tool, val1: asset.remote_id, val2: asset.remote_pw });
|
||||
}
|
||||
}
|
||||
const newRemotesSummary = newNets.map(formatRemote).sort().join(' | ');
|
||||
|
||||
if (newRemotesSummary !== '' && oldRemotesSummary !== newRemotesSummary) {
|
||||
const formatDisplay = (summary) => {
|
||||
if (!summary) return '(없음)';
|
||||
return summary.split(' | ').map(item => {
|
||||
const [type, name, val1, val2] = item.split(':');
|
||||
if (type === 'IP') {
|
||||
return `[IP] ${name}: ${val1} (MAC: ${val2 || '없음'})`;
|
||||
} else {
|
||||
let id = '', pw = '';
|
||||
try {
|
||||
const parsed = JSON.parse(val2);
|
||||
id = parsed.id || '';
|
||||
pw = parsed.pw || '';
|
||||
} catch(e) { id = val1; pw = val2; }
|
||||
return `[원격] ${name}: ID=${id || '없음'}, PW=${pw ? '***' : '없음'}`;
|
||||
}
|
||||
}).join(', ');
|
||||
};
|
||||
|
||||
historyLogs.push({
|
||||
event_type: 'REMOTE_CHANGE',
|
||||
details: `[접속정보 변경] ${formatDisplay(oldRemotesSummary)} -> ${formatDisplay(newRemotesSummary)}`
|
||||
});
|
||||
}
|
||||
|
||||
// 로그 일괄 삽입
|
||||
for (const log of historyLogs) {
|
||||
await connection.query(
|
||||
@@ -518,30 +677,7 @@ app.get('/api/generate-asset-code', async (req, res) => {
|
||||
} catch (err) { handleError(res, err, 'GENERATE CODE'); }
|
||||
});
|
||||
|
||||
function getCleanMapKey(path) {
|
||||
let clean = path.replace('img/location_photo/', '').replace('.png', '');
|
||||
clean = clean.replace('서관', 'W').replace('동관', 'E');
|
||||
clean = clean.replace('한맥빌딩/MDF실/MDF_', 'HAN-MDF-');
|
||||
clean = clean.replace('기술개발센터/서버실/서버실_', 'DEV-SVR-');
|
||||
clean = clean.replace(/\//g, '-');
|
||||
return clean;
|
||||
}
|
||||
|
||||
function getLocationName(path) {
|
||||
if (path.includes('IDC')) return 'IDC';
|
||||
if (path.includes('한맥빌딩')) return '한맥빌딩';
|
||||
if (path.includes('기술개발센터')) return '기술개발센터';
|
||||
return '기타';
|
||||
}
|
||||
|
||||
function getLocationDetail(path, idx) {
|
||||
let clean = path.replace('img/location_photo/', '').replace('.png', '');
|
||||
let parts = clean.split('/');
|
||||
let lastPart = parts[parts.length - 1];
|
||||
return `${lastPart} 구역 자리 #${idx + 1}`;
|
||||
}
|
||||
|
||||
// 6. Map Config API
|
||||
// 6. Map Config API (Adopt database-driven locations from origin/QR_setting)
|
||||
app.get('/api/maps', async (req, res) => {
|
||||
try {
|
||||
const query = `
|
||||
@@ -581,6 +717,83 @@ app.get('/api/maps', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/maps/save', async (req, res) => {
|
||||
let connection;
|
||||
try {
|
||||
const { path, boxes } = req.body;
|
||||
if (!path) return res.status(400).json({ error: 'Path is required' });
|
||||
if (!Array.isArray(boxes)) return res.status(400).json({ error: 'Boxes must be an array' });
|
||||
|
||||
connection = await pool.getConnection();
|
||||
await connection.beginTransaction();
|
||||
|
||||
const cleanKey = getCleanMapKey(path);
|
||||
const locName = getLocationName(path);
|
||||
|
||||
// 1. Get old location codes for this map
|
||||
const [oldLocs] = await connection.query(
|
||||
'SELECT location_code FROM physical_locations WHERE map_image = ?',
|
||||
[path]
|
||||
);
|
||||
const oldLocCodes = oldLocs.map(r => r.location_code);
|
||||
|
||||
// 2. Deactivate and clear foreign key references in asset_location to these old location codes
|
||||
if (oldLocCodes.length > 0) {
|
||||
await connection.query(
|
||||
'UPDATE asset_location SET is_active = 0, deactivated_at = NOW(), physical_location_code = NULL WHERE physical_location_code IN (?)',
|
||||
[oldLocCodes]
|
||||
);
|
||||
}
|
||||
|
||||
// 3. Delete old physical locations for this map
|
||||
await connection.query(
|
||||
'DELETE FROM physical_locations WHERE map_image = ?',
|
||||
[path]
|
||||
);
|
||||
|
||||
// 4. Insert new physical locations and setup asset_location mappings
|
||||
for (let i = 0; i < boxes.length; i++) {
|
||||
const box = boxes[i];
|
||||
const padIdx = String(i + 1).padStart(3, '0');
|
||||
const locCode = `LOC-${cleanKey}-${padIdx}`;
|
||||
const locDetail = getLocationDetail(path, i);
|
||||
|
||||
// Insert physical location
|
||||
await connection.query(`
|
||||
INSERT INTO physical_locations
|
||||
(location_code, location_name, location_detail, map_image, map_x, map_y, map_w, map_h)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`, [locCode, locName, locDetail, path, box.x, box.y, box.w, box.h]);
|
||||
|
||||
// If asset_id is mapped, update asset_location
|
||||
if (box.asset_id) {
|
||||
// Deactivate old active locations for this asset
|
||||
await connection.query(
|
||||
'UPDATE asset_location SET is_active = 0, deactivated_at = NOW() WHERE asset_id = ? AND is_active = 1',
|
||||
[box.asset_id]
|
||||
);
|
||||
|
||||
// Insert new active location mapping
|
||||
const pathPartsForMap = path.split('/');
|
||||
const stdDetailForMap = pathPartsForMap[pathPartsForMap.length - 2] || locDetail;
|
||||
await connection.query(`
|
||||
INSERT INTO asset_location
|
||||
(asset_id, location, location_detail, location_photo, loc_x, loc_y, physical_location_code, is_active)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, 1)
|
||||
`, [box.asset_id, locName, stdDetailForMap, path, box.x, box.y, locCode]);
|
||||
}
|
||||
}
|
||||
|
||||
await connection.commit();
|
||||
res.json({ success: true, message: 'Map and Database synced successfully' });
|
||||
} catch (err) {
|
||||
if (connection) await connection.rollback();
|
||||
handleError(res, err, 'SAVE MAPS SYNC');
|
||||
} finally {
|
||||
if (connection) connection.release();
|
||||
}
|
||||
});
|
||||
|
||||
// 6.5. Get Hardware Components Master List
|
||||
app.get('/api/hardware-components', async (req, res) => {
|
||||
try {
|
||||
@@ -732,85 +945,8 @@ app.delete('/api/system-users/:id', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/maps/save', async (req, res) => {
|
||||
let connection;
|
||||
try {
|
||||
const { path, boxes } = req.body;
|
||||
if (!path) return res.status(400).json({ error: 'Path is required' });
|
||||
if (!Array.isArray(boxes)) return res.status(400).json({ error: 'Boxes must be an array' });
|
||||
|
||||
connection = await pool.getConnection();
|
||||
await connection.beginTransaction();
|
||||
|
||||
const cleanKey = getCleanMapKey(path);
|
||||
const locName = getLocationName(path);
|
||||
|
||||
// 1. Get old location codes for this map
|
||||
const [oldLocs] = await connection.query(
|
||||
'SELECT location_code FROM physical_locations WHERE map_image = ?',
|
||||
[path]
|
||||
);
|
||||
const oldLocCodes = oldLocs.map(r => r.location_code);
|
||||
|
||||
// 2. Deactivate and clear foreign key references in asset_location to these old location codes
|
||||
if (oldLocCodes.length > 0) {
|
||||
await connection.query(
|
||||
'UPDATE asset_location SET is_active = 0, deactivated_at = NOW(), physical_location_code = NULL WHERE physical_location_code IN (?)',
|
||||
[oldLocCodes]
|
||||
);
|
||||
}
|
||||
|
||||
// 3. Delete old physical locations for this map
|
||||
await connection.query(
|
||||
'DELETE FROM physical_locations WHERE map_image = ?',
|
||||
[path]
|
||||
);
|
||||
|
||||
// 4. Insert new physical locations and setup asset_location mappings
|
||||
for (let i = 0; i < boxes.length; i++) {
|
||||
const box = boxes[i];
|
||||
const padIdx = String(i + 1).padStart(3, '0');
|
||||
const locCode = `LOC-${cleanKey}-${padIdx}`;
|
||||
const locDetail = getLocationDetail(path, i);
|
||||
|
||||
// Insert physical location
|
||||
await connection.query(`
|
||||
INSERT INTO physical_locations
|
||||
(location_code, location_name, location_detail, map_image, map_x, map_y, map_w, map_h)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`, [locCode, locName, locDetail, path, box.x, box.y, box.w, box.h]);
|
||||
|
||||
// If asset_id is mapped, update asset_location
|
||||
if (box.asset_id) {
|
||||
// Deactivate old active locations for this asset
|
||||
await connection.query(
|
||||
'UPDATE asset_location SET is_active = 0, deactivated_at = NOW() WHERE asset_id = ? AND is_active = 1',
|
||||
[box.asset_id]
|
||||
);
|
||||
|
||||
// Insert new active location mapping
|
||||
const pathPartsForMap = path.split('/');
|
||||
const stdDetailForMap = pathPartsForMap[pathPartsForMap.length - 2] || locDetail;
|
||||
await connection.query(`
|
||||
INSERT INTO asset_location
|
||||
(asset_id, location, location_detail, location_photo, loc_x, loc_y, physical_location_code, is_active)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, 1)
|
||||
`, [box.asset_id, locName, stdDetailForMap, path, box.x, box.y, locCode]);
|
||||
}
|
||||
}
|
||||
|
||||
await connection.commit();
|
||||
res.json({ success: true, message: 'Map and Database synced successfully' });
|
||||
} catch (err) {
|
||||
if (connection) await connection.rollback();
|
||||
handleError(res, err, 'SAVE MAPS SYNC');
|
||||
} finally {
|
||||
if (connection) connection.release();
|
||||
}
|
||||
});
|
||||
|
||||
// ==========================================
|
||||
// 8. QR Asset Audit & Scan APIs
|
||||
// 8. QR Asset Audit & Scan APIs (From origin/QR_setting)
|
||||
// ==========================================
|
||||
|
||||
// GET all physical locations
|
||||
@@ -1044,6 +1180,30 @@ app.post('/api/upload', (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// Health check endpoint for container orchestration
|
||||
app.get('/health', async (req, res) => {
|
||||
try {
|
||||
const connection = await pool.getConnection();
|
||||
await connection.query('SELECT 1');
|
||||
connection.release();
|
||||
res.status(200).json({ status: 'ok', db: 'connected' });
|
||||
} catch (err) {
|
||||
res.status(200).json({ status: 'degraded', db: 'unreachable', error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Readiness check endpoint (only returns 200 if fully ready)
|
||||
app.get('/ready', async (req, res) => {
|
||||
try {
|
||||
const connection = await pool.getConnection();
|
||||
await connection.query('SELECT 1');
|
||||
connection.release();
|
||||
res.status(200).json({ status: 'ready' });
|
||||
} catch (err) {
|
||||
res.status(503).json({ status: 'not_ready', error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
app.listen(process.env.PORT || 3000, '0.0.0.0', () => {
|
||||
console.log(`📡 ITAM BACKEND SERVER RUNNING ON PORT ${process.env.PORT || 3000} (V3 Normalized)`);
|
||||
});
|
||||
|
||||
@@ -202,7 +202,57 @@ class DomainAssetModal extends BaseModal {
|
||||
if (logs.length === 0) {
|
||||
container.innerHTML = '<div style="color:var(--mute); padding:1rem; text-align:center;">이력이 없습니다.</div>';
|
||||
} else {
|
||||
container.innerHTML = logs.map(l => `<div class="history-item"><div class="history-date">${l.log_date || ''}</div><div class="history-user">${l.log_user || '시스템'}</div><div class="history-details">${l.details}</div></div>`).join('');
|
||||
const createdDate = this.currentAsset?.created_at ? this.currentAsset.created_at.substring(0, 10) : '';
|
||||
|
||||
const grouped: Record<string, typeof logs> = {};
|
||||
logs.forEach(l => {
|
||||
const date = l.log_date || '날짜 미지정';
|
||||
if (!grouped[date]) grouped[date] = [];
|
||||
grouped[date].push(l);
|
||||
});
|
||||
|
||||
container.innerHTML = Object.entries(grouped).map(([date, dateLogs]) => {
|
||||
const entriesHtml = dateLogs.map((l, idx) => {
|
||||
const isLast = idx === dateLogs.length - 1;
|
||||
const borderStyle = isLast ? '' : 'border-bottom: 1px dashed var(--hairline); padding-bottom: 8px; margin-bottom: 8px;';
|
||||
|
||||
let displayDetails = l.details;
|
||||
if (l.details && l.details.trim().startsWith('{')) {
|
||||
try {
|
||||
const data = JSON.parse(l.details);
|
||||
if (data.type === 'checkout') {
|
||||
displayDetails = `[불출] ${data.user || ''} (${data.dept || ''}) ${data.memo ? `| 메모: ${data.memo}` : ''}`;
|
||||
} else if (data.type === 'return') {
|
||||
displayDetails = `[반납] ${data.user || ''} (${data.dept || ''}) ${data.memo ? `| 메모: ${data.memo}` : ''}`;
|
||||
} else if (data.type === 'move') {
|
||||
displayDetails = `[이동] ${data.user || ''} (${data.dept || ''}) ➔ ${data.targetUser || ''} (${data.targetDept || ''}) ${data.memo ? `| 메모: ${data.memo}` : ''}`;
|
||||
}
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
return `
|
||||
<div class="history-entry" style="${borderStyle}">
|
||||
<div style="font-weight: 600; color: var(--primary); opacity: 0.8; margin-bottom: 4px; display: flex; align-items: center; gap: 6px;">
|
||||
<span style="display: inline-block; width: 4px; height: 4px; background-color: var(--primary); border-radius: 50%;"></span>
|
||||
${l.log_user || '시스템'}
|
||||
</div>
|
||||
<div style="color: var(--primary); padding-left: 10px; line-height: 1.5;">${displayDetails}</div>
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
|
||||
const isInitialReg = date === createdDate;
|
||||
const regBadge = isInitialReg ? `<span class="badge-reg" style="font-size: 10px; padding: 1px 5px; margin-left: 6px; background-color: rgba(16, 185, 129, 0.1); color: #10b981; border: 1px solid rgba(16, 185, 129, 0.2); border-radius: 4px; font-weight: 600;">최초등록</span>` : '';
|
||||
|
||||
return `
|
||||
<div class="history-item">
|
||||
<div class="history-date" style="display: flex; align-items: center;">${date} ${regBadge}</div>
|
||||
<div class="history-details" style="display: flex; flex-direction: column; gap: 4px;">
|
||||
${entriesHtml}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,7 +77,7 @@ class HwAssetModal extends BaseModal {
|
||||
<label>${ASSET_SCHEMA.HW_STATUS.ui}</label>
|
||||
<select id="hw-hw_status" name="hw_status">${generateOptionsHTML(HW_STATUS_LIST)}</select>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<div class="form-group service-type-field">
|
||||
<label>${ASSET_SCHEMA.SERVICE_TYPE.ui}</label>
|
||||
<select id="hw-service_type" name="service_type">
|
||||
<option value="외부">외부</option>
|
||||
@@ -98,6 +98,9 @@ class HwAssetModal extends BaseModal {
|
||||
|
||||
<!-- [SECTION 2] 조직 및 사용자 정보 -->
|
||||
<div class="form-section-title">사용자 및 조직 정보</div>
|
||||
<div id="hw-pc-workflow-notice" class="form-group full-width hidden" style="background-color: rgba(59, 130, 246, 0.05); border: 1px solid rgba(59, 130, 246, 0.15); padding: 8px 12px; border-radius: 6px; font-size: 11px; color: var(--primary); line-height: 1.5; margin-bottom: 12px;">
|
||||
💡 PC 자산은 데이터 정합성을 위해 '사용자 및 조직 정보'만 수정이 제한되며, 사양 및 기타 정보는 수정창에서 수정할 수 있습니다.
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>${ASSET_SCHEMA.CURRENT_DEPT.ui}</label>
|
||||
<select id="hw-current_dept" name="current_dept">${generateOptionsHTML(ORG_LIST)}</select>
|
||||
@@ -110,9 +113,14 @@ class HwAssetModal extends BaseModal {
|
||||
<label>${ASSET_SCHEMA.MANAGER_SUB.ui}</label>
|
||||
<input type="text" id="hw-manager_secondary" name="manager_secondary" />
|
||||
</div>
|
||||
<div class="form-group personal-only">
|
||||
<div class="form-group personal-only relative">
|
||||
<label>${ASSET_SCHEMA.CURRENT_USER.ui}</label>
|
||||
<input type="text" id="hw-user_current" name="user_current" />
|
||||
<input type="text" id="hw-user_current" name="user_current" autocomplete="off" />
|
||||
<div id="hw-user-current-list" class="autocomplete-list hidden"></div>
|
||||
</div>
|
||||
<div class="form-group personal-only">
|
||||
<label>${ASSET_SCHEMA.EMP_NO.ui}</label>
|
||||
<input type="text" id="hw-emp_no" name="emp_no" readonly style="background-color: #f1f5f9; cursor: not-allowed;" />
|
||||
</div>
|
||||
<div class="form-group personal-only">
|
||||
<label>${ASSET_SCHEMA.USER_POSITION.ui}</label>
|
||||
@@ -133,6 +141,10 @@ class HwAssetModal extends BaseModal {
|
||||
<label>${ASSET_SCHEMA.SERIAL_NUM.ui}</label>
|
||||
<input type="text" id="hw-serial_num" name="serial_num" />
|
||||
</div>
|
||||
<div class="form-group mainboard-only">
|
||||
<label>${ASSET_SCHEMA.MAINBOARD.ui}</label>
|
||||
<input type="text" id="hw-mainboard" name="mainboard" />
|
||||
</div>
|
||||
<div class="form-group spec-only">
|
||||
<label>${ASSET_SCHEMA.OS.ui}</label>
|
||||
<input type="text" id="hw-os" name="os" />
|
||||
@@ -286,6 +298,7 @@ class HwAssetModal extends BaseModal {
|
||||
this.bindAutocomplete('hw-cpu', 'hw-cpu-list', 'CPU');
|
||||
this.bindAutocomplete('hw-ram', 'hw-ram-list', 'RAM');
|
||||
this.bindAutocomplete('hw-gpu', 'hw-gpu-list', 'GPU');
|
||||
this.bindUserAutocomplete();
|
||||
});
|
||||
|
||||
categorySelect.addEventListener('change', () => {
|
||||
@@ -303,6 +316,12 @@ class HwAssetModal extends BaseModal {
|
||||
typeSelect.addEventListener('change', () => {
|
||||
this.applyRoleVisibility();
|
||||
this.updateHeaderIdentity(this.currentAsset);
|
||||
|
||||
if (typeSelect.value === '공용PC') {
|
||||
setFieldValue('hw-user_current', '');
|
||||
setFieldValue('hw-emp_no', '');
|
||||
setFieldValue('hw-user_position', '공용PC');
|
||||
}
|
||||
});
|
||||
|
||||
bindLocationEvents('hw-bldg-select', 'hw-location_detail', '', '');
|
||||
@@ -314,8 +333,15 @@ class HwAssetModal extends BaseModal {
|
||||
document.getElementById('btn-gen-hw-code')?.addEventListener('click', async () => {
|
||||
const cat = categorySelect.value;
|
||||
if (!cat) { alert('구분을 먼저 선택해주세요.'); return; }
|
||||
const prefix = TYPE_PREFIX_MAP[cat] || 'ETC';
|
||||
|
||||
const purchaseDate = (document.getElementById('hw-purchase_date') as HTMLInputElement)?.value || '';
|
||||
if (!purchaseDate.trim()) {
|
||||
alert('구매일자를 먼저 입력해 주세요. 구매일자가 없으면 자산번호를 생성할 수 없습니다.');
|
||||
return;
|
||||
}
|
||||
|
||||
const type = (document.getElementById('hw-asset_type') as HTMLSelectElement)?.value || '';
|
||||
const prefix = TYPE_PREFIX_MAP[type] || TYPE_PREFIX_MAP[cat] || 'ETC';
|
||||
try {
|
||||
const res = await fetch(`/api/generate-asset-code?prefix=${prefix}&purchaseDate=${purchaseDate}`);
|
||||
const data = await res.json();
|
||||
@@ -400,7 +426,8 @@ class HwAssetModal extends BaseModal {
|
||||
if (!assetCode) {
|
||||
const cat = categorySelect.value;
|
||||
if (!cat) { alert('구분을 먼저 선택해주세요.'); return; }
|
||||
const prefix = TYPE_PREFIX_MAP[cat] || 'ETC';
|
||||
const type = (document.getElementById('hw-asset_type') as HTMLSelectElement)?.value || '';
|
||||
const prefix = TYPE_PREFIX_MAP[type] || TYPE_PREFIX_MAP[cat] || 'ETC';
|
||||
const purchaseDate = (document.getElementById('hw-purchase_date') as HTMLInputElement)?.value || '';
|
||||
try {
|
||||
const res = await fetch(`/api/generate-asset-code?prefix=${prefix}&purchaseDate=${purchaseDate}`);
|
||||
@@ -452,6 +479,27 @@ class HwAssetModal extends BaseModal {
|
||||
formData.forEach((value, key) => { if (key !== 'id') updated[key] = value; });
|
||||
updated.location = bldgSelect.value;
|
||||
|
||||
// 부품 마스터 기준 정합성 검증 (CPU, GPU, RAM)
|
||||
const checkFields = [
|
||||
{ name: 'cpu', label: 'CPU', category: 'CPU' },
|
||||
{ name: 'gpu', label: 'GPU', category: 'GPU' },
|
||||
{ name: 'ram', label: 'RAM', category: 'RAM' }
|
||||
];
|
||||
|
||||
for (const field of checkFields) {
|
||||
const value = String(updated[field.name] || '').trim();
|
||||
if (value) {
|
||||
const isExists = this.masterComponents.some(c =>
|
||||
c.category.toUpperCase() === field.category &&
|
||||
c.component_name.trim().toLowerCase() === value.toLowerCase()
|
||||
);
|
||||
if (!isExists) {
|
||||
alert(`입력하신 ${field.label} "${value}"은(는) 부품 마스터에 등록되지 않은 규격입니다. 자동완성 목록에서 선택하거나 부품마스터에 먼저 등록해 주세요.`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (await saveAsset(this.getCategoryKey(updated), updated)) {
|
||||
alert(UI_TEXT.MESSAGES.SAVE_SUCCESS);
|
||||
onSave(); this.close(); closeModals();
|
||||
@@ -581,6 +629,7 @@ class HwAssetModal extends BaseModal {
|
||||
setFieldValue('hw-manager_primary', asset.manager_primary || '');
|
||||
setFieldValue('hw-manager_secondary', asset.manager_secondary || '');
|
||||
setFieldValue('hw-user_current', asset.user_current || '');
|
||||
setFieldValue('hw-emp_no', asset.emp_no || '');
|
||||
setFieldValue('hw-user_position', asset.user_position || '');
|
||||
setFieldValue('hw-previous_user', asset.previous_user || '');
|
||||
setFieldValue('hw-model_name', asset.model_name || '');
|
||||
@@ -719,20 +768,97 @@ class HwAssetModal extends BaseModal {
|
||||
const hasSpec = specCategories.includes(category) || type.includes('서버PC');
|
||||
const noNetCategories = ['저장매체', '네트워크', '공간정보장비', 'PC부품', '사무가구'];
|
||||
const showNet = (isInfra || isPersonal) && !noNetCategories.includes(category);
|
||||
const hasSN = !['사무가구', 'PC부품'].includes(category);
|
||||
const hasSN = ['외부SW', '내부SW'].includes(category);
|
||||
const showMainboard = category === 'PC';
|
||||
const isParts = ['PC부품', '사무가구'].includes(category);
|
||||
const showRemote = category === '서버' || type.includes('서버');
|
||||
const showServiceType = category === '서버' || type === '서버PC';
|
||||
|
||||
document.querySelectorAll('.remote-section, .remote-field, .monitoring-field').forEach(el => (el as HTMLElement).style.display = showRemote ? '' : 'none');
|
||||
document.querySelectorAll('.service-type-field').forEach(el => (el as HTMLElement).style.display = showServiceType ? '' : 'none');
|
||||
document.querySelectorAll('.net-only').forEach(el => (el as HTMLElement).style.display = showNet ? '' : 'none');
|
||||
document.querySelectorAll('.spec-only').forEach(el => (el as HTMLElement).style.display = hasSpec ? '' : 'none');
|
||||
document.querySelectorAll('.location-section, .location-field').forEach(el => (el as HTMLElement).style.display = (isInfra || category === '공간정보장비') ? '' : 'none');
|
||||
document.querySelectorAll('.org-user-section, .org-user-field').forEach(el => (el as HTMLElement).style.display = (isPersonal || isParts || category === '업무지원장비') ? '' : 'none');
|
||||
document.querySelectorAll('.personal-only').forEach(el => (el as HTMLElement).style.display = isPersonal ? '' : 'none');
|
||||
document.querySelectorAll('.sn-only').forEach(el => (el as HTMLElement).style.display = hasSN ? '' : 'none');
|
||||
document.querySelectorAll('.mainboard-only').forEach(el => (el as HTMLElement).style.display = showMainboard ? '' : 'none');
|
||||
document.querySelectorAll('.monitor-only').forEach(el => (el as HTMLElement).style.display = type.includes('모니터') ? '' : 'none');
|
||||
document.querySelectorAll('.parts-only').forEach(el => (el as HTMLElement).style.display = isParts ? '' : 'none');
|
||||
document.querySelectorAll('.hardware-section').forEach(el => (el as HTMLElement).style.display = (hasSpec || isParts) ? '' : 'none');
|
||||
|
||||
// Lock only User and Organization Information for PC category during edit mode
|
||||
const isEditMode = this.currentMode === 'edit';
|
||||
const isPC = category === 'PC';
|
||||
|
||||
const noticeEl = document.getElementById('hw-pc-workflow-notice');
|
||||
if (noticeEl) {
|
||||
if (isPC && isEditMode) {
|
||||
noticeEl.classList.remove('hidden');
|
||||
} else {
|
||||
noticeEl.classList.add('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
const lockedUserFields = [
|
||||
'hw-current_dept',
|
||||
'hw-manager_primary',
|
||||
'hw-manager_secondary',
|
||||
'hw-user_current',
|
||||
'hw-emp_no',
|
||||
'hw-user_position',
|
||||
'hw-previous_user'
|
||||
];
|
||||
|
||||
const allFormControls = this.formEl ? this.formEl.querySelectorAll('input, select, textarea, button') : [];
|
||||
|
||||
allFormControls.forEach(control => {
|
||||
const el = control as HTMLElement;
|
||||
const id = el.id;
|
||||
|
||||
if (el.tagName === 'INPUT' && (el as HTMLInputElement).type === 'hidden') return;
|
||||
if (id === 'hw-asset_code' || id === 'btn-gen-hw-code') return;
|
||||
|
||||
if (isPC && isEditMode && lockedUserFields.includes(id)) {
|
||||
// Lock user information fields for PC in edit mode
|
||||
if (el.tagName === 'SELECT') {
|
||||
el.setAttribute('disabled', 'true');
|
||||
} else if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') {
|
||||
el.setAttribute('readonly', 'true');
|
||||
(el as HTMLInputElement).style.backgroundColor = '#f1f5f9';
|
||||
(el as HTMLInputElement).style.cursor = 'not-allowed';
|
||||
} else if (el.tagName === 'BUTTON') {
|
||||
el.setAttribute('disabled', 'true');
|
||||
}
|
||||
} else {
|
||||
// Normal behavior based on modal edit/view mode (includes add mode which has this.isEditMode = true)
|
||||
if (!this.isEditMode) {
|
||||
if (el.tagName === 'SELECT') {
|
||||
el.setAttribute('disabled', 'true');
|
||||
} else if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') {
|
||||
el.setAttribute('readonly', 'true');
|
||||
(el as HTMLInputElement).style.backgroundColor = '';
|
||||
(el as HTMLInputElement).style.cursor = '';
|
||||
} else if (el.tagName === 'BUTTON') {
|
||||
if (id !== 'btn-print-hw-qr' && id !== 'btn-close-hw-modal') {
|
||||
el.setAttribute('disabled', 'true');
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (el.tagName === 'SELECT') {
|
||||
el.removeAttribute('disabled');
|
||||
} else if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') {
|
||||
if (id !== 'hw-emp_no') {
|
||||
el.removeAttribute('readonly');
|
||||
(el as HTMLInputElement).style.backgroundColor = '';
|
||||
(el as HTMLInputElement).style.cursor = '';
|
||||
}
|
||||
} else if (el.tagName === 'BUTTON') {
|
||||
el.removeAttribute('disabled');
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private updateMapButtonVisibility() {
|
||||
@@ -933,12 +1059,148 @@ class HwAssetModal extends BaseModal {
|
||||
overlay.querySelector('#btn-preview-close')?.addEventListener('click', () => overlay.remove());
|
||||
}
|
||||
|
||||
private bindUserAutocomplete() {
|
||||
const input = document.getElementById('hw-user_current') as HTMLInputElement;
|
||||
const list = document.getElementById('hw-user-current-list') as HTMLDivElement;
|
||||
const deptSelect = document.getElementById('hw-current_dept') as HTMLSelectElement;
|
||||
const positionInput = document.getElementById('hw-user_position') as HTMLInputElement;
|
||||
const empNoInput = document.getElementById('hw-emp_no') as HTMLInputElement;
|
||||
|
||||
if (!input || !list) return;
|
||||
|
||||
const showList = (filterText: string = '') => {
|
||||
if (!this.isEditMode) return;
|
||||
const category = (document.getElementById('hw-category') as HTMLSelectElement)?.value || '';
|
||||
if (category === 'PC') return;
|
||||
const users = state.masterData.users || [];
|
||||
const query = filterText.trim().toLowerCase();
|
||||
|
||||
const filtered = query
|
||||
? users.filter((u: any) =>
|
||||
u.user_name.toLowerCase().includes(query) ||
|
||||
(u.dept_name && u.dept_name.toLowerCase().includes(query)) ||
|
||||
(u.emp_no && u.emp_no.toLowerCase().includes(query))
|
||||
)
|
||||
: users;
|
||||
|
||||
if (filtered.length === 0) {
|
||||
list.innerHTML = '<div class="autocomplete-item" style="color: #94a3b8; cursor: default;">일치하는 사원 없음</div>';
|
||||
} else {
|
||||
const seen = new Set();
|
||||
const uniqueFiltered = filtered.filter((u: any) => {
|
||||
const key = `${u.user_name}-${u.dept_name}-${u.emp_no}`;
|
||||
if (seen.has(key)) return false;
|
||||
seen.add(key);
|
||||
return true;
|
||||
}).slice(0, 15);
|
||||
|
||||
list.innerHTML = uniqueFiltered.map((u: any) => `
|
||||
<div class="autocomplete-item user-suggestion-item"
|
||||
data-name="${u.user_name}"
|
||||
data-dept="${u.dept_name || ''}"
|
||||
data-pos="${u.position || ''}"
|
||||
data-emp="${u.emp_no || ''}">
|
||||
<div style="font-weight: 600; color: #1e293b;">${u.user_name}</div>
|
||||
<div style="font-size: 0.75rem; color: #64748b; margin-top: 2px;">
|
||||
${u.dept_name || '부서 없음'} / 사번: ${u.emp_no || '-'} / ${u.position || '직급 없음'}
|
||||
</div>
|
||||
</div>
|
||||
`).join('');
|
||||
}
|
||||
list.classList.remove('hidden');
|
||||
};
|
||||
|
||||
input.addEventListener('focus', () => showList(input.value));
|
||||
input.addEventListener('input', () => showList(input.value));
|
||||
|
||||
list.addEventListener('mousedown', (e) => {
|
||||
const item = (e.target as HTMLElement).closest('.user-suggestion-item');
|
||||
if (item) {
|
||||
const name = item.getAttribute('data-name') || '';
|
||||
const dept = item.getAttribute('data-dept') || '';
|
||||
const pos = item.getAttribute('data-pos') || '';
|
||||
const emp = item.getAttribute('data-emp') || '';
|
||||
|
||||
input.value = name;
|
||||
if (positionInput) positionInput.value = pos;
|
||||
if (empNoInput) empNoInput.value = emp;
|
||||
|
||||
if (deptSelect && dept) {
|
||||
for (let i = 0; i < deptSelect.options.length; i++) {
|
||||
if (deptSelect.options[i].value === dept) {
|
||||
deptSelect.selectedIndex = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
list.classList.add('hidden');
|
||||
}
|
||||
});
|
||||
|
||||
document.addEventListener('mousedown', (e) => {
|
||||
if (e.target !== input && !list.contains(e.target as Node)) {
|
||||
list.classList.add('hidden');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private renderHistory(assetId: string) {
|
||||
const container = document.getElementById('hw-history-list');
|
||||
if (!container) return;
|
||||
const logs = (state.masterData.logs || []).filter(l => l.asset_id === assetId);
|
||||
if (logs.length === 0) { container.innerHTML = '<div class="empty-history">기록된 변동 이력이 없습니다.</div>'; return; }
|
||||
container.innerHTML = logs.map(l => `<div class="history-item"><div class="history-date">${l.log_date || ''}</div><div class="history-user">${l.log_user || '시스템'}</div><div class="history-details">${l.details}</div></div>`).join('');
|
||||
|
||||
const createdDate = this.currentAsset?.created_at ? this.currentAsset.created_at.substring(0, 10) : '';
|
||||
|
||||
const grouped: Record<string, typeof logs> = {};
|
||||
logs.forEach(l => {
|
||||
const date = l.log_date || '날짜 미지정';
|
||||
if (!grouped[date]) grouped[date] = [];
|
||||
grouped[date].push(l);
|
||||
});
|
||||
|
||||
container.innerHTML = Object.entries(grouped).map(([date, dateLogs]) => {
|
||||
const entriesHtml = dateLogs.map((l, idx) => {
|
||||
const isLast = idx === dateLogs.length - 1;
|
||||
const borderStyle = isLast ? '' : 'border-bottom: 1px dashed var(--hairline); padding-bottom: 8px; margin-bottom: 8px;';
|
||||
|
||||
let displayDetails = l.details;
|
||||
if (l.details && l.details.trim().startsWith('{')) {
|
||||
try {
|
||||
const data = JSON.parse(l.details);
|
||||
if (data.type === 'checkout') {
|
||||
displayDetails = `[불출] ${data.user || ''} (${data.dept || ''}) ${data.memo ? `| 메모: ${data.memo}` : ''}`;
|
||||
} else if (data.type === 'return') {
|
||||
displayDetails = `[반납] ${data.user || ''} (${data.dept || ''}) ${data.memo ? `| 메모: ${data.memo}` : ''}`;
|
||||
} else if (data.type === 'move') {
|
||||
displayDetails = `[이동] ${data.user || ''} (${data.dept || ''}) ➔ ${data.targetUser || ''} (${data.targetDept || ''}) ${data.memo ? `| 메모: ${data.memo}` : ''}`;
|
||||
}
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
return `
|
||||
<div class="history-entry" style="${borderStyle}">
|
||||
<div style="font-weight: 600; color: var(--primary); opacity: 0.8; margin-bottom: 4px; display: flex; align-items: center; gap: 6px;">
|
||||
<span style="display: inline-block; width: 4px; height: 4px; background-color: var(--primary); border-radius: 50%;"></span>
|
||||
${l.log_user || '시스템'}
|
||||
</div>
|
||||
<div style="color: var(--primary); padding-left: 10px; line-height: 1.5;">${displayDetails}</div>
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
|
||||
const isInitialReg = date === createdDate;
|
||||
const regBadge = isInitialReg ? `<span class="badge-reg" style="font-size: 10px; padding: 1px 5px; margin-left: 6px; background-color: rgba(16, 185, 129, 0.1); color: #10b981; border: 1px solid rgba(16, 185, 129, 0.2); border-radius: 4px; font-weight: 600;">최초등록</span>` : '';
|
||||
|
||||
return `
|
||||
<div class="history-item">
|
||||
<div class="history-date" style="display: flex; align-items: center;">${date} ${regBadge}</div>
|
||||
<div class="history-details" style="display: flex; flex-direction: column; gap: 4px;">
|
||||
${entriesHtml}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
private getCategoryKey(asset: any): string {
|
||||
|
||||
@@ -389,7 +389,58 @@ class SwAssetModal extends BaseModal {
|
||||
if (!container) return;
|
||||
const logs = (state.masterData.logs || []).filter(l => l.asset_id === swId);
|
||||
if (logs.length === 0) { container.innerHTML = '<div class="empty-history">수정 이력이 없습니다.</div>'; return; }
|
||||
container.innerHTML = logs.map(l => `<div class="history-item"><div class="history-date">${l.log_date || ''}</div><div class="history-user">${l.log_user || '시스템'}</div><div class="history-details">${l.details}</div></div>`).join('');
|
||||
|
||||
const createdDate = this.currentAsset?.created_at ? this.currentAsset.created_at.substring(0, 10) : '';
|
||||
|
||||
const grouped: Record<string, typeof logs> = {};
|
||||
logs.forEach(l => {
|
||||
const date = l.log_date || '날짜 미지정';
|
||||
if (!grouped[date]) grouped[date] = [];
|
||||
grouped[date].push(l);
|
||||
});
|
||||
|
||||
container.innerHTML = Object.entries(grouped).map(([date, dateLogs]) => {
|
||||
const entriesHtml = dateLogs.map((l, idx) => {
|
||||
const isLast = idx === dateLogs.length - 1;
|
||||
const borderStyle = isLast ? '' : 'border-bottom: 1px dashed var(--hairline); padding-bottom: 8px; margin-bottom: 8px;';
|
||||
|
||||
let displayDetails = l.details;
|
||||
if (l.details && l.details.trim().startsWith('{')) {
|
||||
try {
|
||||
const data = JSON.parse(l.details);
|
||||
if (data.type === 'checkout') {
|
||||
displayDetails = `[불출] ${data.user || ''} (${data.dept || ''}) ${data.memo ? `| 메모: ${data.memo}` : ''}`;
|
||||
} else if (data.type === 'return') {
|
||||
displayDetails = `[반납] ${data.user || ''} (${data.dept || ''}) ${data.memo ? `| 메모: ${data.memo}` : ''}`;
|
||||
} else if (data.type === 'move') {
|
||||
displayDetails = `[이동] ${data.user || ''} (${data.dept || ''}) ➔ ${data.targetUser || ''} (${data.targetDept || ''}) ${data.memo ? `| 메모: ${data.memo}` : ''}`;
|
||||
}
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
return `
|
||||
<div class="history-entry" style="${borderStyle}">
|
||||
<div style="font-weight: 600; color: var(--primary); opacity: 0.8; margin-bottom: 4px; display: flex; align-items: center; gap: 6px;">
|
||||
<span style="display: inline-block; width: 4px; height: 4px; background-color: var(--primary); border-radius: 50%;"></span>
|
||||
${l.log_user || '시스템'}
|
||||
</div>
|
||||
<div style="color: var(--primary); padding-left: 10px; line-height: 1.5;">${displayDetails}</div>
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
|
||||
const isInitialReg = date === createdDate;
|
||||
const regBadge = isInitialReg ? `<span class="badge-reg" style="font-size: 10px; padding: 1px 5px; margin-left: 6px; background-color: rgba(16, 185, 129, 0.1); color: #10b981; border: 1px solid rgba(16, 185, 129, 0.2); border-radius: 4px; font-weight: 600;">최초등록</span>` : '';
|
||||
|
||||
return `
|
||||
<div class="history-item">
|
||||
<div class="history-date" style="display: flex; align-items: center;">${date} ${regBadge}</div>
|
||||
<div class="history-details" style="display: flex; flex-direction: column; gap: 4px;">
|
||||
${entriesHtml}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -43,6 +43,7 @@ export const TYPE_PREFIX_MAP: Record<string, string> = {
|
||||
'저장매체': 'STM', 'HDD': 'HDD', 'SSD': 'SSD',
|
||||
'노트북': 'NBK', '태블릿': 'TAB',
|
||||
'드론': 'DRO', '측량장비': 'SUR', '보조기기': 'SUR', '허브': 'NET',
|
||||
'모니터': 'MON',
|
||||
'구독SW': 'SW', '영구SW': 'SW', '내부' : 'SW_INT', '외부':'SW_EXT'
|
||||
};
|
||||
|
||||
|
||||
@@ -65,7 +65,7 @@ export function renderNavigation(onTabChange: (tab: string) => void) {
|
||||
});
|
||||
|
||||
if (state.currentUserRole === 'admin' && catKey === 'hw') {
|
||||
visibleTabs = ['대시보드', '실사 승인'];
|
||||
visibleTabs = ['대시보드', '관리도구', '실사 승인', '위치지정'];
|
||||
}
|
||||
|
||||
if (visibleTabs.length === 0) return;
|
||||
@@ -75,29 +75,36 @@ export function renderNavigation(onTabChange: (tab: string) => void) {
|
||||
const item = document.createElement('div');
|
||||
const isActive = state.activeSubTab === tab;
|
||||
item.className = `gnb-trigger ${isActive ? 'active' : ''}`;
|
||||
|
||||
const isSubMenu = tab === '실사 승인' || tab === '위치지정';
|
||||
if (isSubMenu) {
|
||||
item.innerHTML = `<span style="opacity: 0.5; margin-right: 3px; font-family: sans-serif;">↳</span>${tab}`;
|
||||
item.style.fontSize = '11px';
|
||||
item.style.fontWeight = '500';
|
||||
item.style.marginLeft = '6px';
|
||||
if (!isActive) {
|
||||
item.style.color = 'var(--mute)';
|
||||
}
|
||||
} else {
|
||||
item.textContent = tab;
|
||||
item.style.fontSize = 'var(--fs-sm)'; // Ensure small but standard font
|
||||
item.style.fontSize = 'var(--fs-sm)';
|
||||
}
|
||||
|
||||
item.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
state.activeCategory = catKey as any;
|
||||
if (tab === '관리도구') {
|
||||
state.activeSubTab = '실사 승인';
|
||||
} else {
|
||||
state.activeSubTab = tab;
|
||||
}
|
||||
render();
|
||||
onTabChange(tab);
|
||||
onTabChange(state.activeSubTab);
|
||||
});
|
||||
navList.appendChild(item);
|
||||
});
|
||||
});
|
||||
|
||||
// 3. 관리자 전용 '관리도구'
|
||||
if (state.currentUserRole === 'admin') {
|
||||
const adminTrigger = document.createElement('div');
|
||||
adminTrigger.className = 'gnb-trigger admin-trigger';
|
||||
adminTrigger.innerHTML = '관리도구';
|
||||
adminTrigger.addEventListener('click', () => window.open('/map_editor.html', '_blank'));
|
||||
navList.appendChild(adminTrigger);
|
||||
}
|
||||
|
||||
// 4. 이벤트 바인딩
|
||||
document.getElementById('btn-home-logo')?.addEventListener('click', () => location.reload());
|
||||
|
||||
|
||||
@@ -52,7 +52,7 @@ export function renderFilterBar(container: HTMLElement, options: FilterOptions)
|
||||
};
|
||||
|
||||
container.innerHTML = `
|
||||
<div class="search-item flex-1">
|
||||
<div class="search-item keyword-search">
|
||||
<label>${keywordLabel}</label>
|
||||
<input type="text" id="filter-keyword" placeholder="검색어를 입력하세요..." autocomplete="off" value="${initialFilters.keyword || ''}">
|
||||
</div>
|
||||
@@ -108,6 +108,12 @@ export function renderFilterBar(container: HTMLElement, options: FilterOptions)
|
||||
<button id="btn-reset-filters" class="btn btn-outline btn-reset">
|
||||
<i data-lucide="refresh-ccw" class="icon-sm"></i> ${UI_TEXT.ACTION.RESET_FILTER}
|
||||
</button>
|
||||
<div class="search-item result-count-item">
|
||||
<label>검색 결과</label>
|
||||
<div class="result-count-box">
|
||||
<span id="filter-total-count" class="filter-total-count result-count-text">0개</span>
|
||||
</div>
|
||||
</div>
|
||||
${getActionButtonsHTML()}
|
||||
`;
|
||||
|
||||
|
||||
@@ -45,6 +45,63 @@ export async function loadMasterDataFromDB() {
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
// DB의 쪼개진 asset_remote 데이터로부터 가상 대표 속성(IP, MAC, 원격도구)을 주입해주는 전처리 함수
|
||||
const preprocessAssets = (assets: any[]) => {
|
||||
if (!Array.isArray(assets)) return;
|
||||
assets.forEach((asset: any) => {
|
||||
let ip = '';
|
||||
let mac = '';
|
||||
let remoteTool = '';
|
||||
let remoteId = '';
|
||||
let remotePw = '';
|
||||
|
||||
let rems: any[] = [];
|
||||
try {
|
||||
rems = asset.remotes ? (typeof asset.remotes === 'string' ? JSON.parse(asset.remotes) : asset.remotes) : [];
|
||||
} catch(e) {}
|
||||
|
||||
if (Array.isArray(rems)) {
|
||||
rems.forEach((r: any) => {
|
||||
if (r.type === 'IP') {
|
||||
if (!ip) ip = r.val1 || '';
|
||||
if (r.val2) {
|
||||
if (String(r.val2).trim().startsWith('{')) {
|
||||
try {
|
||||
const parsed = JSON.parse(r.val2);
|
||||
remoteTool = r.name || '원격접속';
|
||||
remoteId = parsed.id || '';
|
||||
remotePw = parsed.pw || '';
|
||||
} catch(e) {}
|
||||
} else {
|
||||
if (!mac) mac = r.val2 || '';
|
||||
}
|
||||
}
|
||||
} else if (r.type === 'MAC') {
|
||||
if (!mac) mac = r.val1 || '';
|
||||
} else if (r.type === 'REMOTE') {
|
||||
if (!remoteTool) remoteTool = r.name || '';
|
||||
if (!remoteId) remoteId = r.val1 || '';
|
||||
if (!remotePw) remotePw = r.val2 || '';
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 최상위 가상 속성 바인딩 (목록 및 위치보기 뷰어 매핑용)
|
||||
asset.ip_address = ip;
|
||||
asset.mac_address = mac;
|
||||
asset.remote_tool = remoteTool;
|
||||
asset.remote_id = remoteId;
|
||||
asset.remote_pw = remotePw;
|
||||
});
|
||||
};
|
||||
|
||||
if (data) {
|
||||
const keys = ['pc', 'server', 'storage', 'network', 'survey', 'equipment', 'officeSupplies'];
|
||||
keys.forEach(k => {
|
||||
if (data[k]) preprocessAssets(data[k]);
|
||||
});
|
||||
}
|
||||
|
||||
// 전역 상태 업데이트
|
||||
state.masterData = {
|
||||
...state.masterData,
|
||||
|
||||
54
src/main.ts
54
src/main.ts
@@ -6,6 +6,7 @@ import { renderDashboard } from './views/DashboardView';
|
||||
import { renderSWTable } from './views/SW_Table';
|
||||
import { renderLocationView } from './views/LocationView';
|
||||
import { renderAuditApprovalView } from './views/AuditApprovalView';
|
||||
import { MapEditor } from './views/MapEditor';
|
||||
import { initBaseModal } from './components/Modal/BaseModal';
|
||||
import { initHwModal, openHwModal } from './components/Modal/HWModal';
|
||||
import { initSwModal, openSwModal } from './components/Modal/SWModal';
|
||||
@@ -21,11 +22,19 @@ import { pcFlowModal } from './components/Modal/PCFlowModal';
|
||||
import { createIcons, Plus, X, LayoutDashboard, Monitor, Server, Database, Laptop, CalendarClock, Key, Cpu, Layers, Users, Paperclip, Edit2, History, RefreshCcw, BookOpen, Settings } from 'lucide';
|
||||
|
||||
|
||||
let activeMapEditorInstance: MapEditor | null = null;
|
||||
|
||||
// 화면 갱신 통합 핸들러
|
||||
function refreshView(tab?: string) {
|
||||
async function refreshView(tab?: string) {
|
||||
const mainContent = document.getElementById('main-content')!;
|
||||
if (!mainContent) return;
|
||||
|
||||
// Clean up any active MapEditor instance when navigating away
|
||||
if (activeMapEditorInstance) {
|
||||
activeMapEditorInstance.destroy();
|
||||
activeMapEditorInstance = null;
|
||||
}
|
||||
|
||||
const activeTab = tab || state.activeSubTab;
|
||||
|
||||
if (activeTab === '대시보드') {
|
||||
@@ -34,7 +43,48 @@ function refreshView(tab?: string) {
|
||||
}
|
||||
|
||||
if (activeTab === '실사 승인') {
|
||||
renderAuditApprovalView(mainContent);
|
||||
await renderAuditApprovalView(mainContent);
|
||||
return;
|
||||
}
|
||||
|
||||
if (activeTab === '위치지정') {
|
||||
// Render Map Editor directly into main content to maximize working area
|
||||
mainContent.innerHTML = `
|
||||
<div class="map-editor-page-wrapper" style="display: flex; flex: 1; height: calc(100vh - var(--header-height) - 48px); overflow: hidden; width: 100%;">
|
||||
<!-- Left: File Selector -->
|
||||
<div class="file-sidebar" id="file-sidebar"></div>
|
||||
|
||||
<!-- Center: Main Editor -->
|
||||
<div class="editor-container" id="container">
|
||||
<div class="img-wrapper" id="wrapper">
|
||||
<img src="" id="target-img" alt="Map Image">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Right: Control Panel -->
|
||||
<div class="sidebar">
|
||||
<h2>Map Editor <small class="editor-version">v3.0</small></h2>
|
||||
<div class="current-path" id="current-path">파일을 선택하세요</div>
|
||||
<p>
|
||||
드래그하여 구역을 정의하세요. 저장 버튼을 누르면 즉시 시스템에 반영됩니다.
|
||||
</p>
|
||||
|
||||
<div class="box-list" id="box-list"></div>
|
||||
|
||||
<div class="actions" style="display: flex; flex-direction: column; gap: 0.5rem;">
|
||||
<button id="btn-clear-all" class="btn btn-outline">전체 삭제</button>
|
||||
<button id="btn-print-map-qrs" class="btn btn-outline btn-primary">이 도면 QR 일괄인쇄</button>
|
||||
<button id="btn-save-server" class="btn btn-primary">서버에 즉시 저장</button>
|
||||
<div id="save-status"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
// Initialize MapEditor instance
|
||||
const editor = new MapEditor();
|
||||
await editor.init();
|
||||
activeMapEditorInstance = editor;
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -640,3 +640,28 @@ input:checked + .role-slider:before {
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
/* --- Filter Bar Unified Layout Refactoring --- */
|
||||
.search-item.keyword-search {
|
||||
flex: 0 0 320px;
|
||||
}
|
||||
|
||||
.search-item.result-count-item {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.result-count-box {
|
||||
height: clamp(34px, 4.5vmin, 44px);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
box-sizing: border-box;
|
||||
min-width: 60px;
|
||||
}
|
||||
|
||||
.result-count-text {
|
||||
white-space: nowrap;
|
||||
color: var(--color-blue);
|
||||
font-size: var(--fs-sm);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
|
||||
@@ -196,11 +196,14 @@
|
||||
height: auto;
|
||||
object-fit: contain;
|
||||
display: block;
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.map-overlay {
|
||||
position: absolute;
|
||||
pointer-events: none;
|
||||
pointer-events: auto;
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
.no-map-message {
|
||||
@@ -216,6 +219,7 @@
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
transition: all 0.2s ease;
|
||||
z-index: 3;
|
||||
}
|
||||
|
||||
/* --- Asset Detail Sidebar --- */
|
||||
|
||||
@@ -11,9 +11,9 @@ export function renderEquipmentList(container: HTMLElement) {
|
||||
searchKeys: ['MODEL_NAME', 'CURRENT_USER', 'ASSET_MFR', 'ASSET_TYPE'],
|
||||
filterOptions: {
|
||||
keywordLabel: `통합 검색 (${ASSET_SCHEMA.MODEL_NAME.ui}/${ASSET_SCHEMA.ASSET_MFR.ui})`,
|
||||
showLoc: true,
|
||||
showDept: true,
|
||||
showType: true
|
||||
showType: true,
|
||||
showStatus: true
|
||||
},
|
||||
onRowClick: (asset) => openHwModal(asset, 'view'),
|
||||
columns: [
|
||||
|
||||
@@ -7,13 +7,13 @@ import { createListView } from './ListFactory';
|
||||
export function renderFacilityList(container: HTMLElement) {
|
||||
createListView(container, {
|
||||
title: '사무가구',
|
||||
dataSource: () => sortAssets(state.masterData.equipment?.filter((a: any) => a.category === '시설자산') || []),
|
||||
dataSource: () => sortAssets(state.masterData.officeSupplies || []),
|
||||
searchKeys: ['MODEL_NAME', 'ASSET_MFR', 'ASSET_TYPE'],
|
||||
filterOptions: {
|
||||
keywordLabel: `통합 검색 (${ASSET_SCHEMA.MODEL_NAME.ui})`,
|
||||
showLoc: true,
|
||||
showDept: true,
|
||||
showType: true
|
||||
showType: true,
|
||||
showStatus: true
|
||||
},
|
||||
onRowClick: (asset) => openHwModal(asset, 'view'),
|
||||
columns: [
|
||||
|
||||
@@ -6,13 +6,14 @@ import { createListView } from './ListFactory';
|
||||
export function renderGiftList(container: HTMLElement) {
|
||||
createListView(container, {
|
||||
title: '선물',
|
||||
dataSource: () => sortAssets(state.masterData.equipment?.filter((a: any) => a.category === '선물') || []),
|
||||
dataSource: () => sortAssets(state.masterData.vip || []),
|
||||
searchKeys: ['PRODUCT_NAME', 'MODEL_NAME', 'ASSET_TYPE'],
|
||||
filterOptions: {
|
||||
keywordLabel: `통합 검색 (${ASSET_SCHEMA.PRODUCT_NAME.ui})`,
|
||||
showCorp: true,
|
||||
showDept: true,
|
||||
showType: true
|
||||
showType: true,
|
||||
showStatus: true
|
||||
},
|
||||
onRowClick: () => alert('상세 정보 준비 중입니다.'),
|
||||
columns: [
|
||||
|
||||
@@ -667,10 +667,15 @@ export function createListView(container: HTMLElement, config: ListViewConfig) {
|
||||
let filtered = applyCommonFilters(fullList, currentFilters, config.searchKeys as any[]);
|
||||
if (sortState.key) filtered = dynamicSort(filtered, sortState.key, sortState.direction);
|
||||
|
||||
const totalCountEl = filterBar.querySelector('#filter-total-count');
|
||||
if (totalCountEl) {
|
||||
totalCountEl.textContent = `${filtered.length}개`;
|
||||
}
|
||||
|
||||
thead.innerHTML = `<tr>${config.columns.map(col => {
|
||||
const isDateCol = col.header.includes('일') || col.header.includes('날짜') || col.header.includes('연월');
|
||||
const alignmentClass = col.align ? `text-${col.align}` : (isDateCol ? 'text-center' : '');
|
||||
return `<th class="${alignmentClass}" ${col.sortKey ? `data-sort="${col.sortKey}"` : ''} style="${col.width ? `width:${col.width};` : ''}">${col.header}</th>`;
|
||||
return `<th class="${alignmentClass}" ${col.sortKey ? `data-sort="${col.sortKey}"` : ''} style="${col.width ? `width:${col.width};` : ''}">${col.header}<div class="resizer"></div></th>`;
|
||||
}).join('')}</tr>`;
|
||||
|
||||
tbody.innerHTML = filtered.length === 0 ? `<tr><td colspan="${config.columns.length}" class="text-center empty-cell">${UI_TEXT.MESSAGES.NO_DATA}</td></tr>`
|
||||
@@ -693,13 +698,82 @@ export function createListView(container: HTMLElement, config: ListViewConfig) {
|
||||
`;
|
||||
}
|
||||
|
||||
return `<td class="${alignmentClass} ${customClass}" style="${col.width ? `width:${col.width};` : ''}" ${titleAttr}>${displayContent}</td>`;
|
||||
return `<td class="${alignmentClass} ${customClass}" ${titleAttr}>${displayContent}</td>`;
|
||||
}).join('')}</tr>`).join('');
|
||||
|
||||
tbody.querySelectorAll('.asset-row').forEach((tr, idx) => { tr.addEventListener('click', () => config.onRowClick && config.onRowClick(filtered[idx])); });
|
||||
setupTableSorting(table, sortState, (key, dir) => { sortState = { key, direction: dir }; updateTable(); });
|
||||
makeColumnsResizable(table);
|
||||
};
|
||||
|
||||
function makeColumnsResizable(tableElement: HTMLTableElement) {
|
||||
const headers = tableElement.querySelectorAll('th');
|
||||
headers.forEach((th, index) => {
|
||||
const resizer = th.querySelector('.resizer') as HTMLElement;
|
||||
if (!resizer) return;
|
||||
|
||||
let startX = 0;
|
||||
let startWidth = 0;
|
||||
let startTableWidth = 0;
|
||||
|
||||
const onMouseMove = (e: MouseEvent) => {
|
||||
const dx = e.clientX - startX;
|
||||
const newWidth = Math.max(50, startWidth + dx);
|
||||
|
||||
// Update the width of the dragged column
|
||||
th.style.width = `${newWidth}px`;
|
||||
|
||||
// Dynamically adjust the total table width by the delta change,
|
||||
// preventing neighboring columns from shrinking or expanding.
|
||||
const deltaW = newWidth - startWidth;
|
||||
tableElement.style.width = `${startTableWidth + deltaW}px`;
|
||||
};
|
||||
|
||||
const onMouseUp = () => {
|
||||
resizer.classList.remove('resizing');
|
||||
document.removeEventListener('mousemove', onMouseMove);
|
||||
document.removeEventListener('mouseup', onMouseUp);
|
||||
|
||||
// Save the widths of all columns back to the config so they persist on re-render
|
||||
headers.forEach((hdr, idx) => {
|
||||
if (config.columns[idx]) {
|
||||
config.columns[idx].width = hdr.style.width;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
resizer.addEventListener('mousedown', (e: MouseEvent) => {
|
||||
// Prevents header click sorting trigger from firing on mousedown
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
|
||||
// Freeze all columns at their current precise pixel width before dragging
|
||||
headers.forEach(header => {
|
||||
header.style.width = `${header.getBoundingClientRect().width}px`;
|
||||
});
|
||||
|
||||
// Freeze the table at its current precise pixel width immediately
|
||||
tableElement.style.width = `${tableElement.getBoundingClientRect().width}px`;
|
||||
|
||||
startX = e.clientX;
|
||||
startWidth = th.getBoundingClientRect().width;
|
||||
|
||||
// Capture the initial physical width of the entire table
|
||||
startTableWidth = tableElement.getBoundingClientRect().width;
|
||||
|
||||
resizer.classList.add('resizing');
|
||||
document.addEventListener('mousemove', onMouseMove);
|
||||
document.addEventListener('mouseup', onMouseUp);
|
||||
});
|
||||
|
||||
// Prevents header click sorting trigger from firing on mouseup/click
|
||||
resizer.addEventListener('click', (e: MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const switchView = () => {
|
||||
contentWrapper.innerHTML = '';
|
||||
const isAssetMode = !isServer || state.viewMode === 'list';
|
||||
|
||||
@@ -13,7 +13,8 @@ export function renderMobileList(container: HTMLElement) {
|
||||
keywordLabel: `통합 검색 (${ASSET_SCHEMA.MODEL_NAME.ui})`,
|
||||
showCorp: true,
|
||||
showDept: true,
|
||||
showType: true
|
||||
showType: true,
|
||||
showStatus: true
|
||||
},
|
||||
onRowClick: (asset) => openHwModal(asset, 'view'),
|
||||
columns: [
|
||||
|
||||
@@ -11,9 +11,9 @@ export function renderNetworkList(container: HTMLElement) {
|
||||
searchKeys: ['MODEL_NAME', 'CURRENT_USER', 'ASSET_MFR', 'ASSET_TYPE'],
|
||||
filterOptions: {
|
||||
keywordLabel: `통합 검색 (${ASSET_SCHEMA.MODEL_NAME.ui}/${ASSET_SCHEMA.ASSET_MFR.ui})`,
|
||||
showLoc: true,
|
||||
showDept: true,
|
||||
showType: true
|
||||
showType: true,
|
||||
showStatus: true
|
||||
},
|
||||
onRowClick: (asset) => openHwModal(asset, 'view'),
|
||||
columns: [
|
||||
|
||||
@@ -28,7 +28,6 @@ export function renderPcList(container: HTMLElement) {
|
||||
searchKeys: ['CURRENT_DEPT', 'CURRENT_USER', 'MODEL_NAME', 'MAC_ADDR', 'MANAGER_MAIN', 'ASSET_TYPE'],
|
||||
filterOptions: {
|
||||
keywordLabel: `통합 검색 (${ASSET_SCHEMA.MODEL_NAME.ui}/${ASSET_SCHEMA.MANAGER_MAIN.ui}/${ASSET_SCHEMA.CURRENT_USER.ui})`,
|
||||
showLoc: true,
|
||||
showDept: true,
|
||||
showType: true,
|
||||
showStatus: true
|
||||
@@ -50,7 +49,15 @@ export function renderPcList(container: HTMLElement) {
|
||||
return `<span class="badge ${badgeClass}">${status}</span>`;
|
||||
}
|
||||
},
|
||||
{ header: ASSET_SCHEMA.CURRENT_USER.ui, sortKey: ASSET_SCHEMA.CURRENT_USER.key, align: 'center', render: a => a[ASSET_SCHEMA.CURRENT_USER.key] || '-' },
|
||||
{
|
||||
header: '사용자',
|
||||
sortKey: ASSET_SCHEMA.CURRENT_USER.key,
|
||||
align: 'center',
|
||||
render: a => {
|
||||
const status = a[ASSET_SCHEMA.HW_STATUS.key] || '재고';
|
||||
return (status === '재고' ? a[ASSET_SCHEMA.PREV_USER.key] : a[ASSET_SCHEMA.CURRENT_USER.key]) || '-';
|
||||
}
|
||||
},
|
||||
{ header: ASSET_SCHEMA.USER_POSITION.ui, sortKey: ASSET_SCHEMA.USER_POSITION.key, align: 'center', render: a => a[ASSET_SCHEMA.USER_POSITION.key] || '-' },
|
||||
{ header: ASSET_SCHEMA.ASSET_TYPE.ui, sortKey: ASSET_SCHEMA.ASSET_TYPE.key, align: 'center', width: '10%', render: a => a[ASSET_SCHEMA.ASSET_TYPE.key] || '-' },
|
||||
{ header: ASSET_SCHEMA.CPU.ui, sortKey: ASSET_SCHEMA.CPU.key, align: 'center', render: a => a[ASSET_SCHEMA.CPU.key] || '' },
|
||||
|
||||
@@ -7,13 +7,13 @@ import { createListView } from './ListFactory';
|
||||
export function renderPcPartList(container: HTMLElement) {
|
||||
createListView(container, {
|
||||
title: 'PC부품',
|
||||
dataSource: () => sortAssets(state.masterData.equipment?.filter((a: any) => a.category === 'PC부품') || []),
|
||||
dataSource: () => sortAssets(state.masterData.pcParts || []),
|
||||
searchKeys: ['MODEL_NAME', 'ASSET_TYPE'],
|
||||
filterOptions: {
|
||||
keywordLabel: `통합 검색 (${ASSET_SCHEMA.MODEL_NAME.ui})`,
|
||||
showLoc: true,
|
||||
showDept: true,
|
||||
showType: true
|
||||
showType: true,
|
||||
showStatus: true
|
||||
},
|
||||
onRowClick: (asset) => openHwModal(asset, 'view'),
|
||||
columns: [
|
||||
@@ -24,7 +24,6 @@ export function renderPcPartList(container: HTMLElement) {
|
||||
render: a => `<span class="badge badge-success">${a[ASSET_SCHEMA.HW_STATUS.key] || '보관중'}</span>`
|
||||
},
|
||||
{ header: ASSET_SCHEMA.ASSET_TYPE.ui, sortKey: ASSET_SCHEMA.ASSET_TYPE.key, align: 'center', width: '10%', render: a => a[ASSET_SCHEMA.ASSET_TYPE.key] || '-' },
|
||||
{ header: ASSET_SCHEMA.ASSET_MFR.ui, sortKey: ASSET_SCHEMA.ASSET_MFR.key, align: 'center', render: a => a[ASSET_SCHEMA.ASSET_MFR.key] || '' },
|
||||
{ header: ASSET_SCHEMA.MODEL_NAME.ui, sortKey: ASSET_SCHEMA.MODEL_NAME.key, render: a => formatInline(a[ASSET_SCHEMA.MODEL_NAME.key] || '-') },
|
||||
{ header: ASSET_SCHEMA.VOLUME.ui, sortKey: ASSET_SCHEMA.VOLUME.key, align: 'center', render: a => a[ASSET_SCHEMA.VOLUME.key] || '-' },
|
||||
{ header: ASSET_SCHEMA.MONITOR_INCH.ui, sortKey: ASSET_SCHEMA.MONITOR_INCH.key, align: 'center', render: a => a[ASSET_SCHEMA.MONITOR_INCH.key] || '-' },
|
||||
|
||||
@@ -7,13 +7,13 @@ import { createListView } from './ListFactory';
|
||||
export function renderSpaceInfoList(container: HTMLElement) {
|
||||
createListView(container, {
|
||||
title: '공간정보장비',
|
||||
dataSource: () => sortAssets(state.masterData.equipment?.filter((a: any) => a.category === '공간정보장비') || []),
|
||||
dataSource: () => sortAssets(state.masterData.survey || []),
|
||||
searchKeys: ['MODEL_NAME', 'PRODUCT_NAME', 'CURRENT_USER', 'ASSET_TYPE'],
|
||||
filterOptions: {
|
||||
keywordLabel: `통합 검색 (${ASSET_SCHEMA.MODEL_NAME.ui}/${ASSET_SCHEMA.CURRENT_USER.ui})`,
|
||||
showLoc: true,
|
||||
showDept: true,
|
||||
showType: true
|
||||
showType: true,
|
||||
showStatus: true
|
||||
},
|
||||
onRowClick: (asset) => openHwModal(asset, 'view'),
|
||||
columns: [
|
||||
|
||||
@@ -11,9 +11,9 @@ export function renderStorageList(container: HTMLElement) {
|
||||
searchKeys: ['MODEL_NAME', 'CURRENT_USER', 'SERIAL_NUM', 'ASSET_TYPE'],
|
||||
filterOptions: {
|
||||
keywordLabel: `통합 검색 (${ASSET_SCHEMA.MODEL_NAME.ui}/${ASSET_SCHEMA.CURRENT_USER.ui})`,
|
||||
showLoc: true,
|
||||
showDept: true,
|
||||
showType: true
|
||||
showType: true,
|
||||
showStatus: true
|
||||
},
|
||||
onRowClick: (asset) => openHwModal(asset, 'view'),
|
||||
columns: [
|
||||
|
||||
@@ -39,9 +39,11 @@
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
min-width: 100%;
|
||||
max-width: none;
|
||||
border-collapse: separate;
|
||||
border-spacing: 0;
|
||||
table-layout: fixed; /* Force fixed layout to prevent horizontal scroll */
|
||||
table-layout: fixed;
|
||||
}
|
||||
|
||||
th, td {
|
||||
@@ -68,6 +70,25 @@ th {
|
||||
letter-spacing: -0.02em;
|
||||
box-shadow: inset 0 -1px 0 var(--hairline);
|
||||
text-align: center; /* Set default header alignment to center */
|
||||
position: relative; /* Essential for absolute positioning of resizer handles */
|
||||
}
|
||||
|
||||
.resizer {
|
||||
position: absolute;
|
||||
right: 0;
|
||||
top: 0;
|
||||
width: 6px;
|
||||
height: 100%;
|
||||
cursor: col-resize;
|
||||
user-select: none;
|
||||
z-index: 60; /* Higher than thead's sticky z-index (50) to catch mouse events */
|
||||
}
|
||||
|
||||
.resizer:hover,
|
||||
.resizer.resizing {
|
||||
background-color: var(--primary, #1e5149);
|
||||
opacity: 0.8;
|
||||
width: 3px;
|
||||
}
|
||||
|
||||
td {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { IMAGE_LOCATIONS } from '../components/Modal/SharedData';
|
||||
import { createIcons, X, Save, Trash2, ChevronLeft, ChevronRight } from 'lucide';
|
||||
import { QRPrinter } from '../core/qr_print';
|
||||
import './map-editor.css';
|
||||
|
||||
export class MapEditor {
|
||||
private container: HTMLElement;
|
||||
@@ -114,28 +115,7 @@ export class MapEditor {
|
||||
this.render();
|
||||
}
|
||||
|
||||
private bindEvents() {
|
||||
this.wrapper.addEventListener('mousedown', (e) => {
|
||||
if (e.button !== 0) return;
|
||||
this.isDrawing = true;
|
||||
const rect = this.wrapper.getBoundingClientRect();
|
||||
this.startX = e.clientX - rect.left;
|
||||
this.startY = e.clientY - rect.top;
|
||||
|
||||
this.currentBox = document.createElement('div');
|
||||
this.currentBox.className = 'draw-box';
|
||||
this.currentBox.style.left = this.startX + 'px';
|
||||
this.currentBox.style.top = this.startY + 'px';
|
||||
|
||||
const label = document.createElement('div');
|
||||
label.className = 'box-label';
|
||||
label.textContent = '#' + (this.boxes.length + 1);
|
||||
this.currentBox.appendChild(label);
|
||||
|
||||
this.wrapper.appendChild(this.currentBox);
|
||||
});
|
||||
|
||||
window.addEventListener('mousemove', (e) => {
|
||||
private onWindowMouseMove = (e: MouseEvent) => {
|
||||
if (!this.isDrawing || !this.currentBox) return;
|
||||
const rect = this.wrapper.getBoundingClientRect();
|
||||
const currentX = Math.max(0, Math.min(e.clientX - rect.left, rect.width));
|
||||
@@ -148,9 +128,9 @@ export class MapEditor {
|
||||
this.currentBox.style.height = Math.abs(height) + 'px';
|
||||
this.currentBox.style.left = (width > 0 ? this.startX : currentX) + 'px';
|
||||
this.currentBox.style.top = (height > 0 ? this.startY : currentY) + 'px';
|
||||
});
|
||||
};
|
||||
|
||||
window.addEventListener('mouseup', () => {
|
||||
private onWindowMouseUp = () => {
|
||||
if (!this.isDrawing || !this.currentBox) return;
|
||||
this.isDrawing = false;
|
||||
|
||||
@@ -172,8 +152,32 @@ export class MapEditor {
|
||||
|
||||
this.currentBox.remove();
|
||||
this.currentBox = null;
|
||||
};
|
||||
|
||||
private bindEvents() {
|
||||
this.wrapper.addEventListener('mousedown', (e) => {
|
||||
if (e.button !== 0) return;
|
||||
this.isDrawing = true;
|
||||
const rect = this.wrapper.getBoundingClientRect();
|
||||
this.startX = e.clientX - rect.left;
|
||||
this.startY = e.clientY - rect.top;
|
||||
|
||||
this.currentBox = document.createElement('div');
|
||||
this.currentBox.className = 'draw-box';
|
||||
this.currentBox.style.left = this.startX + 'px';
|
||||
this.currentBox.style.top = this.startY + 'px';
|
||||
|
||||
const label = document.createElement('div');
|
||||
label.className = 'box-label';
|
||||
label.textContent = '#' + (this.boxes.length + 1);
|
||||
this.currentBox.appendChild(label);
|
||||
|
||||
this.wrapper.appendChild(this.currentBox);
|
||||
});
|
||||
|
||||
window.addEventListener('mousemove', this.onWindowMouseMove);
|
||||
window.addEventListener('mouseup', this.onWindowMouseUp);
|
||||
|
||||
(window as any).removeBox = (index: number) => {
|
||||
this.boxes.splice(index, 1);
|
||||
this.render();
|
||||
@@ -341,6 +345,13 @@ export class MapEditor {
|
||||
}]);
|
||||
};
|
||||
}
|
||||
|
||||
public destroy() {
|
||||
window.removeEventListener('mousemove', this.onWindowMouseMove);
|
||||
window.removeEventListener('mouseup', this.onWindowMouseUp);
|
||||
delete (window as any).removeBox;
|
||||
delete (window as any).printBoxQR;
|
||||
}
|
||||
}
|
||||
|
||||
function getCleanMapKey(path: string) {
|
||||
|
||||
10
start_docker_wsl.bat
Normal file
10
start_docker_wsl.bat
Normal file
@@ -0,0 +1,10 @@
|
||||
@echo off
|
||||
chcp 65001 >nul
|
||||
cd /d "%~dp0"
|
||||
powershell -ExecutionPolicy Bypass -File "%~dp0start_docker_wsl.ps1"
|
||||
if errorlevel 1 (
|
||||
echo.
|
||||
echo [ERROR] start_docker_wsl.ps1 failed.
|
||||
pause
|
||||
exit /b %errorlevel%
|
||||
)
|
||||
107
start_docker_wsl.ps1
Normal file
107
start_docker_wsl.ps1
Normal file
@@ -0,0 +1,107 @@
|
||||
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
||||
|
||||
$projectWindowsPath = $PSScriptRoot
|
||||
$wslProjectPath = (wsl wslpath $projectWindowsPath).Trim()
|
||||
$envFilePath = Join-Path $PSScriptRoot '.env'
|
||||
|
||||
function Get-EnvValue {
|
||||
param(
|
||||
[string]$FilePath,
|
||||
[string]$Key
|
||||
)
|
||||
|
||||
if (-not (Test-Path $FilePath)) {
|
||||
return $null
|
||||
}
|
||||
|
||||
$line = Get-Content $FilePath | Where-Object { $_ -match "^$Key=" } | Select-Object -First 1
|
||||
if (-not $line) {
|
||||
return $null
|
||||
}
|
||||
|
||||
return ($line -split '=', 2)[1].Trim()
|
||||
}
|
||||
|
||||
function Test-TcpPortFast {
|
||||
param(
|
||||
[string]$HostName,
|
||||
[int]$Port,
|
||||
[int]$TimeoutMs = 3000
|
||||
)
|
||||
|
||||
$client = New-Object System.Net.Sockets.TcpClient
|
||||
try {
|
||||
$asyncResult = $client.BeginConnect($HostName, $Port, $null, $null)
|
||||
if (-not $asyncResult.AsyncWaitHandle.WaitOne($TimeoutMs, $false)) {
|
||||
$client.Close()
|
||||
return $false
|
||||
}
|
||||
|
||||
$client.EndConnect($asyncResult)
|
||||
$client.Close()
|
||||
return $true
|
||||
}
|
||||
catch {
|
||||
$client.Close()
|
||||
return $false
|
||||
}
|
||||
}
|
||||
|
||||
Write-Host "============================================" -ForegroundColor Cyan
|
||||
Write-Host " HM ITAM WSL Docker Start" -ForegroundColor Cyan
|
||||
Write-Host "============================================" -ForegroundColor Cyan
|
||||
Write-Host ""
|
||||
|
||||
Write-Host "[INFO] Checking WSL..."
|
||||
wsl -l -v
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Host "[ERROR] WSL is not available." -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
|
||||
Write-Host "[INFO] Checking Docker in WSL..."
|
||||
wsl sh -lc "docker --version"
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Host "[ERROR] Docker is not available inside WSL." -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
|
||||
$dbHost = Get-EnvValue -FilePath $envFilePath -Key 'DB_HOST'
|
||||
$dbPort = Get-EnvValue -FilePath $envFilePath -Key 'DB_PORT'
|
||||
|
||||
if (-not $dbPort) {
|
||||
$dbPort = '3306'
|
||||
}
|
||||
|
||||
if (-not $dbHost) {
|
||||
Write-Host "[WARN] .env is missing DB_HOST. Containers will still start, but backend DB calls will fail until DB settings are fixed." -ForegroundColor Yellow
|
||||
}
|
||||
|
||||
if ($dbHost) {
|
||||
Write-Host "[INFO] Checking external DB reachability..."
|
||||
$dbReachable = Test-TcpPortFast -HostName $dbHost -Port ([int]$dbPort)
|
||||
if (-not $dbReachable) {
|
||||
Write-Host "[WARN] External DB is unreachable: $dbHost`:$dbPort" -ForegroundColor Yellow
|
||||
Write-Host "[HINT] Containers will still start. Check VPN/private network connection, firewall rules, DB host/port in .env, or whether the DB server is running." -ForegroundColor Yellow
|
||||
}
|
||||
}
|
||||
|
||||
Write-Host "[INFO] Starting ITAM containers in WSL..."
|
||||
wsl sh -lc "cd '$wslProjectPath' && docker compose up --build -d --remove-orphans"
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Host "[WARN] Build-based startup failed. Retrying with cached images/containers..." -ForegroundColor Yellow
|
||||
wsl sh -lc "cd '$wslProjectPath' && docker compose up -d --remove-orphans"
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Host "[ERROR] Failed to start containers." -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "============================================" -ForegroundColor Green
|
||||
Write-Host " [OK] WSL Docker stack started." -ForegroundColor Green
|
||||
Write-Host " [INFO] Frontend: http://localhost:8080"
|
||||
Write-Host " [INFO] Backend : http://localhost:3000/api/assets/master"
|
||||
Write-Host "============================================" -ForegroundColor Green
|
||||
|
||||
Start-Process "http://localhost:8080"
|
||||
@@ -1,6 +1,49 @@
|
||||
# HM ITAM Server Start Script
|
||||
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
||||
|
||||
function Get-EnvValue {
|
||||
param(
|
||||
[string]$FilePath,
|
||||
[string]$Key
|
||||
)
|
||||
|
||||
if (-not (Test-Path $FilePath)) {
|
||||
return $null
|
||||
}
|
||||
|
||||
$line = Get-Content $FilePath | Where-Object { $_ -match "^$Key=" } | Select-Object -First 1
|
||||
if (-not $line) {
|
||||
return $null
|
||||
}
|
||||
|
||||
return ($line -split '=', 2)[1].Trim()
|
||||
}
|
||||
|
||||
function Test-TcpPortFast {
|
||||
param(
|
||||
[string]$HostName,
|
||||
[int]$Port,
|
||||
[int]$TimeoutMs = 3000
|
||||
)
|
||||
|
||||
$client = New-Object System.Net.Sockets.TcpClient
|
||||
try {
|
||||
$asyncResult = $client.BeginConnect($HostName, $Port, $null, $null)
|
||||
if (-not $asyncResult.AsyncWaitHandle.WaitOne($TimeoutMs, $false)) {
|
||||
$client.Close()
|
||||
return $false
|
||||
}
|
||||
|
||||
$client.EndConnect($asyncResult)
|
||||
$client.Close()
|
||||
return $true
|
||||
}
|
||||
catch {
|
||||
$client.Close()
|
||||
return $false
|
||||
}
|
||||
}
|
||||
|
||||
Write-Host "============================================" -ForegroundColor Cyan
|
||||
Write-Host " HM ITAM System Start" -ForegroundColor Cyan
|
||||
Write-Host "============================================" -ForegroundColor Cyan
|
||||
@@ -21,6 +64,13 @@ if (-not (Test-Path "node_modules")) {
|
||||
Write-Host "[INFO] Checking ports..."
|
||||
$backendPort = 3000
|
||||
$frontendPort = 8080
|
||||
$envFilePath = Join-Path $PSScriptRoot '.env'
|
||||
$dbHost = Get-EnvValue -FilePath $envFilePath -Key 'DB_HOST'
|
||||
$dbPort = Get-EnvValue -FilePath $envFilePath -Key 'DB_PORT'
|
||||
|
||||
if (-not $dbPort) {
|
||||
$dbPort = '3306'
|
||||
}
|
||||
|
||||
if (Get-NetTCPConnection -LocalPort $backendPort -ErrorAction SilentlyContinue) {
|
||||
Write-Host "[WARNING] Port $backendPort [Backend] is already in use." -ForegroundColor Yellow
|
||||
@@ -30,6 +80,21 @@ if (Get-NetTCPConnection -LocalPort $frontendPort -ErrorAction SilentlyContinue)
|
||||
Write-Host "[WARNING] Port $frontendPort [Frontend] is already in use." -ForegroundColor Yellow
|
||||
}
|
||||
|
||||
if (-not $dbHost) {
|
||||
Write-Host "[WARNING] .env is missing DB_HOST. Backend and frontend will still start, but DB calls will fail until DB settings are fixed." -ForegroundColor Yellow
|
||||
}
|
||||
else {
|
||||
Write-Host "[INFO] Checking external DB reachability..."
|
||||
$dbReachable = Test-TcpPortFast -HostName $dbHost -Port ([int]$dbPort)
|
||||
if ($dbReachable) {
|
||||
Write-Host "[INFO] External DB reachable: $dbHost`:$dbPort"
|
||||
}
|
||||
else {
|
||||
Write-Host "[WARNING] External DB is unreachable: $dbHost`:$dbPort" -ForegroundColor Yellow
|
||||
Write-Host "[WARNING] Backend and frontend will still start, but DB-backed screens and APIs may fail." -ForegroundColor Yellow
|
||||
}
|
||||
}
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "[INFO] Starting Backend [Port: 3000]..."
|
||||
Start-Process cmd -ArgumentList "/k npm run server"
|
||||
|
||||
4
stop_docker_wsl.bat
Normal file
4
stop_docker_wsl.bat
Normal file
@@ -0,0 +1,4 @@
|
||||
@echo off
|
||||
chcp 65001 >nul
|
||||
cd /d "%~dp0"
|
||||
powershell -ExecutionPolicy Bypass -File "%~dp0stop_docker_wsl.ps1"
|
||||
13
stop_docker_wsl.ps1
Normal file
13
stop_docker_wsl.ps1
Normal file
@@ -0,0 +1,13 @@
|
||||
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
||||
|
||||
$projectWindowsPath = $PSScriptRoot
|
||||
$wslProjectPath = (wsl wslpath $projectWindowsPath).Trim()
|
||||
|
||||
Write-Host "[INFO] Stopping ITAM WSL Docker stack..."
|
||||
wsl sh -lc "cd '$wslProjectPath' && docker compose down --remove-orphans"
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Host "[ERROR] Failed to stop containers." -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
|
||||
Write-Host "[OK] WSL Docker stack stopped." -ForegroundColor Green
|
||||
Binary file not shown.
Reference in New Issue
Block a user