A local-first personal finance app
[AI] Add opt-in checkbox to sync transfer date to other side (#8454)
Stephen Brown II6aee7eee58c9
diff --git a/packages/desktop-client/package.json b/packages/desktop-client/package.jsonindex 8a4baca5ae..80cab384df 100644--- a/packages/desktop-client/package.json+++ b/packages/desktop-client/package.json@@ -73,6 +73,7 @@"#components/reports/util": "./src/components/reports/util.ts","#components/schedules": "./src/components/schedules/index.tsx","#components/schedules/schedule-edit-utils": "./src/components/schedules/schedule-edit-utils.ts",+ "#components/select/getFirstDayOfWeek": "./src/components/select/getFirstDayOfWeek.ts","#components/transactions/table/columns": "./src/components/transactions/table/columns.ts","#components/transactions/table/utils": "./src/components/transactions/table/utils.ts","#components/util/accountValidation": "./src/components/util/accountValidation.ts",diff --git a/packages/desktop-client/src/components/common/TransferDirectionIcon.tsx b/packages/desktop-client/src/components/common/TransferDirectionIcon.tsxnew file mode 100644index 0000000000..5a483138a1--- /dev/null+++ b/packages/desktop-client/src/components/common/TransferDirectionIcon.tsx@@ -0,0 +1,18 @@+import { SvgLeftArrow2, SvgRightArrow2 } from '@actual-app/components/icons/v0';+import type { CSSProperties } from '@actual-app/components/styles';++type TransferDirectionIconProps = {+ isDeposit?: boolean;+ style?: CSSProperties;+};++export function TransferDirectionIcon({+ isDeposit,+ style,+}: TransferDirectionIconProps) {+ return isDeposit ? (+ <SvgLeftArrow2 style={style} />+ ) : (+ <SvgRightArrow2 style={style} />+ );+}diff --git a/packages/desktop-client/src/components/forms/LabeledCheckbox.tsx b/packages/desktop-client/src/components/forms/LabeledCheckbox.tsxindex 9121292afd..4295448b8d 100644--- a/packages/desktop-client/src/components/forms/LabeledCheckbox.tsx+++ b/packages/desktop-client/src/components/forms/LabeledCheckbox.tsx@@ -11,6 +11,7 @@ type LabeledCheckboxProps = {checked?: ComponentProps<typeof Checkbox>['checked'];disabled?: ComponentProps<typeof Checkbox>['disabled'];onChange?: ComponentProps<typeof Checkbox>['onChange'];+ onMouseDown?: ComponentProps<typeof View>['onMouseDown'];children: ReactNode;style?: CSSProperties;};@@ -20,11 +21,13 @@ export function LabeledCheckbox({checked,disabled,onChange,+ onMouseDown,children,style,}: LabeledCheckboxProps) {return (<View+ onMouseDown={onMouseDown}style={{flex: 1,flexDirection: 'row',diff --git a/packages/desktop-client/src/components/mobile/transactions/TransactionListItem.tsx b/packages/desktop-client/src/components/mobile/transactions/TransactionListItem.tsxindex b46b63a913..9f9d81fa22 100644--- a/packages/desktop-client/src/components/mobile/transactions/TransactionListItem.tsx+++ b/packages/desktop-client/src/components/mobile/transactions/TransactionListItem.tsx@@ -5,11 +5,7 @@ import type { ListBoxItemRenderProps } from 'react-aria-components';import { useTranslation } from 'react-i18next';import { Button } from '@actual-app/components/button';-import {- SvgLeftArrow2,- SvgRightArrow2,- SvgSplit,-} from '@actual-app/components/icons/v0';+import { SvgSplit } from '@actual-app/components/icons/v0';import {SvgArrowsSynchronize,SvgCalendar3,@@ -35,6 +31,7 @@ import {} from '@react-aria/interactions';import { makeAmountFullStyle } from '#components/budget/util';+import { TransferDirectionIcon } from '#components/common/TransferDirectionIcon';import { useAccount } from '#hooks/useAccount';import { useCachedSchedules } from '#hooks/useCachedSchedules';import { useCategories } from '#hooks/useCategories';@@ -438,12 +435,12 @@ function PayeeIcons({ transaction, transferAccount }: PayeeIconsProps) {) : (<SvgCalendar3 style={getScheduleIconStyle({ isPreview })} />))}- {transferAccount &&- (transaction.amount > 0 ? (- <SvgLeftArrow2 style={{ width: 12, height: 12, marginRight: 5 }} />- ) : (- <SvgRightArrow2 style={{ width: 12, height: 12, marginRight: 5 }} />- ))}+ {transferAccount && (+ <TransferDirectionIcon+ isDeposit={transaction.amount > 0}+ style={{ width: 12, height: 12, marginRight: 5 }}+ />+ )}</>);}diff --git a/packages/desktop-client/src/components/reports/Header.tsx b/packages/desktop-client/src/components/reports/Header.tsxindex 470fcb6de1..86e242f494 100644--- a/packages/desktop-client/src/components/reports/Header.tsx+++ b/packages/desktop-client/src/components/reports/Header.tsx@@ -19,7 +19,7 @@ import type { SyncedPrefs } from '@actual-app/core/types/prefs';import { AppliedFilters } from '#components/filters/AppliedFilters';import { FilterButton } from '#components/filters/FiltersMenu';-import { getFirstDayOfWeek } from '#components/select/DateSelect';+import { getFirstDayOfWeek } from '#components/select/getFirstDayOfWeek';import { useDateFormat } from '#hooks/useDateFormat';import { useLanguage } from '#hooks/useLocale';diff --git a/packages/desktop-client/src/components/select/DateSelect.tsx b/packages/desktop-client/src/components/select/DateSelect.tsxindex 89fd9c687e..a8f1bf7e94 100644--- a/packages/desktop-client/src/components/select/DateSelect.tsx+++ b/packages/desktop-client/src/components/select/DateSelect.tsx@@ -24,7 +24,7 @@ import {Heading,I18nProvider,} from 'react-aria-components';-import { useTranslation } from 'react-i18next';+import { Trans, useTranslation } from 'react-i18next';import { useResponsive } from '@actual-app/components/hooks/useResponsive';import {@@ -48,26 +48,14 @@ import { css } from '@emotion/css';import { CalendarDate } from '@internationalized/date';import { addDays, format, isValid, parse, parseISO, subDays } from 'date-fns';+import { LabeledCheckbox } from '#components/forms/LabeledCheckbox';import { InputField } from '#components/mobile/MobileForms';import { useLanguage } from '#hooks/useLocale';import { useMergedRefs } from '#hooks/useMergedRefs';import { useSyncedPref } from '#hooks/useSyncedPref';-const FIRST_DAY_OF_WEEK_NAMES = [- 'sun',- 'mon',- 'tue',- 'wed',- 'thu',- 'fri',- 'sat',-] as const;--type FirstDayOfWeek = (typeof FIRST_DAY_OF_WEEK_NAMES)[number];--export function getFirstDayOfWeek(idx: string | undefined): FirstDayOfWeek {- return FIRST_DAY_OF_WEEK_NAMES[parseInt(idx || '0', 10) || 0];-}+import { getFirstDayOfWeek } from './getFirstDayOfWeek';+import type { FirstDayOfWeek } from './getFirstDayOfWeek';function toCalendarDate(date: Date): CalendarDate {return new CalendarDate(@@ -81,11 +69,13 @@ function fromCalendarDate(date: CalendarDate): Date {return new Date(date.year, date.month - 1, date.day);}+const calendarShadow = '0 0px 4px rgba(0, 0, 0, .25)';+const pickerStyles: CSSProperties = {'& .react-aria-Calendar': {color: theme.calendarText,background: theme.calendarBackground,- boxShadow: '0 0px 4px rgba(0, 0, 0, .25)',+ boxShadow: calendarShadow,borderRadius: 4,padding: 10,},@@ -157,13 +147,17 @@ type DatePickerProps = {firstDayOfWeek: FirstDayOfWeek;onUpdate: (selectedDate: Date) => void;onSelect: (selectedDate: Date) => void;+ attached?: boolean;};type DatePickerForwardedRef = {handleInputKeyDown: (e: KeyboardEvent<HTMLInputElement>) => void;};const DatePicker = forwardRef<DatePickerForwardedRef, DatePickerProps>(- ({ value, dateFormat, locale, firstDayOfWeek, onUpdate, onSelect }, ref) => {+ (+ { value, dateFormat, locale, firstDayOfWeek, onUpdate, onSelect, attached },+ ref,+ ) => {const { t } = useTranslation();const parsedValue = value ? parse(value, dateFormat, currentDate()) : null;const focusedCalendarDate = toCalendarDate(@@ -218,7 +212,17 @@ const DatePicker = forwardRef<DatePickerForwardedRef, DatePickerProps>(return (<View- className={css([pickerStyles, { flex: 1 }])}+ className={css([+ pickerStyles,+ attached && {+ '& .react-aria-Calendar': {+ borderBottomLeftRadius: 0,+ borderBottomRightRadius: 0,+ boxShadow: 'none',+ },+ },+ { flex: 1 },+ ])}data-date-pickeronMouseDown={e => e.preventDefault()}>@@ -286,6 +290,8 @@ type DateSelectProps = {clearOnBlur?: boolean;onUpdate?: (selectedDate: string) => void;onSelect: (selectedDate: string) => void;+ transferDateSyncChecked?: boolean;+ onTransferDateSyncChange?: (checked: boolean) => void;};function DateSelectDesktop({@@ -302,6 +308,8 @@ function DateSelectDesktop({clearOnBlur = true,onUpdate,onSelect,+ transferDateSyncChecked,+ onTransferDateSyncChange,}: DateSelectProps) {const parsedDefaultValue = useMemo(() => {if (defaultValue) {@@ -456,8 +464,7 @@ function DateSelectDesktop({}}onBlur={e => {// react-aria moves focus into the calendar when it's clicked; keep- // the picker open and pull focus back so keyboard entry still works- // (with pikaday, focus never left the input).+ // the picker open and pull focus back so keyboard entry still works.if (e.relatedTarget instanceof Element &&e.relatedTarget.closest('[data-date-picker]')@@ -493,22 +500,48 @@ function DateSelectDesktop({}}/>{maybeWrapTooltip(- <DatePicker- ref={picker}- value={selectedValue}- dateFormat={dateFormat}- locale={locale}- firstDayOfWeek={firstDayOfWeek}- onUpdate={date => {- setSelectedValue(format(date, dateFormat));- onUpdate?.(format(date, 'yyyy-MM-dd'));- }}- onSelect={date => {- setValue(format(date, dateFormat));- onSelect(format(date, 'yyyy-MM-dd'));- setOpen(false);- }}- />,+ <View+ style={+ onTransferDateSyncChange+ ? { borderRadius: 4, boxShadow: calendarShadow }+ : undefined+ }+ >+ <DatePicker+ ref={picker}+ value={selectedValue}+ dateFormat={dateFormat}+ locale={locale}+ firstDayOfWeek={firstDayOfWeek}+ attached={!!onTransferDateSyncChange}+ onUpdate={date => {+ setSelectedValue(format(date, dateFormat));+ onUpdate?.(format(date, 'yyyy-MM-dd'));+ }}+ onSelect={date => {+ setValue(format(date, dateFormat));+ onSelect(format(date, 'yyyy-MM-dd'));+ setOpen(false);+ }}+ />+ {onTransferDateSyncChange && (+ <LabeledCheckbox+ id={`${id ?? 'date-select'}-transfer-date-sync`}+ checked={transferDateSyncChecked}+ onChange={e => onTransferDateSyncChange(e.target.checked)}+ onMouseDown={e => e.preventDefault()}+ style={{+ padding: '6px 8px',+ borderBottomLeftRadius: 4,+ borderBottomRightRadius: 4,+ backgroundColor: theme.calendarBackground,+ color: theme.calendarText,+ }}+ >+ <Trans>Sync both transfer dates</Trans>+ </LabeledCheckbox>+ )}+ </View>,)}</View>);@@ -517,16 +550,18 @@ function DateSelectDesktop({function DateSelectMobile(props: DateSelectProps) {const { style: inputStyle, ...restInputProps } = props.inputProps ?? {};return (- <InputField- id={props.id}- type="date"- value={props.value ?? ''}- onChange={event => {- props.onSelect(event.target.value);- }}- style={{ height: 28, ...inputStyle }}- {...restInputProps}- />+ <View>+ <InputField+ id={props.id}+ type="date"+ value={props.value ?? ''}+ onChange={event => {+ props.onSelect(event.target.value);+ }}+ style={{ height: 28, ...inputStyle }}+ {...restInputProps}+ />+ </View>);}diff --git a/packages/desktop-client/src/components/select/getFirstDayOfWeek.ts b/packages/desktop-client/src/components/select/getFirstDayOfWeek.tsnew file mode 100644index 0000000000..7918fab890--- /dev/null+++ b/packages/desktop-client/src/components/select/getFirstDayOfWeek.ts@@ -0,0 +1,15 @@+const FIRST_DAY_OF_WEEK_NAMES = [+ 'sun',+ 'mon',+ 'tue',+ 'wed',+ 'thu',+ 'fri',+ 'sat',+] as const;++export type FirstDayOfWeek = (typeof FIRST_DAY_OF_WEEK_NAMES)[number];++export function getFirstDayOfWeek(idx: string | undefined): FirstDayOfWeek {+ return FIRST_DAY_OF_WEEK_NAMES[parseInt(idx || '0', 10) || 0];+}diff --git a/packages/desktop-client/src/components/transactions/TransactionsTable.tsx b/packages/desktop-client/src/components/transactions/TransactionsTable.tsxindex e39fca562d..3ca4202a91 100644--- a/packages/desktop-client/src/components/transactions/TransactionsTable.tsx+++ b/packages/desktop-client/src/components/transactions/TransactionsTable.tsx@@ -23,11 +23,7 @@ import { useHotkeys } from 'react-hotkeys-hook';import { Trans, useTranslation } from 'react-i18next';import { Button } from '@actual-app/components/button';-import {- SvgLeftArrow2,- SvgRightArrow2,- SvgSplit,-} from '@actual-app/components/icons/v0';+import { SvgSplit } from '@actual-app/components/icons/v0';import {SvgArrowDown,SvgArrowUp,@@ -50,6 +46,7 @@ import { Text } from '@actual-app/components/text';import { theme } from '@actual-app/components/theme';import { Tooltip } from '@actual-app/components/tooltip';import { View } from '@actual-app/components/view';+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';@@ -87,6 +84,7 @@ import { AccountAutocomplete } from '#components/autocomplete/AccountAutocompletimport { CategoryAutocomplete } from '#components/autocomplete/CategoryAutocomplete';import { PayeeAutocomplete } from '#components/autocomplete/PayeeAutocomplete';import { TagAutocomplete } from '#components/autocomplete/TagAutocomplete';+import { TransferDirectionIcon } from '#components/common/TransferDirectionIcon';import { getStatusProps } from '#components/schedules/StatusBadge';import type { StatusTypes } from '#components/schedules/StatusBadge';import { DateSelect } from '#components/select/DateSelect';@@ -132,6 +130,7 @@ import { useSelectedDispatch, useSelectedItems } from '#hooks/useSelected';import { SheetNameProvider } from '#hooks/useSheetName';import { useSplitsExpanded } from '#hooks/useSplitsExpanded';import type { SplitsExpandedContextValue } from '#hooks/useSplitsExpanded';+import { useSyncedPref } from '#hooks/useSyncedPref';import { pushModal } from '#modals/modalsSlice';import { NotesTagFormatter } from '#notes/NotesTagFormatter';import { addNotification } from '#notifications/notificationsSlice';@@ -902,11 +901,10 @@ function PayeeIcons({}}}>- {isDeposit ? (- <SvgLeftArrow2 style={transferIconStyle} />- ) : (- <SvgRightArrow2 style={transferIconStyle} />- )}+ <TransferDirectionIcon+ isDeposit={isDeposit}+ style={transferIconStyle}+ /></Button>)}</>@@ -1062,6 +1060,12 @@ const Transaction = memo(function Transaction({const [showReconciliationWarning, setShowReconciliationWarning] =useState(false);+ const [syncTransferDatePref, setSyncTransferDatePref] =+ useSyncedPref('sync-transfer-date');+ const syncTransferDate = String(syncTransferDatePref) === 'true';+ const setSyncTransferDate = (checked: boolean) =>+ setSyncTransferDatePref(checked ? 'true' : 'false');+ const transferDateSyncSeq = useRef(0);const onUpdate: TransactionUpdateFunction = async (name, value) => {// Had some issues with this is called twice which is a problem now that we are showing a warning@@ -1210,6 +1214,52 @@ const Transaction = memo(function Transaction({? 'amount': name;onSave(deserialized, subtransactions, deserializedName);++ if (name === 'date' && typeof value === 'string' && syncTransferDate) {+ // transaction's own leg, or a split child's leg+ const transferIds = [+ transaction.transfer_id,+ ...(subtransactions?.map(t => t.transfer_id) ?? []),+ ].filter((id): id is string => Boolean(id));++ if (transferIds.length > 0) {+ const seq = ++transferDateSyncSeq.current;+ void (async () => {+ const updated: { id: string; date: string }[] = transferIds.map(+ id => ({ id, date: value }),+ );++ // sync split parent if the other leg is a split child+ const { data } = (await aqlQuery(+ q('transactions')+ .filter({ id: { $oneof: transferIds } })+ .select(['id', 'is_child', 'parent_id']),+ )) as {+ data: Pick<TransactionEntity, 'id' | 'is_child' | 'parent_id'>[];+ };+ updated.push(+ ...data+ .filter(+ (t): t is typeof t & { parent_id: string } =>+ t.is_child === true && typeof t.parent_id === 'string',+ )+ .map(t => ({ id: t.parent_id, date: value })),+ );++ // a newer date edit started while we were querying: let it win+ if (seq !== transferDateSyncSeq.current) {+ return;+ }++ await send('transactions-batch-update', {+ updated,+ runTransfers: false,+ });+ })().catch(error => {+ console.error('Failed to sync transfer date:', error);+ });+ }+ }}};@@ -1485,7 +1535,11 @@ const Transaction = memo(function Transaction({formatter={date =>date ? formatDate(parseISO(date), dateFormat) : ''}- onExpose={name => !isPreview && onEdit(id, name)}+ onExpose={name => {+ if (!isPreview) {+ onEdit(id, name);+ }+ }}onUpdate={value => {onUpdate('date', value);}}@@ -1506,6 +1560,13 @@ const Transaction = memo(function Transaction({clearOnBluronUpdate={onUpdate}onSelect={onSave}+ transferDateSyncChecked={syncTransferDate}+ onTransferDateSyncChange={+ transaction.transfer_id ||+ subtransactions?.some(t => t.transfer_id)+ ? setSyncTransferDate+ : undefined+ }/>)}</CustomCell>diff --git a/packages/docs/docs/transactions/transfers.md b/packages/docs/docs/transactions/transfers.mdindex fb26229bea..dd4c3a50da 100644--- a/packages/docs/docs/transactions/transfers.md+++ b/packages/docs/docs/transactions/transfers.md@@ -6,7 +6,7 @@ When you create a transfer in Actual, those two transactions are linked and upda-## Creating a transfer+## Creating a TransferIn the **Payee** field of a transaction, choose the account in the dropdown you want to transfer to/from. You can press **Make Transfer** if you want to just see a list of accounts and hide other payees.@@ -18,7 +18,7 @@ A transaction in the corresponding account will automatically be created.If you are importing files, it is recommended to import into a single account and create the transfer first, and then import the second account. This way the transaction in the second account is automatically reconciled to the transfer transaction. If you imported to both accounts first, you can [make a transfer from the already imported transactions](#make-a-transfer-from-two-existing-transactions).-### Make a transfer from two existing transactions+### Make a Transfer from Two Existing Transactions:::noteThis process will only apply when the below conditions are met@@ -37,7 +37,34 @@ Make a transfer of existing transactions in the same way you [bulk-edit transact3. Go to the drop down top right (the arrow below "2 transactions")4. If the transactions are valid to be converted to a transfer, you can click **Make transfer**.-## Deleting a transfer+## Modifying a Transfer++Some fields are tied together across the two halves of a transfer, and some are not.++These fields always update on both sides:++- **Payee**. Moving one side into a different account rewrites the payee on the other side to match.+- **Amount**. The other side always mirrors it, so a **debit** of `10.00` stays paired with a **credit** of `10.00`.+- **Notes**.+- **Schedule**, if the transaction is linked to one.++These fields are independent, and changing one side leaves the other side alone:++- **Cleared** and **reconciled** status, since each account is reconciled against its own statement.+- **Category**. Transfers between two On Budget accounts, or between two Off Budget accounts, have no category at all. For a transfer between an On Budget and an Off Budget account, the category lives only on the On Budget side.+- **Date**, unless you ask for it to be synced.++### Syncing the Transfer Date++By default, changing the date on one side of a transfer leaves the other side where it is. This is useful when the money takes a few days to arrive, so the two accounts see the transaction on different dates, and your Actual register can match the Bank register exactly.++If you want both dates to move together, tick **Sync both transfer dates** at the bottom of the date picker, then choose the new date. The other side of the transfer is moved to the same date.++++The checkbox stays ticked for future edits until you untick it, so you can pick the behavior you use most often and forget about it.++## Deleting a TransferDelete a transfer the same way you delete any transaction: hover over it and press the **X** on the left. Deleting a transfer transaction always deletes both the transaction in the currently open account, as well as the transfer transaction in the other account.@@ -47,6 +74,6 @@ Transfers between On Budget accounts don't have a category. This is because theTransfers between Off Budget and On Budget accounts are different. Only one half of the transfer exists on your budget and, from the perspective of your budget, is the same as a regular transaction. You can create these transfers just the same as an On Budget transfer, but you will be asked to assign a category on the On Budget side of the transfer.-## Payee rules+## Payee RulesTransfers are actually just custom payees, so if you want to you can [create custom rules for them](./payees.md#transfer-payees).diff --git a/packages/docs/static/img/transfers/transfers-sync-both-dates.png b/packages/docs/static/img/transfers/transfers-sync-both-dates.pngnew file mode 100644index 0000000000..e420167324Binary files /dev/null and b/packages/docs/static/img/transfers/transfers-sync-both-dates.png differdiff --git a/packages/loot-core/src/types/prefs.ts b/packages/loot-core/src/types/prefs.tsindex 8b993db334..0275589a4f 100644--- a/packages/loot-core/src/types/prefs.ts+++ b/packages/loot-core/src/types/prefs.ts@@ -40,6 +40,7 @@ export type SyncedPrefs = Partial<| 'transaction-table-columns'| `transaction-table-columns-${string}`| `show-group-${string}`+ | 'sync-transfer-date'// TODO: pull from src/components/modals/ImportTransactions.js| `parse-date-${string}-${'csv' | 'qif'}`| `import-reimport-deleted-${string}`diff --git a/upcoming-release-notes/transfer-date-sync-checkbox.md b/upcoming-release-notes/transfer-date-sync-checkbox.mdnew file mode 100644index 0000000000..358049f6ec--- /dev/null+++ b/upcoming-release-notes/transfer-date-sync-checkbox.md@@ -0,0 +1,6 @@+---+category: Enhancements+authors: [StephenBrown2]+---++Add an opt-in checkbox under the date picker for transfer transactions to also update the date of the other side of the transfer