Skip to content

Develop - #15

Merged
Billos merged 11 commits into
mainfrom
develop
Jan 22, 2026
Merged

Develop#15
Billos merged 11 commits into
mainfrom
develop

Conversation

@Billos

@Billos Billos commented Jan 22, 2026

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • Refactor

    • Restructured queue/worker system with centralized job enqueueing and simpler scheduling
    • Reduced several job delays for faster asynchronous processing
    • Removed legacy automatic-budget endpoint and deprecated PayPal queue workflow
  • New Features

    • Added a message-existence check capability for notification handlers (with explicit unsupported behavior documented for one provider)
  • Chores

    • Lowered logging verbosity for token and webhook verification steps

✏️ Tip: You can customize this high-level summary in your review settings.

@Billos Billos self-assigned this Jan 22, 2026
@coderabbitai

coderabbitai Bot commented Jan 22, 2026

Copy link
Copy Markdown

Warning

Rate limit exceeded

@Billos has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 7 minutes and 26 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📝 Walkthrough

Walkthrough

Centralizes queue enqueueing into new helpers, reorganizes job modules under src/queues/jobs/, updates init signatures to no-arg, removes the updateAutomaticBudgets HTTP endpoint, adjusts several job delays, makes QueueArgs.transactionId optional, and adds hasMessageId plumbing for transaction handlers.

Changes

