# H-Care Firebase Cloud Messaging (FCM) Specification

## 1. Purpose

This document defines the Firebase Cloud Messaging (FCM) architecture and functional requirements for H-Care.

H-Care is a post-Vacant-Possession property management platform. The system has:

- Laravel 13 backend
- PostgreSQL database
- Web administration application
- One H-Care mobile application for both iOS and Android
- Two major mobile experiences:
  - Property Owner Portal
  - Operations Portal for Property Management Staff and Contractors
- Firebase Cloud Messaging (FCM) for mobile push notifications

The mobile application is one application, but the user experience, navigation, permissions, and notification relevance are determined by the user's roles and portal access.

---

# 2. High-Level Architecture

```text
                         H-CARE WEB APPLICATION
                                  |
                                  |
                           Laravel 13 Backend
                                  |
             +--------------------+--------------------+
             |                    |                    |
        Business Events     Notification Engine   Notification History
             |                    |                    |
             +--------------------+--------------------+
                                  |
                           PostgreSQL Database
                                  |
                         Firebase Cloud Messaging
                                  |
                    +-------------+-------------+
                    |                           |
               Android App                 iOS App
                    |                           |
              Owner Portal              Owner Portal
                    |                           |
              Operations Portal          Operations Portal
```

FCM is the delivery infrastructure.

H-Care remains responsible for:

- deciding who receives a notification
- deciding why the notification is sent
- generating the title and message
- determining priority
- determining the destination screen
- recording notification history
- recording user preferences
- handling business rules

FCM is responsible for delivering the push message to registered mobile devices.

---

# 3. Firebase Project

Create a dedicated Firebase project for H-Care.

Recommended environments:

- H-Care Development
- H-Care Staging
- H-Care Production

Do not use production Firebase credentials in development.

Recommended naming:

```text
hcare-dev
hcare-staging
hcare-production
```

Each environment should have its own Firebase configuration and mobile application identifiers where practical.

---

# 4. Mobile Application

One mobile application shall support both iOS and Android.

The application supports:

## Portal A - Property Owner

Customer-facing functions:

- Dashboard
- My Properties
- My Units
- Service Requests
- Appointments
- Announcements
- Documents
- Notifications
- Profile

## Portal B - Operations

Operational functions for:

- Property Management Staff
- Building Manager
- Maintenance Coordinator
- Contractor
- Technician
- Cleaner
- Plumber
- Electrician
- Aircond Technician
- Other service providers

Functions include:

- Dashboard
- Assigned Jobs
- Work Orders
- Schedule
- Job Details
- Check-in / Check-out
- Progress Updates
- Photo Upload
- Completion
- Notifications
- Profile

The application determines the available portal after authentication.

---

# 5. User and Device Model

A user may have:

- one role
- multiple roles
- multiple devices
- multiple active sessions

Example:

```text
John Lim

Roles:
- PROPERTY_OWNER
- CONTRACTOR

Devices:
- iPhone
- Android Tablet
```

The user may select the appropriate portal after login.

FCM registration must be associated with the authenticated H-Care user.

---

# 6. Device Registration Flow

When the mobile application starts:

```text
Open App
    |
Check Authentication
    |
Login / Existing Session
    |
Initialize Firebase
    |
Request Notification Permission
    |
Obtain FCM Registration Token
    |
Send Token to Laravel API
    |
Laravel validates authenticated user
    |
Store / Update Device Record
    |
Device becomes eligible for push notifications
```

The application must refresh and re-register the token when Firebase provides a new token.

Do not assume an FCM token is permanent.

---

# 7. Device Token Database

Recommended table:

## user_devices

Fields:

```text
id
user_id
device_uuid
platform
fcm_token
firebase_installation_id
device_name
device_model
os_version
app_version
last_seen_at
last_token_refresh_at
is_active
created_at
updated_at
```

### Example

```text
User:
Alex Low

Device:
iPhone 16 Pro

Platform:
ios

FCM Token:
<device-specific-token>

App Version:
1.0.0

Status:
Active
```

One user can have multiple records.

---

# 8. Device Registration API

Example:

```text
POST /api/v1/mobile/devices/register
```

Request:

