Files
dashlibstorage/src/store/article/createUnderParent.js

89 lines
2.7 KiB
JavaScript

import { CREATE } from '../../sql/article.js';
import { ADD as ADD_CATEGORYARTICLE } from '../../sql/categoryarticle.js';
import { CREATE as CREATE_ARTICLETEXT } from '../../sql/articletext.js';
import { INSERT as INSERT_HISTORY } from '../../sql/articlehistory.js';
import resolveCategoryAccess from '../category/resolveCategoryAccess.js';
import ensureDefaultUnit from '../unit/ensureDefault.js';
import nextSku from '../numbers/nextSku.js';
import request from '../request.js';
import slugify from '../slugify.js';
export default function createUnderParent(pool) {
const access = resolveCategoryAccess(pool);
const ensureUnit = ensureDefaultUnit(pool);
const allocateSku = nextSku(pool);
/**
* Creates a new article under a given parent category, allocating a SKU and
* a default unit.
*
* @param {object} input - The article creation input.
* @param {number} input.googleAuthId - The id of the Google auth user.
* @param {number} input.parentId - The id of the parent category.
* @param {string} input.name - The article name.
* @returns {Promise<{id: number, parentId: number, name: string, sku: string}>} The created article.
*
* @example
* const article = await store.article.createUnderParent({ googleAuthId: 42, parentId: 5, name: 'Cola' });
* // => { id, parentId, name, sku }
*/
return async ({ googleAuthId, parentId, name }) => {
const { companyId, languageId, companyuserId } = await access(
googleAuthId,
parentId
);
const tx = pool.transaction();
await tx.begin();
try {
const unitId = await ensureUnit(tx, languageId, companyId);
const sku = await allocateSku(companyId, tx);
const slug = slugify(name);
const article = await request(pool, tx)
.input('sku', sku)
.input('unitId', unitId)
.input('unitamount', 1)
.input('weight', 0)
.query(CREATE);
const id = article.recordset[0].id;
await request(pool, tx)
.input('categoryId', parentId)
.input('articleId', id)
.query(ADD_CATEGORYARTICLE);
await request(pool, tx)
.input('articleId', id)
.input('languageId', languageId)
.input('name', name)
.input('slug', slug)
.query(CREATE_ARTICLETEXT);
await request(pool, tx)
.input('articleId', id)
.input('companyuserId', companyuserId)
.input('text', `Artikel "${name}" angelegt`)
.query(INSERT_HISTORY);
await tx.commit();
return {
id,
parentId,
name,
sku,
};
} catch (err) {
try {
await tx.rollback();
} catch {
// ignore
}
throw err;
}
};
}