Cohort / File(s) Change Summary
Queue Core & Types
src/queues/index.ts, src/queues/constants.ts, src/queues/queueArgs.ts
Reorganized imports to jobs/ namespace; changed JobDefinition/TransactionJobDefinition init signatures to init(); widened getQueue() return type; updated JOB_DELAYS for four jobs; made transactionId optional in QueueArgs.
Centralized Queue Helpers
src/queues/jobs.ts
New module adding addJobToQueue(job, asap?) and addTransactionJobToQueue(job, transactionId) to encapsulate queue retrieval, delay/deduplication, job options, and logging.
Job Modules (moved/refactored)
src/queues/jobs/*.ts, src/queues/linkPaypalTransactions.ts
Migrated job modules under src/queues/jobs/; changed init() to no-arg; replaced direct queue.add usage with centralized helpers; removed legacy src/queues/linkPaypalTransactions.ts.
Specific Job Additions
src/queues/jobs/linkPaypalTransactions.ts
Added new job module for linking PayPal transactions (exports id, job, init) under src/queues/jobs/.
Endpoint changes
src/endpoints/updateAutomaticBudgets.ts, src/endpoints/webhook.ts
Removed updateAutomaticBudgets HTTP endpoint. webhook.ts now delegates to addTransactionJobToQueue / addJobToQueue instead of getQueue/getJobDelay and duplicate-existence checks.
Transaction Handler API & Implementations
src/modules/transactionHandler/transactionHandler.ts, src/modules/transactionHandler/discord.ts, src/modules/transactionHandler/gotify.ts
Added hasMessageId API and abstract hasMessageIdImpl; implemented hasMessageIdImpl for Gotify (performs GET messages) and Discord (throws unsupported error).
Logging tweaks
src/utils/tokenMiddleware.ts, src/utils/webhookSecret.ts
Lowered some verification logs from info to debug.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant Webhook as "Webhook Endpoint\n(src/endpoints/webhook.ts)"
  participant JobHelper as "Queue Helpers\n(src/queues/jobs.ts)"
  participant Queue as "BullMQ Queue\n(getQueue)"
  participant Worker as "Worker (job handlers)\n(src/queues/jobs/*)"

  Client->>Webhook: POST webhook payload
  Webhook->>JobHelper: call addJobToQueue(job) or addTransactionJobToQueue(job, transactionId)
  JobHelper->>Queue: getQueue() and compute delay/dedup
  JobHelper->>Queue: queue.add(jobPayload, jobOptions)
  Queue-->>JobHelper: Job enqueued
  Queue->>Worker: worker picks up job
  Worker->>Worker: execute job logic (job handlers under src/queues/jobs/*)
  Webhook-->>Client: send closing script response
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • Feat/worker #8: Touches src/endpoints/updateAutomaticBudgets.ts and relates to enqueueing/refactoring of that endpoint.

Poem

🐰 I hopped through queues with a carrot and quill,
I wrangled jobs and helpers, neat and still,
Modules moved homes, delays trimmed fine,
Endpoints lightened — now the jobs align. ✨

🚥 Pre-merge checks | ✅ 1 | ❌ 2
❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'Develop' is vague and generic, providing no meaningful information about the changeset's purpose or main objectives. Use a descriptive title that summarizes the primary change, such as 'Refactor queue job initialization and remove updateAutomaticBudgets endpoint' or 'Centralize job queueing logic with new queue helpers'.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/queues/jobs/uncategorizedTransactions.ts (1)

56-64: Unreachable null check – the destructuring would throw first.

The transaction variable is destructured on line 56 ({ type, amount, ... } = transaction). If transaction were null or undefined, the destructuring would throw a runtime error before the null check on line 61 is reached.

Consider reordering: check for !transaction before destructuring, or remove the dead code path.

Suggested fix
   const {
     data: {
       attributes: {
         transactions: [transaction],
       },
     },
   } = await TransactionsService.getTransaction(transactionId)
 
+  if (!transaction) {
+    logger.info("Transaction %s not found", transactionId)
+    return
+  }
+
   // Ensure the transaction is a withdrawal
   const { type, amount, currency_decimal_places, currency_symbol, description } = transaction
   if (type !== TransactionTypeProperty.WITHDRAWAL) {
     logger.info("Transaction %s is not a withdrawal", transactionId)
     return
   }
-  if (!transaction) {
-    logger.info("Transaction %s not found", transactionId)
-    return
-  }
src/queues/jobs/unbudgetedTransactions.ts (1)

34-42: Unreachable null check – the destructuring would throw first.

Same issue as in uncategorizedTransactions.ts: the transaction variable is destructured on line 34, but the null check on line 39 would never be reached if transaction were null or undefined.

Consider reordering: check for !transaction before destructuring, or remove the dead code path.

Suggested fix
   const {
     data: {
       attributes: {
         transactions: [transaction],
       },
     },
   } = await TransactionsService.getTransaction(transactionId)
 
+  if (!transaction) {
+    logger.info("Transaction %s not found", transactionId)
+    return
+  }
+
   // Ensure the transaction is a withdrawal
   const { type, amount, currency_decimal_places, currency_symbol, description } = transaction
   if (type !== TransactionTypeProperty.WITHDRAWAL) {
     logger.info("Transaction %s is not a withdrawal", transactionId)
     return
   }
-  if (!transaction) {
-    logger.info("Transaction %s not found", transactionId)
-    return
-  }
🤖 Fix all issues with AI agents
In `@src/queues/jobs.ts`:
- Around line 35-40: The asap flag is ignored because addJobToQueue computes
delay via getJobDelay(job, false, asap) but calls queue.add with
queueConfig(job) which recomputes delay without asap; fix by making queueConfig
accept the computed delay or an asap param and using that when building the job
options—e.g., modify queueConfig signature to queueConfig(job, delay) or
queueConfig(job, asap) and update addJobToQueue to pass the computed delay/asap
so the logged delay matches the actual scheduling for functions addJobToQueue,
getJobDelay and queueConfig.
🧹 Nitpick comments (2)
src/queues/constants.ts (1)

8-13: Consider adding comments to document delay units and rationale.

The delay values have been reduced across all job types. While the relative ordering is preserved, it would be helpful to document:

  1. The unit of these values (seconds, based on getJobDelay multiplying by 1000)
  2. The reasoning behind these specific delay values

This aids future maintainability and helps prevent accidental misinterpretation.

💡 Suggested documentation
+// Delay values in seconds - multiplied by 1000 in getJobDelay()
 export const JOB_DELAYS: Record<JobIds, number> = {
   [JobIds.UPDATE_AUTOMATIC_BUDGETS]: 25,
   [JobIds.UNBUDGETED_TRANSACTIONS]: 15,
   [JobIds.UNCATEGORIZED_TRANSACTIONS]: 8,
   [JobIds.LINK_PAYPAL_TRANSACTIONS]: 30,
 }
src/queues/jobs.ts (1)

28-33: Minor: Redundant getJobDelay computation.

getJobDelay is called on line 30 for logging and again inside queueConfig on line 32. Consider reusing the computed delay to avoid the redundant call.

This also affects addJobToQueue (lines 37-39) and becomes essential there to fix the asap bug noted above.

Comment thread src/queues/jobs.ts
Comment on lines +35 to +40
export async function addJobToQueue(job: JobIds, asap?: boolean): Promise<Job> {
const queue = await getQueue()
const delay = getJobDelay(job, false, asap)
logger.info("Adding job to queue: %s with delay: %d seconds", job, delay / 1000)
return queue.add(job, { job }, queueConfig(job))
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

The asap parameter has no effect on actual job scheduling.

The delay logged on line 38 uses getJobDelay(job, false, asap), but queueConfig(job) on line 39 internally calls getJobDelay(job, false) without the asap parameter. This means:

  • The log message shows the ASAP delay when asap=true
  • But the actual job is scheduled with the normal delay

The asap flag is effectively ignored for actual scheduling.

🐛 Proposed fix

Either pass the computed delay to queueConfig, or extend queueConfig to accept the asap parameter:

Option 1: Pass delay directly

-function queueConfig(job: JobIds, transactionId?: string): JobsOptions {
+function queueConfig(job: JobIds, transactionId?: string, delay?: number): JobsOptions {
+  const effectiveDelay = delay ?? getJobDelay(job, false)
   return {
     removeOnComplete: true,
     removeOnFail: true,
-    delay: getJobDelay(job, false),
+    delay: effectiveDelay,
     deduplication: getDebounce(job, transactionId),
   }
 }

Then update addJobToQueue:

 export async function addJobToQueue(job: JobIds, asap?: boolean): Promise<Job> {
   const queue = await getQueue()
   const delay = getJobDelay(job, false, asap)
   logger.info("Adding job to queue: %s with delay: %d seconds", job, delay / 1000)
-  return queue.add(job, { job }, queueConfig(job))
+  return queue.add(job, { job }, queueConfig(job, undefined, delay))
 }
🤖 Prompt for AI Agents
In `@src/queues/jobs.ts` around lines 35 - 40, The asap flag is ignored because
addJobToQueue computes delay via getJobDelay(job, false, asap) but calls
queue.add with queueConfig(job) which recomputes delay without asap; fix by
making queueConfig accept the computed delay or an asap param and using that
when building the job options—e.g., modify queueConfig signature to
queueConfig(job, delay) or queueConfig(job, asap) and update addJobToQueue to
pass the computed delay/asap so the logged delay matches the actual scheduling
for functions addJobToQueue, getJobDelay and queueConfig.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/queues/jobs/unbudgetedTransactions.ts (1)

33-42: Null check occurs after destructuring - potential runtime error.

The code destructures properties from transaction on line 34, but the existence check for transaction happens later on lines 39-42. If transaction is undefined, this will throw before reaching the guard.

🐛 Proposed fix: Reorder the null check
   const {
     data: {
       attributes: {
         transactions: [transaction],
       },
     },
   } = await TransactionsService.getTransaction(transactionId)

+  if (!transaction) {
+    logger.info("Transaction %s not found", transactionId)
+    return
+  }
+
   // Ensure the transaction is a withdrawal
   const { type, amount, currency_decimal_places, currency_symbol, description } = transaction
   if (type !== TransactionTypeProperty.WITHDRAWAL) {
     logger.info("Transaction %s is not a withdrawal", transactionId)
     return
   }
-  if (!transaction) {
-    logger.info("Transaction %s not found", transactionId)
-    return
-  }
src/queues/jobs/uncategorizedTransactions.ts (1)

55-64: Null check occurs after destructuring - potential runtime error.

Same issue as in unbudgetedTransactions.ts: the code destructures transaction on line 56, but the existence check happens on lines 61-64. This will throw if transaction is undefined.

🐛 Proposed fix: Reorder the null check
   // Ensure the transaction is a withdrawal
-  const { type, amount, currency_decimal_places, currency_symbol, description } = transaction
-  if (type !== TransactionTypeProperty.WITHDRAWAL) {
-    logger.info("Transaction %s is not a withdrawal", transactionId)
-    return
-  }
   if (!transaction) {
     logger.info("Transaction %s not found", transactionId)
     return
   }
+  const { type, amount, currency_decimal_places, currency_symbol, description } = transaction
+  if (type !== TransactionTypeProperty.WITHDRAWAL) {
+    logger.info("Transaction %s is not a withdrawal", transactionId)
+    return
+  }
♻️ Duplicate comments (1)
src/queues/jobs.ts (1)

35-40: The asap parameter has no effect on actual job scheduling.

The delay computed on line 37 uses getJobDelay(job, false, asap), but queueConfig(job) on line 39 internally calls getJobDelay(job, false) without the asap parameter. The logged delay differs from the actual scheduled delay when asap=true.

🧹 Nitpick comments (1)
src/queues/jobs.ts (1)

10-26: Consider extracting shared delay computation to avoid redundancy.

Both getDebounce (line 13) and queueConfig (line 23) independently call getJobDelay(job, false). This results in two separate delay computations for TTL and job delay. While currently consistent, this could drift if logic changes.

♻️ Optional: Compute delay once and pass it
-function queueConfig(job: JobIds, transactionId?: string): JobsOptions {
+function queueConfig(job: JobIds, transactionId?: string, delay?: number): JobsOptions {
+  const effectiveDelay = delay ?? getJobDelay(job, false)
   return {
     removeOnComplete: true,
     removeOnFail: true,
-    delay: getJobDelay(job, false),
-    deduplication: getDebounce(job, transactionId),
+    delay: effectiveDelay,
+    deduplication: {
+      id: transactionId ? `${job}-${transactionId}` : job,
+      ttl: effectiveDelay,
+      extend: true,
+      replace: true,
+    },
   }
 }

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@src/modules/transactionHandler/discord.ts`:
- Around line 30-32: The hasMessageIdImpl method currently declares a parameter
messageId that is unused and triggers TS6133; rename the parameter to _messageId
(matching the file's unused-parameter pattern like _title) so TypeScript treats
it as intentionally unused, leaving the method body unchanged (throwing the same
Error) in the override of hasMessageIdImpl.
🧹 Nitpick comments (1)
src/modules/transactionHandler/gotify.ts (1)

40-48: Add defensive check for potentially undefined messages array.

If the API returns an unexpected response where messages is undefined or null, calling .map() will throw before reaching the catch block. Consider adding a defensive check.

♻️ Proposed fix
   override async hasMessageIdImpl(messageId: string): Promise<boolean> {
     try {
       const messages = await this.request.get<GetMessage>(`/application/${env.gotifyApplicationId}/message?token=${env.gotifyUserToken}`)
-      const ids = messages.data.messages.map((msg) => msg.id.toString())
+      const ids = (messages.data.messages ?? []).map((msg) => msg.id.toString())
       return ids.includes(messageId)
     } catch {
       return false
     }
   }

Comment thread src/modules/transactionHandler/discord.ts Outdated
@Billos
Billos merged commit aad3fab into main Jan 22, 2026
5 checks passed
@coderabbitai coderabbitai Bot mentioned this pull request Jan 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant