pick-active-deal.test.ts1.8 KBView on GitHub
/**
 * Frontend `pickActiveDeal` — parity with the server's `pickActiveExternalCrmDeal`.
 * The two must agree so the badge/stage a user sees matches what the backend routed.
 */

import { pickActiveDeal, type ExternalCrmIntegrationMetadata } from '@/modules/crm/types';

function deal(
  overrides: Partial<ExternalCrmIntegrationMetadata> & { dealId: string },
): ExternalCrmIntegrationMetadata {
  return { type: 'external_crm', provider: 'hubspot', ...overrides } as ExternalCrmIntegrationMetadata;
}

describe('pickActiveDeal (frontend mirror)', () => {
  it('returns null when there is no linked deal', () => {
    expect(pickActiveDeal(null)).toBeNull();
    expect(pickActiveDeal([])).toBeNull();
  });

  it('the active-flag entry wins', () => {
    const md = [
      deal({ dealId: 'A', active: true, isClosed: false, updatedAt: '2026-01-01T00:00:00Z' }),
      deal({ dealId: 'B', isClosed: false, updatedAt: '2026-08-01T00:00:00Z' }),
    ];
    expect(pickActiveDeal(md)?.dealId).toBe('A');
  });

  it('falls back to the most-recent open deal', () => {
    const md = [
      deal({ dealId: 'OLD', isClosed: false, updatedAt: '2026-01-01T00:00:00Z' }),
      deal({ dealId: 'NEW', isClosed: false, updatedAt: '2026-08-01T00:00:00Z' }),
      deal({ dealId: 'CLOSED', isClosed: true, updatedAt: '2026-09-01T00:00:00Z' }),
    ];
    expect(pickActiveDeal(md)?.dealId).toBe('NEW');
  });

  it('falls back to the most-recent deal when all are closed', () => {
    const md = [
      deal({ dealId: 'C1', isClosed: true, updatedAt: '2026-01-01T00:00:00Z' }),
      deal({ dealId: 'C2', isClosed: true, updatedAt: '2026-06-01T00:00:00Z' }),
    ];
    expect(pickActiveDeal(md)?.dealId).toBe('C2');
  });

  it('single legacy deal is returned', () => {
    expect(pickActiveDeal([deal({ dealId: 'LEGACY' })])?.dealId).toBe('LEGACY');
  });
});