Add Activepieces integration for workflow automation

- Add Activepieces fork with SmoothSchedule custom piece
- Create integrations app with Activepieces service layer
- Add embed token endpoint for iframe integration
- Create Automations page with embedded workflow builder
- Add sidebar visibility fix for embed mode
- Add list inactive customers endpoint to Public API
- Include SmoothSchedule triggers: event created/updated/cancelled
- Include SmoothSchedule actions: create/update/cancel events, list resources/services/customers

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
poduck
2025-12-18 22:59:37 -05:00
parent 9848268d34
commit 3aa7199503
16292 changed files with 1284892 additions and 4708 deletions

View File

@@ -117,10 +117,7 @@ const HelpSettingsCommunication = React.lazy(() => import('./pages/help/HelpSett
const HelpComprehensive = React.lazy(() => import('./pages/help/HelpComprehensive'));
const StaffHelp = React.lazy(() => import('./pages/help/StaffHelp'));
const PlatformSupport = React.lazy(() => import('./pages/PlatformSupport')); // Import Platform Support page (for businesses to contact SmoothSchedule)
const AutomationMarketplace = React.lazy(() => import('./pages/AutomationMarketplace')); // Import Automation Marketplace page
const MyAutomations = React.lazy(() => import('./pages/MyAutomations')); // Import My Automations page
const CreateAutomation = React.lazy(() => import('./pages/CreateAutomation')); // Import Create Automation page
const Tasks = React.lazy(() => import('./pages/Tasks')); // Import Tasks page for scheduled automation executions
const Automations = React.lazy(() => import('./pages/Automations')); // Import Automations page (Activepieces embedded)
const SystemEmailTemplates = React.lazy(() => import('./pages/settings/SystemEmailTemplates')); // System email templates (Puck-based)
const Contracts = React.lazy(() => import('./pages/Contracts')); // Import Contracts page
const ContractTemplates = React.lazy(() => import('./pages/ContractTemplates')); // Import Contract Templates page
@@ -805,46 +802,22 @@ const AppContent: React.FC = () => {
<Route path="/dashboard/help/settings/embed-widget" element={<HelpSettingsEmbedWidget />} />
<Route path="/dashboard/help/settings/staff-roles" element={<HelpSettingsStaffRoles />} />
<Route path="/dashboard/help/settings/communication" element={<HelpSettingsCommunication />} />
{/* Automations - Activepieces embedded builder */}
<Route
path="/dashboard/automations/marketplace"
path="/dashboard/automations"
element={
canAccess('can_access_automations') ? (
<AutomationMarketplace />
) : (
<Navigate to="/dashboard" />
)
}
/>
<Route
path="/dashboard/automations/my-automations"
element={
canAccess('can_access_automations') ? (
<MyAutomations />
) : (
<Navigate to="/dashboard" />
)
}
/>
<Route
path="/dashboard/automations/create"
element={
canAccess('can_access_automations') ? (
<CreateAutomation />
) : (
<Navigate to="/dashboard" />
)
}
/>
<Route
path="/dashboard/tasks"
element={
canAccess('can_access_tasks') ? (
<Tasks />
<Automations />
) : (
<Navigate to="/dashboard" />
)
}
/>
{/* Redirect old automation routes to new page */}
<Route path="/dashboard/automations/marketplace" element={<Navigate to="/dashboard/automations" replace />} />
<Route path="/dashboard/automations/my-automations" element={<Navigate to="/dashboard/automations" replace />} />
<Route path="/dashboard/automations/create" element={<Navigate to="/dashboard/automations" replace />} />
<Route path="/dashboard/tasks" element={<Navigate to="/dashboard/automations" replace />} />
{/* Email templates are now accessed via Settings > Email Templates */}
<Route path="/dashboard/support" element={<PlatformSupport />} />
<Route

View File

@@ -0,0 +1,352 @@
/**
* CreateAppointmentModal Component
*
* Modal for creating new appointments with customer, service, and participant selection.
* Supports both linked customers and participants with external email addresses.
*/
import React, { useState, useMemo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { X, Search, User as UserIcon, Calendar, Clock, Users } from 'lucide-react';
import { createPortal } from 'react-dom';
import { Resource, Service, ParticipantInput } from '../types';
import { useCustomers } from '../hooks/useCustomers';
import { ParticipantSelector } from './ParticipantSelector';
interface CreateAppointmentModalProps {
resources: Resource[];
services: Service[];
initialDate?: Date;
initialResourceId?: string | null;
onCreate: (appointmentData: {
serviceId: string;
customerId: string;
startTime: Date;
resourceId?: string | null;
durationMinutes: number;
notes?: string;
participantsInput?: ParticipantInput[];
}) => void;
onClose: () => void;
isCreating?: boolean;
}
export const CreateAppointmentModal: React.FC<CreateAppointmentModalProps> = ({
resources,
services,
initialDate,
initialResourceId,
onCreate,
onClose,
isCreating = false,
}) => {
const { t } = useTranslation();
// Form state
const [selectedServiceId, setSelectedServiceId] = useState('');
const [selectedCustomerId, setSelectedCustomerId] = useState('');
const [customerSearch, setCustomerSearch] = useState('');
const [showCustomerDropdown, setShowCustomerDropdown] = useState(false);
const [selectedDateTime, setSelectedDateTime] = useState(() => {
// Default to initial date or now, rounded to nearest 15 min
const date = initialDate || new Date();
const minutes = Math.ceil(date.getMinutes() / 15) * 15;
date.setMinutes(minutes, 0, 0);
// Convert to datetime-local format
const localDateTime = new Date(date.getTime() - date.getTimezoneOffset() * 60000)
.toISOString()
.slice(0, 16);
return localDateTime;
});
const [selectedResourceId, setSelectedResourceId] = useState(initialResourceId || '');
const [duration, setDuration] = useState(30);
const [notes, setNotes] = useState('');
const [participants, setParticipants] = useState<ParticipantInput[]>([]);
// Fetch customers for search
const { data: customers = [] } = useCustomers({ search: customerSearch });
// Get selected customer details
const selectedCustomer = useMemo(() => {
return customers.find(c => c.id === selectedCustomerId);
}, [customers, selectedCustomerId]);
// Get selected service details
const selectedService = useMemo(() => {
return services.find(s => s.id === selectedServiceId);
}, [services, selectedServiceId]);
// When service changes, update duration to service default
const handleServiceChange = useCallback((serviceId: string) => {
setSelectedServiceId(serviceId);
const service = services.find(s => s.id === serviceId);
if (service) {
setDuration(service.durationMinutes);
}
}, [services]);
// Handle customer selection from search
const handleSelectCustomer = useCallback((customerId: string, customerName: string) => {
setSelectedCustomerId(customerId);
setCustomerSearch(customerName);
setShowCustomerDropdown(false);
}, []);
// Filter customers based on search
const filteredCustomers = useMemo(() => {
if (!customerSearch.trim()) return [];
return customers.slice(0, 10);
}, [customers, customerSearch]);
// Validation
const canCreate = useMemo(() => {
return selectedServiceId && selectedCustomerId && selectedDateTime && duration >= 15;
}, [selectedServiceId, selectedCustomerId, selectedDateTime, duration]);
// Handle create
const handleCreate = useCallback(() => {
if (!canCreate) return;
const startTime = new Date(selectedDateTime);
onCreate({
serviceId: selectedServiceId,
customerId: selectedCustomerId,
startTime,
resourceId: selectedResourceId || null,
durationMinutes: duration,
notes: notes.trim() || undefined,
participantsInput: participants.length > 0 ? participants : undefined,
});
}, [canCreate, selectedServiceId, selectedCustomerId, selectedDateTime, selectedResourceId, duration, notes, participants, onCreate]);
const modalContent = (
<div
className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm"
onClick={onClose}
>
<div
className="w-full max-w-lg bg-white dark:bg-gray-800 rounded-xl shadow-xl border border-gray-200 dark:border-gray-700 overflow-hidden max-h-[90vh] flex flex-col"
onClick={e => e.stopPropagation()}
>
{/* Header */}
<div className="flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-gray-700 bg-gradient-to-r from-brand-50 to-brand-100 dark:from-brand-900/30 dark:to-brand-800/30">
<div className="flex items-center gap-3">
<div className="p-2 bg-brand-500 rounded-lg">
<Calendar className="w-5 h-5 text-white" />
</div>
<h3 className="text-lg font-semibold text-gray-900 dark:text-white">
{t('scheduler.newAppointment', 'New Appointment')}
</h3>
</div>
<button
onClick={onClose}
className="p-1 text-gray-400 hover:bg-white/50 dark:hover:bg-gray-700/50 rounded-full transition-colors"
>
<X size={20} />
</button>
</div>
{/* Scrollable content */}
<div className="overflow-y-auto flex-1 p-6 space-y-5">
{/* Service Selection */}
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
{t('services.title', 'Service')} <span className="text-red-500">*</span>
</label>
<select
value={selectedServiceId}
onChange={(e) => handleServiceChange(e.target.value)}
className="w-full px-3 py-2.5 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg text-sm text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-brand-500"
>
<option value="">{t('scheduler.selectService', 'Select a service...')}</option>
{services.filter(s => s.is_active !== false).map(service => (
<option key={service.id} value={service.id}>
{service.name} ({service.durationMinutes} min)
</option>
))}
</select>
</div>
{/* Customer Selection */}
<div className="relative">
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
{t('customers.title', 'Customer')} <span className="text-red-500">*</span>
</label>
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
<input
type="text"
value={customerSearch}
onChange={(e) => {
setCustomerSearch(e.target.value);
setShowCustomerDropdown(true);
if (!e.target.value.trim()) {
setSelectedCustomerId('');
}
}}
onFocus={() => setShowCustomerDropdown(true)}
placeholder={t('customers.searchPlaceholder', 'Search customers by name or email...')}
className="w-full pl-10 pr-4 py-2.5 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg text-sm text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-brand-500"
/>
{selectedCustomer && (
<button
onClick={() => {
setSelectedCustomerId('');
setCustomerSearch('');
}}
className="absolute right-3 top-1/2 -translate-y-1/2 p-1 text-gray-400 hover:text-gray-600"
>
<X size={14} />
</button>
)}
</div>
{/* Customer search results dropdown */}
{showCustomerDropdown && customerSearch.trim() && (
<div className="absolute z-50 w-full mt-1 bg-white dark:bg-gray-800 border dark:border-gray-700 rounded-lg shadow-lg max-h-60 overflow-y-auto">
{filteredCustomers.length === 0 ? (
<div className="px-4 py-3 text-sm text-gray-500 dark:text-gray-400">
{t('common.noResults', 'No results found')}
</div>
) : (
filteredCustomers.map((customer) => (
<button
key={customer.id}
type="button"
onClick={() => handleSelectCustomer(customer.id, customer.name)}
className="w-full px-4 py-2 flex items-center gap-3 hover:bg-gray-100 dark:hover:bg-gray-700 text-left"
>
<div className="flex-shrink-0 w-8 h-8 bg-gray-200 dark:bg-gray-600 rounded-full flex items-center justify-center">
<UserIcon className="w-4 h-4 text-gray-500 dark:text-gray-400" />
</div>
<div className="flex-grow min-w-0">
<div className="text-sm font-medium text-gray-900 dark:text-white truncate">
{customer.name}
</div>
<div className="text-xs text-gray-500 dark:text-gray-400 truncate">
{customer.email}
</div>
</div>
</button>
))
)}
</div>
)}
{/* Click outside to close dropdown */}
{showCustomerDropdown && (
<div
className="fixed inset-0 z-40"
onClick={() => setShowCustomerDropdown(false)}
/>
)}
</div>
{/* Date, Time & Duration */}
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
{t('scheduler.selectDate', 'Date')} & {t('scheduler.selectTime', 'Time')} <span className="text-red-500">*</span>
</label>
<input
type="datetime-local"
value={selectedDateTime}
onChange={(e) => setSelectedDateTime(e.target.value)}
className="w-full px-3 py-2.5 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg text-sm text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-brand-500"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
<Clock className="w-4 h-4 inline mr-1" />
{t('scheduler.duration', 'Duration')} (min) <span className="text-red-500">*</span>
</label>
<input
type="number"
min="15"
step="15"
value={duration}
onChange={(e) => {
const value = parseInt(e.target.value);
setDuration(value >= 15 ? value : 15);
}}
className="w-full px-3 py-2.5 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg text-sm text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-brand-500"
/>
</div>
</div>
{/* Resource Assignment */}
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
{t('scheduler.selectResource', 'Assign to Resource')}
</label>
<select
value={selectedResourceId}
onChange={(e) => setSelectedResourceId(e.target.value)}
className="w-full px-3 py-2.5 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg text-sm text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-brand-500"
>
<option value="">{t('scheduler.unassigned', 'Unassigned')}</option>
{resources.map(resource => (
<option key={resource.id} value={resource.id}>
{resource.name}
</option>
))}
</select>
</div>
{/* Participants Section */}
<div className="p-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg">
<div className="flex items-center gap-2 mb-3">
<Users className="w-4 h-4 text-gray-500" />
<span className="text-sm font-medium text-gray-700 dark:text-gray-300">
{t('participants.additionalParticipants', 'Additional Participants')}
</span>
</div>
<ParticipantSelector
value={participants}
onChange={setParticipants}
allowedRoles={['STAFF', 'CUSTOMER', 'OBSERVER']}
allowExternalEmail={true}
/>
</div>
{/* Notes */}
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
{t('scheduler.notes', 'Notes')}
</label>
<textarea
value={notes}
onChange={(e) => setNotes(e.target.value)}
rows={3}
className="w-full px-3 py-2 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg text-sm text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-brand-500 resize-none"
placeholder={t('scheduler.notesPlaceholder', 'Add notes about this appointment...')}
/>
</div>
</div>
{/* Footer with action buttons */}
<div className="px-6 py-4 border-t border-gray-200 dark:border-gray-700 flex justify-end gap-3 bg-white dark:bg-gray-800">
<button
onClick={onClose}
disabled={isCreating}
className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-200 bg-gray-100 dark:bg-gray-700 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors disabled:opacity-50"
>
{t('common.cancel', 'Cancel')}
</button>
<button
onClick={handleCreate}
disabled={!canCreate || isCreating}
className="px-4 py-2 text-sm font-medium text-white bg-brand-600 rounded-lg hover:bg-brand-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
>
{isCreating ? t('common.creating', 'Creating...') : t('scheduler.createAppointment', 'Create Appointment')}
</button>
</div>
</div>
</div>
);
return createPortal(modalContent, document.body);
};
export default CreateAppointmentModal;

View File

@@ -1,639 +0,0 @@
import React, { useState } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import axios from '../api/client';
import { X, Calendar, Clock, RotateCw, Zap, CalendarDays } from 'lucide-react';
import toast from 'react-hot-toast';
import {
SCHEDULE_PRESETS,
TRIGGER_OPTIONS,
OFFSET_PRESETS,
getScheduleDescription,
getEventTimingDescription,
} from '../constants/schedulePresets';
import { ErrorMessage } from './ui';
interface AutomationInstallation {
id: string;
template: number;
template_name: string;
template_slug: string;
template_description: string;
category: string;
version: string;
author_name: string;
logo_url?: string;
template_variables: Record<string, unknown>;
scheduled_task?: number;
scheduled_task_name?: string;
installed_at: string;
config_values: Record<string, unknown>;
has_update: boolean;
}
interface CreateTaskModalProps {
isOpen: boolean;
onClose: () => void;
onSuccess: () => void;
}
// Task type: scheduled or event-based
type TaskType = 'scheduled' | 'event';
const CreateTaskModal: React.FC<CreateTaskModalProps> = ({ isOpen, onClose, onSuccess }) => {
const queryClient = useQueryClient();
const [step, setStep] = useState(1);
const [selectedAutomation, setSelectedAutomation] = useState<AutomationInstallation | null>(null);
const [taskName, setTaskName] = useState('');
const [description, setDescription] = useState('');
// Task type selection
const [taskType, setTaskType] = useState<TaskType>('scheduled');
// Schedule selection (for scheduled tasks)
const [selectedPreset, setSelectedPreset] = useState<string>('every_hour');
const [scheduleMode, setScheduleMode] = useState<'preset' | 'onetime' | 'advanced'>('preset');
// One-time schedule
const [runAtDate, setRunAtDate] = useState('');
const [runAtTime, setRunAtTime] = useState('');
// Advanced (custom cron)
const [customCron, setCustomCron] = useState('0 0 * * *');
// Event automation settings (for event tasks)
const [selectedTrigger, setSelectedTrigger] = useState<string>('at_start');
const [selectedOffset, setSelectedOffset] = useState<number>(0);
const [applyToExisting, setApplyToExisting] = useState<boolean>(true);
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState('');
// Fetch available automations
const { data: automations = [], isLoading: automationsLoading } = useQuery<AutomationInstallation[]>({
queryKey: ['automation-installations'],
queryFn: async () => {
const { data } = await axios.get('/automation-installations/');
// Filter out automations that already have scheduled tasks
return data.filter((p: AutomationInstallation) => !p.scheduled_task);
},
enabled: isOpen,
});
const handleClose = () => {
setStep(1);
setSelectedAutomation(null);
setTaskName('');
setDescription('');
setError('');
setTaskType('scheduled');
setScheduleMode('preset');
setSelectedPreset('every_hour');
setSelectedTrigger('at_start');
setSelectedOffset(0);
setApplyToExisting(true);
setRunAtDate('');
setRunAtTime('');
setCustomCron('0 0 * * *');
onClose();
};
const handleAutomationSelect = (automation: AutomationInstallation) => {
setSelectedAutomation(automation);
setTaskName(`${automation.template_name} - Scheduled Task`);
setStep(2);
};
// Use shared helper functions from constants
const scheduleDescriptionText = getScheduleDescription(
scheduleMode,
selectedPreset,
runAtDate,
runAtTime,
customCron
);
const eventTimingDescriptionText = getEventTimingDescription(selectedTrigger, selectedOffset);
const showOffset = !['on_complete', 'on_cancel'].includes(selectedTrigger);
const handleSubmit = async () => {
if (!selectedAutomation) return;
setIsSubmitting(true);
setError('');
try {
if (taskType === 'event') {
// Create global event automation (applies to all events)
const payload = {
automation_installation: selectedAutomation.id,
trigger: selectedTrigger,
offset_minutes: selectedOffset,
is_active: true,
apply_to_existing: applyToExisting,
};
await axios.post('/global-event-automations/', payload);
queryClient.invalidateQueries({ queryKey: ['global-event-automations'] });
toast.success(applyToExisting ? 'Automation attached to all events' : 'Automation will apply to future events');
} else {
// Create scheduled task
let payload: any = {
name: taskName,
description,
automation_name: selectedAutomation.template_slug,
status: 'ACTIVE',
automation_config: selectedAutomation.config_values || {},
};
if (scheduleMode === 'onetime') {
payload.schedule_type = 'ONE_TIME';
payload.run_at = `${runAtDate}T${runAtTime}:00`;
} else if (scheduleMode === 'advanced') {
payload.schedule_type = 'CRON';
payload.cron_expression = customCron;
} else {
const preset = SCHEDULE_PRESETS.find(p => p.id === selectedPreset);
if (preset) {
payload.schedule_type = preset.type;
if (preset.type === 'INTERVAL') {
payload.interval_minutes = preset.interval_minutes;
} else {
payload.cron_expression = preset.cron_expression;
}
}
}
await axios.post('/scheduled-tasks/', payload);
toast.success('Scheduled task created');
}
onSuccess();
handleClose();
} catch (err: any) {
setError(err.response?.data?.detail || err.response?.data?.error || 'Failed to create task');
} finally {
setIsSubmitting(false);
}
};
if (!isOpen) return null;
return (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50">
<div className="bg-white dark:bg-gray-800 rounded-lg max-w-2xl w-full max-h-[90vh] overflow-y-auto">
{/* Header */}
<div className="flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700">
<h2 className="text-2xl font-bold text-gray-900 dark:text-white">
Schedule a Task
</h2>
<button
onClick={handleClose}
className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700"
>
<X className="w-5 h-5" />
</button>
</div>
{/* Steps indicator */}
<div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
<div className="flex items-center justify-center gap-4">
<div className={`flex items-center gap-2 ${step >= 1 ? 'text-blue-600 dark:text-blue-400' : 'text-gray-400'}`}>
<div className={`w-8 h-8 rounded-full flex items-center justify-center ${step >= 1 ? 'bg-blue-600 text-white' : 'bg-gray-200 dark:bg-gray-700 text-gray-500'}`}>
1
</div>
<span className="font-medium">Select Automation</span>
</div>
<div className="w-16 h-0.5 bg-gray-200 dark:bg-gray-700" />
<div className={`flex items-center gap-2 ${step >= 2 ? 'text-blue-600 dark:text-blue-400' : 'text-gray-400'}`}>
<div className={`w-8 h-8 rounded-full flex items-center justify-center ${step >= 2 ? 'bg-blue-600 text-white' : 'bg-gray-200 dark:bg-gray-700 text-gray-500'}`}>
2
</div>
<span className="font-medium">Configure</span>
</div>
</div>
</div>
{/* Content */}
<div className="p-6">
{/* Step 1: Select Automation */}
{step === 1 && (
<div>
<p className="text-gray-600 dark:text-gray-400 mb-4">
Select an automation to schedule for automatic execution.
</p>
{automationsLoading ? (
<div className="flex items-center justify-center py-12">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
</div>
) : automations.length === 0 ? (
<div className="text-center py-12 bg-gray-50 dark:bg-gray-900 rounded-lg">
<Zap className="w-12 h-12 text-gray-400 mx-auto mb-3" />
<p className="text-gray-600 dark:text-gray-400 mb-2">No available automations</p>
<p className="text-sm text-gray-500 dark:text-gray-500">
Install automations from the Marketplace first, or all your automations are already scheduled.
</p>
</div>
) : (
<div className="grid grid-cols-1 gap-3 max-h-96 overflow-y-auto">
{automations.map((automation) => (
<button
key={automation.id}
onClick={() => handleAutomationSelect(automation)}
className="text-left p-4 border border-gray-200 dark:border-gray-700 rounded-lg hover:border-blue-500 dark:hover:border-blue-500 hover:bg-blue-50 dark:hover:bg-blue-900/20 transition-colors"
>
<div className="flex items-start gap-3">
{automation.logo_url ? (
<img src={automation.logo_url} alt="" className="w-10 h-10 rounded" />
) : (
<div className="w-10 h-10 rounded bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center">
<Zap className="w-5 h-5 text-blue-600 dark:text-blue-400" />
</div>
)}
<div className="flex-1">
<h3 className="font-semibold text-gray-900 dark:text-white mb-1">
{automation.template_name}
</h3>
<p className="text-sm text-gray-600 dark:text-gray-400 line-clamp-2">
{automation.template_description}
</p>
</div>
</div>
</button>
))}
</div>
)}
</div>
)}
{/* Step 2: Configure Schedule */}
{step === 2 && selectedAutomation && (
<div className="space-y-6">
{/* Selected Automation */}
<div className="p-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg">
<div className="flex items-center gap-3">
<Zap className="w-5 h-5 text-blue-600 dark:text-blue-400" />
<div>
<p className="text-sm text-blue-800 dark:text-blue-200 font-medium">
Selected Automation
</p>
<p className="text-blue-900 dark:text-blue-100">
{selectedAutomation.template_name}
</p>
</div>
</div>
</div>
{/* Task Type Selection */}
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
How should this automation run?
</label>
<div className="grid grid-cols-2 gap-3">
<button
onClick={() => setTaskType('scheduled')}
className={`p-4 rounded-lg border-2 text-left transition-all ${
taskType === 'scheduled'
? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
: 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600'
}`}
>
<div className="flex items-center gap-2 mb-2">
<Clock className={`w-5 h-5 ${taskType === 'scheduled' ? 'text-blue-600 dark:text-blue-400' : 'text-gray-400'}`} />
<span className={`font-semibold ${taskType === 'scheduled' ? 'text-blue-700 dark:text-blue-300' : 'text-gray-900 dark:text-white'}`}>
Scheduled Task
</span>
</div>
<p className="text-xs text-gray-500 dark:text-gray-400">
Run on a fixed schedule (hourly, daily, weekly, etc.)
</p>
</button>
<button
onClick={() => setTaskType('event')}
className={`p-4 rounded-lg border-2 text-left transition-all ${
taskType === 'event'
? 'border-purple-500 bg-purple-50 dark:bg-purple-900/20'
: 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600'
}`}
>
<div className="flex items-center gap-2 mb-2">
<CalendarDays className={`w-5 h-5 ${taskType === 'event' ? 'text-purple-600 dark:text-purple-400' : 'text-gray-400'}`} />
<span className={`font-semibold ${taskType === 'event' ? 'text-purple-700 dark:text-purple-300' : 'text-gray-900 dark:text-white'}`}>
Event Automation
</span>
</div>
<p className="text-xs text-gray-500 dark:text-gray-400">
Run for every appointment on your calendar
</p>
</button>
</div>
</div>
{/* Scheduled Task Options */}
{taskType === 'scheduled' && (
<>
{/* Task Name */}
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Task Name
</label>
<input
type="text"
value={taskName}
onChange={(e) => setTaskName(e.target.value)}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-900 text-gray-900 dark:text-white"
placeholder="e.g., Daily Customer Report"
/>
</div>
{/* Schedule Mode Tabs */}
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
Schedule
</label>
<div className="flex border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden mb-4">
<button
onClick={() => setScheduleMode('preset')}
className={`flex-1 px-4 py-2 text-sm font-medium transition-colors ${
scheduleMode === 'preset'
? 'bg-blue-600 text-white'
: 'bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700'
}`}
>
<RotateCw className="w-4 h-4 inline mr-2" />
Recurring
</button>
<button
onClick={() => setScheduleMode('onetime')}
className={`flex-1 px-4 py-2 text-sm font-medium transition-colors ${
scheduleMode === 'onetime'
? 'bg-blue-600 text-white'
: 'bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700'
}`}
>
<Calendar className="w-4 h-4 inline mr-2" />
One-Time
</button>
<button
onClick={() => setScheduleMode('advanced')}
className={`flex-1 px-4 py-2 text-sm font-medium transition-colors ${
scheduleMode === 'advanced'
? 'bg-blue-600 text-white'
: 'bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700'
}`}
>
<Clock className="w-4 h-4 inline mr-2" />
Advanced
</button>
</div>
{/* Preset Selection */}
{scheduleMode === 'preset' && (
<div className="grid grid-cols-2 gap-2 max-h-64 overflow-y-auto">
{SCHEDULE_PRESETS.map((preset) => (
<button
key={preset.id}
onClick={() => setSelectedPreset(preset.id)}
className={`text-left p-3 rounded-lg border transition-colors ${
selectedPreset === preset.id
? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
: 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600'
}`}
>
<p className={`text-sm font-medium ${selectedPreset === preset.id ? 'text-blue-700 dark:text-blue-300' : 'text-gray-900 dark:text-white'}`}>
{preset.label}
</p>
<p className="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
{preset.description}
</p>
</button>
))}
</div>
)}
{/* One-Time Selection */}
{scheduleMode === 'onetime' && (
<div className="grid grid-cols-2 gap-4 p-4 bg-gray-50 dark:bg-gray-900 rounded-lg">
<div>
<label className="block text-sm text-gray-600 dark:text-gray-400 mb-1">
Date
</label>
<input
type="date"
value={runAtDate}
onChange={(e) => setRunAtDate(e.target.value)}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
/>
</div>
<div>
<label className="block text-sm text-gray-600 dark:text-gray-400 mb-1">
Time
</label>
<input
type="time"
value={runAtTime}
onChange={(e) => setRunAtTime(e.target.value)}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
/>
</div>
</div>
)}
{/* Advanced Cron */}
{scheduleMode === 'advanced' && (
<div className="p-4 bg-gray-50 dark:bg-gray-900 rounded-lg space-y-3">
<div>
<label className="block text-sm text-gray-600 dark:text-gray-400 mb-1">
Cron Expression
</label>
<input
type="text"
value={customCron}
onChange={(e) => setCustomCron(e.target.value)}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white font-mono text-sm"
placeholder="0 0 * * *"
/>
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
Format: minute hour day month weekday (e.g., "0 9 * * 1-5" = weekdays at 9 AM)
</p>
</div>
</div>
)}
</div>
{/* Schedule Preview */}
<div className="p-3 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg">
<div className="flex items-center gap-2">
<Clock className="w-4 h-4 text-green-600 dark:text-green-400" />
<span className="text-sm text-green-800 dark:text-green-200">
<strong>Schedule:</strong> {scheduleDescriptionText}
</span>
</div>
</div>
</>
)}
{/* Event Automation Options */}
{taskType === 'event' && (
<>
{/* Apply to which events */}
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
Apply to which events?
</label>
<div className="grid grid-cols-2 gap-3">
<button
onClick={() => setApplyToExisting(true)}
className={`p-3 rounded-lg border-2 text-left transition-all ${
applyToExisting
? 'border-purple-500 bg-purple-50 dark:bg-purple-900/20'
: 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600'
}`}
>
<span className={`font-medium text-sm ${applyToExisting ? 'text-purple-700 dark:text-purple-300' : 'text-gray-900 dark:text-white'}`}>
All Events
</span>
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
Existing + future appointments
</p>
</button>
<button
onClick={() => setApplyToExisting(false)}
className={`p-3 rounded-lg border-2 text-left transition-all ${
!applyToExisting
? 'border-purple-500 bg-purple-50 dark:bg-purple-900/20'
: 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600'
}`}
>
<span className={`font-medium text-sm ${!applyToExisting ? 'text-purple-700 dark:text-purple-300' : 'text-gray-900 dark:text-white'}`}>
Future Only
</span>
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
Only new appointments
</p>
</button>
</div>
</div>
{/* Info about timing updates */}
<div className="p-3 bg-gray-50 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg">
<p className="text-xs text-gray-600 dark:text-gray-400">
If an event is rescheduled, the automation timing will automatically update.
</p>
</div>
{/* When to run */}
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
When should it run?
</label>
<div className="grid grid-cols-2 gap-2">
{TRIGGER_OPTIONS.map((opt) => (
<button
key={opt.value}
type="button"
onClick={() => {
setSelectedTrigger(opt.value);
if (['on_complete', 'on_cancel'].includes(opt.value)) {
setSelectedOffset(0);
}
}}
className={`px-3 py-2 text-sm rounded-lg border transition-colors ${
selectedTrigger === opt.value
? 'bg-purple-600 text-white border-purple-600'
: 'bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 border-gray-300 dark:border-gray-600 hover:border-purple-400'
}`}
>
{opt.label}
</button>
))}
</div>
</div>
{/* Offset selection (only for time-based triggers) */}
{showOffset && (
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
How long {selectedTrigger === 'before_start' ? 'before' : 'after'}?
</label>
<div className="flex flex-wrap gap-2">
{OFFSET_PRESETS.map((preset) => (
<button
key={preset.value}
type="button"
onClick={() => setSelectedOffset(preset.value)}
className={`px-3 py-2 text-sm rounded-lg border transition-colors ${
selectedOffset === preset.value
? 'bg-purple-600 text-white border-purple-600'
: 'bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 border-gray-300 dark:border-gray-600 hover:border-purple-400'
}`}
>
{preset.label}
</button>
))}
</div>
</div>
)}
{/* Event Timing Preview */}
<div className="p-3 bg-purple-100 dark:bg-purple-900/30 border border-purple-300 dark:border-purple-700 rounded-lg">
<div className="flex items-center gap-2">
<CalendarDays className="w-4 h-4 text-purple-600 dark:text-purple-400" />
<span className="text-sm text-purple-800 dark:text-purple-200">
<strong>Runs:</strong> {eventTimingDescriptionText}
</span>
</div>
</div>
</>
)}
{/* Error */}
{error && <ErrorMessage message={error} />}
</div>
)}
</div>
{/* Footer */}
<div className="flex items-center justify-between gap-3 px-6 py-4 border-t border-gray-200 dark:border-gray-700">
{step === 2 && (
<button
onClick={() => setStep(1)}
className="px-4 py-2 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
>
Back
</button>
)}
<div className="flex-1" />
<button
onClick={handleClose}
className="px-4 py-2 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
>
Cancel
</button>
{step === 2 && (
<button
onClick={handleSubmit}
disabled={
isSubmitting ||
(taskType === 'scheduled' && !taskName) ||
(taskType === 'scheduled' && scheduleMode === 'onetime' && (!runAtDate || !runAtTime))
}
className={`px-4 py-2 text-white rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed ${
taskType === 'event' ? 'bg-purple-600 hover:bg-purple-700' : 'bg-blue-600 hover:bg-blue-700'
}`}
>
{isSubmitting
? 'Creating...'
: taskType === 'event'
? 'Attach to All Events'
: 'Create Task'}
</button>
)}
</div>
</div>
</div>
);
};
export default CreateTaskModal;

View File

@@ -0,0 +1,302 @@
/**
* EditAppointmentModal Component
*
* Modal for editing existing appointments, including participant management.
* Extracted from OwnerScheduler for reusability and enhanced with participant selector.
*/
import React, { useState, useEffect, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { X, User as UserIcon, Mail, Phone } from 'lucide-react';
import { createPortal } from 'react-dom';
import { Appointment, AppointmentStatus, Resource, Service, ParticipantInput } from '../types';
import { ParticipantSelector } from './ParticipantSelector';
interface EditAppointmentModalProps {
appointment: Appointment & {
customerEmail?: string;
customerPhone?: string;
};
resources: Resource[];
services: Service[];
onSave: (updates: {
startTime?: Date;
resourceId?: string | null;
durationMinutes?: number;
status?: AppointmentStatus;
notes?: string;
participantsInput?: ParticipantInput[];
}) => void;
onClose: () => void;
isSaving?: boolean;
}
export const EditAppointmentModal: React.FC<EditAppointmentModalProps> = ({
appointment,
resources,
services,
onSave,
onClose,
isSaving = false,
}) => {
const { t } = useTranslation();
// Form state
const [editDateTime, setEditDateTime] = useState('');
const [editResource, setEditResource] = useState('');
const [editDuration, setEditDuration] = useState(15);
const [editStatus, setEditStatus] = useState<AppointmentStatus>('SCHEDULED');
const [editNotes, setEditNotes] = useState('');
const [participants, setParticipants] = useState<ParticipantInput[]>([]);
// Initialize form state from appointment
useEffect(() => {
if (appointment) {
// Convert Date to datetime-local format
const startTime = appointment.startTime;
const localDateTime = new Date(startTime.getTime() - startTime.getTimezoneOffset() * 60000)
.toISOString()
.slice(0, 16);
setEditDateTime(localDateTime);
setEditResource(appointment.resourceId || '');
setEditDuration(appointment.durationMinutes || 15);
setEditStatus(appointment.status || 'SCHEDULED');
setEditNotes(appointment.notes || '');
// Initialize participants from existing appointment participants
if (appointment.participants) {
const existingParticipants: ParticipantInput[] = appointment.participants.map(p => ({
role: p.role,
userId: p.userId ? parseInt(p.userId) : undefined,
resourceId: p.resourceId ? parseInt(p.resourceId) : undefined,
externalEmail: p.externalEmail,
externalName: p.externalName,
}));
setParticipants(existingParticipants);
}
}
}, [appointment]);
// Get service name
const serviceName = useMemo(() => {
const service = services.find(s => s.id === appointment.serviceId);
return service?.name || 'Unknown Service';
}, [services, appointment.serviceId]);
// Check if appointment is unassigned (pending)
const isUnassigned = !appointment.resourceId;
// Handle save
const handleSave = () => {
const startTime = new Date(editDateTime);
onSave({
startTime,
resourceId: editResource || null,
durationMinutes: editDuration,
status: editStatus,
notes: editNotes,
participantsInput: participants,
});
};
// Validation
const canSave = useMemo(() => {
if (isUnassigned) {
// For unassigned appointments, require resource and valid duration
return editResource && editDuration >= 15;
}
return true;
}, [isUnassigned, editResource, editDuration]);
const modalContent = (
<div
className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm"
onClick={onClose}
>
<div
className="w-full max-w-lg bg-white dark:bg-gray-800 rounded-xl shadow-xl border border-gray-200 dark:border-gray-700 overflow-hidden max-h-[90vh] flex flex-col"
onClick={e => e.stopPropagation()}
>
{/* Header */}
<div className="flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-gray-700 bg-gradient-to-r from-brand-50 to-brand-100 dark:from-brand-900/30 dark:to-brand-800/30">
<h3 className="text-lg font-semibold text-gray-900 dark:text-white">
{isUnassigned ? t('scheduler.scheduleAppointment') : t('scheduler.editAppointment')}
</h3>
<button
onClick={onClose}
className="p-1 text-gray-400 hover:bg-white/50 dark:hover:bg-gray-700/50 rounded-full transition-colors"
>
<X size={20} />
</button>
</div>
{/* Scrollable content */}
<div className="overflow-y-auto flex-1 p-6 space-y-4">
{/* Customer Info */}
<div className="flex items-start gap-3 p-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg">
<div className="flex-shrink-0 w-10 h-10 rounded-full bg-brand-100 dark:bg-brand-900/50 flex items-center justify-center">
<UserIcon size={20} className="text-brand-600 dark:text-brand-400" />
</div>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium text-gray-500 dark:text-gray-400">
{t('customers.title', 'Customer')}
</p>
<p className="text-lg font-semibold text-gray-900 dark:text-white">
{appointment.customerName}
</p>
{appointment.customerEmail && (
<div className="flex items-center gap-2 mt-1 text-sm text-gray-600 dark:text-gray-300">
<Mail size={14} />
<span>{appointment.customerEmail}</span>
</div>
)}
{appointment.customerPhone && (
<div className="flex items-center gap-2 mt-1 text-sm text-gray-600 dark:text-gray-300">
<Phone size={14} />
<span>{appointment.customerPhone}</span>
</div>
)}
</div>
</div>
{/* Service & Status */}
<div className="grid grid-cols-2 gap-4">
<div className="p-3 bg-gray-50 dark:bg-gray-700/50 rounded-lg">
<p className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1">
{t('services.title', 'Service')}
</p>
<p className="text-sm font-semibold text-gray-900 dark:text-white">{serviceName}</p>
</div>
<div className="p-3 bg-gray-50 dark:bg-gray-700/50 rounded-lg">
<label className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1 block">
{t('scheduler.status', 'Status')}
</label>
<select
value={editStatus}
onChange={(e) => setEditStatus(e.target.value as AppointmentStatus)}
className="w-full px-2 py-1 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded text-sm font-semibold text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-brand-500"
>
<option value="SCHEDULED">{t('scheduler.confirmed', 'Scheduled')}</option>
<option value="EN_ROUTE">En Route</option>
<option value="IN_PROGRESS">In Progress</option>
<option value="COMPLETED">{t('scheduler.completed', 'Completed')}</option>
<option value="AWAITING_PAYMENT">Awaiting Payment</option>
<option value="CANCELLED">{t('scheduler.cancelled', 'Cancelled')}</option>
<option value="NO_SHOW">{t('scheduler.noShow', 'No Show')}</option>
</select>
</div>
</div>
{/* Editable Fields */}
<div className="space-y-4 p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg border border-blue-200 dark:border-blue-800">
<h4 className="text-sm font-semibold text-gray-900 dark:text-white">
{t('scheduler.scheduleDetails', 'Schedule Details')}
</h4>
{/* Date & Time Picker */}
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-2">
{t('scheduler.selectDate', 'Date')} & {t('scheduler.selectTime', 'Time')}
</label>
<input
type="datetime-local"
value={editDateTime}
onChange={(e) => setEditDateTime(e.target.value)}
className="w-full px-3 py-2 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg text-sm text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-brand-500"
/>
</div>
{/* Resource Selector */}
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-2">
{t('scheduler.selectResource', 'Assign to Resource')}
{isUnassigned && <span className="text-red-500 ml-1">*</span>}
</label>
<select
value={editResource}
onChange={(e) => setEditResource(e.target.value)}
className="w-full px-3 py-2 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg text-sm text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-brand-500"
>
<option value="">Unassigned</option>
{resources.map(resource => (
<option key={resource.id} value={resource.id}>
{resource.name}
</option>
))}
</select>
</div>
{/* Duration Input */}
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-2">
{t('scheduler.duration', 'Duration')} (minutes)
{isUnassigned && <span className="text-red-500 ml-1">*</span>}
</label>
<input
type="number"
min="15"
step="15"
value={editDuration || 15}
onChange={(e) => {
const value = parseInt(e.target.value);
setEditDuration(value >= 15 ? value : 15);
}}
className="w-full px-3 py-2 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg text-sm text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-brand-500"
/>
</div>
</div>
{/* Participants Section */}
<div className="p-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg">
<ParticipantSelector
value={participants}
onChange={setParticipants}
allowedRoles={['STAFF', 'CUSTOMER', 'OBSERVER']}
allowExternalEmail={true}
existingParticipants={appointment.participants}
/>
</div>
{/* Notes */}
<div className="p-3 bg-gray-50 dark:bg-gray-700/50 rounded-lg">
<label className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1 block">
{t('scheduler.notes', 'Notes')}
</label>
<textarea
value={editNotes}
onChange={(e) => setEditNotes(e.target.value)}
rows={3}
className="w-full px-3 py-2 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg text-sm text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-brand-500 resize-none"
placeholder={t('scheduler.notesPlaceholder', 'Add notes about this appointment...')}
/>
</div>
</div>
{/* Footer with action buttons */}
<div className="px-6 py-4 border-t border-gray-200 dark:border-gray-700 flex justify-end gap-3 bg-white dark:bg-gray-800">
<button
onClick={onClose}
disabled={isSaving}
className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-200 bg-gray-100 dark:bg-gray-700 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors disabled:opacity-50"
>
{t('scheduler.cancel', 'Cancel')}
</button>
<button
onClick={handleSave}
disabled={!canSave || isSaving}
className="px-4 py-2 text-sm font-medium text-white bg-brand-600 rounded-lg hover:bg-brand-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
>
{isSaving ? t('common.saving', 'Saving...') : (
isUnassigned ? t('scheduler.scheduleAppointment', 'Schedule Appointment') : t('scheduler.saveChanges', 'Save Changes')
)}
</button>
</div>
</div>
</div>
);
return createPortal(modalContent, document.body);
};
export default EditAppointmentModal;

View File

@@ -1,383 +0,0 @@
import React, { useState, useEffect } from 'react';
import axios from '../api/client';
import { X, Calendar, Clock, RotateCw, Zap } from 'lucide-react';
import { formatLocalDate } from '../utils/dateUtils';
interface ScheduledTask {
id: string;
name: string;
description: string;
automation_name: string;
automation_display_name: string;
schedule_type: 'ONE_TIME' | 'INTERVAL' | 'CRON';
cron_expression?: string;
interval_minutes?: number;
run_at?: string;
next_run_at?: string;
last_run_at?: string;
status: 'ACTIVE' | 'PAUSED' | 'DISABLED';
last_run_status?: string;
automation_config: Record<string, any>;
created_at: string;
updated_at: string;
}
interface EditTaskModalProps {
task: ScheduledTask | null;
isOpen: boolean;
onClose: () => void;
onSuccess: () => void;
}
// Schedule presets for visual selection
interface SchedulePreset {
id: string;
label: string;
description: string;
type: 'INTERVAL' | 'CRON';
interval_minutes?: number;
cron_expression?: string;
}
const SCHEDULE_PRESETS: SchedulePreset[] = [
{ id: 'every_15min', label: 'Every 15 minutes', description: 'Runs 4 times per hour', type: 'INTERVAL', interval_minutes: 15 },
{ id: 'every_30min', label: 'Every 30 minutes', description: 'Runs twice per hour', type: 'INTERVAL', interval_minutes: 30 },
{ id: 'every_hour', label: 'Every hour', description: 'Runs 24 times per day', type: 'INTERVAL', interval_minutes: 60 },
{ id: 'every_2hours', label: 'Every 2 hours', description: 'Runs 12 times per day', type: 'INTERVAL', interval_minutes: 120 },
{ id: 'every_4hours', label: 'Every 4 hours', description: 'Runs 6 times per day', type: 'INTERVAL', interval_minutes: 240 },
{ id: 'every_6hours', label: 'Every 6 hours', description: 'Runs 4 times per day', type: 'INTERVAL', interval_minutes: 360 },
{ id: 'every_12hours', label: 'Twice daily', description: 'Runs at midnight and noon', type: 'INTERVAL', interval_minutes: 720 },
{ id: 'daily_midnight', label: 'Daily at midnight', description: 'Runs once per day at 12:00 AM', type: 'CRON', cron_expression: '0 0 * * *' },
{ id: 'daily_9am', label: 'Daily at 9 AM', description: 'Runs once per day at 9:00 AM', type: 'CRON', cron_expression: '0 9 * * *' },
{ id: 'daily_6pm', label: 'Daily at 6 PM', description: 'Runs once per day at 6:00 PM', type: 'CRON', cron_expression: '0 18 * * *' },
{ id: 'weekdays_9am', label: 'Weekdays at 9 AM', description: 'Mon-Fri at 9:00 AM', type: 'CRON', cron_expression: '0 9 * * 1-5' },
{ id: 'weekdays_6pm', label: 'Weekdays at 6 PM', description: 'Mon-Fri at 6:00 PM', type: 'CRON', cron_expression: '0 18 * * 1-5' },
{ id: 'weekly_sunday', label: 'Weekly on Sunday', description: 'Every Sunday at midnight', type: 'CRON', cron_expression: '0 0 * * 0' },
{ id: 'weekly_monday', label: 'Weekly on Monday', description: 'Every Monday at 9:00 AM', type: 'CRON', cron_expression: '0 9 * * 1' },
{ id: 'monthly_1st', label: 'Monthly on the 1st', description: 'First day of each month', type: 'CRON', cron_expression: '0 0 1 * *' },
];
const EditTaskModal: React.FC<EditTaskModalProps> = ({ task, isOpen, onClose, onSuccess }) => {
const [taskName, setTaskName] = useState('');
const [description, setDescription] = useState('');
const [selectedPreset, setSelectedPreset] = useState<string>('');
const [scheduleMode, setScheduleMode] = useState<'preset' | 'onetime' | 'advanced'>('preset');
const [runAtDate, setRunAtDate] = useState('');
const [runAtTime, setRunAtTime] = useState('');
const [customCron, setCustomCron] = useState('0 0 * * *');
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState('');
// Load task data when modal opens
useEffect(() => {
if (task && isOpen) {
setTaskName(task.name);
setDescription(task.description || '');
// Determine schedule mode and preset
if (task.schedule_type === 'ONE_TIME') {
setScheduleMode('onetime');
if (task.run_at) {
const date = new Date(task.run_at);
setRunAtDate(formatLocalDate(date));
setRunAtTime(date.toTimeString().slice(0, 5));
}
} else if (task.schedule_type === 'INTERVAL') {
// Try to match to a preset
const matchingPreset = SCHEDULE_PRESETS.find(
p => p.type === 'INTERVAL' && p.interval_minutes === task.interval_minutes
);
if (matchingPreset) {
setScheduleMode('preset');
setSelectedPreset(matchingPreset.id);
} else {
setScheduleMode('advanced');
// Convert interval to rough cron (not perfect, but gives user a starting point)
setCustomCron(`*/${task.interval_minutes} * * * *`);
}
} else if (task.schedule_type === 'CRON' && task.cron_expression) {
// Try to match to a preset
const matchingPreset = SCHEDULE_PRESETS.find(
p => p.type === 'CRON' && p.cron_expression === task.cron_expression
);
if (matchingPreset) {
setScheduleMode('preset');
setSelectedPreset(matchingPreset.id);
} else {
setScheduleMode('advanced');
setCustomCron(task.cron_expression);
}
}
}
}, [task, isOpen]);
const handleClose = () => {
setError('');
onClose();
};
const getScheduleDescription = () => {
if (scheduleMode === 'onetime') {
if (runAtDate && runAtTime) {
return `Once on ${new Date(`${runAtDate}T${runAtTime}`).toLocaleString()}`;
}
return 'Select date and time';
}
if (scheduleMode === 'advanced') {
return `Custom: ${customCron}`;
}
const preset = SCHEDULE_PRESETS.find(p => p.id === selectedPreset);
return preset?.description || 'Select a schedule';
};
const handleSubmit = async () => {
if (!task) return;
setIsSubmitting(true);
setError('');
try {
let payload: any = {
name: taskName,
description,
};
if (scheduleMode === 'onetime') {
payload.schedule_type = 'ONE_TIME';
payload.run_at = `${runAtDate}T${runAtTime}:00`;
payload.interval_minutes = null;
payload.cron_expression = null;
} else if (scheduleMode === 'advanced') {
payload.schedule_type = 'CRON';
payload.cron_expression = customCron;
payload.interval_minutes = null;
payload.run_at = null;
} else {
const preset = SCHEDULE_PRESETS.find(p => p.id === selectedPreset);
if (preset) {
payload.schedule_type = preset.type;
if (preset.type === 'INTERVAL') {
payload.interval_minutes = preset.interval_minutes;
payload.cron_expression = null;
} else {
payload.cron_expression = preset.cron_expression;
payload.interval_minutes = null;
}
payload.run_at = null;
}
}
await axios.patch(`/scheduled-tasks/${task.id}/`, payload);
onSuccess();
handleClose();
} catch (err: any) {
setError(err.response?.data?.detail || 'Failed to update task');
} finally {
setIsSubmitting(false);
}
};
if (!isOpen || !task) return null;
return (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50">
<div className="bg-white dark:bg-gray-800 rounded-lg max-w-2xl w-full max-h-[90vh] overflow-y-auto">
{/* Header */}
<div className="flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700">
<h2 className="text-2xl font-bold text-gray-900 dark:text-white">
Edit Task
</h2>
<button
onClick={handleClose}
className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700"
>
<X className="w-5 h-5" />
</button>
</div>
{/* Content */}
<div className="p-6 space-y-6">
{/* Automation Info (read-only) */}
<div className="p-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg">
<div className="flex items-center gap-3">
<Zap className="w-5 h-5 text-blue-600 dark:text-blue-400" />
<div>
<p className="text-sm text-blue-800 dark:text-blue-200 font-medium">
Automation
</p>
<p className="text-blue-900 dark:text-blue-100">
{task.automation_display_name}
</p>
</div>
</div>
</div>
{/* Task Name */}
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Task Name
</label>
<input
type="text"
value={taskName}
onChange={(e) => setTaskName(e.target.value)}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-900 text-gray-900 dark:text-white"
/>
</div>
{/* Schedule Mode Tabs */}
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
Schedule
</label>
<div className="flex border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden mb-4">
<button
onClick={() => setScheduleMode('preset')}
className={`flex-1 px-4 py-2 text-sm font-medium transition-colors ${
scheduleMode === 'preset'
? 'bg-blue-600 text-white'
: 'bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700'
}`}
>
<RotateCw className="w-4 h-4 inline mr-2" />
Recurring
</button>
<button
onClick={() => setScheduleMode('onetime')}
className={`flex-1 px-4 py-2 text-sm font-medium transition-colors ${
scheduleMode === 'onetime'
? 'bg-blue-600 text-white'
: 'bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700'
}`}
>
<Calendar className="w-4 h-4 inline mr-2" />
One-Time
</button>
<button
onClick={() => setScheduleMode('advanced')}
className={`flex-1 px-4 py-2 text-sm font-medium transition-colors ${
scheduleMode === 'advanced'
? 'bg-blue-600 text-white'
: 'bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700'
}`}
>
<Clock className="w-4 h-4 inline mr-2" />
Advanced
</button>
</div>
{/* Preset Selection */}
{scheduleMode === 'preset' && (
<div className="grid grid-cols-2 gap-2 max-h-64 overflow-y-auto">
{SCHEDULE_PRESETS.map((preset) => (
<button
key={preset.id}
onClick={() => setSelectedPreset(preset.id)}
className={`text-left p-3 rounded-lg border transition-colors ${
selectedPreset === preset.id
? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
: 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600'
}`}
>
<p className={`text-sm font-medium ${selectedPreset === preset.id ? 'text-blue-700 dark:text-blue-300' : 'text-gray-900 dark:text-white'}`}>
{preset.label}
</p>
<p className="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
{preset.description}
</p>
</button>
))}
</div>
)}
{/* One-Time Selection */}
{scheduleMode === 'onetime' && (
<div className="grid grid-cols-2 gap-4 p-4 bg-gray-50 dark:bg-gray-900 rounded-lg">
<div>
<label className="block text-sm text-gray-600 dark:text-gray-400 mb-1">
Date
</label>
<input
type="date"
value={runAtDate}
onChange={(e) => setRunAtDate(e.target.value)}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
/>
</div>
<div>
<label className="block text-sm text-gray-600 dark:text-gray-400 mb-1">
Time
</label>
<input
type="time"
value={runAtTime}
onChange={(e) => setRunAtTime(e.target.value)}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
/>
</div>
</div>
)}
{/* Advanced Cron */}
{scheduleMode === 'advanced' && (
<div className="p-4 bg-gray-50 dark:bg-gray-900 rounded-lg space-y-3">
<div>
<label className="block text-sm text-gray-600 dark:text-gray-400 mb-1">
Cron Expression
</label>
<input
type="text"
value={customCron}
onChange={(e) => setCustomCron(e.target.value)}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white font-mono text-sm"
placeholder="0 0 * * *"
/>
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
Format: minute hour day month weekday (e.g., "0 9 * * 1-5" = weekdays at 9 AM)
</p>
</div>
</div>
)}
</div>
{/* Schedule Preview */}
<div className="p-3 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg">
<div className="flex items-center gap-2">
<Clock className="w-4 h-4 text-green-600 dark:text-green-400" />
<span className="text-sm text-green-800 dark:text-green-200">
<strong>Schedule:</strong> {getScheduleDescription()}
</span>
</div>
</div>
{/* Error */}
{error && (
<div className="p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg">
<p className="text-sm text-red-800 dark:text-red-200">{error}</p>
</div>
)}
</div>
{/* Footer */}
<div className="flex items-center justify-end gap-3 px-6 py-4 border-t border-gray-200 dark:border-gray-700">
<button
onClick={handleClose}
className="px-4 py-2 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
>
Cancel
</button>
<button
onClick={handleSubmit}
disabled={isSubmitting || !taskName || (scheduleMode === 'onetime' && (!runAtDate || !runAtTime)) || (scheduleMode === 'preset' && !selectedPreset)}
className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
>
{isSubmitting ? 'Saving...' : 'Save Changes'}
</button>
</div>
</div>
</div>
);
};
export default EditTaskModal;

View File

@@ -1,361 +0,0 @@
import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import axios from '../api/client';
import { Zap, Plus, Trash2, Clock, CheckCircle2, XCircle, ChevronDown, Power } from 'lucide-react';
import toast from 'react-hot-toast';
interface AutomationInstallation {
id: string;
template_name: string;
template_description: string;
category: string;
logo_url?: string;
}
interface EventAutomation {
id: string;
event: number;
automation_installation: number;
automation_name: string;
automation_description: string;
automation_category: string;
automation_logo_url?: string;
trigger: string;
trigger_display: string;
offset_minutes: number;
timing_description: string;
is_active: boolean;
execution_order: number;
}
interface TriggerOption {
value: string;
label: string;
}
interface OffsetPreset {
value: number;
label: string;
}
interface EventAutomationsProps {
eventId: string | number;
compact?: boolean;
}
const TRIGGER_OPTIONS: TriggerOption[] = [
{ value: 'before_start', label: 'Before Start' },
{ value: 'at_start', label: 'At Start' },
{ value: 'after_start', label: 'After Start' },
{ value: 'after_end', label: 'After End' },
{ value: 'on_complete', label: 'When Completed' },
{ value: 'on_cancel', label: 'When Canceled' },
];
const OFFSET_PRESETS: OffsetPreset[] = [
{ value: 0, label: 'Immediately' },
{ value: 5, label: '5 min' },
{ value: 10, label: '10 min' },
{ value: 15, label: '15 min' },
{ value: 30, label: '30 min' },
{ value: 60, label: '1 hour' },
];
const EventAutomations: React.FC<EventAutomationsProps> = ({ eventId, compact = false }) => {
const queryClient = useQueryClient();
const [showAddForm, setShowAddForm] = useState(false);
const [selectedAutomation, setSelectedAutomation] = useState<string>('');
const [selectedTrigger, setSelectedTrigger] = useState<string>('at_start');
const [selectedOffset, setSelectedOffset] = useState<number>(0);
// Fetch installed automations
const { data: automations = [] } = useQuery<AutomationInstallation[]>({
queryKey: ['automation-installations'],
queryFn: async () => {
const { data } = await axios.get('/automation-installations/');
return data;
},
});
// Fetch event automations
const { data: eventAutomations = [], isLoading } = useQuery<EventAutomation[]>({
queryKey: ['event-automations', eventId],
queryFn: async () => {
const { data } = await axios.get(`/event-automations/?event_id=${eventId}`);
return data;
},
enabled: !!eventId,
});
// Add automation mutation
const addMutation = useMutation({
mutationFn: async (data: { automation_installation: string; trigger: string; offset_minutes: number }) => {
return axios.post('/event-automations/', {
event: eventId,
...data,
});
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['event-automations', eventId] });
setShowAddForm(false);
setSelectedAutomation('');
setSelectedTrigger('at_start');
setSelectedOffset(0);
toast.success('Automation added');
},
onError: () => {
toast.error('Failed to add automation');
},
});
// Toggle mutation
const toggleMutation = useMutation({
mutationFn: async (automationId: string) => {
return axios.post(`/event-automations/${automationId}/toggle/`);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['event-automations', eventId] });
},
});
// Delete mutation
const deleteMutation = useMutation({
mutationFn: async (automationId: string) => {
return axios.delete(`/event-automations/${automationId}/`);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['event-automations', eventId] });
toast.success('Automation removed');
},
});
const handleAdd = () => {
if (!selectedAutomation) return;
addMutation.mutate({
automation_installation: selectedAutomation,
trigger: selectedTrigger,
offset_minutes: selectedOffset,
});
};
const showOffset = !['on_complete', 'on_cancel'].includes(selectedTrigger);
if (isLoading) {
return (
<div className="p-4 text-center text-gray-500 dark:text-gray-400">
Loading automations...
</div>
);
}
return (
<div className={`${compact ? 'space-y-3' : 'space-y-4'}`}>
{/* Header */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Zap className="w-4 h-4 text-purple-600 dark:text-purple-400" />
<span className="text-sm font-medium text-gray-900 dark:text-white">
Automations
</span>
{eventAutomations.length > 0 && (
<span className="px-1.5 py-0.5 text-xs bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300 rounded">
{eventAutomations.length}
</span>
)}
</div>
{!showAddForm && automations.length > 0 && (
<button
onClick={() => setShowAddForm(true)}
className="flex items-center gap-1 px-2 py-1 text-xs text-purple-600 dark:text-purple-400 hover:bg-purple-50 dark:hover:bg-purple-900/20 rounded transition-colors"
>
<Plus className="w-3 h-3" />
Add
</button>
)}
</div>
{/* Existing automations */}
{eventAutomations.length > 0 && (
<div className="space-y-2">
{eventAutomations.map((ep) => (
<div
key={ep.id}
className={`flex items-center justify-between p-2 rounded-lg border ${
ep.is_active
? 'bg-white dark:bg-gray-800 border-gray-200 dark:border-gray-700'
: 'bg-gray-50 dark:bg-gray-900 border-gray-200 dark:border-gray-700 opacity-60'
}`}
>
<div className="flex items-center gap-2 min-w-0">
<div className={`p-1.5 rounded ${ep.is_active ? 'bg-purple-100 dark:bg-purple-900/30' : 'bg-gray-100 dark:bg-gray-800'}`}>
<Zap className={`w-3 h-3 ${ep.is_active ? 'text-purple-600 dark:text-purple-400' : 'text-gray-400'}`} />
</div>
<div className="min-w-0">
<p className="text-sm font-medium text-gray-900 dark:text-white truncate">
{ep.automation_name}
</p>
<div className="flex items-center gap-1 text-xs text-gray-500 dark:text-gray-400">
<Clock className="w-3 h-3" />
<span>{ep.timing_description}</span>
</div>
</div>
</div>
<div className="flex items-center gap-1">
<button
onClick={() => toggleMutation.mutate(ep.id)}
className={`p-1.5 rounded transition-colors ${
ep.is_active
? 'text-green-600 dark:text-green-400 hover:bg-green-50 dark:hover:bg-green-900/20'
: 'text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700'
}`}
title={ep.is_active ? 'Disable' : 'Enable'}
>
<Power className="w-3.5 h-3.5" />
</button>
<button
onClick={() => deleteMutation.mutate(ep.id)}
className="p-1.5 text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 rounded transition-colors"
title="Remove"
>
<Trash2 className="w-3.5 h-3.5" />
</button>
</div>
</div>
))}
</div>
)}
{/* Add automation form */}
{showAddForm && (
<div className="p-3 bg-purple-50 dark:bg-purple-900/20 rounded-lg border border-purple-200 dark:border-purple-800 space-y-3">
{/* Automation selector */}
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
Automation
</label>
<select
value={selectedAutomation}
onChange={(e) => setSelectedAutomation(e.target.value)}
className="w-full px-2 py-1.5 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
>
<option value="">Select an automation...</option>
{automations.map((a) => (
<option key={a.id} value={a.id}>
{a.template_name}
</option>
))}
</select>
</div>
{/* Timing selector - visual */}
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
When to run
</label>
<div className="grid grid-cols-2 gap-1.5">
{TRIGGER_OPTIONS.map((opt) => (
<button
key={opt.value}
type="button"
onClick={() => {
setSelectedTrigger(opt.value);
if (['on_complete', 'on_cancel'].includes(opt.value)) {
setSelectedOffset(0);
}
}}
className={`px-2 py-1.5 text-xs rounded border transition-colors ${
selectedTrigger === opt.value
? 'bg-purple-600 text-white border-purple-600'
: 'bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 border-gray-300 dark:border-gray-600 hover:border-purple-400'
}`}
>
{opt.label}
</button>
))}
</div>
</div>
{/* Offset selector - only for time-based triggers */}
{showOffset && (
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
Offset
</label>
<div className="flex flex-wrap gap-1.5">
{OFFSET_PRESETS.map((preset) => (
<button
key={preset.value}
type="button"
onClick={() => setSelectedOffset(preset.value)}
className={`px-2 py-1 text-xs rounded border transition-colors ${
selectedOffset === preset.value
? 'bg-purple-600 text-white border-purple-600'
: 'bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 border-gray-300 dark:border-gray-600 hover:border-purple-400'
}`}
>
{preset.label}
</button>
))}
</div>
</div>
)}
{/* Preview */}
{selectedAutomation && (
<div className="text-xs text-purple-800 dark:text-purple-200 bg-purple-100 dark:bg-purple-900/40 px-2 py-1.5 rounded">
Will run: <strong>
{selectedTrigger === 'on_complete' ? 'When completed' :
selectedTrigger === 'on_cancel' ? 'When canceled' :
selectedTrigger === 'before_start' && selectedOffset > 0 ? `${selectedOffset} min before start` :
selectedTrigger === 'after_end' && selectedOffset > 0 ? `${selectedOffset} min after end` :
selectedTrigger === 'after_start' && selectedOffset > 0 ? `${selectedOffset} min after start` :
selectedTrigger === 'at_start' && selectedOffset > 0 ? `${selectedOffset} min after start` :
selectedTrigger === 'before_start' ? 'At start' :
selectedTrigger === 'after_end' ? 'At end' :
'At start'}
</strong>
</div>
)}
{/* Actions */}
<div className="flex justify-end gap-2 pt-1">
<button
onClick={() => setShowAddForm(false)}
className="px-3 py-1.5 text-xs text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded transition-colors"
>
Cancel
</button>
<button
onClick={handleAdd}
disabled={!selectedAutomation || addMutation.isPending}
className="px-3 py-1.5 text-xs bg-purple-600 text-white rounded hover:bg-purple-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
{addMutation.isPending ? 'Adding...' : 'Add Automation'}
</button>
</div>
</div>
)}
{/* Empty state */}
{eventAutomations.length === 0 && !showAddForm && (
<div className="text-center py-3 text-gray-500 dark:text-gray-400">
{automations.length > 0 ? (
<button
onClick={() => setShowAddForm(true)}
className="text-xs text-purple-600 dark:text-purple-400 hover:underline"
>
+ Add your first automation
</button>
) : (
<p className="text-xs">
Install automations from the Marketplace to use them
</p>
)}
</div>
)}
</div>
);
};
export default EventAutomations;

