All files / src/common/services/readingQueue ReadingQueueService.ts

86.47% Statements 339/392
84.61% Branches 88/104
100% Functions 26/26
86.47% Lines 339/392

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 5541x 1x   1x 1x                                                           1x 85x   85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x         85x 16x 16x     14x 16x 16x         85x 5x 5x 5x     5x 4x 4x 4x 3x 3x 4x                     4x   5x 5x 5x         85x 14x   14x 14x 11x   11x 11x 2x 2x 2x 2x 2x   11x 1x 1x 1x 1x 1x     8x 8x   11x               11x 1x 1x 1x 1x 1x   7x 7x 7x 7x   6x 6x 6x 6x 6x 11x 1x 1x 1x 1x 1x 11x 14x 14x 14x 14x         85x 6x   6x 6x 5x   5x 5x   5x 1x 1x 1x 1x 1x   4x 4x 4x 4x   5x             3x 3x 3x 3x 5x 1x 1x 1x 1x 1x 5x 6x 6x 6x 6x         85x 4x   4x 4x 2x   2x 4x 4x 4x 4x 4x 4x 4x 4x             4x   2x 2x 2x 2x 2x   2x 2x 2x 2x 2x 2x 2x 4x 4x 4x 4x         85x 1x   1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x             1x   1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x         85x 4x 4x 4x   4x 1x 1x 1x 1x 1x   3x   4x             2x 4x 1x 1x 1x 1x 1x 4x 4x         85x 5x 5x 5x   5x 5x 5x   5x 5x   5x 5x 1x 1x 1x 1x 1x 5x     4x 4x 4x 4x 4x 4x 4x   4x 4x 4x 4x   5x             3x 5x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x         85x 2x 2x 2x   2x 2x 2x 2x 2x   2x 2x   2x 2x 1x 1x   2x 2x 2x 2x 2x 2x 2x 2x 2x         85x 3x 2x 2x 2x 2x 2x 2x 2x   1x 1x 1x   1x                 1x 1x 3x         85x 4x   4x 4x   2x 2x 4x 4x 4x 4x           85x 14x           14x   99x             99x 14x 14x             85x 1x 1x     85x 1x 1x 1x     85x   1x 1x 1x     1x 1x 1x     85x 1x 1x 1x     85x   1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x     85x 1x 1x 1x 85x     1x  
import { newsletterApi } from '@common/api/newsletterApi';
import { readingQueueApi } from '@common/api/readingQueueApi';
import { NewsletterWithRelations, ReadingQueueItem } from '@common/types';
import { logger } from '@common/utils/logger';
import { BaseService } from '../base/BaseService';
 
export interface ReadingQueueOperationResult {
  success: boolean;
  item?: ReadingQueueItem;
  newsletter?: NewsletterWithRelations;
  error?: string;
}
 
export interface BulkReadingQueueOperationResult {
  success: boolean;
  processedCount: number;
  failedCount: number;
  errors: Array<{ id: string; error: string }>;
}
 
export interface ReadingQueueStats {
  totalItems: number;
  unreadItems: number;
  averageReadTime: number;
  oldestItem?: ReadingQueueItem;
  estimatedReadTime: number;
}
 
export interface ReadingQueueServiceOptions {
  maxQueueSize?: number;
  autoRemoveRead?: boolean;
  priorityOrdering?: boolean;
}
 
export class ReadingQueueService extends BaseService {
  private queueOptions: ReadingQueueServiceOptions;
 
  constructor(options: ReadingQueueServiceOptions = {}) {
    super({
      retryOptions: {
        maxRetries: 3,
        baseDelay: 1000,
      },
      timeout: 30000,
    });
    this.queueOptions = {
      maxQueueSize: 100,
      autoRemoveRead: true,
      priorityOrdering: true,
      ...options,
    };
  }
 
  /**
   * Get all items in reading queue
   */
  async getReadingQueue(): Promise<ReadingQueueItem[]> {
    return this.executeWithLogging(async () => {
      const items = await this.withRetry(() => readingQueueApi.getAll(), 'getReadingQueue');
 
      // Apply business logic for ordering
      return this.applyQueueOrdering(items);
    }, 'getReadingQueue');
  }
 
