From a918c14534c9296b39336f1a89d0ed56114a69fc Mon Sep 17 00:00:00 2001 From: Jan Klattenhoff Date: Thu, 13 Mar 2025 08:02:02 +0100 Subject: [PATCH] feat(docs): add comprehensive documentation for platform --- API-Documentation.md | 516 ++++++++++++++++++++++++++++ Authentication-and-Authorization.md | 244 +++++++++++++ Backend.md | 187 ++++++++++ Coding-Standards.md | 311 +++++++++++++++++ Development-Environment-Setup.md | 212 ++++++++++++ Frontend.md | 137 ++++++++ Game-Modules.md | 268 +++++++++++++++ Home.md | 83 ++++- Payment-System.md | 263 ++++++++++++++ 9 files changed, 2220 insertions(+), 1 deletion(-) create mode 100644 API-Documentation.md create mode 100644 Authentication-and-Authorization.md create mode 100644 Backend.md create mode 100644 Coding-Standards.md create mode 100644 Development-Environment-Setup.md create mode 100644 Frontend.md create mode 100644 Game-Modules.md create mode 100644 Payment-System.md diff --git a/API-Documentation.md b/API-Documentation.md new file mode 100644 index 0000000..73d99fd --- /dev/null +++ b/API-Documentation.md @@ -0,0 +1,516 @@ +# API Documentation + +This page provides documentation for the Casino Gaming Platform API. + +## Overview + +The Casino Gaming Platform exposes a RESTful API that allows the frontend application to interact with the backend services. The API is secured using JWT tokens provided by Keycloak. + +## Base URL + +- Development: `http://localhost:8080` +- Production: `https://api.casino-gaming-platform.com` + +## Authentication + +All API endpoints (except those explicitly marked as public) require authentication. + +### Authentication Header + +Include the JWT token in the `Authorization` header: + +``` +Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA... +``` + +### Obtaining Tokens + +Tokens are obtained through the Keycloak authentication flow. For testing purposes, you can obtain a token using: + +``` +POST /auth/realms/lf12-realm/protocol/openid-connect/token +Content-Type: application/x-www-form-urlencoded + +grant_type=password&client_id=casino-frontend&username=testuser&password=testpassword +``` + +## Error Handling + +The API uses standard HTTP status codes to indicate success or failure: + +- `200 OK`: Successful request +- `201 Created`: Resource created successfully +- `400 Bad Request`: Invalid request parameters +- `401 Unauthorized`: Authentication required +- `403 Forbidden`: Insufficient permissions +- `404 Not Found`: Resource not found +- `500 Internal Server Error`: Server error + +Error responses follow this structure: + +```json +{ + "timestamp": "2023-07-21T15:45:30.123Z", + "status": 400, + "error": "Bad Request", + "message": "Invalid amount", + "path": "/api/deposits/create-session" +} +``` + +## Rate Limiting + +API requests are rate-limited to prevent abuse: + +- Standard users: 100 requests per minute +- VIP users: 300 requests per minute + +Rate limit headers are included in responses: + +``` +X-RateLimit-Limit: 100 +X-RateLimit-Remaining: 95 +X-RateLimit-Reset: 1630000000 +``` + +## API Endpoints + +### Health Check + +#### Get API Health Status + +``` +GET /api/health +``` + +Public endpoint that returns the status of the API. + +**Response:** + +```json +{ + "status": "UP", + "components": { + "db": { + "status": "UP" + }, + "keycloak": { + "status": "UP" + } + } +} +``` + +### User Endpoints + +#### Get Current User + +``` +GET /api/users/me +``` + +Returns the profile of the currently authenticated user. + +**Response:** + +```json +{ + "id": "550e8400-e29b-41d4-a716-446655440000", + "username": "player1", + "email": "player1@example.com", + "balance": 15000, + "createdAt": "2023-01-15T10:30:45Z", + "roles": ["user"], + "preferences": { + "theme": "dark", + "notifications": true + } +} +``` + +#### Get User by ID + +``` +GET /api/users/{id} +``` + +Returns a user by their ID. Requires admin role. + +**Parameters:** + +- `id`: User ID (UUID) + +**Response:** + +```json +{ + "id": "550e8400-e29b-41d4-a716-446655440000", + "username": "player1", + "email": "player1@example.com", + "balance": 15000, + "createdAt": "2023-01-15T10:30:45Z", + "roles": ["user"], + "preferences": { + "theme": "dark", + "notifications": true + } +} +``` + +#### Create User + +``` +POST /api/users +``` + +Creates a new user account. Usually called during registration process. + +**Request Body:** + +```json +{ + "username": "newplayer", + "email": "newplayer@example.com", + "password": "SecurePassword123" +} +``` + +**Response:** + +```json +{ + "id": "550e8400-e29b-41d4-a716-446655440001", + "username": "newplayer", + "email": "newplayer@example.com", + "balance": 1000, + "createdAt": "2023-07-21T15:45:30Z", + "roles": ["user"] +} +``` + +#### Update User Preferences + +``` +PUT /api/users/{id}/preferences +``` + +Updates a user's preferences. + +**Parameters:** + +- `id`: User ID (UUID) + +**Request Body:** + +```json +{ + "theme": "light", + "notifications": false +} +``` + +**Response:** + +```json +{ + "theme": "light", + "notifications": false +} +``` + +### Deposit Endpoints + +#### Create Payment Session + +``` +POST /api/deposits/create-session +``` + +Creates a new Stripe payment session for depositing funds. + +**Request Body:** + +```json +{ + "amount": 1000 +} +``` + +**Response:** + +```json +{ + "sessionId": "cs_test_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0", + "url": "https://checkout.stripe.com/pay/cs_test_a1b2c3d4..." +} +``` + +#### Verify Payment + +``` +POST /api/deposits/verify +``` + +Verifies a completed payment session. Usually called after successful redirect from Stripe. + +**Request Body:** + +```json +{ + "sessionId": "cs_test_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0" +} +``` + +**Response:** + +```json +{ + "verified": true, + "amount": 1000, + "newBalance": 16000 +} +``` + +### Transaction Endpoints + +#### Get User Transactions + +``` +GET /api/transactions?userId={userId}&type={type}&page={page}&size={size} +``` + +Retrieves a user's transaction history. + +**Parameters:** + +- `userId`: User ID (UUID) +- `type`: (Optional) Transaction type (DEPOSIT, BET, WIN, BONUS, REFUND) +- `page`: (Optional) Page number, defaults to 0 +- `size`: (Optional) Page size, defaults to 20 + +**Response:** + +```json +{ + "content": [ + { + "id": "f47ac10b-58cc-4372-a567-0e02b2c3d479", + "userId": "550e8400-e29b-41d4-a716-446655440000", + "type": "DEPOSIT", + "amount": 1000, + "previousBalance": 15000, + "newBalance": 16000, + "timestamp": "2023-07-21T15:45:30Z", + "referenceId": "cs_test_a1b2c3d4...", + "status": "COMPLETED" + }, + { + "id": "f47ac10b-58cc-4372-a567-0e02b2c3d480", + "userId": "550e8400-e29b-41d4-a716-446655440000", + "type": "BET", + "amount": -500, + "previousBalance": 16000, + "newBalance": 15500, + "timestamp": "2023-07-21T15:48:12Z", + "referenceId": "BLACKJACK_1234", + "status": "COMPLETED" + } + ], + "pageable": { + "pageNumber": 0, + "pageSize": 20, + "totalElements": 143, + "totalPages": 8 + } +} +``` + +### Game Endpoints + +#### Get Available Games + +``` +GET /api/games +``` + +Retrieves the list of available games. + +**Response:** + +```json +[ + { + "id": "poker", + "name": "Poker", + "image": "/public/poker.webp", + "description": "Texas Hold'em Poker against AI opponents", + "minBet": 100, + "maxBet": 10000, + "available": true + }, + { + "id": "blackjack", + "name": "Blackjack", + "image": "/public/blackjack.webp", + "description": "Classic casino card game, aim for 21", + "minBet": 50, + "maxBet": 5000, + "available": true + } +] +``` + +#### Get Game Details + +``` +GET /api/games/{id} +``` + +Retrieves detailed information about a specific game. + +**Parameters:** + +- `id`: Game ID + +**Response:** + +```json +{ + "id": "poker", + "name": "Poker", + "image": "/public/poker.webp", + "description": "Texas Hold'em Poker against AI opponents", + "rules": "Standard Texas Hold'em rules apply. Each player...", + "minBet": 100, + "maxBet": 10000, + "available": true, + "variants": ["texas-holdem", "five-card-draw"], + "features": ["ai-opponents", "tournament-mode"], + "stats": { + "playCount": 15432, + "averageBet": 350, + "biggestWin": 25000 + } +} +``` + +#### Start Game Session + +``` +POST /api/games/{id}/sessions +``` + +Starts a new game session. + +**Parameters:** + +- `id`: Game ID + +**Request Body:** + +```json +{ + "betAmount": 200, + "variant": "texas-holdem" +} +``` + +**Response:** + +```json +{ + "sessionId": "g47ac10b-58cc-4372-a567-0e02b2c3d479", + "gameId": "poker", + "variant": "texas-holdem", + "initialBet": 200, + "timestamp": "2023-07-21T15:48:12Z", + "initialState": { + "deck": "encrypted_deck_state", + "players": 4, + "position": 2 + } +} +``` + +### Admin Endpoints + +#### System Status + +``` +GET /api/admin/system/status +``` + +Returns system status information. Requires admin role. + +**Response:** + +```json +{ + "activeSessions": 143, + "registeredUsers": 2567, + "activeGames": { + "poker": 45, + "blackjack": 67, + "slots": 31 + }, + "systemLoad": 0.42, + "databaseSize": "1.3 GB", + "uptime": "27d 14h 12m" +} +``` + +## Webhooks + +### Stripe Payment Webhook + +``` +POST /api/webhooks/stripe +``` + +Webhook endpoint for Stripe payment notifications. This endpoint is called by Stripe when payment events occur. + +**Request Body:** + +Stripe event object. See [Stripe API documentation](https://stripe.com/docs/api/events/object) for details. + +**Response:** + +```json +{ + "received": true +} +``` + +## API Versioning + +The API version is specified in the URL: + +``` +/api/v1/users +``` + +Currently, only `v1` is supported. + +## Cross-Origin Resource Sharing (CORS) + +The API supports CORS for the following origins: + +- `http://localhost:4200` (development) +- `https://casino-gaming-platform.com` (production) + +## API Clients + +### REST Clients + +Sample HTTP requests for testing are available in the repository: + +- `requests/getBearerToken.http` - Obtaining auth token +- `requests/healthCheck.http` - Health check endpoint +- `requests/user.http` - User-related endpoints + +### Swagger UI + +A Swagger UI is available for interactive API exploration: + +- Development: `http://localhost:8080/swagger` +- Production: `https://api.casino-gaming-platform.com/swagger` \ No newline at end of file diff --git a/Authentication-and-Authorization.md b/Authentication-and-Authorization.md new file mode 100644 index 0000000..90fb2ea --- /dev/null +++ b/Authentication-and-Authorization.md @@ -0,0 +1,244 @@ +# Authentication and Authorization + +This page documents the authentication and authorization system of the Casino Gaming Platform. + +## Overview + +The Casino Gaming Platform uses Keycloak as its identity and access management solution. This provides: + +- Secure user authentication +- Single sign-on (SSO) capability +- User profile management +- Role-based access control +- Token-based authorization + +## Architecture + +``` +┌────────────────┐ ┌────────────────┐ ┌────────────────┐ +│ │ │ │ │ │ +│ Frontend │◄──────► Keycloak │◄──────► Backend │ +│ (Angular) │ │ │ │ (Spring Boot) │ +│ │ │ │ │ │ +└────────────────┘ └────────────────┘ └────────────────┘ + ▲ │ + │ │ + └──────────────────────────────────────────────────┘ + (API calls with JWT token) +``` + +## Keycloak Configuration + +### Realm Setup + +The platform uses a dedicated Keycloak realm named `lf12-realm`: + +- **Client ID**: `casino-frontend` +- **Access Type**: Public +- **Valid Redirect URIs**: + - `http://localhost:4200/*` + - `http://casino.example.com/*` (for production) +- **Web Origins**: `+` (allows all origins from Valid Redirect URIs) + +### User Roles + +The following user roles are defined: + +- **user**: Basic authenticated user +- **admin**: Administrative user with management capabilities +- **vip**: Users with premium access (higher limits, special games) + +### Token Configuration + +- **Access Token Lifespan**: 5 minutes +- **Refresh Token Lifespan**: 30 days +- **ID Token Lifespan**: 1 hour + +## Authentication Flow + +### Frontend Authentication + +1. **Login Initiation**: + - User clicks "Login" button on the frontend + - Application redirects to Keycloak login page + +2. **Keycloak Authentication**: + - User enters credentials on Keycloak login page + - Keycloak authenticates the user + - Keycloak redirects back to the application with authorization code + +3. **Token Exchange**: + - Frontend exchanges authorization code for tokens + - Frontend stores tokens in secure storage + - User is redirected to the home page + +4. **Auto-login with Silent Check-SSO**: + - Application uses silent-check-sso.html for quiet refresh + - If user has an active Keycloak session, they're automatically logged in + +### Backend Authentication + +1. **Token Validation**: + - Frontend includes the JWT token in Authorization header + - Backend validates the token signature using Keycloak's public key + - Backend extracts user information and roles from the token + +2. **Token Refresh**: + - When access token expires, frontend uses refresh token to get a new one + - If refresh token is invalid, user is redirected to login + +## Authorization + +### Frontend Authorization + +The Angular application uses route guards to protect routes: + +```typescript +// auth.guard.ts +@Injectable({ + providedIn: 'root' +}) +export class AuthGuard { + constructor(private router: Router) {} + + canActivate(): boolean { + if (!this.isAuthenticated()) { + this.router.navigate(['/landing']); + return false; + } + return true; + } + + isAuthenticated(): boolean { + // Check for valid token + } +} +``` + +Protected routes are configured in the routing module: + +```typescript +const routes: Routes = [ + { path: '', component: LandingComponent }, + { path: 'home', component: HomeComponent, canActivate: [AuthGuard] }, + { path: 'deposit', component: DepositComponent, canActivate: [AuthGuard] } +]; +``` + +### Backend Authorization + +The Spring Boot backend uses Spring Security with Keycloak adapter: + +```java +@Configuration +@EnableWebSecurity +public class KeycloakSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .authorizeRequests() + .antMatchers("/api/health").permitAll() + .antMatchers("/api/users/**").hasRole("user") + .antMatchers("/api/admin/**").hasRole("admin") + .anyRequest().authenticated() + .and() + .oauth2ResourceServer().jwt(); + } +} +``` + +## User Registration + +Users can register in two ways: + +1. **Self-registration through frontend**: + - User clicks "Register" on frontend + - User completes registration form + - Account is created in Keycloak + - User profile is created in application database + +2. **Admin-created accounts**: + - Admins can create users through Keycloak Admin Console + - Backend syncs new users from Keycloak to application database + +## Security Considerations + +### Token Storage + +- Access and refresh tokens are stored in browser's Local Storage +- ID token contains user profile information +- No sensitive information is stored in tokens + +### CSRF Protection + +- Angular includes anti-CSRF token with requests +- Spring Security validates CSRF tokens on state-changing operations + +### Session Management + +- JWT token-based authentication is stateless +- Keycloak manages session state +- Session timeout can be configured in Keycloak + +## Testing Authentication + +### Obtaining a Test Token + +For API testing, obtain a bearer token: + +1. Open `requests/getBearerToken.http` +2. Click the green arrow next to the request +3. Copy the `access_token` from the response + +### Using Swagger with Authentication + +1. Open Swagger UI at http://localhost:8080/swagger +2. Click "Authorize" button +3. Enter the bearer token +4. Test API endpoints with authentication + +## Logout Flow + +1. **Frontend Logout**: + - User clicks "Logout" button + - Frontend clears local tokens + - Frontend redirects to Keycloak logout endpoint + +2. **Keycloak Logout**: + - Keycloak invalidates the session + - Keycloak redirects back to application + +3. **Backend Logout Handling**: + - `KeycloakLogoutHandler` processes logout events + - Any necessary cleanup is performed + +## Troubleshooting + +### Common Issues + +1. **"Invalid token" errors**: + - Check token expiration + - Verify Keycloak is running + - Check time synchronization between services + +2. **"Insufficient permissions" errors**: + - Verify user has required roles + - Check role mapping in Keycloak + +3. **"Invalid redirect URI" errors**: + - Ensure redirect URI is configured in Keycloak client + +### Debugging Tips + +1. **Examine token contents**: + - Use [jwt.io](https://jwt.io) to decode tokens + - Check audience, issuer, and claims + +2. **Check Keycloak logs**: + - Use `docker-compose logs keycloak_lf12` + - Look for authentication errors + +3. **Check browser console**: + - Look for authentication errors in browser console + - Check network tab for failed token requests \ No newline at end of file diff --git a/Backend.md b/Backend.md new file mode 100644 index 0000000..f9a42bb --- /dev/null +++ b/Backend.md @@ -0,0 +1,187 @@ +# Backend Architecture + +This page documents the backend architecture of the Casino Gaming Platform. + +## Tech Stack + +- **Framework**: Spring Boot (Java) +- **Database**: PostgreSQL +- **Authentication**: Keycloak integration +- **Build Tool**: Gradle +- **API Documentation**: OpenAPI/Swagger +- **Payment Processing**: Stripe API + +## Project Structure + +The backend follows a domain-driven design approach with the following structure: + +``` +src/ +├── main/ +│ ├── java/ +│ │ └── de/ +│ │ └── szut/ +│ │ └── casino/ +│ │ ├── CasinoApplication.java +│ │ ├── config/ +│ │ │ └── OpenAPIConfiguration.java +│ │ ├── deposit/ +│ │ │ ├── DepositController.java +│ │ │ └── dto/ +│ │ │ ├── AmountDto.java +│ │ │ └── SessionIdDto.java +│ │ ├── exceptionHandling/ +│ │ │ ├── ErrorDetails.java +│ │ │ ├── GlobalExceptionHandler.java +│ │ │ └── ResourceNotFoundException.java +│ │ ├── health/ +│ │ │ └── HealthController.java +│ │ ├── security/ +│ │ │ ├── KeycloakLogoutHandler.java +│ │ │ └── KeycloakSecurityConfig.java +│ │ └── user/ +│ │ ├── UserController.java +│ │ ├── UserEntity.java +│ │ ├── UserMappingService.java +│ │ ├── UserRepository.java +│ │ ├── UserService.java +│ │ └── dto/ +│ │ ├── CreateUserDto.java +│ │ ├── GetUserDto.java +│ │ └── KeycloakUserDto.java +│ └── resources/ +│ └── application.properties +└── test/ + └── java/ + └── de/ + └── szut/ + └── casino/ + ├── Lf8StarterApplicationTests.java + ├── health/ + │ └── HealthControllerTest.java + └── user/ + └── UserControllerTest.java +``` + +## Key Modules + +### User Management + +The user module handles: +- User registration and profile management +- Balance tracking +- User data retrieval and updates + +Key components: +- `UserController`: REST endpoints for user operations +- `UserService`: Business logic for user operations +- `UserRepository`: Data access layer +- `UserEntity`: Database entity for user data + +### Deposit System + +The deposit module manages virtual currency deposits: +- Integration with Stripe for payment processing +- Creation of payment sessions +- Verification of successful payments +- Updating user balances + +Key components: +- `DepositController`: REST endpoints for deposit operations +- `AmountDto`: Data transfer object for deposit amounts +- `SessionIdDto`: Data transfer object for Stripe session IDs + +### Security + +The security module handles authentication and authorization: +- Integration with Keycloak for identity management +- JWT token validation +- Role-based access control +- Logout handling + +Key components: +- `KeycloakSecurityConfig`: Configuration for Keycloak integration +- `KeycloakLogoutHandler`: Handles user logout flow + +### Exception Handling + +Global exception handling for consistent error responses: +- `GlobalExceptionHandler`: Central exception handler +- `ErrorDetails`: Standardized error response format +- `ResourceNotFoundException`: Custom exception for missing resources + +## API Endpoints + +The backend exposes the following main API endpoints: + +### User API + +- `GET /api/users/{id}`: Get user by ID +- `POST /api/users`: Create a new user +- `PUT /api/users/{id}`: Update user information +- `GET /api/users/me`: Get the current authenticated user + +### Deposit API + +- `POST /api/deposits/create-session`: Create a Stripe payment session +- `POST /api/deposits/verify`: Verify a completed payment + +### Health API + +- `GET /api/health`: Health check endpoint + +## Authentication Flow + +1. User authenticates through the frontend application +2. Frontend receives JWT tokens from Keycloak +3. Backend validates tokens for API requests +4. User info is extracted from validated tokens +5. Authorization is enforced based on token roles + +## Database Schema + +### User Table + +| Column | Type | Description | +|-------------|-------------|-----------------------------------| +| id | UUID | Primary key | +| username | VARCHAR | User's username | +| email | VARCHAR | User's email address | +| balance | DECIMAL | User's virtual currency balance | +| created_at | TIMESTAMP | Account creation timestamp | +| updated_at | TIMESTAMP | Last update timestamp | + +## Development Workflow + +1. Start the backend with: + ```bash + ./gradlew bootRun + ``` + +2. The API will be available at: http://localhost:8080 +3. Swagger documentation: http://localhost:8080/swagger + +## Code Style Guidelines + +- Use PascalCase for classes with descriptive suffixes (Controller, Service, Entity) +- Use camelCase for methods and variables +- Follow domain-driven package organization +- Prefix DTOs with domain and suffix with "Dto" +- Use Spring's global exception handling with custom exceptions + +## Testing + +The backend includes: +- Unit tests for service and controller layers +- Integration tests for API endpoints +- Mock tests using Mockito + +Run tests with: +```bash +./gradlew test +``` + +Check code style with: +```bash +./gradlew checkstyleMain checkstyleTest +``` \ No newline at end of file diff --git a/Coding-Standards.md b/Coding-Standards.md new file mode 100644 index 0000000..c0523c8 --- /dev/null +++ b/Coding-Standards.md @@ -0,0 +1,311 @@ +# Coding Standards + +This page outlines the coding standards and style guidelines for the Casino Gaming Platform. + +## General Principles + +- **Readability**: Code should be easy to read and understand +- **Maintainability**: Code should be easy to maintain and extend +- **Consistency**: Coding style should be consistent across the codebase +- **Testability**: Code should be designed with testing in mind +- **Documentation**: Code should be well-documented + +## Version Control + +### Git Workflow + +We follow a feature branch workflow: + +1. Create a feature branch from `main` +2. Make changes and commit to the feature branch +3. Create a pull request to merge back into `main` +4. Ensure CI passes and the code is reviewed +5. Merge the pull request + +### Commit Messages + +We use semantic commit messages: + +Format: `(): ` + +Where `` is one of: +- `feat`: New feature +- `fix`: Bug fix +- `docs`: Documentation changes +- `style`: Formatting, missing semicolons, etc; no code change +- `refactor`: Code refactoring +- `test`: Adding or refactoring tests +- `chore`: Updating build tasks, etc; no production code change + +Examples: +``` +feat: add user balance display +fix(auth): resolve token expiration issue +docs: update API documentation +``` + +## Frontend (Angular) + +### Code Organization + +#### Directory Structure + +``` +src/ +├── app/ +│ ├── feature/ # Feature modules +│ │ ├── home/ # Home feature +│ │ ├── deposit/ # Deposit feature +│ │ └── ... +│ ├── shared/ # Shared components/services +│ │ ├── components/ # Reusable components +│ │ ├── services/ # Shared services +│ │ └── ... +│ ├── model/ # Data models/interfaces +│ └── service/ # Application services +├── assets/ # Static assets +└── environments/ # Environment configurations +``` + +#### Naming Conventions + +- **Files**: kebab-case + - Components: `user-profile.component.ts` + - Services: `auth.service.ts` + - Models: `user.model.ts` + +- **Classes**: PascalCase with suffixes + - Components: `UserProfileComponent` + - Services: `AuthService` + - Guards: `AuthGuard` + - Directives: `HighlightDirective` + - Pipes: `FormatDatePipe` + +- **Component Selectors**: kebab-case with prefix + - `app-user-profile` + - `app-navbar` + +- **Interfaces and Models**: PascalCase + - `User` + - `GameSession` + +- **Enums**: PascalCase + - `TransactionType` + - `GameStatus` + +- **Constants**: UPPER_SNAKE_CASE + - `MAX_SESSION_TIME` + - `API_ENDPOINTS` + +### Coding Style + +- Use TypeScript's strict mode +- Use typed variables and function returns +- Prefer arrow functions for callbacks +- Use async/await for asynchronous operations +- Use template strings for string interpolation +- Use destructuring for object and array access +- Use the spread operator for shallow copies + +### Component Best Practices + +- One component per file +- Keep components small and focused +- Use OnPush change detection strategy where appropriate +- Use input and output bindings for component communication +- Use services for cross-component communication +- Implement lifecycle hooks explicitly +- Document component inputs and outputs + +### Service Best Practices + +- Use the singleton pattern for services +- Use dependency injection to provide services +- Keep services focused on a single responsibility +- Use RxJS for handling asynchronous operations +- Document service methods and parameters + +### RxJS Usage + +- Use appropriate operators (map, filter, switchMap, etc.) +- Complete observables to prevent memory leaks +- Use the async pipe in templates +- Handle errors with catchError +- Use shareReplay for sharing observable results + +### Angular Template Guidelines + +- Use structural directives (*ngIf, *ngFor) sparingly +- Prefer ngContainer for structural directives +- Limit template complexity +- Use trackBy with *ngFor for performance +- Avoid logic in templates +- Use pipes for data transformation + +### CSS/SCSS Guidelines + +- Use TailwindCSS utility classes +- Create custom utility classes with @apply directive +- Use scoped component styles +- Follow mobile-first responsive design +- Use CSS variables for theming + +## Backend (Java/Spring Boot) + +### Code Organization + +#### Package Structure + +``` +de.szut.casino/ +├── config/ # Configuration classes +├── user/ # User module +│ ├── UserController.java +│ ├── UserService.java +│ ├── UserRepository.java +│ ├── UserEntity.java +│ └── dto/ # Data Transfer Objects +│ ├── CreateUserDto.java +│ └── GetUserDto.java +├── deposit/ # Deposit module +├── game/ # Game module +├── security/ # Security configuration +└── exceptionHandling/ # Exception handling +``` + +#### Naming Conventions + +- **Classes**: PascalCase with suffixes + - Controllers: `UserController` + - Services: `UserService` + - Repositories: `UserRepository` + - Entities: `UserEntity` + - DTOs: `CreateUserDto`, `GetUserDto` + - Exceptions: `ResourceNotFoundException` + +- **Methods**: camelCase + - Controller methods: `getUser()`, `createUser()` + - Service methods: `findUserById()`, `updateUserBalance()` + - Repository methods: follow Spring Data naming conventions + +- **Variables**: camelCase + - Entity fields: `firstName`, `createdAt` + - Method parameters: `userId`, `requestBody` + - Local variables: `userEntity`, `validationResult` + +- **Constants**: UPPER_SNAKE_CASE + - `DEFAULT_PAGE_SIZE` + - `JWT_EXPIRATION_TIME` + +### Java Coding Style + +- Follow standard Java conventions +- Use Java 17 features where appropriate +- Use consistent indentation (4 spaces) +- Limit line length to 120 characters +- Order class members logically +- Document public APIs with Javadoc + +### Spring Best Practices + +- Use constructor injection instead of field injection +- Use Spring Data repositories for database access +- Use Spring Security for authentication/authorization +- Use DTO pattern for API requests/responses +- Use exception handling for error responses +- Use validation annotations for input validation + +### API Design Guidelines + +- Follow RESTful conventions +- Use appropriate HTTP methods (GET, POST, PUT, DELETE) +- Use consistent URL patterns +- Use proper HTTP status codes +- Provide meaningful error messages +- Document API with OpenAPI/Swagger +- Version the API + +### Database Access + +- Use JPA for database access +- Define explicit column names and types +- Use appropriate indexes +- Define relationship mappings explicitly +- Use transactions for data consistency +- Consider performance implications of queries + +### Testing Guidelines + +- Write unit tests for services and controllers +- Use MockMvc for controller tests +- Use Mockito for mocking dependencies +- Use JUnit 5 for tests +- Test happy path and error cases +- Use test data builders for test data + +## Documentation + +### Code Documentation + +- Document public methods with JavaDoc or TSDoc +- Document complex logic with inline comments +- Document non-obvious behavior +- Keep documentation up-to-date with code changes + +### API Documentation + +- Use OpenAPI/Swagger for API documentation +- Document request and response formats +- Document error responses +- Document authentication requirements +- Document rate limiting + +### Wiki Documentation + +- Document architecture and design decisions +- Document deployment and setup procedures +- Document troubleshooting steps +- Keep wiki up-to-date with code changes + +## Security Practices + +- Never commit secrets or credentials +- Use environment variables for configuration +- Validate all user input +- Use prepared statements for database queries +- Use HTTPS for all communication +- Follow OWASP security guidelines +- Implement proper error handling +- Use proper access controls + +## Performance Considerations + +- Use caching where appropriate +- Optimize database queries +- Use pagination for large result sets +- Optimize frontend rendering +- Minimize HTTP requests +- Use appropriate data structures and algorithms +- Consider scalability in design decisions + +## Accessibility + +- Follow WCAG 2.1 AA guidelines +- Use semantic HTML +- Provide alternative text for images +- Ensure keyboard navigation works +- Test with screen readers +- Consider color contrast +- Support text scaling + +## Cross-Browser Compatibility + +- Support latest versions of Chrome, Firefox, Safari, and Edge +- Test on different browsers +- Use feature detection instead of browser detection +- Consider mobile browsers +- Use polyfills for older browsers + +## Conclusion + +Adherence to these coding standards helps maintain a consistent, high-quality codebase. These standards are guidelines rather than strict rules, and there may be valid reasons to deviate from them in certain situations. Use your best judgment and discuss with the team when in doubt. \ No newline at end of file diff --git a/Development-Environment-Setup.md b/Development-Environment-Setup.md new file mode 100644 index 0000000..2947f94 --- /dev/null +++ b/Development-Environment-Setup.md @@ -0,0 +1,212 @@ +# Development Environment Setup + +This guide will help you set up your development environment for the Casino Gaming Platform. + +## Prerequisites + +Before you begin, make sure you have the following tools installed: + +1. **Docker & Docker Compose** + - [Docker installation guide](https://docs.docker.com/get-docker/) + - Docker Compose is included with Docker Desktop for Windows and Mac + +2. **Java Development Kit (JDK) 17+** + - [AdoptOpenJDK](https://adoptopenjdk.net/) or [Oracle JDK](https://www.oracle.com/java/technologies/javase-downloads.html) + - Verify installation with: `java -version` + +3. **Node.js 18+** + - [Node.js download](https://nodejs.org/en/download/) + - Verify installation with: `node --version` + +4. **Bun** (Alternative to npm for faster package management) + - [Bun installation](https://bun.sh/docs/installation) + - Verify installation with: `bun --version` + +5. **IDE/Code Editor** + - Backend: [IntelliJ IDEA](https://www.jetbrains.com/idea/) (recommended) or [Eclipse](https://www.eclipse.org/downloads/) + - Frontend: [Visual Studio Code](https://code.visualstudio.com/) (recommended) + +## Setting Up the Backend + +1. **Clone the repository** + ```bash + git clone + cd casino + ``` + +2. **Import the project into your IDE** + - For IntelliJ IDEA: + - Go to File > Open + - Navigate to the `backend` directory and click Open + - Wait for the Gradle import to complete + +3. **Configure IntelliJ Database View** (Optional) + - Start Docker services (see Infrastructure Setup below) + - Open `application.properties` in the resources folder + - Copy the database URL + - Open the Database tab in IntelliJ + - Click on the database icon with key in the Database toolbar + - Click the plus sign and select "Datasource from URL" + - Paste the DB URL and select PostgreSQL driver + - Enter username `postgres_user` and password `postgres_pass` + - In the Schemas tab, uncheck all options and only check `postgresdb` and `public` + +## Setting Up the Frontend + +1. **Navigate to the frontend directory** + ```bash + cd frontend + ``` + +2. **Install dependencies** + ```bash + bun install + ``` + or + ```bash + npm install + ``` + +3. **Configure your IDE/Editor** (for VS Code) + - Install recommended extensions: + - Angular Language Service + - ESLint + - Prettier + - Tailwind CSS IntelliSense + +4. **Import project settings** + - VS Code workspace settings are included in the repository + +## Setting Up Infrastructure + +1. **Start Docker services** + ```bash + cd docker + docker-compose up -d + ``` + + This will start: + - PostgreSQL database (port 5432) + - PostgreSQL for Keycloak (port 9433) + - Keycloak authentication server (port 9090) + +2. **Verify services are running** + ```bash + docker-compose ps + ``` + + All services should show as "running" + +3. **Access Keycloak Admin Console** + - Open http://localhost:9090 in your browser + - Login with username `admin` and password `admin` + - Verify the `lf12-realm` is imported + +## Configuring IDE for Java Development + +### IntelliJ IDEA Setup + +1. **Install Checkstyle Plugin** + - Go to Settings > Plugins + - Search for "Checkstyle-IDEA" + - Install and restart IntelliJ + +2. **Configure Checkstyle** + - Go to Settings > Tools > Checkstyle + - Set Checkstyle version to 8.42 + - Add a new configuration file + - Select the `checkstyle.xml` from the `config/checkstyle` directory + - Name it "Casino Checkstyle" + - Set it as active + +3. **Configure Code Style** + - Go to Settings > Editor > Code Style + - Import scheme from `config/codestyles/Casino.xml` (if available) + +## Running the Components + +### Backend + +1. **From the IDE** + - Find the `CasinoApplication.java` file + - Right-click and select "Run CasinoApplication" + +2. **From the command line** + ```bash + cd backend + ./gradlew bootRun + ``` + +3. **Verify the backend is running** + - Open http://localhost:8080/swagger in your browser + - You should see the Swagger UI with available API endpoints + +### Frontend + +1. **Start the development server** + ```bash + cd frontend + bun run start + ``` + or + ```bash + bunx @angular/cli serve --proxy-config src/proxy.conf.json + ``` + +2. **Verify the frontend is running** + - Open http://localhost:4200 in your browser + - You should see the landing page of the Casino Gaming Platform + +## Troubleshooting + +### PostgreSQL Issues + +If you encounter PostgreSQL connection issues: + +1. **Reset the database** + ```bash + cd docker + docker-compose down + docker volume rm casino_postgres_data + docker-compose up -d + ``` + +### Keycloak Issues + +If you have problems with Keycloak: + +1. **Reset Keycloak** + ```bash + cd docker + docker-compose down + docker volume rm casino_keycloak_data + docker-compose up -d + ``` + +2. **Manual Realm Import** + - Open http://localhost:9090/admin + - Create a new realm named "lf12-realm" + - Import the realm configuration from `docker/imports/lf12-realm.json` + +### Frontend Build Issues + +If you encounter build or dependency issues: + +1. **Clear node_modules and reinstall** + ```bash + cd frontend + rm -rf node_modules + bun install + ``` + +2. **Clear Angular cache** + ```bash + rm -rf .angular + ``` + +## Getting Help + +If you encounter any issues not covered in this guide: +1. Check the project's GitHub Issues +2. Consult the documentation +3. Reach out to the development team \ No newline at end of file diff --git a/Frontend.md b/Frontend.md new file mode 100644 index 0000000..83d17b2 --- /dev/null +++ b/Frontend.md @@ -0,0 +1,137 @@ +# Frontend Architecture + +This page documents the frontend architecture of the Casino Gaming Platform. + +## Tech Stack + +- **Framework**: Angular 18 +- **CSS Framework**: TailwindCSS +- **State Management**: NgRx Store (for complex state) and Angular Services (for simpler state) +- **Authentication**: Keycloak integration +- **Payment Processing**: Stripe API + +## Project Structure + +The frontend application follows a feature-based structure: + +``` +src/ +├── app/ +│ ├── app.component.* +│ ├── app.config.ts +│ ├── app.routes.ts +│ ├── auth.guard.ts +│ ├── feature/ +│ │ ├── deposit/ +│ │ ├── home/ +│ │ ├── landing/ +│ │ └── login-success/ +│ ├── model/ +│ │ ├── Game.ts +│ │ ├── Transaction.ts +│ │ └── User.ts +│ ├── service/ +│ │ ├── deposit.service.ts +│ │ └── user.service.ts +│ └── shared/ +│ ├── components/ +│ │ ├── confirmation/ +│ │ ├── footer/ +│ │ └── navbar/ +│ └── services/ +│ └── modal-animation.service.ts +├── environments/ +└── assets/ +``` + +## Key Modules + +### Feature Modules + +- **Home**: Main dashboard showing available games and user balance +- **Deposit**: Handles virtual currency deposits via Stripe +- **Landing**: Public landing page for non-authenticated users +- **Login Success**: Handles successful authentication from Keycloak + +### Core Services + +- **User Service**: Manages user data and authentication state +- **Deposit Service**: Handles virtual currency deposit operations +- **Modal Animation Service**: Provides consistent animations for modals + +## Design System + +The application follows a consistent design system: + +### Color Palette + +#### Primary Colors +- Deep Blue: `#0a1219` (background) +- Deep Blue Light: `#121e27` (secondary background) +- Deep Blue Contrast: `#1a2835` (cards, elements) + +#### Accent Colors +- Emerald: `#10b981` (primary buttons) +- Emerald Dark: `#059669` (button hover) +- Emerald Light: `#34d399` (highlights) + +#### Text Colors +- Primary Text: `#ffffff` (white) +- Secondary Text: `#94a3b8` (light gray) +- Tertiary Text: `#64748b` (darker gray) + +### Component Library + +The application uses a consistent set of UI components: + +- **Cards**: Used for game displays and information containers +- **Buttons**: Primary (emerald) and secondary (deep blue) actions +- **Navigation**: Responsive navbar with mobile optimization +- **Forms**: Consistently styled input fields, dropdowns, and validation +- **Modals**: Used for confirmations, settings, and game launches + +## Authentication Flow + +1. User clicks "Login" in the application +2. User is redirected to Keycloak login page +3. After successful authentication, user is redirected to the login-success component +4. The application exchanges the auth code for tokens +5. User is redirected to the home page with active session + +## Best Practices + +### Component Organization + +- Each feature is organized in its own directory +- Components follow the Angular best practices for naming and structure +- Shared components are placed in the shared module for reuse + +### Style Guidelines + +- Use PascalCase for class names with suffixes (Component, Service) +- Use kebab-case for component selectors with "app-" prefix +- File naming follows Angular conventions: `name.component.ts`, `name.service.ts` +- Import order: Angular → third-party → local +- Use RxJS catchError for HTTP error handling + +### Performance Considerations + +- Lazy loading of feature modules +- OnPush change detection strategy for performance-critical components +- Efficient state management with NgRx or RxJS Subjects +- Image optimization for game assets + +## Development Workflow + +1. Start the development server with proxy configuration + ```bash + bun run start + ``` + or + ```bash + bunx @angular/cli serve --proxy-config src/proxy.conf.json + ``` + +2. The application will be available at http://localhost:4200 + +3. API calls are proxied to the backend service running on http://localhost:8080 \ No newline at end of file diff --git a/Game-Modules.md b/Game-Modules.md new file mode 100644 index 0000000..210b6a7 --- /dev/null +++ b/Game-Modules.md @@ -0,0 +1,268 @@ +# Game Modules + +This page documents the game modules available in the Casino Gaming Platform. + +## Overview + +The Casino Gaming Platform offers a variety of casino-style games, each implemented as a separate module. The modular architecture allows for easy addition of new games in the future. + +## Available Games + +### Poker + +![Poker](/public/poker.webp) + +A classic card game where players bet on the strength of their hands. + +**Features:** +- Texas Hold'em variant +- Single player against AI opponents +- Multiple difficulty levels +- Realistic betting system +- Hand strength evaluator +- Game history tracking + +**Technical Implementation:** +- Angular component-based UI +- Canvas-based card animation +- WebSocket connectivity for future multiplayer support +- AI logic implemented with configurable strategies + +### Blackjack + +![Blackjack](/public/blackjack.webp) + +Also known as 21, players compete against the dealer to get closest to 21 without going over. + +**Features:** +- Standard casino rules +- Betting system with chips +- Split, double down, and insurance options +- Detailed statistics tracking +- Adaptive dealer AI + +**Technical Implementation:** +- SVG-based card rendering +- State-based game progression +- Configurable rule variations +- Strategy hints system + +### Slots + +![Slots](/public/slots.webp) + +A virtual slot machine with various themes and payout structures. + +**Features:** +- Multiple slot machine themes +- Variable paylines +- Bonus games and free spins +- Progressive jackpots +- Animated winning combinations + +**Technical Implementation:** +- CSS animation for reel spinning +- WebGL effects for special features +- Pseudo-random number generation with auditable results +- Configurable payout tables + +### Plinko + +![Plinko](/public/plinko.webp) + +A game where a ball drops through a field of pegs into prize slots. + +**Features:** +- Realistic physics simulation +- Adjustable risk levels +- Multiple ball options +- Visual path tracking +- Slow-motion replays + +**Technical Implementation:** +- Physics engine for realistic ball movement +- Canvas-based rendering +- Adjustable difficulty parameters +- Verifiable random drop patterns + +### Liars Dice + +![Liars Dice](/public/liars-dice.webp) + +A bluffing dice game where players make increasingly higher bids about the dice in play. + +**Features:** +- Single player against AI opponents +- Traditional rules with customizable variations +- Opponent personality types +- Bluff detection AI +- Detailed game history + +**Technical Implementation:** +- 3D dice rendering +- Probability-based AI decision making +- Adaptive opponent difficulty +- Social features for future multiplayer support + +### Lootboxes + +![Lootboxes](/public/lootbox.webp) + +A collection of virtual lootboxes with random in-game rewards. + +**Features:** +- Multiple box tiers and themes +- Animated unboxing experience +- Collection tracking +- Rare item showcase +- Trading system (planned) + +**Technical Implementation:** +- 3D box models with WebGL rendering +- Probability-based reward distribution +- Account-linked inventory system +- Social sharing of rare acquisitions + +## Game Architecture + +### Frontend Components + +Each game consists of: + +1. **Game Container**: Main component that initializes the game +2. **Game UI**: User interface elements specific to the game +3. **Game Logic**: Business logic implementing game rules +4. **Game State**: State management for the game session +5. **Animation Controller**: Manages game animations and effects + +### Backend Services + +Games are supported by these backend services: + +1. **Game Session Service**: Manages active game sessions +2. **Random Number Generation Service**: Provides auditable random values +3. **Transaction Service**: Handles bets and winnings +4. **Statistics Service**: Tracks game outcomes and player statistics + +### Common Architecture Pattern + +``` +┌────────────────────────────────────────────────────┐ +│ Game Component │ +│ │ +│ ┌──────────────┐ ┌──────────────┐ ┌──────────┐ │ +│ │ │ │ │ │ │ │ +│ │ Game UI │ │ Game Logic │ │ State │ │ +│ │ │ │ │ │ │ │ +│ └──────────────┘ └──────────────┘ └──────────┘ │ +│ │ +│ ┌──────────────┐ ┌──────────────┐ │ +│ │ │ │ │ │ +│ │ Animation │ │ Services │ │ +│ │ │ │ │ │ +│ └──────────────┘ └──────────────┘ │ +│ │ +└────────────────────────────────────────────────────┘ +``` + +## Game Integration + +### Adding a New Game + +To add a new game to the platform: + +1. Create a new feature module in the frontend +2. Implement the required game components +3. Add the game metadata to the game registry +4. Implement any required backend services +5. Add the game to the home screen carousel + +### Game Development Guidelines + +1. **Fairness**: + - All games must use the platform's verifiable RNG + - Game odds must be transparent and documented + - House edge must be clearly defined + +2. **User Experience**: + - Consistent UI patterns across games + - Clear instructions and help documentation + - Responsive design for all device types + - Accessibility compliance (WCAG 2.1 AA) + +3. **Performance**: + - Games should initialize in under 3 seconds + - Animations should maintain 60fps + - Games should gracefully degrade on lower-end devices + +4. **State Management**: + - Games must handle disconnections gracefully + - Game state should be recoverable + - Critical operations must be atomic + +## Transaction Flow + +### Betting Process + +1. Player selects bet amount +2. Game validates against player balance +3. Bet amount is reserved (not yet committed) +4. Game executes and determines outcome +5. Transaction is finalized (win or loss) +6. Player balance is updated + +### Transaction Verification + +All game transactions: +- Are logged with unique identifiers +- Include initial state, actions, and final state +- Are cryptographically signed +- Can be audited by administrators + +## Testing and Validation + +### Game Testing Requirements + +All games must include: +1. **Unit tests** for game logic +2. **Integration tests** for frontend-backend interactions +3. **Performance tests** for animation and rendering +4. **Fairness tests** verifying expected return to player (RTP) +5. **Usability tests** with representative users + +### Validation Process + +Before release, each game undergoes: +1. Code review by senior developers +2. Mathematical verification of odds +3. Security audit for potential exploits +4. Accessibility evaluation +5. Performance profiling on target devices + +## Future Game Roadmap + +Planned additions to the game library: + +1. **Roulette**: European and American variants +2. **Craps**: Full-featured dice game +3. **Baccarat**: Card game with simple betting +4. **Video Poker**: Multiple variants +5. **Multiplayer Poker**: Real-time tables with multiple players + +## Support and Maintenance + +### Game Updates + +Games receive regular updates for: +- Bug fixes +- Performance improvements +- New features and content +- Seasonal themes and events + +### Support Process + +For issues with specific games: +1. Users report issues through the in-game support interface +2. Support tickets are categorized by game and issue type +3. Development team prioritizes fixes based on impact +4. Updates are deployed in the next release cycle \ No newline at end of file diff --git a/Home.md b/Home.md index 5d08b7b..440df92 100644 --- a/Home.md +++ b/Home.md @@ -1 +1,82 @@ -Welcome to the Wiki. \ No newline at end of file +# Casino Gaming Platform Wiki + +Welcome to the Casino Gaming Platform wiki. This comprehensive guide provides documentation on all aspects of our online gaming platform. + +## 🎮 Project Overview + +The Casino Gaming Platform is an online gaming system offering various casino-style games with virtual currency support. The platform features a modern tech stack with Angular frontend, Spring Boot backend, and complete user authentication via Keycloak. + +### Features + +- Multiple casino games: Poker, Blackjack, Slots, Plinko, Liars Dice, and Lootboxes +- User authentication and account management via Keycloak +- Virtual currency deposit system using Stripe payments +- Transaction history tracking +- Responsive modern UI built with Angular and TailwindCSS + +## 🏗️ Technical Architecture + +### Frontend (Angular) + +The frontend is built with Angular 18, providing a responsive and modern user interface for the casino gaming experience. It uses: + +- **TailwindCSS** for styling and consistent design patterns +- **Keycloak Integration** for authentication +- **Stripe Payment Integration** for virtual currency deposits + +[Frontend Documentation](Frontend) + +### Backend (Spring Boot) + +The backend is built on Spring Boot (Java), providing robust API endpoints for game functionality, user management, and transaction processing. Key components include: + +- **PostgreSQL Database** for data persistence +- **Keycloak Integration** for authentication/authorization +- **Stripe API** for payment processing + +[Backend Documentation](Backend) + +### Infrastructure + +The entire application stack is containerized using Docker, making deployment and scaling straightforward. The infrastructure includes: + +- **PostgreSQL Databases** (application and Keycloak) +- **Keycloak Authentication Server** + +## 🚀 Getting Started + +To get started with development or deployment, follow these guides: + +- [Development Environment Setup](Development-Environment-Setup) +- [Running the Application](Running-the-Application) +- [Architecture Overview](Architecture-Overview) + +## 📝 Developer Guidelines + +- [Coding Standards](Coding-Standards) +- [Git Workflow](Git-Workflow) +- [Testing Guidelines](Testing-Guidelines) + +## 🧩 Key Components + +- [Game Modules](Game-Modules) +- [Authentication & Authorization](Authentication-and-Authorization) +- [Payment System](Payment-System) +- [User Management](User-Management) + +## 🔍 API Reference + +- [Backend API Documentation](API-Documentation) +- [External Services Integration](External-Services) + +## 🧪 Testing + +- [Frontend Testing](Frontend-Testing) +- [Backend Testing](Backend-Testing) +- [Integration Testing](Integration-Testing) + +## 📚 Additional Resources + +- [Troubleshooting](Troubleshooting) +- [Deployment Guide](Deployment-Guide) +- [Glossary](Glossary) \ No newline at end of file diff --git a/Payment-System.md b/Payment-System.md new file mode 100644 index 0000000..57b6cb6 --- /dev/null +++ b/Payment-System.md @@ -0,0 +1,263 @@ +# Payment System + +This page documents the payment system of the Casino Gaming Platform. + +## Overview + +The Casino Gaming Platform uses a virtual currency system that allows users to deposit funds using real money. The payment processing is handled by Stripe, a secure and widely trusted payment provider. + +## Architecture + +``` +┌─────────────┐ ┌─────────────┐ ┌─────────────┐ +│ │ │ │ │ │ +│ Frontend │◄───►│ Backend │◄───►│ Stripe │ +│ (Angular) │ │ (Spring) │ │ │ +│ │ │ │ │ │ +└─────────────┘ └─────────────┘ └─────────────┘ + │ + ▼ + ┌─────────────┐ + │ │ + │ Database │ + │ │ + └─────────────┘ +``` + +## Virtual Currency System + +### Currency Details + +- **Name**: Casino Coins (CC) +- **Exchange Rate**: 1 USD = 100 CC +- **Minimum Deposit**: 5 USD (500 CC) +- **Maximum Deposit**: 1000 USD (100,000 CC) per transaction + +### Balance Management + +- User balances are stored in the database +- Transactions are logged for all balance changes +- Balances are updated in real-time +- History is accessible to users + +## Payment Flow + +### Deposit Process + +1. **Initiation**: + - User selects "Deposit" from the navigation menu + - User enters desired deposit amount + - Frontend sends request to create a payment session + +2. **Session Creation**: + ``` + POST /api/deposits/create-session + { + "amount": 1000 // Amount in cents (10 USD) + } + ``` + +3. **Stripe Integration**: + - Backend creates a Stripe Checkout Session + - Backend returns session ID to frontend + ``` + { + "sessionId": "cs_test_a1b2c3d4..." + } + ``` + +4. **Payment UI**: + - Frontend redirects to Stripe Checkout + - User enters payment information + - Stripe processes the payment + +5. **Completion**: + - On successful payment, Stripe redirects to success URL + - Backend receives webhook notification from Stripe + - Backend verifies payment and updates user balance + - User receives confirmation and updated balance + +### Webhook Handling + +Stripe webhooks are used to provide reliable payment status updates: + +1. The backend listens for `checkout.session.completed` events +2. When received, the webhook handler: + - Verifies the webhook signature + - Checks payment status + - Updates the user's balance + - Records the transaction + +## Transaction Types + +The system records the following transaction types: + +1. **Deposit**: Adding funds to the account +2. **Bet**: Placing a bet in a game +3. **Win**: Receiving winnings from a game +4. **Bonus**: Receiving promotional or bonus funds +5. **Refund**: Receiving a refund for a failed transaction + +## Transaction Record + +Each transaction includes: + +- Unique transaction ID +- User ID +- Transaction type +- Amount +- Previous balance +- New balance +- Timestamp +- Reference ID (e.g., game session ID, Stripe payment ID) +- Status (Pending, Completed, Failed) + +## Security Measures + +### Payment Data Protection + +- No credit card information is stored on our servers +- All payment processing is handled by Stripe +- PCI compliance is maintained by using Stripe Elements +- All communication with Stripe uses TLS encryption + +### Transaction Verification + +- All balance updates require verification +- Double-entry accounting system to prevent errors +- Automated reconciliation processes +- Regular audits of transaction records + +### Fraud Prevention + +- Rate limiting for deposit attempts +- Suspicious activity monitoring +- IP verification +- Device fingerprinting +- Transaction amount limits + +## Testing the Payment System + +### Test Mode + +During development and testing, Stripe's test mode is used: + +1. Use Stripe test cards (e.g., 4242 4242 4242 4242) +2. Test webhooks using the Stripe CLI +3. Verify transaction records in the database + +### Test Cards + +| Card Number | Description | +|-----------------------|-------------------------| +| 4242 4242 4242 4242 | Successful payment | +| 4000 0000 0000 0002 | Declined payment | +| 4000 0000 0000 9995 | Insufficient funds | +| 4000 0027 6000 3184 | 3DS authentication | + +## User Interface + +### Deposit Page + +The deposit page includes: + +- Deposit amount input +- Currency conversion display +- Payment method selection +- Transaction history +- Current balance display + +### Transaction History + +Users can view their transaction history including: + +- Date and time of each transaction +- Transaction type +- Amount +- Status +- Associated game (for bets and wins) + +## Reporting and Analytics + +### Administrative Reports + +The system provides the following reports: + +1. **Daily Transaction Summary**: + - Total deposits + - Total withdrawals (if implemented) + - Net change in system balance + +2. **User Activity Report**: + - Top depositors + - Deposit frequency + - Average deposit amount + +3. **Payment Method Analysis**: + - Breakdown by payment method + - Success/failure rates + - Processing time averages + +## Compliance and Regulations + +### Legal Requirements + +The payment system complies with: + +- Anti-Money Laundering (AML) regulations +- Know Your Customer (KYC) requirements +- Data protection laws (GDPR, CCPA) +- Local gambling regulations where applicable + +### Record Keeping + +- Transaction records are maintained for the legally required period +- User verification documents are securely stored +- Access to payment data is strictly controlled and audited + +## Troubleshooting + +### Common Issues + +1. **Failed Payments**: + - Check Stripe Dashboard for error details + - Verify webhook delivery + - Check for rate limiting or security blocks + +2. **Balance Discrepancies**: + - Review transaction logs + - Check for pending transactions + - Verify webhook processing + +3. **Session Expiration**: + - Stripe sessions expire after 24 hours + - Create a new session if expired + +### Support Process + +For payment-related issues: + +1. User reports issue through support interface +2. Support team accesses transaction logs +3. Issue is categorized and assigned +4. Resolution is communicated to user +5. System improvements are made if needed + +## Future Enhancements + +Planned improvements to the payment system: + +1. **Additional Payment Methods**: + - PayPal integration + - Cryptocurrency support + - Local payment methods + +2. **Withdrawal System**: + - Ability to cash out virtual currency + - Verification processes + - Payout method selection + +3. **Subscription Model**: + - Premium tier with monthly subscription + - Subscriber benefits and bonuses + - Automatic renewal handling \ No newline at end of file