feat: Implement notification system with 3 subpages (Events, Channels, Templates)

##  Correct Implementation Following NOTIFICATION_STRATEGY.md

### Frontend (React) - 3 Subpages

**1. Main Notifications Page** (`Notifications.tsx`)
- Tab navigation for 3 sections
- Events | Channels | Templates

**2. Events Subpage** (`Notifications/Events.tsx`)
- Configure which channels per event
- Grouped by category (Orders, Products, Customers)
- Toggle channels (Email, WhatsApp, Telegram, etc.)
- Show recipient (Admin/Customer/Both)
- Switch UI for enable/disable per channel

**3. Channels Subpage** (`Notifications/Channels.tsx`)
- List available channels
- Built-in channels (Email)
- Addon channels (WhatsApp, Telegram, SMS, Push)
- Channel status (Active/Inactive)
- Configure button for each channel
- Addon discovery cards

**4. Templates Subpage** (`Notifications/Templates.tsx`)
- Email templates (link to WooCommerce)
- Addon channel templates
- Template variables reference
- Preview and edit buttons
- Variable documentation ({order_number}, {customer_name}, etc.)

### Backend (PHP) - Bridge to WooCommerce

**NotificationsController** (`includes/Api/NotificationsController.php`)
- Bridges to WooCommerce email system
- Does NOT reinvent notification system
- Provides addon integration hooks

**REST API Endpoints:**
```
GET  /notifications/channels  - List channels (email + addons)
GET  /notifications/events     - List events (maps to WC emails)
POST /notifications/events/update - Update event channel settings
```

**Key Features:**
 Leverages WooCommerce emails (not reinventing)
 Stores settings in wp_options
 Provides hooks for addons:
   - `woonoow_notification_channels` filter
   - `woonoow_notification_events` filter
   - `woonoow_notification_event_updated` action

### Addon Integration

**Example: WhatsApp Addon**
```php
// Register channel
add_filter("woonoow_notification_channels", function($channels) {
    $channels[] = [
        "id" => "whatsapp",
        "label" => "WhatsApp",
        "icon" => "message-circle",
        "enabled" => true,
        "addon" => "woonoow-whatsapp",
    ];
    return $channels;
});

// React to event updates
add_action("woonoow_notification_event_updated", function($event_id, $channel_id, $enabled, $recipient) {
    if ($channel_id === "whatsapp" && $enabled) {
        // Setup WhatsApp notification for this event
    }
}, 10, 4);

// Hook into WooCommerce email triggers
add_action("woocommerce_order_status_processing", function($order_id) {
    // Send WhatsApp notification
}, 10, 1);
```

### Architecture

**NOT a new notification system** 
- Uses WooCommerce email infrastructure
- Maps events to WC email IDs
- Addons hook into WC triggers

**IS an extensible framework** 
- Unified UI for all channels
- Per-event channel configuration
- Template management
- Addon discovery

### Files Created
- `Notifications.tsx` - Main page with tabs
- `Notifications/Events.tsx` - Events configuration
- `Notifications/Channels.tsx` - Channel management
- `Notifications/Templates.tsx` - Template editor
- `NotificationsController.php` - REST API bridge

### Files Modified
- `Routes.php` - Register NotificationsController

---

**Ready for addon development!** 🚀
Next: Build Telegram addon as proof of concept
This commit is contained in:
dwindown
2025-11-11 12:31:13 +07:00
parent 01fc3eb36d
commit ffdc7aae5f
8 changed files with 910 additions and 752 deletions

View File

@@ -1,280 +1,38 @@
import React, { useState } 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 { SettingsLayout } from './components/SettingsLayout';
import { SettingsCard } from './components/SettingsCard'; import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Switch } from '@/components/ui/switch';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { ExternalLink, RefreshCw, Mail, MessageCircle, Send, Bell } from 'lucide-react';
import { toast } from 'sonner';
import { __ } from '@/lib/i18n'; import { __ } from '@/lib/i18n';
import NotificationEvents from './Notifications/Events';
import NotificationChannels from './Notifications/Channels';
import NotificationTemplates from './Notifications/Templates';
export default function NotificationsSettings() { export default function NotificationsSettings() {
const queryClient = useQueryClient(); const [activeTab, setActiveTab] = useState('events');
const [activeTab, setActiveTab] = useState<'channels' | 'events'>('channels');
// Fetch notification channels
const { data: channels, isLoading: channelsLoading } = useQuery({
queryKey: ['notification-channels'],
queryFn: () => api.get('/notifications/channels'),
});
// 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: ['notification-settings'] });
queryClient.invalidateQueries({ queryKey: ['notification-events'] });
toast.success(__('Notification settings updated'));
},
onError: (error: any) => {
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 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" />
</div>
</SettingsLayout>
);
}
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 ( return (
<SettingsLayout <SettingsLayout
title={__('Notifications')} title={__('Notifications')}
description={__('Manage notifications sent via email and other channels')} description={__('Manage notification events, channels, and templates')}
> >
<div className="space-y-6"> <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-6">
{/* Notification Channels */} <TabsList className="grid w-full grid-cols-3">
<SettingsCard <TabsTrigger value="events">{__('Events')}</TabsTrigger>
title={__('Notification Channels')} <TabsTrigger value="channels">{__('Channels')}</TabsTrigger>
description={__('Available channels for sending notifications')} <TabsTrigger value="templates">{__('Templates')}</TabsTrigger>
> </TabsList>
<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"> <TabsContent value="events" className="space-y-4">
<p className="text-sm text-muted-foreground"> <NotificationEvents />
💡 {__('Want more channels like WhatsApp, Telegram, or SMS? Install notification addons to extend your notification capabilities.')} </TabsContent>
</p>
</div>
</div>
</SettingsCard>
{/* Order Notifications */} <TabsContent value="channels" className="space-y-4">
{events?.orders && events.orders.length > 0 && ( <NotificationChannels />
<SettingsCard </TabsContent>
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 */} <TabsContent value="templates" className="space-y-4">
{events?.products && events.products.length > 0 && ( <NotificationTemplates />
<SettingsCard </TabsContent>
title={__('Product Notifications')} </Tabs>
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">
{__('Email notifications are powered by WooCommerce. For advanced customization like templates, subject lines, and sender details, use the WooCommerce email settings.')}
</p>
<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>
</div>
</SettingsLayout> </SettingsLayout>
); );
} }

View File

@@ -0,0 +1,215 @@
import React from 'react';
import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { SettingsCard } from '../components/SettingsCard';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { RefreshCw, Mail, MessageCircle, Send, Bell, ExternalLink, Settings } from 'lucide-react';
import { __ } from '@/lib/i18n';
interface NotificationChannel {
id: string;
label: string;
icon: string;
enabled: boolean;
builtin?: boolean;
addon?: string;
}
export default function NotificationChannels() {
// Fetch channels
const { data: channels, isLoading } = useQuery({
queryKey: ['notification-channels'],
queryFn: () => api.get('/notifications/channels'),
});
const getChannelIcon = (channelId: string) => {
switch (channelId) {
case 'email':
return <Mail className="h-5 w-5" />;
case 'whatsapp':
return <MessageCircle className="h-5 w-5" />;
case 'telegram':
return <Send className="h-5 w-5" />;
default:
return <Bell className="h-5 w-5" />;
}
};
if (isLoading) {
return (
<div className="flex items-center justify-center py-12">
<RefreshCw className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
);
}
const builtinChannels = channels?.filter((c: NotificationChannel) => c.builtin) || [];
const addonChannels = channels?.filter((c: NotificationChannel) => !c.builtin) || [];
return (
<div className="space-y-6">
{/* Info Card */}
<SettingsCard
title={__('Notification Channels')}
description={__('Configure how notifications are sent')}
>
<div className="text-sm space-y-3">
<p className="text-muted-foreground">
{__(
'Channels are the different ways notifications can be sent. Email is built-in and always available. Install addons to enable additional channels like WhatsApp, Telegram, SMS, and more.'
)}
</p>
</div>
</SettingsCard>
{/* Built-in Channels */}
<SettingsCard title={__('Built-in Channels')} description={__('Channels included with WooNooW')}>
<div className="space-y-4">
{builtinChannels.map((channel: NotificationChannel) => (
<div key={channel.id} className="flex items-center justify-between p-4 rounded-lg border bg-card">
<div className="flex items-center gap-4">
<div className="p-3 rounded-lg bg-primary/10">{getChannelIcon(channel.id)}</div>
<div>
<div className="flex items-center gap-2 mb-1">
<h3 className="font-medium">{channel.label}</h3>
<Badge variant="secondary" className="text-xs">
{__('Built-in')}
</Badge>
<Badge variant={channel.enabled ? 'default' : 'secondary'} className="text-xs">
{channel.enabled ? __('Active') : __('Inactive')}
</Badge>
</div>
<p className="text-sm text-muted-foreground">
{channel.id === 'email' &&
__('Email notifications powered by WooCommerce. Configure templates and SMTP settings.')}
</p>
</div>
</div>
{channel.id === 'email' && (
<Button
variant="outline"
size="sm"
onClick={() =>
window.open(
`${(window as any).WNW_CONFIG?.wpAdminUrl || '/wp-admin'}/admin.php?page=wc-settings&tab=email`,
'_blank'
)
}
>
<Settings className="h-4 w-4 mr-2" />
{__('Configure')}
</Button>
)}
</div>
))}
</div>
</SettingsCard>
{/* Addon Channels */}
{addonChannels.length > 0 ? (
<SettingsCard title={__('Addon Channels')} description={__('Channels provided by installed addons')}>
<div className="space-y-4">
{addonChannels.map((channel: NotificationChannel) => (
<div key={channel.id} className="flex items-center justify-between p-4 rounded-lg border bg-card">
<div className="flex items-center gap-4">
<div className="p-3 rounded-lg bg-primary/10">{getChannelIcon(channel.id)}</div>
<div>
<div className="flex items-center gap-2 mb-1">
<h3 className="font-medium">{channel.label}</h3>
<Badge variant="outline" className="text-xs">
{__('Addon')}
</Badge>
<Badge variant={channel.enabled ? 'default' : 'secondary'} className="text-xs">
{channel.enabled ? __('Active') : __('Inactive')}
</Badge>
</div>
<p className="text-sm text-muted-foreground">
{__('Provided by')} {channel.addon}
</p>
</div>
</div>
<Button variant="outline" size="sm">
<Settings className="h-4 w-4 mr-2" />
{__('Configure')}
</Button>
</div>
))}
</div>
</SettingsCard>
) : (
<SettingsCard
title={__('Extend with Addons')}
description={__('Add more notification channels to your store')}
>
<div className="space-y-4">
<p className="text-sm text-muted-foreground">
{__(
'Install notification addons to send notifications via WhatsApp, Telegram, SMS, Push notifications, and more.'
)}
</p>
<div className="grid gap-4 md:grid-cols-2">
{/* Example addon cards */}
<div className="p-4 rounded-lg border bg-card">
<div className="flex items-center gap-3 mb-2">
<MessageCircle className="h-5 w-5 text-green-600" />
<h4 className="font-medium">{__('WhatsApp Notifications')}</h4>
</div>
<p className="text-sm text-muted-foreground mb-3">
{__('Send order updates and notifications via WhatsApp Business API')}
</p>
<Button variant="outline" size="sm" className="w-full">
<ExternalLink className="h-4 w-4 mr-2" />
{__('View Addon')}
</Button>
</div>
<div className="p-4 rounded-lg border bg-card">
<div className="flex items-center gap-3 mb-2">
<Send className="h-5 w-5 text-blue-600" />
<h4 className="font-medium">{__('Telegram Notifications')}</h4>
</div>
<p className="text-sm text-muted-foreground mb-3">
{__('Get instant notifications in your Telegram channel or group')}
</p>
<Button variant="outline" size="sm" className="w-full">
<ExternalLink className="h-4 w-4 mr-2" />
{__('View Addon')}
</Button>
</div>
<div className="p-4 rounded-lg border bg-card">
<div className="flex items-center gap-3 mb-2">
<Bell className="h-5 w-5 text-purple-600" />
<h4 className="font-medium">{__('SMS Notifications')}</h4>
</div>
<p className="text-sm text-muted-foreground mb-3">
{__('Send SMS notifications via Twilio, Nexmo, or other providers')}
</p>
<Button variant="outline" size="sm" className="w-full">
<ExternalLink className="h-4 w-4 mr-2" />
{__('View Addon')}
</Button>
</div>
<div className="p-4 rounded-lg border bg-card">
<div className="flex items-center gap-3 mb-2">
<Bell className="h-5 w-5 text-orange-600" />
<h4 className="font-medium">{__('Push Notifications')}</h4>
</div>
<p className="text-sm text-muted-foreground mb-3">
{__('Send browser push notifications to customers and admins')}
</p>
<Button variant="outline" size="sm" className="w-full">
<ExternalLink className="h-4 w-4 mr-2" />
{__('View Addon')}
</Button>
</div>
</div>
</div>
</SettingsCard>
)}
</div>
);
}

View File

@@ -0,0 +1,312 @@
import React from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { SettingsCard } from '../components/SettingsCard';
import { Switch } from '@/components/ui/switch';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { RefreshCw, Mail, MessageCircle, Send, Bell } from 'lucide-react';
import { toast } from 'sonner';
import { __ } from '@/lib/i18n';
interface NotificationEvent {
id: string;
label: string;
description: string;
category: string;
enabled: boolean;
channels: {
[channelId: string]: {
enabled: boolean;
recipient: 'admin' | 'customer' | 'both';
};
};
}
interface NotificationChannel {
id: string;
label: string;
icon: string;
enabled: boolean;
builtin?: boolean;
addon?: string;
}
export default function NotificationEvents() {
const queryClient = useQueryClient();
// Fetch events
const { data: eventsData, isLoading: eventsLoading } = useQuery({
queryKey: ['notification-events'],
queryFn: () => api.get('/notifications/events'),
});
// Fetch channels
const { data: channels, isLoading: channelsLoading } = useQuery({
queryKey: ['notification-channels'],
queryFn: () => api.get('/notifications/channels'),
});
// Update event mutation
const updateMutation = useMutation({
mutationFn: async ({ eventId, channelId, enabled, recipient }: any) => {
return api.post('/notifications/events/update', {
eventId,
channelId,
enabled,
recipient,
});
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['notification-events'] });
toast.success(__('Event settings updated'));
},
onError: (error: any) => {
toast.error(error?.message || __('Failed to update event'));
},
});
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" />;
}
};
const toggleChannel = (eventId: string, channelId: string, currentlyEnabled: boolean) => {
updateMutation.mutate({
eventId,
channelId,
enabled: !currentlyEnabled,
recipient: 'admin', // Default recipient
});
};
if (eventsLoading || channelsLoading) {
return (
<div className="flex items-center justify-center py-12">
<RefreshCw className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
);
}
const orderEvents = eventsData?.orders || [];
const productEvents = eventsData?.products || [];
const customerEvents = eventsData?.customers || [];
return (
<div className="space-y-6">
{/* Info Card */}
<SettingsCard
title={__('Notification Events')}
description={__('Configure which channels to use for each notification event')}
>
<div className="text-sm space-y-3">
<p className="text-muted-foreground">
{__(
'Choose which notification channels (Email, WhatsApp, Telegram, etc.) should be used for each event. Enable multiple channels to send notifications through different mediums.'
)}
</p>
<div className="bg-muted/50 rounded-lg p-4">
<p className="text-xs text-muted-foreground">
💡 {__('Tip: Email is always available. Install addons to enable WhatsApp, Telegram, SMS, and other channels.')}
</p>
</div>
</div>
</SettingsCard>
{/* Order Events */}
{orderEvents.length > 0 && (
<SettingsCard
title={__('Order Events')}
description={__('Notifications triggered by order status changes')}
>
<div className="space-y-6">
{orderEvents.map((event: NotificationEvent) => (
<div key={event.id} className="pb-6 border-b last:border-0">
<div className="flex items-start justify-between mb-4">
<div className="flex-1">
<h3 className="font-medium text-sm">{event.label}</h3>
<p className="text-xs text-muted-foreground mt-1">{event.description}</p>
</div>
<Switch checked={event.enabled} disabled />
</div>
{/* Channel Selection */}
<div className="space-y-3">
{channels?.map((channel: NotificationChannel) => {
const channelEnabled = event.channels?.[channel.id]?.enabled || false;
const recipient = event.channels?.[channel.id]?.recipient || 'admin';
return (
<div
key={channel.id}
className="flex items-center justify-between p-3 rounded-lg border bg-card"
>
<div className="flex items-center gap-3">
<div className={`p-2 rounded-lg ${channelEnabled ? 'bg-primary/10' : 'bg-muted'}`}>
{getChannelIcon(channel.id)}
</div>
<div>
<div className="flex items-center gap-2">
<span className="text-sm font-medium">{channel.label}</span>
{channel.builtin && (
<Badge variant="secondary" className="text-xs">
{__('Built-in')}
</Badge>
)}
</div>
{channelEnabled && (
<span className="text-xs text-muted-foreground">
{__('Send to')}: {recipient === 'admin' ? __('Admin') : recipient === 'customer' ? __('Customer') : __('Both')}
</span>
)}
</div>
</div>
<Switch
checked={channelEnabled}
onCheckedChange={() => toggleChannel(event.id, channel.id, channelEnabled)}
disabled={!channel.enabled || updateMutation.isPending}
/>
</div>
);
})}
</div>
</div>
))}
</div>
</SettingsCard>
)}
{/* Product Events */}
{productEvents.length > 0 && (
<SettingsCard
title={__('Product Events')}
description={__('Notifications about product stock levels')}
>
<div className="space-y-6">
{productEvents.map((event: NotificationEvent) => (
<div key={event.id} className="pb-6 border-b last:border-0">
<div className="flex items-start justify-between mb-4">
<div className="flex-1">
<h3 className="font-medium text-sm">{event.label}</h3>
<p className="text-xs text-muted-foreground mt-1">{event.description}</p>
</div>
<Switch checked={event.enabled} disabled />
</div>
<div className="space-y-3">
{channels?.map((channel: NotificationChannel) => {
const channelEnabled = event.channels?.[channel.id]?.enabled || false;
const recipient = event.channels?.[channel.id]?.recipient || 'admin';
return (
<div
key={channel.id}
className="flex items-center justify-between p-3 rounded-lg border bg-card"
>
<div className="flex items-center gap-3">
<div className={`p-2 rounded-lg ${channelEnabled ? 'bg-primary/10' : 'bg-muted'}`}>
{getChannelIcon(channel.id)}
</div>
<div>
<div className="flex items-center gap-2">
<span className="text-sm font-medium">{channel.label}</span>
{channel.builtin && (
<Badge variant="secondary" className="text-xs">
{__('Built-in')}
</Badge>
)}
</div>
{channelEnabled && (
<span className="text-xs text-muted-foreground">
{__('Send to')}: {recipient === 'admin' ? __('Admin') : recipient === 'customer' ? __('Customer') : __('Both')}
</span>
)}
</div>
</div>
<Switch
checked={channelEnabled}
onCheckedChange={() => toggleChannel(event.id, channel.id, channelEnabled)}
disabled={!channel.enabled || updateMutation.isPending}
/>
</div>
);
})}
</div>
</div>
))}
</div>
</SettingsCard>
)}
{/* Customer Events */}
{customerEvents.length > 0 && (
<SettingsCard
title={__('Customer Events')}
description={__('Notifications about customer activities')}
>
<div className="space-y-6">
{customerEvents.map((event: NotificationEvent) => (
<div key={event.id} className="pb-6 border-b last:border-0">
<div className="flex items-start justify-between mb-4">
<div className="flex-1">
<h3 className="font-medium text-sm">{event.label}</h3>
<p className="text-xs text-muted-foreground mt-1">{event.description}</p>
</div>
<Switch checked={event.enabled} disabled />
</div>
<div className="space-y-3">
{channels?.map((channel: NotificationChannel) => {
const channelEnabled = event.channels?.[channel.id]?.enabled || false;
const recipient = event.channels?.[channel.id]?.recipient || 'admin';
return (
<div
key={channel.id}
className="flex items-center justify-between p-3 rounded-lg border bg-card"
>
<div className="flex items-center gap-3">
<div className={`p-2 rounded-lg ${channelEnabled ? 'bg-primary/10' : 'bg-muted'}`}>
{getChannelIcon(channel.id)}
</div>
<div>
<div className="flex items-center gap-2">
<span className="text-sm font-medium">{channel.label}</span>
{channel.builtin && (
<Badge variant="secondary" className="text-xs">
{__('Built-in')}
</Badge>
)}
</div>
{channelEnabled && (
<span className="text-xs text-muted-foreground">
{__('Send to')}: {recipient === 'admin' ? __('Admin') : recipient === 'customer' ? __('Customer') : __('Both')}
</span>
)}
</div>
</div>
<Switch
checked={channelEnabled}
onCheckedChange={() => toggleChannel(event.id, channel.id, channelEnabled)}
disabled={!channel.enabled || updateMutation.isPending}
/>
</div>
);
})}
</div>
</div>
))}
</div>
</SettingsCard>
)}
</div>
);
}

