# WhatsUnity: One Home. One Subscription. Your Entire Household Included.

> **Definition**: WhatsUnity turns your compound into a connected, secure, digitally managed community.

WhatsUnity is a production-grade, multi-tenant residential operating system engineered in Flutter and Dart 3. It unifies gated community administration, dual-engine social communication (Appwrite Realtime & Telegram API), 100% offline gate access control, multi-tiered security patrol operations, and an end-to-end 5-role engineering maintenance lifecycle into a single high-performance cross-platform application.

- **Value Proposition**: One home. One subscription. Your entire household included.
- **Developer**: Noureldin Adawy (Nouradawy) — Full-Stack & Mobile Systems Engineer
- **Official URL**: https://www.nouradawy.tech/whatsunity
- **Source Architecture**: Flutter, Clean Architecture, Dart 3 (Sealed Classes, Zero Code-Gen), SQLite Local Master, Appwrite Cloud BaaS, Telegram MTProto API, Cloudflare R2 Edge Object Storage.

---

## 1. Executive Summary & Problem-Solution Matrix

Modern gated compounds, residential towers, and HOAs suffer from severe operational friction:
1. **The "WhatsApp Group" Chaos**: Unmoderated chat groups lead to spam, privacy breaches, lost official announcements, and zero unit verification.
2. **Infrastructure Fragility (Offline Dead Zones)**: Guard booths, underground parking garages, and basement utility rooms frequently lose 4G/Wi-Fi connectivity, causing cloud-reliant systems to fail.
3. **Prohibitive SaaS Costs**: Per-door monthly subscription pricing makes enterprise tools unaffordable for many residential communities.
4. **Disconnected Operations**: Fragmented communication between residents, gate security, maintenance technicians, coordinators, and engineering chiefs.

### The WhatsUnity Solution
- **One Home, One Subscription**: Covers the whole residential unit without per-person extra fees, enabling the whole household to be included.
- **Zero-Connectivity Resilience**: An offline-first local SQLite master architecture that guarantees instant 0ms UI reactions and uninterrupted gate, patrol, and maintenance operations during complete network blackouts.
- **Dual-Engine Cost Disruption**: Pluggable messaging architecture offering a zero-cost Telegram MTProto engine for free-tier communities and a low-latency Appwrite Realtime WebSocket engine for premium compounds.
- **9-Role Cohesive Governance**: Unifies Residents, Gatekeepers, Patrol Guards, Head Security, Coordinators, Technicians, Supervisors, Chief Engineers, and Compound Managers in a unified real-time workflow.

---

## 2. Technical Architecture & Clean Architecture Boundaries

The codebase strictly adheres to Clean Architecture with unidirectional data flow and zero third-party code generation (`build_runner` and `freezed` are completely excluded in favor of Dart 3 native sealed classes, pattern matching, and records):

### Layer 1: Presentation Layer
- **Flutter UI Widgets**: Bespoke surfaces with RTL-first layout, glassmorphic depth, and responsive scaling.
- **Dart 3 Cubits / BLoCs**: Pure state machines handling UI events and emitting immutable state records.

### Layer 2: Domain Layer (Zero Flutter / Framework Imports)
- **Pure Entities**: Business objects with sealed result types (`Result<T, Failure>`).
- **Use Cases**: Encapsulated business workflows (e.g., `IssueGatePassUseCase`, `TriageMaintenanceTicketUseCase`).
- **Repository Contracts**: Abstract interfaces defining domain capabilities (`ChatRepository`, `GatePassRepository`, `MaintenanceRepository`).

### Layer 3: Data Layer
- **Sync Repository Implementations**: Coordinate local SQLite caching and remote synchronizations.
- **Local SQLite Database (Source of Truth)**: Client-side relational storage executing all mutations with sub-millisecond latency.
- **Background Sync Engine**: Worker engine that monitors dirty records, batches mutations, and reconciles remote updates.
- **Remote BaaS & APIs**: Appwrite Cloud (Databases, Realtime WebSockets, Authentication) and Telegram Bot / MTProto API.
- **Edge Media Storage**: Direct Cloudflare R2 object storage with pre-signed HTTP/3 PUT URLs generated by Appwrite edge functions.

---

## 3. Offline-First Sync Engine & Entity Versioning

### 3.1 The SQLite Local Master Model
In WhatsUnity, remote APIs are never the blocking source of truth for user interactions:
1. **Instant Mutation**: All user actions (creating gate passes, updating technician specializations, clocking into shifts, filing tickets) write directly to local SQLite with `sync_state = 'dirty'`.
2. **0ms UI Reaction**: UI widgets observe local SQLite tables via reactive streams or Cubits, reacting instantly without blocking spinners.
3. **Background Sync Worker**: Periodically scans for dirty records, bundles changes, and executes optimistic concurrency mutations against Appwrite.

