996 lines
35 KiB
TypeScript
996 lines
35 KiB
TypeScript
import { type User, type InsertUser, type Label, type InsertLabel, type SharedLabel, type Task, type InsertTask, type XpEvent, type InsertXpEvent, type Goal, type InsertGoal, xpEvents, goals, type Reward, type InsertReward, type UserReward, type InsertUserReward, rewards, userRewards, systemSettings, type SystemSettings, type InsertSystemSettings, type SharedTask, type InsertSharedTask, type UserTaskAccess, type InsertUserTaskAccess, sharedTasks, userTaskAccess, type InsertPasswordResetToken, type PasswordResetToken } from "../shared/schema.js";
|
|
import { randomUUID } from "crypto";
|
|
import session from "express-session";
|
|
import createMemoryStore from "memorystore";
|
|
import connectPg from "connect-pg-simple";
|
|
import { pool } from "./db.js";
|
|
|
|
const MemoryStore = createMemoryStore(session);
|
|
const PostgresStore = connectPg(session);
|
|
|
|
export interface IStorage {
|
|
sessionStore: session.Store;
|
|
getUser(id: string): Promise<User | undefined>;
|
|
getUserByUsername(username: string): Promise<User | undefined>;
|
|
getUserByEmail(email: string): Promise<User | undefined>;
|
|
getUserByApiKey(apiKey: string): Promise<User | undefined>;
|
|
createUser(user: InsertUser & { role?: string; isActive?: boolean }): Promise<User>;
|
|
updateUserApiKey(userId: string, apiKey: string | null): Promise<User>;
|
|
updateUser(id: string, updates: Partial<User>): Promise<User>;
|
|
deleteUser(id: string): Promise<boolean>;
|
|
getAllUsers(): Promise<User[]>;
|
|
updateUserXP(id: string, xp: number): Promise<void>;
|
|
|
|
// Social & Leaderboard
|
|
getLeaderboard(): Promise<User[]>;
|
|
searchUsers(query: string): Promise<User[]>;
|
|
shareTask(sharedTask: InsertSharedTask): Promise<SharedTask>;
|
|
shareAllTasks(access: InsertUserTaskAccess): Promise<UserTaskAccess>;
|
|
createSharedTask(sharedTask: InsertSharedTask): Promise<SharedTask>; // Alias for shareTask standard naming
|
|
createUserTaskAccess(access: InsertUserTaskAccess): Promise<UserTaskAccess>; // Alias
|
|
|
|
getSharedTasks(userId: string): Promise<SharedTask[]>; // Tasks shared WITH user
|
|
getSharedTasks(userId: string): Promise<SharedTask[]>; // Tasks shared WITH user
|
|
getUserTaskAccess(viewerId: string): Promise<UserTaskAccess[]>; // Access Viewer has to Owners
|
|
getTaskSharedUsers(taskId: string): Promise<User[]>; // Get users a task is shared WITH
|
|
unshareTask(taskId: string, userId: string): Promise<boolean>; // Unshare specific task from user
|
|
|
|
// Shared Labels
|
|
shareLabel(labelId: string, sharedWithUserId: string, sharedByUserId: string, permission?: string): Promise<SharedLabel>;
|
|
getSharedLabels(userId: string): Promise<SharedLabel[]>; // Labels shared WITH user
|
|
getLabelSharedUsers(labelId: string): Promise<User[]>; // Users label is shared WITH
|
|
unshareLabel(labelId: string, userId: string): Promise<boolean>;
|
|
getLabelShares(labelId: string): Promise<SharedLabel[]>;
|
|
|
|
// System Settings (Admin)
|
|
getSystemSettings(key: string): Promise<string | undefined>;
|
|
setSystemSettings(key: string, value: string): Promise<void>;
|
|
hasAdminUser(): Promise<boolean>;
|
|
|
|
// Labels
|
|
getAllLabels(): Promise<Label[]>;
|
|
getLabel(id: string): Promise<Label | undefined>;
|
|
createLabel(label: InsertLabel): Promise<Label>;
|
|
updateLabel(id: string, updates: Partial<InsertLabel>): Promise<Label | undefined>;
|
|
deleteLabel(id: string): Promise<boolean>;
|
|
|
|
// Tasks
|
|
getTasksForUser(userId: string): Promise<Task[]>; // Replaces getAllTasks
|
|
getTask(id: string): Promise<Task | undefined>;
|
|
createTask(task: InsertTask & { userId?: string }): Promise<Task>;
|
|
updateTask(id: string, updates: Partial<InsertTask>): Promise<Task | undefined>;
|
|
deleteTask(id: string): Promise<boolean>;
|
|
|
|
// Gamification
|
|
logXpEvent(event: InsertXpEvent): Promise<XpEvent>;
|
|
getGoals(): Promise<Goal[]>;
|
|
createGoal(goal: InsertGoal): Promise<Goal>;
|
|
updateGoal(id: string, updates: Partial<InsertGoal & { completed?: boolean; current?: number }>): Promise<Goal>;
|
|
|
|
// Rewards
|
|
getAllRewards(): Promise<Reward[]>;
|
|
getUserRewards(userId: string): Promise<UserReward[]>;
|
|
createReward(reward: InsertReward): Promise<Reward>;
|
|
createUserReward(userReward: InsertUserReward): Promise<UserReward>;
|
|
|
|
// History
|
|
// History
|
|
getXpEvents(userId: string): Promise<XpEvent[]>;
|
|
|
|
// Auth - Password Reset
|
|
createPasswordResetToken(token: InsertPasswordResetToken): Promise<PasswordResetToken>;
|
|
getPasswordResetToken(token: string): Promise<PasswordResetToken | undefined>;
|
|
markPasswordResetTokenUsed(id: string): Promise<void>;
|
|
}
|
|
|
|
export class MemStorage implements IStorage {
|
|
private users: Map<string, User>;
|
|
private labels: Map<string, Label>;
|
|
private tasks: Map<string, Task>;
|
|
private xpEvents: Map<string, XpEvent>;
|
|
private settings: Map<string, string>;
|
|
private goals: Map<string, Goal>;
|
|
private rewards: Map<string, Reward>;
|
|
private userRewards: Map<string, UserReward>;
|
|
|
|
// Social maps
|
|
private sharedTasks: Map<string, SharedTask>;
|
|
private sharedLabels: Map<string, SharedLabel>;
|
|
private userTaskAccess: Map<string, UserTaskAccess>;
|
|
private passwordResetTokens: Map<string, PasswordResetToken>; // id -> Token
|
|
|
|
sessionStore: session.Store;
|
|
|
|
constructor() {
|
|
this.users = new Map();
|
|
this.labels = new Map();
|
|
this.tasks = new Map();
|
|
this.xpEvents = new Map();
|
|
this.settings = new Map();
|
|
this.goals = new Map();
|
|
this.rewards = new Map();
|
|
this.userRewards = new Map();
|
|
this.userRewards = new Map();
|
|
this.sharedTasks = new Map();
|
|
this.sharedLabels = new Map();
|
|
this.userTaskAccess = new Map();
|
|
this.passwordResetTokens = new Map();
|
|
this.sessionStore = new MemoryStore({
|
|
checkPeriod: 86400000,
|
|
});
|
|
|
|
// Create some default labels
|
|
this.createDefaultLabels();
|
|
this.createDefaultRewards();
|
|
}
|
|
|
|
// ... (createDefaultLabels)
|
|
|
|
private async createDefaultLabels() {
|
|
// Use fixed IDs to prevent ID churn on server restarts
|
|
const defaultLabels = [
|
|
{ id: 'cb44bed1-8ba3-43fe-9498-bb28e483ed1f', name: "Work", color: "#3B82F6", creatorId: null },
|
|
{ id: '274f0ba4-a133-471a-bbe9-8189aa3b0106', name: "Personal", color: "#10B981", creatorId: null },
|
|
{ id: '2e8c3aa0-278f-4220-b2c5-aa109b4279b7', name: "Urgent", color: "#EF4444", creatorId: null },
|
|
{ id: 'c5eccac9-7919-4eb1-bb50-badacad6b1c1', name: "Study", color: "#8B5CF6", creatorId: null },
|
|
];
|
|
for (const label of defaultLabels) {
|
|
if (!this.labels.has(label.id)) {
|
|
this.labels.set(label.id, label);
|
|
}
|
|
}
|
|
}
|
|
|
|
async getUser(id: string): Promise<User | undefined> {
|
|
return this.users.get(id);
|
|
}
|
|
|
|
async getUserByUsername(username: string): Promise<User | undefined> {
|
|
return Array.from(this.users.values()).find(
|
|
(user) => user.username === username,
|
|
);
|
|
}
|
|
|
|
async getUserByEmail(email: string): Promise<User | undefined> {
|
|
return Array.from(this.users.values()).find(
|
|
(user) => user.email === email,
|
|
);
|
|
}
|
|
|
|
async getAllUsers(): Promise<User[]> {
|
|
return Array.from(this.users.values());
|
|
}
|
|
|
|
async getUserByApiKey(apiKey: string): Promise<User | undefined> {
|
|
return Array.from(this.users.values()).find(u => u.apiKey === apiKey);
|
|
}
|
|
|
|
async updateUserApiKey(userId: string, apiKey: string | null): Promise<User> {
|
|
const user = this.users.get(userId);
|
|
if (!user) throw new Error("User not found");
|
|
const updated = { ...user, apiKey };
|
|
this.users.set(userId, updated);
|
|
return updated;
|
|
}
|
|
|
|
async createUser(insertUser: InsertUser & { role?: string; isActive?: boolean }): Promise<User> {
|
|
const id = randomUUID();
|
|
const user: User = {
|
|
...insertUser,
|
|
id,
|
|
role: insertUser.role || 'user',
|
|
isActive: insertUser.isActive ?? true,
|
|
email: insertUser.email || `missing_${id}@example.com`,
|
|
xp: 0,
|
|
level: 1,
|
|
currentStreak: 0,
|
|
lastTaskDate: null,
|
|
showOnLeaderboard: insertUser.showOnLeaderboard ?? false,
|
|
isSearchable: insertUser.isSearchable ?? false,
|
|
apiKey: null,
|
|
aiEnabled: insertUser.aiEnabled ?? true,
|
|
};
|
|
this.users.set(id, user);
|
|
return user;
|
|
}
|
|
|
|
async updateUser(id: string, updates: Partial<User>): Promise<User> {
|
|
const user = this.users.get(id);
|
|
if (!user) throw new Error("User not found");
|
|
// Ensure we don't accidentally override with undefined
|
|
const updated = { ...user, ...updates };
|
|
this.users.set(id, updated);
|
|
return updated;
|
|
}
|
|
|
|
async deleteUser(id: string): Promise<boolean> {
|
|
return this.users.delete(id);
|
|
}
|
|
|
|
// Social Methods (MemStorage)
|
|
async getLeaderboard(): Promise<User[]> {
|
|
return Array.from(this.users.values())
|
|
.filter(u => u.showOnLeaderboard && u.isActive)
|
|
.sort((a, b) => b.xp - a.xp);
|
|
}
|
|
|
|
async searchUsers(query: string): Promise<User[]> {
|
|
if (!query || query.length < 2) return [];
|
|
const lowerQ = query.toLowerCase();
|
|
return Array.from(this.users.values()).filter(u =>
|
|
u.isSearchable && u.isActive && u.username.toLowerCase().includes(lowerQ)
|
|
);
|
|
}
|
|
|
|
async shareTask(sharedTask: InsertSharedTask): Promise<SharedTask> {
|
|
return this.createSharedTask(sharedTask);
|
|
}
|
|
|
|
async createSharedTask(sharedTask: InsertSharedTask): Promise<SharedTask> {
|
|
const id = randomUUID();
|
|
const newItem: SharedTask = { ...sharedTask, id, createdAt: new Date() };
|
|
this.sharedTasks.set(id, newItem);
|
|
return newItem;
|
|
}
|
|
|
|
async shareAllTasks(access: InsertUserTaskAccess): Promise<UserTaskAccess> {
|
|
return this.createUserTaskAccess(access);
|
|
}
|
|
|
|
async createUserTaskAccess(access: InsertUserTaskAccess): Promise<UserTaskAccess> {
|
|
const id = randomUUID();
|
|
const newItem: UserTaskAccess = { ...access, id, createdAt: new Date() };
|
|
this.userTaskAccess.set(id, newItem);
|
|
return newItem;
|
|
}
|
|
|
|
async getSharedTasks(userId: string): Promise<SharedTask[]> {
|
|
return Array.from(this.sharedTasks.values()).filter(st => st.sharedWithUserId === userId);
|
|
}
|
|
|
|
async getUserTaskAccess(viewerId: string): Promise<UserTaskAccess[]> {
|
|
return Array.from(this.userTaskAccess.values()).filter(uta => uta.viewerId === viewerId);
|
|
}
|
|
|
|
async getTaskSharedUsers(taskId: string): Promise<User[]> {
|
|
const shares = Array.from(this.sharedTasks.values()).filter(st => st.taskId === taskId);
|
|
const users: User[] = [];
|
|
for (const share of shares) {
|
|
const u = this.users.get(share.sharedWithUserId);
|
|
if (u) users.push(u);
|
|
}
|
|
return users;
|
|
}
|
|
|
|
async unshareTask(taskId: string, userId: string): Promise<boolean> {
|
|
let toDeleteId: string | null = null;
|
|
for (const [id, share] of this.sharedTasks.entries()) {
|
|
if (share.taskId === taskId && share.sharedWithUserId === userId) {
|
|
toDeleteId = id;
|
|
break;
|
|
}
|
|
}
|
|
if (toDeleteId) {
|
|
return this.sharedTasks.delete(toDeleteId);
|
|
}
|
|
return false;
|
|
}
|
|
|
|
// Shared Labels (MemStorage)
|
|
async shareLabel(labelId: string, sharedWithUserId: string, sharedByUserId: string, permission: string = 'read'): Promise<SharedLabel> {
|
|
const id = randomUUID();
|
|
const share: SharedLabel = {
|
|
id,
|
|
labelId,
|
|
sharedWithUserId,
|
|
sharedByUserId,
|
|
permission,
|
|
createdAt: new Date()
|
|
};
|
|
this.sharedLabels.set(id, share);
|
|
return share;
|
|
}
|
|
|
|
async getSharedLabels(userId: string): Promise<SharedLabel[]> {
|
|
return Array.from(this.sharedLabels.values()).filter(sl => sl.sharedWithUserId === userId);
|
|
}
|
|
|
|
async getLabelSharedUsers(labelId: string): Promise<User[]> {
|
|
const shares = Array.from(this.sharedLabels.values()).filter(sl => sl.labelId === labelId);
|
|
const users: User[] = [];
|
|
for (const share of shares) {
|
|
const u = this.users.get(share.sharedWithUserId);
|
|
if (u) users.push(u);
|
|
}
|
|
return users;
|
|
}
|
|
|
|
async unshareLabel(labelId: string, userId: string): Promise<boolean> {
|
|
let toDeleteId: string | null = null;
|
|
for (const [id, share] of this.sharedLabels.entries()) {
|
|
if (share.labelId === labelId && share.sharedWithUserId === userId) {
|
|
toDeleteId = id;
|
|
break;
|
|
}
|
|
}
|
|
if (toDeleteId) {
|
|
return this.sharedLabels.delete(toDeleteId);
|
|
}
|
|
return false;
|
|
}
|
|
|
|
async getLabelShares(labelId: string): Promise<SharedLabel[]> {
|
|
return Array.from(this.sharedLabels.values()).filter(sl => sl.labelId === labelId);
|
|
}
|
|
|
|
async getSystemSettings(key: string): Promise<string | undefined> {
|
|
return this.settings.get(key);
|
|
}
|
|
|
|
async setSystemSettings(key: string, value: string): Promise<void> {
|
|
this.settings.set(key, value);
|
|
}
|
|
|
|
async hasAdminUser(): Promise<boolean> {
|
|
return Array.from(this.users.values()).some(u => u.role === 'admin');
|
|
}
|
|
|
|
// Labels
|
|
async getAllLabels(): Promise<Label[]> {
|
|
return Array.from(this.labels.values());
|
|
}
|
|
|
|
async getLabel(id: string): Promise<Label | undefined> {
|
|
return this.labels.get(id);
|
|
}
|
|
|
|
async createLabel(insertLabel: InsertLabel): Promise<Label> {
|
|
const id = randomUUID();
|
|
const label: Label = {
|
|
...insertLabel,
|
|
id,
|
|
creatorId: insertLabel.creatorId ?? null
|
|
};
|
|
this.labels.set(id, label);
|
|
return label;
|
|
}
|
|
|
|
async updateLabel(id: string, updates: Partial<InsertLabel>): Promise<Label | undefined> {
|
|
const existing = this.labels.get(id);
|
|
if (!existing) return undefined;
|
|
|
|
const updated: Label = { ...existing, ...updates };
|
|
this.labels.set(id, updated);
|
|
return updated;
|
|
}
|
|
|
|
async deleteLabel(id: string): Promise<boolean> {
|
|
return this.labels.delete(id);
|
|
}
|
|
|
|
// Tasks
|
|
async getTasksForUser(userId: string): Promise<Task[]> {
|
|
const allTasks = Array.from(this.tasks.values());
|
|
|
|
// 1. My tasks
|
|
const myTasks = allTasks.filter(t => t.userId === userId);
|
|
|
|
// 2. Explicitly shared tasks (Single Task Share)
|
|
const sharedToMe = Array.from(this.sharedTasks.values())
|
|
.filter(st => st.sharedWithUserId === userId)
|
|
.map(st => this.tasks.get(st.taskId))
|
|
.filter((t): t is Task => !!t);
|
|
|
|
// 3. Global Share Access (Share All)
|
|
// Find users who have shared everything with ME (valid viewer)
|
|
const accessGrants = Array.from(this.userTaskAccess.values())
|
|
.filter(uta => uta.viewerId === userId);
|
|
|
|
let globalSharedTasks: Task[] = [];
|
|
if (accessGrants.length > 0) {
|
|
const ownerIds = new Set(accessGrants.map(uta => uta.ownerId));
|
|
globalSharedTasks = allTasks.filter(t => t.userId && ownerIds.has(t.userId));
|
|
}
|
|
|
|
// 4. Shared Labels
|
|
// Find labels shared with me
|
|
const sharedLabels = await this.getSharedLabels(userId);
|
|
const sharedLabelIds = new Set(sharedLabels.map(sl => sl.labelId));
|
|
const tasksFromSharedLabels = allTasks.filter(t => t.labelId && sharedLabelIds.has(t.labelId));
|
|
|
|
// Merge and Dedupe
|
|
const combined = [...myTasks, ...sharedToMe, ...globalSharedTasks, ...tasksFromSharedLabels];
|
|
const unique = Array.from(new Map(combined.map(t => [t.id, t])).values());
|
|
|
|
return unique;
|
|
}
|
|
|
|
async getTask(id: string): Promise<Task | undefined> {
|
|
return this.tasks.get(id);
|
|
}
|
|
|
|
async createTask(insertTask: InsertTask & { userId?: string }): Promise<Task> {
|
|
const id = randomUUID();
|
|
const task: Task = {
|
|
id,
|
|
title: insertTask.title,
|
|
description: insertTask.description || null,
|
|
status: insertTask.status || "todo",
|
|
priority: insertTask.priority || "medium",
|
|
dueDate: insertTask.dueDate || null,
|
|
timeTracked: insertTask.timeTracked || 0,
|
|
isTracking: insertTask.isTracking || false,
|
|
projectId: insertTask.projectId || null,
|
|
notes: insertTask.notes || null,
|
|
labelId: insertTask.labelId || null,
|
|
energyLevel: insertTask.energyLevel || "medium",
|
|
estimatedDuration: insertTask.estimatedDuration || null,
|
|
dependencies: insertTask.dependencies || null,
|
|
userId: insertTask.userId || null // Set ownership
|
|
};
|
|
this.tasks.set(id, task);
|
|
return task;
|
|
}
|
|
|
|
async updateTask(id: string, updates: Partial<InsertTask>): Promise<Task | undefined> {
|
|
const existing = this.tasks.get(id);
|
|
if (!existing) return undefined;
|
|
|
|
const updated: Task = { ...existing, ...updates };
|
|
this.tasks.set(id, updated);
|
|
return updated;
|
|
}
|
|
|
|
async deleteTask(id: string): Promise<boolean> {
|
|
return this.tasks.delete(id);
|
|
}
|
|
|
|
async updateUserXP(id: string, xp: number): Promise<void> {
|
|
const user = this.users.get(id);
|
|
if (user) {
|
|
user.xp += xp;
|
|
this.users.set(id, user);
|
|
}
|
|
}
|
|
|
|
async logXpEvent(event: InsertXpEvent): Promise<XpEvent> {
|
|
const id = randomUUID();
|
|
const xpEvent: XpEvent = {
|
|
...event,
|
|
id,
|
|
userId: event.userId || null,
|
|
taskId: event.taskId || null,
|
|
createdAt: new Date()
|
|
};
|
|
this.xpEvents.set(id, xpEvent);
|
|
// Also update user XP
|
|
console.log("Mock update XP for user:", event.userId);
|
|
return xpEvent;
|
|
}
|
|
|
|
async getGoals(): Promise<Goal[]> {
|
|
return Array.from(this.goals.values());
|
|
}
|
|
|
|
async createGoal(goal: InsertGoal): Promise<Goal> {
|
|
const id = randomUUID();
|
|
const newGoal: Goal = {
|
|
...goal,
|
|
id,
|
|
userId: goal.userId || null,
|
|
deadline: goal.deadline || null,
|
|
current: 0,
|
|
completed: false,
|
|
createdAt: new Date()
|
|
};
|
|
this.goals.set(id, newGoal);
|
|
return newGoal;
|
|
}
|
|
|
|
async updateGoal(id: string, updates: Partial<InsertGoal & { completed?: boolean; current?: number }>): Promise<Goal> {
|
|
const existing = this.goals.get(id);
|
|
if (!existing) throw new Error("Goal not found");
|
|
const updated = { ...existing, ...updates };
|
|
this.goals.set(id, updated);
|
|
return updated;
|
|
}
|
|
|
|
|
|
// Rewards
|
|
private async createDefaultRewards() {
|
|
const defaultRewards = [
|
|
{ id: 'r1', title: "rewards.defaults.coffee.title", description: "rewards.defaults.coffee.description", cost: 50, icon: "coffee", type: "real_world", isSystem: true },
|
|
{ id: 'r2', title: "rewards.defaults.gaming.title", description: "rewards.defaults.gaming.description", cost: 100, icon: "gamepad-2", type: "real_world", isSystem: true },
|
|
{ id: 'r3', title: "rewards.defaults.theme.title", description: "rewards.defaults.theme.description", cost: 500, icon: "palette", type: "feature_unlock", isSystem: true },
|
|
];
|
|
|
|
for (const r of defaultRewards) {
|
|
if (!this.rewards.has(r.id)) {
|
|
this.rewards.set(r.id, r as Reward);
|
|
}
|
|
}
|
|
}
|
|
|
|
async getAllRewards(): Promise<Reward[]> {
|
|
return Array.from(this.rewards.values());
|
|
}
|
|
|
|
async getUserRewards(userId: string): Promise<UserReward[]> {
|
|
return Array.from(this.userRewards.values()).filter(ur => ur.userId === userId);
|
|
}
|
|
|
|
async createReward(insertReward: InsertReward): Promise<Reward> {
|
|
const id = randomUUID();
|
|
const reward: Reward = {
|
|
...insertReward,
|
|
id,
|
|
type: insertReward.type || "virtual",
|
|
description: insertReward.description || null,
|
|
isSystem: false,
|
|
userId: insertReward.userId || null
|
|
};
|
|
this.rewards.set(id, reward);
|
|
return reward;
|
|
}
|
|
|
|
async createUserReward(insertUserReward: InsertUserReward): Promise<UserReward> {
|
|
const id = randomUUID();
|
|
const userReward: UserReward = {
|
|
...insertUserReward,
|
|
id,
|
|
userId: insertUserReward.userId || null,
|
|
rewardId: insertUserReward.rewardId || null,
|
|
purchasedAt: new Date()
|
|
};
|
|
this.userRewards.set(id, userReward);
|
|
return userReward;
|
|
}
|
|
|
|
async getXpEvents(userId: string): Promise<XpEvent[]> {
|
|
return Array.from(this.xpEvents.values())
|
|
.filter(e => e.userId === userId)
|
|
.sort((a, b) => (b.createdAt && a.createdAt ? b.createdAt.getTime() - a.createdAt.getTime() : 0));
|
|
}
|
|
|
|
// Auth - Password Reset (MemStorage)
|
|
async createPasswordResetToken(insertToken: InsertPasswordResetToken): Promise<PasswordResetToken> {
|
|
const id = randomUUID();
|
|
const token: PasswordResetToken = {
|
|
...insertToken,
|
|
id,
|
|
isUsed: false,
|
|
createdAt: new Date()
|
|
};
|
|
this.passwordResetTokens.set(id, token);
|
|
return token;
|
|
}
|
|
|
|
async getPasswordResetToken(tokenString: string): Promise<PasswordResetToken | undefined> {
|
|
return Array.from(this.passwordResetTokens.values()).find(t => t.token === tokenString);
|
|
}
|
|
|
|
async markPasswordResetTokenUsed(id: string): Promise<void> {
|
|
const token = this.passwordResetTokens.get(id);
|
|
if (token) {
|
|
token.isUsed = true;
|
|
this.passwordResetTokens.set(id, token);
|
|
}
|
|
}
|
|
}
|
|
|
|
import { getDatabase } from './db.js';
|
|
import { eq, sql, desc, and } from 'drizzle-orm';
|
|
import * as schema from '../shared/schema.js';
|
|
|
|
export class DbStorage implements IStorage {
|
|
private db = getDatabase();
|
|
sessionStore: session.Store;
|
|
|
|
constructor() {
|
|
this.sessionStore = new PostgresStore({
|
|
pool: pool ?? undefined,
|
|
createTableIfMissing: true,
|
|
});
|
|
}
|
|
|
|
async getUser(id: string): Promise<User | undefined> {
|
|
const result = await this.db.select().from(schema.users).where(eq(schema.users.id, id));
|
|
return result[0];
|
|
}
|
|
|
|
async getUserByUsername(username: string): Promise<User | undefined> {
|
|
const result = await this.db.select().from(schema.users).where(eq(schema.users.username, username));
|
|
return result[0];
|
|
}
|
|
|
|
async getUserByEmail(email: string): Promise<User | undefined> {
|
|
const result = await this.db.select().from(schema.users).where(eq(schema.users.email, email));
|
|
return result[0];
|
|
}
|
|
|
|
async getAllUsers(): Promise<User[]> {
|
|
return await this.db.select().from(schema.users);
|
|
}
|
|
|
|
async getUserByApiKey(apiKey: string): Promise<User | undefined> {
|
|
const result = await this.db.select().from(schema.users).where(eq(schema.users.apiKey, apiKey));
|
|
return result[0];
|
|
}
|
|
|
|
async updateUserApiKey(userId: string, apiKey: string | null): Promise<User> {
|
|
const result = await this.db.update(schema.users)
|
|
.set({ apiKey })
|
|
.where(eq(schema.users.id, userId))
|
|
.returning();
|
|
if (!result[0]) throw new Error("User not found");
|
|
return result[0];
|
|
}
|
|
|
|
async createUser(insertUser: InsertUser & { role?: string; isActive?: boolean }): Promise<User> {
|
|
const result = await this.db.insert(schema.users).values({
|
|
...insertUser,
|
|
role: insertUser.role || 'user',
|
|
isActive: insertUser.isActive ?? true,
|
|
showOnLeaderboard: insertUser.showOnLeaderboard ?? false,
|
|
isSearchable: insertUser.isSearchable ?? false,
|
|
}).returning();
|
|
return result[0];
|
|
}
|
|
|
|
async updateUser(id: string, updates: Partial<User>): Promise<User> {
|
|
const result = await this.db.update(schema.users)
|
|
.set(updates)
|
|
.where(eq(schema.users.id, id))
|
|
.returning();
|
|
if (!result[0]) throw new Error("User not found");
|
|
return result[0];
|
|
}
|
|
|
|
async deleteUser(id: string): Promise<boolean> {
|
|
// Note: This relies on CASCADE DELETE foreign keys in schema,
|
|
// otherwise we need to manually delete related records first.
|
|
// For now, assuming schema handles it or we accept errors.
|
|
const result = await this.db.delete(schema.users).where(eq(schema.users.id, id)).returning();
|
|
return result.length > 0;
|
|
}
|
|
|
|
async getSystemSettings(key: string): Promise<string | undefined> {
|
|
const result = await this.db.select().from(schema.systemSettings).where(eq(schema.systemSettings.key, key));
|
|
return result[0]?.value;
|
|
}
|
|
|
|
async setSystemSettings(key: string, value: string): Promise<void> {
|
|
// Upsert
|
|
await this.db.insert(schema.systemSettings)
|
|
.values({ key, value })
|
|
.onConflictDoUpdate({ target: schema.systemSettings.key, set: { value, updatedAt: new Date() } });
|
|
}
|
|
|
|
async hasAdminUser(): Promise<boolean> {
|
|
const result = await this.db.select().from(schema.users).where(eq(schema.users.role, 'admin')).limit(1);
|
|
return result.length > 0;
|
|
}
|
|
|
|
// ... (rest of DbStorage labels, tasks, etc. implementation - unchanged mostly)
|
|
async getAllLabels(): Promise<Label[]> {
|
|
return await this.db.select().from(schema.labels);
|
|
}
|
|
|
|
async getLabel(id: string): Promise<Label | undefined> {
|
|
const result = await this.db.select().from(schema.labels).where(eq(schema.labels.id, id));
|
|
return result[0];
|
|
}
|
|
|
|
async createLabel(insertLabel: InsertLabel): Promise<Label> {
|
|
const result = await this.db.insert(schema.labels).values(insertLabel).returning();
|
|
return result[0];
|
|
}
|
|
|
|
async updateLabel(id: string, updates: Partial<InsertLabel>): Promise<Label | undefined> {
|
|
const result = await this.db
|
|
.update(schema.labels)
|
|
.set(updates)
|
|
.where(eq(schema.labels.id, id))
|
|
.returning();
|
|
return result[0];
|
|
}
|
|
|
|
async deleteLabel(id: string): Promise<boolean> {
|
|
const result = await this.db.delete(schema.labels).where(eq(schema.labels.id, id)).returning();
|
|
return result.length > 0;
|
|
}
|
|
|
|
async getTasksForUser(userId: string): Promise<Task[]> {
|
|
// Complex query:
|
|
// (tasks.userId = current)
|
|
// OR (id IN (select taskId from sharedTasks where sharedWith = current))
|
|
// OR (userId IN (select ownerId from userTaskAccess where viewerId = current))
|
|
|
|
// For simplicity in this generated code, we can do parallel queries or use `or`.
|
|
// Drizzle's `or` and `inArray` can be used.
|
|
|
|
// 1. My tasks
|
|
const result = await this.db.select().from(schema.tasks).where(eq(schema.tasks.userId, userId));
|
|
|
|
// 2. Shared Tasks
|
|
const sharedLinks = await this.db.select().from(schema.sharedTasks).where(eq(schema.sharedTasks.sharedWithUserId, userId));
|
|
const sharedTaskIds = sharedLinks.map(s => s.taskId);
|
|
let sharedTasks: Task[] = [];
|
|
if (sharedTaskIds.length > 0) {
|
|
sharedTasks = await this.db.select().from(schema.tasks).where(sql`${schema.tasks.id} IN ${sharedTaskIds}`);
|
|
}
|
|
|
|
// 3. Global Access
|
|
const accessGrants = await this.db.select().from(schema.userTaskAccess).where(eq(schema.userTaskAccess.viewerId, userId));
|
|
const ownerIds = accessGrants.map(a => a.ownerId);
|
|
let globalTasks: Task[] = [];
|
|
if (ownerIds.length > 0) {
|
|
globalTasks = await this.db.select().from(schema.tasks).where(sql`${schema.tasks.userId} IN ${ownerIds}`);
|
|
}
|
|
|
|
// 4. Shared Labels
|
|
const sharedLabels = await this.db.select().from(schema.sharedLabels).where(eq(schema.sharedLabels.sharedWithUserId, userId));
|
|
const sharedLabelIds = sharedLabels.map(sl => sl.labelId);
|
|
let tasksFromSharedLabels: Task[] = [];
|
|
if (sharedLabelIds.length > 0) {
|
|
tasksFromSharedLabels = await this.db.select().from(schema.tasks).where(sql`${schema.tasks.labelId} IN ${sharedLabelIds}`);
|
|
}
|
|
|
|
// Dedupe
|
|
const combined = [...result, ...sharedTasks, ...globalTasks, ...tasksFromSharedLabels];
|
|
const unique = Array.from(new Map(combined.map(t => [t.id, t])).values());
|
|
return unique;
|
|
}
|
|
|
|
async getTask(id: string): Promise<Task | undefined> {
|
|
const result = await this.db.select().from(schema.tasks).where(eq(schema.tasks.id, id));
|
|
return result[0];
|
|
}
|
|
|
|
async createTask(insertTask: InsertTask & { userId?: string }): Promise<Task> {
|
|
const result = await this.db.insert(schema.tasks).values(insertTask).returning();
|
|
return result[0];
|
|
}
|
|
|
|
async updateTask(id: string, updates: Partial<InsertTask>): Promise<Task | undefined> {
|
|
const result = await this.db
|
|
.update(schema.tasks)
|
|
.set(updates)
|
|
.where(eq(schema.tasks.id, id))
|
|
.returning();
|
|
return result[0];
|
|
}
|
|
|
|
async deleteTask(id: string): Promise<boolean> {
|
|
const result = await this.db.delete(schema.tasks).where(eq(schema.tasks.id, id)).returning();
|
|
return result.length > 0;
|
|
}
|
|
|
|
async updateUserXP(id: string, xp: number): Promise<void> {
|
|
const user = await this.getUser(id);
|
|
if (user) {
|
|
await this.db.update(schema.users)
|
|
.set({ xp: user.xp + xp })
|
|
.where(eq(schema.users.id, id));
|
|
}
|
|
}
|
|
|
|
async logXpEvent(event: InsertXpEvent): Promise<XpEvent> {
|
|
const result = await this.db.insert(schema.xpEvents).values(event).returning();
|
|
// Also update user XP
|
|
if (event.userId) { // In real app ensure ID
|
|
await this.updateUserXP(event.userId, event.amount);
|
|
}
|
|
return result[0];
|
|
}
|
|
|
|
async getGoals(): Promise<Goal[]> {
|
|
return await this.db.select().from(schema.goals);
|
|
}
|
|
|
|
async createGoal(goal: InsertGoal): Promise<Goal> {
|
|
const result = await this.db.insert(schema.goals).values(goal).returning();
|
|
return result[0];
|
|
}
|
|
|
|
async updateGoal(id: string, updates: Partial<InsertGoal & { completed?: boolean; current?: number }>): Promise<Goal> {
|
|
const result = await this.db.update(schema.goals)
|
|
.set(updates)
|
|
.where(eq(schema.goals.id, id))
|
|
.returning();
|
|
if (!result[0]) throw new Error("Goal not found");
|
|
return result[0];
|
|
}
|
|
|
|
|
|
// Rewards
|
|
async getAllRewards(): Promise<Reward[]> {
|
|
return await this.db.select().from(schema.rewards);
|
|
}
|
|
|
|
async getUserRewards(userId: string): Promise<UserReward[]> {
|
|
return await this.db.select().from(schema.userRewards).where(eq(schema.userRewards.userId, userId));
|
|
}
|
|
|
|
async createReward(insertReward: InsertReward): Promise<Reward> {
|
|
const result = await this.db.insert(schema.rewards).values(insertReward).returning();
|
|
return result[0];
|
|
}
|
|
|
|
async createUserReward(insertUserReward: InsertUserReward): Promise<UserReward> {
|
|
const result = await this.db.insert(schema.userRewards).values(insertUserReward).returning();
|
|
return result[0];
|
|
}
|
|
|
|
async getXpEvents(userId: string): Promise<XpEvent[]> {
|
|
return await this.db.select()
|
|
.from(schema.xpEvents)
|
|
.where(eq(schema.xpEvents.userId, userId))
|
|
.orderBy(desc(schema.xpEvents.createdAt));
|
|
}
|
|
|
|
// Social Methods (DbStorage)
|
|
async getLeaderboard(): Promise<User[]> {
|
|
return await this.db.select()
|
|
.from(schema.users)
|
|
.where(and(
|
|
eq(schema.users.showOnLeaderboard, true),
|
|
eq(schema.users.isActive, true)
|
|
))
|
|
.orderBy(desc(schema.users.xp));
|
|
}
|
|
|
|
// Auth - Password Reset (DbStorage)
|
|
async createPasswordResetToken(insertToken: InsertPasswordResetToken): Promise<PasswordResetToken> {
|
|
const result = await this.db.insert(schema.passwordResetTokens).values(insertToken).returning();
|
|
return result[0];
|
|
}
|
|
|
|
async getPasswordResetToken(tokenString: string): Promise<PasswordResetToken | undefined> {
|
|
const result = await this.db.select().from(schema.passwordResetTokens).where(eq(schema.passwordResetTokens.token, tokenString));
|
|
return result[0];
|
|
}
|
|
|
|
async markPasswordResetTokenUsed(id: string): Promise<void> {
|
|
await this.db.update(schema.passwordResetTokens)
|
|
.set({ isUsed: true })
|
|
.where(eq(schema.passwordResetTokens.id, id));
|
|
}
|
|
|
|
async searchUsers(query: string): Promise<User[]> {
|
|
if (!query || query.length < 2) return [];
|
|
return await this.db.select()
|
|
.from(schema.users)
|
|
.where(and(
|
|
eq(schema.users.isSearchable, true),
|
|
eq(schema.users.isActive, true),
|
|
sql`${schema.users.username} ILIKE ${'%' + query + '%'}`
|
|
));
|
|
}
|
|
|
|
async shareTask(sharedTask: InsertSharedTask): Promise<SharedTask> {
|
|
return this.createSharedTask(sharedTask);
|
|
}
|
|
|
|
async createSharedTask(sharedTask: InsertSharedTask): Promise<SharedTask> {
|
|
const result = await this.db.insert(schema.sharedTasks).values(sharedTask).returning();
|
|
return result[0];
|
|
}
|
|
|
|
async shareAllTasks(access: InsertUserTaskAccess): Promise<UserTaskAccess> {
|
|
return this.createUserTaskAccess(access);
|
|
}
|
|
|
|
async createUserTaskAccess(access: InsertUserTaskAccess): Promise<UserTaskAccess> {
|
|
// Upsert or simple insert. Let's assume one Record per pair
|
|
const result = await this.db.insert(schema.userTaskAccess).values(access).returning();
|
|
return result[0];
|
|
}
|
|
|
|
async getSharedTasks(userId: string): Promise<SharedTask[]> {
|
|
return await this.db.select()
|
|
.from(schema.sharedTasks)
|
|
.where(eq(schema.sharedTasks.sharedWithUserId, userId));
|
|
}
|
|
|
|
async getUserTaskAccess(viewerId: string): Promise<UserTaskAccess[]> {
|
|
return await this.db.select()
|
|
.from(schema.userTaskAccess)
|
|
.where(eq(schema.userTaskAccess.viewerId, viewerId));
|
|
}
|
|
|
|
async getTaskSharedUsers(taskId: string): Promise<User[]> {
|
|
const result = await this.db.select({
|
|
id: schema.users.id,
|
|
username: schema.users.username,
|
|
email: schema.users.email,
|
|
role: schema.users.role,
|
|
isActive: schema.users.isActive,
|
|
xp: schema.users.xp,
|
|
level: schema.users.level,
|
|
currentStreak: schema.users.currentStreak,
|
|
lastTaskDate: schema.users.lastTaskDate,
|
|
showOnLeaderboard: schema.users.showOnLeaderboard,
|
|
isSearchable: schema.users.isSearchable,
|
|
apiKey: schema.users.apiKey,
|
|
aiEnabled: schema.users.aiEnabled,
|
|
password: schema.users.password // Generally shouldn't return this, but following pattern
|
|
})
|
|
.from(schema.sharedTasks)
|
|
.innerJoin(schema.users, eq(schema.sharedTasks.sharedWithUserId, schema.users.id))
|
|
.where(eq(schema.sharedTasks.taskId, taskId));
|
|
return result;
|
|
}
|
|
|
|
async unshareTask(taskId: string, userId: string): Promise<boolean> {
|
|
const result = await this.db.delete(schema.sharedTasks)
|
|
.where(and(
|
|
eq(schema.sharedTasks.taskId, taskId),
|
|
eq(schema.sharedTasks.sharedWithUserId, userId)
|
|
))
|
|
.returning();
|
|
return result.length > 0;
|
|
}
|
|
|
|
// Shared Labels (DbStorage)
|
|
async shareLabel(labelId: string, sharedWithUserId: string, sharedByUserId: string, permission: string = 'read'): Promise<SharedLabel> {
|
|
const result = await this.db.insert(schema.sharedLabels).values({
|
|
labelId,
|
|
sharedWithUserId,
|
|
sharedByUserId,
|
|
permission
|
|
}).returning();
|
|
return result[0];
|
|
}
|
|
|
|
async getSharedLabels(userId: string): Promise<SharedLabel[]> {
|
|
return await this.db.select()
|
|
.from(schema.sharedLabels)
|
|
.where(eq(schema.sharedLabels.sharedWithUserId, userId));
|
|
}
|
|
|
|
async getLabelSharedUsers(labelId: string): Promise<User[]> {
|
|
const result = await this.db.select({
|
|
id: schema.users.id,
|
|
username: schema.users.username,
|
|
email: schema.users.email,
|
|
role: schema.users.role,
|
|
isActive: schema.users.isActive,
|
|
xp: schema.users.xp,
|
|
level: schema.users.level,
|
|
currentStreak: schema.users.currentStreak,
|
|
lastTaskDate: schema.users.lastTaskDate,
|
|
showOnLeaderboard: schema.users.showOnLeaderboard,
|
|
isSearchable: schema.users.isSearchable,
|
|
apiKey: schema.users.apiKey,
|
|
aiEnabled: schema.users.aiEnabled,
|
|
password: schema.users.password
|
|
})
|
|
.from(schema.sharedLabels)
|
|
.innerJoin(schema.users, eq(schema.sharedLabels.sharedWithUserId, schema.users.id))
|
|
.where(eq(schema.sharedLabels.labelId, labelId));
|
|
return result;
|
|
}
|
|
|
|
async unshareLabel(labelId: string, userId: string): Promise<boolean> {
|
|
const result = await this.db.delete(schema.sharedLabels)
|
|
.where(and(
|
|
eq(schema.sharedLabels.labelId, labelId),
|
|
eq(schema.sharedLabels.sharedWithUserId, userId)
|
|
))
|
|
.returning();
|
|
return result.length > 0;
|
|
}
|
|
|
|
async getLabelShares(labelId: string): Promise<SharedLabel[]> {
|
|
return await this.db.select()
|
|
.from(schema.sharedLabels)
|
|
.where(eq(schema.sharedLabels.labelId, labelId));
|
|
}
|
|
}
|
|
|
|
// Export storage based on environment
|
|
export const storage = process.env.NODE_ENV === 'production' || process.env.USE_DB === 'true'
|
|
? new DbStorage()
|
|
: new MemStorage();
|