From 5176ddda63857cad469db6f634c77825c063bce0 Mon Sep 17 00:00:00 2001 From: Michael Fisher Date: Mon, 20 Apr 2026 13:48:46 -0400 Subject: [PATCH 01/26] chore: remove meteor-wormhole package symlink --- packages/meteor-wormhole | 1 - 1 file changed, 1 deletion(-) delete mode 120000 packages/meteor-wormhole diff --git a/packages/meteor-wormhole b/packages/meteor-wormhole deleted file mode 120000 index 83c21d0c0..000000000 --- a/packages/meteor-wormhole +++ /dev/null @@ -1 +0,0 @@ -/Volumes/Case/prj/timehuddle/wormhole/packages/meteor-wormhole \ No newline at end of file From 9724339527b8fa652c2d82f6f66dd6d90817e964 Mon Sep 17 00:00:00 2001 From: Michael Fisher Date: Mon, 20 Apr 2026 23:05:48 -0400 Subject: [PATCH 02/26] feat: add migration plan for transitioning from Meteor to Timecore --- .github/plans/timecore.md | 280 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 280 insertions(+) create mode 100644 .github/plans/timecore.md diff --git a/.github/plans/timecore.md b/.github/plans/timecore.md new file mode 100644 index 000000000..488538aa5 --- /dev/null +++ b/.github/plans/timecore.md @@ -0,0 +1,280 @@ +# Migration Plan: Meteor → Timecore + +Migrate timehuddle off Meteor entirely. Replace Meteor DDP, accounts, and collections with +the shared timecore backend (Fastify + better-auth + MongoDB). The result is a Meteor-free +React app that shares a universal codebase with future mobile (Capacitor / Expo / React Native). + +## Background + +**timecore** (`localhost:3001` in dev) is a Fastify + MongoDB service using better-auth for +email/password authentication. It already has `/v1/me` and `/v1/me/profile` +stubbed. Everything else needs to be added there as part of this migration. + +**timehuddle** currently uses: +- `meteor/accounts-base` for auth +- Meteor DDP (WebSockets) for 13 real-time publications +- `useTracker` / `useSubscribe` as the reactive data layer +- Meteor methods (35 total) as the mutation layer + +## Real-Time Replacement Strategy + +Meteor publications become one of two things in timecore: + +| Publication | Real-time need | Replace with | +|---|---|---| +| `userTeams`, `teamDetails`, `teamMembers` | Low | REST + refresh on action | +| `teamTickets` | Medium | REST + poll (5 s) or SSE | +| `clockEventsForTeams` | **High** — live dashboard | **SSE** `/v1/clock/live` | +| `messages.thread` | **High** — chat | **SSE** per thread | +| `notifications.inbox` | Medium | SSE or REST + poll | +| `clockEventsForUser` | Medium | REST + refresh on action | + +SSE (Server-Sent Events) is Fastify-native, works in browsers and React Native via `EventSource`, +and requires zero extra libraries. + +`useTracker` + `useSubscribe` are replaced by **TanStack Query (React Query)** which handles +caching, background refetch, optimistic updates, and SSE — and runs identically in React, +React Native, and Expo. + +--- + +## Phase 1 — Authentication + +**Effort:** 1–2 days +**Goal:** Replace `meteor/accounts-base` with better-auth. After this phase Meteor is only used +for data — auth is fully owned by timecore. + +### timehuddle changes +- [ ] Replace `LoginForm.tsx` to call `POST /api/auth/sign-in` and `POST /api/auth/sign-up` +- [ ] Add "Forgot password?" flow: submits email to `POST /api/auth/request-password-reset` +- [ ] Add reset-password landing: reads `?token=` from URL, submits new password to `POST /api/auth/reset-password` +- [ ] Replace `Meteor.user()` + `useTracker` with a `useSession()` hook (`GET /v1/me`) +- [ ] Replace `Meteor.logout()` with `POST /api/auth/sign-out` +- [ ] Remove `imports/features/auth/api.ts` +- [ ] Remove `imports/startup/server.ts` (Accounts.config, email hook) +- [ ] Update `client/main.tsx` — gate on `useSession()` instead of `Meteor.user()` + +### timecore changes +- [ ] Configure `sendResetPassword` email callback in `emailAndPassword` auth config — better-auth handles `POST /api/auth/request-password-reset` and `POST /api/auth/reset-password` automatically +- [ ] Setup Trusted Origins +--- + +## Phase 2 — Profile & User Lookups + +**Effort:** 1 day +**Goal:** Remove `Meteor.users` and the `userProfiles` Mongo collection; all user data lives in +timecore's `users` collection managed by better-auth. + +### timehuddle changes +- [ ] Replace `profile.update` Meteor method call → `PUT /v1/me/profile` +- [ ] Replace `Meteor.users` lookups (display names, avatars) → REST calls +- [ ] Remove `imports/features/profile/api.ts` server half +- [ ] Remove `imports/lib/userDisplayName.ts` Meteor dependency + +### timecore changes +- [ ] `GET /v1/users/:id` — single user lookup +- [ ] `GET /v1/users?ids=id1,id2,...` — batch lookup (capped at 200) +- [ ] `PUT /v1/me/profile` — already stubbed, implement write + +--- + +## Phase 3 — Teams & Notifications + +**Effort:** 2–3 days +**Goal:** Move all team management and notifications to timecore REST + SSE. + +### timehuddle changes +- [ ] Replace all 10 team Meteor methods with REST calls +- [ ] Replace `userTeams` / `teamMembers` publications with REST + stale-while-revalidate +- [ ] Replace `notifications.inbox` publication with SSE stream + REST for mark-read/delete +- [ ] Remove `imports/features/teams/api.ts` server half + +### timecore changes +- [ ] `GET /v1/teams` — teams for current user +- [ ] `POST /v1/teams` — create team +- [ ] `DELETE /v1/teams/:id` — delete team +- [ ] `PUT /v1/teams/:id/name` — rename +- [ ] `GET /v1/teams/:id/members` — member list with user details +- [ ] `POST /v1/teams/:id/invite` — invite by email +- [ ] `POST /v1/teams/:id/join` — join by code +- [ ] `DELETE /v1/teams/:id/members/:userId` — remove member +- [ ] `PUT /v1/teams/:id/members/:userId/role` — promote/demote admin +- [ ] `PUT /v1/teams/:id/members/:userId/password` — admin set member password +- [ ] `GET /v1/notifications` — paginated inbox +- [ ] `POST /v1/notifications/read` — mark all read +- [ ] `PATCH /v1/notifications/:id/read` — mark one read +- [ ] `DELETE /v1/notifications/:id` — delete one +- [ ] `GET /v1/notifications/stream` — SSE stream for new notifications + +--- + +## Phase 4 — Tickets + +**Effort:** 2 days +**Goal:** Move ticket CRUD and timer operations to timecore. + +### timehuddle changes +- [ ] Replace 6 ticket Meteor methods with REST calls +- [ ] Replace `teamTickets` / `adminTeamTickets` publications with REST + poll or SSE +- [ ] Remove `imports/features/tickets/api.ts` server half +- [ ] Admin ticket review page — team-admin view of all tickets across managed teams, with batch status update + +### timecore changes +- [ ] `GET /v1/tickets?teamId=` — list tickets for team +- [ ] `POST /v1/tickets` — create ticket +- [ ] `PUT /v1/tickets/:id` — update ticket +- [ ] `DELETE /v1/tickets/:id` — delete ticket +- [ ] `POST /v1/tickets/:id/start` — start timer +- [ ] `POST /v1/tickets/:id/stop` — stop timer +- [ ] `POST /v1/tickets/batch-status` — batch status update +- [ ] `PUT /v1/tickets/:id/assign` — assign to user + +--- + +## Phase 5 — Clock + +**Effort:** 2–3 days +**Goal:** Move clock in/out and timesheet to timecore. This phase has the highest real-time +requirement — the team dashboard shows live clock state for all members. + +### timehuddle changes +- [ ] Replace 7 clock Meteor methods with REST calls +- [ ] Replace `clockEventsForUser` publication with REST + refresh on action +- [ ] Replace `clockEventsForTeams` publication with **SSE** stream +- [ ] Remove `imports/features/clock/api.ts` server half +- [ ] Member Activity page — team-admin view of a specific member's clock history, tickets worked, and message thread + +### timecore changes +- [ ] `POST /v1/clock/start` — clock in +- [ ] `POST /v1/clock/stop` — clock out +- [ ] `POST /v1/clock/:id/ticket/start` — start ticket timer in clock event +- [ ] `POST /v1/clock/:id/ticket/stop` — stop ticket timer +- [ ] `PUT /v1/clock/:id/times` — admin adjust times +- [ ] `PUT /v1/clock/:id/youtube` — attach YouTube link +- [ ] `GET /v1/clock/timesheet` — query timesheet data +- [ ] `GET /v1/clock/live?teamIds=` — **SSE** — live clock state for teams + +--- + +## Phase 6 — Messages + +**Effort:** 1–2 days +**Goal:** Move the admin↔member messaging system to timecore with SSE for real-time delivery. + +### timehuddle changes +- [ ] Replace `messages.send` Meteor method with `POST /v1/messages` +- [ ] Replace `messages.thread` publication with **SSE** stream per thread +- [ ] Remove `imports/features/messages/api.ts` server half + +### timecore changes +- [ ] `GET /v1/messages?teamId=&adminId=&memberId=` — fetch thread +- [ ] `POST /v1/messages` — send message +- [ ] `GET /v1/messages/stream?threadId=` — **SSE** — live message delivery + +--- + +## Phase 7 — Push Notifications + +**Effort:** 1 day +**Goal:** Move VAPID/FCM handling to timecore. The existing `public/sw.js` is already +Meteor-independent and stays as-is. + +### timehuddle changes +- [ ] Replace `getVapidPublicKey`, `push.subscribe`, `push.unsubscribe` Meteor methods +- [ ] Remove `imports/server/push.ts` +- [ ] Remove `imports/lib/pushNotificationsClient.ts` Meteor dependency + +### timecore changes +- [ ] `GET /v1/push/vapid-key` — return public VAPID key +- [ ] `POST /v1/push/subscribe` — store subscription +- [ ] `DELETE /v1/push/subscribe` — remove subscription +- [ ] Move web-push + FCM sending logic from Meteor into timecore service + +--- + +## Phase 8 — GitHub Integration + +**Effort:** 1–2 days +**Goal:** Allow users to connect their GitHub account via OAuth, browse repos/issues, and link GitHub issues to tickets — parity with timeharbor-legacy. + +### timehuddle changes +- [ ] GitHub OAuth connect button in Profile settings (opens popup, stores token on success) +- [ ] Ticket detail — "Link GitHub Issue" picker (search repos → issues) +- [ ] Display linked GitHub issue title/URL on ticket + +### timecore changes +- [ ] `GET /api/github/callback` — OAuth callback: exchange code for token, store on user record +- [ ] `POST /v1/github/connect` — initiate OAuth flow (returns authorization URL + state) +- [ ] `DELETE /v1/github/disconnect` — remove stored token +- [ ] `GET /v1/github/repos` — list user's repos (proxied through stored token) +- [ ] `GET /v1/github/repos/:owner/:repo/issues` — list open issues +- [ ] `GET /v1/github/status` — return whether current user has GitHub connected + +--- + +## Phase 9 — PulseVault Integration + +**Effort:** 1 day +**Goal:** Allow users to attach media to tickets via PulseCam app using a QR code/deeplink — parity with timeharbor-legacy. + +### timehuddle changes +- [ ] Ticket detail — "Attach Media" button that shows PulseVault QR code / deeplink +- [ ] Display attached media previews on ticket once uploaded + +### timecore changes +- [ ] `POST /v1/tickets/:id/pulse-upload` — get or create PulseVault draft (calls PulseVault API, caches result) +- [ ] `GET /v1/tickets/:id/pulse-upload` — return cached draft/deeplink for a ticket +- [ ] Store `pulseDrafts` records in MongoDB (mirrors legacy `PulseDrafts` collection) + +--- + +## Phase 10 — Rip Out Meteor + +**Effort:** 1 day +**Goal:** Remove the Meteor build system and all remaining Meteor packages. Replace the dev +server with Vite. The app becomes a plain React SPA. + +### timehuddle changes +- [ ] Add User Guide page (`/app/guide`) — static help/documentation, parity with legacy `/guide` +- [ ] Remove `server/` directory +- [ ] Remove `imports/startup/` directory +- [ ] Remove remaining `imports/features/*/api.ts` server sections +- [ ] Replace all `useTracker` + `useSubscribe` calls with TanStack Query hooks +- [ ] Replace `useMethod` utility with typed `fetch` wrappers (`imports/lib/api.ts`) +- [ ] Replace `meteor run` / Meteor build system with **Vite** +- [ ] Remove `.meteor/` directory and all `meteor/*` package imports +- [ ] Remove `@types/meteor` and meteor-related devDependencies +- [ ] Verify `public/sw.js` still registers correctly under Vite's static file serving + +### Validation +- [ ] `npm run build` succeeds with no Meteor references +- [ ] Auth flow works end-to-end with timecore +- [ ] All SSE streams connect and deliver events +- [ ] Push notifications subscribe and fire +- [ ] No `meteor/` imports remain (`grep -r "meteor/" src`) + +--- + +## Post-Migration: Mobile Path + +Once Meteor is removed the codebase is universally portable: + +| Target | Additional work | +|---|---| +| **PWA** | Add `manifest.json`, done — `sw.js` already exists | +| **Capacitor** | `npx cap init`, wrap existing React app, ~1 week | +| **Expo (React Native)** | Shared TanStack Query hooks + API layer, new native UI layer | + +better-auth supports cookie auth (web) and token auth (mobile) natively — no changes needed +to timecore when adding mobile clients. + +--- + +## Future — Needs Issues Filed + +These features exist in timeharbor-legacy but are not yet covered by any phase above. +File a GitHub issue for each before starting the affected phase. + +- [ ] **URL title fetch** — when a ticket is created with a reference URL, the server fetches the page title automatically (`extractUrlTitle` method). Needs a timecore endpoint (e.g. `POST /v1/util/extract-url-title`) and timehuddle ticket form integration. *(related: Phase 4)* +- [ ] **Ticket time history** — per-ticket time breakdown by configurable date range (today / yesterday / this week / this month / quarter / year / custom). Used in the ticket detail view (`getTicketTimeHistory` method). Needs a timecore endpoint (e.g. `GET /v1/tickets/:id/time-history?range=`) and timehuddle ticket detail UI. *(related: Phase 4)* +- [ ] **Auto clock-out background job** — server-side job that force-clocks-out any session running for 8+ consecutive hours (burnout prevention), fires push notifications to user and team admins. In legacy this is a `Meteor.setInterval` running every 60 seconds on the server. Needs a scheduled job in timecore (Node `setInterval` or a cron package) that replicates this logic. *(related: Phase 5)* From 3bf51a5915ffc2854ac8e3b721de0ae4b0b26e29 Mon Sep 17 00:00:00 2001 From: Michael Fisher Date: Tue, 21 Apr 2026 09:29:06 -0400 Subject: [PATCH 03/26] feat(auth): implement timecore authentication methods and session management - Added new API methods for user account creation, profile updates, and password resets. - Integrated timecore backend for authentication, replacing previous Meteor methods. - Introduced session context to manage user authentication state across the application. - Updated LoginForm component to handle new authentication flows including password reset requests. - Refactored SettingsPage and UserDropdown components to utilize session context for user data. - Enhanced email handling in development mode to capture unsent emails. - Configured email/password account settings and removed deprecated methods. - Updated SSR handling for login and signup modes. --- .attic/imports/features/auth/api.ts | 98 +++++ {imports => .attic/imports}/startup/server.ts | 0 .github/plans/timecore.md | 1 - client/main.tsx | 48 +- imports/features/auth/api.ts | 83 +--- imports/lib/api.ts | 101 +++++ imports/lib/useSession.tsx | 74 ++++ imports/startup/ssr.tsx | 2 +- imports/ui/LoginForm.tsx | 410 +++++++----------- imports/ui/SettingsPage.tsx | 23 +- imports/ui/UserDropdown.tsx | 17 +- server/main.ts | 1 - settings.json | 3 + 13 files changed, 496 insertions(+), 365 deletions(-) create mode 100644 .attic/imports/features/auth/api.ts rename {imports => .attic/imports}/startup/server.ts (100%) create mode 100644 imports/lib/api.ts create mode 100644 imports/lib/useSession.tsx diff --git a/.attic/imports/features/auth/api.ts b/.attic/imports/features/auth/api.ts new file mode 100644 index 000000000..bef6e4b38 --- /dev/null +++ b/.attic/imports/features/auth/api.ts @@ -0,0 +1,98 @@ +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, +); diff --git a/imports/startup/server.ts b/.attic/imports/startup/server.ts similarity index 100% rename from imports/startup/server.ts rename to .attic/imports/startup/server.ts diff --git a/.github/plans/timecore.md b/.github/plans/timecore.md index 488538aa5..54f51e545 100644 --- a/.github/plans/timecore.md +++ b/.github/plans/timecore.md @@ -56,7 +56,6 @@ for data — auth is fully owned by timecore. ### timecore changes - [ ] Configure `sendResetPassword` email callback in `emailAndPassword` auth config — better-auth handles `POST /api/auth/request-password-reset` and `POST /api/auth/reset-password` automatically -- [ ] Setup Trusted Origins --- ## Phase 2 — Profile & User Lookups diff --git a/client/main.tsx b/client/main.tsx index 647f3d33e..3b5771591 100644 --- a/client/main.tsx +++ b/client/main.tsx @@ -2,40 +2,31 @@ 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…

