Не подтверждена Коммит 38177e6b создал по автору Stanislav Radchenko's avatar Stanislav Radchenko Зафиксировано автором GitHub
Просмотр файлов

Merge pull request #9 from Radch-enko/develop

Update backend documentation
владельцы de60157c f55854d9
# Effective Office # Effective Office
## Overview ## Overview
Effective Office is a comprehensive office management system designed to streamline workplace operations, resource management, and employee interactions. The project consists of a backend server, web clients, and mobile applications that work together to create an efficient office environment. Effective Office is a comprehensive office management system designed to streamline workplace operations, resource management, and employee interactions. The project consists of a backend server and tablet clients that work together to create an efficient office environment.
## Features ## Features
- Resource booking and management - Resource booking and management
...@@ -13,7 +13,7 @@ Effective Office is a comprehensive office management system designed to streaml ...@@ -13,7 +13,7 @@ Effective Office is a comprehensive office management system designed to streaml
## Architecture ## Architecture
The project follows a client-server architecture: The project follows a client-server architecture:
- **Backend**: Spring Boot application with PostgreSQL database - **Backend**: Spring Boot application with PostgreSQL database
- **Clients**: Web applications and iOS mobile app - **Clients**: Client applications and iOS tablet app
- **Deployment**: Docker-based containerization for easy deployment - **Deployment**: Docker-based containerization for easy deployment
- **Security**: Git hooks for leak detection to prevent sensitive information exposure - **Security**: Git hooks for leak detection to prevent sensitive information exposure
...@@ -55,7 +55,7 @@ The project follows a client-server architecture: ...@@ -55,7 +55,7 @@ The project follows a client-server architecture:
effective-office/ effective-office/
├── backend/ # Server-side application ├── backend/ # Server-side application
│ └── README.md # Detailed backend documentation │ └── README.md # Detailed backend documentation
├── clients/ # Web client applications ├── clients/ # Client applications
│ └── README.md # Detailed client documentation │ └── README.md # Detailed client documentation
├── iosApp/ # iOS mobile application ├── iosApp/ # iOS mobile application
├── deploy/ # Deployment configurations ├── deploy/ # Deployment configurations
...@@ -70,6 +70,8 @@ effective-office/ ...@@ -70,6 +70,8 @@ effective-office/
For detailed documentation: For detailed documentation:
- [Backend Documentation](./backend/README.md) - [Backend Documentation](./backend/README.md)
- [Client Documentation](./clients/README.md) - [Client Documentation](./clients/README.md)
- [Build Logic Documentation](./build-logic/README.md)
- [Calendar Integration Documentation](docs/CALENDAR_INTEGRATION.md)
## Development Tools ## Development Tools
- **Build System**: Gradle with Kotlin DSL - **Build System**: Gradle with Kotlin DSL
...@@ -86,7 +88,7 @@ For detailed documentation: ...@@ -86,7 +88,7 @@ For detailed documentation:
## Contributing ## Contributing
1. Ensure you've run the installation script (`./scripts/install.sh`) 1. Ensure you've run the installation script (`./scripts/install.sh`)
2. Follow our [Git Flow](./GIT_FLOW.md) for branching and commit conventions 2. Follow our [Git Flow](docs/GIT_FLOW.md) for branching and commit conventions
3. Create a feature branch (`git checkout -b feature/amazing-feature`) 3. Create a feature branch (`git checkout -b feature/amazing-feature`)
4. Commit your changes (`git commit -m 'Add some amazing feature'`) 4. Commit your changes (`git commit -m 'Add some amazing feature'`)
5. Push to the branch (`git push origin feature/amazing-feature`) 5. Push to the branch (`git push origin feature/amazing-feature`)
......
...@@ -23,13 +23,51 @@ backend/ ...@@ -23,13 +23,51 @@ backend/
├── docs/ # API documentation ├── docs/ # API documentation
└── scripts/ # Backend-specific utility scripts └── scripts/ # Backend-specific utility scripts
``` ```
For detailed documentation:
- [Feature authorization](./backend/feature/authorization/README.md)
- [Feature booking](./backend/feature/booking/README.md)
- [Feature calendar-subscription](./backend/feature/calendar-subscription/README.md)
- [Feature notifications](./backend/feature/notifications/README.md)
- [Feature user](./backend/feature/user/README.md)
- [Feature workspace](./backend/feature/workspace/README.md)
## Technology Stack ## Technology Stack
- **Framework**: Spring Boot
- **Database**: PostgreSQL ### Core Technologies
- **API Documentation**: Swagger/OpenAPI - **Language**: Kotlin 2.1.21
- **Authentication**: JWT-based authentication - **Framework**: Spring Boot 3.5.0
- **Build Tool**: Gradle with Kotlin DSL - **Build Tool**: Gradle 8.x with Kotlin DSL
- **Java Version**: JDK 17
### Database
- **RDBMS**: PostgreSQL 42.7.6
- **Migration Tool**: Flyway 11.8.2
- **Connection Pool**: HikariCP 6.3.0
- **ORM**: Spring Data JPA
### Security
- **Framework**: Spring Security
- **Authentication**: JWT (JSON Web Token) 0.11.5
- **Authorization**: Role-based access control
### API & Documentation
- **API Style**: RESTful
- **Documentation**: SpringDoc OpenAPI 2.8.8 (Swagger UI)
- **Validation**: Jakarta Bean Validation 3.0.2
### Integration
- **Google Calendar**: Google API Client 1.33.0
- **OAuth**: Google OAuth Client 1.33.3
### Testing
- **Unit Testing**: JUnit 5.12.2
- **Mocking**: MockK 1.14.2
- **Integration Testing**: Testcontainers 1.20.2
### Utilities
- **JSON Processing**: Jackson 2.19.0
- **Logging**: SLF4J 2.0.17 with Logback 1.5.18
- **Environment Variables**: Spring dotenv for .env file support
## API Endpoints ## API Endpoints
The backend exposes RESTful APIs for: The backend exposes RESTful APIs for:
...@@ -77,7 +115,6 @@ The database schema includes tables for: ...@@ -77,7 +115,6 @@ The database schema includes tables for:
``` ```
This will use the configuration from `application-local.yml`. This will use the configuration from `application-local.yml`.
## Deployment ## Deployment
### Using Docker ### Using Docker
The backend can be deployed using Docker: The backend can be deployed using Docker:
......
# App Module
## Overview
The App Module is the main application module that ties together all components of the Effective Office backend. It serves as the entry point for the application, configures the Spring Boot environment, and orchestrates the integration of all other modules.
## Features
- Application bootstrapping and initialization
- Module integration and coordination
- Global configuration management
- API endpoint exposure
- Security configuration
- Error handling and exception management
## Architecture
The module follows a standard Spring Boot application structure:
```
app/
├── src/
│ └── main/
│ ├── kotlin/
│ │ └── band/
│ │ └── effective/
│ │ └── office/
│ │ └── backend/
│ │ └── app/
│ │ ├── EffectiveOfficeApplication.kt # Main application class
│ │ ├── config/ # Application-wide configuration
│ │ │ ├── SecurityConfig.kt # Security configuration
│ │ │ ├── WebConfig.kt # Web configuration
│ │ │ └── SwaggerConfig.kt # API documentation configuration
│ │ └── exception/ # Global exception handling
│ └── resources/
│ ├── application.yml # Main application properties
│ ├── application-dev.yml # Development environment properties
│ ├── application-prod.yml # Production environment properties
│ └── application-local.yml # Local development properties
```
## Key Components
### Main Application
- **EffectiveOfficeApplication**: The main Spring Boot application class with the `@SpringBootApplication` annotation that serves as the entry point for the application.
### Configuration
- **SecurityConfig**: Configures Spring Security for authentication and authorization
- **WebConfig**: Configures web-related settings like CORS, content negotiation, etc.
- **SwaggerConfig**: Configures Swagger/OpenAPI documentation
### Exception Handling
- **GlobalExceptionHandler**: Provides centralized exception handling for the entire application
## Integration
The App Module integrates all other modules of the Effective Office backend:
- **Core Modules**:
- Data Module: For data access and persistence
- Domain Module: For business logic and domain models
- Repository Module: For database access
- **Feature Modules**:
- Authorization Module: For user authentication and authorization
- Booking Module: For resource booking management
- Calendar Subscription Module: For calendar integration
- Notifications Module: For user notifications
- User Module: For user management
- Workspace Module: For workspace and office space management
## Configuration
The module provides environment-specific configurations:
- **application.yml**: Default configuration properties
- **application-local.yml**: Local development configuration
## Usage
To run the application:
```bash
./gradlew :backend:app:bootRun
```
To run with a specific profile:
```bash
./gradlew :backend:app:bootRun --args='--spring.profiles.active=local'
```
To build the application:
```bash
./gradlew :backend:app:build
```
## Development
When extending this module:
1. Maintain clear separation of concerns
2. Add new configurations in the appropriate configuration classes
3. Ensure proper integration with other modules
4. Follow Spring Boot best practices for application structure
\ No newline at end of file
# Data Module
## Overview
The Data Module provides common data structures and data transfer objects (DTOs) used across the Effective Office backend. It defines standardized formats for data exchange between different parts of the application.
## Features
- Standardized error response format
- Common data transfer objects
- Shared data structures
## Architecture
The module follows a simple structure:
```
data/
├── src/
│ └── main/
│ └── kotlin/
│ └── band/
│ └── effective/
│ └── office/
│ └── backend/
│ └── core/
│ └── data/
│ └── ErrorDto.kt # Error data transfer object
```
## Key Components
### Data Transfer Objects
- **ErrorDto**: A standardized error response format used across all services
- Contains a message describing the error
- Includes an error code for categorization
## Integration
The Data Module is used by:
- API controllers for standardized error responses
- Service layers for data exchange
- Other modules that need to use common data structures
## Usage Examples
### Error Response Example
```kotlin
// Creating a standard error response
val errorResponse = ErrorDto(
message = "Resource not found",
code = 404
)
// Using in a controller
@ExceptionHandler(ResourceNotFoundException::class)
fun handleResourceNotFoundException(ex: ResourceNotFoundException): ResponseEntity<ErrorDto> {
val errorDto = ErrorDto(
message = ex.message ?: "Resource not found",
code = 404
)
return ResponseEntity(errorDto, HttpStatus.NOT_FOUND)
}
```
## Configuration
The module has minimal configuration requirements as it primarily consists of data structures.
## Development
When extending this module:
1. Follow the established patterns for creating DTOs
2. Ensure backward compatibility when modifying existing DTOs
3. Add proper documentation for new data structures
\ No newline at end of file
# Domain Module
## Overview
The Domain Module defines the core business entities, interfaces, and services for the Effective Office backend. It encapsulates the business logic and rules of the application, independent of specific implementations or external dependencies.
## Features
- Core domain models representing business entities
- Service interfaces defining business operations
- Business logic and validation rules
## Architecture
The module is organized into model and service packages:
```
domain/
├── src/
│ └── main/
│ └── kotlin/
│ └── band/
│ └── effective/
│ └── office/
│ └── backend/
│ └── core/
│ └── domain/
│ ├── model/ # Domain entities
│ │ ├── CalendarId.kt
│ │ ├── User.kt
│ │ ├── Utility.kt
│ │ ├── Workspace.kt
│ │ └── WorkspaceZone.kt
│ └── service/ # Domain services
│ ├── UserDomainService.kt
│ └── WorkspaceDomainService.kt
```
## Key Components
### Domain Models
- **User**: Represents a user in the system with properties like username, email, name, etc.
- **Workspace**: Represents a workspace or office space
- **WorkspaceZone**: Represents a zone within a workspace
- **Utility**: Represents utilities available in workspaces
- **CalendarId**: Represents a calendar identifier linked to a workspace
### Domain Services
- **UserDomainService**: Defines operations for user management (find, create)
- **WorkspaceDomainService**: Defines operations for workspace management
## Validation
The domain models include validation annotations to ensure data integrity:
- Required fields validation
- String length constraints
- Email format validation
## Integration
The Domain Module is used by:
- Feature modules that implement business logic
- Repository implementations that persist domain entities
- API controllers that expose domain operations
## Usage Examples
### Working with Domain Models
```kotlin
// Creating a new user
val user = User(
username = "johndoe",
email = "john.doe@example.com",
firstName = "John",
lastName = "Doe",
role = "USER"
)
// Using domain services
class UserServiceImpl(private val userRepository: UserRepository) : UserDomainService {
override fun findByUsername(username: String): User? {
return userRepository.findByUsername(username)
}
override fun createUser(user: User): User {
// Business logic for user creation
return userRepository.save(user)
}
}
```
## Development
When extending this module:
1. Keep domain models focused on business concepts, not technical details
2. Ensure domain services define clear contracts for business operations
3. Maintain separation between domain logic and implementation details
4. Add proper validation to ensure data integrity
\ No newline at end of file
# Repository Module
## Overview
The Repository Module provides database access and persistence functionality for the Effective Office backend. It manages database connections, migrations, and implements data access patterns for storing and retrieving domain entities.
## Features
- Database configuration and connection management
- Database schema definition and migrations
- Data access layer for domain entities
## Architecture
The module is organized into configuration and database migration resources:
```
repository/
├── src/
│ └── main/
│ ├── kotlin/
│ │ └── band/
│ │ └── effective/
│ │ └── office/
│ │ └── backend/
│ │ └── core/
│ │ └── repository/
│ │ └── config/
│ │ └── DatabaseConfig.kt # Database configuration
│ └── resources/
│ ├── application-repository.yml # Repository-specific configuration
│ └── db/
│ └── migration/
│ └── V1__create_tables.sql # Database schema migration
```
## Key Components
### Configuration
- **DatabaseConfig**: Spring configuration class that enables JPA repositories and transaction management
### Database Schema
The module defines the following database tables:
- **workspace_zones**: Stores workspace zone information
- **users**: Stores user information
- **workspaces**: Stores workspace information
- **utilities**: Stores utilities information
- **workspace_utilities**: Links workspaces and utilities
- **api_keys**: Stores API keys for authentication
- **calendar_ids**: Stores calendar IDs linked to workspaces
- **calendar_channels**: Stores Google Calendar notification channels
## Database Migrations
The module uses Flyway for database migrations:
- **V1__create_tables.sql**: Creates the initial database schema with all necessary tables, indexes, and constraints
### How to Implement Migrations
#### Migration Naming Convention
Flyway uses a specific naming convention for migration files:
```
V{version}__{description}.sql
```
- `{version}`: A version number (e.g., 1, 2, 3.1, 4.5.7)
- `{description}`: A description with words separated by underscores
Examples:
- `V1__create_tables.sql`
- `V2__add_user_preferences.sql`
- `V3__alter_workspace_table.sql`
#### Creating a New Migration
1. **Determine the next version number**: Look at the existing migrations in `src/main/resources/db/migration/` and increment the highest version number.
2. **Create a new SQL file** in the `src/main/resources/db/migration/` directory following the naming convention.
3. **Write your SQL statements** in the file. Include:
- Clear comments explaining the purpose of each change
- Table creation statements with appropriate constraints
- Index creation for frequently queried columns
- Comments on tables and columns for documentation
- Any necessary data migrations
4. **Test your migration** by running the application with the new migration file in place.
#### Best Practices
1. **Make migrations idempotent** when possible (can be run multiple times without causing errors)
2. **Use explicit naming** for constraints, indexes, and foreign keys
3. **Include comments** in your SQL to explain complex changes
4. **Keep migrations focused** on a specific change or related set of changes
5. **Never modify existing migration files** that have been committed to version control
6. **Use transactions** for complex migrations to ensure atomicity
#### Example Migration
```sql
-- Add user preferences table
CREATE TABLE user_preferences
(
user_id UUID PRIMARY KEY REFERENCES users (id),
theme VARCHAR(50) NOT NULL DEFAULT 'light',
notifications BOOLEAN NOT NULL DEFAULT TRUE,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
-- Add index for common queries
CREATE INDEX idx_user_preferences_theme ON user_preferences (theme);
-- Add comment to table
COMMENT ON TABLE user_preferences IS 'Table storing user preference settings';
```
#### Flyway Configuration
The Flyway configuration is defined in `application-repository.yml`:
```yaml
spring:
flyway:
enabled: true
baseline-on-migrate: true
locations: classpath:db/migration
table: flyway_schema_history
```
## Integration
The Repository Module is used by:
- Service implementations that need to persist or retrieve data
- Application configuration for database setup
- Other modules that need data access capabilities
## Configuration
The module includes repository-specific configuration in `application-repository.yml`, which can be customized for different environments.
## Usage Examples
### Implementing a Repository
```kotlin
@Repository
interface UserRepository : JpaRepository<UserEntity, UUID> {
fun findByUsername(username: String): UserEntity?
fun findByEmail(email: String): UserEntity?
}
// Using the repository in a service implementation
@Service
class UserServiceImpl(private val userRepository: UserRepository) : UserService {
override fun findByUsername(username: String): User? {
return userRepository.findByUsername(username)?.toDomain()
}
}
```
## Development
When extending this module:
1. Use Flyway migrations for database schema changes
2. Follow naming conventions for database objects
3. Add appropriate indexes for frequently queried columns
4. Document table structures and relationships
5. Ensure proper transaction management
# Authorization Module
## Overview
The Authorization module provides a flexible and extensible authentication and authorization system for the Effective Office backend. It implements a Chain of Responsibility pattern to support multiple authorization methods, including API key-based authentication and JWT token authentication.
## Features
- Chain of Responsibility pattern for flexible authorization flow
- API key-based authentication
- JWT token authentication
- Integration with Spring Security
- Customizable error handling
## Architecture
The module follows a layered architecture:
```
authorization/
├── apikey/ # API key authentication components
│ ├── config/ # API key configuration
│ ├── entity/ # API key entity classes
│ └── repository/ # API key data access
├── config/ # Security and authorization configuration
├── core/ # Core authorization components
│ └── exception/ # Core-specific exceptions
├── exception/ # Common exception classes
├── security/ # Spring Security integration
└── service/ # Authorization services
```
## Key Components
### Core Components
- **Authorizer**: Interface for authorization chain elements
- **BaseAuthorizer**: Abstract base class for authorizers
- **AuthorizationChain**: Manages the chain of authorizers
- **AuthorizationResult**: Represents the result of an authorization attempt
### API Key Authorization
- **ApiKeyAuthorizer**: Authorizer implementation for API key-based authentication
- **ApiKeyRepository**: Repository for API key storage and retrieval
### Security Integration
- **JwtAuthenticationFilter**: Spring Security filter for JWT authentication
- **SecurityConfig**: Spring Security configuration
### Services
- **AuthorizationService**: Service that coordinates the authorization process
### Configuration
The module provides default configurations that can be customized:
1. **Authorization Chain Configuration**:
```kotlin
@Configuration
class CustomAuthorizationConfig {
@Bean
fun customAuthorizer(): Authorizer {
return CustomAuthorizer()
}
}
```
2. **Security Configuration**:
The module integrates with Spring Security and can be customized through properties or by extending the provided configurations.
### Creating Custom Authorizers
To create a custom authorizer, extend the `BaseAuthorizer` class:
```kotlin
@Component
class CustomAuthorizer : BaseAuthorizer() {
override fun doAuthorize(request: HttpServletRequest): AuthorizationResult {
// Custom authorization logic
return AuthorizationResult(success = true)
}
}
```
## Error Handling
The module provides custom exceptions for different authorization scenarios:
- `AuthorizationException`: Base exception for all authorization errors
- `UnauthorizedException`: Thrown when authorization fails
- `InvalidApiKeyException`: Thrown when an API key is invalid
- `MissingTokenException`: Thrown when a required token is missing
## Integration with Spring Security
The module integrates with Spring Security through the `JwtAuthenticationFilter` and `SecurityConfig` classes. The filter intercepts incoming requests and uses the authorization chain to authenticate them.
## Examples
### Basic Authorization Flow
1. A request comes in with an Authorization header
2. The `JwtAuthenticationFilter` intercepts the request
3. The filter passes the request to the `AuthorizationService`
4. The service uses the `AuthorizationChain` to process the request
5. Each authorizer in the chain attempts to authorize the request
6. If any authorizer succeeds, the request is authorized
7. If all authorizers fail, the request is rejected
### API Key Authorization
API keys are stored in the database in a hashed format. When a request comes in with an API key:
1. The `ApiKeyAuthorizer` extracts the key from the Authorization header
2. The key is hashed using SHA-256
3. The hashed key is compared with keys in the database
4. If a match is found, the request is authorized
## Development
### Adding a New Authorization Method
To add a new authorization method:
1. Create a new authorizer by implementing the `Authorizer` interface or extending `BaseAuthorizer`
2. Register the authorizer as a Spring bean
3. The authorizer will automatically be added to the authorization chain
# Booking Module
## Overview
The Booking module provides functionality for managing resource bookings within the Effective Office system. It enables users to book office resources such as meeting rooms, desks, and equipment, and integrates with calendar systems for scheduling and notifications.
## Features
- Resource booking management
- Calendar integration (Google Calendar and dummy implementation for testing)
- Booking validation and conflict resolution
- Booking notifications
- RESTful API for booking operations
## Architecture
The module follows a layered architecture:
```
booking/
├── calendar/ # Calendar integration components
│ ├── dummy/ # Dummy calendar implementation for testing
│ └── google/ # Google Calendar integration
├── core/ # Core booking functionality
│ ├── config/ # Configuration classes
│ ├── controller/ # REST controllers
│ ├── domain/ # Domain models
│ ├── dto/ # Data Transfer Objects
│ ├── exception/ # Exception handling
│ └── service/ # Business logic services
```
## Key Components
### Core Components
- **BookingController**: REST API endpoints for booking operations
- **BookingService**: Business logic for booking management
- **BookingDomain**: Domain models representing bookings and related entities
- **BookingDTO**: Data Transfer Objects for API communication
### Calendar Integration
- **GoogleCalendarIntegration**: Integration with Google Calendar
- **DummyCalendarImplementation**: Mock implementation for testing and development
## Configuration
The module provides default configurations that can be customized:
1. **Booking Configuration**:
```kotlin
@Configuration
class BookingConfig {
// Configuration properties and beans
}
```
2. **Calendar Integration Configuration**:
The module supports configuration for different calendar providers.
## Error Handling
The module provides custom exceptions for different booking scenarios:
- `BookingException`: Base exception for all booking errors
- `BookingConflictException`: Thrown when a booking conflicts with an existing booking
- `ResourceUnavailableException`: Thrown when a resource is not available for booking
- `InvalidBookingException`: Thrown when booking parameters are invalid
## Integration
The Booking module integrates with:
- Calendar systems (Google Calendar)
- Notification module for booking alerts
- User module for user information
- Workspace module for resource availability
## Examples
### Basic Booking Flow
1. A user requests to book a resource for a specific time period
2. The system validates the booking request
3. If the resource is available, the booking is created
4. The booking is synchronized with the user's calendar
### Booking Conflict Resolution
When a booking conflicts with an existing booking:
1. The system identifies the conflict
2. The user is notified of the conflict
## Development
### Adding a New Calendar Integration
To add a new calendar integration:
1. Create a new implementation in the calendar package
2. Implement the required interfaces
3. Register the implementation in the configuration
\ No newline at end of file
...@@ -11,7 +11,7 @@ This module provides functionality to subscribe to Google Calendar notifications ...@@ -11,7 +11,7 @@ This module provides functionality to subscribe to Google Calendar notifications
## Configuration ## Configuration
The module can be configured through the following properties in `application-local.yml` or environment variables: The module can be configured through the following properties in `application.yml` , `application-local.yml` or environment variables:
| Property | Environment Variable | Description | | Property | Environment Variable | Description |
|----------|---------------------|-------------| |----------|---------------------|-------------|
......
...@@ -40,15 +40,6 @@ class YourService( ...@@ -40,15 +40,6 @@ class YourService(
fun someMethod() { fun someMethod() {
// Send an empty notification // Send an empty notification
notificationSender.sendEmptyMessage("your-topic") notificationSender.sendEmptyMessage("your-topic")
// Send a notification about a workspace modification
notificationSender.sendContentMessage(HttpMethod.POST, workspaceDTO)
// Send a notification about a user modification
notificationSender.sendContentMessage(HttpMethod.PUT, userDto)
// Send a notification about a booking modification
notificationSender.sendContentMessage(HttpMethod.DELETE, bookingDto)
} }
} }
``` ```
......
# User Module
## Overview
The User Module provides functionality for managing users within the Effective Office system. It enables creating, retrieving, updating, and deleting user accounts, as well as managing user-related information.
## Features
- User account management (CRUD operations)
- User authentication integration
- Active user filtering
- RESTful API for user operations
## Architecture
The module follows a layered architecture:
```
user/
├── config/ # Configuration classes
├── controller/ # REST controllers
├── dto/ # Data Transfer Objects
├── repository/ # Data access layer
├── service/ # Business logic services
```
## Key Components
### Core Components
- **UserController**: REST API endpoints for user operations
- **UserService**: Business logic for user management
- **UserRepository**: Data access for user entities
### API Endpoints
The module exposes the following REST endpoints:
- `GET /v1/users`: Get all users
- `GET /v1/users/{id}`: Get user by ID
- `GET /v1/users/by-username/{username}`: Get user by username
- `GET /v1/users/active`: Get all active users
- `POST /v1/users`: Create a new user
- `PUT /v1/users/{id}`: Update an existing user
- `DELETE /v1/users/{id}`: Delete a user
## Integration
The User module integrates with:
- Authentication and authorization module
- Notification module for user-related notifications
- Workspace module for user workspace assignments
# Workspace Module
## Overview
The Workspace Module provides functionality for managing workspaces within the Effective Office system. It enables retrieving information about different types of workspaces, their zones, utilities, and availability for booking.
## Features
- Workspace management and retrieval
- Workspace zone organization
- Workspace utilities tracking
- Integration with booking system for availability checking
- Filtering workspaces by tags
- RESTful API for workspace operations
## Architecture
The module follows a layered architecture:
```
workspace/
└── core/
├── config/ # Configuration classes
├── controller/ # REST controllers
├── dto/ # Data Transfer Objects
├── repository/ # Data access layer
├── service/ # Business logic services
```
## Key Components
### Core Components
- **WorkspaceController**: REST API endpoints for workspace operations
- **WorkspaceService**: Business logic for workspace management
- **WorkspaceRepository**: Data access for workspace entities
### API Endpoints
The module exposes the following REST endpoints:
- `GET /v1/workspaces/{id}`: Get workspace by ID
- `GET /v1/workspaces?workspace_tag={tag}`: Get workspaces by tag
- `GET /v1/workspaces?workspace_tag={tag}&with_bookings_from={timestamp}&with_bookings_until={timestamp}`: Get workspaces by tag with booking information
- `GET /v1/workspaces/zones`: Get all workspace zones
## Data Models
### Workspace
Represents a physical workspace in the office:
- ID
- Name
- Utilities (equipment and amenities)
- Zone (location within the office)
- Tag (type of workspace, e.g., "meeting", "desk")
### Workspace Zone
Represents a physical area or section within the office:
- ID
- Name
### Utility
Represents equipment or amenities available in a workspace:
- ID
- Name
- Icon URL
- Count
## Integration
The Workspace module integrates with:
- Booking module for checking workspace availability
- User module for workspace assignments
- Notification module for workspace-related notifications
## Examples
### Retrieving Available Workspaces
1. A client application requests workspaces with a specific tag (e.g., "meeting")
2. The client specifies a time range for availability checking
3. The system returns workspaces matching the tag, including their booking information
4. The client can determine which workspaces are available during the specified time period
\ No newline at end of file
# Build Logic Module
## Overview
The Build Logic module contains Gradle convention plugins that define common build configurations, dependencies, and tasks used across different modules in the Effective Office project. These plugins help maintain consistency in the build process and reduce duplication in build scripts.
## Features
- Centralized dependency management
- Reusable build configurations
- Standardized plugin application
- Common task definitions
- Consistent project setup
## Structure
```
build-logic/
├── build.gradle.kts # Build script for the build-logic module
├── settings.gradle.kts # Settings for the build-logic module
└── src/
└── main/
└── kotlin/
└── band/
└── effective/
└── office/
└── backend/
├── kotlin-common.gradle.kts # Common Kotlin configuration
├── spring-boot-application.gradle.kts # Spring Boot application configuration
├── spring-boot-common.gradle.kts # Common Spring Boot configuration
├── spring-data-jpa.gradle.kts # Spring Data JPA configuration
├── band.effective.office.client.kmp.data.gradle.kts # KMP data module configuration
├── band.effective.office.client.kmp.domain.gradle.kts # KMP domain module configuration
├── band.effective.office.client.kmp.feature.gradle.kts # KMP feature module configuration
├── band.effective.office.client.kmp.library.gradle.kts # KMP library module configuration
├── band.effective.office.client.kmp.ui.gradle.kts # KMP UI module configuration
└── ProjectExtensions.kt # Kotlin extensions for project configuration
```
## Convention Plugins
### Backend Plugins
- **kotlin-common**: Common Kotlin configuration for backend modules
- **spring-boot-application**: Configuration for Spring Boot application modules
- **spring-boot-common**: Common Spring Boot configuration for backend modules
- **spring-data-jpa**: Configuration for modules using Spring Data JPA
### Client Plugins
- **client.kmp.data**: Configuration for KMP data modules
- **client.kmp.domain**: Configuration for KMP domain modules
- **client.kmp.feature**: Configuration for KMP feature modules
- **client.kmp.library**: Configuration for KMP library modules
- **client.kmp.ui**: Configuration for KMP UI modules
## Usage
### Applying Plugins
To use these convention plugins in a module, add the appropriate plugin to the module's build script:
```kotlin
plugins {
id("band.effective.office.backend.kotlin-common")
}
```
### Example: Setting up a Spring Boot Application Module
```kotlin
plugins {
id("band.effective.office.backend.spring-boot-application")
}
dependencies {
implementation(project(":backend:core:domain"))
implementation(project(":backend:feature:user"))
// Additional dependencies
}
```
### Example: Setting up a KMP Feature Module
```kotlin
plugins {
id("band.effective.office.client.kmp.feature")
}
dependencies {
implementation(project(":clients:shared:domain"))
implementation(project(":clients:shared:ui"))
// Additional dependencies
}
```
## Development
### Adding a New Convention Plugin
To add a new convention plugin:
1. Create a new Gradle script in the appropriate directory
2. Define the plugin logic
3. Register the plugin in the build-logic build script
Example:
```kotlin
// src/main/kotlin/band/effective/office/backend/new-plugin.gradle.kts
plugins {
id("kotlin")
// Other plugins
}
// Configure the plugin
```
## Benefits
- **Consistency**: Ensures consistent configuration across modules
- **Maintainability**: Centralizes build logic for easier updates
- **Reusability**: Allows reuse of common configurations
- **Simplicity**: Simplifies module build scripts
\ No newline at end of file
# Google Calendar API Integration
## Overview
Effective Office integrates with Google Calendar API to provide robust calendar functionality for workspace booking and event management. This document provides detailed information about how Google Calendar API is used in the project, configuration requirements, and implementation details for developers.
## Features
- **Workspace Booking Management**: Create, update, delete, and find booking events in Google Calendar
- **Real-time Calendar Notifications**: Subscribe to Google Calendar push notifications for real-time updates
- **Recurring Events Support**: Handle recurring booking patterns with Google Calendar recurrence rules
- **User Integration**: Associate bookings with users as organizers and attendees
- **Availability Checking**: Prevent overlapping bookings by checking calendar availability
## Architecture
The Google Calendar integration is implemented in two main modules:
1. **Booking Calendar Module** (`backend/feature/booking/calendar/google/`):
- Provides implementation of the `CalendarProvider` interface using Google Calendar API
- Handles CRUD operations for booking events
- Manages workspace calendar associations
2. **Calendar Subscription Module** (`backend/feature/calendar-subscription/`):
- Manages subscriptions to Google Calendar push notifications
- Periodically renews subscriptions to ensure they don't expire
- Processes incoming notification events
## Configuration
### Required Properties
The following properties must be configured in your application configuration files or environment variables:
#### Booking Calendar Configuration
```yaml
calendar:
provider: google # Set to "google" to enable Google Calendar integration
application-name: Effective Office # Application name for Google API requests
delegated-user: user@example.com # User to delegate access to (optional)
credentials.file: classpath:google-credentials.json # Path to credentials file
default-calendar: primary # Default calendar ID to use
```
#### Calendar Subscription Configuration
```yaml
calendar.subscription:
default-app-email: service-account@example.com # Default application email for Google Calendar API
google-credentials: classpath:google-credentials.json # JSON credentials for Google API authentication
application-url: https://your-app.example.com # Application URL for production environment
test-application-url: https://test-app.example.com # Application URL for test environment
calendars: calendar1@group.calendar.google.com,calendar2@group.calendar.google.com # Comma-separated list of calendar IDs
test-calendars: test-calendar@group.calendar.google.com # Comma-separated list of test calendar IDs
```
### Google API Credentials
To use Google Calendar API, you need to:
1. Create a project in the [Google Cloud Console](https://console.cloud.google.com/)
2. Enable the Google Calendar API for your project
3. Create OAuth 2.0 credentials or a service account with appropriate permissions
4. Download the credentials JSON file and place it in your project's resources directory
5. Configure the application to use these credentials
## Implementation Details
### Booking Management
The `GoogleCalendarProvider` class implements the `CalendarProvider` interface and provides methods for:
- **Creating Events**: Convert booking data to Google Calendar events and insert them
- **Updating Events**: Modify existing events with updated booking information
- **Deleting Events**: Remove events from Google Calendar
- **Finding Events**: Query events by workspace, user, or time range
- **Handling Recurrence**: Convert between application recurrence models and Google Calendar recurrence rules
### Push Notifications
The `GoogleCalendarService` class manages Google Calendar push notifications:
- **Subscription Setup**: Create notification channels for specified calendars
- **Channel Management**: Store channel information in the database and renew before expiration
- **Notification Processing**: Handle incoming notifications via a dedicated endpoint
The `CalendarSubscriptionScheduler` runs every 6 days to renew subscriptions before they expire (Google Calendar subscriptions expire after 7 days).
### Notification Handling
The `CalendarNotificationsController` provides an endpoint at `/notifications` that receives push notifications from Google Calendar when events change.
## Usage Examples
### Creating a Booking Event
```kotlin
// Inject the CalendarProvider (will be GoogleCalendarProvider when calendar.provider=google)
@Autowired
private lateinit var calendarProvider: CalendarProvider
// Create a booking
val booking = Booking(
id = "", // Will be set by Google Calendar
owner = user,
participants = listOf(participant1, participant2),
workspace = workspace,
beginBooking = startTime,
endBooking = endTime,
recurrence = recurrenceModel // Optional
)
// Save to Google Calendar
val savedBooking = calendarProvider.createEvent(booking)
```
### Subscribing to Calendar Notifications
The subscription process is handled automatically by the `CalendarSubscriptionScheduler`, which runs periodically to ensure subscriptions are active.
## Troubleshooting
### Common Issues
1. **Authentication Failures**: Verify that your credentials file is correctly formatted and has the necessary permissions
2. **Missing Calendar**: Ensure the calendar IDs specified in configuration exist and are accessible
3. **Webhook Errors**: Verify that your application is publicly accessible for receiving push notifications
4. **Rate Limiting**: Google Calendar API has usage limits; implement retries with exponential backoff for high-volume operations
### Debugging
Enable debug logging for Google Calendar related classes:
```yaml
logging:
level:
band.effective.office.backend.feature.booking.calendar.google: DEBUG
band.effective.office.backend.feature.calendar.subscription: DEBUG
```
## Custom Calendar Implementation
The application is designed with flexibility in mind, allowing you to replace the Google Calendar API with your own custom calendar service implementation. This is particularly useful for:
- Development and testing without requiring Google Calendar credentials
- Implementing integration with different calendar services
- Creating a simplified calendar implementation for specific use cases
### Using the Dummy Calendar Provider
The project includes a `dummy-calendar` module that provides a simple in-memory implementation of the `CalendarProvider` interface. This implementation:
- Stores bookings in memory using a ConcurrentHashMap
- Provides all the required functionality without external dependencies
- Is ideal for development, testing, and demonstration purposes
To use the dummy calendar provider instead of Google Calendar:
1. Set the `calendar.provider` property to `dummy` in your application configuration:
```yaml
calendar:
provider: dummy
```
2. No additional configuration is required for the dummy provider
### Creating Your Own Calendar Provider
You can create your own custom calendar service by implementing the `CalendarProvider` interface:
1. Create a new module or package for your implementation
2. Implement the `CalendarProvider` interface with your custom logic
3. Annotate your implementation with `@Component` and `@ConditionalOnProperty`:
```kotlin
@Component("yourCustomCalendarProvider")
@ConditionalOnProperty(name = ["calendar.provider"], havingValue = "custom")
class YourCustomCalendarProvider : CalendarProvider {
// Implement all required methods
}
```
4. Set the `calendar.provider` property to your custom value in the application configuration
The application will automatically use your custom implementation when the appropriate property is set.
## References
- [Google Calendar API Documentation](https://developers.google.com/calendar/api/guides/overview)
- [Push Notifications Guide](https://developers.google.com/calendar/api/guides/push)
- [Recurring Events](https://developers.google.com/calendar/api/concepts/events-calendars#recurring_events)
Поддерживает Markdown
0% или .
You are about to add 0 people to the discussion. Proceed with caution.
Сначала завершите редактирование этого сообщения!
Пожалуйста, зарегистрируйтесь или чтобы прокомментировать