u
This commit is contained in:
73
src/store/article/createUnderParent.js
Normal file
73
src/store/article/createUnderParent.js
Normal file
@@ -0,0 +1,73 @@
|
||||
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 resolveCategoryAccess from '../category/resolveCategoryAccess.js';
|
||||
import ensureDefaultUnit from '../unit/ensureDefault.js';
|
||||
import nextSku from '../numbers/nextSku.js';
|
||||
import request from '../request.js';
|
||||
|
||||
function slugify(name) {
|
||||
return name
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.normalize('NFD')
|
||||
.replace(/\p{M}/gu, '')
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '');
|
||||
}
|
||||
|
||||
export default function createUnderParent(pool) {
|
||||
const access = resolveCategoryAccess(pool);
|
||||
const ensureUnit = ensureDefaultUnit(pool);
|
||||
const allocateSku = nextSku(pool);
|
||||
|
||||
return async ({ googleAuthId, parentId, name }) => {
|
||||
const { companyId, languageId } = await access(googleAuthId, parentId);
|
||||
|
||||
const tx = pool.transaction();
|
||||
await tx.begin();
|
||||
|
||||
try {
|
||||
const unitId = await ensureUnit(tx);
|
||||
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 tx.commit();
|
||||
|
||||
return {
|
||||
id,
|
||||
parentId,
|
||||
name,
|
||||
sku,
|
||||
};
|
||||
} catch (err) {
|
||||
try {
|
||||
await tx.rollback();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user