feat(articlesupplier): implement store methods, schema constraints, and embed in getBySku
This commit is contained in:
69
src/store/articlesupplier/delete.js
Normal file
69
src/store/articlesupplier/delete.js
Normal file
@@ -0,0 +1,69 @@
|
||||
import {
|
||||
DELETE_BY_ID_AND_ARTICLE_ID,
|
||||
DELETE_PRICE,
|
||||
GET_BY_ID_AND_ARTICLE_ID,
|
||||
} from '../../sql/articlesupplier.js';
|
||||
import request from '../request.js';
|
||||
import resolveArticleBySku from '../article/resolveArticleBySku.js';
|
||||
|
||||
export default function del(pool) {
|
||||
const resolve = resolveArticleBySku(pool);
|
||||
|
||||
/**
|
||||
* Deletes a supplier assignment and cleans up its associated purchase price.
|
||||
*
|
||||
* @param {number} googleAuthId - The id of the Google auth user.
|
||||
* @param {string} sku - The article SKU.
|
||||
* @param {number} id - The id of the articlesupplier record.
|
||||
* @returns {Promise<void>}
|
||||
* @throws {Error} If the supplier assignment is not found.
|
||||
*
|
||||
* @example
|
||||
* await store.articlesupplier.delete(42, 'SKU-1', 12);
|
||||
*/
|
||||
return async (googleAuthId, sku, id) => {
|
||||
if (id == null || !Number.isFinite(id)) {
|
||||
throw new Error('Supplier assignment not found');
|
||||
}
|
||||
|
||||
const { articleId, companyId } = await resolve(googleAuthId, sku);
|
||||
|
||||
const existingRes = await pool
|
||||
.request()
|
||||
.input('id', id)
|
||||
.input('articleId', articleId)
|
||||
.input('companyId', companyId)
|
||||
.query(GET_BY_ID_AND_ARTICLE_ID);
|
||||
|
||||
const existing = existingRes.recordset[0];
|
||||
if (!existing) {
|
||||
throw new Error('Supplier assignment not found');
|
||||
}
|
||||
|
||||
const tx = pool.transaction();
|
||||
await tx.begin();
|
||||
|
||||
try {
|
||||
await request(pool, tx)
|
||||
.input('id', id)
|
||||
.input('articleId', articleId)
|
||||
.query(DELETE_BY_ID_AND_ARTICLE_ID);
|
||||
|
||||
if (existing.priceId != null) {
|
||||
await request(pool, tx)
|
||||
.input('id', existing.priceId)
|
||||
.input('articleId', articleId)
|
||||
.query(DELETE_PRICE);
|
||||
}
|
||||
|
||||
await tx.commit();
|
||||
} catch (err) {
|
||||
try {
|
||||
await tx.rollback();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user