```json
{
  "device_uuid": "device-uuid",
  "platform": "ios",
  "fcm_token": "FCM_DEVICE_TOKEN",
  "firebase_installation_id": "FIREBASE_INSTALLATION_ID",
  "device_name": "iPhone 16 Pro",
  "device_model": "iPhone17,1",
  "os_version": "19.x",
  "app_version": "1.0.0"
}
```

Response:

```json
{
  "success": true,
  "message": "Device registered successfully"
}
```

Required behavior:

- authenticate the user
- validate token
- upsert device record
- deactivate obsolete duplicate device records when appropriate
- update last-seen timestamp

---

# 9. Push Notification Permission

The application must request permission according to the operating system.

## iOS

The user must explicitly grant notification permission.

The application must configure:

- Push Notifications capability
- APNs integration
- Firebase Messaging
- APNs authentication key / required Firebase configuration

FCM delivers Apple-platform notifications through APNs.

## Android

The application must support Android notification permission requirements for supported Android versions.

Notification channels should be configured for Android notification categories.

---

# 10. Firebase / APNs Configuration

For iOS:

1. Create the iOS application in Firebase.
2. Register the iOS bundle identifier.
3. Add the Firebase configuration file.
4. Enable Push Notifications in Xcode.
5. Configure APNs authentication with Firebase.
6. Configure Firebase Messaging.
7. Test on a physical Apple device.

For Android:

1. Register the Android application in Firebase.
2. Configure the Android application identifier.
3. Add the Firebase configuration file.
4. Configure Firebase Messaging.
5. Configure notification channels.
6. Test on physical Android devices.

The exact Firebase setup must follow the current official Firebase documentation.

---

# 11. Notification Architecture

Business event:

```text
Service Request Created
        |
Laravel Event
        |
Notification Listener
        |
Determine Recipients
        |
Build Notification
        |
Create Notification History
        |
Queue Notification
        |
Firebase Cloud Messaging
        |
Mobile Device
```

The business transaction must not depend on the FCM delivery completing synchronously.

Recommended:

```text
Business Transaction
       |
Commit Database Transaction
       |
Dispatch Notification Job
       |
Queue Worker
       |
Send to FCM
```

This prevents slow notification delivery from blocking normal system operations.

---

# 12. Laravel Notification Engine

Create a centralized notification service.

Suggested components:

```text
NotificationService
NotificationRecipientResolver
NotificationBuilder
FirebaseMessagingService
NotificationQueue
NotificationPreferenceService
NotificationHistoryService
```

The application should not place FCM sending logic directly inside controllers.

Bad:

```text
ServiceRequestController
    -> directly send FCM
```

Preferred:

```text
ServiceRequestController
    -> create business event
    -> dispatch notification job
    -> NotificationService
    -> FCM
```

---

# 13. Notification Recipients

H-Care must support recipient resolution based on business relationships.

Possible targets:

## Individual User

Example:

```text
User ID = 1025
```

## Multiple Users

Example:

```text
Users = [1025, 1026, 1027]
```

## Role

Example:

```text
PROPERTY_MANAGER
MAINTENANCE_COORDINATOR
CONTRACTOR
PROPERTY_OWNER
```

## Property

Example:

```text
Property = MUZE
```

All eligible users associated with the property may receive the notification.

## Block

Example:

```text
Property = MUZE
Block = A
```

## Unit

Example:

```text
Property = MUZE
Unit = A-15-08
```

## Contractor Company

Example:

```text
ABC Aircond Services
```

## Assigned Work Order

Send only to the contractor / staff assigned to the work order.

---

# 14. Important Rule: Do Not Rely Only on FCM Topics

FCM topics can be useful for broad broadcasts, but H-Care should maintain its own recipient logic.

Example:

```text
Property:
MUZE

Block:
A

Unit:
A-15-08

Owner:
Alex Low

Tenant:
John Tan

Contractor:
ABC Aircond Services
```

Laravel knows these relationships.

Laravel should determine the intended recipients first.

FCM is the delivery mechanism.

This prevents business authorization logic from being hidden inside Firebase topic subscriptions.

---

# 15. Notification Payload

H-Care should use a notification payload together with structured data where appropriate.

Example:

```json
{
  "notification": {
    "title": "Service Request Updated",
    "body": "Your aircond service request has been completed."
  },
  "data": {
    "notification_id": "NTF000123",
    "notification_type": "SERVICE_REQUEST_COMPLETED",
    "entity_type": "service_request",
    "entity_id": "SR000567",
    "portal": "OWNER",
    "deep_link": "hcare://service-request/SR000567"
  }
}
```

