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

@ -1,7 +1,7 @@
add_header Content-Security-Policy "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self'; font-src 'self'; connect-src https://definma-api.apps.de1.bosch-iot-cloud.com; form-action 'none'; frame-ancestors 'none'; base-uri 'self'";
add_header X-Frame-Options DENY;
add_header X-DNS-Prefetch-Control off;
add_header Strict-Transport-Security "max-age=15552000";
add_header Strict-Transport-Security "max-age=15552000; includeSubDomains";
add_header X-Download-Options noopen;
add_header X-Content-Type-Options nosniff;
add_header X-Permitted-Cross-Domain-Policies none;

14
package-lock.json generated
View File

@ -1887,10 +1887,18 @@
}
},
"@inst-iot/bosch-angular-ui-components": {
"version": "file:../Bosch-UI-Components/bosch-angular-ui-components/dist-lib/inst-iot-bosch-angular-ui-components-0.6.0.tgz",
"integrity": "sha512-A4nKOvpdKzq+GWSZlL7U511Ii1vdSA905Q0tru7jAzpBzjRaYqCTiCvsAjRDLM+gVPpzgZ8HpMYfNfhMoNlG/w==",
"version": "0.7.2",
"resolved": "https://rb-artifactory.bosch.com:443/artifactory/api/npm/iot-insights-release-local/@inst-iot/bosch-angular-ui-components/-/@inst-iot/bosch-angular-ui-components-0.7.2.tgz",
"integrity": "sha1-X0AkwkMAy9u/UsG69Zky40LaN5c=",
"requires": {
"tslib": "^1.10.0"
"tslib": "^2.0.0"
},
"dependencies": {
"tslib": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.0.0.tgz",
"integrity": "sha512-lTqkx847PI7xEDYJntxZH89L2/aXInsyF2luSafe/+0fHOMjlBNXdH6th7f70qxLDhul7KZK0zC8V5ZIyHl0/g=="
}
}
},
"@istanbuljs/schema": {

View File

@ -24,8 +24,7 @@
"@angular/platform-browser-dynamic": "~9.1.7",
"@angular/router": "~9.1.7",
"@hapi/joi": "^17.1.1",
"@inst-iot/bosch-angular-ui-components":
"file:../Bosch-UI-Components/bosch-angular-ui-components/dist-lib/inst-iot-bosch-angular-ui-components-0.6.0.tgz",
"@inst-iot/bosch-angular-ui-components": "^0.7.2",
"angular-2-local-storage": "^3.0.2",
"chart.js": "^2.9.3",
"chartjs-plugin-datalabels": "^0.7.0",

View File

@ -2,8 +2,10 @@
<nav *rbMainNavItems>
<a routerLink="/home" routerLinkActive="active" rbLoadingLink>Home</a>
<a routerLink="/samples" routerLinkActive="active" rbLoadingLink *ngIf="loginService.isLoggedIn">Samples</a>
<a routerLink="/templates" routerLinkActive="active" rbLoadingLink *ngIf="loginService.is('maintain')">Templates</a>
<a routerLink="/users" routerLinkActive="active" rbLoadingLink *ngIf="loginService.is('admin')">Users</a>
<a routerLink="/templates" routerLinkActive="active" rbLoadingLink *ngIf="loginService.isLevel.dev">
Templates
</a>
<a routerLink="/users" routerLinkActive="active" rbLoadingLink *ngIf="loginService.isLevel.admin">Users</a>
<a routerLink="/documentation" routerLinkActive="active" rbLoadingLink>Documentation</a>
</nav>
@ -20,7 +22,19 @@
</ng-template>
</ng-container>
<div *rbSubBrandHeader><span class="dev-label" *ngIf="devMode">DEVELOPMENT</span>Digital Fingerprint of Plastics</div>
<div *rbSubBrandHeader>
<rb-icon-button icon="bug" mode="secondary" class="space-right" [rbModal]="bugModal">Bug</rb-icon-button>
<ng-template let-close="close" #bugModal>
<h3>Report a bug</h3>
<rb-form-textarea class="bug-textarea" label="What did you do?" [(ngModel)]="bugReport.do"></rb-form-textarea>
<rb-form-textarea class="bug-textarea" label="What did not work?" [(ngModel)]="bugReport.work"></rb-form-textarea>
<a [href]="bugReportContent()">
<rb-icon-button icon="mail" mode="primary" (mouseup)="closeBugReport(close)">Send report</rb-icon-button>
</a>
</ng-template>
<span class="dev-label" *ngIf="devMode">DEVELOPMENT</span>
DeFinMa
</div>
</rb-full-header>
<div class="container">

View File

@ -9,3 +9,7 @@
grid-template-columns: 1fr;
grid-row-gap: 10px;
}
.bug-textarea {
width: 800px;
}