View File

@@ -0,0 +1,367 @@
/**
* ParticipantSelector Component
*
* A reusable component for selecting participants (staff, customers, observers)
* for appointments. Supports both linked users and external email participants.
*/
import React, { useState, useMemo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { X, Plus, Search, User, UserPlus, Mail, Users } from 'lucide-react';
import { Participant, ParticipantInput, ParticipantRole } from '../types';
import { useStaff, StaffMember } from '../hooks/useStaff';
import { useCustomers } from '../hooks/useCustomers';
import { Customer } from '../types';
interface ParticipantSelectorProps {
value: ParticipantInput[];
onChange: (participants: ParticipantInput[]) => void;
allowedRoles?: ParticipantRole[];
allowExternalEmail?: boolean;
existingParticipants?: Participant[];
}
// Role badge colors
const roleBadgeColors: Record<ParticipantRole, string> = {
STAFF: 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-300',
CUSTOMER: 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300',
OBSERVER: 'bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-300',
RESOURCE: 'bg-amber-100 text-amber-800 dark:bg-amber-900 dark:text-amber-300',
};
export const ParticipantSelector: React.FC<ParticipantSelectorProps> = ({
value,
onChange,
allowedRoles = ['STAFF', 'CUSTOMER', 'OBSERVER'],
allowExternalEmail = true,
existingParticipants = [],
}) => {
const { t } = useTranslation();
const [searchQuery, setSearchQuery] = useState('');
const [isDropdownOpen, setIsDropdownOpen] = useState(false);
const [showExternalInput, setShowExternalInput] = useState(false);
const [externalEmail, setExternalEmail] = useState('');
const [externalName, setExternalName] = useState('');
const [externalRole, setExternalRole] = useState<ParticipantRole>('OBSERVER');
const [externalEmailError, setExternalEmailError] = useState('');
// Fetch staff and customers for search
const { data: staff = [] } = useStaff({ search: searchQuery });
const { data: customers = [] } = useCustomers({ search: searchQuery });
// Get display name for a participant
const getDisplayName = useCallback((p: ParticipantInput): string => {
if (p.externalName) return p.externalName;
if (p.externalEmail) return p.externalEmail;
// Find from staff or customers
if (p.userId) {
const staffMember = staff.find(s => s.id === String(p.userId));
if (staffMember) return staffMember.name;
const customer = customers.find(c => c.id === String(p.userId));
if (customer) return customer.name;
}
return t('participants.unknownParticipant', 'Unknown');
}, [staff, customers, t]);
// Filter search results
const searchResults = useMemo(() => {
if (!searchQuery.trim()) return [];
const results: Array<{
id: string;
name: string;
email: string;
type: 'staff' | 'customer';
role: ParticipantRole;
}> = [];
// Add staff members if STAFF role is allowed
if (allowedRoles.includes('STAFF')) {
staff.forEach(s => {
// Skip if already added
const alreadyAdded = value.some(p => p.userId === parseInt(s.id));
if (!alreadyAdded) {
results.push({
id: s.id,
name: s.name,
email: s.email,
type: 'staff',
role: 'STAFF',
});
}
});
}
// Add customers if CUSTOMER role is allowed
if (allowedRoles.includes('CUSTOMER')) {
customers.forEach(c => {
// Skip if already added
const alreadyAdded = value.some(p => p.userId === parseInt(c.id));
if (!alreadyAdded) {
results.push({
id: c.id,
name: c.name,
email: c.email,
type: 'customer',
role: 'CUSTOMER',
});
}
});
}
return results.slice(0, 10); // Limit results
}, [searchQuery, staff, customers, value, allowedRoles]);
// Add a user as participant
const handleAddUser = useCallback((userId: string, role: ParticipantRole) => {
const newParticipant: ParticipantInput = {
role,
userId: parseInt(userId),
};
onChange([...value, newParticipant]);
setSearchQuery('');
setIsDropdownOpen(false);
}, [value, onChange]);
// Add external email participant
const handleAddExternal = useCallback(() => {
// Validate email
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!externalEmail.trim()) {
setExternalEmailError(t('participants.emailRequired'));
return;
}
if (!emailRegex.test(externalEmail)) {
setExternalEmailError(t('participants.invalidEmail'));
return;
}
// Check if already added
const alreadyAdded = value.some(p => p.externalEmail === externalEmail);
if (alreadyAdded) {
setExternalEmailError(t('participants.alreadyAdded', 'This email is already added'));
return;
}
const newParticipant: ParticipantInput = {
role: externalRole,
externalEmail: externalEmail.trim(),
externalName: externalName.trim(),
};
onChange([...value, newParticipant]);
setExternalEmail('');
setExternalName('');
setExternalEmailError('');
setShowExternalInput(false);
}, [externalEmail, externalName, externalRole, value, onChange, t]);
// Remove a participant
const handleRemove = useCallback((index: number) => {
const newValue = [...value];
newValue.splice(index, 1);
onChange(newValue);
}, [value, onChange]);
return (
<div className="space-y-3">
{/* Header */}
<div className="flex items-center justify-between">
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300">
{t('participants.title')}
</label>
{allowExternalEmail && (
<button
type="button"
onClick={() => setShowExternalInput(!showExternalInput)}
className="text-sm text-brand-600 hover:text-brand-700 dark:text-brand-400 flex items-center gap-1"
>
<Mail className="w-4 h-4" />
{t('participants.addExternalEmail')}
</button>
)}
</div>
{/* Selected participants */}
<div className="flex flex-wrap gap-2">
{value.length === 0 ? (
<p className="text-sm text-gray-500 dark:text-gray-400">
{t('participants.noParticipants')}
</p>
) : (
value.map((participant, index) => (
<div
key={index}
className={`inline-flex items-center gap-2 px-3 py-1.5 rounded-full text-sm ${
roleBadgeColors[participant.role]
}`}
>
{participant.externalEmail ? (
<Mail className="w-3.5 h-3.5" />
) : (
<User className="w-3.5 h-3.5" />
)}
<span>
{getDisplayName(participant)}
{participant.externalEmail && (
<span className="text-xs opacity-75 ml-1">
({t(`participants.roles.${participant.role}`)})
</span>
)}
</span>
<button
type="button"
onClick={() => handleRemove(index)}
className="hover:bg-white/30 rounded-full p-0.5"
title={t('participants.removeParticipant')}
>
<X className="w-3.5 h-3.5" />
</button>
</div>
))
)}
</div>
{/* External email input */}
{showExternalInput && (
<div className="bg-gray-50 dark:bg-gray-800 rounded-lg p-4 space-y-3 border border-gray-200 dark:border-gray-700">
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">
{t('participants.email')} *
</label>
<input
type="email"
value={externalEmail}
onChange={(e) => {
setExternalEmail(e.target.value);
setExternalEmailError('');
}}
placeholder="guest@example.com"
className="w-full px-3 py-2 text-sm border rounded-md dark:bg-gray-700 dark:border-gray-600 dark:text-white"
/>
{externalEmailError && (
<p className="text-xs text-red-500 mt-1">{externalEmailError}</p>
)}
</div>
<div>
<label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">
{t('participants.name')}
</label>
<input
type="text"
value={externalName}
onChange={(e) => setExternalName(e.target.value)}
placeholder="Guest Name"
className="w-full px-3 py-2 text-sm border rounded-md dark:bg-gray-700 dark:border-gray-600 dark:text-white"
/>
</div>
</div>
<div className="flex items-center justify-between">
<select
value={externalRole}
onChange={(e) => setExternalRole(e.target.value as ParticipantRole)}
className="px-3 py-2 text-sm border rounded-md dark:bg-gray-700 dark:border-gray-600 dark:text-white"
>
{allowedRoles.map(role => (
<option key={role} value={role}>
{t(`participants.roles.${role}`)}
</option>
))}
</select>
<div className="flex gap-2">
<button
type="button"
onClick={() => {
setShowExternalInput(false);
setExternalEmail('');
setExternalName('');
setExternalEmailError('');
}}
className="px-3 py-1.5 text-sm text-gray-600 hover:text-gray-800 dark:text-gray-400"
>
{t('common.cancel', 'Cancel')}
</button>
<button
type="button"
onClick={handleAddExternal}
className="px-3 py-1.5 text-sm bg-brand-600 text-white rounded-md hover:bg-brand-700"
>
{t('participants.addParticipant')}
</button>
</div>
</div>
</div>
)}
{/* Search input */}
<div className="relative">
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
<input
type="text"
value={searchQuery}
onChange={(e) => {
setSearchQuery(e.target.value);
setIsDropdownOpen(true);
}}
onFocus={() => setIsDropdownOpen(true)}
placeholder={t('participants.searchPlaceholder')}
className="w-full pl-10 pr-4 py-2 text-sm border rounded-md dark:bg-gray-700 dark:border-gray-600 dark:text-white"
/>
</div>
{/* Search results dropdown */}
{isDropdownOpen && searchQuery.trim() && (
<div className="absolute z-50 w-full mt-1 bg-white dark:bg-gray-800 border dark:border-gray-700 rounded-lg shadow-lg max-h-60 overflow-y-auto">
{searchResults.length === 0 ? (
<div className="px-4 py-3 text-sm text-gray-500 dark:text-gray-400">
{t('common.noResults', 'No results found')}
</div>
) : (
searchResults.map((result) => (
<button
key={`${result.type}-${result.id}`}
type="button"
onClick={() => handleAddUser(result.id, result.role)}
className="w-full px-4 py-2 flex items-center gap-3 hover:bg-gray-100 dark:hover:bg-gray-700 text-left"
>
<div className="flex-shrink-0">
{result.type === 'staff' ? (
<Users className="w-5 h-5 text-blue-500" />
) : (
<User className="w-5 h-5 text-green-500" />
)}
</div>
<div className="flex-grow min-w-0">
<div className="text-sm font-medium text-gray-900 dark:text-white truncate">
{result.name}
</div>
<div className="text-xs text-gray-500 dark:text-gray-400 truncate">
{result.email}
</div>
</div>
<span className={`text-xs px-2 py-0.5 rounded-full ${roleBadgeColors[result.role]}`}>
{t(`participants.roles.${result.role}`)}
</span>
</button>
))
)}
</div>
)}
</div>
{/* Click outside to close dropdown */}
{isDropdownOpen && (
<div
className="fixed inset-0 z-40"
onClick={() => setIsDropdownOpen(false)}
/>
)}
</div>
);
};
export default ParticipantSelector;

