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

@@ -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>
)}