import { UPDATE_WEIGHT as MSSQL_UPDATE_WEIGHT } from '../../providers/mssql/queries/article.js'; import { UPDATE_WEIGHT as SQLITE_UPDATE_WEIGHT } from '../../providers/sqlite3/queries/article.js'; import { INSERT as MSSQL_INSERT_HISTORY } from '../../providers/mssql/queries/articlehistory.js'; import { INSERT as SQLITE_INSERT_HISTORY } from '../../providers/sqlite3/queries/articlehistory.js'; import queryBySku from './queryBySku.js'; import resolveArticleBySku from './resolveArticleBySku.js'; import makeRunner from '../runner.js'; export default function setWeightBySku(provider) { const resolve = resolveArticleBySku(provider); const load = queryBySku(provider); const sql = provider?.dialect === 'sqlite3' ? SQLITE_UPDATE_WEIGHT : MSSQL_UPDATE_WEIGHT; const insertHistorySql = provider?.dialect === 'sqlite3' ? SQLITE_INSERT_HISTORY : MSSQL_INSERT_HISTORY; /** * Sets the weight of an article by its SKU. * * @param {number} googleAuthId - The id of the Google auth user. * @param {string} sku - The article SKU. * @param {number} weight - The weight (must be >= 0). * @param {object} [tx] - Optional transaction. * @returns {Promise} The updated article. * @throws {Error} If the weight is invalid or the article is not found. * * @example * const article = await store.article.setWeightBySku(42, 'SKU-1', 1.5); * // => { id, sku, name, ... } */ return async (googleAuthId, sku, weight, tx) => { if (!Number.isFinite(weight) || weight < 0) { throw new Error('Invalid weight'); } const runner = makeRunner(provider, tx); const { articleId, languageId, companyuserId } = await resolve(googleAuthId, sku, runner); // Read old weight for history const oldRes = await runner.query( 'SELECT weight FROM article WHERE id = @articleId', { articleId }, ); const oldWeight = oldRes.rows[0]?.weight ?? 0; const result = await runner.query(sql, { articleId, weight, }); if (!result.rowsAffected) { throw new Error('Article not found'); } // Write history if weight changed if (Number(oldWeight) !== weight) { await runner.query(insertHistorySql, { articleId, companyuserId, text: `Gewicht geƤndert von "${oldWeight}" auf "${weight}"`, }); } const article = await load(articleId, languageId, runner); if (!article) { throw new Error('Article not found'); } return article; }; }