Files
dashlibstorage/src/store/article/updateBySku.js
seb 12e83a7ffb Add company-scoped unit list/upsert/delete and article unit patches.
Units are isolated per company; article detail exposes full unit shape, and unused units can be deleted safely via FK NO ACTION.
2026-08-01 06:12:24 +02:00

115 lines
3.1 KiB
JavaScript

import {
UPDATE_UNIT,
UPDATE_UNITAMOUNT,
UPDATE_UNIT_AND_AMOUNT,
} from '../../sql/article.js';
import { UPDATE_BY_ARTICLE_AND_LANGUAGE } from '../../sql/articletext.js';
import { GET_BY_SI } from '../../sql/unit.js';
import request from '../request.js';
import queryBySku from './queryBySku.js';
import resolveArticleBySku from './resolveArticleBySku.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 resolve = resolveArticleBySku(pool);
const load = queryBySku(pool);
return async (googleAuthId, sku, patch = {}) => {
const hasName = Object.prototype.hasOwnProperty.call(patch, 'name');
const hasUnitamount = Object.prototype.hasOwnProperty.call(patch, 'unitamount');
const hasUnitSi = Object.prototype.hasOwnProperty.call(patch, 'unitSi');
if (!hasName && !hasUnitamount && !hasUnitSi) {
throw new Error('Name required');
}
if (hasName && !patch.name?.trim()) {
throw new Error('Name required');
}
if (hasUnitamount && (!Number.isFinite(patch.unitamount) || patch.unitamount <= 0)) {
throw new Error('Invalid unitamount');
}
const { articleId, languageId, companyId } = await resolve(googleAuthId, sku);
let unitId;
if (hasUnitSi) {
if (!patch.unitSi?.trim()) {
throw new Error('Unit not found');
}
const unit = await pool
.request()
.input('companyId', companyId)
.input('si', patch.unitSi.trim())
.query(GET_BY_SI);
unitId = unit.recordset[0]?.id;
if (!unitId) {
throw new Error('Unit not found');
}
}
const tx = pool.transaction();
await tx.begin();
try {
if (hasName) {
const slug = slugify(patch.name);
const update = await request(pool, tx)
.input('articleId', articleId)
.input('languageId', languageId)
.input('name', patch.name.trim())
.input('slug', slug)
.query(UPDATE_BY_ARTICLE_AND_LANGUAGE);
if (!update.rowsAffected[0]) {
throw new Error('Article not found');
}
}
if (hasUnitSi && hasUnitamount) {
await request(pool, tx)
.input('articleId', articleId)
.input('unitId', unitId)
.input('unitamount', patch.unitamount)
.query(UPDATE_UNIT_AND_AMOUNT);
} else if (hasUnitSi) {
await request(pool, tx)
.input('articleId', articleId)
.input('unitId', unitId)
.query(UPDATE_UNIT);
} else if (hasUnitamount) {
await request(pool, tx)
.input('articleId', articleId)
.input('unitamount', patch.unitamount)
.query(UPDATE_UNITAMOUNT);
}
await tx.commit();
} catch (err) {
try {
await tx.rollback();
} catch {
// ignore
}
throw err;
}
const article = await load(articleId, languageId);
if (!article) {
throw new Error('Article not found');
}
return article;
};
}