  /**
   * Get reading queue with full newsletter details
   */
  async getReadingQueueWithDetails(): Promise<NewsletterWithRelations[]> {
    return this.executeWithLogging(async () => {
      const queueItems = await this.getReadingQueue();
      const newsletters: NewsletterWithRelations[] = [];
 
      // Fetch newsletter details for each queue item
      for (const item of queueItems) {
        try {
          const newsletter = await newsletterApi.getById(item.newsletter_id);
          if (newsletter) {
            newsletters.push(newsletter);
          }
        } catch (error) {
          logger.warn(
            'Failed to fetch newsletter details for queue item',
            {
              component: 'ReadingQueueService',
              action: 'get_queue_with_details',
              metadata: { newsletterId: item.newsletter_id },
            },
            error instanceof Error ? error : new Error(String(error))
          );
        }
      }
 
      return newsletters;
    }, 'getReadingQueueWithDetails');
  }
 
  /**
   * Add newsletter to reading queue
   */
  async addToQueue(newsletterId: string): Promise<ReadingQueueOperationResult> {
    this.validateString(newsletterId, 'newsletter ID', { minLength: 1 });
 
    return this.executeWithLogging(
      async () => {
        try {
          // Validate newsletter exists and is not archived
          const newsletter = await newsletterApi.getById(newsletterId);
          if (!newsletter) {
            return {
              success: false,
              error: 'Newsletter not found',
            };
          }
 
          if (newsletter.is_archived) {
            return {
              success: false,
              error: 'Cannot add archived newsletter to reading queue',
            };
          }
 
          // Check if already in queue
          const existingItems = await readingQueueApi.getAll();
          const alreadyInQueue = existingItems.find((item) => item.newsletter_id === newsletterId);
 
          if (alreadyInQueue) {
            return {
              success: false,
              error: 'Newsletter is already in reading queue',
            };
          }
 
          // Check queue size limit
          if (existingItems.length >= this.queueOptions.maxQueueSize!) {
            return {
              success: false,
              error: `Reading queue is full (maximum ${this.queueOptions.maxQueueSize} items)`,
            };
          }
 
          const newItem = await this.withRetry(
            () => readingQueueApi.add(newsletterId),
            'addToQueue'
          );
 
          return {
            success: true,
            item: newItem,
            newsletter,
          };
        } catch (error) {
          return {
            success: false,
            error: error instanceof Error ? error.message : 'Unknown error',
          };
        }
      },
      'addToQueue',
      { newsletterId }
    );
  }
 
  /**
   * Remove newsletter from reading queue
   */
  async removeFromQueue(newsletterId: string): Promise<ReadingQueueOperationResult> {
    this.validateString(newsletterId, 'newsletter ID', { minLength: 1 });
 
    return this.executeWithLogging(
      async () => {
        try {
          // Check if item exists in queue
          const existingItems = await readingQueueApi.getAll();
          const queueItem = existingItems.find((item) => item.newsletter_id === newsletterId);
 
          if (!queueItem) {
            return {
              success: false,
              error: 'Newsletter is not in reading queue',
            };
          }
 
          const success = await this.withRetry(
            () => readingQueueApi.remove(queueItem.id),
            'removeFromQueue'
          );
 
          if (!success) {
            return {
              success: false,
              error: 'Failed to remove newsletter from reading queue',
            };
          }
 
          return {
            success: true,
            item: queueItem,
          };
        } catch (error) {
          return {
            success: false,
            error: error instanceof Error ? error.message : 'Unknown error',
          };
        }
      },
      'removeFromQueue',
      { newsletterId }
    );
  }
 
  /**
   * Bulk add newsletters to reading queue
   */
  async bulkAddToQueue(newsletterIds: string[]): Promise<BulkReadingQueueOperationResult> {
    this.validateArray(newsletterIds, 'newsletter IDs', { minLength: 1 });
 
    return this.executeWithLogging(
      async () => {
        const results: Array<{ id: string; success: boolean; error?: string }> = [];
 
        for (const newsletterId of newsletterIds) {
          try {
            const result = await this.addToQueue(newsletterId);
            results.push({
              id: newsletterId,
              success: result.success,
              error: result.error,
            });
          } catch (error) {
            results.push({
              id: newsletterId,
              success: false,
              error: error instanceof Error ? error.message : 'Unknown error',
            });
          }
        }
 
        const processedCount = results.filter((r) => r.success).length;
        const failedCount = results.length - processedCount;
        const errors = results
          .filter((r) => !r.success)
          .map((r) => ({ id: r.id, error: r.error || 'Unknown error' }));
 
        return {
          success: failedCount === 0,
          processedCount,
          failedCount,
          errors,
        };
      },
      'bulkAddToQueue',
      { count: newsletterIds.length }
    );
  }
 
