<commit_before>import { Feature } from 'toolkit/extension/features/feature';
import {
  isCurrentRouteBudgetPage,
  getEntityManager,
  getSelectedMonth,
  isCurrentMonthSelected,
} from 'toolkit/extension/utils/ynab';
import { pacingForCategory } from 'toolkit/extension/utils/pacing';
import { getEmberView } from 'toolkit/extension/utils/ember';

const progressIndicatorWidth = 0.005; // Current month progress indicator width

export class BudgetProgressBars extends Feature {
  // Supporting functions, or variables, etc
  loadCategories = true;

  selMonth;

  subCats = [];

  internalIdBase;

  monthProgress;

  injectCSS() {
    return require('./index.css');
  }

  shouldInvoke() {
    return isCurrentRouteBudgetPage();
  }

  // Takes N colors and N-1 sorted points from (0, 1) to make color1|color2|color3 bg style.
  generateProgressBarStyle(colors, points) {
    const pointsPercent = [0, ...points, 1].map(p => p * 100);
    return colors.reduce(
      (reduced, color, index) =>
        reduced +
        `${color} ${pointsPercent[index]}%, ${color} ${pointsPercent[index + 1]}%${
          index + 1 === colors.length ? ')' : ', '
        }`,
      'linear-gradient(to right, '
    );
  }

  getCalculation(subCategoryName) {
    const subCategory = this.subCats.find(ele => ele.toolkitName === subCategoryName);

    if (subCategory) {
      const crazyInternalId = this.internalIdBase + subCategory.entityId;
      const calculation = getEntityManager().getMonthlySubCategoryBudgetCalculationById(
        crazyInternalId
      );
      if (!calculation) {
        return;
      }
      /**
       * Add a few values from the subCategory object to the calculation object.
       */
      calculation.targetBalance = subCategory.getGoalTargetAmount();
      calculation.goalType = subCategory.getGoalType();
      calculation.goalCreationMonth = subCategory.goalCreationMonth
        ? subCategory.goalCreationMonth.toString().substr(0, 7)
        : '';
      /**
       * If the month the goal was created in is greater than the selected month, null the goal type to prevent further
       * processing.
       */
      if (calculation.goalCreationMonth && calculation.goalCreationMonth > this.selMonth) {
        calculation.goalType = null;
      }

      return calculation;
    }
  }

  addGoalProgress(subCategoryName, target) {
    const calculation = this.getCalculation(subCategoryName);
    if (!calculation) {
      return;
    }

    if (['TB', 'TBD', 'MF'].includes(calculation && calculation.goalType)) {
      const percent = Math.round(parseFloat(calculation.get('goalPercentageComplete')));
      $(target).css(
        'background',
        `linear-gradient(
          to right,
          var(--tk-color-goal-fill) ${percent}%,
          var(--table_row_background_default) ${percent}%
        )`
      );
    } else {
      $(target).css('background', '');
    }
  }

  addMasterPacingProgress(target) {
    if (!isCurrentMonthSelected()) {
      $(target).css('background', '');
      return;
    }

    $(target).css(
      'background',
      this.generateProgressBarStyle(
        [
          'var(--table_header_background_default)',
          'var(--tk-color-progress-bar-month-indicator)',
          'var(--table_header_background_default)',
        ],
        [this.monthProgress - progressIndicatorWidth, this.monthProgress]
      )
    );
  }

  addPacingProgress(subCategory, target) {
    if (!isCurrentMonthSelected()) {
      $(target).css('background', '');
      return;
    }

    const pacingCalculation = pacingForCategory(subCategory);
    const balancePriorToSpending = subCategory.get('balancePriorToSpending');
    const { budgetedPace, monthPace } = pacingCalculation;

    // For pacing progress bars we can't use budgeted pace higher than 100%, otherwise the bars get screwed. So we cap it at 100% width
    const cappedBudgetedPace = Math.min(budgetedPace, 1);

    if (!pacingCalculation.isDeemphasized) {
      if (balancePriorToSpending > 0) {
        if (monthPace > budgetedPace) {
          $(target).css(
            'background',
            this.generateProgressBarStyle(
              [
                'var(--tk-color-pacing-fill)',
                'var(--table_row_background_default)',
                'var(--tk-color-progress-bar-month-indicator)',
                'var(--table_row_background_default)',
              ],
              [cappedBudgetedPace, this.monthProgress - progressIndicatorWidth, this.monthProgress]
            )
          );
        } else {
          $(target).css(
            'background',
            this.generateProgressBarStyle(
              [
                'var(--tk-color-pacing-fill)',
                'var(--tk-color-progress-bar-month-indicator)',
                'var(--tk-color-pacing-fill)',
                'var(--table_row_background_default)',
              ],
              [this.monthProgress - progressIndicatorWidth, this.monthProgress, cappedBudgetedPace]
            )
          );
        }
      } else {
        $(target).css(
          'background',
          this.generateProgressBarStyle(
            [
              'var(--table_row_background_default)',
              'var(--tk-color-progress-bar-month-indicator)',
              'var(--table_row_background_default)',
            ],
            [this.monthProgress - progressIndicatorWidth, this.monthProgress]
          )
        );
      }
    } else {
      $(target).css('background', '');
    }
  }

