Skip to content

A local-first personal finance app

10.7 KB
Raw Blame
import * as monthUtils from '@actual-app/core/shared/months';
import type { TimeFrame } from '@actual-app/core/types/models';
import type { SyncedPrefs } from '@actual-app/core/types/prefs';

export function validateStart(
  earliest: string,
  latest: string,
  start: string,
  end: string,
  interval?: string,
  firstDayOfWeekIdx?: SyncedPrefs['firstDayOfWeekIdx'],
): [string, string, TimeFrame['mode']] {
  let dateStart: string;
  let fallbackEnd: string;
  switch (interval) {
    case 'Monthly':
      dateStart = start + '-01';
      fallbackEnd = monthUtils.addDays(dateStart, 180);
      break;
    case 'Quarterly':
      dateStart = start + '-01';
      // The chosen quarter and the three after it, ending on a quarter boundary
      fallbackEnd = monthUtils.getMonthEnd(
        monthUtils.getQuarterEnd(monthUtils.addMonths(start, 9)) + '-01',
      );
      break;
    case 'Yearly':
      dateStart = start + '-01-01';
      fallbackEnd = monthUtils.addDays(dateStart, 1095);
      break;
    case 'Daily':
      dateStart = start;
      fallbackEnd = monthUtils.addDays(dateStart, 6);
      break;
    default:
      dateStart = start;
      fallbackEnd = monthUtils.addDays(dateStart, 180);
      break;
  }

  // Compare full dates: `start` may be a shorter month or year key.
  if (end < dateStart) {
    end = fallbackEnd;
  }
  return boundedRange(
    earliest,
    latest,
    dateStart,
    interval ? end : monthUtils.monthFromDate(end),
    interval,
    firstDayOfWeekIdx,
  );
}

export function validateEnd(
  earliest: string,
  latest: string,
  start: string,
  end: string,
  interval?: string,
  firstDayOfWeekIdx?: SyncedPrefs['firstDayOfWeekIdx'],
): [string, string, TimeFrame['mode']] {
  let dateEnd: string;
  let fallbackStart: string;
  switch (interval) {
    case 'Monthly':
      dateEnd = monthUtils.getMonthEnd(end + '-01');
      fallbackStart = monthUtils.subDays(dateEnd, 180);
      break;
    case 'Quarterly':
      dateEnd = monthUtils.getMonthEnd(monthUtils.getQuarterEnd(end) + '-01');
      // The chosen quarter and the three before it, starting on a quarter boundary
      fallbackStart =
        monthUtils.getQuarterStart(monthUtils.subMonths(end, 9)) + '-01';
      break;
    case 'Yearly':
      dateEnd = end + '-12-31';
      fallbackStart = monthUtils.subDays(dateEnd, 1095);
      break;
    case 'Daily':
      dateEnd = end;
      fallbackStart = monthUtils.subDays(dateEnd, 6);
      break;
    default:
      dateEnd = end;
      fallbackStart = monthUtils.subDays(dateEnd, 180);
      break;
  }

  // Compare full dates: `end` may be a shorter month or year key.
  if (start > dateEnd) {
    start = fallbackStart;
  }
  return boundedRange(
    earliest,
    latest,
    interval ? start : monthUtils.monthFromDate(start),
    dateEnd,
    interval,
    firstDayOfWeekIdx,
  );
}

export function validateRange(
  earliest: string,
  start: string,
  end: string,
): [string, string] {
  if (start < earliest) {
    start = earliest;
  }

  return [start, end];
}

export function boundMonthRange(
  earliestMonth: string,
  latestMonth: string,
  startMonth: string,
  endMonth: string,
): [string, string] {
  let boundedStart = startMonth;
  let boundedEnd = endMonth;

  if (monthUtils.isBefore(boundedStart, earliestMonth)) {
    boundedStart = earliestMonth;
  } else if (monthUtils.isAfter(boundedStart, latestMonth)) {
    boundedStart = latestMonth;
  }

  if (monthUtils.isBefore(boundedEnd, earliestMonth)) {
    boundedEnd = earliestMonth;
  } else if (monthUtils.isAfter(boundedEnd, latestMonth)) {
    boundedEnd = latestMonth;
  }

  if (monthUtils.isBefore(boundedEnd, boundedStart)) {
    boundedEnd = boundedStart;
  }

  return [boundedStart, boundedEnd];
}

