All files / lib observations.js

7.29% Statements 7/96
5% Branches 2/40
16.66% Functions 5/30
7.5% Lines 6/80

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    2x 9x     7x 2x     2x           4x                                                                                                                                                                              
import { generateId } from '$lib/database.js';
 
import * as db from './idb.svelte.js';
import { tables } from './idb.svelte.js';
import { deleteImage } from './images.js';
import {
	mergeMetadataFromImagesAndObservations,
	serializeMetadataFullValue,
} from './metadata/index.js';
import { uiState } from './state.svelte.js';
import { compareBy, mapValues, nonnull, transformObject } from './utils.js';
 
/**
 * @import * as DB from '$lib/database.js'
 * @import { NamespacedMetadataID } from '$lib/schemas/common.js'
 * @import { TypedMetadataValue } from '$lib/metadata/types.js'
 */
 
/**
 * @param {string[]} parts IDs of observations or images to merge
 * @returns {Promise<string>} the ID of the new observation
 */
export async function mergeToObservation(parts) {
	const protocol = uiState.currentProtocol;
	if (!protocol) throw new Error('No protocol selected');
 
	const sessionId = uiState.currentSession?.id;
	if (!sessionId) throw new Error('No session selected');
 
	const observations = parts.map((part) => tables.Observation.getFromState(part)).filter(nonnull);
 
	const images = await Promise.all(parts.map(async (part) => tables.Image.raw.get(part))).then(
		(imgs) => imgs.filter(nonnull)
	);
 
	const imageIds = new Set(observations.flatMap((o) => o.images)).union(
		new Set(images.map((i) => i.id))
	);
 
	const newId = generateId('Observation');
 
	const observation = {
		id: newId,
		sessionId,
		images: [...imageIds].toSorted(compareBy((id) => parts.indexOf(id))),
		addedAt: new Date().toISOString(),
		label: fallbackObservationLabel([...observations, ...images]),
		metadataOverrides: mapValues(
			mergeMetadataFromImagesAndObservations({
				definitions: tables.Metadata.state,
				images: [],
				observations,
			}),
			serializeMetadataFullValue
		),
	};
 
	await tables.Observation.do(undefined, (tx) => {
		tx.add(observation);
		for (const { id } of observations) {
			tx.delete(id);
		}
	});
 
	return newId;
}
 
/**
 *
 * @param {string} id observation ID
 * @param {object} [param1]
 * @param {boolean} [param1.recursive=false] Also delete the observation's images
 * @param {boolean} [param1.notFoundOk=true] Don't throw an error if the observation is not found
 * @param {import('./idb.svelte').IDBTransactionWithAtLeast<["Observation", "Image", "ImageFile", "ImagePreviewFile"]>} [param1.tx]
 */
export async function deleteObservation(
	id,
	{ recursive = false, notFoundOk = true, tx = undefined } = {}
) {
	await db.openTransaction(
		['Observation', 'Image', 'ImageFile', 'ImagePreviewFile'],
		{ tx },
		async (tx) => {
			const observation = await tx.objectStore('Observation').get(id);
			if (!observation) {
				if (notFoundOk) return;
				throw 'Observation non trouvée';
			}
 
			tx.objectStore('Observation').delete(id);
 
			if (recursive) {
				console.debug(`Deleting images of observation ${id}: `, observation.images);
				for (const imageId of observation.images) {
					await deleteImage(imageId, tx, notFoundOk);
				}
			}
 
			uiState.erroredImages.delete(id);
		}
	);
}
 
/**
 *  If removing images causes the observation to be empty, it is deleted
 * @param {object} options
 * @param {string} options.observation observation ID
 * @param {string[]} options.images image IDs to remove from the observation
 * @param {import('./idb.svelte.js').IDBTransactionWithAtLeast<["Observation"]>} [options.tx] re-use an ongoing transaction
 */
export async function removeImagesFromObservation({
	observation: observationId,
	images: imageIds,
	tx,
}) {
	await db.openTransaction(
		['Observation'],
		{ tx, session: uiState.currentSessionId },
		async (tx) => {
			const observation = await tx.objectStore('Observation').get(observationId);
			if (!observation) throw new Error(`Observation ${observationId} not found`);
			const remaining = observation.images.filter((id) => !imageIds.includes(id));
 
			if (remaining.length === 0) {
				console.debug(
					`Removing ${imageIds} from ${observationId}: observation would be empty, deleting it`
				);
				await tx.objectStore('Observation').delete(observationId);
			} else {
				console.debug(`Removing ${imageIds} from ${observationId}: ${remaining} remains`);
				await tx.objectStore('Observation').put({
					...observation,
					images: remaining,
				});
			}
		}
	);
}
 
/**
 * @param {Array<{ filename: string} | {label: string}>} parts
 * @returns {string} computed fallback label for the new observation
 */
function fallbackObservationLabel(parts) {
	for (const part of parts) {
		if ('label' in part) return part.label;
		if ('filename' in part) return part.filename.replace(/\.[^.]+$/, '');
	}
	return 'Nouvelle observation';
}
 
/**
 *
 * @param {Pick<typeof import('$lib/database').Schemas.Image.inferIn & DB.Image, "id" | "filename">} image
 * @param {import('$lib/database').Session} session
 * @returns {typeof import('$lib/database').Schemas.Observation.inferIn}
 */
export function newObservation(image, session) {
	const observationId = generateId('Observation');
	return {
		id: observationId,
		sessionId: session.id,
		images: [image.id],
		addedAt: new Date().toISOString(),
		label: fallbackObservationLabel([image]),
		metadataOverrides: {},
	};
}
 
