All files / src/web/services searchService.ts

75.98% Statements 250/329
83.33% Branches 50/60
89.65% Functions 26/29
75.98% Lines 250/329

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 5231x       1x 1x   1x 1x                                                                                                             40x 40x 40x   40x   40x 40x 40x   40x 15x 15x         40x                                                                                                             40x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x         40x 4x 4x 3x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x         40x 4x 4x 4x 4x 4x     4x 4x 4x 4x 4x   2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 4x         40x 2x 2x 2x 2x 2x     2x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 2x         40x 2x   1x 1x 1x 1x 1x   1x 2x         40x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x         40x 1x 1x 1x 1x 1x 1x                   1x         40x                 40x 1x 1x 1x 1x 1x                   1x         40x 11x 11x 11x 11x 11x 11x 11x 11x         40x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x         40x 5x   5x 5x 4x 2x 2x 2x   5x         40x 1x 1x         40x 3x   3x 2x 2x   3x 2x 2x   3x 3x         40x     2x 2x 2x 2x 2x 2x         40x 1x 1x   1x 1x         40x 4x 1x 1x   4x 1x 1x 1x 1x 1x   4x 1x 1x 1x 1x 1x   1x 4x         40x 3x 1x 1x   3x 1x 1x   1x 3x         40x 2x 2x         40x 2x 2x         40x 2x 2x         40x         1x 1x 1x 1x 1x 1x 1x 1x 40x     1x 32x 32x 32x 32x     1x 1x                                   1x
import {
  getAllNewsletterSources as apiGetAllNewsletterSources,
  updateNewsletter as apiUpdateNewsletter,
} from "@common/api";
import { newsletterGroupService } from "@common/services/newsletterGroup/NewsletterGroupService";
import { optimizedNewsletterService } from "@common/services/optimizedNewsletterService";
import { Newsletter, NewsletterGroup, NewsletterSource } from "@common/types";
import { logger as appLogger } from "@common/utils/logger";
import {
  buildSearchParams as utilBuildSearchParams,
  validateSearchFilters as utilValidateSearchFilters,
} from "../utils/searchUtils";
 
export interface SearchServiceDependencies {
  getAllNewsletterSources: typeof apiGetAllNewsletterSources;
  updateNewsletter: typeof apiUpdateNewsletter;
  newsletterService: typeof optimizedNewsletterService;
  newsletterGroupService: {
    getGroups: () => Promise<NewsletterGroup[]>;
  };
  logger: {
    error: (message: string, context?: Record<string, unknown>, error?: Error) => void;
    info: (message: string, context?: Record<string, unknown>) => void;
    debug: (message: string, context?: Record<string, unknown>) => void;
  };
  window: Pick<Window, "location" | "history" | "localStorage">;
  buildSearchParams: typeof utilBuildSearchParams;
  validateSearchFilters: typeof utilValidateSearchFilters;
}
 
export interface SearchFilters {
  selectedSources: string[];
  selectedGroups: string[];
  archivedStatus: "all" | "archived" | "active";
  dateFrom: string;
  dateTo: string;
}
 
export interface SearchOptions {
  query: string;
  filters: SearchFilters;
  page: number;
  itemsPerPage: number;
}
 
export interface SearchResult {
  data: Newsletter[];
  count: number;
  page: number;
  hasMore: boolean;
  totalPages: number;
}
 
export interface SearchState {
  results: Newsletter[];
  loading: boolean;
  error: string | null;
  searchPerformed: boolean;
  totalCount: number;
  currentPage: number;
  hasMore: boolean;
}
 
class SearchService {
  private static readonly RECENT_SEARCHES_KEY = "newsletter_recent_searches";
  private static readonly MAX_RECENT_SEARCHES = 10;
 
  private readonly deps: SearchServiceDependencies;
 
  constructor(dependencies: SearchServiceDependencies) {
    this.deps = dependencies;
  }
 
  private get log() {
    return this.deps.logger;
  }
 
  /**
   * Performs a search with the given options
   */
  async search(options: SearchOptions): Promise<SearchResult> {
    const { query, filters, page, itemsPerPage } = options;
 
    // Validate search query
    if (!query.trim()) {
      throw new Error("Search query cannot be empty");
    }
 
    // Validate filters
    const validation = this.deps.validateSearchFilters(filters);
    if (!validation.isValid) {
      throw new Error(validation.errors.join(", "));
    }
 
    // Build search parameters
    const searchParams = this.deps.buildSearchParams(query, filters, {
      page,
      itemsPerPage,
    });
 
    try {
      const response = await this.deps.newsletterService.getAll({
        ...searchParams,
        search: query,
        limit: itemsPerPage,
        offset: (page - 1) * itemsPerPage,
      });
 
      return {
        data: response.data || [],
        count: response.count || 0,
        page: response.page || page,
        hasMore: response.hasMore || false,
        totalPages: Math.ceil((response.count || 0) / itemsPerPage),
      };
    } catch (error) {
      this.log.error(
        "Search failed",
        {
          action: "search_newsletters",
          metadata: {
            query: options.query,
            page: options.page,
            filters: options.filters,
          },
        },
        error instanceof Error ? error : new Error(String(error)),
      );
      throw new Error("Failed to search newsletters. Please try again.");
    }
  }
 
