diff --git a/lib/services/entity-sync.ts b/lib/services/entity-sync.ts index 1103cb6..bb57f3b 100644 --- a/lib/services/entity-sync.ts +++ b/lib/services/entity-sync.ts @@ -10,18 +10,19 @@ import { EntityType } from '../types/sync'; import { mapAutotaskToDatabase, mapAutotaskBatch } from '../utils/entity-mapper'; import { bulkUpsertRecords, getLastSyncTime, softDeleteMissingRecords } from '../utils/db-helpers'; import { syncProgressTracker } from './sync-progress-tracker'; -import { - getAutotaskEntityName, +import { + getAutotaskEntityName, buildIncrementalFilter, buildActiveFilter, buildDateRangeFilter, + buildCompaniesFilter, buildContractsFilter, buildContractServicesFilter, buildProjectsFilter, buildProjectPhasesFilter, buildTimeEntriesFilter, buildBillingItemsFilter, - getTableName + getTableName } from '../utils/sync-helpers'; import { createSyncLogger, SyncPhase, categorizeError } from '../utils/sync-logger'; @@ -128,9 +129,12 @@ export class EntitySyncService { } const filters: Array<{ field: string; op: string; value: any }> = []; - + // Special handling for entities that require filters - if (entity === EntityType.CONTRACTS) { + if (entity === EntityType.COMPANIES) { + filters.push(...buildCompaniesFilter()); + entityLogger.info('Full sync of all companies (active + inactive)'); + } else if (entity === EntityType.CONTRACTS) { filters.push(...buildContractsFilter()); entityLogger.info('Full sync with status filter for active contracts'); } else if (entity === EntityType.CONTRACT_SERVICES) { diff --git a/lib/utils/sync-helpers.ts b/lib/utils/sync-helpers.ts index 25274d9..0d0b836 100644 --- a/lib/utils/sync-helpers.ts +++ b/lib/utils/sync-helpers.ts @@ -91,6 +91,22 @@ export function buildContractServicesFilter(): Array<{ field: string; op: string ]; } +/** + * Build filter for companies (Companies endpoint requires a filter — use id > 0 to fetch all + * companies regardless of isActive. Active-only filtering misses inactive companies that + * have tickets, causing tickets_company_id_fkey violations on full sync.) + * @returns Query filter array for all companies + */ +export function buildCompaniesFilter(): Array<{ field: string; op: string; value: any }> { + return [ + { + field: 'id', + op: 'gt', + value: 0, + }, + ]; +} + /** * Get table name for entity type * @param entity Entity type