Skip to content
ReferenceForDeveloper⏱ About 10 min

Notifications and messages ​

BMA has one notification service for everything: a module, a cron task, a background job, a console command, an App Builder workflow or the shell itself posts to it, and every person sees their own notifications under the bell in the top bar (what people see). Messages are threads between members of one organization, plus system messages with replies off.

Notifications belong to a person in one organization: the same person in two organizations has two lists. Nothing here takes a person or an organization from a request: the HTTP routes use the session, and server code names them.

A notification ​

FieldValues
kindinfo (default), success, warning, error, message (messages only)
titlerequired, plain text, at most 160 characters (longer is cut)
bodyoptional plain text, at most 2000 characters (longer is cut); line breaks kept; always shown escaped, never as HTML
linkoptional: an in-app route (/sawscore/applications/3, opens in a workspace tab) or an https:// address (opens a browser tab). Anything else (http:, javascript:, //host) is refused
sourcewho sent it: core, cron:<job>, job:<name>, module:<id>, app:<code>. Set for you by the sender helpers below
dedupe_keyoptional, at most 120 characters. A repeat with the same key for the same person and organization updates their unread one (title, body, link, kind, time; repeat_count + 1, shown as ×2, ×3) instead of adding a line. Once read, the next one is a new line
expires_in / expires_atoptional: seconds (60 to 365 days), or a time; hidden after it and deleted by the cleanup task
emailoptional false: never an e-mail copy. Otherwise the person's own choice decides (below)
as_messageoptional true: also start a system message thread (replies off) with the same recipients; the notification is then kind message and links to /messages/<id>

Read notifications are deleted after 30 days, unread ones after 180 (config notifications.keep_read_days / keep_unread_days in config/app.php).

From PHP ​

appcenter-next/api/lib/Notify.php is loaded with the API (requests, bin/cron-run.php, bin/console scripts, module code). Each call returns the ids of the rows written (new ones, and unread ones a dedupe_key updated).

php
Notify::user($tenantId, $userId, $n);              // one member
Notify::users($tenantId, array $userIds, $n);      // several members
Notify::group($tenantId, $groupId, $n);            // members whose group in that organization is $groupId
Notify::permission($tenantId, 'sawscore.decide', $n); // members whose group holds the permission (and group 1)
Notify::organization($tenantId, $n);               // every active member
Notify::staff($n);                                 // platform staff (members of the Platform organization)
Notify::platform('all', $n);                       // every active member of every active organization
Notify::platform(array(12, 15), $n);               // ... of the chosen organizations

Recipients are worked out when you post: only active members of that organization, never anyone else; someone who joins the group later does not get earlier notifications. At most 2000 people per call in one organization (20,000 for Notify::platform); more throws and writes nothing.

A refused notification throws NotifyException ($e->errorCode: invalid_kind, invalid_title, invalid_link, invalid_source, invalid_dedupe_key, invalid_expiry, invalid_target, too_many_recipients). A notification should never stop your work: catch Exception around it in tasks and hooks.

Senders with a fixed source ​

php
Notify::cron('Nightly export')->staff($n);                 // source cron:nightly-export
Notify::job('bureau-import')->user($tid, $uid, $n);        // source job:bureau-import (jobs, console commands)
Notify::module('sawscore')->permission($tid, 'sawscore.decide', $n); // source module:sawscore
Notify::app('leads')->group($tid, $groupId, $n);           // source app:leads

Each returns a sender with user, users, group, permission, organization and staff. The sender's source replaces any source in $n.

Example: a cron task that fails ​

BMA's own cron does this: when a job fails, platform staff get one line per job, however often it fails.

php
Notify::cron($job['name'])->staff(array(
    'kind' => 'error',
    'title' => 'Scheduled job failed: ' . $job['name'],
    'body' => 'Last error: ' . $message,
    'link' => '/admin/cron',
    'dedupe_key' => 'cron-failed:' . $job['job_id'],
));

Example: a module's scheduled task ​

php
class MyModuleHooks extends ModuleHooksBase implements ModuleTaskRunner
{
    public function task($task, array $ctx)
    {
        $late = my_module_late_deals($ctx['tenant_id']);
        if ($late) {
            try {
                Notify::module('my-module')->permission($ctx['tenant_id'], 'my-module.manage', array(
                    'kind' => 'warning',
                    'title' => count($late) . ' deals are late',
                    'link' => '/my-module/deals?late=1',
                    'dedupe_key' => 'late-deals',
                ));
            } catch (Exception $e) {
                error_log('my-module: ' . $e->getMessage());
            }
        }
        return 'late ' . count($late);
    }
}