View File

@@ -282,29 +282,16 @@ const Sidebar: React.FC<SidebarProps> = ({ business, user, isCollapsed, toggleCo
</SidebarSection>
)}
{/* Extend Section - Tasks & Automations */}
{(hasPermission('can_access_tasks') || hasPermission('can_access_automations')) && (
{/* Extend Section - Automations */}
{hasPermission('can_access_automations') && (
<SidebarSection title={t('nav.sections.extend', 'Extend')} isCollapsed={isCollapsed}>
{hasPermission('can_access_tasks') && (
<SidebarItem
to="/dashboard/tasks"
icon={Clock}
label={t('nav.tasks', 'Tasks')}
isCollapsed={isCollapsed}
locked={!canUse('automations') || !canUse('tasks')}
badgeElement={<UnfinishedBadge />}
/>
)}
{hasPermission('can_access_automations') && (
<SidebarItem
to="/dashboard/automations/my-automations"
icon={Plug}
label={t('nav.automations', 'Automations')}
isCollapsed={isCollapsed}
locked={!canUse('automations')}
badgeElement={<UnfinishedBadge />}
/>
)}
<SidebarItem
to="/dashboard/automations"
icon={Plug}
label={t('nav.automations', 'Automations')}
isCollapsed={isCollapsed}
locked={!canUse('automations')}
/>
</SidebarSection>
)}

View File

@@ -4,9 +4,40 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import apiClient from '../api/client';
import { Appointment, AppointmentStatus } from '../types';
import { Appointment, AppointmentStatus, Participant, ParticipantInput } from '../types';
import { format } from 'date-fns';
/**
* Transform backend participant data to frontend format
*/
function transformParticipant(p: any): Participant {
return {
id: String(p.id),
role: p.role,
userId: p.object_id && p.content_type_str?.includes('user') ? String(p.object_id) : undefined,
resourceId: p.object_id && p.content_type_str?.includes('resource') ? String(p.object_id) : undefined,
displayName: p.display_name || p.participant_display || '',
externalEmail: p.external_email || '',
externalName: p.external_name || '',
isExternal: p.is_external || false,
calendarInviteSent: p.calendar_invite_sent || false,
calendarInviteSentAt: p.calendar_invite_sent_at || undefined,
};
}
/**
* Transform frontend participant input to backend format
*/
function transformParticipantInput(p: ParticipantInput): Record<string, unknown> {
return {
role: p.role,
user_id: p.userId || null,
resource_id: p.resourceId || null,
external_email: p.externalEmail || '',
external_name: p.externalName || '',
};
}
interface AppointmentFilters {
resource?: string;
customer?: string;
@@ -62,6 +93,8 @@ export const useAppointments = (filters?: AppointmentFilters) => {
isVariablePricing: a.is_variable_pricing || false,
remainingBalance: a.remaining_balance ? parseFloat(a.remaining_balance) / 100 : null,
overpaidAmount: a.overpaid_amount ? parseFloat(a.overpaid_amount) / 100 : null,
// Participants
participants: a.participants?.map(transformParticipant) || [],
}));
},
});
@@ -103,12 +136,19 @@ export const useAppointment = (id: string) => {
isVariablePricing: data.is_variable_pricing || false,
remainingBalance: data.remaining_balance ? parseFloat(data.remaining_balance) / 100 : null,
overpaidAmount: data.overpaid_amount ? parseFloat(data.overpaid_amount) / 100 : null,
// Participants
participants: data.participants?.map(transformParticipant) || [],
};
},
enabled: !!id,
});
};
// Extended create data that includes participants
interface AppointmentCreateData extends Omit<Appointment, 'id'> {
participantsInput?: ParticipantInput[];
}
/**
* Hook to create an appointment
*/
@@ -116,7 +156,7 @@ export const useCreateAppointment = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (appointmentData: Omit<Appointment, 'id'>) => {
mutationFn: async (appointmentData: AppointmentCreateData) => {
const startTime = appointmentData.startTime;
const endTime = new Date(startTime.getTime() + appointmentData.durationMinutes * 60000);
@@ -133,6 +173,11 @@ export const useCreateAppointment = () => {
backendData.customer = parseInt(appointmentData.customerId);
}
// Include participants if provided
if (appointmentData.participantsInput && appointmentData.participantsInput.length > 0) {
backendData.participants_input = appointmentData.participantsInput.map(transformParticipantInput);
}
const { data } = await apiClient.post('/appointments/', backendData);
return data;
},
@@ -142,6 +187,11 @@ export const useCreateAppointment = () => {
});
};
// Extended update data that includes participants
interface AppointmentUpdateData extends Partial<Appointment> {
participantsInput?: ParticipantInput[];
}
/**
* Hook to update an appointment with optimistic updates for instant UI feedback
*/
@@ -149,7 +199,7 @@ export const useUpdateAppointment = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({ id, updates }: { id: string; updates: Partial<Appointment> }) => {
mutationFn: async ({ id, updates }: { id: string; updates: AppointmentUpdateData }) => {
const backendData: any = {};
if (updates.serviceId) backendData.service = parseInt(updates.serviceId);
@@ -172,6 +222,11 @@ export const useUpdateAppointment = () => {
if (updates.status) backendData.status = updates.status;
if (updates.notes !== undefined) backendData.notes = updates.notes;
// Handle participants update
if (updates.participantsInput !== undefined) {
backendData.participants_input = updates.participantsInput.map(transformParticipantInput);
}
const { data } = await apiClient.patch(`/appointments/${id}/`, backendData);
return data;
},

View File

@@ -22,6 +22,23 @@
"hoursAgo": "{{count}}h ago",
"daysAgo": "{{count}}d ago"
},
"automations": {
"title": "Automations",
"subtitle": "Build powerful workflows to automate your business",
"loading": "Loading automation builder...",
"loadingBuilder": "Loading workflow builder...",
"builderTitle": "Automation Builder",
"aiEnabled": "AI Copilot Enabled",
"openInTab": "Open in new tab",
"locked": {
"title": "Automations",
"description": "Upgrade your plan to access powerful workflow automation with AI-powered flow creation."
},
"error": {
"title": "Unable to load automation builder",
"description": "There was a problem connecting to the automation service. Please try again."
}
},
"common": {
"loading": "Loading...",
"error": "Error",
@@ -33,6 +50,7 @@
"delete": "Delete",
"edit": "Edit",
"create": "Create",
"creating": "Creating...",
"update": "Update",
"close": "Close",
"confirm": "Confirm",
@@ -1467,7 +1485,41 @@
"pendingRequests": "Pending Requests",
"noPendingRequests": "No pending requests",
"dropToArchive": "Drop here to archive",
"min": "min"
"min": "min",
"scheduleAppointment": "Schedule Appointment",
"saveChanges": "Save Changes",
"cancel": "Cancel",
"createAppointment": "Create Appointment",
"unassigned": "Unassigned",
"notesPlaceholder": "Add notes about this appointment...",
"scheduleDetails": "Schedule Details"
},
"participants": {
"title": "Participants",
"additionalParticipants": "Additional Participants",
"addParticipant": "Add Participant",
"addStaff": "Add Staff",
"addCustomer": "Add Customer",
"addObserver": "Add Observer",
"addExternalEmail": "Add by Email",
"searchPlaceholder": "Search by name or email...",
"sendCalendarInvites": "Send calendar invitations",
"externalEmail": "External Email",
"name": "Name",
"email": "Email",
"noParticipants": "No participants added",
"removeParticipant": "Remove participant",
"roles": {
"STAFF": "Staff",
"CUSTOMER": "Customer",
"OBSERVER": "Observer",
"RESOURCE": "Resource"
},
"external": "External",
"emailRequired": "Email is required",
"invalidEmail": "Invalid email address",
"participantAdded": "Participant added",
"participantRemoved": "Participant removed"
},
"customers": {
"title": "Customers",

View File

@@ -1,727 +0,0 @@
import React, { useState, useMemo, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
ShoppingBag,
Search,
Star,
Download,
Zap,
Filter,
X,
CheckCircle,
Mail,
BarChart3,
Users,
Calendar,
Link as LinkIcon,
Bot,
Package,
Eye,
ChevronDown,
AlertTriangle,
Clock,
Settings,
ArrowRight
} from 'lucide-react';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { vscDarkPlus } from 'react-syntax-highlighter/dist/esm/styles/prism';
import api from '../api/client';
import { AutomationTemplate, AutomationCategory } from '../types';
import { usePlanFeatures } from '../hooks/usePlanFeatures';
import { LockedSection } from '../components/UpgradePrompt';
// Category icon mapping
const categoryIcons: Record<AutomationCategory, React.ReactNode> = {
EMAIL: <Mail className="h-4 w-4" />,
REPORTS: <BarChart3 className="h-4 w-4" />,
CUSTOMER: <Users className="h-4 w-4" />,
BOOKING: <Calendar className="h-4 w-4" />,
INTEGRATION: <LinkIcon className="h-4 w-4" />,
AUTOMATION: <Bot className="h-4 w-4" />,
OTHER: <Package className="h-4 w-4" />,
};
// Category colors
const categoryColors: Record<AutomationCategory, string> = {
EMAIL: 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300',
REPORTS: 'bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-300',
CUSTOMER: 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300',
BOOKING: 'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-300',
INTEGRATION: 'bg-cyan-100 text-cyan-700 dark:bg-cyan-900/30 dark:text-cyan-300',
AUTOMATION: 'bg-pink-100 text-pink-700 dark:bg-pink-900/30 dark:text-pink-300',
OTHER: 'bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300',
};
// Helper function to detect platform-only code
const detectPlatformOnlyCode = (code: string): { hasPlatformCode: boolean; warnings: string[] } => {
const warnings: string[] = [];
if (code.includes('{{PLATFORM:')) {
warnings.push('This code uses platform-only features that require special permissions');
}
if (code.includes('{{WHITELIST:')) {
warnings.push('This code requires whitelisting by platform administrators');
}
if (code.includes('{{SUPERUSER:')) {
warnings.push('This code requires superuser privileges to execute');
}
if (code.includes('{{SYSTEM:')) {
warnings.push('This code accesses system-level features');
}
return {
hasPlatformCode: warnings.length > 0,
warnings
};
};
const AutomationMarketplace: React.FC = () => {
const { t } = useTranslation();
const navigate = useNavigate();
const queryClient = useQueryClient();
const [searchQuery, setSearchQuery] = useState('');
const [selectedCategory, setSelectedCategory] = useState<AutomationCategory | 'ALL'>('ALL');
const [selectedAutomation, setSelectedAutomation] = useState<AutomationTemplate | null>(null);
const [showDetailsModal, setShowDetailsModal] = useState(false);
const [showCode, setShowCode] = useState(false);
const [isLoadingDetails, setIsLoadingDetails] = useState(false);
const [showWhatsNextModal, setShowWhatsNextModal] = useState(false);
const [installedAutomationId, setInstalledAutomationId] = useState<string | null>(null);
// Check plan permissions
const { canUse, isLoading: permissionsLoading } = usePlanFeatures();
const hasAutomationsFeature = canUse('automations');
const isLocked = !hasAutomationsFeature;
// Fetch marketplace automations - only when user has the feature
const { data: automations = [], isLoading, error } = useQuery<AutomationTemplate[]>({
queryKey: ['automation-templates', 'marketplace'],
queryFn: async () => {
const { data } = await api.get('/automation-templates/?view=marketplace');
return data.map((p: any) => ({
id: String(p.id),
name: p.name,
description: p.description,
category: p.category,
version: p.version,
author: p.author_name,
rating: parseFloat(p.rating_average || 0),
ratingCount: parseInt(p.rating_count || 0),
installCount: parseInt(p.install_count || 0),
isVerified: p.visibility === 'PLATFORM',
isFeatured: p.is_featured || false,
createdAt: p.created_at,
updatedAt: p.updated_at,
logoUrl: p.logo_url,
automationCode: p.automation_code,
}));
},
// Don't fetch if user doesn't have the automations feature
enabled: hasAutomationsFeature && !permissionsLoading,
});
// Fetch installed automations to check which are already installed
const { data: installedAutomations = [] } = useQuery<{ template: number }[]>({
queryKey: ['automation-installations'],
queryFn: async () => {
const { data } = await api.get('/automation-installations/');
return data;
},
// Don't fetch if user doesn't have the automations feature
enabled: hasAutomationsFeature && !permissionsLoading,
});
// Create a set of installed template IDs for quick lookup
const installedTemplateIds = useMemo(() => {
return new Set(installedAutomations.map(p => String(p.template)));
}, [installedAutomations]);
// Install automation mutation
const installMutation = useMutation({
mutationFn: async (templateId: string) => {
const { data } = await api.post('/automation-installations/', {
template: templateId,
});
return data;
},
onSuccess: (data) => {
queryClient.invalidateQueries({ queryKey: ['automation-installations'] });
setShowDetailsModal(false);
// Show What's Next modal
setInstalledAutomationId(data.id);
setShowWhatsNextModal(true);
},
});
// Filter automations
const filteredAutomations = useMemo(() => {
let result = automations;
// Filter by category
if (selectedCategory !== 'ALL') {
result = result.filter(p => p.category === selectedCategory);
}
// Filter by search query
if (searchQuery.trim()) {
const query = searchQuery.toLowerCase();
result = result.filter(p =>
p.name.toLowerCase().includes(query) ||
p.description.toLowerCase().includes(query) ||
p.author.toLowerCase().includes(query)
);
}
return result;
}, [automations, selectedCategory, searchQuery]);
// Sort: Featured first, then by rating, then by install count
const sortedAutomations = useMemo(() => {
return [...filteredAutomations].sort((a, b) => {
if (a.isFeatured && !b.isFeatured) return -1;
if (!a.isFeatured && b.isFeatured) return 1;
if (a.rating !== b.rating) return b.rating - a.rating;
return b.installCount - a.installCount;
});
}, [filteredAutomations]);
const handleInstall = async (automation: AutomationTemplate) => {
setSelectedAutomation(automation);
setShowDetailsModal(true);
setShowCode(false);
// Fetch full automation details including automation_code
setIsLoadingDetails(true);
try {
const { data } = await api.get(`/automation-templates/${automation.id}/`);
setSelectedAutomation({
...automation,
automationCode: data.automation_code,
logoUrl: data.logo_url,
});
} catch (error) {
console.error('Failed to fetch automation details:', error);
} finally {
setIsLoadingDetails(false);
}
};
const confirmInstall = () => {
if (selectedAutomation) {
installMutation.mutate(selectedAutomation.id);
}
};
if (isLoading || permissionsLoading) {
return (
<div className="p-8">
<div className="flex items-center justify-center h-64">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-brand-600"></div>
</div>
</div>
);
}
// Check if error is a 403 (plan restriction) - show upgrade prompt instead
const is403Error = error && (error as any)?.response?.status === 403;
if (error && !is403Error) {
return (
<div className="p-8">
<div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
<p className="text-red-800 dark:text-red-300">
{t('common.error')}: {error instanceof Error ? error.message : 'Unknown error'}
</p>
</div>
</div>
);
}
// If 403 error, treat as locked
const effectivelyLocked = isLocked || is403Error;
return (
<LockedSection feature="automations" isLocked={effectivelyLocked} variant="overlay">
<div className="p-8 space-y-6 max-w-7xl mx-auto">
{/* Header */}
<div className="flex items-center justify-between">
<div>
<h2 className="text-2xl font-bold text-gray-900 dark:text-white flex items-center gap-2">
<ShoppingBag className="h-7 w-7 text-brand-600" />
{t('automations.marketplace', 'Automation Marketplace')}
</h2>
<p className="text-gray-500 dark:text-gray-400 mt-1">
{t('automations.marketplaceDescription', 'Extend your business with powerful automations')}
</p>
</div>
</div>
{/* Search and Filters */}
<div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6 shadow-sm">
<div className="flex flex-col lg:flex-row gap-4">
{/* Search Bar */}
<div className="flex-1 relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-5 w-5 text-gray-400" />
<input
type="text"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
placeholder={t('automations.searchAutomations', 'Search automations...')}
className="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
/>
</div>
{/* Category Filter */}
<div className="flex items-center gap-2">
<Filter className="h-5 w-5 text-gray-400" />
<select
value={selectedCategory}
onChange={(e) => setSelectedCategory(e.target.value as AutomationCategory | 'ALL')}
className="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
>
<option value="ALL">{t('automations.allCategories', 'All Categories')}</option>
<option value="EMAIL">{t('automations.categoryEmail', 'Email')}</option>
<option value="REPORTS">{t('automations.categoryReports', 'Reports')}</option>
<option value="CUSTOMER">{t('automations.categoryCustomer', 'Customer')}</option>
<option value="BOOKING">{t('automations.categoryBooking', 'Booking')}</option>
<option value="INTEGRATION">{t('automations.categoryIntegration', 'Integration')}</option>
<option value="AUTOMATION">{t('automations.categoryAutomation', 'Automation')}</option>
<option value="OTHER">{t('automations.categoryOther', 'Other')}</option>
</select>
</div>
</div>
{/* Active Filters Summary */}
{(searchQuery || selectedCategory !== 'ALL') && (
<div className="flex items-center gap-2 mt-4">
<span className="text-sm text-gray-500 dark:text-gray-400">
{t('automations.showingResults', 'Showing')} {sortedAutomations.length} {t('automations.results', 'results')}
</span>
{(searchQuery || selectedCategory !== 'ALL') && (
<button
onClick={() => {
setSearchQuery('');
setSelectedCategory('ALL');
}}
className="text-sm text-brand-600 dark:text-brand-400 hover:underline"
>
{t('common.clearAll', 'Clear all')}
</button>
)}
</div>
)}
</div>
{/* Automation Grid */}
{sortedAutomations.length === 0 ? (
<div className="text-center py-12 bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700">
<ShoppingBag className="h-12 w-12 mx-auto text-gray-400 mb-4" />
<p className="text-gray-500 dark:text-gray-400">
{searchQuery || selectedCategory !== 'ALL'
? t('automations.noAutomationsFound', 'No automations found matching your criteria')
: t('automations.noAutomationsAvailable', 'No automations available yet')}
</p>
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{sortedAutomations.map((automation) => (
<div
key={automation.id}
className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 shadow-sm hover:shadow-md transition-shadow overflow-hidden flex flex-col"
>
{/* Automation Card Header */}
<div className="p-6 flex-1">
<div className="flex items-start gap-3 mb-3">
{/* Logo */}
{automation.logoUrl ? (
<img
src={automation.logoUrl}
alt={`${automation.name} logo`}
className="w-12 h-12 rounded-lg object-cover flex-shrink-0"
/>
) : (
<div className="w-12 h-12 rounded-lg bg-gray-100 dark:bg-gray-700 flex items-center justify-center flex-shrink-0">
<Package className="h-6 w-6 text-gray-400" />
</div>
)}
<div className="flex-1 min-w-0">
<div className="flex items-start justify-between mb-2">
<div className="flex items-center gap-2 flex-wrap">
<span className={`inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-medium ${categoryColors[automation.category]}`}>
{categoryIcons[automation.category]}
{automation.category}
</span>
{automation.isFeatured && (
<span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-medium bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300">
<Zap className="h-3 w-3" />
Featured
</span>
)}
{installedTemplateIds.has(automation.id) && (
<span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-medium bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300">
<CheckCircle className="h-3 w-3" />
Installed
</span>
)}
</div>
{automation.isVerified && (
<CheckCircle className="h-5 w-5 text-blue-500 flex-shrink-0" title="Verified" />
)}
</div>
</div>
</div>
<h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-2">
{automation.name}
</h3>
<p className="text-sm text-gray-600 dark:text-gray-400 mb-4 line-clamp-2">
{automation.description}
</p>
{/* Stats */}
<div className="flex items-center gap-4 text-sm text-gray-500 dark:text-gray-400">
<div className="flex items-center gap-1">
<Star className="h-4 w-4 text-amber-500 fill-amber-500" />
<span className="font-medium">{automation.rating.toFixed(1)}</span>
<span className="text-xs">({automation.ratingCount})</span>
</div>
<div className="flex items-center gap-1">
<Download className="h-4 w-4" />
<span>{automation.installCount.toLocaleString()}</span>
</div>
</div>
<div className="mt-3 text-xs text-gray-400 dark:text-gray-500">
by {automation.author} v{automation.version}
</div>
</div>
{/* Automation Card Actions */}
<div className="px-6 py-4 bg-gray-50 dark:bg-gray-900/50 border-t border-gray-100 dark:border-gray-700">
<button
onClick={() => handleInstall(automation)}
className="w-full flex items-center justify-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 transition-colors font-medium text-sm"
>
<Eye className="h-4 w-4" />
{t('automations.view', 'View')}
</button>
</div>
</div>
))}
</div>
)}
{/* Automation Details Modal */}
{showDetailsModal && selectedAutomation && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4">
<div className="bg-white dark:bg-gray-800 rounded-xl shadow-xl max-w-2xl w-full max-h-[90vh] overflow-hidden flex flex-col">
{/* Modal Header */}
<div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between">
<div className="flex items-center gap-3">
{/* Logo in modal header */}
{selectedAutomation.logoUrl ? (
<img
src={selectedAutomation.logoUrl}
alt={`${selectedAutomation.name} logo`}
className="w-10 h-10 rounded-lg object-cover flex-shrink-0"
/>
) : (
<div className="w-10 h-10 rounded-lg bg-gray-100 dark:bg-gray-700 flex items-center justify-center flex-shrink-0">
<Package className="h-5 w-5 text-gray-400" />
</div>
)}
<div className="flex items-center gap-2">
<h3 className="text-xl font-semibold text-gray-900 dark:text-white">
{selectedAutomation.name}
</h3>
{selectedAutomation.isVerified && (
<CheckCircle className="h-5 w-5 text-blue-500" title="Verified" />
)}
</div>
</div>
<button
onClick={() => {
setShowDetailsModal(false);
setSelectedAutomation(null);
setShowCode(false);
}}
className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
>
<X className="h-5 w-5" />
</button>
</div>
{/* Modal Body */}
<div className="p-6 space-y-6 overflow-y-auto flex-1">
{isLoadingDetails ? (
<div className="flex items-center justify-center py-12">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-brand-600"></div>
</div>
) : (
<>
<div className="flex items-center gap-2">
<span className={`inline-flex items-center gap-1 px-3 py-1.5 rounded-full text-sm font-medium ${categoryColors[selectedAutomation.category]}`}>
{categoryIcons[selectedAutomation.category]}
{selectedAutomation.category}
</span>
{selectedAutomation.isFeatured && (
<span className="inline-flex items-center gap-1 px-3 py-1.5 rounded-full text-sm font-medium bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300">
<Zap className="h-4 w-4" />
Featured
</span>
)}
</div>
<div>
<h4 className="text-sm font-semibold text-gray-900 dark:text-white mb-2">
{t('automations.description', 'Description')}
</h4>
<p className="text-gray-600 dark:text-gray-400">
{selectedAutomation.description}
</p>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<h4 className="text-sm font-semibold text-gray-900 dark:text-white mb-2">
{t('automations.version', 'Version')}
</h4>
<p className="text-gray-600 dark:text-gray-400">{selectedAutomation.version}</p>
</div>
<div>
<h4 className="text-sm font-semibold text-gray-900 dark:text-white mb-2">
{t('automations.author', 'Author')}
</h4>
<p className="text-gray-600 dark:text-gray-400">{selectedAutomation.author}</p>
</div>
</div>
<div className="flex items-center gap-6 text-sm">
<div className="flex items-center gap-2">
<Star className="h-5 w-5 text-amber-500 fill-amber-500" />
<span className="font-semibold text-gray-900 dark:text-white">
{selectedAutomation.rating.toFixed(1)}
</span>
<span className="text-gray-500 dark:text-gray-400">
({selectedAutomation.ratingCount} {t('automations.ratings', 'ratings')})
</span>
</div>
<div className="flex items-center gap-2">
<Download className="h-5 w-5 text-gray-400" />
<span className="text-gray-600 dark:text-gray-400">
{selectedAutomation.installCount.toLocaleString()} {t('automations.installs', 'installs')}
</span>
</div>
</div>
{/* Code Viewer Section */}
{selectedAutomation.automationCode && (
<div className="space-y-3">
<button
onClick={() => setShowCode(!showCode)}
className="flex items-center justify-between w-full px-4 py-3 bg-gray-100 dark:bg-gray-700 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors"
>
<span className="font-semibold text-gray-900 dark:text-white">
{t('automations.viewCode', 'View Code')}
</span>
<ChevronDown
className={`h-5 w-5 text-gray-600 dark:text-gray-400 transition-transform ${showCode ? 'rotate-180' : ''}`}
/>
</button>
{showCode && (
<div className="space-y-3">
{/* Platform-only code warnings */}
{(() => {
const { hasPlatformCode, warnings } = detectPlatformOnlyCode(selectedAutomation.automationCode || '');
return hasPlatformCode ? (
<div className="bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg p-4">
<div className="flex items-start gap-3">
<AlertTriangle className="h-5 w-5 text-amber-600 dark:text-amber-400 flex-shrink-0 mt-0.5" />
<div className="flex-1">
<h5 className="font-semibold text-amber-900 dark:text-amber-200 mb-2">
{t('automations.platformOnlyWarning', 'Platform-Only Features Detected')}
</h5>
<ul className="space-y-1 text-sm text-amber-800 dark:text-amber-300">
{warnings.map((warning, idx) => (
<li key={idx} className="flex items-start gap-2">
<span className="text-amber-600 dark:text-amber-400 mt-0.5"></span>
<span>{warning}</span>
</li>
))}
</ul>
</div>
</div>
</div>
) : null;
})()}
{/* Code display with syntax highlighting */}
<div className="rounded-lg overflow-hidden border border-gray-200 dark:border-gray-700">
<SyntaxHighlighter
language="javascript"
style={vscDarkPlus}
customStyle={{
margin: 0,
borderRadius: 0,
fontSize: '0.875rem',
maxHeight: '400px'
}}
showLineNumbers
>
{selectedAutomation.automationCode}
</SyntaxHighlighter>
</div>
</div>
)}
</div>
)}
</>
)}
</div>
{/* Modal Footer */}
<div className="px-6 py-4 bg-gray-50 dark:bg-gray-900/50 border-t border-gray-200 dark:border-gray-700 flex justify-end gap-3">
<button
onClick={() => {
setShowDetailsModal(false);
setSelectedAutomation(null);
setShowCode(false);
}}
className="px-4 py-2 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors font-medium"
>
{installedTemplateIds.has(selectedAutomation.id) ? t('common.close', 'Close') : t('common.cancel', 'Cancel')}
</button>
{installedTemplateIds.has(selectedAutomation.id) ? (
<button
onClick={() => {
setShowDetailsModal(false);
setSelectedAutomation(null);
setShowCode(false);
navigate('/dashboard/automations/my-automations');
}}
className="flex items-center gap-2 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors font-medium"
>
<CheckCircle className="h-4 w-4" />
{t('automations.viewInstalled', 'View in My Automations')}
</button>
) : (
<button
onClick={confirmInstall}
disabled={installMutation.isPending || isLoadingDetails}
className="flex items-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors font-medium"
>
{installMutation.isPending ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
{t('automations.installing', 'Installing...')}
</>
) : (
<>
<Download className="h-4 w-4" />
{t('automations.install', 'Install')}
</>
)}
</button>
)}
</div>
</div>
</div>
)}
{/* What's Next Modal - shown after successful install */}
{showWhatsNextModal && selectedAutomation && (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50">
<div className="bg-white dark:bg-gray-800 rounded-xl max-w-lg w-full shadow-2xl overflow-hidden">
{/* Success Header */}
<div className="bg-gradient-to-r from-green-500 to-emerald-600 px-6 py-8 text-center">
<div className="w-16 h-16 bg-white/20 rounded-full flex items-center justify-center mx-auto mb-4">
<CheckCircle className="w-10 h-10 text-white" />
</div>
<h2 className="text-2xl font-bold text-white mb-2">
Automation Installed!
</h2>
<p className="text-green-100">
{selectedAutomation.name} is ready to use
</p>
</div>
{/* What's Next Options */}
<div className="p-6 space-y-4">
<h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
What would you like to do?
</h3>
{/* Schedule Task Option */}
<button
onClick={() => {
setShowWhatsNextModal(false);
setSelectedAutomation(null);
navigate('/dashboard/tasks');
}}
className="w-full flex items-center gap-4 p-4 border border-gray-200 dark:border-gray-700 rounded-lg hover:border-blue-500 dark:hover:border-blue-500 hover:bg-blue-50 dark:hover:bg-blue-900/20 transition-colors text-left group"
>
<div className="p-3 bg-blue-100 dark:bg-blue-900/30 rounded-lg">
<Clock className="w-6 h-6 text-blue-600 dark:text-blue-400" />
</div>
<div className="flex-1">
<p className="font-semibold text-gray-900 dark:text-white">
Schedule it
</p>
<p className="text-sm text-gray-600 dark:text-gray-400">
Run automatically on a schedule (hourly, daily, etc.)
</p>
</div>
<ArrowRight className="w-5 h-5 text-gray-400 group-hover:text-blue-600 dark:group-hover:text-blue-400 transition-colors" />
</button>
{/* Configure Option */}
<button
onClick={() => {
setShowWhatsNextModal(false);
setSelectedAutomation(null);
navigate('/dashboard/automations/my-automations');
}}
className="w-full flex items-center gap-4 p-4 border border-gray-200 dark:border-gray-700 rounded-lg hover:border-purple-500 dark:hover:border-purple-500 hover:bg-purple-50 dark:hover:bg-purple-900/20 transition-colors text-left group"
>
<div className="p-3 bg-purple-100 dark:bg-purple-900/30 rounded-lg">
<Settings className="w-6 h-6 text-purple-600 dark:text-purple-400" />
</div>
<div className="flex-1">
<p className="font-semibold text-gray-900 dark:text-white">
Configure settings
</p>
<p className="text-sm text-gray-600 dark:text-gray-400">
Set up automation options and customize behavior
</p>
</div>
<ArrowRight className="w-5 h-5 text-gray-400 group-hover:text-purple-600 dark:group-hover:text-purple-400 transition-colors" />
</button>
{/* Done Option */}
<button
onClick={() => {
setShowWhatsNextModal(false);
setSelectedAutomation(null);
}}
className="w-full p-3 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors text-center"
>
Done for now
</button>
</div>
</div>
</div>
)}
</div>
</LockedSection>
);
};
export default AutomationMarketplace;

