# Setup SQL Server DB cho SOLUTION_ERP trên VPS chia sẻ với VIETREPORT. # Tạo database + grant quyền cho user vrapp (đã có sẵn trên server). # Idempotent: chạy lại không phá gì. # # Usage (chạy trên VPS với admin privilege): # .\setup-sql-db.ps1 -SaPassword 'your-sa-password' # # Prereq: # - SQL Server cài sẵn # - Login vrapp đã tồn tại (dùng chung với VIETREPORT) # - sqlcmd CLI available (đi kèm SQL Server) param( [Parameter(Mandatory=$true)] [string]$SaPassword, [string]$Server = ".", [string]$Database = "SolutionErp", [string]$AppUser = "vrapp" ) $ErrorActionPreference = 'Stop' function Invoke-Sql($query) { $output = sqlcmd -S $Server -U sa -P $SaPassword -Q $query -b 2>&1 if ($LASTEXITCODE -ne 0) { throw "SQL fail (exit $LASTEXITCODE):`n$output" } return $output } Write-Host "==> Check SQL Server reachable" Invoke-Sql "SELECT @@VERSION" | Select-Object -First 2 Write-Host "`n==> Check login '$AppUser' exists" $check = Invoke-Sql "SELECT name FROM sys.sql_logins WHERE name = '$AppUser'" if ($check -notmatch $AppUser) { Write-Error "Login '$AppUser' KHONG ton tai. Tao tay truoc: CREATE LOGIN [$AppUser] WITH PASSWORD='...'" exit 1 } Write-Host " OK" Write-Host "`n==> Create database '$Database' (if not exists)" Invoke-Sql @" IF DB_ID(N'$Database') IS NULL BEGIN CREATE DATABASE [$Database]; PRINT 'Created database $Database'; END ELSE PRINT 'Database $Database already exists'; "@ Write-Host "`n==> Grant db_owner cho '$AppUser' tren '$Database'" Invoke-Sql @" USE [$Database]; IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '$AppUser') BEGIN CREATE USER [$AppUser] FOR LOGIN [$AppUser]; PRINT 'Created user $AppUser in DB'; END ELSE PRINT 'User $AppUser already exists in DB'; ALTER ROLE db_owner ADD MEMBER [$AppUser]; PRINT 'Added $AppUser to db_owner'; "@ Write-Host "`n==> Verify kết nối với vrapp (test login)" Write-Host " (skip — tự test khi app chạy)" Write-Host "`n==> Setup backup schedule" Write-Host " Chạy: schtasks /Create /TN 'SolutionErp SQL Backup' /TR 'pwsh -File C:\solution-erp\scripts\backup-sql.ps1 -Server . -Database $Database' /SC DAILY /ST 02:00 /RU SYSTEM /F" Write-Host " (hoặc tạo tay qua Task Scheduler)" Write-Host "`n✅ SQL Server setup DONE" -ForegroundColor Green Write-Host " Database: $Database" Write-Host " App user: $AppUser (db_owner)" Write-Host " Connection string production: Server=localhost;Database=$Database;User Id=$AppUser;Password=***"