|
|
|
|
@ -2,6 +2,9 @@ import { db } from '../db';
|
|
|
|
|
// Environment variables will be mocked in tests
|
|
|
|
|
const env = process.env;
|
|
|
|
|
|
|
|
|
|
// In-memory cache for active groups
|
|
|
|
|
const activeGroupsCache = new Map<string, string>(); // groupId -> groupName
|
|
|
|
|
|
|
|
|
|
type EvolutionGroup = {
|
|
|
|
|
id: string;
|
|
|
|
|
subject: string;
|
|
|
|
|
@ -92,6 +95,43 @@ export class GroupSyncService {
|
|
|
|
|
return data.response;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private static cacheActiveGroups(): void {
|
|
|
|
|
const groups = db.prepare('SELECT id, name FROM groups WHERE active = TRUE').all();
|
|
|
|
|
activeGroupsCache.clear();
|
|
|
|
|
for (const group of groups) {
|
|
|
|
|
activeGroupsCache.set(group.id, group.name);
|
|
|
|
|
}
|
|
|
|
|
console.log(`Cached ${activeGroupsCache.size} active groups`);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private static getActiveGroupsCount(): number {
|
|
|
|
|
const result = db.prepare('SELECT COUNT(*) as count FROM groups WHERE active = TRUE').get();
|
|
|
|
|
return result?.count || 0;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
static async checkInitialGroups(): Promise<void> {
|
|
|
|
|
const count = this.getActiveGroupsCount();
|
|
|
|
|
if (count > 0) {
|
|
|
|
|
this.cacheActiveGroups();
|
|
|
|
|
console.log(`✅ Using ${count} existing groups from database`);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
console.log('⚠️ No groups found in database - performing initial sync');
|
|
|
|
|
try {
|
|
|
|
|
const { added } = await this.syncGroups();
|
|
|
|
|
if (added === 0) {
|
|
|
|
|
throw new Error('Initial group sync completed but no groups were added');
|
|
|
|
|
}
|
|
|
|
|
this.cacheActiveGroups();
|
|
|
|
|
console.log(`✅ Initial group sync completed - added ${added} groups`);
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error('❌ Critical: Initial group sync failed - no groups available');
|
|
|
|
|
console.error(error instanceof Error ? error.message : 'Unknown error');
|
|
|
|
|
process.exit(1);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private static async upsertGroups(groups: EvolutionGroup[]): Promise<{ added: number; updated: number }> {
|
|
|
|
|
let added = 0;
|
|
|
|
|
let updated = 0;
|
|
|
|
|
|