Repository navigation
[React Query] New queries and mutations for rules - #7070
joel-jeremy wants to merge 11 commits into
Conversation
✅ Deploy Preview for actualbudget ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
📝 WalkthroughWalkthroughReplaces IPC-driven rule operations with React Query hooks and mutations, centralizes rule queries/mutations (list, payee-list, CRUD, run, apply, batch), updates UI to consume hook-driven loading/refetch flows, tightens server signatures (throwing errors) and adjusts several component prop/type signatures. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant UI as "Client UI"
participant Hooks as "Rules Hooks / Mutations"
participant Server as "Backend (mutators / RPC)"
participant Cache as "React Query Cache"
UI->>Hooks: call mutateAsync({ transaction / payload })
Hooks->>Server: RPC / mutator call (e.g., rules-run, create-schedule, add-rule)
Server-->>Hooks: result or throw error
Hooks->>Cache: invalidate relevant queries (rules lists)
Cache-->>UI: refetch / updated data via useQuery
Estimated code review effort🎯 4 (Complex) | ⏱️ ~75 minutes Poem
🚥 Pre-merge checks | ✅ 1 | ❌ 1❌ Failed checks (1 inconclusive)
✅ Passed checks (1 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
📝 Coding Plan
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. Comment Tip CodeRabbit can use OpenGrep to find security vulnerabilities and bugs across 17+ programming languages.OpenGrep is compatible with Semgrep configurations. Add an |
There was a problem hiding this comment.
Actionable comments posted: 8
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (8)
packages/desktop-client/src/components/accounts/Account.tsx (1)
712-739:⚠️ Potential issue | 🟡 MinorUser-facing error messages are not translated.
Two notification messages — the formula error summary (Line 714) and the generic failure message (Line 737) — are raw string literals not wrapped with
t(). As per the i18n guidelines, all user-facing strings must be translated.🌐 Proposed fix
- message: `Formula errors in rules:\n${allErrors.join('\n')}`, + message: t('Formula errors in rules:\n{{errors}}', { errors: allErrors.join('\n') }),- message: 'Failed to apply rules to transactions', + message: t('Failed to apply rules to transactions'),🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/desktop-client/src/components/accounts/Account.tsx` around lines 712 - 739, The two user-facing notification strings must be localized: wrap the formula error summary and the generic failure message with the i18n t() function (ensure t is imported where Account.tsx defines methods like the try/catch around apply rules); for the formula error use a translation key with a placeholder and pass errors: allErrors.join('\n') (i.e., message: t('accounts.formulaErrors', { errors: allErrors.join('\n') }) or similar) and replace the hardcoded 'Failed to apply rules to transactions' with t('accounts.applyRulesFailed'); keep the notifications created via addNotification unchanged except for replacing message values, and ensure any newline formatting is preserved via the placeholder.packages/desktop-client/src/components/modals/MergeUnusedPayeesModal.tsx (1)
64-83:⚠️ Potential issue | 🟡 MinorAdd the new mutation to the
useCallbackdeps.
onMergenow closes overaddPayeeRenameRuleAsyncbut it isn’t listed in the dependency array, which risks stale closures and hooks lint warnings.🔧 Suggested change
- [shouldCreateRule, isEditingRule, payees], + [shouldCreateRule, isEditingRule, payees, addPayeeRenameRuleAsync],🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/desktop-client/src/components/modals/MergeUnusedPayeesModal.tsx` around lines 64 - 83, The onMerge useCallback closes over addPayeeRenameRuleAsync (and also uses send) but the dependency array only lists shouldCreateRule, isEditingRule, and payees; update the dependency array for the onMerge callback (the one declared with useCallback in MergeUnusedPayeesModal.tsx) to include addPayeeRenameRuleAsync (and send if it comes from props/hooks) so the hook doesn't capture a stale closure and satisfies lint rules.packages/desktop-client/src/hooks/usePreviewTransactions.ts (2)
76-143:⚠️ Potential issue | 🟡 MinorAdd
runRulesAsyncto the effect dependencies.The effect closes over
runRulesAsync, but it isn’t listed, which can produce stale closures and hooks lint warnings.🔧 Suggested change
- }, [scheduleTransactions, schedules, statuses, upcomingLength]); + }, [runRulesAsync, scheduleTransactions, schedules, statuses, upcomingLength]);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/desktop-client/src/hooks/usePreviewTransactions.ts` around lines 76 - 143, The useEffect in the usePreviewTransactions hook closes over runRulesAsync (from useRunRulesMutation) but the dependency array only lists scheduleTransactions, schedules, statuses, and upcomingLength; update the effect's dependency array to include runRulesAsync so the effect re-runs when the mutation function changes and to satisfy the hooks lint rule; locate the useEffect block inside usePreviewTransactions and add runRulesAsync to the array of dependencies.
76-95:⚠️ Potential issue | 🟠 MajorAvoid user-facing side effects during preview generation.
useRunRulesMutationinvalidates rule queries and dispatches error notifications. Running it for every preview transaction can spam invalidations and surface errors for background previews. Consider using a lightweight helper (e.g., directsend('rules-run')) or adding a “silent”/“no-invalidate” option to the mutation for this path.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/desktop-client/src/hooks/usePreviewTransactions.ts` around lines 76 - 95, The preview hook usePreviewTransactions currently calls runRulesAsync (from useRunRulesMutation) for each scheduleTransactions which triggers query invalidations and error notifications; change this to a non-user-facing path by either (1) invoking a lightweight helper that dispatches the rule engine without side effects (e.g., call send('rules-run') / applyRulesSilently) from inside usePreviewTransactions, or (2) extend useRunRulesMutation to accept a silent option (e.g., { silent: true } or { noInvalidate: true }) and pass that option when calling runRulesAsync so it applies rules for previews without invalidating queries or emitting notifications; update the call sites in usePreviewTransactions (where runRulesAsync is used) to use the new silent helper/option and ensure the mutation implementation checks that flag and skips invalidation/notification logic.packages/desktop-client/src/components/filters/FiltersMenu.tsx (1)
26-32:⚠️ Potential issue | 🔴 Critical
unparseis now undefined—replace withunparseConditionsat line 619.The import was switched to
unparseConditions, but the code at line 619 still calls the undefinedunparsefunction, causing a compilation error.Fix
- // `@ts-expect-error` - fix me - cond = unparse({ ...cond, type: FIELD_TYPES.get(cond.field) }); + // `@ts-expect-error` - fix me + cond = unparseConditions({ ...cond, type: FIELD_TYPES.get(cond.field) });🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/desktop-client/src/components/filters/FiltersMenu.tsx` around lines 26 - 32, The code still calls the removed function unparse (causing a compile error) — replace that call with unparseConditions so the imported symbol is used; update the invocation at the FiltersMenu component where unparse(...) is called to unparseConditions(...) with the same arguments, ensuring you remove any lingering references to unparse and rely on the already-imported unparseConditions.packages/desktop-client/src/components/rules/RuleEditor.tsx (1)
1008-1062:⚠️ Potential issue | 🟠 MajorUse optional chaining for
splitIndexextraction and remove the type assertion inactionSplitsinit.The pattern
'options' in action && 'splitIndex' in action.optionscan throw a TypeError ifoptionsis explicitlyundefined. Most action types in theRuleActionEntityunion haveoptionsas optional, making them vulnerable. Additionally, theas (typeof actionSplits)[0]type assertion violates the coding guideline to avoid assertions.✅ Suggested fix
- const parsedActions = defaultRule.actions.map(parseActions); + const parsedActions = defaultRule.actions.map(parseActions); + const initialSplits: Array<{ + id: string; + actions: Array<RuleActionEntity & { inputKey: string }>; + }> = [{ id: uuid(), actions: [] }]; return parsedActions.reduce( (acc, action) => { - const splitIndex = - 'options' in action && 'splitIndex' in action.options - ? (action.options.splitIndex ?? 0) - : 0; + const splitIndex = action.options?.splitIndex ?? 0; acc[splitIndex] = acc[splitIndex] ?? { id: uuid(), actions: [] }; acc[splitIndex].actions.push({ ...action, inputKey: uuid() }); return acc; }, // The pre-split group is always there - [{ id: uuid(), actions: [] } as (typeof actionSplits)[0]], + initialSplits, );🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/desktop-client/src/components/rules/RuleEditor.tsx` around lines 1008 - 1062, The splitIndex extraction in the actionSplits initializer can throw if action.options is undefined and the initial accumulator uses a type assertion; update the reducer in the actionSplits useState (the block that calls parseActions on defaultRule.actions and reduces into actionSplits) to use optional chaining when reading splitIndex (e.g., action.options?.splitIndex ?? 0) and remove the "as (typeof actionSplits)[0]" assertion by constructing the initial accumulator with an explicitly shaped object that matches the actionSplits element type (id: uuid(), actions: []) or by casting the whole useState generic instead of asserting the initial value.packages/desktop-client/src/components/mobile/transactions/TransactionEdit.tsx (2)
677-792:⚠️ Potential issue | 🟡 MinorAdd
createSingleTimeScheduleFromTransactionto theonSaveInnerdependency array.The mutation function is directly used within the callback at line 730 (
await createSingleTimeScheduleFromTransaction(...)). It must be included in the dependency array to satisfy thereact-hooks/exhaustive-depsESLint rule.Suggested fix
- }, [ - isAdding, - dispatch, - navigate, - onSave, - unserializedTransactions, - upcomingLength, - t, - ]); + }, [ + isAdding, + dispatch, + navigate, + onSave, + unserializedTransactions, + upcomingLength, + t, + createSingleTimeScheduleFromTransaction, + ]);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/desktop-client/src/components/mobile/transactions/TransactionEdit.tsx` around lines 677 - 792, The onSaveInner callback uses the mutation function createSingleTimeScheduleFromTransaction but doesn't list it in its dependency array, violating react-hooks/exhaustive-deps; update the dependency array for onSaveInner (the useCallback that defines onSaveInner) to include createSingleTimeScheduleFromTransaction so the hook re-evaluates when that mutation function changes.
1421-1479:⚠️ Potential issue | 🟡 MinorAdd
runRulesAsyncto theonUpdatedependency array.The callback uses
runRulesAsyncbut doesn't include it in the dependency array. SinceuseMutationis not listed in the codebase's ESLintexhaustive-depsadditionalHooksconfig, all used variables must be explicitly included in dependencies.Suggested fix
- [dateFormat, transactions], + [dateFormat, transactions, runRulesAsync],🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/desktop-client/src/components/mobile/transactions/TransactionEdit.tsx` around lines 1421 - 1479, The onUpdate callback (defined with useCallback) references runRulesAsync from useRunRulesMutation but runRulesAsync is missing from its dependency array; update the dependency array for onUpdate to include runRulesAsync (in addition to dateFormat and transactions) so the callback updates correctly when the mutation function changes.
🧹 Nitpick comments (9)
packages/loot-core/src/server/rules/app.ts (2)
126-134:return isSuccessat Line 133 is alwaystrueand is misleading.After the
if (!isSuccess) throw ...guard,isSuccessis alwaystrue. The explicitreturn isSuccessis confusing — replace withreturn true(orreturn isSuccessis fine logically, but the intent is unclear).♻️ Proposed fix
async function deleteRule(id: RuleEntity['id']) { const isSuccess = await rules.deleteRule(id); if (!isSuccess) { throw new Error( 'Error deleting rule. The rule may be linked to a schedule which prevents it from being deleted.', ); } - return isSuccess; + return true; }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/loot-core/src/server/rules/app.ts` around lines 126 - 134, The return of isSuccess in deleteRule is misleading because after the guard `if (!isSuccess) throw ...` the variable can only be true; update the function to make intent clear by returning a literal true instead of `isSuccess` (or alternatively remove the variable and directly `await rules.deleteRule(id)` then return true); locate the deleteRule function and the `isSuccess` assignment from `rules.deleteRule(id)` and change the final `return isSuccess;` to `return true;` (or simplify by omitting `isSuccess` and returning true after the throw guard).
106-123: Throwing a plainValidationErrorobject loses stack trace information.Both
addRuleandupdateRulethrow errorwhereerroris a plain object{ conditionErrors, actionErrors }(not anErrorinstance). Plain-object throws have no stack trace, andinstanceof Errorguards in catch-blocks won't match them. TheValidationErrortype already exists (Lines 67–70); wrapping it in a properErrorsubclass would make error handling more robust and debuggable.♻️ Suggested improvement
+class RuleValidationError extends Error { + conditionErrors: string[]; + actionErrors: string[]; + constructor({ conditionErrors, actionErrors }: ValidationError) { + super('Rule validation failed'); + this.conditionErrors = conditionErrors; + this.actionErrors = actionErrors; + } +} async function addRule(rule: Omit<RuleEntity, 'id'>): Promise<RuleEntity> { const error = validateRule(rule); if (error) { - throw error; + throw new RuleValidationError(error); } ... }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/loot-core/src/server/rules/app.ts` around lines 106 - 123, The validateRule call presently returns a plain object which is thrown (in addRule and updateRule), losing stack and Error semantics; change this by creating/using a real Error subclass (e.g., class ValidationError extends Error that accepts conditionErrors and actionErrors and sets them as properties, capturing the stack) and replace the raw throws in addRule and updateRule with throwing a new instance (e.g., throw new ValidationError(conditionErrors, actionErrors)); ensure the ValidationError constructor sets name, message, the two error arrays, and captures stack (via Error.captureStackTrace or super()) so downstream instanceof Error checks and stack traces work.packages/desktop-client/src/hooks/useRules.ts (1)
8-8: Consider exportingUseRulesOptionsfor external consumers.
UseRulesOptionsis not exported. Any component that wants to type theoptionsargument ofuseRules(e.g., in auseMemoor when forwarding props) must inlinePick<UseQueryOptions<RuleEntity[]>, 'enabled'>or useParameters<typeof useRules>[0]. Exporting the type is a minor ergonomics improvement.♻️ Proposed change
-type UseRulesOptions = Pick<UseQueryOptions<RuleEntity[]>, 'enabled'>; +export type UseRulesOptions = Pick<UseQueryOptions<RuleEntity[]>, 'enabled'>;🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/desktop-client/src/hooks/useRules.ts` at line 8, UseRulesOptions is currently unexported which forces callers to inline its definition; export the type so external consumers can reference it. Update the declaration of UseRulesOptions to be exported (export type UseRulesOptions = Pick<UseQueryOptions<RuleEntity[]>, 'enabled'>) and ensure the module's public exports include it alongside useRules so callers can import UseRulesOptions directly.packages/desktop-client/src/components/accounts/Account.tsx (1)
1059-1062:Promise.allon rules execution is unnecessary for a single reconciliation transaction.
realizeTempTransactionsalways produces exactly one reconciliation transaction, soPromise.alladds no parallelism benefit. More importantly,runRules→finalizeTransactionForRulescan insert new payees; running multiple transactions concurrently could cause duplicate payee inserts (a known hazard in this codebase). A sequential loop is safer and equally performant here.♻️ Proposed refactor
- const runRules = this.props.onRunRules; - const ruledTransactions = await Promise.all( - reconciliationTransactions.map(transaction => runRules(transaction)), - ); + const ruledTransactions: TransactionEntity[] = []; + for (const transaction of reconciliationTransactions) { + ruledTransactions.push(await this.props.onRunRules(transaction)); + }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/desktop-client/src/components/accounts/Account.tsx` around lines 1059 - 1062, realizeTempTransactions always returns exactly one reconciliation transaction, so calling Promise.all on reconciliationTransactions with runRules risks concurrent inserts (runRules → finalizeTransactionForRules) and is unnecessary; replace the Promise.all call in Account.tsx with a sequential await loop (e.g., for/for-of) that calls this.props.onRunRules (runRules) for each transaction to ensure runs execute one-by-one and avoid duplicate payee inserts.packages/desktop-client/src/rules/mutations.ts (1)
285-305: Replaceascasts withsatisfiesto avoid unsoundness.There are multiple
as RuleConditionEntity/as RuleActionEntitycasts in this function. Prefersatisfiesto retain inference without silencing type checks.♻️ Example refactor
- conditions.push({ - op: 'is', - field, - value, - } as RuleConditionEntity); + const condition = { + op: 'is', + field, + value, + } satisfies RuleConditionEntity; + conditions.push(condition);As per coding guidelines: "Avoid type assertions (
as,!) - prefersatisfies."🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/desktop-client/src/rules/mutations.ts` around lines 285 - 305, Replace the unsound type assertions in this function by using TypeScript's "satisfies" operator on the literal objects pushed into conditions and actions: where you currently do conditions.push({ op: 'is', field, value, } as RuleConditionEntity) and actions.push({ op: 'set', field: 'notes', value: transaction.notes, options: { splitIndex: 0 } } as RuleActionEntity), remove the "as ..." casts and append "satisfies RuleConditionEntity" or "satisfies RuleActionEntity" to the object expression so the compiler narrows types without silencing checks (apply this to the objects created in conditionFields.forEach and the objects pushed when transaction.is_parent && transaction.subtransactions).packages/desktop-client/src/components/ManageRules.tsx (1)
217-244: Don’tawaitmutate—usemutateAsyncor dropasync/await.
useMutation().mutateis not async. The currentawaitis a no-op and can mislead future readers. Either removeasync/awaitor switch tomutateAsyncif you need a promise.✅ Option A: remove async/await
- const onDeleteSelected = async () => { + const onDeleteSelected = () => { batchDeleteRules( { ids: [...selectedInst.items], }, { onSuccess: () => { void refetchRules(); selectedInst.dispatch({ type: 'select-none' }); }, }, ); };- async function onDeleteRule(id: string) { - await deleteRule( + function onDeleteRule(id: string) { + deleteRule( { id }, { onSuccess: () => { void refetchRules(); }, }, ); }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/desktop-client/src/components/ManageRules.tsx` around lines 217 - 244, The handlers onDeleteSelected and onDeleteRule are awaiting non-async mutate functions; update them to either call the async variants or remove async/await: for example replace batchDeleteRules(...) with await batchDeleteRules.mutateAsync({...}) (or drop async/await and call batchDeleteRules({...}) directly) and similarly replace deleteRule(...) with await deleteRule.mutateAsync({ id }) or remove async/await and call deleteRule({ id }). Keep the existing onSuccess callbacks (refetchRules and selectedInst.dispatch) intact when switching to mutateAsync or when keeping mutate.packages/desktop-client/src/components/filters/FiltersMenu.tsx (1)
299-331: Avoidanyin theGenericInputonChange handler.Since this block was touched, consider tightening the type on
onChangeto avoidanyand keep the reducer typed (e.g.,T['value']). This aligns with the repo’s TS guidelines.✅ Example tightening
- // oxlint-disable-next-line typescript/no-explicit-any - onChange={(v: any) => { + onChange={(v: T['value']) => { dispatch({ type: 'set-value', value: v }); }}As per coding guidelines, Avoid
anyorunknownunless absolutely necessary.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/desktop-client/src/components/filters/FiltersMenu.tsx` around lines 299 - 331, The onChange handler for GenericInput uses an any-typed parameter; replace that with a concrete type pulled from the GenericInput prop or your filter state so the reducer stays typed. Locate the GenericInput usage in FiltersMenu.tsx (the onChange that calls dispatch({ type: 'set-value', value: v })) and change the parameter type from any to the proper value type (for example the GenericInput onChange prop type or the FilterState/Reducer action payload type such as T['value'] or the exported type used by GenericInput), updating imports/types if necessary so dispatch({ type: 'set-value', value: v }) remains correctly typed without using any.packages/desktop-client/src/rules/queries.ts (1)
6-20: Prefer function/method syntax andsatisfiesoveras constfor query keys.To align with TS guidelines, avoid const assertions and use function/method syntax for pure functions. You can keep the tuple typing with
satisfies.✅ Example adjustment
-export const ruleQueries = { - all: () => ['rules'] as const, - lists: () => [...ruleQueries.all(), 'lists'] as const, +export const ruleQueries = { + all() { + return ['rules'] satisfies readonly ['rules']; + }, + lists() { + return [...ruleQueries.all(), 'lists'] satisfies readonly ['rules', 'lists']; + }, list: () => queryOptions<RuleEntity[]>({ - queryKey: [...ruleQueries.lists()], + queryKey: [...ruleQueries.lists()], queryFn: async () => { return await send('rules-get'); }, staleTime: Infinity, }),As per coding guidelines, Use the
functionkeyword for pure functions - prefer functional and declarative programming patterns. Avoid type assertions (as,!) - prefersatisfies.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/desktop-client/src/rules/queries.ts` around lines 6 - 20, Change the query key helpers to use named function declarations (use the function keyword) instead of arrow functions and replace "as const" assertions with tuple typing using "satisfies"; specifically update ruleQueries.all, ruleQueries.lists, and any queryKey arrays inside list and listPayee to return typed tuples that use "satisfies readonly [...] " (or appropriate tuple type) rather than casting with as const, and keep queryOptions usages (in list and listPayee) referencing those function results for queryKey so the keys remain strongly typed without const assertions.packages/loot-core/src/shared/rules.ts (1)
98-113: Avoidas unknown asin FIELD_TYPES mapping.The double assertion makes the typing brittle. Consider centralizing the typing with a small
typedEntrieshelper to localize the cast, where a single assertion is more acceptable than the double cast pattern.♻️ Example refactor (helper localizes the necessary assertion)
+const typedEntries = <T extends Record<string, { type: keyof typeof TYPE_INFO }>>( + obj: T, +) => Object.entries(obj) as Array<[keyof T, T[keyof T]]>; + export const FIELD_TYPES = new Map( - Object.entries(FIELD_INFO).map( - ([field, info]) => - [field as unknown as keyof FieldValueTypes, info.type] as const, - ), + typedEntries(FIELD_INFO).map(([field, info]) => [field, info.type] as const), );🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/loot-core/src/shared/rules.ts` around lines 98 - 113, The FIELD_TYPES map uses a brittle double-cast ([field as unknown as keyof FieldValueTypes])—replace that pattern by introducing a small typedEntries helper and use it in the FIELD_TYPES initialization so the key/value types are preserved without ad-hoc casts; update the export const FIELD_TYPES to call typedEntries(FIELD_INFO).map(...) (referencing FIELD_TYPES, FIELD_INFO, and FieldValueTypes) and ensure the helper signature localizes the single, explicit assertion instead of scattering casts across the codebase.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/desktop-client/src/components/ManageRules.tsx`:
- Around line 387-401: Replace the plain string i18n call in the Tooltip's
content prop with a React <Trans> element: in the Tooltip around the Delete
button (Tooltip component with props isOpen={isNonDeletableRuleSelected} and
content={...}), stop passing t('Some selected rules cannot be deleted because
they are linked to schedules.') and instead render a <Trans> component
containing that message so the Tooltip receives a React node; keep existing
props (isOpen) and handlers (onDeleteSelected, selectedInst.items.size)
unchanged.
In `@packages/desktop-client/src/components/mobile/rules/MobileRulesPage.tsx`:
- Around line 114-132: The handleRuleDelete useCallback closes over the
deleteRule function from useDeleteRuleMutation but does not include it in the
dependency array; update the dependency list for the useCallback that defines
handleRuleDelete to include deleteRule (in addition to dispatch,
showUndoNotification, t, refetchRules) so the callback updates if the mutation
hook returns a new function; locate the handleRuleDelete const and its
useCallback invocation and add deleteRule to the dependency array.
In `@packages/desktop-client/src/components/schedules/schedule-edit-utils.ts`:
- Around line 4-15: The filtered array in updateScheduleConditions currently
contains (RuleConditionEntity | null) items because .filter(val => !!val)
doesn't act as a TypeScript type predicate; change the filter to an explicit
type guard so the result is narrowed to RuleConditionEntity[] (e.g. replace the
.filter callback with a predicate like (val): val is RuleConditionEntity => val
!= null) and return that narrowed array from updateScheduleConditions so the
function signature { error?: string; conditions?: RuleConditionEntity[] } is
satisfied.
In `@packages/desktop-client/src/components/transactions/TransactionList.tsx`:
- Around line 253-255: The mutation returned from
useCreateSingleTimeScheduleFromTransaction is currently destructured as mutate
(createSingleTimeScheduleFromTransaction) and used fire-and-forget, so success
notification and onRefetch() may run before the schedule is created; change to
destructure mutateAsync (e.g., const { mutateAsync:
createSingleTimeScheduleFromTransaction } =
useCreateSingleTimeScheduleFromTransaction()) and await
createSingleTimeScheduleFromTransaction(...) so that you only show the success
notification and call onRefetch() after the awaited mutation resolves (and
handle errors if it rejects).
In `@packages/desktop-client/src/rules/mutations.ts`:
- Around line 389-394: The call to updateRule (a mutateAsync) is not awaited,
which can drop rejections and return before changes persist; modify the
invocation in the code that builds the new rule (where rule,
linkScheduleActions, and actions are combined) to await updateRule(...) or use
void updateRule(...) so the promise is handled—ensure you reference the
updateRule mutateAsync call and await its result (or explicitly void it) to
capture errors and guarantee the update completes.
- Around line 28-31: The invalidateQueries helper currently defaults to
ruleQueries.lists(), which misses payee-specific caches (e.g.,
ruleQueries.listPayee uses ruleQueries.all()+payeeId); change the default
queryKey passed into queryClient.invalidateQueries in invalidateQueries to use
ruleQueries.all() instead of ruleQueries.lists() so all rule-related queries
(including payee-specific ones) are invalidated after mutations.
- Around line 362-365: The auto-generated user-facing string assigned to
scheduleName should be localized; replace the hard-coded template with a
translated string using the app i18n function (e.g., t(...)) and interpolation
(use the same variables formattedDate and timestamp) so the label is produced
via translation rather than a literal; update the code around formattedDate,
timestamp, and scheduleName in mutations.ts to call t with a descriptive key and
pass { formattedDate, timestamp } (or equivalent) as interpolation params.
In `@packages/loot-core/src/server/api.ts`:
- Around line 779-795: The handlers api/rule-create and api/rule-update wrap all
errors and rethrow them as a generic APIError which masks infra errors and
passes an untyped unknown as meta; either remove the outer try/catch entirely so
errors from handlers['rule-add'] and handlers['rule-update'] propagate
unchanged, or narrow the catch to only handle validation-shaped errors (e.g.,
test for a ValidationError-like object returned by rules/app.ts) and rethrow
APIError with the correctly typed meta ({ conditionErrors: string[];
actionErrors: string[] }), while rethrowing any other errors unchanged.
---
Outside diff comments:
In `@packages/desktop-client/src/components/accounts/Account.tsx`:
- Around line 712-739: The two user-facing notification strings must be
localized: wrap the formula error summary and the generic failure message with
the i18n t() function (ensure t is imported where Account.tsx defines methods
like the try/catch around apply rules); for the formula error use a translation
key with a placeholder and pass errors: allErrors.join('\n') (i.e., message:
t('accounts.formulaErrors', { errors: allErrors.join('\n') }) or similar) and
replace the hardcoded 'Failed to apply rules to transactions' with
t('accounts.applyRulesFailed'); keep the notifications created via
addNotification unchanged except for replacing message values, and ensure any
newline formatting is preserved via the placeholder.
In `@packages/desktop-client/src/components/filters/FiltersMenu.tsx`:
- Around line 26-32: The code still calls the removed function unparse (causing
a compile error) — replace that call with unparseConditions so the imported
symbol is used; update the invocation at the FiltersMenu component where
unparse(...) is called to unparseConditions(...) with the same arguments,
ensuring you remove any lingering references to unparse and rely on the
already-imported unparseConditions.
In
`@packages/desktop-client/src/components/mobile/transactions/TransactionEdit.tsx`:
- Around line 677-792: The onSaveInner callback uses the mutation function
createSingleTimeScheduleFromTransaction but doesn't list it in its dependency
array, violating react-hooks/exhaustive-deps; update the dependency array for
onSaveInner (the useCallback that defines onSaveInner) to include
createSingleTimeScheduleFromTransaction so the hook re-evaluates when that
mutation function changes.
- Around line 1421-1479: The onUpdate callback (defined with useCallback)
references runRulesAsync from useRunRulesMutation but runRulesAsync is missing
from its dependency array; update the dependency array for onUpdate to include
runRulesAsync (in addition to dateFormat and transactions) so the callback
updates correctly when the mutation function changes.
In `@packages/desktop-client/src/components/modals/MergeUnusedPayeesModal.tsx`:
- Around line 64-83: The onMerge useCallback closes over addPayeeRenameRuleAsync
(and also uses send) but the dependency array only lists shouldCreateRule,
isEditingRule, and payees; update the dependency array for the onMerge callback
(the one declared with useCallback in MergeUnusedPayeesModal.tsx) to include
addPayeeRenameRuleAsync (and send if it comes from props/hooks) so the hook
doesn't capture a stale closure and satisfies lint rules.
In `@packages/desktop-client/src/components/rules/RuleEditor.tsx`:
- Around line 1008-1062: The splitIndex extraction in the actionSplits
initializer can throw if action.options is undefined and the initial accumulator
uses a type assertion; update the reducer in the actionSplits useState (the
block that calls parseActions on defaultRule.actions and reduces into
actionSplits) to use optional chaining when reading splitIndex (e.g.,
action.options?.splitIndex ?? 0) and remove the "as (typeof actionSplits)[0]"
assertion by constructing the initial accumulator with an explicitly shaped
object that matches the actionSplits element type (id: uuid(), actions: []) or
by casting the whole useState generic instead of asserting the initial value.
In `@packages/desktop-client/src/hooks/usePreviewTransactions.ts`:
- Around line 76-143: The useEffect in the usePreviewTransactions hook closes
over runRulesAsync (from useRunRulesMutation) but the dependency array only
lists scheduleTransactions, schedules, statuses, and upcomingLength; update the
effect's dependency array to include runRulesAsync so the effect re-runs when
the mutation function changes and to satisfy the hooks lint rule; locate the
useEffect block inside usePreviewTransactions and add runRulesAsync to the array
of dependencies.
- Around line 76-95: The preview hook usePreviewTransactions currently calls
runRulesAsync (from useRunRulesMutation) for each scheduleTransactions which
triggers query invalidations and error notifications; change this to a
non-user-facing path by either (1) invoking a lightweight helper that dispatches
the rule engine without side effects (e.g., call send('rules-run') /
applyRulesSilently) from inside usePreviewTransactions, or (2) extend
useRunRulesMutation to accept a silent option (e.g., { silent: true } or {
noInvalidate: true }) and pass that option when calling runRulesAsync so it
applies rules for previews without invalidating queries or emitting
notifications; update the call sites in usePreviewTransactions (where
runRulesAsync is used) to use the new silent helper/option and ensure the
mutation implementation checks that flag and skips invalidation/notification
logic.
---
Nitpick comments:
In `@packages/desktop-client/src/components/accounts/Account.tsx`:
- Around line 1059-1062: realizeTempTransactions always returns exactly one
reconciliation transaction, so calling Promise.all on reconciliationTransactions
with runRules risks concurrent inserts (runRules → finalizeTransactionForRules)
and is unnecessary; replace the Promise.all call in Account.tsx with a
sequential await loop (e.g., for/for-of) that calls this.props.onRunRules
(runRules) for each transaction to ensure runs execute one-by-one and avoid
duplicate payee inserts.
In `@packages/desktop-client/src/components/filters/FiltersMenu.tsx`:
- Around line 299-331: The onChange handler for GenericInput uses an any-typed
parameter; replace that with a concrete type pulled from the GenericInput prop
or your filter state so the reducer stays typed. Locate the GenericInput usage
in FiltersMenu.tsx (the onChange that calls dispatch({ type: 'set-value', value:
v })) and change the parameter type from any to the proper value type (for
example the GenericInput onChange prop type or the FilterState/Reducer action
payload type such as T['value'] or the exported type used by GenericInput),
updating imports/types if necessary so dispatch({ type: 'set-value', value: v })
remains correctly typed without using any.
In `@packages/desktop-client/src/components/ManageRules.tsx`:
- Around line 217-244: The handlers onDeleteSelected and onDeleteRule are
awaiting non-async mutate functions; update them to either call the async
variants or remove async/await: for example replace batchDeleteRules(...) with
await batchDeleteRules.mutateAsync({...}) (or drop async/await and call
batchDeleteRules({...}) directly) and similarly replace deleteRule(...) with
await deleteRule.mutateAsync({ id }) or remove async/await and call deleteRule({
id }). Keep the existing onSuccess callbacks (refetchRules and
selectedInst.dispatch) intact when switching to mutateAsync or when keeping
mutate.
In `@packages/desktop-client/src/hooks/useRules.ts`:
- Line 8: UseRulesOptions is currently unexported which forces callers to inline
its definition; export the type so external consumers can reference it. Update
the declaration of UseRulesOptions to be exported (export type UseRulesOptions =
Pick<UseQueryOptions<RuleEntity[]>, 'enabled'>) and ensure the module's public
exports include it alongside useRules so callers can import UseRulesOptions
directly.
In `@packages/desktop-client/src/rules/mutations.ts`:
- Around line 285-305: Replace the unsound type assertions in this function by
using TypeScript's "satisfies" operator on the literal objects pushed into
conditions and actions: where you currently do conditions.push({ op: 'is',
field, value, } as RuleConditionEntity) and actions.push({ op: 'set', field:
'notes', value: transaction.notes, options: { splitIndex: 0 } } as
RuleActionEntity), remove the "as ..." casts and append "satisfies
RuleConditionEntity" or "satisfies RuleActionEntity" to the object expression so
the compiler narrows types without silencing checks (apply this to the objects
created in conditionFields.forEach and the objects pushed when
transaction.is_parent && transaction.subtransactions).
In `@packages/desktop-client/src/rules/queries.ts`:
- Around line 6-20: Change the query key helpers to use named function
declarations (use the function keyword) instead of arrow functions and replace
"as const" assertions with tuple typing using "satisfies"; specifically update
ruleQueries.all, ruleQueries.lists, and any queryKey arrays inside list and
listPayee to return typed tuples that use "satisfies readonly [...] " (or
appropriate tuple type) rather than casting with as const, and keep queryOptions
usages (in list and listPayee) referencing those function results for queryKey
so the keys remain strongly typed without const assertions.
In `@packages/loot-core/src/server/rules/app.ts`:
- Around line 126-134: The return of isSuccess in deleteRule is misleading
because after the guard `if (!isSuccess) throw ...` the variable can only be
true; update the function to make intent clear by returning a literal true
instead of `isSuccess` (or alternatively remove the variable and directly `await
rules.deleteRule(id)` then return true); locate the deleteRule function and the
`isSuccess` assignment from `rules.deleteRule(id)` and change the final `return
isSuccess;` to `return true;` (or simplify by omitting `isSuccess` and returning
true after the throw guard).
- Around line 106-123: The validateRule call presently returns a plain object
which is thrown (in addRule and updateRule), losing stack and Error semantics;
change this by creating/using a real Error subclass (e.g., class ValidationError
extends Error that accepts conditionErrors and actionErrors and sets them as
properties, capturing the stack) and replace the raw throws in addRule and
updateRule with throwing a new instance (e.g., throw new
ValidationError(conditionErrors, actionErrors)); ensure the ValidationError
constructor sets name, message, the two error arrays, and captures stack (via
Error.captureStackTrace or super()) so downstream instanceof Error checks and
stack traces work.
In `@packages/loot-core/src/shared/rules.ts`:
- Around line 98-113: The FIELD_TYPES map uses a brittle double-cast ([field as
unknown as keyof FieldValueTypes])—replace that pattern by introducing a small
typedEntries helper and use it in the FIELD_TYPES initialization so the
key/value types are preserved without ad-hoc casts; update the export const
FIELD_TYPES to call typedEntries(FIELD_INFO).map(...) (referencing FIELD_TYPES,
FIELD_INFO, and FieldValueTypes) and ensure the helper signature localizes the
single, explicit assertion instead of scattering casts across the codebase.
ℹ️ Review info
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (27)
packages/desktop-client/src/components/ManageRules.tsxpackages/desktop-client/src/components/accounts/Account.tsxpackages/desktop-client/src/components/filters/FiltersMenu.tsxpackages/desktop-client/src/components/mobile/rules/MobileRuleEditPage.tsxpackages/desktop-client/src/components/mobile/rules/MobileRulesPage.tsxpackages/desktop-client/src/components/mobile/schedules/MobileScheduleEditPage.tsxpackages/desktop-client/src/components/mobile/transactions/TransactionEdit.tsxpackages/desktop-client/src/components/modals/ManageRulesModal.tsxpackages/desktop-client/src/components/modals/MergeUnusedPayeesModal.tsxpackages/desktop-client/src/components/rules/RuleEditor.tsxpackages/desktop-client/src/components/rules/ScheduleValue.tsxpackages/desktop-client/src/components/rules/Value.tsxpackages/desktop-client/src/components/schedules/DiscoverSchedules.tsxpackages/desktop-client/src/components/schedules/schedule-edit-utils.tspackages/desktop-client/src/components/transactions/TransactionList.tsxpackages/desktop-client/src/hooks/usePayeeRules.tspackages/desktop-client/src/hooks/usePreviewTransactions.tspackages/desktop-client/src/hooks/useRules.tspackages/desktop-client/src/rules/index.tspackages/desktop-client/src/rules/mutations.tspackages/desktop-client/src/rules/queries.tspackages/loot-core/src/server/api.tspackages/loot-core/src/server/rules/app.tspackages/loot-core/src/server/schedules/app.tspackages/loot-core/src/server/transactions/transaction-rules.tspackages/loot-core/src/shared/rules.tspackages/loot-core/src/types/models/rule.ts
💤 Files with no reviewable changes (1)
- packages/desktop-client/src/components/schedules/DiscoverSchedules.tsx
| const { mutate: deleteRule } = useDeleteRuleMutation(); | ||
|
|
||
| const handleRuleDelete = useCallback( | ||
| async (rule: RuleEntity) => { | ||
| try { | ||
| const { someDeletionsFailed } = await send('rule-delete-all', [ | ||
| rule.id, | ||
| ]); | ||
|
|
||
| if (someDeletionsFailed) { | ||
| dispatch( | ||
| addNotification({ | ||
| notification: { | ||
| type: 'warning', | ||
| message: t( | ||
| 'This rule could not be deleted because it is linked to a schedule.', | ||
| ), | ||
| }, | ||
| }), | ||
| ); | ||
| } else { | ||
| showUndoNotification({ | ||
| message: t('Rule deleted successfully'), | ||
| }); | ||
| } | ||
|
|
||
| // Refresh the rules list | ||
| await loadRules(); | ||
| } catch (error) { | ||
| console.error('Failed to delete rule:', error); | ||
| dispatch( | ||
| addNotification({ | ||
| notification: { | ||
| type: 'error', | ||
| message: t('Failed to delete rule. Please try again.'), | ||
| }, | ||
| }), | ||
| ); | ||
| } | ||
| deleteRule( | ||
| { id: rule.id }, | ||
| { | ||
| onSuccess: () => { | ||
| showUndoNotification({ | ||
| message: t('Rule deleted successfully'), | ||
| }); | ||
| // Refresh the rules list | ||
| void refetchRules(); | ||
| }, | ||
| }, | ||
| ); | ||
| }, | ||
| [dispatch, showUndoNotification, t, loadRules], | ||
| [dispatch, showUndoNotification, t, refetchRules], | ||
| ); |
There was a problem hiding this comment.
Include deleteRule in the callback deps.
handleRuleDelete now closes over deleteRule from the mutation hook, but it isn’t listed in the dependency array.
🔧 Suggested change
- [dispatch, showUndoNotification, t, refetchRules],
+ [deleteRule, dispatch, showUndoNotification, t, refetchRules],🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/desktop-client/src/components/mobile/rules/MobileRulesPage.tsx`
around lines 114 - 132, The handleRuleDelete useCallback closes over the
deleteRule function from useDeleteRuleMutation but does not include it in the
dependency array; update the dependency list for the useCallback that defines
handleRuleDelete to include deleteRule (in addition to dispatch,
showUndoNotification, t, refetchRules) so the callback updates if the mutation
hook returns a new function; locate the handleRuleDelete const and its
useCallback invocation and add deleteRule to the dependency array.
|
🤖 Auto-generated Release Notes Hey @joel-jeremy! I've automatically created a release notes file based on CodeRabbit's analysis: Category: Features If you're happy with this release note, you can add it to your pull request. If not, you'll need to add your own before a maintainer can review your change. |
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (6)
packages/desktop-client/src/components/mobile/rules/MobileRulesPage.tsx (1)
114-132:deleteRuleis now present in the dependency array.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/desktop-client/src/components/mobile/rules/MobileRulesPage.tsx` around lines 114 - 132, The dependency array for handleRuleDelete contains a duplicate entry for deleteRule; update the useCallback dependency array in MobileRulesPage.tsx (the handleRuleDelete definition that uses useDeleteRuleMutation, showUndoNotification, t, and refetchRules) to include each dependency only once — i.e., ensure [deleteRule, showUndoNotification, t, refetchRules] contains no duplicates and remove the extra deleteRule entry.packages/desktop-client/src/rules/mutations.ts (3)
28-31:⚠️ Potential issue | 🟠 MajorInvalidate all rule queries, not just lists.
Defaulting to
ruleQueries.lists()misses payee-specific caches. PreferruleQueries.all()to keep the whole rule surface fresh.🔧 Suggested change
function invalidateQueries(queryClient: QueryClient, queryKey?: QueryKey) { void queryClient.invalidateQueries({ - queryKey: queryKey ?? ruleQueries.lists(), + queryKey: queryKey ?? ruleQueries.all(), }); }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/desktop-client/src/rules/mutations.ts` around lines 28 - 31, The invalidateQueries function currently defaults to ruleQueries.lists(), which misses payee-specific caches; update the default queryKey to ruleQueries.all() so that invalidateQueries(queryClient: QueryClient, queryKey?: QueryKey) calls queryClient.invalidateQueries({ queryKey: queryKey ?? ruleQueries.all() }) ensuring the entire rule surface (not just lists) is invalidated.
362-365:⚠️ Potential issue | 🟡 MinorLocalize the auto-generated schedule name.
This string is user-facing and should be translated.
🌐 Suggested change
- const scheduleName = `Auto-created future transaction (${formattedDate}) - ${timestamp}`; + const scheduleName = t( + 'Auto-created future transaction ({{date}}) - {{timestamp}}', + { date: formattedDate, timestamp }, + );As per coding guidelines: Custom ESLint rule
actual/no-untranslated-stringsenforces i18n usage - add i18n translations for user-facing strings.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/desktop-client/src/rules/mutations.ts` around lines 362 - 365, The auto-generated user-facing string in mutations.ts (variables formattedDate, timestamp, scheduleName) must be localized: replace the hardcoded template `Auto-created future transaction (${formattedDate}) - ${timestamp}` with a call to the app's i18n translate function (e.g., t or i18n.t) using a translation key like "auto_created_future_transaction" and pass formattedDate and timestamp as interpolation variables; update usages of scheduleName accordingly and add the new key/placeholder to the locale files.
389-394:⚠️ Potential issue | 🟠 MajorAwait the rule update to avoid dropped rejections.
updateRuleis async; awaiting ensures completion and surfaces failures.✅ Suggested change
- updateRule({ + await updateRule({ rule: { ...rule, actions: [...linkScheduleActions, ...actions], }, });🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/desktop-client/src/rules/mutations.ts` around lines 389 - 394, The call to updateRule is currently not awaited which can drop rejections; change the invocation inside the mutation to await updateRule({ rule: { ...rule, actions: [...linkScheduleActions, ...actions] } }); and either return the awaited promise or wrap it in a try/catch and rethrow/log the error so failures are propagated (reference the updateRule function and the local variables rule, linkScheduleActions, actions to locate the call).packages/desktop-client/src/components/transactions/TransactionList.tsx (1)
253-281:⚠️ Potential issue | 🟠 MajorAwait the schedule-creation mutation before success/refetch.
mutateis fire-and-forget, soonConfirmcompletes before the schedule exists, and the refetch can run too early. Switch tomutateAsyncand await it.✅ Suggested fix
- const { mutate: createSingleTimeScheduleFromTransaction } = - useCreateSingleTimeScheduleFromTransaction(); + const { mutateAsync: createSingleTimeScheduleFromTransaction } = + useCreateSingleTimeScheduleFromTransaction(); @@ - createSingleTimeScheduleFromTransaction({ + await createSingleTimeScheduleFromTransaction({ transaction: transactionWithSubtransactions, }); @@ - createSingleTimeScheduleFromTransaction({ transaction }); + await createSingleTimeScheduleFromTransaction({ transaction });Also applies to: 339-347
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/desktop-client/src/components/transactions/TransactionList.tsx` around lines 253 - 281, The schedule-creation mutation is being fired without awaiting, causing onConfirm to finish (and refetch to run) before the schedule exists; change the destructured mutate from useCreateSingleTimeScheduleFromTransaction to mutateAsync (e.g., const { mutateAsync: createSingleTimeScheduleFromTransaction } = useCreateSingleTimeScheduleFromTransaction()) and then await createSingleTimeScheduleFromTransaction(...) inside the promptToConvertToSchedule onConfirm async callback(s) (the one building transactionWithSubtransactions and the similar occurrence around the other prompt in the file) so the function completes only after the schedule creation finishes.packages/desktop-client/src/components/ManageRules.tsx (1)
387-392:⚠️ Potential issue | 🟡 MinorUse
<Trans>for tooltip content.✅ Suggested change
- <Tooltip - isOpen={isNonDeletableRuleSelected} - content={t( - 'Some selected rules cannot be deleted because they are linked to schedules.', - )} - > + <Tooltip + isOpen={isNonDeletableRuleSelected} + content={ + <Trans> + Some selected rules cannot be deleted because they are + linked to schedules. + </Trans> + } + >As per coding guidelines: Use
Transcomponent instead oft()function when possible - all user-facing strings must be translated.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/desktop-client/src/components/ManageRules.tsx` around lines 387 - 392, Replace the inline t(...) string passed to Tooltip with a Trans component so the tooltip content uses JSX translation: in ManageRules.tsx locate the Tooltip where isNonDeletableRuleSelected is used and change the content prop from t('Some selected rules cannot be deleted because they are linked to schedules.') to a <Trans> element containing that sentence (import Trans from 'react-i18next' if not present); ensure the same translation key/text is available in your locales or update keys accordingly so the tooltip remains translated.
🧹 Nitpick comments (3)
packages/loot-core/src/server/schedules/app.ts (1)
6-22: Use inlinetypeimports for style consistency.These are type-only imports; prefer inline
typespecifiers in the import list.♻️ Suggested change
-import type { WithRequired } from 'loot-core/types/util'; +import { type WithRequired } from 'loot-core/types/util'; @@ -import type { RuleConditionEntity, ScheduleEntity } from '../../types/models'; +import { type RuleConditionEntity, type ScheduleEntity } from '../../types/models';As per coding guidelines: Use inline type imports:
import { type MyType } from '...'.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/loot-core/src/server/schedules/app.ts` around lines 6 - 22, The import list uses bare type imports; change them to inline type specifiers to follow style (e.g. import { type WithRequired } from 'loot-core/types/util' and import { type RuleConditionEntity, type ScheduleEntity } from '../../types/models'); update the top imports where WithRequired, RuleConditionEntity, and ScheduleEntity are referenced so each type is imported with the inline "type" keyword and leave non-type imports (captureBreadcrumb, connection, logger, currentDay, dayFromDate, parseDate, q, extractScheduleConds, getDateWithSkippedWeekend, getHasTransactionsQuery, getNextDate, getScheduledAmount, getStatus, recurConfigToRSchedule) unchanged.packages/desktop-client/src/rules/mutations.ts (2)
277-342: Replaceascasts withsatisfiesfor rule literals.This keeps the literals checked without unsafe assertions.
♻️ Example adjustment
- conditions.push({ - op: 'is', - field, - value, - } as RuleConditionEntity); + conditions.push({ + op: 'is', + field, + value, + } satisfies RuleConditionEntity); @@ - actions.push({ + actions.push({ op: 'set', field: 'notes', value: split.notes, options: { splitIndex }, - } as RuleActionEntity); + } satisfies RuleActionEntity);As per coding guidelines: Avoid type assertions (
as,!) - prefersatisfies.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/desktop-client/src/rules/mutations.ts` around lines 277 - 342, Replace the unsafe "as" casts for the literal objects with TypeScript "satisfies" checks so the literals are type-validated without asserting; update the initial arrays (conditions: RuleConditionEntity[] and actions: RuleActionEntity[]) and every object pushed into them (the date condition, the loop over conditionFields, and the action objects created inside the transaction.is_parent && transaction.subtransactions branch and its subtransaction handling) to use "satisfies RuleConditionEntity" or "satisfies RuleActionEntity" respectively instead of "as RuleConditionEntity"/"as RuleActionEntity", ensuring the shapes of the objects (fields like op, field, value, options, splitIndex, method) are verified by the compiler.
3-18: Prefer inlinetypeimports to match repo style.♻️ Suggested change
-import { useMutation, useQueryClient } from '@tanstack/react-query'; -import type { QueryClient, QueryKey } from '@tanstack/react-query'; +import { + useMutation, + useQueryClient, + type QueryClient, + type QueryKey, +} from '@tanstack/react-query'; @@ -import type { +import { + type NewRuleEntity, + type PayeeEntity, + type RuleActionEntity, + type RuleConditionEntity, + type RuleEntity, + type ScheduleEntity, + type TransactionEntity, +} from 'loot-core/types/models';As per coding guidelines: Use inline type imports:
import { type MyType } from '...'.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/desktop-client/src/rules/mutations.ts` around lines 3 - 18, Replace top-level `import type` usages with inline `type` imports to match repo style: change `import type { QueryClient, QueryKey } from '@tanstack/react-query';` to `import { type QueryClient, type QueryKey } from '@tanstack/react-query';` and change `import type { NewRuleEntity, PayeeEntity, RuleActionEntity, RuleConditionEntity, RuleEntity, ScheduleEntity, TransactionEntity } from 'loot-core/types/models';` to `import { type NewRuleEntity, type PayeeEntity, type RuleActionEntity, type RuleConditionEntity, type RuleEntity, type ScheduleEntity, type TransactionEntity } from 'loot-core/types/models';` so all type-only imports use the inline `type` specifier (refer to the import statements and the listed type names).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/desktop-client/src/components/mobile/rules/MobileRulesPage.tsx`:
- Around line 116-131: handleRuleDelete currently is marked async but never
awaits, and its per-call onSuccess redundantly calls refetchRules even though
useDeleteRuleMutation already invalidates queries; remove the async keyword from
handleRuleDelete and drop the void refetchRules() call inside the onSuccess
handler so the per-call onSuccess only calls showUndoNotification; keep
deleteRule invocation and leave global onSuccess/invalidation in
useDeleteRuleMutation to trigger the actual refetch.
- Line 28: Remove the unused Redux binding: delete the import of useDispatch and
the local assignment const dispatch = useDispatch() inside the MobileRulesPage
component since dispatch is never used after migrating to the mutation hook;
update the imports and component body to remove any references to
useDispatch/dispatch (search for useDispatch and dispatch in MobileRulesPage) so
there is no dead code.
---
Duplicate comments:
In `@packages/desktop-client/src/components/ManageRules.tsx`:
- Around line 387-392: Replace the inline t(...) string passed to Tooltip with a
Trans component so the tooltip content uses JSX translation: in ManageRules.tsx
locate the Tooltip where isNonDeletableRuleSelected is used and change the
content prop from t('Some selected rules cannot be deleted because they are
linked to schedules.') to a <Trans> element containing that sentence (import
Trans from 'react-i18next' if not present); ensure the same translation key/text
is available in your locales or update keys accordingly so the tooltip remains
translated.
In `@packages/desktop-client/src/components/mobile/rules/MobileRulesPage.tsx`:
- Around line 114-132: The dependency array for handleRuleDelete contains a
duplicate entry for deleteRule; update the useCallback dependency array in
MobileRulesPage.tsx (the handleRuleDelete definition that uses
useDeleteRuleMutation, showUndoNotification, t, and refetchRules) to include
each dependency only once — i.e., ensure [deleteRule, showUndoNotification, t,
refetchRules] contains no duplicates and remove the extra deleteRule entry.
In `@packages/desktop-client/src/components/transactions/TransactionList.tsx`:
- Around line 253-281: The schedule-creation mutation is being fired without
awaiting, causing onConfirm to finish (and refetch to run) before the schedule
exists; change the destructured mutate from
useCreateSingleTimeScheduleFromTransaction to mutateAsync (e.g., const {
mutateAsync: createSingleTimeScheduleFromTransaction } =
useCreateSingleTimeScheduleFromTransaction()) and then await
createSingleTimeScheduleFromTransaction(...) inside the
promptToConvertToSchedule onConfirm async callback(s) (the one building
transactionWithSubtransactions and the similar occurrence around the other
prompt in the file) so the function completes only after the schedule creation
finishes.
In `@packages/desktop-client/src/rules/mutations.ts`:
- Around line 28-31: The invalidateQueries function currently defaults to
ruleQueries.lists(), which misses payee-specific caches; update the default
queryKey to ruleQueries.all() so that invalidateQueries(queryClient:
QueryClient, queryKey?: QueryKey) calls queryClient.invalidateQueries({
queryKey: queryKey ?? ruleQueries.all() }) ensuring the entire rule surface (not
just lists) is invalidated.
- Around line 362-365: The auto-generated user-facing string in mutations.ts
(variables formattedDate, timestamp, scheduleName) must be localized: replace
the hardcoded template `Auto-created future transaction (${formattedDate}) -
${timestamp}` with a call to the app's i18n translate function (e.g., t or
i18n.t) using a translation key like "auto_created_future_transaction" and pass
formattedDate and timestamp as interpolation variables; update usages of
scheduleName accordingly and add the new key/placeholder to the locale files.
- Around line 389-394: The call to updateRule is currently not awaited which can
drop rejections; change the invocation inside the mutation to await updateRule({
rule: { ...rule, actions: [...linkScheduleActions, ...actions] } }); and either
return the awaited promise or wrap it in a try/catch and rethrow/log the error
so failures are propagated (reference the updateRule function and the local
variables rule, linkScheduleActions, actions to locate the call).
---
Nitpick comments:
In `@packages/desktop-client/src/rules/mutations.ts`:
- Around line 277-342: Replace the unsafe "as" casts for the literal objects
with TypeScript "satisfies" checks so the literals are type-validated without
asserting; update the initial arrays (conditions: RuleConditionEntity[] and
actions: RuleActionEntity[]) and every object pushed into them (the date
condition, the loop over conditionFields, and the action objects created inside
the transaction.is_parent && transaction.subtransactions branch and its
subtransaction handling) to use "satisfies RuleConditionEntity" or "satisfies
RuleActionEntity" respectively instead of "as RuleConditionEntity"/"as
RuleActionEntity", ensuring the shapes of the objects (fields like op, field,
value, options, splitIndex, method) are verified by the compiler.
- Around line 3-18: Replace top-level `import type` usages with inline `type`
imports to match repo style: change `import type { QueryClient, QueryKey } from
'@tanstack/react-query';` to `import { type QueryClient, type QueryKey } from
'@tanstack/react-query';` and change `import type { NewRuleEntity, PayeeEntity,
RuleActionEntity, RuleConditionEntity, RuleEntity, ScheduleEntity,
TransactionEntity } from 'loot-core/types/models';` to `import { type
NewRuleEntity, type PayeeEntity, type RuleActionEntity, type
RuleConditionEntity, type RuleEntity, type ScheduleEntity, type
TransactionEntity } from 'loot-core/types/models';` so all type-only imports use
the inline `type` specifier (refer to the import statements and the listed type
names).
In `@packages/loot-core/src/server/schedules/app.ts`:
- Around line 6-22: The import list uses bare type imports; change them to
inline type specifiers to follow style (e.g. import { type WithRequired } from
'loot-core/types/util' and import { type RuleConditionEntity, type
ScheduleEntity } from '../../types/models'); update the top imports where
WithRequired, RuleConditionEntity, and ScheduleEntity are referenced so each
type is imported with the inline "type" keyword and leave non-type imports
(captureBreadcrumb, connection, logger, currentDay, dayFromDate, parseDate, q,
extractScheduleConds, getDateWithSkippedWeekend, getHasTransactionsQuery,
getNextDate, getScheduledAmount, getStatus, recurConfigToRSchedule) unchanged.
ℹ️ Review info
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (10)
packages/desktop-client/src/components/ManageRules.tsxpackages/desktop-client/src/components/filters/FiltersMenu.tsxpackages/desktop-client/src/components/mobile/rules/MobileRulesPage.tsxpackages/desktop-client/src/components/mobile/transactions/TransactionEdit.tsxpackages/desktop-client/src/components/modals/MergeUnusedPayeesModal.tsxpackages/desktop-client/src/components/transactions/TransactionList.tsxpackages/desktop-client/src/hooks/usePreviewTransactions.tspackages/desktop-client/src/rules/mutations.tspackages/loot-core/src/server/schedules/app.tsupcoming-release-notes/7070.md
🚧 Files skipped from review as they are similar to previous changes (2)
- packages/desktop-client/src/hooks/usePreviewTransactions.ts
- packages/desktop-client/src/components/modals/MergeUnusedPayeesModal.tsx
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (1)
packages/desktop-client/src/components/mobile/rules/MobileRulesPage.tsx (1)
114-129: Remove redundant refetch + unnecessaryasyncin the delete handler.
useDeleteRuleMutationalready invalidates rule queries, so the per-callrefetchRules()duplicates work. Also, the handler doesn’tawaitanything.♻️ Suggested change
- const handleRuleDelete = useCallback( - async (rule: RuleEntity) => { + const handleRuleDelete = useCallback( + (rule: RuleEntity) => { deleteRule( { id: rule.id }, { onSuccess: () => { showUndoNotification({ message: t('Rule deleted successfully'), }); - // Refresh the rules list - void refetchRules(); }, }, ); }, - [deleteRule, showUndoNotification, t, refetchRules], + [deleteRule, showUndoNotification, t], );🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/desktop-client/src/components/mobile/rules/MobileRulesPage.tsx` around lines 114 - 129, The handleRuleDelete function is marked async and manually calls refetchRules despite useDeleteRuleMutation already invalidating queries; remove the unnecessary async keyword, remove the explicit refetchRules() call inside handleRuleDelete, and update the dependency array for the useCallback (remove refetchRules) to avoid stale lint warnings; keep deleteRule, showUndoNotification, and t in the dependency list so handleRuleDelete remains stable.
🧹 Nitpick comments (4)
packages/desktop-client/src/components/rules/RuleEditor.tsx (2)
966-967: Usefunctionfor the pure helper.♻️ Suggested adjustment
-const getUnparsedActions = splits => getActions(splits).map(unparseActions); +function getUnparsedActions(splits) { + return getActions(splits).map(unparseActions); +}As per coding guidelines: Use the
functionkeyword for pure functions - prefer functional and declarative programming patterns.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/desktop-client/src/components/rules/RuleEditor.tsx` around lines 966 - 967, The two helpers getActions and getUnparsedActions are defined as arrow functions but must be pure helpers declared with the function keyword; replace the arrow definitions of getActions and getUnparsedActions with function declarations (keeping the same parameter name splits and behavior that uses unparseActions and .flatMap) so callers and hoisting behave consistently.
1026-1027: Avoid theasassertion for the initial split element.You can model the initial element with a concrete type (or
satisfies) and avoid the assertion.♻️ Suggested adjustment
- [{ id: uuid(), actions: [] } as (typeof actionSplits)[0]], + [ + ({ id: uuid(), actions: [] } satisfies { + id: string; + actions: Array<RuleActionEntity & { inputKey: string }>; + }), + ],As per coding guidelines: Avoid type assertions (
as,!) - prefersatisfies.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/desktop-client/src/components/rules/RuleEditor.tsx` around lines 1026 - 1027, The initial pre-split element currently uses a type assertion ("as") which should be removed; instead construct the initial element with an explicit shape or use TypeScript's "satisfies" to ensure it matches the actionSplits item type. Locate the array literal that creates [{ id: uuid(), actions: [] } as (typeof actionSplits)[0]] and replace the assertion by either declaring the element with the concrete interface/type used by actionSplits or append "satisfies (typeof actionSplits)[0]" so the value is type-checked without an "as" cast (keeping uuid() and actions:[] intact). Ensure imports/types required for the concrete type are available and adjust the expression accordingly.packages/desktop-client/src/components/ManageRules.tsx (2)
217-244: Avoid redundant refetches after delete mutations.Both delete mutations already invalidate rule queries; the extra
refetchRules()triggers a second fetch. Dropping it keeps UX the same while reducing duplicate work.♻️ Suggested change
batchDeleteRules( { ids: [...selectedInst.items], }, { onSuccess: () => { - void refetchRules(); selectedInst.dispatch({ type: 'select-none' }); }, }, ); }; function onDeleteRule(id: string) { - deleteRule( - { id }, - { - onSuccess: () => { - void refetchRules(); - }, - }, - ); + deleteRule({ id }); }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/desktop-client/src/components/ManageRules.tsx` around lines 217 - 244, The onDeleteSelected and onDeleteRule handlers call refetchRules() inside their onSuccess callbacks even though batchDeleteRules and deleteRule mutations already invalidate the rules queries; remove the explicit void refetchRules() calls from onSuccess in both onDeleteSelected (where batchDeleteRules is called) and onDeleteRule (where deleteRule is called) so the query invalidation handles refetching and avoids duplicate fetches, retaining the selectedInst.dispatch call in onDeleteSelected and keeping onSuccess otherwise unchanged.
129-153: Gate payee-rule fetching/loading whenpayeeIdis null.
usePayeeRulesstill runs for the all-rules view, and its loading flags are folded intoisLoading. That can trigger an unnecessary request and spinner even when onlyuseRulesis relevant. Consider disabling the payee query whenpayeeIdis falsy, or at least excluding its loading flags in that case.♻️ Suggested adjustment
- const isLoading = - isAllRulesLoading || - isAllRulesRefetching || - isPayeeRulesLoading || - isPayeeRulesRefetching; + const isLoading = payeeId + ? isPayeeRulesLoading || isPayeeRulesRefetching + : isAllRulesLoading || isAllRulesRefetching;🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/desktop-client/src/components/ManageRules.tsx` around lines 129 - 153, The payee-specific query is running even when payeeId is null which causes unnecessary requests and makes isLoading reflect payee flags; update the usePayeeRules call to disable the query when payeeId is falsy (e.g., pass an enabled: !!payeeId option) and/or change the isLoading computation to only include isPayeeRulesLoading and isPayeeRulesRefetching when payeeId is truthy; adjust refetchRules to keep the existing ternary (refetchPayeeRules vs refetchAllRules) so behavior stays correct.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/desktop-client/src/components/rules/RuleEditor.tsx`:
- Around line 1018-1021: The guard for reading splitIndex is unsafe because
"'splitIndex' in action.options" will throw if action.options is undefined;
update the computation of splitIndex in RuleEditor.tsx to use a safe optional
check such as using optional chaining or a fallback object (e.g. compute
splitIndex from action.options?.splitIndex ?? 0 or use "'splitIndex' in
(action.options ?? {})" before accessing), referencing the splitIndex variable
and the action object so the code never accesses action.options when it's
undefined.
In `@packages/desktop-client/src/rules/queries.ts`:
- Around line 6-30: Change ruleQueries' properties (all, lists, list, listPayee)
from arrow functions to method syntax and remove the "as const" assertions:
implement them as methods on the ruleQueries object (e.g., all() { ... },
lists() { ... }) and replace any "as const" queryKey/trailing assertions with a
TypeScript "satisfies" constraint on the ruleQueries object so the returned
queryKey tuples are strongly typed without type assertions; keep the same
queryOptions usage for list and listPayee (including queryFn, staleTime,
enabled) and retain the payeeId runtime guard in listPayee but avoid
non-null/assertion operators. Ensure you reference and update ruleQueries.all,
ruleQueries.lists, ruleQueries.list, and ruleQueries.listPayee when applying
these changes.
---
Duplicate comments:
In `@packages/desktop-client/src/components/mobile/rules/MobileRulesPage.tsx`:
- Around line 114-129: The handleRuleDelete function is marked async and
manually calls refetchRules despite useDeleteRuleMutation already invalidating
queries; remove the unnecessary async keyword, remove the explicit
refetchRules() call inside handleRuleDelete, and update the dependency array for
the useCallback (remove refetchRules) to avoid stale lint warnings; keep
deleteRule, showUndoNotification, and t in the dependency list so
handleRuleDelete remains stable.
---
Nitpick comments:
In `@packages/desktop-client/src/components/ManageRules.tsx`:
- Around line 217-244: The onDeleteSelected and onDeleteRule handlers call
refetchRules() inside their onSuccess callbacks even though batchDeleteRules and
deleteRule mutations already invalidate the rules queries; remove the explicit
void refetchRules() calls from onSuccess in both onDeleteSelected (where
batchDeleteRules is called) and onDeleteRule (where deleteRule is called) so the
query invalidation handles refetching and avoids duplicate fetches, retaining
the selectedInst.dispatch call in onDeleteSelected and keeping onSuccess
otherwise unchanged.
- Around line 129-153: The payee-specific query is running even when payeeId is
null which causes unnecessary requests and makes isLoading reflect payee flags;
update the usePayeeRules call to disable the query when payeeId is falsy (e.g.,
pass an enabled: !!payeeId option) and/or change the isLoading computation to
only include isPayeeRulesLoading and isPayeeRulesRefetching when payeeId is
truthy; adjust refetchRules to keep the existing ternary (refetchPayeeRules vs
refetchAllRules) so behavior stays correct.
In `@packages/desktop-client/src/components/rules/RuleEditor.tsx`:
- Around line 966-967: The two helpers getActions and getUnparsedActions are
defined as arrow functions but must be pure helpers declared with the function
keyword; replace the arrow definitions of getActions and getUnparsedActions with
function declarations (keeping the same parameter name splits and behavior that
uses unparseActions and .flatMap) so callers and hoisting behave consistently.
- Around line 1026-1027: The initial pre-split element currently uses a type
assertion ("as") which should be removed; instead construct the initial element
with an explicit shape or use TypeScript's "satisfies" to ensure it matches the
actionSplits item type. Locate the array literal that creates [{ id: uuid(),
actions: [] } as (typeof actionSplits)[0]] and replace the assertion by either
declaring the element with the concrete interface/type used by actionSplits or
append "satisfies (typeof actionSplits)[0]" so the value is type-checked without
an "as" cast (keeping uuid() and actions:[] intact). Ensure imports/types
required for the concrete type are available and adjust the expression
accordingly.
ℹ️ Review info
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (7)
packages/desktop-client/src/components/ManageRules.tsxpackages/desktop-client/src/components/filters/FiltersMenu.tsxpackages/desktop-client/src/components/mobile/rules/MobileRulesPage.tsxpackages/desktop-client/src/components/rules/RuleEditor.tsxpackages/desktop-client/src/components/transactions/TransactionList.tsxpackages/desktop-client/src/rules/mutations.tspackages/desktop-client/src/rules/queries.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/desktop-client/src/rules/mutations.ts
✅ Deploy Preview for actualbudget-website ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
There was a problem hiding this comment.
Actionable comments posted: 3
♻️ Duplicate comments (1)
packages/desktop-client/src/components/mobile/rules/MobileRulesPage.tsx (1)
115-130:⚠️ Potential issue | 🟠 MajorHandle non-deleted results explicitly and drop the extra refetch.
At Line 119,
onSuccessalways shows a success message, but the server delete path can returnfalse(rule not deleted, e.g. linked schedule). Also, Line 124 triggers an extra fetch even thoughuseDeleteRuleMutationalready invalidates queries globally.🔧 Proposed fix
const handleRuleDelete = useCallback( (rule: RuleEntity) => { deleteRule( { id: rule.id }, { - onSuccess: () => { - showUndoNotification({ - message: t('Rule deleted successfully'), - }); - // Refresh the rules list - void refetchRules(); + onSuccess: wasDeleted => { + if (!wasDeleted) { + return; + } + showUndoNotification({ + message: t('Rule deleted successfully'), + }); }, }, ); }, - [deleteRule, showUndoNotification, t, refetchRules], + [deleteRule, showUndoNotification, t], );🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/desktop-client/src/components/mobile/rules/MobileRulesPage.tsx` around lines 115 - 130, The onSuccess handler for deleteRule should check the mutation result and only show the success/undo notification if the server actually deleted the rule, and you should remove the redundant explicit refetchRules call because useDeleteRuleMutation already invalidates queries; update the anonymous callback passed to deleteRule (the onSuccess in the deleteRule call) to inspect the response (e.g., a boolean or { deleted } result returned by the mutation) and conditionally call showUndoNotification, and then delete the void refetchRules() invocation from that handler.
🧹 Nitpick comments (1)
packages/desktop-client/src/components/rules/RuleEditor.tsx (1)
1025-1025: Replace theasassertion with asatisfies-based initializerLine 1025 uses
as (typeof actionSplits)[0], which is brittle and violates the repo TS rule.Proposed refactor
- const [actionSplits, setActionSplits] = useState< - Array<{ - id: string; - actions: Array<RuleActionEntity & { inputKey: string }>; - }> - >(() => { + type ActionSplit = { + id: string; + actions: Array<RuleActionEntity & { inputKey: string }>; + }; + const [actionSplits, setActionSplits] = useState<ActionSplit[]>(() => { @@ - [{ id: uuid(), actions: [] } as (typeof actionSplits)[0]], + [{ id: uuid(), actions: [] } satisfies ActionSplit], ); });As per coding guidelines, "Use
satisfiesinstead of type assertions (as,!) in TypeScript".🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/desktop-client/src/components/rules/RuleEditor.tsx` at line 1025, Replace the brittle type assertion on the array initializer by using TypeScript's satisfies with the action template: construct the object literal { id: uuid(), actions: [] } and apply "satisfies (typeof actionSplits)[0]" to that literal (e.g., wrap the single-item array element with satisfies) instead of using "as (typeof actionSplits)[0]"; keep the surrounding array and ensure you reference the existing actionSplits identifier and uuid() call so the shape is validated without an assertion.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/desktop-client/src/components/rules/RuleEditor.tsx`:
- Around line 1264-1267: In RuleEditor update the call to originalOnSave so the
server-returned id wins: when invoking originalOnSave (the block using
originalOnSave?.({...})) change the object spread order so you spread the
existing rule first and then set id (use {...rule, id}) instead of {id,
...rule}, ensuring the mutation result stored in the id variable cannot be
overwritten by rule.id.
- Around line 1240-1242: The onSuccess callback for applyRuleActions currently
closes over actionSplits and calls setActionSplits([...actionSplits]), risking a
stale update; change this to use the functional updater form (e.g.,
setActionSplits(prev => [...prev])) so the latest state is used when
applyRuleActions resolves, referencing the existing setActionSplits,
actionSplits, and the onSuccess handler around applyRuleActions.
- Around line 1269-1275: The onError callback in RuleEditor uses the 'in'
operator on the unknown error parameter (lines around onError) which can throw
if error is null or a primitive; add a defensive narrow (e.g., check error !==
null && typeof error === 'object') before any 'in' checks, then safely access
error.conditionErrors and error.actionErrors to call
setConditions(applyErrors(...)) and the action error handling (usedErrorIdx
logic); ensure you narrow once at the start of the onError handler so subsequent
references to conditionErrors/actionErrors are type-safe.
---
Duplicate comments:
In `@packages/desktop-client/src/components/mobile/rules/MobileRulesPage.tsx`:
- Around line 115-130: The onSuccess handler for deleteRule should check the
mutation result and only show the success/undo notification if the server
actually deleted the rule, and you should remove the redundant explicit
refetchRules call because useDeleteRuleMutation already invalidates queries;
update the anonymous callback passed to deleteRule (the onSuccess in the
deleteRule call) to inspect the response (e.g., a boolean or { deleted } result
returned by the mutation) and conditionally call showUndoNotification, and then
delete the void refetchRules() invocation from that handler.
---
Nitpick comments:
In `@packages/desktop-client/src/components/rules/RuleEditor.tsx`:
- Line 1025: Replace the brittle type assertion on the array initializer by
using TypeScript's satisfies with the action template: construct the object
literal { id: uuid(), actions: [] } and apply "satisfies (typeof
actionSplits)[0]" to that literal (e.g., wrap the single-item array element with
satisfies) instead of using "as (typeof actionSplits)[0]"; keep the surrounding
array and ensure you reference the existing actionSplits identifier and uuid()
call so the shape is validated without an assertion.
ℹ️ Review info
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
packages/desktop-client/src/components/mobile/rules/MobileRulesPage.tsxpackages/desktop-client/src/components/rules/RuleEditor.tsx
| onSuccess: () => { | ||
| setActionSplits([...actionSplits]); | ||
| }, |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
fd "RuleEditor.tsx" packages/desktop-clientRepository: actualbudget/actual
Length of output: 122
🏁 Script executed:
cat -n packages/desktop-client/src/components/rules/RuleEditor.tsx | sed -n '1230,1255p'Repository: actualbudget/actual
Length of output: 915
🏁 Script executed:
cat -n packages/desktop-client/src/components/rules/RuleEditor.tsx | sed -n '1,100p'Repository: actualbudget/actual
Length of output: 4216
🏁 Script executed:
cat -n packages/desktop-client/src/components/rules/RuleEditor.tsx | sed -n '100,300p'Repository: actualbudget/actual
Length of output: 5678
🏁 Script executed:
cat -n packages/desktop-client/src/components/rules/RuleEditor.tsx | sed -n '700,900p'Repository: actualbudget/actual
Length of output: 7156
🏁 Script executed:
cat -n packages/desktop-client/src/components/rules/RuleEditor.tsx | sed -n '1050,1150p'Repository: actualbudget/actual
Length of output: 4235
🏁 Script executed:
cat -n packages/desktop-client/src/components/rules/RuleEditor.tsx | sed -n '1000,1050p'Repository: actualbudget/actual
Length of output: 2044
🏁 Script executed:
cat -n packages/desktop-client/src/components/rules/RuleEditor.tsx | sed -n '1230,1280p'Repository: actualbudget/actual
Length of output: 1737
🏁 Script executed:
rg "useApplyRuleActionsMutation" packages/desktop-client/src/components/rules/RuleEditor.tsx -A 10Repository: actualbudget/actual
Length of output: 734
🏁 Script executed:
fd "rules.ts" packages/desktop-client/src -type f | head -20Repository: actualbudget/actual
Length of output: 233
🏁 Script executed:
fd "rules\\.ts" packages/desktop-client/srcRepository: actualbudget/actual
Length of output: 214
🏁 Script executed:
rg "useApplyRuleActionsMutation" packages/desktop-client/src --type ts --type tsx -lRepository: actualbudget/actual
Length of output: 90
🏁 Script executed:
rg "useApplyRuleActionsMutation" packages/desktop-client/src -lRepository: actualbudget/actual
Length of output: 169
🏁 Script executed:
cat -n packages/desktop-client/src/rules/mutations.tsRepository: actualbudget/actual
Length of output: 14005
🏁 Script executed:
cat -n packages/desktop-client/src/components/rules/RuleEditor.tsx | sed -n '1190,1230p'Repository: actualbudget/actual
Length of output: 1439
🏁 Script executed:
cat -n packages/desktop-client/src/components/rules/RuleEditor.tsx | sed -n '1115,1165p'Repository: actualbudget/actual
Length of output: 2281
Use state setter function to avoid stale closure in onSuccess
Line 1241 captures actionSplits in the callback closure. If edits occur while applyRuleActions is in flight, the success callback will restore the stale captured state instead of the current state. Other state updates in this file correctly use functional updates (lines 1193–1225), which should be applied here as well.
Safe state update
- onSuccess: () => {
- setActionSplits([...actionSplits]);
- },
+ onSuccess: () => {
+ setActionSplits(current => [...current]);
+ },📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| onSuccess: () => { | |
| setActionSplits([...actionSplits]); | |
| }, | |
| onSuccess: () => { | |
| setActionSplits(current => [...current]); | |
| }, |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/desktop-client/src/components/rules/RuleEditor.tsx` around lines
1240 - 1242, The onSuccess callback for applyRuleActions currently closes over
actionSplits and calls setActionSplits([...actionSplits]), risking a stale
update; change this to use the functional updater form (e.g.,
setActionSplits(prev => [...prev])) so the latest state is used when
applyRuleActions resolves, referencing the existing setActionSplits,
actionSplits, and the onSuccess handler around applyRuleActions.
✅ Deploy Preview for actualbudget-storybook ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/desktop-client/src/hooks/usePreviewTransactions.ts (1)
67-87:⚠️ Potential issue | 🟠 MajorUse a non-invalidating path for preview rule execution.
Line 67 wires preview generation to
useRunRulesMutation, and lines 82–86 call it once per preview transaction. The mutation invalidates the rule queries cache on each success (viaonSuccessinpackages/desktop-client/src/rules/mutations.ts), which is unnecessary overhead for a read-only preview flow. Consider callingsend('rules-run', ...)directly or using a mutation without the invalidation side effect.Additionally, the dependency array at lines 119–125 includes
schedulesandupcomingLength, which are not used in the effect body itself—only in theuseMemoabove that computesscheduleTransactions. Remove these redundant dependencies to avoid unnecessary effect reruns.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/desktop-client/src/hooks/usePreviewTransactions.ts` around lines 67 - 87, The preview effect is calling the invalidating mutation via useRunRulesMutation (mutateAsync aliased as runRulesAsync) for each scheduleTransaction, causing unnecessary cache invalidations; change the effect in usePreviewTransactions to invoke the read-only preview path (e.g., dispatch send('rules-run', { transaction }) or create/use a non-invalidating mutation specifically for previews) instead of calling runRulesAsync, and keep all other logic (isUnmounted, setIsLoading, setPreviewTransactions) unchanged. Also remove the unused dependencies (schedules and upcomingLength) from the effect's dependency array—leave only values that the effect actually reads (such as scheduleTransactions and run/send function references) so the effect doesn't rerun unnecessarily.
🧹 Nitpick comments (3)
packages/loot-core/src/server/schedules/app.ts (1)
275-281: Prefer immutable normalization forschedule.name.Current behavior is fine, but mutating
schedulein-place is avoidable here.♻️ Suggested refactor
- if (schedule.name) { - if (await checkIfScheduleExists(schedule.name, scheduleId)) { + const normalizedSchedule = { + ...schedule, + name: schedule.name || null, + }; + + if (normalizedSchedule.name) { + if (await checkIfScheduleExists(normalizedSchedule.name, scheduleId)) { throw new Error('Cannot create schedules with the same name'); } - } else { - schedule.name = null; } @@ await db.insertWithSchema('schedules', { - ...schedule, + ...normalizedSchedule, id: scheduleId, rule: ruleId, });🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/loot-core/src/server/schedules/app.ts` around lines 275 - 281, Avoid mutating schedule in-place: instead of assigning schedule.name = null, compute a normalizedName (e.g., const normalizedName = schedule.name ?? null), use normalizedName when calling checkIfScheduleExists(schedule.name, scheduleId) (or pass normalizedName) and when constructing any new schedule payload or DB upsert, and leave the original schedule object untouched; update references in this block to use normalizedName and keep the rest of the flow (including throwing via throw new Error('Cannot create schedules with the same name')) unchanged.packages/desktop-client/src/hooks/usePreviewTransactions.ts (1)
119-124: Trim redundant effect dependencies.Line 121 (
schedules) and Line 123 (upcomingLength) are not read inside the effect body;scheduleTransactionsalready captures them. Keeping only values used by the effect will reduce extra reruns.Suggested diff
}, [ scheduleTransactions, - schedules, statuses, - upcomingLength, runRulesAsync, ]);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/desktop-client/src/hooks/usePreviewTransactions.ts` around lines 119 - 124, The effect in usePreviewTransactions has redundant dependencies—remove schedules and upcomingLength from the dependency array because scheduleTransactions already captures those values; update the dependencies to only include the values actually referenced inside the effect (e.g., scheduleTransactions, statuses, runRulesAsync) and ensure scheduleTransactions is a stable reference (useCallback) if it isn't already so the effect behavior remains correct.packages/desktop-client/src/components/mobile/transactions/TransactionEdit.tsx (1)
692-693: PrefermutateAsync+awaitin this confirm flow.Line 753 uses fire-and-forget
mutateinside anasynconConfirmhandler that already awaits deletion (line 736). UsingmutateAsynchere keeps the delete → create operation fully sequential and ensures the entire operation completes before the handler returns.Suggested diff
- const { mutate: createSingleTimeScheduleFromTransaction } = + const { mutateAsync: createSingleTimeScheduleFromTransaction } = useCreateSingleTimeScheduleFromTransaction(); ... - createSingleTimeScheduleFromTransaction( - { - transaction: transactionForSchedule, - }, - { - onSuccess: () => { - dispatch( - addNotification({ - notification: { - type: 'message', - message: t('Schedule created successfully'), - }, - }), - ); - void navigate(-1); - }, - }, - ); + await createSingleTimeScheduleFromTransaction({ + transaction: transactionForSchedule, + }); + dispatch( + addNotification({ + notification: { + type: 'message', + message: t('Schedule created successfully'), + }, + }), + ); + void navigate(-1);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/desktop-client/src/components/mobile/transactions/TransactionEdit.tsx` around lines 692 - 693, The confirm flow currently calls createSingleTimeScheduleFromTransaction.mutate in a fire-and-forget way; update the onConfirm async handler to call and await createSingleTimeScheduleFromTransaction.mutateAsync so the sequence is delete (already awaited) → create is fully sequential and the handler only returns after creation completes; adjust any surrounding try/catch or error handling in the onConfirm handler to handle errors from mutateAsync appropriately.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Outside diff comments:
In `@packages/desktop-client/src/hooks/usePreviewTransactions.ts`:
- Around line 67-87: The preview effect is calling the invalidating mutation via
useRunRulesMutation (mutateAsync aliased as runRulesAsync) for each
scheduleTransaction, causing unnecessary cache invalidations; change the effect
in usePreviewTransactions to invoke the read-only preview path (e.g., dispatch
send('rules-run', { transaction }) or create/use a non-invalidating mutation
specifically for previews) instead of calling runRulesAsync, and keep all other
logic (isUnmounted, setIsLoading, setPreviewTransactions) unchanged. Also remove
the unused dependencies (schedules and upcomingLength) from the effect's
dependency array—leave only values that the effect actually reads (such as
scheduleTransactions and run/send function references) so the effect doesn't
rerun unnecessarily.
---
Nitpick comments:
In
`@packages/desktop-client/src/components/mobile/transactions/TransactionEdit.tsx`:
- Around line 692-693: The confirm flow currently calls
createSingleTimeScheduleFromTransaction.mutate in a fire-and-forget way; update
the onConfirm async handler to call and await
createSingleTimeScheduleFromTransaction.mutateAsync so the sequence is delete
(already awaited) → create is fully sequential and the handler only returns
after creation completes; adjust any surrounding try/catch or error handling in
the onConfirm handler to handle errors from mutateAsync appropriately.
In `@packages/desktop-client/src/hooks/usePreviewTransactions.ts`:
- Around line 119-124: The effect in usePreviewTransactions has redundant
dependencies—remove schedules and upcomingLength from the dependency array
because scheduleTransactions already captures those values; update the
dependencies to only include the values actually referenced inside the effect
(e.g., scheduleTransactions, statuses, runRulesAsync) and ensure
scheduleTransactions is a stable reference (useCallback) if it isn't already so
the effect behavior remains correct.
In `@packages/loot-core/src/server/schedules/app.ts`:
- Around line 275-281: Avoid mutating schedule in-place: instead of assigning
schedule.name = null, compute a normalizedName (e.g., const normalizedName =
schedule.name ?? null), use normalizedName when calling
checkIfScheduleExists(schedule.name, scheduleId) (or pass normalizedName) and
when constructing any new schedule payload or DB upsert, and leave the original
schedule object untouched; update references in this block to use normalizedName
and keep the rest of the flow (including throwing via throw new Error('Cannot
create schedules with the same name')) unchanged.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 12c8bedc-e0c3-4960-ba44-affd29d4eaf7
📒 Files selected for processing (8)
packages/desktop-client/src/components/filters/FiltersMenu.tsxpackages/desktop-client/src/components/mobile/transactions/TransactionEdit.tsxpackages/desktop-client/src/components/modals/ManageRulesModal.tsxpackages/desktop-client/src/components/modals/MergeUnusedPayeesModal.tsxpackages/desktop-client/src/components/schedules/DiscoverSchedules.tsxpackages/desktop-client/src/hooks/usePreviewTransactions.tspackages/loot-core/src/server/api.tspackages/loot-core/src/server/schedules/app.ts
💤 Files with no reviewable changes (1)
- packages/desktop-client/src/components/schedules/DiscoverSchedules.tsx
🚧 Files skipped from review as they are similar to previous changes (2)
- packages/desktop-client/src/components/modals/ManageRulesModal.tsx
- packages/loot-core/src/server/api.ts
|
@joel-jeremy one more conflict by the look of it. I've done a review and all looks good, so feel free to ping me when you've resolved and I'll stamp it |
There was a problem hiding this comment.
Actionable comments posted: 4
♻️ Duplicate comments (2)
packages/desktop-client/src/components/rules/RuleEditor.tsx (2)
1240-1242:⚠️ Potential issue | 🟡 MinorUse functional state update to avoid stale closure.
The
onSuccesscallback capturesactionSplitsin its closure. If the user makes edits whileapplyRuleActionsis in flight, the callback will restore the stale captured state instead of the current state.Proposed fix
onSuccess: () => { - setActionSplits([...actionSplits]); + setActionSplits(current => [...current]); },🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/desktop-client/src/components/rules/RuleEditor.tsx` around lines 1240 - 1242, The onSuccess callback for applyRuleActions captures actionSplits in its closure and can restore stale state; change the updater to use a functional state update so it reads the latest value at call time (i.e., in onSuccess call setActionSplits with an updater that accepts prev and returns a new array based on prev). Update the onSuccess handler where applyRuleActions is used so it references setActionSplits(prev => [...prev]) (or an equivalent functional updater) instead of setActionSplits([...actionSplits]).
1266-1282:⚠️ Potential issue | 🟠 MajorGuard error shape before using
'in'checks and use functional state update.Two issues in the
onErrorhandler:
Type safety: The
errorparameter isunknown. Using'in'operator onnull,undefined, or primitives throws a TypeError. Add a defensive guard at the start.Stale closure: Line 1274 uses
actionSplitsfrom the closure. If edits occur while the mutation is in flight, the error handler will operate on stale state.Proposed fix
onError: error => { + if (typeof error !== 'object' || error == null) { + return; + } + if ('conditionErrors' in error && error.conditionErrors) { setConditions(applyErrors(conditions, error.conditionErrors)); } if ('actionErrors' in error && error.actionErrors) { let usedErrorIdx = 0; - setActionSplits( - actionSplits.map(item => ({ + setActionSplits(currentSplits => + currentSplits.map(item => ({ ...item, actions: item.actions.map(action => ({ ...action, error: error.actionErrors[usedErrorIdx++] ?? null, })), })), ); } },🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/desktop-client/src/components/rules/RuleEditor.tsx` around lines 1266 - 1282, The onError handler must first guard the unknown error shape (e.g., if (!error || typeof error !== 'object')) before using 'in' so 'conditionErrors'/'actionErrors' checks are safe, and should use functional state updates to avoid stale closures: call setConditions(prev => applyErrors(prev, (error as any).conditionErrors)) only after verifying Array.isArray((error as any).conditionErrors), and replace the setActionSplits(actionSplits.map(...)) with setActionSplits(prev => { let usedErrorIdx = 0; return prev.map(item => ({ ...item, actions: item.actions.map(action => ({ ...action, error: ((error as any).actionErrors && Array.isArray((error as any).actionErrors)) ? ((error as any).actionErrors[usedErrorIdx++] ?? null) : null })) })); }) so you operate on the latest state and only index into actionErrors after confirming its array shape.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/desktop-client/src/components/accounts/Account.tsx`:
- Around line 695-697: The current code calls this.props.onRunRules(transaction)
inside a for loop which triggers useRunRulesMutation().mutateAsync's onSuccess
invalidation for each transaction; change it to batch or defer invalidation by
collecting transactions into an array and calling onRunRules once with the full
array (or add a new batched entrypoint), or call mutateAsync for each but pass
an options object that suppresses per-call invalidation and then perform a
single query invalidation/refetch after the loop; update references to
onRunRules and the useRunRulesMutation().mutateAsync call sites accordingly so
invalidation happens once after all transactions are processed.
In `@packages/desktop-client/src/components/mobile/rules/MobileRulesPage.tsx`:
- Around line 114-128: The useCallback for handleRuleDelete includes an unused
refetchRules in its dependency array; update the dependency array for the
handleRuleDelete declaration to remove refetchRules so it only depends on
deleteRule, showUndoNotification and t (i.e., ensure handleRuleDelete's
dependency array matches the actual references inside the callback that call
deleteRule and showUndoNotification).
In
`@packages/desktop-client/src/components/mobile/transactions/TransactionEdit.tsx`:
- Around line 753-770: The modal is closed (state.close()) before the async
onConfirm handler finishes, causing a race with
createSingleTimeScheduleFromTransaction; to fix, make the confirm flow await the
schedule creation: either change createSingleTimeScheduleFromTransaction usage
to call its mutateAsync variant and await it inside the async onConfirm (so the
onSuccess logic and navigate(-1) run deterministically) or make the button
handler async and await onConfirm() before calling state.close(); update
ConvertToScheduleModal's onConfirm/state.close usage and similarly adjust
DiscoverSchedules if present to ensure state.close() happens only after the
awaited mutation completes.
In `@packages/desktop-client/src/components/rules/Value.tsx`:
- Around line 92-125: The switch case blocks for 'payee', 'category',
'category_group', 'account', and 'rule' declare consts (payee, category,
categoryGroup, account) that can leak scope; wrap the body of each of those case
labels in a block (e.g., case 'payee': { ... break; }) so the const declarations
are block-scoped and do not collide across cases, ensuring each case returns as
before and includes the existing valueIsRaw checks and describe/t('(deleted)')
handling.
---
Duplicate comments:
In `@packages/desktop-client/src/components/rules/RuleEditor.tsx`:
- Around line 1240-1242: The onSuccess callback for applyRuleActions captures
actionSplits in its closure and can restore stale state; change the updater to
use a functional state update so it reads the latest value at call time (i.e.,
in onSuccess call setActionSplits with an updater that accepts prev and returns
a new array based on prev). Update the onSuccess handler where applyRuleActions
is used so it references setActionSplits(prev => [...prev]) (or an equivalent
functional updater) instead of setActionSplits([...actionSplits]).
- Around line 1266-1282: The onError handler must first guard the unknown error
shape (e.g., if (!error || typeof error !== 'object')) before using 'in' so
'conditionErrors'/'actionErrors' checks are safe, and should use functional
state updates to avoid stale closures: call setConditions(prev =>
applyErrors(prev, (error as any).conditionErrors)) only after verifying
Array.isArray((error as any).conditionErrors), and replace the
setActionSplits(actionSplits.map(...)) with setActionSplits(prev => { let
usedErrorIdx = 0; return prev.map(item => ({ ...item, actions:
item.actions.map(action => ({ ...action, error: ((error as any).actionErrors &&
Array.isArray((error as any).actionErrors)) ? ((error as
any).actionErrors[usedErrorIdx++] ?? null) : null })) })); }) so you operate on
the latest state and only index into actionErrors after confirming its array
shape.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: a54b479b-aeee-4c32-9a93-17b05d244d4f
📒 Files selected for processing (13)
packages/desktop-client/src/components/accounts/Account.tsxpackages/desktop-client/src/components/filters/FiltersMenu.tsxpackages/desktop-client/src/components/mobile/rules/MobileRulesPage.tsxpackages/desktop-client/src/components/mobile/transactions/TransactionEdit.tsxpackages/desktop-client/src/components/modals/ManageRulesModal.tsxpackages/desktop-client/src/components/modals/MergeUnusedPayeesModal.tsxpackages/desktop-client/src/components/rules/RuleEditor.tsxpackages/desktop-client/src/components/rules/Value.tsxpackages/desktop-client/src/components/schedules/DiscoverSchedules.tsxpackages/desktop-client/src/components/transactions/TransactionList.tsxpackages/desktop-client/src/hooks/usePreviewTransactions.tspackages/loot-core/src/server/api.tspackages/loot-core/src/server/schedules/app.ts
💤 Files with no reviewable changes (1)
- packages/desktop-client/src/components/schedules/DiscoverSchedules.tsx
🚧 Files skipped from review as they are similar to previous changes (4)
- packages/desktop-client/src/hooks/usePreviewTransactions.ts
- packages/desktop-client/src/components/modals/ManageRulesModal.tsx
- packages/desktop-client/src/components/filters/FiltersMenu.tsx
- packages/desktop-client/src/components/modals/MergeUnusedPayeesModal.tsx
There was a problem hiding this comment.
🧹 Nitpick comments (1)
packages/desktop-client/src/components/mobile/rules/MobileRulesPage.tsx (1)
114-128: Consider removing manualuseCallbackforhandleRuleDeletein desktop-client.Given the React Compiler guidance for this package, this callback can be a plain function and avoids dependency-array upkeep.
♻️ Proposed simplification
- const handleRuleDelete = useCallback( - (rule: RuleEntity) => { - deleteRule( - { id: rule.id }, - { - onSuccess: () => { - showUndoNotification({ - message: t('Rule deleted successfully'), - }); - }, - }, - ); - }, - [deleteRule, showUndoNotification, t], - ); + function handleRuleDelete(rule: RuleEntity) { + deleteRule( + { id: rule.id }, + { + onSuccess: () => { + showUndoNotification({ + message: t('Rule deleted successfully'), + }); + }, + }, + ); + }As per coding guidelines, "In desktop-client, the React Compiler automatically memoizes component bodies; omit manual
useCallback,useMemo, andReact.memowhen adding or refactoring code."🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/desktop-client/src/components/mobile/rules/MobileRulesPage.tsx` around lines 114 - 128, Remove the manual useCallback wrapper around handleRuleDelete: replace the useCallback-wrapped function with a plain function named handleRuleDelete(rule: RuleEntity) that calls deleteRule({ id: rule.id }, { onSuccess: () => showUndoNotification({ message: t('Rule deleted successfully') }) }); remove useCallback import if unused and update the dependency array usage (deleteRule, showUndoNotification, t) is no longer needed; keep the function name handleRuleDelete and ensure any callers still reference it unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@packages/desktop-client/src/components/mobile/rules/MobileRulesPage.tsx`:
- Around line 114-128: Remove the manual useCallback wrapper around
handleRuleDelete: replace the useCallback-wrapped function with a plain function
named handleRuleDelete(rule: RuleEntity) that calls deleteRule({ id: rule.id },
{ onSuccess: () => showUndoNotification({ message: t('Rule deleted
successfully') }) }); remove useCallback import if unused and update the
dependency array usage (deleteRule, showUndoNotification, t) is no longer
needed; keep the function name handleRuleDelete and ensure any callers still
reference it unchanged.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 624d3f9b-5280-4f6b-bbe6-923d2d7eedcd
📒 Files selected for processing (1)
packages/desktop-client/src/components/mobile/rules/MobileRulesPage.tsx
5c7c70d to
d262f7d
Compare
|
This PR is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 5 days. |
|
This PR was closed because it has been stalled for 5 days with no activity. |
Description
Related issue(s)
Testing
Checklist
Bundle Stats
View detailed bundle stats
desktop-client
Total
Changeset
src/rules/mutations.tssrc/rules/queries.tssrc/hooks/useRules.tssrc/hooks/usePayeeRules.tssrc/components/rules/Value.tsxsrc/components/mobile/rules/MobileRulesPage.tsxhome/runner/work/actual/actual/packages/loot-core/src/shared/rules.tssrc/components/ManageRules.tsxsrc/components/rules/ScheduleValue.tsxsrc/hooks/usePreviewTransactions.tssrc/components/modals/MergeUnusedPayeesModal.tsxsrc/components/accounts/Account.tsxsrc/components/mobile/transactions/TransactionEdit.tsxnode_modules/react-dnd/dist/hooks/useDrop/useDrop.jssrc/budget/mutations.tsnode_modules/react-dnd/dist/hooks/useDrag/useDrag.jssrc/components/sort.tsxsrc/components/transactions/TransactionMenu.tsxsrc/components/filters/FiltersMenu.tsxsrc/components/rules/RuleEditor.tsxsrc/components/budget/ExpenseGroup.tsxsrc/components/budget/IncomeCategory.tsxsrc/components/transactions/TransactionsTable.tsxsrc/components/budget/ExpenseCategory.tsxsrc/components/mobile/accounts/AccountTransactions.tsxsrc/components/CommandBar.tsxsrc/components/budget/BudgetCategories.tsxsrc/components/sidebar/Account.tsxsrc/components/payees/ManagePayees.tsxsrc/components/autocomplete/CategoryAutocomplete.tsxsrc/components/transactions/SelectedTransactionsButton.tsxsrc/rules/index.tssrc/components/table.tsxsrc/components/autocomplete/AccountAutocomplete.tsxsrc/components/mobile/MobileNavTabs.tsxsrc/components/PrivacyFilter.tsxsrc/components/budget/envelope/CoverMenu.tsxsrc/components/budget/envelope/TransferMenu.tsxsrc/hooks/useSelected.tsxsrc/hooks/useDisplayPayee.tsxsrc/components/transactions/table/utils.tsnode_modules/@use-gesture/react/dist/use-gesture-react.esm.jssrc/components/schedules/DiscoverSchedules.tsxsrc/components/mobile/rules/MobileRuleEditPage.tsxsrc/components/transactions/TransactionList.tsxsrc/components/modals/ManageRulesModal.tsxView detailed bundle breakdown
Added
No assets were added
Removed
No assets were removed
Bigger
Smaller
Unchanged
loot-core
Total
Changeset
home/runner/work/actual/actual/packages/loot-core/src/server/rules/app.tshome/runner/work/actual/actual/packages/loot-core/src/server/schedules/app.tshome/runner/work/actual/actual/packages/loot-core/src/server/api.tsView detailed bundle breakdown
Added
Removed
Bigger
No assets were bigger
Smaller
No assets were smaller
Unchanged
No assets were unchanged
api
Total
Changeset
home/runner/work/actual/actual/packages/loot-core/src/server/rules/app.tshome/runner/work/actual/actual/packages/loot-core/src/server/schedules/app.tshome/runner/work/actual/actual/packages/loot-core/src/server/api.tsView detailed bundle breakdown
Added
No assets were added
Removed
No assets were removed
Bigger
Smaller
No assets were smaller
Unchanged