View File

@@ -0,0 +1,225 @@
import React from 'react';
import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { SettingsCard } from '../components/SettingsCard';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { RefreshCw, Mail, MessageCircle, Send, Bell, ExternalLink, Edit, Eye } from 'lucide-react';
import { __ } from '@/lib/i18n';
interface NotificationChannel {
id: string;
label: string;
icon: string;
enabled: boolean;
builtin?: boolean;
addon?: string;
}
export default function NotificationTemplates() {
// Fetch channels
const { data: channels, isLoading } = useQuery({
queryKey: ['notification-channels'],
queryFn: () => api.get('/notifications/channels'),
});
const getChannelIcon = (channelId: string) => {
switch (channelId) {
case 'email':
return <Mail className="h-5 w-5" />;
case 'whatsapp':
return <MessageCircle className="h-5 w-5" />;
case 'telegram':
return <Send className="h-5 w-5" />;
default:
return <Bell className="h-5 w-5" />;
}
};
if (isLoading) {
return (
<div className="flex items-center justify-center py-12">
<RefreshCw className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
);
}
const enabledChannels = channels?.filter((c: NotificationChannel) => c.enabled) || [];
return (
<div className="space-y-6">
{/* Info Card */}
<SettingsCard
title={__('Notification Templates')}
description={__('Customize notification templates for each channel')}
>
<div className="text-sm space-y-3">
<p className="text-muted-foreground">
{__(
'Templates define the content and format of notifications sent through each channel. Customize the message, subject, and variables for each notification type.'
)}
</p>
<div className="bg-muted/50 rounded-lg p-4">
<p className="text-xs text-muted-foreground">
💡 {__('Tip: Use variables like {customer_name}, {order_number}, and {order_total} to personalize your notifications.')}
</p>
</div>
</div>
</SettingsCard>
{/* Email Templates */}
<SettingsCard
title={__('Email Templates')}
description={__('Customize email notification templates')}
>
<div className="space-y-4">
<div className="flex items-center justify-between p-4 rounded-lg border bg-card">
<div className="flex items-center gap-4">
<div className="p-3 rounded-lg bg-primary/10">
<Mail className="h-5 w-5" />
</div>
<div>
<div className="flex items-center gap-2 mb-1">
<h3 className="font-medium">{__('Email Templates')}</h3>
<Badge variant="secondary" className="text-xs">
{__('Built-in')}
</Badge>
</div>
<p className="text-sm text-muted-foreground">
{__('Email templates are managed by WooCommerce. Customize subject lines, headers, and content.')}
</p>
</div>
</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'
)
}
>
<Edit className="h-4 w-4 mr-2" />
{__('Edit Templates')}
</Button>
</div>
<div className="bg-muted/50 rounded-lg p-4">
<h4 className="font-medium text-sm mb-2">{__('Available Email Templates')}</h4>
<ul className="text-sm text-muted-foreground space-y-1">
<li> {__('New Order (Admin)')}</li>
<li> {__('Order Processing (Customer)')}</li>
<li> {__('Order Completed (Customer)')}</li>
<li> {__('Order Cancelled')}</li>
<li> {__('Order Refunded')}</li>
<li> {__('Customer Note')}</li>
<li> {__('Low Stock Alert')}</li>
<li> {__('Out of Stock Alert')}</li>
</ul>
</div>
</div>
</SettingsCard>
{/* Addon Channel Templates */}
{enabledChannels.filter((c: NotificationChannel) => !c.builtin).length > 0 ? (
<SettingsCard
title={__('Addon Channel Templates')}
description={__('Templates for addon notification channels')}
>
<div className="space-y-4">
{enabledChannels
.filter((c: NotificationChannel) => !c.builtin)
.map((channel: NotificationChannel) => (
<div key={channel.id} className="flex items-center justify-between p-4 rounded-lg border bg-card">
<div className="flex items-center gap-4">
<div className="p-3 rounded-lg bg-primary/10">{getChannelIcon(channel.id)}</div>
<div>
<div className="flex items-center gap-2 mb-1">
<h3 className="font-medium">{channel.label} {__('Templates')}</h3>
<Badge variant="outline" className="text-xs">
{__('Addon')}
</Badge>
</div>
<p className="text-sm text-muted-foreground">
{__('Customize message templates for')} {channel.label} {__('notifications')}
</p>
</div>
</div>
<div className="flex gap-2">
<Button variant="outline" size="sm">
<Eye className="h-4 w-4 mr-2" />
{__('Preview')}
</Button>
<Button variant="outline" size="sm">
<Edit className="h-4 w-4 mr-2" />
{__('Edit')}
</Button>
</div>
</div>
))}
</div>
</SettingsCard>
) : (
<SettingsCard
title={__('No Addon Templates')}
description={__('Install notification addons to customize their templates')}
>
<div className="text-center py-8">
<Bell className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
<p className="text-sm text-muted-foreground mb-4">
{__(
'Install notification addons like WhatsApp, Telegram, or SMS to customize their message templates.'
)}
</p>
<Button variant="outline" size="sm">
<ExternalLink className="h-4 w-4 mr-2" />
{__('Browse Addons')}
</Button>
</div>
</SettingsCard>
)}
{/* Template Variables Reference */}
<SettingsCard
title={__('Template Variables')}
description={__('Available variables you can use in your templates')}
>
<div className="space-y-4">
<div>
<h4 className="font-medium text-sm mb-2">{__('Order Variables')}</h4>
<div className="grid grid-cols-2 gap-2 text-sm">
<code className="px-2 py-1 rounded bg-muted text-xs">{'{order_number}'}</code>
<code className="px-2 py-1 rounded bg-muted text-xs">{'{order_total}'}</code>
<code className="px-2 py-1 rounded bg-muted text-xs">{'{order_status}'}</code>
<code className="px-2 py-1 rounded bg-muted text-xs">{'{order_date}'}</code>
<code className="px-2 py-1 rounded bg-muted text-xs">{'{payment_method}'}</code>
<code className="px-2 py-1 rounded bg-muted text-xs">{'{shipping_method}'}</code>
</div>
</div>
<div>
<h4 className="font-medium text-sm mb-2">{__('Customer Variables')}</h4>
<div className="grid grid-cols-2 gap-2 text-sm">
<code className="px-2 py-1 rounded bg-muted text-xs">{'{customer_name}'}</code>
<code className="px-2 py-1 rounded bg-muted text-xs">{'{customer_email}'}</code>
<code className="px-2 py-1 rounded bg-muted text-xs">{'{customer_phone}'}</code>
<code className="px-2 py-1 rounded bg-muted text-xs">{'{billing_address}'}</code>
<code className="px-2 py-1 rounded bg-muted text-xs">{'{shipping_address}'}</code>
</div>
</div>
<div>
<h4 className="font-medium text-sm mb-2">{__('Store Variables')}</h4>
<div className="grid grid-cols-2 gap-2 text-sm">
<code className="px-2 py-1 rounded bg-muted text-xs">{'{store_name}'}</code>
<code className="px-2 py-1 rounded bg-muted text-xs">{'{store_url}'}</code>
<code className="px-2 py-1 rounded bg-muted text-xs">{'{store_email}'}</code>
<code className="px-2 py-1 rounded bg-muted text-xs">{'{store_phone}'}</code>
</div>
</div>
</div>
</SettingsCard>
</div>
);
}