  invoke() {<commit_msg>issue-2144: fix budget progress bar variables due to upstream change (#2145)<commit_after>import { Feature } from 'toolkit/extension/features/feature';
import {
  isCurrentRouteBudgetPage,
  getEntityManager,
  getSelectedMonth,
  isCurrentMonthSelected,
} from 'toolkit/extension/utils/ynab';
import { pacingForCategory } from 'toolkit/extension/utils/pacing';
import { getEmberView } from 'toolkit/extension/utils/ember';

const progressIndicatorWidth = 0.005; // Current month progress indicator width

export class BudgetProgressBars extends Feature {
  // Supporting functions, or variables, etc
  loadCategories = true;

  selMonth;

  subCats = [];

  internalIdBase;

  monthProgress;

  injectCSS() {
    return require('./index.css');
  }

  shouldInvoke() {
    return isCurrentRouteBudgetPage();
  }

  // Takes N colors and N-1 sorted points from (0, 1) to make color1|color2|color3 bg style.
  generateProgressBarStyle(colors, points) {
    const pointsPercent = [0, ...points, 1].map(p => p * 100);
    return colors.reduce(
      (reduced, color, index) =>
        reduced +
        `${color} ${pointsPercent[index]}%, ${color} ${pointsPercent[index + 1]}%${
          index + 1 === colors.length ? ')' : ', '
        }`,
      'linear-gradient(to right, '
    );
  }

  getCalculation(subCategoryName) {
    const subCategory = this.subCats.find(ele => ele.toolkitName === subCategoryName);

    if (subCategory) {
      const crazyInternalId = this.internalIdBase + subCategory.entityId;
      const calculation = getEntityManager().getMonthlySubCategoryBudgetCalculationById(
        crazyInternalId
      );
      if (!calculation) {
        return;
      }
      /**
       * Add a few values from the subCategory object to the calculation object.
       */
      calculation.targetBalance = subCategory.getGoalTargetAmount();
      calculation.goalType = subCategory.getGoalType();
      calculation.goalCreationMonth = subCategory.goalCreationMonth
        ? subCategory.goalCreationMonth.toString().substr(0, 7)
        : '';
      /**
       * If the month the goal was created in is greater than the selected month, null the goal type to prevent further
       * processing.
       */
      if (calculation.goalCreationMonth && calculation.goalCreationMonth > this.selMonth) {
        calculation.goalType = null;
      }

      return calculation;
    }
  }

  addGoalProgress(subCategoryName, target) {
    const calculation = this.getCalculation(subCategoryName);
    if (!calculation) {
      return;
    }

    if (['TB', 'TBD', 'MF'].includes(calculation && calculation.goalType)) {
      const percent = Math.round(parseFloat(calculation.get('goalPercentageComplete')));
      $(target).css(
        'background',
        `linear-gradient(
          to right,
          var(--tk-color-goal-fill) ${percent}%,
          var(--table_row_background) ${percent}%
        )`
      );
    } else {
      $(target).css('background', '');
    }
  }

  addMasterPacingProgress(target) {
    if (!isCurrentMonthSelected()) {
      $(target).css('background', '');
      return;
    }

    $(target).css(
      'background',
      this.generateProgressBarStyle(
        [
          'var(--table_header_background)',
          'var(--tk-color-progress-bar-month-indicator)',
          'var(--table_header_background)',
        ],
        [this.monthProgress - progressIndicatorWidth, this.monthProgress]
      )
    );
  }

  addPacingProgress(subCategory, target) {
    if (!isCurrentMonthSelected()) {
      $(target).css('background', '');
      return;
    }

    const pacingCalculation = pacingForCategory(subCategory);
    const balancePriorToSpending = subCategory.get('balancePriorToSpending');
    const { budgetedPace, monthPace } = pacingCalculation;

    // For pacing progress bars we can't use budgeted pace higher than 100%, otherwise the bars get screwed. So we cap it at 100% width
    const cappedBudgetedPace = Math.min(budgetedPace, 1);

    if (!pacingCalculation.isDeemphasized) {
      if (balancePriorToSpending > 0) {
        if (monthPace > budgetedPace) {
          $(target).css(
            'background',
            this.generateProgressBarStyle(
              [
                'var(--tk-color-pacing-fill)',
                'var(--table_row_background)',
                'var(--tk-color-progress-bar-month-indicator)',
                'var(--table_row_background)',
              ],
              [cappedBudgetedPace, this.monthProgress - progressIndicatorWidth, this.monthProgress]
            )
          );
        } else {
          $(target).css(
            'background',
            this.generateProgressBarStyle(
              [
                'var(--tk-color-pacing-fill)',
                'var(--tk-color-progress-bar-month-indicator)',
                'var(--tk-color-pacing-fill)',
                'var(--table_row_background)',
              ],
              [this.monthProgress - progressIndicatorWidth, this.monthProgress, cappedBudgetedPace]
            )
          );
        }
      } else {
        $(target).css(
          'background',
          this.generateProgressBarStyle(
            [
              'var(--table_row_background)',
              'var(--tk-color-progress-bar-month-indicator)',
              'var(--table_row_background)',
            ],
            [this.monthProgress - progressIndicatorWidth, this.monthProgress]
          )
        );
      }
    } else {
      $(target).css('background', '');
    }
  }

  invoke() {
{'fraction_non_alphanumeric': 0.12494337229319562, 'fraction_numerical': 0.005617468514995017, 'mean_word_length': 2.355015197568389, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3433675', 'n_tokens_mistral': 3244, 'n_tokens_neox': 3074, 'n_words': 584}