All files / services collections.service.ts

94.33% Statements 50/53
70% Branches 7/10
100% Functions 11/11
94.23% Lines 49/52

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                                                                                                                                                                                                  13x 64x 57x           13x 85x 83x           13x 87x       85x 85x 4x     81x           13x 3x 2x           13x       5x 4x           13x 3x           13x 20x 18x           13x       4x 3x                                                                                                                     13x 4x   4x           4x 4x 4x               4x 4x 4x 4x 4x 4x 4x 4x 4x             13x       7x         6x           13x                                 13x                 13x                       13x                   13x                                    
/**
 * Collections API service
 * Handles API calls for collection management
 */
 
import { apiClient } from '@/lib/api';
 
export interface FieldDefinition {
  name: string;
  type: string;
  required?: boolean;
  default?: unknown;
  unique?: boolean;
  options?: Record<string, unknown>;
  collection?: string;
  on_delete?: string;
  pii?: boolean;
  mask_type?: string;
  expression?: string;
  return_type?: string;
}
 
export interface Collection {
  id: string;
  name: string;
  table_name: string;
  schema: FieldDefinition[];
  created_at: string;
  updated_at: string;
}
 
export interface CollectionListItem {
  id: string;
  name: string;
  table_name: string;
  fields_count: number;
  records_count: number;
  has_public_access: boolean;
  created_at: string;
}
 
export interface CollectionListResponse {
  items: CollectionListItem[];
  total: number;
  page: number;
  page_size: number;
  total_pages: number;
}
 
export interface CreateCollectionData {
  name: string;
  schema: FieldDefinition[];
}
 
export interface UpdateCollectionData {
  schema: FieldDefinition[];
}
 
export interface CollectionRule {
  id: string;
  collection_id: string;
  list_rule: string | null;
  view_rule: string | null;
  create_rule: string | null;
  update_rule: string | null;
  delete_rule: string | null;
  list_fields: string;
  view_fields: string;
  create_fields: string;
  update_fields: string;
  created_at: string;
  updated_at: string;
}
 
export interface UpdateCollectionRulesData {
  list_rule?: string | null;
  view_rule?: string | null;
  create_rule?: string | null;
  update_rule?: string | null;
  delete_rule?: string | null;
  list_fields?: string;
  view_fields?: string;
  create_fields?: string;
  update_fields?: string;
}
 
export interface GetCollectionsParams {
  page?: number;
  page_size?: number;
  sort_by?: string;
  sort_order?: 'asc' | 'desc';
  search?: string;
}
 
/**
 * Get list of collections with pagination and search
 */
export const getCollections = async (params: GetCollectionsParams = {}): Promise<CollectionListResponse> => {
  const response = await apiClient.get<CollectionListResponse>('/collections', { params });
  return response.data;
};
 
/**
 * Get collection by ID
 */
export const getCollectionById = async (collectionId: string): Promise<Collection> => {
  const response = await apiClient.get<Collection>(`/collections/${collectionId}`);
  return response.data;
};
 
/**
 * Get collection by name
 */
export const getCollectionByName = async (collectionName: string): Promise<Collection> => {
  const response = await apiClient.get<CollectionListResponse>('/collections', {
    params: { search: collectionName }
  });
  // Find exact match from results
  const collection = response.data.items.find((c: CollectionListItem) => c.name === collectionName);
  if (!collection) {
    throw new Error(`Collection '${collectionName}' not found`);
  }
  // Need to fetch full schema using getCollectionById
  return getCollectionById(collection.id);
};
 
/**
 * Create a new collection
 */
export const createCollection = async (data: CreateCollectionData): Promise<Collection> => {
  const response = await apiClient.post<Collection>('/collections', data);
  return response.data;
};
 
/**
 * Update a collection schema
 */
export const updateCollection = async (
  collectionId: string,
  data: UpdateCollectionData
): Promise<Collection> => {
  const response = await apiClient.put<Collection>(`/collections/${collectionId}`, data);
  return response.data;
};
 
/**
 * Delete a collection
 */
export const deleteCollection = async (collectionId: string): Promise<void> => {
  await apiClient.delete(`/collections/${collectionId}`);
};
 
/**
 * Get collection rules by collection name
 */
export const getCollectionRules = async (collectionName: string): Promise<CollectionRule> => {
  const response = await apiClient.get<CollectionRule>(`/collections/${collectionName}/rules`);
  return response.data;
};
 
/**
 * Update collection rules by collection name
 */
export const updateCollectionRules = async (
  collectionName: string,
  data: UpdateCollectionRulesData
): Promise<CollectionRule> => {
  const response = await apiClient.put<CollectionRule>(`/collections/${collectionName}/rules`, data);
  return response.data;
};
 
