56 lines
1.4 KiB
JavaScript
56 lines
1.4 KiB
JavaScript
import { CREATE } from '../../sql/entity.js';
|
|
import { INSERT as INSERT_HISTORY } from '../../sql/entityhistory.js';
|
|
import request from '../request.js';
|
|
import resolveCompanyAccess from '../companyuser/resolveCompanyAccess.js';
|
|
import ensureLieferantenGroup from './ensureLieferantenGroup.js';
|
|
|
|
export default function create(pool) {
|
|
const access = resolveCompanyAccess(pool);
|
|
|
|
return async (googleAuthId, companyId, { name } = {}) => {
|
|
const cleaned = name?.trim();
|
|
if (!cleaned) {
|
|
throw new Error('Name required');
|
|
}
|
|
|
|
const { companyuserId } = await access(googleAuthId, companyId);
|
|
|
|
const tx = pool.transaction();
|
|
await tx.begin();
|
|
|
|
try {
|
|
const customergroupId = await ensureLieferantenGroup(pool, companyId, tx);
|
|
|
|
const created = await request(pool, tx)
|
|
.input('customergroupId', customergroupId)
|
|
.input('firstName', null)
|
|
.input('name', cleaned)
|
|
.query(CREATE);
|
|
|
|
const row = created.recordset[0];
|
|
|
|
await request(pool, tx)
|
|
.input('entityId', row.id)
|
|
.input('companyuserId', companyuserId)
|
|
.input('text', 'Erstellt')
|
|
.query(INSERT_HISTORY);
|
|
|
|
await tx.commit();
|
|
|
|
return {
|
|
id: row.id,
|
|
name: row.name,
|
|
createdAt: row.createdAt,
|
|
updatedAt: row.updatedAt,
|
|
};
|
|
} catch (err) {
|
|
try {
|
|
await tx.rollback();
|
|
} catch {
|
|
// ignore
|
|
}
|
|
throw err;
|
|
}
|
|
};
|
|
}
|