Do not place sensitive personal, financial, or confidential information in the push payload.

The notification should contain only the minimum information required to display the alert and identify the destination.

The mobile application should retrieve detailed information from the H-Care API after opening the relevant screen.

---

# 16. Deep Linking

Notifications must support deep linking.

Example:

```text
Push Notification
      |
User taps
      |
H-Care Mobile App opens
      |
Authenticate session
      |
Validate permission
      |
Open Service Request
      |
GET /api/v1/service-requests/SR000567
```

Examples:

```text
hcare://service-request/SR000567
hcare://work-order/WO000123
hcare://announcement/ANN00045
hcare://appointment/APP000123
hcare://unit/UNIT000456
hcare://document/DOC000123
```

The mobile application must not assume that the user still has permission to access the object.

Every deep link must be authorized against the current user.

---

# 17. Notification Types

## Owner Notifications

### Service Request

- Request Submitted
- Request Approved
- Contractor Assigned
- Appointment Scheduled
- Work Started
- Work Delayed
- Work Completed
- Request Closed
- Request Reopened

### Property

- New Announcement
- Property Notice
- Facility Closure
- Water Disruption
- Lift Maintenance
- Emergency Alert

### Tenancy

- Lease Expiry Reminder
- Renewal Reminder
- Tenancy Update

### Documents

- New Document
- Document Updated
- Document Expiring

### Appointments

- Appointment Created
- Appointment Confirmed
- Appointment Rescheduled
- Appointment Cancelled
- Appointment Reminder

---

# 18. Operations Notifications

### Work Order

- New Job Assigned
- Job Accepted
- Job Rejected
- Job Rescheduled
- Job Cancelled
- Job Escalated
- Job Started
- Job Completed

### Maintenance

- Urgent Maintenance
- Inspection Required
- Preventive Maintenance Due

### Internal

- New Assignment
- Schedule Change
- Management Announcement
- Emergency Alert

---

# 19. Notification Priority

Recommended categories:

| Type | Priority |
|---|---|
| Information | Low |
| General Announcement | Normal |
| Reminder | Normal |
| Action Required | High |
| Warning | High |
| Emergency | Critical |

Do not classify every notification as high priority.

Emergency notifications should be reserved for genuine urgent situations.

---

# 20. Notification Channels - Android

Recommended notification channels:

```text
GENERAL
SERVICE_REQUEST
WORK_ORDER
APPOINTMENT
ANNOUNCEMENT
EMERGENCY
```

Users can control notification channel behavior through Android system settings.

---

# 21. iOS Notification Categories

Use appropriate notification categories/actions where useful.

Example:

```text
WORK_ORDER_ASSIGNED

Actions:
- View Job
```

Owner:

```text
SERVICE_REQUEST_COMPLETED

Action:
- View Request
```

Avoid excessive interactive actions. Important actions should normally open the relevant H-Care screen.

---

# 22. Notification History

H-Care must maintain its own notification inbox.

Recommended table:

## notifications

```text
id
notification_no
user_id
type
category
priority
title
body
entity_type
entity_id
portal
deep_link
status
sent_at
delivered_at
read_at
failed_at
failure_reason
created_at
updated_at
```

Example:

```text
Notification No:
NTF000123

User:
Alex Low

Type:
SERVICE_REQUEST_COMPLETED

Title:
Service Request Completed

Body:
Your aircond service request has been completed.

Entity:
service_request / SR000567

Portal:
OWNER

Status:
READ
```

---

# 23. Notification Status

Recommended statuses:

```text
PENDING
QUEUED
SENT
DELIVERED
READ
FAILED
CANCELLED
```

Important:

FCM acceptance does not necessarily mean the user has read the notification.

Therefore:

```text
SENT != DELIVERED != READ
```

These should be treated as different states.

---

# 24. Notification Preferences

Users should be able to configure notification categories.

## Owner Example

```text
Announcements          ON
Service Requests       ON
Appointments            ON
Lease Reminders         ON
Documents               ON
Maintenance Notices     ON
Marketing               OFF
```

## Operations Example

