All files / src/common/utils newsletterActionHandlers.ts

53.86% Statements 251/466
86.44% Branches 51/59
54.54% Functions 12/22
53.86% Lines 251/466

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 554 555 556 557 558 559 560 561 562 563 564 5651x   1x 1x 1x                                               1x 22x 22x 22x 22x 22x 22x 22x   22x 22x 22x 22x 22x   22x 10x 10x 10x 10x 10x 10x 10x 10x 10x   10x   10x 9x 9x 9x 9x 9x 9x 8x 9x 1x 1x 1x 1x 1x 1x 1x 1x   1x 9x     10x     7x 2x 7x     10x 1x 10x 6x 6x   7x 10x 10x   3x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x   1x 1x 2x   3x 3x 3x 3x   3x 3x 3x 10x   22x                                                                                                               22x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   22x                                   22x                                                           22x 9x 9x 9x 9x 9x 9x   9x 9x 9x 9x 9x 9x 9x 9x 9x 9x   9x 9x 9x 9x 9x 9x   6x 6x 6x 6x 6x 6x 6x 6x   6x 9x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 9x 9x 9x 9x 9x 6x 6x 6x 6x 6x 9x 9x 9x   22x                                                 22x 10x 10x 10x 10x 10x 10x   10x 10x 10x 10x 10x 10x 10x 10x 10x   10x   10x   3x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 10x   6x 4x 4x 4x 4x 4x 4x 4x 4x 4x     6x 4x 6x   10x 5x 5x   10x 10x 3x   3x 3x 3x 3x 3x 3x 3x 3x 3x     3x   3x 3x 3x 3x 3x 3x 10x   22x                                                   22x                                   22x                                         22x                                   22x                                   22x                                                           22x 1x 1x 1x 1x 1x 22x     1x 3x 3x 3x 3x 3x  
import { readingQueueApi } from '@common/api';
import type { NewsletterWithRelations } from '@common/types';
import { toast } from 'react-hot-toast';
import { getCacheManager } from './cacheUtils';
import { logger } from './logger';
 
export interface NewsletterActionHandlers {
  markAsRead: (id: string) => Promise<void>;
  markAsUnread: (id: string) => Promise<void>;
  toggleLike: (id: string) => Promise<void>;
  toggleArchive: (id: string) => Promise<void>;
  deleteNewsletter: (id: string) => Promise<void>;
  toggleInQueue: (id: string) => Promise<void>;
  updateTags: (id: string, tagIds: string[]) => Promise<void>;
  bulkMarkAsRead: (ids: string[]) => Promise<void>;
  bulkMarkAsUnread: (ids: string[]) => Promise<void>;
  bulkArchive: (ids: string[]) => Promise<void>;
  bulkUnarchive: (ids: string[]) => Promise<void>;
  bulkDelete: (ids: string[]) => Promise<void>;
}
 
export interface NewsletterActionOptions {
  showToasts?: boolean;
  optimisticUpdates?: boolean;
  onSuccess?: (newsletter?: NewsletterWithRelations) => void;
  onError?: (error: Error) => void;
}
 
export class SharedNewsletterActionHandlers {
  private cacheManager: ReturnType<typeof getCacheManager>;
  private handlers: NewsletterActionHandlers;
  private log = logger;
  private defaultOptions: NewsletterActionOptions = {
    showToasts: true,
    optimisticUpdates: true,
  };
 
  constructor(handlers: NewsletterActionHandlers, options?: Partial<NewsletterActionOptions>) {
    this.handlers = handlers;
    this.cacheManager = getCacheManager();
    this.defaultOptions = { ...this.defaultOptions, ...options };
  }
 
