Notifications, email, activity and live messages
Handbook · Coverage · Source reference
A notification row, an email, a websocket message and a webhook are different delivery mechanisms. Pulse provides each separately. Choose whether the user needs durable history, immediate UI updates or an external integration, then call the relevant service explicitly.
A method named newUserRegistered() does not establish that registration calls it. The event catalog and hook registry also do not prove delivery. Trace the caller as well as the service before promising automatic behavior.
Choose the right channel
| Mechanism | Stores history? | Primary destination | Main class |
|---|---|---|---|
| Player notification | Database row | One player's inbox | NotificationService |
| Admin notification | Separate database rows | Staff dashboard | AdminNotificationService |
| Activity | Database activity_logs |
Player/admin history | ActivityLogService |
| Mail transport/queue | External mailbox | DynamicEmail, EmailSetting |
|
| Websocket/polling | Short-lived cache plus broadcast transport | Active clients | WebSocketService |
| Generic webhook | Delivery records | Configured external HTTPS URL | WebhookService |
| Discord/Slack | No shared core delivery record | External workspace/channel | Dedicated webhook service |
An in-app row does not automatically send an email or broadcast. Add those behaviors deliberately, test them independently, and avoid sending secrets in payloads.
Player notification API
Use App\Core\Services\NotificationService from trusted backend or plugin code.
use App\Core\Models\User;
use App\Core\Services\NotificationService;
// Inside an authenticated plugin controller action:
$user = $request->user();
$notification = app(NotificationService::class)->system(
$user,
'Report ready',
'Your report is ready to read.',
['report_id' => 42]
);
Expected: one persisted Notification belonging to this user, with type system and an unread state. It does not create report 42, send mail or create a route. If you link to a plugin page, ensure the frontend route exists.
| Signature | Result/side effect |
|---|---|
create(User $user, string $type, string $title, string $message, ?array $data = null, ?string $icon = null, ?string $link = null): Notification |
Inserts row |
adminMessage(User $user, string $message, ?string $title = null): Notification |
admin_message, default title Admin Message |
message(User $user, string $from, int $messageId): Notification |
Message notice linking /messages/{id}; does not implement messaging itself |
announcement(User $user, string $title, string $message, ?string $link = null): Notification |
Announcement row |
system(User $user, string $title, string $message, ?array $data = null): Notification |
System row |
getAll(User $user, int $limit = 50): Collection |
Newest rows for user |
getUnread(User $user, int $limit = 50): Collection |
Newest unread rows |
getUnreadCount(User $user): int |
Count |
markAsRead(int $notificationId): bool |
Finds ID globally and marks read; false if absent |
markAllAsRead(User $user): int |
Number updated |
delete(int $notificationId): bool |
Deletes by global ID; false if absent |
deleteAll(User $user): int |
Number deleted |
deleteRead(User $user): int |
Number of read rows deleted |
deleteOld(int $days = 30): int |
Deletes old notifications across users |
broadcastToAll(string $title, string $message, ?string $link = null): int |
Creates per-user announcement rows in chunks of 100 |
ID-only service mutation methods do not verify ownership. The current NotificationController::markAsRead() and delete() also pass IDs directly to these methods without owner scoping. Consequently these existing authenticated mutation endpoints should not be treated as an example of secure per-user authorization. New controllers must scope the record to the authenticated user before changing it. This handbook records the gap; it does not repair runtime code.
broadcastToAll() asserts plugin permission notifications.broadcast through PluginContext. This is a plugin execution capability, separate from the actor's role. Its return is the number of user rows processed, not websocket recipients or email deliveries.
Authenticated player routes under /api/v1/notifications are GET list, /recent, /unread-count; POST /{id}/read, /mark-all-read; DELETE /{id}, /read/clear. List/recent returns {notifications, unread_count}; each item includes ID, type, title/message, icon/link/data, is_read, time_ago, and ISO creation time. The full list is limited to 100 and recent to ten. The count route returns {count}. Read/delete returns a success boolean even for missing records rather than a guaranteed 404.
Admin notifications
AdminNotification is a different model/table from player notifications. Staff inbox routes live under /api/v1/admin/notifications and require the core admin/moderator group.
AdminNotificationService::notify(int $userId, string $type, string $title, string $message, array $data = [], ?string $icon = null, ?string $link = null, string $priority = AdminNotification::PRIORITY_NORMAL): AdminNotification persists a staff notification. A null icon uses the model's default for the type.
notifyAll() takes the same arguments without user ID and returns void; recipient selection is delegated to AdminNotification::notifyAllAdmins(), which selects users with admin or moderator roles. HTTP access to an inbox and selection as a recipient remain different operations.
Convenience methods include:
| Method | Purpose |
|---|---|
newUserRegistered(User $user): void |
Low-priority registration notice |
newTicket(int $ticketId, string $subject, string $username): void |
Support-ticket notice; ticket system belongs to a plugin |
backupCompleted(string $filename, string $size): void |
Backup notice |
systemError(string $errorMessage, ?string $context = null): void |
High-priority error |
cacheCleared(int $adminId): void |
Notice for one admin |
moduleInstalled(string $moduleName): void |
Legacy-named install notice |
suspiciousActivity(string $description, array $data = []): void |
High-priority warning |
taskCompleted(string $taskName, ?string $result = null): void |
Task completion |
userReport(string $reporterName, string $reportedName, string $reason): void |
Report notice |
Admin HTTP endpoints include list/recent/unread-count, single read, read-all, delete, clear-read, test and broadcast. Test/broadcast endpoints create records and are not read-only diagnostics.
Activity and audit records
ActivityLogService inserts user_id, type, description, JSON metadata, request IP/user-agent and creation time. It does not automatically observe every database update. user_id is nullable: when an account is deleted, its own non-admin_action rows are deleted with it, but the admin_action rows it took stay with user_id null and the actor's name in metadata.actor_username (see activity logs).
| Signature | Result/limit |
|---|---|
log(User $user, string $type, string $description, array $metadata = []): void |
Insert one activity row |
logLogin(User): void, logLogout(User): void, logRegistration(User): void |
Convenience descriptions/types |
logProfileUpdate(User, array $details = []): void |
Profile-update activity |
logSettingsUpdate(User, array $details = []): void |
Settings-update activity |
logAdminAction(User $admin, string $action, ?User $targetUser = null, array $details = []): void |
Includes target ID/username metadata and fills the indexed target_user_id column if provided. Also records the actor's name as metadata.actor_username so the row stays attributable after the actor's account is deleted |
getUserActivity(User $user, int $limit = 50, int $offset = 0) |
Newest user history collection; $offset pages further back |
getRecentActivity(int $limit = 100, ?string $type = null) |
Recent collection with a left join on users; an action by a deleted actor has a null username |
getSuspiciousActivity(): array |
More than three distinct login IPs in one hour |
cleanOldLogs(): int |
Deletes history older than 90 days, except admin_action rows, which it never deletes |
Player GET /api/v1/activity and /activity/my-activity expose own history. Admin /admin/activity supplies recent, user, suspicious and cleanup routes. Cleanup is destructive history management; it is not error recovery.
Activity metadata should contain identifiers and a concise reason, not passwords, OAuth tokens or unrestricted request bodies. An audit-worthy balance movement belongs in the economy ledger, even if an activity description is also useful.
Email settings and templates
EmailSetting::getActive(): ?self returns the first active row. applyToConfig(): void selects SMTP or Mailgun and sets runtime From identity. Password/Mailgun secrets are encrypted and hidden on serialization. Preserve the application key; see configuration.
Admin routes under /api/v1/admin/email manage /settings, /settings/test, /send, /templates, template defaults, preview and test sends. All test/send operations can contact external recipients. Preview is the appropriate first step when checking content without delivery.
EmailTemplate::findBySlug(string $slug): ?self only returns active templates. render(array $variables = []): array returns subject, body_html, body_text. Substitution replaces exact double-brace placeholders using plain str_replace; it is not Blade evaluation. Values are HTML-escaped in body_html and lose line breaks in the subject; body_text gets them unchanged. These raw-HTML rows are the legacy path: new content is stored as blocks (below).
Default template definitions include welcome, password reset, password changed, account banned/unbanned and ticket reply. A default definition does not automatically create the row or trigger that event. getDefaults(): array supplies data for the seeding flow.
Example in a local test method, with no outgoing mail:
use App\Core\Models\EmailTemplate;
$template = new EmailTemplate([
'subject' => 'Hello {{username}}',
'body_html' => '<p>Hello {{username}}</p>',
'body_text' => 'Hello {{username}}',
]);
$rendered = $template->render(['username' => 'Learner']);
$this->assertSame('Hello Learner', $rendered['subject']);
Expected: substituted strings; no database save and no delivery. Escape untrusted values before inserting them into HTML. Missing variables remain as their placeholder text.
new App\Mail\DynamicEmail(string $templateSlug, array $variables = [], ?string $locale = null) is queued (ShouldQueue) and resolves everything when the message is delivered, which for queued mail is in the worker:
- Content, through
EmailTemplateLibrary::resolveForSend(): the version published for the locale; else the version published for English; else the active legacyemail_templatesrow of the same slug (a site that customised raw HTML keeps it until it publishes blocks); else the registry default. An unknown key gets the generic “template not configured” notice. Content that cannot be rendered falls back to the registry default, then the notice; only the key is logged. The locale is the one passed, else the mailable'slocale(), else the app locale; an unsupported one means English. - Transport:
send()reads the activeEmailSettingat delivery time and sends through an uncached mailer built from it (DynamicEmail::deliveryMailer()), with its From address, without changing the worker's global mail configuration. With no active settings the job throwsEmail system is not configured.and fails visibly. Before this fix the constructor applied the settings in the web request, so queued mail went out through the worker's environment mailer. - Plain text: every send has a text part: built from the blocks, the legacy row's
body_text, or text derived from its HTML.
Delivery timing and failure visibility depend on the queue worker. Do not equate a successful registration response with mailbox delivery. Registration tries welcome mail only when active email settings exist and catches errors raised in that controller. Reset requires active settings and can return 500. Queued worker failures occur outside the original request and need worker diagnostics.
Account emails. App\Core\Email\AccountEmail sends the core account emails to one player in their language: users.locale when supported, else its language part (de-AT gives de), else the site's configured fallback language (app.fallback_locale), then English; never the language of the request that triggered the mail. The welcome and reset-link mails pass the recipient's saved locale too. Fixed words fall back to English if lang/LOCALE/email.php cannot be loaded.
| Key | Sent when |
|---|---|
verify-email |
User::sendEmailVerificationNotification() (the resend route), with the same signed link VerifyEmail::createUrlUsing builds (an absolute frontend /verify-email address carrying the signed API path) |
password-changed |
a signed-in password change, and a completed password reset (with the time and the request IP) |
two-factor-enabled, two-factor-disabled |
2FA confirm and disable; never the secret or a recovery code |
oauth-linked, oauth-unlinked |
since 1.0.4, a successful POST /oauth/{provider}/link or DELETE /oauth/{provider}/unlink, with the provider's name and the time |
account-banned, account-unbanned |
ModerationService::banPlayer() (with the reason the player already sees at a banned sign-in, or a "no reason was given" line, never staff notes) and unbanPlayer() (only when a ban was in force, decided from the users row held locked; lifting a temporary ban that had already ended sends nothing) |
AccountEmail::notice() sends nothing while the admin email settings are inactive, queues only after the surrounding transaction commits, and never fails the action: an error while queueing (or, on the sync queue, delivering) is logged with the template key and exception type only. With a real queue a transport error happens later in the worker, as a failed job. Dates (AccountEmail::moment()) are written in the recipient's language, in UTC, and fixed words such as the end of a permanent ban come from lang/LOCALE/email.php.
Limits. A notice goes to whatever address the account holds, unverified ones included, on actions the holder can repeat, so notice() limits it per recipient address (a hash of it, never the address): at most PER_TEMPLATE_LIMIT (2) of one template per PER_TEMPLATE_WINDOW (600 seconds), and DAILY_LIMIT (12) of all notices per day. Only sends made while mail is configured count. A notice over a limit is dropped and logged as Account email dropped by the per-recipient limit. with the template key only; the action still succeeds. The routes that trigger them also have their own throttles, 5 a minute per account: throttle:5,1,change-password, two-factor-confirm and two-factor-disable.
Verification is the exception, because the send is the action itself. The resend route is open to unverified accounts, so User::sendEmailVerificationNotification() first checks its own per-recipient limit, AccountEmail::verificationAllowed(): at most VERIFY_LIMIT (3) per VERIFY_WINDOW (600 seconds) and VERIFY_DAILY_LIMIT (10) a day per address, a budget separate from the notices. It covers both the template and the framework fallback; over it nothing is sent, the drop is logged with the key verify-email only, and the route still answers the usual 200 message, so the answer does not reveal the limit. The route keeps its throttle:6,1 on top. With active admin settings the verify-email mail is queued, so the route answers 503 only when the message cannot be queued, or, on the sync queue, cannot be delivered; with a real worker a later transport failure shows in the worker, not in the response. With no active admin settings the framework VerifyEmail notification goes out in the request through the environment mailer, as before, and a failure there answers 503. Not covered: the anti-multi cluster ban and the user-tools "remove banned flag" path, which change the ban state outside ModerationService.
Email templates {#email-templates}
Admins edit every email the site sends as structured blocks in Settings, Email templates (API: email template library). Nothing stored is raw HTML.
Registry. App\Core\Email\EmailTemplateRegistry (a singleton, built once per process) lists each email by key with its name, description, where it is used, owner and variables. Core defines welcome, password-reset, verify-email, password-changed, account-banned, account-unbanned, two-factor-enabled, two-factor-disabled, oauth-linked and oauth-unlinked (1.0.4) in CoreEmailTemplates; each has a sender (see account emails above). Plugins add theirs through the email.templates.register action, which hands them an EmailTemplateRegistrar: the owner is stamped from the plugin context, a plugin's keys start with its slug and a dot, existing keys (core's included) and any add outside a plugin context are refused; each refusal is logged and skips only that email. Send a plugin email with new DynamicEmail('shop.receipt', [...], $user->locale).
Variables. Each template declares its variables (text, url, number or date) with a label and a sample value. Only those {{name}} tokens may appear, and a url variable only in a url field. Pass the values to DynamicEmail; a missing value renders empty. Previews and test sends use the samples, never real user data.
Blocks. header (logo or site name), heading, text (newlines, **bold** and links written as a label in square brackets followed by the address in round brackets, nothing else; a link address cannot contain spaces or round brackets), button, image (alt required, width up to 600), divider and footer (brand footer and address appended). At most 40 blocks and 64 KB. EmailBlockSchema::validate() refuses unknown types and fields, undeclared variables and any URL that is not an absolute http or https address or exactly one url variable.
Rendering. EmailRenderer writes a 600 px table layout with inline styles, a hidden preheader, color-scheme light and dark with a prefers-color-scheme: dark override, a phone-width rule and dir="rtl" for Arabic. It escapes by context: admin text is split into marks first and variables are filled in afterwards, escaped, so a value cannot add markup or links; a url variable whose value is not http or https drops the link (logged with the key and variable name, not the value); the subject loses line breaks and control characters. The plain-text part comes from the same blocks. Brand settings (logo URL, three colours, footer text, address) are one email_brand settings row shared by every email.
Before the migrations. Until the two tables exist, sends use the legacy row or the registry default. A running worker checks again on each send until it finds them, then remembers that, so no restart is needed after migrating.
Versions. Drafts are per key and locale in email_template_contents; publishing (behind admin.recent-auth, and only with the draft_hash of the draft the admin reviewed, else 409) appends the next numbered row to email_template_versions under a lock on the content row, and points the content at it. Restore copies an old version into the draft; reset publishes the registry default as a new version. Each change is an admin_action activity row with the key, locale and version numbers only.
use App\Core\Email\EmailTemplateLibrary;
// In a feature test: render the default welcome email without sending it.
$message = app(EmailTemplateLibrary::class)->resolveDefault('welcome', [
'app_name' => 'Pulse', 'username' => 'Ada', 'login_url' => 'https://example.test/login',
]);
$this->assertSame('Welcome to Pulse, Ada!', $message['subject']);
$this->assertStringContainsString("Sign in\nhttps://example.test/login", $message['text']);
Websocket and polling service
WebSocketService::broadcast(string $channel, string $event, array $data = []): void first stores a polling envelope, then dispatches WebSocketBroadcast. The cached envelope has channel, event, data, timestamp. The actual broadcast event's payload is the supplied data.
| Method | Behavior |
|---|---|
toUser(User $user, string $event, array $data = []): void |
Channel user.{id} |
toAll(string $event, array $data = []): void |
Channel global |
toAdmins(string $event, array $data = []): void |
Channel admin |
notification(User, string $type, string $title, string $message, array $extra = []): void |
Live notification payload; no notification row |
chatMessage(string $channel, array $message): void |
Broadcasts message on chat.{channel} |
announcement(string $title, string $message, string $type = 'info'): void |
Global announcement event |
getMessages(string $channel, ?string $since = null): array |
Cached messages, optionally after timestamp string |
authorizeChannel(User $user, string $channel): bool |
Own user.*, admin role for admin, otherwise true |
setOnline(User): void, setOffline(User): void, isOnline(User): bool |
Five-minute per-user cache flag |
getOnlineCount(): int |
Cached count, default zero |
getPresenceMembers(string $channel): array |
Cached member map |
joinPresence(string $channel, User $user): void, leavePresence(...): void |
Updates cached map and broadcasts |
Polling keeps the latest 100 messages per channel for one hour. It is not a durable event log. Timestamp-only cursors can miss equal-timestamp messages; reconnecting clients should refresh durable application state.
updateOnlineUsers() currently reads the existing online_users_count key and broadcasts it; it does not calculate/set a new total. Do not interpret heartbeat's count as an authoritative active-user census.
Authenticated /api/v1/ws routes provide POST /auth, /poll, /heartbeat and GET /online-count, /presence/{channel}. Poll takes channels: string[] and nullable since; unauthorized channels are silently skipped. Response is {messages, timestamp}.
WebSocketBroadcast creates private channels for user.* and admin, otherwise public channels. Laravel routes/channels.php currently registers only App.Models.User.{id}. The custom /ws/auth response and standard broadcaster authorization are separate contracts: test actual client/driver subscriptions rather than assuming all private channels work because polling does.
Plugin broadcast events and PHP helpers
App\Core\Events\PluginBroadcastEvent is a separate broadcast path from WebSocketService. Its constructor is __construct(string $pluginId, string $eventName, array $data = [], string $channelType = 'public', ?string $channelSuffix = null). Construction alone does not send a message. The event implements Laravel ShouldBroadcast, so dispatch normally depends on the selected queue/broadcast connection. It does not write the polling history described above.
| Method | Contract |
|---|---|
broadcastOn(): array |
One channel named plugin-<id>[.<suffix>]; private/presence types construct the corresponding Laravel channel. Any other type, including an invalid value, constructs a public channel. |
broadcastAs(): string |
<pluginId>:<eventName>. |
broadcastWith(): array |
Supplied data plus app_prefix = plugin ID and an ISO timestamp; these reserved keys overwrite same-named input fields. |
private(string $pluginId, string $eventName, array $data = [], ?string $channelSuffix = null): self |
Private event factory. |
presence(string $pluginId, string $eventName, array $data = [], ?string $channelSuffix = null): self |
Presence event factory. |
forUser(int $userId, string $pluginId, string $eventName, array $data = []): self |
Private event with suffix user.<id>. It does not authorize the user ID. |
For example, this checks the event contract without dispatching or contacting a transport:
use App\Core\Events\PluginBroadcastEvent;
$event = PluginBroadcastEvent::forUser(42, 'journal', 'report.ready', ['report_id' => 7]);
$this->assertSame('journal:report.ready', $event->broadcastAs());
$this->assertSame('private-plugin-journal.user.42', $event->broadcastOn()[0]->name);
$this->assertSame('journal', $event->broadcastWith()['app_prefix']);
To send it from an authorized handler, Laravel's broadcast($event) creates a PendingBroadcast; failures and asynchronous delivery depend on the configured transport/worker. Establish actual client subscriptions and explicit private/presence channel authorization first. The checked-in routes/channels.php only authorizes App.Models.User.{id}; it does not automatically authorize plugin-journal.user.{id}. A private-looking channel name is not evidence of a working permission check or delivery.
The global functions in app/Core/Helpers/broadcast.php are convenience wrappers:
| Signature | Result |
|---|---|
broadcastToPlugin(string $pluginId, string $event, array $data = [], string $channelType = 'public'): ?PendingBroadcast |
Constructs and broadcasts the event using the requested type. |
broadcastToPluginPrivate(string $pluginId, string $event, array $data = []): ?PendingBroadcast |
Broadcasts the private factory result. |
broadcastToPluginPresence(string $pluginId, string $event, array $data = []): ?PendingBroadcast |
Broadcasts the presence factory result. |
broadcastToPluginUser(int $userId, string $pluginId, string $event, array $data = []): ?PendingBroadcast |
Broadcasts the user-targeted factory result. |
getPluginChannelName(string $pluginId, ?string $suffix = null): string |
plugin-<id> plus a nonempty suffix. |
getPluginPrivateChannelName(string $pluginId, ?string $suffix = null): string |
Wire name private- plus the base channel name. |
getPluginPresenceChannelName(string $pluginId, ?string $suffix = null): string |
Wire name presence- plus the base channel name. |
PendingBroadcast above means Illuminate\Broadcasting\PendingBroadcast. These helpers declare nullable returns and propagate dispatch failures; they do not supply durable history, authorization or delivery confirmation. Their file is currently not listed in Composer's autoload.files and no core bootstrap/provider loads it. A bare helper call can therefore be undefined unless your integration explicitly loads that file. Prefer direct event construction for code that needs no optional global. The Plugin base's broadcast() checks availability and silently does nothing if the helper is absent. JavaScript's similarly named helper has its own frontend contract.
Source: event, helpers, Composer loading. No external message or subscription was used to verify this explanation.
Staff chat
Admin staff chat routes are GET/POST /api/v1/admin/staff-chat/messages and GET /unread. Sending requires a string content of at most 1,000 characters. The controller stores one first matching @(\w+) mention and updates the sender's last_active.
Sending and reading return formatted content and the original message in content_raw. Reading loads the last 100 messages in chronological display order, lists admins/moderators active in the last five minutes, and advances the caller's read marker. GET messages therefore has a read-status side effect.
Unread excludes the user's own messages after the last read ID. If the table is absent, read/unread returns an empty result rather than proving chat is correctly installed. Sending still requires the table. This controller does not broadcast chat messages; clients must use its implemented retrieval flow.
Generic outgoing webhooks
WebhookService selects active webhook rows whose events JSON contains the event or *. dispatch(string $event, array $payload = []): void schedules a closure after the HTTP response for each recipient. This is not a durable event bus with guaranteed replay.
create(array $data): Webhook requires name and URL, defaults user_id null, secret to a random 32-character value, events to ['*'], active true, headers empty, retry_count 3. The admin controller adds request validation; service callers must supply valid data themselves.
deliver(Webhook $webhook, string $event, array $payload, int $attempt = 1): array wraps the payload:
{
"id": "a generated UUID",
"event": "report.ready",
"created_at": "an ISO timestamp",
"data": {"report_id": 42}
}
It requires an HTTPS URL, resolves the hostname and checks its implemented private-IP rules, strips a list of risky headers, adds event/signature/timestamp headers and posts with a 30-second timeout plus configured HTTP retries. This source has specific filtering rules, not a universal network-isolation guarantee.
X-Webhook-Signature is sha256= plus HMAC-SHA256 of json_encode($fullPayload) with the secret. generateSignature(array $payload, ?string $secret): string returns an empty signature for no secret. verifySignature(string $payload, string $signature, string $secret): bool compares HMAC over the received string using hash_equals; receivers should use the exact raw body.
Delivery returns success, status, response, delivery_id, webhook_id, attempt, error. Response bodies are limited to 5,000 characters. HTTP/transport failures update failure counters and delivery records. Webhook::incrementFailure() deactivates a webhook once its failure count reaches ten; a successful delivery resets that count. URL validation occurs before the delivery try/catch, so it can throw without returning that result shape or saving a delivery record.
retry(WebhookDelivery $delivery): array creates a fresh delivery/envelope with incremented attempt. Its UUID changes; consumers need business identifiers for deduplication. test(Webhook $webhook): array sends webhook.test. Both perform external requests.
The advertised catalog is user registered/login/logout/banned/unbanned, admin announcement/maintenance, ticket created/replied. These names do not prove a core dispatch site. A plugin can call dispatch('report.ready', [...]); configure its recipient subscriptions explicitly.
Admin /admin/webhooks routes provide CRUD, events, toggle, test, delivery history, retry and secret regeneration. Delivery tests and retries are mutations with outbound effects. Keep webhook secrets and URLs out of public settings and logs.
Discord and Slack helpers
DiscordWebhookService has send(string $webhookUrl, array $data): bool, sendMessage(string $webhookUrl, string $message): bool, sendEmbed(string $webhookUrl, array $embed): bool, and sendAdminAlert(string $webhookUrl, string $title, string $message, string $severity = 'info'): bool.
SlackWebhookService has the same send/alert pattern plus sendMessage(..., ?string $channel = null): bool, sendBlocks(string $webhookUrl, array $blocks, ?string $text = null): bool, and array builders sectionBlock(string $text, ?array $fields = null), dividerBlock(), headerBlock(string $text).
These helpers directly call Laravel HTTP, catch exceptions, log and return a success boolean. They do not use generic webhook delivery records, configured retries or the generic service's URL filtering. The caller owns trustworthy destination selection, permissions and retry policy. Slack block builders only build arrays; those are useful for tests without outbound requests.
Troubleshooting and source map
| Symptom | Inspect |
|---|---|
| Inbox empty, websocket event visible | Separate row creation from broadcasting |
| Mail accepted but absent | Queued job status, active settings, template, transport logs |
| Unread chat count changed after GET | Read-status side effect is intentional |
| Private polling works, socket fails | Different channel authorization contracts |
| Webhook absent from delivery history | Event actually dispatched? Active subscription? Validation threw before save? |
| Duplicate external side effects | HTTP retry/manual retry and receiver idempotency |
Source: NotificationService, AdminNotificationService, ActivityLogService, WebSocketService, WebhookService, DiscordWebhookService, SlackWebhookService; models Notification, AdminNotification, EmailSetting, EmailTemplate, Webhook, WebhookDelivery, StaffChatMessage, StaffChatReadStatus; App/Mail/DynamicEmail, WebSocketBroadcast, routes/api.php, routes/channels.php, and corresponding controllers.
No external message was sent to verify this chapter. Use testing to fake transports and operations to inspect deployed workers and delivery failures.
Text formatting and emoji
TextFormatterService is the text-formatter singleton and is exposed through App\Core\Facades\TextFormatter. It combines BBCode parsing and JoyPixels conversion. In a booted backend:
use App\Core\Services\TextFormatterService;
$formatter = app(TextFormatterService::class);
$html = $formatter->formatStaffChat('[b]Hello[/b] :smile:');
Staff chat escapes message text before rendering BBCode and converting emoji to Unicode. It allows HTTP, HTTPS and relative links, and accepts same-origin image URLs. The admin component rebuilds the formatted content from allowed elements and attributes.
| Method | Input/defaults | Output / limit |
|---|---|---|
formatStaffChat(string $text): string |
Staff chat text | Formatted markup with preserved whitespace. |
formatPlain(string $text): string |
Text | Converts shortcodes to Unicode and strips HTML tags. It leaves BBCode delimiters in place. |
parseEmoji(string $text, bool $toImage = true): string |
Raw text, image/Unicode mode | HTML-escapes the input in both modes, then converts emoji to image markup by default or Unicode when $toImage is false. For plain-text shortcode conversion, use shortcodeToUnicode(). |
getAvailableBBCodes(): array |
None | Grouped descriptions/examples of supported tags. |
getPopularEmojis(): array |
None | Curated grouped shortcode list, not every Unicode emoji. |
emojiToShortcode(string $text): string |
Emoji text | Shortname conversion. |
shortcodeToUnicode(string $text): string |
Shortcode text | Unicode conversion. |
Authenticated endpoints under /api/v1/format include GET /bbcodes, GET /emojis, POST /plain, GET /emoji/search. Plain text length is capped at 50,000 characters by the controller. Search requires at least two query characters and returns at most 20 matches from the curated list.
EmojiController separately exposes /api/v1/emojis, /emojis/quick-reactions and /emojis/search backed by config/emojis.php. Do not assume that controller's catalogue is identical to JoyPixels' conversion rules. Formatter source, controller.
Announcement types
AnnouncementType is a configurable category model with fillable name, label, color, icon, sort_order. /api/v1/admin/announcement-types is a resource route using the core admin/moderator gate. Editing a category is distinct from sending a notification or email. The model storage definition and controller source show the actual schema/validation.