```text
New Work Orders         ON
Job Changes             ON
Job Cancellations       ON
Schedule Updates        ON
Emergency Alerts        ON
```

Emergency notifications may be forced ON depending on business policy.

---

# 25. Business Event Examples

## Example 1 - Owner Creates Service Request

```text
Owner
  |
Create Service Request
  |
Laravel creates SR000567
  |
Event: ServiceRequestCreated
  |
Determine recipients
  |
Property Management / Customer Service
  |
Create notification records
  |
Queue
  |
FCM
  |
Operations mobile devices
```

---

# 26. Example 2 - Contractor Assigned

```text
Property Manager
       |
Assign SR000567
       |
System creates assignment
       |
Event: WorkOrderAssigned
       |
Find contractor user
       |
Check notification preference
       |
Create notification
       |
FCM
       |
Contractor phone
```

Notification:

```text
New Job Assigned

Aircond service required at MUZE
Block A, Unit A-15-08.

Tap to view job.
```

---

# 27. Example 3 - Contractor Completes Job

```text
Contractor
    |
Complete Work Order
    |
Laravel validates completion
    |
Event: WorkOrderCompleted
    |
Find owner
    |
Create notification
    |
FCM
    |
Owner phone
```

Notification:

```text
Service Completed

Your aircond service request has been completed.

Tap to view details.
```

---

# 28. Example 4 - Property Announcement

Property management publishes:

```text
Water Supply Interruption
```

Target:

```text
Property = MUZE
Block = A
```

Laravel resolves all eligible users associated with Block A.

Then:

```text
Laravel
  |
Recipient Resolver
  |
Users 1001, 1002, 1003...
  |
Notification Records
  |
FCM
  |
Devices
```

---

# 29. Example 5 - Emergency Notification

Emergency:

```text
Fire Alarm Activated
Block B
```

Target:

```text
All eligible users in MUZE
```

Priority:

```text
CRITICAL
```

The notification should be sent immediately.

The application should provide a clear action such as:

```text
View Emergency Information
```

---

# 30. Queue Processing

Push notifications should use Laravel queues.

Recommended flow:

```text
Database Transaction
        |
Event
        |
Queue Notification Job
        |
Redis / Queue
        |
Laravel Worker
        |
Firebase
```

This allows high-volume notifications without slowing down normal web/API transactions.

---

# 31. Bulk Notifications

For large properties, the system may need to notify hundreds or thousands of users.

The backend should:

- resolve recipients
- remove duplicate users
- remove inactive devices
- batch messages
- queue delivery
- record results
- retry transient failures

Do not send thousands of notifications inside a single HTTP request.

---

# 32. Retry Handling

If Firebase returns a temporary failure:

```text
Attempt 1
   |
Failed
   |
Retry
   |
Attempt 2
   |
Retry
   |
Attempt 3
```

After maximum retry attempts:

```text
FAILED
```

Store the failure reason.

Permanent invalid-device-token errors should cause the device record to be marked inactive or otherwise removed from future targeting.

---

# 33. Multi-Device Delivery

Example:

```text
Alex Low

iPhone
Android Tablet
iPad
```

A notification may be sent to all active devices.

However, H-Care should avoid creating duplicate in-app notification records for the same user.

Conceptually:

```text
1 Business Notification
        |
3 Device Deliveries
        |
1 User Notification History
```

Device-level delivery details can be stored separately if detailed delivery analytics are required.

---

# 34. Recommended Additional Table

## notification_deliveries

```text
id
notification_id
user_device_id
provider
provider_message_id
status
sent_at
delivered_at
failed_at
failure_code
failure_reason
created_at
updated_at
```

This separates:

```text
Notification
```

from:

```text
Device Delivery
```

This is important when one user owns multiple devices.

---

# 35. Notification Templates

Do not hard-code notification wording throughout the application.

Create notification templates.

Example:

```text
SERVICE_REQUEST_COMPLETED
```

Template:

```text
Title:
Service Request Completed

Body:
Your service request {request_no} has been completed.
```

Variables:

```text
{request_no}
{property_name}
{unit_no}
{category}
```

This makes notifications easier to maintain and potentially support multiple languages later.

---

# 36. Notification Localization

Future support:

```text
English
Bahasa Malaysia
Chinese
```

Templates should be designed so notification content can be localized.

