All files / src/queues/jobs updateLeftoverBudgetLimit.ts

3.33% Statements 3/90
0% Branches 0/37
0% Functions 0/9
3.57% Lines 3/84

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                                      3x                                                                                                                                   1x   1x                                                                                                                                                            
import {
  AccountsService,
  BudgetLimitArray,
  BudgetLimitStore,
  BudgetRead,
  BudgetsService,
  InsightGroupEntry,
  InsightService,
} from "@billos/firefly-iii-sdk"
import pino from "pino"
 
import { client } from "../../client"
import DynamicConfig, { VConfig } from "../../modules/config/dynamic"
import { getEndOfCurrentMonth, getStartOfCurrentMonth } from "../../utils/date"
import { getQueue } from "../queue"
import { addJobToQueue } from "../utils"
import { SimpleJob } from "./BaseJob"
import { BudgetSumUpJob } from "./budgetSumUp"
 
const logger = pino()
 
async function getSumWithoutLeftovers(
  allBudgets: BudgetRead[],
  leftoversBudget: BudgetRead,
  allLimits: BudgetLimitArray,
  start: string,
  end: string,
): Promise<number> {
  const currentAccountId = await DynamicConfig.get(VConfig.CurrentAccountId)
  if (!currentAccountId) {
    throw new Error("Current account ID is not set in the configuration")
  }
  const assetAccount = await AccountsService.getAccount({ client, path: { id: currentAccountId } })
  if (!assetAccount || !assetAccount.data || !assetAccount.data) {
    throw new Error("Asset account not found")
  }
  let leftoverAmount = Number.parseFloat(assetAccount.data.attributes.current_balance || "0")
  logger.info("Current balance %d", leftoverAmount)
 
  const limitsWithoutLeftovers = allLimits.data.filter(({ attributes: { budget_id } }) => budget_id !== leftoversBudget.id)
  const budgetsIds = allLimits.data.map(({ attributes: { budget_id } }) => Number(budget_id))
 
  const insightsRaw = await InsightService.insightExpenseBudget({ client, query: { start, end, "budgets[]": budgetsIds } })
  if (!insightsRaw) {
    logger.info("No insights found, returning current balance as leftover amount")
    return leftoverAmount
  }
  const insights: Record<string, InsightGroupEntry | undefined> = {}
  for (const insight of insightsRaw) {
    if (!insight.id) {
      logger.warn("Insight with no id found, skipping")
      continue
    }
    insights[insight.id] = insight
  }
  for (const limit of limitsWithoutLeftovers) {
    const {
      // attributes: { spent, budget_id, amount },
      attributes: { budget_id, amount },
    } = limit
    if (!budget_id || !amount) {
      logger.warn("Budget limit with id %s has no budget_id or amount, skipping", limit.id)
      continue
    }
    const insight = insights[budget_id]
 
    let spentValue = "0"
    const budget = allBudgets.find((b) => b.id === budget_id)!
    const { name } = budget.attributes
    if (insight?.difference) {
      spentValue = insight.difference
    }
 
    // const { data: budget } = await BudgetsService.getBudget(budget_id)
    // const spentValue = spent[0].sum || "0"
    // const name = budget.attributes.name
    const budgetLeftover = parseFloat(amount) + parseFloat(spentValue)
    logger.info("Subtracting %s - limit of %s - spent %s - Budget leftover %d", name, amount, spentValue, budgetLeftover)
    // A budget leftover might be negative, if the budget is overspent, this means it will be added to the leftover amount
    leftoverAmount -= Math.abs(budgetLeftover)
  }
  return leftoverAmount
}
 
export class UpdateLeftoverBudgetLimitJob extends SimpleJob {
  readonly id = "update-leftovers-budget-limit"
 
  override readonly startDelay = 25
 
  async run(): Promise<void> {
    const start = getStartOfCurrentMonth()
    const end = getEndOfCurrentMonth()
 
    const [allBudgets, allLimits] = await Promise.all([
      BudgetsService.listBudget({ client, query: { page: 1, limit: 50, start, end } }),
      BudgetsService.listBudgetLimit({ client, query: { start, end } }),
    ])
    const leftoversBudgetId = await DynamicConfig.get(VConfig.RoleBudgetLeftoversId)
    const leftoversBudget = allBudgets.data.find(({ id }) => id === leftoversBudgetId)
    const leftOverLimit = allLimits.data.find(({ attributes: { budget_id } }) => budget_id === leftoversBudgetId)
 
    if (!leftoversBudget) {
      logger.warn("Leftovers budget not found, skipping updateLeftoverBudgetLimit job")
      throw new Error("Leftovers budget not found")
    }
 
    let leftoverAmount = await getSumWithoutLeftovers(allBudgets.data, leftoversBudget, allLimits, start, end)
    if (leftoverAmount < 0) {
      logger.info("Leftover amount is negative, setting to 0.1")
      leftoverAmount = 0.1
    }
 
    const currentLeftOverBudget = allBudgets.data.find(({ id }) => id === leftoversBudget.id)!
    const [spent] = currentLeftOverBudget.attributes.spent || []
    if (!spent) {
      logger.info("No spent amount found, setting it to 0")
    }
    const sum = spent?.sum || "0"
 
    const amount = String(-parseFloat(sum) + leftoverAmount)
 
    logger.info("Leftover amount %d", leftoverAmount)
    logger.info("Leftover spent %s", sum)
    logger.info("Budget limit should be %s", amount)
 
    if (parseFloat(amount) < 0) {
      logger.info("Amount is negative, stopping")
      return
    }
 
    if (amount === leftOverLimit?.attributes.amount) {
      logger.info("Amount is the same as the current limit, stopping")
      return
    }
 
    const body: BudgetLimitStore = { amount, budget_id: leftoversBudget.id, start, end, fire_webhooks: false }
 
    if (!leftOverLimit) {
      logger.info("No leftovers budget limit found, creating budget limit")
      await BudgetsService.storeBudgetLimit({ client, path: { id: leftoversBudget.id }, body })
      return
    }
 
    await BudgetsService.updateBudgetLimit({ client, path: { id: leftoversBudget.id, limitId: leftOverLimit.id }, body })
    logger.info("Leftovers budget limit updated")
 
    const budgetSumUpJob = new BudgetSumUpJob()
    const queue = await getQueue()
    const existingJobs = await queue.getJobs(["waiting", "delayed"])
    for (const existingJob of existingJobs) {
      if (existingJob.name === budgetSumUpJob.id) {
        logger.info("Cancelling existing BudgetSumUpJob %s before adding new one", existingJob.id)
        await existingJob.remove()
      }
    }
 
    await addJobToQueue(budgetSumUpJob)
  }
 
  override async init(): Promise<void> {
    logger.info("Initializing UpdateLeftoverBudgetLimit job")
    await addJobToQueue(this)
    logger.info("UpdateLeftoverBudgetLimit job initialized")
  }
}