65 lines
1.8 KiB
JavaScript
65 lines
1.8 KiB
JavaScript
import sql from 'mssql';
|
|
import { CREATE } from '../../sql/company.js';
|
|
import { CREATE as CREATE_CATEGORY } from '../../sql/category.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 create(pool) {
|
|
const nameTaken = getByName(pool);
|
|
const ensureLang = langEnsure(pool);
|
|
const ensureTax = taxEnsure(pool);
|
|
|
|
return async ({ iso639, name, taxrate, reducedtaxrate }) => {
|
|
const tx = new sql.Transaction(pool);
|
|
await tx.begin();
|
|
|
|
try {
|
|
const existing = await nameTaken(name, tx);
|
|
if (existing) {
|
|
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);
|
|
const taxfreerateId = await ensureTax(0, tx);
|
|
|
|
const category = await request(pool, tx)
|
|
.input('parentId', sql.Int, null)
|
|
.input('sort', sql.Int, 0)
|
|
.query(CREATE_CATEGORY);
|
|
|
|
const rootCategoryId = category.recordset[0].id;
|
|
|
|
const result = await request(pool, tx)
|
|
.input('name', sql.NVarChar(255), name)
|
|
.input('rootCategoryId', sql.Int, rootCategoryId)
|
|
.input('languageId', sql.Int, languageId)
|
|
.input('taxrate', sql.Int, taxrateId)
|
|
.input('reducedtaxrate', sql.Int, reducedtaxrateId)
|
|
.input('taxfreerate', sql.Int, taxfreerateId)
|
|
.query(CREATE);
|
|
|
|
await tx.commit();
|
|
|
|
return {
|
|
id: result.recordset[0].id,
|
|
rootCategoryId,
|
|
languageId,
|
|
taxrateId,
|
|
reducedtaxrateId,
|
|
taxfreerateId,
|
|
};
|
|
} catch (err) {
|
|
try {
|
|
await tx.rollback();
|
|
} catch {
|
|
// ignore
|
|
}
|
|
throw err;
|
|
}
|
|
};
|
|
}
|