export function boundMonthRangeFromDates(
  earliestDate: string,
  latestDate: string,
  start: string,
  end: string,
): [string, string] {
  return boundMonthRange(
    monthUtils.getMonth(earliestDate),
    monthUtils.getMonth(latestDate),
    monthUtils.getMonth(start),
    monthUtils.getMonth(end),
  );
}

function boundedRange(
  earliest: string,
  latest: string,
  start: string,
  end: string,
  interval?: string,
  _firstDayOfWeekIdx?: SyncedPrefs['firstDayOfWeekIdx'],
): [string, string, 'static'] {
  switch (interval) {
    case 'Daily':
      latest = monthUtils.currentDay();
      break;
    case 'Weekly':
      // For weekly views, clamp to today so the current (ongoing) week is included
      // and reflects data up to the current day.
      latest = monthUtils.currentDay();
      break;
    case 'Monthly':
    case 'Quarterly':
      latest = monthUtils.getMonthEnd(monthUtils.currentDay());
      break;
    case 'Yearly':
      latest = monthUtils.currentDay();
      break;
    default:
      break;
  }

  if (end > latest) {
    end = latest;
  }
  if (start < earliest) {
    start = earliest;
  }
  return [start, end, 'static'];
}

export function getSpecificRange(
  offset: number,
  addNumber: number | null,
  type?: string,
  firstDayOfWeekIdx?: SyncedPrefs['firstDayOfWeekIdx'],
) {
  const currentDay = monthUtils.currentDay();
  const currentWeek = monthUtils.currentWeek(firstDayOfWeekIdx);

  let dateStart = monthUtils.subMonths(currentDay, offset) + '-01';
  let dateEnd = monthUtils.getMonthEnd(
    monthUtils.addMonths(dateStart, addNumber === null ? offset : addNumber) +
      '-01',
  );

  if (type === 'Week') {
    dateStart = monthUtils.subWeeks(currentWeek, offset);
    dateEnd = monthUtils.getWeekEnd(
      monthUtils.addWeeks(dateStart, addNumber === null ? offset : addNumber),
      firstDayOfWeekIdx,
    );
  }

  return [dateStart, dateEnd, 'static'];
}

export function getFullRange(start: string, end: string) {
  return [start, end, 'full'] as const;
}

export function getLatestRange(offset: number) {
  const end = monthUtils.currentMonth();
  const start = monthUtils.subMonths(end, offset);

  return [start, end, 'sliding-window'] as const;
}

export function getNextRange(offset: number) {
  const start = monthUtils.currentMonth();
  const end = monthUtils.addMonths(start, offset);

  return [start, end, 'static'] as const;
}

export function getFullFutureRange(latestMonth?: string) {
  const start = monthUtils.currentMonth();
  const defaultEnd = monthUtils.addMonths(start, 24);
  const end =
    latestMonth && monthUtils.isAfter(latestMonth, start)
      ? latestMonth
      : defaultEnd;

  return [start, end, 'static'] as const;
}

// For month-granular consumers (e.g. formula queries): collapse day-shaped
// bounds so a live range keeps sliding by whole months rather than days.
export function asMonthSlidingTimeFrame(
  timeFrame: Partial<TimeFrame>,
): Partial<TimeFrame> {
  const { start, end, mode } = timeFrame;
  if (mode !== 'sliding-window' || !start || !end) {
    return timeFrame;
  }
  return {
    ...timeFrame,
    start: monthUtils.getMonth(start),
    end: monthUtils.getMonth(end),
  };
}