Modules post only through Notify (and NotifyMessages); they never read or write the notification tables.

Messages ​

php
// A conversation started by a member (they and the recipients can reply; everyone else is told):
$threadId = NotifyMessages::start($tenantId, $senderUserId, array($userA, $userB), 'Subject', "Text\nmore text");
NotifyMessages::reply($tenantId, $userId, $threadId, 'A reply');

// A system message with replies off, to a group (also a notification of kind message):
Notify::module('my-module')->group($tenantId, $groupId, array('title' => 'New price list', 'body' => '…', 'as_message' => true));

Each new message tells the other members with one notification per thread (dedupe_key thread:<id>); opening the thread marks it read. Subjects are at most 160 characters, messages 4000, plain text.

From the command line ​

bash
php bin/console notify:send --tenant=pinecrest-motors --group=Sales --kind=warning \
    --title="Bureau import is late" --link=/sawscore/applications --dedupe=bureau-late --source=bureau-import
php bin/console notify:send --staff --kind=error --title="Backup failed on db2"
php bin/console notify:send --platform=all --title="Maintenance Sunday 2-3 am" --expires-in=86400

Recipients: --tenant=<id|code> with --user=<id|name>, --group=<id|name>, --permission=<key> or --organization; or --staff; or --platform=all|<code,code>. --message also starts a system message, --no-email never e-mails, --json prints the ids. The source is job:<--source> (default job:console).

From App Builder workflows ​

Add a Notify node to a workflow. Send to: the person running it, a user, a group, everyone with a permission, or everyone in the organization (this organization only); then kind, title, text, link and dedupe key, each with {{…}} placeholders ({{input.customer}}, {{vars.query_rows_count}}). The source is app:<workflow code>; the run log shows how many people it reached (vars.notified). A scheduled run has no "person running it".

From a module screen (the shell) ​

Runtime modules get host.notify (check that it exists: an older host has none):

ts
if (host.notify) {
  await host.notify.post({ kind: 'success', title: 'Export ready', link: '/m/my-module/exports/7' })
  const n = host.notify.unreadCount()    // the bell's count
  const m = host.notify.unreadMessages() // unread message threads
  await host.notify.refresh()            // after your own API posted something for this person
}

post reaches the signed-in person only (source module:<your id>), is never e-mailed, and allows 30 a minute. To tell anyone else, post from your module's API code. The full contract is in appcenter-next/docs/modules/AUTHORING.md §7.

HTTP API (the signed-in person, session organization) ​

CallDoes
GET /me/notifications?page=1&per_page=20&unread=1{items, total, unread, unread_messages, page, per_page, can_announce}; unread first, then newest; expired ones left out
GET /me/notifications/count{unread, unread_messages} (the bell polls this at most once a minute while visible)
POST /me/notifications{kind?, title, body?, link?, module?}: a notification to oneself (host.notify.post)
POST /me/notifications/{id}/readmark one read (404 when it is not yours)
POST /me/notifications/read-all{marked}
DELETE /me/notifications/{id}remove one
GET / PUT /me/notifications/settings{email_kinds}: the kinds e-mailed to you in this organization
GET /me/messagesyour threads, newest first, with unread, can_broadcast, can_send
GET /me/messages/recipients?q=members to write to (and groups, with notifications.broadcast)
POST /me/messages{to: {users: [ids], groups: [ids], organization: bool}, subject, body} → {thread_id, recipients}
GET /me/messages/{id}a thread (its newest 200 messages and members); marks it read (?peek=1 does not)
POST /me/messages/{id}{body}: reply (409 replies_off for system messages)
POST /me/messages/{id}/readmark a thread read
POST /admin/announcementsplatform staff: {title, body?, kind?, link?, tenants: "all" | [ids], expires_in_days?}

Writing to a group or the whole organization needs notifications.broadcast (or tenant admin); announcements need platform.announce, working in the Platform organization. While staff view as another user, nothing is written (403 impersonating).

E-mail copies ​

People choose which kinds they also get by e-mail, per organization, in My account; by default only error. Copies are queued when the notification is posted (only for people who chose that kind and have an address) and sent by the cron task Notification e-mail every 5 minutes, at most 100 a run, through the platform's mail settings. A copy is skipped when the notification was read first, tried up to 3 times, and dropped after a day (so nothing floods out the day e-mail is switched on). Nothing is ever sent inside a request. Pass 'email' => false for notifications that must never be e-mailed.