OG Framework
OG Framework Documentação
Voltar para Documentação

Comunicação

Sistema de Notificações

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.

Arquitectura

Origem Código da Aplicação CLI / Worker Helper notify() NotificationService Fluent API • using(Channel::class) • debugging() • send($notification) Canais Database Email MM CentroMensagens SMTP API v4

Facade Notification

A facade Notification fornece acesso fluente ao NotificationService:

Envio Simples

use Notification;

// Usa canal padrão: DatabaseChannel
Notification::send([
    'text' => 'Operação concluída!',
    'subject' => 'Sistema',
    'color' => 'success'
]);

Especificar Canal

use MattermostChannel;

Notification::using(MattermostChannel::class)
    ->send([
        'text' => 'Alerta crítico!',
        'color' => 'danger'
    ]);

Múltiplos Canais

Notification::using([
    MattermostChannel::class,
    EmailChannel::class
])->send([
    'text' => 'Sistema actualizado',
    'to' => 'admin@empresa.com',
    'subject' => 'Actualização',
    'body' => '<p>O sistema foi actualizado.</p>'
]);

Helper Global: notify()

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

Exemplos Básicos

// 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'
);

Com Options

// Especificar canais
notify(
    message: 'Manutenção',
    type: 'warning',
    options: [
        'channels' => [
            MattermostChannel::class
        ]
    ]
);

// Formato legacy
notify(
    message: 'Alerta',
    options: [
        'mattermost' => true,
        'database' => false
    ]
);

Canais de Notificação

DatabaseChannel

Integra com o sistema legacy CentroMensagens para notificações internas.

Campo Tipo Descrição
textstringCorpo da mensagem
subjectstringAssunto/título
codemprintID do destinatário
colorstringsuccess, warning, error, info

EmailChannel

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']
]);

MattermostChannel

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],
    ]
]);

CliNotifier

Componente especializado para notificações em ambiente CLI (workers, commands, cron jobs). Oferece 40+ métodos específicos para debugging.

Debug (Condicional) debug() warning() Crítico (Sempre Enviado) critical() NOTIFICATION_DEBUG=true Sempre Mattermost Channel

Métodos Base

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'
]);

Notificações Específicas

// 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');

Configuração

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 -

Extensibilidade

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));