🌊 TeamFlow — Modern Trello alternative with email integration

- Full-stack: React 18 + Express + SQLite
- Drag-and-drop kanban boards with @hello-pangea/dnd
- Google App Password email integration (SMTP + IMAP)
- Inbound email: create cards by sending emails
- Reply-to-card: email replies become comments
- Admin/user management with role-based access
- Setup wizard: email config → admin creation
- Checklists, time tracking, priorities, labels, due dates
- Real-time notifications with activity feed
- Beautiful HTML email templates
This commit is contained in:
admin
2026-04-03 15:11:27 +00:00
Unverified
commit 460f83aef8
40 changed files with 8512 additions and 0 deletions

36
server/routes/auth.js Normal file
View File

@@ -0,0 +1,36 @@
import { Router } from 'express';
import bcrypt from 'bcryptjs';
import db from '../db.js';
import { generateToken, authMiddleware } from '../middleware/auth.js';
const router = Router();
router.post('/login', (req, res) => {
const { email, password } = req.body;
if (!email || !password) return res.status(400).json({ error: 'Email and password required' });
const user = db.prepare('SELECT * FROM users WHERE email = ?').get(email);
if (!user || !user.is_active) return res.status(401).json({ error: 'Invalid credentials' });
if (!bcrypt.compareSync(password, user.password)) return res.status(401).json({ error: 'Invalid credentials' });
const token = generateToken(user);
res.json({ user: { id: user.id, email: user.email, name: user.name, avatar_color: user.avatar_color, role: user.role }, token });
});
router.get('/me', authMiddleware, (req, res) => {
res.json(req.user);
});
router.put('/me', authMiddleware, async (req, res) => {
const { name, avatar_color, current_password, new_password } = req.body;
if (name) db.prepare('UPDATE users SET name = ? WHERE id = ?').run(name, req.user.id);
if (avatar_color) db.prepare('UPDATE users SET avatar_color = ? WHERE id = ?').run(avatar_color, req.user.id);
if (new_password) {
const user = db.prepare('SELECT password FROM users WHERE id = ?').get(req.user.id);
if (!bcrypt.compareSync(current_password, user.password)) return res.status(400).json({ error: 'Current password incorrect' });
const hash = await bcrypt.hash(new_password, 12);
db.prepare('UPDATE users SET password = ? WHERE id = ?').run(hash, req.user.id);
}
const updated = db.prepare('SELECT id, email, name, avatar_color, role FROM users WHERE id = ?').get(req.user.id);
res.json(updated);
});
export default router;

129
server/routes/boards.js Normal file
View File