@@ -60,11 +51,16 @@ Meteor.startup(() => { // Dev inbox — no auth required, no SSR to hydrate. 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(); + createRoot(el).render( + + + , + ); } else { - // Unknown routes — no SSR content to hydrate, mount fresh. - createRoot(el).render(); + createRoot(el).render( + + + , + ); } }); diff --git a/imports/features/auth/api.ts b/imports/features/auth/api.ts index bef6e4b38..61040fc11 100644 --- a/imports/features/auth/api.ts +++ b/imports/features/auth/api.ts @@ -1,37 +1,18 @@ -import { Accounts } from 'meteor/accounts-base'; +/** + * Auth feature — remaining server methods for Phase 1. + * + * createUserAccount and resetPasswordWithTeamCode have been replaced by + * timecore (better-auth). Archived originals: .attic/imports/features/auth/api.ts + * + * updateUserProfile will be replaced by PUT /v1/me/profile in Phase 2. + */ import { Meteor } from 'meteor/meteor'; -import { DDPRateLimiter } from 'meteor/ddp-rate-limiter'; -import { signupSchema, updateProfileSchema, resetPasswordSchema } from './schema'; +import { updateProfileSchema } 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'); @@ -49,50 +30,4 @@ Meteor.methods({ }); 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, -); diff --git a/imports/lib/api.ts b/imports/lib/api.ts new file mode 100644 index 000000000..c80b98e17 --- /dev/null +++ b/imports/lib/api.ts @@ -0,0 +1,101 @@ +/** + * Typed fetch wrappers for the timecore backend. + * + * Base URL is read from Meteor.settings.public.timecoreUrl (set in settings.json), + * falling back to localhost:4000 for local development. + */ +import { Meteor } from 'meteor/meteor'; + +// ─── Config ─────────────────────────────────────────────────────────────────── + +export const TIMECORE_BASE_URL: string = + (Meteor.settings?.public as Record | undefined)?.timecoreUrl ?? + 'http://localhost:4000'; + +// ─── Types ──────────────────────────────────────────────────────────────────── + +export interface TimecoreUser { + id: string; + email: string; + name: string; + createdAt: string; + emailVerified: boolean; + image?: string | null; +} + +// ─── Base request ───────────────────────────────────────────────────────────── + +async function request(path: string, options: RequestInit = {}): Promise { + const res = await fetch(`${TIMECORE_BASE_URL}${path}`, { + credentials: 'include', + headers: { 'Content-Type': 'application/json', ...options.headers }, + ...options, + }); + + if (!res.ok) { + const body = await res.json().catch(() => ({})) as Record; + throw new Error( + (body.message as string | undefined) ?? + (body.error as string | undefined) ?? + `HTTP ${res.status}`, + ); + } + + return res.json() as Promise; +} + +// ─── Auth API ───────────────────────────────────────────────────────────────── + +export const authApi = { + /** Sign in — sets better-auth session cookie on success. */ + signIn: (email: string, password: string) => + request('/api/auth/sign-in/email', { + method: 'POST', + body: JSON.stringify({ email, password }), + }), + + /** Sign up — creates account. Does NOT auto-create session; call signIn after. */ + signUp: (email: string, password: string, name: string) => + request('/api/auth/sign-up/email', { + method: 'POST', + body: JSON.stringify({ email, password, name }), + }), + + /** Sign out — clears better-auth session cookie. */ + signOut: () => + request('/api/auth/sign-out', { method: 'POST' }), + + /** + * Request a password-reset email. + * @param redirectTo - URL to include in the email link as the callbackURL. + * better-auth will append ?token=TOKEN before redirecting. + */ + requestPasswordReset: (email: string, redirectTo: string) => + request('/api/auth/request-password-reset', { + method: 'POST', + body: JSON.stringify({ email, redirectTo }), + }), + + /** + * Reset password using the token from the reset-password email. + * @param token - from the ?token= query param on the reset-password landing page. + */ + resetPassword: (token: string, newPassword: string) => + request('/api/auth/reset-password', { + method: 'POST', + body: JSON.stringify({ token, newPassword }), + }), + + /** + * Fetch the currently authenticated user. + * Returns null on 401 (not authenticated), throws on other errors. + */ + getMe: async (): Promise<{ user: TimecoreUser } | null> => { + try { + return await request<{ user: TimecoreUser }>('/v1/me'); + } catch (err) { + if (err instanceof Error && err.message.startsWith('HTTP 401')) return null; + throw err; + } + }, +}; diff --git a/imports/lib/useSession.tsx b/imports/lib/useSession.tsx new file mode 100644 index 000000000..ef1d0f0f9 --- /dev/null +++ b/imports/lib/useSession.tsx @@ -0,0 +1,74 @@ +/** + * Session context — wraps the app and provides timecore auth state. + * + * Usage: + * wrap root with + * read auth state anywhere with useSession() + */ +import React, { + createContext, + useCallback, + useContext, + useEffect, + useState, +} from 'react'; + +import { authApi, type TimecoreUser } from './api'; + +// ─── Types ──────────────────────────────────────────────────────────────────── + +interface SessionState { + user: TimecoreUser | null; + loading: boolean; + /** Re-fetch session from timecore — call after sign-in / sign-up. */ + refetch: () => Promise; + /** Sign out from timecore and clear local session state. */ + signOut: () => Promise; +} + +// ─── Context ────────────────────────────────────────────────────────────────── + +const SessionContext = createContext({ + user: null, + loading: true, + refetch: async () => {}, + signOut: async () => {}, +}); + +// ─── Provider ───────────────────────────────────────────────────────────────── + +export const SessionProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => { + const [user, setUser] = useState(null); + const [loading, setLoading] = useState(true); + + const fetchSession = useCallback(async () => { + setLoading(true); + try { + const data = await authApi.getMe(); + setUser(data?.user ?? null); + } catch { + setUser(null); + } finally { + setLoading(false); + } + }, []); + + useEffect(() => { + fetchSession(); + }, [fetchSession]); + + const signOut = useCallback(async () => { + await authApi.signOut().catch(() => {}); + setUser(null); + }, []); + + return ( + + {children} + + ); +}; + +// ─── Hook ───────────────────────────────────────────────────────────────────── + +export const useSession = (): SessionState => useContext(SessionContext); diff --git a/imports/startup/ssr.tsx b/imports/startup/ssr.tsx index 21d58befc..c5611db88 100644 --- a/imports/startup/ssr.tsx +++ b/imports/startup/ssr.tsx @@ -151,7 +151,7 @@ onPageLoad((sink) => { // Unauthenticated visitors see the LoginForm. Authenticated users // will be swapped to AppLayout after hydration on the client. const mode = - query.mode === 'signup' ? 'signup' : query.mode === 'reset' ? 'reset' : 'login'; + query.mode === 'signup' ? 'signup' : query.mode === 'forgot' ? 'forgot' : 'login'; try { const html = renderToString(); sink.appendToHead( diff --git a/imports/ui/LoginForm.tsx b/imports/ui/LoginForm.tsx index 22da42b0a..b6e25b0e8 100644 --- a/imports/ui/LoginForm.tsx +++ b/imports/ui/LoginForm.tsx @@ -4,19 +4,19 @@ import { faShieldHalved, faUsers, faListCheck, - faFlask, } from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; -import { Meteor } from 'meteor/meteor'; -import React, { useEffect, useState } from 'react'; +import React, { useState } from 'react'; -import { useMethod } from '../lib/useMethod'; +import { authApi } from '../lib/api'; +import { useSession } from '../lib/useSession'; import { Button, Input, Text } from '@mieweb/ui'; import { ThemeToggle } from './ThemeToggle'; // ─── Types ──────────────────────────────────────────────────────────────────── -type AuthMode = 'login' | 'signup' | 'reset'; +/** login / signup / forgot = request reset email / reset-confirm = enter new password via token */ +type AuthMode = 'login' | 'signup' | 'forgot' | 'reset-confirm'; interface LoginFormProps { initialMode?: AuthMode; @@ -24,17 +24,20 @@ interface LoginFormProps { // ─── Helpers ────────────────────────────────────────────────────────────────── -function getMode(): AuthMode { +function getMode(resetTokenInUrl: boolean): AuthMode { + if (resetTokenInUrl) return 'reset-confirm'; if (typeof window === 'undefined') return 'login'; const params = new URLSearchParams(window.location.search); const m = params.get('mode'); if (m === 'signup') return 'signup'; - if (m === 'reset') return 'reset'; + if (m === 'forgot') return 'forgot'; return 'login'; } function setModeParam(mode: AuthMode) { const url = new URL(window.location.href); + // Remove any reset token when explicitly switching modes + url.searchParams.delete('token'); url.searchParams.set('mode', mode); window.history.replaceState(null, '', url.toString()); } @@ -50,35 +53,32 @@ const FEATURES = [ ] as const; export const LoginForm: React.FC = ({ initialMode }) => { - const [mode, setMode] = useState(initialMode ?? getMode()); + const session = useSession(); + + const resetToken = + typeof window !== 'undefined' + ? new URLSearchParams(window.location.search).get('token') ?? undefined + : undefined; + + const [mode, setMode] = useState(initialMode ?? getMode(!!resetToken)); const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [confirmPassword, setConfirmPassword] = useState(''); const [firstName, setFirstName] = useState(''); const [lastName, setLastName] = useState(''); - const [teamCode, setTeamCode] = useState(''); const [error, setError] = useState(null); const [loading, setLoading] = useState(false); - const [resetSuccess, setResetSuccess] = useState(false); - - const createUser = useMethod< - [{ email: string; password: string; firstName: string; lastName: string }], - string - >('createUserAccount'); - - const resetPassword = useMethod< - [{ email: string; teamCode: string; newPassword: string }], - boolean - >('resetPasswordWithTeamCode'); + const [successMessage, setSuccessMessage] = useState(null); const isSignup = mode === 'signup'; - const isReset = mode === 'reset'; + const isForgot = mode === 'forgot'; + const isResetConfirm = mode === 'reset-confirm'; const switchMode = (next: AuthMode) => { setMode(next); setModeParam(next); setError(null); - setResetSuccess(false); + setSuccessMessage(null); }; const handleLogin = async (e: React.FormEvent) => { @@ -86,14 +86,13 @@ export const LoginForm: React.FC = ({ initialMode }) => { if (!email || !password || loading) return; setLoading(true); setError(null); - Meteor.loginWithPassword(email.trim().toLowerCase(), password, (err) => { + try { + await authApi.signIn(email.trim().toLowerCase(), password); + await session.refetch(); + } catch (err: unknown) { + setError((err as Error).message || 'Login failed'); setLoading(false); - if (err) { - setError( - (err as Meteor.Error).reason || (err as Error).message || 'Login failed', - ); - } - }); + } }; const handleSignup = async (e: React.FormEvent) => { @@ -106,32 +105,36 @@ export const LoginForm: React.FC = ({ initialMode }) => { } setLoading(true); try { - await createUser.call({ - email: email.trim().toLowerCase(), - password, - firstName: firstName.trim(), - lastName: lastName.trim(), - }); - // Auto-login after signup - Meteor.loginWithPassword(email.trim().toLowerCase(), password, (err) => { - setLoading(false); - if (err) { - setError( - (err as Meteor.Error).reason || (err as Error).message || 'Login failed after signup', - ); - } - }); + const name = `${firstName.trim()} ${lastName.trim()}`.trim(); + await authApi.signUp(email.trim().toLowerCase(), password, name); + // Sign in immediately after signup to establish the session cookie + await authApi.signIn(email.trim().toLowerCase(), password); + await session.refetch(); } catch (err: unknown) { setLoading(false); - setError( - (err as Meteor.Error)?.reason || (err as Error)?.message || 'Signup failed', - ); + setError((err as Error).message || 'Signup failed'); } }; - const handleReset = async (e: React.FormEvent) => { + const handleForgot = async (e: React.FormEvent) => { e.preventDefault(); - if (loading) return; + if (!email || loading) return; + setLoading(true); + setError(null); + try { + const redirectTo = `${window.location.origin}/app`; + await authApi.requestPasswordReset(email.trim().toLowerCase(), redirectTo); + setSuccessMessage('Check your email for a reset link.'); + } catch (err: unknown) { + setError((err as Error).message || 'Request failed'); + } finally { + setLoading(false); + } + }; + + const handleResetConfirm = async (e: React.FormEvent) => { + e.preventDefault(); + if (!resetToken || loading) return; setError(null); if (password !== confirmPassword) { setError('Passwords do not match'); @@ -139,22 +142,30 @@ export const LoginForm: React.FC = ({ initialMode }) => { } setLoading(true); try { - await resetPassword.call({ - email: email.trim().toLowerCase(), - teamCode: teamCode.trim(), - newPassword: password, - }); - setResetSuccess(true); - setLoading(false); + await authApi.resetPassword(resetToken, password); + // Clear token from URL and go to login with success message + const url = new URL(window.location.href); + url.searchParams.delete('token'); + url.searchParams.set('mode', 'login'); + window.history.replaceState(null, '', url.toString()); + setMode('login'); + setPassword(''); + setConfirmPassword(''); + setSuccessMessage('Password reset successfully. You can now sign in.'); } catch (err: unknown) { + setError((err as Error).message || 'Password reset failed'); + } finally { setLoading(false); - setError( - (err as Meteor.Error)?.reason || (err as Error)?.message || 'Password reset failed', - ); } }; - const onSubmit = isReset ? handleReset : isSignup ? handleSignup : handleLogin; + const onSubmit = isResetConfirm + ? handleResetConfirm + : isForgot + ? handleForgot + : isSignup + ? handleSignup + : handleLogin; // ── Marketing panel (left) ────────────────────────────────────────────────── @@ -168,15 +179,15 @@ export const LoginForm: React.FC = ({ initialMode }) => {

{isSignup ? 'Start tracking in minutes' - : isReset + : isForgot || isResetConfirm ? 'Reset your password' : 'Welcome back'}

{isSignup ? 'Create your account and start tracking time with your team — real-time collaboration built in.' - : isReset - ? 'Use your team code to securely reset your password.' + : isForgot || isResetConfirm + ? 'Enter your email address and we\'ll send you a link to reset your password.' : 'Sign in to pick up where you left off. Your data syncs in real-time.'}

@@ -233,26 +244,30 @@ export const LoginForm: React.FC = ({ initialMode }) => {

{isSignup ? 'Create your account' - : isReset - ? 'Reset your password' - : 'Sign in to your account'} + : isForgot + ? 'Forgot your password?' + : isResetConfirm + ? 'Set a new password' + : 'Sign in to your account'}

{isSignup ? 'Enter your details to get started' - : isReset - ? 'Use your team code to verify your identity' - : 'Enter your email and password'} + : isForgot + ? 'Enter your email and we\'ll send a reset link' + : isResetConfirm + ? 'Enter and confirm your new password' + : 'Enter your email and password'}

{/* Form */}
- {resetSuccess ? ( + {successMessage ? (

- Password reset successfully! You can now sign in with your new password. + {successMessage}

)} - {/* Email */} - setEmail(e.target.value)} - type="email" - required - autoComplete="email" - inputMode="email" - spellCheck={false} - placeholder="you@example.com" - disabled={loading} - /> - - {/* Team code (reset only) */} - {isReset && ( + {/* Email (login / signup / forgot) */} + {!isResetConfirm && ( setTeamCode(e.target.value)} + label="Email address" + value={email} + onChange={(e) => setEmail(e.target.value)} + type="email" required - placeholder="ABCD1234" + autoComplete="email" + inputMode="email" + spellCheck={false} + placeholder="you@example.com" disabled={loading} /> )} - {/* Password */} - setPassword(e.target.value)} - type="password" - required - autoComplete={isSignup || isReset ? 'new-password' : 'current-password'} - placeholder="••••••••" - disabled={loading} - /> + {/* Password (login / signup / reset-confirm) */} + {!isForgot && ( + setPassword(e.target.value)} + type="password" + required + autoComplete={isSignup || isResetConfirm ? 'new-password' : 'current-password'} + placeholder="••••••••" + disabled={loading} + /> + )} - {/* Confirm password (signup + reset) */} - {(isSignup || isReset) && ( + {/* Confirm password (signup + reset-confirm) */} + {(isSignup || isResetConfirm) && ( = ({ initialMode }) => { > {isSignup ? 'Create account' - : isReset - ? 'Reset password' - : 'Sign in'} + : isForgot + ? 'Send reset link' + : isResetConfirm + ? 'Set new password' + : 'Sign in'} )}
- {/* Forgot password (login mode) */} + {/* Forgot password (login mode only) */} {mode === 'login' && (
)} - {/* Divider */} -
-
- or -
-
- - {/* Mode toggle */} -

- {isSignup ? ( - <> - Already have an account?{' '} - - - ) : ( - <> - Don't have an account?{' '} - - - )} -

- - {/* Dev persona picker — only in development */} - {Meteor.isDevelopment && } -
-
- - ); -}; - -// ─── Dev Persona Picker ─────────────────────────────────────────────────────── - -interface PersonaInfo { - key: string; - firstName: string; - lastName: string; - role: string; - description: string; - email: string; -} - -const DevPersonaPicker: React.FC = () => { - const [personas, setPersonas] = useState([]); - const [loading, setLoading] = useState(null); - const [error, setError] = useState(null); - - useEffect(() => { - Meteor.call('dev.personas', (err: Meteor.Error | null, result: PersonaInfo[]) => { - if (!err && result) setPersonas(result); - }); - }, []); - - const loginAs = (personaKey: string) => { - setLoading(personaKey); - setError(null); - Meteor.call( - 'dev.loginAs', - personaKey, - (err: Meteor.Error | null, result: { userId: string; token: string }) => { - if (err) { - setLoading(null); - setError(err.reason || 'Login failed'); - return; - } - Meteor.loginWithToken(result.token, (loginErr) => { - setLoading(null); - if (loginErr) { - setError((loginErr as Error).message || 'Token login failed'); - } - }); - }, - ); - }; - - if (personas.length === 0) return null; - - return ( -
-
- - Dev Quick Login -
- - {error && ( -

- {error} -

- )} - -
- {personas.map((p) => ( - + + ) : ( + <> + Don't have an account?{' '} + + + )}

+ + )} + + {/* Back to sign in (forgot / reset-confirm) */} + {(isForgot || isResetConfirm) && !successMessage && ( +
+
- {loading === p.key && ( - - - - - )} - - ))} + )} +
); diff --git a/imports/ui/SettingsPage.tsx b/imports/ui/SettingsPage.tsx index 3e97245b6..a754cd513 100644 --- a/imports/ui/SettingsPage.tsx +++ b/imports/ui/SettingsPage.tsx @@ -28,8 +28,6 @@ import { Select, Text, } from '@mieweb/ui'; -import { Meteor } from 'meteor/meteor'; -import { useTracker } from 'meteor/react-meteor-data'; import React, { useCallback, useEffect, useState } from 'react'; import { @@ -40,6 +38,7 @@ import { } from '../lib/pushNotificationsClient'; import { useBrand, BRANDS } from '../lib/useBrand'; import { useMethod } from '../lib/useMethod'; +import { useSession } from '../lib/useSession'; import { useTheme } from '../lib/useTheme'; // ─── Primitives ─────────────────────────────────────────────────────────────── @@ -244,12 +243,20 @@ const PushNotificationsSettings: React.FC = () => { // ─── SettingsPage ───────────────────────────────────────────────────────────── export const SettingsPage: React.FC = () => { - const user = useTracker(() => Meteor.user()); - const profile = user?.profile as { firstName?: string; lastName?: string; email?: string } | undefined; - const email: string | undefined = user?.emails?.[0]?.address ?? profile?.email; + const { user, signOut } = useSession(); + const email = user?.email; + + // Split display name into first/last for the edit fields + const [firstName, setFirstName] = useState(''); + const [lastName, setLastName] = useState(''); + useEffect(() => { + if (user?.name) { + const [first = '', ...rest] = user.name.split(' '); + setFirstName(first); + setLastName(rest.join(' ')); + } + }, [user?.name]); - const [firstName, setFirstName] = useState(profile?.firstName ?? ''); - const [lastName, setLastName] = useState(profile?.lastName ?? ''); const [saved, setSaved] = useState(false); const updateProfile = useMethod<[{ firstName: string; lastName: string }]>('updateUserProfile'); @@ -332,7 +339,7 @@ export const SettingsPage: React.FC = () => { variant="danger" size="sm" leftIcon={} - onClick={() => Meteor.logout()} + onClick={() => void signOut()} > Sign out diff --git a/imports/ui/UserDropdown.tsx b/imports/ui/UserDropdown.tsx index bd18d537e..27610b0e3 100644 --- a/imports/ui/UserDropdown.tsx +++ b/imports/ui/UserDropdown.tsx @@ -12,29 +12,26 @@ import { DropdownSeparator, Text, } from '@mieweb/ui'; -import { Meteor } from 'meteor/meteor'; -import { useTracker } from 'meteor/react-meteor-data'; import React, { useCallback } from 'react'; +import { useSession } from '../lib/useSession'; import { useRouter } from './router'; // ─── UserDropdown ───────────────────────────────────────────────────────────── export const UserDropdown: React.FC = () => { - const user = useTracker(() => Meteor.user()); - const email: string | undefined = - user?.emails?.[0]?.address ?? (user?.profile as { email?: string } | undefined)?.email; + const { user, signOut } = useSession(); + const email = user?.email; const { navigate } = useRouter(); const handleLogout = useCallback(() => { - Meteor.logout(); - }, []); + void signOut(); + }, [signOut]); const handleProfile = useCallback(() => { - const uid = Meteor.userId(); - if (uid) navigate(`/app/profile/${uid}`); - }, [navigate]); + if (user?.id) navigate(`/app/profile/${user.id}`); + }, [navigate, user?.id]); const displayName = email ?? 'Account'; const truncated = displayName.length > 22 ? `${displayName.slice(0, 20)}…` : displayName; diff --git a/server/main.ts b/server/main.ts index 9cd6085e9..fa7a1a769 100644 --- a/server/main.ts +++ b/server/main.ts @@ -1,4 +1,3 @@ -import '../imports/startup/server'; import '../imports/startup/seed'; // E2E seed data (only when ALLOW_E2E_SEED is set) import '../imports/startup/ssr'; // SSR: onPageLoad renders landing page & injects SEO // ─── Features ───────────────────────────────────────────────────────────────── diff --git a/settings.json b/settings.json index ba842ea5d..49e0babce 100644 --- a/settings.json +++ b/settings.json @@ -1,4 +1,7 @@ { + "public": { + "timecoreUrl": "http://localhost:4000" + }, "packages": { "mongo": { "reactivity": ["changeStreams", "oplog", "polling"] From 071680a1a540217a220840f1d2891482f5ee6315 Mon Sep 17 00:00:00 2001 From: Michael Fisher Date: Tue, 21 Apr 2026 10:24:04 -0400 Subject: [PATCH 04/26] feat: migrate user authentication and profile management to timecore API --- .github/plans/timecore.md | 34 ++++----- imports/features/auth/api.ts | 33 ++------- imports/features/profile/ProfilePage.tsx | 83 ++++++++++++---------- imports/features/profile/UsernameBadge.tsx | 22 +++--- imports/features/profile/api.ts | 61 +--------------- imports/lib/api.ts | 29 ++++++++ imports/lib/userDisplayName.ts | 7 +- imports/ui/SettingsPage.tsx | 33 ++++++--- 8 files changed, 139 insertions(+), 163 deletions(-) diff --git a/.github/plans/timecore.md b/.github/plans/timecore.md index 54f51e545..d0f4516a1 100644 --- a/.github/plans/timecore.md +++ b/.github/plans/timecore.md @@ -6,7 +6,7 @@ React app that shares a universal codebase with future mobile (Capacitor / Expo ## Background -**timecore** (`localhost:3001` in dev) is a Fastify + MongoDB service using better-auth for +**timecore** (`localhost:4000` in dev) is a Fastify + MongoDB service using better-auth for email/password authentication. It already has `/v1/me` and `/v1/me/profile` stubbed. Everything else needs to be added there as part of this migration. @@ -45,17 +45,17 @@ React Native, and Expo. for data — auth is fully owned by timecore. ### timehuddle changes -- [ ] Replace `LoginForm.tsx` to call `POST /api/auth/sign-in` and `POST /api/auth/sign-up` -- [ ] Add "Forgot password?" flow: submits email to `POST /api/auth/request-password-reset` -- [ ] Add reset-password landing: reads `?token=` from URL, submits new password to `POST /api/auth/reset-password` -- [ ] Replace `Meteor.user()` + `useTracker` with a `useSession()` hook (`GET /v1/me`) -- [ ] Replace `Meteor.logout()` with `POST /api/auth/sign-out` -- [ ] Remove `imports/features/auth/api.ts` -- [ ] Remove `imports/startup/server.ts` (Accounts.config, email hook) -- [ ] Update `client/main.tsx` — gate on `useSession()` instead of `Meteor.user()` +- [x] Replace `LoginForm.tsx` to call `POST /api/auth/sign-in` and `POST /api/auth/sign-up` +- [x] Add "Forgot password?" flow: submits email to `POST /api/auth/request-password-reset` +- [x] Add reset-password landing: reads `?token=` from URL, submits new password to `POST /api/auth/reset-password` +- [x] Replace `Meteor.user()` + `useTracker` with a `useSession()` hook (`GET /v1/me`) +- [x] Replace `Meteor.logout()` with `POST /api/auth/sign-out` +- [x] Remove `imports/features/auth/api.ts` +- [x] Remove `imports/startup/server.ts` (Accounts.config, email hook) +- [x] Update `client/main.tsx` — gate on `useSession()` instead of `Meteor.user()` ### timecore changes -- [ ] Configure `sendResetPassword` email callback in `emailAndPassword` auth config — better-auth handles `POST /api/auth/request-password-reset` and `POST /api/auth/reset-password` automatically +- [x] Configure `sendResetPassword` email callback in `emailAndPassword` auth config — better-auth handles `POST /api/auth/request-password-reset` and `POST /api/auth/reset-password` automatically --- ## Phase 2 — Profile & User Lookups @@ -65,15 +65,15 @@ for data — auth is fully owned by timecore. timecore's `users` collection managed by better-auth. ### timehuddle changes -- [ ] Replace `profile.update` Meteor method call → `PUT /v1/me/profile` -- [ ] Replace `Meteor.users` lookups (display names, avatars) → REST calls -- [ ] Remove `imports/features/profile/api.ts` server half -- [ ] Remove `imports/lib/userDisplayName.ts` Meteor dependency +- [x] Replace `profile.update` Meteor method call → `PUT /v1/me/profile` +- [x] Replace `Meteor.users` lookups (display names, avatars) → REST calls +- [x] Remove `imports/features/profile/api.ts` server half +- [x] Remove `imports/lib/userDisplayName.ts` Meteor dependency ### timecore changes -- [ ] `GET /v1/users/:id` — single user lookup -- [ ] `GET /v1/users?ids=id1,id2,...` — batch lookup (capped at 200) -- [ ] `PUT /v1/me/profile` — already stubbed, implement write +- [x] `GET /v1/users/:id` — single user lookup +- [x] `GET /v1/users?ids=id1,id2,...` — batch lookup (capped at 200) +- [x] `PUT /v1/me/profile` — already stubbed, implement write --- diff --git a/imports/features/auth/api.ts b/imports/features/auth/api.ts index 61040fc11..aaa75918b 100644 --- a/imports/features/auth/api.ts +++ b/imports/features/auth/api.ts @@ -1,33 +1,8 @@ /** - * Auth feature — remaining server methods for Phase 1. + * Auth feature — server methods removed in Phase 2. * - * createUserAccount and resetPasswordWithTeamCode have been replaced by - * timecore (better-auth). Archived originals: .attic/imports/features/auth/api.ts + * createUserAccount and resetPasswordWithTeamCode → timecore better-auth. + * updateUserProfile → PUT /v1/me/profile (timecore Phase 2). * - * updateUserProfile will be replaced by PUT /v1/me/profile in Phase 2. + * Archived originals: .attic/imports/features/auth/api.ts */ -import { Meteor } from 'meteor/meteor'; - -import { updateProfileSchema } from './schema'; - -// ─── Methods ────────────────────────────────────────────────────────────────── - -Meteor.methods({ - 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; - }, -}); diff --git a/imports/features/profile/ProfilePage.tsx b/imports/features/profile/ProfilePage.tsx index a000deeb3..6f87610f4 100644 --- a/imports/features/profile/ProfilePage.tsx +++ b/imports/features/profile/ProfilePage.tsx @@ -3,68 +3,74 @@ * * • Any authenticated user can view any profile by userId * • The profile owner sees an inline edit form (displayName, bio, website) - * • Avatar, displayName, bio and website are the editable public fields - * - * Subscriptions: 'profile.public' for the viewed userId + * • Data fetched from timecore GET /v1/users/:id and PUT /v1/me/profile */ import { faGlobe, faPen } from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { Avatar, Button, Card, Input, Spinner, Text } from '@mieweb/ui'; -import { Meteor } from 'meteor/meteor'; -import { useTracker } from 'meteor/react-meteor-data'; -import React, { useState } from 'react'; +import React, { useEffect, useState } from 'react'; import { PROFILE_BIO_MAX, PROFILE_DISPLAY_NAME_MAX, PROFILE_WEBSITE_MAX, } from '../../lib/constants'; -import { useMethod } from '../../lib/useMethod'; -import { UserProfiles } from './api'; -import { type ProfileUpdateInput } from './schema'; +import { userApi, type PublicUser } from '../../lib/api'; +import { useSession } from '../../lib/useSession'; interface ProfilePageProps { userId: string; } export const ProfilePage: React.FC = ({ userId }) => { - const myId = useTracker(() => Meteor.userId(), []); - const isOwn = myId === userId; - - const { profile, isReady } = useTracker(() => { - const handle = Meteor.subscribe('profile.public', userId); - return { - profile: UserProfiles.findOne({ userId }), - isReady: handle.ready(), - }; + const { user: sessionUser, refetch: refetchSession } = useSession(); + const isOwn = sessionUser?.id === userId; + + const [profile, setProfile] = useState(null); + const [isReady, setIsReady] = useState(false); + + useEffect(() => { + setIsReady(false); + userApi + .getUser(userId) + .then((p) => setProfile(p)) + .catch(() => setProfile(null)) + .finally(() => setIsReady(true)); }, [userId]); - const email = useTracker(() => { - if (!isOwn) return null; - const user = Meteor.user(); - return user?.emails?.[0]?.address ?? null; - }, [isOwn]); - const [editing, setEditing] = useState(false); const [displayName, setDisplayName] = useState(''); const [bio, setBio] = useState(''); const [website, setWebsite] = useState(''); - const updateProfile = useMethod<[ProfileUpdateInput]>('profile.update'); + const [saving, setSaving] = useState(false); + const [saveError, setSaveError] = useState(null); const startEdit = () => { - setDisplayName(profile?.displayName ?? ''); + setDisplayName(profile?.name ?? ''); setBio(profile?.bio ?? ''); setWebsite(profile?.website ?? ''); - updateProfile.clearError(); + setSaveError(null); setEditing(true); }; - const save = (e: React.FormEvent) => { + const save = async (e: React.FormEvent) => { e.preventDefault(); - updateProfile - .call({ displayName, bio, website }) - .then(() => setEditing(false)) - .catch(() => {}); // error shown via updateProfile.error + setSaving(true); + setSaveError(null); + try { + const updated = await userApi.updateProfile({ + name: displayName.trim() || undefined, + bio: bio.trim(), + website: website.trim(), + }); + setProfile(updated); + await refetchSession(); + setEditing(false); + } catch (err) { + setSaveError(err instanceof Error ? err.message : 'Something went wrong'); + } finally { + setSaving(false); + } }; if (!isReady) { @@ -75,8 +81,7 @@ export const ProfilePage: React.FC = ({ userId }) => { ); } - // Determine what to display: prefer saved displayName, then email, then fallback - const nameText = profile?.displayName || email || 'Unknown user'; + const nameText = profile?.name || sessionUser?.email?.split('@')[0] || 'Unknown user'; return (
{/* Profile header card */} @@ -86,8 +91,8 @@ export const ProfilePage: React.FC = ({ userId }) => {
{nameText} - {isOwn && email && ( - {email} + {isOwn && sessionUser?.email && ( + {sessionUser.email} )} {profile?.bio && ( @@ -106,7 +111,7 @@ export const ProfilePage: React.FC = ({ userId }) => { )} - {isOwn && !profile?.displayName && !profile?.bio && !editing && ( + {isOwn && !profile?.name && !profile?.bio && !editing && ( Your profile is empty. Click edit to add a display name and bio. @@ -159,7 +164,7 @@ export const ProfilePage: React.FC = ({ userId }) => { type="url" /> - {updateProfile.error && {updateProfile.error}} + {saveError && {saveError}}
{saved && Saved!} - {updateProfile.error && {updateProfile.error}} + {profileError && {profileError}}
From 62a38ed595f5f2b4ca54858ce18c66d2b42ebe5a Mon Sep 17 00:00:00 2001 From: Michael Fisher Date: Tue, 21 Apr 2026 13:48:23 -0400 Subject: [PATCH 05/26] feat(tickets): migrate ticket management to timecore API and remove Meteor dependencies --- .github/plans/timecore.md | 40 ++++++-- imports/features/tickets/TicketsPage.tsx | 122 +++++++++++++---------- imports/features/tickets/api.ts | 27 ++--- imports/lib/api.ts | 64 ++++++++++++ 4 files changed, 175 insertions(+), 78 deletions(-) diff --git a/.github/plans/timecore.md b/.github/plans/timecore.md index d0f4516a1..e4286d322 100644 --- a/.github/plans/timecore.md +++ b/.github/plans/timecore.md @@ -1,5 +1,11 @@ # Migration Plan: Meteor → Timecore +## Rationale + +Meteor's tightly-coupled DDP protocol and proprietary accounts system lock timehuddle to a single Node.js monolith that cannot be shared with mobile clients or scaled independently. Replacing it with timecore (a standard REST/SSE API) makes the auth and data layer portable across web, iOS, and Android while removing a framework dependency that adds ~40 MB to the bundle and limits hiring to Meteor specialists. + +## Summary + Migrate timehuddle off Meteor entirely. Replace Meteor DDP, accounts, and collections with the shared timecore backend (Fastify + better-auth + MongoDB). The result is a Meteor-free React app that shares a universal codebase with future mobile (Capacitor / Expo / React Native). @@ -77,15 +83,14 @@ timecore's `users` collection managed by better-auth. --- -## Phase 3 — Teams & Notifications +## Phase 3 — Teams **Effort:** 2–3 days -**Goal:** Move all team management and notifications to timecore REST + SSE. +**Goal:** Move all team management to timecore REST. ### timehuddle changes - [ ] Replace all 10 team Meteor methods with REST calls - [ ] Replace `userTeams` / `teamMembers` publications with REST + stale-while-revalidate -- [ ] Replace `notifications.inbox` publication with SSE stream + REST for mark-read/delete - [ ] Remove `imports/features/teams/api.ts` server half ### timecore changes @@ -99,11 +104,6 @@ timecore's `users` collection managed by better-auth. - [ ] `DELETE /v1/teams/:id/members/:userId` — remove member - [ ] `PUT /v1/teams/:id/members/:userId/role` — promote/demote admin - [ ] `PUT /v1/teams/:id/members/:userId/password` — admin set member password -- [ ] `GET /v1/notifications` — paginated inbox -- [ ] `POST /v1/notifications/read` — mark all read -- [ ] `PATCH /v1/notifications/:id/read` — mark one read -- [ ] `DELETE /v1/notifications/:id` — delete one -- [ ] `GET /v1/notifications/stream` — SSE stream for new notifications --- @@ -191,7 +191,25 @@ Meteor-independent and stays as-is. --- -## Phase 8 — GitHub Integration +## Phase 8 — Notifications + +**Effort:** 1 day +**Goal:** Move the notifications inbox to timecore with SSE for real-time delivery. + +### timehuddle changes +- [ ] Replace `notifications.inbox` publication with SSE stream + REST for mark-read/delete +- [ ] Remove notifications server code from `imports/features/notifications/` + +### timecore changes +- [ ] `GET /v1/notifications` — paginated inbox +- [ ] `POST /v1/notifications/read` — mark all read +- [ ] `PATCH /v1/notifications/:id/read` — mark one read +- [ ] `DELETE /v1/notifications/:id` — delete one +- [ ] `GET /v1/notifications/stream` — SSE stream for new notifications + +--- + +## Phase 9 — GitHub Integration **Effort:** 1–2 days **Goal:** Allow users to connect their GitHub account via OAuth, browse repos/issues, and link GitHub issues to tickets — parity with timeharbor-legacy. @@ -211,7 +229,7 @@ Meteor-independent and stays as-is. --- -## Phase 9 — PulseVault Integration +## Phase 10 — PulseVault Integration **Effort:** 1 day **Goal:** Allow users to attach media to tickets via PulseCam app using a QR code/deeplink — parity with timeharbor-legacy. @@ -227,7 +245,7 @@ Meteor-independent and stays as-is. --- -## Phase 10 — Rip Out Meteor +## Phase 11 — Rip Out Meteor **Effort:** 1 day **Goal:** Remove the Meteor build system and all remaining Meteor packages. Replace the dev diff --git a/imports/features/tickets/TicketsPage.tsx b/imports/features/tickets/TicketsPage.tsx index 8abc909df..37ca34d7c 100644 --- a/imports/features/tickets/TicketsPage.tsx +++ b/imports/features/tickets/TicketsPage.tsx @@ -20,8 +20,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, @@ -40,32 +38,40 @@ import { Spinner, Text, } from '@mieweb/ui'; -import React, { useCallback, useMemo, useState } from 'react'; +import React, { useCallback, useEffect, useMemo, useState } from 'react'; +import { ticketApi, type Ticket } from '../../lib/api'; import { useTeam } from '../../lib/TeamContext'; import { formatDuration } from '../../lib/timeUtils'; -import { useMethod } from '../../lib/useMethod'; -import { Tickets } from './api'; -import type { TicketDoc } from './schema'; +import { useSession } from '../../lib/useSession'; export const TicketsPage: React.FC = () => { - const userId = Meteor.userId(); + const { user } = useSession(); + const userId = user?.id ?? null; const { teams, selectedTeamId, setSelectedTeamId, teamsReady, currentTime } = useTeam(); - const teamIds = useMemo(() => (selectedTeamId ? [selectedTeamId] : []), [selectedTeamId]); - useSubscribe('teamTickets', teamIds); + const [tickets, setTickets] = useState([]); - const allTickets = useFind( - () => Tickets.find({ teamId: selectedTeamId ?? '__none__' }, { sort: { createdAt: -1 } }), - [selectedTeamId], - ); + const refetch = useCallback(async () => { + if (!selectedTeamId) { + setTickets([]); + return; + } + try { + const data = await ticketApi.getTickets(selectedTeamId); + setTickets(data); + } catch { + // keep previous tickets on error + } + }, [selectedTeamId]); + + useEffect(() => { + void refetch(); + }, [refetch]); - // Methods - const createTicketMethod = useMethod<[{ teamId: string; title: string; github?: string }], string>('tickets.create'); - const updateTicketMethod = useMethod<[{ ticketId: string; updates: Record }]>('tickets.update'); - const deleteTicketMethod = useMethod<[string]>('tickets.delete'); - const startTicketMethod = useMethod<[{ ticketId: string; now: number }]>('tickets.start'); - const stopTicketMethod = useMethod<[{ ticketId: string; now: number }]>('tickets.stop'); + // Mutation loading states + const [createLoading, setCreateLoading] = useState(false); + const [deleteLoading, setDeleteLoading] = useState(false); // UI state const [showCreate, setShowCreate] = useState(false); @@ -79,12 +85,12 @@ export const TicketsPage: React.FC = () => { // Filter tickets const filteredTickets = useMemo(() => { - if (!searchQuery.trim()) return allTickets; + if (!searchQuery.trim()) return tickets; const q = searchQuery.toLowerCase(); - return allTickets.filter( + return tickets.filter( (t) => t.title.toLowerCase().includes(q) || t.github?.toLowerCase().includes(q), ); - }, [allTickets, searchQuery]); + }, [tickets, searchQuery]); // My tickets vs others const myTickets = useMemo(() => filteredTickets.filter((t) => t.createdBy === userId), [filteredTickets, userId]); @@ -94,58 +100,72 @@ export const TicketsPage: React.FC = () => { const handleCreate = useCallback(async () => { if (!createTitle.trim() || !selectedTeamId) return; - await createTicketMethod.call({ - teamId: selectedTeamId, - title: createTitle.trim(), - github: createGithub.trim() || undefined, - }); - setCreateTitle(''); - setCreateGithub(''); - setShowCreate(false); - }, [createTitle, createGithub, selectedTeamId, createTicketMethod]); + setCreateLoading(true); + try { + await ticketApi.createTicket({ + teamId: selectedTeamId, + title: createTitle.trim(), + github: createGithub.trim() || undefined, + }); + setCreateTitle(''); + setCreateGithub(''); + setShowCreate(false); + void refetch(); + } finally { + setCreateLoading(false); + } + }, [createTitle, createGithub, selectedTeamId, refetch]); const handleStartStop = useCallback( - async (ticket: TicketDoc) => { + async (ticket: Ticket) => { const now = Date.now(); if (ticket.startTimestamp) { - await stopTicketMethod.call({ ticketId: ticket._id!, now }); + await ticketApi.stopTimer(ticket.id, now); } else { - await startTicketMethod.call({ ticketId: ticket._id!, now }); + await ticketApi.startTimer(ticket.id, now); } + void refetch(); }, - [startTicketMethod, stopTicketMethod], + [refetch], ); const handleSaveEdit = useCallback(async () => { if (!editingId || !editTitle.trim()) return; - await updateTicketMethod.call({ - ticketId: editingId, - updates: { title: editTitle.trim(), github: editGithub.trim() }, + await ticketApi.updateTicket(editingId, { + title: editTitle.trim(), + github: editGithub.trim(), }); setEditingId(null); - }, [editingId, editTitle, editGithub, updateTicketMethod]); + void refetch(); + }, [editingId, editTitle, editGithub, refetch]); const handleDelete = useCallback(async () => { if (!deleteId) return; - await deleteTicketMethod.call(deleteId); - setDeleteId(null); - }, [deleteId, deleteTicketMethod]); + setDeleteLoading(true); + try { + await ticketApi.deleteTicket(deleteId); + setDeleteId(null); + void refetch(); + } finally { + setDeleteLoading(false); + } + }, [deleteId, refetch]); - const startEdit = (ticket: TicketDoc) => { - setEditingId(ticket._id!); + const startEdit = (ticket: Ticket) => { + setEditingId(ticket.id); setEditTitle(ticket.title); setEditGithub(ticket.github || ''); }; // ── Ticket Row ── - const TicketRow: React.FC<{ ticket: TicketDoc; canManage: boolean }> = ({ ticket, canManage }) => { + const TicketRow: React.FC<{ ticket: Ticket; canManage: boolean }> = ({ ticket, canManage }) => { const isRunning = !!ticket.startTimestamp; const elapsed = isRunning ? (ticket.accumulatedTime || 0) + Math.floor((currentTime - ticket.startTimestamp!) / 1000) : ticket.accumulatedTime || 0; - const isEditing = editingId === ticket._id; + const isEditing = editingId === ticket.id; return (
  • @@ -239,7 +259,7 @@ export const TicketsPage: React.FC = () => { diff --git a/imports/features/tickets/api.ts b/imports/features/tickets/api.ts index 906b4740d..1631fdcea 100644 --- a/imports/features/tickets/api.ts +++ b/imports/features/tickets/api.ts @@ -1,21 +1,16 @@ -import { DDPRateLimiter } from 'meteor/ddp-rate-limiter'; -import { Meteor } from 'meteor/meteor'; -import { Mongo } from 'meteor/mongo'; - -import { Teams } from '../teams/api'; -import { - assignTicketSchema, - batchUpdateStatusSchema, - createTicketSchema, - ticketTimerSchema, - updateTicketSchema, - type TicketDoc, +/** + * Tickets feature — server-side Meteor API removed in Phase 4. + * Data is now served by timecore (/v1/tickets). + */ +export type { + TicketDoc, + CreateTicketInput, + UpdateTicketInput, + TicketTimerInput, + BatchUpdateStatusInput, + AssignTicketInput, } from './schema'; -// ─── Collections ────────────────────────────────────────────────────────────── - -export const Tickets = new Mongo.Collection('tickets'); - // ─── Server ─────────────────────────────────────────────────────────────────── if (Meteor.isServer) { diff --git a/imports/lib/api.ts b/imports/lib/api.ts index 3a255889f..422d94c86 100644 --- a/imports/lib/api.ts +++ b/imports/lib/api.ts @@ -128,3 +128,67 @@ export const userApi = { body: JSON.stringify(data), }).then((r) => r.user), }; + +// ─── Ticket API ─────────────────────────────────────────────────────────────── + +export interface Ticket { + id: string; + teamId: string; + title: string; + github: string; + accumulatedTime: number; + startTimestamp: number | null; + status: string; + createdBy: string; + assignedTo: string | null; + reviewedBy: string | null; + reviewedAt: string | null; + createdAt: string; + updatedAt: string | null; +} + +export const ticketApi = { + getTickets: (teamId: string) => + request<{ tickets: Ticket[] }>(`/v1/tickets?teamId=${encodeURIComponent(teamId)}`).then( + (r) => r.tickets, + ), + + createTicket: (data: { teamId: string; title: string; github?: string; accumulatedTime?: number }) => + request<{ ticket: Ticket }>('/v1/tickets', { + method: 'POST', + body: JSON.stringify(data), + }).then((r) => r.ticket), + + updateTicket: (id: string, updates: { title?: string; github?: string; accumulatedTime?: number; status?: string }) => + request<{ ticket: Ticket }>(`/v1/tickets/${encodeURIComponent(id)}`, { + method: 'PUT', + body: JSON.stringify(updates), + }).then((r) => r.ticket), + + deleteTicket: (id: string) => + request<{ ok: boolean }>(`/v1/tickets/${encodeURIComponent(id)}`, { method: 'DELETE' }), + + startTimer: (id: string, now: number) => + request<{ ticket: Ticket }>(`/v1/tickets/${encodeURIComponent(id)}/start`, { + method: 'POST', + body: JSON.stringify({ now }), + }).then((r) => r.ticket), + + stopTimer: (id: string, now: number) => + request<{ ticket: Ticket }>(`/v1/tickets/${encodeURIComponent(id)}/stop`, { + method: 'POST', + body: JSON.stringify({ now }), + }).then((r) => r.ticket), + + batchUpdateStatus: (data: { ticketIds: string[]; status: string; teamId: string }) => + request<{ modified: number }>('/v1/tickets/batch-status', { + method: 'POST', + body: JSON.stringify(data), + }), + + assignTicket: (id: string, assignedToUserId: string | null) => + request<{ ticket: Ticket }>(`/v1/tickets/${encodeURIComponent(id)}/assign`, { + method: 'PUT', + body: JSON.stringify({ assignedToUserId }), + }).then((r) => r.ticket), +}; From cbc5b4566bb93e5ff016fe8942a3844923b168e7 Mon Sep 17 00:00:00 2001 From: Michael Fisher Date: Tue, 21 Apr 2026 17:47:52 -0400 Subject: [PATCH 06/26] refactor: migrate teams feature to use REST API and remove Meteor methods - Updated TeamsPage component to fetch teams and members via REST API. - Removed Meteor subscriptions and methods related to teams. - Introduced teamApi for handling team-related API requests. - Refactored TeamContext to manage team state using REST. - Adjusted ticket handling to align with new team structure. - Cleaned up unused code and improved loading states for team actions. --- imports/features/clock/ClockPage.tsx | 2 +- imports/features/dashboard/DashboardPage.tsx | 4 +- imports/features/messages/MessagesPage.tsx | 2 +- imports/features/teams/TeamsPage.tsx | 174 +++++++++------- imports/features/teams/api.ts | 200 ------------------- imports/features/tickets/TicketsPage.tsx | 2 +- imports/features/tickets/api.ts | 182 ++--------------- imports/lib/TeamContext.tsx | 114 +++++++---- imports/lib/api.ts | 84 +++++++- 9 files changed, 282 insertions(+), 482 deletions(-) diff --git a/imports/features/clock/ClockPage.tsx b/imports/features/clock/ClockPage.tsx index 8fd7ce20d..09f560f8c 100644 --- a/imports/features/clock/ClockPage.tsx +++ b/imports/features/clock/ClockPage.tsx @@ -142,7 +142,7 @@ export const ClockPage: React.FC = () => { const teamOptions = useMemo( () => teams.map((t) => ({ - value: t._id!, + value: t.id, label: t.isPersonal ? 'Personal' : t.name, })), [teams], diff --git a/imports/features/dashboard/DashboardPage.tsx b/imports/features/dashboard/DashboardPage.tsx index 72efc5c41..75d4acc92 100644 --- a/imports/features/dashboard/DashboardPage.tsx +++ b/imports/features/dashboard/DashboardPage.tsx @@ -108,7 +108,7 @@ export const DashboardPage: React.FC = () => { const teamOptions = useMemo( () => teams.map((t) => ({ - value: t._id!, + value: t.id, label: t.isPersonal ? 'Personal Workspace' : t.name, })), [teams], @@ -254,7 +254,7 @@ export const DashboardPage: React.FC = () => { const start = new Date(event.startTimestamp); const end = event.endTime ? new Date(event.endTime) : null; const durSec = end ? (end.getTime() - event.startTimestamp) / 1000 : 0; - const team = teams.find((t) => t._id === event.teamId); + const team = teams.find((t) => t.id === event.teamId); return (
  • diff --git a/imports/features/messages/MessagesPage.tsx b/imports/features/messages/MessagesPage.tsx index c3941c738..8c23b79d7 100644 --- a/imports/features/messages/MessagesPage.tsx +++ b/imports/features/messages/MessagesPage.tsx @@ -176,7 +176,7 @@ export const MessagesPage: React.FC = () => { () => teams .filter((t) => !t.isPersonal) - .map((t) => ({ value: t._id!, label: t.name })), + .map((t) => ({ value: t.id, label: t.name })), [teams], ); diff --git a/imports/features/teams/TeamsPage.tsx b/imports/features/teams/TeamsPage.tsx index bd668f13c..7bc49f22d 100644 --- a/imports/features/teams/TeamsPage.tsx +++ b/imports/features/teams/TeamsPage.tsx @@ -22,8 +22,6 @@ import { faUserPlus, } 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 { Avatar, Badge, @@ -46,10 +44,11 @@ import { Spinner, Text, } from '@mieweb/ui'; -import React, { useCallback, useMemo, useState } from 'react'; +import React, { useCallback, useEffect, useMemo, useState } from 'react'; +import { teamApi, type TeamMember } from '../../lib/api'; import { useTeam } from '../../lib/TeamContext'; -import { useMethod } from '../../lib/useMethod'; +import { useSession } from '../../lib/useSession'; const TeamChart = React.lazy(() => import('./TeamChart').then((m) => ({ default: m.TeamChart })) ); @@ -57,29 +56,36 @@ const TeamChart = React.lazy(() => // ─── TeamsPage ──────────────────────────────────────────────────────────────── export const TeamsPage: React.FC = () => { - const userId = Meteor.userId(); - const { teams, teamsReady, selectedTeamId, setSelectedTeamId, isAdmin } = useTeam(); - - // Subscribe to team members - useSubscribe('teamMembers', selectedTeamId ?? ''); + const { user } = useSession(); + const userId = user?.id ?? null; + const { teams, teamsReady, selectedTeamId, setSelectedTeamId, isAdmin, refetchTeams } = useTeam(); + + // Fetch members for selected team + const [members, setMembers] = useState([]); + const fetchMembers = useCallback(async (teamId: string | null) => { + if (!teamId) { setMembers([]); return; } + try { + const data = await teamApi.getMembers(teamId); + setMembers(data); + } catch { + setMembers([]); + } + }, []); - const members = useFind( - () => Meteor.users.find({}, { fields: { 'emails.address': 1, profile: 1 } }), - [selectedTeamId], - ); + useEffect(() => { + void fetchMembers(selectedTeamId); + }, [selectedTeamId, fetchMembers]); - const selectedTeam = teams.find((t) => t._id === selectedTeamId) ?? null; + const selectedTeam = teams.find((t) => t.id === selectedTeamId) ?? null; - // Methods - const createTeam = useMethod<[{ name: string; description?: string }], { teamId: string; code: string }>('teams.create'); - const joinTeam = useMethod<[{ teamCode: string }], string>('teams.join'); - const updateName = useMethod<[{ teamId: string; newName: string }]>('teams.updateName'); - const deleteTeam = useMethod<[string]>('teams.delete'); - const addAdmin = useMethod<[{ teamId: string; userId: string }]>('teams.addAdmin'); - const removeAdmin = useMethod<[{ teamId: string; userId: string }]>('teams.removeAdmin'); - const removeMember = useMethod<[{ teamId: string; userId: string }]>('teams.removeMember'); - const inviteMember = useMethod<[{ teamId: string; email: string }], string>('teams.invite'); - const setPassword = useMethod<[{ teamId: string; userId: string; newPassword: string }]>('teams.setMemberPassword'); + // Loading states for mutations + const [createLoading, setCreateLoading] = useState(false); + const [joinLoading, setJoinLoading] = useState(false); + const [renameLoading, setRenameLoading] = useState(false); + const [deleteLoading, setDeleteLoading] = useState(false); + const [inviteLoading, setInviteLoading] = useState(false); + const [passwordLoading, setPasswordLoading] = useState(false); + const [removeLoading, setRemoveLoading] = useState(false); // Modal state const [modal, setModal] = useState< @@ -108,14 +114,14 @@ export const TeamsPage: React.FC = () => { const teamOptions = useMemo( () => teams.map((t) => ({ - value: t._id!, + value: t.id, label: t.isPersonal ? 'Personal Workspace' : t.name, })), [teams], ); - const usersById = useMemo( - () => new Map(members.map((u) => [u._id!, u])), + const membersById = useMemo( + () => new Map(members.map((m) => [m.id, m])), [members], ); @@ -123,80 +129,108 @@ export const TeamsPage: React.FC = () => { const handleCreate = useCallback(async () => { if (!formValue.trim()) return; + setCreateLoading(true); try { - const result = await createTeam.call({ + const team = await teamApi.createTeam({ name: formValue.trim(), description: createDescription.trim() || undefined, }); - setSelectedTeamId(result.teamId); - setModal({ type: 'created', code: result.code }); + setSelectedTeamId(team.id); + setModal({ type: 'created', code: team.code }); setFormValue(''); setCreateDescription(''); + refetchTeams(); } catch (e: any) { - setFormError(e.reason || 'Failed to create team'); + setFormError(e.message || 'Failed to create team'); + } finally { + setCreateLoading(false); } - }, [formValue, createDescription, createTeam, setSelectedTeamId]); + }, [formValue, createDescription, setSelectedTeamId, refetchTeams]); const handleJoin = useCallback(async () => { if (!formValue.trim()) return; + setJoinLoading(true); try { - const teamId = await joinTeam.call({ teamCode: formValue.trim() }); - setSelectedTeamId(teamId); + const team = await teamApi.joinTeam(formValue.trim()); + setSelectedTeamId(team.id); closeModal(); + refetchTeams(); } catch (e: any) { - setFormError(e.reason || 'Failed to join team'); + setFormError(e.message || 'Failed to join team'); + } finally { + setJoinLoading(false); } - }, [formValue, joinTeam, setSelectedTeamId]); + }, [formValue, setSelectedTeamId, refetchTeams]); const handleRename = useCallback(async () => { if (!formValue.trim() || !selectedTeamId) return; + setRenameLoading(true); try { - await updateName.call({ teamId: selectedTeamId, newName: formValue.trim() }); + await teamApi.renameTeam(selectedTeamId, formValue.trim()); closeModal(); + refetchTeams(); } catch (e: any) { - setFormError(e.reason || 'Failed to rename'); + setFormError(e.message || 'Failed to rename'); + } finally { + setRenameLoading(false); } - }, [formValue, selectedTeamId, updateName]); + }, [formValue, selectedTeamId, refetchTeams]); const handleDelete = useCallback(async () => { if (!selectedTeamId) return; + setDeleteLoading(true); try { - await deleteTeam.call(selectedTeamId); + await teamApi.deleteTeam(selectedTeamId); closeModal(); + refetchTeams(); } catch (e: any) { - setFormError(e.reason || 'Failed to delete'); + setFormError(e.message || 'Failed to delete'); + } finally { + setDeleteLoading(false); } - }, [selectedTeamId, deleteTeam]); + }, [selectedTeamId, refetchTeams]); const handleInvite = useCallback(async () => { if (!formValue.trim() || !selectedTeamId) return; + setInviteLoading(true); try { - await inviteMember.call({ teamId: selectedTeamId, email: formValue.trim() }); + await teamApi.inviteMember(selectedTeamId, formValue.trim()); closeModal(); + await fetchMembers(selectedTeamId); } catch (e: any) { - setFormError(e.reason || 'Failed to invite'); + setFormError(e.message || 'Failed to invite'); + } finally { + setInviteLoading(false); } - }, [formValue, selectedTeamId, inviteMember]); + }, [formValue, selectedTeamId, fetchMembers]); const handleSetPassword = useCallback(async (memberId: string) => { if (!formValue.trim() || !selectedTeamId) return; + setPasswordLoading(true); try { - await setPassword.call({ teamId: selectedTeamId, userId: memberId, newPassword: formValue.trim() }); + await teamApi.setMemberPassword(selectedTeamId, memberId, formValue.trim()); closeModal(); } catch (e: any) { - setFormError(e.reason || 'Failed to set password'); + setFormError(e.message || 'Failed to set password'); + } finally { + setPasswordLoading(false); } - }, [formValue, selectedTeamId, setPassword]); + }, [formValue, selectedTeamId]); const handleRemoveMember = useCallback(async (memberId: string) => { if (!selectedTeamId) return; + setRemoveLoading(true); try { - await removeMember.call({ teamId: selectedTeamId, userId: memberId }); + await teamApi.removeMember(selectedTeamId, memberId); closeModal(); + refetchTeams(); + await fetchMembers(selectedTeamId); } catch (e: any) { - setFormError(e.reason || 'Failed to remove member'); + setFormError(e.message || 'Failed to remove member'); + } finally { + setRemoveLoading(false); } - }, [selectedTeamId, removeMember]); + }, [selectedTeamId, refetchTeams, fetchMembers]); const copyCode = useCallback(() => { if (selectedTeam?.code) { @@ -204,12 +238,6 @@ export const TeamsPage: React.FC = () => { } }, [selectedTeam]); - const getName = (u: Meteor.User) => { - const p = u.profile as { firstName?: string; lastName?: string } | undefined; - if (p?.firstName || p?.lastName) return [p.firstName, p.lastName].filter(Boolean).join(' '); - return u.emails?.[0]?.address?.split('@')[0] ?? 'Unknown'; - }; - if (!teamsReady) { return (
    @@ -312,9 +340,9 @@ export const TeamsPage: React.FC = () => {
      {selectedTeam.members.map((memberId) => { - const user = usersById.get(memberId); - const name = user ? getName(user) : memberId; - const email = user?.emails?.[0]?.address ?? ''; + const m = membersById.get(memberId); + const name = m?.name ?? memberId; + const email = m?.email ?? ''; const isMemberAdmin = selectedTeam.admins.includes(memberId); const isMe = memberId === userId; @@ -323,7 +351,7 @@ export const TeamsPage: React.FC = () => {
      - {name} {isMe && (you)} + {name}{isMe && (you)} {email && {email}}
      @@ -344,14 +372,14 @@ export const TeamsPage: React.FC = () => { {!isMemberAdmin ? ( } - onClick={() => addAdmin.call({ teamId: selectedTeamId!, userId: memberId })} + onClick={() => { void teamApi.setMemberRole(selectedTeamId!, memberId, 'admin').then(() => { refetchTeams(); void fetchMembers(selectedTeamId); }); }} > Make Admin ) : ( } - onClick={() => removeAdmin.call({ teamId: selectedTeamId!, userId: memberId })} + onClick={() => { void teamApi.setMemberRole(selectedTeamId!, memberId, 'member').then(() => { refetchTeams(); void fetchMembers(selectedTeamId); }); }} > Remove Admin @@ -391,11 +419,11 @@ export const TeamsPage: React.FC = () => { { - const user = usersById.get(memberId); + const m = membersById.get(memberId); return { id: memberId, - name: user ? getName(user) : memberId, - email: user?.emails?.[0]?.address, + name: m?.name ?? memberId, + email: m?.email, isAdmin: selectedTeam.admins.includes(memberId), }; })} @@ -440,7 +468,7 @@ export const TeamsPage: React.FC = () => { variant="primary" fullWidth onClick={handleCreate} - isLoading={createTeam.loading} + isLoading={createLoading} loadingText="Creating…" > Create @@ -471,7 +499,7 @@ export const TeamsPage: React.FC = () => { variant="primary" fullWidth onClick={handleJoin} - isLoading={joinTeam.loading} + isLoading={joinLoading} loadingText="Joining…" > Join @@ -500,7 +528,7 @@ export const TeamsPage: React.FC = () => { variant="primary" fullWidth onClick={handleRename} - isLoading={updateName.loading} + isLoading={renameLoading} > Save @@ -523,7 +551,7 @@ export const TeamsPage: React.FC = () => { @@ -553,7 +581,7 @@ export const TeamsPage: React.FC = () => { variant="primary" fullWidth onClick={handleInvite} - isLoading={inviteMember.loading} + isLoading={inviteLoading} > Send Invite @@ -598,7 +626,7 @@ export const TeamsPage: React.FC = () => { modal.type === 'password' && handleSetPassword(modal.memberId) } - isLoading={setPassword.loading} + isLoading={passwordLoading} > Set Password @@ -630,7 +658,7 @@ export const TeamsPage: React.FC = () => { modal.type === 'remove' && handleRemoveMember(modal.memberId) } - isLoading={removeMember.loading} + isLoading={removeLoading} > Remove diff --git a/imports/features/teams/api.ts b/imports/features/teams/api.ts index 6275ba51c..d29ec11da 100644 --- a/imports/features/teams/api.ts +++ b/imports/features/teams/api.ts @@ -1,15 +1,7 @@ -import { Accounts } from 'meteor/accounts-base'; -import { DDPRateLimiter } from 'meteor/ddp-rate-limiter'; import { Meteor } from 'meteor/meteor'; import { Mongo } from 'meteor/mongo'; import { - createTeamSchema, - inviteTeamMemberSchema, - joinTeamSchema, - setTeamMemberPasswordSchema, - teamMemberActionSchema, - updateTeamNameSchema, type NotificationDoc, type TeamDoc, } from './schema'; @@ -21,10 +13,6 @@ export const Notifications = new Mongo.Collection('notification // ─── Helpers ────────────────────────────────────────────────────────────────── -function generateTeamCode(): string { - return Math.random().toString(36).substring(2, 10).toUpperCase(); -} - function idStr(id: unknown): string { if (id == null) return ''; if (typeof id === 'string') return id; @@ -50,79 +38,15 @@ async function getBasicUsers(userIds: string[]): Promise { })); } -async function requireTeamAdmin(teamId: string, userId: string): Promise { - const team = await Teams.findOneAsync(teamId); - if (!team) throw new Meteor.Error('not-found', 'Team not found'); - if (!team.admins.includes(userId)) throw new Meteor.Error('forbidden', 'Only admins can perform this action'); - return team; -} - -async function ensurePersonalWorkspace(userId: string): Promise { - const existing = await Teams.findOneAsync({ isPersonal: true, members: userId, admins: userId }); - if (existing) return existing._id!; - const code = generateTeamCode(); - return await Teams.insertAsync({ - name: 'Personal', - members: [userId], - admins: [userId], - code, - isPersonal: true, - createdAt: new Date(), - }); -} - // ─── Server ─────────────────────────────────────────────────────────────────── if (Meteor.isServer) { Meteor.startup(async () => { - await Teams.createIndexAsync({ members: 1 }); - await Teams.createIndexAsync({ code: 1 }, { unique: true }); await Notifications.createIndexAsync({ userId: 1, createdAt: -1 }); - - const methodNames = [ - 'teams.ensurePersonalWorkspace', - 'teams.create', - 'teams.join', - 'teams.updateName', - 'teams.delete', - 'teams.addAdmin', - 'teams.removeAdmin', - 'teams.removeMember', - 'teams.invite', - 'teams.setMemberPassword', - 'teams.getUsers', - 'notifications.markAsRead', - 'notifications.markAllAsRead', - 'notifications.delete', - 'notifications.getTeamInvitePreview', - 'notifications.respondToTeamInvite', - ]; - DDPRateLimiter.addRule({ name: (n) => methodNames.includes(n), userId: () => true }, 20, 60_000); }); // ─── Publications ──────────────────────────────────────────────────────────── - Meteor.publish('userTeams', function () { - if (!this.userId) return this.ready(); - return Teams.find({ members: this.userId }); - }); - - Meteor.publish('teamDetails', function (teamId: string) { - if (!this.userId) return this.ready(); - return Teams.find({ _id: teamId, members: this.userId }); - }); - - Meteor.publish('teamMembers', async function (teamId: string) { - if (!this.userId) return this.ready(); - const team = await Teams.findOneAsync({ _id: teamId, members: this.userId }); - if (!team) return this.ready(); - const allIds = [...new Set([...team.members, ...team.admins])]; - return Meteor.users.find( - { _id: { $in: allIds } }, - { fields: { 'emails.address': 1, profile: 1 } }, - ); - }); - Meteor.publish('notifications.inbox', function () { if (!this.userId) return this.ready(); return Notifications.find({ userId: this.userId }, { sort: { createdAt: -1 }, limit: 200 }); @@ -131,130 +55,6 @@ if (Meteor.isServer) { // ─── Methods ────────────────────────────────────────────────────────────────── Meteor.methods({ - async 'teams.ensurePersonalWorkspace'() { - if (!this.userId) throw new Meteor.Error('not-authorized'); - return await ensurePersonalWorkspace(this.userId); - }, - - async 'teams.create'(fields: { name: string; description?: string }) { - if (!this.userId) throw new Meteor.Error('not-authorized'); - const result = createTeamSchema.safeParse(fields); - if (!result.success) throw new Meteor.Error('validation', result.error.issues[0]?.message ?? 'Invalid input'); - const code = generateTeamCode(); - const teamId = await Teams.insertAsync({ - name: result.data.name, - description: result.data.description, - members: [this.userId], - admins: [this.userId], - code, - createdAt: new Date(), - }); - return { teamId, code }; - }, - - async 'teams.join'(fields: { teamCode: string }) { - if (!this.userId) throw new Meteor.Error('not-authorized'); - const result = joinTeamSchema.safeParse(fields); - if (!result.success) throw new Meteor.Error('validation', result.error.issues[0]?.message ?? 'Invalid input'); - const team = await Teams.findOneAsync({ code: result.data.teamCode }); - if (!team) throw new Meteor.Error('not-found', 'Team not found'); - if (team.members.includes(this.userId)) throw new Meteor.Error('already-member', 'You are already a member of this team'); - await Teams.updateAsync(team._id!, { $push: { members: this.userId } }); - return team._id; - }, - - async 'teams.updateName'(fields: { teamId: string; newName: string }) { - if (!this.userId) throw new Meteor.Error('not-authorized'); - const result = updateTeamNameSchema.safeParse(fields); - if (!result.success) throw new Meteor.Error('validation', result.error.issues[0]?.message ?? 'Invalid input'); - await requireTeamAdmin(result.data.teamId, this.userId); - await Teams.updateAsync(result.data.teamId, { $set: { name: result.data.newName } }); - }, - - async 'teams.delete'(teamId: string) { - if (!this.userId) throw new Meteor.Error('not-authorized'); - await requireTeamAdmin(teamId, this.userId); - await Teams.removeAsync(teamId); - }, - - async 'teams.addAdmin'(fields: { teamId: string; userId: string }) { - if (!this.userId) throw new Meteor.Error('not-authorized'); - const result = teamMemberActionSchema.safeParse(fields); - if (!result.success) throw new Meteor.Error('validation', result.error.issues[0]?.message ?? 'Invalid input'); - const team = await requireTeamAdmin(result.data.teamId, this.userId); - if (!team.members.includes(result.data.userId)) throw new Meteor.Error('bad-request', 'User is not a member of this team'); - await Teams.updateAsync(result.data.teamId, { $addToSet: { admins: result.data.userId } }); - }, - - async 'teams.removeAdmin'(fields: { teamId: string; userId: string }) { - if (!this.userId) throw new Meteor.Error('not-authorized'); - const result = teamMemberActionSchema.safeParse(fields); - if (!result.success) throw new Meteor.Error('validation', result.error.issues[0]?.message ?? 'Invalid input'); - const team = await requireTeamAdmin(result.data.teamId, this.userId); - const remaining = team.admins.filter((id) => id !== result.data.userId); - if (remaining.length === 0) throw new Meteor.Error('bad-request', 'Team must have at least one admin'); - await Teams.updateAsync(result.data.teamId, { $set: { admins: remaining } }); - }, - - async 'teams.removeMember'(fields: { teamId: string; userId: string }) { - if (!this.userId) throw new Meteor.Error('not-authorized'); - const result = teamMemberActionSchema.safeParse(fields); - if (!result.success) throw new Meteor.Error('validation', result.error.issues[0]?.message ?? 'Invalid input'); - const team = await requireTeamAdmin(result.data.teamId, this.userId); - if (result.data.userId === this.userId) throw new Meteor.Error('bad-request', 'You cannot remove yourself; use Leave Team'); - if (!team.members.includes(result.data.userId)) throw new Meteor.Error('bad-request', 'User is not a member of this team'); - const remainingAdmins = team.admins.filter((id) => id !== result.data.userId); - if (remainingAdmins.length === 0) throw new Meteor.Error('bad-request', 'Promote another member to admin first'); - await Teams.updateAsync(result.data.teamId, { $pull: { members: result.data.userId, admins: result.data.userId } }); - }, - - async 'teams.invite'(fields: { teamId: string; email: string }) { - if (!this.userId) throw new Meteor.Error('not-authorized'); - const result = inviteTeamMemberSchema.safeParse(fields); - if (!result.success) throw new Meteor.Error('validation', result.error.issues[0]?.message ?? 'Invalid input'); - const team = await Teams.findOneAsync(result.data.teamId); - if (!team) throw new Meteor.Error('not-found', 'Team not found'); - if (!team.members.includes(this.userId)) throw new Meteor.Error('forbidden', 'You must be a member of this team'); - const emailRegex = new RegExp(`^${result.data.email.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}$`, 'i'); - const invitedUser = await Meteor.users.findOneAsync({ 'emails.address': emailRegex }); - if (!invitedUser) throw new Meteor.Error('not-found', 'No user found with that email. They need to sign up first.'); - if (team.members.includes(invitedUser._id)) throw new Meteor.Error('already-member', 'Already a member'); - const inviter = await Meteor.users.findOneAsync(this.userId); - const inviterName = inviter ? getUserDisplayName(inviter) : 'Someone'; - await Notifications.insertAsync({ - userId: invitedUser._id, - title: 'Team Invite', - body: `${inviterName} invited you to join "${team.name}" using code "${team.code}"`, - data: { type: 'team-invite', teamId: team._id, teamCode: team.code, inviterId: this.userId }, - read: false, - createdAt: new Date(), - }); - return `Invite sent to ${result.data.email}!`; - }, - - async 'teams.setMemberPassword'(fields: { teamId: string; userId: string; newPassword: string }) { - if (!this.userId) throw new Meteor.Error('not-authorized'); - const result = setTeamMemberPasswordSchema.safeParse(fields); - if (!result.success) throw new Meteor.Error('validation', result.error.issues[0]?.message ?? 'Invalid input'); - const team = await requireTeamAdmin(result.data.teamId, this.userId); - if (!team.members.includes(result.data.userId)) throw new Meteor.Error('bad-request', 'User is not a member'); - const user = await Meteor.users.findOneAsync(result.data.userId); - if (!user) throw new Meteor.Error('not-found', 'User not found'); - if (typeof Accounts.setPasswordAsync === 'function') { - await Accounts.setPasswordAsync(result.data.userId, result.data.newPassword, { logout: false }); - } else { - Accounts.setPassword(result.data.userId, result.data.newPassword, { logout: false }); - } - return true; - }, - - async 'teams.getUsers'(userIds: string[]) { - if (!this.userId) throw new Meteor.Error('not-authorized'); - if (!Array.isArray(userIds) || userIds.length === 0) return []; - const safeIds = userIds.slice(0, 200); - return await getBasicUsers(safeIds); - }, - async 'notifications.markAsRead'(notificationId: unknown) { if (!this.userId) throw new Meteor.Error('not-authorized'); if (notificationId === undefined || notificationId === null) { diff --git a/imports/features/tickets/TicketsPage.tsx b/imports/features/tickets/TicketsPage.tsx index 37ca34d7c..d66b66b01 100644 --- a/imports/features/tickets/TicketsPage.tsx +++ b/imports/features/tickets/TicketsPage.tsx @@ -274,7 +274,7 @@ export const TicketsPage: React.FC = () => { const teamOptions = useMemo( () => teams.map((t) => ({ - value: t._id!, + value: t.id, label: t.isPersonal ? 'Personal' : t.name, })), [teams], diff --git a/imports/features/tickets/api.ts b/imports/features/tickets/api.ts index 1631fdcea..c18a617d5 100644 --- a/imports/features/tickets/api.ts +++ b/imports/features/tickets/api.ts @@ -1,9 +1,14 @@ /** - * Tickets feature — server-side Meteor API removed in Phase 4. - * Data is now served by timecore (/v1/tickets). + * Tickets feature — Meteor methods removed in Phase 4 (moved to timecore /v1/tickets). + * Collection + publications remain until ClockPage migrates (Phase 5). */ +import { Meteor } from 'meteor/meteor'; +import { Mongo } from 'meteor/mongo'; + +import type { TicketDoc } from './schema'; + +export { type TicketDoc } from './schema'; export type { - TicketDoc, CreateTicketInput, UpdateTicketInput, TicketTimerInput, @@ -11,178 +16,17 @@ export type { AssignTicketInput, } from './schema'; -// ─── Server ─────────────────────────────────────────────────────────────────── - -if (Meteor.isServer) { - // Lazy import ClockEvents to avoid circular dependency - let ClockEvents: Mongo.Collection>; - const getClockEvents = async () => { - if (!ClockEvents) { - const mod = await import('../clock/api'); - ClockEvents = mod.ClockEvents as unknown as Mongo.Collection>; - } - return ClockEvents; - }; - - Meteor.startup(async () => { - await Tickets.createIndexAsync({ teamId: 1 }); - await Tickets.createIndexAsync({ createdBy: 1 }); - await Tickets.createIndexAsync({ teamId: 1, createdBy: 1 }); +// ─── Collection ─────────────────────────────────────────────────────────────── - const methodNames = [ - 'tickets.create', - 'tickets.update', - 'tickets.delete', - 'tickets.start', - 'tickets.stop', - 'tickets.batchUpdateStatus', - 'tickets.assign', - ]; - DDPRateLimiter.addRule({ name: (n) => methodNames.includes(n), userId: () => true }, 30, 60_000); - }); +export const Tickets = new Mongo.Collection('tickets'); - // ─── Publications ──────────────────────────────────────────────────────────── +// ─── Publications ───────────────────────────────────────────────────────────── +if (Meteor.isServer) { Meteor.publish('teamTickets', function (teamIds: string[]) { if (!this.userId) return this.ready(); if (!Array.isArray(teamIds) || teamIds.length === 0) return this.ready(); return Tickets.find({ teamId: { $in: teamIds } }); }); - - Meteor.publish('adminTeamTickets', async function (teamId: string) { - if (!this.userId) return this.ready(); - const team = await Teams.findOneAsync({ _id: teamId, admins: this.userId }); - if (!team) return this.ready(); - return Tickets.find({ teamId }); - }); - - // ─── Methods ────────────────────────────────────────────────────────────────── - - Meteor.methods({ - async 'tickets.create'(fields: { teamId: string; title: string; github?: string; accumulatedTime?: number }) { - if (!this.userId) throw new Meteor.Error('not-authorized'); - const result = createTicketSchema.safeParse(fields); - if (!result.success) throw new Meteor.Error('validation', result.error.issues[0]?.message ?? 'Invalid'); - const { teamId, title, github, accumulatedTime } = result.data; - const team = await Teams.findOneAsync({ _id: teamId, members: this.userId }); - if (!team) throw new Meteor.Error('not-authorized', 'Not a member of this team'); - const ticketId = await Tickets.insertAsync({ - teamId, - title, - github, - accumulatedTime, - createdBy: this.userId, - assignedTo: this.userId, - createdAt: new Date(), - }); - // Add to active clock event if exists - const CE = await getClockEvents(); - const activeEvent = await CE.findOneAsync({ userId: this.userId, teamId, endTime: null }); - if (activeEvent) { - await CE.updateAsync(activeEvent._id!, { - $push: { - tickets: { - ticketId, - startTimestamp: Date.now(), - accumulatedTime, - sessions: [{ startTimestamp: Date.now(), endTimestamp: null }], - }, - } as any, - }); - } - return ticketId; - }, - - async 'tickets.update'(fields: { ticketId: string; updates: Record }) { - if (!this.userId) throw new Meteor.Error('not-authorized'); - const result = updateTicketSchema.safeParse(fields); - if (!result.success) throw new Meteor.Error('validation', result.error.issues[0]?.message ?? 'Invalid'); - const { ticketId, updates } = result.data; - const ticket = await Tickets.findOneAsync(ticketId); - if (!ticket) throw new Meteor.Error('not-found', 'Ticket not found'); - if (ticket.createdBy !== this.userId) throw new Meteor.Error('not-authorized', 'Not your ticket'); - const team = await Teams.findOneAsync({ _id: ticket.teamId, members: this.userId }); - if (!team) throw new Meteor.Error('not-authorized', 'Not a member of this team'); - await Tickets.updateAsync(ticketId, { $set: { ...updates, updatedAt: new Date() } }); - }, - - async 'tickets.delete'(ticketId: string) { - if (!this.userId) throw new Meteor.Error('not-authorized'); - const ticket = await Tickets.findOneAsync(ticketId); - if (!ticket) throw new Meteor.Error('not-found', 'Ticket not found'); - if (ticket.createdBy !== this.userId) throw new Meteor.Error('not-authorized', 'Not your ticket'); - // Remove from clock events - const CE = await getClockEvents(); - await CE.updateAsync( - { userId: this.userId, teamId: ticket.teamId, 'tickets.ticketId': ticketId }, - { $pull: { tickets: { ticketId } } } as any, - { multi: true } as any, - ); - await Tickets.removeAsync(ticketId); - }, - - async 'tickets.start'(fields: { ticketId: string; now: number }) { - if (!this.userId) throw new Meteor.Error('not-authorized'); - const result = ticketTimerSchema.safeParse(fields); - if (!result.success) throw new Meteor.Error('validation', result.error.issues[0]?.message ?? 'Invalid'); - const { ticketId, now } = result.data; - const ticket = await Tickets.findOneAsync(ticketId); - if (!ticket) throw new Meteor.Error('not-found', 'Ticket not found'); - if (ticket.createdBy !== this.userId) throw new Meteor.Error('not-authorized', 'Not your ticket'); - await Tickets.updateAsync(ticketId, { $set: { startTimestamp: now } }); - }, - - async 'tickets.stop'(fields: { ticketId: string; now: number }) { - if (!this.userId) throw new Meteor.Error('not-authorized'); - const result = ticketTimerSchema.safeParse(fields); - if (!result.success) throw new Meteor.Error('validation', result.error.issues[0]?.message ?? 'Invalid'); - const { ticketId, now } = result.data; - const ticket = await Tickets.findOneAsync(ticketId); - if (!ticket) throw new Meteor.Error('not-found', 'Ticket not found'); - if (ticket.createdBy !== this.userId) throw new Meteor.Error('not-authorized', 'Not your ticket'); - if (ticket.startTimestamp) { - const elapsed = Math.floor((now - ticket.startTimestamp) / 1000); - const prev = ticket.accumulatedTime || 0; - await Tickets.updateAsync(ticketId, { - $set: { accumulatedTime: prev + elapsed }, - $unset: { startTimestamp: '' }, - }); - } - }, - - async 'tickets.batchUpdateStatus'(fields: { ticketIds: string[]; status: string; teamId: string }) { - if (!this.userId) throw new Meteor.Error('not-authorized'); - const result = batchUpdateStatusSchema.safeParse(fields); - if (!result.success) throw new Meteor.Error('validation', result.error.issues[0]?.message ?? 'Invalid'); - const { ticketIds, status, teamId } = result.data; - const team = await Teams.findOneAsync({ _id: teamId, admins: this.userId }); - if (!team) throw new Meteor.Error('not-authorized', 'Not a team admin'); - const updateFields: Record = { status, updatedAt: new Date(), updatedBy: this.userId }; - if (status === 'reviewed') { - updateFields.reviewedBy = this.userId; - updateFields.reviewedAt = new Date(); - } - return await Tickets.updateAsync( - { _id: { $in: ticketIds }, teamId }, - { $set: updateFields }, - { multi: true } as any, - ); - }, - - async 'tickets.assign'(fields: { ticketId: string; assignedToUserId: string | null }) { - if (!this.userId) throw new Meteor.Error('not-authorized'); - const result = assignTicketSchema.safeParse(fields); - if (!result.success) throw new Meteor.Error('validation', result.error.issues[0]?.message ?? 'Invalid'); - const { ticketId, assignedToUserId } = result.data; - const ticket = await Tickets.findOneAsync(ticketId); - if (!ticket) throw new Meteor.Error('not-found', 'Ticket not found'); - const team = await Teams.findOneAsync({ _id: ticket.teamId, admins: this.userId }); - if (!team) throw new Meteor.Error('forbidden', 'Only admins can assign tickets'); - if (assignedToUserId) { - const allIds = [...(team.members || []), ...(team.admins || [])]; - if (!allIds.includes(assignedToUserId)) throw new Meteor.Error('bad-request', 'Assignee must be a team member'); - } - await Tickets.updateAsync(ticketId, { $set: { assignedTo: assignedToUserId, updatedAt: new Date() } }); - }, - }); } + diff --git a/imports/lib/TeamContext.tsx b/imports/lib/TeamContext.tsx index 75ac9bbea..2925b83e3 100644 --- a/imports/lib/TeamContext.tsx +++ b/imports/lib/TeamContext.tsx @@ -1,31 +1,40 @@ /** - * TeamContext — Shared selected-team state + subscriptions. + * TeamContext — Shared selected-team state. + * + * Teams are now fetched via REST from timecore (Phase 3). + * Clock events still use Meteor subscriptions (Phase 5 will migrate them). * * Provides: - * • teams — all teams the user belongs to + * • teams — all teams the user belongs to (REST) + * • teamsReady — true once the first fetch completes + * • refetchTeams — callable after mutations to refresh the list * • selectedTeamId — persisted in localStorage - * • activeClockEvent — the user's current open clock event (if any) + * • activeClockEvent — the user's current open clock event (still Meteor) * • currentTime — ticks every second for live timers */ -import { Meteor } from 'meteor/meteor'; import { useFind, useSubscribe } from 'meteor/react-meteor-data'; -import React, { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react'; +import React, { + createContext, + useCallback, + useContext, + useEffect, + useMemo, + useState, +} from 'react'; import type { ClockEventDoc } from '../features/clock/schema'; -import type { TeamDoc } from '../features/teams/schema'; - -// We import collections from their api modules. These are isomorphic — the -// Mongo.Collection constructors run on both client and server. import { ClockEvents } from '../features/clock/api'; -import { Teams } from '../features/teams/api'; +import { teamApi, type Team } from './api'; +import { useSession } from './useSession'; const TEAM_KEY = 'app:selectedTeamId'; export interface TeamContextValue { - teams: TeamDoc[]; + teams: Team[]; teamsReady: boolean; + refetchTeams: () => void; selectedTeamId: string | null; - selectedTeam: TeamDoc | null; + selectedTeam: Team | null; setSelectedTeamId: (id: string) => void; isAdmin: boolean; activeClockEvent: ClockEventDoc | null; @@ -36,6 +45,7 @@ export interface TeamContextValue { const TeamCtx = createContext({ teams: [], teamsReady: false, + refetchTeams: () => {}, selectedTeamId: null, selectedTeam: null, setSelectedTeamId: () => {}, @@ -48,16 +58,33 @@ const TeamCtx = createContext({ export const useTeam = () => useContext(TeamCtx); export const TeamProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => { - const userId = Meteor.userId(); + const { user } = useSession(); + const userId = user?.id ?? null; - // Subscriptions — useSubscribe returns an isLoading() function - const teamsLoading = useSubscribe('userTeams'); - const clockLoading = useSubscribe('clockEventsForUser'); + // ── Teams via REST ────────────────────────────────────────────────────────── - // Data - const teams = useFind(() => Teams.find({}, { sort: { isPersonal: -1, name: 1 } as any }), []); + const [teams, setTeams] = useState([]); + const [teamsReady, setTeamsReady] = useState(false); + + const refetchTeams = useCallback(() => { + teamApi + .getTeams() + .then(setTeams) + .catch(() => {}) + .finally(() => setTeamsReady(true)); + }, []); + + useEffect(() => { + if (!userId) return; + // Ensure a personal workspace exists (idempotent), then load teams + teamApi + .ensurePersonal() + .catch(() => {}) + .finally(() => refetchTeams()); + }, [userId, refetchTeams]); + + // ── Selected team ─────────────────────────────────────────────────────────── - // Selected team const [selectedTeamId, _setSelectedTeamId] = useState(() => { if (typeof window === 'undefined') return null; return localStorage.getItem(TEAM_KEY); @@ -71,12 +98,12 @@ export const TeamProvider: React.FC<{ children: React.ReactNode }> = ({ children // Auto-select first team when none selected useEffect(() => { if (!selectedTeamId && teams.length > 0) { - setSelectedTeamId(teams[0]._id!); + setSelectedTeamId(teams[0].id); } }, [selectedTeamId, teams, setSelectedTeamId]); const selectedTeam = useMemo( - () => teams.find((t) => t._id === selectedTeamId) ?? null, + () => teams.find((t) => t.id === selectedTeamId) ?? null, [teams, selectedTeamId], ); @@ -85,27 +112,35 @@ export const TeamProvider: React.FC<{ children: React.ReactNode }> = ({ children [userId, selectedTeam], ); - // Active clock event for selected team - const activeClockEvent = useFind( - () => - ClockEvents.find( - { userId: userId ?? '__none__', teamId: selectedTeamId ?? '__none__', endTime: null }, - { limit: 1 }, - ), - [userId, selectedTeamId], - )?.[0] ?? null; - - // Live timer — ticks every second + // ── Clock events (still Meteor — Phase 5) ────────────────────────────────── + + const clockLoading = useSubscribe('clockEventsForUser'); + + const activeClockEvent = + useFind( + () => + ClockEvents.find( + { userId: userId ?? '__none__', teamId: selectedTeamId ?? '__none__', endTime: null }, + { limit: 1 }, + ), + [userId, selectedTeamId], + )?.[0] ?? null; + + // ── Live timer ────────────────────────────────────────────────────────────── + const [currentTime, setCurrentTime] = useState(Date.now()); useEffect(() => { const id = setInterval(() => setCurrentTime(Date.now()), 1000); return () => clearInterval(id); }, []); + // ── Context value ─────────────────────────────────────────────────────────── + const value = useMemo( () => ({ teams, - teamsReady: !teamsLoading(), + teamsReady, + refetchTeams, selectedTeamId, selectedTeam, setSelectedTeamId, @@ -114,7 +149,18 @@ export const TeamProvider: React.FC<{ children: React.ReactNode }> = ({ children clockReady: !clockLoading(), currentTime, }), - [teams, teamsLoading, selectedTeamId, selectedTeam, setSelectedTeamId, isAdmin, activeClockEvent, clockLoading, currentTime], + [ + teams, + teamsReady, + refetchTeams, + selectedTeamId, + selectedTeam, + setSelectedTeamId, + isAdmin, + activeClockEvent, + clockLoading, + currentTime, + ], ); return {children}; diff --git a/imports/lib/api.ts b/imports/lib/api.ts index 422d94c86..ded749441 100644 --- a/imports/lib/api.ts +++ b/imports/lib/api.ts @@ -34,9 +34,13 @@ export interface PublicUser { // ─── Base request ───────────────────────────────────────────────────────────── async function request(path: string, options: RequestInit = {}): Promise { + const hasBody = options.body != null; const res = await fetch(`${TIMECORE_BASE_URL}${path}`, { credentials: 'include', - headers: { 'Content-Type': 'application/json', ...options.headers }, + headers: { + ...(hasBody ? { 'Content-Type': 'application/json' } : {}), + ...options.headers, + }, ...options, }); @@ -192,3 +196,81 @@ export const ticketApi = { body: JSON.stringify({ assignedToUserId }), }).then((r) => r.ticket), }; + +// ─── Team API ───────────────────────────────────────────────────────────────── + +export interface Team { + id: string; + name: string; + description: string | null; + members: string[]; + admins: string[]; + code: string; + isPersonal: boolean; + createdAt: string; + updatedAt: string | null; +} + +export interface TeamMember { + id: string; + name: string; + email: string; +} + +export const teamApi = { + getTeams: () => + request<{ teams: Team[] }>('/v1/teams').then((r) => r.teams), + + ensurePersonal: () => + request<{ team: Team }>('/v1/teams/ensure-personal', { method: 'POST' }).then((r) => r.team), + + createTeam: (data: { name: string; description?: string }) => + request<{ team: Team }>('/v1/teams', { + method: 'POST', + body: JSON.stringify(data), + }).then((r) => r.team), + + joinTeam: (teamCode: string) => + request<{ team: Team }>('/v1/teams/join', { + method: 'POST', + body: JSON.stringify({ teamCode }), + }).then((r) => r.team), + + renameTeam: (id: string, newName: string) => + request<{ team: Team }>(`/v1/teams/${encodeURIComponent(id)}/name`, { + method: 'PUT', + body: JSON.stringify({ newName }), + }).then((r) => r.team), + + deleteTeam: (id: string) => + request<{ ok: boolean }>(`/v1/teams/${encodeURIComponent(id)}`, { method: 'DELETE' }), + + getMembers: (id: string) => + request<{ members: TeamMember[] }>(`/v1/teams/${encodeURIComponent(id)}/members`).then( + (r) => r.members, + ), + + inviteMember: (id: string, email: string) => + request<{ ok: boolean }>(`/v1/teams/${encodeURIComponent(id)}/invite`, { + method: 'POST', + body: JSON.stringify({ email }), + }), + + removeMember: (id: string, userId: string) => + request<{ ok: boolean }>( + `/v1/teams/${encodeURIComponent(id)}/members/${encodeURIComponent(userId)}`, + { method: 'DELETE' }, + ), + + setMemberRole: (id: string, userId: string, role: 'admin' | 'member') => + request<{ ok: boolean }>( + `/v1/teams/${encodeURIComponent(id)}/members/${encodeURIComponent(userId)}/role`, + { method: 'PUT', body: JSON.stringify({ role }) }, + ), + + setMemberPassword: (id: string, userId: string, newPassword: string) => + request<{ ok: boolean }>( + `/v1/teams/${encodeURIComponent(id)}/members/${encodeURIComponent(userId)}/password`, + { method: 'PUT', body: JSON.stringify({ newPassword }) }, + ), +}; From e6eab60ebf4df15432f8e3901af53ed3ee015327 Mon Sep 17 00:00:00 2001 From: Michael Fisher Date: Tue, 21 Apr 2026 20:02:44 -0400 Subject: [PATCH 07/26] Refactor clock feature to use REST API for teams and clock events - Removed Meteor subscriptions and methods for clock events and tickets. - Integrated REST API calls for starting/stopping clock events and managing tickets. - Updated ClockPage and TimesheetPage components to handle new API structure. - Enhanced TeamContext to manage active clock events via REST. - Adjusted API definitions to support new clock event and ticket structures. --- .github/plans/timecore.md | 44 +-- imports/features/clock/ClockPage.tsx | 105 ++--- imports/features/clock/TimesheetPage.tsx | 83 ++-- imports/features/clock/api.ts | 467 +---------------------- imports/lib/TeamContext.tsx | 65 ++-- imports/lib/api.ts | 83 ++++ 6 files changed, 245 insertions(+), 602 deletions(-) diff --git a/.github/plans/timecore.md b/.github/plans/timecore.md index e4286d322..e19f2fb58 100644 --- a/.github/plans/timecore.md +++ b/.github/plans/timecore.md @@ -89,21 +89,21 @@ timecore's `users` collection managed by better-auth. **Goal:** Move all team management to timecore REST. ### timehuddle changes -- [ ] Replace all 10 team Meteor methods with REST calls -- [ ] Replace `userTeams` / `teamMembers` publications with REST + stale-while-revalidate -- [ ] Remove `imports/features/teams/api.ts` server half +- [x] Replace all 10 team Meteor methods with REST calls +- [x] Replace `userTeams` / `teamMembers` publications with REST + stale-while-revalidate +- [x] Remove `imports/features/teams/api.ts` server half ### timecore changes -- [ ] `GET /v1/teams` — teams for current user -- [ ] `POST /v1/teams` — create team -- [ ] `DELETE /v1/teams/:id` — delete team -- [ ] `PUT /v1/teams/:id/name` — rename -- [ ] `GET /v1/teams/:id/members` — member list with user details -- [ ] `POST /v1/teams/:id/invite` — invite by email -- [ ] `POST /v1/teams/:id/join` — join by code -- [ ] `DELETE /v1/teams/:id/members/:userId` — remove member -- [ ] `PUT /v1/teams/:id/members/:userId/role` — promote/demote admin -- [ ] `PUT /v1/teams/:id/members/:userId/password` — admin set member password +- [x] `GET /v1/teams` — teams for current user +- [x] `POST /v1/teams` — create team +- [x] `DELETE /v1/teams/:id` — delete team +- [x] `PUT /v1/teams/:id/name` — rename +- [x] `GET /v1/teams/:id/members` — member list with user details +- [x] `POST /v1/teams/:id/invite` — invite by email +- [x] `POST /v1/teams/:id/join` — join by code +- [x] `DELETE /v1/teams/:id/members/:userId` — remove member +- [x] `PUT /v1/teams/:id/members/:userId/role` — promote/demote admin +- [x] `PUT /v1/teams/:id/members/:userId/password` — admin set member password --- @@ -113,18 +113,18 @@ timecore's `users` collection managed by better-auth. **Goal:** Move ticket CRUD and timer operations to timecore. ### timehuddle changes -- [ ] Replace 6 ticket Meteor methods with REST calls -- [ ] Replace `teamTickets` / `adminTeamTickets` publications with REST + poll or SSE -- [ ] Remove `imports/features/tickets/api.ts` server half +- [x] Replace 6 ticket Meteor methods with REST calls +- [x] Replace `teamTickets` / `adminTeamTickets` publications with REST + poll or SSE +- [x] Remove `imports/features/tickets/api.ts` server half - [ ] Admin ticket review page — team-admin view of all tickets across managed teams, with batch status update ### timecore changes -- [ ] `GET /v1/tickets?teamId=` — list tickets for team -- [ ] `POST /v1/tickets` — create ticket -- [ ] `PUT /v1/tickets/:id` — update ticket -- [ ] `DELETE /v1/tickets/:id` — delete ticket -- [ ] `POST /v1/tickets/:id/start` — start timer -- [ ] `POST /v1/tickets/:id/stop` — stop timer +- [x] `GET /v1/tickets?teamId=` — list tickets for team +- [x] `POST /v1/tickets` — create ticket +- [x] `PUT /v1/tickets/:id` — update ticket +- [x] `DELETE /v1/tickets/:id` — delete ticket +- [x] `POST /v1/tickets/:id/start` — start timer +- [x] `POST /v1/tickets/:id/stop` — stop timer - [ ] `POST /v1/tickets/batch-status` — batch status update - [ ] `PUT /v1/tickets/:id/assign` — assign to user diff --git a/imports/features/clock/ClockPage.tsx b/imports/features/clock/ClockPage.tsx index 09f560f8c..c2c27f4cd 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,21 @@ 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 +83,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 +98,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,8 +150,8 @@ 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( @@ -187,7 +202,7 @@ export const ClockPage: React.FC = () => { @@ -264,7 +279,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) @@ -316,10 +331,10 @@ export const ClockPage: React.FC = () => {
        {availableTickets.slice(0, 5).map((t) => ( @@ -363,7 +378,7 @@ export const ClockPage: React.FC = () => { - diff --git a/imports/features/clock/TimesheetPage.tsx b/imports/features/clock/TimesheetPage.tsx index f6688ffdd..74907e890 100644 --- a/imports/features/clock/TimesheetPage.tsx +++ b/imports/features/clock/TimesheetPage.tsx @@ -29,27 +29,16 @@ 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'; +import { clockApi, type ClockEvent } from '../../lib/api'; +import { useSession } from '../../lib/useSession'; -interface TimesheetSession { - id: string; - date: string; - startTime: Date; - endTime: Date | null; - duration: number | null; - isActive: boolean; - teamName: string | null; - teamId: string; - accumulatedTime: number; -} interface TimesheetData { - sessions: TimesheetSession[]; + sessions: ClockEvent[]; summary: { totalSeconds: number; totalSessions: number; @@ -94,23 +83,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 +108,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 +178,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 @@ -222,16 +210,16 @@ export const TimesheetPage: React.FC = () => { )} {/* Loading */} - {getTimesheet.loading && ( + {loading && (
        )} {/* Error */} - {getTimesheet.error && ( + {error && ( - {getTimesheet.error} + {error} )} @@ -254,15 +242,23 @@ export const TimesheetPage: React.FC = () => { - {data.sessions.map((s) => ( + {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(new Date(s.startTime), true)} - {formatTime(new Date(s.startTime))} - {s.endTime ? formatTime(new Date(s.endTime)) : '—'} - {s.duration ? formatDuration(s.duration) : '—'} - {s.teamName ?? '—'} + {formatDate(startTime, true)} + {formatTime(startTime)} + {endTime ? formatTime(endTime) : '—'} + {duration ? formatDuration(duration) : '—'} + {teamName} - {s.isActive ? ( + {isActive ? ( Active @@ -272,14 +268,15 @@ export const TimesheetPage: React.FC = () => { )} - ))} + ); + })} )} - {data && data.sessions.length === 0 && !getTimesheet.loading && ( + {data && data.sessions.length === 0 && !loading && ( diff --git a/imports/features/clock/api.ts b/imports/features/clock/api.ts index 87f82b00a..ad65563f9 100644 --- a/imports/features/clock/api.ts +++ b/imports/features/clock/api.ts @@ -1,473 +1,8 @@ -import { DDPRateLimiter } from 'meteor/ddp-rate-limiter'; -import { Meteor } from 'meteor/meteor'; import { Mongo } from 'meteor/mongo'; -import { getUserDisplayName } from '../../lib/userDisplayName'; -import { Teams } from '../teams/api'; -import { - clockEventStartSchema, - clockEventStopSchema, - clockEventTicketSchema, - timesheetQuerySchema, - updateClockEventTimesSchema, - updateYoutubeLinkSchema, - type ClockEventDoc, - type SessionDoc, -} from './schema'; +import type { ClockEventDoc, SessionDoc } from './schema'; // ─── Collections ────────────────────────────────────────────────────────────── export const ClockEvents = new Mongo.Collection('clockevents'); export const Sessions = new Mongo.Collection('sessions'); - -// ─── Helpers ────────────────────────────────────────────────────────────────── - -function formatDurationText(totalSeconds: number): string { - const h = Math.floor(totalSeconds / 3600); - const m = Math.floor((totalSeconds % 3600) / 60); - if (h > 0) return `${h}h ${m}m`; - return `${m}m`; -} - -async function stopTicketInClockEvent( - clockEventId: string, - ticketId: string, - now: number, -): Promise { - const clockEvent = await ClockEvents.findOneAsync(clockEventId); - if (!clockEvent) return; - const entry = clockEvent.tickets?.find((t) => t.ticketId === ticketId); - if (!entry || !entry.startTimestamp) return; - const elapsed = Math.floor((now - entry.startTimestamp) / 1000); - const prev = entry.accumulatedTime || 0; - - // Close the open session - const sessions = entry.sessions ?? []; - const updatedSessions = sessions.map((s) => - s.endTimestamp === null ? { ...s, endTimestamp: now } : s, - ); - - await ClockEvents.updateAsync( - { _id: clockEventId, 'tickets.ticketId': ticketId }, - { - $set: { - 'tickets.$.accumulatedTime': prev + elapsed, - 'tickets.$.sessions': updatedSessions, - }, - $unset: { 'tickets.$.startTimestamp': '' }, - }, - ); -} - -// ─── Server ─────────────────────────────────────────────────────────────────── - -if (Meteor.isServer) { - // Lazy import Tickets to avoid circular dependency - let Tickets: Mongo.Collection>; - const getTickets = async () => { - if (!Tickets) { - const mod = await import('../tickets/api'); - Tickets = mod.Tickets as unknown as Mongo.Collection>; - } - return Tickets; - }; - - Meteor.startup(async () => { - await ClockEvents.createIndexAsync({ userId: 1, teamId: 1, endTime: 1 }); - await ClockEvents.createIndexAsync({ 'tickets.ticketId': 1 }); - await Sessions.createIndexAsync({ userId: 1, teamId: 1 }); - - const methodNames = [ - 'clock.start', - 'clock.stop', - 'clock.addTicket', - 'clock.stopTicket', - 'clock.updateYoutubeLink', - 'clock.updateTimes', - 'clock.getTimesheetData', - ]; - DDPRateLimiter.addRule({ name: (n) => methodNames.includes(n), userId: () => true }, 30, 60_000); - - // Auto-clock-out: end events running 8+ hours (push + inbox parity with timeharbor-old) - const EIGHT_HOURS_MS = 8 * 60 * 60 * 1000; - Meteor.setInterval(async () => { - try { - const now = Date.now(); - const cutoff = now - EIGHT_HOURS_MS; - const stale = await ClockEvents.find({ endTime: null, startTimestamp: { $lt: cutoff } }).fetchAsync(); - if (stale.length === 0) return; - - const TicketsColl = await getTickets(); - const { notifyUser, notifyTeamAdmins, APP_NAME_PUSH, PUSH_ICON } = await import('../../server/push'); - - for (const event of stale) { - try { - const startTs = event.startTimestamp; - const prevAcc = event.accumulatedTime || 0; - const elapsed = Math.floor((now - startTs) / 1000); - const totalSeconds = prevAcc + elapsed; - const durationText = formatDurationText(totalSeconds); - - if (event.tickets) { - for (const t of event.tickets.filter((t) => t.startTimestamp)) { - await stopTicketInClockEvent(event._id!, t.ticketId, now); - } - } - - const running = await TicketsColl.find({ - teamId: event.teamId, - createdBy: event.userId, - startTimestamp: { $exists: true }, - }).fetchAsync(); - for (const ticket of running) { - const telapsed = Math.floor((now - (ticket as any).startTimestamp) / 1000); - const tprev = (ticket as any).accumulatedTime || 0; - await TicketsColl.updateAsync(ticket._id!, { - $set: { accumulatedTime: tprev + telapsed }, - $unset: { startTimestamp: '' }, - }); - } - - await ClockEvents.updateAsync(event._id!, { - $set: { endTime: new Date(), accumulatedTime: totalSeconds }, - }); - - const user = await Meteor.users.findOneAsync(event.userId); - const userName = getUserDisplayName(user, 'A user'); - const team = await Teams.findOneAsync(event.teamId); - const teamName = team?.name || 'a team'; - - try { - await notifyUser(event.userId, { - title: `${APP_NAME_PUSH} - Auto Clock Out`, - body: `You were automatically clocked out after 8 hours of continuous work to prevent burnout. Total time: ${durationText}`, - icon: PUSH_ICON, - badge: PUSH_ICON, - tag: `auto-clockout-user-${event.userId}-${Date.now()}`, - data: { - type: 'auto-clock-out', - userId: event.userId, - userName, - teamName, - teamId: event.teamId, - clockEventId: event._id, - duration: durationText, - autoClockOut: true, - url: '/app/tickets', - }, - }); - } catch (e) { - console.error('[Push] auto clock-out user notify:', e); - } - - try { - const peer = encodeURIComponent(event.userId); - const tid = encodeURIComponent(event.teamId); - await notifyTeamAdmins(event.teamId, { - title: `${APP_NAME_PUSH} - Auto Clock Out`, - body: `${userName} was automatically clocked out of ${teamName} after ${durationText} (8-hour burnout prevention)`, - icon: PUSH_ICON, - badge: PUSH_ICON, - tag: `auto-clockout-admin-${event.userId}-${Date.now()}`, - data: { - type: 'clock-out', - userId: event.userId, - userName, - teamName, - teamId: event.teamId, - clockEventId: event._id, - duration: durationText, - autoClockOut: true, - url: `/app/messages?openTeam=${tid}&openPeer=${peer}`, - }, - }); - } catch (e) { - console.error('[Push] auto clock-out admin notify:', e); - } - } catch (err) { - console.error(`[Clock] auto clock-out failed for ${event._id}:`, err); - } - } - } catch (err) { - // Mongo monitor hiccups can happen in dev; don't crash process. - console.error('[Clock] auto clock-out interval failed:', err); - } - }, 60_000); - }); - - // ─── Publications ──────────────────────────────────────────────────────────── - - Meteor.publish('clockEventsForUser', function () { - if (!this.userId) return this.ready(); - return ClockEvents.find({ userId: this.userId }); - }); - - Meteor.publish('clockEventsForTeams', function (teamIds: string[]) { - if (!this.userId) return this.ready(); - if (!Array.isArray(teamIds) || teamIds.length === 0) return this.ready(); - return ClockEvents.find({ teamId: { $in: teamIds } }); - }); - - // ─── Methods ────────────────────────────────────────────────────────────────── - - Meteor.methods({ - async 'clock.start'(fields: { teamId: string }) { - if (!this.userId) throw new Meteor.Error('not-authorized'); - const result = clockEventStartSchema.safeParse(fields); - if (!result.success) throw new Meteor.Error('validation', result.error.issues[0]?.message ?? 'Invalid'); - const { teamId } = result.data; - // Close any open clock events for this user/team - await ClockEvents.updateAsync( - { userId: this.userId, teamId, endTime: null }, - { $set: { endTime: new Date() } }, - { multi: true } as any, - ); - const clockEventId = await ClockEvents.insertAsync({ - userId: this.userId, - teamId, - startTimestamp: Date.now(), - accumulatedTime: 0, - tickets: [], - endTime: null, - }); - - try { - const { notifyTeamAdmins, APP_NAME_PUSH, PUSH_ICON } = await import('../../server/push'); - const user = await Meteor.users.findOneAsync(this.userId); - const userName = getUserDisplayName(user, 'A user'); - const team = await Teams.findOneAsync(teamId); - const teamName = team?.name || 'a team'; - const peer = encodeURIComponent(this.userId); - const tid = encodeURIComponent(teamId); - await notifyTeamAdmins(teamId, { - title: APP_NAME_PUSH, - body: `${userName} clocked in to ${teamName}`, - icon: PUSH_ICON, - badge: PUSH_ICON, - tag: `clockin-${this.userId}-${Date.now()}`, - data: { - type: 'clock-in', - userId: this.userId, - userName, - teamName, - teamId, - clockEventId, - url: `/app/messages?openTeam=${tid}&openPeer=${peer}`, - }, - }); - } catch (e) { - console.error('[Push] clock-in notify:', e); - } - - return clockEventId; - }, - - async 'clock.stop'(fields: { teamId: string; youtubeShortLink?: string }) { - if (!this.userId) throw new Meteor.Error('not-authorized'); - const result = clockEventStopSchema.safeParse(fields); - if (!result.success) throw new Meteor.Error('validation', result.error.issues[0]?.message ?? 'Invalid'); - const { teamId, youtubeShortLink } = result.data; - const clockEvent = await ClockEvents.findOneAsync({ userId: this.userId, teamId, endTime: null }); - if (!clockEvent) return; - - const now = Date.now(); - // Accumulate time - if (clockEvent.startTimestamp) { - const elapsed = Math.floor((now - clockEvent.startTimestamp) / 1000); - const prev = clockEvent.accumulatedTime || 0; - await ClockEvents.updateAsync(clockEvent._id!, { $set: { accumulatedTime: prev + elapsed } }); - } - // Stop all running tickets - if (clockEvent.tickets) { - for (const t of clockEvent.tickets.filter((t) => t.startTimestamp)) { - await stopTicketInClockEvent(clockEvent._id!, t.ticketId, now); - } - } - // Also stop ticket collection timers - const TicketsColl = await getTickets(); - const running = await TicketsColl.find({ - teamId: clockEvent.teamId, - createdBy: this.userId, - startTimestamp: { $exists: true }, - }).fetchAsync(); - for (const ticket of running) { - const elapsed = Math.floor((now - (ticket as any).startTimestamp) / 1000); - const prev = (ticket as any).accumulatedTime || 0; - await TicketsColl.updateAsync(ticket._id!, { - $set: { accumulatedTime: prev + elapsed }, - $unset: { startTimestamp: '' }, - }); - } - // End event - const setFields: Record = { endTime: new Date() }; - const link = typeof youtubeShortLink === 'string' ? youtubeShortLink.trim() : ''; - if (link) setFields.youtubeShortLink = link; - await ClockEvents.updateAsync(clockEvent._id!, { $set: setFields }); - - let durationText = ''; - if (clockEvent.startTimestamp) { - const elapsed = Math.floor((now - clockEvent.startTimestamp) / 1000); - const prev = clockEvent.accumulatedTime || 0; - durationText = formatDurationText(prev + elapsed); - } - - try { - const { notifyTeamAdmins, APP_NAME_PUSH, PUSH_ICON } = await import('../../server/push'); - const user = await Meteor.users.findOneAsync(this.userId); - const userName = getUserDisplayName(user, 'A user'); - const team = await Teams.findOneAsync(teamId); - const teamName = team?.name || 'a team'; - const peer = encodeURIComponent(this.userId); - const tid = encodeURIComponent(teamId); - await notifyTeamAdmins(teamId, { - title: APP_NAME_PUSH, - body: `${userName} clocked out of ${teamName} (${durationText})`, - icon: PUSH_ICON, - badge: PUSH_ICON, - tag: `clockout-${this.userId}-${Date.now()}`, - data: { - type: 'clock-out', - userId: this.userId, - userName, - teamName, - teamId, - clockEventId: clockEvent._id, - duration: durationText, - url: `/app/messages?openTeam=${tid}&openPeer=${peer}`, - }, - }); - } catch (e) { - console.error('[Push] clock-out notify:', e); - } - }, - - async 'clock.addTicket'(fields: { clockEventId: string; ticketId: string; now: number }) { - if (!this.userId) throw new Meteor.Error('not-authorized'); - const result = clockEventTicketSchema.safeParse(fields); - if (!result.success) throw new Meteor.Error('validation', result.error.issues[0]?.message ?? 'Invalid'); - const { clockEventId, ticketId, now } = result.data; - const clockEvent = await ClockEvents.findOneAsync(clockEventId); - if (!clockEvent) return; - const existing = clockEvent.tickets?.find((t) => t.ticketId === ticketId); - if (existing) { - await ClockEvents.updateAsync( - { _id: clockEventId, 'tickets.ticketId': ticketId }, - { - $set: { 'tickets.$.startTimestamp': now }, - $push: { 'tickets.$.sessions': { startTimestamp: now, endTimestamp: null } } as any, - }, - ); - } else { - const TicketsColl = await getTickets(); - const ticket = await TicketsColl.findOneAsync(ticketId); - const initialTime = ticket ? ((ticket as any).accumulatedTime || 0) : 0; - await ClockEvents.updateAsync(clockEventId, { - $push: { - tickets: { - ticketId, - startTimestamp: now, - accumulatedTime: initialTime, - sessions: [{ startTimestamp: now, endTimestamp: null }], - }, - } as any, - }); - } - }, - - async 'clock.stopTicket'(fields: { clockEventId: string; ticketId: string; now: number }) { - if (!this.userId) throw new Meteor.Error('not-authorized'); - const result = clockEventTicketSchema.safeParse(fields); - if (!result.success) throw new Meteor.Error('validation', result.error.issues[0]?.message ?? 'Invalid'); - await stopTicketInClockEvent(result.data.clockEventId, result.data.ticketId, result.data.now); - }, - - async 'clock.updateYoutubeLink'(fields: { clockEventId: string; youtubeShortLink: string }) { - if (!this.userId) throw new Meteor.Error('not-authorized'); - const result = updateYoutubeLinkSchema.safeParse(fields); - if (!result.success) throw new Meteor.Error('validation', result.error.issues[0]?.message ?? 'Invalid'); - const clockEvent = await ClockEvents.findOneAsync({ _id: result.data.clockEventId, userId: this.userId }); - if (!clockEvent) throw new Meteor.Error('not-found', 'Clock event not found'); - const link = result.data.youtubeShortLink.trim(); - if (link) { - await ClockEvents.updateAsync(result.data.clockEventId, { $set: { youtubeShortLink: link } }); - } - }, - - async 'clock.updateTimes'(fields: { clockEventId: string; startTimestamp?: number; endTimestamp?: number | null }) { - if (!this.userId) throw new Meteor.Error('not-authorized'); - const result = updateClockEventTimesSchema.safeParse(fields); - if (!result.success) throw new Meteor.Error('validation', result.error.issues[0]?.message ?? 'Invalid'); - const { clockEventId, startTimestamp, endTimestamp } = result.data; - const clockEvent = await ClockEvents.findOneAsync(clockEventId); - if (!clockEvent) throw new Meteor.Error('not-found', 'Clock event not found'); - // Must be team admin - const team = await Teams.findOneAsync({ _id: clockEvent.teamId, admins: this.userId }); - if (!team) throw new Meteor.Error('not-authorized', 'Not authorized'); - if (typeof startTimestamp === 'number' && typeof endTimestamp === 'number' && endTimestamp < startTimestamp) { - throw new Meteor.Error('validation', 'Clock-out cannot be earlier than clock-in'); - } - const $set: Record = {}; - if (typeof startTimestamp === 'number') $set.startTimestamp = startTimestamp; - if (endTimestamp === null) $set.endTime = null; - else if (typeof endTimestamp === 'number') $set.endTime = new Date(endTimestamp); - if (Object.keys($set).length > 0) await ClockEvents.updateAsync(clockEventId, { $set }); - }, - - async 'clock.getTimesheetData'(fields: { userId: string; startDate: string; endDate: string }) { - if (!this.userId) throw new Meteor.Error('not-authorized'); - const result = timesheetQuerySchema.safeParse(fields); - if (!result.success) throw new Meteor.Error('validation', result.error.issues[0]?.message ?? 'Invalid'); - const { userId, startDate, endDate } = result.data; - // Verify shared team membership - const userTeams = await Teams.find({ members: this.userId }).fetchAsync(); - const hasPermission = userTeams.some( - (t) => t.members.includes(userId) || t.admins.includes(userId), - ); - if (!hasPermission) throw new Meteor.Error('not-authorized', 'Cannot view this user\'s timesheet'); - - const start = new Date(`${startDate}T00:00:00`); - const end = new Date(`${endDate}T23:59:59`); - const events = await ClockEvents.find({ - userId, - startTimestamp: { $gte: start.getTime(), $lte: end.getTime() }, - }).fetchAsync(); - - const sessions = await Promise.all( - events.map(async (event) => { - const startTime = new Date(event.startTimestamp); - const endTime = event.endTime ?? null; - const duration = endTime ? (endTime.getTime() - startTime.getTime()) / 1000 : null; - const team = await Teams.findOneAsync(event.teamId); - return { - id: event._id, - date: startTime.toISOString().split('T')[0], - startTime, - endTime, - duration, - isActive: !endTime, - teamName: team?.name ?? null, - teamId: event.teamId, - accumulatedTime: event.accumulatedTime || 0, - }; - }), - ); - sessions.sort((a, b) => b.startTime.getTime() - a.startTime.getTime()); - - const totalSeconds = sessions.reduce((sum, s) => sum + (s.duration || 0), 0); - const completed = sessions.filter((s) => s.duration != null); - const avgSeconds = completed.length > 0 ? totalSeconds / completed.length : 0; - const uniqueDates = new Set(sessions.map((s) => s.date)); - - return { - sessions, - summary: { - totalSeconds, - totalSessions: sessions.length, - completedSessions: completed.length, - averageSessionSeconds: avgSeconds, - workingDays: uniqueDates.size, - }, - }; - }, - }); -} diff --git a/imports/lib/TeamContext.tsx b/imports/lib/TeamContext.tsx index 2925b83e3..0bd17dd0c 100644 --- a/imports/lib/TeamContext.tsx +++ b/imports/lib/TeamContext.tsx @@ -1,18 +1,18 @@ /** * TeamContext — Shared selected-team state. * - * Teams are now fetched via REST from timecore (Phase 3). - * Clock events still use Meteor subscriptions (Phase 5 will migrate them). + * Teams and clock events are fetched via REST from timecore. * * Provides: - * • teams — all teams the user belongs to (REST) - * • teamsReady — true once the first fetch completes - * • refetchTeams — callable after mutations to refresh the list - * • selectedTeamId — persisted in localStorage - * • activeClockEvent — the user's current open clock event (still Meteor) - * • currentTime — ticks every second for live timers + * • teams — all teams the user belongs to (REST) + * • teamsReady — true once the first fetch completes + * • refetchTeams — callable after mutations to refresh the list + * • selectedTeamId — persisted in localStorage + * • activeClockEvent — the user's current open clock event (REST) + * • clockReady — true once the first clock fetch completes + * • refetchClock — callable after clock mutations to refresh + * • currentTime — ticks every second for live timers */ -import { useFind, useSubscribe } from 'meteor/react-meteor-data'; import React, { createContext, useCallback, @@ -22,9 +22,7 @@ import React, { useState, } from 'react'; -import type { ClockEventDoc } from '../features/clock/schema'; -import { ClockEvents } from '../features/clock/api'; -import { teamApi, type Team } from './api'; +import { teamApi, clockApi, type Team, type ClockEvent } from './api'; import { useSession } from './useSession'; const TEAM_KEY = 'app:selectedTeamId'; @@ -37,8 +35,9 @@ export interface TeamContextValue { selectedTeam: Team | null; setSelectedTeamId: (id: string) => void; isAdmin: boolean; - activeClockEvent: ClockEventDoc | null; + activeClockEvent: ClockEvent | null; clockReady: boolean; + refetchClock: () => void; currentTime: number; } @@ -52,6 +51,7 @@ const TeamCtx = createContext({ isAdmin: false, activeClockEvent: null, clockReady: false, + refetchClock: () => {}, currentTime: Date.now(), }); @@ -112,19 +112,30 @@ export const TeamProvider: React.FC<{ children: React.ReactNode }> = ({ children [userId, selectedTeam], ); - // ── Clock events (still Meteor — Phase 5) ────────────────────────────────── + // ── Clock events via REST ─────────────────────────────────────────────────── - const clockLoading = useSubscribe('clockEventsForUser'); + const [activeClockEvent, setActiveClockEvent] = useState(null); + const [clockReady, setClockReady] = useState(false); - const activeClockEvent = - useFind( - () => - ClockEvents.find( - { userId: userId ?? '__none__', teamId: selectedTeamId ?? '__none__', endTime: null }, - { limit: 1 }, - ), - [userId, selectedTeamId], - )?.[0] ?? null; + const refetchClock = useCallback(async () => { + if (!userId) { + setActiveClockEvent(null); + setClockReady(true); + return; + } + try { + const event = await clockApi.getActive(); + setActiveClockEvent(event); + } catch { + setActiveClockEvent(null); + } finally { + setClockReady(true); + } + }, [userId]); + + useEffect(() => { + void refetchClock(); + }, [refetchClock, selectedTeamId]); // ── Live timer ────────────────────────────────────────────────────────────── @@ -146,7 +157,8 @@ export const TeamProvider: React.FC<{ children: React.ReactNode }> = ({ children setSelectedTeamId, isAdmin, activeClockEvent, - clockReady: !clockLoading(), + clockReady, + refetchClock, currentTime, }), [ @@ -158,7 +170,8 @@ export const TeamProvider: React.FC<{ children: React.ReactNode }> = ({ children setSelectedTeamId, isAdmin, activeClockEvent, - clockLoading, + clockReady, + refetchClock, currentTime, ], ); diff --git a/imports/lib/api.ts b/imports/lib/api.ts index ded749441..7bc4f2d06 100644 --- a/imports/lib/api.ts +++ b/imports/lib/api.ts @@ -274,3 +274,86 @@ export const teamApi = { { method: 'PUT', body: JSON.stringify({ newPassword }) }, ), }; + +// ─── Clock API ──────────────────────────────────────────────────────────────── + +export interface ClockTicketSession { + startTimestamp: number; + endTimestamp: number | null; +} + +export interface ClockEventTicket { + ticketId: string; + startTimestamp: number | null; + accumulatedTime: number; + sessions: ClockTicketSession[]; +} + +export interface ClockEvent { + id: string; + userId: string; + teamId: string; + startTimestamp: number; + accumulatedTime: number; + tickets: ClockEventTicket[]; + endTime: string | null; + youtubeShortLink: string | null; +} + +export const clockApi = { + /** Clock in to a team. Returns the new clock event. */ + start: (teamId: string) => + request<{ event: ClockEvent }>('/v1/clock/start', { + method: 'POST', + body: JSON.stringify({ teamId }), + }).then((r) => r.event), + + /** Clock out of a team. */ + stop: (teamId: string, youtubeShortLink?: string) => + request<{ event: ClockEvent }>('/v1/clock/stop', { + method: 'POST', + body: JSON.stringify({ teamId, ...(youtubeShortLink ? { youtubeShortLink } : {}) }), + }).then((r) => r.event), + + /** Start a ticket timer inside an active clock event. */ + addTicket: (clockEventId: string, ticketId: string, now: number) => + request<{ event: ClockEvent }>(`/v1/clock/${encodeURIComponent(clockEventId)}/ticket/start`, { + method: 'POST', + body: JSON.stringify({ ticketId, now }), + }).then((r) => r.event), + + /** Stop a ticket timer inside a clock event. */ + stopTicket: (clockEventId: string, ticketId: string, now: number) => + request<{ event: ClockEvent }>(`/v1/clock/${encodeURIComponent(clockEventId)}/ticket/stop`, { + method: 'POST', + body: JSON.stringify({ ticketId, now }), + }).then((r) => r.event), + + /** Get the current user's active clock event (any team), or null. */ + getActive: () => + request<{ event: ClockEvent | null }>('/v1/clock/active').then((r) => r.event), + + /** Get all clock events for the current user. */ + getEvents: () => + request<{ events: ClockEvent[] }>('/v1/clock/events').then((r) => r.events), + + /** Get timesheet data for a user over a date range. */ + getTimesheet: (userId: string, startDate: string, endDate: string) => + request<{ + sessions: ClockEvent[]; + summary: { + totalSeconds: number; + totalSessions: number; + completedSessions: number; + averageSessionSeconds: number; + workingDays: number; + }; + }>(`/v1/clock/timesheet?userId=${encodeURIComponent(userId)}&startDate=${startDate}&endDate=${endDate}`), + + /** Open an SSE connection for live team clock state. Returns an EventSource. */ + openLiveStream: (teamIds: string[]): EventSource => + new EventSource( + `${TIMECORE_BASE_URL}/v1/clock/live?teamIds=${teamIds.map(encodeURIComponent).join(',')}`, + { withCredentials: true }, + ), +}; From 75ea941d6c328ccaeb3b244f8631f2efd0621d31 Mon Sep 17 00:00:00 2001 From: Michael Fisher Date: Tue, 21 Apr 2026 20:20:47 -0400 Subject: [PATCH 08/26] plans: add mobile migration plan and push notification handling --- .github/plans/mobile.md | 33 ++++++++++++++++++++ .github/plans/timecore.md | 63 ++++++++++----------------------------- 2 files changed, 48 insertions(+), 48 deletions(-) create mode 100644 .github/plans/mobile.md diff --git a/.github/plans/mobile.md b/.github/plans/mobile.md new file mode 100644 index 000000000..c467e175f --- /dev/null +++ b/.github/plans/mobile.md @@ -0,0 +1,33 @@ +## Post-Migration: Mobile Path + +Once Meteor is removed the codebase is universally portable: + +| Target | Additional work | +|---|---| +| **PWA** | Add `manifest.json`, done — `sw.js` already exists | +| **Capacitor** | `npx cap init`, wrap existing React app, ~1 week | +| **Expo (React Native)** | Shared TanStack Query hooks + API layer, new native UI layer | + +better-auth supports cookie auth (web) and token auth (mobile) natively — no changes needed +to timecore when adding mobile clients. + +--- + +## Push Notifications + +**Effort:** 1 day +**Goal:** Move VAPID/FCM handling to timecore. The existing `public/sw.js` is already +Meteor-independent and stays as-is. + +### timehuddle changes +- [ ] Replace `getVapidPublicKey`, `push.subscribe`, `push.unsubscribe` Meteor methods +- [ ] Remove `imports/server/push.ts` +- [ ] Remove `imports/lib/pushNotificationsClient.ts` Meteor dependency + +### timecore changes +- [ ] `GET /v1/push/vapid-key` — return public VAPID key +- [ ] `POST /v1/push/subscribe` — store subscription +- [ ] `DELETE /v1/push/subscribe` — remove subscription +- [ ] Move web-push + FCM sending logic from Meteor into timecore service + +--- \ No newline at end of file diff --git a/.github/plans/timecore.md b/.github/plans/timecore.md index e19f2fb58..b3d2227c4 100644 --- a/.github/plans/timecore.md +++ b/.github/plans/timecore.md @@ -137,20 +137,20 @@ timecore's `users` collection managed by better-auth. requirement — the team dashboard shows live clock state for all members. ### timehuddle changes -- [ ] Replace 7 clock Meteor methods with REST calls -- [ ] Replace `clockEventsForUser` publication with REST + refresh on action +- [x] Replace 7 clock Meteor methods with REST calls +- [x] Replace `clockEventsForUser` publication with REST + refresh on action - [ ] Replace `clockEventsForTeams` publication with **SSE** stream -- [ ] Remove `imports/features/clock/api.ts` server half +- [x] Remove `imports/features/clock/api.ts` server half - [ ] Member Activity page — team-admin view of a specific member's clock history, tickets worked, and message thread ### timecore changes -- [ ] `POST /v1/clock/start` — clock in -- [ ] `POST /v1/clock/stop` — clock out -- [ ] `POST /v1/clock/:id/ticket/start` — start ticket timer in clock event -- [ ] `POST /v1/clock/:id/ticket/stop` — stop ticket timer -- [ ] `PUT /v1/clock/:id/times` — admin adjust times -- [ ] `PUT /v1/clock/:id/youtube` — attach YouTube link -- [ ] `GET /v1/clock/timesheet` — query timesheet data +- [x] `POST /v1/clock/start` — clock in +- [x] `POST /v1/clock/stop` — clock out +- [x] `POST /v1/clock/:id/ticket/start` — start ticket timer in clock event +- [x] `POST /v1/clock/:id/ticket/stop` — stop ticket timer +- [x] `PUT /v1/clock/:id/times` — admin adjust times +- [x] `PUT /v1/clock/:id/youtube` — attach YouTube link +- [x] `GET /v1/clock/timesheet` — query timesheet data - [ ] `GET /v1/clock/live?teamIds=` — **SSE** — live clock state for teams --- @@ -172,26 +172,7 @@ requirement — the team dashboard shows live clock state for all members. --- -## Phase 7 — Push Notifications - -**Effort:** 1 day -**Goal:** Move VAPID/FCM handling to timecore. The existing `public/sw.js` is already -Meteor-independent and stays as-is. - -### timehuddle changes -- [ ] Replace `getVapidPublicKey`, `push.subscribe`, `push.unsubscribe` Meteor methods -- [ ] Remove `imports/server/push.ts` -- [ ] Remove `imports/lib/pushNotificationsClient.ts` Meteor dependency - -### timecore changes -- [ ] `GET /v1/push/vapid-key` — return public VAPID key -- [ ] `POST /v1/push/subscribe` — store subscription -- [ ] `DELETE /v1/push/subscribe` — remove subscription -- [ ] Move web-push + FCM sending logic from Meteor into timecore service - ---- - -## Phase 8 — Notifications +## Phase 7 — Notifications **Effort:** 1 day **Goal:** Move the notifications inbox to timecore with SSE for real-time delivery. @@ -209,7 +190,7 @@ Meteor-independent and stays as-is. --- -## Phase 9 — GitHub Integration +## Phase 8 — GitHub Integration **Effort:** 1–2 days **Goal:** Allow users to connect their GitHub account via OAuth, browse repos/issues, and link GitHub issues to tickets — parity with timeharbor-legacy. @@ -229,7 +210,7 @@ Meteor-independent and stays as-is. --- -## Phase 10 — PulseVault Integration +## Phase 9 — PulseVault Integration **Effort:** 1 day **Goal:** Allow users to attach media to tickets via PulseCam app using a QR code/deeplink — parity with timeharbor-legacy. @@ -245,7 +226,7 @@ Meteor-independent and stays as-is. --- -## Phase 11 — Rip Out Meteor +## Phase 10 — Rip Out Meteor **Effort:** 1 day **Goal:** Remove the Meteor build system and all remaining Meteor packages. Replace the dev @@ -272,21 +253,6 @@ server with Vite. The app becomes a plain React SPA. --- -## Post-Migration: Mobile Path - -Once Meteor is removed the codebase is universally portable: - -| Target | Additional work | -|---|---| -| **PWA** | Add `manifest.json`, done — `sw.js` already exists | -| **Capacitor** | `npx cap init`, wrap existing React app, ~1 week | -| **Expo (React Native)** | Shared TanStack Query hooks + API layer, new native UI layer | - -better-auth supports cookie auth (web) and token auth (mobile) natively — no changes needed -to timecore when adding mobile clients. - ---- - ## Future — Needs Issues Filed These features exist in timeharbor-legacy but are not yet covered by any phase above. @@ -295,3 +261,4 @@ File a GitHub issue for each before starting the affected phase. - [ ] **URL title fetch** — when a ticket is created with a reference URL, the server fetches the page title automatically (`extractUrlTitle` method). Needs a timecore endpoint (e.g. `POST /v1/util/extract-url-title`) and timehuddle ticket form integration. *(related: Phase 4)* - [ ] **Ticket time history** — per-ticket time breakdown by configurable date range (today / yesterday / this week / this month / quarter / year / custom). Used in the ticket detail view (`getTicketTimeHistory` method). Needs a timecore endpoint (e.g. `GET /v1/tickets/:id/time-history?range=`) and timehuddle ticket detail UI. *(related: Phase 4)* - [ ] **Auto clock-out background job** — server-side job that force-clocks-out any session running for 8+ consecutive hours (burnout prevention), fires push notifications to user and team admins. In legacy this is a `Meteor.setInterval` running every 60 seconds on the server. Needs a scheduled job in timecore (Node `setInterval` or a cron package) that replicates this logic. *(related: Phase 5)* +- [ ] **File Mobile issues** - see [mobile.md](./mobile.md) \ No newline at end of file From 4a208c9eda1c15741bac00878dd860e5e67d71c1 Mon Sep 17 00:00:00 2001 From: Michael Fisher Date: Tue, 21 Apr 2026 21:43:59 -0400 Subject: [PATCH 09/26] feat(messages): migrate messaging system to Timecore API and implement SSE for real-time updates --- .github/plans/timecore.md | 12 +-- imports/features/messages/MessagesPage.tsx | 108 ++++++++++---------- imports/features/messages/api.ts | 111 +-------------------- imports/lib/api.ts | 39 ++++++++ 4 files changed, 105 insertions(+), 165 deletions(-) diff --git a/.github/plans/timecore.md b/.github/plans/timecore.md index b3d2227c4..2ef6c9098 100644 --- a/.github/plans/timecore.md +++ b/.github/plans/timecore.md @@ -161,14 +161,14 @@ requirement — the team dashboard shows live clock state for all members. **Goal:** Move the admin↔member messaging system to timecore with SSE for real-time delivery. ### timehuddle changes -- [ ] Replace `messages.send` Meteor method with `POST /v1/messages` -- [ ] Replace `messages.thread` publication with **SSE** stream per thread -- [ ] Remove `imports/features/messages/api.ts` server half +- [x] Replace `messages.send` Meteor method with `POST /v1/messages` +- [x] Replace `messages.thread` publication with **SSE** stream per thread +- [x] Remove `imports/features/messages/api.ts` server half ### timecore changes -- [ ] `GET /v1/messages?teamId=&adminId=&memberId=` — fetch thread -- [ ] `POST /v1/messages` — send message -- [ ] `GET /v1/messages/stream?threadId=` — **SSE** — live message delivery +- [x] `GET /v1/messages?teamId=&adminId=&memberId=` — fetch thread +- [x] `POST /v1/messages` — send message +- [x] `GET /v1/messages/stream?threadId=` — **SSE** — live message delivery --- diff --git a/imports/features/messages/MessagesPage.tsx b/imports/features/messages/MessagesPage.tsx index 8c23b79d7..074f90351 100644 --- a/imports/features/messages/MessagesPage.tsx +++ b/imports/features/messages/MessagesPage.tsx @@ -4,7 +4,7 @@ * Features: * • Thread list — admin sees all member threads, member sees admin threads * • Message composition with send - * • Real-time updates via Meteor subscription + * • Real-time updates via SSE stream */ import { faEnvelope, @@ -23,19 +23,18 @@ import { Spinner, Text, } from '@mieweb/ui'; -import { Meteor } from 'meteor/meteor'; -import { useFind, useSubscribe } from 'meteor/react-meteor-data'; import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { MESSAGES_PENDING_THREAD_KEY } from '../../lib/constants'; import { useTeam } from '../../lib/TeamContext'; -import { useMethod } from '../../lib/useMethod'; -import { Messages } from './api'; +import { useSession } from '../../lib/useSession'; +import { messageApi, userApi, type Message } from '../../lib/api'; // ─── MessagesPage ───────────────────────────────────────────────────────────── export const MessagesPage: React.FC = () => { - const userId = Meteor.userId()!; + const { user } = useSession(); + const userId = user?.id ?? ''; const { teams, selectedTeamId, setSelectedTeamId, teamsReady, isAdmin, selectedTeam } = useTeam(); // Thread selection @@ -47,6 +46,10 @@ export const MessagesPage: React.FC = () => { const effectiveAdminId = isAdmin ? userId : selectedAdminId; const effectiveMemberId = isAdmin ? selectedMemberId : userId; + // Messages state + const [messages, setMessages] = useState([]); + const [sendLoading, setSendLoading] = useState(false); + /** From push notification URL: /app/messages?openTeam=&openPeer= */ const pendingOpenPeerRef = useRef(null); useEffect(() => { @@ -58,7 +61,6 @@ export const MessagesPage: React.FC = () => { if (openTeam) setSelectedTeamId(openTeam); if (openPeer) pendingOpenPeerRef.current = openPeer; window.history.replaceState(null, '', '/app/messages'); - }, []); useEffect(() => { @@ -74,8 +76,7 @@ export const MessagesPage: React.FC = () => { // Deep-link from notification inbox (threadId team:admin:member) — one-shot on mount useEffect(() => { - const uid = Meteor.userId(); - if (!uid || typeof window === 'undefined') return; + if (!userId || typeof window === 'undefined') return; let raw: string | null = null; try { raw = sessionStorage.getItem(MESSAGES_PENDING_THREAD_KEY); @@ -89,53 +90,53 @@ export const MessagesPage: React.FC = () => { const { teamId, adminId, memberId } = parsed; if (teamId) setSelectedTeamId(teamId); if (adminId && memberId) { - if (uid === adminId) setSelectedMemberId(memberId); - else if (uid === memberId) setSelectedAdminId(adminId); + if (userId === adminId) setSelectedMemberId(memberId); + else if (userId === memberId) setSelectedAdminId(adminId); } } catch { /* ignore */ } - - }, []); + }, [userId]); - // Subscribe to thread - useSubscribe( - 'messages.thread', - selectedTeamId ?? '', - effectiveAdminId ?? '', - effectiveMemberId ?? '', - ); + // Fetch thread history + open SSE when thread is selected + useEffect(() => { + if (!selectedTeamId || !effectiveAdminId || !effectiveMemberId) { + setMessages([]); + return; + } + const threadId = `${selectedTeamId}:${effectiveAdminId}:${effectiveMemberId}`; - const messages = useFind( - () => { - if (!selectedTeamId || !effectiveAdminId || !effectiveMemberId) { - return Messages.find({ _id: '__none__' }); - } - const threadId = `${selectedTeamId}:${effectiveAdminId}:${effectiveMemberId}`; - return Messages.find({ threadId }, { sort: { createdAt: 1 } }); - }, - [selectedTeamId, effectiveAdminId, effectiveMemberId], - ); + // Initial fetch + messageApi.getThread(selectedTeamId, effectiveAdminId, effectiveMemberId) + .then(setMessages) + .catch(() => {}); - // Fetch team member names - const getUsers = useMethod<[string[]], Array<{ id: string; name: string; email: string }>>('teams.getUsers'); + // SSE for real-time updates + const es = messageApi.openStream(threadId); + es.onmessage = (e) => { + try { + const msg = JSON.parse(e.data) as Message; + setMessages((prev) => { + // Deduplicate by id + if (prev.some((m) => m.id === msg.id)) return prev; + return [...prev, msg]; + }); + } catch { /* ignore */ } + }; + return () => es.close(); + }, [selectedTeamId, effectiveAdminId, effectiveMemberId]); + // Fetch team member names via REST useEffect(() => { if (!selectedTeam) return; const ids = [...new Set([...selectedTeam.members, ...selectedTeam.admins])]; - getUsers.call(ids).then((users) => { + userApi.getUsers(ids).then((users) => { const names: Record = {}; for (const u of users) names[u.id] = u.name; setMemberNames(names); }).catch(() => {}); }, [selectedTeam]); - // Send message - const sendMessage = useMethod< - [{ teamId: string; toUserId: string; text: string; adminId: string }], - string - >('messages.send'); - const [messageText, setMessageText] = useState(''); const messagesEndRef = useRef(null); @@ -147,14 +148,21 @@ export const MessagesPage: React.FC = () => { const handleSend = useCallback(async () => { if (!messageText.trim() || !selectedTeamId || !effectiveAdminId || !effectiveMemberId) return; const toUserId = userId === effectiveAdminId ? effectiveMemberId : effectiveAdminId; - await sendMessage.call({ - teamId: selectedTeamId, - toUserId, - text: messageText.trim(), - adminId: effectiveAdminId, - }); - setMessageText(''); - }, [messageText, selectedTeamId, effectiveAdminId, effectiveMemberId, userId, sendMessage]); + setSendLoading(true); + try { + const sent = await messageApi.send({ + teamId: selectedTeamId, + toUserId, + text: messageText.trim(), + adminId: effectiveAdminId, + }); + // Append immediately (SSE will deduplicate if it also arrives) + setMessages((prev) => prev.some((m) => m.id === sent.id) ? prev : [...prev, sent]); + setMessageText(''); + } finally { + setSendLoading(false); + } + }, [messageText, selectedTeamId, effectiveAdminId, effectiveMemberId, userId]); // Thread participants const threadMembers = useMemo(() => { @@ -267,7 +275,7 @@ export const MessagesPage: React.FC = () => { {messages.map((msg) => { const isMe = msg.fromUserId === userId; return ( -
        +
        { variant="primary" size="icon" onClick={handleSend} - disabled={sendMessage.loading || !messageText.trim()} - isLoading={sendMessage.loading} + disabled={sendLoading || !messageText.trim()} + isLoading={sendLoading} aria-label="Send message" > diff --git a/imports/features/messages/api.ts b/imports/features/messages/api.ts index 7935649cf..1bb6fb7e5 100644 --- a/imports/features/messages/api.ts +++ b/imports/features/messages/api.ts @@ -1,114 +1,7 @@ -import { DDPRateLimiter } from 'meteor/ddp-rate-limiter'; -import { Meteor } from 'meteor/meteor'; import { Mongo } from 'meteor/mongo'; -import { Notifications, Teams } from '../teams/api'; -import { sendMessageSchema, type MessageDoc } from './schema'; +import type { MessageDoc } from './schema'; -// ─── Collections ────────────────────────────────────────────────────────────── +// ─── Collection ─────────────────────────────────────────────────────────────── export const Messages = new Mongo.Collection('messages'); - -// ─── Helpers ────────────────────────────────────────────────────────────────── - -function buildThreadId(teamId: string, adminId: string, memberId: string): string { - return `${teamId}:${adminId}:${memberId}`; -} - -function getUserDisplayName(user: Meteor.User, fallback = 'Unknown'): string { - const p = user.profile as { firstName?: string; lastName?: string } | undefined; - if (p?.firstName || p?.lastName) return [p.firstName, p.lastName].filter(Boolean).join(' '); - return user.emails?.[0]?.address?.split('@')[0] ?? fallback; -} - -// ─── Server ─────────────────────────────────────────────────────────────────── - -if (Meteor.isServer) { - Meteor.startup(async () => { - await Messages.createIndexAsync({ threadId: 1, createdAt: 1 }); - await Messages.createIndexAsync({ teamId: 1 }); - - DDPRateLimiter.addRule( - { name: (n) => n === 'messages.send', userId: () => true }, - 20, - 60_000, - ); - }); - - // ─── Publications ──────────────────────────────────────────────────────────── - - Meteor.publish('messages.thread', function (teamId: string, adminId: string, memberId: string) { - if (!this.userId) return this.ready(); - const threadId = buildThreadId(teamId, adminId, memberId); - // Only allow participants to read - if (this.userId !== adminId && this.userId !== memberId) return this.ready(); - return Messages.find({ threadId }, { sort: { createdAt: 1 } }); - }); - - // ─── Methods ────────────────────────────────────────────────────────────────── - - Meteor.methods({ - async 'messages.send'(fields: { - teamId: string; - toUserId: string; - text: string; - adminId: string; - ticketId?: string; - }) { - if (!this.userId) throw new Meteor.Error('not-authorized'); - const result = sendMessageSchema.safeParse(fields); - if (!result.success) - throw new Meteor.Error('validation', result.error.issues[0]?.message ?? 'Invalid'); - const { teamId, toUserId, text, adminId, ticketId } = result.data; - - const team = await Teams.findOneAsync(teamId); - if (!team) throw new Meteor.Error('not-found', 'Team not found'); - - const isAdmin = team.admins.includes(this.userId); - const isMember = team.members.includes(this.userId); - if (!isAdmin && !isMember) throw new Meteor.Error('not-authorized', 'Not a team member'); - - const memberId = isAdmin ? toUserId : this.userId; - const threadId = buildThreadId(teamId, adminId, memberId); - - // Sender must be one of the thread participants - if (this.userId !== adminId && this.userId !== memberId) - throw new Meteor.Error('not-authorized', 'Invalid thread'); - if (!team.admins.includes(adminId)) - throw new Meteor.Error('not-authorized', 'Admin not in team'); - const allMembers = [...team.members, ...team.admins]; - if (!allMembers.includes(memberId)) - throw new Meteor.Error('not-authorized', 'Member not in team'); - - const fromUser = await Meteor.users.findOneAsync(this.userId); - const senderName = fromUser ? getUserDisplayName(fromUser) : 'Unknown'; - - const doc: Omit = { - threadId, - teamId, - adminId, - memberId, - fromUserId: this.userId, - toUserId, - text, - senderName, - createdAt: new Date(), - }; - if (ticketId) (doc as MessageDoc).ticketId = ticketId; - - const messageId = await Messages.insertAsync(doc as MessageDoc); - - // Create in-app notification for recipient - await Notifications.insertAsync({ - userId: toUserId, - title: 'TimeHuddle', - body: `${senderName}: ${text}`, - data: { type: 'message', teamId, threadId, ticketId: ticketId || null }, - read: false, - createdAt: new Date(), - }); - - return messageId; - }, - }); -} diff --git a/imports/lib/api.ts b/imports/lib/api.ts index 7bc4f2d06..7679abdf1 100644 --- a/imports/lib/api.ts +++ b/imports/lib/api.ts @@ -357,3 +357,42 @@ export const clockApi = { { withCredentials: true }, ), }; + +// ─── Messages ───────────────────────────────────────────────────────────────── + +export interface Message { + id: string; + threadId: string; + teamId: string; + adminId: string; + memberId: string; + fromUserId: string; + toUserId: string; + text: string; + senderName: string; + ticketId?: string; + createdAt: string; // ISO +} + +export const messageApi = { + /** Fetch a thread's message history. */ + getThread: (teamId: string, adminId: string, memberId: string) => + request<{ messages: Message[] }>( + `/v1/messages?teamId=${encodeURIComponent(teamId)}&adminId=${encodeURIComponent(adminId)}&memberId=${encodeURIComponent(memberId)}`, + ).then((r) => r.messages), + + /** Send a message. */ + send: (data: { teamId: string; toUserId: string; text: string; adminId: string; ticketId?: string }) => + request<{ message: Message }>('/v1/messages', { + method: 'POST', + body: JSON.stringify(data), + }).then((r) => r.message), + + /** Open an SSE stream for a thread. Returns an EventSource. */ + openStream: (threadId: string): EventSource => + new EventSource( + `${TIMECORE_BASE_URL}/v1/messages/stream?threadId=${encodeURIComponent(threadId)}`, + { withCredentials: true }, + ), +}; + From bade506e496bf5d34587d55efa1b9315989fe938 Mon Sep 17 00:00:00 2001 From: Michael Fisher Date: Wed, 22 Apr 2026 07:16:30 -0400 Subject: [PATCH 10/26] feat(notifications): migrate notifications to Timecore API with SSE for real-time updates --- .github/plans/timecore.md | 14 +- .../notifications/NotificationsPage.tsx | 160 +++++++++--------- imports/lib/api.ts | 66 ++++++++ 3 files changed, 154 insertions(+), 86 deletions(-) diff --git a/.github/plans/timecore.md b/.github/plans/timecore.md index 2ef6c9098..60edc34f5 100644 --- a/.github/plans/timecore.md +++ b/.github/plans/timecore.md @@ -178,15 +178,15 @@ requirement — the team dashboard shows live clock state for all members. **Goal:** Move the notifications inbox to timecore with SSE for real-time delivery. ### timehuddle changes -- [ ] Replace `notifications.inbox` publication with SSE stream + REST for mark-read/delete -- [ ] Remove notifications server code from `imports/features/notifications/` +- [x] Replace `notifications.inbox` publication with SSE stream + REST for mark-read/delete +- [x] Remove notifications server code from `imports/features/notifications/` ### timecore changes -- [ ] `GET /v1/notifications` — paginated inbox -- [ ] `POST /v1/notifications/read` — mark all read -- [ ] `PATCH /v1/notifications/:id/read` — mark one read -- [ ] `DELETE /v1/notifications/:id` — delete one -- [ ] `GET /v1/notifications/stream` — SSE stream for new notifications +- [x] `GET /v1/notifications` — paginated inbox +- [x] `POST /v1/notifications/read` — mark all read +- [x] `PATCH /v1/notifications/:id/read` — mark one read +- [x] `DELETE /v1/notifications` — bulk delete +- [x] `GET /v1/notifications/stream` — SSE stream for new notifications --- diff --git a/imports/features/notifications/NotificationsPage.tsx b/imports/features/notifications/NotificationsPage.tsx index 5fadfab14..5d3afc59f 100644 --- a/imports/features/notifications/NotificationsPage.tsx +++ b/imports/features/notifications/NotificationsPage.tsx @@ -7,38 +7,12 @@ import { faCheckDouble, faCircleInfo, faTrash, faXmark } from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { Button, Modal, ModalBody, ModalClose, ModalFooter, ModalHeader, ModalTitle, Text } from '@mieweb/ui'; -import { useFind, useSubscribe } from 'meteor/react-meteor-data'; import React, { useCallback, useEffect, useMemo, useState } from 'react'; import { MESSAGES_PENDING_THREAD_KEY } from '../../lib/constants'; -import { useMethod } from '../../lib/useMethod'; +import { notificationApi, type Notification, type TeamInvitePreview } from '../../lib/api'; +import { useSession } from '../../lib/useSession'; import { useRouter } from '../../ui/router'; -import { Notifications } from '../teams/api'; -import type { NotificationDoc } from '../teams/schema'; - -type UserSummary = { - id: string; - name: string; - email: string; -}; - -type TeamInvitePreview = { - notificationId: string; - teamId: string; - teamName: string; - teamDescription: string; - inviter: UserSummary | null; - members: UserSummary[]; - admins: UserSummary[]; - alreadyMember: boolean; -}; - -function idStr(id: unknown): string { - if (id == null) return ''; - if (typeof id === 'string') return id; - const o = id as { _str?: string; toHexString?: () => string }; - return o._str ?? o.toHexString?.() ?? String(id); -} function timeAgo(date: Date | string | undefined): string { if (!date) return ''; @@ -74,7 +48,7 @@ function normalizeAppPath(path: string): string { } function resolveNotificationTarget( - doc: NotificationDoc | undefined, + doc: Notification | undefined, navigate: (path: string) => void, ): void { if (!doc) return; @@ -121,29 +95,43 @@ function resolveNotificationTarget( export const NotificationsPage: React.FC = () => { const { navigate } = useRouter(); - const loading = useSubscribe('notifications.inbox'); - const notifications = useFind( - () => Notifications.find({}, { sort: { createdAt: -1 } }), - [], - ); + const { user } = useSession(); - const [selectMode, setSelectMode] = useState(false); - const [selectedIds, setSelectedIds] = useState([]); + const [notifications, setNotifications] = useState([]); + const [loading, setLoading] = useState(true); + const [markAllLoading, setMarkAllLoading] = useState(false); + const [deleteLoading, setDeleteLoading] = useState(false); + const [respondLoading, setRespondLoading] = useState(false); + + // Fetch inbox + open SSE for real-time delivery + useEffect(() => { + if (!user) return; - const markAsRead = useMethod<[unknown], void>('notifications.markAsRead'); - const markAllAsRead = useMethod<[], void>('notifications.markAllAsRead'); - const deleteNotifications = useMethod<[string[]], { deletedCount: number }>('notifications.delete'); - const getInvitePreview = useMethod<[unknown], TeamInvitePreview>('notifications.getTeamInvitePreview'); - const respondToInvite = useMethod< - [{ notificationId: unknown; action: 'join' | 'ignore' }], - { success: true } - >('notifications.respondToTeamInvite'); + setLoading(true); + notificationApi.getInbox() + .then(setNotifications) + .catch(() => {}) + .finally(() => setLoading(false)); + const es = notificationApi.openStream(); + es.onmessage = (e) => { + try { + const n = JSON.parse(e.data) as Notification; + setNotifications((prev) => + prev.some((x) => x.id === n.id) ? prev : [n, ...prev], + ); + } catch { /* ignore */ } + }; + return () => es.close(); + }, [user]); + + const [selectMode, setSelectMode] = useState(false); + const [selectedIds, setSelectedIds] = useState([]); const [invitePreview, setInvitePreview] = useState(null); const [inviteError, setInviteError] = useState(null); const hasUnread = useMemo(() => notifications.some((n) => !n.read), [notifications]); - const allIds = useMemo(() => notifications.map((n) => idStr(n._id)), [notifications]); + const allIds = useMemo(() => notifications.map((n) => n.id), [notifications]); const allSelected = allIds.length > 0 && selectedIds.length === allIds.length; const toggleSelect = useCallback((id: string) => { @@ -156,43 +144,54 @@ export const NotificationsPage: React.FC = () => { }, []); const handleRowClick = useCallback( - async (doc: NotificationDoc) => { - const nid = idStr(doc._id); + async (doc: Notification) => { if (selectMode) { - toggleSelect(nid); + toggleSelect(doc.id); return; } try { const data = (doc.data ?? {}) as Record; if (data.type === 'team-invite') { - await markAsRead.call(doc._id ?? nid); - const preview = await getInvitePreview.call(doc._id ?? nid); + await notificationApi.markOneRead(doc.id); + setNotifications((prev) => + prev.map((n) => (n.id === doc.id ? { ...n, read: true } : n)), + ); + const preview = await notificationApi.getInvitePreview(doc.id); setInvitePreview(preview); setInviteError(null); return; } - await markAsRead.call(doc._id ?? nid); + await notificationApi.markOneRead(doc.id); + setNotifications((prev) => + prev.map((n) => (n.id === doc.id ? { ...n, read: true } : n)), + ); resolveNotificationTarget(doc, navigate); - } catch { - /* useMethod surfaces error */ - } + } catch { /* ignore */ } }, - [selectMode, toggleSelect, markAsRead, getInvitePreview, navigate], + [selectMode, toggleSelect, navigate], ); - const handleMarkAllRead = useCallback(() => { - markAllAsRead.call().catch(() => {}); - }, [markAllAsRead]); + const handleMarkAllRead = useCallback(async () => { + setMarkAllLoading(true); + try { + await notificationApi.markAllRead(); + setNotifications((prev) => prev.map((n) => ({ ...n, read: true }))); + } catch { /* ignore */ } finally { + setMarkAllLoading(false); + } + }, []); - const handleDeleteSelected = useCallback(() => { + const handleDeleteSelected = useCallback(async () => { if (selectedIds.length === 0) return; - deleteNotifications - .call(selectedIds) - .then(() => { - setSelectedIds([]); - }) - .catch(() => {}); - }, [selectedIds, deleteNotifications]); + setDeleteLoading(true); + try { + await notificationApi.deleteMany(selectedIds); + setNotifications((prev) => prev.filter((n) => !selectedIds.includes(n.id))); + setSelectedIds([]); + } catch { /* ignore */ } finally { + setDeleteLoading(false); + } + }, [selectedIds]); useEffect(() => { if (selectMode && notifications.length === 0) exitSelectMode(); @@ -205,16 +204,20 @@ export const NotificationsPage: React.FC = () => { const handleInviteAction = useCallback(async (action: 'join' | 'ignore') => { if (!invitePreview) return; + setRespondLoading(true); try { - await respondToInvite.call({ notificationId: invitePreview.notificationId, action }); + await notificationApi.respondToInvite(invitePreview.notificationId, action); + setNotifications((prev) => prev.filter((n) => n.id !== invitePreview.notificationId)); closeInviteModal(); if (action === 'join') navigate('/app/teams'); } catch (e: any) { - setInviteError(e?.reason || 'Failed to process invite'); + setInviteError(e?.message || 'Failed to process invite'); + } finally { + setRespondLoading(false); } - }, [invitePreview, respondToInvite, closeInviteModal, navigate]); + }, [invitePreview, closeInviteModal, navigate]); - if (loading()) { + if (loading) { return (
        @@ -250,7 +253,7 @@ export const NotificationsPage: React.FC = () => { variant="danger" size="sm" onClick={handleDeleteSelected} - isLoading={deleteNotifications.loading} + isLoading={deleteLoading} aria-label="Delete selected notifications" > @@ -263,7 +266,7 @@ export const NotificationsPage: React.FC = () => { <>
        {hasUnread && ( - @@ -280,10 +283,9 @@ export const NotificationsPage: React.FC = () => { {notifications.length > 0 ? (
          {notifications.map((n) => { - const nid = idStr(n._id); - const selected = selectedIds.includes(nid); + const selected = selectedIds.includes(n.id); return ( -
        • +
        • { ? 'border-blue-500 bg-blue-500 text-white' : 'border-neutral-400 bg-white dark:border-neutral-500 dark:bg-neutral-800', ].join(' ')} - data-notification-id={nid} + data-notification-id={n.id} aria-label={selected ? 'Deselect' : 'Select'} onClick={(e) => { e.stopPropagation(); - toggleSelect(nid); + toggleSelect(n.id); }} > {selected && ✓} @@ -400,13 +402,13 @@ export const NotificationsPage: React.FC = () => { )} - - Tap to clock out + + Tap to clock out + ) : ( <> @@ -225,7 +238,9 @@ export const ClockPage: React.FC = () => { > - Tap to clock in + + Tap to clock in + )} @@ -267,7 +282,10 @@ export const ClockPage: React.FC = () => {
          - + {formatDuration(elapsed)}
        • @@ -327,7 +351,9 @@ export const ClockPage: React.FC = () => { {/* Add existing ticket */} {availableTickets.length > 0 && (
          - Add existing ticket: + + Add existing ticket: +
          {availableTickets.slice(0, 5).map((t) => ( + diff --git a/imports/features/clock/TimesheetPage.tsx b/imports/features/clock/TimesheetPage.tsx index 74907e890..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, @@ -36,7 +34,6 @@ import { formatDuration, formatTime, formatDate, toDateString } from '../../lib/ import { clockApi, type ClockEvent } from '../../lib/api'; import { useSession } from '../../lib/useSession'; - interface TimesheetData { sessions: ClockEvent[]; summary: { @@ -190,22 +187,46 @@ 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} + + +
          )} @@ -251,23 +272,27 @@ export const TimesheetPage: React.FC = () => { 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 - )} - - + + {formatDate(startTime, true)} + {formatTime(startTime)} + {endTime ? formatTime(endTime) : '—'} + + {duration ? formatDuration(duration) : '—'} + + {teamName} + + {isActive ? ( + + + Active + + ) : ( + + Completed + + )} + + ); })} @@ -279,8 +304,13 @@ export const TimesheetPage: React.FC = () => { {data && data.sessions.length === 0 && !loading && ( - - No clock events in this date range. + + + No clock events in this date range. + )} diff --git a/imports/features/dashboard/DashboardPage.tsx b/imports/features/dashboard/DashboardPage.tsx index 13b89b669..f2d4e7c79 100644 --- a/imports/features/dashboard/DashboardPage.tsx +++ b/imports/features/dashboard/DashboardPage.tsx @@ -57,20 +57,17 @@ function computeHours(events: ClockEvent[], after: number, now: number): number export const DashboardPage: React.FC = () => { const { user } = useSession(); const { navigate } = useRouter(); - const { - teams, - teamsReady, - selectedTeamId, - setSelectedTeamId, - activeClockEvent, - currentTime, - } = useTeam(); + const { teams, teamsReady, selectedTeamId, setSelectedTeamId, activeClockEvent, currentTime } = + useTeam(); // All user clock events (from timecore REST) const [allEvents, setAllEvents] = useState([]); useEffect(() => { if (!user) return; - clockApi.getEvents().then(setAllEvents).catch(() => setAllEvents([])); + clockApi + .getEvents() + .then(setAllEvents) + .catch(() => setAllEvents([])); }, [user]); // Compute stats @@ -92,15 +89,9 @@ export const DashboardPage: React.FC = () => { [allEvents, weekStart, currentTime], ); - const activeSessions = useMemo( - () => allEvents.filter((e) => !e.endTime).length, - [allEvents], - ); + const activeSessions = useMemo(() => allEvents.filter((e) => !e.endTime).length, [allEvents]); - const recentEvents = useMemo( - () => allEvents.filter((e) => e.endTime).slice(0, 5), - [allEvents], - ); + const recentEvents = useMemo(() => allEvents.filter((e) => e.endTime).slice(0, 5), [allEvents]); const isFirstTime = teams.length <= 1 && allEvents.length === 0; @@ -139,7 +130,9 @@ export const DashboardPage: React.FC = () => { {isFirstTime && ( - Welcome to TimeHuddle + + Welcome to TimeHuddle + Get started by creating or joining a team, then clock in to start tracking time. @@ -178,8 +171,12 @@ export const DashboardPage: React.FC = () => {
          - Today - {formatDuration(todayHours)} + + Today + + + {formatDuration(todayHours)} +
          @@ -189,19 +186,29 @@ export const DashboardPage: React.FC = () => {
          - This Week - {formatDuration(weekHours)} + + This Week + + + {formatDuration(weekHours)} +
          -
          0 ? 'bg-green-50 text-green-600 dark:bg-green-950/50 dark:text-green-400' : 'bg-neutral-100 text-neutral-500 dark:bg-neutral-800 dark:text-neutral-400'}`}> +
          0 ? 'bg-green-50 text-green-600 dark:bg-green-950/50 dark:text-green-400' : 'bg-neutral-100 text-neutral-500 dark:bg-neutral-800 dark:text-neutral-400'}`} + >
          - Active - {String(activeSessions)} + + Active + + + {String(activeSessions)} +
          @@ -211,8 +218,12 @@ export const DashboardPage: React.FC = () => {
          - Teams - {String(teams.filter((t) => !t.isPersonal).length)} + + Teams + + + {String(teams.filter((t) => !t.isPersonal).length)} +
          @@ -220,7 +231,10 @@ export const DashboardPage: React.FC = () => { {/* Active session banner */} {activeClockEvent && ( - }> + } + > Session Active Started {formatTime(new Date(activeClockEvent.startTimestamp))} •{' '} @@ -262,11 +276,13 @@ export const DashboardPage: React.FC = () => { {end ? ` – ${formatTime(end)}` : ''} - {team?.isPersonal ? 'Personal' : team?.name ?? 'Unknown'} + {team?.isPersonal ? 'Personal' : (team?.name ?? 'Unknown')} {event.tickets.length > 0 && ` • ${event.tickets.length} ticket(s)`}
        - {formatDuration(durSec)} + + {formatDuration(durSec)} + ); })} diff --git a/imports/features/inbox/InboxPage.tsx b/imports/features/inbox/InboxPage.tsx index a4db11eec..b9ae3cded 100644 --- a/imports/features/inbox/InboxPage.tsx +++ b/imports/features/inbox/InboxPage.tsx @@ -177,11 +177,7 @@ export const InboxPage: React.FC = ({ initialEmail }) => { onChange={(e) => setInputValue(e.target.value)} placeholder="Enter email to check inbox…" /> - diff --git a/imports/features/messages/MessagesPage.tsx b/imports/features/messages/MessagesPage.tsx index 074f90351..7edd06454 100644 --- a/imports/features/messages/MessagesPage.tsx +++ b/imports/features/messages/MessagesPage.tsx @@ -6,10 +6,7 @@ * • Message composition with send * • Real-time updates via SSE stream */ -import { - faEnvelope, - faPaperPlane, -} from '@fortawesome/free-solid-svg-icons'; +import { faEnvelope, faPaperPlane } from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { Avatar, @@ -107,7 +104,8 @@ export const MessagesPage: React.FC = () => { const threadId = `${selectedTeamId}:${effectiveAdminId}:${effectiveMemberId}`; // Initial fetch - messageApi.getThread(selectedTeamId, effectiveAdminId, effectiveMemberId) + messageApi + .getThread(selectedTeamId, effectiveAdminId, effectiveMemberId) .then(setMessages) .catch(() => {}); @@ -121,7 +119,9 @@ export const MessagesPage: React.FC = () => { if (prev.some((m) => m.id === msg.id)) return prev; return [...prev, msg]; }); - } catch { /* ignore */ } + } catch { + /* ignore */ + } }; return () => es.close(); }, [selectedTeamId, effectiveAdminId, effectiveMemberId]); @@ -130,11 +130,14 @@ export const MessagesPage: React.FC = () => { useEffect(() => { if (!selectedTeam) return; const ids = [...new Set([...selectedTeam.members, ...selectedTeam.admins])]; - userApi.getUsers(ids).then((users) => { - const names: Record = {}; - for (const u of users) names[u.id] = u.name; - setMemberNames(names); - }).catch(() => {}); + userApi + .getUsers(ids) + .then((users) => { + const names: Record = {}; + for (const u of users) names[u.id] = u.name; + setMemberNames(names); + }) + .catch(() => {}); }, [selectedTeam]); const [messageText, setMessageText] = useState(''); @@ -157,7 +160,7 @@ export const MessagesPage: React.FC = () => { adminId: effectiveAdminId, }); // Append immediately (SSE will deduplicate if it also arrives) - setMessages((prev) => prev.some((m) => m.id === sent.id) ? prev : [...prev, sent]); + setMessages((prev) => (prev.some((m) => m.id === sent.id) ? prev : [...prev, sent])); setMessageText(''); } finally { setSendLoading(false); @@ -181,10 +184,7 @@ export const MessagesPage: React.FC = () => { const hasThread = isAdmin ? !!selectedMemberId : !!selectedAdminId; const teamOptions = useMemo( - () => - teams - .filter((t) => !t.isPersonal) - .map((t) => ({ value: t.id, label: t.name })), + () => teams.filter((t) => !t.isPersonal).map((t) => ({ value: t.id, label: t.name })), [teams], ); @@ -207,7 +207,11 @@ export const MessagesPage: React.FC = () => { size="sm" options={teamOptions} value={selectedTeamId ?? ''} - onValueChange={(v) => { setSelectedTeamId(v); setSelectedMemberId(null); setSelectedAdminId(null); }} + onValueChange={(v) => { + setSelectedTeamId(v); + setSelectedMemberId(null); + setSelectedAdminId(null); + }} />
        )} @@ -216,7 +220,11 @@ export const MessagesPage: React.FC = () => { {/* Thread list */} - + {isAdmin ? 'Members' : 'Admins'} @@ -228,7 +236,9 @@ export const MessagesPage: React.FC = () => {
      • @@ -266,12 +286,24 @@ export const NotificationsPage: React.FC = () => { <>
        {hasUnread && ( - )} -
        @@ -327,7 +359,9 @@ export const NotificationsPage: React.FC = () => {

        {n.title}

        -

        {n.body}

        +

        + {n.body} +

      • @@ -366,17 +400,25 @@ export const NotificationsPage: React.FC = () => { {invitePreview && (
        - Team name - {invitePreview.teamName} + + Team name + + + {invitePreview.teamName} +
        - Team description + + Team description + {invitePreview.teamDescription || 'No team description provided.'}
        - Invited by + + Invited by + {invitePreview.inviter ? `${invitePreview.inviter.name}${invitePreview.inviter.email ? ` (${invitePreview.inviter.email})` : ''}` @@ -384,25 +426,35 @@ export const NotificationsPage: React.FC = () => {
        - Admins ({invitePreview.admins.length}) + + Admins ({invitePreview.admins.length}) + {invitePreview.admins.map((a) => a.name).join(', ') || 'None'}
        - Team members ({invitePreview.members.length}) + + Team members ({invitePreview.members.length}) + {invitePreview.members.map((m) => m.name).join(', ') || 'None'}
        {inviteError && ( - {inviteError} + + {inviteError} + )}
        )} - -
        diff --git a/imports/features/profile/UsernameBadge.tsx b/imports/features/profile/UsernameBadge.tsx index 27fb9df7d..cdaf48864 100644 --- a/imports/features/profile/UsernameBadge.tsx +++ b/imports/features/profile/UsernameBadge.tsx @@ -24,8 +24,12 @@ export const UsernameBadge: React.FC = ({ userId, username } useEffect(() => { userApi .getUser(userId) - .then((p) => { if (p.name) setDisplayName(p.name); }) - .catch(() => { /* keep fallback */ }); + .then((p) => { + if (p.name) setDisplayName(p.name); + }) + .catch(() => { + /* keep fallback */ + }); }, [userId]); return ( diff --git a/imports/features/profile/api.ts b/imports/features/profile/api.ts index 7ec567ec2..be3014010 100644 --- a/imports/features/profile/api.ts +++ b/imports/features/profile/api.ts @@ -4,4 +4,3 @@ */ export type { ProfileUpdateInput, UserProfileDoc } from './schema'; - diff --git a/imports/features/teams/TeamChart.tsx b/imports/features/teams/TeamChart.tsx index 091466db3..d7008e6c7 100644 --- a/imports/features/teams/TeamChart.tsx +++ b/imports/features/teams/TeamChart.tsx @@ -62,9 +62,7 @@ function buildYaml(teamName: string, members: Member[]): string { const TeamChartMount: React.FC<{ yaml: string }> = ({ yaml }) => { const containerRef = useRef(null); const instanceRef = useRef(null); - const chartId = useRef( - `tc-${Date.now()}-${Math.random().toString(36).slice(2)}` - ).current; + const chartId = useRef(`tc-${Date.now()}-${Math.random().toString(36).slice(2)}`).current; useEffect(() => { const el = containerRef.current!; @@ -122,20 +120,17 @@ const TeamChartMount: React.FC<{ yaml: string }> = ({ yaml }) => { }; export const TeamChart: React.FC = ({ teamName, members }) => { - const memberKey = members.map((m) => `${m.id}:${m.name}:${m.email ?? ''}:${m.isAdmin ? '1' : '0'}`).join(','); + const memberKey = members + .map((m) => `${m.id}:${m.name}:${m.email ?? ''}:${m.isAdmin ? '1' : '0'}`) + .join(','); const yaml = useMemo(() => buildYaml(teamName, members), [teamName, memberKey]); if (members.length === 0) { - return ( -

        No members to display.

        - ); + return

        No members to display.

        ; } return ( -
        +
        ); diff --git a/imports/features/teams/TeamsPage.tsx b/imports/features/teams/TeamsPage.tsx index 7bc49f22d..0a6226d47 100644 --- a/imports/features/teams/TeamsPage.tsx +++ b/imports/features/teams/TeamsPage.tsx @@ -49,9 +49,7 @@ import React, { useCallback, useEffect, useMemo, useState } from 'react'; import { teamApi, type TeamMember } from '../../lib/api'; import { useTeam } from '../../lib/TeamContext'; import { useSession } from '../../lib/useSession'; -const TeamChart = React.lazy(() => - import('./TeamChart').then((m) => ({ default: m.TeamChart })) -); +const TeamChart = React.lazy(() => import('./TeamChart').then((m) => ({ default: m.TeamChart }))); // ─── TeamsPage ──────────────────────────────────────────────────────────────── @@ -63,7 +61,10 @@ export const TeamsPage: React.FC = () => { // Fetch members for selected team const [members, setMembers] = useState([]); const fetchMembers = useCallback(async (teamId: string | null) => { - if (!teamId) { setMembers([]); return; } + if (!teamId) { + setMembers([]); + return; + } try { const data = await teamApi.getMembers(teamId); setMembers(data); @@ -120,10 +121,7 @@ export const TeamsPage: React.FC = () => { [teams], ); - const membersById = useMemo( - () => new Map(members.map((m) => [m.id, m])), - [members], - ); + const membersById = useMemo(() => new Map(members.map((m) => [m.id, m])), [members]); // ── Handlers ── @@ -204,33 +202,39 @@ export const TeamsPage: React.FC = () => { } }, [formValue, selectedTeamId, fetchMembers]); - const handleSetPassword = useCallback(async (memberId: string) => { - if (!formValue.trim() || !selectedTeamId) return; - setPasswordLoading(true); - try { - await teamApi.setMemberPassword(selectedTeamId, memberId, formValue.trim()); - closeModal(); - } catch (e: any) { - setFormError(e.message || 'Failed to set password'); - } finally { - setPasswordLoading(false); - } - }, [formValue, selectedTeamId]); + const handleSetPassword = useCallback( + async (memberId: string) => { + if (!formValue.trim() || !selectedTeamId) return; + setPasswordLoading(true); + try { + await teamApi.setMemberPassword(selectedTeamId, memberId, formValue.trim()); + closeModal(); + } catch (e: any) { + setFormError(e.message || 'Failed to set password'); + } finally { + setPasswordLoading(false); + } + }, + [formValue, selectedTeamId], + ); - const handleRemoveMember = useCallback(async (memberId: string) => { - if (!selectedTeamId) return; - setRemoveLoading(true); - try { - await teamApi.removeMember(selectedTeamId, memberId); - closeModal(); - refetchTeams(); - await fetchMembers(selectedTeamId); - } catch (e: any) { - setFormError(e.message || 'Failed to remove member'); - } finally { - setRemoveLoading(false); - } - }, [selectedTeamId, refetchTeams, fetchMembers]); + const handleRemoveMember = useCallback( + async (memberId: string) => { + if (!selectedTeamId) return; + setRemoveLoading(true); + try { + await teamApi.removeMember(selectedTeamId, memberId); + closeModal(); + refetchTeams(); + await fetchMembers(selectedTeamId); + } catch (e: any) { + setFormError(e.message || 'Failed to remove member'); + } finally { + setRemoveLoading(false); + } + }, + [selectedTeamId, refetchTeams, fetchMembers], + ); const copyCode = useCallback(() => { if (selectedTeam?.code) { @@ -295,7 +299,9 @@ export const TeamsPage: React.FC = () => { )} {!selectedTeam.isPersonal && (
        - {selectedTeam.code} + + {selectedTeam.code} +
        + } + > { @@ -524,12 +568,7 @@ export const TeamsPage: React.FC = () => { /> - @@ -544,15 +583,17 @@ export const TeamsPage: React.FC = () => { Are you sure? This action cannot be undone. All team data will be permanently deleted. - {formError && {formError}} + {formError && ( + + {formError} + + )} - - + @@ -577,12 +618,7 @@ export const TeamsPage: React.FC = () => { /> - @@ -646,10 +682,16 @@ export const TeamsPage: React.FC = () => { Remove this member from the team? They can rejoin using the team code. - {formError && {formError}} + {formError && ( + + {formError} + + )} - +
        - +
        diff --git a/imports/features/tickets/TicketsPage.tsx b/imports/features/tickets/TicketsPage.tsx index d66b66b01..a948c0350 100644 --- a/imports/features/tickets/TicketsPage.tsx +++ b/imports/features/tickets/TicketsPage.tsx @@ -93,8 +93,14 @@ export const TicketsPage: React.FC = () => { }, [tickets, searchQuery]); // My tickets vs others - const myTickets = useMemo(() => filteredTickets.filter((t) => t.createdBy === userId), [filteredTickets, userId]); - const otherTickets = useMemo(() => filteredTickets.filter((t) => t.createdBy !== userId), [filteredTickets, userId]); + const myTickets = useMemo( + () => filteredTickets.filter((t) => t.createdBy === userId), + [filteredTickets, userId], + ); + const otherTickets = useMemo( + () => filteredTickets.filter((t) => t.createdBy !== userId), + [filteredTickets, userId], + ); // ── Handlers ── @@ -208,13 +214,19 @@ export const TicketsPage: React.FC = () => { size="sm" />
        - - + +
        ) : ( <> - {ticket.title} + + {ticket.title} +
        {ticket.github && ( { )} {ticket.status && ticket.status !== 'open' && ( - + {ticket.status} )} @@ -248,12 +257,7 @@ export const TicketsPage: React.FC = () => { {/* Actions */} {canManage && !isEditing && (
        -
        @@ -404,7 +422,9 @@ export const TicketsPage: React.FC = () => { - {searchQuery ? 'No tickets match your search.' : 'No tickets yet. Create one to get started!'} + {searchQuery + ? 'No tickets match your search.' + : 'No tickets yet. Create one to get started!'} @@ -422,12 +442,10 @@ export const TicketsPage: React.FC = () => { - - + diff --git a/imports/features/tickets/api.ts b/imports/features/tickets/api.ts index 6f849cbe9..86b8f048b 100644 --- a/imports/features/tickets/api.ts +++ b/imports/features/tickets/api.ts @@ -7,4 +7,3 @@ export type { BatchUpdateStatusInput, AssignTicketInput, } from './schema'; - diff --git a/imports/lib/api.ts b/imports/lib/api.ts index 9bf0bf2c6..7ce0d0a77 100644 --- a/imports/lib/api.ts +++ b/imports/lib/api.ts @@ -8,7 +8,8 @@ // ─── Config ─────────────────────────────────────────────────────────────────── export const TIMECORE_BASE_URL: string = - (typeof import.meta !== 'undefined' && (import.meta as { env?: Record }).env?.VITE_TIMECORE_URL) || + (typeof import.meta !== 'undefined' && + (import.meta as { env?: Record }).env?.VITE_TIMECORE_URL) || 'http://localhost:4000'; // ─── Types ──────────────────────────────────────────────────────────────────── @@ -44,11 +45,11 @@ async function request(path: string, options: RequestInit = {}): Pr }); if (!res.ok) { - const body = await res.json().catch(() => ({})) as Record; + const body = (await res.json().catch(() => ({}))) as Record; throw new Error( (body.message as string | undefined) ?? - (body.error as string | undefined) ?? - `HTTP ${res.status}`, + (body.error as string | undefined) ?? + `HTTP ${res.status}`, ); } @@ -73,8 +74,7 @@ export const authApi = { }), /** Sign out — clears better-auth session cookie. */ - signOut: () => - request('/api/auth/sign-out', { method: 'POST' }), + signOut: () => request('/api/auth/sign-out', { method: 'POST' }), /** * Request a password-reset email. @@ -156,13 +156,21 @@ export const ticketApi = { (r) => r.tickets, ), - createTicket: (data: { teamId: string; title: string; github?: string; accumulatedTime?: number }) => + createTicket: (data: { + teamId: string; + title: string; + github?: string; + accumulatedTime?: number; + }) => request<{ ticket: Ticket }>('/v1/tickets', { method: 'POST', body: JSON.stringify(data), }).then((r) => r.ticket), - updateTicket: (id: string, updates: { title?: string; github?: string; accumulatedTime?: number; status?: string }) => + updateTicket: ( + id: string, + updates: { title?: string; github?: string; accumulatedTime?: number; status?: string }, + ) => request<{ ticket: Ticket }>(`/v1/tickets/${encodeURIComponent(id)}`, { method: 'PUT', body: JSON.stringify(updates), @@ -217,8 +225,7 @@ export interface TeamMember { } export const teamApi = { - getTeams: () => - request<{ teams: Team[] }>('/v1/teams').then((r) => r.teams), + getTeams: () => request<{ teams: Team[] }>('/v1/teams').then((r) => r.teams), ensurePersonal: () => request<{ team: Team }>('/v1/teams/ensure-personal', { method: 'POST' }).then((r) => r.team), @@ -329,12 +336,10 @@ export const clockApi = { }).then((r) => r.event), /** Get the current user's active clock event (any team), or null. */ - getActive: () => - request<{ event: ClockEvent | null }>('/v1/clock/active').then((r) => r.event), + getActive: () => request<{ event: ClockEvent | null }>('/v1/clock/active').then((r) => r.event), /** Get all clock events for the current user. */ - getEvents: () => - request<{ events: ClockEvent[] }>('/v1/clock/events').then((r) => r.events), + getEvents: () => request<{ events: ClockEvent[] }>('/v1/clock/events').then((r) => r.events), /** Get timesheet data for a user over a date range. */ getTimesheet: (userId: string, startDate: string, endDate: string) => @@ -347,7 +352,9 @@ export const clockApi = { averageSessionSeconds: number; workingDays: number; }; - }>(`/v1/clock/timesheet?userId=${encodeURIComponent(userId)}&startDate=${startDate}&endDate=${endDate}`), + }>( + `/v1/clock/timesheet?userId=${encodeURIComponent(userId)}&startDate=${startDate}&endDate=${endDate}`, + ), /** Open an SSE connection for live team clock state. Returns an EventSource. */ openLiveStream: (teamIds: string[]): EventSource => @@ -381,7 +388,13 @@ export const messageApi = { ).then((r) => r.messages), /** Send a message. */ - send: (data: { teamId: string; toUserId: string; text: string; adminId: string; ticketId?: string }) => + send: (data: { + teamId: string; + toUserId: string; + text: string; + adminId: string; + ticketId?: string; + }) => request<{ message: Message }>('/v1/messages', { method: 'POST', body: JSON.stringify(data), @@ -421,9 +434,7 @@ export type TeamInvitePreview = { export const notificationApi = { /** Fetch the user's notification inbox. */ getInbox: () => - request<{ notifications: Notification[] }>('/v1/notifications').then( - (r) => r.notifications, - ), + request<{ notifications: Notification[] }>('/v1/notifications').then((r) => r.notifications), /** Mark a single notification as read. */ markOneRead: (id: string) => @@ -432,8 +443,7 @@ export const notificationApi = { }), /** Mark all notifications as read. */ - markAllRead: () => - request<{ ok: boolean }>('/v1/notifications/read', { method: 'POST' }), + markAllRead: () => request<{ ok: boolean }>('/v1/notifications/read', { method: 'POST' }), /** Bulk-delete notifications by ID. */ deleteMany: (ids: string[]) => @@ -444,16 +454,14 @@ export const notificationApi = { /** Fetch team-invite preview for a notification. */ getInvitePreview: (id: string) => - request( - `/v1/notifications/${encodeURIComponent(id)}/invite-preview`, - ), + request(`/v1/notifications/${encodeURIComponent(id)}/invite-preview`), /** Accept or ignore a team invite. */ respondToInvite: (id: string, action: 'join' | 'ignore') => - request<{ ok: boolean }>( - `/v1/notifications/${encodeURIComponent(id)}/invite-respond`, - { method: 'POST', body: JSON.stringify({ action }) }, - ), + request<{ ok: boolean }>(`/v1/notifications/${encodeURIComponent(id)}/invite-respond`, { + method: 'POST', + body: JSON.stringify({ action }), + }), /** Open an SSE stream for new notifications. */ openStream: (): EventSource => diff --git a/imports/lib/constants.ts b/imports/lib/constants.ts index 8e6c6a79d..41f61ef56 100644 --- a/imports/lib/constants.ts +++ b/imports/lib/constants.ts @@ -27,5 +27,4 @@ export const MESSAGES_PENDING_THREAD_KEY = 'app:messagesPendingThread' as const; // ─── Misc ───────────────────────────────────────────────────────────────────── -export const REPO_URL = - 'https://github.com/mieweb/timehuddle' as const; +export const REPO_URL = 'https://github.com/mieweb/timehuddle' as const; diff --git a/imports/lib/useSession.tsx b/imports/lib/useSession.tsx index ef1d0f0f9..beffd4cb3 100644 --- a/imports/lib/useSession.tsx +++ b/imports/lib/useSession.tsx @@ -5,13 +5,7 @@ * wrap root with * read auth state anywhere with useSession() */ -import React, { - createContext, - useCallback, - useContext, - useEffect, - useState, -} from 'react'; +import React, { createContext, useCallback, useContext, useEffect, useState } from 'react'; import { authApi, type TimecoreUser } from './api'; diff --git a/imports/ui/LoginForm.tsx b/imports/ui/LoginForm.tsx index b6e25b0e8..8341f8d3c 100644 --- a/imports/ui/LoginForm.tsx +++ b/imports/ui/LoginForm.tsx @@ -57,7 +57,7 @@ export const LoginForm: React.FC = ({ initialMode }) => { const resetToken = typeof window !== 'undefined' - ? new URLSearchParams(window.location.search).get('token') ?? undefined + ? (new URLSearchParams(window.location.search).get('token') ?? undefined) : undefined; const [mode, setMode] = useState(initialMode ?? getMode(!!resetToken)); @@ -187,7 +187,7 @@ export const LoginForm: React.FC = ({ initialMode }) => { {isSignup ? 'Create your account and start tracking time with your team — real-time collaboration built in.' : isForgot || isResetConfirm - ? 'Enter your email address and we\'ll send you a link to reset your password.' + ? "Enter your email address and we'll send you a link to reset your password." : 'Sign in to pick up where you left off. Your data syncs in real-time.'}

        @@ -254,7 +254,7 @@ export const LoginForm: React.FC = ({ initialMode }) => { {isSignup ? 'Enter your details to get started' : isForgot - ? 'Enter your email and we\'ll send a reset link' + ? "Enter your email and we'll send a reset link" : isResetConfirm ? 'Enter and confirm your new password' : 'Enter your email and password'} diff --git a/imports/ui/SettingsPage.tsx b/imports/ui/SettingsPage.tsx index 389b2c826..3196126b1 100644 --- a/imports/ui/SettingsPage.tsx +++ b/imports/ui/SettingsPage.tsx @@ -57,7 +57,9 @@ const Section: React.FC<{
        {title} {description && ( - {description} + + {description} + )}
        @@ -74,8 +76,14 @@ const Row: React.FC<{ label: string; hint?: string; children: React.ReactNode }> }) => (
        - {label} - {hint && {hint}} + + {label} + + {hint && ( + + {hint} + + )}
        {children}
        @@ -165,8 +173,10 @@ const PushNotificationsSettings: React.FC = () => { try { await subscribeToWebPush(); await refreshStatus(); - - window.alert('Notifications enabled! You will receive alerts when team members clock in or out.'); + + window.alert( + 'Notifications enabled! You will receive alerts when team members clock in or out.', + ); } catch (error: unknown) { const msg = error instanceof Error ? error.message : String(error); let detail = 'Failed to enable notifications. '; @@ -177,7 +187,7 @@ const PushNotificationsSettings: React.FC = () => { } else { detail += msg; } - + window.alert(detail); } finally { setLoading(false); @@ -185,16 +195,14 @@ const PushNotificationsSettings: React.FC = () => { }; const handleDisable = async () => { - if (!window.confirm('Are you sure you want to disable push notifications?')) return; setLoading(true); try { await unsubscribeFromWebPush(); await refreshStatus(); - + window.alert('Notifications disabled.'); } catch { - window.alert('Failed to disable notifications. Please try again.'); } finally { setLoading(false); @@ -205,8 +213,9 @@ const PushNotificationsSettings: React.FC = () => {
        {serverHasVapid === false && (
        - Web Push is not configured on this server. Add VAPID keys to settings.json{' '} - (see settings.push.example.json). + Web Push is not configured on this server. Add VAPID keys to{' '} + settings.json (see{' '} + settings.push.example.json).
        )} {!supported ? ( @@ -218,7 +227,13 @@ const PushNotificationsSettings: React.FC = () => {
        Notifications are enabled. You will receive alerts when team members clock in or out.
        - @@ -289,11 +304,7 @@ export const SettingsPage: React.FC = () => { return (
        {/* Profile */} -
        +
        { > Save Profile - {saved && Saved!} - {profileError && {profileError}} + {saved && ( + + Saved! + + )} + {profileError && ( + + {profileError} + + )}
        @@ -381,7 +400,6 @@ export const SettingsPage: React.FC = () => { {version} ))} -
        ); diff --git a/imports/ui/Sidebar.tsx b/imports/ui/Sidebar.tsx index 5ae1d48b4..1c9fdd9df 100644 --- a/imports/ui/Sidebar.tsx +++ b/imports/ui/Sidebar.tsx @@ -144,10 +144,7 @@ const SidebarContent: React.FC = () => { ].join(' ')} > {' '} - + {/* Icon mark */}
        TH diff --git a/imports/ui/ThemeToggle.tsx b/imports/ui/ThemeToggle.tsx index 95c12b90e..7bc2273b5 100644 --- a/imports/ui/ThemeToggle.tsx +++ b/imports/ui/ThemeToggle.tsx @@ -11,12 +11,7 @@ export const ThemeToggle: React.FC = () => { const label = theme === 'dark' ? 'Switch to light mode' : 'Switch to dark mode'; return ( - diff --git a/imports/ui/UserDropdown.tsx b/imports/ui/UserDropdown.tsx index 27610b0e3..90316ec98 100644 --- a/imports/ui/UserDropdown.tsx +++ b/imports/ui/UserDropdown.tsx @@ -5,13 +5,7 @@ */ import { faChevronDown, faCircleUser, faRightFromBracket } from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; -import { - Avatar, - Dropdown, - DropdownItem, - DropdownSeparator, - Text, -} from '@mieweb/ui'; +import { Avatar, Dropdown, DropdownItem, DropdownSeparator, Text } from '@mieweb/ui'; import React, { useCallback } from 'react'; import { useSession } from '../lib/useSession'; @@ -45,10 +39,7 @@ export const UserDropdown: React.FC = () => { > {truncated} - + } placement="bottom-end" @@ -58,17 +49,18 @@ export const UserDropdown: React.FC = () => {
        - {truncated} - Authenticated + + {truncated} + + + Authenticated +
        - } - onClick={handleProfile} - > + } onClick={handleProfile}> Profile diff --git a/index.html b/index.html index 541bfba3b..f4fa590f9 100644 --- a/index.html +++ b/index.html @@ -17,8 +17,12 @@ })(); From 1f4efebc2b12f4d2bc258b6ab70c299838095edf Mon Sep 17 00:00:00 2001 From: Michael Fisher Date: Wed, 22 Apr 2026 15:37:07 -0400 Subject: [PATCH 17/26] Resolve package resolutions --- package-lock.json | 13 +++++-------- package.json | 2 +- 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/package-lock.json b/package-lock.json index d1817cf61..5a4a95cdc 100644 --- a/package-lock.json +++ b/package-lock.json @@ -14,7 +14,7 @@ "@fortawesome/free-solid-svg-icons": "^7.0.1", "@fortawesome/react-fontawesome": "^3.0.2", "@mieweb/ui": "^0.2.4", - "@mieweb/ychart": "^1.0.0", + "@mieweb/ychart": "1.0.0", "@swc/helpers": "^0.5.17", "motion": "^12.34.3", "postcss-load-config": "^6.0.1", @@ -738,9 +738,9 @@ } }, "node_modules/@mieweb/ychart": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@mieweb/ychart/-/ychart-1.1.0.tgz", - "integrity": "sha512-wW5GKYzPrDg5uO+qh61KtZbm46k/GJzTU6Xqu3rgD2gjQ1TFUAtK1VqW1FLJZMPHbW9rczc121r9bfbAFV0hwA==", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@mieweb/ychart/-/ychart-1.0.0.tgz", + "integrity": "sha512-vUOFJ94BC2QF/zVDOg7s4EU4dExoz1pdE81HsfBIj5zWbRDZQDUYr5HCOo7rN7NgFf2mR/3y4TXrtwAAVj5w3Q==", "license": "MIT", "dependencies": { "@codemirror/lang-yaml": "^6.1.2", @@ -748,7 +748,6 @@ "@codemirror/state": "^6.5.2", "@codemirror/theme-one-dark": "^6.1.3", "@codemirror/view": "^6.38.6", - "@mieweb/ui": "^0.2.4", "bootstrap": "^5.3.8", "codemirror": "^6.0.2", "d3": "^7.9.0", @@ -760,9 +759,7 @@ "d3-selection": "3", "d3-shape": "3", "d3-zoom": "3", - "js-yaml": "^4.1.1", - "react": "^19.1.0", - "react-dom": "^19.1.0" + "js-yaml": "^4.1.1" }, "engines": { "node": ">=24.0.0" diff --git a/package.json b/package.json index 52f12e8c1..af60ee8c4 100644 --- a/package.json +++ b/package.json @@ -26,7 +26,7 @@ "@fortawesome/free-solid-svg-icons": "^7.0.1", "@fortawesome/react-fontawesome": "^3.0.2", "@mieweb/ui": "^0.2.4", - "@mieweb/ychart": "^1.0.0", + "@mieweb/ychart": "1.0.0", "@swc/helpers": "^0.5.17", "motion": "^12.34.3", "postcss-load-config": "^6.0.1", From ddd019f84f7ad20bf17b45c38ee420083275f1ca Mon Sep 17 00:00:00 2001 From: Michael Fisher Date: Wed, 22 Apr 2026 15:45:18 -0400 Subject: [PATCH 18/26] ci: remove meteor build/test in actions --- .github/workflows/ci.yml | 32 +++++--------------------------- 1 file changed, 5 insertions(+), 27 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a528d568d..2d74c5e7a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,16 +21,6 @@ jobs: with: node-version: 22 cache: 'npm' - - name: Cache Meteor - uses: actions/cache@v4 - with: - path: ~/.meteor - key: meteor-${{ runner.os }}-3.4-beta.3 - - name: Install Meteor - run: | - if ! command -v meteor >/dev/null; then - curl https://install.meteor.com/ | sh - fi - name: Install deps run: npm ci --no-audit --no-fund - name: Lint @@ -41,7 +31,7 @@ jobs: run: npm test build: - name: Meteor Build (Linux) + name: Vite Build runs-on: ubuntu-latest needs: lint_and_types steps: @@ -51,25 +41,13 @@ jobs: with: node-version: 22 cache: 'npm' - - name: Cache Meteor - uses: actions/cache@v4 - with: - path: ~/.meteor - key: meteor-${{ runner.os }}-3.4-beta.3 - - name: Install Meteor - run: | - if ! command -v meteor >/dev/null; then - curl https://install.meteor.com/ | sh - fi - name: Install deps run: npm ci --no-audit --no-fund - - name: Build (directory) - run: | - meteor build ./build --directory - ls -1 ./build + - name: Build + run: npm run build - name: Upload build artifact uses: actions/upload-artifact@v4 with: - name: meteor-build - path: build + name: vite-build + path: dist if-no-files-found: error From 357be056f14144b543a2306c2d5b2eb94bd41789 Mon Sep 17 00:00:00 2001 From: Michael Fisher Date: Wed, 22 Apr 2026 15:49:10 -0400 Subject: [PATCH 19/26] ci: remove Meteor, use Node 24, switch to Vite build MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Remove Meteor install/cache steps — project is now Vite-based - Bump Node to 24 (required by @mieweb/ychart engine constraint) - Replace meteor build with npm run build (Vite) - Update artifact path from build/ to dist/ --- .github/workflows/ci.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2d74c5e7a..88b01c768 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -12,14 +12,14 @@ concurrency: jobs: lint_and_types: - name: Lint & Type Check (Node 22) + name: Lint & Type Check (Node 24) runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - name: Use Node 22 + - name: Use Node 24 uses: actions/setup-node@v4 with: - node-version: 22 + node-version: 24 cache: 'npm' - name: Install deps run: npm ci --no-audit --no-fund @@ -36,10 +36,10 @@ jobs: needs: lint_and_types steps: - uses: actions/checkout@v4 - - name: Use Node 22 + - name: Use Node 24 uses: actions/setup-node@v4 with: - node-version: 22 + node-version: 24 cache: 'npm' - name: Install deps run: npm ci --no-audit --no-fund From 8f69018a8dfcfbc35ea7fc265c8338f9eb888b77 Mon Sep 17 00:00:00 2001 From: Michael Fisher Date: Wed, 22 Apr 2026 15:51:49 -0400 Subject: [PATCH 20/26] ci: use Node 25 to match local dev environment --- .github/workflows/ci.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 88b01c768..ad8083638 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -12,14 +12,14 @@ concurrency: jobs: lint_and_types: - name: Lint & Type Check (Node 24) + name: Lint & Type Check (Node 25) runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - name: Use Node 24 + - name: Use Node 25 uses: actions/setup-node@v4 with: - node-version: 24 + node-version: 25 cache: 'npm' - name: Install deps run: npm ci --no-audit --no-fund @@ -36,10 +36,10 @@ jobs: needs: lint_and_types steps: - uses: actions/checkout@v4 - - name: Use Node 24 + - name: Use Node 25 uses: actions/setup-node@v4 with: - node-version: 24 + node-version: 25 cache: 'npm' - name: Install deps run: npm ci --no-audit --no-fund From 393a4e53ace42e20a5b969cc55bad2a637d103a2 Mon Sep 17 00:00:00 2001 From: Michael Fisher Date: Wed, 22 Apr 2026 15:54:43 -0400 Subject: [PATCH 21/26] ci: use npm install instead of npm ci to fix cross-platform lock file mismatch --- .github/workflows/ci.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ad8083638..200a8caad 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,7 +22,7 @@ jobs: node-version: 25 cache: 'npm' - name: Install deps - run: npm ci --no-audit --no-fund + run: npm install --no-audit --no-fund - name: Lint run: npm run lint - name: Type Check @@ -42,7 +42,7 @@ jobs: node-version: 25 cache: 'npm' - name: Install deps - run: npm ci --no-audit --no-fund + run: npm install --no-audit --no-fund - name: Build run: npm run build - name: Upload build artifact From d6b81751f772b2fc5f92ca5e75f0d58c163f17ac Mon Sep 17 00:00:00 2001 From: Michael Fisher Date: Wed, 22 Apr 2026 15:57:39 -0400 Subject: [PATCH 22/26] fix: exclude vite.config.ts from app tsconfig to fix typecheck --- tsconfig.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tsconfig.json b/tsconfig.json index 3e38087d5..2c24904b4 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -17,6 +17,6 @@ "@lib/*": ["imports/lib/*"] } }, - "include": ["imports", "client", "vite.config.ts"], + "include": ["imports", "client"], "exclude": ["node_modules"] } From 9adce175e661d9f1f4a7350a3a8eb7abeafd8c7a Mon Sep 17 00:00:00 2001 From: Michael Fisher Date: Wed, 22 Apr 2026 16:07:52 -0400 Subject: [PATCH 23/26] fix: override ychart global header CSS that was turning app header blue ychart injects an unlayered header{} rule with a blue gradient background. Added a higher-specificity header.sticky{} override to reset the affected properties (background, color, padding, box-shadow) so app chrome is unaffected. --- client/styles.css | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/client/styles.css b/client/styles.css index 22577f76c..76dcd72c8 100644 --- a/client/styles.css +++ b/client/styles.css @@ -8,6 +8,16 @@ html { html[data-theme='dark'] { background-color: #0a0a0a; /* neutral-950 */ } + +/* Neutralize @mieweb/ychart global `header {}` rule that overrides our app header. + ychart injects unlayered CSS, so we need an unlayered rule with higher specificity. */ +header.sticky { + background: transparent; + color: inherit; + padding: 0; + box-shadow: none; + z-index: 10; +} @source "../node_modules/@mieweb/ui/dist"; @custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *)); From 7f0ea08431bf5ac16bc7ef072fa08103508f9213 Mon Sep 17 00:00:00 2001 From: Poonam Dharamkar Date: Wed, 22 Apr 2026 19:29:21 -0400 Subject: [PATCH 24/26] feat: implement frontend deployment workflow and add backend submodule --- .github/workflows/ci.yml | 87 +++++++++++++++++++++++++++++++++++++--- .gitmodules | 3 ++ backend | 1 + 3 files changed, 86 insertions(+), 5 deletions(-) create mode 100644 .gitmodules create mode 160000 backend diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 200a8caad..fe71f75b7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,13 +1,12 @@ -name: CI +name: Deploy Frontend on: push: - branches: [main] - pull_request: - branches: [main] + branches: + - main concurrency: - group: ci-${{ github.ref }} + group: deploy-frontend-${{ github.ref }} cancel-in-progress: true jobs: @@ -51,3 +50,81 @@ jobs: name: vite-build path: dist if-no-files-found: error + + deploy: + name: Deploy Frontend - ${{ matrix.env }} + runs-on: ubuntu-latest + needs: build + strategy: + fail-fast: false + matrix: + include: + - env: DEV + host_secret: SSH_HOST_DEV + port_secret: SSH_PORT_DEV + key_secret: SSH_PRIVATE_KEY_DEV + pm2_name: timehuddledev + - env: PROD + host_secret: SSH_HOST_PROD + port_secret: SSH_PORT_PROD + key_secret: SSH_PRIVATE_KEY_PROD + pm2_name: timehuddle-prod + + steps: + - name: Setup SSH + run: | + mkdir -p ~/.ssh + echo "${{ secrets[matrix.key_secret] }}" > ~/.ssh/deploy_key + chmod 600 ~/.ssh/deploy_key + ssh-keyscan -p ${{ secrets[matrix.port_secret] }} ${{ secrets[matrix.host_secret] }} >> ~/.ssh/known_hosts 2>/dev/null || true + + - name: Deploy to ${{ matrix.env }} + run: | + ssh -p ${{ secrets[matrix.port_secret] }} \ + -i ~/.ssh/deploy_key \ + -o StrictHostKeyChecking=no \ + ${{ secrets.SSH_USER }}@${{ secrets[matrix.host_secret] }} << 'EOF' + set -e + + REPO_DIR="/home/pdharamkar/timehuddle" + PM2_NAME="${{ matrix.pm2_name }}" + + git config --global --add safe.directory "$REPO_DIR" 2>/dev/null || true + cd "$REPO_DIR" + + echo "🛑 Stopping PM2 process: $PM2_NAME..." + pm2 stop "$PM2_NAME" 2>/dev/null || true + + echo "🔄 Fetching and pulling latest code..." + git fetch origin + git pull origin main + + echo "⚙️ Installing dependencies..." + npm install + + echo "🏗️ Building frontend..." + npm run build + + echo "🚀 Restarting PM2..." + pm2 restart "$PM2_NAME" 2>/dev/null || pm2 start ecosystem.config.cjs --only "$PM2_NAME" + pm2 save + + echo "⏳ Waiting for process to stabilize..." + sleep 5 + + echo "📊 PM2 Status:" + pm2 status + + echo "✅ Verifying $PM2_NAME is online..." + if pm2 list | grep -E "$PM2_NAME" | grep -q "online"; then + echo "✅ ${{ matrix.env }} frontend deployment successful! $PM2_NAME is online." + else + echo "❌ $PM2_NAME failed to start!" + pm2 logs "$PM2_NAME" --lines 30 --nostream || true + exit 1 + fi + EOF + + - name: Deployment Status + if: failure() + run: echo "❌ ${{ matrix.env }} frontend deployment failed!" diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 000000000..50f502bd2 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "backend"] + path = backend + url = https://github.com/Dharp02/timeharbor-timehuddle-backend.git diff --git a/backend b/backend new file mode 160000 index 000000000..ba4c4a2f4 --- /dev/null +++ b/backend @@ -0,0 +1 @@ +Subproject commit ba4c4a2f4cab865c6c0712c0fbae4a44c5c3b6f6 From 546aaf686c68ca8b371e277151b11f32c575d3a3 Mon Sep 17 00:00:00 2001 From: Michael Fisher Date: Wed, 22 Apr 2026 19:34:40 -0400 Subject: [PATCH 25/26] Revert "fix: override ychart global header CSS that was turning app header blue" This reverts commit 9adce175e661d9f1f4a7350a3a8eb7abeafd8c7a. --- client/styles.css | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/client/styles.css b/client/styles.css index 76dcd72c8..22577f76c 100644 --- a/client/styles.css +++ b/client/styles.css @@ -8,16 +8,6 @@ html { html[data-theme='dark'] { background-color: #0a0a0a; /* neutral-950 */ } - -/* Neutralize @mieweb/ychart global `header {}` rule that overrides our app header. - ychart injects unlayered CSS, so we need an unlayered rule with higher specificity. */ -header.sticky { - background: transparent; - color: inherit; - padding: 0; - box-shadow: none; - z-index: 10; -} @source "../node_modules/@mieweb/ui/dist"; @custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *)); From 71763bf7cb1519082abf6c03cef760eae4b1bfd0 Mon Sep 17 00:00:00 2001 From: Michael Fisher Date: Wed, 22 Apr 2026 19:42:04 -0400 Subject: [PATCH 26/26] fix: update @mieweb/ychart to version 1.1.0 in package.json and package-lock.json --- package-lock.json | 13 ++++++++----- package.json | 2 +- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/package-lock.json b/package-lock.json index 5a4a95cdc..8bda3ce6b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -14,7 +14,7 @@ "@fortawesome/free-solid-svg-icons": "^7.0.1", "@fortawesome/react-fontawesome": "^3.0.2", "@mieweb/ui": "^0.2.4", - "@mieweb/ychart": "1.0.0", + "@mieweb/ychart": "^1.1.0", "@swc/helpers": "^0.5.17", "motion": "^12.34.3", "postcss-load-config": "^6.0.1", @@ -738,9 +738,9 @@ } }, "node_modules/@mieweb/ychart": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@mieweb/ychart/-/ychart-1.0.0.tgz", - "integrity": "sha512-vUOFJ94BC2QF/zVDOg7s4EU4dExoz1pdE81HsfBIj5zWbRDZQDUYr5HCOo7rN7NgFf2mR/3y4TXrtwAAVj5w3Q==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@mieweb/ychart/-/ychart-1.1.0.tgz", + "integrity": "sha512-wW5GKYzPrDg5uO+qh61KtZbm46k/GJzTU6Xqu3rgD2gjQ1TFUAtK1VqW1FLJZMPHbW9rczc121r9bfbAFV0hwA==", "license": "MIT", "dependencies": { "@codemirror/lang-yaml": "^6.1.2", @@ -748,6 +748,7 @@ "@codemirror/state": "^6.5.2", "@codemirror/theme-one-dark": "^6.1.3", "@codemirror/view": "^6.38.6", + "@mieweb/ui": "^0.2.4", "bootstrap": "^5.3.8", "codemirror": "^6.0.2", "d3": "^7.9.0", @@ -759,7 +760,9 @@ "d3-selection": "3", "d3-shape": "3", "d3-zoom": "3", - "js-yaml": "^4.1.1" + "js-yaml": "^4.1.1", + "react": "^19.1.0", + "react-dom": "^19.1.0" }, "engines": { "node": ">=24.0.0" diff --git a/package.json b/package.json index af60ee8c4..adaf6ad8a 100644 --- a/package.json +++ b/package.json @@ -26,7 +26,7 @@ "@fortawesome/free-solid-svg-icons": "^7.0.1", "@fortawesome/react-fontawesome": "^3.0.2", "@mieweb/ui": "^0.2.4", - "@mieweb/ychart": "1.0.0", + "@mieweb/ychart": "^1.1.0", "@swc/helpers": "^0.5.17", "motion": "^12.34.3", "postcss-load-config": "^6.0.1",