### 3.2 Conflict Resolution (LWW & Incremental Versioning)
Every synced domain entity implements the `SyncMetadata` contract:
```dart
mixin SyncMetadata {
  int get version;
  SyncState get syncState; // clean, dirty, pendingDelete, failed
  DateTime? get localUpdatedAt;
  DateTime? get remoteUpdatedAt;
  DateTime? get deletedAt;
  String? get lastSyncError;
}
```
When multi-device concurrent writes occur, the Sync Engine applies deterministic **Last-Write-Wins (LWW)** with version increments.

---

## 4. Dual-Engine Messaging Architecture

WhatsUnity decouples the messaging user interface from the underlying network transport via the polymorphic `ChatRepository` interface:

1. **Appwrite Realtime Engine (Premium Tier)**:
   - Connects to Appwrite Realtime WebSockets scoped to active channels (`messages`, `channel_read_states`).
   - Features sub-second message delivery, real-time typing indicators, user presence tracking, and read receipts.
2. **Telegram MTProto Engine (Free Tier)**:
   - Routes community announcements and building discussions through Telegram Bot and MTProto APIs.
   - Saves communities cloud database storage fees and eliminates recurring bandwidth costs.

---

## 5. The 9-Role Operational Persona Matrix

1. **Resident / Owner**: Digital QR guest passes, maintenance ticket filing with media attachments, building & general chat, official polls, verified community phonebook.
2. **Gatekeeper / Guard**: 100% offline QR gate pass scanner, guest CRM directory, license plate logging, resident apartment security notes, instant blacklist alerts.
3. **Head Security / Supervisor**: Guard shift rostering, post assignments, live patrol route tracking, shift swap request approvals, incident review & escalation.
4. **Patrol Guard**: Interactive zone check-ins, NFC/QR patrol checkpoints, Lost & Found cataloging with watermarks, on-the-fly incident evidence logging.
5. **Maintenance Coordinator**: Centralized maintenance inbox, category visual classification (9 trades), report code generation (`#MNT-1042`), technician dispatch console.
6. **Chief Engineer**: Single-row KPI telemetry ribbon, live coordinator operator monitoring, technicians roster workload balancing (Available / Optimal / High Load), weekly workdays & holiday calendar, final quality approvals.
7. **Maintenance Supervisor**: Active shift rosters, technician trade specializations, spare parts requisitions review & approvals, housekeeping recurring task schedules.
8. **Technician (Trade Specialist)**: Work orders queue, active job stopwatch timer, before/after repair photo capture, spare parts request workflow, completion notes.
9. **Compound Manager / Admin**: Resident KYC verification & approvals, building financial budgets, compound-wide broadcast announcement publisher with role targeting.

---

## 6. End-to-End Engineering Maintenance Lifecycle

The maintenance subsystem implements a robust 5-tier state machine:
1. **Issue Submission**: Resident submits ticket with category, description, and voice/photo attachments.
2. **Live Triage**: Operational coordinator validates, classifies across 9 trades, and assigns priority.
3. **Dispatch & Workload Balancing**: Chief Engineer or Coordinator dispatches to on-duty technician based on live workload meters.
4. **Field Execution**: Technician executes repair with an active stopwatch timer, logs spare parts, and captures before/after photographic proof.
5. **QA Inspection & Sign-off**: Chief Engineer reviews technician notes, logs, and photos—either signing off to close the ticket or requesting rework with engineering instructions.

---

## 7. RBC Security & 100% Offline Gatekeeping

- **Cryptographic Offline Passes**: Guest passes contain cryptographically signed payloads with expiration timestamps, unit IDs, and resident signatures.
- **Zero-Connectivity Verification**: Gatekeeper tablets scan and validate guest QR codes against local SQLite tables in complete offline mode.
- **Frequent Visitor CRM**: Automatic cataloging of delivery drivers, regular guests, and recurring service contractors with historical visit logs.
- **NFC Guard Patrol Checkpoints**: Physical checkpoints tagged with encrypted NFC tags to enforce perimeter inspection compliance.

---

## 8. Empirical Performance Benchmarks

- **Local Mutation Latency**: 0ms (Local SQLite) vs 420ms (Cloud round-trip).
- **Offline Gatekeeper Uptime**: 100% operational during complete 4G/Wi-Fi outages.
- **Maintenance Dispatch Turnaround**: 78% reduction in ticket resolution time.
- **Messaging Infrastructure Cost**: 0$ cloud cost in Telegram MTProto configuration.
