All files / src/utils notification.ts

0% Statements 0/13
0% Branches 0/6
0% Functions 0/5
0% Lines 0/13

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                                                                                             
import { TransactionSplit, TransactionsService } from "@billos/firefly-iii-sdk"
 
import { client } from "../client"
import { MessageType } from "../modules/notifiers/notifier"
 
async function getTransaction(id: string): Promise<TransactionSplit> {
  const {
    data: {
      data: {
        attributes: {
          transactions: [transaction],
        },
      },
    },
  } = await TransactionsService.getTransaction({ client, path: { id } })
  return transaction
}
 
async function setNotes(transactionId: string, notes: string): Promise<void> {
  await TransactionsService.updateTransaction({
    client,
    path: { id: transactionId },
    body: { apply_rules: false, fire_webhooks: false, transactions: [{ notes }] },
  })
}
 
function escapeRegExp(str: string): string {
  return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
}
 
export async function bindTransactionToNotification(transactionId: string, messageType: MessageType, messageId: string): Promise<void> {
  const transaction = await getTransaction(transactionId)
  let notes = transaction.notes || ""
  if (!notes.includes(messageType)) {
    notes += `\n${messageType}: ${messageId}\n`
  } else {
    notes = notes.replace(new RegExp(`${escapeRegExp(messageType)}: (\\d+)`), `${messageType}: ${messageId}`)
  }
  await setNotes(transactionId, notes)
}
 
export async function unbindTransactionToNotification(transactionId: string, messageType: MessageType, messageId: string): Promise<void> {
  const transaction = await getTransaction(transactionId)
  const notes = (transaction.notes || "").replace(`${messageType}: ${messageId}`, "")
  await setNotes(transactionId, notes)
}