  private async withOptimisticUpdate<T>(
    newsletterId: string,
    updates: Partial<NewsletterWithRelations>,
    operation: () => Promise<T>,
    operationType: string,
    options: NewsletterActionOptions = {}
  ): Promise<T> {
    const opts = { ...this.defaultOptions, ...options };
    let originalData: NewsletterWithRelations | null = null;
    let optimisticUpdateApplied = false;
 
    try {
      // Apply optimistic update if enabled
      if (opts.optimisticUpdates) {
        try {
          originalData = await this.cacheManager.optimisticUpdate(
            newsletterId,
            updates,
            operationType
          );
          optimisticUpdateApplied = true;
        } catch (_) {
          this.log.warn('Failed to apply optimistic update', {
            action: 'optimistic_update',
            metadata: {
              newsletterId,
              operationType,
              updateFields: Object.keys(updates),
            },
          });
          // Continue without optimistic update
        }
      }
 
      // Perform the actual operation
      const result = await operation();
 
      // Use gentle invalidation to prevent UI flashing
      setTimeout(async () => {
        await this.cacheManager.invalidateRelatedQueries([newsletterId], operationType);
      }, 100);
 
      // Dispatch custom events for real-time updates
      if (operationType === 'mark-read' || operationType === 'mark-unread') {
        window.dispatchEvent(new CustomEvent('newsletter:read-status-changed'));
      } else if (operationType === 'archive' || operationType === 'unarchive') {
        window.dispatchEvent(new CustomEvent('newsletter:archived'));
      }
 
      opts.onSuccess?.();
      return result;
    } catch (error) {
      // Revert optimistic update on error
      if (optimisticUpdateApplied && originalData) {
        try {
          this.cacheManager.updateNewsletterInCache({
            id: newsletterId,
            updates: originalData,
          });
        } catch (_) {
          this.log.warn('Failed to revert optimistic update', {
            action: 'revert_optimistic_update',
            metadata: {
              newsletterId,
              operationType,
            },
          });
          // Force refresh if revert fails
          await this.cacheManager.invalidateRelatedQueries([newsletterId], 'error-recovery');
        }
      }
 
      const errorMessage = error instanceof Error ? error.message : 'An error occurred';
      if (opts.showToasts) {
        toast.error(`Failed to ${operationType.replace('-', ' ')}: ${errorMessage}`);
      }
 
      opts.onError?.(error instanceof Error ? error : new Error(errorMessage));
      throw error;
    }
  }
 
  private async withBulkOptimisticUpdate<T>(
    newsletterIds: string[],
    updates: Partial<NewsletterWithRelations>,
    operation: () => Promise<T>,
    operationType: string,
    options: NewsletterActionOptions = {}
  ): Promise<T> {
    const opts = { ...this.defaultOptions, ...options };
    let optimisticUpdateApplied = false;
 
    try {
      // Apply bulk optimistic updates if enabled
      if (opts.optimisticUpdates) {
        try {
          this.cacheManager.batchUpdateNewsletters(newsletterIds.map((id) => ({ id, updates })));
          optimisticUpdateApplied = true;
        } catch (_) {
          this.log.warn('Failed to apply bulk optimistic update', {
            action: 'bulk_optimistic_update',
            metadata: {
              newsletterIds: newsletterIds.length,
              operationType,
              updateFields: Object.keys(updates),
            },
          });
          // Continue without optimistic update
        }
      }
 
      // Perform the actual operation
      const result = await operation();
 
      // Use gentle invalidation to prevent UI flashing for bulk operations
      setTimeout(async () => {
        await this.cacheManager.invalidateRelatedQueries(newsletterIds, operationType);
      }, 150);
 
      opts.onSuccess?.();
      return result;
    } catch (error) {
      // For bulk operations, we invalidate the entire cache on error
      // as reverting individual optimistic updates is complex
      if (optimisticUpdateApplied) {
        await this.cacheManager.invalidateRelatedQueries(newsletterIds, 'error-recovery');
      }
 
      const errorMessage = error instanceof Error ? error.message : 'An error occurred';
      if (opts.showToasts) {
        toast.error(`Failed to ${operationType.replace('-', ' ')}: ${errorMessage}`);
      }
 
      opts.onError?.(error instanceof Error ? error : new Error(errorMessage));
      throw error;
    }
  }
 
  async markAsRead(newsletterId: string, options?: NewsletterActionOptions): Promise<void> {
    return this.withOptimisticUpdate(
      newsletterId,
      { is_read: true },
      () => this.handlers.markAsRead(newsletterId),
      'mark-read',
      {
        ...options,
        onSuccess: () => {
          if (options?.showToasts !== false) {
            toast.success('Marked as read');
          }
          options?.onSuccess?.();
        },
      }
    );
  }
 
  async markAsUnread(newsletterId: string, options?: NewsletterActionOptions): Promise<void> {
    return this.withOptimisticUpdate(
      newsletterId,
      { is_read: false },
      () => this.handlers.markAsUnread(newsletterId),
      'mark-unread',
      {
        ...options,
        onSuccess: () => {
          if (options?.showToasts !== false) {
            toast.success('Marked as unread');
          }
          options?.onSuccess?.();
        },
      }
    );
  }
 
  async toggleLike(
    newsletter: NewsletterWithRelations,
    options?: NewsletterActionOptions
  ): Promise<void> {
    const newLikedState = !newsletter.is_liked;
    return this.withOptimisticUpdate(
      newsletter.id,
      {
        is_liked: newLikedState,
        updated_at: new Date().toISOString(),
      },
      () => this.handlers.toggleLike(newsletter.id),
      'toggle-like',
      {
        ...options,
        optimisticUpdates: true, // Always use optimistic updates for like
        onSuccess: () => {
          if (options?.showToasts !== false) {
            toast.success(newLikedState ? 'Added to liked' : 'Removed from liked');
          }
          options?.onSuccess?.({
            ...newsletter,
            is_liked: newLikedState,
            updated_at: new Date().toISOString(),
          });
        },
      }
    );
  }
 
