Spaces:
Running

File size: 10,892 Bytes
f287aeb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
import { useCallback, useEffect, useMemo, useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Button } from "./ui/button";
import { Badge } from "./ui/badge";
import { toast } from "sonner";
import {
  CheckCircle2,
  Clock3,
  ListChecks,
  RefreshCcw,
  Trash2,
} from "lucide-react";
import { User } from "../types";
import {
  deleteTask,
  getFarmTasks,
  getMyTasks,
  isFeedingTask,
  notifyFeedingTaskCompleted,
  TaskItem,
  TaskStatus,
  updateTaskStatus,
} from "../services/taskApi";

interface TasksProps {
  user: User;
}

const STATUSES: TaskStatus[] = ["OPEN", "IN_PROGRESS", "DONE", "CANCELLED"];

const STATUS_BADGE_CLASS: Record<TaskStatus, string> = {
  OPEN: "bg-blue-100 text-blue-800",
  IN_PROGRESS: "bg-yellow-100 text-amber-800",
  DONE: "bg-green-600 text-white border-green-600",
  CANCELLED: "bg-red-100 text-white border-red-700",
};

const formatDateTime = (value?: string): string => {
  if (!value) return "N/A";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "N/A";
  return date.toLocaleString();
};

export default function Tasks({ user }: TasksProps) {
  const canViewFarmTasks = user.role === "admin" || user.role === "manager";
  const canCancelTask = canViewFarmTasks;

  const [scope, setScope] = useState<"mine" | "farm">(
    canViewFarmTasks ? "farm" : "mine",
  );
  const [statusFilter, setStatusFilter] = useState<"ALL" | TaskStatus>("ALL");
  const [tasks, setTasks] = useState<TaskItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [busyTaskIds, setBusyTaskIds] = useState<Record<string, boolean>>({});

  const setTaskBusy = (taskId: string, busy: boolean) => {
    setBusyTaskIds((prev) => ({ ...prev, [taskId]: busy }));
  };

  const loadTasks = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const data =
        scope === "mine"
          ? await getMyTasks()
          : await getFarmTasks(
              statusFilter === "ALL" ? undefined : statusFilter,
            );
      setTasks(data);
    } catch (err) {
      setError((err as Error).message);
      setTasks([]);
    } finally {
      setLoading(false);
    }
  }, [scope, statusFilter]);

  useEffect(() => {
    void loadTasks();
  }, [loadTasks]);

  const filteredTasks = useMemo(() => {
    if (statusFilter === "ALL") return tasks;
    return tasks.filter((task) => task.status === statusFilter);
  }, [statusFilter, tasks]);

  const summary = useMemo(() => {
    const counts: Record<"total" | TaskStatus, number> = {
      total: filteredTasks.length,
      OPEN: 0,
      IN_PROGRESS: 0,
      DONE: 0,
      CANCELLED: 0,
    };

    filteredTasks.forEach((task) => {
      counts[task.status] += 1;
    });

    return counts;
  }, [filteredTasks]);

  const handleUpdateStatus = async (task: TaskItem, status: TaskStatus) => {
    setTaskBusy(task.id, true);
    try {
      await updateTaskStatus(task.id, status);
      if (status === "DONE" && isFeedingTask(task)) {
        notifyFeedingTaskCompleted(task.id);
      }
      toast.success(`Task moved to ${status}`);
      await loadTasks();
    } catch (err) {
      toast.error(`Failed to update task: ${(err as Error).message}`);
    } finally {
      setTaskBusy(task.id, false);
    }
  };

  const handleDeleteTask = async (task: TaskItem) => {
    setTaskBusy(task.id, true);
    try {
      await deleteTask(task.id);
      toast.success("Task cancelled");
      await loadTasks();
    } catch (err) {
      toast.error(`Failed to cancel task: ${(err as Error).message}`);
    } finally {
      setTaskBusy(task.id, false);
    }
  };
  const isWorker = user.role.toLowerCase() === "worker";
  return (
    <div className="p-6 space-y-6">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div>
          <h1 className="text-2xl font-semibold">Tasks</h1>
          <p className="text-sm text-gray-600">
            Track and complete operational tasks assigned from alerts and
            workflows.
          </p>
        </div>

        <Button
          variant="outline"
          onClick={() => void loadTasks()}
          disabled={loading}
        >
          <RefreshCcw className="w-4 h-4 mr-2" />
          Refresh
        </Button>
      </div>

      <Card>
        <CardContent className="pt-6 flex flex-wrap gap-3 items-center">
          {canViewFarmTasks && (
            <div className="flex items-center gap-2">
              <Button
                size="sm"
                variant={scope === "farm" ? "default" : "outline"}
                onClick={() => setScope("farm")}
              >
                Farm Tasks
              </Button>
              <Button
                size="sm"
                variant={scope === "mine" ? "default" : "outline"}
                onClick={() => setScope("mine")}
              >
                My Tasks
              </Button>
            </div>
          )}

          <select
            className="h-9 rounded-md border border-input bg-background px-3 text-sm"
            value={statusFilter}
            onChange={(event) =>
              setStatusFilter(event.target.value as "ALL" | TaskStatus)
            }
          >
            <option value="ALL">All Statuses</option>
            {STATUSES.map((status) => (
              <option key={status} value={status}>
                {status}
              </option>
            ))}
          </select>
        </CardContent>
      </Card>

      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm">Total</CardTitle>
          </CardHeader>
          <CardContent className="text-2xl font-semibold">
            {summary.total}
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm">Open</CardTitle>
          </CardHeader>
          <CardContent className="text-2xl font-semibold text-blue-700">
            {summary.OPEN}
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm">In Progress</CardTitle>
          </CardHeader>
          <CardContent className="text-2xl font-semibold text-amber-700">
            {summary.IN_PROGRESS}
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm">Done</CardTitle>
          </CardHeader>
          <CardContent className="text-2xl font-semibold text-emerald-700">
            {summary.DONE}
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardHeader>
          <CardTitle className="text-base">
            {scope === "farm" ? "Farm Task Queue" : "My Assigned Tasks"}
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-3">
          {loading && (
            <div className="text-sm text-gray-600">Loading tasks...</div>
          )}

          {!loading && error && (
            <div className="text-sm text-red-700">
              Failed to load tasks: {error}
            </div>
          )}

          {!loading && !error && filteredTasks.length === 0 && (
            <div className="py-10 text-center text-gray-500">
              <ListChecks className="w-10 h-10 mx-auto mb-2 text-gray-400" />
              <p>No tasks found for the selected filter.</p>
            </div>
          )}

          {!loading &&
            !error &&
            filteredTasks.map((task) => {
              const isBusy = !!busyTaskIds[task.id];
              const canStart = task.status === "OPEN";
              const canComplete =
                task.status === "OPEN" || task.status === "IN_PROGRESS";
              const canCancel =
                canCancelTask &&
                task.status !== "DONE" &&
                task.status !== "CANCELLED";

              return (
                <div key={task.id} className="rounded-lg border p-4 space-y-3">
                  <div className="flex flex-wrap items-center justify-between gap-2">
                    <div className="flex items-center gap-2">
                      <p className="font-medium">
                        {task.title.replace("Feed Tank ", "Feed Tank : ")}
                      </p>
                      <Badge
                        className={STATUS_BADGE_CLASS[task.status]}
                        variant="outline"
                      >
                        {task.status}
                      </Badge>
                    </div>
                    <p className="text-xs text-gray-500">ID: {task.id}</p>
                  </div>

                  <p className="text-sm text-gray-700">
                    {task.description || "No description provided."}
                  </p>

                  <div className="grid grid-cols-1 md:grid-cols-3 gap-2 text-xs text-gray-600">
                    <p>Assigned To: {task.assignedToUserId || "N/A"}</p>
                    <p>Due: {formatDateTime(task.dueAt)}</p>
                    <p>Created: {formatDateTime(task.createdAt)}</p>
                  </div>

                  <div className="flex flex-wrap gap-2">
                    {canStart && isWorker && (
                      <Button
                        size="sm"
                        variant="outline"
                        disabled={isBusy}
                        onClick={() =>
                          void handleUpdateStatus(task, "IN_PROGRESS")
                        }
                      >
                        <Clock3 className="w-3 h-3 mr-1" />
                        Start
                      </Button>
                    )}

                    {canComplete && isWorker && (
                      <Button
                        size="sm"
                        disabled={isBusy}
                        onClick={() => void handleUpdateStatus(task, "DONE")}
                      >
                        <CheckCircle2 className="w-3 h-3 mr-1" />
                        Mark Done
                      </Button>
                    )}

                    {canCancel && isWorker && (
                      <Button
                        size="sm"
                        variant="ghost"
                        className="text-red-600 hover:text-red-700"
                        disabled={isBusy}
                        onClick={() => void handleDeleteTask(task)}
                      >
                        <Trash2 className="w-3 h-3 mr-1" />
                        Cancel
                      </Button>
                    )}
                  </div>
                </div>
              );
            })}
        </CardContent>
      </Card>
    </div>
  );
}