View File

@ -6,6 +6,8 @@ import {Router} from '@angular/router';
// TODO: validation: DPT: filename
// TODO: filter by not completely filled/no measurements
// TODO: validation of samples
// TODO: centralize fetching of materials / templates, etc.
// TODO: PWA
// TODO: get rid of chart.js (+moment.js)
@ -16,6 +18,8 @@ import {Router} from '@angular/router';
})
export class AppComponent {
bugReport = {do: '', work: ''};
constructor(
public loginService: LoginService,
private router: Router
@ -30,4 +34,28 @@ export class AppComponent {
this.loginService.logout();
this.router.navigate(['/']);
}
bugReportContent() {
return `mailto:lukas.veit@de.bosch.com?subject=Bug report&body=Thanks for sending the report! Your bug will be (hopefully) fixed soon.
%0D%0A%0D%0A--- REPORT DATA ---
%0D%0A%0D%0ATime: ${new Date().toString()}%0D%0A
URL: ${window.location}%0D%0A%0D%0AWhat did you do?%0D%0A${encodeURIComponent(this.bugReport.do)}
%0D%0A%0D%0AWhat did not work?%0D%0A${encodeURIComponent(this.bugReport.work)}%0D%0A%0D%0ABrowser:%0D%0A
%0D%0AappCodeName: ${navigator.appCodeName}
%0D%0AappVersion: ${navigator.appVersion}
%0D%0Alanguage: ${navigator.language}
%0D%0AonLine: ${navigator.onLine}
%0D%0Aoscpu: ${navigator.oscpu}
%0D%0Aplatform: ${navigator.platform}
%0D%0AuserAgent: ${navigator.userAgent}
%0D%0AinnerWidth: ${window.innerWidth}
%0D%0AinnerHeight: ${window.innerHeight}`;
}
closeBugReport(close) {
setTimeout(() => close(), 1);
}
}

View File

@ -1,9 +1,67 @@
<h2>Samples</h2>
<h2>Documentation</h2>
<p>
Find the API documentation here: <a href="https://definma-api.apps.de1.bosch-iot-cloud.com/api-doc/">https://definma-api.apps.de1.bosch-iot-cloud.com/api-doc/</a>
Find the API documentation here:
<a href="https://definma-api.apps.de1.bosch-iot-cloud.com/api-doc/">
https://definma-api.apps.de1.bosch-iot-cloud.com/api-doc/
</a>
</p>
<h4>User levels</h4>
<rb-table>
<tr>
<th></th>
<th>read sample data</th>
<th>add samples/edit own</th>
<th>read spectral data</th>
<th>edit other's data</th>
<th>maintain templates</th>
<th>edit users</th>
</tr>
<tr>
<td>read</td>
<td><span class="rb-ic rb-ic-checkmark-frame"></span></td>
<td><span class="rb-ic rb-ic-abort-frame"></span></td>
<td><span class="rb-ic rb-ic-abort-frame"></span></td>
<td><span class="rb-ic rb-ic-abort-frame"></span></td>
<td><span class="rb-ic rb-ic-abort-frame"></span></td>
<td><span class="rb-ic rb-ic-abort-frame"></span></td>
</tr>
<tr>
<td>write</td>
<td><span class="rb-ic rb-ic-checkmark-frame"></span></td>
<td><span class="rb-ic rb-ic-checkmark-frame"></span></td>
<td><span class="rb-ic rb-ic-abort-frame"></span></td>
<td><span class="rb-ic rb-ic-abort-frame"></span></td>
<td><span class="rb-ic rb-ic-abort-frame"></span></td>
<td><span class="rb-ic rb-ic-abort-frame"></span></td>
</tr>
<tr>
<td>dev</td>
<td><span class="rb-ic rb-ic-checkmark-frame"></span></td>
<td><span class="rb-ic rb-ic-checkmark-frame"></span></td>
<td><span class="rb-ic rb-ic-checkmark-frame"></span></td>
<td><span class="rb-ic rb-ic-checkmark-frame"></span></td>
<td><span class="rb-ic rb-ic-checkmark-frame"></span></td>
<td><span class="rb-ic rb-ic-abort-frame"></span></td>
</tr>
<tr>
<td>admin</td>
<td><span class="rb-ic rb-ic-checkmark-frame"></span></td>
<td><span class="rb-ic rb-ic-checkmark-frame"></span></td>
<td><span class="rb-ic rb-ic-checkmark-frame"></span></td>
<td><span class="rb-ic rb-ic-checkmark-frame"></span></td>
<td><span class="rb-ic rb-ic-checkmark-frame"></span></td>
<td><span class="rb-ic rb-ic-checkmark-frame"></span></td>
</tr>
</rb-table>
<h4>Database model</h4>
<app-img-magnifier src="assets/imgs/db_structure_latest.svg" zoom="2" [magnifierSize]="{width: 400, height: 300}" id="db-structure"></app-img-magnifier>
<app-img-magnifier src="assets/imgs/db_structure_latest.svg" zoom="2" [magnifierSize]="{width: 400, height: 300}"
id="db-structure"></app-img-magnifier>

View File

@ -1,3 +1,5 @@
@import "~@inst-iot/bosch-angular-ui-components/styles/variables/colors";
p {
margin-bottom: 20px;
}
@ -5,3 +7,11 @@ p {
img#db-structure {
width: 100%;
}
.rb-ic-checkmark-frame {
color: $brand-success;
}
.rb-ic-abort-frame {
color: $brand-danger;
}

View File

@ -1,4 +1,5 @@
import pick from 'lodash/pick';
import cloneDeep from 'lodash/cloneDeep';
import {IdModel} from './id.model';
import {MaterialModel} from './material.model';
import {MeasurementModel} from './measurement.model';
@ -10,12 +11,13 @@ export class SampleModel extends BaseModel {
number = '';
type = '';
batch = '';
condition: {condition_template: string, [prop: string]: string} | {} = {};
condition: {condition_template: string, [prop: string]: string} = {condition_template: null};
material_id: IdModel = null;
material: MaterialModel;
measurements: MeasurementModel[] = [];
note_id: IdModel = null;
user_id: IdModel = null;
validate = false;
notes: {
comment: string,
sample_references: {sample_id: IdModel, relation: string}[],
@ -39,6 +41,14 @@ export class SampleModel extends BaseModel {
}
sendFormat() {
return pick(this, ['color', 'type', 'batch', 'condition', 'material_id', 'notes']);
return pick(this.conditionTemplateCheck(), ['color', 'type', 'batch', 'condition', 'material_id', 'notes']);
}
private conditionTemplateCheck() {
const res = cloneDeep(this);
if (res.condition.condition_template === null) {
res.condition = {};
}
return res;
}
}

View File

@ -1,4 +1,4 @@
<button class="rb-btn rb" [ngClass]="'rb-' + mode" [type]="type" [disabled]="disabled">
<span class="rb-ic" [ngClass]="'rb-ic-' + icon"></span>&nbsp;&nbsp;
<span class="rb-ic" [ngClass]="'rb-ic-' + icon" [class.icon-space]="iconOnly === undefined"></span>
<ng-content></ng-content>
</button>

View File

@ -0,0 +1,8 @@
.icon-space {
margin-right: 0.1em !important;
}
button.rb-btn > span:not(.icon-space) {
margin-right: -10px;
margin-left: -10px;
}

View File

@ -11,6 +11,7 @@ export class RbIconButtonComponent implements OnInit {
@Input() icon: string;
@Input() mode: string;
@Input() iconOnly;
@Input() disabled;
@Input() type = 'button';

View File

@ -1,5 +1,4 @@
<script src="rb-table.component.ts"></script>
<div class="table-wrapper">
<div class="table-wrapper space-below">
<table>
<ng-content></ng-content>
</table>

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,63 +113,101 @@
</rb-array-input>
</div>
&nbsp;
<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 class="conditions shaded-container">
<h4>
<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()"
[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>
<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 condition.parameters; index as i" [name]="'conditionParameter' + i"
<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)]="sample.condition[parameter.name]" #parameterInput="ngModel">
[(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>
&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>
<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 getMeasurementTemplate(measurement.measurement_template).parameters;
<div *ngFor="let parameter of d.id.measurementTemplates[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">
<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' + mIndex + '-' + pIndex"
<rb-form-file *ngIf="parameter.range.type"
[name]="'measurementParameter-' + gIndex + '-' + mIndex + '-' + pIndex"
[label]="parameter.name" maxSize="10000000" multiple
(ngModelChange)="fileToArray($event, mIndex, parameter.name)"
placeholder="Select file or drag and drop" dragDrop required ngModel>
[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[mIndex][0].data.length > 0" class="dpt-chart" [@inOut]
[datasets]="charts[mIndex]"
<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(mIndex)"
[disabled]="!measurementTemplates">
<rb-icon-button icon="delete" mode="danger" (click)="removeMeasurement(gIndex, mIndex)">
Delete measurement
</rb-icon-button>
</div>
@ -176,35 +215,23 @@
&nbsp;
<div>
<rb-icon-button icon="add" mode="secondary" (click)="addMeasurement()" [disabled]="!measurementTemplates">
<rb-icon-button icon="add" mode="secondary" (click)="addMeasurement(gIndex)">
New measurement
</rb-icon-button>
</div>
</div>
<div>
<button class="rb-btn rb-primary" type="submit" (click)="saveSample()" [disabled]="!sampleForm.form.valid">
Save sample
</button>
</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 *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>
</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[] = [];
sampleReferenceAutocomplete: string[][] = [[]];
responseData: SampleModel; // gets filled with response data after saving the sample
measurementTemplates: TemplateModel[];
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.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.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;
});
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) {
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, i);
console.log(this.charts);
}, spectrumCounter * 20);
this.generateChart(measurement.values.dpt, 0, i);
}, spectrumCounter * 20); // generate charts one after another to avoid freezing the UI
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.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;
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 => {
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) {
if (!--loadCounter) { // insert empty template when all instances were loaded
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.loading--;
});
this.api.get<TemplateModel[]>('/sample/notes/fields', data => {
this.availableCustomFields = data.map(e => e.name);
this.loading--;
});
}
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);
});
if (this.checkFormAfterInit) {
this.checkFormAfterInit = false;
this.initialValidate();
}
}
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);
});
});
});
}
initialValidate() {
console.log('initVal');
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();
});
}
}
}
}
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,23 +282,38 @@ 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);
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);
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;
});
}
}).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 => {
});
}
// 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 => {
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 = data._id;
measurement.sample_id = sample._id;
this.api.post<MeasurementModel>('/measurement/new', measurement.sendFormat());
}
else { // update measurement
@ -306,132 +326,129 @@ export class SampleComponent implements OnInit, AfterContentChecked {
}
});
});
});
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,6 +476,7 @@ export class SampleComponent implements OnInit, AfterContentChecked {
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 => {
@ -469,6 +487,11 @@ export class SampleComponent implements OnInit, AfterContentChecked {
observer.complete();
this.sampleReferenceIdFind(value);
});
}
else {
observer.next([]);
observer.complete();
}
});
}
@ -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();
}
}
}

