88 lines
2.3 KiB
Go
88 lines
2.3 KiB
Go
package main
|
|
|
|
import (
|
|
"log"
|
|
"os"
|
|
"path/filepath"
|
|
|
|
"accounting-app/internal/config"
|
|
"accounting-app/internal/database"
|
|
"accounting-app/internal/models"
|
|
|
|
"github.com/joho/godotenv"
|
|
)
|
|
|
|
func main() {
|
|
// Load .env file from project root (try multiple locations)
|
|
envPaths := []string{
|
|
".env", // Current directory
|
|
"../.env", // Parent directory (when running from backend/)
|
|
"../../.env", // Two levels up (when running from backend/cmd/migrate/)
|
|
filepath.Join("..", "..", ".env"), // Explicit path
|
|
}
|
|
|
|
var envDir string
|
|
for _, envPath := range envPaths {
|
|
if err := godotenv.Load(envPath); err == nil {
|
|
log.Printf("Loaded environment from: %s", envPath)
|
|
envDir = filepath.Dir(envPath)
|
|
break
|
|
}
|
|
}
|
|
|
|
// Load specific environment file if APP_ENV is set (e.g. .env.dev, .env.prod)
|
|
if appEnv := os.Getenv("APP_ENV"); appEnv != "" {
|
|
targetEnvFile := ".env." + appEnv
|
|
targetEnvPath := targetEnvFile
|
|
if envDir != "" && envDir != "." {
|
|
targetEnvPath = filepath.Join(envDir, targetEnvFile)
|
|
}
|
|
|
|
if err := godotenv.Overload(targetEnvPath); err == nil {
|
|
log.Printf("Loaded specific environment config from: %s", targetEnvPath)
|
|
} else {
|
|
log.Printf("Note: Specific environment file %s not found or could not be loaded", targetEnvPath)
|
|
}
|
|
}
|
|
|
|
// Load configuration
|
|
cfg := config.Load()
|
|
|
|
// Initialize database connection
|
|
db, err := database.Initialize(
|
|
cfg.DBHost,
|
|
cfg.DBPort,
|
|
cfg.DBUser,
|
|
cfg.DBPassword,
|
|
cfg.DBName,
|
|
cfg.DBCharset,
|
|
)
|
|
if err != nil {
|
|
log.Fatalf("Failed to connect to database: %v", err)
|
|
}
|
|
|
|
// Get underlying SQL DB for cleanup
|
|
sqlDB, err := db.DB()
|
|
if err != nil {
|
|
log.Fatalf("Failed to get underlying database: %v", err)
|
|
}
|
|
defer sqlDB.Close()
|
|
|
|
log.Println("Starting database migration...")
|
|
|
|
// Run auto migration for all models
|
|
if err := db.AutoMigrate(models.AllModels()...); err != nil {
|
|
log.Fatalf("Failed to run migrations: %v", err)
|
|
}
|
|
|
|
log.Println("Database migration completed successfully!")
|
|
|
|
// Initialize system categories (refund and reimbursement)
|
|
log.Println("Initializing system categories...")
|
|
if err := models.InitSystemCategories(db); err != nil {
|
|
log.Fatalf("Failed to initialize system categories: %v", err)
|
|
}
|
|
|
|
log.Println("System categories initialized successfully!")
|
|
}
|