All files / src/services/api companyApi.ts

91.25% Statements 73/80
90.9% Branches 40/44
90% Functions 9/10
91.25% Lines 73/80

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                                              30x                                           6x 6x 6x 6x     6x   1x       5x 5x 1x   5x 1x       5x 1x         5x 1x     5x       4x   1x                 127x 127x 127x 124x     127x       127x 2x   26x                       3x 3x 3x 3x     3x 1x     3x       3x                             3x 3x 3x 3x     3x       3x         3x 3x                                       11x   11x 6x     5x 5x   6x                                                       3x   3x 1x     2x 2x   1x                 2x 2x   1x                                             12x 12x                 35x   24x       24x 24x   24x           24x 24x 24x   24x     11x         30x                   30x       30x  
/**
 * Company API Client
 *
 * HTTP client for Company Management Service APIs
 * Based on Story 1.14 backend API contracts
 * Integrates with Story 1.11 security and Story 1.9 error handling
 */
 
import apiClient from '@/services/api/apiClient';
import { AxiosError } from 'axios';
import type { components } from '@/types/generated/company-api.types';
import type { CompanyFilters, PaginationParams } from '@/types/company.types';
 
// Type aliases for cleaner code
type Company = components['schemas']['CompanyResponse'];
type CompanyListResponse = components['schemas']['PaginatedCompanyResponse'];
type CreateCompanyRequest = components['schemas']['CreateCompanyRequest'];
type UpdateCompanyRequest = components['schemas']['UpdateCompanyRequest'];
// Note: Logo upload types removed in Story 1.16.3 - use generic file upload API instead
 
// API base path for company endpoints
// Note: apiClient baseURL is set from runtime config to 'http://localhost:8080/api/v1'
// so we only need '/companies' (the /v1 prefix is already in the baseURL)
const COMPANY_API_PATH = '/companies';
 
/**
 * Company API Client Class
 *
 * Handles all HTTP requests to the Company Management Service
 * Features:
 * - JWT authentication via interceptors (Story 1.17)
 * - Error handling with correlation IDs (Story 1.9)
 * - Security headers (Story 1.11)
 * - Request/response transformation
 */
class CompanyApiClient {
  /**
   * Get paginated list of companies with optional filters
   * Uses MongoDB-style JSON filter syntax as per backend API
   */
  async getCompanies(
    pagination: PaginationParams = { page: 1, limit: 20 },
    filters?: CompanyFilters,
    options?: { expand?: string[] }
  ): Promise<CompanyListResponse> {
    try {
      const params = new URLSearchParams();
      params.append('page', pagination.page.toString());
      params.append('limit', pagination.limit.toString());
 
      // If there's a search query, use the search endpoint instead
      if (filters?.searchQuery) {
        // Use the dedicated search endpoint which is optimized for text search
        return this.searchCompaniesWithPagination(filters.searchQuery, pagination, options);
      }
 
      // Build MongoDB-style JSON filter object for non-search filters
      const filterObj: Record<string, boolean | string> = {};
      if (filters?.isVerified !== undefined) {
        filterObj.isVerified = filters.isVerified;
      }
      if (filters?.industry) {
        filterObj.industry = filters.industry;
      }
 
      // Only add filter parameter if we have filters
      if (Object.keys(filterObj).length > 0) {
        params.append('filter', JSON.stringify(filterObj));
      }
 
      // Add include parameter for resource expansion (e.g., ?include=logo,statistics)
      // Backend uses 'include' not 'expand' for resource expansion
      if (options?.expand && options.expand.length > 0) {
        params.append('include', options.expand.join(','));
      }
 
      const response = await apiClient.get<CompanyListResponse>(
        `${COMPANY_API_PATH}?${params.toString()}`
      );
 
      return response.data;
    } catch (error) {
      throw this.transformError(error);
    }
  }
 
  /**
   * Get single company by name with optional resource expansion
   * Story 1.16.2: Uses company name as identifier instead of UUID
   */
  async getCompany(name: string, options?: { expand?: string[] }): Promise<Company> {
    try {
      const params = new URLSearchParams();
      if (options?.expand && options.expand.length > 0) {
        params.append('expand', options.expand.join(','));
      }
 
      const url = params.toString()
        ? `${COMPANY_API_PATH}/${name}?${params.toString()}`
        : `${COMPANY_API_PATH}/${name}`;
 
      const response = await apiClient.get<Company>(url);
      return response.data;
    } catch (error) {
      throw this.transformError(error);
    }
  }
 
  /**
   * Search companies by query string (returns simple array, not paginated)
   */
  async searchCompanies(
    query: string,
    limit: number = 20,
    options?: { expand?: string[] }
  ): Promise<Company[]> {
    try {
      const params = new URLSearchParams();
      params.append('query', query);
      params.append('limit', limit.toString());
 
      // Add include parameter for resource expansion (e.g., ?include=logo)
      if (options?.expand && options.expand.length > 0) {
        params.append('include', options.expand.join(','));
      }
 
      const response = await apiClient.get<Company[]>(
        `${COMPANY_API_PATH}/search?${params.toString()}`
      );
 
      return response.data;
    } catch (error) {
      throw this.transformError(error);
    }
  }
 
