feat: Implement notification system with extensible channel architecture

##  Notification System Implementation

Following NOTIFICATION_STRATEGY.md, built on top of WooCommerce email infrastructure.

### Backend (PHP)

**1. NotificationManager** (`includes/Core/Notifications/NotificationManager.php`)
- Central manager for notification system
- Registers email channel (built-in)
- Registers default notification events (orders, products, customers)
- Provides hooks for addon channels
- Maps to WooCommerce email IDs

**2. NotificationSettingsProvider** (`includes/Core/Notifications/NotificationSettingsProvider.php`)
- Manages settings in wp_options
- Per-event channel configuration
- Per-channel recipient settings (admin/customer/both)
- Default settings with email enabled

**3. NotificationsController** (`includes/Api/NotificationsController.php`)
- REST API endpoints:
  - GET /notifications/channels - List available channels
  - GET /notifications/events - List notification events (grouped by category)
  - GET /notifications/settings - Get all settings
  - POST /notifications/settings - Update settings

### Frontend (React)

**Updated Notifications.tsx:**
- Shows available notification channels (email + addons)
- Channel cards with built-in/addon badges
- Event configuration by category (orders, products, customers)
- Toggle channels per event with button UI
- Link to WooCommerce advanced email settings
- Responsive and modern UI

### Key Features

 **Built on WooCommerce Emails**
- Email channel uses existing WC email system
- No reinventing the wheel
- Maps events to WC email IDs

 **Extensible Architecture**
- Addons can register channels via hooks
- `woonoow_notification_channels` filter
- `woonoow_notification_send_{channel}` action
- Per-event channel selection

 **User-Friendly UI**
- Clear channel status (Active/Inactive)
- Per-event channel toggles
- Category grouping (orders, products, customers)
- Addon discovery hints

 **Settings Storage**
- Stored in wp_options (woonoow_notification_settings)
- Per-event configuration
- Per-channel settings
- Default: email enabled for all events

### Addon Integration Example

```php
// Addon registers WhatsApp channel
add_action("woonoow_register_notification_channels", function() {
    NotificationManager::register_channel("whatsapp", [
        "label" => "WhatsApp",
        "icon" => "message-circle",
        "addon" => "woonoow-whatsapp",
    ]);
});

// Addon handles sending
add_action("woonoow_notification_send_whatsapp", function($event_id, $data) {
    // Send WhatsApp message
}, 10, 2);
```

### Files Created
- NotificationManager.php
- NotificationSettingsProvider.php
- NotificationsController.php

### Files Modified
- Routes.php - Register NotificationsController
- Bootstrap.php - Initialize NotificationManager
- Notifications.tsx - New UI with channels and events

---

**Ready for addon development!** 🚀
Next: Build Telegram addon as proof of concept
This commit is contained in:
dwindown
2025-11-11 12:11:08 +07:00
parent 4746834a82
commit 01fc3eb36d
6 changed files with 829 additions and 108 deletions

View File

