79 lines
2.8 KiB
JavaScript
79 lines
2.8 KiB
JavaScript
import { UPDATE as MSSQL_UPDATE } from '../../providers/mssql/queries/company.js';
|
|
import { UPDATE as SQLITE_UPDATE } from '../../providers/sqlite3/queries/company.js';
|
|
import getById from './getById.js';
|
|
import getByName from './getByName.js';
|
|
import langEnsure from '../lang/ensure.js';
|
|
import taxEnsure from '../tax/ensure.js';
|
|
import makeRunner from '../runner.js';
|
|
|
|
export default function update(provider) {
|
|
const byId = getById(provider);
|
|
const byName = getByName(provider);
|
|
const ensureLang = langEnsure(provider);
|
|
const ensureTax = taxEnsure(provider);
|
|
const isSqlite = provider?.dialect === 'sqlite3';
|
|
const updateSql = isSqlite ? SQLITE_UPDATE : MSSQL_UPDATE;
|
|
|
|
/**
|
|
* Updates an existing company's name, language and tax rates.
|
|
*
|
|
* @param {number} id - The id of the company to update.
|
|
* @param {object} input - The update input.
|
|
* @param {string} input.iso639 - The ISO 639 language code.
|
|
* @param {string} input.name - The new company name (must be unique).
|
|
* @param {number} input.taxrate - The standard tax rate in percent.
|
|
* @param {number} input.reducedtaxrate - The reduced tax rate in percent.
|
|
* @param {object} [tx] - Optional transaction to run within.
|
|
* @returns {Promise<{id: number, rootCategoryId: number, languageId: number, taxrateId: number, reducedtaxrateId: number, taxfreerateId: number}>} The updated company ids.
|
|
* @throws {Error} If the company is not found or the name is taken.
|
|
*
|
|
* @example
|
|
* const result = await store.company.update(1, { iso639: 'de', name: 'Acme', taxrate: 19, reducedtaxrate: 7 });
|
|
* // => { id, rootCategoryId, languageId, taxrateId, reducedtaxrateId, taxfreerateId }
|
|
*/
|
|
return async (id, { iso639, name, taxrate, reducedtaxrate }, tx) => {
|
|
const runUpdate = async (runner) => {
|
|
const company = await byId(id, runner);
|
|
if (!company) {
|
|
throw new Error('Company not found');
|
|
}
|
|
|
|
if (name !== company.name) {
|
|
const taken = await byName(name, runner);
|
|
if (taken) {
|
|
throw new Error('Company name not available');
|
|
}
|
|
}
|
|
|
|
const languageId = await ensureLang(iso639, runner);
|
|
const taxrateId = await ensureTax(taxrate, runner);
|
|
const reducedtaxrateId = await ensureTax(reducedtaxrate, runner);
|
|
|
|
await runner.query(updateSql, {
|
|
id,
|
|
name,
|
|
languageId,
|
|
taxrate: taxrateId,
|
|
reducedtaxrate: reducedtaxrateId,
|
|
});
|
|
|
|
return {
|
|
id,
|
|
rootCategoryId: company.root_category_id,
|
|
languageId,
|
|
taxrateId,
|
|
reducedtaxrateId,
|
|
taxfreerateId: company.taxfreerate,
|
|
};
|
|
};
|
|
|
|
if (tx) {
|
|
return runUpdate(makeRunner(provider, tx));
|
|
}
|
|
if (typeof provider?.transaction === 'function') {
|
|
return provider.transaction(runUpdate);
|
|
}
|
|
return runUpdate(makeRunner(provider));
|
|
};
|
|
}
|