All files / src/queues/jobs updateLeftoverBudgetLimit.ts

4.54% Statements 3/66
0% Branches 0/16
0% Functions 0/9
5% Lines 3/60

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                                  1x                                                                                                   1x   1x                                                                                                                        
import {
  AccountsService,
  BudgetLimitArray,
  BudgetLimitStore,
  BudgetRead,
  BudgetsService,
  InsightGroupEntry,
  InsightService,
} from "@billos/firefly-iii-sdk"
import pino from "pino"
 
import { client } from "../../client"
import { env } from "../../config"
import { getDateNow } from "../../utils/date"
import { addJobToQueue } from "../utils"
import { SimpleJob } from "./BaseJob"
 
const logger = pino()
 
async function getSumWithoutLeftovers(
  allBudgets: BudgetRead[],
  leftoversBudget: BudgetRead,
  allLimits: BudgetLimitArray,
  start: string,
  end: string,
): Promise<number> {
  const assetAccount = await AccountsService.getAccount({ client, path: { id: env.assetAccountId } })
  if (!assetAccount) {
    throw new Error("Asset account not found")
  }
  let leftoverAmount = Number.parseFloat(assetAccount.data.data.attributes.current_balance)
  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 { data: insightsRaw } = await InsightService.insightExpenseBudget({ client, query: { start, end, "budgets[]": budgetsIds } })
  const insights: Record<string, InsightGroupEntry> = {}
  for (const insight of insightsRaw) {
    insights[insight.id] = insight
  }
  for (const limit of limitsWithoutLeftovers) {
    const {
      // attributes: { spent, budget_id, amount },
      attributes: { budget_id, amount },
    } = limit
    const insight = insights[budget_id]
 
    let spentValue = "0"
    const budget = allBudgets.find((b) => b.id === budget_id)!
    const { name } = budget.attributes
    if (insight) {
      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 = getDateNow().startOf("month").toISODate()
    const end = getDateNow().endOf("month").toISODate()
 
    const [allBudgets, allLimits] = await Promise.all([
      BudgetsService.listBudget({ client, query: { page: 1, limit: 50, start, end } }),
      BudgetsService.listBudgetLimit({ client, query: { start, end } }),
    ])
    const leftoversBudget = allBudgets.data.data.find(({ id }) => id === env.leftoversBudgetId)
    const leftOverLimit = allLimits.data.data.find(({ attributes: { budget_id } }) => budget_id === env.leftoversBudgetId)
 
    let leftoverAmount = await getSumWithoutLeftovers(allBudgets.data.data, leftoversBudget, allLimits.data, start, end)
    if (leftoverAmount < 0) {
      logger.info("Leftover amount is negative, setting to 0.1")
      leftoverAmount = 0.1
    }
 
    const currentLeftOverBudget = allBudgets.data.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")
  }
 
  override async init(): Promise<void> {
    logger.info("Initializing UpdateLeftoverBudgetLimit job")
    await addJobToQueue(this)
    logger.info("UpdateLeftoverBudgetLimit job initialized")
  }
}