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

Extract payees related server handlers from main.ts to server/payees/app.ts #4443

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ function makePayee(name: string, options?: { favorite: boolean }): PayeeEntity {
return {
id: name.toLowerCase() + '-id',
name,
favorite: options?.favorite ? 1 : 0,
favorite: options?.favorite ? true : false,
transfer_acct: undefined,
};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,7 @@ export function PayeeAutocomplete({
return filteredSuggestions;
}

return [{ id: 'new', favorite: 0, name: '' }, ...filteredSuggestions];
return [{ id: 'new', favorite: false, name: '' }, ...filteredSuggestions];
}, [commonPayees, payees, focusTransferPayees, accounts, hasPayeeInput]);

const dispatch = useDispatch();
Expand Down
20 changes: 13 additions & 7 deletions packages/desktop-client/src/components/payees/ManagePayees.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ function PayeeTableHeader() {
type ManagePayeesProps = {
payees: PayeeEntity[];
ruleCounts: ComponentProps<typeof PayeeTable>['ruleCounts'];
orphanedPayees: PayeeEntity[];
orphanedPayees: Array<Pick<PayeeEntity, 'id'>>;
initialSelectedIds: string[];
onBatchChange: (diff: Diff<PayeeEntity>) => void;
onViewRules: ComponentProps<typeof PayeeTable>['onViewRules'];
Expand Down Expand Up @@ -154,16 +154,16 @@ export const ManagePayees = ({
function onFavorite() {
const allFavorited = [...selected.items]
.map(id => payeesById[id].favorite)
.every(f => f === 1);
.every(f => f);
if (allFavorited) {
onBatchChange({
updated: [...selected.items].map(id => ({ id, favorite: 0 })),
updated: [...selected.items].map(id => ({ id, favorite: false })),
added: [],
deleted: [],
});
} else {
onBatchChange({
updated: [...selected.items].map(id => ({ id, favorite: 1 })),
updated: [...selected.items].map(id => ({ id, favorite: true })),
added: [],
deleted: [],
});
Expand All @@ -174,16 +174,22 @@ export const ManagePayees = ({
function onLearn() {
const allLearnCategories = [...selected.items]
.map(id => payeesById[id].learn_categories)
.every(f => f === 1);
.every(f => f);
if (allLearnCategories) {
onBatchChange({
updated: [...selected.items].map(id => ({ id, learn_categories: 0 })),
updated: [...selected.items].map(id => ({
id,
learn_categories: false,
})),
added: [],
deleted: [],
});
} else {
onBatchChange({
updated: [...selected.items].map(id => ({ id, learn_categories: 1 })),
updated: [...selected.items].map(id => ({
id,
learn_categories: true,
})),
added: [],
deleted: [],
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export function ManagePayeesWithData({
const dispatch = useDispatch();

const [ruleCounts, setRuleCounts] = useState({ value: new Map() });
const [orphans, setOrphans] = useState<PayeeEntity[]>([]);
const [orphans, setOrphans] = useState<Array<Pick<PayeeEntity, 'id'>>>([]);

const refetchOrphanedPayees = useCallback(async () => {
const orphs = await send('payees-get-orphaned');
Expand Down Expand Up @@ -127,7 +127,6 @@ export function ManagePayeesWithData({
initialSelectedIds={initialSelectedIds}
onBatchChange={async (changes: Diff<PayeeEntity>) => {
await send('payees-batch-change', changes);
await dispatch(getPayees());
setOrphans(applyChanges(changes, orphans));
}}
onMerge={async ([targetId, ...mergeIds]) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -180,14 +180,10 @@ export const PayeeTableRow = memo(
onDelete(id);
break;
case 'favorite':
onUpdate(id, 'favorite', payee.favorite ? 0 : 1);
onUpdate(id, 'favorite', !payee.favorite);
break;
case 'learn':
onUpdate(
id,
'learn_categories',
payee.learn_categories ? 0 : 1,
);
onUpdate(id, 'learn_categories', !payee.learn_categories);
break;
case 'view-rules':
onViewRules(id);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,16 +56,16 @@ const payees: PayeeEntity[] = [
{
id: 'bob-id',
name: 'Bob',
favorite: 1,
favorite: true,
},
{
id: 'alice-id',
name: 'Alice',
favorite: 1,
favorite: true,
},
{
id: 'guy',
favorite: 0,
favorite: false,
name: 'This guy on the side of the road',
},
];
Expand Down
1 change: 1 addition & 0 deletions packages/loot-core/src/server/aql/schema/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ export const schema = {
transfer_acct: f('id', { ref: 'accounts' }),
tombstone: f('boolean'),
favorite: f('boolean'),
learn_categories: f('boolean'),
},
accounts: {
id: f('id'),
Expand Down
17 changes: 10 additions & 7 deletions packages/loot-core/src/server/db/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import * as sqlite from '../../platform/server/sqlite';
import * as monthUtils from '../../shared/months';
import { groupById } from '../../shared/util';
import { CategoryEntity, CategoryGroupEntity } from '../../types/models';
import { WithRequired } from '../../types/util';
import {
schema,
schemaConfig,
Expand Down Expand Up @@ -514,9 +515,11 @@ export async function getAccount(id: DbAccount['id']) {
return first<DbAccount>(`SELECT * FROM accounts WHERE id = ?`, [id]);
}

export async function insertPayee(payee) {
export async function insertPayee(
payee: WithRequired<Partial<DbPayee>, 'name'>,
) {
payee = payeeModel.validate(payee);
let id;
let id: DbPayee['id'];
await batchMessages(async () => {
id = await insertWithUUID('payees', payee);
await insert('payee_mapping', { id, targetId: id });
Expand Down Expand Up @@ -549,7 +552,7 @@ export async function deleteTransferPayee(payee: Pick<DbPayee, 'id'>) {
return delete_('payees', payee.id);
}

export function updatePayee(payee) {
export function updatePayee(payee: WithRequired<Partial<DbPayee>, 'id'>) {
payee = payeeModel.validate(payee, { update: true });
return update('payees', payee);
}
Expand Down Expand Up @@ -594,7 +597,7 @@ export async function mergePayees(
});
}

export function getPayees() {
export function getPayees(): Promise<DbPayee[]> {
return all(`
SELECT p.*, COALESCE(a.name, p.name) AS name FROM payees p
LEFT JOIN accounts a ON (p.transfer_acct = a.id AND a.tombstone = 0)
Expand All @@ -603,7 +606,7 @@ export function getPayees() {
`);
}

export function getCommonPayees() {
export function getCommonPayees(): Promise<DbPayee[]> {
const twelveWeeksAgo = toDateRepr(
monthUtils.subWeeks(monthUtils.currentDate(), 12),
);
Expand Down Expand Up @@ -645,11 +648,11 @@ const orphanedPayeesQuery = `
`;
/* eslint-enable rulesdir/typography */

export function syncGetOrphanedPayees() {
export function syncGetOrphanedPayees(): Promise<Array<Pick<DbPayee, 'id'>>> {
return all(orphanedPayeesQuery);
}

export async function getOrphanedPayees() {
export async function getOrphanedPayees(): Promise<Array<DbPayee['id']>> {
const rows = await all(orphanedPayeesQuery);
return rows.map(row => row.id);
}
Expand Down
77 changes: 4 additions & 73 deletions packages/loot-core/src/server/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ import { handleBudgetImport } from './importers';
import { app } from './main-app';
import { mutator, runHandler } from './mutators';
import { app as notesApp } from './notes/app';
import { app as payeesApp } from './payees/app';
import * as Platform from './platform';
import { get, post } from './post';
import { app as preferencesApp } from './preferences/app';
Expand All @@ -55,18 +56,18 @@ import { resolveName, unresolveName } from './spreadsheet/util';
import {
initialFullSync,
fullSync,
batchMessages,
setSyncingMode,
makeTestMessage,
clearFullSyncTimeout,
resetSync,
repairSync,
batchMessages,
} from './sync';
import * as syncMigrations from './sync/migrate';
import { app as toolsApp } from './tools/app';
import { app as transactionsApp } from './transactions/app';
import * as rules from './transactions/transaction-rules';
import { withUndo, clearUndo, undo, redo } from './undo';
import { clearUndo, undo, redo, withUndo } from './undo';
import { updateVersion } from './update';
import {
uniqueBudgetName,
Expand Down Expand Up @@ -377,77 +378,6 @@ handlers['must-category-transfer'] = async function ({ id }) {
});
};

handlers['payee-create'] = mutator(async function ({ name }) {
return withUndo(async () => {
return db.insertPayee({ name });
});
});

handlers['common-payees-get'] = async function () {
return db.getCommonPayees();
};

handlers['payees-get'] = async function () {
return db.getPayees();
};

handlers['payees-get-orphaned'] = async function () {
return db.syncGetOrphanedPayees();
};

handlers['payees-get-rule-counts'] = async function () {
const payeeCounts = {};

rules.iterateIds(rules.getRules(), 'payee', (rule, id) => {
if (payeeCounts[id] == null) {
payeeCounts[id] = 0;
}
payeeCounts[id]++;
});

return payeeCounts;
};

handlers['payees-merge'] = mutator(async function ({ targetId, mergeIds }) {
return withUndo(
async () => {
return db.mergePayees(targetId, mergeIds);
},
{ targetId, mergeIds },
);
});

handlers['payees-batch-change'] = mutator(async function ({
added,
deleted,
updated,
}) {
return withUndo(async () => {
return batchMessages(async () => {
if (deleted) {
await Promise.all(deleted.map(p => db.deletePayee(p)));
}

if (added) {
await Promise.all(added.map(p => db.insertPayee(p)));
}

if (updated) {
await Promise.all(updated.map(p => db.updatePayee(p)));
}
});
});
});

handlers['payees-check-orphaned'] = async function ({ ids }) {
const orphaned = new Set(await db.getOrphanedPayees());
return ids.filter(id => orphaned.has(id));
};

handlers['payees-get-rules'] = async function ({ id }) {
return rules.getRulesForPayee(id).map(rule => rule.serialize());
};

handlers['make-filters-from-conditions'] = async function ({
conditions,
applySpecialCases,
Expand Down Expand Up @@ -1491,6 +1421,7 @@ app.combine(
adminApp,
transactionsApp,
accountsApp,
payeesApp,
);

export function getDefaultDocumentDir() {
Expand Down
Loading