View File

@@ -2,7 +2,7 @@
/** /**
* Notifications REST API Controller * Notifications REST API Controller
* *
* Handles notification settings API endpoints. * Bridge to WooCommerce emails + addon channel framework.
* *
* @package WooNooW\Api * @package WooNooW\Api
*/ */
@@ -12,8 +12,6 @@ namespace WooNooW\Api;
use WP_REST_Request; use WP_REST_Request;
use WP_REST_Response; use WP_REST_Response;
use WP_Error; use WP_Error;
use WooNooW\Core\Notifications\NotificationManager;
use WooNooW\Core\Notifications\NotificationSettingsProvider;
class NotificationsController { class NotificationsController {
@@ -49,20 +47,11 @@ class NotificationsController {
], ],
]); ]);
// GET /woonoow/v1/notifications/settings // POST /woonoow/v1/notifications/events/update
register_rest_route($this->namespace, '/' . $this->rest_base . '/settings', [ register_rest_route($this->namespace, '/' . $this->rest_base . '/events/update', [
[
'methods' => 'GET',
'callback' => [$this, 'get_settings'],
'permission_callback' => [$this, 'check_permission'],
],
]);
// POST /woonoow/v1/notifications/settings
register_rest_route($this->namespace, '/' . $this->rest_base . '/settings', [
[ [
'methods' => 'POST', 'methods' => 'POST',
'callback' => [$this, 'update_settings'], 'callback' => [$this, 'update_event'],
'permission_callback' => [$this, 'check_permission'], 'permission_callback' => [$this, 'check_permission'],
], ],
]); ]);
@@ -75,17 +64,20 @@ class NotificationsController {
* @return WP_REST_Response * @return WP_REST_Response
*/ */
public function get_channels(WP_REST_Request $request) { public function get_channels(WP_REST_Request $request) {
$channels = NotificationManager::get_channels(); $channels = [
[
'id' => 'email',
'label' => __('Email', 'woonoow'),
'icon' => 'mail',
'enabled' => true,
'builtin' => true,
],
];
// Add enabled status from settings // Allow addons to register their channels
$settings = NotificationSettingsProvider::get_settings(); $channels = apply_filters('woonoow_notification_channels', $channels);
$channel_settings = $settings['channels'] ?? [];
foreach ($channels as $id => &$channel) { return new WP_REST_Response($channels, 200);
$channel['enabled'] = $channel_settings[$id]['enabled'] ?? $channel['builtin'];
}
return new WP_REST_Response(array_values($channels), 200);
} }
/** /**
@@ -95,78 +87,148 @@ class NotificationsController {
* @return WP_REST_Response * @return WP_REST_Response
*/ */
public function get_events(WP_REST_Request $request) { public function get_events(WP_REST_Request $request) {
$events = NotificationManager::get_events(); // Get saved settings
$settings = NotificationSettingsProvider::get_settings(); $settings = get_option('woonoow_notification_settings', []);
$event_settings = $settings['events'] ?? [];
// Merge event data with settings // Define default events (maps to WooCommerce emails)
foreach ($events as $id => &$event) { $events = [
$event_config = $event_settings[$id] ?? []; 'orders' => [
$event['enabled'] = $event_config['enabled'] ?? true; [
$event['channels'] = $event_config['channels'] ?? ['email']; 'id' => 'order_placed',
$event['recipients'] = $event_config['recipients'] ?? ['email' => 'admin']; 'label' => __('Order Placed', 'woonoow'),
} 'description' => __('When a new order is placed', 'woonoow'),
'category' => 'orders',
// Group by category 'wc_email' => 'new_order',
$grouped = [ 'enabled' => true,
'orders' => [], 'channels' => $settings['order_placed'] ?? ['email' => ['enabled' => true, 'recipient' => 'admin']],
'products' => [], ],
'customers' => [], [
'id' => 'order_processing',
'label' => __('Order Processing', 'woonoow'),
'description' => __('When order status changes to processing', 'woonoow'),
'category' => 'orders',
'wc_email' => 'customer_processing_order',
'enabled' => true,
'channels' => $settings['order_processing'] ?? ['email' => ['enabled' => true, 'recipient' => 'customer']],
],
[
'id' => 'order_completed',
'label' => __('Order Completed', 'woonoow'),
'description' => __('When order is marked as completed', 'woonoow'),
'category' => 'orders',
'wc_email' => 'customer_completed_order',
'enabled' => true,
'channels' => $settings['order_completed'] ?? ['email' => ['enabled' => true, 'recipient' => 'customer']],
],
[
'id' => 'order_cancelled',
'label' => __('Order Cancelled', 'woonoow'),
'description' => __('When order is cancelled', 'woonoow'),
'category' => 'orders',
'wc_email' => 'cancelled_order',
'enabled' => true,
'channels' => $settings['order_cancelled'] ?? ['email' => ['enabled' => true, 'recipient' => 'admin']],
],
[
'id' => 'order_refunded',
'label' => __('Order Refunded', 'woonoow'),
'description' => __('When order is refunded', 'woonoow'),
'category' => 'orders',
'wc_email' => 'customer_refunded_order',
'enabled' => true,
'channels' => $settings['order_refunded'] ?? ['email' => ['enabled' => true, 'recipient' => 'customer']],
],
],
'products' => [
[
'id' => 'low_stock',
'label' => __('Low Stock Alert', 'woonoow'),
'description' => __('When product stock is low', 'woonoow'),
'category' => 'products',
'wc_email' => 'low_stock',
'enabled' => true,
'channels' => $settings['low_stock'] ?? ['email' => ['enabled' => true, 'recipient' => 'admin']],
],
[
'id' => 'out_of_stock',
'label' => __('Out of Stock Alert', 'woonoow'),
'description' => __('When product is out of stock', 'woonoow'),
'category' => 'products',
'wc_email' => 'no_stock',
'enabled' => true,
'channels' => $settings['out_of_stock'] ?? ['email' => ['enabled' => true, 'recipient' => 'admin']],
],
],
'customers' => [
[
'id' => 'new_customer',
'label' => __('New Customer', 'woonoow'),
'description' => __('When a new customer registers', 'woonoow'),
'category' => 'customers',
'wc_email' => 'customer_new_account',
'enabled' => true,
'channels' => $settings['new_customer'] ?? ['email' => ['enabled' => true, 'recipient' => 'customer']],
],
[
'id' => 'customer_note',
'label' => __('Customer Note Added', 'woonoow'),
'description' => __('When a note is added to customer order', 'woonoow'),
'category' => 'customers',
'wc_email' => 'customer_note',
'enabled' => true,
'channels' => $settings['customer_note'] ?? ['email' => ['enabled' => true, 'recipient' => 'customer']],
],
],
]; ];
foreach ($events as $event) { // Allow addons to add custom events
$category = $event['category'] ?? 'general'; $events = apply_filters('woonoow_notification_events', $events);
if (!isset($grouped[$category])) {
$grouped[$category] = [];
}
$grouped[$category][] = $event;
}
return new WP_REST_Response($grouped, 200); return new WP_REST_Response($events, 200);
} }
/** /**
* Get notification settings * Update event settings
*
* @param WP_REST_Request $request Request object
* @return WP_REST_Response
*/
public function get_settings(WP_REST_Request $request) {
$settings = NotificationSettingsProvider::get_settings();
return new WP_REST_Response($settings, 200);
}
/**
* Update notification settings
* *
* @param WP_REST_Request $request Request object * @param WP_REST_Request $request Request object
* @return WP_REST_Response|WP_Error * @return WP_REST_Response|WP_Error
*/ */
public function update_settings(WP_REST_Request $request) { public function update_event(WP_REST_Request $request) {
$new_settings = $request->get_json_params(); $event_id = $request->get_param('eventId');
$channel_id = $request->get_param('channelId');
$enabled = $request->get_param('enabled');
$recipient = $request->get_param('recipient');
if (empty($new_settings)) { if (empty($event_id) || empty($channel_id)) {
return new WP_Error( return new WP_Error(
'invalid_settings', 'invalid_params',
__('Invalid settings data', 'woonoow'), __('Event ID and Channel ID are required', 'woonoow'),
['status' => 400] ['status' => 400]
); );
} }
$updated = NotificationSettingsProvider::update_settings($new_settings); // Get current settings
$settings = get_option('woonoow_notification_settings', []);
if (!$updated) { // Update settings
return new WP_Error( if (!isset($settings[$event_id])) {
'update_failed', $settings[$event_id] = [];
__('Failed to update notification settings', 'woonoow'),
['status' => 500]
);
} }
$settings[$event_id][$channel_id] = [
'enabled' => $enabled,
'recipient' => $recipient ?? 'admin',
];
// Save settings
update_option('woonoow_notification_settings', $settings);
// Fire action for addons to react
do_action('woonoow_notification_event_updated', $event_id, $channel_id, $enabled, $recipient);
return new WP_REST_Response([ return new WP_REST_Response([
'success' => true, 'success' => true,
'message' => __('Notification settings updated successfully', 'woonoow'), 'message' => __('Event settings updated successfully', 'woonoow'),
'settings' => NotificationSettingsProvider::get_settings(),
], 200); ], 200);
} }

View File

@@ -19,7 +19,6 @@ use WooNooW\Core\Mail\MailQueue;
use WooNooW\Core\Mail\WooEmailOverride; use WooNooW\Core\Mail\WooEmailOverride;
use WooNooW\Core\DataStores\OrderStore; use WooNooW\Core\DataStores\OrderStore;
use WooNooW\Core\MediaUpload; use WooNooW\Core\MediaUpload;
use WooNooW\Core\Notifications\NotificationManager;
use WooNooW\Branding; use WooNooW\Branding;
class Bootstrap { class Bootstrap {
@@ -31,7 +30,6 @@ class Bootstrap {
StandaloneAdmin::init(); StandaloneAdmin::init();
Branding::init(); Branding::init();
MediaUpload::init(); MediaUpload::init();
NotificationManager::init();
// Addon system (order matters: Registry → Routes → Navigation) // Addon system (order matters: Registry → Routes → Navigation)
AddonRegistry::init(); AddonRegistry::init();

View File

@@ -1,230 +0,0 @@
<?php
/**
* Notification Manager
*
* Central manager for notification system. Works with WooCommerce emails
* and provides hooks for addon channels (WhatsApp, Telegram, etc.)
*
* @package WooNooW\Core\Notifications
*/
namespace WooNooW\Core\Notifications;
class NotificationManager {
/**
* Registered notification channels
*
* @var array
*/
private static $channels = [];
/**
* Notification events registry
*
* @var array
*/
private static $events = [];
/**
* Initialize notification system
*/
public static function init() {
// Register built-in email channel
self::register_channel('email', [
'id' => 'email',
'label' => __('Email', 'woonoow'),
'icon' => 'mail',
'builtin' => true,
'enabled' => true,
]);
// Register default notification events
self::register_default_events();
// Allow addons to register their channels
add_action('woonoow_register_notification_channels', [__CLASS__, 'allow_addon_registration']);
}
/**
* Register a notification channel
*
* @param string $id Channel ID
* @param array $args Channel arguments
*/
public static function register_channel($id, $args = []) {
$defaults = [
'id' => $id,
'label' => ucfirst($id),
'icon' => 'bell',
'builtin' => false,
'enabled' => false,
'addon' => '',
];
self::$channels[$id] = wp_parse_args($args, $defaults);
}
/**
* Get all registered channels
*
* @return array
*/
public static function get_channels() {
return apply_filters('woonoow_notification_channels', self::$channels);
}
/**
* Register default notification events
*/
private static function register_default_events() {
// Order events
self::register_event('order_placed', [
'label' => __('Order Placed', 'woonoow'),
'description' => __('When a new order is placed', 'woonoow'),
'category' => 'orders',
'wc_email' => 'new_order', // Maps to WC_Email_New_Order
]);
self::register_event('order_processing', [
'label' => __('Order Processing', 'woonoow'),
'description' => __('When order status changes to processing', 'woonoow'),
'category' => 'orders',
'wc_email' => 'customer_processing_order',
]);
self::register_event('order_completed', [
'label' => __('Order Completed', 'woonoow'),
'description' => __('When order is marked as completed', 'woonoow'),
'category' => 'orders',
'wc_email' => 'customer_completed_order',
]);
self::register_event('order_cancelled', [
'label' => __('Order Cancelled', 'woonoow'),
'description' => __('When order is cancelled', 'woonoow'),
'category' => 'orders',
'wc_email' => 'cancelled_order',
]);
self::register_event('order_refunded', [
'label' => __('Order Refunded', 'woonoow'),
'description' => __('When order is refunded', 'woonoow'),
'category' => 'orders',
'wc_email' => 'customer_refunded_order',
]);
// Product events
self::register_event('low_stock', [
'label' => __('Low Stock Alert', 'woonoow'),
'description' => __('When product stock is low', 'woonoow'),
'category' => 'products',
'wc_email' => 'low_stock',
]);
self::register_event('out_of_stock', [
'label' => __('Out of Stock Alert', 'woonoow'),
'description' => __('When product is out of stock', 'woonoow'),
'category' => 'products',
'wc_email' => 'no_stock',
]);
// Customer events
self::register_event('new_customer', [
'label' => __('New Customer', 'woonoow'),
'description' => __('When a new customer registers', 'woonoow'),
'category' => 'customers',
'wc_email' => 'customer_new_account',
]);
self::register_event('customer_note', [
'label' => __('Customer Note Added', 'woonoow'),
'description' => __('When a note is added to customer order', 'woonoow'),
'category' => 'customers',
'wc_email' => 'customer_note',
]);
}
/**
* Register a notification event
*
* @param string $id Event ID
* @param array $args Event arguments
*/
public static function register_event($id, $args = []) {
$defaults = [
'id' => $id,
'label' => ucfirst(str_replace('_', ' ', $id)),
'description' => '',
'category' => 'general',
'wc_email' => '',
'channels' => [],
];
self::$events[$id] = wp_parse_args($args, $defaults);
}
/**
* Get all registered events
*
* @return array
*/
public static function get_events() {
return apply_filters('woonoow_notification_events', self::$events);
}
/**
* Get events by category
*
* @param string $category Category name
* @return array
*/
public static function get_events_by_category($category) {
$events = self::get_events();
return array_filter($events, function($event) use ($category) {
return $event['category'] === $category;
});
}
/**
* Send notification
*
* @param string $event_id Event ID
* @param array $data Notification data
* @param array $channels Channels to use (default: from settings)
*/
public static function send($event_id, $data = [], $channels = null) {
// Get event configuration
$event = self::$events[$event_id] ?? null;
if (!$event) {
return;
}
// Get channels from settings if not specified
if ($channels === null) {
$settings = NotificationSettingsProvider::get_event_settings($event_id);
$channels = $settings['channels'] ?? ['email'];
}
// Send via each enabled channel
foreach ($channels as $channel_id) {
// Email is handled by WooCommerce, skip it
if ($channel_id === 'email') {
continue;
}
// Fire action for addon channels
do_action("woonoow_notification_send_{$channel_id}", $event_id, $data);
}
}
/**
* Allow addons to register channels
*/
public static function allow_addon_registration() {
// Addons hook into this to register their channels
// Example: add_action('woonoow_register_notification_channels', function() {
// NotificationManager::register_channel('whatsapp', [...]);
// });
}
}

View File

@@ -1,182 +0,0 @@
<?php
/**
* Notification Settings Provider
*
* Manages notification settings stored in wp_options.
* Works with WooCommerce email settings.
*
* @package WooNooW\Core\Notifications
*/
namespace WooNooW\Core\Notifications;
class NotificationSettingsProvider {
/**
* Option key for notification settings
*/
const OPTION_KEY = 'woonoow_notification_settings';
/**
* Get all notification settings
*
* @return array
*/
public static function get_settings() {
$defaults = self::get_default_settings();
$saved = get_option(self::OPTION_KEY, []);
return wp_parse_args($saved, $defaults);
}
/**
* Get default notification settings
*
* @return array
*/
private static function get_default_settings() {
return [
'events' => self::get_default_event_settings(),
'channels' => self::get_default_channel_settings(),
];
}
/**
* Get default event settings
*
* @return array
*/
private static function get_default_event_settings() {
$events = NotificationManager::get_events();
$settings = [];
foreach ($events as $event_id => $event) {
$settings[$event_id] = [
'enabled' => true,
'channels' => ['email'], // Email enabled by default
'recipients' => [
'email' => 'admin', // admin, customer, or both
],
];
}
return $settings;
}
/**
* Get default channel settings
*
* @return array
*/
private static function get_default_channel_settings() {
return [
'email' => [
'enabled' => true,
// Email settings are managed by WooCommerce
// We just track if it's enabled in our system
],
];
}
/**
* Get settings for a specific event
*
* @param string $event_id Event ID
* @return array
*/
public static function get_event_settings($event_id) {
$settings = self::get_settings();
return $settings['events'][$event_id] ?? [];
}
/**
* Get settings for a specific channel
*
* @param string $channel_id Channel ID
* @return array
*/
public static function get_channel_settings($channel_id) {
$settings = self::get_settings();
return $settings['channels'][$channel_id] ?? [];
}
/**
* Update notification settings
*
* @param array $new_settings New settings
* @return bool
*/
public static function update_settings($new_settings) {
$current = self::get_settings();
$updated = wp_parse_args($new_settings, $current);
return update_option(self::OPTION_KEY, $updated);
}
/**
* Update event settings
*
* @param string $event_id Event ID
* @param array $event_settings Event settings
* @return bool
*/
public static function update_event_settings($event_id, $event_settings) {
$settings = self::get_settings();
$settings['events'][$event_id] = $event_settings;
return self::update_settings($settings);
}
/**
* Update channel settings
*
* @param string $channel_id Channel ID
* @param array $channel_settings Channel settings
* @return bool
*/
public static function update_channel_settings($channel_id, $channel_settings) {
$settings = self::get_settings();
$settings['channels'][$channel_id] = $channel_settings;
return self::update_settings($settings);
}
/**
* Check if event is enabled
*
* @param string $event_id Event ID
* @return bool
*/
public static function is_event_enabled($event_id) {
$event_settings = self::get_event_settings($event_id);
return $event_settings['enabled'] ?? true;
}
/**
* Check if channel is enabled for event
*
* @param string $event_id Event ID
* @param string $channel_id Channel ID
* @return bool
*/
public static function is_channel_enabled_for_event($event_id, $channel_id) {
$event_settings = self::get_event_settings($event_id);
$channels = $event_settings['channels'] ?? [];
return in_array($channel_id, $channels, true);
}
/**
* Get recipient type for event channel
*
* @param string $event_id Event ID
* @param string $channel_id Channel ID
* @return string admin|customer|both
*/
public static function get_recipient_type($event_id, $channel_id) {
$event_settings = self::get_event_settings($event_id);
$recipients = $event_settings['recipients'] ?? [];
return $recipients[$channel_id] ?? 'admin';
}
}