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 { 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 { Badge } from '@/components/ui/badge';
import { ExternalLink, RefreshCw, Mail, MessageCircle, Send, Bell } from 'lucide-react';
import { toast } from 'sonner';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { __ } from '@/lib/i18n';
import NotificationEvents from './Notifications/Events';
import NotificationChannels from './Notifications/Channels';
import NotificationTemplates from './Notifications/Templates';
export default function NotificationsSettings() {
const queryClient = useQueryClient();
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" />;
}
};
const [activeTab, setActiveTab] = useState('events');
return (
<SettingsLayout
title={__('Notifications')}
description={__('Manage notifications sent via email and other channels')}
description={__('Manage notification events, channels, and templates')}
>
<div className="space-y-6">
{/* Notification Channels */}
<SettingsCard
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>
<Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-6">
<TabsList className="grid w-full grid-cols-3">
<TabsTrigger value="events">{__('Events')}</TabsTrigger>
<TabsTrigger value="channels">{__('Channels')}</TabsTrigger>
<TabsTrigger value="templates">{__('Templates')}</TabsTrigger>
</TabsList>
{/* 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>
)}
<TabsContent value="events" className="space-y-4">
<NotificationEvents />
</TabsContent>
{/* 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>
)}
<TabsContent value="channels" className="space-y-4">
<NotificationChannels />
</TabsContent>
{/* 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>
<TabsContent value="templates" className="space-y-4">
<NotificationTemplates />
</TabsContent>
</Tabs>
</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>
);
}