forked from enviPath/enviPy
[Feature] Adds timeseries display (#313)
Adds a way to input/display timeseries data to the additional information Reviewed-on: enviPath/enviPy#313 Reviewed-by: jebus <lorsbach@envipath.com> Co-authored-by: Tobias O <tobias.olenyi@envipath.com> Co-committed-by: Tobias O <tobias.olenyi@envipath.com>
This commit is contained in:
@ -32,14 +32,14 @@ window.AdditionalInformationApi = {
|
||||
sanitizePayload(value) {
|
||||
if (Array.isArray(value)) {
|
||||
return value
|
||||
.map(item => this.sanitizePayload(item))
|
||||
.filter(item => item !== '');
|
||||
.map((item) => this.sanitizePayload(item))
|
||||
.filter((item) => item !== "");
|
||||
}
|
||||
|
||||
if (value && typeof value === 'object') {
|
||||
if (value && typeof value === "object") {
|
||||
const cleaned = {};
|
||||
for (const [key, item] of Object.entries(value)) {
|
||||
if (item === '') continue;
|
||||
if (item === "") continue;
|
||||
cleaned[key] = this.sanitizePayload(item);
|
||||
}
|
||||
return cleaned;
|
||||
@ -53,7 +53,7 @@ window.AdditionalInformationApi = {
|
||||
* @returns {string} CSRF token
|
||||
*/
|
||||
getCsrfToken() {
|
||||
return document.querySelector('[name=csrf-token]')?.content || '';
|
||||
return document.querySelector("[name=csrf-token]")?.content || "";
|
||||
},
|
||||
|
||||
/**
|
||||
@ -62,10 +62,10 @@ window.AdditionalInformationApi = {
|
||||
*/
|
||||
_buildHeaders(includeContentType = true) {
|
||||
const headers = {
|
||||
'X-CSRFToken': this.getCsrfToken()
|
||||
"X-CSRFToken": this.getCsrfToken(),
|
||||
};
|
||||
if (includeContentType) {
|
||||
headers['Content-Type'] = 'application/json';
|
||||
headers["Content-Type"] = "application/json";
|
||||
}
|
||||
return headers;
|
||||
},
|
||||
@ -85,26 +85,34 @@ window.AdditionalInformationApi = {
|
||||
|
||||
// Try to parse the error if it's a JSON string
|
||||
let parsedError = errorData;
|
||||
if (typeof errorData.error === 'string' && errorData.error.startsWith('{')) {
|
||||
const errorStr = errorData.detail || errorData.error;
|
||||
if (typeof errorStr === "string" && errorStr.startsWith("{")) {
|
||||
try {
|
||||
parsedError = JSON.parse(errorData.error);
|
||||
parsedError = JSON.parse(errorStr);
|
||||
} 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) {
|
||||
if (parsedError.type === "validation_error" && parsedError.field_errors) {
|
||||
this._log(`${action} VALIDATION ERROR`, parsedError);
|
||||
const error = new Error(parsedError.message || 'Validation failed');
|
||||
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 });
|
||||
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);
|
||||
}
|
||||
|
||||
@ -118,9 +126,9 @@ window.AdditionalInformationApi = {
|
||||
* @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');
|
||||
this._log("loadSchemas", "Starting...");
|
||||
const response = await fetch("/api/v1/information/schema/");
|
||||
return this._handleResponse(response, "loadSchemas");
|
||||
},
|
||||
|
||||
/**
|
||||
@ -129,9 +137,11 @@ window.AdditionalInformationApi = {
|
||||
* @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');
|
||||
this._log("loadItems", { scenarioUuid });
|
||||
const response = await fetch(
|
||||
`/api/v1/scenario/${scenarioUuid}/information/`,
|
||||
);
|
||||
return this._handleResponse(response, "loadItems");
|
||||
},
|
||||
|
||||
/**
|
||||
@ -140,11 +150,11 @@ window.AdditionalInformationApi = {
|
||||
* @returns {Promise<{schemas: Object, items: Array}>}
|
||||
*/
|
||||
async loadSchemasAndItems(scenarioUuid) {
|
||||
this._log('loadSchemasAndItems', { scenarioUuid });
|
||||
this._log("loadSchemasAndItems", { scenarioUuid });
|
||||
|
||||
const [schemas, items] = await Promise.all([
|
||||
this.loadSchemas(),
|
||||
this.loadItems(scenarioUuid)
|
||||
this.loadItems(scenarioUuid),
|
||||
]);
|
||||
|
||||
return { schemas, items };
|
||||
@ -159,7 +169,7 @@ window.AdditionalInformationApi = {
|
||||
*/
|
||||
async createItem(scenarioUuid, modelName, data) {
|
||||
const sanitizedData = this.sanitizePayload(data);
|
||||
this._log('createItem', { scenarioUuid, modelName, data: sanitizedData });
|
||||
this._log("createItem", { scenarioUuid, modelName, data: sanitizedData });
|
||||
|
||||
// Normalize model name to lowercase
|
||||
const normalizedName = modelName.toLowerCase();
|
||||
@ -167,13 +177,13 @@ window.AdditionalInformationApi = {
|
||||
const response = await fetch(
|
||||
`/api/v1/scenario/${scenarioUuid}/information/${normalizedName}/`,
|
||||
{
|
||||
method: 'POST',
|
||||
method: "POST",
|
||||
headers: this._buildHeaders(),
|
||||
body: JSON.stringify(sanitizedData)
|
||||
}
|
||||
body: JSON.stringify(sanitizedData),
|
||||
},
|
||||
);
|
||||
|
||||
return this._handleResponse(response, 'createItem');
|
||||
return this._handleResponse(response, "createItem");
|
||||
},
|
||||
|
||||
/**
|
||||
@ -183,17 +193,17 @@ window.AdditionalInformationApi = {
|
||||
* @returns {Promise<{status: string}>}
|
||||
*/
|
||||
async deleteItem(scenarioUuid, itemUuid) {
|
||||
this._log('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)
|
||||
}
|
||||
method: "DELETE",
|
||||
headers: this._buildHeaders(false),
|
||||
},
|
||||
);
|
||||
|
||||
return this._handleResponse(response, 'deleteItem');
|
||||
return this._handleResponse(response, "deleteItem");
|
||||
},
|
||||
|
||||
/**
|
||||
@ -205,7 +215,10 @@ window.AdditionalInformationApi = {
|
||||
*/
|
||||
async updateItem(scenarioUuid, item) {
|
||||
const sanitizedData = this.sanitizePayload(item.data);
|
||||
this._log('updateItem', { scenarioUuid, item: { ...item, data: sanitizedData } });
|
||||
this._log("updateItem", {
|
||||
scenarioUuid,
|
||||
item: { ...item, data: sanitizedData },
|
||||
});
|
||||
|
||||
const { uuid, type } = item;
|
||||
|
||||
@ -213,20 +226,23 @@ window.AdditionalInformationApi = {
|
||||
const response = await fetch(
|
||||
`/api/v1/scenario/${scenarioUuid}/information/item/${uuid}/`,
|
||||
{
|
||||
method: 'PATCH',
|
||||
method: "PATCH",
|
||||
headers: this._buildHeaders(),
|
||||
body: JSON.stringify(sanitizedData)
|
||||
}
|
||||
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');
|
||||
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');
|
||||
return this._handleResponse(response, "updateItem");
|
||||
},
|
||||
|
||||
/**
|
||||
@ -236,38 +252,50 @@ window.AdditionalInformationApi = {
|
||||
* @returns {Promise<Array>} Array of results with success status
|
||||
*/
|
||||
async updateItems(scenarioUuid, items) {
|
||||
this._log('updateItems', { scenarioUuid, itemCount: items.length });
|
||||
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 });
|
||||
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
|
||||
isValidationError: error.isValidationError,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const failed = results.filter(r => !r.success);
|
||||
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;
|
||||
// If all failures are validation errors, return all validation errors for display
|
||||
const validationErrors = failed.filter((f) => f.isValidationError);
|
||||
if (validationErrors.length === failed.length) {
|
||||
// All failures are validation errors - return all field errors by item UUID
|
||||
const allFieldErrors = {};
|
||||
validationErrors.forEach((ve) => {
|
||||
allFieldErrors[ve.oldUuid] = ve.fieldErrors || {};
|
||||
});
|
||||
const error = new Error(
|
||||
`${failed.length} item(s) have validation errors. Please correct them.`,
|
||||
);
|
||||
error.fieldErrors = allFieldErrors; // Map of UUID -> field errors
|
||||
error.isValidationError = true;
|
||||
error.itemUuid = failed[0].oldUuid;
|
||||
error.isMultipleErrors = true; // Flag indicating multiple items have errors
|
||||
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.`);
|
||||
throw new Error(
|
||||
`Failed to update ${failed.length} item(s). Please check the form for errors.`,
|
||||
);
|
||||
}
|
||||
|
||||
return results;
|
||||
@ -285,16 +313,13 @@ window.AdditionalInformationApi = {
|
||||
* @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');
|
||||
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");
|
||||
},
|
||||
|
||||
/**
|
||||
@ -302,9 +327,9 @@ window.AdditionalInformationApi = {
|
||||
* @returns {Promise<{groups: string[]}>}
|
||||
*/
|
||||
async loadGroups() {
|
||||
this._log('loadGroups', 'Starting...');
|
||||
const response = await fetch('/api/v1/information/groups/');
|
||||
return this._handleResponse(response, 'loadGroups');
|
||||
this._log("loadGroups", "Starting...");
|
||||
const response = await fetch("/api/v1/information/groups/");
|
||||
return this._handleResponse(response, "loadGroups");
|
||||
},
|
||||
|
||||
/**
|
||||
@ -313,7 +338,7 @@ window.AdditionalInformationApi = {
|
||||
* @returns {Promise<Object>} Object with subcategories as keys and arrays of model info
|
||||
*/
|
||||
async loadGroupModels(groupName) {
|
||||
this._log('loadGroupModels', { groupName });
|
||||
this._log("loadGroupModels", { groupName });
|
||||
const response = await fetch(`/api/v1/information/groups/${groupName}/`);
|
||||
return this._handleResponse(response, `loadGroupModels-${groupName}`);
|
||||
},
|
||||
@ -323,8 +348,8 @@ window.AdditionalInformationApi = {
|
||||
* @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 });
|
||||
async loadGroupsWithModels(groupNames = ["soil", "sludge", "sediment"]) {
|
||||
this._log("loadGroupsWithModels", { groupNames });
|
||||
|
||||
const results = {};
|
||||
const promises = groupNames.map(async (groupName) => {
|
||||
@ -347,9 +372,9 @@ window.AdditionalInformationApi = {
|
||||
* @returns {Object} Object with group names as keys and filtered schemas as values
|
||||
*/
|
||||
organizeSchemasByGroup(schemas, groupModelsData) {
|
||||
this._log('organizeSchemasByGroup', {
|
||||
this._log("organizeSchemasByGroup", {
|
||||
schemaCount: Object.keys(schemas).length,
|
||||
groupCount: Object.keys(groupModelsData).length
|
||||
groupCount: Object.keys(groupModelsData).length,
|
||||
});
|
||||
|
||||
const organized = {};
|
||||
@ -377,18 +402,18 @@ window.AdditionalInformationApi = {
|
||||
* @param {Array<string>} groupNames - Defaults to ['soil', 'sludge', 'sediment']
|
||||
* @returns {Promise<{schemas, groupSchemas, groupModels}>}
|
||||
*/
|
||||
async loadSchemasWithGroups(groupNames = ['soil', 'sludge', 'sediment']) {
|
||||
this._log('loadSchemasWithGroups', { groupNames });
|
||||
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)
|
||||
this.loadGroupsWithModels(groupNames),
|
||||
]);
|
||||
|
||||
// Organize schemas by group
|
||||
const groupSchemas = this.organizeSchemasByGroup(schemas, groupModels);
|
||||
|
||||
return { schemas, groupSchemas, groupModels };
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user