315 lines
13 KiB
TypeScript
315 lines
13 KiB
TypeScript
'use client';
|
|
|
|
import { useEffect, useState, type ReactNode } from 'react';
|
|
import { ChevronLeft, ChevronRight, Plus, RefreshCw, Trash2 } from 'lucide-react';
|
|
import { toast } from 'sonner';
|
|
import { crmTaskCalendarService, CrmCalendarEvent } from '@/services/api/crmTaskCalendarService';
|
|
import { systemConfigService, CrmLocation } from '@/services/api/systemConfigService';
|
|
import { CustomSelect } from '@/components/ui/CustomSelect';
|
|
import { SlideOver } from '@/components/ui/SlideOver';
|
|
|
|
const shell =
|
|
'crm-radius-section border border-border bg-card shadow-[0_1px_3px_rgba(16,24,40,0.06)] min-w-0';
|
|
const field =
|
|
'w-full h-9 px-3 bg-card border border-border crm-radius-control text-[13px] text-foreground focus:outline-none focus:border-primary';
|
|
const primaryButton =
|
|
'inline-flex items-center justify-center gap-2 h-9 px-4 crm-radius-control bg-primary hover:bg-primary/90 text-white text-[13px] font-semibold cursor-pointer disabled:opacity-50';
|
|
const secondaryButton =
|
|
'inline-flex items-center justify-center gap-2 h-9 px-3 crm-radius-control border border-border bg-card text-foreground text-[13px] font-medium hover:bg-muted cursor-pointer disabled:opacity-50';
|
|
|
|
const WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
|
|
|
|
export default function CrmCalendarPage() {
|
|
const [events, setEvents] = useState<CrmCalendarEvent[]>([]);
|
|
const [locations, setLocations] = useState<CrmLocation[]>([]);
|
|
const [loading, setLoading] = useState(true);
|
|
|
|
const [currentDate, setCurrentDate] = useState(new Date());
|
|
|
|
const [isModalOpen, setIsModalOpen] = useState(false);
|
|
const [title, setTitle] = useState('');
|
|
const [description, setDescription] = useState('');
|
|
const [locationId, setLocationId] = useState('');
|
|
const [startTime, setStartTime] = useState('');
|
|
const [endTime, setEndTime] = useState('');
|
|
const [isAllDay, setIsAllDay] = useState(false);
|
|
const [sourceType, setSourceType] = useState('MANUAL');
|
|
const [isSubmitting, setIsSubmitting] = useState(false);
|
|
|
|
useEffect(() => {
|
|
loadData();
|
|
}, []);
|
|
|
|
const loadData = async () => {
|
|
try {
|
|
setLoading(true);
|
|
const [evtData, locData] = await Promise.all([
|
|
crmTaskCalendarService.getCalendarEvents(),
|
|
systemConfigService.getLocations(),
|
|
]);
|
|
setEvents(Array.isArray(evtData) ? evtData : []);
|
|
setLocations(Array.isArray(locData) ? locData : []);
|
|
} catch {
|
|
toast.error('Failed to load CRM calendar events');
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
const handleCreateEvent = async (e: React.FormEvent) => {
|
|
e.preventDefault();
|
|
if (!title.trim() || !startTime || !endTime) {
|
|
toast.error('Title, start time, and end time are required');
|
|
return;
|
|
}
|
|
|
|
try {
|
|
setIsSubmitting(true);
|
|
await crmTaskCalendarService.createCalendarEvent({
|
|
title: title.trim(),
|
|
description: description || undefined,
|
|
location_id: locationId || undefined,
|
|
start_time: new Date(startTime).toISOString(),
|
|
end_time: new Date(endTime).toISOString(),
|
|
is_all_day: isAllDay,
|
|
source_type: sourceType,
|
|
status: 'SCHEDULED',
|
|
});
|
|
toast.success('Calendar event scheduled!');
|
|
setIsModalOpen(false);
|
|
setTitle('');
|
|
setDescription('');
|
|
setLocationId('');
|
|
setStartTime('');
|
|
setEndTime('');
|
|
setIsAllDay(false);
|
|
loadData();
|
|
} catch (err: any) {
|
|
toast.error(err?.message || 'Failed to schedule calendar event');
|
|
} finally {
|
|
setIsSubmitting(false);
|
|
}
|
|
};
|
|
|
|
const handleDeleteEvent = async (eventId: string) => {
|
|
if (!confirm('Are you sure you want to delete this event?')) return;
|
|
try {
|
|
await crmTaskCalendarService.deleteCalendarEvent(eventId);
|
|
toast.success('Calendar event removed');
|
|
loadData();
|
|
} catch {
|
|
toast.error('Failed to delete event');
|
|
}
|
|
};
|
|
|
|
const handlePrevMonth = () => {
|
|
setCurrentDate(new Date(currentDate.getFullYear(), currentDate.getMonth() - 1, 1));
|
|
};
|
|
|
|
const handleNextMonth = () => {
|
|
setCurrentDate(new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 1));
|
|
};
|
|
|
|
const year = currentDate.getFullYear();
|
|
const month = currentDate.getMonth();
|
|
const monthName = currentDate.toLocaleString('default', { month: 'long' });
|
|
|
|
const firstDayOfMonth = new Date(year, month, 1).getDay();
|
|
const daysInMonth = new Date(year, month + 1, 0).getDate();
|
|
|
|
const daysArray = Array.from({ length: daysInMonth }, (_, i) => i + 1);
|
|
|
|
return (
|
|
<div className="flex flex-col gap-5 min-w-0">
|
|
<div className="flex flex-wrap items-center justify-between gap-3">
|
|
<div className="flex items-center gap-2 min-w-0">
|
|
<h1 className="text-lg font-semibold text-foreground">Calendar</h1>
|
|
<span className="inline-flex items-center justify-center min-w-5 h-5 px-1.5 crm-radius-toggle bg-primary/10 text-primary text-[11px] font-semibold">
|
|
{events.length}
|
|
</span>
|
|
</div>
|
|
<div className="flex items-center gap-2">
|
|
<button
|
|
type="button"
|
|
onClick={() => loadData()}
|
|
className="w-9 h-9 crm-radius-control border border-border bg-card text-muted-foreground hover:text-foreground hover:bg-muted flex items-center justify-center cursor-pointer"
|
|
title="Reload"
|
|
>
|
|
<RefreshCw className={`w-3.5 h-3.5 ${loading ? 'animate-spin' : ''}`} />
|
|
</button>
|
|
<button type="button" onClick={() => setIsModalOpen(true)} className={primaryButton}>
|
|
<Plus className="w-3.5 h-3.5" />
|
|
New event
|
|
</button>
|
|
</div>
|
|
</div>
|
|
|
|
<div className={shell}>
|
|
<div className="flex flex-wrap items-center justify-between gap-3 px-4 py-3 border-b border-border">
|
|
<h2 className="text-[15px] font-semibold text-foreground">
|
|
{monthName} {year}
|
|
</h2>
|
|
<div className="flex items-center gap-2">
|
|
<button
|
|
type="button"
|
|
onClick={handlePrevMonth}
|
|
className="w-9 h-9 crm-radius-control border border-border bg-card text-foreground hover:bg-muted flex items-center justify-center cursor-pointer"
|
|
aria-label="Previous month"
|
|
>
|
|
<ChevronLeft className="w-4 h-4" />
|
|
</button>
|
|
<button type="button" onClick={() => setCurrentDate(new Date())} className={secondaryButton}>
|
|
Today
|
|
</button>
|
|
<button
|
|
type="button"
|
|
onClick={handleNextMonth}
|
|
className="w-9 h-9 crm-radius-control border border-border bg-card text-foreground hover:bg-muted flex items-center justify-center cursor-pointer"
|
|
aria-label="Next month"
|
|
>
|
|
<ChevronRight className="w-4 h-4" />
|
|
</button>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="overflow-x-auto">
|
|
<div className="min-w-[640px]">
|
|
<div className="grid grid-cols-7 border-b border-border bg-muted/40 text-center text-[12px] font-medium text-muted-foreground py-2.5">
|
|
{WEEKDAYS.map((day) => (
|
|
<div key={day}>{day}</div>
|
|
))}
|
|
</div>
|
|
|
|
<div className="grid grid-cols-7 auto-rows-fr gap-px bg-border">
|
|
{Array.from({ length: firstDayOfMonth }).map((_, idx) => (
|
|
<div key={`empty-${idx}`} className="bg-muted/20 min-h-[72px] sm:min-h-[110px] p-1.5 sm:p-2" />
|
|
))}
|
|
|
|
{daysArray.map((dayNum) => {
|
|
const isToday = new Date().toDateString() === new Date(year, month, dayNum).toDateString();
|
|
const dayEvents = events.filter((event) => {
|
|
if (!event.start_time) return false;
|
|
const date = new Date(event.start_time);
|
|
return date.getFullYear() === year && date.getMonth() === month && date.getDate() === dayNum;
|
|
});
|
|
|
|
return (
|
|
<div
|
|
key={`day-${dayNum}`}
|
|
className={`bg-card min-h-[72px] sm:min-h-[110px] p-1.5 sm:p-2 space-y-1.5 ${isToday ? 'bg-primary/5' : ''}`}
|
|
>
|
|
<div className="flex items-center justify-between">
|
|
<span className={`text-[12px] font-semibold w-6 h-6 rounded-full flex items-center justify-center ${isToday ? 'bg-primary text-white' : 'text-foreground'}`}>
|
|
{dayNum}
|
|
</span>
|
|
{dayEvents.length > 0 && (
|
|
<span className="text-[11px] font-medium text-muted-foreground">{dayEvents.length}</span>
|
|
)}
|
|
</div>
|
|
|
|
<div className="space-y-1 overflow-y-auto max-h-[80px]">
|
|
{dayEvents.map((event) => {
|
|
const locName = locations.find((location) => location.location_id === event.location_id)?.name;
|
|
return (
|
|
<div
|
|
key={event.event_id}
|
|
className="px-1.5 py-1 crm-radius-control bg-primary/10 text-[11px] text-foreground flex items-center justify-between gap-1"
|
|
>
|
|
<div className="min-w-0">
|
|
<p className="font-semibold truncate">{event.title}</p>
|
|
<p className="text-[10px] text-muted-foreground truncate">
|
|
{new Date(event.start_time).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
|
|
{locName ? ` ยท ${locName}` : ''}
|
|
</p>
|
|
</div>
|
|
<button
|
|
type="button"
|
|
onClick={() => handleDeleteEvent(event.event_id)}
|
|
className="text-muted-foreground hover:text-foreground cursor-pointer shrink-0"
|
|
aria-label="Delete event"
|
|
>
|
|
<Trash2 className="w-3 h-3" />
|
|
</button>
|
|
</div>
|
|
);
|
|
})}
|
|
</div>
|
|
</div>
|
|
);
|
|
})}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<Modal open={isModalOpen} title="New event" onClose={() => setIsModalOpen(false)}>
|
|
<form onSubmit={handleCreateEvent} className="space-y-3">
|
|
<Field label="Title">
|
|
<input required value={title} onChange={(e) => setTitle(e.target.value)} className={field} />
|
|
</Field>
|
|
<Field label="Description">
|
|
<textarea
|
|
value={description}
|
|
onChange={(e) => setDescription(e.target.value)}
|
|
className="w-full px-3 py-2 bg-card border border-border crm-radius-control text-[13px] text-foreground focus:outline-none focus:border-primary min-h-20"
|
|
/>
|
|
</Field>
|
|
<Field label="Location">
|
|
<CustomSelect
|
|
value={locationId}
|
|
onChange={setLocationId}
|
|
aria-label="Store location"
|
|
options={[
|
|
{ value: '', label: 'All stores' },
|
|
...locations.map((location) => ({ value: location.location_id, label: location.name })),
|
|
]}
|
|
/>
|
|
</Field>
|
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
|
<Field label="Start">
|
|
<input required type="datetime-local" value={startTime} onChange={(e) => setStartTime(e.target.value)} className={field} />
|
|
</Field>
|
|
<Field label="End">
|
|
<input required type="datetime-local" value={endTime} onChange={(e) => setEndTime(e.target.value)} className={field} />
|
|
</Field>
|
|
</div>
|
|
<label className="flex items-center gap-2 text-[13px] text-foreground cursor-pointer">
|
|
<input
|
|
type="checkbox"
|
|
id="allDayCheck"
|
|
checked={isAllDay}
|
|
onChange={(e) => setIsAllDay(e.target.checked)}
|
|
className="accent-primary cursor-pointer"
|
|
/>
|
|
All day
|
|
</label>
|
|
<div className="flex justify-end gap-2 pt-2">
|
|
<button type="button" className={secondaryButton} onClick={() => setIsModalOpen(false)}>Cancel</button>
|
|
<button type="submit" className={primaryButton} disabled={isSubmitting}>
|
|
{isSubmitting ? 'Saving...' : 'Save event'}
|
|
</button>
|
|
</div>
|
|
</form>
|
|
</Modal>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function Field({ label, children }: { label: string; children: ReactNode }) {
|
|
return (
|
|
<label className="block">
|
|
<span className="block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5">{label}</span>
|
|
{children}
|
|
</label>
|
|
);
|
|
}
|
|
|
|
function Modal({ open, title, onClose, children }: { open: boolean; title: string; onClose: () => void; children: ReactNode }) {
|
|
return (
|
|
<SlideOver open={open} onClose={onClose} title={title}>
|
|
<div className="flex min-h-0 flex-1 flex-col">
|
|
<div className="flex-1 min-h-0 overflow-y-auto px-5 py-4">{children}</div>
|
|
</div>
|
|
</SlideOver>
|
|
);
|
|
}
|