View File

@ -1,9 +1,15 @@
<script src="samples.component.ts"></script>
<div class="header-addnew">
<h2>Samples</h2>
<a routerLink="/samples/new">
<rb-icon-button icon="add" mode="primary">New sample</rb-icon-button>
<a routerLink="/samples/new" *ngIf="login.isLevel.write">
<rb-icon-button icon="add" mode="primary" class="space-left">New sample</rb-icon-button>
</a>
<rb-icon-button *ngIf="validation" mode="secondary" icon="close" (click)="validation = false" class="validation-close"
iconOnly></rb-icon-button>
<rb-icon-button *ngIf="login.isLevel.dev" [icon]="validation? 'checkmark' : 'clear-all'"
mode="secondary" (click)="validate()">
Validate
</rb-icon-button>
</div>
<rb-accordion>
@ -86,13 +92,15 @@
<ng-container *ngTemplateOutlet="paging"></ng-container>
<div class="download">
<rb-icon-button icon="download" mode="secondary" [rbModal]="linkModal">JSON download link</rb-icon-button>
<div class="download space-below" *ngIf="login.isLevel.dev">
<rb-icon-button class="space-right" icon="download" mode="secondary" [rbModal]="linkModal">
JSON download link
</rb-icon-button>
<ng-template #linkModal>
<label for="jsonUrl">URL for JSON download</label>
<textarea class="linkmodal" id="jsonUrl" #linkarea [value]="sampleUrl({export: true, host: true})"
(keydown)="preventDefault($event)"></textarea>
<rb-form-checkbox name="download-csv" [(ngModel)]="downloadCsv">
<rb-form-checkbox class="space-below" name="download-csv" [(ngModel)]="downloadCsv">
add spectra
</rb-form-checkbox>
<rb-icon-button icon="clipboard" mode="secondary" (click)="clipboard()">Copy to clipboard</rb-icon-button>
@ -104,8 +112,11 @@
</a>
</div>
<rb-table>
<rb-table class="samples-table">
<tr>
<th *ngIf="validation">
<rb-form-checkbox name="validate-all" (change)="selectAll($event)">all</rb-form-checkbox>
</th>
<th *ngFor="let key of activeKeys">
<div class="sort-header">
<span>{{key.label}}</span>
@ -119,17 +130,21 @@
</ng-container>
</div>
</th>
<th></th>
<th *ngIf="login.isLevel.write"></th>
</tr>
<tr *ngFor="let sample of samples">
<tr *ngFor="let sample of samples; index as i" class="clickable" (click)="sampleDetails(sample._id, sampleModal)">
<td *ngIf="validation">
<rb-form-checkbox [name]="'validate-' + i" (click)="stopPropagation($event)" [(ngModel)]="sample.validate">
</rb-form-checkbox>
</td>
<td *ngIf="isActiveKey['number']">{{sample.number}}</td>
<td *ngIf="isActiveKey['material.numbers']">{{materials[sample.material_id].numbers}}</td>
<td *ngIf="isActiveKey['material.name']">{{materials[sample.material_id].name}}</td>
<td *ngIf="isActiveKey['material.supplier']">{{materials[sample.material_id].supplier}}</td>
<td *ngIf="isActiveKey['material.group']">{{materials[sample.material_id].group}}</td>
<td *ngIf="isActiveKey['material.numbers']">{{d.id.materials[sample.material_id].numbers}}</td>
<td *ngIf="isActiveKey['material.name']">{{d.id.materials[sample.material_id].name}}</td>
<td *ngIf="isActiveKey['material.supplier']">{{d.id.materials[sample.material_id].supplier}}</td>
<td *ngIf="isActiveKey['material.group']">{{d.id.materials[sample.material_id].group}}</td>
<td *ngFor="let key of activeTemplateKeys.material">
{{materials[sample.material_id].properties[key[2]] | exists}}
{{d.id.materials[sample.material_id].properties[key[2]] | exists}}
</td>
<td *ngIf="isActiveKey['type']">{{sample.type}}</td>
<td *ngIf="isActiveKey['color']">{{sample.color}}</td>
@ -137,7 +152,12 @@
<td *ngIf="isActiveKey['notes']">{{sample.notes | object: ['_id', 'sample_references']}}</td>
<td *ngFor="let key of activeTemplateKeys.measurements">{{sample[key[1]] | exists: key[2]}}</td>
<td *ngIf="isActiveKey['added']">{{sample.added | date:'dd/MM/yy'}}</td>
<td><a [routerLink]="'/samples/edit/' + sample._id"><span class="rb-ic rb-ic-edit"></span></a></td>
<td *ngIf="login.isLevel.write">
<a [routerLink]="'/samples/edit/' + sample._id"
*ngIf="login.isLevel.dev || (login.isLevel.write && sample.user_id === login.userId)">
<span class="rb-ic rb-ic-edit"></span>
</a>
</td>
</tr>
</rb-table>
@ -159,3 +179,35 @@
</div>
</ng-template>
<ng-template #sampleModal>
<rb-loading-spinner *ngIf="sampleDetailsSample === null; else sampleDetailsTemplate"></rb-loading-spinner>
<ng-template #sampleDetailsTemplate>
<h3>{{sampleDetailsSample.number}}</h3>
<rb-table class="sample-details-table">
<tr><th>Material</th><td>{{sampleDetailsSample.material.name}}</td></tr>
<tr><th>Supplier</th><td>{{sampleDetailsSample.material.supplier}}</td></tr>
<tr><th>Group</th><td>{{sampleDetailsSample.material.group}}</td></tr>
<tr><th>Type</th><td>{{sampleDetailsSample.type}}</td></tr>
<tr><th>color</th><td>{{sampleDetailsSample.color}}</td></tr>
<tr><th>Batch</th><td>{{sampleDetailsSample.batch}}</td></tr>
<tr><th>Comment</th><td>{{sampleDetailsSample.notes.comment | exists}}</td></tr>
<tr *ngFor="let customField of sampleDetailsSample.notes.custom_fields_entries">
<th>{{customField[0]}}</th>
<td>{{customField[0]}}</td>
</tr>
<tr *ngFor="let reference of sampleDetailsSample.notes.sample_references">
<th>{{reference.relation}}</th>
<td>
<button class="rb-btn rb-link" (click)="sampleDetails(reference.sample_id, sampleModal)">
{{reference.number}}
</button>
</td>
</tr>
<tr *ngFor="let measurement of sampleDetailsSample.measurement_entries">
<th>{{measurement.name}}</th>
<td>{{measurement.value}}</td>
</tr>
<tr><th>User</th><td>{{sampleDetailsSample.user}}</td></tr>
</rb-table>
</ng-template>
</ng-template>

