import { GET_ID_BY_SKU, SET_FATHER_SORT, SET_IS_FATHER, UPDATE_FATHER_BY_SKU, } from '../../providers/mssql/queries/article.js'; import { GET_CHILD_COUNT } from '../../providers/mssql/queries/articleDelete.js'; import request from '../request.js'; import queryBySku from './queryBySku.js'; import resolveArticleBySku from './resolveArticleBySku.js'; export default function setFatherBySku(pool) { const resolve = resolveArticleBySku(pool); const load = queryBySku(pool); /** * Links an article to a father article (V/K compound) by their SKUs. * * @param {number} googleAuthId - The id of the Google auth user. * @param {string} sku - The child article SKU. * @param {string|null} fatherSku - The father article SKU, or `null` to unlink. * @returns {Promise} The updated child article. * @throws {Error} If the article or father is not found, or the link is invalid. * * @example * const article = await store.article.setFatherBySku(42, '42001190-1', '42001190'); * // => { id, sku, name, fatherSku: '42001190', ... } */ return async (googleAuthId, sku, fatherSku) => { const { articleId, languageId } = await resolve(googleAuthId, sku); if (fatherSku == null || fatherSku === '') { await request(pool) .input('sku', sku) .input('fatherArticleId', null) .query(UPDATE_FATHER_BY_SKU); const unlinked = await load(articleId, languageId); if (!unlinked) { throw new Error('Article not found'); } return unlinked; } const father = await pool .request() .input('sku', fatherSku) .query(GET_ID_BY_SKU); const fatherId = father.recordset[0]?.articleId; if (!fatherId) { throw new Error('Father not found'); } if (fatherId === articleId) { throw new Error('Invalid father'); } const tx = pool.transaction(); await tx.begin(); try { await request(pool, tx) .input('sku', sku) .input('fatherArticleId', fatherId) .query(UPDATE_FATHER_BY_SKU); await request(pool, tx) .input('articleId', fatherId) .query(SET_IS_FATHER); const childCount = await request(pool, tx) .input('articleId', fatherId) .query(GET_CHILD_COUNT); const count = childCount.recordset[0].count; // The child's sort is its 0-based position among the father's children. await request(pool, tx) .input('articleId', articleId) .input('fatherArticleId', fatherId) .input('fathersort', count - 1) .query(SET_FATHER_SORT); 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; }; }