definma-ui/src/app/sample/sample.component.ts

530 lines
21 KiB
TypeScript
Raw Normal View History

2020-07-30 14:23:51 +02:00
import cloneDeep from 'lodash/cloneDeep';
import merge from 'lodash/merge';
import omit from 'lodash/omit';
import strCompare from 'str-compare';
import {
AfterContentChecked,
Component,
OnInit, TemplateRef,
ViewChild
} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {AutocompleteService} from '../services/autocomplete.service';
import {ApiService} from '../services/api.service';
import {MaterialModel} from '../models/material.model';
import {SampleModel} from '../models/sample.model';
import {NgForm, Validators} from '@angular/forms';
import {ValidationService} from '../services/validation.service';
import {MeasurementModel} from '../models/measurement.model';
import { ChartOptions } from 'chart.js';
import {animate, style, transition, trigger} from '@angular/animations';
2020-07-22 10:45:34 +02:00
import {Observable} from 'rxjs';
import {ModalService} from '@inst-iot/bosch-angular-ui-components';
import {DataService} from '../services/data.service';
// TODO: clean up this mess !!!
2020-06-26 11:09:59 +02:00
// TODO: only show condition (if not set) and measurements in edit sample dialog at first
// TODO: multiple samples for base data, extend multiple measurements, conditions
@Component({
selector: 'app-sample',
templateUrl: './sample.component.html',
styleUrls: ['./sample.component.scss'],
animations: [
trigger(
'inOut', [
transition(':enter', [
style({height: 0, opacity: 0}),
animate('0.5s ease-out', style({height: '*', opacity: 1}))
]),
transition(':leave', [
style({height: '*', opacity: 1}),
animate('0.5s ease-in', style({height: 0, opacity: 0}))
])
]
)
]
})
export class SampleComponent implements OnInit, AfterContentChecked {
@ViewChild('sampleForm') sampleForm: NgForm;
@ViewChild('cmForm') cmForm: NgForm;
sample = new SampleModel(); // base sample which is saved
sampleCount = 1; // number of samples to be generated
generatedSamples: SampleModel[] = []; // gets filled with response data after saving the sample
2020-07-22 10:45:34 +02:00
sampleReferences: [string, string, string][] = [['', '', '']];
sampleReferenceFinds: {_id: string, number: string}[] = []; // raw sample reference data from db
currentSRIndex = 0; // index of last entered sample reference
2020-07-22 10:45:34 +02:00
sampleReferenceAutocomplete: string[][] = [[]];
customFields: [string, string][] = [];
availableCustomFields: string[] = [];
newMaterial = false; // true if new material should be created
materials: MaterialModel[] = []; // all materials
materialNames = []; // only names for autocomplete
material = new MaterialModel(); // object of current selected material
defaultDevice = ''; // default device for spectra
new; // true if new sample should be created
editSampleBase = false; // set true to edit sample base values even when generatedSamples .length > 0
loading = 0; // number of currently loading instances
checkFormAfterInit = false;
modalText = {list: '', suggestion: ''};
charts = [[]]; // chart data for spectra
readonly chartInit = [{
data: [],
label: 'Spectrum',
showLine: true,
fill: false,
pointRadius: 0,
borderColor: '#00a8b0',
borderWidth: 2
}];
readonly chartOptions: ChartOptions = {
scales: {
xAxes: [{ticks: {min: 400, max: 4000, stepSize: 400, reverse: true}}],
yAxes: [{ticks: {min: 0, max: 1}}]
},
responsive: true,
tooltips: {enabled: false},
hover: {mode: null},
maintainAspectRatio: true,
plugins: {datalabels: {display: false}}
};
constructor(
private router: Router,
private route: ActivatedRoute,
private api: ApiService,
private validation: ValidationService,
public autocomplete: AutocompleteService,
private modal: ModalService,
public d: DataService
) { }
ngOnInit(): void {
this.new = this.router.url === '/samples/new';
2020-07-22 10:45:34 +02:00
this.loading = 7;
this.d.load('materials', () => {
this.materialNames = this.d.arr.materials.map(e => e.name);
this.loading--;
});
this.d.load('materialSuppliers', () => {
this.loading--;
});
this.d.load('materialGroups', () => {
this.loading--;
});
this.d.load('conditionTemplates', () => {
this.loading--;
});
this.d.load('measurementTemplates', () => {
2020-07-22 10:45:34 +02:00
this.loading--;
});
this.d.load('materialTemplates', () => {
if (!this.material.properties.material_template) {
this.material.properties.material_template = this.d.arr.materialTemplates.filter(e => e.name === 'plastic').reverse()[0]._id;
2020-07-22 10:45:34 +02:00
}
this.loading--;
});
this.d.load('sampleNotesFields', () => {
this.availableCustomFields = this.d.arr.sampleNotesFields.map(e => e.name);
this.loading--;
});
this.d.load('user', () => {
this.defaultDevice = this.d.d.user.device_name;
});
if (!this.new) {
this.loading++;
this.api.get<SampleModel>('/sample/' + this.route.snapshot.paramMap.get('id'), sData => {
this.sample.deserialize(sData);
this.generatedSamples[0] = this.sample;
this.charts = [[]];
let spectrumCounter = 0; // generate charts for spectrum measurements
this.generatedSamples[0].measurements.forEach((measurement, i) => {
this.charts[0].push(cloneDeep(this.chartInit));
if (measurement.values.dpt) {
setTimeout(() => {
this.generateChart(measurement.values.dpt, 0, i);
}, spectrumCounter * 20); // generate charts one after another to avoid freezing the UI
spectrumCounter ++;
}
});
this.material = new MaterialModel().deserialize(sData.material); // read material
this.customFields = this.sample.notes.custom_fields && this.sample.notes.custom_fields !== {} ? // read custom fields
Object.keys(this.sample.notes.custom_fields).map(e => [e, this.sample.notes.custom_fields[e]]) : [];
if (this.sample.notes.sample_references.length) { // read sample references
this.sampleReferences = [];
this.sampleReferenceAutocomplete = [];
let loadCounter = this.sample.notes.sample_references.length; // count down instances still loading
this.sample.notes.sample_references.forEach(reference => {
this.api.get<SampleModel>('/sample/' + reference.sample_id, srData => { // get sample numbers for ids
this.sampleReferences.push([srData.number, reference.relation, reference.sample_id]);
this.sampleReferenceAutocomplete.push([srData.number]);
if (!--loadCounter) { // insert empty template when all instances were loaded
this.sampleReferences.push(['', '', '']);
this.sampleReferenceAutocomplete.push([]);
}
});
});
}
this.loading--;
this.checkFormAfterInit = true;
});
}
}
ngAfterContentChecked() {
if (this.generatedSamples.length) { // conditions are displayed
this.generatedSamples.forEach((gSample, gIndex) => {
if (this.d.id.conditionTemplates[gSample.condition.condition_template]) {
this.d.id.conditionTemplates[gSample.condition.condition_template].parameters.forEach((parameter, pIndex) => {
this.attachValidator(this.cmForm, `conditionParameter-${gIndex}-${pIndex}`, parameter.range, true);
});
}
gSample.measurements.forEach((measurement, mIndex) => {
this.d.id.measurementTemplates[measurement.measurement_template].parameters.forEach((parameter, pIndex) => {
this.attachValidator(this.cmForm, `measurementParameter-${gIndex}-${mIndex}-${pIndex}`, parameter.range, false);
});
});
});
}
if (this.sampleForm && this.material.properties.material_template) { // material template is set
this.d.id.materialTemplates[this.material.properties.material_template].parameters.forEach((parameter, i) => {
this.attachValidator(this.sampleForm, 'materialParameter' + i, parameter.range, true);
});
2020-07-22 10:45:34 +02:00
}
if (this.checkFormAfterInit) {
if (this.editSampleBase) { // validate sampleForm
if (this.sampleForm !== undefined && this.sampleForm.form.get('cf-key0')) {
this.checkFormAfterInit = false;
Object.keys(this.sampleForm.form.controls).forEach(field => {
this.sampleForm.form.get(field).updateValueAndValidity();
});
}
}
else { // validate cmForm
// check that all fields are ready for validation
let formReady: boolean = this.cmForm !== undefined; // forms exist
if (this.generatedSamples[0].condition.condition_template) { // if condition is set, last condition field exists
formReady = formReady && this.cmForm.form.get('conditionParameter-0-' +
(this.d.id.conditionTemplates[this.generatedSamples[0].condition.condition_template].parameters.length - 1)) as any;
}
if (this.generatedSamples[0].measurements.length) { // if there are measurements, last measurement field exists
formReady = formReady && this.cmForm.form.get('measurementParameter-0-' + (this.generatedSamples[0].measurements.length - 1) +
'-' + (this.d.id.measurementTemplates[this.generatedSamples[0].measurements[this.generatedSamples[0].measurements.length - 1]
.measurement_template].parameters.length - 1)) as any;
}
if (formReady) { // fields are ready, do validation
this.checkFormAfterInit = false;
Object.keys(this.cmForm.form.controls).forEach(field => {
this.cmForm.form.get(field).updateValueAndValidity();
});
}
}
}
}
// attach validators specified in range to input with name
attachValidator(form, name: string, range: {[prop: string]: any}, required: boolean) {
if (form && form.form.get(name)) {
const validators = [];
if (required) {
validators.push(Validators.required);
}
if (range.hasOwnProperty('values')) {
validators.push(this.validation.generate('stringOf', [range.values]));
}
else if (range.hasOwnProperty('min') && range.hasOwnProperty('max')) {
validators.push(this.validation.generate('minMax', [range.min, range.max]));
}
else if (range.hasOwnProperty('min')) {
validators.push(this.validation.generate('min', [range.min]));
}
else if (range.hasOwnProperty('max')) {
validators.push(this.validation.generate('max', [range.max]));
}
form.form.get(name).setValidators(validators);
}
}
// save base sample
saveSample() {
if (this.new) {
this.loading = this.sampleCount; // set up loading spinner
}
new Promise<void>(resolve => {
if (this.newMaterial) { // save material first if new one exists
this.api.post<MaterialModel>('/material/new', this.material.sendFormat(), data => {
this.d.arr.materials.push(data); // add material to data
this.material = data;
this.sample.material_id = data._id; // add new material id to sample data
resolve();
});
}
else {
resolve();
}
}).then(() => { // save sample
this.sample.notes.custom_fields = {};
this.customFields.forEach(element => {
if (element[0] !== '') {
this.sample.notes.custom_fields[element[0]] = element[1];
}
});
this.sample.notes.sample_references = this.sampleReferences
.filter(e => e[0] && e[1] && e[2])
.map(e => ({sample_id: e[2], relation: e[1]}));
if (this.new) {
for (let i = 0; i < this.sampleCount; i ++) {
this.api.post<SampleModel>('/sample/new', this.sample.sendFormat(), data => {
this.generatedSamples[i] = new SampleModel().deserialize(data);
this.generatedSamples[i].material = this.d.arr.materials.find(e => e._id === this.generatedSamples[i].material_id);
this.loading --;
});
}
}
else {
this.api.put<SampleModel>('/sample/' + this.sample._id, this.sample.sendFormat(), data => {
merge(this.generatedSamples[0], omit(data, ['condition']));
this.generatedSamples[0].material = this.d.arr.materials.find(e => e._id === this.generatedSamples[0].material_id);
this.editSampleBase = false;
});
}
});
}
// save conditions and measurements
cmSave() { // save measurements and conditions
this.generatedSamples.forEach(sample => {
if (sample.condition.condition_template) { // condition was set
this.api.put('/sample/' + sample._id, {condition: sample.condition});
}
sample.measurements.forEach(measurement => { // save measurements
if (Object.keys(measurement.values).map(e => measurement.values[e]).join('') !== '') {
Object.keys(measurement.values).forEach(key => { // map empty values to null
measurement.values[key] = measurement.values[key] === '' ? null : measurement.values[key];
});
if (measurement._id === null) { // new measurement
measurement.sample_id = sample._id;
this.api.post<MeasurementModel>('/measurement/new', measurement.sendFormat());
}
else { // update measurement
this.api.put<MeasurementModel>('/measurement/' + measurement._id,
measurement.sendFormat(['sample_id', 'measurement_template']));
}
}
else if (measurement._id !== null) { // existing measurement was left empty to delete
this.api.delete('/measurement/' + measurement._id);
}
});
});
this.router.navigate(['/samples']);
}
// set material based on found material name
findMaterial(name) {
const res = this.d.arr.materials.find(e => e.name === name); // search for match
if (res) { // material found
2020-07-30 14:23:51 +02:00
this.material = cloneDeep(res);
this.sample.material_id = this.material._id;
}
else { // no matching material found
2020-07-22 10:45:34 +02:00
if (this.sample.material_id !== null) { // reset previous match
this.material = new MaterialModel();
this.material.properties.material_template = this.d.arr.materialTemplates.filter(e => e.name === 'plastic').reverse()[0]._id;
2020-07-22 10:45:34 +02:00
}
this.sample.material_id = null;
}
this.setNewMaterial();
}
// set newMaterial, if value === null -> toggle
setNewMaterial(value = null) {
if (value === null) { // toggle dialog
this.newMaterial = !this.sample.material_id;
}
2020-07-22 10:45:34 +02:00
else if (value || (!value && this.sample.material_id !== null )) { // set to false only if material already exists
this.newMaterial = value;
}
if (this.newMaterial) { // set validators if dialog is open
this.sampleForm.form.get('materialname').setValidators([Validators.required]);
}
else { // material name must be from list if dialog is closed
this.sampleForm.form.get('materialname')
.setValidators([Validators.required, this.validation.generate('stringOf', [this.materialNames])]);
}
this.sampleForm.form.get('materialname').updateValueAndValidity();
}
// add a new measurement for generated sample at index
addMeasurement(gIndex) {
this.generatedSamples[gIndex].measurements.push(
new MeasurementModel(this.d.arr.measurementTemplates.filter(e => e.name === 'spectrum').reverse()[0]._id)
);
this.generatedSamples[gIndex].measurements[this.generatedSamples[gIndex].measurements.length - 1].values.device = this.defaultDevice;
if (!this.charts[gIndex]) { // add array if there are no charts yet
this.charts[gIndex] = [];
}
this.charts[gIndex].push(cloneDeep(this.chartInit));
}
// remove the measurement at the specified index
removeMeasurement(gIndex, mIndex) {
if (this.generatedSamples[gIndex].measurements[mIndex]._id !== null) {
this.api.delete('/measurement/' + this.generatedSamples[gIndex].measurements[mIndex]._id);
2020-07-22 10:45:34 +02:00
}
this.generatedSamples[gIndex].measurements.splice(mIndex, 1);
this.charts[gIndex].splice(mIndex, 1);
2020-07-22 10:45:34 +02:00
}
// remove measurement data at the specified index
clearMeasurement(gIndex, mIndex) {
this.charts[gIndex][mIndex][0].data = [];
this.generatedSamples[gIndex].measurements[mIndex].values = {};
}
fileToArray(files, gIndex, mIndex, parameter) {
console.log(files);
for (const i in files) {
if (files.hasOwnProperty(i)) {
const fileReader = new FileReader();
fileReader.onload = () => {
let index: number = mIndex;
if (Number(i) > 0) { // append further spectra
this.addMeasurement(gIndex);
index = this.generatedSamples[gIndex].measurements.length - 1;
}
this.generatedSamples[gIndex].measurements[index].values.filename = files[i].name;
this.generatedSamples[gIndex].measurements[index].values[parameter] =
fileReader.result.toString().split('\r\n').map(e => e.split(','));
this.generateChart(this.generatedSamples[gIndex].measurements[index].values[parameter], gIndex, index);
};
fileReader.readAsText(files[i]);
}
}
}
generateChart(spectrum, gIndex, mIndex) {
this.charts[gIndex][mIndex][0].data = spectrum.map(e => ({x: parseFloat(e[0]), y: parseFloat(e[1])}));
}
toggleCondition(sample) {
if (sample.condition.condition_template) {
sample.condition.condition_template = null;
}
else {
sample.condition.condition_template = this.d.arr.conditionTemplates[0]._id;
}
}
checkTypo(list, mKey, modal: TemplateRef<any>) {
if (this.d.arr[list].indexOf(this.material[list]) < 0) { // entry is not in list
this.modalText.list = mKey;
this.modalText.suggestion = this.d.arr[list] // find possible entry from list
.map(e => ({v: e, s: strCompare.sorensenDice(e, this.material[mKey])}))
.sort((a, b) => b.s - a.s)[0].v;
this.modal.open(modal).then(result => {
if (result) { // use suggestion
this.material[mKey] = this.modalText.suggestion;
}
});
}
}
deleteConfirm(modal) {
this.modal.open(modal).then(result => {
if (result) {
this.api.delete('/sample/' + this.sample._id);
this.router.navigate(['/samples']);
}
});
}
2020-07-22 10:45:34 +02:00
checkSampleReference(value, index) {
if (value) {
this.sampleReferences[index][0] = value;
}
this.currentSRIndex = index;
const fieldNo = this.sampleReferences.length;
let filledFields = 0;
this.sampleReferences.forEach(field => {
if (field[0] !== '') {
filledFields ++;
}
});
// append new field
if (filledFields === fieldNo) {
this.sampleReferences.push(['', '', '']);
this.sampleReferenceAutocomplete.push([]);
}
// remove if two end fields are empty
if (fieldNo > 1 && this.sampleReferences[fieldNo - 1][0] === '' && this.sampleReferences[fieldNo - 2][0] === '') {
this.sampleReferences.pop();
this.sampleReferenceAutocomplete.pop();
}
this.sampleReferenceIdFind(value);
}
sampleReferenceList(value) {
return new Observable(observer => {
if (value !== '') {
this.api.get<{ _id: string, number: string }[]>(
'/samples?status=all&page-size=25&sort=number-asc&fields[]=number&fields[]=_id&' +
'filters[]=%7B%22mode%22%3A%22stringin%22%2C%22field%22%3A%22number%22%2C%22values%22%3A%5B%22' + value + '%22%5D%7D', data => {
console.log(data);
this.sampleReferenceAutocomplete[this.currentSRIndex] = data.map(e => e.number);
this.sampleReferenceFinds = data;
observer.next(data.map(e => e.number));
observer.complete();
this.sampleReferenceIdFind(value);
});
}
else {
observer.next([]);
2020-07-22 10:45:34 +02:00
observer.complete();
}
2020-07-22 10:45:34 +02:00
});
}
sampleReferenceIdFind(value) {
const idFind = this.sampleReferenceFinds.find(e => e.number === value);
if (idFind) {
this.sampleReferences[this.currentSRIndex][2] = idFind._id;
}
else {
this.sampleReferences[this.currentSRIndex][2] = '';
}
}
sampleReferenceListBind() {
return this.sampleReferenceList.bind(this);
}
uniqueCfValues(index) { // returns all names until index for unique check
return this.customFields ? this.customFields.slice(0, index).map(e => e[0]) : [];
}
preventDefault(event) {
if (event.key && event.key === 'Enter' || event.type === 'dragover') {
event.preventDefault();
}
}
}
// 1. ngAfterViewInit wird ja jedes mal nach einem ngOnChanges aufgerufen, also zB wenn sich dein ngFor aufbaut. Du könntest also in der
// Methode prüfen, ob die Daten schon da sind und dann dementsprechend handeln. Das wäre die Eleganteste Variante
// 2. Der state "dirty" soll eigentlich anzeigen, wenn ein Form-Field vom User geändert wurde; damit missbrauchst du es hier etwas
// 3. Die Dirty-Variante: Pack in deine ngFor ein {{ onFirstLoad(data) }} rein, das einfach ausgeführt wird. müsstest dann natürlich
// abfangen, dass das nicht nach jedem view-cycle neu getriggert wird. Schön ist das nicht, aber besser als mit Timeouts^^