// ============================================================================
// Collection Export/Import Types and Functions
// ============================================================================
 
export interface CollectionExportRules {
  list_rule: string | null;
  view_rule: string | null;
  create_rule: string | null;
  update_rule: string | null;
  delete_rule: string | null;
  list_fields: string;
  view_fields: string;
  create_fields: string;
  update_fields: string;
}
 
export interface CollectionExportItem {
  name: string;
  schema: FieldDefinition[];
  rules: CollectionExportRules;
}
 
export interface CollectionExportData {
  version: string;
  exported_at: string;
  exported_by: string;
  collections: CollectionExportItem[];
}
 
export type ImportStrategy = 'error' | 'skip' | 'update';
 
export interface CollectionImportRequest {
  data: CollectionExportData;
  strategy: ImportStrategy;
  generate_migrations: boolean;
}
 
export interface CollectionImportItemResult {
  name: string;
  status: 'imported' | 'skipped' | 'updated' | 'error';
  message: string;
}
 
export interface CollectionImportResult {
  success: boolean;
  imported_count: number;
  skipped_count: number;
  updated_count: number;
  failed_count: number;
  collections: CollectionImportItemResult[];
  migrations_created: string[];
}
 
/**
 * Export collections to JSON file (triggers download)
 */
export const exportCollections = async (collectionIds?: string[]): Promise<void> => {
  const params = collectionIds?.length ? { collection_ids: collectionIds.join(',') } : {};
  
  const response = await apiClient.get('/collections/export', {
    params,
    responseType: 'blob',
  });
 
  // Get filename from Content-Disposition header or generate one
  const contentDisposition = response.headers['content-disposition'];
  let filename = `collections_export_${new Date().toISOString().slice(0, 19).replace(/[:-]/g, '')}.json`;
  Iif (contentDisposition) {
    const match = contentDisposition.match(/filename=([^;]+)/);
    if (match) {
      filename = match[1].trim();
    }
  }
 
  // Create blob and download
  const blob = new Blob([response.data], { type: 'application/json' });
  const url = window.URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = filename;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  window.URL.revokeObjectURL(url);
};
 
/**
 * Import collections from export data
 * Migrations are always generated to ensure database tables are created
 */
export const importCollections = async (
  data: CollectionExportData,
  strategy: ImportStrategy = 'error'
): Promise<CollectionImportResult> => {
  const response = await apiClient.post<CollectionImportResult>('/collections/import', {
    data,
    strategy,
    generate_migrations: true,
  });
  return response.data;
};
 
/**
 * Field type options for the schema builder
 */
export const FIELD_TYPES = [
  { value: 'boolean', label: 'Boolean' },
  { value: 'computed', label: 'Computed' },
  { value: 'date', label: 'Date' },
  { value: 'datetime', label: 'DateTime' },
  { value: 'email', label: 'Email' },
  { value: 'file', label: 'File' },
  { value: 'json', label: 'JSON' },
  { value: 'number', label: 'Number' },
  { value: 'reference', label: 'Reference' },
  { value: 'text', label: 'Text' },
  { value: 'url', label: 'URL' },
] as const;
 
/**
 * On delete action options for reference fields
 */
export const ON_DELETE_OPTIONS = [
  { value: 'cascade', label: 'Cascade' },
  { value: 'set_null', label: 'Set Null' },
  { value: 'restrict', label: 'Restrict' },
] as const;
 
/**
 * PII mask type options
 */
export const MASK_TYPE_OPTIONS = [
  { value: 'email', label: 'Email' },
  { value: 'ssn', label: 'SSN' },
  { value: 'phone', label: 'Phone' },
  { value: 'name', label: 'Name' },
  { value: 'full', label: 'Full' },
  { value: 'custom', label: 'Custom' },
] as const;
 
/**
 * Return type options for computed fields
 */
export const RETURN_TYPE_OPTIONS = [
  { value: 'text', label: 'Text' },
  { value: 'number', label: 'Number' },
  { value: 'boolean', label: 'Boolean' },
  { value: 'datetime', label: 'DateTime' },
] as const;
 
/**
 * Import strategy options for the import dialog
 */
export const IMPORT_STRATEGY_OPTIONS = [
  { 
    value: 'error' as ImportStrategy, 
    label: 'Error on Conflict', 
    description: 'Fail if any collection already exists (safest)' 
  },
  { 
    value: 'skip' as ImportStrategy, 
    label: 'Skip Existing', 
    description: 'Skip existing collections, import only new ones' 
  },
  { 
    value: 'update' as ImportStrategy, 
    label: 'Update Existing', 
    description: 'Update existing collections with new schema (add fields only)' 
  },
] as const;