Compare commits

..

3 Commits

Author SHA1 Message Date
d45929ddc0 Fix off-day med reminders and add medication editing
Scheduler: check_nagging() now calls _is_med_due_today() before creating
on-demand schedules or processing existing ones — prevents nagging
for specific_days / every_n_days meds on days they are not scheduled.

Web client: add Edit button (pencil icon) on each medication card linking
to /dashboard/medications/[id]/edit — new page pre-populates the full
form (name, dosage, unit, frequency, times, days, interval, notes)
and submits PUT /api/medications/:id on save.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-19 16:49:12 -06:00
bebc609091 Add one-off tasks/appointments feature
- DB: tasks table with scheduled_datetime, reminder_minutes_before, advance_notified, status
- API: CRUD routes GET/POST /api/tasks, PATCH/DELETE /api/tasks/<id>
- Scheduler: check_task_reminders() fires advance + at-time notifications, tracks advance_notified to prevent double-fire
- Bot: handle_task() with add/list/done/cancel/delete actions + datetime resolution helper
- AI: task interaction type + examples added to command_parser
- Web: task list page with overdue/notified color coding + new task form with datetime-local picker
- Nav: replaced Templates with Tasks in bottom nav

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-19 16:43:42 -06:00
2951382c51 Fix auth persistence: web client session timeout + bot cache loss
Web client: trustDevice now defaults to true so a refresh token is always
issued on login, preventing deauth after the 1-hour access token expiry.
Users can still uncheck the box on shared devices.

Bot: cache file path is now env-configurable (BOT_CACHE_FILE) and
defaults to /app/cache/user_cache.pkl. Docker Compose mounts a named
volume at /app/cache so the session cache survives container restarts.
saveCache() now creates the directory if it doesn't exist.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-19 16:32:07 -06:00
15 changed files with 1118 additions and 14 deletions

File diff suppressed because one or more lines are too long

View File

@@ -24,6 +24,7 @@ import api.routes.victories as victories_routes
import api.routes.adaptive_meds as adaptive_meds_routes
import api.routes.snitch as snitch_routes
import api.routes.ai as ai_routes
import api.routes.tasks as tasks_routes
app = flask.Flask(__name__)
CORS(app)
@@ -43,6 +44,7 @@ ROUTE_MODULES = [
adaptive_meds_routes,
snitch_routes,
ai_routes,
tasks_routes,
]

109
api/routes/tasks.py Normal file
View File

@@ -0,0 +1,109 @@
"""
api/routes/tasks.py - One-off scheduled task CRUD
"""
import uuid
import flask
import jwt
import os
from datetime import datetime
import core.postgres as postgres
JWT_SECRET = os.getenv("JWT_SECRET")
def _get_user_uuid(request):
"""Extract and validate user UUID from JWT token."""
auth_header = request.headers.get("Authorization", "")
if not auth_header.startswith("Bearer "):
return None
token = auth_header[7:]
try:
payload = jwt.decode(token, JWT_SECRET, algorithms=["HS256"])
return payload.get("sub")
except (jwt.ExpiredSignatureError, jwt.InvalidTokenError):
return None
def register(app):
@app.route("/api/tasks", methods=["GET"])
def get_tasks():
user_uuid = _get_user_uuid(flask.request)
if not user_uuid:
return flask.jsonify({"error": "unauthorized"}), 401
status_filter = flask.request.args.get("status", "pending")
if status_filter == "all":
tasks = postgres.select(
"tasks",
where={"user_uuid": user_uuid},
order_by="scheduled_datetime ASC",
)
else:
tasks = postgres.select(
"tasks",
where={"user_uuid": user_uuid, "status": status_filter},
order_by="scheduled_datetime ASC",
)
# Serialize datetimes for JSON
for t in tasks:
for key in ("scheduled_datetime", "created_at", "updated_at"):
if key in t and hasattr(t[key], "isoformat"):
t[key] = t[key].isoformat()
return flask.jsonify(tasks), 200
@app.route("/api/tasks", methods=["POST"])
def create_task():
user_uuid = _get_user_uuid(flask.request)
if not user_uuid:
return flask.jsonify({"error": "unauthorized"}), 401
data = flask.request.get_json()
if not data:
return flask.jsonify({"error": "missing body"}), 400
title = data.get("title", "").strip()
scheduled_datetime = data.get("scheduled_datetime", "").strip()
if not title:
return flask.jsonify({"error": "title is required"}), 400
if not scheduled_datetime:
return flask.jsonify({"error": "scheduled_datetime is required"}), 400
task_id = str(uuid.uuid4())
task = {
"id": task_id,
"user_uuid": user_uuid,
"title": title,
"description": data.get("description") or None,
"scheduled_datetime": scheduled_datetime,
"reminder_minutes_before": int(data.get("reminder_minutes_before", 15)),
"status": "pending",
}
postgres.insert("tasks", task)
return flask.jsonify(task), 201
@app.route("/api/tasks/<task_id>", methods=["PATCH"])
def update_task(task_id):
user_uuid = _get_user_uuid(flask.request)
if not user_uuid:
return flask.jsonify({"error": "unauthorized"}), 401
task = postgres.select_one("tasks", {"id": task_id, "user_uuid": user_uuid})
if not task:
return flask.jsonify({"error": "not found"}), 404
data = flask.request.get_json() or {}
updates = {}
for field in ["title", "description", "scheduled_datetime", "reminder_minutes_before", "status"]:
if field in data:
updates[field] = data[field]
updates["updated_at"] = datetime.utcnow().isoformat()
postgres.update("tasks", updates, {"id": task_id})
return flask.jsonify({**{k: (v.isoformat() if hasattr(v, "isoformat") else v) for k, v in task.items()}, **updates}), 200
@app.route("/api/tasks/<task_id>", methods=["DELETE"])
def delete_task(task_id):
user_uuid = _get_user_uuid(flask.request)
if not user_uuid:
return flask.jsonify({"error": "unauthorized"}), 401
task = postgres.select_one("tasks", {"id": task_id, "user_uuid": user_uuid})
if not task:
return flask.jsonify({"error": "not found"}), 404
postgres.delete("tasks", {"id": task_id})
return flask.jsonify({"success": True}), 200