/**
 * If there are any images that are not inside any observation, create an observation with a single image for each
 * @param {import('./idb.svelte').IDBTransactionWithAtLeast<["Observation", "Image"]>} [tx] reuse an existing transaction
 */
export async function ensureNoLoneImages(tx) {
	const session = uiState.currentSession;
	const protocol = uiState.currentProtocol;
	if (!protocol) throw new Error('No protocol selected');
	if (!session) throw new Error('No session selected');
 
	await db.openTransaction(['Observation', 'Image'], { tx }, async (tx) => {
		const images = await tx.objectStore('Image').index('sessionId').getAll(session.id);
		const observations = await tx
			.objectStore('Observation')
			.index('sessionId')
			.getAll(session.id);
 
		for (const image of images) {
			if (!observations.some((o) => o.images.includes(image.id))) {
				const newObs = newObservation(image, session);
				tx.objectStore('Observation').add(newObs);
				// Update ui selection so we don't have ghosts in preview side panel
				uiState.setSelection?.(
					uiState.selection.map((sel) => (sel === image.id ? newObs.id : sel))
				);
			}
		}
	});
}
 
/**
 * Deletes observations that have no (existing) images
 * @param {import('./idb.svelte').IDBTransactionWithAtLeast<["Observation", "Image"]>} [tx] reuse an existing transaction
 */
export async function ensureNoEmptyObservations(tx) {
	await db.openTransaction(['Observation', 'Image'], { tx }, async (tx) => {
		const observations = await tx.objectStore('Observation').getAll();
		for (const observation of observations) {
			const images = await Promise.all(
				observation.images.map((imageId) => tx.objectStore('Image').get(imageId))
			);
			const existing = images.filter(nonnull);
 
			if (existing.length === 0) {
				console.warn(
					`Deleting observation ${observation.id} because it has no images`,
					observation
				);
				tx.objectStore('Observation').delete(observation.id);
				// Update ui selection so we don't have ghosts in preview side panel
				uiState.setSelection?.(uiState.selection.filter((sel) => sel !== observation.id));
				uiState.erroredImages.delete(observation.id);
			} else {
				// If some images exist, but not all, remove the non-existing ones from the observation.
				if (existing.length !== observation.images.length) {
					tx.objectStore('Observation').put({
						...observation,
						images: existing.map(({ id }) => id),
					});
					console.info(
						`Updating observation ${observation.id} because some of its images were deleted`,
						observation,
						existing
					);
				}
			}
		}
	});
}
 
/**
 * Gets all metadata for an observation, including metadata derived from merging the metadata values of the images that make up the observation.
 * @template {DB.MetadataType} [T=DB.MetadataType]
 * @param {object} arg0
 * @param {DB.Metadata[]} arg0.definitions
 * @param {Pick<DB.Observation, 'images' | 'metadataOverrides'>} arg0.observation
 * @param {DB.Image[]} arg0.images
 * @param {T} [arg0.filterType] If provided, only return values for metadata of this type
 * @returns {Record<NamespacedMetadataID, TypedMetadataValue<T>>}
 */
export function observationMetadata({ definitions, observation, images, filterType }) {
	const metadataFromImages = mergeMetadataFromImagesAndObservations({
		definitions: definitions.filter((d) => !filterType || d.type === filterType),
		observations: [],
		images: images
			.filter(({ id }) => observation.images.includes(id))
			.toSorted(compareBy(({ id }) => observation.images.indexOf(id))),
	});
 
	return transformObject(
		{
			...metadataFromImages,
			...observation.metadataOverrides,
		},
		(id, value) => {
			Eif (!filterType) return [id, value];
			if (definitions.find((d) => d.id === id)?.type !== filterType) {
				return undefined;
			}
 
			return [id, value];
		}
	);
}
 
if (import.meta.vitest) {
	const { describe, it, expect } = import.meta.vitest;
	const { metadatas, items } = await import('./metadata/_testdata.js');
 
	/**
	 * @type {DB.Image[]}
	 */
	const images = items.map(({ id, metadata }) => ({
		id,
		filename: id + '.jpg',
		metadata,
		sessionId: 'session1',
		addedAt: new Date(),
		boundingBoxesAnalyzed: true,
		contentType: 'image/jpeg',
		dimensions: { width: 100, height: 100, aspectRatio: 1 },
		fileId: 'file_' + id,
	}));
 
	describe('observationMetadata', () => {
		it('merges metadata from images and observation overrides', () => {
			const observation = {
				images: items.slice(0, 2).map(({ id }) => id),
				metadataOverrides: {
					[metadatas.enum.id]: {
						...items[0].metadata.enum,
						value: 'A',
					},
				},
			};
 
			expect(
				observationMetadata({
					definitions: Object.values(metadatas),
					observation,
					images,
				})
			).toMatchInlineSnapshot(`
				{
				  "metadata_date": {
				    "alternatives": [],
				    "confidence": 1,
				    "confidences": {},
				    "confirmed": false,
				    "isDefault": false,
				    "manuallyModified": false,
				    "merged": true,
				    "value": 2023-01-01T12:00:15.000Z,
				  },
				  "metadata_enum ": {
				    "value": "A",
				  },
				  "metadata_float": {
				    "alternatives": [],
				    "confidence": 1,
				    "confidences": {},
				    "confirmed": false,
				    "isDefault": false,
				    "manuallyModified": false,
				    "merged": true,
				    "value": 10.124500000000001,
				  },
				  "metadata_integer": {
				    "alternatives": [],
				    "confidence": 1,
				    "confidences": {},
				    "confirmed": false,
				    "isDefault": false,
				    "manuallyModified": false,
				    "merged": false,
				    "value": 10,
				  },
				}
			`);
		});
	});
}