Dev-only bulk delete all campaigns; deleteCollection SQL bulk + gates
Feature: debug button to wipe all campaigns/encounters/logs in dev builds.
Previously bulk delete fetched all logs per campaign, client-filtered,
batchWrite — 30s+/campaign. Now SQL bulk DELETE, no fetch.
Server (server/db.js, server/index.js):
- deleteCollection(collPath, {where}) — SQL DELETE FROM docs WHERE parent=?,
optional where-filter. Broadcasts deletions to WS subscribers.
- DELETE /api/collection endpoint
- Gate: ALLOW_DEV_ENDPOINTS=1 env OR createServer({allowDevEndpoints:true})
- createServer accepts allowDevEndpoints param (tests bypass env)
Storage (src/storage/server.js, src/storage/firebase.js):
- deleteCollection(path, whereField, whereValue) both adapters
- Firebase: fetch matching + batch-delete (firestore no bulk), 500-chunk
- Gate: throws if NODE_ENV not development/test
- Contract-tested both backends
App (src/App.js):
- deleteCampaignCascade refactored (reusable, no try/catch split)
- handleDeleteAllCampaigns: Promise.all per campaign, deleteCollection for
encounters (no fetch), deleteCollection logs once globally, parallel
- Button dev-gated (NODE_ENV), confirm modal, hidden when no campaigns
Mock fixes (surfaced by new tests):
- firebase firestore mock: added where() export, getDocs applies constraints
(was returning all docs ignoring query constraints — pre-existing gap)
Tests:
- contract: deleteCollection (bulk, where-filter, empty) both backends
- server-contract: live deleteCollection (bulk, where, 403 gate)
- runStorageContract via makeStorage({allowDevEndpoints:true})
Safety (3 layers):
- UI button hidden in prod (NODE_ENV gate)
- storage method throws in prod (NODE_ENV gate)
- HTTP endpoint 403 in prod (env/param gate)
This commit is contained in:
+91
-40
@@ -2313,50 +2313,81 @@ function AdminView({ userId }) {
|
||||
if (!db || !itemToDelete) return;
|
||||
|
||||
const campaignId = itemToDelete.id;
|
||||
await deleteCampaignCascade(campaignId);
|
||||
|
||||
try {
|
||||
const encountersPath = getPath.encounters(campaignId);
|
||||
const encounters = await storage.getCollection(encountersPath);
|
||||
const deleteOps = encounters.map(e => {
|
||||
const id = e.id || e.path?.split('/').pop();
|
||||
return { type: 'delete', path: `${encountersPath}/${id}` };
|
||||
});
|
||||
|
||||
// cascade: delete logs for every encounter in this campaign
|
||||
const allLogs = await storage.getCollection(getPath.logs());
|
||||
const encPaths = new Set(encounters.map(e => `${encountersPath}/${e.id || e.path?.split('/').pop()}`));
|
||||
const encIds = new Set(encounters.map(e => e.id || e.path?.split('/').pop()));
|
||||
const logOps = allLogs
|
||||
.filter(l =>
|
||||
(l.encounterId && encIds.has(l.encounterId)) ||
|
||||
(l.encounterPath && [...encPaths].some(p => l.encounterPath.includes(p)))
|
||||
)
|
||||
.map(l => ({
|
||||
type: 'delete',
|
||||
path: `${getPath.logs()}/${l.id || l.path?.split('/').pop()}`,
|
||||
}));
|
||||
|
||||
if (deleteOps.length > 0 || logOps.length > 0) {
|
||||
await storage.batchWrite([...deleteOps, ...logOps]);
|
||||
}
|
||||
|
||||
await storage.deleteDoc(getPath.campaign(campaignId));
|
||||
|
||||
if (selectedCampaignId === campaignId) {
|
||||
setSelectedCampaignId(null);
|
||||
}
|
||||
|
||||
const activeDisplay = await storage.getDoc(getPath.activeDisplay());
|
||||
|
||||
if (activeDisplay && activeDisplay.activeCampaignId === campaignId) {
|
||||
await storage.updateDoc(getPath.activeDisplay(), { activeCampaignId: null, activeEncounterId: null });
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Error deleting campaign:", err);
|
||||
showToast("Failed to delete campaign. Please try again."); }
|
||||
if (selectedCampaignId === campaignId) {
|
||||
setSelectedCampaignId(null);
|
||||
}
|
||||
|
||||
setShowDeleteConfirm(false);
|
||||
setItemToDelete(null);
|
||||
showToast('Campaign deleted.');
|
||||
};
|
||||
|
||||
// Cascade delete: encounters + logs + display + campaign doc.
|
||||
const deleteCampaignCascade = async (campaignId) => {
|
||||
const encountersPath = getPath.encounters(campaignId);
|
||||
const encounters = await storage.getCollection(encountersPath);
|
||||
const deleteOps = encounters.map(e => {
|
||||
const id = e.id || e.path?.split('/').pop();
|
||||
return { type: 'delete', path: `${encountersPath}/${id}` };
|
||||
});
|
||||
|
||||
const allLogs = await storage.getCollection(getPath.logs());
|
||||
const encPaths = new Set(encounters.map(e => `${encountersPath}/${e.id || e.path?.split('/').pop()}`));
|
||||
const encIds = new Set(encounters.map(e => e.id || e.path?.split('/').pop()));
|
||||
const logOps = allLogs
|
||||
.filter(l =>
|
||||
(l.encounterId && encIds.has(l.encounterId)) ||
|
||||
(l.encounterPath && [...encPaths].some(p => l.encounterPath.includes(p)))
|
||||
)
|
||||
.map(l => ({
|
||||
type: 'delete',
|
||||
path: `${getPath.logs()}/${l.id || l.path?.split('/').pop()}`,
|
||||
}));
|
||||
|
||||
if (deleteOps.length > 0 || logOps.length > 0) {
|
||||
await storage.batchWrite([...deleteOps, ...logOps]);
|
||||
}
|
||||
|
||||
await storage.deleteDoc(getPath.campaign(campaignId));
|
||||
|
||||
const activeDisplay = await storage.getDoc(getPath.activeDisplay());
|
||||
if (activeDisplay && activeDisplay.activeCampaignId === campaignId) {
|
||||
await storage.updateDoc(getPath.activeDisplay(), { activeCampaignId: null, activeEncounterId: null });
|
||||
}
|
||||
};
|
||||
|
||||
// Dev-only: wipe all campaigns + encounters + logs. Irreversible.
|
||||
// Uses deleteCollection (SQL bulk DELETE, no fetch). Parallel per campaign.
|
||||
const [showDeleteAllConfirm, setShowDeleteAllConfirm] = useState(false);
|
||||
const handleDeleteAllCampaigns = async () => {
|
||||
if (!db) return;
|
||||
try {
|
||||
const all = await storage.getCollection(getPath.campaigns());
|
||||
await Promise.all(all.map(async (c) => {
|
||||
const cid = c.id || c.path?.split('/').pop();
|
||||
// bulk-delete all encounters under this campaign (SQL DELETE, no fetch)
|
||||
if (storage.deleteCollection) {
|
||||
await storage.deleteCollection(getPath.encounters(cid));
|
||||
}
|
||||
await storage.deleteDoc(getPath.campaign(cid));
|
||||
}));
|
||||
// nuke all logs in one shot (orphans acceptable in dev; logs span campaigns)
|
||||
if (storage.deleteCollection) {
|
||||
await storage.deleteCollection(getPath.logs());
|
||||
}
|
||||
const activeDisplay = await storage.getDoc(getPath.activeDisplay());
|
||||
if (activeDisplay && activeDisplay.activeCampaignId) {
|
||||
await storage.updateDoc(getPath.activeDisplay(), { activeCampaignId: null, activeEncounterId: null });
|
||||
}
|
||||
setSelectedCampaignId(null);
|
||||
setShowDeleteAllConfirm(false);
|
||||
showToast(`Deleted ${all.length} campaign(s).`);
|
||||
} catch (err) {
|
||||
console.error('Error deleting all campaigns:', err);
|
||||
showToast('Failed to delete all campaigns.');
|
||||
}
|
||||
};
|
||||
|
||||
const selectedCampaign = campaignsWithDetails.find(c => c.id === selectedCampaignId);
|
||||
@@ -2495,6 +2526,26 @@ function AdminView({ userId }) {
|
||||
title="Delete Campaign?"
|
||||
message={`Are you sure you want to delete the campaign "${itemToDelete?.name}" and all its encounters? This action cannot be undone.`}
|
||||
/>
|
||||
|
||||
{process.env.NODE_ENV === 'development' && campaignsWithDetails.length > 0 && (
|
||||
<div className="mt-4">
|
||||
<button
|
||||
onClick={() => setShowDeleteAllConfirm(true)}
|
||||
className="px-3 py-1.5 text-xs rounded bg-red-900 hover:bg-red-800 text-red-100 border border-red-700"
|
||||
title="DEV ONLY: Delete every campaign, encounter, and log. Irreversible."
|
||||
>
|
||||
<Trash2 size={12} className="inline mr-1" />DEV: Delete All Campaigns
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ConfirmationModal
|
||||
isOpen={showDeleteAllConfirm}
|
||||
onClose={() => setShowDeleteAllConfirm(false)}
|
||||
onConfirm={handleDeleteAllCampaigns}
|
||||
title="Delete ALL Campaigns?"
|
||||
message="DEV ONLY: This permanently deletes EVERY campaign, all encounters, and all logs. Cannot be undone. Are you absolutely sure?"
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user