@@ -0,0 +1,129 @@
import { Router } from 'express';
import db from '../db.js';
import { authMiddleware } from '../middleware/auth.js';
const router = Router();
router.use(authMiddleware);
const BACKGROUNDS = [
'gradient-blue', 'gradient-purple', 'gradient-green', 'gradient-orange',
'gradient-pink', 'gradient-teal', 'gradient-indigo', 'gradient-red',
];
function canAccessBoard(userId, boardId) {
const m = db.prepare('SELECT 1 FROM board_members WHERE board_id = ? AND user_id = ?').get(boardId, userId);
return !!m;
}
router.get('/', (req, res) => {
const boards = db.prepare(`
SELECT b.*, bm.role as my_role,
(SELECT COUNT(*) FROM lists l JOIN cards c ON c.list_id = l.id WHERE l.board_id = b.id AND c.assigned_to = ? AND c.due_date IS NOT NULL AND date(c.due_date) <= date('now', '+3 days')) as due_soon_count
FROM boards b
JOIN board_members bm ON bm.board_id = b.id AND bm.user_id = ?
WHERE b.is_archived = 0
ORDER BY b.created_at DESC
`).all(req.user.id, req.user.id);
res.json(boards);
});
router.post('/', (req, res) => {
const { title, description, background } = req.body;
if (!title) return res.status(400).json({ error: 'Title required' });
const bg = background && BACKGROUNDS.includes(background) ? background : BACKGROUNDS[Math.floor(Math.random() * BACKGROUNDS.length)];
const result = db.prepare('INSERT INTO boards (title, description, background, created_by) VALUES (?, ?, ?, ?)')
.run(title, description || '', bg, req.user.id);
db.prepare('INSERT INTO board_members (board_id, user_id, role) VALUES (?, ?, ?)').run(result.lastInsertRowid, req.user.id, 'admin');
const defaultLists = ['To Do', 'In Progress', 'Review', 'Done'];
const insertList = db.prepare('INSERT INTO lists (board_id, title, position) VALUES (?, ?, ?)');
defaultLists.forEach((l, i) => insertList.run(result.lastInsertRowid, l, i * 65536));
const board = db.prepare('SELECT * FROM boards WHERE id = ?').get(result.lastInsertRowid);
board.my_role = 'admin';
res.json(board);
});
router.get('/:id', (req, res) => {
if (!canAccessBoard(req.user.id, req.params.id)) return res.status(403).json({ error: 'Access denied' });
const board = db.prepare('SELECT * FROM boards WHERE id = ?').get(req.params.id);
res.json(board);
});
router.put('/:id', (req, res) => {
if (!canAccessBoard(req.user.id, req.params.id)) return res.status(403).json({ error: 'Access denied' });
const { title, description, background, is_archived } = req.body;
const board = db.prepare('SELECT * FROM boards WHERE id = ?').get(req.params.id);
if (!board) return res.status(404).json({ error: 'Not found' });
if (title !== undefined) db.prepare('UPDATE boards SET title = ? WHERE id = ?').run(title, req.params.id);
if (description !== undefined) db.prepare('UPDATE boards SET description = ? WHERE id = ?').run(description, req.params.id);
if (background !== undefined) db.prepare('UPDATE boards SET background = ? WHERE id = ?').run(background, req.params.id);
if (is_archived !== undefined) db.prepare('UPDATE boards SET is_archived = ? WHERE id = ?').run(is_archived ? 1 : 0, req.params.id);
const updated = db.prepare('SELECT * FROM boards WHERE id = ?').get(req.params.id);
res.json(updated);
});
router.delete('/:id', (req, res) => {
if (!canAccessBoard(req.user.id, req.params.id)) return res.status(403).json({ error: 'Access denied' });
db.prepare('DELETE FROM boards WHERE id = ?').run(req.params.id);
res.json({ success: true });
});
router.get('/:id/full', (req, res) => {
if (!canAccessBoard(req.user.id, req.params.id)) return res.status(403).json({ error: 'Access denied' });
const board = db.prepare('SELECT * FROM boards WHERE id = ?').get(req.params.id);
const lists = db.prepare('SELECT * FROM lists WHERE board_id = ? AND is_archived = 0 ORDER BY position').all(req.params.id);
const labels = db.prepare('SELECT * FROM labels WHERE board_id = ? ORDER BY name').all(req.params.id);
const members = db.prepare(`
SELECT u.id, u.email, u.name, u.avatar_color, bm.role as board_role
FROM board_members bm JOIN users u ON u.id = bm.user_id WHERE bm.board_id = ?
`).all(req.params.id);
const cards = db.prepare(`
SELECT c.*,
u1.name as creator_name, u1.avatar_color as creator_color,
u2.name as assignee_name, u2.avatar_color as assignee_color,
(SELECT COUNT(*) FROM checklist_items ci JOIN checklists cl ON cl.id = ci.checklist_id WHERE cl.card_id = c.id) as total_items,
(SELECT COUNT(*) FROM checklist_items ci JOIN checklists cl ON cl.id = ci.checklist_id WHERE cl.card_id = c.id AND ci.is_checked = 1) as done_items
FROM cards c
LEFT JOIN users u1 ON u1.id = c.created_by
LEFT JOIN users u2 ON u2.id = c.assigned_to
WHERE c.list_id IN (SELECT id FROM lists WHERE board_id = ? AND is_archived = 0)
ORDER BY c.position
`).all(req.params.id);
const cardLabels = db.prepare(`
SELECT cl.card_id, l.id as label_id, l.name, l.color
FROM card_labels cl JOIN labels l ON l.id = cl.label_id
WHERE l.board_id = ?
`).all(req.params.id);
const cardsById = {};
cards.forEach(c => { c.labels = []; cardsById[c.id] = c; });
cardLabels.forEach(cl => { if (cardsById[cl.card_id]) cardsById[cl.card_id].labels.push({ id: cl.label_id, name: cl.name, color: cl.color }); });
const listsWithCards = lists.map(l => ({
...l,
cards: cards.filter(c => c.list_id === l.id),
}));
res.json({ ...board, lists: listsWithCards, labels, members });
});
router.post('/:id/members', (req, res) => {
if (!canAccessBoard(req.user.id, req.params.id)) return res.status(403).json({ error: 'Access denied' });
const { user_id, role } = req.body;
if (!user_id) return res.status(400).json({ error: 'User ID required' });
const existing = db.prepare('SELECT 1 FROM board_members WHERE board_id = ? AND user_id = ?').get(req.params.id, user_id);
if (existing) return res.status(400).json({ error: 'Already a member' });
db.prepare('INSERT INTO board_members (board_id, user_id, role) VALUES (?, ?, ?)').run(req.params.id, user_id, role || 'member');
const member = db.prepare(`SELECT u.id, u.email, u.name, u.avatar_color, bm.role as board_role
FROM board_members bm JOIN users u ON u.id = bm.user_id WHERE bm.board_id = ? AND bm.user_id = ?`).get(req.params.id, user_id);
res.json(member);
});
router.delete('/:id/members/:userId', (req, res) => {
if (!canAccessBoard(req.user.id, req.params.id)) return res.status(403).json({ error: 'Access denied' });
db.prepare('DELETE FROM board_members WHERE board_id = ? AND user_id = ?').run(req.params.id, req.params.userId);
res.json({ success: true });
});
export default router;

