bug button, data service, user level adjustments, multiple sample support for edit dialog, validation functionality

This commit is contained in:
VLE2FE
2020-08-06 08:18:57 +02:00
parent 72ecdad573
commit e8ad6aaa7a
25 changed files with 841 additions and 402 deletions

View File

@ -2,32 +2,33 @@
<rb-loading-spinner *ngIf="loading"></rb-loading-spinner>
<form #sampleForm="ngForm" *ngIf="!responseData && !loading">
<!--<form #sampleForm="ngForm">-->
<form #sampleForm="ngForm" *ngIf="(!generatedSamples.length || editSampleBase) && !loading">
<div class="sample">
<div>
<rb-form-input name="materialname" label="material name" [rbDebounceTime]="0" [rbInitialOpen]="true"
[rbFormInputAutocomplete]="autocomplete.bind(this, ac.materialNames)" appValidate="stringOf"
[rbFormInputAutocomplete]="autocomplete.bind(this, materialNames)" appValidate="stringOf"
(keydown)="preventDefault($event)" (ngModelChange)="findMaterial($event)" ngModel
[appValidateArgs]="[ac.materialName]" required [(ngModel)]="material.name" [autofocus]="true">
[appValidateArgs]="[materialNames]" required [(ngModel)]="material.name" [autofocus]="true">
<ng-template rbFormValidationMessage="required">Cannot be empty</ng-template>
<ng-template rbFormValidationMessage="failure">Unknown material, add properties for new material</ng-template>
</rb-form-input>
<rb-icon-button icon="add" mode="secondary" (click)="setNewMaterial(!newMaterial)">New material</rb-icon-button>
<rb-icon-button class="set-new-material space-below" icon="add" mode="secondary"
(click)="setNewMaterial(!newMaterial)">New material</rb-icon-button>
</div>
<div class="material shaded-container" *ngIf="newMaterial" [@inOut]>
<h4>Material properties</h4>
<rb-form-input name="supplier" label="supplier" [rbFormInputAutocomplete]="autocomplete.bind(this, ac.supplier)"
<rb-form-input name="supplier" label="supplier"
[rbFormInputAutocomplete]="autocomplete.bind(this, d.arr.materialSupplier)"
[rbDebounceTime]="0" [rbInitialOpen]="true" appValidate="string" required
[(ngModel)]="material.supplier" #supplierInput="ngModel"
(focusout)="checkTypo('supplier', modalWarning)">
(focusout)="checkTypo('materialSuppliers', 'supplier', modalWarning)">
<ng-template rbFormValidationMessage="failure">{{supplierInput.errors.failure}}</ng-template>
</rb-form-input>
<rb-form-input name="group" label="group" [rbFormInputAutocomplete]="autocomplete.bind(this, ac.mgroup)"
<rb-form-input name="group" label="group" [rbFormInputAutocomplete]="autocomplete.bind(this, d.arr.materialGroup)"
[rbDebounceTime]="0" [rbInitialOpen]="true" appValidate="string" required
[(ngModel)]="material.group" #groupInput="ngModel"
(focusout)="checkTypo('mgroup', modalWarning)">
(focusout)="checkTypo('materialGroups', 'group', modalWarning)">
<ng-template rbFormValidationMessage="failure">{{groupInput.errors.failure}}</ng-template>
</rb-form-input>
<ng-template #modalWarning>
@ -41,11 +42,12 @@
label="material number" appValidate="string" [name]="'materialNumber-' + item.i"
[ngModel]="item.value"></rb-form-input>
</rb-array-input>
<rb-form-select name="conditionSelect" label="Condition" (ngModelChange)="selectMaterialTemplate($event)"
[ngModel]="material.properties.material_template">
<option *ngFor="let m of materialTemplates" [value]="m._id">{{m.name}}</option>
<rb-form-select name="conditionSelect" label="Condition"
[(ngModel)]="material.properties.material_template">
<option *ngFor="let m of d.arr.materialTemplates" [value]="m._id">{{m.name}}</option>
</rb-form-select>
<rb-form-input *ngFor="let parameter of materialTemplate.parameters; index as i" [name]="'materialParameter' + i"
<rb-form-input *ngFor="let parameter of d.id.materialTemplates[material.properties.material_template].parameters;
index as i" [name]="'materialParameter' + i"
[label]="parameter.name" appValidate="string" required
[(ngModel)]="material.properties[parameter.name]" #parameterInput="ngModel">
<ng-template rbFormValidationMessage="failure">{{parameterInput.errors.failure}}</ng-template>
@ -53,15 +55,14 @@
</rb-form-input>
</div>
&nbsp;
<div>
<rb-form-input name="type" label="type" appValidate="string" required [(ngModel)]="sample.type"
#typeInput="ngModel">
<ng-template rbFormValidationMessage="failure">{{typeInput.errors.failure}}</ng-template>
<rb-form-select name="type" label="type" required [(ngModel)]="sample.type" ngModel>
<option value="granulate">granulate</option>
<option value="part">part</option>
<option value="tension rod">tension rod</option>
<ng-template rbFormValidationMessage="required">Cannot be empty</ng-template>
</rb-form-input>
<rb-form-input name="color" label="color" appValidate="string" required [(ngModel)]="sample.color"
</rb-form-select>
<rb-form-input name="color" label="color" appValidate="string" [(ngModel)]="sample.color"
#colorInput="ngModel">
<ng-template rbFormValidationMessage="failure">{{colorInput.errors.failure}}</ng-template>
<ng-template rbFormValidationMessage="required">Cannot be empty</ng-template>
@ -112,99 +113,125 @@
</rb-array-input>
</div>
&nbsp;
<div class="conditions shaded-container">
<h4>
Condition
<button class="rb-btn rb-secondary condition-set" type="button" (click)="toggleCondition()"
[disabled]="!conditionTemplates">{{condition ? 'Do not set condition' : 'Set condition'}}</button>
</h4>
<div *ngIf="condition" [@inOut]>
<rb-form-select name="conditionSelect" label="Condition" (ngModelChange)="selectCondition($event)"
[ngModel]="condition._id">
<option *ngFor="let c of conditionTemplates" [value]="c._id">{{c.name}}</option>
</rb-form-select>
<rb-form-input *ngFor="let parameter of condition.parameters; index as i" [name]="'conditionParameter' + i"
[label]="parameter.name" appValidate="string" required
[(ngModel)]="sample.condition[parameter.name]" #parameterInput="ngModel">
<ng-template rbFormValidationMessage="failure">{{parameterInput.errors.failure}}</ng-template>
<ng-template rbFormValidationMessage="required">Cannot be empty</ng-template>
</rb-form-input>
</div>
</div>
&nbsp;
<div class="measurements shaded-container">
<h4>Measurements</h4>
<div *ngFor="let measurement of sample.measurements; index as mIndex" [@inOut]>
<rb-form-select name="measurementTemplateSelect" label="Template" [(ngModel)]="measurement.measurement_template"
(ngModelChange)="clearChart(mIndex)">
<option *ngFor="let m of measurementTemplates" [value]="m._id">{{m.name}}</option>
</rb-form-select>
<div *ngFor="let parameter of getMeasurementTemplate(measurement.measurement_template).parameters;
index as pIndex">
<rb-form-input *ngIf="!parameter.range.type" [name]="'measurementParameter' + mIndex + '-' + pIndex"
[label]="parameter.name" appValidate="string" [(ngModel)]="measurement.values[parameter.name]"
#parameterInput="ngModel">
<ng-template rbFormValidationMessage="failure">{{parameterInput.errors.failure}}</ng-template>
<ng-template rbFormValidationMessage="required">Cannot be empty</ng-template>
</rb-form-input>
<rb-form-file *ngIf="parameter.range.type" [name]="'measurementParameter' + mIndex + '-' + pIndex"
[label]="parameter.name" maxSize="10000000" multiple
(ngModelChange)="fileToArray($event, mIndex, parameter.name)"
placeholder="Select file or drag and drop" dragDrop required ngModel>
<ng-template rbFormValidationMessage="required">Cannot be empty</ng-template>
</rb-form-file>
<canvas baseChart *ngIf="parameter.range.type && charts[mIndex][0].data.length > 0" class="dpt-chart" [@inOut]
[datasets]="charts[mIndex]"
[labels]="[]"
[options]="chartOptions"
[legend]="false"
chartType="scatter">
</canvas>
</div>
<rb-icon-button icon="delete" mode="danger" (click)="removeMeasurement(mIndex)"
[disabled]="!measurementTemplates">
Delete measurement
</rb-icon-button>
</div>
&nbsp;
<div>
<rb-icon-button icon="add" mode="secondary" (click)="addMeasurement()" [disabled]="!measurementTemplates">
New measurement
</rb-icon-button>
</div>
</div>
<div>
<div *ngIf="editSampleBase; else generateSamples" class="space-below">
<button class="rb-btn rb-primary" type="submit" (click)="saveSample()" [disabled]="!sampleForm.form.valid">
Save sample
</button>
</div>
<ng-template #generateSamples>
<rb-form-input type="number" name="sample-count" label="number of samples" pattern="^\d+?$" required
rbNumberConverter rbMin="1" [(ngModel)]="sampleCount" class="sample-count">
<ng-template rbFormValidationMessage="required">Cannot be empty</ng-template>
<ng-template rbFormValidationMessage="rbMin">Must be at least 1</ng-template>
</rb-form-input>
<button class="rb-btn rb-primary space-below" type="submit" (click)="saveSample()"
[disabled]="!sampleForm.form.valid">
Generate sample{{sampleCount > 1 ? 's' : ''}}
</button>
</ng-template>
</form>
<div *ngIf="responseData">
<h3>Successfully added sample:</h3>
<rb-table id="response-data">
<tr><td>Sample number</td><td>{{responseData.number}}</td></tr>
<tr><td>Type</td><td>{{responseData.type}}</td></tr>
<tr><td>color</td><td>{{responseData.color}}</td></tr>
<tr><td>Batch</td><td>{{responseData.batch}}</td></tr>
<tr><td>Material</td><td>{{material.name}}</td></tr>
</rb-table>
&nbsp;
<div>
<a routerLink="/samples">
<button class="rb-btn rb-primary" type="button">Return to samples</button>
</a>
<div *ngIf="generatedSamples.length && !loading">
<div *ngIf="!editSampleBase">
<h3 *ngIf="new">Successfully added samples:</h3>
<span class="rb-ic rb-ic-edit clickable" (click)="checkFormAfterInit = editSampleBase = true"></span>
<rb-table id="response-data">
<tr><td>Material</td><td>{{generatedSamples[0].material.name}}</td></tr>
<tr><td>Type</td><td>{{generatedSamples[0].type}}</td></tr>
<tr><td>color</td><td>{{generatedSamples[0].color}}</td></tr>
<tr><td>Batch</td><td>{{generatedSamples[0].batch}}</td></tr>
</rb-table>
</div>
<form #cmForm="ngForm">
<div *ngFor="let gSample of generatedSamples; index as gIndex">
<h4 *ngIf="new">{{gSample.number}}</h4>
<div class="conditions shaded-container space-below">
<h5>
Condition
<button class="rb-btn rb-secondary condition-set" type="button" (click)="toggleCondition(gSample)">
{{gSample.condition.condition_template ? 'Do not set condition' : 'Set condition'}}
</button>
</h5>
<div *ngIf="gSample.condition.condition_template" [@inOut]>
<rb-form-select name="conditionSelect" label="Condition"
[(ngModel)]="gSample.condition.condition_template">
<option *ngFor="let c of d.arr.conditionTemplates" [value]="c._id">{{c.name}}</option>
</rb-form-select>
<rb-form-input *ngFor="let parameter of
d.id.conditionTemplates[gSample.condition.condition_template].parameters; index as i"
[name]="'conditionParameter-' + gIndex + '-' + i"
[label]="parameter.name" appValidate="string" required
[(ngModel)]="gSample.condition[parameter.name]" #parameterInput="ngModel">
<ng-template rbFormValidationMessage="failure">{{parameterInput.errors.failure}}</ng-template>
<ng-template rbFormValidationMessage="required">Cannot be empty</ng-template>
</rb-form-input>
</div>
</div>
<div class="measurements shaded-container space-below">
<h5>Measurements</h5>
<div *ngFor="let measurement of gSample.measurements; index as mIndex" [@inOut]>
<rb-form-select [name]="'measurementTemplateSelect-' + gIndex + '-' + mIndex" label="Template"
[(ngModel)]="measurement.measurement_template"
(ngModelChange)="clearMeasurement(gIndex, mIndex)">
<option *ngFor="let m of d.arr.measurementTemplates" [value]="m._id">{{m.name}}</option>
</rb-form-select>
<div *ngFor="let parameter of d.id.measurementTemplates[measurement.measurement_template].parameters;
index as pIndex">
<rb-form-input *ngIf="!parameter.range.type"
[name]="'measurementParameter-' + gIndex + '-' + mIndex + '-' + pIndex"
[label]="parameter.name" appValidate="string"
[(ngModel)]="measurement.values[parameter.name]" #parameterInput="ngModel">
<ng-template rbFormValidationMessage="failure">{{parameterInput.errors.failure}}</ng-template>
<ng-template rbFormValidationMessage="required">Cannot be empty</ng-template>
</rb-form-input>
<rb-form-file *ngIf="parameter.range.type"
[name]="'measurementParameter-' + gIndex + '-' + mIndex + '-' + pIndex"
[label]="parameter.name" maxSize="10000000" multiple
[required]="measurement.values[parameter.name] && !measurement.values[parameter.name].length"
(ngModelChange)="fileToArray($event, gIndex, mIndex, parameter.name)"
placeholder="Select file or drag and drop" dragDrop ngModel>
<ng-template rbFormValidationMessage="required">Cannot be empty</ng-template>
</rb-form-file>
<canvas baseChart *ngIf="parameter.range.type && charts[gIndex][mIndex][0].data.length > 0"
class="dpt-chart"
[@inOut]
[datasets]="charts[gIndex][mIndex]"
[labels]="[]"
[options]="chartOptions"
[legend]="false"
chartType="scatter">
</canvas>
</div>
<rb-icon-button icon="delete" mode="danger" (click)="removeMeasurement(gIndex, mIndex)">
Delete measurement
</rb-icon-button>
</div>
&nbsp;
<div>
<rb-icon-button icon="add" mode="secondary" (click)="addMeasurement(gIndex)">
New measurement
</rb-icon-button>
</div>
</div>
</div>
<rb-icon-button icon="save" mode="primary" type="submit" (click)="cmSave()" [disabled]="!cmForm.form.valid">
Save sample{{generatedSamples.length > 1 ? 's' : ''}}
</rb-icon-button>
<rb-icon-button class="delete-sample" icon="delete" mode="danger" *ngIf="!new"
(click)="deleteConfirm(modalDeleteConfirm)">
Delete sample
</rb-icon-button>
<ng-template #modalDeleteConfirm>
<rb-alert alertTitle="Are you sure" type="danger" okBtnLabel="Delete sample" cancelBtnLabel="Cancel">
Do you really want to delete {{sample.number}}?
</rb-alert>
</ng-template>
</form>
</div>