export function calculateTimeRange(
  timeFrame?: Partial<TimeFrame>,
  defaultTimeFrame?: TimeFrame,
  latestTransaction?: string,
) {
  const start =
    timeFrame?.start ??
    defaultTimeFrame?.start ??
    monthUtils.subMonths(monthUtils.currentMonth(), 5);
  const end =
    timeFrame?.end ?? defaultTimeFrame?.end ?? monthUtils.currentMonth();
  const mode = timeFrame?.mode ?? defaultTimeFrame?.mode ?? 'sliding-window';

  if (mode === 'full') {
    const latestTransactionMonth = latestTransaction
      ? monthUtils.monthFromDate(latestTransaction)
      : null;
    const currentMonth = monthUtils.currentMonth();
    const fullEnd =
      latestTransactionMonth &&
      monthUtils.isAfter(latestTransactionMonth, currentMonth)
        ? latestTransactionMonth
        : currentMonth;
    return getFullRange(start, fullEnd);
  }
  if (mode === 'sliding-window') {
    // Day-shaped ranges slide by days: same width, ending today.
    if (
      monthUtils.isValidYearMonthDay(start) &&
      monthUtils.isValidYearMonthDay(end)
    ) {
      const dayOffset = monthUtils.differenceInCalendarDays(end, start);
      const today = monthUtils.currentDay();
      return [
        monthUtils.subDays(today, Math.max(dayOffset, 0)),
        today,
        'sliding-window',
      ] as const;
    }

    const offset = monthUtils.differenceInCalendarMonths(end, start);

    if (start > end) {
      return [
        monthUtils.currentMonth(),
        monthUtils.subMonths(monthUtils.currentMonth(), -offset),
        'sliding-window',
      ] as const;
    }

    return getLatestRange(offset);
  }
  if (mode === 'lastMonth') {
    const lastMonth = monthUtils.subMonths(monthUtils.currentMonth(), 1);
    return [lastMonth, lastMonth, 'lastMonth'] as const;
  }
  if (mode === 'lastYear') {
    return [
      monthUtils.getYearStart(monthUtils.prevYear(monthUtils.currentMonth())),
      monthUtils.getYearEnd(monthUtils.prevYear(monthUtils.currentDate())),
      'lastYear',
    ] as const;
  }
  if (mode === 'yearToDate') {
    return [
      monthUtils.currentYear() + '-01',
      monthUtils.currentMonth(),
      'yearToDate',
    ] as const;
  }
  if (mode === 'priorYearToDate') {
    return [
      monthUtils.getYearStart(monthUtils.prevYear(monthUtils.currentMonth())),
      monthUtils.prevYear(monthUtils.currentDate(), 'yyyy-MM-dd'),
      'priorYearToDate',
    ] as const;
  }
  if (mode === 'currentQuarter') {
    const currentMonth = monthUtils.currentMonth();
    return [
      monthUtils.getQuarterStart(currentMonth),
      monthUtils.getQuarterEnd(currentMonth),
      'currentQuarter',
    ] as const;
  }
  if (mode === 'previousQuarter') {
    const prevQuarterMonth = monthUtils.prevQuarter(monthUtils.currentMonth());
    return [
      monthUtils.getQuarterStart(prevQuarterMonth),
      monthUtils.getQuarterEnd(prevQuarterMonth),
      'previousQuarter',
    ] as const;
  }

  return [start, end, 'static'] as const;
}

export function calculateSpendingReportTimeRange({
  compare,
  compareTo,
  isLive = true,
  mode = 'single-month',
}: {
  compare?: string;
  compareTo?: string;
  isLive?: boolean;
  mode?: 'budget' | 'average' | 'single-month';
}): [string, string] {
  // Budget and average chart a single month, so a live report is always the
  // current month.
  if (['budget', 'average'].includes(mode) && isLive) {
    const month = monthUtils.currentMonth();
    return [month, month];
  }

  // Default a missing end to the month before `compare`; the shared default is
  // the month before now, which would widen the comparison.
  const [start, end] = calculateTimeRange(
    {
      start: compare,
      end:
        compareTo ?? (compare ? monthUtils.subMonths(compare, 1) : undefined),
      mode: (isLive ?? true) ? 'sliding-window' : 'static',
    },
    {
      start: monthUtils.currentMonth(),
      end: monthUtils.subMonths(monthUtils.currentMonth(), 1),
      mode: 'sliding-window',
    },
  );
  return [start, end];
}