Files
WooNooW/NOTIFICATION_ENHANCEMENTS_PLAN.md
dwindown debe42f4e1 feat: Implement activity log system
##  Activity Log System - Complete

### Backend Implementation

**1. Database Table**
- `ActivityLogTable.php` - Table creation and management
- Auto-creates on plugin init
- Indexed for performance (user_id, action, object, created_at)

**2. Logger Class**
- `Logger.php` - Main logging functionality
- `log()` - Log activities
- `get_activities()` - Query with filters
- `get_stats()` - Activity statistics
- `cleanup()` - Delete old logs

**3. REST API**
- `ActivityLogController.php` - REST endpoints
- GET `/activity-log` - List activities
- POST `/activity-log` - Create activity
- GET `/activity-log/stats` - Get statistics

### Features

**Logging:**
- User ID and name
- Action type (order.created, product.updated, etc.)
- Object type and ID
- Object name (auto-resolved)
- Description
- Metadata (JSON)
- IP address
- User agent
- Timestamp

**Querying:**
- Pagination
- Filter by action, object, user, date
- Search by description, object name, user name
- Sort by date (newest first)

**Statistics:**
- Total activities
- By action (top 10)
- By user (top 10)
- Date range filtering

### Activity Types

**Orders:**
- order.created, order.updated, order.status_changed
- order.payment_completed, order.refunded, order.deleted

**Products:**
- product.created, product.updated
- product.stock_changed, product.deleted

**Customers:**
- customer.created, customer.updated, customer.deleted

**Notifications:**
- notification.sent, notification.failed, notification.clicked

**Settings:**
- settings.updated, channel.toggled, event.toggled

### Integration

- Registered in Bootstrap
- REST API routes registered
- Ready for WooCommerce hooks
- Ready for frontend UI

---

**Next:** Frontend UI + WooCommerce hooks
2025-11-11 17:52:03 +07:00

429 lines
11 KiB
Markdown

# Notification System Enhancements - Implementation Plan
## Overview
This document outlines the complete implementation plan for notification system enhancements, including dynamic URLs, activity logging, and customer notifications.
---
## 1. Customer Email Notifications
### Current State
- WooCommerce handles customer emails automatically
- WooNooW notifications are for admin alerts only
- Recipient field exists but not fully utilized
### Strategy: Integration, Not Replacement
**Decision:** Keep WooCommerce's customer email system, add admin notification layer
**Why:**
- ✅ WooCommerce emails are battle-tested
- ✅ Merchants already customize them
- ✅ Templates, styling, and logic already exist
- ✅ We focus on admin experience
**What We Add:**
- Admin notifications (email + push)
- Real-time alerts for admins
- Activity logging
- Better UI for managing notifications
### Implementation
**No code changes needed!** System already supports:
- `recipient: 'admin'` - Admin notifications
- `recipient: 'customer'` - Customer notifications (via WooCommerce)
- `recipient: 'both'` - Both (admin via WooNooW, customer via WooCommerce)
**Documentation Update:**
- Clarify that customer emails use WooCommerce
- Document integration points
- Add filter for custom recipient logic
---
## 2. Activity Log System
### Current State
- WooCommerce has order notes (limited)
- No comprehensive activity log
- No UI for viewing all activities
### Strategy: Build Custom Activity Log
**Why Build Our Own:**
- ✅ Full control over what's logged
- ✅ Better UI/UX
- ✅ Searchable and filterable
- ✅ Integration with notifications
- ✅ Real-time updates
### Data Structure
```php
// wp_woonoow_activity_log table
CREATE TABLE wp_woonoow_activity_log (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
user_id BIGINT UNSIGNED NOT NULL,
action VARCHAR(50) NOT NULL,
object_type VARCHAR(50) NOT NULL,
object_id BIGINT UNSIGNED NOT NULL,
description TEXT,
metadata LONGTEXT, -- JSON
ip_address VARCHAR(45),
user_agent TEXT,
created_at DATETIME NOT NULL,
INDEX idx_user_id (user_id),
INDEX idx_action (action),
INDEX idx_object (object_type, object_id),
INDEX idx_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
```
### Activity Types
**Orders:**
- `order.created` - Order created
- `order.updated` - Order updated
- `order.status_changed` - Status changed
- `order.payment_completed` - Payment completed
- `order.refunded` - Order refunded
- `order.deleted` - Order deleted
**Products:**
- `product.created` - Product created
- `product.updated` - Product updated
- `product.stock_changed` - Stock changed
- `product.deleted` - Product deleted
**Customers:**
- `customer.created` - Customer registered
- `customer.updated` - Customer updated
- `customer.deleted` - Customer deleted
**Notifications:**
- `notification.sent` - Notification sent
- `notification.failed` - Notification failed
- `notification.clicked` - Notification clicked
**Settings:**
- `settings.updated` - Settings changed
- `channel.toggled` - Channel enabled/disabled
- `event.toggled` - Event enabled/disabled
### Implementation Files
**Backend:**
1. `includes/Core/ActivityLog/Logger.php` - Main logger class
2. `includes/Core/ActivityLog/ActivityLogTable.php` - Database table
3. `includes/Api/ActivityLogController.php` - REST API
4. Hook into WooCommerce actions
**Frontend:**
1. `admin-spa/src/routes/ActivityLog/index.tsx` - Activity log page
2. `admin-spa/src/routes/ActivityLog/ActivityItem.tsx` - Single activity
3. `admin-spa/src/routes/ActivityLog/Filters.tsx` - Filter UI
---
## 3. Dynamic Push Notification URLs
### Current State
- Global URL: `/wp-admin/admin.php?page=woonoow#/orders`
- All notifications go to same page
### Strategy: Event-Specific Deep Links
### URL Templates
```php
$url_templates = [
// Orders
'order_placed' => '/wp-admin/admin.php?page=woonoow#/orders/{order_id}',
'order_processing' => '/wp-admin/admin.php?page=woonoow#/orders/{order_id}',
'order_completed' => '/wp-admin/admin.php?page=woonoow#/orders/{order_id}',
'order_cancelled' => '/wp-admin/admin.php?page=woonoow#/orders/{order_id}',
'order_refunded' => '/wp-admin/admin.php?page=woonoow#/orders/{order_id}',
// Products
'low_stock' => '/wp-admin/admin.php?page=woonoow#/products/{product_id}',
'out_of_stock' => '/wp-admin/admin.php?page=woonoow#/products/{product_id}',
// Customers
'new_customer' => '/wp-admin/admin.php?page=woonoow#/customers/{customer_id}',
'customer_note' => '/wp-admin/admin.php?page=woonoow#/orders/{order_id}',
];
```
### Template Variables
**Available Variables:**
- `{order_id}` - Order ID
- `{product_id}` - Product ID
- `{customer_id}` - Customer ID
- `{user_id}` - User ID
- `{site_url}` - Site URL
- `{admin_url}` - Admin URL
### Implementation
**Backend:**
1. Add URL template field to push settings
2. Parse template variables when sending
3. Store parsed URL in notification metadata
**Frontend:**
1. Add URL template field to Templates page
2. Show available variables
3. Preview parsed URL
---
## 4. Rich Notification Content
### Event-Specific Icons
```php
$notification_icons = [
'order_placed' => '🛒',
'order_processing' => '⚙️',
'order_completed' => '✅',
'order_cancelled' => '❌',
'order_refunded' => '💰',
'low_stock' => '📦',
'out_of_stock' => '🚫',
'new_customer' => '👤',
'customer_note' => '💬',
];
```
### Event-Specific Images
**Order Notifications:**
- Show first product image
- Fallback to store logo
**Product Notifications:**
- Show product image
- Fallback to placeholder
**Customer Notifications:**
- Show customer avatar (Gravatar)
- Fallback to default avatar
### Rich Content Structure
```json
{
"title": "New Order #1234",
"body": "John Doe ordered 2 items (Rp137.000)",
"icon": "🛒",
"image": "https://example.com/product.jpg",
"badge": "https://example.com/logo.png",
"data": {
"url": "/wp-admin/admin.php?page=woonoow#/orders/1234",
"order_id": 1234,
"customer_name": "John Doe",
"total": 137000
},
"actions": [
{
"action": "view",
"title": "View Order",
"icon": "👁️"
},
{
"action": "mark_processing",
"title": "Mark Processing",
"icon": "⚙️"
}
]
}
```
---
## Implementation Priority
### Phase 1: Dynamic URLs (Immediate) ✅
1. Add URL template to push settings
2. Parse template variables
3. Update notification sending logic
4. Test with different events
### Phase 2: Activity Log (Immediate) ✅
1. Create database table
2. Implement Logger class
3. Hook into WooCommerce actions
4. Create REST API
5. Build frontend UI
### Phase 3: Rich Content (Future) 📋
1. Add icon field to events
2. Add image field to events
3. Implement image fetching logic
4. Update push notification payload
5. Test on different browsers
### Phase 4: Notification Actions (Future) 📋
1. Define action types
2. Implement action handlers
3. Update push notification payload
4. Handle action clicks
5. Test on different browsers
---
## Database Schema
### Activity Log Table
```sql
CREATE TABLE IF NOT EXISTS wp_woonoow_activity_log (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
user_id BIGINT UNSIGNED NOT NULL,
user_name VARCHAR(255) NOT NULL,
action VARCHAR(50) NOT NULL,
object_type VARCHAR(50) NOT NULL,
object_id BIGINT UNSIGNED NOT NULL,
object_name VARCHAR(255),
description TEXT,
metadata LONGTEXT,
ip_address VARCHAR(45),
user_agent TEXT,
created_at DATETIME NOT NULL,
INDEX idx_user_id (user_id),
INDEX idx_action (action),
INDEX idx_object (object_type, object_id),
INDEX idx_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
```
### Push Settings Update
```php
// Add to woonoow_push_notification_settings
[
'enabled' => true,
'vapid_public_key' => '...',
'vapid_private_key' => '...',
'default_url' => '/wp-admin/admin.php?page=woonoow#/orders',
'url_templates' => [
'order_placed' => '/wp-admin/admin.php?page=woonoow#/orders/{order_id}',
// ... more templates
],
'show_store_logo' => true,
'show_product_images' => true,
'show_customer_avatar' => true,
'require_interaction' => false,
'silent_notifications' => false,
]
```
---
## API Endpoints
### Activity Log
```
GET /woonoow/v1/activity-log
?page=1&per_page=20&action=order.created&user_id=1&date_from=2025-11-01
POST /woonoow/v1/activity-log
{ action, object_type, object_id, description, metadata }
GET /woonoow/v1/activity-log/stats
?date_from=2025-11-01&date_to=2025-11-30
```
### Push Notification URLs
```
GET /woonoow/v1/notifications/push/url-templates
POST /woonoow/v1/notifications/push/url-templates
{ event_id, url_template }
POST /woonoow/v1/notifications/push/preview-url
{ event_id, url_template, variables }
```
---
## Testing Checklist
### Dynamic URLs
- [ ] Order notification → Order detail page
- [ ] Product notification → Product edit page
- [ ] Customer notification → Customer page
- [ ] Variables parsed correctly
- [ ] Fallback to default URL
### Activity Log
- [ ] Activities logged correctly
- [ ] Filtering works
- [ ] Pagination works
- [ ] Search works
- [ ] Real-time updates
- [ ] Performance with 10k+ logs
### Rich Content
- [ ] Icons display correctly
- [ ] Images load correctly
- [ ] Fallbacks work
- [ ] Different browsers (Chrome, Firefox, Safari)
- [ ] Mobile devices
---
## Success Metrics
**User Experience:**
- Click-through rate on notifications
- Time to action after notification
- User satisfaction score
**Technical:**
- Notification delivery rate
- Activity log query performance
- Storage usage
**Business:**
- Faster response to orders
- Reduced missed notifications
- Better audit trail
---
## Timeline
**Week 1: Dynamic URLs + Activity Log**
- Day 1-2: Dynamic URLs implementation
- Day 3-5: Activity Log backend
- Day 6-7: Activity Log frontend
**Week 2: Rich Content**
- Day 1-3: Icons and images
- Day 4-5: Testing and polish
- Day 6-7: Documentation
**Week 3: Notification Actions**
- Day 1-3: Action handlers
- Day 4-5: Testing
- Day 6-7: Documentation and release
---
## Conclusion
This plan provides a comprehensive roadmap for enhancing the notification system with:
1. ✅ Customer email clarification (no changes needed)
2. ✅ Activity log system (custom build)
3. ✅ Dynamic push URLs (event-specific)
4. ✅ Rich notification content (icons, images, actions)
All enhancements are designed to improve admin experience while maintaining compatibility with WooCommerce's existing systems.