-| Login (Light) | Login (Dark) | Dashboard (Light) |
-| ----------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
-|
|
|
|
+| Login (Light) | Login (Dark) | Dashboard (Light) |
+| -------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------- |
+|
|
|
|
-| Dashboard (Dark) | Clock (Light) | Clock (Dark) |
-| ------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
-|
|
|
|
+| Dashboard (Dark) | Clock (Light) | Clock (Dark) |
+| --------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
+|
|
|
|
-| Tickets (Light) | Tickets (Dark) | Teams (Light) |
-| ------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
-|
|
|
|
+| Tickets (Light) | Tickets (Dark) | Teams (Light) |
+| ------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
+|
|
|
|
## Quick Start
+You need both **timehuddle** (this repo, the frontend) and **timecore** (the backend API) running.
+
+### 1. Start the backend (timecore)
+
```bash
-# Install Meteor (if not already installed)
-curl https://install.meteor.com/ | sh
+cd ../timecore
+npm install
+npm run dev # Fastify API on http://localhost:4000
+```
-# Clone and run
+### 2. Start the frontend (timehuddle)
+
+```bash
git clone https://github.com/mieweb/timehuddle.git
cd timehuddle
-npm ci --no-audit --no-fund
-meteor run
+npm install
+npm run dev # Vite dev server on http://localhost:3000
```
Open http://localhost:3000 β you'll see the login page. Create an account to get started.
+### Environment
+
+Copy `.env` and adjust if your timecore URL differs:
+
+```bash
+# .env (already committed with defaults)
+VITE_TIMECORE_URL=http://localhost:4000
+# VITE_VAPID_PUBLIC_KEY=your_vapid_public_key_here # optional, for push notifications
+```
+
## Project Structure
```
+index.html # Vite entry point
client/
- main.tsx # React root β createRoot / hydrateRoot
- main.html # HTML shell with
- styles.css # Tailwind imports + minimal global styles
+ main.tsx # React root β createRoot
+ styles.css # Tailwind imports + minimal global styles
imports/
- features/ # Feature modules β self-contained API + UI
+ features/ # Feature modules β self-contained UI + types
auth/
- api.ts # Account creation, profile update, password reset
- schema.ts # Zod schemas for auth validation
+ schema.ts # Zod schemas for auth validation
clock/
- api.ts # Clock events collection, start/stop, ticket timers
- schema.ts # Clock event schemas
- ClockPage.tsx # Clock in/out UI
- TimesheetPage.tsx # Timesheet view
+ schema.ts # Clock event schemas
+ ClockPage.tsx # Clock in/out UI
+ TimesheetPage.tsx # Timesheet view
dashboard/
- DashboardPage.tsx # Main dashboard with stats overview
+ DashboardPage.tsx # Main dashboard with stats overview
messages/
- api.ts # Direct messages collection and methods
- schema.ts # Message schemas
- MessagesPage.tsx # Messaging UI
+ schema.ts # Message schemas
+ MessagesPage.tsx # Messaging UI
+ notifications/
+ NotificationsPage.tsx # Notification inbox UI
profile/
- api.ts # User profile methods and publication
- schema.ts # Profile schemas
- ProfilePage.tsx # User profile page
- UsernameBadge.tsx # Display name component
+ schema.ts # Profile schemas
+ ProfilePage.tsx # User profile page
teams/
- api.ts # Teams collection, CRUD, invites, roles
- schema.ts # Team schemas
- TeamsPage.tsx # Team management UI
+ schema.ts # Team schemas
+ TeamsPage.tsx # Team management UI
tickets/
- api.ts # Tickets collection, CRUD, time tracking
- schema.ts # Ticket schemas
- TicketsPage.tsx # Ticket tracking UI
- inbox/ # Dev email viewer (auto-disabled in production)
+ schema.ts # Ticket schemas
+ TicketsPage.tsx # Ticket tracking UI
+ inbox/
+ InboxPage.tsx # Dev email viewer (/inbox route, dev only)
lib/
- constants.ts # Shared validation limits, storage keys
+ api.ts # All timecore REST API wrappers
+ constants.ts # Shared validation limits, storage keys
TeamContext.tsx # React context for active team selection
- timeUtils.ts # Time formatting utilities
- useBrand.ts # Branding hook
- useMethod.ts # Typed Meteor.call wrapper hook
- useTheme.ts # Shared theme hook (read/apply/toggle)
- startup/
- client.ts # Client startup (feature API imports)
- server.ts # Accounts config, dev email capture, user pub
- seed.ts # E2E seed data (dev only)
- ssr.tsx # SSR for login page + SEO meta tags
- ui/ # Shared UI components
- AppLayout.tsx # Root shell β routing, sidebar, header
- LoginForm.tsx # Email/password auth form
- Sidebar.tsx # Collapsible sidebar navigation
- AppHeader.tsx # Top bar with title, theme toggle, user menu
+ timeUtils.ts # Time formatting utilities
+ useBrand.ts # Branding hook
+ useSession.ts # Auth session hook (reads timecore session)
+ useTheme.ts # Shared theme hook (read/apply/toggle)
+ pushNotificationsClient.ts # Web Push subscription helpers
+ ui/ # Shared UI components
+ AppLayout.tsx # Root shell β routing, sidebar, header
+ LoginForm.tsx # Email/password auth form
+ Sidebar.tsx # Collapsible sidebar navigation
+ AppHeader.tsx # Top bar with title, theme toggle, user menu
ThemeToggle.tsx # Dark/light mode toggle
UserDropdown.tsx # User menu dropdown
SettingsPage.tsx # App settings
- LandingPage.tsx # Marketing page (not used as default route)
-server/
- main.ts # Server entry β imports features + startup
```
### How to Add a Feature
1. Create `imports/features/myfeature/`
2. Add `schema.ts` β Zod schemas + TypeScript types
-3. Add `api.ts` β collection, methods, publication (import schemas)
-4. Add `MyFeaturePage.tsx` β UI component (import `useMethod` + constants)
-5. Add route in `imports/ui/AppLayout.tsx` β `ROUTES` map
-6. Add nav item in `imports/ui/Sidebar.tsx` β `NAV_SECTIONS`
-7. Import `api.ts` in `server/main.ts` and `imports/startup/client.ts`
+3. Add `MyFeaturePage.tsx` β UI component (use `imports/lib/api.ts` for data)
+4. Add route in `imports/ui/AppLayout.tsx` β `ROUTES` map
+5. Add nav item in `imports/ui/Sidebar.tsx` β `NAV_SECTIONS`
+6. Add backend endpoints in [timecore](../timecore)
### Conventions
-- **Validation**: Define Zod schemas in `schema.ts`, use them in both server methods and client forms
+- **API calls**: All data fetching goes through `imports/lib/api.ts` β typed wrappers around `fetch`
+- **Validation**: Define Zod schemas in `schema.ts`, use them in client forms
- **Constants**: Shared limits/keys live in `imports/lib/constants.ts`
-- **Methods**: Components use `useMethod('method.name')` β never call `Meteor.call` directly
-- **Theme**: Use `useTheme()` from `imports/lib/useTheme.ts` β never access `localStorage` directly for theme
-- **Types**: Export TypeScript interfaces from `schema.ts`, re-export from `api.ts`
+- **Auth**: Use `useSession()` from `imports/lib/useSession.ts` to get the current user
+- **Theme**: Use `useTheme()` from `imports/lib/useTheme.ts` β never access `localStorage` directly
- **UI Components**: Use `@mieweb/ui` for all UI primitives (Button, Input, Modal, etc.)
## Auth Flow
-1. User creates an account with email, password, first name, and last name
-2. User signs in with email and password
-3. Password reset is available via team code verification
+1. User creates an account with email, password, and name (POST `/api/auth/sign-up/email`)
+2. User signs in with email and password (POST `/api/auth/sign-in/email`)
+3. Password reset available via email link
4. Authenticated users are redirected to `/app/dashboard`
## Commands
```bash
# Development
-meteor run # Start dev server (2-5 min first startup)
-npm run lint # Check code style
-npm run typecheck # Check TypeScript
-npm run format # Check Prettier formatting
-npm test # Run Vitest tests
-npm run test:watch # Run tests in watch mode
+npm run dev # Start Vite dev server on :3000
+npm run lint # Check code style
+npm run typecheck # Check TypeScript
+npm run format # Check Prettier formatting
+npm test # Run Vitest tests
+npm run test:watch # Run tests in watch mode
# Fixes
-npm run lint:fix # Auto-fix lint issues
-npm run format:fix # Auto-format code
+npm run lint:fix # Auto-fix lint issues
+npm run format:fix # Auto-format code
# Production
-meteor build ../build --directory # Build (5-15 min)
+npm run build # Vite production build β dist/
+npm run preview # Preview the production build locally
```
-## Feature API Reference
-
-### Auth
-
-| Method | Args | Description |
-| ------------------------- | ------------------------------------------------------- | ---------------------------------- |
-| `createUserAccount` | `{ email, password, firstName, lastName }` | Create a new user account |
-| `updateUserProfile` | `{ firstName, lastName }` | Update user profile name |
-| `resetPasswordWithTeamCode` | `{ email, teamCode, newPassword }` | Reset password with team code |
-
-### Clock
-
-| Method | Args | Description |
-| --------------------- | ------------------------------------------------- | -------------------------------- |
-| `clock.start` | `{ teamId }` | Clock in for a team |
-| `clock.stop` | `{ teamId, youtubeShortLink? }` | Clock out with optional link |
-| `clock.addTicket` | `{ clockEventId, ticketId, now }` | Start tracking a ticket |
-| `clock.stopTicket` | `{ clockEventId, ticketId, now }` | Stop tracking a ticket |
-| `clock.updateYoutubeLink` | `{ clockEventId, youtubeShortLink }` | Update YouTube link on entry |
-| `clock.updateTimes` | `{ clockEventId, startTimestamp?, endTimestamp? }` | Edit clock event times |
-| `clock.getTimesheetData` | `{ userId, startDate, endDate }` | Fetch timesheet data |
-
-### Teams
-
-| Method | Args | Description |
-| --------------------- | --------------------------------- | ---------------------------- |
-| `teams.ensurePersonalWorkspace` | β | Create personal workspace |
-| `teams.create` | `{ name, description? }` | Create a new team |
-| `teams.join` | `{ teamCode }` | Join a team via invite code |
-| `teams.updateName` | `{ teamId, newName }` | Rename a team |
-| `teams.delete` | `teamId` | Delete a team |
-| `teams.addAdmin` | `{ teamId, userId }` | Promote member to admin |
-| `teams.removeAdmin` | `{ teamId, userId }` | Demote admin to member |
-| `teams.removeMember` | `{ teamId, userId }` | Remove a team member |
-| `teams.invite` | `{ teamId, email }` | Invite user by email |
-| `teams.setMemberPassword` | `{ teamId, userId, newPassword }` | Set member password |
-
-### Tickets
-
-| Method | Args | Description |
-| ----------------------- | ---------------------------------------------------- | ---------------------------- |
-| `tickets.create` | `{ teamId, title, github?, accumulatedTime? }` | Create a ticket |
-| `tickets.update` | `{ ticketId, updates }` | Update ticket fields |
-| `tickets.delete` | `ticketId` | Delete a ticket |
-| `tickets.start` | `{ ticketId, now }` | Start ticket timer |
-| `tickets.stop` | `{ ticketId, now }` | Stop ticket timer |
-| `tickets.batchUpdateStatus` | `{ ticketIds, status, teamId }` | Batch update ticket status |
-| `tickets.assign` | `{ ticketId, assignedToUserId }` | Assign ticket to user |
-
-### Messages
-
-| Method | Args | Description |
-| --------------- | ---------------------------------------------- | -------------------- |
-| `messages.send` | `{ teamId, toUserId, text, adminId, ticketId? }` | Send a direct message |
-
-### Profile
-
-| Method | Args | Description |
-| ---------------- | --------------------------------------- | ------------------- |
-| `profile.update` | `{ displayName?, bio?, website? }` | Update user profile |
-
## Styling & Theming
- **Tailwind CSS 4** with Oxide (Lightning CSS) engine
- Minimal custom CSS in `client/styles.css` (font smoothing + resets)
- Dark mode via `data-theme` attribute + `dark` class
- Theme persisted in `localStorage` using shared `THEME_KEY` constant
-- SSR inline script prevents flash of wrong theme
## Production
```bash
-meteor build ../build --directory
-cd ../build/bundle
-npm install --production
-PORT=3000 MONGO_URL="mongodb://..." ROOT_URL="https://..." MAIL_URL="smtp://..." node main.js
+npm run build
+# Serve the dist/ folder with any static host (Nginx, Caddy, Vercel, etc.)
+# Set VITE_TIMECORE_URL to your production timecore URL at build time:
+VITE_TIMECORE_URL=https://api.yourdomain.com npm run build
```
-Add a reverse proxy (Nginx / Caddy) for TLS and compression.
+The backend (timecore) is a separate Fastify service β see [timecore README](../timecore/README.md) for deployment.
## License
diff --git a/backend b/backend
new file mode 160000
index 000000000..ba4c4a2f4
--- /dev/null
+++ b/backend
@@ -0,0 +1 @@
+Subproject commit ba4c4a2f4cab865c6c0712c0fbae4a44c5c3b6f6
diff --git a/client/main.html b/client/main.html
index f8ef63990..200481c3e 100644
--- a/client/main.html
+++ b/client/main.html
@@ -5,5 +5,16 @@
every route gets the correct SEO content without duplication.
-->
+
+
diff --git a/client/main.tsx b/client/main.tsx
index 647f3d33e..54d78292a 100644
--- a/client/main.tsx
+++ b/client/main.tsx
@@ -1,41 +1,28 @@
import './styles.css';
-import '../imports/startup/client';
-import { Meteor } from 'meteor/meteor';
-import { useTracker } from 'meteor/react-meteor-data';
-import React, { useEffect, useState } from 'react';
+import React from 'react';
import { createRoot } from 'react-dom/client';
import { InboxPage } from '../imports/features/inbox/InboxPage';
+import { SessionProvider, useSession } from '../imports/lib/useSession';
import { AppLayout } from '../imports/ui/AppLayout';
import { LoginForm } from '../imports/ui/LoginForm';
-/** Must match `imports/startup/ssr.tsx` query β initialMode mapping for /app hydration. */
-function getSsrMatchedAuthMode(): 'login' | 'signup' | 'reset' {
- if (typeof window === 'undefined') return 'login';
- const m = new URLSearchParams(window.location.search).get('mode');
- if (m === 'signup') return 'signup';
- if (m === 'reset') return 'reset';
- return 'login';
-}
-
// βββ App (client-side rendered, /app and all non-root routes) βββββββββββββββββ
const App: React.FC = () => {
- const user = useTracker(() => Meteor.user());
- const userId = useTracker(() => Meteor.userId());
- const loggingIn = useTracker(() => Meteor.loggingIn());
+ const { user, loading } = useSession();
- const [authUiReady, setAuthUiReady] = useState(false);
- useEffect(() => {
- setAuthUiReady(true);
- }, []);
+ // If a reset token is present in the URL, show the reset-confirm form
+ // regardless of auth state (so users can reset even if cookies are stale).
+ const resetToken =
+ typeof window !== 'undefined' ? new URLSearchParams(window.location.search).get('token') : null;
- if (!authUiReady) {
- return
;
+ if (resetToken) {
+ return
;
}
- if (loggingIn || (userId && !user)) {
+ if (loading) {
return (
Loadingβ¦
@@ -46,25 +33,22 @@ const App: React.FC = () => {
if (!user) return
;
return
;
};
-// βββ Entry point ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-Meteor.startup(() => {
- const el = document.getElementById('root');
- if (!el) return;
+// βββ Entry point ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
+const el = document.getElementById('root');
+if (el) {
if (window.location.pathname === '/') {
// Root redirects to /app (login or dashboard depending on auth state).
window.location.replace('/app');
- return;
} else if (window.location.pathname === '/inbox') {
- // Dev inbox β no auth required, no SSR to hydrate.
+ // Dev inbox β no auth required.
createRoot(el).render(
);
- } else if (window.location.pathname.startsWith('/app')) {
- // SSR sends a loading placeholder (not a full React tree), so use
- // createRoot β hydrateRoot would throw a hydration mismatch.
- createRoot(el).render(
);
} else {
- // Unknown routes β no SSR content to hydrate, mount fresh.
- createRoot(el).render(
);
+ createRoot(el).render(
+
+
+ ,
+ );
}
-});
+}
diff --git a/client/styles.css b/client/styles.css
index b35a9f6a8..22577f76c 100644
--- a/client/styles.css
+++ b/client/styles.css
@@ -1,5 +1,13 @@
@import '@mieweb/ui/brands/bluehive.css' layer(theme);
@import 'tailwindcss';
+
+/* Prevent white flash before React mounts β matches AppLayout bg classes */
+html {
+ background-color: #fafafa; /* neutral-50 */
+}
+html[data-theme='dark'] {
+ background-color: #0a0a0a; /* neutral-950 */
+}
@source "../node_modules/@mieweb/ui/dist";
@custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *));
diff --git a/eslint.config.mjs b/eslint.config.mjs
index 53efd11b9..9f6f23400 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -62,7 +62,10 @@ export default [
'prettier/prettier': 'off',
'simple-import-sort/imports': 'off',
'no-undef': 'off',
- '@typescript-eslint/no-unused-vars': ['error', { varsIgnorePattern: '^_', argsIgnorePattern: '^_', caughtErrorsIgnorePattern: '^_' }],
+ '@typescript-eslint/no-unused-vars': [
+ 'error',
+ { varsIgnorePattern: '^_', argsIgnorePattern: '^_', caughtErrorsIgnorePattern: '^_' },
+ ],
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/ban-ts-comment': 'error',
},
diff --git a/imports/features/auth/api.ts b/imports/features/auth/api.ts
index bef6e4b38..aaa75918b 100644
--- a/imports/features/auth/api.ts
+++ b/imports/features/auth/api.ts
@@ -1,98 +1,8 @@
-import { Accounts } from 'meteor/accounts-base';
-import { Meteor } from 'meteor/meteor';
-import { DDPRateLimiter } from 'meteor/ddp-rate-limiter';
-
-import { signupSchema, updateProfileSchema, resetPasswordSchema } from './schema';
-
-// βββ Methods ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-
-Meteor.methods({
- async createUserAccount(data: {
- email: string;
- password: string;
- firstName: string;
- lastName: string;
- }) {
- const result = signupSchema.safeParse(data);
- if (!result.success)
- throw new Meteor.Error('validation', result.error.issues[0]?.message ?? 'Invalid input');
-
- const { email, password, firstName, lastName } = result.data;
-
- try {
- const userId = Accounts.createUser({
- email,
- password,
- profile: { firstName, lastName },
- });
- return userId;
- } catch (err: unknown) {
- const message = err instanceof Meteor.Error ? err.reason : 'Failed to create user';
- throw new Meteor.Error('server-error', message ?? 'Failed to create user');
- }
- },
-
- async updateUserProfile(data: { firstName: string; lastName: string }) {
- if (!this.userId) throw new Meteor.Error('not-authorized');
-
- const result = updateProfileSchema.safeParse(data);
- if (!result.success)
- throw new Meteor.Error('validation', result.error.issues[0]?.message ?? 'Invalid input');
-
- const { firstName, lastName } = result.data;
-
- await Meteor.users.updateAsync(this.userId, {
- $set: {
- 'profile.firstName': firstName,
- 'profile.lastName': lastName,
- },
- });
- return true;
- },
-
- async resetPasswordWithTeamCode(data: {
- email: string;
- teamCode: string;
- newPassword: string;
- }) {
- const result = resetPasswordSchema.safeParse(data);
- if (!result.success)
- throw new Meteor.Error('validation', result.error.issues[0]?.message ?? 'Invalid input');
-
- const { email, teamCode, newPassword } = result.data;
-
- // Dynamic import to avoid circular dependency β Teams may not exist yet during startup
- const { Teams } = await import('../teams/api');
-
- const user = await Accounts.findUserByEmail(email);
- if (!user) throw new Meteor.Error('not-found', 'User not found');
-
- const team = await Teams.findOneAsync({ code: teamCode });
- if (!team) throw new Meteor.Error('invalid-code', 'Invalid team code');
-
- const isMember =
- (team.members || []).includes(user._id) ||
- (team.admins || []).includes(user._id);
- if (!isMember) throw new Meteor.Error('forbidden', 'User is not in this team');
-
- if (typeof Accounts.setPasswordAsync === 'function') {
- await Accounts.setPasswordAsync(user._id, newPassword, { logout: false });
- } else {
- Accounts.setPassword(user._id, newPassword, { logout: false });
- }
- return true;
- },
-});
-
-// βββ Rate limiting ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-
-const AUTH_METHODS = ['createUserAccount', 'updateUserProfile', 'resetPasswordWithTeamCode'];
-
-DDPRateLimiter.addRule(
- {
- name: (n) => AUTH_METHODS.includes(n),
- userId: () => true,
- },
- 10,
- 60_000,
-);
+/**
+ * Auth feature β server methods removed in Phase 2.
+ *
+ * createUserAccount and resetPasswordWithTeamCode β timecore better-auth.
+ * updateUserProfile β PUT /v1/me/profile (timecore Phase 2).
+ *
+ * Archived originals: .attic/imports/features/auth/api.ts
+ */
diff --git a/imports/features/clock/ClockPage.tsx b/imports/features/clock/ClockPage.tsx
index 8fd7ce20d..28a7632f9 100644
--- a/imports/features/clock/ClockPage.tsx
+++ b/imports/features/clock/ClockPage.tsx
@@ -18,8 +18,6 @@ import {
faXmark,
} from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
-import { Meteor } from 'meteor/meteor';
-import { useFind, useSubscribe } from 'meteor/react-meteor-data';
import {
Badge,
Button,
@@ -38,17 +36,15 @@ import {
Spinner,
Text,
} from '@mieweb/ui';
-import React, { useCallback, useMemo, useState } from 'react';
+import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { useTeam } from '../../lib/TeamContext';
import { formatTimer, formatDuration } from '../../lib/timeUtils';
-import { useMethod } from '../../lib/useMethod';
-import { Tickets } from '../tickets/api';
+import { clockApi, ticketApi, type Ticket } from '../../lib/api';
// βββ ClockPage ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
export const ClockPage: React.FC = () => {
- const userId = Meteor.userId();
const {
teams,
selectedTeamId,
@@ -56,23 +52,27 @@ export const ClockPage: React.FC = () => {
activeClockEvent,
currentTime,
teamsReady,
+ refetchClock,
} = useTeam();
- // Subscribe to tickets for the selected team
- const teamIds = useMemo(() => (selectedTeamId ? [selectedTeamId] : []), [selectedTeamId]);
- useSubscribe('teamTickets', teamIds);
+ // Tickets for the selected team
+ const [allTickets, setAllTickets] = useState
([]);
- const allTickets = useFind(
- () => Tickets.find({ teamId: selectedTeamId ?? '__none__' }),
- [selectedTeamId],
- );
+ useEffect(() => {
+ if (!selectedTeamId) {
+ setAllTickets([]);
+ return;
+ }
+ ticketApi
+ .getTickets(selectedTeamId)
+ .then(setAllTickets)
+ .catch(() => {});
+ }, [selectedTeamId]);
- // Methods
- const clockStart = useMethod<[{ teamId: string }], string>('clock.start');
- const clockStop = useMethod<[{ teamId: string; youtubeShortLink?: string }]>('clock.stop');
- const addTicketToEvent = useMethod<[{ clockEventId: string; ticketId: string; now: number }]>('clock.addTicket');
- const stopTicketInEvent = useMethod<[{ clockEventId: string; ticketId: string; now: number }]>('clock.stopTicket');
- const createTicket = useMethod<[{ teamId: string; title: string }], string>('tickets.create');
+ // Loading states
+ const [clockInLoading, setClockInLoading] = useState(false);
+ const [clockOutLoading, setClockOutLoading] = useState(false);
+ const [createTicketLoading, setCreateTicketLoading] = useState(false);
// UI state
const [showYoutubeModal, setShowYoutubeModal] = useState(false);
@@ -89,8 +89,14 @@ export const ClockPage: React.FC = () => {
const handleClockIn = useCallback(async () => {
if (!selectedTeamId) return;
- await clockStart.call({ teamId: selectedTeamId });
- }, [selectedTeamId, clockStart]);
+ setClockInLoading(true);
+ try {
+ await clockApi.start(selectedTeamId);
+ await refetchClock();
+ } finally {
+ setClockInLoading(false);
+ }
+ }, [selectedTeamId, refetchClock]);
const handleClockOut = useCallback(() => {
setShowYoutubeModal(true);
@@ -98,34 +104,49 @@ export const ClockPage: React.FC = () => {
const confirmClockOut = useCallback(async () => {
if (!selectedTeamId) return;
- const link = youtubeLink.trim();
- await clockStop.call({ teamId: selectedTeamId, youtubeShortLink: link || undefined });
- setShowYoutubeModal(false);
- setYoutubeLink('');
- }, [selectedTeamId, clockStop, youtubeLink]);
+ setClockOutLoading(true);
+ try {
+ const link = youtubeLink.trim();
+ await clockApi.stop(selectedTeamId, link || undefined);
+ await refetchClock();
+ setShowYoutubeModal(false);
+ setYoutubeLink('');
+ } finally {
+ setClockOutLoading(false);
+ }
+ }, [selectedTeamId, refetchClock, youtubeLink]);
const handleStartTicket = useCallback(
async (ticketId: string) => {
- if (!activeClockEvent?._id) return;
- await addTicketToEvent.call({ clockEventId: activeClockEvent._id, ticketId, now: Date.now() });
+ if (!activeClockEvent?.id) return;
+ await clockApi.addTicket(activeClockEvent.id, ticketId, Date.now());
+ await refetchClock();
},
- [activeClockEvent, addTicketToEvent],
+ [activeClockEvent, refetchClock],
);
const handleStopTicket = useCallback(
async (ticketId: string) => {
- if (!activeClockEvent?._id) return;
- await stopTicketInEvent.call({ clockEventId: activeClockEvent._id, ticketId, now: Date.now() });
+ if (!activeClockEvent?.id) return;
+ await clockApi.stopTicket(activeClockEvent.id, ticketId, Date.now());
+ await refetchClock();
},
- [activeClockEvent, stopTicketInEvent],
+ [activeClockEvent, refetchClock],
);
const handleCreateTicket = useCallback(async () => {
if (!newTicketTitle.trim() || !selectedTeamId) return;
- await createTicket.call({ teamId: selectedTeamId, title: newTicketTitle.trim() });
- setNewTicketTitle('');
- setShowNewTicket(false);
- }, [newTicketTitle, selectedTeamId, createTicket]);
+ setCreateTicketLoading(true);
+ try {
+ await ticketApi.createTicket({ teamId: selectedTeamId, title: newTicketTitle.trim() });
+ const updated = await ticketApi.getTickets(selectedTeamId);
+ setAllTickets(updated);
+ setNewTicketTitle('');
+ setShowNewTicket(false);
+ } finally {
+ setCreateTicketLoading(false);
+ }
+ }, [newTicketTitle, selectedTeamId]);
// Tickets in the active clock event
const activeTicketIds = useMemo(
@@ -135,14 +156,14 @@ export const ClockPage: React.FC = () => {
// Available tickets not yet in the session
const availableTickets = useMemo(
- () => allTickets.filter((t) => !activeTicketIds.has(t._id!) && t.createdBy === userId),
- [allTickets, activeTicketIds, userId],
+ () => allTickets.filter((t) => !activeTicketIds.has(t.id)),
+ [allTickets, activeTicketIds],
);
const teamOptions = useMemo(
() =>
teams.map((t) => ({
- value: t._id!,
+ value: t.id,
label: t.isPersonal ? 'Personal' : t.name,
})),
[teams],
@@ -176,7 +197,12 @@ export const ClockPage: React.FC = () => {
{activeClockEvent ? (
<>
-
+
Session Active
@@ -187,13 +213,15 @@ export const ClockPage: React.FC = () => {
- Tap to clock out
+
+ Tap to clock out
+
>
) : (
<>
@@ -204,13 +232,15 @@ export const ClockPage: React.FC = () => {
- Tap to clock in
+
+ Tap to clock in
+
>
)}
@@ -245,14 +275,17 @@ export const ClockPage: React.FC = () => {
variant="primary"
size="sm"
onClick={handleCreateTicket}
- isLoading={createTicket.loading}
+ isLoading={createTicketLoading}
>
Add
{ setShowNewTicket(false); setNewTicketTitle(''); }}
+ onClick={() => {
+ setShowNewTicket(false);
+ setNewTicketTitle('');
+ }}
aria-label="Cancel"
>
@@ -264,7 +297,7 @@ export const ClockPage: React.FC = () => {
{activeClockEvent.tickets.map((ct) => {
- const ticket = allTickets.find((t) => t._id === ct.ticketId);
+ const ticket = allTickets.find((t) => t.id === ct.ticketId);
const isRunning = !!ct.startTimestamp;
const elapsed = isRunning
? ct.accumulatedTime + Math.floor((currentTime - ct.startTimestamp!) / 1000)
@@ -275,7 +308,9 @@ export const ClockPage: React.FC = () => {
(isRunning ? handleStopTicket(ct.ticketId) : handleStartTicket(ct.ticketId))}
+ onClick={() =>
+ isRunning ? handleStopTicket(ct.ticketId) : handleStartTicket(ct.ticketId)
+ }
className={
isRunning
? 'rounded-full bg-amber-100 text-amber-600 dark:bg-amber-900/40 dark:text-amber-400'
@@ -300,7 +335,11 @@ export const ClockPage: React.FC = () => {
)}
-
+
{formatDuration(elapsed)}
@@ -312,14 +351,16 @@ export const ClockPage: React.FC = () => {
{/* Add existing ticket */}
{availableTickets.length > 0 && (
-
Add existing ticket:
+
+ Add existing ticket:
+
{availableTickets.slice(0, 5).map((t) => (
handleStartTicket(t._id!)}
+ onClick={() => handleStartTicket(t.id)}
>
{t.title}
@@ -362,8 +403,10 @@ export const ClockPage: React.FC = () => {
/>
- Skip
-
+
+ Skip
+
+
Clock Out
diff --git a/imports/features/clock/TimesheetPage.tsx b/imports/features/clock/TimesheetPage.tsx
index f6688ffdd..bc9e0c274 100644
--- a/imports/features/clock/TimesheetPage.tsx
+++ b/imports/features/clock/TimesheetPage.tsx
@@ -6,9 +6,7 @@
* β’ Session list with date, times, duration, team name, tickets
* β’ Summary stats (total hours, sessions, avg, working days)
*/
-import {
- faCalendar
-} from '@fortawesome/free-solid-svg-icons';
+import { faCalendar } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
Alert,
@@ -29,27 +27,15 @@ import {
TableRow,
Text,
} from '@mieweb/ui';
-import { Meteor } from 'meteor/meteor';
import React, { useCallback, useEffect, useState } from 'react';
import { useTeam } from '../../lib/TeamContext';
import { formatDuration, formatTime, formatDate, toDateString } from '../../lib/timeUtils';
-import { useMethod } from '../../lib/useMethod';
-
-interface TimesheetSession {
- id: string;
- date: string;
- startTime: Date;
- endTime: Date | null;
- duration: number | null;
- isActive: boolean;
- teamName: string | null;
- teamId: string;
- accumulatedTime: number;
-}
+import { clockApi, type ClockEvent } from '../../lib/api';
+import { useSession } from '../../lib/useSession';
interface TimesheetData {
- sessions: TimesheetSession[];
+ sessions: ClockEvent[];
summary: {
totalSeconds: number;
totalSessions: number;
@@ -94,23 +80,18 @@ function getDateRange(preset: Preset): [Date, Date] {
}
export const TimesheetPage: React.FC = () => {
- const userId = Meteor.userId();
- const { teamsReady } = useTeam();
+ const { user } = useSession();
+ const { teamsReady, teams } = useTeam();
const [preset, setPreset] = useState
('week');
const [customStart, setCustomStart] = useState('');
const [customEnd, setCustomEnd] = useState('');
-
- const getTimesheet = useMethod<
- [{ userId: string; startDate: string; endDate: string }],
- TimesheetData
- >('clock.getTimesheetData');
-
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState(null);
const [data, setData] = useState(null);
const fetchData = useCallback(async () => {
- if (!userId) return;
-
+ if (!user?.id) return;
let startDate: string;
let endDate: string;
@@ -124,16 +105,20 @@ export const TimesheetPage: React.FC = () => {
endDate = toDateString(e);
}
+ setLoading(true);
+ setError(null);
try {
- const result = await getTimesheet.call({ userId, startDate, endDate });
+ const result = await clockApi.getTimesheet(user?.id ?? '', startDate, endDate);
setData(result);
- } catch {
- // Error is in getTimesheet.error
+ } catch (e) {
+ setError(e instanceof Error ? e.message : 'Failed to load timesheet');
+ } finally {
+ setLoading(false);
}
- }, [userId, preset, customStart, customEnd, getTimesheet]);
+ }, [user?.id, preset, customStart, customEnd]);
useEffect(() => {
- fetchData();
+ void fetchData();
}, [preset]);
const presets: { key: Preset; label: string }[] = [
@@ -190,8 +175,8 @@ export const TimesheetPage: React.FC = () => {
variant="primary"
size="sm"
onClick={fetchData}
- disabled={getTimesheet.loading || !customStart || !customEnd}
- isLoading={getTimesheet.loading}
+ disabled={loading || !customStart || !customEnd}
+ isLoading={loading}
loadingText="Applyingβ¦"
>
Apply
@@ -202,36 +187,60 @@ export const TimesheetPage: React.FC = () => {
{/* Summary stats */}
{data && (
-
- Total Hours
- {formatDuration(data.summary.totalSeconds)}
-
-
- Sessions
- {data.summary.totalSessions}
-
-
- Avg Session
- {formatDuration(data.summary.averageSessionSeconds)}
-
-
- Working Days
- {data.summary.workingDays}
-
+
+
+
+ Total Hours
+
+
+ {formatDuration(data.summary.totalSeconds)}
+
+
+
+
+
+
+ Sessions
+
+
+ {data.summary.totalSessions}
+
+
+
+
+
+
+ Avg Session
+
+
+ {formatDuration(data.summary.averageSessionSeconds)}
+
+
+
+
+
+
+ Working Days
+
+
+ {data.summary.workingDays}
+
+
+
)}
{/* Loading */}
- {getTimesheet.loading && (
+ {loading && (
)}
{/* Error */}
- {getTimesheet.error && (
+ {error && (
- {getTimesheet.error}
+ {error}
)}
@@ -254,36 +263,54 @@ export const TimesheetPage: React.FC = () => {
- {data.sessions.map((s) => (
-
- {formatDate(new Date(s.startTime), true)}
- {formatTime(new Date(s.startTime))}
- {s.endTime ? formatTime(new Date(s.endTime)) : 'β'}
- {s.duration ? formatDuration(s.duration) : 'β'}
- {s.teamName ?? 'β'}
-
- {s.isActive ? (
-
-
- Active
-
- ) : (
- Completed
- )}
-
-
- ))}
+ {data.sessions.map((s) => {
+ const startTime = new Date(s.startTimestamp);
+ const endTime = s.endTime ? new Date(s.endTime) : null;
+ const duration = endTime
+ ? Math.floor((endTime.getTime() - startTime.getTime()) / 1000)
+ : null;
+ const isActive = !s.endTime;
+ const teamName = teams.find((t) => t.id === s.teamId)?.name ?? s.teamId;
+ return (
+
+ {formatDate(startTime, true)}
+ {formatTime(startTime)}
+ {endTime ? formatTime(endTime) : 'β'}
+
+ {duration ? formatDuration(duration) : 'β'}
+
+ {teamName}
+
+ {isActive ? (
+
+
+ Active
+
+ ) : (
+
+ Completed
+
+ )}
+
+
+ );
+ })}