diff --git a/.claude/settings.local.json b/.claude/settings.local.json deleted file mode 100644 index af66fec..0000000 --- a/.claude/settings.local.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "permissions": { - "allow": [ - "Bash(./mvnw clean compile -q)", - "mcp__ide__getDiagnostics", - "Bash(find:*)", - "Bash(./mvnw:*)", - "Bash(rm:*)", - "Bash(lsof:*)", - "Bash(xargs kill:*)", - "Bash(cat:*)", - "Bash(mongosh:*)", - "Bash(mongo:*)", - "Bash(kill:*)" - ], - "deny": [], - "ask": [] - } -} diff --git a/.gitignore b/.gitignore index ddc419e..8c8dafc 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,3 @@ -/target/ .idea/ .vscode/ .settings @@ -8,14 +7,27 @@ *.iml .DS_Store -# The following files are generated/updated by vaadin-maven-plugin -node_modules/ -src/main/frontend/generated/ -vite.generated.ts +# Backend (Spring Boot / Vaadin) +/backend/target/ +/backend/node_modules/ +/backend/src/main/frontend/generated/ +/backend/vite.generated.ts +/backend/logs/ +/backend/.env -# Log files -logs/ +# Flutter app +/app/.dart_tool/ +/app/build/ +/app/coverage/ +/app/.flutter-plugins +/app/.flutter-plugins-dependencies +/app/android/.gradle/ +/app/android/.kotlin/ +/app/android/local.properties +/app/ios/Pods/ +/app/ios/.symlinks/ +/app/macos/Pods/ + +# Root build artifacts +/target/ *.log - -# Environment variables -.env diff --git a/AGENTS.md b/AGENTS.md deleted file mode 100644 index 1d9814a..0000000 --- a/AGENTS.md +++ /dev/null @@ -1,22 +0,0 @@ -# Repository Guidelines - -## Project Structure & Module Organization -Backend Java sits in `src/main/java/de/assecutor/votianlt`; domain models stay in `model`, persistence logic in `repository`, services in `service`, MQTT integration under `mqtt`, and access control in `security`. Vaadin views and UI helpers live in `pages/view` and `pages/base`. TypeScript, styles, and theming live in `src/main/frontend` (leave `generated/` untouched). Shared configs and templates live in `src/main/resources`, while Vaadin bundle descriptors reside in `src/main/bundles`. Maven output lands in `target/`. - -## Build, Test, and Development Commands -Use `./mvnw` for the Spring Boot dev server with frontend hot reload. Build production bits with `./mvnw -Pproduction package`. Run `./mvnw test` for unit checks and `./mvnw -Pintegration-test verify` when integration coverage is needed. After dependency changes, refresh Vaadin assets with `./mvnw vaadin:prepare-frontend`. Apply formatting via `./mvnw spotless:apply`. - -## Coding Style & Naming Conventions -Spotless enforces Java 21 formatting using `eclipse-formatter.xml`; keep imports ordered and rely on Lombok already present. Classes remain PascalCase, Spring stereotypes end with `Service`, `Repository`, or `Config`, and Vaadin views retain the `*View` naming within `pages/view`. Frontend code follows the repo’s Prettier rules (`.prettierrc.json`); keep TypeScript modules co-located with their views, prefer camelCase for variables, and avoid checking in generated `.class` files. - -## Testing Guidelines -Create tests under `src/test/java` mirroring the production package path. Name unit classes `*Test` and integration suites `*IT` so the failsafe profile picks them up. Lean on Spring Boot’s testing annotations for wiring, Mockito for isolates, and add Testcontainers when MongoDB or MQTT brokers are involved. Run `./mvnw test` before any push; trigger `./mvnw -Pintegration-test verify` for messaging, persistence, or security changes. - -## Commit & Pull Request Guidelines -History currently uses brief German titles; shift to imperative, scoped summaries such as `feat: add PDF mailer` or `fix: guard MQTT reconnects`. Keep unrelated updates out of the same commit and exclude artifacts like `node_modules/` or `target/`. Pull requests should explain the motivation, link issues, note config or data-seed impacts, and attach screenshots or screencasts when Vaadin views change. List manual verification steps and flag any migrations or bundle adjustments for reviewers. - -## Security & Configuration Tips -External service credentials for MongoDB, SMTP, and MQTT belong in environment variables or a developer-specific `application-local.properties` kept out of version control. Document default ports and topics when touching `MqttConfig` so ops can replicate environments. For two-factor flows, keep shared secrets in secure storage and avoid logging codes during development. - -# Misc -Never start the application; leave that to the user. \ No newline at end of file diff --git a/CLAUDE.md b/CLAUDE.md deleted file mode 100644 index 9a71044..0000000 --- a/CLAUDE.md +++ /dev/null @@ -1,103 +0,0 @@ -# CLAUDE.md - -This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. - -## Development Commands - -- **Start development server**: `./mvnw` (runs Spring Boot with Vaadin dev mode) -- **Build for production**: `./mvnw -Pproduction package` -- **Clean build**: `./mvnw clean compile` -- **Format code**: `./mvnw spotless:apply` (applies Eclipse formatter for Java, Prettier for TypeScript) -- **Check formatting**: `./mvnw spotless:check` - -## Architecture Overview - -This is a **Vaadin Spring Boot** application for job/task management with real-time mobile app communication via a pluggable messaging transport layer. The system manages logistics jobs with tasks that mobile app users complete. - -### Core Architecture Layers - -**Frontend**: Vaadin Flow views (server-side rendered) -- `src/main/java/de/assecutor/votianlt/pages/view/` - Main UI views -- `src/main/java/de/assecutor/votianlt/pages/base/ui/` - Shared UI components - -**Backend Services**: -- `src/main/java/de/assecutor/votianlt/service/` - Business logic -- `src/main/java/de/assecutor/votianlt/controller/` - Message handling (routes inbound messages to processors) -- `src/main/java/de/assecutor/votianlt/repository/` - MongoDB data access - -**Messaging Layer** (`src/main/java/de/assecutor/votianlt/messaging/`): -- `plugin/` - Transport plugin interface and implementations (MQTT, extensible for WebSocket, gRPC) -- `delivery/` - Reliable message delivery with acknowledgment tracking, retries, and expiry -- `model/` - Message envelopes, delivery status, pending deliveries -- `config/` - Messaging configuration and wiring - -**Models**: -- `src/main/java/de/assecutor/votianlt/model/` - Domain entities -- Task hierarchy: `BaseTask` with subtypes (`PhotoTask`, `BarcodeTask`, `SignatureTask`, etc.) - -### Key Architectural Patterns - -**Job-Task Relationship**: Jobs contain multiple ordered tasks. Tasks have completion states and can store completion data (photos, barcodes, signatures). - -**User Hierarchy**: -- `User` - Web interface users (job managers) -- `AppUser` - Mobile app users (task executors) -- `AppUser.owner` field links to `User` for notifications - -**Messaging Plugin Architecture**: -- `MessagingPlugin` interface abstracts transport protocols (currently MQTT via HiveMQ) -- `MessageDeliveryService` provides guaranteed delivery with acknowledgment tracking -- `AcknowledgmentHandler` processes ACKs and updates delivery status -- Plugins are responsible for topic/channel structure; delivery layer uses `clientId` and `messageType` - -**Client Connection Monitoring**: -- `ClientConnectionService` tracks connected mobile clients via ping/pong mechanism -- Server sends ping to `/client/{clientId}/ping`, client responds on `/server/{clientId}/pong` - -**History Tracking**: `JobHistoryService` logs all job/task changes with detailed audit trail displayed in `JobHistoryView`. - -**Email Notifications**: `EmailService` sends notifications for job creation, task completion, and job completion using Spring Mail with SMTP. - -## Data Storage - -**MongoDB Collections**: -- `jobs` - Main job entities with status tracking -- `tasks` - Polymorphic task storage (discriminated by `taskType`) -- `job_history` - Audit trail for all job changes -- `pending_deliveries` - Message delivery tracking for retries -- `photos`, `barcodes`, `signatures` - Task completion data -- `users` - Web interface users -- `app_user` - Mobile app users -- `cargo_item` - Job cargo/delivery items - -## Configuration - -**Database**: MongoDB (configurable via `spring.data.mongodb.uri`) -**Messaging**: Plugin-based, currently MQTT via HiveMQ (`app.messaging.plugin.*` properties) -**Email**: SMTP via Spring Boot mail auto-configuration - -## Development Environment - -**Java 21** with **Spring Boot 3.4.3** and **Vaadin 24.7.0** -**Security**: Spring Security with role-based access (`USER` role required) -**Formatting**: Spotless Maven plugin with Eclipse formatter (Java) and Prettier (TypeScript) -**Profiles**: `production` profile for optimized builds, `integration-test` profile for failsafe plugin - -## Key Integration Points - -When adding new task types: -1. Extend `BaseTask` and add to `@JsonSubTypes` -2. Add completion logic in `MessageController.handleTaskCompleted()` -3. Update `JobHistoryView` for task-specific previews if needed - -When modifying job status flow: -1. Update `JobStatus` enum -2. Modify `EmailService.updateJobStatusToCompleted()` logic -3. Consider email notification templates - -When adding new messaging transports: -1. Implement `MessagingPlugin` interface -2. Register in `PluginMessagingConfig` -3. Add configuration properties under `app.messaging.plugin..*` - -Message routing follows pattern: `MessageController` receives messages via `MessageDeliveryService`, extracts `taskType`/`messageType` from payload, routes to appropriate processor method. diff --git a/README.md b/README.md index 9c6b078..a1b3c47 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,40 @@ -docker buildx build --platform linux/amd64 -t appcreationgmbh/votianlt:0.8.0 --push . +# VotianLT Monorepo -docker buildx build --platform linux/amd64 -t registry.assecutor.de/votianlt:0.9.10 --push . +## Struktur -adsg -G8m0T3vz \ No newline at end of file +- `backend/`: Spring Boot / Vaadin Backend +- `app/`: Flutter App +- `.vscode/`: gemeinsame Workspace-Launches für Backend und Flutter + +## Backend + +```bash +cd backend +./mvnw +``` + +Wichtige Befehle: + +```bash +cd backend && ./mvnw test +cd backend && ./mvnw -Pproduction package +cd backend && ./mvnw spotless:apply +``` + +## Flutter App + +```bash +cd app +flutter pub get +flutter run +``` + +## Release Image + +Das Release-Script liegt im Repo-Root und baut/pusht das Backend-Image: + +```bash +docker login registry.assecutor.org +./docker_push.sh +./docker_push.sh 0.9.13 +``` diff --git a/app/.gitignore b/app/.gitignore new file mode 100644 index 0000000..b68f230 --- /dev/null +++ b/app/.gitignore @@ -0,0 +1,2 @@ +.dart_tool/ +build/ \ No newline at end of file diff --git a/app/AGENTS.md b/app/AGENTS.md new file mode 100644 index 0000000..558388b --- /dev/null +++ b/app/AGENTS.md @@ -0,0 +1,429 @@ +# Votian LT App - Agent Guidelines + +## Project Overview + +**Votian LT** is a Flutter-based mobile application for logistics and transport management. The app enables drivers to manage transport jobs, complete tasks (photos, signatures, barcodes), communicate via real-time chat, and navigate to pickup/delivery locations. + +### Key Features +- **Job Management**: View and manage assigned transport jobs with cargo items +- **Task System**: Complete various task types (confirmation, photo capture, signature, barcode scanning, todo lists, comments) +- **Real-time Chat**: Job-specific and general chat via WebSocket +- **Offline Support**: Full offline functionality with local ObjectBox database +- **Navigation**: Integration with external maps and embedded WebView routing +- **Push Notifications**: Local notifications for new jobs and messages +- **Implementation**: When making changes, be careful not to damage existing functionalities. + +--- + +## Technology Stack + +| Layer | Technology | +|-------|------------| +| Framework | Flutter 3.7+ with Dart | +| State Management | Singleton pattern + Custom DartMQ pub/sub | +| Local Database | ObjectBox (NoSQL) | +| Real-time Communication | WebSocket (STOMP-style protocol) | +| Backend Integration | WebSocket to `ws://localhost:8082/ws/messaging` | +| UI Design | Material Design 3 | + +### Key Dependencies (pubspec.yaml) +- `web_socket_channel: ^3.0.0` - WebSocket client +- `objectbox: ^4.0.3` + `objectbox_flutter_libs` - Local database +- `camera: ^0.10.5+9` - Photo capture +- `mobile_scanner: ^5.0.0` - Barcode scanning +- `signature: ^5.5.0` - Signature capture canvas +- `flutter_local_notifications: ^18.0.0` - Local notifications +- `url_launcher: ^6.3.0` - External navigation +- `webview_flutter: ^4.8.0` - Embedded maps +- `image: ^4.2.0` - Image processing +- `package_info_plus: ^8.0.0` - App version info + +--- + +## Project Structure + +``` +lib/ +├── main.dart # App entry point, MaterialApp setup +├── app_state.dart # Global app state singleton (jobs, login) +├── navigation_observer.dart # Route observer for analytics +├── routing_view.dart # Embedded navigation WebView +│ +├── models/ # Domain models (JSON serializable) +│ ├── job.dart # Transport job with cargo items and tasks +│ ├── cargo_item.dart # Cargo/load items +│ ├── task.dart # Abstract task base class +│ ├── tasks/ # Concrete task implementations +│ │ ├── confirmation_task.dart +│ │ ├── photo_task.dart +│ │ ├── signature_task.dart +│ │ ├── barcode_task.dart +│ │ ├── todolist_task.dart +│ │ ├── comment_task.dart +│ │ └── generic_task.dart +│ ├── chat.dart # Chat conversation +│ ├── chat_message.dart # Individual message +│ ├── message_envelope.dart # WebSocket message wrapper +│ ├── acknowledgment_message.dart +│ └── queued_message.dart # Offline message queue +│ +├── entities/ # ObjectBox database entities +│ ├── job_entity.dart +│ ├── task_status_entity.dart +│ ├── user_data_entity.dart +│ ├── photo_entity.dart +│ ├── queued_message_entity.dart +│ └── chat_message_entity.dart +│ +├── services/ # Business logic services (singletons) +│ ├── websocket_service.dart # WebSocket connection & messaging +│ ├── database_service.dart # ObjectBox database operations +│ ├── chat_service.dart # Chat management +│ ├── dart_mq.dart # In-app pub/sub message bus +│ ├── notification_service.dart # Local notifications +│ ├── message_handler.dart # Incoming message processing +│ ├── ack_tracker.dart # Message acknowledgment tracking +│ └── developer.dart # Developer utilities/logging +│ +├── views/ # Main UI screens +│ ├── login_view.dart # Authentication screen +│ ├── jobs_view.dart # Job list screen +│ ├── cargo_items_view.dart # Cargo details for a job +│ ├── chats_view.dart # Chat list screen +│ ├── chat_details_view.dart # Individual chat conversation +│ └── task_view.dart # Task completion screen +│ +├── tasks/ # Task-specific UI screens +│ ├── photo_capture_screen.dart +│ ├── signature_capture_screen.dart +│ └── barcode_capture_screen.dart +│ +└── widgets/ # Reusable UI components + ├── chat_photo_dialog.dart + └── offline_banner.dart + +test/ # Unit and widget tests +├── models/ +│ ├── job_parsing_test.dart +│ ├── message_envelope_test.dart +│ └── acknowledgment_message_test.dart +└── services/ + ├── ack_tracker_test.dart + ├── message_handler_test.dart + └── mqtt_integration_test.dart + +android/, ios/, macos/, linux/, windows/ # Platform-specific code +``` + +--- + +## Build, Test, and Development Commands + +### Setup +```bash +# Install dependencies +flutter pub get + +# Generate ObjectBox code (after entity changes) +flutter pub run build_runner build +``` + +### Development +```bash +# Run static analysis +flutter analyze + +# Format code (CI expects formatted code) +dart format lib/ test/ + +# Run the app +flutter run + +# Run on specific device +flutter run -d +``` + +### Testing +```bash +# Run all tests +flutter test + +# Run with coverage +flutter test --coverage + +# Run specific test file +flutter test test/models/job_parsing_test.dart +``` + +--- + +## Architecture Patterns + +### Singleton Services +All major services use the singleton pattern for app-wide state: + +```dart +// Accessing services +final appState = AppState(); +final chatService = ChatService(); +final wsService = WebSocketService(); +final dbService = DatabaseService(); +``` + +### DartMQ Pub/Sub +Custom lightweight message bus for decoupled communication: + +```dart +// Subscribe to topics +final sub = DartMQ().subscribe>( + MQTopics.authResponse, + (data) => handleAuth(data), +); + +// Publish messages +DartMQ().publish(MQTopics.connectionStatus, true); + +// Cleanup +sub.cancel(); +``` + +**Common Topics** (`lib/services/dart_mq.dart`): +- `connection/status` - WebSocket connection state (bool) +- `auth/response` - Authentication responses (Map) +- `jobs/response` - Job list updates (List) +- `jobsUpdated` - Job data changed notification (void) +- `job/deleted` - Job deletion event (Map) +- `job/created` - New job created (Map) +- `chat/incoming` - New chat message (ChatMessage) + +### Task System +Tasks are polymorphic based on `taskType` field: + +| Task Type | Description | +|-----------|-------------| +| `CONFIRMATION` | Button tap confirmation | +| `PHOTO` | Capture photos (min/max count) | +| `SIGNATURE` | Capture signature as SVG | +| `BARCODE` | Scan barcodes/QR codes | +| `TODOLIST` | Checklist of items | +| `COMMENT` | Text input field | +| `GENERIC` | Fallback type | + +--- + +## Coding Style Guidelines + +### Dart/Flutter Conventions +- **Indentation**: 2 spaces +- **Trailing Commas**: Use trailing commas to encourage proper auto-formatting +- **Naming**: + - Classes: `UpperCamelCase` + - Methods/variables: `lowerCamelCase` + - Private members: `_leadingUnderscore` + - Constants: `camelCase` or `UPPER_SNAKE_CASE` for static const + +### Code Style Examples +```dart +// Good: trailing commas for multi-line +final job = Job( + id: '123', + jobNumber: 'JOB-001', + status: 'ASSIGNED', + // ... +); + +// Good: private helper methods +String _formatAddress(String street, String city) { + return '$street, $city'; +} + +// Good: type annotations for public APIs +Future> loadJobs() async { + // ... +} +``` + +### Imports +- Order: Dart SDK → Flutter → Third-party → Project (alphabetical within groups) +- Use `package:votianlt_app/` prefix for project imports + +--- + +## Testing Guidelines + +### Test Structure +```dart +import 'package:flutter_test/flutter_test.dart'; +import 'package:votianlt_app/models/job.dart'; + +void main() { + group('Job Parsing', () { + test('parses basic fields correctly', () { + // Arrange + final json = {'job': {'id': '123', ...}}; + + // Act + final job = Job.fromJson(json); + + // Assert + expect(job.id, '123'); + }); + }); +} +``` + +### Testing Patterns +- Mirror the `lib/` directory structure in `test/` +- Name tests after the unit: `job_parsing_test.dart` +- Use `group()` for related assertions +- Test both success and edge cases +- Test round-trip serialization (`fromJson` → `toJson` → `fromJson`) + +### Mocking +Use `mocktail` for mocking dependencies in service tests. + +--- + +## Database (ObjectBox) + +### Entity Definition Example +```dart +@Entity() +class JobEntity { + @Id() + int id = 0; + + @Unique() + String jobId; + + String jobData; // JSON-encoded + + @Property(type: PropertyType.date) + DateTime createdAt; + + @Property(type: PropertyType.date) + DateTime updatedAt; + + JobEntity({...}); +} +``` + +### Regenerating Code +After modifying entities in `lib/entities/`: +```bash +flutter pub run build_runner build +``` + +This generates `lib/objectbox.g.dart`. + +--- + +## WebSocket Protocol + +### Connection +- URL: `ws://localhost:8082/ws/messaging` (desktop) +- Android Emulator: `ws://10.0.2.2:8082/ws/messaging` + +### Message Format +```json +{ + "topic": "/client/auth", + "payload": { ... } +} +``` + +### Client → Server Topics +- `/server/login` - Authentication +- `/server/jobs/assigned` - Request job list +- `/server/message` - Send chat message +- `/server/task_completed` - Mark task complete + +### Server → Client Topics +- `/client/{userId}/auth` - Auth response +- `/client/{userId}/jobs` - Job list +- `/client/{userId}/message` - Incoming chat +- `/client/{userId}/job_deleted` - Job deleted +- `/client/{userId}/job_created` - New job + +--- + +## Security Considerations + +### Credentials +- Email/password stored in ObjectBox (encrypted at rest by OS) +- Credentials cleared on logout +- Auto-login with saved credentials + +### WebSocket +- Reconnection with 15-second interval +- Message buffering when offline +- Unique App ID per installation for client identification + +### Secrets +- Do not commit API keys or credentials +- Server endpoint configurable in `WebSocketService._buildWebSocketUrl()` + +--- + +## Platform-Specific Notes + +### Android +- Minimum SDK: Defined in `android/app/build.gradle` +- Permissions in `AndroidManifest.xml`: + - `INTERNET` - WebSocket communication + - `CAMERA` - Photo/barcode capture + - `WRITE_EXTERNAL_STORAGE` - Photo storage + - `POST_NOTIFICATIONS` - Push notifications + - `VIBRATE` - Notification vibration + +### iOS +- Camera and photo permissions in `ios/Runner/Info.plist` +- Notification permissions configured + +--- + +## Common Development Tasks + +### Adding a New Task Type +1. Create model in `lib/models/tasks/new_task_type.dart` +2. Add to `Task.fromJson()` factory in `lib/models/task.dart` +3. Add UI screen in `lib/tasks/` if needed +4. Update `task_view.dart` to handle the new type +5. Add tests in `test/models/` + +### Adding a New Database Entity +1. Create entity class in `lib/entities/` +2. Run `flutter pub run build_runner build` +3. Add CRUD operations in `DatabaseService` + +### Modifying WebSocket Messages +1. Update message handler in `WebSocketService._handleMessage()` +2. Add topic constant to `MQTopics` if needed +3. Update `MessageHandler` for processing logic + +--- + +## Localization + +The app uses German for UI text: +- Job status: "Erstellt", "Zugewiesen", "In Bearbeitung", "Abgeschlossen" +- Notifications: "Neue Jobs", "Neue Nachricht" +- Chat: "Allgemeine Nachrichten" + +--- + +## Debugging + +### Logging +Use the developer log utility: +```dart +import 'package:votianlt_app/services/developer.dart' as developer; + +developer.log('Debug message', name: 'ComponentName'); +``` + +### Common Issues +1. **WebSocket not connecting**: Check server is running on port 8082 +2. **Database errors**: Run `flutter clean` and `flutter pub get` +3. **ObjectBox issues**: Regenerate with `build_runner` +4. **Camera not working**: Check platform permissions diff --git a/app/CLAUDE.md b/app/CLAUDE.md new file mode 100644 index 0000000..7724b2a --- /dev/null +++ b/app/CLAUDE.md @@ -0,0 +1,71 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Build & Development Commands + +```bash +flutter pub get # Install dependencies +flutter analyze # Run static analysis (run after every task) +dart format # Format code +flutter test # Run tests +flutter run -d # Run app on device +dart run build_runner build # Generate ObjectBox code after entity changes +``` + +**Important:** Run `flutter analyze` after every task and fix any reported issues before committing. + +## Architecture Overview + +This is a Flutter app for job/task management with MQTT-based backend communication. The app is written in German for end users. + +### Core Components + +**AppState** (`lib/app_state.dart`) +- Singleton managing global state: `appUserId`, in-memory jobs list +- Handles persistence via DatabaseService with coalesced writes +- Emits `jobsUpdated` events via both StreamController and DartMQ + +**DartMQ** (`lib/services/dart_mq.dart`) +- Lightweight in-app pub/sub message bus for decoupled communication +- Key topics defined in `MQTopics`: `connectionStatus`, `authResponse`, `jobsResponse`, `taskEvents`, `jobsUpdated`, `chatIncoming`, `chatOutgoing` +- UI and services subscribe/publish without direct dependencies + +**MqttService** (`lib/services/mqtt_service.dart`, aliased as `StompService`) +- MQTT client connecting to Mosquitto broker at `mqtt-2.assecutor.de:42099` +- Handles authentication, job loading, chat messages, task completion +- Message envelope pattern with ACK/retry system for reliable delivery +- Offline message queuing via DatabaseService +- Publishes all server events through DartMQ topics + +**DatabaseService** (`lib/services/database_service.dart`) +- ObjectBox-based local persistence +- Stores jobs, task status, user data, chat messages, queued MQTT messages +- Entities in `lib/entities/` require `dart run build_runner build` after changes + +### Data Flow + +1. `LoginView` initiates MQTT connection, sends credentials to `/server/login` +2. Server responds on `/client/{appId}/auth` → MqttService publishes `MQTopics.authResponse` +3. On success, `AppState` stores `appUserId`, `JobsView` requests jobs via `/server/{userId}/jobs/assigned` +4. Jobs arrive on `/client/{userId}/jobs` → published to `MQTopics.jobsResponse` → persisted → UI refresh via `MQTopics.jobsUpdated` +5. Task updates flow through `/client/{userId}/notifications` → `MQTopics.taskEvents` + +### Models + +- **Job** (`lib/models/job.dart`): Contains pickup/delivery addresses, cargo items, and tasks +- **Task** (`lib/models/task.dart`): Abstract base with subtypes: `ConfirmationTask`, `PhotoTask`, `TodoListTask`, `SignatureTask`, `BarcodeTask`, `CommentTask`, `GenericTask` +- **ChatMessage** (`lib/models/chat_message.dart`): Chat with direction, content type, job linking + +### Views + +- `LoginView` → `JobsView` → `CargoItemsView` → Task screens +- `ChatsView` → `ChatDetailsView` +- Task capture screens in `lib/tasks/`: photo, signature, barcode + +## Key Patterns + +- All services are singletons (factory constructors returning `_instance`) +- MQTT messages wrapped in `MessageEnvelope` for reliable delivery with ACK +- UI subscribes to DartMQ topics rather than holding service references +- Jobs are normalized before persistence to ensure consistent data diff --git a/app/README.md b/app/README.md new file mode 100644 index 0000000..495d7b5 --- /dev/null +++ b/app/README.md @@ -0,0 +1,16 @@ +# votianlt_app + +votian LT + +## Getting Started + +This project is a starting point for a Flutter application. + +A few resources to get you started if this is your first Flutter project: + +- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) +- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook) + +For help getting started with Flutter development, view the +[online documentation](https://docs.flutter.dev/), which offers tutorials, +samples, guidance on mobile development, and a full API reference. diff --git a/app/analysis_options.yaml b/app/analysis_options.yaml new file mode 100644 index 0000000..0d29021 --- /dev/null +++ b/app/analysis_options.yaml @@ -0,0 +1,28 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at https://dart.dev/lints. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/app/android/.gitignore b/app/android/.gitignore new file mode 100644 index 0000000..be3943c --- /dev/null +++ b/app/android/.gitignore @@ -0,0 +1,14 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java +.cxx/ + +# Remember to never publicly share your keystore. +# See https://flutter.dev/to/reference-keystore +key.properties +**/*.keystore +**/*.jks diff --git a/app/android/app/build.gradle.kts b/app/android/app/build.gradle.kts new file mode 100644 index 0000000..4556282 --- /dev/null +++ b/app/android/app/build.gradle.kts @@ -0,0 +1,49 @@ +plugins { + id("com.android.application") + id("kotlin-android") + // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + id("dev.flutter.flutter-gradle-plugin") +} + +android { + namespace = "de.assecutor.votianlt_app" + compileSdk = 36 + ndkVersion = "27.0.12077973" + + compileOptions { + isCoreLibraryDesugaringEnabled = true + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 + } + + kotlinOptions { + jvmTarget = JavaVersion.VERSION_11.toString() + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId = "de.assecutor.votianlt_app" + // You can update the following values to match your application needs. + // For more information, see: https://flutter.dev/to/review-gradle-config. + minSdk = flutter.minSdkVersion + targetSdk = flutter.targetSdkVersion + versionCode = flutter.versionCode + versionName = flutter.versionName + } + + buildTypes { + release { + // TODO: Add your own signing config for the release build. + // Signing with the debug keys for now, so `flutter run --release` works. + signingConfig = signingConfigs.getByName("debug") + } + } +} + +dependencies { + coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.4") +} + +flutter { + source = "../.." +} diff --git a/app/android/app/src/debug/AndroidManifest.xml b/app/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/app/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/app/android/app/src/main/AndroidManifest.xml b/app/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..32393e5 --- /dev/null +++ b/app/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/android/app/src/main/kotlin/de/assecutor/votianlt_app/MainActivity.kt b/app/android/app/src/main/kotlin/de/assecutor/votianlt_app/MainActivity.kt new file mode 100644 index 0000000..9570a75 --- /dev/null +++ b/app/android/app/src/main/kotlin/de/assecutor/votianlt_app/MainActivity.kt @@ -0,0 +1,5 @@ +package de.assecutor.votianlt_app + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity : FlutterActivity() diff --git a/app/android/app/src/main/res/drawable-v21/launch_background.xml b/app/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 0000000..f74085f --- /dev/null +++ b/app/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/app/android/app/src/main/res/drawable/launch_background.xml b/app/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 0000000..304732f --- /dev/null +++ b/app/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/app/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/app/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..db77bb4 Binary files /dev/null and b/app/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/app/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/app/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..17987b7 Binary files /dev/null and b/app/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/app/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/app/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..09d4391 Binary files /dev/null and b/app/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/app/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/app/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..d5f1c8d Binary files /dev/null and b/app/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/app/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/app/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..4d6372e Binary files /dev/null and b/app/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/app/android/app/src/main/res/values-night/styles.xml b/app/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 0000000..06952be --- /dev/null +++ b/app/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/app/android/app/src/main/res/values/styles.xml b/app/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..cb1ef88 --- /dev/null +++ b/app/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/app/android/app/src/main/res/xml/network_security_config.xml b/app/android/app/src/main/res/xml/network_security_config.xml new file mode 100644 index 0000000..387c32b --- /dev/null +++ b/app/android/app/src/main/res/xml/network_security_config.xml @@ -0,0 +1,13 @@ + + + + + 192.168.180.10 + 192.168.0.0/16 + 10.0.0.0/8 + 10.0.2.2 + 172.16.0.0/12 + localhost + 127.0.0.1 + + diff --git a/app/android/app/src/profile/AndroidManifest.xml b/app/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/app/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/app/android/build.gradle.kts b/app/android/build.gradle.kts new file mode 100644 index 0000000..89176ef --- /dev/null +++ b/app/android/build.gradle.kts @@ -0,0 +1,21 @@ +allprojects { + repositories { + google() + mavenCentral() + } +} + +val newBuildDir: Directory = rootProject.layout.buildDirectory.dir("../../build").get() +rootProject.layout.buildDirectory.value(newBuildDir) + +subprojects { + val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name) + project.layout.buildDirectory.value(newSubprojectBuildDir) +} +subprojects { + project.evaluationDependsOn(":app") +} + +tasks.register("clean") { + delete(rootProject.layout.buildDirectory) +} diff --git a/app/android/gradle.properties b/app/android/gradle.properties new file mode 100644 index 0000000..f018a61 --- /dev/null +++ b/app/android/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError +android.useAndroidX=true +android.enableJetifier=true diff --git a/app/android/gradle/wrapper/gradle-wrapper.properties b/app/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..afa1e8e --- /dev/null +++ b/app/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-all.zip diff --git a/app/android/settings.gradle.kts b/app/android/settings.gradle.kts new file mode 100644 index 0000000..11662c3 --- /dev/null +++ b/app/android/settings.gradle.kts @@ -0,0 +1,25 @@ +pluginManagement { + val flutterSdkPath = run { + val properties = java.util.Properties() + file("local.properties").inputStream().use { properties.load(it) } + val flutterSdkPath = properties.getProperty("flutter.sdk") + require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" } + flutterSdkPath + } + + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") + + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +plugins { + id("dev.flutter.flutter-plugin-loader") version "1.0.0" + id("com.android.application") version "8.7.0" apply false + id("org.jetbrains.kotlin.android") version "2.1.0" apply false +} + +include(":app") diff --git a/app/devtools_options.yaml b/app/devtools_options.yaml new file mode 100644 index 0000000..fa0b357 --- /dev/null +++ b/app/devtools_options.yaml @@ -0,0 +1,3 @@ +description: This file stores settings for Dart & Flutter DevTools. +documentation: https://docs.flutter.dev/tools/devtools/extensions#configure-extension-enablement-states +extensions: diff --git a/app/ios/.gitignore b/app/ios/.gitignore new file mode 100644 index 0000000..7a7f987 --- /dev/null +++ b/app/ios/.gitignore @@ -0,0 +1,34 @@ +**/dgph +*.mode1v3 +*.mode2v3 +*.moved-aside +*.pbxuser +*.perspectivev3 +**/*sync/ +.sconsign.dblite +.tags* +**/.vagrant/ +**/DerivedData/ +Icon? +**/Pods/ +**/.symlinks/ +profile +xcuserdata +**/.generated/ +Flutter/App.framework +Flutter/Flutter.framework +Flutter/Flutter.podspec +Flutter/Generated.xcconfig +Flutter/ephemeral/ +Flutter/app.flx +Flutter/app.zip +Flutter/flutter_assets/ +Flutter/flutter_export_environment.sh +ServiceDefinitions.json +Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!default.mode1v3 +!default.mode2v3 +!default.pbxuser +!default.perspectivev3 diff --git a/app/ios/Flutter/AppFrameworkInfo.plist b/app/ios/Flutter/AppFrameworkInfo.plist new file mode 100644 index 0000000..7c56964 --- /dev/null +++ b/app/ios/Flutter/AppFrameworkInfo.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + App + CFBundleIdentifier + io.flutter.flutter.app + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + App + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + MinimumOSVersion + 12.0 + + diff --git a/app/ios/Flutter/Debug.xcconfig b/app/ios/Flutter/Debug.xcconfig new file mode 100644 index 0000000..ec97fc6 --- /dev/null +++ b/app/ios/Flutter/Debug.xcconfig @@ -0,0 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" +#include "Generated.xcconfig" diff --git a/app/ios/Flutter/Release.xcconfig b/app/ios/Flutter/Release.xcconfig new file mode 100644 index 0000000..c4855bf --- /dev/null +++ b/app/ios/Flutter/Release.xcconfig @@ -0,0 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" +#include "Generated.xcconfig" diff --git a/app/ios/Podfile b/app/ios/Podfile new file mode 100644 index 0000000..e549ee2 --- /dev/null +++ b/app/ios/Podfile @@ -0,0 +1,43 @@ +# Uncomment this line to define a global platform for your project +# platform :ios, '12.0' + +# CocoaPods analytics sends network stats synchronously affecting flutter build latency. +ENV['COCOAPODS_DISABLE_STATS'] = 'true' + +project 'Runner', { + 'Debug' => :debug, + 'Profile' => :release, + 'Release' => :release, +} + +def flutter_root + generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) + unless File.exist?(generated_xcode_build_settings_path) + raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" + end + + File.foreach(generated_xcode_build_settings_path) do |line| + matches = line.match(/FLUTTER_ROOT\=(.*)/) + return matches[1].strip if matches + end + raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" +end + +require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) + +flutter_ios_podfile_setup + +target 'Runner' do + use_frameworks! + + flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) + target 'RunnerTests' do + inherit! :search_paths + end +end + +post_install do |installer| + installer.pods_project.targets.each do |target| + flutter_additional_ios_build_settings(target) + end +end diff --git a/app/ios/Podfile.lock b/app/ios/Podfile.lock new file mode 100644 index 0000000..94cd685 --- /dev/null +++ b/app/ios/Podfile.lock @@ -0,0 +1,198 @@ +PODS: + - camera_avfoundation (0.0.1): + - Flutter + - DKImagePickerController/Core (4.3.9): + - DKImagePickerController/ImageDataManager + - DKImagePickerController/Resource + - DKImagePickerController/ImageDataManager (4.3.9) + - DKImagePickerController/PhotoGallery (4.3.9): + - DKImagePickerController/Core + - DKPhotoGallery + - DKImagePickerController/Resource (4.3.9) + - DKPhotoGallery (0.0.19): + - DKPhotoGallery/Core (= 0.0.19) + - DKPhotoGallery/Model (= 0.0.19) + - DKPhotoGallery/Preview (= 0.0.19) + - DKPhotoGallery/Resource (= 0.0.19) + - SDWebImage + - SwiftyGif + - DKPhotoGallery/Core (0.0.19): + - DKPhotoGallery/Model + - DKPhotoGallery/Preview + - SDWebImage + - SwiftyGif + - DKPhotoGallery/Model (0.0.19): + - SDWebImage + - SwiftyGif + - DKPhotoGallery/Preview (0.0.19): + - DKPhotoGallery/Model + - DKPhotoGallery/Resource + - SDWebImage + - SwiftyGif + - DKPhotoGallery/Resource (0.0.19): + - SDWebImage + - SwiftyGif + - file_picker (0.0.1): + - DKImagePickerController/PhotoGallery + - Flutter + - file_selector_ios (0.0.1): + - Flutter + - Flutter (1.0.0) + - GoogleDataTransport (9.4.1): + - GoogleUtilities/Environment (~> 7.7) + - nanopb (< 2.30911.0, >= 2.30908.0) + - PromisesObjC (< 3.0, >= 1.2) + - GoogleMLKit/BarcodeScanning (6.0.0): + - GoogleMLKit/MLKitCore + - MLKitBarcodeScanning (~> 5.0.0) + - GoogleMLKit/MLKitCore (6.0.0): + - MLKitCommon (~> 11.0.0) + - GoogleToolboxForMac/Defines (4.2.1) + - GoogleToolboxForMac/Logger (4.2.1): + - GoogleToolboxForMac/Defines (= 4.2.1) + - "GoogleToolboxForMac/NSData+zlib (4.2.1)": + - GoogleToolboxForMac/Defines (= 4.2.1) + - GoogleUtilities/Environment (7.13.3): + - GoogleUtilities/Privacy + - PromisesObjC (< 3.0, >= 1.2) + - GoogleUtilities/Logger (7.13.3): + - GoogleUtilities/Environment + - GoogleUtilities/Privacy + - GoogleUtilities/Privacy (7.13.3) + - GoogleUtilities/UserDefaults (7.13.3): + - GoogleUtilities/Logger + - GoogleUtilities/Privacy + - GoogleUtilitiesComponents (1.1.0): + - GoogleUtilities/Logger + - GTMSessionFetcher/Core (3.5.0) + - MLImage (1.0.0-beta5) + - MLKitBarcodeScanning (5.0.0): + - MLKitCommon (~> 11.0) + - MLKitVision (~> 7.0) + - MLKitCommon (11.0.0): + - GoogleDataTransport (< 10.0, >= 9.4.1) + - GoogleToolboxForMac/Logger (< 5.0, >= 4.2.1) + - "GoogleToolboxForMac/NSData+zlib (< 5.0, >= 4.2.1)" + - GoogleUtilities/UserDefaults (< 8.0, >= 7.13.0) + - GoogleUtilitiesComponents (~> 1.0) + - GTMSessionFetcher/Core (< 4.0, >= 3.3.2) + - MLKitVision (7.0.0): + - GoogleToolboxForMac/Logger (< 5.0, >= 4.2.1) + - "GoogleToolboxForMac/NSData+zlib (< 5.0, >= 4.2.1)" + - GTMSessionFetcher/Core (< 4.0, >= 3.3.2) + - MLImage (= 1.0.0-beta5) + - MLKitCommon (~> 11.0) + - mobile_scanner (5.2.3): + - Flutter + - GoogleMLKit/BarcodeScanning (~> 6.0.0) + - nanopb (2.30910.0): + - nanopb/decode (= 2.30910.0) + - nanopb/encode (= 2.30910.0) + - nanopb/decode (2.30910.0) + - nanopb/encode (2.30910.0) + - ObjectBox (4.4.1) + - objectbox_flutter_libs (0.0.1): + - Flutter + - ObjectBox (= 4.4.1) + - package_info_plus (0.4.5): + - Flutter + - path_provider_foundation (0.0.1): + - Flutter + - FlutterMacOS + - PromisesObjC (2.4.0) + - SDWebImage (5.21.5): + - SDWebImage/Core (= 5.21.5) + - SDWebImage/Core (5.21.5) + - SwiftyGif (5.4.5) + - url_launcher_ios (0.0.1): + - Flutter + - webview_flutter_wkwebview (0.0.1): + - Flutter + - FlutterMacOS + +DEPENDENCIES: + - camera_avfoundation (from `.symlinks/plugins/camera_avfoundation/ios`) + - file_picker (from `.symlinks/plugins/file_picker/ios`) + - file_selector_ios (from `.symlinks/plugins/file_selector_ios/ios`) + - Flutter (from `Flutter`) + - mobile_scanner (from `.symlinks/plugins/mobile_scanner/ios`) + - objectbox_flutter_libs (from `.symlinks/plugins/objectbox_flutter_libs/ios`) + - package_info_plus (from `.symlinks/plugins/package_info_plus/ios`) + - path_provider_foundation (from `.symlinks/plugins/path_provider_foundation/darwin`) + - url_launcher_ios (from `.symlinks/plugins/url_launcher_ios/ios`) + - webview_flutter_wkwebview (from `.symlinks/plugins/webview_flutter_wkwebview/darwin`) + +SPEC REPOS: + trunk: + - DKImagePickerController + - DKPhotoGallery + - GoogleDataTransport + - GoogleMLKit + - GoogleToolboxForMac + - GoogleUtilities + - GoogleUtilitiesComponents + - GTMSessionFetcher + - MLImage + - MLKitBarcodeScanning + - MLKitCommon + - MLKitVision + - nanopb + - ObjectBox + - PromisesObjC + - SDWebImage + - SwiftyGif + +EXTERNAL SOURCES: + camera_avfoundation: + :path: ".symlinks/plugins/camera_avfoundation/ios" + file_picker: + :path: ".symlinks/plugins/file_picker/ios" + file_selector_ios: + :path: ".symlinks/plugins/file_selector_ios/ios" + Flutter: + :path: Flutter + mobile_scanner: + :path: ".symlinks/plugins/mobile_scanner/ios" + objectbox_flutter_libs: + :path: ".symlinks/plugins/objectbox_flutter_libs/ios" + package_info_plus: + :path: ".symlinks/plugins/package_info_plus/ios" + path_provider_foundation: + :path: ".symlinks/plugins/path_provider_foundation/darwin" + url_launcher_ios: + :path: ".symlinks/plugins/url_launcher_ios/ios" + webview_flutter_wkwebview: + :path: ".symlinks/plugins/webview_flutter_wkwebview/darwin" + +SPEC CHECKSUMS: + camera_avfoundation: be3be85408cd4126f250386828e9b1dfa40ab436 + DKImagePickerController: 946cec48c7873164274ecc4624d19e3da4c1ef3c + DKPhotoGallery: b3834fecb755ee09a593d7c9e389d8b5d6deed60 + file_picker: a0560bc09d61de87f12d246fc47d2119e6ef37be + file_selector_ios: f92e583d43608aebc2e4a18daac30b8902845502 + Flutter: e0871f40cf51350855a761d2e70bf5af5b9b5de7 + GoogleDataTransport: 6c09b596d841063d76d4288cc2d2f42cc36e1e2a + GoogleMLKit: 97ac7af399057e99182ee8edfa8249e3226a4065 + GoogleToolboxForMac: d1a2cbf009c453f4d6ded37c105e2f67a32206d8 + GoogleUtilities: ea963c370a38a8069cc5f7ba4ca849a60b6d7d15 + GoogleUtilitiesComponents: 679b2c881db3b615a2777504623df6122dd20afe + GTMSessionFetcher: 5aea5ba6bd522a239e236100971f10cb71b96ab6 + MLImage: 1824212150da33ef225fbd3dc49f184cf611046c + MLKitBarcodeScanning: 10ca0845a6d15f2f6e911f682a1998b68b973e8b + MLKitCommon: afec63980417d29ffbb4790529a1b0a2291699e1 + MLKitVision: e858c5f125ecc288e4a31127928301eaba9ae0c1 + mobile_scanner: 92e8812bf22a8f84131e2a7f9d0f44dad1a4742b + nanopb: 438bc412db1928dac798aa6fd75726007be04262 + ObjectBox: 7da4aceb5013d041bfafdbc6d744a26918b09757 + objectbox_flutter_libs: 09b1dec1b4cd27bf1a5f9bae7ccaa7e43588bf31 + package_info_plus: af8e2ca6888548050f16fa2f1938db7b5a5df499 + path_provider_foundation: 080d55be775b7414fd5a5ef3ac137b97b097e564 + PromisesObjC: f5707f49cb48b9636751c5b2e7d227e43fba9f47 + SDWebImage: e9c98383c7572d713c1a0d7dd2783b10599b9838 + SwiftyGif: 706c60cf65fa2bc5ee0313beece843c8eb8194d4 + url_launcher_ios: 694010445543906933d732453a59da0a173ae33d + webview_flutter_wkwebview: 1821ceac936eba6f7984d89a9f3bcb4dea99ebb2 + +PODFILE CHECKSUM: 4305caec6b40dde0ae97be1573c53de1882a07e5 + +COCOAPODS: 1.16.2 diff --git a/app/ios/Runner.xcodeproj/project.pbxproj b/app/ios/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..5863df3 --- /dev/null +++ b/app/ios/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,746 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXBuildFile section */ + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; + 2510A7C53652D94A0BD1AC0E /* Pods_RunnerTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = B1894F93A282ED106CA1628A /* Pods_RunnerTests.framework */; }; + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; }; + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; + 7750814138033D7B5089EA79 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6A466C5081D4AFB2E83EE48C /* Pods_Runner.framework */; }; + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C8085294A63A400263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 97C146E61CF9000F007C117D /* Project object */; + proxyType = 1; + remoteGlobalIDString = 97C146ED1CF9000F007C117D; + remoteInfo = Runner; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 9705A1C41CF9048500538489 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; + 331C807B294A618700263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 3A0BB33DF424113620931648 /* Pods-RunnerTests.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.profile.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.profile.xcconfig"; sourceTree = ""; }; + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; + 48563AD38CD52F6EB5981C45 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; + 6352F6ED7E5B9DC92334C090 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; + 6A466C5081D4AFB2E83EE48C /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; + 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; + 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 97E626E31BDD11C098C2470E /* Pods-RunnerTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.release.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.release.xcconfig"; sourceTree = ""; }; + A042B5F29AFF592248DD7D50 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; + AB23306D1B7EEAFBF39838CE /* Pods-RunnerTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.debug.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.debug.xcconfig"; sourceTree = ""; }; + B1894F93A282ED106CA1628A /* Pods_RunnerTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_RunnerTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 353CB3693FF9EBD22F03DEB9 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 2510A7C53652D94A0BD1AC0E /* Pods_RunnerTests.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EB1CF9000F007C117D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 7750814138033D7B5089EA79 /* Pods_Runner.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 2AC4A5BBFC8A63F231B5394E /* Pods */ = { + isa = PBXGroup; + children = ( + A042B5F29AFF592248DD7D50 /* Pods-Runner.debug.xcconfig */, + 6352F6ED7E5B9DC92334C090 /* Pods-Runner.release.xcconfig */, + 48563AD38CD52F6EB5981C45 /* Pods-Runner.profile.xcconfig */, + AB23306D1B7EEAFBF39838CE /* Pods-RunnerTests.debug.xcconfig */, + 97E626E31BDD11C098C2470E /* Pods-RunnerTests.release.xcconfig */, + 3A0BB33DF424113620931648 /* Pods-RunnerTests.profile.xcconfig */, + ); + name = Pods; + path = Pods; + sourceTree = ""; + }; + 331C8082294A63A400263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C807B294A618700263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 511A3FF81F794991B7581FB8 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 6A466C5081D4AFB2E83EE48C /* Pods_Runner.framework */, + B1894F93A282ED106CA1628A /* Pods_RunnerTests.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; + 9740EEB11CF90186004384FC /* Flutter */ = { + isa = PBXGroup; + children = ( + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 9740EEB31CF90195004384FC /* Generated.xcconfig */, + ); + name = Flutter; + sourceTree = ""; + }; + 97C146E51CF9000F007C117D = { + isa = PBXGroup; + children = ( + 9740EEB11CF90186004384FC /* Flutter */, + 97C146F01CF9000F007C117D /* Runner */, + 97C146EF1CF9000F007C117D /* Products */, + 331C8082294A63A400263BE5 /* RunnerTests */, + 2AC4A5BBFC8A63F231B5394E /* Pods */, + 511A3FF81F794991B7581FB8 /* Frameworks */, + ); + sourceTree = ""; + }; + 97C146EF1CF9000F007C117D /* Products */ = { + isa = PBXGroup; + children = ( + 97C146EE1CF9000F007C117D /* Runner.app */, + 331C8081294A63A400263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 97C146F01CF9000F007C117D /* Runner */ = { + isa = PBXGroup; + children = ( + 97C146FA1CF9000F007C117D /* Main.storyboard */, + 97C146FD1CF9000F007C117D /* Assets.xcassets */, + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, + 97C147021CF9000F007C117D /* Info.plist */, + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, + ); + path = Runner; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C8080294A63A400263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 34F233ACE4BA3F5B820F795F /* [CP] Check Pods Manifest.lock */, + 331C807D294A63A400263BE5 /* Sources */, + 331C807F294A63A400263BE5 /* Resources */, + 353CB3693FF9EBD22F03DEB9 /* Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + 331C8086294A63A400263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C8081294A63A400263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 97C146ED1CF9000F007C117D /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + B808696A3E30F0EC4B8DF6F5 /* [CP] Check Pods Manifest.lock */, + 9740EEB61CF901F6004384FC /* Run Script */, + 97C146EA1CF9000F007C117D /* Sources */, + 97C146EB1CF9000F007C117D /* Frameworks */, + 97C146EC1CF9000F007C117D /* Resources */, + 9705A1C41CF9048500538489 /* Embed Frameworks */, + 3B06AD1E1E4923F5004D2608 /* Thin Binary */, + 70582023162C4E4C0B4CC063 /* [CP] Embed Pods Frameworks */, + DE505B8273E1DC801F9E27AD /* [CP] Copy Pods Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Runner; + productName = Runner; + productReference = 97C146EE1CF9000F007C117D /* Runner.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 97C146E61CF9000F007C117D /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C8080294A63A400263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 97C146ED1CF9000F007C117D; + }; + 97C146ED1CF9000F007C117D = { + CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 1100; + }; + }; + }; + buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 97C146E51CF9000F007C117D; + productRefGroup = 97C146EF1CF9000F007C117D /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 97C146ED1CF9000F007C117D /* Runner */, + 331C8080294A63A400263BE5 /* RunnerTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C807F294A63A400263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EC1CF9000F007C117D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 34F233ACE4BA3F5B820F795F /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-RunnerTests-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${TARGET_BUILD_DIR}/${INFOPLIST_PATH}", + ); + name = "Thin Binary"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; + }; + 70582023162C4E4C0B4CC063 /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-input-files.xcfilelist", + ); + name = "[CP] Embed Pods Frameworks"; + outputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-output-files.xcfilelist", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + 9740EEB61CF901F6004384FC /* Run Script */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Run Script"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; + }; + B808696A3E30F0EC4B8DF6F5 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + DE505B8273E1DC801F9E27AD /* [CP] Copy Pods Resources */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-resources-${CONFIGURATION}-input-files.xcfilelist", + ); + name = "[CP] Copy Pods Resources"; + outputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-resources-${CONFIGURATION}-output-files.xcfilelist", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-resources.sh\"\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C807D294A63A400263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EA1CF9000F007C117D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C8086294A63A400263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 97C146ED1CF9000F007C117D /* Runner */; + targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 97C146FA1CF9000F007C117D /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C146FB1CF9000F007C117D /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C147001CF9000F007C117D /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 249021D3217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Profile; + }; + 249021D4217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = de.assecutor.votianltApp; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Profile; + }; + 331C8088294A63A400263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = AB23306D1B7EEAFBF39838CE /* Pods-RunnerTests.debug.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = de.assecutor.votianltApp.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Debug; + }; + 331C8089294A63A400263BE5 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 97E626E31BDD11C098C2470E /* Pods-RunnerTests.release.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = de.assecutor.votianltApp.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Release; + }; + 331C808A294A63A400263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 3A0BB33DF424113620931648 /* Pods-RunnerTests.profile.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = de.assecutor.votianltApp.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Profile; + }; + 97C147031CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 97C147041CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 97C147061CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = de.assecutor.votianltApp; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Debug; + }; + 97C147071CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = de.assecutor.votianltApp; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C8088294A63A400263BE5 /* Debug */, + 331C8089294A63A400263BE5 /* Release */, + 331C808A294A63A400263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147031CF9000F007C117D /* Debug */, + 97C147041CF9000F007C117D /* Release */, + 249021D3217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147061CF9000F007C117D /* Debug */, + 97C147071CF9000F007C117D /* Release */, + 249021D4217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 97C146E61CF9000F007C117D /* Project object */; +} diff --git a/app/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/app/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/app/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/app/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/app/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/app/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/app/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/app/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/app/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/app/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/app/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..15cada4 --- /dev/null +++ b/app/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,99 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/ios/Runner.xcworkspace/contents.xcworkspacedata b/app/ios/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..21a3cc1 --- /dev/null +++ b/app/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/app/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/app/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/app/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/app/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/app/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/app/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/app/ios/Runner/AppDelegate.swift b/app/ios/Runner/AppDelegate.swift new file mode 100644 index 0000000..6266644 --- /dev/null +++ b/app/ios/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import Flutter +import UIKit + +@main +@objc class AppDelegate: FlutterAppDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + GeneratedPluginRegistrant.register(with: self) + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } +} diff --git a/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..d36b1fa --- /dev/null +++ b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,122 @@ +{ + "images" : [ + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@3x.png", + "scale" : "3x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@3x.png", + "scale" : "3x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@3x.png", + "scale" : "3x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@2x.png", + "scale" : "2x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@3x.png", + "scale" : "3x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@1x.png", + "scale" : "1x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@1x.png", + "scale" : "1x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@1x.png", + "scale" : "1x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@2x.png", + "scale" : "2x" + }, + { + "size" : "83.5x83.5", + "idiom" : "ipad", + "filename" : "Icon-App-83.5x83.5@2x.png", + "scale" : "2x" + }, + { + "size" : "1024x1024", + "idiom" : "ios-marketing", + "filename" : "Icon-App-1024x1024@1x.png", + "scale" : "1x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png new file mode 100644 index 0000000..dc9ada4 Binary files /dev/null and b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png differ diff --git a/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png new file mode 100644 index 0000000..7353c41 Binary files /dev/null and b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png new file mode 100644 index 0000000..797d452 Binary files /dev/null and b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ diff --git a/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png new file mode 100644 index 0000000..6ed2d93 Binary files /dev/null and b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png new file mode 100644 index 0000000..4cd7b00 Binary files /dev/null and b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ diff --git a/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png new file mode 100644 index 0000000..fe73094 Binary files /dev/null and b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png new file mode 100644 index 0000000..321773c Binary files /dev/null and b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png new file mode 100644 index 0000000..797d452 Binary files /dev/null and b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ diff --git a/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png new file mode 100644 index 0000000..502f463 Binary files /dev/null and b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ diff --git a/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png new file mode 100644 index 0000000..0ec3034 Binary files /dev/null and b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ diff --git a/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png new file mode 100644 index 0000000..0ec3034 Binary files /dev/null and b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ diff --git a/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png new file mode 100644 index 0000000..e9f5fea Binary files /dev/null and b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ diff --git a/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png new file mode 100644 index 0000000..84ac32a Binary files /dev/null and b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png new file mode 100644 index 0000000..8953cba Binary files /dev/null and b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png new file mode 100644 index 0000000..0467bf1 Binary files /dev/null and b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 0000000..0bedcf2 --- /dev/null +++ b/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "LaunchImage.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differ diff --git a/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png differ diff --git a/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png differ diff --git a/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md new file mode 100644 index 0000000..89c2725 --- /dev/null +++ b/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md @@ -0,0 +1,5 @@ +# Launch Screen Assets + +You can customize the launch screen with your own desired assets by replacing the image files in this directory. + +You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. \ No newline at end of file diff --git a/app/ios/Runner/Base.lproj/LaunchScreen.storyboard b/app/ios/Runner/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..f2e259c --- /dev/null +++ b/app/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/ios/Runner/Base.lproj/Main.storyboard b/app/ios/Runner/Base.lproj/Main.storyboard new file mode 100644 index 0000000..f3c2851 --- /dev/null +++ b/app/ios/Runner/Base.lproj/Main.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/ios/Runner/Info.plist b/app/ios/Runner/Info.plist new file mode 100644 index 0000000..7e35d6c --- /dev/null +++ b/app/ios/Runner/Info.plist @@ -0,0 +1,68 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + Votianlt App + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + votianlt_app + CFBundlePackageType + APPL + CFBundleShortVersionString + ${FLUTTER_BUILD_NAME:1.0.0} + CFBundleSignature + ???? + CFBundleVersion + ${FLUTTER_BUILD_NUMBER:1} + LSRequiresIPhoneOS + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + CADisableMinimumFrameDurationOnPhone + + UIApplicationSupportsIndirectInputEvents + + + NSAppTransportSecurity + + NSAllowsArbitraryLoads + + NSAllowsLocalNetworking + + + NSLocalNetworkUsageDescription + This app needs to connect to local network services for STOMP messaging. + NSCameraUsageDescription + This app needs access to camera to take photos for task completion. + NSPhotoLibraryUsageDescription + This app needs access to photo library to save and manage task photos. + + NSLocationWhenInUseUsageDescription + This app needs access to your location to track delivery routes. + NSLocationAlwaysUsageDescription + This app needs access to your location to track delivery routes even when in the background. + + diff --git a/app/ios/Runner/Runner-Bridging-Header.h b/app/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 0000000..308a2a5 --- /dev/null +++ b/app/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1 @@ +#import "GeneratedPluginRegistrant.h" diff --git a/app/ios/RunnerTests/RunnerTests.swift b/app/ios/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..86a7c3b --- /dev/null +++ b/app/ios/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Flutter +import UIKit +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/app/lib/app_state.dart b/app/lib/app_state.dart new file mode 100644 index 0000000..53872f6 --- /dev/null +++ b/app/lib/app_state.dart @@ -0,0 +1,173 @@ +import 'dart:async'; +import 'package:flutter/material.dart'; +import 'models/job.dart'; +import 'services/database_service.dart'; +import 'services/dart_mq.dart'; +import 'l10n/app_localizations.dart'; + +/// Global notifier for language changes +final ValueNotifier localeNotifier = ValueNotifier(const Locale('de')); + +class AppState { + static final AppState _instance = AppState._internal(); + factory AppState() => _instance; + AppState._internal(); + + String? _loggedInEmail; + List _assignedJobs = []; + final DatabaseService _databaseService = DatabaseService(); + + // Language settings + String _languageCode = 'de'; + String get languageCode => _languageCode; + + /// Get current locale + Locale get currentLocale => Locale(_languageCode); + + /// Set language and update the global notifier + Future setLanguage(String languageCode) async { + if (supportedLanguageCodes.contains(languageCode)) { + _languageCode = languageCode; + await _databaseService.saveLanguagePreference(languageCode); + localeNotifier.value = Locale(languageCode); + } + } + + /// Load language preference from database + Future loadLanguagePreference() async { + final savedLanguage = await _databaseService.loadLanguagePreference(); + if (savedLanguage != null && supportedLanguageCodes.contains(savedLanguage)) { + _languageCode = savedLanguage; + localeNotifier.value = Locale(savedLanguage); + } + } + + // Serialize persistence to avoid overlapping DB save/load cycles + bool _isPersistingJobs = false; + List? _pendingJobs; // holds the latest jobs to persist if calls overlap + + // Jobs update notification (emitted once after DB was updated) + final StreamController _jobsUpdatedController = StreamController.broadcast(); + Stream get jobsUpdated => _jobsUpdatedController.stream; + + /// The logged-in user's email (used as local identifier for chats) + String? get loggedInEmail => _loggedInEmail; + + List get assignedJobs => List.unmodifiable(_assignedJobs); + + void setLoggedInEmail(String email) { + _loggedInEmail = email; + } + + Future clearLogin() async { + _loggedInEmail = null; + _assignedJobs.clear(); + // Clear database + await _databaseService.clearAllData(); + // Notify listeners/UI that jobs were cleared + _jobsUpdatedController.add(null); + DartMQ().publish(MQTopics.jobsUpdated, null); + } + + bool get isLoggedIn => _loggedInEmail != null; + + Future setAssignedJobs(List jobs) async { + // Coalesce overlapping calls: if a persist is already running, remember only the latest + if (_isPersistingJobs) { + _pendingJobs = jobs; + return; + } + + _isPersistingJobs = true; + try { + // Start with the initial batch to persist + var toPersist = jobs; + while (true) { + // Normalize first + final normalized = toPersist.map((j) => j.normalized()).toList(); + + // Persist normalized list to DB only (no UI notifications here) + await _databaseService.saveJobs(normalized); + + // If another request came in during persistence, handle only the latest once + if (_pendingJobs != null) { + toPersist = _pendingJobs!; + _pendingJobs = null; + continue; + } + break; + } + // After DB is updated with the latest data, notify listeners once to refresh UI + _jobsUpdatedController.add(null); + // Also publish via dart_mq for app-wide decoupled messaging + DartMQ().publish(MQTopics.jobsUpdated, null); + } finally { + _isPersistingJobs = false; + } + } + + void addJob(Job job) { + if (!_assignedJobs.contains(job)) { + _assignedJobs.add(job); + } + } + + void removeJob(String jobId) { + _assignedJobs.removeWhere((job) => job.id == jobId); + // Update database + _databaseService.saveJobs(_assignedJobs); + } + + /// Delete a job by ID (called when server sends job_deleted event) + Future deleteJob(String jobId) async { + _assignedJobs.removeWhere((job) => job.id == jobId); + // Delete from database + await _databaseService.deleteJob(jobId); + // Notify listeners + _jobsUpdatedController.add(null); + DartMQ().publish(MQTopics.jobsUpdated, null); + } + + /// Add a new job (called when server sends job_created event) + Future addNewJob(Job job) async { + // Check if job already exists + if (_assignedJobs.any((j) => j.id == job.id)) { + return; + } + // Add to memory + _assignedJobs.insert(0, job); + // Persist to database + await _databaseService.saveOrUpdateJob(job); + // Notify listeners + _jobsUpdatedController.add(null); + DartMQ().publish(MQTopics.jobsUpdated, null); + } + + /// Load login state from saved credentials on app start + Future loadLoginFromDatabase() async { + final credentials = await _databaseService.loadCredentials(); + if (credentials != null) { + _loggedInEmail = credentials.email; + } + } + + void updateJob(Job updatedJob) { + final index = _assignedJobs.indexWhere((job) => job.id == updatedJob.id); + if (index != -1) { + _assignedJobs[index] = updatedJob; + } + } + + /// Refresh in-memory jobs from the database without emitting other notifications + Future refreshJobsFromDatabase() async { + final jobs = await _databaseService.loadJobs(); + _assignedJobs = jobs; + } + + /// Persistently upsert a single job and refresh in-memory list + Future upsertJob(Job job) async { + await _databaseService.saveOrUpdateJob(job); + final persisted = await _databaseService.loadJobs(); + _assignedJobs = persisted.isNotEmpty ? persisted : _assignedJobs; + } +} diff --git a/app/lib/cargo_items_view.dart b/app/lib/cargo_items_view.dart new file mode 100644 index 0000000..2c659c8 --- /dev/null +++ b/app/lib/cargo_items_view.dart @@ -0,0 +1,437 @@ +import 'package:flutter/material.dart'; + +import 'l10n/app_localizations.dart'; +import 'models/delivery_station.dart'; +import 'models/job.dart'; +import 'services/database_service.dart'; +import 'task_view.dart'; +import 'widgets/offline_banner.dart'; + +@visibleForTesting +Color? deliveryStationCardBackgroundColor( + DeliveryStation station, + Map taskStatuses, +) { + if (station.tasks.isEmpty) { + return null; + } + + final isCompleted = station.tasks.every( + (task) => taskStatuses[task.id] ?? task.completed, + ); + return isCompleted ? Colors.green[50] : null; +} + +class CargoItemsView extends StatefulWidget { + final Job job; + + const CargoItemsView({super.key, required this.job}); + + @override + State createState() => _CargoItemsViewState(); +} + +class _CargoItemsViewState extends State { + final DatabaseService _databaseService = DatabaseService(); + Map _taskStatuses = const {}; + + @override + void initState() { + super.initState(); + _loadLocalTaskStatuses(); + } + + Future _loadLocalTaskStatuses() async { + final map = await _databaseService.loadAllTaskStatuses(); + if (!mounted) return; + setState(() { + _taskStatuses = map; + }); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: Text(widget.job.jobNumber), + backgroundColor: Colors.deepPurple[100], + leading: IconButton( + icon: const Icon(Icons.arrow_back), + onPressed: () { + Navigator.of(context).pop(); + }, + ), + actions: [ + IconButton( + icon: const Icon(Icons.chat), + onPressed: () { + Navigator.of(context).pushNamed('/chats'); + }, + tooltip: AppLocalizations.of(context).openChat, + ), + ], + ), + body: Column( + children: [ + OfflineBanner(), + // Main content area + Expanded( + child: Padding( + padding: const EdgeInsets.all(16.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Job summary card + Card( + margin: const EdgeInsets.only(bottom: 16), + elevation: 2, + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + widget.job.jobNumber.isNotEmpty + ? widget.job.jobNumber + : widget.job.title, + style: const TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + ), + ), + if (widget.job.customerSelection.isNotEmpty) ...[ + const SizedBox(height: 4), + Text( + widget.job.customerSelection, + style: TextStyle( + fontSize: 14, + color: Colors.grey[700], + fontWeight: FontWeight.w500, + ), + ), + ], + const SizedBox(height: 8), + Row( + children: [ + Icon( + Icons.arrow_upward, + size: 16, + color: Colors.green[600], + ), + const SizedBox(width: 4), + Text( + widget.job.pickupCity, + style: TextStyle( + fontSize: 12, + color: Colors.grey[700], + ), + ), + const SizedBox(width: 8), + Icon( + Icons.arrow_forward, + size: 16, + color: Colors.grey[600], + ), + const SizedBox(width: 8), + Icon( + Icons.arrow_downward, + size: 16, + color: Colors.blue[600], + ), + const SizedBox(width: 4), + Text( + widget.job.deliveryCitiesDisplay.isNotEmpty + ? widget.job.deliveryCitiesDisplay + : widget.job.deliveryCity, + style: TextStyle( + fontSize: 12, + color: Colors.grey[700], + ), + ), + ], + ), + ], + ), + ), + ), + // Delivery stations section header + Row( + children: [ + Icon( + Icons.local_shipping_outlined, + size: 24, + color: Colors.deepPurple[600], + ), + const SizedBox(width: 8), + Text( + 'Lieferstationen (${_deliveryStations.length})', + style: const TextStyle( + fontSize: 20, + fontWeight: FontWeight.bold, + ), + ), + ], + ), + const SizedBox(height: 16), + Expanded(child: _buildDeliveryStationsList()), + ], + ), + ), + ), + ], + ), + ); + } + + List get _deliveryStations { + if (widget.job.deliveryStations.isNotEmpty) { + return widget.job.deliveryStations; + } + + return [ + DeliveryStation( + stationOrder: 0, + company: widget.job.deliveryCompany, + salutation: widget.job.deliverySalutation, + firstName: widget.job.deliveryFirstName, + lastName: widget.job.deliveryLastName, + phone: widget.job.deliveryPhone, + street: widget.job.deliveryStreet, + houseNumber: widget.job.deliveryHouseNumber, + addressAddition: widget.job.deliveryAddressAddition, + zip: widget.job.deliveryZip, + city: widget.job.deliveryCity, + deliveryDate: widget.job.deliveryDate, + deliveryTime: widget.job.deliveryTime, + tasks: widget.job.tasks, + ), + ]; + } + + Widget _buildDeliveryStationsList() { + if (_deliveryStations.isEmpty) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon( + Icons.local_shipping_outlined, + size: 64, + color: Colors.grey[400], + ), + const SizedBox(height: 16), + Text( + 'Keine Lieferstationen', + style: TextStyle(fontSize: 16, color: Colors.grey[600]), + ), + const SizedBox(height: 8), + Text( + 'Dieser Job enthält aktuell keine Lieferstationen.', + style: TextStyle(fontSize: 14, color: Colors.grey[500]), + textAlign: TextAlign.center, + ), + ], + ), + ); + } + + return ListView.builder( + itemCount: _deliveryStations.length, + itemBuilder: (context, index) { + final station = _deliveryStations[index]; + return _buildDeliveryStationCard(station); + }, + ); + } + + Widget _buildDeliveryStationCard(DeliveryStation station) { + final backgroundColor = deliveryStationCardBackgroundColor( + station, + _taskStatuses, + ); + final title = + station.displayName.isNotEmpty ? station.displayName : station.company; + final subtitle = + station.company.isNotEmpty && station.company != title + ? station.company + : null; + final addressLines = + [ + [ + station.street, + station.houseNumber, + ].where((part) => part.trim().isNotEmpty).join(' '), + if (station.addressAddition.trim().isNotEmpty) + station.addressAddition, + [ + station.zip, + station.city, + ].where((part) => part.trim().isNotEmpty).join(' '), + ].where((line) => line.trim().isNotEmpty).toList(); + + return Card( + color: backgroundColor, + margin: const EdgeInsets.symmetric(horizontal: 0, vertical: 8), + elevation: 2, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + side: BorderSide(color: Colors.grey[300]!, width: 1), + ), + clipBehavior: Clip.antiAlias, + child: InkWell( + onTap: () async { + await Navigator.of(context).push( + MaterialPageRoute( + builder: + (context) => TaskView( + job: widget.job, + stationOrder: station.stationOrder, + stationTitle: + station.displayName.isNotEmpty + ? station.displayName + : 'Station ${station.stationOrder + 1}', + ), + ), + ); + await _loadLocalTaskStatuses(); + }, + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Container( + padding: const EdgeInsets.symmetric( + horizontal: 8, + vertical: 4, + ), + decoration: BoxDecoration( + color: Colors.deepPurple[100], + borderRadius: BorderRadius.circular(12), + ), + child: Text( + 'Station ${station.stationOrder + 1}', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Colors.deepPurple[700], + ), + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title.isNotEmpty ? title : 'Unbenannte Station', + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.bold, + ), + ), + if (subtitle != null) ...[ + const SizedBox(height: 2), + Text( + subtitle, + style: TextStyle( + fontSize: 13, + color: Colors.grey[700], + ), + ), + ], + ], + ), + ), + ], + ), + const SizedBox(height: 12), + _buildDetailItem( + Icons.location_on_outlined, + AppLocalizations.of(context).location, + addressLines.join('\n'), + Colors.blue, + ), + if (station.phone.trim().isNotEmpty) ...[ + const SizedBox(height: 12), + _buildDetailItem( + Icons.phone_outlined, + 'Telefon', + station.phone, + Colors.green, + ), + ], + if (station.deliveryDate.trim().isNotEmpty || + station.deliveryTime.trim().isNotEmpty) ...[ + const SizedBox(height: 12), + _buildDetailItem( + Icons.schedule, + AppLocalizations.of(context).delivery, + [ + station.deliveryDate, + station.deliveryTime, + ].where((part) => part.trim().isNotEmpty).join(' '), + Colors.orange, + ), + ], + const SizedBox(height: 12), + _buildDetailItem( + Icons.task_alt, + AppLocalizations.of(context).tasks, + '${station.tasks.length}', + Colors.deepPurple, + ), + ], + ), + ), + ), + ); + } + + Widget _buildDetailItem( + IconData icon, + String label, + String value, + Color color, + ) { + return Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: color.withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: color.withValues(alpha: 0.3)), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon(icon, size: 16, color: color.withValues(alpha: 0.8)), + const SizedBox(width: 4), + Text( + label, + style: TextStyle( + fontSize: 12, + color: Colors.grey[700], + fontWeight: FontWeight.w500, + ), + ), + ], + ), + const SizedBox(height: 4), + Text( + value, + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + color: Colors.grey[800], + ), + ), + ], + ), + ); + } +} diff --git a/app/lib/chat_details_view.dart b/app/lib/chat_details_view.dart new file mode 100644 index 0000000..7db0089 --- /dev/null +++ b/app/lib/chat_details_view.dart @@ -0,0 +1,692 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:image/image.dart' as img; +import 'l10n/app_localizations.dart'; +import 'app_state.dart'; +import 'models/chat.dart'; +import 'models/chat_message.dart'; +import 'services/chat_service.dart'; +import 'services/websocket_service.dart'; +import 'services/notification_service.dart'; +import 'widgets/chat_photo_dialog.dart'; +import 'widgets/offline_banner.dart'; + +class ChatDetailsView extends StatefulWidget { + final Chat chat; + + const ChatDetailsView({super.key, required this.chat}); + + @override + State createState() => _ChatDetailsViewState(); +} + +class _PreparedImage { + const _PreparedImage({required this.base64DataUri, required this.bytes}); + + final String base64DataUri; + final Uint8List bytes; +} + +class _ChatDetailsViewState extends State { + final TextEditingController _messageController = TextEditingController(); + final ScrollController _scrollController = ScrollController(); + late List _messages; + final WebSocketService _webSocketService = WebSocketService(); + StreamSubscription>? _chatsStreamSubscription; + String? _currentUserId; + late final String _conversationKey; + final ChatService _chatService = ChatService(); + final Map _imageCache = {}; + late Chat _activeChat; + static const int _maxDisplayMessages = 30; + + @override + void initState() { + super.initState(); + _activeChat = widget.chat; + _conversationKey = _activeChat.id; + NotificationService().activeConversationKey = _conversationKey; + _messages = _lastMessages(_activeChat.messages); + _currentUserId = AppState().loggedInEmail; + + _chatsStreamSubscription = _chatService.chatsStream.listen( + _handleChatsUpdate, + ); + + _chatService.initialize().then((_) async { + _syncActiveChatFromService(replaceMessages: _messages.isEmpty); + final history = await _chatService.loadMessagesForChat(_conversationKey); + if (!mounted) return; + if (history.isNotEmpty) { + setState(() { + _imageCache.clear(); + _messages = _lastMessages(history); + }); + _scrollToBottom(immediate: true); + } + _syncActiveChatFromService(); + await _chatService.markConversationRead(_conversationKey); + }); + + // Scroll to bottom after initial build is complete + _scrollToBottom(immediate: true); + } + + @override + void dispose() { + if (NotificationService().activeConversationKey == _conversationKey) { + NotificationService().activeConversationKey = null; + } + _chatsStreamSubscription?.cancel(); + _messageController.dispose(); + _scrollController.dispose(); + super.dispose(); + } + + void _scrollToBottom({bool immediate = false}) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!_scrollController.hasClients) { + return; + } + final target = _scrollController.position.maxScrollExtent; + if (immediate) { + _scrollController.jumpTo(target); + } else { + _scrollController.animateTo( + target, + duration: const Duration(milliseconds: 250), + curve: Curves.easeOut, + ); + } + }); + } + + void _handleChatsUpdate(List chats) { + if (!mounted) { + return; + } + final updated = _findChatById(chats); + if (updated == null) { + return; + } + + final shouldReplace = _shouldReplaceMessages(updated); + + setState(() { + _activeChat = updated; + if (shouldReplace) { + _imageCache.clear(); + _messages = _lastMessages(updated.messages); + } + }); + + if (shouldReplace) { + _scrollToBottom(); + unawaited(_chatService.markConversationRead(_conversationKey)); + } + } + + bool _shouldReplaceMessages(Chat chat) { + if (chat.messages.length != _messages.length) { + return true; + } + if (_messages.isEmpty) { + return false; + } + final currentLast = _messages.last; + final updatedLast = chat.messages.last; + return currentLast.id != updatedLast.id || + currentLast.content != updatedLast.content || + currentLast.contentType != updatedLast.contentType; + } + + List _lastMessages(List messages) { + final sorted = List.from(messages) + ..sort((a, b) => a.createdAt.compareTo(b.createdAt)); + if (sorted.length > _maxDisplayMessages) { + return sorted.sublist(sorted.length - _maxDisplayMessages); + } + return sorted; + } + + Chat? _findChatById(List chats) { + for (final chat in chats) { + if (chat.id == _conversationKey) { + return chat; + } + } + return null; + } + + void _syncActiveChatFromService({bool replaceMessages = false}) { + final updated = _findChatById(_chatService.currentChats); + if (updated == null || !mounted) { + return; + } + + final shouldReplace = replaceMessages || _shouldReplaceMessages(updated); + + setState(() { + _activeChat = updated; + if (shouldReplace) { + _imageCache.clear(); + _messages = _lastMessages(updated.messages); + } + }); + + if (shouldReplace) { + _scrollToBottom(); + unawaited(_chatService.markConversationRead(_conversationKey)); + } + } + + Future _sendMessage() async { + final text = _messageController.text.trim(); + if (text.isEmpty) { + return; + } + + final sender = _currentUserId; + final receiver = _activeChat.receiver; + + if (sender == null || sender.isEmpty) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(AppLocalizations.of(context).noSenderMessage), + ), + ); + } + return; + } + + if (receiver == null || receiver.isEmpty) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(AppLocalizations.of(context).noRecipientMessage), + ), + ); + } + return; + } + + final result = await _webSocketService.sendChatMessage( + sender: sender, + receiver: receiver, + content: text, + jobId: _activeChat.jobId, + jobNumber: _activeChat.jobNumber, + ); + + if (result == null) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(AppLocalizations.of(context).messageSendError), + ), + ); + } + return; + } + + await _chatService.saveOutgoingMessage(result); + _syncActiveChatFromService(); + + _messageController.clear(); + + _scrollToBottom(); + } + + @override + Widget build(BuildContext context) { + final isJobChat = _activeChat.type == ChatType.jobSpecific; + + return Scaffold( + appBar: AppBar( + title: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(_activeChat.title, style: const TextStyle(fontSize: 16)), + if (isJobChat && _activeChat.jobNumber != null) + Text( + 'Job-Nr: ${_activeChat.jobNumber}', + style: TextStyle( + fontSize: 12, + color: Colors.grey[600], + fontWeight: FontWeight.normal, + ), + ), + ], + ), + backgroundColor: Colors.deepPurple[100], + actions: [ + IconButton( + icon: Icon(isJobChat ? Icons.work : Icons.support_agent), + onPressed: () { + // Show chat info + _showChatInfo(); + }, + tooltip: AppLocalizations.of(context).chatInfo, + ), + ], + ), + body: Column( + children: [ + const OfflineBanner(), + // Messages list + Expanded( + child: Container( + decoration: BoxDecoration(color: Colors.grey[50]), + child: ListView.builder( + controller: _scrollController, + padding: const EdgeInsets.fromLTRB(8, 8, 8, 96), + itemCount: _messages.length, + itemBuilder: (context, index) { + final message = _messages[index]; + return _buildMessageBubble(message); + }, + ), + ), + ), + // Message input + _buildMessageInput(), + ], + ), + ); + } + + Widget _buildMessageBubble(ChatMessage message) { + final isOwn = message.isOwn; + final isImage = message.contentType == ChatContentType.image; + + return Padding( + padding: const EdgeInsets.symmetric(vertical: 2), + child: Row( + mainAxisAlignment: + isOwn ? MainAxisAlignment.end : MainAxisAlignment.start, + children: [ + if (!isOwn) const SizedBox(width: 8), + Flexible( + child: Container( + constraints: BoxConstraints( + maxWidth: MediaQuery.of(context).size.width * 0.7, + ), + margin: EdgeInsets.only( + left: isOwn ? 40 : 0, + right: isOwn ? 0 : 40, + ), + padding: EdgeInsets.symmetric( + horizontal: isImage ? 6 : 12, + vertical: isImage ? 6 : 8, + ), + decoration: BoxDecoration( + color: isOwn ? Colors.deepPurple[100] : Colors.white, + borderRadius: BorderRadius.only( + topLeft: const Radius.circular(12), + topRight: const Radius.circular(12), + bottomLeft: Radius.circular(isOwn ? 12 : 4), + bottomRight: Radius.circular(isOwn ? 4 : 12), + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.1), + blurRadius: 2, + offset: const Offset(0, 1), + ), + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildMessageContent(message, isImage: isImage), + const SizedBox(height: 4), + Row( + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.end, + children: [ + Text( + _formatMessageTime(message.createdAt), + style: TextStyle(fontSize: 11, color: Colors.grey[600]), + ), + if (isOwn) ...[ + const SizedBox(width: 4), + Icon( + message.pendingSync + ? Icons.schedule + : (message.read ? Icons.done_all : Icons.done), + size: 14, + color: + message.pendingSync + ? Colors.orange[700] + : (message.read + ? Colors.deepPurple[400] + : Colors.grey[600]), + ), + ], + ], + ), + ], + ), + ), + ), + if (isOwn) const SizedBox(width: 8), + ], + ), + ); + } + + Widget _buildMessageContent(ChatMessage message, {required bool isImage}) { + if (!isImage) { + return Text( + message.content, + style: TextStyle(fontSize: 15, color: Colors.grey[800]), + ); + } + + final imageBytes = _imageCache[message.id] ?? _decodeImageBytes(message); + + if (imageBytes == null) { + return const Text( + 'Bild konnte nicht geladen werden.', + style: TextStyle(fontSize: 15), + ); + } + + return GestureDetector( + onTap: () => _showImagePreview(imageBytes), + child: ClipRRect( + borderRadius: BorderRadius.circular(12), + child: Container( + color: Colors.black.withValues(alpha: 0.05), + constraints: const BoxConstraints(maxWidth: 260, minWidth: 140), + child: AspectRatio( + aspectRatio: 4 / 3, + child: Image.memory(imageBytes, fit: BoxFit.cover), + ), + ), + ), + ); + } + + Uint8List? _decodeImageBytes(ChatMessage message) { + final rawContent = message.content.trim(); + if (rawContent.isEmpty) { + return null; + } + + final base64Payload = + rawContent.startsWith('data:') + ? rawContent.substring(rawContent.indexOf(',') + 1) + : rawContent; + + final normalized = base64Payload.replaceAll(RegExp(r'\s'), ''); + + try { + final bytes = base64Decode(normalized); + _imageCache[message.id] = bytes; + return bytes; + } catch (_) { + return null; + } + } + + Future _showImagePreview(Uint8List imageBytes) async { + if (!mounted) return; + await showDialog( + context: context, + builder: (context) { + return Dialog( + insetPadding: const EdgeInsets.all(16), + backgroundColor: Colors.black, + child: InteractiveViewer( + child: Image.memory(imageBytes, fit: BoxFit.contain), + ), + ); + }, + ); + } + + Widget _buildMessageInput() { + return Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: Colors.white, + border: Border(top: BorderSide(color: Colors.grey[300]!)), + ), + child: SafeArea( + child: Row( + children: [ + GestureDetector( + onTap: _handleAttachmentTap, + child: Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: Colors.grey[200], + borderRadius: BorderRadius.circular(20), + ), + child: const Icon( + Icons.attach_file, + color: Colors.black87, + size: 20, + ), + ), + ), + const SizedBox(width: 8), + Expanded( + child: Container( + decoration: BoxDecoration( + color: Colors.grey[100], + borderRadius: BorderRadius.circular(20), + ), + child: TextField( + controller: _messageController, + decoration: InputDecoration( + hintText: AppLocalizations.of(context).typeMessage, + contentPadding: EdgeInsets.symmetric( + horizontal: 16, + vertical: 8, + ), + border: InputBorder.none, + ), + maxLines: null, + keyboardType: TextInputType.multiline, + textInputAction: TextInputAction.send, + onSubmitted: (_) => _sendMessage(), + ), + ), + ), + const SizedBox(width: 8), + GestureDetector( + onTap: () { + _sendMessage(); + }, + child: Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: Colors.deepPurple, + borderRadius: BorderRadius.circular(20), + ), + child: const Icon(Icons.send, color: Colors.white, size: 20), + ), + ), + ], + ), + ), + ); + } + + Future _handleAttachmentTap() async { + if (!mounted) return; + final Uint8List? photoBytes = await showDialog( + context: context, + builder: (context) => const ChatPhotoDialog(), + ); + + if (photoBytes == null || photoBytes.isEmpty) { + return; + } + + await _sendImageMessage(photoBytes); + } + + Future _sendImageMessage(Uint8List imageBytes) async { + final sender = _currentUserId; + final receiver = _activeChat.receiver; + + if (sender == null || sender.isEmpty) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(AppLocalizations.of(context).noSenderMessage), + ), + ); + } + return; + } + + if (receiver == null || receiver.isEmpty) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(AppLocalizations.of(context).noRecipientMessage), + ), + ); + } + return; + } + + final prepared = await _prepareImagePayload(imageBytes); + if (prepared == null) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(AppLocalizations.of(context).photoProcessError), + ), + ); + } + return; + } + + final result = await _webSocketService.sendChatMessage( + sender: sender, + receiver: receiver, + content: prepared.base64DataUri, + contentType: ChatContentType.image, + jobId: _activeChat.jobId, + jobNumber: _activeChat.jobNumber, + ); + + if (result == null) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(AppLocalizations.of(context).imageSendError)), + ); + } + return; + } + + await _chatService.saveOutgoingMessage(result); + _syncActiveChatFromService(); + + if (prepared.bytes.isNotEmpty) { + _imageCache[result.id] = prepared.bytes; + } + } + + Future<_PreparedImage?> _prepareImagePayload(Uint8List originalBytes) async { + try { + final decoded = img.decodeImage(originalBytes); + if (decoded == null) { + return null; + } + + final baked = img.bakeOrientation(decoded); + const maxDimension = 1280; + img.Image processed = baked; + + if (baked.width > maxDimension || baked.height > maxDimension) { + final scale = + baked.width > baked.height + ? maxDimension / baked.width + : maxDimension / baked.height; + final targetWidth = (baked.width * scale).round(); + final targetHeight = (baked.height * scale).round(); + processed = img.copyResize( + baked, + width: targetWidth, + height: targetHeight, + interpolation: img.Interpolation.average, + ); + } + + final encodedBytes = Uint8List.fromList( + img.encodeJpg(processed, quality: 85), + ); + final base64Payload = base64Encode(encodedBytes); + final dataUri = 'data:image/jpeg;base64,$base64Payload'; + + return _PreparedImage(base64DataUri: dataUri, bytes: encodedBytes); + } catch (_) { + return null; + } + } + + String _formatMessageTime(DateTime dateTime) { + final now = DateTime.now(); + final today = DateTime(now.year, now.month, now.day); + final messageDate = DateTime(dateTime.year, dateTime.month, dateTime.day); + + if (messageDate == today) { + // Today - show only time + return '${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}'; + } else if (messageDate == today.subtract(const Duration(days: 1))) { + // Yesterday + return 'Gestern ${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}'; + } else { + // Older - show date and time + return '${dateTime.day.toString().padLeft(2, '0')}.${dateTime.month.toString().padLeft(2, '0')} ${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}'; + } + } + + void _showChatInfo() { + final isJobChat = _activeChat.type == ChatType.jobSpecific; + + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: Text(_activeChat.title), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('${AppLocalizations.of(context).status}: ${isJobChat ? AppLocalizations.of(context).chatTypeJob : AppLocalizations.of(context).chatTypeGeneral}'), + const SizedBox(height: 8), + if (isJobChat && _activeChat.jobNumber != null) ...[ + Text('${AppLocalizations.of(context).jobNumber}: ${_activeChat.jobNumber}'), + const SizedBox(height: 8), + ], + Text('${AppLocalizations.of(context).messages}: ${_messages.length}'), + const SizedBox(height: 8), + Text( + 'Erstellt: ${_formatMessageTime(_messages.isNotEmpty ? _messages.first.createdAt : DateTime.now())}', + ), + ], + ), + actions: [ + TextButton( + onPressed: () { + Navigator.of(context).pop(); + }, + child: Text(AppLocalizations.of(context).close), + ), + ], + ); + }, + ); + } +} diff --git a/app/lib/chats_view.dart b/app/lib/chats_view.dart new file mode 100644 index 0000000..f009002 --- /dev/null +++ b/app/lib/chats_view.dart @@ -0,0 +1,186 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'l10n/app_localizations.dart'; +import 'models/chat.dart'; +import 'services/chat_service.dart'; +import 'widgets/offline_banner.dart'; + +class ChatsView extends StatefulWidget { + const ChatsView({super.key}); + + @override + State createState() => _ChatsViewState(); +} + +class _ChatsViewState extends State { + final ChatService _chatService = ChatService(); + List _chats = const []; + StreamSubscription>? _chatSubscription; + bool _isInitializing = true; + + @override + void initState() { + super.initState(); + _initializeChats(); + } + + Future _initializeChats() async { + await _chatService.initialize(); + if (!mounted) return; + + setState(() { + _chats = _chatService.currentChats; + _isInitializing = false; + }); + + _chatSubscription = _chatService.chatsStream.listen((chats) { + if (!mounted) return; + setState(() { + _chats = chats; + }); + }); + } + + @override + void dispose() { + _chatSubscription?.cancel(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: Text(AppLocalizations.of(context).chats), + backgroundColor: Colors.deepPurple[100], + ), + body: Column( + children: [ + const OfflineBanner(), + Expanded(child: _buildBody()), + ], + ), + ); + } + + Widget _buildBody() { + if (_isInitializing) { + return const Center(child: CircularProgressIndicator()); + } + + if (_chats.isEmpty) { + return const Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.chat_outlined, size: 64, color: Colors.grey), + SizedBox(height: 16), + Text( + 'Keine Chats verfügbar', + style: TextStyle(fontSize: 16, color: Colors.grey), + ), + ], + ), + ); + } + + return ListView.builder( + itemCount: _chats.length, + itemBuilder: (context, index) { + final chat = _chats[index]; + return _buildChatTile(chat); + }, + ); + } + + Widget _buildChatTile(Chat chat) { + final isJobChat = chat.type == ChatType.jobSpecific; + final hasMessages = chat.messages.isNotEmpty; + final previewText = + hasMessages ? chat.lastMessagePreview : 'Noch keine Nachrichten'; + final timeLabel = hasMessages ? _formatTime(chat.lastMessageTime) : '--'; + final jobId = chat.jobId?.trim(); + final jobNumber = chat.jobNumber?.trim(); + final showJobId = isJobChat && jobId != null && jobId.isNotEmpty; + + return Card( + margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + child: ListTile( + leading: CircleAvatar( + backgroundColor: isJobChat ? Colors.blue[100] : Colors.green[100], + child: Icon( + isJobChat ? Icons.work : Icons.support_agent, + color: isJobChat ? Colors.blue[700] : Colors.green[700], + ), + ), + title: Text(() { + if (isJobChat) { + if (jobNumber != null && jobNumber.isNotEmpty) { + return 'Job $jobNumber'; + } + if (showJobId) { + return 'Job $jobId'; + } + } + return chat.type == ChatType.general + ? 'Allgemeine Nachrichten' + : chat.title; + }(), style: const TextStyle(fontWeight: FontWeight.w600, fontSize: 16)), + subtitle: Text( + previewText, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 14, color: Colors.grey[700]), + ), + trailing: Column( + crossAxisAlignment: CrossAxisAlignment.end, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text( + timeLabel, + style: TextStyle(fontSize: 12, color: Colors.grey[500]), + ), + const SizedBox(height: 4), + Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: isJobChat ? Colors.blue[50] : Colors.green[50], + borderRadius: BorderRadius.circular(10), + border: Border.all( + color: isJobChat ? Colors.blue[200]! : Colors.green[200]!, + ), + ), + child: Text( + isJobChat ? 'JOB' : 'ALLG', + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.w600, + color: isJobChat ? Colors.blue[700] : Colors.green[700], + ), + ), + ), + ], + ), + onTap: () { + Navigator.of(context).pushNamed('/chat_details', arguments: chat); + }, + ), + ); + } + + String _formatTime(DateTime dateTime) { + final now = DateTime.now(); + final difference = now.difference(dateTime); + + if (difference.inDays > 0) { + return '${difference.inDays}T'; + } else if (difference.inHours > 0) { + return '${difference.inHours}h'; + } else if (difference.inMinutes > 0) { + return '${difference.inMinutes}m'; + } else { + return 'jetzt'; + } + } +} diff --git a/app/lib/config/translation_config.dart b/app/lib/config/translation_config.dart new file mode 100644 index 0000000..7e6336e --- /dev/null +++ b/app/lib/config/translation_config.dart @@ -0,0 +1,32 @@ +enum TranslationBackend { lmStudio, moonshot } + +class TranslationConfig { + TranslationConfig._(); + + /// Das aktive Übersetzungs-Backend. + /// Hier umschalten zwischen LM Studio (lokal) und Moonshot AI (Cloud). + static const TranslationBackend activeBackend = TranslationBackend.moonshot; + + // --------------------------------------------------------------------------- + // LM Studio (lokales Modell) + // --------------------------------------------------------------------------- + + /// Basis-URL des LM Studio REST-Servers (lokales Netzwerk) + static const String lmStudioBaseUrl = 'http://lmstudio.appcreation.de'; + + /// Modellname – LM Studio ignoriert diesen Wert normalerweise + static const String lmStudioModel = 'local-model'; + + // --------------------------------------------------------------------------- + // Moonshot AI (Kimi Cloud API) + // --------------------------------------------------------------------------- + + /// Basis-URL der Moonshot AI API + static const String moonshotBaseUrl = 'https://api.moonshot.ai/v1'; + + /// API-Key für die Moonshot AI Authentifizierung + static const String moonshotApiKey = 'sk-EfHJfwCsxiZbOoBJ21OLWb9RUJQXSXAFIFGKnOedKke5JYZp'; + + /// Moonshot-Modell: moonshot-v1-8k (kurze Texte), moonshot-v1-32k, moonshot-v1-128k + static const String moonshotModel = 'moonshot-v1-8k'; +} diff --git a/app/lib/entities/chat_message_entity.dart b/app/lib/entities/chat_message_entity.dart new file mode 100644 index 0000000..e565a52 --- /dev/null +++ b/app/lib/entities/chat_message_entity.dart @@ -0,0 +1,48 @@ +import 'package:objectbox/objectbox.dart'; + +@Entity() +class ChatMessageEntity { + @Id() + int id = 0; + + @Unique() + String messageId; + + @Index() + String conversationKey; + + String content; + + String contentType; // 'TEXT' or 'IMAGE' + + @Property(type: PropertyType.date) + @Index() + DateTime createdAt; + + String origin; // 'INCOMING' or 'OUTGOING' + + String messageType; // 'NORMAL', 'JOB_ASSIGNMENT', etc. + + String? jobId; + + String? jobNumber; + + bool read; + + bool pendingSync; + + ChatMessageEntity({ + required this.messageId, + required this.conversationKey, + required this.content, + this.contentType = 'TEXT', + required this.createdAt, + required this.origin, + required this.messageType, + this.jobId, + this.jobNumber, + this.read = false, + this.pendingSync = false, + }); +} + diff --git a/app/lib/entities/job_entity.dart b/app/lib/entities/job_entity.dart new file mode 100644 index 0000000..dbc39b3 --- /dev/null +++ b/app/lib/entities/job_entity.dart @@ -0,0 +1,26 @@ +import 'package:objectbox/objectbox.dart'; + +@Entity() +class JobEntity { + @Id() + int id = 0; + + @Unique() + String jobId; // The original job ID from the Job model + + String jobData; // JSON-encoded job data + + @Property(type: PropertyType.date) + DateTime createdAt; + + @Property(type: PropertyType.date) + DateTime updatedAt; + + JobEntity({ + required this.jobId, + required this.jobData, + required this.createdAt, + required this.updatedAt, + }); +} + diff --git a/app/lib/entities/photo_entity.dart b/app/lib/entities/photo_entity.dart new file mode 100644 index 0000000..44c12e1 --- /dev/null +++ b/app/lib/entities/photo_entity.dart @@ -0,0 +1,23 @@ +import 'package:objectbox/objectbox.dart'; + +@Entity() +class PhotoEntity { + @Id() + int id = 0; + + String taskId; + + int photoIndex; + + String data; // Base64-encoded photo data + + @Property(type: PropertyType.date) + DateTime createdAt; + + PhotoEntity({ + required this.taskId, + required this.photoIndex, + required this.data, + required this.createdAt, + }); +} diff --git a/app/lib/entities/queued_message_entity.dart b/app/lib/entities/queued_message_entity.dart new file mode 100644 index 0000000..729073d --- /dev/null +++ b/app/lib/entities/queued_message_entity.dart @@ -0,0 +1,27 @@ +import 'package:objectbox/objectbox.dart'; + +@Entity() +class QueuedMessageEntity { + @Id() + int id = 0; + + @Unique() + String messageId; + + String topic; + + String payload; // JSON-encoded payload + + @Property(type: PropertyType.date) + DateTime createdAt; + + int retryCount; + + QueuedMessageEntity({ + required this.messageId, + required this.topic, + required this.payload, + required this.createdAt, + this.retryCount = 0, + }); +} diff --git a/app/lib/entities/task_status_entity.dart b/app/lib/entities/task_status_entity.dart new file mode 100644 index 0000000..e8bca13 --- /dev/null +++ b/app/lib/entities/task_status_entity.dart @@ -0,0 +1,30 @@ +import 'package:objectbox/objectbox.dart'; + +@Entity() +class TaskStatusEntity { + @Id() + int id = 0; + + @Unique() + String taskId; + + bool completed; + + @Property(type: PropertyType.date) + DateTime? completedAt; + + @Property(type: PropertyType.date) + DateTime createdAt; + + @Property(type: PropertyType.date) + DateTime updatedAt; + + TaskStatusEntity({ + required this.taskId, + required this.completed, + this.completedAt, + required this.createdAt, + required this.updatedAt, + }); +} + diff --git a/app/lib/entities/user_data_entity.dart b/app/lib/entities/user_data_entity.dart new file mode 100644 index 0000000..53af3c5 --- /dev/null +++ b/app/lib/entities/user_data_entity.dart @@ -0,0 +1,26 @@ +import 'package:objectbox/objectbox.dart'; + +@Entity() +class UserDataEntity { + @Id() + int id = 0; + + @Unique() + String key; + + String value; + + @Property(type: PropertyType.date) + DateTime createdAt; + + @Property(type: PropertyType.date) + DateTime updatedAt; + + UserDataEntity({ + required this.key, + required this.value, + required this.createdAt, + required this.updatedAt, + }); +} + diff --git a/app/lib/jobs_route_mixin.dart b/app/lib/jobs_route_mixin.dart new file mode 100644 index 0000000..07fd39f --- /dev/null +++ b/app/lib/jobs_route_mixin.dart @@ -0,0 +1,23 @@ +import 'package:flutter/material.dart'; +import 'navigation_observer.dart'; + +mixin RouteAwareState on State implements RouteAware { + @override + void didPopNext() { + // When returning to this route, subclasses can override to refresh state. + } + + void subscribeRouteAware() { + WidgetsBinding.instance.addPostFrameCallback((_) { + final route = ModalRoute.of(context); + if (route != null) { + routeObserver.subscribe(this, route); + } + }); + } + + void unsubscribeRouteAware() { + routeObserver.unsubscribe(this); + } +} + diff --git a/app/lib/jobs_view.dart b/app/lib/jobs_view.dart new file mode 100644 index 0000000..86c1810 --- /dev/null +++ b/app/lib/jobs_view.dart @@ -0,0 +1,1866 @@ +import 'package:flutter/material.dart'; +import 'app_state.dart'; +import 'l10n/app_localizations.dart'; +import 'services/websocket_service.dart'; +import 'services/dart_mq.dart'; +import 'services/chat_service.dart'; +import 'models/delivery_station.dart'; +import 'models/job.dart'; +import 'models/task.dart'; +import 'models/tasks/confirmation_task.dart'; +import 'models/tasks/photo_task.dart'; +import 'models/tasks/todolist_task.dart'; +import 'models/tasks/signature_task.dart'; +import 'models/tasks/barcode_task.dart'; +import 'models/tasks/comment_task.dart'; +import 'widgets/offline_banner.dart'; +import 'package:votianlt_app/services/developer.dart' as developer; +import 'dart:async'; +import 'services/database_service.dart'; + +import 'navigation_observer.dart'; +import 'routing_view.dart'; + +class JobsView extends StatefulWidget { + const JobsView({super.key}); + + @override + State createState() => _JobsViewState(); +} + +class _JobsViewState extends State with RouteAware { + bool _routeActionInProgress = false; + void _openRoutingView({ + required String address, + required bool isDelivery, + String? title, + }) { + Navigator.of(context).push( + MaterialPageRoute( + builder: + (_) => RoutingView( + address: address, + isDelivery: isDelivery, + title: title, + ), + ), + ); + } + + final AppState _appState = AppState(); + final StompService _stompService = StompService(); + final ChatService _chatService = ChatService(); + + bool _isLoadingDialogShowing = false; + bool _isLoadingJobs = false; + DartMQSubscription? _jobsSub; + DartMQSubscription? _connectionSub; + DartMQSubscription? _jobDeletedSub; + DartMQSubscription? _jobCreatedSub; + bool _wasConnected = false; + bool _isLoggingOut = false; + final DatabaseService _databaseService = DatabaseService(); + Map _taskStatuses = const {}; + Map _jobSeen = const {}; + Map _jobSwipeOffsets = const {}; + String? _openJobId; + static const double _jobSwipeRevealOffset = 50.0; + final Set _jobsBeingDeleted = {}; + // Listen to AppState jobsUpdated to apply UI refresh exactly once + StreamSubscription? _jobsUpdatedSub; + bool _isApplyingJobs = false; + StreamSubscription? _unreadCountSub; + int _unreadMessageCount = 0; + + @override + void initState() { + super.initState(); + + // Always load local task completion statuses to compute progress/card colors + _loadLocalTaskStatuses(); + + // Remember initial connection state + _wasConnected = _stompService.isConnected; + // Subscribe to route changes + WidgetsBinding.instance.addPostFrameCallback((_) { + final route = ModalRoute.of(context); + if (route != null) { + routeObserver.subscribe(this, route); + } + }); + + // Listen to connection changes to show banner (handled by widget) and trigger reloads + _connectionSub = DartMQ().subscribe(MQTopics.connectionStatus, ( + isConnected, + ) { + // Went online + if (isConnected && !_wasConnected) { + _showSnack( + AppLocalizations.of(context).connectionRestored, + backgroundColor: Colors.green, + ); + if (_appState.isLoggedIn) { + _loadJobs(); + } + } + + // Went offline + if (!isConnected && _wasConnected) { + if (mounted && _isLoadingDialogShowing) { + _isLoadingDialogShowing = false; + Navigator.of(context, rootNavigator: true).pop(); + } + // Only show offline message when user is logged in and not in logout flow + if (_appState.isLoggedIn && !_isLoggingOut) { + _showSnack( + AppLocalizations.of(context).connectionLost, + backgroundColor: Colors.red, + ); + } + } + + _wasConnected = isConnected; + }); + + // Listen to job deletion events from server + _jobDeletedSub = DartMQ().subscribe< + Map + >(MQTopics.jobDeleted, (data) async { + final jobId = data['jobId']?.toString(); + final jobNumber = data['jobNumber']?.toString(); + + if (jobId == null) return; + + developer.log( + 'Job deleted event received: $jobId ($jobNumber)', + name: 'JobsView', + ); + + // Delete job from AppState (which also updates DB and notifies listeners) + await _appState.deleteJob(jobId); + + // Show notification to user + if (mounted) { + final message = + jobNumber != null + ? 'Job $jobNumber ${AppLocalizations.of(context).jobRemoved}' + : AppLocalizations.of(context).jobRemoved; + _showSnack(message, backgroundColor: Colors.orange); + } + }); + + // Listen to job creation events from server + _jobCreatedSub = DartMQ().subscribe< + Map + >(MQTopics.jobCreated, (data) async { + developer.log('Job created event received', name: 'JobsView'); + + try { + // WICHTIG: Der Job wurde bereits vom WebSocketService übersetzt und in die DB gespeichert. + // Wir laden die Jobs aus der Datenbank neu, um die übersetzte Version anzuzeigen. + developer.log( + 'Reloading jobs from database to get translated version...', + name: 'JobsView', + ); + await _loadJobsFromDatabase(); + + // Extract job number for notification + final jobNumber = + data['job']?['jobNumber']?.toString() ?? + data['jobNumber']?.toString() ?? + ''; + + // Show notification to user + if (mounted) { + final message = + jobNumber.isNotEmpty + ? '${AppLocalizations.of(context).newJobReceived}: $jobNumber' + : AppLocalizations.of(context).newJobReceived; + _showSnack(message, backgroundColor: Colors.green); + } + } catch (e) { + developer.log('Error handling job_created event: $e', name: 'JobsView'); + } + }); + + // Listen once-per-cycle for jobs updates from AppState + _jobsUpdatedSub = _appState.jobsUpdated.listen((_) async { + if (_isApplyingJobs) { + return; + } + _isApplyingJobs = true; + try { + await _appState.refreshJobsFromDatabase(); + await _loadLocalTaskStatuses(); + await _loadSeenFlagsForCurrentJobs(); + if (mounted && _isLoadingDialogShowing) { + _isLoadingDialogShowing = false; + Navigator.of(context, rootNavigator: true).pop(); + } + if (mounted) { + setState(() { + _syncSwipeStateWithJobs(); + }); + _showSnack( + AppLocalizations.of(context).jobsUpdated, + backgroundColor: Colors.green, + ); + } + } finally { + _isApplyingJobs = false; + } + }); + + // Listen to unread message count changes + _unreadCountSub = _chatService.unreadCountStream.listen((count) { + developer.log( + '[DEBUG_LOG] JobsView received unread count from stream: $count', + name: 'JobsView', + ); + if (mounted) { + setState(() { + _unreadMessageCount = count; + }); + developer.log( + '[DEBUG_LOG] JobsView updated badge with count: $_unreadMessageCount', + name: 'JobsView', + ); + } + }); + + // Initialize chat service and get initial unread count + _chatService.initialize().then((_) { + developer.log( + '[DEBUG_LOG] ChatService initialized, initial unread count: ${_chatService.unreadCount}', + name: 'JobsView', + ); + if (mounted) { + setState(() { + _unreadMessageCount = _chatService.unreadCount; + }); + developer.log( + '[DEBUG_LOG] JobsView set initial badge count to: $_unreadMessageCount', + name: 'JobsView', + ); + } + }); + + // Load jobs from database first (for offline/cached jobs) + _loadJobsFromDatabase(); + + _initializeAndLoadJobs(); + // Also load seen flags for any jobs already in memory (e.g., from DB) + _loadSeenFlagsForCurrentJobs(); + } + + /// Load jobs from database on startup + Future _loadJobsFromDatabase() async { + try { + developer.log( + 'Loading jobs from database on startup...', + name: 'JobsView', + ); + await _appState.refreshJobsFromDatabase(); + await _loadLocalTaskStatuses(); + await _loadSeenFlagsForCurrentJobs(); + if (mounted) { + setState(() { + _syncSwipeStateWithJobs(); + }); + developer.log( + 'Jobs loaded from database: ${_appState.assignedJobs.length}', + name: 'JobsView', + ); + + // Debug: Log each job loaded from database + for (int i = 0; i < _appState.assignedJobs.length; i++) { + final job = _appState.assignedJobs[i]; + developer.log( + 'DB Job $i: ${job.jobNumber} (${job.id}) - Tasks: ${job.tasks.length}, CargoItems: ${job.cargoItems.length}', + name: 'JobsView', + ); + } + } + } catch (e, stackTrace) { + developer.log('Error loading jobs from database: $e', name: 'JobsView'); + developer.log('Stack trace: $stackTrace', name: 'JobsView'); + } + } + + /// Initialize connection and load jobs + Future _initializeAndLoadJobs() async { + // Only proceed if user is logged in + if (!_appState.isLoggedIn) { + developer.log( + 'Skip jobs initialization: user not logged in', + name: 'JobsView', + ); + return; + } + + try { + // If not connected and authenticated, initiate connection and wait + final isFullyConnected = + _stompService.isConnected && _stompService.isAuthenticated; + if (!isFullyConnected) { + developer.log( + 'No authenticated connection at jobs load time - initiating connection', + name: 'JobsView', + ); + + // Show loading dialog while waiting for connection + if (mounted && !_isLoadingDialogShowing) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted && !_isLoadingDialogShowing) { + _showLoadingDialog(); + } + }); + } + + // Initiate WebSocket connection (will auto-login with saved credentials) + // connect() is safe to call multiple times - it prevents overlapping attempts + _stompService.connect(); + + // Wait for connection and authentication with timeout + await _waitForConnection(); + } + + // Show loading dialog if not already shown and we're fully connected + final isNowFullyConnected = + _stompService.isConnected && _stompService.isAuthenticated; + if (mounted && !_isLoadingDialogShowing && isNowFullyConnected) { + WidgetsBinding.instance.addPostFrameCallback((_) { + final stillFullyConnected = + _stompService.isConnected && _stompService.isAuthenticated; + if (mounted && !_isLoadingDialogShowing && stillFullyConnected) { + _showLoadingDialog(); + } + }); + } + + // Load jobs only if connected AND authenticated + if (_stompService.isConnected && _stompService.isAuthenticated) { + await _loadJobs(); + } else { + _showSnack( + 'Verbindung zum Server konnte nicht hergestellt werden.', + backgroundColor: Colors.red, + ); + } + } catch (e) { + developer.log('Error during initialization: $e', name: 'JobsView'); + } + + // Reset loading flag after attempt (no dialog to close) + if (mounted && _isLoadingDialogShowing) { + _isLoadingDialogShowing = false; + } + } + + /// Wait for WebSocket connection and authentication to be established + Future _waitForConnection() async { + // If already connected and authenticated, return immediately + if (_stompService.isConnected && _stompService.isAuthenticated) { + return; + } + + final completer = Completer(); + + // Listen for connection status changes + final connectionSub = DartMQ().subscribe(MQTopics.connectionStatus, ( + isConnected, + ) { + if (isConnected && !completer.isCompleted) { + completer.complete(); + } + }); + + try { + // Wait with timeout (30 seconds) + await completer.future.timeout(const Duration(seconds: 30)); + } catch (e) { + developer.log('Connection wait timeout or error: $e', name: 'JobsView'); + } finally { + // Cancel subscription after completer resolves or times out + connectionSub.cancel(); + } + } + + /// Preload task statuses (no dialog shown) + void _showLoadingDialog() { + _isLoadingDialogShowing = true; + // Preload task statuses to compute card colors + _databaseService.loadAllTaskStatuses().then((map) { + if (!mounted) return; + setState(() { + _taskStatuses = map; + }); + }); + // Dialog removed - loading happens silently in background + } + + /// Load jobs from server + Future _loadJobs() async { + if (!_appState.isLoggedIn) { + developer.log('Not logged in - cannot load jobs', name: 'JobsView'); + return; + } + + if (_isLoadingJobs) { + developer.log( + 'Load jobs already in progress - skipping', + name: 'JobsView', + ); + return; + } + + _isLoadingJobs = true; + + final completer = Completer(); + + try { + developer.log('Loading jobs...', name: 'JobsView'); + + // Listen for first jobs response only + _jobsSub?.cancel(); + _jobsSub = DartMQ().subscribe>(MQTopics.jobsResponse, ( + jobsData, + ) async { + if (!mounted) return; + + final List list = jobsData; + developer.log( + 'Jobs response received: ${list.length} jobs', + name: 'JobsView', + ); + + // WICHTIG: Die Jobs wurden bereits vom WebSocketService übersetzt und in die DB gespeichert. + // Wir laden die Jobs aus der Datenbank, um die übersetzten Versionen zu erhalten. + developer.log( + 'Loading translated jobs from database...', + name: 'JobsView', + ); + await _loadJobsFromDatabase(); + + // Complete and cancel subscription + if (!completer.isCompleted) { + completer.complete(); + } + _jobsSub?.cancel(); + _jobsSub = null; + _isLoadingJobs = false; + }); + } catch (e) { + developer.log('Error loading jobs: $e', name: 'JobsView'); + if (mounted && _isLoadingDialogShowing) { + _isLoadingDialogShowing = false; + } + _isLoadingJobs = false; + } + } + + // Helper to show SnackBars safely (not during initState) + void _showSnack(String message, {Color? backgroundColor}) { + if (!mounted) return; + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + final messenger = ScaffoldMessenger.maybeOf(context); + messenger?.showSnackBar( + SnackBar( + content: Text(message), + backgroundColor: backgroundColor, + duration: const Duration(seconds: 1), + ), + ); + }); + } + + Future _loadLocalTaskStatuses() async { + final map = await _databaseService.loadAllTaskStatuses(); + if (!mounted) return; + setState(() { + _taskStatuses = map; + }); + } + + Future _loadSeenFlagsForCurrentJobs() async { + final jobs = _appState.assignedJobs; + if (jobs.isEmpty) return; + final ids = jobs.map((j) => j.id).toSet(); + final seenMap = await _databaseService.loadSeenJobsForIds(ids); + if (!mounted) return; + setState(() { + _jobSeen = seenMap; + }); + } + + String _two(int n) => n.toString().padLeft(2, '0'); + + String _formatDateString(String dateStr) { + // Convert "YYYY-MM-DD" to "DD.MM.YYYY" + if (dateStr.isEmpty) return ''; + final parts = dateStr.split('-'); + if (parts.length == 3) { + return '${parts[2]}.${parts[1]}.${parts[0]}'; + } + return dateStr; + } + + String _formatTimeString(String timeStr) { + // Convert "HH:MM:SS" to "HH:MM" + if (timeStr.isEmpty) return ''; + final parts = timeStr.split(':'); + if (parts.length >= 2) { + return '${parts[0]}:${parts[1]}'; + } + return timeStr; + } + + String _formatDate(DateTime dt) { + // Format: dd.MM.yyyy HH:mm + return '${_two(dt.day)}.${_two(dt.month)}.${dt.year} ${_two(dt.hour)}:${_two(dt.minute)}'; + } + + String _joinNonEmpty(List parts, {String sep = ' '}) => + parts.where((p) => p.trim().isNotEmpty).join(sep); + + @override + void didPopNext() { + // Called when returning to this route from another route (e.g., TaskView) + // Reload local task statuses so progress and card colors reflect changes + _loadLocalTaskStatuses(); + } + + @override + void dispose() { + routeObserver.unsubscribe(this); + _jobsSub?.cancel(); + _jobsSub = null; + _jobsUpdatedSub?.cancel(); + _jobsUpdatedSub = null; + _unreadCountSub?.cancel(); + _unreadCountSub = null; + _connectionSub?.cancel(); + _connectionSub = null; + _jobDeletedSub?.cancel(); + _jobDeletedSub = null; + _jobCreatedSub?.cancel(); + _jobCreatedSub = null; + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Stack( + children: [ + PopScope( + canPop: false, + child: Scaffold( + appBar: AppBar( + automaticallyImplyLeading: false, + title: Text(AppLocalizations.of(context).availableJobs), + backgroundColor: Colors.deepPurple[100], + leading: IconButton( + icon: const Icon(Icons.logout), + onPressed: () { + _handleLogout(); + }, + tooltip: AppLocalizations.of(context).logout, + ), + actions: [ + // Chat Icon with Badge + Padding( + padding: const EdgeInsets.only(right: 4.0), + child: Badge( + label: Text('$_unreadMessageCount'), + isLabelVisible: _unreadMessageCount > 0, + child: IconButton( + icon: const Icon(Icons.chat), + onPressed: () { + Navigator.of(context).pushNamed('/chats'); + }, + tooltip: AppLocalizations.of(context).openChat, + ), + ), + ), + // Settings Icon + Padding( + padding: const EdgeInsets.only(right: 10.0), + child: IconButton( + icon: const Icon(Icons.settings), + onPressed: () { + Navigator.of(context).pushNamed('/settings'); + }, + tooltip: AppLocalizations.of(context).settings, + ), + ), + ], + ), + body: Column( + children: [ + // Offline banner under header + OfflineBanner(), + + Expanded( + child: Padding( + padding: const EdgeInsets.all(16.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [Expanded(child: _buildJobsList())], + ), + ), + ), + ], + ), + ), + ), + ], + ); + } + + void _handleLogout() { + // Capture a parent context before opening the dialog to ensure we can always navigate on root + final parentContext = context; + showDialog( + context: parentContext, + builder: (BuildContext dialogContext) { + return AlertDialog( + title: Text(AppLocalizations.of(context).logoutConfirm), + content: Text(AppLocalizations.of(context).logoutConfirmMessage), + actions: [ + TextButton( + onPressed: () { + Navigator.of(dialogContext).pop(); + }, + child: Text(AppLocalizations.of(context).cancel), + ), + ElevatedButton( + onPressed: () async { + _isLoggingOut = true; // suppress connection snackbars + + // We'll ensure navigation to login in a finally block + try { + await _appState.clearLogin(); // clear login + DB + await _stompService + .logout(); // only clear auth state, keep WebSocket connected + + // Cleanup + _jobsSub?.cancel(); + _jobsSub = null; + + // Prevent further job loads until next login + _wasConnected = false; + } catch (e, stackTrace) { + developer.log( + 'Error during logout flow: $e', + name: 'JobsView', + ); + developer.log('Stack trace: $stackTrace', name: 'JobsView'); + } finally { + if (!mounted) { + // If the widget is already unmounted, we cannot navigate here safely. + // Navigation to login will be handled by higher-level route guards on next build. + } else { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) { + return; + } + + // Use the parentContext to get the root navigator (avoid dialog context pitfalls) + final rootNav = Navigator.of( + parentContext, + rootNavigator: true, + ); + + // Clear any visible SnackBars before navigation + ScaffoldMessenger.maybeOf( + parentContext, + )?.clearSnackBars(); + + // Close any remaining routes above root (e.g., dialogs) + while (rootNav.canPop()) { + rootNav.pop(); + } + + // Navigate to login, clearing stack and suppressing connection snack + rootNav.pushNamedAndRemoveUntil( + '/login', + (route) => false, + arguments: true, // suppressConnectionSnack + ); + }); + } + } + }, + style: ElevatedButton.styleFrom( + backgroundColor: Colors.red, + foregroundColor: Colors.white, + ), + child: Text(AppLocalizations.of(context).logout), + ), + ], + ); + }, + ); + } + + Widget _buildJobsList() { + final jobs = List.from(_appState.assignedJobs)..sort((a, b) { + final aSeen = _jobSeen[a.id] ?? false; + final bSeen = _jobSeen[b.id] ?? false; + if (aSeen != bSeen) { + // Unseen first + return aSeen ? 1 : -1; + } + // Then by time (oldest first within each group) + return a.createdAt.compareTo(b.createdAt); + }); + + return RefreshIndicator( + onRefresh: _refreshJobs, + child: + jobs.isEmpty + ? ListView( + children: [ + SizedBox( + height: MediaQuery.of(context).size.height * 0.6, + child: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon( + Icons.work_outline, + size: 64, + color: Colors.grey[400], + ), + const SizedBox(height: 16), + Text( + AppLocalizations.of(context).noJobsAssigned, + style: TextStyle( + fontSize: 16, + color: Colors.grey[600], + ), + ), + const SizedBox(height: 8), + Text( + AppLocalizations.of(context).noJobsMessage, + style: TextStyle( + fontSize: 14, + color: Colors.grey[500], + ), + textAlign: TextAlign.center, + ), + const SizedBox(height: 8), + Text( + AppLocalizations.of(context).pullToRefresh, + style: TextStyle( + fontSize: 12, + color: Colors.grey[400], + ), + textAlign: TextAlign.center, + ), + const SizedBox(height: 16), + ElevatedButton.icon( + onPressed: _refreshJobs, + icon: const Icon(Icons.refresh), + label: Text(AppLocalizations.of(context).refresh), + style: ElevatedButton.styleFrom( + backgroundColor: Colors.deepPurple[100], + foregroundColor: Colors.deepPurple[700], + ), + ), + ], + ), + ), + ), + ], + ) + : ListView.builder( + itemCount: jobs.length, + itemBuilder: (context, index) { + final job = jobs[index]; + return _buildJobCard(job); + }, + ), + ); + } + + Future _refreshJobs() async { + if (_stompService.isConnected && _stompService.isAuthenticated) { + await _loadJobs(); + } else { + _showSnack( + AppLocalizations.of(context).offline, + backgroundColor: Colors.red, + ); + } + } + + void _syncSwipeStateWithJobs() { + final jobIds = _appState.assignedJobs.map((job) => job.id).toSet(); + final updatedOffsets = {}; + _jobSwipeOffsets.forEach((jobId, offset) { + if (jobIds.contains(jobId) && offset != 0) { + updatedOffsets[jobId] = offset; + } + }); + _jobSwipeOffsets = updatedOffsets; + if (_openJobId != null && !jobIds.contains(_openJobId)) { + _openJobId = null; + } + } + + void _handleJobDragUpdate(Job job, DragUpdateDetails details) { + final current = _jobSwipeOffsets[job.id] ?? 0.0; + var next = current + details.delta.dx; + if (next < -_jobSwipeRevealOffset) { + next = -_jobSwipeRevealOffset; + } + if (next > 0) { + next = 0; + } + if ((next - current).abs() < 0.5) { + return; + } + setState(() { + final updated = Map.from(_jobSwipeOffsets); + if (next == 0) { + updated.remove(job.id); + } else { + updated[job.id] = next; + } + _jobSwipeOffsets = updated; + }); + } + + void _handleJobDragEnd(Job job, DragEndDetails details) { + final current = _jobSwipeOffsets[job.id] ?? 0.0; + final velocity = details.primaryVelocity ?? 0.0; + final shouldOpen = + current <= -(_jobSwipeRevealOffset / 2) || velocity < -300; + setState(() { + final updated = Map.from(_jobSwipeOffsets); + if (shouldOpen) { + updated + ..clear() + ..[job.id] = -_jobSwipeRevealOffset; + _jobSwipeOffsets = updated; + _openJobId = job.id; + } else { + updated.remove(job.id); + _jobSwipeOffsets = updated; + if (_openJobId == job.id) { + _openJobId = null; + } + } + }); + } + + void _closeSwipe(String jobId) { + final current = _jobSwipeOffsets[jobId] ?? 0.0; + if (current == 0 && _openJobId != jobId) { + return; + } + setState(() { + final updated = Map.from(_jobSwipeOffsets)..remove(jobId); + _jobSwipeOffsets = updated; + if (_openJobId == jobId) { + _openJobId = null; + } + }); + } + + Future _deleteJob(Job job) async { + final jobId = job.id; + if (_jobsBeingDeleted.contains(jobId)) { + return; + } + + setState(() { + _jobsBeingDeleted.add(jobId); + }); + + _closeSwipe(jobId); + + try { + await _databaseService.deleteJobAndRelatedData(job); + _appState.removeJob(jobId); + + final updatedStatuses = Map.from( + _taskStatuses, + )..removeWhere((taskId, _) => job.tasks.any((task) => task.id == taskId)); + final updatedSeen = Map.from(_jobSeen)..remove(jobId); + + if (mounted) { + setState(() { + _taskStatuses = updatedStatuses; + _jobSeen = updatedSeen; + _syncSwipeStateWithJobs(); + }); + } + + await _chatService.deleteJobChats( + jobId, + jobNumber: job.jobNumber.trim().isEmpty ? null : job.jobNumber, + ); + + if (mounted) { + _showSnack( + AppLocalizations.of(context).jobDeleted, + backgroundColor: Colors.red, + ); + } + } catch (e, st) { + developer.log('Error deleting job $jobId: $e', name: 'JobsView'); + developer.log('Stack trace: $st', name: 'JobsView'); + if (mounted) { + _showSnack( + AppLocalizations.of(context).jobDeleteError, + backgroundColor: Colors.red, + ); + } + } finally { + if (mounted) { + setState(() { + _jobsBeingDeleted.remove(jobId); + }); + } else { + _jobsBeingDeleted.remove(jobId); + } + } + } + + Widget _buildJobCard(Job job) { + Color statusColor; + switch (job.statusColor) { + case 'green': + statusColor = Colors.green; + break; + case 'blue': + statusColor = Colors.blue; + break; + case 'orange': + statusColor = Colors.orange; + break; + case 'red': + statusColor = Colors.red; + break; + default: + statusColor = Colors.grey; + } + + // Determine card background color based on task completion + final totalTasks = job.tasks.length; + int completedTasks = 0; + for (final t in job.tasks) { + final isCompleted = _taskStatuses[t.id] ?? t.completed; + if (isCompleted) completedTasks++; + } + + // Check if all tasks are completed (job is done) + final bool isJobCompleted = totalTasks > 0 && completedTasks == totalTasks; + + Color? cardBg; + if (totalTasks == 0 || completedTasks == 0) { + cardBg = null; // unchanged (default) + } else if (completedTasks > 0 && completedTasks < totalTasks) { + cardBg = Colors.yellow[50]; + } else if (completedTasks == totalTasks) { + cardBg = Colors.green[50]; + } + // Build robust display strings with fallbacks + final pickupName = _joinNonEmpty([job.pickupFirstName, job.pickupLastName]); + final pickupDisplayName = + pickupName.isNotEmpty ? pickupName : job.pickupCompany; + final pickupAddress = _joinNonEmpty([ + _joinNonEmpty([job.pickupStreet, job.pickupHouseNumber]), + _joinNonEmpty([job.pickupZip, job.pickupCity]), + ], sep: ', '); + + final deliveryName = _joinNonEmpty([ + job.deliveryFirstName, + job.deliveryLastName, + ]); + final firstDeliveryStation = + job.deliveryStations.isNotEmpty ? job.deliveryStations.first : null; + final hasMultipleDeliveryStations = job.deliveryStations.length > 1; + final deliveryDisplayName = + hasMultipleDeliveryStations + ? (job.deliveryCitiesDisplay.isNotEmpty + ? job.deliveryCitiesDisplay + : job.deliveryCompany) + : (deliveryName.isNotEmpty + ? deliveryName + : (firstDeliveryStation?.displayName.isNotEmpty == true + ? firstDeliveryStation!.displayName + : job.deliveryCompany)); + final deliveryAddress = + hasMultipleDeliveryStations + ? '${job.deliveryStations.length} Stationen' + : (firstDeliveryStation?.formattedAddress.isNotEmpty == true + ? firstDeliveryStation!.formattedAddress + : _joinNonEmpty([ + _joinNonEmpty([job.deliveryStreet, job.deliveryHouseNumber]), + _joinNonEmpty([job.deliveryZip, job.deliveryCity]), + ], sep: ', ')); + final deliveryRouteAddress = + firstDeliveryStation?.formattedAddress.isNotEmpty == true + ? firstDeliveryStation!.formattedAddress + : deliveryAddress; + + final swipeOffset = _jobSwipeOffsets[job.id] ?? 0.0; + final isDeleting = _jobsBeingDeleted.contains(job.id); + + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + child: Stack( + children: [ + Positioned.fill( + child: Align( + alignment: Alignment.centerRight, + child: IgnorePointer( + ignoring: swipeOffset == 0, + child: AnimatedOpacity( + opacity: (swipeOffset.abs() / _jobSwipeRevealOffset).clamp( + 0, + 1, + ), + duration: const Duration(milliseconds: 150), + child: IconButton( + iconSize: 28, + padding: const EdgeInsets.all(10), + splashRadius: 24, + icon: const Icon(Icons.delete, color: Colors.red), + tooltip: AppLocalizations.of(context).deleteJob, + onPressed: () { + if (isDeleting) { + return; + } + _deleteJob(job); + }, + ), + ), + ), + ), + ), + GestureDetector( + // Only enable swipe gestures for completed jobs + onHorizontalDragStart: + isJobCompleted + ? (_) { + final openId = _openJobId; + if (openId != null && openId != job.id) { + _closeSwipe(openId); + } + } + : null, + onHorizontalDragUpdate: + isJobCompleted + ? (details) { + if (_jobsBeingDeleted.contains(job.id)) { + return; + } + _handleJobDragUpdate(job, details); + } + : null, + onHorizontalDragEnd: + isJobCompleted + ? (details) { + if (_jobsBeingDeleted.contains(job.id)) { + return; + } + _handleJobDragEnd(job, details); + } + : null, + onHorizontalDragCancel: + isJobCompleted ? () => _closeSwipe(job.id) : null, + child: TweenAnimationBuilder( + tween: Tween(begin: 0, end: swipeOffset), + duration: const Duration(milliseconds: 150), + curve: Curves.easeOut, + builder: (context, value, child) { + return Transform.translate( + offset: Offset(value, 0), + child: child, + ); + }, + child: Card( + margin: EdgeInsets.zero, + elevation: 2, + color: cardBg, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(8), + ), + clipBehavior: Clip.antiAlias, + child: InkWell( + onTap: () { + final isOpen = (_jobSwipeOffsets[job.id] ?? 0) != 0; + if (isOpen) { + _closeSwipe(job.id); + return; + } + _showJobDetails(job); + }, + borderRadius: BorderRadius.circular(8), + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + job.jobNumber.isNotEmpty + ? job.jobNumber + : job.title, + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.bold, + ), + ), + if (job.customerSelection.isNotEmpty) ...[ + const SizedBox(height: 2), + Text( + job.customerSelection, + style: TextStyle( + fontSize: 14, + color: Colors.grey[700], + fontWeight: FontWeight.w500, + ), + ), + ], + if (job.customerSelection.isEmpty && + (job.pickupCity.isNotEmpty || + job.deliveryCity.isNotEmpty)) ...[ + const SizedBox(height: 2), + Text( + '${AppLocalizations.of(context).from} ${job.pickupCity.isNotEmpty ? job.pickupCity : '?'} ${AppLocalizations.of(context).to} ${job.deliveryCity.isNotEmpty ? job.deliveryCity : '?'}', + style: TextStyle( + fontSize: 13, + color: Colors.grey[700], + ), + ), + ], + if (job.customerSelection.isEmpty && + job.pickupCity.isEmpty && + job.deliveryCity.isEmpty && + job.description.isNotEmpty) ...[ + const SizedBox(height: 2), + Text( + job.description, + style: TextStyle( + fontSize: 13, + color: Colors.grey[700], + ), + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + ], + ], + ), + ), + Builder( + builder: (_) { + final seen = _jobSeen[job.id] ?? false; + if (!seen) { + // Fire and forget DB write; do not block build + _databaseService.setJobSeen(job.id).then(( + _, + ) async { + if (mounted) { + setState(() { + _jobSeen = Map.from( + _jobSeen, + )..[job.id] = true; + }); + } + }); + } + if (seen) { + return const SizedBox.shrink(); + } + return Container( + padding: const EdgeInsets.symmetric( + horizontal: 8, + vertical: 4, + ), + decoration: BoxDecoration( + color: statusColor.withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(12), + border: Border.all( + color: statusColor.withValues(alpha: 0.3), + ), + ), + child: Text( + AppLocalizations.of(context).newLabel, + style: TextStyle( + fontSize: 12, + color: statusColor.withValues(alpha: 0.8), + fontWeight: FontWeight.w500, + ), + ), + ); + }, + ), + ], + ), + // Progress bar for tasks + if (totalTasks > 0) ...[ + const SizedBox(height: 8), + Text( + AppLocalizations.of(context).tasksToComplete, + style: TextStyle( + fontSize: 12, + color: Colors.grey[500], + ), + ), + const SizedBox(height: 4), + Row( + children: [ + Expanded( + child: ClipRRect( + borderRadius: BorderRadius.circular(6), + child: LinearProgressIndicator( + value: + totalTasks == 0 + ? 0 + : completedTasks / totalTasks, + minHeight: 8, + backgroundColor: Colors.grey[200], + valueColor: AlwaysStoppedAnimation( + completedTasks >= totalTasks + ? Colors.green + : (completedTasks > 0 + ? Colors.amber + : Colors.deepPurpleAccent), + ), + ), + ), + ), + const SizedBox(width: 8), + Text( + '$completedTasks/$totalTasks', + style: TextStyle( + fontSize: 12, + color: Colors.grey[700], + ), + ), + ], + ), + ], + const SizedBox(height: 12), + // Pickup Information + Row( + children: [ + Icon( + Icons.arrow_upward, + size: 16, + color: Colors.green[600], + ), + const SizedBox(width: 4), + Text( + '${AppLocalizations.of(context).pickup}${job.pickupDate.isNotEmpty ? ' ${_formatDateString(job.pickupDate)}${job.pickupTime.isNotEmpty ? ' ${_formatTimeString(job.pickupTime)}' : ''}' : ''}', + style: TextStyle( + fontSize: 12, + color: Colors.grey[700], + fontWeight: FontWeight.w500, + ), + ), + ], + ), + const SizedBox(height: 2), + if (pickupDisplayName.isNotEmpty) + Text( + pickupDisplayName, + style: TextStyle( + fontSize: 13, + color: Colors.grey[800], + ), + ), + if (pickupAddress.isNotEmpty) + Row( + children: [ + Expanded( + child: Text( + pickupAddress, + style: TextStyle( + fontSize: 12, + color: Colors.grey[600], + ), + ), + ), + const SizedBox(width: 8), + IconButton( + tooltip: AppLocalizations.of(context).routePlan, + icon: const Icon( + Icons.route, + color: Colors.green, + ), + onPressed: () { + if (_routeActionInProgress) return; + setState(() => _routeActionInProgress = true); + _openRoutingView( + address: pickupAddress, + isDelivery: false, + title: + pickupDisplayName.isNotEmpty + ? 'Abholung$pickupDisplayName' + : 'Abholadresse', + ); + // Reset after short delay to avoid double-push + Future.delayed( + const Duration(milliseconds: 600), + () { + if (mounted) { + setState( + () => _routeActionInProgress = false, + ); + } + }, + ); + }, + ), + ], + ), + const SizedBox(height: 8), + // Delivery Information + Row( + children: [ + Icon( + Icons.arrow_downward, + size: 16, + color: Colors.blue[600], + ), + const SizedBox(width: 4), + Text( + '${AppLocalizations.of(context).delivery}${job.deliveryDate.isNotEmpty ? ' ${_formatDateString(job.deliveryDate)}${job.deliveryTime.isNotEmpty ? ' ${_formatTimeString(job.deliveryTime)}' : ''}' : ''}', + style: TextStyle( + fontSize: 12, + color: Colors.grey[700], + fontWeight: FontWeight.w500, + ), + ), + ], + ), + const SizedBox(height: 2), + if (deliveryDisplayName.isNotEmpty) + Text( + deliveryDisplayName, + style: TextStyle( + fontSize: 13, + color: Colors.grey[800], + ), + ), + if (deliveryAddress.isNotEmpty) + Row( + children: [ + Expanded( + child: Text( + deliveryAddress, + style: TextStyle( + fontSize: 12, + color: Colors.grey[600], + ), + ), + ), + const SizedBox(width: 8), + IconButton( + tooltip: 'Route planen', + icon: const Icon( + Icons.route, + color: Colors.blueAccent, + ), + onPressed: () { + if (_routeActionInProgress) return; + setState(() => _routeActionInProgress = true); + _openRoutingView( + address: deliveryRouteAddress, + isDelivery: true, + title: + hasMultipleDeliveryStations + ? 'Erste Zustelladresse' + : (deliveryDisplayName.isNotEmpty + ? 'Zustellung $deliveryDisplayName' + : 'Zustelladresse'), + ); + // Reset after short delay to avoid double-push + Future.delayed( + const Duration(milliseconds: 600), + () { + if (mounted) { + setState( + () => _routeActionInProgress = false, + ); + } + }, + ); + }, + ), + ], + ), + const SizedBox(height: 8), + // Dates and Price + Row( + children: [ + Expanded( + child: Row( + children: [ + Icon( + Icons.schedule, + size: 16, + color: Colors.grey[500], + ), + const SizedBox(width: 4), + Text( + '${AppLocalizations.of(context).created}: ${_formatDate(job.createdAt)}', + style: TextStyle( + fontSize: 12, + color: Colors.grey[500], + ), + ), + ], + ), + ), + if (job.price > 0) ...[ + Container( + padding: const EdgeInsets.symmetric( + horizontal: 6, + vertical: 2, + ), + decoration: BoxDecoration( + color: Colors.green[50], + borderRadius: BorderRadius.circular(8), + border: Border.all(color: Colors.green[200]!), + ), + child: Text( + '${job.price.toStringAsFixed(2)} €', + style: TextStyle( + fontSize: 12, + color: Colors.green[700], + fontWeight: FontWeight.w600, + ), + ), + ), + ], + ], + ), + ], + ), + ), + ), + ), + ), + ), + ], + ), + ); + } + + void _showJobDetails(Job job) { + Navigator.of(context).pushNamed('/cargo_items', arguments: job); + } + + void _toggleTaskCompletion(Job job, int taskIndex) { + // Create a new task with toggled completion status + final updatedTask = job.tasks[taskIndex].copyWith( + completed: !job.tasks[taskIndex].completed, + ); + + // Create a new list with the updated task + final updatedTasks = List.from(job.tasks); + updatedTasks[taskIndex] = updatedTask; + final updatedDeliveryStations = + job.deliveryStations + .map( + (station) => DeliveryStation( + stationOrder: station.stationOrder, + company: station.company, + salutation: station.salutation, + firstName: station.firstName, + lastName: station.lastName, + phone: station.phone, + street: station.street, + houseNumber: station.houseNumber, + addressAddition: station.addressAddition, + zip: station.zip, + city: station.city, + deliveryDate: station.deliveryDate, + deliveryTime: station.deliveryTime, + tasks: + station.tasks + .map( + (task) => + task.id == updatedTask.id ? updatedTask : task, + ) + .toList(), + ), + ) + .toList(); + + // Create a new job instance with updated tasks + final updatedJob = Job( + id: job.id, + jobNumber: job.jobNumber, + status: job.status, + createdAt: job.createdAt, + updatedAt: job.updatedAt, + createdBy: job.createdBy, + customerSelection: job.customerSelection, + pickupCompany: job.pickupCompany, + pickupSalutation: job.pickupSalutation, + pickupFirstName: job.pickupFirstName, + pickupLastName: job.pickupLastName, + pickupPhone: job.pickupPhone, + pickupStreet: job.pickupStreet, + pickupHouseNumber: job.pickupHouseNumber, + pickupAddressAddition: job.pickupAddressAddition, + pickupZip: job.pickupZip, + pickupCity: job.pickupCity, + deliveryCompany: job.deliveryCompany, + deliverySalutation: job.deliverySalutation, + deliveryFirstName: job.deliveryFirstName, + deliveryLastName: job.deliveryLastName, + deliveryPhone: job.deliveryPhone, + deliveryStreet: job.deliveryStreet, + deliveryHouseNumber: job.deliveryHouseNumber, + deliveryAddressAddition: job.deliveryAddressAddition, + deliveryZip: job.deliveryZip, + deliveryCity: job.deliveryCity, + digitalProcessing: job.digitalProcessing, + appUser: job.appUser, + pickupDate: job.pickupDate, + pickupTime: job.pickupTime, + deliveryDate: job.deliveryDate, + deliveryTime: job.deliveryTime, + remark: job.remark, + price: job.price, + draft: job.draft, + cargoItems: job.cargoItems, + deliveryStations: updatedDeliveryStations, + tasks: updatedTasks, + deliveryCitiesDisplay: job.deliveryCitiesDisplay, + firstDeliveryCity: job.firstDeliveryCity, + lastDeliveryCity: job.lastDeliveryCity, + title: job.title, + description: job.description, + priority: job.priority, + dueDate: job.dueDate, + assignedTo: job.assignedTo, + location: job.location, + additionalData: job.additionalData, + ); + + // Update the job in the app state + _appState.updateJob(updatedJob); + + setState(() { + // Trigger UI refresh + }); + + // Close and reopen the dialog to reflect changes + Navigator.of(context).pop(); + _showJobDetailsDialog(updatedJob); + } + + void _showJobDetailsDialog(Job job) { + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: Text(job.title), + content: SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + '${AppLocalizations.of(context).status}: ${job.statusDisplayText}', + style: const TextStyle(fontWeight: FontWeight.w500), + ), + const SizedBox(height: 8), + Text( + '${AppLocalizations.of(context).priority}: ${job.priorityDisplayText}', + style: const TextStyle(fontWeight: FontWeight.w500), + ), + const SizedBox(height: 8), + Text( + '${AppLocalizations.of(context).created}: ${_formatDate(job.createdAt)}', + style: const TextStyle(fontWeight: FontWeight.w500), + ), + if (job.dueDate != null) ...[ + const SizedBox(height: 8), + Text( + '${AppLocalizations.of(context).dueDate}: ${_formatDate(job.dueDate!)}', + style: const TextStyle(fontWeight: FontWeight.w500), + ), + ], + if (job.location != null) ...[ + const SizedBox(height: 8), + Text( + '${AppLocalizations.of(context).location}: ${job.location}', + style: const TextStyle(fontWeight: FontWeight.w500), + ), + ], + if (job.description.isNotEmpty) ...[ + const SizedBox(height: 16), + Text( + AppLocalizations.of(context).description, + style: const TextStyle(fontWeight: FontWeight.w600), + ), + const SizedBox(height: 8), + Text(job.description), + ], + // CargoItems section + if (job.cargoItems.isNotEmpty) ...[ + const SizedBox(height: 16), + Text( + AppLocalizations.of(context).cargo, + style: const TextStyle(fontWeight: FontWeight.w600), + ), + const SizedBox(height: 8), + ...job.cargoItems.asMap().entries.map((entry) { + final cargoItem = entry.value; + return Container( + margin: const EdgeInsets.only(bottom: 8), + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: Colors.grey[50], + borderRadius: BorderRadius.circular(8), + border: Border.all(color: Colors.grey[300]!), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + cargoItem.description, + style: const TextStyle(fontWeight: FontWeight.w500), + ), + const SizedBox(height: 4), + Text( + '${AppLocalizations.of(context).quantity}: ${cargoItem.quantity}', + ), + Text( + '${AppLocalizations.of(context).weight}: ${cargoItem.formattedWeight}', + ), + Text( + '${AppLocalizations.of(context).dimensions}: ${cargoItem.formattedDimensions}', + ), + ], + ), + ); + }), + ], + if (job.deliveryStations.isNotEmpty) ...[ + const SizedBox(height: 16), + Text( + '${AppLocalizations.of(context).delivery} (${job.deliveryStations.length})', + style: const TextStyle(fontWeight: FontWeight.w600), + ), + const SizedBox(height: 8), + ...job.deliveryStations.map( + (station) => Container( + margin: const EdgeInsets.only(bottom: 8), + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: Colors.grey[50], + borderRadius: BorderRadius.circular(8), + border: Border.all(color: Colors.grey[300]!), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Station ${station.stationOrder + 1}: ${station.displayName}', + style: const TextStyle(fontWeight: FontWeight.w500), + ), + if (station.formattedAddress.isNotEmpty) ...[ + const SizedBox(height: 4), + Text(station.formattedAddress), + ], + if (station.tasks.isNotEmpty) ...[ + const SizedBox(height: 4), + Text( + '${AppLocalizations.of(context).tasks}: ${station.tasks.length}', + ), + ], + ], + ), + ), + ), + ], + // Tasks section + if (job.tasks.isNotEmpty) ...[ + const SizedBox(height: 16), + Text( + AppLocalizations.of(context).tasks, + style: const TextStyle(fontWeight: FontWeight.w600), + ), + const SizedBox(height: 8), + ...job.tasks.asMap().entries.map( + (entry) => GestureDetector( + onTap: () => _toggleTaskCompletion(job, entry.key), + child: Container( + margin: const EdgeInsets.only(bottom: 4), + padding: const EdgeInsets.symmetric( + vertical: 8, + horizontal: 4, + ), + decoration: BoxDecoration( + color: + entry.value.completed + ? Colors.green.withValues(alpha: 0.1) + : Colors.transparent, + borderRadius: BorderRadius.circular(4), + border: Border.all( + color: + entry.value.completed + ? Colors.green.withValues(alpha: 0.3) + : Colors.transparent, + ), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon( + entry.value.completed + ? Icons.check_circle + : Icons.radio_button_unchecked, + size: 20, + color: + entry.value.completed + ? Colors.green + : Colors.grey[600], + ), + const SizedBox(width: 8), + Text( + '${entry.key + 1}. ', + style: TextStyle( + fontWeight: FontWeight.w500, + decoration: + entry.value.completed + ? TextDecoration.lineThrough + : null, + color: + entry.value.completed + ? Colors.grey[600] + : null, + ), + ), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + _getTaskDisplayText(entry.value), + style: TextStyle( + decoration: + entry.value.completed + ? TextDecoration.lineThrough + : null, + color: + entry.value.completed + ? Colors.grey[600] + : null, + ), + ), + if (_getTaskStationLabel(job, entry.value) != + null) ...[ + const SizedBox(height: 2), + Text( + _getTaskStationLabel(job, entry.value)!, + style: TextStyle( + fontSize: 12, + color: Colors.grey[600], + ), + ), + ], + ], + ), + ), + ], + ), + ), + ), + ), + ], + if (job.additionalData != null && + job.additionalData!.isNotEmpty) ...[ + const SizedBox(height: 16), + Text( + AppLocalizations.of(context).description, + style: const TextStyle(fontWeight: FontWeight.w600), + ), + const SizedBox(height: 8), + ...job.additionalData!.entries.map( + (entry) => Padding( + padding: const EdgeInsets.only(bottom: 4), + child: Text('${entry.key}: ${entry.value}'), + ), + ), + ], + ], + ), + ), + actions: [ + TextButton( + onPressed: () { + Navigator.of(context).pop(); + }, + child: Text(AppLocalizations.of(context).close), + ), + ], + ); + }, + ); + } + + String _getTaskDisplayText(Task task) { + final l10n = AppLocalizations.of(context); + // Generate display text based on task type + switch (task) { + case ConfirmationTask(): + return task.description!; + + case PhotoTask(): + return '${l10n.photoCapture} (${task.minPhotoCount}-${task.maxPhotoCount} ${l10n.photos})'; + + case TodoListTask(): + return '${l10n.checklist} (${task.todoItems.length})'; + + case SignatureTask(): + return l10n.signatureRequired; + + case BarcodeTask(): + return '${l10n.barcodeScan} (${task.minBarcodeCount}-${task.maxBarcodeCount})'; + + case CommentTask(): + return task.required ? l10n.commentRequired : l10n.comment; + + default: + return l10n.tasks; + } + } + + String? _getTaskStationLabel(Job job, Task task) { + final stationOrder = task.stationOrder; + if (stationOrder == null) { + return null; + } + + for (final station in job.deliveryStations) { + if (station.stationOrder == stationOrder) { + final suffix = + station.displayName.isNotEmpty ? station.displayName : station.city; + return suffix.isNotEmpty + ? 'Station ${stationOrder + 1}: $suffix' + : 'Station ${stationOrder + 1}'; + } + } + + return 'Station ${stationOrder + 1}'; + } +} diff --git a/app/lib/l10n/app_localizations.dart b/app/lib/l10n/app_localizations.dart new file mode 100644 index 0000000..09fb421 --- /dev/null +++ b/app/lib/l10n/app_localizations.dart @@ -0,0 +1,267 @@ +import 'package:flutter/material.dart'; +import 'app_localizations_de.dart'; +import 'app_localizations_en.dart'; +import 'app_localizations_es.dart'; +import 'app_localizations_fr.dart'; +import 'app_localizations_pl.dart'; +import 'app_localizations_ru.dart'; +import 'app_localizations_tr.dart'; +import 'app_localizations_et.dart'; +import 'app_localizations_lv.dart'; +import 'app_localizations_lt.dart'; + +/// Supported language codes +const List supportedLanguageCodes = ['de', 'en', 'es', 'fr', 'pl', 'ru', 'tr', 'et', 'lv', 'lt']; + +/// AppLocalizations provides localized strings for the app +abstract class AppLocalizations { + static AppLocalizations of(BuildContext context) { + return Localizations.of(context, AppLocalizations) ?? AppLocalizationsDe(); + } + + static const LocalizationsDelegate delegate = _AppLocalizationsDelegate(); + + /// Language name + String get languageName; + + /// Flag emoji + String get flagEmoji; + + // ==================== GENERAL ==================== + String get appTitle; + String get ok; + String get cancel; + String get save; + String get delete; + String get close; + String get confirm; + String get error; + String get success; + String get loading; + String get refresh; + String get version; + String get unknown; + + // ==================== NAVIGATION ==================== + String get jobs; + String get availableJobs; + String get chats; + String get settings; + String get logout; + String get logoutConfirm; + String get logoutConfirmMessage; + String get openChat; + String get chatInfo; + String get routePlan; + + // ==================== LOGIN ==================== + String get welcomeBack; + String get loginSubtitle; + String get email; + String get password; + String get login; + String get loggingIn; + String get forgotPassword; + String get forgotPasswordMessage; + String get loginSuccess; + String get loginFailed; + String get connectionFailed; + String get connectionTimeout; + String get connecting; + String get connectionError; + String get loginError; + + // ==================== JOBS ==================== + String get noJobsAssigned; + String get noJobsMessage; + String get pullToRefresh; + String get newLabel; + String get tasksToComplete; + String get pickup; + String get delivery; + String get created; + String get status; + String get priority; + String get dueDate; + String get location; + String get description; + String get cargo; + String get quantity; + String get weight; + String get dimensions; + String get jobDeleted; + String get jobDeleteError; + String get jobCompleted; + String get from; + String get to; + String get jobsUpdated; + String get connectionRestored; + String get connectionLost; + String get offline; + String get deleteJob; + String get jobRemoved; + String get newJobReceived; + + // ==================== TASKS ==================== + String get tasks; + String get noTasks; + String get noTasksMessage; + String get taskOrder; + String get confirmationRequired; + String get confirmationDescription; + String get checklist; + String get checklistDescription; + String get completeTask; + String get completeTaskConfirm; + String get completeTaskNote; + String get taskCompleted; + String get comment; + String get commentRequired; + String get enterComment; + String get commentDescription; + String get finish; + String get signature; + String get signatureCapture; + String get signatureRequired; + String get clear; + String get signatureError; + String get signatureInstruction; + String get photoCapture; + String get requiredPhotos; + String get photosTaken; + String get photos; + String get takePhoto; + String get selectFromLibrary; + String get retakePhoto; + String get photoRequired; + String get minPhotos; + String get maxPhotos; + String get photoError; + String get deletePhoto; + String get deletePhotoConfirm; + String get barcode; + String get barcodeScan; + String get scanBarcode; + String get barcodeRequired; + String get minBarcodes; + String get maxBarcodes; + String get scanned; + String get scannedBarcodes; + String get barcodesRequired; + String get enterBarcode; + String get barcodeEnterDescription; + String barcodeNumberRequired(int number); + String barcodeNumberOptional(int number); + String get barcodeError; + String get cameraError; + String get cameraNotReady; + String get cameraNotAvailable; + String get cameraNotSupportedMessage; + String get cameraNotSupportedOnPlatform; + String get maxPhotosReached; + String get cameraReadyNoPreview; + String get cameraLoading; + String get cameraInitializing; + String get cameraLoadingMessage; + String get addPhotos; + String get addPhotosInstruction; + String get photoOf; + + // ==================== CHAT ==================== + String get typeMessage; + String get send; + String get noSender; + String get noSenderMessage; + String get noRecipient; + String get noRecipientMessage; + String get messageSendError; + String get photoSendError; + String get photoProcessError; + String get imageSendError; + String get chatTypeJob; + String get chatTypeGeneral; + String get jobNumber; + String get messages; + String get selectPhoto; + String get unreadMessages; + + // ==================== CARGO ==================== + String get cargoDetails; + String get itemName; + String get itemNumber; + String get item; + String get weightUnit; + String get dimensionUnit; + String get noCargoItems; + String get noCargoItemsMessage; + String get article; + + // ==================== TASK TYPES ==================== + String get takePhotos; + String get photosCount; + String get checklistPoints; + String get signatureRequiredText; + String get scanBarcodes; + String get barcodeCount; + String get commentOptional; + String get genericTask; + String get complete; + String get abort; + String get optional; + String get skipTask; + + // ==================== SETTINGS ==================== + String get language; + String get languageChanged; + String get appInfo; + + // ==================== STATUS ==================== + String get statusCreated; + String get statusAssigned; + String get statusInProgress; + String get statusCompleted; + String get priorityLow; + String get priorityMedium; + String get priorityHigh; + String get priorityUrgent; +} + +class _AppLocalizationsDelegate extends LocalizationsDelegate { + const _AppLocalizationsDelegate(); + + @override + bool isSupported(Locale locale) { + return supportedLanguageCodes.contains(locale.languageCode); + } + + @override + Future load(Locale locale) async { + switch (locale.languageCode) { + case 'de': + return AppLocalizationsDe(); + case 'en': + return AppLocalizationsEn(); + case 'es': + return AppLocalizationsEs(); + case 'fr': + return AppLocalizationsFr(); + case 'pl': + return AppLocalizationsPl(); + case 'ru': + return AppLocalizationsRu(); + case 'tr': + return AppLocalizationsTr(); + case 'et': + return AppLocalizationsEt(); + case 'lv': + return AppLocalizationsLv(); + case 'lt': + return AppLocalizationsLt(); + default: + return AppLocalizationsDe(); + } + } + + @override + bool shouldReload(LocalizationsDelegate old) => false; +} diff --git a/app/lib/l10n/app_localizations_de.dart b/app/lib/l10n/app_localizations_de.dart new file mode 100644 index 0000000..0139050 --- /dev/null +++ b/app/lib/l10n/app_localizations_de.dart @@ -0,0 +1,551 @@ +import 'app_localizations.dart'; + +class AppLocalizationsDe extends AppLocalizations { + @override + String get languageName => 'Deutsch'; + + @override + String get flagEmoji => '🇩🇪'; + + // ==================== GENERAL ==================== + @override + String get appTitle => 'VotianLT App'; + + @override + String get ok => 'OK'; + + @override + String get cancel => 'Abbrechen'; + + @override + String get save => 'Speichern'; + + @override + String get delete => 'Löschen'; + + @override + String get close => 'Schließen'; + + @override + String get confirm => 'Bestätigen'; + + @override + String get error => 'Fehler'; + + @override + String get success => 'Erfolg'; + + @override + String get loading => 'Laden...'; + + @override + String get refresh => 'Aktualisieren'; + + @override + String get version => 'Version'; + + @override + String get unknown => 'Unbekannt'; + + // ==================== NAVIGATION ==================== + @override + String get jobs => 'Jobs'; + + @override + String get availableJobs => 'Verfügbare Jobs'; + + @override + String get chats => 'Chats'; + + @override + String get settings => 'Einstellungen'; + + @override + String get logout => 'Abmelden'; + + @override + String get logoutConfirm => 'Abmelden'; + + @override + String get logoutConfirmMessage => 'Möchten Sie sich wirklich abmelden?'; + + @override + String get openChat => 'Chat öffnen'; + + @override + String get chatInfo => 'Chat-Info'; + + @override + String get routePlan => 'Route planen'; + + // ==================== LOGIN ==================== + @override + String get welcomeBack => 'Willkommen zurück'; + + @override + String get loginSubtitle => 'Melden Sie sich in Ihrem Konto an'; + + @override + String get email => 'E-Mail'; + + @override + String get password => 'Passwort'; + + @override + String get login => 'Anmelden'; + + @override + String get loggingIn => 'Verbinden…'; + + @override + String get forgotPassword => 'Passwort vergessen?'; + + @override + String get forgotPasswordMessage => 'Passwort vergessen Funktion noch nicht implementiert'; + + @override + String get loginSuccess => 'Erfolgreich abgemeldet'; + + @override + String get loginFailed => 'Anmeldung fehlgeschlagen'; + + @override + String get connectionFailed => 'Verbindung zum Server fehlgeschlagen (Timeout).'; + + @override + String get connectionTimeout => 'Verbindung zum Server fehlgeschlagen (Timeout).'; + + @override + String get connecting => 'Verbindung zum Server wird hergestellt...'; + + @override + String get connectionError => 'Verbindungsfehler'; + + @override + String get loginError => 'Fehler bei der Anmeldung'; + + // ==================== JOBS ==================== + @override + String get noJobsAssigned => 'Keine Jobs zugewiesen'; + + @override + String get noJobsMessage => 'Ihre zugewiesenen Jobs werden hier angezeigt.'; + + @override + String get pullToRefresh => 'Nach unten ziehen zum Aktualisieren'; + + @override + String get newLabel => 'NEU'; + + @override + String get tasksToComplete => 'Zu erledigende Aufgaben'; + + @override + String get pickup => 'Abholung'; + + @override + String get delivery => 'Zustellung'; + + @override + String get created => 'Erstellt'; + + @override + String get status => 'Status'; + + @override + String get priority => 'Priorität'; + + @override + String get dueDate => 'Fälligkeitsdatum'; + + @override + String get location => 'Ort'; + + @override + String get description => 'Beschreibung'; + + @override + String get cargo => 'Fracht'; + + @override + String get quantity => 'Anzahl'; + + @override + String get weight => 'Gewicht'; + + @override + String get dimensions => 'Abmessungen'; + + @override + String get jobDeleted => 'Job gelöscht'; + + @override + String get jobDeleteError => 'Fehler beim Löschen des Jobs'; + + @override + String get jobCompleted => 'Job abgeschlossen'; + + @override + String get from => 'Von'; + + @override + String get to => 'nach'; + + @override + String get jobsUpdated => 'Jobs aktualisiert'; + + @override + String get connectionRestored => 'Verbindung wiederhergestellt. Lade Jobs...'; + + @override + String get connectionLost => 'Verbindung verloren. Offline.'; + + @override + String get offline => 'Offline'; + + @override + String get deleteJob => 'Job löschen'; + + @override + String get jobRemoved => 'wurde entfernt'; + + @override + String get newJobReceived => 'Neuer Job erhalten'; + + // ==================== TASKS ==================== + @override + String get tasks => 'Aufgaben'; + + @override + String get noTasks => 'Keine Aufgaben'; + + @override + String get noTasksMessage => 'Für diesen Job sind keine Aufgaben definiert.'; + + @override + String get taskOrder => 'Reihenfolge'; + + @override + String get confirmationRequired => 'Bestätigung erforderlich'; + + @override + String get confirmationDescription => 'Klicken Sie auf den Button um die Aufgabe zu erledigen.'; + + @override + String get checklist => 'Checkliste'; + + @override + String get checklistDescription => 'Bitte alle Punkte abhaken:'; + + @override + String get completeTask => 'Aufgabe abschließen'; + + @override + String get completeTaskConfirm => 'Möchten Sie diese Aufgabe als erledigt markieren?'; + + @override + String get completeTaskNote => 'Notiz (optional)'; + + @override + String get taskCompleted => 'Aufgabe erledigt'; + + @override + String get comment => 'Kommentar'; + + @override + String get commentRequired => 'Kommentar (erforderlich)'; + + @override + String get enterComment => 'Kommentar eingeben'; + + @override + String get commentDescription => 'Bitte geben Sie einen Kommentar ein:'; + + @override + String get finish => 'Fertig'; + + @override + String get signature => 'Unterschrift'; + + @override + String get signatureCapture => 'Unterschrift erfassen'; + + @override + String get signatureRequired => 'Bitte eine Unterschrift erfassen.'; + + @override + String get clear => 'Leeren'; + + @override + String get signatureError => 'Fehler beim Speichern der Unterschrift'; + + @override + String get signatureInstruction => 'Bitte unterschreiben Sie im Feld unten (Maus oder Finger).'; + + @override + String get photoCapture => 'Fotos aufnehmen'; + @override + String get requiredPhotos => 'Benötigte Fotos'; + @override + String get photosTaken => 'Aufgenommen'; + + @override + String get photos => 'Fotos'; + + @override + String get takePhoto => 'Foto aufnehmen'; + + @override + String get selectFromLibrary => 'Aus Bibliothek wählen'; + + @override + String get retakePhoto => 'Neu aufnehmen'; + + @override + String get photoRequired => 'Foto erforderlich'; + + @override + String get minPhotos => 'Mindestens'; + + @override + String get maxPhotos => 'Maximal'; + + @override + String get photoError => 'Fehler beim Aufnehmen des Fotos'; + + @override + String get deletePhoto => 'Foto löschen'; + + @override + String get deletePhotoConfirm => 'Möchten Sie dieses Foto wirklich löschen?'; + + @override + String get barcode => 'Barcode'; + + @override + String get barcodeScan => 'Barcode scannen'; + + @override + String get scanBarcode => 'Barcode scannen'; + + @override + String get barcodeRequired => 'Barcode erforderlich'; + + @override + String get minBarcodes => 'Mindestens'; + + @override + String get maxBarcodes => 'Maximal'; + + @override + String get scanned => 'Gescannt'; + + @override + String get scannedBarcodes => 'Gescannte Barcodes'; + + @override + String get barcodesRequired => 'Barcodes erforderlich'; + + @override + String get enterBarcode => 'Barcode eingeben'; + + @override + String get barcodeEnterDescription => 'Bitte geben Sie die Barcodes ein:'; + + @override + String barcodeNumberRequired(int number) => 'Barcode $number (erforderlich)'; + + @override + String barcodeNumberOptional(int number) => 'Barcode $number (optional)'; + + @override + String get barcodeError => 'Fehler beim Scannen des Barcodes'; + + @override + String get cameraError => 'Fehler beim Initialisieren der Kamera'; + + @override + String get cameraNotReady => 'Kamera ist nicht bereit oder nicht verfügbar'; + + @override + String get cameraNotAvailable => 'Kamera nicht verfügbar'; + + @override + String get cameraNotSupportedMessage => 'Auf dieser Plattform wird die Kamera nicht unterstützt.'; + + @override + String get cameraNotSupportedOnPlatform => 'Nicht unterstützt auf dieser Plattform'; + + @override + String get maxPhotosReached => 'Maximum erreicht'; + + @override + String get cameraReadyNoPreview => 'Kamera bereit (ohne Vorschau)'; + + @override + String get cameraLoading => 'Kamera lädt...'; + + @override + String get cameraInitializing => 'Kamera wird initialisiert...'; + + @override + String get cameraLoadingMessage => 'Bitte warten Sie, während die Kamera geladen wird'; + + @override + String get addPhotos => 'Fotos hinzufügen'; + + @override + String get addPhotosInstruction => 'Verwenden Sie den Button „Foto auswählen", um Bilder von Ihrer Kamera oder Festplatte hinzuzufügen.'; + + @override + String get photoOf => 'von'; + + // ==================== CHAT ==================== + @override + String get typeMessage => 'Nachricht eingeben...'; + + @override + String get send => 'Senden'; + + @override + String get noSender => 'Kein Absender verfügbar'; + + @override + String get noSenderMessage => 'Kein Absender verfügbar. Bitte erneut anmelden.'; + + @override + String get noRecipient => 'Kein Empfänger konfiguriert'; + + @override + String get noRecipientMessage => 'Kein Empfänger für diesen Chat konfiguriert.'; + + @override + String get messageSendError => 'Nachricht konnte nicht gesendet werden.'; + + @override + String get photoSendError => 'Foto konnte nicht gesendet werden.'; + + @override + String get photoProcessError => 'Foto konnte nicht verarbeitet werden.'; + + @override + String get imageSendError => 'Bild konnte nicht gesendet werden.'; + + @override + String get chatTypeJob => 'Job-spezifisch'; + + @override + String get chatTypeGeneral => 'Allgemein'; + + @override + String get jobNumber => 'Job-Nummer'; + + @override + String get messages => 'Nachrichten'; + + @override + String get selectPhoto => 'Foto auswählen'; + + @override + String get unreadMessages => 'Ungelesene Nachrichten'; + + // ==================== SETTINGS ==================== + @override + String get language => 'Sprache'; + + @override + String get languageChanged => 'Sprache geändert zu'; + + @override + String get appInfo => 'APP-INFO'; + + // ==================== CARGO ==================== + @override + String get cargoDetails => 'Frachtdetails'; + + @override + String get itemName => 'Bezeichnung'; + + @override + String get itemNumber => 'Positions-Nr.'; + + @override + String get item => 'Position'; + + @override + String get weightUnit => 'kg'; + + @override + String get dimensionUnit => 'cm'; + + @override + String get noCargoItems => 'Keine Frachtgüter'; + + @override + String get noCargoItemsMessage => 'Für diesen Job sind keine Frachtgüter definiert.'; + + @override + String get article => 'Artikel'; + + // ==================== TASK TYPES ==================== + @override + String get takePhotos => 'Fotos aufnehmen'; + + @override + String get photosCount => 'Fotos'; + + @override + String get checklistPoints => 'Punkte'; + + @override + String get signatureRequiredText => 'Unterschrift erforderlich'; + + @override + String get scanBarcodes => 'Barcode scannen'; + + @override + String get barcodeCount => 'Codes'; + + @override + String get commentOptional => 'Kommentar'; + + @override + String get genericTask => 'Allgemeine Aufgabe'; + + @override + String get complete => 'Abschließen'; + + @override + String get abort => 'Abbrechen'; + + @override + String get optional => 'Optional'; + + @override + String get skipTask => 'Überspringen'; + + // ==================== STATUS ==================== + @override + String get statusCreated => 'Erstellt'; + + @override + String get statusAssigned => 'Zugewiesen'; + + @override + String get statusInProgress => 'In Bearbeitung'; + + @override + String get statusCompleted => 'Abgeschlossen'; + + @override + String get priorityLow => 'Niedrig'; + + @override + String get priorityMedium => 'Mittel'; + + @override + String get priorityHigh => 'Hoch'; + + @override + String get priorityUrgent => 'Dringend'; +} diff --git a/app/lib/l10n/app_localizations_en.dart b/app/lib/l10n/app_localizations_en.dart new file mode 100644 index 0000000..7a6eb9c --- /dev/null +++ b/app/lib/l10n/app_localizations_en.dart @@ -0,0 +1,551 @@ +import 'app_localizations.dart'; + +class AppLocalizationsEn extends AppLocalizations { + @override + String get languageName => 'English'; + + @override + String get flagEmoji => '🇬🇧'; + + // ==================== GENERAL ==================== + @override + String get appTitle => 'VotianLT App'; + + @override + String get ok => 'OK'; + + @override + String get cancel => 'Cancel'; + + @override + String get save => 'Save'; + + @override + String get delete => 'Delete'; + + @override + String get close => 'Close'; + + @override + String get confirm => 'Confirm'; + + @override + String get error => 'Error'; + + @override + String get success => 'Success'; + + @override + String get loading => 'Loading...'; + + @override + String get refresh => 'Refresh'; + + @override + String get version => 'Version'; + + @override + String get unknown => 'Unknown'; + + // ==================== NAVIGATION ==================== + @override + String get jobs => 'Jobs'; + + @override + String get availableJobs => 'Available Jobs'; + + @override + String get chats => 'Chats'; + + @override + String get settings => 'Settings'; + + @override + String get logout => 'Logout'; + + @override + String get logoutConfirm => 'Logout'; + + @override + String get logoutConfirmMessage => 'Do you really want to logout?'; + + @override + String get openChat => 'Open Chat'; + + @override + String get chatInfo => 'Chat Info'; + + @override + String get routePlan => 'Plan Route'; + + // ==================== LOGIN ==================== + @override + String get welcomeBack => 'Welcome Back'; + + @override + String get loginSubtitle => 'Sign in to your account'; + + @override + String get email => 'Email'; + + @override + String get password => 'Password'; + + @override + String get login => 'Login'; + + @override + String get loggingIn => 'Connecting...'; + + @override + String get forgotPassword => 'Forgot Password?'; + + @override + String get forgotPasswordMessage => 'Forgot password feature not yet implemented'; + + @override + String get loginSuccess => 'Successfully logged out'; + + @override + String get loginFailed => 'Login failed'; + + @override + String get connectionFailed => 'Connection to server failed (Timeout).'; + + @override + String get connectionTimeout => 'Connection to server failed (Timeout).'; + + @override + String get connecting => 'Connecting to server...'; + + @override + String get connectionError => 'Connection error'; + + @override + String get loginError => 'Error during login'; + + // ==================== JOBS ==================== + @override + String get noJobsAssigned => 'No Jobs Assigned'; + + @override + String get noJobsMessage => 'Your assigned jobs will be displayed here.'; + + @override + String get pullToRefresh => 'Pull down to refresh'; + + @override + String get newLabel => 'NEW'; + + @override + String get tasksToComplete => 'Tasks to Complete'; + + @override + String get pickup => 'Pickup'; + + @override + String get delivery => 'Delivery'; + + @override + String get created => 'Created'; + + @override + String get status => 'Status'; + + @override + String get priority => 'Priority'; + + @override + String get dueDate => 'Due Date'; + + @override + String get location => 'Location'; + + @override + String get description => 'Description'; + + @override + String get cargo => 'Cargo'; + + @override + String get quantity => 'Quantity'; + + @override + String get weight => 'Weight'; + + @override + String get dimensions => 'Dimensions'; + + @override + String get jobDeleted => 'Job deleted'; + + @override + String get jobDeleteError => 'Error deleting job'; + + @override + String get jobCompleted => 'Job completed'; + + @override + String get from => 'From'; + + @override + String get to => 'to'; + + @override + String get jobsUpdated => 'Jobs updated'; + + @override + String get connectionRestored => 'Connection restored. Loading jobs...'; + + @override + String get connectionLost => 'Connection lost. Offline.'; + + @override + String get offline => 'Offline'; + + @override + String get deleteJob => 'Delete Job'; + + @override + String get jobRemoved => 'was removed'; + + @override + String get newJobReceived => 'New job received'; + + // ==================== TASKS ==================== + @override + String get tasks => 'Tasks'; + + @override + String get noTasks => 'No Tasks'; + + @override + String get noTasksMessage => 'No tasks defined for this job.'; + + @override + String get taskOrder => 'Order'; + + @override + String get confirmationRequired => 'Confirmation Required'; + + @override + String get confirmationDescription => 'Click the button to complete the task.'; + + @override + String get checklist => 'Checklist'; + + @override + String get checklistDescription => 'Please check all items:'; + + @override + String get completeTask => 'Complete Task'; + + @override + String get completeTaskConfirm => 'Do you want to mark this task as completed?'; + + @override + String get completeTaskNote => 'Note (optional)'; + + @override + String get taskCompleted => 'Task completed'; + + @override + String get comment => 'Comment'; + + @override + String get commentRequired => 'Comment (required)'; + + @override + String get enterComment => 'Enter Comment'; + + @override + String get commentDescription => 'Please enter a comment:'; + + @override + String get finish => 'Finish'; + + @override + String get signature => 'Signature'; + + @override + String get signatureCapture => 'Capture Signature'; + + @override + String get signatureRequired => 'Please capture a signature.'; + + @override + String get clear => 'Clear'; + + @override + String get signatureError => 'Error saving signature'; + + @override + String get signatureInstruction => 'Please sign in the field below (mouse or finger).'; + + @override + String get photoCapture => 'Take Photos'; + @override + String get requiredPhotos => 'Required Photos'; + @override + String get photosTaken => 'Taken'; + + @override + String get photos => 'Photos'; + + @override + String get takePhoto => 'Take Photo'; + + @override + String get selectFromLibrary => 'Select from Library'; + + @override + String get retakePhoto => 'Retake'; + + @override + String get photoRequired => 'Photo required'; + + @override + String get minPhotos => 'At least'; + + @override + String get maxPhotos => 'Maximum'; + + @override + String get photoError => 'Error taking photo'; + + @override + String get deletePhoto => 'Delete Photo'; + + @override + String get deletePhotoConfirm => 'Do you really want to delete this photo?'; + + @override + String get barcode => 'Barcode'; + + @override + String get barcodeScan => 'Scan Barcode'; + + @override + String get scanBarcode => 'Scan Barcode'; + + @override + String get barcodeRequired => 'Barcode required'; + + @override + String get minBarcodes => 'At least'; + + @override + String get maxBarcodes => 'Maximum'; + + @override + String get scanned => 'Scanned'; + + @override + String get scannedBarcodes => 'Scanned Barcodes'; + + @override + String get barcodesRequired => 'Barcodes Required'; + + @override + String get enterBarcode => 'Enter Barcode'; + + @override + String get barcodeEnterDescription => 'Please enter the barcodes:'; + + @override + String barcodeNumberRequired(int number) => 'Barcode $number (required)'; + + @override + String barcodeNumberOptional(int number) => 'Barcode $number (optional)'; + + @override + String get barcodeError => 'Error scanning barcode'; + + @override + String get cameraError => 'Error initializing camera'; + + @override + String get cameraNotReady => 'Camera is not ready or not available'; + + @override + String get cameraNotAvailable => 'Camera not available'; + + @override + String get cameraNotSupportedMessage => 'The camera is not supported on this platform.'; + + @override + String get cameraNotSupportedOnPlatform => 'Not supported on this platform'; + + @override + String get maxPhotosReached => 'Maximum reached'; + + @override + String get cameraReadyNoPreview => 'Camera ready (no preview)'; + + @override + String get cameraLoading => 'Camera loading...'; + + @override + String get cameraInitializing => 'Initializing camera...'; + + @override + String get cameraLoadingMessage => 'Please wait while the camera is loading'; + + @override + String get addPhotos => 'Add photos'; + + @override + String get addPhotosInstruction => 'Use the "Select photo" button to add images from your camera or hard drive.'; + + @override + String get photoOf => 'of'; + + // ==================== CHAT ==================== + @override + String get typeMessage => 'Type a message...'; + + @override + String get send => 'Send'; + + @override + String get noSender => 'No sender available'; + + @override + String get noSenderMessage => 'No sender available. Please login again.'; + + @override + String get noRecipient => 'No recipient configured'; + + @override + String get noRecipientMessage => 'No recipient configured for this chat.'; + + @override + String get messageSendError => 'Message could not be sent.'; + + @override + String get photoSendError => 'Photo could not be sent.'; + + @override + String get photoProcessError => 'Photo could not be processed.'; + + @override + String get imageSendError => 'Image could not be sent.'; + + @override + String get chatTypeJob => 'Job-specific'; + + @override + String get chatTypeGeneral => 'General'; + + @override + String get jobNumber => 'Job Number'; + + @override + String get messages => 'Messages'; + + @override + String get selectPhoto => 'Select Photo'; + + @override + String get unreadMessages => 'Unread Messages'; + + // ==================== CARGO ==================== + @override + String get cargoDetails => 'Cargo Details'; + + @override + String get itemName => 'Description'; + + @override + String get itemNumber => 'Item Number'; + + @override + String get item => 'Item'; + + @override + String get weightUnit => 'kg'; + + @override + String get dimensionUnit => 'cm'; + + @override + String get noCargoItems => 'No Cargo Items'; + + @override + String get noCargoItemsMessage => 'No cargo items defined for this job.'; + + @override + String get article => 'Article'; + + // ==================== TASK TYPES ==================== + @override + String get takePhotos => 'Take Photos'; + + @override + String get photosCount => 'Photos'; + + @override + String get checklistPoints => 'Points'; + + @override + String get signatureRequiredText => 'Signature Required'; + + @override + String get scanBarcodes => 'Scan Barcodes'; + + @override + String get barcodeCount => 'Codes'; + + @override + String get commentOptional => 'Comment'; + + @override + String get genericTask => 'Generic Task'; + + @override + String get complete => 'Complete'; + + @override + String get abort => 'Cancel'; + + @override + String get optional => 'Optional'; + + @override + String get skipTask => 'Skip'; + + // ==================== SETTINGS ==================== + @override + String get language => 'Language'; + + @override + String get languageChanged => 'Language changed to'; + + @override + String get appInfo => 'APP INFO'; + + // ==================== STATUS ==================== + @override + String get statusCreated => 'Created'; + + @override + String get statusAssigned => 'Assigned'; + + @override + String get statusInProgress => 'In Progress'; + + @override + String get statusCompleted => 'Completed'; + + @override + String get priorityLow => 'Low'; + + @override + String get priorityMedium => 'Medium'; + + @override + String get priorityHigh => 'High'; + + @override + String get priorityUrgent => 'Urgent'; +} diff --git a/app/lib/l10n/app_localizations_es.dart b/app/lib/l10n/app_localizations_es.dart new file mode 100644 index 0000000..d2c676b --- /dev/null +++ b/app/lib/l10n/app_localizations_es.dart @@ -0,0 +1,385 @@ +import 'app_localizations.dart'; + +class AppLocalizationsEs extends AppLocalizations { + @override + String get languageName => 'Español'; + + @override + String get flagEmoji => '🇪🇸'; + + // ==================== GENERAL ==================== + @override + String get appTitle => 'VotianLT App'; + @override + String get ok => 'OK'; + @override + String get cancel => 'Cancelar'; + @override + String get save => 'Guardar'; + @override + String get delete => 'Eliminar'; + @override + String get close => 'Cerrar'; + @override + String get confirm => 'Confirmar'; + @override + String get error => 'Error'; + @override + String get success => 'Éxito'; + @override + String get loading => 'Cargando...'; + @override + String get refresh => 'Actualizar'; + @override + String get version => 'Versión'; + @override + String get unknown => 'Desconocido'; + + // ==================== NAVIGATION ==================== + @override + String get jobs => 'Trabajos'; + @override + String get availableJobs => 'Trabajos Disponibles'; + @override + String get chats => 'Chats'; + @override + String get settings => 'Ajustes'; + @override + String get logout => 'Cerrar sesión'; + @override + String get logoutConfirm => 'Cerrar sesión'; + @override + String get logoutConfirmMessage => '¿Realmente desea cerrar sesión?'; + @override + String get openChat => 'Abrir chat'; + @override + String get chatInfo => 'Info del chat'; + @override + String get routePlan => 'Planificar ruta'; + + // ==================== LOGIN ==================== + @override + String get welcomeBack => 'Bienvenido de nuevo'; + @override + String get loginSubtitle => 'Inicie sesión en su cuenta'; + @override + String get email => 'Correo electrónico'; + @override + String get password => 'Contraseña'; + @override + String get login => 'Iniciar sesión'; + @override + String get loggingIn => 'Conectando...'; + @override + String get forgotPassword => '¿Olvidó su contraseña?'; + @override + String get forgotPasswordMessage => 'Función de contraseña olvidada aún no implementada'; + @override + String get loginSuccess => 'Sesión cerrada correctamente'; + @override + String get loginFailed => 'Error al iniciar sesión'; + @override + String get connectionFailed => 'Error de conexión al servidor (Tiempo agotado).'; + @override + String get connectionTimeout => 'Error de conexión al servidor (Tiempo agotado).'; + @override + String get connecting => 'Conectando al servidor...'; + @override + String get connectionError => 'Error de conexión'; + @override + String get loginError => 'Error durante el inicio de sesión'; + + // ==================== JOBS ==================== + @override + String get noJobsAssigned => 'No hay trabajos asignados'; + @override + String get noJobsMessage => 'Sus trabajos asignados se mostrarán aquí.'; + @override + String get pullToRefresh => 'Deslice hacia abajo para actualizar'; + @override + String get newLabel => 'NUEVO'; + @override + String get tasksToComplete => 'Tareas por completar'; + @override + String get pickup => 'Recogida'; + @override + String get delivery => 'Entrega'; + @override + String get created => 'Creado'; + @override + String get status => 'Estado'; + @override + String get priority => 'Prioridad'; + @override + String get dueDate => 'Fecha de vencimiento'; + @override + String get location => 'Ubicación'; + @override + String get description => 'Descripción'; + @override + String get cargo => 'Carga'; + @override + String get quantity => 'Cantidad'; + @override + String get weight => 'Peso'; + @override + String get dimensions => 'Dimensiones'; + @override + String get jobDeleted => 'Trabajo eliminado'; + @override + String get jobDeleteError => 'Error al eliminar el trabajo'; + @override + String get jobCompleted => 'Trabajo completado'; + @override + String get from => 'De'; + @override + String get to => 'a'; + @override + String get jobsUpdated => 'Trabajos actualizados'; + @override + String get connectionRestored => 'Conexión restaurada. Cargando trabajos...'; + @override + String get connectionLost => 'Conexión perdida. Sin conexión.'; + @override + String get offline => 'Sin conexión'; + @override + String get deleteJob => 'Eliminar trabajo'; + @override + String get jobRemoved => 'fue eliminado'; + @override + String get newJobReceived => 'Nuevo trabajo recibido'; + + // ==================== TASKS ==================== + @override + String get tasks => 'Tareas'; + @override + String get noTasks => 'Sin tareas'; + @override + String get noTasksMessage => 'No hay tareas definidas para este trabajo.'; + @override + String get taskOrder => 'Orden'; + @override + String get confirmationRequired => 'Confirmación requerida'; + @override + String get confirmationDescription => 'Haga clic en el botón para completar la tarea.'; + @override + String get checklist => 'Lista de verificación'; + @override + String get checklistDescription => 'Por favor marque todos los elementos:'; + @override + String get completeTask => 'Completar tarea'; + @override + String get completeTaskConfirm => '¿Desea marcar esta tarea como completada?'; + @override + String get completeTaskNote => 'Nota (opcional)'; + @override + String get taskCompleted => 'Tarea completada'; + @override + String get comment => 'Comentario'; + @override + String get commentRequired => 'Comentario (requerido)'; + @override + String get enterComment => 'Ingrese comentario'; + @override + String get commentDescription => 'Por favor ingrese un comentario:'; + @override + String get finish => 'Finalizar'; + @override + String get signature => 'Firma'; + @override + String get signatureCapture => 'Capturar firma'; + @override + String get signatureRequired => 'Por favor capture una firma.'; + @override + String get clear => 'Limpiar'; + @override + String get signatureError => 'Error al guardar la firma'; + @override + String get signatureInstruction => 'Por favor, firme en el campo de abajo (ratón o dedo).'; + @override + String get photoCapture => 'Tomar fotos'; + @override + String get requiredPhotos => 'Fotos requeridas'; + @override + String get photosTaken => 'Tomadas'; + @override + String get photos => 'Fotos'; + @override + String get takePhoto => 'Tomar foto'; + @override + String get selectFromLibrary => 'Seleccionar de la biblioteca'; + @override + String get retakePhoto => 'Volver a tomar'; + @override + String get photoRequired => 'Foto requerida'; + @override + String get minPhotos => 'Al menos'; + @override + String get maxPhotos => 'Máximo'; + @override + String get photoError => 'Error al tomar la foto'; + @override + String get deletePhoto => 'Eliminar foto'; + @override + String get deletePhotoConfirm => '¿Realmente desea eliminar esta foto?'; + @override + String get barcode => 'Código de barras'; + @override + String get barcodeScan => 'Escanear código de barras'; + @override + String get scanBarcode => 'Escanear código de barras'; + @override + String get barcodeRequired => 'Código de barras requerido'; + @override + String get minBarcodes => 'Al menos'; + @override + String get maxBarcodes => 'Máximo'; + @override + String get scanned => 'Escaneado'; + @override + String get scannedBarcodes => 'Códigos de barras escaneados'; + @override + String get barcodesRequired => 'Códigos de barras requeridos'; + @override + String get enterBarcode => 'Ingresar código de barras'; + @override + String get barcodeEnterDescription => 'Por favor ingrese los códigos de barras:'; + @override + String barcodeNumberRequired(int number) => 'Código de barras $number (requerido)'; + @override + String barcodeNumberOptional(int number) => 'Código de barras $number (opcional)'; + @override + String get barcodeError => 'Error al escanear el código de barras'; + @override + String get cameraError => 'Error al inicializar la cámara'; + @override + String get cameraNotReady => 'La cámara no está lista o no disponible'; + @override + String get cameraNotAvailable => 'Cámara no disponible'; + @override + String get cameraNotSupportedMessage => 'La cámara no es compatible con esta plataforma.'; + @override + String get cameraNotSupportedOnPlatform => 'No soportado en esta plataforma'; + @override + String get maxPhotosReached => 'Máximo alcanzado'; + @override + String get cameraReadyNoPreview => 'Cámara lista (sin vista previa)'; + @override + String get cameraLoading => 'Cargando cámara...'; + @override + String get cameraInitializing => 'Inicializando cámara...'; + @override + String get cameraLoadingMessage => 'Por favor espere mientras se carga la cámara'; + @override + String get addPhotos => 'Añadir fotos'; + @override + String get addPhotosInstruction => 'Use el botón "Seleccionar foto" para añadir imágenes de su cámara o disco duro.'; + @override + String get photoOf => 'de'; + + // ==================== CHAT ==================== + @override + String get typeMessage => 'Escriba un mensaje...'; + @override + String get send => 'Enviar'; + @override + String get noSender => 'No hay remitente disponible'; + @override + String get noSenderMessage => 'No hay remitente disponible. Por favor inicie sesión de nuevo.'; + @override + String get noRecipient => 'No hay destinatario configurado'; + @override + String get noRecipientMessage => 'No hay destinatario configurado para este chat.'; + @override + String get messageSendError => 'El mensaje no pudo ser enviado.'; + @override + String get photoSendError => 'La foto no pudo ser enviada.'; + @override + String get photoProcessError => 'La foto no pudo ser procesada.'; + @override + String get imageSendError => 'La imagen no pudo ser enviada.'; + @override + String get chatTypeJob => 'Específico del trabajo'; + @override + String get chatTypeGeneral => 'General'; + @override + String get jobNumber => 'Número de trabajo'; + @override + String get messages => 'Mensajes'; + @override + String get selectPhoto => 'Seleccionar foto'; + @override + String get unreadMessages => 'Mensajes no leídos'; + + // ==================== CARGO ==================== + @override + String get cargoDetails => 'Detalles de carga'; + @override + String get itemName => 'Descripción'; + @override + String get itemNumber => 'Nº de posición'; + @override + String get item => 'Posición'; + @override + String get weightUnit => 'kg'; + @override + String get dimensionUnit => 'cm'; + @override + String get noCargoItems => 'Sin artículos de carga'; + @override + String get noCargoItemsMessage => 'No hay artículos de carga definidos para este trabajo.'; + @override + String get article => 'Artículo'; + + // ==================== TASK TYPES ==================== + @override + String get takePhotos => 'Tomar fotos'; + @override + String get photosCount => 'Fotos'; + @override + String get checklistPoints => 'Puntos'; + @override + String get signatureRequiredText => 'Firma requerida'; + @override + String get scanBarcodes => 'Escanear códigos'; + @override + String get barcodeCount => 'Códigos'; + @override + String get commentOptional => 'Comentario'; + @override + String get genericTask => 'Tarea genérica'; + @override + String get complete => 'Completar'; + @override + String get abort => 'Cancelar'; + @override + String get optional => 'Opcional'; + @override + String get skipTask => 'Omitir'; + + // ==================== SETTINGS ==================== + @override + String get language => 'Idioma'; + @override + String get languageChanged => 'Idioma cambiado a'; + @override + String get appInfo => 'INFO DE LA APP'; + + // ==================== STATUS ==================== + @override + String get statusCreated => 'Creado'; + @override + String get statusAssigned => 'Asignado'; + @override + String get statusInProgress => 'En progreso'; + @override + String get statusCompleted => 'Completado'; + @override + String get priorityLow => 'Baja'; + @override + String get priorityMedium => 'Media'; + @override + String get priorityHigh => 'Alta'; + @override + String get priorityUrgent => 'Urgente'; +} diff --git a/app/lib/l10n/app_localizations_et.dart b/app/lib/l10n/app_localizations_et.dart new file mode 100644 index 0000000..380c585 --- /dev/null +++ b/app/lib/l10n/app_localizations_et.dart @@ -0,0 +1,385 @@ +import 'app_localizations.dart'; + +class AppLocalizationsEt extends AppLocalizations { + @override + String get languageName => 'Eesti'; + + @override + String get flagEmoji => '🇪🇪'; + + // ==================== GENERAL ==================== + @override + String get appTitle => 'VotianLT App'; + @override + String get ok => 'OK'; + @override + String get cancel => 'Tühista'; + @override + String get save => 'Salvesta'; + @override + String get delete => 'Kustuta'; + @override + String get close => 'Sulge'; + @override + String get confirm => 'Kinnita'; + @override + String get error => 'Viga'; + @override + String get success => 'Edu'; + @override + String get loading => 'Laadimine...'; + @override + String get refresh => 'Värskenda'; + @override + String get version => 'Versioon'; + @override + String get unknown => 'Tundmatu'; + + // ==================== NAVIGATION ==================== + @override + String get jobs => 'Tööd'; + @override + String get availableJobs => 'Saadaolevad tööd'; + @override + String get chats => 'Vestlused'; + @override + String get settings => 'Seaded'; + @override + String get logout => 'Logi välja'; + @override + String get logoutConfirm => 'Logi välja'; + @override + String get logoutConfirmMessage => 'Kas soovite tõesti välja logida?'; + @override + String get openChat => 'Ava vestlus'; + @override + String get chatInfo => 'Vestluse info'; + @override + String get routePlan => 'Kavanda marsruut'; + + // ==================== LOGIN ==================== + @override + String get welcomeBack => 'Tere tulemast tagasi'; + @override + String get loginSubtitle => 'Logige oma kontosse sisse'; + @override + String get email => 'E-post'; + @override + String get password => 'Parool'; + @override + String get login => 'Logi sisse'; + @override + String get loggingIn => 'Ühendamine...'; + @override + String get forgotPassword => 'Unustasid parooli?'; + @override + String get forgotPasswordMessage => 'Unustatud parooli funktsioon pole veel rakendatud'; + @override + String get loginSuccess => 'Edukalt välja logitud'; + @override + String get loginFailed => 'Sisselogimine ebaõnnestus'; + @override + String get connectionFailed => 'Serveriga ühenduse loomine ebaõnnestus (Aegunud).'; + @override + String get connectionTimeout => 'Serveriga ühenduse loomine ebaõnnestus (Aegunud).'; + @override + String get connecting => 'Serveriga ühendamine...'; + @override + String get connectionError => 'Ühenduse viga'; + @override + String get loginError => 'Viga sisselogimisel'; + + // ==================== JOBS ==================== + @override + String get noJobsAssigned => 'Ülesandeid pole määratud'; + @override + String get noJobsMessage => 'Teie määratud tööd kuvatakse siin.'; + @override + String get pullToRefresh => 'Värskendamiseks tõmmake alla'; + @override + String get newLabel => 'UUS'; + @override + String get tasksToComplete => 'Täitmiseks ülesanded'; + @override + String get pickup => 'Pealevõtt'; + @override + String get delivery => 'Kohaletoimetamine'; + @override + String get created => 'Loodud'; + @override + String get status => 'Olek'; + @override + String get priority => 'Prioriteet'; + @override + String get dueDate => 'Tähtaeg'; + @override + String get location => 'Asukoht'; + @override + String get description => 'Kirjeldus'; + @override + String get cargo => 'Kaup'; + @override + String get quantity => 'Kogus'; + @override + String get weight => 'Kaal'; + @override + String get dimensions => 'Mõõtmed'; + @override + String get jobDeleted => 'Töö kustutatud'; + @override + String get jobDeleteError => 'Viga töö kustutamisel'; + @override + String get jobCompleted => 'Töö lõpetatud'; + @override + String get from => 'Kust'; + @override + String get to => 'kus'; + @override + String get jobsUpdated => 'Tööd värskendatud'; + @override + String get connectionRestored => 'Ühendus taastatud. Tööde laadimine...'; + @override + String get connectionLost => 'Ühendus kaotatud. Võrguühenduseta.'; + @override + String get offline => 'Võrguühenduseta'; + @override + String get deleteJob => 'Kustuta töö'; + @override + String get jobRemoved => 'eemaldati'; + @override + String get newJobReceived => 'Uus töö saadud'; + + // ==================== TASKS ==================== + @override + String get tasks => 'Ülesanded'; + @override + String get noTasks => 'Ülesandeid pole'; + @override + String get noTasksMessage => 'Selle töö jaoks pole ülesandeid määratud.'; + @override + String get taskOrder => 'Järjekord'; + @override + String get confirmationRequired => 'Vajalik kinnitus'; + @override + String get confirmationDescription => 'Ülesande lõpuleviimiseks klõpsake nuppu.'; + @override + String get checklist => 'Kontrollnimekiri'; + @override + String get checklistDescription => 'Palun märkige kõik punktid:'; + @override + String get completeTask => 'Lõpeta ülesanne'; + @override + String get completeTaskConfirm => 'Kas soovite selle ülesande lõpetatuks märgistada?'; + @override + String get completeTaskNote => 'Märkus (valikuline)'; + @override + String get taskCompleted => 'Ülesanne lõpetatud'; + @override + String get comment => 'Kommentaar'; + @override + String get commentRequired => 'Kommentaar (nõutav)'; + @override + String get enterComment => 'Sisesta kommentaar'; + @override + String get commentDescription => 'Palun sisestage kommentaar:'; + @override + String get finish => 'Lõpeta'; + @override + String get signature => 'Allkiri'; + @override + String get signatureCapture => 'Salvesta allkiri'; + @override + String get signatureRequired => 'Palun salvestage allkiri.'; + @override + String get clear => 'Tühjenda'; + @override + String get signatureError => 'Viga allkirja salvestamisel'; + @override + String get signatureInstruction => 'Palun allkirjastage allolevas väljas (hiir või sõrm).'; + @override + String get photoCapture => 'Tee pilte'; + @override + String get requiredPhotos => 'Vajalikud fotod'; + @override + String get photosTaken => 'Tehtud'; + @override + String get photos => 'Fotod'; + @override + String get takePhoto => 'Tee foto'; + @override + String get selectFromLibrary => 'Vali galeriist'; + @override + String get retakePhoto => 'Pildista uuesti'; + @override + String get photoRequired => 'Foto nõutav'; + @override + String get minPhotos => 'Vähemalt'; + @override + String get maxPhotos => 'Maksimum'; + @override + String get photoError => 'Viga foto tegemisel'; + @override + String get deletePhoto => 'Kustuta foto'; + @override + String get deletePhotoConfirm => 'Kas soovite tõesti selle foto kustutada?'; + @override + String get barcode => 'Vöötkood'; + @override + String get barcodeScan => 'Skaneeri vöötkood'; + @override + String get scanBarcode => 'Skaneeri vöötkood'; + @override + String get barcodeRequired => 'Vöötkood nõutav'; + @override + String get minBarcodes => 'Vähemalt'; + @override + String get maxBarcodes => 'Maksimum'; + @override + String get scanned => 'Skaneeritud'; + @override + String get scannedBarcodes => 'Skaneeritud vöötkoodid'; + @override + String get barcodesRequired => 'Vöötkoodid nõutavad'; + @override + String get enterBarcode => 'Sisesta vöötkood'; + @override + String get barcodeEnterDescription => 'Palun sisestage vöötkoodid:'; + @override + String barcodeNumberRequired(int number) => 'Vöötkood $number (nõutav)'; + @override + String barcodeNumberOptional(int number) => 'Vöötkood $number (valikuline)'; + @override + String get barcodeError => 'Viga vöötkoodi skaneerimisel'; + @override + String get cameraError => 'Viga kaamera käivitamisel'; + @override + String get cameraNotReady => 'Kaamera pole valmis või pole saadaval'; + @override + String get cameraNotAvailable => 'Kaamera pole saadaval'; + @override + String get cameraNotSupportedMessage => 'Kaamerat ei toetata sellel platvormil.'; + @override + String get cameraNotSupportedOnPlatform => 'Sellel platvormil ei toetata'; + @override + String get maxPhotosReached => 'Maksimaalne arv saavutatud'; + @override + String get cameraReadyNoPreview => 'Kaamera valmis (eelvaade puudub)'; + @override + String get cameraLoading => 'Kaamera laadib...'; + @override + String get cameraInitializing => 'Kaamera initsialiseerimine...'; + @override + String get cameraLoadingMessage => 'Palun oodake, kuni kaamera laadib'; + @override + String get addPhotos => 'Lisa fotod'; + @override + String get addPhotosInstruction => 'Kasutage nuppu "Vali foto", et lisada pilte kaamerast või kõvakettalt.'; + @override + String get photoOf => '/'; + + // ==================== CHAT ==================== + @override + String get typeMessage => 'Sisesta sõnum...'; + @override + String get send => 'Saada'; + @override + String get noSender => 'Saatja pole saadaval'; + @override + String get noSenderMessage => 'Saatja pole saadaval. Palun logige uuesti sisse.'; + @override + String get noRecipient => 'Vastuvõtjat pole konfigureeritud'; + @override + String get noRecipientMessage => 'Selle vestluse jaoks pole vastuvõtjat konfigureeritud.'; + @override + String get messageSendError => 'Sõnumi saatmine ebaõnnestus.'; + @override + String get photoSendError => 'Foto saatmine ebaõnnestus.'; + @override + String get photoProcessError => 'Foto töötlemine ebaõnnestus.'; + @override + String get imageSendError => 'Pildi saatmine ebaõnnestus.'; + @override + String get chatTypeJob => 'Töö-spetsiifiline'; + @override + String get chatTypeGeneral => 'Üldine'; + @override + String get jobNumber => 'Töö number'; + @override + String get messages => 'Sõnumid'; + @override + String get selectPhoto => 'Vali foto'; + @override + String get unreadMessages => 'Lugemata sõnumid'; + + // ==================== CARGO ==================== + @override + String get cargoDetails => 'Kauba detailid'; + @override + String get itemName => 'Kirjeldus'; + @override + String get itemNumber => 'Positsiooni nr'; + @override + String get item => 'Positsioon'; + @override + String get weightUnit => 'kg'; + @override + String get dimensionUnit => 'cm'; + @override + String get noCargoItems => 'Kaubaosi puuduvad'; + @override + String get noCargoItemsMessage => 'Selle töö jaoks pole kaubaosi määratud.'; + @override + String get article => 'Artikkel'; + + // ==================== TASK TYPES ==================== + @override + String get takePhotos => 'Tee pilte'; + @override + String get photosCount => 'Fotod'; + @override + String get checklistPoints => 'Punktid'; + @override + String get signatureRequiredText => 'Allkiri nõutav'; + @override + String get scanBarcodes => 'Skaneeri vöötkoode'; + @override + String get barcodeCount => 'Koodid'; + @override + String get commentOptional => 'Kommentaar'; + @override + String get genericTask => 'Üldine ülesanne'; + @override + String get complete => 'Lõpeta'; + @override + String get abort => 'Tühista'; + @override + String get optional => 'Valikuline'; + @override + String get skipTask => 'Vahele jätta'; + + // ==================== SETTINGS ==================== + @override + String get language => 'Keel'; + @override + String get languageChanged => 'Keel muudetud:'; + @override + String get appInfo => 'RAKENDUSE INFO'; + + // ==================== STATUS ==================== + @override + String get statusCreated => 'Loodud'; + @override + String get statusAssigned => 'Määratud'; + @override + String get statusInProgress => 'Töös'; + @override + String get statusCompleted => 'Lõpetatud'; + @override + String get priorityLow => 'Madal'; + @override + String get priorityMedium => 'Keskmine'; + @override + String get priorityHigh => 'Kõrge'; + @override + String get priorityUrgent => 'Kiire'; +} diff --git a/app/lib/l10n/app_localizations_fr.dart b/app/lib/l10n/app_localizations_fr.dart new file mode 100644 index 0000000..8d035fe --- /dev/null +++ b/app/lib/l10n/app_localizations_fr.dart @@ -0,0 +1,385 @@ +import 'app_localizations.dart'; + +class AppLocalizationsFr extends AppLocalizations { + @override + String get languageName => 'Français'; + + @override + String get flagEmoji => '🇫🇷'; + + // ==================== GENERAL ==================== + @override + String get appTitle => 'VotianLT App'; + @override + String get ok => 'OK'; + @override + String get cancel => 'Annuler'; + @override + String get save => 'Enregistrer'; + @override + String get delete => 'Supprimer'; + @override + String get close => 'Fermer'; + @override + String get confirm => 'Confirmer'; + @override + String get error => 'Erreur'; + @override + String get success => 'Succès'; + @override + String get loading => 'Chargement...'; + @override + String get refresh => 'Actualiser'; + @override + String get version => 'Version'; + @override + String get unknown => 'Inconnu'; + + // ==================== NAVIGATION ==================== + @override + String get jobs => 'Emplois'; + @override + String get availableJobs => 'Emplois Disponibles'; + @override + String get chats => 'Discussions'; + @override + String get settings => 'Paramètres'; + @override + String get logout => 'Déconnexion'; + @override + String get logoutConfirm => 'Déconnexion'; + @override + String get logoutConfirmMessage => 'Voulez-vous vraiment vous déconnecter?'; + @override + String get openChat => 'Ouvrir la discussion'; + @override + String get chatInfo => 'Info discussion'; + @override + String get routePlan => 'Planifier l\'itinéraire'; + + // ==================== LOGIN ==================== + @override + String get welcomeBack => 'Bon retour'; + @override + String get loginSubtitle => 'Connectez-vous à votre compte'; + @override + String get email => 'E-mail'; + @override + String get password => 'Mot de passe'; + @override + String get login => 'Connexion'; + @override + String get loggingIn => 'Connexion...'; + @override + String get forgotPassword => 'Mot de passe oublié?'; + @override + String get forgotPasswordMessage => 'Fonction mot de passe oublié pas encore implémentée'; + @override + String get loginSuccess => 'Déconnexion réussie'; + @override + String get loginFailed => 'Échec de la connexion'; + @override + String get connectionFailed => 'Échec de la connexion au serveur (Délai dépassé).'; + @override + String get connectionTimeout => 'Échec de la connexion au serveur (Délai dépassé).'; + @override + String get connecting => 'Connexion au serveur...'; + @override + String get connectionError => 'Erreur de connexion'; + @override + String get loginError => 'Erreur lors de la connexion'; + + // ==================== JOBS ==================== + @override + String get noJobsAssigned => 'Aucun emploi assigné'; + @override + String get noJobsMessage => 'Vos emplois assignés seront affichés ici.'; + @override + String get pullToRefresh => 'Tirez vers le bas pour actualiser'; + @override + String get newLabel => 'NOUVEAU'; + @override + String get tasksToComplete => 'Tâches à accomplir'; + @override + String get pickup => 'Ramassage'; + @override + String get delivery => 'Livraison'; + @override + String get created => 'Créé'; + @override + String get status => 'Statut'; + @override + String get priority => 'Priorité'; + @override + String get dueDate => 'Date d\'échéance'; + @override + String get location => 'Lieu'; + @override + String get description => 'Description'; + @override + String get cargo => 'Cargaison'; + @override + String get quantity => 'Quantité'; + @override + String get weight => 'Poids'; + @override + String get dimensions => 'Dimensions'; + @override + String get jobDeleted => 'Emploi supprimé'; + @override + String get jobDeleteError => 'Erreur lors de la suppression de l\'emploi'; + @override + String get jobCompleted => 'Emploi terminé'; + @override + String get from => 'De'; + @override + String get to => 'à'; + @override + String get jobsUpdated => 'Emplois actualisés'; + @override + String get connectionRestored => 'Connexion restaurée. Chargement des emplois...'; + @override + String get connectionLost => 'Connexion perdue. Hors ligne.'; + @override + String get offline => 'Hors ligne'; + @override + String get deleteJob => 'Supprimer l\'emploi'; + @override + String get jobRemoved => 'a été supprimé'; + @override + String get newJobReceived => 'Nouvel emploi reçu'; + + // ==================== TASKS ==================== + @override + String get tasks => 'Tâches'; + @override + String get noTasks => 'Aucune tâche'; + @override + String get noTasksMessage => 'Aucune tâche définie pour cet emploi.'; + @override + String get taskOrder => 'Ordre'; + @override + String get confirmationRequired => 'Confirmation requise'; + @override + String get confirmationDescription => 'Cliquez sur le bouton pour terminer la tâche.'; + @override + String get checklist => 'Liste de contrôle'; + @override + String get checklistDescription => 'Veuillez cocher tous les éléments:'; + @override + String get completeTask => 'Terminer la tâche'; + @override + String get completeTaskConfirm => 'Voulez-vous marquer cette tâche comme terminée?'; + @override + String get completeTaskNote => 'Note (optionnelle)'; + @override + String get taskCompleted => 'Tâche terminée'; + @override + String get comment => 'Commentaire'; + @override + String get commentRequired => 'Commentaire (requis)'; + @override + String get enterComment => 'Saisir un commentaire'; + @override + String get commentDescription => 'Veuillez saisir un commentaire:'; + @override + String get finish => 'Terminer'; + @override + String get signature => 'Signature'; + @override + String get signatureCapture => 'Capturer la signature'; + @override + String get signatureRequired => 'Veuillez capturer une signature.'; + @override + String get clear => 'Effacer'; + @override + String get signatureError => 'Erreur lors de l\'enregistrement de la signature'; + @override + String get signatureInstruction => 'Veuillez signer dans le champ ci-dessous (souris ou doigt).'; + @override + String get photoCapture => 'Prendre des photos'; + @override + String get requiredPhotos => 'Photos requises'; + @override + String get photosTaken => 'Prises'; + @override + String get photos => 'Photos'; + @override + String get takePhoto => 'Prendre une photo'; + @override + String get selectFromLibrary => 'Sélectionner depuis la bibliothèque'; + @override + String get retakePhoto => 'Reprendre'; + @override + String get photoRequired => 'Photo requise'; + @override + String get minPhotos => 'Au moins'; + @override + String get maxPhotos => 'Maximum'; + @override + String get photoError => 'Erreur lors de la prise de photo'; + @override + String get deletePhoto => 'Supprimer la photo'; + @override + String get deletePhotoConfirm => 'Voulez-vous vraiment supprimer cette photo?'; + @override + String get barcode => 'Code-barres'; + @override + String get barcodeScan => 'Scanner le code-barres'; + @override + String get scanBarcode => 'Scanner le code-barres'; + @override + String get barcodeRequired => 'Code-barres requis'; + @override + String get minBarcodes => 'Au moins'; + @override + String get maxBarcodes => 'Maximum'; + @override + String get scanned => 'Scanné'; + @override + String get scannedBarcodes => 'Codes-barres scannés'; + @override + String get barcodesRequired => 'Codes-barres requis'; + @override + String get enterBarcode => 'Entrer le code-barres'; + @override + String get barcodeEnterDescription => 'Veuillez entrer les codes-barres:'; + @override + String barcodeNumberRequired(int number) => 'Code-barres $number (requis)'; + @override + String barcodeNumberOptional(int number) => 'Code-barres $number (optionnel)'; + @override + String get barcodeError => 'Erreur lors du scan du code-barres'; + @override + String get cameraError => 'Erreur lors de l\'initialisation de la caméra'; + @override + String get cameraNotReady => 'La caméra n\'est pas prête ou non disponible'; + @override + String get cameraNotAvailable => 'Caméra non disponible'; + @override + String get cameraNotSupportedMessage => 'La caméra n\'est pas prise en charge sur cette plateforme.'; + @override + String get cameraNotSupportedOnPlatform => 'Non supporté sur cette plateforme'; + @override + String get maxPhotosReached => 'Maximum atteint'; + @override + String get cameraReadyNoPreview => 'Caméra prête (sans aperçu)'; + @override + String get cameraLoading => 'Chargement de la caméra...'; + @override + String get cameraInitializing => 'Initialisation de la caméra...'; + @override + String get cameraLoadingMessage => 'Veuillez patienter pendant le chargement de la caméra'; + @override + String get addPhotos => 'Ajouter des photos'; + @override + String get addPhotosInstruction => 'Utilisez le bouton "Sélectionner une photo" pour ajouter des images depuis votre appareil photo ou disque dur.'; + @override + String get photoOf => 'sur'; + + // ==================== CHAT ==================== + @override + String get typeMessage => 'Tapez un message...'; + @override + String get send => 'Envoyer'; + @override + String get noSender => 'Aucun expéditeur disponible'; + @override + String get noSenderMessage => 'Aucun expéditeur disponible. Veuillez vous reconnecter.'; + @override + String get noRecipient => 'Aucun destinataire configuré'; + @override + String get noRecipientMessage => 'Aucun destinataire configuré pour cette discussion.'; + @override + String get messageSendError => 'Le message n\'a pas pu être envoyé.'; + @override + String get photoSendError => 'La photo n\'a pas pu être envoyée.'; + @override + String get photoProcessError => 'La photo n\'a pas pu être traitée.'; + @override + String get imageSendError => 'L\'image n\'a pas pu être envoyée.'; + @override + String get chatTypeJob => 'Spécifique à l\'emploi'; + @override + String get chatTypeGeneral => 'Général'; + @override + String get jobNumber => 'Numéro d\'emploi'; + @override + String get messages => 'Messages'; + @override + String get selectPhoto => 'Sélectionner une photo'; + @override + String get unreadMessages => 'Messages non lus'; + + // ==================== CARGO ==================== + @override + String get cargoDetails => 'Détails de cargaison'; + @override + String get itemName => 'Description'; + @override + String get itemNumber => 'N° de position'; + @override + String get item => 'Position'; + @override + String get weightUnit => 'kg'; + @override + String get dimensionUnit => 'cm'; + @override + String get noCargoItems => 'Aucun article de cargaison'; + @override + String get noCargoItemsMessage => 'Aucun article de cargaison défini pour cet emploi.'; + @override + String get article => 'Article'; + + // ==================== TASK TYPES ==================== + @override + String get takePhotos => 'Prendre des photos'; + @override + String get photosCount => 'Photos'; + @override + String get checklistPoints => 'Points'; + @override + String get signatureRequiredText => 'Signature requise'; + @override + String get scanBarcodes => 'Scanner les codes-barres'; + @override + String get barcodeCount => 'Codes'; + @override + String get commentOptional => 'Commentaire'; + @override + String get genericTask => 'Tâche générique'; + @override + String get complete => 'Terminer'; + @override + String get abort => 'Annuler'; + @override + String get optional => 'Facultatif'; + @override + String get skipTask => 'Ignorer'; + + // ==================== SETTINGS ==================== + @override + String get language => 'Langue'; + @override + String get languageChanged => 'Langue changée en'; + @override + String get appInfo => 'INFO APP'; + + // ==================== STATUS ==================== + @override + String get statusCreated => 'Créé'; + @override + String get statusAssigned => 'Assigné'; + @override + String get statusInProgress => 'En cours'; + @override + String get statusCompleted => 'Terminé'; + @override + String get priorityLow => 'Basse'; + @override + String get priorityMedium => 'Moyenne'; + @override + String get priorityHigh => 'Haute'; + @override + String get priorityUrgent => 'Urgente'; +} diff --git a/app/lib/l10n/app_localizations_lt.dart b/app/lib/l10n/app_localizations_lt.dart new file mode 100644 index 0000000..61397b2 --- /dev/null +++ b/app/lib/l10n/app_localizations_lt.dart @@ -0,0 +1,385 @@ +import 'app_localizations.dart'; + +class AppLocalizationsLt extends AppLocalizations { + @override + String get languageName => 'Lietuvių'; + + @override + String get flagEmoji => '🇱🇹'; + + // ==================== GENERAL ==================== + @override + String get appTitle => 'VotianLT App'; + @override + String get ok => 'Gerai'; + @override + String get cancel => 'Atšaukti'; + @override + String get save => 'Išsaugoti'; + @override + String get delete => 'Ištrinti'; + @override + String get close => 'Uždaryti'; + @override + String get confirm => 'Patvirtinti'; + @override + String get error => 'Klaida'; + @override + String get success => 'Sėkmė'; + @override + String get loading => 'Kraunama...'; + @override + String get refresh => 'Atnaujinti'; + @override + String get version => 'Versija'; + @override + String get unknown => 'Nežinoma'; + + // ==================== NAVIGATION ==================== + @override + String get jobs => 'Darbai'; + @override + String get availableJobs => 'Galimi darbai'; + @override + String get chats => 'Pokalbiai'; + @override + String get settings => 'Nustatymai'; + @override + String get logout => 'Atsijungti'; + @override + String get logoutConfirm => 'Atsijungti'; + @override + String get logoutConfirmMessage => 'Ar tikrai norite atsijungti?'; + @override + String get openChat => 'Atidaryti pokalbį'; + @override + String get chatInfo => 'Pokalbio info'; + @override + String get routePlan => 'Planuoti maršrutą'; + + // ==================== LOGIN ==================== + @override + String get welcomeBack => 'Sveiki sugrįžę'; + @override + String get loginSubtitle => 'Prisijunkite prie savo paskyros'; + @override + String get email => 'El. paštas'; + @override + String get password => 'Slaptažodis'; + @override + String get login => 'Prisijungti'; + @override + String get loggingIn => 'Jungiamasi...'; + @override + String get forgotPassword => 'Pamiršote slaptažodį?'; + @override + String get forgotPasswordMessage => 'Pamiršto slaptažodžio funkcija dar neįdiegta'; + @override + String get loginSuccess => 'Sėkmingai atsijungta'; + @override + String get loginFailed => 'Prisijungimas nepavyko'; + @override + String get connectionFailed => 'Nepavyko prisijungti prie serverio (Laikas baigėsi).'; + @override + String get connectionTimeout => 'Nepavyko prisijungti prie serverio (Laikas baigėsi).'; + @override + String get connecting => 'Jungiamasi prie serverio...'; + @override + String get connectionError => 'Ryšio klaida'; + @override + String get loginError => 'Klaida prisijungiant'; + + // ==================== JOBS ==================== + @override + String get noJobsAssigned => 'Nėra priskirtų darbų'; + @override + String get noJobsMessage => 'Jūsų priskirti darbai bus rodomi čia.'; + @override + String get pullToRefresh => 'Patraukite žemyn, kad atnaujintumėte'; + @override + String get newLabel => 'NAUJAS'; + @override + String get tasksToComplete => 'Užduotys, kurias reikia atlikti'; + @override + String get pickup => 'Paėmimas'; + @override + String get delivery => 'Pristatymas'; + @override + String get created => 'Sukurta'; + @override + String get status => 'Būsena'; + @override + String get priority => 'Prioritetas'; + @override + String get dueDate => 'Terminas'; + @override + String get location => 'Vieta'; + @override + String get description => 'Aprašymas'; + @override + String get cargo => 'Krovinys'; + @override + String get quantity => 'Kiekis'; + @override + String get weight => 'Svoris'; + @override + String get dimensions => 'Matmenys'; + @override + String get jobDeleted => 'Darbas ištrintas'; + @override + String get jobDeleteError => 'Klaida ištrinant darbą'; + @override + String get jobCompleted => 'Darbas baigtas'; + @override + String get from => 'Iš'; + @override + String get to => 'į'; + @override + String get jobsUpdated => 'Darbai atnaujinti'; + @override + String get connectionRestored => 'Ryšys atkurtas. Kraunami darbai...'; + @override + String get connectionLost => 'Ryšys prarastas. Neprisijungta.'; + @override + String get offline => 'Neprisijungta'; + @override + String get deleteJob => 'Ištrinti darbą'; + @override + String get jobRemoved => 'buvo pašalintas'; + @override + String get newJobReceived => 'Gautas naujas darbas'; + + // ==================== TASKS ==================== + @override + String get tasks => 'Užduotys'; + @override + String get noTasks => 'Nėra užduočių'; + @override + String get noTasksMessage => 'Šiam darbui nėra apibrėžtų užduočių.'; + @override + String get taskOrder => 'Eilės tvarka'; + @override + String get confirmationRequired => 'Reikalingas patvirtinimas'; + @override + String get confirmationDescription => 'Spustelėkite mygtuką, kad atliktumėte užduotį.'; + @override + String get checklist => 'Patikros sąrašas'; + @override + String get checklistDescription => 'Prašome pažymėti visus punktus:'; + @override + String get completeTask => 'Baigti užduotį'; + @override + String get completeTaskConfirm => 'Ar norite pažymėti šią užduotį kaip baigtą?'; + @override + String get completeTaskNote => 'Pastaba (neprivaloma)'; + @override + String get taskCompleted => 'Užduotis baigta'; + @override + String get comment => 'Komentaras'; + @override + String get commentRequired => 'Komentaras (būtinas)'; + @override + String get enterComment => 'Įveskite komentarą'; + @override + String get commentDescription => 'Prašome įvesti komentarą:'; + @override + String get finish => 'Baigti'; + @override + String get signature => 'Parašas'; + @override + String get signatureCapture => 'Įrašyti parašą'; + @override + String get signatureRequired => 'Prašome įrašyti parašą.'; + @override + String get clear => 'Išvalyti'; + @override + String get signatureError => 'Klaida išsaugant parašą'; + @override + String get signatureInstruction => 'Prašome pasirašyti laukelyje žemiau (pele arba pirštu).'; + @override + String get photoCapture => 'Daryti nuotraukas'; + @override + String get requiredPhotos => 'Reikalingos nuotraukos'; + @override + String get photosTaken => 'Padaryta'; + @override + String get photos => 'Nuotraukos'; + @override + String get takePhoto => 'Daryti nuotrauką'; + @override + String get selectFromLibrary => 'Pasirinkti iš bibliotekos'; + @override + String get retakePhoto => 'Perdaryti'; + @override + String get photoRequired => 'Reikalinga nuotrauka'; + @override + String get minPhotos => 'Mažiausiai'; + @override + String get maxPhotos => 'Daugiausia'; + @override + String get photoError => 'Klaida darant nuotrauką'; + @override + String get deletePhoto => 'Ištrinti nuotrauką'; + @override + String get deletePhotoConfirm => 'Ar tikrai norite ištrinti šią nuotrauką?'; + @override + String get barcode => 'Brūkšninis kodas'; + @override + String get barcodeScan => 'Skaityti brūkšninį kodą'; + @override + String get scanBarcode => 'Skaityti brūkšninį kodą'; + @override + String get barcodeRequired => 'Reikalingas brūkšninis kodas'; + @override + String get minBarcodes => 'Mažiausiai'; + @override + String get maxBarcodes => 'Daugiausia'; + @override + String get scanned => 'Nuskaityta'; + @override + String get scannedBarcodes => 'Nuskaityti brūkšniniai kodai'; + @override + String get barcodesRequired => 'Reikalingi brūkšniniai kodai'; + @override + String get enterBarcode => 'Įveskite brūkšninį kodą'; + @override + String get barcodeEnterDescription => 'Prašome įvesti brūkšninius kodus:'; + @override + String barcodeNumberRequired(int number) => 'Brūkšninis kodas $number (būtinas)'; + @override + String barcodeNumberOptional(int number) => 'Brūkšninis kodas $number (neprivalomas)'; + @override + String get barcodeError => 'Klaida skaitant brūkšninį kodą'; + @override + String get cameraError => 'Klaida inicializuojant kamerą'; + @override + String get cameraNotReady => 'Kamera nėra pasiruošusi arba nepasiekiama'; + @override + String get cameraNotAvailable => 'Kamera nepasiekiama'; + @override + String get cameraNotSupportedMessage => 'Šioje platformoje kamera nepalaikoma.'; + @override + String get cameraNotSupportedOnPlatform => 'Nepalaikoma šioje platformoje'; + @override + String get maxPhotosReached => 'Pasiektas maksimumas'; + @override + String get cameraReadyNoPreview => 'Kamera paruošta (be peržiūros)'; + @override + String get cameraLoading => 'Kamera kraunama...'; + @override + String get cameraInitializing => 'Kamera inicializuojama...'; + @override + String get cameraLoadingMessage => 'Palaukite, kol kamera įkraunama'; + @override + String get addPhotos => 'Pridėti nuotraukas'; + @override + String get addPhotosInstruction => 'Naudokite mygtuką "Pasirinkti nuotrauką", norėdami pridėti vaizdų iš fotoaparato ar standžiojo disko.'; + @override + String get photoOf => 'iš'; + + // ==================== CHAT ==================== + @override + String get typeMessage => 'Įveskite žinutę...'; + @override + String get send => 'Siųsti'; + @override + String get noSender => 'Siuntėjas nepasiekiamas'; + @override + String get noSenderMessage => 'Siuntėjas nepasiekiamas. Prašome prisijungti dar kartą.'; + @override + String get noRecipient => 'Gavėjas nesukonfigūruotas'; + @override + String get noRecipientMessage => 'Šiam pokalbiui nesukonfigūruotas gavėjas.'; + @override + String get messageSendError => 'Žinutės išsiųsti nepavyko.'; + @override + String get photoSendError => 'Nuotraukos išsiųsti nepavyko.'; + @override + String get photoProcessError => 'Nuotraukos apdoroti nepavyko.'; + @override + String get imageSendError => 'Vaizdo išsiųsti nepavyko.'; + @override + String get chatTypeJob => 'Specifinis darbui'; + @override + String get chatTypeGeneral => 'Bendras'; + @override + String get jobNumber => 'Darbo numeris'; + @override + String get messages => 'Žinutės'; + @override + String get selectPhoto => 'Pasirinkti nuotrauką'; + @override + String get unreadMessages => 'Neskaitytos žinutės'; + + // ==================== CARGO ==================== + @override + String get cargoDetails => 'Krovinio detalės'; + @override + String get itemName => 'Aprašymas'; + @override + String get itemNumber => 'Pozicijos Nr.'; + @override + String get item => 'Pozicija'; + @override + String get weightUnit => 'kg'; + @override + String get dimensionUnit => 'cm'; + @override + String get noCargoItems => 'Nėra krovinių pozicijų'; + @override + String get noCargoItemsMessage => 'Šiam darbui nėra apibrėžtų krovinių pozicijų.'; + @override + String get article => 'Pozicija'; + + // ==================== TASK TYPES ==================== + @override + String get takePhotos => 'Daryti nuotraukas'; + @override + String get photosCount => 'Nuotraukos'; + @override + String get checklistPoints => 'Taškai'; + @override + String get signatureRequiredText => 'Parašas būtinas'; + @override + String get scanBarcodes => 'Skaityti brūkšninius kodus'; + @override + String get barcodeCount => 'Kodai'; + @override + String get commentOptional => 'Komentaras'; + @override + String get genericTask => 'Bendra užduotis'; + @override + String get complete => 'Baigti'; + @override + String get abort => 'Atšaukti'; + @override + String get optional => 'Neprivaloma'; + @override + String get skipTask => 'Praleisti'; + + // ==================== SETTINGS ==================== + @override + String get language => 'Kalba'; + @override + String get languageChanged => 'Kalba pakeista į'; + @override + String get appInfo => 'PROGRAMĖLĖS INFO'; + + // ==================== STATUS ==================== + @override + String get statusCreated => 'Sukurta'; + @override + String get statusAssigned => 'Priskirta'; + @override + String get statusInProgress => 'Vykdoma'; + @override + String get statusCompleted => 'Baigta'; + @override + String get priorityLow => 'Žemas'; + @override + String get priorityMedium => 'Vidutinis'; + @override + String get priorityHigh => 'Aukštas'; + @override + String get priorityUrgent => 'Skubus'; +} diff --git a/app/lib/l10n/app_localizations_lv.dart b/app/lib/l10n/app_localizations_lv.dart new file mode 100644 index 0000000..06426e9 --- /dev/null +++ b/app/lib/l10n/app_localizations_lv.dart @@ -0,0 +1,385 @@ +import 'app_localizations.dart'; + +class AppLocalizationsLv extends AppLocalizations { + @override + String get languageName => 'Latviešu'; + + @override + String get flagEmoji => '🇱🇻'; + + // ==================== GENERAL ==================== + @override + String get appTitle => 'VotianLT App'; + @override + String get ok => 'Labi'; + @override + String get cancel => 'Atcelt'; + @override + String get save => 'Saglabāt'; + @override + String get delete => 'Dzēst'; + @override + String get close => 'Aizvērt'; + @override + String get confirm => 'Apstiprināt'; + @override + String get error => 'Kļūda'; + @override + String get success => 'Veiksmīgi'; + @override + String get loading => 'Ielādē...'; + @override + String get refresh => 'Atsvaidzināt'; + @override + String get version => 'Versija'; + @override + String get unknown => 'Nezināms'; + + // ==================== NAVIGATION ==================== + @override + String get jobs => 'Darbi'; + @override + String get availableJobs => 'Pieejamie darbi'; + @override + String get chats => 'Tērzēšanas'; + @override + String get settings => 'Iestatījumi'; + @override + String get logout => 'Iziet'; + @override + String get logoutConfirm => 'Iziet'; + @override + String get logoutConfirmMessage => 'Vai tiešām vēlaties iziet?'; + @override + String get openChat => 'Atvērt tērzēšanu'; + @override + String get chatInfo => 'Tērzēšanas info'; + @override + String get routePlan => 'Plānot maršrutu'; + + // ==================== LOGIN ==================== + @override + String get welcomeBack => 'Laipni lūgti atpakaļ'; + @override + String get loginSubtitle => 'Pierakstieties savā kontā'; + @override + String get email => 'E-pasts'; + @override + String get password => 'Parole'; + @override + String get login => 'Pierakstīties'; + @override + String get loggingIn => 'Savienojas...'; + @override + String get forgotPassword => 'Aizmirsāt paroli?'; + @override + String get forgotPasswordMessage => 'Aizmirstās paroles funkcija vēl nav ieviesta'; + @override + String get loginSuccess => 'Veiksmīgi izrakstījās'; + @override + String get loginFailed => 'Pierakstīšanās neizdevās'; + @override + String get connectionFailed => 'Savienojuma kļūda ar serveri (Noildze).'; + @override + String get connectionTimeout => 'Savienojuma kļūda ar serveri (Noildze).'; + @override + String get connecting => 'Savienojas ar serveri...'; + @override + String get connectionError => 'Savienojuma kļūda'; + @override + String get loginError => 'Kļūda pierakstīšanās laikā'; + + // ==================== JOBS ==================== + @override + String get noJobsAssigned => 'Nav piešķirtu darbu'; + @override + String get noJobsMessage => 'Jūsu piešķirtie darbi tiks parādīti šeit.'; + @override + String get pullToRefresh => 'Velciet uz leju, lai atsvaidzinātu'; + @override + String get newLabel => 'JAUNS'; + @override + String get tasksToComplete => 'Uzdevumi, kas jāveic'; + @override + String get pickup => 'Saņemšana'; + @override + String get delivery => 'Piegāde'; + @override + String get created => 'Izveidots'; + @override + String get status => 'Statuss'; + @override + String get priority => 'Prioritāte'; + @override + String get dueDate => 'Izpildes termiņš'; + @override + String get location => 'Atrašanās vieta'; + @override + String get description => 'Apraksts'; + @override + String get cargo => 'Krava'; + @override + String get quantity => 'Daudzums'; + @override + String get weight => 'Svars'; + @override + String get dimensions => 'Izmēri'; + @override + String get jobDeleted => 'Darbs izdzēsts'; + @override + String get jobDeleteError => 'Kļūda dzēšot darbu'; + @override + String get jobCompleted => 'Darbs pabeigts'; + @override + String get from => 'No'; + @override + String get to => 'uz'; + @override + String get jobsUpdated => 'Darbi atsvaidzināti'; + @override + String get connectionRestored => 'Savienojums atjaunots. Ielādē darbus...'; + @override + String get connectionLost => 'Savienojums pazaudēts. Bezsaistē.'; + @override + String get offline => 'Bezsaistē'; + @override + String get deleteJob => 'Dzēst darbu'; + @override + String get jobRemoved => 'tika noņemts'; + @override + String get newJobReceived => 'Saņemts jauns darbs'; + + // ==================== TASKS ==================== + @override + String get tasks => 'Uzdevumi'; + @override + String get noTasks => 'Nav uzdevumu'; + @override + String get noTasksMessage => 'Šim darbam nav definētu uzdevumu.'; + @override + String get taskOrder => 'Secība'; + @override + String get confirmationRequired => 'Nepieciešams apstiprinājums'; + @override + String get confirmationDescription => 'Noklikšķiniet uz pogas, lai pabeigtu uzdevumu.'; + @override + String get checklist => 'Pārbaudes saraksts'; + @override + String get checklistDescription => 'Lūdzu, atzīmējiet visus punktus:'; + @override + String get completeTask => 'Pabeigt uzdevumu'; + @override + String get completeTaskConfirm => 'Vai vēlaties atzīmēt šo uzdevumu kā pabeigtu?'; + @override + String get completeTaskNote => 'Piezīme (neobligāta)'; + @override + String get taskCompleted => 'Uzdevums pabeigts'; + @override + String get comment => 'Komentārs'; + @override + String get commentRequired => 'Komentārs (obligāts)'; + @override + String get enterComment => 'Ievadiet komentāru'; + @override + String get commentDescription => 'Lūdzu, ievadiet komentāru:'; + @override + String get finish => 'Pabeigt'; + @override + String get signature => 'Paraksts'; + @override + String get signatureCapture => 'Uzņemt parakstu'; + @override + String get signatureRequired => 'Lūdzu, uzņemiet parakstu.'; + @override + String get clear => 'Notīrīt'; + @override + String get signatureError => 'Kļūda saglabājot parakstu'; + @override + String get signatureInstruction => 'Lūdzu parakstieties zemāk esošajā laukā (pele vai pirksts).'; + @override + String get photoCapture => 'Uzņemt fotogrāfijas'; + @override + String get requiredPhotos => 'Nepieciešamās fotogrāfijas'; + @override + String get photosTaken => 'Uzņemtas'; + @override + String get photos => 'Fotogrāfijas'; + @override + String get takePhoto => 'Uzņemt fotogrāfiju'; + @override + String get selectFromLibrary => 'Izvēlēties no bibliotēkas'; + @override + String get retakePhoto => 'Uzņemt vēlreiz'; + @override + String get photoRequired => 'Nepieciešama fotogrāfija'; + @override + String get minPhotos => 'Vismaz'; + @override + String get maxPhotos => 'Maksimums'; + @override + String get photoError => 'Kļūda uzņemot fotogrāfiju'; + @override + String get deletePhoto => 'Dzēst fotogrāfiju'; + @override + String get deletePhotoConfirm => 'Vai tiešām vēlaties dzēst šo fotogrāfiju?'; + @override + String get barcode => 'Svītrkods'; + @override + String get barcodeScan => 'Skenēt svītrkodu'; + @override + String get scanBarcode => 'Skenēt svītrkodu'; + @override + String get barcodeRequired => 'Nepieciešams svītrkods'; + @override + String get minBarcodes => 'Vismaz'; + @override + String get maxBarcodes => 'Maksimums'; + @override + String get scanned => 'Skenēts'; + @override + String get scannedBarcodes => 'Skenēti svītrkodi'; + @override + String get barcodesRequired => 'Nepieciešami svītrkodi'; + @override + String get enterBarcode => 'Ievadiet svītrkodu'; + @override + String get barcodeEnterDescription => 'Lūdzu, ievadiet svītrkodus:'; + @override + String barcodeNumberRequired(int number) => 'Svītrkods $number (obligāts)'; + @override + String barcodeNumberOptional(int number) => 'Svītrkods $number (neobligāts)'; + @override + String get barcodeError => 'Kļūda skenējot svītrkodu'; + @override + String get cameraError => 'Kļūda inicializējot kameru'; + @override + String get cameraNotReady => 'Kamera nav gatava vai nav pieejama'; + @override + String get cameraNotAvailable => 'Kamera nav pieejama'; + @override + String get cameraNotSupportedMessage => 'Šajā platformā kamera netiek atbalstīta.'; + @override + String get cameraNotSupportedOnPlatform => 'Šajā platformā netiek atbalstīts'; + @override + String get maxPhotosReached => 'Maksimums sasniegts'; + @override + String get cameraReadyNoPreview => 'Kamera gatava (bez priekšskatījuma)'; + @override + String get cameraLoading => 'Kamera ielādē...'; + @override + String get cameraInitializing => 'Kamera tiek inicializēta...'; + @override + String get cameraLoadingMessage => 'Lūdzu, uzgaidiet, kamēr kamera tiek ielādēta'; + @override + String get addPhotos => 'Pievienot fotogrāfijas'; + @override + String get addPhotosInstruction => 'Izmantojiet pogu "Izvēlēties fotogrāfiju", lai pievienotu attēlus no kameras vai cietā diska.'; + @override + String get photoOf => 'no'; + + // ==================== CHAT ==================== + @override + String get typeMessage => 'Ierakstiet ziņojumu...'; + @override + String get send => 'Sūtīt'; + @override + String get noSender => 'Sūtītājs nav pieejams'; + @override + String get noSenderMessage => 'Sūtītājs nav pieejams. Lūdzu, piesakieties vēlreiz.'; + @override + String get noRecipient => 'Saņēmējs nav konfigurēts'; + @override + String get noRecipientMessage => 'Šai tērzēšanai nav konfigurēts saņēmējs.'; + @override + String get messageSendError => 'Ziņojumu neizdevās nosūtīt.'; + @override + String get photoSendError => 'Fotogrāfiju neizdevās nosūtīt.'; + @override + String get photoProcessError => 'Fotogrāfiju neizdevās apstrādāt.'; + @override + String get imageSendError => 'Attēlu neizdevās nosūtīt.'; + @override + String get chatTypeJob => 'Darba specifisks'; + @override + String get chatTypeGeneral => 'Vispārējs'; + @override + String get jobNumber => 'Darba numurs'; + @override + String get messages => 'Ziņojumi'; + @override + String get selectPhoto => 'Izvēlēties fotogrāfiju'; + @override + String get unreadMessages => 'Nelasīti ziņojumi'; + + // ==================== CARGO ==================== + @override + String get cargoDetails => 'Kravas detaļas'; + @override + String get itemName => 'Apraksts'; + @override + String get itemNumber => 'Pozīcijas Nr.'; + @override + String get item => 'Pozīcija'; + @override + String get weightUnit => 'kg'; + @override + String get dimensionUnit => 'cm'; + @override + String get noCargoItems => 'Nav kravas pozīciju'; + @override + String get noCargoItemsMessage => 'Šim darbam nav definētu kravas pozīciju.'; + @override + String get article => 'Pozīcija'; + + // ==================== TASK TYPES ==================== + @override + String get takePhotos => 'Uzņemt fotogrāfijas'; + @override + String get photosCount => 'Fotogrāfijas'; + @override + String get checklistPoints => 'Punkti'; + @override + String get signatureRequiredText => 'Paraksts nepieciešams'; + @override + String get scanBarcodes => 'Skenēt svītrkodus'; + @override + String get barcodeCount => 'Kodi'; + @override + String get commentOptional => 'Komentārs'; + @override + String get genericTask => 'Vispārējs uzdevums'; + @override + String get complete => 'Pabeigt'; + @override + String get abort => 'Atcelt'; + @override + String get optional => 'Neobligāts'; + @override + String get skipTask => 'Izlaist'; + + // ==================== SETTINGS ==================== + @override + String get language => 'Valoda'; + @override + String get languageChanged => 'Valoda mainīta uz'; + @override + String get appInfo => 'LIETOTNES INFO'; + + // ==================== STATUS ==================== + @override + String get statusCreated => 'Izveidots'; + @override + String get statusAssigned => 'Piešķirts'; + @override + String get statusInProgress => 'Procesā'; + @override + String get statusCompleted => 'Pabeigts'; + @override + String get priorityLow => 'Zema'; + @override + String get priorityMedium => 'Vidēja'; + @override + String get priorityHigh => 'Augsta'; + @override + String get priorityUrgent => 'Steidzama'; +} diff --git a/app/lib/l10n/app_localizations_pl.dart b/app/lib/l10n/app_localizations_pl.dart new file mode 100644 index 0000000..43b7bfc --- /dev/null +++ b/app/lib/l10n/app_localizations_pl.dart @@ -0,0 +1,385 @@ +import 'app_localizations.dart'; + +class AppLocalizationsPl extends AppLocalizations { + @override + String get languageName => 'Polski'; + + @override + String get flagEmoji => '🇵🇱'; + + // ==================== GENERAL ==================== + @override + String get appTitle => 'VotianLT App'; + @override + String get ok => 'OK'; + @override + String get cancel => 'Anuluj'; + @override + String get save => 'Zapisz'; + @override + String get delete => 'Usuń'; + @override + String get close => 'Zamknij'; + @override + String get confirm => 'Potwierdź'; + @override + String get error => 'Błąd'; + @override + String get success => 'Sukces'; + @override + String get loading => 'Ładowanie...'; + @override + String get refresh => 'Odśwież'; + @override + String get version => 'Wersja'; + @override + String get unknown => 'Nieznany'; + + // ==================== NAVIGATION ==================== + @override + String get jobs => 'Zadania'; + @override + String get availableJobs => 'Dostępne Zadania'; + @override + String get chats => 'Czaty'; + @override + String get settings => 'Ustawienia'; + @override + String get logout => 'Wyloguj'; + @override + String get logoutConfirm => 'Wyloguj'; + @override + String get logoutConfirmMessage => 'Czy na pewno chcesz się wylogować?'; + @override + String get openChat => 'Otwórz czat'; + @override + String get chatInfo => 'Info o czacie'; + @override + String get routePlan => 'Planuj trasę'; + + // ==================== LOGIN ==================== + @override + String get welcomeBack => 'Witaj ponownie'; + @override + String get loginSubtitle => 'Zaloguj się do swojego konta'; + @override + String get email => 'E-mail'; + @override + String get password => 'Hasło'; + @override + String get login => 'Zaloguj'; + @override + String get loggingIn => 'Łączenie...'; + @override + String get forgotPassword => 'Zapomniałeś hasła?'; + @override + String get forgotPasswordMessage => 'Funkcja zapomnianego hasła jeszcze nie zaimplementowana'; + @override + String get loginSuccess => 'Pomyślnie wylogowano'; + @override + String get loginFailed => 'Logowanie nie powiodło się'; + @override + String get connectionFailed => 'Błąd połączenia z serwerem (Upłynął czas).'; + @override + String get connectionTimeout => 'Błąd połączenia z serwerem (Upłynął czas).'; + @override + String get connecting => 'Łączenie z serwerem...'; + @override + String get connectionError => 'Błąd połączenia'; + @override + String get loginError => 'Błąd podczas logowania'; + + // ==================== JOBS ==================== + @override + String get noJobsAssigned => 'Brak przypisanych zadań'; + @override + String get noJobsMessage => 'Twoje przypisane zadania będą wyświetlane tutaj.'; + @override + String get pullToRefresh => 'Przeciągnij w dół, aby odświeżyć'; + @override + String get newLabel => 'NOWE'; + @override + String get tasksToComplete => 'Zadania do wykonania'; + @override + String get pickup => 'Odbiór'; + @override + String get delivery => 'Dostawa'; + @override + String get created => 'Utworzono'; + @override + String get status => 'Status'; + @override + String get priority => 'Priorytet'; + @override + String get dueDate => 'Termin'; + @override + String get location => 'Lokalizacja'; + @override + String get description => 'Opis'; + @override + String get cargo => 'Ładunek'; + @override + String get quantity => 'Ilość'; + @override + String get weight => 'Waga'; + @override + String get dimensions => 'Wymiary'; + @override + String get jobDeleted => 'Zadanie usunięte'; + @override + String get jobDeleteError => 'Błąd podczas usuwania zadania'; + @override + String get jobCompleted => 'Zadanie ukończone'; + @override + String get from => 'Z'; + @override + String get to => 'do'; + @override + String get jobsUpdated => 'Zadania zaktualizowane'; + @override + String get connectionRestored => 'Połączenie przywrócone. Ładowanie zadań...'; + @override + String get connectionLost => 'Utracono połączenie. Offline.'; + @override + String get offline => 'Offline'; + @override + String get deleteJob => 'Usuń zadanie'; + @override + String get jobRemoved => 'zostało usunięte'; + @override + String get newJobReceived => 'Otrzymano nowe zadanie'; + + // ==================== TASKS ==================== + @override + String get tasks => 'Zadania'; + @override + String get noTasks => 'Brak zadań'; + @override + String get noTasksMessage => 'Brak zdefiniowanych zadań dla tego zadania.'; + @override + String get taskOrder => 'Kolejność'; + @override + String get confirmationRequired => 'Wymagane potwierdzenie'; + @override + String get confirmationDescription => 'Kliknij przycisk, aby ukończyć zadanie.'; + @override + String get checklist => 'Lista kontrolna'; + @override + String get checklistDescription => 'Proszę zaznaczyć wszystkie punkty:'; + @override + String get completeTask => 'Ukończ zadanie'; + @override + String get completeTaskConfirm => 'Czy chcesz oznaczyć to zadanie jako ukończone?'; + @override + String get completeTaskNote => 'Notatka (opcjonalnie)'; + @override + String get taskCompleted => 'Zadanie ukończone'; + @override + String get comment => 'Komentarz'; + @override + String get commentRequired => 'Komentarz (wymagany)'; + @override + String get enterComment => 'Wprowadź komentarz'; + @override + String get commentDescription => 'Proszę wprowadzić komentarz:'; + @override + String get finish => 'Zakończ'; + @override + String get signature => 'Podpis'; + @override + String get signatureCapture => 'Przechwyć podpis'; + @override + String get signatureRequired => 'Proszę przechwycić podpis.'; + @override + String get clear => 'Wyczyść'; + @override + String get signatureError => 'Błąd podczas zapisywania podpisu'; + @override + String get signatureInstruction => 'Proszę podpisać się w polu poniżej (mysz lub palec).'; + @override + String get photoCapture => 'Zrób zdjęcia'; + @override + String get requiredPhotos => 'Wymagane zdjęcia'; + @override + String get photosTaken => 'Wykonane'; + @override + String get photos => 'Zdjęcia'; + @override + String get takePhoto => 'Zrób zdjęcie'; + @override + String get selectFromLibrary => 'Wybierz z biblioteki'; + @override + String get retakePhoto => 'Ponów'; + @override + String get photoRequired => 'Zdjęcie wymagane'; + @override + String get minPhotos => 'Co najmniej'; + @override + String get maxPhotos => 'Maksimum'; + @override + String get photoError => 'Błąd podczas robienia zdjęcia'; + @override + String get deletePhoto => 'Usuń zdjęcie'; + @override + String get deletePhotoConfirm => 'Czy na pewno chcesz usunąć to zdjęcie?'; + @override + String get barcode => 'Kod kreskowy'; + @override + String get barcodeScan => 'Skanuj kod kreskowy'; + @override + String get scanBarcode => 'Skanuj kod kreskowy'; + @override + String get barcodeRequired => 'Kod kreskowy wymagany'; + @override + String get minBarcodes => 'Co najmniej'; + @override + String get maxBarcodes => 'Maksimum'; + @override + String get scanned => 'Zeskanowano'; + @override + String get scannedBarcodes => 'Zeskanowane kody kreskowe'; + @override + String get barcodesRequired => 'Wymagane kody kreskowe'; + @override + String get enterBarcode => 'Wprowadź kod kreskowy'; + @override + String get barcodeEnterDescription => 'Proszę wprowadzić kody kreskowe:'; + @override + String barcodeNumberRequired(int number) => 'Kod kreskowy $number (wymagany)'; + @override + String barcodeNumberOptional(int number) => 'Kod kreskowy $number (opcjonalny)'; + @override + String get barcodeError => 'Błąd podczas skanowania kodu kreskowego'; + @override + String get cameraError => 'Błąd podczas inicjalizacji kamery'; + @override + String get cameraNotReady => 'Kamera nie jest gotowa lub niedostępna'; + @override + String get cameraNotAvailable => 'Kamera niedostępna'; + @override + String get cameraNotSupportedMessage => 'Kamera nie jest obsługiwana na tej platformie.'; + @override + String get cameraNotSupportedOnPlatform => 'Nieobsługiwane na tej platformie'; + @override + String get maxPhotosReached => 'Maksimum osiągnięte'; + @override + String get cameraReadyNoPreview => 'Kamera gotowa (bez podglądu)'; + @override + String get cameraLoading => 'Kamera ładuje się...'; + @override + String get cameraInitializing => 'Inicjalizacja kamery...'; + @override + String get cameraLoadingMessage => 'Proszę czekać, trwa ładowanie kamery'; + @override + String get addPhotos => 'Dodaj zdjęcia'; + @override + String get addPhotosInstruction => 'Użyj przycisku "Wybierz zdjęcie", aby dodać obrazy z kamery lub dysku twardego.'; + @override + String get photoOf => 'z'; + + // ==================== CHAT ==================== + @override + String get typeMessage => 'Wpisz wiadomość...'; + @override + String get send => 'Wyślij'; + @override + String get noSender => 'Brak dostępnego nadawcy'; + @override + String get noSenderMessage => 'Brak dostępnego nadawcy. Proszę zalogować się ponownie.'; + @override + String get noRecipient => 'Brak skonfigurowanego odbiorcy'; + @override + String get noRecipientMessage => 'Brak skonfigurowanego odbiorcy dla tego czatu.'; + @override + String get messageSendError => 'Wiadomość nie mogła zostać wysłana.'; + @override + String get photoSendError => 'Zdjęcie nie mogło zostać wysłane.'; + @override + String get photoProcessError => 'Zdjęcie nie mogło zostać przetworzone.'; + @override + String get imageSendError => 'Obraz nie mógł zostać wysłany.'; + @override + String get chatTypeJob => 'Specyficzne dla zadania'; + @override + String get chatTypeGeneral => 'Ogólny'; + @override + String get jobNumber => 'Numer zadania'; + @override + String get messages => 'Wiadomości'; + @override + String get selectPhoto => 'Wybierz zdjęcie'; + @override + String get unreadMessages => 'Nieprzeczytane wiadomości'; + + // ==================== CARGO ==================== + @override + String get cargoDetails => 'Szczegóły ładunku'; + @override + String get itemName => 'Opis'; + @override + String get itemNumber => 'Nr pozycji'; + @override + String get item => 'Pozycja'; + @override + String get weightUnit => 'kg'; + @override + String get dimensionUnit => 'cm'; + @override + String get noCargoItems => 'Brak pozycji ładunku'; + @override + String get noCargoItemsMessage => 'Brak pozycji ładunku zdefiniowanych dla tego zadania.'; + @override + String get article => 'Pozycja'; + + // ==================== TASK TYPES ==================== + @override + String get takePhotos => 'Zrób zdjęcia'; + @override + String get photosCount => 'Zdjęcia'; + @override + String get checklistPoints => 'Punkty'; + @override + String get signatureRequiredText => 'Wymagany podpis'; + @override + String get scanBarcodes => 'Skanuj kody kreskowe'; + @override + String get barcodeCount => 'Kody'; + @override + String get commentOptional => 'Komentarz'; + @override + String get genericTask => 'Zadanie ogólne'; + @override + String get complete => 'Zakończ'; + @override + String get abort => 'Anuluj'; + @override + String get optional => 'Opcjonalny'; + @override + String get skipTask => 'Pomiń'; + + // ==================== SETTINGS ==================== + @override + String get language => 'Język'; + @override + String get languageChanged => 'Język zmieniony na'; + @override + String get appInfo => 'INFO O APLIKACJI'; + + // ==================== STATUS ==================== + @override + String get statusCreated => 'Utworzono'; + @override + String get statusAssigned => 'Przypisano'; + @override + String get statusInProgress => 'W trakcie'; + @override + String get statusCompleted => 'Ukończono'; + @override + String get priorityLow => 'Niski'; + @override + String get priorityMedium => 'Średni'; + @override + String get priorityHigh => 'Wysoki'; + @override + String get priorityUrgent => 'Pilny'; +} diff --git a/app/lib/l10n/app_localizations_ru.dart b/app/lib/l10n/app_localizations_ru.dart new file mode 100644 index 0000000..357f3da --- /dev/null +++ b/app/lib/l10n/app_localizations_ru.dart @@ -0,0 +1,385 @@ +import 'app_localizations.dart'; + +class AppLocalizationsRu extends AppLocalizations { + @override + String get languageName => 'Русский'; + + @override + String get flagEmoji => '🇷🇺'; + + // ==================== GENERAL ==================== + @override + String get appTitle => 'VotianLT App'; + @override + String get ok => 'OK'; + @override + String get cancel => 'Отмена'; + @override + String get save => 'Сохранить'; + @override + String get delete => 'Удалить'; + @override + String get close => 'Закрыть'; + @override + String get confirm => 'Подтвердить'; + @override + String get error => 'Ошибка'; + @override + String get success => 'Успех'; + @override + String get loading => 'Загрузка...'; + @override + String get refresh => 'Обновить'; + @override + String get version => 'Версия'; + @override + String get unknown => 'Неизвестно'; + + // ==================== NAVIGATION ==================== + @override + String get jobs => 'Задания'; + @override + String get availableJobs => 'Доступные задания'; + @override + String get chats => 'Чаты'; + @override + String get settings => 'Настройки'; + @override + String get logout => 'Выход'; + @override + String get logoutConfirm => 'Выход'; + @override + String get logoutConfirmMessage => 'Вы действительно хотите выйти?'; + @override + String get openChat => 'Открыть чат'; + @override + String get chatInfo => 'Информация о чате'; + @override + String get routePlan => 'Планировать маршрут'; + + // ==================== LOGIN ==================== + @override + String get welcomeBack => 'С возвращением'; + @override + String get loginSubtitle => 'Войдите в свою учетную запись'; + @override + String get email => 'Эл. почта'; + @override + String get password => 'Пароль'; + @override + String get login => 'Войти'; + @override + String get loggingIn => 'Подключение...'; + @override + String get forgotPassword => 'Забыли пароль?'; + @override + String get forgotPasswordMessage => 'Функция восстановления пароля еще не реализована'; + @override + String get loginSuccess => 'Успешный выход из системы'; + @override + String get loginFailed => 'Ошибка входа'; + @override + String get connectionFailed => 'Ошибка подключения к серверу (Таймаут).'; + @override + String get connectionTimeout => 'Ошибка подключения к серверу (Таймаут).'; + @override + String get connecting => 'Подключение к серверу...'; + @override + String get connectionError => 'Ошибка подключения'; + @override + String get loginError => 'Ошибка при входе'; + + // ==================== JOBS ==================== + @override + String get noJobsAssigned => 'Нет назначенных заданий'; + @override + String get noJobsMessage => 'Ваши назначенные задания будут отображаться здесь.'; + @override + String get pullToRefresh => 'Потяните вниз, чтобы обновить'; + @override + String get newLabel => 'НОВОЕ'; + @override + String get tasksToComplete => 'Задачи для выполнения'; + @override + String get pickup => 'Забор'; + @override + String get delivery => 'Доставка'; + @override + String get created => 'Создано'; + @override + String get status => 'Статус'; + @override + String get priority => 'Приоритет'; + @override + String get dueDate => 'Срок выполнения'; + @override + String get location => 'Местоположение'; + @override + String get description => 'Описание'; + @override + String get cargo => 'Груз'; + @override + String get quantity => 'Количество'; + @override + String get weight => 'Вес'; + @override + String get dimensions => 'Размеры'; + @override + String get jobDeleted => 'Задание удалено'; + @override + String get jobDeleteError => 'Ошибка при удалении задания'; + @override + String get jobCompleted => 'Задание завершено'; + @override + String get from => 'Из'; + @override + String get to => 'в'; + @override + String get jobsUpdated => 'Задания обновлены'; + @override + String get connectionRestored => 'Соединение восстановлено. Загрузка заданий...'; + @override + String get connectionLost => 'Соединение потеряно. Офлайн.'; + @override + String get offline => 'Офлайн'; + @override + String get deleteJob => 'Удалить задание'; + @override + String get jobRemoved => 'было удалено'; + @override + String get newJobReceived => 'Получено новое задание'; + + // ==================== TASKS ==================== + @override + String get tasks => 'Задачи'; + @override + String get noTasks => 'Нет задач'; + @override + String get noTasksMessage => 'Для этого задания не определены задачи.'; + @override + String get taskOrder => 'Порядок'; + @override + String get confirmationRequired => 'Требуется подтверждение'; + @override + String get confirmationDescription => 'Нажмите кнопку, чтобы выполнить задачу.'; + @override + String get checklist => 'Контрольный список'; + @override + String get checklistDescription => 'Пожалуйста, отметьте все пункты:'; + @override + String get completeTask => 'Завершить задачу'; + @override + String get completeTaskConfirm => 'Хотите отметить эту задачу как выполненную?'; + @override + String get completeTaskNote => 'Примечание (необязательно)'; + @override + String get taskCompleted => 'Задача выполнена'; + @override + String get comment => 'Комментарий'; + @override + String get commentRequired => 'Комментарий (обязательно)'; + @override + String get enterComment => 'Введите комментарий'; + @override + String get commentDescription => 'Пожалуйста, введите комментарий:'; + @override + String get finish => 'Готово'; + @override + String get signature => 'Подпись'; + @override + String get signatureCapture => 'Захватить подпись'; + @override + String get signatureRequired => 'Пожалуйста, сделайте подпись.'; + @override + String get clear => 'Очистить'; + @override + String get signatureError => 'Ошибка при сохранении подписи'; + @override + String get signatureInstruction => 'Пожалуйста, подпишитесь в поле ниже (мышь или палец).'; + @override + String get photoCapture => 'Сделать фото'; + @override + String get requiredPhotos => 'Необходимые фото'; + @override + String get photosTaken => 'Сделано'; + @override + String get photos => 'Фото'; + @override + String get takePhoto => 'Сделать фото'; + @override + String get selectFromLibrary => 'Выбрать из библиотеки'; + @override + String get retakePhoto => 'Переснять'; + @override + String get photoRequired => 'Требуется фото'; + @override + String get minPhotos => 'Минимум'; + @override + String get maxPhotos => 'Максимум'; + @override + String get photoError => 'Ошибка при съемке фото'; + @override + String get deletePhoto => 'Удалить фото'; + @override + String get deletePhotoConfirm => 'Вы действительно хотите удалить это фото?'; + @override + String get barcode => 'Штрих-код'; + @override + String get barcodeScan => 'Сканировать штрих-код'; + @override + String get scanBarcode => 'Сканировать штрих-код'; + @override + String get barcodeRequired => 'Требуется штрих-код'; + @override + String get minBarcodes => 'Минимум'; + @override + String get maxBarcodes => 'Максимум'; + @override + String get scanned => 'Отсканировано'; + @override + String get scannedBarcodes => 'Отсканированные штрих-коды'; + @override + String get barcodesRequired => 'Требуются штрих-коды'; + @override + String get enterBarcode => 'Введите штрих-код'; + @override + String get barcodeEnterDescription => 'Пожалуйста, введите штрих-коды:'; + @override + String barcodeNumberRequired(int number) => 'Штрих-код $number (обязательно)'; + @override + String barcodeNumberOptional(int number) => 'Штрих-код $number (необязательно)'; + @override + String get barcodeError => 'Ошибка при сканировании штрих-кода'; + @override + String get cameraError => 'Ошибка инициализации камеры'; + @override + String get cameraNotReady => 'Камера не готова или недоступна'; + @override + String get cameraNotAvailable => 'Камера недоступна'; + @override + String get cameraNotSupportedMessage => 'Камера не поддерживается на этой платформе.'; + @override + String get cameraNotSupportedOnPlatform => 'Не поддерживается на этой платформе'; + @override + String get maxPhotosReached => 'Максимум достигнут'; + @override + String get cameraReadyNoPreview => 'Камера готова (без предпросмотра)'; + @override + String get cameraLoading => 'Камера загружается...'; + @override + String get cameraInitializing => 'Инициализация камеры...'; + @override + String get cameraLoadingMessage => 'Пожалуйста, подождите, пока загружается камера'; + @override + String get addPhotos => 'Добавить фото'; + @override + String get addPhotosInstruction => 'Используйте кнопку "Выбрать фото", чтобы добавить изображения с камеры или жёсткого диска.'; + @override + String get photoOf => 'из'; + + // ==================== CHAT ==================== + @override + String get typeMessage => 'Введите сообщение...'; + @override + String get send => 'Отправить'; + @override + String get noSender => 'Отправитель недоступен'; + @override + String get noSenderMessage => 'Отправитель недоступен. Пожалуйста, войдите снова.'; + @override + String get noRecipient => 'Получатель не настроен'; + @override + String get noRecipientMessage => 'Получатель не настроен для этого чата.'; + @override + String get messageSendError => 'Сообщение не удалось отправить.'; + @override + String get photoSendError => 'Фото не удалось отправить.'; + @override + String get photoProcessError => 'Фото не удалось обработать.'; + @override + String get imageSendError => 'Изображение не удалось отправить.'; + @override + String get chatTypeJob => 'Специфичный для задания'; + @override + String get chatTypeGeneral => 'Общий'; + @override + String get jobNumber => 'Номер задания'; + @override + String get messages => 'Сообщения'; + @override + String get selectPhoto => 'Выбрать фото'; + @override + String get unreadMessages => 'Непрочитанные сообщения'; + + // ==================== CARGO ==================== + @override + String get cargoDetails => 'Детали груза'; + @override + String get itemName => 'Описание'; + @override + String get itemNumber => 'Номер позиции'; + @override + String get item => 'Позиция'; + @override + String get weightUnit => 'кг'; + @override + String get dimensionUnit => 'см'; + @override + String get noCargoItems => 'Нет позиций груза'; + @override + String get noCargoItemsMessage => 'Для этого задания не определены позиции груза.'; + @override + String get article => 'Позиция'; + + // ==================== TASK TYPES ==================== + @override + String get takePhotos => 'Сделать фото'; + @override + String get photosCount => 'Фото'; + @override + String get checklistPoints => 'Пункты'; + @override + String get signatureRequiredText => 'Требуется подпись'; + @override + String get scanBarcodes => 'Сканировать штрих-коды'; + @override + String get barcodeCount => 'Коды'; + @override + String get commentOptional => 'Комментарий'; + @override + String get genericTask => 'Общая задача'; + @override + String get complete => 'Завершить'; + @override + String get abort => 'Отмена'; + @override + String get optional => 'Необязательно'; + @override + String get skipTask => 'Пропустить'; + + // ==================== SETTINGS ==================== + @override + String get language => 'Язык'; + @override + String get languageChanged => 'Язык изменен на'; + @override + String get appInfo => 'ИНФОРМАЦИЯ О ПРИЛОЖЕНИИ'; + + // ==================== STATUS ==================== + @override + String get statusCreated => 'Создано'; + @override + String get statusAssigned => 'Назначено'; + @override + String get statusInProgress => 'В процессе'; + @override + String get statusCompleted => 'Завершено'; + @override + String get priorityLow => 'Низкий'; + @override + String get priorityMedium => 'Средний'; + @override + String get priorityHigh => 'Высокий'; + @override + String get priorityUrgent => 'Срочный'; +} diff --git a/app/lib/l10n/app_localizations_tr.dart b/app/lib/l10n/app_localizations_tr.dart new file mode 100644 index 0000000..5ed83be --- /dev/null +++ b/app/lib/l10n/app_localizations_tr.dart @@ -0,0 +1,385 @@ +import 'app_localizations.dart'; + +class AppLocalizationsTr extends AppLocalizations { + @override + String get languageName => 'Türkçe'; + + @override + String get flagEmoji => '🇹🇷'; + + // ==================== GENERAL ==================== + @override + String get appTitle => 'VotianLT App'; + @override + String get ok => 'Tamam'; + @override + String get cancel => 'İptal'; + @override + String get save => 'Kaydet'; + @override + String get delete => 'Sil'; + @override + String get close => 'Kapat'; + @override + String get confirm => 'Onayla'; + @override + String get error => 'Hata'; + @override + String get success => 'Başarılı'; + @override + String get loading => 'Yükleniyor...'; + @override + String get refresh => 'Yenile'; + @override + String get version => 'Versiyon'; + @override + String get unknown => 'Bilinmiyor'; + + // ==================== NAVIGATION ==================== + @override + String get jobs => 'İşler'; + @override + String get availableJobs => 'Mevcut İşler'; + @override + String get chats => 'Sohbetler'; + @override + String get settings => 'Ayarlar'; + @override + String get logout => 'Çıkış'; + @override + String get logoutConfirm => 'Çıkış'; + @override + String get logoutConfirmMessage => 'Gerçekten çıkış yapmak istiyor musunuz?'; + @override + String get openChat => 'Sohbeti aç'; + @override + String get chatInfo => 'Sohbet bilgisi'; + @override + String get routePlan => 'Rota planla'; + + // ==================== LOGIN ==================== + @override + String get welcomeBack => 'Tekrar hoş geldiniz'; + @override + String get loginSubtitle => 'Hesabınıza giriş yapın'; + @override + String get email => 'E-posta'; + @override + String get password => 'Şifre'; + @override + String get login => 'Giriş'; + @override + String get loggingIn => 'Bağlanıyor...'; + @override + String get forgotPassword => 'Şifrenizi mi unuttunuz?'; + @override + String get forgotPasswordMessage => 'Şifremi unuttum özelliği henüz uygulanmadı'; + @override + String get loginSuccess => 'Başarıyla çıkış yapıldı'; + @override + String get loginFailed => 'Giriş başarısız'; + @override + String get connectionFailed => 'Sunucu bağlantısı başarısız (Zaman aşımı).'; + @override + String get connectionTimeout => 'Sunucu bağlantısı başarısız (Zaman aşımı).'; + @override + String get connecting => 'Sunucuya bağlanılıyor...'; + @override + String get connectionError => 'Bağlantı hatası'; + @override + String get loginError => 'Giriş sırasında hata'; + + // ==================== JOBS ==================== + @override + String get noJobsAssigned => 'Atanmış iş yok'; + @override + String get noJobsMessage => 'Atanmış işleriniz burada görüntülenecek.'; + @override + String get pullToRefresh => 'Yenilemek için aşağı çekin'; + @override + String get newLabel => 'YENİ'; + @override + String get tasksToComplete => 'Tamamlanacak görevler'; + @override + String get pickup => 'Alım'; + @override + String get delivery => 'Teslimat'; + @override + String get created => 'Oluşturuldu'; + @override + String get status => 'Durum'; + @override + String get priority => 'Öncelik'; + @override + String get dueDate => 'Bitiş tarihi'; + @override + String get location => 'Konum'; + @override + String get description => 'Açıklama'; + @override + String get cargo => 'Yük'; + @override + String get quantity => 'Miktar'; + @override + String get weight => 'Ağırlık'; + @override + String get dimensions => 'Boyutlar'; + @override + String get jobDeleted => 'İş silindi'; + @override + String get jobDeleteError => 'İş silinirken hata oluştu'; + @override + String get jobCompleted => 'İş tamamlandı'; + @override + String get from => 'Kimden'; + @override + String get to => 'den'; + @override + String get jobsUpdated => 'İşler güncellendi'; + @override + String get connectionRestored => 'Bağlantı geri yüklendi. İşler yükleniyor...'; + @override + String get connectionLost => 'Bağlantı kesildi. Çevrimdışı.'; + @override + String get offline => 'Çevrimdışı'; + @override + String get deleteJob => 'İşi sil'; + @override + String get jobRemoved => 'kaldırıldı'; + @override + String get newJobReceived => 'Yeni iş alındı'; + + // ==================== TASKS ==================== + @override + String get tasks => 'Görevler'; + @override + String get noTasks => 'Görev yok'; + @override + String get noTasksMessage => 'Bu iş için tanımlanmış görev yok.'; + @override + String get taskOrder => 'Sıra'; + @override + String get confirmationRequired => 'Onay gerekli'; + @override + String get confirmationDescription => 'Görevi tamamlamak için butona tıklayın.'; + @override + String get checklist => 'Kontrol listesi'; + @override + String get checklistDescription => 'Lütfen tüm maddeleri işaretleyin:'; + @override + String get completeTask => 'Görevi tamamla'; + @override + String get completeTaskConfirm => 'Bu görevi tamamlandı olarak işaretlemek istiyor musunuz?'; + @override + String get completeTaskNote => 'Not (isteğe bağlı)'; + @override + String get taskCompleted => 'Görev tamamlandı'; + @override + String get comment => 'Yorum'; + @override + String get commentRequired => 'Yorum (gerekli)'; + @override + String get enterComment => 'Yorum gir'; + @override + String get commentDescription => 'Lütfen bir yorum girin:'; + @override + String get finish => 'Bitir'; + @override + String get signature => 'İmza'; + @override + String get signatureCapture => 'İmza yakalama'; + @override + String get signatureRequired => 'Lütfen bir imza yakalayın.'; + @override + String get clear => 'Temizle'; + @override + String get signatureError => 'İmza kaydedilirken hata oluştu'; + @override + String get signatureInstruction => 'Lütfen aşağıdaki alana imzanızı atın (fare veya parmak).'; + @override + String get photoCapture => 'Fotoğraf çek'; + @override + String get requiredPhotos => 'Gerekli fotoğraflar'; + @override + String get photosTaken => 'Çekilen'; + @override + String get photos => 'Fotoğraflar'; + @override + String get takePhoto => 'Fotoğraf çek'; + @override + String get selectFromLibrary => 'Kütüphaneden seç'; + @override + String get retakePhoto => 'Tekrar çek'; + @override + String get photoRequired => 'Fotoğraf gerekli'; + @override + String get minPhotos => 'En az'; + @override + String get maxPhotos => 'En fazla'; + @override + String get photoError => 'Fotoğraf çekilirken hata oluştu'; + @override + String get deletePhoto => 'Fotoğrafı sil'; + @override + String get deletePhotoConfirm => 'Bu fotoğrafı gerçekten silmek istiyor musunuz?'; + @override + String get barcode => 'Barkod'; + @override + String get barcodeScan => 'Barkod tara'; + @override + String get scanBarcode => 'Barkod tara'; + @override + String get barcodeRequired => 'Barkod gerekli'; + @override + String get minBarcodes => 'En az'; + @override + String get maxBarcodes => 'En fazla'; + @override + String get scanned => 'Tarandı'; + @override + String get scannedBarcodes => 'Taranan barkodlar'; + @override + String get barcodesRequired => 'Barkodlar gerekli'; + @override + String get enterBarcode => 'Barkod gir'; + @override + String get barcodeEnterDescription => 'Lütfen barkodları girin:'; + @override + String barcodeNumberRequired(int number) => 'Barkod $number (gerekli)'; + @override + String barcodeNumberOptional(int number) => 'Barkod $number (isteğe bağlı)'; + @override + String get barcodeError => 'Barkod taranırken hata oluştu'; + @override + String get cameraError => 'Kamera başlatılırken hata oluştu'; + @override + String get cameraNotReady => 'Kamera hazır değil veya kullanılamıyor'; + @override + String get cameraNotAvailable => 'Kamera kullanılamıyor'; + @override + String get cameraNotSupportedMessage => 'Bu platformda kamera desteklenmiyor.'; + @override + String get cameraNotSupportedOnPlatform => 'Bu platformda desteklenmiyor'; + @override + String get maxPhotosReached => 'Maksimum ulaşıldı'; + @override + String get cameraReadyNoPreview => 'Kamera hazır (önizleme yok)'; + @override + String get cameraLoading => 'Kamera yükleniyor...'; + @override + String get cameraInitializing => 'Kamera başlatılıyor...'; + @override + String get cameraLoadingMessage => 'Kamera yüklenirken lütfen bekleyin'; + @override + String get addPhotos => 'Fotoğraf ekle'; + @override + String get addPhotosInstruction => 'Kamera veya sabit diskten görüntü eklemek için "Fotoğraf seç" düğmesini kullanın.'; + @override + String get photoOf => '/'; + + // ==================== CHAT ==================== + @override + String get typeMessage => 'Mesaj yazın...'; + @override + String get send => 'Gönder'; + @override + String get noSender => 'Gönderen mevcut değil'; + @override + String get noSenderMessage => 'Gönderen mevcut değil. Lütfen tekrar giriş yapın.'; + @override + String get noRecipient => 'Alıcı yapılandırılmamış'; + @override + String get noRecipientMessage => 'Bu sohbet için alıcı yapılandırılmamış.'; + @override + String get messageSendError => 'Mesaj gönderilemedi.'; + @override + String get photoSendError => 'Fotoğraf gönderilemedi.'; + @override + String get photoProcessError => 'Fotoğraf işlenemedi.'; + @override + String get imageSendError => 'Görüntü gönderilemedi.'; + @override + String get chatTypeJob => 'İşe özel'; + @override + String get chatTypeGeneral => 'Genel'; + @override + String get jobNumber => 'İş numarası'; + @override + String get messages => 'Mesajlar'; + @override + String get selectPhoto => 'Fotoğraf seç'; + @override + String get unreadMessages => 'Okunmamış mesajlar'; + + // ==================== CARGO ==================== + @override + String get cargoDetails => 'Yük Detayları'; + @override + String get itemName => 'Açıklama'; + @override + String get itemNumber => 'Pozisyon No'; + @override + String get item => 'Pozisyon'; + @override + String get weightUnit => 'kg'; + @override + String get dimensionUnit => 'cm'; + @override + String get noCargoItems => 'Yük kalemi yok'; + @override + String get noCargoItemsMessage => 'Bu iş için tanımlanmış yük kalemi yok.'; + @override + String get article => 'Kalem'; + + // ==================== TASK TYPES ==================== + @override + String get takePhotos => 'Fotoğraf çek'; + @override + String get photosCount => 'Fotoğraflar'; + @override + String get checklistPoints => 'Noktalar'; + @override + String get signatureRequiredText => 'İmza gerekli'; + @override + String get scanBarcodes => 'Barkodları tara'; + @override + String get barcodeCount => 'Kodlar'; + @override + String get commentOptional => 'Yorum'; + @override + String get genericTask => 'Genel görev'; + @override + String get complete => 'Tamamla'; + @override + String get abort => 'İptal'; + @override + String get optional => 'İsteğe bağlı'; + @override + String get skipTask => 'Atla'; + + // ==================== SETTINGS ==================== + @override + String get language => 'Dil'; + @override + String get languageChanged => 'Dil değiştirildi:'; + @override + String get appInfo => 'UYGULAMA BİLGİSİ'; + + // ==================== STATUS ==================== + @override + String get statusCreated => 'Oluşturuldu'; + @override + String get statusAssigned => 'Atandı'; + @override + String get statusInProgress => 'Devam ediyor'; + @override + String get statusCompleted => 'Tamamlandı'; + @override + String get priorityLow => 'Düşük'; + @override + String get priorityMedium => 'Orta'; + @override + String get priorityHigh => 'Yüksek'; + @override + String get priorityUrgent => 'Acil'; +} diff --git a/app/lib/login_view.dart b/app/lib/login_view.dart new file mode 100644 index 0000000..731f73d --- /dev/null +++ b/app/lib/login_view.dart @@ -0,0 +1,383 @@ +import 'dart:async'; +import 'package:flutter/foundation.dart'; +import 'package:votianlt_app/services/developer.dart' as developer; +import 'package:flutter/material.dart'; +import 'package:package_info_plus/package_info_plus.dart'; +import 'services/websocket_service.dart'; +import 'services/dart_mq.dart'; +import 'services/database_service.dart'; +import 'app_state.dart'; +import 'l10n/app_localizations.dart'; + +class LoginView extends StatefulWidget { + const LoginView({super.key, this.suppressConnectionSnack = false}); + + // If true, suppress connection-related SnackBars until the user attempts login + final bool suppressConnectionSnack; + + @override + State createState() => _LoginViewState(); +} + +class _LoginViewState extends State { + final _formKey = GlobalKey(); + final _emailController = TextEditingController(); + final _passwordController = TextEditingController(); + bool _isPasswordVisible = false; + bool _isLoggingIn = false; + final StompService _stompService = StompService(); + final AppState _appState = AppState(); + + // DartMQ subscriptions for proper cleanup + DartMQSubscription? _connectionStatusSubscription; + DartMQSubscription? _authResponseSubscription; + bool _logoutNoticeShown = false; + bool _hasNavigatedToJobs = false; + String _appVersion = ''; + + @override + void initState() { + super.initState(); + // Pre-populate with test data + if (kDebugMode) { + _emailController.text = 'mail@svencarstensen.de'; + _passwordController.text = 'test123'; + } + + _loadAppVersion(); + _initializeStompService(); + + // If we came here due to logout, show only a success message and suppress other connection snacks + if (widget.suppressConnectionSnack && !_logoutNoticeShown) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + _logoutNoticeShown = true; + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(AppLocalizations.of(context).loginSuccess), backgroundColor: Colors.green, duration: const Duration(seconds: 1))); + }); + } + } + + @override + void dispose() { + // Cancel all stream subscriptions to prevent setState() after dispose + _connectionStatusSubscription?.cancel(); + _authResponseSubscription?.cancel(); + _emailController.dispose(); + _passwordController.dispose(); + + // Don't dispose the singleton StompService as it may be used elsewhere + // _stompService.dispose(); + + super.dispose(); + } + + Future _loadAppVersion() async { + try { + final PackageInfo packageInfo = await PackageInfo.fromPlatform(); + setState(() { + _appVersion = packageInfo.version; + }); + } catch (e) { + developer.log('Error loading app version: $e', name: 'LoginView'); + } + } + + void _initializeStompService() { + // Listen to connection status changes via dart_mq + // Note: Don't reset _isLoggingIn here - the login flow in _handleLogin + // manages button state through its own error/success handling. + _connectionStatusSubscription = DartMQ().subscribe(MQTopics.connectionStatus, (isConnected) { + if (mounted) { + setState(() {}); + } + }); + + // Listen to authentication responses via dart_mq + _authResponseSubscription = DartMQ().subscribe>(MQTopics.authResponse, (response) { + final responseTime = DateTime.now(); + developer.log('=== AUTHENTICATION RESPONSE RECEIVED ===', name: 'LoginView'); + developer.log('Timestamp: ${responseTime.toIso8601String()}', name: 'LoginView'); + developer.log('Response data: $response', name: 'LoginView'); + + if (mounted) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + + setState(() { + _isLoggingIn = false; + }); + + if (response['success'] == true) { + // Prevent duplicate navigation from multiple auth responses + if (_hasNavigatedToJobs) { + developer.log('Already navigated to jobs view - ignoring duplicate auth response', name: 'LoginView'); + return; + } + _hasNavigatedToJobs = true; + + final message = response['message'] ?? 'Anmeldung erfolgreich'; + final email = _emailController.text.trim(); + final password = _passwordController.text; + + developer.log('=== LOGIN SUCCESS ===', name: 'LoginView'); + developer.log('Email: $email', name: 'LoginView'); + developer.log('Message: $message', name: 'LoginView'); + + // Store email as login identifier + _appState.setLoggedInEmail(email); + + // Save credentials for auto-login on app restart + DatabaseService().saveCredentials(email, password); + + // Navigate directly to jobs view - jobs will be loaded there + developer.log('Navigating to jobs view - jobs will be loaded there...', name: 'LoginView'); + Navigator.of(context).pushReplacementNamed('/jobs'); + } else { + final errorMessage = response['message'] ?? 'Unbekannter Fehler'; + final errorCode = response['code'] ?? 'No code'; + + developer.log('=== LOGIN FAILURE ===', name: 'LoginView'); + developer.log('Error message: $errorMessage', name: 'LoginView'); + developer.log('Error code: $errorCode', name: 'LoginView'); + developer.log('Full error response: $response', name: 'LoginView'); + + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('${AppLocalizations.of(context).loginFailed}: $errorMessage'), backgroundColor: Colors.red, duration: const Duration(seconds: 1))); + } + }); + } else { + developer.log('Widget not mounted - skipping UI updates for auth response', name: 'LoginView'); + } + + developer.log('Authentication response processing completed', name: 'LoginView'); + }); + } + + Future _handleLogin() async { + final loginStartTime = DateTime.now(); + final sessionId = loginStartTime.millisecondsSinceEpoch.toString(); + + developer.log('=== LOGIN ATTEMPT STARTED ===', name: 'LoginView'); + developer.log('Session ID: $sessionId', name: 'LoginView'); + developer.log('Timestamp: ${loginStartTime.toIso8601String()}', name: 'LoginView'); + + if (!_formKey.currentState!.validate()) { + developer.log('Login validation failed - form is invalid', name: 'LoginView'); + return; + } + + if (_isLoggingIn) { + developer.log('Login already in progress - ignoring duplicate request', name: 'LoginView'); + return; + } + + String email = _emailController.text.trim(); + developer.log('Login attempt for email: $email', name: 'LoginView'); + developer.log('Password length: ${_passwordController.text.length} characters', name: 'LoginView'); + + // Capture ScaffoldMessenger and localizations before any async operations + final scaffoldMessenger = ScaffoldMessenger.of(context); + final localizations = AppLocalizations.of(context); + + if (!_stompService.isConnected) { + developer.log('Not connected to STOMP server - establishing connection first', name: 'LoginView'); + developer.log('STOMP service connection state: ${_stompService.isConnected}', name: 'LoginView'); + + // Always attempt connection to fixed STOMP endpoint (no discovery gating) + // Show connecting message + if (!widget.suppressConnectionSnack) { + scaffoldMessenger.showSnackBar(SnackBar(content: Text(localizations.connecting), backgroundColor: Colors.blue, duration: const Duration(seconds: 1))); + } + + // Set loading state + setState(() { + _isLoggingIn = true; + }); + + try { + // Start connection to STOMP server + await _stompService.connect(); + + // Check if already connected after connect returns + if (!_stompService.isConnected) { + // Wait for connection to be established with a timeout + try { + final completer = Completer(); + final subscription = DartMQ().subscribe(MQTopics.connectionStatus, (isConnected) { + if (isConnected && !completer.isCompleted) { + completer.complete(true); + } + }); + + await completer.future.timeout(const Duration(seconds: 12)); + subscription.cancel(); + developer.log('STOMP connection established - proceeding with login', name: 'LoginView'); + } on TimeoutException { + developer.log('STOMP connection timed out', name: 'LoginView'); + } + } else { + developer.log('STOMP already connected after connect - proceeding with login', name: 'LoginView'); + } + + // Check if connection was successful + if (!_stompService.isConnected) { + setState(() { + _isLoggingIn = false; + }); + scaffoldMessenger.showSnackBar(SnackBar(content: Text(localizations.connectionTimeout), backgroundColor: Colors.red, duration: const Duration(seconds: 2))); + return; + } + } catch (e, stackTrace) { + setState(() { + _isLoggingIn = false; + }); + developer.log('Error connecting to STOMP server: $e', name: 'LoginView'); + developer.log('Stack trace: $stackTrace', name: 'LoginView'); + scaffoldMessenger.showSnackBar(SnackBar(content: Text('${localizations.connectionError}: $e'), backgroundColor: Colors.red, duration: const Duration(seconds: 1))); + return; + } + } + + developer.log('Pre-login checks passed - initiating login request', name: 'LoginView'); + developer.log('Connection status: connected=${_stompService.isConnected}', name: 'LoginView'); + + setState(() { + _isLoggingIn = true; + }); + + String password = _passwordController.text; + + developer.log('Sending login request via STOMP service...', name: 'LoginView'); + + try { + // Send login request via STOMP + await _stompService.login(email, password); + + final requestSentTime = DateTime.now(); + final requestDuration = requestSentTime.difference(loginStartTime).inMilliseconds; + developer.log('Login request sent successfully after ${requestDuration}ms', name: 'LoginView'); + } catch (e, stackTrace) { + final errorTime = DateTime.now(); + final errorDuration = errorTime.difference(loginStartTime).inMilliseconds; + + developer.log('LOGIN ERROR: Exception during login request after ${errorDuration}ms', name: 'LoginView'); + developer.log('Error: $e', name: 'LoginView'); + developer.log('Stack trace: $stackTrace', name: 'LoginView'); + + setState(() { + _isLoggingIn = false; + }); + + scaffoldMessenger.showSnackBar(SnackBar(content: Text('${localizations.loginError}: $e'), backgroundColor: Colors.red, duration: const Duration(seconds: 1))); + } + + // The auth response will be handled by the stream listener + // _isLoggingIn will be set to false in the listener + developer.log('Login request phase completed - waiting for auth response', name: 'LoginView'); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: Colors.grey[50], + body: Column( + children: [ + Expanded( + child: SafeArea( + child: Center( + child: SingleChildScrollView( + padding: const EdgeInsets.all(24.0), + child: Form( + key: _formKey, + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + // Logo oder App-Name + Icon(Icons.account_circle, size: 100, color: Colors.deepPurple), + const SizedBox(height: 32), + + Text(AppLocalizations.of(context).welcomeBack, style: Theme.of(context).textTheme.headlineMedium?.copyWith(fontWeight: FontWeight.bold, color: Colors.grey[800]), textAlign: TextAlign.center), + const SizedBox(height: 8), + + Text(AppLocalizations.of(context).loginSubtitle, style: Theme.of(context).textTheme.bodyLarge?.copyWith(color: Colors.grey[600]), textAlign: TextAlign.center), + const SizedBox(height: 32), + // E-Mail-Feld + TextFormField( + controller: _emailController, + keyboardType: TextInputType.emailAddress, + decoration: InputDecoration(labelText: 'E-Mail-Adresse', hintText: 'Geben Sie Ihre E-Mail-Adresse ein', prefixIcon: const Icon(Icons.email_outlined), border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)), filled: true, fillColor: Colors.white), + validator: (value) { + if (value == null || value.isEmpty) { + return 'Bitte geben Sie Ihre E-Mail-Adresse ein'; + } + if (!RegExp(r'^[A-Za-z0-9_.+-]+@[A-Za-z0-9-]+\.[A-Za-z0-9.-]+$').hasMatch(value)) { + return 'Bitte geben Sie eine gültige E-Mail-Adresse ein'; + } + return null; + }, + ), + const SizedBox(height: 16), + + // Passwort-Feld + TextFormField( + controller: _passwordController, + obscureText: !_isPasswordVisible, + decoration: InputDecoration( + labelText: 'Passwort', + hintText: 'Geben Sie Ihr Passwort ein', + prefixIcon: const Icon(Icons.lock_outlined), + suffixIcon: IconButton( + icon: Icon(_isPasswordVisible ? Icons.visibility : Icons.visibility_off), + onPressed: () { + setState(() { + _isPasswordVisible = !_isPasswordVisible; + }); + }, + ), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)), + filled: true, + fillColor: Colors.white, + ), + validator: (value) { + if (value == null || value.isEmpty) { + return 'Bitte geben Sie Ihr Passwort ein'; + } + if (value.length < 6) { + return 'Das Passwort muss mindestens 6 Zeichen lang sein'; + } + return null; + }, + ), + const SizedBox(height: 24), + + // Passwort vergessen Link + Align( + alignment: Alignment.centerRight, + child: TextButton( + onPressed: () { + // Hier würde die "Passwort vergessen" Funktionalität implementiert werden + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(AppLocalizations.of(context).forgotPasswordMessage), duration: const Duration(seconds: 1))); + }, + child: Text(AppLocalizations.of(context).forgotPassword, style: const TextStyle(color: Colors.deepPurple, fontWeight: FontWeight.w500)), + ), + ), + const SizedBox(height: 24), + + // Verbindungsstatus + // Anmelden Button + ElevatedButton(onPressed: _isLoggingIn ? null : _handleLogin, style: ElevatedButton.styleFrom(backgroundColor: Colors.deepPurple, foregroundColor: Colors.white, padding: const EdgeInsets.symmetric(vertical: 16), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), elevation: 2), child: _isLoggingIn ? Row(mainAxisAlignment: MainAxisAlignment.center, children: const [SizedBox(width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 2.5, valueColor: AlwaysStoppedAnimation(Colors.white))), SizedBox(width: 12), Text('Verbinden…', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600))]) : const Text('Anmelden', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600))), + const SizedBox(height: 24), + ], + ), + ), + ), + ), + ), + ), + // Version number at the bottom + if (_appVersion.isNotEmpty) Padding(padding: const EdgeInsets.only(bottom: 16.0), child: Text('Version $_appVersion', style: TextStyle(fontSize: 12, color: Colors.grey[500]), textAlign: TextAlign.center)), + ], + ), + ); + } +} diff --git a/app/lib/main.dart b/app/lib/main.dart new file mode 100644 index 0000000..d2fbe87 --- /dev/null +++ b/app/lib/main.dart @@ -0,0 +1,122 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'login_view.dart'; +import 'jobs_view.dart'; +import 'cargo_items_view.dart'; +import 'chats_view.dart'; +import 'chat_details_view.dart'; +import 'settings_view.dart'; +import 'models/job.dart'; +import 'models/chat.dart'; +import 'services/database_service.dart'; +import 'services/chat_service.dart'; +import 'app_state.dart'; +import 'navigation_observer.dart'; +import 'services/notification_service.dart'; +import 'l10n/app_localizations.dart'; + +void main() async { + WidgetsFlutterBinding.ensureInitialized(); + + // Initialize SQLite database + await DatabaseService().initialize(); + + // Load data from database + await AppState().loadLoginFromDatabase(); + + // Load language preference + await AppState().loadLanguagePreference(); + + // Load jobs from database to trigger message type logging at startup + await AppState().refreshJobsFromDatabase(); + + // Prepare chat service before WebSocket events start flowing + await ChatService().initialize(); + + // Initialize notification service for local notifications with sound + await NotificationService().initialize(); + + // Note: WebSocket connection is initiated from the view that needs it: + // - If userId exists: JobsView initiates connection on startup + // - If no userId: LoginView initiates connection when login button is clicked + + runApp(const MyApp()); +} + +class MyApp extends StatelessWidget { + const MyApp({super.key}); + + @override + Widget build(BuildContext context) { + // Check if user is already logged in + final appState = AppState(); + final initialRoute = appState.isLoggedIn ? '/jobs' : '/login'; + + return ValueListenableBuilder( + valueListenable: localeNotifier, + builder: (context, locale, child) { + return MaterialApp( + title: 'VotianLT App', + debugShowCheckedModeBanner: false, + theme: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), useMaterial3: true), + // Localization configuration + locale: locale, + localizationsDelegates: const [AppLocalizations.delegate, GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, GlobalCupertinoLocalizations.delegate], + supportedLocales: supportedLanguageCodes.map((code) => Locale(code)).toList(), + navigatorObservers: [routeObserver], + initialRoute: initialRoute, + onGenerateRoute: (settings) { + switch (settings.name) { + case '/login': + final arg = settings.arguments; + final suppress = (arg is bool) ? arg : false; + return MaterialPageRoute(builder: (_) => LoginView(suppressConnectionSnack: suppress)); + case '/jobs': + return MaterialPageRoute(builder: (_) => const JobsView()); + case '/cargo_items': + final job = settings.arguments as Job; + return MaterialPageRoute(builder: (_) => CargoItemsView(job: job)); + case '/chats': + return MaterialPageRoute(builder: (_) => const ChatsView()); + case '/chat_details': + final chat = settings.arguments as Chat; + return MaterialPageRoute(builder: (_) => ChatDetailsView(chat: chat)); + case '/settings': + return MaterialPageRoute(builder: (_) => const SettingsView()); + default: + return MaterialPageRoute(builder: (_) => const LoginView(suppressConnectionSnack: false)); + } + }, + ); + }, + ); + } +} + +class MyHomePage extends StatefulWidget { + const MyHomePage({super.key, required this.title}); + + final String title; + + @override + State createState() => _MyHomePageState(); +} + +class _MyHomePageState extends State { + int _counter = 0; + + void _incrementCounter() { + setState(() { + _counter++; + }); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar(backgroundColor: Theme.of(context).colorScheme.inversePrimary, title: Text(widget.title)), + body: Center(child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [const Text('You have pushed the button this many times:'), Text('$_counter', style: Theme.of(context).textTheme.headlineMedium)])), + floatingActionButton: FloatingActionButton(onPressed: _incrementCounter, tooltip: 'Increment', child: const Icon(Icons.add)), // This trailing comma makes auto-formatting nicer for build methods. + ); + } +} diff --git a/app/lib/models/acknowledgment_message.dart b/app/lib/models/acknowledgment_message.dart new file mode 100644 index 0000000..1feebfc --- /dev/null +++ b/app/lib/models/acknowledgment_message.dart @@ -0,0 +1,85 @@ +/// Acknowledgment message sent by client to confirm message receipt +class AcknowledgmentMessage { + /// ID of the message being acknowledged + final String messageId; + + /// Status of the acknowledgment + final AcknowledgmentStatus status; + + /// Timestamp when the acknowledgment was created + final DateTime timestamp; + + /// Optional error message if status is FAILED + final String? errorMessage; + + AcknowledgmentMessage({ + required this.messageId, + required this.status, + required this.timestamp, + this.errorMessage, + }); + + /// Create AcknowledgmentMessage from JSON + factory AcknowledgmentMessage.fromJson(Map json) { + return AcknowledgmentMessage( + messageId: json['messageId'] as String, + status: AcknowledgmentStatus.fromString(json['status'] as String), + timestamp: DateTime.parse(json['timestamp'] as String), + errorMessage: json['errorMessage'] as String?, + ); + } + + /// Convert AcknowledgmentMessage to JSON + Map toJson() { + return { + 'messageId': messageId, + 'status': status.toString(), + 'timestamp': timestamp.toIso8601String(), + if (errorMessage != null) 'errorMessage': errorMessage, + }; + } + + @override + String toString() { + return 'AcknowledgmentMessage(messageId: $messageId, status: $status)'; + } +} + +/// Status of an acknowledgment +enum AcknowledgmentStatus { + /// Message was received by the client + received, + + /// Message was processed successfully + processed, + + /// Message processing failed + failed; + + /// Convert string to AcknowledgmentStatus + static AcknowledgmentStatus fromString(String value) { + switch (value.toUpperCase()) { + case 'RECEIVED': + return AcknowledgmentStatus.received; + case 'PROCESSED': + return AcknowledgmentStatus.processed; + case 'FAILED': + return AcknowledgmentStatus.failed; + default: + return AcknowledgmentStatus.received; + } + } + + @override + String toString() { + switch (this) { + case AcknowledgmentStatus.received: + return 'RECEIVED'; + case AcknowledgmentStatus.processed: + return 'PROCESSED'; + case AcknowledgmentStatus.failed: + return 'FAILED'; + } + } +} + diff --git a/app/lib/models/cargo_item.dart b/app/lib/models/cargo_item.dart new file mode 100644 index 0000000..9e89491 --- /dev/null +++ b/app/lib/models/cargo_item.dart @@ -0,0 +1,99 @@ +class CargoItem { + final String id; // Will store the timestamp as string + final String jobId; // Will store the timestamp as string + final String description; + final int quantity; + final double weightKg; + final double lengthCm; + final double widthCm; + final double heightCm; + + CargoItem({ + required this.id, + required this.jobId, + required this.description, + required this.quantity, + required this.weightKg, + required this.lengthCm, + required this.widthCm, + required this.heightCm, + }); + + static String _readString(dynamic value, {String fallback = ''}) { + if (value is String) { + return value; + } + if (value is num || value is bool) { + return value.toString(); + } + return fallback; + } + + factory CargoItem.fromJson(Map json) { + // Parse the complex id object - can be either a Map or a simple string + String idValue = ''; + if (json['id'] is Map) { + final idMap = json['id'] as Map; + idValue = idMap['timestamp']?.toString() ?? ''; + } else { + idValue = json['id']?.toString() ?? ''; + } + + // Parse the complex jobId object - can be either a Map or a simple string + String jobIdValue = ''; + if (json['jobId'] is Map) { + final jobIdMap = json['jobId'] as Map; + jobIdValue = jobIdMap['timestamp']?.toString() ?? ''; + } else { + jobIdValue = json['jobId']?.toString() ?? ''; + } + + return CargoItem( + id: idValue, + jobId: jobIdValue, + description: _readString(json['description']), + quantity: json['quantity'] is num ? json['quantity'].toInt() : 0, + weightKg: json['weightKg'] is num ? json['weightKg'].toDouble() : 0.0, + lengthCm: json['lengthMm'] is num ? json['lengthMm'].toDouble() : 0.0, + widthCm: json['widthMm'] is num ? json['widthMm'].toDouble() : 0.0, + heightCm: json['heightMm'] is num ? json['heightMm'].toDouble() : 0.0, + ); + } + + Map toJson() { + return { + 'id': id, + 'jobId': jobId, + 'description': description, + 'quantity': quantity, + 'weightKg': weightKg, + 'lengthMm': lengthCm, + 'widthMm': widthCm, + 'heightMm': heightCm, + }; + } + + @override + String toString() { + return 'CargoItem(id: $id, description: $description, quantity: $quantity)'; + } + + @override + bool operator ==(Object other) { + if (identical(this, other)) return true; + return other is CargoItem && other.id == id; + } + + @override + int get hashCode => id.hashCode; + + /// Get formatted dimensions string for display + String get formattedDimensions { + return '${lengthCm.toInt()} × ${widthCm.toInt()} × ${heightCm.toInt()} cm'; + } + + /// Get formatted weight string for display + String get formattedWeight { + return '${weightKg.toStringAsFixed(1)} kg'; + } +} diff --git a/app/lib/models/chat.dart b/app/lib/models/chat.dart new file mode 100644 index 0000000..40021f2 --- /dev/null +++ b/app/lib/models/chat.dart @@ -0,0 +1,162 @@ +import 'chat_message.dart'; + +enum ChatType { general, jobSpecific } + +class Chat { + final String id; + final String title; + final String? receiver; + final ChatType type; + final String? jobId; // only for job-specific chats + final String? jobNumber; // only for job-specific chats + final List messages; + final DateTime lastMessageTime; + final String lastMessagePreview; + + Chat({ + required this.id, + required this.title, + this.receiver, + required this.type, + this.jobId, + this.jobNumber, + required this.messages, + required this.lastMessageTime, + required this.lastMessagePreview, + }); + + factory Chat.fromJson(Map json) { + final messagesList = json['messages'] as List? ?? []; + final messages = + messagesList + .map( + (messageJson) => + ChatMessage.fromJson(messageJson as Map), + ) + .toList(); + + return Chat( + id: json['id']?.toString() ?? '', + title: json['title']?.toString() ?? '', + receiver: json['receiver']?.toString(), + type: + json['type'] == 'jobSpecific' + ? ChatType.jobSpecific + : ChatType.general, + jobId: json['jobId']?.toString(), + jobNumber: json['jobNumber']?.toString(), + messages: messages, + lastMessageTime: _resolveLastMessageTime(json, messages), + lastMessagePreview: _resolveLastMessagePreview(json, messages), + ); + } + + Map toJson() { + return { + 'id': id, + 'title': title, + 'receiver': receiver, + 'type': type == ChatType.jobSpecific ? 'jobSpecific' : 'general', + 'jobId': jobId, + 'jobNumber': jobNumber, + 'messages': messages.map((message) => message.toJson()).toList(), + 'lastMessageTime': lastMessageTime.toIso8601String(), + 'lastMessagePreview': lastMessagePreview, + }; + } + + // Factory constructor for general chat + factory Chat.general({ + required String id, + required String title, + String? receiver, + required List messages, + }) { + final lastMessage = messages.isNotEmpty ? messages.last : null; + return Chat( + id: id, + title: title, + receiver: receiver, + type: ChatType.general, + messages: messages, + lastMessageTime: lastMessage?.createdAt ?? DateTime.now(), + lastMessagePreview: + lastMessage != null + ? _previewForMessage(lastMessage) + : 'Noch keine Nachrichten', + ); + } + + // Factory constructor for job-specific chat + factory Chat.jobSpecific({ + required String id, + required String jobId, + required String jobNumber, + String? receiver, + required List messages, + }) { + final lastMessage = messages.isNotEmpty ? messages.last : null; + return Chat( + id: id, + title: 'Job $jobNumber', + receiver: receiver, + type: ChatType.jobSpecific, + jobId: jobId, + jobNumber: jobNumber, + messages: messages, + lastMessageTime: lastMessage?.createdAt ?? DateTime.now(), + lastMessagePreview: + lastMessage != null + ? _previewForMessage(lastMessage) + : 'Noch keine Nachrichten', + ); + } + + static DateTime _resolveLastMessageTime( + Map json, + List messages, + ) { + if (messages.isNotEmpty) { + return messages.last.createdAt; + } + final raw = json['lastMessageTime']?.toString(); + if (raw != null) { + final parsed = DateTime.tryParse(raw); + if (parsed != null) { + return parsed; + } + } + return DateTime.now(); + } + + static String _resolveLastMessagePreview( + Map json, + List messages, + ) { + if (messages.isNotEmpty) { + return _previewForMessage(messages.last); + } + return json['lastMessagePreview']?.toString() ?? 'Noch keine Nachrichten'; + } + + static String _previewForMessage(ChatMessage message) { + if (message.contentType == ChatContentType.image) { + return '[Bild]'; + } + return message.content; + } + + @override + String toString() { + return 'Chat(id: $id, title: $title, type: $type, jobId: $jobId, messagesCount: ${messages.length})'; + } + + @override + bool operator ==(Object other) { + if (identical(this, other)) return true; + return other is Chat && other.id == id; + } + + @override + int get hashCode => id.hashCode; +} diff --git a/app/lib/models/chat_message.dart b/app/lib/models/chat_message.dart new file mode 100644 index 0000000..ed46bff --- /dev/null +++ b/app/lib/models/chat_message.dart @@ -0,0 +1,211 @@ +import 'package:votianlt_app/services/developer.dart' as developer; + +enum ChatDirection { incoming, outgoing } + +enum ChatMessageType { general, jobRelated } + +enum ChatContentType { text, image } + +ChatDirection chatDirectionFromString( + String? value, { + ChatDirection fallback = ChatDirection.incoming, +}) { + switch (value?.toUpperCase()) { + case 'CLIENT': + case 'OUTGOING': + return ChatDirection.outgoing; + case 'SERVER': + case 'INCOMING': + return ChatDirection.incoming; + default: + return fallback; + } +} + +String chatDirectionToString(ChatDirection direction) { + return direction == ChatDirection.outgoing ? 'CLIENT' : 'SERVER'; +} + +ChatMessageType chatMessageTypeFromString( + String? value, { + ChatMessageType fallback = ChatMessageType.general, +}) { + switch (value?.toUpperCase()) { + case 'JOB_RELATED': + return ChatMessageType.jobRelated; + case 'GENERAL': + return ChatMessageType.general; + default: + return fallback; + } +} + +String chatMessageTypeToString(ChatMessageType type) { + return type == ChatMessageType.jobRelated ? 'JOB_RELATED' : 'GENERAL'; +} + +ChatContentType chatContentTypeFromString( + String? value, { + ChatContentType fallback = ChatContentType.text, +}) { + switch (value?.toUpperCase()) { + case 'IMAGE': + return ChatContentType.image; + case 'TEXT': + return ChatContentType.text; + default: + return fallback; + } +} + +String chatContentTypeToString(ChatContentType type) { + return type == ChatContentType.image ? 'IMAGE' : 'TEXT'; +} + +class ChatMessage { + final String id; + final String content; + final DateTime createdAt; + final ChatDirection direction; + final ChatMessageType messageType; + final ChatContentType contentType; + final String? jobId; + final String? jobNumber; + final bool read; + final bool pendingSync; + + const ChatMessage({ + required this.id, + required this.content, + required this.createdAt, + required this.direction, + required this.messageType, + this.contentType = ChatContentType.text, + this.jobId, + this.jobNumber, + this.read = false, + this.pendingSync = false, + }); + + factory ChatMessage.fromJson(Map json) { + final rawId = (json['messageId'] ?? json['id'] ?? '').toString(); + final rawContent = (json['content'] ?? json['text'] ?? '').toString(); + final rawContentType = json['contentType']?.toString(); + + DateTime createdAt; + final createdAtRaw = json['createdAt'] ?? json['timestamp']; + if (createdAtRaw is DateTime) { + createdAt = createdAtRaw; + } else { + createdAt = + DateTime.tryParse(createdAtRaw?.toString() ?? '') ?? DateTime.now(); + } + + var direction = chatDirectionFromString( + json['origin']?.toString() ?? json['direction']?.toString(), + fallback: + json['isOwn'] == true + ? ChatDirection.outgoing + : ChatDirection.incoming, + ); + + var messageType = chatMessageTypeFromString( + json['messageType']?.toString(), + fallback: + ((json['jobId']?.toString().isNotEmpty ?? false) || + (json['jobNumber']?.toString().isNotEmpty ?? false)) + ? ChatMessageType.jobRelated + : ChatMessageType.general, + ); + + final jobIdRaw = json['jobId']?.toString(); + final jobNumberRaw = json['jobNumber']?.toString(); + final jobId = jobIdRaw?.trim(); + final jobNumber = jobNumberRaw?.trim(); + + if (rawId.isEmpty || rawContent.isEmpty) { + developer.log( + 'Invalid ChatMessage payload (one or more required fields missing): $json', + ); + } + + return ChatMessage( + id: rawId, + content: rawContent, + createdAt: createdAt, + direction: direction, + messageType: messageType, + contentType: chatContentTypeFromString(rawContentType), + jobId: jobId?.isEmpty ?? true ? null : jobId, + jobNumber: jobNumber?.isEmpty ?? true ? null : jobNumber, + read: json['read'] == true, + pendingSync: json['pendingSync'] == true, + ); + } + + Map toJson() { + final map = { + 'messageId': id, + 'content': content, + 'origin': chatDirectionToString(direction), + 'messageType': chatMessageTypeToString(messageType), + 'contentType': chatContentTypeToString(contentType), + 'createdAt': createdAt.toIso8601String(), + 'read': read, + }; + + if (jobId != null && jobId!.isNotEmpty) { + map['jobId'] = jobId; + } + if (jobNumber != null && jobNumber!.isNotEmpty) { + map['jobNumber'] = jobNumber; + } + if (pendingSync) { + map['pendingSync'] = true; + } + + return map; + } + + bool get isOwn => direction == ChatDirection.outgoing; + + ChatMessage copyWith({ + String? id, + String? content, + DateTime? createdAt, + ChatDirection? direction, + ChatMessageType? messageType, + ChatContentType? contentType, + String? jobId, + String? jobNumber, + bool? read, + bool? pendingSync, + }) { + return ChatMessage( + id: id ?? this.id, + content: content ?? this.content, + createdAt: createdAt ?? this.createdAt, + direction: direction ?? this.direction, + messageType: messageType ?? this.messageType, + contentType: contentType ?? this.contentType, + jobId: jobId ?? this.jobId, + jobNumber: jobNumber ?? this.jobNumber, + read: read ?? this.read, + pendingSync: pendingSync ?? this.pendingSync, + ); + } + + @override + String toString() { + return 'ChatMessage(id: $id, direction: $direction, messageType: $messageType, contentType: $contentType, createdAt: $createdAt)'; + } + + @override + bool operator ==(Object other) { + if (identical(this, other)) return true; + return other is ChatMessage && other.id == id; + } + + @override + int get hashCode => id.hashCode; +} diff --git a/app/lib/models/delivery_station.dart b/app/lib/models/delivery_station.dart new file mode 100644 index 0000000..403cdd5 --- /dev/null +++ b/app/lib/models/delivery_station.dart @@ -0,0 +1,136 @@ +import 'task.dart'; + +class DeliveryStation { + final int stationOrder; + final String company; + final String? salutation; + final String firstName; + final String lastName; + final String phone; + final String street; + final String houseNumber; + final String addressAddition; + final String zip; + final String city; + final String deliveryDate; + final String deliveryTime; + final List tasks; + + DeliveryStation({ + required this.stationOrder, + required this.company, + this.salutation, + required this.firstName, + required this.lastName, + required this.phone, + required this.street, + required this.houseNumber, + required this.addressAddition, + required this.zip, + required this.city, + required this.deliveryDate, + required this.deliveryTime, + required this.tasks, + }); + + static String _readString(dynamic value, {String fallback = ''}) { + if (value is String) { + return value; + } + if (value is num || value is bool) { + return value.toString(); + } + return fallback; + } + + factory DeliveryStation.fromJson(Map json) { + final stationOrder = + json['stationOrder'] is num + ? (json['stationOrder'] as num).toInt() + : int.tryParse(json['stationOrder']?.toString() ?? '') ?? 0; + + final tasks = + (json['tasks'] as List? ?? const []).map((rawTask) { + final taskJson = Map.from(rawTask as Map); + taskJson['stationOrder'] ??= stationOrder; + return Task.fromJson(taskJson); + }).toList() + ..sort((a, b) => (a.taskOrder ?? 0).compareTo(b.taskOrder ?? 0)); + + return DeliveryStation( + stationOrder: stationOrder, + company: _readString(json['company']), + salutation: json['salutation']?.toString(), + firstName: _readString(json['firstName']), + lastName: _readString(json['lastName']), + phone: _readString(json['phone']), + street: _readString(json['street']), + houseNumber: _readString(json['houseNumber']), + addressAddition: _readString(json['addressAddition']), + zip: _readString(json['zip']), + city: _readString(json['city']), + deliveryDate: _readString(json['deliveryDate']), + deliveryTime: _readString(json['deliveryTime']), + tasks: tasks, + ); + } + + Map toJson() { + return { + 'stationOrder': stationOrder, + 'company': company, + 'salutation': salutation, + 'firstName': firstName, + 'lastName': lastName, + 'phone': phone, + 'street': street, + 'houseNumber': houseNumber, + 'addressAddition': addressAddition, + 'zip': zip, + 'city': city, + 'deliveryDate': deliveryDate, + 'deliveryTime': deliveryTime, + 'tasks': tasks.map((task) => task.toJson()).toList(), + }; + } + + DeliveryStation normalized() { + String t(String? value) => (value ?? '').trim(); + return DeliveryStation( + stationOrder: stationOrder, + company: t(company), + salutation: t(salutation), + firstName: t(firstName), + lastName: t(lastName), + phone: t(phone), + street: t(street), + houseNumber: t(houseNumber), + addressAddition: t(addressAddition), + zip: t(zip), + city: t(city), + deliveryDate: t(deliveryDate), + deliveryTime: t(deliveryTime), + tasks: tasks, + ); + } + + String get displayName { + final name = [ + firstName.trim(), + lastName.trim(), + ].where((part) => part.isNotEmpty).join(' '); + return name.isNotEmpty ? name : company; + } + + String get formattedAddress { + final streetPart = [ + street.trim(), + houseNumber.trim(), + ].where((part) => part.isNotEmpty).join(' '); + final cityPart = [ + zip.trim(), + city.trim(), + ].where((part) => part.isNotEmpty).join(' '); + return [streetPart, cityPart].where((part) => part.isNotEmpty).join(', '); + } +} diff --git a/app/lib/models/job.dart b/app/lib/models/job.dart new file mode 100644 index 0000000..b56103a --- /dev/null +++ b/app/lib/models/job.dart @@ -0,0 +1,542 @@ +import 'cargo_item.dart'; +import 'delivery_station.dart'; +import 'task.dart'; + +class Job { + final String id; // Will store the timestamp as string + final String jobNumber; + final String status; + final DateTime createdAt; + final DateTime updatedAt; + final String createdBy; + final String customerSelection; + final String pickupCompany; + final String? pickupSalutation; + final String pickupFirstName; + final String pickupLastName; + final String pickupPhone; + final String pickupStreet; + final String pickupHouseNumber; + final String pickupAddressAddition; + final String pickupZip; + final String pickupCity; + final String deliveryCompany; + final String? deliverySalutation; + final String deliveryFirstName; + final String deliveryLastName; + final String deliveryPhone; + final String deliveryStreet; + final String deliveryHouseNumber; + final String deliveryAddressAddition; + final String deliveryZip; + final String deliveryCity; + final bool digitalProcessing; + final String appUser; + final String pickupDate; + final String pickupTime; + final String deliveryDate; + final String deliveryTime; + final String remark; + final double price; + final bool draft; + + // New fields for cargoItems and tasks + final List cargoItems; + final List deliveryStations; + final List tasks; + final String deliveryCitiesDisplay; + final String firstDeliveryCity; + final String lastDeliveryCity; + + // Legacy fields for backward compatibility + final String title; + final String description; + final String priority; + final DateTime? dueDate; + final String? assignedTo; + final String? location; + final Map? additionalData; + + Job({ + required this.id, + required this.jobNumber, + required this.status, + required this.createdAt, + required this.updatedAt, + required this.createdBy, + required this.customerSelection, + required this.pickupCompany, + this.pickupSalutation, + required this.pickupFirstName, + required this.pickupLastName, + required this.pickupPhone, + required this.pickupStreet, + required this.pickupHouseNumber, + required this.pickupAddressAddition, + required this.pickupZip, + required this.pickupCity, + required this.deliveryCompany, + this.deliverySalutation, + required this.deliveryFirstName, + required this.deliveryLastName, + required this.deliveryPhone, + required this.deliveryStreet, + required this.deliveryHouseNumber, + required this.deliveryAddressAddition, + required this.deliveryZip, + required this.deliveryCity, + required this.digitalProcessing, + required this.appUser, + required this.pickupDate, + required this.pickupTime, + required this.deliveryDate, + required this.deliveryTime, + required this.remark, + required this.price, + required this.draft, + // New fields for cargoItems and tasks + required this.cargoItems, + required this.tasks, + this.deliveryStations = const [], + this.deliveryCitiesDisplay = '', + this.firstDeliveryCity = '', + this.lastDeliveryCity = '', + // Legacy fields + String? title, + String? description, + this.priority = 'normal', + this.dueDate, + this.assignedTo, + this.location, + this.additionalData, + }) : title = title ?? 'Job $jobNumber', + description = + description ?? 'Transport von $pickupCity nach $deliveryCity'; + + /// Parse DateTime from either string or array format + static DateTime? _parseDateTime(dynamic value) { + if (value == null) return null; + + if (value is String) { + return DateTime.tryParse(value); + } + + if (value is List && value.isNotEmpty) { + try { + // Array format: [year, month, day, hour, minute, second, nanosecond] + final year = value[0] as int; + final month = value.length > 1 ? value[1] as int : 1; + final day = value.length > 2 ? value[2] as int : 1; + final hour = value.length > 3 ? value[3] as int : 0; + final minute = value.length > 4 ? value[4] as int : 0; + final second = value.length > 5 ? value[5] as int : 0; + final nanosecond = value.length > 6 ? value[6] as int : 0; + + // Convert nanoseconds to microseconds (divide by 1000) + final microsecond = nanosecond ~/ 1000; + + return DateTime(year, month, day, hour, minute, second, microsecond); + } catch (e) { + return null; + } + } + + return null; + } + + /// Parse time string (for pickupTime/deliveryTime) + static String? _parseTimeString(dynamic value) { + if (value == null) return null; + if (value is String && value.isNotEmpty && value != 'null') { + return value; + } + return null; + } + + /// Parse date string from either string or array format (for pickupDate/deliveryDate) + static String? _parseDateString(dynamic value) { + if (value == null) return null; + + if (value is String) { + return value; + } + + if (value is List && value.isNotEmpty) { + try { + // Array format: [year, month, day] + final year = value[0] as int; + final month = value.length > 1 ? value[1] as int : 1; + final day = value.length > 2 ? value[2] as int : 1; + + // Format as ISO date string + return '${year.toString().padLeft(4, '0')}-${month.toString().padLeft(2, '0')}-${day.toString().padLeft(2, '0')}'; + } catch (e) { + return null; + } + } + + return value.toString(); + } + + static String _readString(dynamic value, {String fallback = ''}) { + if (value is String) { + return value; + } + if (value is num || value is bool) { + return value.toString(); + } + return fallback; + } + + factory Job.fromJson(Map json) { + // Support both flat structure and { job: {...}, cargoItems: [...], tasks: [...] } + final jobJson = + (json['job'] is Map) + ? Map.from(json['job'] as Map) + : json; + + // Determine the id robustly. Prefer the inner job.id if present. + String idValue = ''; + final dynamic innerId = jobJson['id']; + if (innerId is Map) { + // Some backends send an object; try common fields + idValue = + innerId['timestamp']?.toString() ?? + innerId[r'$oid']?.toString() ?? + ''; + } else if (innerId != null) { + idValue = innerId.toString(); + } + if (idValue.isEmpty) { + // Fallback to outer json['id'] if provided + final dynamic outerId = json['id']; + if (outerId is Map) { + idValue = + outerId['timestamp']?.toString() ?? + outerId[r'$oid']?.toString() ?? + ''; + } else if (outerId != null) { + idValue = outerId.toString(); + } + } + + // Parse cargoItems array + List cargoItems = []; + if (json['cargoItems'] is List) { + cargoItems = + (json['cargoItems'] as List) + .map( + (item) => + CargoItem.fromJson(Map.from(item as Map)), + ) + .toList(); + } + + // Parse delivery stations and prefer their tasks over the legacy top-level tasks. + List deliveryStations = []; + final deliveryStationsRaw = + jobJson['deliveryStations'] ?? json['deliveryStations']; + if (deliveryStationsRaw is List) { + deliveryStations = + deliveryStationsRaw + .map( + (station) => DeliveryStation.fromJson( + Map.from(station as Map), + ), + ) + .toList() + ..sort((a, b) => a.stationOrder.compareTo(b.stationOrder)); + } + + int compareTasks(Task a, Task b) { + final stationCompare = (a.stationOrder ?? -1).compareTo( + b.stationOrder ?? -1, + ); + if (stationCompare != 0) { + return stationCompare; + } + return (a.taskOrder ?? 0).compareTo(b.taskOrder ?? 0); + } + + // Parse tasks array + List tasks = []; + if (deliveryStations.isNotEmpty) { + tasks = + deliveryStations.expand((station) => station.tasks).toList() + ..sort(compareTasks); + } else if (json['tasks'] is List) { + tasks = + (json['tasks'] as List) + .map( + (task) => Task.fromJson(Map.from(task as Map)), + ) + .toList() + ..sort(compareTasks); + } else if (jobJson['tasks'] is List) { + tasks = + (jobJson['tasks'] as List) + .map( + (task) => Task.fromJson(Map.from(task as Map)), + ) + .toList() + ..sort(compareTasks); + } + + // As a last resort, derive a deterministic id if still empty (avoid UNIQUE '' collisions) + if (idValue.isEmpty) { + final jobNumber = jobJson['jobNumber']?.toString(); + final createdAt = jobJson['createdAt']?.toString(); + idValue = + (jobNumber?.isNotEmpty == true) + ? 'jobnum:$jobNumber' + : (createdAt?.isNotEmpty == true + ? 'ts:${createdAt!}' + : DateTime.now().millisecondsSinceEpoch.toString()); + } + + return Job( + id: idValue, + jobNumber: jobJson['jobNumber']?.toString() ?? '', + status: jobJson['status']?.toString() ?? 'UNKNOWN', + createdAt: _parseDateTime(jobJson['createdAt']) ?? DateTime.now(), + updatedAt: _parseDateTime(jobJson['updatedAt']) ?? DateTime.now(), + createdBy: jobJson['createdBy']?.toString() ?? '', + customerSelection: jobJson['customerSelection']?.toString() ?? '', + pickupCompany: jobJson['pickupCompany']?.toString() ?? '', + pickupSalutation: jobJson['pickupSalutation']?.toString(), + pickupFirstName: jobJson['pickupFirstName']?.toString() ?? '', + pickupLastName: jobJson['pickupLastName']?.toString() ?? '', + pickupPhone: jobJson['pickupPhone']?.toString() ?? '', + pickupStreet: jobJson['pickupStreet']?.toString() ?? '', + pickupHouseNumber: jobJson['pickupHouseNumber']?.toString() ?? '', + pickupAddressAddition: jobJson['pickupAddressAddition']?.toString() ?? '', + pickupZip: jobJson['pickupZip']?.toString() ?? '', + pickupCity: jobJson['pickupCity']?.toString() ?? '', + deliveryCompany: jobJson['deliveryCompany']?.toString() ?? '', + deliverySalutation: jobJson['deliverySalutation']?.toString(), + deliveryFirstName: jobJson['deliveryFirstName']?.toString() ?? '', + deliveryLastName: jobJson['deliveryLastName']?.toString() ?? '', + deliveryPhone: jobJson['deliveryPhone']?.toString() ?? '', + deliveryStreet: jobJson['deliveryStreet']?.toString() ?? '', + deliveryHouseNumber: jobJson['deliveryHouseNumber']?.toString() ?? '', + deliveryAddressAddition: + jobJson['deliveryAddressAddition']?.toString() ?? '', + deliveryZip: jobJson['deliveryZip']?.toString() ?? '', + deliveryCity: jobJson['deliveryCity']?.toString() ?? '', + digitalProcessing: jobJson['digitalProcessing'] == true, + appUser: jobJson['appUser']?.toString() ?? '', + pickupDate: _parseDateString(jobJson['pickupDate']) ?? '', + pickupTime: _parseTimeString(jobJson['pickupTime']) ?? '', + deliveryDate: _parseDateString(jobJson['deliveryDate']) ?? '', + deliveryTime: _parseTimeString(jobJson['deliveryTime']) ?? '', + remark: _readString(jobJson['remark']), + price: (jobJson['price'] is num) ? jobJson['price'].toDouble() : 0.0, + draft: jobJson['draft'] == true, + // New fields for cargoItems and tasks + cargoItems: cargoItems, + deliveryStations: deliveryStations, + tasks: tasks, + deliveryCitiesDisplay: _readString(jobJson['deliveryCitiesDisplay']), + firstDeliveryCity: _readString(jobJson['firstDeliveryCity']), + lastDeliveryCity: _readString(jobJson['lastDeliveryCity']), + // Legacy fields for backward compatibility + title: jobJson['title']?.toString(), + description: jobJson['description']?.toString(), + priority: jobJson['priority']?.toString() ?? 'normal', + dueDate: _parseDateTime(jobJson['dueDate']), + assignedTo: jobJson['assignedTo']?.toString(), + location: jobJson['location']?.toString(), + additionalData: jobJson['additionalData'] as Map?, + ); + } + + /// Return a normalized copy (trim strings, null→'') + Job normalized() { + String t(String? s) => (s ?? '').trim(); + return Job( + id: id, + jobNumber: t(jobNumber), + status: t(status), + createdAt: createdAt, + updatedAt: updatedAt, + createdBy: t(createdBy), + customerSelection: t(customerSelection), + pickupCompany: t(pickupCompany), + pickupSalutation: t(pickupSalutation), + pickupFirstName: t(pickupFirstName), + pickupLastName: t(pickupLastName), + pickupPhone: t(pickupPhone), + pickupStreet: t(pickupStreet), + pickupHouseNumber: t(pickupHouseNumber), + pickupAddressAddition: t(pickupAddressAddition), + pickupZip: t(pickupZip), + pickupCity: t(pickupCity), + deliveryCompany: t(deliveryCompany), + deliverySalutation: t(deliverySalutation), + deliveryFirstName: t(deliveryFirstName), + deliveryLastName: t(deliveryLastName), + deliveryPhone: t(deliveryPhone), + deliveryStreet: t(deliveryStreet), + deliveryHouseNumber: t(deliveryHouseNumber), + deliveryAddressAddition: t(deliveryAddressAddition), + deliveryZip: t(deliveryZip), + deliveryCity: t(deliveryCity), + digitalProcessing: digitalProcessing, + appUser: t(appUser), + pickupDate: t(pickupDate), + pickupTime: t(pickupTime), + deliveryDate: t(deliveryDate), + deliveryTime: t(deliveryTime), + remark: t(remark), + price: price, + draft: draft, + cargoItems: cargoItems, + deliveryStations: + deliveryStations.map((station) => station.normalized()).toList(), + tasks: tasks, + deliveryCitiesDisplay: t(deliveryCitiesDisplay), + firstDeliveryCity: t(firstDeliveryCity), + lastDeliveryCity: t(lastDeliveryCity), + title: t(title), + description: t(description), + priority: t(priority), + dueDate: dueDate, + assignedTo: t(assignedTo), + location: t(location), + additionalData: additionalData, + ); + } + + Map toJson() { + return { + 'id': id, + 'jobNumber': jobNumber, + 'status': status, + 'createdAt': createdAt.toIso8601String(), + 'updatedAt': updatedAt.toIso8601String(), + 'createdBy': createdBy, + 'customerSelection': customerSelection, + 'pickupCompany': pickupCompany, + 'pickupSalutation': pickupSalutation, + 'pickupFirstName': pickupFirstName, + 'pickupLastName': pickupLastName, + 'pickupPhone': pickupPhone, + 'pickupStreet': pickupStreet, + 'pickupHouseNumber': pickupHouseNumber, + 'pickupAddressAddition': pickupAddressAddition, + 'pickupZip': pickupZip, + 'pickupCity': pickupCity, + 'deliveryCompany': deliveryCompany, + 'deliverySalutation': deliverySalutation, + 'deliveryFirstName': deliveryFirstName, + 'deliveryLastName': deliveryLastName, + 'deliveryPhone': deliveryPhone, + 'deliveryStreet': deliveryStreet, + 'deliveryHouseNumber': deliveryHouseNumber, + 'deliveryAddressAddition': deliveryAddressAddition, + 'deliveryZip': deliveryZip, + 'deliveryCity': deliveryCity, + 'digitalProcessing': digitalProcessing, + 'appUser': appUser, + 'pickupDate': pickupDate, + 'pickupTime': pickupTime, + 'deliveryDate': deliveryDate, + 'deliveryTime': deliveryTime, + 'remark': remark, + 'price': price, + 'draft': draft, + // New fields for cargoItems and tasks + 'cargoItems': cargoItems.map((item) => item.toJson()).toList(), + 'deliveryStations': + deliveryStations.map((station) => station.toJson()).toList(), + 'tasks': tasks.map((task) => task.toJson()).toList(), + 'deliveryCitiesDisplay': deliveryCitiesDisplay, + 'firstDeliveryCity': firstDeliveryCity, + 'lastDeliveryCity': lastDeliveryCity, + // Legacy fields + 'title': title, + 'description': description, + 'priority': priority, + 'dueDate': dueDate?.toIso8601String(), + 'assignedTo': assignedTo, + 'location': location, + 'additionalData': additionalData, + }; + } + + @override + String toString() { + return 'Job(id: $id, title: $title, status: $status, priority: $priority)'; + } + + @override + bool operator ==(Object other) { + if (identical(this, other)) return true; + return other is Job && other.id == id; + } + + @override + int get hashCode => id.hashCode; + + /// Get status color for UI display + String get statusColor { + switch (status.toLowerCase()) { + case 'created': + return 'orange'; + case 'pending': + case 'assigned': + return 'orange'; + case 'in_progress': + case 'started': + return 'blue'; + case 'completed': + case 'done': + return 'green'; + case 'cancelled': + case 'failed': + return 'red'; + default: + return 'grey'; + } + } + + /// Get status display text in German + String get statusDisplayText { + switch (status.toLowerCase()) { + case 'created': + return 'Erstellt'; + case 'pending': + return 'Wartend'; + case 'assigned': + return 'Zugewiesen'; + case 'in_progress': + case 'started': + return 'In Bearbeitung'; + case 'completed': + case 'done': + return 'Abgeschlossen'; + case 'cancelled': + return 'Abgebrochen'; + case 'failed': + return 'Fehlgeschlagen'; + default: + return status; // Show the original status if not mapped + } + } + + /// Get priority display text in German + String get priorityDisplayText { + switch (priority.toLowerCase()) { + case 'low': + return 'Niedrig'; + case 'normal': + return 'Normal'; + case 'high': + return 'Hoch'; + case 'urgent': + return 'Dringend'; + default: + return 'Normal'; + } + } +} diff --git a/app/lib/models/message_envelope.dart b/app/lib/models/message_envelope.dart new file mode 100644 index 0000000..5370ffe --- /dev/null +++ b/app/lib/models/message_envelope.dart @@ -0,0 +1,90 @@ +/// Message Envelope for wrapping all WebSocket messages with metadata +/// +/// This provides reliable message delivery with acknowledgment mechanism +class MessageEnvelope { + /// Unique message identifier (UUID) + final String messageId; + + /// Timestamp when the message was created + final DateTime timestamp; + + /// Target topic + final String topic; + + /// Original message payload (can be Map or List) + final dynamic payload; + + /// Whether this message requires acknowledgment + final bool requiresAck; + + /// Number of retry attempts (for tracking) + final int retryCount; + + /// Optional expiration timestamp + final DateTime? expiresAt; + + MessageEnvelope({ + required this.messageId, + required this.timestamp, + required this.topic, + required this.payload, + this.requiresAck = true, + this.retryCount = 0, + this.expiresAt, + }); + + /// Create MessageEnvelope from JSON + factory MessageEnvelope.fromJson(Map json) { + return MessageEnvelope( + messageId: json['messageId'] as String, + timestamp: DateTime.parse(json['timestamp'] as String), + topic: json['topic'] as String, + payload: json['payload'], + requiresAck: json['requiresAck'] as bool? ?? true, + retryCount: json['retryCount'] as int? ?? 0, + expiresAt: json['expiresAt'] != null + ? DateTime.parse(json['expiresAt'] as String) + : null, + ); + } + + /// Convert MessageEnvelope to JSON + Map toJson() { + return { + 'messageId': messageId, + 'timestamp': timestamp.toIso8601String(), + 'topic': topic, + 'payload': payload, + 'requiresAck': requiresAck, + 'retryCount': retryCount, + if (expiresAt != null) 'expiresAt': expiresAt!.toIso8601String(), + }; + } + + /// Create a copy with updated fields + MessageEnvelope copyWith({ + String? messageId, + DateTime? timestamp, + String? topic, + dynamic payload, + bool? requiresAck, + int? retryCount, + DateTime? expiresAt, + }) { + return MessageEnvelope( + messageId: messageId ?? this.messageId, + timestamp: timestamp ?? this.timestamp, + topic: topic ?? this.topic, + payload: payload ?? this.payload, + requiresAck: requiresAck ?? this.requiresAck, + retryCount: retryCount ?? this.retryCount, + expiresAt: expiresAt ?? this.expiresAt, + ); + } + + @override + String toString() { + return 'MessageEnvelope(messageId: $messageId, topic: $topic, requiresAck: $requiresAck, retryCount: $retryCount)'; + } +} + diff --git a/app/lib/models/queued_message.dart b/app/lib/models/queued_message.dart new file mode 100644 index 0000000..8b4838d --- /dev/null +++ b/app/lib/models/queued_message.dart @@ -0,0 +1,51 @@ +class QueuedMessage { + final String id; + final String topic; + final Map payload; + final DateTime createdAt; + final int retryCount; + + QueuedMessage({ + required this.id, + required this.topic, + required this.payload, + required this.createdAt, + this.retryCount = 0, + }); + + factory QueuedMessage.fromJson(Map json) { + return QueuedMessage( + id: json['id'], + topic: json['topic'], + payload: Map.from(json['payload']), + createdAt: DateTime.parse(json['createdAt']), + retryCount: json['retryCount'] ?? 0, + ); + } + + Map toJson() { + return { + 'id': id, + 'topic': topic, + 'payload': payload, + 'createdAt': createdAt.toIso8601String(), + 'retryCount': retryCount, + }; + } + + QueuedMessage copyWith({ + String? id, + String? topic, + Map? payload, + DateTime? createdAt, + int? retryCount, + }) { + return QueuedMessage( + id: id ?? this.id, + topic: topic ?? this.topic, + payload: payload ?? this.payload, + createdAt: createdAt ?? this.createdAt, + retryCount: retryCount ?? this.retryCount, + ); + } +} diff --git a/app/lib/models/remark_translation.dart b/app/lib/models/remark_translation.dart new file mode 100644 index 0000000..06285be --- /dev/null +++ b/app/lib/models/remark_translation.dart @@ -0,0 +1,20 @@ +/// Represents a translated remark in a specific language +class RemarkTranslation { + final String language; + final String text; + + RemarkTranslation({required this.language, required this.text}); + + factory RemarkTranslation.fromJson(Map json) { + return RemarkTranslation(language: json['language']?.toString() ?? '', text: json['text']?.toString() ?? ''); + } + + Map toJson() { + return {'language': language, 'text': text}; + } + + @override + String toString() { + return 'RemarkTranslation(language: $language, text: $text)'; + } +} diff --git a/app/lib/models/task.dart b/app/lib/models/task.dart new file mode 100644 index 0000000..da90e68 --- /dev/null +++ b/app/lib/models/task.dart @@ -0,0 +1,198 @@ +// Import all task types +import 'tasks/generic_task.dart'; +import 'tasks/confirmation_task.dart'; +import 'tasks/photo_task.dart'; +import 'tasks/todolist_task.dart'; +import 'tasks/signature_task.dart'; +import 'tasks/barcode_task.dart'; +import 'tasks/comment_task.dart'; + +abstract class Task { + final String id; + final String jobId; + final int? stationOrder; + final bool completed; + final bool optional; + final DateTime? completedAt; + final String? completedBy; + final int? taskOrder; + final String? title; + final String? description; + final String? displayName; + + Task({ + required this.id, + required this.jobId, + this.stationOrder, + this.completed = false, + this.optional = false, + this.completedAt, + this.completedBy, + this.taskOrder, + this.title, + this.description, + this.displayName, + }); + + factory Task.fromJson(Map json) { + // Get task specific data to determine task type + final taskSpecificData = json['taskSpecificData'] as Map?; + final taskType = + (taskSpecificData?['taskType'] ?? json['taskType'])?.toString(); + + // Create specific task type based on taskType + switch (taskType) { + case 'CONFIRMATION': + return ConfirmationTask.fromJson(json); + case 'PHOTO': + return PhotoTask.fromJson(json); + case 'TODOLIST': + return TodoListTask.fromJson(json); + case 'SIGNATURE': + return SignatureTask.fromJson(json); + case 'BARCODE': + return BarcodeTask.fromJson(json); + case 'COMMENT': + return CommentTask.fromJson(json); + case 'GENERIC': + return GenericTask.fromJson(json); + default: + // Fallback to a generic task if no specific type is found + return GenericTask.fromJson(json); + } + } + + Map toJson(); + + Task copyWith({ + String? id, + String? jobId, + int? stationOrder, + bool? completed, + bool? optional, + DateTime? completedAt, + String? completedBy, + int? taskOrder, + String? title, + String? description, + String? displayName, + }); + + @override + String toString() { + return 'Task(id: $id, jobId: $jobId, stationOrder: $stationOrder, completed: $completed, taskOrder: $taskOrder)'; + } + + @override + bool operator ==(Object other) { + if (identical(this, other)) return true; + return other is Task && other.id == id; + } + + @override + int get hashCode => id.hashCode; + + /// Parse DateTime from either string or array format + static DateTime? _parseDateTime(dynamic value) { + if (value == null) return null; + + if (value is String) { + return DateTime.tryParse(value); + } + + if (value is List && value.isNotEmpty) { + try { + // Array format: [year, month, day, hour, minute, second, microsecond] + final year = value[0] as int; + final month = value.length > 1 ? value[1] as int : 1; + final day = value.length > 2 ? value[2] as int : 1; + final hour = value.length > 3 ? value[3] as int : 0; + final minute = value.length > 4 ? value[4] as int : 0; + final second = value.length > 5 ? value[5] as int : 0; + final microsecond = value.length > 6 ? value[6] as int : 0; + + return DateTime(year, month, day, hour, minute, second, microsecond); + } catch (e) { + return null; + } + } + + return null; + } + + static String? _readOptionalString(dynamic value) { + if (value == null) { + return null; + } + if (value is String) { + return value; + } + if (value is num || value is bool) { + return value.toString(); + } + return null; + } + + static int? _readOptionalInt(dynamic value) { + if (value is int) { + return value; + } + if (value is num) { + return value.toInt(); + } + if (value is String) { + return int.tryParse(value); + } + return null; + } + + // Helper method to parse common properties + static Map parseCommonProperties(Map json) { + // Parse the complex id object - can be either a Map or a simple string + String idValue = ''; + if (json['id'] is Map) { + final idMap = json['id'] as Map; + idValue = idMap['timestamp']?.toString() ?? ''; + } else { + idValue = json['id']?.toString() ?? ''; + } + + // Parse the complex jobId object - can be either a Map or a simple string + String jobIdValue = ''; + if (json['jobId'] is Map) { + final jobIdMap = json['jobId'] as Map; + jobIdValue = jobIdMap['timestamp']?.toString() ?? ''; + } else { + jobIdValue = json['jobId']?.toString() ?? ''; + } + + // Parse completedAt using the helper method to handle both string and array formats + final completedAt = _parseDateTime(json['completedAt']); + + final taskSpecificData = json['taskSpecificData'] as Map?; + final stationOrder = _readOptionalInt(json['stationOrder']); + final title = _readOptionalString( + json['title'] ?? taskSpecificData?['title'], + ); + final description = _readOptionalString( + json['description'] ?? taskSpecificData?['description'], + ); + final displayName = _readOptionalString( + json['displayName'] ?? taskSpecificData?['displayName'], + ); + + return { + 'id': idValue, + 'jobId': jobIdValue, + 'stationOrder': stationOrder, + 'completed': json['completed'] ?? false, + 'optional': json['optional'] ?? false, + 'completedAt': completedAt, + 'completedBy': json['completedBy'], + 'taskOrder': json['taskOrder'], + 'title': title, + 'description': description, + 'displayName': displayName, + }; + } +} diff --git a/app/lib/models/tasks/barcode_task.dart b/app/lib/models/tasks/barcode_task.dart new file mode 100644 index 0000000..4bac09a --- /dev/null +++ b/app/lib/models/tasks/barcode_task.dart @@ -0,0 +1,99 @@ +import '../task.dart'; + +// Barcode Task +class BarcodeTask extends Task { + final int minBarcodeCount; + final int maxBarcodeCount; + + BarcodeTask({ + required super.id, + required super.jobId, + required this.minBarcodeCount, + required this.maxBarcodeCount, + super.stationOrder, + super.completed = false, + super.optional = false, + super.completedAt, + super.completedBy, + super.taskOrder, + super.title, + super.description, + super.displayName, + }); + + factory BarcodeTask.fromJson(Map json) { + final commonProps = Task.parseCommonProperties(json); + final taskSpecificData = json['taskSpecificData'] as Map; + + return BarcodeTask( + id: commonProps['id'], + jobId: commonProps['jobId'], + stationOrder: commonProps['stationOrder'], + completed: commonProps['completed'], + optional: commonProps['optional'], + completedAt: commonProps['completedAt'], + completedBy: commonProps['completedBy'], + taskOrder: commonProps['taskOrder'], + title: commonProps['title'], + description: commonProps['description'], + displayName: commonProps['displayName'], + minBarcodeCount: taskSpecificData['minBarcodeCount'] ?? 1, + maxBarcodeCount: taskSpecificData['maxBarcodeCount'] ?? 10, + ); + } + + @override + Map toJson() { + return { + 'id': id, + 'jobId': jobId, + 'stationOrder': stationOrder, + 'completed': completed, + 'optional': optional, + 'completedAt': completedAt?.toIso8601String(), + 'completedBy': completedBy, + 'taskOrder': taskOrder, + 'description': description, + 'displayName': displayName, + 'taskSpecificData': { + 'taskType': 'BARCODE', + 'title': title, + 'minBarcodeCount': minBarcodeCount, + 'maxBarcodeCount': maxBarcodeCount, + }, + }; + } + + @override + BarcodeTask copyWith({ + String? id, + String? jobId, + int? stationOrder, + bool? completed, + bool? optional, + DateTime? completedAt, + String? completedBy, + int? taskOrder, + String? title, + String? description, + String? displayName, + int? minBarcodeCount, + int? maxBarcodeCount, + }) { + return BarcodeTask( + id: id ?? this.id, + jobId: jobId ?? this.jobId, + stationOrder: stationOrder ?? this.stationOrder, + completed: completed ?? this.completed, + optional: optional ?? this.optional, + completedAt: completedAt ?? this.completedAt, + completedBy: completedBy ?? this.completedBy, + taskOrder: taskOrder ?? this.taskOrder, + title: title ?? this.title, + description: description ?? this.description, + displayName: displayName ?? this.displayName, + minBarcodeCount: minBarcodeCount ?? this.minBarcodeCount, + maxBarcodeCount: maxBarcodeCount ?? this.maxBarcodeCount, + ); + } +} diff --git a/app/lib/models/tasks/comment_task.dart b/app/lib/models/tasks/comment_task.dart new file mode 100644 index 0000000..f27f13b --- /dev/null +++ b/app/lib/models/tasks/comment_task.dart @@ -0,0 +1,99 @@ +import '../task.dart'; + +// Comment Task +class CommentTask extends Task { + final String commentText; + final bool required; + + CommentTask({ + required super.id, + required super.jobId, + required this.commentText, + this.required = false, + super.stationOrder, + super.completed = false, + super.optional = false, + super.completedAt, + super.completedBy, + super.taskOrder, + super.title, + super.description, + super.displayName, + }); + + factory CommentTask.fromJson(Map json) { + final commonProps = Task.parseCommonProperties(json); + final taskSpecificData = json['taskSpecificData'] as Map; + + return CommentTask( + id: commonProps['id'], + jobId: commonProps['jobId'], + stationOrder: commonProps['stationOrder'], + completed: commonProps['completed'], + optional: commonProps['optional'], + completedAt: commonProps['completedAt'], + completedBy: commonProps['completedBy'], + taskOrder: commonProps['taskOrder'], + title: commonProps['title'], + description: commonProps['description'], + displayName: commonProps['displayName'], + commentText: taskSpecificData['commentText'] ?? '', + required: taskSpecificData['required'] ?? false, + ); + } + + @override + Map toJson() { + return { + 'id': id, + 'jobId': jobId, + 'stationOrder': stationOrder, + 'completed': completed, + 'optional': optional, + 'completedAt': completedAt?.toIso8601String(), + 'completedBy': completedBy, + 'taskOrder': taskOrder, + 'description': description, + 'displayName': displayName, + 'taskSpecificData': { + 'taskType': 'COMMENT', + 'title': title, + 'commentText': commentText, + 'required': required, + }, + }; + } + + @override + CommentTask copyWith({ + String? id, + String? jobId, + int? stationOrder, + bool? completed, + bool? optional, + DateTime? completedAt, + String? completedBy, + int? taskOrder, + String? title, + String? description, + String? displayName, + String? commentText, + bool? required, + }) { + return CommentTask( + id: id ?? this.id, + jobId: jobId ?? this.jobId, + stationOrder: stationOrder ?? this.stationOrder, + completed: completed ?? this.completed, + optional: optional ?? this.optional, + completedAt: completedAt ?? this.completedAt, + completedBy: completedBy ?? this.completedBy, + taskOrder: taskOrder ?? this.taskOrder, + title: title ?? this.title, + description: description ?? this.description, + displayName: displayName ?? this.displayName, + commentText: commentText ?? this.commentText, + required: required ?? this.required, + ); + } +} diff --git a/app/lib/models/tasks/confirmation_task.dart b/app/lib/models/tasks/confirmation_task.dart new file mode 100644 index 0000000..f3787ae --- /dev/null +++ b/app/lib/models/tasks/confirmation_task.dart @@ -0,0 +1,95 @@ +import '../task.dart'; + +// Confirmation Task +class ConfirmationTask extends Task { + final String buttonText; + + ConfirmationTask({ + required super.id, + required super.jobId, + required this.buttonText, + super.stationOrder, + super.completed = false, + super.optional = false, + super.completedAt, + super.completedBy, + super.taskOrder, + super.title, + super.description, + super.displayName, + }); + + factory ConfirmationTask.fromJson(Map json) { + final commonProps = Task.parseCommonProperties(json); + final taskSpecificData = json['taskSpecificData'] as Map; + final buttonText = + taskSpecificData['buttonText']?.toString() ?? 'Bestätigen'; + + return ConfirmationTask( + id: commonProps['id'], + jobId: commonProps['jobId'], + stationOrder: commonProps['stationOrder'], + completed: commonProps['completed'], + optional: commonProps['optional'], + completedAt: commonProps['completedAt'], + completedBy: commonProps['completedBy'], + taskOrder: commonProps['taskOrder'], + title: commonProps['title'], + description: commonProps['description'], + displayName: commonProps['displayName'], + buttonText: buttonText, + ); + } + + @override + Map toJson() { + return { + 'id': id, + 'jobId': jobId, + 'stationOrder': stationOrder, + 'completed': completed, + 'optional': optional, + 'completedAt': completedAt?.toIso8601String(), + 'completedBy': completedBy, + 'taskOrder': taskOrder, + 'description': description, + 'displayName': displayName, + 'taskSpecificData': { + 'taskType': 'CONFIRMATION', + 'title': title, + 'buttonText': buttonText, + }, + }; + } + + @override + ConfirmationTask copyWith({ + String? id, + String? jobId, + int? stationOrder, + bool? completed, + bool? optional, + DateTime? completedAt, + String? completedBy, + int? taskOrder, + String? title, + String? description, + String? displayName, + String? buttonText, + }) { + return ConfirmationTask( + id: id ?? this.id, + jobId: jobId ?? this.jobId, + stationOrder: stationOrder ?? this.stationOrder, + completed: completed ?? this.completed, + optional: optional ?? this.optional, + completedAt: completedAt ?? this.completedAt, + completedBy: completedBy ?? this.completedBy, + taskOrder: taskOrder ?? this.taskOrder, + title: title ?? this.title, + description: description ?? this.description, + displayName: displayName ?? this.displayName, + buttonText: buttonText ?? this.buttonText, + ); + } +} diff --git a/app/lib/models/tasks/generic_task.dart b/app/lib/models/tasks/generic_task.dart new file mode 100644 index 0000000..2bb2c00 --- /dev/null +++ b/app/lib/models/tasks/generic_task.dart @@ -0,0 +1,81 @@ +import '../task.dart'; + +// Generic Task implementation for fallback +class GenericTask extends Task { + GenericTask({ + required super.id, + required super.jobId, + super.stationOrder, + super.completed = false, + super.optional = false, + super.completedAt, + super.completedBy, + super.taskOrder, + super.title, + super.description, + super.displayName, + }); + + factory GenericTask.fromJson(Map json) { + final commonProps = Task.parseCommonProperties(json); + return GenericTask( + id: commonProps['id'], + jobId: commonProps['jobId'], + stationOrder: commonProps['stationOrder'], + completed: commonProps['completed'], + optional: commonProps['optional'], + completedAt: commonProps['completedAt'], + completedBy: commonProps['completedBy'], + taskOrder: commonProps['taskOrder'], + title: commonProps['title'], + description: commonProps['description'], + displayName: commonProps['displayName'], + ); + } + + @override + Map toJson() { + return { + 'id': id, + 'jobId': jobId, + 'stationOrder': stationOrder, + 'completed': completed, + 'optional': optional, + 'completedAt': completedAt?.toIso8601String(), + 'completedBy': completedBy, + 'taskOrder': taskOrder, + 'description': description, + 'displayName': displayName, + 'taskSpecificData': {'taskType': 'GENERIC', 'title': title}, + }; + } + + @override + GenericTask copyWith({ + String? id, + String? jobId, + int? stationOrder, + bool? completed, + bool? optional, + DateTime? completedAt, + String? completedBy, + int? taskOrder, + String? title, + String? description, + String? displayName, + }) { + return GenericTask( + id: id ?? this.id, + jobId: jobId ?? this.jobId, + stationOrder: stationOrder ?? this.stationOrder, + completed: completed ?? this.completed, + optional: optional ?? this.optional, + completedAt: completedAt ?? this.completedAt, + completedBy: completedBy ?? this.completedBy, + taskOrder: taskOrder ?? this.taskOrder, + title: title ?? this.title, + description: description ?? this.description, + displayName: displayName ?? this.displayName, + ); + } +} diff --git a/app/lib/models/tasks/photo_task.dart b/app/lib/models/tasks/photo_task.dart new file mode 100644 index 0000000..0a3923a --- /dev/null +++ b/app/lib/models/tasks/photo_task.dart @@ -0,0 +1,99 @@ +import '../task.dart'; + +// Photo Task +class PhotoTask extends Task { + final int minPhotoCount; + final int maxPhotoCount; + + PhotoTask({ + required super.id, + required super.jobId, + required this.minPhotoCount, + required this.maxPhotoCount, + super.stationOrder, + super.completed = false, + super.optional = false, + super.completedAt, + super.completedBy, + super.taskOrder, + super.title, + super.description, + super.displayName, + }); + + factory PhotoTask.fromJson(Map json) { + final commonProps = Task.parseCommonProperties(json); + final taskSpecificData = json['taskSpecificData'] as Map; + + return PhotoTask( + id: commonProps['id'], + jobId: commonProps['jobId'], + stationOrder: commonProps['stationOrder'], + completed: commonProps['completed'], + optional: commonProps['optional'], + completedAt: commonProps['completedAt'], + completedBy: commonProps['completedBy'], + taskOrder: commonProps['taskOrder'], + title: commonProps['title'], + description: commonProps['description'], + displayName: commonProps['displayName'], + minPhotoCount: taskSpecificData['minPhotoCount'] ?? 1, + maxPhotoCount: taskSpecificData['maxPhotoCount'] ?? 5, + ); + } + + @override + Map toJson() { + return { + 'id': id, + 'jobId': jobId, + 'stationOrder': stationOrder, + 'completed': completed, + 'optional': optional, + 'completedAt': completedAt?.toIso8601String(), + 'completedBy': completedBy, + 'taskOrder': taskOrder, + 'description': description, + 'displayName': displayName, + 'taskSpecificData': { + 'taskType': 'PHOTO', + 'title': title, + 'minPhotoCount': minPhotoCount, + 'maxPhotoCount': maxPhotoCount, + }, + }; + } + + @override + PhotoTask copyWith({ + String? id, + String? jobId, + int? stationOrder, + bool? completed, + bool? optional, + DateTime? completedAt, + String? completedBy, + int? taskOrder, + String? title, + String? description, + String? displayName, + int? minPhotoCount, + int? maxPhotoCount, + }) { + return PhotoTask( + id: id ?? this.id, + jobId: jobId ?? this.jobId, + stationOrder: stationOrder ?? this.stationOrder, + completed: completed ?? this.completed, + optional: optional ?? this.optional, + completedAt: completedAt ?? this.completedAt, + completedBy: completedBy ?? this.completedBy, + taskOrder: taskOrder ?? this.taskOrder, + title: title ?? this.title, + description: description ?? this.description, + displayName: displayName ?? this.displayName, + minPhotoCount: minPhotoCount ?? this.minPhotoCount, + maxPhotoCount: maxPhotoCount ?? this.maxPhotoCount, + ); + } +} diff --git a/app/lib/models/tasks/signature_task.dart b/app/lib/models/tasks/signature_task.dart new file mode 100644 index 0000000..41f4a75 --- /dev/null +++ b/app/lib/models/tasks/signature_task.dart @@ -0,0 +1,82 @@ +import '../task.dart'; + +// Signature Task +class SignatureTask extends Task { + SignatureTask({ + required super.id, + required super.jobId, + super.stationOrder, + super.completed = false, + super.optional = false, + super.completedAt, + super.completedBy, + super.taskOrder, + super.title, + super.description, + super.displayName, + }); + + factory SignatureTask.fromJson(Map json) { + final commonProps = Task.parseCommonProperties(json); + + return SignatureTask( + id: commonProps['id'], + jobId: commonProps['jobId'], + stationOrder: commonProps['stationOrder'], + completed: commonProps['completed'], + optional: commonProps['optional'], + completedAt: commonProps['completedAt'], + completedBy: commonProps['completedBy'], + taskOrder: commonProps['taskOrder'], + title: commonProps['title'], + description: commonProps['description'], + displayName: commonProps['displayName'], + ); + } + + @override + Map toJson() { + return { + 'id': id, + 'jobId': jobId, + 'stationOrder': stationOrder, + 'completed': completed, + 'optional': optional, + 'completedAt': completedAt?.toIso8601String(), + 'completedBy': completedBy, + 'taskOrder': taskOrder, + 'description': description, + 'displayName': displayName, + 'taskSpecificData': {'taskType': 'SIGNATURE', 'title': title}, + }; + } + + @override + SignatureTask copyWith({ + String? id, + String? jobId, + int? stationOrder, + bool? completed, + bool? optional, + DateTime? completedAt, + String? completedBy, + int? taskOrder, + String? title, + String? description, + String? displayName, + }) { + return SignatureTask( + id: id ?? this.id, + jobId: jobId ?? this.jobId, + stationOrder: stationOrder ?? this.stationOrder, + completed: completed ?? this.completed, + optional: optional ?? this.optional, + completedAt: completedAt ?? this.completedAt, + completedBy: completedBy ?? this.completedBy, + taskOrder: taskOrder ?? this.taskOrder, + title: title ?? this.title, + description: description ?? this.description, + displayName: displayName ?? this.displayName, + ); + } +} diff --git a/app/lib/models/tasks/todolist_task.dart b/app/lib/models/tasks/todolist_task.dart new file mode 100644 index 0000000..636607e --- /dev/null +++ b/app/lib/models/tasks/todolist_task.dart @@ -0,0 +1,96 @@ +import '../task.dart'; + +// TodoList Task +class TodoListTask extends Task { + final List todoItems; + + TodoListTask({ + required super.id, + required super.jobId, + required this.todoItems, + super.stationOrder, + super.completed = false, + super.optional = false, + super.completedAt, + super.completedBy, + super.taskOrder, + super.title, + super.description, + super.displayName, + }); + + factory TodoListTask.fromJson(Map json) { + final commonProps = Task.parseCommonProperties(json); + final taskSpecificData = json['taskSpecificData'] as Map; + + final rawItems = taskSpecificData['todoItems'] as List? ?? []; + final todoItems = rawItems.map((item) => item?.toString() ?? '').toList(); + + return TodoListTask( + id: commonProps['id'], + jobId: commonProps['jobId'], + stationOrder: commonProps['stationOrder'], + completed: commonProps['completed'], + optional: commonProps['optional'], + completedAt: commonProps['completedAt'], + completedBy: commonProps['completedBy'], + taskOrder: commonProps['taskOrder'], + title: commonProps['title'], + description: commonProps['description'], + displayName: commonProps['displayName'], + todoItems: todoItems, + ); + } + + @override + Map toJson() { + return { + 'id': id, + 'jobId': jobId, + 'stationOrder': stationOrder, + 'completed': completed, + 'optional': optional, + 'completedAt': completedAt?.toIso8601String(), + 'completedBy': completedBy, + 'taskOrder': taskOrder, + 'description': description, + 'displayName': displayName, + 'taskSpecificData': { + 'taskType': 'TODOLIST', + 'title': title, + 'todoItems': todoItems, + }, + }; + } + + @override + TodoListTask copyWith({ + String? id, + String? jobId, + int? stationOrder, + bool? completed, + bool? optional, + DateTime? completedAt, + String? completedBy, + int? taskOrder, + String? title, + String? description, + String? displayName, + List? todoItems, + }) { + return TodoListTask( + id: id ?? this.id, + jobId: jobId ?? this.jobId, + stationOrder: stationOrder ?? this.stationOrder, + completed: completed ?? this.completed, + optional: optional ?? this.optional, + completedAt: completedAt ?? this.completedAt, + completedBy: completedBy ?? this.completedBy, + taskOrder: taskOrder ?? this.taskOrder, + title: title ?? this.title, + description: description ?? this.description, + displayName: displayName ?? this.displayName, + todoItems: todoItems ?? this.todoItems, + ); + } +} diff --git a/app/lib/navigation_observer.dart b/app/lib/navigation_observer.dart new file mode 100644 index 0000000..fb33c21 --- /dev/null +++ b/app/lib/navigation_observer.dart @@ -0,0 +1,4 @@ +import 'package:flutter/material.dart'; + +final RouteObserver> routeObserver = RouteObserver>(); + diff --git a/app/lib/objectbox-model.json b/app/lib/objectbox-model.json new file mode 100644 index 0000000..50f54ee --- /dev/null +++ b/app/lib/objectbox-model.json @@ -0,0 +1,281 @@ +{ + "_note1": "KEEP THIS FILE! Check it into a version control system (VCS) like git.", + "_note2": "ObjectBox manages crucial IDs for your object model. See docs for details.", + "_note3": "If you have VCS merge conflicts, you must resolve them according to ObjectBox docs.", + "entities": [ + { + "id": "1:7611693027744165533", + "lastPropertyId": "12:2309286538364575316", + "name": "ChatMessageEntity", + "properties": [ + { + "id": "1:2877174849434222825", + "name": "id", + "type": 6, + "flags": 1 + }, + { + "id": "2:7133214518465925033", + "name": "messageId", + "indexId": "1:5239829446791635795", + "type": 9, + "flags": 2080 + }, + { + "id": "3:4299321820179972091", + "name": "conversationKey", + "indexId": "2:7958984541640853733", + "type": 9, + "flags": 2048 + }, + { + "id": "4:5939280612219671854", + "name": "content", + "type": 9 + }, + { + "id": "5:3937520230579179052", + "name": "contentType", + "type": 9 + }, + { + "id": "6:824275627423835844", + "name": "createdAt", + "indexId": "3:5224279695299690370", + "type": 10, + "flags": 8 + }, + { + "id": "7:4938488440801306283", + "name": "origin", + "type": 9 + }, + { + "id": "8:3675289388362712872", + "name": "messageType", + "type": 9 + }, + { + "id": "9:5014932119114547439", + "name": "jobId", + "type": 9 + }, + { + "id": "10:6511433113986718524", + "name": "jobNumber", + "type": 9 + }, + { + "id": "11:7341546288167795221", + "name": "read", + "type": 1 + }, + { + "id": "12:2309286538364575316", + "name": "pendingSync", + "type": 1 + } + ], + "relations": [] + }, + { + "id": "2:2377210606864651652", + "lastPropertyId": "5:4330118937838819262", + "name": "JobEntity", + "properties": [ + { + "id": "1:5764695419124422056", + "name": "id", + "type": 6, + "flags": 1 + }, + { + "id": "2:5230369747102400974", + "name": "jobId", + "indexId": "4:5912728233158498728", + "type": 9, + "flags": 2080 + }, + { + "id": "3:8786313603756997847", + "name": "jobData", + "type": 9 + }, + { + "id": "4:9125996217822689005", + "name": "createdAt", + "type": 10 + }, + { + "id": "5:4330118937838819262", + "name": "updatedAt", + "type": 10 + } + ], + "relations": [] + }, + { + "id": "3:5853367178512403842", + "lastPropertyId": "5:7993370300880580866", + "name": "PhotoEntity", + "properties": [ + { + "id": "1:4387782442589683314", + "name": "id", + "type": 6, + "flags": 1 + }, + { + "id": "2:7269827572185524897", + "name": "taskId", + "type": 9 + }, + { + "id": "3:117404329471165159", + "name": "photoIndex", + "type": 6 + }, + { + "id": "4:175585982820628578", + "name": "data", + "type": 9 + }, + { + "id": "5:7993370300880580866", + "name": "createdAt", + "type": 10 + } + ], + "relations": [] + }, + { + "id": "4:3098331694244942316", + "lastPropertyId": "6:8514324254890213490", + "name": "QueuedMessageEntity", + "properties": [ + { + "id": "1:7708425959688472926", + "name": "id", + "type": 6, + "flags": 1 + }, + { + "id": "2:6817215813894799570", + "name": "messageId", + "indexId": "5:853241783777319657", + "type": 9, + "flags": 2080 + }, + { + "id": "3:60965955604348905", + "name": "topic", + "type": 9 + }, + { + "id": "4:4779773601253035683", + "name": "payload", + "type": 9 + }, + { + "id": "5:2120244644382713824", + "name": "createdAt", + "type": 10 + }, + { + "id": "6:8514324254890213490", + "name": "retryCount", + "type": 6 + } + ], + "relations": [] + }, + { + "id": "5:2194624907249454848", + "lastPropertyId": "6:5035828038544573244", + "name": "TaskStatusEntity", + "properties": [ + { + "id": "1:2660897068318660363", + "name": "id", + "type": 6, + "flags": 1 + }, + { + "id": "2:2717300553109032772", + "name": "taskId", + "indexId": "6:3594410711639811810", + "type": 9, + "flags": 2080 + }, + { + "id": "3:1940249619044527831", + "name": "completed", + "type": 1 + }, + { + "id": "4:5172336642033012706", + "name": "completedAt", + "type": 10 + }, + { + "id": "5:5219138373705672631", + "name": "createdAt", + "type": 10 + }, + { + "id": "6:5035828038544573244", + "name": "updatedAt", + "type": 10 + } + ], + "relations": [] + }, + { + "id": "6:753334402157356597", + "lastPropertyId": "5:7622589620848481852", + "name": "UserDataEntity", + "properties": [ + { + "id": "1:258617559550142129", + "name": "id", + "type": 6, + "flags": 1 + }, + { + "id": "2:3549771662483971304", + "name": "key", + "indexId": "7:8692774416314022957", + "type": 9, + "flags": 2080 + }, + { + "id": "3:6572116502376820780", + "name": "value", + "type": 9 + }, + { + "id": "4:6220239104166844131", + "name": "createdAt", + "type": 10 + }, + { + "id": "5:7622589620848481852", + "name": "updatedAt", + "type": 10 + } + ], + "relations": [] + } + ], + "lastEntityId": "6:753334402157356597", + "lastIndexId": "7:8692774416314022957", + "lastRelationId": "0:0", + "lastSequenceId": "0:0", + "modelVersion": 5, + "modelVersionParserMinimum": 5, + "retiredEntityUids": [], + "retiredIndexUids": [], + "retiredPropertyUids": [], + "retiredRelationUids": [], + "version": 1 +} \ No newline at end of file diff --git a/app/lib/objectbox.g.dart b/app/lib/objectbox.g.dart new file mode 100644 index 0000000..16b2eb8 --- /dev/null +++ b/app/lib/objectbox.g.dart @@ -0,0 +1,943 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// This code was generated by ObjectBox. To update it run the generator again +// with `dart run build_runner build`. +// See also https://docs.objectbox.io/getting-started#generate-objectbox-code + +// ignore_for_file: camel_case_types, depend_on_referenced_packages +// coverage:ignore-file + +import 'dart:typed_data'; + +import 'package:flat_buffers/flat_buffers.dart' as fb; +import 'package:objectbox/internal.dart' + as obx_int; // generated code can access "internal" functionality +import 'package:objectbox/objectbox.dart' as obx; +import 'package:objectbox_flutter_libs/objectbox_flutter_libs.dart'; + +import 'entities/chat_message_entity.dart'; +import 'entities/job_entity.dart'; +import 'entities/photo_entity.dart'; +import 'entities/queued_message_entity.dart'; +import 'entities/task_status_entity.dart'; +import 'entities/user_data_entity.dart'; + +export 'package:objectbox/objectbox.dart'; // so that callers only have to import this file + +final _entities = [ + obx_int.ModelEntity( + id: const obx_int.IdUid(1, 7611693027744165533), + name: 'ChatMessageEntity', + lastPropertyId: const obx_int.IdUid(12, 2309286538364575316), + flags: 0, + properties: [ + obx_int.ModelProperty( + id: const obx_int.IdUid(1, 2877174849434222825), + name: 'id', + type: 6, + flags: 1, + ), + obx_int.ModelProperty( + id: const obx_int.IdUid(2, 7133214518465925033), + name: 'messageId', + type: 9, + flags: 2080, + indexId: const obx_int.IdUid(1, 5239829446791635795), + ), + obx_int.ModelProperty( + id: const obx_int.IdUid(3, 4299321820179972091), + name: 'conversationKey', + type: 9, + flags: 2048, + indexId: const obx_int.IdUid(2, 7958984541640853733), + ), + obx_int.ModelProperty( + id: const obx_int.IdUid(4, 5939280612219671854), + name: 'content', + type: 9, + flags: 0, + ), + obx_int.ModelProperty( + id: const obx_int.IdUid(5, 3937520230579179052), + name: 'contentType', + type: 9, + flags: 0, + ), + obx_int.ModelProperty( + id: const obx_int.IdUid(6, 824275627423835844), + name: 'createdAt', + type: 10, + flags: 8, + indexId: const obx_int.IdUid(3, 5224279695299690370), + ), + obx_int.ModelProperty( + id: const obx_int.IdUid(7, 4938488440801306283), + name: 'origin', + type: 9, + flags: 0, + ), + obx_int.ModelProperty( + id: const obx_int.IdUid(8, 3675289388362712872), + name: 'messageType', + type: 9, + flags: 0, + ), + obx_int.ModelProperty( + id: const obx_int.IdUid(9, 5014932119114547439), + name: 'jobId', + type: 9, + flags: 0, + ), + obx_int.ModelProperty( + id: const obx_int.IdUid(10, 6511433113986718524), + name: 'jobNumber', + type: 9, + flags: 0, + ), + obx_int.ModelProperty( + id: const obx_int.IdUid(11, 7341546288167795221), + name: 'read', + type: 1, + flags: 0, + ), + obx_int.ModelProperty( + id: const obx_int.IdUid(12, 2309286538364575316), + name: 'pendingSync', + type: 1, + flags: 0, + ), + ], + relations: [], + backlinks: [], + ), + obx_int.ModelEntity( + id: const obx_int.IdUid(2, 2377210606864651652), + name: 'JobEntity', + lastPropertyId: const obx_int.IdUid(5, 4330118937838819262), + flags: 0, + properties: [ + obx_int.ModelProperty( + id: const obx_int.IdUid(1, 5764695419124422056), + name: 'id', + type: 6, + flags: 1, + ), + obx_int.ModelProperty( + id: const obx_int.IdUid(2, 5230369747102400974), + name: 'jobId', + type: 9, + flags: 2080, + indexId: const obx_int.IdUid(4, 5912728233158498728), + ), + obx_int.ModelProperty( + id: const obx_int.IdUid(3, 8786313603756997847), + name: 'jobData', + type: 9, + flags: 0, + ), + obx_int.ModelProperty( + id: const obx_int.IdUid(4, 9125996217822689005), + name: 'createdAt', + type: 10, + flags: 0, + ), + obx_int.ModelProperty( + id: const obx_int.IdUid(5, 4330118937838819262), + name: 'updatedAt', + type: 10, + flags: 0, + ), + ], + relations: [], + backlinks: [], + ), + obx_int.ModelEntity( + id: const obx_int.IdUid(3, 5853367178512403842), + name: 'PhotoEntity', + lastPropertyId: const obx_int.IdUid(5, 7993370300880580866), + flags: 0, + properties: [ + obx_int.ModelProperty( + id: const obx_int.IdUid(1, 4387782442589683314), + name: 'id', + type: 6, + flags: 1, + ), + obx_int.ModelProperty( + id: const obx_int.IdUid(2, 7269827572185524897), + name: 'taskId', + type: 9, + flags: 0, + ), + obx_int.ModelProperty( + id: const obx_int.IdUid(3, 117404329471165159), + name: 'photoIndex', + type: 6, + flags: 0, + ), + obx_int.ModelProperty( + id: const obx_int.IdUid(4, 175585982820628578), + name: 'data', + type: 9, + flags: 0, + ), + obx_int.ModelProperty( + id: const obx_int.IdUid(5, 7993370300880580866), + name: 'createdAt', + type: 10, + flags: 0, + ), + ], + relations: [], + backlinks: [], + ), + obx_int.ModelEntity( + id: const obx_int.IdUid(4, 3098331694244942316), + name: 'QueuedMessageEntity', + lastPropertyId: const obx_int.IdUid(6, 8514324254890213490), + flags: 0, + properties: [ + obx_int.ModelProperty( + id: const obx_int.IdUid(1, 7708425959688472926), + name: 'id', + type: 6, + flags: 1, + ), + obx_int.ModelProperty( + id: const obx_int.IdUid(2, 6817215813894799570), + name: 'messageId', + type: 9, + flags: 2080, + indexId: const obx_int.IdUid(5, 853241783777319657), + ), + obx_int.ModelProperty( + id: const obx_int.IdUid(3, 60965955604348905), + name: 'topic', + type: 9, + flags: 0, + ), + obx_int.ModelProperty( + id: const obx_int.IdUid(4, 4779773601253035683), + name: 'payload', + type: 9, + flags: 0, + ), + obx_int.ModelProperty( + id: const obx_int.IdUid(5, 2120244644382713824), + name: 'createdAt', + type: 10, + flags: 0, + ), + obx_int.ModelProperty( + id: const obx_int.IdUid(6, 8514324254890213490), + name: 'retryCount', + type: 6, + flags: 0, + ), + ], + relations: [], + backlinks: [], + ), + obx_int.ModelEntity( + id: const obx_int.IdUid(5, 2194624907249454848), + name: 'TaskStatusEntity', + lastPropertyId: const obx_int.IdUid(6, 5035828038544573244), + flags: 0, + properties: [ + obx_int.ModelProperty( + id: const obx_int.IdUid(1, 2660897068318660363), + name: 'id', + type: 6, + flags: 1, + ), + obx_int.ModelProperty( + id: const obx_int.IdUid(2, 2717300553109032772), + name: 'taskId', + type: 9, + flags: 2080, + indexId: const obx_int.IdUid(6, 3594410711639811810), + ), + obx_int.ModelProperty( + id: const obx_int.IdUid(3, 1940249619044527831), + name: 'completed', + type: 1, + flags: 0, + ), + obx_int.ModelProperty( + id: const obx_int.IdUid(4, 5172336642033012706), + name: 'completedAt', + type: 10, + flags: 0, + ), + obx_int.ModelProperty( + id: const obx_int.IdUid(5, 5219138373705672631), + name: 'createdAt', + type: 10, + flags: 0, + ), + obx_int.ModelProperty( + id: const obx_int.IdUid(6, 5035828038544573244), + name: 'updatedAt', + type: 10, + flags: 0, + ), + ], + relations: [], + backlinks: [], + ), + obx_int.ModelEntity( + id: const obx_int.IdUid(6, 753334402157356597), + name: 'UserDataEntity', + lastPropertyId: const obx_int.IdUid(5, 7622589620848481852), + flags: 0, + properties: [ + obx_int.ModelProperty( + id: const obx_int.IdUid(1, 258617559550142129), + name: 'id', + type: 6, + flags: 1, + ), + obx_int.ModelProperty( + id: const obx_int.IdUid(2, 3549771662483971304), + name: 'key', + type: 9, + flags: 2080, + indexId: const obx_int.IdUid(7, 8692774416314022957), + ), + obx_int.ModelProperty( + id: const obx_int.IdUid(3, 6572116502376820780), + name: 'value', + type: 9, + flags: 0, + ), + obx_int.ModelProperty( + id: const obx_int.IdUid(4, 6220239104166844131), + name: 'createdAt', + type: 10, + flags: 0, + ), + obx_int.ModelProperty( + id: const obx_int.IdUid(5, 7622589620848481852), + name: 'updatedAt', + type: 10, + flags: 0, + ), + ], + relations: [], + backlinks: [], + ), +]; + +/// Shortcut for [obx.Store.new] that passes [getObjectBoxModel] and for Flutter +/// apps by default a [directory] using `defaultStoreDirectory()` from the +/// ObjectBox Flutter library. +/// +/// Note: for desktop apps it is recommended to specify a unique [directory]. +/// +/// See [obx.Store.new] for an explanation of all parameters. +/// +/// For Flutter apps, also calls `loadObjectBoxLibraryAndroidCompat()` from +/// the ObjectBox Flutter library to fix loading the native ObjectBox library +/// on Android 6 and older. +Future openStore({ + String? directory, + int? maxDBSizeInKB, + int? maxDataSizeInKB, + int? fileMode, + int? maxReaders, + bool queriesCaseSensitiveDefault = true, + String? macosApplicationGroup, +}) async { + await loadObjectBoxLibraryAndroidCompat(); + return obx.Store( + getObjectBoxModel(), + directory: directory ?? (await defaultStoreDirectory()).path, + maxDBSizeInKB: maxDBSizeInKB, + maxDataSizeInKB: maxDataSizeInKB, + fileMode: fileMode, + maxReaders: maxReaders, + queriesCaseSensitiveDefault: queriesCaseSensitiveDefault, + macosApplicationGroup: macosApplicationGroup, + ); +} + +/// Returns the ObjectBox model definition for this project for use with +/// [obx.Store.new]. +obx_int.ModelDefinition getObjectBoxModel() { + final model = obx_int.ModelInfo( + entities: _entities, + lastEntityId: const obx_int.IdUid(6, 753334402157356597), + lastIndexId: const obx_int.IdUid(7, 8692774416314022957), + lastRelationId: const obx_int.IdUid(0, 0), + lastSequenceId: const obx_int.IdUid(0, 0), + retiredEntityUids: const [], + retiredIndexUids: const [], + retiredPropertyUids: const [], + retiredRelationUids: const [], + modelVersion: 5, + modelVersionParserMinimum: 5, + version: 1, + ); + + final bindings = { + ChatMessageEntity: obx_int.EntityDefinition( + model: _entities[0], + toOneRelations: (ChatMessageEntity object) => [], + toManyRelations: (ChatMessageEntity object) => {}, + getId: (ChatMessageEntity object) => object.id, + setId: (ChatMessageEntity object, int id) { + object.id = id; + }, + objectToFB: (ChatMessageEntity object, fb.Builder fbb) { + final messageIdOffset = fbb.writeString(object.messageId); + final conversationKeyOffset = fbb.writeString(object.conversationKey); + final contentOffset = fbb.writeString(object.content); + final contentTypeOffset = fbb.writeString(object.contentType); + final originOffset = fbb.writeString(object.origin); + final messageTypeOffset = fbb.writeString(object.messageType); + final jobIdOffset = object.jobId == null + ? null + : fbb.writeString(object.jobId!); + final jobNumberOffset = object.jobNumber == null + ? null + : fbb.writeString(object.jobNumber!); + fbb.startTable(13); + fbb.addInt64(0, object.id); + fbb.addOffset(1, messageIdOffset); + fbb.addOffset(2, conversationKeyOffset); + fbb.addOffset(3, contentOffset); + fbb.addOffset(4, contentTypeOffset); + fbb.addInt64(5, object.createdAt.millisecondsSinceEpoch); + fbb.addOffset(6, originOffset); + fbb.addOffset(7, messageTypeOffset); + fbb.addOffset(8, jobIdOffset); + fbb.addOffset(9, jobNumberOffset); + fbb.addBool(10, object.read); + fbb.addBool(11, object.pendingSync); + fbb.finish(fbb.endTable()); + return object.id; + }, + objectFromFB: (obx.Store store, ByteData fbData) { + final buffer = fb.BufferContext(fbData); + final rootOffset = buffer.derefObject(0); + final messageIdParam = const fb.StringReader( + asciiOptimization: true, + ).vTableGet(buffer, rootOffset, 6, ''); + final conversationKeyParam = const fb.StringReader( + asciiOptimization: true, + ).vTableGet(buffer, rootOffset, 8, ''); + final contentParam = const fb.StringReader( + asciiOptimization: true, + ).vTableGet(buffer, rootOffset, 10, ''); + final contentTypeParam = const fb.StringReader( + asciiOptimization: true, + ).vTableGet(buffer, rootOffset, 12, ''); + final createdAtParam = DateTime.fromMillisecondsSinceEpoch( + const fb.Int64Reader().vTableGet(buffer, rootOffset, 14, 0), + ); + final originParam = const fb.StringReader( + asciiOptimization: true, + ).vTableGet(buffer, rootOffset, 16, ''); + final messageTypeParam = const fb.StringReader( + asciiOptimization: true, + ).vTableGet(buffer, rootOffset, 18, ''); + final jobIdParam = const fb.StringReader( + asciiOptimization: true, + ).vTableGetNullable(buffer, rootOffset, 20); + final jobNumberParam = const fb.StringReader( + asciiOptimization: true, + ).vTableGetNullable(buffer, rootOffset, 22); + final readParam = const fb.BoolReader().vTableGet( + buffer, + rootOffset, + 24, + false, + ); + final pendingSyncParam = const fb.BoolReader().vTableGet( + buffer, + rootOffset, + 26, + false, + ); + final object = ChatMessageEntity( + messageId: messageIdParam, + conversationKey: conversationKeyParam, + content: contentParam, + contentType: contentTypeParam, + createdAt: createdAtParam, + origin: originParam, + messageType: messageTypeParam, + jobId: jobIdParam, + jobNumber: jobNumberParam, + read: readParam, + pendingSync: pendingSyncParam, + )..id = const fb.Int64Reader().vTableGet(buffer, rootOffset, 4, 0); + + return object; + }, + ), + JobEntity: obx_int.EntityDefinition( + model: _entities[1], + toOneRelations: (JobEntity object) => [], + toManyRelations: (JobEntity object) => {}, + getId: (JobEntity object) => object.id, + setId: (JobEntity object, int id) { + object.id = id; + }, + objectToFB: (JobEntity object, fb.Builder fbb) { + final jobIdOffset = fbb.writeString(object.jobId); + final jobDataOffset = fbb.writeString(object.jobData); + fbb.startTable(6); + fbb.addInt64(0, object.id); + fbb.addOffset(1, jobIdOffset); + fbb.addOffset(2, jobDataOffset); + fbb.addInt64(3, object.createdAt.millisecondsSinceEpoch); + fbb.addInt64(4, object.updatedAt.millisecondsSinceEpoch); + fbb.finish(fbb.endTable()); + return object.id; + }, + objectFromFB: (obx.Store store, ByteData fbData) { + final buffer = fb.BufferContext(fbData); + final rootOffset = buffer.derefObject(0); + final jobIdParam = const fb.StringReader( + asciiOptimization: true, + ).vTableGet(buffer, rootOffset, 6, ''); + final jobDataParam = const fb.StringReader( + asciiOptimization: true, + ).vTableGet(buffer, rootOffset, 8, ''); + final createdAtParam = DateTime.fromMillisecondsSinceEpoch( + const fb.Int64Reader().vTableGet(buffer, rootOffset, 10, 0), + ); + final updatedAtParam = DateTime.fromMillisecondsSinceEpoch( + const fb.Int64Reader().vTableGet(buffer, rootOffset, 12, 0), + ); + final object = JobEntity( + jobId: jobIdParam, + jobData: jobDataParam, + createdAt: createdAtParam, + updatedAt: updatedAtParam, + )..id = const fb.Int64Reader().vTableGet(buffer, rootOffset, 4, 0); + + return object; + }, + ), + PhotoEntity: obx_int.EntityDefinition( + model: _entities[2], + toOneRelations: (PhotoEntity object) => [], + toManyRelations: (PhotoEntity object) => {}, + getId: (PhotoEntity object) => object.id, + setId: (PhotoEntity object, int id) { + object.id = id; + }, + objectToFB: (PhotoEntity object, fb.Builder fbb) { + final taskIdOffset = fbb.writeString(object.taskId); + final dataOffset = fbb.writeString(object.data); + fbb.startTable(6); + fbb.addInt64(0, object.id); + fbb.addOffset(1, taskIdOffset); + fbb.addInt64(2, object.photoIndex); + fbb.addOffset(3, dataOffset); + fbb.addInt64(4, object.createdAt.millisecondsSinceEpoch); + fbb.finish(fbb.endTable()); + return object.id; + }, + objectFromFB: (obx.Store store, ByteData fbData) { + final buffer = fb.BufferContext(fbData); + final rootOffset = buffer.derefObject(0); + final taskIdParam = const fb.StringReader( + asciiOptimization: true, + ).vTableGet(buffer, rootOffset, 6, ''); + final photoIndexParam = const fb.Int64Reader().vTableGet( + buffer, + rootOffset, + 8, + 0, + ); + final dataParam = const fb.StringReader( + asciiOptimization: true, + ).vTableGet(buffer, rootOffset, 10, ''); + final createdAtParam = DateTime.fromMillisecondsSinceEpoch( + const fb.Int64Reader().vTableGet(buffer, rootOffset, 12, 0), + ); + final object = PhotoEntity( + taskId: taskIdParam, + photoIndex: photoIndexParam, + data: dataParam, + createdAt: createdAtParam, + )..id = const fb.Int64Reader().vTableGet(buffer, rootOffset, 4, 0); + + return object; + }, + ), + QueuedMessageEntity: obx_int.EntityDefinition( + model: _entities[3], + toOneRelations: (QueuedMessageEntity object) => [], + toManyRelations: (QueuedMessageEntity object) => {}, + getId: (QueuedMessageEntity object) => object.id, + setId: (QueuedMessageEntity object, int id) { + object.id = id; + }, + objectToFB: (QueuedMessageEntity object, fb.Builder fbb) { + final messageIdOffset = fbb.writeString(object.messageId); + final topicOffset = fbb.writeString(object.topic); + final payloadOffset = fbb.writeString(object.payload); + fbb.startTable(7); + fbb.addInt64(0, object.id); + fbb.addOffset(1, messageIdOffset); + fbb.addOffset(2, topicOffset); + fbb.addOffset(3, payloadOffset); + fbb.addInt64(4, object.createdAt.millisecondsSinceEpoch); + fbb.addInt64(5, object.retryCount); + fbb.finish(fbb.endTable()); + return object.id; + }, + objectFromFB: (obx.Store store, ByteData fbData) { + final buffer = fb.BufferContext(fbData); + final rootOffset = buffer.derefObject(0); + final messageIdParam = const fb.StringReader( + asciiOptimization: true, + ).vTableGet(buffer, rootOffset, 6, ''); + final topicParam = const fb.StringReader( + asciiOptimization: true, + ).vTableGet(buffer, rootOffset, 8, ''); + final payloadParam = const fb.StringReader( + asciiOptimization: true, + ).vTableGet(buffer, rootOffset, 10, ''); + final createdAtParam = DateTime.fromMillisecondsSinceEpoch( + const fb.Int64Reader().vTableGet(buffer, rootOffset, 12, 0), + ); + final retryCountParam = const fb.Int64Reader().vTableGet( + buffer, + rootOffset, + 14, + 0, + ); + final object = QueuedMessageEntity( + messageId: messageIdParam, + topic: topicParam, + payload: payloadParam, + createdAt: createdAtParam, + retryCount: retryCountParam, + )..id = const fb.Int64Reader().vTableGet(buffer, rootOffset, 4, 0); + + return object; + }, + ), + TaskStatusEntity: obx_int.EntityDefinition( + model: _entities[4], + toOneRelations: (TaskStatusEntity object) => [], + toManyRelations: (TaskStatusEntity object) => {}, + getId: (TaskStatusEntity object) => object.id, + setId: (TaskStatusEntity object, int id) { + object.id = id; + }, + objectToFB: (TaskStatusEntity object, fb.Builder fbb) { + final taskIdOffset = fbb.writeString(object.taskId); + fbb.startTable(7); + fbb.addInt64(0, object.id); + fbb.addOffset(1, taskIdOffset); + fbb.addBool(2, object.completed); + fbb.addInt64(3, object.completedAt?.millisecondsSinceEpoch); + fbb.addInt64(4, object.createdAt.millisecondsSinceEpoch); + fbb.addInt64(5, object.updatedAt.millisecondsSinceEpoch); + fbb.finish(fbb.endTable()); + return object.id; + }, + objectFromFB: (obx.Store store, ByteData fbData) { + final buffer = fb.BufferContext(fbData); + final rootOffset = buffer.derefObject(0); + final completedAtValue = const fb.Int64Reader().vTableGetNullable( + buffer, + rootOffset, + 10, + ); + final taskIdParam = const fb.StringReader( + asciiOptimization: true, + ).vTableGet(buffer, rootOffset, 6, ''); + final completedParam = const fb.BoolReader().vTableGet( + buffer, + rootOffset, + 8, + false, + ); + final completedAtParam = completedAtValue == null + ? null + : DateTime.fromMillisecondsSinceEpoch(completedAtValue); + final createdAtParam = DateTime.fromMillisecondsSinceEpoch( + const fb.Int64Reader().vTableGet(buffer, rootOffset, 12, 0), + ); + final updatedAtParam = DateTime.fromMillisecondsSinceEpoch( + const fb.Int64Reader().vTableGet(buffer, rootOffset, 14, 0), + ); + final object = TaskStatusEntity( + taskId: taskIdParam, + completed: completedParam, + completedAt: completedAtParam, + createdAt: createdAtParam, + updatedAt: updatedAtParam, + )..id = const fb.Int64Reader().vTableGet(buffer, rootOffset, 4, 0); + + return object; + }, + ), + UserDataEntity: obx_int.EntityDefinition( + model: _entities[5], + toOneRelations: (UserDataEntity object) => [], + toManyRelations: (UserDataEntity object) => {}, + getId: (UserDataEntity object) => object.id, + setId: (UserDataEntity object, int id) { + object.id = id; + }, + objectToFB: (UserDataEntity object, fb.Builder fbb) { + final keyOffset = fbb.writeString(object.key); + final valueOffset = fbb.writeString(object.value); + fbb.startTable(6); + fbb.addInt64(0, object.id); + fbb.addOffset(1, keyOffset); + fbb.addOffset(2, valueOffset); + fbb.addInt64(3, object.createdAt.millisecondsSinceEpoch); + fbb.addInt64(4, object.updatedAt.millisecondsSinceEpoch); + fbb.finish(fbb.endTable()); + return object.id; + }, + objectFromFB: (obx.Store store, ByteData fbData) { + final buffer = fb.BufferContext(fbData); + final rootOffset = buffer.derefObject(0); + final keyParam = const fb.StringReader( + asciiOptimization: true, + ).vTableGet(buffer, rootOffset, 6, ''); + final valueParam = const fb.StringReader( + asciiOptimization: true, + ).vTableGet(buffer, rootOffset, 8, ''); + final createdAtParam = DateTime.fromMillisecondsSinceEpoch( + const fb.Int64Reader().vTableGet(buffer, rootOffset, 10, 0), + ); + final updatedAtParam = DateTime.fromMillisecondsSinceEpoch( + const fb.Int64Reader().vTableGet(buffer, rootOffset, 12, 0), + ); + final object = UserDataEntity( + key: keyParam, + value: valueParam, + createdAt: createdAtParam, + updatedAt: updatedAtParam, + )..id = const fb.Int64Reader().vTableGet(buffer, rootOffset, 4, 0); + + return object; + }, + ), + }; + + return obx_int.ModelDefinition(model, bindings); +} + +/// [ChatMessageEntity] entity fields to define ObjectBox queries. +class ChatMessageEntity_ { + /// See [ChatMessageEntity.id]. + static final id = obx.QueryIntegerProperty( + _entities[0].properties[0], + ); + + /// See [ChatMessageEntity.messageId]. + static final messageId = obx.QueryStringProperty( + _entities[0].properties[1], + ); + + /// See [ChatMessageEntity.conversationKey]. + static final conversationKey = obx.QueryStringProperty( + _entities[0].properties[2], + ); + + /// See [ChatMessageEntity.content]. + static final content = obx.QueryStringProperty( + _entities[0].properties[3], + ); + + /// See [ChatMessageEntity.contentType]. + static final contentType = obx.QueryStringProperty( + _entities[0].properties[4], + ); + + /// See [ChatMessageEntity.createdAt]. + static final createdAt = obx.QueryDateProperty( + _entities[0].properties[5], + ); + + /// See [ChatMessageEntity.origin]. + static final origin = obx.QueryStringProperty( + _entities[0].properties[6], + ); + + /// See [ChatMessageEntity.messageType]. + static final messageType = obx.QueryStringProperty( + _entities[0].properties[7], + ); + + /// See [ChatMessageEntity.jobId]. + static final jobId = obx.QueryStringProperty( + _entities[0].properties[8], + ); + + /// See [ChatMessageEntity.jobNumber]. + static final jobNumber = obx.QueryStringProperty( + _entities[0].properties[9], + ); + + /// See [ChatMessageEntity.read]. + static final read = obx.QueryBooleanProperty( + _entities[0].properties[10], + ); + + /// See [ChatMessageEntity.pendingSync]. + static final pendingSync = obx.QueryBooleanProperty( + _entities[0].properties[11], + ); +} + +/// [JobEntity] entity fields to define ObjectBox queries. +class JobEntity_ { + /// See [JobEntity.id]. + static final id = obx.QueryIntegerProperty( + _entities[1].properties[0], + ); + + /// See [JobEntity.jobId]. + static final jobId = obx.QueryStringProperty( + _entities[1].properties[1], + ); + + /// See [JobEntity.jobData]. + static final jobData = obx.QueryStringProperty( + _entities[1].properties[2], + ); + + /// See [JobEntity.createdAt]. + static final createdAt = obx.QueryDateProperty( + _entities[1].properties[3], + ); + + /// See [JobEntity.updatedAt]. + static final updatedAt = obx.QueryDateProperty( + _entities[1].properties[4], + ); +} + +/// [PhotoEntity] entity fields to define ObjectBox queries. +class PhotoEntity_ { + /// See [PhotoEntity.id]. + static final id = obx.QueryIntegerProperty( + _entities[2].properties[0], + ); + + /// See [PhotoEntity.taskId]. + static final taskId = obx.QueryStringProperty( + _entities[2].properties[1], + ); + + /// See [PhotoEntity.photoIndex]. + static final photoIndex = obx.QueryIntegerProperty( + _entities[2].properties[2], + ); + + /// See [PhotoEntity.data]. + static final data = obx.QueryStringProperty( + _entities[2].properties[3], + ); + + /// See [PhotoEntity.createdAt]. + static final createdAt = obx.QueryDateProperty( + _entities[2].properties[4], + ); +} + +/// [QueuedMessageEntity] entity fields to define ObjectBox queries. +class QueuedMessageEntity_ { + /// See [QueuedMessageEntity.id]. + static final id = obx.QueryIntegerProperty( + _entities[3].properties[0], + ); + + /// See [QueuedMessageEntity.messageId]. + static final messageId = obx.QueryStringProperty( + _entities[3].properties[1], + ); + + /// See [QueuedMessageEntity.topic]. + static final topic = obx.QueryStringProperty( + _entities[3].properties[2], + ); + + /// See [QueuedMessageEntity.payload]. + static final payload = obx.QueryStringProperty( + _entities[3].properties[3], + ); + + /// See [QueuedMessageEntity.createdAt]. + static final createdAt = obx.QueryDateProperty( + _entities[3].properties[4], + ); + + /// See [QueuedMessageEntity.retryCount]. + static final retryCount = obx.QueryIntegerProperty( + _entities[3].properties[5], + ); +} + +/// [TaskStatusEntity] entity fields to define ObjectBox queries. +class TaskStatusEntity_ { + /// See [TaskStatusEntity.id]. + static final id = obx.QueryIntegerProperty( + _entities[4].properties[0], + ); + + /// See [TaskStatusEntity.taskId]. + static final taskId = obx.QueryStringProperty( + _entities[4].properties[1], + ); + + /// See [TaskStatusEntity.completed]. + static final completed = obx.QueryBooleanProperty( + _entities[4].properties[2], + ); + + /// See [TaskStatusEntity.completedAt]. + static final completedAt = obx.QueryDateProperty( + _entities[4].properties[3], + ); + + /// See [TaskStatusEntity.createdAt]. + static final createdAt = obx.QueryDateProperty( + _entities[4].properties[4], + ); + + /// See [TaskStatusEntity.updatedAt]. + static final updatedAt = obx.QueryDateProperty( + _entities[4].properties[5], + ); +} + +/// [UserDataEntity] entity fields to define ObjectBox queries. +class UserDataEntity_ { + /// See [UserDataEntity.id]. + static final id = obx.QueryIntegerProperty( + _entities[5].properties[0], + ); + + /// See [UserDataEntity.key]. + static final key = obx.QueryStringProperty( + _entities[5].properties[1], + ); + + /// See [UserDataEntity.value]. + static final value = obx.QueryStringProperty( + _entities[5].properties[2], + ); + + /// See [UserDataEntity.createdAt]. + static final createdAt = obx.QueryDateProperty( + _entities[5].properties[3], + ); + + /// See [UserDataEntity.updatedAt]. + static final updatedAt = obx.QueryDateProperty( + _entities[5].properties[4], + ); +} diff --git a/app/lib/routing_view.dart b/app/lib/routing_view.dart new file mode 100644 index 0000000..4bb07c4 --- /dev/null +++ b/app/lib/routing_view.dart @@ -0,0 +1,141 @@ +import 'package:flutter/material.dart'; +import 'package:webview_flutter/webview_flutter.dart'; +import 'l10n/app_localizations.dart'; +import 'package:url_launcher/url_launcher.dart'; +import 'widgets/offline_banner.dart'; + +// Routing view that immediately opens a Google Maps navigation inside a WebView +// It receives an address string and optionally a title. +class RoutingView extends StatefulWidget { + final String address; + final String? title; + final bool isDelivery; // to distinguish pickup/delivery if needed later + + const RoutingView({super.key, required this.address, this.title, this.isDelivery = true}); + + @override + State createState() => _RoutingViewState(); +} + +class _RoutingViewState extends State { + bool _initialized = false; + late final WebViewController _controller; + double _progress = 0.0; + + String _buildDirectionsUrl(String rawAddress) { + const apiKey = 'AIzaSyDnbitL06iLp3elmj-WtPudCykX9xvXcVE'; + final query = Uri.encodeComponent(rawAddress); + // Google Maps Directions URL with API key appended. + return 'https://www.google.com/maps/dir/?api=1&destination=$query&travelmode=driving&key=$apiKey'; + } + + String? _extractBrowserFallbackUrl(String intentUrl) { + const key = 'S.browser_fallback_url='; + final idx = intentUrl.indexOf(key); + if (idx == -1) return null; + final start = idx + key.length; + final end = intentUrl.indexOf(';', start); + final encoded = end == -1 ? intentUrl.substring(start) : intentUrl.substring(start, end); + try { + return Uri.decodeComponent(encoded); + } catch (_) { + return encoded; + } + } + + String? _convertIntentToHttps(String intentUrl) { + const prefix = 'intent://'; + if (!intentUrl.startsWith(prefix)) return null; + final after = intentUrl.substring(prefix.length); + final hashIndex = after.indexOf('#'); + final pathPart = hashIndex == -1 ? after : after.substring(0, hashIndex); + + // default scheme is https unless specified + var scheme = 'https'; + final schemeKey = '#Intent;scheme='; + final schemeIdx = intentUrl.indexOf(schemeKey); + if (schemeIdx != -1) { + final start = schemeIdx + schemeKey.length; + final end = intentUrl.indexOf(';', start); + if (end > start) { + scheme = intentUrl.substring(start, end); + } + } + return '$scheme://$pathPart'; + } + + @override + void initState() { + assert(!_initialized); + super.initState(); + final url = _buildDirectionsUrl(widget.address); + _controller = + WebViewController() + ..setJavaScriptMode(JavaScriptMode.unrestricted) + ..setNavigationDelegate( + NavigationDelegate( + onNavigationRequest: (NavigationRequest request) async { + final uri = Uri.tryParse(request.url); + if (uri == null) { + return NavigationDecision.prevent; + } + + // Handle intent:// and other non-http(s) schemes by launching externally or using fallback. + if (uri.scheme == 'intent') { + final fallback = _extractBrowserFallbackUrl(request.url); + if (fallback != null) { + await _controller.loadRequest(Uri.parse(fallback)); + } else { + // Try converting to https as a naive fallback + final httpsCandidate = _convertIntentToHttps(request.url); + if (httpsCandidate != null && await canLaunchUrl(Uri.parse(httpsCandidate))) { + await launchUrl(Uri.parse(httpsCandidate), mode: LaunchMode.externalApplication); + } else { + // As a last resort, prevent navigation and show a hint + if (mounted) { + ScaffoldMessenger.maybeOf(context)?.showSnackBar(SnackBar(content: Text(AppLocalizations.of(context).connectionError))); + } + } + } + return NavigationDecision.prevent; + } + + if (uri.scheme != 'http' && uri.scheme != 'https' && uri.scheme != 'about' && uri.scheme != 'data') { + if (await canLaunchUrl(uri)) { + await launchUrl(uri, mode: LaunchMode.externalApplication); + } + return NavigationDecision.prevent; + } + + return NavigationDecision.navigate; + }, + onProgress: (int progress) { + setState(() { + _progress = progress / 100.0; + }); + }, + onWebResourceError: (WebResourceError error) { + // Optionally show a snackbar on error + if (mounted) { + ScaffoldMessenger.maybeOf(context)?.showSnackBar(SnackBar(content: Text('${AppLocalizations.of(context).error}: ${error.errorCode}'))); + } + }, + ), + ) + ..loadRequest(Uri.parse(url)); + _initialized = true; + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar(title: Text(widget.title?.isNotEmpty == true ? widget.title! : (widget.isDelivery ? 'Route zur Zustelladresse' : 'Route zur Abholadresse'))), + body: Column( + children: [ + OfflineBanner(), + Expanded(child: Stack(children: [WebViewWidget(key: const ValueKey('routing-webview'), controller: _controller), if (_progress < 1.0) LinearProgressIndicator(value: _progress)])), + ], + ), + ); + } +} diff --git a/app/lib/services/ack_tracker.dart b/app/lib/services/ack_tracker.dart new file mode 100644 index 0000000..8ef03d9 --- /dev/null +++ b/app/lib/services/ack_tracker.dart @@ -0,0 +1,143 @@ +import 'package:flutter/foundation.dart'; + +/// Represents a message awaiting acknowledgment +class PendingMessage { + /// Unique message identifier + final String messageId; + + /// Target topic + final String topic; + + /// The JSON payload to retry sending + final String jsonPayload; + + /// When the message was originally sent + final DateTime sentAt; + + /// Number of retry attempts so far + int retryCount; + + PendingMessage({ + required this.messageId, + required this.topic, + required this.jsonPayload, + required this.sentAt, + this.retryCount = 0, + }); +} + +/// Tracks pending messages awaiting acknowledgment and handles retries. +/// +/// This class is extracted from WebSocketService for testability. +/// It manages: +/// - Tracking sent messages that require ACK +/// - Removing messages when ACK is received +/// - Retrying unacknowledged messages +/// - Timing out messages after max retries +class AckTracker { + final Map _pendingMessages = {}; + + /// Maximum number of retry attempts before timeout + final int maxRetries; + + /// Callback to retry sending a message. + /// Returns true if send was successful. + final Future Function(String topic, String payload)? onRetry; + + /// Callback when a message times out (max retries exceeded) + final void Function(String messageId, String topic)? onTimeout; + + AckTracker({ + this.maxRetries = 4, + this.onRetry, + this.onTimeout, + }); + + /// Track a sent message that requires acknowledgment + void track(String messageId, String topic, String payload) { + _pendingMessages[messageId] = PendingMessage( + messageId: messageId, + topic: topic, + jsonPayload: payload, + sentAt: DateTime.now(), + ); + } + + /// Remove a message from tracking (ACK received) + void acknowledge(String messageId) { + _pendingMessages.remove(messageId); + } + + /// Check if a message is pending acknowledgment + bool isPending(String messageId) => + _pendingMessages.containsKey(messageId); + + /// Get the number of pending messages + int get pendingCount => _pendingMessages.length; + + /// Get all pending message IDs + List get pendingMessageIds => + List.unmodifiable(_pendingMessages.keys); + + /// Get a pending message by ID (for testing) + @visibleForTesting + PendingMessage? getPendingMessage(String messageId) => + _pendingMessages[messageId]; + + /// Process all pending messages and retry if needed. + /// + /// This should be called periodically (e.g., every 5 seconds). + /// Messages that exceed maxRetries will be timed out and removed. + /// + /// Set [isConnected] to false to skip retry attempts while disconnected. + Future processRetries({bool isConnected = true}) async { + if (_pendingMessages.isEmpty) { + return; + } + + final messagesToRemove = []; + + for (final entry in _pendingMessages.entries) { + final messageId = entry.key; + final pending = entry.value; + + if (pending.retryCount >= maxRetries) { + // Max retries exceeded - timeout + onTimeout?.call(messageId, pending.topic); + messagesToRemove.add(messageId); + } else if (isConnected) { + // Increment retry count and attempt resend + pending.retryCount++; + + if (onRetry != null) { + await onRetry!(pending.topic, pending.jsonPayload); + } + } + } + + // Remove timed out messages + for (final messageId in messagesToRemove) { + _pendingMessages.remove(messageId); + } + } + + /// Clear all pending messages. + /// + /// Primarily for testing purposes. + @visibleForTesting + void clearAll() => _pendingMessages.clear(); + + /// Clear pending messages for a specific topic pattern. + /// + /// Useful for clearing login messages when auth response is received. + void clearForTopic(String topicPattern) { + final toRemove = _pendingMessages.entries + .where((e) => e.value.topic == topicPattern) + .map((e) => e.key) + .toList(); + + for (final messageId in toRemove) { + _pendingMessages.remove(messageId); + } + } +} diff --git a/app/lib/services/chat_service.dart b/app/lib/services/chat_service.dart new file mode 100644 index 0000000..4ef3de8 --- /dev/null +++ b/app/lib/services/chat_service.dart @@ -0,0 +1,500 @@ +import 'dart:async'; + +import 'package:votianlt_app/services/developer.dart' as developer; + +import '../app_state.dart'; +import '../models/chat.dart'; +import '../models/chat_message.dart'; +import 'database_service.dart'; + +class ChatService { + ChatService._internal(); + static final ChatService _instance = ChatService._internal(); + factory ChatService() => _instance; + + static const _jobIdPrefix = 'job:'; + static const _jobNumberPrefix = 'job_number:'; + static const _generalPrefix = 'general:'; + + final DatabaseService _databaseService = DatabaseService(); + final AppState _appState = AppState(); + + final List _chats = []; + final StreamController> _chatsController = + StreamController>.broadcast(); + final StreamController _unreadCountController = + StreamController.broadcast(); + + bool _initialized = false; + Completer? _initCompleter; + int _unreadCount = 0; + + Stream> get chatsStream => _chatsController.stream; + List get currentChats => List.unmodifiable(_chats); + Stream get unreadCountStream => _unreadCountController.stream; + int get unreadCount => _unreadCount; + + Future initialize() async { + if (_initialized) { + await _loadChatsFromDatabase(); + developer.log( + 'ChatService already initialized, refreshed chats/unread count: $_unreadCount', + name: 'ChatService', + ); + return; + } + if (_initCompleter != null) { + return _initCompleter!.future; + } + + _initCompleter = Completer(); + developer.log('Initializing ChatService...', name: 'ChatService'); + + await _loadChatsFromDatabase(); + + _initialized = true; + _initCompleter!.complete(); + developer.log( + 'ChatService initialized with unread count: $_unreadCount', + name: 'ChatService', + ); + } + + Future dispose() async { + await _chatsController.close(); + await _unreadCountController.close(); + _initialized = false; + _initCompleter = null; + } + + Future> loadMessagesForChat(String conversationKey) async { + await initialize(); + return _databaseService.loadChatMessages(conversationKey: conversationKey); + } + + Future markConversationRead(String conversationKey) async { + await initialize(); + await _databaseService.markConversationRead(conversationKey); + await _refreshConversation(conversationKey); + // Note: _refreshConversation already calls _updateUnreadCount, + // so we don't need to call it again here + } + + Future deleteJobChats(String jobId, {String? jobNumber}) async { + if (!_initialized) { + await initialize(); + } + + final trimmedJobId = jobId.trim(); + final lowerJobId = trimmedJobId.toLowerCase(); + final trimmedJobNumber = jobNumber?.trim() ?? ''; + final lowerJobNumber = trimmedJobNumber.toLowerCase(); + + final conversationKeys = [ + if (trimmedJobId.isNotEmpty) '$_jobIdPrefix$lowerJobId', + if (trimmedJobNumber.isNotEmpty) '$_jobNumberPrefix$lowerJobNumber', + ]; + + await _databaseService.deleteChatMessagesForJob( + jobId: trimmedJobId.isNotEmpty ? trimmedJobId : null, + jobNumber: trimmedJobNumber.isNotEmpty ? trimmedJobNumber : null, + conversationKeys: conversationKeys, + ); + + _chats.removeWhere((chat) { + final matchesKey = conversationKeys.contains(chat.id); + final matchesId = trimmedJobId.isNotEmpty && + (chat.jobId?.trim().toLowerCase() == lowerJobId); + final matchesNumber = trimmedJobNumber.isNotEmpty && + (chat.jobNumber?.trim().toLowerCase() == lowerJobNumber); + return matchesKey || matchesId || matchesNumber; + }); + + _ensureDefaultGeneralChat(); + _sortChats(); + _emitChats(); + await _updateUnreadCount(); + + developer.log( + 'Removed chat conversations for jobId=$jobId jobNumber=$jobNumber', + name: 'ChatService', + ); + } + + String conversationKeyForMessage(ChatMessage message) { + developer.log( + '[DEBUG_LOG] conversationKeyForMessage called for message ${message.id}, messageType=${message.messageType}, direction=${message.direction}', + name: 'ChatService', + ); + + // Messages with GENERAL messageType should always go to the default general chat + if (message.messageType == ChatMessageType.general) { + final localId = _primaryLocalIdentifier(); + if (localId != null && localId.isNotEmpty) { + final key = _conversationKeyForParticipants( + localId, + _appState.loggedInEmail!, + ); + developer.log( + '[DEBUG_LOG] GENERAL message detected, routing to conversation key: $key (localId=$localId, receiver=${_appState.loggedInEmail})', + name: 'ChatService', + ); + return key; + } + } + + // Job-related messages go to job-specific chats + final jobId = message.jobId?.trim(); + if (jobId != null && jobId.isNotEmpty) { + final normalizedJobId = jobId.toLowerCase(); + final key = '$_jobIdPrefix$normalizedJobId'; + developer.log( + '[DEBUG_LOG] Job-related message (by jobId), routing to conversation key: $key', + name: 'ChatService', + ); + return key; + } + final jobNumber = message.jobNumber?.trim(); + if (jobNumber != null && jobNumber.isNotEmpty) { + final normalizedJobNumber = jobNumber.toLowerCase(); + final key = '$_jobNumberPrefix$normalizedJobNumber'; + developer.log( + '[DEBUG_LOG] Job-related message (by jobNumber), routing to conversation key: $key', + name: 'ChatService', + ); + return key; + } + + // Fallback: create conversation based on userId + final localId = _primaryLocalIdentifier(); + if (localId != null && localId.isNotEmpty) { + final key = _conversationKeyForParticipants( + localId, + _appState.loggedInEmail!, + ); + developer.log( + '[DEBUG_LOG] Using fallback routing, conversation key: $key', + name: 'ChatService', + ); + return key; + } + + developer.log( + '[DEBUG_LOG] No local identifier available for fallback routing', + name: 'ChatService', + ); + return '$_generalPrefix${_appState.loggedInEmail!}'; + } + + String _conversationKeyForParticipants(String a, String b) { + final participants = [a.toLowerCase(), b.toLowerCase()]..sort(); + return '$_generalPrefix${participants.join('|')}'; + } + + Future saveIncomingMessage(ChatMessage message) async { + if (!_initialized) { + await initialize(); + } + await _persistMessage(message.copyWith(pendingSync: false)); + } + + Future saveOutgoingMessage(ChatMessage message) async { + if (!_initialized) { + await initialize(); + } + await _persistMessage(message); + } + + Future _persistMessage(ChatMessage message) async { + final conversationKey = conversationKeyForMessage(message); + + final jobId = message.jobId?.trim(); + if (jobId != null && jobId.isNotEmpty) { + final legacyKey = '$_jobIdPrefix$jobId'; + if (legacyKey != conversationKey) { + await _databaseService.migrateConversationKey( + legacyKey, + conversationKey, + ); + } + } else { + final jobNumber = message.jobNumber?.trim(); + if (jobNumber != null && jobNumber.isNotEmpty) { + final legacyKey = '$_jobNumberPrefix$jobNumber'; + if (legacyKey != conversationKey) { + await _databaseService.migrateConversationKey( + legacyKey, + conversationKey, + ); + } + } + } + + await _databaseService.upsertChatMessage(message, conversationKey); + if (!message.pendingSync) { + await _databaseService.removePendingDuplicates(conversationKey, message); + } + await _refreshConversation(conversationKey); + } + + Future _loadChatsFromDatabase() async { + await _databaseService.ensureInitialized(); + final grouped = await _databaseService.loadAllChatMessagesGrouped(); + _chats.clear(); + grouped.forEach((conversationKey, messages) { + final chat = _buildChat(conversationKey, messages); + if (chat != null) { + _chats.add(chat); + } + }); + _ensureDefaultGeneralChat(); + _sortChats(); + _emitChats(); + await _updateUnreadCount(); + } + + Future _refreshConversation(String conversationKey) async { + final messages = await _databaseService.loadChatMessages( + conversationKey: conversationKey, + ); + final index = _chats.indexWhere((chat) => chat.id == conversationKey); + + if (messages.isEmpty) { + if (index != -1) { + _chats.removeAt(index); + } + _ensureDefaultGeneralChat(); + _sortChats(); + _emitChats(); + await _updateUnreadCount(); + return; + } + + final chat = _buildChat(conversationKey, messages); + if (chat == null) { + return; + } + + if (index == -1) { + _chats.add(chat); + } else { + _chats[index] = chat; + } + _ensureDefaultGeneralChat(); + _sortChats(); + _emitChats(); + await _updateUnreadCount(); + } + + Chat? _buildChat(String conversationKey, List messages) { + if (messages.isEmpty) { + return null; + } + + messages.sort((a, b) => a.createdAt.compareTo(b.createdAt)); + final lastMessage = messages.last; + + final jobId = messages + .map((m) => m.jobId) + .firstWhere( + (value) => value != null && value.isNotEmpty, + orElse: () => null, + ); + final jobNumber = messages + .map((m) => m.jobNumber) + .firstWhere( + (value) => value != null && value.isNotEmpty, + orElse: () => null, + ); + final counterpart = _determineCounterpart(conversationKey, messages); + + final isJobChat = + conversationKey.startsWith(_jobIdPrefix) || + conversationKey.startsWith(_jobNumberPrefix) || + messages.any((m) => m.messageType == ChatMessageType.jobRelated); + + final chatType = isJobChat ? ChatType.jobSpecific : ChatType.general; + + final counterpartNormalized = + counterpart != null && + counterpart.toLowerCase() == _appState.loggedInEmail!.toLowerCase() + ? _appState.loggedInEmail! + : counterpart; + + final bool isDefaultGeneral = + !isJobChat && + conversationKey.startsWith(_generalPrefix) && + (counterpartNormalized?.toLowerCase() == + _appState.loggedInEmail!.toLowerCase()); + + final title = + isJobChat + ? _buildJobTitle(jobNumber, jobId) + : (isDefaultGeneral + ? 'Allgemeine Nachrichten' + : (counterpart ?? 'Allgemeiner Chat')); + + return Chat( + id: conversationKey, + title: title, + receiver: counterpartNormalized, + type: chatType, + jobId: jobId, + jobNumber: jobNumber, + messages: List.unmodifiable(messages), + lastMessageTime: lastMessage.createdAt, + lastMessagePreview: + lastMessage.contentType == ChatContentType.image + ? '[Bild]' + : lastMessage.content, + ); + } + + String _buildJobTitle(String? jobNumber, String? jobId) { + if (jobNumber != null && jobNumber.isNotEmpty) { + return 'Job $jobNumber'; + } + if (jobId != null && jobId.length >= 6) { + return 'Job ${jobId.substring(0, 6).toUpperCase()}'; + } + return 'Job-Chat'; + } + + String? _determineCounterpart( + String conversationKey, + List messages, + ) { + // Receiver is always the userId for general chats + return _appState.loggedInEmail; + } + + void _sortChats() { + _chats.sort((a, b) => b.lastMessageTime.compareTo(a.lastMessageTime)); + } + + void _emitChats() { + if (_chatsController.isClosed) { + return; + } + _chatsController.add(List.unmodifiable(_chats)); + } + + Future _updateUnreadCount() async { + try { + await _databaseService.ensureInitialized(); + final count = await _databaseService.getTotalUnreadMessageCount(); + developer.log( + '[DEBUG_LOG] Unread count from database: $count', + name: 'ChatService', + ); + _unreadCount = count; + if (!_unreadCountController.isClosed) { + _unreadCountController.add(count); + developer.log( + '[DEBUG_LOG] Emitted unread count to stream: $count', + name: 'ChatService', + ); + } else { + developer.log( + '[DEBUG_LOG] Unread count controller is closed, cannot emit', + name: 'ChatService', + ); + } + } catch (e, st) { + developer.log('Error updating unread count: $e', name: 'ChatService'); + developer.log('Stack trace: $st', name: 'ChatService'); + } + } + + void _ensureDefaultGeneralChat() { + final localId = _primaryLocalIdentifier(); + if (localId == null || localId.isEmpty) { + developer.log( + '[DEBUG_LOG] _ensureDefaultGeneralChat: No local identifier available, skipping', + name: 'ChatService', + ); + return; + } + + final conversationKey = _conversationKeyForParticipants( + localId, + _appState.loggedInEmail!, + ); + + developer.log( + '[DEBUG_LOG] _ensureDefaultGeneralChat: Creating/ensuring default general chat with key: $conversationKey (localId=$localId, receiver=${_appState.loggedInEmail})', + name: 'ChatService', + ); + + _chats.removeWhere( + (chat) => + chat.id != conversationKey && + chat.type == ChatType.general && + chat.receiver != null && + chat.receiver!.toLowerCase() == + _appState.loggedInEmail!.toLowerCase() && + chat.messages.isEmpty, + ); + final index = _chats.indexWhere((chat) => chat.id == conversationKey); + + if (index == -1) { + developer.log( + '[DEBUG_LOG] _ensureDefaultGeneralChat: Chat not found, creating new "Allgemeine Nachrichten" chat', + name: 'ChatService', + ); + _chats.add( + Chat( + id: conversationKey, + title: 'Allgemeine Nachrichten', + receiver: _appState.loggedInEmail!, + type: ChatType.general, + jobId: null, + jobNumber: null, + messages: const [], + lastMessageTime: DateTime.fromMillisecondsSinceEpoch(0), + lastMessagePreview: 'Noch keine Nachrichten', + ), + ); + } else { + developer.log( + '[DEBUG_LOG] _ensureDefaultGeneralChat: Chat already exists at index $index, verifying/updating it', + name: 'ChatService', + ); + final existing = _chats[index]; + if (existing.type != ChatType.general || + existing.receiver == null || + existing.receiver!.toLowerCase() != + _appState.loggedInEmail!.toLowerCase() || + (existing.messages.isEmpty && + existing.title != 'Allgemeine Nachrichten')) { + developer.log( + '[DEBUG_LOG] _ensureDefaultGeneralChat: Updating existing chat to ensure correct settings', + name: 'ChatService', + ); + _chats[index] = Chat( + id: existing.id, + title: + existing.messages.isEmpty + ? 'Allgemeine Nachrichten' + : existing.title, + receiver: _appState.loggedInEmail!, + type: ChatType.general, + jobId: existing.jobId, + jobNumber: existing.jobNumber, + messages: existing.messages, + lastMessageTime: existing.lastMessageTime, + lastMessagePreview: existing.lastMessagePreview, + ); + } else { + developer.log( + '[DEBUG_LOG] _ensureDefaultGeneralChat: Existing chat is already correctly configured (${existing.messages.length} messages)', + name: 'ChatService', + ); + } + } + } + + String? _primaryLocalIdentifier() { + return _appState.loggedInEmail; + } +} diff --git a/app/lib/services/dart_mq.dart b/app/lib/services/dart_mq.dart new file mode 100644 index 0000000..6ffcf4e --- /dev/null +++ b/app/lib/services/dart_mq.dart @@ -0,0 +1,100 @@ +import 'package:votianlt_app/services/developer.dart' as developer; + +/// A lightweight in-app message bus ("dart_mq") for pub/sub style communication. +/// +// Usage: +// final mq = DartMQ(); +// final sub = mq.subscribe('connection/status', (isOnline) { /* ... */ }); +// mq.publish('connection/status', true); +// sub.cancel(); +class DartMQ { + DartMQ._internal(); + static final DartMQ _instance = DartMQ._internal(); + factory DartMQ() => _instance; + + final Map> _subscribers = {}; + + /// Subscribe to a topic. Returns a cancellable subscription handle. + DartMQSubscription subscribe(String topic, void Function(T data) handler) { + final sub = _DartMQSubscriber(topic: topic, handler: handler); + final list = _subscribers.putIfAbsent(topic, () => <_DartMQSubscriber>[]); + list.add(sub); + return DartMQSubscription._(this, sub); + } + + /// Publish a message to a topic. If no subscribers exist, this is a no-op. + void publish(String topic, T data) { + final list = _subscribers[topic]; + if (list == null || list.isEmpty) return; + + // Make a defensive copy to allow cancellation during iteration. + final current = List<_DartMQSubscriber>.from(list); + for (final s in current) { + // Only deliver if types match; otherwise, try dynamic fallback + if (s is _DartMQSubscriber) { + try { + s.handler(data); + } catch (e, stackTrace) { + developer.log( + 'Error delivering message to subscriber on topic "$topic": $e', + ); + developer.log('Stack trace: $stackTrace'); + } + } else { + // Fallback delivery for handlers expecting dynamic or different T + try { + final dynamicHandler = s.handler as dynamic; + dynamicHandler(data); + } catch (e, stackTrace) { + developer.log( + 'Error delivering dynamic message to subscriber on topic "$topic": $e', + ); + developer.log('Stack trace: $stackTrace'); + } + } + } + } + + void _cancel(_DartMQSubscriber subscriber) { + final list = _subscribers[subscriber.topic]; + if (list == null) return; + list.remove(subscriber); + if (list.isEmpty) { + _subscribers.remove(subscriber.topic); + } + } +} + +/// Cancellable subscription handle +class DartMQSubscription { + final DartMQ _mq; + final _DartMQSubscriber _subscriber; + bool _isCancelled = false; + + DartMQSubscription._(this._mq, this._subscriber); + + void cancel() { + if (_isCancelled) return; + _isCancelled = true; + _mq._cancel(_subscriber); + } +} + +class _DartMQSubscriber { + final String topic; + final void Function(T data) handler; + _DartMQSubscriber({required this.topic, required this.handler}); +} + +/// Common topics used in the app +class MQTopics { + static const connectionStatus = 'connection/status'; // bool + static const authResponse = 'auth/response'; // Map + static const jobsResponse = 'jobs/response'; // List + static const taskEvents = 'task/events'; // Map + static const jobsUpdated = 'app/jobsUpdated'; // void/null + static const jobDeleted = 'job/deleted'; // Map {jobId, jobNumber, deletedAt} + static const jobCreated = 'job/created'; // Map - full job data + static const chatIncoming = 'chat/incoming'; // ChatMessage + static const chatOutgoing = 'chat/outgoing'; // ChatMessage +} diff --git a/app/lib/services/database_service.dart b/app/lib/services/database_service.dart new file mode 100644 index 0000000..2199dcb --- /dev/null +++ b/app/lib/services/database_service.dart @@ -0,0 +1,1529 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:path/path.dart'; +import 'package:path_provider/path_provider.dart'; +import 'package:votianlt_app/services/developer.dart' as developer; + +import '../models/chat_message.dart'; +import '../models/job.dart'; +import '../models/queued_message.dart'; +import '../objectbox.g.dart'; +import '../entities/job_entity.dart'; +import '../entities/task_status_entity.dart'; +import '../entities/user_data_entity.dart'; +import '../entities/photo_entity.dart'; +import '../entities/queued_message_entity.dart'; +import '../entities/chat_message_entity.dart'; + +class DatabaseService { + static final DatabaseService _instance = DatabaseService._internal(); + factory DatabaseService() => _instance; + DatabaseService._internal(); + + Store? _store; + Completer? _initializingCompleter; + + bool get isInitialized => _store != null; + + /// Initialize ObjectBox database + Future initialize() async { + if (_store != null) { + return; + } + if (_initializingCompleter != null) { + return _initializingCompleter!.future; + } + + final completer = Completer(); + _initializingCompleter = completer; + try { + developer.log('Initializing ObjectBox database...', name: 'DatabaseService'); + + // Get database path + final docsDir = await getApplicationDocumentsDirectory(); + final path = join(docsDir.path, 'objectbox'); + + // Open ObjectBox store + _store = await openStore(directory: path); + + developer.log( + 'ObjectBox database initialized successfully', + name: 'DatabaseService', + ); + await _logDatabaseStats(); + completer.complete(); + } catch (e, stackTrace) { + developer.log( + 'Error initializing ObjectBox database: $e', + name: 'DatabaseService', + ); + developer.log('Stack trace: $stackTrace', name: 'DatabaseService'); + if (!completer.isCompleted) { + completer.completeError(e); + } + rethrow; + } finally { + _initializingCompleter = null; + } + } + + Future ensureInitialized() async { + if (isInitialized) { + return; + } + await initialize(); + } + + + + /// Log database statistics + Future _logDatabaseStats() async { + try { + if (_store == null) return; + + final jobCount = _store!.box().count(); + final taskStatusCount = _store!.box().count(); + final userDataCount = _store!.box().count(); + + developer.log( + 'Database stats - Jobs: $jobCount, Task statuses: $taskStatusCount, User data: $userDataCount', + name: 'DatabaseService', + ); + } catch (e) { + developer.log( + 'Error getting database stats: $e', + name: 'DatabaseService', + ); + } + } + + /// Save jobs to database + Future saveJobs(List jobs) async { + try { + if (_store == null) { + developer.log('Database not initialized', name: 'DatabaseService'); + return; + } + + developer.log( + 'Saving ${jobs.length} jobs to database...', + name: 'DatabaseService', + ); + + final now = DateTime.now(); + final jobBox = _store!.box(); + final taskStatusBox = _store!.box(); + + // Clear existing jobs and related task statuses before inserting new ones + jobBox.removeAll(); + taskStatusBox.removeAll(); + + // Save new jobs + for (final job in jobs) { + final normalized = job.normalized(); + final jobEntity = JobEntity( + jobId: normalized.id, + jobData: jsonEncode(normalized.toJson()), + createdAt: now, + updatedAt: now, + ); + jobBox.put(jobEntity); + + // Also persist task completion states from JSON (adopt status on load) + // Only set completed=true entries to avoid overwriting local progress with false + for (final task in normalized.tasks) { + if (task.completed) { + final taskStatusEntity = TaskStatusEntity( + taskId: task.id, + completed: true, + completedAt: now, + createdAt: now, + updatedAt: now, + ); + taskStatusBox.put(taskStatusEntity); + } + } + } + + developer.log( + 'Jobs and task statuses saved successfully', + name: 'DatabaseService', + ); + } catch (e, stackTrace) { + developer.log('Error saving jobs: $e', name: 'DatabaseService'); + developer.log('Stack trace: $stackTrace', name: 'DatabaseService'); + } + } + + /// Delete a single job by ID + Future deleteJob(String jobId) async { + try { + if (_store == null) { + developer.log('Database not initialized', name: 'DatabaseService'); + return; + } + + developer.log('Deleting job $jobId from database...', name: 'DatabaseService'); + + final jobBox = _store!.box(); + final query = jobBox.query(JobEntity_.jobId.equals(jobId)).build(); + final entities = query.find(); + query.close(); + + if (entities.isNotEmpty) { + jobBox.remove(entities.first.id); + developer.log('Job $jobId deleted successfully', name: 'DatabaseService'); + } else { + developer.log('Job $jobId not found in database', name: 'DatabaseService'); + } + } catch (e, stackTrace) { + developer.log('Error deleting job: $e', name: 'DatabaseService'); + developer.log('Stack trace: $stackTrace', name: 'DatabaseService'); + } + } + + /// Load jobs from database + Future> loadJobs() async { + try { + if (_store == null) { + developer.log('Database not initialized', name: 'DatabaseService'); + return []; + } + + developer.log('Loading jobs from database...', name: 'DatabaseService'); + + final jobBox = _store!.box(); + final jobEntities = jobBox.getAll(); + + final List jobs = []; + + for (final entity in jobEntities) { + try { + final jobData = jsonDecode(entity.jobData); + final job = Job.fromJson(Map.from(jobData)); + jobs.add(job); + } catch (e) { + developer.log('Error parsing job data: $e', name: 'DatabaseService'); + } + } + + // Sort by created_at DESC + jobs.sort((a, b) => b.createdAt.compareTo(a.createdAt)); + + developer.log( + 'Loaded ${jobs.length} jobs from database', + name: 'DatabaseService', + ); + + // Log message types for job-related messages in database + if (jobs.isNotEmpty) { + try { + final chatBox = _store!.box(); + final query = chatBox.query( + (ChatMessageEntity_.jobId.notNull() | ChatMessageEntity_.jobNumber.notNull()) + ).build(); + final messagesWithJobs = query.find(); + query.close(); + + developer.log( + 'Found ${messagesWithJobs.length} messages related to jobs in database', + name: 'DatabaseService', + ); + + // Group by message type and log + final Map messageTypeCount = {}; + for (final msg in messagesWithJobs) { + final messageType = msg.messageType; + final jobId = msg.jobId; + final jobNumber = msg.jobNumber; + + messageTypeCount[messageType] = + (messageTypeCount[messageType] ?? 0) + 1; + + developer.log( + 'Job-related message: messageType=$messageType, jobId=$jobId, jobNumber=$jobNumber', + name: 'DatabaseService', + ); + } + + // Summary log + if (messageTypeCount.isNotEmpty) { + developer.log( + 'Message type summary for jobs in database: $messageTypeCount', + name: 'DatabaseService', + ); + } + } catch (e) { + developer.log( + 'Error logging job message types: $e', + name: 'DatabaseService', + ); + } + } + + return jobs; + } catch (e, stackTrace) { + developer.log('Error loading jobs: $e', name: 'DatabaseService'); + developer.log('Stack trace: $stackTrace', name: 'DatabaseService'); + return []; + } + } + + /// Save task completion status + Future saveTaskStatus(String taskId, bool completed) async { + try { + if (_store == null) { + developer.log('Database not initialized', name: 'DatabaseService'); + return; + } + + final now = DateTime.now(); + final taskStatusBox = _store!.box(); + + // Find existing entity by taskId + final query = taskStatusBox.query(TaskStatusEntity_.taskId.equals(taskId)).build(); + final existing = query.findFirst(); + query.close(); + + if (existing != null) { + existing.completed = completed; + existing.completedAt = completed ? now : null; + existing.updatedAt = now; + taskStatusBox.put(existing); + } else { + final entity = TaskStatusEntity( + taskId: taskId, + completed: completed, + completedAt: completed ? now : null, + createdAt: now, + updatedAt: now, + ); + taskStatusBox.put(entity); + } + + developer.log( + 'Task status saved: $taskId = $completed', + name: 'DatabaseService', + ); + } catch (e, stackTrace) { + developer.log('Error saving task status: $e', name: 'DatabaseService'); + developer.log('Stack trace: $stackTrace', name: 'DatabaseService'); + } + } + + /// Load task completion status + Future loadTaskStatus(String taskId) async { + try { + if (_store == null) { + developer.log('Database not initialized', name: 'DatabaseService'); + return false; + } + + final taskStatusBox = _store!.box(); + final query = taskStatusBox.query(TaskStatusEntity_.taskId.equals(taskId)).build(); + final entity = query.findFirst(); + query.close(); + + if (entity != null) { + return entity.completed; + } + + return false; + } catch (e, stackTrace) { + developer.log('Error loading task status: $e', name: 'DatabaseService'); + developer.log('Stack trace: $stackTrace', name: 'DatabaseService'); + return false; + } + } + + /// Load all task completion statuses + Future> loadAllTaskStatuses() async { + try { + if (_store == null) { + developer.log('Database not initialized', name: 'DatabaseService'); + return {}; + } + + final taskStatusBox = _store!.box(); + final entities = taskStatusBox.getAll(); + final Map statuses = {}; + + for (final entity in entities) { + statuses[entity.taskId] = entity.completed; + } + + developer.log( + 'Loaded ${statuses.length} task statuses from database', + name: 'DatabaseService', + ); + return statuses; + } catch (e, stackTrace) { + developer.log('Error loading task statuses: $e', name: 'DatabaseService'); + developer.log('Stack trace: $stackTrace', name: 'DatabaseService'); + return {}; + } + } + + /// Save user ID + Future saveUserId(String userId) async { + try { + if (_store == null) { + developer.log('Database not initialized', name: 'DatabaseService'); + return; + } + + await saveKeyValue('userId', userId); + developer.log('User ID saved: $userId', name: 'DatabaseService'); + } catch (e, stackTrace) { + developer.log('Error saving user ID: $e', name: 'DatabaseService'); + developer.log('Stack trace: $stackTrace', name: 'DatabaseService'); + } + } + + /// Load user ID + Future loadUserId() async { + try { + if (_store == null) { + developer.log('Database not initialized', name: 'DatabaseService'); + return null; + } + + final userId = await loadKeyValue('userId'); + + if (userId != null) { + developer.log('User ID loaded: $userId', name: 'DatabaseService'); + return userId; + } + + developer.log('No user ID found in database', name: 'DatabaseService'); + return null; + } catch (e, stackTrace) { + developer.log('Error loading user ID: $e', name: 'DatabaseService'); + developer.log('Stack trace: $stackTrace', name: 'DatabaseService'); + return null; + } + } + + /// Mark a job as seen (persistently) + Future setJobSeen(String jobId) async { + try { + if (_store == null) { + developer.log('Database not initialized', name: 'DatabaseService'); + return; + } + await saveKeyValue('job_seen:$jobId', '1'); + } catch (e, stackTrace) { + developer.log('Error setting job seen: $e', name: 'DatabaseService'); + developer.log('Stack trace: $stackTrace', name: 'DatabaseService'); + } + } + + /// Check if a job has been seen + Future isJobSeen(String jobId) async { + try { + if (_store == null) { + developer.log('Database not initialized', name: 'DatabaseService'); + return false; + } + final value = await loadKeyValue('job_seen:$jobId'); + return value != null; + } catch (e, stackTrace) { + developer.log('Error checking job seen: $e', name: 'DatabaseService'); + developer.log('Stack trace: $stackTrace', name: 'DatabaseService'); + return false; + } + } + + /// Load seen flags for a set of job IDs (batch) + Future> loadSeenJobsForIds(Iterable jobIds) async { + final Map map = {}; + try { + if (_store == null) { + developer.log('Database not initialized', name: 'DatabaseService'); + return map; + } + if (jobIds.isEmpty) return map; + + final userDataBox = _store!.box(); + final keys = jobIds.map((id) => 'job_seen:$id').toList(); + + for (final key in keys) { + final query = userDataBox.query(UserDataEntity_.key.equals(key)).build(); + final entity = query.findFirst(); + query.close(); + + final jobId = key.replaceFirst('job_seen:', ''); + map[jobId] = entity != null; + } + } catch (e, stackTrace) { + developer.log('Error loading seen jobs: $e', name: 'DatabaseService'); + developer.log('Stack trace: $stackTrace', name: 'DatabaseService'); + } + return map; + } + + /// Clear all data (for logout) + Future clearAllData() async { + try { + if (_store == null) { + developer.log('Database not initialized', name: 'DatabaseService'); + return; + } + + developer.log('Clearing all database data...', name: 'DatabaseService'); + + _store!.box().removeAll(); + _store!.box().removeAll(); + _store!.box().removeAll(); + + developer.log('All database data cleared', name: 'DatabaseService'); + } catch (e, stackTrace) { + developer.log( + 'Error clearing database data: $e', + name: 'DatabaseService', + ); + developer.log('Stack trace: $stackTrace', name: 'DatabaseService'); + } + } + + /// Clear all jobs and related data (task statuses, photos). + /// Preserves user credentials, chat messages, and other user data. + /// Called after reconnection before notifying server. + Future clearAllJobsAndRelatedData() async { + try { + if (_store == null) { + developer.log('Database not initialized', name: 'DatabaseService'); + return; + } + + developer.log( + 'Clearing all jobs and related data...', + name: 'DatabaseService', + ); + + final jobBox = _store!.box(); + final taskStatusBox = _store!.box(); + final photoBox = _store!.box(); + + final jobCount = jobBox.count(); + final taskStatusCount = taskStatusBox.count(); + final photoCount = photoBox.count(); + + jobBox.removeAll(); + taskStatusBox.removeAll(); + photoBox.removeAll(); + + // Note: Chat messages are intentionally NOT deleted here + // to preserve chat history across reconnections. + + developer.log( + 'Cleared $jobCount jobs, $taskStatusCount task statuses, $photoCount photos (chat messages preserved)', + name: 'DatabaseService', + ); + } catch (e, stackTrace) { + developer.log( + 'Error clearing jobs and related data: $e', + name: 'DatabaseService', + ); + developer.log('Stack trace: $stackTrace', name: 'DatabaseService'); + } + } + + /// Upsert a single job and update its related task statuses + Future saveOrUpdateJob(Job job) async { + try { + if (_store == null) { + developer.log('Database not initialized', name: 'DatabaseService'); + return; + } + + final now = DateTime.now(); + final normalized = job.normalized(); + + final jobBox = _store!.box(); + final taskStatusBox = _store!.box(); + + // Find existing job entity by jobId + final jobQuery = jobBox.query(JobEntity_.jobId.equals(normalized.id)).build(); + final existingJob = jobQuery.findFirst(); + jobQuery.close(); + + if (existingJob != null) { + existingJob.jobData = jsonEncode(normalized.toJson()); + existingJob.updatedAt = now; + jobBox.put(existingJob); + } else { + final jobEntity = JobEntity( + jobId: normalized.id, + jobData: jsonEncode(normalized.toJson()), + createdAt: now, + updatedAt: now, + ); + jobBox.put(jobEntity); + } + + // Update task_status for this job only: + // 1) Remove any existing statuses for the tasks of this job (to avoid stale entries) + final taskIds = normalized.tasks.map((t) => t.id).toList(); + if (taskIds.isNotEmpty) { + for (final taskId in taskIds) { + final query = taskStatusBox.query(TaskStatusEntity_.taskId.equals(taskId)).build(); + final entities = query.find(); + query.close(); + for (final entity in entities) { + taskStatusBox.remove(entity.id); + } + } + } + + // 2) Insert completed=true entries for tasks coming as completed from JSON + for (final t in normalized.tasks) { + if (t.completed) { + final taskStatusEntity = TaskStatusEntity( + taskId: t.id, + completed: true, + completedAt: now, + createdAt: now, + updatedAt: now, + ); + taskStatusBox.put(taskStatusEntity); + } + } + + developer.log( + 'Upserted job ${normalized.id} and updated ${taskIds.length} task statuses', + name: 'DatabaseService', + ); + } catch (e, st) { + developer.log('Error in saveOrUpdateJob: $e', name: 'DatabaseService'); + developer.log('Stack trace: $st', name: 'DatabaseService'); + } + } + + Future deleteJobAndRelatedData(Job job) async { + try { + await ensureInitialized(); + if (_store == null) { + developer.log('Database not initialized', name: 'DatabaseService'); + return; + } + + final trimmedJobId = job.id.trim(); + final jobBox = _store!.box(); + final userDataBox = _store!.box(); + final taskStatusBox = _store!.box(); + final photoBox = _store!.box(); + + if (trimmedJobId.isNotEmpty) { + // Delete job + final jobQuery = jobBox.query(JobEntity_.jobId.equals(trimmedJobId)).build(); + final jobEntities = jobQuery.find(); + jobQuery.close(); + for (final entity in jobEntities) { + jobBox.remove(entity.id); + } + + // Delete job_seen flag + final seenQuery = userDataBox.query(UserDataEntity_.key.equals('job_seen:$trimmedJobId')).build(); + final seenEntities = seenQuery.find(); + seenQuery.close(); + for (final entity in seenEntities) { + userDataBox.remove(entity.id); + } + } + + final taskIds = job.tasks + .map((task) => task.id.trim()) + .where((id) => id.isNotEmpty) + .toList(); + + if (taskIds.isNotEmpty) { + for (final taskId in taskIds) { + // Delete task status + final taskQuery = taskStatusBox.query(TaskStatusEntity_.taskId.equals(taskId)).build(); + final taskEntities = taskQuery.find(); + taskQuery.close(); + for (final entity in taskEntities) { + taskStatusBox.remove(entity.id); + } + + // Delete photos + final photoQuery = photoBox.query(PhotoEntity_.taskId.equals(taskId)).build(); + final photoEntities = photoQuery.find(); + photoQuery.close(); + for (final entity in photoEntities) { + photoBox.remove(entity.id); + } + + // Delete user data related to task (photos, signatures, barcodes) + final allUserData = userDataBox.getAll(); + for (final entity in allUserData) { + if (entity.key.contains(':$taskId')) { + userDataBox.remove(entity.id); + } + } + } + } + + final trimmedJobNumber = + job.jobNumber.trim().isEmpty ? null : job.jobNumber.trim(); + final conversationKeys = [ + if (trimmedJobId.isNotEmpty) 'job:${trimmedJobId.toLowerCase()}', + if (trimmedJobNumber != null) + 'job_number:${trimmedJobNumber.toLowerCase()}', + ]; + await deleteChatMessagesForJob( + jobId: trimmedJobId.isNotEmpty ? trimmedJobId : null, + jobNumber: trimmedJobNumber, + conversationKeys: conversationKeys, + ); + + developer.log( + 'Deleted job $trimmedJobId and related local data', + name: 'DatabaseService', + ); + } catch (e, st) { + developer.log( + 'Error deleting job ${job.id}: $e', + name: 'DatabaseService', + ); + developer.log('Stack trace: $st', name: 'DatabaseService'); + } + } + + /// Save Base64-encoded photos for a task into user_data table (legacy list storage) + Future saveTaskPhotos(String taskId, List base64Photos) async { + try { + if (_store == null) { + developer.log('Database not initialized', name: 'DatabaseService'); + return; + } + final key = 'task_photos:$taskId'; + final value = jsonEncode(base64Photos); + await saveKeyValue(key, value); + developer.log( + 'Saved ${base64Photos.length} photos for task $taskId', + name: 'DatabaseService', + ); + } catch (e, st) { + developer.log('Error saving task photos: $e', name: 'DatabaseService'); + developer.log('Stack trace: $st', name: 'DatabaseService'); + } + } + + /// Load Base64-encoded photos for a task from user_data table + Future> loadTaskPhotos(String taskId) async { + try { + if (_store == null) { + developer.log('Database not initialized', name: 'DatabaseService'); + return []; + } + final key = 'task_photos:$taskId'; + final raw = await loadKeyValue(key); + if (raw == null) return []; + final decoded = jsonDecode(raw); + if (decoded is List) { + return decoded.map((e) => e.toString()).toList(); + } + return []; + } catch (e, st) { + developer.log('Error loading task photos: $e', name: 'DatabaseService'); + developer.log('Stack trace: $st', name: 'DatabaseService'); + return []; + } + } + + /// Save photos into the dedicated photos collection (one row per photo) + Future savePhotosForTask( + String taskId, + List base64Photos, + ) async { + try { + if (_store == null) { + developer.log('Database not initialized', name: 'DatabaseService'); + return; + } + final photoBox = _store!.box(); + + // Clear existing photos for this task first + final query = photoBox.query(PhotoEntity_.taskId.equals(taskId)).build(); + final existingPhotos = query.find(); + query.close(); + for (final photo in existingPhotos) { + photoBox.remove(photo.id); + } + + final now = DateTime.now(); + for (int i = 0; i < base64Photos.length; i++) { + final data = base64Photos[i]; + final photoEntity = PhotoEntity( + taskId: taskId, + photoIndex: i, + data: data, + createdAt: now, + ); + photoBox.put(photoEntity); + } + + developer.log( + 'Saved ${base64Photos.length} photos into collection for task $taskId', + name: 'DatabaseService', + ); + } catch (e, st) { + developer.log( + 'Error saving photos for task to collection: $e', + name: 'DatabaseService', + ); + developer.log('Stack trace: $st', name: 'DatabaseService'); + } + } + + /// Save signature SVG for a task into user_data table + Future saveTaskSignature(String taskId, String svg) async { + try { + if (_store == null) { + developer.log('Database not initialized', name: 'DatabaseService'); + return; + } + final key = 'task_signature_svg:$taskId'; + await saveKeyValue(key, svg); + developer.log( + 'Saved signature SVG for task $taskId', + name: 'DatabaseService', + ); + } catch (e, st) { + developer.log( + 'Error saving task signature SVG: $e', + name: 'DatabaseService', + ); + developer.log('Stack trace: $st', name: 'DatabaseService'); + } + } + + /// Load signature SVG for a task from user_data table + Future loadTaskSignature(String taskId) async { + try { + if (_store == null) { + developer.log('Database not initialized', name: 'DatabaseService'); + return null; + } + // Try new SVG key first; fallback to legacy PNG key if present + final svgKey = 'task_signature_svg:$taskId'; + final legacyKey = 'task_signature:$taskId'; + + String? result = await loadKeyValue(svgKey); + result ??= await loadKeyValue(legacyKey); + return result; + } catch (e, st) { + developer.log( + 'Error loading task signature (SVG): $e', + name: 'DatabaseService', + ); + developer.log('Stack trace: $st', name: 'DatabaseService'); + return null; + } + } + + /// Save barcodes for a task into user_data table + Future saveTaskBarcodes(String taskId, List barcodes) async { + try { + if (_store == null) { + developer.log('Database not initialized', name: 'DatabaseService'); + return; + } + final key = 'task_barcodes:$taskId'; + final value = jsonEncode(barcodes); + await saveKeyValue(key, value); + developer.log( + 'Saved ${barcodes.length} barcodes for task $taskId', + name: 'DatabaseService', + ); + } catch (e, st) { + developer.log('Error saving task barcodes: $e', name: 'DatabaseService'); + developer.log('Stack trace: $st', name: 'DatabaseService'); + } + } + + /// Load barcodes for a task from user_data table + Future> loadTaskBarcodes(String taskId) async { + try { + if (_store == null) { + developer.log('Database not initialized', name: 'DatabaseService'); + return []; + } + final key = 'task_barcodes:$taskId'; + final raw = await loadKeyValue(key); + if (raw == null) return []; + final decoded = jsonDecode(raw); + if (decoded is List) { + return decoded.map((e) => e.toString()).toList(); + } + return []; + } catch (e, st) { + developer.log('Error loading task barcodes: $e', name: 'DatabaseService'); + developer.log('Stack trace: $st', name: 'DatabaseService'); + return []; + } + } + + /// Close database connections + Future close() async { + try { + _store?.close(); + _store = null; + + developer.log('Database connection closed', name: 'DatabaseService'); + } catch (e, stackTrace) { + developer.log('Error closing database: $e', name: 'DatabaseService'); + developer.log('Stack trace: $stackTrace', name: 'DatabaseService'); + } + } + + /// Generic helpers: save and load key-value pairs in user_data table + Future saveKeyValue(String key, String value) async { + try { + if (_store == null) { + developer.log('Database not initialized', name: 'DatabaseService'); + return; + } + final now = DateTime.now(); + final userDataBox = _store!.box(); + + // Find existing entity by key + final query = userDataBox.query(UserDataEntity_.key.equals(key)).build(); + final existing = query.findFirst(); + query.close(); + + if (existing != null) { + existing.value = value; + existing.updatedAt = now; + userDataBox.put(existing); + } else { + final entity = UserDataEntity( + key: key, + value: value, + createdAt: now, + updatedAt: now, + ); + userDataBox.put(entity); + } + + developer.log('Saved key "$key"', name: 'DatabaseService'); + } catch (e, st) { + developer.log('Error saving key "$key": $e', name: 'DatabaseService'); + developer.log('Stack trace: $st', name: 'DatabaseService'); + } + } + + Future loadKeyValue(String key) async { + try { + if (_store == null) { + developer.log('Database not initialized', name: 'DatabaseService'); + return null; + } + final userDataBox = _store!.box(); + final query = userDataBox.query(UserDataEntity_.key.equals(key)).build(); + final entity = query.findFirst(); + query.close(); + + return entity?.value; + } catch (e, st) { + developer.log('Error loading key "$key": $e', name: 'DatabaseService'); + developer.log('Stack trace: $st', name: 'DatabaseService'); + return null; + } + } + + Future deleteKeyValue(String key) async { + try { + if (_store == null) { + developer.log('Database not initialized', name: 'DatabaseService'); + return; + } + final userDataBox = _store!.box(); + final query = userDataBox.query(UserDataEntity_.key.equals(key)).build(); + final entity = query.findFirst(); + query.close(); + + if (entity != null) { + userDataBox.remove(entity.id); + developer.log('Deleted key "$key"', name: 'DatabaseService'); + } + } catch (e, st) { + developer.log('Error deleting key "$key": $e', name: 'DatabaseService'); + developer.log('Stack trace: $st', name: 'DatabaseService'); + } + } + + // Credentials persistence ---------------------------------------------------- + + /// Save login credentials for auto-login on app restart + Future saveCredentials(String email, String password) async { + await saveKeyValue('auth_email', email); + await saveKeyValue('auth_password', password); + developer.log('Credentials saved for $email', name: 'DatabaseService'); + } + + /// Load saved login credentials + /// Returns null if no credentials are stored + Future<({String email, String password})?> loadCredentials() async { + final email = await loadKeyValue('auth_email'); + final password = await loadKeyValue('auth_password'); + if (email != null && password != null) { + developer.log('Credentials loaded for $email', name: 'DatabaseService'); + return (email: email, password: password); + } + developer.log('No credentials found', name: 'DatabaseService'); + return null; + } + + /// Delete saved login credentials (on logout) + Future deleteCredentials() async { + await deleteKeyValue('auth_email'); + await deleteKeyValue('auth_password'); + developer.log('Credentials deleted', name: 'DatabaseService'); + } + + // Chat messages persistence ------------------------------------------------- + + Future upsertChatMessage( + ChatMessage message, + String conversationKey, + ) async { + try { + await ensureInitialized(); + if (_store == null) { + developer.log('Database not initialized', name: 'DatabaseService'); + return; + } + + final directionString = chatDirectionToString(message.direction); + + developer.log( + '[DEBUG_LOG] Upserting message: id=${message.id}, direction=${message.direction} (stored as: $directionString), read=${message.read}', + name: 'DatabaseService', + ); + + final chatBox = _store!.box(); + + // Find existing entity by messageId + final query = chatBox.query(ChatMessageEntity_.messageId.equals(message.id)).build(); + final existing = query.findFirst(); + query.close(); + + if (existing != null) { + existing.conversationKey = conversationKey; + existing.content = message.content; + existing.contentType = chatContentTypeToString(message.contentType); + existing.createdAt = message.createdAt; + existing.origin = directionString; + existing.messageType = chatMessageTypeToString(message.messageType); + existing.jobId = message.jobId; + existing.jobNumber = message.jobNumber; + existing.read = message.read; + existing.pendingSync = message.pendingSync; + chatBox.put(existing); + } else { + final entity = ChatMessageEntity( + messageId: message.id, + conversationKey: conversationKey, + content: message.content, + contentType: chatContentTypeToString(message.contentType), + createdAt: message.createdAt, + origin: directionString, + messageType: chatMessageTypeToString(message.messageType), + jobId: message.jobId, + jobNumber: message.jobNumber, + read: message.read, + pendingSync: message.pendingSync, + ); + chatBox.put(entity); + } + } catch (e, st) { + developer.log( + 'Error saving chat message ${message.id}: $e', + name: 'DatabaseService', + ); + developer.log('Stack trace: $st', name: 'DatabaseService'); + } + } + + Future migrateConversationKey(String fromKey, String toKey) async { + if (fromKey == toKey) { + return; + } + try { + await ensureInitialized(); + if (_store == null) { + developer.log('Database not initialized', name: 'DatabaseService'); + return; + } + final chatBox = _store!.box(); + final query = chatBox.query(ChatMessageEntity_.conversationKey.equals(fromKey)).build(); + final entities = query.find(); + query.close(); + + for (final entity in entities) { + entity.conversationKey = toKey; + chatBox.put(entity); + } + } catch (e, st) { + developer.log( + 'Error migrating conversation key from "$fromKey" to "$toKey": $e', + name: 'DatabaseService', + ); + developer.log('Stack trace: $st', name: 'DatabaseService'); + } + } + + Future removePendingDuplicates( + String conversationKey, + ChatMessage message, + ) async { + try { + await ensureInitialized(); + if (_store == null) { + developer.log('Database not initialized', name: 'DatabaseService'); + return; + } + + final chatBox = _store!.box(); + final query = chatBox.query( + ChatMessageEntity_.conversationKey.equals(conversationKey) & + ChatMessageEntity_.pendingSync.equals(true) & + ChatMessageEntity_.content.equals(message.content) & + ChatMessageEntity_.contentType.equals(chatContentTypeToString(message.contentType)) & + ChatMessageEntity_.messageId.notEquals(message.id) + ).build(); + final entities = query.find(); + query.close(); + + for (final entity in entities) { + chatBox.remove(entity.id); + } + } catch (e, st) { + developer.log( + 'Error removing pending duplicates: $e', + name: 'DatabaseService', + ); + developer.log('Stack trace: $st', name: 'DatabaseService'); + } + } + + Future> loadChatMessages({String? conversationKey}) async { + try { + await ensureInitialized(); + if (_store == null) { + developer.log('Database not initialized', name: 'DatabaseService'); + return []; + } + + final chatBox = _store!.box(); + List entities; + + if (conversationKey != null) { + final query = chatBox.query(ChatMessageEntity_.conversationKey.equals(conversationKey)) + .order(ChatMessageEntity_.createdAt) + .build(); + entities = query.find(); + query.close(); + } else { + entities = chatBox.getAll(); + entities.sort((a, b) => a.createdAt.compareTo(b.createdAt)); + } + + return entities.map(_chatMessageFromEntity).toList(); + } catch (e, st) { + developer.log('Error loading chat messages: $e', name: 'DatabaseService'); + developer.log('Stack trace: $st', name: 'DatabaseService'); + return []; + } + } + + Future>> loadAllChatMessagesGrouped() async { + try { + await ensureInitialized(); + if (_store == null) { + developer.log('Database not initialized', name: 'DatabaseService'); + return {}; + } + + final chatBox = _store!.box(); + final entities = chatBox.getAll(); + + // Sort by conversation_key and created_at + entities.sort((a, b) { + final keyCompare = a.conversationKey.compareTo(b.conversationKey); + if (keyCompare != 0) return keyCompare; + return a.createdAt.compareTo(b.createdAt); + }); + + final Map> grouped = {}; + for (final entity in entities) { + final key = entity.conversationKey; + final message = _chatMessageFromEntity(entity); + final list = grouped.putIfAbsent(key, () => []); + list.add(message); + } + return grouped; + } catch (e, st) { + developer.log( + 'Error loading grouped chat messages: $e', + name: 'DatabaseService', + ); + developer.log('Stack trace: $st', name: 'DatabaseService'); + return {}; + } + } + + Future markConversationRead(String conversationKey) async { + try { + await ensureInitialized(); + if (_store == null) { + developer.log('Database not initialized', name: 'DatabaseService'); + return; + } + + final chatBox = _store!.box(); + final query = chatBox.query(ChatMessageEntity_.conversationKey.equals(conversationKey)).build(); + final entities = query.find(); + query.close(); + + for (final entity in entities) { + entity.read = true; + chatBox.put(entity); + } + } catch (e, st) { + developer.log( + 'Error marking conversation read: $e', + name: 'DatabaseService', + ); + developer.log('Stack trace: $st', name: 'DatabaseService'); + } + } + + Future deleteChatMessage(String messageId) async { + try { + if (_store == null) { + developer.log('Database not initialized', name: 'DatabaseService'); + return; + } + + final chatBox = _store!.box(); + final query = chatBox.query(ChatMessageEntity_.messageId.equals(messageId)).build(); + final entities = query.find(); + query.close(); + + for (final entity in entities) { + chatBox.remove(entity.id); + } + } catch (e, st) { + developer.log( + 'Error deleting chat message "$messageId": $e', + name: 'DatabaseService', + ); + developer.log('Stack trace: $st', name: 'DatabaseService'); + } + } + + Future deleteChatMessagesForJob({ + String? jobId, + String? jobNumber, + Iterable? conversationKeys, + }) async { + try { + await ensureInitialized(); + if (_store == null) { + developer.log('Database not initialized', name: 'DatabaseService'); + return; + } + + final trimmedJobId = jobId?.trim() ?? ''; + final trimmedJobNumber = jobNumber?.trim() ?? ''; + final keysList = conversationKeys == null + ? [] + : conversationKeys + .map((key) => key.trim()) + .where((key) => key.isNotEmpty) + .toSet() + .toList(); + + if (trimmedJobId.isEmpty && trimmedJobNumber.isEmpty && keysList.isEmpty) { + developer.log( + 'No chat messages matched deletion criteria for jobId=$jobId jobNumber=$jobNumber', + name: 'DatabaseService', + ); + return; + } + + final chatBox = _store!.box(); + final entitiesToDelete = []; + + if (trimmedJobId.isNotEmpty) { + final query = chatBox.query(ChatMessageEntity_.jobId.equals(trimmedJobId)).build(); + entitiesToDelete.addAll(query.find()); + query.close(); + } + + if (trimmedJobNumber.isNotEmpty) { + final query = chatBox.query(ChatMessageEntity_.jobNumber.equals(trimmedJobNumber)).build(); + entitiesToDelete.addAll(query.find()); + query.close(); + } + + if (keysList.isNotEmpty) { + for (final key in keysList) { + final query = chatBox.query(ChatMessageEntity_.conversationKey.equals(key)).build(); + entitiesToDelete.addAll(query.find()); + query.close(); + } + } + + // Remove duplicates by id + final uniqueIds = {}; + for (final entity in entitiesToDelete) { + if (uniqueIds.add(entity.id)) { + chatBox.remove(entity.id); + } + } + + developer.log( + 'Deleted chat messages for jobId=$jobId jobNumber=$jobNumber (conversationKeys=${keysList.length})', + name: 'DatabaseService', + ); + } catch (e, st) { + developer.log( + 'Error deleting chat messages for jobId=$jobId jobNumber=$jobNumber: $e', + name: 'DatabaseService', + ); + developer.log('Stack trace: $st', name: 'DatabaseService'); + } + } + + Future getTotalUnreadMessageCount() async { + try { + if (_store == null) { + developer.log('Database not initialized', name: 'DatabaseService'); + return 0; + } + + final chatBox = _store!.box(); + final query = chatBox.query(ChatMessageEntity_.read.equals(false)).build(); + final count = query.count(); + query.close(); + + developer.log( + '[DEBUG_LOG] Total unread message count: $count', + name: 'DatabaseService', + ); + + return count; + } catch (e, st) { + developer.log( + 'Error getting total unread message count: $e', + name: 'DatabaseService', + ); + developer.log('Stack trace: $st', name: 'DatabaseService'); + return 0; + } + } + + ChatMessage _chatMessageFromEntity(ChatMessageEntity entity) { + return ChatMessage( + id: entity.messageId, + content: entity.content, + contentType: chatContentTypeFromString(entity.contentType), + createdAt: entity.createdAt, + direction: chatDirectionFromString(entity.origin), + messageType: chatMessageTypeFromString(entity.messageType), + jobId: entity.jobId, + jobNumber: entity.jobNumber, + read: entity.read, + pendingSync: entity.pendingSync, + ); + } + + // Message Queue Management + + /// Save a failed message to the queue + Future queueMessage(QueuedMessage message) async { + try { + if (_store == null) { + developer.log('Database not initialized', name: 'DatabaseService'); + return; + } + + final box = _store!.box(); + + // Find existing entity by messageId + final query = box.query(QueuedMessageEntity_.messageId.equals(message.id)).build(); + final existing = query.findFirst(); + query.close(); + + if (existing != null) { + existing.topic = message.topic; + existing.payload = jsonEncode(message.payload); + existing.createdAt = message.createdAt; + existing.retryCount = message.retryCount; + box.put(existing); + } else { + final entity = QueuedMessageEntity( + messageId: message.id, + topic: message.topic, + payload: jsonEncode(message.payload), + createdAt: message.createdAt, + retryCount: message.retryCount, + ); + box.put(entity); + } + + developer.log( + 'Queued message: ${message.id} for topic: ${message.topic}', + name: 'DatabaseService', + ); + } catch (e, st) { + developer.log('Error queuing message: $e', name: 'DatabaseService'); + developer.log('Stack trace: $st', name: 'DatabaseService'); + } + } + + /// Get all queued messages + Future> getQueuedMessages() async { + try { + if (_store == null) { + developer.log('Database not initialized', name: 'DatabaseService'); + return []; + } + + final box = _store!.box(); + final entities = box.getAll(); + + // Sort by created_at ASC + entities.sort((a, b) => a.createdAt.compareTo(b.createdAt)); + + return entities.map((entity) { + return QueuedMessage( + id: entity.messageId, + topic: entity.topic, + payload: jsonDecode(entity.payload), + createdAt: entity.createdAt, + retryCount: entity.retryCount, + ); + }).toList(); + } catch (e, st) { + developer.log( + 'Error getting queued messages: $e', + name: 'DatabaseService', + ); + developer.log('Stack trace: $st', name: 'DatabaseService'); + return []; + } + } + + /// Remove a successfully sent message from the queue + Future removeQueuedMessage(String messageId) async { + try { + if (_store == null) { + developer.log('Database not initialized', name: 'DatabaseService'); + return; + } + + final box = _store!.box(); + final query = box.query(QueuedMessageEntity_.messageId.equals(messageId)).build(); + final entities = query.find(); + query.close(); + + for (final entity in entities) { + box.remove(entity.id); + } + + developer.log( + 'Removed queued message: $messageId', + name: 'DatabaseService', + ); + } catch (e, st) { + developer.log( + 'Error removing queued message: $e', + name: 'DatabaseService', + ); + developer.log('Stack trace: $st', name: 'DatabaseService'); + } + } + + /// Update retry count for a message + Future updateMessageRetryCount( + String messageId, + int retryCount, + ) async { + try { + if (_store == null) { + developer.log('Database not initialized', name: 'DatabaseService'); + return; + } + + final box = _store!.box(); + final query = box.query(QueuedMessageEntity_.messageId.equals(messageId)).build(); + final entity = query.findFirst(); + query.close(); + + if (entity != null) { + entity.retryCount = retryCount; + box.put(entity); + } + + developer.log( + 'Updated retry count for message: $messageId to $retryCount', + name: 'DatabaseService', + ); + } catch (e, st) { + developer.log( + 'Error updating message retry count: $e', + name: 'DatabaseService', + ); + developer.log('Stack trace: $st', name: 'DatabaseService'); + } + } + + /// Clear all queued messages (for cleanup) + Future clearQueuedMessages() async { + try { + if (_store == null) { + developer.log('Database not initialized', name: 'DatabaseService'); + return; + } + + _store!.box().removeAll(); + developer.log( + 'Cleared all queued messages', + name: 'DatabaseService', + ); + } catch (e, st) { + developer.log( + 'Error clearing queued messages: $e', + name: 'DatabaseService', + ); + developer.log('Stack trace: $st', name: 'DatabaseService'); + } + } + + // Language preference persistence ---------------------------------------------------- + + /// Save language preference + Future saveLanguagePreference(String languageCode) async { + await saveKeyValue('language_preference', languageCode); + developer.log('Language preference saved: $languageCode', name: 'DatabaseService'); + } + + /// Load saved language preference + /// Returns null if no preference is stored + Future loadLanguagePreference() async { + final languageCode = await loadKeyValue('language_preference'); + if (languageCode != null) { + developer.log('Language preference loaded: $languageCode', name: 'DatabaseService'); + return languageCode; + } + developer.log('No language preference found', name: 'DatabaseService'); + return null; + } +} diff --git a/app/lib/services/developer.dart b/app/lib/services/developer.dart new file mode 100644 index 0000000..eace307 --- /dev/null +++ b/app/lib/services/developer.dart @@ -0,0 +1,47 @@ +// Wrapper around dart:developer.log that also outputs logs in release mode. +// +// Usage: import this file as `developer` instead of `dart:developer`. +// Then call `developer.log(...)` as usual. In debug/profile, it forwards to +// dart:developer.log; in release it prints to stdout so logs are visible. +export 'dart:developer' hide log; + +import 'dart:async' show Zone; +import 'dart:developer' as dev; +import 'package:flutter/foundation.dart'; + +void log( + String message, { + DateTime? time, + int? sequenceNumber, + int level = 0, + String name = '', + Zone? zone, + Object? error, + StackTrace? stackTrace, +}) { + if (kReleaseMode) { + final ts = (time ?? DateTime.now()).toIso8601String(); + final tag = name.isNotEmpty ? '[$name] ' : ''; + final seq = sequenceNumber != null ? ' #$sequenceNumber' : ''; + final lvl = level != 0 ? ' L$level' : ''; + final err = error != null ? ' | error: $error' : ''; + final st = stackTrace != null ? ' | stack: $stackTrace' : ''; + // Keep it a single line to avoid mixing with platform loggers. + // Using print to ensure output in release builds. + // Example: 2025-09-13T12:47:00.123Z [StompService] Connected ... L800 #42 + // Note: Some platforms may trim long lines; we still prefer a single print. + // ignore: avoid_print + print('$ts $tag$message$seq$lvl$err$st'); + } else { + dev.log( + message, + time: time, + sequenceNumber: sequenceNumber, + level: level, + name: name, + zone: zone, + error: error, + stackTrace: stackTrace, + ); + } +} diff --git a/app/lib/services/location_service.dart b/app/lib/services/location_service.dart new file mode 100644 index 0000000..b10ab18 --- /dev/null +++ b/app/lib/services/location_service.dart @@ -0,0 +1,184 @@ +import 'dart:async'; +import 'dart:convert'; +import 'package:geolocator/geolocator.dart'; +import 'package:votianlt_app/services/developer.dart' as developer; +import 'websocket_service.dart'; + +/// Service for tracking and sending GPS location. +/// Sends position every 30 seconds when online. +/// Does not buffer location data when offline. +class LocationService { + static final LocationService _instance = LocationService._internal(); + + factory LocationService() => _instance; + + LocationService._internal(); + + Timer? _locationTimer; + bool _isTracking = false; + Position? _lastPosition; + + static const String _topic = '/server/location'; + static const int _sendIntervalSeconds = 30; + + /// Check if location services are enabled and permission is granted + Future _checkPermissions() async { + // Check if location services are enabled + bool serviceEnabled = await Geolocator.isLocationServiceEnabled(); + if (!serviceEnabled) { + developer.log( + 'Location services are disabled', + name: 'LocationService', + ); + return false; + } + + // Check location permission + LocationPermission permission = await Geolocator.checkPermission(); + if (permission == LocationPermission.denied) { + permission = await Geolocator.requestPermission(); + if (permission == LocationPermission.denied) { + developer.log( + 'Location permission denied', + name: 'LocationService', + ); + return false; + } + } + + if (permission == LocationPermission.deniedForever) { + developer.log( + 'Location permission permanently denied', + name: 'LocationService', + ); + return false; + } + + return true; + } + + /// Start location tracking and periodic sending + Future startTracking() async { + if (_isTracking) { + developer.log( + 'Location tracking already active', + name: 'LocationService', + ); + return; + } + + final hasPermission = await _checkPermissions(); + if (!hasPermission) { + developer.log( + 'Cannot start location tracking - permission not granted', + name: 'LocationService', + ); + return; + } + + _isTracking = true; + developer.log( + 'Starting location tracking (sending every $_sendIntervalSeconds seconds)', + name: 'LocationService', + ); + + // Get initial position + await _updateAndSendPosition(); + + // Start periodic timer + _locationTimer = Timer.periodic( + const Duration(seconds: _sendIntervalSeconds), + (_) => _updateAndSendPosition(), + ); + } + + /// Stop location tracking + void stopTracking() { + if (!_isTracking) return; + + developer.log( + 'Stopping location tracking', + name: 'LocationService', + ); + + _locationTimer?.cancel(); + _locationTimer = null; + _isTracking = false; + } + + /// Get current position and send to server if online + Future _updateAndSendPosition() async { + try { + final position = await Geolocator.getCurrentPosition( + locationSettings: const LocationSettings( + accuracy: LocationAccuracy.best, + ), + ); + + _lastPosition = position; + + developer.log( + 'Position updated: ${position.latitude}, ${position.longitude}', + name: 'LocationService', + ); + + await _sendPosition(position); + } catch (e, st) { + developer.log( + 'Error getting position: $e', + name: 'LocationService', + ); + developer.log('Stack: $st', name: 'LocationService'); + } + } + + /// Send position to server if online + /// Does NOT buffer when offline - location data is time-sensitive + Future _sendPosition(Position position) async { + final wsService = WebSocketService(); + + // Only send if connected and authenticated + if (!wsService.isConnected || !wsService.isAuthenticated) { + developer.log( + 'Not sending position - not connected/authenticated', + name: 'LocationService', + ); + return; + } + + final payload = { + 'latitude': position.latitude, + 'longitude': position.longitude, + 'accuracy': position.accuracy, + 'altitude': position.altitude, + 'speed': position.speed, + 'heading': position.heading, + 'timestamp': position.timestamp.toIso8601String(), + }; + + try { + const topic = _topic; + final jsonPayload = jsonEncode(payload); + + // Use direct WebSocket send to avoid buffering + wsService.sendMessage(topic, jsonPayload); + + developer.log( + 'Position sent to server: ${position.latitude}, ${position.longitude}', + name: 'LocationService', + ); + } catch (e, st) { + developer.log( + 'Error sending position: $e', + name: 'LocationService', + ); + developer.log('Stack: $st', name: 'LocationService'); + } + } + + /// Get the last known position + Position? get lastPosition => _lastPosition; + + /// Check if tracking is active + bool get isTracking => _isTracking; +} diff --git a/app/lib/services/message_handler.dart b/app/lib/services/message_handler.dart new file mode 100644 index 0000000..daa3429 --- /dev/null +++ b/app/lib/services/message_handler.dart @@ -0,0 +1,114 @@ +import 'package:flutter/foundation.dart'; + +import '../models/message_envelope.dart'; + +/// Result of unwrapping a message envelope +class UnwrapResult { + /// The unwrapped payload + final dynamic payload; + + /// The message ID (null if not an envelope) + final String? messageId; + + /// Whether this message requires acknowledgment + final bool requiresAck; + + UnwrapResult({ + required this.payload, + this.messageId, + this.requiresAck = false, + }); +} + +/// Handles message envelope unwrapping and deduplication. +/// +/// This class is extracted from WebSocketService for testability. +/// It manages: +/// - Detecting and unwrapping MessageEnvelope structures +/// - Deduplicating messages by messageId +/// - Triggering ACK callbacks when required +class MessageHandler { + final Set _processedMessageIds = {}; + + /// Maximum number of message IDs to track for deduplication + final int maxProcessedIds; + + /// Callback invoked when an ACK should be sent + final void Function(String messageId)? onAckRequired; + + MessageHandler({ + this.maxProcessedIds = 100, + this.onAckRequired, + }); + + /// Check if data is a valid MessageEnvelope structure. + /// + /// A valid envelope must contain: + /// - messageId + /// - timestamp + /// - topic + /// - payload + bool isEnvelopeMessage(dynamic data) { + if (data is! Map) return false; + return data.containsKey('messageId') && + data.containsKey('timestamp') && + data.containsKey('topic') && + data.containsKey('payload'); + } + + /// Unwrap a message envelope and handle deduplication. + /// + /// Returns null if the message was already processed (duplicate). + /// For duplicates, still triggers onAckRequired if the original required ACK. + /// + /// Returns [UnwrapResult] with payload and ACK info for new messages. + /// If data is not an envelope, returns it as-is with requiresAck=false. + UnwrapResult? unwrapEnvelope(dynamic data) { + if (!isEnvelopeMessage(data)) { + // Not an envelope, return data as-is (no ACK needed) + return UnwrapResult( + payload: data, + messageId: null, + requiresAck: false, + ); + } + + final envelope = MessageEnvelope.fromJson(data as Map); + + // Check for duplicate + if (_processedMessageIds.contains(envelope.messageId)) { + // Still send ACK for duplicate messages + if (envelope.requiresAck && onAckRequired != null) { + onAckRequired!(envelope.messageId); + } + return null; + } + + // Track this message as processed + _processedMessageIds.add(envelope.messageId); + + // Limit set size to prevent memory growth (FIFO eviction) + if (_processedMessageIds.length > maxProcessedIds) { + _processedMessageIds.remove(_processedMessageIds.first); + } + + return UnwrapResult( + payload: envelope.payload, + messageId: envelope.messageId, + requiresAck: envelope.requiresAck, + ); + } + + /// Check if a message ID was already processed + bool wasProcessed(String messageId) => + _processedMessageIds.contains(messageId); + + /// Get the count of tracked message IDs + int get processedCount => _processedMessageIds.length; + + /// Clear all processed message IDs. + /// + /// Primarily for testing purposes. + @visibleForTesting + void clearProcessedIds() => _processedMessageIds.clear(); +} diff --git a/app/lib/services/notification_service.dart b/app/lib/services/notification_service.dart new file mode 100644 index 0000000..90d7462 --- /dev/null +++ b/app/lib/services/notification_service.dart @@ -0,0 +1,123 @@ +import 'package:flutter_local_notifications/flutter_local_notifications.dart'; +import 'package:votianlt_app/services/developer.dart' as developer; + +class NotificationService { + NotificationService._internal(); + static final NotificationService _instance = NotificationService._internal(); + factory NotificationService() => _instance; + + final FlutterLocalNotificationsPlugin _plugin = + FlutterLocalNotificationsPlugin(); + + bool _initialized = false; + + /// The conversation key of the chat currently being viewed by the user. + /// When set, incoming chat notifications for this conversation are suppressed. + String? activeConversationKey; + + static const String _chatChannelId = 'chat_messages'; + static const String _chatChannelName = 'Chat-Nachrichten'; + static const String _chatChannelDescription = + 'Benachrichtigungen bei neuen Chat-Nachrichten'; + + static const String _jobChannelId = 'new_jobs'; + static const String _jobChannelName = 'Neue Jobs'; + static const String _jobChannelDescription = + 'Benachrichtigungen bei neuen Job-Zuweisungen'; + + int _nextId = 0; + + Future initialize() async { + if (_initialized) return; + + const androidSettings = AndroidInitializationSettings( + '@mipmap/ic_launcher', + ); + + const iosSettings = DarwinInitializationSettings( + requestAlertPermission: true, + requestBadgePermission: true, + requestSoundPermission: true, + ); + + const initSettings = InitializationSettings( + android: androidSettings, + iOS: iosSettings, + ); + + await _plugin.initialize(initSettings); + + await _plugin + .resolvePlatformSpecificImplementation< + AndroidFlutterLocalNotificationsPlugin>() + ?.requestNotificationsPermission(); + + _initialized = true; + developer.log('NotificationService initialized', + name: 'NotificationService'); + } + + Future showChatNotification({ + required String title, + required String body, + required String conversationKey, + }) async { + if (!_initialized) return; + + if (activeConversationKey == conversationKey) return; + + const androidDetails = AndroidNotificationDetails( + _chatChannelId, + _chatChannelName, + channelDescription: _chatChannelDescription, + importance: Importance.high, + priority: Priority.high, + playSound: true, + enableVibration: true, + ); + + const iosDetails = DarwinNotificationDetails( + presentAlert: true, + presentBadge: true, + presentSound: true, + ); + + const details = NotificationDetails( + android: androidDetails, + iOS: iosDetails, + ); + + await _plugin.show(_nextId++, title, body, details, + payload: 'chat:$conversationKey'); + } + + Future showJobNotification({ + required String title, + required String body, + }) async { + if (!_initialized) return; + + const androidDetails = AndroidNotificationDetails( + _jobChannelId, + _jobChannelName, + channelDescription: _jobChannelDescription, + importance: Importance.high, + priority: Priority.high, + playSound: true, + enableVibration: true, + ); + + const iosDetails = DarwinNotificationDetails( + presentAlert: true, + presentBadge: true, + presentSound: true, + ); + + const details = NotificationDetails( + android: androidDetails, + iOS: iosDetails, + ); + + await _plugin.show(_nextId++, title, body, details, payload: 'job'); + } +} diff --git a/app/lib/services/translation_service.dart b/app/lib/services/translation_service.dart new file mode 100644 index 0000000..a54e68d --- /dev/null +++ b/app/lib/services/translation_service.dart @@ -0,0 +1,535 @@ +import 'dart:convert'; +import 'dart:io'; +import 'package:http/http.dart' as http; +import 'package:votianlt_app/config/translation_config.dart'; +import 'package:votianlt_app/services/dart_mq.dart'; +import 'package:votianlt_app/services/developer.dart' as developer; +import 'package:votianlt_app/app_state.dart'; + +/// Service für Übersetzungen – unterstützt LM Studio (lokal) und Moonshot AI (Cloud). +/// +/// Das aktive Backend wird in [TranslationConfig.activeBackend] konfiguriert. +/// Verwendet das Singleton-Pattern wie andere Services in der App. +/// Übersetzt in die vom Benutzer in der App eingestellte Sprache. +class TranslationService { + static final TranslationService _instance = TranslationService._internal(); + factory TranslationService() => _instance; + TranslationService._internal(); + + static const String _chatCompletionsEndpoint = '/chat/completions'; + + // HTTP Client + final http.Client _client = http.Client(); + + // Verfügbarkeitsstatus + bool _isAvailable = false; + + // Aktuell eingestellte Zielsprache (aus der App) + String get _targetLanguageCode => AppState().languageCode; + + /// Gibt an ob das Übersetzungsbackend verfügbar ist + bool get isAvailable => _isAvailable; + + /// Name des aktiven Backends (für Logs und DartMQ-Nachrichten) + String get _backendName => switch (TranslationConfig.activeBackend) { + TranslationBackend.lmStudio => 'lm-studio', + TranslationBackend.moonshot => 'moonshot-ai', + }; + + // Verfügbare Sprachen für Übersetzung (alle unterstützten App-Sprachen) + static final Map supportedLanguages = { + 'de': 'German', + 'en': 'English', + 'es': 'Spanish', + 'fr': 'French', + 'pl': 'Polish', + 'ru': 'Russian', + 'tr': 'Turkish', + 'et': 'Estonian', + 'lv': 'Latvian', + 'lt': 'Lithuanian', + }; + + /// Initialisiert den Translation Service + Future initialize() async { + try { + // Auf Sprachänderungen hören + _listenToLanguageChanges(); + + // Verfügbarkeit prüfen + _isAvailable = await _checkAvailability(); + + _notifyInitialization(); + + developer.log( + 'TranslationService initialisiert - Backend: $_backendName, Zielsprache: ${supportedLanguages[_targetLanguageCode]}', + name: 'TranslationService', + ); + } catch (e) { + developer.log('Fehler bei Initialisierung des TranslationService: $e', + name: 'TranslationService'); + _isAvailable = false; + } + } + + /// Prüft ob das konfigurierte Backend erreichbar ist + Future _checkAvailability() async { + switch (TranslationConfig.activeBackend) { + case TranslationBackend.lmStudio: + return _checkLmStudioAvailability(); + case TranslationBackend.moonshot: + return _checkMoonshotAvailability(); + } + } + + Future _checkLmStudioAvailability() async { + try { + final response = await _client + .get(Uri.parse('${TranslationConfig.lmStudioBaseUrl}/v1/models')) + .timeout(const Duration(seconds: 5)); + + if (response.statusCode == 200) { + final data = jsonDecode(response.body); + final models = data['data'] as List?; + developer.log( + 'LM Studio verbunden - Verfügbare Modelle: ${models?.length ?? 0}', + name: 'TranslationService', + ); + return true; + } + return false; + } catch (e) { + developer.log('LM Studio nicht erreichbar: $e', name: 'TranslationService'); + return false; + } + } + + Future _checkMoonshotAvailability() async { + try { + final response = await _client + .get( + Uri.parse('${TranslationConfig.moonshotBaseUrl}/models'), + headers: {'Authorization': 'Bearer ${TranslationConfig.moonshotApiKey}'}, + ) + .timeout(const Duration(seconds: 5)); + + if (response.statusCode == 200) { + developer.log('Moonshot AI verbunden - API erreichbar', name: 'TranslationService'); + return true; + } + return false; + } catch (e) { + developer.log('Moonshot AI nicht erreichbar: $e', name: 'TranslationService'); + return false; + } + } + + /// Sendet Initialisierungs-Notification über DartMQ + void _notifyInitialization() { + DartMQ().publish>('translation/service_initialized', { + 'language': _targetLanguageCode, + 'backend': _backendName, + 'isAvailable': isAvailable, + 'endpoint': _activeEndpoint, + }); + } + + /// Hört auf Sprachänderungen und aktualisiert den Service + void _listenToLanguageChanges() { + localeNotifier.addListener(() { + final newLanguage = AppState().languageCode; + developer.log( + 'Sprache in App geändert zu: ${supportedLanguages[newLanguage] ?? newLanguage}', + name: 'TranslationService', + ); + DartMQ().publish>('translation/language_changed', { + 'language': newLanguage, + 'displayName': supportedLanguages[newLanguage], + 'backend': _backendName, + }); + }); + } + + /// Basis-URL des aktiven Backends + String get _activeEndpoint => switch (TranslationConfig.activeBackend) { + TranslationBackend.lmStudio => TranslationConfig.lmStudioBaseUrl, + TranslationBackend.moonshot => TranslationConfig.moonshotBaseUrl, + }; + + /// Übersetzt einen Text in die vom Benutzer eingestellte Sprache + /// + /// [text] - Der zu übersetzende Text + /// [sourceLanguage] - Die Ausgangssprache (optional, wird automatisch erkannt wenn null) + /// + /// Gibt den übersetzten Text zurück oder den Originaltext bei Fehlern + Future translate( + String text, { + String? sourceLanguage, + }) async { + if (text.isEmpty) { + return text; + } + + // Bei rein numerischem Text oder sehr kurzem Text nicht übersetzen + if (_shouldSkipTranslation(text)) { + developer.log('Übersetzung übersprungen (kein Text): "$text"', + name: 'TranslationService'); + return text; + } + + // Zielsprache aus der App holen + final targetCode = _targetLanguageCode; + + // Wenn Quelle gleich Ziel, nicht übersetzen + final detectedSource = sourceLanguage ?? await _detectLanguage(text); + if (detectedSource == targetCode) { + developer.log('Übersetzung übersprungen (Quelle = Ziel): "$text"', + name: 'TranslationService'); + return text; + } + + try { + final translatedText = await _translate(text, detectedSource, targetCode); + + developer.log( + 'Übersetzung [${supportedLanguages[detectedSource]} -> ${supportedLanguages[targetCode]}]:\n' + ' Original: "$text"\n' + ' Übersetzt: "$translatedText"', + name: 'TranslationService', + ); + + return translatedText; + } catch (e) { + developer.log( + 'Fehler bei der Übersetzung: $e\n Original: "$text"', + name: 'TranslationService', + ); + return text; // Bei Fehler Original zurückgeben + } + } + + /// Übersetzt eine Liste von Texten in die vom Benutzer eingestellte Sprache + Future> translateList( + List texts, { + String? sourceLanguage, + }) async { + if (texts.isEmpty) return texts; + + final results = []; + final targetCode = _targetLanguageCode; + + developer.log( + 'Starte Batch-Übersetzung von ${texts.length} Texten nach ${supportedLanguages[targetCode]}', + name: 'TranslationService', + ); + + for (int i = 0; i < texts.length; i++) { + final text = texts[i]; + + if (text.isEmpty || _shouldSkipTranslation(text)) { + results.add(text); + continue; + } + + try { + final detectedSource = sourceLanguage ?? await _detectLanguage(text); + + if (detectedSource == targetCode) { + results.add(text); + continue; + } + + final translatedText = await _translate(text, detectedSource, targetCode); + + developer.log( + 'Batch [${i + 1}/${texts.length}] [${supportedLanguages[detectedSource]} -> ${supportedLanguages[targetCode]}]:\n' + ' Original: "$text"\n' + ' Übersetzt: "$translatedText"', + name: 'TranslationService', + ); + + results.add(translatedText); + } catch (e) { + developer.log( + 'Fehler bei Batch-Übersetzung [${i + 1}/${texts.length}]: $e\n Original: "$text"', + name: 'TranslationService', + ); + results.add(text); + } + } + + developer.log( + 'Batch-Übersetzung abgeschlossen: ${texts.length} Texte verarbeitet', + name: 'TranslationService', + ); + + return results; + } + + /// Dispatcht die Übersetzung an das konfigurierte Backend + Future _translate(String text, String sourceCode, String targetCode) { + switch (TranslationConfig.activeBackend) { + case TranslationBackend.lmStudio: + return _translateWithLmStudio(text, sourceCode, targetCode); + case TranslationBackend.moonshot: + return _translateWithMoonshot(text, sourceCode, targetCode); + } + } + + /// Übersetzung mit LM Studio REST API (lokales Modell, kein API-Key) + Future _translateWithLmStudio( + String text, + String sourceCode, + String targetCode, + ) async { + final targetName = supportedLanguages[targetCode] ?? targetCode; + final sourceName = supportedLanguages[sourceCode] ?? sourceCode; + + final systemPrompt = + 'You are a professional translator. Translate the user input from $sourceName to $targetName. ' + 'Return ONLY the translation, without any additional text, explanations, or quotes.'; + + final requestBody = { + 'model': TranslationConfig.lmStudioModel, + 'messages': [ + {'role': 'system', 'content': systemPrompt}, + {'role': 'user', 'content': text}, + ], + 'temperature': 0.1, + 'max_tokens': 2048, + 'stream': false, + }; + + developer.log( + 'Sende Übersetzungsanfrage an LM Studio: $sourceName -> $targetName (${text.length} Zeichen)', + name: 'TranslationService', + ); + + final response = await _client + .post( + Uri.parse('${TranslationConfig.lmStudioBaseUrl}$_chatCompletionsEndpoint'), + headers: {'Content-Type': 'application/json'}, + body: jsonEncode(requestBody), + ) + .timeout(const Duration(seconds: 30)); + + if (response.statusCode != 200) { + throw Exception('LM Studio API Fehler: ${response.statusCode} - ${response.body}'); + } + + return _extractTranslation(response.body, 'LM Studio'); + } + + /// Übersetzung mit Moonshot AI Cloud API (Kimi, API-Key erforderlich) + Future _translateWithMoonshot( + String text, + String sourceCode, + String targetCode, + ) async { + final targetName = supportedLanguages[targetCode] ?? targetCode; + final sourceName = supportedLanguages[sourceCode] ?? sourceCode; + + final systemPrompt = + 'You are a professional translator. Translate the user input from $sourceName to $targetName. ' + 'Return ONLY the translation, without any additional text, explanations, or quotes.'; + + final requestBody = { + 'model': TranslationConfig.moonshotModel, + 'messages': [ + {'role': 'system', 'content': systemPrompt}, + {'role': 'user', 'content': text}, + ], + 'temperature': 0.1, + 'max_tokens': 2048, + 'stream': false, + }; + + developer.log( + 'Sende Übersetzungsanfrage an Moonshot AI: $sourceName -> $targetName (${text.length} Zeichen)', + name: 'TranslationService', + ); + + final response = await _client + .post( + Uri.parse('${TranslationConfig.moonshotBaseUrl}$_chatCompletionsEndpoint'), + headers: { + 'Content-Type': 'application/json', + 'Authorization': 'Bearer ${TranslationConfig.moonshotApiKey}', + }, + body: jsonEncode(requestBody), + ) + .timeout(const Duration(seconds: 30)); + + if (response.statusCode != 200) { + throw Exception('Moonshot AI API Fehler: ${response.statusCode} - ${response.body}'); + } + + return _extractTranslation(response.body, 'Moonshot AI'); + } + + /// Extrahiert den Übersetzungstext aus der OpenAI-kompatiblen API-Antwort + String _extractTranslation(String responseBody, String backendLabel) { + final data = jsonDecode(responseBody); + final choices = data['choices'] as List?; + + if (choices == null || choices.isEmpty) { + throw Exception('Leere Antwort von $backendLabel'); + } + + final message = choices[0]['message'] as Map?; + String translated = message?['content']?.toString().trim() ?? ''; + + // Anführungszeichen entfernen falls vorhanden + if ((translated.startsWith('"') && translated.endsWith('"')) || + (translated.startsWith("'") && translated.endsWith("'"))) { + translated = translated.substring(1, translated.length - 1); + } + + return translated; + } + + /// Hilfsmethode: Erkennt die Sprache eines Textes + Future _detectLanguage(String text) async { + // Für kurze Texte: Default zu Englisch + if (text.length < 10) { + return 'en'; + } + + // Einfache Heuristik basierend auf häufigen Wörtern/Zeichen + final lowerText = text.toLowerCase(); + + // Deutsche Wörter prüfen + final germanWords = ['der', 'die', 'das', 'und', 'ist', 'zu', 'den', 'mit', 'von', 'für']; + if (germanWords.any((word) => + lowerText.contains(' $word ') || lowerText.startsWith('$word '))) { + return 'de'; + } + + // Französische Wörter prüfen + final frenchWords = ['le', 'la', 'les', 'et', 'est', 'pour', 'dans', 'sur', 'avec', 'une']; + if (frenchWords.any((word) => + lowerText.contains(' $word ') || lowerText.startsWith('$word '))) { + return 'fr'; + } + + // Spanische Wörter prüfen + final spanishWords = ['el', 'la', 'los', 'las', 'y', 'es', 'para', 'con', 'por', 'del']; + if (spanishWords.any((word) => + lowerText.contains(' $word ') || lowerText.startsWith('$word '))) { + return 'es'; + } + + // Polnische Wörter prüfen + final polishWords = ['jest', 'i', 'w', 'na', 'do', 'nie', 'się', 'tego', 'tej']; + if (polishWords.any((word) => + lowerText.contains(' $word ') || lowerText.startsWith('$word '))) { + return 'pl'; + } + + // Russische/Cyrillische Zeichen prüfen + if (RegExp(r'[а-яА-Я]').hasMatch(text)) { + return 'ru'; + } + + // Türkische Zeichen prüfen + if (RegExp(r'[çğıöşüÇĞİÖŞÜ]').hasMatch(text)) { + return 'tr'; + } + + // Estnische Zeichen prüfen + if (RegExp(r'[äöüõÄÖÜÕ]').hasMatch(text)) { + return 'et'; + } + + // Lettische Zeichen prüfen + if (RegExp(r'[āčēģīķļņšūžĀČĒĢĪĶĻŅŠŪŽ]').hasMatch(text)) { + return 'lv'; + } + + // Litauische Zeichen prüfen + if (RegExp(r'[ąčęėįšųūžĄČĘĖĮŠŲŪŽ]').hasMatch(text)) { + return 'lt'; + } + + // Arabische Zeichen prüfen + if (RegExp(r'[\u0600-\u06FF]').hasMatch(text)) { + return 'ar'; + } + + // Chinesische/Japanische/Koreanische Zeichen prüfen + if (RegExp(r'[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff]').hasMatch(text)) { + return 'zh'; + } + + // Default: Englisch + return 'en'; + } + + /// Prüft ob die Übersetzung übersprungen werden sollte + bool _shouldSkipTranslation(String text) { + // Numerische Werte nicht übersetzen + if (RegExp(r'^\d+$').hasMatch(text.trim())) { + return true; + } + + // Sehr kurze Codes nicht übersetzen + if (text.trim().length <= 2) { + return true; + } + + // E-Mail Adressen nicht übersetzen + if (text.contains('@') && text.contains('.')) { + return true; + } + + // URLs nicht übersetzen + if (text.startsWith('http://') || text.startsWith('https://')) { + return true; + } + + return false; + } + + /// Prüft ob ein Übersetzungsmodell verfügbar ist + Future isModelAvailable() async { + return _checkAvailability(); + } + + /// Gibt detaillierte Verfügbarkeitsinformationen zurück + Future> getAvailabilityInfo() async { + final isOnline = await _checkAvailability(); + return { + 'isAvailable': isOnline, + 'backend': _backendName, + 'targetLanguage': _targetLanguageCode, + 'endpoint': _activeEndpoint, + 'platform': Platform.operatingSystem, + }; + } + + /// Gibt die aktuell eingestellte Zielsprache zurück + String get targetLanguageCode => _targetLanguageCode; + + /// Gibt den Anzeigenamen der aktuellen Sprache zurück + String get targetLanguageDisplayName { + return supportedLanguages[_targetLanguageCode] ?? _targetLanguageCode; + } + + /// Gibt eine Liste aller verfügbaren Sprachen zurück + List> getAvailableLanguages() { + return supportedLanguages.entries.toList(); + } + + /// Gibt den Anzeigenamen einer Sprache zurück + String getLanguageDisplayName(String code) { + return supportedLanguages[code] ?? code; + } + + /// Schließt den Service und gibt Ressourcen frei + Future dispose() async { + _client.close(); + _isAvailable = false; + + developer.log('TranslationService disposed', name: 'TranslationService'); + } +} diff --git a/app/lib/services/websocket_service.dart b/app/lib/services/websocket_service.dart new file mode 100644 index 0000000..3cf6165 --- /dev/null +++ b/app/lib/services/websocket_service.dart @@ -0,0 +1,1064 @@ +import 'dart:async'; +import 'dart:convert'; +import 'package:flutter/foundation.dart'; +import 'package:votianlt_app/services/developer.dart' as developer; + +import 'package:web_socket_channel/web_socket_channel.dart'; +import 'package:web_socket_channel/status.dart' as ws_status; +import 'dart:math'; +import 'database_service.dart'; +import 'chat_service.dart'; +import 'notification_service.dart'; +import 'location_service.dart'; +import '../app_state.dart'; +import '../models/chat_message.dart'; +import '../models/job.dart'; +import 'dart_mq.dart'; + +class WebSocketService { + static final WebSocketService _instance = WebSocketService._internal(); + + factory WebSocketService() => _instance; + + WebSocketService._internal(); + + WebSocketChannel? _wsChannel; + StreamSubscription? _wsSubscription; + bool _isConnected = false; + bool _isConnecting = false; + + // Authentication state + bool _isAuthenticated = false; + String? _authToken; + + // Keep last known values for UI initialization (Behavior-like) + Map? _lastAuthResponse; + + // Completer to await a graceful WebSocket disconnect + Completer? _disconnectCompleter; + + // Unique persistent App ID for client identification + String? _appId; + + // Automatic reconnection timer + Timer? _reconnectTimer; + + // In-memory message buffer for messages sent while disconnected + final List<_BufferedMessage> _messageBuffer = []; + + // Database service + final DatabaseService _databaseService = DatabaseService(); + + // Validator for optional jobId field on chat messages + final RegExp _jobIdRegExp = RegExp(r'^[0-9a-fA-F]{24}$'); + + /// Ensure a unique persistent App ID exists. + /// Generates a UUID v4 if not already stored. + Future _ensureAppId() async { + if (_appId != null) return; + try { + final existing = await _databaseService.loadKeyValue('appId'); + if (existing != null && existing.isNotEmpty) { + _appId = existing; + developer.log( + 'Loaded existing appId: $_appId', + name: 'WebSocketService', + ); + return; + } + } catch (_) {} + // Generate a UUID v4 and persist + _appId = _generateUuid(); + developer.log('Generated new appId: $_appId', name: 'WebSocketService'); + try { + await _databaseService.saveKeyValue('appId', _appId!); + } catch (_) {} + } + + /// Get the unique persistent App ID (for external access if needed) + String? get appId => _appId; + + /// Generate a UUID v4 + String _generateUuid() { + final rand = Random(); + final buf = StringBuffer(); + + for (int i = 0; i < 36; i++) { + if (i == 8 || i == 13 || i == 18 || i == 23) { + buf.write('-'); + } else if (i == 14) { + buf.write('4'); + } else if (i == 19) { + buf.write(['8', '9', 'a', 'b'][rand.nextInt(4)]); + } else { + buf.write(rand.nextInt(16).toRadixString(16)); + } + } + return buf.toString(); + } + + // --------------------------------------------------------------------------- + // WebSocket Connection + // --------------------------------------------------------------------------- + + /// Build the WebSocket URL + /// Im Release-Modus: votianlt.de (Produktionsserver) + /// Im Debug-Modus: localhost (Android Emulator: 10.0.2.2) + String _buildWebSocketUrl() { + // Release-Modus: Verbindung zum Produktionsserver + if (kReleaseMode) { + return 'wss://votianlt.de/ws/messaging'; + } + + return 'ws://192.168.180.10:8082/ws/messaging'; + } + + /// Handle a connected WebSocket (common setup for connect and reconnect) + void _onWebSocketConnected() { + developer.log('WebSocket connected', name: 'WebSocketService'); + + // Update internal connection state + _isConnected = true; + _isConnecting = false; + // Note: Don't publish connectionStatus=true yet - wait for successful auth + + // Re-run the same setup as initial connection (auto-login) + _setupAfterConnect(); + } + + /// Setup auto-login after connection (initial or reconnect) + Future _setupAfterConnect() async { + try { + // Ensure we have an appId + await _ensureAppId(); + + // Auto-login with saved credentials if user was previously logged in + final credentials = await _databaseService.loadCredentials(); + if (credentials != null) { + developer.log( + 'Auto-login with saved credentials for ${credentials.email}', + name: 'WebSocketService', + ); + await login(credentials.email, credentials.password); + } + } catch (e, st) { + developer.log( + 'Error in _setupAfterConnect: $e', + name: 'WebSocketService', + ); + developer.log('Stack: $st', name: 'WebSocketService'); + } + } + + /// Handle WebSocket disconnection + void _handleWebSocketDisconnect() { + developer.log('WebSocket disconnected', name: 'WebSocketService'); + _isConnected = false; + _isAuthenticated = false; + Future.microtask(() { + DartMQ().publish(MQTopics.connectionStatus, false); + }); + + // Clean up WebSocket resources + _wsSubscription?.cancel(); + _wsSubscription = null; + _wsChannel = null; + + try { + _disconnectCompleter?.complete(); + } catch (_) {} + _disconnectCompleter = null; + + // Start automatic reconnection attempts + _startReconnectTimer(); + } + + void _startReconnectTimer() { + _stopReconnectTimer(); + _reconnectTimer = Timer.periodic(const Duration(seconds: 15), (timer) { + if (_isConnected || _isConnecting) { + _stopReconnectTimer(); + return; + } + developer.log( + 'Attempting automatic reconnection...', + name: 'WebSocketService', + ); + connect(); + }); + } + + void _stopReconnectTimer() { + _reconnectTimer?.cancel(); + _reconnectTimer = null; + } + + // --------------------------------------------------------------------------- + // WebSocket Send / Receive + // --------------------------------------------------------------------------- + + /// Send a message over WebSocket in wire format: {"topic": ..., "payload": ...} + bool _sendWebSocket(String topic, String jsonPayload) { + if (!_isConnected || _wsChannel == null) { + developer.log( + 'Cannot send, not connected. Topic=$topic', + name: 'WebSocketService', + ); + return false; + } + try { + final parsed = jsonDecode(jsonPayload); + final wireMessage = jsonEncode({'topic': topic, 'payload': parsed}); + developer.log('>> SEND: $wireMessage', name: 'WebSocketService'); + _wsChannel!.sink.add(wireMessage); + return true; + } catch (e, st) { + developer.log( + 'Error sending WebSocket message: $e', + name: 'WebSocketService', + ); + developer.log('Stack: $st', name: 'WebSocketService'); + return false; + } + } + + /// Handle incoming WebSocket message + void _onWebSocketMessage(dynamic rawData) async { + if (rawData is! String) { + developer.log( + 'Received non-text WebSocket message, ignoring', + name: 'WebSocketService', + ); + return; + } + + try { + final wireMessage = jsonDecode(rawData) as Map; + final topic = wireMessage['topic'] as String?; + final payload = wireMessage['payload']; + + if (topic == null) { + developer.log( + 'WebSocket message missing topic field', + name: 'WebSocketService', + ); + return; + } + + developer.log('<< RECEIVED: $rawData', name: 'WebSocketService'); + + await _handleMessage(topic, payload); + } catch (e, st) { + developer.log( + 'Error parsing WebSocket message: $e', + name: 'WebSocketService', + ); + developer.log('Stack: $st', name: 'WebSocketService'); + } + } + + // --------------------------------------------------------------------------- + // Message Handlers + // --------------------------------------------------------------------------- + + Future _handleMessage(String topic, dynamic data) async { + developer.log( + '_handleMessage called with topic: $topic', + name: 'WebSocketService', + ); + if (topic.startsWith('/client/')) { + await _handleClientMessage(topic, data); + } else { + developer.log( + 'Topic does not start with /client/, ignoring', + name: 'WebSocketService', + ); + } + } + + Future _handleClientMessage(String topic, dynamic data) async { + developer.log( + 'Handling client message: topic=$topic, dataType=${data.runtimeType}', + name: 'WebSocketService', + ); + + if (topic.endsWith('/auth')) { + await _handleAuthMessage(topic, data); + } else if (topic.endsWith('/jobs')) { + _handleJobsMessage(data); + } else if (topic.endsWith('/job_deleted')) { + _handleJobDeletedMessage(data); + } else if (topic.endsWith('/job_created')) { + _handleJobCreatedMessage(data); + } else if (topic.endsWith('/message')) { + await _handleChatMessage(topic, data); + } else { + _handleOtherClientMessage(topic, data); + } + } + + Future _handleAuthMessage( + String topic, + Map data, + ) async { + _lastAuthResponse = data; + DartMQ().publish>(MQTopics.authResponse, data); + + if (data['success'] == true) { + await _handleSuccessfulAuth(); + } else { + _handleFailedAuth(); + } + } + + Future _handleSuccessfulAuth() async { + _isAuthenticated = true; + + developer.log('Auth successful', name: 'WebSocketService'); + + // Publish connection status to UI - fully connected and authenticated (async to avoid build-phase issues) + Future.microtask(() { + DartMQ().publish(MQTopics.connectionStatus, true); + }); + + // Flush any messages that were buffered while disconnected. + // This also clears local jobs and notifies the server. + await _flushMessageBuffer(); + + // Start location tracking only if enabled in auth response + final locationTrackingEnabled = + _lastAuthResponse?['locationTrackingEnabled'] == true; + developer.log( + 'Location tracking enabled: $locationTrackingEnabled', + name: 'WebSocketService', + ); + if (locationTrackingEnabled) { + LocationService().startTracking(); + developer.log('Location tracking started', name: 'WebSocketService'); + } else { + developer.log( + 'Location tracking disabled by server', + name: 'WebSocketService', + ); + } + } + + void _handleFailedAuth() { + _isAuthenticated = false; + _authToken = null; + } + + /// Übersetzung deaktiviert - Texte werden im Original angezeigt + Future> _translateJobData( + Map jobData, + ) async { + // Keine Übersetzung - Daten werden so wie vom Server empfangen verwendet + return jobData; + } + + void _handleJobsMessage(List data) async { + final jobs = data; + + // Log empfangene Jobs JSON + developer.log( + '<< JOBS RECEIVED: ${jsonEncode(data)}', + name: 'WebSocketService', + ); + + if (jobs.isNotEmpty) { + final currentJobCount = AppState().assignedJobs.length; + if (currentJobCount > 0 && jobs.length > currentJobCount) { + final newCount = jobs.length - currentJobCount; + NotificationService().showJobNotification( + title: 'Neue Jobs', + body: + newCount == 1 + ? 'Sie haben einen neuen Job erhalten.' + : 'Sie haben $newCount neue Jobs erhalten.', + ); + } + + // Parse and persist jobs to database immediately + try { + final List parsedJobs = []; + for (final jobData in jobs) { + try { + Map actualJobData; + if (jobData is Map && jobData.containsKey('job')) { + actualJobData = Map.from( + jobData['job'] as Map, + ); + if (jobData.containsKey('tasks') && jobData['tasks'] is List) { + actualJobData['tasks'] = jobData['tasks']; + } + if (jobData.containsKey('cargoItems') && + jobData['cargoItems'] is List) { + actualJobData['cargoItems'] = jobData['cargoItems']; + } + } else { + actualJobData = jobData as Map; + } + + // Übersetze Textfelder vor dem Speichern + actualJobData = await _translateJobData(actualJobData); + + final job = Job.fromJson(actualJobData); + parsedJobs.add(job); + } catch (e, stackTrace) { + developer.log('Error parsing job: $e', name: 'WebSocketService'); + developer.log('Stack trace: $stackTrace', name: 'WebSocketService'); + } + } + + // Save all parsed jobs to database + if (parsedJobs.isNotEmpty) { + await _databaseService.saveJobs(parsedJobs); + developer.log( + 'Saved ${parsedJobs.length} jobs to database', + name: 'WebSocketService', + ); + } + } catch (e, stackTrace) { + developer.log( + 'Error saving jobs to database: $e', + name: 'WebSocketService', + ); + developer.log('Stack trace: $stackTrace', name: 'WebSocketService'); + } + + DartMQ().publish>(MQTopics.jobsResponse, jobs); + } else { + // Clear all jobs from database when empty list received + await _databaseService.clearAllJobsAndRelatedData(); + developer.log( + 'Cleared all jobs from database (empty list received)', + name: 'WebSocketService', + ); + + // Still publish empty list to complete any waiting operations + DartMQ().publish>(MQTopics.jobsResponse, []); + } + } + + void _handleJobDeletedMessage(Map data) async { + final jobId = data['jobId']?.toString(); + final jobNumber = data['jobNumber']?.toString(); + + if (jobId == null || jobId.isEmpty) { + developer.log( + 'Received job_deleted message without jobId', + name: 'WebSocketService', + ); + return; + } + + developer.log( + '<< JOB DELETED: jobId=$jobId, jobNumber=$jobNumber', + name: 'WebSocketService', + ); + + // Delete job from database immediately + try { + await _databaseService.deleteJob(jobId); + developer.log( + 'Deleted job $jobId from database', + name: 'WebSocketService', + ); + } catch (e, stackTrace) { + developer.log( + 'Error deleting job $jobId from database: $e', + name: 'WebSocketService', + ); + developer.log('Stack trace: $stackTrace', name: 'WebSocketService'); + } + + // Publish event via DartMQ for UI to handle + DartMQ().publish>(MQTopics.jobDeleted, data); + } + + void _handleJobCreatedMessage(Map data) async { + final jobId = data['job']?['id']?.toString() ?? data['id']?.toString(); + final jobNumber = + data['job']?['jobNumber']?.toString() ?? data['jobNumber']?.toString(); + + // Log empfangenes Job JSON + developer.log( + '<< JOB CREATED JSON: ${jsonEncode(data)}', + name: 'WebSocketService', + ); + developer.log( + '<< JOB CREATED: jobId=$jobId, jobNumber=$jobNumber', + name: 'WebSocketService', + ); + + // Parse and persist job to database immediately + try { + Map actualJobData; + if (data.containsKey('job')) { + actualJobData = Map.from( + data['job'] as Map, + ); + if (data.containsKey('tasks') && data['tasks'] is List) { + actualJobData['tasks'] = data['tasks']; + } + if (data.containsKey('cargoItems') && data['cargoItems'] is List) { + actualJobData['cargoItems'] = data['cargoItems']; + } + } else { + actualJobData = data; + } + + // Übersetze Textfelder vor dem Speichern + actualJobData = await _translateJobData(actualJobData); + + final job = Job.fromJson(actualJobData); + await _databaseService.saveOrUpdateJob(job); + developer.log( + 'Saved new job ${job.id} to database', + name: 'WebSocketService', + ); + } catch (e, stackTrace) { + developer.log( + 'Error saving new job to database: $e', + name: 'WebSocketService', + ); + developer.log('Stack trace: $stackTrace', name: 'WebSocketService'); + } + + // Show notification with sound for new job + NotificationService().showJobNotification( + title: 'Neuer Job', + body: + jobNumber != null && jobNumber.isNotEmpty + ? 'Job $jobNumber wurde Ihnen zugewiesen.' + : 'Sie haben einen neuen Job erhalten.', + ); + + // Publish event via DartMQ for UI to handle + DartMQ().publish>(MQTopics.jobCreated, data); + } + + Future _handleChatMessage( + String topic, + Map data, + ) async { + const requiredFields = [ + 'messageId', + 'content', + 'origin', + 'messageType', + 'createdAt', + ]; + final missing = []; + for (final field in requiredFields) { + final value = data[field]; + if (value == null || (value is String && value.trim().isEmpty)) { + missing.add(field); + } + } + + if (missing.isNotEmpty) { + return; + } + + try { + final message = ChatMessage.fromJson(data); + await ChatService().saveIncomingMessage(message); + + final conversationKey = ChatService().conversationKeyForMessage(message); + + String notificationTitle; + if (message.messageType == ChatMessageType.jobRelated) { + final jobNumber = message.jobNumber ?? ''; + notificationTitle = + jobNumber.isNotEmpty + ? 'Nachricht zu Job $jobNumber' + : 'Neue Job-Nachricht'; + } else { + notificationTitle = 'Neue Nachricht'; + } + + String notificationBody; + if (message.contentType == ChatContentType.image) { + notificationBody = '[Bild]'; + } else { + final content = message.content; + notificationBody = + content.length > 100 ? '${content.substring(0, 100)}...' : content; + } + + NotificationService().showChatNotification( + title: notificationTitle, + body: notificationBody, + conversationKey: conversationKey, + ); + } catch (e, st) { + developer.log('Error parsing chat message: $e', name: 'WebSocketService'); + developer.log('Stack: $st', name: 'WebSocketService'); + } + } + + void _handleOtherClientMessage(String topic, Map data) { + final type = data['type']; + if (topic.contains('/tasks/') || type == 'task') { + DartMQ().publish>(MQTopics.taskEvents, data); + } else { + developer.log( + 'Unhandled client message type: $type on topic: $topic', + name: 'WebSocketService', + ); + } + } + + // --------------------------------------------------------------------------- + // Public API + // --------------------------------------------------------------------------- + + bool get isConnected => _isConnected; + + bool get isConnecting => _isConnecting; + + bool get isAuthenticated => _isAuthenticated; + + String? get authToken => _authToken; + + /// Connect to the WebSocket server + Future connect() async { + // Prevent overlapping connection attempts + if (_isConnected) { + developer.log( + 'Already connected to WebSocket server', + name: 'WebSocketService', + ); + return; + } + if (_isConnecting) { + developer.log( + 'Connection attempt already in progress - skipping', + name: 'WebSocketService', + ); + return; + } + + final wsUrl = _buildWebSocketUrl(); + + developer.log( + 'Connecting to WebSocket server: $wsUrl', + name: 'WebSocketService', + ); + + _isConnecting = true; + + // Publish "not connected" status to UI while connecting (async to avoid build-phase issues) + Future.microtask(() { + DartMQ().publish(MQTopics.connectionStatus, false); + }); + + try { + // Ensure stable appId + await _ensureAppId(); + + final channel = WebSocketChannel.connect(Uri.parse(wsUrl)); + + // Wait for the connection to be established + await channel.ready; + + _wsChannel = channel; + + // Listen for incoming messages + _wsSubscription = channel.stream.listen( + _onWebSocketMessage, + onError: (error) { + developer.log('WebSocket error: $error', name: 'WebSocketService'); + _handleWebSocketDisconnect(); + }, + onDone: () { + developer.log( + 'WebSocket connection closed', + name: 'WebSocketService', + ); + _handleWebSocketDisconnect(); + }, + cancelOnError: false, + ); + + // Stop any reconnection attempts since we're now connected + _stopReconnectTimer(); + + developer.log( + 'Connected to WebSocket server at $wsUrl', + name: 'WebSocketService', + ); + + // Run common post-connect setup (sets _isConnected, starts timers, auto-login) + _onWebSocketConnected(); + } catch (e) { + _isConnecting = false; + developer.log( + 'Error connecting to WebSocket server: $e', + name: 'WebSocketService', + ); + + // Start reconnection attempts on connection failure + _startReconnectTimer(); + } + } + + /// Send a message to the server. Buffers if not connected/authenticated + /// or if sending fails due to an exception. + void sendMessage(String topic, String message) { + if (_isConnected && _isAuthenticated && _wsChannel != null) { + final success = _sendWebSocket(topic, message); + if (!success) { + // Message could not be sent due to exception - buffer for retry + developer.log( + '>> BUFFERED (send failed): topic=$topic', + name: 'WebSocketService', + ); + _messageBuffer.add(_BufferedMessage(topic, message)); + } + } else { + developer.log( + '>> BUFFERED (not ready): topic=$topic', + name: 'WebSocketService', + ); + _messageBuffer.add(_BufferedMessage(topic, message)); + } + } + + /// Flush all buffered messages after successful authentication. + /// Messages that fail to send are re-buffered for the next flush cycle. + /// Clears all local jobs and related data, then notifies the server. + Future _flushMessageBuffer() async { + final initialBufferSize = _messageBuffer.length; + + if (initialBufferSize > 0) { + developer.log( + 'Flushing ${_messageBuffer.length} buffered messages', + name: 'WebSocketService', + ); + final messages = List<_BufferedMessage>.from(_messageBuffer); + _messageBuffer.clear(); + final failedMessages = <_BufferedMessage>[]; + for (final msg in messages) { + final success = _sendWebSocket(msg.topic, msg.jsonPayload); + if (!success) { + // Re-buffer failed messages for retry on next connection + failedMessages.add(msg); + } + } + // Add failed messages back to buffer for retry + if (failedMessages.isNotEmpty) { + developer.log( + '${failedMessages.length} messages failed to send, re-buffering for retry', + name: 'WebSocketService', + ); + _messageBuffer.addAll(failedMessages); + } + } + + // Clear all local jobs and related data before notifying server. + // The server will send current jobs automatically. + developer.log( + 'Clearing local jobs and related data before buffer_flushed notification', + name: 'WebSocketService', + ); + await _databaseService.clearAllJobsAndRelatedData(); + + // Notify server that buffer flush is complete + final sentCount = initialBufferSize - _messageBuffer.length; + final bufferFlushedPayload = jsonEncode({ + 'timestamp': DateTime.now().toIso8601String(), + 'messageCount': sentCount, + }); + _sendWebSocket('/server/buffer_flushed', bufferFlushedPayload); + } + + /// Publish a chat message according to the backend contract. + /// Returns the locally constructed message so callers can persist it locally. + /// Messages are buffered if offline and sent automatically when reconnected. + Future sendChatMessage({ + required String sender, + required String receiver, + required String content, + ChatContentType contentType = ChatContentType.text, + String? jobId, + String? jobNumber, + }) async { + final trimmedSender = sender.trim(); + final trimmedReceiver = receiver.trim(); + final trimmedContent = content.trim(); + final normalizedJobId = jobId?.trim(); + final normalizedJobNumber = jobNumber?.trim(); + + if (trimmedSender.isEmpty || + trimmedReceiver.isEmpty || + trimmedContent.isEmpty) { + developer.log( + 'Cannot send chat message - missing required fields', + name: 'WebSocketService', + ); + return null; + } + + if (normalizedJobId != null && + normalizedJobId.isNotEmpty && + !_jobIdRegExp.hasMatch(normalizedJobId)) { + developer.log( + 'Cannot send chat message - jobId has invalid format: $normalizedJobId', + name: 'WebSocketService', + ); + return null; + } + + final payload = { + 'sender': trimmedSender, + 'receiver': trimmedReceiver, + 'content': trimmedContent, + }; + + if (normalizedJobId != null && normalizedJobId.isNotEmpty) { + payload['jobId'] = normalizedJobId; + } + if (normalizedJobNumber != null && normalizedJobNumber.isNotEmpty) { + payload['jobNumber'] = normalizedJobNumber; + } + payload['contentType'] = chatContentTypeToString(contentType); + + const topic = '/server/message'; + + try { + final jsonPayload = jsonEncode(payload); + // sendMessage buffers automatically if not connected/authenticated + sendMessage(topic, jsonPayload); + + final now = DateTime.now(); + final message = ChatMessage( + id: 'local-${now.microsecondsSinceEpoch}', + content: trimmedContent, + createdAt: now, + direction: ChatDirection.outgoing, + messageType: + normalizedJobId != null && normalizedJobId.isNotEmpty + ? ChatMessageType.jobRelated + : ChatMessageType.general, + contentType: contentType, + jobId: normalizedJobId?.isEmpty ?? true ? null : normalizedJobId, + jobNumber: + normalizedJobNumber?.isEmpty ?? true ? null : normalizedJobNumber, + read: false, + pendingSync: true, + ); + + return message; + } catch (e, st) { + developer.log( + 'Error encoding chat message payload: $e', + name: 'WebSocketService', + ); + developer.log('Stack: $st', name: 'WebSocketService'); + return null; + } + } + + /// Subscribe to a topic (no-op for WebSocket - all messages arrive on one connection) + void subscribe(String topic, [Function? callback]) { + // WebSocket does not use topic subscriptions. + // All messages are routed by the server to this connection after authentication. + } + + /// Send login request + Future login(String email, String password) async { + final loginStartTime = DateTime.now(); + final sessionId = loginStartTime.millisecondsSinceEpoch.toString(); + + developer.log('=== LOGIN METHOD CALLED ===', name: 'WebSocketService'); + developer.log('Email: $email', name: 'WebSocketService'); + developer.log('isConnected: $_isConnected', name: 'WebSocketService'); + developer.log( + 'wsChannel: ${_wsChannel != null ? "exists" : "null"}', + name: 'WebSocketService', + ); + + await _ensureAppId(); + developer.log('AppId: $_appId', name: 'WebSocketService'); + + if (!_isConnected || _wsChannel == null) { + developer.log( + 'LOGIN ABORTED: Not connected to server', + name: 'WebSocketService', + ); + _lastAuthResponse = { + 'success': false, + 'message': 'Nicht mit Server verbunden', + 'sessionId': sessionId, + 'timestamp': loginStartTime.toIso8601String(), + }; + DartMQ().publish>( + MQTopics.authResponse, + _lastAuthResponse!, + ); + return; + } + + final loginData = {'email': email, 'password': password}; + + try { + const topic = '/server/login'; + final jsonPayload = jsonEncode(loginData); + + developer.log( + 'Sending login message to $topic', + name: 'WebSocketService', + ); + + // Send login directly (not via sendMessage which buffers until authenticated) + _sendWebSocket(topic, jsonPayload); + + developer.log( + 'Login message sent successfully', + name: 'WebSocketService', + ); + } catch (e, st) { + developer.log('Error sending login: $e', name: 'WebSocketService'); + developer.log('Stack: $st', name: 'WebSocketService'); + + _lastAuthResponse = { + 'success': false, + 'message': 'Fehler beim Senden der Anmeldedaten', + 'error': e.toString(), + 'sessionId': sessionId, + 'timestamp': DateTime.now().toIso8601String(), + }; + DartMQ().publish>( + MQTopics.authResponse, + _lastAuthResponse!, + ); + } + } + + /// Retry login with saved credentials (called from UI after auth timeout) + Future retryLoginWithSavedCredentials() async { + if (!_isConnected || _wsChannel == null) { + developer.log( + 'Cannot retry login: not connected to server', + name: 'WebSocketService', + ); + return; + } + + final credentials = await _databaseService.loadCredentials(); + if (credentials != null) { + developer.log( + 'Retrying login with saved credentials for ${credentials.email}', + name: 'WebSocketService', + ); + await login(credentials.email, credentials.password); + } else { + developer.log( + 'Cannot retry login: no saved credentials found', + name: 'WebSocketService', + ); + } + } + + /// Logout user + Future logout() async { + _isAuthenticated = false; + _authToken = null; + // Delete saved credentials to prevent auto-login + await _databaseService.deleteCredentials(); + // Stop location tracking + LocationService().stopTracking(); + } + + /// Disconnect from WebSocket server + Future disconnect() async { + // Stop location tracking + LocationService().stopTracking(); + + if (_wsChannel != null) { + final completer = Completer(); + _disconnectCompleter = completer; + + try { + await _wsChannel!.sink.close(ws_status.normalClosure); + } catch (e, st) { + developer.log('Error during disconnect: $e', name: 'WebSocketService'); + developer.log('Stack: $st', name: 'WebSocketService'); + if (!completer.isCompleted) { + completer.complete(); + } + } + + try { + await completer.future.timeout(const Duration(seconds: 3)); + } catch (_) {} + + _wsSubscription?.cancel(); + _wsSubscription = null; + _wsChannel = null; + _disconnectCompleter = null; + } + _isConnected = false; + _isAuthenticated = false; + _authToken = null; + _stopReconnectTimer(); + _lastAuthResponse = null; + _messageBuffer.clear(); + Future.microtask(() { + DartMQ().publish(MQTopics.connectionStatus, false); + }); + } + + /// Reset service state without disposing (useful for logout) + Future reset() async { + await disconnect(); + } + + /// Send task completion event to server. + /// Messages are buffered if offline and sent automatically when reconnected. + Future sendTaskCompleted({ + required String taskId, + String? taskType, + Map? extraData, + }) async { + final String normalizedType = (taskType ?? 'UNKNOWN').toUpperCase(); + const String destination = '/server/task_completed'; + + final payload = { + 'taskId': taskId, + 'taskType': normalizedType, + }; + if (extraData != null && extraData.isNotEmpty) { + payload['extraData'] = extraData; + } + + try { + final jsonPayload = jsonEncode(payload); + // sendMessage buffers automatically if not connected/authenticated + sendMessage(destination, jsonPayload); + } catch (e, st) { + developer.log( + 'Error sending task completion: $e', + name: 'WebSocketService', + ); + developer.log('Stack: $st', name: 'WebSocketService'); + } + } + + /// Dispose resources + void dispose() { + _stopReconnectTimer(); + disconnect(); + } +} + +class _BufferedMessage { + final String topic; + final String jsonPayload; + _BufferedMessage(this.topic, this.jsonPayload); +} + +// Backward compatibility typedef +typedef StompService = WebSocketService; diff --git a/app/lib/settings_view.dart b/app/lib/settings_view.dart new file mode 100644 index 0000000..d81147e --- /dev/null +++ b/app/lib/settings_view.dart @@ -0,0 +1,225 @@ +import 'package:flutter/material.dart'; +import 'l10n/app_localizations.dart'; +import 'app_state.dart'; + +/// Supported languages with their display names and flag emojis +class LanguageOption { + final String code; + final String name; + final String flagEmoji; + + const LanguageOption({ + required this.code, + required this.name, + required this.flagEmoji, + }); +} + +class SettingsView extends StatefulWidget { + const SettingsView({super.key}); + + @override + State createState() => _SettingsViewState(); +} + +class _SettingsViewState extends State { + late String _selectedLanguageCode; + final AppState _appState = AppState(); + + @override + void initState() { + super.initState(); + _selectedLanguageCode = _appState.languageCode; + } + + void _onLanguageSelected(String languageCode) async { + setState(() { + _selectedLanguageCode = languageCode; + }); + + // Save language preference + await _appState.setLanguage(languageCode); + + // Show confirmation snackbar + _showLanguageChangedSnackBar(languageCode); + } + + void _showLanguageChangedSnackBar(String languageCode) { + final l10n = AppLocalizations.of(context); + + // Get the language name from the corresponding localization + String languageName; + String flagEmoji; + switch (languageCode) { + case 'de': + languageName = 'Deutsch'; + flagEmoji = '🇩🇪'; + break; + case 'en': + languageName = 'English'; + flagEmoji = '🇬🇧'; + break; + case 'es': + languageName = 'Español'; + flagEmoji = '🇪🇸'; + break; + case 'fr': + languageName = 'Français'; + flagEmoji = '🇫🇷'; + break; + case 'pl': + languageName = 'Polski'; + flagEmoji = '🇵🇱'; + break; + case 'ru': + languageName = 'Русский'; + flagEmoji = '🇷🇺'; + break; + case 'tr': + languageName = 'Türkçe'; + flagEmoji = '🇹🇷'; + break; + case 'et': + languageName = 'Eesti'; + flagEmoji = '🇪🇪'; + break; + case 'lv': + languageName = 'Latviešu'; + flagEmoji = '🇱🇻'; + break; + case 'lt': + languageName = 'Lietuvių'; + flagEmoji = '🇱🇹'; + break; + default: + languageName = languageCode; + flagEmoji = '🌐'; + } + + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text( + '${l10n.languageChanged}: $flagEmoji $languageName', + ), + duration: const Duration(seconds: 2), + backgroundColor: Colors.green, + ), + ); + } + + /// Get all available language options with their localized names + List _getLanguageOptions() { + return [ + const LanguageOption(code: 'de', name: 'Deutsch', flagEmoji: '🇩🇪'), + const LanguageOption(code: 'en', name: 'English', flagEmoji: '🇬🇧'), + const LanguageOption(code: 'es', name: 'Español', flagEmoji: '🇪🇸'), + const LanguageOption(code: 'fr', name: 'Français', flagEmoji: '🇫🇷'), + const LanguageOption(code: 'pl', name: 'Polski', flagEmoji: '🇵🇱'), + const LanguageOption(code: 'ru', name: 'Русский', flagEmoji: '🇷🇺'), + const LanguageOption(code: 'tr', name: 'Türkçe', flagEmoji: '🇹🇷'), + const LanguageOption(code: 'et', name: 'Eesti', flagEmoji: '🇪🇪'), + const LanguageOption(code: 'lv', name: 'Latviešu', flagEmoji: '🇱🇻'), + const LanguageOption(code: 'lt', name: 'Lietuvių', flagEmoji: '🇱🇹'), + ]; + } + + @override + Widget build(BuildContext context) { + final l10n = AppLocalizations.of(context); + final languageOptions = _getLanguageOptions(); + + return Scaffold( + appBar: AppBar( + title: Text(l10n.settings), + backgroundColor: Colors.deepPurple[100], + ), + body: ListView( + children: [ + // Language Selection Section + Padding( + padding: const EdgeInsets.fromLTRB(16, 24, 16, 8), + child: Text( + l10n.language.toUpperCase(), + style: const TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Colors.grey, + letterSpacing: 1.2, + ), + ), + ), + const Divider(height: 1), + + // Language List + ...languageOptions.map((language) { + final isSelected = language.code == _selectedLanguageCode; + return Column( + children: [ + ListTile( + leading: Container( + width: 40, + height: 40, + decoration: BoxDecoration( + color: Colors.grey[100], + borderRadius: BorderRadius.circular(20), + ), + child: Center( + child: Text( + language.flagEmoji, + style: const TextStyle(fontSize: 24), + ), + ), + ), + title: Text( + language.name, + style: TextStyle( + fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal, + color: isSelected ? Colors.deepPurple : Colors.black87, + ), + ), + trailing: isSelected + ? const Icon( + Icons.check_circle, + color: Colors.deepPurple, + ) + : const Icon( + Icons.circle_outlined, + color: Colors.grey, + ), + onTap: () => _onLanguageSelected(language.code), + selected: isSelected, + selectedTileColor: Colors.deepPurple.withValues(alpha: 0.05), + ), + const Divider(height: 1, indent: 72), + ], + ); + }), + + // App Info Section + Padding( + padding: const EdgeInsets.fromLTRB(16, 32, 16, 8), + child: Text( + l10n.appInfo, + style: const TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Colors.grey, + letterSpacing: 1.2, + ), + ), + ), + const Divider(height: 1), + ListTile( + leading: Icon( + Icons.info_outline, + color: Colors.grey[600], + ), + title: Text(l10n.version), + subtitle: const Text('0.9.2'), + ), + const Divider(height: 1, indent: 72), + ], + ), + ); + } +} diff --git a/app/lib/task_view.dart b/app/lib/task_view.dart new file mode 100644 index 0000000..414f225 --- /dev/null +++ b/app/lib/task_view.dart @@ -0,0 +1,796 @@ +import 'dart:async'; +import 'dart:convert'; +import 'package:votianlt_app/services/developer.dart' as developer; +import 'package:image/image.dart' as img; + +import 'package:flutter/material.dart'; +import 'package:flutter/foundation.dart'; +import 'l10n/app_localizations.dart'; +import 'models/job.dart'; +import 'models/task.dart'; +import 'models/tasks/confirmation_task.dart'; +import 'models/tasks/photo_task.dart'; +import 'models/tasks/todolist_task.dart'; +import 'models/tasks/signature_task.dart'; +import 'models/tasks/barcode_task.dart'; +import 'models/tasks/comment_task.dart'; +import 'services/database_service.dart'; +import 'widgets/offline_banner.dart'; +import 'services/websocket_service.dart'; +import 'Tasks/photo_capture_screen.dart'; +import 'Tasks/barcode_capture_screen.dart'; +import 'Tasks/signature_capture_screen.dart'; + +class TaskView extends StatefulWidget { + final Job job; + final int? stationOrder; + final String? stationTitle; + + const TaskView({ + super.key, + required this.job, + this.stationOrder, + this.stationTitle, + }); + + @override + State createState() => _TaskViewState(); +} + +class _TaskViewState extends State { + final Set _completedTasks = {}; + final Set _skippedTasks = {}; + final DatabaseService _databaseService = DatabaseService(); + // Store SVG representations of signatures per task for later use + final Map _signatureSvgByTask = {}; + + @override + void initState() { + super.initState(); + _loadTaskStatuses(); + } + + List get _visibleTasks { + final stationOrder = widget.stationOrder; + if (stationOrder == null) { + return widget.job.tasks; + } + return widget.job.tasks + .where((task) => task.stationOrder == stationOrder) + .toList(); + } + + /// Load task completion statuses from database and merge with JSON task states + Future _loadTaskStatuses() async { + final statuses = await _databaseService.loadAllTaskStatuses(); + setState(() { + _completedTasks.clear(); + // 1) Add all completed from DB + for (final entry in statuses.entries) { + if (entry.value) { + _completedTasks.add(entry.key); + } + } + // 2) Merge: also mark tasks completed if the job JSON already had them completed + for (final t in widget.job.tasks) { + if (t.completed) { + _completedTasks.add(t.id); + } + } + }); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: Text( + widget.stationTitle?.isNotEmpty == true + ? '${AppLocalizations.of(context).tasks} - ${widget.stationTitle}' + : '${AppLocalizations.of(context).tasks} - ${widget.job.jobNumber}', + ), + backgroundColor: Colors.deepPurple[100], + leading: IconButton( + icon: const Icon(Icons.arrow_back), + onPressed: () { + Navigator.of(context).pop(); + }, + ), + actions: [ + IconButton( + icon: const Icon(Icons.chat), + onPressed: () { + Navigator.of(context).pushNamed('/chats'); + }, + tooltip: AppLocalizations.of(context).openChat, + ), + ], + ), + body: Column( + children: [ + OfflineBanner(), + if (_getRemark().isNotEmpty) + Container( + width: double.infinity, + margin: const EdgeInsets.all(5), + constraints: const BoxConstraints(maxHeight: 150), + padding: const EdgeInsets.all(12.0), + decoration: BoxDecoration( + color: const Color(0xFFF8F9FA), + border: Border.all(color: Colors.grey[300]!, width: 1), + borderRadius: BorderRadius.circular(8), + ), + child: SingleChildScrollView( + child: Text( + _getRemark(), + style: TextStyle(fontSize: 14, color: Colors.grey[700]), + ), + ), + ), + Expanded( + child: Padding( + padding: const EdgeInsets.all(16.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [Expanded(child: _buildTasksStepper())], + ), + ), + ), + ], + ), + ); + } + + Widget _buildTasksStepper() { + if (_visibleTasks.isEmpty) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.task_outlined, size: 64, color: Colors.grey[400]), + const SizedBox(height: 16), + Text( + AppLocalizations.of(context).noTasks, + style: TextStyle(fontSize: 16, color: Colors.grey[600]), + ), + const SizedBox(height: 8), + Text( + AppLocalizations.of(context).noTasksMessage, + style: TextStyle(fontSize: 14, color: Colors.grey[500]), + textAlign: TextAlign.center, + ), + ], + ), + ); + } + + return ListView.builder( + itemCount: _visibleTasks.length, + itemBuilder: (context, index) { + final task = _visibleTasks[index]; + final isCompleted = _completedTasks.contains(task.id); + final isSkipped = _skippedTasks.contains(task.id); + final canBeCompletedNow = + !isCompleted && !isSkipped && _arePreviousTasksCompleted(index); + + // Hintergrundfarbe je nach Status: + // abgeschlossen → hellgrün, übersprungen → hellgelb, bearbeitbar → weiß, gesperrt → hellgrau + final Color cardColor = + isCompleted + ? const Color(0xFFE8F5E9) // hellgrün + : isSkipped + ? const Color(0xFFFFF8E1) // hellgelb + : canBeCompletedNow + ? Colors.white + : const Color(0xFFF5F5F5); // hellgrau + final Color borderColor = + isCompleted + ? Colors.green[300]! + : isSkipped + ? Colors.amber[300]! + : canBeCompletedNow + ? Colors.grey[300]! + : Colors.grey[200]!; + final Color circleColor = + isCompleted + ? Colors.green[600]! + : isSkipped + ? Colors.amber[600]! + : canBeCompletedNow + ? Colors.deepPurple[400]! + : Colors.grey[400]!; + + return Card( + margin: const EdgeInsets.only(bottom: 12), + elevation: isCompleted || canBeCompletedNow ? 2 : 0, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + side: BorderSide(color: borderColor, width: 1), + ), + child: InkWell( + onTap: + canBeCompletedNow + ? () => _showTaskCompletionDialog(task, index) + : null, + borderRadius: BorderRadius.circular(12), + child: Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(12), + color: cardColor, + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + // Task number circle + Container( + width: 40, + height: 40, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: circleColor, + ), + child: Center( + child: Text( + '${index + 1}', + style: TextStyle( + color: Colors.white, + fontWeight: FontWeight.bold, + fontSize: 16, + ), + ), + ), + ), + const SizedBox(width: 16), + // Task content + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildTaskDisplayText( + task, + isCompleted || isSkipped, + index, + ), + if (_getTaskStationLabel(task) != null) ...[ + const SizedBox(height: 4), + Text( + _getTaskStationLabel(task)!, + style: TextStyle( + fontSize: 12, + color: Colors.grey[600], + fontWeight: FontWeight.w500, + ), + ), + ], + ], + ), + ), + if (isCompleted) ...[ + const SizedBox(width: 8), + Icon(Icons.check_circle, color: Colors.green[600]), + ], + if (isSkipped) ...[ + const SizedBox(width: 8), + Icon(Icons.skip_next, color: Colors.amber[600]), + ], + ], + ), + ), + ), + ); + }, + ); + } + + void _showTaskCompletionDialog(Task task, int taskIndex) { + switch (task) { + case ConfirmationTask(): + _showConfirmationDialog(task, taskIndex); + break; + case PhotoTask(): + _showPhotoDialog(task); + break; + case TodoListTask(): + _showTodoListDialog(task); + break; + case SignatureTask(): + _showSignatureDialog(task); + break; + case BarcodeTask(): + _showBarcodeDialog(task); + break; + case CommentTask(): + _showCommentDialog(task); + break; + default: + _showGenericDialog(task); + break; + } + } + + void _showConfirmationDialog(ConfirmationTask task, int taskIndex) { + final description = + task.description?.isNotEmpty == true + ? task.description! + : AppLocalizations.of(context).confirmationDescription; + final buttonText = + task.buttonText.isNotEmpty + ? task.buttonText + : AppLocalizations.of(context).confirm; + + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: Text(AppLocalizations.of(context).confirmationRequired), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [Text(description)], + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: Text(AppLocalizations.of(context).cancel), + ), + ElevatedButton( + onPressed: () { + Navigator.of(context).pop(); + _completeTask(task.id, taskType: 'CONFIRMATION'); + }, + child: Text(buttonText), + ), + ], + ); + }, + ); + } + + // Compress photos and Base64-encode while keeping total payload under a cap + Future> _compressAndEncodePhotos( + List photos, { + int maxDim = 1280, + int jpegQuality = 70, + int maxTotalBase64Bytes = 450 * 1024, + }) async { + final List encoded = []; + int total = 0; + for (final bytes in photos) { + try { + final img.Image? decoded = img.decodeImage(bytes); + if (decoded == null) { + continue; + } + // Resize if needed keeping aspect ratio + final int w = decoded.width; + final int h = decoded.height; + img.Image resized = decoded; + final int longest = w > h ? w : h; + if (longest > maxDim) { + if (w >= h) { + resized = img.copyResize(decoded, width: maxDim); + } else { + resized = img.copyResize(decoded, height: maxDim); + } + } + final List jpg = img.encodeJpg(resized, quality: jpegQuality); + final String b64 = base64Encode(jpg); + // Respect total payload cap + if (total + b64.length > maxTotalBase64Bytes) { + break; + } + encoded.add(b64); + total += b64.length; + } catch (e, st) { + developer.log('Photo compress/encode error: $e', name: 'TaskView'); + developer.log('Stack: $st', name: 'TaskView'); + } + } + return encoded; + } + + void _showPhotoDialog(PhotoTask task) { + Navigator.of(context).push( + MaterialPageRoute( + builder: + (context) => PhotoCaptureScreen( + task: task, + onPhotosCompleted: (List photoData) async { + // Compress + encode photos for network send (limit payload) + final List base64List = await _compressAndEncodePhotos( + photoData, + ); + final bool truncated = base64List.length < photoData.length; + + // Try to persist full-quality (encoded) photos to DB for offline/backup + try { + // Persist the compressed versions to keep DB size reasonable as well + await _databaseService.saveTaskPhotos(task.id, base64List); + } catch (e, stackTrace) { + developer.log( + 'Error saving task photos: $e', + name: 'TaskView', + ); + developer.log('Stack trace: $stackTrace', name: 'TaskView'); + } + + // Always complete the task regardless of persistence success/failure + _completeTask( + task.id, + taskType: 'PHOTO', + extraData: { + 'photos': base64List, + 'count': photoData.length, + if (truncated) 'truncated': true, + }, + ); + }, + ), + ), + ); + } + + void _showTodoListDialog(TodoListTask task) { + final items = task.todoItems; + final List checkedItems = List.filled(items.length, false); + + showDialog( + context: context, + builder: (BuildContext context) { + return StatefulBuilder( + builder: (context, setState) { + return AlertDialog( + title: Text(AppLocalizations.of(context).checklist), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(AppLocalizations.of(context).checklistDescription), + const SizedBox(height: 16), + ...items.asMap().entries.map((entry) { + final index = entry.key; + final item = entry.value; + return CheckboxListTile( + title: Text(item), + value: checkedItems[index], + onChanged: (bool? value) { + setState(() { + checkedItems[index] = value ?? false; + }); + }, + dense: true, + contentPadding: EdgeInsets.zero, + ); + }), + ], + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: Text(AppLocalizations.of(context).abort), + ), + ElevatedButton( + onPressed: + checkedItems.every((checked) => checked) + ? () { + Navigator.of(context).pop(); + _completeTask( + task.id, + taskType: 'TODOLIST', + extraData: { + 'items': task.todoItems, + 'checkedStates': checkedItems, + }, + ); + } + : null, + child: Text(AppLocalizations.of(context).finish), + ), + ], + ); + }, + ); + }, + ); + } + + void _showSignatureDialog(SignatureTask task) { + Navigator.of(context).push( + MaterialPageRoute( + builder: + (context) => SignatureCaptureScreen( + task: task, + onSignatureCompleted: (String svg) async { + try { + // Persist SVG only (no PNG) + await _databaseService.saveTaskSignature(task.id, svg); + } catch (e, stackTrace) { + developer.log( + 'Error saving task signature: $e', + name: 'TaskView', + ); + developer.log('Stack trace: $stackTrace', name: 'TaskView'); + } + // Store SVG for later use in this TaskView session + setState(() { + _signatureSvgByTask[task.id] = svg; + }); + // Read back once (for analyzer to see it used) and optional debug + debugPrint( + 'Signature SVG stored for task ${task.id}: length=${_signatureSvgByTask[task.id]?.length ?? 0}', + ); + + _completeTask( + task.id, + taskType: 'SIGNATURE', + extraData: { + 'signatureSvg': svg, + 'svgLength': svg.length, + 'hasSignature': true, + }, + ); + }, + ), + ), + ); + } + + void _showBarcodeDialog(BarcodeTask task) { + Navigator.of(context).push( + MaterialPageRoute( + builder: + (context) => BarcodeCaptureScreen( + task: task, + onBarcodesCompleted: (List barcodes) async { + try { + // Save barcodes to database for later use + await _databaseService.saveTaskBarcodes(task.id, barcodes); + } catch (e, stackTrace) { + developer.log( + 'Error saving task barcodes: $e', + name: 'TaskView', + ); + developer.log('Stack trace: $stackTrace', name: 'TaskView'); + } + _completeTask( + task.id, + taskType: 'BARCODE', + extraData: {'barcodes': barcodes, 'count': barcodes.length}, + ); + }, + ), + ), + ); + } + + void _showGenericDialog(Task task) { + final TextEditingController noteController = TextEditingController(); + + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: Text(AppLocalizations.of(context).completeTask), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(AppLocalizations.of(context).completeTaskConfirm), + const SizedBox(height: 16), + TextField( + controller: noteController, + decoration: InputDecoration( + labelText: AppLocalizations.of(context).completeTaskNote, + border: const OutlineInputBorder(), + ), + maxLines: 3, + ), + ], + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: Text(AppLocalizations.of(context).abort), + ), + ElevatedButton( + onPressed: () { + Navigator.of(context).pop(); + _completeTask(task.id, taskType: 'GENERIC'); + }, + child: Text(AppLocalizations.of(context).complete), + ), + ], + ); + }, + ); + } + + void _completeTask( + String taskId, { + String? taskType, + Map? extraData, + }) { + setState(() { + _completedTasks.add(taskId); + }); + // Save to database + _databaseService.saveTaskStatus(taskId, true); + + // Notify server via STOMP about task completion (best-effort) + try { + StompService().sendTaskCompleted( + taskId: taskId, + taskType: taskType, + extraData: extraData, + ); + } catch (e) { + developer.log('Error sending task completion: $e', name: 'TaskView'); + } + } + + bool _arePreviousTasksCompleted(int index) { + if (index <= 0) return true; + for (int i = 0; i < index; i++) { + final t = _visibleTasks[i]; + if (!t.optional && + !_completedTasks.contains(t.id) && + !_skippedTasks.contains(t.id)) { + return false; + } + } + return true; + } + + void _showCommentDialog(CommentTask task) { + final TextEditingController commentController = TextEditingController(); + commentController.text = task.commentText; + + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: Text(AppLocalizations.of(context).enterComment), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(AppLocalizations.of(context).commentDescription), + const SizedBox(height: 16), + TextField( + controller: commentController, + decoration: InputDecoration( + labelText: + task.required + ? AppLocalizations.of(context).commentRequired + : AppLocalizations.of(context).comment, + border: const OutlineInputBorder(), + hintText: '...', + ), + maxLines: 4, + minLines: 2, + ), + ], + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: Text(AppLocalizations.of(context).abort), + ), + ElevatedButton( + onPressed: () { + final comment = commentController.text.trim(); + if (task.required && comment.isEmpty) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text( + AppLocalizations.of(context).commentRequired, + ), + ), + ); + return; + } + Navigator.of(context).pop(); + _completeTask( + task.id, + taskType: 'COMMENT', + extraData: { + 'commentText': comment, + 'required': task.required, + }, + ); + }, + child: Text(AppLocalizations.of(context).save), + ), + ], + ); + }, + ); + } + + Widget _buildTaskDisplayText(Task task, bool isCompleted, int taskIndex) { + final titleStyle = TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600, + color: Colors.grey[800], + decoration: isCompleted ? TextDecoration.lineThrough : null, + ); + final subtitleStyle = TextStyle( + fontSize: 13, + color: Colors.grey[600], + decoration: isCompleted ? TextDecoration.lineThrough : null, + ); + + final displayName = task.displayName; + final description = task.description; + + if (displayName?.isNotEmpty == true) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(displayName!, style: titleStyle), + if (description?.isNotEmpty == true) ...[ + const SizedBox(height: 2), + Text(description!, style: subtitleStyle), + ], + ], + ); + } + + if (description?.isNotEmpty == true) { + return Text(description!, style: titleStyle); + } + + // Fall back to standard text based on task type + return Text(_getStandardTaskDisplayText(task), style: titleStyle); + } + + String _getStandardTaskDisplayText(Task task) { + // Generate display text based on task type + switch (task) { + case PhotoTask(): + return '${AppLocalizations.of(context).takePhotos} (${task.minPhotoCount}-${task.maxPhotoCount} ${AppLocalizations.of(context).photosCount})'; + + case TodoListTask(): + return '${AppLocalizations.of(context).checklist} (${task.todoItems.length} ${AppLocalizations.of(context).checklistPoints})'; + + case SignatureTask(): + return AppLocalizations.of(context).signatureRequiredText; + + case BarcodeTask(): + return '${AppLocalizations.of(context).scanBarcodes} (${task.minBarcodeCount}-${task.maxBarcodeCount} ${AppLocalizations.of(context).barcodeCount})'; + + case CommentTask(): + return task.required + ? AppLocalizations.of(context).commentRequired + : AppLocalizations.of(context).commentOptional; + + default: + return AppLocalizations.of(context).genericTask; + } + } + + String _getRemark() => widget.job.remark; + + String? _getTaskStationLabel(Task task) { + if (widget.stationOrder != null) { + return null; + } + final stationOrder = task.stationOrder; + if (stationOrder == null) { + return null; + } + + for (final station in widget.job.deliveryStations) { + if (station.stationOrder == stationOrder) { + final suffix = + station.displayName.isNotEmpty ? station.displayName : station.city; + return suffix.isNotEmpty + ? 'Station ${stationOrder + 1}: $suffix' + : 'Station ${stationOrder + 1}'; + } + } + + return 'Station ${stationOrder + 1}'; + } +} diff --git a/app/lib/tasks/barcode_capture_screen.dart b/app/lib/tasks/barcode_capture_screen.dart new file mode 100644 index 0000000..adcd469 --- /dev/null +++ b/app/lib/tasks/barcode_capture_screen.dart @@ -0,0 +1,227 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/foundation.dart'; +import 'package:mobile_scanner/mobile_scanner.dart'; +import '../l10n/app_localizations.dart'; +import '../models/tasks/barcode_task.dart'; +import '../widgets/offline_banner.dart'; + +class BarcodeCaptureScreen extends StatefulWidget { + final BarcodeTask task; + final Function(List) onBarcodesCompleted; + + const BarcodeCaptureScreen({super.key, required this.task, required this.onBarcodesCompleted}); + + @override + State createState() => _BarcodeCaptureScreenState(); +} + +class _BarcodeCaptureScreenState extends State { + final List _scannedBarcodes = []; + final List _textControllers = []; + MobileScannerController? _scannerController; + bool _isMobilePlatform = false; + bool _isScannerInitialized = false; + + @override + void initState() { + super.initState(); + _detectPlatformAndInit(); + } + + @override + void dispose() { + _scannerController?.dispose(); + for (final controller in _textControllers) { + controller.dispose(); + } + super.dispose(); + } + + void _detectPlatformAndInit() { + // Determine if we're on a mobile platform + if (kIsWeb) { + _isMobilePlatform = false; + _initializeDesktopMode(); + } else { + switch (defaultTargetPlatform) { + case TargetPlatform.android: + case TargetPlatform.iOS: + _isMobilePlatform = true; + _initializeMobileScanner(); + break; + case TargetPlatform.macOS: + case TargetPlatform.windows: + case TargetPlatform.linux: + _isMobilePlatform = false; + _initializeDesktopMode(); + break; + default: + _isMobilePlatform = false; + _initializeDesktopMode(); + } + } + } + + void _initializeMobileScanner() { + try { + _scannerController = MobileScannerController(); + setState(() { + _isScannerInitialized = true; + }); + } catch (e) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('${AppLocalizations.of(context).cameraError}: $e'))); + } + } + } + + void _initializeDesktopMode() { + // Create text controllers for desktop input fields + for (int i = 0; i < widget.task.maxBarcodeCount; i++) { + _textControllers.add(TextEditingController()); + } + setState(() { + _isScannerInitialized = true; + }); + } + + void _onBarcodeDetected(BarcodeCapture capture) { + final List barcodes = capture.barcodes; + for (final barcode in barcodes) { + final String? code = barcode.rawValue; + if (code != null && code.isNotEmpty && !_scannedBarcodes.contains(code)) { + if (_scannedBarcodes.length < widget.task.maxBarcodeCount) { + setState(() { + _scannedBarcodes.add(code); + }); + } + } + } + } + + void _removeBarcode(int index) { + setState(() { + _scannedBarcodes.removeAt(index); + }); + } + + void _finishTask() { + final List barcodes; + if (_isMobilePlatform) { + barcodes = _scannedBarcodes; + } else { + // Collect barcodes from text fields + barcodes = []; + for (final controller in _textControllers) { + if (controller.text.trim().isNotEmpty) { + barcodes.add(controller.text.trim()); + } + } + } + + // Navigate back to task view first + Navigator.of(context).pop(); + + // Then call the completion callback + widget.onBarcodesCompleted(barcodes); + } + + bool _canFinish() { + if (_isMobilePlatform) { + return _scannedBarcodes.length >= widget.task.minBarcodeCount; + } else { + int filledFields = 0; + for (final controller in _textControllers) { + if (controller.text.trim().isNotEmpty) { + filledFields++; + } + } + return filledFields >= widget.task.minBarcodeCount; + } + } + + @override + Widget build(BuildContext context) { + return Scaffold(appBar: AppBar(title: Text(AppLocalizations.of(context).barcodeScan), backgroundColor: Colors.deepPurple[100], leading: IconButton(icon: const Icon(Icons.arrow_back), onPressed: () => Navigator.of(context).pop())), body: Column(children: [OfflineBanner(), Expanded(child: _isScannerInitialized ? (_isMobilePlatform ? _buildMobileView() : _buildDesktopView()) : const Center(child: CircularProgressIndicator()))])); + } + + Widget _buildMobileView() { + return Column( + children: [ + // Scanner view + Expanded( + flex: 3, + child: Stack( + children: [ + MobileScanner(controller: _scannerController, onDetect: _onBarcodeDetected), + // Overlay with scanning frame + Container(decoration: BoxDecoration(color: Colors.black.withValues(alpha: 0.5)), child: Center(child: Container(width: 250, height: 250, decoration: BoxDecoration(border: Border.all(color: Colors.white, width: 2), borderRadius: BorderRadius.circular(12)), child: Container(margin: const EdgeInsets.all(20), decoration: BoxDecoration(border: Border.all(color: Colors.green, width: 2), borderRadius: BorderRadius.circular(8)))))), + ], + ), + ), + // Scanned barcodes list + Expanded( + flex: 2, + child: Container( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('${AppLocalizations.of(context).scannedBarcodes} (${_scannedBarcodes.length}/${widget.task.maxBarcodeCount})', style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold)), + const SizedBox(height: 8), + Text('${AppLocalizations.of(context).minBarcodes} ${widget.task.minBarcodeCount} ${AppLocalizations.of(context).barcodesRequired}', style: TextStyle(fontSize: 14, color: Colors.grey[600])), + const SizedBox(height: 16), + Expanded( + child: ListView.builder( + itemCount: _scannedBarcodes.length, + itemBuilder: (context, index) { + return Card(child: ListTile(leading: const Icon(Icons.qr_code), title: Text(_scannedBarcodes[index]), trailing: IconButton(icon: const Icon(Icons.delete, color: Colors.red), onPressed: () => _removeBarcode(index)))); + }, + ), + ), + const SizedBox(height: 16), + SizedBox(width: double.infinity, child: ElevatedButton(onPressed: _canFinish() ? _finishTask : null, style: ElevatedButton.styleFrom(padding: const EdgeInsets.symmetric(vertical: 16)), child: Text(AppLocalizations.of(context).finish))), + ], + ), + ), + ), + ], + ); + } + + Widget _buildDesktopView() { + return Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(AppLocalizations.of(context).enterBarcode, style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold)), + const SizedBox(height: 8), + Text('${AppLocalizations.of(context).barcodeEnterDescription} (${widget.task.minBarcodeCount}-${widget.task.maxBarcodeCount})', style: TextStyle(fontSize: 16, color: Colors.grey[600])), + const SizedBox(height: 24), + Expanded( + child: ListView.builder( + itemCount: widget.task.maxBarcodeCount, + itemBuilder: (context, index) { + return Padding( + padding: const EdgeInsets.only(bottom: 12), + child: TextField( + controller: _textControllers[index], + decoration: InputDecoration(labelText: index < widget.task.minBarcodeCount ? AppLocalizations.of(context).barcodeNumberRequired(index + 1) : AppLocalizations.of(context).barcodeNumberOptional(index + 1), border: const OutlineInputBorder(), prefixIcon: const Icon(Icons.qr_code)), + onChanged: (value) { + setState(() { + // Trigger rebuild to update button state + }); + }, + ), + ); + }, + ), + ), + const SizedBox(height: 16), + SizedBox(width: double.infinity, child: ElevatedButton(onPressed: _canFinish() ? _finishTask : null, style: ElevatedButton.styleFrom(padding: const EdgeInsets.symmetric(vertical: 16)), child: Text(AppLocalizations.of(context).finish))), + ], + ), + ); + } +} diff --git a/app/lib/tasks/photo_capture_screen.dart b/app/lib/tasks/photo_capture_screen.dart new file mode 100644 index 0000000..93e0316 --- /dev/null +++ b/app/lib/tasks/photo_capture_screen.dart @@ -0,0 +1,679 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter/foundation.dart'; +import 'package:camera/camera.dart'; +import 'package:file_picker/file_picker.dart'; +import 'package:file_selector/file_selector.dart' as fsel; +import 'package:votianlt_app/services/developer.dart' as developer; +import '../l10n/app_localizations.dart'; +import '../models/tasks/photo_task.dart'; +import '../widgets/offline_banner.dart'; + +class PhotoCaptureScreen extends StatefulWidget { + final PhotoTask task; + final Function(List) onPhotosCompleted; + + const PhotoCaptureScreen({ + super.key, + required this.task, + required this.onPhotosCompleted, + }); + + @override + State createState() => _PhotoCaptureScreenState(); +} + +class _PhotoCaptureScreenState extends State { + CameraController? _cameraController; // Android/iOS/Web + List? _cameras; + final List _capturedPhotos = []; + final PageController _pageController = PageController(); + int _currentPhotoIndex = 0; + bool _isCameraInitialized = false; + bool _isCameraSupportedOnThisPlatform = false; + bool _useFilePickerMode = false; // desktop fallback + + @override + void initState() { + super.initState(); + _detectPlatformSupportAndInit(); + } + + @override + void dispose() { + _cameraController?.dispose(); + _pageController.dispose(); + super.dispose(); + } + + void _detectPlatformSupportAndInit() { + // Requirement: Desktop (macOS/Windows/Linux) uses file picker; Android/iOS uses camera. + if (kIsWeb) { + // Keep web behavior using camera if available + _isCameraSupportedOnThisPlatform = true; + _initializeCamera(); + return; + } + switch (defaultTargetPlatform) { + case TargetPlatform.android: + case TargetPlatform.iOS: + _isCameraSupportedOnThisPlatform = true; // enable capture button + _useFilePickerMode = false; + _initializeCamera(); + return; + case TargetPlatform.macOS: + case TargetPlatform.windows: + case TargetPlatform.linux: + // Desktop → use file picker instead of camera + _isCameraSupportedOnThisPlatform = true; // enable button + _useFilePickerMode = true; + return; + default: + _isCameraSupportedOnThisPlatform = false; + } + } + + Future _initializeCamera() async { + try { + // Android/iOS/Web camera initialization + _cameras = await availableCameras(); + if (_cameras != null && _cameras!.isNotEmpty) { + _cameraController = CameraController( + _cameras![0], + ResolutionPreset.medium, + ); + await _cameraController!.initialize(); + if (mounted) { + setState(() { + _isCameraInitialized = true; + }); + } + } + } catch (e, stackTrace) { + developer.log('Error initializing camera: $e', name: 'PhotoCaptureScreen'); + developer.log('Stack trace: $stackTrace', name: 'PhotoCaptureScreen'); + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('${AppLocalizations.of(context).cameraError}: $e')), + ); + } + } + } + + Future _capturePhoto() async { + try { + // Camera plugin path (Android/iOS/Web) + if (_cameraController != null && _isCameraInitialized) { + final XFile photo = await _cameraController!.takePicture(); + final Uint8List photoBytes = await photo.readAsBytes(); + + setState(() { + _capturedPhotos.add(photoBytes); + }); + + // Navigate to the newly added photo (even if it's the first one). If the + // PageView is not attached yet, _showPhotoAt will schedule a post-frame jump. + _showPhotoAt(_capturedPhotos.length - 1); + } else { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(AppLocalizations.of(context).cameraNotReady)), + ); + } + } + } catch (e, stackTrace) { + developer.log('Error capturing photo: $e', name: 'PhotoCaptureScreen'); + developer.log('Stack trace: $stackTrace', name: 'PhotoCaptureScreen'); + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('${AppLocalizations.of(context).photoError}: $e')), + ); + } + } + } + + Future _pickPhotoFromFile() async { + try { + // Use file_selector for desktop and web for robust platform support + final bool useFileSelector = kIsWeb || + defaultTargetPlatform == TargetPlatform.macOS || + defaultTargetPlatform == TargetPlatform.windows || + defaultTargetPlatform == TargetPlatform.linux; + + if (useFileSelector) { + final typeGroup = fsel.XTypeGroup( + label: 'images', + extensions: ['jpg', 'jpeg', 'png', 'heic', 'bmp', 'gif', 'webp'], + ); + final fsel.XFile? picked = await fsel.openFile(acceptedTypeGroups: [typeGroup]); + if (picked != null) { + final data = await picked.readAsBytes(); + setState(() { + _capturedPhotos.add(data); + }); + + _showPhotoAt(_capturedPhotos.length - 1); + } + } else { + // On Android/iOS, use file_picker which integrates with platform pickers + final result = await FilePicker.platform.pickFiles( + allowMultiple: false, + type: FileType.image, + withData: true, + ); + if (result != null && result.files.isNotEmpty) { + final file = result.files.first; + final bytes = file.bytes; + if (bytes != null) { + setState(() { + _capturedPhotos.add(bytes); + }); + + _showPhotoAt(_capturedPhotos.length - 1); + } else { + // On some platforms, bytes may be null if withData was false; try path + final path = file.path; + if (path != null) { + final data = await XFile(path).readAsBytes(); + setState(() { + _capturedPhotos.add(data); + }); + if (_capturedPhotos.length > 1) { + _showPhotoAt(_capturedPhotos.length - 1); + } + } + } + } + } + } catch (e, stackTrace) { + developer.log('Error picking photo from file: $e', name: 'PhotoCaptureScreen'); + developer.log('Stack trace: $stackTrace', name: 'PhotoCaptureScreen'); + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('${AppLocalizations.of(context).photoError}: $e')), + ); + } + } + } + + void _deletePhoto(int index) { + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: Text(AppLocalizations.of(context).deletePhoto), + content: Text(AppLocalizations.of(context).deletePhotoConfirm), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: Text(AppLocalizations.of(context).cancel), + ), + ElevatedButton( + onPressed: () { + Navigator.of(context).pop(); + // Remove and navigate to a valid photo if any remain + int targetIndex = _currentPhotoIndex; + setState(() { + _capturedPhotos.removeAt(index); + if (_capturedPhotos.isEmpty) { + _currentPhotoIndex = 0; + } else { + if (targetIndex >= _capturedPhotos.length) { + targetIndex = _capturedPhotos.length - 1; + } + _currentPhotoIndex = targetIndex; + } + }); + if (_capturedPhotos.isNotEmpty) { + _showPhotoAt(_currentPhotoIndex); + } + }, + style: ElevatedButton.styleFrom(backgroundColor: Colors.red), + child: Text(AppLocalizations.of(context).delete, style: const TextStyle(color: Colors.white)), + ), + ], + ); + }, + ); + } + + bool get _canComplete { + return _capturedPhotos.length >= widget.task.minPhotoCount && + _capturedPhotos.length <= widget.task.maxPhotoCount; + } + + bool get _canTakeMore { + return _capturedPhotos.length < widget.task.maxPhotoCount; + } + + bool get _isDesktopPlatform { + if (kIsWeb) return false; + switch (defaultTargetPlatform) { + case TargetPlatform.macOS: + case TargetPlatform.windows: + case TargetPlatform.linux: + return true; + default: + return false; + } + } + + void _showPhotoAt(int index) { + if (_capturedPhotos.isEmpty) return; + final int clamped = index.clamp(0, _capturedPhotos.length - 1); + if (!mounted) return; + + // Always schedule navigation after the current frame so that + // PageView has rebuilt with the latest itemCount before we jump/animate. + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + if (_pageController.hasClients) { + try { + _pageController.animateToPage( + clamped, + duration: const Duration(milliseconds: 250), + curve: Curves.easeInOut, + ); + } catch (e, stackTrace) { + developer.log('Error animating to page: $e', name: 'PhotoCaptureScreen'); + developer.log('Stack trace: $stackTrace', name: 'PhotoCaptureScreen'); + _pageController.jumpToPage(clamped); + } + setState(() { + _currentPhotoIndex = clamped; + }); + } + }); + } + + void _goToPreviousPhoto() { + if (_currentPhotoIndex > 0) { + _showPhotoAt(_currentPhotoIndex - 1); + } + } + + void _goToNextPhoto() { + if (_currentPhotoIndex < _capturedPhotos.length - 1) { + _showPhotoAt(_currentPhotoIndex + 1); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: Text(AppLocalizations.of(context).photoCapture), + backgroundColor: Colors.blue, + foregroundColor: Colors.white, + actions: [ + if (_canComplete) + TextButton( + onPressed: () { + widget.onPhotosCompleted(_capturedPhotos); + Navigator.of(context).pop(); + }, + child: Text( + AppLocalizations.of(context).finish, + style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold), + ), + ), + ], + ), + body: Column( + children: [ + OfflineBanner(), + // Task info header + Container( + width: double.infinity, + padding: EdgeInsets.all(16), + color: Colors.grey[100], + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '${AppLocalizations.of(context).requiredPhotos}: ${widget.task.minPhotoCount}-${widget.task.maxPhotoCount}', + style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold), + ), + Text( + '${AppLocalizations.of(context).photosTaken}: ${_capturedPhotos.length}', + style: TextStyle(fontSize: 14, color: Colors.grey[600]), + ), + ], + ), + ), + + // Camera preview, photo gallery or empty state + Expanded( + child: _capturedPhotos.isEmpty + ? _buildCameraOrEmptyState() + : _buildPhotoGallery(), + ), + + // Bottom controls + Container( + padding: EdgeInsets.all(16), + decoration: BoxDecoration( + color: Colors.white, + boxShadow: [ + BoxShadow( + color: Colors.grey.withValues(alpha: 0.3), + spreadRadius: 1, + blurRadius: 5, + offset: Offset(0, -3), + ), + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: [ + // Camera or file select button + Expanded( + child: ElevatedButton.icon( + onPressed: _canTakeMore && _isCameraSupportedOnThisPlatform + ? (_useFilePickerMode + ? _pickPhotoFromFile + : (_isCameraInitialized ? _capturePhoto : null)) + : null, + icon: Icon(_useFilePickerMode ? Icons.photo_library : Icons.camera_alt), + label: Text( + !_isCameraSupportedOnThisPlatform + ? AppLocalizations.of(context).cameraNotSupportedOnPlatform + : (!_canTakeMore + ? AppLocalizations.of(context).maxPhotosReached + : (_useFilePickerMode + ? AppLocalizations.of(context).selectPhoto + : (_isCameraInitialized ? AppLocalizations.of(context).takePhoto : (defaultTargetPlatform == TargetPlatform.macOS ? AppLocalizations.of(context).cameraReadyNoPreview : AppLocalizations.of(context).cameraLoading)))), + ), + style: ElevatedButton.styleFrom( + backgroundColor: _canTakeMore && (_useFilePickerMode || _isCameraInitialized) ? Colors.blue : Colors.grey, + foregroundColor: Colors.white, + padding: EdgeInsets.symmetric(vertical: 12), + ), + ), + ), + + if (_capturedPhotos.isNotEmpty) ...[ + SizedBox(width: 16), + // Delete current photo button + ElevatedButton.icon( + onPressed: () => _deletePhoto(_currentPhotoIndex), + icon: Icon(Icons.delete), + label: Text(AppLocalizations.of(context).delete), + style: ElevatedButton.styleFrom( + backgroundColor: Colors.red, + foregroundColor: Colors.white, + padding: EdgeInsets.symmetric(vertical: 12, horizontal: 16), + ), + ), + ], + ], + ), + SizedBox(height: 12), + // Bottom 'Fertig' button placed under the row + SizedBox( + width: double.infinity, + child: ElevatedButton( + onPressed: _canComplete + ? () { + widget.onPhotosCompleted(_capturedPhotos); + Navigator.of(context).pop(); + } + : null, + style: ElevatedButton.styleFrom( + backgroundColor: _canComplete ? Colors.green : Colors.grey, + foregroundColor: Colors.white, + padding: EdgeInsets.symmetric(vertical: 14), + ), + child: Text(AppLocalizations.of(context).finish, style: const TextStyle(fontWeight: FontWeight.bold)), + ), + ), + ], + ), + ), + ], + ), + ); + } + + Widget _buildCameraOrEmptyState() { + // If platform not supported, show informative message + if (!_isCameraSupportedOnThisPlatform) { + return Center( + child: Padding( + padding: EdgeInsets.all(24), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.desktop_windows, size: 80, color: Colors.grey[400]), + SizedBox(height: 16), + Text( + AppLocalizations.of(context).cameraNotAvailable, + style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600, color: Colors.grey[700]), + ), + SizedBox(height: 8), + Text( + AppLocalizations.of(context).cameraNotSupportedMessage, + textAlign: TextAlign.center, + style: TextStyle(fontSize: 14, color: Colors.grey[600]), + ), + ], + ), + ), + ); + } + + // macOS fallback: explain file selection + if (_useFilePickerMode) { + return Center( + child: Padding( + padding: EdgeInsets.all(24), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.photo_library, size: 80, color: Colors.grey[400]), + SizedBox(height: 16), + Text( + AppLocalizations.of(context).addPhotos, + style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600, color: Colors.grey[700]), + ), + SizedBox(height: 8), + Text( + AppLocalizations.of(context).addPhotosInstruction, + textAlign: TextAlign.center, + style: TextStyle(fontSize: 14, color: Colors.grey[600]), + ), + ], + ), + ), + ); + } + + // Show camera preview if available on any platform + if (_isCameraInitialized && _cameraController != null) { + return Container( + margin: EdgeInsets.all(16), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(12), + boxShadow: [ + BoxShadow( + color: Colors.grey.withValues(alpha: 0.3), + spreadRadius: 2, + blurRadius: 8, + offset: Offset(0, 4), + ), + ], + ), + child: ClipRRect( + borderRadius: BorderRadius.circular(12), + child: CameraPreview(_cameraController!), + ), + ); + } + + // When camera is not available, show empty state + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon( + Icons.camera_alt, + size: 80, + color: Colors.grey[400], + ), + SizedBox(height: 16), + Text( + AppLocalizations.of(context).cameraInitializing, + style: TextStyle( + fontSize: 18, + color: Colors.grey[600], + fontWeight: FontWeight.w500, + ), + ), + SizedBox(height: 8), + Text( + AppLocalizations.of(context).cameraLoadingMessage, + style: TextStyle( + fontSize: 14, + color: Colors.grey[500], + ), + textAlign: TextAlign.center, + ), + ], + ), + ); + } + + Widget _buildPhotoGallery() { + return Column( + children: [ + // Photo counter (if more than one photo) + if (_capturedPhotos.length > 1) + Container( + padding: EdgeInsets.symmetric(vertical: 8), + child: Text( + '${_currentPhotoIndex + 1} ${AppLocalizations.of(context).photoOf} ${_capturedPhotos.length}', + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.w500, + color: Colors.grey[700], + ), + ), + ), + + // Photo viewer with swipe gestures and navigation arrows + Expanded( + child: Stack( + children: [ + PageView.builder( + controller: _pageController, + onPageChanged: (index) { + setState(() { + _currentPhotoIndex = index; + }); + }, + itemCount: _capturedPhotos.length, + itemBuilder: (context, index) { + return Container( + margin: EdgeInsets.all(16), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(12), + boxShadow: [ + BoxShadow( + color: Colors.grey.withValues(alpha: 0.3), + spreadRadius: 2, + blurRadius: 8, + offset: Offset(0, 4), + ), + ], + ), + child: ClipRRect( + borderRadius: BorderRadius.circular(12), + child: Image.memory( + _capturedPhotos[index], + fit: BoxFit.contain, + errorBuilder: (context, error, stackTrace) { + return Container( + color: Colors.grey[300], + child: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.error, size: 50, color: Colors.grey[600]), + SizedBox(height: 8), + Text(AppLocalizations.of(context).photoError), + ], + ), + ), + ); + }, + ), + ), + ); + }, + ), + if (_capturedPhotos.length > 1 && _isDesktopPlatform) + Positioned( + left: 8, + top: 0, + bottom: 0, + child: Center( + child: IconButton( + onPressed: _currentPhotoIndex > 0 + ? _goToPreviousPhoto + : null, + icon: Icon(Icons.chevron_left, size: 36), + style: IconButton.styleFrom( + backgroundColor: Colors.white.withValues(alpha: 0.7), + ), + ), + ), + ), + if (_capturedPhotos.length > 1 && _isDesktopPlatform) + Positioned( + right: 8, + top: 0, + bottom: 0, + child: Center( + child: IconButton( + onPressed: _currentPhotoIndex < _capturedPhotos.length - 1 + ? _goToNextPhoto + : null, + icon: Icon(Icons.chevron_right, size: 36), + style: IconButton.styleFrom( + backgroundColor: Colors.white.withValues(alpha: 0.7), + ), + ), + ), + ), + ], + ), + ), + + // Photo indicators (if more than one photo) + if (_capturedPhotos.length > 1) + Container( + padding: EdgeInsets.symmetric(vertical: 16), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: _capturedPhotos.asMap().entries.map((entry) { + return Container( + width: 8, + height: 8, + margin: EdgeInsets.symmetric(horizontal: 4), + decoration: BoxDecoration( + shape: BoxShape.circle, + color: _currentPhotoIndex == entry.key + ? Colors.blue + : Colors.grey[400], + ), + ); + }).toList(), + ), + ), + ], + ); + } +} \ No newline at end of file diff --git a/app/lib/tasks/signature_capture_screen.dart b/app/lib/tasks/signature_capture_screen.dart new file mode 100644 index 0000000..8c5413f --- /dev/null +++ b/app/lib/tasks/signature_capture_screen.dart @@ -0,0 +1,260 @@ + +import 'package:flutter/material.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:signature/signature.dart'; +import '../l10n/app_localizations.dart'; +import '../models/tasks/signature_task.dart'; +import '../widgets/offline_banner.dart'; + +class SignatureCaptureScreen extends StatefulWidget { + final SignatureTask task; + final void Function(String svg) onSignatureCompleted; + + const SignatureCaptureScreen({ + super.key, + required this.task, + required this.onSignatureCompleted, + }); + + @override + State createState() => _SignatureCaptureScreenState(); +} + +class _SignatureCaptureScreenState extends State { + late final SignatureController _controller; + bool _hasSignature = false; + bool _isMobilePlatform = false; + + @override + void initState() { + super.initState(); + _controller = SignatureController( + penStrokeWidth: 3, + penColor: Colors.black, + exportBackgroundColor: Colors.white, + ); + + // Listen to signature controller changes + _controller.addListener(_onSignatureChanged); + + _detectPlatformAndSetOrientation(); + } + + void _onSignatureChanged() { + final bool hasPoints = _controller.points.isNotEmpty; + if (hasPoints != _hasSignature) { + setState(() { + _hasSignature = hasPoints; + }); + } + } + + void _detectPlatformAndSetOrientation() { + // Check if we're on a mobile platform + if (!kIsWeb) { + switch (defaultTargetPlatform) { + case TargetPlatform.android: + case TargetPlatform.iOS: + _isMobilePlatform = true; + // Rotate screen 90 degrees to the right (landscape left) + SystemChrome.setPreferredOrientations([ + DeviceOrientation.landscapeLeft, + ]); + break; + default: + _isMobilePlatform = false; + } + } + } + + void _restoreOrientation() { + // Restore original orientation when leaving the screen + if (_isMobilePlatform) { + SystemChrome.setPreferredOrientations([ + DeviceOrientation.portraitUp, + DeviceOrientation.portraitDown, + DeviceOrientation.landscapeLeft, + DeviceOrientation.landscapeRight, + ]); + } + } + + @override + void dispose() { + _controller.removeListener(_onSignatureChanged); + _controller.dispose(); + _restoreOrientation(); + super.dispose(); + } + + String _buildSvgFromPoints(List points, {double strokeWidth = 3.0, String strokeColor = '#000000'}) { + // Convert collected signature points (with null separators for stroke breaks) into an SVG string + // Determine bounds + double? minX, minY, maxX, maxY; + for (final p in points) { + if (p == null) continue; + final x = p.offset.dx; + final y = p.offset.dy; + if (minX == null || x < minX) minX = x; + if (minY == null || y < minY) minY = y; + if (maxX == null || x > maxX) maxX = x; + if (maxY == null || y > maxY) maxY = y; + } + // Fallback bounds if empty or degenerate + if (minX == null || minY == null || maxX == null || maxY == null) { + minX = 0; + minY = 0; + maxX = 1; + maxY = 1; + } + double width = (maxX - minX); + double height = (maxY - minY); + if (width <= 0) width = 1; + if (height <= 0) height = 1; + + final StringBuffer d = StringBuffer(); + bool newStroke = true; + for (final p in points) { + if (p == null) { + newStroke = true; + continue; + } + final x = (p.offset.dx - minX); + final y = (p.offset.dy - minY); + if (newStroke) { + d.write('M${x.toStringAsFixed(2)} ${y.toStringAsFixed(2)} '); + newStroke = false; + } else { + d.write('L${x.toStringAsFixed(2)} ${y.toStringAsFixed(2)} '); + } + } + + final String svg = ''; + return svg; + } + + Future _finish() async { + try { + // Ensure there is at least one non-null point in the signature + final hasAnyPoint = _controller.points.isNotEmpty; + if (!hasAnyPoint) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(AppLocalizations.of(context).signatureRequired)), + ); + return; + } + + // Build SVG from the captured signature points + final String svg = _buildSvgFromPoints(_controller.points); + + // Close this screen first to show the updated TaskView quickly + if (!mounted) return; + _restoreOrientation(); + Navigator.of(context).pop(); + + // Then notify the caller (SVG only) + widget.onSignatureCompleted(svg); + } catch (e) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('${AppLocalizations.of(context).signatureError}: $e')), + ); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: Text(AppLocalizations.of(context).signatureCapture), + backgroundColor: Colors.deepPurple[100], + leading: IconButton( + icon: const Icon(Icons.arrow_back), + onPressed: () { + _restoreOrientation(); + Navigator.of(context).pop(); + }, + ), + actions: [ + IconButton( + tooltip: AppLocalizations.of(context).delete, + onPressed: () { + _controller.clear(); + // The listener will automatically update _hasSignature when points are cleared + }, + icon: const Icon(Icons.delete_outline), + ), + ], + ), + body: Column( + children: [ + OfflineBanner(), + Expanded( + child: Padding( + padding: const EdgeInsets.all(16.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + AppLocalizations.of(context).signatureInstruction, + style: TextStyle(color: Colors.grey[700]), + ), + const SizedBox(height: 12), + Expanded( + child: Container( + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: Colors.grey[400]!), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.05), + blurRadius: 6, + offset: const Offset(0, 2), + ), + ], + ), + child: ClipRRect( + borderRadius: BorderRadius.circular(12), + child: Signature( + controller: _controller, + backgroundColor: Colors.white, + ), + ), + ), + ), + const SizedBox(height: 16), + Row( + children: [ + OutlinedButton.icon( + onPressed: () { + _controller.clear(); + // The listener will automatically update _hasSignature when points are cleared + }, + icon: const Icon(Icons.refresh), + label: Text(AppLocalizations.of(context).clear), + ), + const Spacer(), + SizedBox( + width: 160, + child: ElevatedButton( + onPressed: _hasSignature ? _finish : null, + style: ElevatedButton.styleFrom( + padding: const EdgeInsets.symmetric(vertical: 14), + ), + child: Text(AppLocalizations.of(context).finish), + ), + ), + ], + ), + ], + ), + ), + ), + ], + ), + ); + } +} diff --git a/app/lib/widgets/chat_photo_dialog.dart b/app/lib/widgets/chat_photo_dialog.dart new file mode 100644 index 0000000..3043a8b --- /dev/null +++ b/app/lib/widgets/chat_photo_dialog.dart @@ -0,0 +1,358 @@ +import 'package:camera/camera.dart'; +import 'package:file_picker/file_picker.dart'; +import 'package:file_selector/file_selector.dart' as file_selector; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:votianlt_app/services/developer.dart' as developer; +import '../l10n/app_localizations.dart'; + +class ChatPhotoDialog extends StatefulWidget { + const ChatPhotoDialog({super.key}); + + @override + State createState() => _ChatPhotoDialogState(); +} + +class _ChatPhotoDialogState extends State { + CameraController? _cameraController; + bool _isCameraInitialized = false; + bool _useCamera = false; + bool _useFilePicker = false; + bool _isBusy = false; + Uint8List? _previewBytes; + String? _errorMessage; + + @override + void initState() { + super.initState(); + _detectAndInit(); + } + + @override + void dispose() { + _cameraController?.dispose(); + super.dispose(); + } + + Future _detectAndInit() async { + if (kIsWeb) { + setState(() { + _useCamera = true; + _useFilePicker = true; + }); + await _initializeCamera(); + return; + } + + switch (defaultTargetPlatform) { + case TargetPlatform.android: + case TargetPlatform.iOS: + setState(() { + _useCamera = true; + _useFilePicker = true; + }); + await _initializeCamera(); + return; + case TargetPlatform.macOS: + case TargetPlatform.windows: + case TargetPlatform.linux: + setState(() { + _useFilePicker = true; + }); + return; + default: + setState(() { + _errorMessage = 'Dieses Gerät unterstützt keine Fotoaufnahme.'; + }); + } + } + + Future _initializeCamera() async { + try { + final cameras = await availableCameras(); + if (cameras.isEmpty) { + setState(() { + _errorMessage = 'Keine Kamera gefunden.'; + }); + return; + } + + final controller = CameraController( + cameras.first, + ResolutionPreset.medium, + enableAudio: false, + ); + await controller.initialize(); + + if (!mounted) { + await controller.dispose(); + return; + } + + setState(() { + _cameraController = controller; + _isCameraInitialized = true; + }); + } catch (e, stackTrace) { + developer.log( + 'Fehler beim Initialisieren der Kamera: $e', + name: 'ChatPhotoDialog', + ); + developer.log('StackTrace: $stackTrace', name: 'ChatPhotoDialog'); + if (!mounted) { + return; + } + setState(() { + _errorMessage = 'Kamera konnte nicht gestartet werden.'; + }); + } + } + + Future _capturePhoto() async { + if (_cameraController == null || !_cameraController!.value.isInitialized) { + setState(() { + _errorMessage = 'Kamera ist nicht bereit.'; + }); + return; + } + + try { + setState(() { + _isBusy = true; + _errorMessage = null; + }); + + final XFile photo = await _cameraController!.takePicture(); + final Uint8List bytes = await photo.readAsBytes(); + + if (!mounted) { + return; + } + + setState(() { + _previewBytes = bytes; + }); + } catch (e, stackTrace) { + developer.log( + 'Fehler beim Aufnehmen des Fotos: $e', + name: 'ChatPhotoDialog', + ); + developer.log('StackTrace: $stackTrace', name: 'ChatPhotoDialog'); + if (!mounted) { + return; + } + setState(() { + _errorMessage = 'Foto konnte nicht aufgenommen werden.'; + }); + } finally { + if (mounted) { + setState(() { + _isBusy = false; + }); + } + } + } + + Future _pickPhotoFromFile() async { + try { + setState(() { + _isBusy = true; + _errorMessage = null; + }); + + if (kIsWeb || + defaultTargetPlatform == TargetPlatform.macOS || + defaultTargetPlatform == TargetPlatform.windows || + defaultTargetPlatform == TargetPlatform.linux) { + final group = file_selector.XTypeGroup( + label: 'images', + extensions: ['jpg', 'jpeg', 'png', 'heic', 'bmp', 'gif', 'webp'], + ); + final file = await file_selector.openFile(acceptedTypeGroups: [group]); + if (file == null) { + return; + } + final bytes = await file.readAsBytes(); + if (!mounted) { + return; + } + setState(() { + _previewBytes = bytes; + }); + return; + } + + final result = await FilePicker.platform.pickFiles( + allowMultiple: false, + type: FileType.image, + withData: true, + ); + if (result == null || result.files.isEmpty) { + return; + } + final picked = result.files.first; + final bytes = picked.bytes; + if (bytes == null) { + setState(() { + _errorMessage = 'Die ausgewählte Datei konnte nicht gelesen werden.'; + }); + return; + } + if (!mounted) { + return; + } + setState(() { + _previewBytes = bytes; + }); + } catch (e, stackTrace) { + developer.log( + 'Fehler beim Auswählen eines Fotos: $e', + name: 'ChatPhotoDialog', + ); + developer.log('StackTrace: $stackTrace', name: 'ChatPhotoDialog'); + if (!mounted) { + return; + } + setState(() { + _errorMessage = 'Foto konnte nicht geladen werden.'; + }); + } finally { + if (mounted) { + setState(() { + _isBusy = false; + }); + } + } + } + + void _resetPreview() { + setState(() { + _previewBytes = null; + }); + } + + @override + Widget build(BuildContext context) { + return AlertDialog( + title: Text(AppLocalizations.of(context).takePhoto), + content: SizedBox(width: 320, child: _buildDialogBody()), + actions: [ + TextButton( + onPressed: _isBusy ? null : () => Navigator.of(context).pop(), + child: Text(AppLocalizations.of(context).cancel), + ), + TextButton( + onPressed: + _previewBytes != null && !_isBusy + ? () => Navigator.of(context).pop(_previewBytes) + : null, + child: Text(AppLocalizations.of(context).send), + ), + ], + ); + } + + Widget _buildDialogBody() { + if (_previewBytes != null) { + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + AspectRatio( + aspectRatio: 4 / 3, + child: ClipRRect( + borderRadius: BorderRadius.circular(12), + child: Image.memory(_previewBytes!, fit: BoxFit.cover), + ), + ), + const SizedBox(height: 12), + TextButton.icon( + onPressed: _isBusy ? null : _resetPreview, + icon: const Icon(Icons.refresh), + label: Text(AppLocalizations.of(context).retakePhoto), + ), + ], + ); + } + + if (_errorMessage != null) { + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.warning, color: Colors.orange[700], size: 40), + const SizedBox(height: 12), + Text(_errorMessage!, textAlign: TextAlign.center), + ], + ); + } + + if (_useCamera) { + if (!_isCameraInitialized) { + return const SizedBox( + height: 200, + child: Center(child: CircularProgressIndicator()), + ); + } + + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + AspectRatio( + aspectRatio: _cameraController?.value.aspectRatio ?? (3 / 4), + child: ClipRRect( + borderRadius: BorderRadius.circular(12), + child: CameraPreview(_cameraController!), + ), + ), + const SizedBox(height: 12), + Wrap( + alignment: WrapAlignment.center, + spacing: 8, + runSpacing: 8, + children: [ + ElevatedButton.icon( + onPressed: _isBusy ? null : _capturePhoto, + icon: const Icon(Icons.camera_alt), + label: Text(AppLocalizations.of(context).takePhoto), + ), + if (_useFilePicker) + OutlinedButton.icon( + onPressed: _isBusy ? null : _pickPhotoFromFile, + icon: const Icon(Icons.photo_library), + label: Text(AppLocalizations.of(context).selectFromLibrary), + ), + ], + ), + ], + ); + } + + if (_useFilePicker) { + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.photo_camera_back, + color: Colors.deepPurple[400], + size: 48, + ), + const SizedBox(height: 12), + const Text( + 'Wähle ein Foto von deinem Gerät aus.', + textAlign: TextAlign.center, + ), + const SizedBox(height: 12), + ElevatedButton.icon( + onPressed: _isBusy ? null : _pickPhotoFromFile, + icon: const Icon(Icons.photo_library), + label: Text(AppLocalizations.of(context).selectPhoto), + ), + ], + ); + } + + return const SizedBox( + height: 160, + child: Center(child: CircularProgressIndicator()), + ); + } +} diff --git a/app/lib/widgets/offline_banner.dart b/app/lib/widgets/offline_banner.dart new file mode 100644 index 0000000..6f412b5 --- /dev/null +++ b/app/lib/widgets/offline_banner.dart @@ -0,0 +1,168 @@ +import 'dart:async'; +import 'package:flutter/material.dart'; +import 'package:votianlt_app/services/developer.dart' as developer; +import 'package:votianlt_app/services/websocket_service.dart'; +import 'package:votianlt_app/services/dart_mq.dart'; + +class OfflineBanner extends StatefulWidget { + const OfflineBanner({super.key}); + + @override + State createState() => _OfflineBannerState(); +} + +class _OfflineBannerState extends State { + final StompService _stompService = StompService(); + DartMQSubscription? _connSub; + Timer? _countdownTimer; + int _secondsToRetry = 15; + bool _hadConnection = false; // Track if we ever had a successful connection + + @override + void initState() { + super.initState(); + // Check if we're already connected (e.g., coming back to this screen) + _hadConnection = _stompService.isConnected && _stompService.isAuthenticated; + // Initialize countdown based on current connection state + _onConnectionChange(_stompService.isConnected && _stompService.isAuthenticated); + _connSub = DartMQ().subscribe(MQTopics.connectionStatus, _onConnectionChange); + } + + void _onConnectionChange(bool isConnected) { + if (!mounted) return; + if (isConnected) { + _hadConnection = true; // Mark that we had a successful connection + _stopCountdown(); + setState(() {}); + } else { + _startCountdown(); + } + } + + void _startCountdown() { + _stopCountdown(); + setState(() { + _secondsToRetry = 15; + }); + _countdownTimer = Timer.periodic(const Duration(seconds: 1), (_) async { + if (!mounted) return; + if (_stompService.isConnected) { + _stopCountdown(); + return; + } + + // Decrement until 0, then attempt reconnect + if (_secondsToRetry > 1) { + setState(() { + _secondsToRetry = _secondsToRetry - 1; + }); + return; + } + + // Show 0 for one tick and try to reconnect now + setState(() { + _secondsToRetry = 0; + }); + + try { + // Only auto-reconnect if we already know the target; discovery remains user-initiated + await _stompService.connect(); + } catch (e, stackTrace) { + developer.log('Auto-reconnect attempt failed: $e', name: 'OfflineBanner'); + developer.log('Stack trace: $stackTrace', name: 'OfflineBanner'); + } + + if (!mounted) return; + if (!_stompService.isConnected) { + // Still offline -> reset countdown for next attempt + setState(() { + _secondsToRetry = 15; + }); + } + }); + } + + void _stopCountdown() { + _countdownTimer?.cancel(); + _countdownTimer = null; + } + + @override + void dispose() { + _stopCountdown(); + _connSub?.cancel(); + _connSub = null; + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final isOnline = _stompService.isConnected && _stompService.isAuthenticated; + if (isOnline) return const SizedBox.shrink(); + + // Different messages for initial connection vs connection lost + final String title; + final String subtitle; + final IconData icon; + final Color? bgColor; + final Color? iconColor; + final Color? titleColor; + final Color? subtitleColor; + + if (_hadConnection) { + // Connection was lost + title = 'Offline – Verbindung verloren'; + subtitle = 'Verbindung wird wiederhergestellt.'; + icon = Icons.wifi_off; + bgColor = Colors.red[50]; + iconColor = Colors.red[700]; + titleColor = Colors.red[900]; + subtitleColor = Colors.red[800]; + } else { + // Initial connection attempt + title = 'Verbinde mit Server...'; + subtitle = 'Bitte warten.'; + icon = Icons.sync; + bgColor = Colors.orange[50]; + iconColor = Colors.orange[700]; + titleColor = Colors.orange[900]; + subtitleColor = Colors.orange[800]; + } + + return Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 12), + color: bgColor, + child: Row( + children: [ + Icon(icon, color: iconColor), + const SizedBox(width: 8), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + title, + style: TextStyle( + color: titleColor, + fontWeight: FontWeight.w700, + ), + ), + const SizedBox(height: 2), + Text( + subtitle, + style: TextStyle( + color: subtitleColor, + fontSize: 12, + ), + ), + ], + ), + ), + ], + ), + ); + } +} + diff --git a/app/linux/.gitignore b/app/linux/.gitignore new file mode 100644 index 0000000..d3896c9 --- /dev/null +++ b/app/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/app/linux/CMakeLists.txt b/app/linux/CMakeLists.txt new file mode 100644 index 0000000..b273464 --- /dev/null +++ b/app/linux/CMakeLists.txt @@ -0,0 +1,128 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "votianlt_app") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "de.assecutor.votianlt_app") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Load bundled libraries from the lib/ directory relative to the binary. +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Root filesystem for cross-building. +if(FLUTTER_TARGET_PLATFORM_SYSROOT) + set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +endif() + +# Define build configuration options. +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") +endif() + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_14) + target_compile_options(${TARGET} PRIVATE -Wall -Werror) + target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") + target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) + +# Only the install-generated bundle's copy of the executable will launch +# correctly, since the resources must in the right relative locations. To avoid +# people trying to run the unbundled copy, put it in a subdirectory instead of +# the default top-level location. +set_target_properties(${BINARY_NAME} + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" +) + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# By default, "installing" just makes a relocatable bundle in the build +# directory. +set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +# Start with a clean build bundle directory every time. +install(CODE " + file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") + " COMPONENT Runtime) + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) + install(FILES "${bundled_library}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endforeach(bundled_library) + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") + install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() diff --git a/app/linux/flutter/CMakeLists.txt b/app/linux/flutter/CMakeLists.txt new file mode 100644 index 0000000..d5bd016 --- /dev/null +++ b/app/linux/flutter/CMakeLists.txt @@ -0,0 +1,88 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.10) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. + +# Serves the same purpose as list(TRANSFORM ... PREPEND ...), +# which isn't available in 3.10. +function(list_prepend LIST_NAME PREFIX) + set(NEW_LIST "") + foreach(element ${${LIST_NAME}}) + list(APPEND NEW_LIST "${PREFIX}${element}") + endforeach(element) + set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) +endfunction() + +# === Flutter Library === +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) +pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) +pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) + +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "fl_basic_message_channel.h" + "fl_binary_codec.h" + "fl_binary_messenger.h" + "fl_dart_project.h" + "fl_engine.h" + "fl_json_message_codec.h" + "fl_json_method_codec.h" + "fl_message_codec.h" + "fl_method_call.h" + "fl_method_channel.h" + "fl_method_codec.h" + "fl_method_response.h" + "fl_plugin_registrar.h" + "fl_plugin_registry.h" + "fl_standard_message_codec.h" + "fl_standard_method_codec.h" + "fl_string_codec.h" + "fl_value.h" + "fl_view.h" + "flutter_linux.h" +) +list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") +target_link_libraries(flutter INTERFACE + PkgConfig::GTK + PkgConfig::GLIB + PkgConfig::GIO +) +add_dependencies(flutter flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CMAKE_CURRENT_BINARY_DIR}/_phony_ + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" + ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} +) diff --git a/app/linux/flutter/generated_plugin_registrant.cc b/app/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..f27db27 --- /dev/null +++ b/app/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,23 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include +#include +#include + +void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) file_selector_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "FileSelectorPlugin"); + file_selector_plugin_register_with_registrar(file_selector_linux_registrar); + g_autoptr(FlPluginRegistrar) objectbox_flutter_libs_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "ObjectboxFlutterLibsPlugin"); + objectbox_flutter_libs_plugin_register_with_registrar(objectbox_flutter_libs_registrar); + g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin"); + url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar); +} diff --git a/app/linux/flutter/generated_plugin_registrant.h b/app/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..e0f0a47 --- /dev/null +++ b/app/linux/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void fl_register_plugins(FlPluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/app/linux/flutter/generated_plugins.cmake b/app/linux/flutter/generated_plugins.cmake new file mode 100644 index 0000000..b691ac7 --- /dev/null +++ b/app/linux/flutter/generated_plugins.cmake @@ -0,0 +1,26 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + file_selector_linux + objectbox_flutter_libs + url_launcher_linux +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/app/linux/runner/CMakeLists.txt b/app/linux/runner/CMakeLists.txt new file mode 100644 index 0000000..e97dabc --- /dev/null +++ b/app/linux/runner/CMakeLists.txt @@ -0,0 +1,26 @@ +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} + "main.cc" + "my_application.cc" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the application ID. +add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") + +# Add dependency libraries. Add any application-specific dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) + +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") diff --git a/app/linux/runner/main.cc b/app/linux/runner/main.cc new file mode 100644 index 0000000..e7c5c54 --- /dev/null +++ b/app/linux/runner/main.cc @@ -0,0 +1,6 @@ +#include "my_application.h" + +int main(int argc, char** argv) { + g_autoptr(MyApplication) app = my_application_new(); + return g_application_run(G_APPLICATION(app), argc, argv); +} diff --git a/app/linux/runner/my_application.cc b/app/linux/runner/my_application.cc new file mode 100644 index 0000000..7a14142 --- /dev/null +++ b/app/linux/runner/my_application.cc @@ -0,0 +1,130 @@ +#include "my_application.h" + +#include +#ifdef GDK_WINDOWING_X11 +#include +#endif + +#include "flutter/generated_plugin_registrant.h" + +struct _MyApplication { + GtkApplication parent_instance; + char** dart_entrypoint_arguments; +}; + +G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) + +// Implements GApplication::activate. +static void my_application_activate(GApplication* application) { + MyApplication* self = MY_APPLICATION(application); + GtkWindow* window = + GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); + + // Use a header bar when running in GNOME as this is the common style used + // by applications and is the setup most users will be using (e.g. Ubuntu + // desktop). + // If running on X and not using GNOME then just use a traditional title bar + // in case the window manager does more exotic layout, e.g. tiling. + // If running on Wayland assume the header bar will work (may need changing + // if future cases occur). + gboolean use_header_bar = TRUE; +#ifdef GDK_WINDOWING_X11 + GdkScreen* screen = gtk_window_get_screen(window); + if (GDK_IS_X11_SCREEN(screen)) { + const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); + if (g_strcmp0(wm_name, "GNOME Shell") != 0) { + use_header_bar = FALSE; + } + } +#endif + if (use_header_bar) { + GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); + gtk_widget_show(GTK_WIDGET(header_bar)); + gtk_header_bar_set_title(header_bar, "votianlt_app"); + gtk_header_bar_set_show_close_button(header_bar, TRUE); + gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); + } else { + gtk_window_set_title(window, "votianlt_app"); + } + + gtk_window_set_default_size(window, 1280, 720); + gtk_widget_show(GTK_WIDGET(window)); + + g_autoptr(FlDartProject) project = fl_dart_project_new(); + fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments); + + FlView* view = fl_view_new(project); + gtk_widget_show(GTK_WIDGET(view)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + + fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + + gtk_widget_grab_focus(GTK_WIDGET(view)); +} + +// Implements GApplication::local_command_line. +static gboolean my_application_local_command_line(GApplication* application, gchar*** arguments, int* exit_status) { + MyApplication* self = MY_APPLICATION(application); + // Strip out the first argument as it is the binary name. + self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); + + g_autoptr(GError) error = nullptr; + if (!g_application_register(application, nullptr, &error)) { + g_warning("Failed to register: %s", error->message); + *exit_status = 1; + return TRUE; + } + + g_application_activate(application); + *exit_status = 0; + + return TRUE; +} + +// Implements GApplication::startup. +static void my_application_startup(GApplication* application) { + //MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application startup. + + G_APPLICATION_CLASS(my_application_parent_class)->startup(application); +} + +// Implements GApplication::shutdown. +static void my_application_shutdown(GApplication* application) { + //MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application shutdown. + + G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application); +} + +// Implements GObject::dispose. +static void my_application_dispose(GObject* object) { + MyApplication* self = MY_APPLICATION(object); + g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); + G_OBJECT_CLASS(my_application_parent_class)->dispose(object); +} + +static void my_application_class_init(MyApplicationClass* klass) { + G_APPLICATION_CLASS(klass)->activate = my_application_activate; + G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line; + G_APPLICATION_CLASS(klass)->startup = my_application_startup; + G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown; + G_OBJECT_CLASS(klass)->dispose = my_application_dispose; +} + +static void my_application_init(MyApplication* self) {} + +MyApplication* my_application_new() { + // Set the program name to the application ID, which helps various systems + // like GTK and desktop environments map this running application to its + // corresponding .desktop file. This ensures better integration by allowing + // the application to be recognized beyond its binary name. + g_set_prgname(APPLICATION_ID); + + return MY_APPLICATION(g_object_new(my_application_get_type(), + "application-id", APPLICATION_ID, + "flags", G_APPLICATION_NON_UNIQUE, + nullptr)); +} diff --git a/app/linux/runner/my_application.h b/app/linux/runner/my_application.h new file mode 100644 index 0000000..72271d5 --- /dev/null +++ b/app/linux/runner/my_application.h @@ -0,0 +1,18 @@ +#ifndef FLUTTER_MY_APPLICATION_H_ +#define FLUTTER_MY_APPLICATION_H_ + +#include + +G_DECLARE_FINAL_TYPE(MyApplication, my_application, MY, APPLICATION, + GtkApplication) + +/** + * my_application_new: + * + * Creates a new Flutter-based application. + * + * Returns: a new #MyApplication. + */ +MyApplication* my_application_new(); + +#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/app/macos/.gitignore b/app/macos/.gitignore new file mode 100644 index 0000000..746adbb --- /dev/null +++ b/app/macos/.gitignore @@ -0,0 +1,7 @@ +# Flutter-related +**/Flutter/ephemeral/ +**/Pods/ + +# Xcode-related +**/dgph +**/xcuserdata/ diff --git a/app/macos/Flutter/Flutter-Debug.xcconfig b/app/macos/Flutter/Flutter-Debug.xcconfig new file mode 100644 index 0000000..4b81f9b --- /dev/null +++ b/app/macos/Flutter/Flutter-Debug.xcconfig @@ -0,0 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/app/macos/Flutter/Flutter-Release.xcconfig b/app/macos/Flutter/Flutter-Release.xcconfig new file mode 100644 index 0000000..5caa9d1 --- /dev/null +++ b/app/macos/Flutter/Flutter-Release.xcconfig @@ -0,0 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/app/macos/Flutter/GeneratedPluginRegistrant.swift b/app/macos/Flutter/GeneratedPluginRegistrant.swift new file mode 100644 index 0000000..a8de190 --- /dev/null +++ b/app/macos/Flutter/GeneratedPluginRegistrant.swift @@ -0,0 +1,30 @@ +// +// Generated file. Do not edit. +// + +import FlutterMacOS +import Foundation + +import file_picker +import file_selector_macos +import flutter_local_notifications +import geolocator_apple +import mobile_scanner +import objectbox_flutter_libs +import package_info_plus +import path_provider_foundation +import url_launcher_macos +import webview_flutter_wkwebview + +func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + FilePickerPlugin.register(with: registry.registrar(forPlugin: "FilePickerPlugin")) + FileSelectorPlugin.register(with: registry.registrar(forPlugin: "FileSelectorPlugin")) + FlutterLocalNotificationsPlugin.register(with: registry.registrar(forPlugin: "FlutterLocalNotificationsPlugin")) + GeolocatorPlugin.register(with: registry.registrar(forPlugin: "GeolocatorPlugin")) + MobileScannerPlugin.register(with: registry.registrar(forPlugin: "MobileScannerPlugin")) + ObjectboxFlutterLibsPlugin.register(with: registry.registrar(forPlugin: "ObjectboxFlutterLibsPlugin")) + FPPPackageInfoPlusPlugin.register(with: registry.registrar(forPlugin: "FPPPackageInfoPlusPlugin")) + PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin")) + UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin")) + WebViewFlutterPlugin.register(with: registry.registrar(forPlugin: "WebViewFlutterPlugin")) +} diff --git a/app/macos/Podfile b/app/macos/Podfile new file mode 100644 index 0000000..ff5ddb3 --- /dev/null +++ b/app/macos/Podfile @@ -0,0 +1,42 @@ +platform :osx, '10.15' + +# CocoaPods analytics sends network stats synchronously affecting flutter build latency. +ENV['COCOAPODS_DISABLE_STATS'] = 'true' + +project 'Runner', { + 'Debug' => :debug, + 'Profile' => :release, + 'Release' => :release, +} + +def flutter_root + generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'ephemeral', 'Flutter-Generated.xcconfig'), __FILE__) + unless File.exist?(generated_xcode_build_settings_path) + raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure \"flutter pub get\" is executed first" + end + + File.foreach(generated_xcode_build_settings_path) do |line| + matches = line.match(/FLUTTER_ROOT\=(.*)/) + return matches[1].strip if matches + end + raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Flutter-Generated.xcconfig, then run \"flutter pub get\"" +end + +require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) + +flutter_macos_podfile_setup + +target 'Runner' do + use_frameworks! + + flutter_install_all_macos_pods File.dirname(File.realpath(__FILE__)) + target 'RunnerTests' do + inherit! :search_paths + end +end + +post_install do |installer| + installer.pods_project.targets.each do |target| + flutter_additional_macos_build_settings(target) + end +end diff --git a/app/macos/Podfile.lock b/app/macos/Podfile.lock new file mode 100644 index 0000000..034b725 --- /dev/null +++ b/app/macos/Podfile.lock @@ -0,0 +1,86 @@ +PODS: + - file_picker (0.0.1): + - FlutterMacOS + - file_selector_macos (0.0.1): + - FlutterMacOS + - flutter_local_notifications (0.0.1): + - FlutterMacOS + - FlutterMacOS (1.0.0) + - geolocator_apple (1.2.0): + - Flutter + - FlutterMacOS + - mobile_scanner (5.2.3): + - FlutterMacOS + - ObjectBox (4.4.1) + - objectbox_flutter_libs (0.0.1): + - FlutterMacOS + - ObjectBox (= 4.4.1) + - package_info_plus (0.0.1): + - FlutterMacOS + - path_provider_foundation (0.0.1): + - Flutter + - FlutterMacOS + - url_launcher_macos (0.0.1): + - FlutterMacOS + - webview_flutter_wkwebview (0.0.1): + - Flutter + - FlutterMacOS + +DEPENDENCIES: + - file_picker (from `Flutter/ephemeral/.symlinks/plugins/file_picker/macos`) + - file_selector_macos (from `Flutter/ephemeral/.symlinks/plugins/file_selector_macos/macos`) + - flutter_local_notifications (from `Flutter/ephemeral/.symlinks/plugins/flutter_local_notifications/macos`) + - FlutterMacOS (from `Flutter/ephemeral`) + - geolocator_apple (from `Flutter/ephemeral/.symlinks/plugins/geolocator_apple/darwin`) + - mobile_scanner (from `Flutter/ephemeral/.symlinks/plugins/mobile_scanner/macos`) + - objectbox_flutter_libs (from `Flutter/ephemeral/.symlinks/plugins/objectbox_flutter_libs/macos`) + - package_info_plus (from `Flutter/ephemeral/.symlinks/plugins/package_info_plus/macos`) + - path_provider_foundation (from `Flutter/ephemeral/.symlinks/plugins/path_provider_foundation/darwin`) + - url_launcher_macos (from `Flutter/ephemeral/.symlinks/plugins/url_launcher_macos/macos`) + - webview_flutter_wkwebview (from `Flutter/ephemeral/.symlinks/plugins/webview_flutter_wkwebview/darwin`) + +SPEC REPOS: + trunk: + - ObjectBox + +EXTERNAL SOURCES: + file_picker: + :path: Flutter/ephemeral/.symlinks/plugins/file_picker/macos + file_selector_macos: + :path: Flutter/ephemeral/.symlinks/plugins/file_selector_macos/macos + flutter_local_notifications: + :path: Flutter/ephemeral/.symlinks/plugins/flutter_local_notifications/macos + FlutterMacOS: + :path: Flutter/ephemeral + geolocator_apple: + :path: Flutter/ephemeral/.symlinks/plugins/geolocator_apple/darwin + mobile_scanner: + :path: Flutter/ephemeral/.symlinks/plugins/mobile_scanner/macos + objectbox_flutter_libs: + :path: Flutter/ephemeral/.symlinks/plugins/objectbox_flutter_libs/macos + package_info_plus: + :path: Flutter/ephemeral/.symlinks/plugins/package_info_plus/macos + path_provider_foundation: + :path: Flutter/ephemeral/.symlinks/plugins/path_provider_foundation/darwin + url_launcher_macos: + :path: Flutter/ephemeral/.symlinks/plugins/url_launcher_macos/macos + webview_flutter_wkwebview: + :path: Flutter/ephemeral/.symlinks/plugins/webview_flutter_wkwebview/darwin + +SPEC CHECKSUMS: + file_picker: 7584aae6fa07a041af2b36a2655122d42f578c1a + file_selector_macos: 6280b52b459ae6c590af5d78fc35c7267a3c4b31 + flutter_local_notifications: 13862b132e32eb858dea558a86d45d08daeacfe7 + FlutterMacOS: d0db08ddef1a9af05a5ec4b724367152bb0500b1 + geolocator_apple: ab36aa0e8b7d7a2d7639b3b4e48308394e8cef5e + mobile_scanner: bd1e7cd9b67b442f4d903747f4778e040513f860 + ObjectBox: 7da4aceb5013d041bfafdbc6d744a26918b09757 + objectbox_flutter_libs: f51d18f6a4b5965c218843373b7dc5ed5e3a2008 + package_info_plus: f0052d280d17aa382b932f399edf32507174e870 + path_provider_foundation: 080d55be775b7414fd5a5ef3ac137b97b097e564 + url_launcher_macos: 0fba8ddabfc33ce0a9afe7c5fef5aab3d8d2d673 + webview_flutter_wkwebview: 1821ceac936eba6f7984d89a9f3bcb4dea99ebb2 + +PODFILE CHECKSUM: 54d867c82ac51cbd61b565781b9fada492027009 + +COCOAPODS: 1.16.2 diff --git a/app/macos/Runner.xcodeproj/project.pbxproj b/app/macos/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..5adcccc --- /dev/null +++ b/app/macos/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,801 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXAggregateTarget section */ + 33CC111A2044C6BA0003C045 /* Flutter Assemble */ = { + isa = PBXAggregateTarget; + buildConfigurationList = 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */; + buildPhases = ( + 33CC111E2044C6BF0003C045 /* ShellScript */, + ); + dependencies = ( + ); + name = "Flutter Assemble"; + productName = FLX; + }; +/* End PBXAggregateTarget section */ + +/* Begin PBXBuildFile section */ + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; }; + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; + 57F71CAB5E0EBF0FD74BB60C /* Pods_RunnerTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 647A9BAFCD1C8579C27ACB06 /* Pods_RunnerTests.framework */; }; + E87F79BD075DEE9201421A7E /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C2E4B0891E0C69DBA2C9AEB6 /* Pods_Runner.framework */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC10EC2044A3C60003C045; + remoteInfo = Runner; + }; + 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC111A2044C6BA0003C045; + remoteInfo = FLX; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 33CC110E2044A8840003C045 /* Bundle Framework */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Bundle Framework"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 25FEF72D24C8799A98FE44EA /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; + 33CC10ED2044A3C60003C045 /* votianlt_app.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = votianlt_app.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = ""; }; + 33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; }; + 33CC10F72044A3C60003C045 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = Runner/Info.plist; sourceTree = ""; }; + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainFlutterWindow.swift; sourceTree = ""; }; + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Debug.xcconfig"; sourceTree = ""; }; + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Release.xcconfig"; sourceTree = ""; }; + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = "Flutter-Generated.xcconfig"; path = "ephemeral/Flutter-Generated.xcconfig"; sourceTree = ""; }; + 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; + 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; + 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; + 363E3B406EE7CD6720F9499F /* Pods-RunnerTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.debug.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.debug.xcconfig"; sourceTree = ""; }; + 470F12E13C2EC8D8C22EFFAD /* Pods-RunnerTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.release.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.release.xcconfig"; sourceTree = ""; }; + 647A9BAFCD1C8579C27ACB06 /* Pods_RunnerTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_RunnerTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 6C9D44A130B618B8B5DF5B9D /* Pods-RunnerTests.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.profile.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.profile.xcconfig"; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; + AB167F435A1B32AED245C5DF /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; + B7673F699BC41AFB3C5BF892 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; + C2E4B0891E0C69DBA2C9AEB6 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 331C80D2294CF70F00263BE5 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 57F71CAB5E0EBF0FD74BB60C /* Pods_RunnerTests.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EA2044A3C60003C045 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + E87F79BD075DEE9201421A7E /* Pods_Runner.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C80D6294CF71000263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C80D7294CF71000263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 33BA886A226E78AF003329D5 /* Configs */ = { + isa = PBXGroup; + children = ( + 33E5194F232828860026EE4D /* AppInfo.xcconfig */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */, + ); + path = Configs; + sourceTree = ""; + }; + 33CC10E42044A3C60003C045 = { + isa = PBXGroup; + children = ( + 33FAB671232836740065AC1E /* Runner */, + 33CEB47122A05771004F2AC0 /* Flutter */, + 331C80D6294CF71000263BE5 /* RunnerTests */, + 33CC10EE2044A3C60003C045 /* Products */, + D73912EC22F37F3D000D13A0 /* Frameworks */, + 9982E4CBDB0D5FE545EF7173 /* Pods */, + ); + sourceTree = ""; + }; + 33CC10EE2044A3C60003C045 /* Products */ = { + isa = PBXGroup; + children = ( + 33CC10ED2044A3C60003C045 /* votianlt_app.app */, + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 33CC11242044D66E0003C045 /* Resources */ = { + isa = PBXGroup; + children = ( + 33CC10F22044A3C60003C045 /* Assets.xcassets */, + 33CC10F42044A3C60003C045 /* MainMenu.xib */, + 33CC10F72044A3C60003C045 /* Info.plist */, + ); + name = Resources; + path = ..; + sourceTree = ""; + }; + 33CEB47122A05771004F2AC0 /* Flutter */ = { + isa = PBXGroup; + children = ( + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */, + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */, + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */, + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */, + ); + path = Flutter; + sourceTree = ""; + }; + 33FAB671232836740065AC1E /* Runner */ = { + isa = PBXGroup; + children = ( + 33CC10F02044A3C60003C045 /* AppDelegate.swift */, + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */, + 33E51913231747F40026EE4D /* DebugProfile.entitlements */, + 33E51914231749380026EE4D /* Release.entitlements */, + 33CC11242044D66E0003C045 /* Resources */, + 33BA886A226E78AF003329D5 /* Configs */, + ); + path = Runner; + sourceTree = ""; + }; + 9982E4CBDB0D5FE545EF7173 /* Pods */ = { + isa = PBXGroup; + children = ( + 25FEF72D24C8799A98FE44EA /* Pods-Runner.debug.xcconfig */, + AB167F435A1B32AED245C5DF /* Pods-Runner.release.xcconfig */, + B7673F699BC41AFB3C5BF892 /* Pods-Runner.profile.xcconfig */, + 363E3B406EE7CD6720F9499F /* Pods-RunnerTests.debug.xcconfig */, + 470F12E13C2EC8D8C22EFFAD /* Pods-RunnerTests.release.xcconfig */, + 6C9D44A130B618B8B5DF5B9D /* Pods-RunnerTests.profile.xcconfig */, + ); + name = Pods; + path = Pods; + sourceTree = ""; + }; + D73912EC22F37F3D000D13A0 /* Frameworks */ = { + isa = PBXGroup; + children = ( + C2E4B0891E0C69DBA2C9AEB6 /* Pods_Runner.framework */, + 647A9BAFCD1C8579C27ACB06 /* Pods_RunnerTests.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C80D4294CF70F00263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + C92644550AD9162F3D6A9D10 /* [CP] Check Pods Manifest.lock */, + 331C80D1294CF70F00263BE5 /* Sources */, + 331C80D2294CF70F00263BE5 /* Frameworks */, + 331C80D3294CF70F00263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C80DA294CF71000263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C80D5294CF71000263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 33CC10EC2044A3C60003C045 /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 1010DD6DAE3A67FE110257BA /* [CP] Check Pods Manifest.lock */, + 33CC10E92044A3C60003C045 /* Sources */, + 33CC10EA2044A3C60003C045 /* Frameworks */, + 33CC10EB2044A3C60003C045 /* Resources */, + 33CC110E2044A8840003C045 /* Bundle Framework */, + 3399D490228B24CF009A79C7 /* ShellScript */, + 840B659C2FD46EAA567374AC /* [CP] Embed Pods Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + 33CC11202044C79F0003C045 /* PBXTargetDependency */, + ); + name = Runner; + productName = Runner; + productReference = 33CC10ED2044A3C60003C045 /* votianlt_app.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 33CC10E52044A3C60003C045 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastSwiftUpdateCheck = 0920; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C80D4294CF70F00263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 33CC10EC2044A3C60003C045; + }; + 33CC10EC2044A3C60003C045 = { + CreatedOnToolsVersion = 9.2; + LastSwiftMigration = 1100; + ProvisioningStyle = Automatic; + SystemCapabilities = { + com.apple.Sandbox = { + enabled = 1; + }; + }; + }; + 33CC111A2044C6BA0003C045 = { + CreatedOnToolsVersion = 9.2; + ProvisioningStyle = Manual; + }; + }; + }; + buildConfigurationList = 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 33CC10E42044A3C60003C045; + productRefGroup = 33CC10EE2044A3C60003C045 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 33CC10EC2044A3C60003C045 /* Runner */, + 331C80D4294CF70F00263BE5 /* RunnerTests */, + 33CC111A2044C6BA0003C045 /* Flutter Assemble */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C80D3294CF70F00263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EB2044A3C60003C045 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */, + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 1010DD6DAE3A67FE110257BA /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + 3399D490228B24CF009A79C7 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "echo \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed\n"; + }; + 33CC111E2044C6BF0003C045 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + Flutter/ephemeral/FlutterInputs.xcfilelist, + ); + inputPaths = ( + Flutter/ephemeral/tripwire, + ); + outputFileListPaths = ( + Flutter/ephemeral/FlutterOutputs.xcfilelist, + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; + }; + 840B659C2FD46EAA567374AC /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-input-files.xcfilelist", + ); + name = "[CP] Embed Pods Frameworks"; + outputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-output-files.xcfilelist", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + C92644550AD9162F3D6A9D10 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-RunnerTests-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C80D1294CF70F00263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10E92044A3C60003C045 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */, + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */, + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C80DA294CF71000263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC10EC2044A3C60003C045 /* Runner */; + targetProxy = 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */; + }; + 33CC11202044C79F0003C045 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */; + targetProxy = 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 33CC10F42044A3C60003C045 /* MainMenu.xib */ = { + isa = PBXVariantGroup; + children = ( + 33CC10F52044A3C60003C045 /* Base */, + ); + name = MainMenu.xib; + path = Runner; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 331C80DB294CF71000263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 363E3B406EE7CD6720F9499F /* Pods-RunnerTests.debug.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = de.assecutor.votianltApp.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/votianlt_app.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/votianlt_app"; + }; + name = Debug; + }; + 331C80DC294CF71000263BE5 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 470F12E13C2EC8D8C22EFFAD /* Pods-RunnerTests.release.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = de.assecutor.votianltApp.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/votianlt_app.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/votianlt_app"; + }; + name = Release; + }; + 331C80DD294CF71000263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 6C9D44A130B618B8B5DF5B9D /* Pods-RunnerTests.profile.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = de.assecutor.votianltApp.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/votianlt_app.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/votianlt_app"; + }; + name = Profile; + }; + 338D0CE9231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.15; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Profile; + }; + 338D0CEA231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Profile; + }; + 338D0CEB231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Profile; + }; + 33CC10F92044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.15; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 33CC10FA2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.15; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; + 33CC10FC2044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + 33CC10FD2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; + 33CC111C2044C6BA0003C045 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + 33CC111D2044C6BA0003C045 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C80DB294CF71000263BE5 /* Debug */, + 331C80DC294CF71000263BE5 /* Release */, + 331C80DD294CF71000263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10F92044A3C60003C045 /* Debug */, + 33CC10FA2044A3C60003C045 /* Release */, + 338D0CE9231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10FC2044A3C60003C045 /* Debug */, + 33CC10FD2044A3C60003C045 /* Release */, + 338D0CEA231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC111C2044C6BA0003C045 /* Debug */, + 33CC111D2044C6BA0003C045 /* Release */, + 338D0CEB231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 33CC10E52044A3C60003C045 /* Project object */; +} diff --git a/app/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/app/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/app/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/app/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/app/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..11e6fbc --- /dev/null +++ b/app/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,99 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/macos/Runner.xcworkspace/contents.xcworkspacedata b/app/macos/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..21a3cc1 --- /dev/null +++ b/app/macos/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/app/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/app/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/app/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/app/macos/Runner/AppDelegate.swift b/app/macos/Runner/AppDelegate.swift new file mode 100644 index 0000000..b3c1761 --- /dev/null +++ b/app/macos/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import Cocoa +import FlutterMacOS + +@main +class AppDelegate: FlutterAppDelegate { + override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { + return true + } + + override func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { + return true + } +} diff --git a/app/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/app/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..a2ec33f --- /dev/null +++ b/app/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,68 @@ +{ + "images" : [ + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_16.png", + "scale" : "1x" + }, + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "2x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "1x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_64.png", + "scale" : "2x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_128.png", + "scale" : "1x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "2x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "1x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "2x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "1x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_1024.png", + "scale" : "2x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/app/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/app/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png new file mode 100644 index 0000000..82b6f9d Binary files /dev/null and b/app/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png differ diff --git a/app/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/app/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png new file mode 100644 index 0000000..13b35eb Binary files /dev/null and b/app/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png differ diff --git a/app/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/app/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png new file mode 100644 index 0000000..0a3f5fa Binary files /dev/null and b/app/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png differ diff --git a/app/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/app/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png new file mode 100644 index 0000000..bdb5722 Binary files /dev/null and b/app/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png differ diff --git a/app/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/app/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png new file mode 100644 index 0000000..f083318 Binary files /dev/null and b/app/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png differ diff --git a/app/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/app/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png new file mode 100644 index 0000000..326c0e7 Binary files /dev/null and b/app/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png differ diff --git a/app/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/app/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png new file mode 100644 index 0000000..2f1632c Binary files /dev/null and b/app/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png differ diff --git a/app/macos/Runner/Base.lproj/MainMenu.xib b/app/macos/Runner/Base.lproj/MainMenu.xib new file mode 100644 index 0000000..8a7234d --- /dev/null +++ b/app/macos/Runner/Base.lproj/MainMenu.xib @@ -0,0 +1,343 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/macos/Runner/Configs/AppInfo.xcconfig b/app/macos/Runner/Configs/AppInfo.xcconfig new file mode 100644 index 0000000..5cc6262 --- /dev/null +++ b/app/macos/Runner/Configs/AppInfo.xcconfig @@ -0,0 +1,14 @@ +// Application-level settings for the Runner target. +// +// This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the +// future. If not, the values below would default to using the project name when this becomes a +// 'flutter create' template. + +// The application's name. By default this is also the title of the Flutter window. +PRODUCT_NAME = votianlt_app + +// The application's bundle identifier +PRODUCT_BUNDLE_IDENTIFIER = de.assecutor.votianltApp + +// The copyright displayed in application information +PRODUCT_COPYRIGHT = Copyright © 2025 de.assecutor. All rights reserved. diff --git a/app/macos/Runner/Configs/Debug.xcconfig b/app/macos/Runner/Configs/Debug.xcconfig new file mode 100644 index 0000000..36b0fd9 --- /dev/null +++ b/app/macos/Runner/Configs/Debug.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Debug.xcconfig" +#include "Warnings.xcconfig" diff --git a/app/macos/Runner/Configs/Release.xcconfig b/app/macos/Runner/Configs/Release.xcconfig new file mode 100644 index 0000000..dff4f49 --- /dev/null +++ b/app/macos/Runner/Configs/Release.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Release.xcconfig" +#include "Warnings.xcconfig" diff --git a/app/macos/Runner/Configs/Version.xcconfig b/app/macos/Runner/Configs/Version.xcconfig new file mode 100644 index 0000000..f3c2103 --- /dev/null +++ b/app/macos/Runner/Configs/Version.xcconfig @@ -0,0 +1,12 @@ +// +// Version.xcconfig +// Configuration for app versioning to fix DVTDeviceOperation build number issues +// + +// Set marketing version and current project version from Flutter build variables +MARKETING_VERSION = $(FLUTTER_BUILD_NAME:1.0.0) +CURRENT_PROJECT_VERSION = $(FLUTTER_BUILD_NUMBER:1) + +// Ensure build number is never empty +FLUTTER_BUILD_NAME = $(inherited:1.0.0) +FLUTTER_BUILD_NUMBER = $(inherited:1) diff --git a/app/macos/Runner/Configs/Warnings.xcconfig b/app/macos/Runner/Configs/Warnings.xcconfig new file mode 100644 index 0000000..42bcbf4 --- /dev/null +++ b/app/macos/Runner/Configs/Warnings.xcconfig @@ -0,0 +1,13 @@ +WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings +GCC_WARN_UNDECLARED_SELECTOR = YES +CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES +CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE +CLANG_WARN__DUPLICATE_METHOD_MATCH = YES +CLANG_WARN_PRAGMA_PACK = YES +CLANG_WARN_STRICT_PROTOTYPES = YES +CLANG_WARN_COMMA = YES +GCC_WARN_STRICT_SELECTOR_MATCH = YES +CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES +CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES +GCC_WARN_SHADOW = YES +CLANG_WARN_UNREACHABLE_CODE = YES diff --git a/app/macos/Runner/DebugProfile.entitlements b/app/macos/Runner/DebugProfile.entitlements new file mode 100644 index 0000000..84199e0 --- /dev/null +++ b/app/macos/Runner/DebugProfile.entitlements @@ -0,0 +1,18 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.cs.allow-jit + + com.apple.security.network.server + + com.apple.security.network.client + + com.apple.security.files.user-selected.read-write + + com.apple.security.files.downloads.read-write + + + diff --git a/app/macos/Runner/Info.plist b/app/macos/Runner/Info.plist new file mode 100644 index 0000000..7ac638d --- /dev/null +++ b/app/macos/Runner/Info.plist @@ -0,0 +1,44 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIconFile + + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSMinimumSystemVersion + $(MACOSX_DEPLOYMENT_TARGET) + NSHumanReadableCopyright + $(PRODUCT_COPYRIGHT) + NSMainNibFile + MainMenu + NSPrincipalClass + NSApplication + + NSAppTransportSecurity + + NSAllowsArbitraryLoads + + NSAllowsLocalNetworking + + + NSLocalNetworkUsageDescription + This app needs to connect to local network services for STOMP messaging. + NSPhotoLibraryUsageDescription + This app needs access to photo library to save and manage task photos. + + diff --git a/app/macos/Runner/MainFlutterWindow.swift b/app/macos/Runner/MainFlutterWindow.swift new file mode 100644 index 0000000..3cc05eb --- /dev/null +++ b/app/macos/Runner/MainFlutterWindow.swift @@ -0,0 +1,15 @@ +import Cocoa +import FlutterMacOS + +class MainFlutterWindow: NSWindow { + override func awakeFromNib() { + let flutterViewController = FlutterViewController() + let windowFrame = self.frame + self.contentViewController = flutterViewController + self.setFrame(windowFrame, display: true) + + RegisterGeneratedPlugins(registry: flutterViewController) + + super.awakeFromNib() + } +} diff --git a/app/macos/Runner/Release.entitlements b/app/macos/Runner/Release.entitlements new file mode 100644 index 0000000..c2dafcd --- /dev/null +++ b/app/macos/Runner/Release.entitlements @@ -0,0 +1,14 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.network.client + + com.apple.security.files.user-selected.read-write + + com.apple.security.files.downloads.read-write + + + diff --git a/app/macos/RunnerTests/RunnerTests.swift b/app/macos/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..61f3bd1 --- /dev/null +++ b/app/macos/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Cocoa +import FlutterMacOS +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/app/pubspec.lock b/app/pubspec.lock new file mode 100644 index 0000000..60ba3f8 --- /dev/null +++ b/app/pubspec.lock @@ -0,0 +1,1135 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + _fe_analyzer_shared: + dependency: transitive + description: + name: _fe_analyzer_shared + sha256: f0bb5d1648339c8308cc0b9838d8456b3cfe5c91f9dc1a735b4d003269e5da9a + url: "https://pub.dev" + source: hosted + version: "88.0.0" + analyzer: + dependency: transitive + description: + name: analyzer + sha256: "0b7b9c329d2879f8f05d6c05b32ee9ec025f39b077864bdb5ac9a7b63418a98f" + url: "https://pub.dev" + source: hosted + version: "8.1.1" + archive: + dependency: transitive + description: + name: archive + sha256: "2fde1607386ab523f7a36bb3e7edb43bd58e6edaf2ffb29d8a6d578b297fdbbd" + url: "https://pub.dev" + source: hosted + version: "4.0.7" + args: + dependency: transitive + description: + name: args + sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04 + url: "https://pub.dev" + source: hosted + version: "2.7.0" + async: + dependency: transitive + description: + name: async + sha256: d2872f9c19731c2e5f10444b14686eb7cc85c76274bd6c16e1816bff9a3bab63 + url: "https://pub.dev" + source: hosted + version: "2.12.0" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + build: + dependency: transitive + description: + name: build + sha256: ce76b1d48875e3233fde17717c23d1f60a91cc631597e49a400c89b475395b1d + url: "https://pub.dev" + source: hosted + version: "3.1.0" + build_config: + dependency: transitive + description: + name: build_config + sha256: "4f64382b97504dc2fcdf487d5aae33418e08b4703fc21249e4db6d804a4d0187" + url: "https://pub.dev" + source: hosted + version: "1.2.0" + build_daemon: + dependency: transitive + description: + name: build_daemon + sha256: "409002f1adeea601018715d613115cfaf0e31f512cb80ae4534c79867ae2363d" + url: "https://pub.dev" + source: hosted + version: "4.1.0" + build_resolvers: + dependency: transitive + description: + name: build_resolvers + sha256: d1d57f7807debd7349b4726a19fd32ec8bc177c71ad0febf91a20f84cd2d4b46 + url: "https://pub.dev" + source: hosted + version: "3.0.3" + build_runner: + dependency: "direct dev" + description: + name: build_runner + sha256: b24597fceb695969d47025c958f3837f9f0122e237c6a22cb082a5ac66c3ca30 + url: "https://pub.dev" + source: hosted + version: "2.7.1" + build_runner_core: + dependency: transitive + description: + name: build_runner_core + sha256: "066dda7f73d8eb48ba630a55acb50c4a84a2e6b453b1cb4567f581729e794f7b" + url: "https://pub.dev" + source: hosted + version: "9.3.1" + built_collection: + dependency: transitive + description: + name: built_collection + sha256: "376e3dd27b51ea877c28d525560790aee2e6fbb5f20e2f85d5081027d94e2100" + url: "https://pub.dev" + source: hosted + version: "5.1.1" + built_value: + dependency: transitive + description: + name: built_value + sha256: a30f0a0e38671e89a492c44d005b5545b830a961575bbd8336d42869ff71066d + url: "https://pub.dev" + source: hosted + version: "8.12.0" + camera: + dependency: "direct main" + description: + name: camera + sha256: dfa8fc5a1adaeb95e7a54d86a5bd56f4bb0e035515354c8ac6d262e35cec2ec8 + url: "https://pub.dev" + source: hosted + version: "0.10.6" + camera_android: + dependency: transitive + description: + name: camera_android + sha256: "4db8a27da163130d913ab4360297549ead1c7f9a6a88e71c44e5f4d10081a3d4" + url: "https://pub.dev" + source: hosted + version: "0.10.10+6" + camera_avfoundation: + dependency: transitive + description: + name: camera_avfoundation + sha256: "951ef122d01ebba68b7a54bfe294e8b25585635a90465c311b2f875ae72c412f" + url: "https://pub.dev" + source: hosted + version: "0.9.21+2" + camera_platform_interface: + dependency: transitive + description: + name: camera_platform_interface + sha256: "2f757024a48696ff4814a789b0bd90f5660c0fb25f393ab4564fb483327930e2" + url: "https://pub.dev" + source: hosted + version: "2.10.0" + camera_web: + dependency: transitive + description: + name: camera_web + sha256: "595f28c89d1fb62d77c73c633193755b781c6d2e0ebcd8dc25b763b514e6ba8f" + url: "https://pub.dev" + source: hosted + version: "0.3.5" + characters: + dependency: transitive + description: + name: characters + sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + checked_yaml: + dependency: transitive + description: + name: checked_yaml + sha256: feb6bed21949061731a7a75fc5d2aa727cf160b91af9a3e464c5e3a32e28b5ff + url: "https://pub.dev" + source: hosted + version: "2.0.3" + clock: + dependency: transitive + description: + name: clock + sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b + url: "https://pub.dev" + source: hosted + version: "1.1.2" + code_builder: + dependency: transitive + description: + name: code_builder + sha256: "11654819532ba94c34de52ff5feb52bd81cba1de00ef2ed622fd50295f9d4243" + url: "https://pub.dev" + source: hosted + version: "4.11.0" + collection: + dependency: transitive + description: + name: collection + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.dev" + source: hosted + version: "1.19.1" + convert: + dependency: transitive + description: + name: convert + sha256: b30acd5944035672bc15c6b7a8b47d773e41e2f17de064350988c5d02adb1c68 + url: "https://pub.dev" + source: hosted + version: "3.1.2" + cross_file: + dependency: transitive + description: + name: cross_file + sha256: "7caf6a750a0c04effbb52a676dce9a4a592e10ad35c34d6d2d0e4811160d5670" + url: "https://pub.dev" + source: hosted + version: "0.3.4+2" + crypto: + dependency: transitive + description: + name: crypto + sha256: "1e445881f28f22d6140f181e07737b22f1e099a5e1ff94b0af2f9e4a463f4855" + url: "https://pub.dev" + source: hosted + version: "3.0.6" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + sha256: ba631d1c7f7bef6b729a622b7b752645a2d076dba9976925b8f25725a30e1ee6 + url: "https://pub.dev" + source: hosted + version: "1.0.8" + dart_style: + dependency: transitive + description: + name: dart_style + sha256: c87dfe3d56f183ffe9106a18aebc6db431fc7c98c31a54b952a77f3d54a85697 + url: "https://pub.dev" + source: hosted + version: "3.1.2" + dbus: + dependency: transitive + description: + name: dbus + sha256: "79e0c23480ff85dc68de79e2cd6334add97e48f7f4865d17686dd6ea81a47e8c" + url: "https://pub.dev" + source: hosted + version: "0.7.11" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44" + url: "https://pub.dev" + source: hosted + version: "1.3.3" + ffi: + dependency: transitive + description: + name: ffi + sha256: "289279317b4b16eb2bb7e271abccd4bf84ec9bdcbe999e278a94b804f5630418" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + file: + dependency: transitive + description: + name: file + sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4 + url: "https://pub.dev" + source: hosted + version: "7.0.1" + file_picker: + dependency: "direct main" + description: + name: file_picker + sha256: ab13ae8ef5580a411c458d6207b6774a6c237d77ac37011b13994879f68a8810 + url: "https://pub.dev" + source: hosted + version: "8.3.7" + file_selector: + dependency: "direct main" + description: + name: file_selector + sha256: "5019692b593455127794d5718304ff1ae15447dea286cdda9f0db2a796a1b828" + url: "https://pub.dev" + source: hosted + version: "1.0.3" + file_selector_android: + dependency: transitive + description: + name: file_selector_android + sha256: "4be8ae7374c81daf88e49084a1d68dfe68466ef38a6a3d711cc0b83d53e22465" + url: "https://pub.dev" + source: hosted + version: "0.5.1+16" + file_selector_ios: + dependency: transitive + description: + name: file_selector_ios + sha256: fe9f52123af16bba4ad65bd7e03defbbb4b172a38a8e6aaa2a869a0c56a5f5fb + url: "https://pub.dev" + source: hosted + version: "0.5.3+2" + file_selector_linux: + dependency: transitive + description: + name: file_selector_linux + sha256: "54cbbd957e1156d29548c7d9b9ec0c0ebb6de0a90452198683a7d23aed617a33" + url: "https://pub.dev" + source: hosted + version: "0.9.3+2" + file_selector_macos: + dependency: transitive + description: + name: file_selector_macos + sha256: "19124ff4a3d8864fdc62072b6a2ef6c222d55a3404fe14893a3c02744907b60c" + url: "https://pub.dev" + source: hosted + version: "0.9.4+4" + file_selector_platform_interface: + dependency: transitive + description: + name: file_selector_platform_interface + sha256: a3994c26f10378a039faa11de174d7b78eb8f79e4dd0af2a451410c1a5c3f66b + url: "https://pub.dev" + source: hosted + version: "2.6.2" + file_selector_web: + dependency: transitive + description: + name: file_selector_web + sha256: c4c0ea4224d97a60a7067eca0c8fd419e708ff830e0c83b11a48faf566cec3e7 + url: "https://pub.dev" + source: hosted + version: "0.9.4+2" + file_selector_windows: + dependency: transitive + description: + name: file_selector_windows + sha256: "320fcfb6f33caa90f0b58380489fc5ac05d99ee94b61aa96ec2bff0ba81d3c2b" + url: "https://pub.dev" + source: hosted + version: "0.9.3+4" + fixnum: + dependency: transitive + description: + name: fixnum + sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be + url: "https://pub.dev" + source: hosted + version: "1.1.1" + flat_buffers: + dependency: transitive + description: + name: flat_buffers + sha256: "380bdcba5664a718bfd4ea20a45d39e13684f5318fcd8883066a55e21f37f4c3" + url: "https://pub.dev" + source: hosted + version: "23.5.26" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: "5398f14efa795ffb7a33e9b6a08798b26a180edac4ad7db3f231e40f82ce11e1" + url: "https://pub.dev" + source: hosted + version: "5.0.0" + flutter_local_notifications: + dependency: "direct main" + description: + name: flutter_local_notifications + sha256: ef41ae901e7529e52934feba19ed82827b11baa67336829564aeab3129460610 + url: "https://pub.dev" + source: hosted + version: "18.0.1" + flutter_local_notifications_linux: + dependency: transitive + description: + name: flutter_local_notifications_linux + sha256: "8f685642876742c941b29c32030f6f4f6dacd0e4eaecb3efbb187d6a3812ca01" + url: "https://pub.dev" + source: hosted + version: "5.0.0" + flutter_local_notifications_platform_interface: + dependency: transitive + description: + name: flutter_local_notifications_platform_interface + sha256: "6c5b83c86bf819cdb177a9247a3722067dd8cc6313827ce7c77a4b238a26fd52" + url: "https://pub.dev" + source: hosted + version: "8.0.0" + flutter_localizations: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_plugin_android_lifecycle: + dependency: transitive + description: + name: flutter_plugin_android_lifecycle + sha256: b0694b7fb1689b0e6cc193b3f1fcac6423c4f93c74fb20b806c6b6f196db0c31 + url: "https://pub.dev" + source: hosted + version: "2.0.30" + flutter_svg: + dependency: transitive + description: + name: flutter_svg + sha256: b9c2ad5872518a27507ab432d1fb97e8813b05f0fc693f9d40fad06d073e0678 + url: "https://pub.dev" + source: hosted + version: "2.2.1" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + frontend_server_client: + dependency: transitive + description: + name: frontend_server_client + sha256: f64a0333a82f30b0cca061bc3d143813a486dc086b574bfb233b7c1372427694 + url: "https://pub.dev" + source: hosted + version: "4.0.0" + geolocator: + dependency: "direct main" + description: + name: geolocator + sha256: f62bcd90459e63210bbf9c35deb6a51c521f992a78de19a1fe5c11704f9530e2 + url: "https://pub.dev" + source: hosted + version: "13.0.4" + geolocator_android: + dependency: transitive + description: + name: geolocator_android + sha256: fcb1760a50d7500deca37c9a666785c047139b5f9ee15aa5469fae7dbbe3170d + url: "https://pub.dev" + source: hosted + version: "4.6.2" + geolocator_apple: + dependency: transitive + description: + name: geolocator_apple + sha256: dbdd8789d5aaf14cf69f74d4925ad1336b4433a6efdf2fce91e8955dc921bf22 + url: "https://pub.dev" + source: hosted + version: "2.3.13" + geolocator_platform_interface: + dependency: transitive + description: + name: geolocator_platform_interface + sha256: "30cb64f0b9adcc0fb36f628b4ebf4f731a2961a0ebd849f4b56200205056fe67" + url: "https://pub.dev" + source: hosted + version: "4.2.6" + geolocator_web: + dependency: transitive + description: + name: geolocator_web + sha256: b1ae9bdfd90f861fde8fd4f209c37b953d65e92823cb73c7dee1fa021b06f172 + url: "https://pub.dev" + source: hosted + version: "4.1.3" + geolocator_windows: + dependency: transitive + description: + name: geolocator_windows + sha256: "175435404d20278ffd220de83c2ca293b73db95eafbdc8131fe8609be1421eb6" + url: "https://pub.dev" + source: hosted + version: "0.2.5" + glob: + dependency: transitive + description: + name: glob + sha256: c3f1ee72c96f8f78935e18aa8cecced9ab132419e8625dc187e1c2408efc20de + url: "https://pub.dev" + source: hosted + version: "2.1.3" + graphs: + dependency: transitive + description: + name: graphs + sha256: "741bbf84165310a68ff28fe9e727332eef1407342fca52759cb21ad8177bb8d0" + url: "https://pub.dev" + source: hosted + version: "2.3.2" + http: + dependency: "direct main" + description: + name: http + sha256: bb2ce4590bc2667c96f318d68cac1b5a7987ec819351d32b1c987239a815e007 + url: "https://pub.dev" + source: hosted + version: "1.5.0" + http_multi_server: + dependency: transitive + description: + name: http_multi_server + sha256: aa6199f908078bb1c5efb8d8638d4ae191aac11b311132c3ef48ce352fb52ef8 + url: "https://pub.dev" + source: hosted + version: "3.2.2" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571" + url: "https://pub.dev" + source: hosted + version: "4.1.2" + image: + dependency: "direct main" + description: + name: image + sha256: "4e973fcf4caae1a4be2fa0a13157aa38a8f9cb049db6529aa00b4d71abc4d928" + url: "https://pub.dev" + source: hosted + version: "4.5.4" + intl: + dependency: transitive + description: + name: intl + sha256: "3df61194eb431efc39c4ceba583b95633a403f46c9fd341e550ce0bfa50e9aa5" + url: "https://pub.dev" + source: hosted + version: "0.20.2" + io: + dependency: transitive + description: + name: io + sha256: dfd5a80599cf0165756e3181807ed3e77daf6dd4137caaad72d0b7931597650b + url: "https://pub.dev" + source: hosted + version: "1.0.5" + json_annotation: + dependency: transitive + description: + name: json_annotation + sha256: "1ce844379ca14835a50d2f019a3099f419082cfdd231cd86a142af94dd5c6bb1" + url: "https://pub.dev" + source: hosted + version: "4.9.0" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de" + url: "https://pub.dev" + source: hosted + version: "11.0.2" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1" + url: "https://pub.dev" + source: hosted + version: "3.0.10" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + lints: + dependency: transitive + description: + name: lints + sha256: c35bb79562d980e9a453fc715854e1ed39e24e7d0297a880ef54e17f9874a9d7 + url: "https://pub.dev" + source: hosted + version: "5.1.1" + logging: + dependency: transitive + description: + name: logging + sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61 + url: "https://pub.dev" + source: hosted + version: "1.3.0" + matcher: + dependency: transitive + description: + name: matcher + sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2 + url: "https://pub.dev" + source: hosted + version: "0.12.17" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec + url: "https://pub.dev" + source: hosted + version: "0.11.1" + meta: + dependency: transitive + description: + name: meta + sha256: "23f08335362185a5ea2ad3a4e597f1375e78bce8a040df5c600c8d3552ef2394" + url: "https://pub.dev" + source: hosted + version: "1.17.0" + mime: + dependency: transitive + description: + name: mime + sha256: "41a20518f0cb1256669420fdba0cd90d21561e560ac240f26ef8322e45bb7ed6" + url: "https://pub.dev" + source: hosted + version: "2.0.0" + mobile_scanner: + dependency: "direct main" + description: + name: mobile_scanner + sha256: d234581c090526676fd8fab4ada92f35c6746e3fb4f05a399665d75a399fb760 + url: "https://pub.dev" + source: hosted + version: "5.2.3" + objectbox: + dependency: "direct main" + description: + name: objectbox + sha256: "3cc186749178a3556e1020c9082d0897d0f9ecbdefcc27320e65c5bc650f0e57" + url: "https://pub.dev" + source: hosted + version: "4.3.1" + objectbox_flutter_libs: + dependency: "direct main" + description: + name: objectbox_flutter_libs + sha256: cd754766e04229a4f51250f121813d9a3c1a74fc21cd68e48b3c6085cbcd6c85 + url: "https://pub.dev" + source: hosted + version: "4.3.1" + objectbox_generator: + dependency: "direct dev" + description: + name: objectbox_generator + sha256: "71a3f6948e631be5c7160d512ad2a8cb7471cdbcf1731ec6baf2a794b82386d7" + url: "https://pub.dev" + source: hosted + version: "4.3.1" + package_config: + dependency: transitive + description: + name: package_config + sha256: f096c55ebb7deb7e384101542bfba8c52696c1b56fca2eb62827989ef2353bbc + url: "https://pub.dev" + source: hosted + version: "2.2.0" + package_info_plus: + dependency: "direct main" + description: + name: package_info_plus + sha256: "16eee997588c60225bda0488b6dcfac69280a6b7a3cf02c741895dd370a02968" + url: "https://pub.dev" + source: hosted + version: "8.3.1" + package_info_plus_platform_interface: + dependency: transitive + description: + name: package_info_plus_platform_interface + sha256: "202a487f08836a592a6bd4f901ac69b3a8f146af552bbd14407b6b41e1c3f086" + url: "https://pub.dev" + source: hosted + version: "3.2.1" + path: + dependency: "direct main" + description: + name: path + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" + url: "https://pub.dev" + source: hosted + version: "1.9.1" + path_parsing: + dependency: transitive + description: + name: path_parsing + sha256: "883402936929eac138ee0a45da5b0f2c80f89913e6dc3bf77eb65b84b409c6ca" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + path_provider: + dependency: "direct main" + description: + name: path_provider + sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd" + url: "https://pub.dev" + source: hosted + version: "2.1.5" + path_provider_android: + dependency: transitive + description: + name: path_provider_android + sha256: "3b4c1fc3aa55ddc9cd4aa6759984330d5c8e66aa7702a6223c61540dc6380c37" + url: "https://pub.dev" + source: hosted + version: "2.2.19" + path_provider_foundation: + dependency: transitive + description: + name: path_provider_foundation + sha256: "16eef174aacb07e09c351502740fa6254c165757638eba1e9116b0a781201bbd" + url: "https://pub.dev" + source: hosted + version: "2.4.2" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279 + url: "https://pub.dev" + source: hosted + version: "2.2.1" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 + url: "https://pub.dev" + source: hosted + version: "2.3.0" + petitparser: + dependency: transitive + description: + name: petitparser + sha256: "07c8f0b1913bcde1ff0d26e57ace2f3012ccbf2b204e070290dad3bb22797646" + url: "https://pub.dev" + source: hosted + version: "6.1.0" + platform: + dependency: transitive + description: + name: platform + sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984" + url: "https://pub.dev" + source: hosted + version: "3.1.6" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" + url: "https://pub.dev" + source: hosted + version: "2.1.8" + pointycastle: + dependency: transitive + description: + name: pointycastle + sha256: "92aa3841d083cc4b0f4709b5c74fd6409a3e6ba833ffc7dc6a8fee096366acf5" + url: "https://pub.dev" + source: hosted + version: "4.0.0" + pool: + dependency: transitive + description: + name: pool + sha256: "978783255c543aa3586a1b3c21f6e9d720eb315376a915872c61ef8b5c20177d" + url: "https://pub.dev" + source: hosted + version: "1.5.2" + posix: + dependency: transitive + description: + name: posix + sha256: "6323a5b0fa688b6a010df4905a56b00181479e6d10534cecfecede2aa55add61" + url: "https://pub.dev" + source: hosted + version: "6.0.3" + pub_semver: + dependency: transitive + description: + name: pub_semver + sha256: "5bfcf68ca79ef689f8990d1160781b4bad40a3bd5e5218ad4076ddb7f4081585" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + pubspec_parse: + dependency: transitive + description: + name: pubspec_parse + sha256: "0560ba233314abbed0a48a2956f7f022cce7c3e1e73df540277da7544cad4082" + url: "https://pub.dev" + source: hosted + version: "1.5.0" + shelf: + dependency: transitive + description: + name: shelf + sha256: e7dd780a7ffb623c57850b33f43309312fc863fb6aa3d276a754bb299839ef12 + url: "https://pub.dev" + source: hosted + version: "1.4.2" + shelf_web_socket: + dependency: transitive + description: + name: shelf_web_socket + sha256: "3632775c8e90d6c9712f883e633716432a27758216dfb61bd86a8321c0580925" + url: "https://pub.dev" + source: hosted + version: "3.0.0" + signature: + dependency: "direct main" + description: + name: signature + sha256: "8056e091ad59c2eb5735fee975ec649d0caf8ce802bb1ffb1e0955b00a6d0daa" + url: "https://pub.dev" + source: hosted + version: "5.5.0" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + source_gen: + dependency: transitive + description: + name: source_gen + sha256: "7b19d6ba131c6eb98bfcbf8d56c1a7002eba438af2e7ae6f8398b2b0f4f381e3" + url: "https://pub.dev" + source: hosted + version: "3.1.0" + source_span: + dependency: transitive + description: + name: source_span + sha256: "254ee5351d6cb365c859e20ee823c3bb479bf4a293c22d17a9f1bf144ce86f7c" + url: "https://pub.dev" + source: hosted + version: "1.10.1" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" + url: "https://pub.dev" + source: hosted + version: "1.12.1" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + stream_transform: + dependency: transitive + description: + name: stream_transform + sha256: ad47125e588cfd37a9a7f86c7d6356dde8dfe89d071d293f80ca9e9273a33871 + url: "https://pub.dev" + source: hosted + version: "2.1.1" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" + url: "https://pub.dev" + source: hosted + version: "1.4.1" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" + url: "https://pub.dev" + source: hosted + version: "1.2.2" + test_api: + dependency: transitive + description: + name: test_api + sha256: ab2726c1a94d3176a45960b6234466ec367179b87dd74f1611adb1f3b5fb9d55 + url: "https://pub.dev" + source: hosted + version: "0.7.7" + timezone: + dependency: transitive + description: + name: timezone + sha256: dd14a3b83cfd7cb19e7888f1cbc20f258b8d71b54c06f79ac585f14093a287d1 + url: "https://pub.dev" + source: hosted + version: "0.10.1" + timing: + dependency: transitive + description: + name: timing + sha256: "62ee18aca144e4a9f29d212f5a4c6a053be252b895ab14b5821996cff4ed90fe" + url: "https://pub.dev" + source: hosted + version: "1.0.2" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + url_launcher: + dependency: "direct main" + description: + name: url_launcher + sha256: f6a7e5c4835bb4e3026a04793a4199ca2d14c739ec378fdfe23fc8075d0439f8 + url: "https://pub.dev" + source: hosted + version: "6.3.2" + url_launcher_android: + dependency: transitive + description: + name: url_launcher_android + sha256: "69ee86740f2847b9a4ba6cffa74ed12ce500bbe2b07f3dc1e643439da60637b7" + url: "https://pub.dev" + source: hosted + version: "6.3.18" + url_launcher_ios: + dependency: transitive + description: + name: url_launcher_ios + sha256: d80b3f567a617cb923546034cc94bfe44eb15f989fe670b37f26abdb9d939cb7 + url: "https://pub.dev" + source: hosted + version: "6.3.4" + url_launcher_linux: + dependency: transitive + description: + name: url_launcher_linux + sha256: "4e9ba368772369e3e08f231d2301b4ef72b9ff87c31192ef471b380ef29a4935" + url: "https://pub.dev" + source: hosted + version: "3.2.1" + url_launcher_macos: + dependency: transitive + description: + name: url_launcher_macos + sha256: c043a77d6600ac9c38300567f33ef12b0ef4f4783a2c1f00231d2b1941fea13f + url: "https://pub.dev" + source: hosted + version: "3.2.3" + url_launcher_platform_interface: + dependency: transitive + description: + name: url_launcher_platform_interface + sha256: "552f8a1e663569be95a8190206a38187b531910283c3e982193e4f2733f01029" + url: "https://pub.dev" + source: hosted + version: "2.3.2" + url_launcher_web: + dependency: transitive + description: + name: url_launcher_web + sha256: "4bd2b7b4dc4d4d0b94e5babfffbca8eac1a126c7f3d6ecbc1a11013faa3abba2" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + url_launcher_windows: + dependency: transitive + description: + name: url_launcher_windows + sha256: "3284b6d2ac454cf34f114e1d3319866fdd1e19cdc329999057e44ffe936cfa77" + url: "https://pub.dev" + source: hosted + version: "3.1.4" + uuid: + dependency: transitive + description: + name: uuid + sha256: a11b666489b1954e01d992f3d601b1804a33937b5a8fe677bd26b8a9f96f96e8 + url: "https://pub.dev" + source: hosted + version: "4.5.2" + vector_graphics: + dependency: transitive + description: + name: vector_graphics + sha256: a4f059dc26fc8295b5921376600a194c4ec7d55e72f2fe4c7d2831e103d461e6 + url: "https://pub.dev" + source: hosted + version: "1.1.19" + vector_graphics_codec: + dependency: transitive + description: + name: vector_graphics_codec + sha256: "99fd9fbd34d9f9a32efd7b6a6aae14125d8237b10403b422a6a6dfeac2806146" + url: "https://pub.dev" + source: hosted + version: "1.1.13" + vector_graphics_compiler: + dependency: transitive + description: + name: vector_graphics_compiler + sha256: d354a7ec6931e6047785f4db12a1f61ec3d43b207fc0790f863818543f8ff0dc + url: "https://pub.dev" + source: hosted + version: "1.1.19" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b + url: "https://pub.dev" + source: hosted + version: "2.2.0" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: "0968250880a6c5fe7edc067ed0a13d4bae1577fe2771dcf3010d52c4a9d3ca14" + url: "https://pub.dev" + source: hosted + version: "14.3.1" + watcher: + dependency: transitive + description: + name: watcher + sha256: "592ab6e2892f67760543fb712ff0177f4ec76c031f02f5b4ff8d3fc5eb9fb61a" + url: "https://pub.dev" + source: hosted + version: "1.1.4" + web: + dependency: transitive + description: + name: web + sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a" + url: "https://pub.dev" + source: hosted + version: "1.1.1" + web_socket: + dependency: transitive + description: + name: web_socket + sha256: "34d64019aa8e36bf9842ac014bb5d2f5586ca73df5e4d9bf5c936975cae6982c" + url: "https://pub.dev" + source: hosted + version: "1.0.1" + web_socket_channel: + dependency: "direct main" + description: + name: web_socket_channel + sha256: d645757fb0f4773d602444000a8131ff5d48c9e47adfe9772652dd1a4f2d45c8 + url: "https://pub.dev" + source: hosted + version: "3.0.3" + webview_flutter: + dependency: "direct main" + description: + name: webview_flutter + sha256: c3e4fe614b1c814950ad07186007eff2f2e5dd2935eba7b9a9a1af8e5885f1ba + url: "https://pub.dev" + source: hosted + version: "4.13.0" + webview_flutter_android: + dependency: transitive + description: + name: webview_flutter_android + sha256: "9a25f6b4313978ba1c2cda03a242eea17848174912cfb4d2d8ee84a556f248e3" + url: "https://pub.dev" + source: hosted + version: "4.10.1" + webview_flutter_platform_interface: + dependency: transitive + description: + name: webview_flutter_platform_interface + sha256: "63d26ee3aca7256a83ccb576a50272edd7cfc80573a4305caa98985feb493ee0" + url: "https://pub.dev" + source: hosted + version: "2.14.0" + webview_flutter_wkwebview: + dependency: transitive + description: + name: webview_flutter_wkwebview + sha256: fb46db8216131a3e55bcf44040ca808423539bc6732e7ed34fb6d8044e3d512f + url: "https://pub.dev" + source: hosted + version: "3.23.0" + win32: + dependency: transitive + description: + name: win32 + sha256: "329edf97fdd893e0f1e3b9e88d6a0e627128cc17cc316a8d67fda8f1451178ba" + url: "https://pub.dev" + source: hosted + version: "5.13.0" + xdg_directories: + dependency: transitive + description: + name: xdg_directories + sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + xml: + dependency: transitive + description: + name: xml + sha256: b015a8ad1c488f66851d762d3090a21c600e479dc75e68328c52774040cf9226 + url: "https://pub.dev" + source: hosted + version: "6.5.0" + yaml: + dependency: transitive + description: + name: yaml + sha256: b9da305ac7c39faa3f030eccd175340f968459dae4af175130b3fc47e40d76ce + url: "https://pub.dev" + source: hosted + version: "3.1.3" +sdks: + dart: ">=3.8.0-0 <4.0.0" + flutter: ">=3.29.0" diff --git a/app/pubspec.yaml b/app/pubspec.yaml new file mode 100644 index 0000000..1b9de10 --- /dev/null +++ b/app/pubspec.yaml @@ -0,0 +1,141 @@ +name: votianlt_app +description: "votian LT" +# The following line prevents the package from being accidentally published to +# pub.dev using `flutter pub publish`. This is preferred for private packages. +publish_to: 'none' # Remove this line if you wish to publish to pub.dev + +# The following defines the version and build number for your application. +# A version number is three numbers separated by dots, like 1.2.43 +# followed by an optional build number separated by a +. +# Both the version and the builder number may be overridden in flutter +# build by specifying --build-name and --build-number, respectively. +# In Android, build-name is used as versionName while build-number used as versionCode. +# Read more about Android versioning at https://developer.android.com/studio/publish/versioning +# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion. +# Read more about iOS verclaudsioning at +# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html +# In Windows, build-name is used as the major, minor, and patch parts +# of the product and file versions while build-number is used as the build suffix. +version: 0.9.12+1 + +environment: + sdk: ^3.7.0 + +# Dependencies specify other packages that your package needs in order to work. +# To automatically upgrade your package dependencies to the latest versions +# consider running `flutter pub upgrade --major-versions`. Alternatively, +# dependencies can be manually updated by changing the version numbers below to +# the latest version available on pub.dev. To see which dependencies have newer +# versions available, run `flutter pub outdated`. +dependencies: + flutter: + sdk: flutter + flutter_localizations: + sdk: flutter + + # The following adds the Cupertino Icons font to your application. + # Use with the CupertinoIcons class for iOS style icons. + cupertino_icons: ^1.0.8 + + # WebSocket client for messaging + web_socket_channel: ^3.0.0 + + # URL Launcher for opening external maps/navigation + url_launcher: ^6.3.0 + + # In-app WebView for embedded Google Maps navigation + webview_flutter: ^4.8.0 + + # HTTP client for network requests + http: ^1.1.0 + + # ObjectBox database for local storage + objectbox: ^4.0.3 + objectbox_flutter_libs: any + path: ^1.8.3 + path_provider: ^2.1.5 + + # Camera for photo tasks (Android/iOS/Web) + camera: ^0.10.5+9 + + # File selection (mobile uses file_picker; desktop uses file_selector) + file_picker: ^8.0.6 + file_selector: ^1.0.3 + + # Barcode scanning for mobile platforms + mobile_scanner: ^5.0.0 + + # Signature drawing canvas for capturing signatures + signature: ^5.5.0 + + # Image processing for photo compression/resizing before STOMP send + image: ^4.2.0 + + # Package info for getting version number + package_info_plus: ^8.0.0 + + # Local notifications with sound + flutter_local_notifications: ^18.0.0 + + # GPS location tracking + geolocator: ^13.0.2 + + # HTTP client für LM Studio REST API (Übersetzungen) + # http bereits oben definiert + +dev_dependencies: + flutter_test: + sdk: flutter + + # The "flutter_lints" package below contains a set of recommended lints to + # encourage good coding practices. The lint set provided by the package is + # activated in the `analysis_options.yaml` file located at the root of your + # package. See that file for information about deactivating specific lint + # rules and activating additional ones. + flutter_lints: ^5.0.0 + + # Build runner for ObjectBox code generation + build_runner: ^2.4.0 + objectbox_generator: any + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter packages. +flutter: + + # The following line ensures that the Material Icons font is + # included with your application, so that you can use the icons in + # the material Icons class. + uses-material-design: true + + # To add assets to your application, add an assets section, like this: + # assets: + # - images/a_dot_burr.jpeg + # - images/a_dot_ham.jpeg + + # An image asset can refer to one or more resolution-specific "variants", see + # https://flutter.dev/to/resolution-aware-images + + # For details regarding adding assets from package dependencies, see + # https://flutter.dev/to/asset-from-package + + # To add custom fonts to your application, add a fonts section here, + # in this "flutter" section. Each entry in this list should have a + # "family" key with the font family name, and a "fonts" key with a + # list giving the asset and other descriptors for the font. For + # example: + # fonts: + # - family: Schyler + # fonts: + # - asset: fonts/Schyler-Regular.ttf + # - asset: fonts/Schyler-Italic.ttf + # style: italic + # - family: Trajan Pro + # fonts: + # - asset: fonts/TrajanPro.ttf + # - asset: fonts/TrajanPro_Bold.ttf + # weight: 700 + # + # For details regarding fonts from package dependencies, + # see https://flutter.dev/to/font-from-package diff --git a/app/test/models/acknowledgment_message_test.dart b/app/test/models/acknowledgment_message_test.dart new file mode 100644 index 0000000..874af07 --- /dev/null +++ b/app/test/models/acknowledgment_message_test.dart @@ -0,0 +1,201 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:votianlt_app/models/acknowledgment_message.dart'; + +void main() { + group('AcknowledgmentMessage', () { + group('fromJson', () { + test('parses all required fields correctly', () { + final json = { + 'messageId': 'msg-123', + 'status': 'RECEIVED', + 'timestamp': '2024-01-15T10:30:00.000Z', + }; + + final ack = AcknowledgmentMessage.fromJson(json); + + expect(ack.messageId, 'msg-123'); + expect(ack.status, AcknowledgmentStatus.received); + expect(ack.timestamp, DateTime.utc(2024, 1, 15, 10, 30, 0)); + expect(ack.errorMessage, isNull); + }); + + test('parses errorMessage when present', () { + final json = { + 'messageId': 'msg-123', + 'status': 'FAILED', + 'timestamp': '2024-01-15T10:30:00.000Z', + 'errorMessage': 'Connection timeout', + }; + + final ack = AcknowledgmentMessage.fromJson(json); + + expect(ack.status, AcknowledgmentStatus.failed); + expect(ack.errorMessage, 'Connection timeout'); + }); + + test('parses PROCESSED status', () { + final json = { + 'messageId': 'msg-123', + 'status': 'PROCESSED', + 'timestamp': '2024-01-15T10:30:00.000Z', + }; + + final ack = AcknowledgmentMessage.fromJson(json); + + expect(ack.status, AcknowledgmentStatus.processed); + }); + }); + + group('toJson', () { + test('serializes all fields correctly', () { + final ack = AcknowledgmentMessage( + messageId: 'msg-123', + status: AcknowledgmentStatus.received, + timestamp: DateTime.utc(2024, 1, 15, 10, 30, 0), + ); + + final json = ack.toJson(); + + expect(json['messageId'], 'msg-123'); + expect(json['status'], 'RECEIVED'); + expect(json['timestamp'], '2024-01-15T10:30:00.000Z'); + expect(json.containsKey('errorMessage'), false); + }); + + test('includes errorMessage when present', () { + final ack = AcknowledgmentMessage( + messageId: 'msg-123', + status: AcknowledgmentStatus.failed, + timestamp: DateTime.utc(2024, 1, 15, 10, 30, 0), + errorMessage: 'Processing error', + ); + + final json = ack.toJson(); + + expect(json['errorMessage'], 'Processing error'); + }); + }); + + group('fromJson/toJson roundtrip', () { + test('preserves all data through serialization', () { + final original = AcknowledgmentMessage( + messageId: 'roundtrip-msg', + status: AcknowledgmentStatus.processed, + timestamp: DateTime.utc(2024, 1, 15, 10, 30, 0), + ); + + final json = original.toJson(); + final restored = AcknowledgmentMessage.fromJson(json); + + expect(restored.messageId, original.messageId); + expect(restored.status, original.status); + expect(restored.timestamp, original.timestamp); + expect(restored.errorMessage, original.errorMessage); + }); + + test('preserves errorMessage through serialization', () { + final original = AcknowledgmentMessage( + messageId: 'error-msg', + status: AcknowledgmentStatus.failed, + timestamp: DateTime.utc(2024, 1, 15, 10, 30, 0), + errorMessage: 'Something went wrong', + ); + + final json = original.toJson(); + final restored = AcknowledgmentMessage.fromJson(json); + + expect(restored.errorMessage, 'Something went wrong'); + }); + }); + + group('toString', () { + test('returns readable representation', () { + final ack = AcknowledgmentMessage( + messageId: 'msg-123', + status: AcknowledgmentStatus.received, + timestamp: DateTime.utc(2024, 1, 15, 10, 30, 0), + ); + + final str = ack.toString(); + + expect(str, contains('msg-123')); + expect(str, contains('RECEIVED')); + }); + }); + }); + + group('AcknowledgmentStatus', () { + group('fromString', () { + test('parses RECEIVED', () { + expect( + AcknowledgmentStatus.fromString('RECEIVED'), + AcknowledgmentStatus.received, + ); + }); + + test('parses PROCESSED', () { + expect( + AcknowledgmentStatus.fromString('PROCESSED'), + AcknowledgmentStatus.processed, + ); + }); + + test('parses FAILED', () { + expect( + AcknowledgmentStatus.fromString('FAILED'), + AcknowledgmentStatus.failed, + ); + }); + + test('handles lowercase input', () { + expect( + AcknowledgmentStatus.fromString('received'), + AcknowledgmentStatus.received, + ); + expect( + AcknowledgmentStatus.fromString('processed'), + AcknowledgmentStatus.processed, + ); + expect( + AcknowledgmentStatus.fromString('failed'), + AcknowledgmentStatus.failed, + ); + }); + + test('defaults to received for unknown values', () { + expect( + AcknowledgmentStatus.fromString('UNKNOWN'), + AcknowledgmentStatus.received, + ); + expect( + AcknowledgmentStatus.fromString(''), + AcknowledgmentStatus.received, + ); + }); + }); + + group('toString', () { + test('returns RECEIVED for received', () { + expect(AcknowledgmentStatus.received.toString(), 'RECEIVED'); + }); + + test('returns PROCESSED for processed', () { + expect(AcknowledgmentStatus.processed.toString(), 'PROCESSED'); + }); + + test('returns FAILED for failed', () { + expect(AcknowledgmentStatus.failed.toString(), 'FAILED'); + }); + }); + + group('fromString/toString roundtrip', () { + test('preserves status through conversion', () { + for (final status in AcknowledgmentStatus.values) { + final str = status.toString(); + final restored = AcknowledgmentStatus.fromString(str); + expect(restored, status); + } + }); + }); + }); +} diff --git a/app/test/models/job_parsing_test.dart b/app/test/models/job_parsing_test.dart new file mode 100644 index 0000000..a69ee00 --- /dev/null +++ b/app/test/models/job_parsing_test.dart @@ -0,0 +1,883 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:votianlt_app/models/job.dart'; +import 'package:votianlt_app/models/cargo_item.dart'; +import 'package:votianlt_app/models/task.dart'; +import 'package:votianlt_app/models/tasks/confirmation_task.dart'; +import 'package:votianlt_app/models/tasks/photo_task.dart'; +import 'package:votianlt_app/models/tasks/signature_task.dart'; +import 'package:votianlt_app/models/tasks/barcode_task.dart'; +import 'package:votianlt_app/models/tasks/todolist_task.dart'; +import 'package:votianlt_app/models/tasks/comment_task.dart'; +import 'package:votianlt_app/models/tasks/generic_task.dart'; + +/// Test data based on job_json.md documentation from +/// https://www.appcreation.de/download/job_json.md +void main() { + // Complete job JSON according to documentation + final Map completeJobJson = { + 'job': { + 'id': {'timestamp': 1705312200, '\$oid': '65a4b5c8d4e5f6a7b8c9d0e1'}, + 'jobNumber': 'JOB-2024-001', + 'status': 'ASSIGNED', + 'createdAt': '2024-01-15T10:30:00.000Z', + 'updatedAt': '2024-01-15T14:45:00.000Z', + 'createdBy': 'admin@example.com', + 'customerSelection': 'Kunde ABC GmbH', + 'pickupCompany': 'Absender GmbH', + 'pickupSalutation': 'Herr', + 'pickupFirstName': 'Max', + 'pickupLastName': 'Mustermann', + 'pickupPhone': '+49 123 456789', + 'pickupStreet': 'Hauptstraße', + 'pickupHouseNumber': '42', + 'pickupAddressAddition': 'Hinterhaus', + 'pickupZip': '10115', + 'pickupCity': 'Berlin', + 'deliveryCompany': 'Empfänger AG', + 'deliverySalutation': 'Frau', + 'deliveryFirstName': 'Erika', + 'deliveryLastName': 'Musterfrau', + 'deliveryPhone': '+49 987 654321', + 'deliveryStreet': 'Nebenstraße', + 'deliveryHouseNumber': '7a', + 'deliveryAddressAddition': null, + 'deliveryZip': '80331', + 'deliveryCity': 'München', + 'digitalProcessing': true, + 'appUser': 'driver@example.com', + 'pickupDate': '2024-01-16', + 'deliveryDate': '2024-01-17', + 'remark': 'Bitte vorsichtig behandeln', + 'price': 149.99, + 'draft': false, + }, + 'cargoItems': [ + { + 'id': {'timestamp': 1705312201}, + 'jobId': {'timestamp': 1705312200}, + 'description': 'Palette mit Elektronik', + 'quantity': 2, + 'weightKg': 150.5, + 'lengthMm': 1200.0, + 'widthMm': 800.0, + 'heightMm': 1000.0, + }, + { + 'id': {'timestamp': 1705312202}, + 'jobId': {'timestamp': 1705312200}, + 'description': 'Karton mit Dokumenten', + 'quantity': 5, + 'weightKg': 12.0, + 'lengthMm': 400.0, + 'widthMm': 300.0, + 'heightMm': 200.0, + }, + ], + 'tasks': [ + { + 'id': {'timestamp': 1705312210}, + 'jobId': {'timestamp': 1705312200}, + 'completed': false, + 'completedAt': null, + 'completedBy': null, + 'taskOrder': 1, + 'taskSpecificData': { + 'taskType': 'CONFIRMATION', + 'buttonText': 'Abholung bestätigen', + }, + }, + { + 'id': {'timestamp': 1705312211}, + 'jobId': {'timestamp': 1705312200}, + 'completed': true, + 'completedAt': '2024-01-16T09:15:00.000Z', + 'completedBy': 'driver@example.com', + 'taskOrder': 2, + 'taskSpecificData': {'taskType': 'SIGNATURE'}, + }, + { + 'id': {'timestamp': 1705312212}, + 'jobId': {'timestamp': 1705312200}, + 'completed': false, + 'completedAt': null, + 'completedBy': null, + 'taskOrder': 3, + 'taskSpecificData': { + 'taskType': 'PHOTO', + 'minPhotoCount': 2, + 'maxPhotoCount': 10, + }, + }, + { + 'id': {'timestamp': 1705312213}, + 'jobId': {'timestamp': 1705312200}, + 'completed': false, + 'completedAt': null, + 'completedBy': null, + 'taskOrder': 4, + 'taskSpecificData': { + 'taskType': 'BARCODE', + 'minBarcodeCount': 1, + 'maxBarcodeCount': 5, + }, + }, + { + 'id': {'timestamp': 1705312214}, + 'jobId': {'timestamp': 1705312200}, + 'completed': false, + 'completedAt': null, + 'completedBy': null, + 'taskOrder': 5, + 'taskSpecificData': { + 'taskType': 'TODOLIST', + 'todoItems': [ + 'Ladung sichern', + 'Dokumente prüfen', + 'Unterschrift einholen', + ], + }, + }, + { + 'id': {'timestamp': 1705312215}, + 'jobId': {'timestamp': 1705312200}, + 'completed': false, + 'completedAt': null, + 'completedBy': null, + 'taskOrder': 6, + 'taskSpecificData': { + 'taskType': 'COMMENT', + 'commentText': '', + 'required': true, + }, + }, + ], + }; + + group('Job Parsing', () { + late Job job; + + setUp(() { + job = Job.fromJson(completeJobJson); + }); + + test('parses job basic fields correctly', () { + expect(job.id, '1705312200'); + expect(job.jobNumber, 'JOB-2024-001'); + expect(job.status, 'ASSIGNED'); + expect(job.createdBy, 'admin@example.com'); + expect(job.customerSelection, 'Kunde ABC GmbH'); + expect(job.appUser, 'driver@example.com'); + expect(job.remark, 'Bitte vorsichtig behandeln'); + }); + + test('parses pickup address correctly', () { + expect(job.pickupCompany, 'Absender GmbH'); + expect(job.pickupSalutation, 'Herr'); + expect(job.pickupFirstName, 'Max'); + expect(job.pickupLastName, 'Mustermann'); + expect(job.pickupPhone, '+49 123 456789'); + expect(job.pickupStreet, 'Hauptstraße'); + expect(job.pickupHouseNumber, '42'); + expect(job.pickupAddressAddition, 'Hinterhaus'); + expect(job.pickupZip, '10115'); + expect(job.pickupCity, 'Berlin'); + }); + + test('parses delivery address correctly', () { + expect(job.deliveryCompany, 'Empfänger AG'); + expect(job.deliverySalutation, 'Frau'); + expect(job.deliveryFirstName, 'Erika'); + expect(job.deliveryLastName, 'Musterfrau'); + expect(job.deliveryPhone, '+49 987 654321'); + expect(job.deliveryStreet, 'Nebenstraße'); + expect(job.deliveryHouseNumber, '7a'); + expect(job.deliveryAddressAddition, ''); + expect(job.deliveryZip, '80331'); + expect(job.deliveryCity, 'München'); + }); + + test('parses date strings correctly', () { + expect(job.pickupDate, '2024-01-16'); + expect(job.deliveryDate, '2024-01-17'); + }); + + test('parses DateTime from ISO string', () { + expect(job.createdAt, DateTime.utc(2024, 1, 15, 10, 30, 0)); + expect(job.updatedAt, DateTime.utc(2024, 1, 15, 14, 45, 0)); + }); + + test('parses DateTime from array format', () { + final jsonWithArrayDate = Map.from(completeJobJson); + final jobData = Map.from(jsonWithArrayDate['job']); + jobData['createdAt'] = [2024, 1, 15, 10, 30, 0, 0]; + jobData['updatedAt'] = [2024, 1, 15, 14, 45, 0, 500000000]; + jsonWithArrayDate['job'] = jobData; + + final jobWithArrayDate = Job.fromJson(jsonWithArrayDate); + + expect(jobWithArrayDate.createdAt, DateTime(2024, 1, 15, 10, 30, 0, 0)); + expect(jobWithArrayDate.updatedAt.year, 2024); + expect(jobWithArrayDate.updatedAt.month, 1); + expect(jobWithArrayDate.updatedAt.day, 15); + }); + + test('parses price as double', () { + expect(job.price, 149.99); + }); + + test('parses boolean fields correctly', () { + expect(job.digitalProcessing, true); + expect(job.draft, false); + }); + + test('parses cargoItems array', () { + expect(job.cargoItems.length, 2); + }); + + test('parses tasks array', () { + expect(job.tasks.length, 6); + }); + + test('parses delivery stations and flattens station tasks', () { + final jsonWithStations = { + 'job': { + 'id': 'station-job-1', + 'jobNumber': 'JOB-STATION-001', + 'status': 'CREATED', + 'deliveryCompany': 'Legacy Delivery', + 'deliveryStreet': 'Legacy Street', + 'deliveryHouseNumber': '1', + 'deliveryZip': '12345', + 'deliveryCity': 'Legacy City', + 'deliveryCitiesDisplay': 'Boostedt -> Geesthacht', + 'firstDeliveryCity': 'Boostedt', + 'lastDeliveryCity': 'Geesthacht', + 'deliveryStations': [ + { + 'stationOrder': 0, + 'company': 'Volker Hinst', + 'street': 'Vossbarg', + 'houseNumber': '24', + 'zip': '24893', + 'city': 'Boostedt', + 'tasks': [ + { + 'id': 'station-task-1', + 'jobId': 'station-job-1', + 'taskOrder': 0, + 'description': 'Erste Station', + 'displayName': 'Bestätigung', + 'taskSpecificData': { + 'taskType': 'CONFIRMATION', + 'buttonText': 'Blubb', + }, + }, + ], + }, + { + 'stationOrder': 1, + 'company': 'Timm GmbH', + 'street': 'Gerhart-Hauptmann-Weg', + 'houseNumber': '14', + 'zip': '21502', + 'city': 'Geesthacht', + 'tasks': [ + { + 'id': 'station-task-2', + 'jobId': 'station-job-1', + 'taskOrder': 0, + 'description': 'Zweite Station', + 'displayName': 'Bestätigung', + 'taskSpecificData': { + 'taskType': 'CONFIRMATION', + 'buttonText': 'Blubb', + }, + }, + ], + }, + ], + }, + 'cargoItems': [], + 'tasks': [ + { + 'id': 'legacy-task', + 'jobId': 'station-job-1', + 'taskOrder': 0, + 'description': 'Legacy', + 'taskSpecificData': { + 'taskType': 'CONFIRMATION', + 'buttonText': 'Legacy', + }, + }, + ], + }; + + final jobWithStations = Job.fromJson(jsonWithStations); + + expect(jobWithStations.deliveryStations.length, 2); + expect(jobWithStations.tasks.length, 2); + expect(jobWithStations.tasks[0].stationOrder, 0); + expect(jobWithStations.tasks[1].stationOrder, 1); + expect( + jobWithStations.deliveryStations[0].tasks.first.id, + 'station-task-1', + ); + expect(jobWithStations.deliveryCitiesDisplay, 'Boostedt -> Geesthacht'); + }); + + test('extracts ID from Map object with timestamp', () { + expect(job.id, '1705312200'); + }); + + test('extracts ID from Map object with \$oid fallback', () { + final jsonWithOidOnly = { + 'job': { + 'id': {'\$oid': '65a4b5c8d4e5f6a7b8c9d0e1'}, + 'jobNumber': 'JOB-TEST', + 'status': 'CREATED', + }, + 'cargoItems': [], + 'tasks': [], + }; + + final jobWithOid = Job.fromJson(jsonWithOidOnly); + expect(jobWithOid.id, '65a4b5c8d4e5f6a7b8c9d0e1'); + }); + + test('handles flat JSON structure (without nested job object)', () { + final flatJson = { + 'id': 'flat-job-id-123', + 'jobNumber': 'JOB-FLAT-001', + 'status': 'CREATED', + 'createdAt': '2024-01-15T10:30:00.000Z', + 'updatedAt': '2024-01-15T10:30:00.000Z', + 'createdBy': 'test@test.de', + 'customerSelection': 'Test Kunde', + 'pickupCompany': 'Test Firma', + 'pickupFirstName': 'Test', + 'pickupLastName': 'User', + 'pickupPhone': '12345', + 'pickupStreet': 'Teststr', + 'pickupHouseNumber': '1', + 'pickupAddressAddition': '', + 'pickupZip': '12345', + 'pickupCity': 'Teststadt', + 'deliveryCompany': 'Ziel Firma', + 'deliveryFirstName': 'Ziel', + 'deliveryLastName': 'Person', + 'deliveryPhone': '54321', + 'deliveryStreet': 'Zielstr', + 'deliveryHouseNumber': '2', + 'deliveryAddressAddition': '', + 'deliveryZip': '54321', + 'deliveryCity': 'Zielstadt', + 'digitalProcessing': false, + 'appUser': 'user@test.de', + 'pickupDate': '2024-01-20', + 'deliveryDate': '2024-01-21', + 'remark': '', + 'price': 0.0, + 'draft': true, + }; + + final flatJob = Job.fromJson(flatJson); + + expect(flatJob.id, 'flat-job-id-123'); + expect(flatJob.jobNumber, 'JOB-FLAT-001'); + expect(flatJob.draft, true); + }); + }); + + group('CargoItem Parsing', () { + late Job job; + + setUp(() { + job = Job.fromJson(completeJobJson); + }); + + test('parses CargoItem fields correctly', () { + final cargoItem = job.cargoItems[0]; + + expect(cargoItem.id, '1705312201'); + expect(cargoItem.jobId, '1705312200'); + expect(cargoItem.description, 'Palette mit Elektronik'); + expect(cargoItem.quantity, 2); + expect(cargoItem.weightKg, 150.5); + expect(cargoItem.lengthCm, 1200.0); + expect(cargoItem.widthCm, 800.0); + expect(cargoItem.heightCm, 1000.0); + }); + + test('parses multiple CargoItems', () { + expect(job.cargoItems.length, 2); + expect(job.cargoItems[0].description, 'Palette mit Elektronik'); + expect(job.cargoItems[1].description, 'Karton mit Dokumenten'); + }); + + test('extracts CargoItem ID from Map object', () { + expect(job.cargoItems[0].id, '1705312201'); + expect(job.cargoItems[1].id, '1705312202'); + }); + + test('handles CargoItem with simple string ID', () { + final cargoJson = { + 'id': 'simple-string-id', + 'jobId': 'simple-job-id', + 'description': 'Test Item', + 'quantity': 1, + 'weightKg': 10.0, + 'lengthMm': 100.0, + 'widthMm': 100.0, + 'heightMm': 100.0, + }; + + final cargoItem = CargoItem.fromJson(cargoJson); + + expect(cargoItem.id, 'simple-string-id'); + expect(cargoItem.jobId, 'simple-job-id'); + }); + }); + + group('Task Parsing', () { + late Job job; + + setUp(() { + job = Job.fromJson(completeJobJson); + }); + + test('creates ConfirmationTask with buttonText', () { + final task = job.tasks[0]; + + expect(task, isA()); + final confirmationTask = task as ConfirmationTask; + expect(confirmationTask.taskOrder, 1); + expect(confirmationTask.buttonText, 'Abholung bestätigen'); + expect(confirmationTask.completed, false); + }); + + test('creates SignatureTask', () { + final task = job.tasks[1]; + + expect(task, isA()); + expect(task.taskOrder, 2); + expect(task.completed, true); + expect(task.completedBy, 'driver@example.com'); + }); + + test('creates PhotoTask with min/maxPhotoCount', () { + final task = job.tasks[2]; + + expect(task, isA()); + final photoTask = task as PhotoTask; + expect(photoTask.taskOrder, 3); + expect(photoTask.minPhotoCount, 2); + expect(photoTask.maxPhotoCount, 10); + }); + + test('creates BarcodeTask with min/maxBarcodeCount', () { + final task = job.tasks[3]; + + expect(task, isA()); + final barcodeTask = task as BarcodeTask; + expect(barcodeTask.taskOrder, 4); + expect(barcodeTask.minBarcodeCount, 1); + expect(barcodeTask.maxBarcodeCount, 5); + }); + + test('creates TodoListTask with todoItems', () { + final task = job.tasks[4]; + + expect(task, isA()); + final todoListTask = task as TodoListTask; + expect(todoListTask.taskOrder, 5); + expect(todoListTask.todoItems.length, 3); + expect(todoListTask.todoItems[0], 'Ladung sichern'); + expect(todoListTask.todoItems[1], 'Dokumente prüfen'); + expect(todoListTask.todoItems[2], 'Unterschrift einholen'); + }); + + test('creates CommentTask with commentText and required', () { + final task = job.tasks[5]; + + expect(task, isA()); + final commentTask = task as CommentTask; + expect(commentTask.taskOrder, 6); + expect(commentTask.commentText, ''); + expect(commentTask.required, true); + }); + + test('falls back to GenericTask for unknown task type', () { + final unknownTaskJson = { + 'id': {'timestamp': 1705312299}, + 'jobId': {'timestamp': 1705312200}, + 'completed': false, + 'taskOrder': 99, + 'taskSpecificData': {'taskType': 'UNKNOWN_TYPE'}, + }; + + final task = Task.fromJson(unknownTaskJson); + + expect(task, isA()); + }); + + test('falls back to GenericTask when taskType is missing', () { + final noTypeTaskJson = { + 'id': {'timestamp': 1705312298}, + 'jobId': {'timestamp': 1705312200}, + 'completed': false, + 'taskOrder': 98, + 'taskSpecificData': {}, + }; + + final task = Task.fromJson(noTypeTaskJson); + + expect(task, isA()); + }); + + test('parses completedAt from ISO string', () { + final task = job.tasks[1]; + + expect(task.completedAt, DateTime.utc(2024, 1, 16, 9, 15, 0)); + }); + + test('parses completedAt from array format', () { + final taskJsonWithArrayDate = { + 'id': {'timestamp': 1705312220}, + 'jobId': {'timestamp': 1705312200}, + 'completed': true, + 'completedAt': [2024, 1, 16, 9, 15, 0, 0], + 'completedBy': 'driver@example.com', + 'taskOrder': 10, + 'taskSpecificData': {'taskType': 'SIGNATURE'}, + }; + + final task = Task.fromJson(taskJsonWithArrayDate); + + expect(task.completedAt, DateTime(2024, 1, 16, 9, 15, 0, 0)); + }); + + test('extracts task ID from Map object', () { + final task = job.tasks[0]; + expect(task.id, '1705312210'); + }); + + test('extracts task jobId from Map object', () { + final task = job.tasks[0]; + expect(task.jobId, '1705312200'); + }); + }); + + group('Task Defaults', () { + test('ConfirmationTask uses default buttonText', () { + final taskJson = { + 'id': 'task-1', + 'jobId': 'job-1', + 'taskOrder': 1, + 'taskSpecificData': {'taskType': 'CONFIRMATION'}, + }; + + final task = Task.fromJson(taskJson) as ConfirmationTask; + expect(task.buttonText, 'Bestätigen'); + }); + + test('PhotoTask uses default min/max counts', () { + final taskJson = { + 'id': 'task-2', + 'jobId': 'job-1', + 'taskOrder': 2, + 'taskSpecificData': {'taskType': 'PHOTO'}, + }; + + final task = Task.fromJson(taskJson) as PhotoTask; + expect(task.minPhotoCount, 1); + expect(task.maxPhotoCount, 5); + }); + + test('BarcodeTask uses default min/max counts', () { + final taskJson = { + 'id': 'task-3', + 'jobId': 'job-1', + 'taskOrder': 3, + 'taskSpecificData': {'taskType': 'BARCODE'}, + }; + + final task = Task.fromJson(taskJson) as BarcodeTask; + expect(task.minBarcodeCount, 1); + expect(task.maxBarcodeCount, 10); + }); + + test('CommentTask uses default values', () { + final taskJson = { + 'id': 'task-4', + 'jobId': 'job-1', + 'taskOrder': 4, + 'taskSpecificData': {'taskType': 'COMMENT'}, + }; + + final task = Task.fromJson(taskJson) as CommentTask; + expect(task.commentText, ''); + expect(task.required, false); + }); + + test('TodoListTask handles empty todoItems', () { + final taskJson = { + 'id': 'task-5', + 'jobId': 'job-1', + 'taskOrder': 5, + 'taskSpecificData': {'taskType': 'TODOLIST'}, + }; + + final task = Task.fromJson(taskJson) as TodoListTask; + expect(task.todoItems, isEmpty); + }); + }); + + group('Edge Cases', () { + test('handles empty cargoItems array', () { + final jsonWithEmptyCargoItems = Map.from( + completeJobJson, + ); + jsonWithEmptyCargoItems['cargoItems'] = []; + + final job = Job.fromJson(jsonWithEmptyCargoItems); + + expect(job.cargoItems, isEmpty); + }); + + test('handles empty tasks array', () { + final jsonWithEmptyTasks = Map.from(completeJobJson); + jsonWithEmptyTasks['tasks'] = []; + + final job = Job.fromJson(jsonWithEmptyTasks); + + expect(job.tasks, isEmpty); + }); + + test('handles missing optional fields with defaults', () { + final minimalJson = { + 'job': {'jobNumber': 'JOB-MIN-001'}, + 'cargoItems': [], + 'tasks': [], + }; + + final job = Job.fromJson(minimalJson); + + expect(job.jobNumber, 'JOB-MIN-001'); + expect(job.status, 'UNKNOWN'); + expect(job.pickupCompany, ''); + expect(job.deliveryCompany, ''); + expect(job.digitalProcessing, false); + expect(job.price, 0.0); + expect(job.draft, false); + }); + + test('handles null values in optional fields', () { + final jsonWithNulls = { + 'job': { + 'id': 'null-test-id', + 'jobNumber': 'JOB-NULL-001', + 'status': 'CREATED', + 'pickupSalutation': null, + 'deliverySalutation': null, + 'pickupAddressAddition': null, + 'deliveryAddressAddition': null, + 'remark': null, + }, + 'cargoItems': [], + 'tasks': [], + }; + + final job = Job.fromJson(jsonWithNulls); + + expect(job.pickupSalutation, isNull); + expect(job.deliverySalutation, isNull); + expect(job.pickupAddressAddition, ''); + expect(job.deliveryAddressAddition, ''); + expect(job.remark, ''); + }); + + test('generates ID from jobNumber when ID is missing', () { + final jsonWithoutId = { + 'job': {'jobNumber': 'JOB-NOID-001'}, + 'cargoItems': [], + 'tasks': [], + }; + + final job = Job.fromJson(jsonWithoutId); + + expect(job.id, 'jobnum:JOB-NOID-001'); + }); + }); + + group('Roundtrip (fromJson -> toJson -> fromJson)', () { + test('Job preserves data through serialization', () { + final original = Job.fromJson(completeJobJson); + final json = original.toJson(); + final restored = Job.fromJson(json); + + expect(restored.id, original.id); + expect(restored.jobNumber, original.jobNumber); + expect(restored.status, original.status); + expect(restored.pickupCompany, original.pickupCompany); + expect(restored.pickupCity, original.pickupCity); + expect(restored.deliveryCompany, original.deliveryCompany); + expect(restored.deliveryCity, original.deliveryCity); + expect(restored.price, original.price); + expect(restored.digitalProcessing, original.digitalProcessing); + }); + + test('CargoItem preserves data through serialization', () { + final original = Job.fromJson(completeJobJson).cargoItems[0]; + final json = original.toJson(); + final restored = CargoItem.fromJson(json); + + expect(restored.id, original.id); + expect(restored.jobId, original.jobId); + expect(restored.description, original.description); + expect(restored.quantity, original.quantity); + expect(restored.weightKg, original.weightKg); + expect(restored.lengthCm, original.lengthCm); + }); + + test('ConfirmationTask preserves data through serialization', () { + final original = + Job.fromJson(completeJobJson).tasks[0] as ConfirmationTask; + final json = original.toJson(); + final restored = Task.fromJson(json) as ConfirmationTask; + + expect(restored.id, original.id); + expect(restored.jobId, original.jobId); + expect(restored.buttonText, original.buttonText); + expect(restored.taskOrder, original.taskOrder); + }); + + test('PhotoTask preserves data through serialization', () { + final original = Job.fromJson(completeJobJson).tasks[2] as PhotoTask; + final json = original.toJson(); + final restored = Task.fromJson(json) as PhotoTask; + + expect(restored.minPhotoCount, original.minPhotoCount); + expect(restored.maxPhotoCount, original.maxPhotoCount); + }); + + test('TodoListTask preserves data through serialization', () { + final original = Job.fromJson(completeJobJson).tasks[4] as TodoListTask; + final json = original.toJson(); + final restored = Task.fromJson(json) as TodoListTask; + + expect(restored.todoItems, original.todoItems); + }); + + test('CommentTask preserves data through serialization', () { + final original = Job.fromJson(completeJobJson).tasks[5] as CommentTask; + final json = original.toJson(); + final restored = Task.fromJson(json) as CommentTask; + + expect(restored.commentText, original.commentText); + expect(restored.required, original.required); + }); + }); + + group('Job Status', () { + test('statusDisplayText returns German text for known statuses', () { + final statuses = { + 'CREATED': 'Erstellt', + 'PENDING': 'Wartend', + 'ASSIGNED': 'Zugewiesen', + 'IN_PROGRESS': 'In Bearbeitung', + 'STARTED': 'In Bearbeitung', + 'COMPLETED': 'Abgeschlossen', + 'DONE': 'Abgeschlossen', + 'CANCELLED': 'Abgebrochen', + 'FAILED': 'Fehlgeschlagen', + }; + + for (final entry in statuses.entries) { + final json = { + 'job': { + 'id': 'status-test', + 'jobNumber': 'JOB-STATUS', + 'status': entry.key, + }, + 'cargoItems': [], + 'tasks': [], + }; + + final job = Job.fromJson(json); + expect( + job.statusDisplayText, + entry.value, + reason: 'Status ${entry.key} should display as ${entry.value}', + ); + } + }); + + test('statusColor returns correct color for statuses', () { + final statusColors = { + 'CREATED': 'orange', + 'ASSIGNED': 'orange', + 'IN_PROGRESS': 'blue', + 'COMPLETED': 'green', + 'CANCELLED': 'red', + }; + + for (final entry in statusColors.entries) { + final json = { + 'job': { + 'id': 'color-test', + 'jobNumber': 'JOB-COLOR', + 'status': entry.key, + }, + 'cargoItems': [], + 'tasks': [], + }; + + final job = Job.fromJson(json); + expect( + job.statusColor, + entry.value, + reason: 'Status ${entry.key} should have color ${entry.value}', + ); + } + }); + }); + + group('Job normalized()', () { + test('trims string fields', () { + final json = { + 'job': { + 'id': 'normalize-test', + 'jobNumber': ' JOB-TRIM ', + 'status': ' ASSIGNED ', + 'pickupCompany': ' Test Company ', + 'pickupCity': ' Berlin ', + }, + 'cargoItems': [], + 'tasks': [], + }; + + final job = Job.fromJson(json).normalized(); + + expect(job.jobNumber, 'JOB-TRIM'); + expect(job.status, 'ASSIGNED'); + expect(job.pickupCompany, 'Test Company'); + expect(job.pickupCity, 'Berlin'); + }); + + test('converts null strings to empty strings', () { + final json = { + 'job': { + 'id': 'null-normalize-test', + 'jobNumber': 'JOB-NULL', + 'pickupSalutation': null, + }, + 'cargoItems': [], + 'tasks': [], + }; + + final job = Job.fromJson(json).normalized(); + + expect(job.pickupSalutation, ''); + }); + }); +} diff --git a/app/test/models/message_envelope_test.dart b/app/test/models/message_envelope_test.dart new file mode 100644 index 0000000..aed4915 --- /dev/null +++ b/app/test/models/message_envelope_test.dart @@ -0,0 +1,190 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:votianlt_app/models/message_envelope.dart'; + +void main() { + group('MessageEnvelope', () { + group('fromJson', () { + test('parses all required fields correctly', () { + final json = { + 'messageId': 'test-uuid-123', + 'timestamp': '2024-01-15T10:30:00.000Z', + 'topic': '/server/user123/message', + 'payload': {'key': 'value'}, + }; + + final envelope = MessageEnvelope.fromJson(json); + + expect(envelope.messageId, 'test-uuid-123'); + expect(envelope.timestamp, DateTime.utc(2024, 1, 15, 10, 30, 0)); + expect(envelope.topic, '/server/user123/message'); + expect(envelope.payload, {'key': 'value'}); + expect(envelope.requiresAck, true); // default + expect(envelope.retryCount, 0); // default + expect(envelope.expiresAt, isNull); + }); + + test('parses optional fields when present', () { + final json = { + 'messageId': 'test-uuid-456', + 'timestamp': '2024-01-15T10:30:00.000Z', + 'topic': '/server/user123/message', + 'payload': {'data': 123}, + 'requiresAck': false, + 'retryCount': 3, + 'expiresAt': '2024-01-15T11:30:00.000Z', + }; + + final envelope = MessageEnvelope.fromJson(json); + + expect(envelope.requiresAck, false); + expect(envelope.retryCount, 3); + expect(envelope.expiresAt, DateTime.utc(2024, 1, 15, 11, 30, 0)); + }); + + test('handles list payload', () { + final json = { + 'messageId': 'test-uuid-789', + 'timestamp': '2024-01-15T10:30:00.000Z', + 'topic': '/server/user123/jobs', + 'payload': [ + {'id': '1'}, + {'id': '2'} + ], + }; + + final envelope = MessageEnvelope.fromJson(json); + + expect(envelope.payload, isList); + expect(envelope.payload.length, 2); + }); + + test('handles null payload', () { + final json = { + 'messageId': 'test-uuid-null', + 'timestamp': '2024-01-15T10:30:00.000Z', + 'topic': '/server/user123/ping', + 'payload': null, + }; + + final envelope = MessageEnvelope.fromJson(json); + + expect(envelope.payload, isNull); + }); + }); + + group('toJson', () { + test('serializes all fields correctly', () { + final envelope = MessageEnvelope( + messageId: 'test-uuid-123', + timestamp: DateTime.utc(2024, 1, 15, 10, 30, 0), + topic: '/server/user123/message', + payload: {'key': 'value'}, + requiresAck: true, + retryCount: 2, + expiresAt: DateTime.utc(2024, 1, 15, 11, 30, 0), + ); + + final json = envelope.toJson(); + + expect(json['messageId'], 'test-uuid-123'); + expect(json['timestamp'], '2024-01-15T10:30:00.000Z'); + expect(json['topic'], '/server/user123/message'); + expect(json['payload'], {'key': 'value'}); + expect(json['requiresAck'], true); + expect(json['retryCount'], 2); + expect(json['expiresAt'], '2024-01-15T11:30:00.000Z'); + }); + + test('omits expiresAt when null', () { + final envelope = MessageEnvelope( + messageId: 'test-uuid-123', + timestamp: DateTime.utc(2024, 1, 15, 10, 30, 0), + topic: '/server/user123/message', + payload: {'key': 'value'}, + ); + + final json = envelope.toJson(); + + expect(json.containsKey('expiresAt'), false); + }); + }); + + group('fromJson/toJson roundtrip', () { + test('preserves all data through serialization', () { + final original = MessageEnvelope( + messageId: 'roundtrip-uuid', + timestamp: DateTime.utc(2024, 1, 15, 10, 30, 0), + topic: '/server/user123/message', + payload: {'nested': {'key': 'value'}, 'list': [1, 2, 3]}, + requiresAck: false, + retryCount: 5, + expiresAt: DateTime.utc(2024, 1, 16, 10, 30, 0), + ); + + final json = original.toJson(); + final restored = MessageEnvelope.fromJson(json); + + expect(restored.messageId, original.messageId); + expect(restored.timestamp, original.timestamp); + expect(restored.topic, original.topic); + expect(restored.payload, original.payload); + expect(restored.requiresAck, original.requiresAck); + expect(restored.retryCount, original.retryCount); + expect(restored.expiresAt, original.expiresAt); + }); + }); + + group('copyWith', () { + test('creates copy with updated messageId', () { + final original = MessageEnvelope( + messageId: 'original-id', + timestamp: DateTime.utc(2024, 1, 15, 10, 30, 0), + topic: '/server/user123/message', + payload: {'key': 'value'}, + ); + + final copy = original.copyWith(messageId: 'new-id'); + + expect(copy.messageId, 'new-id'); + expect(copy.timestamp, original.timestamp); + expect(copy.topic, original.topic); + expect(copy.payload, original.payload); + }); + + test('creates copy with updated retryCount', () { + final original = MessageEnvelope( + messageId: 'test-id', + timestamp: DateTime.utc(2024, 1, 15, 10, 30, 0), + topic: '/server/user123/message', + payload: {'key': 'value'}, + retryCount: 0, + ); + + final copy = original.copyWith(retryCount: 3); + + expect(copy.retryCount, 3); + expect(copy.messageId, original.messageId); + }); + }); + + group('toString', () { + test('returns readable representation', () { + final envelope = MessageEnvelope( + messageId: 'test-id', + timestamp: DateTime.utc(2024, 1, 15, 10, 30, 0), + topic: '/server/user123/message', + payload: {'key': 'value'}, + requiresAck: true, + retryCount: 2, + ); + + final str = envelope.toString(); + + expect(str, contains('test-id')); + expect(str, contains('/server/user123/message')); + expect(str, contains('requiresAck: true')); + expect(str, contains('retryCount: 2')); + }); + }); + }); +} diff --git a/app/test/services/ack_tracker_test.dart b/app/test/services/ack_tracker_test.dart new file mode 100644 index 0000000..f9852cd --- /dev/null +++ b/app/test/services/ack_tracker_test.dart @@ -0,0 +1,312 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:votianlt_app/services/ack_tracker.dart'; + +void main() { + group('AckTracker', () { + late AckTracker tracker; + late List> retryCalls; + late List> timeoutCalls; + + setUp(() { + retryCalls = []; + timeoutCalls = []; + tracker = AckTracker( + maxRetries: 4, + onRetry: (topic, payload) async { + retryCalls.add({'topic': topic, 'payload': payload}); + return true; + }, + onTimeout: (messageId, topic) { + timeoutCalls.add({'messageId': messageId, 'topic': topic}); + }, + ); + }); + + group('track', () { + test('adds message to pending', () { + tracker.track('msg-1', '/server/user/message', '{"data": "test"}'); + + expect(tracker.isPending('msg-1'), true); + expect(tracker.pendingCount, 1); + }); + + test('can track multiple messages', () { + tracker.track('msg-1', '/topic1', 'payload1'); + tracker.track('msg-2', '/topic2', 'payload2'); + tracker.track('msg-3', '/topic3', 'payload3'); + + expect(tracker.pendingCount, 3); + expect(tracker.isPending('msg-1'), true); + expect(tracker.isPending('msg-2'), true); + expect(tracker.isPending('msg-3'), true); + }); + + test('stores correct topic and payload', () { + tracker.track('msg-1', '/server/user/message', '{"key": "value"}'); + + final pending = tracker.getPendingMessage('msg-1'); + expect(pending, isNotNull); + expect(pending!.topic, '/server/user/message'); + expect(pending.jsonPayload, '{"key": "value"}'); + expect(pending.retryCount, 0); + }); + + test('overwrites existing message with same ID', () { + tracker.track('msg-1', '/old/topic', 'old payload'); + tracker.track('msg-1', '/new/topic', 'new payload'); + + final pending = tracker.getPendingMessage('msg-1'); + expect(pending!.topic, '/new/topic'); + expect(pending.jsonPayload, 'new payload'); + expect(tracker.pendingCount, 1); + }); + }); + + group('acknowledge', () { + test('removes message from pending', () { + tracker.track('msg-1', '/topic', 'payload'); + expect(tracker.isPending('msg-1'), true); + + tracker.acknowledge('msg-1'); + + expect(tracker.isPending('msg-1'), false); + expect(tracker.pendingCount, 0); + }); + + test('does nothing for unknown message ID', () { + tracker.track('msg-1', '/topic', 'payload'); + + tracker.acknowledge('unknown-msg'); + + expect(tracker.pendingCount, 1); + expect(tracker.isPending('msg-1'), true); + }); + + test('only removes specified message', () { + tracker.track('msg-1', '/topic1', 'payload1'); + tracker.track('msg-2', '/topic2', 'payload2'); + + tracker.acknowledge('msg-1'); + + expect(tracker.isPending('msg-1'), false); + expect(tracker.isPending('msg-2'), true); + expect(tracker.pendingCount, 1); + }); + }); + + group('isPending', () { + test('returns true for tracked message', () { + tracker.track('msg-1', '/topic', 'payload'); + expect(tracker.isPending('msg-1'), true); + }); + + test('returns false for untracked message', () { + expect(tracker.isPending('unknown'), false); + }); + + test('returns false after acknowledge', () { + tracker.track('msg-1', '/topic', 'payload'); + tracker.acknowledge('msg-1'); + expect(tracker.isPending('msg-1'), false); + }); + }); + + group('pendingMessageIds', () { + test('returns empty list when no messages pending', () { + expect(tracker.pendingMessageIds, isEmpty); + }); + + test('returns all pending message IDs', () { + tracker.track('msg-1', '/topic1', 'payload1'); + tracker.track('msg-2', '/topic2', 'payload2'); + + final ids = tracker.pendingMessageIds; + + expect(ids, containsAll(['msg-1', 'msg-2'])); + expect(ids.length, 2); + }); + + test('returns unmodifiable list', () { + tracker.track('msg-1', '/topic', 'payload'); + + final ids = tracker.pendingMessageIds; + + expect(() => ids.add('new-id'), throwsUnsupportedError); + }); + }); + + group('processRetries', () { + test('increments retryCount on each call', () async { + tracker.track('msg-1', '/topic', 'payload'); + + await tracker.processRetries(); + expect(tracker.getPendingMessage('msg-1')!.retryCount, 1); + + await tracker.processRetries(); + expect(tracker.getPendingMessage('msg-1')!.retryCount, 2); + + await tracker.processRetries(); + expect(tracker.getPendingMessage('msg-1')!.retryCount, 3); + }); + + test('calls onRetry callback with correct parameters', () async { + tracker.track('msg-1', '/server/user/message', '{"data": "test"}'); + + await tracker.processRetries(); + + expect(retryCalls.length, 1); + expect(retryCalls[0]['topic'], '/server/user/message'); + expect(retryCalls[0]['payload'], '{"data": "test"}'); + }); + + test('calls onRetry for each pending message', () async { + tracker.track('msg-1', '/topic1', 'payload1'); + tracker.track('msg-2', '/topic2', 'payload2'); + + await tracker.processRetries(); + + expect(retryCalls.length, 2); + }); + + test('calls onTimeout after maxRetries exceeded', () async { + tracker.track('msg-1', '/timeout/topic', 'payload'); + + // Process until maxRetries reached + for (var i = 0; i < 4; i++) { + await tracker.processRetries(); + } + + expect(timeoutCalls, isEmpty); + expect(tracker.isPending('msg-1'), true); + + // One more retry should trigger timeout + await tracker.processRetries(); + + expect(timeoutCalls.length, 1); + expect(timeoutCalls[0]['messageId'], 'msg-1'); + expect(timeoutCalls[0]['topic'], '/timeout/topic'); + }); + + test('removes message after timeout', () async { + tracker.track('msg-1', '/topic', 'payload'); + + // Process until timeout + for (var i = 0; i <= 4; i++) { + await tracker.processRetries(); + } + + expect(tracker.isPending('msg-1'), false); + expect(tracker.pendingCount, 0); + }); + + test('does not retry when isConnected is false', () async { + tracker.track('msg-1', '/topic', 'payload'); + + await tracker.processRetries(isConnected: false); + + expect(retryCalls, isEmpty); + expect(tracker.getPendingMessage('msg-1')!.retryCount, 0); + }); + + test('still times out when disconnected after max retries', () async { + tracker.track('msg-1', '/topic', 'payload'); + + // Manually set retry count to max (simulating previous retries) + final pending = tracker.getPendingMessage('msg-1')!; + pending.retryCount = 4; + + await tracker.processRetries(isConnected: false); + + expect(timeoutCalls.length, 1); + expect(tracker.isPending('msg-1'), false); + }); + + test('does nothing when no messages pending', () async { + await tracker.processRetries(); + + expect(retryCalls, isEmpty); + expect(timeoutCalls, isEmpty); + }); + }); + + group('clearAll', () { + test('removes all pending messages', () { + tracker.track('msg-1', '/topic1', 'payload1'); + tracker.track('msg-2', '/topic2', 'payload2'); + + tracker.clearAll(); + + expect(tracker.pendingCount, 0); + expect(tracker.isPending('msg-1'), false); + expect(tracker.isPending('msg-2'), false); + }); + }); + + group('clearForTopic', () { + test('removes only messages for matching topic', () { + tracker.track('msg-1', '/server/login', 'login1'); + tracker.track('msg-2', '/server/login', 'login2'); + tracker.track('msg-3', '/server/user/message', 'message'); + + tracker.clearForTopic('/server/login'); + + expect(tracker.isPending('msg-1'), false); + expect(tracker.isPending('msg-2'), false); + expect(tracker.isPending('msg-3'), true); + expect(tracker.pendingCount, 1); + }); + + test('does nothing when no matching topic', () { + tracker.track('msg-1', '/server/user/message', 'payload'); + + tracker.clearForTopic('/server/login'); + + expect(tracker.pendingCount, 1); + expect(tracker.isPending('msg-1'), true); + }); + }); + + group('without callbacks', () { + test('processRetries works without onRetry callback', () async { + final noCallbackTracker = AckTracker(maxRetries: 2); + noCallbackTracker.track('msg-1', '/topic', 'payload'); + + // Should not throw + await noCallbackTracker.processRetries(); + + expect(noCallbackTracker.getPendingMessage('msg-1')!.retryCount, 1); + }); + + test('processRetries works without onTimeout callback', () async { + final noCallbackTracker = AckTracker(maxRetries: 1); + noCallbackTracker.track('msg-1', '/topic', 'payload'); + + // Process until timeout + await noCallbackTracker.processRetries(); + await noCallbackTracker.processRetries(); + + // Should be removed even without callback + expect(noCallbackTracker.isPending('msg-1'), false); + }); + }); + + group('PendingMessage', () { + test('stores sentAt timestamp', () { + final before = DateTime.now(); + tracker.track('msg-1', '/topic', 'payload'); + final after = DateTime.now(); + + final pending = tracker.getPendingMessage('msg-1')!; + + expect(pending.sentAt.isAfter(before) || pending.sentAt == before, true); + expect(pending.sentAt.isBefore(after) || pending.sentAt == after, true); + }); + + test('initializes retryCount to 0', () { + tracker.track('msg-1', '/topic', 'payload'); + + expect(tracker.getPendingMessage('msg-1')!.retryCount, 0); + }); + }); + }); +} diff --git a/app/test/services/message_handler_test.dart b/app/test/services/message_handler_test.dart new file mode 100644 index 0000000..f7c8443 --- /dev/null +++ b/app/test/services/message_handler_test.dart @@ -0,0 +1,350 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:votianlt_app/services/message_handler.dart'; + +void main() { + group('MessageHandler', () { + late MessageHandler handler; + late List ackCallbackCalls; + + setUp(() { + ackCallbackCalls = []; + handler = MessageHandler( + maxProcessedIds: 100, + onAckRequired: (messageId) => ackCallbackCalls.add(messageId), + ); + }); + + group('isEnvelopeMessage', () { + test('returns true for valid envelope with all required fields', () { + final data = { + 'messageId': 'test-id', + 'timestamp': '2024-01-15T10:30:00.000Z', + 'topic': '/server/user/message', + 'payload': {'key': 'value'}, + }; + + expect(handler.isEnvelopeMessage(data), true); + }); + + test('returns false when messageId is missing', () { + final data = { + 'timestamp': '2024-01-15T10:30:00.000Z', + 'topic': '/server/user/message', + 'payload': {'key': 'value'}, + }; + + expect(handler.isEnvelopeMessage(data), false); + }); + + test('returns false when timestamp is missing', () { + final data = { + 'messageId': 'test-id', + 'topic': '/server/user/message', + 'payload': {'key': 'value'}, + }; + + expect(handler.isEnvelopeMessage(data), false); + }); + + test('returns false when topic is missing', () { + final data = { + 'messageId': 'test-id', + 'timestamp': '2024-01-15T10:30:00.000Z', + 'payload': {'key': 'value'}, + }; + + expect(handler.isEnvelopeMessage(data), false); + }); + + test('returns false when payload is missing', () { + final data = { + 'messageId': 'test-id', + 'timestamp': '2024-01-15T10:30:00.000Z', + 'topic': '/server/user/message', + }; + + expect(handler.isEnvelopeMessage(data), false); + }); + + test('returns false for non-map data', () { + expect(handler.isEnvelopeMessage('string'), false); + expect(handler.isEnvelopeMessage(123), false); + expect(handler.isEnvelopeMessage(['list']), false); + expect(handler.isEnvelopeMessage(null), false); + }); + + test('returns true even if payload is null', () { + final data = { + 'messageId': 'test-id', + 'timestamp': '2024-01-15T10:30:00.000Z', + 'topic': '/server/user/message', + 'payload': null, + }; + + expect(handler.isEnvelopeMessage(data), true); + }); + }); + + group('unwrapEnvelope', () { + test('extracts payload from valid envelope', () { + final data = { + 'messageId': 'test-id-123', + 'timestamp': '2024-01-15T10:30:00.000Z', + 'topic': '/server/user/message', + 'payload': {'content': 'Hello'}, + 'requiresAck': true, + }; + + final result = handler.unwrapEnvelope(data); + + expect(result, isNotNull); + expect(result!.payload, {'content': 'Hello'}); + expect(result.messageId, 'test-id-123'); + expect(result.requiresAck, true); + }); + + test('returns non-envelope data as-is', () { + final plainData = {'content': 'Hello', 'sender': 'user1'}; + + final result = handler.unwrapEnvelope(plainData); + + expect(result, isNotNull); + expect(result!.payload, plainData); + expect(result.messageId, isNull); + expect(result.requiresAck, false); + }); + + test('returns null for duplicate messageId', () { + final data = { + 'messageId': 'duplicate-id', + 'timestamp': '2024-01-15T10:30:00.000Z', + 'topic': '/server/user/message', + 'payload': {'content': 'First'}, + 'requiresAck': false, + }; + + // First call should succeed + final firstResult = handler.unwrapEnvelope(data); + expect(firstResult, isNotNull); + + // Second call with same messageId should return null + final secondResult = handler.unwrapEnvelope(data); + expect(secondResult, isNull); + }); + + test('calls onAckRequired for duplicate when original required ACK', () { + final data = { + 'messageId': 'ack-duplicate-id', + 'timestamp': '2024-01-15T10:30:00.000Z', + 'topic': '/server/user/message', + 'payload': {'content': 'Message'}, + 'requiresAck': true, + }; + + // First call + handler.unwrapEnvelope(data); + expect(ackCallbackCalls, isEmpty); // No ACK callback on first process + + // Second call (duplicate) - should trigger ACK + handler.unwrapEnvelope(data); + expect(ackCallbackCalls, ['ack-duplicate-id']); + }); + + test('does not call onAckRequired for duplicate when requiresAck is false', () { + final data = { + 'messageId': 'no-ack-duplicate', + 'timestamp': '2024-01-15T10:30:00.000Z', + 'topic': '/server/user/message', + 'payload': {'content': 'Message'}, + 'requiresAck': false, + }; + + handler.unwrapEnvelope(data); + handler.unwrapEnvelope(data); + + expect(ackCallbackCalls, isEmpty); + }); + + test('defaults requiresAck to true when not specified', () { + final data = { + 'messageId': 'default-ack-id', + 'timestamp': '2024-01-15T10:30:00.000Z', + 'topic': '/server/user/message', + 'payload': {'content': 'Message'}, + // requiresAck not specified + }; + + final result = handler.unwrapEnvelope(data); + + expect(result!.requiresAck, true); + }); + + test('handles list payload', () { + final data = { + 'messageId': 'list-payload-id', + 'timestamp': '2024-01-15T10:30:00.000Z', + 'topic': '/server/user/jobs', + 'payload': [ + {'id': '1'}, + {'id': '2'} + ], + }; + + final result = handler.unwrapEnvelope(data); + + expect(result!.payload, isList); + expect(result.payload.length, 2); + }); + + test('handles null payload', () { + final data = { + 'messageId': 'null-payload-id', + 'timestamp': '2024-01-15T10:30:00.000Z', + 'topic': '/server/user/ping', + 'payload': null, + }; + + final result = handler.unwrapEnvelope(data); + + expect(result!.payload, isNull); + }); + }); + + group('deduplication memory management', () { + test('respects maxProcessedIds limit', () { + final smallHandler = MessageHandler(maxProcessedIds: 3); + + // Add 4 messages + for (var i = 1; i <= 4; i++) { + smallHandler.unwrapEnvelope({ + 'messageId': 'msg-$i', + 'timestamp': '2024-01-15T10:30:00.000Z', + 'topic': '/test', + 'payload': null, + }); + } + + // Should only have 3 IDs tracked + expect(smallHandler.processedCount, 3); + + // First message should have been evicted (FIFO) + expect(smallHandler.wasProcessed('msg-1'), false); + expect(smallHandler.wasProcessed('msg-2'), true); + expect(smallHandler.wasProcessed('msg-3'), true); + expect(smallHandler.wasProcessed('msg-4'), true); + }); + + test('allows reprocessing after eviction', () { + final smallHandler = MessageHandler(maxProcessedIds: 2); + + // Process msg-1 + final first = smallHandler.unwrapEnvelope({ + 'messageId': 'msg-1', + 'timestamp': '2024-01-15T10:30:00.000Z', + 'topic': '/test', + 'payload': {'first': true}, + }); + expect(first, isNotNull); + + // Process msg-2 and msg-3 to evict msg-1 + smallHandler.unwrapEnvelope({ + 'messageId': 'msg-2', + 'timestamp': '2024-01-15T10:30:00.000Z', + 'topic': '/test', + 'payload': null, + }); + smallHandler.unwrapEnvelope({ + 'messageId': 'msg-3', + 'timestamp': '2024-01-15T10:30:00.000Z', + 'topic': '/test', + 'payload': null, + }); + + // msg-1 should be processable again + final reprocessed = smallHandler.unwrapEnvelope({ + 'messageId': 'msg-1', + 'timestamp': '2024-01-15T10:30:00.000Z', + 'topic': '/test', + 'payload': {'reprocessed': true}, + }); + expect(reprocessed, isNotNull); + expect(reprocessed!.payload, {'reprocessed': true}); + }); + }); + + group('wasProcessed', () { + test('returns true for processed message', () { + handler.unwrapEnvelope({ + 'messageId': 'processed-id', + 'timestamp': '2024-01-15T10:30:00.000Z', + 'topic': '/test', + 'payload': null, + }); + + expect(handler.wasProcessed('processed-id'), true); + }); + + test('returns false for unprocessed message', () { + expect(handler.wasProcessed('unknown-id'), false); + }); + }); + + group('clearProcessedIds', () { + test('removes all tracked message IDs', () { + handler.unwrapEnvelope({ + 'messageId': 'msg-1', + 'timestamp': '2024-01-15T10:30:00.000Z', + 'topic': '/test', + 'payload': null, + }); + handler.unwrapEnvelope({ + 'messageId': 'msg-2', + 'timestamp': '2024-01-15T10:30:00.000Z', + 'topic': '/test', + 'payload': null, + }); + + expect(handler.processedCount, 2); + + handler.clearProcessedIds(); + + expect(handler.processedCount, 0); + expect(handler.wasProcessed('msg-1'), false); + expect(handler.wasProcessed('msg-2'), false); + }); + + test('allows reprocessing cleared messages', () { + final data = { + 'messageId': 'cleared-msg', + 'timestamp': '2024-01-15T10:30:00.000Z', + 'topic': '/test', + 'payload': {'value': 1}, + }; + + handler.unwrapEnvelope(data); + handler.clearProcessedIds(); + + final result = handler.unwrapEnvelope(data); + expect(result, isNotNull); + }); + }); + + group('without onAckRequired callback', () { + test('handles duplicate gracefully when no callback set', () { + final noCallbackHandler = MessageHandler(); + + final data = { + 'messageId': 'no-callback-msg', + 'timestamp': '2024-01-15T10:30:00.000Z', + 'topic': '/test', + 'payload': null, + 'requiresAck': true, + }; + + noCallbackHandler.unwrapEnvelope(data); + // Should not throw when processing duplicate + expect(() => noCallbackHandler.unwrapEnvelope(data), returnsNormally); + }); + }); + }); +} diff --git a/app/test/services/mqtt_integration_test.dart b/app/test/services/mqtt_integration_test.dart new file mode 100644 index 0000000..cf6dfad --- /dev/null +++ b/app/test/services/mqtt_integration_test.dart @@ -0,0 +1,401 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:votianlt_app/services/message_handler.dart'; +import 'package:votianlt_app/services/ack_tracker.dart'; + +/// Integration tests simulating the full MQTT message flow +/// based on real app behavior from login through job loading. +void main() { + group('MQTT Integration Scenarios', () { + group('Login Flow', () { + test('complete login flow with message tracking and ACK handling', () async { + // === SETUP === + final acksSent = []; + final retriedMessages = []; + + final messageHandler = MessageHandler(maxProcessedIds: 100, onAckRequired: (messageId) => acksSent.add(messageId)); + + final ackTracker = AckTracker( + maxRetries: 4, + onRetry: (topic, payload) async { + retriedMessages.add(topic); + return true; + }, + onTimeout: (messageId, topic) {}, + ); + + const appId = '410cea21-a3cf-47c3-97ad-b1c01f0bacbb'; + const userId = '693fdcc757853e744d2ab0d5'; + + // === STEP 1: Send Login Request === + // App sends login message with envelope + const loginMessageId = '5f4907de-684e-4381-a771-bd4d7ecdddbd'; + const loginTopic = '/server/login'; + final loginPayload = '''{ + "messageId": "$loginMessageId", + "timestamp": "2026-01-13T11:13:10.275836", + "topic": "$loginTopic", + "payload": { + "email": "mail@svencarstensen.de", + "password": "secret" + }, + "requiresAck": true, + "retryCount": 0 + }'''; + + // Track the sent login message for ACK + ackTracker.track(loginMessageId, loginTopic, loginPayload); + + expect(ackTracker.isPending(loginMessageId), true); + expect(ackTracker.pendingCount, 1); + + // === STEP 2: Receive Auth Response === + // Server sends auth response with envelope + const authResponseMessageId = '9d867b3a-fe87-40d7-80bf-56b031beb76d'; + final authResponseEnvelope = { + 'messageId': authResponseMessageId, + 'timestamp': '2026-01-13T11:13:10.607327', + 'topic': '/client/$appId/auth', + 'payload': {'success': true, 'message': 'Anmeldung erfolgreich', 'token': null, 'userId': null, 'appUserId': userId}, + 'requiresAck': true, + 'retryCount': 0, + }; + + // Unwrap and process the auth response + final authResult = messageHandler.unwrapEnvelope(authResponseEnvelope); + + expect(authResult, isNotNull); + expect(authResult!.messageId, authResponseMessageId); + expect(authResult.requiresAck, true); + expect(authResult.payload['success'], true); + expect(authResult.payload['appUserId'], userId); + + // Message was processed, now marked as seen + expect(messageHandler.wasProcessed(authResponseMessageId), true); + + // === STEP 3: Auth Response acts as implicit ACK for login === + // The auth response itself confirms the login was received + ackTracker.clearForTopic('/server/login'); + + expect(ackTracker.isPending(loginMessageId), false); + expect(ackTracker.pendingCount, 0); + + // === STEP 4: Send ACK for auth response === + // Simulate sending ACK (callback would be called after processing) + acksSent.add(authResponseMessageId); + + expect(acksSent, contains(authResponseMessageId)); + + // === STEP 5: Verify duplicate auth response is ignored === + final duplicateResult = messageHandler.unwrapEnvelope(authResponseEnvelope); + + expect(duplicateResult, isNull); // Duplicate returns null + // But ACK is still triggered for duplicate (via callback) + expect(acksSent.where((id) => id == authResponseMessageId).length, 2); + }); + + test('login request retry when no ACK received', () async { + final retriedTopics = []; + final timedOutMessages = []; + + final ackTracker = AckTracker( + maxRetries: 4, + onRetry: (topic, payload) async { + retriedTopics.add(topic); + return true; + }, + onTimeout: (messageId, topic) { + timedOutMessages.add(messageId); + }, + ); + + const loginMessageId = 'login-no-ack-test'; + const loginTopic = '/server/login'; + + // Track login message + ackTracker.track(loginMessageId, loginTopic, '{"test": true}'); + + // Simulate 4 retry cycles (5 seconds each in real app) + for (var i = 1; i <= 4; i++) { + await ackTracker.processRetries(); + expect(retriedTopics.length, i); + expect(ackTracker.isPending(loginMessageId), true); + } + + // 5th cycle should timeout + await ackTracker.processRetries(); + + expect(timedOutMessages, contains(loginMessageId)); + expect(ackTracker.isPending(loginMessageId), false); + }); + }); + + group('Job Loading Flow', () { + test('complete job loading flow with request, ACK, and response', () async { + // === SETUP === + final acksSent = []; + + final messageHandler = MessageHandler(maxProcessedIds: 100, onAckRequired: (messageId) => acksSent.add(messageId)); + + final ackTracker = AckTracker(maxRetries: 4, onRetry: (topic, payload) async => true, onTimeout: (messageId, topic) {}); + + const userId = '693fdcc757853e744d2ab0d5'; + + // === STEP 1: Send Jobs Request === + const jobsRequestMessageId = 'eb678b54-2b5e-47f5-9c3e-823d7092c49a'; + const jobsRequestTopic = '/server/$userId/jobs/assigned'; + + ackTracker.track(jobsRequestMessageId, jobsRequestTopic, '{"messageId": "$jobsRequestMessageId"}'); + + expect(ackTracker.isPending(jobsRequestMessageId), true); + + // === STEP 2: Receive ACK for jobs request === + // Server acknowledges our request + final jobsRequestAckEnvelope = { + 'messageId': 'ack-envelope-id-1', + 'timestamp': '2026-01-13T11:13:10.700000', + 'topic': '/client/$userId/ack', + 'payload': {'messageId': jobsRequestMessageId, 'status': 'RECEIVED', 'timestamp': '2026-01-13T11:13:10.700000', 'clientId': 'server'}, + 'requiresAck': false, + 'retryCount': 0, + }; + + // Process ACK envelope + final ackResult = messageHandler.unwrapEnvelope(jobsRequestAckEnvelope); + expect(ackResult, isNotNull); + expect(ackResult!.requiresAck, false); // ACKs don't need ACKs + + // Remove from pending based on ACK content + final ackPayload = ackResult.payload as Map; + final acknowledgedMessageId = ackPayload['messageId'] as String; + ackTracker.acknowledge(acknowledgedMessageId); + + expect(ackTracker.isPending(jobsRequestMessageId), false); + + // === STEP 3: Receive Jobs Response === + const jobsResponseMessageId = 'c92ef207-65a5-4204-802c-99e097f833f5'; + final jobsResponseEnvelope = { + 'messageId': jobsResponseMessageId, + 'timestamp': '2026-01-13T11:13:10.800000', + 'topic': '/client/$userId/jobs', + 'payload': [ + { + 'job': {'jobNumber': 'JOB20260106001', 'status': 'CREATED', 'id': '695ce8faf3fbbd0c2acfdb17', 'pickupCompany': 'cAPPacity GmbH', 'deliveryCompany': 'cAPPacity GmbH', 'pickupCity': 'Taarstedt', 'deliveryCity': 'Taarstedt'}, + 'cargoItems': [ + {'description': 'Europalette', 'quantity': 1, 'id': '695ce8faf3fbbd0c2acfdb18'}, + ], + 'tasks': [ + {'taskType': 'CONFIRMATION', 'taskOrder': 0, 'completed': false, 'buttonText': 'TEST', 'displayName': 'Bestätigung', 'id': '695ce8faf3fbbd0c2acfdb19'}, + ], + }, + ], + 'requiresAck': true, + 'retryCount': 0, + }; + + // Process jobs response + final jobsResult = messageHandler.unwrapEnvelope(jobsResponseEnvelope); + + expect(jobsResult, isNotNull); + expect(jobsResult!.messageId, jobsResponseMessageId); + expect(jobsResult.requiresAck, true); + expect(jobsResult.payload, isList); + expect((jobsResult.payload as List).length, 1); + + // Verify job data + final jobData = (jobsResult.payload as List)[0] as Map; + expect(jobData['job']['jobNumber'], 'JOB20260106001'); + expect(jobData['cargoItems'].length, 1); + expect(jobData['tasks'].length, 1); + + // === STEP 4: Send ACK for jobs response === + acksSent.add(jobsResponseMessageId); + + expect(acksSent, contains(jobsResponseMessageId)); + expect(messageHandler.wasProcessed(jobsResponseMessageId), true); + + // === STEP 5: Verify duplicate jobs response is handled === + final duplicateJobsResult = messageHandler.unwrapEnvelope(jobsResponseEnvelope); + + expect(duplicateJobsResult, isNull); + // Duplicate triggers ACK callback + expect(acksSent.where((id) => id == jobsResponseMessageId).length, 2); + }); + + test('multiple concurrent job requests with independent ACK tracking', () async { + final ackTracker = AckTracker(maxRetries: 4); + + const userId = '693fdcc757853e744d2ab0d5'; + + // Two JobsView instances send requests (as seen in log) + const request1Id = 'eb678b54-2b5e-47f5-9c3e-823d7092c49a'; + const request2Id = '936161ce-6535-4098-9e12-0e7bfb9393ed'; + const topic = '/server/$userId/jobs/assigned'; + + ackTracker.track(request1Id, topic, '{}'); + ackTracker.track(request2Id, topic, '{}'); + + expect(ackTracker.pendingCount, 2); + expect(ackTracker.isPending(request1Id), true); + expect(ackTracker.isPending(request2Id), true); + + // Both ACKs arrive + ackTracker.acknowledge(request1Id); + expect(ackTracker.pendingCount, 1); + expect(ackTracker.isPending(request1Id), false); + expect(ackTracker.isPending(request2Id), true); + + ackTracker.acknowledge(request2Id); + expect(ackTracker.pendingCount, 0); + }); + + test('ping messages without envelope are handled correctly', () { + final messageHandler = MessageHandler(); + + // Ping messages come without envelope wrapper + final pingData = {'type': 'ping', 'timestamp': '2026-01-13T11:13:15.000000'}; + + final result = messageHandler.unwrapEnvelope(pingData); + + expect(result, isNotNull); + expect(result!.messageId, isNull); // No messageId for non-envelope + expect(result.requiresAck, false); // No ACK needed + expect(result.payload, pingData); // Returns data as-is + }); + }); + + group('Message Deduplication Across Sessions', () { + test('prevents reprocessing of already-seen messages', () { + final processedPayloads = []; + final acksSent = []; + + final messageHandler = MessageHandler(maxProcessedIds: 100, onAckRequired: (messageId) => acksSent.add(messageId)); + + const messageId = 'duplicate-test-id'; + final envelope = { + 'messageId': messageId, + 'timestamp': '2026-01-13T11:13:10.000000', + 'topic': '/client/user/jobs', + 'payload': {'jobNumber': 'JOB001'}, + 'requiresAck': true, + }; + + // First processing + final result1 = messageHandler.unwrapEnvelope(envelope); + if (result1 != null) { + processedPayloads.add(result1.payload['jobNumber']); + } + + // Simulate server retry (same message arrives again) + final result2 = messageHandler.unwrapEnvelope(envelope); + if (result2 != null) { + processedPayloads.add(result2.payload['jobNumber']); + } + + // Third arrival + final result3 = messageHandler.unwrapEnvelope(envelope); + if (result3 != null) { + processedPayloads.add(result3.payload['jobNumber']); + } + + // Payload should only be processed once + expect(processedPayloads.length, 1); + expect(processedPayloads.first, 'JOB001'); + + // But ACK should be sent for each duplicate + expect(acksSent.length, 2); // Only duplicates trigger callback + }); + }); + + group('Full Session Flow', () { + test('simulates complete app session from login to job receipt', () async { + // === SETUP === + final processedMessages = {}; + final acksSent = []; + final pendingAcks = []; + + final messageHandler = MessageHandler(maxProcessedIds: 100, onAckRequired: (messageId) => acksSent.add(messageId)); + + final ackTracker = AckTracker(maxRetries: 4, onRetry: (topic, payload) async => true); + + const appId = '410cea21-a3cf-47c3-97ad-b1c01f0bacbb'; + const userId = '693fdcc757853e744d2ab0d5'; + + // === PHASE 1: LOGIN === + const loginMsgId = '5f4907de-684e-4381-a771-bd4d7ecdddbd'; + ackTracker.track(loginMsgId, '/server/login', '{}'); + pendingAcks.add(loginMsgId); + + expect(ackTracker.pendingCount, 1); + + // Auth response arrives + const authMsgId = '9d867b3a-fe87-40d7-80bf-56b031beb76d'; + final authResult = messageHandler.unwrapEnvelope({ + 'messageId': authMsgId, + 'timestamp': '2026-01-13T11:13:10.607327', + 'topic': '/client/$appId/auth', + 'payload': {'success': true, 'appUserId': userId}, + 'requiresAck': true, + }); + + processedMessages['auth'] = authResult!.payload; + acksSent.add(authMsgId); // Send ACK for auth + + // Login implicitly ACKed by auth response + ackTracker.clearForTopic('/server/login'); + pendingAcks.remove(loginMsgId); + + expect(ackTracker.pendingCount, 0); + expect(processedMessages['auth']['success'], true); + + // === PHASE 2: REQUEST JOBS === + const jobsReqMsgId = 'eb678b54-2b5e-47f5-9c3e-823d7092c49a'; + ackTracker.track(jobsReqMsgId, '/server/$userId/jobs/assigned', '{}'); + pendingAcks.add(jobsReqMsgId); + + expect(ackTracker.pendingCount, 1); + + // ACK for jobs request arrives + ackTracker.acknowledge(jobsReqMsgId); + pendingAcks.remove(jobsReqMsgId); + + expect(ackTracker.pendingCount, 0); + + // === PHASE 3: RECEIVE JOBS === + const jobsMsgId = 'c92ef207-65a5-4204-802c-99e097f833f5'; + final jobsResult = messageHandler.unwrapEnvelope({ + 'messageId': jobsMsgId, + 'timestamp': '2026-01-13T11:13:10.800000', + 'topic': '/client/$userId/jobs', + 'payload': [ + { + 'job': {'jobNumber': 'JOB20260106001', 'id': '695ce8faf3fbbd0c2acfdb17'}, + 'tasks': [ + {'taskType': 'CONFIRMATION', 'id': '695ce8faf3fbbd0c2acfdb19'}, + ], + }, + ], + 'requiresAck': true, + }); + + processedMessages['jobs'] = jobsResult!.payload; + acksSent.add(jobsMsgId); // Send ACK for jobs + + // === VERIFY FINAL STATE === + expect(processedMessages.length, 2); + expect(acksSent.length, 2); + expect(pendingAcks, isEmpty); + expect(ackTracker.pendingCount, 0); + + // Verify processed data + expect(processedMessages['auth']['appUserId'], userId); + expect((processedMessages['jobs'] as List).length, 1); + expect((processedMessages['jobs'] as List)[0]['job']['jobNumber'], 'JOB20260106001'); + + // Verify deduplication state + expect(messageHandler.wasProcessed(authMsgId), true); + expect(messageHandler.wasProcessed(jobsMsgId), true); + expect(messageHandler.processedCount, 2); + }); + }); + }); +} diff --git a/app/test/views/cargo_items_view_test.dart b/app/test/views/cargo_items_view_test.dart new file mode 100644 index 0000000..bfa8b67 --- /dev/null +++ b/app/test/views/cargo_items_view_test.dart @@ -0,0 +1,86 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:votianlt_app/cargo_items_view.dart'; +import 'package:votianlt_app/models/delivery_station.dart'; +import 'package:votianlt_app/models/tasks/confirmation_task.dart'; + +void main() { + group('deliveryStationCardBackgroundColor', () { + DeliveryStation buildStation(List tasks) { + return DeliveryStation( + stationOrder: 0, + company: 'ACME', + salutation: null, + firstName: 'Max', + lastName: 'Mustermann', + phone: '12345', + street: 'Musterstrasse', + houseNumber: '1', + addressAddition: '', + zip: '12345', + city: 'Berlin', + deliveryDate: '2026-03-10', + deliveryTime: '10:00', + tasks: tasks, + ); + } + + ConfirmationTask buildTask(String id, {bool completed = false}) { + return ConfirmationTask( + id: id, + jobId: 'job-1', + buttonText: 'Bestaetigen', + completed: completed, + ); + } + + test('returns light green when all station tasks are completed', () { + final station = buildStation([ + buildTask('task-1', completed: true), + buildTask('task-2', completed: true), + ]); + + final color = deliveryStationCardBackgroundColor(station, const {}); + + expect(color, Colors.green[50]); + }); + + test('returns null when only some tasks are completed', () { + final station = buildStation([ + buildTask('task-1', completed: true), + buildTask('task-2'), + ]); + + final color = deliveryStationCardBackgroundColor(station, const {}); + + expect(color, isNull); + }); + + test('returns null when no tasks are completed', () { + final station = buildStation([buildTask('task-1'), buildTask('task-2')]); + + final color = deliveryStationCardBackgroundColor(station, const {}); + + expect(color, isNull); + }); + + test('returns null when station has no tasks', () { + final station = buildStation(const []); + + final color = deliveryStationCardBackgroundColor(station, const {}); + + expect(color, isNull); + }); + + test('prefers local task status over incomplete task payload', () { + final station = buildStation([buildTask('task-1'), buildTask('task-2')]); + + final color = deliveryStationCardBackgroundColor(station, const { + 'task-1': true, + 'task-2': true, + }); + + expect(color, Colors.green[50]); + }); + }); +} diff --git a/app/windows/.gitignore b/app/windows/.gitignore new file mode 100644 index 0000000..d492d0d --- /dev/null +++ b/app/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/app/windows/CMakeLists.txt b/app/windows/CMakeLists.txt new file mode 100644 index 0000000..85c52de --- /dev/null +++ b/app/windows/CMakeLists.txt @@ -0,0 +1,108 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(votianlt_app LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "votianlt_app") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(VERSION 3.14...3.25) + +# Define build configuration option. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() +# Define settings for the Profile build mode. +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/app/windows/flutter/CMakeLists.txt b/app/windows/flutter/CMakeLists.txt new file mode 100644 index 0000000..903f489 --- /dev/null +++ b/app/windows/flutter/CMakeLists.txt @@ -0,0 +1,109 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.14) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# Set fallback configurations for older versions of the flutter tool. +if (NOT DEFINED FLUTTER_TARGET_PLATFORM) + set(FLUTTER_TARGET_PLATFORM "windows-x64") +endif() + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + ${FLUTTER_TARGET_PLATFORM} $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/app/windows/flutter/generated_plugin_registrant.cc b/app/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..9ec8be4 --- /dev/null +++ b/app/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,23 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include +#include +#include +#include + +void RegisterPlugins(flutter::PluginRegistry* registry) { + FileSelectorWindowsRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FileSelectorWindows")); + GeolocatorWindowsRegisterWithRegistrar( + registry->GetRegistrarForPlugin("GeolocatorWindows")); + ObjectboxFlutterLibsPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("ObjectboxFlutterLibsPlugin")); + UrlLauncherWindowsRegisterWithRegistrar( + registry->GetRegistrarForPlugin("UrlLauncherWindows")); +} diff --git a/app/windows/flutter/generated_plugin_registrant.h b/app/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..dc139d8 --- /dev/null +++ b/app/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/app/windows/flutter/generated_plugins.cmake b/app/windows/flutter/generated_plugins.cmake new file mode 100644 index 0000000..91c3394 --- /dev/null +++ b/app/windows/flutter/generated_plugins.cmake @@ -0,0 +1,27 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + file_selector_windows + geolocator_windows + objectbox_flutter_libs + url_launcher_windows +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/app/windows/runner/CMakeLists.txt b/app/windows/runner/CMakeLists.txt new file mode 100644 index 0000000..394917c --- /dev/null +++ b/app/windows/runner/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the build version. +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") + +# Disable Windows macros that collide with C++ standard library functions. +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") + +# Add dependency libraries and include directories. Add any application-specific +# dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/app/windows/runner/Runner.rc b/app/windows/runner/Runner.rc new file mode 100644 index 0000000..2075a43 --- /dev/null +++ b/app/windows/runner/Runner.rc @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\app_icon.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) +#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD +#else +#define VERSION_AS_NUMBER 1,0,0,0 +#endif + +#if defined(FLUTTER_VERSION) +#define VERSION_AS_STRING FLUTTER_VERSION +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "de.assecutor" "\0" + VALUE "FileDescription", "votianlt_app" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "votianlt_app" "\0" + VALUE "LegalCopyright", "Copyright (C) 2025 de.assecutor. All rights reserved." "\0" + VALUE "OriginalFilename", "votianlt_app.exe" "\0" + VALUE "ProductName", "votianlt_app" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/app/windows/runner/flutter_window.cpp b/app/windows/runner/flutter_window.cpp new file mode 100644 index 0000000..955ee30 --- /dev/null +++ b/app/windows/runner/flutter_window.cpp @@ -0,0 +1,71 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + + flutter_controller_->engine()->SetNextFrameCallback([&]() { + this->Show(); + }); + + // Flutter can complete the first frame before the "show window" callback is + // registered. The following call ensures a frame is pending to ensure the + // window is shown. It is a no-op if the first frame hasn't completed yet. + flutter_controller_->ForceRedraw(); + + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/app/windows/runner/flutter_window.h b/app/windows/runner/flutter_window.h new file mode 100644 index 0000000..6da0652 --- /dev/null +++ b/app/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow hosting a Flutter view running |project|. + explicit FlutterWindow(const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/app/windows/runner/main.cpp b/app/windows/runner/main.cpp new file mode 100644 index 0000000..3cec0c3 --- /dev/null +++ b/app/windows/runner/main.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "utils.h" + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.Create(L"votianlt_app", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/app/windows/runner/resource.h b/app/windows/runner/resource.h new file mode 100644 index 0000000..66a65d1 --- /dev/null +++ b/app/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/app/windows/runner/resources/app_icon.ico b/app/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000..c04e20c Binary files /dev/null and b/app/windows/runner/resources/app_icon.ico differ diff --git a/app/windows/runner/runner.exe.manifest b/app/windows/runner/runner.exe.manifest new file mode 100644 index 0000000..1461720 --- /dev/null +++ b/app/windows/runner/runner.exe.manifest @@ -0,0 +1,21 @@ + + + + + PerMonitorV2 + + + + + + + + + + + + + + + + diff --git a/app/windows/runner/utils.cpp b/app/windows/runner/utils.cpp new file mode 100644 index 0000000..3a0b465 --- /dev/null +++ b/app/windows/runner/utils.cpp @@ -0,0 +1,65 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + unsigned int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, nullptr, 0, nullptr, nullptr) + -1; // remove the trailing null character + int input_length = (int)wcslen(utf16_string); + std::string utf8_string; + if (target_length == 0 || target_length > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, utf8_string.data(), target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/app/windows/runner/utils.h b/app/windows/runner/utils.h new file mode 100644 index 0000000..3879d54 --- /dev/null +++ b/app/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/app/windows/runner/win32_window.cpp b/app/windows/runner/win32_window.cpp new file mode 100644 index 0000000..60608d0 --- /dev/null +++ b/app/windows/runner/win32_window.cpp @@ -0,0 +1,288 @@ +#include "win32_window.h" + +#include +#include + +#include "resource.h" + +namespace { + +/// Window attribute that enables dark mode window decorations. +/// +/// Redefined in case the developer's machine has a Windows SDK older than +/// version 10.0.22000.0. +/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 +#endif + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +/// Registry key for app theme preference. +/// +/// A value of 0 indicates apps should use dark mode. A non-zero or missing +/// value indicates apps should use light mode. +constexpr const wchar_t kGetPreferredBrightnessRegKey[] = + L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; +constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + } + FreeLibrary(user32_module); +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registrar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::Create(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + UpdateTheme(window); + + return OnCreate(); +} + +bool Win32Window::Show() { + return ShowWindow(window_handle_, SW_SHOWNORMAL); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + + case WM_DWMCOLORIZATIONCOLORCHANGED: + UpdateTheme(hwnd); + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} + +void Win32Window::UpdateTheme(HWND const window) { + DWORD light_mode; + DWORD light_mode_size = sizeof(light_mode); + LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, + kGetPreferredBrightnessRegValue, + RRF_RT_REG_DWORD, nullptr, &light_mode, + &light_mode_size); + + if (result == ERROR_SUCCESS) { + BOOL enable_dark_mode = light_mode == 0; + DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, + &enable_dark_mode, sizeof(enable_dark_mode)); + } +} diff --git a/app/windows/runner/win32_window.h b/app/windows/runner/win32_window.h new file mode 100644 index 0000000..e901dde --- /dev/null +++ b/app/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates a win32 window with |title| that is positioned and sized using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size this function will scale the inputted width and height as + // as appropriate for the default monitor. The window is invisible until + // |Show| is called. Returns true if the window was created successfully. + bool Create(const std::wstring& title, const Point& origin, const Size& size); + + // Show the current window. Returns true if the window was successfully shown. + bool Show(); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + // Update the window frame's theme to match the system theme. + static void UpdateTheme(HWND const window); + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_ diff --git a/backend/.gitignore b/backend/.gitignore new file mode 100644 index 0000000..e325f1b --- /dev/null +++ b/backend/.gitignore @@ -0,0 +1,8 @@ +/target/ +/node_modules/ +/src/main/frontend/generated/ +/vite.generated.ts +/logs/ +/.env +*.log +.DS_Store diff --git a/.mvn/wrapper/maven-wrapper.properties b/backend/.mvn/wrapper/maven-wrapper.properties similarity index 100% rename from .mvn/wrapper/maven-wrapper.properties rename to backend/.mvn/wrapper/maven-wrapper.properties diff --git a/.prettierrc.json b/backend/.prettierrc.json similarity index 100% rename from .prettierrc.json rename to backend/.prettierrc.json diff --git a/Dockerfile b/backend/Dockerfile similarity index 100% rename from Dockerfile rename to backend/Dockerfile diff --git a/HANDBUCH.md b/backend/HANDBUCH.md similarity index 100% rename from HANDBUCH.md rename to backend/HANDBUCH.md diff --git a/HANDBUCH.pdf b/backend/HANDBUCH.pdf similarity index 100% rename from HANDBUCH.pdf rename to backend/HANDBUCH.pdf diff --git a/STYLEGUIDE.md b/backend/STYLEGUIDE.md similarity index 99% rename from STYLEGUIDE.md rename to backend/STYLEGUIDE.md index 1481a33..59daf9f 100644 --- a/STYLEGUIDE.md +++ b/backend/STYLEGUIDE.md @@ -1,7 +1,7 @@ # VotianLT – UI Theme & Gestaltungsrichtlinien -> Gilt für alle Views unter `src/main/java/de/assecutor/votianlt/pages/view/` -> Theme-Datei: `src/main/frontend/themes/votian-modern/styles.css` +> Gilt für alle Views unter `backend/src/main/java/de/assecutor/votianlt/pages/view/` +> Theme-Datei: `backend/src/main/frontend/themes/votian-modern/styles.css` > Stand: UI-Änderungen bis 23.03.2026 berücksichtigt (`Landing-Hero-CTA/Demo-Button`, `ViewToolbar`-Migrationen, Landing-/Dashboard-Updates, TabSheet-Dialoge, Message-/Statistics-Layouts) --- diff --git a/docker_push.sh b/backend/docker_push.sh similarity index 71% rename from docker_push.sh rename to backend/docker_push.sh index 822c4a5..5884ee8 100755 --- a/docker_push.sh +++ b/backend/docker_push.sh @@ -4,6 +4,7 @@ set -euo pipefail readonly SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" readonly REGISTRY_IMAGE="registry.assecutor.org/votianlt" +readonly BACKEND_DIR="${SCRIPT_DIR}/backend" usage() { cat <<'EOF' @@ -33,11 +34,11 @@ require_command() { } resolve_pom_version() { - [[ -x "./mvnw" ]] || fail "'./mvnw' wurde nicht gefunden oder ist nicht ausführbar." + [[ -x "${BACKEND_DIR}/mvnw" ]] || fail "'${BACKEND_DIR}/mvnw' wurde nicht gefunden oder ist nicht ausführbar." local version version="$( - ./mvnw -q -DforceStdout help:evaluate -Dexpression=project.version \ + cd "${BACKEND_DIR}" && ./mvnw -q -DforceStdout help:evaluate -Dexpression=project.version \ | awk 'NF { last = $0 } END { print last }' )" @@ -63,17 +64,19 @@ cd "${SCRIPT_DIR}" echo "Verwende Release-Version ${VERSION}." echo "Baue Production-JAR für Version ${VERSION} ..." -./mvnw -Pproduction -DskipTests -Drevision="${VERSION}" package +(cd "${BACKEND_DIR}" && ./mvnw -Pproduction -DskipTests -Drevision="${VERSION}" package) -JAR_FILE="target/votianlt-${VERSION}.jar" -[[ -f "${JAR_FILE}" ]] || fail "Release-JAR wurde nicht gefunden: ${JAR_FILE}" +JAR_FILE_REL="target/votianlt-${VERSION}.jar" +JAR_FILE_ABS="${BACKEND_DIR}/${JAR_FILE_REL}" +[[ -f "${JAR_FILE_ABS}" ]] || fail "Release-JAR wurde nicht gefunden: ${JAR_FILE_ABS}" echo "Pushe Image ${REGISTRY_IMAGE}:${VERSION} ..." docker buildx build \ --platform linux/amd64 \ - --build-arg "JAR_FILE=${JAR_FILE}" \ + -f "${BACKEND_DIR}/Dockerfile" \ + --build-arg "JAR_FILE=${JAR_FILE_REL}" \ -t "${REGISTRY_IMAGE}:${VERSION}" \ --push \ - . + "${BACKEND_DIR}" echo "Fertig: ${REGISTRY_IMAGE}:${VERSION}" diff --git a/eclipse-formatter.xml b/backend/eclipse-formatter.xml similarity index 100% rename from eclipse-formatter.xml rename to backend/eclipse-formatter.xml diff --git a/flutter_websocket_test.html b/backend/flutter_websocket_test.html similarity index 100% rename from flutter_websocket_test.html rename to backend/flutter_websocket_test.html diff --git a/mvnw b/backend/mvnw similarity index 100% rename from mvnw rename to backend/mvnw diff --git a/mvnw.cmd b/backend/mvnw.cmd similarity index 100% rename from mvnw.cmd rename to backend/mvnw.cmd diff --git a/package-lock.json b/backend/package-lock.json similarity index 100% rename from package-lock.json rename to backend/package-lock.json diff --git a/package.json b/backend/package.json similarity index 100% rename from package.json rename to backend/package.json diff --git a/pom.xml b/backend/pom.xml similarity index 100% rename from pom.xml rename to backend/pom.xml diff --git a/src/main/bundles/README.md b/backend/src/main/bundles/README.md similarity index 100% rename from src/main/bundles/README.md rename to backend/src/main/bundles/README.md diff --git a/src/main/bundles/dev.bundle b/backend/src/main/bundles/dev.bundle similarity index 100% rename from src/main/bundles/dev.bundle rename to backend/src/main/bundles/dev.bundle diff --git a/src/main/bundles/prod.bundle b/backend/src/main/bundles/prod.bundle similarity index 100% rename from src/main/bundles/prod.bundle rename to backend/src/main/bundles/prod.bundle diff --git a/src/main/frontend/index.html b/backend/src/main/frontend/index.html similarity index 100% rename from src/main/frontend/index.html rename to backend/src/main/frontend/index.html diff --git a/src/main/frontend/invoice-generator/invoice-generator.js b/backend/src/main/frontend/invoice-generator/invoice-generator.js similarity index 100% rename from src/main/frontend/invoice-generator/invoice-generator.js rename to backend/src/main/frontend/invoice-generator/invoice-generator.js diff --git a/src/main/frontend/invoice-generator/profile-invoice-generator.js b/backend/src/main/frontend/invoice-generator/profile-invoice-generator.js similarity index 100% rename from src/main/frontend/invoice-generator/profile-invoice-generator.js rename to backend/src/main/frontend/invoice-generator/profile-invoice-generator.js diff --git a/src/main/frontend/themes/default/styles.css b/backend/src/main/frontend/themes/default/styles.css similarity index 100% rename from src/main/frontend/themes/default/styles.css rename to backend/src/main/frontend/themes/default/styles.css diff --git a/src/main/frontend/themes/default/theme.json b/backend/src/main/frontend/themes/default/theme.json similarity index 100% rename from src/main/frontend/themes/default/theme.json rename to backend/src/main/frontend/themes/default/theme.json diff --git a/src/main/frontend/themes/votian-modern/components/vaadin-tabsheet.css b/backend/src/main/frontend/themes/votian-modern/components/vaadin-tabsheet.css similarity index 100% rename from src/main/frontend/themes/votian-modern/components/vaadin-tabsheet.css rename to backend/src/main/frontend/themes/votian-modern/components/vaadin-tabsheet.css diff --git a/src/main/frontend/themes/votian-modern/styles.css b/backend/src/main/frontend/themes/votian-modern/styles.css similarity index 100% rename from src/main/frontend/themes/votian-modern/styles.css rename to backend/src/main/frontend/themes/votian-modern/styles.css diff --git a/src/main/frontend/themes/votian-modern/theme.json b/backend/src/main/frontend/themes/votian-modern/theme.json similarity index 100% rename from src/main/frontend/themes/votian-modern/theme.json rename to backend/src/main/frontend/themes/votian-modern/theme.json diff --git a/src/main/frontend/utils/language-cookie.ts b/backend/src/main/frontend/utils/language-cookie.ts similarity index 100% rename from src/main/frontend/utils/language-cookie.ts rename to backend/src/main/frontend/utils/language-cookie.ts diff --git a/src/main/java/de/assecutor/votianlt/Application.java b/backend/src/main/java/de/assecutor/votianlt/Application.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/Application.java rename to backend/src/main/java/de/assecutor/votianlt/Application.java diff --git a/src/main/java/de/assecutor/votianlt/ai/config/LlmConfig.java b/backend/src/main/java/de/assecutor/votianlt/ai/config/LlmConfig.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/ai/config/LlmConfig.java rename to backend/src/main/java/de/assecutor/votianlt/ai/config/LlmConfig.java diff --git a/src/main/java/de/assecutor/votianlt/ai/service/AiStatisticsService.java b/backend/src/main/java/de/assecutor/votianlt/ai/service/AiStatisticsService.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/ai/service/AiStatisticsService.java rename to backend/src/main/java/de/assecutor/votianlt/ai/service/AiStatisticsService.java diff --git a/src/main/java/de/assecutor/votianlt/ai/service/LlmRestClient.java b/backend/src/main/java/de/assecutor/votianlt/ai/service/LlmRestClient.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/ai/service/LlmRestClient.java rename to backend/src/main/java/de/assecutor/votianlt/ai/service/LlmRestClient.java diff --git a/src/main/java/de/assecutor/votianlt/config/DataInitializer.java b/backend/src/main/java/de/assecutor/votianlt/config/DataInitializer.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/config/DataInitializer.java rename to backend/src/main/java/de/assecutor/votianlt/config/DataInitializer.java diff --git a/src/main/java/de/assecutor/votianlt/config/DemoSessionCleanupConfig.java b/backend/src/main/java/de/assecutor/votianlt/config/DemoSessionCleanupConfig.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/config/DemoSessionCleanupConfig.java rename to backend/src/main/java/de/assecutor/votianlt/config/DemoSessionCleanupConfig.java diff --git a/src/main/java/de/assecutor/votianlt/config/JacksonConfig.java b/backend/src/main/java/de/assecutor/votianlt/config/JacksonConfig.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/config/JacksonConfig.java rename to backend/src/main/java/de/assecutor/votianlt/config/JacksonConfig.java diff --git a/src/main/java/de/assecutor/votianlt/config/LocaleVaadinInitListener.java b/backend/src/main/java/de/assecutor/votianlt/config/LocaleVaadinInitListener.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/config/LocaleVaadinInitListener.java rename to backend/src/main/java/de/assecutor/votianlt/config/LocaleVaadinInitListener.java diff --git a/src/main/java/de/assecutor/votianlt/config/MongoConfig.java b/backend/src/main/java/de/assecutor/votianlt/config/MongoConfig.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/config/MongoConfig.java rename to backend/src/main/java/de/assecutor/votianlt/config/MongoConfig.java diff --git a/src/main/java/de/assecutor/votianlt/config/PasswordEncoderConfig.java b/backend/src/main/java/de/assecutor/votianlt/config/PasswordEncoderConfig.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/config/PasswordEncoderConfig.java rename to backend/src/main/java/de/assecutor/votianlt/config/PasswordEncoderConfig.java diff --git a/src/main/java/de/assecutor/votianlt/config/TranslationProvider.java b/backend/src/main/java/de/assecutor/votianlt/config/TranslationProvider.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/config/TranslationProvider.java rename to backend/src/main/java/de/assecutor/votianlt/config/TranslationProvider.java diff --git a/src/main/java/de/assecutor/votianlt/controller/LocationApiController.java b/backend/src/main/java/de/assecutor/votianlt/controller/LocationApiController.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/controller/LocationApiController.java rename to backend/src/main/java/de/assecutor/votianlt/controller/LocationApiController.java diff --git a/src/main/java/de/assecutor/votianlt/controller/MessageApiController.java b/backend/src/main/java/de/assecutor/votianlt/controller/MessageApiController.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/controller/MessageApiController.java rename to backend/src/main/java/de/assecutor/votianlt/controller/MessageApiController.java diff --git a/src/main/java/de/assecutor/votianlt/controller/MessageController.java b/backend/src/main/java/de/assecutor/votianlt/controller/MessageController.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/controller/MessageController.java rename to backend/src/main/java/de/assecutor/votianlt/controller/MessageController.java diff --git a/src/main/java/de/assecutor/votianlt/dto/AppLoginRequest.class b/backend/src/main/java/de/assecutor/votianlt/dto/AppLoginRequest.class similarity index 100% rename from src/main/java/de/assecutor/votianlt/dto/AppLoginRequest.class rename to backend/src/main/java/de/assecutor/votianlt/dto/AppLoginRequest.class diff --git a/src/main/java/de/assecutor/votianlt/dto/AppLoginRequest.java b/backend/src/main/java/de/assecutor/votianlt/dto/AppLoginRequest.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/dto/AppLoginRequest.java rename to backend/src/main/java/de/assecutor/votianlt/dto/AppLoginRequest.java diff --git a/src/main/java/de/assecutor/votianlt/dto/AppLoginResponse.class b/backend/src/main/java/de/assecutor/votianlt/dto/AppLoginResponse.class similarity index 100% rename from src/main/java/de/assecutor/votianlt/dto/AppLoginResponse.class rename to backend/src/main/java/de/assecutor/votianlt/dto/AppLoginResponse.class diff --git a/src/main/java/de/assecutor/votianlt/dto/AppLoginResponse.java b/backend/src/main/java/de/assecutor/votianlt/dto/AppLoginResponse.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/dto/AppLoginResponse.java rename to backend/src/main/java/de/assecutor/votianlt/dto/AppLoginResponse.java diff --git a/src/main/java/de/assecutor/votianlt/dto/ChatMessageInboundPayload.class b/backend/src/main/java/de/assecutor/votianlt/dto/ChatMessageInboundPayload.class similarity index 100% rename from src/main/java/de/assecutor/votianlt/dto/ChatMessageInboundPayload.class rename to backend/src/main/java/de/assecutor/votianlt/dto/ChatMessageInboundPayload.class diff --git a/src/main/java/de/assecutor/votianlt/dto/ChatMessageInboundPayload.java b/backend/src/main/java/de/assecutor/votianlt/dto/ChatMessageInboundPayload.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/dto/ChatMessageInboundPayload.java rename to backend/src/main/java/de/assecutor/votianlt/dto/ChatMessageInboundPayload.java diff --git a/src/main/java/de/assecutor/votianlt/dto/ChatMessageOutboundPayload.class b/backend/src/main/java/de/assecutor/votianlt/dto/ChatMessageOutboundPayload.class similarity index 100% rename from src/main/java/de/assecutor/votianlt/dto/ChatMessageOutboundPayload.class rename to backend/src/main/java/de/assecutor/votianlt/dto/ChatMessageOutboundPayload.class diff --git a/src/main/java/de/assecutor/votianlt/dto/ChatMessageOutboundPayload.java b/backend/src/main/java/de/assecutor/votianlt/dto/ChatMessageOutboundPayload.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/dto/ChatMessageOutboundPayload.java rename to backend/src/main/java/de/assecutor/votianlt/dto/ChatMessageOutboundPayload.java diff --git a/src/main/java/de/assecutor/votianlt/dto/ClientMessageSummary.class b/backend/src/main/java/de/assecutor/votianlt/dto/ClientMessageSummary.class similarity index 100% rename from src/main/java/de/assecutor/votianlt/dto/ClientMessageSummary.class rename to backend/src/main/java/de/assecutor/votianlt/dto/ClientMessageSummary.class diff --git a/src/main/java/de/assecutor/votianlt/dto/ClientMessageSummary.java b/backend/src/main/java/de/assecutor/votianlt/dto/ClientMessageSummary.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/dto/ClientMessageSummary.java rename to backend/src/main/java/de/assecutor/votianlt/dto/ClientMessageSummary.java diff --git a/src/main/java/de/assecutor/votianlt/dto/JobWithRelatedDataDTO.class b/backend/src/main/java/de/assecutor/votianlt/dto/JobWithRelatedDataDTO.class similarity index 100% rename from src/main/java/de/assecutor/votianlt/dto/JobWithRelatedDataDTO.class rename to backend/src/main/java/de/assecutor/votianlt/dto/JobWithRelatedDataDTO.class diff --git a/src/main/java/de/assecutor/votianlt/dto/JobWithRelatedDataDTO.java b/backend/src/main/java/de/assecutor/votianlt/dto/JobWithRelatedDataDTO.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/dto/JobWithRelatedDataDTO.java rename to backend/src/main/java/de/assecutor/votianlt/dto/JobWithRelatedDataDTO.java diff --git a/src/main/java/de/assecutor/votianlt/event/MessageReadStatusChangedEvent.java b/backend/src/main/java/de/assecutor/votianlt/event/MessageReadStatusChangedEvent.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/event/MessageReadStatusChangedEvent.java rename to backend/src/main/java/de/assecutor/votianlt/event/MessageReadStatusChangedEvent.java diff --git a/src/main/java/de/assecutor/votianlt/event/MessageReceivedEvent.java b/backend/src/main/java/de/assecutor/votianlt/event/MessageReceivedEvent.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/event/MessageReceivedEvent.java rename to backend/src/main/java/de/assecutor/votianlt/event/MessageReceivedEvent.java diff --git a/src/main/java/de/assecutor/votianlt/mcp/config/McpServerConfig.java b/backend/src/main/java/de/assecutor/votianlt/mcp/config/McpServerConfig.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/mcp/config/McpServerConfig.java rename to backend/src/main/java/de/assecutor/votianlt/mcp/config/McpServerConfig.java diff --git a/src/main/java/de/assecutor/votianlt/mcp/dto/CustomerRevenueResult.java b/backend/src/main/java/de/assecutor/votianlt/mcp/dto/CustomerRevenueResult.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/mcp/dto/CustomerRevenueResult.java rename to backend/src/main/java/de/assecutor/votianlt/mcp/dto/CustomerRevenueResult.java diff --git a/src/main/java/de/assecutor/votianlt/mcp/dto/JobQueryResult.java b/backend/src/main/java/de/assecutor/votianlt/mcp/dto/JobQueryResult.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/mcp/dto/JobQueryResult.java rename to backend/src/main/java/de/assecutor/votianlt/mcp/dto/JobQueryResult.java diff --git a/src/main/java/de/assecutor/votianlt/mcp/dto/JobStatisticsResult.java b/backend/src/main/java/de/assecutor/votianlt/mcp/dto/JobStatisticsResult.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/mcp/dto/JobStatisticsResult.java rename to backend/src/main/java/de/assecutor/votianlt/mcp/dto/JobStatisticsResult.java diff --git a/src/main/java/de/assecutor/votianlt/mcp/dto/TaskCompletionResult.java b/backend/src/main/java/de/assecutor/votianlt/mcp/dto/TaskCompletionResult.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/mcp/dto/TaskCompletionResult.java rename to backend/src/main/java/de/assecutor/votianlt/mcp/dto/TaskCompletionResult.java diff --git a/src/main/java/de/assecutor/votianlt/mcp/tools/JobQueryTool.java b/backend/src/main/java/de/assecutor/votianlt/mcp/tools/JobQueryTool.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/mcp/tools/JobQueryTool.java rename to backend/src/main/java/de/assecutor/votianlt/mcp/tools/JobQueryTool.java diff --git a/src/main/java/de/assecutor/votianlt/mcp/tools/JobStatisticsTool.java b/backend/src/main/java/de/assecutor/votianlt/mcp/tools/JobStatisticsTool.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/mcp/tools/JobStatisticsTool.java rename to backend/src/main/java/de/assecutor/votianlt/mcp/tools/JobStatisticsTool.java diff --git a/src/main/java/de/assecutor/votianlt/mcp/tools/TaskCompletionTool.java b/backend/src/main/java/de/assecutor/votianlt/mcp/tools/TaskCompletionTool.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/mcp/tools/TaskCompletionTool.java rename to backend/src/main/java/de/assecutor/votianlt/mcp/tools/TaskCompletionTool.java diff --git a/src/main/java/de/assecutor/votianlt/messaging/MessagingConfig.java b/backend/src/main/java/de/assecutor/votianlt/messaging/MessagingConfig.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/messaging/MessagingConfig.java rename to backend/src/main/java/de/assecutor/votianlt/messaging/MessagingConfig.java diff --git a/src/main/java/de/assecutor/votianlt/messaging/MessagingPublisher.java b/backend/src/main/java/de/assecutor/votianlt/messaging/MessagingPublisher.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/messaging/MessagingPublisher.java rename to backend/src/main/java/de/assecutor/votianlt/messaging/MessagingPublisher.java diff --git a/src/main/java/de/assecutor/votianlt/messaging/WebSocketConfig.java b/backend/src/main/java/de/assecutor/votianlt/messaging/WebSocketConfig.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/messaging/WebSocketConfig.java rename to backend/src/main/java/de/assecutor/votianlt/messaging/WebSocketConfig.java diff --git a/src/main/java/de/assecutor/votianlt/messaging/WebSocketService.java b/backend/src/main/java/de/assecutor/votianlt/messaging/WebSocketService.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/messaging/WebSocketService.java rename to backend/src/main/java/de/assecutor/votianlt/messaging/WebSocketService.java diff --git a/src/main/java/de/assecutor/votianlt/model/AddressValidationResult.java b/backend/src/main/java/de/assecutor/votianlt/model/AddressValidationResult.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/AddressValidationResult.java rename to backend/src/main/java/de/assecutor/votianlt/model/AddressValidationResult.java diff --git a/src/main/java/de/assecutor/votianlt/model/AppUser.java b/backend/src/main/java/de/assecutor/votianlt/model/AppUser.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/AppUser.java rename to backend/src/main/java/de/assecutor/votianlt/model/AppUser.java diff --git a/src/main/java/de/assecutor/votianlt/model/Barcode.java b/backend/src/main/java/de/assecutor/votianlt/model/Barcode.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/Barcode.java rename to backend/src/main/java/de/assecutor/votianlt/model/Barcode.java diff --git a/src/main/java/de/assecutor/votianlt/model/CargoItem.java b/backend/src/main/java/de/assecutor/votianlt/model/CargoItem.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/CargoItem.java rename to backend/src/main/java/de/assecutor/votianlt/model/CargoItem.java diff --git a/src/main/java/de/assecutor/votianlt/model/Comment.java b/backend/src/main/java/de/assecutor/votianlt/model/Comment.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/Comment.java rename to backend/src/main/java/de/assecutor/votianlt/model/Comment.java diff --git a/src/main/java/de/assecutor/votianlt/model/Company.java b/backend/src/main/java/de/assecutor/votianlt/model/Company.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/Company.java rename to backend/src/main/java/de/assecutor/votianlt/model/Company.java diff --git a/src/main/java/de/assecutor/votianlt/model/Customer.java b/backend/src/main/java/de/assecutor/votianlt/model/Customer.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/Customer.java rename to backend/src/main/java/de/assecutor/votianlt/model/Customer.java diff --git a/src/main/java/de/assecutor/votianlt/model/DeliveryStation.java b/backend/src/main/java/de/assecutor/votianlt/model/DeliveryStation.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/DeliveryStation.java rename to backend/src/main/java/de/assecutor/votianlt/model/DeliveryStation.java diff --git a/src/main/java/de/assecutor/votianlt/model/InvoiceTemplate.java b/backend/src/main/java/de/assecutor/votianlt/model/InvoiceTemplate.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/InvoiceTemplate.java rename to backend/src/main/java/de/assecutor/votianlt/model/InvoiceTemplate.java diff --git a/src/main/java/de/assecutor/votianlt/model/Job.java b/backend/src/main/java/de/assecutor/votianlt/model/Job.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/Job.java rename to backend/src/main/java/de/assecutor/votianlt/model/Job.java diff --git a/src/main/java/de/assecutor/votianlt/model/JobHistory.java b/backend/src/main/java/de/assecutor/votianlt/model/JobHistory.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/JobHistory.java rename to backend/src/main/java/de/assecutor/votianlt/model/JobHistory.java diff --git a/src/main/java/de/assecutor/votianlt/model/JobHistoryType.java b/backend/src/main/java/de/assecutor/votianlt/model/JobHistoryType.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/JobHistoryType.java rename to backend/src/main/java/de/assecutor/votianlt/model/JobHistoryType.java diff --git a/src/main/java/de/assecutor/votianlt/model/JobServiceSelection.java b/backend/src/main/java/de/assecutor/votianlt/model/JobServiceSelection.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/JobServiceSelection.java rename to backend/src/main/java/de/assecutor/votianlt/model/JobServiceSelection.java diff --git a/src/main/java/de/assecutor/votianlt/model/JobStatus.java b/backend/src/main/java/de/assecutor/votianlt/model/JobStatus.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/JobStatus.java rename to backend/src/main/java/de/assecutor/votianlt/model/JobStatus.java diff --git a/src/main/java/de/assecutor/votianlt/model/Language.java b/backend/src/main/java/de/assecutor/votianlt/model/Language.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/Language.java rename to backend/src/main/java/de/assecutor/votianlt/model/Language.java diff --git a/src/main/java/de/assecutor/votianlt/model/LocationPosition.java b/backend/src/main/java/de/assecutor/votianlt/model/LocationPosition.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/LocationPosition.java rename to backend/src/main/java/de/assecutor/votianlt/model/LocationPosition.java diff --git a/src/main/java/de/assecutor/votianlt/model/Message.java b/backend/src/main/java/de/assecutor/votianlt/model/Message.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/Message.java rename to backend/src/main/java/de/assecutor/votianlt/model/Message.java diff --git a/src/main/java/de/assecutor/votianlt/model/MessageContentType.java b/backend/src/main/java/de/assecutor/votianlt/model/MessageContentType.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/MessageContentType.java rename to backend/src/main/java/de/assecutor/votianlt/model/MessageContentType.java diff --git a/src/main/java/de/assecutor/votianlt/model/MessageDeliveryStatus.java b/backend/src/main/java/de/assecutor/votianlt/model/MessageDeliveryStatus.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/MessageDeliveryStatus.java rename to backend/src/main/java/de/assecutor/votianlt/model/MessageDeliveryStatus.java diff --git a/src/main/java/de/assecutor/votianlt/model/MessageOrigin.java b/backend/src/main/java/de/assecutor/votianlt/model/MessageOrigin.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/MessageOrigin.java rename to backend/src/main/java/de/assecutor/votianlt/model/MessageOrigin.java diff --git a/src/main/java/de/assecutor/votianlt/model/MessageType.java b/backend/src/main/java/de/assecutor/votianlt/model/MessageType.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/MessageType.java rename to backend/src/main/java/de/assecutor/votianlt/model/MessageType.java diff --git a/src/main/java/de/assecutor/votianlt/model/Photo.java b/backend/src/main/java/de/assecutor/votianlt/model/Photo.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/Photo.java rename to backend/src/main/java/de/assecutor/votianlt/model/Photo.java diff --git a/src/main/java/de/assecutor/votianlt/model/PriceTable.java b/backend/src/main/java/de/assecutor/votianlt/model/PriceTable.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/PriceTable.java rename to backend/src/main/java/de/assecutor/votianlt/model/PriceTable.java diff --git a/src/main/java/de/assecutor/votianlt/model/RouteCalculationResult.java b/backend/src/main/java/de/assecutor/votianlt/model/RouteCalculationResult.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/RouteCalculationResult.java rename to backend/src/main/java/de/assecutor/votianlt/model/RouteCalculationResult.java diff --git a/src/main/java/de/assecutor/votianlt/model/Service.java b/backend/src/main/java/de/assecutor/votianlt/model/Service.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/Service.java rename to backend/src/main/java/de/assecutor/votianlt/model/Service.java diff --git a/src/main/java/de/assecutor/votianlt/model/Signature.java b/backend/src/main/java/de/assecutor/votianlt/model/Signature.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/Signature.java rename to backend/src/main/java/de/assecutor/votianlt/model/Signature.java diff --git a/src/main/java/de/assecutor/votianlt/model/TaskEntry.java b/backend/src/main/java/de/assecutor/votianlt/model/TaskEntry.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/TaskEntry.java rename to backend/src/main/java/de/assecutor/votianlt/model/TaskEntry.java diff --git a/src/main/java/de/assecutor/votianlt/model/TaskTemplate.java b/backend/src/main/java/de/assecutor/votianlt/model/TaskTemplate.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/TaskTemplate.java rename to backend/src/main/java/de/assecutor/votianlt/model/TaskTemplate.java diff --git a/src/main/java/de/assecutor/votianlt/model/TranslationCacheEntry.java b/backend/src/main/java/de/assecutor/votianlt/model/TranslationCacheEntry.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/TranslationCacheEntry.java rename to backend/src/main/java/de/assecutor/votianlt/model/TranslationCacheEntry.java diff --git a/src/main/java/de/assecutor/votianlt/model/User.java b/backend/src/main/java/de/assecutor/votianlt/model/User.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/User.java rename to backend/src/main/java/de/assecutor/votianlt/model/User.java diff --git a/src/main/java/de/assecutor/votianlt/model/UserInvoiceData.java b/backend/src/main/java/de/assecutor/votianlt/model/UserInvoiceData.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/UserInvoiceData.java rename to backend/src/main/java/de/assecutor/votianlt/model/UserInvoiceData.java diff --git a/src/main/java/de/assecutor/votianlt/model/invoices/CustomerInvoice.java b/backend/src/main/java/de/assecutor/votianlt/model/invoices/CustomerInvoice.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/invoices/CustomerInvoice.java rename to backend/src/main/java/de/assecutor/votianlt/model/invoices/CustomerInvoice.java diff --git a/src/main/java/de/assecutor/votianlt/model/invoices/CustomerInvoiceData.java b/backend/src/main/java/de/assecutor/votianlt/model/invoices/CustomerInvoiceData.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/invoices/CustomerInvoiceData.java rename to backend/src/main/java/de/assecutor/votianlt/model/invoices/CustomerInvoiceData.java diff --git a/src/main/java/de/assecutor/votianlt/model/invoices/CustomerInvoiceItem.java b/backend/src/main/java/de/assecutor/votianlt/model/invoices/CustomerInvoiceItem.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/invoices/CustomerInvoiceItem.java rename to backend/src/main/java/de/assecutor/votianlt/model/invoices/CustomerInvoiceItem.java diff --git a/src/main/java/de/assecutor/votianlt/model/invoices/SystemInvoice.java b/backend/src/main/java/de/assecutor/votianlt/model/invoices/SystemInvoice.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/invoices/SystemInvoice.java rename to backend/src/main/java/de/assecutor/votianlt/model/invoices/SystemInvoice.java diff --git a/src/main/java/de/assecutor/votianlt/model/invoices/SystemInvoiceData.java b/backend/src/main/java/de/assecutor/votianlt/model/invoices/SystemInvoiceData.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/invoices/SystemInvoiceData.java rename to backend/src/main/java/de/assecutor/votianlt/model/invoices/SystemInvoiceData.java diff --git a/src/main/java/de/assecutor/votianlt/model/invoices/SystemInvoiceItem.java b/backend/src/main/java/de/assecutor/votianlt/model/invoices/SystemInvoiceItem.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/invoices/SystemInvoiceItem.java rename to backend/src/main/java/de/assecutor/votianlt/model/invoices/SystemInvoiceItem.java diff --git a/src/main/java/de/assecutor/votianlt/model/task/BarcodeTask.java b/backend/src/main/java/de/assecutor/votianlt/model/task/BarcodeTask.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/task/BarcodeTask.java rename to backend/src/main/java/de/assecutor/votianlt/model/task/BarcodeTask.java diff --git a/src/main/java/de/assecutor/votianlt/model/task/BaseTask.java b/backend/src/main/java/de/assecutor/votianlt/model/task/BaseTask.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/task/BaseTask.java rename to backend/src/main/java/de/assecutor/votianlt/model/task/BaseTask.java diff --git a/src/main/java/de/assecutor/votianlt/model/task/CommentTask.java b/backend/src/main/java/de/assecutor/votianlt/model/task/CommentTask.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/task/CommentTask.java rename to backend/src/main/java/de/assecutor/votianlt/model/task/CommentTask.java diff --git a/src/main/java/de/assecutor/votianlt/model/task/ConfirmationTask.java b/backend/src/main/java/de/assecutor/votianlt/model/task/ConfirmationTask.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/task/ConfirmationTask.java rename to backend/src/main/java/de/assecutor/votianlt/model/task/ConfirmationTask.java diff --git a/src/main/java/de/assecutor/votianlt/model/task/PhotoTask.java b/backend/src/main/java/de/assecutor/votianlt/model/task/PhotoTask.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/task/PhotoTask.java rename to backend/src/main/java/de/assecutor/votianlt/model/task/PhotoTask.java diff --git a/src/main/java/de/assecutor/votianlt/model/task/SignatureTask.java b/backend/src/main/java/de/assecutor/votianlt/model/task/SignatureTask.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/task/SignatureTask.java rename to backend/src/main/java/de/assecutor/votianlt/model/task/SignatureTask.java diff --git a/src/main/java/de/assecutor/votianlt/model/task/TaskType.java b/backend/src/main/java/de/assecutor/votianlt/model/task/TaskType.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/task/TaskType.java rename to backend/src/main/java/de/assecutor/votianlt/model/task/TaskType.java diff --git a/src/main/java/de/assecutor/votianlt/model/task/TodoListTask.java b/backend/src/main/java/de/assecutor/votianlt/model/task/TodoListTask.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/model/task/TodoListTask.java rename to backend/src/main/java/de/assecutor/votianlt/model/task/TodoListTask.java diff --git a/src/main/java/de/assecutor/votianlt/pages/base/ui/component/DeliveryStationDialog.java b/backend/src/main/java/de/assecutor/votianlt/pages/base/ui/component/DeliveryStationDialog.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/base/ui/component/DeliveryStationDialog.java rename to backend/src/main/java/de/assecutor/votianlt/pages/base/ui/component/DeliveryStationDialog.java diff --git a/src/main/java/de/assecutor/votianlt/pages/base/ui/component/DeliveryStationTile.java b/backend/src/main/java/de/assecutor/votianlt/pages/base/ui/component/DeliveryStationTile.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/base/ui/component/DeliveryStationTile.java rename to backend/src/main/java/de/assecutor/votianlt/pages/base/ui/component/DeliveryStationTile.java diff --git a/src/main/java/de/assecutor/votianlt/pages/base/ui/component/DialogStylingHelper.java b/backend/src/main/java/de/assecutor/votianlt/pages/base/ui/component/DialogStylingHelper.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/base/ui/component/DialogStylingHelper.java rename to backend/src/main/java/de/assecutor/votianlt/pages/base/ui/component/DialogStylingHelper.java diff --git a/src/main/java/de/assecutor/votianlt/pages/base/ui/component/PickupStationDialog.java b/backend/src/main/java/de/assecutor/votianlt/pages/base/ui/component/PickupStationDialog.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/base/ui/component/PickupStationDialog.java rename to backend/src/main/java/de/assecutor/votianlt/pages/base/ui/component/PickupStationDialog.java diff --git a/src/main/java/de/assecutor/votianlt/pages/base/ui/component/StationTile.java b/backend/src/main/java/de/assecutor/votianlt/pages/base/ui/component/StationTile.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/base/ui/component/StationTile.java rename to backend/src/main/java/de/assecutor/votianlt/pages/base/ui/component/StationTile.java diff --git a/src/main/java/de/assecutor/votianlt/pages/base/ui/component/ViewToolbar.class b/backend/src/main/java/de/assecutor/votianlt/pages/base/ui/component/ViewToolbar.class similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/base/ui/component/ViewToolbar.class rename to backend/src/main/java/de/assecutor/votianlt/pages/base/ui/component/ViewToolbar.class diff --git a/src/main/java/de/assecutor/votianlt/pages/base/ui/component/ViewToolbar.java b/backend/src/main/java/de/assecutor/votianlt/pages/base/ui/component/ViewToolbar.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/base/ui/component/ViewToolbar.java rename to backend/src/main/java/de/assecutor/votianlt/pages/base/ui/component/ViewToolbar.java diff --git a/src/main/java/de/assecutor/votianlt/pages/base/ui/view/AdminLayout.java b/backend/src/main/java/de/assecutor/votianlt/pages/base/ui/view/AdminLayout.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/base/ui/view/AdminLayout.java rename to backend/src/main/java/de/assecutor/votianlt/pages/base/ui/view/AdminLayout.java diff --git a/src/main/java/de/assecutor/votianlt/pages/base/ui/view/MainErrorHandler.java b/backend/src/main/java/de/assecutor/votianlt/pages/base/ui/view/MainErrorHandler.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/base/ui/view/MainErrorHandler.java rename to backend/src/main/java/de/assecutor/votianlt/pages/base/ui/view/MainErrorHandler.java diff --git a/src/main/java/de/assecutor/votianlt/pages/base/ui/view/MainLayout.java b/backend/src/main/java/de/assecutor/votianlt/pages/base/ui/view/MainLayout.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/base/ui/view/MainLayout.java rename to backend/src/main/java/de/assecutor/votianlt/pages/base/ui/view/MainLayout.java diff --git a/src/main/java/de/assecutor/votianlt/pages/domain/AddCompanyRepository.java b/backend/src/main/java/de/assecutor/votianlt/pages/domain/AddCompanyRepository.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/domain/AddCompanyRepository.java rename to backend/src/main/java/de/assecutor/votianlt/pages/domain/AddCompanyRepository.java diff --git a/src/main/java/de/assecutor/votianlt/pages/domain/AddCustomerRepository.java b/backend/src/main/java/de/assecutor/votianlt/pages/domain/AddCustomerRepository.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/domain/AddCustomerRepository.java rename to backend/src/main/java/de/assecutor/votianlt/pages/domain/AddCustomerRepository.java diff --git a/src/main/java/de/assecutor/votianlt/pages/domain/CustomerRepository.java b/backend/src/main/java/de/assecutor/votianlt/pages/domain/CustomerRepository.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/domain/CustomerRepository.java rename to backend/src/main/java/de/assecutor/votianlt/pages/domain/CustomerRepository.java diff --git a/src/main/java/de/assecutor/votianlt/pages/domain/LoginRepository.java b/backend/src/main/java/de/assecutor/votianlt/pages/domain/LoginRepository.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/domain/LoginRepository.java rename to backend/src/main/java/de/assecutor/votianlt/pages/domain/LoginRepository.java diff --git a/src/main/java/de/assecutor/votianlt/pages/domain/Order.java b/backend/src/main/java/de/assecutor/votianlt/pages/domain/Order.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/domain/Order.java rename to backend/src/main/java/de/assecutor/votianlt/pages/domain/Order.java diff --git a/src/main/java/de/assecutor/votianlt/pages/domain/RegisterRepository.java b/backend/src/main/java/de/assecutor/votianlt/pages/domain/RegisterRepository.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/domain/RegisterRepository.java rename to backend/src/main/java/de/assecutor/votianlt/pages/domain/RegisterRepository.java diff --git a/src/main/java/de/assecutor/votianlt/pages/service/AddCompanyService.java b/backend/src/main/java/de/assecutor/votianlt/pages/service/AddCompanyService.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/service/AddCompanyService.java rename to backend/src/main/java/de/assecutor/votianlt/pages/service/AddCompanyService.java diff --git a/src/main/java/de/assecutor/votianlt/pages/service/AddCustomerService.java b/backend/src/main/java/de/assecutor/votianlt/pages/service/AddCustomerService.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/service/AddCustomerService.java rename to backend/src/main/java/de/assecutor/votianlt/pages/service/AddCustomerService.java diff --git a/src/main/java/de/assecutor/votianlt/pages/service/AddJobService.java b/backend/src/main/java/de/assecutor/votianlt/pages/service/AddJobService.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/service/AddJobService.java rename to backend/src/main/java/de/assecutor/votianlt/pages/service/AddJobService.java diff --git a/src/main/java/de/assecutor/votianlt/pages/service/AddressValidationService.java b/backend/src/main/java/de/assecutor/votianlt/pages/service/AddressValidationService.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/service/AddressValidationService.java rename to backend/src/main/java/de/assecutor/votianlt/pages/service/AddressValidationService.java diff --git a/src/main/java/de/assecutor/votianlt/pages/service/AppUserService.java b/backend/src/main/java/de/assecutor/votianlt/pages/service/AppUserService.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/service/AppUserService.java rename to backend/src/main/java/de/assecutor/votianlt/pages/service/AppUserService.java diff --git a/src/main/java/de/assecutor/votianlt/pages/service/CustomerService.java b/backend/src/main/java/de/assecutor/votianlt/pages/service/CustomerService.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/service/CustomerService.java rename to backend/src/main/java/de/assecutor/votianlt/pages/service/CustomerService.java diff --git a/src/main/java/de/assecutor/votianlt/pages/service/LoginService.java b/backend/src/main/java/de/assecutor/votianlt/pages/service/LoginService.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/service/LoginService.java rename to backend/src/main/java/de/assecutor/votianlt/pages/service/LoginService.java diff --git a/src/main/java/de/assecutor/votianlt/pages/service/PasswordResetService.java b/backend/src/main/java/de/assecutor/votianlt/pages/service/PasswordResetService.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/service/PasswordResetService.java rename to backend/src/main/java/de/assecutor/votianlt/pages/service/PasswordResetService.java diff --git a/src/main/java/de/assecutor/votianlt/pages/service/RegisterService.java b/backend/src/main/java/de/assecutor/votianlt/pages/service/RegisterService.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/service/RegisterService.java rename to backend/src/main/java/de/assecutor/votianlt/pages/service/RegisterService.java diff --git a/src/main/java/de/assecutor/votianlt/pages/service/TaskTemplateService.java b/backend/src/main/java/de/assecutor/votianlt/pages/service/TaskTemplateService.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/service/TaskTemplateService.java rename to backend/src/main/java/de/assecutor/votianlt/pages/service/TaskTemplateService.java diff --git a/src/main/java/de/assecutor/votianlt/pages/service/UserInvoiceDataService.java b/backend/src/main/java/de/assecutor/votianlt/pages/service/UserInvoiceDataService.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/service/UserInvoiceDataService.java rename to backend/src/main/java/de/assecutor/votianlt/pages/service/UserInvoiceDataService.java diff --git a/src/main/java/de/assecutor/votianlt/pages/service/UserService.java b/backend/src/main/java/de/assecutor/votianlt/pages/service/UserService.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/service/UserService.java rename to backend/src/main/java/de/assecutor/votianlt/pages/service/UserService.java diff --git a/src/main/java/de/assecutor/votianlt/pages/view/AddAppUserView.java b/backend/src/main/java/de/assecutor/votianlt/pages/view/AddAppUserView.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/view/AddAppUserView.java rename to backend/src/main/java/de/assecutor/votianlt/pages/view/AddAppUserView.java diff --git a/src/main/java/de/assecutor/votianlt/pages/view/AddCompanyView.java b/backend/src/main/java/de/assecutor/votianlt/pages/view/AddCompanyView.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/view/AddCompanyView.java rename to backend/src/main/java/de/assecutor/votianlt/pages/view/AddCompanyView.java diff --git a/src/main/java/de/assecutor/votianlt/pages/view/AddCustomerView.java b/backend/src/main/java/de/assecutor/votianlt/pages/view/AddCustomerView.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/view/AddCustomerView.java rename to backend/src/main/java/de/assecutor/votianlt/pages/view/AddCustomerView.java diff --git a/src/main/java/de/assecutor/votianlt/pages/view/AddJobView.java b/backend/src/main/java/de/assecutor/votianlt/pages/view/AddJobView.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/view/AddJobView.java rename to backend/src/main/java/de/assecutor/votianlt/pages/view/AddJobView.java diff --git a/src/main/java/de/assecutor/votianlt/pages/view/AdminDashboardView.java b/backend/src/main/java/de/assecutor/votianlt/pages/view/AdminDashboardView.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/view/AdminDashboardView.java rename to backend/src/main/java/de/assecutor/votianlt/pages/view/AdminDashboardView.java diff --git a/src/main/java/de/assecutor/votianlt/pages/view/AdminPricetableView.java b/backend/src/main/java/de/assecutor/votianlt/pages/view/AdminPricetableView.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/view/AdminPricetableView.java rename to backend/src/main/java/de/assecutor/votianlt/pages/view/AdminPricetableView.java diff --git a/src/main/java/de/assecutor/votianlt/pages/view/AppUserView.java b/backend/src/main/java/de/assecutor/votianlt/pages/view/AppUserView.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/view/AppUserView.java rename to backend/src/main/java/de/assecutor/votianlt/pages/view/AppUserView.java diff --git a/src/main/java/de/assecutor/votianlt/pages/view/AuthenticatedStartView.java b/backend/src/main/java/de/assecutor/votianlt/pages/view/AuthenticatedStartView.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/view/AuthenticatedStartView.java rename to backend/src/main/java/de/assecutor/votianlt/pages/view/AuthenticatedStartView.java diff --git a/src/main/java/de/assecutor/votianlt/pages/view/CreateInvoiceView.java b/backend/src/main/java/de/assecutor/votianlt/pages/view/CreateInvoiceView.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/view/CreateInvoiceView.java rename to backend/src/main/java/de/assecutor/votianlt/pages/view/CreateInvoiceView.java diff --git a/src/main/java/de/assecutor/votianlt/pages/view/CustomersView.java b/backend/src/main/java/de/assecutor/votianlt/pages/view/CustomersView.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/view/CustomersView.java rename to backend/src/main/java/de/assecutor/votianlt/pages/view/CustomersView.java diff --git a/src/main/java/de/assecutor/votianlt/pages/view/EditAppUserView.java b/backend/src/main/java/de/assecutor/votianlt/pages/view/EditAppUserView.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/view/EditAppUserView.java rename to backend/src/main/java/de/assecutor/votianlt/pages/view/EditAppUserView.java diff --git a/src/main/java/de/assecutor/votianlt/pages/view/EditCustomerView.java b/backend/src/main/java/de/assecutor/votianlt/pages/view/EditCustomerView.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/view/EditCustomerView.java rename to backend/src/main/java/de/assecutor/votianlt/pages/view/EditCustomerView.java diff --git a/src/main/java/de/assecutor/votianlt/pages/view/EditProfileView.java b/backend/src/main/java/de/assecutor/votianlt/pages/view/EditProfileView.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/view/EditProfileView.java rename to backend/src/main/java/de/assecutor/votianlt/pages/view/EditProfileView.java diff --git a/src/main/java/de/assecutor/votianlt/pages/view/ForgetPasswordView.java b/backend/src/main/java/de/assecutor/votianlt/pages/view/ForgetPasswordView.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/view/ForgetPasswordView.java rename to backend/src/main/java/de/assecutor/votianlt/pages/view/ForgetPasswordView.java diff --git a/src/main/java/de/assecutor/votianlt/pages/view/ForgotPasswordRequestView.java b/backend/src/main/java/de/assecutor/votianlt/pages/view/ForgotPasswordRequestView.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/view/ForgotPasswordRequestView.java rename to backend/src/main/java/de/assecutor/votianlt/pages/view/ForgotPasswordRequestView.java diff --git a/src/main/java/de/assecutor/votianlt/pages/view/ImprintView.java b/backend/src/main/java/de/assecutor/votianlt/pages/view/ImprintView.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/view/ImprintView.java rename to backend/src/main/java/de/assecutor/votianlt/pages/view/ImprintView.java diff --git a/src/main/java/de/assecutor/votianlt/pages/view/InvoiceGeneratorView.java b/backend/src/main/java/de/assecutor/votianlt/pages/view/InvoiceGeneratorView.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/view/InvoiceGeneratorView.java rename to backend/src/main/java/de/assecutor/votianlt/pages/view/InvoiceGeneratorView.java diff --git a/src/main/java/de/assecutor/votianlt/pages/view/InvoicesView.java b/backend/src/main/java/de/assecutor/votianlt/pages/view/InvoicesView.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/view/InvoicesView.java rename to backend/src/main/java/de/assecutor/votianlt/pages/view/InvoicesView.java diff --git a/src/main/java/de/assecutor/votianlt/pages/view/JobHistoryView.java b/backend/src/main/java/de/assecutor/votianlt/pages/view/JobHistoryView.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/view/JobHistoryView.java rename to backend/src/main/java/de/assecutor/votianlt/pages/view/JobHistoryView.java diff --git a/src/main/java/de/assecutor/votianlt/pages/view/JobSummaryView.java b/backend/src/main/java/de/assecutor/votianlt/pages/view/JobSummaryView.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/view/JobSummaryView.java rename to backend/src/main/java/de/assecutor/votianlt/pages/view/JobSummaryView.java diff --git a/src/main/java/de/assecutor/votianlt/pages/view/LoginView.java b/backend/src/main/java/de/assecutor/votianlt/pages/view/LoginView.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/view/LoginView.java rename to backend/src/main/java/de/assecutor/votianlt/pages/view/LoginView.java diff --git a/src/main/java/de/assecutor/votianlt/pages/view/MessageDetailsView.java b/backend/src/main/java/de/assecutor/votianlt/pages/view/MessageDetailsView.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/view/MessageDetailsView.java rename to backend/src/main/java/de/assecutor/votianlt/pages/view/MessageDetailsView.java diff --git a/src/main/java/de/assecutor/votianlt/pages/view/MessagesView.java b/backend/src/main/java/de/assecutor/votianlt/pages/view/MessagesView.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/view/MessagesView.java rename to backend/src/main/java/de/assecutor/votianlt/pages/view/MessagesView.java diff --git a/src/main/java/de/assecutor/votianlt/pages/view/MyInvoicesView.java b/backend/src/main/java/de/assecutor/votianlt/pages/view/MyInvoicesView.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/view/MyInvoicesView.java rename to backend/src/main/java/de/assecutor/votianlt/pages/view/MyInvoicesView.java diff --git a/src/main/java/de/assecutor/votianlt/pages/view/RegisterView.java b/backend/src/main/java/de/assecutor/votianlt/pages/view/RegisterView.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/view/RegisterView.java rename to backend/src/main/java/de/assecutor/votianlt/pages/view/RegisterView.java diff --git a/src/main/java/de/assecutor/votianlt/pages/view/ShowCustomersView.java b/backend/src/main/java/de/assecutor/votianlt/pages/view/ShowCustomersView.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/view/ShowCustomersView.java rename to backend/src/main/java/de/assecutor/votianlt/pages/view/ShowCustomersView.java diff --git a/src/main/java/de/assecutor/votianlt/pages/view/ShowJobsView.java b/backend/src/main/java/de/assecutor/votianlt/pages/view/ShowJobsView.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/view/ShowJobsView.java rename to backend/src/main/java/de/assecutor/votianlt/pages/view/ShowJobsView.java diff --git a/src/main/java/de/assecutor/votianlt/pages/view/StartView.java b/backend/src/main/java/de/assecutor/votianlt/pages/view/StartView.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/view/StartView.java rename to backend/src/main/java/de/assecutor/votianlt/pages/view/StartView.java diff --git a/src/main/java/de/assecutor/votianlt/pages/view/StatisticsView.java b/backend/src/main/java/de/assecutor/votianlt/pages/view/StatisticsView.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/view/StatisticsView.java rename to backend/src/main/java/de/assecutor/votianlt/pages/view/StatisticsView.java diff --git a/src/main/java/de/assecutor/votianlt/pages/view/UserMessagesView.java b/backend/src/main/java/de/assecutor/votianlt/pages/view/UserMessagesView.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/view/UserMessagesView.java rename to backend/src/main/java/de/assecutor/votianlt/pages/view/UserMessagesView.java diff --git a/src/main/java/de/assecutor/votianlt/pages/view/VerwaltungView.java b/backend/src/main/java/de/assecutor/votianlt/pages/view/VerwaltungView.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/pages/view/VerwaltungView.java rename to backend/src/main/java/de/assecutor/votianlt/pages/view/VerwaltungView.java diff --git a/src/main/java/de/assecutor/votianlt/repository/AppUserRepository.class b/backend/src/main/java/de/assecutor/votianlt/repository/AppUserRepository.class similarity index 100% rename from src/main/java/de/assecutor/votianlt/repository/AppUserRepository.class rename to backend/src/main/java/de/assecutor/votianlt/repository/AppUserRepository.class diff --git a/src/main/java/de/assecutor/votianlt/repository/AppUserRepository.java b/backend/src/main/java/de/assecutor/votianlt/repository/AppUserRepository.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/repository/AppUserRepository.java rename to backend/src/main/java/de/assecutor/votianlt/repository/AppUserRepository.java diff --git a/src/main/java/de/assecutor/votianlt/repository/BarcodeRepository.java b/backend/src/main/java/de/assecutor/votianlt/repository/BarcodeRepository.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/repository/BarcodeRepository.java rename to backend/src/main/java/de/assecutor/votianlt/repository/BarcodeRepository.java diff --git a/src/main/java/de/assecutor/votianlt/repository/CargoItemRepository.java b/backend/src/main/java/de/assecutor/votianlt/repository/CargoItemRepository.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/repository/CargoItemRepository.java rename to backend/src/main/java/de/assecutor/votianlt/repository/CargoItemRepository.java diff --git a/src/main/java/de/assecutor/votianlt/repository/CommentRepository.class b/backend/src/main/java/de/assecutor/votianlt/repository/CommentRepository.class similarity index 100% rename from src/main/java/de/assecutor/votianlt/repository/CommentRepository.class rename to backend/src/main/java/de/assecutor/votianlt/repository/CommentRepository.class diff --git a/src/main/java/de/assecutor/votianlt/repository/CommentRepository.java b/backend/src/main/java/de/assecutor/votianlt/repository/CommentRepository.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/repository/CommentRepository.java rename to backend/src/main/java/de/assecutor/votianlt/repository/CommentRepository.java diff --git a/src/main/java/de/assecutor/votianlt/repository/CustomerInvoiceRepository.java b/backend/src/main/java/de/assecutor/votianlt/repository/CustomerInvoiceRepository.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/repository/CustomerInvoiceRepository.java rename to backend/src/main/java/de/assecutor/votianlt/repository/CustomerInvoiceRepository.java diff --git a/src/main/java/de/assecutor/votianlt/repository/InvoiceTemplateRepository.java b/backend/src/main/java/de/assecutor/votianlt/repository/InvoiceTemplateRepository.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/repository/InvoiceTemplateRepository.java rename to backend/src/main/java/de/assecutor/votianlt/repository/InvoiceTemplateRepository.java diff --git a/src/main/java/de/assecutor/votianlt/repository/JobHistoryRepository.class b/backend/src/main/java/de/assecutor/votianlt/repository/JobHistoryRepository.class similarity index 100% rename from src/main/java/de/assecutor/votianlt/repository/JobHistoryRepository.class rename to backend/src/main/java/de/assecutor/votianlt/repository/JobHistoryRepository.class diff --git a/src/main/java/de/assecutor/votianlt/repository/JobHistoryRepository.java b/backend/src/main/java/de/assecutor/votianlt/repository/JobHistoryRepository.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/repository/JobHistoryRepository.java rename to backend/src/main/java/de/assecutor/votianlt/repository/JobHistoryRepository.java diff --git a/src/main/java/de/assecutor/votianlt/repository/JobRepository.class b/backend/src/main/java/de/assecutor/votianlt/repository/JobRepository.class similarity index 100% rename from src/main/java/de/assecutor/votianlt/repository/JobRepository.class rename to backend/src/main/java/de/assecutor/votianlt/repository/JobRepository.class diff --git a/src/main/java/de/assecutor/votianlt/repository/JobRepository.java b/backend/src/main/java/de/assecutor/votianlt/repository/JobRepository.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/repository/JobRepository.java rename to backend/src/main/java/de/assecutor/votianlt/repository/JobRepository.java diff --git a/src/main/java/de/assecutor/votianlt/repository/LocationPositionRepository.java b/backend/src/main/java/de/assecutor/votianlt/repository/LocationPositionRepository.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/repository/LocationPositionRepository.java rename to backend/src/main/java/de/assecutor/votianlt/repository/LocationPositionRepository.java diff --git a/src/main/java/de/assecutor/votianlt/repository/MessageRepository.java b/backend/src/main/java/de/assecutor/votianlt/repository/MessageRepository.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/repository/MessageRepository.java rename to backend/src/main/java/de/assecutor/votianlt/repository/MessageRepository.java diff --git a/src/main/java/de/assecutor/votianlt/repository/PhotoRepository.class b/backend/src/main/java/de/assecutor/votianlt/repository/PhotoRepository.class similarity index 100% rename from src/main/java/de/assecutor/votianlt/repository/PhotoRepository.class rename to backend/src/main/java/de/assecutor/votianlt/repository/PhotoRepository.class diff --git a/src/main/java/de/assecutor/votianlt/repository/PhotoRepository.java b/backend/src/main/java/de/assecutor/votianlt/repository/PhotoRepository.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/repository/PhotoRepository.java rename to backend/src/main/java/de/assecutor/votianlt/repository/PhotoRepository.java diff --git a/src/main/java/de/assecutor/votianlt/repository/PriceTableRepository.java b/backend/src/main/java/de/assecutor/votianlt/repository/PriceTableRepository.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/repository/PriceTableRepository.java rename to backend/src/main/java/de/assecutor/votianlt/repository/PriceTableRepository.java diff --git a/src/main/java/de/assecutor/votianlt/repository/ServiceRepository.java b/backend/src/main/java/de/assecutor/votianlt/repository/ServiceRepository.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/repository/ServiceRepository.java rename to backend/src/main/java/de/assecutor/votianlt/repository/ServiceRepository.java diff --git a/src/main/java/de/assecutor/votianlt/repository/SignatureRepository.java b/backend/src/main/java/de/assecutor/votianlt/repository/SignatureRepository.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/repository/SignatureRepository.java rename to backend/src/main/java/de/assecutor/votianlt/repository/SignatureRepository.java diff --git a/src/main/java/de/assecutor/votianlt/repository/TaskRepository.java b/backend/src/main/java/de/assecutor/votianlt/repository/TaskRepository.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/repository/TaskRepository.java rename to backend/src/main/java/de/assecutor/votianlt/repository/TaskRepository.java diff --git a/src/main/java/de/assecutor/votianlt/repository/TaskTemplateRepository.java b/backend/src/main/java/de/assecutor/votianlt/repository/TaskTemplateRepository.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/repository/TaskTemplateRepository.java rename to backend/src/main/java/de/assecutor/votianlt/repository/TaskTemplateRepository.java diff --git a/src/main/java/de/assecutor/votianlt/repository/TranslationCacheRepository.java b/backend/src/main/java/de/assecutor/votianlt/repository/TranslationCacheRepository.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/repository/TranslationCacheRepository.java rename to backend/src/main/java/de/assecutor/votianlt/repository/TranslationCacheRepository.java diff --git a/src/main/java/de/assecutor/votianlt/repository/UserInvoiceDataRepository.java b/backend/src/main/java/de/assecutor/votianlt/repository/UserInvoiceDataRepository.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/repository/UserInvoiceDataRepository.java rename to backend/src/main/java/de/assecutor/votianlt/repository/UserInvoiceDataRepository.java diff --git a/src/main/java/de/assecutor/votianlt/repository/UserRepository.java b/backend/src/main/java/de/assecutor/votianlt/repository/UserRepository.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/repository/UserRepository.java rename to backend/src/main/java/de/assecutor/votianlt/repository/UserRepository.java diff --git a/src/main/java/de/assecutor/votianlt/security/CustomUserPrincipal.java b/backend/src/main/java/de/assecutor/votianlt/security/CustomUserPrincipal.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/security/CustomUserPrincipal.java rename to backend/src/main/java/de/assecutor/votianlt/security/CustomUserPrincipal.java diff --git a/src/main/java/de/assecutor/votianlt/security/SecurityConfig.java b/backend/src/main/java/de/assecutor/votianlt/security/SecurityConfig.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/security/SecurityConfig.java rename to backend/src/main/java/de/assecutor/votianlt/security/SecurityConfig.java diff --git a/src/main/java/de/assecutor/votianlt/security/SecurityService.java b/backend/src/main/java/de/assecutor/votianlt/security/SecurityService.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/security/SecurityService.java rename to backend/src/main/java/de/assecutor/votianlt/security/SecurityService.java diff --git a/src/main/java/de/assecutor/votianlt/security/SessionAuthenticationService.java b/backend/src/main/java/de/assecutor/votianlt/security/SessionAuthenticationService.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/security/SessionAuthenticationService.java rename to backend/src/main/java/de/assecutor/votianlt/security/SessionAuthenticationService.java diff --git a/src/main/java/de/assecutor/votianlt/security/UserDetailsServiceImpl.java b/backend/src/main/java/de/assecutor/votianlt/security/UserDetailsServiceImpl.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/security/UserDetailsServiceImpl.java rename to backend/src/main/java/de/assecutor/votianlt/security/UserDetailsServiceImpl.java diff --git a/src/main/java/de/assecutor/votianlt/security/totp/TwoFactorService.java b/backend/src/main/java/de/assecutor/votianlt/security/totp/TwoFactorService.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/security/totp/TwoFactorService.java rename to backend/src/main/java/de/assecutor/votianlt/security/totp/TwoFactorService.java diff --git a/src/main/java/de/assecutor/votianlt/service/ClientConnectionService.java b/backend/src/main/java/de/assecutor/votianlt/service/ClientConnectionService.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/service/ClientConnectionService.java rename to backend/src/main/java/de/assecutor/votianlt/service/ClientConnectionService.java diff --git a/src/main/java/de/assecutor/votianlt/service/CustomerInvoiceService.java b/backend/src/main/java/de/assecutor/votianlt/service/CustomerInvoiceService.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/service/CustomerInvoiceService.java rename to backend/src/main/java/de/assecutor/votianlt/service/CustomerInvoiceService.java diff --git a/src/main/java/de/assecutor/votianlt/service/DemoModeService.java b/backend/src/main/java/de/assecutor/votianlt/service/DemoModeService.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/service/DemoModeService.java rename to backend/src/main/java/de/assecutor/votianlt/service/DemoModeService.java diff --git a/src/main/java/de/assecutor/votianlt/service/DemoSessionRegistry.java b/backend/src/main/java/de/assecutor/votianlt/service/DemoSessionRegistry.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/service/DemoSessionRegistry.java rename to backend/src/main/java/de/assecutor/votianlt/service/DemoSessionRegistry.java diff --git a/src/main/java/de/assecutor/votianlt/service/EmailService.java b/backend/src/main/java/de/assecutor/votianlt/service/EmailService.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/service/EmailService.java rename to backend/src/main/java/de/assecutor/votianlt/service/EmailService.java diff --git a/src/main/java/de/assecutor/votianlt/service/InvoiceTemplateService.java b/backend/src/main/java/de/assecutor/votianlt/service/InvoiceTemplateService.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/service/InvoiceTemplateService.java rename to backend/src/main/java/de/assecutor/votianlt/service/InvoiceTemplateService.java diff --git a/src/main/java/de/assecutor/votianlt/service/JobHistoryService.java b/backend/src/main/java/de/assecutor/votianlt/service/JobHistoryService.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/service/JobHistoryService.java rename to backend/src/main/java/de/assecutor/votianlt/service/JobHistoryService.java diff --git a/src/main/java/de/assecutor/votianlt/service/JobStatisticsService.java b/backend/src/main/java/de/assecutor/votianlt/service/JobStatisticsService.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/service/JobStatisticsService.java rename to backend/src/main/java/de/assecutor/votianlt/service/JobStatisticsService.java diff --git a/src/main/java/de/assecutor/votianlt/service/JobUpdateBroadcaster.java b/backend/src/main/java/de/assecutor/votianlt/service/JobUpdateBroadcaster.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/service/JobUpdateBroadcaster.java rename to backend/src/main/java/de/assecutor/votianlt/service/JobUpdateBroadcaster.java diff --git a/src/main/java/de/assecutor/votianlt/service/LanguageService.java b/backend/src/main/java/de/assecutor/votianlt/service/LanguageService.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/service/LanguageService.java rename to backend/src/main/java/de/assecutor/votianlt/service/LanguageService.java diff --git a/src/main/java/de/assecutor/votianlt/service/LocationService.java b/backend/src/main/java/de/assecutor/votianlt/service/LocationService.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/service/LocationService.java rename to backend/src/main/java/de/assecutor/votianlt/service/LocationService.java diff --git a/src/main/java/de/assecutor/votianlt/service/MessageBadgeUpdateService.java b/backend/src/main/java/de/assecutor/votianlt/service/MessageBadgeUpdateService.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/service/MessageBadgeUpdateService.java rename to backend/src/main/java/de/assecutor/votianlt/service/MessageBadgeUpdateService.java diff --git a/src/main/java/de/assecutor/votianlt/service/MessageBroadcaster.java b/backend/src/main/java/de/assecutor/votianlt/service/MessageBroadcaster.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/service/MessageBroadcaster.java rename to backend/src/main/java/de/assecutor/votianlt/service/MessageBroadcaster.java diff --git a/src/main/java/de/assecutor/votianlt/service/MessageService.java b/backend/src/main/java/de/assecutor/votianlt/service/MessageService.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/service/MessageService.java rename to backend/src/main/java/de/assecutor/votianlt/service/MessageService.java diff --git a/src/main/java/de/assecutor/votianlt/service/MonthlySchedulerService.java b/backend/src/main/java/de/assecutor/votianlt/service/MonthlySchedulerService.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/service/MonthlySchedulerService.java rename to backend/src/main/java/de/assecutor/votianlt/service/MonthlySchedulerService.java diff --git a/src/main/java/de/assecutor/votianlt/service/SystemInvoiceService.java b/backend/src/main/java/de/assecutor/votianlt/service/SystemInvoiceService.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/service/SystemInvoiceService.java rename to backend/src/main/java/de/assecutor/votianlt/service/SystemInvoiceService.java diff --git a/src/main/java/de/assecutor/votianlt/service/TaskAssignmentService.java b/backend/src/main/java/de/assecutor/votianlt/service/TaskAssignmentService.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/service/TaskAssignmentService.java rename to backend/src/main/java/de/assecutor/votianlt/service/TaskAssignmentService.java diff --git a/src/main/java/de/assecutor/votianlt/service/TranslationService.java b/backend/src/main/java/de/assecutor/votianlt/service/TranslationService.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/service/TranslationService.java rename to backend/src/main/java/de/assecutor/votianlt/service/TranslationService.java diff --git a/src/main/java/de/assecutor/votianlt/util/DateTimeFormatUtil.java b/backend/src/main/java/de/assecutor/votianlt/util/DateTimeFormatUtil.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/util/DateTimeFormatUtil.java rename to backend/src/main/java/de/assecutor/votianlt/util/DateTimeFormatUtil.java diff --git a/src/main/java/de/assecutor/votianlt/util/Util.java b/backend/src/main/java/de/assecutor/votianlt/util/Util.java similarity index 100% rename from src/main/java/de/assecutor/votianlt/util/Util.java rename to backend/src/main/java/de/assecutor/votianlt/util/Util.java diff --git a/src/main/resources/application-dev.properties b/backend/src/main/resources/application-dev.properties similarity index 100% rename from src/main/resources/application-dev.properties rename to backend/src/main/resources/application-dev.properties diff --git a/src/main/resources/application-production.properties b/backend/src/main/resources/application-production.properties similarity index 100% rename from src/main/resources/application-production.properties rename to backend/src/main/resources/application-production.properties diff --git a/src/main/resources/application.properties b/backend/src/main/resources/application.properties similarity index 100% rename from src/main/resources/application.properties rename to backend/src/main/resources/application.properties diff --git a/src/main/resources/html/imprint.html b/backend/src/main/resources/html/imprint.html similarity index 100% rename from src/main/resources/html/imprint.html rename to backend/src/main/resources/html/imprint.html diff --git a/src/main/resources/messages_de.properties b/backend/src/main/resources/messages_de.properties similarity index 100% rename from src/main/resources/messages_de.properties rename to backend/src/main/resources/messages_de.properties diff --git a/src/main/resources/messages_ee.properties b/backend/src/main/resources/messages_ee.properties similarity index 100% rename from src/main/resources/messages_ee.properties rename to backend/src/main/resources/messages_ee.properties diff --git a/src/main/resources/messages_en.properties b/backend/src/main/resources/messages_en.properties similarity index 100% rename from src/main/resources/messages_en.properties rename to backend/src/main/resources/messages_en.properties diff --git a/src/main/resources/messages_es.properties b/backend/src/main/resources/messages_es.properties similarity index 100% rename from src/main/resources/messages_es.properties rename to backend/src/main/resources/messages_es.properties diff --git a/src/main/resources/messages_fr.properties b/backend/src/main/resources/messages_fr.properties similarity index 100% rename from src/main/resources/messages_fr.properties rename to backend/src/main/resources/messages_fr.properties diff --git a/src/main/resources/messages_lt.properties b/backend/src/main/resources/messages_lt.properties similarity index 100% rename from src/main/resources/messages_lt.properties rename to backend/src/main/resources/messages_lt.properties diff --git a/src/main/resources/messages_lv.properties b/backend/src/main/resources/messages_lv.properties similarity index 100% rename from src/main/resources/messages_lv.properties rename to backend/src/main/resources/messages_lv.properties diff --git a/src/main/resources/messages_pl.properties b/backend/src/main/resources/messages_pl.properties similarity index 100% rename from src/main/resources/messages_pl.properties rename to backend/src/main/resources/messages_pl.properties diff --git a/src/main/resources/messages_ru.properties b/backend/src/main/resources/messages_ru.properties similarity index 100% rename from src/main/resources/messages_ru.properties rename to backend/src/main/resources/messages_ru.properties diff --git a/src/main/resources/messages_tr.properties b/backend/src/main/resources/messages_tr.properties similarity index 100% rename from src/main/resources/messages_tr.properties rename to backend/src/main/resources/messages_tr.properties diff --git a/src/main/resources/mqtt/chat/incoming-chat-message.json b/backend/src/main/resources/mqtt/chat/incoming-chat-message.json similarity index 100% rename from src/main/resources/mqtt/chat/incoming-chat-message.json rename to backend/src/main/resources/mqtt/chat/incoming-chat-message.json diff --git a/src/main/resources/mqtt/chat/outgoing-chat-message.json b/backend/src/main/resources/mqtt/chat/outgoing-chat-message.json similarity index 100% rename from src/main/resources/mqtt/chat/outgoing-chat-message.json rename to backend/src/main/resources/mqtt/chat/outgoing-chat-message.json diff --git a/src/main/resources/templates/customer_invoice.html b/backend/src/main/resources/templates/customer_invoice.html similarity index 100% rename from src/main/resources/templates/customer_invoice.html rename to backend/src/main/resources/templates/customer_invoice.html diff --git a/src/main/resources/templates/demo_invoice_template_default.json b/backend/src/main/resources/templates/demo_invoice_template_default.json similarity index 100% rename from src/main/resources/templates/demo_invoice_template_default.json rename to backend/src/main/resources/templates/demo_invoice_template_default.json diff --git a/src/main/resources/templates/system_invoice.html b/backend/src/main/resources/templates/system_invoice.html similarity index 100% rename from src/main/resources/templates/system_invoice.html rename to backend/src/main/resources/templates/system_invoice.html diff --git a/src/test/java/de/assecutor/votianlt/service/DemoModeServiceTest.java b/backend/src/test/java/de/assecutor/votianlt/service/DemoModeServiceTest.java similarity index 100% rename from src/test/java/de/assecutor/votianlt/service/DemoModeServiceTest.java rename to backend/src/test/java/de/assecutor/votianlt/service/DemoModeServiceTest.java diff --git a/src/test/java/de/assecutor/votianlt/service/DemoSessionRegistryTest.java b/backend/src/test/java/de/assecutor/votianlt/service/DemoSessionRegistryTest.java similarity index 100% rename from src/test/java/de/assecutor/votianlt/service/DemoSessionRegistryTest.java rename to backend/src/test/java/de/assecutor/votianlt/service/DemoSessionRegistryTest.java diff --git a/tsconfig.json b/backend/tsconfig.json similarity index 100% rename from tsconfig.json rename to backend/tsconfig.json diff --git a/types.d.ts b/backend/types.d.ts similarity index 100% rename from types.d.ts rename to backend/types.d.ts diff --git a/vite.config.ts b/backend/vite.config.ts similarity index 100% rename from vite.config.ts rename to backend/vite.config.ts