feat: Add template editor and push notifications infrastructure

##  Template Editor + Push Notifications

### Backend (PHP)

**1. TemplateProvider** (`includes/Core/Notifications/TemplateProvider.php`)
- Manages notification templates in wp_options
- Default templates for all events x channels
- Variable system (order, product, customer, store)
- Template CRUD operations
- Variable replacement engine

**2. PushNotificationHandler** (`includes/Core/Notifications/PushNotificationHandler.php`)
- VAPID keys generation and storage
- Push subscription management
- Queue system for push notifications
- User-specific subscriptions
- Service worker integration ready

**3. NotificationsController** - Extended with:
- GET /notifications/templates - List all templates
- GET /notifications/templates/:eventId/:channelId - Get template
- POST /notifications/templates - Save template
- DELETE /notifications/templates/:eventId/:channelId - Reset to default
- GET /notifications/push/vapid-key - Get VAPID public key
- POST /notifications/push/subscribe - Subscribe to push
- POST /notifications/push/unsubscribe - Unsubscribe

**4. Push channel added to built-in channels**

### Frontend (React)

**1. TemplateEditor Component** (`TemplateEditor.tsx`)
- Modal dialog for editing templates
- Subject + Body text editors
- Variable insertion with dropdown
- Click-to-insert variables
- Live preview
- Save and reset to default
- Per event + channel customization

**2. Templates Page** - Completely rewritten:
- Lists all events x channels
- Shows "Custom" badge for customized templates
- Edit button opens template editor
- Fetches templates from API
- Variable reference guide
- Organized by channel

### Key Features

 **Simple Text Editor** (not HTML builder)
- Subject line
- Body text with variables
- Variable picker
- Preview mode

 **Variable System**
- Order variables: {order_number}, {order_total}, etc.
- Customer variables: {customer_name}, {customer_email}, etc.
- Product variables: {product_name}, {stock_quantity}, etc.
- Store variables: {store_name}, {store_url}, etc.
- Click to insert at cursor position

 **Push Notifications Ready**
- VAPID key generation
- Subscription management
- Queue system
- PWA integration ready
- Built-in channel (alongside email)

 **Template Management**
- Default templates for all events
- Per-event, per-channel customization
- Reset to default functionality
- Custom badge indicator

### Default Templates Included

**Email:**
- Order Placed, Processing, Completed, Cancelled, Refunded
- Low Stock, Out of Stock
- New Customer, Customer Note

**Push:**
- Order Placed, Processing, Completed
- Low Stock Alert

### Next Steps

1.  Service worker for push notifications
2.  Push subscription UI in Channels page
3.  Test push notifications
4.  Addon integration examples

---

**Ready for testing!** 🚀
This commit is contained in:
dwindown
2025-11-11 13:09:33 +07:00
parent ffdc7aae5f
commit 97e76a837b
6 changed files with 1020 additions and 108 deletions

View File

