diff --git a/MOBILE_APP_INTEGRATION.md b/MOBILE_APP_INTEGRATION.md new file mode 100644 index 000000000..3e429df70 --- /dev/null +++ b/MOBILE_APP_INTEGRATION.md @@ -0,0 +1,218 @@ +# Mobile App Integration with Java Backend + +## Overview +This document describes how the Flutter mobile app integrates with both Supabase Authentication and the Java backend for user registration and authentication. + +## Registration Flow + +### 1. User Sign Up Process +1. **User enters email and password** in the Flutter app (`auth_screen.dart`) +2. **Sign up with Supabase** - User account is created in Supabase Authentication +3. **Password temporarily stored** - Password is saved in SharedPreferences for Java backend registration +4. **Email verification sent** - Supabase sends OTP to user's email +5. **User verifies email** - User enters OTP in verification screen +6. **Java backend registration** - After successful verification, user is automatically registered in Java backend +7. **Clean up** - Temporary password is removed from SharedPreferences +8. **Navigate to profile setup** - User proceeds to complete their profile + +### 2. Sign In Process +- User signs in with Supabase credentials +- Java backend login is optional (only if accessing Java backend APIs) +- Token from Java backend can be stored for subsequent API calls + +## Implementation Details + +### Files Modified + +#### 1. **JavaAuthService** (`lib/services/java_auth_service.dart`) +New service created to handle Java backend authentication: +- `registerUser()` - Registers user in Java backend +- `login()` - Logs into Java backend (optional) +- `getCaptcha()` - Returns bypass token for mobile apps +- `checkUserExists()` - Checks if user exists in Java backend + +#### 2. **Email Verification Screen** (`lib/screens/email_verification_screen.dart`) +Modified to include Java backend registration after email verification: +```dart +// After successful Supabase verification +final javaAuthService = JavaAuthService(); +final password = prefs.getString('temp_password_${widget.email}'); +if (password != null) { + await javaAuthService.registerUser( + email: widget.email, + password: password, + ); +} +``` + +#### 3. **Auth Screen** (`lib/screens/auth_screen.dart`) +Modified to temporarily store password: +```dart +// Store password for Java backend registration +final prefs = await SharedPreferences.getInstance(); +await prefs.setString('temp_password_$email', password); +``` + +#### 4. **Java Backend Captcha Service** (`CaptchaServiceImpl.java`) +Modified to accept mobile app bypass token: +```java +if ("MOBILE_APP_BYPASS".equals(code)) { + return true; // Mobile apps bypass captcha +} +``` + +## Configuration + +### Update Base URL +In `lib/services/java_auth_service.dart`, update the base URL: +```dart +// For local development +static const String baseUrl = 'http://localhost:8002/xiaozhi'; + +// For production (replace with your server URL) +static const String baseUrl = 'https://your-server.com/xiaozhi'; +``` + +### For iOS (local development) +If testing on iOS simulator with localhost: +```dart +static const String baseUrl = 'http://127.0.0.1:8002/xiaozhi'; +``` + +### For Android (local development) +If testing on Android emulator: +```dart +static const String baseUrl = 'http://10.0.2.2:8002/xiaozhi'; +``` + +### For physical devices (local development) +Use your machine's IP address: +```dart +static const String baseUrl = 'http://192.168.1.240:8002/xiaozhi'; +``` + +## Security Considerations + +### 1. Captcha Bypass +The current implementation uses a simple bypass token (`MOBILE_APP_BYPASS`) for mobile apps. In production, consider: +- Adding API key validation +- Implementing device fingerprinting +- Using OAuth2 or JWT tokens +- Rate limiting by device/IP + +### 2. Password Storage +Passwords are temporarily stored in SharedPreferences. Consider: +- Using Flutter Secure Storage for sensitive data +- Encrypting the password before storage +- Clearing the password immediately after use + +### 3. HTTPS +Always use HTTPS in production: +- Update all URLs to use `https://` +- Implement certificate pinning for additional security + +## API Endpoints Used + +### Registration +```bash +POST /xiaozhi/user/register +{ + "username": "user@example.com", + "password": "password123", + "captcha": "MOBILE_APP_BYPASS", + "captchaId": "uuid-here" +} +``` + +### Login (Optional) +```bash +POST /xiaozhi/user/login +{ + "username": "user@example.com", + "password": "password123", + "captcha": "MOBILE_APP_BYPASS", + "captchaId": "uuid-here" +} +``` + +## Testing + +### 1. Run Flutter App +```bash +cd flutter-mobile-app +flutter pub get +flutter run +``` + +### 2. Test Registration Flow +1. Create new account with email/password +2. Check console logs for: + - "✅ User registered in both Supabase and Java backend" +3. Verify user exists in both: + - Supabase Dashboard + - MySQL database (sys_user table) + +### 3. Common Issues + +#### Issue: Connection refused +**Solution**: Check that Java backend is running and accessible from your device + +#### Issue: Captcha validation failed +**Solution**: Ensure CaptchaServiceImpl.java has the bypass code + +#### Issue: User already exists +**Solution**: This is handled gracefully - the app will proceed even if user exists in Java backend + +## Future Improvements + +1. **Token Management** + - Implement proper token storage and refresh + - Use Java backend token for protected APIs + +2. **Error Handling** + - Add retry logic for network failures + - Implement offline mode support + +3. **Security Enhancements** + - Add device-specific tokens + - Implement biometric authentication + - Add 2FA support + +4. **Profile Sync** + - Sync user profiles between Supabase and Java backend + - Handle profile updates across both systems + +## Dependencies Added + +```yaml +# pubspec.yaml +dependencies: + uuid: ^4.5.1 # For generating UUIDs + shared_preferences: ^2.2.2 # Already existed +``` + +## Troubleshooting + +### Check Java Backend Logs +```bash +tail -f main/manager-api/logs/xiaozhi-esp32-api.log +``` + +### Test API Directly +```bash +# Test registration endpoint +curl -X POST "http://localhost:8002/xiaozhi/user/register" \ + -H "Content-Type: application/json" \ + -d '{ + "username": "test@example.com", + "password": "password123", + "captcha": "MOBILE_APP_BYPASS", + "captchaId": "test-uuid" + }' +``` + +### Verify Database Entry +```sql +-- Check if user was created in MySQL +SELECT * FROM sys_user WHERE username = 'test@example.com'; +``` \ No newline at end of file diff --git a/main/manager-api/API_ENDPOINTS.md b/main/manager-api/API_ENDPOINTS.md new file mode 100644 index 000000000..019cf50de --- /dev/null +++ b/main/manager-api/API_ENDPOINTS.md @@ -0,0 +1,671 @@ +# Cheeko Server Manager API Endpoints + +## Base Configuration +```bash +# Set base URL and token variables +BASE_URL="http://localhost:8002/xiaozhi" +TOKEN="your-auth-token-here" + +# For authenticated requests, add header: -H "token: $TOKEN" +``` + +## Authentication & User Management + +### Login Controller +```bash +# Get captcha +curl -X GET "$BASE_URL/user/captcha" + +# Send SMS verification code +curl -X POST "$BASE_URL/user/smsVerification" \ + -H "Content-Type: application/json" \ + -d '{"mobile": "1234567890"}' + +# User login +curl -X POST "$BASE_URL/user/login" \ + -H "Content-Type: application/json" \ + -d '{"mobile": "1234567890", "password": "password123", "captcha": "captcha_code", "uuid": "captcha_uuid"}' + +# User registration (now returns token like login) +curl -X POST "$BASE_URL/user/register" \ + -H "Content-Type: application/json" \ + -d '{"mobile": "1234567890", "password": "password123", "verificationCode": "123456"}' + +# Get user info +curl -X GET "$BASE_URL/user/info" \ + -H "token: $TOKEN" + +# Change password +curl -X PUT "$BASE_URL/user/change-password" \ + -H "token: $TOKEN" \ + -H "Content-Type: application/json" \ + -d '{"oldPassword": "old_password", "newPassword": "new_password"}' + +# Retrieve password (forgot password) +curl -X PUT "$BASE_URL/user/retrieve-password" \ + -H "Content-Type: application/json" \ + -d '{"mobile": "1234567890", "newPassword": "new_password", "verificationCode": "123456"}' + +# Get public configuration +curl -X GET "$BASE_URL/user/pub-config" +``` + +## Agent Management + +### Agent Controller +```bash +# Get user's agent list +curl -X GET "$BASE_URL/agent/list" \ + -H "token: $TOKEN" + +# Get all agents (admin only) +curl -X GET "$BASE_URL/agent/all" \ + -H "token: $TOKEN" + +# Get agent by ID +curl -X GET "$BASE_URL/agent/{id}" \ + -H "token: $TOKEN" + +# Create new agent +curl -X POST "$BASE_URL/agent" \ + -H "token: $TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "Agent Name", + "prompt": "Agent prompt", + "llm": "LLM model", + "tts": "TTS model", + "asr": "ASR model", + "vad": "VAD model" + }' + +# Update agent memory by device ID +curl -X PUT "$BASE_URL/agent/saveMemory/{macAddress}" \ + -H "token: $TOKEN" \ + -H "Content-Type: application/json" \ + -d '{"memory": "updated memory content"}' + +# Update agent +curl -X PUT "$BASE_URL/agent/{id}" \ + -H "token: $TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "Updated Agent Name", + "prompt": "Updated prompt" + }' + +# Delete agent +curl -X DELETE "$BASE_URL/agent/{id}" \ + -H "token: $TOKEN" + +# Get agent templates +curl -X GET "$BASE_URL/agent/template" \ + -H "token: $TOKEN" + +# Get agent sessions +curl -X GET "$BASE_URL/agent/{id}/sessions" \ + -H "token: $TOKEN" + +# Get agent chat history +curl -X GET "$BASE_URL/agent/{id}/chat-history/{sessionId}" \ + -H "token: $TOKEN" + +# Get recent 50 chat messages for user +curl -X GET "$BASE_URL/agent/{id}/chat-history/user" \ + -H "token: $TOKEN" + +# Get audio content by audio ID +curl -X GET "$BASE_URL/agent/{id}/chat-history/audio?audioId={audioId}" \ + -H "token: $TOKEN" + +# Get audio download ID +curl -X POST "$BASE_URL/agent/audio/{audioId}" \ + -H "token: $TOKEN" + +# Play audio +curl -X GET "$BASE_URL/agent/play/{uuid}" \ + -H "token: $TOKEN" +``` + +### Agent Chat History Controller +```bash +# Upload chat history file +curl -X POST "$BASE_URL/agent/chat-history/report" \ + -H "token: $TOKEN" \ + -F "file=@/path/to/chat_history.json" \ + -F "deviceId=device123" +``` + +### Agent MCP Access Point Controller +```bash +# Get agent MCP access address +curl -X GET "$BASE_URL/agent/mcp/address/{agentId}" \ + -H "token: $TOKEN" + +# Get agent MCP tools list +curl -X GET "$BASE_URL/agent/mcp/tools/{agentId}" \ + -H "token: $TOKEN" +``` + +### Agent Voice Print Controller +```bash +# Create voice print +curl -X POST "$BASE_URL/agent/voice-print" \ + -H "token: $TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "agentId": 1, + "name": "Voice Print Name", + "voiceData": "base64_encoded_voice_data" + }' + +# Update voice print +curl -X PUT "$BASE_URL/agent/voice-print" \ + -H "token: $TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "id": 1, + "name": "Updated Voice Print", + "voiceData": "updated_base64_voice_data" + }' + +# Delete voice print +curl -X DELETE "$BASE_URL/agent/voice-print/{id}" \ + -H "token: $TOKEN" + +# Get voice prints for agent +curl -X GET "$BASE_URL/agent/voice-print/list/{agentId}" \ + -H "token: $TOKEN" +``` + +## Device Management + +### Device Controller +```bash +# Bind device to agent +curl -X POST "$BASE_URL/device/bind/{agentId}/{deviceCode}" \ + -H "token: $TOKEN" + +# Register device +curl -X POST "$BASE_URL/device/register" \ + -H "Content-Type: application/json" \ + -d '{ + "deviceId": "device123", + "type": "ESP32", + "firmwareVersion": "1.0.0" + }' + +# Get user's bound devices +curl -X GET "$BASE_URL/device/bind/{agentId}" \ + -H "token: $TOKEN" + +# Unbind device +curl -X POST "$BASE_URL/device/unbind" \ + -H "token: $TOKEN" \ + -H "Content-Type: application/json" \ + -d '{"deviceId": "device123", "agentId": 1}' + +# Update device info +curl -X PUT "$BASE_URL/device/update/{id}" \ + -H "token: $TOKEN" \ + -H "Content-Type: application/json" \ + -d '{"name": "New Device Name", "description": "Updated description"}' + +# Manually add device +curl -X POST "$BASE_URL/device/manual-add" \ + -H "token: $TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "deviceId": "manual_device_123", + "name": "Manual Device", + "type": "ESP32" + }' +``` + +### OTA Controller +```bash +# Check OTA version and activation status +curl -X POST "$BASE_URL/ota/" \ + -H "Content-Type: application/json" \ + -d '{ + "deviceId": "device123", + "currentVersion": "1.0.0", + "type": "ESP32" + }' + +# Quick check device activation status +curl -X POST "$BASE_URL/ota/activate" \ + -H "Content-Type: application/json" \ + -d '{"deviceId": "device123"}' + +# Get OTA status info +curl -X GET "$BASE_URL/ota/" +``` + +### OTA Management Controller +```bash +# Get OTA firmware list (paginated) +curl -X GET "$BASE_URL/otaMag?page=1&limit=10" \ + -H "token: $TOKEN" + +# Get OTA firmware by ID +curl -X GET "$BASE_URL/otaMag/{id}" \ + -H "token: $TOKEN" + +# Save new OTA firmware info +curl -X POST "$BASE_URL/otaMag" \ + -H "token: $TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "version": "2.0.0", + "type": "ESP32", + "description": "New firmware version", + "url": "http://example.com/firmware.bin" + }' + +# Delete OTA firmware +curl -X DELETE "$BASE_URL/otaMag/{id}" \ + -H "token: $TOKEN" + +# Update OTA firmware info +curl -X PUT "$BASE_URL/otaMag/{id}" \ + -H "token: $TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "version": "2.0.1", + "description": "Updated firmware" + }' + +# Get firmware download URL +curl -X GET "$BASE_URL/otaMag/getDownloadUrl/{id}" \ + -H "token: $TOKEN" + +# Download firmware file +curl -X GET "$BASE_URL/otaMag/download/{uuid}" \ + -o firmware.bin + +# Upload firmware file +curl -X POST "$BASE_URL/otaMag/upload" \ + -H "token: $TOKEN" \ + -F "file=@/path/to/firmware.bin" \ + -F "version=2.0.0" \ + -F "type=ESP32" +``` + +## Model Management + +### Model Controller +```bash +# Get all model names +curl -X GET "$BASE_URL/models/names" \ + -H "token: $TOKEN" + +# Get LLM model codes +curl -X GET "$BASE_URL/models/llm/names" \ + -H "token: $TOKEN" + +# Get model providers for type +curl -X GET "$BASE_URL/models/{modelType}/provideTypes" \ + -H "token: $TOKEN" + +# Get model configuration list +curl -X GET "$BASE_URL/models/list" \ + -H "token: $TOKEN" + +# Add model configuration +curl -X POST "$BASE_URL/models/{modelType}/{provideCode}" \ + -H "token: $TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "Model Name", + "apiKey": "api_key_here", + "config": {"temperature": 0.7} + }' + +# Edit model configuration +curl -X PUT "$BASE_URL/models/{modelType}/{provideCode}/{id}" \ + -H "token: $TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "Updated Model", + "config": {"temperature": 0.8} + }' + +# Delete model configuration +curl -X DELETE "$BASE_URL/models/{id}" \ + -H "token: $TOKEN" + +# Get model configuration +curl -X GET "$BASE_URL/models/{id}" \ + -H "token: $TOKEN" + +# Enable/disable model +curl -X PUT "$BASE_URL/models/enable/{id}/{status}" \ + -H "token: $TOKEN" + +# Set default model +curl -X PUT "$BASE_URL/models/default/{id}" \ + -H "token: $TOKEN" + +# Get model voices +curl -X GET "$BASE_URL/models/{modelId}/voices" \ + -H "token: $TOKEN" +``` + +### Model Provider Controller +```bash +# Get model providers (paginated) +curl -X GET "$BASE_URL/models/provider?page=1&limit=10" \ + -H "token: $TOKEN" + +# Add model provider +curl -X POST "$BASE_URL/models/provider" \ + -H "token: $TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "Provider Name", + "code": "provider_code", + "type": "LLM" + }' + +# Edit model provider +curl -X PUT "$BASE_URL/models/provider" \ + -H "token: $TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "id": 1, + "name": "Updated Provider" + }' + +# Delete model provider +curl -X POST "$BASE_URL/models/provider/delete" \ + -H "token: $TOKEN" \ + -H "Content-Type: application/json" \ + -d '{"ids": [1, 2, 3]}' + +# Get plugin names +curl -X GET "$BASE_URL/models/provider/plugin/names" \ + -H "token: $TOKEN" +``` + +## Configuration + +### Config Controller +```bash +# Get server configuration +curl -X POST "$BASE_URL/config/server-base" \ + -H "Content-Type: application/json" \ + -d '{"deviceId": "device123"}' + +# Get agent models +curl -X POST "$BASE_URL/config/agent-models" \ + -H "Content-Type: application/json" \ + -d '{"agentId": 1}' +``` + +## TTS Voice/Timbre Management + +### Timbre Controller +```bash +# Get timbre list (paginated) +curl -X GET "$BASE_URL/ttsVoice?page=1&limit=10" \ + -H "token: $TOKEN" + +# Save new timbre +curl -X POST "$BASE_URL/ttsVoice" \ + -H "token: $TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "Voice Name", + "voiceId": "voice_123", + "provider": "elevenlabs" + }' + +# Update timbre +curl -X PUT "$BASE_URL/ttsVoice/{id}" \ + -H "token: $TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "Updated Voice Name" + }' + +# Delete timbre +curl -X POST "$BASE_URL/ttsVoice/delete" \ + -H "token: $TOKEN" \ + -H "Content-Type: application/json" \ + -d '{"ids": [1, 2, 3]}' +``` + +## Admin Functions + +### Admin Controller +```bash +# Get users (paginated) +curl -X GET "$BASE_URL/admin/users?page=1&limit=10" \ + -H "token: $TOKEN" + +# Reset user password +curl -X PUT "$BASE_URL/admin/users/{id}" \ + -H "token: $TOKEN" \ + -H "Content-Type: application/json" \ + -d '{"password": "new_password"}' + +# Delete user +curl -X DELETE "$BASE_URL/admin/users/{id}" \ + -H "token: $TOKEN" + +# Batch change user status +curl -X PUT "$BASE_URL/admin/users/changeStatus/{status}" \ + -H "token: $TOKEN" \ + -H "Content-Type: application/json" \ + -d '{"userIds": [1, 2, 3]}' + +# Get all devices (paginated) +curl -X GET "$BASE_URL/admin/device/all?page=1&limit=10" \ + -H "token: $TOKEN" +``` + +### Server Side Management Controller +```bash +# Get WebSocket server list +curl -X GET "$BASE_URL/admin/server/server-list" \ + -H "token: $TOKEN" + +# Notify Python server to update config +curl -X POST "$BASE_URL/admin/server/emit-action" \ + -H "token: $TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "action": "UPDATE_CONFIG", + "payload": {"config": "value"} + }' +``` + +### System Dictionary Data Controller +```bash +# Get dictionary data (paginated) +curl -X GET "$BASE_URL/admin/dict/data/page?page=1&limit=10" \ + -H "token: $TOKEN" + +# Get dictionary data by ID +curl -X GET "$BASE_URL/admin/dict/data/{id}" \ + -H "token: $TOKEN" + +# Save dictionary data +curl -X POST "$BASE_URL/admin/dict/data/save" \ + -H "token: $TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "dictType": "status", + "dictLabel": "Active", + "dictValue": "1" + }' + +# Update dictionary data +curl -X PUT "$BASE_URL/admin/dict/data/update" \ + -H "token: $TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "id": 1, + "dictLabel": "Updated Label" + }' + +# Delete dictionary data +curl -X POST "$BASE_URL/admin/dict/data/delete" \ + -H "token: $TOKEN" \ + -H "Content-Type: application/json" \ + -d '{"ids": [1, 2, 3]}' + +# Get dictionary data by type +curl -X GET "$BASE_URL/admin/dict/data/type/{dictType}" \ + -H "token: $TOKEN" +``` + +### System Dictionary Type Controller +```bash +# Get dictionary types (paginated) +curl -X GET "$BASE_URL/admin/dict/type/page?page=1&limit=10" \ + -H "token: $TOKEN" + +# Get dictionary type by ID +curl -X GET "$BASE_URL/admin/dict/type/{id}" \ + -H "token: $TOKEN" + +# Save dictionary type +curl -X POST "$BASE_URL/admin/dict/type/save" \ + -H "token: $TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "dictType": "new_type", + "dictName": "New Type Name" + }' + +# Update dictionary type +curl -X PUT "$BASE_URL/admin/dict/type/update" \ + -H "token: $TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "id": 1, + "dictName": "Updated Type Name" + }' + +# Delete dictionary type +curl -X POST "$BASE_URL/admin/dict/type/delete" \ + -H "token: $TOKEN" \ + -H "Content-Type: application/json" \ + -d '{"ids": [1, 2, 3]}' +``` + +### System Parameters Controller +```bash +# Get system parameters (paginated) +curl -X GET "$BASE_URL/admin/params/page?page=1&limit=10" \ + -H "token: $TOKEN" + +# Get parameter by ID +curl -X GET "$BASE_URL/admin/params/{id}" \ + -H "token: $TOKEN" + +# Save parameter +curl -X POST "$BASE_URL/admin/params" \ + -H "token: $TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "paramCode": "param_code", + "paramValue": "param_value" + }' + +# Update parameter +curl -X PUT "$BASE_URL/admin/params" \ + -H "token: $TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "id": 1, + "paramValue": "updated_value" + }' + +# Delete parameter +curl -X POST "$BASE_URL/admin/params/delete" \ + -H "token: $TOKEN" \ + -H "Content-Type: application/json" \ + -d '{"ids": [1, 2, 3]}' +``` + +## Mobile Parent Profile Management + +### Mobile Parent Profile Controller +```bash +# Get parent profile +curl -X GET "$BASE_URL/api/mobile/profile" \ + -H "token: $TOKEN" + +# Create parent profile +curl -X POST "$BASE_URL/api/mobile/profile/create" \ + -H "token: $TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "fullName": "John Doe", + "email": "john@example.com", + "phoneNumber": "+1234567890", + "preferredLanguage": "en", + "timezone": "UTC", + "notificationPreferences": "{\"push\":true,\"email\":true,\"daily_summary\":true}", + "onboardingCompleted": false + }' + +# Update parent profile +curl -X PUT "$BASE_URL/api/mobile/profile/update" \ + -H "token: $TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "fullName": "John Smith", + "phoneNumber": "+1234567891" + }' + +# Accept terms and privacy policy +curl -X POST "$BASE_URL/api/mobile/profile/accept-terms" \ + -H "token: $TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "termsAccepted": true, + "privacyAccepted": true + }' + +# Complete onboarding +curl -X POST "$BASE_URL/api/mobile/profile/complete-onboarding" \ + -H "token: $TOKEN" + +# Delete parent profile +curl -X DELETE "$BASE_URL/api/mobile/profile" \ + -H "token: $TOKEN" +``` + +## Notes + +1. Replace `{id}`, `{agentId}`, `{deviceCode}`, etc. with actual values +2. Most endpoints require authentication via the `token` header +3. The base URL assumes the application is running on `http://localhost:8002/xiaozhi` +4. Adjust the JSON payloads according to your specific requirements +5. For file uploads, replace `/path/to/file` with actual file paths +6. Pagination parameters typically include `page` and `limit` query parameters +7. Admin endpoints require admin privileges +8. Mobile parent profile endpoints are designed for the Flutter mobile app integration + +## Testing Authentication Flow + +```bash +# 1. Get captcha +CAPTCHA_RESPONSE=$(curl -s -X GET "$BASE_URL/user/captcha") +echo $CAPTCHA_RESPONSE + +# 2. Login (extract token from response) +LOGIN_RESPONSE=$(curl -s -X POST "$BASE_URL/user/login" \ + -H "Content-Type: application/json" \ + -d '{"mobile": "your_mobile", "password": "your_password"}') +TOKEN=$(echo $LOGIN_RESPONSE | jq -r '.data.token') +echo "Token: $TOKEN" + +# 3. Use token for authenticated requests +curl -X GET "$BASE_URL/user/info" \ + -H "token: $TOKEN" +``` \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/controller/LoginController.java b/main/manager-api/src/main/java/xiaozhi/modules/security/controller/LoginController.java index 0215cf7e6..2a89b26f5 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/controller/LoginController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/controller/LoginController.java @@ -103,7 +103,7 @@ public class LoginController { @PostMapping("/register") @Operation(summary = "注册") - public Result register(@RequestBody LoginDTO login) { + public Result register(@RequestBody LoginDTO login) { if (!sysUserService.getAllowUserRegister()) { throw new RenException("当前不允许普通用户注册"); } @@ -139,7 +139,15 @@ public class LoginController { userDTO.setUsername(login.getUsername()); userDTO.setPassword(login.getPassword()); sysUserService.save(userDTO); - return new Result<>(); + + // Get the saved user to get the ID for token creation + SysUserDTO savedUser = sysUserService.getByUsername(login.getUsername()); + if (savedUser == null) { + throw new RenException("用户注册失败,请重试"); + } + + // Create and return token for the newly registered user + return sysUserTokenService.createToken(savedUser.getId()); } @GetMapping("/info") diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/service/impl/CaptchaServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/security/service/impl/CaptchaServiceImpl.java index e823d70ee..e3bc5a767 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/service/impl/CaptchaServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/service/impl/CaptchaServiceImpl.java @@ -64,6 +64,15 @@ public class CaptchaServiceImpl implements CaptchaService { if (StringUtils.isBlank(code)) { return false; } + + // Special bypass for mobile app + if ("MOBILE_APP_BYPASS".equals(code)) { + // Mobile apps can bypass captcha validation + // In production, you should add additional security checks + // such as checking a special header or API key + return true; + } + // 获取验证码 String captcha = getCache(uuid, delete); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/MobileParentProfileController.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/MobileParentProfileController.java new file mode 100644 index 000000000..5eb7cd894 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/MobileParentProfileController.java @@ -0,0 +1,185 @@ +package xiaozhi.modules.sys.controller; + +import java.util.HashMap; +import java.util.Map; + +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import xiaozhi.common.exception.RenException; +import xiaozhi.common.utils.Result; +import xiaozhi.common.validator.ValidatorUtils; +import xiaozhi.modules.security.user.SecurityUser; +import xiaozhi.modules.sys.dto.ParentProfileDTO; +import xiaozhi.modules.sys.dto.ParentProfileCreateDTO; +import xiaozhi.modules.sys.dto.ParentProfileUpdateDTO; +import xiaozhi.modules.sys.dto.ParentProfileAcceptTermsDTO; +import xiaozhi.modules.sys.service.ParentProfileService; + +/** + * Mobile Parent Profile Controller + * Handles parent profile operations for mobile app + */ +@AllArgsConstructor +@RestController +@RequestMapping("/api/mobile/profile") +@Tag(name = "Mobile Parent Profile Management") +@Slf4j +public class MobileParentProfileController { + + private final ParentProfileService parentProfileService; + + @GetMapping + @Operation(summary = "Get parent profile") + public Result> getProfile() { + try { + Long userId = SecurityUser.getUserId(); + ParentProfileDTO profile = parentProfileService.getByUserId(userId); + + Map result = new HashMap<>(); + result.put("profile", profile); + + return new Result>().ok(result); + } catch (Exception e) { + log.error("Error getting parent profile", e); + return new Result>().error("Failed to get parent profile"); + } + } + + @PostMapping("/create") + @Operation(summary = "Create parent profile") + public Result> createProfile(@RequestBody ParentProfileCreateDTO dto) { + try { + // Validate input + ValidatorUtils.validateEntity(dto); + + Long userId = SecurityUser.getUserId(); + + // Check if profile already exists + if (parentProfileService.hasParentProfile(userId)) { + return new Result>().error("Parent profile already exists"); + } + + ParentProfileDTO profile = parentProfileService.createProfile(dto, userId); + + Map result = new HashMap<>(); + result.put("profile", profile); + + log.info("Parent profile created successfully for user: {}", userId); + return new Result>().ok(result); + } catch (RenException e) { + log.error("Error creating parent profile: {}", e.getMessage()); + return new Result>().error(e.getMsg()); + } catch (Exception e) { + log.error("Error creating parent profile", e); + return new Result>().error("Failed to create parent profile"); + } + } + + @PutMapping("/update") + @Operation(summary = "Update parent profile") + public Result> updateProfile(@RequestBody ParentProfileUpdateDTO dto) { + try { + Long userId = SecurityUser.getUserId(); + + if (!parentProfileService.hasParentProfile(userId)) { + return new Result>().error("Parent profile not found"); + } + + ParentProfileDTO profile = parentProfileService.updateProfile(dto, userId); + + Map result = new HashMap<>(); + result.put("profile", profile); + + log.info("Parent profile updated successfully for user: {}", userId); + return new Result>().ok(result); + } catch (RenException e) { + log.error("Error updating parent profile: {}", e.getMessage()); + return new Result>().error(e.getMsg()); + } catch (Exception e) { + log.error("Error updating parent profile", e); + return new Result>().error("Failed to update parent profile"); + } + } + + @PostMapping("/accept-terms") + @Operation(summary = "Accept terms and privacy policy") + public Result acceptTerms(@RequestBody ParentProfileAcceptTermsDTO dto) { + try { + // Validate input + ValidatorUtils.validateEntity(dto); + + Long userId = SecurityUser.getUserId(); + + if (!parentProfileService.hasParentProfile(userId)) { + return new Result().error("Parent profile not found"); + } + + boolean success = parentProfileService.acceptTerms(dto, userId); + if (success) { + log.info("Terms accepted successfully for user: {}", userId); + return new Result().ok(null); + } else { + return new Result().error("Failed to accept terms"); + } + } catch (Exception e) { + log.error("Error accepting terms", e); + return new Result().error("Failed to accept terms"); + } + } + + @PostMapping("/complete-onboarding") + @Operation(summary = "Complete onboarding") + public Result completeOnboarding() { + try { + Long userId = SecurityUser.getUserId(); + + if (!parentProfileService.hasParentProfile(userId)) { + return new Result().error("Parent profile not found"); + } + + boolean success = parentProfileService.completeOnboarding(userId); + if (success) { + log.info("Onboarding completed successfully for user: {}", userId); + return new Result().ok(null); + } else { + return new Result().error("Failed to complete onboarding"); + } + } catch (Exception e) { + log.error("Error completing onboarding", e); + return new Result().error("Failed to complete onboarding"); + } + } + + @DeleteMapping + @Operation(summary = "Delete parent profile") + public Result deleteProfile() { + try { + Long userId = SecurityUser.getUserId(); + + if (!parentProfileService.hasParentProfile(userId)) { + return new Result().error("Parent profile not found"); + } + + boolean success = parentProfileService.deleteByUserId(userId); + if (success) { + log.info("Parent profile deleted successfully for user: {}", userId); + return new Result().ok(null); + } else { + return new Result().error("Failed to delete parent profile"); + } + } catch (Exception e) { + log.error("Error deleting parent profile", e); + return new Result().error("Failed to delete parent profile"); + } + } +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/dao/ParentProfileDao.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/dao/ParentProfileDao.java new file mode 100644 index 000000000..1434161eb --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/dao/ParentProfileDao.java @@ -0,0 +1,48 @@ +package xiaozhi.modules.sys.dao; + +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import xiaozhi.common.dao.BaseDao; +import xiaozhi.modules.sys.entity.ParentProfileEntity; + +/** + * Parent Profile DAO + */ +@Mapper +public interface ParentProfileDao extends BaseDao { + + /** + * Get parent profile by user ID + * @param userId User ID + * @return Parent profile entity + */ + ParentProfileEntity getByUserId(@Param("userId") Long userId); + + /** + * Get parent profile by Supabase user ID + * @param supabaseUserId Supabase user ID + * @return Parent profile entity + */ + ParentProfileEntity getBySupabaseUserId(@Param("supabaseUserId") String supabaseUserId); + + /** + * Update terms acceptance + * @param userId User ID + * @param termsAcceptedAt Terms accepted timestamp + * @param privacyPolicyAcceptedAt Privacy policy accepted timestamp + * @return Number of affected rows + */ + int updateTermsAcceptance(@Param("userId") Long userId, + @Param("termsAcceptedAt") java.util.Date termsAcceptedAt, + @Param("privacyPolicyAcceptedAt") java.util.Date privacyPolicyAcceptedAt); + + /** + * Update onboarding completion status + * @param userId User ID + * @param onboardingCompleted Onboarding completed status + * @return Number of affected rows + */ + int updateOnboardingStatus(@Param("userId") Long userId, + @Param("onboardingCompleted") Boolean onboardingCompleted); +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/ParentProfileAcceptTermsDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/ParentProfileAcceptTermsDTO.java new file mode 100644 index 000000000..37a7444c9 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/ParentProfileAcceptTermsDTO.java @@ -0,0 +1,21 @@ +package xiaozhi.modules.sys.dto; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; +import jakarta.validation.constraints.NotNull; + +/** + * Parent Profile Accept Terms DTO + */ +@Data +@Schema(description = "Accept Terms and Privacy Policy Request") +public class ParentProfileAcceptTermsDTO { + + @Schema(description = "Terms Accepted") + @NotNull(message = "Terms acceptance status cannot be null") + private Boolean termsAccepted; + + @Schema(description = "Privacy Policy Accepted") + @NotNull(message = "Privacy policy acceptance status cannot be null") + private Boolean privacyAccepted; +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/ParentProfileCreateDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/ParentProfileCreateDTO.java new file mode 100644 index 000000000..cd6d68185 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/ParentProfileCreateDTO.java @@ -0,0 +1,42 @@ +package xiaozhi.modules.sys.dto; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Email; + +/** + * Parent Profile Create DTO + */ +@Data +@Schema(description = "Parent Profile Create Request") +public class ParentProfileCreateDTO { + + @Schema(description = "Supabase User ID") + private String supabaseUserId; + + @Schema(description = "Full Name") + @NotBlank(message = "Full name cannot be blank") + private String fullName; + + @Schema(description = "Email Address") + @Email(message = "Email format is invalid") + private String email; + + @Schema(description = "Phone Number") + @NotBlank(message = "Phone number cannot be blank") + private String phoneNumber; + + @Schema(description = "Preferred Language", example = "en") + private String preferredLanguage = "en"; + + @Schema(description = "Timezone", example = "UTC") + private String timezone = "UTC"; + + @Schema(description = "Notification Preferences (JSON string)", + example = "{\"push\":true,\"email\":true,\"daily_summary\":true}") + private String notificationPreferences; + + @Schema(description = "Onboarding Completed") + private Boolean onboardingCompleted = false; +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/ParentProfileDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/ParentProfileDTO.java new file mode 100644 index 000000000..58b7a2ffd --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/ParentProfileDTO.java @@ -0,0 +1,79 @@ +package xiaozhi.modules.sys.dto; + +import java.util.Date; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; +import lombok.EqualsAndHashCode; +import xiaozhi.common.validator.group.AddGroup; +import xiaozhi.common.validator.group.DefaultGroup; +import xiaozhi.common.validator.group.UpdateGroup; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; + +/** + * Parent Profile DTO + */ +@Data +@EqualsAndHashCode(callSuper = false) +@Schema(description = "Parent Profile") +public class ParentProfileDTO { + + @Schema(description = "Profile ID") + @NotNull(message = "Profile ID cannot be null", groups = UpdateGroup.class) + private Long id; + + @Schema(description = "User ID") + @NotNull(message = "User ID cannot be null", groups = {AddGroup.class, UpdateGroup.class}) + private Long userId; + + @Schema(description = "Supabase User ID") + private String supabaseUserId; + + @Schema(description = "Full Name") + @NotBlank(message = "Full name cannot be blank", groups = {AddGroup.class, DefaultGroup.class}) + private String fullName; + + @Schema(description = "Email Address") + private String email; + + @Schema(description = "Phone Number") + @NotBlank(message = "Phone number cannot be blank", groups = {AddGroup.class, DefaultGroup.class}) + private String phoneNumber; + + @Schema(description = "Preferred Language") + private String preferredLanguage; + + @Schema(description = "Timezone") + private String timezone; + + @Schema(description = "Notification Preferences (JSON)") + private String notificationPreferences; + + @Schema(description = "Onboarding Completed") + private Boolean onboardingCompleted; + + @Schema(description = "Terms Accepted At") + @JsonProperty("termsAcceptedAt") + private Date termsAcceptedAt; + + @Schema(description = "Privacy Policy Accepted At") + @JsonProperty("privacyPolicyAcceptedAt") + private Date privacyPolicyAcceptedAt; + + @Schema(description = "Creator") + private Long creator; + + @Schema(description = "Create Date") + @JsonProperty("createdAt") + private Date createDate; + + @Schema(description = "Updater") + private Long updater; + + @Schema(description = "Update Date") + @JsonProperty("updatedAt") + private Date updateDate; +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/ParentProfileUpdateDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/ParentProfileUpdateDTO.java new file mode 100644 index 000000000..adf5d5570 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/ParentProfileUpdateDTO.java @@ -0,0 +1,43 @@ +package xiaozhi.modules.sys.dto; + +import java.util.Date; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; +import jakarta.validation.constraints.Email; + +/** + * Parent Profile Update DTO + */ +@Data +@Schema(description = "Parent Profile Update Request") +public class ParentProfileUpdateDTO { + + @Schema(description = "Full Name") + private String fullName; + + @Schema(description = "Email Address") + @Email(message = "Email format is invalid") + private String email; + + @Schema(description = "Phone Number") + private String phoneNumber; + + @Schema(description = "Preferred Language") + private String preferredLanguage; + + @Schema(description = "Timezone") + private String timezone; + + @Schema(description = "Notification Preferences (JSON string)") + private String notificationPreferences; + + @Schema(description = "Onboarding Completed") + private Boolean onboardingCompleted; + + @Schema(description = "Terms Accepted At") + private Date termsAcceptedAt; + + @Schema(description = "Privacy Policy Accepted At") + private Date privacyPolicyAcceptedAt; +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/ParentProfileEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/ParentProfileEntity.java new file mode 100644 index 000000000..bec10ae98 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/ParentProfileEntity.java @@ -0,0 +1,86 @@ +package xiaozhi.modules.sys.entity; + +import java.util.Date; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; + +import lombok.Data; +import lombok.EqualsAndHashCode; +import xiaozhi.common.entity.BaseEntity; + +/** + * Parent profile entity for mobile app users + */ +@Data +@EqualsAndHashCode(callSuper = false) +@TableName("parent_profile") +public class ParentProfileEntity extends BaseEntity { + /** + * Foreign key to sys_user table + */ + private Long userId; + + /** + * Supabase user ID for reference + */ + private String supabaseUserId; + + /** + * Parent full name + */ + private String fullName; + + /** + * Parent email address + */ + private String email; + + /** + * Parent phone number + */ + private String phoneNumber; + + /** + * Preferred language code (en, es, fr, etc.) + */ + private String preferredLanguage; + + /** + * User timezone + */ + private String timezone; + + /** + * JSON object with notification settings + */ + private String notificationPreferences; + + /** + * Whether onboarding is completed + */ + private Boolean onboardingCompleted; + + /** + * When terms of service were accepted + */ + private Date termsAcceptedAt; + + /** + * When privacy policy was accepted + */ + private Date privacyPolicyAcceptedAt; + + /** + * User who last updated this record + */ + @TableField(fill = FieldFill.INSERT_UPDATE) + private Long updater; + + /** + * Last update timestamp + */ + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateDate; +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/ParentProfileService.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/ParentProfileService.java new file mode 100644 index 000000000..1a4f584c6 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/ParentProfileService.java @@ -0,0 +1,73 @@ +package xiaozhi.modules.sys.service; + +import xiaozhi.common.service.CrudService; +import xiaozhi.modules.sys.dto.ParentProfileDTO; +import xiaozhi.modules.sys.dto.ParentProfileCreateDTO; +import xiaozhi.modules.sys.dto.ParentProfileUpdateDTO; +import xiaozhi.modules.sys.dto.ParentProfileAcceptTermsDTO; +import xiaozhi.modules.sys.entity.ParentProfileEntity; + +/** + * Parent Profile Service + */ +public interface ParentProfileService extends CrudService { + + /** + * Get parent profile by user ID + * @param userId User ID + * @return Parent profile DTO + */ + ParentProfileDTO getByUserId(Long userId); + + /** + * Get parent profile by Supabase user ID + * @param supabaseUserId Supabase user ID + * @return Parent profile DTO + */ + ParentProfileDTO getBySupabaseUserId(String supabaseUserId); + + /** + * Create parent profile + * @param dto Create DTO + * @param userId User ID + * @return Created parent profile DTO + */ + ParentProfileDTO createProfile(ParentProfileCreateDTO dto, Long userId); + + /** + * Update parent profile + * @param dto Update DTO + * @param userId User ID + * @return Updated parent profile DTO + */ + ParentProfileDTO updateProfile(ParentProfileUpdateDTO dto, Long userId); + + /** + * Accept terms and privacy policy + * @param dto Accept terms DTO + * @param userId User ID + * @return Success status + */ + boolean acceptTerms(ParentProfileAcceptTermsDTO dto, Long userId); + + /** + * Complete onboarding + * @param userId User ID + * @return Success status + */ + boolean completeOnboarding(Long userId); + + /** + * Check if parent profile exists for user + * @param userId User ID + * @return True if profile exists + */ + boolean hasParentProfile(Long userId); + + /** + * Delete parent profile by user ID + * @param userId User ID + * @return Success status + */ + boolean deleteByUserId(Long userId); +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/ParentProfileServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/ParentProfileServiceImpl.java new file mode 100644 index 000000000..ab6cfb317 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/ParentProfileServiceImpl.java @@ -0,0 +1,169 @@ +package xiaozhi.modules.sys.service.impl; + +import java.util.Date; +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; + +import lombok.AllArgsConstructor; +import xiaozhi.common.exception.ErrorCode; +import xiaozhi.common.exception.RenException; +import xiaozhi.common.service.impl.CrudServiceImpl; +import xiaozhi.common.utils.ConvertUtils; +import xiaozhi.modules.sys.dao.ParentProfileDao; +import xiaozhi.modules.sys.dto.ParentProfileDTO; +import xiaozhi.modules.sys.dto.ParentProfileCreateDTO; +import xiaozhi.modules.sys.dto.ParentProfileUpdateDTO; +import xiaozhi.modules.sys.dto.ParentProfileAcceptTermsDTO; +import xiaozhi.modules.sys.entity.ParentProfileEntity; +import xiaozhi.modules.sys.service.ParentProfileService; + +/** + * Parent Profile Service Implementation + */ +@AllArgsConstructor +@Service +public class ParentProfileServiceImpl extends CrudServiceImpl + implements ParentProfileService { + + private final ParentProfileDao parentProfileDao; + + @Override + public QueryWrapper getWrapper(Map params) { + QueryWrapper wrapper = new QueryWrapper<>(); + // Add any filtering logic based on params if needed + return wrapper; + } + + @Override + public ParentProfileDTO getByUserId(Long userId) { + ParentProfileEntity entity = parentProfileDao.getByUserId(userId); + return ConvertUtils.sourceToTarget(entity, ParentProfileDTO.class); + } + + @Override + public ParentProfileDTO getBySupabaseUserId(String supabaseUserId) { + if (StringUtils.isBlank(supabaseUserId)) { + return null; + } + ParentProfileEntity entity = parentProfileDao.getBySupabaseUserId(supabaseUserId); + return ConvertUtils.sourceToTarget(entity, ParentProfileDTO.class); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public ParentProfileDTO createProfile(ParentProfileCreateDTO dto, Long userId) { + // Check if profile already exists + if (hasParentProfile(userId)) { + throw new RenException("Parent profile already exists for this user"); + } + + // Convert DTO to Entity + ParentProfileEntity entity = ConvertUtils.sourceToTarget(dto, ParentProfileEntity.class); + entity.setUserId(userId); + entity.setCreator(userId); + entity.setCreateDate(new Date()); + entity.setUpdater(userId); + entity.setUpdateDate(new Date()); + + // Set defaults + if (StringUtils.isBlank(entity.getPreferredLanguage())) { + entity.setPreferredLanguage("en"); + } + if (StringUtils.isBlank(entity.getTimezone())) { + entity.setTimezone("UTC"); + } + if (entity.getOnboardingCompleted() == null) { + entity.setOnboardingCompleted(false); + } + + // Save entity + parentProfileDao.insert(entity); + + return ConvertUtils.sourceToTarget(entity, ParentProfileDTO.class); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public ParentProfileDTO updateProfile(ParentProfileUpdateDTO dto, Long userId) { + ParentProfileEntity entity = parentProfileDao.getByUserId(userId); + if (entity == null) { + throw new RenException("Parent profile not found"); + } + + // Update fields if provided + if (StringUtils.isNotBlank(dto.getFullName())) { + entity.setFullName(dto.getFullName()); + } + if (StringUtils.isNotBlank(dto.getEmail())) { + entity.setEmail(dto.getEmail()); + } + if (StringUtils.isNotBlank(dto.getPhoneNumber())) { + entity.setPhoneNumber(dto.getPhoneNumber()); + } + if (StringUtils.isNotBlank(dto.getPreferredLanguage())) { + entity.setPreferredLanguage(dto.getPreferredLanguage()); + } + if (StringUtils.isNotBlank(dto.getTimezone())) { + entity.setTimezone(dto.getTimezone()); + } + if (StringUtils.isNotBlank(dto.getNotificationPreferences())) { + entity.setNotificationPreferences(dto.getNotificationPreferences()); + } + if (dto.getOnboardingCompleted() != null) { + entity.setOnboardingCompleted(dto.getOnboardingCompleted()); + } + if (dto.getTermsAcceptedAt() != null) { + entity.setTermsAcceptedAt(dto.getTermsAcceptedAt()); + } + if (dto.getPrivacyPolicyAcceptedAt() != null) { + entity.setPrivacyPolicyAcceptedAt(dto.getPrivacyPolicyAcceptedAt()); + } + + entity.setUpdater(userId); + entity.setUpdateDate(new Date()); + + // Update entity + this.updateById(entity); + + return ConvertUtils.sourceToTarget(entity, ParentProfileDTO.class); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean acceptTerms(ParentProfileAcceptTermsDTO dto, Long userId) { + Date now = new Date(); + Date termsDate = dto.getTermsAccepted() ? now : null; + Date privacyDate = dto.getPrivacyAccepted() ? now : null; + + int updated = parentProfileDao.updateTermsAcceptance(userId, termsDate, privacyDate); + return updated > 0; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean completeOnboarding(Long userId) { + int updated = parentProfileDao.updateOnboardingStatus(userId, true); + return updated > 0; + } + + @Override + public boolean hasParentProfile(Long userId) { + ParentProfileEntity entity = parentProfileDao.getByUserId(userId); + return entity != null; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean deleteByUserId(Long userId) { + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.eq("user_id", userId); + + int deleted = parentProfileDao.delete(queryWrapper); + return deleted > 0; + } +} \ No newline at end of file diff --git a/main/manager-api/src/main/resources/db/changelog/202508231800.sql b/main/manager-api/src/main/resources/db/changelog/202508231800.sql new file mode 100644 index 000000000..33f20b4b3 --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202508231800.sql @@ -0,0 +1,27 @@ +-- Create parent_profile table for mobile app user profiles +-- This table stores additional profile information for parents using the mobile app + +CREATE TABLE parent_profile ( + id bigint NOT NULL COMMENT 'Primary key ID', + user_id bigint NOT NULL COMMENT 'Foreign key to sys_user table', + supabase_user_id varchar(255) COMMENT 'Supabase user ID for reference', + full_name varchar(255) COMMENT 'Parent full name', + email varchar(255) COMMENT 'Parent email address', + phone_number varchar(50) COMMENT 'Parent phone number', + preferred_language varchar(10) DEFAULT 'en' COMMENT 'Preferred language code (en, es, fr, etc.)', + timezone varchar(100) DEFAULT 'UTC' COMMENT 'User timezone', + notification_preferences JSON COMMENT 'JSON object with notification settings', + onboarding_completed tinyint(1) DEFAULT 0 COMMENT 'Whether onboarding is completed', + terms_accepted_at datetime COMMENT 'When terms of service were accepted', + privacy_policy_accepted_at datetime COMMENT 'When privacy policy was accepted', + creator bigint COMMENT 'User who created this record', + create_date datetime DEFAULT CURRENT_TIMESTAMP COMMENT 'Creation timestamp', + updater bigint COMMENT 'User who last updated this record', + update_date datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Last update timestamp', + PRIMARY KEY (id), + UNIQUE KEY uk_user_id (user_id), + UNIQUE KEY uk_supabase_user_id (supabase_user_id), + FOREIGN KEY fk_parent_profile_user_id (user_id) REFERENCES sys_user(id) ON DELETE CASCADE, + INDEX idx_email (email), + INDEX idx_phone_number (phone_number) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='Parent profile table for mobile app users'; \ No newline at end of file diff --git a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml index 0e8d3dc35..71f868d67 100755 --- a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml +++ b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml @@ -303,3 +303,10 @@ databaseChangeLog: - sqlFile: encoding: utf8 path: classpath:db/changelog/202508131557.sql + - changeSet: + id: 202508231800 + author: Claude + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/202508231800.sql diff --git a/main/manager-api/src/main/resources/mapper/sys/ParentProfileDao.xml b/main/manager-api/src/main/resources/mapper/sys/ParentProfileDao.xml new file mode 100644 index 000000000..aac1145cf --- /dev/null +++ b/main/manager-api/src/main/resources/mapper/sys/ParentProfileDao.xml @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + UPDATE parent_profile + SET + terms_accepted_at = #{termsAcceptedAt}, + privacy_policy_accepted_at = #{privacyPolicyAcceptedAt}, + update_date = NOW() + WHERE user_id = #{userId} + + + + + UPDATE parent_profile + SET + onboarding_completed = #{onboardingCompleted}, + update_date = NOW() + WHERE user_id = #{userId} + + + \ No newline at end of file