296
server/routes/cards.js Normal file
View File

@@ -0,0 +1,296 @@
import { Router } from 'express';
import db from '../db.js';
import { authMiddleware } from '../middleware/auth.js';
import { sendMail, buildCardNotificationHtml, buildCardUrl, getEmailConfig } from '../email/transporter.js';
import { v4 as uuidv4 } from 'uuid';
const router = Router();
router.use(authMiddleware);
function canAccessCard(userId, cardId) {
const card = db.prepare(`
SELECT 1 FROM cards c
JOIN lists l ON l.id = c.list_id
JOIN board_members bm ON bm.board_id = l.board_id AND bm.user_id = ?
WHERE c.id = ?
`).get(userId, cardId);
return !!card;
}
function getBoardIdForCard(cardId) {
const r = db.prepare(`SELECT l.board_id FROM cards c JOIN lists l ON l.id = c.list_id WHERE c.id = ?`).get(cardId);
return r?.board_id;
}
async function notifyCard({ cardId, userId, action, comment }) {
const card = db.prepare(`
SELECT c.*, l.board_id, b.title as board_title,
u.name as user_name, u2.email as assignee_email, u2.name as assignee_name
FROM cards c
JOIN lists l ON l.id = c.list_id
JOIN boards b ON b.id = l.board_id
LEFT JOIN users u ON u.id = ?
LEFT JOIN users u2 ON u2.id = c.assigned_to
WHERE c.id = ?
`).get(userId, cardId);
if (!card || !card.assignee_email) return;
if (card.assigned_to === userId) return;
const config = getEmailConfig();
if (!config) return;
const token = uuidv4();
db.prepare('INSERT INTO email_tokens (card_id, user_id, token, expires_at) VALUES (?, ?, ?, datetime("now", "+30 days"))')
.run(cardId, card.assigned_to, token);
db.prepare(`INSERT INTO notifications (user_id, type, title, message, card_id, board_id) VALUES (?, ?, ?, ?, ?, ?)`)
.run(card.assigned_to, action, card.title, `${card.user_name} ${action}`, cardId, card.board_id);
try {
await sendMail({
to: card.assignee_email,
subject: `[TeamFlow] ${card.user_name} ${action}${card.title}`,
html: buildCardNotificationHtml({
userName: card.user_name,
boardTitle: card.board_title,
cardTitle: card.title,
action,
cardUrl: buildCardUrl(cardId, card.board_id),
comment,
}),
replyTo: config.email,
});
} catch {}
}
// Lists
router.post('/:boardId/lists', (req, res) => {
const { title, position } = req.body;
if (!title) return res.status(400).json({ error: 'Title required' });
const maxPos = db.prepare('SELECT MAX(position) as p FROM lists WHERE board_id = ?').get(req.params.boardId);
const result = db.prepare('INSERT INTO lists (board_id, title, position) VALUES (?, ?, ?)')
.run(req.params.boardId, title, position ?? (maxPos.p || 0) + 65536);
const list = db.prepare('SELECT * FROM lists WHERE id = ?').get(result.lastInsertRowid);
res.json(list);
});
router.put('/lists/:id/reorder', (req, res) => {
const { position } = req.body;
db.prepare('UPDATE lists SET position = ? WHERE id = ?').run(position, req.params.id);
res.json({ success: true });
});
router.put('/lists/:id', (req, res) => {
const { title, is_archived } = req.body;
if (title !== undefined) db.prepare('UPDATE lists SET title = ? WHERE id = ?').run(title, req.params.id);
if (is_archived !== undefined) db.prepare('UPDATE lists SET is_archived = ? WHERE id = ?').run(is_archived ? 1 : 0, req.params.id);
res.json({ success: true });
});
// Cards
router.post('/lists/:listId/cards', async (req, res) => {
const { title, description, due_date, priority, assigned_to, labels } = req.body;
if (!title) return res.status(400).json({ error: 'Title required' });
const maxPos = db.prepare('SELECT MAX(position) as p FROM cards WHERE list_id = ?').get(req.params.listId);
const result = db.prepare('INSERT INTO cards (list_id, title, description, position, due_date, priority, assigned_to, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?)')
.run(req.params.listId, title, description || '', (maxPos.p || 0) + 65536, due_date || null, priority || 'none', assigned_to || null, req.user.id);
if (labels?.length) {
const ins = db.prepare('INSERT OR IGNORE INTO card_labels (card_id, label_id) VALUES (?, ?)');
labels.forEach(lid => ins.run(result.lastInsertRowid, lid));
}
db.prepare('INSERT INTO card_activity (card_id, user_id, action) VALUES (?, ?, ?)').run(result.lastInsertRowid, req.user.id, 'created');
const card = db.prepare('SELECT c.*, u.name as creator_name FROM cards c LEFT JOIN users u ON u.id = c.created_by WHERE c.id = ?').get(result.lastInsertRowid);
if (assigned_to) notifyCard({ cardId: result.lastInsertRowid, userId: req.user.id, action: 'assigned you to a card' });
res.json(card);
});
router.get('/cards/:id', (req, res) => {
if (!canAccessCard(req.user.id, req.params.id)) return res.status(403).json({ error: 'Access denied' });
const card = db.prepare(`
SELECT c.*, u1.name as creator_name, u2.name as assignee_name, u2.avatar_color as assignee_color
FROM cards c
LEFT JOIN users u1 ON u1.id = c.created_by
LEFT JOIN users u2 ON u2.id = c.assigned_to
WHERE c.id = ?
`).get(req.params.id);
const labels = db.prepare(`SELECT l.* FROM card_labels cl JOIN labels l ON l.id = cl.label_id WHERE cl.card_id = ?`).all(req.params.id);
const comments = db.prepare(`
SELECT cc.*, u.name, u.avatar_color FROM card_comments cc
LEFT JOIN users u ON u.id = cc.user_id WHERE cc.card_id = ? ORDER BY cc.created_at
`).all(req.params.id);
const activity = db.prepare(`
SELECT ca.*, u.name, u.avatar_color FROM card_activity ca
LEFT JOIN users u ON u.id = ca.user_id WHERE ca.card_id = ? ORDER BY ca.created_at DESC LIMIT 50
`).all(req.params.id);
const checklists = db.prepare(`
SELECT cl.*,
(SELECT COUNT(*) FROM checklist_items WHERE checklist_id = cl.id) as total_items,
(SELECT COUNT(*) FROM checklist_items WHERE checklist_id = cl.id AND is_checked = 1) as done_items
FROM checklists cl WHERE cl.card_id = ? ORDER BY cl.position
`).all(req.params.id);
const checklistItems = {};
for (const cl of checklists) {
checklistItems[cl.id] = db.prepare('SELECT * FROM checklist_items WHERE checklist_id = ? ORDER BY position').all(cl.id);
}
res.json({ ...card, labels, comments, activity, checklists, checklistItems });
});
router.put('/cards/:id', async (req, res) => {
if (!canAccessCard(req.user.id, req.params.id)) return res.status(403).json({ error: 'Access denied' });
const { title, description, due_date, priority, color, assigned_to, list_id, position, estimated_hours, time_spent } = req.body;
const old = db.prepare('SELECT * FROM cards WHERE id = ?').get(req.params.id);
if (!old) return res.status(404).json({ error: 'Not found' });
const updates = [];
const params = [];
if (title !== undefined) { updates.push('title = ?'); params.push(title); }
if (description !== undefined) { updates.push('description = ?'); params.push(description); }
if (due_date !== undefined) { updates.push('due_date = ?'); params.push(due_date); }
if (priority !== undefined) { updates.push('priority = ?'); params.push(priority); }
if (color !== undefined) { updates.push('color = ?'); params.push(color); }
if (assigned_to !== undefined) { updates.push('assigned_to = ?'); params.push(assigned_to); }
if (list_id !== undefined) { updates.push('list_id = ?'); params.push(list_id); }
if (position !== undefined) { updates.push('position = ?'); params.push(position); }
if (estimated_hours !== undefined) { updates.push('estimated_hours = ?'); params.push(estimated_hours); }
if (time_spent !== undefined) { updates.push('time_spent = ?'); params.push(time_spent); }
updates.push("updated_at = datetime('now')");
params.push(req.params.id);
if (updates.length > 1) {
db.prepare(`UPDATE cards SET ${updates.join(', ')} WHERE id = ?`).run(...params);
}
if (assigned_to && assigned_to !== old.assigned_to) {
db.prepare('INSERT INTO card_activity (card_id, user_id, action, details) VALUES (?, ?, ?, ?)')
.run(req.params.id, req.user.id, 'assigned', `Assigned to ${assigned_to}`);
notifyCard({ cardId: req.params.id, userId: req.user.id, action: 'assigned you to a card' });
}
if (list_id && list_id !== old.list_id) {
const newList = db.prepare('SELECT title FROM lists WHERE id = ?').get(list_id);
db.prepare('INSERT INTO card_activity (card_id, user_id, action, details) VALUES (?, ?, ?, ?)')
.run(req.params.id, req.user.id, 'moved', `Moved to ${newList?.title || 'Unknown'}`);
const assignee = db.prepare('SELECT assigned_to FROM cards WHERE id = ?').get(req.params.id);
if (assignee?.assigned_to && assignee.assigned_to !== req.user.id) {
notifyCard({ cardId: req.params.id, userId: req.user.id, action: 'moved a card' });
}
}
const card = db.prepare('SELECT * FROM cards WHERE id = ?').get(req.params.id);
res.json(card);
});
router.delete('/cards/:id', (req, res) => {
if (!canAccessCard(req.user.id, req.params.id)) return res.status(403).json({ error: 'Access denied' });
db.prepare('DELETE FROM cards WHERE id = ?').run(req.params.id);
res.json({ success: true });
});
// Card reorder (batch)
router.put('/cards/reorder', (req, res) => {
const { cards } = req.body;
if (!Array.isArray(cards)) return res.status(400).json({ error: 'Cards array required' });
const update = db.prepare('UPDATE cards SET list_id = ?, position = ? WHERE id = ?');
const moveActivity = db.prepare('INSERT INTO card_activity (card_id, user_id, action, details) VALUES (?, ?, ?, ?)');
for (const c of cards) {
update.run(c.list_id, c.position, c.id);
if (c.moved && c.old_list_id !== c.list_id) {
const listName = db.prepare('SELECT title FROM lists WHERE id = ?').get(c.list_id)?.title || '';
moveActivity.run(c.id, req.user.id, 'moved', `Moved to ${listName}`);
}
}
res.json({ success: true });
});
// Comments
router.post('/cards/:id/comments', async (req, res) => {
if (!canAccessCard(req.user.id, req.params.id)) return res.status(403).json({ error: 'Access denied' });
const { content } = req.body;
if (!content) return res.status(400).json({ error: 'Content required' });
const result = db.prepare('INSERT INTO card_comments (card_id, user_id, content) VALUES (?, ?, ?)').run(req.params.id, req.user.id, content);
db.prepare('INSERT INTO card_activity (card_id, user_id, action, details) VALUES (?, ?, ?, ?)').run(req.params.id, req.user.id, 'commented', '');
notifyCard({ cardId: req.params.id, userId: req.user.id, action: 'commented on a card', comment: content });
const comment = db.prepare('SELECT cc.*, u.name, u.avatar_color FROM card_comments cc LEFT JOIN users u ON u.id = cc.user_id WHERE cc.id = ?').get(result.lastInsertRowid);
res.json(comment);
});
// Labels
router.post('/:boardId/labels', (req, res) => {
const { name, color } = req.body;
if (!name || !color) return res.status(400).json({ error: 'Name and color required' });
const result = db.prepare('INSERT INTO labels (board_id, name, color) VALUES (?, ?, ?)').run(req.params.boardId, name, color);
const label = db.prepare('SELECT * FROM labels WHERE id = ?').get(result.lastInsertRowid);
res.json(label);
});
router.put('/labels/:id', (req, res) => {
const { name, color } = req.body;
if (name !== undefined) db.prepare('UPDATE labels SET name = ? WHERE id = ?').run(name, req.params.id);
if (color !== undefined) db.prepare('UPDATE labels SET color = ? WHERE id = ?').run(color, req.params.id);
const label = db.prepare('SELECT * FROM labels WHERE id = ?').get(req.params.id);
res.json(label);
});
router.delete('/labels/:id', (req, res) => {
db.prepare('DELETE FROM labels WHERE id = ?').run(req.params.id);
res.json({ success: true });
});
router.put('/cards/:id/labels', (req, res) => {
if (!canAccessCard(req.user.id, req.params.id)) return res.status(403).json({ error: 'Access denied' });
const { labels } = req.body;
db.prepare('DELETE FROM card_labels WHERE card_id = ?').run(req.params.id);
if (labels?.length) {
const ins = db.prepare('INSERT OR IGNORE INTO card_labels (card_id, label_id) VALUES (?, ?)');
labels.forEach(lid => ins.run(req.params.id, lid));
}
res.json({ success: true });
});
// Checklists
router.post('/cards/:id/checklists', (req, res) => {
if (!canAccessCard(req.user.id, req.params.id)) return res.status(403).json({ error: 'Access denied' });
const { title } = req.body;
const maxPos = db.prepare('SELECT MAX(position) as p FROM checklists WHERE card_id = ?').get(req.params.id);
const result = db.prepare('INSERT INTO checklists (card_id, title, position) VALUES (?, ?, ?)')
.run(req.params.id, title || 'Checklist', (maxPos?.p || 0) + 65536);
const cl = db.prepare('SELECT * FROM checklists WHERE id = ?').get(result.lastInsertRowid);
res.json({ ...cl, items: [] });
});
router.post('/checklists/:id/items', (req, res) => {
const checklist = db.prepare('SELECT * FROM checklists WHERE id = ?').get(req.params.id);
if (!checklist) return res.status(404).json({ error: 'Not found' });
if (!canAccessCard(req.user.id, checklist.card_id)) return res.status(403).json({ error: 'Access denied' });
const { text } = req.body;
if (!text) return res.status(400).json({ error: 'Text required' });
const maxPos = db.prepare('SELECT MAX(position) as p FROM checklist_items WHERE checklist_id = ?').get(req.params.id);
const result = db.prepare('INSERT INTO checklist_items (checklist_id, text, position) VALUES (?, ?, ?)')
.run(req.params.id, text, (maxPos?.p || 0) + 65536);
const item = db.prepare('SELECT * FROM checklist_items WHERE id = ?').get(result.lastInsertRowid);
res.json(item);
});
router.put('/checklist-items/:id', (req, res) => {
const item = db.prepare('SELECT ci.*, cl.card_id FROM checklist_items ci JOIN checklists cl ON cl.id = ci.checklist_id WHERE ci.id = ?').get(req.params.id);
if (!item) return res.status(404).json({ error: 'Not found' });
if (!canAccessCard(req.user.id, item.card_id)) return res.status(403).json({ error: 'Access denied' });
const { text, is_checked } = req.body;
if (text !== undefined) db.prepare('UPDATE checklist_items SET text = ? WHERE id = ?').run(text, req.params.id);
if (is_checked !== undefined) db.prepare('UPDATE checklist_items SET is_checked = ? WHERE id = ?').run(is_checked ? 1 : 0, req.params.id);
const updated = db.prepare('SELECT * FROM checklist_items WHERE id = ?').get(req.params.id);
res.json(updated);
});
router.delete('/checklist-items/:id', (req, res) => {
const item = db.prepare('SELECT ci.*, cl.card_id FROM checklist_items ci JOIN checklists cl ON cl.id = ci.checklist_id WHERE ci.id = ?').get(req.params.id);
if (!item) return res.status(404).json({ error: 'Not found' });
if (!canAccessCard(req.user.id, item.card_id)) return res.status(403).json({ error: 'Access denied' });
db.prepare('DELETE FROM checklist_items WHERE id = ?').run(req.params.id);
res.json({ success: true });
});
router.delete('/checklists/:id', (req, res) => {
const cl = db.prepare('SELECT * FROM checklists WHERE id = ?').get(req.params.id);
if (!cl) return res.status(404).json({ error: 'Not found' });
if (!canAccessCard(req.user.id, cl.card_id)) return res.status(403).json({ error: 'Access denied' });
db.prepare('DELETE FROM checklists WHERE id = ?').run(req.params.id);
res.json({ success: true });
});
export default router;