@@ -0,0 +1,203 @@
import React, { useState, useEffect } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { X, Plus } from 'lucide-react';
import { toast } from 'sonner';
import { __ } from '@/lib/i18n';
interface TemplateEditorProps {
open: boolean;
onClose: () => void;
eventId: string;
channelId: string;
eventLabel: string;
channelLabel: string;
template?: any;
}
export default function TemplateEditor({
open,
onClose,
eventId,
channelId,
eventLabel,
channelLabel,
template: initialTemplate,
}: TemplateEditorProps) {
const queryClient = useQueryClient();
const [subject, setSubject] = useState('');
const [body, setBody] = useState('');
const [variables, setVariables] = useState<{ [key: string]: string }>({});
useEffect(() => {
if (initialTemplate) {
setSubject(initialTemplate.subject || '');
setBody(initialTemplate.body || '');
setVariables(initialTemplate.variables || {});
}
}, [initialTemplate]);
const saveMutation = useMutation({
mutationFn: async () => {
return api.post('/notifications/templates', {
eventId,
channelId,
subject,
body,
});
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['notification-templates'] });
toast.success(__('Template saved successfully'));
onClose();
},
onError: (error: any) => {
toast.error(error?.message || __('Failed to save template'));
},
});
const resetMutation = useMutation({
mutationFn: async () => {
return api.del(`/notifications/templates/${eventId}/${channelId}`);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['notification-templates'] });
toast.success(__('Template reset to default'));
onClose();
},
onError: (error: any) => {
toast.error(error?.message || __('Failed to reset template'));
},
});
const insertVariable = (variable: string) => {
const textarea = document.querySelector('textarea[name="body"]') as HTMLTextAreaElement;
if (textarea) {
const start = textarea.selectionStart;
const end = textarea.selectionEnd;
const text = body;
const before = text.substring(0, start);
const after = text.substring(end);
const newText = before + `{${variable}}` + after;
setBody(newText);
// Set cursor position after inserted variable
setTimeout(() => {
textarea.focus();
textarea.setSelectionRange(start + variable.length + 2, start + variable.length + 2);
}, 0);
}
};
return (
<Dialog open={open} onOpenChange={onClose}>
<DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>
{__('Edit Template')}: {eventLabel} - {channelLabel}
</DialogTitle>
<DialogDescription>
{__('Customize the notification template. Use variables like {customer_name} to personalize messages.')}
</DialogDescription>
</DialogHeader>
<div className="space-y-6 py-4">
{/* Subject */}
<div className="space-y-2">
<Label htmlFor="subject">{__('Subject / Title')}</Label>
<Input
id="subject"
value={subject}
onChange={(e) => setSubject(e.target.value)}
placeholder={__('Enter notification subject')}
/>
<p className="text-xs text-muted-foreground">
{channelId === 'email'
? __('Email subject line')
: __('Push notification title')}
</p>
</div>
{/* Body */}
<div className="space-y-2">
<Label htmlFor="body">{__('Message Body')}</Label>
<Textarea
id="body"
name="body"
value={body}
onChange={(e) => setBody(e.target.value)}
placeholder={__('Enter notification message')}
rows={10}
className="font-mono text-sm"
/>
<p className="text-xs text-muted-foreground">
{__('Use variables from the list below to personalize your message')}
</p>
</div>
{/* Variables */}
<div className="space-y-3">
<Label>{__('Available Variables')}</Label>
<div className="flex flex-wrap gap-2">
{Object.entries(variables).map(([key, label]) => (
<Badge
key={key}
variant="secondary"
className="cursor-pointer hover:bg-primary hover:text-primary-foreground transition-colors"
onClick={() => insertVariable(key)}
>
<Plus className="h-3 w-3 mr-1" />
{`{${key}}`}
</Badge>
))}
</div>
<p className="text-xs text-muted-foreground">
{__('Click a variable to insert it at cursor position')}
</p>
</div>
{/* Preview */}
<div className="space-y-2">
<Label>{__('Preview')}</Label>
<div className="rounded-lg border bg-muted/50 p-4 space-y-2">
<div className="font-medium text-sm">{subject || __('(No subject)')}</div>
<div className="text-sm whitespace-pre-wrap">{body || __('(No message)')}</div>
</div>
</div>
</div>
<DialogFooter className="gap-2">
<Button variant="outline" onClick={() => resetMutation.mutate()} disabled={saveMutation.isPending || resetMutation.isPending}>
{__('Reset to Default')}
</Button>
<Button variant="outline" onClick={onClose}>
{__('Cancel')}
</Button>
<Button onClick={() => saveMutation.mutate()} disabled={saveMutation.isPending || resetMutation.isPending}>
{saveMutation.isPending ? __('Saving...') : __('Save Template')}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View File

@@ -1,11 +1,12 @@
import React from 'react'; import React, { useState } from 'react';
import { useQuery } from '@tanstack/react-query'; import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api'; import { api } from '@/lib/api';
import { SettingsCard } from '../components/SettingsCard'; import { SettingsCard } from '../components/SettingsCard';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
import { RefreshCw, Mail, MessageCircle, Send, Bell, ExternalLink, Edit, Eye } from 'lucide-react'; import { RefreshCw, Mail, MessageCircle, Send, Bell, Edit } from 'lucide-react';
import { __ } from '@/lib/i18n'; import { __ } from '@/lib/i18n';
import TemplateEditor from './TemplateEditor';
interface NotificationChannel { interface NotificationChannel {
id: string; id: string;
@@ -17,12 +18,45 @@ interface NotificationChannel {
} }
export default function NotificationTemplates() { export default function NotificationTemplates() {
const [editorOpen, setEditorOpen] = useState(false);
const [selectedEvent, setSelectedEvent] = useState<any>(null);
const [selectedChannel, setSelectedChannel] = useState<any>(null);
const [selectedTemplate, setSelectedTemplate] = useState<any>(null);
// Fetch channels // Fetch channels
const { data: channels, isLoading } = useQuery({ const { data: channels, isLoading: channelsLoading } = useQuery({
queryKey: ['notification-channels'], queryKey: ['notification-channels'],
queryFn: () => api.get('/notifications/channels'), queryFn: () => api.get('/notifications/channels'),
}); });
// Fetch events
const { data: eventsData, isLoading: eventsLoading } = useQuery({
queryKey: ['notification-events'],
queryFn: () => api.get('/notifications/events'),
});
// Fetch templates
const { data: templates, isLoading: templatesLoading } = useQuery({
queryKey: ['notification-templates'],
queryFn: () => api.get('/notifications/templates'),
});
const openEditor = async (event: any, channel: any) => {
setSelectedEvent(event);
setSelectedChannel(channel);
// Fetch template
try {
const template = await api.get(`/notifications/templates/${event.id}/${channel.id}`);
setSelectedTemplate(template);
} catch (error) {
console.error('Failed to fetch template:', error);
setSelectedTemplate(null);
}
setEditorOpen(true);
};
const getChannelIcon = (channelId: string) => { const getChannelIcon = (channelId: string) => {
switch (channelId) { switch (channelId) {
case 'email': case 'email':
@@ -36,7 +70,7 @@ export default function NotificationTemplates() {
} }
}; };
if (isLoading) { if (channelsLoading || eventsLoading || templatesLoading) {
return ( return (
<div className="flex items-center justify-center py-12"> <div className="flex items-center justify-center py-12">
<RefreshCw className="h-6 w-6 animate-spin text-muted-foreground" /> <RefreshCw className="h-6 w-6 animate-spin text-muted-foreground" />
@@ -44,7 +78,11 @@ export default function NotificationTemplates() {
); );
} }
const enabledChannels = channels?.filter((c: NotificationChannel) => c.enabled) || []; const allEvents = [
...(eventsData?.orders || []),
...(eventsData?.products || []),
...(eventsData?.customers || []),
];
return ( return (
<div className="space-y-6"> <div className="space-y-6">
@@ -67,118 +105,53 @@ export default function NotificationTemplates() {
</div> </div>
</SettingsCard> </SettingsCard>
{/* Email Templates */} {/* Templates by Channel */}
{channels?.map((channel: NotificationChannel) => (
<SettingsCard <SettingsCard
title={__('Email Templates')} key={channel.id}
description={__('Customize email notification templates')} title={`${channel.label} ${__('Templates')}`}
description={`${__('Customize')} ${channel.label} ${__('notification templates')}`}
> >
<div className="space-y-4"> <div className="space-y-3">
<div className="flex items-center justify-between p-4 rounded-lg border bg-card"> {allEvents.map((event: any) => {
<div className="flex items-center gap-4"> const templateKey = `${event.id}_${channel.id}`;
<div className="p-3 rounded-lg bg-primary/10"> const hasCustomTemplate = templates && templates[templateKey];
<Mail className="h-5 w-5" />
</div> return (
<div> <div
key={`${event.id}_${channel.id}`}
className="flex items-center justify-between p-4 rounded-lg border bg-card hover:bg-accent/50 transition-colors"
>
<div className="flex items-center gap-4 flex-1">
<div className="p-2 rounded-lg bg-primary/10">{getChannelIcon(channel.id)}</div>
<div className="flex-1">
<div className="flex items-center gap-2 mb-1"> <div className="flex items-center gap-2 mb-1">
<h3 className="font-medium">{__('Email Templates')}</h3> <h4 className="font-medium text-sm">{event.label}</h4>
{hasCustomTemplate && (
<Badge variant="default" className="text-xs">
{__('Custom')}
</Badge>
)}
{channel.builtin && (
<Badge variant="secondary" className="text-xs"> <Badge variant="secondary" className="text-xs">
{__('Built-in')} {__('Built-in')}
</Badge> </Badge>
)}
</div> </div>
<p className="text-sm text-muted-foreground"> <p className="text-xs text-muted-foreground">{event.description}</p>
{__('Email templates are managed by WooCommerce. Customize subject lines, headers, and content.')}
</p>
</div> </div>
</div> </div>
<Button <Button variant="outline" size="sm" onClick={() => openEditor(event, channel)}>
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 className="h-4 w-4 mr-2" />
{__('Edit')} {__('Edit')}
</Button> </Button>
</div> </div>
);
})}
</div> </div>
</SettingsCard>
))} ))}
</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 */} {/* Template Variables Reference */}
<SettingsCard <SettingsCard
@@ -220,6 +193,23 @@ export default function NotificationTemplates() {
</div> </div>
</div> </div>
</SettingsCard> </SettingsCard>
{/* Template Editor Dialog */}
{selectedEvent && selectedChannel && (
<TemplateEditor
open={editorOpen}
onClose={() => {
setEditorOpen(false);
setSelectedEvent(null);
setSelectedChannel(null);
setSelectedTemplate(null);
}}
eventId={selectedEvent.id}
channelId={selectedChannel.id}
eventLabel={selectedEvent.label}
channelLabel={selectedChannel.label}
template={selectedTemplate}
/>
)}
</div> </div>
); );
} }

View File

@@ -12,6 +12,8 @@ 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\TemplateProvider;
use WooNooW\Core\Notifications\PushNotificationHandler;
class NotificationsController { class NotificationsController {
@@ -55,6 +57,69 @@ class NotificationsController {
'permission_callback' => [$this, 'check_permission'], 'permission_callback' => [$this, 'check_permission'],
], ],
]); ]);
// GET /woonoow/v1/notifications/templates
register_rest_route($this->namespace, '/' . $this->rest_base . '/templates', [
[
'methods' => 'GET',
'callback' => [$this, 'get_templates'],
'permission_callback' => [$this, 'check_permission'],
],
]);
// GET /woonoow/v1/notifications/templates/:eventId/:channelId
register_rest_route($this->namespace, '/' . $this->rest_base . '/templates/(?P<eventId>[a-zA-Z0-9_-]+)/(?P<channelId>[a-zA-Z0-9_-]+)', [
[
'methods' => 'GET',
'callback' => [$this, 'get_template'],
'permission_callback' => [$this, 'check_permission'],
],
]);
// POST /woonoow/v1/notifications/templates
register_rest_route($this->namespace, '/' . $this->rest_base . '/templates', [
[
'methods' => 'POST',
'callback' => [$this, 'save_template'],
'permission_callback' => [$this, 'check_permission'],
],
]);
// DELETE /woonoow/v1/notifications/templates/:eventId/:channelId
register_rest_route($this->namespace, '/' . $this->rest_base . '/templates/(?P<eventId>[a-zA-Z0-9_-]+)/(?P<channelId>[a-zA-Z0-9_-]+)', [
[
'methods' => 'DELETE',
'callback' => [$this, 'delete_template'],
'permission_callback' => [$this, 'check_permission'],
],
]);
// GET /woonoow/v1/notifications/push/vapid-key
register_rest_route($this->namespace, '/' . $this->rest_base . '/push/vapid-key', [
[
'methods' => 'GET',
'callback' => [$this, 'get_vapid_key'],
'permission_callback' => '__return_true',
],
]);
// POST /woonoow/v1/notifications/push/subscribe
register_rest_route($this->namespace, '/' . $this->rest_base . '/push/subscribe', [
[
'methods' => 'POST',
'callback' => [$this, 'push_subscribe'],
'permission_callback' => '__return_true',
],
]);
// POST /woonoow/v1/notifications/push/unsubscribe
register_rest_route($this->namespace, '/' . $this->rest_base . '/push/unsubscribe', [
[
'methods' => 'POST',
'callback' => [$this, 'push_unsubscribe'],
'permission_callback' => '__return_true',
],
]);
} }
/** /**
@@ -72,6 +137,13 @@ class NotificationsController {
'enabled' => true, 'enabled' => true,
'builtin' => true, 'builtin' => true,
], ],
[
'id' => 'push',
'label' => __('Push Notifications', 'woonoow'),
'icon' => 'bell',
'enabled' => true,
'builtin' => true,
],
]; ];
// Allow addons to register their channels // Allow addons to register their channels
@@ -240,4 +312,160 @@ class NotificationsController {
public function check_permission() { public function check_permission() {
return current_user_can('manage_woocommerce') || current_user_can('manage_options'); return current_user_can('manage_woocommerce') || current_user_can('manage_options');
} }
/**
* Get all templates
*
* @param WP_REST_Request $request Request object
* @return WP_REST_Response
*/
public function get_templates(WP_REST_Request $request) {
$templates = TemplateProvider::get_templates();
return new WP_REST_Response($templates, 200);
}
/**
* Get single template
*
* @param WP_REST_Request $request Request object
* @return WP_REST_Response|WP_Error
*/
public function get_template(WP_REST_Request $request) {
$event_id = $request->get_param('eventId');
$channel_id = $request->get_param('channelId');
$template = TemplateProvider::get_template($event_id, $channel_id);
if (!$template) {
return new WP_Error(
'template_not_found',
__('Template not found', 'woonoow'),
['status' => 404]
);
}
return new WP_REST_Response($template, 200);
}
/**
* Save template
*
* @param WP_REST_Request $request Request object
* @return WP_REST_Response|WP_Error
*/
public function save_template(WP_REST_Request $request) {
$event_id = $request->get_param('eventId');
$channel_id = $request->get_param('channelId');
$subject = $request->get_param('subject');
$body = $request->get_param('body');
if (empty($event_id) || empty($channel_id)) {
return new WP_Error(
'invalid_params',
__('Event ID and Channel ID are required', 'woonoow'),
['status' => 400]
);
}
$success = TemplateProvider::save_template($event_id, $channel_id, [
'subject' => $subject,
'body' => $body,
]);
if (!$success) {
return new WP_Error(
'save_failed',
__('Failed to save template', 'woonoow'),
['status' => 500]
);
}
return new WP_REST_Response([
'success' => true,
'message' => __('Template saved successfully', 'woonoow'),
], 200);
}
/**
* Delete template (revert to default)
*
* @param WP_REST_Request $request Request object
* @return WP_REST_Response
*/
public function delete_template(WP_REST_Request $request) {
$event_id = $request->get_param('eventId');
$channel_id = $request->get_param('channelId');
TemplateProvider::delete_template($event_id, $channel_id);
return new WP_REST_Response([
'success' => true,
'message' => __('Template reverted to default', 'woonoow'),
], 200);
}
/**
* Get VAPID public key for push notifications
*
* @param WP_REST_Request $request Request object
* @return WP_REST_Response
*/
public function get_vapid_key(WP_REST_Request $request) {
$public_key = PushNotificationHandler::get_public_key();
return new WP_REST_Response([
'publicKey' => $public_key,
], 200);
}
/**
* Subscribe to push notifications
*
* @param WP_REST_Request $request Request object
* @return WP_REST_Response|WP_Error
*/
public function push_subscribe(WP_REST_Request $request) {
$subscription = $request->get_param('subscription');
$user_id = get_current_user_id();
if (empty($subscription)) {
return new WP_Error(
'invalid_subscription',
__('Subscription data is required', 'woonoow'),
['status' => 400]
);
}
$success = PushNotificationHandler::subscribe($subscription, $user_id);
if (!$success) {
return new WP_Error(
'subscribe_failed',
__('Failed to subscribe to push notifications', 'woonoow'),
['status' => 500]
);
}
return new WP_REST_Response([
'success' => true,
'message' => __('Subscribed to push notifications', 'woonoow'),
], 200);
}
/**
* Unsubscribe from push notifications
*
* @param WP_REST_Request $request Request object
* @return WP_REST_Response
*/
public function push_unsubscribe(WP_REST_Request $request) {
$subscription_id = $request->get_param('subscriptionId');
PushNotificationHandler::unsubscribe($subscription_id);
return new WP_REST_Response([
'success' => true,
'message' => __('Unsubscribed from push notifications', 'woonoow'),
], 200);
}
} }

View File

@@ -19,6 +19,7 @@ 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\PushNotificationHandler;
use WooNooW\Branding; use WooNooW\Branding;
class Bootstrap { class Bootstrap {
@@ -30,6 +31,7 @@ class Bootstrap {
StandaloneAdmin::init(); StandaloneAdmin::init();
Branding::init(); Branding::init();
MediaUpload::init(); MediaUpload::init();
PushNotificationHandler::init();
// Addon system (order matters: Registry → Routes → Navigation) // Addon system (order matters: Registry → Routes → Navigation)
AddonRegistry::init(); AddonRegistry::init();

View File

@@ -0,0 +1,213 @@
<?php
/**
* Push Notification Handler
*
* Handles browser push notifications for PWA.
*
* @package WooNooW\Core\Notifications
*/
namespace WooNooW\Core\Notifications;
class PushNotificationHandler {
/**
* Option key for storing subscriptions
*/
const SUBSCRIPTIONS_KEY = 'woonoow_push_subscriptions';
/**
* Option key for VAPID keys
*/
const VAPID_KEYS_KEY = 'woonoow_push_vapid_keys';
/**
* Initialize push notifications
*/
public static function init() {
// Generate VAPID keys if not exists
self::ensure_vapid_keys();
}
/**
* Ensure VAPID keys exist
*
* @return array
*/
public static function ensure_vapid_keys() {
$keys = get_option(self::VAPID_KEYS_KEY);
if (!$keys || !isset($keys['public_key']) || !isset($keys['private_key'])) {
// Generate new VAPID keys
$keys = self::generate_vapid_keys();
update_option(self::VAPID_KEYS_KEY, $keys);
}
return $keys;
}
/**
* Generate VAPID keys
*
* @return array
*/
private static function generate_vapid_keys() {
// For now, use placeholder keys
// In production, use web-push library or external service
return [
'public_key' => base64_encode(random_bytes(65)),
'private_key' => base64_encode(random_bytes(32)),
'generated_at' => current_time('mysql'),
];
}
/**
* Get VAPID public key
*
* @return string
*/
public static function get_public_key() {
$keys = self::ensure_vapid_keys();
return $keys['public_key'];
}
/**
* Subscribe to push notifications
*
* @param array $subscription Subscription data
* @param int $user_id User ID
* @return bool
*/
public static function subscribe($subscription, $user_id = 0) {
$subscriptions = get_option(self::SUBSCRIPTIONS_KEY, []);
$subscription_id = md5(json_encode($subscription));
$subscriptions[$subscription_id] = [
'subscription' => $subscription,
'user_id' => $user_id,
'subscribed_at' => current_time('mysql'),
];
return update_option(self::SUBSCRIPTIONS_KEY, $subscriptions);
}
/**
* Unsubscribe from push notifications
*
* @param string $subscription_id Subscription ID
* @return bool
*/
public static function unsubscribe($subscription_id) {
$subscriptions = get_option(self::SUBSCRIPTIONS_KEY, []);
if (isset($subscriptions[$subscription_id])) {
unset($subscriptions[$subscription_id]);
return update_option(self::SUBSCRIPTIONS_KEY, $subscriptions);
}
return false;
}
/**
* Get all subscriptions
*
* @param int $user_id Optional user ID filter
* @return array
*/
public static function get_subscriptions($user_id = null) {
$subscriptions = get_option(self::SUBSCRIPTIONS_KEY, []);
if ($user_id !== null) {
return array_filter($subscriptions, function($sub) use ($user_id) {
return $sub['user_id'] == $user_id;
});
}
return $subscriptions;
}
/**
* Send push notification
*
* @param string $title Notification title
* @param string $body Notification body
* @param array $options Additional options
* @param int $user_id Optional user ID to target
* @return int Number of notifications sent
*/
public static function send($title, $body, $options = [], $user_id = null) {
$subscriptions = self::get_subscriptions($user_id);
if (empty($subscriptions)) {
return 0;
}
$payload = [
'title' => $title,
'body' => $body,
'icon' => $options['icon'] ?? get_site_icon_url(),
'badge' => $options['badge'] ?? get_site_icon_url(),
'data' => $options['data'] ?? [],
'actions' => $options['actions'] ?? [],
];
$sent = 0;
foreach ($subscriptions as $subscription_id => $sub) {
try {
// In production, use web-push library
// For now, store in queue for service worker to fetch
self::queue_notification($subscription_id, $payload);
$sent++;
} catch (\Exception $e) {
error_log('Push notification error: ' . $e->getMessage());
}
}
return $sent;
}
/**
* Queue notification for delivery
*
* @param string $subscription_id Subscription ID
* @param array $payload Notification payload
*/
private static function queue_notification($subscription_id, $payload) {
$queue = get_option('woonoow_push_queue', []);
$queue[] = [
'subscription_id' => $subscription_id,
'payload' => $payload,
'queued_at' => current_time('mysql'),
];
update_option('woonoow_push_queue', $queue);
}
/**
* Get queued notifications for user
*
* @param int $user_id User ID
* @return array
*/
public static function get_queued_notifications($user_id) {
$queue = get_option('woonoow_push_queue', []);
$subscriptions = self::get_subscriptions($user_id);
$subscription_ids = array_keys($subscriptions);
$user_notifications = array_filter($queue, function($item) use ($subscription_ids) {
return in_array($item['subscription_id'], $subscription_ids);
});
// Clear delivered notifications
$remaining = array_filter($queue, function($item) use ($subscription_ids) {
return !in_array($item['subscription_id'], $subscription_ids);
});
update_option('woonoow_push_queue', $remaining);
return array_values($user_notifications);
}
}

View File

@@ -0,0 +1,276 @@
<?php
/**
* Notification Template Provider
*
* Manages notification templates for all channels.
*
* @package WooNooW\Core\Notifications
*/
namespace WooNooW\Core\Notifications;
class TemplateProvider {
/**
* Option key for storing templates
*/
const OPTION_KEY = 'woonoow_notification_templates';
/**
* Get all templates
*
* @return array
*/
public static function get_templates() {
$templates = get_option(self::OPTION_KEY, []);
// Merge with defaults
$defaults = self::get_default_templates();
return array_merge($defaults, $templates);
}
/**
* Get template for specific event and channel
*
* @param string $event_id Event ID
* @param string $channel_id Channel ID
* @return array|null
*/
public static function get_template($event_id, $channel_id) {
$templates = self::get_templates();
$key = "{$event_id}_{$channel_id}";
if (isset($templates[$key])) {
return $templates[$key];
}
// Return default if exists
$defaults = self::get_default_templates();
return $defaults[$key] ?? null;
}
/**
* Save template
*
* @param string $event_id Event ID
* @param string $channel_id Channel ID
* @param array $template Template data
* @return bool
*/
public static function save_template($event_id, $channel_id, $template) {
$templates = get_option(self::OPTION_KEY, []);
$key = "{$event_id}_{$channel_id}";
$templates[$key] = [
'event_id' => $event_id,
'channel_id' => $channel_id,
'subject' => $template['subject'] ?? '',
'body' => $template['body'] ?? '',
'variables' => $template['variables'] ?? [],
'updated_at' => current_time('mysql'),
];
return update_option(self::OPTION_KEY, $templates);
}
/**
* Delete template (revert to default)
*
* @param string $event_id Event ID
* @param string $channel_id Channel ID
* @return bool
*/
public static function delete_template($event_id, $channel_id) {
$templates = get_option(self::OPTION_KEY, []);
$key = "{$event_id}_{$channel_id}";
if (isset($templates[$key])) {
unset($templates[$key]);
return update_option(self::OPTION_KEY, $templates);
}
return false;
}
/**
* Get default templates
*
* @return array
*/
public static function get_default_templates() {
return [
// Email templates
'order_placed_email' => [
'event_id' => 'order_placed',
'channel_id' => 'email',
'subject' => __('New Order #{order_number}', 'woonoow'),
'body' => __("Hi Admin,\n\nYou have received a new order.\n\nOrder Number: {order_number}\nOrder Total: {order_total}\nCustomer: {customer_name}\nEmail: {customer_email}\n\nView order: {order_url}", 'woonoow'),
'variables' => self::get_order_variables(),
],
'order_processing_email' => [
'event_id' => 'order_processing',
'channel_id' => 'email',
'subject' => __('Your order #{order_number} is being processed', 'woonoow'),
'body' => __("Hi {customer_name},\n\nThank you for your order! We're now processing it.\n\nOrder Number: {order_number}\nOrder Total: {order_total}\nPayment Method: {payment_method}\n\nYou can track your order here: {order_url}\n\nBest regards,\n{store_name}", 'woonoow'),
'variables' => self::get_order_variables(),
],
'order_completed_email' => [
'event_id' => 'order_completed',
'channel_id' => 'email',
'subject' => __('Your order #{order_number} is complete', 'woonoow'),
'body' => __("Hi {customer_name},\n\nYour order has been completed and shipped!\n\nOrder Number: {order_number}\nOrder Total: {order_total}\nTracking Number: {tracking_number}\n\nThank you for shopping with us!\n\nBest regards,\n{store_name}", 'woonoow'),
'variables' => self::get_order_variables(),
],
'order_cancelled_email' => [
'event_id' => 'order_cancelled',
'channel_id' => 'email',
'subject' => __('Order #{order_number} has been cancelled', 'woonoow'),
'body' => __("Hi Admin,\n\nOrder #{order_number} has been cancelled.\n\nOrder Number: {order_number}\nOrder Total: {order_total}\nCustomer: {customer_name}\n\nView order: {order_url}", 'woonoow'),
'variables' => self::get_order_variables(),
],
'order_refunded_email' => [
'event_id' => 'order_refunded',
'channel_id' => 'email',
'subject' => __('Your order #{order_number} has been refunded', 'woonoow'),
'body' => __("Hi {customer_name},\n\nYour order has been refunded.\n\nOrder Number: {order_number}\nRefund Amount: {refund_amount}\n\nThe refund will be processed within 5-7 business days.\n\nBest regards,\n{store_name}", 'woonoow'),
'variables' => self::get_order_variables(),
],
'low_stock_email' => [
'event_id' => 'low_stock',
'channel_id' => 'email',
'subject' => __('Low Stock Alert: {product_name}', 'woonoow'),
'body' => __("Hi Admin,\n\nThe following product is running low on stock:\n\nProduct: {product_name}\nSKU: {product_sku}\nCurrent Stock: {stock_quantity}\n\nPlease restock soon.\n\nView product: {product_url}", 'woonoow'),
'variables' => self::get_product_variables(),
],
'out_of_stock_email' => [
'event_id' => 'out_of_stock',
'channel_id' => 'email',
'subject' => __('Out of Stock Alert: {product_name}', 'woonoow'),
'body' => __("Hi Admin,\n\nThe following product is now out of stock:\n\nProduct: {product_name}\nSKU: {product_sku}\n\nPlease restock immediately.\n\nView product: {product_url}", 'woonoow'),
'variables' => self::get_product_variables(),
],
'new_customer_email' => [
'event_id' => 'new_customer',
'channel_id' => 'email',
'subject' => __('Welcome to {store_name}!', 'woonoow'),
'body' => __("Hi {customer_name},\n\nWelcome to {store_name}!\n\nYour account has been created successfully.\n\nEmail: {customer_email}\n\nYou can now browse our products and place orders.\n\nVisit our store: {store_url}\n\nBest regards,\n{store_name}", 'woonoow'),
'variables' => self::get_customer_variables(),
],
'customer_note_email' => [
'event_id' => 'customer_note',
'channel_id' => 'email',
'subject' => __('Note added to your order #{order_number}', 'woonoow'),
'body' => __("Hi {customer_name},\n\nA note has been added to your order:\n\nOrder Number: {order_number}\nNote: {note_content}\n\nView order: {order_url}\n\nBest regards,\n{store_name}", 'woonoow'),
'variables' => self::get_order_variables(),
],
// Push notification templates
'order_placed_push' => [
'event_id' => 'order_placed',
'channel_id' => 'push',
'subject' => __('New Order #{order_number}', 'woonoow'),
'body' => __('New order from {customer_name} - {order_total}', 'woonoow'),
'variables' => self::get_order_variables(),
],
'order_processing_push' => [
'event_id' => 'order_processing',
'channel_id' => 'push',
'subject' => __('Order Processing', 'woonoow'),
'body' => __('Your order #{order_number} is being processed', 'woonoow'),
'variables' => self::get_order_variables(),
],
'order_completed_push' => [
'event_id' => 'order_completed',
'channel_id' => 'push',
'subject' => __('Order Completed', 'woonoow'),
'body' => __('Your order #{order_number} has been completed!', 'woonoow'),
'variables' => self::get_order_variables(),
],
'low_stock_push' => [
'event_id' => 'low_stock',
'channel_id' => 'push',
'subject' => __('Low Stock Alert', 'woonoow'),
'body' => __('{product_name} is running low on stock', 'woonoow'),
'variables' => self::get_product_variables(),
],
];
}
/**
* Get available order variables
*
* @return array
*/
public static function get_order_variables() {
return [
'order_number' => __('Order Number', 'woonoow'),
'order_total' => __('Order Total', 'woonoow'),
'order_status' => __('Order Status', 'woonoow'),
'order_date' => __('Order Date', 'woonoow'),
'order_url' => __('Order URL', 'woonoow'),
'payment_method' => __('Payment Method', 'woonoow'),
'shipping_method' => __('Shipping Method', 'woonoow'),
'tracking_number' => __('Tracking Number', 'woonoow'),
'refund_amount' => __('Refund Amount', 'woonoow'),
'customer_name' => __('Customer Name', 'woonoow'),
'customer_email' => __('Customer Email', 'woonoow'),
'customer_phone' => __('Customer Phone', 'woonoow'),
'billing_address' => __('Billing Address', 'woonoow'),
'shipping_address' => __('Shipping Address', 'woonoow'),
'store_name' => __('Store Name', 'woonoow'),
'store_url' => __('Store URL', 'woonoow'),
'store_email' => __('Store Email', 'woonoow'),
];
}
/**
* Get available product variables
*
* @return array
*/
public static function get_product_variables() {
return [
'product_name' => __('Product Name', 'woonoow'),
'product_sku' => __('Product SKU', 'woonoow'),
'product_url' => __('Product URL', 'woonoow'),
'stock_quantity' => __('Stock Quantity', 'woonoow'),
'store_name' => __('Store Name', 'woonoow'),
'store_url' => __('Store URL', 'woonoow'),
];
}
/**
* Get available customer variables
*
* @return array
*/
public static function get_customer_variables() {
return [
'customer_name' => __('Customer Name', 'woonoow'),
'customer_email' => __('Customer Email', 'woonoow'),
'customer_phone' => __('Customer Phone', 'woonoow'),
'store_name' => __('Store Name', 'woonoow'),
'store_url' => __('Store URL', 'woonoow'),
'store_email' => __('Store Email', 'woonoow'),
];
}
/**
* Replace variables in template
*
* @param string $content Content with variables
* @param array $data Data to replace variables
* @return string
*/
public static function replace_variables($content, $data) {
foreach ($data as $key => $value) {
$content = str_replace('{' . $key . '}', $value, $content);
}
return $content;
}
}