64 lines
1.7 KiB
JavaScript
64 lines
1.7 KiB
JavaScript
import sql from 'mssql';
|
|
import { UPDATE } from '../../sql/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 request from '../request.js';
|
|
|
|
export default function update(pool) {
|
|
const byId = getById(pool);
|
|
const byName = getByName(pool);
|
|
const ensureLang = langEnsure(pool);
|
|
const ensureTax = taxEnsure(pool);
|
|
|
|
return async (id, { iso639, name, taxrate, reducedtaxrate }) => {
|
|
const tx = new sql.Transaction(pool);
|
|
await tx.begin();
|
|
|
|
try {
|
|
const company = await byId(id, tx);
|
|
if (!company) {
|
|
throw new Error('Company not found');
|
|
}
|
|
|
|
if (name !== company.name) {
|
|
const taken = await byName(name, tx);
|
|
if (taken) {
|
|
throw new Error('Company name not available');
|
|
}
|
|
}
|
|
|
|
const languageId = await ensureLang(iso639, tx);
|
|
const taxrateId = await ensureTax(taxrate, tx);
|
|
const reducedtaxrateId = await ensureTax(reducedtaxrate, tx);
|
|
|
|
await request(pool, tx)
|
|
.input('id', sql.Int, id)
|
|
.input('name', sql.NVarChar(255), name)
|
|
.input('languageId', sql.Int, languageId)
|
|
.input('taxrate', sql.Int, taxrateId)
|
|
.input('reducedtaxrate', sql.Int, reducedtaxrateId)
|
|
.query(UPDATE);
|
|
|
|
await tx.commit();
|
|
|
|
return {
|
|
id,
|
|
root_category_id: company.root_category_id,
|
|
language_id: languageId,
|
|
taxrate: taxrateId,
|
|
reducedtaxrate: reducedtaxrateId,
|
|
taxfreerate: company.taxfreerate,
|
|
};
|
|
} catch (err) {
|
|
try {
|
|
await tx.rollback();
|
|
} catch {
|
|
// ignore
|
|
}
|
|
throw err;
|
|
}
|
|
};
|
|
}
|