37
server/routes/email.js Normal file
View File

@@ -0,0 +1,37 @@
import { Router } from 'express';
import db from '../db.js';
import { authMiddleware, adminOnly } from '../middleware/auth.js';
import { getEmailConfig } from '../email/transporter.js';
import { pollInbox } from '../email/imap.js';
const router = Router();
router.use(authMiddleware);
router.get('/config', adminOnly, (req, res) => {
const config = getEmailConfig();
if (!config) return res.status(404).json({ error: 'Not configured' });
res.json({ ...config, app_password: '••••••••' });
});
router.get('/log', adminOnly, (req, res) => {
const logs = db.prepare('SELECT * FROM email_log ORDER BY created_at DESC LIMIT 100').all();
res.json(logs);
});
router.post('/poll', adminOnly, async (req, res) => {
try {
await pollInbox();
res.json({ success: true });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
router.get('/stats', adminOnly, (req, res) => {
const sent = db.prepare("SELECT COUNT(*) as c FROM email_log WHERE direction = 'sent'").get().c;
const received = db.prepare("SELECT COUNT(*) as c FROM email_log WHERE direction = 'received'").get().c;
const failed = db.prepare("SELECT COUNT(*) as c FROM email_log WHERE status = 'failed'").get().c;
res.json({ sent, received, failed });
});
export default router;

View File

@@ -0,0 +1,34 @@
import { Router } from 'express';
import db from '../db.js';
import { authMiddleware } from '../middleware/auth.js';
const router = Router();
router.use(authMiddleware);
router.get('/', (req, res) => {
const notifs = db.prepare(`
SELECT n.* FROM notifications n
WHERE n.user_id = ?
ORDER BY n.is_read ASC, n.created_at DESC
LIMIT 50
`).all(req.user.id);
const unread = db.prepare('SELECT COUNT(*) as c FROM notifications WHERE user_id = ? AND is_read = 0').get(req.user.id).c;
res.json({ notifications: notifs, unread });
});
router.put('/:id/read', (req, res) => {
db.prepare('UPDATE notifications SET is_read = 1 WHERE id = ? AND user_id = ?').run(req.params.id, req.user.id);
res.json({ success: true });
});
router.put('/read-all', (req, res) => {
db.prepare('UPDATE notifications SET is_read = 1 WHERE user_id = ?').run(req.user.id);
res.json({ success: true });
});
router.delete('/:id', (req, res) => {
db.prepare('DELETE FROM notifications WHERE id = ? AND user_id = ?').run(req.params.id, req.user.id);
res.json({ success: true });
});
export default router;

83
server/routes/setup.js Normal file
View File

@@ -0,0 +1,83 @@
import { Router } from 'express';
import bcrypt from 'bcryptjs';
import db from '../db.js';
import { generateToken } from '../middleware/auth.js';
import { testConnection, initTransporter } from '../email/transporter.js';
const router = Router();
router.get('/status', (req, res) => {
const hasEmail = !!db.prepare('SELECT 1 FROM email_config WHERE id = 1').get();
const userCount = db.prepare('SELECT COUNT(*) as c FROM users').get().c;
const setupComplete = hasEmail && userCount > 0;
res.json({ hasEmail, userCount, setupComplete });
});
router.post('/email', async (req, res) => {
try {
const { smtp_host, smtp_port, email, app_password } = req.body;
if (!email || !app_password) return res.status(400).json({ error: 'Email and app password required' });
const host = smtp_host || 'smtp.gmail.com';
const port = parseInt(smtp_port) || 587;
await testConnection(host, port, email, app_password);
db.prepare(`INSERT OR REPLACE INTO email_config (id, smtp_host, smtp_port, email, app_password)
VALUES (1, ?, ?, ?, ?)`).run(host, port, email, app_password);
await initTransporter();
res.json({ success: true });
} catch (err) {
res.status(400).json({ error: err.message });
}
});
router.post('/email/test', async (req, res) => {
try {
const { to } = req.body;
const config = db.prepare('SELECT * FROM email_config WHERE id = 1').get();
if (!config) return res.status(400).json({ error: 'Email not configured' });
const { sendMail } = await import('../email/transporter.js');
await sendMail({
to,
subject: 'TeamFlow — Test Email',
html: `<div style="padding:32px;font-family:sans-serif">
<h2 style="color:#6366f1">✅ TeamFlow Email Working!</h2>
<p>Your email integration is configured correctly.</p>
</div>`,
});
res.json({ success: true });
} catch (err) {
res.status(400).json({ error: err.message });
}
});
router.post('/admin', async (req, res) => {
const hasEmail = !!db.prepare('SELECT 1 FROM email_config WHERE id = 1').get();
if (!hasEmail) return res.status(400).json({ error: 'Configure email first' });
const existing = db.prepare('SELECT COUNT(*) as c FROM users').get();
if (existing.c > 0) return res.status(400).json({ error: 'Admin already exists' });
const { email, name, password } = req.body;
if (!email || !name || !password) return res.status(400).json({ error: 'All fields required' });
if (password.length < 6) return res.status(400).json({ error: 'Password must be at least 6 characters' });
const hash = await bcrypt.hash(password, 12);
const result = db.prepare('INSERT INTO users (email, name, password, role) VALUES (?, ?, ?, ?)').run(email, name, hash);
const user = db.prepare('SELECT id, email, name, avatar_color, role FROM users WHERE id = ?').get(result.lastInsertRowid);
const token = generateToken(user);
res.json({ user, token });
});
router.put('/email/inbound', async (req, res) => {
const config = db.prepare('SELECT * FROM email_config WHERE id = 1').get();
if (!config) return res.status(400).json({ error: 'Email not configured' });
const { enabled, folder, prefix } = req.body;
db.prepare(`UPDATE email_config SET inbound_enabled = ?, inbound_folder = ?, board_email_prefix = ? WHERE id = 1`)
.run(enabled ? 1 : 0, folder || 'INBOX', prefix || 'tf-');
if (enabled) {
const { startImapPolling } = await import('../email/imap.js');
startImapPolling();
} else {
const { stopImapPolling } = await import('../email/imap.js');
stopImapPolling();
}
res.json({ success: true });
});
export default router;

77
server/routes/users.js Normal file
View File

@@ -0,0 +1,77 @@
import { Router } from 'express';
import bcrypt from 'bcryptjs';
import db from '../db.js';
import { authMiddleware, adminOnly, generateToken } from '../middleware/auth.js';
import { sendMail, buildCardNotificationHtml, buildCardUrl } from '../email/transporter.js';
const router = Router();
router.use(authMiddleware);
router.get('/', (req, res) => {
if (req.user.role !== 'admin') return res.status(403).json({ error: 'Admin only' });
const users = db.prepare('SELECT id, email, name, avatar_color, role, is_active, created_at FROM users ORDER BY created_at').all();
res.json(users);
});
router.post('/', adminOnly, async (req, res) => {
const { email, name, password, role } = req.body;
if (!email || !name || !password) return res.status(400).json({ error: 'All fields required' });
if (password.length < 6) return res.status(400).json({ error: 'Password must be at least 6 characters' });
const existing = db.prepare('SELECT id FROM users WHERE email = ?').get(email);
if (existing) return res.status(400).json({ error: 'Email already exists' });
const hash = await bcrypt.hash(password, 12);
const colors = ['#ef4444','#f97316','#eab308','#22c55e','#14b8a6','#3b82f6','#6366f1','#a855f7','#ec4899'];
const color = colors[Math.floor(Math.random() * colors.length)];
const result = db.prepare('INSERT INTO users (email, name, password, role, avatar_color) VALUES (?, ?, ?, ?, ?)')
.run(email, name, hash, role || 'member', color);
const user = db.prepare('SELECT id, email, name, avatar_color, role FROM users WHERE id = ?').get(result.lastInsertRowid);
try {
await sendMail({
to: email,
subject: 'Welcome to TeamFlow! 🚀',
html: `<div style="padding:32px;font-family:sans-serif;max-width:480px;margin:0 auto">
<h2 style="color:#6366f1">Welcome to TeamFlow, ${name}!</h2>
<p>Your account has been created. Log in to get started.</p>
<p><strong>Email:</strong> ${email}</p>
<p><strong>Password:</strong> (set by your admin)</p>
<a href="${process.env.APP_URL || 'http://localhost:5173'}" style="display:inline-block;background:#6366f1;color:#fff;padding:12px 24px;border-radius:8px;text-decoration:none;margin-top:16px">Go to TeamFlow</a>
</div>`,
});
} catch {}
res.json(user);
});
router.put('/:id', adminOnly, (req, res) => {
const { name, role, is_active } = req.body;
const user = db.prepare('SELECT id FROM users WHERE id = ?').get(req.params.id);
if (!user) return res.status(404).json({ error: 'User not found' });
if (user.id === req.user.id) return res.status(400).json({ error: 'Cannot modify yourself' });
if (name !== undefined) db.prepare('UPDATE users SET name = ? WHERE id = ?').run(name, user.id);
if (role !== undefined) db.prepare('UPDATE users SET role = ? WHERE id = ?').run(role, user.id);
if (is_active !== undefined) db.prepare('UPDATE users SET is_active = ? WHERE id = ?').run(is_active ? 1 : 0, user.id);
const updated = db.prepare('SELECT id, email, name, avatar_color, role, is_active FROM users WHERE id = ?').get(user.id);
res.json(updated);
});
router.put('/:id/reset-password', adminOnly, async (req, res) => {
const { password } = req.body;
if (!password || password.length < 6) return res.status(400).json({ error: 'Password must be at least 6 characters' });
const user = db.prepare('SELECT id, email, name FROM users WHERE id = ?').get(req.params.id);
if (!user) return res.status(404).json({ error: 'User not found' });
const hash = await bcrypt.hash(password, 12);
db.prepare('UPDATE users SET password = ? WHERE id = ?').run(hash, user.id);
res.json({ success: true });
});
router.get('/board/:boardId', (req, res) => {
const members = db.prepare(`
SELECT u.id, u.email, u.name, u.avatar_color, u.role, bm.role as board_role
FROM board_members bm
JOIN users u ON u.id = bm.user_id
WHERE bm.board_id = ?
`).all(req.params.boardId);
res.json(members);
});
export default router;