View File

@ -19,3 +19,17 @@ td:first-child {
.dpt-chart {
max-width: 400px;
}
.sample-count {
max-width: 150px;
margin-right: 20px;
display: inline-block;
}
.set-new-material {
display: block;
}
.delete-sample {
float: right;
}

View File

@ -1,4 +1,6 @@
import cloneDeep from 'lodash/cloneDeep';
import merge from 'lodash/merge';
import omit from 'lodash/omit';
import strCompare from 'str-compare';
import {
AfterContentChecked,
@ -13,14 +15,14 @@ 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 {TemplateModel} from '../models/template.model';
import {MeasurementModel} from '../models/measurement.model';
import { ChartOptions } from 'chart.js';
import {animate, style, transition, trigger} from '@angular/animations';
import {Observable} from 'rxjs';
import {ModalService} from '@inst-iot/bosch-angular-ui-components';
import {UserModel} from '../models/user.model';
import {DataService} from '../services/data.service';
// TODO: clean up this mess !!!
// 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
@ -47,34 +49,33 @@ import {UserModel} from '../models/user.model';
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
new; // true if new sample should be created
newMaterial = false; // true if new material should be created
materials: MaterialModel[] = []; // all materials
ac: {[group: string]: string[]} = { // autocomplete data
supplier: [],
group: [],
materialName: []
};
conditionTemplates: TemplateModel[]; // all conditions
condition: TemplateModel | null = null; // selected condition
materialTemplates: TemplateModel[]; // all material templates
materialTemplate: TemplateModel | null = null; // selected material template
material = new MaterialModel(); // object of current selected material
sample = new SampleModel();
customFields: [string, string][];
sampleReferences: [string, string, string][] = [['', '', '']];
sampleReferenceFinds: {_id: string, number: string}[] = []; // raw sample reference data from db
currentSRIndex = 0; // index of last entered sample reference
availableCustomFields: string[] = [];
sampleReferenceFinds: {_id: string, number: string}[] = []; // raw sample reference data from db
currentSRIndex = 0; // index of last entered sample reference
sampleReferenceAutocomplete: string[][] = [[]];
responseData: SampleModel; // gets filled with response data after saving the sample
measurementTemplates: TemplateModel[];
loading = 0; // number of currently loading instances
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
defaultDevice = '';
charts = [[]]; // chart data for spectra
readonly chartInit = [{
data: [],
label: 'Spectrum',
@ -102,138 +103,138 @@ export class SampleComponent implements OnInit, AfterContentChecked {
private api: ApiService,
private validation: ValidationService,
public autocomplete: AutocompleteService,
private modal: ModalService
private modal: ModalService,
public d: DataService
) { }
ngOnInit(): void {
this.new = this.router.url === '/samples/new';
this.loading = 7;
this.api.get<MaterialModel[]>('/materials?status=all', (data: any) => {
this.materials = data.map(e => new MaterialModel().deserialize(e));
this.ac.materialName = data.map(e => e.name);
this.d.load('materials', () => {
this.materialNames = this.d.arr.materials.map(e => e.name);
this.loading--;
});
this.api.get<string[]>('/material/suppliers', (data: any) => {
this.ac.supplier = data;
this.d.load('materialSuppliers', () => {
this.loading--;
});
this.api.get<string[]>('/material/groups', (data: any) => {
this.ac.mgroup = data;
this.d.load('materialGroups', () => {
this.loading--;
});
this.api.get<TemplateModel[]>('/template/conditions', data => {
this.conditionTemplates = data.map(e => new TemplateModel().deserialize(e));
this.d.load('conditionTemplates', () => {
this.loading--;
});
this.api.get<TemplateModel[]>('/template/materials', data => {
this.materialTemplates = data.map(e => new TemplateModel().deserialize(e));
this.selectMaterialTemplate(this.materialTemplates[0]._id);
this.d.load('measurementTemplates', () => {
this.loading--;
});
this.api.get<UserModel>('/user', data => {
this.defaultDevice = data.device_name;
});
this.api.get<TemplateModel[]>('/template/measurements', data => {
this.measurementTemplates = data.map(e => new TemplateModel().deserialize(e));
if (!this.new) {
this.loading++;
this.api.get<SampleModel>('/sample/' + this.route.snapshot.paramMap.get('id'), sData => {
this.sample.deserialize(sData);
this.charts = [];
const spectrumTemplate = this.measurementTemplates.find(e => e.name === 'spectrum')._id;
let spectrumCounter = 0;
this.sample.measurements.forEach((measurement, i) => {
this.charts.push(cloneDeep(this.chartInit));
if (measurement.measurement_template === spectrumTemplate) {
setTimeout(() => {
this.generateChart(measurement.values.dpt, i);
console.log(this.charts);
}, spectrumCounter * 20);
spectrumCounter ++;
}
});
this.material = sData.material;
this.customFields = this.sample.notes.custom_fields && this.sample.notes.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) {
this.sampleReferences = [];
this.sampleReferenceAutocomplete = [];
let loadCounter = this.sample.notes.sample_references.length;
this.sample.notes.sample_references.forEach(reference => {
this.api.get<SampleModel>('/sample/' + reference.sample_id, srData => {
this.sampleReferences.push([srData.number, reference.relation, reference.sample_id]);
this.sampleReferenceAutocomplete.push([srData.number]);
if (!--loadCounter) {
this.sampleReferences.push(['', '', '']);
this.sampleReferenceAutocomplete.push([]);
console.log(this.sampleReferences);
console.log(this.sampleReferenceAutocomplete);
}
});
});
}
if ('condition_template' in this.sample.condition) {
this.selectCondition(this.sample.condition.condition_template);
}
console.log('data loaded');
this.loading--;
this.checkFormAfterInit = true;
});
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;
}
this.loading--;
});
this.api.get<TemplateModel[]>('/sample/notes/fields', data => {
this.availableCustomFields = data.map(e => e.name);
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() {
// attach validators to dynamic condition fields when all values are available and template was fully created
if (this.condition && this.condition.hasOwnProperty('parameters') && this.condition.parameters.length > 0 &&
this.condition.parameters[0].hasOwnProperty('range') && this.sampleForm && this.sampleForm.form.get('conditionParameter0')) {
for (const i in this.condition.parameters) {
if (this.condition.parameters[i]) {
this.attachValidator('conditionParameter' + i, this.condition.parameters[i].range, true);
}
}
}
// attach validators to dynamic material fields when all values are available and template was fully created
if (this.materialTemplate && this.materialTemplate.hasOwnProperty('parameters') && this.materialTemplate.parameters.length > 0 &&
this.materialTemplate.parameters[0].hasOwnProperty('range') && this.sampleForm && this.sampleForm.form.get('materialParameter0')) {
for (const i in this.materialTemplate.parameters) {
if (this.materialTemplate.parameters[i]) {
this.attachValidator('materialParameter' + i, this.materialTemplate.parameters[i].range, true);
}
}
}
if (this.sampleForm && this.sampleForm.form.get('measurementParameter0-0')) {
this.sample.measurements.forEach((measurement, mIndex) => {
const template = this.getMeasurementTemplate(measurement.measurement_template);
for (const i in template.parameters) {
if (template.parameters[i]) {
this.attachValidator('measurementParameter' + mIndex + '-' + i, template.parameters[i].range, false);
}
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.checkFormAfterInit) {
this.checkFormAfterInit = false;
this.initialValidate();
}
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);
});
}
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();
});
}
}
}
}
initialValidate() {
console.log('initVal');
Object.keys(this.sampleForm.form.controls).forEach(field => {
this.sampleForm.form.get(field).updateValueAndValidity();
});
}
attachValidator(name: string, range: {[prop: string]: any}, required: boolean) {
if (this.sampleForm.form.get(name)) {
// 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);
@ -250,15 +251,19 @@ export class SampleComponent implements OnInit, AfterContentChecked {
else if (range.hasOwnProperty('max')) {
validators.push(this.validation.generate('max', [range.max]));
}
this.sampleForm.form.get(name).setValidators(validators);
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.materials.push(data); // add material to 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();
@ -277,161 +282,173 @@ export class SampleComponent implements OnInit, AfterContentChecked {
this.sample.notes.sample_references = this.sampleReferences
.filter(e => e[0] && e[1] && e[2])
.map(e => ({sample_id: e[2], relation: e[1]}));
new Promise<SampleModel>(resolve => {
if (this.new) {
this.api.post<SampleModel>('/sample/new', this.sample.sendFormat(), resolve);
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(), resolve);
}
}).then( data => {
this.responseData = new SampleModel().deserialize(data);
this.material = this.materials.find(e => e._id === this.responseData.material_id);
this.sample.measurements.forEach(measurement => {
if (Object.keys(measurement.values).map(e => measurement.values[e]).join('') !== '') {
Object.keys(measurement.values).forEach(key => {
measurement.values[key] = measurement.values[key] === '' ? null : measurement.values[key];
});
if (measurement._id === null) { // new measurement
measurement.sample_id = data._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);
}
}
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.materials.find(e => e.name === name); // search for match
if (res) {
const res = this.d.arr.materials.find(e => e.name === name); // search for match
if (res) { // material found
this.material = cloneDeep(res);
this.sample.material_id = this.material._id;
}
else {
else { // no matching material found
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;
}
this.sample.material_id = null;
}
this.setNewMaterial();
}
preventDefault(event) {
if (event.key && event.key === 'Enter' || event.type === 'dragover') {
event.preventDefault();
}
}
// set newMaterial, if value === null -> toggle
setNewMaterial(value = null) {
if (value === null) {
if (value === null) { // toggle dialog
this.newMaterial = !this.sample.material_id;
}
else if (value || (!value && this.sample.material_id !== null )) { // set to false only if material already exists
this.newMaterial = value;
}
if (this.newMaterial) {
if (this.newMaterial) { // set validators if dialog is open
this.sampleForm.form.get('materialname').setValidators([Validators.required]);
}
else {
else { // material name must be from list if dialog is closed
this.sampleForm.form.get('materialname')
.setValidators([Validators.required, this.validation.generate('stringOf', [this.ac.materialName])]);
.setValidators([Validators.required, this.validation.generate('stringOf', [this.materialNames])]);
}
this.sampleForm.form.get('materialname').updateValueAndValidity();
}
selectCondition(id) {
this.condition = this.conditionTemplates.find(e => e._id === id);
console.log(this.condition);
console.log(this.sample);
if ('condition_template' in this.sample.condition) {
this.sample.condition.condition_template = id;
// 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));
}
selectMaterialTemplate(id) {
this.materialTemplate = this.materialTemplates.find(e => e._id === id);
if ('material_template' in this.material.properties) {
this.material.properties.material_template = id;
// 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);
}
this.generatedSamples[gIndex].measurements.splice(mIndex, 1);
this.charts[gIndex].splice(mIndex, 1);
}
getMeasurementTemplate(id): TemplateModel {
return this.measurementTemplates && id ? this.measurementTemplates.find(e => e._id === id) : new TemplateModel();
// remove measurement data at the specified index
clearMeasurement(gIndex, mIndex) {
this.charts[gIndex][mIndex][0].data = [];
this.generatedSamples[gIndex].measurements[mIndex].values = {};
}
addMeasurement() {
this.sample.measurements.push(new MeasurementModel(this.measurementTemplates.filter(e => e.name === 'spectrum').reverse()[0]._id));
this.sample.measurements[this.sample.measurements.length - 1].values.device = this.defaultDevice;
this.charts.push(cloneDeep(this.chartInit));
}
removeMeasurement(index) {
if (this.sample.measurements[index]._id !== null) {
this.api.delete('/measurement/' + this.sample.measurements[index]._id);
}
this.sample.measurements.splice(index, 1);
this.charts.splice(index, 1);
}
clearChart(index) {
this.charts[index][0].data = [];
}
fileToArray(files, mIndex, parameter) {
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();
index = this.sample.measurements.length - 1;
this.addMeasurement(gIndex);
index = this.generatedSamples[gIndex].measurements.length - 1;
}
this.sample.measurements[index].values[parameter] =
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.sample.measurements[index].values[parameter], index);
this.generateChart(this.generatedSamples[gIndex].measurements[index].values[parameter], gIndex, index);
};
fileReader.readAsText(files[i]);
}
}
}
generateChart(spectrum, index) {
this.charts[index][0].data = spectrum.map(e => ({x: parseFloat(e[0]), y: parseFloat(e[1])}));
generateChart(spectrum, gIndex, mIndex) {
this.charts[gIndex][mIndex][0].data = spectrum.map(e => ({x: parseFloat(e[0]), y: parseFloat(e[1])}));
}
toggleCondition() {
if (this.condition) {
this.condition = null;
toggleCondition(sample) {
if (sample.condition.condition_template) {
sample.condition.condition_template = null;
}
else {
this.sample.condition = {condition_template: null};
this.selectCondition(this.conditionTemplates[0]._id);
sample.condition.condition_template = this.d.arr.conditionTemplates[0]._id;
}
}
checkTypo(list, modal: TemplateRef<any>) {
if (this.ac[list].indexOf(this.material[list]) < 0) { // entry is not in lise
this.modalText.list = list;
this.modalText.suggestion = this.ac[list] // find possible entry from list
.map(e => ({v: e, s: strCompare.sorensenDice(e, this.material[list])}))
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[list] = this.modalText.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']);
}
});
}
checkSampleReference(value, index) {
if (value) {
this.sampleReferences[index][0] = value;
@ -459,16 +476,22 @@ export class SampleComponent implements OnInit, AfterContentChecked {
sampleReferenceList(value) {
return new Observable(observer => {
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));
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([]);
observer.complete();
this.sampleReferenceIdFind(value);
});
}
});
}
@ -489,6 +512,12 @@ export class SampleComponent implements OnInit, AfterContentChecked {
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();
}
}
}