  /**
   * Search companies with pagination wrapper
   * Wraps the search endpoint results in paginated format for consistency
   */
  async searchCompaniesWithPagination(
    query: string,
    pagination: PaginationParams = { page: 1, limit: 20 },
    options?: { expand?: string[] }
  ): Promise<CompanyListResponse> {
    try {
      const params = new URLSearchParams();
      params.append('query', query);
      params.append('limit', pagination.limit.toString());
 
      // Add include parameter for resource expansion (e.g., ?include=logo)
      Iif (options?.expand && options.expand.length > 0) {
        params.append('include', options.expand.join(','));
      }
 
      const response = await apiClient.get<Company[]>(
        `${COMPANY_API_PATH}/search?${params.toString()}`
      );
 
      // Wrap in paginated response format
      const data = response.data;
      return {
        data,
        pagination: {
          page: pagination.page,
          limit: pagination.limit,
          totalItems: data.length,
          totalPages: 1,
          hasNext: false,
          hasPrev: false,
        },
      };
    } catch (error) {
      throw this.transformError(error);
    }
  }
 
  /**
   * Create a new company
   */
  async createCompany(data: CreateCompanyRequest): Promise<Company> {
    try {
      // Client-side validation for Swiss UID format
      if (data.swissUID && !this.isValidSwissUID(data.swissUID)) {
        throw new Error('Invalid Swiss UID format. Expected format: CHE-XXX.XXX.XXX');
      }
 
      const response = await apiClient.post<Company>(COMPANY_API_PATH, data);
      return response.data;
    } catch (error) {
      throw this.transformError(error);
    }
  }
 
  /**
   * Get an existing company or create one from a display name (idempotent).
   *
   * Materialises a brand-new company picked in the autocomplete and returns its
   * canonical slug (`name`) so callers store a real company reference instead of
   * a free-typed string (ADR-003). Safe to call repeatedly — the backend resolves
   * the slug and returns the existing company if it already exists.
   */
  async getOrCreateCompany(displayName: string): Promise<Company> {
    try {
      const response = await apiClient.post<Company>(`${COMPANY_API_PATH}:get-or-create`, {
        displayName,
      });
      return response.data;
    } catch (error) {
      throw this.transformError(error);
    }
  }
 
  /**
   * Update existing company
   * Story 1.16.2: Uses company name as identifier instead of UUID
   */
  async updateCompany(name: string, data: UpdateCompanyRequest): Promise<Company> {
    try {
      // Client-side validation for Swiss UID format
      if (data.swissUID && !this.isValidSwissUID(data.swissUID)) {
        throw new Error('Invalid Swiss UID format. Expected format: CHE-XXX.XXX.XXX');
      }
 
      const response = await apiClient.patch<Company>(`${COMPANY_API_PATH}/${name}`, data);
      return response.data;
    } catch (error) {
      throw this.transformError(error);
    }
  }
 
  /**
   * Delete company (soft delete)
   * Story 1.16.2: Uses company name as identifier instead of UUID
   */
  async deleteCompany(name: string): Promise<void> {
    try {
      await apiClient.delete(`${COMPANY_API_PATH}/${name}`);
    } catch (error) {
      throw this.transformError(error);
    }
  }
 
  /**
   * DEPRECATED: Logo upload methods removed in Story 1.16.3
   * Use the generic file upload API instead (see file-upload-api.openapi.yml)
   *
   * Migration path:
   * 1. POST /api/v1/logos/presigned-url - Generate upload URL
   * 2. PUT (presigned URL) - Upload file to S3
   * 3. POST /api/v1/logos/{uploadId}/confirm - Confirm upload
   * 4. POST /api/v1/companies (with logoUploadId) - Associate logo with company
   */
 
  // async requestLogoUploadUrl(...) - REMOVED - Use generic file upload API
  // async confirmLogoUpload(...) - REMOVED - Use generic file upload API
 
  /**
   * Validate Swiss UID format
   * @private
   */
  private isValidSwissUID(uid: string): boolean {
    const pattern = /^CHE-\d{3}\.\d{3}\.\d{3}$/;
    return pattern.test(uid.trim());
  }
 
  /**
   * Transform axios errors into standardized error format
   * Includes correlation ID from Story 1.9 error handling
   * @private
   */
  private transformError(error: unknown): Error {
    if (error instanceof AxiosError) {
      const correlationId =
        error.config?.headers?.['X-Correlation-ID'] ||
        error.response?.headers?.['x-correlation-id'] ||
        'unknown';
 
      const status = error.response?.status;
      const message = error.response?.data?.message || error.message;
 
      const enhancedError = new Error(message) as Error & {
        status?: number;
        correlationId: string;
        originalError: unknown;
      };
 
      enhancedError.status = status;
      enhancedError.correlationId = correlationId;
      enhancedError.originalError = error;
 
      return enhancedError;
    }
 
    return error as Error;
  }
}
 
// Export singleton instance
export const companyApiClient = new CompanyApiClient();
 
// Export convenience methods for direct use
export const {
  getCompanies,
  getCompany,
  searchCompanies,
  createCompany,
  updateCompany,
  deleteCompany,
} = companyApiClient;
 
// Bound separately so the profile "create new company" flow keeps `this` when the
// method's catch path calls this.transformError (destructured methods lose binding).
export const getOrCreateCompany = companyApiClient.getOrCreateCompany.bind(companyApiClient);