Add article.setPricesBySku to replace POS prices for a SKU.

Gives dashback a single store call that atomically replaces all price rows for the article’s poscustomergroup.
This commit is contained in:
seb
2026-08-01 05:16:50 +02:00
parent 9be9f7f74c
commit 54700a145e
5 changed files with 156 additions and 1 deletions

View File

@@ -0,0 +1,104 @@
import {
CREATE as CREATE_PRICE,
DELETE_BY_ARTICLE_AND_CUSTOMERGROUP,
} from '../../sql/price.js';
import request from '../request.js';
import taxEnsure from '../tax/ensure.js';
import queryBySku from './queryBySku.js';
import resolveArticleBySku from './resolveArticleBySku.js';
function normalizePrices(prices) {
if (!Array.isArray(prices)) {
throw new Error('Invalid prices');
}
const seen = new Set();
const normalized = [];
for (const entry of prices) {
const price = entry?.price;
const tax = entry?.tax;
const minmultiplier =
entry?.minmultiplier === undefined || entry?.minmultiplier === null
? 1
: entry.minmultiplier;
if (!Number.isFinite(price) || !Number.isFinite(tax) || !Number.isFinite(minmultiplier)) {
throw new Error('Invalid prices');
}
if (minmultiplier <= 0) {
throw new Error('Invalid prices');
}
const key = String(minmultiplier);
if (seen.has(key)) {
throw new Error('Invalid prices');
}
seen.add(key);
normalized.push({ price, tax, minmultiplier });
}
return normalized;
}
export default function setPricesBySku(pool) {
const resolve = resolveArticleBySku(pool);
const ensureTax = taxEnsure(pool);
const load = queryBySku(pool);
return async (googleAuthId, sku, prices) => {
const normalized = normalizePrices(prices);
const { articleId, languageId, posCustomerGroupId } = await resolve(
googleAuthId,
sku,
);
if (!posCustomerGroupId) {
throw new Error('POS customer group required');
}
const tx = pool.transaction();
await tx.begin();
try {
const taxIds = new Map();
for (const entry of normalized) {
if (!taxIds.has(entry.tax)) {
taxIds.set(entry.tax, await ensureTax(entry.tax, tx));
}
}
await request(pool, tx)
.input('articleId', articleId)
.input('customerGroupId', posCustomerGroupId)
.query(DELETE_BY_ARTICLE_AND_CUSTOMERGROUP);
for (const entry of normalized) {
await request(pool, tx)
.input('taxId', taxIds.get(entry.tax))
.input('articleId', articleId)
.input('minmultiplier', entry.minmultiplier)
.input('customerGroupId', posCustomerGroupId)
.input('net', entry.price)
.query(CREATE_PRICE);
}
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;
};
}