A local-first personal finance app
♻️ (typescript) refactor ScheduleDetails to tsx (#3964)
Matiss Janis Aboltinsaf0a14ce3dc9
diff --git a/packages/desktop-client/src/components/schedules/ScheduleDetails.jsx b/packages/desktop-client/src/components/schedules/ScheduleDetails.tsxsimilarity index 79%rename from packages/desktop-client/src/components/schedules/ScheduleDetails.jsxrename to packages/desktop-client/src/components/schedules/ScheduleDetails.tsxindex 8e185e5cc5..6d02f34d1e 100644--- a/packages/desktop-client/src/components/schedules/ScheduleDetails.jsx+++ b/packages/desktop-client/src/components/schedules/ScheduleDetails.tsx@@ -1,3 +1,4 @@+// @ts-strict-ignoreimport React, { useEffect, useReducer } from 'react';import { Trans, useTranslation } from 'react-i18next';import { useDispatch } from 'react-redux';@@ -11,6 +12,12 @@ import { send, sendCatch } from 'loot-core/src/platform/client/fetch';import * as monthUtils from 'loot-core/src/shared/months';import { q } from 'loot-core/src/shared/query';import { extractScheduleConds } from 'loot-core/src/shared/schedules';+import {+ type TransactionEntity,+ type ScheduleEntity,+ type RuleConditionOp,+ type RecurConfig,+} from 'loot-core/types/models';import { useDateFormat } from '../../hooks/useDateFormat';import { usePayees } from '../../hooks/usePayees';@@ -33,10 +40,30 @@ import { SimpleTransactionsTable } from '../transactions/SimpleTransactionsTableimport { AmountInput, BetweenAmountInput } from '../util/AmountInput';import { GenericInput } from '../util/GenericInput';-function updateScheduleConditions(schedule, fields) {+type Fields = {+ payee: null | string;+ account: null | string;+ amount: null | number | { num1: number; num2: number };+ amountOp: null | string;+ date: null | string | RecurConfig;+ posts_transaction: boolean;+ name: null | string;+};++function updateScheduleConditions(+ schedule: Partial<ScheduleEntity>,+ fields: Fields,+) {const conds = extractScheduleConds(schedule._conditions);- const updateCond = (cond, op, field, value) => {+ const updateCond = (+ cond: ReturnType<typeof extractScheduleConds>[keyof ReturnType<+ typeof extractScheduleConds+ >],+ op: RuleConditionOp,+ field: string,+ value: (typeof fields)[keyof typeof fields],+ ) => {if (cond) {return { ...cond, value };}@@ -69,11 +96,16 @@ function updateScheduleConditions(schedule, fields) {field: 'amount',value: fields.amount,},- ].filter(Boolean),+ ].filter(val => !!val),};}-export function ScheduleDetails({ id, transaction }) {+type ScheduleDetailsProps = {+ id: string;+ transaction: TransactionEntity;+};++export function ScheduleDetails({ id, transaction }: ScheduleDetailsProps) {const { t } = useTranslation();const adding = id == null;@@ -83,7 +115,67 @@ export function ScheduleDetails({ id, transaction }) {const dateFormat = useDateFormat() || 'MM/dd/yyyy';const [state, dispatch] = useReducer(- (state, action) => {+ (+ state: {+ isCustom?: boolean;+ schedule: null | Partial<ScheduleEntity>;+ upcomingDates: null | string[];+ error: null | string;+ fields: Fields;+ transactions: TransactionEntity[];+ transactionsMode: 'matched' | 'linked';+ },+ action:+ | {+ type: 'set-schedule';+ schedule: Partial<ScheduleEntity>;+ }+ | {+ type: 'set-field';+ field: 'name' | 'account' | 'payee';+ value: string;+ }+ | {+ type: 'set-field';+ field: 'amountOp';+ value: 'is' | 'isbetween' | 'isapprox';+ }+ | {+ type: 'set-field';+ field: 'amount';+ value: number | { num1: number; num2: number };+ }+ | {+ type: 'set-field';+ field: 'date';+ value: string | RecurConfig;+ }+ | {+ type: 'set-field';+ field: 'posts_transaction';+ value: boolean;+ }+ | {+ type: 'set-transactions';+ transactions: TransactionEntity[];+ }+ | {+ type: 'set-repeats';+ repeats: boolean;+ }+ | {+ type: 'set-upcoming-dates';+ dates: null | string[];+ }+ | {+ type: 'form-error';+ error: null | string;+ }+ | {+ type: 'switch-transactions';+ mode: 'matched' | 'linked';+ },+ ) => {switch (action.type) {case 'set-schedule': {const schedule = action.schedule;@@ -91,31 +183,34 @@ export function ScheduleDetails({ id, transaction }) {// See if there are custom rulesconst conds = extractScheduleConds(schedule._conditions);const condsSet = new Set(Object.values(conds));- const isCustom =- schedule._conditions.find(c => !condsSet.has(c)) ||- schedule._actions.find(a => a.op !== 'link-schedule');+ const isCustom = !!(+ schedule._conditions?.find(c => !condsSet.has(c)) ||+ schedule._actions?.find(a => a.op !== 'link-schedule')+ );return {...state,schedule: action.schedule,isCustom,fields: {- payee: schedule._payee,- account: schedule._account,+ payee: schedule._payee ?? null,+ account: schedule._account ?? null,amount: schedule._amount || 0,amountOp: schedule._amountOp || 'isapprox',- date: schedule._date,- posts_transaction: action.schedule.posts_transaction,- name: schedule.name,+ date: schedule._date ?? null,+ posts_transaction: action.schedule.posts_transaction ?? false,+ name: schedule.name ?? null,},};}- case 'set-field':+ case 'set-field': {if (!(action.field in state.fields)) {throw new Error('Unknown field: ' + action.field);}- const fields = { [action.field]: action.value };+ const fields: { [key: string]: typeof action.value | undefined } = {+ [action.field]: action.value,+ };// If we are changing the amount operator either to or// away from the `isbetween` operator, the amount value is@@ -141,7 +236,7 @@ export function ScheduleDetails({ id, transaction }) {fields.amount =typeof state.fields.amount === 'number'? state.fields.amount- : state.fields.amount.num1;+ : state.fields.amount?.num1;}}@@ -149,41 +244,52 @@ export function ScheduleDetails({ id, transaction }) {...state,fields: { ...state.fields, ...fields },};- case 'set-transactions':+ }++ case 'set-transactions': {if (fromTrans && action.transactions) {action.transactions.sort(a => {return transaction.id === a.id ? -1 : 1;});}return { ...state, transactions: action.transactions };- case 'set-repeats':+ }++ case 'set-repeats': {return {...state,fields: {...state.fields,date: action.repeats- ? {+ ? ({frequency: 'monthly',+ endMode: 'never',start: monthUtils.currentDay(),patterns: [],- }+ } satisfies RecurConfig): monthUtils.currentDay(),},};- case 'set-upcoming-dates':+ }++ case 'set-upcoming-dates': {return {...state,upcomingDates: action.dates,};+ }- case 'form-error':+ case 'form-error': {return { ...state, error: action.error };+ }- case 'switch-transactions':+ case 'switch-transactions': {return { ...state, transactionsMode: action.mode };+ }- default:- throw new Error('Unknown action: ' + action.type);+ default: {+ throw new Error('Unknown action');+ }}},{@@ -219,11 +325,11 @@ export function ScheduleDetails({ id, transaction }) {skipWeekend: false,weekendSolveMode: 'after',endMode: 'never',- endOccurrences: '1',+ endOccurrences: 1,endDate: monthUtils.currentDay(),- };+ } satisfies RecurConfig;- const schedule = fromTrans+ const schedule: Partial<ScheduleEntity> = fromTrans? {posts_transaction: false,_conditions: [{ op: 'isapprox', field: 'date', value: date }],@@ -258,30 +364,33 @@ export function ScheduleDetails({ id, transaction }) {}run();+ // eslint-disable-next-line react-hooks/exhaustive-deps}, []);useEffect(() => {async function run() {const date = state.fields.date;- if (date == null) {+ if (date === null) {dispatch({ type: 'set-upcoming-dates', dates: null });- } else {- if (date.frequency) {- const { data } = await sendCatch('schedule/get-upcoming-dates', {- config: date,- count: 3,- });- dispatch({ type: 'set-upcoming-dates', dates: data });+ return;+ }++ if (typeof date === 'string') {+ const today = monthUtils.currentDay();+ if (date === today || monthUtils.isAfter(date, today)) {+ dispatch({ type: 'set-upcoming-dates', dates: [date] });} else {- const today = monthUtils.currentDay();- if (date === today || monthUtils.isAfter(date, today)) {- dispatch({ type: 'set-upcoming-dates', dates: [date] });- } else {- dispatch({ type: 'set-upcoming-dates', dates: null });- }+ dispatch({ type: 'set-upcoming-dates', dates: null });}+ return;}++ const { data } = await sendCatch('schedule/get-upcoming-dates', {+ config: date,+ count: 3,+ });+ dispatch({ type: 'set-upcoming-dates', dates: data });}run();}, [state.fields.date]);@@ -292,7 +401,7 @@ export function ScheduleDetails({ id, transaction }) {state.schedule.id &&state.transactionsMode === 'linked') {- const live = liveQuery(+ const live = liveQuery<TransactionEntity>(q('transactions').filter({ schedule: state.schedule.id }).select('*')@@ -308,21 +417,20 @@ export function ScheduleDetails({ id, transaction }) {useEffect(() => {let current = true;- let unsubscribe;+ let unsubscribe: (() => void) | undefined;if (state.schedule && state.transactionsMode === 'matched') {- const { error, conditions: originalConditions } =- updateScheduleConditions(state.schedule, state.fields);+ const updated = updateScheduleConditions(state.schedule, state.fields);- if (error) {- dispatch({ type: 'form-error', error });+ if ('error' in updated) {+ dispatch({ type: 'form-error', error: updated.error });return;}// *Extremely* gross hack because the rules are not mapped to// public names automatically. We really should be doing that// at the database layer- const conditions = originalConditions.map(cond => {+ const conditions = updated.conditions.map(cond => {if (cond.field === 'description') {return { ...cond, field: 'payee' };} else if (cond.field === 'acct') {@@ -335,7 +443,7 @@ export function ScheduleDetails({ id, transaction }) {conditions,}).then(({ filters }) => {if (current) {- const live = liveQuery(+ const live = liveQuery<TransactionEntity>(q('transactions').filter({ $and: filters }).select('*')@@ -364,13 +472,13 @@ export function ScheduleDetails({ id, transaction }) {transaction ? [transaction.id] : [],);- async function onSave(close) {+ async function onSave(close: () => void, schedule: Partial<ScheduleEntity>) {dispatch({ type: 'form-error', error: null });if (state.fields.name) {const { data: sameName } = await runQuery(q('schedules').filter({ name: state.fields.name }).select('id'),);- if (sameName.length > 0 && sameName[0].id !== state.schedule.id) {+ if (sameName.length > 0 && sameName[0].id !== schedule.id) {dispatch({type: 'form-error',error: t('There is already a schedule with this name'),@@ -380,7 +488,7 @@ export function ScheduleDetails({ id, transaction }) {}const { error, conditions } = updateScheduleConditions(- state.schedule,+ schedule,state.fields,);@@ -393,7 +501,7 @@ export function ScheduleDetails({ id, transaction }) {adding ? 'schedule/create' : 'schedule/update',{schedule: {- id: state.schedule.id,+ id: schedule.id,posts_transaction: state.fields.posts_transaction,name: state.fields.name,},@@ -418,8 +526,8 @@ export function ScheduleDetails({ id, transaction }) {close();}- async function onEditRule(ruleId) {- const rule = await send('rule-get', { id: ruleId || state.schedule.rule });+ async function onEditRule(id: string) {+ const rule = await send('rule-get', { id });globalDispatch(pushModal('edit-rule', {@@ -432,35 +540,41 @@ export function ScheduleDetails({ id, transaction }) {);}- async function onLinkTransactions(ids, scheduleId) {+ async function onLinkTransactions(ids: string[], scheduleId?: string) {await send('transactions-batch-update', {updated: ids.map(id => ({id,- schedule: scheduleId || state.schedule.id,+ schedule: scheduleId,})),});selectedInst.dispatch({ type: 'select-none' });}- async function onUnlinkTransactions(ids) {+ async function onUnlinkTransactions(ids: string[]) {await send('transactions-batch-update', {updated: ids.map(id => ({ id, schedule: null })),});selectedInst.dispatch({ type: 'select-none' });}- if (state.schedule == null) {+ const { schedule } = state;++ if (schedule == null) {return null;}- function onSwitchTransactions(mode) {+ function onSwitchTransactions(mode: 'linked' | 'matched') {dispatch({ type: 'switch-transactions', mode });selectedInst.dispatch({ type: 'select-none' });}- const payee = payees ? payees[state.fields.payee] : null;+ const payee =+ payees && state.fields.payee ? payees[state.fields.payee] : null;// This is derived from the date- const repeats = state.fields.date ? !!state.fields.date.frequency : false;+ const repeats =+ state.fields.date && typeof state.fields.date !== 'string'+ ? !!state.fields.date.frequency+ : false;return (<Modal name="schedule-edit">{({ state: { close } }) => (@@ -477,6 +591,7 @@ export function ScheduleDetails({ id, transaction }) {<FormField style={{ flex: 1 }}><FormLabel title={t('Schedule Name')} htmlFor="name-field" /><InitialFocus>+ {/* @ts-expect-error should be auto-patched once GenericInput is converted to TS */}<GenericInputfield="string"type="string"@@ -530,6 +645,7 @@ export function ScheduleDetails({ id, transaction }) {htmlFor="amount-field"style={{ margin: 0, flex: 1 }}/>+ {/* @ts-expect-error should be auto-patched once GenericInput is converted to TS */}<OpSelectops={['isapprox', 'is', 'isbetween']}value={state.fields.amountOp}@@ -561,6 +677,7 @@ export function ScheduleDetails({ id, transaction }) {</Stack>{state.fields.amountOp === 'isbetween' ? (<BetweenAmountInput+ // @ts-expect-error fix medefaultValue={state.fields.amount}onChange={value =>dispatch({@@ -573,6 +690,7 @@ export function ScheduleDetails({ id, transaction }) {) : (<AmountInputid="amount-field"+ // @ts-expect-error fix mevalue={state.fields.amount}onUpdate={value =>dispatch({@@ -594,6 +712,7 @@ export function ScheduleDetails({ id, transaction }) {<View style={{ width: '13.44rem' }}>{repeats ? (<RecurringSchedulePicker+ // @ts-expect-error fix mevalue={state.fields.date}onChange={value =>dispatch({ type: 'set-field', field: 'date', value })@@ -601,6 +720,7 @@ export function ScheduleDetails({ id, transaction }) {/>) : (<DateSelect+ // @ts-expect-error fix mevalue={state.fields.date}onSelect={date =>dispatch({ type: 'set-field', field: 'date', value: date })@@ -694,7 +814,7 @@ export function ScheduleDetails({ id, transaction }) {</Trans></Text>- {!adding && state.schedule.rule && (+ {!adding && schedule.rule && (<Stack direction="row" align="center" style={{ marginTop: 20 }}>{state.isCustom && (<Text@@ -710,7 +830,10 @@ export function ScheduleDetails({ id, transaction }) {</Trans></Text>)}- <Button onPress={() => onEditRule()} isDisabled={adding}>+ <Button+ onPress={() => onEditRule(schedule.rule)}+ isDisabled={adding}+ ><Trans>Edit as rule</Trans></Button></Stack>@@ -771,7 +894,7 @@ export function ScheduleDetails({ id, transaction }) {onSelect={(name, ids) => {switch (name) {case 'link':- onLinkTransactions(ids);+ onLinkTransactions(ids, schedule.id);break;case 'unlink':onUnlinkTransactions(ids);@@ -818,7 +941,7 @@ export function ScheduleDetails({ id, transaction }) {<Buttonvariant="primary"onPress={() => {- onSave(close);+ onSave(close, schedule);}}>{adding ? t('Add') : t('Save')}@@ -830,7 +953,12 @@ export function ScheduleDetails({ id, transaction }) {);}-function NoTransactionsMessage(props) {+type NoTransactionsMessageProps = {+ error: string | null;+ transactionsMode: 'matched' | 'linked';+};++function NoTransactionsMessage(props: NoTransactionsMessageProps) {const { t } = useTranslation();return (diff --git a/packages/desktop-client/src/components/util/AmountInput.tsx b/packages/desktop-client/src/components/util/AmountInput.tsxindex d83d558ab0..b14a24b739 100644--- a/packages/desktop-client/src/components/util/AmountInput.tsx+++ b/packages/desktop-client/src/components/util/AmountInput.tsx@@ -154,7 +154,15 @@ export function AmountInput({);}-export function BetweenAmountInput({ defaultValue, onChange }) {+type BetweenAmountInputProps = {+ defaultValue: { num1: number; num2: number };+ onChange: (newValue: { num1: number; num2: number }) => void;+};++export function BetweenAmountInput({+ defaultValue,+ onChange,+}: BetweenAmountInputProps) {const { t } = useTranslation();const [num1, setNum1] = useState(defaultValue.num1);const [num2, setNum2] = useState(defaultValue.num2);diff --git a/packages/desktop-client/src/hooks/useSelected.tsx b/packages/desktop-client/src/hooks/useSelected.tsxindex a2052e333d..ceab8ce560 100644--- a/packages/desktop-client/src/hooks/useSelected.tsx+++ b/packages/desktop-client/src/hooks/useSelected.tsx@@ -8,6 +8,7 @@ import React, {useRef,type Dispatch,type ReactElement,+ type ReactNode,} from 'react';import { useSelector } from 'react-redux';@@ -257,7 +258,7 @@ export function useSelectedItems() {type SelectedProviderProps<T extends Item> = {instance: ReturnType<typeof useSelected<T>>;fetchAllIds?: () => Promise<string[]>;- children: ReactElement;+ children: ReactNode;};export function SelectedProvider<T extends Item>({diff --git a/packages/loot-core/src/client/query-helpers.ts b/packages/loot-core/src/client/query-helpers.tsindex c1e63e156c..b566d705f1 100644--- a/packages/loot-core/src/client/query-helpers.ts+++ b/packages/loot-core/src/client/query-helpers.ts@@ -45,7 +45,7 @@ export function pagedQuery<TResponse = unknown>();}-type Data<TResponse> = ReadonlyArray<TResponse>;+type Data<TResponse> = TResponse[];type Listener<TResponse = unknown> = (data: Data<TResponse>,diff --git a/packages/loot-core/src/types/models/rule.d.ts b/packages/loot-core/src/types/models/rule.d.tsindex 8d85f2c663..aa2aa6e5f3 100644--- a/packages/loot-core/src/types/models/rule.d.ts+++ b/packages/loot-core/src/types/models/rule.d.ts@@ -1,4 +1,4 @@-import { type ScheduleEntity } from './schedule';+import { type RecurConfig, type ScheduleEntity } from './schedule';export interface NewRuleEntity {stage: 'pre' | null | 'post';@@ -31,11 +31,11 @@ export type RuleConditionOp =| 'onBudget'| 'offBudget';-type FieldValueTypes = {+export type FieldValueTypes = {account: string;amount: number;category: string;- date: string;+ date: string | RecurConfig;notes: string;payee: string;payee_name: string;@@ -55,7 +55,9 @@ type BaseConditionEntity<op: Op;value: Op extends 'oneOf' | 'notOneOf'? Array<FieldValueTypes[Field]>- : FieldValueTypes[Field];+ : Op extends 'isbetween'+ ? { num1: number; num2: number }+ : FieldValueTypes[Field];options?: {inflow?: boolean;outflow?: boolean;diff --git a/packages/loot-core/src/types/models/schedule.d.ts b/packages/loot-core/src/types/models/schedule.d.tsindex 1fdc885da4..16ff20442e 100644--- a/packages/loot-core/src/types/models/schedule.d.ts+++ b/packages/loot-core/src/types/models/schedule.d.ts@@ -1,6 +1,6 @@import type { AccountEntity } from './account';import type { PayeeEntity } from './payee';-import type { RuleEntity } from './rule';+import type { RuleConditionEntity, RuleEntity } from './rule';export interface RecurPattern {value: number;@@ -9,7 +9,7 @@ export interface RecurPattern {export interface RecurConfig {frequency: 'daily' | 'weekly' | 'monthly' | 'yearly';- interval: number;+ interval?: number;patterns?: RecurPattern[];skipWeekend?: boolean;start: string;@@ -35,8 +35,8 @@ export interface ScheduleEntity {_amount: number | { num1: number; num2: number };_amountOp: string;_date: RecurConfig;- _conditions: unknown;- _actions: unknown;+ _conditions: RuleConditionEntity[];+ _actions: Array<{ op: unknown }>;}export type DiscoverScheduleEntity = {@@ -45,18 +45,5 @@ export type DiscoverScheduleEntity = {payee: PayeeEntity['id'];date: ScheduleEntity['_date'];amount: ScheduleEntity['_amount'];- _conditions: Array<- | { op: 'is'; field: 'account'; value: AccountEntity['id'] }- | { op: 'is'; field: 'payee'; value: PayeeEntity['id'] }- | {- op: 'is' | 'isapprox';- field: 'date';- value: ScheduleEntity['_date'];- }- | {- op: 'is' | 'isapprox';- field: 'amount';- value: ScheduleEntity['_amount'];- }- >;+ _conditions: ScheduleEntity['_conditions'];};diff --git a/packages/loot-core/src/types/server-handlers.d.ts b/packages/loot-core/src/types/server-handlers.d.tsindex 4c623262c0..24032b4b5d 100644--- a/packages/loot-core/src/types/server-handlers.d.ts+++ b/packages/loot-core/src/types/server-handlers.d.ts@@ -122,7 +122,7 @@ export interface ServerHandlers {'payees-get-rules': (arg: { id: string }) => Promise<RuleEntity[]>;'make-filters-from-conditions': (arg: {- conditions;+ conditions: unknown;}) => Promise<{ filters: unknown[] }>;getCell: (arg: {diff --git a/upcoming-release-notes/3964.md b/upcoming-release-notes/3964.mdnew file mode 100644index 0000000000..377b604a7e--- /dev/null+++ b/upcoming-release-notes/3964.md@@ -0,0 +1,6 @@+---+category: Maintenance+authors: [MatissJanis]+---++TypeScript: move ScheduleDetails to tsx.