OpenStock is an open-source alternative to expensive market platforms. Track real-time prices, set personalized alerts, and explore detailed company insights — built openly, for everyone, forever free.
// Server-only helpers for background jobs. Deliberately NOT a 'use server' module: these read
// every user's email and watchlist, so they must never be callable from a browser.
import {connectToDatabase} from "@/database/mongoose";
import { Watchlist } from "@/database/models/watchlist.model";
export const getAllUsersForNewsEmail = async () => {
try {
const mongoose = await connectToDatabase();
const db = mongoose.connection.db;
if(!db) throw new Error('Mongoose connection not connected');
const users = await db.collection('user').find(
{ email: { $exists: true, $ne: null }},
{ projection: { _id: 1, id: 1, email: 1, name: 1, country:1 }}
).toArray();
return users.filter((user) => user.email && user.name).map((user) => ({
id: user.id || user._id?.toString() || '',
email: user.email,
name: user.name
}))
} catch (e) {
console.error('Error fetching users for news email:', e)
return []
}
}
export async function getWatchlistSymbolsByEmail(email: string): Promise<string[]> {
if (!email) return [];
try {
const mongoose = await connectToDatabase();
const db = mongoose.connection.db;
if (!db) throw new Error('MongoDB connection not found');
// Better Auth stores users in the "user" collection
const user = await db.collection('user').findOne<{ _id?: unknown; id?: string; email?: string }>({ email });
if (!user) return [];
const userId = (user.id as string) || String(user._id || '');
if (!userId) return [];
const items = await Watchlist.find({ userId }, { symbol: 1 }).lean();
return items.map((i) => String(i.symbol));
} catch (err) {
console.error('getWatchlistSymbolsByEmail error:', err);
return [];
}
}