diff --git a/README.md b/README.md index 2a929bd..89c8347 100644 --- a/README.md +++ b/README.md @@ -1,250 +1,391 @@ -# Chamaa API +# Chamaa.API + +

+ + Build Status + + + GitHub Issues + + + License + + + Discord + +

+ +> A community-based lending platform with blockchain integration for transparent and secure loan management in African communities. + +## About + +Chamaa.API is an open-source platform enabling community-driven savings groups (chamas) with transparent ledger systems, blockchain-secured transactions, and mobile-first access. The project implements a full-stack monorepo with a Spring Boot backend and Android mobile application. + +## Features + +- **User Management** - Registration, authentication, and profile management +- **Group Management** - Create and manage community lending groups (chamas) +- **Loan System** - Request, approve, and track loans within groups +- **Wallet & Transactions** - Deposit, withdraw, and transaction history +- **Blockchain Integration** - Polygon network integration for transparent transactions +- **Android Mobile App** - Native Android application with offline support +- **Payment Integration** - M-Pesa, Airtel Money, PayPal support (planned) -A community-based lending platform REST API built with Spring Boot, featuring blockchain integration for secure loan management. +## Project Structure -## Quick Start +``` +chamaa.api/ +├── apps/ +│ ├── backend/ # Spring Boot REST API +│ │ ├── src/main/java/com/chamaa/ +│ │ │ ├── blockchain/ # Blockchain integration (Web3j) +│ │ │ ├── common/ # Shared utilities & exceptions +│ │ │ ├── config/ # Configuration classes +│ │ │ ├── controllers/ # REST API endpoints +│ │ │ ├── entities/ # JPA entities +│ │ │ ├── repositories/ # Data access layer +│ │ │ └── services/ # Business logic +│ │ └── pom.xml +│ │ +│ └── android/ +│ └── ChamaApp/ # Android mobile app +│ └── app/ +│ └── src/main/java/com/example/chama/ +│ ├── network/ # Retrofit + OkHttp client +│ ├── models/ # Data models +│ └── ui/ # Jetpack Compose screens +│ +├── docs/ # Documentation +│ ├── api-spec.md # API specification +│ ├── architecture.md # Architecture overview +│ ├── blockchain.md # Blockchain integration guide +│ ├── DATABASE_SETUP.md # Database configuration +│ ├── DOCKER_GUIDE.md # Docker deployment guide +│ └── CI_CD_PIPELINE.md # CI/CD documentation +│ +├── infra/ # Infrastructure configurations +├── .github/ # GitHub Actions workflows +├── README.md # This file +├── ROADMAP.md # Project roadmap +├── CONTRIBUTING.md # Contribution guidelines +└── LICENSE # MIT License +``` -### Prerequisites -- Java 17+ -- Maven 3.8+ -- PostgreSQL 12+ +## Tech Stack + +### Backend +| Component | Technology | +|-----------|------------| +| Framework | Spring Boot 3.2 | +| Language | Java 17+ | +| Database | PostgreSQL (prod), H2 (dev) | +| ORM | Spring Data JPA / Hibernate | +| Security | Spring Security + Firebase Auth | +| Blockchain | Web3j (Polygon) | +| Build Tool | Maven | + +### Android App +| Component | Technology | +|-----------|------------| +| Language | Kotlin | +| UI Framework | Jetpack Compose | +| Architecture | MVVM | +| Networking | Retrofit 2 + OkHttp | +| Local Database | Room | +| DI | Hilt (planned) | +| Build Tool | Gradle (Kotlin DSL) | + +## Getting Started -### Installation +### Prerequisites -1. Clone the repository: -```bash -git clone https://github.com/flow-pie/chamaa.api -cd chamaa.api -``` +| Tool | Version | Notes | +|------|---------|-------| +| Java | 17+ | Required for backend | +| Maven | 3.8+ | For backend build | +| Android Studio | Ladybug+ | For Android development | +| JDK | 11+ | For Android build | +| Git | 2.0+ | Version control | +| Docker | 24+ | Optional, for containerized deployment | + +### Backend Setup + +1. **Clone the repository** + ```bash + git clone https://github.com/flow-pie/chamaa.api.git + cd chamaa.api + ``` + +2. **Configure environment variables** + ```bash + cp .env.example .env + # Edit .env with your configuration + ``` + +3. **Run the backend** + ```bash + cd apps/backend + ./mvnw spring-boot:run + ``` + + The API will be available at `http://localhost:8080/api` + +4. **Run tests** + ```bash + cd apps/backend + ./mvnw clean test + ``` + +### Android App Setup + +1. **Open in Android Studio** + ``` + apps/android/ChamaApp + ``` + +2. **Build the debug APK** + ```bash + cd apps/android/ChamaApp + ./gradlew assembleDebug + ``` + +3. **Install on emulator/device** + ```bash + ./gradlew installDebug + ``` + + > **Note:** For emulator, the app connects to host machine at `10.0.2.2:8080` + +### Running with Docker -2. Configure environment variables: ```bash -# Copy the example environment file -cp .env.example .env +# Backend only with H2 (development) +docker-compose -f docker-compose.yml -f docker-compose.dev.yml up -# Edit .env with your local configuration -nano .env +# Full stack with PostgreSQL +docker-compose up ``` -3. Build the project: +See [DOCKER_GUIDE.md](docs/DOCKER_GUIDE.md) for detailed Docker configuration. + +## API Reference + +### Users +| Method | Endpoint | Description | +|--------|----------|-------------| +| POST | `/api/users` | Create new user | +| GET | `/api/users/{id}` | Get user by ID | +| GET | `/api/users` | List all users | +| PUT | `/api/users/{id}` | Update user | +| DELETE | `/api/users/{id}` | Delete user | + +### Groups +| Method | Endpoint | Description | +|--------|----------|-------------| +| POST | `/api/groups` | Create new group | +| GET | `/api/groups/{id}` | Get group by ID | +| GET | `/api/groups` | List all groups | +| PUT | `/api/groups/{id}` | Update group | +| DELETE | `/api/groups/{id}` | Delete group | + +### Loans +| Method | Endpoint | Description | +|--------|----------|-------------| +| POST | `/api/loans` | Request loan | +| GET | `/api/loans/{id}` | Get loan by ID | +| GET | `/api/loans` | List all loans | +| PUT | `/api/loans/{id}/approve` | Approve loan | +| PUT | `/api/loans/{id}/reject` | Reject loan | + +### Wallets +| Method | Endpoint | Description | +|--------|----------|-------------| +| GET | `/api/wallets/{userId}` | Get wallet balance | +| POST | `/api/wallets/{userId}/deposit` | Deposit funds | +| POST | `/api/wallets/{userId}/withdraw` | Withdraw funds | +| GET | `/api/wallets/{userId}/transactions` | Transaction history | + +### Request Example + ```bash -./mvnw clean install +# Create a user +curl -X POST http://localhost:8080/api/users \ + -H "Content-Type: application/json" \ + -d '{ + "email": "john@example.com", + "firstName": "John", + "lastName": "Doe", + "phoneNumber": "+254712345678" + }' + +# Create a group +curl -X POST http://localhost:8080/api/groups \ + -H "Content-Type: application/json" \ + -d '{ + "name": "Community Savings", + "description": "Monthly savings group", + "creatorId": 1, + "targetAmount": 10000.0 + }' + +# Request a loan +curl -X POST http://localhost:8080/api/loans \ + -H "Content-Type: application/json" \ + -d '{ + "borrowerId": 1, + "groupId": 1, + "amount": 5000.0, + "durationInMonths": 12, + "purpose": "Business expansion" + }' ``` -4. Run the application: +## Configuration + +### Environment Variables + +| Variable | Description | Default | +|----------|-------------|---------| +| `PORT` | Server port | `8080` | +| `DB_URL` | PostgreSQL connection URL | - | +| `DB_USERNAME` | Database username | - | +| `DB_PASSWORD` | Database password | - | +| `JPA_DDL_AUTO` | JPA schema strategy | `create-drop` | +| `POLYGON_RPC_URL` | Polygon RPC endpoint | - | +| `POLYGON_CHAIN_ID` | Polygon chain ID | `80001` | +| `LOG_LEVEL_ROOT` | Root logging level | `INFO` | + +### Profile-Specific Configuration + ```bash +# Development (H2 in-memory) ./mvnw spring-boot:run + +# Production (PostgreSQL) +SPRING_PROFILES_ACTIVE=prod ./mvnw spring-boot:run ``` -The API will be available at `http://localhost:8080/api` +See [.env.example](.env.example) for all available configuration options. -## Documentation +## Development -- [API Specification](docs/api-spec.md) - Complete API endpoints documentation -- [Architecture](docs/architecture.md) - Project structure and design patterns -- [Blockchain Integration](docs/blockchain.md) - Blockchain service details +### Code Style -## Project Structure +- **Backend**: Follows Spring Boot conventions, Google Java Style +- **Android**: Kotlin coding conventions, Jetpack Compose guidelines -``` -chamaa-api/ -├── pom.xml # Maven configuration -├── src/ -│ ├── main/ -│ │ ├── java/com/chamaa/ -│ │ │ ├── ChamaaApplication.java # Main application entry -│ │ │ ├── config/ # Configuration classes -│ │ │ ├── common/ # Shared utilities -│ │ │ ├── entities/ # JPA entities -│ │ │ ├── repositories/ # Data access layer -│ │ │ ├── services/ # Business logic -│ │ │ ├── controllers/ # REST endpoints -│ │ │ └── blockchain/ # Blockchain services -│ │ └── resources/ -│ │ ├── application.properties # Configuration -│ │ └── db/schema.sql # Database schema -│ └── test/ -│ └── java/com/chamaa/ # Unit tests -├── docs/ -│ ├── api-spec.md # API documentation -│ ├── architecture.md # Architecture guide -│ └── blockchain.md # Blockchain integration -└── README.md -``` +### Running Tests -## 🔧 Configuration +```bash +# Backend unit tests +cd apps/backend +./mvnw test -### Environment Variables -All sensitive configuration is managed through environment variables. Copy `.env.example` to `.env` and configure your values: +# Backend tests with coverage report +./mvnw clean test jacoco:report -```bash -cp .env.example .env -``` +# Run specific test class +./mvnw test -Dtest=UserServiceTest -**Core Environment Variables:** -- `PORT` - Server port (default: 8080) -- `DB_URL` - PostgreSQL connection URL -- `DB_USERNAME` - Database username -- `DB_PASSWORD` - Database password -- `JPA_DDL_AUTO` - JPA DDL strategy (validate, update, create, create-drop) -- `POLYGON_RPC_URL` - Polygon RPC endpoint -- `POLYGON_CHAIN_ID` - Polygon chain ID - -**Logging Levels:** -- `LOG_LEVEL_ROOT` - Root logging level -- `LOG_LEVEL_CHAMAA` - Chamaa application logging level -- `LOG_LEVEL_SPRING_WEB` - Spring Web logging level -- `LOG_LEVEL_HIBERNATE` - Hibernate logging level - -**⚠️ Security Notes:** -- **Never commit `.env` file** - it's excluded in `.gitignore` -- **Always use `.env.example`** for defaults and documentation -- In production, use a secrets manager (Vault, AWS Secrets Manager, etc.) -- Environment variables override `.env` file values - -## Database - -The application uses a sophisticated database setup with support for both development and production environments: - -### Databases Supported -- **PostgreSQL** (Production & Staging) - Relational database with full ACID compliance -- **H2** (Development & Testing) - In-memory database with PostgreSQL mode for compatibility - -### Key Features -- **Spring Data JPA** with Hibernate ORM for object-relational mapping -- **HikariCP** connection pooling for efficient resource management -- **Flyway** database migrations for versioned schema changes -- **Lazy loading** on all relationships to prevent N+1 queries -- **Strategic indexes** on frequently queried columns for performance -- **Cascade/Restrict delete** policies for data integrity - -### Tables -- **users** - User accounts with validation -- **groups** - Community lending groups -- **wallets** - User wallets with balance tracking -- **transactions** - Transaction history between wallets -- **loans** - Loan records within groups - -### Running with Different Databases - -**Development (H2 - Default)** -```bash -./mvnw spring-boot:run -# Uses H2 in-memory database -# Schema auto-created with create-drop strategy +# Run specific test method +./mvnw test -Dtest=UserServiceTest#testCreateUser ``` -**Development (with Docker PostgreSQL)** -```bash -docker-compose -f docker-compose.yml -f docker-compose.dev.yml up -# Starts PostgreSQL in Docker for realistic testing -``` +### Database Schema -**Production (PostgreSQL)** -```bash -SPRING_PROFILES_ACTIVE=prod ./mvnw spring-boot:run -# Requires FLYWAY_ENABLED=true for migration execution -# Uses validate strategy (no auto schema changes) -``` +The application uses the following core entities: +- **User** - User accounts with authentication +- **Group** - Community lending groups +- **Loan** - Loan records within groups +- **Wallet** - User wallet with balance tracking +- **Transaction** - Transaction history -### Database Configuration -- See [DATABASE_SETUP.md](docs/DATABASE_SETUP.md) for comprehensive database documentation -- Configure via environment variables: `DB_URL`, `DB_USERNAME`, `DB_PASSWORD` -- Connection pool settings: `DB_POOL_SIZE`, `DB_MIN_IDLE` +See [DATABASE_SETUP.md](docs/DATABASE_SETUP.md) for detailed schema documentation. -## Security +## Contributing -- Passwords encrypted using BCrypt -- Spring Security integration -- JWT token support (to be implemented) -- API request validation +We welcome contributions! Please read our [Contributing Guidelines](CONTRIBUTING.md) before submitting PRs. -## Testing +### Quick Start for Contributors -Run unit tests: -```bash -./mvnw test -``` +1. Fork the repository +2. Create a feature branch: `git checkout -b feature/your-feature` +3. Make your changes +4. Run tests and ensure code quality +5. Commit with conventional commits: `git commit -m "feat: add new feature"` +6. Push and create a Pull Request -Run all tests with coverage: -```bash -./mvnw clean test jacoco:report -``` +### Issue Labels -### Database Testing -The application includes comprehensive tests with: -- H2 in-memory database for unit tests -- JPA entity mapping validation -- Service layer business logic tests -- All tests use PostgreSQL-compatible H2 mode +| Label | Description | +|-------|-------------| +| `good first issue` | Beginner-friendly tasks | +| `help wanted` | Community assistance needed | +| `backend` | Backend/API work | +| `android` | Android app development | +| `blockchain` | Blockchain integration | +| `documentation` | Docs improvements | -## API Examples +### Commit Message Format + +We follow [Conventional Commits](https://www.conventionalcommits.org/): -### Create User -```bash -POST /api/users -Content-Type: application/json - -{ - "email": "john@example.com", - "password": "password123", - "firstName": "John", - "lastName": "Doe", - "phoneNumber": "+254712345678" -} ``` +(): -### Create Group -```bash -POST /api/groups -Content-Type: application/json - -{ - "name": "Community Savings", - "description": "Group for community savings", - "creatorId": 1, - "targetAmount": 10000.0 -} +Types: feat, fix, docs, style, refactor, test, chore ``` -### Request Loan -```bash -POST /api/loans -Content-Type: application/json - -{ - "borrowerId": 1, - "groupId": 1, - "amount": 5000.0, - "durationInMonths": 12, - "purpose": "Business expansion" -} +Example: +``` +feat(wallet): add transaction history endpoint +fix(api): resolve user authentication bug +docs(readme): update setup instructions ``` -## CI/CD +## Roadmap + +The project is organized into 8 phases. See [ROADMAP.md](ROADMAP.md) for detailed progress and future plans. + +| Phase | Focus | Status | +|-------|-------|--------| +| 1 | Project Setup | Complete | +| 2 | Infrastructure | In Progress | +| 3 | Core API Features | Planned | +| 4 | Blockchain Layer | Planned | +| 5 | Governance & Voting | Planned | +| 6 | Mobile App (Android) | In Progress | +| 7 | DevOps & Scaling | Planned | +| 8 | Long-term Goals | Planned | + +## Resources + +- 📖 [API Documentation](docs/api-spec.md) +- 🏗️ [Architecture Guide](docs/architecture.md) +- ⛓️ [Blockchain Integration](docs/blockchain.md) +- 🐳 [Docker Guide](docs/DOCKER_GUIDE.md) +- 📊 [Database Setup](docs/DATABASE_SETUP.md) +- 🔄 [CI/CD Pipeline](docs/CI_CD_PIPELINE.md) + +## Community + +- 💬 [Discord](https://discord.gg/chamaa) +- 💻 [GitHub Discussions](https://github.com/flow-pie/chamaa.api/discussions) +- 🐛 [Issue Tracker](https://github.com/flow-pie/chamaa.api/issues) -GitHub Actions workflow for: -- Build verification -- Unit tests -- Code quality checks -- Automated deployment +## License -## Blockchain Integration +This project is licensed under the MIT License - see [LICENSE](LICENSE) for details. -Built with Polygon network support via Web3j: -- Smart contract deployment -- Transaction recording -- Loan agreement execution -- Payment verification +## Acknowledgments -## Dependencies +- [Spring Boot](https://spring.io/projects/spring-boot) +- [Jetpack Compose](https://developer.android.com/jetpack/compose) +- [Web3j](https://web3j.io/) +- All contributors and community members -- Spring Boot 3.2.0 -- Spring Data JPA -- Spring Security -- MySQL Connector -- Lombok -- Web3j -- JUnit 5 -- Springdoc OpenAPI (Swagger) +--- +