  /**
   * Get all newsletter sources for filtering
   */
  async getSources(): Promise<NewsletterSource[]> {
    try {
      const response = await this.deps.getAllNewsletterSources();
      return response.data || [];
    } catch (error) {
      this.log.error(
        "Failed to load newsletter sources",
        {
          action: "get_sources",
          metadata: {},
        },
        error instanceof Error ? error : new Error(String(error)),
      );
      throw new Error("Failed to load newsletter sources");
    }
  }
 
  /**
   * Gets all newsletter groups for filtering
   */
  async getGroups(): Promise<NewsletterGroup[]> {
    try {
      const response = await this.deps.newsletterGroupService.getGroups();
      return response;
    } catch (error) {
      this.log.error(
        "Failed to load newsletter groups",
        {
          action: "get_groups",
          metadata: {},
        },
        error instanceof Error ? error : new Error(String(error)),
      );
      throw new Error("Failed to load newsletter groups");
    }
  }
 
  /**
   * Marks a newsletter as read and archives it
   */
  async markAsReadAndArchive(newsletterId: string): Promise<void> {
    try {
      this.log.debug("Updating newsletter status", {
        action: "mark_as_read_and_archive",
        metadata: { newsletterId },
      });
 
      // Update both read and archived status in one call
      await this.deps.updateNewsletter({
        id: newsletterId,
        is_read: true,
        is_archived: true,
      });
 
      this.log.info("Newsletter marked as read and archived", {
        action: "mark_as_read_and_archive",
        metadata: { newsletterId },
      });
    } catch (error) {
      this.log.error(
        "Failed to mark newsletter as read and archive",
        {
          action: "mark_as_read_and_archive",
          metadata: { newsletterId },
        },
        error instanceof Error ? error : new Error(String(error)),
      );
      throw new Error("Failed to update newsletter status");
    }
  }
 
  /**
   * Opens newsletter detail view and updates status
   */
  async openNewsletterDetail(newsletterId: string): Promise<void> {
    try {
      this.log.info("Opening newsletter detail", {
        action: "open_newsletter_detail",
        metadata: { newsletterId },
      });
 
      // Update newsletter status
      await this.markAsReadAndArchive(newsletterId);
 
      // Navigate to detail view
      this.log.debug("Navigating to newsletter detail", {
        action: "open_newsletter_detail",
        metadata: { newsletterId, url: `/newsletters/${newsletterId}` },
      });
      this.deps.window.location.href = `/newsletters/${newsletterId}`;
    } catch (error) {
      this.log.error(
        "Failed to open newsletter detail",
        {
          action: "open_newsletter_detail",
          metadata: { newsletterId },
        },
        error instanceof Error ? error : new Error(String(error)),
      );
      // Still navigate even if status update fails
      this.deps.window.location.href = `/newsletters/${newsletterId}`;
    }
  }
 
  /**
   * Saves a search query to recent searches
   */
  saveRecentSearch(query: string): void {
    if (!query.trim()) return;
 
    const recentSearches = this.getRecentSearches();
    const updatedSearches = [
      query.trim(),
      ...recentSearches.filter((search) => search !== query.trim()),
    ].slice(0, SearchService.MAX_RECENT_SEARCHES);
 
    this.setRecentSearches(updatedSearches);
  }
 
  /**
   * Gets recent searches from localStorage
   */
  getRecentSearches(): string[] {
    try {
      const saved = this.deps.window.localStorage.getItem(
        SearchService.RECENT_SEARCHES_KEY,
      );
      return saved ? JSON.parse(saved) : [];
    } catch (error) {
      this.log.error(
        "Failed to parse recent searches",
        {
          action: "get_recent_searches",
          metadata: {},
        },
        error instanceof Error ? error : new Error(String(error)),
      );
      return [];
    }
  }
 
  /**
   * Sets recent searches in localStorage
   */
  private setRecentSearches(searches: string[]): void {
    try {
      this.deps.window.localStorage.setItem(
        SearchService.RECENT_SEARCHES_KEY,
        JSON.stringify(searches),
      );
    } catch (error) {
      this.log.error(
        "Failed to save recent searches",
        {
          action: "set_recent_searches",
          metadata: { searchCount: searches.length },
        },
        error instanceof Error ? error : new Error(String(error)),
      );
    }
  }
 
  /**
   * Removes a specific search from recent searches
   */
  removeRecentSearch(query: string): void {
    const recentSearches = this.getRecentSearches();
    const updatedSearches = recentSearches.filter((search) => search !== query);
    this.setRecentSearches(updatedSearches);
  }
 
