Commit 6f1ef1da authored by Benjamin Bouvier's avatar Benjamin Bouvier
Browse files

Singularize models again;

parent af6cef93
import { makeLogger } from './helpers';
import { setupOrm, Users } from './models';
import { setupOrm, User } from './models';
let log = makeLogger('cli');
......@@ -9,7 +9,7 @@ export async function createUser(login) {
log.info(`Creating user with login ${login}: setting up database.`);
await setupOrm();
log.info('Database set up; creating user...');
let user = await Users.create({ login });
let user = await User.create({ login });
let id = user.id;
log.info(`User ${login} created with success! id=${id}`);
} catch (err) {
......
import { Accesses } from '../models';
import { Access } from '../models';
import accountManager from '../lib/accounts-manager';
import { fullPoll } from '../lib/poller';
......@@ -16,7 +16,7 @@ let log = makeLogger('controllers/accesses');
export async function preloadAccess(req, res, next, accessId) {
try {
let { id: userId } = req.user;
let access = await Accesses.find(userId, accessId);
let access = await Access.find(userId, accessId);
if (!access) {
throw new KError('bank access not found', 404);
}
......@@ -29,7 +29,7 @@ export async function preloadAccess(req, res, next, accessId) {
export async function destroyWithData(userId, access) {
log.info(`Removing access ${access.id} for bank ${access.vendorId}...`);
await Accesses.destroy(userId, access.id);
await Access.destroy(userId, access.id);
await AccountController.fixupDefaultAccount(userId);
log.info('Done!');
}
......@@ -62,7 +62,7 @@ export async function createAndRetrieveData(userId, params) {
let access = null;
try {
access = await Accesses.create(userId, params);
access = await Access.create(userId, params);
await accountManager.retrieveAndAddAccountsByAccess(userId, access, /* interactive */ true);
let { accounts, newOperations } = await accountManager.retrieveOperationsByAccess(
userId,
......@@ -81,7 +81,7 @@ export async function createAndRetrieveData(userId, params) {
// Let sql remove all the dependent data for us.
if (access !== null) {
log.info('\tdeleting access...');
await Accesses.destroy(userId, access.id);
await Access.destroy(userId, access.id);
}
// Rethrow the error
......@@ -207,7 +207,7 @@ export async function update(req, res) {
newFields.customLabel = null;
}
await Accesses.update(userId, access.id, newFields);
await Access.update(userId, access.id, newFields);
res.status(201).json({ status: 'OK' });
} catch (err) {
return asyncErr(res, err, 'when updating bank access');
......@@ -227,7 +227,7 @@ export async function updateAndFetchAccounts(req, res) {
}
// The preloaded access needs to be updated before calling fetchAccounts.
req.preloaded.access = await Accesses.update(userId, access.id, newFields);
req.preloaded.access = await Access.update(userId, access.id, newFields);
await fetchAccounts(req, res);
} catch (err) {
return asyncErr(res, err, 'when updating and fetching bank access');
......
import { Accesses, Accounts, Settings } from '../models';
import { Access, Account, Setting } from '../models';
import { makeLogger, KError, asyncErr } from '../helpers';
import { checkAllowedFields } from '../shared/validators';
import accountManager from '../lib/accounts-manager';
......@@ -11,7 +11,7 @@ let log = makeLogger('controllers/accounts');
export async function preloadAccount(req, res, next, accountID) {
try {
let { id: userId } = req.user;
let account = await Accounts.find(userId, accountID);
let account = await Account.find(userId, accountID);
if (!account) {
throw new KError('Bank account not found', 404);
}
......@@ -23,14 +23,14 @@ export async function preloadAccount(req, res, next, accountID) {
}
export async function fixupDefaultAccount(userId) {
let found = await Settings.findOrCreateDefault(userId, 'default-account-id');
let found = await Setting.findOrCreateDefault(userId, 'default-account-id');
if (found && found.value !== '') {
let accountFound = await Accounts.find(userId, found.value);
let accountFound = await Account.find(userId, found.value);
if (!accountFound) {
log.info(
"-> Removing the default account setting since the account doesn't exist anymore."
);
await Settings.update(userId, found.id, { value: '' });
await Setting.update(userId, found.id, { value: '' });
}
}
}
......@@ -41,14 +41,14 @@ export async function destroyWithOperations(userId, account) {
log.info(`Removing account ${account.label} from database...`);
log.info(`\t-> Destroy account ${account.label}`);
await Accounts.destroy(userId, account.id);
await Account.destroy(userId, account.id);
await fixupDefaultAccount(userId);
let accounts = await Accounts.byAccess(userId, { id: account.accessId });
let accounts = await Account.byAccess(userId, { id: account.accessId });
if (accounts && accounts.length === 0) {
log.info('\t-> No other accounts bound: destroying access.');
await Accesses.destroy(userId, account.accessId);
await Access.destroy(userId, account.accessId);
}
}
......@@ -63,7 +63,7 @@ export async function update(req, res) {
}
let account = req.preloaded.account;
let newAccount = await Accounts.update(userId, account.id, newFields);
let newAccount = await Account.update(userId, account.id, newFields);
res.status(200).json(newAccount);
} catch (err) {
return asyncErr(res, err, 'when updating an account');
......
import { Accounts, Alerts } from '../models';
import { Account, Alert } from '../models';
import { asyncErr, KError } from '../helpers';
import { checkAlert } from '../shared/validators';
export async function loadAlert(req, res, next, alertId) {
try {
let { id: userId } = req.user;
let alert = await Alerts.find(userId, alertId);
let alert = await Alert.find(userId, alertId);
if (!alert) {
throw new KError('bank alert not found', 404);
}
......@@ -35,12 +35,12 @@ export async function create(req, res) {
throw new KError(validationError, 400);
}
let account = await Accounts.find(userId, newAlert.accountId);
let account = await Account.find(userId, newAlert.accountId);
if (!account) {
throw new KError('bank account not found', 404);
}
let alert = await Alerts.create(userId, newAlert);
let alert = await Alert.create(userId, newAlert);
res.status(201).json(alert);
} catch (err) {
return asyncErr(res, err, 'when creating an alert');
......@@ -51,7 +51,7 @@ export async function destroy(req, res) {
try {
let { id: userId } = req.user;
await Alerts.destroy(userId, req.preloaded.alert.id);
await Alert.destroy(userId, req.preloaded.alert.id);
res.status(204).end();
} catch (err) {
return asyncErr(res, err, 'when deleting a bank alert');
......@@ -75,7 +75,7 @@ export async function update(req, res) {
throw new KError(validationError, 400);
}
newAlert = await Alerts.update(userId, alert.id, req.body);
newAlert = await Alert.update(userId, alert.id, req.body);
res.status(200).json(newAlert);
} catch (err) {
return asyncErr(res, err, 'when updating a bank alert');
......
import crypto from 'crypto';
import { Accesses, Accounts, Alerts, Budgets, Categories, Settings, Transactions } from '../models';
import { Access, Account, Alert, Budget, Category, Setting, Transaction } from '../models';
import {
assert,
......@@ -35,8 +35,8 @@ function cleanMeta(obj) {
async function getAllData(userId, isExport = false, cleanPassword = true) {
let ret = {};
ret.accounts = (await Accounts.all(userId)).map(cleanMeta);
ret.accesses = (await Accesses.all(userId)).map(cleanMeta);
ret.accounts = (await Account.all(userId)).map(cleanMeta);
ret.accesses = (await Access.all(userId)).map(cleanMeta);
for (let access of ret.accesses) {
// Process enabled status only for the /all request.
......@@ -56,19 +56,19 @@ async function getAllData(userId, isExport = false, cleanPassword = true) {
}
}
ret.categories = (await Categories.all(userId)).map(cleanMeta);
ret.operations = (await Transactions.all(userId)).map(cleanMeta);
ret.categories = (await Category.all(userId)).map(cleanMeta);
ret.operations = (await Transaction.all(userId)).map(cleanMeta);
ret.settings = (isExport
? await Settings.allWithoutGhost(userId)
: await Settings.all(userId)
? await Setting.allWithoutGhost(userId)
: await Setting.all(userId)
).map(cleanMeta);
if (isExport) {
ret.budgets = (await Budgets.all(userId)).map(cleanMeta);
ret.budgets = (await Budget.all(userId)).map(cleanMeta);
}
if (isExport || isEmailEnabled() || isAppriseApiEnabled()) {
ret.alerts = (await Alerts.all(userId)).map(cleanMeta);
ret.alerts = (await Alert.all(userId)).map(cleanMeta);
} else {
ret.alerts = [];
}
......@@ -222,13 +222,13 @@ export function parseDate(date) {
}
export async function importData(userId, world) {
world.accesses = (world.accesses || []).map(applyRenamings(Accesses));
world.accounts = (world.accounts || []).map(applyRenamings(Accounts));
world.alerts = (world.alerts || []).map(applyRenamings(Alerts));
world.budgets = (world.budgets || []).map(applyRenamings(Budgets));
world.categories = (world.categories || []).map(applyRenamings(Categories));
world.operations = (world.operations || []).map(applyRenamings(Transactions));
world.settings = (world.settings || []).map(applyRenamings(Settings));
world.accesses = (world.accesses || []).map(applyRenamings(Access));
world.accounts = (world.accounts || []).map(applyRenamings(Account));
world.alerts = (world.alerts || []).map(applyRenamings(Alert));
world.budgets = (world.budgets || []).map(applyRenamings(Budget));
world.categories = (world.categories || []).map(applyRenamings(Category));
world.operations = (world.operations || []).map(applyRenamings(Transaction));
world.settings = (world.settings || []).map(applyRenamings(Setting));
// Static data.
world.operationtypes = world.operationtypes || [];
......@@ -280,7 +280,7 @@ export async function importData(userId, world) {
access.fields = sanitizedCustomFields;
let created = await Accesses.create(userId, access);
let created = await Access.create(userId, access);
accessMap[accessId] = created.id;
}
......@@ -316,7 +316,7 @@ export async function importData(userId, world) {
}
account.accessId = accessMap[account.accessId];
let created = await Accounts.create(userId, account);
let created = await Account.create(userId, account);
accountIdToAccount.set(accountId, created.id);
vendorToOwnAccountId.set(created.vendorAccountId, created.id);
......@@ -324,7 +324,7 @@ export async function importData(userId, world) {
log.info('Done.');
log.info('Import categories...');
let existingCategories = await Categories.all(userId);
let existingCategories = await Category.all(userId);
let existingCategoriesMap = new Map();
for (let category of existingCategories) {
existingCategoriesMap.set(category.label, category);
......@@ -338,7 +338,7 @@ export async function importData(userId, world) {
let existing = existingCategoriesMap.get(category.label);
categoryMap[catId] = existing.id;
} else {
let created = await Categories.create(userId, category);
let created = await Category.create(userId, category);
categoryMap[catId] = created.id;
}
}
......@@ -347,7 +347,7 @@ export async function importData(userId, world) {
log.info('Import budgets...');
let makeBudgetKey = b => `${b.categoryId}-${b.year}-${b.month}`;
let existingBudgets = await Budgets.all(userId);
let existingBudgets = await Budget.all(userId);
let existingBudgetsMap = new Map();
for (let budget of existingBudgets) {
existingBudgetsMap.set(makeBudgetKey(budget), budget);
......@@ -363,13 +363,13 @@ export async function importData(userId, world) {
!existingBudget.threshold ||
existingBudget.threshold !== importedBudget.threshold
) {
await Budgets.update(userId, existingBudget.id, {
await Budget.update(userId, existingBudget.id, {
threshold: importedBudget.threshold
});
}
} else {
delete importedBudget.id;
await Budgets.create(userId, importedBudget);
await Budget.create(userId, importedBudget);
}
}
log.info('Done.');
......@@ -471,7 +471,7 @@ export async function importData(userId, world) {
world.operations.splice(skipTransactions[i], 1);
}
}
await Transactions.bulkCreate(userId, world.operations);
await Transaction.bulkCreate(userId, world.operations);
log.info('Done.');
log.info('Import settings...');
......@@ -491,21 +491,21 @@ export async function importData(userId, world) {
}
setting.value = accountIdToAccount.get(setting.value);
await Settings.updateByKey(userId, 'default-account-id', setting.value);
await Setting.updateByKey(userId, 'default-account-id', setting.value);
continue;
}
// Overwrite the previous value of the demo-mode, if it was set.
if (setting.key === 'demo-mode' && setting.value === 'true') {
let found = await Settings.byKey(userId, 'demo-mode');
let found = await Setting.byKey(userId, 'demo-mode');
if (found && found.value !== 'true') {
await Settings.updateByKey(userId, 'demo-mode', true);
await Setting.updateByKey(userId, 'demo-mode', true);
continue;
}
}
// Note that former existing values are not overwritten!
await Settings.findOrCreateByKey(userId, setting.key, setting.value);
await Setting.findOrCreateByKey(userId, setting.key, setting.value);
}
log.info('Done.');
......@@ -530,7 +530,7 @@ export async function importData(userId, world) {
// Remove bankAccount as the alert is now linked to account with accountId prop.
delete a.bankAccount;
delete a.id;
await Alerts.create(userId, a);
await Alert.create(userId, a);
}
log.info('Done.');
}
......
import { Budgets, Categories } from '../models';
import { Budget, Category } from '../models';
import { KError, asyncErr } from '../helpers';
import { checkBudget } from '../shared/validators';
......@@ -6,7 +6,7 @@ import { checkBudget } from '../shared/validators';
async function createBudget(userId, budget) {
// Missing parameters
if (typeof budget.categoryId !== 'undefined') {
let categoryExists = await Categories.exists(userId, budget.categoryId);
let categoryExists = await Category.exists(userId, budget.categoryId);
if (!categoryExists) {
throw new KError(`Category ${budget.categoryId} not found`, 404);
}
......@@ -17,7 +17,7 @@ async function createBudget(userId, budget) {
throw new KError(error, 400);
}
return await Budgets.create(userId, budget);
return await Budget.create(userId, budget);
}
export async function getByYearAndMonth(req, res) {
......@@ -35,16 +35,16 @@ export async function getByYearAndMonth(req, res) {
throw new KError('Invalid month parameter', 400);
}
let budgets = await Budgets.byYearAndMonth(userId, year, month);
let budgets = await Budget.byYearAndMonth(userId, year, month);
// Ensure there is a budget for each category.
let categories = await Categories.all(userId);
let categories = await Category.all(userId);
for (let cat of categories) {
if (!budgets.find(b => b.categoryId === cat.id)) {
// Retrieve the last threshold used for this category instead of defaulting to 0.
// "last" here means "last in time" not last entered (TODO: fix it when we'll be
// able to sort by creation/update order).
let sameCategoryBudgets = await Budgets.byCategory(userId, cat.id);
let sameCategoryBudgets = await Budget.byCategory(userId, cat.id);
let currentYear = 0;
let currentMonth = 0;
let threshold = null;
......@@ -101,7 +101,7 @@ export async function update(req, res) {
throw new KError(error, 400);
}
const newBudget = Budgets.findAndUpdate(userId, categoryId, year, month, params.threshold);
const newBudget = Budget.findAndUpdate(userId, categoryId, year, month, params.threshold);
res.status(200).json(newBudget);
} catch (err) {
return asyncErr(res, err, 'when updating a budget');
......
import { Budgets, Categories, Transactions } from '../models';
import { Budget, Category, Transaction } from '../models';
import { makeLogger, KError, asyncErr } from '../helpers';
import { checkExactFields, checkAllowedFields } from '../shared/validators';
......@@ -8,7 +8,7 @@ export async function preloadCategory(req, res, next, id) {
try {
let { id: userId } = req.user;
let category;
category = await Categories.find(userId, id);
category = await Category.find(userId, id);
if (!category) {
throw new KError('Category not found', 404);
......@@ -30,7 +30,7 @@ export async function create(req, res) {
throw new KError(`when creating a category: ${error}`, 400);
}
let created = await Categories.create(userId, req.body);
let created = await Category.create(userId, req.body);
res.status(200).json(created);
} catch (err) {
return asyncErr(res, err, 'when creating category');
......@@ -47,7 +47,7 @@ export async function update(req, res) {
}
let category = req.preloaded.category;
let newCat = await Categories.update(userId, category.id, req.body);
let newCat = await Category.update(userId, category.id, req.body);
res.status(200).json(newCat);
} catch (err) {
return asyncErr(res, err, 'when updating a category');
......@@ -68,7 +68,7 @@ export async function destroy(req, res) {
let replaceBy = req.body.replaceByCategoryId;
if (replaceBy !== null) {
log.debug(`Replacing category ${former.id} by ${replaceBy}...`);
let categoryToReplaceBy = await Categories.find(userId, replaceBy);
let categoryToReplaceBy = await Category.find(userId, replaceBy);
if (!categoryToReplaceBy) {
throw new KError('Replacement category not found', 404);
}
......@@ -77,14 +77,14 @@ export async function destroy(req, res) {
}
let categoryId = replaceBy;
let operations = await Transactions.byCategory(userId, former.id);
let operations = await Transaction.byCategory(userId, former.id);
for (let op of operations) {
await Transactions.update(userId, op.id, { categoryId });
await Transaction.update(userId, op.id, { categoryId });
}
await Budgets.destroyForCategory(userId, former.id, categoryId);
await Budget.destroyForCategory(userId, former.id, categoryId);
await Categories.destroy(userId, former.id);
await Category.destroy(userId, former.id);
res.status(200).end();
} catch (err) {
return asyncErr(res, err, 'when deleting a category');
......
import { Accesses, Budgets, Categories, Settings } from '../models';
import { Access, Budget, Category, Setting } from '../models';
import { asyncErr, KError, translate as $t } from '../helpers';
import DefaultCategories from '../shared/default-categories.json';
......@@ -13,7 +13,7 @@ import {
export async function setupDemoMode(userId) {
// Create default categories.
for (let category of DefaultCategories) {
await Categories.create(userId, {
await Category.create(userId, {
label: $t(category.label),
color: category.color
});
......@@ -27,10 +27,10 @@ export async function setupDemoMode(userId) {
});
// Set the demo mode to true only if other operations succeeded.
const isEnabled = await Settings.findOrCreateByKey(userId, 'demo-mode', 'true');
const isEnabled = await Setting.findOrCreateByKey(userId, 'demo-mode', 'true');
if (isEnabled.value !== 'true') {
// The setting already existed and has the wrong value.
await Settings.updateByKey(userId, 'demo-mode', 'true');
await Setting.updateByKey(userId, 'demo-mode', 'true');
}
return data;
......@@ -66,21 +66,21 @@ export async function disable(req, res) {
throw new KError('Demo mode was not enabled, not disabling it.', 400);
}
const accesses = await Accesses.all(userId);
const accesses = await Access.all(userId);
for (let acc of accesses) {
await destroyAccessWithData(userId, acc);
}
// Delete categories and associated budgets.
const categories = await Categories.all(userId);
const categories = await Category.all(userId);
for (let cat of categories) {
await Budgets.destroyForCategory(userId, cat.id /* no replacement category */);
await Categories.destroy(userId, cat.id);
await Budget.destroyForCategory(userId, cat.id /* no replacement category */);
await Category.destroy(userId, cat.id);
}
// Only reset the setting value if all the destroy operations
// succeeded.
await Settings.updateByKey(userId, 'demo-mode', 'false');
await Setting.updateByKey(userId, 'demo-mode', 'false');
res.status(200).end();
} catch (err) {
......
import fs from 'fs';
import { promisify } from 'util';
import { Accesses, Accounts } from '../models';
import { Access, Account } from '../models';
import { asyncErr } from '../helpers';
import { obfuscateKeywords, obfuscatePasswords } from './helpers';
......@@ -16,7 +16,7 @@ export async function getLogs(req, res) {
let sensitiveKeywords = new Set();
let passwords = new Set();
const accounts = await Accounts.all(userId);
const accounts = await Account.all(userId);
accounts.forEach(acc => {
if (acc.accessId) {
sensitiveKeywords.add(acc.accessId);
......@@ -31,7 +31,7 @@ export async function getLogs(req, res) {
}
});
const accesses = await Accesses.all(userId);
const accesses = await Access.all(userId);
accesses.forEach(acc => {
if (acc.login) {
sensitiveKeywords.add(acc.login);
......
import { Settings } from '../models';
import { Setting } from '../models';
export async function getManifest(req, res) {
const iconsDirectory = 'favicon/';
......@@ -13,7 +13,7 @@ export async function getManifest(req, res) {
name: 'Kresus',
short_name: 'Kresus',
description: 'Your personal finances manager',
lang: await Settings.getLocale(userId),
lang: await Setting.getLocale(userId),
start_url: scope,
scope,
display: 'fullscreen',
......
import moment from 'moment';
import { Categories, Transactions } from '../models';
import { Category, Transaction } from '../models';
import { isKnownTransactionTypeName } from '../lib/transaction-types';
import { KError, asyncErr, UNKNOWN_OPERATION_TYPE } from '../helpers';
async function preload(varName, req, res, next, operationID) {
let { id: userId } = req.user;
try {
let operation = await Transactions.find(userId, operationID);
let operation = await Transaction.find(userId, operationID);
if (!operation) {
throw new KError('bank operation not found', 404);
}
......@@ -47,7 +47,7 @@ export async function update(req, res) {
let opUpdate = {};
if (typeof attr.categoryId !== 'undefined') {
if (attr.categoryId !== null) {
let found = await Categories.find(userId, attr.categoryId);
let found = await Category.find(userId, attr.categoryId);
if (!found) {
throw new KError('Category not found', 404);
}
......@@ -79,7 +79,7 @@ export async function update(req, res) {
}
}
await Transactions.update(userId, req.preloaded.operation.id, opUpdate);
await Transaction.update(userId, req.preloaded.operation.id, opUpdate);
res.status(200).end();
} catch (err) {
return asyncErr(res, err, 'when updating attributes of operation');
......@@ -96,9 +96,9 @@ export async function merge(req, res) {
// Transfer various fields upon deletion
let newFields = op.mergeWith(otherOp);
op = await Transactions.update(userId, op.id, newFields);
op = await Transaction.update(userId, op.id, newFields);
await Transactions.destroy(userId, otherOp.id);
await Transaction