A local-first personal finance app
Replace "convert to schedule" prompt with inline button (#8588)
Caleb Burton1c5255f753fc
diff --git a/packages/desktop-client/e2e/help-menu.test.ts-snapshots/Help-menu-Check-the-keyboard-shortcuts-modal-visuals-1-chromium-linux.png b/packages/desktop-client/e2e/help-menu.test.ts-snapshots/Help-menu-Check-the-keyboard-shortcuts-modal-visuals-1-chromium-linux.pngindex ec183469a1..28efac9c36 100644Binary files a/packages/desktop-client/e2e/help-menu.test.ts-snapshots/Help-menu-Check-the-keyboard-shortcuts-modal-visuals-1-chromium-linux.png and b/packages/desktop-client/e2e/help-menu.test.ts-snapshots/Help-menu-Check-the-keyboard-shortcuts-modal-visuals-1-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/help-menu.test.ts-snapshots/Help-menu-Check-the-keyboard-shortcuts-modal-visuals-2-chromium-linux.png b/packages/desktop-client/e2e/help-menu.test.ts-snapshots/Help-menu-Check-the-keyboard-shortcuts-modal-visuals-2-chromium-linux.pngindex c5d9f24e8b..493cb3cd2b 100644Binary files a/packages/desktop-client/e2e/help-menu.test.ts-snapshots/Help-menu-Check-the-keyboard-shortcuts-modal-visuals-2-chromium-linux.png and b/packages/desktop-client/e2e/help-menu.test.ts-snapshots/Help-menu-Check-the-keyboard-shortcuts-modal-visuals-2-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/help-menu.test.ts-snapshots/Help-menu-Check-the-keyboard-shortcuts-modal-visuals-3-chromium-linux.png b/packages/desktop-client/e2e/help-menu.test.ts-snapshots/Help-menu-Check-the-keyboard-shortcuts-modal-visuals-3-chromium-linux.pngindex cadb51a911..0a9ae0faa4 100644Binary files a/packages/desktop-client/e2e/help-menu.test.ts-snapshots/Help-menu-Check-the-keyboard-shortcuts-modal-visuals-3-chromium-linux.png and b/packages/desktop-client/e2e/help-menu.test.ts-snapshots/Help-menu-Check-the-keyboard-shortcuts-modal-visuals-3-chromium-linux.png differdiff --git a/packages/desktop-client/src/components/mobile/transactions/TransactionEdit.tsx b/packages/desktop-client/src/components/mobile/transactions/TransactionEdit.tsxindex 1c68158b50..30f340032e 100644--- a/packages/desktop-client/src/components/mobile/transactions/TransactionEdit.tsx+++ b/packages/desktop-client/src/components/mobile/transactions/TransactionEdit.tsx@@ -38,7 +38,7 @@ import { DEFAULT_MAX_DISTANCE_METERS } from '@actual-app/core/shared/constants';import { calculateDistance } from '@actual-app/core/shared/location-utils';import * as monthUtils from '@actual-app/core/shared/months';import { q } from '@actual-app/core/shared/query';-import { getUpcomingDays } from '@actual-app/core/shared/schedules';+import { DEFAULT_UPCOMING_SCHEDULE_DAYS } from '@actual-app/core/shared/schedules';import {addSplitTransaction,deleteTransaction,@@ -82,7 +82,6 @@ import {import { getPrettyPayee } from '#components/mobile/utils';import { MobilePageHeader, Page } from '#components/Page';import { shouldApplyRuleChange } from '#components/transactions/table/utils';-import { createSingleTimeScheduleFromTransaction } from '#components/transactions/TransactionList';import { useAccounts } from '#hooks/useAccounts';import { useCategories } from '#hooks/useCategories';import { useCurrentWordRange } from '#hooks/useCurrentWordRange';@@ -109,6 +108,11 @@ import { aqlQuery } from '#queries/aqlQuery';import { useDispatch, useSelector } from '#redux';import { setLastTransaction } from '#transactions/transactionsSlice';import { getStatusLabel } from '#util/schedule';+import {+ calculateFutureTransactionInfo,+ createSingleTimeScheduleFromTransaction,+ isFutureTransaction,+} from '#util/schedule-actions';import { AmountInput } from './AmountInput';import { SplitAmountInput } from './SplitAmountInput';@@ -232,10 +236,12 @@ type FooterProps = {isAdding: boolean;onAdd: () => void;onSave: () => void;+ onSchedule: () => void;onSplit: (id: TransactionEntity['id']) => void;onAddSplit: (id: TransactionEntity['id']) => void;onEmptySplitFound: (id: TransactionEntity['id']) => void;editingField?: string;+ isFuture: boolean;onEditField: (id: TransactionEntity['id'],field: 'category' | 'payee' | 'account' | 'date' | 'amount' | 'notes',@@ -247,11 +253,13 @@ function Footer({isAdding,onAdd,onSave,+ onSchedule,onSplit,onAddSplit,onEmptySplitFound,editingField,onEditField,+ isFuture,}: FooterProps) {const [transaction, ...childTransactions] = transactions;const emptySplitTransaction = childTransactions.find(t => t.amount === 0);@@ -278,8 +286,27 @@ function Footer({backgroundColor: theme.tableHeaderBackground,borderTopWidth: 1,borderColor: theme.tableBorder,+ gap: 8,}}>+ {isFuture && (+ <Button+ variant="normal"+ style={{ height: styles.mobileMinHeight }}+ isDisabled={!!editingField}+ onPress={onSchedule}+ >+ <SvgCalendar width={17} height={17} />+ <Text+ style={{+ ...styles.text,+ marginLeft: 6,+ }}+ >+ <Trans>Schedule</Trans>+ </Text>+ </Button>+ )}{transaction.error?.type === 'SplitTransactionError' ? (<Buttonvariant="primary"@@ -623,7 +650,7 @@ const TransactionEditInner = memo<TransactionEditInnerProps>(const navigate = useNavigate();const dispatch = useDispatch();const [showHiddenCategories] = useLocalPref('budget.showHiddenCategories');- const [upcomingLength = '7'] = useSyncedPref(+ const [upcomingLength = DEFAULT_UPCOMING_SCHEDULE_DAYS] = useSyncedPref('upcomingScheduledTransactionLength',);const transactions = useMemo(@@ -646,6 +673,10 @@ const TransactionEditInner = memo<TransactionEditInnerProps>(const [transaction, ...childTransactions] = transactions;+ const isFuture =+ unserializedTransactions.length > 0 &&+ isFutureTransaction(unserializedTransactions[0]);+const { editingField, onRequestActiveEdit, onClearActiveEdit } =useSingleActiveEditForm()!;const childTransactionElementRefMap = useRef<@@ -702,8 +733,6 @@ const TransactionEditInner = memo<TransactionEditInnerProps>();const onSaveInner = useCallback(async () => {- const [unserializedTransaction] = unserializedTransactions;-const onConfirmSave = () => {let transactionsToSave = unserializedTransactions;if (isAdding) {@@ -716,71 +745,6 @@ const TransactionEditInner = memo<TransactionEditInnerProps>(void navigate(-1);};- const today = monthUtils.currentDay();- const isFuture = unserializedTransaction.date > today;- const isLinkedToSchedule = !!unserializedTransaction.schedule;-- if (isFuture && !isLinkedToSchedule) {- const upcomingDays = getUpcomingDays(upcomingLength, today);- const daysUntilTransaction = monthUtils.differenceInCalendarDays(- unserializedTransaction.date,- today,- );- const isBeyondWindow = daysUntilTransaction > upcomingDays;-- dispatch(- pushModal({- modal: {- name: 'convert-to-schedule',- options: {- isBeyondWindow,- daysUntilTransaction,- upcomingDays,- onConfirm: async () => {- if (- !isAdding &&- unserializedTransaction.id &&- !unserializedTransaction.id.startsWith('temp')- ) {- await send('transaction-delete', {- id: unserializedTransaction.id,- });- }-- const transactionForSchedule =- unserializedTransaction.is_parent- ? {- ...unserializedTransaction,- subtransactions: unserializedTransactions.filter(- t =>- t.is_child &&- t.parent_id === unserializedTransaction.id,- ),- }- : unserializedTransaction;-- await createSingleTimeScheduleFromTransaction(- transactionForSchedule,- );-- dispatch(- addNotification({- notification: {- type: 'message',- message: t('Schedule created successfully'),- },- }),- );- void navigate(-1);- },- onCancel: onConfirmSave,- },- },- }),- );- return;- }-if (unserializedTransactions.some(t => t.reconciled)) {// On mobile any save gives the warning.// On the web only certain changes trigger a warning.@@ -830,11 +794,111 @@ const TransactionEditInner = memo<TransactionEditInnerProps>(onConfirmSave();}}+ }, [isAdding, dispatch, navigate, onSave, unserializedTransactions, t]);++ const onSchedule = useCallback(async () => {+ const [unserializedTransaction] = unserializedTransactions;++ if (!unserializedTransaction.account) {+ dispatch(+ addNotification({+ notification: {+ type: 'error',+ message: t('Account is a required field'),+ },+ }),+ );+ return;+ }++ // Already linked to a schedule; keep it as a transaction.+ if (unserializedTransaction.schedule) {+ return;+ }++ const transactionForSchedule = unserializedTransaction.is_parent+ ? {+ ...unserializedTransaction,+ subtransactions: unserializedTransactions.filter(+ t => t.is_child && t.parent_id === unserializedTransaction.id,+ ),+ }+ : unserializedTransaction;++ const createSchedule = async () => {+ try {+ await createSingleTimeScheduleFromTransaction(transactionForSchedule);+ } catch {+ dispatch(+ addNotification({+ notification: {+ type: 'error',+ message: t('Failed to create schedule'),+ },+ }),+ );+ return;+ }++ try {+ if (+ !isAdding &&+ unserializedTransaction.id &&+ !unserializedTransaction.id.startsWith('temp')+ ) {+ await send('transaction-delete', {+ id: unserializedTransaction.id,+ });+ }+ } catch {+ dispatch(+ addNotification({+ notification: {+ type: 'error',+ message: t(+ 'Schedule created, but the original transaction could not be deleted',+ ),+ },+ }),+ );+ void navigate(-1);+ return;+ }++ dispatch(+ addNotification({+ notification: {+ type: 'message',+ message: t('Schedule created successfully'),+ },+ }),+ );+ void navigate(-1);+ };++ const { isBeyondWindow, daysUntilTransaction, upcomingDays } =+ calculateFutureTransactionInfo(transactionForSchedule, upcomingLength);++ if (isBeyondWindow) {+ dispatch(+ pushModal({+ modal: {+ name: 'convert-to-schedule',+ options: {+ daysUntilTransaction,+ upcomingDays,+ onConfirm: createSchedule,+ },+ },+ }),+ );+ } else {+ await createSchedule();+ }}, [isAdding,dispatch,navigate,- onSave,unserializedTransactions,upcomingLength,t,@@ -1126,10 +1190,12 @@ const TransactionEditInner = memo<TransactionEditInnerProps>(isAdding={isAdding}onAdd={onSaveInner}onSave={onSaveInner}+ onSchedule={onSchedule}onSplit={onSplit}onAddSplit={onAddSplit}onEmptySplitFound={onEmptySplitFound}editingField={editingField}+ isFuture={isFuture}onEditField={onEditFieldInner}/>}diff --git a/packages/desktop-client/src/components/modals/ConvertToScheduleModal.tsx b/packages/desktop-client/src/components/modals/ConvertToScheduleModal.tsxindex 110f757953..0b6804a877 100644--- a/packages/desktop-client/src/components/modals/ConvertToScheduleModal.tsx+++ b/packages/desktop-client/src/components/modals/ConvertToScheduleModal.tsx@@ -20,7 +20,6 @@ type ConvertToScheduleModalProps = Extract<export function ConvertToScheduleModal({onCancel,onConfirm,- isBeyondWindow,daysUntilTransaction,upcomingDays,}: ConvertToScheduleModalProps) {@@ -45,37 +44,24 @@ export function ConvertToScheduleModal({rightContent={<ModalCloseButton onPress={() => state.close()} />}/><View style={{ lineHeight: 1.5 }}>- <Block>- <Trans>- This transaction has a future date. Would you like to convert it- to a single-time schedule instead?+ <Block+ style={{+ marginTop: 10,+ padding: 10,+ backgroundColor: theme.warningBackground,+ borderRadius: 4,+ }}+ >+ <Trans count={daysUntilTransaction}>+ <strong>Warning:</strong> This transaction is{' '}+ {{ count: daysUntilTransaction }} days away,+ </Trans>{' '}+ <Trans count={upcomingDays}>+ which is beyond your configured upcoming length of{' '}+ {{ count: upcomingDays }} days. The schedule preview will not be+ visible in your account until it gets closer to the date.</Trans></Block>- {isBeyondWindow ? (- <Block- style={{- marginTop: 10,- padding: 10,- backgroundColor: theme.warningBackground,- borderRadius: 4,- }}- >- <Trans>- <strong>Warning:</strong> This transaction is{' '}- {{ daysUntilTransaction }} days away, which is beyond your- configured upcoming length of {{ upcomingDays }} days. The- schedule preview will not be visible in your account until it- gets closer to the date.- </Trans>- </Block>- ) : (- <Block style={{ marginTop: 10 }}>- <Trans>- The transaction will appear as a schedule preview in your- account.- </Trans>- </Block>- )}<Viewstyle={{marginTop: 20,@@ -95,7 +81,7 @@ export function ConvertToScheduleModal({onCancel?.();}}>- <Trans>No, keep as transaction</Trans>+ <Trans>Cancel</Trans></Button><InitialFocus><Button@@ -110,7 +96,7 @@ export function ConvertToScheduleModal({onConfirm();}}>- <Trans>Yes, create schedule</Trans>+ <Trans>Create schedule anyway</Trans></Button></InitialFocus></View>diff --git a/packages/desktop-client/src/components/modals/KeyboardShortcutModal.tsx b/packages/desktop-client/src/components/modals/KeyboardShortcutModal.tsxindex a4bc5f1257..a599e8f01f 100644--- a/packages/desktop-client/src/components/modals/KeyboardShortcutModal.tsx+++ b/packages/desktop-client/src/components/modals/KeyboardShortcutModal.tsx@@ -342,6 +342,13 @@ export function KeyboardShortcutModal() {meta: ctrl,description: t('Add transaction and close form'),},+ {+ id: 'create-schedule-in-new-transaction',+ shortcut: 'Enter',+ meta: ctrl,+ shift: true,+ description: t('Turn the new transaction into a schedule'),+ },{id: 'move-right-when-editing',shortcut: 'Tab',diff --git a/packages/desktop-client/src/components/schedules/CustomUpcomingLength.tsx b/packages/desktop-client/src/components/schedules/CustomUpcomingLength.tsxindex c21ec9d8e6..cd711ee3b0 100644--- a/packages/desktop-client/src/components/schedules/CustomUpcomingLength.tsx+++ b/packages/desktop-client/src/components/schedules/CustomUpcomingLength.tsx@@ -1,4 +1,4 @@-import React, { useEffect, useState } from 'react';+import { useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';import { Input } from '@actual-app/components/input';@@ -22,15 +22,13 @@ export function CustomUpcomingLength({{ value: 'year', label: t('Years') },];- let timePeriod = [];- if (tempValue === 'custom') {- timePeriod = ['1', 'day'];- } else {- timePeriod = tempValue.split('-');- }+ const timePeriod =+ tempValue === 'custom' ? ['1', 'day'] : tempValue.split('-');- const [numValue, setNumValue] = useState(parseInt(timePeriod[0]));- const [unit, setUnit] = useState(timePeriod[1]);+ const [numValue, setNumValue] = useState(+ Number.parseInt(timePeriod[0], 10) || 1,+ );+ const [unit, setUnit] = useState(timePeriod[1] ?? 'day');useEffect(() => {onChange(`${numValue}-${unit}`);diff --git a/packages/desktop-client/src/components/schedules/ScheduleEditForm.tsx b/packages/desktop-client/src/components/schedules/ScheduleEditForm.tsxindex 7573e79203..dc930cea7b 100644--- a/packages/desktop-client/src/components/schedules/ScheduleEditForm.tsx+++ b/packages/desktop-client/src/components/schedules/ScheduleEditForm.tsx@@ -6,6 +6,7 @@ import { Button } from '@actual-app/components/button';import { useResponsive } from '@actual-app/components/hooks/useResponsive';import { InitialFocus } from '@actual-app/components/initial-focus';import { Input } from '@actual-app/components/input';+import type { Menu } from '@actual-app/components/menu';import { Select } from '@actual-app/components/select';import { SpaceBetween } from '@actual-app/components/space-between';import { styles } from '@actual-app/components/styles';@@ -13,6 +14,7 @@ import { Text } from '@actual-app/components/text';import { theme } from '@actual-app/components/theme';import { View } from '@actual-app/components/view';import * as monthUtils from '@actual-app/core/shared/months';+import { UPCOMING_LENGTH_PRESET_OPTIONS } from '@actual-app/core/shared/schedules';import type {RecurConfig,ScheduleEntity,@@ -330,10 +332,11 @@ export function ScheduleEditForm({htmlFor="upcoming-length-field"/>{(() => {- const presetValues = ['1', '7', '14', 'oneMonth', 'currentMonth'];const isPreset =fields.custom_upcoming_length != null &&- presetValues.includes(fields.custom_upcoming_length);+ UPCOMING_LENGTH_PRESET_OPTIONS.some(+ o => o.value === fields.custom_upcoming_length,+ );const isCustomValue =fields.custom_upcoming_length != null && !isPreset;const isValidCustomFormat =@@ -346,19 +349,21 @@ export function ScheduleEditForm({? fields.custom_upcoming_length: '1-day';+ const options: Array<+ readonly [string, string] | typeof Menu.line+ > = [+ ['', t('Use global default')] as [string, string],+ ...UPCOMING_LENGTH_PRESET_OPTIONS.map(+ o => [o.value, t(o.labelKey)] as [string, string],+ ),+ ['custom', t('Custom length')] as [string, string],+ ];+return (<><Selectid="upcoming-length-field"- options={[- ['', t('Use global default')],- ['1', t('1 day')],- ['7', t('1 week')],- ['14', t('2 weeks')],- ['oneMonth', t('1 month')],- ['currentMonth', t('End of the current month')],- ['custom', t('Custom length')],- ]}+ options={options}value={fields.custom_upcoming_length == null? ''diff --git a/packages/desktop-client/src/components/schedules/UpcomingLength.tsx b/packages/desktop-client/src/components/schedules/UpcomingLength.tsxindex 4911ce5a98..e0fd0afbaf 100644--- a/packages/desktop-client/src/components/schedules/UpcomingLength.tsx+++ b/packages/desktop-client/src/components/schedules/UpcomingLength.tsx@@ -5,7 +5,11 @@ import { Button } from '@actual-app/components/button';import { Paragraph } from '@actual-app/components/paragraph';import { Select } from '@actual-app/components/select';import { View } from '@actual-app/components/view';-import type { SyncedPrefs } from '@actual-app/core/types/prefs';+import {+ DEFAULT_UPCOMING_SCHEDULE_DAYS,+ isCustomUpcomingLength,+ UPCOMING_LENGTH_PRESET_OPTIONS,+} from '@actual-app/core/shared/schedules';import { Modal, ModalCloseButton, ModalHeader } from '#components/common/Modal';import { useSyncedPref } from '#hooks/useSyncedPref';@@ -15,26 +19,19 @@ import { CustomUpcomingLength } from './CustomUpcomingLength';function useUpcomingLengthOptions() {const { t } = useTranslation();- const upcomingLengthOptions: {- value: SyncedPrefs['upcomingScheduledTransactionLength'];- label: string;- }[] = [- { value: '1', label: t('1 day') },- { value: '7', label: t('1 week') },- { value: '14', label: t('2 weeks') },- { value: 'oneMonth', label: t('1 month') },- { value: 'currentMonth', label: t('End of the current month') },- { value: 'custom', label: t('Custom length') },- ];+ const upcomingLengthOptions: Array<{ value: string; label: string }> =+ UPCOMING_LENGTH_PRESET_OPTIONS.map(o => ({+ value: o.value,+ label: t(o.labelKey),+ }));++ upcomingLengthOptions.push({ value: 'custom', label: t('Custom length') });return { upcomingLengthOptions };}function nonCustomUpcomingLengthValues(value: string) {- return (- ['1', '7', '14', 'oneMonth', 'currentMonth'].findIndex(x => x === value) ===- -1- );+ return isCustomUpcomingLength(value);}export function UpcomingLength() {@@ -49,7 +46,7 @@ export function UpcomingLength() {const { upcomingLengthOptions } = useUpcomingLengthOptions();- const upcomingLength = _upcomingLength || '7';+ const upcomingLength = _upcomingLength || DEFAULT_UPCOMING_SCHEDULE_DAYS;const [tempUpcomingLength, setTempUpcomingLength] = useState(upcomingLength);const [useCustomLength, setUseCustomLength] = useState(@@ -91,7 +88,7 @@ export function UpcomingLength() {<View><Selectoptions={upcomingLengthOptions.map(x => [- x.value || '7',+ x.value || DEFAULT_UPCOMING_SCHEDULE_DAYS,x.label,])}value={diff --git a/packages/desktop-client/src/components/transactions/TransactionList.tsx b/packages/desktop-client/src/components/transactions/TransactionList.tsxindex d04ff1dab2..efcd613d08 100644--- a/packages/desktop-client/src/components/transactions/TransactionList.tsx+++ b/packages/desktop-client/src/components/transactions/TransactionList.tsx@@ -3,13 +3,9 @@import { useCallback, useLayoutEffect, useRef } from 'react';import type { RefObject } from 'react';import { ErrorBoundary } from 'react-error-boundary';-import { useTranslation } from 'react-i18next';import { theme } from '@actual-app/components/theme';import { send } from '@actual-app/core/platform/client/connection';-import * as monthUtils from '@actual-app/core/shared/months';-import { q } from '@actual-app/core/shared/query';-import { getUpcomingDays } from '@actual-app/core/shared/schedules';import {addSplitTransaction,applyTransactionDiff,@@ -24,7 +20,6 @@ import type {AccountEntity,CategoryEntity,PayeeEntity,- RuleActionEntity,RuleConditionEntity,ScheduleEntity,TransactionEntity,@@ -87,157 +82,6 @@ async function saveDiffAndApply(diff, changes, onChange, learnCategories) {);}-export async function createSingleTimeScheduleFromTransaction(- transaction: TransactionEntity,-): Promise<ScheduleEntity['id']> {- const conditions: RuleConditionEntity[] = [- { op: 'is', field: 'date', value: transaction.date },- ];-- const actions: RuleActionEntity[] = [];-- const conditionFields = ['amount', 'payee', 'account'];-- conditionFields.forEach(field => {- const value = transaction[field];- if (value != null && value !== '') {- conditions.push({- op: 'is',- field,- value,- } as RuleConditionEntity);- }- });-- if (transaction.is_parent && transaction.subtransactions) {- if (transaction.notes) {- actions.push({- op: 'set',- field: 'notes',- value: transaction.notes,- options: {- splitIndex: 0,- },- } as RuleActionEntity);- }-- transaction.subtransactions.forEach((split, index) => {- const splitIndex = index + 1;-- if (split.amount != null) {- actions.push({- op: 'set-split-amount',- value: split.amount,- options: {- splitIndex,- method: 'fixed-amount',- },- } as RuleActionEntity);- }-- if (split.category) {- actions.push({- op: 'set',- field: 'category',- value: split.category,- options: {- splitIndex,- },- } as RuleActionEntity);- }-- if (split.notes) {- actions.push({- op: 'set',- field: 'notes',- value: split.notes,- options: {- splitIndex,- },- } as RuleActionEntity);- }- });- } else {- if (transaction.category) {- actions.push({- op: 'set',- field: 'category',- value: transaction.category,- } as RuleActionEntity);- }-- if (transaction.notes) {- actions.push({- op: 'set',- field: 'notes',- value: transaction.notes,- } as RuleActionEntity);- }- }-- const formattedDate = monthUtils.format(transaction.date, 'MMM dd, yyyy');- const timestamp = Date.now();- const scheduleName = `Auto-created future transaction (${formattedDate}) - ${timestamp}`;-- const scheduleId = await send('schedule/create', {- conditions,- schedule: {- posts_transaction: true,- name: scheduleName,- },- });-- if (actions.length > 0) {- const schedules = await send(- 'query',- q('schedules').filter({ id: scheduleId }).select('rule').serialize(),- );-- const ruleId = schedules?.data?.[0]?.rule;-- if (ruleId) {- const rule = await send('rule-get', { id: ruleId });-- if (rule) {- const linkScheduleActions = rule.actions.filter(- a => a.op === 'link-schedule',- );-- await send('rule-update', {- ...rule,- actions: [...linkScheduleActions, ...actions],- });- }- }- }-- return scheduleId;-}--function isFutureTransaction(transaction: TransactionEntity): boolean {- const today = monthUtils.currentDay();- return transaction.date > today;-}--function calculateFutureTransactionInfo(- transaction: TransactionEntity,- upcomingLength: string,-) {- const today = monthUtils.currentDay();- const upcomingDays = getUpcomingDays(upcomingLength, today);- const daysUntilTransaction = monthUtils.differenceInCalendarDays(- transaction.date,- today,- );- const isBeyondWindow = daysUntilTransaction > upcomingDays;-- return {- isBeyondWindow,- daysUntilTransaction,- upcomingDays,- };-}-type TransactionListProps = Pick<TransactionTableProps,| 'accounts'@@ -332,102 +176,23 @@ export function TransactionList({onScheduleAction,onMakeAsNonSplitTransactions,}: TransactionListProps) {- const { t } = useTranslation();-const dispatch = useDispatch();const navigate = useNavigate();const [learnCategories = 'true'] = useSyncedPref('learn-categories');const isLearnCategoriesEnabled = String(learnCategories) === 'true';- const [upcomingLength = '7'] = useSyncedPref(- 'upcomingScheduledTransactionLength',- );const transactionsLatest = useRef<readonly TransactionEntity[]>([]);useLayoutEffect(() => {transactionsLatest.current = transactions;}, [transactions]);- const promptToConvertToSchedule = useCallback(- (- transaction: TransactionEntity,- onConfirm: () => Promise<void>,- onCancel: () => Promise<void>,- ) => {- const futureInfo = calculateFutureTransactionInfo(- transaction,- upcomingLength,- );-- dispatch(- pushModal({- modal: {- name: 'convert-to-schedule',- options: {- ...futureInfo,- onConfirm: async () => {- await onConfirm();- dispatch(- addNotification({- notification: {- type: 'message',- message: t('Schedule created successfully'),- },- }),- );- onRefetch();- },- onCancel: async () => {- await onCancel();- onRefetch();- },- },- },- }),- );- },- [dispatch, onRefetch, upcomingLength, t],- );-const onAdd = useCallback(async (newTransactions: TransactionEntity[]) => {newTransactions = realizeTempTransactions(newTransactions);-- const parentTransaction = newTransactions.find(t => !t.is_child);- const isLinkedToSchedule = !!parentTransaction?.schedule;-- if (- parentTransaction &&- isFutureTransaction(parentTransaction) &&- !isLinkedToSchedule- ) {- const transactionWithSubtransactions = {- ...parentTransaction,- subtransactions: newTransactions.filter(- t => t.is_child && t.parent_id === parentTransaction.id,- ),- };-- promptToConvertToSchedule(- transactionWithSubtransactions,- async () => {- await createSingleTimeScheduleFromTransaction(- transactionWithSubtransactions,- );- },- async () => {- await saveDiff(- { added: newTransactions },- isLearnCategoriesEnabled,- );- },- );- return;- }-await saveDiff({ added: newTransactions }, isLearnCategoriesEnabled);onRefetch();},- [isLearnCategoriesEnabled, onRefetch, promptToConvertToSchedule],+ [isLearnCategoriesEnabled, onRefetch],);const onSave = useCallback(@@ -457,33 +222,9 @@ export function TransactionList({}};- const isLinkedToSchedule = !!transaction.schedule;- if (isFutureTransaction(transaction) && !isLinkedToSchedule) {- const originalTransaction = transactionsLatest.current.find(- t => t.id === transaction.id,- );- const dateChanged =- !originalTransaction || originalTransaction.date !== transaction.date;-- if (dateChanged || !originalTransaction) {- promptToConvertToSchedule(- transaction,- async () => {- if (transaction.id && !transaction.id.startsWith('temp')) {- await send('transaction-delete', { id: transaction.id });- }-- await createSingleTimeScheduleFromTransaction(transaction);- },- saveTransaction,- );- return;- }- }-await saveTransaction();},- [isLearnCategoriesEnabled, onChange, onRefetch, promptToConvertToSchedule],+ [isLearnCategoriesEnabled, onChange, onRefetch],);const onAddSplit = useCallback(diff --git a/packages/desktop-client/src/components/transactions/TransactionsTable.test.tsx b/packages/desktop-client/src/components/transactions/TransactionsTable.test.tsxindex 0ac8736c2d..655ca89337 100644--- a/packages/desktop-client/src/components/transactions/TransactionsTable.test.tsx+++ b/packages/desktop-client/src/components/transactions/TransactionsTable.test.tsx@@ -40,6 +40,7 @@ import { SelectedProviderWithItems } from '#hooks/useSelected';import { SplitsExpandedProvider } from '#hooks/useSplitsExpanded';import { SpreadsheetProvider } from '#hooks/useSpreadsheet';import { createTestQueryClient, TestProviders } from '#mocks';+import * as modalsSlice from '#modals/modalsSlice';import { payeeQueries } from '#payees';import { tagQueries } from '#tags/queries';@@ -116,6 +117,7 @@ vi.mock('../../hooks/useCategories', () => ({const usualGroup = categoryGroups[1];let schedules: ScheduleEntity[] = [];+const createScheduleMock = vi.fn(async () => 'new-schedule');function generateTransactions(count: number,@@ -276,11 +278,13 @@ function initBasicServer() {id: 'new-tag',...tag,}),+ 'schedule/create': createScheduleMock,});}beforeEach(() => {schedules = [];+ createScheduleMock.mockClear();initBasicServer();});@@ -1165,6 +1169,177 @@ describe('Transactions', () => {);});+ describe('Schedule button for future-dated new transactions', () => {+ const scheduleButtonSelector =+ '[data-testid="new-transaction"] [data-testid="schedule-button"]';++ test('shows the Schedule button for a future-dated new transaction', async () => {+ const { container, updateProps } = renderTransactions();+ updateProps({ isAdding: true });++ const dateInput = queryNewField(container, 'date', 'input');+ await userEvent.clear(dateInput);+ await userEvent.type(dateInput, '02/01/2017[Tab]');++ expect(container.querySelector(scheduleButtonSelector)).toBeTruthy();+ });++ test('hides the Schedule button for a non-future-dated new transaction', () => {+ const { container, updateProps } = renderTransactions();+ updateProps({ isAdding: true });++ expect(container.querySelector(scheduleButtonSelector)).toBeNull();+ });++ test('creates a schedule directly when the date is within the upcoming window', async () => {+ const { container, getTransactions, updateProps } = renderTransactions();+ updateProps({ isAdding: true });++ const dateInput = queryNewField(container, 'date', 'input');+ await userEvent.clear(dateInput);+ await userEvent.type(dateInput, '01/02/2017[Tab]');++ const scheduleButton = container.querySelector(scheduleButtonSelector)!;+ await userEvent.click(scheduleButton);++ await waitFor(() => {+ expect(createScheduleMock).toHaveBeenCalled();+ });+ expect(getTransactions().length).toBe(5);+ });++ test('opens the convert-to-schedule modal when the date is beyond the upcoming window', async () => {+ const pushModalSpy = vi.spyOn(modalsSlice, 'pushModal');+ const { container, getTransactions, updateProps } = renderTransactions();+ updateProps({ isAdding: true });++ const dateInput = queryNewField(container, 'date', 'input');+ await userEvent.clear(dateInput);+ await userEvent.type(dateInput, '02/01/2017[Tab]');++ const scheduleButton = container.querySelector(scheduleButtonSelector)!;+ await userEvent.click(scheduleButton);++ await waitFor(() => {+ expect(pushModalSpy).toHaveBeenCalled();+ });+ expect(createScheduleMock).not.toHaveBeenCalled();+ expect(getTransactions().length).toBe(5);++ const modal = pushModalSpy.mock.calls[0][0].modal as Extract<+ modalsSlice.Modal,+ { name: 'convert-to-schedule' }+ >;+ expect(modal.name).toBe('convert-to-schedule');+ pushModalSpy.mockRestore();+ });++ test('confirming the modal creates a schedule', async () => {+ const pushModalSpy = vi.spyOn(modalsSlice, 'pushModal');+ const { container, getTransactions, updateProps } = renderTransactions();+ updateProps({ isAdding: true });++ const dateInput = queryNewField(container, 'date', 'input');+ await userEvent.clear(dateInput);+ await userEvent.type(dateInput, '02/01/2017[Tab]');++ const scheduleButton = container.querySelector(scheduleButtonSelector)!;+ await userEvent.click(scheduleButton);++ await waitFor(() => {+ expect(pushModalSpy).toHaveBeenCalled();+ });++ const modal = pushModalSpy.mock.calls[0][0].modal as Extract<+ modalsSlice.Modal,+ { name: 'convert-to-schedule' }+ >;+ modal.options.onConfirm();++ await waitFor(() => {+ expect(createScheduleMock).toHaveBeenCalled();+ });+ expect(getTransactions().length).toBe(5);+ pushModalSpy.mockRestore();+ });++ test('cancelling the modal keeps the transaction without creating a schedule', async () => {+ const pushModalSpy = vi.spyOn(modalsSlice, 'pushModal');+ const { container, getTransactions, updateProps } = renderTransactions();+ updateProps({ isAdding: true });++ const dateInput = queryNewField(container, 'date', 'input');+ await userEvent.clear(dateInput);+ await userEvent.type(dateInput, '02/01/2017[Tab]');++ const scheduleButton = container.querySelector(scheduleButtonSelector)!;+ await userEvent.click(scheduleButton);++ await waitFor(() => {+ expect(pushModalSpy).toHaveBeenCalled();+ });++ const modal = pushModalSpy.mock.calls[0][0].modal as Extract<+ modalsSlice.Modal,+ { name: 'convert-to-schedule' }+ >;+ modal.options.onCancel?.();++ expect(createScheduleMock).not.toHaveBeenCalled();+ expect(getTransactions().length).toBe(5);+ pushModalSpy.mockRestore();+ });++ test('ctrl/cmd+shift+enter creates a schedule when the date is within the upcoming window', async () => {+ const { container, getTransactions, updateProps } = renderTransactions();+ updateProps({ isAdding: true });++ const dateInput = queryNewField(container, 'date', 'input');+ await userEvent.clear(dateInput);+ await userEvent.type(dateInput, '01/02/2017[Tab]');++ await userEvent.keyboard('{Control>}{Shift>}{Enter}{/Shift}{/Control}');++ await waitFor(() => {+ expect(createScheduleMock).toHaveBeenCalled();+ });+ expect(getTransactions().length).toBe(5);+ });++ test('ctrl/cmd+shift+enter opens the convert-to-schedule modal when the date is beyond the upcoming window', async () => {+ const pushModalSpy = vi.spyOn(modalsSlice, 'pushModal');+ const { container, getTransactions, updateProps } = renderTransactions();+ updateProps({ isAdding: true });++ const dateInput = queryNewField(container, 'date', 'input');+ await userEvent.clear(dateInput);+ await userEvent.type(dateInput, '02/01/2017[Tab]');++ await userEvent.keyboard('{Control>}{Shift>}{Enter}{/Shift}{/Control}');++ await waitFor(() => {+ expect(pushModalSpy).toHaveBeenCalled();+ });+ expect(createScheduleMock).not.toHaveBeenCalled();+ expect(getTransactions().length).toBe(5);+ pushModalSpy.mockRestore();+ });++ test('ctrl/cmd+shift+enter does nothing for a non-future-dated transaction', async () => {+ const { container, getTransactions, updateProps } = renderTransactions();+ updateProps({ isAdding: true });++ const input = await editNewField(container, 'notes');+ await userEvent.clear(input);+ await userEvent.type(input, 'test');++ await userEvent.keyboard('{Control>}{Shift>}{Enter}{/Shift}{/Control}');++ expect(createScheduleMock).not.toHaveBeenCalled();+ expect(getTransactions().length).toBe(5);+ });+ });+test('ctrl/cmd+enter adds transaction and closes form', async () => {const { container, getTransactions, updateProps } = renderTransactions({onCloseAddTransaction: () => {diff --git a/packages/desktop-client/src/components/transactions/TransactionsTable.tsx b/packages/desktop-client/src/components/transactions/TransactionsTable.tsxindex 746577dce1..ee58a28547 100644--- a/packages/desktop-client/src/components/transactions/TransactionsTable.tsx+++ b/packages/desktop-client/src/components/transactions/TransactionsTable.tsx@@ -50,6 +50,7 @@ import { send } from '@actual-app/core/platform/client/connection';import { memoizeOne } from '@actual-app/core/shared/memoize';import * as monthUtils from '@actual-app/core/shared/months';import { q } from '@actual-app/core/shared/query';+import { DEFAULT_UPCOMING_SCHEDULE_DAYS } from '@actual-app/core/shared/schedules';import {addSplitTransaction,deleteTransaction,@@ -138,6 +139,11 @@ import { getPayeesById } from '#payees';import { aqlQuery } from '#queries/aqlQuery';import { useDispatch } from '#redux';import { getStatusLabel } from '#util/schedule';+import {+ calculateFutureTransactionInfo,+ createSingleTimeScheduleFromTransaction,+ isFutureTransaction,+} from '#util/schedule-actions';import {isTransactionTableColumnAvailableInChildRows,@@ -2345,6 +2351,7 @@ type NewTransactionProps = {editingTransaction: TransactionEntity['id'];focusedField: string;hideFraction: boolean;+ onSchedule: () => void;onAdd: () => void;onAddAndClose: () => void;onAddSplit: (id: TransactionEntity['id']) => void;@@ -2392,6 +2399,7 @@ function NewTransaction({onEdit,onDelete,onSave,+ onSchedule,onAdd,onAddAndClose,onAddSplit,@@ -2406,6 +2414,7 @@ function NewTransaction({}: NewTransactionProps) {const error = transactions[0].error;const isDeposit = transactions[0].amount > 0;+ const isFuture = isFutureTransaction(transactions[0]);const childTransactions = transactions.filter(t => t.parent_id === transactions[0].id,@@ -2413,6 +2422,8 @@ function NewTransaction({const addButtonRef = useRef(null);useProperFocus(addButtonRef, focusedField === 'add');+ const scheduleButtonRef = useRef(null);+ useProperFocus(scheduleButtonRef, focusedField === 'schedule');const cancelButtonRef = useRef(null);useProperFocus(cancelButtonRef, focusedField === 'cancel');@@ -2492,6 +2503,16 @@ function NewTransaction({><Trans>Cancel</Trans></Button>+ {isFuture && (+ <Button+ style={{ marginRight: 10, padding: '4px 10px' }}+ onPress={onSchedule}+ data-testid="schedule-button"+ ref={scheduleButtonRef}+ >+ <Trans>Schedule</Trans>+ </Button>+ )}{error ? (<TransactionErrorerror={error}@@ -2581,6 +2602,7 @@ type TransactionTableInnerProps = {onBatchUnlinkSchedule: (ids: TransactionEntity['id'][]) => void;onCheckNewEnter: (e: KeyboardEvent) => void;onCheckEnter: (e: KeyboardEvent) => void;+ onScheduleTemporary: (id?: TransactionEntity['id']) => void;onAddTemporary: (id?: TransactionEntity['id']) => void;onAddAndCloseTemporary: () => void;onDistributeRemainder: (id: TransactionEntity['id']) => void;@@ -2865,6 +2887,7 @@ function TransactionTableInner({dateFormat={dateFormat}hideFraction={props.hideFraction}onClose={props.onCloseAddTransaction}+ onSchedule={props.onScheduleTemporary}onAdd={props.onAddTemporary}onAddAndClose={props.onAddAndCloseTemporary}onAddSplit={props.onAddSplit}@@ -3003,6 +3026,9 @@ export const TransactionTable = forwardRef(const dispatch = useDispatch();const [showHiddenCategories] = useLocalPref('budget.showHiddenCategories');+ const [upcomingLength = DEFAULT_UPCOMING_SCHEDULE_DAYS] = useSyncedPref(+ 'upcomingScheduledTransactionLength',+ );const [newTransactions, setNewTransactions] = useState<TransactionEntity[]>([],);@@ -3206,8 +3232,14 @@ export const TransactionTable = forwardRef(transactionsWithExpandedSplits,getFieldsTableTransaction,);+ const shouldSchedule = useRef(false);const shouldAdd = useRef(false);const shouldAddAndClose = useRef(false);+ const pendingConvertToSchedule = useRef<null | {+ daysUntilTransaction: number;+ upcomingDays: number;+ onConfirm: () => void;+ }>(null);const latestState = useRef<TableState>({newTransactions: newTransactions ?? [],newNavigator,@@ -3274,6 +3306,94 @@ export const TransactionTable = forwardRef(shouldAddAndClose.current = false;}+ if (shouldSchedule.current) {+ const transactions = latestState.current.newTransactions;+ if (transactions[0] == null) {+ shouldSchedule.current = false;+ } else if (transactions[0].account == null) {+ dispatch(+ addNotification({+ notification: {+ type: 'error',+ message: t('Account is a required field'),+ },+ }),+ );+ newNavigator.onEdit('temp', 'account');+ } else if (transactions[0].schedule != null) {+ // Already linked to a schedule; keep it as a transaction.+ shouldSchedule.current = false;+ } else {+ const tx = transactions[0];+ const subs = tx.is_parent+ ? transactions.filter(t => t.parent_id === tx.id)+ : null;+ const transaction = subs ? groupTransaction([tx, ...subs]) : tx;++ const createSchedule = () => {+ afterSave(async () => {+ try {+ await createSingleTimeScheduleFromTransaction(transaction);+ dispatch(+ addNotification({+ notification: {+ type: 'message',+ message: t('Schedule created successfully'),+ },+ }),+ );+ // Reset form like onAddTemporary does+ setNewTransactions(+ makeTemporaryTransactions(+ props.currentAccountId,+ props.currentCategoryId,+ ),+ );+ newNavigator.onEdit('temp', 'date');+ } catch {+ dispatch(+ addNotification({+ notification: {+ type: 'error',+ message: t('Failed to create schedule'),+ },+ }),+ );+ }+ });+ };++ const { isBeyondWindow, daysUntilTransaction, upcomingDays } =+ calculateFutureTransactionInfo(transaction, upcomingLength);++ if (isBeyondWindow) {+ pendingConvertToSchedule.current = {+ daysUntilTransaction,+ upcomingDays,+ onConfirm: createSchedule,+ };+ } else {+ createSchedule();+ }+ }+ shouldSchedule.current = false;+ }++ useEffect(() => {+ if (pendingConvertToSchedule.current) {+ const options = pendingConvertToSchedule.current;+ pendingConvertToSchedule.current = null;+ dispatch(+ pushModal({+ modal: {+ name: 'convert-to-schedule',+ options,+ },+ }),+ );+ }+ });+useEffect(() => {if (savePending.current && afterSaveFunc.current) {const func = afterSaveFunc.current;@@ -3301,9 +3421,17 @@ export const TransactionTable = forwardRef(}function getFieldsNewTransaction(item?: TransactionEntity) {- const fields = ['select', ...getFocusableFields(), 'cancel', 'add'];-- return getFields(item, fields);+ const fields = [+ 'select',+ ...getFocusableFields(),+ 'cancel',+ 'schedule',+ 'add',+ ];++ return getFields(item, fields).filter(+ f => f !== 'schedule' || (item ? isFutureTransaction(item) : false),+ );}function getFieldsTableTransaction(item?: TransactionEntity) {@@ -3348,7 +3476,21 @@ export const TransactionTable = forwardRef(function onCheckNewEnter(e: KeyboardEvent) {if (e.key === 'Enter') {- if (e.metaKey || e.ctrlKey) {+ if ((e.metaKey || e.ctrlKey) && e.shiftKey) {+ const current = latestState.current.newTransactions[0];+ if (!current || !isFutureTransaction(current)) {+ return;+ }+ e.preventDefault();+ e.stopPropagation();+ afterSave(() => {+ const transaction = latestState.current.newTransactions[0];+ if (transaction && isFutureTransaction(transaction)) {+ shouldSchedule.current = true;+ forceRerender({});+ }+ });+ } else if (e.metaKey || e.ctrlKey) {e.preventDefault();e.stopPropagation();afterSave(() => {@@ -3416,6 +3558,13 @@ export const TransactionTable = forwardRef(}}+ const onScheduleTemporary = useCallback(() => {+ afterSave(() => {+ shouldSchedule.current = true;+ forceRerender({});+ });+ }, []);+const onAddTemporary = useCallback(() => {afterSave(() => {shouldAdd.current = true;@@ -3801,6 +3950,7 @@ export const TransactionTable = forwardRef(onSplit={onSplit}onCheckNewEnter={onCheckNewEnter}onCheckEnter={onCheckEnter}+ onScheduleTemporary={onScheduleTemporary}onAddTemporary={onAddTemporary}onAddAndCloseTemporary={onAddAndCloseTemporary}onAddSplit={onAddSplit}diff --git a/packages/desktop-client/src/modals/modalsSlice.ts b/packages/desktop-client/src/modals/modalsSlice.tsindex 81323fc0a9..a4a3a9e346 100644--- a/packages/desktop-client/src/modals/modalsSlice.ts+++ b/packages/desktop-client/src/modals/modalsSlice.ts@@ -596,7 +596,6 @@ export type Modal =options: {onConfirm: () => void;onCancel?: () => void;- isBeyondWindow?: boolean;daysUntilTransaction?: number;upcomingDays?: number;};diff --git a/packages/desktop-client/src/util/schedule-actions.ts b/packages/desktop-client/src/util/schedule-actions.tsnew file mode 100644index 0000000000..aa08e9dca7--- /dev/null+++ b/packages/desktop-client/src/util/schedule-actions.ts@@ -0,0 +1,154 @@+import { send } from '@actual-app/core/platform/client/connection';+import * as monthUtils from '@actual-app/core/shared/months';+import { q } from '@actual-app/core/shared/query';+import { getUpcomingDays } from '@actual-app/core/shared/schedules';+import type {+ RuleActionEntity,+ RuleConditionEntity,+ ScheduleEntity,+ TransactionEntity,+} from '@actual-app/core/types/models';++export function isFutureTransaction(transaction: TransactionEntity): boolean {+ const today = monthUtils.currentDay();+ return transaction.date > today;+}++export function calculateFutureTransactionInfo(+ transaction: TransactionEntity,+ upcomingLength: string,+) {+ const today = monthUtils.currentDay();+ const upcomingDays = getUpcomingDays(upcomingLength, today);+ const daysUntilTransaction = monthUtils.differenceInCalendarDays(+ transaction.date,+ today,+ );+ const isBeyondWindow = daysUntilTransaction > upcomingDays;++ return { isBeyondWindow, daysUntilTransaction, upcomingDays };+}++export async function createSingleTimeScheduleFromTransaction(+ transaction: TransactionEntity,+): Promise<ScheduleEntity['id']> {+ const conditions: RuleConditionEntity[] = [+ { op: 'is', field: 'date', value: transaction.date },+ ];++ const actions: RuleActionEntity[] = [];++ if (transaction.amount != null) {+ conditions.push({ op: 'is', field: 'amount', value: transaction.amount });+ }+ if (transaction.payee != null && transaction.payee !== '') {+ conditions.push({ op: 'is', field: 'payee', value: transaction.payee });+ }+ if (transaction.account != null && transaction.account !== '') {+ conditions.push({ op: 'is', field: 'account', value: transaction.account });+ }++ if (transaction.is_parent && transaction.subtransactions) {+ if (transaction.notes) {+ actions.push({+ op: 'set',+ field: 'notes',+ value: transaction.notes,+ options: {+ splitIndex: 0,+ },+ });+ }++ transaction.subtransactions.forEach((split, index) => {+ const splitIndex = index + 1;++ if (split.amount != null) {+ actions.push({+ op: 'set-split-amount',+ value: split.amount,+ options: {+ splitIndex,+ method: 'fixed-amount',+ },+ });+ }++ if (split.category) {+ actions.push({+ op: 'set',+ field: 'category',+ value: split.category,+ options: {+ splitIndex,+ },+ });+ }++ if (split.notes) {+ actions.push({+ op: 'set',+ field: 'notes',+ value: split.notes,+ options: {+ splitIndex,+ },+ });+ }+ });+ } else {+ if (transaction.category) {+ actions.push({+ op: 'set',+ field: 'category',+ value: transaction.category,+ });+ }++ if (transaction.notes) {+ actions.push({+ op: 'set',+ field: 'notes',+ value: transaction.notes,+ });+ }+ }++ const formattedDate = monthUtils.format(transaction.date, 'MMM dd, yyyy');+ const timestamp = Date.now();+ const scheduleName = `Auto-created future transaction (${formattedDate}) - ${timestamp}`;++ const scheduleId = await send('schedule/create', {+ conditions,+ schedule: {+ posts_transaction: true,+ name: scheduleName,+ },+ });++ if (actions.length > 0) {+ const schedules = await send(+ 'query',+ q('schedules').filter({ id: scheduleId }).select('rule').serialize(),+ );++ const ruleId = schedules?.data?.[0]?.rule;++ if (ruleId) {+ const rule = await send('rule-get', { id: ruleId });++ if (rule) {+ const linkScheduleActions = rule.actions.filter(+ (a: RuleActionEntity) => a.op === 'link-schedule',+ );++ await send('rule-update', {+ ...rule,+ actions: [...linkScheduleActions, ...actions],+ });+ }+ }+ }++ return scheduleId;+}diff --git a/packages/docs/docs/schedules.md b/packages/docs/docs/schedules.mdindex 4c20e6e46b..f7624655f3 100644--- a/packages/docs/docs/schedules.md+++ b/packages/docs/docs/schedules.md@@ -100,6 +100,25 @@ It may also be useful to link the schedule to transactions.Once a schedule is started, Actual will search the transaction history for entries that match the schedule. You can then select the matches, and will have the option to link those transactions to the current schedule. You can click on the **Find matching transactions** button to have Actual look for matches.+## Converting Future Transactions to Schedules++When you add a transaction with a future date, Actual can turn it into a single-time schedule instead of posting it to your register right away.++1. Navigate to the account where you want to add the transaction.+2. Click **Add transaction** and enter a future date along with the other details of the transaction.+3. A **Schedule** button appears in the new transaction row, next to the **Add** button.+4. Click **Schedule** to create a single-time schedule for the transaction's date.++If the transaction's date is further away than your **Upcoming length** setting, a confirmation dialog appears before the schedule is created to warn you that the schedule will not be visible in the upcoming view until it gets closer to the date. Click **Create schedule anyway** to proceed, or **Cancel** to go back to the in-progress transaction and return to editing.++The transaction is not posted to your register. Instead, it becomes an upcoming scheduled transaction that posts automatically on its scheduled date. You can find it and adjust its details later in [the Schedules view](#the-schedules-overview-screen).++:::note+The **Schedule** button only appears for future-dated transactions. For transactions dated today or earlier, it is hidden. As a shortcut, you can press **Ctrl+Shift+Enter** (**Cmd+Shift+Enter** on macOS) in the new transaction row instead of clicking **Schedule**.+:::++On mobile, a **Schedule** button also appears in the transaction editor when you add a new future-dated transaction or edit an existing future-dated transaction. Converting an existing transaction creates the schedule and then deletes the original transaction.+## Let Actual Find Scheduled TransactionsInstead of manually entering each schedule, you can let Actual find and suggest schedules for you.diff --git a/packages/loot-core/src/server/schedules/app.ts b/packages/loot-core/src/server/schedules/app.tsindex f7e352eacf..6b55a25b7c 100644--- a/packages/loot-core/src/server/schedules/app.ts+++ b/packages/loot-core/src/server/schedules/app.ts@@ -25,6 +25,7 @@ import { RSchedule } from '#server/util/rschedule';import { currentDay, dayFromDate, parseDate } from '#shared/months';import { q } from '#shared/query';import {+ DEFAULT_UPCOMING_SCHEDULE_DAYS,extractScheduleConds,getDateWithSkippedWeekend,getHasTransactionsQuery,@@ -693,7 +694,9 @@ export async function advanceSchedulesService(syncSuccess) {schedule.next_date,schedule.completed,hasTrans.has(schedule.id),- schedule.custom_upcoming_length ?? upcomingLength[0]?.value ?? '7',+ schedule.custom_upcoming_length ??+ upcomingLength[0]?.value ??+ DEFAULT_UPCOMING_SCHEDULE_DAYS,);if (@@ -727,7 +730,7 @@ export async function advanceSchedulesService(syncSuccess) {await hasTransactionForSchedule(currentSchedule),currentSchedule.custom_upcoming_length ??upcomingLength[0]?.value ??- '7',+ DEFAULT_UPCOMING_SCHEDULE_DAYS,);continue;}@@ -760,7 +763,7 @@ export async function advanceSchedulesService(syncSuccess) {await hasTransactionForSchedule(currentSchedule),currentSchedule.custom_upcoming_length ??upcomingLength[0]?.value ??- '7',+ DEFAULT_UPCOMING_SCHEDULE_DAYS,);}} else if (status === 'paid') {diff --git a/packages/loot-core/src/shared/schedules.test.ts b/packages/loot-core/src/shared/schedules.test.tsindex 49165701c0..2e4c13f468 100644--- a/packages/loot-core/src/shared/schedules.test.ts+++ b/packages/loot-core/src/shared/schedules.test.ts@@ -11,7 +11,11 @@ import {getStatus,getUpcomingDays,indexPostedScheduleTransactions,+ isCustomUpcomingLength,isScheduleOccurrencePosted,+ UPCOMING_LENGTH_PRESET_LABELS,+ UPCOMING_LENGTH_PRESET_OPTIONS,+ UPCOMING_LENGTH_PRESET_VALUES,} from './schedules';import type { ScheduleStatuses } from './schedules';@@ -493,4 +497,33 @@ describe('schedules', () => {expect(result).toBeNull();});});++ describe('shared presets', () => {+ it('preset values and options align', () => {+ const valuesFromOptions = UPCOMING_LENGTH_PRESET_OPTIONS.map(+ o => o.value,+ );+ expect(valuesFromOptions).toEqual(+ UPCOMING_LENGTH_PRESET_VALUES as readonly string[],+ );+ });++ it('every preset has a label entry', () => {+ for (const v of UPCOMING_LENGTH_PRESET_VALUES) {+ expect(UPCOMING_LENGTH_PRESET_LABELS[v]).toBeDefined();+ expect(typeof UPCOMING_LENGTH_PRESET_LABELS[v]).toBe('string');+ }+ });++ it('isCustomUpcomingLength recognizes presets and custom values', () => {+ for (const v of UPCOMING_LENGTH_PRESET_VALUES) {+ expect(isCustomUpcomingLength(v)).toBe(false);+ }++ expect(isCustomUpcomingLength('1-day')).toBe(true);+ expect(isCustomUpcomingLength('2-week')).toBe(true);+ expect(isCustomUpcomingLength(null)).toBe(false);+ expect(isCustomUpcomingLength(undefined)).toBe(false);+ });+ });});diff --git a/packages/loot-core/src/shared/schedules.ts b/packages/loot-core/src/shared/schedules.tsindex 034de54d4f..9f9a2d4adb 100644--- a/packages/loot-core/src/shared/schedules.ts+++ b/packages/loot-core/src/shared/schedules.ts@@ -8,11 +8,52 @@ import type { RuleConditionEntity, ScheduleEntity } from '#types/models';import * as monthUtils from './months';import { q } from './query';+export const DEFAULT_UPCOMING_SCHEDULE_DAYS = '7';++// Preset token values used by UI selects. Keep labels in the UI (i18n) but+// centralize the canonical preset tokens so all components share the same set.+export const UPCOMING_LENGTH_PRESET_VALUES = [+ '1',+ '7',+ '14',+ 'oneMonth',+ 'currentMonth',+] as const;++export type UpcomingLengthPresetValue =+ (typeof UPCOMING_LENGTH_PRESET_VALUES)[number];++export const UPCOMING_LENGTH_PRESET_LABELS: Record<+ UpcomingLengthPresetValue,+ string+> = {+ '1': '1 day',+ '7': '1 week',+ '14': '2 weeks',+ oneMonth: '1 month',+ currentMonth: 'End of the current month',+};++export const UPCOMING_LENGTH_PRESET_OPTIONS: {+ value: UpcomingLengthPresetValue;+ labelKey: string;+}[] = UPCOMING_LENGTH_PRESET_VALUES.map(v => ({+ value: v,+ labelKey: UPCOMING_LENGTH_PRESET_LABELS[v],+}));++export function isCustomUpcomingLength(value: string | null | undefined) {+ if (value == null) return false;+ return (+ (UPCOMING_LENGTH_PRESET_VALUES as readonly string[]).indexOf(value) === -1+ );+}+export function getStatus(nextDate: string,completed: boolean,hasTrans: boolean,- upcomingLength: string = '7',+ upcomingLength: string = DEFAULT_UPCOMING_SCHEDULE_DAYS,) {const upcomingDays = getUpcomingDays(upcomingLength);const today = monthUtils.currentDay();@@ -306,7 +347,7 @@ export function getScheduledAmount(}export function getUpcomingDays(- upcomingLength = '7',+ upcomingLength = DEFAULT_UPCOMING_SCHEDULE_DAYS,today = monthUtils.currentDay(), // for testability): number {const month = monthUtils.getMonth(today);diff --git a/upcoming-release-notes/create-schedule-from-future-transaction.md b/upcoming-release-notes/create-schedule-from-future-transaction.mdnew file mode 100644index 0000000000..bc69ca0bcb--- /dev/null+++ b/upcoming-release-notes/create-schedule-from-future-transaction.md@@ -0,0 +1,6 @@+---+category: Enhancements+authors: [CalebBurton]+---++Replace the "Convert to Schedule" prompt for future-dated transactions with a new "Schedule" button, which asks for confirmation only when the scheduled date falls beyond your upcoming length setting. You can also press Ctrl+Shift+Enter (Cmd+Shift+Enter on macOS) in the new transaction row to create a schedule.