diff --git a/src/datasources/product-api.ts b/src/datasources/product-api.ts index b695a8b..0fa57fc 100644 --- a/src/datasources/product-api.ts +++ b/src/datasources/product-api.ts @@ -962,7 +962,17 @@ export class ProductAPI extends BaseSQLDataSource { .filter(Boolean)[0]; // Remove falsy } - // Delete all prior interiors + // Get the mapping of interior_id to roomtype_id before delete + // This data will be lost when we delete from interiors due to CASCADE + const priorRoomtypes = await this.knex.raw( + `SELECT irt.interior_id, irt.roomtype_id + FROM interiors_roomtypes irt + INNER JOIN interiors i ON i.id = irt.interior_id + WHERE i.print_id = ?`, + [insertPrintId], + ); + + // Delete all prior interiors (this will cascade delete interiors_roomtypes) await this.knex.raw(`DELETE FROM interiors WHERE print_id = ?`, [ insertPrintId, ]); @@ -987,7 +997,28 @@ export class ProductAPI extends BaseSQLDataSource { } }); - return Promise.all(insertPromises); + // Wait for all interiors to be inserted first + await Promise.all(insertPromises); + + // Re-insert the roomtypes for custom interiors that preserved their IDs + // Custom interiors keep their ID on re-insertion (line with item.id above) + const roomtypesPromises = []; + for (const priorRoomtype of priorRoomtypes.rows) { + // Check if this interior_id still exists (custom interiors preserve their ID) + const interiorStillExists = insertRegistry.some( + (item) => item.id === priorRoomtype.interior_id, + ); + if (interiorStillExists) { + roomtypesPromises.push( + this.knex.raw( + `INSERT INTO interiors_roomtypes (interior_id, roomtype_id) VALUES (?, ?)`, + [priorRoomtype.interior_id, priorRoomtype.roomtype_id], + ), + ); + } + } + + return Promise.all(roomtypesPromises); } /**