Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix send types in a number of places (2/2) #4147

Merged
merged 3 commits into from
Jan 20, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions packages/desktop-client/src/components/accounts/Account.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -480,7 +480,11 @@ class AccountInternal extends PureComponent<
}

fetchAllIds = async () => {
const { data } = await runQuery(this.paged?.query.select('id'));
if (!this.paged) {
return [];
}

const { data } = await runQuery(this.paged.query.select('id'));
// Remember, this is the `grouped` split type so we need to deal
// with the `subtransactions` property
return data.reduce((arr: string[], t: TransactionEntity) => {
Expand Down Expand Up @@ -709,12 +713,12 @@ class AccountInternal extends PureComponent<
};

async calculateBalances() {
if (!this.canCalculateBalance()) {
if (!this.canCalculateBalance() || !this.paged) {
jfdoming marked this conversation as resolved.
Show resolved Hide resolved
return null;
}

const { data } = await runQuery(
this.paged?.query
this.paged.query
.options({ splits: 'none' })
.select([{ balance: { $sumOver: '$amount' } }]),
);
Expand Down Expand Up @@ -930,8 +934,12 @@ class AccountInternal extends PureComponent<
}

getFilteredAmount = async () => {
if (!this.paged) {
return 0;
}

const { data: amount } = await runQuery(
this.paged?.query.calculate({ $sum: '$amount' }),
this.paged.query.calculate({ $sum: '$amount' }),
);
return amount;
};
Expand Down
8 changes: 4 additions & 4 deletions packages/desktop-client/src/components/modals/EditUser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -83,14 +83,14 @@ function useSaveUser() {
user: User,
setError: (error: string) => void,
): Promise<boolean> {
const res = (await send(method, user)) || {};
if (!res['error']) {
const newId = res['id'];
const res = await send(method, user);
if (!('error' in res)) {
const newId = res.id;
if (newId) {
user.id = newId;
}
} else {
const error = res['error'];
const error = res.error;
setError(getUserDirectoryErrors(error));
if (error === 'token-expired') {
dispatch(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ export function Overview() {
const res = await send('dashboard-import', { filepath });
setIsImporting(false);

if (res.error) {
if ('error' in res) {
switch (res.error) {
case 'json-parse-error':
dispatch(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,11 @@ function reducer(state: ReducerState, action: ReducerAction): ReducerState {
}
}

function SchedulePreview({ previewDates }: { previewDates: Date[] }) {
function SchedulePreview({
previewDates,
}: {
previewDates: string[] | string;
}) {
const dateFormat = (useDateFormat() || 'MM/dd/yyyy')
.replace('MM', 'M')
.replace('dd', 'd');
Expand Down Expand Up @@ -369,7 +373,9 @@ function RecurringScheduleTooltip({
onSave: (config: RecurConfig) => void;
}) {
const { t } = useTranslation();
const [previewDates, setPreviewDates] = useState(null);
const [previewDates, setPreviewDates] = useState<string[] | string | null>(
null,
);

const { FREQUENCY_OPTIONS } = useFrequencyOptions();

Expand Down
7 changes: 2 additions & 5 deletions packages/loot-core/src/client/actions/budgets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,14 +148,11 @@ export function createBudget({ testMode = false, demoMode = false } = {}) {
};
}

export function validateBudgetName(name: string): {
valid: boolean;
message?: string;
} {
export function validateBudgetName(name: string) {
return send('validate-budget-name', { name });
}

export function uniqueBudgetName(name: string): string {
export function uniqueBudgetName(name: string) {
return send('unique-budget-name', { name });
}

Expand Down
2 changes: 1 addition & 1 deletion packages/loot-core/src/client/actions/prefs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export function loadPrefs() {
);

// We need to load translations before the app renders
setI18NextLanguage(globalPrefs.language);
setI18NextLanguage(globalPrefs.language ?? '');

return prefs;
};
Expand Down
2 changes: 1 addition & 1 deletion packages/loot-core/src/client/data-hooks/transactions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ export function usePreviewTransactions(): UsePreviewTransactionsResult {
if (!isUnmounted) {
const withDefaults = newTrans.map(t => ({
...t,
category: statuses.get(t.schedule),
category: t.schedule != null ? statuses.get(t.schedule) : undefined,
schedule: t.schedule,
subtransactions: t.subtransactions?.map(
(st: TransactionEntity) => ({
Expand Down
4 changes: 2 additions & 2 deletions packages/loot-core/src/client/query-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { listen, send } from '../platform/client/fetch';
import { once } from '../shared/async';
import { getPrimaryOrderBy, type Query } from '../shared/query';

export async function runQuery(query) {
export async function runQuery(query: Query) {
return send('query', query.serialize());
}

Expand Down Expand Up @@ -207,7 +207,7 @@ export class LiveQuery<TResponse = unknown> {
protected fetchData = async (
runQuery: () => Promise<{
data: Data<TResponse>;
dependencies: Set<string>;
dependencies: string[];
jfdoming marked this conversation as resolved.
Show resolved Hide resolved
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice! This is definitely an array of table names

}>,
) => {
// TODO: precompile queries, or cache compilation results on the
Expand Down
3 changes: 2 additions & 1 deletion packages/loot-core/src/platform/client/fetch/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@ export type Unlisten = typeof unlisten;
/** Mock functions */
export function initServer(handlers: {
query: (query: { table: string; selectExpressions: unknown }) => Promise<{
data: unknown;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just curious, what issue was the unknown causing?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This particular instance didn't cause any error. The other one in server-handlers.d.ts causes a bunch of errors like Type 'unknown' is not assignable to type 'number' because the result type of a query varies wildly based on the query being run. We could totally have better types here in the future!

Happy to revert the mock if you like, but my thinking is it would be good to keep the mock and implementation types the same

// eslint-disable-next-line @typescript-eslint/no-explicit-any
data: any;
jfdoming marked this conversation as resolved.
Show resolved Hide resolved
dependencies: string[];
}>;
getCell?: () => { value: number };
Expand Down
8 changes: 5 additions & 3 deletions packages/loot-core/src/server/admin/types/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,17 @@ export interface AdminHandlers {

'user-delete-all': (
ids: string[],
) => Promise<{ someDeletionsFailed: boolean; ids?: number[] }>;
) => Promise<
{ someDeletionsFailed: boolean; ids?: number[] } | { error: string }
>;

'user-add': (
user: Omit<UserEntity, 'id'>,
) => Promise<{ error?: string } | { id: string }>;
) => Promise<{ error: string } | { id: string }>;

'user-update': (
user: Omit<UserEntity, 'id'>,
) => Promise<{ error?: string } | { id: string }>;
) => Promise<{ error: string } | { id: string }>;

'access-add': (
user: NewUserAccessEntity,
Expand Down
5 changes: 2 additions & 3 deletions packages/loot-core/src/server/aql/compiler.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { getNormalisedString } from '../../shared/normalisation';
import { QueryState } from '../../shared/query';

// @ts-strict-ignore
let _uid = 0;
Expand Down Expand Up @@ -1005,9 +1006,7 @@ export type SchemaConfig = {
| Record<string, unknown>
| ((name: string, config: { withDead; isJoin; tableOptions }) => unknown);
tableFilters?: (name: string) => unknown[];
customizeQuery?: <T extends { table: string; orderExpressions: unknown[] }>(
queryString: T,
) => T;
customizeQuery?: (queryString: QueryState) => QueryState;
views?: Record<
string,
{
Expand Down
8 changes: 4 additions & 4 deletions packages/loot-core/src/server/rules/types/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,9 @@ export interface RulesHandlers {

'rules-get': () => Promise<RuleEntity[]>;

// TODO: change return value to `RuleEntity`
'rule-get': (arg: { id: string }) => Promise<unknown>;
'rule-get': (arg: { id: RuleEntity['id'] }) => Promise<RuleEntity>;

// TODO: change types to `TransactionEntity`
'rules-run': (arg: { transaction }) => Promise<unknown>;
'rules-run': (arg: {
transaction: TransactionEntity;
}) => Promise<TransactionEntity>;
}
2 changes: 2 additions & 0 deletions packages/loot-core/src/server/schedules/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,8 @@ export async function updateSchedule({

await db.updateWithSchema('schedules', schedule);
});

return schedule.id;
}

export async function deleteSchedule({ id }) {
Expand Down
14 changes: 9 additions & 5 deletions packages/loot-core/src/server/schedules/types/handlers.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// @ts-strict-ignore
import { DiscoverScheduleEntity } from '../../../types/models';
import { DiscoverScheduleEntity, ScheduleEntity } from '../../../types/models';

export interface SchedulesHandlers {
'schedule/create': (arg: {
Expand All @@ -15,13 +15,17 @@ export interface SchedulesHandlers {
schedule;
conditions?;
resetNextDate?: boolean;
}) => Promise<void>;
}) => Promise<ScheduleEntity['id']>;

'schedule/delete': (arg: { id: string }) => Promise<void>;
'schedule/delete': (arg: { id: ScheduleEntity['id'] }) => Promise<void>;

'schedule/skip-next-date': (arg: { id: string }) => Promise<void>;
'schedule/skip-next-date': (arg: {
id: ScheduleEntity['id'];
}) => Promise<void>;

'schedule/post-transaction': (arg: { id: string }) => Promise<void>;
'schedule/post-transaction': (arg: {
id: ScheduleEntity['id'];
}) => Promise<void>;

'schedule/force-run-service': () => Promise<unknown>;

Expand Down
2 changes: 2 additions & 0 deletions packages/loot-core/src/types/models/simplefin.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@ import { AccountEntity } from './account';
import { BankSyncResponse } from './bank-sync';

export type SimpleFinOrganization = {
id: string;
name: string;
domain: string;
};

export type SimpleFinAccount = {
id: string;
name: string;
balance: number;
org: SimpleFinOrganization;
};

Expand Down
20 changes: 14 additions & 6 deletions packages/loot-core/src/types/server-handlers.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export interface ServerHandlers {
payees;
}) => Promise<unknown>;

'transactions-export-query': (arg: { query: QueryState }) => Promise<unknown>;
'transactions-export-query': (arg: { query: QueryState }) => Promise<string>;

'get-categories': () => Promise<{
grouped: Array<CategoryGroupEntity>;
Expand Down Expand Up @@ -109,7 +109,7 @@ export interface ServerHandlers {

'payees-get': () => Promise<PayeeEntity[]>;

'payees-get-rule-counts': () => Promise<unknown>;
'payees-get-rule-counts': () => Promise<Record<PayeeEntity['id'], number>>;

'payees-merge': (arg: { targetId; mergeIds }) => Promise<void>;

Expand Down Expand Up @@ -141,7 +141,8 @@ export interface ServerHandlers {

'create-query': (arg: { sheetName; name; query }) => Promise<unknown>;

query: (query: Query) => Promise<{ data: unknown; dependencies }>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
query: (query: Query) => Promise<{ data: any; dependencies: string[] }>;

'account-update': (arg: { id; name }) => Promise<unknown>;

Expand Down Expand Up @@ -182,7 +183,10 @@ export interface ServerHandlers {

'account-move': (arg: { id; targetId }) => Promise<unknown>;

'secret-set': (arg: { name: string; value: string | null }) => Promise<null>;
'secret-set': (arg: {
name: string;
value: string | null;
}) => Promise<{ error?: string; reason?: string }>;
'secret-check': (arg: string) => Promise<string | { error?: string }>;

'gocardless-poll-web-token': (arg: {
Expand All @@ -196,7 +200,11 @@ export interface ServerHandlers {

'simplefin-status': () => Promise<{ configured: boolean }>;

'simplefin-accounts': () => Promise<{ accounts: SimpleFinAccount[] }>;
'simplefin-accounts': () => Promise<{
accounts?: SimpleFinAccount[];
error_code?: string;
reason?: string;
}>;

'simplefin-batch-sync': ({ ids }: { ids: string[] }) => Promise<
{
Expand Down Expand Up @@ -326,7 +334,7 @@ export interface ServerHandlers {
return_url;
loginMethod?: 'openid';
},
) => Promise<{ error?: string }>;
) => Promise<{ error?: string; redirect_url?: string }>;

'subscribe-sign-out': () => Promise<'ok'>;

Expand Down
6 changes: 6 additions & 0 deletions upcoming-release-notes/4147.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
category: Maintenance
authors: [jfdoming]
---

Fix `send` types in a number of places (2/2)
Loading