+ Built with ❤️ by the Chamaa community +

diff --git a/apps/cd b/apps/cd deleted file mode 100644 index e69de29..0000000 diff --git a/apps/dir b/apps/dir deleted file mode 100644 index e69de29..0000000 diff --git a/chamaa.api b/chamaa.api deleted file mode 160000 index 90073e6..0000000 --- a/chamaa.api +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 90073e650a92bec58ee6ee9613428f21925c20de diff --git a/docs/ANDROID.md b/docs/ANDROID.md new file mode 100644 index 0000000..d35e205 --- /dev/null +++ b/docs/ANDROID.md @@ -0,0 +1,301 @@ +# Android App Documentation + +## Overview + +The Chamaa Android app is built with Kotlin and Jetpack Compose, providing a mobile interface for the community lending platform. + +## Technology Stack + +| Component | Technology | +|-----------|------------| +| Language | Kotlin | +| UI Framework | Jetpack Compose | +| Architecture | MVVM | +| Networking | Retrofit 2 + OkHttp | +| JSON Parsing | Gson | +| Local Storage | SharedPreferences (tokens), Room (planned) | +| DI | Manual (planned: Hilt) | +| Min SDK | 26 (Android 8.0) | +| Target SDK | 35 | + +## Project Structure + +``` +apps/android/ChamaApp/ +├── app/ +│ ├── src/main/ +│ │ ├── java/com/example/chama/ +│ │ │ ├── MainActivity.kt # Entry point +│ │ │ ├── network/ # Networking layer +│ │ │ │ ├── RetrofitInstance.kt # Retrofit singleton +│ │ │ │ ├── ApiService.kt # API interface +│ │ │ │ ├── AuthInterceptor.kt # Auth token handler +│ │ │ │ ├── TokenManager.kt # Token storage +│ │ │ │ └── ErrorHandler.kt # Error handling +│ │ │ ├── models/ # Data models +│ │ │ │ ├── BaseResponse.kt # Generic response wrapper +│ │ │ │ ├── UserModel.kt +│ │ │ │ ├── GroupModel.kt +│ │ │ │ └── LoanModel.kt +│ │ │ └── ui/ # UI components +│ │ │ └── theme/ +│ │ └── res/ # Resources +│ └── build.gradle.kts # Dependencies +├── gradle/ +└── build.gradle.kts +``` + +## Network Layer + +### RetrofitInstance + +Singleton Retrofit instance with OkHttp client: + +```kotlin +object RetrofitInstance { + private const val BASE_URL = "http://10.0.2.2:8080/api/" + + private val okHttpClient = OkHttpClient.Builder() + .addInterceptor(AuthInterceptor()) + .addInterceptor(HttpLoggingInterceptor()) + .connectTimeout(30, TimeUnit.SECONDS) + .readTimeout(30, TimeUnit.SECONDS) + .build() + + val api: ApiService by lazy { + Retrofit.Builder() + .baseUrl(BASE_URL) + .client(okHttpClient) + .addConverterFactory(GsonConverterFactory.create()) + .create(ApiService::class.java) + } +} +``` + +### ApiService + +REST API interface: + +```kotlin +interface ApiService { + // Users + @POST("users") + suspend fun createUser(@Body user: UserModel): Response> + + @GET("users/{id}") + suspend fun getUser(@Path("id") id: Long): Response> + + // Groups + @POST("groups") + suspend fun createGroup(@Body group: GroupModel): Response> + + @GET("groups") + suspend fun getGroups(): Response>> + + // Loans + @POST("loans") + suspend fun requestLoan(@Body loan: LoanModel): Response> + + @GET("loans/{id}") + suspend fun getLoan(@Path("id") id: Long): Response> +} +``` + +### AuthInterceptor + +Attaches Firebase ID token to requests: + +```kotlin +class AuthInterceptor : Interceptor { + override fun intercept(chain: Interceptor.Chain): Response { + val request = chain.request() + val token = TokenManager.getToken() + + val newRequest = request.newBuilder() + .header("Authorization", "Bearer $token") + .header("Content-Type", "application/json") + .build() + + return chain.proceed(newRequest) + } +} +``` + +### TokenManager + +Manages authentication tokens using SharedPreferences: + +```kotlin +object TokenManager { + private const val PREF_NAME = "chamaa_prefs" + private const val KEY_TOKEN = "auth_token" + + fun init(context: Context) { ... } + fun saveToken(token: String) { ... } + fun getToken(): String? { ... } + fun clearToken() { ... } +} +``` + +### ErrorHandler + +Standardized error handling: + +```kotlin +object ErrorHandler { + fun handleResponse(response: Response): Result { + return when { + response.isSuccessful -> { ... } + response.code() == 401 -> { ... } // Clear token, prompt re-login + response.code() == 404 -> { ... } + response.code() == 500 -> { ... } + else -> { ... } + } + } +} +``` + +## Data Models + +### BaseResponse + +Generic response wrapper for all API calls: + +```kotlin +data class BaseResponse( + val success: Boolean, + val message: String, + val data: T? = null, + val error: String? = null +) +``` + +### UserModel + +```kotlin +data class UserModel( + val id: Long? = null, + val email: String, + val firstName: String, + val lastName: String, + val phoneNumber: String +) +``` + +### GroupModel + +```kotlin +data class GroupModel( + val id: Long? = null, + val name: String, + val description: String, + val creatorId: Long, + val targetAmount: Double +) +``` + +### LoanModel + +```kotlin +data class LoanModel( + val id: Long? = null, + val borrowerId: Long, + val groupId: Long, + val amount: Double, + val durationInMonths: Int, + val purpose: String +) +``` + +## Setup + +### Prerequisites + +- Android Studio Ladybug+ +- JDK 11+ +- Android SDK 35 + +### Build + +```bash +cd apps/android/ChamaApp +./gradlew assembleDebug +``` + +### Install on Emulator + +```bash +./gradlew installDebug +``` + +### Connect to Backend + +The app connects to `http://10.0.2.2:8080/api/` - this is the Android emulator's alias for the host machine's localhost. + +For physical device testing, use your machine's local IP address. + +## Usage + +### Initialize TokenManager + +In `MainActivity.kt`: + +```kotlin +class MainActivity : ComponentActivity() { + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + TokenManager.init(this) + // ... rest of setup + } +} +``` + +### Making API Calls + +```kotlin +// Example: Fetch groups +suspend fun loadGroups() { + try { + val response = RetrofitInstance.api.getGroups() + val result = ErrorHandler.handleResponse(response) + + result.onSuccess { baseResponse -> + val groups = baseResponse.data + // Update UI + }.onFailure { error -> + // Show error + } + } catch (e: Exception) { + // Handle network error + } +} +``` + +## Dependencies + +```kotlin +// Retrofit +implementation("com.squareup.retrofit2:retrofit:2.9.0") +implementation("com.squareup.retrofit2:converter-gson:2.9.0") + +// OkHttp +implementation("com.squareup.okhttp3:okhttp:4.12.0") +implementation("com.squareup.okhttp3:logging-interceptor:4.12.0") + +// Coroutines +implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3") + +// Room (planned) +implementation("androidx.room:room-runtime:2.6.1") +implementation("androidx.room:room-ktx:2.6.1") +``` + +## Future Enhancements + +- [ ] Hilt dependency injection +- [ ] Room database for offline support +- [ ] Firebase Authentication +- [ ] Push notifications +- [ ] Image upload for profiles +- [ ] Biometric authentication +- [ ] Dark theme support diff --git a/docs/api-spec.md b/docs/api-spec.md index 184a2ef..aef6d10 100644 --- a/docs/api-spec.md +++ b/docs/api-spec.md @@ -1,4 +1,4 @@ -# Chamaa API Specification +# API Specification ## Base URL ``` @@ -6,50 +6,133 @@ http://localhost:8080/api ``` ## Authentication -(To be implemented) + +Firebase Authentication is used for secure API access. Include the Firebase ID token in the Authorization header: + +```bash +Authorization: Bearer +``` ## Endpoints ### Users -- `POST /users` - Create a new user -- `GET /users` - Get all users -- `GET /users/{id}` - Get user by ID -- `GET /users/email/{email}` - Get user by email -- `PUT /users/{id}` - Update user -- `DELETE /users/{id}` - Delete user + +| Method | Endpoint | Description | +|--------|----------|-------------| +| POST | `/api/users` | Create a new user | +| GET | `/api/users` | Get all users | +| GET | `/api/users/{id}` | Get user by ID | +| GET | `/api/users/email/{email}` | Get user by email | +| PUT | `/api/users/{id}` | Update user | +| DELETE | `/api/users/{id}` | Delete user | + +**Request Body (POST /users):** +```json +{ + "email": "user@example.com", + "firstName": "John", + "lastName": "Doe", + "phoneNumber": "+254712345678" +} +``` ### Groups -- `POST /groups` - Create a new group -- `GET /groups` - Get all groups -- `GET /groups/{id}` - Get group by ID -- `GET /groups/creator/{creatorId}` - Get groups by creator -- `GET /groups/active` - Get active groups -- `PUT /groups/{id}` - Update group -- `DELETE /groups/{id}` - Delete group + +| Method | Endpoint | Description | +|--------|----------|-------------| +| POST | `/api/groups` | Create a new group | +| GET | `/api/groups` | Get all groups | +| GET | `/api/groups/{id}` | Get group by ID | +| GET | `/api/groups/creator/{creatorId}` | Get groups by creator | +| GET | `/api/groups/active` | Get active groups | +| PUT | `/api/groups/{id}` | Update group | +| DELETE | `/api/groups/{id}` | Delete group | + +**Request Body (POST /groups):** +```json +{ + "name": "Community Savings", + "description": "Monthly savings group", + "creatorId": 1, + "targetAmount": 10000.0 +} +``` ### Wallets -- `POST /wallets` - Create a new wallet -- `GET /wallets/{id}` - Get wallet by ID -- `GET /wallets/user/{userId}` - Get wallet by user ID -- `PUT /wallets/{id}/balance` - Update wallet balance -- `DELETE /wallets/{id}` - Delete wallet + +| Method | Endpoint | Description | +|--------|----------|-------------| +| POST | `/api/wallets` | Create a new wallet | +| GET | `/api/wallets/{id}` | Get wallet by ID | +| GET | `/api/wallets/user/{userId}` | Get wallet by user ID | +| PUT | `/api/wallets/{id}/balance` | Update wallet balance | +| DELETE | `/api/wallets/{id}` | Delete wallet | ### Loans -- `POST /loans` - Create a new loan -- `GET /loans/{id}` - Get loan by ID -- `GET /loans/borrower/{borrowerId}` - Get loans by borrower -- `GET /loans/group/{groupId}` - Get loans by group -- `GET /loans/status/{status}` - Get loans by status -- `PUT /loans/{id}/approve` - Approve a loan -- `PUT /loans/{id}/reject` - Reject a loan -- `DELETE /loans/{id}` - Delete loan - -## Error Handling -All errors follow this format: + +| Method | Endpoint | Description | +|--------|----------|-------------| +| POST | `/api/loans` | Create a new loan | +| GET | `/api/loans/{id}` | Get loan by ID | +| GET | `/api/loans/borrower/{borrowerId}` | Get loans by borrower | +| GET | `/api/loans/group/{groupId}` | Get loans by group | +| GET | `/api/loans/status/{status}` | Get loans by status | +| PUT | `/api/loans/{id}/approve` | Approve a loan | +| PUT | `/api/loans/{id}/reject` | Reject a loan | +| DELETE | `/api/loans/{id}` | Delete loan | + +**Request Body (POST /loans):** ```json { - "error_code": "ERROR_CODE", - "message": "Error message", - "status_code": 400 + "borrowerId": 1, + "groupId": 1, + "amount": 5000.0, + "durationInMonths": 12, + "purpose": "Business expansion" } ``` + +## Response Formats + +### Success Response +```json +{ + "id": 1, + "email": "user@example.com", + "firstName": "John", + "lastName": "Doe", + "createdAt": "2024-01-01T10:00:00", + "updatedAt": "2024-01-01T10:00:00" +} +``` + +### Error Response +```json +{ + "error": "VALIDATION_ERROR", + "message": "Invalid request", + "status": 400, + "timestamp": "2024-01-01T10:00:00" +} +``` + +### Base Response Wrapper (Android) +```json +{ + "success": true, + "message": "Operation successful", + "data": { ... }, + "error": null +} +``` + +## Status Codes + +| Code | Description | +|------|-------------| +| 200 | OK - Success | +| 201 | Created - Resource created | +| 400 | Bad Request - Invalid input | +| 401 | Unauthorized - Invalid/missing auth | +| 404 | Not Found - Resource doesn't exist | +| 500 | Internal Server Error | diff --git a/docs/architecture.md b/docs/architecture.md index c57f6dd..9e8f345 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,87 +1,187 @@ -# Chamaa API Architecture +# Architecture ## Overview -Chamaa API is a Spring Boot REST API for a community-based lending platform built with: -- Spring Boot 3.2.0 -- Spring Data JPA -- Spring Security -- PostgreSQL Database -- Blockchain Integration (Polygon) + +Chamaa.API is a monorepo containing a Spring Boot backend and Android mobile application. The project uses a modular architecture with clear separation of concerns. + +## Architecture Diagram + +``` +┌─────────────────────────────────────────────────────────────┐ +│ Android App │ +│ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────┐ │ +│ │ UI Layer │ │ ViewModel │ │ Network Layer │ │ +│ │ (Compose) │ │ (MVVM) │ │ (Retrofit+OkHttp) │ │ +│ └─────────────┘ └─────────────┘ └─────────────────────┘ │ +└─────────────────────────────────────────────────────────────┘ + │ + │ HTTP/REST + ▼ +┌─────────────────────────────────────────────────────────────┐ +│ Spring Boot Backend │ +│ ┌─────────────────────────────────────────────────────┐ │ +│ │ Controllers │ │ +│ │ User │ Group │ Loan │ Wallet │ Admin │ │ +│ └─────────────────────────────────────────────────────┘ │ +│ ┌─────────────────────────────────────────────────────┐ │ +│ │ Services │ │ +│ │ UserService │ GroupService │ LoanService │ ... │ │ +│ └─────────────────────────────────────────────────────┘ │ +│ ┌─────────────────────────────────────────────────────┐ │ +│ │ Repositories (JPA) │ │ +│ └─────────────────────────────────────────────────────┘ │ +│ ┌─────────────┐ ┌─────────────┐ ┌──────────────────┐ │ +│ │ PostgreSQL │ │ Firebase │ │ Polygon │ │ +│ │ Database │ │ Authentication│ │ Blockchain │ │ +│ └─────────────┘ └─────────────┘ └──────────────────┘ │ +└─────────────────────────────────────────────────────────────┘ +``` ## Project Structure +### Backend (`apps/backend/`) + +``` +apps/backend/ +├── src/main/java/com/chamaa/ +│ ├── ChamaaApplication.java # Application entry point +│ ├── config/ # Configuration classes +│ │ ├── DatabaseConfig.java # Database configuration +│ │ ├── SecurityConfig.java # Security & CORS config +│ │ ├── FirebaseConfig.java # Firebase setup +│ │ └── AppProperties.java # App properties +│ ├── controllers/ # REST API controllers +│ │ ├── UserController.java +│ │ ├── GroupController.java +│ │ ├── LoanController.java +│ │ └── WalletController.java +│ ├── services/ # Business logic +│ │ ├── UserService.java +│ │ ├── GroupService.java +│ │ ├── LoanService.java +│ │ ├── WalletService.java +│ │ └── FirebaseTokenVerificationService.java +│ ├── repositories/ # Data access layer +│ ├── entities/ # JPA entities +│ │ ├── User.java +│ │ ├── Group.java +│ │ ├── Loan.java +│ │ ├── Wallet.java +│ │ └── Transaction.java +│ ├── blockchain/ # Blockchain integration +│ │ ├── BlockchainService.java +│ │ ├── ContractService.java +│ │ └── PolygonService.java +│ └── common/ # Shared utilities +│ ├── exceptions/ +│ └── utils/ +└── src/main/resources/ + └── application.properties +``` + +### Android App (`apps/android/ChamaApp/`) + ``` -src/ -├── main/ -│ ├── java/com/chamaa/ -│ │ ├── ChamaaApplication.java # Entry point -│ │ ├── config/ # Configuration classes -│ │ ├── common/ # Shared utilities -│ │ ├── entities/ # JPA entities -│ │ ├── repositories/ # Data access layer -│ │ ├── services/ # Business logic -│ │ ├── controllers/ # REST endpoints -│ │ └── blockchain/ # Blockchain services -│ └── resources/ -│ ├── application.properties # App configuration -│ └── db/schema.sql # Database schema -└── test/ - └── java/com/chamaa/ # Unit tests +apps/android/ChamaApp/app/ +├── src/main/java/com/example/chama/ +│ ├── MainActivity.kt # Entry point +│ ├── network/ # Networking +│ │ ├── RetrofitInstance.kt # Retrofit setup +│ │ ├── ApiService.kt # API interface +│ │ ├── AuthInterceptor.kt # Auth token interceptor +│ │ ├── TokenManager.kt # Token storage +│ │ └── ErrorHandler.kt # Error handling +│ ├── models/ # Data models +│ │ ├── BaseResponse.kt +│ │ ├── UserModel.kt +│ │ ├── GroupModel.kt +│ │ └── LoanModel.kt +│ └── ui/ # UI screens +│ └── theme/ +└── build.gradle.kts # Dependencies ``` ## Design Patterns -### Layered Architecture -- **Controllers**: Handle HTTP requests/responses -- **Services**: Implement business logic -- **Repositories**: Manage database access -- **Entities**: Represent domain models +### Backend -### Key Features -- JPA Auditing (createdAt, updatedAt timestamps) -- Password encryption using BCrypt -- RESTful API design -- Transactional operations -- Database relationships with proper foreign keys +| Pattern | Usage | +|---------|-------| +| **Layered Architecture** | Controllers → Services → Repositories → Entities | +| **Dependency Injection** | Spring IoC container | +| **Repository Pattern** | Data access abstraction | +| **Service Layer** | Business logic encapsulation | -## Technology Stack -- **Framework**: Spring Boot 3.2.0 -- **ORM**: Hibernate/JPA -- **Database**: PostgreSQL 12+ -- **Authentication**: Spring Security (BCrypt) -- **Blockchain**: Web3j (Polygon integration) -- **Testing**: JUnit 5 -- **Build**: Maven 3.8+ +### Android + +| Pattern | Usage | +|---------|-------| +| **MVVM** | Model-View-ViewModel | +| **Repository Pattern** | Data abstraction layer | +| **Interceptor** | Network request/response handling | +| **Lazy Initialization** | Retrofit singleton | + +## Security + +### Authentication Flow +1. User authenticates via Firebase (Android app) +2. Firebase returns ID token +3. App includes token in API requests: `Authorization: Bearer ` +4. Backend validates token via Firebase Admin SDK +5. Request processed with authenticated user context + +### Security Configuration +- CORS enabled for mobile app origins +- Firebase Authentication required for all endpoints +- BCrypt password encryption (where applicable) +- Input validation on all endpoints ## Database Schema +### Entity Relationships + +``` +User (1) ─────< (N) Group +User (1) ─────< (N) Loan +User (1) ──1:1< Wallet +Group (1) ───< (N) Loan +Wallet (1) ──< (N) Transaction +``` + ### Tables -- **users**: User accounts and profiles -- **groups**: Community groups for lending +- **users**: User accounts +- **groups**: Community lending groups +- **loans**: Loan records with status tracking - **wallets**: User wallet balances - **transactions**: Transaction history -- **loans**: Loan records with status tracking -## API Response Format - -### Success Response -```json -{ - "id": 1, - "email": "user@example.com", - "firstName": "John", - "lastName": "Doe", - "createdAt": "2024-01-01T10:00:00", - "updatedAt": "2024-01-01T10:00:00" -} -``` +## Technology Stack -### Error Response -```json -{ - "error_code": "VALIDATION_ERROR", - "message": "Invalid request", - "status_code": 400, - "timestamp": "2024-01-01T10:00:00" -} -``` +| Layer | Technology | +|-------|------------| +| Backend Framework | Spring Boot 3.2 | +| Language | Java 17+ | +| Database | PostgreSQL / H2 (dev) | +| ORM | Spring Data JPA / Hibernate | +| Authentication | Firebase Auth | +| Blockchain | Web3j (Polygon) | +| Android UI | Jetpack Compose | +| Android Networking | Retrofit 2 + OkHttp | +| Android Database | Room | +| Build (Backend) | Maven | +| Build (Android) | Gradle (Kotlin DSL) | + +## Configuration + +### Backend +Configuration via `application.properties` and environment variables: +- Database connection (JDBC URL, credentials) +- Server port +- Firebase project settings +- Blockchain RPC endpoints +- Logging levels + +### Android +- BASE_URL points to backend (`http://10.0.2.2:8080/api`) +- Gson for JSON serialization +- SharedPreferences for token storage diff --git a/docs/blockchain.md b/docs/blockchain.md index 8d475f6..16a26b3 100644 --- a/docs/blockchain.md +++ b/docs/blockchain.md @@ -1,59 +1,157 @@ # Blockchain Integration ## Overview -Chamaa API integrates with the Polygon blockchain for: -- Smart contract deployment -- Transaction recording -- Loan agreement execution -- Payment verification + +Chamaa.API integrates with the Polygon blockchain to provide transparent, immutable transaction records for loan agreements and payments. + +## Why Polygon? + +- Low transaction fees compared to Ethereum mainnet +- Fast confirmation times +- EVM-compatible for easy integration +- Testnet (Amoy) available for development + +## Architecture + +``` +┌─────────────────┐ ┌──────────────────┐ ┌─────────────┐ +│ LoanService │────>│ ContractService │────>│ Polygon │ +│ (Business) │ │ (Contract mgmt) │ │ (Network) │ +└─────────────────┘ └──────────────────┘ └─────────────┘ + │ + ▼ + ┌─────────────┐ + │ Web3j │ + │ (SDK) │ + └─────────────┘ +``` ## Services ### BlockchainService -Handles low-level blockchain operations: -- `submitTransaction(from, to, amount)` - Submit blockchain transaction -- `getBalance(walletAddress)` - Get wallet balance -- `deployContract(code)` - Deploy smart contract -- `callContractFunction(address, function, params)` - Call contract function + +Low-level blockchain operations: + +```java +public interface BlockchainService { + String submitTransaction(String from, String to, BigDecimal amount); + BigDecimal getBalance(String walletAddress); + String deployContract(String abi, String bytecode, List params); + String callContractFunction(String contractAddress, String function, List params); +} +``` ### ContractService + Manages loan-specific smart contracts: -- `deployLoanContract(group, amount, duration)` - Deploy loan contract -- `recordLoanPayment(contract, amount)` - Record payment -- `getLoanBalance(contract)` - Get loan balance + +```java +public interface ContractService { + String deployLoanContract(Group group, BigDecimal amount, int durationMonths); + String recordLoanPayment(String contractAddress, BigDecimal amount); + BigDecimal getLoanBalance(String contractAddress); + boolean verifyPayment(String txHash); +} +``` ### PolygonService -Polygon network specific operations: -- `getNetworkStatus()` - Check network status -- `estimateGasFee()` - Estimate transaction fees -- `submitTransactionToPolygon(txData)` - Submit to Polygon + +Polygon network-specific operations: + +```java +public interface PolygonService { + NetworkStatus getNetworkStatus(); + BigDecimal estimateGasFee(String txData); + String submitTransaction(TransactionData txData); + String getTransactionReceipt(String txHash); +} +``` ## Configuration Add to `application.properties`: + ```properties +# Polygon Configuration blockchain.polygon.rpc-url=https://polygon-rpc.com blockchain.polygon.chain-id=137 +blockchain.polygon.private-key=${POLYGON_PRIVATE_KEY} + +# For testnet +blockchain.polygon.rpc-url=https://rpc-amoy.polygon.technology +blockchain.polygon.chain-id=80001 ``` ## Integration Points ### Loan Creation Flow + +``` 1. User requests loan → LoanController -2. LoanService creates Loan entity -3. ContractService deploys smart contract -4. BlockchainService records on chain -5. Transaction recorded in database +2. LoanService validates and creates Loan entity +3. ContractService deploys loan smart contract +4. BlockchainService submits deployment transaction +5. Contract address stored with Loan record +6. Response returned to client +``` ### Payment Processing + +``` 1. Payment initiated → WalletService -2. BlockchainService validates balance -3. ContractService records payment -4. Transaction status updated in DB +2. Transaction recorded in database +3. BlockchainService validates/records on-chain +4. ContractService updates loan status +5. Both DB and blockchain in sync +``` + +## Smart Contract (Future) + +Planned smart contract features: + +```solidity +// Planned: Loan Agreement Contract +contract LoanAgreement { + address borrower; + address lender; + uint256 amount; + uint256 duration; + uint256 installmentsPaid; + + function makePayment() external; + function calculatePenalty() public view returns (uint256); + function getRemainingBalance() public view returns (uint256); +} +``` + +## Development + +### Setting Up + +1. Create Polygon wallet +2. Get MATIC tokens (testnet for development) +3. Configure private key in environment +4. Use Amoy testnet for development + +### Testing + +```bash +# Deploy to testnet +./mvnw spring-boot:run -Dspring-boot.run.arguments=--blockchain.polygon.rpc-url=https://rpc-amoy.polygon.technology +``` ## Future Enhancements -- Implement smart contract ABI parsing -- Add transaction fee optimization -- Implement async transaction polling -- Add blockchain event listeners -- Integrate with Web3j properly + +- [ ] Smart contract for automatic loan disbursement +- [ ] On-chain voting for loan approval +- [ ] Automated penalty enforcement +- [ ] Event listeners for real-time updates +- [ ] Transaction fee optimization +- [ ] Multi-signature wallet support + +## Security Considerations + +- Private keys stored as environment variables +- Transaction signing happens server-side +- Non-custodial - user funds stay in their wallets +- Audit trails both on-chain and in database diff --git a/fake-firebase.json b/fake-firebase.json deleted file mode 100644 index 10efbb3..0000000 --- a/fake-firebase.json +++ /dev/null @@ -1,8 +0,0 @@ -{ "type": "service_account", - "project_id": "chamaa-dev", - "private_key_id": "fake", - "private_key": "-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEA2a2rwplBQLzHPZe5TNJT5sGqbCMBOp0cGkBGmDHMbcBWvhbl\nMIIEowIBAAKCAQEA2a2rwplBQLzHPZe5TNJT5sGqbCMBOp0cGkBGmDHMbcBWvhbl\n-----END RSA PRIVATE KEY-----\n", - "client_email": "fake@chamaa-dev.iam.gserviceaccount.com", - "client_id": "123456789", - "auth_uri": "https://accounts.google.com/o/oauth2/auth", - "token_uri": "https://oauth2.googleapis.com/token"}