View File

@@ -0,0 +1,309 @@
import { useState, useEffect, useRef, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { useQuery } from '@tanstack/react-query';
import { Bot, RefreshCw, AlertTriangle, Loader2, ExternalLink, Sparkles } from 'lucide-react';
import api from '../api/client';
import { usePlanFeatures } from '../hooks/usePlanFeatures';
import { LockedSection } from '../components/UpgradePrompt';
interface ActivepiecesEmbedData {
token: string;
projectId: string;
embedUrl: string;
}
// Activepieces SDK event types
const ActivepiecesClientEventName = {
CLIENT_INIT: 'CLIENT_INIT',
CLIENT_AUTHENTICATION_SUCCESS: 'CLIENT_AUTHENTICATION_SUCCESS',
CLIENT_AUTHENTICATION_FAILED: 'CLIENT_AUTHENTICATION_FAILED',
CLIENT_CONFIGURATION_FINISHED: 'CLIENT_CONFIGURATION_FINISHED',
CLIENT_ROUTE_CHANGED: 'CLIENT_ROUTE_CHANGED',
} as const;
const ActivepiecesVendorEventName = {
VENDOR_INIT: 'VENDOR_INIT',
VENDOR_ROUTE_CHANGED: 'VENDOR_ROUTE_CHANGED',
} as const;
/**
* Automations Page
*
* Embeds the Activepieces workflow builder directly in SmoothSchedule.
* Each tenant gets their own isolated Activepieces project.
*
* Features:
* - Visual workflow builder with drag-and-drop
* - AI Copilot for natural language flow creation
* - Pre-built integrations with thousands of apps
* - Per-tenant isolation
*/
export default function Automations() {
const { t, i18n } = useTranslation();
const { features, loading: featuresLoading } = usePlanFeatures();
const iframeRef = useRef<HTMLIFrameElement>(null);
const [iframeReady, setIframeReady] = useState(false);
const [authenticated, setAuthenticated] = useState(false);
const initSentRef = useRef(false);
// Fetch embed token for Activepieces
const {
data: embedData,
isLoading,
error,
refetch,
} = useQuery<ActivepiecesEmbedData>({
queryKey: ['activepieces-embed'],
queryFn: async () => {
const response = await api.get('/activepieces/embed-token/');
return response.data;
},
staleTime: 1000 * 60 * 30, // Token valid for 30 minutes
retry: 2,
});
// Navigate to a specific route in Activepieces iframe
const navigateToRoute = useCallback((route: string) => {
if (!iframeRef.current?.contentWindow) {
return;
}
const routeMessage = {
type: ActivepiecesVendorEventName.VENDOR_ROUTE_CHANGED,
data: {
vendorRoute: route, // Must be vendorRoute, not route
},
};
iframeRef.current.contentWindow.postMessage(routeMessage, '*');
}, []);
// Send VENDOR_INIT message to iframe with JWT token
const sendInitMessage = useCallback(() => {
if (!iframeRef.current?.contentWindow || !embedData?.token || initSentRef.current) {
return;
}
const initMessage = {
type: ActivepiecesVendorEventName.VENDOR_INIT,
data: {
jwtToken: embedData.token,
hideSidebar: false,
disableNavigationInBuilder: false,
hideFolders: false,
hideFlowNameInBuilder: false,
hideExportAndImportFlow: false,
hideDuplicateFlow: false,
hideFlowsPageNavbar: false,
hidePageHeader: false,
locale: i18n.language || 'en',
initialRoute: '/flows', // Start on flows page to show sidebar
},
};
iframeRef.current.contentWindow.postMessage(initMessage, '*');
initSentRef.current = true;
}, [embedData?.token, i18n.language]);
// Listen for messages from Activepieces iframe
useEffect(() => {
const handleMessage = (event: MessageEvent) => {
// Verify origin matches our Activepieces instance
if (embedData?.embedUrl && !event.origin.includes(new URL(embedData.embedUrl).host)) {
return;
}
const { type } = event.data || {};
switch (type) {
case ActivepiecesClientEventName.CLIENT_INIT:
// Iframe is ready, send init with token
setIframeReady(true);
sendInitMessage();
break;
case ActivepiecesClientEventName.CLIENT_AUTHENTICATION_SUCCESS:
// Authentication succeeded, wait for configuration to finish
break;
case ActivepiecesClientEventName.CLIENT_AUTHENTICATION_FAILED:
console.error('Activepieces authentication failed:', event.data);
setAuthenticated(false);
break;
case ActivepiecesClientEventName.CLIENT_CONFIGURATION_FINISHED:
// Configuration complete, builder is ready
setAuthenticated(true);
break;
}
};
window.addEventListener('message', handleMessage);
return () => window.removeEventListener('message', handleMessage);
}, [embedData?.embedUrl, sendInitMessage, navigateToRoute]);
// Reset state when token changes
useEffect(() => {
if (embedData?.token) {
setIframeReady(false);
setAuthenticated(false);
initSentRef.current = false;
}
}, [embedData?.token]);
// Check feature access
const canAccessAutomations = features?.can_access_automations ?? true;
// Loading state
if (isLoading || featuresLoading) {
return (
<div className="flex items-center justify-center min-h-[400px]">
<div className="text-center">
<Loader2 className="h-8 w-8 animate-spin text-primary-600 mx-auto mb-3" />
<p className="text-gray-600 dark:text-gray-400">
{t('automations.loading', 'Loading automation builder...')}
</p>
</div>
</div>
);
}
// Feature locked state
if (!canAccessAutomations) {
return (
<div className="p-6">
<LockedSection
title={t('automations.locked.title', 'Automations')}
description={t(
'automations.locked.description',
'Upgrade your plan to access powerful workflow automation with AI-powered flow creation.'
)}
featureName="automations"
/>
</div>
);
}
// Error state
if (error) {
return (
<div className="p-6">
<div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-6 text-center">
<AlertTriangle className="h-12 w-12 text-red-500 mx-auto mb-4" />
<h3 className="text-lg font-semibold text-red-800 dark:text-red-200 mb-2">
{t('automations.error.title', 'Unable to load automation builder')}
</h3>
<p className="text-red-600 dark:text-red-300 mb-4">
{t(
'automations.error.description',
'There was a problem connecting to the automation service. Please try again.'
)}
</p>
<button
onClick={() => refetch()}
className="inline-flex items-center px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors"
>
<RefreshCw className="h-4 w-4 mr-2" />
{t('common.retry', 'Try Again')}
</button>
</div>
</div>
);
}
// Build iframe URL - use /embed route for SDK communication
const iframeSrc = embedData?.embedUrl
? `${embedData.embedUrl}/embed`
: '';
// Show loading until authenticated
const showLoading = !authenticated && iframeSrc;
return (
<div className="h-full flex flex-col">
{/* Header */}
<div className="bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 px-6 py-4">
<div className="flex items-center justify-between">
<div className="flex items-center space-x-3">
<div className="p-2 bg-primary-100 dark:bg-primary-900/30 rounded-lg">
<Bot className="h-6 w-6 text-primary-600 dark:text-primary-400" />
</div>
<div>
<h1 className="text-xl font-semibold text-gray-900 dark:text-white">
{t('automations.title', 'Automations')}
</h1>
<p className="text-sm text-gray-500 dark:text-gray-400">
{t(
'automations.subtitle',
'Build powerful workflows to automate your business'
)}
</p>
</div>
</div>
<div className="flex items-center space-x-3">
{/* AI Copilot hint */}
<div className="hidden sm:flex items-center px-3 py-1.5 bg-purple-100 dark:bg-purple-900/30 rounded-full">
<Sparkles className="h-4 w-4 text-purple-600 dark:text-purple-400 mr-2" />
<span className="text-sm font-medium text-purple-700 dark:text-purple-300">
{t('automations.aiEnabled', 'AI Copilot Enabled')}
</span>
</div>
{/* Refresh button */}
<button
onClick={() => {
initSentRef.current = false;
setAuthenticated(false);
setIframeReady(false);
refetch();
}}
className="p-2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
title={t('common.refresh', 'Refresh')}
>
<RefreshCw className="h-5 w-5" />
</button>
{/* Open in new tab */}
{embedData?.embedUrl && (
<a
href={embedData.embedUrl}
target="_blank"
rel="noopener noreferrer"
className="p-2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
title={t('automations.openInTab', 'Open in new tab')}
>
<ExternalLink className="h-5 w-5" />
</a>
)}
</div>
</div>
</div>
{/* Embedded Activepieces Builder */}
<div className="flex-1 relative bg-gray-50 dark:bg-gray-900">
{/* Loading overlay */}
{showLoading && (
<div className="absolute inset-0 flex items-center justify-center bg-gray-50 dark:bg-gray-900 z-10">
<div className="text-center">
<Loader2 className="h-8 w-8 animate-spin text-primary-600 mx-auto mb-3" />
<p className="text-gray-600 dark:text-gray-400">
{t('automations.loadingBuilder', 'Loading workflow builder...')}
</p>
</div>
</div>
)}
{iframeSrc && (
<iframe
ref={iframeRef}
src={iframeSrc}
className="w-full h-full border-0"
allow="clipboard-read; clipboard-write"
title={t('automations.builderTitle', 'Automation Builder')}
/>
)}
</div>
</div>
);
}

View File

@@ -1,568 +0,0 @@
/**
* Create Automation Page
*
* Allows businesses to create custom automations with code editor,
* category selection, and visibility options.
*/
import React, { useState, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import {
Code,
Save,
Eye,
EyeOff,
ArrowLeft,
Info,
CheckCircle,
AlertTriangle,
Mail,
BarChart3,
Users,
Calendar,
Link as LinkIcon,
Bot,
Package,
Image,
HelpCircle,
} from 'lucide-react';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { vscDarkPlus } from 'react-syntax-highlighter/dist/esm/styles/prism';
import api from '../api/client';
import { AutomationCategory } from '../types';
import { usePlanFeatures } from '../hooks/usePlanFeatures';
// Category icon mapping
const categoryIcons: Record<AutomationCategory, React.ReactNode> = {
EMAIL: <Mail className="h-4 w-4" />,
REPORTS: <BarChart3 className="h-4 w-4" />,
CUSTOMER: <Users className="h-4 w-4" />,
BOOKING: <Calendar className="h-4 w-4" />,
INTEGRATION: <LinkIcon className="h-4 w-4" />,
AUTOMATION: <Bot className="h-4 w-4" />,
OTHER: <Package className="h-4 w-4" />,
};
// Category descriptions
const categoryDescriptions: Record<AutomationCategory, string> = {
EMAIL: 'Email notifications and automated messaging',
REPORTS: 'Analytics, reports, and data exports',
CUSTOMER: 'Customer engagement and retention',
BOOKING: 'Scheduling and booking automation',
INTEGRATION: 'Third-party service integrations',
AUTOMATION: 'General business automation',
OTHER: 'Miscellaneous automations',
};
// Default automation code template
const DEFAULT_AUTOMATION_CODE = `# My Custom Automation
#
# This automation runs on a schedule and can interact with your business data.
# Use template variables to make your automation configurable.
#
# Available template variables:
# {{PROMPT:variable_name:default_value:description}}
# {{CONTEXT:context_type}} - Access business context (CUSTOMERS, EVENTS, etc.)
# {{DATE:format}} - Current date in specified format
# Example: Get all customers who haven't booked in 30 days
inactive_days = int("{{PROMPT:inactive_days:30:Days of inactivity}}")
# Access customer data
customers = {{CONTEXT:CUSTOMERS}}
# Filter inactive customers
from datetime import datetime, timedelta
cutoff_date = datetime.now() - timedelta(days=inactive_days)
inactive_customers = [
c for c in customers
if not c.get('last_booking') or
datetime.fromisoformat(c['last_booking']) < cutoff_date
]
# Return results (will be logged)
result = {
'inactive_count': len(inactive_customers),
'customers': inactive_customers[:10], # First 10 for preview
'message': f"Found {len(inactive_customers)} inactive customers"
}
`;
interface FormData {
name: string;
shortDescription: string;
description: string;
category: AutomationCategory;
automationCode: string;
version: string;
logoUrl: string;
visibility: 'PRIVATE' | 'PUBLIC';
}
const CreateAutomation: React.FC = () => {
const { t } = useTranslation();
const navigate = useNavigate();
const queryClient = useQueryClient();
const { canUse } = usePlanFeatures();
const [formData, setFormData] = useState<FormData>({
name: '',
shortDescription: '',
description: '',
category: 'AUTOMATION',
automationCode: DEFAULT_AUTOMATION_CODE,
version: '1.0.0',
logoUrl: '',
visibility: 'PRIVATE',
});
const [showPreview, setShowPreview] = useState(false);
const [extractedVariables, setExtractedVariables] = useState<any[]>([]);
// Extract template variables from code
const extractVariables = useCallback((code: string) => {
const promptPattern = /\{\{PROMPT:([^:}]+):([^:}]*):([^}]*)\}\}/g;
const contextPattern = /\{\{CONTEXT:([^}]+)\}\}/g;
const datePattern = /\{\{DATE:([^}]+)\}\}/g;
const variables: any[] = [];
let match;
while ((match = promptPattern.exec(code)) !== null) {
variables.push({
type: 'PROMPT',
name: match[1],
default: match[2],
description: match[3],
});
}
while ((match = contextPattern.exec(code)) !== null) {
variables.push({
type: 'CONTEXT',
name: match[1],
});
}
while ((match = datePattern.exec(code)) !== null) {
variables.push({
type: 'DATE',
format: match[1],
});
}
return variables;
}, []);
// Update extracted variables when code changes
const handleCodeChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
const newCode = e.target.value;
setFormData(prev => ({ ...prev, automationCode: newCode }));
setExtractedVariables(extractVariables(newCode));
};
// Create automation mutation
const createMutation = useMutation({
mutationFn: async (data: FormData) => {
const payload = {
name: data.name,
short_description: data.shortDescription,
description: data.description,
category: data.category,
automation_code: data.automationCode,
version: data.version,
logo_url: data.logoUrl || undefined,
visibility: data.visibility,
};
const response = await api.post('/automation-templates/', payload);
return response.data;
},
onSuccess: (data) => {
queryClient.invalidateQueries({ queryKey: ['automation-templates'] });
navigate('/dashboard/automations/my-automations');
},
});
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
createMutation.mutate(formData);
};
// Check if user can create automations
const canCreateAutomations = canUse('can_create_automations');
if (!canCreateAutomations) {
return (
<div className="p-8 max-w-4xl mx-auto">
<div className="bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-xl p-8 text-center">
<AlertTriangle className="h-16 w-16 mx-auto text-amber-500 mb-4" />
<h2 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">
{t('automations.upgradeRequired', 'Upgrade Required')}
</h2>
<p className="text-gray-600 dark:text-gray-400 mb-6">
{t('automations.upgradeToCreate', 'Automation creation is available on higher-tier plans. Upgrade your subscription to create custom automations.')}
</p>
<button
onClick={() => navigate('/dashboard/settings/billing')}
className="px-6 py-3 bg-brand-600 text-white rounded-lg hover:bg-brand-700 transition-colors font-medium"
>
{t('automations.viewPlans', 'View Plans')}
</button>
</div>
</div>
);
}
return (
<div className="p-8 max-w-6xl mx-auto">
{/* Header */}
<div className="mb-8">
<button
onClick={() => navigate('/dashboard/automations/my-automations')}
className="flex items-center gap-2 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white mb-4 transition-colors"
>
<ArrowLeft size={20} />
{t('common.back', 'Back')}
</button>
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-gray-900 dark:text-white flex items-center gap-3">
<Code className="text-brand-500" />
{t('automations.createAutomation', 'Create Custom Automation')}
</h1>
<p className="text-gray-500 dark:text-gray-400 mt-1">
{t('automations.createAutomationDescription', 'Build a custom automation for your business')}
</p>
</div>
<a
href="/help/automations"
target="_blank"
className="flex items-center gap-2 text-brand-600 dark:text-brand-400 hover:underline"
>
<HelpCircle size={18} />
{t('automations.viewDocs', 'View Documentation')}
</a>
</div>
</div>
<form onSubmit={handleSubmit} className="space-y-6">
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
{/* Left Column - Basic Info */}
<div className="lg:col-span-1 space-y-6">
{/* Automation Name */}
<div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6">
<h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
{t('automations.basicInfo', 'Basic Information')}
</h3>
<div className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
{t('automations.automationName', 'Automation Name')} *
</label>
<input
type="text"
value={formData.name}
onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500"
placeholder="e.g., Win Back Inactive Customers"
required
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
{t('automations.shortDescription', 'Short Description')} *
</label>
<input
type="text"
value={formData.shortDescription}
onChange={(e) => setFormData(prev => ({ ...prev, shortDescription: e.target.value }))}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500"
placeholder="Brief summary for marketplace listing"
maxLength={200}
required
/>
<p className="mt-1 text-xs text-gray-500">{formData.shortDescription.length}/200</p>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
{t('automations.description', 'Full Description')}
</label>
<textarea
value={formData.description}
onChange={(e) => setFormData(prev => ({ ...prev, description: e.target.value }))}
rows={4}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 resize-none"
placeholder="Detailed description of what this automation does..."
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
{t('automations.category', 'Category')} *
</label>
<select
value={formData.category}
onChange={(e) => setFormData(prev => ({ ...prev, category: e.target.value as AutomationCategory }))}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500"
>
{Object.entries(categoryDescriptions).map(([key, desc]) => (
<option key={key} value={key}>
{key} - {desc}
</option>
))}
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
{t('automations.version', 'Version')}
</label>
<input
type="text"
value={formData.version}
onChange={(e) => setFormData(prev => ({ ...prev, version: e.target.value }))}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500"
placeholder="1.0.0"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
<Image size={16} className="inline mr-1" />
{t('automations.logoUrl', 'Logo URL')} ({t('common.optional', 'optional')})
</label>
<input
type="url"
value={formData.logoUrl}
onChange={(e) => setFormData(prev => ({ ...prev, logoUrl: e.target.value }))}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500"
placeholder="https://example.com/logo.png"
/>
</div>
</div>
</div>
{/* Visibility */}
<div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6">
<h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
{t('automations.visibility', 'Visibility')}
</h3>
<div className="space-y-3">
<label className="flex items-start gap-3 p-3 border border-gray-200 dark:border-gray-700 rounded-lg cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors">
<input
type="radio"
name="visibility"
value="PRIVATE"
checked={formData.visibility === 'PRIVATE'}
onChange={(e) => setFormData(prev => ({ ...prev, visibility: 'PRIVATE' }))}
className="mt-1"
/>
<div>
<div className="flex items-center gap-2">
<EyeOff size={16} className="text-gray-500" />
<span className="font-medium text-gray-900 dark:text-white">
{t('automations.private', 'Private')}
</span>
</div>
<p className="text-sm text-gray-500 dark:text-gray-400">
{t('automations.privateDescription', 'Only you can see and use this automation')}
</p>
</div>
</label>
<label className="flex items-start gap-3 p-3 border border-gray-200 dark:border-gray-700 rounded-lg cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors">
<input
type="radio"
name="visibility"
value="PUBLIC"
checked={formData.visibility === 'PUBLIC'}
onChange={(e) => setFormData(prev => ({ ...prev, visibility: 'PUBLIC' }))}
className="mt-1"
/>
<div>
<div className="flex items-center gap-2">
<Eye size={16} className="text-green-500" />
<span className="font-medium text-gray-900 dark:text-white">
{t('automations.public', 'Public (Marketplace)')}
</span>
</div>
<p className="text-sm text-gray-500 dark:text-gray-400">
{t('automations.publicDescription', 'Submit for review to be listed in the marketplace')}
</p>
</div>
</label>
</div>
{formData.visibility === 'PUBLIC' && (
<div className="mt-4 p-3 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg">
<div className="flex items-start gap-2">
<Info size={16} className="text-blue-500 mt-0.5 flex-shrink-0" />
<p className="text-sm text-blue-800 dark:text-blue-200">
{t('automations.publicNote', 'Public automations require approval before appearing in the marketplace. Our team will review your code for security and quality.')}
</p>
</div>
</div>
)}
</div>
{/* Extracted Variables */}
{extractedVariables.length > 0 && (
<div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6">
<h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
{t('automations.templateVariables', 'Detected Variables')}
</h3>
<div className="space-y-2">
{extractedVariables.map((v, idx) => (
<div key={idx} className="p-2 bg-gray-50 dark:bg-gray-900/50 rounded-lg text-sm">
<div className="flex items-center gap-2">
<span className={`px-1.5 py-0.5 rounded text-xs font-medium ${
v.type === 'PROMPT' ? 'bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-300' :
v.type === 'CONTEXT' ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300' :
'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300'
}`}>
{v.type}
</span>
<span className="font-mono text-gray-900 dark:text-white">
{v.name || v.format}
</span>
</div>
{v.description && (
<p className="text-gray-500 dark:text-gray-400 mt-1 ml-4">
{v.description}
</p>
)}
</div>
))}
</div>
</div>
)}
</div>
{/* Right Column - Code Editor */}
<div className="lg:col-span-2 space-y-6">
<div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden">
<div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between">
<h3 className="text-lg font-semibold text-gray-900 dark:text-white flex items-center gap-2">
<Code size={20} className="text-brand-500" />
{t('automations.automationCode', 'Automation Code')}
</h3>
<button
type="button"
onClick={() => setShowPreview(!showPreview)}
className="flex items-center gap-2 text-sm text-brand-600 dark:text-brand-400 hover:underline"
>
{showPreview ? <EyeOff size={16} /> : <Eye size={16} />}
{showPreview ? t('automations.hidePreview', 'Hide Preview') : t('automations.showPreview', 'Show Preview')}
</button>
</div>
{showPreview ? (
<div className="max-h-[600px] overflow-auto">
<SyntaxHighlighter
language="python"
style={vscDarkPlus}
customStyle={{
margin: 0,
borderRadius: 0,
fontSize: '0.875rem',
}}
showLineNumbers
>
{formData.automationCode}
</SyntaxHighlighter>
</div>
) : (
<textarea
value={formData.automationCode}
onChange={handleCodeChange}
rows={25}
className="w-full px-4 py-4 bg-[#1e1e1e] text-gray-100 font-mono text-sm focus:outline-none resize-none"
placeholder="# Write your automation code here..."
spellCheck={false}
/>
)}
</div>
{/* Quick Reference */}
<div className="bg-gradient-to-r from-brand-50 to-indigo-50 dark:from-brand-900/20 dark:to-indigo-900/20 rounded-xl border border-brand-200 dark:border-brand-800 p-6">
<h4 className="font-semibold text-gray-900 dark:text-white mb-3">
{t('automations.quickReference', 'Quick Reference')}
</h4>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm">
<div>
<p className="font-medium text-gray-900 dark:text-white mb-1">Prompt Variable</p>
<code className="text-xs bg-white dark:bg-gray-800 px-2 py-1 rounded block">
{`{{PROMPT:name:default:desc}}`}
</code>
</div>
<div>
<p className="font-medium text-gray-900 dark:text-white mb-1">Context Data</p>
<code className="text-xs bg-white dark:bg-gray-800 px-2 py-1 rounded block">
{`{{CONTEXT:CUSTOMERS}}`}
</code>
</div>
<div>
<p className="font-medium text-gray-900 dark:text-white mb-1">Date Format</p>
<code className="text-xs bg-white dark:bg-gray-800 px-2 py-1 rounded block">
{`{{DATE:%Y-%m-%d}}`}
</code>
</div>
</div>
</div>
</div>
</div>
{/* Error Message */}
{createMutation.isError && (
<div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
<div className="flex items-center gap-2">
<AlertTriangle className="text-red-500" size={20} />
<p className="text-red-800 dark:text-red-200">
{createMutation.error instanceof Error ? createMutation.error.message : 'Failed to create automation'}
</p>
</div>
</div>
)}
{/* Submit Buttons */}
<div className="flex items-center justify-end gap-4 pt-4 border-t border-gray-200 dark:border-gray-700">
<button
type="button"
onClick={() => navigate('/dashboard/automations/my-automations')}
className="px-4 py-2 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
>
{t('common.cancel', 'Cancel')}
</button>
<button
type="submit"
disabled={createMutation.isPending || !formData.name || !formData.shortDescription}
className="flex items-center gap-2 px-6 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors font-medium"
>
{createMutation.isPending ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
{t('automations.creating', 'Creating...')}
</>
) : (
<>
<Save size={18} />
{formData.visibility === 'PUBLIC'
? t('automations.createAndSubmit', 'Create & Submit for Review')
: t('automations.createAutomation', 'Create Automation')}
</>
)}
</button>
</div>
</form>
</div>
);
};
export default CreateAutomation;