View File

@ -180,3 +180,33 @@ textarea.linkmodal {
display: inline-block;
width: 220px;
}
.sample-details-table {
::ng-deep .table-wrapper {
max-height: 80vh;
overflow-y: scroll;
}
td {
max-width: none;
}
}
.validation-close {
margin-left: -1px;
}
.samples-table tr.clickable {
background: none;
transition: background-color 0.5s;
&:hover {
background: $color-gray-mercury;
}
}
::ng-deep .samples-table rb-form-checkbox .input-wrapper {
padding-top: 0;
margin-top: -4.5px;
}

View File

@ -1,9 +1,12 @@
import {Component, ElementRef, isDevMode, OnInit, ViewChild} from '@angular/core';
import {Component, ElementRef, isDevMode, OnInit, TemplateRef, ViewChild} from '@angular/core';
import {ApiService} from '../services/api.service';
import {AutocompleteService} from '../services/autocomplete.service';
import cloneDeep from 'lodash/cloneDeep';
import pick from 'lodash/pick';
import {SampleModel} from '../models/sample.model';
import {LoginService} from '../services/login.service';
import {ModalService} from '@inst-iot/bosch-angular-ui-components';
import {DataService} from '../services/data.service';
interface LoadSamplesOptions {
@ -32,7 +35,6 @@ export class SamplesComponent implements OnInit {
@ViewChild('linkarea') linkarea: ElementRef<HTMLTextAreaElement>;
downloadCsv = false;
materials = {};
samples: SampleModel[] = [];
totalSamples = 0; // total number of samples
csvUrl = ''; // store url separate so it only has to be generated when clicking the download button
@ -60,7 +62,6 @@ export class SamplesComponent implements OnInit {
page = 1;
pages = 1;
loadSamplesQueue = []; // arguments of queued up loadSamples() calls
apiKey = '';
keys: KeyInterface[] = [
{id: 'number', label: 'Number', active: true, sortable: true},
{id: 'material.numbers', label: 'Material numbers', active: true, sortable: false},
@ -76,55 +77,55 @@ export class SamplesComponent implements OnInit {
isActiveKey: {[key: string]: boolean} = {};
activeKeys: KeyInterface[] = [];
activeTemplateKeys = {material: [], measurements: []};
sampleDetailsSample: any = null;
validation = false; // true to activate validation mode
constructor(
private api: ApiService,
public autocomplete: AutocompleteService
public autocomplete: AutocompleteService,
public login: LoginService,
private modalService: ModalService,
public d: DataService
) {
}
ngOnInit(): void {
this.calcFieldSelectKeys();
this.api.get('/materials?status=all', (mData: any) => {
this.materials = {};
mData.forEach(material => {
this.materials[material._id] = material;
});
this.filters.filters.find(e => e.field === 'material.name').autocomplete = mData.map(e => e.name);
this.d.load('materials', () => {
this.filters.filters.find(e => e.field === 'material.name').autocomplete = this.d.arr.materials.map(e => e.name);
this.filters.filters.find(e => e.field === 'color').autocomplete =
[...new Set(mData.reduce((s, e) => {s.push(...e.numbers.map(el => el.color)); return s; }, []))];
[...new Set(this.d.arr.materials.reduce((s, e) => {s.push(...e.numbers.map(el => el.color)); return s; }, []))];
this.loadSamples();
});
this.api.get('/user/key', (data: {key: string}) => {
this.apiKey = data.key;
this.d.load('materialSuppliers', () => {
this.filters.filters.find(e => e.field === 'material.supplier').autocomplete = this.d.arr.materialSuppliers;
});
this.api.get<string[]>('/material/suppliers', (data: any) => {
this.filters.filters.find(e => e.field === 'material.supplier').autocomplete = data;
this.d.load('materialGroups', () => {
console.log(this.d.arr.materialGroups);
this.filters.filters.find(e => e.field === 'material.group').autocomplete = this.d.arr.materialGroups;
});
this.api.get<string[]>('/material/groups', (data: any) => {
this.filters.filters.find(e => e.field === 'material.group').autocomplete = data;
});
this.loadTemplateKeys('materials', 'type');
this.loadTemplateKeys('measurements', 'added');
this.d.load('userKey');
this.loadTemplateKeys('material', 'type');
this.loadTemplateKeys('measurement', 'added');
}
loadTemplateKeys(collection, insertBefore) {
this.api.get('/template/' + collection, (data: {name: string, parameters: {name: string, range: object}[]}[]) => {
this.d.load(collection + 'Templates', () => {
const templateKeys = [];
data.forEach(item => {
this.d.arr[collection + 'Templates'].forEach(item => {
item.parameters.forEach(parameter => {
const parameterName = encodeURIComponent(parameter.name);
// exclude spectrum
// exclude spectrum and duplicates
if (parameter.name !== 'dpt' && !templateKeys.find(e => new RegExp('.' + parameterName + '$').test(e.id))) {
templateKeys.push({
id: `${collection === 'materials' ? 'material.properties' : collection + '.' + item.name}.${parameterName}`,
id: `${collection === 'material' ? 'material.properties' : collection + 's.' + item.name}.${parameterName}`,
label: `${this.ucFirst(item.name)} ${this.ucFirst(parameter.name)}`,
active: false,
sortable: true
});
this.filters.filters.push({
field: `${collection === 'materials' ? 'material.properties' : collection + '.' + item.name}.${parameterName}`,
field: `${collection === 'material' ? 'material.properties' : collection + 's.' + item.name}.${parameterName}`,
label: `${this.ucFirst(item.name)} ${this.ucFirst(parameter.name)}`,
active: false,
autocomplete: [],
@ -181,7 +182,7 @@ export class SamplesComponent implements OnInit {
export?: boolean,
host?: boolean
}) { // return url to fetch samples
const additionalTableKeys = ['material_id', '_id']; // keys which should always be added if export = false
const additionalTableKeys = ['material_id', '_id', 'user_id']; // keys which should always be added if export = false
const query: string[] = [];
query.push(
'status=' + (this.filters.status.new && this.filters.status.validated ? 'all' : (this.filters.status.new ? 'new' : 'validated'))
@ -205,7 +206,7 @@ export class SamplesComponent implements OnInit {
query.push('csv=true');
}
if (options.export) {
query.push('key=' + this.apiKey);
query.push('key=' + this.d.d.userKey.key);
}
this.keys.forEach(key => {
// do not load material properties for table
@ -278,12 +279,75 @@ export class SamplesComponent implements OnInit {
});
}
// TODO: add measurements when ressource service is done
sampleDetails(id: string, modal: TemplateRef<any>) {
this.sampleDetailsSample = null;
this.api.get<SampleModel>('/sample/' + id, data => {
this.sampleDetailsSample = new SampleModel().deserialize(data);
if (data.notes.custom_fields) { // convert custom_fields for more optimized display
this.sampleDetailsSample.notes.custom_fields_entries = Object.entries(this.sampleDetailsSample.notes.custom_fields);
}
else {
this.sampleDetailsSample.custom_fields_entries = [];
}
this.sampleDetailsSample.measurement_entries = [];
this.sampleDetailsSample.measurements.forEach(measurement => { // convert measurements for more optimized display without dpt
const name = this.d.id.measurementTemplates[measurement.measurement_template].name;
this.sampleDetailsSample.measurement_entries.push(...Object.entries(measurement.values).filter(e => e[0] !== 'dpt')
.map(e => ({name: this.ucFirst(name) + ' ' + this.ucFirst(e[0]), value: e[1]})));
});
new Promise(resolve => {
if (data.notes.sample_references.length) { // load referenced samples if available
let loadingCounter = data.notes.sample_references.length;
this.sampleDetailsSample.notes.sample_references.forEach(reference => {
this.api.get<SampleModel>('/sample/' + reference.sample_id, rData => {
reference.number = rData.number;
loadingCounter --;
if (!loadingCounter) {
resolve();
}
});
});
}
else {
resolve();
}
}).then(() => {
this.modalService.open(modal).then(() => {});
});
});
}
validate() {
if (this.validation) {
this.samples.forEach(sample => {
if (sample.validate) {
this.api.put('/sample/validate/' + sample._id);
}
});
this.validation = false;
}
else {
this.validation = true;
}
}
selectAll(event) {
this.samples.forEach(sample => {
sample.validate = event.target.checked;
});
}
preventDefault(event, key = 'all') {
if (key === 'all' || event.key === key) {
event.preventDefault();
}
}
stopPropagation(event) {
event.stopPropagation();
}
clipboard() {
this.linkarea.nativeElement.select();
this.linkarea.nativeElement.setSelectionRange(0, 99999);

View File

@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { DataService } from './data.service';
describe('DataService', () => {
let service: DataService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(DataService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});

View File

@ -0,0 +1,52 @@
import { Injectable } from '@angular/core';
import {TemplateModel} from '../models/template.model';
import {ApiService} from './api.service';
import {MaterialModel} from '../models/material.model';
import {BaseModel} from '../models/base.model';
import {UserModel} from '../models/user.model';
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(
private api: ApiService
) { }
private collectionMap = {
materials: {path: '/materials?status=all', model: MaterialModel, array: true},
materialSuppliers: {path: '/material/suppliers', model: null, array: true},
materialGroups: {path: '/material/groups', model: null, array: true},
materialTemplates: {path: '/template/materials', model: TemplateModel, array: true},
measurementTemplates: {path: '/template/measurements', model: TemplateModel, array: true},
conditionTemplates: {path: '/template/conditions', model: TemplateModel, array: true},
sampleNotesFields: {path: '/sample/notes/fields', model: TemplateModel, array: true},
users: {path: '/users', model: UserModel, array: true},
user: {path: '/user', model: UserModel, array: false},
userKey: {path: '/user/key', model: BaseModel, array: false}
};
arr: {[key: string]: any[]} = {}; // array of data
id: {[key: string]: {[id: string]: any}} = {}; // data in format _id: data
d: {[key: string]: any} = {}; // data not in array format
load(collection, f = () => {}) { // load data
if (this.arr[collection]) { // data already loaded
f();
}
else { // load data
this.api.get<any>(this.collectionMap[collection].path, data => {
if (this.collectionMap[collection].array) { // array data
this.arr[collection] = data
.map(e => this.collectionMap[collection].model ? new this.collectionMap[collection].model().deserialize(e) : e);
this.id[collection] = this.arr[collection].reduce((s, e) => {s[e._id] = e; return s; }, {});
}
else { // not array data
this.d[collection] = new this.collectionMap[collection].model().deserialize(data);
}
f();
});
}
}
}

View File

@ -10,19 +10,19 @@ import {Observable} from 'rxjs';
export class LoginService implements CanActivate {
private pathPermissions = [
{path: 'templates', permission: 'maintain'},
{path: 'templates', permission: 'dev'},
{path: 'users', permission: 'admin'}
];
readonly levels = [
'read',
'write',
'maintain',
'dev',
'admin'
];
isLevel: {[level: string]: boolean} = {};
userId = '';
private loggedIn;
private level;
constructor(
private api: ApiService,
@ -57,7 +57,10 @@ export class LoginService implements CanActivate {
if (!error) {
if (data.status === 'Authorization successful') {
this.loggedIn = true;
this.level = data.level;
this.levels.forEach(level => {
this.isLevel[level] = this.levels.indexOf(data.level) >= this.levels.indexOf(level);
});
this.userId = data.user_id;
resolve(true);
} else {
this.loggedIn = false;
@ -91,7 +94,7 @@ export class LoginService implements CanActivate {
}
}).then(res => {
const pathPermission = this.pathPermissions.find(e => e.path.indexOf(route.url[0].path) >= 0);
const ok = res && !pathPermission || this.is(pathPermission.permission); // check if level is permitted for path
const ok = res && (!pathPermission || this.isLevel[pathPermission.permission]); // check if level is permitted for path
observer.next(ok);
observer.complete();
if (!ok) {
@ -105,10 +108,6 @@ export class LoginService implements CanActivate {
return this.loggedIn;
}
is(level) {
return this.levels.indexOf(this.level) >= this.levels.indexOf(level);
}
get username() {
return atob(this.storage.get('basicAuth')).split(':')[0];
}

View File

@ -37,6 +37,7 @@ export class UsersComponent implements OnInit {
this.api.post('/user/new', {...this.newUser.sendFormat('admin'), pass: this.newUserPass}, data => {
this.newUser = null;
this.users.push(new UserModel().deserialize(data));
this.newUserPass = '';
});
}

View File

@ -2,7 +2,7 @@
<html lang="en">
<head>
<meta charset="utf-8">
<title>DFOP</title>
<title>DeFinMa</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">

View File

@ -23,3 +23,19 @@ button::-moz-focus-inner {
.clickable {
cursor: pointer;
}
.space-below {
margin-bottom: $default-spacing;
}
.space-above {
margin-top: $default-spacing;
}
.space-right {
margin-right: $default-spacing;
}
.space-left {
margin-left: $default-spacing;
}