  async toggleArchive(
    newsletter: NewsletterWithRelations,
    options?: NewsletterActionOptions
  ): Promise<void> {
    const newArchivedState = !newsletter.is_archived;
    const operation = newArchivedState ? 'archive' : 'unarchive';
    const startTime = Date.now();
 
    this.log.info('Starting archive operation', {
      action: 'archive_operation_start',
      metadata: {
        newsletterId: newsletter.id,
        newsletterTitle: newsletter.title,
        operation,
        currentArchiveState: newsletter.is_archived,
        newArchiveState: newArchivedState,
      },
    });
 
    return this.withOptimisticUpdate(
      newsletter.id,
      { is_archived: newArchivedState },
      async () => {
        try {
          const result = await this.handlers.toggleArchive(newsletter.id);
 
          this.log.info('Archive operation successful', {
            action: 'archive_operation_success',
            metadata: {
              newsletterId: newsletter.id,
              operation,
              duration: Date.now() - startTime,
            },
          });
 
          return result;
        } catch (error) {
          this.log.error('Archive operation failed', {
            action: 'archive_operation_error',
            metadata: {
              newsletterId: newsletter.id,
              operation,
              error: error instanceof Error ? error.message : 'Unknown error',
              duration: Date.now() - startTime,
            },
          });
          throw error;
        }
      },
      operation,
      {
        ...options,
        onSuccess: () => {
          if (options?.showToasts !== false) {
            toast.success(newArchivedState ? 'Newsletter archived' : 'Newsletter unarchived');
          }
          options?.onSuccess?.(newsletter);
        },
      }
    );
  }
 
  async deleteNewsletter(newsletterId: string, options?: NewsletterActionOptions): Promise<void> {
    if (!window.confirm('Are you sure? This action is final and cannot be undone.')) {
      return;
    }
 
    try {
      await this.handlers.deleteNewsletter(newsletterId);
 
      // Remove from cache immediately
      await this.cacheManager.invalidateRelatedQueries([newsletterId], 'delete');
 
      if (options?.showToasts !== false) {
        toast.success('Newsletter deleted permanently');
      }
      options?.onSuccess?.();
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'An error occurred';
      if (options?.showToasts !== false) {
        toast.error(`Failed to delete newsletter: ${errorMessage}`);
      }
      options?.onError?.(error instanceof Error ? error : new Error(errorMessage));
      throw error;
    }
  }
 
  async toggleInQueue(
    newsletter: NewsletterWithRelations,
    isInQueue: boolean,
    options?: NewsletterActionOptions
  ): Promise<void> {
    const startTime = Date.now();
    const operation = isInQueue ? 'remove-from-queue' : 'add-to-queue';
 
    this.log.info('Starting queue operation', {
      action: 'queue_operation_start',
      metadata: {
        newsletterId: newsletter.id,
        operation,
        isInQueue,
        newsletterTitle: newsletter.title,
      },
    });
 
    try {
      // Use the isInQueue parameter to determine the correct action
      if (isInQueue) {
        // Remove from queue - find the queue item first
        const queueItems = await readingQueueApi.getAll();
        const queueItem = queueItems.find((item) => item.newsletter_id === newsletter.id);
        if (queueItem) {
          await readingQueueApi.remove(queueItem.id);
          this.log.info('Successfully removed from queue', {
            action: 'queue_remove_success',
            metadata: {
              newsletterId: newsletter.id,
              queueItemId: queueItem.id,
              duration: Date.now() - startTime,
            },
          });
        } else {
          throw new Error('Newsletter not found in reading queue');
        }
      } else {
        // Add to queue
        const queueItem = await readingQueueApi.add(newsletter.id);
        this.log.info('Successfully added to queue', {
          action: 'queue_add_success',
          metadata: {
            newsletterId: newsletter.id,
            queueItemId: queueItem.id,
            duration: Date.now() - startTime,
          },
        });
      }
 
      // Invalidate reading queue cache after successful operation
      setTimeout(async () => {
        await this.cacheManager.invalidateRelatedQueries([newsletter.id], 'toggle-queue');
      }, 100);
 
      if (options?.showToasts !== false) {
        toast.success(isInQueue ? 'Removed from reading queue' : 'Added to reading queue');
      }
 
      options?.onSuccess?.(newsletter);
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'An error occurred';
 
      this.log.error('Queue operation failed', {
        action: 'queue_operation_error',
        metadata: {
          newsletterId: newsletter.id,
          operation,
          error: errorMessage,
          duration: Date.now() - startTime,
        },
      });
 
      // Force cache refresh on error to ensure consistency
      await this.cacheManager.invalidateRelatedQueries([newsletter.id], 'toggle-queue-error');
 
      if (options?.showToasts !== false) {
        toast.error(`Failed to update reading queue: ${errorMessage}`);
      }
      options?.onError?.(error instanceof Error ? error : new Error(errorMessage));
      throw error;
    }
  }
 
