forked from enviPath/enviPy
[Feature] Dynamic additional information rendering in frontend (#282)
This implements a version of #274, relying on Pydantics built in JSON schema and JSON rendering. Requires additional UI tagging in the ai model repo but will remove HTML tags. Example scenario with filled information: 5882df9c-dae1-4d80-a40e-db4724271456/scenario/3a4d395a-6a6d-4154-8ce3-ced667fceec0 Reviewed-on: enviPath/enviPy#282 Co-authored-by: Tobias O <tobias.olenyi@envipath.com> Co-committed-by: Tobias O <tobias.olenyi@envipath.com>
This commit is contained in:
253
static/js/alpine/components/schema-form.js
Normal file
253
static/js/alpine/components/schema-form.js
Normal file
@ -0,0 +1,253 @@
|
||||
/**
|
||||
* Alpine.js Schema Renderer Component
|
||||
*
|
||||
* Renders forms dynamically from JSON Schema with RJSF format support.
|
||||
* Supports uiSchema for widget hints, labels, help text, and field ordering.
|
||||
*
|
||||
* Usage:
|
||||
* <div x-data="schemaRenderer({
|
||||
* rjsf: { schema: {...}, uiSchema: {...}, formData: {...}, groups: [...] },
|
||||
* data: { interval: { start: 20, end: 25 } },
|
||||
* mode: 'view', // 'view' | 'edit'
|
||||
* endpoint: '/api/v1/scenario/{uuid}/information/temperature/'
|
||||
* })">
|
||||
*/
|
||||
document.addEventListener('alpine:init', () => {
|
||||
Alpine.data('schemaRenderer', (options = {}) => ({
|
||||
schema: null,
|
||||
uiSchema: {},
|
||||
data: {},
|
||||
mode: options.mode || 'view', // 'view' | 'edit'
|
||||
endpoint: options.endpoint || '',
|
||||
loading: false,
|
||||
error: null,
|
||||
fieldErrors: {}, // Server-side field-level errors
|
||||
|
||||
async init() {
|
||||
// Listen for field error events from parent modal
|
||||
window.addEventListener('set-field-errors', (e) => {
|
||||
// Apply to all forms (used by add modal which has only one form)
|
||||
this.fieldErrors = e.detail || {};
|
||||
});
|
||||
|
||||
// Listen for field error events targeted to a specific item (for update modal)
|
||||
window.addEventListener('set-field-errors-for-item', (e) => {
|
||||
// Only update if this form matches the UUID
|
||||
const itemData = options.data || {};
|
||||
if (itemData.uuid === e.detail?.uuid) {
|
||||
this.fieldErrors = e.detail.fieldErrors || {};
|
||||
}
|
||||
});
|
||||
|
||||
if (options.schemaUrl) {
|
||||
try {
|
||||
this.loading = true;
|
||||
const res = await fetch(options.schemaUrl);
|
||||
if (!res.ok) {
|
||||
throw new Error(`Failed to load schema: ${res.statusText}`);
|
||||
}
|
||||
const rjsf = await res.json();
|
||||
|
||||
// RJSF format: {schema, uiSchema, formData, groups}
|
||||
if (!rjsf.schema) {
|
||||
throw new Error('Invalid RJSF format: missing schema property');
|
||||
}
|
||||
|
||||
this.schema = rjsf.schema;
|
||||
this.uiSchema = rjsf.uiSchema || {};
|
||||
this.data = options.data
|
||||
? JSON.parse(JSON.stringify(options.data))
|
||||
: (rjsf.formData || {});
|
||||
} catch (err) {
|
||||
this.error = err.message;
|
||||
console.error('Error loading schema:', err);
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
} else if (options.rjsf) {
|
||||
// Direct RJSF object passed
|
||||
if (!options.rjsf.schema) {
|
||||
throw new Error('Invalid RJSF format: missing schema property');
|
||||
}
|
||||
|
||||
this.schema = options.rjsf.schema;
|
||||
this.uiSchema = options.rjsf.uiSchema || {};
|
||||
this.data = options.data
|
||||
? JSON.parse(JSON.stringify(options.data))
|
||||
: (options.rjsf.formData || {});
|
||||
}
|
||||
|
||||
// Initialize data from formData or options
|
||||
if (!this.data || Object.keys(this.data).length === 0) {
|
||||
this.data = {};
|
||||
}
|
||||
|
||||
// Ensure all schema fields are properly initialized
|
||||
if (this.schema && this.schema.properties) {
|
||||
for (const [key, propSchema] of Object.entries(this.schema.properties)) {
|
||||
const widget = this.getWidget(key, propSchema);
|
||||
|
||||
if (widget === 'interval') {
|
||||
// Ensure interval fields are objects with start/end
|
||||
if (!this.data[key] || typeof this.data[key] !== 'object') {
|
||||
this.data[key] = { start: null, end: null };
|
||||
} else {
|
||||
// Ensure start and end exist
|
||||
if (this.data[key].start === undefined) this.data[key].start = null;
|
||||
if (this.data[key].end === undefined) this.data[key].end = null;
|
||||
}
|
||||
} else if (widget === 'timeseries-table') {
|
||||
// Ensure timeseries fields are arrays
|
||||
if (!this.data[key] || !Array.isArray(this.data[key])) {
|
||||
this.data[key] = [];
|
||||
}
|
||||
} else if (this.data[key] === undefined) {
|
||||
// ONLY initialize if truly undefined, not just falsy
|
||||
// This preserves empty strings, null, 0, false as valid values
|
||||
if (propSchema.type === 'boolean') {
|
||||
this.data[key] = false;
|
||||
} else if (propSchema.type === 'number' || propSchema.type === 'integer') {
|
||||
this.data[key] = null;
|
||||
} else if (propSchema.enum) {
|
||||
// For select fields, use null to show placeholder
|
||||
this.data[key] = null;
|
||||
} else {
|
||||
this.data[key] = '';
|
||||
}
|
||||
}
|
||||
// If data[key] exists (even if empty string or null), don't overwrite
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
getWidget(fieldName, fieldSchema) {
|
||||
// Check uiSchema first (RJSF format)
|
||||
if (this.uiSchema[fieldName] && this.uiSchema[fieldName]['ui:widget']) {
|
||||
return this.uiSchema[fieldName]['ui:widget'];
|
||||
}
|
||||
|
||||
// Check for interval type (object with start/end properties)
|
||||
if (fieldSchema.type === 'object' &&
|
||||
fieldSchema.properties &&
|
||||
fieldSchema.properties.start &&
|
||||
fieldSchema.properties.end) {
|
||||
return 'interval';
|
||||
}
|
||||
|
||||
// Infer from JSON Schema type
|
||||
if (fieldSchema.enum) return 'select';
|
||||
if (fieldSchema.type === 'number' || fieldSchema.type === 'integer') return 'number';
|
||||
if (fieldSchema.type === 'boolean') return 'checkbox';
|
||||
return 'text';
|
||||
},
|
||||
|
||||
getLabel(fieldName, fieldSchema) {
|
||||
// Check uiSchema (RJSF format)
|
||||
if (this.uiSchema[fieldName] && this.uiSchema[fieldName]['ui:label']) {
|
||||
return this.uiSchema[fieldName]['ui:label'];
|
||||
}
|
||||
|
||||
// Default: format field name
|
||||
return fieldName.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase());
|
||||
},
|
||||
|
||||
getHelp(fieldName) {
|
||||
// Get help text from uiSchema
|
||||
if (this.uiSchema[fieldName] && this.uiSchema[fieldName]['ui:help']) {
|
||||
return this.uiSchema[fieldName]['ui:help'];
|
||||
}
|
||||
return null;
|
||||
},
|
||||
|
||||
getPlaceholder(fieldName) {
|
||||
// Get placeholder from uiSchema
|
||||
if (this.uiSchema[fieldName] && this.uiSchema[fieldName]['ui:placeholder']) {
|
||||
return this.uiSchema[fieldName]['ui:placeholder'];
|
||||
}
|
||||
return null;
|
||||
},
|
||||
|
||||
getFieldOrder() {
|
||||
// Get ordered list of field names based on ui:order
|
||||
if (!this.schema || !this.schema.properties) return [];
|
||||
|
||||
const fields = Object.keys(this.schema.properties);
|
||||
|
||||
// Sort by ui:order if available
|
||||
return fields.sort((a, b) => {
|
||||
const orderA = this.uiSchema[a]?.['ui:order'] || '999';
|
||||
const orderB = this.uiSchema[b]?.['ui:order'] || '999';
|
||||
return parseInt(orderA) - parseInt(orderB);
|
||||
});
|
||||
},
|
||||
|
||||
async submit() {
|
||||
if (!this.endpoint) {
|
||||
console.error('No endpoint specified for submission');
|
||||
return;
|
||||
}
|
||||
|
||||
this.loading = true;
|
||||
this.error = null;
|
||||
|
||||
try {
|
||||
const csrftoken = document.querySelector("[name=csrf-token]")?.content || '';
|
||||
const res = await fetch(this.endpoint, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-CSRFToken': csrftoken
|
||||
},
|
||||
body: JSON.stringify(this.data)
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
let errorData;
|
||||
try {
|
||||
errorData = await res.json();
|
||||
} catch {
|
||||
errorData = { error: res.statusText };
|
||||
}
|
||||
|
||||
// Handle validation errors (field-level)
|
||||
this.fieldErrors = {};
|
||||
|
||||
// Try to parse structured error response
|
||||
let parsedError = errorData;
|
||||
|
||||
// If error is a JSON string, parse it
|
||||
if (typeof errorData.error === 'string' && errorData.error.startsWith('{')) {
|
||||
parsedError = JSON.parse(errorData.error);
|
||||
|
||||
}
|
||||
|
||||
if (parsedError.detail && Array.isArray(parsedError.detail)) {
|
||||
// Pydantic validation errors format: [{loc: ['field'], msg: '...', type: '...'}]
|
||||
for (const err of parsedError.detail) {
|
||||
const field = err.loc && err.loc.length > 0 ? err.loc[err.loc.length - 1] : 'root';
|
||||
if (!this.fieldErrors[field]) {
|
||||
this.fieldErrors[field] = [];
|
||||
}
|
||||
this.fieldErrors[field].push(err.msg || err.message || 'Validation error');
|
||||
}
|
||||
throw new Error('Validation failed. Please check the fields below.');
|
||||
} else {
|
||||
// General error
|
||||
throw new Error(parsedError.error || parsedError.detail || `Request failed: ${res.statusText}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Clear errors on success
|
||||
this.fieldErrors = {};
|
||||
|
||||
const result = await res.json();
|
||||
return result;
|
||||
} catch (err) {
|
||||
this.error = err.message;
|
||||
throw err;
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
}
|
||||
}));
|
||||
});
|
||||
186
static/js/alpine/components/widgets.js
Normal file
186
static/js/alpine/components/widgets.js
Normal file
@ -0,0 +1,186 @@
|
||||
/**
|
||||
* Alpine.js Widget Components for Schema Forms
|
||||
*
|
||||
* Centralized widget component definitions for dynamic form rendering.
|
||||
* Each widget receives explicit parameters instead of context object for better traceability.
|
||||
*/
|
||||
document.addEventListener('alpine:init', () => {
|
||||
// Base widget factory with common functionality
|
||||
const baseWidget = (fieldName, data, schema, uiSchema, fieldErrors, mode) => ({
|
||||
fieldName,
|
||||
data,
|
||||
schema,
|
||||
uiSchema,
|
||||
fieldErrors,
|
||||
mode,
|
||||
|
||||
// Field schema access
|
||||
get fieldSchema() {
|
||||
return this.schema?.properties?.[this.fieldName] || {};
|
||||
},
|
||||
|
||||
// Common metadata
|
||||
get label() {
|
||||
// Check uiSchema first (RJSF format)
|
||||
if (this.uiSchema?.[this.fieldName]?.['ui:label']) {
|
||||
return this.uiSchema[this.fieldName]['ui:label'];
|
||||
}
|
||||
// Fall back to schema title
|
||||
if (this.fieldSchema.title) {
|
||||
return this.fieldSchema.title;
|
||||
}
|
||||
// Default: format field name
|
||||
return this.fieldName.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase());
|
||||
},
|
||||
get helpText() {
|
||||
return this.fieldSchema.description || '';
|
||||
},
|
||||
|
||||
// Field-level unit extraction from uiSchema (RJSF format)
|
||||
get unit() {
|
||||
return this.uiSchema?.[this.fieldName]?.['ui:unit'] || null;
|
||||
},
|
||||
|
||||
// Error handling
|
||||
get hasError() {
|
||||
return !!this.fieldErrors?.[this.fieldName];
|
||||
},
|
||||
get errors() {
|
||||
return this.fieldErrors?.[this.fieldName] || [];
|
||||
},
|
||||
|
||||
// Mode checks
|
||||
get isViewMode() { return this.mode === 'view'; },
|
||||
get isEditMode() { return this.mode === 'edit'; },
|
||||
});
|
||||
|
||||
// Text widget
|
||||
Alpine.data('textWidget', (fieldName, data, schema, uiSchema, fieldErrors, mode) => ({
|
||||
...baseWidget(fieldName, data, schema, uiSchema, fieldErrors, mode),
|
||||
|
||||
get value() { return this.data[this.fieldName] || ''; },
|
||||
set value(v) { this.data[this.fieldName] = v; },
|
||||
}));
|
||||
|
||||
// Textarea widget
|
||||
Alpine.data('textareaWidget', (fieldName, data, schema, uiSchema, fieldErrors, mode) => ({
|
||||
...baseWidget(fieldName, data, schema, uiSchema, fieldErrors, mode),
|
||||
|
||||
get value() { return this.data[this.fieldName] || ''; },
|
||||
set value(v) { this.data[this.fieldName] = v; },
|
||||
}));
|
||||
|
||||
// Number widget with unit support
|
||||
Alpine.data('numberWidget', (fieldName, data, schema, uiSchema, fieldErrors, mode) => ({
|
||||
...baseWidget(fieldName, data, schema, uiSchema, fieldErrors, mode),
|
||||
|
||||
get value() { return this.data[this.fieldName]; },
|
||||
set value(v) {
|
||||
this.data[this.fieldName] = v === '' || v === null ? null : parseFloat(v);
|
||||
},
|
||||
get hasValue() {
|
||||
return this.value !== null && this.value !== undefined && this.value !== '';
|
||||
},
|
||||
// Format value with unit for view mode
|
||||
get displayValue() {
|
||||
if (!this.hasValue) return '—';
|
||||
return this.unit ? `${this.value} ${this.unit}` : String(this.value);
|
||||
},
|
||||
}));
|
||||
|
||||
// Select widget
|
||||
Alpine.data('selectWidget', (fieldName, data, schema, uiSchema, fieldErrors, mode) => ({
|
||||
...baseWidget(fieldName, data, schema, uiSchema, fieldErrors, mode),
|
||||
|
||||
get value() { return this.data[this.fieldName] || ''; },
|
||||
set value(v) { this.data[this.fieldName] = v; },
|
||||
get options() { return this.fieldSchema.enum || []; },
|
||||
}));
|
||||
|
||||
// Checkbox widget
|
||||
Alpine.data('checkboxWidget', (fieldName, data, schema, uiSchema, fieldErrors, mode) => ({
|
||||
...baseWidget(fieldName, data, schema, uiSchema, fieldErrors, mode),
|
||||
|
||||
get checked() { return !!this.data[this.fieldName]; },
|
||||
set checked(v) { this.data[this.fieldName] = v; },
|
||||
}));
|
||||
|
||||
// Interval widget with unit support
|
||||
Alpine.data('intervalWidget', (fieldName, data, schema, uiSchema, fieldErrors, mode) => ({
|
||||
...baseWidget(fieldName, data, schema, uiSchema, fieldErrors, mode),
|
||||
|
||||
get start() {
|
||||
return this.data[this.fieldName]?.start ?? null;
|
||||
},
|
||||
set start(v) {
|
||||
if (!this.data[this.fieldName]) this.data[this.fieldName] = {};
|
||||
this.data[this.fieldName].start = v === '' || v === null ? null : parseFloat(v);
|
||||
},
|
||||
get end() {
|
||||
return this.data[this.fieldName]?.end ?? null;
|
||||
},
|
||||
set end(v) {
|
||||
if (!this.data[this.fieldName]) this.data[this.fieldName] = {};
|
||||
this.data[this.fieldName].end = v === '' || v === null ? null : parseFloat(v);
|
||||
},
|
||||
// Format interval with unit for view mode
|
||||
get displayValue() {
|
||||
const s = this.start, e = this.end;
|
||||
const unitStr = this.unit ? ` ${this.unit}` : '';
|
||||
|
||||
if (s !== null && e !== null) return `${s} – ${e}${unitStr}`;
|
||||
if (s !== null) return `≥ ${s}${unitStr}`;
|
||||
if (e !== null) return `≤ ${e}${unitStr}`;
|
||||
return '—';
|
||||
},
|
||||
|
||||
get isSameValue() {
|
||||
return this.start !== null && this.start === this.end;
|
||||
},
|
||||
|
||||
// Validation: start must be <= end
|
||||
get hasValidationError() {
|
||||
if (this.isViewMode) return false;
|
||||
const s = this.start;
|
||||
const e = this.end;
|
||||
// Only validate if both values are provided
|
||||
if (s !== null && e !== null && typeof s === 'number' && typeof e === 'number') {
|
||||
return s > e;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
|
||||
// Override hasError to include validation error
|
||||
get hasError() {
|
||||
return this.hasValidationError || !!this.fieldErrors?.[this.fieldName];
|
||||
},
|
||||
|
||||
// Override errors to include validation error message
|
||||
get errors() {
|
||||
const serverErrors = this.fieldErrors?.[this.fieldName] || [];
|
||||
const validationErrors = this.hasValidationError
|
||||
? ['Start value must be less than or equal to end value']
|
||||
: [];
|
||||
return [...validationErrors, ...serverErrors];
|
||||
},
|
||||
}));
|
||||
|
||||
// PubMed link widget
|
||||
Alpine.data('pubmedWidget', (fieldName, data, schema, uiSchema, fieldErrors, mode) => ({
|
||||
...baseWidget(fieldName, data, schema, uiSchema, fieldErrors, mode),
|
||||
|
||||
get value() { return this.data[this.fieldName] || ''; },
|
||||
set value(v) { this.data[this.fieldName] = v; },
|
||||
get pubmedUrl() {
|
||||
return this.value ? `https://pubmed.ncbi.nlm.nih.gov/${this.value}` : null;
|
||||
},
|
||||
}));
|
||||
|
||||
// Compound link widget
|
||||
Alpine.data('compoundWidget', (fieldName, data, schema, uiSchema, fieldErrors, mode) => ({
|
||||
...baseWidget(fieldName, data, schema, uiSchema, fieldErrors, mode),
|
||||
|
||||
get value() { return this.data[this.fieldName] || ''; },
|
||||
set value(v) { this.data[this.fieldName] = v; },
|
||||
}));
|
||||
});
|
||||
394
static/js/api/additional-information.js
Normal file
394
static/js/api/additional-information.js
Normal file
@ -0,0 +1,394 @@
|
||||
/**
|
||||
* Unified API client for Additional Information endpoints
|
||||
* Provides consistent error handling, logging, and CRUD operations
|
||||
*/
|
||||
window.AdditionalInformationApi = {
|
||||
// Configuration
|
||||
_debug: false,
|
||||
|
||||
/**
|
||||
* Enable or disable debug logging
|
||||
* @param {boolean} enabled - Whether to enable debug mode
|
||||
*/
|
||||
setDebug(enabled) {
|
||||
this._debug = enabled;
|
||||
},
|
||||
|
||||
/**
|
||||
* Internal logging helper
|
||||
* @private
|
||||
*/
|
||||
_log(action, data) {
|
||||
if (this._debug) {
|
||||
console.log(`[AdditionalInformationApi] ${action}:`, data);
|
||||
}
|
||||
},
|
||||
//FIXME: this has the side effect of users not being able to explicitly set an empty string for a field.
|
||||
/**
|
||||
* Remove empty strings from payload recursively
|
||||
* @param {any} value
|
||||
* @returns {any}
|
||||
*/
|
||||
sanitizePayload(value) {
|
||||
if (Array.isArray(value)) {
|
||||
return value
|
||||
.map(item => this.sanitizePayload(item))
|
||||
.filter(item => item !== '');
|
||||
}
|
||||
|
||||
if (value && typeof value === 'object') {
|
||||
const cleaned = {};
|
||||
for (const [key, item] of Object.entries(value)) {
|
||||
if (item === '') continue;
|
||||
cleaned[key] = this.sanitizePayload(item);
|
||||
}
|
||||
return cleaned;
|
||||
}
|
||||
|
||||
return value;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get CSRF token from meta tag
|
||||
* @returns {string} CSRF token
|
||||
*/
|
||||
getCsrfToken() {
|
||||
return document.querySelector('[name=csrf-token]')?.content || '';
|
||||
},
|
||||
|
||||
/**
|
||||
* Build headers for API requests
|
||||
* @private
|
||||
*/
|
||||
_buildHeaders(includeContentType = true) {
|
||||
const headers = {
|
||||
'X-CSRFToken': this.getCsrfToken()
|
||||
};
|
||||
if (includeContentType) {
|
||||
headers['Content-Type'] = 'application/json';
|
||||
}
|
||||
return headers;
|
||||
},
|
||||
|
||||
/**
|
||||
* Handle API response with consistent error handling
|
||||
* @private
|
||||
*/
|
||||
async _handleResponse(response, action) {
|
||||
if (!response.ok) {
|
||||
let errorData;
|
||||
try {
|
||||
errorData = await response.json();
|
||||
} catch {
|
||||
errorData = { error: response.statusText };
|
||||
}
|
||||
|
||||
// Try to parse the error if it's a JSON string
|
||||
let parsedError = errorData;
|
||||
if (typeof errorData.error === 'string' && errorData.error.startsWith('{')) {
|
||||
try {
|
||||
parsedError = JSON.parse(errorData.error);
|
||||
} catch {
|
||||
// Not JSON, use as-is
|
||||
}
|
||||
}
|
||||
|
||||
// If it's a structured validation error, throw with field errors
|
||||
if (parsedError.type === 'validation_error' && parsedError.field_errors) {
|
||||
this._log(`${action} VALIDATION ERROR`, parsedError);
|
||||
const error = new Error(parsedError.message || 'Validation failed');
|
||||
error.fieldErrors = parsedError.field_errors;
|
||||
error.isValidationError = true;
|
||||
throw error;
|
||||
}
|
||||
|
||||
// General error
|
||||
const errorMsg = parsedError.message || parsedError.error || parsedError.detail || `${action} failed: ${response.statusText}`;
|
||||
this._log(`${action} ERROR`, { status: response.status, error: errorMsg });
|
||||
throw new Error(errorMsg);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
this._log(`${action} SUCCESS`, data);
|
||||
return data;
|
||||
},
|
||||
|
||||
/**
|
||||
* Load all available schemas
|
||||
* @returns {Promise<Object>} Object with schema definitions
|
||||
*/
|
||||
async loadSchemas() {
|
||||
this._log('loadSchemas', 'Starting...');
|
||||
const response = await fetch('/api/v1/information/schema/');
|
||||
return this._handleResponse(response, 'loadSchemas');
|
||||
},
|
||||
|
||||
/**
|
||||
* Load additional information items for a scenario
|
||||
* @param {string} scenarioUuid - UUID of the scenario
|
||||
* @returns {Promise<Array>} Array of additional information items
|
||||
*/
|
||||
async loadItems(scenarioUuid) {
|
||||
this._log('loadItems', { scenarioUuid });
|
||||
const response = await fetch(`/api/v1/scenario/${scenarioUuid}/information/`);
|
||||
return this._handleResponse(response, 'loadItems');
|
||||
},
|
||||
|
||||
/**
|
||||
* Load both schemas and items in parallel
|
||||
* @param {string} scenarioUuid - UUID of the scenario
|
||||
* @returns {Promise<{schemas: Object, items: Array}>}
|
||||
*/
|
||||
async loadSchemasAndItems(scenarioUuid) {
|
||||
this._log('loadSchemasAndItems', { scenarioUuid });
|
||||
|
||||
const [schemas, items] = await Promise.all([
|
||||
this.loadSchemas(),
|
||||
this.loadItems(scenarioUuid)
|
||||
]);
|
||||
|
||||
return { schemas, items };
|
||||
},
|
||||
|
||||
/**
|
||||
* Create new additional information for a scenario
|
||||
* @param {string} scenarioUuid - UUID of the scenario
|
||||
* @param {string} modelName - Name/type of the additional information model
|
||||
* @param {Object} data - Data for the new item
|
||||
* @returns {Promise<{status: string, uuid: string}>}
|
||||
*/
|
||||
async createItem(scenarioUuid, modelName, data) {
|
||||
const sanitizedData = this.sanitizePayload(data);
|
||||
this._log('createItem', { scenarioUuid, modelName, data: sanitizedData });
|
||||
|
||||
// Normalize model name to lowercase
|
||||
const normalizedName = modelName.toLowerCase();
|
||||
|
||||
const response = await fetch(
|
||||
`/api/v1/scenario/${scenarioUuid}/information/${normalizedName}/`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: this._buildHeaders(),
|
||||
body: JSON.stringify(sanitizedData)
|
||||
}
|
||||
);
|
||||
|
||||
return this._handleResponse(response, 'createItem');
|
||||
},
|
||||
|
||||
/**
|
||||
* Delete additional information from a scenario
|
||||
* @param {string} scenarioUuid - UUID of the scenario
|
||||
* @param {string} itemUuid - UUID of the item to delete
|
||||
* @returns {Promise<{status: string}>}
|
||||
*/
|
||||
async deleteItem(scenarioUuid, itemUuid) {
|
||||
this._log('deleteItem', { scenarioUuid, itemUuid });
|
||||
|
||||
const response = await fetch(
|
||||
`/api/v1/scenario/${scenarioUuid}/information/item/${itemUuid}/`,
|
||||
{
|
||||
method: 'DELETE',
|
||||
headers: this._buildHeaders(false)
|
||||
}
|
||||
);
|
||||
|
||||
return this._handleResponse(response, 'deleteItem');
|
||||
},
|
||||
|
||||
/**
|
||||
* Update existing additional information
|
||||
* Tries PATCH first, falls back to delete+recreate if not supported
|
||||
* @param {string} scenarioUuid - UUID of the scenario
|
||||
* @param {Object} item - Item object with uuid, type, and data properties
|
||||
* @returns {Promise<{status: string, uuid: string}>}
|
||||
*/
|
||||
async updateItem(scenarioUuid, item) {
|
||||
const sanitizedData = this.sanitizePayload(item.data);
|
||||
this._log('updateItem', { scenarioUuid, item: { ...item, data: sanitizedData } });
|
||||
|
||||
const { uuid, type } = item;
|
||||
|
||||
// Try PATCH first (preferred method - preserves UUID)
|
||||
const response = await fetch(
|
||||
`/api/v1/scenario/${scenarioUuid}/information/item/${uuid}/`,
|
||||
{
|
||||
method: 'PATCH',
|
||||
headers: this._buildHeaders(),
|
||||
body: JSON.stringify(sanitizedData)
|
||||
}
|
||||
);
|
||||
|
||||
if (response.status === 405) {
|
||||
// PATCH not supported, fall back to delete+recreate
|
||||
this._log('updateItem', 'PATCH not supported, falling back to delete+recreate');
|
||||
await this.deleteItem(scenarioUuid, uuid);
|
||||
return await this.createItem(scenarioUuid, type, sanitizedData);
|
||||
}
|
||||
|
||||
return this._handleResponse(response, 'updateItem');
|
||||
},
|
||||
|
||||
/**
|
||||
* Update multiple items sequentially to avoid race conditions
|
||||
* @param {string} scenarioUuid - UUID of the scenario
|
||||
* @param {Array<Object>} items - Array of items to update
|
||||
* @returns {Promise<Array>} Array of results with success status
|
||||
*/
|
||||
async updateItems(scenarioUuid, items) {
|
||||
this._log('updateItems', { scenarioUuid, itemCount: items.length });
|
||||
|
||||
const results = [];
|
||||
for (const item of items) {
|
||||
try {
|
||||
const result = await this.updateItem(scenarioUuid, item);
|
||||
results.push({ success: true, oldUuid: item.uuid, newUuid: result.uuid });
|
||||
} catch (error) {
|
||||
results.push({
|
||||
success: false,
|
||||
oldUuid: item.uuid,
|
||||
error: error.message,
|
||||
fieldErrors: error.fieldErrors,
|
||||
isValidationError: error.isValidationError
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const failed = results.filter(r => !r.success);
|
||||
if (failed.length > 0) {
|
||||
// If all failures are validation errors, throw a validation error
|
||||
const validationErrors = failed.filter(f => f.isValidationError);
|
||||
if (validationErrors.length === failed.length && failed.length === 1) {
|
||||
// Single validation error - preserve field errors for display
|
||||
const error = new Error(failed[0].error);
|
||||
error.fieldErrors = failed[0].fieldErrors;
|
||||
error.isValidationError = true;
|
||||
error.itemUuid = failed[0].oldUuid;
|
||||
throw error;
|
||||
}
|
||||
// Multiple failures or mixed errors - show count
|
||||
throw new Error(`Failed to update ${failed.length} item(s). Please check the form for errors.`);
|
||||
}
|
||||
|
||||
return results;
|
||||
},
|
||||
|
||||
/**
|
||||
* Create a new scenario with optional additional information
|
||||
* @param {string} packageUuid - UUID of the package
|
||||
* @param {Object} payload - Scenario data matching ScenarioCreateSchema
|
||||
* @param {string} payload.name - Scenario name (required)
|
||||
* @param {string} payload.description - Scenario description (optional, default: "")
|
||||
* @param {string} payload.scenario_date - Scenario date (optional, default: "No date")
|
||||
* @param {string} payload.scenario_type - Scenario type (optional, default: "Not specified")
|
||||
* @param {Array} payload.additional_information - Array of additional information (optional, default: [])
|
||||
* @returns {Promise<{uuid, url, name, description, review_status, package}>}
|
||||
*/
|
||||
async createScenario(packageUuid, payload) {
|
||||
this._log('createScenario', { packageUuid, payload });
|
||||
const response = await fetch(
|
||||
`/api/v1/package/${packageUuid}/scenario/`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: this._buildHeaders(),
|
||||
body: JSON.stringify(payload)
|
||||
}
|
||||
);
|
||||
return this._handleResponse(response, 'createScenario');
|
||||
},
|
||||
|
||||
/**
|
||||
* Load all available group names
|
||||
* @returns {Promise<{groups: string[]}>}
|
||||
*/
|
||||
async loadGroups() {
|
||||
this._log('loadGroups', 'Starting...');
|
||||
const response = await fetch('/api/v1/information/groups/');
|
||||
return this._handleResponse(response, 'loadGroups');
|
||||
},
|
||||
|
||||
/**
|
||||
* Load model definitions for a specific group
|
||||
* @param {string} groupName - One of 'soil', 'sludge', 'sediment'
|
||||
* @returns {Promise<Object>} Object with subcategories as keys and arrays of model info
|
||||
*/
|
||||
async loadGroupModels(groupName) {
|
||||
this._log('loadGroupModels', { groupName });
|
||||
const response = await fetch(`/api/v1/information/groups/${groupName}/`);
|
||||
return this._handleResponse(response, `loadGroupModels-${groupName}`);
|
||||
},
|
||||
|
||||
/**
|
||||
* Load model information for multiple groups in parallel
|
||||
* @param {Array<string>} groupNames - Defaults to ['soil', 'sludge', 'sediment']
|
||||
* @returns {Promise<Object>} Object with group names as keys
|
||||
*/
|
||||
async loadGroupsWithModels(groupNames = ['soil', 'sludge', 'sediment']) {
|
||||
this._log('loadGroupsWithModels', { groupNames });
|
||||
|
||||
const results = {};
|
||||
const promises = groupNames.map(async (groupName) => {
|
||||
try {
|
||||
results[groupName] = await this.loadGroupModels(groupName);
|
||||
} catch (err) {
|
||||
this._log(`loadGroupsWithModels-${groupName} ERROR`, err);
|
||||
results[groupName] = {};
|
||||
}
|
||||
});
|
||||
|
||||
await Promise.all(promises);
|
||||
return results;
|
||||
},
|
||||
|
||||
/**
|
||||
* Helper to organize schemas by group based on group model information
|
||||
* @param {Object} schemas - Full schema map from loadSchemas()
|
||||
* @param {Object} groupModelsData - Group models data from loadGroupsWithModels()
|
||||
* @returns {Object} Object with group names as keys and filtered schemas as values
|
||||
*/
|
||||
organizeSchemasByGroup(schemas, groupModelsData) {
|
||||
this._log('organizeSchemasByGroup', {
|
||||
schemaCount: Object.keys(schemas).length,
|
||||
groupCount: Object.keys(groupModelsData).length
|
||||
});
|
||||
|
||||
const organized = {};
|
||||
|
||||
for (const groupName in groupModelsData) {
|
||||
organized[groupName] = {};
|
||||
const groupData = groupModelsData[groupName];
|
||||
|
||||
// Iterate through subcategories in the group
|
||||
for (const subcategory in groupData) {
|
||||
for (const model of groupData[subcategory]) {
|
||||
// Look up schema by lowercase model name
|
||||
if (schemas[model.name]) {
|
||||
organized[groupName][model.name] = schemas[model.name];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return organized;
|
||||
},
|
||||
|
||||
/**
|
||||
* Convenience method that loads schemas and organizes them by group in one call
|
||||
* @param {Array<string>} groupNames - Defaults to ['soil', 'sludge', 'sediment']
|
||||
* @returns {Promise<{schemas, groupSchemas, groupModels}>}
|
||||
*/
|
||||
async loadSchemasWithGroups(groupNames = ['soil', 'sludge', 'sediment']) {
|
||||
this._log('loadSchemasWithGroups', { groupNames });
|
||||
|
||||
// Load schemas and all groups in parallel
|
||||
const [schemas, groupModels] = await Promise.all([
|
||||
this.loadSchemas(),
|
||||
this.loadGroupsWithModels(groupNames)
|
||||
]);
|
||||
|
||||
// Organize schemas by group
|
||||
const groupSchemas = this.organizeSchemasByGroup(schemas, groupModels);
|
||||
|
||||
return { schemas, groupSchemas, groupModels };
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user