Do not store only a final English sentence if multilingual support is expected.

---

# 37. Notification Audit

Administrators should be able to see:

```text
Notification
    |
Recipient
    |
Device
    |
Sent
    |
Delivery
    |
Read
```

Reports:

- Total Sent
- Total Delivered
- Total Failed
- Total Read
- Delivery Rate
- Read Rate
- Notification Category
- Notification Volume
- User
- Property
- Date Range

---

# 38. Security Requirements

Never send:

- IC/passport numbers
- Bank account numbers
- Passwords
- Full financial statements
- Sensitive documents
- Private personal information

inside the push payload.

Use:

```text
"Your document is ready."
```

rather than sending the document contents.

The user taps the notification and the application retrieves the protected document through the authenticated H-Care API.

---

# 39. Authentication and Authorization

FCM does not replace H-Care authentication.

The sequence is:

```text
FCM Notification
       |
User taps
       |
H-Care App
       |
Check Login Session
       |
Check API Authentication
       |
Check Authorization
       |
Retrieve Data
```

A notification must never grant access to a resource.

---

# 40. Portal Security

Because the same app supports Owner and Operations users, notification deep links must include portal context where necessary.

Example:

```text
portal = OWNER
```

or

```text
portal = OPERATIONS
```

However, the backend must still verify the user's current permissions.

Example:

A user may previously have been a contractor but later lose contractor access.

The notification may still exist on the device, but tapping it must result in:

```text
Access Denied
```

or redirect to an appropriate screen.

---

# 41. FCM Topics

Topics may be used for suitable broadcast scenarios.

Potential topics:

```text
property_MUZE
property_MUZE_block_A
announcements_MUZE
emergency_MUZE
```

However, do not use topics as the primary authorization mechanism.

Sensitive or user-specific notifications should be sent using user/device targeting controlled by Laravel.

---

# 42. Firebase Admin / Server Integration

Laravel should communicate with FCM through a trusted server-side integration using Firebase's current server APIs / Admin SDK approach.

Credentials must remain on the server.

Never place Firebase server credentials inside the mobile application.

Recommended:

```text
Mobile App
    |
FCM SDK
    |
FCM
```

and:

```text
Laravel Server
    |
Firebase server authentication
    |
FCM
```

The mobile application must never contain server-side Firebase credentials.

---

# 43. Environment Configuration

Example conceptual configuration:

```text
FIREBASE_PROJECT_ID=
FIREBASE_CREDENTIALS=
FIREBASE_MESSAGING_ENABLED=true
```

Production secrets must be stored securely.

Do not commit credentials to Git.

Do not put service account JSON files in public web directories.

---

# 44. Testing Requirements

Testing must cover:

## Device Registration

- New device
- Existing device
- Token refresh
- Logout
- Re-login
- Multiple devices

## Notification Delivery

- Android foreground
- Android background
- Android terminated
- iOS foreground
- iOS background
- iOS terminated

## Deep Linking

- Service Request
- Work Order
- Announcement
- Appointment
- Document
- Unit

## Permissions

- Owner
- Contractor
- Property Management
- Multi-role user
- Revoked role

## Failure

- Invalid token
- Offline device
- Firebase failure
- Expired session
- Deleted record
- Unauthorized resource

---

# 45. Important Mobile Behavior

The app must distinguish between:

```text
Foreground
Background
Terminated
```

The behavior of notification and data payloads differs by platform and app state.

The mobile implementation must therefore define explicit handling for all three states.

Do not assume that a notification payload behaves identically on iOS and Android.

---

# 46. Recommended Notification UX

When notification arrives:

```text
[H-Care Icon]

Service Request Completed

Your aircond service request at
MUZE A-15-08 has been completed.

Tap to view
```

When tapped:

```text
Open H-Care
      |
Authenticate
      |
Resolve Deep Link
      |
Service Request Detail
```

---

# 47. Notification Centre in Mobile App

The app should have an in-app notification centre.

Example:

```text
Notifications

Today

Service Request Completed
10:35 AM

New Announcement
9:10 AM

Yesterday

Appointment Reminder
4:30 PM
```

Functions:

- Read / unread
- Mark all as read
- Filter
- Open notification
- Delete / archive if required

---

# 48. Web Notification Management

The H-Care web application should allow authorized staff to:

