@extends('layouts.docs') @section('title', 'Sistema de Notificações - OG Framework') @section('body')
Comunicação
Sistema robusto e extensível para envio de notificações através de múltiplos canais. Construído sobre os padrões Strategy, Observer e Service Provider.
A facade Notification fornece acesso fluente ao NotificationService:
use Notification;
// Usa canal padrão: DatabaseChannel
Notification::send([
'text' => 'Operação concluída!',
'subject' => 'Sistema',
'color' => 'success'
]);
use MattermostChannel;
Notification::using(MattermostChannel::class)
->send([
'text' => 'Alerta crítico!',
'color' => 'danger'
]);
Notification::using([
MattermostChannel::class,
EmailChannel::class
])->send([
'text' => 'Sistema actualizado',
'to' => 'admin@empresa.com',
'subject' => 'Actualização',
'body' => '<p>O sistema foi actualizado.</p>'
]);
Interface simplificada para notificações rápidas:
function notify(
string $message, // Corpo da mensagem
?string $subject = null, // Assunto
?int $userId = null, // Destinatário (null = utilizador actual)
null|string|Carbon $date = null, // Data do alerta
?string $url = null, // URL associado
string $type = 'success', // success, warning, error, info
array $options = [] // Opções adicionais
): void
// Simples
notify('Documento guardado!');
// Com destinatário
notify(
message: 'Nova tarefa',
subject: 'Tarefas',
userId: 42
);
// Com URL de acção
notify(
message: 'Novo pedido #12345',
url: '/pedidos/ver/12345',
type: 'info'
);
// Especificar canais
notify(
message: 'Manutenção',
type: 'warning',
options: [
'channels' => [
MattermostChannel::class
]
]
);
// Formato legacy
notify(
message: 'Alerta',
options: [
'mattermost' => true,
'database' => false
]
);
Integra com o sistema legacy CentroMensagens para notificações internas.
| Campo | Tipo | Descrição |
|---|---|---|
| text | string | Corpo da mensagem |
| subject | string | Assunto/título |
| codempr | int | ID do destinatário |
| color | string | success, warning, error, info |
Classe readonly para envio de emails. Suporta múltiplos destinatários (array ou string separada por vírgulas).
// Campos obrigatórios: to, subject, body
Notification::using(EmailChannel::class)->send([
'to' => ['admin@empresa.com', 'manager@empresa.com'],
'subject' => 'Relatório Mensal',
'body' => '<p>Segue o relatório...</p>',
'from' => ['name' => 'Sistema', 'email' => 'noreply@empresa.com']
]);
Integração completa com Mattermost API v4, incluindo rich formatting e attachments.
Notification::using(MattermostChannel::class)->send([
'text' => 'Deploy concluído',
'subject' => 'Produção Actualizada',
'formatted_text' => "### Detalhes\n- Branch: main\n- Commit: abc123",
'color' => 'success',
'mattermost_mentions' => ['@devops', '@backend'],
'fields' => [
['title' => 'Versão', 'value' => '2.1.0', 'short' => true],
['title' => 'Ambiente', 'value' => 'production', 'short' => true],
]
]);
Componente especializado para notificações em ambiente CLI (workers, commands, cron jobs). Oferece 40+ métodos específicos para debugging.
{{-- SVG: CliNotifier Levels --}}use CliNotifier;
CliNotifier::debug('Processamento iniciado', [
'batch_size' => 100
]);
CliNotifier::warning('Memória elevada', [
'usage' => '450MB'
]);
// SEMPRE enviado em CLI
CliNotifier::critical('Falha crítica', [
'error' => 'DB connection lost'
]);
// Bootstrap
CliNotifier::databaseConnected(45.2, 'MySQL');
CliNotifier::addonLoaded('saft_ao');
// Queue/Jobs
CliNotifier::queueJobPopped('default', 'found');
CliNotifier::queueJobFailed($jobId, $class, $e);
CliNotifier::memoryWarning(450.5, 512.0);
// Email
CliNotifier::emailSentSuccessfully('invoice', 'cli@ex');
CliNotifier::emailSendingFailed('invoice', 'cli@ex', 'Timeout');
Ficheiro: Modules/Common/Config/notifications.php
| Variável | Descrição | Default |
|---|---|---|
| NOTIFICATION_DEFAULT_CHANNEL | Canal padrão | database |
| NOTIFICATION_DEBUG | Habilita modo debug | false |
| MATTERMOST_NOTIFICATIONS_ENABLED | Activa Mattermost | false |
| MATTERMOST_NOTIFICATIONS_URL | URL da API | - |
| MATTERMOST_TOKEN | Token de autenticação | - |
Adicionar novos canais é simples através da interface NotificationChannelInterface:
class SlackChannel implements NotificationChannelInterface
{
public function __construct(
private string $webhookUrl,
private string $defaultChannel = '#general'
) {}
public function send(array $notification): bool
{
try {
$response = $this->client->post($this->webhookUrl, [
'json' => [
'channel' => $notification['slack_channel'] ?? $this->defaultChannel,
'text' => $notification['text'],
'attachments' => [[
'color' => $this->getColor($notification['color'] ?? 'good'),
'title' => $notification['subject'] ?? '',
]]
]
]);
return $response->getStatusCode() === 200;
} catch (\Throwable $e) {
return false;
}
}
public function shouldSend(array $notification): bool
{
return ($notification['slack'] ?? false) === true;
}
}
// Registar no ServiceProvider
$service->addChannel(new SlackChannel($webhookUrl));