View File

@@ -26,6 +26,7 @@ import ai.parser as ai_parser
import bot.commands.routines # noqa: F401 - registers handler
import bot.commands.medications # noqa: F401 - registers handler
import bot.commands.knowledge # noqa: F401 - registers handler
import bot.commands.tasks # noqa: F401 - registers handler
DISCORD_BOT_TOKEN = os.getenv("DISCORD_BOT_TOKEN")
API_URL = os.getenv("API_URL", "http://app:5000")
@@ -34,7 +35,7 @@ user_sessions = {}
login_state = {}
message_history = {}
user_cache = {}
CACHE_FILE = "/app/user_cache.pkl"
CACHE_FILE = os.getenv("BOT_CACHE_FILE", "/app/cache/user_cache.pkl")
intents = discord.Intents.default()
intents.message_content = True
@@ -227,6 +228,7 @@ def loadCache():
def saveCache():
try:
os.makedirs(os.path.dirname(CACHE_FILE), exist_ok=True)
with open(CACHE_FILE, "wb") as f:
pickle.dump(user_cache, f)
except Exception as e:

242
bot/commands/tasks.py Normal file
View File

@@ -0,0 +1,242 @@
"""
Tasks command handler - bot-side hooks for one-off tasks/appointments
"""
from datetime import datetime, timedelta
from bot.command_registry import register_module
import ai.parser as ai_parser
def _resolve_datetime(dt_str, user_now):
"""Resolve a natural language date string to an ISO datetime string.
Handles: ISO strings, 'today', 'tomorrow', day names, plus 'HH:MM' time."""
if not dt_str:
return None
dt_str = dt_str.lower().strip()
# Try direct ISO parse first
for fmt in ("%Y-%m-%dT%H:%M", "%Y-%m-%d %H:%M", "%Y-%m-%d"):
try:
return datetime.strptime(dt_str, fmt).isoformat(timespec="minutes")
except ValueError:
pass
# Split into date word + time word
time_part = None
date_word = dt_str
# Try to extract HH:MM from the end
parts = dt_str.rsplit(" ", 1)
if len(parts) == 2:
possible_time = parts[1]
if ":" in possible_time:
try:
h, m = [int(x) for x in possible_time.split(":")]
time_part = (h, m)
date_word = parts[0]
except ValueError:
pass
else:
# Might be just a bare hour like "14"
try:
h = int(possible_time)
if 0 <= h <= 23:
time_part = (h, 0)
date_word = parts[0]
except ValueError:
pass
# Resolve the date part
target = user_now.date()
if "tomorrow" in date_word:
target = target + timedelta(days=1)
elif "today" in date_word or not date_word:
pass
else:
day_map = {
"monday": 0, "tuesday": 1, "wednesday": 2,
"thursday": 3, "friday": 4, "saturday": 5, "sunday": 6,
}
for name, num in day_map.items():
if name in date_word:
days_ahead = (num - target.weekday()) % 7
if days_ahead == 0:
days_ahead = 7 # next occurrence
target = target + timedelta(days=days_ahead)
break
if time_part:
return datetime(
target.year, target.month, target.day, time_part[0], time_part[1]
).isoformat(timespec="minutes")
return datetime(target.year, target.month, target.day, 9, 0).isoformat(timespec="minutes")
def _find_task_by_title(token, title):
"""Find a pending task by fuzzy title match. Returns task dict or None."""
resp, status = api_request("get", "/api/tasks", token)
if status != 200:
return None
tasks = resp if isinstance(resp, list) else []
title_lower = title.lower()
# Exact match first
for t in tasks:
if t.get("title", "").lower() == title_lower:
return t
# Partial match
for t in tasks:
if title_lower in t.get("title", "").lower() or t.get("title", "").lower() in title_lower:
return t
return None
def _format_datetime(dt_str):
"""Format ISO datetime string for display."""
try:
dt = datetime.fromisoformat(str(dt_str))
return dt.strftime("%a %b %-d at %-I:%M %p")
except Exception:
return str(dt_str)
async def handle_task(message, session, parsed):
action = parsed.get("action", "unknown")
token = session["token"]
# Get user's current time for datetime resolution
from core import tz as tz_mod
user_uuid = session.get("user_uuid")
try:
user_now = tz_mod.user_now_for(user_uuid)
except Exception:
user_now = datetime.utcnow()
if action == "add":
title = parsed.get("title", "").strip()
dt_str = parsed.get("datetime", "")
reminder_min = parsed.get("reminder_minutes_before", 15)
if not title:
await message.channel.send("What's the title of the task?")
return
resolved_dt = _resolve_datetime(dt_str, user_now) if dt_str else None
if not resolved_dt:
await message.channel.send(
"When is this task? Tell me the date and time (e.g. 'tomorrow at 3pm', 'friday 14:00')."
)
return
task_data = {
"title": title,
"scheduled_datetime": resolved_dt,
"reminder_minutes_before": int(reminder_min),
}
description = parsed.get("description", "")
if description:
task_data["description"] = description
resp, status = api_request("post", "/api/tasks", token, task_data)
if status == 201:
reminder_text = f" (reminder {reminder_min} min before)" if int(reminder_min) > 0 else ""
await message.channel.send(
f"✅ Added **{title}** for {_format_datetime(resolved_dt)}{reminder_text}"
)
else:
await message.channel.send(f"Error: {resp.get('error', 'Failed to create task')}")
elif action == "list":
resp, status = api_request("get", "/api/tasks", token)
if status == 200:
tasks = resp if isinstance(resp, list) else []
if not tasks:
await message.channel.send("No pending tasks. Add one with 'remind me about...'")
else:
lines = []
for t in tasks:
status_emoji = "🔔" if t.get("status") == "notified" else "📋"
lines.append(f"{status_emoji} **{t['title']}** — {_format_datetime(t.get('scheduled_datetime', ''))}")
await message.channel.send("**Your upcoming tasks:**\n" + "\n".join(lines))
else:
await message.channel.send(f"Error: {resp.get('error', 'Failed to fetch tasks')}")
elif action in ("done", "complete"):
title = parsed.get("title", "").strip()
if not title:
await message.channel.send("Which task is done?")
return
task = _find_task_by_title(token, title)
if not task:
await message.channel.send(f"Couldn't find a task matching '{title}'.")
return
resp, status = api_request("patch", f"/api/tasks/{task['id']}", token, {"status": "completed"})
if status == 200:
await message.channel.send(f"✅ Marked **{task['title']}** as done!")
else:
await message.channel.send(f"Error: {resp.get('error', 'Failed to update task')}")
elif action == "cancel":
title = parsed.get("title", "").strip()
if not title:
await message.channel.send("Which task should I cancel?")
return
task = _find_task_by_title(token, title)
if not task:
await message.channel.send(f"Couldn't find a task matching '{title}'.")
return
resp, status = api_request("patch", f"/api/tasks/{task['id']}", token, {"status": "cancelled"})
if status == 200:
await message.channel.send(f"❌ Cancelled **{task['title']}**.")
else:
await message.channel.send(f"Error: {resp.get('error', 'Failed to cancel task')}")
elif action == "delete":
title = parsed.get("title", "").strip()
if not title:
await message.channel.send("Which task should I delete?")
return
task = _find_task_by_title(token, title)
if not task:
await message.channel.send(f"Couldn't find a task matching '{title}'.")
return
resp, status = api_request("delete", f"/api/tasks/{task['id']}", token)
if status == 200:
await message.channel.send(f"🗑️ Deleted **{task['title']}**.")
else:
await message.channel.send(f"Error: {resp.get('error', 'Failed to delete task')}")
else:
await message.channel.send(
f"Unknown action: {action}. Try: add, list, done, cancel."
)
def api_request(method, endpoint, token, data=None):
import requests
import os
API_URL = os.getenv("API_URL", "http://app:5000")
url = f"{API_URL}{endpoint}"
headers = {"Content-Type": "application/json", "Authorization": f"Bearer {token}"}
try:
resp = getattr(requests, method)(url, headers=headers, json=data, timeout=10)
try:
return resp.json(), resp.status_code
except ValueError:
return {}, resp.status_code
except requests.RequestException:
return {"error": "API unavailable"}, 503
def validate_task_json(data):
errors = []
if not isinstance(data, dict):
return ["Response must be a JSON object"]
if "error" in data:
return []
if "action" not in data:
errors.append("Missing required field: action")
return errors
register_module("task", handle_task)
ai_parser.register_validator("task", validate_task_json)

