jasan/MIGRATE_V2_FIN.php
2026-03-04 21:17:52 +09:00

92 lines
3.6 KiB
PHP
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
/**
* Synology Autonomous Architect - Database Migration Script
* Target: laptop_assets table enhancement for 'Disposed' and 'Stock' status logic.
* Date: 2026-03-04
*/
header('Content-Type: text/plain; charset=utf-8');
try {
// 1. DB 연결 (절대 경로 보장)
$dbPath = __DIR__ . DIRECTORY_SEPARATOR . 'assets.db';
if (!file_exists($dbPath)) {
throw new Exception("데이터베이스 파일({$dbPath})을 찾을 수 없습니다.");
}
$db = new PDO("sqlite:$dbPath");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "--- [마이그레이션 시작] 노트북 자산 관리 시스템 v2 ---\n\n";
// 2. 백업 생성 (안전을 위한 rsync 성격의 파일 복사)
$backupPath = $dbPath . '.bak_' . date('Ymd_His');
if (!copy($dbPath, $backupPath)) {
throw new Exception("데이터베이스 백업 생성 실패");
}
echo "🛡️ 데이터 안전: 원본 백업이 생성되었습니다. ($backupPath)\n";
// 3. 스키마 확장 (컬럼 추가)
$newColumns = [
'real_user' => 'TEXT',
'disposal_user_id' => 'INTEGER'
];
foreach ($newColumns as $col => $type) {
try {
$db->exec("ALTER TABLE laptop_assets ADD COLUMN $col $type");
echo "✅ 컬럼 추가 성공: $col\n";
} catch (PDOException $e) {
if (strpos($e->getMessage(), 'duplicate column name') !== false) {
echo " 이미 존재함: $col (스키마 유지)\n";
} else {
throw $e;
}
}
}
// 4. 데이터 정합성 마이그레이션 - STOCK 상태 자산 명칭 동기화
// 기존에 STOCK 상태인 모든 자산의 배정사용자를 '업무용(TEMP_44666b)'으로 통합
$stmtStock = $db->prepare("
UPDATE laptop_assets
SET assigned_user_name = '업무용(TEMP_44666b)',
current_user_id = NULL
WHERE status = 'stock'
AND (assigned_user_name != '업무용(TEMP_44666b)' OR assigned_user_name IS NULL)
");
$stmtStock->execute();
$affectedStock = $stmtStock->rowCount();
echo "✅ 데이터 동기화: STOCK 자산 $affectedStock 건의 입력을 '업무용(TEMP_44666b)'으로 통일했습니다.\n";
// 5. 데이터 정합성 마이그레이션 - 매각 대상자 ID 복구
// 기존 매각 대상자 이름(disposal_recipient)이 직원 리스트에 있다면 ID를 찾아 매핑
$allDisposed = $db->query("
SELECT id, disposal_recipient
FROM laptop_assets
WHERE status = 'disposed'
AND disposal_recipient IS NOT NULL
AND disposal_user_id IS NULL
")->fetchAll(PDO::FETCH_ASSOC);
$idRestored = 0;
$userFinder = $db->prepare("SELECT id FROM users WHERE name = ? LIMIT 1");
$idUpdater = $db->prepare("UPDATE laptop_assets SET disposal_user_id = ? WHERE id = ?");
foreach ($allDisposed as $row) {
$userFinder->execute([$row['disposal_recipient']]);
$uid = $userFinder->fetchColumn();
if ($uid) {
$idUpdater->execute([$uid, $row['id']]);
$idRestored++;
}
}
echo "✅ 데이터 정합성: DISPOSED 자산 $idRestored 건의 사번 ID를 자동 매핑했습니다.\n\n";
echo "--- [마이그레이션 완료] 시스템이 정상적으로 업데이트되었습니다. ---\n";
} catch (Exception $e) {
echo "\n❌ [마이그레이션 실패] 오류 내용: " . $e->getMessage() . "\n";
if (isset($backupPath) && file_exists($backupPath)) {
echo "⚠️ 주의: 원본 데이터가 손상되었을 수 있으므로 백업 파일($backupPath)을 확인하십시오.\n";
}
}