View File

@@ -1,829 +0,0 @@
import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import {
Package,
Plus,
Trash2,
Star,
RefreshCw,
CheckCircle,
XCircle,
Mail,
BarChart3,
Users,
Calendar,
Link as LinkIcon,
Bot,
Package as PackageIcon,
X,
AlertTriangle,
Clock,
Settings,
Lock,
Crown,
ArrowUpRight
} from 'lucide-react';
import { Link } from 'react-router-dom';
import api from '../api/client';
import { AutomationInstallation, AutomationCategory } from '../types';
import EmailTemplateSelector from '../components/EmailTemplateSelector';
import { usePlanFeatures } from '../hooks/usePlanFeatures';
import { LockedSection } from '../components/UpgradePrompt';
// Category icon mapping
const categoryIcons: Record<AutomationCategory, React.ReactNode> = {
EMAIL: <Mail className="h-4 w-4" />,
REPORTS: <BarChart3 className="h-4 w-4" />,
CUSTOMER: <Users className="h-4 w-4" />,
BOOKING: <Calendar className="h-4 w-4" />,
INTEGRATION: <LinkIcon className="h-4 w-4" />,
AUTOMATION: <Bot className="h-4 w-4" />,
OTHER: <PackageIcon className="h-4 w-4" />,
};
// Category colors
const categoryColors: Record<AutomationCategory, string> = {
EMAIL: 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300',
REPORTS: 'bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-300',
CUSTOMER: 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300',
BOOKING: 'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-300',
INTEGRATION: 'bg-cyan-100 text-cyan-700 dark:bg-cyan-900/30 dark:text-cyan-300',
AUTOMATION: 'bg-pink-100 text-pink-700 dark:bg-pink-900/30 dark:text-pink-300',
OTHER: 'bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300',
};
const MyAutomations: React.FC = () => {
const { t } = useTranslation();
const navigate = useNavigate();
const queryClient = useQueryClient();
const [selectedAutomation, setSelectedAutomation] = useState<AutomationInstallation | null>(null);
const [showUninstallModal, setShowUninstallModal] = useState(false);
const [showRatingModal, setShowRatingModal] = useState(false);
const [showEditModal, setShowEditModal] = useState(false);
const [rating, setRating] = useState(0);
const [review, setReview] = useState('');
const [configValues, setConfigValues] = useState<Record<string, any>>({});
// Check plan permissions
const { canUse, isLoading: permissionsLoading } = usePlanFeatures();
const hasAutomationsFeature = canUse('automations');
const canCreateAutomations = canUse('can_create_automations');
const isLocked = !hasAutomationsFeature;
// Fetch installed automations - only when user has the feature
const { data: automations = [], isLoading, error } = useQuery<AutomationInstallation[]>({
queryKey: ['automation-installations'],
queryFn: async () => {
const { data } = await api.get('/automation-installations/');
return data.map((a: any) => ({
id: String(a.id),
template: String(a.template),
templateName: a.template_name || a.templateName,
templateDescription: a.template_description || a.templateDescription,
category: a.category,
version: a.version,
authorName: a.author_name || a.authorName,
logoUrl: a.logo_url || a.logoUrl,
templateVariables: a.template_variables || a.templateVariables || {},
configValues: a.config_values || a.configValues || {},
isActive: a.is_active !== undefined ? a.is_active : a.isActive,
installedAt: a.installed_at || a.installedAt,
hasUpdate: a.has_update !== undefined ? a.has_update : a.hasUpdate || false,
rating: a.rating,
review: a.review,
}));
},
// Don't fetch if user doesn't have the automations feature
enabled: hasAutomationsFeature && !permissionsLoading,
});
// Uninstall automation mutation
const uninstallMutation = useMutation({
mutationFn: async (automationId: string) => {
await api.delete(`/automation-installations/${automationId}/`);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['automation-installations'] });
setShowUninstallModal(false);
setSelectedAutomation(null);
},
});
// Rate automation mutation
const rateMutation = useMutation({
mutationFn: async ({ automationId, rating, review }: { automationId: string; rating: number; review: string }) => {
const { data } = await api.post(`/automation-installations/${automationId}/rate/`, {
rating,
review,
});
return data;
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['automation-installations'] });
setShowRatingModal(false);
setSelectedAutomation(null);
setRating(0);
setReview('');
},
});
// Update automation mutation
const updateMutation = useMutation({
mutationFn: async (automationId: string) => {
const { data } = await api.post(`/automation-installations/${automationId}/update/`);
return data;
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['automation-installations'] });
},
});
// Edit config mutation
const editConfigMutation = useMutation({
mutationFn: async ({ automationId, configValues }: { automationId: string; configValues: Record<string, any> }) => {
const { data } = await api.patch(`/automation-installations/${automationId}/`, {
config_values: configValues,
});
return data;
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['automation-installations'] });
setShowEditModal(false);
setSelectedAutomation(null);
setConfigValues({});
},
});
const handleUninstall = (automation: AutomationInstallation) => {
setSelectedAutomation(automation);
setShowUninstallModal(true);
};
const confirmUninstall = () => {
if (selectedAutomation) {
uninstallMutation.mutate(selectedAutomation.id);
}
};
const handleRating = (automation: AutomationInstallation) => {
setSelectedAutomation(automation);
setRating(automation.rating || 0);
setReview(automation.review || '');
setShowRatingModal(true);
};
const submitRating = () => {
if (selectedAutomation && rating > 0) {
rateMutation.mutate({
automationId: selectedAutomation.id,
rating,
review,
});
}
};
const handleUpdate = (automation: AutomationInstallation) => {
updateMutation.mutate(automation.id);
};
const unescapeString = (str: string): string => {
return str
.replace(/\\n/g, '\n')
.replace(/\\r/g, '\r')
.replace(/\\t/g, '\t')
.replace(/\\'/g, "'")
.replace(/\\"/g, '"')
.replace(/\\\\/g, '\\');
};
const handleEdit = (automation: AutomationInstallation) => {
setSelectedAutomation(automation);
// Convert escape sequences to actual characters for display
const displayValues = { ...automation.configValues || {} };
if (automation.templateVariables) {
Object.entries(automation.templateVariables).forEach(([key, variable]: [string, any]) => {
if (displayValues[key]) {
displayValues[key] = unescapeString(displayValues[key]);
}
});
}
setConfigValues(displayValues);
setShowEditModal(true);
};
const escapeString = (str: string): string => {
return str
.replace(/\\/g, '\\\\') // Escape backslashes first
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r')
.replace(/\t/g, '\\t')
.replace(/'/g, "\\'")
.replace(/"/g, '\\"');
};
const submitConfigEdit = () => {
if (selectedAutomation) {
// Convert actual characters back to escape sequences for storage
const storageValues = { ...configValues };
if (selectedAutomation.templateVariables) {
Object.entries(selectedAutomation.templateVariables).forEach(([key, variable]: [string, any]) => {
if (storageValues[key]) {
storageValues[key] = escapeString(storageValues[key]);
}
});
}
editConfigMutation.mutate({
automationId: selectedAutomation.id,
configValues: storageValues,
});
}
};
if (isLoading || permissionsLoading) {
return (
<div className="p-8">
<div className="flex items-center justify-center h-64">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-brand-600"></div>
</div>
</div>
);
}
// Check if error is a 403 (plan restriction) - show upgrade prompt instead
const is403Error = error && (error as any)?.response?.status === 403;
if (error && !is403Error) {
return (
<div className="p-8">
<div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
<p className="text-red-800 dark:text-red-300">
{t('common.error')}: {error instanceof Error ? error.message : 'Unknown error'}
</p>
</div>
</div>
);
}
// If 403 error, treat as locked
const effectivelyLocked = isLocked || is403Error;
return (
<LockedSection feature="automations" isLocked={effectivelyLocked} variant="overlay">
<div className="p-8 space-y-6 max-w-7xl mx-auto">
{/* Header */}
<div className="flex items-center justify-between">
<div>
<h2 className="text-2xl font-bold text-gray-900 dark:text-white flex items-center gap-2">
<Package className="h-7 w-7 text-brand-600" />
{t('automations.myAutomations', 'My Automations')}
</h2>
<p className="text-gray-500 dark:text-gray-400 mt-1">
{t('automations.myAutomationsDescription', 'Manage your installed automations')}
</p>
</div>
<button
onClick={() => navigate('/dashboard/automations/marketplace')}
className="flex items-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 transition-colors font-medium"
>
<Plus className="h-5 w-5" />
{t('automations.browseMarketplace', 'Browse Marketplace')}
</button>
</div>
{/* Automation List */}
{automations.length === 0 ? (
<div className="text-center py-12 bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700">
<Package className="h-12 w-12 mx-auto text-gray-400 mb-4" />
<p className="text-gray-500 dark:text-gray-400 mb-4">
{t('automations.noAutomationsInstalled', 'No automations installed yet')}
</p>
<button
onClick={() => navigate('/dashboard/automations/marketplace')}
className="inline-flex items-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 transition-colors font-medium"
>
<Plus className="h-4 w-4" />
{t('automations.browseMarketplace', 'Browse Marketplace')}
</button>
</div>
) : (
<div className="space-y-4">
{automations.map((item) => (
<div
key={item.id}
className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 shadow-sm hover:shadow-md transition-shadow overflow-hidden"
>
<div className="p-6">
<div className="flex items-start justify-between">
{/* Automation Info */}
<div className="flex-1 min-w-0">
<div className="flex items-center gap-3 mb-2">
{item.logoUrl && (
<img
src={item.logoUrl}
alt={`${item.templateName} logo`}
className="w-10 h-10 rounded-lg object-cover flex-shrink-0"
onError={(e) => {
// Hide image if it fails to load
e.currentTarget.style.display = 'none';
}}
/>
)}
<h3 className="text-lg font-semibold text-gray-900 dark:text-white">
{item.templateName}
</h3>
<span className={`inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium ${categoryColors[item.category]}`}>
{categoryIcons[item.category]}
{item.category}
</span>
{item.hasUpdate && (
<span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300">
<RefreshCw className="h-3 w-3" />
Update Available
</span>
)}
</div>
<p className="text-sm text-gray-600 dark:text-gray-400 mb-3">
{item.templateDescription}
</p>
<div className="flex items-center gap-6 text-sm text-gray-500 dark:text-gray-400">
{item.authorName && (
<div className="flex items-center gap-1">
<span className="font-medium">
{t('automations.author', 'Author')}:
</span>
<span>{item.authorName}</span>
</div>
)}
<div className="flex items-center gap-1">
<span className="font-medium">
{t('automations.version', 'Version')}:
</span>
<span>{item.version}</span>
</div>
<div className="flex items-center gap-1">
<span className="font-medium">
{t('automations.installedOn', 'Installed on')}:
</span>
<span>
{new Date(item.installedAt).toLocaleDateString()}
</span>
</div>
<div className="flex items-center gap-1">
{item.isActive ? (
<>
<CheckCircle className="h-4 w-4 text-green-500" />
<span className="text-green-600 dark:text-green-400 font-medium">
{t('automations.active', 'Active')}
</span>
</>
) : (
<>
<XCircle className="h-4 w-4 text-gray-400" />
<span className="text-gray-500 dark:text-gray-400">
{t('automations.inactive', 'Inactive')}
</span>
</>
)}
</div>
{item.rating && (
<div className="flex items-center gap-1">
<Star className="h-4 w-4 text-amber-500 fill-amber-500" />
<span className="font-medium">{item.rating}/5</span>
</div>
)}
</div>
</div>
{/* Actions */}
<div className="flex items-center gap-2 ml-4">
{/* Configure button */}
<button
onClick={() => handleEdit(item)}
className="flex items-center gap-2 px-3 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 transition-colors text-sm font-medium"
title={t('automations.configure', 'Configure')}
>
<Settings className="h-4 w-4" />
{t('automations.configure', 'Configure')}
</button>
{/* Schedule button - only if not already scheduled */}
{!item.scheduledTaskId && (
<button
onClick={() => navigate('/dashboard/tasks')}
className="flex items-center gap-2 px-3 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors text-sm font-medium"
title={t('automations.schedule', 'Schedule')}
>
<Clock className="h-4 w-4" />
{t('automations.schedule', 'Schedule')}
</button>
)}
{/* Already scheduled indicator */}
{item.scheduledTaskId && (
<span className="flex items-center gap-1.5 px-3 py-2 bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-300 rounded-lg text-sm font-medium">
<Clock className="h-4 w-4" />
{t('automations.scheduled', 'Scheduled')}
</span>
)}
{item.hasUpdate && (
<button
onClick={() => handleUpdate(item)}
disabled={updateMutation.isPending}
className="flex items-center gap-2 px-3 py-2 bg-amber-600 text-white rounded-lg hover:bg-amber-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors text-sm font-medium"
title={t('automations.update', 'Update')}
>
{updateMutation.isPending ? (
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
) : (
<RefreshCw className="h-4 w-4" />
)}
{t('automations.update', 'Update')}
</button>
)}
<button
onClick={() => handleRating(item)}
className="flex items-center gap-2 px-3 py-2 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors text-sm font-medium"
title={item.rating ? t('automations.editRating', 'Edit Rating') : t('automations.rate', 'Rate')}
>
<Star className={`h-4 w-4 ${item.rating ? 'fill-amber-500 text-amber-500' : ''}`} />
{item.rating ? t('automations.editRating', 'Edit Rating') : t('automations.rate', 'Rate')}
</button>
<button
onClick={() => handleUninstall(item)}
className="p-2 text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors"
title={t('automations.uninstall', 'Uninstall')}
>
<Trash2 className="h-5 w-5" />
</button>
</div>
</div>
</div>
</div>
))}
</div>
)}
{/* Info Box */}
<div className={`rounded-xl p-6 border ${
canCreateAutomations
? 'bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800'
: 'bg-amber-50 dark:bg-amber-900/20 border-amber-300 dark:border-amber-700'
}`}>
<div className="flex items-start gap-4">
<div className={`shrink-0 p-2 rounded-lg ${
canCreateAutomations
? 'bg-blue-100 dark:bg-blue-900/40'
: 'bg-gradient-to-br from-amber-400 to-orange-500'
}`}>
{canCreateAutomations ? (
<Package className="h-6 w-6 text-blue-600 dark:text-blue-400" />
) : (
<Crown className="h-6 w-6 text-white" />
)}
</div>
<div className="flex-1">
<div className="flex items-center gap-2 mb-2">
<h3 className={`text-lg font-semibold ${
canCreateAutomations
? 'text-blue-900 dark:text-blue-100'
: 'text-gray-900 dark:text-gray-100'
}`}>
{t('automations.needCustomAutomation', 'Need a custom automation?')}
</h3>
{!canCreateAutomations && (
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300">
<Lock className="h-3 w-3" />
{t('common.upgradeRequired', 'Upgrade Required')}
</span>
)}
</div>
<p className={`mb-4 ${
canCreateAutomations
? 'text-blue-800 dark:text-blue-200'
: 'text-gray-600 dark:text-gray-400'
}`}>
{canCreateAutomations
? t('automations.customAutomationDescription', 'Create your own custom automations to extend your business functionality with specific features tailored to your needs.')
: t('automations.customAutomationUpgradeDescription', 'Custom automations allow you to create automated workflows tailored to your business needs. Upgrade your plan to unlock this feature.')
}
</p>
{canCreateAutomations ? (
<button
onClick={() => navigate('/dashboard/automations/create')}
className="inline-flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors font-medium"
>
<Plus className="h-4 w-4" />
{t('automations.createCustomAutomation', 'Create Custom Automation')}
</button>
) : (
<Link
to="/dashboard/settings/billing"
className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-gradient-to-r from-amber-500 to-orange-500 text-white font-medium hover:from-amber-600 hover:to-orange-600 transition-all shadow-md hover:shadow-lg"
>
<Crown className="h-4 w-4" />
{t('common.upgradeYourPlan', 'Upgrade Your Plan')}
<ArrowUpRight className="h-4 w-4" />
</Link>
)}
</div>
</div>
</div>
{/* Uninstall Confirmation Modal */}
{showUninstallModal && selectedAutomation && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4">
<div className="bg-white dark:bg-gray-800 rounded-xl shadow-xl max-w-md w-full overflow-hidden">
{/* Modal Header */}
<div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="p-2 bg-red-100 dark:bg-red-900/30 rounded-lg">
<AlertTriangle className="h-5 w-5 text-red-600 dark:text-red-400" />
</div>
<h3 className="text-lg font-semibold text-gray-900 dark:text-white">
{t('automations.confirmUninstall', 'Confirm Uninstall')}
</h3>
</div>
<button
onClick={() => {
setShowUninstallModal(false);
setSelectedAutomation(null);
}}
className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
>
<X className="h-5 w-5" />
</button>
</div>
{/* Modal Body */}
<div className="p-6">
<p className="text-gray-600 dark:text-gray-400 mb-4">
{t('automations.uninstallWarning', 'Are you sure you want to uninstall')} <span className="font-semibold text-gray-900 dark:text-white">{selectedAutomation.templateName}</span>?
</p>
<p className="text-sm text-gray-500 dark:text-gray-400">
{t('automations.uninstallNote', 'This action cannot be undone. Your automation data and settings will be removed.')}
</p>
</div>
{/* Modal Footer */}
<div className="px-6 py-4 bg-gray-50 dark:bg-gray-900/50 border-t border-gray-200 dark:border-gray-700 flex justify-end gap-3">
<button
onClick={() => {
setShowUninstallModal(false);
setSelectedAutomation(null);
}}
className="px-4 py-2 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors font-medium"
>
{t('common.cancel', 'Cancel')}
</button>
<button
onClick={confirmUninstall}
disabled={uninstallMutation.isPending}
className="flex items-center gap-2 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors font-medium"
>
{uninstallMutation.isPending ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
{t('automations.uninstalling', 'Uninstalling...')}
</>
) : (
<>
<Trash2 className="h-4 w-4" />
{t('automations.uninstall', 'Uninstall')}
</>
)}
</button>
</div>
</div>
</div>
)}
{/* Rating Modal */}
{showRatingModal && selectedAutomation && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4">
<div className="bg-white dark:bg-gray-800 rounded-xl shadow-xl max-w-md w-full overflow-hidden">
{/* Modal Header */}
<div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between">
<h3 className="text-lg font-semibold text-gray-900 dark:text-white">
{t('automations.rateAutomation', 'Rate Automation')}
</h3>
<button
onClick={() => {
setShowRatingModal(false);
setSelectedAutomation(null);
setRating(0);
setReview('');
}}
className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
>
<X className="h-5 w-5" />
</button>
</div>
{/* Modal Body */}
<div className="p-6 space-y-4">
<div>
<h4 className="text-sm font-medium text-gray-900 dark:text-white mb-2">
{selectedAutomation.templateName}
</h4>
<p className="text-sm text-gray-500 dark:text-gray-400">
{t('automations.rateDescription', 'Share your experience with this automation')}
</p>
</div>
{/* Star Rating */}
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
{t('automations.yourRating', 'Your Rating')} *
</label>
<div className="flex items-center gap-2">
{[1, 2, 3, 4, 5].map((star) => (
<button
key={star}
type="button"
onClick={() => setRating(star)}
className="p-1 hover:scale-110 transition-transform"
>
<Star
className={`h-8 w-8 ${
star <= rating
? 'fill-amber-500 text-amber-500'
: 'text-gray-300 dark:text-gray-600'
}`}
/>
</button>
))}
</div>
</div>
{/* Review */}
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
{t('automations.review', 'Review')} ({t('automations.optional', 'optional')})
</label>
<textarea
value={review}
onChange={(e) => setReview(e.target.value)}
rows={4}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-brand-500 resize-none"
placeholder={t('automations.reviewPlaceholder', 'Share your thoughts about this automation...')}
/>
</div>
</div>
{/* Modal Footer */}
<div className="px-6 py-4 bg-gray-50 dark:bg-gray-900/50 border-t border-gray-200 dark:border-gray-700 flex justify-end gap-3">
<button
onClick={() => {
setShowRatingModal(false);
setSelectedAutomation(null);
setRating(0);
setReview('');
}}
className="px-4 py-2 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors font-medium"
>
{t('common.cancel', 'Cancel')}
</button>
<button
onClick={submitRating}
disabled={rating === 0 || rateMutation.isPending}
className="flex items-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors font-medium"
>
{rateMutation.isPending ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
{t('automations.submitting', 'Submitting...')}
</>
) : (
<>
<Star className="h-4 w-4" />
{t('automations.submitRating', 'Submit Rating')}
</>
)}
</button>
</div>
</div>
</div>
)}
{/* Edit Config Modal */}
{showEditModal && selectedAutomation && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4">
<div className="bg-white dark:bg-gray-800 rounded-xl shadow-xl max-w-2xl w-full overflow-hidden max-h-[80vh] flex flex-col">
{/* Modal Header */}
<div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between">
<h3 className="text-lg font-semibold text-gray-900 dark:text-white">
{t('automations.editConfig', 'Edit Automation Configuration')}
</h3>
<button
onClick={() => {
setShowEditModal(false);
setSelectedAutomation(null);
setConfigValues({});
}}
className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
>
<X className="h-5 w-5" />
</button>
</div>
{/* Modal Body */}
<div className="p-6 overflow-y-auto flex-1">
<div className="mb-4">
<h4 className="text-sm font-medium text-gray-900 dark:text-white mb-2">
{selectedAutomation.templateName}
</h4>
<p className="text-sm text-gray-500 dark:text-gray-400">
{selectedAutomation.templateDescription}
</p>
</div>
{/* Config Fields */}
{selectedAutomation.templateVariables && Object.keys(selectedAutomation.templateVariables).length > 0 ? (
<div className="space-y-4">
{Object.entries(selectedAutomation.templateVariables).map(([key, variable]: [string, any]) => (
<div key={key}>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
{variable.description || key}
{variable.required && <span className="text-red-500 ml-1">*</span>}
</label>
{variable.type === 'email_template' ? (
<EmailTemplateSelector
value={configValues[key] || variable.default}
onChange={(templateId) => setConfigValues({ ...configValues, [key]: templateId })}
required={variable.required}
/>
) : variable.type === 'textarea' ? (
<textarea
value={configValues[key] !== undefined ? configValues[key] : (variable.default ? unescapeString(variable.default) : '')}
onChange={(e) => setConfigValues({ ...configValues, [key]: e.target.value })}
rows={6}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-brand-500 resize-none font-mono text-sm"
placeholder={variable.default ? unescapeString(variable.default) : ''}
/>
) : (
<input
type="text"
value={configValues[key] || variable.default || ''}
onChange={(e) => setConfigValues({ ...configValues, [key]: e.target.value })}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
placeholder={variable.default || ''}
/>
)}
{variable.help_text && (
<p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
{variable.help_text}
</p>
)}
</div>
))}
</div>
) : (
<div className="text-center py-8 text-gray-500 dark:text-gray-400">
{t('automations.noConfigOptions', 'This automation has no configuration options')}
</div>
)}
</div>
{/* Modal Footer */}
<div className="px-6 py-4 bg-gray-50 dark:bg-gray-900/50 border-t border-gray-200 dark:border-gray-700 flex justify-end gap-3">
<button
onClick={() => {
setShowEditModal(false);
setSelectedAutomation(null);
setConfigValues({});
}}
className="px-4 py-2 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors font-medium"
>
{t('common.cancel', 'Cancel')}
</button>
<button
onClick={submitConfigEdit}
disabled={editConfigMutation.isPending}
className="flex items-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors font-medium"
>
{editConfigMutation.isPending ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
{t('automations.saving', 'Saving...')}
</>
) : (
<>
<CheckCircle className="h-4 w-4" />
{t('common.save', 'Save')}
</>
)}
</button>
</div>
</div>
</div>
)}
</div>
</LockedSection>
);
};
export default MyAutomations;