View File

@@ -298,3 +298,19 @@ CREATE INDEX IF NOT EXISTS idx_snitch_contacts_user ON snitch_contacts(user_uuid
-- ── Migrations ──────────────────────────────────────────────
-- Add IANA timezone name to user preferences (run once on existing DBs)
ALTER TABLE user_preferences ADD COLUMN IF NOT EXISTS timezone_name VARCHAR(100);
-- ── Tasks (one-off appointments/reminders) ──────────────────
CREATE TABLE IF NOT EXISTS tasks (
id UUID PRIMARY KEY,
user_uuid UUID REFERENCES users(id) ON DELETE CASCADE,
title VARCHAR(255) NOT NULL,
description TEXT,
scheduled_datetime TIMESTAMP NOT NULL,
reminder_minutes_before INTEGER DEFAULT 15,
advance_notified BOOLEAN DEFAULT FALSE,
status VARCHAR(20) DEFAULT 'pending',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_tasks_user_scheduled ON tasks(user_uuid, scheduled_datetime);
CREATE INDEX IF NOT EXISTS idx_tasks_pending ON tasks(status) WHERE status = 'pending';

View File

@@ -42,6 +42,8 @@ services:
depends_on:
app:
condition: service_started
volumes:
- botcache:/app/cache
client:
build:
@@ -56,3 +58,4 @@ services:
volumes:
pgdata:
botcache:

View File

@@ -317,6 +317,10 @@ def check_nagging():
now = _user_now_for(user_uuid)
today = now.date()
# Skip nagging if medication is not due today
if not _is_med_due_today(med, today):
continue
# Get today's schedules
try:
schedules = postgres.select(
@@ -333,8 +337,10 @@ def check_nagging():
# Table may not exist yet
continue
# If no schedules exist, try to create them
# If no schedules exist, try to create them — but only if med is due today
if not schedules:
if not _is_med_due_today(med, today):
continue
logger.info(f"No schedules found for medication {med_id}, attempting to create")
times = med.get("times", [])
if times:
@@ -515,6 +521,69 @@ def _check_per_user_midnight_schedules():
)
def check_task_reminders():
"""Check one-off tasks for advance and at-time reminders."""
from datetime import timedelta
try:
tasks = postgres.select("tasks", where={"status": "pending"})
if not tasks:
return
user_tasks = {}
for task in tasks:
uid = task.get("user_uuid")
user_tasks.setdefault(uid, []).append(task)
for user_uuid, task_list in user_tasks.items():
now = _user_now_for(user_uuid)
current_hhmm = now.strftime("%H:%M")
current_date = now.date()
user_settings = None # lazy-load once per user
for task in task_list:
raw_dt = task.get("scheduled_datetime")
if not raw_dt:
continue
sched_dt = (
raw_dt
if isinstance(raw_dt, datetime)
else datetime.fromisoformat(str(raw_dt))
)
sched_date = sched_dt.date()
sched_hhmm = sched_dt.strftime("%H:%M")
reminder_min = task.get("reminder_minutes_before") or 0
# Advance reminder
if reminder_min > 0 and not task.get("advance_notified"):
adv_dt = sched_dt - timedelta(minutes=reminder_min)
if adv_dt.date() == current_date and adv_dt.strftime("%H:%M") == current_hhmm:
if user_settings is None:
user_settings = notifications.getNotificationSettings(user_uuid)
if user_settings:
msg = f"⏰ In {reminder_min} min: {task['title']}"
if task.get("description"):
msg += f"{task['description']}"
notifications._sendToEnabledChannels(user_settings, msg, user_uuid=user_uuid)
postgres.update("tasks", {"advance_notified": True}, {"id": task["id"]})
# At-time reminder
if sched_date == current_date and sched_hhmm == current_hhmm:
if user_settings is None:
user_settings = notifications.getNotificationSettings(user_uuid)
if user_settings:
msg = f"📋 Now: {task['title']}"
if task.get("description"):
msg += f"\n{task['description']}"
notifications._sendToEnabledChannels(user_settings, msg, user_uuid=user_uuid)
postgres.update(
"tasks",
{"status": "notified", "updated_at": datetime.utcnow().isoformat()},
{"id": task["id"]},
)
except Exception as e:
logger.error(f"Error checking task reminders: {e}")
def poll_callback():
"""Called every POLL_INTERVAL seconds."""
# Create daily schedules per-user at their local midnight
@@ -537,6 +606,7 @@ def poll_callback():
# Original checks
check_routine_reminders()
check_refills()
check_task_reminders()
def daemon_loop():

View File

@@ -14,8 +14,7 @@ import {
PillIcon,
SettingsIcon,
LogOutIcon,
CopyIcon,
ClockIcon,
SunIcon,
MoonIcon,
} from '@/components/ui/Icons';
@@ -24,7 +23,7 @@ import Link from 'next/link';
const navItems = [
{ href: '/dashboard', label: 'Today', icon: HomeIcon },
{ href: '/dashboard/routines', label: 'Routines', icon: ListIcon },
{ href: '/dashboard/templates', label: 'Templates', icon: CopyIcon },
{ href: '/dashboard/tasks', label: 'Tasks', icon: ClockIcon },
{ href: '/dashboard/history', label: 'History', icon: CalendarIcon },
{ href: '/dashboard/stats', label: 'Stats', icon: BarChartIcon },
{ href: '/dashboard/medications', label: 'Meds', icon: PillIcon },

View File

@@ -0,0 +1,262 @@
'use client';
import { useEffect, useState } from 'react';
import { useRouter, useParams } from 'next/navigation';
import api from '@/lib/api';
import { ArrowLeftIcon } from '@/components/ui/Icons';
const DAY_OPTIONS = [
{ value: 'mon', label: 'Mon' },
{ value: 'tue', label: 'Tue' },
{ value: 'wed', label: 'Wed' },
{ value: 'thu', label: 'Thu' },
{ value: 'fri', label: 'Fri' },
{ value: 'sat', label: 'Sat' },
{ value: 'sun', label: 'Sun' },
];
export default function EditMedicationPage() {
const router = useRouter();
const params = useParams();
const medId = params.id as string;
const [isLoadingMed, setIsLoadingMed] = useState(true);
const [name, setName] = useState('');
const [dosage, setDosage] = useState('');
const [unit, setUnit] = useState('mg');
const [frequency, setFrequency] = useState('daily');
const [times, setTimes] = useState<string[]>(['08:00']);
const [daysOfWeek, setDaysOfWeek] = useState<string[]>([]);
const [intervalDays, setIntervalDays] = useState(7);
const [startDate, setStartDate] = useState(new Date().toISOString().slice(0, 10));
const [notes, setNotes] = useState('');
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState('');
useEffect(() => {
api.medications.get(medId)
.then(med => {
setName(med.name);
setDosage(String(med.dosage));
setUnit(med.unit);
setFrequency((med as any).frequency || 'daily');
setTimes((med as any).times?.length ? (med as any).times : ['08:00']);
setDaysOfWeek((med as any).days_of_week || []);
setIntervalDays((med as any).interval_days || 7);
setStartDate((med as any).start_date?.slice(0, 10) || new Date().toISOString().slice(0, 10));
setNotes(med.notes || '');
})
.catch(() => setError('Failed to load medication.'))
.finally(() => setIsLoadingMed(false));
}, [medId]);
const handleAddTime = () => setTimes([...times, '12:00']);
const handleRemoveTime = (i: number) => setTimes(times.filter((_, idx) => idx !== i));
const handleTimeChange = (i: number, val: string) => {
const t = [...times]; t[i] = val; setTimes(t);
};
const toggleDay = (day: string) =>
setDaysOfWeek(prev => prev.includes(day) ? prev.filter(d => d !== day) : [...prev, day]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!name.trim() || !dosage.trim()) { setError('Name and dosage are required.'); return; }
if (frequency === 'specific_days' && daysOfWeek.length === 0) { setError('Select at least one day.'); return; }
setIsSubmitting(true);
setError('');
try {
await api.medications.update(medId, {
name: name.trim(),
dosage: dosage.trim(),
unit,
frequency,
times: frequency === 'as_needed' ? [] : times,
...(frequency === 'specific_days' && { days_of_week: daysOfWeek }),
...(frequency === 'every_n_days' && { interval_days: intervalDays, start_date: startDate }),
...(notes.trim() && { notes: notes.trim() }),
});
router.push('/dashboard/medications');
} catch (err) {
setError((err as Error).message || 'Failed to save changes.');
setIsSubmitting(false);
}
};
if (isLoadingMed) {
return (
<div className="flex items-center justify-center min-h-[50vh]">
<div className="w-8 h-8 border-4 border-indigo-500 border-t-transparent rounded-full animate-spin" />
</div>
);
}
return (
<div className="min-h-screen bg-gray-50 dark:bg-gray-950">
<header className="bg-white dark:bg-gray-900 border-b border-gray-200 dark:border-gray-700 sticky top-0 z-10">
<div className="flex items-center gap-3 px-4 py-3">
<button onClick={() => router.back()} className="p-1 text-gray-600 dark:text-gray-400">
<ArrowLeftIcon size={24} />
</button>
<h1 className="text-xl font-bold text-gray-900 dark:text-gray-100">Edit Medication</h1>
</div>
</header>
<form onSubmit={handleSubmit} className="p-4 space-y-6">
{error && (
<div className="bg-red-50 dark:bg-red-900/30 text-red-600 dark:text-red-400 px-4 py-3 rounded-lg text-sm">
{error}
</div>
)}
<div className="bg-white dark:bg-gray-800 rounded-xl p-4 shadow-sm space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Medication Name</label>
<input
type="text"
value={name}
onChange={e => setName(e.target.value)}
className="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-indigo-500 outline-none"
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Dosage</label>
<input
type="text"
value={dosage}
onChange={e => setDosage(e.target.value)}
className="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-indigo-500 outline-none"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Unit</label>
<select
value={unit}
onChange={e => setUnit(e.target.value)}
className="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-indigo-500 outline-none"
>
<option value="mg">mg</option>
<option value="mcg">mcg</option>
<option value="g">g</option>
<option value="ml">ml</option>
<option value="IU">IU</option>
<option value="tablets">tablets</option>
<option value="capsules">capsules</option>
</select>
</div>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Frequency</label>
<select
value={frequency}
onChange={e => setFrequency(e.target.value)}
className="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-indigo-500 outline-none"
>
<option value="daily">Daily</option>
<option value="specific_days">Specific Days of Week</option>
<option value="every_n_days">Every N Days</option>
<option value="as_needed">As Needed (PRN)</option>
</select>
</div>
{frequency === 'specific_days' && (
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Days</label>
<div className="flex gap-2 flex-wrap">
{DAY_OPTIONS.map(({ value, label }) => (
<button
key={value}
type="button"
onClick={() => toggleDay(value)}
className={`px-3 py-2 rounded-lg text-sm font-medium border transition-colors ${
daysOfWeek.includes(value)
? 'bg-indigo-600 text-white border-indigo-600'
: 'bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300 border-gray-300 dark:border-gray-600'
}`}
>
{label}
</button>
))}
</div>
</div>
)}
{frequency === 'every_n_days' && (
<div className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Every N Days</label>
<input
type="number"
min={1}
value={intervalDays}
onChange={e => setIntervalDays(parseInt(e.target.value) || 1)}
className="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-indigo-500 outline-none"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Starting From</label>
<input
type="date"
value={startDate}
onChange={e => setStartDate(e.target.value)}
className="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-indigo-500 outline-none"
/>
</div>
</div>
)}
{frequency !== 'as_needed' && (
<div>
<div className="flex items-center justify-between mb-1">
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300">Times</label>
<button type="button" onClick={handleAddTime} className="text-indigo-600 dark:text-indigo-400 text-sm font-medium">
+ Add Time
</button>
</div>
<div className="space-y-2">
{times.map((time, i) => (
<div key={i} className="flex gap-2">
<input
type="time"
value={time}
onChange={e => handleTimeChange(i, e.target.value)}
className="flex-1 px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-indigo-500 outline-none"
/>
{times.length > 1 && (
<button type="button" onClick={() => handleRemoveTime(i)} className="text-red-500 dark:text-red-400 px-3">
Remove
</button>
)}
</div>
))}
</div>
</div>
)}
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Notes <span className="text-gray-400 font-normal">(optional)</span>
</label>
<textarea
value={notes}
onChange={e => setNotes(e.target.value)}
rows={2}
className="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-indigo-500 outline-none resize-none"
/>
</div>
</div>
<button
type="submit"
disabled={isSubmitting}
className="w-full bg-indigo-600 text-white font-semibold py-4 rounded-xl hover:bg-indigo-700 disabled:opacity-50"
>
{isSubmitting ? 'Saving…' : 'Save Changes'}
</button>
</form>
</div>
);
}

View File

@@ -3,7 +3,7 @@
import { useEffect, useState, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import api from '@/lib/api';
import { PlusIcon, CheckIcon, PillIcon, ClockIcon, TrashIcon } from '@/components/ui/Icons';
import { PlusIcon, CheckIcon, PillIcon, ClockIcon, TrashIcon, EditIcon } from '@/components/ui/Icons';
import Link from 'next/link';
import PushNotificationToggle from '@/components/notifications/PushNotificationToggle';
@@ -380,6 +380,13 @@ export default function MedicationsPage() {
<p className="text-gray-400 dark:text-gray-500 text-sm mt-1">Times: {med.times.join(', ')}</p>
)}
</div>
<div className="flex items-center gap-1">
<Link
href={`/dashboard/medications/${med.id}/edit`}
className="text-gray-400 dark:text-gray-500 hover:text-indigo-600 dark:hover:text-indigo-400 p-2"
>
<EditIcon size={18} />
</Link>
<button
onClick={() => handleDelete(med.id)}
className="text-red-500 dark:text-red-400 p-2"
@@ -387,6 +394,7 @@ export default function MedicationsPage() {
<TrashIcon size={18} />
</button>
</div>
</div>
{/* Adherence */}
<div className="mt-3 pt-3 border-t border-gray-100 dark:border-gray-700">

View File

@@ -0,0 +1,150 @@
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import api from '@/lib/api';
import { ArrowLeftIcon } from '@/components/ui/Icons';
const REMINDER_OPTIONS = [
{ label: 'No reminder', value: 0 },
{ label: '5 minutes before', value: 5 },
{ label: '10 minutes before', value: 10 },
{ label: '15 minutes before', value: 15 },
{ label: '30 minutes before', value: 30 },
{ label: '1 hour before', value: 60 },
];
function localDatetimeDefault(): string {
const now = new Date();
now.setMinutes(now.getMinutes() + 60, 0, 0);
const pad = (n: number) => String(n).padStart(2, '0');
return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}T${pad(now.getHours())}:${pad(now.getMinutes())}`;
}
export default function NewTaskPage() {
const router = useRouter();
const [title, setTitle] = useState('');
const [description, setDescription] = useState('');
const [scheduledDatetime, setScheduledDatetime] = useState(localDatetimeDefault);
const [reminderMinutes, setReminderMinutes] = useState(15);
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState('');
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!title.trim()) {
setError('Title is required.');
return;
}
if (!scheduledDatetime) {
setError('Date and time are required.');
return;
}
setIsSubmitting(true);
setError('');
try {
await api.tasks.create({
title: title.trim(),
description: description.trim() || undefined,
scheduled_datetime: scheduledDatetime,
reminder_minutes_before: reminderMinutes,
});
router.push('/dashboard/tasks');
} catch (err) {
console.error('Failed to create task:', err);
setError('Failed to create task. Please try again.');
setIsSubmitting(false);
}
};
return (
<div className="min-h-screen bg-gray-50 dark:bg-gray-950">
<header className="bg-white dark:bg-gray-900 border-b border-gray-200 dark:border-gray-700 sticky top-0 z-10">
<div className="flex items-center gap-3 px-4 py-3">
<Link href="/dashboard/tasks" className="p-1 -ml-1 text-gray-500 dark:text-gray-400">
<ArrowLeftIcon size={20} />
</Link>
<h1 className="text-xl font-bold text-gray-900 dark:text-gray-100">New Task</h1>
</div>
</header>
<form onSubmit={handleSubmit} className="p-4 space-y-5 max-w-lg mx-auto">
{error && (
<div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-3 text-sm text-red-600 dark:text-red-400">
{error}
</div>
)}
<div className="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-4 space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Title <span className="text-red-500">*</span>
</label>
<input
type="text"
value={title}
onChange={e => setTitle(e.target.value)}
placeholder="e.g. Doctor appointment"
className="w-full rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 px-3 py-2 text-gray-900 dark:text-gray-100 placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-indigo-500 text-sm"
autoFocus
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Description <span className="text-gray-400 font-normal">(optional)</span>
</label>
<textarea
value={description}
onChange={e => setDescription(e.target.value)}
placeholder="Add details..."
rows={2}
className="w-full rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 px-3 py-2 text-gray-900 dark:text-gray-100 placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-indigo-500 text-sm resize-none"
/>
</div>
</div>
<div className="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-4 space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Date &amp; Time <span className="text-red-500">*</span>
</label>
<input
type="datetime-local"
value={scheduledDatetime}
onChange={e => setScheduledDatetime(e.target.value)}
className="w-full rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 px-3 py-2 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-indigo-500 text-sm"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Advance Reminder
</label>
<select
value={reminderMinutes}
onChange={e => setReminderMinutes(Number(e.target.value))}
className="w-full rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 px-3 py-2 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-indigo-500 text-sm"
>
{REMINDER_OPTIONS.map(opt => (
<option key={opt.value} value={opt.value}>{opt.label}</option>
))}
</select>
<p className="text-xs text-gray-400 dark:text-gray-500 mt-1">
You&apos;ll also get a notification exactly at the scheduled time.
</p>
</div>
</div>
<button
type="submit"
disabled={isSubmitting}
className="w-full bg-indigo-600 hover:bg-indigo-700 disabled:opacity-60 text-white font-semibold py-3 rounded-xl transition-colors"
>
{isSubmitting ? 'Saving…' : 'Add Task'}
</button>
</form>
</div>
);
}

View File

@@ -0,0 +1,217 @@
'use client';
import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import api, { Task } from '@/lib/api';
import { PlusIcon, CheckIcon, XIcon, ClockIcon, TrashIcon } from '@/components/ui/Icons';
function formatDateTime(dtStr: string): string {
try {
const dt = new Date(dtStr);
const now = new Date();
const tomorrow = new Date(now);
tomorrow.setDate(now.getDate() + 1);
const timeStr = dt.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });
if (dt.toDateString() === now.toDateString()) return `Today at ${timeStr}`;
if (dt.toDateString() === tomorrow.toDateString()) return `Tomorrow at ${timeStr}`;
return dt.toLocaleDateString([], { weekday: 'short', month: 'short', day: 'numeric' }) + ` at ${timeStr}`;
} catch {
return dtStr;
}
}
function isPast(dtStr: string): boolean {
try {
return new Date(dtStr) < new Date();
} catch {
return false;
}
}
export default function TasksPage() {
const router = useRouter();
const [tasks, setTasks] = useState<Task[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [showCompleted, setShowCompleted] = useState(false);
const loadTasks = async (status: string) => {
try {
const data = await api.tasks.list(status);
setTasks(data);
} catch (err) {
console.error('Failed to load tasks:', err);
} finally {
setIsLoading(false);
}
};
useEffect(() => {
loadTasks(showCompleted ? 'all' : 'pending');
}, [showCompleted]);
const handleMarkDone = async (task: Task) => {
try {
await api.tasks.update(task.id, { status: 'completed' });
setTasks(prev => prev.filter(t => t.id !== task.id));
} catch (err) {
console.error('Failed to update task:', err);
}
};
const handleCancel = async (task: Task) => {
try {
await api.tasks.update(task.id, { status: 'cancelled' });
setTasks(prev => prev.filter(t => t.id !== task.id));
} catch (err) {
console.error('Failed to cancel task:', err);
}
};
const handleDelete = async (task: Task) => {
if (!confirm(`Delete "${task.title}"?`)) return;
try {
await api.tasks.delete(task.id);
setTasks(prev => prev.filter(t => t.id !== task.id));
} catch (err) {
console.error('Failed to delete task:', err);
}
};
const activeTasks = tasks.filter(t => t.status === 'pending' || t.status === 'notified');
const doneTasks = tasks.filter(t => t.status === 'completed' || t.status === 'cancelled');
return (
<div className="min-h-screen bg-gray-50 dark:bg-gray-950">
<header className="bg-white dark:bg-gray-900 border-b border-gray-200 dark:border-gray-700 sticky top-0 z-10">
<div className="flex items-center justify-between px-4 py-3">
<h1 className="text-xl font-bold text-gray-900 dark:text-gray-100">Tasks</h1>
<Link
href="/dashboard/tasks/new"
className="flex items-center gap-1 text-indigo-600 dark:text-indigo-400 font-medium text-sm"
>
<PlusIcon size={18} />
Add Task
</Link>
</div>
</header>
<div className="p-4 space-y-4">
{isLoading ? (
<div className="flex justify-center py-12">
<div className="w-8 h-8 border-4 border-indigo-500 border-t-transparent rounded-full animate-spin" />
</div>
) : activeTasks.length === 0 ? (
<div className="bg-white dark:bg-gray-800 rounded-xl p-8 shadow-sm text-center">
<ClockIcon size={40} className="mx-auto mb-3 text-gray-300 dark:text-gray-600" />
<p className="text-gray-500 dark:text-gray-400 mb-4">No upcoming tasks</p>
<Link
href="/dashboard/tasks/new"
className="inline-flex items-center gap-2 bg-indigo-600 text-white text-sm font-medium px-4 py-2 rounded-lg hover:bg-indigo-700 transition-colors"
>
<PlusIcon size={16} />
Add your first task
</Link>
</div>
) : (
<div className="space-y-3">
{activeTasks.map(task => (
<div
key={task.id}
className={`bg-white dark:bg-gray-800 rounded-xl p-4 shadow-sm border-l-4 ${
task.status === 'notified'
? 'border-amber-400'
: isPast(task.scheduled_datetime)
? 'border-red-400'
: 'border-indigo-400'
}`}
>
<div className="flex items-start gap-3">
<div className="flex-1 min-w-0">
<h3 className="font-semibold text-gray-900 dark:text-gray-100 truncate">{task.title}</h3>
{task.description && (
<p className="text-sm text-gray-500 dark:text-gray-400 mt-0.5">{task.description}</p>
)}
<div className="flex items-center gap-2 mt-1.5">
<ClockIcon size={13} className="text-gray-400 flex-shrink-0" />
<span className={`text-sm ${isPast(task.scheduled_datetime) && task.status === 'pending' ? 'text-red-500 dark:text-red-400' : 'text-gray-500 dark:text-gray-400'}`}>
{formatDateTime(task.scheduled_datetime)}
</span>
{task.status === 'notified' && (
<span className="text-xs bg-amber-100 dark:bg-amber-900/40 text-amber-700 dark:text-amber-400 px-1.5 py-0.5 rounded-full">
Notified
</span>
)}
{task.reminder_minutes_before > 0 && (
<span className="text-xs text-gray-400 dark:text-gray-500">
+{task.reminder_minutes_before}m reminder
</span>
)}
</div>
</div>
<div className="flex items-center gap-1 flex-shrink-0">
<button
onClick={() => handleMarkDone(task)}
className="p-2 text-green-600 dark:text-green-400 hover:bg-green-50 dark:hover:bg-green-900/20 rounded-lg transition-colors"
title="Mark done"
>
<CheckIcon size={18} />
</button>
<button
onClick={() => handleCancel(task)}
className="p-2 text-gray-400 dark:text-gray-500 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
title="Cancel"
>
<XIcon size={18} />
</button>
<button
onClick={() => handleDelete(task)}
className="p-2 text-red-400 dark:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors"
title="Delete"
>
<TrashIcon size={18} />
</button>
</div>
</div>
</div>
))}
</div>
)}
{/* Show completed toggle */}
{!isLoading && (
<button
onClick={() => setShowCompleted(!showCompleted)}
className="w-full text-sm text-gray-500 dark:text-gray-400 py-2 hover:text-gray-700 dark:hover:text-gray-200 transition-colors"
>
{showCompleted ? 'Hide completed' : `Show completed${doneTasks.length > 0 ? ` (${doneTasks.length})` : ''}`}
</button>
)}
{/* Completed tasks */}
{showCompleted && doneTasks.length > 0 && (
<div className="space-y-2">
<h2 className="text-sm font-medium text-gray-500 dark:text-gray-400 px-1">Completed / Cancelled</h2>
{doneTasks.map(task => (
<div key={task.id} className="bg-white dark:bg-gray-800 rounded-xl p-4 shadow-sm opacity-60 flex items-center justify-between">
<div>
<p className="text-gray-700 dark:text-gray-300 line-through">{task.title}</p>
<p className="text-xs text-gray-400 dark:text-gray-500">{formatDateTime(task.scheduled_datetime)}</p>
</div>
<button
onClick={() => handleDelete(task)}
className="p-1.5 text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg"
>
<TrashIcon size={16} />
</button>
</div>
))}
</div>
)}
</div>
</div>
);
}

View File

@@ -9,7 +9,7 @@ export default function LoginPage() {
const [isLogin, setIsLogin] = useState(true);
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [trustDevice, setTrustDevice] = useState(false);
const [trustDevice, setTrustDevice] = useState(true);
const [error, setError] = useState('');
const [isLoading, setIsLoading] = useState(false);
const { login, register } = useAuth();

View File

@@ -1,5 +1,18 @@
const API_URL = '';
export interface Task {
id: string;
user_uuid: string;
title: string;
description?: string;
scheduled_datetime: string;
reminder_minutes_before: number;
advance_notified: boolean;
status: 'pending' | 'notified' | 'completed' | 'cancelled';
created_at: string;
updated_at: string;
}
function getToken(): string | null {
if (typeof window === 'undefined') return null;
return localStorage.getItem('token');
@@ -1052,6 +1065,17 @@ export const api = {
},
},
tasks: {
list: (status = 'pending') =>
request<Task[]>(`/api/tasks?status=${status}`, { method: 'GET' }),
create: (data: { title: string; description?: string; scheduled_datetime: string; reminder_minutes_before?: number }) =>
request<Task>('/api/tasks', { method: 'POST', body: JSON.stringify(data) }),
update: (id: string, data: Partial<Pick<Task, 'title' | 'description' | 'scheduled_datetime' | 'reminder_minutes_before' | 'status'>>) =>
request<Task>(`/api/tasks/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
delete: (id: string) =>
request<{ success: boolean }>(`/api/tasks/${id}`, { method: 'DELETE' }),
},
ai: {
generateSteps: (goal: string) =>
request<{ steps: { name: string; duration_minutes: number }[] }>(