Add category.order to reorder siblings under a parent.

Sets each direct child's sort to its index in the given categoryIds,
scoped by parentId. Validates the set matches the current children.
This commit is contained in:
seb
2026-08-02 19:41:54 +02:00
parent e96bfb0624
commit b070607357
5 changed files with 108 additions and 0 deletions

View File

@@ -9,6 +9,7 @@ import categoryGetTreeForCompany from './store/category/getTreeForCompany.js';
import categoryGetCategoryArticles from './store/category/getCategoryArticles.js';
import categoryCreateUnderParent from './store/category/createUnderParent.js';
import categoryRename from './store/category/rename.js';
import categoryOrder from './store/category/order.js';
import categoryDelete from './store/category/delete.js';
import articleDelete from './store/article/delete.js';
import articleDeleteImage from './store/article/deleteImage.js';
@@ -73,6 +74,7 @@ export default class LibDashStore {
getCategoryArticles: categoryGetCategoryArticles(pool),
createUnderParent: categoryCreateUnderParent(pool),
rename: categoryRename(pool),
order: categoryOrder(pool),
delete: categoryDelete(pool),
};

View File

@@ -91,6 +91,18 @@ FROM category
WHERE parent_id = @parentId
`;
export const LIST_CHILD_IDS = `
SELECT id
FROM category
WHERE parent_id = @parentId
`;
export const UPDATE_SORT = `
UPDATE category
SET sort = @sort
WHERE id = @id AND parent_id = @parentId
`;
export const DELETE = `
DELETE FROM category
WHERE id = @id

View File

@@ -0,0 +1,62 @@
import {
LIST_CHILD_IDS,
UPDATE_SORT,
} from '../../sql/category.js';
import request from '../request.js';
import resolveCategoryAccess from './resolveCategoryAccess.js';
export default function order(pool) {
const access = resolveCategoryAccess(pool);
return async ({ googleAuthId, parentId, categoryIds }) => {
if (!Array.isArray(categoryIds)) {
throw new Error('Invalid category order');
}
// Auth + ensures parentId is a real category of the user's company.
await access(googleAuthId, parentId);
const children = await pool
.request()
.input('parentId', parentId)
.query(LIST_CHILD_IDS);
const existing = new Set(children.recordset.map((r) => r.id));
if (categoryIds.length !== existing.size) {
throw new Error('Invalid category order');
}
const seen = new Set();
for (const categoryId of categoryIds) {
if (!Number.isFinite(categoryId) || !existing.has(categoryId) || seen.has(categoryId)) {
throw new Error('Invalid category order');
}
seen.add(categoryId);
}
const tx = pool.transaction();
await tx.begin();
try {
for (let sort = 0; sort < categoryIds.length; sort++) {
await request(pool, tx)
.input('id', categoryIds[sort])
.input('parentId', parentId)
.input('sort', sort)
.query(UPDATE_SORT);
}
await tx.commit();
return { categoryIds };
} catch (err) {
try {
await tx.rollback();
} catch {
// ignore
}
throw err;
}
};
}