Files
chronus/src/pages/dashboard/tracker.astro
Atridad Lahiji 12d59bb42f
All checks were successful
Docker Deploy / build-and-push (push) Successful in 3m57s
Refactored a bunch of shit
2026-02-09 01:49:19 -07:00

387 lines
15 KiB
Plaintext

---
import DashboardLayout from '../../layouts/DashboardLayout.astro';
import { Icon } from 'astro-icon/components';
import Timer from '../../components/Timer.vue';
import ManualEntry from '../../components/ManualEntry.vue';
import { db } from '../../db';
import { timeEntries, clients, tags, users } from '../../db/schema';
import { eq, desc, asc, and, sql, or, like } from 'drizzle-orm';
import { formatTimeRange } from '../../lib/formatTime';
import { getCurrentTeam } from '../../lib/getCurrentTeam';
const user = Astro.locals.user;
if (!user) return Astro.redirect('/login');
const userMembership = await getCurrentTeam(user, Astro.cookies.get('currentTeamId')?.value);
if (!userMembership) return Astro.redirect('/dashboard');
const organizationId = userMembership.organizationId;
const allClients = await db.select()
.from(clients)
.where(eq(clients.organizationId, organizationId))
.all();
const allTags = await db.select()
.from(tags)
.where(eq(tags.organizationId, organizationId))
.all();
// Query params
const url = new URL(Astro.request.url);
const page = parseInt(url.searchParams.get('page') || '1');
const pageSize = 20;
const offset = (page - 1) * pageSize;
const filterClient = url.searchParams.get('client') || '';
const filterStatus = url.searchParams.get('status') || '';
const filterType = url.searchParams.get('type') || '';
const sortBy = url.searchParams.get('sort') || 'start-desc';
const searchTerm = url.searchParams.get('search') || '';
const conditions = [eq(timeEntries.organizationId, organizationId)];
if (filterClient) {
conditions.push(eq(timeEntries.clientId, filterClient));
}
if (filterStatus === 'completed') {
conditions.push(sql`${timeEntries.endTime} IS NOT NULL`);
} else if (filterStatus === 'running') {
conditions.push(sql`${timeEntries.endTime} IS NULL`);
}
if (searchTerm) {
conditions.push(like(timeEntries.description, `%${searchTerm}%`));
}
if (filterType === 'manual') {
conditions.push(eq(timeEntries.isManual, true));
} else if (filterType === 'timed') {
conditions.push(eq(timeEntries.isManual, false));
}
const totalCount = await db.select({ count: sql<number>`count(*)` })
.from(timeEntries)
.where(and(...conditions))
.get();
const totalPages = Math.ceil((totalCount?.count || 0) / pageSize);
let orderBy;
switch (sortBy) {
case 'start-asc':
orderBy = asc(timeEntries.startTime);
break;
case 'duration-desc':
orderBy = desc(sql`(CASE WHEN ${timeEntries.endTime} IS NULL THEN 0 ELSE ${timeEntries.endTime} - ${timeEntries.startTime} END)`);
break;
case 'duration-asc':
orderBy = asc(sql`(CASE WHEN ${timeEntries.endTime} IS NULL THEN 0 ELSE ${timeEntries.endTime} - ${timeEntries.startTime} END)`);
break;
default:
orderBy = desc(timeEntries.startTime);
}
const entries = await db.select({
entry: timeEntries,
client: clients,
user: users,
tag: tags,
})
.from(timeEntries)
.leftJoin(clients, eq(timeEntries.clientId, clients.id))
.leftJoin(users, eq(timeEntries.userId, users.id))
.leftJoin(tags, eq(timeEntries.tagId, tags.id))
.where(and(...conditions))
.orderBy(orderBy)
.limit(pageSize)
.offset(offset)
.all();
const runningEntry = await db.select({
entry: timeEntries,
client: clients,
tag: tags,
})
.from(timeEntries)
.leftJoin(clients, eq(timeEntries.clientId, clients.id))
.leftJoin(tags, eq(timeEntries.tagId, tags.id))
.where(and(
eq(timeEntries.userId, user.id),
sql`${timeEntries.endTime} IS NULL`
))
.get();
function getPaginationPages(currentPage: number, totalPages: number): number[] {
const pages: number[] = [];
const numPagesToShow = Math.min(5, totalPages);
for (let i = 0; i < numPagesToShow; i++) {
let pageNum;
if (totalPages <= 5) {
pageNum = i + 1;
} else if (currentPage <= 3) {
pageNum = i + 1;
} else if (currentPage >= totalPages - 2) {
pageNum = totalPages - 4 + i;
} else {
pageNum = currentPage - 2 + i;
}
pages.push(pageNum);
}
return pages;
}
const paginationPages = getPaginationPages(page, totalPages);
---
<DashboardLayout title="Time Tracker - Chronus">
<h1 class="text-3xl font-bold mb-6">Time Tracker</h1>
<!-- Tabs for Timer and Manual Entry -->
<div class="tabs tabs-lift mb-6">
<input type="radio" name="tracker_tabs" class="tab" aria-label="Timer" checked="checked" />
<div class="tab-content bg-base-100 border-base-300 p-6">
{allClients.length === 0 ? (
<div class="alert alert-warning flex flex-col sm:flex-row items-center gap-4">
<Icon name="heroicons:exclamation-triangle" class="stroke-current shrink-0 h-6 w-6" />
<span class="flex-1 text-center sm:text-left">You need to create a client before tracking time.</span>
<a href="/dashboard/clients/new" class="btn btn-sm btn-primary whitespace-nowrap">Add Client</a>
</div>
) : (
<Timer
client:load
initialRunningEntry={runningEntry ? {
startTime: runningEntry.entry.startTime.getTime(),
description: runningEntry.entry.description,
clientId: runningEntry.entry.clientId,
tagId: runningEntry.tag?.id,
} : null}
clients={allClients.map(c => ({ id: c.id, name: c.name }))}
tags={allTags.map(t => ({ id: t.id, name: t.name, color: t.color }))}
/>
)}
</div>
<input type="radio" name="tracker_tabs" class="tab" aria-label="Manual Entry" />
<div class="tab-content bg-base-100 border-base-300 p-6">
{allClients.length === 0 ? (
<div class="alert alert-warning flex flex-col sm:flex-row items-center gap-4">
<Icon name="heroicons:exclamation-triangle" class="stroke-current shrink-0 h-6 w-6" />
<span class="flex-1 text-center sm:text-left">You need to create a client before adding time entries.</span>
<a href="/dashboard/clients/new" class="btn btn-sm btn-primary whitespace-nowrap">Add Client</a>
</div>
) : (
<ManualEntry
client:idle
clients={allClients.map(c => ({ id: c.id, name: c.name }))}
tags={allTags.map(t => ({ id: t.id, name: t.name, color: t.color }))}
/>
)}
</div>
</div>
{allClients.length === 0 ? (
<!-- If no clients/categories, show nothing extra here since tabs handle warnings -->
) : null}
<!-- Filters and Search -->
<div class="card bg-base-200/50 backdrop-blur-sm shadow-lg border border-base-300/50 hover:border-base-300 transition-all duration-200 mb-6">
<div class="card-body">
<form method="GET" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-6 gap-4">
<div class="form-control">
<label class="label font-medium" for="tracker-search">
Search
</label>
<input
type="text"
id="tracker-search"
name="search"
placeholder="Search descriptions..."
class="input input-bordered bg-base-300/50 hover:bg-base-300 focus:bg-base-300 border-base-300/50 focus:border-primary transition-colors w-full"
value={searchTerm}
/>
</div>
<div class="form-control">
<label class="label font-medium" for="tracker-client">
Client
</label>
<select id="tracker-client" name="client" class="select select-bordered bg-base-300/50 hover:bg-base-300 focus:bg-base-300 border-base-300/50 focus:border-primary transition-colors w-full" onchange="this.form.submit()">
<option value="">All Clients</option>
{allClients.map(client => (
<option value={client.id} selected={filterClient === client.id}>
{client.name}
</option>
))}
</select>
</div>
<div class="form-control">
<label class="label font-medium" for="tracker-status">
Status
</label>
<select id="tracker-status" name="status" class="select select-bordered bg-base-300/50 hover:bg-base-300 focus:bg-base-300 border-base-300/50 focus:border-primary transition-colors w-full" onchange="this.form.submit()">
<option value="" selected={filterStatus === ''}>All Entries</option>
<option value="completed" selected={filterStatus === 'completed'}>Completed</option>
<option value="running" selected={filterStatus === 'running'}>Running</option>
</select>
</div>
<div class="form-control">
<label class="label font-medium" for="tracker-type">
Entry Type
</label>
<select id="tracker-type" name="type" class="select select-bordered bg-base-300/50 hover:bg-base-300 focus:bg-base-300 border-base-300/50 focus:border-primary transition-colors w-full" onchange="this.form.submit()">
<option value="" selected={filterType === ''}>All Types</option>
<option value="timed" selected={filterType === 'timed'}>Timed</option>
<option value="manual" selected={filterType === 'manual'}>Manual</option>
</select>
</div>
<div class="form-control">
<label class="label font-medium" for="tracker-sort">
Sort By
</label>
<select id="tracker-sort" name="sort" class="select select-bordered bg-base-300/50 hover:bg-base-300 focus:bg-base-300 border-base-300/50 focus:border-primary transition-colors w-full" onchange="this.form.submit()">
<option value="start-desc" selected={sortBy === 'start-desc'}>Newest First</option>
<option value="start-asc" selected={sortBy === 'start-asc'}>Oldest First</option>
<option value="duration-desc" selected={sortBy === 'duration-desc'}>Longest Duration</option>
<option value="duration-asc" selected={sortBy === 'duration-asc'}>Shortest Duration</option>
</select>
</div>
<input type="hidden" name="page" value="1" />
<div class="form-control md:col-span-2 lg:col-span-6">
<button type="submit" class="btn btn-primary shadow-lg shadow-primary/20 hover:shadow-xl hover:shadow-primary/30 transition-all">
<Icon name="heroicons:magnifying-glass" class="w-5 h-5" />
Search
</button>
</div>
</form>
</div>
</div>
<div class="card bg-base-200/30 backdrop-blur-sm shadow-lg border border-base-300/50 hover:border-base-300 transition-all duration-200">
<div class="card-body">
<div class="flex justify-between items-center mb-4">
<h2 class="card-title">
<Icon name="heroicons:list-bullet" class="w-6 h-6" />
Time Entries ({totalCount?.count || 0} total)
</h2>
{(filterClient || filterStatus || filterType || searchTerm) && (
<a href="/dashboard/tracker" class="btn btn-sm btn-ghost hover:bg-base-300/50 transition-colors">
<Icon name="heroicons:x-mark" class="w-4 h-4" />
Clear Filters
</a>
)}
</div>
<div class="overflow-x-auto">
<table class="table table-zebra">
<thead>
<tr class="bg-base-300/30">
<th>Type</th>
<th>Client</th>
<th>Description</th>
<th>Member</th>
<th>Start Time</th>
<th>End Time</th>
<th>Duration</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{entries.map(({ entry, client, user: entryUser }) => (
<tr class="hover:bg-base-300/20 transition-colors">
<td>
{entry.isManual ? (
<span class="badge badge-info badge-sm gap-1 shadow-sm" title="Manual Entry">
<Icon name="heroicons:pencil" class="w-3 h-3" />
Manual
</span>
) : (
<span class="badge badge-success badge-sm gap-1 shadow-sm" title="Timed Entry">
<Icon name="heroicons:clock" class="w-3 h-3" />
Timed
</span>
)}
</td>
<td class="font-medium">{client?.name || 'Unknown'}</td>
<td class="text-base-content/80">{entry.description || '-'}</td>
<td>{entryUser?.name || 'Unknown'}</td>
<td class="whitespace-nowrap">
{entry.startTime.toLocaleDateString()}<br/>
<span class="text-xs opacity-50">
{entry.startTime.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})}
</span>
</td>
<td class="whitespace-nowrap">
{entry.endTime ? (
<>
{entry.endTime.toLocaleDateString()}<br/>
<span class="text-xs opacity-50">
{entry.endTime.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})}
</span>
</>
) : (
<span class="badge badge-success shadow-sm">Running</span>
)}
</td>
<td class="font-mono font-semibold text-primary">{formatTimeRange(entry.startTime, entry.endTime)}</td>
<td>
<form method="POST" action={`/api/time-entries/${entry.id}/delete`} class="inline">
<button
type="submit"
class="btn btn-ghost btn-sm text-error hover:bg-error/10 transition-colors"
onclick="return confirm('Are you sure you want to delete this entry?')"
>
<Icon name="heroicons:trash" class="w-4 h-4" />
</button>
</form>
</td>
</tr>
))}
</tbody>
</table>
</div>
<!-- Pagination -->
{totalPages > 1 && (
<div class="flex justify-center items-center gap-2 mt-6">
<a
href={`?page=${Math.max(1, page - 1)}${filterClient ? `&client=${filterClient}` : ''}${filterStatus ? `&status=${filterStatus}` : ''}${filterType ? `&type=${filterType}` : ''}${sortBy ? `&sort=${sortBy}` : ''}${searchTerm ? `&search=${searchTerm}` : ''}`}
class={`btn btn-sm transition-all ${page === 1 ? 'btn-disabled' : 'hover:bg-base-300/50'}`}
>
<Icon name="heroicons:chevron-left" class="w-4 h-4" />
Previous
</a>
<div class="flex gap-1">
{paginationPages.map(pageNum => (
<a
href={`?page=${pageNum}${filterClient ? `&client=${filterClient}` : ''}${filterStatus ? `&status=${filterStatus}` : ''}${filterType ? `&type=${filterType}` : ''}${sortBy ? `&sort=${sortBy}` : ''}${searchTerm ? `&search=${searchTerm}` : ''}`}
class={`btn btn-sm transition-all ${page === pageNum ? 'btn-active' : 'hover:bg-base-300/50'}`}
>
{pageNum}
</a>
))}
</div>
<a
href={`?page=${Math.min(totalPages, page + 1)}${filterClient ? `&client=${filterClient}` : ''}${filterStatus ? `&status=${filterStatus}` : ''}${filterType ? `&type=${filterType}` : ''}${sortBy ? `&sort=${sortBy}` : ''}${searchTerm ? `&search=${searchTerm}` : ''}`}
class={`btn btn-sm transition-all ${page === totalPages ? 'btn-disabled' : 'hover:bg-base-300/50'}`}
>
Next
<Icon name="heroicons:chevron-right" class="w-4 h-4" />
</a>
</div>
)}
</div>
</div>
</DashboardLayout>