Planora

Intelligent Alert & Task Management

API Documentation
Instructions for interacting with the AlertSync API.

Planora Webhook API: מדריך למפתחי base44



מסמך זה מסביר כיצד לשלב את אפליקציית base44 עם שירות Planora לצורך שליחת התראות Push למשתמשים באמצעות OneSignal.

⚙️ זרימת העבודה (ארכיטקטורה מומלצת)



הארכיטקטורה מבוססת על שימוש ב-iframe שקוף וב-postMessage כדי לבדוק סטטוס רישום של מכשיר ולקשר אותו למשתמש, ללא צורך בהפניות (redirects) הגלויות למשתמש.

1. **בדיקה ורישום שקט (באחריות Planora):**
* אפליקציית base44 טוענת iframe נסתר המצביע לדף ייעודי ב-Planora.
* דף זה מאתחל את ה-SDK של OneSignal במצב "שקט" ובודק אם קיים playerId עבור המכשיר הנוכחי.
* Planora שומר את מזהה המכשיר (playerId, אם קיים) בבסיס הנתונים שלו, משויך ל-userId שהועבר.
* בסיום, הדף ב-iframe שולח הודעה (postMessage) בחזרה לאפליקציית base44 עם סטטוס הרישום ו-playerId.

2. **תזמון התראה (באחריות base44):**
* כאשר מערכת base44 רוצה לשלוח התראה למשתמש, היא שולחת בקשת POST ל-Webhook של Planora, תוך שימוש ב-userId של המשתמש.

3. **שליחה על ידי Planora:**
* שירות Planora מקבל את הבקשה. בזמן השליחה, הוא מחפש בבסיס הנתונים שלו איזה playerId משויך ל-userId שהתקבל, ושולח את ההתראה דרך ה-API של OneSignal.

---

🚀 שלב 1: הטמעת רישום שקט באמצעות iframe



כדי לבדוק את סטטוס הרישום של מכשיר המשתמש באופן שקוף, יש להטמיע את הקוד הבא באפליקציית הלקוח (base44). הקוד יוצר iframe נסתר, מאזין להודעות ממנו, ומסיר אותו בסיום.

**החלף את USER_ID_FROM_YOUR_SYSTEM במזהה הייחודי של המשתמש במערכת base44.**

<!-- דוגמה להטמעה באפליקציית הלקוח (base44) -->

<script>
function checkDeviceRegistration(userId) {
return new Promise((resolve, reject) => {
const planoraHost = 'https://studio--planoraaleret-62152057-8e5b6.us-central1.hosted.app';
// ה-URL מכוון לדף ייעודי ב-Planora שמבצע בדיקה שקטה
const iframeUrl = `${planoraHost}/silent-push-check?userId=${encodeURIComponent(userId)}&origin=${encodeURIComponent(window.location.origin)}`;

const iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.src = iframeUrl;

const timeout = setTimeout(() => {
cleanup();
reject(new Error('Timeout: No response from Planora iframe.'));
}, 10000); // 10-second timeout

const messageHandler = (event) => {
// ודא שההודעה הגיעה מהמקור הנכון (ה-iframe של Planora)
if (event.origin !== planoraHost) {
return;
}

if (event.data?.type === 'PLANORA_PUSH_STATUS') {
console.log('Received push status from Planora:', event.data);
cleanup();
resolve(event.data);
}

if (event.data?.type === 'PLANORA_PUSH_ERROR') {
console.error('Error from Planora iframe:', event.data.message);
cleanup();
reject(new Error(event.data.message));
}
};

const cleanup = () => {
clearTimeout(timeout);
window.removeEventListener('message', messageHandler);
document.body.removeChild(iframe);
};

window.addEventListener('message', messageHandler);
document.body.appendChild(iframe);
});
}

// --- אופן השימוש ---
// החלף את 'user_12345' במזהה המשתמש האמיתי
checkDeviceRegistration('user_12345')
.then(status => {
// status יכיל: { type, userId, playerId, isSubscribed }
if (status.isSubscribed && status.playerId) {
console.log(`Device is registered with Player ID: ${status.playerId}`);
// שמור את ה-playerId ב-localStorage או ב-state של האפליקציה
} else {
console.log('Device is not subscribed.');
// כעת תוכל להציג למשתמש כפתור "הירשם להתראות"
// לחיצה על כפתור זה תוביל לדף הרישום האקטיבי
}
})
.catch(error => {
console.error('Failed to check device registration:', error);
});

</script>

### **רישום אקטיבי (אם המשתמש לא רשום)**

אם הבדיקה השקטה מגלה שהמשתמש אינו רשום (isSubscribed: false), יש להציג לו כפתור "הפעל התראות". לחיצה על הכפתור צריכה להפנות אותו לדף הרישום האקטיבי של Planora.

https://studio--planoraaleret-62152057-8e5b6.us-central1.hosted.app/register?userId=USER_ID_FROM_YOUR_SYSTEM&returnUrl=URL_ENCODED_RETURN_URL

לאחר שהמשתמש יאשר (או ידחה) את ההרשאה, הוא יוחזר ל-returnUrl עם הפרמטרים device_registered ו-player_id בכתובת.

---

🧐 שלב 1.5 (אופציונלי): בדיקת סטטוס רישום מהשרת



לפני תזמון התראה, ניתן לבדוק האם למשתמש מסוים יש לפחות מכשיר אחד רשום במערכת.

### Endpoint

- **URL**: https://studio--planoraaleret-62152057-8e5b6.us-central1.hosted.app/api/devices/status/[userId]
- **Method**: GET
- **URL Params**:
- userId (string, required): The unique user ID from your base44 system.

### Authentication

