Fix issue #44: Sync item folders
Some checks failed
Test / test (push) Failing after 2s

This commit is contained in:
Gitea OpenCode Agent
2026-10-14 23:39:26 +00:00
parent c7d20dd1f7
commit 1f9ab330b9
14 changed files with 981 additions and 23 deletions

View File

@@ -12,8 +12,20 @@ const FolderSchema = new Schema({
type: Schema.Types.ObjectId,
ref: 'Folder'
},
// Which campaign list a folder belongs to. Note folders are what this model has
// always held, and their rows carry no target at all, so everything reading the
// note tree asks for `{ target: { $ne: 'item' } }` and keeps finding them.
target: { type: String, enum: ['note', 'item'], default: 'note' },
// The Foundry item folder this row mirrors, set by the item sync only
// (see routes/foundry-link.js).
foundryFolderId: { type: String },
color: { type: String },
date: { type: Date, default: Date.now }
});
FolderSchema.index(
{ campaign: 1, foundryFolderId: 1 },
{ unique: true, partialFilterExpression: { foundryFolderId: { $type: 'string' } } }
);
module.exports = mongoose.model('Folder', FolderSchema);

View File

@@ -28,6 +28,13 @@ const ItemSchema = new Schema({
ref: 'Campaign',
required: true
},
// The folder this item stands in: a Folder of the same campaign whose target is
// 'item' (null = the root of the item list).
folder: {
type: Schema.Types.ObjectId,
ref: 'Folder',
default: null
},
foundryItemId: { type: String },
// Names Foundry uses for this item. Dragonroll may rename it, and the copies
// Foundry keeps sending still have to fold into this row instead of

View File

@@ -4,6 +4,7 @@ const router = express.Router();
const Campaign = require('../models/Campaign');
const Folder = require('../models/Folder');
const Note = require('../models/Note');
const Item = require('../models/Item');
async function userOwnsCampaign(campaignId, userId) {
const campaign = await Campaign.findOne({ _id: campaignId, createdBy: userId }).lean();
@@ -18,7 +19,7 @@ router.get('/list', async (req, res) => {
const hasAccess = await userOwnsCampaign(campaign, req.user.id);
if (!hasAccess) return res.json({ status: 'error', msg: 'unauthorized' });
const folders = await Folder.find({ campaign })
const folders = await Folder.find({ campaign, target: { $ne: 'item' } })
.select('_id name date color')
.sort({ date: -1 })
.lean();
@@ -89,6 +90,12 @@ router.post('/delete', async (req, res) => {
{ folder: folderId },
{ $set: { folder: null, date: Date.now() } }
);
// Item folders share this model: the items inside move to the root of
// the item list rather than point at a folder that is gone.
await Item.updateMany(
{ folder: folderId },
{ $set: { folder: null } }
);
await Folder.deleteOne({ _id: folderId });
for (const sub of subfolders) {
await moveRecursive(sub._id);

View File

@@ -6,6 +6,7 @@ const router = express.Router();
const Campaign = require('../models/Campaign');
const Actor = require('../models/Actor');
const Item = require('../models/Item');
const Folder = require('../models/Folder');
const { foundryActorToCharacter } = require('../services/actor-foundry');
const { foundryItemToItemData } = require('../services/item-foundry');
@@ -81,7 +82,7 @@ function snapshotItemSources(body) {
return sources;
}
async function saveFoundryItem(campaign, source, fullSync = false) {
async function saveFoundryItem(campaign, source, fullSync = false, folders = null) {
const foundryItemId = String(source?._id || source?.id || '').trim().slice(0, 120);
const fields = foundryItemToItemData(source || {});
if (!foundryItemId || !fields) return null;
@@ -115,19 +116,113 @@ async function saveFoundryItem(campaign, source, fullSync = false) {
if (!item.foundryNames.includes(fields.name)) {
item.foundryNames = [...item.foundryNames, fields.name].slice(-MAX_FOUNDRY_NAMES);
}
// Which folder of the campaign's item tree the world says this item stands in.
// `undefined` means the push says nothing about folders — an item embedded in an
// actor, or a module that knows nothing about them — and the item stays where it
// is. The world owns the folder of its own directory, so a move lands on a full
// snapshot too: nothing on the Dragonroll side files items by hand.
const folder = resolveFoundryItemFolder(source, folders);
if (folder !== undefined) item.folder = folder;
await item.save();
return { foundryItemId, itemId: item.id };
}
async function syncFoundryItems(campaign, sources, fullSync = false) {
async function syncFoundryItems(campaign, sources, fullSync = false, folders = null) {
const items = [];
for (const source of sources) {
const mapping = await saveFoundryItem(campaign, source, fullSync);
const mapping = await saveFoundryItem(campaign, source, fullSync, folders);
if (mapping) items.push(mapping);
}
return items;
}
// --- Item folders ------------------------------------------------------------
// A Foundry world groups its item directory into folders; the campaign mirrors that
// tree as Folders of target 'item' so its item list reads like the world's. Every
// push from a module that knows about folders carries the whole world tree, and
// names the folder each world item it sends stands in. Items embedded in an actor
// say nothing: the folders they carry belong to that actor's own inventory, and
// Dragonroll keeps one item per piece of gear anyway.
// Parents before children, so a folder is mapped before the one nested in it.
// A folder whose parent is missing, or caught in a cycle, becomes a root.
function orderFoundryFolderSources(sources) {
const byId = new Map();
for (const source of sources) {
const id = String(source?.id || '').trim().slice(0, 120);
const name = String(source?.name || '').trim();
if (!id || !name) continue;
byId.set(id, { id, name, parent: String(source?.parent || '').trim().slice(0, 120) });
}
const ordered = [];
const placed = new Set();
const visiting = new Set();
function place(id) {
if (!byId.has(id) || placed.has(id) || visiting.has(id)) return;
visiting.add(id);
place(byId.get(id).parent);
visiting.delete(id);
placed.add(id);
ordered.push(byId.get(id));
}
for (const id of byId.keys()) place(id);
return ordered;
}
// The campaign folders mirroring the world's item folder tree, keyed by the Foundry
// folder id so pushing the same tree again neither doubles a folder nor loses the
// items filed in it. Rows the campaign made for its own items (no foundryFolderId)
// are left alone: the world does not know them.
async function syncFoundryItemFolders(campaign, folderSources) {
const folders = new Map();
for (const folder of await Folder.find({ campaign: campaign._id, target: 'item' })) {
if (folder.foundryFolderId) folders.set(String(folder.foundryFolderId), folder);
}
const ordered = orderFoundryFolderSources(folderSources);
const inTree = new Set(ordered.map((source) => source.id));
for (const source of ordered) {
let folder = folders.get(source.id);
if (!folder) {
folder = new Folder({
campaign: campaign._id,
target: 'item',
foundryFolderId: source.id,
name: source.name
});
}
// The world owns this tree, so unlike an item's fields a rename or a move
// lands whatever kind of push carried it: the whole tree arrives with each.
folder.name = source.name;
const parent = inTree.has(source.parent) ? folders.get(source.parent) : null;
folder.parentFolder = parent ? parent._id : null;
await folder.save();
folders.set(source.id, folder);
}
// Folders the world no longer has go with it, and the items standing in them
// move to the root instead of pointing at a folder that is not there.
const staleIds = [...folders.values()]
.filter((folder) => folder.foundryFolderId && !inTree.has(String(folder.foundryFolderId)))
.map((folder) => folder._id);
if (staleIds.length) {
await Item.updateMany({ campaign: campaign._id, folder: { $in: staleIds } }, { $set: { folder: null } });
await Folder.deleteMany({ campaign: campaign._id, _id: { $in: staleIds } });
}
return folders;
}
// The folder of a pushed item: undefined when the push says nothing about folders,
// null for the root of the item directory, and the campaign folder otherwise. An
// id the tree does not know puts the item at the root rather than nowhere.
function resolveFoundryItemFolder(source, folders) {
const foundryFolderId = source?.dragonroll?.folder;
if (!folders || typeof foundryFolderId !== 'string') return undefined;
return folders.get(foundryFolderId.trim())?._id || null;
}
// Linking a world to a campaign happens through the sign-up link every service
// uses (routes/service-link.js); what stays here is the sync that world keeps up
// with the campaign once that link has handed it its token.
@@ -163,12 +258,16 @@ router.post('/sync/snapshot', async (req, res) => {
}
const fullSync = req.body.fullSync === true;
// A module that knows nothing about item folders sends neither the tree
// nor the folder of an item, and then nothing here touches the folders.
const folderSources = Array.isArray(req.body.folders) ? req.body.folders : null;
const actors = [];
for (const source of actorSources || []) {
const mapping = await saveFoundryActor(campaign, source, fullSync);
if (mapping) actors.push(mapping);
}
const items = await syncFoundryItems(campaign, snapshotItemSources(req.body), fullSync);
const itemFolders = folderSources ? await syncFoundryItemFolders(campaign, folderSources) : null;
const items = await syncFoundryItems(campaign, snapshotItemSources(req.body), fullSync, itemFolders);
if (fullSync && actorSources) {
const currentIds = actorSources
@@ -197,17 +296,21 @@ router.post('/sync/snapshot', async (req, res) => {
}
});
// Live Foundry item edits: upserts only, never prunes. Removing items that no
// longer exist is left to the full snapshot sent with the actors.
// Live Foundry item edits: upserts only, never prunes items. Removing items that no
// longer exist is left to the full snapshot sent with the actors. Item folders are
// the exception: every request carries the world's whole folder tree, so a folder
// the world dropped is dropped here too, and a push may carry folders only.
router.post('/sync/item-snapshot', async (req, res) => {
try {
const campaign = await syncCampaign(req, res);
if (!campaign) return;
const folderSources = Array.isArray(req.body.folders) ? req.body.folders : null;
if (!requestMatchesWorld(campaign, req.body.worldId) || !Array.isArray(req.body.items)) {
return res.json({ status: 'error', msg: 'errors.missing-data' });
}
res.json({ status: 'ok', items: await syncFoundryItems(campaign, req.body.items) });
const folders = folderSources ? await syncFoundryItemFolders(campaign, folderSources) : null;
res.json({ status: 'ok', items: await syncFoundryItems(campaign, req.body.items, false, folders) });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });

View File

@@ -5,12 +5,22 @@ const upload = require('../services/storage');
const Campaign = require('../models/Campaign');
const Item = require('../models/Item');
const Folder = require('../models/Folder');
async function userOwnsCampaign(campaignId, userId) {
const campaign = await Campaign.findOne({ _id: campaignId, createdBy: userId }).lean();
return Boolean(campaign);
}
// Folders the campaign's items are grouped into, in the shape the sidebar groups by
// (the world's own item folders arrive through the sync, see routes/foundry-link.js).
async function itemFolders(campaignId) {
return Folder.find({ campaign: campaignId, target: 'item' })
.select('_id name parentFolder date')
.sort({ date: -1 })
.lean();
}
router.get('/list', async (req, res) => {
try {
const { campaign } = req.query;
@@ -18,7 +28,7 @@ router.get('/list', async (req, res) => {
if (!(await userOwnsCampaign(campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' });
const items = await Item.find({ campaign }).sort({ name: 1 }).lean();
res.json({ status: 'ok', items });
res.json({ status: 'ok', items, folders: await itemFolders(campaign) });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });

View File

@@ -19,7 +19,9 @@ router.get('/list', async (req, res) => {
const hasAccess = await userOwnsCampaign(campaign, req.user.id);
if (!hasAccess) return res.json({ status: 'error', msg: 'unauthorized' });
const folders = await Folder.find({ campaign })
// The note tree only: item folders share this model and would otherwise
// turn up as empty folders between the notes.
const folders = await Folder.find({ campaign, target: { $ne: 'item' } })
.select('_id name parentFolder date color')
.sort({ date: -1 })
.lean();
@@ -48,7 +50,7 @@ router.get('/subfolder/list', async (req, res) => {
const folderDoc = await Folder.findOne({ _id: folder, campaign }).lean();
if (!folderDoc) return res.json({ status: 'error', msg: 'errors.notfound' });
const subfolders = await Folder.find({ campaign, parentFolder: folder })
const subfolders = await Folder.find({ campaign, parentFolder: folder, target: { $ne: 'item' } })
.select('_id name date color')
.sort({ date: -1 })
.lean();
@@ -80,7 +82,7 @@ router.get('/all', async (req, res) => {
.sort({ title: 1 })
.lean();
const folders = await Folder.find({ campaign })
const folders = await Folder.find({ campaign, target: { $ne: 'item' } })
.select('_id name parentFolder')
.lean();