ifixkart-admin/app/(admin)/crm-todos/page.tsx

364 lines
15 KiB
TypeScript

'use client';
import { useEffect, useState, type ReactNode } from 'react';
import { format } from 'date-fns';
import { CheckCircle2, Circle, Plus, RefreshCw, Trash2 } from 'lucide-react';
import { toast } from 'sonner';
import { crmTaskCalendarService, CrmTask } 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 PRIORITY_META: Record<string, { label: string; className: string }> = {
HIGH: { label: 'High', className: 'bg-destructive/10 text-destructive' },
MEDIUM: { label: 'Medium', className: 'bg-warning/15 text-warning' },
LOW: { label: 'Low', className: 'bg-muted text-foreground' },
};
function priorityMeta(priority?: string) {
return PRIORITY_META[priority || ''] || { label: priority || '—', className: 'bg-muted text-foreground' };
}
function formatDue(iso?: string) {
if (!iso) return '—';
const date = new Date(iso);
if (Number.isNaN(date.getTime())) return '—';
return format(date, 'dd MMM yyyy, hh:mm a');
}
export default function CrmTodosPage() {
const [tasks, setTasks] = useState<CrmTask[]>([]);
const [locations, setLocations] = useState<CrmLocation[]>([]);
const [loading, setLoading] = useState(true);
const [filterStatus, setFilterStatus] = useState<string>('ALL');
const [filterPriority, setFilterPriority] = useState<string>('ALL');
const [filterLocationId, setFilterLocationId] = useState<string>('ALL');
const [isModalOpen, setIsModalOpen] = useState(false);
const [title, setTitle] = useState('');
const [description, setDescription] = useState('');
const [locationId, setLocationId] = useState<string>('');
const [priority, setPriority] = useState<string>('MEDIUM');
const [entityType, setEntityType] = useState<string>('');
const [entityId, setEntityId] = useState<string>('');
const [dueAt, setDueAt] = useState<string>('');
const [isSubmitting, setIsSubmitting] = useState(false);
useEffect(() => {
loadData();
}, []);
const loadData = async () => {
try {
setLoading(true);
const [taskData, locData] = await Promise.all([
crmTaskCalendarService.getTasks(),
systemConfigService.getLocations(),
]);
setTasks(Array.isArray(taskData) ? taskData : []);
setLocations(Array.isArray(locData) ? locData : []);
} catch {
toast.error('Failed to load CRM tasks');
} finally {
setLoading(false);
}
};
const handleCreateTask = async (e: React.FormEvent) => {
e.preventDefault();
if (!title.trim()) {
toast.error('Task title is required');
return;
}
try {
setIsSubmitting(true);
await crmTaskCalendarService.createTask({
title: title.trim(),
description: description || undefined,
location_id: locationId || undefined,
priority: priority,
status: 'PENDING',
entity_type: entityType || undefined,
entity_id: entityId || undefined,
due_at: dueAt ? new Date(dueAt).toISOString() : undefined,
});
toast.success('CRM Task created successfully!');
setIsModalOpen(false);
setTitle('');
setDescription('');
setLocationId('');
setPriority('MEDIUM');
setEntityType('');
setEntityId('');
setDueAt('');
loadData();
} catch (err: any) {
toast.error(err?.message || 'Failed to create task');
} finally {
setIsSubmitting(false);
}
};
const handleToggleStatus = async (task: CrmTask) => {
const newStatus = task.status === 'COMPLETED' ? 'PENDING' : 'COMPLETED';
try {
await crmTaskCalendarService.updateTask(task.task_id, { status: newStatus });
toast.success(`Task marked as ${newStatus}`);
loadData();
} catch {
toast.error('Failed to update task status');
}
};
const handleDeleteTask = async (taskId: string) => {
if (!confirm('Are you sure you want to delete this task?')) return;
try {
await crmTaskCalendarService.deleteTask(taskId);
toast.success('Task deleted');
loadData();
} catch {
toast.error('Failed to delete task');
}
};
const filteredTasks = tasks.filter((t) => {
if (filterStatus !== 'ALL' && t.status !== filterStatus) return false;
if (filterPriority !== 'ALL' && t.priority !== filterPriority) return false;
if (filterLocationId !== 'ALL' && t.location_id !== filterLocationId) return false;
return true;
});
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">Tasks</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">
{filteredTasks.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 task
</button>
</div>
</div>
<div className={shell}>
<div className="flex flex-wrap items-center gap-2 px-4 py-3 border-b border-border">
<CustomSelect
value={filterStatus}
onChange={setFilterStatus}
aria-label="Task status"
className="w-[160px]"
options={[
{ value: 'ALL', label: 'All statuses' },
{ value: 'PENDING', label: 'Pending' },
{ value: 'COMPLETED', label: 'Completed' },
]}
/>
<CustomSelect
value={filterPriority}
onChange={setFilterPriority}
aria-label="Task priority"
className="w-[160px]"
options={[
{ value: 'ALL', label: 'All priorities' },
{ value: 'HIGH', label: 'High' },
{ value: 'MEDIUM', label: 'Medium' },
{ value: 'LOW', label: 'Low' },
]}
/>
<CustomSelect
value={filterLocationId}
onChange={setFilterLocationId}
aria-label="Store location"
className="w-[200px]"
options={[
{ value: 'ALL', label: 'All locations' },
...locations.map((loc) => ({ value: loc.location_id, label: loc.name })),
]}
/>
</div>
{loading ? (
<p className="py-16 text-center text-[13px] text-muted-foreground">Loading tasks</p>
) : (
<div className="overflow-x-auto">
<table className="crm-data-table min-w-[860px]">
<thead>
<tr className="border-y border-border">
<th className="w-10" />
<th className="text-left font-medium text-muted-foreground px-4 py-2.5">Task</th>
<th className="text-left font-medium text-muted-foreground px-4 py-2.5">Priority</th>
<th className="text-left font-medium text-muted-foreground px-4 py-2.5">Location</th>
<th className="text-left font-medium text-muted-foreground px-4 py-2.5">Linked</th>
<th className="text-left font-medium text-muted-foreground px-4 py-2.5">Due</th>
<th className="text-right font-medium text-muted-foreground px-4 py-2.5">Action</th>
</tr>
</thead>
<tbody>
{filteredTasks.length === 0 ? (
<tr>
<td colSpan={7} className="px-4 py-16 text-center text-[13px] text-muted-foreground whitespace-normal">No tasks match this view.</td>
</tr>
) : filteredTasks.map((task) => {
const locName = locations.find((l) => l.location_id === task.location_id)?.name;
const isDone = task.status === 'COMPLETED';
const priority = priorityMeta(task.priority);
return (
<tr key={task.task_id} className="border-b border-border last:border-0">
<td className="pl-4 py-3">
<button
type="button"
onClick={() => handleToggleStatus(task)}
className="text-muted-foreground hover:text-primary cursor-pointer"
aria-label={isDone ? 'Mark pending' : 'Mark completed'}
>
{isDone ? <CheckCircle2 className="w-4 h-4 text-success" /> : <Circle className="w-4 h-4" />}
</button>
</td>
<td className="px-4 py-3">
<p className={`font-semibold ${isDone ? 'line-through text-muted-foreground' : 'text-foreground'}`}>
{task.title}
</p>
{task.description && <p className="text-[12px] text-muted-foreground mt-0.5">{task.description}</p>}
</td>
<td className="px-4 py-3">
<span className={`inline-flex items-center px-2.5 py-1 crm-radius-badge text-[11px] font-semibold ${priority.className}`}>
{priority.label}
</span>
</td>
<td className="px-4 py-3 text-muted-foreground">{locName || '—'}</td>
<td className="px-4 py-3 text-muted-foreground">
{task.entity_type ? `${task.entity_type.replaceAll('_', ' ').toLowerCase()}${task.entity_id ? ` · ${task.entity_id}` : ''}` : '—'}
</td>
<td className="px-4 py-3 text-muted-foreground whitespace-nowrap">{formatDue(task.due_at)}</td>
<td className="px-4 py-3 text-right">
<button
type="button"
onClick={() => handleDeleteTask(task.task_id)}
className="w-8 h-8 inline-flex items-center justify-center crm-radius-control text-muted-foreground hover:text-foreground hover:bg-muted cursor-pointer"
aria-label="Delete task"
>
<Trash2 className="w-3.5 h-3.5" />
</button>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
)}
</div>
<Modal open={isModalOpen} title="New task" onClose={() => setIsModalOpen(false)}>
<form onSubmit={handleCreateTask} 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>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<Field label="Priority">
<CustomSelect
value={priority}
onChange={setPriority}
aria-label="Priority"
options={[
{ value: 'LOW', label: 'Low' },
{ value: 'MEDIUM', label: 'Medium' },
{ value: 'HIGH', label: 'High' },
]}
/>
</Field>
<Field label="Location">
<CustomSelect
value={locationId}
onChange={setLocationId}
aria-label="Store location"
options={[
{ value: '', label: 'All stores' },
...locations.map((loc) => ({ value: loc.location_id, label: loc.name })),
]}
/>
</Field>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<Field label="Linked to">
<CustomSelect
value={entityType}
onChange={setEntityType}
aria-label="Linked entity"
options={[
{ value: '', label: 'None' },
{ value: 'REPAIR_TICKET', label: 'Repair ticket' },
{ value: 'LEAD', label: 'Lead' },
{ value: 'CUSTOMER', label: 'Customer' },
{ value: 'QUOTATION', label: 'Quotation' },
]}
/>
</Field>
<Field label="Record id">
<input value={entityId} onChange={(e) => setEntityId(e.target.value)} className={field} />
</Field>
</div>
<Field label="Due">
<input type="datetime-local" value={dueAt} onChange={(e) => setDueAt(e.target.value)} className={field} />
</Field>
<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 task'}
</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>
);
}