הנקודה מוגנת באמצעות מפתח API. יש לכלול את המפתח בהידר x-api-key.

- **Header Name**: x-api-key
- **Value**: AIzaSyC0n-Rfy4FtI4_S_D6inv1qsayoE8U8gM4

### תגובה (Response)

גוף התגובה יכיל אובייקט JSON עם המידע הבא:

FieldTypeDescription
isRegisteredbooleantrue אם למשתמש יש לפחות מכשיר אחד רשום, אחרת false.
deviceCountnumberמספר המכשירים הרשומים עבור המשתמש.

#### דוגמת תגובה (משתמש רשום)

{
"isRegistered": true,
"deviceCount": 2
}

#### דוגמת פקודת curl

# Replace user_101 with the actual User ID you want to check
curl -X GET \
-H "x-api-key: AIzaSyC0n-Rfy4FtI4_S_D6inv1qsayoE8U8gM4" \
https://studio--planoraaleret-62152057-8e5b6.us-central1.hosted.app/api/devices/status/user_101

---


📬 שלב 2: תזמון התראה (Webhook)



לאחר שהמשתמש נרשם, תוכל לשלוח בקשה ל-Webhook של Planora כדי לתזמן עבורו התראה, **תוך שימוש ב-userId שלו**.

### Endpoint

- **URL**: https://studio--planoraaleret-62152057-8e5b6.us-central1.hosted.app/api/webhook
- **Method**: POST

### Authentication

הנקודה מוגנת באמצעות מפתח API. יש לכלול את המפתח בהידר x-api-key.

- **Header Name**: x-api-key
- **Value**: AIzaSyC0n-Rfy4FtI4_S_D6inv1qsayoE8U8gM4 (ניתן לשנות ב-.env של פרויקט Planora).

### Headers

- Content-Type: application/json
- x-api-key: AIzaSyC0n-Rfy4FtI4_S_D6inv1qsayoE8U8gM4

### Request Body Schema

FieldTypeRequiredDescription
userIdstringYesThe unique user ID from your base44 system.
alertTypestringYesThe type of the alert (e.g., "High Temperature", "Security Breach").
sendAtstringYesAn ISO 8601 formatted date-time string indicating when the alert should be sent.
providerstringNoThe notification provider. Can be 'onesignal' or 'firebase'. Defaults to 'onesignal' if not provided.
alertDetailsstringNoOptional detailed information about the alert.
appNamestringNoOptional name of the application sending the alert. This will be used as the push notification title. Defaults to "Planora Alert" if not provided.
webUrlstringNoOptional URL to open when the notification is clicked. Defaults to https://planora.app/ if not provided.
timestampstringNoAn ISO 8601 formatted date-time string for when the event occurred. If not provided, the server will use the current time.

#### דוגמת בקשה (Request Body)

{
"userId": "user_101",
"alertType": "Security Breach",
"alertDetails": "Unauthorized access attempt detected from IP 192.168.1.100.",
"sendAt": "2024-08-15T10:35:00Z",
"timestamp": "2024-08-15T10:30:00Z",
"appName": "Base44 Security",
"provider": "onesignal",
"webUrl": "https://aspaklaria.base44.app/dashboard/security"
}

### דוגמת פקודת curl

# Replace user_101 with the actual User ID from your system
# This example will send the notification via the 'onesignal' provider with a default URL
curl -X POST \
-H "Content-Type: application/json" \
-H "x-api-key: AIzaSyC0n-Rfy4FtI4_S_D6inv1qsayoE8U8gM4" \
-d '{
"userId": "user_101",
"alertType": "High Temperature",
"alertDetails": "CPU temperature has exceeded 90°C.",
"sendAt": "'$(date -u -v+1M +'%Y-%m-%dT%H:%M:%SZ')'",
"appName": "Base44",
"provider": "onesignal"
}' \
https://studio--planoraaleret-62152057-8e5b6.us-central1.hosted.app/api/webhook

---

### תגובות (Responses)

- **201Created:** הבקשה התקבלה בהצלחה וההתראה תוזמנה.
- **400 Bad Request:** גוף הבקשה אינו תקין או שחסרים שדות חובה.
- **401 Unauthorized:** המפתח x-api-key חסר או שגוי.
- **500 Internal Server Error:** שגיאה פנימית בשרת.

---

🗑️ שלב 3: הסרת רישום של מכשיר (Unregister)



ניתן להסיר רישום של מכשיר ספציפי מהמערכת (כולל מ-OneSignal) באמצעות ה-playerId שלו.

### Endpoint

- **URL**: https://studio--planoraaleret-62152057-8e5b6.us-central1.hosted.app/api/devices/[playerId]
- **Method**: DELETE
- **URL Params**:
- playerId (string, required): The OneSignal Player ID of the device to unregister.

### Authentication

הנקודה מוגנת באמצעות מפתח API. יש לכלול את המפתח בהידר x-api-key.

- **Header Name**: x-api-key
- **Value**: AIzaSyC0n-Rfy4FtI4_S_D6inv1qsayoE8U8gM4

### תגובות (Responses)

- **200 OK**: המכשיר הוסר בהצלחה.
- **401 Unauthorized**: המפתח x-api-key חסר או שגוי.
- **404 Not Found**: לא נמצא מכשיר עם ה-playerId שצוין.
- **500 Internal Server Error**: שגיאה פנימית בשרת.

### דוגמת פקודת curl

# Replace {playerId} with the actual Player ID you want to delete
curl -X DELETE \
-H "x-api-key: AIzaSyC0n-Rfy4FtI4_S_D6inv1qsayoE8U8gM4" \
https://studio--planoraaleret-62152057-8e5b6.us-central1.hosted.app/api/devices/{playerId}