  /**
   * Bulk remove newsletters from reading queue
   */
  async bulkRemoveFromQueue(newsletterIds: string[]): Promise<BulkReadingQueueOperationResult> {
    this.validateArray(newsletterIds, 'newsletter IDs', { minLength: 1 });
 
    return this.executeWithLogging(
      async () => {
        const results: Array<{ id: string; success: boolean; error?: string }> = [];
 
        for (const newsletterId of newsletterIds) {
          try {
            const result = await this.removeFromQueue(newsletterId);
            results.push({
              id: newsletterId,
              success: result.success,
              error: result.error,
            });
          } catch (error) {
            results.push({
              id: newsletterId,
              success: false,
              error: error instanceof Error ? error.message : 'Unknown error',
            });
          }
        }
 
        const processedCount = results.filter((r) => r.success).length;
        const failedCount = results.length - processedCount;
        const errors = results
          .filter((r) => !r.success)
          .map((r) => ({ id: r.id, error: r.error || 'Unknown error' }));
 
        return {
          success: failedCount === 0,
          processedCount,
          failedCount,
          errors,
        };
      },
      'bulkRemoveFromQueue',
      { count: newsletterIds.length }
    );
  }
 
  /**
   * Clear all items from reading queue
   */
  async clearQueue(): Promise<ReadingQueueOperationResult> {
    return this.executeWithLogging(async () => {
      try {
        const existingItems = await readingQueueApi.getAll();
 
        if (existingItems.length === 0) {
          return {
            success: true,
            error: 'Reading queue is already empty',
          };
        }
 
        const success = await this.withRetry(() => readingQueueApi.clear(), 'clearQueue');
 
        if (!success) {
          return {
            success: false,
            error: 'Failed to clear reading queue',
          };
        }
 
        return { success: true };
      } catch (error) {
        return {
          success: false,
          error: error instanceof Error ? error.message : 'Unknown error',
        };
      }
    }, 'clearQueue');
  }
 
  /**
   * Reorder reading queue items
   */
  async reorderQueue(orderedNewsletterIds: string[]): Promise<ReadingQueueOperationResult> {
    this.validateArray(orderedNewsletterIds, 'ordered newsletter IDs', {
      minLength: 1,
    });
 
    return this.executeWithLogging(
      async () => {
        try {
          // Validate all newsletters are in the queue
          const existingItems = await readingQueueApi.getAll();
          const existingIds = new Set(existingItems.map((item) => item.newsletter_id));
 
          for (const newsletterId of orderedNewsletterIds) {
            if (!existingIds.has(newsletterId)) {
              return {
                success: false,
                error: `Newsletter ${newsletterId} not found in reading queue`,
              };
            }
          }
 
          // Create the reorder updates with positions
          const reorderUpdates = orderedNewsletterIds.map((newsletterId, index) => {
            const item = existingItems.find((item) => item.newsletter_id === newsletterId);
            return {
              id: item!.id,
              position: index + 1,
            };
          });
 
          const success = await this.withRetry(
            () => readingQueueApi.reorder(reorderUpdates),
            'reorderQueue'
          );
 
          if (!success) {
            return {
              success: false,
              error: 'Failed to reorder reading queue',
            };
          }
 
          return { success: true };
        } catch (error) {
          return {
            success: false,
            error: error instanceof Error ? error.message : 'Unknown error',
          };
        }
      },
      'reorderQueue',
      { count: orderedNewsletterIds.length }
    );
  }
 
