Add category.move to reparent a category.

Validates both source and target via resolveCategoryAccess so the new
parent must be a category of the same authorized company, and guards
against moving into a descendant (cycle). Assigns next sibling sort.
This commit is contained in:
seb
2026-08-03 03:01:02 +02:00
parent b070607357
commit d8d66ce105
5 changed files with 114 additions and 0 deletions

View File

@@ -0,0 +1,67 @@
import {
GET_NEXT_SIBLING_SORT,
IS_ANCESTOR,
MOVE,
} from '../../sql/category.js';
import request from '../request.js';
import resolveCategoryAccess from './resolveCategoryAccess.js';
export default function move(pool) {
const access = resolveCategoryAccess(pool);
return async ({ googleAuthId, id, parentId }) => {
// Source category auth (throws if missing / not authorized).
const source = await access(googleAuthId, id);
// Target must be a valid category for the same authorized user/company.
const target = await access(googleAuthId, parentId);
if (target.companyId !== source.companyId) {
throw new Error('Parent not found');
}
if (id === parentId) {
throw new Error('Invalid parent');
}
const cycle = await pool
.request()
.input('id', id)
.input('parentId', parentId)
.query(IS_ANCESTOR);
if (cycle.recordset[0]) {
throw new Error('Invalid parent');
}
const tx = pool.transaction();
await tx.begin();
try {
const sortResult = await request(pool, tx)
.input('parentId', parentId)
.query(GET_NEXT_SIBLING_SORT);
const sort = sortResult.recordset[0].sort;
const result = await request(pool, tx)
.input('id', id)
.input('parentId', parentId)
.input('sort', sort)
.query(MOVE);
if (!result.rowsAffected[0]) {
throw new Error('Category not found');
}
await tx.commit();
return { id, parentId, sort };
} catch (err) {
try {
await tx.rollback();
} catch {
// ignore
}
throw err;
}
};
}