  async updateTags(
    newsletterId: string,
    tagIds: string[],
    options?: NewsletterActionOptions
  ): Promise<void> {
    try {
      await this.handlers.updateTags(newsletterId, tagIds);
 
      // Invalidate tag-related queries
      await this.cacheManager.invalidateRelatedQueries([newsletterId], 'tag-update');
 
      if (options?.showToasts !== false) {
        toast.success('Tags updated successfully');
      }
      options?.onSuccess?.();
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'An error occurred';
      if (options?.showToasts !== false) {
        toast.error(`Failed to update tags: ${errorMessage}`);
      }
      options?.onError?.(error instanceof Error ? error : new Error(errorMessage));
      throw error;
    }
  }
 
  // Bulk operations
  async bulkMarkAsRead(newsletterIds: string[], options?: NewsletterActionOptions): Promise<void> {
    return this.withBulkOptimisticUpdate(
      newsletterIds,
      { is_read: true },
      () => this.handlers.bulkMarkAsRead(newsletterIds),
      'bulk-mark-read',
      {
        ...options,
        onSuccess: () => {
          if (options?.showToasts !== false) {
            toast.success(`Marked ${newsletterIds.length} newsletters as read`);
          }
          options?.onSuccess?.();
        },
      }
    );
  }
 
  async bulkMarkAsUnread(
    newsletterIds: string[],
    options?: NewsletterActionOptions
  ): Promise<void> {
    return this.withBulkOptimisticUpdate(
      newsletterIds,
      { is_read: false },
      () => this.handlers.bulkMarkAsUnread(newsletterIds),
      'bulk-mark-unread',
      {
        ...options,
        onSuccess: () => {
          if (options?.showToasts !== false) {
            toast.success(`Marked ${newsletterIds.length} newsletters as unread`);
          }
          options?.onSuccess?.();
        },
      }
    );
  }
 
  async bulkArchive(newsletterIds: string[], options?: NewsletterActionOptions): Promise<void> {
    return this.withBulkOptimisticUpdate(
      newsletterIds,
      { is_archived: true },
      () => this.handlers.bulkArchive(newsletterIds),
      'bulk-archive',
      {
        ...options,
        onSuccess: () => {
          if (options?.showToasts !== false) {
            toast.success(`Archived ${newsletterIds.length} newsletters`);
          }
          options?.onSuccess?.();
        },
      }
    );
  }
 
  async bulkUnarchive(newsletterIds: string[], options?: NewsletterActionOptions): Promise<void> {
    return this.withBulkOptimisticUpdate(
      newsletterIds,
      { is_archived: false },
      () => this.handlers.bulkUnarchive(newsletterIds),
      'bulk-unarchive',
      {
        ...options,
        onSuccess: () => {
          if (options?.showToasts !== false) {
            toast.success(`Unarchived ${newsletterIds.length} newsletters`);
          }
          options?.onSuccess?.();
        },
      }
    );
  }
 
  async bulkDelete(newsletterIds: string[], options?: NewsletterActionOptions): Promise<void> {
    if (
      !window.confirm(
        `Are you sure you want to permanently delete ${newsletterIds.length} newsletters? This action cannot be undone.`
      )
    ) {
      return;
    }
 
    try {
      await this.handlers.bulkDelete(newsletterIds);
 
      // Invalidate related queries
      await this.cacheManager.invalidateRelatedQueries(newsletterIds, 'bulk-delete');
 
      if (options?.showToasts !== false) {
        toast.success(`Deleted ${newsletterIds.length} newsletters permanently`);
      }
      options?.onSuccess?.();
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'An error occurred';
      if (options?.showToasts !== false) {
        toast.error(`Failed to delete newsletters: ${errorMessage}`);
      }
      options?.onError?.(error instanceof Error ? error : new Error(errorMessage));
      throw error;
    }
  }
 
  // Utility method to create handlers with specific options
  withOptions(options: Partial<NewsletterActionOptions>): SharedNewsletterActionHandlers {
    return new SharedNewsletterActionHandlers(this.handlers, {
      ...this.defaultOptions,
      ...options,
    });
  }
}
 
// Factory function to create shared handlers
export function createSharedNewsletterHandlers(
  handlers: NewsletterActionHandlers,
  options?: Partial<NewsletterActionOptions>
): SharedNewsletterActionHandlers {
  return new SharedNewsletterActionHandlers(handlers, options);
}