@@ -1,43 +1,76 @@
import React from 'react';
import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { SettingsLayout } from './components/SettingsLayout';
import { SettingsCard } from './components/SettingsCard';
import { Switch } from '@/components/ui/switch';
import { Button } from '@/components/ui/button';
import { ExternalLink, RefreshCw, Mail } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { ExternalLink, RefreshCw, Mail, MessageCircle, Send, Bell } from 'lucide-react';
import { toast } from 'sonner';
import { __ } from '@/lib/i18n';
export default function NotificationsSettings() {
const queryClient = useQueryClient();
const wcAdminUrl = (window as any).WNW_CONFIG?.wpAdminUrl || '/wp-admin';
const [activeTab, setActiveTab] = useState<'channels' | 'events'>('channels');
// Fetch email settings
const { data: settings, isLoading, refetch } = useQuery({
queryKey: ['email-settings'],
queryFn: () => api.get('/settings/emails'),
// Fetch notification channels
const { data: channels, isLoading: channelsLoading } = useQuery({
queryKey: ['notification-channels'],
queryFn: () => api.get('/notifications/channels'),
});
// Toggle email mutation
const toggleMutation = useMutation({
mutationFn: async ({ emailId, enabled }: { emailId: string; enabled: boolean }) => {
return api.post(`/settings/emails/${emailId}/toggle`, { enabled });
// Fetch notification events
const { data: events, isLoading: eventsLoading } = useQuery({
queryKey: ['notification-events'],
queryFn: () => api.get('/notifications/events'),
});
// Fetch notification settings
const { data: settings, isLoading: settingsLoading } = useQuery({
queryKey: ['notification-settings'],
queryFn: () => api.get('/notifications/settings'),
});
// Update settings mutation
const updateMutation = useMutation({
mutationFn: async (newSettings: any) => {
return api.post('/notifications/settings', newSettings);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['email-settings'] });
toast.success(__('Email settings updated'));
queryClient.invalidateQueries({ queryKey: ['notification-settings'] });
queryClient.invalidateQueries({ queryKey: ['notification-events'] });
toast.success(__('Notification settings updated'));
},
onError: (error: any) => {
toast.error(error?.message || __('Failed to update email settings'));
toast.error(error?.message || __('Failed to update settings'));
},
});
const toggleEventChannel = (eventId: string, channelId: string, enabled: boolean) => {
const newSettings = { ...settings };
if (!newSettings.events) newSettings.events = {};
if (!newSettings.events[eventId]) newSettings.events[eventId] = { enabled: true, channels: [], recipients: {} };
const channels = newSettings.events[eventId].channels || [];
if (enabled) {
if (!channels.includes(channelId)) {
newSettings.events[eventId].channels = [...channels, channelId];
}
} else {
newSettings.events[eventId].channels = channels.filter((c: string) => c !== channelId);
}
updateMutation.mutate(newSettings);
};
const isLoading = channelsLoading || eventsLoading || settingsLoading;
if (isLoading) {
return (
<SettingsLayout
title={__('Notifications')}
description={__('Manage email notifications sent to customers and admins')}
description={__('Manage notifications sent via email and other channels')}
>
<div className="flex items-center justify-center py-12">
<RefreshCw className="h-6 w-6 animate-spin text-muted-foreground" />
@@ -46,110 +79,198 @@ export default function NotificationsSettings() {
);
}
const customerEmails = settings?.emails?.filter((e: any) => e.recipient === 'customer') || [];
const adminEmails = settings?.emails?.filter((e: any) => e.recipient === 'admin') || [];
const getChannelIcon = (channelId: string) => {
switch (channelId) {
case 'email': return <Mail className="h-4 w-4" />;
case 'whatsapp': return <MessageCircle className="h-4 w-4" />;
case 'telegram': return <Send className="h-4 w-4" />;
default: return <Bell className="h-4 w-4" />;
}
};
return (
<SettingsLayout
title={__('Notifications')}
description={__('Manage email notifications sent to customers and admins')}
action={
<Button
variant="outline"
size="sm"
onClick={() => refetch()}
>
<RefreshCw className="h-4 w-4 mr-2" />
{__('Refresh')}
</Button>
}
description={__('Manage notifications sent via email and other channels')}
>
<div className="space-y-6">
{/* Info Card - Shopify/Marketplace Style */}
{/* Notification Channels */}
<SettingsCard
title={__('Email Notifications')}
description={__('Manage automated emails sent to customers and admins')}
title={__('Notification Channels')}
description={__('Available channels for sending notifications')}
>
<div className="space-y-4">
{channels?.map((channel: any) => (
<div key={channel.id} className="flex items-center justify-between py-3 border-b last:border-0">
<div className="flex items-center gap-3 flex-1">
<div className="p-2 rounded-lg bg-muted">
{getChannelIcon(channel.id)}
</div>
<div className="flex-1">
<div className="flex items-center gap-2">
<h3 className="font-medium text-sm">{channel.label}</h3>
{channel.builtin && (
<Badge variant="secondary" className="text-xs">{__('Built-in')}</Badge>
)}
{channel.addon && (
<Badge variant="outline" className="text-xs">{__('Addon')}</Badge>
)}
</div>
{channel.addon && (
<p className="text-xs text-muted-foreground mt-0.5">
{__('Provided by')} {channel.addon}
</p>
)}
</div>
</div>
<Badge variant={channel.enabled ? 'default' : 'secondary'}>
{channel.enabled ? __('Active') : __('Inactive')}
</Badge>
</div>
))}
<div className="bg-muted/50 rounded-lg p-4 mt-4">
<p className="text-sm text-muted-foreground">
💡 {__('Want more channels like WhatsApp, Telegram, or SMS? Install notification addons to extend your notification capabilities.')}
</p>
</div>
</div>
</SettingsCard>
{/* Order Notifications */}
{events?.orders && events.orders.length > 0 && (
<SettingsCard
title={__('Order Notifications')}
description={__('Notifications sent when order status changes')}
>
<div className="space-y-4">
{events.orders.map((event: any) => (
<div key={event.id} className="py-3 border-b last:border-0">
<div className="flex items-start justify-between mb-3">
<div className="flex-1">
<h3 className="font-medium text-sm">{event.label}</h3>
<p className="text-xs text-muted-foreground mt-0.5">{event.description}</p>
</div>
</div>
<div className="flex flex-wrap gap-2">
{channels?.map((channel: any) => {
const isEnabled = event.channels?.includes(channel.id);
return (
<Button
key={channel.id}
variant={isEnabled ? 'default' : 'outline'}
size="sm"
onClick={() => toggleEventChannel(event.id, channel.id, !isEnabled)}
disabled={!channel.enabled || updateMutation.isPending}
className="text-xs"
>
{getChannelIcon(channel.id)}
<span className="ml-1.5">{channel.label}</span>
</Button>
);
})}
</div>
</div>
))}
</div>
</SettingsCard>
)}
{/* Product Notifications */}
{events?.products && events.products.length > 0 && (
<SettingsCard
title={__('Product Notifications')}
description={__('Notifications about product stock levels')}
>
<div className="space-y-4">
{events.products.map((event: any) => (
<div key={event.id} className="py-3 border-b last:border-0">
<div className="flex items-start justify-between mb-3">
<div className="flex-1">
<h3 className="font-medium text-sm">{event.label}</h3>
<p className="text-xs text-muted-foreground mt-0.5">{event.description}</p>
</div>
</div>
<div className="flex flex-wrap gap-2">
{channels?.map((channel: any) => {
const isEnabled = event.channels?.includes(channel.id);
return (
<Button
key={channel.id}
variant={isEnabled ? 'default' : 'outline'}
size="sm"
onClick={() => toggleEventChannel(event.id, channel.id, !isEnabled)}
disabled={!channel.enabled || updateMutation.isPending}
className="text-xs"
>
{getChannelIcon(channel.id)}
<span className="ml-1.5">{channel.label}</span>
</Button>
);
})}
</div>
</div>
))}
</div>
</SettingsCard>
)}
{/* Customer Notifications */}
{events?.customers && events.customers.length > 0 && (
<SettingsCard
title={__('Customer Notifications')}
description={__('Notifications about customer activities')}
>
<div className="space-y-4">
{events.customers.map((event: any) => (
<div key={event.id} className="py-3 border-b last:border-0">
<div className="flex items-start justify-between mb-3">
<div className="flex-1">
<h3 className="font-medium text-sm">{event.label}</h3>
<p className="text-xs text-muted-foreground mt-0.5">{event.description}</p>
</div>
</div>
<div className="flex flex-wrap gap-2">
{channels?.map((channel: any) => {
const isEnabled = event.channels?.includes(channel.id);
return (
<Button
key={channel.id}
variant={isEnabled ? 'default' : 'outline'}
size="sm"
onClick={() => toggleEventChannel(event.id, channel.id, !isEnabled)}
disabled={!channel.enabled || updateMutation.isPending}
className="text-xs"
>
{getChannelIcon(channel.id)}
<span className="ml-1.5">{channel.label}</span>
</Button>
);
})}
</div>
</div>
))}
</div>
</SettingsCard>
)}
{/* WooCommerce Email Settings Link */}
<SettingsCard
title={__('Advanced Email Settings')}
description={__('Customize email templates and sender details')}
>
<div className="text-sm space-y-3">
<p className="text-muted-foreground">
{__('Control which email notifications are sent automatically when orders are placed, shipped, or updated. All emails use your store branding and can be customized in WooCommerce settings.')}
{__('Email notifications are powered by WooCommerce. For advanced customization like templates, subject lines, and sender details, use the WooCommerce email settings.')}
</p>
<div className="bg-muted/50 rounded-lg p-4 space-y-2">
<p className="font-medium text-foreground text-sm">
💡 {__('Quick Tips')}
</p>
<ul className="text-xs text-muted-foreground space-y-1.5">
<li> {__('Keep order confirmation emails enabled - customers expect immediate confirmation')}</li>
<li> {__('Enable shipping notifications to reduce "where is my order?" inquiries')}</li>
<li> {__('Admin notifications help you stay on top of new orders and issues')}</li>
<li> {__('Disable emails you don\'t need to reduce inbox clutter')}</li>
</ul>
</div>
<div className="pt-2">
<p className="text-xs text-muted-foreground">
{__('Need to customize email templates, subject lines, or sender details?')}{' '}
<a
href={`${(window as any).WNW_CONFIG?.wpAdminUrl || '/wp-admin'}/admin.php?page=wc-settings&tab=email`}
target="_blank"
rel="noopener noreferrer"
className="text-primary hover:underline"
>
{__('Go to advanced email settings →')}
</a>
</p>
</div>
</div>
</SettingsCard>
{/* Customer Emails */}
<SettingsCard
title={__('Customer Notifications')}
description={__('Emails sent to customers about their orders')}
>
<div className="space-y-4">
{customerEmails.map((email: any) => (
<div key={email.id} className="flex items-center justify-between py-3 border-b last:border-0">
<div className="flex-1">
<h3 className="font-medium text-sm">{email.title}</h3>
<p className="text-xs text-muted-foreground mt-0.5">{email.description}</p>
</div>
<Switch
checked={email.enabled === 'yes'}
onCheckedChange={(checked) => toggleMutation.mutate({
emailId: email.id,
enabled: checked
})}
disabled={toggleMutation.isPending}
/>
</div>
))}
</div>
</SettingsCard>
{/* Admin Emails */}
<SettingsCard
title={__('Admin Notifications')}
description={__('Emails sent to store administrators')}
>
<div className="space-y-4">
{adminEmails.map((email: any) => (
<div key={email.id} className="flex items-center justify-between py-3 border-b last:border-0">
<div className="flex-1">
<h3 className="font-medium text-sm">{email.title}</h3>
<p className="text-xs text-muted-foreground mt-0.5">{email.description}</p>
</div>
<Switch
checked={email.enabled === 'yes'}
onCheckedChange={(checked) => toggleMutation.mutate({
emailId: email.id,
enabled: checked
})}
disabled={toggleMutation.isPending}
/>
</div>
))}
<Button
variant="outline"
size="sm"
onClick={() => window.open(`${(window as any).WNW_CONFIG?.wpAdminUrl || '/wp-admin'}/admin.php?page=wc-settings&tab=email`, '_blank')}
>
<ExternalLink className="h-4 w-4 mr-2" />
{__('Open WooCommerce Email Settings')}
</Button>
</div>
</SettingsCard>