A local-first personal finance app
[AI] Fix budget template notification translations (#8478)
Abdullah Khawaja79341b3be183
diff --git a/packages/desktop-client/src/budget/mutations.test.ts b/packages/desktop-client/src/budget/mutations.test.tsnew file mode 100644index 0000000000..9ccde232d5--- /dev/null+++ b/packages/desktop-client/src/budget/mutations.test.ts@@ -0,0 +1,123 @@+import type { TFunction } from 'i18next';+import i18next from 'i18next';+import { beforeAll, describe, expect, it } from 'vitest';++import { translateBudgetTemplateNotification } from './mutations';++const t = ((key: string, options?: Record<string, unknown>) => {+ if (!options) {+ return `translated:${key}`;+ }+ return `${key}:${JSON.stringify(options)}`;+}) as TFunction;++const pluralI18n = i18next.createInstance();+const pluralT = pluralI18n.t.bind(pluralI18n) as TFunction;+const cleanupAppliedMessage =+ 'Successfully returned funds from $t(budget-template-source, {"count": {{sourceCount}}}) and funded $t(budget-template-sinking-fund, {"count": {{sinkCount}}}).';+const cleanupAppliedWithErrorsMessage = `${cleanupAppliedMessage} There were errors interpreting some templates:`;++beforeAll(async () => {+ await pluralI18n.init({+ lng: 'en',+ fallbackLng: false,+ resources: {+ en: {+ translation: {+ 'budget-template-source_one': '{{count}} source',+ 'budget-template-source_other': '{{count}} sources',+ 'budget-template-sinking-fund_one': '{{count}} sinking fund',+ 'budget-template-sinking-fund_other': '{{count}} sinking funds',+ [cleanupAppliedMessage]: cleanupAppliedMessage,+ [cleanupAppliedWithErrorsMessage]: cleanupAppliedWithErrorsMessage,+ },+ },+ },+ interpolation: { escapeValue: false },+ });+});++describe('translateBudgetTemplateNotification', () => {+ it('translates static budget template notification keys', () => {+ expect(+ translateBudgetTemplateNotification(+ { message: 'templates-check-passed' },+ t,+ ).message,+ ).toBe('translated:All templates passed! π');+ expect(+ translateBudgetTemplateNotification({ message: 'template-errors' }, t)+ .message,+ ).toBe('translated:There were errors interpreting some templates:');+ });++ it('translates template notification counts', () => {+ expect(+ translateBudgetTemplateNotification(+ { message: 'templates-applied', count: 3 },+ t,+ ).message,+ ).toBe(+ 'Successfully applied templates to {{count}} categories:{"count":3}',+ );+ });++ it('leaves non-template notifications unchanged', () => {+ expect(+ translateBudgetTemplateNotification({ message: 'Already translated' }, t)+ .message,+ ).toBe('Already translated');+ });++ it('translates cleanup notifications with i18next nesting', () => {+ const cases = [+ [+ 0,+ 0,+ 'Successfully returned funds from 0 sources and funded 0 sinking funds.',+ ],+ [+ 1,+ 1,+ 'Successfully returned funds from 1 source and funded 1 sinking fund.',+ ],+ [+ 1,+ 2,+ 'Successfully returned funds from 1 source and funded 2 sinking funds.',+ ],+ [+ 2,+ 1,+ 'Successfully returned funds from 2 sources and funded 1 sinking fund.',+ ],+ [+ 2,+ 2,+ 'Successfully returned funds from 2 sources and funded 2 sinking funds.',+ ],+ ] as const;++ for (const [sourceCount, sinkCount, expected] of cases) {+ expect(+ translateBudgetTemplateNotification(+ { message: 'cleanup-applied', sourceCount, sinkCount },+ pluralT,+ ).message,+ ).toBe(expected);+ }++ expect(+ translateBudgetTemplateNotification(+ {+ message: 'cleanup-applied-with-errors',+ sourceCount: 1,+ sinkCount: 2,+ },+ pluralT,+ ).message,+ ).toBe(+ 'Successfully returned funds from 1 source and funded 2 sinking funds. There were errors interpreting some templates:',+ );+ });+});diff --git a/packages/desktop-client/src/budget/mutations.ts b/packages/desktop-client/src/budget/mutations.tsindex 27d2289dfb..6c1e7d74f8 100644--- a/packages/desktop-client/src/budget/mutations.ts+++ b/packages/desktop-client/src/budget/mutations.ts@@ -13,6 +13,7 @@ import { v4 as uuidv4 } from 'uuid';import { pushModal } from '#modals/modalsSlice';import { addNotification } from '#notifications/notificationsSlice';+import type { Notification } from '#notifications/notificationsSlice';import { useDispatch } from '#redux';import type { AppDispatch } from '#redux/store';@@ -59,6 +60,81 @@ function dispatchCategoryNameAlreadyExistsNotification();}+export type BudgetTemplateNotification = Notification & {+ count?: number | undefined;+ sourceCount?: number | undefined;+ sinkCount?: number | undefined;+};++// i18next-parser does not extract keys nested inside translation strings.+// t('budget-template-source', { count: 1, defaultValue_one: '{{count}} source', defaultValue_other: '{{count}} sources' })+// t('budget-template-sinking-fund', { count: 1, defaultValue_one: '{{count}} sinking fund', defaultValue_other: '{{count}} sinking funds' })+function formatCleanupApplied(+ notification: BudgetTemplateNotification,+ t: TFunction,+) {+ const sourceCount = notification.sourceCount ?? 0;+ const sinkCount = notification.sinkCount ?? 0;++ return t(+ 'Successfully returned funds from $t(budget-template-source, {"count": {{sourceCount}}}) and funded $t(budget-template-sinking-fund, {"count": {{sinkCount}}}).',+ { sourceCount, sinkCount },+ );+}++function formatCleanupAppliedWithErrors(+ notification: BudgetTemplateNotification,+ t: TFunction,+) {+ const sourceCount = notification.sourceCount ?? 0;+ const sinkCount = notification.sinkCount ?? 0;++ return t(+ 'Successfully returned funds from $t(budget-template-source, {"count": {{sourceCount}}}) and funded $t(budget-template-sinking-fund, {"count": {{sinkCount}}}). There were errors interpreting some templates:',+ { sourceCount, sinkCount },+ );+}++export function translateBudgetTemplateNotification(+ notification: BudgetTemplateNotification,+ t: TFunction,+): Notification {+ switch (notification.message) {+ case 'templates-up-to-date':+ return { ...notification, message: t('Everything is up to date') };+ case 'template-errors':+ return {+ ...notification,+ message: t('There were errors interpreting some templates:'),+ };+ case 'templates-applied':+ return {+ ...notification,+ message: t('Successfully applied templates to {{count}} categories', {+ count: notification.count ?? 0,+ }),+ };+ case 'templates-check-passed':+ return { ...notification, message: t('All templates passed! π') };+ case 'cleanup-no-funds':+ return { ...notification, message: t('Global: Funds not available:') };+ case 'cleanup-up-to-date':+ return { ...notification, message: t('All categories were up to date.') };+ case 'cleanup-applied':+ return {+ ...notification,+ message: formatCleanupApplied(notification, t),+ };+ case 'cleanup-applied-with-errors':+ return {+ ...notification,+ message: formatCleanupAppliedWithErrors(notification, t),+ };+ default:+ return notification;+ }+}+type CreateCategoryPayload = {name: CategoryEntity['name'];groupId: CategoryGroupEntity['id'];@@ -824,7 +900,7 @@ export function useBudgetActions() {if (notification) {dispatch(addNotification({- notification,+ notification: translateBudgetTemplateNotification(notification, t),}),);}diff --git a/packages/loot-core/src/server/budget/cleanup-template.ts b/packages/loot-core/src/server/budget/cleanup-template.tsindex 130ea0f0c3..0ac1eb9bc8 100644--- a/packages/loot-core/src/server/budget/cleanup-template.ts+++ b/packages/loot-core/src/server/budget/cleanup-template.ts@@ -5,14 +5,7 @@ import type { CleanupTemplate } from '#types/models/cleanup-templates';import { getSheetValue, setBudget, setGoal } from './actions';import { storeNoteCleanups } from './cleanup-template-notes';--type Notification = {- type?: 'message' | 'error' | 'warning' | undefined;- pre?: string | undefined;- title?: string | undefined;- message: string;- sticky?: boolean | undefined;-};+import type { TemplateNotification } from './template-notification';export async function cleanupTemplate({ month }: { month: string }) {await storeNoteCleanups();@@ -146,7 +139,7 @@ async function applyGroupCleanups(return warnings;}-async function processCleanup(month: string): Promise<Notification> {+async function processCleanup(month: string): Promise<TemplateNotification> {let num_sources = 0;let num_sinks = 0;let total_weight = 0;@@ -310,46 +303,48 @@ async function processCleanup(month: string): Promise<Notification> {return {type: 'error',sticky: true,- message: 'There were errors interpreting some templates:',+ message: 'template-errors',pre: errors.join('\n\n'),};} else if (warnings.length) {return {type: 'warning',- message: 'Global: Funds not available:',+ message: 'cleanup-no-funds',pre: warnings.join('\n\n'),};} else {return {type: 'message',- message: 'All categories were up to date.',+ message: 'cleanup-up-to-date',};}} else {- const applied = `Successfully returned funds from ${num_sources} ${- num_sources === 1 ? 'source' : 'sources'- } and funded ${num_sinks} sinking ${num_sinks === 1 ? 'fund' : 'funds'}.`;if (errors.length) {return {+ type: 'error',sticky: true,- message: `${applied} There were errors interpreting some templates:`,+ message: 'cleanup-applied-with-errors',+ sourceCount: num_sources,+ sinkCount: num_sinks,pre: errors.join('\n\n'),};} else if (warnings.length) {return {type: 'warning',- message: 'Global: Funds not available:',+ message: 'cleanup-no-funds',pre: warnings.join('\n\n'),};} else if (budgetAvailable === 0) {return {type: 'message',- message: 'All categories were up to date.',+ message: 'cleanup-up-to-date',};} else {return {type: 'message',- message: applied,+ message: 'cleanup-applied',+ sourceCount: num_sources,+ sinkCount: num_sinks,};}}diff --git a/packages/loot-core/src/server/budget/goal-template.test.ts b/packages/loot-core/src/server/budget/goal-template.test.tsindex 248a5a9c9d..7263908ff8 100644--- a/packages/loot-core/src/server/budget/goal-template.test.ts+++ b/packages/loot-core/src/server/budget/goal-template.test.ts@@ -337,7 +337,8 @@ describe('applyMultipleCategoryTemplates', () => {categoryIds: [cat1.id, cat2.id],});- expect(result.message).toMatch(/Successfully applied/);+ expect(result.message).toBe('templates-applied');+ expect(result.count).toBe(2);expect(actions.setBudget).toHaveBeenCalledTimes(2);const budgetCalls = vi.mocked(actions.setBudget)@@ -414,7 +415,7 @@ describe('applyMultipleCategoryTemplates', () => {categoryIds: [cat1.id],});- expect(result.message).toMatch(/There were errors/);+ expect(result.message).toBe('template-errors');expect(result.pre).toMatch(/Target month has passed/);expect(actions.setBudget).not.toHaveBeenCalled();});@@ -434,7 +435,7 @@ describe('applyMultipleCategoryTemplates', () => {categoryIds: [cat1.id],});- expect(result.message).toBe('Everything is up to date');+ expect(result.message).toBe('templates-up-to-date');const goalCalls = vi.mocked(actions.setGoal).mock.calls.map(c => c[0]);expect(goalCalls).toContainEqual(expect.objectContaining({ category: cat1.id, goal: null }),diff --git a/packages/loot-core/src/server/budget/goal-template.ts b/packages/loot-core/src/server/budget/goal-template.tsindex dee1bd87d6..1d64402935 100644--- a/packages/loot-core/src/server/budget/goal-template.ts+++ b/packages/loot-core/src/server/budget/goal-template.ts@@ -12,6 +12,7 @@ import { getSheetValue, isTrackingBudget, setBudget, setGoal } from './actions';import { CategoryTemplateContext } from './category-template-context';import { tombstoneOrphanCleanupGroups } from './cleanup-groups';import { checkTemplateNotes, storeNoteTemplates } from './template-notes';+import type { TemplateNotification } from './template-notification';export function distributeRemainder(templateContexts: CategoryTemplateContext[],@@ -34,14 +35,6 @@ export function distributeRemainder(return availBudget;}-type Notification = {- type?: 'message' | 'error' | 'warning' | undefined;- pre?: string | undefined;- title?: string | undefined;- message: string;- sticky?: boolean | undefined;-};-export async function storeTemplates({categoriesWithTemplates,source,@@ -79,7 +72,7 @@ export async function applyTemplate({month,}: {month: string;-}): Promise<Notification> {+}): Promise<TemplateNotification> {await storeNoteTemplates();const categoryTemplates = await getTemplates();const ret = await processTemplate(month, false, categoryTemplates, []);@@ -90,7 +83,7 @@ export async function overwriteTemplate({month,}: {month: string;-}): Promise<Notification> {+}): Promise<TemplateNotification> {await storeNoteTemplates();const categoryTemplates = await getTemplates();const ret = await processTemplate(month, true, categoryTemplates, []);@@ -311,7 +304,7 @@ async function processTemplate(force: boolean,categoryTemplates: Record<CategoryEntity['id'], Template[]>,categories: CategoryEntity[] = [],-): Promise<Notification> {+): Promise<TemplateNotification> {const { contexts, errors, orphanGoals } = await computeTemplates(month,force,@@ -325,13 +318,13 @@ async function processTemplate(}return {type: 'message',- message: 'Everything is up to date',+ message: 'templates-up-to-date',};}if (errors.length > 0) {return {sticky: true,- message: 'There were errors interpreting some templates:',+ message: 'template-errors',pre: errors.join(`\n\n`),};}@@ -355,7 +348,8 @@ async function processTemplate(return {type: 'message',- message: `Successfully applied templates to ${contexts.length} categories`,+ message: 'templates-applied',+ count: contexts.length,};}diff --git a/packages/loot-core/src/server/budget/template-notes.test.ts b/packages/loot-core/src/server/budget/template-notes.test.tsindex 56742fba2a..0857ac15f4 100644--- a/packages/loot-core/src/server/budget/template-notes.test.ts+++ b/packages/loot-core/src/server/budget/template-notes.test.ts@@ -268,7 +268,7 @@ describe('checkTemplates', () => {mockSchedules: mockSchedules(),expected: {type: 'message',- message: 'All templates passed! π',+ message: 'templates-check-passed',},},{@@ -283,7 +283,7 @@ describe('checkTemplates', () => {mockSchedules: mockSchedules(),expected: {type: 'message',- message: 'All templates passed! π',+ message: 'templates-check-passed',},},{@@ -298,7 +298,7 @@ describe('checkTemplates', () => {mockSchedules: mockSchedules(),expected: {sticky: true,- message: 'There were errors interpreting some templates:',+ message: 'template-errors',pre: 'Category 1: #template broken template',},},@@ -314,7 +314,7 @@ describe('checkTemplates', () => {mockSchedules: mockSchedules(),expected: {sticky: true,- message: 'There were errors interpreting some templates:',+ message: 'template-errors',pre: 'Category 1: Schedule "Non-existent Schedule" does not exist',},},@@ -330,7 +330,7 @@ describe('checkTemplates', () => {mockSchedules: mockSchedules(),expected: {sticky: true,- message: 'There were errors interpreting some templates:',+ message: 'template-errors',pre: 'Category 1: #template schedule Mock Schedule 1 [increase 1001%]\nError: Invalid adjustment percentage (1001%). Must be between -100% and 1000%',},},@@ -346,7 +346,7 @@ describe('checkTemplates', () => {mockSchedules: mockSchedules(),expected: {sticky: true,- message: 'There were errors interpreting some templates:',+ message: 'template-errors',pre: 'Category 1: #template schedule Mock Schedule 1 [decrease 101%]\nError: Invalid adjustment percentage (-101%). Must be between -100% and 1000%',},},diff --git a/packages/loot-core/src/server/budget/template-notes.ts b/packages/loot-core/src/server/budget/template-notes.tsindex 9b9a500ea9..9941adbfb2 100644--- a/packages/loot-core/src/server/budget/template-notes.ts+++ b/packages/loot-core/src/server/budget/template-notes.ts@@ -8,13 +8,7 @@ import {resetCategoryGoalDefsWithNoTemplates,} from './statements';import type { CategoryWithTemplateNote } from './statements';--type Notification = {- type?: 'message' | 'error' | 'warning' | undefined;- pre?: string | undefined;- message: string;- sticky?: boolean | undefined;-};+import type { TemplateNotification } from './template-notification';export const TEMPLATE_PREFIX = '#template';export const GOAL_PREFIX = '#goal';@@ -36,7 +30,7 @@ type CategoryWithTemplateNotes = {templates: Template[];};-export async function checkTemplateNotes(): Promise<Notification> {+export async function checkTemplateNotes(): Promise<TemplateNotification> {const categoryWithTemplates = await getCategoriesWithTemplates();const schedules = await getActiveSchedules();const scheduleNames = schedules.map(({ name }) => name);@@ -64,14 +58,14 @@ export async function checkTemplateNotes(): Promise<Notification> {if (errors.length) {return {sticky: true,- message: 'There were errors interpreting some templates:',+ message: 'template-errors',pre: errors.join('\n\n'),};}return {type: 'message',- message: 'All templates passed! π',+ message: 'templates-check-passed',};}diff --git a/packages/loot-core/src/server/budget/template-notification.ts b/packages/loot-core/src/server/budget/template-notification.tsnew file mode 100644index 0000000000..8a14c70a5e--- /dev/null+++ b/packages/loot-core/src/server/budget/template-notification.ts@@ -0,0 +1,20 @@+export type TemplateNotificationMessage =+ | 'templates-up-to-date'+ | 'template-errors'+ | 'templates-applied'+ | 'templates-check-passed'+ | 'cleanup-no-funds'+ | 'cleanup-up-to-date'+ | 'cleanup-applied'+ | 'cleanup-applied-with-errors';++export type TemplateNotification = {+ type?: 'message' | 'error' | 'warning' | undefined;+ pre?: string | undefined;+ title?: string | undefined;+ message: TemplateNotificationMessage;+ sticky?: boolean | undefined;+ count?: number | undefined;+ sourceCount?: number | undefined;+ sinkCount?: number | undefined;+};diff --git a/upcoming-release-notes/translate-budget-template-notifications.md b/upcoming-release-notes/translate-budget-template-notifications.mdnew file mode 100644index 0000000000..c13d25302a--- /dev/null+++ b/upcoming-release-notes/translate-budget-template-notifications.md@@ -0,0 +1,6 @@+---+category: Bugfix+authors: [DarthAmk97]+---++Translate budget template action notifications.