View File

@@ -2,16 +2,17 @@
* Owner Scheduler - Horizontal timeline view for owner/manager/staff users
*/
import React, { useState, useRef, useEffect, useMemo } from 'react';
import { Appointment, AppointmentStatus, User, Business, Resource } from '../types';
import { Clock, Calendar as CalendarIcon, Filter, GripVertical, CheckCircle2, Trash2, X, User as UserIcon, Mail, Phone, Undo, Redo, ChevronLeft, ChevronRight, ChevronDown, Check, AlertTriangle } from 'lucide-react';
import { useAppointments, useUpdateAppointment, useDeleteAppointment } from '../hooks/useAppointments';
import React, { useState, useRef, useEffect, useMemo, useCallback } from 'react';
import { Appointment, AppointmentStatus, User, Business, Resource, ParticipantInput } from '../types';
import { Clock, Calendar as CalendarIcon, Filter, GripVertical, CheckCircle2, Trash2, Undo, Redo, ChevronLeft, ChevronRight, ChevronDown, Check, AlertTriangle } from 'lucide-react';
import { useAppointments, useUpdateAppointment, useDeleteAppointment, useCreateAppointment } from '../hooks/useAppointments';
import { EditAppointmentModal } from '../components/EditAppointmentModal';
import { CreateAppointmentModal } from '../components/CreateAppointmentModal';
import { useResources } from '../hooks/useResources';
import { useServices } from '../hooks/useServices';
import { useAppointmentWebSocket } from '../hooks/useAppointmentWebSocket';
import { useBlockedDates } from '../hooks/useTimeBlocks';
import Portal from '../components/Portal';
import EventAutomations from '../components/EventAutomations';
import TimeBlockCalendarOverlay from '../components/time-blocks/TimeBlockCalendarOverlay';
import { getOverQuotaResourceIds } from '../utils/quotaUtils';
import { formatLocalDate } from '../utils/dateUtils';
@@ -85,6 +86,10 @@ const OwnerScheduler: React.FC<OwnerSchedulerProps> = ({ user, business }) => {
const { data: services = [] } = useServices();
const updateMutation = useUpdateAppointment();
const deleteMutation = useDeleteAppointment();
const createMutation = useCreateAppointment();
// State for create appointment modal
const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
// Fetch blocked dates for the calendar overlay
const blockedDatesParams = useMemo(() => ({
@@ -116,12 +121,6 @@ const OwnerScheduler: React.FC<OwnerSchedulerProps> = ({ user, business }) => {
const monthOverlayDelayRef = useRef<NodeJS.Timeout | null>(null);
const pendingMonthDropRef = useRef<{ date: Date; rect: DOMRect } | null>(null);
// State for editing appointments
const [editDateTime, setEditDateTime] = useState('');
const [editResource, setEditResource] = useState('');
const [editDuration, setEditDuration] = useState(0);
const [editStatus, setEditStatus] = useState<AppointmentStatus>('SCHEDULED');
// Filter state
const [showFilterMenu, setShowFilterMenu] = useState(false);
const [showStatusLegend, setShowStatusLegend] = useState(false);
@@ -133,23 +132,6 @@ const OwnerScheduler: React.FC<OwnerSchedulerProps> = ({ user, business }) => {
const filterMenuRef = useRef<HTMLDivElement>(null);
const statusLegendRef = useRef<HTMLDivElement>(null);
// Update edit state when selected appointment changes
useEffect(() => {
if (selectedAppointment) {
// Format date in local time for datetime-local input (toISOString uses UTC)
const date = new Date(selectedAppointment.startTime);
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
setEditDateTime(`${year}-${month}-${day}T${hours}:${minutes}`);
setEditResource(selectedAppointment.resourceId || '');
setEditDuration(selectedAppointment.durationMinutes);
setEditStatus(selectedAppointment.status);
}
}, [selectedAppointment]);
// Undo/Redo history
type HistoryAction = {
type: 'move' | 'resize';
@@ -893,29 +875,54 @@ const OwnerScheduler: React.FC<OwnerSchedulerProps> = ({ user, business }) => {
}
};
const handleSaveAppointment = () => {
// Handle saving appointment updates from EditAppointmentModal
const handleSaveAppointment = useCallback((updates: {
startTime?: Date;
resourceId?: string | null;
durationMinutes?: number;
status?: AppointmentStatus;
notes?: string;
participantsInput?: ParticipantInput[];
}) => {
if (!selectedAppointment) return;
// Validate duration is at least 15 minutes
const validDuration = editDuration >= 15 ? editDuration : 15;
const updates: any = {
startTime: new Date(editDateTime),
durationMinutes: validDuration,
status: editStatus,
};
if (editResource) {
updates.resourceId = editResource;
}
updateMutation.mutate({
id: selectedAppointment.id,
updates
updates: {
...updates,
resourceId: updates.resourceId ?? undefined,
}
});
setSelectedAppointment(null);
};
}, [selectedAppointment, updateMutation]);
// Handle creating new appointment from CreateAppointmentModal
const handleCreateAppointment = useCallback((appointmentData: {
serviceId: string;
customerId: string;
startTime: Date;
resourceId?: string | null;
durationMinutes: number;
notes?: string;
participantsInput?: ParticipantInput[];
}) => {
createMutation.mutate({
serviceId: appointmentData.serviceId,
customerId: appointmentData.customerId,
customerName: '', // Will be set by backend
startTime: appointmentData.startTime,
resourceId: appointmentData.resourceId ?? null,
durationMinutes: appointmentData.durationMinutes,
status: 'SCHEDULED',
notes: appointmentData.notes || '',
participantsInput: appointmentData.participantsInput,
}, {
onSuccess: () => {
setIsCreateModalOpen(false);
}
});
}, [createMutation]);
const handleTimelineDragOver = (e: React.DragEvent) => {
if (resizeState) return;
@@ -1195,7 +1202,10 @@ const OwnerScheduler: React.FC<OwnerSchedulerProps> = ({ user, business }) => {
</div>
</div>
<div className="flex items-center gap-3">
<button className="flex items-center gap-2 px-4 py-2 text-sm font-medium text-white bg-brand-500 rounded-lg hover:bg-brand-600 transition-colors shadow-sm">
<button
onClick={() => setIsCreateModalOpen(true)}
className="flex items-center gap-2 px-4 py-2 text-sm font-medium text-white bg-brand-500 rounded-lg hover:bg-brand-600 transition-colors shadow-sm"
>
+ New Appointment
</button>
{/* Filter Dropdown */}
@@ -2003,157 +2013,28 @@ const OwnerScheduler: React.FC<OwnerSchedulerProps> = ({ user, business }) => {
</div>
)}
{/* Appointment Detail/Edit Modal */}
{/* Edit Appointment Modal */}
{selectedAppointment && (
<Portal>
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm" onClick={() => setSelectedAppointment(null)}>
<div className="w-full max-w-lg bg-white dark:bg-gray-800 rounded-xl shadow-xl border border-gray-200 dark:border-gray-700 overflow-hidden" onClick={e => e.stopPropagation()}>
<div className="flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-gray-700 bg-gradient-to-r from-brand-50 to-brand-100 dark:from-brand-900/30 dark:to-brand-800/30">
<h3 className="text-lg font-semibold text-gray-900 dark:text-white">
{!selectedAppointment.resourceId ? 'Schedule Appointment' : 'Edit Appointment'}
</h3>
<button onClick={() => setSelectedAppointment(null)} className="p-1 text-gray-400 hover:bg-white/50 dark:hover:bg-gray-700/50 rounded-full transition-colors">
<X size={20} />
</button>
</div>
<div className="p-6 space-y-4">
{/* Customer Info */}
<div className="flex items-start gap-3 p-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg">
<div className="flex-shrink-0 w-10 h-10 rounded-full bg-brand-100 dark:bg-brand-900/50 flex items-center justify-center">
<UserIcon size={20} className="text-brand-600 dark:text-brand-400" />
</div>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium text-gray-500 dark:text-gray-400">Customer</p>
<p className="text-lg font-semibold text-gray-900 dark:text-white">{selectedAppointment.customerName}</p>
{selectedAppointment.customerEmail && (
<div className="flex items-center gap-2 mt-1 text-sm text-gray-600 dark:text-gray-300">
<Mail size={14} />
<span>{selectedAppointment.customerEmail}</span>
</div>
)}
{selectedAppointment.customerPhone && (
<div className="flex items-center gap-2 mt-1 text-sm text-gray-600 dark:text-gray-300">
<Phone size={14} />
<span>{selectedAppointment.customerPhone}</span>
</div>
)}
</div>
</div>
<EditAppointmentModal
appointment={selectedAppointment}
resources={resources as Resource[]}
services={services}
onSave={handleSaveAppointment}
onClose={() => setSelectedAppointment(null)}
isSaving={updateMutation.isPending}
/>
)}
{/* Service & Status */}
<div className="grid grid-cols-2 gap-4">
<div className="p-3 bg-gray-50 dark:bg-gray-700/50 rounded-lg">
<p className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1">Service</p>
<p className="text-sm font-semibold text-gray-900 dark:text-white">{services.find(s => s.id === selectedAppointment.serviceId)?.name}</p>
</div>
<div className="p-3 bg-gray-50 dark:bg-gray-700/50 rounded-lg">
<label className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1 block">Status</label>
<select
value={editStatus}
onChange={(e) => setEditStatus(e.target.value as AppointmentStatus)}
className="w-full px-2 py-1 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded text-sm font-semibold text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-brand-500"
>
<option value="SCHEDULED">Scheduled</option>
<option value="EN_ROUTE">En Route</option>
<option value="IN_PROGRESS">In Progress</option>
<option value="COMPLETED">Completed</option>
<option value="AWAITING_PAYMENT">Awaiting Payment</option>
<option value="CANCELLED">Cancelled</option>
<option value="NO_SHOW">No Show</option>
</select>
</div>
</div>
{/* Editable Fields */}
<div className="space-y-4 p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg border border-blue-200 dark:border-blue-800">
<h4 className="text-sm font-semibold text-gray-900 dark:text-white">Schedule Details</h4>
{/* Date & Time Picker */}
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-2">
Date & Time
</label>
<input
type="datetime-local"
value={editDateTime}
onChange={(e) => setEditDateTime(e.target.value)}
className="w-full px-3 py-2 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg text-sm text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-brand-500"
/>
</div>
{/* Resource Selector */}
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-2">
Assign to Resource {!selectedAppointment.resourceId && <span className="text-red-500">*</span>}
</label>
<select
value={editResource}
onChange={(e) => setEditResource(e.target.value)}
className="w-full px-3 py-2 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg text-sm text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-brand-500"
>
<option value="">Unassigned</option>
{resources.map(resource => (
<option key={resource.id} value={resource.id}>
{resource.name}
</option>
))}
</select>
</div>
{/* Duration Input */}
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-2">
Duration (minutes) {!selectedAppointment.resourceId && <span className="text-red-500">*</span>}
</label>
<input
type="number"
min="15"
step="15"
value={editDuration || 15}
onChange={(e) => {
const value = parseInt(e.target.value);
setEditDuration(value >= 15 ? value : 15);
}}
className="w-full px-3 py-2 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg text-sm text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-brand-500"
/>
</div>
</div>
{/* Notes */}
{selectedAppointment.notes && (
<div className="p-3 bg-gray-50 dark:bg-gray-700/50 rounded-lg">
<p className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1">Notes</p>
<p className="text-sm text-gray-700 dark:text-gray-200">{selectedAppointment.notes}</p>
</div>
)}
{/* Automations - only show for saved appointments */}
{selectedAppointment.id && (
<div className="p-3 bg-purple-50 dark:bg-purple-900/20 rounded-lg border border-purple-200 dark:border-purple-800">
<EventAutomations eventId={selectedAppointment.id} compact />
</div>
)}
{/* Action Buttons */}
<div className="pt-4 flex justify-end gap-3 border-t border-gray-200 dark:border-gray-700">
<button
onClick={() => setSelectedAppointment(null)}
className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-200 bg-gray-100 dark:bg-gray-700 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors"
>
Cancel
</button>
<button
onClick={handleSaveAppointment}
disabled={!selectedAppointment.resourceId && (!editResource || !editDuration || editDuration < 15)}
className="px-4 py-2 text-sm font-medium text-white bg-brand-600 rounded-lg hover:bg-brand-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
>
{!selectedAppointment.resourceId ? 'Schedule Appointment' : 'Save Changes'}
</button>
</div>
</div>
</div>
</div>
</Portal>
{/* Create Appointment Modal */}
{isCreateModalOpen && (
<CreateAppointmentModal
resources={resources as Resource[]}
services={services}
initialDate={viewDate}
onCreate={handleCreateAppointment}
onClose={() => setIsCreateModalOpen(false)}
isCreating={createMutation.isPending}
/>
)}
</div>
);

View File

@@ -1,796 +0,0 @@
import React, { useState, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import axios from '../api/client';
import {
Plus,
Play,
Pause,
Trash2,
Edit,
Clock,
Calendar,
CalendarDays,
RotateCw,
CheckCircle2,
XCircle,
AlertCircle,
Zap,
Power,
} from 'lucide-react';
import toast from 'react-hot-toast';
import CreateTaskModal from '../components/CreateTaskModal';
import EditTaskModal from '../components/EditTaskModal';
import { usePlanFeatures } from '../hooks/usePlanFeatures';
import { LockedSection } from '../components/UpgradePrompt';
// Types
interface ScheduledTask {
id: string;
name: string;
description: string;
automation_name: string;
automation_display_name: string;
schedule_type: 'ONE_TIME' | 'INTERVAL' | 'CRON';
cron_expression?: string;
interval_minutes?: number;
run_at?: string;
next_run_at?: string;
last_run_at?: string;
status: 'ACTIVE' | 'PAUSED' | 'DISABLED';
last_run_status?: string;
automation_config: Record<string, any>;
created_at: string;
updated_at: string;
}
interface AutomationInstallation {
id: string;
template: number;
template_name: string;
template_slug: string;
template_description: string;
category: string;
version: string;
author_name: string;
logo_url?: string;
template_variables: Record<string, any>;
scheduled_task?: number;
scheduled_task_name?: string;
installed_at: string;
config_values: Record<string, any>;
has_update: boolean;
}
interface GlobalEventAutomation {
id: string;
automation_installation: number;
automation_name: string;
automation_description: string;
automation_category: string;
automation_logo_url?: string;
trigger: string;
trigger_display: string;
offset_minutes: number;
timing_description: string;
is_active: boolean;
apply_to_existing: boolean;
execution_order: number;
events_count: number;
created_at: string;
updated_at: string;
}
// Unified task type for display
type UnifiedTask = {
type: 'scheduled';
data: ScheduledTask;
} | {
type: 'event';
data: GlobalEventAutomation;
};
const Tasks: React.FC = () => {
const { t } = useTranslation();
const queryClient = useQueryClient();
const [showCreateModal, setShowCreateModal] = useState(false);
const [editingTask, setEditingTask] = useState<ScheduledTask | null>(null);
const [editingEventAutomation, setEditingEventAutomation] = useState<GlobalEventAutomation | null>(null);
// Check plan permissions - tasks requires both automations AND tasks features
const { canUse, isLoading: permissionsLoading } = usePlanFeatures();
const hasAutomationsFeature = canUse('automations');
const hasTasksFeature = canUse('tasks');
const isLocked = !hasAutomationsFeature || !hasTasksFeature;
// Fetch scheduled tasks - only when user has the feature
const { data: scheduledTasks = [], isLoading: tasksLoading, error: tasksError } = useQuery<ScheduledTask[]>({
queryKey: ['scheduled-tasks'],
queryFn: async () => {
const { data } = await axios.get('/scheduled-tasks/');
return data;
},
// Don't fetch if user doesn't have the required features
enabled: hasAutomationsFeature && hasTasksFeature && !permissionsLoading,
});
// Fetch global event automations - only when user has the feature
const { data: eventAutomations = [], isLoading: automationsLoading, error: automationsError } = useQuery<GlobalEventAutomation[]>({
queryKey: ['global-event-automations'],
queryFn: async () => {
const { data } = await axios.get('/global-event-automations/');
return data;
},
// Don't fetch if user doesn't have the required features
enabled: hasAutomationsFeature && hasTasksFeature && !permissionsLoading,
});
// Check if any error is a 403 (plan restriction)
const is403Error = (tasksError && (tasksError as any)?.response?.status === 403) ||
(automationsError && (automationsError as any)?.response?.status === 403);
const effectivelyLocked = isLocked || is403Error;
// Combine into unified list
const allTasks: UnifiedTask[] = useMemo(() => {
const scheduled: UnifiedTask[] = scheduledTasks.map(t => ({ type: 'scheduled' as const, data: t }));
const events: UnifiedTask[] = eventAutomations.map(e => ({ type: 'event' as const, data: e }));
return [...scheduled, ...events].sort((a, b) => {
const dateA = new Date(a.data.created_at).getTime();
const dateB = new Date(b.data.created_at).getTime();
return dateB - dateA; // Most recent first
});
}, [scheduledTasks, eventAutomations]);
const isLoading = tasksLoading || automationsLoading;
// Delete task
const deleteMutation = useMutation({
mutationFn: async (taskId: string) => {
await axios.delete(`/scheduled-tasks/${taskId}/`);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['scheduled-tasks'] });
toast.success('Task deleted successfully');
},
onError: (error: any) => {
toast.error(error.response?.data?.detail || 'Failed to delete task');
},
});
// Toggle task active status
const toggleActiveMutation = useMutation({
mutationFn: async ({ taskId, status }: { taskId: string; status: 'ACTIVE' | 'PAUSED' }) => {
await axios.patch(`/scheduled-tasks/${taskId}/`, { status });
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['scheduled-tasks'] });
toast.success('Task updated successfully');
},
onError: (error: any) => {
toast.error(error.response?.data?.detail || 'Failed to update task');
},
});
// Trigger task manually
const triggerMutation = useMutation({
mutationFn: async (taskId: string) => {
await axios.post(`/scheduled-tasks/${taskId}/trigger/`);
},
onSuccess: () => {
toast.success('Task triggered successfully');
},
onError: (error: any) => {
toast.error(error.response?.data?.detail || 'Failed to trigger task');
},
});
// Delete event automation
const deleteEventAutomationMutation = useMutation({
mutationFn: async (automationId: string) => {
await axios.delete(`/global-event-automations/${automationId}/`);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['global-event-automations'] });
toast.success('Event automation deleted');
},
onError: (error: any) => {
toast.error(error.response?.data?.detail || 'Failed to delete automation');
},
});
// Toggle event automation active status
const toggleEventAutomationMutation = useMutation({
mutationFn: async (automationId: string) => {
await axios.post(`/global-event-automations/${automationId}/toggle/`);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['global-event-automations'] });
toast.success('Automation updated');
},
onError: (error: any) => {
toast.error(error.response?.data?.detail || 'Failed to update automation');
},
});
// Update event automation
const updateEventAutomationMutation = useMutation({
mutationFn: async ({ id, data }: { id: string; data: Partial<GlobalEventAutomation> }) => {
await axios.patch(`/global-event-automations/${id}/`, data);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['global-event-automations'] });
toast.success('Automation updated');
setEditingEventAutomation(null);
},
onError: (error: any) => {
toast.error(error.response?.data?.detail || 'Failed to update automation');
},
});
const getScheduleDisplay = (task: ScheduledTask): string => {
if (task.schedule_type === 'ONE_TIME') {
return `Once on ${new Date(task.run_at!).toLocaleString()}`;
} else if (task.schedule_type === 'INTERVAL') {
const hours = Math.floor(task.interval_minutes! / 60);
const mins = task.interval_minutes! % 60;
if (hours > 0 && mins > 0) {
return `Every ${hours}h ${mins}m`;
} else if (hours > 0) {
return `Every ${hours} hour${hours > 1 ? 's' : ''}`;
} else {
return `Every ${mins} minute${mins > 1 ? 's' : ''}`;
}
} else {
return task.cron_expression || 'Custom schedule';
}
};
const getScheduleIcon = (task: ScheduledTask) => {
if (task.schedule_type === 'ONE_TIME') return Calendar;
if (task.schedule_type === 'INTERVAL') return RotateCw;
return Clock;
};
const getStatusColor = (task: ScheduledTask): string => {
if (task.status === 'PAUSED' || task.status === 'DISABLED') return 'text-gray-400 dark:text-gray-500';
if (task.last_run_at) return 'text-green-600 dark:text-green-400';
return 'text-blue-600 dark:text-blue-400';
};
const getStatusIcon = (task: ScheduledTask) => {
if (task.status === 'PAUSED' || task.status === 'DISABLED') return Pause;
if (task.last_run_at) return CheckCircle2;
return AlertCircle;
};
if (isLoading || permissionsLoading) {
return (
<div className="flex items-center justify-center h-96">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
</div>
);
}
return (
<LockedSection feature="tasks" isLocked={effectivelyLocked} variant="overlay">
<div className="p-6 max-w-7xl mx-auto">
{/* Header */}
<div className="flex items-center justify-between mb-6">
<div>
<h1 className="text-3xl font-bold text-gray-900 dark:text-white">
{t('Tasks')}
</h1>
<p className="text-gray-600 dark:text-gray-400 mt-1">
Schedule and manage automated executions
</p>
</div>
<button
onClick={() => setShowCreateModal(true)}
className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
>
<Plus className="w-5 h-5" />
New Task
</button>
</div>
{/* Stats */}
<div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
<div className="bg-white dark:bg-gray-800 rounded-lg p-4 border border-gray-200 dark:border-gray-700">
<div className="flex items-center gap-3">
<div className="p-2 bg-blue-100 dark:bg-blue-900/30 rounded-lg">
<Zap className="w-5 h-5 text-blue-600 dark:text-blue-400" />
</div>
<div>
<p className="text-sm text-gray-600 dark:text-gray-400">Total Tasks</p>
<p className="text-2xl font-bold text-gray-900 dark:text-white">{allTasks.length}</p>
</div>
</div>
</div>
<div className="bg-white dark:bg-gray-800 rounded-lg p-4 border border-gray-200 dark:border-gray-700">
<div className="flex items-center gap-3">
<div className="p-2 bg-green-100 dark:bg-green-900/30 rounded-lg">
<CheckCircle2 className="w-5 h-5 text-green-600 dark:text-green-400" />
</div>
<div>
<p className="text-sm text-gray-600 dark:text-gray-400">Active</p>
<p className="text-2xl font-bold text-gray-900 dark:text-white">
{scheduledTasks.filter(t => t.status === 'ACTIVE').length + eventAutomations.filter(e => e.is_active).length}
</p>
</div>
</div>
</div>
<div className="bg-white dark:bg-gray-800 rounded-lg p-4 border border-gray-200 dark:border-gray-700">
<div className="flex items-center gap-3">
<div className="p-2 bg-purple-100 dark:bg-purple-900/30 rounded-lg">
<CalendarDays className="w-5 h-5 text-purple-600 dark:text-purple-400" />
</div>
<div>
<p className="text-sm text-gray-600 dark:text-gray-400">Event Automations</p>
<p className="text-2xl font-bold text-gray-900 dark:text-white">
{eventAutomations.length}
</p>
</div>
</div>
</div>
<div className="bg-white dark:bg-gray-800 rounded-lg p-4 border border-gray-200 dark:border-gray-700">
<div className="flex items-center gap-3">
<div className="p-2 bg-blue-100 dark:bg-blue-900/30 rounded-lg">
<RotateCw className="w-5 h-5 text-blue-600 dark:text-blue-400" />
</div>
<div>
<p className="text-sm text-gray-600 dark:text-gray-400">Scheduled</p>
<p className="text-2xl font-bold text-gray-900 dark:text-white">
{scheduledTasks.length}
</p>
</div>
</div>
</div>
</div>
{/* Tasks List */}
{allTasks.length === 0 ? (
<div className="text-center py-16 bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700">
<Zap className="w-16 h-16 text-gray-400 mx-auto mb-4" />
<h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-2">
No tasks yet
</h3>
<p className="text-gray-600 dark:text-gray-400 mb-4">
Create your first automated task to get started
</p>
<button
onClick={() => setShowCreateModal(true)}
className="inline-flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
>
<Plus className="w-5 h-5" />
Create Task
</button>
</div>
) : (
<div className="space-y-4">
{allTasks.map((unifiedTask) => {
if (unifiedTask.type === 'scheduled') {
const task = unifiedTask.data;
const ScheduleIcon = getScheduleIcon(task);
const StatusIcon = getStatusIcon(task);
return (
<div
key={`scheduled-${task.id}`}
className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-6 hover:shadow-md transition-shadow"
>
<div className="flex items-start justify-between">
<div className="flex-1">
<div className="flex items-center gap-3 mb-2">
<span className="px-2 py-0.5 text-xs font-medium bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 rounded">
Scheduled
</span>
<h3 className="text-lg font-semibold text-gray-900 dark:text-white">
{task.name}
</h3>
<StatusIcon className={`w-5 h-5 ${getStatusColor(task)}`} />
</div>
{task.description && (
<p className="text-gray-600 dark:text-gray-400 text-sm mb-3">
{task.description}
</p>
)}
<div className="flex flex-wrap items-center gap-4 text-sm">
<div className="flex items-center gap-2 text-gray-600 dark:text-gray-400">
<Zap className="w-4 h-4" />
<span>{task.automation_display_name}</span>
</div>
<div className="flex items-center gap-2 text-gray-600 dark:text-gray-400">
<ScheduleIcon className="w-4 h-4" />
<span>{getScheduleDisplay(task)}</span>
</div>
{task.next_run_at && task.status === 'ACTIVE' && (
<div className="flex items-center gap-2 text-gray-600 dark:text-gray-400">
<Clock className="w-4 h-4" />
<span>Next: {new Date(task.next_run_at).toLocaleString()}</span>
</div>
)}
{task.last_run_at && (
<div className="flex items-center gap-2 text-gray-600 dark:text-gray-400">
<CheckCircle2 className="w-4 h-4" />
<span>Last: {new Date(task.last_run_at).toLocaleString()}</span>
</div>
)}
</div>
</div>
{/* Actions */}
<div className="flex items-center gap-2 ml-4">
<button
onClick={() => triggerMutation.mutate(task.id)}
className="p-2 text-blue-600 dark:text-blue-400 hover:bg-blue-50 dark:hover:bg-blue-900/20 rounded-lg transition-colors"
title="Run now"
>
<Play className="w-5 h-5" />
</button>
<button
onClick={() => toggleActiveMutation.mutate({
taskId: task.id,
status: task.status === 'ACTIVE' ? 'PAUSED' : 'ACTIVE'
})}
className={`p-2 rounded-lg transition-colors ${
task.status === 'ACTIVE'
? 'text-orange-600 dark:text-orange-400 hover:bg-orange-50 dark:hover:bg-orange-900/20'
: 'text-green-600 dark:text-green-400 hover:bg-green-50 dark:hover:bg-green-900/20'
}`}
title={task.status === 'ACTIVE' ? 'Pause' : 'Resume'}
>
{task.status === 'ACTIVE' ? <Pause className="w-5 h-5" /> : <Play className="w-5 h-5" />}
</button>
<button
onClick={() => setEditingTask(task)}
className="p-2 text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
title="Edit"
>
<Edit className="w-5 h-5" />
</button>
<button
onClick={() => {
if (confirm('Are you sure you want to delete this task?')) {
deleteMutation.mutate(task.id);
}
}}
className="p-2 text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors"
title="Delete"
>
<Trash2 className="w-5 h-5" />
</button>
</div>
</div>
</div>
);
} else {
// Event automation
const automation = unifiedTask.data;
return (
<div
key={`event-${automation.id}`}
className={`bg-white dark:bg-gray-800 rounded-lg border p-6 hover:shadow-md transition-shadow ${
automation.is_active
? 'border-gray-200 dark:border-gray-700'
: 'border-gray-200 dark:border-gray-700 opacity-60'
}`}
>
<div className="flex items-start justify-between">
<div className="flex-1">
<div className="flex items-center gap-3 mb-2">
<span className="px-2 py-0.5 text-xs font-medium bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300 rounded">
Event Automation
</span>
<h3 className="text-lg font-semibold text-gray-900 dark:text-white">
{automation.automation_name}
</h3>
{automation.is_active ? (
<CheckCircle2 className="w-5 h-5 text-green-600 dark:text-green-400" />
) : (
<Pause className="w-5 h-5 text-gray-400" />
)}
</div>
{automation.automation_description && (
<p className="text-gray-600 dark:text-gray-400 text-sm mb-3">
{automation.automation_description}
</p>
)}
<div className="flex flex-wrap items-center gap-4 text-sm">
<div className="flex items-center gap-2 text-gray-600 dark:text-gray-400">
<CalendarDays className="w-4 h-4" />
<span>{automation.timing_description}</span>
</div>
<div className="flex items-center gap-2 text-gray-600 dark:text-gray-400">
<Zap className="w-4 h-4" />
<span>{automation.events_count} events</span>
</div>
<div className="flex items-center gap-2 text-gray-600 dark:text-gray-400">
<span className={`px-2 py-0.5 text-xs rounded ${
automation.apply_to_existing
? 'bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-300'
: 'bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400'
}`}>
{automation.apply_to_existing ? 'All events' : 'Future only'}
</span>
</div>
</div>
</div>
{/* Actions */}
<div className="flex items-center gap-2 ml-4">
<button
onClick={() => toggleEventAutomationMutation.mutate(automation.id)}
className={`p-2 rounded-lg transition-colors ${
automation.is_active
? 'text-orange-600 dark:text-orange-400 hover:bg-orange-50 dark:hover:bg-orange-900/20'
: 'text-green-600 dark:text-green-400 hover:bg-green-50 dark:hover:bg-green-900/20'
}`}
title={automation.is_active ? 'Disable' : 'Enable'}
>
<Power className="w-5 h-5" />
</button>
<button
onClick={() => setEditingEventAutomation(automation)}
className="p-2 text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
title="Edit"
>
<Edit className="w-5 h-5" />
</button>
<button
onClick={() => {
if (confirm('Are you sure you want to delete this automation? It will be removed from all events.')) {
deleteEventAutomationMutation.mutate(automation.id);
}
}}
className="p-2 text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors"
title="Delete"
>
<Trash2 className="w-5 h-5" />
</button>
</div>
</div>
</div>
);
}
})}
</div>
)}
{/* Create Task Modal */}
<CreateTaskModal
isOpen={showCreateModal}
onClose={() => setShowCreateModal(false)}
onSuccess={() => {
queryClient.invalidateQueries({ queryKey: ['scheduled-tasks'] });
queryClient.invalidateQueries({ queryKey: ['global-event-automations'] });
}}
/>
{/* Edit Task Modal */}
<EditTaskModal
task={editingTask}
isOpen={!!editingTask}
onClose={() => setEditingTask(null)}
onSuccess={() => {
queryClient.invalidateQueries({ queryKey: ['scheduled-tasks'] });
toast.success('Task updated successfully');
}}
/>
{/* Edit Event Automation Modal */}
{editingEventAutomation && (
<EditEventAutomationModal
automation={editingEventAutomation}
isOpen={!!editingEventAutomation}
onClose={() => setEditingEventAutomation(null)}
onSave={(data) => updateEventAutomationMutation.mutate({ id: editingEventAutomation.id, data })}
isLoading={updateEventAutomationMutation.isPending}
/>
)}
</div>
</LockedSection>
);
};
// Inline Edit Event Automation Modal component
interface EditEventAutomationModalProps {
automation: GlobalEventAutomation;
isOpen: boolean;
onClose: () => void;
onSave: (data: Partial<GlobalEventAutomation>) => void;
isLoading: boolean;
}
const TRIGGER_OPTIONS = [
{ value: 'before_start', label: 'Before Start' },
{ value: 'at_start', label: 'At Start' },
{ value: 'after_start', label: 'After Start' },
{ value: 'after_end', label: 'After End' },
{ value: 'on_complete', label: 'When Completed' },
{ value: 'on_cancel', label: 'When Canceled' },
];
const OFFSET_PRESETS = [
{ value: 0, label: 'Immediately' },
{ value: 5, label: '5 min' },
{ value: 10, label: '10 min' },
{ value: 15, label: '15 min' },
{ value: 30, label: '30 min' },
{ value: 60, label: '1 hour' },
];
const EditEventAutomationModal: React.FC<EditEventAutomationModalProps> = ({
automation,
isOpen,
onClose,
onSave,
isLoading,
}) => {
const [trigger, setTrigger] = useState(automation.trigger);
const [offsetMinutes, setOffsetMinutes] = useState(automation.offset_minutes);
const showOffset = !['on_complete', 'on_cancel'].includes(trigger);
const getTimingDescription = () => {
if (trigger === 'on_complete') return 'When event is completed';
if (trigger === 'on_cancel') return 'When event is canceled';
if (offsetMinutes === 0) {
if (trigger === 'before_start' || trigger === 'at_start' || trigger === 'after_start') return 'At event start';
if (trigger === 'after_end') return 'At event end';
}
const offsetLabel = OFFSET_PRESETS.find(o => o.value === offsetMinutes)?.label || `${offsetMinutes} min`;
if (trigger === 'before_start') return `${offsetLabel} before event starts`;
if (trigger === 'at_start' || trigger === 'after_start') return `${offsetLabel} after event starts`;
if (trigger === 'after_end') return `${offsetLabel} after event ends`;
return 'Unknown timing';
};
const handleSave = () => {
onSave({
trigger,
offset_minutes: offsetMinutes,
});
};
if (!isOpen) return null;
return (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50">
<div className="bg-white dark:bg-gray-800 rounded-lg max-w-lg w-full">
{/* Header */}
<div className="flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700">
<h2 className="text-xl font-bold text-gray-900 dark:text-white">
Edit Event Automation
</h2>
<button
onClick={onClose}
className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700"
>
<XCircle className="w-5 h-5" />
</button>
</div>
{/* Content */}
<div className="p-6 space-y-6">
{/* Automation info */}
<div className="p-4 bg-purple-50 dark:bg-purple-900/20 border border-purple-200 dark:border-purple-800 rounded-lg">
<div className="flex items-center gap-3">
<Zap className="w-5 h-5 text-purple-600 dark:text-purple-400" />
<div>
<p className="text-sm text-purple-800 dark:text-purple-200 font-medium">
Automation
</p>
<p className="text-purple-900 dark:text-purple-100">
{automation.automation_name}
</p>
</div>
</div>
</div>
{/* When to run */}
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
When should it run?
</label>
<div className="grid grid-cols-2 gap-2">
{TRIGGER_OPTIONS.map((opt) => (
<button
key={opt.value}
type="button"
onClick={() => {
setTrigger(opt.value);
if (['on_complete', 'on_cancel'].includes(opt.value)) {
setOffsetMinutes(0);
}
}}
className={`px-3 py-2 text-sm rounded-lg border transition-colors ${
trigger === opt.value
? 'bg-purple-600 text-white border-purple-600'
: 'bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 border-gray-300 dark:border-gray-600 hover:border-purple-400'
}`}
>
{opt.label}
</button>
))}
</div>
</div>
{/* Offset selection */}
{showOffset && (
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
How long {trigger === 'before_start' ? 'before' : 'after'}?
</label>
<div className="flex flex-wrap gap-2">
{OFFSET_PRESETS.map((preset) => (
<button
key={preset.value}
type="button"
onClick={() => setOffsetMinutes(preset.value)}
className={`px-3 py-2 text-sm rounded-lg border transition-colors ${
offsetMinutes === preset.value
? 'bg-purple-600 text-white border-purple-600'
: 'bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 border-gray-300 dark:border-gray-600 hover:border-purple-400'
}`}
>
{preset.label}
</button>
))}
</div>
</div>
)}
{/* Preview */}
<div className="p-3 bg-purple-100 dark:bg-purple-900/30 border border-purple-300 dark:border-purple-700 rounded-lg">
<div className="flex items-center gap-2">
<CalendarDays className="w-4 h-4 text-purple-600 dark:text-purple-400" />
<span className="text-sm text-purple-800 dark:text-purple-200">
<strong>Runs:</strong> {getTimingDescription()}
</span>
</div>
</div>
</div>
{/* Footer */}
<div className="flex items-center justify-end gap-3 px-6 py-4 border-t border-gray-200 dark:border-gray-700">
<button
onClick={onClose}
className="px-4 py-2 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
>
Cancel
</button>
<button
onClick={handleSave}
disabled={isLoading}
className="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors disabled:opacity-50"
>
{isLoading ? 'Saving...' : 'Save Changes'}
</button>
</div>
</div>
</div>
);
};
export default Tasks;

View File

@@ -228,6 +228,36 @@ export type AppointmentStatus =
// Legacy aliases for frontend compatibility
| 'PENDING' | 'CONFIRMED' | 'CANCELLED' | 'NO_SHOW';
// Participant role types
export type ParticipantRole = 'RESOURCE' | 'STAFF' | 'CUSTOMER' | 'OBSERVER';
// Participant representing an attendee of an appointment
export interface Participant {
id: string;
role: ParticipantRole;
// For linked participants (users/resources in the system)
userId?: string;
resourceId?: string;
displayName?: string;
// For external email participants
externalEmail?: string;
externalName?: string;
// Computed
isExternal?: boolean;
// Calendar invitation tracking
calendarInviteSent?: boolean;
calendarInviteSentAt?: string;
}
// Input type for creating/updating participants
export interface ParticipantInput {
role: ParticipantRole;
userId?: number;
resourceId?: number;
externalEmail?: string;
externalName?: string;
}
export interface Appointment {
id: string;
resourceId: string | null; // null if unassigned
@@ -240,6 +270,8 @@ export interface Appointment {
notes?: string;
// Location field
location?: number | null; // FK to Location
// Participants (new field)
participants?: Participant[];
}
export interface Blocker {