added help component, improved prediction with model templates

This commit is contained in:
VLE2FE 2020-08-20 10:42:02 +02:00
parent 9c2095c31a
commit 433572f819
25 changed files with 459 additions and 65 deletions

View File

@ -11,12 +11,14 @@ import {UsersComponent} from './users/users.component';
import {ChangelogComponent} from './changelog/changelog.component';
import {DocumentationDatabaseComponent} from './documentation-database/documentation-database.component';
import {PredictionComponent} from './prediction/prediction.component';
import {ModelTemplatesComponent} from './model-templates/model-templates.component';
const routes: Routes = [
{path: '', component: HomeComponent},
{path: 'home', component: HomeComponent},
{path: 'prediction', component: PredictionComponent},
{path: 'models', component: ModelTemplatesComponent},
{path: 'samples', component: SamplesComponent, canActivate: [LoginService]},
{path: 'samples/new', component: SampleComponent, canActivate: [LoginService]},
{path: 'samples/edit/:id', component: SampleComponent, canActivate: [LoginService]},

View File

@ -1,7 +1,8 @@
<rb-full-header id="top">
<nav *rbMainNavItems>
<a routerLink="/home" routerLinkActive="active" rbLoadingLink>Home</a>
<a routerLink="/prediction" routerLinkActive="active" rbLoadingLink *ngIf="login.isLevel.admin">Prediction</a>
<a routerLink="/prediction" routerLinkActive="active" rbLoadingLink *ngIf="login.isLevel.dev">Prediction</a>
<a routerLink="/models" routerLinkActive="active" rbLoadingLink *ngIf="login.isLevel.dev">Models</a>
<a routerLink="/samples" routerLinkActive="active" rbLoadingLink *ngIf="login.isLoggedIn">Samples</a>
<a routerLink="/templates" routerLinkActive="active" rbLoadingLink *ngIf="login.isLevel.dev">
Templates
@ -18,6 +19,10 @@
</nav>
</ng-container>
<nav *rbMetaNavItems>
<span class="rb-ic rb-ic-question-frame clickable space-above" (click)="help()"></span>
</nav>
<ng-container *ngIf="login.isLoggedIn">
<nav *rbActionNavItems>
<a href="javascript:" [rbPopover]="userPopover" [anchor]="popoverAnchor">
@ -55,3 +60,12 @@
<rb-icon-button icon="up" mode="primary" iconOnly (click)="toTheTop()"></rb-icon-button>
</div>
</div>
<rb-footer-nav>
<span class="copyright">
CR/APS1 and CR/ANA1 2020
</span>
<nav>
<a [href]="'mailto:' + d.contact">Contact</a>
</nav>
</rb-footer-nav>

View File

@ -16,6 +16,7 @@
.to-the-top-container {
position: relative;
overflow: hidden;
}
.to-the-top {

View File

@ -1,6 +1,9 @@
import {Component, isDevMode, OnInit} from '@angular/core';
import {LoginService} from './services/login.service';
import {NavigationStart, Router} from '@angular/router';
import {ModalService} from '@inst-iot/bosch-angular-ui-components';
import {HelpComponent} from './help/help.component';
import {DataService} from './services/data.service';
// TODO: get rid of chart.js (+moment.js)
@ -19,7 +22,9 @@ export class AppComponent implements OnInit{
constructor(
public login: LoginService,
public router: Router,
private window: Window
private window: Window,
private modal: ModalService,
public d: DataService
) {
this.devMode = isDevMode();
this.router.events.subscribe(event => {
@ -30,7 +35,12 @@ export class AppComponent implements OnInit{
}
ngOnInit() {
this.login.login();
this.login.login().then(res => {
console.log(res);
if (!res) {
this.router.navigate(['/']);
}
});
}
logout() {
@ -38,6 +48,10 @@ export class AppComponent implements OnInit{
this.router.navigate(['/']);
}
help() {
this.modal.openComponent(HelpComponent);
}
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 ---

View File

@ -30,6 +30,8 @@ import { DocumentationDatabaseComponent } from './documentation-database/documen
import { PredictionComponent } from './prediction/prediction.component';
import { ServiceWorkerModule } from '@angular/service-worker';
import { environment } from '../environments/environment';
import { HelpComponent } from './help/help.component';
import { ModelTemplatesComponent } from './model-templates/model-templates.component';
@NgModule({
declarations: [
@ -50,7 +52,9 @@ import { environment } from '../environments/environment';
UsersComponent,
ChangelogComponent,
DocumentationDatabaseComponent,
PredictionComponent
PredictionComponent,
HelpComponent,
ModelTemplatesComponent
],
imports: [
LocalStorageModule.forRoot({

View File

@ -0,0 +1,14 @@
<h3>Help</h3>
<ng-container [ngSwitch]="route">
<p *ngSwitchCase="'/'">Please log in for further access. If you do not have an account yet, please contact
<a [href]="'mailto:' + d.contact">{{d.contact}}</a>.
</p>
<p *ngSwitchCase="'/home'">Please log in for further access. If you do not have an account yet, please contact
<a [href]="'mailto:' + d.contact">{{d.contact}}</a>.
</p>
<p *ngSwitchDefault>
Sadly, currently there is no help available for this page. Please contact
<a [href]="'mailto:' + d.contact">{{d.contact}}</a> for further questions.
</p>
</ng-container>

View File

View File

@ -0,0 +1,25 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { HelpComponent } from './help.component';
describe('HelpComponent', () => {
let component: HelpComponent;
let fixture: ComponentFixture<HelpComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ HelpComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(HelpComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,24 @@
import { Component, OnInit } from '@angular/core';
import {Router} from '@angular/router';
import {DataService} from '../services/data.service';
@Component({
selector: 'app-help',
templateUrl: './help.component.html',
styleUrls: ['./help.component.scss']
})
export class HelpComponent implements OnInit {
route = '';
constructor(
private router: Router,
public d: DataService
) { }
ngOnInit(): void {
this.route = this.router.url.replace(/\/[0-9a-f]{24}/, ''); // remove ids
console.log(this.route);
}
}

View File

@ -0,0 +1,65 @@
<h2>Models</h2>
<rb-icon-button icon="add" mode="primary" (click)="newModel = !newModel" class="space-below">New model</rb-icon-button>
<form *ngIf="newModel" #modelForm="ngForm">
<rb-form-input name="group" label="group" appValidate="string" required [(ngModel)]="modelGroup" #groupInput="ngModel"
[rbFormInputAutocomplete]="autocomplete.bind(this, groups)"
[rbDebounceTime]="0" [rbInitialOpen]="true">
<ng-template rbFormValidationMessage="failure">{{groupInput.errors.failure}}</ng-template>
<ng-template rbFormValidationMessage="required">Cannot be empty</ng-template>
</rb-form-input>
<rb-form-input name="name" label="name" appValidate="string" required [(ngModel)]="model.name" #nameInput="ngModel">
<ng-template rbFormValidationMessage="failure">{{nameInput.errors.failure}}</ng-template>
<ng-template rbFormValidationMessage="required">Cannot be empty</ng-template>
</rb-form-input>
<rb-form-input name="label" label="label" appValidate="string" [(ngModel)]="model.label" #labelInput="ngModel">
<ng-template rbFormValidationMessage="failure">{{labelInput.errors.failure}}</ng-template>
</rb-form-input>
<rb-form-input name="url" label="URL" appValidate="url" required [(ngModel)]="model.url" #urlInput="ngModel">
<ng-template rbFormValidationMessage="failure">{{urlInput.errors.failure}}</ng-template>
<ng-template rbFormValidationMessage="required">Cannot be empty</ng-template>
</rb-form-input>
<rb-icon-button icon="save" mode="primary" type="submit" [disabled]="!modelForm.form.valid" (click)="saveModel()">
Save model
</rb-icon-button>
</form>
<rb-table class="space-above">
<tr>
<th>Name</th>
<th>Label</th>
<th>URL</th>
<th></th>
<th></th>
</tr>
<ng-container *ngFor="let group of d.arr.modelGroups">
<tr><th>{{group.group}}</th><th></th><th></th><th></th><th></th></tr>
<tr *ngFor="let modelItem of group.models">
<td>{{modelItem.name}}</td>
<td>{{modelItem.label}}</td>
<td>{{modelItem.url}}</td>
<td>
<span class="rb-ic rb-ic-edit clickable"
(click)="modelGroup = group.group;
oldModelGroup = group.group;
oldModelName = modelItem.name;
model = modelItem;
newModel = true;">
</span>
</td>
<td>
<span class="rb-ic rb-ic-delete clickable"
(click)="deleteModel(group.group, modelItem.name, modalDeleteConfirm)"></span>
</td>
</tr>
</ng-container>
</rb-table>
<ng-template #modalDeleteConfirm>
<rb-alert alertTitle="Are you sure?" type="danger" okBtnLabel="Delete model" cancelBtnLabel="Cancel">
Do you really want to delete this model?
</rb-alert>
</ng-template>

View File

@ -0,0 +1,25 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ModelTemplatesComponent } from './model-templates.component';
describe('ModelTemplatesComponent', () => {
let component: ModelTemplatesComponent;
let fixture: ComponentFixture<ModelTemplatesComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ ModelTemplatesComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ModelTemplatesComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,74 @@
import { Component, OnInit } from '@angular/core';
import {DataService} from '../services/data.service';
import {ModelItemModel} from '../models/model-item.model';
import {ApiService} from '../services/api.service';
import {AutocompleteService} from '../services/autocomplete.service';
import {ModalService} from '@inst-iot/bosch-angular-ui-components';
@Component({
selector: 'app-model-templates',
templateUrl: './model-templates.component.html',
styleUrls: ['./model-templates.component.scss']
})
export class ModelTemplatesComponent implements OnInit {
newModel = false;
modelGroup = '';
oldModelGroup = '';
oldModelName = '';
model = new ModelItemModel().models[0];
groups = [];
constructor(
private api: ApiService,
public autocomplete: AutocompleteService,
public d: DataService,
private modal: ModalService
) { }
ngOnInit(): void {
this.loadGroups();
}
loadGroups() {
delete this.d.arr.modelGroups;
this.d.load('modelGroups', () => {
this.groups = this.d.arr.modelGroups.map(e => e.group);
});
}
saveModel() {
if (this.modelGroup !== this.oldModelGroup) { // group was changed, delete model in old group
this.deleteModel(this.oldModelGroup, this.oldModelName);
}
this.api.post('/model/' + this.modelGroup, this.model, () => {
this.newModel = false;
this.loadGroups();
this.modelGroup = '';
this.oldModelGroup = '';
this.oldModelName = '';
this.model = new ModelItemModel().models[0];
this.groups = this.d.arr.modelGroups.map(e => e.group);
});
}
deleteModel(group, name, modal = null) {
new Promise(resolve => {
if (modal) {
this.modal.open(modal).then(result => {
resolve(result);
});
}
else {
resolve(true);
}
}).then(res => {
if (res) {
this.api.delete(`/model/${group}/${name}`, () => {
this.loadGroups();
});
}
});
}
}

View File

@ -0,0 +1,7 @@
import { ModelItemModel } from './model-item.model';
describe('ModelItemModel', () => {
it('should create an instance', () => {
expect(new ModelItemModel()).toBeTruthy();
});
});

View File

@ -0,0 +1,10 @@
import {BaseModel} from './base.model';
export class ModelItemModel extends BaseModel {
group = '';
models = [{
name: '',
url: '',
label: ''
}];
}

View File

@ -7,10 +7,4 @@ export class TemplateModel extends BaseModel {
version = 0;
first_id: IdModel = null;
parameters: {name: string, range: {[prop: string]: any}, rangeString?: string}[] = [];
deserialize(input: any): this {
Object.assign(this, input);
return this;
}
}

View File

@ -1,12 +1,53 @@
<h2>Prediction</h2>
<h4 *ngIf="result !== '' || loading" [@inOut]>
Result: {{result}}<rb-loading-spinner *ngIf="loading"></rb-loading-spinner>
</h4>
<rb-tab-panel (tabChanged)="groupChange($event)">
<ng-container *ngFor="let group of d.arr.modelGroups; index as i">
<div *rbTabPanelItem="group.group; id: i"></div>
</ng-container>
</rb-tab-panel>
<rb-form-file name="spectrum-upload" label="spectrum file" maxSize="10000000" class="space-below"
(ngModelChange)="fileToArray($event)" placeholder="Select file or drag and drop" dragDrop ngModel>
</rb-form-file>
<rb-form-select label="Model" (change)="result = undefined" [(ngModel)]="activeModelIndex">
<option *ngFor="let model of activeGroup.models; index as i" [value]="i">{{model.name}}</option>
</rb-form-select>
<div *ngIf="result" class="result" [@inOut]>
<ng-container *ngIf="multipleSamples; else singleSampleResult">
<h4 *ngFor="let prediction of result.predictions; index as i">
{{spectrumNames[i]}}: {{prediction}}&nbsp;{{activeGroup.models[activeModelIndex].label}}
</h4>
</ng-container>
<ng-template #singleSampleResult>
<h4>
Average result: {{result.meanPrediction}}&nbsp;{{activeGroup.models[activeModelIndex].label}},
standard deviation: {{result.std}}
</h4>
<a href="javascript:" class="rb-details-toggle" rbDetailsToggle #triggerDetails="rbDetailsToggle">Details</a>
<div *ngIf="triggerDetails.open" class="space-below">
<p *ngFor="let prediction of result.predictions; index as i">
{{spectrumNames[i]}}: {{prediction}}&nbsp;{{activeGroup.models[activeModelIndex].label}}
</p>
</div>
</ng-template>
</div>
<div class="file-input space-below">
<rb-form-file name="spectrum-upload" label="spectrum file" maxSize="10000000" class="space-below" multiple
(ngModelChange)="fileToArray($event)" placeholder="Select file or drag and drop" dragDrop ngModel>
</rb-form-file>
<rb-loading-spinner *ngIf="loading; else predictButton"></rb-loading-spinner>
<ng-template #predictButton>
<rb-icon-button icon="forward-right" mode="primary" *ngIf="spectrumNames.length; else placeholder"
(click)="loadPrediction()">
Predict
</rb-icon-button>
<ng-template #placeholder><div></div></ng-template>
</ng-template>
<rb-form-checkbox name="multiple-samples" [(ngModel)]="multipleSamples">
multiple samples
</rb-form-checkbox>
</div>
<div class="dpt-chart">
<canvas baseChart

View File

@ -2,3 +2,17 @@
max-width: 800px;
margin: 0 auto;
}
.file-input {
display: grid;
grid-template-columns: 1fr auto;
grid-column-gap: 1rem;
}
.result {
margin: 30px 0;
h4 {
margin-bottom: 1rem;
}
}

View File

@ -2,6 +2,15 @@ import { Component, OnInit } from '@angular/core';
import {ChartOptions} from 'chart.js';
import {ApiService} from '../services/api.service';
import {animate, style, transition, trigger} from '@angular/animations';
import cloneDeep from 'lodash/cloneDeep';
import {DataService} from '../services/data.service';
import {ModelItemModel} from '../models/model-item.model';
interface PredictionResult {
meanPrediction: string;
std: string;
predictions: string[];
}
@Component({
selector: 'app-prediction',
@ -24,11 +33,16 @@ import {animate, style, transition, trigger} from '@angular/animations';
})
export class PredictionComponent implements OnInit {
readonly predictionUrl = 'https://definma-model-test.apps.de1.bosch-iot-cloud.com/predict';
result = '';
result: PredictionResult;
loading = false;
activeGroup: ModelItemModel = new ModelItemModel();
activeModelIndex = 0;
multipleSamples = false; // if true, spectra belong to different samples, otherwise multiple spectra from the same sample are given
spectrumNames: string[] = [];
spectrum: string[][] = [[]];
chart = [{
flattenedSpectra = [];
chart = [];
readonly chartInit = {
data: [],
label: 'Spectrum',
showLine: true,
@ -36,7 +50,7 @@ export class PredictionComponent implements OnInit {
pointRadius: 0,
borderColor: '#00a8b0',
borderWidth: 2
}];
};
readonly chartOptions: ChartOptions = {
scales: {
xAxes: [{ticks: {min: 400, max: 4000, stepSize: 400, reverse: true}}],
@ -50,25 +64,53 @@ export class PredictionComponent implements OnInit {
};
constructor(
private api: ApiService
) { }
private api: ApiService,
public d: DataService
) {
this.chart[0] = cloneDeep(this.chartInit);
}
ngOnInit(): void {
this.d.load('modelGroups', () => {
this.activeGroup = this.d.arr.modelGroups[0];
});
}
fileToArray(files) {
const fileReader = new FileReader();
fileReader.onload = () => {
this.spectrum = fileReader.result.toString().split('\r\n').map(e => e.split(','));
this.loading = true;
this.api.post<{result: string}>(this.predictionUrl, this.spectrum, data => {
this.result = data.result;
this.loading = false;
});
this.chart[0].data = this.spectrum.map(e => ({x: parseFloat(e[0]), y: parseFloat(e[1])}));
console.log(this.chart);
};
fileReader.readAsText(files[0]);
this.loading = true;
this.flattenedSpectra = [];
this.chart = [];
let load = files.length;
this.spectrumNames = files.map(e => e.name);
for (const i in files) {
if (files.hasOwnProperty(i)) {
const fileReader = new FileReader();
fileReader.onload = () => {
this.spectrum = fileReader.result.toString().split('\r\n').map(e => e.split(',').map(el => parseFloat(el))) as any;
this.flattenedSpectra[i] = {labels: this.spectrum.map(e => e[0]), values: this.spectrum.map(e => e[1])};
this.chart[i] = cloneDeep(this.chartInit);
this.chart[i].data = this.spectrum.map(e => ({x: parseFloat(e[0]), y: parseFloat(e[1])}));
load --;
if (load <= 0) {
this.loadPrediction();
}
};
fileReader.readAsText(files[i]);
}
}
}
loadPrediction() {
this.loading = true;
console.log(this.activeModelIndex);
this.api.post<PredictionResult>(this.activeGroup.models[this.activeModelIndex].url, this.flattenedSpectra, data => {
this.result = data;
this.loading = false;
});
}
groupChange(index) {
this.activeGroup = this.d.arr.modelGroups[index];
this.result = undefined;
}
}

View File

@ -230,8 +230,6 @@ export class SampleComponent implements OnInit, AfterContentChecked {
if (formReady) { // fields are ready, do validation
this.checkFormAfterInit = false;
Object.keys(this.cmForm.form.controls).forEach(field => {
console.log(field);
console.log(this.cmForm.form.get(field).valid);
this.cmForm.form.get(field).updateValueAndValidity();
});
}
@ -269,7 +267,6 @@ export class SampleComponent implements OnInit, AfterContentChecked {
}
new Promise<void>(resolve => {
if (this.newMaterial) { // save material first if new one exists
console.log(this.material);
this.material.numbers = this.material.numbers.filter(e => e !== '');
this.api.post<MaterialModel>('/material/new', this.material.sendFormat(), data => {
this.d.arr.materials.push(data); // add material to data
@ -379,7 +376,6 @@ export class SampleComponent implements OnInit, AfterContentChecked {
this.generatedSamples[gIndex].measurements.push(
new MeasurementModel(this.d.latest.measurementTemplates.find(e => e.name === 'spectrum')._id)
);
console.log(this.d.latest.measurementTemplates.find(e => e.name === 'spectrum'));
if (!this.charts[gIndex]) { // add array if there are no charts yet
this.charts[gIndex] = [];
}
@ -402,7 +398,6 @@ export class SampleComponent implements OnInit, AfterContentChecked {
}
fileToArray(files, gIndex, mIndex, parameter) {
console.log(files);
for (const i in files) {
if (files.hasOwnProperty(i)) {
const fileReader = new FileReader();
@ -494,7 +489,6 @@ export class SampleComponent implements OnInit, AfterContentChecked {
this.api.get<{ _id: string, number: string }[]>(
'/samples?status[]=validated&status[]=new&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));

View File

@ -105,18 +105,21 @@
</ng-container>
</div>
</div>
<rb-icon-button icon="forward-right" mode="primary" (click)="loadSamples({firstPage: true})">
Apply filters
</rb-icon-button>
</form>
<rb-icon-button icon="forward-right" mode="primary" (click)="loadSamples({firstPage: true})">
Apply filters
</rb-icon-button>
</rb-accordion-body>
</rb-accordion>
<ng-container *ngTemplateOutlet="paging"></ng-container>
<rb-loading-spinner class="samples-loading" *ngIf="loading"></rb-loading-spinner>
<div class="samples-loading" *ngIf="loading">
<rb-loading-spinner></rb-loading-spinner>
<div>Loading...</div>
</div>
<div class="download space-below" *ngIf="login.isLevel.dev">
<rb-icon-button class="space-right" icon="download" mode="secondary" [rbModal]="linkModal">

View File

@ -237,7 +237,19 @@ textarea.linkmodal {
.samples-loading {
float: left;
transform: scale(0.5);
display: grid;
grid-template-columns: auto auto;
grid-template-rows: 1fr auto 1fr;
rb-loading-spinner {
grid-row: span 3;
transform: scale(0.5);
}
& > div {
grid-column: 2 / 3;
grid-row: 2 / 3;
}
}
.reset-preferences {

View File

@ -5,6 +5,7 @@ import {Observable} from 'rxjs';
import {ErrorComponent} from '../error/error.component';
import {ModalService} from '@inst-iot/bosch-angular-ui-components';
// TODO: find solution when client wants to visit subpage but is not logged in to redirect to login without showing request failed errors
@Injectable({
providedIn: 'root'

View File

@ -4,6 +4,7 @@ import {ApiService} from './api.service';
import {MaterialModel} from '../models/material.model';
import {BaseModel} from '../models/base.model';
import {UserModel} from '../models/user.model';
import {ModelItemModel} from '../models/model-item.model';
@Injectable({
providedIn: 'root'
@ -15,14 +16,15 @@ export class DataService {
) { }
private collectionMap = {
materials: {path: '/materials?status=all', model: MaterialModel, type: 'array'},
materialSuppliers: {path: '/material/suppliers', model: null, type: 'array'},
materialGroups: {path: '/material/groups', model: null, type: 'array'},
materials: {path: '/materials?status=all', model: MaterialModel, type: 'idArray'},
materialSuppliers: {path: '/material/suppliers', model: null, type: 'idArray'},
materialGroups: {path: '/material/groups', model: null, type: 'idArray'},
materialTemplates: {path: '/template/materials', model: TemplateModel, type: 'template'},
measurementTemplates: {path: '/template/measurements', model: TemplateModel, type: 'template'},
conditionTemplates: {path: '/template/conditions', model: TemplateModel, type: 'template'},
sampleNotesFields: {path: '/sample/notes/fields', model: TemplateModel, type: 'array'},
users: {path: '/users', model: UserModel, type: 'array'},
sampleNotesFields: {path: '/sample/notes/fields', model: TemplateModel, type: 'idArray'},
users: {path: '/users', model: UserModel, type: 'idArray'},
modelGroups: {path: '/model/groups', model: ModelItemModel, type: 'array'},
user: {path: '/user', model: UserModel, type: 'string'},
userKey: {path: '/user/key', model: BaseModel, type: 'string'}
};
@ -32,6 +34,8 @@ export class DataService {
id: {[key: string]: {[id: string]: any}} = {}; // data in format _id: data
d: {[key: string]: any} = {}; // data not in array format
contact = 'dominic.lingenfelser@bosch.com';
load(collection, f = () => {}) { // load data
if (this.arr[collection]) { // data already loaded
f();
@ -41,20 +45,8 @@ export class DataService {
if (this.collectionMap[collection].type !== 'string') { // array data
this.arr[collection] = data
.map(e => this.collectionMap[collection].model ? new this.collectionMap[collection].model().deserialize(e) : e);
this.idReload(collection);
if (this.collectionMap[collection].type === 'template') {
const tmpTemplates = {};
this.arr[collection].forEach(template => {
if (tmpTemplates[template.first_id]) { // already found another version
if (template.version > tmpTemplates[template.first_id].version) {
tmpTemplates[template.first_id] = template;
}
}
else {
tmpTemplates[template.first_id] = template;
}
});
this.latest[collection] = Object.values(tmpTemplates);
if (this.collectionMap[collection].type === 'idArray' || this.collectionMap[collection].type === 'template') {
this.idReload(collection);
}
}
else { // not array data
@ -67,5 +59,19 @@ export class DataService {
idReload(collection) {
this.id[collection] = this.arr[collection].reduce((s, e) => {s[e._id] = e; return s; }, {});
if (this.collectionMap[collection].type === 'template') {
const tmpTemplates = {};
this.arr[collection].forEach(template => {
if (tmpTemplates[template.first_id]) { // already found another version
if (template.version > tmpTemplates[template.first_id].version) {
tmpTemplates[template.first_id] = template;
}
}
else {
tmpTemplates[template.first_id] = template;
}
});
this.latest[collection] = Object.values(tmpTemplates);
}
}
}

View File

@ -103,6 +103,14 @@ export class ValidationService {
return {ok: true, error: ''};
}
url(data) {
const {ignore, error} = Joi.string().uri().validate(data);
if (error) {
return {ok: false, error: `must be a valid URL`};
}
return {ok: true, error: ''};
}
unique(data, list) {
const {ignore, error} = Joi.string().allow('').invalid(...list.map(e => e.toString())).validate(data);
if (error) {