This commit is contained in:
@@ -0,0 +1,12 @@
|
||||
import { drizzle } from 'drizzle-orm/node-postgres';
|
||||
import { Pool } from 'pg';
|
||||
import * as schema from './schema';
|
||||
|
||||
const pool = new Pool({
|
||||
connectionString: process.env.DATABASE_URL,
|
||||
max: 20,
|
||||
});
|
||||
|
||||
export const db = drizzle(pool, { schema });
|
||||
|
||||
export type DB = typeof db;
|
||||
@@ -0,0 +1,107 @@
|
||||
import { pgTable, text, integer, bigint, boolean, timestamp, unique, index } from 'drizzle-orm/pg-core';
|
||||
import { sql } from 'drizzle-orm';
|
||||
|
||||
export const users = pgTable('users', {
|
||||
id: text('id').primaryKey(),
|
||||
username: text('username').notNull().unique(),
|
||||
passwordHash: text('password_hash').notNull(),
|
||||
resetToken: text('reset_token'),
|
||||
resetTokenExpiry: bigint('reset_token_expiry', { mode: 'number' }),
|
||||
createdAt: bigint('created_at', { mode: 'number' }).notNull().default(sql`EXTRACT(EPOCH FROM NOW()) * 1000`),
|
||||
});
|
||||
|
||||
export const friendships = pgTable(
|
||||
'friendships',
|
||||
{
|
||||
id: text('id').primaryKey(),
|
||||
userId: text('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
|
||||
friendId: text('friend_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
|
||||
status: text('status', { enum: ['pending', 'accepted'] }).notNull().default('pending'),
|
||||
createdAt: bigint('created_at', { mode: 'number' }).notNull().default(sql`EXTRACT(EPOCH FROM NOW()) * 1000`),
|
||||
updatedAt: bigint('updated_at', { mode: 'number' }).notNull().default(sql`EXTRACT(EPOCH FROM NOW()) * 1000`),
|
||||
},
|
||||
(t) => ({
|
||||
pairUnique: unique('friendships_pair').on(t.userId, t.friendId),
|
||||
userIdx: index('friendships_user_idx').on(t.userId),
|
||||
friendIdx: index('friendships_friend_idx').on(t.friendId),
|
||||
})
|
||||
);
|
||||
|
||||
export const categories = pgTable('categories', {
|
||||
id: text('id').primaryKey(),
|
||||
userId: text('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
|
||||
name: text('name').notNull(),
|
||||
color: text('color').notNull(),
|
||||
order: integer('order').notNull().default(0),
|
||||
createdAt: bigint('created_at', { mode: 'number' }).notNull().default(sql`EXTRACT(EPOCH FROM NOW()) * 1000`),
|
||||
updatedAt: bigint('updated_at', { mode: 'number' }).notNull().default(sql`EXTRACT(EPOCH FROM NOW()) * 1000`),
|
||||
});
|
||||
|
||||
export const tasks = pgTable('tasks', {
|
||||
id: text('id').primaryKey(),
|
||||
userId: text('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
|
||||
categoryId: text('category_id').notNull().references(() => categories.id, { onDelete: 'cascade' }),
|
||||
title: text('title').notNull(),
|
||||
description: text('description').notNull().default(''),
|
||||
priority: text('priority', { enum: ['none', 'low', 'medium', 'high', 'critical'] }).notNull().default('none'),
|
||||
completed: boolean('completed').notNull().default(false),
|
||||
dueDate: bigint('due_date', { mode: 'number' }).notNull().default(0),
|
||||
dueTime: text('due_time').notNull().default(''),
|
||||
endTime: text('end_time').notNull().default(''),
|
||||
allDay: boolean('all_day').notNull().default(false),
|
||||
repeat: text('repeat', { enum: ['none', 'daily', 'weekly', 'monthly', 'custom'] }).notNull().default('none'),
|
||||
repeatInterval: integer('repeat_interval').notNull().default(1),
|
||||
repeatDays: text('repeat_days').notNull().default(''),
|
||||
seriesId: text('series_id').notNull().default(''),
|
||||
assigneeId: text('assignee_id').references(() => users.id, { onDelete: 'set null' }),
|
||||
reminder: text('reminder', { enum: ['none', 'at_time', '15', '30', '60', '120', '1440'] }).notNull().default('none'),
|
||||
reminders: text('reminders').notNull().default(''),
|
||||
createdAt: bigint('created_at', { mode: 'number' }).notNull().default(sql`EXTRACT(EPOCH FROM NOW()) * 1000`),
|
||||
updatedAt: bigint('updated_at', { mode: 'number' }).notNull().default(sql`EXTRACT(EPOCH FROM NOW()) * 1000`),
|
||||
});
|
||||
|
||||
export const repeatProfiles = pgTable('repeat_profiles', {
|
||||
id: text('id').primaryKey(),
|
||||
userId: text('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
|
||||
name: text('name').notNull(),
|
||||
repeat: text('repeat', { enum: ['none', 'daily', 'weekly', 'monthly', 'custom'] }).notNull().default('none'),
|
||||
repeatInterval: integer('repeat_interval').notNull().default(1),
|
||||
repeatDays: text('repeat_days').notNull().default(''),
|
||||
createdAt: bigint('created_at', { mode: 'number' }).notNull().default(sql`EXTRACT(EPOCH FROM NOW()) * 1000`),
|
||||
updatedAt: bigint('updated_at', { mode: 'number' }).notNull().default(sql`EXTRACT(EPOCH FROM NOW()) * 1000`),
|
||||
});
|
||||
|
||||
export const subtasks = pgTable('subtasks', {
|
||||
id: text('id').primaryKey(),
|
||||
userId: text('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
|
||||
taskId: text('task_id').notNull().references(() => tasks.id, { onDelete: 'cascade' }),
|
||||
title: text('title').notNull(),
|
||||
description: text('description').notNull().default(''),
|
||||
priority: text('priority', { enum: ['none', 'low', 'medium', 'high', 'critical'] }).notNull().default('none'),
|
||||
completed: boolean('completed').notNull().default(false),
|
||||
dueDate: bigint('due_date', { mode: 'number' }).notNull().default(0),
|
||||
dueTime: text('due_time').notNull().default(''),
|
||||
endTime: text('end_time').notNull().default(''),
|
||||
allDay: boolean('all_day').notNull().default(false),
|
||||
repeat: text('repeat', { enum: ['none', 'daily', 'weekly', 'monthly', 'custom'] }).notNull().default('none'),
|
||||
repeatInterval: integer('repeat_interval').notNull().default(1),
|
||||
repeatDays: text('repeat_days').notNull().default(''),
|
||||
seriesId: text('series_id').notNull().default(''),
|
||||
reminder: text('reminder', { enum: ['none', 'at_time', '15', '30', '60', '120', '1440'] }).notNull().default('none'),
|
||||
reminders: text('reminders').notNull().default(''),
|
||||
assigneeId: text('assignee_id').references(() => users.id, { onDelete: 'set null' }),
|
||||
order: integer('order').notNull().default(0),
|
||||
createdAt: bigint('created_at', { mode: 'number' }).notNull().default(sql`EXTRACT(EPOCH FROM NOW()) * 1000`),
|
||||
updatedAt: bigint('updated_at', { mode: 'number' }).notNull().default(sql`EXTRACT(EPOCH FROM NOW()) * 1000`),
|
||||
});
|
||||
|
||||
export const userSettings = pgTable('user_settings', {
|
||||
userId: text('user_id').primaryKey().references(() => users.id, { onDelete: 'cascade' }),
|
||||
darkMode: boolean('dark_mode').notNull().default(false),
|
||||
notifications: boolean('notifications').notNull().default(true),
|
||||
reminderTime: text('reminder_time').notNull().default('09:00'),
|
||||
defaultCategory: text('default_category'),
|
||||
sortBy: text('sort_by', { enum: ['dueDate', 'priority', 'title', 'createdAt'] }).notNull().default('dueDate'),
|
||||
sortOrder: text('sort_order', { enum: ['asc', 'desc'] }).notNull().default('asc'),
|
||||
updatedAt: bigint('updated_at', { mode: 'number' }).notNull().default(sql`EXTRACT(EPOCH FROM NOW()) * 1000`),
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import 'dotenv/config';
|
||||
import express from 'express';
|
||||
import cors from 'cors';
|
||||
import authRoutes from './routes/auth';
|
||||
import categoryRoutes from './routes/categories';
|
||||
import taskRoutes from './routes/tasks';
|
||||
import subtaskRoutes from './routes/subtasks';
|
||||
import userRoutes from './routes/users';
|
||||
import friendRoutes from './routes/friends';
|
||||
import repeatProfileRoutes from './routes/repeatProfiles';
|
||||
import syncRoutes from './routes/sync';
|
||||
import { errorHandler, notFoundHandler } from './middleware/errorHandler';
|
||||
|
||||
const app = express();
|
||||
const PORT = process.env.PORT || 3000;
|
||||
|
||||
app.use(cors({
|
||||
origin: true,
|
||||
credentials: true,
|
||||
}));
|
||||
app.use(express.json());
|
||||
|
||||
// Health check
|
||||
app.get('/health', (req, res) => {
|
||||
res.json({ status: 'ok', timestamp: Date.now() });
|
||||
});
|
||||
|
||||
// API routes
|
||||
app.use('/api/auth', authRoutes);
|
||||
app.use('/api/categories', categoryRoutes);
|
||||
app.use('/api/tasks', taskRoutes);
|
||||
app.use('/api/subtasks', subtaskRoutes);
|
||||
app.use('/api/users', userRoutes);
|
||||
app.use('/api/repeat-profiles', repeatProfileRoutes);
|
||||
app.use('/api/sync', syncRoutes);
|
||||
app.use('/api/friends', friendRoutes);
|
||||
|
||||
// 404 handler
|
||||
app.use(notFoundHandler);
|
||||
|
||||
// Error handler
|
||||
app.use(errorHandler);
|
||||
|
||||
app.listen(PORT, () => {
|
||||
console.log(`🚀 Server running on http://localhost:${PORT}`);
|
||||
console.log(`📚 API available at http://localhost:${PORT}/api`);
|
||||
});
|
||||
|
||||
export default app;
|
||||
@@ -0,0 +1,56 @@
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import { ZodError } from 'zod';
|
||||
|
||||
export class AppError extends Error {
|
||||
constructor(
|
||||
public code: string,
|
||||
public message: string,
|
||||
public statusCode: number = 500,
|
||||
public details?: Record<string, any>
|
||||
) {
|
||||
super(message);
|
||||
this.name = 'AppError';
|
||||
}
|
||||
}
|
||||
|
||||
export function errorHandler(err: Error, req: Request, res: Response, next: NextFunction): void {
|
||||
console.error('Error:', err);
|
||||
|
||||
if (err instanceof ZodError) {
|
||||
res.status(400).json({
|
||||
error: {
|
||||
code: 'INVALID_PAYLOAD',
|
||||
message: 'Request validation failed',
|
||||
details: err.flatten().fieldErrors,
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (err instanceof AppError) {
|
||||
res.status(err.statusCode).json({
|
||||
error: {
|
||||
code: err.code,
|
||||
message: err.message,
|
||||
details: err.details,
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
res.status(500).json({
|
||||
error: {
|
||||
code: 'SERVER_ERROR',
|
||||
message: 'Internal server error',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function notFoundHandler(req: Request, res: Response): void {
|
||||
res.status(404).json({
|
||||
error: {
|
||||
code: 'NOT_FOUND',
|
||||
message: `Route ${req.method} ${req.path} not found`,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
import { Router, Request, Response } from 'express';
|
||||
import { asyncHandler } from '../utils/asyncHandler';
|
||||
import { db } from '../db';
|
||||
import { users } from '../db/schema';
|
||||
import { eq } from 'drizzle-orm';
|
||||
import { generateToken, generateId, getCurrentTimestamp } from '../utils/auth';
|
||||
import { AppError } from '../middleware/errorHandler';
|
||||
import { z } from 'zod';
|
||||
import bcrypt from 'bcryptjs';
|
||||
import rateLimit from 'express-rate-limit';
|
||||
import crypto from 'crypto';
|
||||
|
||||
const router = Router();
|
||||
|
||||
// Rate limiting for auth endpoints
|
||||
const authLimiter = rateLimit({
|
||||
windowMs: 15 * 60 * 1000, // 15 minutes
|
||||
max: 10, // limit each IP to 10 requests per windowMs
|
||||
message: {
|
||||
error: {
|
||||
code: 'RATE_LIMITED',
|
||||
message: 'Too many attempts. Please try again later.',
|
||||
},
|
||||
},
|
||||
standardHeaders: true,
|
||||
legacyHeaders: false,
|
||||
});
|
||||
|
||||
const loginLimiter = rateLimit({
|
||||
windowMs: 15 * 60 * 1000, // 15 minutes
|
||||
max: 5, // stricter limit for login
|
||||
message: {
|
||||
error: {
|
||||
code: 'RATE_LIMITED',
|
||||
message: 'Too many login attempts. Please try again later.',
|
||||
},
|
||||
},
|
||||
standardHeaders: true,
|
||||
legacyHeaders: false,
|
||||
});
|
||||
|
||||
const passwordResetLimiter = rateLimit({
|
||||
windowMs: 60 * 60 * 1000, // 1 hour
|
||||
max: 3, // very strict for password reset
|
||||
message: {
|
||||
error: {
|
||||
code: 'RATE_LIMITED',
|
||||
message: 'Too many password reset requests. Please try again later.',
|
||||
},
|
||||
},
|
||||
standardHeaders: true,
|
||||
legacyHeaders: false,
|
||||
});
|
||||
|
||||
const usernameSchema = z
|
||||
.string()
|
||||
.min(3)
|
||||
.max(30)
|
||||
.regex(/^[a-zA-Z0-9_.-]+$/, 'Username can only contain letters, numbers, dots, dashes and underscores');
|
||||
|
||||
const registerSchema = z.object({
|
||||
username: usernameSchema,
|
||||
password: z.string().min(8),
|
||||
});
|
||||
|
||||
const loginSchema = z.object({
|
||||
username: z.string(),
|
||||
password: z.string(),
|
||||
});
|
||||
|
||||
const forgotPasswordSchema = z.object({
|
||||
username: z.string().min(1),
|
||||
});
|
||||
|
||||
const resetPasswordSchema = z.object({
|
||||
token: z.string().min(1),
|
||||
password: z.string().min(8),
|
||||
});
|
||||
|
||||
const BCRYPT_ROUNDS = 12;
|
||||
|
||||
async function hashPassword(password: string): Promise<string> {
|
||||
return bcrypt.hash(password, BCRYPT_ROUNDS);
|
||||
}
|
||||
|
||||
async function verifyPassword(password: string, hash: string): Promise<boolean> {
|
||||
return bcrypt.compare(password, hash);
|
||||
}
|
||||
|
||||
function generateResetToken(): string {
|
||||
return crypto.randomBytes(32).toString('hex');
|
||||
}
|
||||
|
||||
router.post('/register', authLimiter, asyncHandler(async (req: Request, res: Response) => {
|
||||
const data = registerSchema.parse(req.body);
|
||||
|
||||
const existing = await db.select().from(users).where(eq(users.username, data.username)).limit(1);
|
||||
if (existing.length > 0) {
|
||||
throw new AppError('USERNAME_EXISTS', 'Username already registered', 409);
|
||||
}
|
||||
|
||||
const userId = generateId('user');
|
||||
const now = getCurrentTimestamp();
|
||||
|
||||
await db.insert(users).values({
|
||||
id: userId,
|
||||
username: data.username,
|
||||
passwordHash: await hashPassword(data.password),
|
||||
createdAt: now,
|
||||
});
|
||||
|
||||
const token = generateToken({ userId, username: data.username });
|
||||
|
||||
res.status(201).json({
|
||||
user: { id: userId, username: data.username },
|
||||
token,
|
||||
});
|
||||
}));
|
||||
|
||||
router.post('/login', loginLimiter, asyncHandler(async (req: Request, res: Response) => {
|
||||
const data = loginSchema.parse(req.body);
|
||||
|
||||
const user = await db.select().from(users).where(eq(users.username, data.username)).limit(1);
|
||||
if (user.length === 0 || !verifyPassword(data.password, user[0].passwordHash)) {
|
||||
throw new AppError('INVALID_CREDENTIALS', 'Invalid username or password', 401);
|
||||
}
|
||||
|
||||
const token = generateToken({ userId: user[0].id, username: user[0].username });
|
||||
|
||||
res.json({
|
||||
user: { id: user[0].id, username: user[0].username },
|
||||
token,
|
||||
});
|
||||
}));
|
||||
|
||||
router.get('/me', asyncHandler(async (req: Request, res: Response) => {
|
||||
if (!req.user) {
|
||||
throw new AppError('UNAUTHORIZED', 'Authentication required', 401);
|
||||
}
|
||||
|
||||
const user = await db.select().from(users).where(eq(users.id, req.user.userId)).limit(1);
|
||||
if (user.length === 0) {
|
||||
throw new AppError('NOT_FOUND', 'User not found', 404);
|
||||
}
|
||||
|
||||
res.json({ id: user[0].id, username: user[0].username });
|
||||
}));
|
||||
|
||||
router.post('/forgot-password', passwordResetLimiter, asyncHandler(async (req: Request, res: Response) => {
|
||||
const data = forgotPasswordSchema.parse(req.body);
|
||||
|
||||
const user = await db.select().from(users).where(eq(users.username, data.username)).limit(1);
|
||||
// Always return success to prevent username enumeration
|
||||
if (user.length === 0) {
|
||||
res.json({ success: true });
|
||||
return;
|
||||
}
|
||||
|
||||
const resetToken = generateResetToken();
|
||||
const resetTokenExpiry = Date.now() + 3600000; // 1 hour
|
||||
|
||||
await db
|
||||
.update(users)
|
||||
.set({ resetToken, resetTokenExpiry })
|
||||
.where(eq(users.id, user[0].id));
|
||||
|
||||
// In production, send email with reset link
|
||||
// For now, return token in response (dev only)
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
res.json({ success: true, resetToken });
|
||||
} else {
|
||||
res.json({ success: true });
|
||||
}
|
||||
}));
|
||||
|
||||
router.post('/reset-password', passwordResetLimiter, asyncHandler(async (req: Request, res: Response) => {
|
||||
const data = resetPasswordSchema.parse(req.body);
|
||||
|
||||
const user = await db
|
||||
.select()
|
||||
.from(users)
|
||||
.where(eq(users.resetToken, data.token))
|
||||
.limit(1);
|
||||
|
||||
if (user.length === 0 || !user[0].resetTokenExpiry || user[0].resetTokenExpiry < Date.now()) {
|
||||
throw new AppError('INVALID_TOKEN', 'Invalid or expired reset token', 400);
|
||||
}
|
||||
|
||||
const newPasswordHash = await hashPassword(data.password);
|
||||
|
||||
await db
|
||||
.update(users)
|
||||
.set({ passwordHash: newPasswordHash, resetToken: null, resetTokenExpiry: null })
|
||||
.where(eq(users.id, user[0].id));
|
||||
|
||||
res.json({ success: true });
|
||||
}));
|
||||
|
||||
export default router;
|
||||
@@ -0,0 +1,95 @@
|
||||
import { Router, Request, Response } from 'express';
|
||||
import { asyncHandler } from '../utils/asyncHandler';
|
||||
import { db } from '../db';
|
||||
import { categories } from '../db/schema';
|
||||
import { eq, and, desc, asc } from 'drizzle-orm';
|
||||
import { authMiddleware } from '../utils/auth';
|
||||
import { AppError } from '../middleware/errorHandler';
|
||||
import { categoryCreateSchema, categoryUpdateSchema } from '../utils/validation';
|
||||
|
||||
const router = Router();
|
||||
|
||||
router.use(authMiddleware);
|
||||
|
||||
router.get('/', asyncHandler(async (req: Request, res: Response) => {
|
||||
const userCategories = await db
|
||||
.select()
|
||||
.from(categories)
|
||||
.where(eq(categories.userId, req.user!.userId))
|
||||
.orderBy(asc(categories.order), asc(categories.createdAt));
|
||||
|
||||
res.json({ categories: userCategories });
|
||||
}));
|
||||
|
||||
router.post('/', asyncHandler(async (req: Request, res: Response) => {
|
||||
const data = categoryCreateSchema.parse(req.body);
|
||||
const userId = req.user!.userId;
|
||||
const now = Date.now();
|
||||
|
||||
const maxOrder = await db
|
||||
.select({ order: categories.order })
|
||||
.from(categories)
|
||||
.where(eq(categories.userId, userId))
|
||||
.orderBy(desc(categories.order))
|
||||
.limit(1);
|
||||
|
||||
const newCategory = {
|
||||
id: `cat_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`,
|
||||
userId,
|
||||
name: data.name,
|
||||
color: data.color,
|
||||
order: data.order ?? (maxOrder[0]?.order ?? -1) + 1,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
await db.insert(categories).values(newCategory);
|
||||
|
||||
res.status(201).json(newCategory);
|
||||
}));
|
||||
|
||||
router.patch('/:id', asyncHandler(async (req: Request, res: Response) => {
|
||||
const data = categoryUpdateSchema.parse(req.body);
|
||||
const userId = req.user!.userId;
|
||||
|
||||
const existing = await db
|
||||
.select()
|
||||
.from(categories)
|
||||
.where(and(eq(categories.id, req.params.id), eq(categories.userId, userId)))
|
||||
.limit(1);
|
||||
|
||||
if (existing.length === 0) {
|
||||
throw new AppError('NOT_FOUND', 'Category not found', 404);
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const updated = await db
|
||||
.update(categories)
|
||||
.set({ ...data, updatedAt: now })
|
||||
.where(and(eq(categories.id, req.params.id), eq(categories.userId, userId)))
|
||||
.returning();
|
||||
|
||||
res.json(updated[0]);
|
||||
}));
|
||||
|
||||
router.delete('/:id', asyncHandler(async (req: Request, res: Response) => {
|
||||
const userId = req.user!.userId;
|
||||
|
||||
const existing = await db
|
||||
.select()
|
||||
.from(categories)
|
||||
.where(and(eq(categories.id, req.params.id), eq(categories.userId, userId)))
|
||||
.limit(1);
|
||||
|
||||
if (existing.length === 0) {
|
||||
throw new AppError('NOT_FOUND', 'Category not found', 404);
|
||||
}
|
||||
|
||||
await db
|
||||
.delete(categories)
|
||||
.where(and(eq(categories.id, req.params.id), eq(categories.userId, userId)));
|
||||
|
||||
res.status(204).send();
|
||||
}));
|
||||
|
||||
export default router;
|
||||
@@ -0,0 +1,194 @@
|
||||
import { Router, Request, Response } from 'express';
|
||||
import { asyncHandler } from '../utils/asyncHandler';
|
||||
import { db } from '../db';
|
||||
import { users, friendships } from '../db/schema';
|
||||
import { eq, and, or, ilike, ne, asc } from 'drizzle-orm';
|
||||
import { generateId } from '../utils/auth';
|
||||
import { authMiddleware } from '../utils/auth';
|
||||
import { AppError } from '../middleware/errorHandler';
|
||||
import { friendRequestSchema, searchQuerySchema } from '../utils/validation';
|
||||
|
||||
const router = Router();
|
||||
|
||||
router.use(authMiddleware);
|
||||
|
||||
interface FriendRow {
|
||||
id: string;
|
||||
username: string;
|
||||
requestId?: string;
|
||||
status?: string;
|
||||
}
|
||||
|
||||
async function findUsernames(ids: string[]): Promise<Map<string, string>> {
|
||||
if (ids.length === 0) return new Map();
|
||||
const rows = await db.select().from(users).where(or(...ids.map((id) => eq(users.id, id))));
|
||||
return new Map(rows.map((u) => [u.id, u.username]));
|
||||
}
|
||||
|
||||
router.get('/', asyncHandler(async (req: Request, res: Response) => {
|
||||
const userId = req.user!.userId;
|
||||
|
||||
const outgoingRows = await db
|
||||
.select()
|
||||
.from(friendships)
|
||||
.where(and(eq(friendships.userId, userId), eq(friendships.status, 'pending')));
|
||||
|
||||
const incomingRows = await db
|
||||
.select()
|
||||
.from(friendships)
|
||||
.where(and(eq(friendships.friendId, userId), eq(friendships.status, 'pending')));
|
||||
|
||||
const acceptedRows = await db
|
||||
.select()
|
||||
.from(friendships)
|
||||
.where(and(
|
||||
or(eq(friendships.userId, userId), eq(friendships.friendId, userId)),
|
||||
eq(friendships.status, 'accepted')
|
||||
));
|
||||
|
||||
const friendIds = acceptedRows.map((r) => (r.userId === userId ? r.friendId : r.userId));
|
||||
const outgoingIds = outgoingRows.map((r) => r.friendId);
|
||||
const incomingIds = incomingRows.map((r) => r.userId);
|
||||
const usernames = await findUsernames([...friendIds, ...outgoingIds, ...incomingIds]);
|
||||
|
||||
const friends: FriendRow[] = acceptedRows.map((r) => {
|
||||
const friendId = r.userId === userId ? r.friendId : r.userId;
|
||||
return { id: friendId, username: usernames.get(friendId) ?? '' };
|
||||
});
|
||||
|
||||
const outgoing: FriendRow[] = outgoingRows.map((r) => ({
|
||||
id: r.id,
|
||||
username: usernames.get(r.friendId) ?? '',
|
||||
requestId: r.id,
|
||||
status: 'pending',
|
||||
}));
|
||||
|
||||
const incoming: FriendRow[] = incomingRows.map((r) => ({
|
||||
id: r.userId,
|
||||
username: usernames.get(r.userId) ?? '',
|
||||
requestId: r.id,
|
||||
status: 'pending',
|
||||
}));
|
||||
|
||||
res.json({ friends, incoming, outgoing });
|
||||
}));
|
||||
|
||||
router.get('/search', asyncHandler(async (req: Request, res: Response) => {
|
||||
const { q } = searchQuerySchema.parse(req.query);
|
||||
const userId = req.user!.userId;
|
||||
|
||||
const results = await db
|
||||
.select({ id: users.id, username: users.username })
|
||||
.from(users)
|
||||
.where(and(
|
||||
ne(users.id, userId),
|
||||
ilike(users.username, `%${q}%`)
|
||||
))
|
||||
.orderBy(asc(users.username))
|
||||
.limit(20);
|
||||
|
||||
res.json(results);
|
||||
}));
|
||||
|
||||
router.post('/requests', asyncHandler(async (req: Request, res: Response) => {
|
||||
const { username } = friendRequestSchema.parse(req.body);
|
||||
const userId = req.user!.userId;
|
||||
|
||||
if (username.toLowerCase() === (await meUsername(userId))) {
|
||||
throw new AppError('SELF_REQUEST', 'You cannot add yourself', 400);
|
||||
}
|
||||
|
||||
const target = await db.select().from(users).where(eq(users.username, username)).limit(1);
|
||||
if (target.length === 0) {
|
||||
throw new AppError('USER_NOT_FOUND', 'No user with that username found', 404);
|
||||
}
|
||||
|
||||
const existing = await db
|
||||
.select()
|
||||
.from(friendships)
|
||||
.where(or(
|
||||
and(eq(friendships.userId, userId), eq(friendships.friendId, target[0].id)),
|
||||
and(eq(friendships.userId, target[0].id), eq(friendships.friendId, userId))
|
||||
))
|
||||
.limit(1);
|
||||
|
||||
if (existing.length > 0) {
|
||||
throw new AppError(
|
||||
'ALREADY_FRIENDS',
|
||||
existing[0].status === 'accepted' ? 'You are already friends' : 'Friend request already pending',
|
||||
409
|
||||
);
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
await db.insert(friendships).values({
|
||||
id: generateId('friend'),
|
||||
userId,
|
||||
friendId: target[0].id,
|
||||
status: 'pending',
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
|
||||
res.status(201).json({ success: true });
|
||||
}));
|
||||
|
||||
router.post('/requests/:id/accept', asyncHandler(async (req: Request, res: Response) => {
|
||||
const userId = req.user!.userId;
|
||||
const requestId = req.params.id;
|
||||
|
||||
const row = await db.select().from(friendships).where(eq(friendships.id, requestId)).limit(1);
|
||||
if (row.length === 0) {
|
||||
throw new AppError('NOT_FOUND', 'Request not found', 404);
|
||||
}
|
||||
if (row[0].friendId !== userId) {
|
||||
throw new AppError('FORBIDDEN', 'This request was not sent to you', 403);
|
||||
}
|
||||
if (row[0].status !== 'pending') {
|
||||
throw new AppError('INVALID_STATE', 'Request is no longer pending', 409);
|
||||
}
|
||||
|
||||
await db
|
||||
.update(friendships)
|
||||
.set({ status: 'accepted', updatedAt: Date.now() })
|
||||
.where(eq(friendships.id, requestId));
|
||||
|
||||
res.json({ success: true });
|
||||
}));
|
||||
|
||||
router.delete('/requests/:id', asyncHandler(async (req: Request, res: Response) => {
|
||||
const userId = req.user!.userId;
|
||||
const requestId = req.params.id;
|
||||
|
||||
const row = await db.select().from(friendships).where(eq(friendships.id, requestId)).limit(1);
|
||||
if (row.length === 0) {
|
||||
throw new AppError('NOT_FOUND', 'Request not found', 404);
|
||||
}
|
||||
if (row[0].userId !== userId && row[0].friendId !== userId) {
|
||||
throw new AppError('FORBIDDEN', 'Not allowed', 403);
|
||||
}
|
||||
|
||||
await db.delete(friendships).where(eq(friendships.id, requestId));
|
||||
res.json({ success: true });
|
||||
}));
|
||||
|
||||
router.delete('/:friendId', asyncHandler(async (req: Request, res: Response) => {
|
||||
const userId = req.user!.userId;
|
||||
const friendId = req.params.friendId;
|
||||
|
||||
await db
|
||||
.delete(friendships)
|
||||
.where(or(
|
||||
and(eq(friendships.userId, userId), eq(friendships.friendId, friendId)),
|
||||
and(eq(friendships.userId, friendId), eq(friendships.friendId, userId))
|
||||
));
|
||||
|
||||
res.json({ success: true });
|
||||
}));
|
||||
|
||||
async function meUsername(userId: string): Promise<string> {
|
||||
const me = await db.select().from(users).where(eq(users.id, userId)).limit(1);
|
||||
return me.length > 0 ? me[0].username.toLowerCase() : '';
|
||||
}
|
||||
|
||||
export default router;
|
||||
@@ -0,0 +1,90 @@
|
||||
import { Router, Request, Response } from 'express';
|
||||
import { asyncHandler } from '../utils/asyncHandler';
|
||||
import { db } from '../db';
|
||||
import { repeatProfiles } from '../db/schema';
|
||||
import { eq, and, asc } from 'drizzle-orm';
|
||||
import { authMiddleware } from '../utils/auth';
|
||||
import { generateId } from '../utils/auth';
|
||||
import { AppError } from '../middleware/errorHandler';
|
||||
import { repeatProfileSchema, repeatProfileUpdateSchema } from '../utils/validation';
|
||||
|
||||
const router = Router();
|
||||
|
||||
router.use(authMiddleware);
|
||||
|
||||
router.get('/', asyncHandler(async (req: Request, res: Response) => {
|
||||
const profiles = await db
|
||||
.select()
|
||||
.from(repeatProfiles)
|
||||
.where(eq(repeatProfiles.userId, req.user!.userId))
|
||||
.orderBy(asc(repeatProfiles.createdAt));
|
||||
|
||||
res.json({ profiles });
|
||||
}));
|
||||
|
||||
router.post('/', asyncHandler(async (req: Request, res: Response) => {
|
||||
const data = repeatProfileSchema.parse(req.body);
|
||||
const userId = req.user!.userId;
|
||||
const now = Date.now();
|
||||
|
||||
const newProfile = {
|
||||
id: generateId('rp'),
|
||||
userId,
|
||||
name: data.name,
|
||||
repeat: data.repeat,
|
||||
repeatInterval: data.repeatInterval,
|
||||
repeatDays: data.repeatDays,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
await db.insert(repeatProfiles).values(newProfile);
|
||||
|
||||
res.status(201).json(newProfile);
|
||||
}));
|
||||
|
||||
router.patch('/:id', asyncHandler(async (req: Request, res: Response) => {
|
||||
const data = repeatProfileUpdateSchema.parse(req.body);
|
||||
const userId = req.user!.userId;
|
||||
|
||||
const existing = await db
|
||||
.select()
|
||||
.from(repeatProfiles)
|
||||
.where(and(eq(repeatProfiles.id, req.params.id), eq(repeatProfiles.userId, userId)))
|
||||
.limit(1);
|
||||
|
||||
if (existing.length === 0) {
|
||||
throw new AppError('NOT_FOUND', 'Repeat profile not found', 404);
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const updated = await db
|
||||
.update(repeatProfiles)
|
||||
.set({ ...data, updatedAt: now })
|
||||
.where(and(eq(repeatProfiles.id, req.params.id), eq(repeatProfiles.userId, userId)))
|
||||
.returning();
|
||||
|
||||
res.json(updated[0]);
|
||||
}));
|
||||
|
||||
router.delete('/:id', asyncHandler(async (req: Request, res: Response) => {
|
||||
const userId = req.user!.userId;
|
||||
|
||||
const existing = await db
|
||||
.select()
|
||||
.from(repeatProfiles)
|
||||
.where(and(eq(repeatProfiles.id, req.params.id), eq(repeatProfiles.userId, userId)))
|
||||
.limit(1);
|
||||
|
||||
if (existing.length === 0) {
|
||||
throw new AppError('NOT_FOUND', 'Repeat profile not found', 404);
|
||||
}
|
||||
|
||||
await db
|
||||
.delete(repeatProfiles)
|
||||
.where(and(eq(repeatProfiles.id, req.params.id), eq(repeatProfiles.userId, userId)));
|
||||
|
||||
res.status(204).send();
|
||||
}));
|
||||
|
||||
export default router;
|
||||
@@ -0,0 +1,154 @@
|
||||
import { Router, Request, Response } from 'express';
|
||||
import { asyncHandler } from '../utils/asyncHandler';
|
||||
import { db } from '../db';
|
||||
import { subtasks, tasks } from '../db/schema';
|
||||
import { eq, and, asc, desc } from 'drizzle-orm';
|
||||
import { authMiddleware } from '../utils/auth';
|
||||
import { AppError } from '../middleware/errorHandler';
|
||||
import { subtaskCreateSchema, subtaskUpdateSchema } from '../utils/validation';
|
||||
|
||||
const router = Router();
|
||||
|
||||
router.use(authMiddleware);
|
||||
|
||||
router.get('/task/:taskId', asyncHandler(async (req: Request, res: Response) => {
|
||||
const userId = req.user!.userId;
|
||||
|
||||
// Verify task exists and belongs to user
|
||||
const task = await db
|
||||
.select()
|
||||
.from(tasks)
|
||||
.where(and(eq(tasks.id, req.params.taskId), eq(tasks.userId, userId)))
|
||||
.limit(1);
|
||||
|
||||
if (task.length === 0) {
|
||||
throw new AppError('NOT_FOUND', 'Task not found', 404);
|
||||
}
|
||||
|
||||
const taskSubtasks = await db
|
||||
.select()
|
||||
.from(subtasks)
|
||||
.where(and(eq(subtasks.taskId, req.params.taskId), eq(subtasks.userId, userId)))
|
||||
.orderBy(asc(subtasks.order));
|
||||
|
||||
res.json({ subtasks: taskSubtasks });
|
||||
}));
|
||||
|
||||
router.post('/task/:taskId', asyncHandler(async (req: Request, res: Response) => {
|
||||
const data = subtaskCreateSchema.parse(req.body);
|
||||
const userId = req.user!.userId;
|
||||
|
||||
const task = await db
|
||||
.select()
|
||||
.from(tasks)
|
||||
.where(and(eq(tasks.id, req.params.taskId), eq(tasks.userId, userId)))
|
||||
.limit(1);
|
||||
|
||||
if (task.length === 0) {
|
||||
throw new AppError('NOT_FOUND', 'Task not found', 404);
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const maxOrder = await db
|
||||
.select({ order: subtasks.order })
|
||||
.from(subtasks)
|
||||
.where(and(eq(subtasks.taskId, req.params.taskId), eq(subtasks.userId, userId)))
|
||||
.orderBy(desc(subtasks.order))
|
||||
.limit(1);
|
||||
|
||||
const subtaskId = `sub_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
|
||||
|
||||
const newSubtask = {
|
||||
id: subtaskId,
|
||||
userId,
|
||||
taskId: req.params.taskId,
|
||||
title: data.title,
|
||||
description: data.description ?? '',
|
||||
priority: data.priority ?? 'none',
|
||||
completed: false,
|
||||
dueDate: data.dueDate ?? 0,
|
||||
dueTime: data.dueTime ?? '',
|
||||
endTime: data.endTime ?? '',
|
||||
allDay: data.allDay ?? false,
|
||||
repeat: data.repeat ?? 'none',
|
||||
repeatInterval: data.repeatInterval ?? 1,
|
||||
repeatDays: data.repeatDays ?? '',
|
||||
seriesId: data.seriesId ?? '',
|
||||
reminder: data.reminder ?? 'none',
|
||||
reminders: data.reminders ?? '',
|
||||
assigneeId: data.assigneeId ?? null,
|
||||
order: data.order ?? (maxOrder[0]?.order ?? -1) + 1,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
await db.insert(subtasks).values(newSubtask);
|
||||
|
||||
// Update task updatedAt
|
||||
await db
|
||||
.update(tasks)
|
||||
.set({ updatedAt: now })
|
||||
.where(and(eq(tasks.id, req.params.taskId), eq(tasks.userId, userId)));
|
||||
|
||||
res.status(201).json(newSubtask);
|
||||
}));
|
||||
|
||||
router.patch('/:id', asyncHandler(async (req: Request, res: Response) => {
|
||||
const data = subtaskUpdateSchema.parse(req.body);
|
||||
const userId = req.user!.userId;
|
||||
|
||||
const existing = await db
|
||||
.select()
|
||||
.from(subtasks)
|
||||
.where(and(eq(subtasks.id, req.params.id), eq(subtasks.userId, userId)))
|
||||
.limit(1);
|
||||
|
||||
if (existing.length === 0) {
|
||||
throw new AppError('NOT_FOUND', 'Subtask not found', 404);
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const updated = await db
|
||||
.update(subtasks)
|
||||
.set({ ...data, updatedAt: now })
|
||||
.where(and(eq(subtasks.id, req.params.id), eq(subtasks.userId, userId)))
|
||||
.returning();
|
||||
|
||||
// Update task updatedAt
|
||||
await db
|
||||
.update(tasks)
|
||||
.set({ updatedAt: now })
|
||||
.where(and(eq(tasks.id, existing[0].taskId), eq(tasks.userId, userId)));
|
||||
|
||||
res.json(updated[0]);
|
||||
}));
|
||||
|
||||
router.delete('/:id', asyncHandler(async (req: Request, res: Response) => {
|
||||
const userId = req.user!.userId;
|
||||
|
||||
const existing = await db
|
||||
.select()
|
||||
.from(subtasks)
|
||||
.where(and(eq(subtasks.id, req.params.id), eq(subtasks.userId, userId)))
|
||||
.limit(1);
|
||||
|
||||
if (existing.length === 0) {
|
||||
throw new AppError('NOT_FOUND', 'Subtask not found', 404);
|
||||
}
|
||||
|
||||
const taskId = existing[0].taskId;
|
||||
|
||||
await db
|
||||
.delete(subtasks)
|
||||
.where(and(eq(subtasks.id, req.params.id), eq(subtasks.userId, userId)));
|
||||
|
||||
// Update task updatedAt
|
||||
await db
|
||||
.update(tasks)
|
||||
.set({ updatedAt: Date.now() })
|
||||
.where(and(eq(tasks.id, taskId), eq(tasks.userId, userId)));
|
||||
|
||||
res.status(204).send();
|
||||
}));
|
||||
|
||||
export default router;
|
||||
@@ -0,0 +1,381 @@
|
||||
import { Router, Request, Response } from 'express';
|
||||
import { asyncHandler } from '../utils/asyncHandler';
|
||||
import { db } from '../db';
|
||||
import { categories, tasks, subtasks, repeatProfiles, users, friendships } from '../db/schema';
|
||||
import { eq, and, gte, lte, asc, or, inArray, sql } from 'drizzle-orm';
|
||||
import { authMiddleware } from '../utils/auth';
|
||||
import { AppError } from '../middleware/errorHandler';
|
||||
import { syncQuerySchema, pushChangesSchema, canCompleteTask } from '../utils/validation';
|
||||
|
||||
const router = Router();
|
||||
|
||||
router.use(authMiddleware);
|
||||
|
||||
router.get('/', asyncHandler(async (req: Request, res: Response) => {
|
||||
const { since } = syncQuerySchema.parse(req.query);
|
||||
const userId = req.user!.userId;
|
||||
|
||||
const sinceDate = since;
|
||||
|
||||
// Fetch categories changed since timestamp
|
||||
const changedCategories = await db
|
||||
.select()
|
||||
.from(categories)
|
||||
.where(and(eq(categories.userId, userId), gte(categories.updatedAt, sinceDate)))
|
||||
.orderBy(asc(categories.updatedAt));
|
||||
|
||||
// Fetch tasks changed since timestamp
|
||||
const changedTasks = await db
|
||||
.select()
|
||||
.from(tasks)
|
||||
.where(and(eq(tasks.userId, userId), gte(tasks.updatedAt, sinceDate)))
|
||||
.orderBy(asc(tasks.updatedAt));
|
||||
|
||||
// Fetch subtasks changed since timestamp
|
||||
const taskIds = changedTasks.map(t => t.id);
|
||||
let changedSubtasks: any[] = [];
|
||||
|
||||
if (taskIds.length > 0) {
|
||||
changedSubtasks = await db
|
||||
.select()
|
||||
.from(subtasks)
|
||||
.where(and(eq(subtasks.userId, userId), gte(subtasks.updatedAt, sinceDate)))
|
||||
.orderBy(asc(subtasks.updatedAt));
|
||||
} else {
|
||||
// Also fetch subtasks for tasks that might have been deleted (we track by updatedAt)
|
||||
changedSubtasks = await db
|
||||
.select()
|
||||
.from(subtasks)
|
||||
.where(and(eq(subtasks.userId, userId), gte(subtasks.updatedAt, sinceDate)))
|
||||
.orderBy(asc(subtasks.updatedAt));
|
||||
}
|
||||
|
||||
// Fetch repeat profiles changed since timestamp
|
||||
const changedRepeatProfiles = await db
|
||||
.select()
|
||||
.from(repeatProfiles)
|
||||
.where(and(eq(repeatProfiles.userId, userId), gte(repeatProfiles.updatedAt, sinceDate)))
|
||||
.orderBy(asc(repeatProfiles.updatedAt));
|
||||
|
||||
// Fetch friendships changed since timestamp
|
||||
const changedFriendships = await db
|
||||
.select()
|
||||
.from(friendships)
|
||||
.where(and(
|
||||
or(eq(friendships.userId, userId), eq(friendships.friendId, userId)),
|
||||
gte(friendships.updatedAt, sinceDate)
|
||||
))
|
||||
.orderBy(asc(friendships.updatedAt));
|
||||
|
||||
const timestamp = Date.now();
|
||||
|
||||
res.json({
|
||||
categories: changedCategories,
|
||||
tasks: changedTasks,
|
||||
subtasks: changedSubtasks,
|
||||
repeatProfiles: changedRepeatProfiles,
|
||||
friendships: changedFriendships,
|
||||
timestamp,
|
||||
});
|
||||
}));
|
||||
|
||||
router.post('/push', asyncHandler(async (req: Request, res: Response) => {
|
||||
const data = pushChangesSchema.parse(req.body);
|
||||
const userId = req.user!.userId;
|
||||
const conflicts: any[] = [];
|
||||
const timestamp = Date.now();
|
||||
|
||||
try {
|
||||
await db.transaction(async (tx) => {
|
||||
// Ensure every referenced category exists (FK integrity) so a stale or
|
||||
// never-synced category reference cannot fail the entire push. Missing
|
||||
// categories are recreated as a fallback and the client heals on pull.
|
||||
const referencedCategoryIds = new Set<string>();
|
||||
for (const task of data.changes.tasks ?? []) {
|
||||
if (task.categoryId) referencedCategoryIds.add(task.categoryId);
|
||||
}
|
||||
for (const sub of data.changes.subtasks ?? []) {
|
||||
const task = (data.changes.tasks ?? []).find((t) => t.id === sub.taskId);
|
||||
if (task?.categoryId) referencedCategoryIds.add(task.categoryId);
|
||||
}
|
||||
if (referencedCategoryIds.size > 0) {
|
||||
const existing = await tx
|
||||
.select({ id: categories.id })
|
||||
.from(categories)
|
||||
.where(inArray(categories.id, [...referencedCategoryIds]));
|
||||
const existingIds = new Set(existing.map((c) => c.id));
|
||||
const missing = [...referencedCategoryIds].filter((id) => !existingIds.has(id));
|
||||
if (missing.length > 0) {
|
||||
const rows = await tx
|
||||
.select({ max: sql<number>`max(${categories.order})` })
|
||||
.from(categories)
|
||||
.where(eq(categories.userId, userId));
|
||||
const startOrder = (rows[0]?.max ?? -1) + 1;
|
||||
await tx.insert(categories).values(
|
||||
missing.map((id, i) => ({
|
||||
id,
|
||||
userId,
|
||||
name: 'Default',
|
||||
color: '#9E9E9E',
|
||||
order: startOrder + i,
|
||||
createdAt: Date.now(),
|
||||
updatedAt: Date.now(),
|
||||
}))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Process categories
|
||||
if (data.changes.categories && data.changes.categories.length > 0) {
|
||||
for (const cat of data.changes.categories) {
|
||||
const existing = await tx
|
||||
.select()
|
||||
.from(categories)
|
||||
.where(and(eq(categories.id, cat.id), eq(categories.userId, userId)))
|
||||
.limit(1);
|
||||
|
||||
if (existing.length > 0) {
|
||||
// Check for conflict
|
||||
if (existing[0].updatedAt > cat.updatedAt) {
|
||||
conflicts.push({
|
||||
entity: 'categories',
|
||||
id: cat.id,
|
||||
serverVersion: existing[0],
|
||||
clientVersion: cat,
|
||||
resolution: 'server_wins',
|
||||
});
|
||||
continue; // Server wins
|
||||
}
|
||||
|
||||
await tx
|
||||
.update(categories)
|
||||
.set({
|
||||
name: cat.name,
|
||||
color: cat.color,
|
||||
order: cat.order,
|
||||
updatedAt: cat.updatedAt,
|
||||
})
|
||||
.where(and(eq(categories.id, cat.id), eq(categories.userId, userId)));
|
||||
} else {
|
||||
await tx.insert(categories).values({
|
||||
...cat,
|
||||
userId,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Process tasks
|
||||
if (data.changes.tasks && data.changes.tasks.length > 0) {
|
||||
for (const task of data.changes.tasks) {
|
||||
const existing = await tx
|
||||
.select()
|
||||
.from(tasks)
|
||||
.where(and(eq(tasks.id, task.id), eq(tasks.userId, userId)))
|
||||
.limit(1);
|
||||
|
||||
if (existing.length > 0) {
|
||||
// Check for conflict
|
||||
if (existing[0].updatedAt > task.updatedAt) {
|
||||
conflicts.push({
|
||||
entity: 'tasks',
|
||||
id: task.id,
|
||||
serverVersion: existing[0],
|
||||
clientVersion: task,
|
||||
resolution: 'server_wins',
|
||||
});
|
||||
continue; // Server wins
|
||||
}
|
||||
|
||||
// Prevent completing tasks with future due dates
|
||||
if (task.completed === true) {
|
||||
const effectiveDueDate = task.dueDate ?? existing[0].dueDate;
|
||||
if (!canCompleteTask(effectiveDueDate)) {
|
||||
conflicts.push({
|
||||
entity: 'tasks',
|
||||
id: task.id,
|
||||
serverVersion: existing[0],
|
||||
clientVersion: task,
|
||||
resolution: 'server_wins',
|
||||
});
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
await tx
|
||||
.update(tasks)
|
||||
.set({
|
||||
title: task.title,
|
||||
description: task.description,
|
||||
categoryId: task.categoryId,
|
||||
priority: task.priority,
|
||||
completed: task.completed,
|
||||
dueDate: task.dueDate,
|
||||
dueTime: task.dueTime ?? '',
|
||||
endTime: task.endTime ?? '',
|
||||
allDay: task.allDay ?? false,
|
||||
repeat: task.repeat ?? 'none',
|
||||
repeatInterval: task.repeatInterval ?? 1,
|
||||
repeatDays: task.repeatDays ?? '',
|
||||
seriesId: task.seriesId ?? '',
|
||||
reminder: task.reminder ?? 'none',
|
||||
reminders: task.reminders ?? '',
|
||||
assigneeId: task.assigneeId ?? null,
|
||||
updatedAt: task.updatedAt,
|
||||
})
|
||||
.where(and(eq(tasks.id, task.id), eq(tasks.userId, userId)));
|
||||
} else {
|
||||
await tx.insert(tasks).values({
|
||||
...task,
|
||||
allDay: task.allDay ?? false,
|
||||
userId,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Process subtasks
|
||||
if (data.changes.subtasks && data.changes.subtasks.length > 0) {
|
||||
for (const sub of data.changes.subtasks) {
|
||||
const existing = await tx
|
||||
.select()
|
||||
.from(subtasks)
|
||||
.where(and(eq(subtasks.id, sub.id), eq(subtasks.userId, userId)))
|
||||
.limit(1);
|
||||
|
||||
if (existing.length > 0) {
|
||||
// Check for conflict
|
||||
if (existing[0].updatedAt > sub.updatedAt) {
|
||||
conflicts.push({
|
||||
entity: 'subtasks',
|
||||
id: sub.id,
|
||||
serverVersion: existing[0],
|
||||
clientVersion: sub,
|
||||
resolution: 'server_wins',
|
||||
});
|
||||
continue; // Server wins
|
||||
}
|
||||
|
||||
await tx
|
||||
.update(subtasks)
|
||||
.set({
|
||||
taskId: sub.taskId,
|
||||
title: sub.title,
|
||||
description: sub.description ?? '',
|
||||
priority: sub.priority ?? 'none',
|
||||
completed: sub.completed,
|
||||
dueDate: sub.dueDate ?? 0,
|
||||
dueTime: sub.dueTime ?? '',
|
||||
endTime: sub.endTime ?? '',
|
||||
allDay: sub.allDay ?? false,
|
||||
repeat: sub.repeat ?? 'none',
|
||||
repeatInterval: sub.repeatInterval ?? 1,
|
||||
repeatDays: sub.repeatDays ?? '',
|
||||
seriesId: sub.seriesId ?? '',
|
||||
reminder: sub.reminder ?? 'none',
|
||||
reminders: sub.reminders ?? '',
|
||||
assigneeId: sub.assigneeId ?? null,
|
||||
order: sub.order,
|
||||
updatedAt: sub.updatedAt,
|
||||
})
|
||||
.where(and(eq(subtasks.id, sub.id), eq(subtasks.userId, userId)));
|
||||
} else {
|
||||
await tx.insert(subtasks).values({
|
||||
...sub,
|
||||
userId,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Process repeat profiles
|
||||
if (data.changes.repeatProfiles && data.changes.repeatProfiles.length > 0) {
|
||||
for (const profile of data.changes.repeatProfiles) {
|
||||
const existing = await tx
|
||||
.select()
|
||||
.from(repeatProfiles)
|
||||
.where(and(eq(repeatProfiles.id, profile.id), eq(repeatProfiles.userId, userId)))
|
||||
.limit(1);
|
||||
|
||||
if (existing.length > 0) {
|
||||
// Check for conflict
|
||||
if (existing[0].updatedAt > profile.updatedAt) {
|
||||
conflicts.push({
|
||||
entity: 'repeatProfiles',
|
||||
id: profile.id,
|
||||
serverVersion: existing[0],
|
||||
clientVersion: profile,
|
||||
resolution: 'server_wins',
|
||||
});
|
||||
continue; // Server wins
|
||||
}
|
||||
|
||||
await tx
|
||||
.update(repeatProfiles)
|
||||
.set({
|
||||
name: profile.name,
|
||||
repeat: profile.repeat,
|
||||
repeatInterval: profile.repeatInterval,
|
||||
repeatDays: profile.repeatDays,
|
||||
updatedAt: profile.updatedAt,
|
||||
})
|
||||
.where(and(eq(repeatProfiles.id, profile.id), eq(repeatProfiles.userId, userId)));
|
||||
} else {
|
||||
await tx.insert(repeatProfiles).values({
|
||||
...profile,
|
||||
userId,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Process friendships
|
||||
if (data.changes.friendships && data.changes.friendships.length > 0) {
|
||||
for (const friendship of data.changes.friendships) {
|
||||
const existing = await tx
|
||||
.select()
|
||||
.from(friendships)
|
||||
.where(eq(friendships.id, friendship.id))
|
||||
.limit(1);
|
||||
|
||||
if (existing.length > 0) {
|
||||
// Check for conflict
|
||||
if (existing[0].updatedAt > friendship.updatedAt) {
|
||||
conflicts.push({
|
||||
entity: 'friendships',
|
||||
id: friendship.id,
|
||||
serverVersion: existing[0],
|
||||
clientVersion: friendship,
|
||||
resolution: 'server_wins',
|
||||
});
|
||||
continue; // Server wins
|
||||
}
|
||||
|
||||
await tx
|
||||
.update(friendships)
|
||||
.set({
|
||||
userId: friendship.userId,
|
||||
friendId: friendship.friendId,
|
||||
status: friendship.status,
|
||||
updatedAt: friendship.updatedAt,
|
||||
})
|
||||
.where(eq(friendships.id, friendship.id));
|
||||
} else {
|
||||
await tx.insert(friendships).values(friendship);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Sync push error:', error);
|
||||
throw new AppError('SERVER_ERROR', 'Failed to process sync push', 500);
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
timestamp,
|
||||
conflicts,
|
||||
});
|
||||
}));
|
||||
|
||||
export default router;
|
||||
@@ -0,0 +1,326 @@
|
||||
import { Router, Request, Response } from 'express';
|
||||
import { asyncHandler } from '../utils/asyncHandler';
|
||||
import { db } from '../db';
|
||||
import { tasks, subtasks, categories } from '../db/schema';
|
||||
import { eq, and, desc, asc, gte, lte, inArray, sql } from 'drizzle-orm';
|
||||
import { authMiddleware } from '../utils/auth';
|
||||
import { AppError } from '../middleware/errorHandler';
|
||||
import { taskCreateSchema, taskUpdateSchema, taskQuerySchema, canCompleteTask } from '../utils/validation';
|
||||
import { z } from 'zod';
|
||||
|
||||
const router = Router();
|
||||
|
||||
router.use(authMiddleware);
|
||||
|
||||
function applyTaskFilters(query: any, userId: string, filters: any) {
|
||||
const conditions = [eq(tasks.userId, userId)];
|
||||
|
||||
if (filters.categoryId) {
|
||||
conditions.push(eq(tasks.categoryId, filters.categoryId));
|
||||
}
|
||||
if (filters.completed !== undefined) {
|
||||
conditions.push(eq(tasks.completed, filters.completed));
|
||||
}
|
||||
if (filters.dueBefore) {
|
||||
conditions.push(lte(tasks.dueDate, filters.dueBefore));
|
||||
}
|
||||
if (filters.dueAfter) {
|
||||
conditions.push(gte(tasks.dueDate, filters.dueAfter));
|
||||
}
|
||||
if (filters.priority) {
|
||||
conditions.push(eq(tasks.priority, filters.priority));
|
||||
}
|
||||
|
||||
return query.where(and(...conditions));
|
||||
}
|
||||
|
||||
function applyTaskSorting(query: any, sortBy: string = 'dueDate', sortOrder: string = 'asc') {
|
||||
const orderFn = sortOrder === 'desc' ? desc : asc;
|
||||
const columnMap: Record<string, any> = {
|
||||
dueDate: tasks.dueDate,
|
||||
priority: tasks.priority,
|
||||
createdAt: tasks.createdAt,
|
||||
title: tasks.title,
|
||||
};
|
||||
return query.orderBy(orderFn(columnMap[sortBy] || tasks.dueDate));
|
||||
}
|
||||
|
||||
router.get('/', asyncHandler(async (req: Request, res: Response) => {
|
||||
const filters = taskQuerySchema.parse(req.query);
|
||||
const userId = req.user!.userId;
|
||||
|
||||
let query: any = db.select().from(tasks);
|
||||
query = applyTaskFilters(query, userId, filters);
|
||||
query = applyTaskSorting(query, filters.sortBy, filters.sortOrder);
|
||||
|
||||
const limit = filters.limit ?? 50;
|
||||
const offset = filters.offset ?? 0;
|
||||
query = query.limit(limit).offset(offset);
|
||||
|
||||
const results = await query;
|
||||
|
||||
// Fetch subtasks for each task
|
||||
const taskIds = results.map((t: { id: string }) => t.id);
|
||||
let taskSubtasks: any[] = [];
|
||||
if (taskIds.length > 0) {
|
||||
taskSubtasks = await db
|
||||
.select()
|
||||
.from(subtasks)
|
||||
.where(and(eq(subtasks.userId, userId), inArray(subtasks.taskId, taskIds)))
|
||||
.orderBy(asc(subtasks.order));
|
||||
}
|
||||
|
||||
const subtasksByTask = taskSubtasks.reduce((acc, st) => {
|
||||
if (!acc[st.taskId]) acc[st.taskId] = [];
|
||||
acc[st.taskId].push(st);
|
||||
return acc;
|
||||
}, {} as Record<string, any[]>);
|
||||
|
||||
const tasksWithSubtasks = results.map((task: any) => ({
|
||||
...task,
|
||||
subtasks: subtasksByTask[task.id] || [],
|
||||
}));
|
||||
|
||||
// Get total count
|
||||
const countQuery: any = db.select({ count: sql`count(*)` }).from(tasks);
|
||||
const countResult = await applyTaskFilters(countQuery, userId, filters);
|
||||
const total = Number(countResult[0]?.count ?? 0);
|
||||
|
||||
res.json({ tasks: tasksWithSubtasks, total, limit, offset });
|
||||
}));
|
||||
|
||||
router.get('/:id', asyncHandler(async (req: Request, res: Response) => {
|
||||
const userId = req.user!.userId;
|
||||
|
||||
const task = await db
|
||||
.select()
|
||||
.from(tasks)
|
||||
.where(and(eq(tasks.id, req.params.id), eq(tasks.userId, userId)))
|
||||
.limit(1);
|
||||
|
||||
if (task.length === 0) {
|
||||
throw new AppError('NOT_FOUND', 'Task not found', 404);
|
||||
}
|
||||
|
||||
const taskSubtasks = await db
|
||||
.select()
|
||||
.from(subtasks)
|
||||
.where(and(eq(subtasks.taskId, req.params.id), eq(subtasks.userId, userId)))
|
||||
.orderBy(asc(subtasks.order));
|
||||
|
||||
res.json({ ...task[0], subtasks: taskSubtasks });
|
||||
}));
|
||||
|
||||
router.post('/', asyncHandler(async (req: Request, res: Response) => {
|
||||
const data = taskCreateSchema.parse(req.body);
|
||||
const userId = req.user!.userId;
|
||||
const now = Date.now();
|
||||
|
||||
// Verify category exists and belongs to user
|
||||
const cat = await db
|
||||
.select()
|
||||
.from(categories)
|
||||
.where(and(eq(categories.id, data.categoryId), eq(categories.userId, userId)))
|
||||
.limit(1);
|
||||
|
||||
if (cat.length === 0) {
|
||||
throw new AppError('NOT_FOUND', 'Category not found', 404);
|
||||
}
|
||||
|
||||
const taskId = `task_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
|
||||
|
||||
const newTask = {
|
||||
id: taskId,
|
||||
userId,
|
||||
categoryId: data.categoryId,
|
||||
title: data.title,
|
||||
description: data.description ?? '',
|
||||
priority: data.priority ?? 'none',
|
||||
completed: false,
|
||||
dueDate: data.dueDate ?? 0,
|
||||
dueTime: data.dueTime ?? '',
|
||||
endTime: data.endTime ?? '',
|
||||
allDay: data.allDay ?? false,
|
||||
assigneeId: data.assigneeId ?? null,
|
||||
reminder: data.reminder ?? 'none',
|
||||
reminders: data.reminders ?? '',
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
await db.insert(tasks).values(newTask);
|
||||
|
||||
// Create subtasks if provided
|
||||
if (data.subtasks && data.subtasks.length > 0) {
|
||||
const subtaskValues = data.subtasks.map((st, index) => ({
|
||||
id: `sub_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}${index}`,
|
||||
userId,
|
||||
taskId,
|
||||
title: st.title,
|
||||
completed: false,
|
||||
order: index,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
}));
|
||||
await db.insert(subtasks).values(subtaskValues);
|
||||
}
|
||||
|
||||
const createdSubtasks = await db
|
||||
.select()
|
||||
.from(subtasks)
|
||||
.where(and(eq(subtasks.taskId, taskId), eq(subtasks.userId, userId)))
|
||||
.orderBy(asc(subtasks.order));
|
||||
|
||||
res.status(201).json({ ...newTask, subtasks: createdSubtasks });
|
||||
}));
|
||||
|
||||
router.patch('/:id', asyncHandler(async (req: Request, res: Response) => {
|
||||
const data = taskUpdateSchema.parse(req.body);
|
||||
const userId = req.user!.userId;
|
||||
|
||||
const existing = await db
|
||||
.select()
|
||||
.from(tasks)
|
||||
.where(and(eq(tasks.id, req.params.id), eq(tasks.userId, userId)))
|
||||
.limit(1);
|
||||
|
||||
if (existing.length === 0) {
|
||||
throw new AppError('NOT_FOUND', 'Task not found', 404);
|
||||
}
|
||||
|
||||
// Verify category if provided
|
||||
if (data.categoryId) {
|
||||
const cat = await db
|
||||
.select()
|
||||
.from(categories)
|
||||
.where(and(eq(categories.id, data.categoryId), eq(categories.userId, userId)))
|
||||
.limit(1);
|
||||
if (cat.length === 0) {
|
||||
throw new AppError('NOT_FOUND', 'Category not found', 404);
|
||||
}
|
||||
}
|
||||
|
||||
// Prevent completing tasks with future due dates
|
||||
if (data.completed === true) {
|
||||
const effectiveDueDate = data.dueDate ?? existing[0].dueDate;
|
||||
if (!canCompleteTask(effectiveDueDate)) {
|
||||
throw new AppError('VALIDATION_ERROR', 'Cannot mark a task as completed if its due date is in the future', 400);
|
||||
}
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const updated = await db
|
||||
.update(tasks)
|
||||
.set({ ...data, updatedAt: now })
|
||||
.where(and(eq(tasks.id, req.params.id), eq(tasks.userId, userId)))
|
||||
.returning();
|
||||
|
||||
const taskSubtasks = await db
|
||||
.select()
|
||||
.from(subtasks)
|
||||
.where(and(eq(subtasks.taskId, req.params.id), eq(subtasks.userId, userId)))
|
||||
.orderBy(asc(subtasks.order));
|
||||
|
||||
res.json({ ...updated[0], subtasks: taskSubtasks });
|
||||
}));
|
||||
|
||||
router.delete('/:id', asyncHandler(async (req: Request, res: Response) => {
|
||||
const userId = req.user!.userId;
|
||||
|
||||
const existing = await db
|
||||
.select()
|
||||
.from(tasks)
|
||||
.where(and(eq(tasks.id, req.params.id), eq(tasks.userId, userId)))
|
||||
.limit(1);
|
||||
|
||||
if (existing.length === 0) {
|
||||
throw new AppError('NOT_FOUND', 'Task not found', 404);
|
||||
}
|
||||
|
||||
await db
|
||||
.delete(tasks)
|
||||
.where(and(eq(tasks.id, req.params.id), eq(tasks.userId, userId)));
|
||||
|
||||
res.status(204).send();
|
||||
}));
|
||||
|
||||
router.post('/batch', asyncHandler(async (req: Request, res: Response) => {
|
||||
const { operations } = z.object({
|
||||
operations: z.array(
|
||||
z.union([
|
||||
z.object({ type: z.literal('create'), data: taskCreateSchema }),
|
||||
z.object({ type: z.literal('update'), id: z.string(), data: taskUpdateSchema }),
|
||||
z.object({ type: z.literal('delete'), id: z.string() }),
|
||||
])
|
||||
),
|
||||
}).parse(req.body);
|
||||
|
||||
const userId = req.user!.userId;
|
||||
const results: any[] = [];
|
||||
|
||||
for (const op of operations) {
|
||||
try {
|
||||
if (op.type === 'create') {
|
||||
const cat = await db
|
||||
.select()
|
||||
.from(categories)
|
||||
.where(and(eq(categories.id, op.data.categoryId), eq(categories.userId, userId)))
|
||||
.limit(1);
|
||||
if (cat.length === 0) throw new AppError('NOT_FOUND', 'Category not found', 404);
|
||||
|
||||
const taskId = `task_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
|
||||
const now = Date.now();
|
||||
|
||||
await db.insert(tasks).values({
|
||||
id: taskId,
|
||||
userId,
|
||||
...op.data,
|
||||
completed: false,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
|
||||
results.push({ id: taskId, success: true });
|
||||
} else if (op.type === 'update') {
|
||||
if (op.data.completed === true) {
|
||||
let effectiveDueDate: number;
|
||||
if (op.data.dueDate !== undefined) {
|
||||
effectiveDueDate = op.data.dueDate;
|
||||
} else {
|
||||
const existingTask = await db
|
||||
.select({ dueDate: tasks.dueDate })
|
||||
.from(tasks)
|
||||
.where(and(eq(tasks.id, op.id), eq(tasks.userId, userId)))
|
||||
.limit(1);
|
||||
if (existingTask.length === 0) throw new AppError('NOT_FOUND', 'Task not found', 404);
|
||||
effectiveDueDate = existingTask[0].dueDate;
|
||||
}
|
||||
if (!canCompleteTask(effectiveDueDate)) {
|
||||
throw new AppError('VALIDATION_ERROR', 'Cannot mark a task as completed if its due date is in the future', 400);
|
||||
}
|
||||
}
|
||||
|
||||
await db
|
||||
.update(tasks)
|
||||
.set({ ...op.data, updatedAt: Date.now() })
|
||||
.where(and(eq(tasks.id, op.id), eq(tasks.userId, userId)));
|
||||
results.push({ id: op.id, success: true });
|
||||
} else if (op.type === 'delete') {
|
||||
await db
|
||||
.delete(tasks)
|
||||
.where(and(eq(tasks.id, op.id), eq(tasks.userId, userId)));
|
||||
results.push({ id: op.id, success: true });
|
||||
}
|
||||
} catch (error) {
|
||||
results.push({
|
||||
id: 'id' in op ? op.id : 'unknown',
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Unknown error'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
res.json({ results });
|
||||
}));
|
||||
|
||||
export default router;
|
||||
@@ -0,0 +1,111 @@
|
||||
import { Router, Request, Response } from 'express';
|
||||
import { asyncHandler } from '../utils/asyncHandler';
|
||||
import { db } from '../db';
|
||||
import { users, userSettings, categories } from '../db/schema';
|
||||
import { eq, and, ilike } from 'drizzle-orm';
|
||||
import { authMiddleware } from '../utils/auth';
|
||||
import { AppError } from '../middleware/errorHandler';
|
||||
import { userSettingsSchema } from '../utils/validation';
|
||||
|
||||
const router = Router();
|
||||
|
||||
router.use(authMiddleware);
|
||||
|
||||
router.get('/me', asyncHandler(async (req: Request, res: Response) => {
|
||||
const userId = req.user!.userId;
|
||||
|
||||
const user = await db.select().from(users).where(eq(users.id, userId)).limit(1);
|
||||
if (user.length === 0) {
|
||||
throw new AppError('NOT_FOUND', 'User not found', 404);
|
||||
}
|
||||
|
||||
const settings = await db
|
||||
.select()
|
||||
.from(userSettings)
|
||||
.where(eq(userSettings.userId, userId))
|
||||
.limit(1);
|
||||
|
||||
let defaultCategory = settings[0]?.defaultCategory;
|
||||
if (defaultCategory) {
|
||||
const cat = await db
|
||||
.select()
|
||||
.from(categories)
|
||||
.where(and(eq(categories.id, defaultCategory), eq(categories.userId, userId)))
|
||||
.limit(1);
|
||||
if (cat.length === 0) {
|
||||
defaultCategory = null;
|
||||
}
|
||||
}
|
||||
|
||||
res.json({
|
||||
id: user[0].id,
|
||||
username: user[0].username,
|
||||
settings: {
|
||||
darkMode: settings[0]?.darkMode ?? false,
|
||||
notifications: settings[0]?.notifications ?? true,
|
||||
reminderTime: settings[0]?.reminderTime ?? '09:00',
|
||||
defaultCategory,
|
||||
sortBy: settings[0]?.sortBy ?? 'dueDate',
|
||||
sortOrder: settings[0]?.sortOrder ?? 'asc',
|
||||
},
|
||||
createdAt: user[0].createdAt,
|
||||
});
|
||||
}));
|
||||
|
||||
router.patch('/me/settings', asyncHandler(async (req: Request, res: Response) => {
|
||||
const data = userSettingsSchema.parse(req.body);
|
||||
const userId = req.user!.userId;
|
||||
|
||||
// Validate defaultCategory if provided
|
||||
if (data.defaultCategory) {
|
||||
const cat = await db
|
||||
.select()
|
||||
.from(categories)
|
||||
.where(and(eq(categories.id, data.defaultCategory), eq(categories.userId, userId)))
|
||||
.limit(1);
|
||||
if (cat.length === 0) {
|
||||
throw new AppError('NOT_FOUND', 'Default category not found', 404);
|
||||
}
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const existing = await db
|
||||
.select()
|
||||
.from(userSettings)
|
||||
.where(eq(userSettings.userId, userId))
|
||||
.limit(1);
|
||||
|
||||
if (existing.length === 0) {
|
||||
await db.insert(userSettings).values({
|
||||
userId,
|
||||
...data,
|
||||
updatedAt: now,
|
||||
});
|
||||
} else {
|
||||
await db
|
||||
.update(userSettings)
|
||||
.set({ ...data, updatedAt: now })
|
||||
.where(eq(userSettings.userId, userId));
|
||||
}
|
||||
|
||||
res.status(200).json({ success: true });
|
||||
}));
|
||||
|
||||
router.get('/search', asyncHandler(async (req: Request, res: Response) => {
|
||||
const { q } = req.query;
|
||||
const userId = req.user!.userId;
|
||||
|
||||
if (!q || typeof q !== 'string' || q.length < 2) {
|
||||
return res.json([]);
|
||||
}
|
||||
|
||||
const results = await db
|
||||
.select({ id: users.id, username: users.username })
|
||||
.from(users)
|
||||
.where(and(ilike(users.username, `%${q}%`), eq(users.id, userId)))
|
||||
.limit(10);
|
||||
|
||||
res.json(results);
|
||||
}));
|
||||
|
||||
export default router;
|
||||
@@ -0,0 +1,91 @@
|
||||
export interface Category {
|
||||
id: string;
|
||||
name: string;
|
||||
color: string;
|
||||
order: number;
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
}
|
||||
|
||||
export interface Task {
|
||||
id: string;
|
||||
title: string;
|
||||
description: string;
|
||||
categoryId: string;
|
||||
priority: 'none' | 'low' | 'medium' | 'high' | 'critical';
|
||||
completed: boolean;
|
||||
dueDate: number;
|
||||
dueTime: string;
|
||||
endTime: string;
|
||||
assigneeId: string | null;
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
subtasks?: Subtask[];
|
||||
}
|
||||
|
||||
export interface Subtask {
|
||||
id: string;
|
||||
taskId: string;
|
||||
title: string;
|
||||
completed: boolean;
|
||||
order: number;
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
}
|
||||
|
||||
export interface UserSettings {
|
||||
darkMode: boolean;
|
||||
notifications: boolean;
|
||||
reminderTime: string;
|
||||
defaultCategory: string | null;
|
||||
sortBy: 'dueDate' | 'priority' | 'title' | 'createdAt';
|
||||
sortOrder: 'asc' | 'desc';
|
||||
}
|
||||
|
||||
export interface User {
|
||||
id: string;
|
||||
username: string;
|
||||
settings: UserSettings;
|
||||
createdAt: number;
|
||||
}
|
||||
|
||||
export interface SyncResponse {
|
||||
categories: Category[];
|
||||
tasks: Task[];
|
||||
subtasks: Subtask[];
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
export interface PushChangesRequest {
|
||||
changes: {
|
||||
categories: Category[];
|
||||
tasks: Task[];
|
||||
subtasks: Subtask[];
|
||||
};
|
||||
lastPulledAt: number;
|
||||
}
|
||||
|
||||
export interface PushChangesResponse {
|
||||
success: boolean;
|
||||
timestamp: number;
|
||||
conflicts: Array<{
|
||||
entity: string;
|
||||
id: string;
|
||||
serverVersion: any;
|
||||
clientVersion: any;
|
||||
resolution: 'server_wins' | 'client_wins' | 'merge';
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface AuthPayload {
|
||||
userId: string;
|
||||
username: string;
|
||||
}
|
||||
|
||||
declare global {
|
||||
namespace Express {
|
||||
interface Request {
|
||||
user?: AuthPayload;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
|
||||
type AsyncHandler = (req: Request, res: Response, next: NextFunction) => Promise<unknown>;
|
||||
|
||||
export function asyncHandler(handler: AsyncHandler) {
|
||||
return (req: Request, res: Response, next: NextFunction): void => {
|
||||
handler(req, res, next).catch(next);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { db } from '../db';
|
||||
import { users } from '../db/schema';
|
||||
import { eq } from 'drizzle-orm';
|
||||
import { AuthPayload } from '../types';
|
||||
|
||||
const JWT_SECRET = process.env.JWT_SECRET || 'your-super-secret-jwt-key-change-in-production';
|
||||
const JWT_EXPIRES_IN = '7d';
|
||||
|
||||
export function generateToken(payload: AuthPayload): string {
|
||||
return jwt.sign(payload, JWT_SECRET, { expiresIn: JWT_EXPIRES_IN });
|
||||
}
|
||||
|
||||
export function verifyToken(token: string): AuthPayload | null {
|
||||
try {
|
||||
return jwt.verify(token, JWT_SECRET) as AuthPayload;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function authMiddleware(req: Request, res: Response, next: NextFunction): Promise<void> {
|
||||
const authHeader = req.headers.authorization;
|
||||
|
||||
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
||||
res.status(401).json({
|
||||
error: {
|
||||
code: 'UNAUTHORIZED',
|
||||
message: 'Missing or invalid authorization header',
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const token = authHeader.slice(7);
|
||||
const payload = verifyToken(token);
|
||||
|
||||
if (!payload) {
|
||||
res.status(401).json({
|
||||
error: {
|
||||
code: 'UNAUTHORIZED',
|
||||
message: 'Invalid or expired token',
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const user = await db.select({ id: users.id }).from(users).where(eq(users.id, payload.userId)).limit(1);
|
||||
if (user.length === 0) {
|
||||
res.status(401).json({
|
||||
error: {
|
||||
code: 'UNAUTHORIZED',
|
||||
message: 'User no longer exists, please log in again',
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
req.user = payload;
|
||||
next();
|
||||
}
|
||||
|
||||
export function optionalAuthMiddleware(req: Request, res: Response, next: NextFunction): void {
|
||||
const authHeader = req.headers.authorization;
|
||||
|
||||
if (authHeader && authHeader.startsWith('Bearer ')) {
|
||||
const token = authHeader.slice(7);
|
||||
const payload = verifyToken(token);
|
||||
if (payload) {
|
||||
req.user = payload;
|
||||
}
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
export function generateId(prefix: string = ''): string {
|
||||
const timestamp = Date.now().toString(36);
|
||||
const random = Math.random().toString(36).slice(2, 10);
|
||||
return `${prefix}${prefix ? '_' : ''}${timestamp}${random}`;
|
||||
}
|
||||
|
||||
export function getCurrentTimestamp(): number {
|
||||
return Date.now();
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export function canCompleteTask(dueDate: number): boolean {
|
||||
if (dueDate === 0) return true;
|
||||
const now = new Date();
|
||||
const endOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59, 999).getTime();
|
||||
return dueDate <= endOfToday;
|
||||
}
|
||||
|
||||
export const categoryCreateSchema = z.object({
|
||||
name: z.string().min(1).max(50),
|
||||
color: z.string().regex(/^#[0-9A-Fa-f]{6}$/),
|
||||
order: z.number().int().min(0).optional(),
|
||||
});
|
||||
|
||||
export const categoryUpdateSchema = z.object({
|
||||
name: z.string().min(1).max(50).optional(),
|
||||
color: z.string().regex(/^#[0-9A-Fa-f]{6}$/).optional(),
|
||||
order: z.number().int().min(0).optional(),
|
||||
});
|
||||
|
||||
export const repeatSchema = z.enum(['none', 'daily', 'weekly', 'monthly', 'custom']);
|
||||
|
||||
export const taskCreateSchema = z.object({
|
||||
title: z.string().min(1).max(100),
|
||||
description: z.string().max(1000).optional(),
|
||||
categoryId: z.string().min(1),
|
||||
priority: z.enum(['none', 'low', 'medium', 'high', 'critical']).optional(),
|
||||
dueDate: z.number().int().min(0).optional(),
|
||||
dueTime: z.string().regex(/^([01]\d|2[0-3]):([0-5]\d)$/).optional().or(z.literal('')).transform(v => v ?? ''),
|
||||
endTime: z.string().regex(/^([01]\d|2[0-3]):([0-5]\d)$/).optional().or(z.literal('')),
|
||||
allDay: z.boolean().optional(),
|
||||
repeat: repeatSchema.optional(),
|
||||
repeatInterval: z.number().int().min(1).max(30).optional(),
|
||||
repeatDays: z.string().max(20).optional(),
|
||||
seriesId: z.string().max(50).optional(),
|
||||
reminder: z.enum(['none', 'at_time', '15', '30', '60', '120', '1440']).optional(),
|
||||
reminders: z.string().max(100).optional(),
|
||||
assigneeId: z.string().nullable().optional(),
|
||||
subtasks: z.array(z.object({ title: z.string().min(1).max(100) })).optional(),
|
||||
});
|
||||
|
||||
export const taskUpdateSchema = z.object({
|
||||
title: z.string().min(1).max(100).optional(),
|
||||
description: z.string().max(1000).optional(),
|
||||
categoryId: z.string().min(1).optional(),
|
||||
priority: z.enum(['none', 'low', 'medium', 'high', 'critical']).optional(),
|
||||
completed: z.boolean().optional(),
|
||||
dueDate: z.number().int().min(0).optional(),
|
||||
dueTime: z.string().regex(/^([01]\d|2[0-3]):([0-5]\d)$/).optional().or(z.literal('')).transform(v => v === '' ? undefined : v),
|
||||
endTime: z.string().regex(/^([01]\d|2[0-3]):([0-5]\d)$/).optional(),
|
||||
reminders: z.string().max(100).optional(),
|
||||
assigneeId: z.string().nullable().optional(),
|
||||
});
|
||||
|
||||
export const subtaskCreateSchema = z.object({
|
||||
title: z.string().min(1).max(100),
|
||||
description: z.string().max(1000).optional(),
|
||||
priority: z.enum(['none', 'low', 'medium', 'high', 'critical']).optional(),
|
||||
dueDate: z.number().int().min(0).optional(),
|
||||
dueTime: z.string().regex(/^([01]\d|2[0-3]):([0-5]\d)$/).optional().or(z.literal('')).transform(v => v ?? ''),
|
||||
endTime: z.string().regex(/^([01]\d|2[0-3]):([0-5]\d)$/).optional().or(z.literal('')),
|
||||
allDay: z.boolean().optional(),
|
||||
repeat: repeatSchema.optional(),
|
||||
repeatInterval: z.number().int().min(1).max(30).optional(),
|
||||
repeatDays: z.string().max(20).optional(),
|
||||
seriesId: z.string().max(50).optional(),
|
||||
reminder: z.enum(['none', 'at_time', '15', '30', '60', '120', '1440']).optional(),
|
||||
reminders: z.string().max(100).optional(),
|
||||
assigneeId: z.string().nullable().optional(),
|
||||
order: z.number().int().min(0).optional(),
|
||||
});
|
||||
|
||||
export const subtaskUpdateSchema = z.object({
|
||||
title: z.string().min(1).max(100).optional(),
|
||||
description: z.string().max(1000).optional(),
|
||||
priority: z.enum(['none', 'low', 'medium', 'high', 'critical']).optional(),
|
||||
completed: z.boolean().optional(),
|
||||
dueDate: z.number().int().min(0).optional(),
|
||||
dueTime: z.string().regex(/^([01]\d|2[0-3]):([0-5]\d)$/).optional().or(z.literal('')).transform(v => v === '' ? undefined : v),
|
||||
endTime: z.string().regex(/^([01]\d|2[0-3]):([0-5]\d)$/).optional(),
|
||||
allDay: z.boolean().optional(),
|
||||
repeat: repeatSchema.optional(),
|
||||
repeatInterval: z.number().int().min(1).max(30).optional(),
|
||||
repeatDays: z.string().max(20).optional(),
|
||||
seriesId: z.string().max(50).optional(),
|
||||
reminder: z.enum(['none', 'at_time', '15', '30', '60', '120', '1440']).optional(),
|
||||
reminders: z.string().max(100).optional(),
|
||||
assigneeId: z.string().nullable().optional(),
|
||||
order: z.number().int().min(0).optional(),
|
||||
});
|
||||
|
||||
export const userSettingsSchema = z.object({
|
||||
darkMode: z.boolean().optional(),
|
||||
notifications: z.boolean().optional(),
|
||||
reminderTime: z.string().regex(/^([01]\d|2[0-3]):([0-5]\d)$/).optional(),
|
||||
defaultCategory: z.string().optional().nullable(),
|
||||
sortBy: z.enum(['dueDate', 'priority', 'title', 'createdAt']).optional(),
|
||||
sortOrder: z.enum(['asc', 'desc']).optional(),
|
||||
});
|
||||
|
||||
export const repeatProfileSchema = z.object({
|
||||
name: z.string().min(1).max(50),
|
||||
repeat: repeatSchema,
|
||||
repeatInterval: z.number().int().min(1).max(30),
|
||||
repeatDays: z.string().max(20),
|
||||
});
|
||||
|
||||
export const repeatProfileUpdateSchema = z.object({
|
||||
name: z.string().min(1).max(50).optional(),
|
||||
repeat: repeatSchema.optional(),
|
||||
repeatInterval: z.number().int().min(1).max(30).optional(),
|
||||
repeatDays: z.string().max(20).optional(),
|
||||
});
|
||||
|
||||
export const searchQuerySchema = z.object({
|
||||
q: z.string().min(1).max(50),
|
||||
});
|
||||
|
||||
export const friendRequestSchema = z.object({
|
||||
username: z.string().min(1).max(50),
|
||||
});
|
||||
|
||||
export const friendshipSchema = z.object({
|
||||
id: z.string(),
|
||||
userId: z.string(),
|
||||
friendId: z.string(),
|
||||
status: z.enum(['pending', 'accepted']),
|
||||
createdAt: z.number(),
|
||||
updatedAt: z.number(),
|
||||
});
|
||||
|
||||
export const pushChangesSchema = z.object({
|
||||
changes: z.object({
|
||||
categories: z.array(categoryCreateSchema.extend({ id: z.string(), createdAt: z.number(), updatedAt: z.number() })).optional(),
|
||||
tasks: z.array(taskCreateSchema.extend({ id: z.string(), completed: z.boolean(), createdAt: z.number(), updatedAt: z.number() })).optional(),
|
||||
subtasks: z.array(subtaskCreateSchema.extend({ id: z.string(), taskId: z.string(), completed: z.boolean(), createdAt: z.number(), updatedAt: z.number() })).optional(),
|
||||
repeatProfiles: z.array(repeatProfileSchema.extend({ id: z.string(), createdAt: z.number(), updatedAt: z.number() })).optional(),
|
||||
friendships: z.array(friendshipSchema).optional(),
|
||||
}),
|
||||
lastPulledAt: z.number().int().min(0),
|
||||
});
|
||||
|
||||
export const syncQuerySchema = z.object({
|
||||
since: z.string().transform(Number).pipe(z.number().int().min(0)),
|
||||
});
|
||||
|
||||
export const taskQuerySchema = z.object({
|
||||
categoryId: z.string().optional(),
|
||||
completed: z.string().transform(v => v === 'true').optional(),
|
||||
dueBefore: z.string().transform(Number).pipe(z.number().int().min(0)).optional(),
|
||||
dueAfter: z.string().transform(Number).pipe(z.number().int().min(0)).optional(),
|
||||
priority: z.enum(['none', 'low', 'medium', 'high', 'critical']).optional(),
|
||||
sortBy: z.enum(['dueDate', 'priority', 'createdAt', 'title']).optional(),
|
||||
sortOrder: z.enum(['asc', 'desc']).optional(),
|
||||
limit: z.string().transform(Number).pipe(z.number().int().min(1).max(100)).optional(),
|
||||
offset: z.string().transform(Number).pipe(z.number().int().min(0)).optional(),
|
||||
});
|
||||
Reference in New Issue
Block a user