u
This commit is contained in:
77
src/store/article/updateBySku.js
Normal file
77
src/store/article/updateBySku.js
Normal file
@@ -0,0 +1,77 @@
|
||||
import { GET_BY_SKU, GET_CATEGORY_ID_BY_SKU } from '../../sql/article.js';
|
||||
import { UPDATE_BY_ARTICLE_AND_LANGUAGE } from '../../sql/articletext.js';
|
||||
import resolveCategoryAccess from '../category/resolveCategoryAccess.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 updateBySku(pool) {
|
||||
const access = resolveCategoryAccess(pool);
|
||||
|
||||
return async (googleAuthId, sku, { name }) => {
|
||||
if (!name?.trim()) {
|
||||
throw new Error('Name required');
|
||||
}
|
||||
|
||||
const categoryLookup = await pool
|
||||
.request()
|
||||
.input('sku', sku)
|
||||
.query(GET_CATEGORY_ID_BY_SKU);
|
||||
|
||||
const row = categoryLookup.recordset[0];
|
||||
if (!row?.categoryId || !row?.articleId) {
|
||||
throw new Error('Article not found');
|
||||
}
|
||||
|
||||
const { languageId, posCustomerGroupId } = await access(
|
||||
googleAuthId,
|
||||
row.categoryId,
|
||||
);
|
||||
|
||||
const slug = slugify(name);
|
||||
const tx = pool.transaction();
|
||||
await tx.begin();
|
||||
|
||||
try {
|
||||
const update = await request(pool, tx)
|
||||
.input('articleId', row.articleId)
|
||||
.input('languageId', languageId)
|
||||
.input('name', name.trim())
|
||||
.input('slug', slug)
|
||||
.query(UPDATE_BY_ARTICLE_AND_LANGUAGE);
|
||||
|
||||
if (!update.rowsAffected[0]) {
|
||||
throw new Error('Article not found');
|
||||
}
|
||||
|
||||
const result = await request(pool, tx)
|
||||
.input('sku', sku)
|
||||
.input('languageId', languageId)
|
||||
.input('posCustomerGroupId', posCustomerGroupId)
|
||||
.query(GET_BY_SKU);
|
||||
|
||||
const article = result.recordset[0];
|
||||
if (!article) {
|
||||
throw new Error('Article not found');
|
||||
}
|
||||
|
||||
await tx.commit();
|
||||
return article;
|
||||
} catch (err) {
|
||||
try {
|
||||
await tx.rollback();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user