diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..85aee0d --- /dev/null +++ b/.env.example @@ -0,0 +1,33 @@ +# Server Configuration +PORT=8080 +HOST=localhost + +# Database Configuration +DB_HOST=localhost +DB_PORT=5432 +DB_USER=postgres +DB_PASSWORD=your_password +DB_NAME=booking_system +DB_SSLMODE=disable + +# JWT Configuration +JWT_SECRET=your-super-secret-jwt-key +JWT_EXPIRATION=24h + +# Stripe Configuration +STRIPE_SECRET_KEY=sk_test_your_stripe_secret_key +STRIPE_WEBHOOK_SECRET=whsec_your_webhook_secret +STRIPE_PUBLISHABLE_KEY=pk_test_your_publishable_key + +# SMTP Configuration +SMTP_HOST=smtp.gmail.com +SMTP_PORT=587 +SMTP_USERNAME=your_email@gmail.com +SMTP_PASSWORD=your_app_password +SMTP_FROM=your_email@gmail.com + +# Jitsi Configuration +JITSI_BASE_URL=https://meet.jit.si +JITSI_API_KEY=your_jitsi_api_key +JITSI_APP_ID=your_jitsi_app_id +JITSI_PRIVATE_KEY=your_jitsi_private_key \ No newline at end of file diff --git a/.gitignore b/.gitignore index 6b3f41d..e17b714 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ -.kiro/ \ No newline at end of file +.kiro/ +bin/ \ No newline at end of file diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..ab3b367 --- /dev/null +++ b/Makefile @@ -0,0 +1,57 @@ +.PHONY: build run test clean deps server cli + +# Build the server binary +build: + go build -o bin/server cmd/server/main.go + +# Build the CLI binary +build-cli: + go build -o bin/cli cmd/cli/main.go + +# Run the server +run: + go run cmd/server/main.go + +# Run the CLI +cli: + go run cmd/cli/main.go + +# Install dependencies +deps: + go mod tidy + go mod download + +# Run tests +test: + go test ./... + +# Clean build artifacts +clean: + rm -rf bin/ + +# Format code +fmt: + go fmt ./... + +# Vet code +vet: + go vet ./... + +# Run linter (requires golangci-lint) +lint: + golangci-lint run + +# Database operations +db-migrate: build-cli + ./bin/cli migrate + +db-health: build-cli + ./bin/cli db health + +db-seed: build-cli + ./bin/cli db seed + +# Development setup +dev-setup: deps + cp .env.example .env + @echo "Please update .env file with your configuration" \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..3e64411 --- /dev/null +++ b/README.md @@ -0,0 +1,104 @@ +# Video Conference Booking System + +A Go-based backend service for booking video conference meetings with Stripe payment integration and Jitsi Meet video conferencing. + +## Features + +- User registration and authentication +- Meeting booking with payment processing +- Jitsi Meet integration for video conferences +- Email notifications via SMTP +- Admin dashboard for system management +- CLI tools for admin operations + +## Project Structure + +``` +├── cmd/ +│ ├── server/ # HTTP server entry point +│ └── cli/ # CLI tools entry point +├── internal/ +│ ├── config/ # Configuration management +│ ├── server/ # HTTP server setup +│ ├── cli/ # CLI commands +│ ├── models/ # Database models +│ ├── services/ # Business logic layer +│ ├── repositories/ # Data access layer +│ ├── handlers/ # HTTP handlers +│ └── middleware/ # HTTP middleware +├── bin/ # Compiled binaries +├── .env.example # Environment variables template +├── Makefile # Development commands +└── README.md # This file +``` + +## Prerequisites + +- Go 1.21 or higher +- PostgreSQL database +- Stripe account (for payments) +- SMTP server (for email notifications) + +## Setup + +1. Clone the repository +2. Copy environment variables: + ```bash + cp .env.example .env + ``` +3. Update `.env` with your configuration +4. Install dependencies: + ```bash + make deps + ``` +5. Build the application: + ```bash + make build + ``` + +## Running the Application + +### HTTP Server +```bash +make run +# or +./bin/server +``` + +### CLI Tools +```bash +make cli +# or +./bin/cli +``` + +## Development + +- `make build` - Build server binary +- `make build-cli` - Build CLI binary +- `make run` - Run the server +- `make test` - Run tests +- `make fmt` - Format code +- `make vet` - Vet code +- `make clean` - Clean build artifacts + +## API Endpoints + +The server will start on `http://localhost:8080` by default. + +- `GET /health` - Health check +- `POST /api/v1/auth/register` - User registration +- `POST /api/v1/auth/login` - User login +- `GET /api/v1/bookings` - Get user bookings +- `POST /api/v1/bookings` - Create booking +- `GET /api/v1/schedules` - Get available slots +- `POST /api/v1/payments/intent` - Create payment intent +- `GET /api/v1/admin/dashboard` - Admin dashboard + +## Environment Variables + +See `.env.example` for all required environment variables. + +## License + +This project is proprietary software. \ No newline at end of file diff --git a/cmd/cli/main.go b/cmd/cli/main.go new file mode 100644 index 0000000..cc88079 --- /dev/null +++ b/cmd/cli/main.go @@ -0,0 +1,9 @@ +package main + +import ( + "attune-heart-therapy/internal/cli" +) + +func main() { + cli.Execute() +} diff --git a/cmd/server/main.go b/cmd/server/main.go new file mode 100644 index 0000000..bffbba4 --- /dev/null +++ b/cmd/server/main.go @@ -0,0 +1,62 @@ +package main + +import ( + "context" + "log" + "net/http" + "os" + "os/signal" + "syscall" + "time" + + "attune-heart-therapy/internal/config" + "attune-heart-therapy/internal/server" + + "github.com/joho/godotenv" +) + +func main() { + // Load environment variables + if err := godotenv.Load(); err != nil { + log.Println("No .env file found, using system environment variables") + } + + // Load configuration + cfg, err := config.Load() + if err != nil { + log.Fatalf("Failed to load configuration: %v", err) + } + + // Initialize server + srv := server.New(cfg) + + // Setup graceful shutdown + quit := make(chan os.Signal, 1) + signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) + + // Start server in a goroutine + go func() { + if err := srv.Start(); err != nil && err != http.ErrServerClosed { + log.Fatalf("Failed to start server: %v", err) + } + }() + + log.Println("Server started successfully") + + // Wait for interrupt signal + <-quit + log.Println("Shutting down server...") + + // Create a deadline for shutdown + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + // Shutdown server gracefully + if err := srv.Shutdown(); err != nil { + log.Printf("Error during server shutdown: %v", err) + } + + // Wait for context deadline or completion + <-ctx.Done() + log.Println("Server shutdown completed") +} diff --git a/go.mod b/go.mod index dd73dd6..8eb0006 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,50 @@ module attune-heart-therapy go 1.25.1 + +require ( + github.com/gin-gonic/gin v1.9.1 + github.com/joho/godotenv v1.5.1 + github.com/spf13/cobra v1.8.0 + github.com/stripe/stripe-go/v76 v76.25.0 + gorm.io/driver/postgres v1.6.0 + gorm.io/gorm v1.31.1 +) + +require ( + github.com/bytedance/sonic v1.9.1 // indirect + github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect + github.com/gabriel-vasile/mimetype v1.4.2 // indirect + github.com/gin-contrib/sse v0.1.0 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/go-playground/validator/v10 v10.14.0 // indirect + github.com/goccy/go-json v0.10.2 // indirect + github.com/inconshreveable/mousetrap v1.1.0 // indirect + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/jackc/pgx/v5 v5.6.0 // indirect + github.com/jackc/puddle/v2 v2.2.2 // indirect + github.com/jinzhu/inflection v1.0.0 // indirect + github.com/jinzhu/now v1.1.5 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/klauspost/cpuid/v2 v2.2.4 // indirect + github.com/kr/text v0.2.0 // indirect + github.com/leodido/go-urn v1.2.4 // indirect + github.com/mattn/go-isatty v0.0.19 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/pelletier/go-toml/v2 v2.0.8 // indirect + github.com/rogpeppe/go-internal v1.14.1 // indirect + github.com/spf13/pflag v1.0.5 // indirect + github.com/twitchyliquid64/golang-asm v0.15.1 // indirect + github.com/ugorji/go/codec v1.2.11 // indirect + golang.org/x/arch v0.3.0 // indirect + golang.org/x/crypto v0.31.0 // indirect + golang.org/x/net v0.21.0 // indirect + golang.org/x/sync v0.10.0 // indirect + golang.org/x/sys v0.28.0 // indirect + golang.org/x/text v0.21.0 // indirect + google.golang.org/protobuf v1.30.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..05b4879 --- /dev/null +++ b/go.sum @@ -0,0 +1,130 @@ +github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM= +github.com/bytedance/sonic v1.9.1 h1:6iJ6NqdoxCDr6mbY8h18oSO+cShGSMRGCEo7F2h0x8s= +github.com/bytedance/sonic v1.9.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U= +github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY= +github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 h1:qSGYFH7+jGhDF8vLC+iwCD4WpbV1EBDSzWkJODFLams= +github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk= +github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU= +github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA= +github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= +github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= +github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg= +github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU= +github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= +github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.14.0 h1:vgvQWe3XCz3gIeFDm/HnTIbj6UGmg/+t63MyGU2n5js= +github.com/go-playground/validator/v10 v10.14.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU= +github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= +github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= +github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.6.0 h1:SWJzexBzPL5jb0GEsrPMLIsi/3jOo7RHlzTjcAeDrPY= +github.com/jackc/pgx/v5 v5.6.0/go.mod h1:DNZ/vlrUnhWCoFGxHAG8U2ljioxukquj7utPDgtQdTw= +github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= +github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= +github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= +github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= +github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= +github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.2.4 h1:acbojRNwl3o09bUq+yDCtZFc1aiwaAAxtcn8YkZXnvk= +github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY= +github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= +github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q= +github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4= +github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= +github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/pelletier/go-toml/v2 v2.0.8 h1:0ctb6s9mE31h0/lhu+J6OPmVeDxJn+kYnJc2jZR9tGQ= +github.com/pelletier/go-toml/v2 v2.0.8/go.mod h1:vuYfssBdrU2XDZ9bYydBu6t+6a6PYNcZljzZR9VXg+4= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= +github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0= +github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho= +github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= +github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.3 h1:RP3t2pwF7cMEbC1dqtB6poj3niw/9gnV4Cjg5oW5gtY= +github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stripe/stripe-go/v76 v76.25.0 h1:kmDoOTvdQSTQssQzWZQQkgbAR2Q8eXdMWbN/ylNalWA= +github.com/stripe/stripe-go/v76 v76.25.0/go.mod h1:rw1MxjlAKKcZ+3FOXgTHgwiOa2ya6CPq6ykpJ0Q6Po4= +github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= +github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= +github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU= +github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= +golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= +golang.org/x/arch v0.3.0 h1:02VY4/ZcO/gBOH6PUaoiptASxtXU10jazRCP865E97k= +golang.org/x/arch v0.3.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= +golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U= +golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk= +golang.org/x/net v0.0.0-20210520170846-37e1c6afe023/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4= +golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44= +golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ= +golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA= +golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo= +golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= +google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng= +google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gorm.io/driver/postgres v1.6.0 h1:2dxzU8xJ+ivvqTRph34QX+WrRaJlmfyPqXmoGVjMBa4= +gorm.io/driver/postgres v1.6.0/go.mod h1:vUw0mrGgrTK+uPHEhAdV4sfFELrByKVGnaVRkXDhtWo= +gorm.io/gorm v1.31.1 h1:7CA8FTFz/gRfgqgpeKIBcervUn3xSyPUmr6B2WXJ7kg= +gorm.io/gorm v1.31.1/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs= +rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= diff --git a/internal/cli/db.go b/internal/cli/db.go new file mode 100644 index 0000000..f75eb83 --- /dev/null +++ b/internal/cli/db.go @@ -0,0 +1,94 @@ +package cli + +import ( + "log" + + "attune-heart-therapy/internal/config" + "attune-heart-therapy/internal/database" + + "github.com/joho/godotenv" + "github.com/spf13/cobra" +) + +var dbCmd = &cobra.Command{ + Use: "db", + Short: "Database management commands", + Long: "Commands for managing database operations", +} + +var dbHealthCmd = &cobra.Command{ + Use: "health", + Short: "Check database connectivity", + Long: "Check if the database connection is working properly", + Run: runDBHealth, +} + +var dbSeedCmd = &cobra.Command{ + Use: "seed", + Short: "Seed database with initial data", + Long: "Populate database with initial data", + Run: runDBSeed, +} + +func runDBHealth(cmd *cobra.Command, args []string) { + // Load environment variables + if err := godotenv.Load(); err != nil { + log.Println("No .env file found, using system environment variables") + } + + // Load configuration + cfg, err := config.Load() + if err != nil { + log.Fatalf("Failed to load configuration: %v", err) + } + + // Initialize database connection + db, err := database.New(cfg) + if err != nil { + log.Fatalf("Failed to connect to database: %v", err) + } + defer db.Close() + + // Check database health + if err := db.Health(); err != nil { + log.Fatalf("Database health check failed: %v", err) + } + + log.Println("Database connection is healthy") +} + +func runDBSeed(cmd *cobra.Command, args []string) { + // Load environment variables + if err := godotenv.Load(); err != nil { + log.Println("No .env file found, using system environment variables") + } + + // Load configuration + cfg, err := config.Load() + if err != nil { + log.Fatalf("Failed to load configuration: %v", err) + } + + // Initialize database connection + db, err := database.New(cfg) + if err != nil { + log.Fatalf("Failed to connect to database: %v", err) + } + defer db.Close() + + // Run seeding + if err := db.Seed(); err != nil { + log.Fatalf("Failed to seed database: %v", err) + } + + log.Println("Database seeding completed successfully") +} + +func init() { + // Add subcommands to db command + dbCmd.AddCommand(dbHealthCmd) + dbCmd.AddCommand(dbSeedCmd) + + // Add db command to root + rootCmd.AddCommand(dbCmd) +} diff --git a/internal/cli/migrate.go b/internal/cli/migrate.go new file mode 100644 index 0000000..3ec5b91 --- /dev/null +++ b/internal/cli/migrate.go @@ -0,0 +1,49 @@ +package cli + +import ( + "log" + + "attune-heart-therapy/internal/config" + "attune-heart-therapy/internal/database" + + "github.com/joho/godotenv" + "github.com/spf13/cobra" +) + +var migrateCmd = &cobra.Command{ + Use: "migrate", + Short: "Run database migrations", + Long: "Run database migrations to create or update database schema", + Run: runMigrate, +} + +func runMigrate(cmd *cobra.Command, args []string) { + // Load environment variables + if err := godotenv.Load(); err != nil { + log.Println("No .env file found, using system environment variables") + } + + // Load configuration + cfg, err := config.Load() + if err != nil { + log.Fatalf("Failed to load configuration: %v", err) + } + + // Initialize database connection + db, err := database.New(cfg) + if err != nil { + log.Fatalf("Failed to connect to database: %v", err) + } + defer db.Close() + + // Run migrations + if err := db.Migrate(); err != nil { + log.Fatalf("Failed to run migrations: %v", err) + } + + log.Println("Database migrations completed successfully") +} + +func init() { + rootCmd.AddCommand(migrateCmd) +} diff --git a/internal/cli/root.go b/internal/cli/root.go new file mode 100644 index 0000000..29618e7 --- /dev/null +++ b/internal/cli/root.go @@ -0,0 +1,25 @@ +package cli + +import ( + "fmt" + "os" + + "github.com/spf13/cobra" +) + +var rootCmd = &cobra.Command{ + Use: "booking-system", + Short: "Video Conference Booking System CLI", + Long: "Command line interface for managing the video conference booking system", +} + +func Execute() { + if err := rootCmd.Execute(); err != nil { + fmt.Println(err) + os.Exit(1) + } +} + +func init() { + // Add subcommands here in later tasks +} diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100644 index 0000000..e3b741d --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,122 @@ +package config + +import ( + "os" + "strconv" + "time" +) + +type Config struct { + Server ServerConfig + Database DatabaseConfig + JWT JWTConfig + Stripe StripeConfig + SMTP SMTPConfig + Jitsi JitsiConfig +} + +type ServerConfig struct { + Port string + Host string +} + +type DatabaseConfig struct { + Host string + Port string + User string + Password string + Name string + SSLMode string +} + +type JWTConfig struct { + Secret string + Expiration time.Duration +} + +type StripeConfig struct { + SecretKey string + WebhookSecret string + PublishableKey string +} + +type SMTPConfig struct { + Host string + Port int + Username string + Password string + From string +} + +type JitsiConfig struct { + BaseURL string + APIKey string + AppID string + PrivateKey string +} + +func Load() (*Config, error) { + cfg := &Config{ + Server: ServerConfig{ + Port: getEnv("PORT", "8080"), + Host: getEnv("HOST", "localhost"), + }, + Database: DatabaseConfig{ + Host: getEnv("DB_HOST", "localhost"), + Port: getEnv("DB_PORT", "5432"), + User: getEnv("DB_USER", "postgres"), + Password: getEnv("DB_PASSWORD", ""), + Name: getEnv("DB_NAME", "booking_system"), + SSLMode: getEnv("DB_SSLMODE", "disable"), + }, + JWT: JWTConfig{ + Secret: getEnv("JWT_SECRET", "your-secret-key"), + Expiration: getEnvDuration("JWT_EXPIRATION", 24*time.Hour), + }, + Stripe: StripeConfig{ + SecretKey: getEnv("STRIPE_SECRET_KEY", ""), + WebhookSecret: getEnv("STRIPE_WEBHOOK_SECRET", ""), + PublishableKey: getEnv("STRIPE_PUBLISHABLE_KEY", ""), + }, + SMTP: SMTPConfig{ + Host: getEnv("SMTP_HOST", ""), + Port: getEnvInt("SMTP_PORT", 587), + Username: getEnv("SMTP_USERNAME", ""), + Password: getEnv("SMTP_PASSWORD", ""), + From: getEnv("SMTP_FROM", ""), + }, + Jitsi: JitsiConfig{ + BaseURL: getEnv("JITSI_BASE_URL", ""), + APIKey: getEnv("JITSI_API_KEY", ""), + AppID: getEnv("JITSI_APP_ID", ""), + PrivateKey: getEnv("JITSI_PRIVATE_KEY", ""), + }, + } + + return cfg, nil +} + +func getEnv(key, defaultValue string) string { + if value := os.Getenv(key); value != "" { + return value + } + return defaultValue +} + +func getEnvInt(key string, defaultValue int) int { + if value := os.Getenv(key); value != "" { + if intValue, err := strconv.Atoi(value); err == nil { + return intValue + } + } + return defaultValue +} + +func getEnvDuration(key string, defaultValue time.Duration) time.Duration { + if value := os.Getenv(key); value != "" { + if duration, err := time.ParseDuration(value); err == nil { + return duration + } + } + return defaultValue +} diff --git a/internal/database/database.go b/internal/database/database.go new file mode 100644 index 0000000..b98ffb5 --- /dev/null +++ b/internal/database/database.go @@ -0,0 +1,112 @@ +package database + +import ( + "fmt" + "log" + + "attune-heart-therapy/internal/config" + "attune-heart-therapy/internal/models" + + "gorm.io/driver/postgres" + "gorm.io/gorm" + "gorm.io/gorm/logger" +) + +// DB holds the database connection +type DB struct { + *gorm.DB +} + +// New creates a new database connection +func New(cfg *config.Config) (*DB, error) { + dsn := fmt.Sprintf( + "host=%s user=%s password=%s dbname=%s port=%s sslmode=%s TimeZone=UTC", + cfg.Database.Host, + cfg.Database.User, + cfg.Database.Password, + cfg.Database.Name, + cfg.Database.Port, + cfg.Database.SSLMode, + ) + + // Configure GORM logger + gormConfig := &gorm.Config{ + Logger: logger.Default.LogMode(logger.Info), + } + + db, err := gorm.Open(postgres.Open(dsn), gormConfig) + if err != nil { + return nil, fmt.Errorf("failed to connect to database: %w", err) + } + + // Configure connection pool + sqlDB, err := db.DB() + if err != nil { + return nil, fmt.Errorf("failed to get underlying sql.DB: %w", err) + } + + // Set connection pool settings + sqlDB.SetMaxIdleConns(10) + sqlDB.SetMaxOpenConns(100) + + log.Println("Successfully connected to PostgreSQL database") + + return &DB{db}, nil +} + +// Close closes the database connection +func (db *DB) Close() error { + sqlDB, err := db.DB.DB() + if err != nil { + return err + } + return sqlDB.Close() +} + +// Migrate runs database migrations +func (db *DB) Migrate() error { + log.Println("Running database migrations...") + + // Auto-migrate all models + err := db.AutoMigrate( + &models.User{}, + &models.Schedule{}, + &models.Booking{}, + &models.Notification{}, + ) + + if err != nil { + return fmt.Errorf("failed to run migrations: %w", err) + } + + log.Println("Database migrations completed successfully") + return nil +} + +// Seed creates initial data for the database +func (db *DB) Seed() error { + log.Println("Seeding database with initial data...") + + // Check if we already have data to avoid duplicate seeding + var userCount int64 + db.Model(&models.User{}).Count(&userCount) + + if userCount > 0 { + log.Println("Database already contains data, skipping seeding") + return nil + } + + // Add any initial data here if needed + // For now, we'll just log that seeding is complete + log.Println("Database seeding completed") + return nil +} + +// Health checks database connectivity +func (db *DB) Health() error { + sqlDB, err := db.DB.DB() + if err != nil { + return err + } + return sqlDB.Ping() +} diff --git a/internal/handlers/admin.go b/internal/handlers/admin.go new file mode 100644 index 0000000..357aa9f --- /dev/null +++ b/internal/handlers/admin.go @@ -0,0 +1,38 @@ +package handlers + +import ( + "github.com/gin-gonic/gin" +) + +type AdminHandler struct { + // Will be implemented in later tasks +} + +func NewAdminHandler() *AdminHandler { + return &AdminHandler{} +} + +func (h *AdminHandler) GetDashboard(c *gin.Context) { + // Will be implemented in task 11 + c.JSON(501, gin.H{"message": "Not implemented yet"}) +} + +func (h *AdminHandler) CreateSchedule(c *gin.Context) { + // Will be implemented in task 11 + c.JSON(501, gin.H{"message": "Not implemented yet"}) +} + +func (h *AdminHandler) GetUsers(c *gin.Context) { + // Will be implemented in task 11 + c.JSON(501, gin.H{"message": "Not implemented yet"}) +} + +func (h *AdminHandler) GetBookings(c *gin.Context) { + // Will be implemented in task 11 + c.JSON(501, gin.H{"message": "Not implemented yet"}) +} + +func (h *AdminHandler) GetFinancialReports(c *gin.Context) { + // Will be implemented in task 11 + c.JSON(501, gin.H{"message": "Not implemented yet"}) +} diff --git a/internal/handlers/auth.go b/internal/handlers/auth.go new file mode 100644 index 0000000..f9a7668 --- /dev/null +++ b/internal/handlers/auth.go @@ -0,0 +1,33 @@ +package handlers + +import ( + "github.com/gin-gonic/gin" +) + +type AuthHandler struct { + // Will be implemented in later tasks +} + +func NewAuthHandler() *AuthHandler { + return &AuthHandler{} +} + +func (h *AuthHandler) Register(c *gin.Context) { + // Will be implemented in task 6 + c.JSON(501, gin.H{"message": "Not implemented yet"}) +} + +func (h *AuthHandler) Login(c *gin.Context) { + // Will be implemented in task 6 + c.JSON(501, gin.H{"message": "Not implemented yet"}) +} + +func (h *AuthHandler) GetProfile(c *gin.Context) { + // Will be implemented in task 6 + c.JSON(501, gin.H{"message": "Not implemented yet"}) +} + +func (h *AuthHandler) UpdateProfile(c *gin.Context) { + // Will be implemented in task 6 + c.JSON(501, gin.H{"message": "Not implemented yet"}) +} diff --git a/internal/handlers/booking.go b/internal/handlers/booking.go new file mode 100644 index 0000000..b8ebbea --- /dev/null +++ b/internal/handlers/booking.go @@ -0,0 +1,38 @@ +package handlers + +import ( + "github.com/gin-gonic/gin" +) + +type BookingHandler struct { + // Will be implemented in later tasks +} + +func NewBookingHandler() *BookingHandler { + return &BookingHandler{} +} + +func (h *BookingHandler) GetAvailableSlots(c *gin.Context) { + // Will be implemented in task 9 + c.JSON(501, gin.H{"message": "Not implemented yet"}) +} + +func (h *BookingHandler) CreateBooking(c *gin.Context) { + // Will be implemented in task 9 + c.JSON(501, gin.H{"message": "Not implemented yet"}) +} + +func (h *BookingHandler) GetUserBookings(c *gin.Context) { + // Will be implemented in task 9 + c.JSON(501, gin.H{"message": "Not implemented yet"}) +} + +func (h *BookingHandler) CancelBooking(c *gin.Context) { + // Will be implemented in task 9 + c.JSON(501, gin.H{"message": "Not implemented yet"}) +} + +func (h *BookingHandler) RescheduleBooking(c *gin.Context) { + // Will be implemented in task 9 + c.JSON(501, gin.H{"message": "Not implemented yet"}) +} diff --git a/internal/handlers/payment.go b/internal/handlers/payment.go new file mode 100644 index 0000000..c6dafbb --- /dev/null +++ b/internal/handlers/payment.go @@ -0,0 +1,28 @@ +package handlers + +import ( + "github.com/gin-gonic/gin" +) + +type PaymentHandler struct { + // Will be implemented in later tasks +} + +func NewPaymentHandler() *PaymentHandler { + return &PaymentHandler{} +} + +func (h *PaymentHandler) CreatePaymentIntent(c *gin.Context) { + // Will be implemented in task 7 + c.JSON(501, gin.H{"message": "Not implemented yet"}) +} + +func (h *PaymentHandler) ConfirmPayment(c *gin.Context) { + // Will be implemented in task 7 + c.JSON(501, gin.H{"message": "Not implemented yet"}) +} + +func (h *PaymentHandler) HandleWebhook(c *gin.Context) { + // Will be implemented in task 7 + c.JSON(501, gin.H{"message": "Not implemented yet"}) +} diff --git a/internal/middleware/auth.go b/internal/middleware/auth.go new file mode 100644 index 0000000..ffbbcba --- /dev/null +++ b/internal/middleware/auth.go @@ -0,0 +1,23 @@ +package middleware + +import ( + "github.com/gin-gonic/gin" +) + +// AuthMiddleware validates JWT tokens +func AuthMiddleware() gin.HandlerFunc { + return func(c *gin.Context) { + // Will be implemented in task 5 + c.JSON(501, gin.H{"message": "Auth middleware not implemented yet"}) + c.Abort() + } +} + +// AdminMiddleware ensures user has admin privileges +func AdminMiddleware() gin.HandlerFunc { + return func(c *gin.Context) { + // Will be implemented in task 5 + c.JSON(501, gin.H{"message": "Admin middleware not implemented yet"}) + c.Abort() + } +} diff --git a/internal/middleware/cors.go b/internal/middleware/cors.go new file mode 100644 index 0000000..1f020e7 --- /dev/null +++ b/internal/middleware/cors.go @@ -0,0 +1,22 @@ +package middleware + +import ( + "github.com/gin-gonic/gin" +) + +// CORSMiddleware handles Cross-Origin Resource Sharing +func CORSMiddleware() gin.HandlerFunc { + return func(c *gin.Context) { + // Will be implemented in task 13 + c.Header("Access-Control-Allow-Origin", "*") + c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS") + c.Header("Access-Control-Allow-Headers", "Origin, Content-Type, Authorization") + + if c.Request.Method == "OPTIONS" { + c.AbortWithStatus(204) + return + } + + c.Next() + } +} diff --git a/internal/models/booking.go b/internal/models/booking.go new file mode 100644 index 0000000..5f08c32 --- /dev/null +++ b/internal/models/booking.go @@ -0,0 +1,88 @@ +package models + +import ( + "errors" + "time" + + "gorm.io/gorm" +) + +// BookingStatus represents the possible states of a booking +type BookingStatus string + +const ( + BookingStatusScheduled BookingStatus = "scheduled" + BookingStatusCompleted BookingStatus = "completed" + BookingStatusCancelled BookingStatus = "cancelled" +) + +// PaymentStatus represents the possible states of a payment +type PaymentStatus string + +const ( + PaymentStatusPending PaymentStatus = "pending" + PaymentStatusSucceeded PaymentStatus = "succeeded" + PaymentStatusFailed PaymentStatus = "failed" + PaymentStatusRefunded PaymentStatus = "refunded" +) + +// Booking represents a scheduled meeting +type Booking struct { + gorm.Model + UserID uint `json:"user_id" gorm:"not null;index" validate:"required"` + User User `json:"user" gorm:"foreignKey:UserID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE"` + ScheduledAt time.Time `json:"scheduled_at" gorm:"not null;index" validate:"required"` + Duration int `json:"duration" gorm:"default:60;check:duration > 0" validate:"min=15,max=480"` // minutes, 15min to 8hrs + Status BookingStatus `json:"status" gorm:"default:'scheduled';size:20" validate:"required,oneof=scheduled completed cancelled"` + JitsiRoomID string `json:"jitsi_room_id" gorm:"size:255;index"` + JitsiRoomURL string `json:"jitsi_room_url" gorm:"size:500"` + PaymentID string `json:"payment_id" gorm:"size:255;index"` + PaymentStatus PaymentStatus `json:"payment_status" gorm:"size:20" validate:"omitempty,oneof=pending succeeded failed refunded"` + Amount float64 `json:"amount" gorm:"type:decimal(10,2);check:amount >= 0" validate:"min=0"` + Notes string `json:"notes" gorm:"type:text"` +} + +// BeforeCreate is a GORM hook that runs before creating a booking record +func (b *Booking) BeforeCreate(tx *gorm.DB) error { + // Validate that the scheduled time is in the future + if b.ScheduledAt.Before(time.Now()) { + return errors.New("booking cannot be scheduled in the past") + } + + // Set default status if not provided + if b.Status == "" { + b.Status = BookingStatusScheduled + } + + // Set default duration if not provided + if b.Duration == 0 { + b.Duration = 60 + } + + return nil +} + +// BeforeUpdate is a GORM hook that runs before updating a booking record +func (b *Booking) BeforeUpdate(tx *gorm.DB) error { + // Prevent updating completed bookings + if b.Status == BookingStatusCompleted { + return errors.New("cannot modify completed bookings") + } + + return nil +} + +// CanBeCancelled checks if the booking can be cancelled +func (b *Booking) CanBeCancelled() bool { + return b.Status == BookingStatusScheduled && b.ScheduledAt.After(time.Now().Add(24*time.Hour)) +} + +// CanBeRescheduled checks if the booking can be rescheduled +func (b *Booking) CanBeRescheduled() bool { + return b.Status == BookingStatusScheduled && b.ScheduledAt.After(time.Now().Add(2*time.Hour)) +} + +// IsUpcoming checks if the booking is scheduled for the future +func (b *Booking) IsUpcoming() bool { + return b.Status == BookingStatusScheduled && b.ScheduledAt.After(time.Now()) +} diff --git a/internal/models/notification.go b/internal/models/notification.go new file mode 100644 index 0000000..261ab41 --- /dev/null +++ b/internal/models/notification.go @@ -0,0 +1,19 @@ +package models + +import ( + "time" + + "gorm.io/gorm" +) + +// Notification represents email notifications +type Notification struct { + gorm.Model + UserID uint `json:"user_id"` + Type string `json:"type"` // welcome, payment_success, payment_failed, meeting_info, reminder + Subject string `json:"subject"` + Body string `json:"body"` + SentAt *time.Time `json:"sent_at"` + Status string `json:"status" gorm:"default:'pending'"` // pending, sent, failed + ScheduledAt *time.Time `json:"scheduled_at"` +} diff --git a/internal/models/schedule.go b/internal/models/schedule.go new file mode 100644 index 0000000..c05d3e3 --- /dev/null +++ b/internal/models/schedule.go @@ -0,0 +1,17 @@ +package models + +import ( + "time" + + "gorm.io/gorm" +) + +// Schedule represents available time slots +type Schedule struct { + gorm.Model + StartTime time.Time `json:"start_time" gorm:"not null"` + EndTime time.Time `json:"end_time" gorm:"not null"` + IsAvailable bool `json:"is_available" gorm:"default:true"` + MaxBookings int `json:"max_bookings" gorm:"default:1"` + BookedCount int `json:"booked_count" gorm:"default:0"` +} diff --git a/internal/models/user.go b/internal/models/user.go new file mode 100644 index 0000000..97d343f --- /dev/null +++ b/internal/models/user.go @@ -0,0 +1,52 @@ +package models + +import ( + "errors" + "strings" + "time" + + "golang.org/x/crypto/bcrypt" + "gorm.io/gorm" +) + +// User represents a system user +type User struct { + gorm.Model + FirstName string `json:"first_name" gorm:"not null;size:100" validate:"required,min=2,max=100"` + LastName string `json:"last_name" gorm:"not null;size:100" validate:"required,min=2,max=100"` + Email string `json:"email" gorm:"unique;not null;size:255" validate:"required,email"` + Phone string `json:"phone" gorm:"size:20" validate:"omitempty,min=10,max=20"` + Location string `json:"location" gorm:"size:255" validate:"omitempty,max=255"` + DateOfBirth time.Time `json:"date_of_birth" validate:"omitempty"` + PasswordHash string `json:"-" gorm:"not null;size:255"` + IsAdmin bool `json:"is_admin" gorm:"default:false"` + Bookings []Booking `json:"bookings" gorm:"foreignKey:UserID"` +} + +// HashPassword hashes the user's password using bcrypt +func (u *User) HashPassword(password string) error { + if len(password) < 8 { + return errors.New("password must be at least 8 characters long") + } + + hashedBytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) + if err != nil { + return err + } + + u.PasswordHash = string(hashedBytes) + return nil +} + +// CheckPassword verifies if the provided password matches the user's hashed password +func (u *User) CheckPassword(password string) bool { + err := bcrypt.CompareHashAndPassword([]byte(u.PasswordHash), []byte(password)) + return err == nil +} + +// BeforeCreate is a GORM hook that runs before creating a user record +func (u *User) BeforeCreate(tx *gorm.DB) error { + // Ensure email is lowercase for consistency + u.Email = strings.ToLower(u.Email) + return nil +} diff --git a/internal/repositories/interfaces.go b/internal/repositories/interfaces.go new file mode 100644 index 0000000..5b26c57 --- /dev/null +++ b/internal/repositories/interfaces.go @@ -0,0 +1,42 @@ +package repositories + +import ( + "time" + + "attune-heart-therapy/internal/models" +) + +// UserRepository handles user data persistence +type UserRepository interface { + Create(user *models.User) error + GetByID(id uint) (*models.User, error) + GetByEmail(email string) (*models.User, error) + Update(user *models.User) error + GetActiveUsersCount() (int64, error) +} + +// BookingRepository handles booking data persistence +type BookingRepository interface { + Create(booking *models.Booking) error + GetByID(id uint) (*models.Booking, error) + GetByUserID(userID uint) ([]models.Booking, error) + Update(booking *models.Booking) error + Delete(id uint) error + GetUpcomingBookings() ([]models.Booking, error) +} + +// ScheduleRepository handles schedule data persistence +type ScheduleRepository interface { + Create(schedule *models.Schedule) error + GetAvailable(date time.Time) ([]models.Schedule, error) + Update(schedule *models.Schedule) error + GetByID(id uint) (*models.Schedule, error) +} + +// NotificationRepository handles notification data persistence +type NotificationRepository interface { + Create(notification *models.Notification) error + GetByID(id uint) (*models.Notification, error) + Update(notification *models.Notification) error + GetPendingNotifications() ([]models.Notification, error) +} diff --git a/internal/server/server.go b/internal/server/server.go new file mode 100644 index 0000000..e7e0c31 --- /dev/null +++ b/internal/server/server.go @@ -0,0 +1,166 @@ +package server + +import ( + "fmt" + "log" + + "attune-heart-therapy/internal/config" + "attune-heart-therapy/internal/database" + + "github.com/gin-gonic/gin" +) + +type Server struct { + config *config.Config + db *database.DB + router *gin.Engine +} + +func New(cfg *config.Config) *Server { + // Set Gin mode based on environment + gin.SetMode(gin.ReleaseMode) + + router := gin.New() + + // Add basic middleware + router.Use(gin.Logger()) + router.Use(gin.Recovery()) + + return &Server{ + config: cfg, + router: router, + } +} + +// Initialize sets up the database connection and runs migrations +func (s *Server) Initialize() error { + // Initialize database connection + db, err := database.New(s.config) + if err != nil { + return fmt.Errorf("failed to initialize database: %w", err) + } + s.db = db + + // Run database migrations + if err := s.db.Migrate(); err != nil { + return fmt.Errorf("failed to run database migrations: %w", err) + } + + // Seed database with initial data + if err := s.db.Seed(); err != nil { + return fmt.Errorf("failed to seed database: %w", err) + } + + log.Println("Server initialization completed successfully") + return nil +} + +func (s *Server) Start() error { + // Initialize database and run migrations + if err := s.Initialize(); err != nil { + return err + } + + // Setup routes + s.setupRoutes() + + // Start server + addr := fmt.Sprintf("%s:%s", s.config.Server.Host, s.config.Server.Port) + log.Printf("Starting server on %s", addr) + + return s.router.Run(addr) +} + +// Shutdown gracefully shuts down the server +func (s *Server) Shutdown() error { + if s.db != nil { + log.Println("Closing database connection...") + return s.db.Close() + } + return nil +} + +func (s *Server) setupRoutes() { + // Health check endpoint + s.router.GET("/health", s.healthCheck) + + // API v1 routes group + v1 := s.router.Group("/api/v1") + { + // Auth routes (will be implemented in later tasks) + auth := v1.Group("/auth") + { + auth.POST("/register", func(c *gin.Context) { + c.JSON(501, gin.H{"message": "Not implemented yet"}) + }) + auth.POST("/login", func(c *gin.Context) { + c.JSON(501, gin.H{"message": "Not implemented yet"}) + }) + } + + // Booking routes (will be implemented in later tasks) + bookings := v1.Group("/bookings") + { + bookings.GET("/", func(c *gin.Context) { + c.JSON(501, gin.H{"message": "Not implemented yet"}) + }) + bookings.POST("/", func(c *gin.Context) { + c.JSON(501, gin.H{"message": "Not implemented yet"}) + }) + } + + // Schedule routes (will be implemented in later tasks) + schedules := v1.Group("/schedules") + { + schedules.GET("/", func(c *gin.Context) { + c.JSON(501, gin.H{"message": "Not implemented yet"}) + }) + } + + // Payment routes (will be implemented in later tasks) + payments := v1.Group("/payments") + { + payments.POST("/intent", func(c *gin.Context) { + c.JSON(501, gin.H{"message": "Not implemented yet"}) + }) + payments.POST("/confirm", func(c *gin.Context) { + c.JSON(501, gin.H{"message": "Not implemented yet"}) + }) + payments.POST("/webhook", func(c *gin.Context) { + c.JSON(501, gin.H{"message": "Not implemented yet"}) + }) + } + + // Admin routes (will be implemented in later tasks) + admin := v1.Group("/admin") + { + admin.GET("/dashboard", func(c *gin.Context) { + c.JSON(501, gin.H{"message": "Not implemented yet"}) + }) + } + } +} + +// healthCheck handles the health check endpoint +func (s *Server) healthCheck(c *gin.Context) { + response := gin.H{ + "status": "ok", + "message": "Video Conference Booking System API", + } + + // Check database connectivity + if s.db != nil { + if err := s.db.Health(); err != nil { + response["status"] = "error" + response["database"] = "disconnected" + response["error"] = err.Error() + c.JSON(500, response) + return + } + response["database"] = "connected" + } else { + response["database"] = "not initialized" + } + + c.JSON(200, response) +} diff --git a/internal/services/interfaces.go b/internal/services/interfaces.go new file mode 100644 index 0000000..03a3677 --- /dev/null +++ b/internal/services/interfaces.go @@ -0,0 +1,80 @@ +package services + +import ( + "time" + + "attune-heart-therapy/internal/models" + + "github.com/stripe/stripe-go/v76" +) + +// UserService handles user-related operations +type UserService interface { + Register(req RegisterRequest) (*models.User, error) + Login(email, password string) (*models.User, string, error) // returns user and JWT token + GetProfile(userID uint) (*models.User, error) + UpdateProfile(userID uint, req UpdateProfileRequest) (*models.User, error) +} + +// BookingService handles booking operations +type BookingService interface { + GetAvailableSlots(date time.Time) ([]models.Schedule, error) + CreateBooking(userID uint, req BookingRequest) (*models.Booking, error) + GetUserBookings(userID uint) ([]models.Booking, error) + CancelBooking(userID, bookingID uint) error + RescheduleBooking(userID, bookingID uint, newScheduleID uint) error +} + +// PaymentService handles Stripe integration +type PaymentService interface { + CreatePaymentIntent(amount float64, currency string) (*stripe.PaymentIntent, error) + ConfirmPayment(paymentIntentID string) (*stripe.PaymentIntent, error) + HandleWebhook(payload []byte, signature string) error +} + +// NotificationService handles email notifications +type NotificationService interface { + SendWelcomeEmail(user *models.User) error + SendPaymentNotification(user *models.User, booking *models.Booking, success bool) error + SendMeetingInfo(user *models.User, booking *models.Booking) error + SendReminder(user *models.User, booking *models.Booking) error + ScheduleReminder(bookingID uint, reminderTime time.Time) error +} + +// JitsiService handles video conference integration +type JitsiService interface { + CreateMeeting(bookingID uint, scheduledAt time.Time) (*JitsiMeeting, error) + GetMeetingURL(roomID string) string + DeleteMeeting(roomID string) error +} + +// JitsiMeeting represents a Jitsi meeting +type JitsiMeeting struct { + RoomID string `json:"room_id"` + RoomURL string `json:"room_url"` +} + +// Request/Response DTOs +type RegisterRequest struct { + FirstName string `json:"first_name" binding:"required"` + LastName string `json:"last_name" binding:"required"` + Email string `json:"email" binding:"required,email"` + Phone string `json:"phone"` + Location string `json:"location"` + DateOfBirth time.Time `json:"date_of_birth"` + Password string `json:"password" binding:"required,min=6"` +} + +type UpdateProfileRequest struct { + FirstName string `json:"first_name"` + LastName string `json:"last_name"` + Phone string `json:"phone"` + Location string `json:"location"` + DateOfBirth time.Time `json:"date_of_birth"` +} + +type BookingRequest struct { + ScheduleID uint `json:"schedule_id" binding:"required"` + Notes string `json:"notes"` + Amount float64 `json:"amount" binding:"required"` +}