16 Commits

Author SHA1 Message Date
Joyce
267c1747f4 update 2026-02-02 14:12:27 -05:00
9412d5c0a0 Merge pull request 'imporvements' (#4) from implement-feedback into main
Reviewed-on: #4
2026-02-02 18:52:36 +00:00
Joyce
192b885149 imporvements 2026-02-02 13:49:11 -05:00
10675b6846 Merge pull request 'update to use authentik' (#3) from implement-authentication into main
Reviewed-on: #3
2026-01-29 17:46:43 +00:00
Joyce
e544872430 update to use authentik 2026-01-29 12:46:01 -05:00
f2142633d4 Merge pull request 'improve timezone discovery' (#2) from fix-timezone-issue into main
Reviewed-on: #2
2026-01-28 20:35:27 +00:00
Joyce
117b28c2e9 improve timezone discovery 2026-01-28 15:31:30 -05:00
Joyce
880925f30d improve timezone discovery 2026-01-28 14:53:12 -05:00
daa0afaa25 Merge pull request 'cleanup-and-test' (#1) from cleanup-and-test into main
Reviewed-on: #1
2026-01-23 20:44:13 +00:00
Joyce
49dbc786e9 fix: use SYNC_DATABASE_URL env var for alembic migrations
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-21 17:24:41 -05:00
Joyce
922b6f31d1 add static serve 2026-01-21 16:36:40 -05:00
Joyce
f02b6ca886 chore: rename compose files - production as default
- docker-compose.yml → production (Coolify default)
- docker-compose.dev.yml → local development

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-21 15:25:05 -05:00
Joyce
cd62d7f94b chore: improve production deployment flexibility
- Switch frontend from nginx to caddy for consistency with Coolify
- Make VITE_API_URL optional, auto-derive from window.location.origin/api
- Remove hardcoded port mappings, let Coolify/Traefik handle routing
- Simplifies deployment configuration

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-21 15:25:05 -05:00
Joyce
a8ec0936d4 chore: improve production deployment flexibility
- Switch frontend from nginx to caddy for consistency with Coolify
- Make VITE_API_URL optional, auto-derive from window.location.origin/api
- Simplifies deployment by not requiring build-time API URL

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-21 14:55:26 -05:00
Joyce
7fefd634f5 feat: add production deployment config
- Add docker-compose.prod.yml with env var support
- Add frontend/Dockerfile.prod with nginx for static serving
- Fix Zulip notification to run in thread pool (avoid blocking)
- Use Zulip time format for timezone-aware display
- Add Zulip @mentions for users matched by email

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-21 14:29:52 -05:00
Joyce
26311c867a feat: add email, scheduler, and Zulip integration services
- Add email service for sending meeting invites with ICS attachments
- Add scheduler for background calendar sync jobs
- Add Zulip service for meeting notifications
- Make ics_url optional for participants
- Add /api/schedule endpoint with 2-hour lead time validation
- Update frontend to support scheduling flow

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-21 13:52:02 -05:00
36 changed files with 1422 additions and 225 deletions

View File

@@ -1,3 +1,4 @@
import os
from logging.config import fileConfig
from alembic import context
@@ -9,6 +10,10 @@ config = context.config
fileConfig(config.config_file_name)
target_metadata = Base.metadata
# Use SYNC_DATABASE_URL env var if set, otherwise fall back to alembic.ini
if os.getenv("SYNC_DATABASE_URL"):
config.set_main_option("sqlalchemy.url", os.getenv("SYNC_DATABASE_URL"))
def run_migrations_offline():
url = config.get_main_option("sqlalchemy.url")

View File

@@ -22,7 +22,7 @@ def upgrade() -> None:
sa.Column("id", sa.UUID(), nullable=False),
sa.Column("name", sa.String(255), nullable=False),
sa.Column("email", sa.String(255), nullable=False),
sa.Column("ics_url", sa.Text(), nullable=False),
sa.Column("ics_url", sa.Text(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("updated_at", sa.DateTime(), nullable=False),
sa.PrimaryKeyConstraint("id"),

View File

@@ -0,0 +1,29 @@
"""add timezone to participant
Revision ID: 46a2e388b20a
Revises: 001
Create Date: 2026-01-28 18:48:09.141869
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
revision: str = '46a2e388b20a'
down_revision: Union[str, None] = '001'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('participants', sa.Column('timezone', sa.String(length=50), nullable=False, server_default='UTC'))
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('participants', 'timezone')
# ### end Alembic commands ###

View File

@@ -15,6 +15,9 @@ dependencies = [
"python-dateutil>=2.9.0",
"pydantic[email]>=2.10.0",
"pydantic-settings>=2.6.0",
"apscheduler>=3.10.4",
"aiosmtplib>=3.0.1",
"zulip>=0.9.0",
]
[project.optional-dependencies]

View File

@@ -70,7 +70,7 @@ async def calculate_availability(
participants = {p.id: p for p in participants_result.scalars().all()}
days = ["Mon", "Tue", "Wed", "Thu", "Fri"]
hours = list(range(9, 18))
hours = list(range(0, 24))
slots = []
for day_offset, day_name in enumerate(days):
@@ -96,8 +96,9 @@ async def calculate_availability(
availability = "none"
slots.append({
"day": day_name,
"day": slot_start.strftime("%Y-%m-%d"),
"hour": hour,
"start_time": slot_start,
"availability": availability,
"availableParticipants": available_participants,
})

View File

@@ -6,6 +6,18 @@ class Settings(BaseSettings):
sync_database_url: str = "postgresql://postgres:postgres@db:5432/availability"
ics_refresh_interval_minutes: int = 15
# SMTP Settings
smtp_host: str | None = None
smtp_port: int = 587
smtp_user: str | None = None
smtp_password: str | None = None
# Zulip Settings
zulip_site: str | None = None
zulip_email: str | None = None
zulip_api_key: str | None = None
zulip_stream: str = "general"
class Config:
env_file = ".env"

View File

@@ -0,0 +1,82 @@
import logging
import uuid
from datetime import datetime, timezone
import aiosmtplib
from email.message import EmailMessage
from icalendar import Calendar, Event, vCalAddress, vText
from app.config import settings
logger = logging.getLogger(__name__)
async def send_meeting_invite(
participants: list[dict],
title: str,
description: str,
start_time: datetime,
end_time: datetime,
) -> bool:
if not settings.smtp_host or not settings.smtp_user or not settings.smtp_password:
logger.warning("SMTP credentials not configured. Skipping email invite.")
return False
# Create the ICS content
cal = Calendar()
cal.add('prodid', '-//Common Availability//m.com//')
cal.add('version', '2.0')
cal.add('method', 'REQUEST')
event = Event()
event.add('summary', title)
event.add('dtstart', start_time)
event.add('dtend', end_time)
event.add('dtstamp', datetime.now(timezone.utc))
event.add('description', description)
event.add('uid', str(uuid.uuid4()))
event.add('organizer', vCalAddress(f'MAILTO:{settings.smtp_user}'))
attendee_emails = []
for p in participants:
attendee = vCalAddress(f'MAILTO:{p["email"]}')
attendee.params['cn'] = vText(p["name"])
attendee.params['ROLE'] = vText('REQ-PARTICIPANT')
event.add('attendee', attendee, encode=0)
attendee_emails.append(p["email"])
cal.add_component(event)
ics_data = cal.to_ical()
# Create Email
msg = EmailMessage()
msg["Subject"] = f"Invitation: {title}"
msg["From"] = settings.smtp_user
msg["To"] = ", ".join(attendee_emails)
msg.set_content(
f"You have been invited to: {title}\n"
f"When: {start_time.strftime('%Y-%m-%d %H:%M %Z')}\n\n"
f"{description}"
)
# Attach ICS
msg.add_attachment(
ics_data,
maintype="text",
subtype="calendar",
filename="invite.ics",
params={"method": "REQUEST"}
)
# Send
try:
await aiosmtplib.send(
msg,
hostname=settings.smtp_host,
port=settings.smtp_port,
username=settings.smtp_user,
password=settings.smtp_password,
start_tls=True
)
logger.info(f"Sent meeting invites to {len(attendee_emails)} participants")
return True
except Exception as e:
logger.error(f"Failed to send email invite: {e}")
return False

View File

@@ -1,3 +1,4 @@
import asyncio
import logging
from uuid import UUID
@@ -14,14 +15,27 @@ from app.schemas import (
AvailabilityRequest,
AvailabilityResponse,
ParticipantCreate,
ParticipantUpdate,
ParticipantResponse,
SyncResponse,
ScheduleRequest,
)
from app.scheduler import start_scheduler, stop_scheduler
from app.email_service import send_meeting_invite
from app.zulip_service import send_zulip_notification
from contextlib import asynccontextmanager
from datetime import datetime, timezone, timedelta
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
app = FastAPI(title="Common Availability API")
@asynccontextmanager
async def lifespan(app: FastAPI):
start_scheduler()
yield
stop_scheduler()
app = FastAPI(title="Common Availability API", lifespan=lifespan)
app.add_middleware(
CORSMiddleware,
@@ -50,6 +64,7 @@ async def create_participant(
participant = Participant(
name=data.name,
email=data.email,
timezone=data.timezone,
ics_url=data.ics_url,
)
db.add(participant)
@@ -57,7 +72,8 @@ async def create_participant(
await db.refresh(participant)
try:
await sync_participant_calendar(db, participant)
if participant.ics_url:
await sync_participant_calendar(db, participant)
except Exception as e:
logger.warning(f"Initial sync failed for {participant.email}: {e}")
@@ -81,6 +97,35 @@ async def get_participant(participant_id: UUID, db: AsyncSession = Depends(get_d
return participant
@app.patch("/api/participants/{participant_id}", response_model=ParticipantResponse)
async def update_participant(
participant_id: UUID, data: ParticipantUpdate, db: AsyncSession = Depends(get_db)
):
result = await db.execute(
select(Participant).where(Participant.id == participant_id)
)
participant = result.scalar_one_or_none()
if not participant:
raise HTTPException(status_code=404, detail="Participant not found")
if data.timezone is not None:
participant.timezone = data.timezone
if data.ics_url is not None:
participant.ics_url = data.ics_url if data.ics_url else None
await db.commit()
await db.refresh(participant)
# Re-sync calendar if ICS URL was updated
if data.ics_url is not None and participant.ics_url:
try:
await sync_participant_calendar(db, participant)
except Exception as e:
logger.warning(f"Calendar sync failed for {participant.email}: {e}")
return participant
@app.delete("/api/participants/{participant_id}")
async def delete_participant(participant_id: UUID, db: AsyncSession = Depends(get_db)):
result = await db.execute(
@@ -99,7 +144,8 @@ async def delete_participant(participant_id: UUID, db: AsyncSession = Depends(ge
async def get_availability(
request: AvailabilityRequest, db: AsyncSession = Depends(get_db)
):
slots = await calculate_availability(db, request.participant_ids)
reference_date = datetime.now(timezone.utc) + timedelta(weeks=request.week_offset)
slots = await calculate_availability(db, request.participant_ids, reference_date)
return {"slots": slots}
@@ -121,7 +167,54 @@ async def sync_participant(participant_id: UUID, db: AsyncSession = Depends(get_
raise HTTPException(status_code=404, detail="Participant not found")
try:
count = await sync_participant_calendar(db, participant)
return {"status": "success", "blocks_synced": count}
if participant.ics_url:
count = await sync_participant_calendar(db, participant)
return {"status": "success", "blocks_synced": count}
return {"status": "skipped", "message": "No ICS URL provided"}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/schedule")
async def schedule_meeting(
data: ScheduleRequest, db: AsyncSession = Depends(get_db)
):
min_start_time = datetime.now(timezone.utc) + timedelta(hours=2)
if data.start_time.replace(tzinfo=timezone.utc) < min_start_time:
raise HTTPException(
status_code=400,
detail="Meetings must be scheduled at least 2 hours in advance."
)
result = await db.execute(
select(Participant).where(Participant.id.in_(data.participant_ids))
)
participants = result.scalars().all()
if len(participants) != len(data.participant_ids):
raise HTTPException(status_code=400, detail="Some participants not found")
participant_dicts = [
{"name": p.name, "email": p.email} for p in participants
]
email_success = await send_meeting_invite(
participant_dicts,
data.title,
data.description,
data.start_time,
data.end_time
)
zulip_success = await asyncio.to_thread(
send_zulip_notification,
data.title,
data.start_time,
participant_dicts
)
return {
"status": "success",
"email_sent": email_success,
"zulip_sent": zulip_success
}

View File

@@ -18,7 +18,8 @@ class Participant(Base):
)
name: Mapped[str] = mapped_column(String(255), nullable=False)
email: Mapped[str] = mapped_column(String(255), nullable=False, unique=True)
ics_url: Mapped[str] = mapped_column(Text, nullable=False)
timezone: Mapped[str] = mapped_column(String(50), nullable=False, default="America/Toronto")
ics_url: Mapped[str | None] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, nullable=False
)

View File

@@ -0,0 +1,39 @@
import logging
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.interval import IntervalTrigger
from sqlalchemy import select
from app.database import async_session_maker
from app.models import Participant
from app.ics_service import sync_participant_calendar
from app.config import settings
logger = logging.getLogger(__name__)
scheduler = AsyncIOScheduler()
async def run_sync_job():
logger.info("Starting background calendar sync...")
async with async_session_maker() as db:
result = await db.execute(select(Participant).where(Participant.ics_url.is_not(None)))
participants = result.scalars().all()
for participant in participants:
try:
await sync_participant_calendar(db, participant)
except Exception as e:
logger.error(f"Background sync failed for {participant.email}: {e}")
logger.info("Background calendar sync completed.")
def start_scheduler():
scheduler.add_job(
run_sync_job,
IntervalTrigger(minutes=settings.ics_refresh_interval_minutes),
id="calendar_sync",
replace_existing=True
)
scheduler.start()
logger.info("Scheduler started.")
def stop_scheduler():
scheduler.shutdown()
logger.info("Scheduler stopped.")

View File

@@ -7,14 +7,21 @@ from pydantic import BaseModel, EmailStr
class ParticipantCreate(BaseModel):
name: str
email: EmailStr
ics_url: str
timezone: str = "America/Toronto"
ics_url: str | None = None
class ParticipantUpdate(BaseModel):
timezone: str | None = None
ics_url: str | None = None
class ParticipantResponse(BaseModel):
id: UUID
name: str
email: str
ics_url: str
timezone: str
ics_url: str | None
created_at: datetime
updated_at: datetime
@@ -25,12 +32,14 @@ class ParticipantResponse(BaseModel):
class TimeSlot(BaseModel):
day: str
hour: int
start_time: datetime
availability: str
availableParticipants: list[str]
class AvailabilityRequest(BaseModel):
participant_ids: list[UUID]
week_offset: int = 0
class AvailabilityResponse(BaseModel):
@@ -39,3 +48,11 @@ class AvailabilityResponse(BaseModel):
class SyncResponse(BaseModel):
results: dict[str, dict]
class ScheduleRequest(BaseModel):
participant_ids: list[UUID]
title: str
description: str
start_time: datetime
end_time: datetime

View File

@@ -0,0 +1,83 @@
import logging
import zulip
from app.config import settings
from datetime import datetime
logger = logging.getLogger(__name__)
def get_zulip_usernames_by_email(client: zulip.Client) -> dict[str, str]:
"""Fetch all Zulip users and return a mapping of email -> full_name for mentions."""
try:
result = client.get_users()
if result.get("result") == "success":
users_map = {
user["email"].lower(): user["full_name"]
for user in result.get("members", [])
if not user.get("is_bot", False)
}
return users_map
except Exception as e:
logger.warning(f"Failed to fetch Zulip users: {e}")
return {}
def format_participant_mentions(
participants: list[dict],
zulip_users: dict[str, str],
) -> str:
"""Format participants as Zulip mentions where possible, plain names otherwise."""
formatted = []
for p in participants:
email = p["email"].lower()
if email in zulip_users:
formatted.append(f'@**{zulip_users[email]}**')
else:
formatted.append(p["name"])
return ", ".join(formatted)
def send_zulip_notification(
title: str,
start_time: datetime,
participants: list[dict],
) -> bool:
if not settings.zulip_site or not settings.zulip_api_key or not settings.zulip_email:
return False
try:
client = zulip.Client(
email=settings.zulip_email,
api_key=settings.zulip_api_key,
site=settings.zulip_site
)
zulip_users = get_zulip_usernames_by_email(client)
people = format_participant_mentions(participants, zulip_users)
zulip_time = f"<time:{start_time.isoformat()}>"
content = (
f"📅 **Meeting Scheduled**\n"
f"**What:** {title}\n"
f"**When:** {zulip_time}\n"
f"**Who:** {people}"
)
request = {
"type": "stream",
"to": settings.zulip_stream,
"topic": "Meeting Announcements",
"content": content
}
result = client.send_message(request)
if result.get("result") == "success":
return True
else:
logger.error(f"Zulip API error: {result.get('msg')}")
return False
except Exception as e:
logger.error(f"Failed to send Zulip notification: {e}")
return False

50
docker-compose.dev.yml Normal file
View File

@@ -0,0 +1,50 @@
services:
db:
image: postgres:16-alpine
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: availability
volumes:
- postgres_data:/var/lib/postgresql/data
ports:
- "5433:5432"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 5s
timeout: 5s
retries: 5
backend:
build:
context: ./backend
dockerfile: Dockerfile
environment:
DATABASE_URL: postgresql+asyncpg://postgres:postgres@db:5432/availability
SYNC_DATABASE_URL: postgresql://postgres:postgres@db:5432/availability
env_file:
- .env
ports:
- "8001:8000"
depends_on:
db:
condition: service_healthy
volumes:
- ./backend/src:/app/src
- ./backend/alembic:/app/alembic
frontend:
build:
context: ./frontend
dockerfile: Dockerfile
ports:
- "5174:8080"
environment:
VITE_API_URL: http://localhost:8001
depends_on:
- backend
volumes:
- ./frontend/src:/app/src
volumes:
postgres_data:

View File

@@ -2,47 +2,53 @@ services:
db:
image: postgres:16-alpine
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: availability
POSTGRES_USER: ${POSTGRES_USER:-postgres}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD required}
POSTGRES_DB: ${POSTGRES_DB:-availability}
volumes:
- postgres_data:/var/lib/postgresql/data
ports:
- "5432:5432"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 5s
timeout: 5s
retries: 5
restart: unless-stopped
backend:
build:
context: ./backend
dockerfile: Dockerfile
environment:
DATABASE_URL: postgresql+asyncpg://postgres:postgres@db:5432/availability
SYNC_DATABASE_URL: postgresql://postgres:postgres@db:5432/availability
ports:
- "8000:8000"
DATABASE_URL: postgresql+asyncpg://${POSTGRES_USER:-postgres}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB:-availability}
SYNC_DATABASE_URL: postgresql://${POSTGRES_USER:-postgres}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB:-availability}
SMTP_HOST: ${SMTP_HOST:-}
SMTP_PORT: ${SMTP_PORT:-587}
SMTP_USER: ${SMTP_USER:-}
SMTP_PASSWORD: ${SMTP_PASSWORD:-}
ZULIP_SITE: ${ZULIP_SITE:-}
ZULIP_EMAIL: ${ZULIP_EMAIL:-}
ZULIP_API_KEY: ${ZULIP_API_KEY:-}
ZULIP_STREAM: ${ZULIP_STREAM:-general}
depends_on:
db:
condition: service_healthy
volumes:
- ./backend/src:/app/src
- ./backend/alembic:/app/alembic
labels:
- traefik.http.middlewares.authentik-auth@file
restart: unless-stopped
frontend:
build:
context: ./frontend
dockerfile: Dockerfile
ports:
- "5173:8080"
environment:
VITE_API_URL: http://localhost:8000
dockerfile: Dockerfile.prod
args:
VITE_API_URL: ${VITE_API_URL:-}
depends_on:
- backend
volumes:
- ./frontend/src:/app/src
labels:
- traefik.http.middlewares.authentik-auth@file
restart: unless-stopped
expose:
- '80'
volumes:
postgres_data:

28
frontend/Dockerfile.prod Normal file
View File

@@ -0,0 +1,28 @@
# Build stage
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
# VITE_API_URL must be set at build time
ARG VITE_API_URL
ENV VITE_API_URL=${VITE_API_URL}
RUN npm run build
# Production stage
FROM nginx:alpine
# Copy built assets
COPY --from=builder /app/dist /usr/share/nginx/html
# Copy nginx config
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

19
frontend/nginx.conf Normal file
View File

@@ -0,0 +1,19 @@
server {
listen 80;
server_name _;
root /usr/share/nginx/html;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
location /assets/ {
expires 1y;
add_header Cache-Control "public, immutable";
}
gzip on;
gzip_types text/css application/javascript application/json image/svg+xml;
gzip_comp_level 6;
}

View File

@@ -2859,7 +2859,6 @@
"integrity": "sha512-bJFoMATwIGaxxx8VJPeM8TonI8t579oRvgAuT8zFugJsJZgzqv0Fu8Mhp68iecjzG7cnN3mO2dJQ5uUM2EFrgQ==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"undici-types": "~6.21.0"
}
@@ -2877,7 +2876,6 @@
"integrity": "sha512-/LDXMQh55EzZQ0uVAZmKKhfENivEvWz6E+EYzh+/MCjMhNsotd+ZHhBGIjFDTi6+fz0OhQQQLbTgdQIxxCsC0w==",
"devOptional": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@types/prop-types": "*",
"csstype": "^3.0.2"
@@ -2889,7 +2887,6 @@
"integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==",
"devOptional": true,
"license": "MIT",
"peer": true,
"peerDependencies": {
"@types/react": "^18.0.0"
}
@@ -2940,7 +2937,6 @@
"integrity": "sha512-Zhy8HCvBUEfBECzIl1PKqF4p11+d0aUJS1GeUiuqK9WmOug8YCmC4h4bjyBvMyAMI9sbRczmrYL5lKg/YMbrcQ==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@typescript-eslint/scope-manager": "8.38.0",
"@typescript-eslint/types": "8.38.0",
@@ -3173,7 +3169,6 @@
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
"dev": true,
"license": "MIT",
"peer": true,
"bin": {
"acorn": "bin/acorn"
},
@@ -3378,7 +3373,6 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"caniuse-lite": "^1.0.30001726",
"electron-to-chromium": "^1.5.173",
@@ -3712,7 +3706,6 @@
"resolved": "https://registry.npmjs.org/date-fns/-/date-fns-3.6.0.tgz",
"integrity": "sha512-fRHTG8g/Gif+kSh50gaGEdToemgfj74aRX3swtiouboip5JDLAyDE9F11nHMIcvOaXeOC6D7SpNhi7uFyB7Uww==",
"license": "MIT",
"peer": true,
"funding": {
"type": "github",
"url": "https://github.com/sponsors/kossnocorp"
@@ -3794,8 +3787,7 @@
"version": "8.6.0",
"resolved": "https://registry.npmjs.org/embla-carousel/-/embla-carousel-8.6.0.tgz",
"integrity": "sha512-SjWyZBHJPbqxHOzckOfo8lHisEaJWmwd23XppYFYVh10bU66/Pn5tkVkbkCMZVdbUE5eTCI2nD8OyIP4Z+uwkA==",
"license": "MIT",
"peer": true
"license": "MIT"
},
"node_modules/embla-carousel-react": {
"version": "8.6.0",
@@ -3893,7 +3885,6 @@
"integrity": "sha512-LSehfdpgMeWcTZkWZVIJl+tkZ2nuSkyyB9C27MZqFWXuph7DvaowgcTvKqxvpLW1JZIk8PN7hFY3Rj9LQ7m7lg==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@eslint-community/eslint-utils": "^4.2.0",
"@eslint-community/regexpp": "^4.12.1",
@@ -5415,7 +5406,6 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"nanoid": "^3.3.11",
"picocolors": "^1.1.1",
@@ -5602,7 +5592,6 @@
"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
"integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"loose-envify": "^1.1.0"
},
@@ -5629,7 +5618,6 @@
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
"integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
"license": "MIT",
"peer": true,
"dependencies": {
"loose-envify": "^1.1.0",
"scheduler": "^0.23.2"
@@ -5643,7 +5631,6 @@
"resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.61.1.tgz",
"integrity": "sha512-2vbXUFDYgqEgM2RcXcAT2PwDW/80QARi+PKmHy5q2KhuKvOlG8iIYgf7eIlIANR5trW9fJbP4r5aub3a4egsew==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=18.0.0"
},
@@ -6197,7 +6184,6 @@
"resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.17.tgz",
"integrity": "sha512-w33E2aCvSDP0tW9RZuNXadXlkHXqFzSkQew/aIa2i/Sj8fThxwovwlXHSPXTbAHwEIhBFXAedUhP2tueAKP8Og==",
"license": "MIT",
"peer": true,
"dependencies": {
"@alloc/quick-lru": "^5.2.0",
"arg": "^5.0.2",
@@ -6322,7 +6308,6 @@
"integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==",
"dev": true,
"license": "Apache-2.0",
"peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
@@ -6502,7 +6487,6 @@
"integrity": "sha512-qO3aKv3HoQC8QKiNSTuUM1l9o/XX3+c+VTgLHbJWHZGeTPVAg2XwazI9UWzoxjIJCGCV2zU60uqMzjeLZuULqA==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"esbuild": "^0.21.3",
"postcss": "^8.4.43",

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -16,6 +16,8 @@ const App = () => (
<BrowserRouter>
<Routes>
<Route path="/" element={<Index />} />
<Route path="/participants" element={<Index defaultTab="participants" />} />
<Route path="/schedule" element={<Index defaultTab="schedule" />} />
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
<Route path="*" element={<NotFound />} />
</Routes>

View File

@@ -1,10 +1,12 @@
const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:8000';
// Use VITE_API_URL if set at build time, otherwise derive from current origin
const API_URL = import.meta.env.VITE_API_URL || `${window.location.origin}/api`;
export interface ParticipantAPI {
id: string;
name: string;
email: string;
ics_url: string;
timezone: string;
ics_url: string | null;
created_at: string;
updated_at: string;
}
@@ -12,6 +14,7 @@ export interface ParticipantAPI {
export interface TimeSlotAPI {
day: string;
hour: number;
start_time: string;
availability: 'full' | 'partial' | 'none';
availableParticipants: string[];
}
@@ -19,7 +22,13 @@ export interface TimeSlotAPI {
export interface CreateParticipantRequest {
name: string;
email: string;
ics_url: string;
timezone: string;
ics_url?: string;
}
export interface UpdateParticipantRequest {
timezone?: string;
ics_url?: string;
}
async function handleResponse<T>(response: Response): Promise<T> {
@@ -44,6 +53,15 @@ export async function createParticipant(data: CreateParticipantRequest): Promise
return handleResponse<ParticipantAPI>(response);
}
export async function updateParticipant(id: string, data: UpdateParticipantRequest): Promise<ParticipantAPI> {
const response = await fetch(`${API_URL}/api/participants/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});
return handleResponse<ParticipantAPI>(response);
}
export async function deleteParticipant(id: string): Promise<void> {
const response = await fetch(`${API_URL}/api/participants/${id}`, {
method: 'DELETE',
@@ -53,11 +71,11 @@ export async function deleteParticipant(id: string): Promise<void> {
}
}
export async function fetchAvailability(participantIds: string[]): Promise<TimeSlotAPI[]> {
export async function fetchAvailability(participantIds: string[], weekOffset: number = 0): Promise<TimeSlotAPI[]> {
const response = await fetch(`${API_URL}/api/availability`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ participant_ids: participantIds }),
body: JSON.stringify({ participant_ids: participantIds, week_offset: weekOffset }),
});
const data = await handleResponse<{ slots: TimeSlotAPI[] }>(response);
return data.slots;
@@ -76,3 +94,24 @@ export async function syncParticipant(id: string): Promise<void> {
throw new Error('Failed to sync participant calendar');
}
}
export async function scheduleMeeting(
participantIds: string[],
title: string,
description: string,
startTime: string,
endTime: string,
): Promise<{ email_sent: boolean; zulip_sent: boolean }> {
const response = await fetch(`${API_URL}/api/schedule`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
participant_ids: participantIds,
title,
description,
start_time: startTime,
end_time: endTime,
}),
});
return handleResponse(response);
}

View File

@@ -6,17 +6,86 @@ import {
PopoverTrigger,
} from '@/components/ui/popover';
import { Button } from '@/components/ui/button';
import { Check, X, Loader2 } from 'lucide-react';
import { useState } from 'react';
import { Check, X, Loader2, ChevronLeft, ChevronRight, ChevronsRight } from 'lucide-react';
const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'];
const TIMEZONE = 'America/Toronto';
const dayNames = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'];
const hours = [9, 10, 11, 12, 13, 14, 15, 16, 17];
// Get the dates for Mon-Fri of a week in a specific timezone, offset by N weeks
const getWeekDates = (timezone: string, weekOffset: number = 0): string[] => {
// Get "now" in the target timezone
const now = new Date();
const formatter = new Intl.DateTimeFormat('en-CA', {
timeZone: timezone,
year: 'numeric',
month: '2-digit',
day: '2-digit',
});
// Parse today's date in the target timezone
const todayStr = formatter.format(now);
const [year, month, day] = todayStr.split('-').map(Number);
// Calculate Monday of this week
const todayDate = new Date(year, month - 1, day);
const dayOfWeek = todayDate.getDay();
const daysToMonday = dayOfWeek === 0 ? -6 : 1 - dayOfWeek;
const mondayDate = new Date(year, month - 1, day + daysToMonday + weekOffset * 7);
return dayNames.map((_, i) => {
const d = new Date(mondayDate);
d.setDate(mondayDate.getDate() + i);
const y = d.getFullYear();
const m = String(d.getMonth() + 1).padStart(2, '0');
const dd = String(d.getDate()).padStart(2, '0');
return `${y}-${m}-${dd}`;
});
};
// Convert a date string and hour in a timezone to a UTC Date
const toUTCDate = (dateStr: string, hour: number, timezone: string): Date => {
// Create a date string that represents the given hour in the given timezone
// Then parse it to get the UTC equivalent
const localDateStr = `${dateStr}T${String(hour).padStart(2, '0')}:00:00`;
// Use a trick: format in UTC then in target TZ to find the offset
const testDate = new Date(localDateStr + 'Z'); // Treat as UTC first
// Get what hour this would be in the target timezone
const tzHour = parseInt(
new Intl.DateTimeFormat('en-US', {
timeZone: timezone,
hour: 'numeric',
hour12: false,
}).format(testDate)
);
// Calculate offset in hours
const offset = tzHour - testDate.getUTCHours();
// Adjust: if we want `hour` in timezone, subtract the offset to get UTC
const utcDate = new Date(localDateStr + 'Z');
utcDate.setUTCHours(utcDate.getUTCHours() - offset);
return utcDate;
};
const MIN_WEEK_OFFSET = 0;
const DEFAULT_MAX_WEEK_OFFSET = 1;
const EXPANDED_MAX_WEEK_OFFSET = 4;
interface AvailabilityHeatmapProps {
slots: TimeSlot[];
selectedParticipants: Participant[];
onSlotSelect: (slot: TimeSlot) => void;
showPartialAvailability?: boolean;
isLoading?: boolean;
weekOffset?: number;
onWeekOffsetChange?: (offset: number) => void;
}
export const AvailabilityHeatmap = ({
@@ -25,9 +94,23 @@ export const AvailabilityHeatmap = ({
onSlotSelect,
showPartialAvailability = false,
isLoading = false,
weekOffset = 0,
onWeekOffsetChange,
}: AvailabilityHeatmapProps) => {
const getSlot = (day: string, hour: number) => {
return slots.find((s) => s.day === day && s.hour === hour);
const [expanded, setExpanded] = useState(false);
const maxWeekOffset = expanded ? EXPANDED_MAX_WEEK_OFFSET : DEFAULT_MAX_WEEK_OFFSET;
const weekDates = getWeekDates(TIMEZONE, weekOffset);
// Find a slot that matches the given display timezone date/hour
const getSlot = (dateStr: string, hour: number): TimeSlot | undefined => {
// Convert display timezone date/hour to UTC
const targetUTC = toUTCDate(dateStr, hour, TIMEZONE);
return slots.find((s) => {
const slotDate = new Date(s.start_time);
// Compare UTC timestamps (with some tolerance for rounding)
return Math.abs(slotDate.getTime() - targetUTC.getTime()) < 60000; // 1 minute tolerance
});
};
const getEffectiveAvailability = (slot: TimeSlot) => {
@@ -41,17 +124,36 @@ export const AvailabilityHeatmap = ({
return `${hour.toString().padStart(2, '0')}:00`;
};
const getWeekDateRange = () => {
const isSlotTooSoon = (dateStr: string, hour: number) => {
// Convert to UTC and compare with current time
const slotTimeUTC = toUTCDate(dateStr, hour, TIMEZONE);
const now = new Date();
const monday = new Date(now);
monday.setDate(now.getDate() - now.getDay() + 1);
const friday = new Date(monday);
friday.setDate(monday.getDate() + 4);
const twoHoursFromNow = new Date(now.getTime() + 2 * 60 * 60 * 1000);
return slotTimeUTC < twoHoursFromNow;
};
const format = (d: Date) => d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
const getWeekDateRange = () => {
if (weekDates.length < 5) return '';
const monday = new Date(weekDates[0] + 'T12:00:00Z');
const friday = new Date(weekDates[4] + 'T12:00:00Z');
const format = (d: Date) =>
d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' });
return `${format(monday)} ${format(friday)}`;
};
// Format hour for display in popover (in the display timezone)
const formatDisplayTime = (hour: number) => {
// Create a date at that hour
const date = new Date();
date.setHours(hour, 0, 0, 0);
return new Intl.DateTimeFormat('en-US', {
hour: 'numeric',
minute: '2-digit',
hour12: true,
}).format(date);
};
if (selectedParticipants.length === 0) {
return (
<div className="bg-card rounded-xl shadow-card p-8 text-center animate-fade-in">
@@ -74,25 +176,84 @@ export const AvailabilityHeatmap = ({
return (
<div className="bg-card rounded-xl shadow-card p-6 animate-slide-up">
<div className="mb-6">
<h3 className="text-lg font-semibold text-foreground">
Common Availability Week of {getWeekDateRange()}
</h3>
<p className="text-sm text-muted-foreground mt-1">
{selectedParticipants.length} participant{selectedParticipants.length > 1 ? 's' : ''}: {selectedParticipants.map(p => p.name.split(' ')[0]).join(', ')}
</p>
<div className="mb-6 flex justify-between items-start">
<div>
<div className="flex items-center gap-2">
<h3 className="text-lg font-semibold text-foreground">
Common Availability Week of {getWeekDateRange()}
</h3>
</div>
<p className="text-sm text-muted-foreground mt-1">
{selectedParticipants.length} participant{selectedParticipants.length > 1 ? 's' : ''}: {selectedParticipants.map(p => p.name.split(' ')[0]).join(', ')}
</p>
</div>
{onWeekOffsetChange && (
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
disabled={weekOffset <= MIN_WEEK_OFFSET}
onClick={() => onWeekOffsetChange(weekOffset - 1)}
>
<ChevronLeft className="w-4 h-4" />
</Button>
{weekOffset !== 0 && (
<Button
variant="ghost"
size="sm"
className="h-8 text-xs"
onClick={() => onWeekOffsetChange(0)}
>
This week
</Button>
)}
{weekOffset < maxWeekOffset ? (
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={() => onWeekOffsetChange(weekOffset + 1)}
>
<ChevronRight className="w-4 h-4" />
</Button>
) : !expanded ? (
<Button
variant="outline"
size="sm"
className="h-8 text-xs gap-1"
onClick={() => setExpanded(true)}
>
<ChevronsRight className="w-3.5 h-3.5" />
Look further ahead
</Button>
) : (
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
disabled
>
<ChevronRight className="w-4 h-4" />
</Button>
)}
</div>
)}
</div>
<div className="overflow-x-auto">
<div className="min-w-[600px]">
<div className="grid grid-cols-[60px_repeat(5,1fr)] gap-1 mb-2">
<div></div>
{days.map((day) => (
{dayNames.map((dayName, i) => (
<div
key={day}
key={dayName}
className="text-center text-sm font-medium text-muted-foreground py-2"
>
{day}
<div>{dayName}</div>
<div className="text-xs opacity-70">
{weekDates[i]?.slice(5).replace('-', '/')}
</div>
</div>
))}
</div>
@@ -103,18 +264,22 @@ export const AvailabilityHeatmap = ({
<div className="text-xs text-muted-foreground flex items-center justify-end pr-3">
{formatHour(hour)}
</div>
{days.map((day) => {
const slot = getSlot(day, hour);
if (!slot) return <div key={`${day}-${hour}`} className="h-12 bg-muted rounded" />;
{weekDates.map((dateStr, dayIndex) => {
const slot = getSlot(dateStr, hour);
const dayName = dayNames[dayIndex];
const tooSoon = isSlotTooSoon(dateStr, hour);
if (!slot) return <div key={`${dateStr}-${hour}`} className="h-12 bg-muted rounded" />;
const effectiveAvailability = getEffectiveAvailability(slot);
return (
<Popover key={`${day}-${hour}`}>
<Popover key={`${dateStr}-${hour}`}>
<PopoverTrigger asChild>
<button
className={cn(
"h-12 rounded-md transition-all duration-200 hover:scale-105 hover:shadow-md focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
"h-12 rounded-md transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
tooSoon && "opacity-40 cursor-not-allowed",
!tooSoon && "hover:scale-105 hover:shadow-md",
effectiveAvailability === 'full' && "bg-availability-full hover:bg-availability-full/90",
effectiveAvailability === 'partial' && "bg-availability-partial hover:bg-availability-partial/90",
effectiveAvailability === 'none' && "bg-availability-none hover:bg-availability-none/90"
@@ -124,11 +289,17 @@ export const AvailabilityHeatmap = ({
<PopoverContent className="w-64 p-4 animate-scale-in" align="center">
<div className="space-y-3">
<div className="font-semibold text-foreground">
{day} {formatHour(hour)}{formatHour(hour + 1)}
{dayName} {formatDisplayTime(hour)}{formatDisplayTime(hour + 1)}
</div>
{tooSoon && (
<div className="text-sm text-muted-foreground italic">
This time slot has passed or is too soon to schedule
</div>
)}
<div className="space-y-2">
{selectedParticipants.map((participant) => {
const isAvailable = slot.availableParticipants.includes(participant.name);
return (
<div
key={participant.id}
@@ -142,13 +313,13 @@ export const AvailabilityHeatmap = ({
<span className={cn(
isAvailable ? "text-foreground" : "text-muted-foreground"
)}>
{participant.name.split(' ')[0]} {isAvailable ? 'free' : 'busy'}
{participant.name.split(' ')[0]}
</span>
</div>
);
})}
</div>
{effectiveAvailability !== 'none' && (
{effectiveAvailability !== 'none' && !tooSoon && (
<Button
variant="schedule"
className="w-full mt-2"

View File

@@ -1,4 +1,5 @@
import { Calendar } from 'lucide-react';
import { getAvatarColor } from '@/lib/utils';
export const Header = () => {
return (
@@ -14,7 +15,10 @@ export const Header = () => {
</div>
</div>
<div className="flex items-center gap-2">
<div className="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-sm font-medium text-primary">
<div
className="w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium text-white"
style={{ backgroundColor: getAvatarColor("AR") }}
>
AR
</div>
</div>

View File

@@ -3,38 +3,52 @@ import { Participant } from '@/types/calendar';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { UserPlus, Trash2, User } from 'lucide-react';
import { UserPlus, Trash2, User, Pencil, Check, X, AlertCircle } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';
import { getAvatarColor } from '@/lib/utils';
interface ParticipantManagerProps {
participants: Participant[];
onAddParticipant: (participant: { name: string; email: string; icsLink: string }) => void;
onAddParticipant: (participant: { name: string; email: string; timezone: string; icsLink: string }) => void;
onRemoveParticipant: (id: string) => void;
onUpdateParticipant?: (id: string, data: { timezone?: string; ics_url?: string }) => Promise<void>;
}
export const ParticipantManager = ({
participants,
onAddParticipant,
onRemoveParticipant,
onUpdateParticipant,
}: ParticipantManagerProps) => {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [icsLink, setIcsLink] = useState('');
// Edit state
const [editingId, setEditingId] = useState<string | null>(null);
const [editIcsLink, setEditIcsLink] = useState('');
const [isUpdating, setIsUpdating] = useState(false);
const { toast } = useToast();
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (!name.trim() || !email.trim() || !icsLink.trim()) {
if (!name.trim() || !email.trim()) {
toast({
title: "Missing fields",
description: "Please fill in all fields",
description: "Please fill in name and email",
variant: "destructive",
});
return;
}
onAddParticipant({ name: name.trim(), email: email.trim(), icsLink: icsLink.trim() });
onAddParticipant({
name: name.trim(),
email: email.trim(),
timezone: 'America/Toronto',
icsLink: icsLink.trim() || ''
});
setName('');
setEmail('');
setIcsLink('');
@@ -45,6 +59,40 @@ export const ParticipantManager = ({
});
};
const startEditing = (participant: Participant) => {
setEditingId(participant.id);
setEditIcsLink(participant.icsLink || '');
};
const cancelEditing = () => {
setEditingId(null);
setEditIcsLink('');
};
const saveEditing = async (participantId: string) => {
if (!onUpdateParticipant) return;
setIsUpdating(true);
try {
await onUpdateParticipant(participantId, {
ics_url: editIcsLink || undefined,
});
toast({
title: "Participant updated",
description: "Changes saved successfully",
});
setEditingId(null);
} catch (error) {
toast({
title: "Update failed",
description: error instanceof Error ? error.message : "Unknown error",
variant: "destructive",
});
} finally {
setIsUpdating(false);
}
};
const getInitials = (name: string) => {
return name
.split(' ')
@@ -64,7 +112,7 @@ export const ParticipantManager = ({
</h3>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="grid gap-4 sm:grid-cols-3">
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
<div className="space-y-2">
<Label htmlFor="name">Name</Label>
<Input
@@ -92,7 +140,7 @@ export const ParticipantManager = ({
<Label htmlFor="icsLink">Calendar ICS Link</Label>
<Input
id="icsLink"
placeholder="https://calendar.google.com/..."
placeholder="https://..."
value={icsLink}
onChange={(e) => setIcsLink(e.target.value)}
className="bg-background"
@@ -123,26 +171,106 @@ export const ParticipantManager = ({
{participants.map((participant) => (
<div
key={participant.id}
className="flex items-center justify-between p-4 bg-background rounded-lg border border-border"
className="p-4 bg-background rounded-lg border border-border"
>
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-sm font-medium text-primary">
{getInitials(participant.name)}
</div>
<div>
<div className="font-medium text-foreground">{participant.name}</div>
<div className="text-sm text-muted-foreground">{participant.email}</div>
</div>
</div>
{editingId === participant.id ? (
// Edit mode
<div className="space-y-4">
<div className="flex items-center gap-3">
<div
className="w-10 h-10 rounded-full flex items-center justify-center text-sm font-medium text-white"
style={{ backgroundColor: getAvatarColor(participant.name) }}
>
{getInitials(participant.name)}
</div>
<div>
<div className="font-medium text-foreground">{participant.name}</div>
<div className="text-sm text-muted-foreground">{participant.email}</div>
</div>
</div>
<Button
variant="ghost"
size="icon"
onClick={() => onRemoveParticipant(participant.id)}
className="text-muted-foreground hover:text-destructive"
>
<Trash2 className="w-4 h-4" />
</Button>
<div className="space-y-2">
<Label htmlFor={`edit-ics-${participant.id}`}>Calendar ICS Link</Label>
<Input
id={`edit-ics-${participant.id}`}
value={editIcsLink}
onChange={(e) => setEditIcsLink(e.target.value)}
placeholder="https://..."
className="bg-card"
/>
</div>
<div className="flex gap-2">
<Button
size="sm"
onClick={() => saveEditing(participant.id)}
disabled={isUpdating}
>
<Check className="w-4 h-4 mr-1" />
{isUpdating ? 'Saving...' : 'Save'}
</Button>
<Button
size="sm"
variant="ghost"
onClick={cancelEditing}
disabled={isUpdating}
>
<X className="w-4 h-4 mr-1" />
Cancel
</Button>
</div>
</div>
) : (
// View mode
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div
className="w-10 h-10 rounded-full flex items-center justify-center text-sm font-medium text-white"
style={{ backgroundColor: getAvatarColor(participant.name) }}
>
{getInitials(participant.name)}
</div>
<div>
<div className="font-medium text-foreground">{participant.name}</div>
<div className="text-sm text-muted-foreground flex flex-wrap gap-x-2">
<span>{participant.email}</span>
<span className="text-muted-foreground/60"></span>
{participant.icsLink ? (
<span className="text-primary truncate max-w-[200px]" title={participant.icsLink}>
ICS linked
</span>
) : (
<span className="text-amber-600 flex items-center gap-1">
<AlertCircle className="w-3 h-3" />
No calendar linked
</span>
)}
</div>
</div>
</div>
<div className="flex items-center gap-1">
{onUpdateParticipant && (
<Button
variant="ghost"
size="icon"
onClick={() => startEditing(participant)}
className="text-muted-foreground hover:text-foreground"
>
<Pencil className="w-4 h-4" />
</Button>
)}
<Button
variant="ghost"
size="icon"
onClick={() => onRemoveParticipant(participant.id)}
className="text-muted-foreground hover:text-destructive"
>
<Trash2 className="w-4 h-4" />
</Button>
</div>
</div>
)}
</div>
))}
</div>

View File

@@ -1,8 +1,8 @@
import { useState } from 'react';
import { useState, useRef, useCallback, useEffect } from 'react';
import { Participant } from '@/types/calendar';
import { Input } from '@/components/ui/input';
import { X, Plus, Search, User } from 'lucide-react';
import { cn } from '@/lib/utils';
import { X, Plus, Search, AlertCircle } from 'lucide-react';
import { cn, getAvatarColor } from '@/lib/utils';
interface ParticipantSelectorProps {
participants: Participant[];
@@ -17,6 +17,19 @@ export const ParticipantSelector = ({
}: ParticipantSelectorProps) => {
const [searchQuery, setSearchQuery] = useState('');
const [isDropdownOpen, setIsDropdownOpen] = useState(false);
const [highlightedIndex, setHighlightedIndex] = useState(0);
const inputRef = useRef<HTMLInputElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const handleClickOutside = (e: MouseEvent) => {
if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
setIsDropdownOpen(false);
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, []);
const filteredParticipants = participants.filter(
(p) =>
@@ -25,14 +38,43 @@ export const ParticipantSelector = ({
p.email.toLowerCase().includes(searchQuery.toLowerCase()))
);
const addParticipant = (participant: Participant) => {
const addParticipant = useCallback((participant: Participant) => {
onSelectionChange([...selectedParticipants, participant]);
setSearchQuery('');
setIsDropdownOpen(false);
// Keep dropdown open for multi-select; clamp highlight to new list length
setHighlightedIndex((prev) => {
const newLength = filteredParticipants.length - 1;
return prev >= newLength ? Math.max(0, newLength - 1) : prev;
});
// Keep focus on input so user can continue selecting
requestAnimationFrame(() => inputRef.current?.focus());
}, [onSelectionChange, selectedParticipants, filteredParticipants.length]);
const handleKeyDown = (e: React.KeyboardEvent) => {
if (!isDropdownOpen || filteredParticipants.length === 0) return;
if (e.key === 'ArrowDown') {
e.preventDefault();
setHighlightedIndex((prev) =>
prev < filteredParticipants.length - 1 ? prev + 1 : 0
);
} else if (e.key === 'ArrowUp') {
e.preventDefault();
setHighlightedIndex((prev) =>
prev > 0 ? prev - 1 : filteredParticipants.length - 1
);
} else if (e.key === 'Enter') {
e.preventDefault();
addParticipant(filteredParticipants[highlightedIndex]);
} else if (e.key === 'Escape') {
setIsDropdownOpen(false);
}
};
const removeParticipant = (participantId: string) => {
onSelectionChange(selectedParticipants.filter((p) => p.id !== participantId));
setIsDropdownOpen(false);
inputRef.current?.blur();
};
const getInitials = (name: string) => {
@@ -45,38 +87,49 @@ export const ParticipantSelector = ({
};
return (
<div className="space-y-4">
<div ref={containerRef} className="space-y-4">
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
<Input
ref={inputRef}
placeholder="Search people..."
value={searchQuery}
onChange={(e) => {
setSearchQuery(e.target.value);
setHighlightedIndex(0);
setIsDropdownOpen(true);
}}
onFocus={() => setIsDropdownOpen(true)}
onKeyDown={handleKeyDown}
className="pl-10 h-12 bg-background border-border"
/>
{isDropdownOpen && filteredParticipants.length > 0 && (
<div className="absolute z-10 w-full mt-2 bg-popover border border-border rounded-lg shadow-popover animate-scale-in overflow-hidden">
{filteredParticipants.map((participant) => (
{filteredParticipants.map((participant, index) => (
<button
key={participant.id}
onClick={() => addParticipant(participant)}
className="w-full px-4 py-3 flex items-center gap-3 hover:bg-accent transition-colors text-left"
onMouseEnter={() => setHighlightedIndex(index)}
className={cn(
"w-full px-4 py-3 flex items-center gap-3 hover:bg-accent transition-colors text-left",
index === highlightedIndex && "bg-accent"
)}
>
<div className="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-xs font-medium text-primary">
<div
className="w-8 h-8 rounded-full flex items-center justify-center text-xs font-medium text-white"
style={{ backgroundColor: getAvatarColor(participant.name) }}
>
{getInitials(participant.name)}
</div>
<div>
<div className="font-medium text-foreground">{participant.name}</div>
<div className="text-xs text-muted-foreground">{participant.email}</div>
</div>
{!participant.connected && (
<span className="ml-auto text-xs text-muted-foreground bg-muted px-2 py-0.5 rounded">
Not connected
{!participant.icsLink && (
<span className="ml-auto text-xs text-amber-600 flex items-center gap-1">
<AlertCircle className="w-3 h-3" />
No calendar
</span>
)}
</button>
@@ -96,10 +149,16 @@ export const ParticipantSelector = ({
)}
style={{ animationDelay: `${index * 50}ms` }}
>
<div className="w-6 h-6 rounded-full bg-primary/20 flex items-center justify-center text-xs font-medium">
<div
className="w-6 h-6 rounded-full flex items-center justify-center text-xs font-medium text-white"
style={{ backgroundColor: getAvatarColor(participant.name) }}
>
{getInitials(participant.name)}
</div>
<span className="font-medium">{participant.name.split(' ')[0]}</span>
{!participant.icsLink && (
<AlertCircle className="w-3 h-3 text-amber-600" title="No calendar linked" />
)}
<button
onClick={() => removeParticipant(participant.id)}
className="w-5 h-5 rounded-full hover:bg-primary/20 flex items-center justify-center transition-colors"

View File

@@ -1,5 +1,6 @@
import { useState } from 'react';
import { TimeSlot, Participant } from '@/types/calendar';
import { scheduleMeeting } from '@/api/client';
import {
Dialog,
DialogContent,
@@ -11,7 +12,7 @@ import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { toast } from '@/hooks/use-toast';
import { Calendar, Clock, Users, Send } from 'lucide-react';
import { Calendar, Clock, Users, Send, AlertCircle } from 'lucide-react';
interface ScheduleModalProps {
isOpen: boolean;
@@ -34,7 +35,23 @@ export const ScheduleModal = ({
return `${hour.toString().padStart(2, '0')}:00`;
};
const handleSubmit = () => {
const formatDate = (dateStr: string) => {
const date = new Date(dateStr + 'T00:00:00');
return date.toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric' });
};
const isTooSoon = () => {
if (!slot) return false;
// Use UTC to match backend timezone
const startDateTime = new Date(`${slot.day}T${formatHour(slot.hour)}:00Z`);
const now = new Date();
const twoHoursFromNow = new Date(now.getTime() + 2 * 60 * 60 * 1000);
return startDateTime < twoHoursFromNow;
};
const tooSoon = isTooSoon();
const handleSubmit = async () => {
if (!title.trim()) {
toast({
title: "Please enter a meeting title",
@@ -43,19 +60,41 @@ export const ScheduleModal = ({
return;
}
if (!slot) return;
setIsSubmitting(true);
// Simulate API call
setTimeout(() => {
setIsSubmitting(false);
try {
// Calculate start and end times
// slot.day is YYYY-MM-DD
const startDateTime = new Date(`${slot.day}T${formatHour(slot.hour)}:00Z`);
const endDateTime = new Date(`${slot.day}T${formatHour(slot.hour + 1)}:00Z`);
await scheduleMeeting(
participants.map(p => p.id),
title,
notes,
startDateTime.toISOString(),
endDateTime.toISOString()
);
toast({
title: "Meeting scheduled",
description: "Invitations sent to all participants",
description: "Invitations sent via Email and Zulip",
});
setTitle('');
setNotes('');
onClose();
}, 1000);
} catch (error) {
toast({
title: "Scheduling failed",
description: error instanceof Error ? error.message : "Unknown error",
variant: "destructive",
});
} finally {
setIsSubmitting(false);
}
};
if (!slot) return null;
@@ -72,7 +111,7 @@ export const ScheduleModal = ({
<div className="bg-accent/50 rounded-lg p-4 space-y-3">
<div className="flex items-center gap-3 text-sm">
<Calendar className="w-4 h-4 text-primary" />
<span className="font-medium">{slot.day}</span>
<span className="font-medium">{formatDate(slot.day)}</span>
</div>
<div className="flex items-center gap-3 text-sm">
<Clock className="w-4 h-4 text-primary" />
@@ -109,12 +148,20 @@ export const ScheduleModal = ({
</div>
</div>
{/* Lead Time Warning */}
{tooSoon && (
<div className="flex items-center gap-2 p-3 bg-destructive/10 border border-destructive/20 rounded-lg text-sm text-destructive">
<AlertCircle className="w-4 h-4 flex-shrink-0" />
<span>Meetings must be scheduled at least 2 hours in advance</span>
</div>
)}
{/* Actions */}
<Button
variant="schedule"
className="w-full h-12"
onClick={handleSubmit}
disabled={isSubmitting}
disabled={isSubmitting || tooSoon}
>
{isSubmitting ? (
<span className="animate-pulse">Sending...</span>

View File

@@ -0,0 +1,217 @@
import { useState, useEffect, useRef } from 'react';
import { Input } from '@/components/ui/input';
import { Search, Globe, ChevronDown } from 'lucide-react';
import { cn } from '@/lib/utils';
interface TimezoneSelectorProps {
value: string;
onChange: (timezone: string) => void;
className?: string;
}
// Get all IANA timezones
const getAllTimezones = (): string[] => {
try {
return Intl.supportedValuesOf('timeZone');
} catch {
// Fallback for older browsers
return [
'UTC',
'America/New_York',
'America/Chicago',
'America/Denver',
'America/Los_Angeles',
'America/Toronto',
'America/Vancouver',
'Europe/London',
'Europe/Paris',
'Europe/Berlin',
'Asia/Tokyo',
'Asia/Shanghai',
'Asia/Singapore',
'Australia/Sydney',
'Pacific/Auckland',
];
}
};
// Get UTC offset for a timezone
const getTimezoneOffset = (timezone: string): string => {
try {
const now = new Date();
const formatter = new Intl.DateTimeFormat('en-US', {
timeZone: timezone,
timeZoneName: 'shortOffset',
});
const parts = formatter.formatToParts(now);
const offsetPart = parts.find((p) => p.type === 'timeZoneName');
return offsetPart?.value || '';
} catch {
return '';
}
};
// Get current time in a timezone
const getCurrentTimeInTimezone = (timezone: string): string => {
try {
return new Intl.DateTimeFormat('en-US', {
timeZone: timezone,
hour: 'numeric',
minute: '2-digit',
hour12: true,
}).format(new Date());
} catch {
return '';
}
};
// Format timezone for display (e.g., "America/New_York" -> "New York")
const formatTimezoneLabel = (timezone: string): string => {
const parts = timezone.split('/');
const city = parts[parts.length - 1];
return city.replace(/_/g, ' ');
};
const ALL_TIMEZONES = getAllTimezones();
export const TimezoneSelector = ({
value,
onChange,
className,
}: TimezoneSelectorProps) => {
const [searchQuery, setSearchQuery] = useState('');
const [isDropdownOpen, setIsDropdownOpen] = useState(false);
const [hoveredTimezone, setHoveredTimezone] = useState<string | null>(null);
const containerRef = useRef<HTMLDivElement>(null);
// Close dropdown when clicking outside
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
setIsDropdownOpen(false);
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, []);
const filteredTimezones = ALL_TIMEZONES.filter((tz) => {
const query = searchQuery.toLowerCase();
const tzLower = tz.toLowerCase();
const labelLower = formatTimezoneLabel(tz).toLowerCase();
const offset = getTimezoneOffset(tz).toLowerCase();
return (
tzLower.includes(query) ||
labelLower.includes(query) ||
offset.includes(query)
);
});
const selectTimezone = (timezone: string) => {
onChange(timezone);
setSearchQuery('');
setIsDropdownOpen(false);
};
const selectedOffset = getTimezoneOffset(value);
const selectedLabel = formatTimezoneLabel(value);
return (
<div ref={containerRef} className={cn('relative', className)}>
<button
onClick={() => setIsDropdownOpen(!isDropdownOpen)}
className={cn(
'flex items-center gap-2 px-3 py-1.5 rounded-lg text-sm',
'bg-muted hover:bg-accent transition-colors',
'border border-transparent hover:border-border'
)}
>
<Globe className="w-4 h-4 text-muted-foreground" />
<span className="text-foreground font-medium">{selectedLabel}</span>
<span className="text-muted-foreground">{selectedOffset}</span>
<ChevronDown className={cn(
'w-4 h-4 text-muted-foreground transition-transform',
isDropdownOpen && 'rotate-180'
)} />
</button>
{isDropdownOpen && (
<div className="absolute z-20 right-0 mt-2 w-80 bg-popover border border-border rounded-lg shadow-popover animate-scale-in overflow-hidden">
<div className="p-2 border-b border-border">
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
<Input
placeholder="Search timezone..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-10 h-9 bg-background border-border"
autoFocus
/>
</div>
</div>
<div className="max-h-64 overflow-y-auto">
{filteredTimezones.length === 0 ? (
<div className="px-4 py-3 text-sm text-muted-foreground text-center">
No timezones found
</div>
) : (
filteredTimezones.slice(0, 50).map((timezone) => {
const isSelected = timezone === value;
const offset = getTimezoneOffset(timezone);
const label = formatTimezoneLabel(timezone);
const isHovered = hoveredTimezone === timezone;
return (
<button
key={timezone}
onClick={() => selectTimezone(timezone)}
onMouseEnter={() => setHoveredTimezone(timezone)}
onMouseLeave={() => setHoveredTimezone(null)}
className={cn(
'w-full px-4 py-2.5 flex items-center justify-between text-left transition-colors',
isSelected ? 'bg-primary/10 text-primary' : 'hover:bg-accent'
)}
>
<div className="flex items-center gap-3">
<span className={cn(
'text-xs font-mono w-16',
isSelected ? 'text-primary' : 'text-muted-foreground'
)}>
{offset}
</span>
<div>
<div className={cn(
'font-medium',
isSelected ? 'text-primary' : 'text-foreground'
)}>
{label}
</div>
<div className="text-xs text-muted-foreground">
{timezone}
</div>
</div>
</div>
{isHovered && (
<span className="text-xs text-muted-foreground animate-fade-in">
{getCurrentTimeInTimezone(timezone)}
</span>
)}
</button>
);
})
)}
</div>
{filteredTimezones.length > 50 && (
<div className="px-4 py-2 text-xs text-muted-foreground text-center border-t border-border">
Showing 50 of {filteredTimezones.length} results
</div>
)}
</div>
)}
</div>
);
};

View File

@@ -1,104 +1,119 @@
@import url('https://fonts.googleapis.com/css2?family=DM+Sans:ital,opsz,wght@0,9..40,100..1000;1,9..40,100..1000&display=swap');
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
@font-face {
font-family: 'Inter';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url('/fonts/inter-400.woff2') format('woff2');
}
@font-face {
font-family: 'Inter';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url('/fonts/inter-500.woff2') format('woff2');
}
@font-face {
font-family: 'Inter';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url('/fonts/inter-600.woff2') format('woff2');
}
@font-face {
font-family: 'Source Serif Pro';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url('/fonts/source-serif-pro-400.woff2') format('woff2');
}
@font-face {
font-family: 'Source Serif Pro';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url('/fonts/source-serif-pro-600.woff2') format('woff2');
}
@font-face {
font-family: 'Source Serif Pro';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url('/fonts/source-serif-pro-700.woff2') format('woff2');
}
:root {
--background: 210 20% 98%;
--foreground: 222 47% 11%;
/* Greyhaven Colors converted to HSL */
/* Light Mode Defaults */
--background: 60 9% 93%; /* #F0F0EC */
--foreground: 60 5% 8%; /* #161614 */
--card: 0 0% 100%;
--card-foreground: 222 47% 11%;
--card: 60 9% 97%; /* #F9F9F7 */
--card-foreground: 60 5% 8%;
--popover: 0 0% 100%;
--popover-foreground: 222 47% 11%;
--popover: 60 9% 97%;
--popover-foreground: 60 5% 8%;
--primary: 173 58% 39%;
--primary-foreground: 0 0% 100%;
--primary: 18 68% 51%; /* #D95E2A (RGB 217 94 42) */
--primary-foreground: 60 9% 97%;
--secondary: 210 20% 96%;
--secondary-foreground: 222 47% 11%;
--secondary: 60 9% 93%;
--secondary-foreground: 60 3% 18%; /* #2F2F2C */
--muted: 210 20% 94%;
--muted-foreground: 215 16% 47%;
--muted: 60 5% 84%; /* Darker than background for contrast */
--muted-foreground: 60 2% 34%; /* #575753 */
--accent: 173 58% 94%;
--accent-foreground: 173 58% 25%;
--accent: 60 9% 85%; /* #DDD7 */
--accent-foreground: 60 5% 8%;
--destructive: 0 84% 60%;
--destructive-foreground: 0 0% 100%;
--destructive: 0 57% 45%; /* #B43232 (RGB 180 50 50) */
--destructive-foreground: 60 9% 97%;
--border: 214 32% 91%;
--input: 214 32% 91%;
--ring: 173 58% 39%;
--border: 60 5% 77%; /* #C4C4BD (RGB 196 196 189) */
--input: 60 5% 77%;
--ring: 18 68% 51%;
--radius: 0.75rem;
--radius: 0.375rem;
/* Custom colors for heatmap */
--availability-full: 142 71% 45%;
--availability-partial: 48 96% 53%;
--availability-none: 215 16% 85%;
/* Custom colors for heatmap - Updated to match system tags */
--availability-full: 142 76% 36%; /* Tag Green */
--availability-partial: 25 80% 65%; /* Tag Orange */
--availability-none: 0 0% 80%; /* Grey */
/* Tag Colors */
--tag-orange: 25 80% 65%;
--tag-green: 142 76% 36%;
--tag-blue: 210 100% 60%;
--tag-purple: 270 70% 65%;
--tag-brown: 30 40% 50%;
/* Typography */
--font-serif: 'Source Serif Pro', Georgia, 'Times New Roman', serif;
--font-display: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
/* Shadows */
--shadow-sm: 0 1px 2px 0 hsl(222 47% 11% / 0.05);
--shadow-md: 0 4px 6px -1px hsl(222 47% 11% / 0.1), 0 2px 4px -2px hsl(222 47% 11% / 0.1);
--shadow-lg: 0 10px 15px -3px hsl(222 47% 11% / 0.1), 0 4px 6px -4px hsl(222 47% 11% / 0.1);
--shadow-xl: 0 20px 25px -5px hsl(222 47% 11% / 0.1), 0 8px 10px -6px hsl(222 47% 11% / 0.1);
--shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
--shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1);
--shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1);
--shadow-xl: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -6px rgba(0, 0, 0, 0.1);
--sidebar-background: 0 0% 98%;
--sidebar-foreground: 240 5.3% 26.1%;
--sidebar-primary: 240 5.9% 10%;
--sidebar-primary-foreground: 0 0% 98%;
--sidebar-accent: 240 4.8% 95.9%;
--sidebar-accent-foreground: 240 5.9% 10%;
--sidebar-border: 220 13% 91%;
--sidebar-ring: 217.2 91.2% 59.8%;
--sidebar-background: 60 9% 93%;
--sidebar-foreground: 60 5% 8%;
--sidebar-primary: 18 68% 51%;
--sidebar-primary-foreground: 60 9% 97%;
--sidebar-accent: 60 9% 85%;
--sidebar-accent-foreground: 60 5% 8%;
--sidebar-border: 60 5% 77%;
--sidebar-ring: 18 68% 51%;
}
.dark {
--background: 222 47% 6%;
--foreground: 210 20% 98%;
--card: 222 47% 8%;
--card-foreground: 210 20% 98%;
--popover: 222 47% 8%;
--popover-foreground: 210 20% 98%;
--primary: 173 58% 45%;
--primary-foreground: 0 0% 100%;
--secondary: 222 47% 14%;
--secondary-foreground: 210 20% 98%;
--muted: 222 47% 14%;
--muted-foreground: 215 16% 65%;
--accent: 173 58% 15%;
--accent-foreground: 173 58% 75%;
--destructive: 0 62% 30%;
--destructive-foreground: 210 20% 98%;
--border: 222 47% 17%;
--input: 222 47% 17%;
--ring: 173 58% 45%;
--availability-full: 142 71% 35%;
--availability-partial: 48 96% 40%;
--availability-none: 222 47% 20%;
--sidebar-background: 240 5.9% 10%;
--sidebar-foreground: 240 4.8% 95.9%;
--sidebar-primary: 224.3 76.3% 48%;
--sidebar-primary-foreground: 0 0% 100%;
--sidebar-accent: 240 3.7% 15.9%;
--sidebar-accent-foreground: 240 4.8% 95.9%;
--sidebar-border: 240 3.7% 15.9%;
--sidebar-ring: 217.2 91.2% 59.8%;
}
/* Dark mode intentionally removed/reset to match light mode system for now,
or you can define a proper dark mode if required.
Keeping it simple as per previous apps. */
}
@layer base {
@@ -107,8 +122,12 @@
}
body {
@apply bg-background text-foreground font-sans antialiased;
font-family: 'DM Sans', sans-serif;
@apply bg-background text-foreground antialiased;
font-family: var(--font-display);
}
h1, h2, h3, h4, h5, h6 {
font-family: var(--font-serif);
}
}

View File

@@ -4,3 +4,18 @@ import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
export function getAvatarColor(name?: string): string {
const colors = [
'hsl(var(--tag-green))',
'hsl(var(--tag-blue))',
'hsl(var(--tag-orange))',
'hsl(var(--tag-purple))',
'hsl(var(--tag-brown))',
];
if (!name) return colors[0];
const hash = name.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0);
return colors[hash % colors.length];
}

View File

@@ -1,4 +1,5 @@
import { useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { Header } from '@/components/Header';
import { ParticipantSelector } from '@/components/ParticipantSelector';
import { ParticipantManager } from '@/components/ParticipantManager';
@@ -19,6 +20,7 @@ import { useToast } from '@/hooks/use-toast';
import {
fetchParticipants,
createParticipant,
updateParticipant,
deleteParticipant,
fetchAvailability,
syncCalendars,
@@ -40,22 +42,41 @@ function apiToParticipant(p: ParticipantAPI): Participant {
id: p.id,
name: p.name,
email: p.email,
timezone: p.timezone,
icsLink: p.ics_url,
connected: true,
};
}
const Index = () => {
interface IndexProps {
defaultTab?: string;
}
const Index = ({ defaultTab = 'schedule' }: IndexProps) => {
const navigate = useNavigate();
const location = useLocation();
const [activeTab, setActiveTab] = useState(defaultTab);
const [participants, setParticipants] = useState<Participant[]>([]);
const [selectedParticipants, setSelectedParticipants] = useState<Participant[]>([]);
const [availabilitySlots, setAvailabilitySlots] = useState<TimeSlot[]>([]);
const [selectedSlot, setSelectedSlot] = useState<TimeSlot | null>(null);
const [isModalOpen, setIsModalOpen] = useState(false);
const [settings, setSettings] = useState<SettingsState>(defaultSettings);
const [weekOffset, setWeekOffset] = useState(0);
const [isLoading, setIsLoading] = useState(false);
const [isSyncing, setIsSyncing] = useState(false);
const { toast } = useToast();
useEffect(() => {
// Sync internal state if prop changes (e.g. browser back button)
setActiveTab(defaultTab);
}, [defaultTab]);
const handleTabChange = (value: string) => {
setActiveTab(value);
navigate(`/${value}`);
};
useEffect(() => {
const stored = localStorage.getItem(SETTINGS_KEY);
if (stored) {
@@ -81,7 +102,7 @@ const Index = () => {
} else {
setAvailabilitySlots([]);
}
}, [selectedParticipants]);
}, [selectedParticipants, weekOffset]);
const loadParticipants = async () => {
try {
@@ -100,7 +121,7 @@ const Index = () => {
setIsLoading(true);
try {
const ids = selectedParticipants.map((p) => p.id);
const slots = await fetchAvailability(ids);
const slots = await fetchAvailability(ids, weekOffset);
setAvailabilitySlots(slots);
} catch (error) {
toast({
@@ -113,12 +134,13 @@ const Index = () => {
}
};
const handleAddParticipant = async (data: { name: string; email: string; icsLink: string }) => {
const handleAddParticipant = async (data: { name: string; email: string; timezone: string; icsLink: string }) => {
try {
const created = await createParticipant({
name: data.name,
email: data.email,
ics_url: data.icsLink,
timezone: data.timezone,
ics_url: data.icsLink || undefined,
});
setParticipants((prev) => [...prev, apiToParticipant(created)]);
toast({
@@ -151,6 +173,16 @@ const Index = () => {
}
};
const handleUpdateParticipant = async (id: string, data: { timezone?: string; ics_url?: string }) => {
const updated = await updateParticipant(id, data);
setParticipants((prev) =>
prev.map((p) => (p.id === id ? apiToParticipant(updated) : p))
);
setSelectedParticipants((prev) =>
prev.map((p) => (p.id === id ? apiToParticipant(updated) : p))
);
};
const handleSyncCalendars = async () => {
setIsSyncing(true);
try {
@@ -183,22 +215,28 @@ const Index = () => {
<Header />
<main className="container max-w-5xl mx-auto px-4 py-8">
<Tabs defaultValue="schedule" className="space-y-6">
<TabsList className="grid w-full max-w-md mx-auto grid-cols-2">
<TabsTrigger value="participants" className="flex items-center gap-2">
<Tabs value={activeTab} onValueChange={handleTabChange} className="space-y-6">
<TabsList className="grid w-full max-w-md mx-auto grid-cols-2 bg-muted p-1 rounded-xl">
<TabsTrigger
value="participants"
className="flex items-center gap-2 rounded-lg data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm transition-all"
>
<Users className="w-4 h-4" />
Participants
People
</TabsTrigger>
<TabsTrigger value="schedule" className="flex items-center gap-2">
<TabsTrigger
value="schedule"
className="flex items-center gap-2 rounded-lg data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm transition-all"
>
<CalendarDays className="w-4 h-4" />
Schedule
</TabsTrigger>
</TabsList>
<TabsContent value="participants" className="animate-fade-in">
<TabsContent value="participants" className="animate-fade-in focus-visible:outline-none">
<div className="text-center mb-6">
<h2 className="text-3xl font-bold text-foreground mb-2">
Manage Participants
Manage People
</h2>
<p className="text-muted-foreground">
Add team members with their calendar ICS links
@@ -209,6 +247,7 @@ const Index = () => {
participants={participants}
onAddParticipant={handleAddParticipant}
onRemoveParticipant={handleRemoveParticipant}
onUpdateParticipant={handleUpdateParticipant}
/>
</TabsContent>
@@ -265,7 +304,7 @@ const Index = () => {
<Users className="w-12 h-12 mx-auto mb-4 text-muted-foreground opacity-50" />
<h3 className="text-lg font-medium text-foreground mb-2">No participants yet</h3>
<p className="text-muted-foreground">
Add participants in the Participants tab to start scheduling.
Add people in the People tab to start scheduling.
</p>
</div>
) : (
@@ -287,6 +326,8 @@ const Index = () => {
onSlotSelect={handleSlotSelect}
showPartialAvailability={settings.showPartialAvailability}
isLoading={isLoading}
weekOffset={weekOffset}
onWeekOffsetChange={setWeekOffset}
/>
</>
)}

View File

@@ -2,6 +2,7 @@ export interface Participant {
id: string;
name: string;
email: string;
timezone: string;
icsLink?: string;
avatar?: string;
connected: boolean;
@@ -10,6 +11,7 @@ export interface Participant {
export interface TimeSlot {
day: string;
hour: number;
start_time: string;
availability: 'full' | 'partial' | 'none';
availableParticipants: string[];
}

View File

@@ -14,7 +14,8 @@ export default {
},
extend: {
fontFamily: {
sans: ['DM Sans', 'system-ui', 'sans-serif'],
sans: ['Inter', 'system-ui', 'sans-serif'],
serif: ['Source Serif Pro', 'Georgia', 'serif'],
},
colors: {
border: "hsl(var(--border))",