  /**
   * Clears all recent searches
   */
  clearRecentSearches(): void {
    try {
      this.deps.window.localStorage.removeItem(
        SearchService.RECENT_SEARCHES_KEY,
      );
    } catch (error) {
      this.log.error(
        "Failed to clear recent searches",
        {
          action: "clear_recent_searches",
          metadata: {},
        },
        error instanceof Error ? error : new Error(String(error)),
      );
    }
  }
 
  /**
   * Creates default search filters
   */
  createDefaultFilters(): SearchFilters {
    return {
      selectedSources: [],
      selectedGroups: [],
      archivedStatus: "active",
      dateFrom: "",
      dateTo: "",
    };
  }
 
  /**
   * Creates initial search state
   */
  createInitialState(): SearchState {
    return {
      results: [],
      loading: false,
      error: null,
      searchPerformed: false,
      totalCount: 0,
      currentPage: 1,
      hasMore: false,
    };
  }
 
  /**
   * Checks if filters are applied (not default)
   */
  hasFiltersApplied(filters: SearchFilters): boolean {
    const defaultFilters = this.createDefaultFilters();
 
    return (
      filters.selectedSources.length > 0 ||
      filters.selectedGroups.length > 0 ||
      filters.archivedStatus !== defaultFilters.archivedStatus ||
      filters.dateFrom !== defaultFilters.dateFrom ||
      filters.dateTo !== defaultFilters.dateTo
    );
  }
 
  /**
   * Resets filters to default values
   */
  resetFilters(): SearchFilters {
    return this.createDefaultFilters();
  }
 
  /**
   * Builds URL search parameters for browser history
   */
  buildUrlParams(query: string, page?: number): URLSearchParams {
    const params = new URLSearchParams();
 
    if (query.trim()) {
      params.set("q", query.trim());
    }
 
    if (page && page > 1) {
      params.set("page", page.toString());
    }
 
    return params;
  }
 
  /**
   * Parses URL search parameters
   */
  parseUrlParams(searchParams: URLSearchParams): {
    query: string;
    page: number;
  } {
    return {
      query: searchParams.get("q") || "",
      page: parseInt(searchParams.get("page") || "1", 10),
    };
  }
 
  /**
   * Updates browser URL with search state
   */
  updateUrl(query: string, page?: number): void {
    const params = this.buildUrlParams(query, page);
    const newUrl = `/search${params.toString() ? `?${params.toString()}` : ""}`;
 
    this.deps.window.history.pushState({ path: newUrl }, "", newUrl);
  }
 
  /**
   * Validates search input
   */
  validateSearchInput(query: string): { isValid: boolean; error?: string } {
    if (!query.trim()) {
      return { isValid: false, error: "Search query cannot be empty" };
    }
 
    if (query.trim().length < 2) {
      return {
        isValid: false,
        error: "Search query must be at least 2 characters long",
      };
    }
 
    if (query.length > 500) {
      return {
        isValid: false,
        error: "Search query is too long (maximum 500 characters)",
      };
    }
 
    return { isValid: true };
  }
 
  /**
   * Formats search error for display
   */
  formatSearchError(error: unknown): string {
    if (error instanceof Error) {
      return error.message;
    }
 
    if (typeof error === "string") {
      return error;
    }
 
    return "An unexpected error occurred while searching";
  }
 
  /**
   * Checks if search results are empty
   */
  hasResults(state: SearchState): boolean {
    return state.results.length > 0;
  }
 
  /**
   * Checks if search is in progress
   */
  isSearching(state: SearchState): boolean {
    return state.loading;
  }
 
  /**
   * Checks if search has been performed
   */
  hasSearched(state: SearchState): boolean {
    return state.searchPerformed;
  }
 
  /**
   * Gets search statistics for display
   */
  getSearchStats(state: SearchState): {
    totalResults: number;
    currentPage: number;
    totalPages: number;
    hasMore: boolean;
  } {
    return {
      totalResults: state.totalCount,
      currentPage: state.currentPage,
      totalPages: Math.ceil(state.totalCount / 20), // Default page size
      hasMore: state.hasMore,
    };
  }
}
 
// Factory function to create SearchService instance
export const createSearchService = (
  deps: SearchServiceDependencies,
): SearchService => {
  return new SearchService(deps);
};
 
// Export singleton instance - created lazily
let searchServiceInstance: SearchService | null = null;
export const searchService = (): SearchService => {
  if (!searchServiceInstance) {
    const deps: SearchServiceDependencies = {
      getAllNewsletterSources: apiGetAllNewsletterSources,
      updateNewsletter: apiUpdateNewsletter,
      newsletterService: optimizedNewsletterService,
      newsletterGroupService: newsletterGroupService,
      logger: appLogger,
      window: window,
      buildSearchParams: utilBuildSearchParams,
      validateSearchFilters: utilValidateSearchFilters,
    };
    searchServiceInstance = new SearchService(deps);
  }
  return searchServiceInstance;
};
 
export { SearchService };
export default searchService;