  /**
   * Get reading queue statistics
   */
  async getQueueStats(): Promise<ReadingQueueStats> {
    return this.executeWithLogging(async () => {
      const items = await this.getReadingQueue();
      const newsletters = await this.getReadingQueueWithDetails();
 
      const unreadItems = newsletters.filter((n) => !n.is_read).length;
      const totalEstimatedTime = newsletters.reduce(
        (sum, n) => sum + (n.estimated_read_time || 5),
        0
      );
 
      const averageReadTime =
        newsletters.length > 0 ? Math.round(totalEstimatedTime / newsletters.length) : 0;
 
      const oldestItem =
        items.length > 0
          ? items.sort((a, b) => new Date(a.added_at).getTime() - new Date(b.added_at).getTime())[0]
          : undefined;
 
      return {
        totalItems: items.length,
        unreadItems,
        averageReadTime,
        oldestItem,
        estimatedReadTime: totalEstimatedTime,
      };
    }, 'getQueueStats');
  }
 
  /**
   * Auto-cleanup reading queue (remove read newsletters if enabled)
   */
  async autoCleanup(): Promise<BulkReadingQueueOperationResult> {
    if (!this.queueOptions.autoRemoveRead) {
      return {
        success: true,
        processedCount: 0,
        failedCount: 0,
        errors: [],
      };
    }
 
    return this.executeWithLogging(async () => {
      const newsletters = await this.getReadingQueueWithDetails();
      const readNewsletterIds = newsletters.filter((n) => n.is_read).map((n) => n.id);
 
      if (readNewsletterIds.length === 0) {
        return {
          success: true,
          processedCount: 0,
          failedCount: 0,
          errors: [],
        };
      }
 
      return await this.bulkRemoveFromQueue(readNewsletterIds);
    }, 'autoCleanup');
  }
 
  /**
   * Check if newsletter is in reading queue
   */
  async isInQueue(newsletterId: string): Promise<boolean> {
    this.validateString(newsletterId, 'newsletter ID', { minLength: 1 });
 
    return this.executeWithLogging(
      async () => {
        // Use the efficient API method that only queries for the specific newsletter
        return await readingQueueApi.isInQueue(newsletterId);
      },
      'isInQueue',
      { newsletterId }
    );
  }
 
  /**
   * Private helper methods
   */
 
  private applyQueueOrdering(items: ReadingQueueItem[]): ReadingQueueItem[] {
    if (!this.queueOptions.priorityOrdering) {
      return items;
    }
 
    // Apply business logic for queue ordering
    // Priority: creation date (older items first), then priority if available
    return items.sort((a, b) => {
      // First sort by creation date (oldest first)
      const dateComparison = new Date(a.added_at).getTime() - new Date(b.added_at).getTime();
 
      // Future: Add priority field to ReadingQueueItem and sort by priority
      // if (a.priority !== b.priority) {
      //   return (b.priority || 0) - (a.priority || 0);
      // }
 
      return dateComparison;
    });
  }
 
  /**
   * Alias methods for backward compatibility
   */
 
  // Alias for getReadingQueue
  async getAll(): Promise<ReadingQueueItem[]> {
    return this.getReadingQueue();
  }
 
  // Alias for addToQueue
  async add(newsletterId: string): Promise<boolean> {
    const result = await this.addToQueue(newsletterId);
    return result.success;
  }
 
  // Alias for removeFromQueue
  async remove(queueItemId: string): Promise<boolean> {
    // Find the newsletter ID from the queue item ID
    const existingItems = await readingQueueApi.getAll();
    const item = existingItems.find((item) => item.id === queueItemId);
    if (!item) {
      return false;
    }
    const result = await this.removeFromQueue(item.newsletter_id);
    return result.success;
  }
 
  // Alias for clearQueue
  async clear(): Promise<boolean> {
    const result = await this.clearQueue();
    return result.success;
  }
 
  // Alias for reorderQueue
  async reorder(updates: { id: string; position: number }[]): Promise<boolean> {
    // Find the queue items and get their newsletter IDs
    const existingItems = await readingQueueApi.getAll();
    const orderedNewsletterIds = updates
      .sort((a, b) => a.position - b.position)
      .map((update) => {
        const item = existingItems.find((item) => item.id === update.id);
        return item?.newsletter_id;
      })
      .filter(Boolean) as string[];
 
    const result = await this.reorderQueue(orderedNewsletterIds);
    return result.success;
  }
 
  // Method for cleaning up orphaned items
  async cleanupOrphanedItems(): Promise<{ removedCount: number }> {
    const result = await this.autoCleanup();
    return { removedCount: result.processedCount };
  }
}
 
// Export singleton instance
export const readingQueueService = new ReadingQueueService();