- Create announcements
- Send notifications
- Select target property
- Select block
- Select audience
- Select notification category
- Set priority
- Schedule notification
- Preview notification
- View delivery results

Example:

```text
Create Notification

Title:
Lift Maintenance

Message:
Lift A will be unavailable tomorrow from 9:00 AM to 12:00 PM.

Target:
MUZE

Block:
A

Audience:
Owners + Tenants

Priority:
Normal

Schedule:
10-Aug-2026 18:00
```

---

# 49. Scheduled Notifications

The system should support scheduled notifications.

Examples:

```text
Appointment Reminder
24 hours before

Lease Expiry
90 days before

Lease Expiry
30 days before

Maintenance Appointment
24 hours before

Inspection
2 hours before
```

Laravel Scheduler / queued jobs should generate these notifications.

---

# 50. Notification Lifecycle

The complete H-Care notification lifecycle should be:

```text
BUSINESS EVENT
      |
      v
RECIPIENT RESOLUTION
      |
      v
USER PREFERENCE CHECK
      |
      v
CREATE NOTIFICATION
      |
      v
CREATE DELIVERY RECORDS
      |
      v
QUEUE
      |
      v
FCM
      |
      v
DEVICE
      |
      v
USER TAPS
      |
      v
DEEP LINK
      |
      v
AUTHORIZATION
      |
      v
OPEN H-CARE SCREEN
      |
      v
MARK AS READ
```

---

# 51. Recommended H-Care Notification Module

The backend should have a dedicated notification subsystem:

```text
Notification Management
|
+-- Notification Types
+-- Notification Templates
+-- Notification Preferences
+-- User Devices
+-- Notification History
+-- Notification Deliveries
+-- Notification Queue
+-- Notification Logs
+-- Scheduled Notifications
+-- Broadcast Notifications
+-- Notification Analytics
```

---

# 52. Technology Summary

## Backend

```text
Laravel 13
PHP 8.3+
PostgreSQL
Laravel Queue
Redis (recommended)
```

## Mobile

```text
Single H-Care Mobile App
iOS
Android
Owner Portal
Operations Portal
```

## Push Notification

```text
Firebase Cloud Messaging
        |
        +-- Android
        |
        +-- APNs -> iOS
```

## API

```text
REST API
JSON
HTTPS
Token Authentication
Role-Based Authorization
```

---

# 53. Official Firebase References

Use the current Firebase documentation as the implementation authority:

- Firebase Cloud Messaging overview
- Firebase Android setup and message handling
- Firebase Apple platform setup and APNs configuration
- FCM message types
- FCM server-side sending
- FCM topic messaging

The Firebase documentation should be checked during implementation because Firebase APIs, supported platform versions, and recommended server integration methods can change.

---

# 54. Key Design Decisions

The H-Care implementation should follow these principles:

1. One H-Care mobile application for iOS and Android.
2. Owner and Operations portals are separate UI experiences inside the same app.
3. Laravel 13 is the source of business logic.
4. PostgreSQL is the source of notification history and device records.
5. FCM is the push delivery service.
6. Laravel determines recipients.
7. FCM does not determine authorization.
8. Push payloads contain minimal information.
9. Detailed data is retrieved through authenticated APIs.
10. Every notification is recorded in H-Care.
11. Every device is independently registered.
12. One user may have multiple devices.
13. Notification preferences are controlled by H-Care.
14. Notifications support deep links.
15. Notification sending should use queues.
16. Failed deliveries must be tracked.
17. Invalid device tokens must be deactivated.
18. Emergency notifications require special handling.
19. Production Firebase credentials must remain server-side.
20. The design must support future email, SMS, WhatsApp, and AI notification channels.

---

# 55. Future Notification Channels

FCM should not become the only notification architecture.

Design H-Care's notification engine so that FCM is one delivery channel.

Future architecture:

```text
                    H-Care Notification Engine
                              |
       +----------+-----------+-----------+----------+
       |          |                       |          |
      FCM       Email                    SMS      WhatsApp
       |
  iOS / Android
```

The business event should not care which channel is used.

Example:

```text
Lease Expiring
      |
Notification Engine
      |
+-----+---------+---------+
|               |         |
Push           Email      WhatsApp
```

This allows H-Care to add additional communication channels later without redesigning the core property management modules.
