repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
MauroDataMapper/mdm-ui
src/app/shared/catalogue-item-properties/catalogue-item-properties.component.ts
/* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, Input, OnChanges, SimpleChanges } from '@angular/core'; import { Branchable, CatalogueItem, CatalogueItemDomainType, DataModelDetail, Finalisable, Historical, ModelableDetail, SecurableModel, Versionable } from '@maurodatamapper/mdm-resources'; export type CatalogueItemPropertiesType = CatalogueItem & Partial<ModelableDetail> & Partial<SecurableModel> & Partial<Finalisable> & Partial<Versionable> & Partial<Branchable> & Partial<Historical>; @Component({ selector: 'mdm-catalogue-item-properties', templateUrl: './catalogue-item-properties.component.html', styleUrls: ['./catalogue-item-properties.component.scss'] }) export class CatalogueItemPropertiesComponent implements OnChanges { @Input() item: CatalogueItemPropertiesType; itemType: string; constructor() { } ngOnChanges(changes: SimpleChanges): void { if (changes.item) { this.setItemType(); } } private setItemType() { if (this.item.domainType === CatalogueItemDomainType.DataModel) { const dataModel = this.item as DataModelDetail; this.itemType = dataModel.type; return; } switch (this.item.domainType) { case CatalogueItemDomainType.CodeSet: this.itemType = 'Code Set'; break; case CatalogueItemDomainType.ReferenceDataModel: this.itemType = 'Reference Data Model'; break; default: this.itemType = this.item.domainType; break; } } }
MauroDataMapper/mdm-ui
src/app/pipes/join-array.pipe.ts
/* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import {Pipe, PipeTransform} from '@angular/core'; @Pipe({name: 'joinArray'}) export class JoinArrayPipe implements PipeTransform { transform(values: any[], delimiter = '', propertyName?: string) { if (!values || values.length === 0) { return ''; } if (propertyName) { return values.map(v => v[propertyName]).join(delimiter); } return values.join(delimiter); } }
MauroDataMapper/mdm-ui
src/app/utility/mc-select/mc-select.component.ts
<gh_stars>1-10 /* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, OnInit, Input, ViewChildren, ViewChild, Inject, ContentChild, TemplateRef, AfterViewInit, Output, EventEmitter, ChangeDetectorRef, HostListener } from '@angular/core'; import { ValidatorService } from '@mdm/services/validator.service'; import { DOCUMENT } from '@angular/common'; @Component({ selector: 'mdm-select', templateUrl: './mc-select.component.html', styleUrls: ['./mc-select.component.sass'], host: { '(click)': 'onClick($event)' } // TODO - check if this is needed }) export class McSelectComponent implements OnInit, AfterViewInit { @Output() paginationChanged = new EventEmitter<any>(); @Output() defaultValueChanged = new EventEmitter<any>(); @Input() loadAllOnClick: boolean; @Input() acceptTypedInput: boolean; @Input() minInputLength: number; @Input() idProperty: any; @Input() displayProperty: any; @Input() searchProperty: any; @Input() valueType: any; @Input() width: any; @Input() showAllStaticValues: any; @Input() onTextUpdated: any; @Input() multiSelect: boolean; @Input() staticValues: any; @Input() loadDynamicValues: any; @Input() hasError: any; @Input() itemTemplate: any; @Input() doNotCloseOnSelect: boolean | false; @Input() defaultPlaceholder: any; @ViewChildren('mcSelectItem') elements; @ViewChild('input', { static: false }) input; @ViewChild('mcSelect2', { static: false }) mcSelect2; @ViewChild('mcSelectHolder', { static: false }) mcSelectHolder; @ContentChild('lineContent', { static: true }) lineContentTmpl: TemplateRef<any>; @Output() selectEvent = new EventEmitter<any>(); @Output() recordChanged = new EventEmitter<any>(); recordVal: any; selectedValue: any[]; wasInside = false; inputText: any; defaultVal: any; paginationVal: McSelectPagination; loadingDynamicData: boolean; processing: boolean; show: boolean; showCaret: boolean; displayValues: any[]; inputStyle: any; holderStyle: any; constructor(private changeRef: ChangeDetectorRef, private validator: ValidatorService, @Inject(DOCUMENT) private document: Document) { } @HostListener('document:click') clickout() { this.show = false; } @Input() get pagination() { return this.paginationVal; } set pagination(val) { this.paginationVal = val; this.paginationChanged.emit(val); } @Input() get defaultValue() { return this.defaultVal; } set defaultValue(val) { this.defaultVal = val; } @Input() get record() { return this.recordVal; } set record(val) { this.recordVal = val; this.recordChanged.emit(val); } ngOnInit() { this.setDefaultValue(); this.pagination = { offset: undefined, count: undefined }; this.showCaret = true; this.inputStyle = { width: this.width, padding: '6px 40px 6px 12px' }; this.holderStyle = { width: this.width, 'background-color': '#FFF' }; if (this.input !== undefined) { this.input.nativeElement.setAttribute('placeholder', (this.defaultPlaceholder ? this.defaultPlaceholder : 'Search...')); } } ngAfterViewInit() { this.input.nativeElement.setAttribute('placeholder', (this.defaultPlaceholder ? this.defaultPlaceholder : 'Search...')); } onScroll(event) { if (parseInt(event.target.scrollTop, 10) + parseInt(event.target.clientHeight, 10) + 300 >= event.target.scrollHeight) { this.loadMore(); } } setDefaultValue() { if (this.defaultValue) { if (this.multiSelect === true) { this.selectedValue = this.defaultValue; } else { // if it is an object if (typeof this.defaultValue === 'object') { this.selectedValue = this.defaultValue; const value = this.validator.getProperty(this.selectedValue, this.displayProperty); this.inputText = value; // scope.selectedValue[scope.displayProperty]; } else { // if it is not an object, create a default object for it this.inputText = this.defaultValue; this.selectedValue = []; this.selectedValue[this.idProperty] = -1; this.selectedValue[this.searchProperty] = this.inputText; } } } } onClick(event) { if (this.processing) { return; } // if clicking on input if (event.target === this.input.nativeElement || event.target === this.mcSelect2.nativeElement) { if (this.valueType === 'static') { // load all values this.displayValues = this.staticValues; this.input.nativeElement.focus(); this.show = true; event.stopPropagation(); } else { this.input.nativeElement.focus(); this.showCaret = false; this.input.nativeElement.setAttribute('placeholder', (this.defaultPlaceholder ? this.defaultPlaceholder : 'Search...')); if (this.loadAllOnClick) { this.inputText = ''; this.textUpdated(); } } } else { this.showCaret = true; this.input.nativeElement.setAttribute('placeholder', (this.defaultPlaceholder ? this.defaultPlaceholder : '')); if (this.multiSelect === true) { // clear the input this.inputText = ''; if (this.input.val !== undefined) { this.input.val(''); } this.show = false; } else { // if we have selected element, show it if (this.selectedValue && this.selectedValue[this.idProperty] !== -1) { const value = this.validator.getProperty(this.selectedValue, this.displayProperty); this.input.nativeElement.value = value; } else if (this.inputText) { if (this.acceptTypedInput && this.inputText.trim().length !== 0) { this.input.nativeElement.value = this.inputText; this.recordChanged.emit(this.inputText); } else { // clear the input this.inputText = ''; this.input.nativeElement.value = ''; } } else { // clear the input this.inputText = ''; this.input.nativeElement.value = ''; } this.show = false; } } } onInputKeyDown(event) { // if Escape is pressed, then close the div if (event.keyCode === 27) { this.show = false; } else if (event.keyCode === 40) { // down arrow key if (this.displayValues && this.displayValues.length === 0) { return false; } const currentElements = this.mcSelectHolder.nativeElement.querySelectorAll('#current'); if (currentElements.length > 0) { // eslint-disable-next-line @typescript-eslint/restrict-plus-operands const nextElement = this.elements._results[this.elements._results.findIndex(x => x.nativeElement === currentElements[0]) + 1]; if (nextElement.length === 0) { return; } currentElements.forEach(x => { x.id = ''; x.className = 'mcSelectItem'; }); nextElement.nativeElement.id = 'current'; nextElement.nativeElement.className = 'mcSelectItem current'; const elPosition = this.elementPositionInHolder(nextElement); const elHeight = parseInt(nextElement.nativeElement.offsetHeight, 10); const holderHeight = this.mcSelectHolder.nativeElement.offsetHeight; if ((elPosition + elHeight) > holderHeight) { this.mcSelectHolder.nativeElement.scrollTop = elPosition; } } else { this.elements._results[0].nativeElement.id = 'current'; this.elements._results[0].nativeElement.className = 'mcSelectItem current'; } } else if (event.keyCode === 38) { // UP arrow key if (this.displayValues && this.displayValues.length === 0) { return false; } const currentElements = this.mcSelectHolder.nativeElement.querySelectorAll('.current'); if (currentElements.length > 0) { const prevElement = this.elements._results[this.elements._results.findIndex(x => x.nativeElement === currentElements[0]) - 1]; if (prevElement.length === 0) { return; } currentElements.forEach(x => { x.id = ''; x.className = 'mcSelectItem'; }); prevElement.nativeElement.id = 'current'; prevElement.nativeElement.className = 'mcSelectItem current'; const elPosition = this.elementPositionInHolder(prevElement); const holderScrollTop = this.mcSelectHolder.nativeElement.scrollTop; if (elPosition < holderScrollTop) { this.mcSelectHolder.nativeElement.scrollTop = elPosition; } } else { this.elements._result[0].nativeElement.className = 'mcSelectItem current'; } } else if (event.keyCode === 13) { const currentElement = this.mcSelectHolder.nativeElement.querySelectorAll('.current'); currentElement[0].click(); this.show = false; } } elementPositionInHolder(el) { let fromTop = 0; const indexOfElement = this.elements._results.findIndex(x => x === el); this.elements._results.slice(0, indexOfElement).forEach((prev) => { fromTop += parseInt(prev.nativeElement.clientHeight, 10) + 10; // 10: [3(padding) + 2(margin)]*2(up and bottom) }); return fromTop; } onElementSelect(selectedElement) { if (this.multiSelect === true) { this.selectedValue = this.selectedValue || []; // if it doesn't exist, then add it let found = false; for (let i = 0; i < this.selectedValue.length && !found; i++) { if (selectedElement[this.idProperty] === this.selectedValue[i][this.idProperty]) { found = true; } } if (!found) { this.selectedValue.push(selectedElement); } } else { this.selectedValue = selectedElement; const value = this.validator.getProperty(this.selectedValue, this.displayProperty); this.inputText = value; } if (this.selectEvent) { this.selectEvent.emit([this.selectedValue, this.record]); } } textUpdated() { if (this.onTextUpdated) { this.onTextUpdated(this.inputText, this.record); } this.pagination = { offset: undefined, count: undefined }; let searchText = this.inputText; if (this.minInputLength && this.inputText.trim().length < this.minInputLength) { searchText = ''; } // Don't search on the empty string if (searchText !== '') { this.filterValues(searchText).then((result) => { this.show = true; this.displayValues = Object.assign([], result); if (this.acceptTypedInput) { const selected = {}; selected[this.searchProperty] = this.inputText; this.recordChanged.emit(this.inputText); if (this.idProperty) { selected[this.idProperty] = -1; } this.onElementSelect(selected); } }); } } filterValues(inputValue) { const found = []; const p = new Promise((resolve) => { if (this.valueType === 'static') { if (inputValue.trim().length === 0) { resolve(this.staticValues); } if (this.staticValues !== undefined) { this.staticValues.forEach((staticValue) => { if (staticValue[this.searchProperty].toLowerCase().indexOf(inputValue.toLowerCase()) > -1) { found.push(staticValue); } }); resolve(found); } else { resolve([]); } } else if (this.valueType === 'dynamic') { if ((inputValue && inputValue.trim().length === 0) || !this.loadDynamicValues) { resolve([]); } let loadAll = false; if (!inputValue && this.loadAllOnClick) { loadAll = true; } const query = this.loadDynamicValues(inputValue, loadAll, this.pagination.offset, this.pagination.limit); this.loadingDynamicData = true; query.subscribe((result) => { this.pagination.count = 100; // if (result.body.count != null && result.body.count !== undefined) { // } if(result.body.items) { resolve(result.body.items); } if(result.body.rows) { resolve(result.body.rows); } this.loadingDynamicData = false; }, () => { this.loadingDynamicData = false; }); } }); return p; } loadMore() { // if dynamic and is not loading // if it's loading, so do not load it again if (this.valueType === 'dynamic' && this.loadingDynamicData === false) { const loadedSoFar = this.pagination.offset + this.pagination.limit; console.log(loadedSoFar, this.pagination.count); if (loadedSoFar > 0 && this.pagination.count <= loadedSoFar) { return; } const inputValue = this.inputText; this.loadingDynamicData = true; this.pagination.offset += this.pagination.limit; this.changeRef.detectChanges(); console.log(this.pagination); this.loadDynamicValues(inputValue, false, this.pagination.offset, this.pagination.limit).subscribe((result) => { // append to this.displayValues if(result.body.items) { this.displayValues = this.displayValues.concat(result.body.items); } if(result.body.rows) { this.displayValues = this.displayValues.concat(result.body.rows); } this.loadingDynamicData = false; }, () => { this.loadingDynamicData = false; }); } } remove(event, element?) { if (this.processing) { return; } if (this.multiSelect) { const found = false; for (let i = 0; i < this.selectedValue.length && !found; i++) { if (element[this.idProperty] === this.selectedValue[i][this.idProperty]) { this.selectedValue.splice(i, 1); break; } } if (this.selectEvent) { this.selectEvent.emit([this.selectedValue, this.record]); } } else { this.selectedValue = null; this.inputText = ''; this.input.nativeElement.value = ''; if (this.selectEvent) { this.selectEvent.emit([null, this.record]); } } event.stopPropagation(); return false; } getDisplayValue = (element, displayProperty) => { if (element) { return this.validator.getProperty(element, displayProperty); } }; itemClicked(event, item) { if (this.doNotCloseOnSelect) { event.preventDefault(); event.stopPropagation(); this.show = true; } else { this.show = false; } this.onElementSelect(item); this.loadingDynamicData = false; } } export interface McSelectPagination { offset?: number; limit?: number; count?: number; max?: number; }
MauroDataMapper/mdm-ui
src/app/wizards/dataType/data-type-main/data-type-main.component.ts
<reponame>MauroDataMapper/mdm-ui<gh_stars>1-10 /* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, OnInit, ChangeDetectorRef } from '@angular/core'; import { StateService } from '@uirouter/core'; import { StateHandlerService } from '@mdm/services/handlers/state-handler.service'; import { MdmResourcesService } from '@mdm/modules/resources'; import { MessageHandlerService } from '@mdm/services/utility/message-handler.service'; import { Step } from '@mdm/model/stepModel'; import { DataTypeStep1Component } from '../data-type-step1/data-type-step1.component'; import { DataTypeStep2Component } from '../data-type-step2/data-type-step2.component'; import { Title } from '@angular/platform-browser'; import { CatalogueItemDomainType, DataModelDetailResponse, DataType, Uuid } from '@maurodatamapper/mdm-resources'; import { ElementTypesService } from '@mdm/services'; @Component({ selector: 'mdm-data-type-main', templateUrl: './data-type-main.component.html', styleUrls: ['./data-type-main.component.sass'], }) export class DataTypeMainComponent implements OnInit { parentDataModelId: Uuid; steps: Step[] = []; processing: boolean; isProcessComplete: boolean; model = { createType: 'new', copyFromDataModel: [], isValid: false, parent: { id: '', }, parentDataModel: { id: '' }, label: '', description: '', organisation: '', domainType: CatalogueItemDomainType.PrimitiveType, metadata: [], enumerationValues: [], classifiers: [], referencedDataType: { id: '' }, referencedModel: { id: '', domainType: '' }, referencedDataClass: { id: '' }, isProcessComplete: false, }; constructor( private stateService: StateService, private stateHandler: StateHandlerService, private resources: MdmResourcesService, private messageHandler: MessageHandlerService, private title: Title, private changeRef: ChangeDetectorRef, private elementTypes: ElementTypesService ) { } ngOnInit() { // tslint:disable-next-line: deprecation this.parentDataModelId = this.stateService.params.parentDataModelId; if (!this.parentDataModelId) { this.stateHandler.NotFound({ location: false }); return; } const step1 = new Step(); step1.title = 'Add Data Type'; step1.component = DataTypeStep1Component; step1.scope = this; step1.hasForm = true; step1.invalid = false; const step2 = new Step(); step2.title = 'Data Type Details'; step2.component = DataTypeStep2Component; step2.scope = this; step2.invalid = true; this.resources.dataModel.get(this.parentDataModelId).subscribe((result: DataModelDetailResponse) => { result.body.breadcrumbs = []; result.body.breadcrumbs.push(Object.assign({}, result.body)); this.model.parent.id = result.body.id || ''; this.steps.push(step1); this.steps.push(step2); this.changeRef.detectChanges(); }); this.title.setTitle('New Data Type'); } cancelWizard() { this.stateHandler.GoPrevious(); } save = () => { if (this.model.createType === 'new') { this.saveNewDataType(); } else { this.saveCopiedDataTypes(); } }; fireChanged = (tab: any) => { for (let i = 0; i < this.steps.length; i++) { const step: Step = this.steps[i]; if (i === tab.selectedIndex) { if (step.compRef) { if (step.compRef.instance.onLoad !== undefined) { step.compRef.instance.onLoad(); } step.active = true; } } else { step.active = false; } } }; saveNewDataType() { const domainType = this.elementTypes.isModelDataType(this.model.domainType) ? CatalogueItemDomainType.ModelDataType : this.model.domainType; const resource: DataType = { domainType, label: this.model.label, description: this.model.description, classifiers: this.model.classifiers.map((cls) => { return { id: cls.id }; }) }; if (domainType === CatalogueItemDomainType.ModelDataType) { resource.modelResourceDomainType = this.model.referencedModel?.domainType; resource.modelResourceId = this.model.referencedModel?.id; } else { resource.organisation = this.model.organisation; resource.referenceDataType = { id: this.model.referencedDataType ? this.model.referencedDataType.id : null }; resource.referenceClass = { id: this.model.referencedDataClass ? this.model.referencedDataClass.id : null }; resource.enumerationValues = this.model.enumerationValues.map((m) => { return { key: m.key, value: m.value, category: m.category }; }); resource.metadata = this.model.metadata.map((m) => { return { key: m.key, value: m.value, namespace: m.namespace }; }); } this.resources.dataType.save(this.model.parent.id, resource).subscribe(response => { this.messageHandler.showSuccess('Data Type saved successfully.'); this.stateHandler.Go( 'DataType', { dataModelId: response.body.model, id: response.body.id }, { reload: true, location: true } ); }, error => { this.messageHandler.showError('There was a problem saving the Data Type.', error); }); } saveCopiedDataTypes = () => { this.steps[1].compRef.instance.saveCopiedDataTypes(); }; }
MauroDataMapper/mdm-ui
src/app/services/handlers/security-handler.model.ts
<reponame>MauroDataMapper/mdm-ui<filename>src/app/services/handlers/security-handler.model.ts /* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { HttpErrorResponse } from '@angular/common/http'; import { MdmResourcesError } from '@mdm/modules/resources/mdm-resources.models'; export enum SignInErrorType { UnknownError, InvalidCredentials, AlreadySignedIn } /** * Represents an error that occurred during sign-in. */ export class SignInError extends MdmResourcesError { /** * The type of sign-in error that occurered, represented by the `SignInErrorType` enum constants. */ type: SignInErrorType; constructor(response: HttpErrorResponse) { super(response); switch (response.status) { case 401: this.type = SignInErrorType.InvalidCredentials; break; case 409: this.type = SignInErrorType.AlreadySignedIn; break; default: this.type = SignInErrorType.UnknownError; break; } } } /** * Represents an error that occurred during a check for an authenticated session. */ export class AuthenticatedSessionError extends MdmResourcesError { readonly invalidated: boolean; constructor(response: HttpErrorResponse) { super(response); this.invalidated = response.status === 500 && response.message === 'Session has been invalidated'; } } /** * Represents the common details of a signed in user. */ export interface UserDetails { id: string; token?: string; firstName: string; lastName: string; userName: string; email: string; role?: string; isAdmin?: boolean; needsToResetPassword?: boolean; }
MauroDataMapper/mdm-ui
src/app/shared/branch-selector/branch-selector.component.ts
/* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; import { BasicModelVersionItem, BasicModelVersionTreeResponse, CatalogueItem, Uuid } from '@maurodatamapper/mdm-resources'; import { MdmResourcesService } from '@mdm/modules/resources'; import { ElementTypesService, MessageHandlerService, StateHandlerService } from '@mdm/services'; import { EMPTY } from 'rxjs'; import { catchError } from 'rxjs/operators'; @Component({ selector: 'mdm-branch-selector', templateUrl: './branch-selector.component.html', styleUrls: ['./branch-selector.component.scss'] }) export class BranchSelectorComponent implements OnInit { @Input() catalogueItem: CatalogueItem; @Input() forMerge: boolean; @Input() disabled: boolean; @Output() selectedCatalogueItemChanged = new EventEmitter<Uuid>(); versionList: BasicModelVersionItem[]; currentVersionId: Uuid; constructor( private resources: MdmResourcesService, private elementTypes: ElementTypesService, private messageHandler: MessageHandlerService, private stateHandler: StateHandlerService ) {} ngOnInit(): void { this.currentVersionId = this.catalogueItem.id; this.disabled = this.disabled ?? false; const domainElementType = this.elementTypes.getBaseTypeForDomainType( this.catalogueItem.domainType ); this.resources[domainElementType.resourceName] .simpleModelVersionTree(this.catalogueItem.id,{branchesOnly : this.forMerge}) .pipe( catchError((error) => { this.messageHandler.showError( 'There was a problem fetching the branch list.', error ); return EMPTY; }) ) .subscribe((response: BasicModelVersionTreeResponse) => { this.versionList = response.body; this.versionList.sort((a, b) => a.displayName.localeCompare(b.displayName) ); }); } currentVersionIdChanged() { if (this.forMerge) { this.selectedCatalogueItemChanged.emit(this.currentVersionId); } else { this.stateHandler.Go( this.catalogueItem.domainType, { id: this.currentVersionId }, { reload: true, location: true } ); } } }
MauroDataMapper/mdm-ui
src/app/shared/favourites/favourites.component.ts
<reponame>MauroDataMapper/mdm-ui<filename>src/app/shared/favourites/favourites.component.ts /* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, OnInit, Output, EventEmitter, ViewChild, OnDestroy } from '@angular/core'; import { FavouriteHandlerService } from '@mdm/services/handlers/favourite-handler.service'; import { ElementTypesService } from '@mdm/services/element-types.service'; import { MdmResourcesService } from '@mdm/modules/resources'; import { forkJoin, of, Subject } from 'rxjs'; import { MatMenuTrigger } from '@angular/material/menu'; import { catchError, map, takeUntil } from 'rxjs/operators'; import { BroadcastService } from '@mdm/services'; import { CatalogueItem } from '@maurodatamapper/mdm-resources'; @Component({ selector: 'mdm-favourites', templateUrl: './favourites.component.html', styleUrls: ['./favourites.component.sass'] }) export class FavouritesComponent implements OnInit, OnDestroy { @Output() favouriteClick = new EventEmitter<any>(); @Output() favouriteDbClick = new EventEmitter<any>(); @ViewChild(MatMenuTrigger, { static: false }) contextMenu: MatMenuTrigger; reloading = false; allFavourites: Array<Favorite>; storedFavourites : Array<Favorite>; selectedFavourite: any; menuOptions = []; favourites = []; formData = { filterCriteria: '' }; contextMenuPosition = { x: '0px', y: '0px' }; private $unsubscribe = new Subject(); constructor( private resources: MdmResourcesService, private elementTypes: ElementTypesService, private favouriteHandler: FavouriteHandlerService, private broadcast: BroadcastService ) {} ngOnInit() { this.loadFavourites(); this.broadcast .onFavouritesChanged() .pipe(takeUntil(this.$unsubscribe)) .subscribe(() => this.loadFavourites()); } ngOnDestroy(): void { this.$unsubscribe.next(); this.$unsubscribe.complete(); } loadFavourites = () => { this.reloading = true; const queries = []; this.allFavourites = []; this.favourites = []; this.storedFavourites = this.favouriteHandler.get(); const domainTypes = this.elementTypes.getBaseTypes(); this.storedFavourites.forEach((favourite) => { const resourceName = domainTypes[favourite.domainType].resourceName; // make sure we have a resource name for it if (!this.resources[resourceName]) { return; } queries.push( this.resources[resourceName] .get(favourite.id, {}, { handleGetErrors: false }) .pipe( map((res) => res), catchError(() => of('Not Found')) ) ); }); if (queries.length === 0) { this.reloading = false; } forkJoin(queries).subscribe((results) => { let index = 0; results.forEach((res: any) => { if (res !== 'Not Found') { const result = res.body; this.allFavourites[index] = result; index++; } }); this.reloading = false; this.favourites = this.filter( Object.assign([], this.allFavourites), this.formData.filterCriteria ); }); }; filter = (allFavourites, text) => { let i = allFavourites.length - 1; while (i >= 0) { if ( allFavourites[i].label .trim() .toLowerCase() .indexOf(text.trim().toLowerCase()) === -1 ) { allFavourites.splice(i, 1); } i--; } return allFavourites; }; nodeClick = ($event, favourite) => { this.click($event, favourite); }; nodeDbClick = ($event, favourite) => { this.click($event, favourite); }; click = ($event, favourite) => { favourite.selected = !favourite.selected; if (this.selectedFavourite) { this.selectedFavourite.selected = false; } this.selectedFavourite = favourite; if (this.favouriteDbClick) { this.favouriteDbClick.emit(favourite); } }; dataModelContextMenu(favourite : CatalogueItem) { const subMenu = [ { name: 'Remove from Favourites', action: () => { this.favouriteHandler.remove(favourite); } } ]; return subMenu; } rightClick = (event, favourite) => { if (favourite.domainType === 'DataModel') { this.menuOptions = this.dataModelContextMenu(favourite); } event.preventDefault(); this.contextMenuPosition.x = `${event.clientX}px`; this.contextMenuPosition.y = `${event.clientY}px`; this.contextMenu.menuData = { favourite }; this.contextMenu.menu.focusFirstItem('mouse'); this.contextMenu.openMenu(); }; onSearchInputKeyDown() { this.search(); }; search = () => { this.favourites = this.filter( Object.assign([], this.allFavourites), this.formData.filterCriteria ); }; } export interface Favorite { id:string; domainType:string; }
MauroDataMapper/mdm-ui
src/app/admin/openid-connect-provider/openid-connect-provider.component.ts
/* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, OnInit } from '@angular/core'; import { Title } from '@angular/platform-browser'; import { OpenIdConnectProviderDetail, OpenIdConnectProvidersDetailResponse, Uuid } from '@maurodatamapper/mdm-resources'; import { MdmResourcesService } from '@mdm/modules/resources'; import { MessageHandlerService, SecurityHandlerService, SharedService, StateHandlerService } from '@mdm/services'; import { EditingService } from '@mdm/services/editing.service'; import { UIRouterGlobals } from '@uirouter/angular'; import { EMPTY, Observable } from 'rxjs'; import { catchError } from 'rxjs/operators'; import { OpenIdConnectProviderForm } from './openid-connect-provider.model'; @Component({ selector: 'mdm-openid-connect-provider', templateUrl: './openid-connect-provider.component.html', styleUrls: ['./openid-connect-provider.component.scss'] }) export class OpenidConnectProviderComponent implements OnInit { id: Uuid; editExisting = false; form: OpenIdConnectProviderForm; previewImageUrl?: string; redirectUri: string; constructor( private uiRouterGlobals: UIRouterGlobals, private resources: MdmResourcesService, private messageHandler: MessageHandlerService, private stateHandler: StateHandlerService, private editing: EditingService, private shared: SharedService, private title: Title, private securityHandler: SecurityHandlerService) { } ngOnInit(): void { if (!this.shared.features.useOpenIdConnect) { this.stateHandler.Go('alldatamodel'); return; } this.redirectUri = this.securityHandler.getOpenIdAuthorizeUrl().toString(); this.editing.start(); this.id = this.uiRouterGlobals.params.id; this.editExisting = this.id !== undefined && this.id !== null; if (this.editExisting) { this.title.setTitle('OpenID Connect - Edit provider'); this.loadExistingProvider(); } else { this.title.setTitle('OpenID Connect - Add provider'); this.createForm(); } } refreshImagePreview() { this.previewImageUrl = this.form.imageUrl.value; } cancel() { this.editing.confirmCancelAsync().subscribe(confirm => { if (confirm) { this.navigateToParent(); } }); } save() { if (this.form.group.invalid) { return; } const payload = this.form.createPayload(); const request: Observable<OpenIdConnectProvidersDetailResponse> = this.editExisting ? this.resources.pluginOpenIdConnect.update(this.id, payload) : this.resources.pluginOpenIdConnect.save(payload); request .pipe( catchError(error => { this.messageHandler.showError('There was a problem saving the OpenID Connect provider.', error); return EMPTY; }) ) .subscribe(() => { this.messageHandler.showSuccess('The OpenID Connect provider was updated successfully.'); this.navigateToParent(); }); } private createForm(provider?: OpenIdConnectProviderDetail) { this.previewImageUrl = provider?.imageUrl; this.form = new OpenIdConnectProviderForm(provider); } private loadExistingProvider() { this.resources.pluginOpenIdConnect .get(this.id) .pipe( catchError(error => { this.messageHandler.showError('There was a problem getting the OpenID Connect provider.', error); return EMPTY; }) ) .subscribe((response: OpenIdConnectProvidersDetailResponse) => { this.createForm(response.body); }); } private navigateToParent() { this.editing.stop(); this.stateHandler.Go('appContainer.adminArea.openIdConnectProviders'); } }
MauroDataMapper/mdm-ui
src/app/shared/new-version/new-version.component.ts
/* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, OnInit } from '@angular/core'; import { AbstractControl, FormControl, FormGroup, ValidationErrors, ValidatorFn, Validators } from '@angular/forms'; import { Title } from '@angular/platform-browser'; import { CatalogueItem, Modelable, ForkModelPayload, CatalogueItemDomainType, MdmResponse, BranchModelPayload } from '@maurodatamapper/mdm-resources'; import { MdmResourcesService } from '@mdm/modules/resources'; import { StateHandlerService, MessageHandlerService, ElementTypesService, CatalogueElementType } from '@mdm/services'; import { UIRouterGlobals } from '@uirouter/core'; import { EMPTY, Observable } from 'rxjs'; import { catchError, finalize } from 'rxjs/operators'; interface NewVersionAction { name: string; value: 'Fork' | 'Branch' | 'Version'; selectedName: string; icon: string; getDescription(domainType: CatalogueItemDomainType, item: CatalogueItem & Modelable): string; } @Component({ selector: 'mdm-new-version', templateUrl: './new-version.component.html', styleUrls: ['./new-version.component.scss'] }) export class NewVersionComponent implements OnInit { catalogueItem: CatalogueItem & Modelable; domainType: CatalogueItemDomainType; domainElementType: CatalogueElementType; processing: boolean; setupForm: FormGroup; availableActions: NewVersionAction[] = [ { name: 'New Fork', value: 'Fork', selectedName: 'Creating a new fork', icon: 'fa-list', getDescription: (domainType, item) => { return `This will create a copy of <b>${item.label}</b> with a new name, and a new 'main' branch. Use this option if you are planning on taking this ${domainType === CatalogueItemDomainType.VersionedFolder ? 'folder' : 'model'} in a new direction, or under a new authority.`; } }, { name: 'New Version', value: 'Version', selectedName: 'Creating a new version', icon: 'fa-file-alt', getDescription: (domainType, item) => { return `This will create a draft copy of <b>${item.label }</b> under the 'main' branch. Use this option if you want to create the next iteration of this ${domainType === CatalogueItemDomainType.VersionedFolder ? 'folder' : 'model'}.`; } }, { name: 'New Branch', value: 'Branch', selectedName: 'Creating a new branch', icon: 'fa-code-branch', getDescription: (_, item) => { return `This will create a copy of <b>${item.label}</b> in a new branch. You may choose the name of the new branch. Use this option if you want to make some changes that you subsequently wish to merge back into 'main'.`; } }, ]; get action() { return this.setupForm.get('action'); } get actionValue(): 'Fork' | 'Branch' | 'Version' | undefined { return this.action.value; } get actionSelectedName() { return this.availableActions.find(a => a.value === this.actionValue)?.selectedName; } get label() { return this.setupForm.get('label'); } get branchName() { return this.setupForm.get('branchName'); } constructor( private uiRouterGlobals: UIRouterGlobals, private stateHandler: StateHandlerService, private resources: MdmResourcesService, private messageHandler: MessageHandlerService, private elementTypes: ElementTypesService, private title: Title) { } ngOnInit(): void { this.title.setTitle('New Version'); this.domainType = this.uiRouterGlobals.params.domainType; if (!this.uiRouterGlobals.params.id || !this.domainType) { this.stateHandler.NotFound({ location: false }); return; } const types = this.elementTypes.getBaseTypes(); this.domainElementType = types[this.domainType]; // Setup first key field in form first, remaining form fields depend on the type selected this.setupForm = new FormGroup({ action: new FormControl('', Validators.required) // eslint-disable-line @typescript-eslint/unbound-method }); this.resources[this.domainElementType.resourceName] .get(this.uiRouterGlobals.params.id) .subscribe((response: MdmResponse<CatalogueItem & Modelable>) => { this.catalogueItem = response.body; }); } actionChanged() { if (this.label) { this.setupForm.removeControl('label'); } if (this.branchName) { this.setupForm.removeControl('branchName'); } if (this.actionValue === 'Fork') { this.setupForm.addControl( 'label', new FormControl( '', [ Validators.required, // eslint-disable-line @typescript-eslint/unbound-method this.forbiddenName(this.catalogueItem.label) ])); } if (this.actionValue === 'Branch') { this.setupForm.addControl( 'branchName', new FormControl('', Validators.required)); // eslint-disable-line @typescript-eslint/unbound-method } } forbiddenName(disallow: string): ValidatorFn { return (control: AbstractControl): ValidationErrors | null => { if (disallow.trim().toLowerCase() === control.value.trim().toLowerCase()) { return { forbiddenName: { value: control.value } }; } return null; }; } create() { if (!this.setupForm.valid) { return; } this.processing = true; this.setupForm.disable(); if (this.actionValue === 'Fork') { const resource: ForkModelPayload = { label: this.label.value, copyPermissions: false, copyDataFlows: false }; const request : Observable<MdmResponse<CatalogueItem>> = this.resources[this.domainElementType.resourceName] .newForkModel(this.catalogueItem.id, resource); this.handleCreateResponse( request, 'New forked version created successfully.', 'There was a problem creating the new forked version.'); } else if (this.actionValue === 'Version') { const request : Observable<MdmResponse<CatalogueItem>> = this.resources[this.domainElementType.resourceName] .newBranchModelVersion(this.catalogueItem.id, {}); this.handleCreateResponse( request, 'New version created successfully.', 'There was a problem creating the new version.'); } else if (this.actionValue === 'Branch') { const resource: BranchModelPayload = { branchName: this.branchName.value }; const request : Observable<MdmResponse<CatalogueItem>> = this.resources[this.domainElementType.resourceName] .newBranchModelVersion(this.catalogueItem.id, resource); this.handleCreateResponse( request, 'New branch created successfully.', 'There was a problem creating the new branch.'); } } cancel() { this.stateHandler.Go(this.domainType, { id: this.catalogueItem.id }); } private handleCreateResponse( request: Observable<MdmResponse<CatalogueItem>>, successMessage: string, errorMessage: string) { request .pipe( catchError(error => { this.messageHandler.showError(errorMessage, error); return EMPTY; }), finalize(() => { this.processing = false; this.setupForm.enable(); }) ) .subscribe((response: MdmResponse<CatalogueItem>) => { this.messageHandler.showSuccess(successMessage); this.stateHandler.Go( this.domainType, { id: response.body.id }, { reload: true } ); }); } }
MauroDataMapper/mdm-ui
src/app/services/handlers/folder-handler.service.ts
<gh_stars>1-10 /* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Injectable } from '@angular/core'; import { MdmResourcesService } from '@mdm/modules/resources'; import { MessageHandlerService } from '../utility/message-handler.service'; import { MatDialog } from '@angular/material/dialog'; import { Observable, of } from 'rxjs'; import { catchError, map, mergeMap } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class FolderHandlerService { constructor( private resourcesService: MdmResourcesService, private messageHandler: MessageHandlerService, private dialog: MatDialog) {} askForSoftDelete(id: string): Observable<void> { return this.dialog.openConfirmationAsync({ data: { title: 'Are you sure you want to delete this Folder?', okBtnTitle: 'Yes, delete', btnType: 'warn', message: `<p class="marginless">This Folder will be marked as deleted and will not be viewable by users </p> <p class="marginless">except Administrators.</p>` } }) .pipe( mergeMap(() => this.delete(id, false)) ); } askForPermanentDelete(id: string): Observable<void> { return this.dialog.openDoubleConfirmationAsync({ data: { title: 'Permanent deletion', okBtnTitle: 'Yes, delete', btnType: 'warn', message: 'Are you sure you want to <span class=\'warning\'>permanently</span> delete this Folder?' } }, { data: { title: 'Confirm permanent deletion', okBtnTitle: 'Confirm deletion', btnType: 'warn', message: '<strong>Note: </strong> All its \'Data Models\' and \'Folders\' will be deleted <span class=\'warning\'>permanently</span>.' } }) .pipe( mergeMap(() => this.delete(id, true)) ); } delete(id: string, permanent = false): Observable<void> { return this.resourcesService.folder .remove(id, { permanent }) .pipe( map(() => this.messageHandler.showSuccess('Successfully Deleted Folder')), catchError(error => { this.messageHandler.showError('There was a problem deleting the Folder.', error); return of(); }) ); } }
MauroDataMapper/mdm-ui
src/app/dataElement/data-element-details/data-element-details.component.ts
<reponame>MauroDataMapper/mdm-ui /* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, Input, OnDestroy, OnInit } from '@angular/core'; import { Subscription } from 'rxjs'; import { MessageService } from '@mdm/services/message.service'; import { MdmResourcesService } from '@mdm/modules/resources'; import { MessageHandlerService } from '@mdm/services/utility/message-handler.service'; import { StateHandlerService } from '@mdm/services/handlers/state-handler.service'; import { Title } from '@angular/platform-browser'; import { BroadcastService } from '@mdm/services/broadcast.service'; import { MatDialog } from '@angular/material/dialog'; import { SecurityHandlerService } from '@mdm/services/handlers/security-handler.service'; import { EditingService } from '@mdm/services/editing.service'; import { DataClass, DataElement, DataElementDetail, DataModel } from '@maurodatamapper/mdm-resources'; import { ValidatorService } from '@mdm/services'; import { Access } from '@mdm/model/access'; @Component({ selector: 'mdm-data-element-details', templateUrl: './data-element-details.component.html', styleUrls: ['./data-element-details.component.sass'] }) export class DataElementDetailsComponent implements OnInit, OnDestroy { @Input() parentDataModel : DataModel; @Input() parentDataClass : DataClass; @Input() editMode = false; result: DataElementDetail; subscription: Subscription; deleteInProgress: boolean; parentLabel = ''; access: Access; errorMessage = ''; constructor( private messageService: MessageService, private resourcesService: MdmResourcesService, private messageHandler: MessageHandlerService, private stateHandler: StateHandlerService, private title: Title, private broadcast: BroadcastService, private dialog: MatDialog, private securityHandler: SecurityHandlerService, private editingService: EditingService, private validatorService: ValidatorService ) { this.dataElementDetails(); } ngOnInit() { } dataElementDetails(): any { this.subscription = this.messageService.dataChanged$.subscribe( (serverResult) => { this.result = serverResult; if (this.result.breadcrumbs) { this.parentLabel = this.result.breadcrumbs[ serverResult.breadcrumbs.length - 1 ].label; } this.title.setTitle(`Data Element - ${this.result?.label}`); this.access = this.securityHandler.elementAccess(this.result); } ); } ngOnDestroy() { this.subscription.unsubscribe(); // unsubscribe to ensure no memory leaks } askForPermanentDelete() { this.dialog .openDoubleConfirmationAsync( { data: { title: 'Permanent deletion', okBtnTitle: 'Yes, delete', btnType: 'warn', message: `<p>Are you sure you want to <span class='warning'>permanently</span> delete this Data Element?</p> <p class='marginless'><strong>Note:</strong> You are deleting the <strong><i>${this.result.label}</i></strong> Data Element.</p>` } }, { data: { title: 'Confirm permanent deletion', okBtnTitle: 'Confirm deletion', btnType: 'warn', message: '<strong>Note: </strong> All its contents will be deleted <span class="warning">permanently</span>.' } } ) .subscribe(() => this.delete()); } delete() { this.resourcesService.dataElement .remove(this.result.model, this.result.dataClass, this.result.id) .subscribe( () => { this.messageHandler.showSuccess('Data Element deleted successfully.'); this.broadcast.reloadCatalogueTree(); this.stateHandler.Go( 'appContainer.mainApp.twoSidePanel.catalogue.allDataModel' ); }, (error) => { this.deleteInProgress = false; this.messageHandler.showError( 'There was a problem deleting the Data Element.', error ); } ); } save() { if (this.validatorService.validateLabel(this.result.label)) { const resource: DataElement = { id: this.result.id, label: this.result.label, domainType: this.result.domainType }; this.resourcesService.dataElement .update( this.parentDataModel.id, this.parentDataClass.id, this.result.id, resource ) .subscribe( () => { this.editMode = false; this.editingService.stop(); this.messageHandler.showSuccess( 'Data Element updated successfully.' ); this.broadcast.reloadCatalogueTree(); }, (error) => { this.messageHandler.showError( 'There was a problem updating the Data Element.', error ); } ); } else{ this.messageHandler.showError('There is an error with the label please correct and try again'); } } toggleShowSearch() { this.messageService.toggleSearch(); } showForm() { this.editMode = true; this.editingService.start(); } cancel() { this.editingService.stop(); this.dataElementDetails(); this.editMode = false; // Use Input editor whe adding a new folder. } }
MauroDataMapper/mdm-ui
src/app/wizards/dataClass/data-class-main/data-class-main.component.ts
<gh_stars>1-10 /* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, EventEmitter, ChangeDetectorRef, AfterViewInit } from '@angular/core'; import { Step } from '@mdm/model/stepModel'; import { DataClassStep2Component } from '../data-class-step2/data-class-step2.component'; import { DataClassStep1Component } from '../data-class-step1/data-class-step1.component'; import { StateHandlerService } from '@mdm/services/handlers/state-handler.service'; import { StateService } from '@uirouter/core'; import { MdmResourcesService } from '@mdm/modules/resources'; import { MessageHandlerService } from '@mdm/services/utility/message-handler.service'; import { Title } from '@angular/platform-browser'; import { BroadcastService } from '@mdm/services/broadcast.service'; import { CatalogueItemDomainType, DataClass, DataClassDetailResponse } from '@maurodatamapper/mdm-resources'; import { Observable } from 'rxjs'; @Component({ selector: 'mdm-data-class-main', templateUrl: './data-class-main.component.html', styleUrls: ['./data-class-main.component.sass'] }) export class DataClassMainComponent implements AfterViewInit { steps: Step[] = []; doneEvent = new EventEmitter<any>(); parentDataModelId: any; grandParentDataClassId: any; parentDataClassId: any; model: any = { metadata: [], classifiers: [], parent: {}, createType: 'new', copyFromDataModel: [], selectedDataClasses: [], selectedDataClassesMap: {} }; constructor( private title: Title, private stateService: StateService, private stateHandler: StateHandlerService, private resources: MdmResourcesService, private messageHandler: MessageHandlerService, private broadcastSvc: BroadcastService, private changeRef: ChangeDetectorRef ) {} ngAfterViewInit(): void { // Called after ngAfterContentInit when the component's view has been initialized. Applies to components only. this.title.setTitle('New Data Class'); // tslint:disable-next-line: deprecation this.parentDataModelId = this.stateService.params.parentDataModelId; // tslint:disable-next-line: deprecation this.grandParentDataClassId = this.stateService.params.grandParentDataClassId; // tslint:disable-next-line: deprecation this.parentDataClassId = this.stateService.params.parentDataClassId; if (!this.parentDataModelId) { this.stateHandler.NotFound({ location: false }); return; } const step1 = new Step(); step1.title = 'Select an Import Method'; step1.component = DataClassStep1Component; step1.scope = this; step1.hasForm = true; step1.invalid = true; const step2 = new Step(); step2.title = 'Data Class Details'; step2.component = DataClassStep2Component; step2.scope = this; step2.invalid = true; if (this.parentDataClassId) { this.resources.dataClass .getChildDataClass( this.parentDataModelId, this.grandParentDataClassId, this.parentDataClassId ) .toPromise() .then((result) => { result.body.breadcrumbs.push(Object.assign([], result.body)); this.model.parent = result.body; this.steps.push(step1); this.steps.push(step2); this.changeRef.detectChanges(); }); } else { this.resources.dataModel .get(this.parentDataModelId) .toPromise() .then((result) => { result.body.breadcrumbs = []; result.body.breadcrumbs.push(Object.assign({}, result.body)); this.model.parent = result.body; this.steps.push(step1); this.steps.push(step2); this.changeRef.detectChanges(); }); } } closeWizard = () => { this.stateHandler.GoPrevious(); }; save = () => { if (this.model.createType === 'new') { this.saveNewDataClass(); } else { this.saveCopiedDataClasses(); } }; getMultiplicity = (resource, multiplicity) => { if (this.model[multiplicity] === '*') { this.model[multiplicity] = -1; } if (!isNaN(this.model[multiplicity])) { resource[multiplicity] = parseInt(this.model[multiplicity], 10); } }; fireChanged = (tab: any) => { for (let i = 0; i < this.steps.length; i++) { const step: Step = this.steps[i]; if (i === tab.selectedIndex) { if (step.compRef) { if (step.compRef.instance.onLoad !== undefined) { step.compRef.instance.onLoad(); } step.active = true; } } else { step.active = false; } } }; saveCopiedDataClasses = () => { this.steps[1].compRef.instance.saveCopiedDataClasses(); }; saveNewDataClass = () => { const resource: DataClass = { domainType: CatalogueItemDomainType.DataClass, label: this.model.label, description: this.model.description, classifiers: this.model.classifiers.map((cls) => { return { id: cls.id }; }), metadata: this.model.metadata.map((m) => { return { key: m.key, value: m.value, namespace: m.namespace }; }), minMultiplicity: null, maxMultiplicity: null }; this.getMultiplicity(resource, 'minMultiplicity'); this.getMultiplicity(resource, 'maxMultiplicity'); let deferred: Observable<DataClassDetailResponse>; if (this.model.parent.domainType === 'DataClass') { deferred = this.resources.dataClass.addChildDataClass( this.model.parent.model, this.model.parent.id, resource ); } else { deferred = this.resources.dataClass.save(this.model.parent.id, resource); } deferred.subscribe( (response) => { this.messageHandler.showSuccess('Data Class saved successfully.'); this.stateHandler.Go( 'dataClass', { dataModelId: response.body.model || '', dataClassId: response.body.parentDataClass || '', id: response.body.id }, { reload: true, location: true } ); }, (error) => { this.messageHandler.showError( 'There was a problem saving the Data Class.', error ); } ); }; }
MauroDataMapper/mdm-ui
src/app/diagram/services/models-merging-diagram.service.ts
<reponame>MauroDataMapper/mdm-ui /* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { BasicDiagramService } from './basic-diagram.service'; import { Injectable } from '@angular/core'; import * as joint from 'jointjs'; import { Observable, throwError } from 'rxjs'; import { DiagramParameters } from '../diagram/diagram.model'; import { CatalogueItemDomainType, ModelVersionItem, ModelVersionTreeResponse } from '@maurodatamapper/mdm-resources'; @Injectable({ providedIn: 'root' }) export class ModelsMergingDiagramService extends BasicDiagramService { parentId: string; // Color codes for the diagram shapes fontColorBlack = '#000000'; fontColorWhite = '#ffffff'; darkOrange = '#f27954'; lightOrange = '#f7a900'; shadedOrange = '#fec994'; getDiagramContent(params: DiagramParameters): Observable<ModelVersionTreeResponse> { this.parentId = params.parent.id; switch (params.parent.domainType) { case CatalogueItemDomainType.DataModel: return this.resourcesService.dataModel.modelVersionTree(params.parent.id); case CatalogueItemDomainType.CodeSet: return this.resourcesService.codeSet.modelVersionTree(params.parent.id); case CatalogueItemDomainType.Terminology: return this.resourcesService.terminology.modelVersionTree(params.parent.id); case CatalogueItemDomainType.ReferenceDataModelType: return this.resourcesService.referenceDataModel.modelVersionTree(params.parent.id); case CatalogueItemDomainType.VersionedFolder: return this.resourcesService.versionedFolder.modelVersionTree(params.parent.id); default: return throwError(`Cannot get merge graph content for '${params.parent.domainType} ${params.parent.id}' - not supported.`); } } render(result: ModelVersionTreeResponse): void { this.changeComponent(null); result.body.forEach((item: ModelVersionItem) => { if (item.id === this.parentId) { this.addColoredRectangleCell( this.fontColorWhite, this.darkOrange, item.id, `${item.label} \n\n Version ${item.documentationVersion} \n\n ${item.branch} branch`, 300, 100, 288 ); } else if (item.isNewFork) { this.addRectangleCell( item.id, `Fork \n\n ${item.label} \n\n ${item.branch} branch`, 300, 100, 288 ); } else if (item.isNewDocumentationVersion) { this.addColoredRectangleCell( this.fontColorBlack, this.shadedOrange, item.id, `${item.label} \n\n Version ${item.documentationVersion} \n\n ${item.branch} branch`, 300, 100, 288 ); } else { if (item.modelVersion) { this.addColoredRectangleCell( this.fontColorBlack, this.lightOrange, item.id, `${item.label} \n\n Version ${item.modelVersion}`, 300, 100, 288 ); } else { this.addColoredRectangleCell( this.fontColorBlack, this.shadedOrange, item.id, `${item.label} \n\n ${item.branch} branch`, 300, 100, 288 ); } } }); // Adding the links in a separate loop, because it won't find the target otherwise result.body.forEach((item: ModelVersionItem) => { let link: any; item.targets.forEach((itmTarget) => { link = new joint.shapes.standard.Link({ id: `${item.id} _ ${itmTarget.id}`, source: { id: itmTarget.id }, target: { id: item.id }, labels: [ { attrs: { text: { text: itmTarget.description } }, position: { offset: 35, distance: 0.5 } } ] }); this.graph.addCell(link); }); }); } configurePaper(paper: joint.dia.Paper): void { paper.on('cell:pointerclick', () => {}); paper.on('link:pointerdblclick', () => {}); } canGoUp(): boolean { return true; } goUp(): void {} }
MauroDataMapper/mdm-ui
src/app/search/date-from-to/format-datepicker.ts
/* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { MatDateFormats } from '@angular/material/core/datetime/date-formats'; import { NativeDateAdapter } from '@angular/material/core/datetime/native-date-adapter'; export class AppDateAdapter extends NativeDateAdapter { format(date: Date, displayFormat: any): string { if (displayFormat === 'input') { let day: string = date.getDate().toString(); day = +day < 10 ? '0' + day : day; let month: string = (date.getMonth() + 1).toString(); month = +month < 10 ? '0' + month : month; const year = date.getFullYear(); return `${day}.${month}.${year}`; } return date.toDateString(); } } // eslint-disable-next-line @typescript-eslint/naming-convention export const APP_DATE_FORMATS: MatDateFormats = { parse: { dateInput: { month: 'short', year: 'numeric', day: 'numeric' } }, display: { dateInput: 'input', monthYearLabel: { year: 'numeric', month: 'numeric' }, dateA11yLabel: { year: 'numeric', month: 'long', day: 'numeric' }, monthYearA11yLabel: { year: 'numeric', month: 'long' } } };
MauroDataMapper/mdm-ui
src/app/classification/classification-details/classification-details.component.ts
/* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, OnInit, Input} from '@angular/core'; import { MdmResourcesService } from '@mdm/modules/resources'; import { MessageService } from '@mdm/services/message.service'; import { MessageHandlerService } from '@mdm/services/utility/message-handler.service'; import { SecurityHandlerService } from '@mdm/services/handlers/security-handler.service'; import { FolderHandlerService } from '@mdm/services/handlers/folder-handler.service'; import { StateHandlerService } from '@mdm/services/handlers/state-handler.service'; import { ElementSelectorDialogueService } from '@mdm/services/element-selector-dialogue.service'; import { BroadcastService } from '@mdm/services/broadcast.service'; import { DialogPosition } from '@angular/material/dialog'; import { Title } from '@angular/platform-browser'; import { MatDialog } from '@angular/material/dialog'; import { EditingService } from '@mdm/services/editing.service'; import { ClassifierDetail, ClassifierDetailResponse } from '@maurodatamapper/mdm-resources'; import { ValidatorService } from '@mdm/services'; import { Access } from '@mdm/model/access'; @Component({ selector: 'mdm-classification-details', templateUrl: './classification-details.component.html', styleUrls: ['./classification-details.component.sass'] }) export class ClassificationDetailsComponent implements OnInit { @Input() classification: ClassifierDetail; originalClassification: ClassifierDetail; editMode = false; errorMessage = ''; access: Access; constructor( private messageService: MessageService, private securityHandler: SecurityHandlerService, private folderHandler: FolderHandlerService, private elementDialogueService: ElementSelectorDialogueService, private stateHandler: StateHandlerService, private title: Title, private dialog: MatDialog, private validator: ValidatorService, private resources: MdmResourcesService, private messageHandler: MessageHandlerService, private editing: EditingService, private broadcast: BroadcastService ) { } public showAddElementToMarkdown() { // Remove from here & put in markdown this.elementDialogueService.open('Search_Help', 'left' as DialogPosition); } ngOnInit() { this.originalClassification = Object.assign({}, this.classification); this.ClassifierDetails(); } ClassifierDetails(): any { this.access = this.securityHandler.elementAccess(this.classification); this.title.setTitle(`Classifier - ${this.classification.label}`); } toggleSecuritySection() { this.dialog.openSecurityAccess(this.classification, 'classifier'); } toggleShowSearch() { this.messageService.toggleSearch(); } askForSoftDelete() { if (!this.securityHandler.isAdmin()) { return; } this.folderHandler .askForSoftDelete(this.classification.id) .subscribe(() => { this.stateHandler.reload(); }); } askForPermanentDelete() { if (!this.access.showPermanentDelete) { return; } this.dialog .openDoubleConfirmationAsync( { data: { title: 'Permanent deletion', okBtnTitle: 'Yes, delete', btnType: 'warn', message: `<p>Are you sure you want to <span class='warning'>permanently</span> delete this Classifier?</p> <p class='marginless'><strong>Note:</strong> You are deleting the <strong><i>${this.classification.label}</i></strong> classifier.</p>` } }, { data: { title: 'Confirm permanent deletion', okBtnTitle: 'Confirm deletion', btnType: 'warn', message: '<strong>Note: </strong> All its contents will be deleted <span class=\'warning\'>permanently</span>.' } } ) .subscribe(() => this.delete()); } save() { if (this.validator.validateLabel(this.classification.label)) { this.editMode = false; this.errorMessage = ''; const resource = { id: this.classification.id, label: this.classification.label }; this.resources.classifier .update(this.classification.id, resource) .subscribe( (result: ClassifierDetailResponse) => { this.messageHandler.showSuccess('Classifier updated successfully.'); this.editing.stop(); this.originalClassification = result.body; }, (error) => { this.messageHandler.showError( 'There was a problem updating the Classifier.', error ); } ); } } showForm() { this.editing.start(); this.editMode = true; } cancel() { this.classification = Object.assign({}, this.originalClassification); this.editMode = false; // Use Input editor whe adding a new folder. this.errorMessage = ''; } delete() { this.resources.classifier .remove(this.classification.id, { permanent: true }) .subscribe( () => { this.messageHandler.showSuccess('Classifier deleted successfully.'); this.broadcast.reloadClassificationTree(); this.stateHandler.Go( 'allDataModel', { reload: true, location: true }, null ); }, (error) => { this.messageHandler.showError( 'There was a problem deleting this Classification.', error ); } ); } }
MauroDataMapper/mdm-ui
src/app/admin/emails/emails.component.ts
/* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, OnInit, ViewChild, ViewChildren, EventEmitter, ElementRef, AfterViewInit, ChangeDetectorRef } from '@angular/core'; import { MatSort } from '@angular/material/sort'; import { MdmResourcesService } from '@mdm/modules/resources'; import { merge, Observable } from 'rxjs'; import { catchError, map, startWith, switchMap } from 'rxjs/operators'; import { MdmPaginatorComponent } from '@mdm/shared/mdm-paginator/mdm-paginator'; import { Title } from '@angular/platform-browser'; import { GridService } from '@mdm/services/grid.service'; @Component({ selector: 'mdm-app-emails', templateUrl: './emails.component.html', styleUrls: ['./emails.component.sass'] }) export class EmailsComponent implements OnInit, AfterViewInit { @ViewChildren('filters', { read: ElementRef }) filters: ElementRef[]; @ViewChild(MatSort, { static: false }) sort: MatSort; @ViewChild(MdmPaginatorComponent, { static: true }) paginator: MdmPaginatorComponent; hideFilters = true; isLoadingResults: boolean; totalItemCount = 0; filterEvent = new EventEmitter<any>(); filter: {}; records: any[] = []; displayedColumns = ['sentToEmailAddress', 'dateTimeSent', 'subject', 'body', 'successfullySent']; constructor( private resourcesService: MdmResourcesService, private title: Title, private changeRef: ChangeDetectorRef, private gridService: GridService ) { } ngOnInit() { this.title.setTitle('Emails'); } ngAfterViewInit() { this.sort.sortChange.subscribe(() => (this.paginator.pageIndex = 0)); this.filterEvent.subscribe(() => (this.paginator.pageIndex = 0)); merge(this.sort.sortChange, this.paginator.page, this.filterEvent).pipe(startWith({}), switchMap(() => { this.isLoadingResults = true; return this.mailsFetch(this.paginator.pageSize, this.paginator.pageOffset, this.sort.active, this.sort.direction, this.filter); }), map((data: any) => { this.totalItemCount = data.body.count; this.isLoadingResults = false; return data.body.items; }), catchError(() => { this.isLoadingResults = false; return []; })).subscribe(data => { this.records = data; }); this.changeRef.detectChanges(); } mailsFetch(pageSize?, pageIndex?, sortBy?, sortType?, filters?): Observable<any> { const options = this.gridService.constructOptions(pageSize, pageIndex, sortBy, sortType, filters); return this.resourcesService.admin.emails(options); } applyFilter = () => { const filter = {}; this.filters.forEach((x: any) => { const name = x.nativeElement.name; const value = x.nativeElement.value; if (value !== '') { filter[name] = value; } }); this.filter = filter; this.filterEvent.emit(filter); }; filterClick = () => { this.hideFilters = !this.hideFilters; }; toggleMessage(record) { record.showFailure = !record.showFailure; } }
MauroDataMapper/mdm-ui
src/app/model/access.ts
<filename>src/app/model/access.ts /* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ /** * Represents access/permissions flags to determine what a catalogue item can do. * * @see {@link SecurityHandlerService.elementAccess} */ export interface Access { showEdit: boolean; canEditDescription: boolean; showNewVersion?: boolean; showFinalise: boolean; showPermission: boolean; showSoftDelete: boolean; showPermanentDelete: boolean; canAddAnnotation: boolean; canAddMetadata: boolean; showDelete: boolean; canAddLink: boolean; canCreateFolder: boolean; canCreateVersionedFolder: boolean; canCreateFolderContainer: boolean; canCreateModel: boolean; canCreateModelItem: boolean; canCreate: boolean; canMoveToFolder: boolean; canMoveToVersionedFolder: boolean; canReadAfterFinalised: boolean; canEditAfterFinalise: boolean; canMergeInto: boolean; }
MauroDataMapper/mdm-ui
src/app/errors/server-timeout/server-timeout.component.ts
/* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import {Component, OnInit} from '@angular/core'; import {MessageService} from '@mdm/services/message.service'; import {ClipboardService} from 'ngx-clipboard'; import {YoutrackService} from '@mdm/services/youtrack.service'; import {SharedService} from '@mdm/services/shared.service'; import {ErrorComponent} from '../error.component'; @Component({ selector: 'mdm-server-timeout-error', templateUrl: '../error.component.html', styleUrls: [] }) export class ServerTimeoutComponent extends ErrorComponent implements OnInit { constructor(protected messageService: MessageService, protected clipboardService: ClipboardService, protected sharedService: SharedService, protected youtrackService: YoutrackService) { super(messageService, clipboardService, sharedService, youtrackService); this.errorHeader = 'Server Timeout Error'; this.errorMessage = 'We\'re sorry, but the server responded with an error message.'; this.errorResolution = 'The request may have succeeded. Please allow some time and then select the catalogue item you were on from the model tree to refresh the view.'; this.errorReportMessage = 'Alternatively, if the error persists, please report the issue to us by using the link below:'; this.dataSource.push({field: 'Reason', value: 'Server Timeout', code: false}); this.dataSource.push({field: 'Status', value: 'Server Gateway Timeout', code: false}); this.dataSource.push({field: 'Error Code', value: '504', code: false}); } }
MauroDataMapper/mdm-ui
src/app/folders-tree/folders-tree.module.ts
/* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { NgModule } from '@angular/core'; import { MatTreeModule } from '@angular/material/tree'; import { MatDividerModule } from '@angular/material/divider'; import { MatIconModule } from '@angular/material/icon'; import { MatMenuModule } from '@angular/material/menu'; import { MatCheckboxModule } from '@angular/material/checkbox'; import { MatButtonModule } from '@angular/material/button'; import { FoldersTreeComponent } from './folders-tree.component'; import { FormsModule } from '@angular/forms'; import { CommonModule } from '@angular/common'; import { StringifyPipe } from '../pipes/stringify.pipe'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { FolderService } from './folder.service'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatInputModule } from '@angular/material/input'; import { PipesModule } from '@mdm/modules/pipes/pipes.module'; @NgModule({ imports: [ CommonModule, FormsModule, MatTreeModule, MatDividerModule, MatButtonModule, MatIconModule, MatMenuModule, MatCheckboxModule, BrowserAnimationsModule, MatFormFieldModule, MatInputModule, PipesModule ], declarations: [ FoldersTreeComponent, StringifyPipe ], entryComponents: [ FoldersTreeComponent ], exports: [ FoldersTreeComponent, StringifyPipe, MatFormFieldModule, MatInputModule, ], providers: [ FolderService ] }) export class FoldersTreeModule { }
MauroDataMapper/mdm-ui
src/app/wizards/dcl-wrapper.component.ts
<filename>src/app/wizards/dcl-wrapper.component.ts /* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Output, Component, ViewContainerRef, ViewChild, Input, ComponentFactoryResolver, ChangeDetectorRef, EventEmitter, OnChanges, AfterViewInit, OnDestroy, Type } from '@angular/core'; // Helper component to add dynamic components @Component({ selector: 'mdm-dcl-wrapper', template: '<div #target></div>' }) export class DclWrapperComponent implements OnChanges, AfterViewInit, OnDestroy { @Output() stepChanged = new EventEmitter<any>(); @ViewChild('target', { read: ViewContainerRef, static: false }) target; @Input() type : Type<unknown>; stepVal: any; private isViewInitialized = false; constructor(private componentFactoryResolver: ComponentFactoryResolver, private cdRef: ChangeDetectorRef) { } @Input() get step(): any { return this.stepVal; } set step(val) { this.stepVal = val; this.stepChanged.emit(); } updateComponent() { if (!this.isViewInitialized) { return; } if (this.step.compRef) { this.step.compRef.destroy(); } const factory = this.componentFactoryResolver.resolveComponentFactory(this.type); this.step.compRef = this.target.createComponent(factory); this.step.compRef.instance.step = this.step; this.cdRef.detectChanges(); } ngOnChanges() { this.updateComponent(); } ngAfterViewInit() { this.isViewInitialized = true; this.updateComponent(); } ngOnDestroy() { if (this.step.compRef) { this.step.compRef.destroy(); } } }
MauroDataMapper/mdm-ui
src/app/shared/path-name/path-name.model.ts
/* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ /** * Prefixes used in Mauro to represent Fully Qualified Paths (FQPs). */ export enum PathElementType { ApiKey = 'ak', Annotation = 'ann', ApiProperty = 'api', Authority = 'auth', Classifier = 'cl', CodeSet = 'cs', CatalogueUser = 'cu', DataClass = 'dc', DataClassComponent = 'dcc', DataElement = 'de', DataElementComponent = 'dec', DataFlow = 'df', DataModel = 'dm', EnumerationType = 'dt', Edit = 'ed', EnumerationValue = 'ev', Folder = 'fo', GroupRole = 'gr', Metadata = 'md', ReferenceDataElement = 'rde', ReferenceDataModel = 'rdm', ReferenceEnumerationType = 'rdt', ReferenceDataValue = 'rdv', ReferenceEnumerationValue = 'rev', ReferenceFile = 'rf', RuleRepresentation = 'rr', ReferenceSummaryMetadata = 'rsm', ReferenceSummaryMetadataReport = 'rsmr', Rule = 'ru', SemanticLink = 'sl', SummaryMetadata = 'sm', SummaryMetadataReport = 'smr', SecurableResourceGroupRole = 'srgr', SubscribedCatalogue = 'subc', SubscribedModel = 'subm', Terminology = 'te', Term = 'tm', TermRelationship = 'tr', TermRelationshipType = 'trt', UserGroup = 'ug', UserImageFile = 'uif', VersionedFolder = 'vf', VersionLink = 'vl' } export const pathElementTypeNames = new Map<PathElementType, string>( [ [ PathElementType.ApiKey, 'API key'], [ PathElementType.Annotation, 'Annotation'], [ PathElementType.ApiProperty, 'API property'], [ PathElementType.Authority, 'Authority'], [ PathElementType.Classifier, 'Classifier'], [ PathElementType.CodeSet, 'Code set'], [ PathElementType.CatalogueUser, 'Catalogue user'], [ PathElementType.DataClass, 'Data class'], [ PathElementType.DataClassComponent, 'Data class component'], [ PathElementType.DataElement, 'Data element'], [ PathElementType.DataElementComponent, 'Data element component'], [ PathElementType.DataFlow, 'Data flow'], [ PathElementType.DataModel, 'Data model'], [ PathElementType.EnumerationType, 'Enumeration type'], [ PathElementType.Edit, 'Edit'], [ PathElementType.EnumerationValue, 'Enumeration value'], [ PathElementType.Folder, 'Folder'], [ PathElementType.GroupRole, 'Group role'], [ PathElementType.Metadata, 'Metadata'], [ PathElementType.ReferenceDataElement, 'Reference data element'], [ PathElementType.ReferenceDataModel, 'Reference data model'], [ PathElementType.ReferenceEnumerationType, 'Reference enumeration type'], [ PathElementType.ReferenceDataValue, 'Reference data value'], [ PathElementType.ReferenceEnumerationValue, 'Reference enumeration value'], [ PathElementType.ReferenceFile, 'Reference file'], [ PathElementType.RuleRepresentation, 'Rule representation'], [ PathElementType.ReferenceSummaryMetadata, 'Reference summary metadata'], [ PathElementType.ReferenceSummaryMetadataReport, 'Reference summary metadata report'], [ PathElementType.Rule, 'Rule'], [ PathElementType.SemanticLink, 'Semantic link'], [ PathElementType.SummaryMetadata, 'Summary metadata'], [ PathElementType.SummaryMetadataReport, 'Summary metadata report'], [ PathElementType.SecurableResourceGroupRole, 'Securable resource group role'], [ PathElementType.SubscribedCatalogue, 'Subscribed catalogue'], [ PathElementType.SubscribedModel, 'Subscribed model'], [ PathElementType.Terminology, 'Terminology'], [ PathElementType.Term, 'Term'], [ PathElementType.TermRelationship, 'Term relationship'], [ PathElementType.TermRelationshipType, 'Term relationship type'], [ PathElementType.UserGroup, 'User group'], [ PathElementType.UserImageFile, 'User image file'], [ PathElementType.VersionedFolder, 'Versioned folder'], [ PathElementType.VersionLink, 'Version link'] ] ); export interface PathProperty { name: string; qualifiedName: string[]; } export interface PathElement { type: PathElementType; typeName: string; label: string; version?: string; property?: PathProperty; }
MauroDataMapper/mdm-ui
src/app/modals/versioning-graph-modal/versioning-graph-modal.component.ts
/* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, OnInit, Inject } from '@angular/core'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; import { VersioningGraphModalConfiguration } from './versioning-graph-modal.model'; import { MergableCatalogueItem } from '@maurodatamapper/mdm-resources'; @Component({ selector: 'mdm-versioning-graph-modal', templateUrl: './versioning-graph-modal.component.html', styleUrls: ['./versioning-graph-modal.component.scss'] }) export class VersioningGraphModalComponent implements OnInit { catalogueItem: MergableCatalogueItem; constructor( public dialogRef: MatDialogRef<VersioningGraphModalComponent>, @Inject(MAT_DIALOG_DATA) public data: VersioningGraphModalConfiguration) { } ngOnInit() { this.catalogueItem = this.data.catalogueItem; } }
MauroDataMapper/mdm-ui
src/app/services/youtrack.service.ts
/* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { SharedService } from './shared.service'; import { Observable } from 'rxjs'; import { SecurityHandlerService } from './handlers/security-handler.service'; import { mergeMap } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class YoutrackService { username: string; constructor( private httpClient: HttpClient, private sharedService: SharedService, private securityHandlerService: SecurityHandlerService) { this.username = securityHandlerService.getUserFromLocalStorage()?.firstName + ' ' + securityHandlerService.getUserFromLocalStorage()?.lastName; } reportIssue(summary: string, description: string): Observable<object> { // make sure youTrack is configured return this.getYoutrackProjectId(this.sharedService.youTrack.project) .pipe( mergeMap((data: object) => this.submitIssue(data[0].id, summary, description)) ); } getYoutrackProjectId(shortName: string): Observable<object> { const url = this.sharedService.youTrack.url + '/api/admin/projects?fields=id,name,shortName&query=' + encodeURIComponent(shortName); return this.httpClient.get(url); } submitIssue( projectId: string, summary: string, description: string): Observable<object> { const url = this.sharedService.youTrack.url + '/api/issues'; this.username = this.securityHandlerService.getUserFromLocalStorage()?.firstName + ' ' + this.securityHandlerService.getUserFromLocalStorage()?.lastName; const body = { summary, description, project: { id: projectId }, customFields: [ { value: this.username, name: 'Reporter\'s name', $type: 'SimpleIssueCustomField' }, { value: { name: 'Server', $type: 'OwnedBundleElement' }, name: 'Subsystem', $type: 'SingleOwnedIssueCustomField' } ] }; return this.httpClient.post(url, body); } }
MauroDataMapper/mdm-ui
src/app/model/model-domain-type.ts
/* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ export enum ModelDomainRequestType { folders = 'folder', dataModels = 'dataModel', dataClasses = 'dataClass', dataTypes = 'dataType', terminologies = 'terminology', referenceDataModels = 'referenceDataModel', terms = 'term', Folders = 'folder', DataModels = 'dataModel', DataClasses = 'dataClass', DataTypes = 'dataType', Terminologies = 'terminology', ReferenceDataModels = 'referenceDataModel', Terms = 'term', Folder = 'folder', DataModel = 'dataModel', DataClass = 'dataClass', DataType = 'dataType', Terminology = 'terminology', ReferenceDataModel = 'referenceDataModel', Term = 'term', }
MauroDataMapper/mdm-ui
src/app/shared/mc-data-set-metadata/mc-data-set-metadata.component.ts
<reponame>MauroDataMapper/mdm-ui<filename>src/app/shared/mc-data-set-metadata/mc-data-set-metadata.component.ts /* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, AfterViewInit, Input, ViewChild, ViewChildren, QueryList, EventEmitter, ChangeDetectorRef, } from '@angular/core'; import { MdmResourcesService } from '@mdm/modules/resources'; import { SecurityHandlerService } from '@mdm/services/handlers/security-handler.service'; import { MessageHandlerService } from '@mdm/services/utility/message-handler.service'; import { merge } from 'rxjs'; import { catchError, map, startWith, switchMap } from 'rxjs/operators'; import { MatSort } from '@angular/material/sort'; import { MatInput } from '@angular/material/input'; import { MdmPaginatorComponent } from '../mdm-paginator/mdm-paginator'; import { GridService } from '@mdm/services/grid.service'; import { EditingService } from '@mdm/services/editing.service'; import { Access } from '@mdm/model/access'; @Component({ selector: 'mdm-data-set-metadata', templateUrl: './mc-data-set-metadata.component.html', styleUrls: ['./mc-data-set-metadata.component.scss'], }) export class McDataSetMetadataComponent implements AfterViewInit { @Input() parent: any; @Input() type: 'static' | 'dynamic'; @Input() metaDataItems: any; @Input() loadingData: any; @Input() clientSide: any; @Input() afterSave: any; @Input() domainType: any; @Input() isProfileView = false; @ViewChild(MatSort, { static: true }) sort: MatSort; @ViewChild(MdmPaginatorComponent, { static: true }) paginator: MdmPaginatorComponent; @ViewChildren('filters') filters: QueryList<MatInput>; namespaces: any[]; metadataKeys: any[]; access: Access; loading = false; records: any[]; metadata: any; displayedColumns: string[] = ['namespace', 'key', 'value', 'btns']; hideFilters = true; totalItemCount = 0; isLoadingResults = true; filterEvent = new EventEmitter<any>(); filter: {}; constructor( private resources: MdmResourcesService, private securityHandler: SecurityHandlerService, private messageHandler: MessageHandlerService, private changeDetectorRefs: ChangeDetectorRef, private gridService: GridService, private editingService: EditingService ) { } ngAfterViewInit() { if (this.parent) { this.namespaces = []; this.metadataKeys = []; this.records = []; this.access = this.securityHandler.elementAccess(this.parent); this.changeDetectorRefs.detectChanges(); if (this.type === 'dynamic') { this.loadNamespaces(); this.sort.sortChange.subscribe(() => (this.paginator.pageIndex = 0)); this.filterEvent.subscribe(() => (this.paginator.pageIndex = 0)); merge(this.sort.sortChange, this.paginator.page, this.filterEvent) .pipe( startWith({}), switchMap(() => { this.isLoadingResults = true; this.changeDetectorRefs.detectChanges(); return this.metadataFetch( this.paginator.pageSize, this.paginator.pageOffset, this.sort.active, this.sort.direction, this.filter ); }), map((data: any) => { this.totalItemCount = data.body.count; this.isLoadingResults = false; this.changeDetectorRefs.detectChanges(); return data.body.items; }), catchError((error) => { this.isLoadingResults = false; this.changeDetectorRefs.detectChanges(); this.messageHandler.showError('There was a problem loading the metadata.', error); return []; }) ) .subscribe((data) => { this.records = data; }); } if (this.type === 'static') { this.loading = true; this.loadNamespaces(); this.loadingData.onChange((newValue) => { if (newValue !== null && newValue !== undefined) { this.loading = newValue; } }); this.metaDataItems.onChange((newValue) => { if (newValue !== null && newValue !== undefined) { this.showRecords(); } }); } } } loadNamespaces() { this.resources.metadata .namespaces() .pipe( map((response: any) => response.body.filter((n) => n.defaultNamespace === false)) ) .subscribe( data => this.namespaces = data, errors => this.messageHandler.showError('There was a problem getting the namespace list.', errors)); } metadataFetch(pageSize?, pageIndex?, sortBy?, sortType?, filters?) { const options = this.gridService.constructOptions(pageSize, pageIndex, sortBy, sortType, filters); if(this.isProfileView) { return this.resources.profile.otherMetadata(this.domainType, this.parent.id, options); } else { return this.resources.catalogueItem.listMetadata(this.domainType, this.parent.id, options); } } applyFilter = () => { const filter = {}; this.filters.forEach((x: any) => { const name = x.nativeElement.name; const value = x.nativeElement.value; if (value !== '') { if (name === 'namespace') { filter['ns'] = value; } else { filter[name] = value; } } }); this.filter = filter; this.filterEvent.emit(filter); }; onNamespaceSelect(select, record) { if (select) { record.edit.namespace = select.namespace; record.metadataKeys = []; // now fill the 'metadataKeys' for (const namespace of this.namespaces) { if (namespace.namespace === select.namespace) { record.metadataKeys = namespace.keys; // create object for the keys as mcSelect2 expects objects with id let id = 0; record.metadataKeys = namespace.keys.map((key) => { return { id: id++, key }; }); break; } } } else { record.edit.namespace = ''; record.metadataKeys = []; } } onKeySelect(select, record) { if (select) { record.edit.key = select.key; } else { record.edit.key = ''; } } onEdit(record) { this.editingService.setFromCollection(this.records); // now fill the 'metadataKeys' for (const namespace of this.namespaces) { if (namespace.namespace === record.namespace) { record.metadataKeys = namespace.metadataKeys; break; } } } showRecords() { if (this.metadata) { this.records = [].concat(this.metadata); } } validate = (record, index) => { let isValid = true; record.edit.errors = []; if (this.type === 'static') { if (record.edit.key.trim().length === 0) { record.edit.errors.key = 'Key can\'t be empty!'; isValid = false; } if (record.edit.value.trim().length === 0) { record.edit.errors.value = 'Value can\'t be empty!'; isValid = false; } for (let i = 0; i < this.records.length; i++) { if (i === index) { continue; } if ( this.records[i].key.toLowerCase().trim() === record.edit.key.toLowerCase().trim() && this.records[i].namespace.toLowerCase().trim() === record.edit.namespace.toLowerCase().trim() ) { record.edit.errors.key = 'Key already exists'; isValid = false; } } if (isValid) { delete record.edit.errors; } } else { if (record.edit.key.trim().length === 0) { record.edit.errors.key = 'Key can\'t be empty!'; isValid = false; } if (record.edit.value.trim().length === 0) { record.edit.errors.value = 'Value can\'t be empty!'; isValid = false; } // Call a backend service and see if it's duplicate } return isValid; }; add() { const newRecord = { id: '', namespace: '', key: '', value: '', edit: { id: '', namespace: '', key: '', value: '', }, inEdit: true, isNew: true, }; this.records = [].concat([newRecord]).concat(this.records); this.editingService.setFromCollection(this.records); } cancelEdit(record, index) { if (record.isNew) { this.records.splice(index, 1); this.records = [].concat(this.records); } this.editingService.setFromCollection(this.records); } save(record, index) { const resource = { key: record.edit.key, value: record.edit.value, namespace: record.edit.namespace, }; // if clientSide is true, it should not pass details to the server // this is used in wizard for adding metadata items when creating a new model,class or element if (this.clientSide) { record.namespace = resource.namespace; record.key = resource.key; record.value = resource.value; record.inEdit = false; record.isNew = false; this.records[index] = record; this.metaDataItems = this.records; return; } // in edit mode, we save them here if (record.id && record.id !== '') { this.resources.catalogueItem.updateMetadata(this.domainType, this.parent.id, record.id, resource).subscribe(() => { if (this.afterSave) { this.afterSave(resource); } record.namespace = resource.namespace; record.key = resource.key; record.value = resource.value; record.inEdit = false; this.editingService.setFromCollection(this.records); this.messageHandler.showSuccess('Property updated successfully.'); }, (error) => { // duplicate namespace + key if (error.status === 422) { record.edit.errors = []; record.edit.errors.key = 'Key already exists'; return; } this.messageHandler.showError('There was a problem updating the property.', error); } ); } else { this.resources.catalogueItem.saveMetadata(this.domainType, this.parent.id, resource).subscribe((response) => { // after successfully saving the row, it if is a new row,then remove its newRow property record.id = response.body.id; record.namespace = response.body.namespace; record.key = response.body.key; record.value = response.body.value; record.inEdit = false; this.editingService.setFromCollection(this.records); delete record.edit; if (this.type === 'static') { this.records[index] = record; this.messageHandler.showSuccess('Property saved successfully.'); } else { this.records[index] = record; this.messageHandler.showSuccess('Property saved successfully.'); this.filterEvent.emit(); } }, (error) => { // duplicate namespace + key if (error.status === 422) { record.edit.errors = []; record.edit.errors.key = 'Key already exists'; return; } this.messageHandler.showError('There was a problem saving property.', error); }); } } delete(record, $index) { if (this.clientSide) { this.records.splice($index, 1); this.metaDataItems = this.records; return; } this.resources.catalogueItem.removeMetadata(this.domainType, this.parent.id, record.id).subscribe(() => { if (this.type === 'static') { this.records.splice($index, 1); this.messageHandler.showSuccess('Property deleted successfully.'); } else { this.records.splice($index, 1); this.messageHandler.showSuccess('Property deleted successfully.'); this.filterEvent.emit(); } }, (error) => { this.messageHandler.showError('There was a problem deleting the property.', error); }); } filterClick() { this.hideFilters = !this.hideFilters; } }
MauroDataMapper/mdm-ui
src/app/merge-diff/merge-item-selector/merge-item-selector.component.ts
<filename>src/app/merge-diff/merge-item-selector/merge-item-selector.component.ts /* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, Input, OnInit, Output, EventEmitter } from '@angular/core'; import { MergeDiffItem, MergeDiffType, MergeConflictResolution } from '@maurodatamapper/mdm-resources'; import { MergeDiffItemModel} from '../types/merge-item-type'; @Component({ selector: 'mdm-merge-item-selector', templateUrl: './merge-item-selector.component.html', styleUrls: ['./merge-item-selector.component.scss'] }) export class MergeItemSelectorComponent implements OnInit { @Output() selectedMergeItemChanged = new EventEmitter<MergeDiffItem>(); @Input() mergeItems: MergeDiffItemModel[]; @Input() isCommitting: boolean; changesList: MergeDiffItem[] = []; constructor() {} ngOnInit(): void { } selectedItem(mergeItem: MergeDiffItem) { this.selectedMergeItemChanged.emit( mergeItem); } public get mergeType() { return MergeDiffType; } getBranchSelectedIcon(selected: MergeConflictResolution) { switch (selected) { case MergeConflictResolution.Source: return 'fas fa-file-export'; case MergeConflictResolution.Target: return 'fas fa-file-import'; case MergeConflictResolution.Mixed: return 'fab fa-mixer'; default: return ''; } } getBranchSelectedTooltip(selected: MergeConflictResolution) { switch (selected) { case MergeConflictResolution.Source: return 'Take from Source'; case MergeConflictResolution.Target: return 'Take from Target'; case MergeConflictResolution.Mixed: return 'Mixed/combined content'; default: return ''; } } getMergeTypeTooltip(type: MergeDiffType) { switch (type) { case MergeDiffType.Creation: return 'Created'; case MergeDiffType.Deletion: return 'Deleted'; case MergeDiffType.Modification: return 'Modified'; default: return ''; } } }
MauroDataMapper/mdm-ui
src/app/shared/inline-text-edit/inline-text-edit.component.ts
/* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, OnInit, Input, Output, EventEmitter, forwardRef } from '@angular/core'; import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms'; @Component({ selector: 'mdm-inline-text-edit', templateUrl: './inline-text-edit.component.html', styleUrls: ['./inline-text-edit.component.scss'], providers: [ { provide: NG_VALUE_ACCESSOR, // eslint-disable-next-line @typescript-eslint/no-use-before-define useExisting: forwardRef(() => InlineTextEditComponent), multi: true } ] }) export class InlineTextEditComponent implements ControlValueAccessor, OnInit { @Output() saveClicked = new EventEmitter(); @Output() cancelClicked = new EventEmitter(); @Input() inEditMode: boolean; @Input() readOnly = true; @Input() isRequired: boolean; @Input() styleCss: string; @Input() name: string; @Input() showButtons = false; val: any; constructor() { } get ngValue() { return this.val; } set ngValue(val) { this.val = val; this.propChange(val); } writeValue(obj: any): void { this.ngValue = obj; } registerOnChange(fn: any): void { this.propChange = fn; } // eslint-disable-next-line @typescript-eslint/no-unused-vars registerOnTouched(fn: any): void { } // eslint-disable-next-line @typescript-eslint/no-unused-vars setDisabledState?(isDisabled: boolean): void { } ngOnInit() { if (!this.inEditMode) { this.inEditMode = false; } } save() { this.saveClicked.emit(); } cancel() { this.cancelClicked.emit(); } propChange: any = () => { }; }
MauroDataMapper/mdm-ui
src/app/shared/reference-data-element/reference-data-element.component.ts
/* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, Input, ViewChild, AfterViewInit, ChangeDetectorRef, EventEmitter, Output } from '@angular/core'; import { MdmPaginatorComponent } from '../mdm-paginator/mdm-paginator'; import { MdmResourcesService } from '@mdm/modules/resources/mdm-resources.service'; import { merge } from 'rxjs'; import { catchError, map, startWith, switchMap } from 'rxjs/operators'; import { GridService } from '@mdm/services'; import { CatalogueItem } from '@maurodatamapper/mdm-resources'; @Component({ selector: 'mdm-reference-data-element', templateUrl: './reference-data-element.component.html', styleUrls: ['./reference-data-element.component.scss'] }) export class ReferenceDataElementComponent implements AfterViewInit { @Input() parent: CatalogueItem; @ViewChild(MdmPaginatorComponent, { static: true }) paginator: MdmPaginatorComponent; @Output() totalCount = new EventEmitter<string>(); records: any[] = []; totalItemCount = 0; isLoadingResults = true; displayedColumns = ['name', 'description', 'type']; constructor( private resources: MdmResourcesService, private changeRef: ChangeDetectorRef, private gridService: GridService ) { } ngAfterViewInit(): void { merge(this.paginator.page).pipe(startWith({}), switchMap(() => { this.isLoadingResults = true; this.changeRef.detectChanges(); return this.listDataElements(this.paginator.pageSize, this.paginator.pageOffset); }), map((data: any) => { this.totalItemCount = data.body.count; this.totalCount.emit(String(data.body.count)); this.isLoadingResults = false; return data.body.items; }), catchError(() => { this.isLoadingResults = false; this.changeRef.detectChanges(); return []; })).subscribe(data => { this.records = data; this.isLoadingResults = false; this.changeRef.detectChanges(); }); } listDataElements = (pageSize?, pageIndex?) => { const options = this.gridService.constructOptions(pageSize, pageIndex); return this.resources.referenceDataElement.list(this.parent?.id, options); }; }
MauroDataMapper/mdm-ui
src/app/services/handlers/favourite-handler.service.ts
/* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Injectable } from '@angular/core'; import { UserSettingsHandlerService } from '../utility/user-settings-handler.service'; import { MessageHandlerService } from '../utility/message-handler.service'; import { BroadcastService } from '../broadcast.service'; import { CatalogueItem } from '@maurodatamapper/mdm-resources'; @Injectable({ providedIn: 'root' }) export class FavouriteHandlerService { constructor( private userSettingsHandler: UserSettingsHandlerService, private messageHandler: MessageHandlerService, private broadcast: BroadcastService) { } add(element: CatalogueItem) { const favorites = this.userSettingsHandler.get('favourites'); let fvt = false; favorites.forEach(favorite => { if (favorite.id === element.id) { fvt = true; return; } }); if (!fvt) { favorites.push({ id: element.id, domainType: element.domainType }); } this.userSettingsHandler.update('favourites', favorites); this.userSettingsHandler.saveOnServer().subscribe(() => { this.messageHandler.showSuccess(`${element.domainType} added to Favorites successfully.`); this.broadcast.favouritesChanged({ name: 'add', element }); }, error => { this.messageHandler.showError('There was a problem updating the Favorites.', error); }); return favorites; } get() { return this.userSettingsHandler.get('favourites'); } isAdded(element: CatalogueItem) { const favorites = this.userSettingsHandler.get('favourites'); let fvt = false; favorites.forEach(favorite => { if (favorite.id === element.id) { fvt = true; return; } }); return fvt ? true : false; } remove(element: CatalogueItem) { const favorites = this.userSettingsHandler.get('favourites'); const index = favorites.findIndex(favorite => favorite.id === element.id ); if (index === -1) { return; } favorites.splice(index, 1); this.userSettingsHandler.update('favourites', favorites); this.userSettingsHandler.saveOnServer().subscribe(() => { this.messageHandler.showSuccess('Removed from Favorites successfully.'); this.broadcast.favouritesChanged({ name: 'remove', element }); }, (error) => { this.messageHandler.showError('There was a problem updating the Favorites.', error); }); } toggle(element: CatalogueItem) { const favorites = this.userSettingsHandler.get('favourites'); let processFinish = false; let fvt = false; favorites.forEach(favorite => { if (favorite.id === element.id) { fvt = true; return; } }); if (!fvt) { this.add(element); processFinish = true; } else { this.remove(element); processFinish = true; } return processFinish; } }
MauroDataMapper/mdm-ui
src/app/admin/home/plugins/plugins.component.ts
/* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, OnInit, ElementRef, ViewChildren, ViewChild, AfterViewInit, } from '@angular/core'; import { MessageHandlerService } from '@mdm/services/utility/message-handler.service'; import { MdmResourcesService } from '@mdm/modules/resources'; import { MatPaginator } from '@angular/material/paginator'; import { MatSort } from '@angular/material/sort'; import { MatTableDataSource } from '@angular/material/table'; import { GridService } from '@mdm/services/grid.service'; @Component({ selector: 'mdm-plugins', templateUrl: './plugins.component.html', styleUrls: ['./plugins.component.sass'] }) export class PluginsComponent implements OnInit, AfterViewInit { @ViewChildren('filters', { read: ElementRef }) filters: ElementRef[]; @ViewChild(MatSort, { static: false }) sort: MatSort; @ViewChild(MatPaginator, { static: false }) paginator: MatPaginator; displayedColumns = ['displayName', 'version', 'pluginType']; totalItemCount = 0; hideFilters = true; dataSource = new MatTableDataSource<any>(); constructor( private messageHandler: MessageHandlerService, private resourcesService: MdmResourcesService, private gridService: GridService ) { } ngOnInit() { if (this.sort) { this.sort.sortChange.subscribe(() => this.paginator.pageIndex = 0); } this.requestDataFromMultipleSources(); } ngAfterViewInit() { this.dataSource.sort = this.sort; this.dataSource.paginator = this.paginator; } requestDataFromMultipleSources( pageSize?, pageIndex?, sortBy?, sortType?, filters? ) { const options = this.gridService.constructOptions(pageSize, pageIndex, 'displayName', 'asc', filters); this.resourcesService.provider.importers(options).subscribe(resp => { this.dataSource.data = [...this.dataSource.data, ...resp.body]; this.totalItemCount = this.dataSource.data.length; }, err => { this.messageHandler.showError('There was a problem loading the importers.', err); } ); this.resourcesService.provider.emailers(options).subscribe(resp => { this.dataSource.data = [...this.dataSource.data, ...resp.body]; this.totalItemCount = this.dataSource.data.length; }, err => { this.messageHandler.showError('There was a problem loading the emailers.', err); } ); this.resourcesService.provider.dataLoaders(options).subscribe(resp => { this.dataSource.data = [...this.dataSource.data, ...resp.body]; this.totalItemCount = this.dataSource.data.length; }, err => { this.messageHandler.showError('There was a problem loading the dataLoaders.', err); } ); this.resourcesService.provider.exporters(options).subscribe(resp => { this.dataSource.data = [...this.dataSource.data, ...resp.body]; this.totalItemCount = this.dataSource.data.length; }, (err: any) => { this.messageHandler.showError('There was a problem loading the exporters.', err); }); } // TODO applyFilter = () => { }; }
MauroDataMapper/mdm-ui
src/app/errors/not-authorized/not-authorized.component.ts
/* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, OnInit } from '@angular/core'; import { MessageService } from '@mdm/services/message.service'; import { ClipboardService } from 'ngx-clipboard'; import { YoutrackService } from '@mdm/services/youtrack.service'; import { SharedService } from '@mdm/services/shared.service'; import { ErrorComponent } from '../error.component'; @Component({ selector: 'mdm-not-authorized-error', templateUrl: '../error.component.html', styleUrls: [] }) export class NotAuthorizedComponent extends ErrorComponent implements OnInit { constructor(protected messageService: MessageService, protected clipboardService: ClipboardService, protected sharedService: SharedService, protected youtrackService: YoutrackService) { super(messageService, clipboardService, sharedService, youtrackService); this.errorHeader = 'Not Authorized'; this.errorMessage = 'We\'re sorry, but the server does not allow you to view this page.'; this.errorResolution = 'You may need to check that the item you have requested actually exists, and that you have permission to view it'; this.errorReportMessage = 'Alternatively, if you believe you really should have access to this item, please report the issue to us by using the link below:'; this.dataSource.push({ field: 'Message', value: this.lastError.message, code: false }); this.dataSource.push({ field: 'Status', value: this.lastError.status, code: false }); this.dataSource.push({ field: 'Path', value: this.lastError.url, code: false }); } }
MauroDataMapper/mdm-ui
src/app/admin/home/home.component.ts
<filename>src/app/admin/home/home.component.ts /* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, OnInit } from '@angular/core'; import { StateService } from '@uirouter/core'; import { StateHandlerService } from '@mdm/services/handlers/state-handler.service'; import { SharedService } from '@mdm/services/shared.service'; import { Title } from '@angular/platform-browser'; @Component({ selector: 'mdm-home', templateUrl: './home.component.html', styleUrls: ['./home.component.sass'] }) export class DashboardComponent implements OnInit { activeTab: any; appVersion: string; constructor( private stateService: StateService, private stateHandler: StateHandlerService, private shared: SharedService, private title: Title ) {} ngOnInit() { // tslint:disable-next-line: deprecation this.activeTab = this.getTabDetailByName(this.stateService.params.tabView as string); this.appVersion = this.shared.appVersion; this.title.setTitle('Dashboard'); } tabSelected(itemsName) { const tab = this.getTabDetail(itemsName); this.stateHandler.Go( 'admin/home', { tabView: tab.name }, { notify: false, location: tab.index !== 0 } ); } getTabDetail(tabIndex) { switch (tabIndex) { case 0: return { index: 0, name: 'Active Sessions' }; case 1: return { index: 1, name: 'Plugins & Modules' }; case 2: return { index: 2, name: 'Profiles Dashboard' }; default: return { index: 0, name: 'Active Sessions' }; } } getTabDetailByName(tabName) { switch (tabName) { case 'Active Sessions': return { index: 0, name: 'Active Sessions' }; case 'Plugins & Modules': return { index: 1, name: 'Plugins & Modules' }; case 'Profiles Dashboard': return { index: 2, name: 'Profiles Dashboard' }; default: return { index: 0, name: 'Active Sessions' }; } } }
MauroDataMapper/mdm-ui
src/app/modules/resources/mdm-rest-handler.service.ts
<reponame>MauroDataMapper/mdm-ui /* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { HttpClient, HttpErrorResponse } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { MdmRestHandler, RequestSettings } from '@maurodatamapper/mdm-resources'; import { BroadcastService } from '@mdm/services/broadcast.service'; import { StateHandlerService } from '@mdm/services/handlers/state-handler.service'; import { MessageService } from '@mdm/services/message.service'; import { throwError } from 'rxjs'; import { catchError } from 'rxjs/operators'; /** * An IMdmRestHandler implemented using Angular's HttpClient. */ @Injectable() export class MdmRestHandlerService implements MdmRestHandler { constructor( private messageService: MessageService, private http: HttpClient, private broadcast: BroadcastService, private stateHandler: StateHandlerService) { } process(url: string, options: RequestSettings) { if (options.withCredentials === undefined || options.withCredentials === null || (options.withCredentials !== undefined && options.withCredentials === false)) { throw new Error('withCredentials is not provided!'); } if (options.responseType) { } else { options.responseType = undefined; } options.headers = options.headers || {}; // STOP IE11 from Caching HTTP GET options.headers['Cache-Control'] = 'no-cache'; options.headers.Pragma = 'no-cache'; // For any GET requests that return 4XX response, automatically handle them unless overridden const handleGetErrors: boolean = options?.handleGetErrors ?? true; return this.http.request(options.method, url, { body: options.body, headers: options.headers, withCredentials: options.withCredentials, observe: 'response', responseType: options.responseType }).pipe( catchError((response: HttpErrorResponse) => { if (response.status === 0 || response.status === -1) { this.broadcast.applicationOffline(response); } else if (response.status === 401) { this.messageService.lastError = response; if (options.login === undefined) { this.stateHandler.NotAuthorized(response); } } else if (response.status === 504) { this.messageService.lastError = response; this.stateHandler.ServerTimeout(); } else if (response.status === 404 && options.method === 'GET' && handleGetErrors) { this.messageService.lastError = response; this.stateHandler.NotFound(response); } else if (response.status === 501) { this.messageService.lastError = response; this.stateHandler.NotImplemented(response); } else if (response.status >= 400 && response.status < 500 && options.method === 'GET' && handleGetErrors) { this.messageService.lastError = response; this.stateHandler.NotFound(response); // this.broadcastSvc.broadcast('resourceNotFound', response); } else if (response.status >= 500) { this.messageService.lastError = response; this.stateHandler.ServerError(response); } return throwError(response); }) ); } }
MauroDataMapper/mdm-ui
src/app/wizards/dataElement/data-element-step2/data-element-step2.component.ts
/* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, ElementRef, EventEmitter, OnInit, ViewChild, ViewChildren, ChangeDetectorRef, QueryList, AfterViewInit, OnDestroy } from '@angular/core'; import { merge, Subscription } from 'rxjs'; import { NgForm } from '@angular/forms'; import { MatSort } from '@angular/material/sort'; import { MatPaginator } from '@angular/material/paginator'; import { ValidatorService } from '@mdm/services/validator.service'; import { MdmResourcesService } from '@mdm/modules/resources'; import { McSelectPagination } from '@mdm/utility/mc-select/mc-select.component'; import { MatTableDataSource } from '@angular/material/table'; import { catchError, map, startWith, switchMap } from 'rxjs/operators'; import { MessageHandlerService } from '@mdm/services/utility/message-handler.service'; import { BroadcastService } from '@mdm/services/broadcast.service'; import { GridService } from '@mdm/services/grid.service'; import { CreateType } from '@mdm/wizards/wizards.model'; import { DataClass, DataModel } from '@maurodatamapper/mdm-resources'; @Component({ selector: 'mdm-data-element-step2', templateUrl: './data-element-step2.component.html', styleUrls: ['./data-element-step2.component.sass'] }) export class DataElementStep2Component implements OnInit, AfterViewInit, OnDestroy { @ViewChildren(MatPaginator) paginator = new QueryList<MatPaginator>(); @ViewChild('myForm', { static: false }) myForm: NgForm; @ViewChildren('filters', { read: ElementRef }) filters: ElementRef[]; @ViewChildren(MatSort) sort = new QueryList<MatSort>(); step: any; model: { [key: string]: any; createType: CreateType; selectedDataTypes: Array<any>; parent:DataModel; copyFromDataModel: Array<DataModel>; copyFromDataClass: Array<DataClass>; }; multiplicityError: any; selectedDataClassesStr = ''; defaultCheckedMap: any; loaded = false; error = ''; dataTypeErrors = ''; processing = false; parentScopeHandler: any; hideFiltersSelectedDataTypes = true; totalItemCount = 0; isLoadingResults: boolean; isProcessComplete = false; finalResult = {}; failCount = 0; successCount = 0; formChangesSubscription: Subscription; dataSourceSelectedDataElements = new MatTableDataSource<any>(); dataSourceDataElements = new MatTableDataSource<any>(); filterEvent = new EventEmitter<any>(); filter: {}; hideFilters = true; displayedColumns = ['name', 'description', 'status']; pagination: McSelectPagination; dataSource: any; displayedColumnsDataTypes: string[]; displayedColumnsSelectedDataTypes: string[]; recordsDataElements: any[] = []; isAllChecked = true; checkAllCheckbox = false; totalSelectedItemsCount = 0; pageSize = 20; pageSizeOptions = [5, 10, 20, 50]; constructor( private changeRef: ChangeDetectorRef, private gridService: GridService, private validator: ValidatorService, private resources: MdmResourcesService, private messageHandler: MessageHandlerService, private broadcast: BroadcastService) { this.dataSourceDataElements = new MatTableDataSource(this.recordsDataElements); const settings = JSON.parse(localStorage.getItem('userSettings')); if (settings) { this.pageSize = settings.countPerTable; this.pageSizeOptions = settings.counts; } } ngOnInit() { this.model = this.step.scope.model; this.dataSourceSelectedDataElements = new MatTableDataSource<any>(this.model.selectedDataTypes); } ngAfterViewInit() { this.formChangesSubscription = this.myForm?.form.valueChanges.subscribe(x => { this.validate(x); }); } dataElementsFetch(pageSize, pageIndex, sortBy, sortType, filters) { const options = this.gridService.constructOptions(pageSize, pageIndex, sortBy, sortType, filters); const dataClass : DataClass = this.model.copyFromDataClass[0]; return this.resources.dataElement.list(dataClass.model, dataClass.id, options); } onLoad() { this.defaultCheckedMap = this.model.selectedDataClassesMap; if (this.model.selectedDataClassesMap) { this.createSelectedArray(); this.validate(); } this.loaded = true; this.displayedColumnsDataTypes = ['checkbox', 'label', 'description', 'domainType']; this.displayedColumnsSelectedDataTypes = ['label', 'description', 'domainType', 'status']; if (this.sort !== null && this.sort !== undefined && this.sort.toArray().length > 0 && this.paginator !== null && this.paginator !== undefined && this.paginator.toArray().length > 0) { this.sort.toArray()[0].sortChange.subscribe(() => (this.paginator.toArray()[0].pageIndex = 0)); this.filterEvent.subscribe(() => (this.paginator.toArray()[0].pageIndex = 0)); this.dataSourceDataElements.sort = this.sort.toArray()[0]; this.dataSourceSelectedDataElements.paginator = this.paginator.toArray()[1]; if (this.sort != null && this.sort !== undefined && this.sort.length > 0 && this.paginator != null && this.paginator !== undefined && this.paginator.length > 0) { merge(this.sort.toArray()[0].sortChange, this.paginator.toArray()[0].page, this.filterEvent).pipe(startWith({}), switchMap(() => { this.isLoadingResults = true; return this.dataElementsFetch( this.paginator.toArray()[0].pageSize, this.paginator.toArray()[0].pageIndex * this.paginator.toArray()[0].pageSize, this.sort.toArray()[0].active, this.sort.toArray()[0].direction, this.filter ); }), map((data: any) => { this.totalItemCount = data.body.count; this.isLoadingResults = false; return data.body.items; }), catchError(() => { this.isLoadingResults = false; return []; })).subscribe(data => { this.recordsDataElements = data; this.dataSourceDataElements.data = this.recordsDataElements; // Sorting/paging is making a backend call and looses the checked checkboxes if (this.model.selectedDataElements != null && this.model.selectedDataElements.length > 0) { this.reCheckSelectedDataElements(); } }); } this.validate(); this.loaded = true; } } reCheckSelectedDataElements() { let currentPageSelectedItemsNum = 0; this.model.selectedDataElements.forEach((sdt: any) => { const currentId = sdt.id; const item = this.recordsDataElements.find(r => r.id === currentId); if (item !== null && item !== undefined) { item.checked = true; } // Count how many records are selected in the CURRENT page if (item && item.checked) { currentPageSelectedItemsNum++; } }); // If all the records on the current page are selected, check the "Check All" checkbox if (currentPageSelectedItemsNum === this.paginator.toArray()[0].pageSize) { this.isAllChecked = true; } else { this.isAllChecked = false; } } onCheckAll = () => { this.recordsDataElements.forEach(element => { element.checked = this.checkAllCheckbox; if (this.checkAllCheckbox) { this.model.selectedDataElements.push(element); } else { this.model.selectedDataElements = []; } }); this.validate(); this.dataSourceSelectedDataElements.data = this.model.selectedDataElements; this.totalSelectedItemsCount = this.model.selectedDataElements.length; }; onCheck(record) { if (record.checked) { this.model.selectedDataElements.push(record); } else { const index = this.model.selectedDataElements.findIndex(r => r.id === record.id); if (index !== -1) { this.model.selectedDataElements.splice(index, 1); } } this.validate(); this.dataSourceSelectedDataElements.data = this.model.selectedDataElements; this.totalSelectedItemsCount = this.model.selectedDataElements.length; } toggleShowNewInlineDataType() { this.model.showNewInlineDataType = !this.model.showNewInlineDataType; this.error = ''; this.dataTypeErrors = ''; } createSelectedArray = () => { this.model.selectedDataClasses = []; for (const id in this.model.selectedDataClassesMap) { if (this.model.selectedDataClassesMap.hasOwnProperty(id)) { const element = this.model.selectedDataClassesMap[id]; this.model.selectedDataClasses.push(element.node); } } }; validate = (newValue?) => { let invalid = false; this.step.invalid = false; if (newValue && ['copy', 'import'].includes(this.model.createType)) { // check Min/Max this.multiplicityError = this.validator.validateMultiplicities(newValue.minMultiplicity, newValue.maxMultiplicity); // Check Mandatory fields if (!newValue.label || newValue.label.trim().length === 0 || this.multiplicityError) { this.step.invalid = true; return; } if (!this.model.showNewInlineDataType && !this.model.dataType) { this.step.invalid = true; return; } invalid = this.myForm.invalid; } if (['copy', 'import'].includes(this.model.createType)) { if (this.model.selectedDataElements.length === 0) { this.step.invalid = true; return; } } this.step.invalid = invalid; }; ngOnDestroy() { this.formChangesSubscription.unsubscribe(); } fetchDataTypes = (text, loadAll, offset, limit) => { const options = this.gridService.constructOptions(limit, offset, 'label', 'asc', {label: text}); this.pagination = { // tslint:disable-next-line: no-string-literal limit: options['limit'], // tslint:disable-next-line: no-string-literal offset: options['offset'] }; this.changeRef.detectChanges(); if (loadAll) { // tslint:disable-next-line: no-string-literal delete options['label']; } return this.resources.dataType.list(this.model.parent.id, options); }; onTargetSelect = (selectedValue) => { this.model.dataType = selectedValue; this.validate(this.model); }; applyFilter = () => { const filter = {}; this.filters.forEach((x: any) => { const name = x.nativeElement.name; const value = x.nativeElement.value; if (value !== '') { filter[name] = value; } }); this.filter = filter; this.filterEvent.emit(filter); }; validationStatusEmitter($event) { this.step.invalid = JSON.parse($event); } filterClick = () => { this.hideFilters = !this.hideFilters; }; filterClickSelectedDataTypes = () => { this.hideFiltersSelectedDataTypes = !this.hideFiltersSelectedDataTypes; }; saveCopiedDataClasses = () => { this.processing = true; this.isProcessComplete = false; this.failCount = 0; this.successCount = 0; let promise = Promise.resolve(); this.model.selectedDataElements.forEach((dc: any) => { promise = promise.then((result: any) => { this.successCount++; this.finalResult[dc.id] = { result, hasError: false }; switch (this.model.createType) { case 'copy': return this.resources.dataElement.copyDataElement(this.model.parentDataModel.id, this.model.parentDataClass.id, dc.model, dc.dataClass, dc.id, null).toPromise(); case 'import': return this.resources.dataClass.importDataElement(this.model.parentDataModel.id, this.model.parentDataClass.id, dc.model, dc.dataClass, dc.id, null).toPromise(); } }).catch(error => { this.failCount++; const errorText = this.messageHandler.getErrorText(error); this.finalResult[dc.id] = { result: errorText, hasError: true }; }); }); promise.then(() => { this.processing = false; this.isProcessComplete = true; this.broadcast.reloadCatalogueTree(); }).catch(() => { this.processing = false; this.isProcessComplete = true; }); }; }
MauroDataMapper/mdm-ui
src/app/admin/subscribed-catalogue/subscribed-catalogue.component.ts
/* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, OnInit } from '@angular/core'; import { Title } from '@angular/platform-browser'; import { SubscribedCatalogue, SubscribedCatalogueResponse, Uuid } from '@maurodatamapper/mdm-resources'; import { MdmResourcesService } from '@mdm/modules/resources'; import { MessageHandlerService, SharedService, StateHandlerService } from '@mdm/services'; import { EditingService } from '@mdm/services/editing.service'; import { UIRouterGlobals } from '@uirouter/core'; interface SubscribedCatalogueComponentErrors { label?: string; url?: string; apiKey?: string; } @Component({ selector: 'mdm-subscribed-catalogue', templateUrl: './subscribed-catalogue.component.html', styleUrls: ['./subscribed-catalogue.component.scss'] }) export class SubscribedCatalogueComponent implements OnInit { catalogue: SubscribedCatalogue; errors: SubscribedCatalogueComponentErrors; isCreating: boolean; constructor( private resources: MdmResourcesService, private routerGobals: UIRouterGlobals, private stateHandler: StateHandlerService, private shared: SharedService, private messageHandler: MessageHandlerService, private title: Title, private editingService: EditingService) { } ngOnInit(): void { if (!this.shared.features.useSubscribedCatalogues) { this.stateHandler.Go('alldatamodel'); return; } this.editingService.start(); const catalogueId : Uuid = this.routerGobals.params.id; if (catalogueId) { this.isCreating = false; this.title.setTitle('Subscribed Catalogue - Edit Subscription'); this.resources.admin .getSubscribedCatalogue(catalogueId) .subscribe( (data: SubscribedCatalogueResponse) => this.catalogue = data.body, error => { this.messageHandler.showError('Unable to get the subscribed catalogue.', error); this.navigateToParent(); }); } else { this.isCreating = true; this.title.setTitle('Subscribed Catalogue - Add Subscription'); this.catalogue = { label: '', url: '' }; } } save() { if (!this.validate()) { return; } if (this.catalogue.id) { this.resources.admin .updateSubscribedCatalogue(this.catalogue.id, this.catalogue) .subscribe( () => { this.messageHandler.showSuccess('Subscribed catalogue updated successfully.'); this.navigateToParent(); }, error => this.messageHandler.showError('There was a problem updating the subscribed catalogue.', error)); } else { this.resources.admin .saveSubscribedCatalogues(this.catalogue) .subscribe( () => { this.messageHandler.showSuccess('Subscribed catalogue saved successfully.'); this.navigateToParent(); }, error => this.messageHandler.showError('There was a problem saving the subscribed catalogue.', error)); } } cancel() { this.editingService.confirmCancelAsync().subscribe(confirm => { if (confirm) { this.navigateToParent(); } }); } validate() { let isValid = true; this.errors = {}; if (this.catalogue.label.trim().length === 0) { this.errors.label = 'Label cannot be empty'; isValid = false; } if (this.catalogue.url.trim().length === 0) { this.errors.url = 'URL cannot be empty'; isValid = false; } return isValid; } private navigateToParent() { this.editingService.stop(); this.stateHandler.Go('appContainer.adminArea.subscribedCatalogues'); } }
MauroDataMapper/mdm-ui
src/app/directives/file-size.pipe.ts
/* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'fileSize' }) export class FileSizePipe implements PipeTransform { transform(bytes : any, precision? : number): string { if (isNaN(parseFloat(bytes)) || !isFinite(bytes)) { return '-'; } if (typeof precision === 'undefined') { precision = 1; } const units = ['bytes', 'kB', 'MB', 'GB', 'TB', 'PB']; const num = Math.floor(Math.log(bytes) / Math.log(1024)); return ((bytes / Math.pow(1024, Math.floor(num))).toFixed(precision) + ' ' + units[num]); } }
MauroDataMapper/mdm-ui
src/app/wizards/dataClass/data-class-step1/data-class-step1.component.ts
/* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import {Component, OnInit, ChangeDetectorRef} from '@angular/core'; @Component({ selector: 'mdm-data-class-step1', templateUrl: './data-class-step1.component.html', styleUrls: ['./data-class-step1.component.sass'] }) export class DataClassStep1Component implements OnInit { step: any; modelVal: any; constructor(private changeRef: ChangeDetectorRef) {} get model() { return this.modelVal; } set model(val) { this.modelVal = val; this.validate(); } ngOnInit() { this.model = this.step.scope.model; } onSelect = dataModel => { this.model.copyFromDataModel = dataModel; this.model.selectedDataTypes = []; this.model.selectedDataClassesMap = []; this.validate(); }; validate = () => { if (!this.model.createType) { this.step.invalid = true; return; } if (['copy', 'import', 'extend'].includes(this.model.createType) && this.model.copyFromDataModel.length === 0) { this.step.invalid = true; return; } this.step.invalid = false; }; selectCreateType = createType => { this.model.createType = createType; this.validate(); }; }
MauroDataMapper/mdm-ui
src/app/doi-redirect/doi-redirect.component.ts
/* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, OnInit } from '@angular/core'; import { CatalogueItemDomainType, DataClass, DataElement, DataType, DoiResolvedItem, DoiResolvedItemResponse, isDataType, Term } from '@maurodatamapper/mdm-resources'; import { MdmResourcesService } from '@mdm/modules/resources'; import { StateHandlerService } from '@mdm/services'; import { UIRouterGlobals } from '@uirouter/core'; import { EMPTY } from 'rxjs'; import { catchError, finalize } from 'rxjs/operators'; @Component({ selector: 'mdm-doi-redirect', templateUrl: './doi-redirect.component.html', styleUrls: ['./doi-redirect.component.scss'] }) export class DoiRedirectComponent implements OnInit { identifier: string; resolving = true; errorMessage: string; constructor( private uiRouterGlobals: UIRouterGlobals, private stateHandler: StateHandlerService, private resources: MdmResourcesService) { } ngOnInit(): void { this.identifier = this.uiRouterGlobals.params.id; if (!this.identifier) { this.stateHandler.Go('home'); return; } this.resources.pluginDoi .resolve(this.identifier) .pipe( catchError(error => { this.errorMessage = error; return EMPTY; }), finalize(() => this.resolving = false) ) .subscribe((response: DoiResolvedItemResponse) => { this.redirectToItem(response.body); }); } private redirectToItem(item: DoiResolvedItem) { const params: any = { id: item.id }; let state: string = item.domainType; if (item.domainType === CatalogueItemDomainType.DataClass) { const dataClass = item as DataClass; params.dataModelId = dataClass.model; params.dataClassId = dataClass.dataClass ?? ''; } else if (item.domainType === CatalogueItemDomainType.DataElement) { const dataElement = item as DataElement; params.dataModelId = dataElement.model; params.dataClassId = dataElement.dataClass; } else if (isDataType(item.domainType)) { const dataType = item as DataType; params.dataModelId = dataType.model; state = 'appContainer.mainApp.twoSidePanel.catalogue.dataType'; } else if (item.domainType === CatalogueItemDomainType.Term) { const term = item as Term; params.terminologyId = term.model; } this.stateHandler .Go(state, params) .catch(error => { this.errorMessage = `Unable to redirect to ${item.domainType} ${item.id}. ${error}`; }); } }
MauroDataMapper/mdm-ui
src/app/services/editing.service.ts
<filename>src/app/services/editing.service.ts<gh_stars>1-10 /* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { ComponentType } from '@angular/cdk/portal'; import { Injectable, TemplateRef } from '@angular/core'; import { MatDialog, MatDialogConfig, MatDialogRef } from '@angular/material/dialog'; import { MatTab, MatTabGroup, MatTabHeader } from '@angular/material/tabs'; import { ModalDialogStatus } from '@mdm/constants/modal-dialog-status'; import { Observable, of } from 'rxjs'; import { map, switchMap } from 'rxjs/operators'; import '@mdm/utility/extensions/mat-dialog.extensions'; const editableRouteNames = [ 'appContainer.mainApp.twoSidePanel.catalogue.dataModel', 'appContainer.mainApp.twoSidePanel.catalogue.dataClass', 'appContainer.mainApp.twoSidePanel.catalogue.classification', 'appContainer.mainApp.twoSidePanel.catalogue.codeSet', 'appContainer.mainApp.twoSidePanel.catalogue.dataType', 'appContainer.mainApp.twoSidePanel.catalogue.dataElement', 'appContainer.mainApp.twoSidePanel.catalogue.folder', 'appContainer.mainApp.twoSidePanel.catalogue.versionedFolder', 'appContainer.mainApp.twoSidePanel.catalogue.ReferenceDataModel', 'appContainer.adminArea.user', 'appContainer.adminArea.group', 'appContainer.adminArea.subscribedCatalogue' ]; export interface EditableObject { inEdit?: boolean; } /** * Service to manage global editing state of the application. * * Used to track when editing is happening and to confirm whether it is safe to leave views/editors during edits. */ @Injectable({ providedIn: 'root' }) export class EditingService { private _isEditing = false; constructor(private dialog: MatDialog) { } /** * Mark the application as starting edits. */ start(): void { this._isEditing = true; } /** * Mark the application as stopping edits. */ stop(): void { this._isEditing = false; } /** * Determine if something in the application is editing currently. */ isEditing = () => this._isEditing; /** * Determine if a route is allowed to be edited and should be checked before transitioning out of the view. * * @param name The name of the route */ isRouteEditable = (name: string) => editableRouteNames.indexOf(name) !== -1; /** * Mark the application as being in edit mode if any item in the given collection states it is being edited. * * @param items Array of `EditableObject` items which should contain an `inEdit` property */ setFromCollection(items: Array<EditableObject>) { if (!items) { return; } this._isEditing = items.some(item => item.inEdit); } /** * Set a custom click event handler to a `MatTabGroup` to add confirmation to each tab click. * * @param tabGroup The `MatTabGroup` to modify. * * The `MatTabGroup` responds to click events when a tab is clicked but does not provide the ability * to cancel that click event. For the case when something is still being edited, the cancellation of a tab click * is important. * * A custom click event handler is therefore attached to intercept the click event and first check if editing is in * place. If not or the user allows the transition, the original tab click event will be carried out. */ setTabGroupClickEvent(tabGroup: MatTabGroup) { tabGroup._handleClick = (tab: MatTab, tabHeader: MatTabHeader, index: number) => { this.confirmCancelAsync().subscribe(confirm => { if (confirm) { // Manually stop "editing" so that other transition hooks don't trigger another confirmation message this.stop(); MatTabGroup.prototype._handleClick.apply(tabGroup, [tab, tabHeader, index]); } }); }; } isTabGroupClickEventHandled(tabGroup: MatTabGroup): boolean { return !!tabGroup && tabGroup._handleClick !== null; } /** * Configure a `MatDialogRef` to handle editing state tracking and confirmations. * * @param dialogRef The `MatDialogRef` to configure * * Configuring the dialog will involve the following: * * * Subscribing to the `afterOpened()` observable to track state after opening * * Subscribing to the `afterClosed()` observable to track state after closing * * Subscribing to the `backdropClick()` observable to confirm if the dialog should be closed * * Use this function if a dialog contains any component that edit data to ensure that editing state is * correctly maintained for the duration of the dialog. */ configureDialogRef<T, R>(dialogRef: MatDialogRef<T, R>) { dialogRef.afterOpened().subscribe(() => this.start()); dialogRef.afterClosed().subscribe(() => this.stop()); dialogRef.disableClose = true; dialogRef .backdropClick() .pipe( switchMap(() => this.confirmCancelAsync()) ) .subscribe(confirm => { if (confirm) { dialogRef.close(); } }); } /** * Open an Angular Material dialog which will be configured to handle editing state tracking and confirmations. * * @param componentOrTemplateRef The component or template to display in the dialog. * @param config The dialog configuration. * * @returns The `MatDialogRef<T, R>` that can be used to subscribe to events when the dialog closes. * * @see configureDialogRef() */ openDialog<T, D = any, R = any>(componentOrTemplateRef: ComponentType<T> | TemplateRef<T>, config?: MatDialogConfig<D>): MatDialogRef<T, R> { const dialogRef = this.dialog.open(componentOrTemplateRef, config); this.configureDialogRef(dialogRef); return dialogRef; } /** * Confirm if it is safe to leave a view to transition to another. * * @returns True if confirmation was provided. * * **Note:** This confirmation uses the browser `alert()` synchronously. To use the Angular Material confirmation dialog, * use `confirmLeaveAsync()`. * * @see confirmLeaveAsync() */ confirmLeave = (): boolean => this.confirmStop('Are you sure you want to leave this view? Any unsaved changes will be lost.'); /** * Confirm if it is safe to leave a view to transition to another asynchronously. * * @returns An `Observable<boolean>` to subscribe to. If the next value is true, then confirmation was provided. * * This confirmation uses the Angular Material `MatDialog` which returns observables. If it is essential to have the * confirmation run synchronously, use the `confirmLeave()` function instead. * * @see confirmLeave() */ confirmLeaveAsync = (): Observable<boolean> => this.confirmStopAsync('Are you sure you want to leave this view? Any unsaved changes will be lost.'); /** * Confirm if it is safe to leave a view to transition to another asynchronously. * * @returns An `Observable<boolean>` to subscribe to. If the next value is true, then confirmation was provided. * * This confirmation uses the Angular Material `MatDialog` which returns observables. */ confirmCancelAsync = (): Observable<boolean> => this.confirmStopAsync('Are you sure you want to cancel? Any unsaved changes will be lost.'); private confirmStop(message: string): boolean { if (!this._isEditing) { return true; } return confirm(message); } private confirmStopAsync(message: string): Observable<boolean> { if (!this._isEditing) { return of(true); } return this.dialog .openConfirmation({ data: { title: 'Confirmation', message, okBtnTitle: 'Yes', cancelBtnTitle: 'No' }, disableClose: true }) .afterClosed() .pipe( map(result => result.status === ModalDialogStatus.Ok) ); } }
MauroDataMapper/mdm-ui
src/app/utility/mc-paged-list/mc-paged-list.component.ts
<gh_stars>1-10 /* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, OnInit, Input, ViewChild, ElementRef, ContentChild, TemplateRef, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'mdm-paged-list', templateUrl: './mc-paged-list.component.html', styleUrls: ['./mc-paged-list.component.sass'] }) export class McPagedListComponent implements OnInit { fetchMethod: any; // when it's 'type=dynamic' editBtnTooltip: any; editBtnText: any; doNotDisplayTitle: any; currentPage = 0; disablePrev = false; disableNext = false; total = 0; displayItems: any[]; displayValues: any[]; constructor() {} @ViewChild('displayItemsDiv', { static: false }) displayItemsDiv: ElementRef; @ContentChild('pageListTemplate', { static: true }) pageListTemplateTmpl: TemplateRef<any>; @Input() type: any; // static,dynamic @Input() name: string; @Input() mcTitle: string; @Output() itemsChange = new EventEmitter(); @Input() pageSize: number; itemValues: any; @Input() get items() { return this.itemValues; } set items(val) { this.itemValues = val; if (val === null || val === undefined) { this.itemValues = null; } else { this.itemValues = val; } this.itemsChange.emit(this.itemValues); this.ngOnInit(); } ngOnInit() { if (this.type === 'static') { this.total = this.items.length; this.displayItems = Object.assign([], this.items); if (this.total < this.pageSize) { this.disablePrev = true; this.disableNext = true; this.currentPage = 0; } this.addToUI(); } if (this.type === 'dynamic') { this.fetchData(); } } addToUI = () => { if (this.type === 'static') { const tempValues = []; const start = this.pageSize * this.currentPage; for (let i = start; i < start + this.pageSize, 10 && i < this.total; i++) { tempValues.push(this.displayItems[i]); } this.displayValues = tempValues; } else { const tempValues = []; for (let i = 0; this.displayItems && i < this.displayItems.length; i++) { tempValues.push(this.displayItems[i]); } this.displayValues = tempValues; } this.disableNext = false; const pageCount = Math.floor(this.total / this.pageSize); const lastPage = Math.floor(this.total % this.pageSize) > 0 ? 1 : 0; if (this.currentPage + 1 >= pageCount + lastPage) { this.disableNext = true; } this.disablePrev = false; if (this.currentPage === 0) { this.disablePrev = true; } }; fetchData = () => { const offset = this.currentPage * this.pageSize; this.fetchMethod(offset, this.pageSize).subscribe(result => { this.total = result.count; this.displayItems = Object.assign([], result.items); if (this.total < this.pageSize) { this.disablePrev = true; this.disableNext = true; this.currentPage = 0; } this.addToUI(); }); }; next = () => { const pageCount = Math.floor(this.total / this.pageSize); const lastPage = Math.floor(this.total % this.pageSize) > 0 ? 1 : 0; if (this.currentPage + 1 >= pageCount + lastPage) { return; } this.currentPage = this.currentPage + 1; if (this.type === 'static') { this.addToUI(); } else { this.fetchData(); } }; prev = () => { if (this.currentPage === 0) { return; } this.currentPage = this.currentPage - 1; if (this.type === 'static') { this.addToUI(); } else { this.fetchData(); } }; }
MauroDataMapper/mdm-ui
src/app/admin/openid-connect-provider/openid-connect-provider.model.ts
<filename>src/app/admin/openid-connect-provider/openid-connect-provider.model.ts<gh_stars>1-10 /* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { FormControl, FormGroup, Validators } from '@angular/forms'; import { OpenIdAuthorizationEndpointParametersPayload, OpenIdConnectProviderDetail, OpenIdConnectProviderUpdatePayload } from '@maurodatamapper/mdm-resources'; import { MdmValidators } from '@mdm/utility/mdm-validators'; export class OpenIdConnectProviderForm { group: FormGroup; /* eslint-disable @typescript-eslint/unbound-method */ constructor(provider?: OpenIdConnectProviderDetail) { this.group = new FormGroup({ label: new FormControl(provider?.label, [ Validators.required ]), imageUrl: new FormControl(provider?.imageUrl, [ MdmValidators.url ]), security: new FormGroup({ clientId: new FormControl(provider?.clientId, [ Validators.required ]), clientSecret: new FormControl(provider?.clientSecret, [ Validators.required ]) }), discovery: new FormGroup({ standardProvider: new FormControl(provider?.standardProvider ?? true), discoveryDocumentUrl: new FormControl(provider?.discoveryDocumentUrl, [ MdmValidators.requiredConditional(() => this.useStandardProvider), MdmValidators.url ]), issuer: new FormControl(provider?.discoveryDocument?.issuer, [ MdmValidators.requiredConditional(() => !this.useStandardProvider), MdmValidators.url ]), authorizationEndpoint: new FormControl(provider?.discoveryDocument?.authorizationEndpoint, [ MdmValidators.requiredConditional(() => !this.useStandardProvider), MdmValidators.url ]), tokenEndpoint: new FormControl(provider?.discoveryDocument?.tokenEndpoint, [ MdmValidators.requiredConditional(() => !this.useStandardProvider), MdmValidators.url ]), userinfoEndpoint: new FormControl(provider?.discoveryDocument?.userinfoEndpoint, [ MdmValidators.url ]), endSessionEndpoint: new FormControl(provider?.discoveryDocument?.endSessionEndpoint, [ MdmValidators.url ]), jwksUri: new FormControl(provider?.discoveryDocument?.jwksUri, [ MdmValidators.requiredConditional(() => !this.useStandardProvider), MdmValidators.url ]), }), authorizationEndpointParams: new FormGroup({ scope: new FormControl(provider?.authorizationEndpointParameters?.scope ?? 'openid email profile'), responseType: new FormControl(provider?.authorizationEndpointParameters?.responseType ?? 'code'), responseMode: new FormControl(provider?.authorizationEndpointParameters?.responseMode), display: new FormControl(this.handleDropdownValue(provider?.authorizationEndpointParameters?.display)), prompt: new FormControl(this.handleDropdownValue(provider?.authorizationEndpointParameters?.prompt)), maxAge: new FormControl(provider?.authorizationEndpointParameters?.maxAge), uiLocales: new FormControl(provider?.authorizationEndpointParameters?.uiLocales), idTokenHint: new FormControl(provider?.authorizationEndpointParameters?.idTokenHint), loginHint: new FormControl(provider?.authorizationEndpointParameters?.loginHint), acrValues: new FormControl(provider?.authorizationEndpointParameters?.acrValues) }) }); // When the standardProvider field is changed, update the conditional validity of related // fields this.standardProvider.valueChanges.subscribe(() => { this.discoveryDocumentUrl.updateValueAndValidity(); this.issuer.updateValueAndValidity(); this.authorizationEndpoint.updateValueAndValidity(); this.tokenEndpoint.updateValueAndValidity(); this.jwksUri.updateValueAndValidity(); }); } /* eslint-enable @typescript-eslint/unbound-method */ get label() { return this.group.get('label'); } get imageUrl() { return this.group.get('imageUrl'); } get clientId() { return this.group.get('security.clientId'); } get clientSecret() { return this.group.get('security.clientSecret'); } get standardProvider() { return this.group?.get('discovery.standardProvider'); } get useStandardProvider(): boolean { return this.standardProvider?.value; } get discoveryDocumentUrl() { return this.group.get('discovery.discoveryDocumentUrl'); } get issuer() { return this.group.get('discovery.issuer'); } get authorizationEndpoint() { return this.group.get('discovery.authorizationEndpoint'); } get tokenEndpoint() { return this.group.get('discovery.tokenEndpoint'); } get userinfoEndpoint() { return this.group.get('discovery.userinfoEndpoint'); } get endSessionEndpoint() { return this.group.get('discovery.endSessionEndpoint'); } get jwksUri() { return this.group.get('discovery.jwksUri'); } createPayload(): OpenIdConnectProviderUpdatePayload { if (this.useStandardProvider) { return { label: this.label.value, clientId: this.clientId.value, clientSecret: this.clientSecret.value, imageUrl: this.imageUrl.value, authorizationEndpointParameters: this.createAuthorizationEndpointParametersPayload(), standardProvider: true, discoveryDocumentUrl: this.discoveryDocumentUrl.value }; } else { return { label: this.label.value, clientId: this.clientId.value, clientSecret: this.clientSecret.value, imageUrl: this.imageUrl.value, authorizationEndpointParameters: this.createAuthorizationEndpointParametersPayload(), standardProvider: false, discoveryDocument: { issuer: this.issuer.value, authorizationEndpoint: this.authorizationEndpoint.value, tokenEndpoint: this.tokenEndpoint.value, jwksUri: this.jwksUri.value, userinfoEndpoint: this.userinfoEndpoint.value, endSessionEndpoint: this.endSessionEndpoint.value } }; } } private createAuthorizationEndpointParametersPayload(): OpenIdAuthorizationEndpointParametersPayload { return { scope: this.group.get('authorizationEndpointParams.scope').value , responseType: this.group.get('authorizationEndpointParams.responseType').value, responseMode: this.group.get('authorizationEndpointParams.responseMode').value, display: this.group.get('authorizationEndpointParams.display').value === undefined ? null : this.group.get('authorizationEndpointParams.display').value, prompt: this.group.get('authorizationEndpointParams.prompt').value === undefined ? null : this.group.get('authorizationEndpointParams.prompt').value, maxAge: this.group.get('authorizationEndpointParams.maxAge').value, uiLocales: this.group.get('authorizationEndpointParams.uiLocales').value, idTokenHint: this.group.get('authorizationEndpointParams.idTokenHint').value, loginHint: this.group.get('authorizationEndpointParams.loginHint').value, acrValues: this.group.get('authorizationEndpointParams.acrValues').value }; } private handleDropdownValue(value: string) { if(value !== undefined) { return value.toUpperCase(); } return value; } }
MauroDataMapper/mdm-ui
src/app/shared/default-profile/default-profile.component.ts
/* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, Input, OnInit } from '@angular/core'; import { CatalogueItem } from '@maurodatamapper/mdm-resources'; import { DefaultProfileControls } from '@mdm/model/defaultProfileModel'; @Component({ selector: 'mdm-default-profile', templateUrl: './default-profile.component.html' }) export class DefaultProfileComponent implements OnInit { @Input() catalogueItem: CatalogueItem & { [key: string]: any }; controls: Array<string>; constructor() {} ngOnInit(): void { this.controls = DefaultProfileControls.renderControls( this.catalogueItem.domainType ); } isInControlList(control: string): boolean { return this.controls.findIndex((x) => x === control) !== -1; } }
MauroDataMapper/mdm-ui
src/app/classification/classification.component.ts
<reponame>MauroDataMapper/mdm-ui /* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, OnInit, Input, OnDestroy, ViewChild, AfterViewInit } from '@angular/core'; import { Subscription } from 'rxjs'; import { MdmResourcesService } from '@mdm/modules/resources'; import { MessageService } from '../services/message.service'; import { SharedService } from '../services/shared.service'; import { UIRouterGlobals } from '@uirouter/core'; import { StateHandlerService } from '../services/handlers/state-handler.service'; import { Title } from '@angular/platform-browser'; import { MatTabGroup } from '@angular/material/tabs'; import { EditingService } from '@mdm/services/editing.service'; import { MessageHandlerService } from '@mdm/services'; import { TabCollection } from '@mdm/model/ui.model'; import { CatalogueItemDomainType, ClassifierDetail, ClassifierDetailResponse, SecurableDomainType, Uuid } from '@maurodatamapper/mdm-resources'; import { DefaultProfileItem } from '@mdm/model/defaultProfileModel'; import { BaseComponent } from '@mdm/shared/base/base.component'; @Component({ selector: 'mdm-classification', templateUrl: './classification.component.html', styleUrls: ['./classification.component.sass'] }) export class ClassificationComponent extends BaseComponent implements OnInit, AfterViewInit, OnDestroy { @ViewChild('tab', { static: false }) tabGroup: MatTabGroup; @Input() afterSave: any; @Input() editMode = false; @Input() mcClassification; classifier = null; result: ClassifierDetail; showSecuritySection: boolean; subscription: Subscription; showSearch = false; parentId: string; activeTab: number; catalogueItemsCount: any; terminologiesCount: any; termsCount: any; codeSetsCount: any; loading = false; catalogueItems: any; tabs = new TabCollection(['description', 'classifiedElements', 'annotations', 'history']); annotationsView = 'default'; descriptionView = 'default'; constructor( private resourcesService: MdmResourcesService, private messageService: MessageService, private sharedService: SharedService, private uiRouterGlobals: UIRouterGlobals, private stateHandler: StateHandlerService, private title: Title, private editingService: EditingService, private messageHandler: MessageHandlerService) { super(); } ngOnInit() { if (!this.uiRouterGlobals.params.id) { this.stateHandler.NotFound({ location: false }); return; } if (this.uiRouterGlobals.params.edit === 'true') { this.editMode = true; } this.title.setTitle('Classifier'); this.classifierDetails(this.uiRouterGlobals.params.id as string); this.subscription = this.messageService.changeUserGroupAccess.subscribe( (message: boolean) => { this.showSecuritySection = message; } ); this.subscription = this.messageService.changeUserGroupAccess.subscribe( (message: boolean) => { this.showSecuritySection = message; } ); this.subscription = this.messageService.changeSearch.subscribe( (message: boolean) => { this.showSearch = message; } ); this.afterSave = (result: { body: { id: Uuid } }) => this.classifierDetails(result.body.id); this.activeTab = this.tabs.getByName(this.uiRouterGlobals.params.tabView as string).index; this.tabSelected(this.activeTab); } ngAfterViewInit(): void { this.editingService.setTabGroupClickEvent(this.tabGroup); } classifierDetails(id: Uuid) { this.resourcesService.classifier .get(id) .subscribe((response: ClassifierDetailResponse) => { this.result = response.body; this.result.domainType = CatalogueItemDomainType.Classifier; this.catalogueItem = this.result; this.parentId = this.result.id; // Will Be added later // this.ClassifierUsedProfiles(this.result.id); // this.ClassifierUnUsedProfiles(this.result.id); if (this.sharedService.isLoggedIn(true)) { this.classifierPermissions(id); } else { this.messageService.FolderSendMessage(this.result); this.messageService.dataChanged(this.result); } }); } classifierPermissions(id: Uuid) { this.resourcesService.security .permissions(SecurableDomainType.Classifiers, id) .subscribe((permissions: { body: { [x: string]: any } }) => { Object.keys(permissions.body).forEach((attrname) => { this.result[attrname] = permissions.body[attrname]; }); // Send it to message service to receive in child components this.messageService.FolderSendMessage(this.result); this.messageService.dataChanged(this.result); }); } toggleShowSearch() { this.messageService.toggleSearch(); } ngOnDestroy() { if (this.subscription) { // unsubscribe to ensure no memory leaks this.subscription.unsubscribe(); } } tabSelected(index: number) { const tab = this.tabs.getByIndex(index); this.stateHandler.Go('classification', { tabView: tab.name }, { notify: false }); } save(saveItems: Array<DefaultProfileItem>) { const resource = { id: this.result.id }; saveItems.forEach((item: DefaultProfileItem) => { resource[item.propertyName] = item.value; }); this.resourcesService.classifier.update(this.result.id, resource).subscribe( (result: ClassifierDetailResponse) => { this.messageHandler.showSuccess('Classifier updated successfully.'); this.editingService.stop(); this.result = result.body; this.catalogueItem = result.body; }, (error) => { this.messageHandler.showError( 'There was a problem updating the Classifier.', error ); } ); } }
MauroDataMapper/mdm-ui
src/app/utility/new-data-type-inline/new-data-type-inline.component.ts
/* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, OnInit, Input, Output, EventEmitter, ViewChild, AfterViewInit } from '@angular/core'; import { MdmResourcesService } from '@mdm/modules/resources'; import { ElementTypesService } from '@mdm/services/element-types.service'; import { NgForm } from '@angular/forms'; import { Subscription } from 'rxjs'; import { CodeSet, CodeSetIndexResponse, ReferenceDataModel, ReferenceDataModelIndexResponse, Terminology, TerminologyIndexResponse } from '@maurodatamapper/mdm-resources'; @Component({ selector: 'mdm-data-type-inline', templateUrl: './new-data-type-inline.component.html', styleUrls: ['./new-data-type-inline.component.sass'] }) export class NewDataTypeInlineComponent implements OnInit, AfterViewInit { @Output() validationStatusEvent = new EventEmitter<string>(); @Input() parentDataModel; @Input() showParentDataModel = false; @Input() showClassification = false; @ViewChild('myFormNewDataType', { static: false }) myFormNewDataType: NgForm; @Input() model: any = { label: '', description: '', domainType: '', referencedDataClass: '', referencedTerminology: '' }; @Input() parentScopeHandler; formDataTypeChangesSubscription: Subscription; allDataTypes; isValid = false; reloading = false; terminologies: Terminology[]; codesets: CodeSet[]; referenceDataModels: ReferenceDataModel[]; constructor( private resourceService: MdmResourcesService, private elementTypes: ElementTypesService ) { this.allDataTypes = this.elementTypes.getAllDataTypesArray(); if (this.allDataTypes) { this.model.domainType = this.allDataTypes[0]; } this.loadTerminologies(); this.loadCodeSets(); this.loadReferenceModels(); } sendValidationStatus() { this.validationStatusEvent.emit(String(!this.isValid)); } ngOnInit() { this.validate(); if (this.parentScopeHandler) { this.parentScopeHandler.$broadcast('newDataTypeInlineUpdated', { model: this.model, isValid: this.isValid }); } } ngAfterViewInit() { this.formDataTypeChangesSubscription = this.myFormNewDataType.form.valueChanges.subscribe( x => { this.validate(x); } ); } onTypeSelect() { if (this.model.domainType !== 'TerminologyType') { this.model.referencedTerminology.id = ''; } this.validate(); } validate(newValue?) { let isValid = true; if (newValue !== undefined) { this.model.label = newValue.label; this.model.domainType = newValue.dataModelType; } if (!this.model.label || this.model.label.trim().length === 0) { isValid = false; } // Check if for EnumerationType, at least one value is added if (this.model.domainType === 'EnumerationType' && this.model.enumerationValues.length === 0) { isValid = false; } // Check if for ReferenceType, the dataClass is selected if (this.model.domainType === 'ReferenceType' && (!this.model.referencedDataClass || this.model.referencedDataClass.id === '')) { isValid = false; } if (this.model.domainType === 'Primitive') { isValid = true; } // Check if for TerminologyType, the terminology is selected if (this.model.domainType === 'TerminologyType' && (!this.model.referencedModel || this.model.referencedModel.id === '')) { isValid = false; } if (this.model.domainType === 'CodeSetType' && (!this.model.referencedModel || this.model.referencedModel.id === '')) { isValid = false; } if (this.model.domainType === 'ReferenceDataModelType' && (!this.model.referencedModel || this.model.referencedModel.id === '')) { isValid = false; } this.isValid = isValid; this.sendValidationStatus(); } onDataClassSelect = dataClasses => { if (dataClasses && dataClasses.length > 0) { this.model.referencedDataClass = dataClasses[0]; } else { this.model.referencedDataClass = null; } this.validate(); this.sendValidationStatus(); }; loadTerminologies() { this.reloading = true; this.resourceService.terminology.list().subscribe((data: TerminologyIndexResponse) => { this.terminologies = data.body.items; this.reloading = false; }, () => { this.reloading = false; }); } // onTerminologySelect(terminology: any) { // this.model.referencedTerminology = terminology; // this.model.terminology = terminology; // this.validate(); // this.sendValidationStatus(); // } modelDataTypeSelected(value: any) { this.model.referencedModel = value; this.validate(); this.sendValidationStatus(); } loadCodeSets() { this.reloading = true; this.resourceService.codeSet.list().subscribe((data: CodeSetIndexResponse) => { this.codesets = data.body.items; this.reloading = false; }, () => { this.reloading = false; }); } loadReferenceModels() { this.reloading = true; this.resourceService.referenceDataModel.list().subscribe((data: ReferenceDataModelIndexResponse) => { this.referenceDataModels = data.body.items; this.reloading = false; }, () => { this.reloading = false; }); } onEnumListUpdated = newEnumList => { this.model.enumerationValues = newEnumList; this.validate(); this.sendValidationStatus(); }; }
MauroDataMapper/mdm-ui
src/app/data-type/data-type-detail/data-type-detail.component.ts
<gh_stars>1-10 /* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, OnInit, Input, } from '@angular/core'; import { ElementTypesService } from '@mdm/services/element-types.service'; import { MdmResourcesService } from '@mdm/modules/resources'; import { MessageHandlerService } from '@mdm/services/utility/message-handler.service'; import { StateHandlerService } from '@mdm/services/handlers/state-handler.service'; import { SharedService } from '@mdm/services/shared.service'; import { MatDialog } from '@angular/material/dialog'; import { SecurityHandlerService } from '@mdm/services/handlers/security-handler.service'; import { EditingService } from '@mdm/services/editing.service'; import { DataModel, DataType, DataTypeDetail, DataTypeDetailResponse } from '@maurodatamapper/mdm-resources'; import { Access } from '@mdm/model/access'; @Component({ selector: 'mdm-data-type-detail', templateUrl: './data-type-detail.component.html', styleUrls: ['./data-type-detail.component.scss'] }) export class DataTypeDetailComponent implements OnInit { @Input() dataType: DataTypeDetail; @Input() mcParentDataModel: DataModel; originalDataType : DataTypeDetail; elementType: any; access: Access; editMode = false; constructor( private dialog: MatDialog, private sharedService: SharedService, private elementTypes: ElementTypesService, private resources: MdmResourcesService, private messageHandler: MessageHandlerService, private stateHandler: StateHandlerService, private securityHandler: SecurityHandlerService, private editingService: EditingService ) { } ngOnInit() { this.originalDataType = Object.assign({}, this.dataType); this.access = this.securityHandler.elementAccess(this.dataType); } save() { const resource: DataType = { id: this.dataType.id, label: this.dataType.label, domainType: this.dataType.domainType }; this.resources.dataType.update(this.mcParentDataModel.id, this.dataType.id, resource).subscribe((res: DataTypeDetailResponse) => { this.dataType = res.body; this.editMode = false; this.messageHandler.showSuccess('Data Type updated successfully.'); this.editingService.stop(); }, error => { this.messageHandler.showError('There was a problem updating the Data Type.', error); } ); }; showForm() { this.editingService.start(); this.editMode = true; } cancel(){ this.editingService.stop(); this.dataType = Object.assign({}, this.originalDataType); this.editMode = false; } delete(){ this.resources.dataType.remove(this.mcParentDataModel.id, this.dataType.id).subscribe(() => { this.messageHandler.showSuccess('Data Type deleted successfully.'); this.stateHandler.Go('appContainer.mainApp.twoSidePanel.catalogue.allDataModel'); }, error => { this.messageHandler.showError('There was a problem deleting the Data Type.', error); }); }; askToDelete(){ if (!this.sharedService.isAdminUser()) { return; } // check if it has DataElements this.resources.dataElement.listWithDataType(this.mcParentDataModel.id, this.dataType.id).subscribe((res) => { const result = res.body; const dataElementsCount = result.count; let message = '<p class=\'marginless\'>Are you sure you want to <span class=\'warning\'>permanently</span> delete this Data Type?</p>'; if (dataElementsCount > 0) { message += `<p>All it's Data Elements <strong>(${dataElementsCount})</strong> will be deleted <span class='warning'>permanently</span> as well:</p>`; for (let i = 0; i < Math.min(5, result.items.length); i++) { const link = this.elementTypes.getLinkUrl(result.items[i]); message += `<div><a target='_blank' href='${link}'>${result.items[i].label}</a></div>`; } if (result.count > 5) { message += ' ...'; } } this.dialog .openConfirmationAsync({ data: { title: 'Permanent deletion', okBtnTitle: 'Yes, delete', btnType: 'warn', message } }) .subscribe(() => this.delete()); }); }; }
MauroDataMapper/mdm-ui
src/app/shared/alert/alert.component.ts
<filename>src/app/shared/alert/alert.component.ts /* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, Input, OnInit } from '@angular/core'; import { AlertStyle, AlertStyleMetadata } from './alert.model'; @Component({ selector: 'mdm-alert', templateUrl: './alert.component.html', styleUrls: ['./alert.component.scss'] }) export class AlertComponent implements OnInit { @Input() alertStyle: AlertStyle = 'none'; @Input() showIcon = false; private readonly styleMetadata = new Map<AlertStyle, AlertStyleMetadata>([ ['none', { icon: '', cssModifier: ''}], ['success', { icon: 'fa-check-circle', cssModifier: 'mdm-alert--success' }], ['info', { icon: 'fa-info-circle', cssModifier: 'mdm-alert--info' }], ['warning', { icon: 'fa-exclamation-triangle', cssModifier: 'mdm-alert--warning' }], ['error', { icon: 'fa-times-circle', cssModifier: 'mdm-alert--error' }] ]); constructor() { } get iconName() { if (!this.showIcon) { return ''; } return this.styleMetadata.get(this.alertStyle)?.icon ?? ''; } get cssModifier() { return this.styleMetadata.get(this.alertStyle)?.cssModifier ?? ''; } ngOnInit(): void { } }
MauroDataMapper/mdm-ui
src/app/model/defaultProfileModel.ts
/* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { CatalogueItemDomainType, Container, DataTypeReference } from '@maurodatamapper/mdm-resources'; import { ModalDialogStatus } from '@mdm/constants/modal-dialog-status'; export interface DefaultProfileModalConfiguration { items: Array<DefaultProfileItem>; parentCatalogueItem?: any; } export interface DefaultProfileModalResponse { status: ModalDialogStatus; items?: Array<DefaultProfileItem>; } export interface DefaultProfileItem { displayName: string; value?: string | Container[] | string[] | DataTypeReference; controlType: ProfileControlTypes; minMultiplicity?: number | string; maxMultiplicity?: number | string; propertyName: string; } export enum ProfileControlTypes { text = 'Text', html = 'HTML', aliases = 'Aliases', classifications = 'Classifications', multiplicity = 'Multiplicity', dataType = 'DataType' } export class DefaultProfileControls { static renderControls(domainType): string[] { const dataModel = [ 'description', 'author', 'aliases', 'organisation', 'classifications' ]; const dataClass = [ 'description', 'classifications', 'multiplicity', 'aliases' ]; const dataElement = [ 'description', 'classifications', 'multiplicity', 'aliases', 'dataType' ]; const folder = ['description']; const dataType = ['description', 'aliases', 'classifications', 'dataType']; const term = ['description', 'aliases', 'classifications', 'url','terminology']; const classification = ['description']; switch (domainType) { case CatalogueItemDomainType.DataModel: case CatalogueItemDomainType.ReferenceDataModel: case CatalogueItemDomainType.Terminology: case CatalogueItemDomainType.CodeSet: return dataModel; case CatalogueItemDomainType.Term: return term; case CatalogueItemDomainType.DataClass: return dataClass; case CatalogueItemDomainType.Folder: case CatalogueItemDomainType.VersionedFolder: return folder; case CatalogueItemDomainType.DataElement: return dataElement; case CatalogueItemDomainType.ReferenceDataModelType: case CatalogueItemDomainType.CodeSetType: case CatalogueItemDomainType.ModelDataType: case CatalogueItemDomainType.PrimitiveType: case CatalogueItemDomainType.TerminologyType: case CatalogueItemDomainType.EnumerationType: case CatalogueItemDomainType.ReferenceType: return dataType; case CatalogueItemDomainType.Classifier: return classification; default: return dataModel; } } }
MauroDataMapper/mdm-ui
src/app/shared/data-type-list-buttons/data-type-list-buttons.component.ts
/* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; import { DataElementBulkEditDialogService } from '@mdm/services/data-element-bulk-edit-dialog.service'; @Component({ selector: 'mdm-data-type-list-buttons', templateUrl: './data-type-list-buttons.component.html', styleUrls: ['./data-type-list-buttons.component.sass'] }) export class DataTypeListButtonsComponent implements OnInit { @Output() deleteRows = new EventEmitter<any>(); @Input() add: any; @Input() displayRecords: any[]; @Input() deleteInProgress = false; @Input() showContentDropdown = false; @Input() addDataClass: any; @Input() addDataElement: any; @Input() showDeleteButton = true; @Input() parentDataModel: any; @Input() parentDataClass: any; deletePending: boolean; textLocation: string; deleteWarning: string; message: boolean; constructor(private dataElementBulkEditDialogService: DataElementBulkEditDialogService) { } ngOnInit() { this.textLocation = 'left'; this.deletePending = false; } confirmDeleteClicked = () => { if (this.deleteRows) { this.deletePending = false; this.deleteInProgress = true; this.deleteRows.emit(); } }; onAskDelete = () => { let showDelete = false; this.displayRecords.forEach(record => { if (record.checked === true) { showDelete = true; } }); if (showDelete) { this.deletePending = true; } else { this.deleteWarning = 'Please select one or more elements.'; } }; cancelDeleteClicked = () => { this.deletePending = false; }; }
MauroDataMapper/mdm-ui
src/app/modals/check-in-modal/check-in-modal-payload.ts
<reponame>MauroDataMapper/mdm-ui /* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Branchable, MergableMultiFacetAwareDomainType } from '@maurodatamapper/mdm-resources'; import { ModalDialogStatus } from '@mdm/constants/modal-dialog-status'; import { MergeDiffItemModel } from '@mdm/merge-diff/types/merge-item-type'; export interface CheckinModelConfiguration { deleteSourceBranch: boolean; commitComment?: string; items?: MergeDiffItemModel[]; label?: string; domainType?: MergableMultiFacetAwareDomainType; isDataAsset?: boolean; source?: Branchable; target?: Branchable; } export interface CheckinModelResult { status: ModalDialogStatus; deleteSourceBranch?: boolean; commitComment?: string; }
MauroDataMapper/mdm-ui
src/app/security/open-id-connect-authorize/open-id-connect-authorize.component.ts
<gh_stars>1-10 /* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, OnInit } from '@angular/core'; import { BroadcastService, MessageService, SecurityHandlerService } from '@mdm/services'; import { SignInError, SignInErrorType } from '@mdm/services/handlers/security-handler.model'; import { EMPTY } from 'rxjs'; import { catchError, finalize } from 'rxjs/operators'; /** * Component to authorize a user session authenticated via an OpenID Connect provider. * * This acts as the landing page when an OpenID Connect provider redirects back to Mauro after authenticating a user. * This page will complete the authorization of a Mauro user session to complete login. * * The component has 3 states that occur (in order): * * 1. A user is not signed into Mauro yet - capture the parameters from the OpenID Connect redirect URL containing the * authentication session state. Pass those parameters to Mauro's login endpoint. * * 2. When successfully logged into Mauro, the component will redirect back to itself. The reason why is to remove * the extraneous query parameters from the current location URL (a full redirect seems to be the only way to * do this, UIRouter does not update browser state). * * 3. If logged into Mauro - update internal state with logged in broadcast messages and navigate to the start page. */ @Component({ selector: 'mdm-open-id-connect-authorize', templateUrl: './open-id-connect-authorize.component.html', styleUrls: ['./open-id-connect-authorize.component.scss'] }) export class OpenIdConnectAuthorizeComponent implements OnInit { authorizing = true; errorMessage: string; constructor( private securityHandler: SecurityHandlerService, private messages: MessageService, private broadcast: BroadcastService) { } ngOnInit(): void { if (this.verifyLoggedIn()) { return; } let query = window.location.search; if (!query || query.length === 0) { query = window.location.hash.slice(window.location.hash.indexOf('?')); } const params = new URLSearchParams(query); const state = params.get('state'); const sessionState = params.get('session_state'); const code = params.get('code'); if (!state || !sessionState || !code) { this.authorizing = false; this.errorMessage = 'OpenID Connect session state has not been provided.'; return; } this.securityHandler .authorizeOpenIdConnectSession({ state, sessionState, code }) .pipe( catchError((error: SignInError) => { switch (error.type) { case SignInErrorType.InvalidCredentials: this.errorMessage = 'Invalid username or password!'; break; case SignInErrorType.AlreadySignedIn: this.errorMessage = 'A user is already signed in, please sign out first.'; break; default: this.errorMessage = 'Unable to sign in. Please try again later.'; break; } return EMPTY; }), finalize(() => this.authorizing = false) ) .subscribe(() => { this.verifyLoggedIn(); }); } private verifyLoggedIn() { if (this.securityHandler.isLoggedIn()) { this.messages.loggedInChanged(true); this.broadcast.userLoggedIn({ nextRoute: 'appContainer.mainApp.twoSidePanel.catalogue.allDataModel' }); return true; } return false; } }
MauroDataMapper/mdm-ui
src/app/profiles-dashboard/profiles-dashboard.component.ts
/* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { EventEmitter } from '@angular/core'; import { Component, ElementRef, ViewChild, ViewChildren } from '@angular/core'; import { MatSort } from '@angular/material/sort'; import { MatTable } from '@angular/material/table'; import { MdmResourcesService } from '@mdm/modules/resources'; import { GridService } from '@mdm/services'; import { MdmPaginatorComponent } from '@mdm/shared/mdm-paginator/mdm-paginator'; import { catchError, map, startWith, switchMap } from 'rxjs/operators'; import { merge, Observable } from 'rxjs'; import { AfterViewInit } from '@angular/core'; @Component({ selector: 'mdm-profiles-dashboard', templateUrl: './profiles-dashboard.component.html', styleUrls: ['./profiles-dashboard.component.scss'] }) export class ProfilesDashboardComponent implements AfterViewInit { @ViewChildren('filters', { read: ElementRef }) filters: ElementRef[]; @ViewChild(MatSort, { static: false }) sort: MatSort; @ViewChild(MdmPaginatorComponent, { static: true }) paginator: MdmPaginatorComponent; @ViewChild(MatTable, { static: false }) table: MatTable<any>; filterEvent = new EventEmitter<any>(); isLoadingResults: boolean; totalProfileCount: number; filter: {}; dynamicProfileRecords: any[] = []; hideFilters = true; displayedColumns = ['displayName', 'metadataNamespace', 'version']; constructor( private resourcesService: MdmResourcesService, private gridService: GridService ) {} ngAfterViewInit(): void { this.sort?.sortChange.subscribe(() => (this.paginator.pageIndex = 0)); this.filterEvent.subscribe(() => (this.paginator.pageIndex = 0)); this.loadProfileData(); } loadProfileData() { merge(this.sort?.sortChange, this.paginator?.page, this.filterEvent) .pipe( startWith({}), switchMap(() => { this.isLoadingResults = true; return this.dynamicProfilesFetch(); }), map((data: any) => { // TODO catch to totalcount once request is updated this.totalProfileCount = data.body.length; this.isLoadingResults = false; return data.body; }), catchError(() => { this.isLoadingResults = false; return []; }) ) .subscribe((data) => { data.forEach((res) => res.dataModel['domainType'] = 'DataModel'); this.dynamicProfileRecords = data; }); } applyFilter = () => { const filter = {}; this.filters.forEach((x: any) => { const name = x.nativeElement.name; const value = x.nativeElement.value; if (value !== '') { filter[name] = value; } }); this.filter = filter; this.filterEvent.emit(filter); }; filterClick = () => { this.hideFilters = !this.hideFilters; }; // TODO update when paging is added dynamicProfilesFetch( // pageSize?, // pageIndex?, // sortBy?, // sortType?, // filters? ): Observable<any> { // const options = this.gridService.constructOptions( // pageSize, // pageIndex, // sortBy, // sortType, // filters // ); return this.resourcesService.profile.providerDynamic(); } }
MauroDataMapper/mdm-ui
src/app/services/handlers/security-handler.service.spec.ts
/* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { TestBed } from '@angular/core/testing'; import { SecurityHandlerService } from './security-handler.service'; import { HttpClientTestingModule } from '@angular/common/http/testing'; import { UIRouterModule } from '@uirouter/angular'; import { ToastrModule } from 'ngx-toastr'; import { ElementTypesService } from '@mdm/services/element-types.service'; import { MdmResourcesService } from '@mdm/modules/resources'; import { UserDetails } from './security-handler.model'; import { cold } from 'jest-marbles'; import { HttpErrorResponse } from '@angular/common/http'; import { LoginPayload } from '@maurodatamapper/mdm-resources'; interface MdmSecurityResourceStub { login: jest.Mock; logout: jest.Mock; } interface MdmSessionResourceStub { isApplicationAdministration: jest.Mock; isAuthenticated: jest.Mock; } interface MdmResourcesServiceStub { security: MdmSecurityResourceStub; session: MdmSessionResourceStub; } describe('SecurityHandlerService', () => { let service: SecurityHandlerService; const resourcesStub: MdmResourcesServiceStub = { security: { login: jest.fn(), logout: jest.fn() }, session: { isApplicationAdministration: jest.fn(), isAuthenticated: jest.fn() } }; beforeEach(() => { TestBed.configureTestingModule({ imports: [ HttpClientTestingModule, UIRouterModule.forRoot({ useHash: true }), ToastrModule.forRoot() ], providers: [ { provide: MdmResourcesService, useValue: resourcesStub }, ElementTypesService ] }); service = TestBed.inject(SecurityHandlerService); }); it('should be created', () => { expect(service).toBeTruthy(); }); it.each([ ['123', '<EMAIL>', false], ['456', '<EMAIL>', true] ])('should sign in user %s %s when admin = %o', (id, userName, isAdmin) => { const credentials: LoginPayload = { username: userName, password: '<PASSWORD>' }; const expectedUser: UserDetails = { id, userName, email: userName, firstName: 'first', lastName: 'last', isAdmin, needsToResetPassword: false, role: '', token: undefined }; resourcesStub.security.login.mockImplementationOnce(() => cold('--a|', { a: { body: { id: expectedUser.id, emailAddress: expectedUser.userName, firstName: expectedUser.firstName, lastName: expectedUser.lastName } } })); resourcesStub.session.isApplicationAdministration.mockImplementationOnce(() => cold('--a|', { a: { body: { applicationAdministrationSession: expectedUser.isAdmin } } })); const expected$ = cold('----a|', { a: expectedUser }); const actual$ = service.signIn(credentials); expect(actual$).toBeObservable(expected$); }); it('should throw error if sign in fails', () => { resourcesStub.security.login.mockImplementationOnce(() => cold('--#', null, new HttpErrorResponse({}))); const expected$ = cold('--#'); const actual$ = service.signIn({ username: 'fail', password: '<PASSWORD>' }); expect(actual$).toBeObservable(expected$); }); });
MauroDataMapper/mdm-ui
src/app/services/element-selector-dialogue.service.ts
<filename>src/app/services/element-selector-dialogue.service.ts /* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Injectable } from '@angular/core'; import { ElementSelectorComponent } from '../utility/element-selector.component'; import { MatDialog } from '@angular/material/dialog'; @Injectable({ providedIn: 'root' }) export class ElementSelectorDialogueService { constructor(public dialog: MatDialog) { } open(validTypesToSelect, notAllowedToSelectIds) { if (!validTypesToSelect || (validTypesToSelect && validTypesToSelect.length === 0)) { validTypesToSelect = ['CodeSet', 'DataModel', 'DataClass', 'DataType', 'DataElement', 'Term']; } const dg = this.dialog.open(ElementSelectorComponent, { data: { validTypesToSelect, notAllowedToSelectIds }, panelClass: 'element-selector-modal' }); return dg; } }
MauroDataMapper/mdm-ui
src/app/constants/roles.ts
/* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class ROLES { map = { ADMINISTRATOR: 'Administrator', EDITOR: 'Editor', PENDING: 'Pending' }; array = [ { value: 'ADMINISTRATOR', text: 'Administrator' }, { value: 'EDITOR', text: 'Editor' }, { value: 'PENDING', text: 'Pending' } ]; notPendingArray = [ { value: 'ADMINISTRATOR', text: 'Administrator' }, { value: 'EDITOR', text: 'Editor' } ]; constructor() {} }
MauroDataMapper/mdm-ui
src/app/merge-diff/conflict-editor/number-conflict-editor/number-conflict-editor.component.ts
/* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, Input, OnInit } from '@angular/core'; import { Branchable, MergeDiffItem } from '@maurodatamapper/mdm-resources'; @Component({ selector: 'mdm-number-conflict-editor', templateUrl: './number-conflict-editor.component.html', styleUrls: ['./number-conflict-editor.component.scss'] }) export class NumberConflictEditorComponent implements OnInit { @Input() source: Branchable; @Input() target: Branchable; @Input() item: MergeDiffItem; resolvedValue: number; constructor() { } ngOnInit(): void { this.resolvedValue = Number(this.item.sourceValue); } getFinalResolvedValue() { return this.resolvedValue; } }
MauroDataMapper/mdm-ui
src/app/userArea/user-details/user-details.component.ts
/* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, OnInit, ViewEncapsulation, Input, Output, EventEmitter, OnDestroy } from '@angular/core'; import { UserDetailsResult } from '@mdm/model/userDetailsModel'; import { MdmResourcesService } from '@mdm/modules/resources'; import { MessageService } from '@mdm/services/message.service'; import { Subscription } from 'rxjs'; import { Title } from '@angular/platform-browser'; import { MessageHandlerService } from '@mdm/services/utility/message-handler.service'; @Component({ selector: 'mdm-user-details', templateUrl: './user-details.component.html', styleUrls: ['./user-details.component.sass'], encapsulation: ViewEncapsulation.None }) export class UserDetailsComponent implements OnInit, OnDestroy { @Input() afterSave: any; @Output() refreshUserDetails: EventEmitter<any> = new EventEmitter(); user: UserDetailsResult; public: false; subscription: Subscription; isWritable: boolean; errorMessage = ''; constructor( private resourcesService: MdmResourcesService, private messageService: MessageService, private title: Title, private messageHandler: MessageHandlerService ) { this.userDetails(); } ngOnInit() { this.title.setTitle('My profile'); } userDetails(): any { // subscribe to parent component userDetails messages; this.subscription = this.messageService.getUserDetails().subscribe((message) => { this.user = message; }); } checkEmailExists(data: string) { return this.resourcesService.catalogueUser.exists(data); } formBeforeSave = () => { this.errorMessage = ''; this.checkEmailExists(this.user.emailAddress).subscribe(() => { const userDetails = { firstName: this.user.firstName, lastName: this.user.lastName, organisation: this.user.organisation, jobTitle: this.user.jobTitle || '', }; if (this.validateInput(this.user.firstName) && this.validateInput(this.user.lastName) && this.validateInput(this.user.organisation)) { this.resourcesService.catalogueUser.update(this.user.id, userDetails).subscribe(result => { if (this.afterSave) { this.afterSave(result); } this.messageHandler.showSuccess('User details updated successfully.'); }, error => { this.messageHandler.showError('There was a problem updating the User Details.', error); } ); } }); }; validateInput(value): any { if (value != null && value.trim().length === 0) { return false; } else { return true; } } ngOnDestroy() { this.subscription.unsubscribe(); // unsubscribe to ensure no memory leaks } }
MauroDataMapper/mdm-ui
src/app/dataElement/data-element/data-element.component.ts
<gh_stars>1-10 /* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core'; import { MdmResourcesService } from '@mdm/modules/resources'; import { MessageService } from '@mdm/services/message.service'; import { SharedService } from '@mdm/services/shared.service'; import { UIRouterGlobals } from '@uirouter/core'; import { StateHandlerService } from '@mdm/services/handlers/state-handler.service'; import { Subscription } from 'rxjs'; import { MatTabGroup } from '@angular/material/tabs'; import { Title } from '@angular/platform-browser'; import { EditingService } from '@mdm/services/editing.service'; import { GridService, MessageHandlerService, SecurityHandlerService } from '@mdm/services'; import { McSelectPagination } from '@mdm/utility/mc-select/mc-select.component'; import { DataElement, DataElementDetail, DataElementDetailResponse, DataTypeReference } from '@maurodatamapper/mdm-resources'; import { DefaultProfileItem, ProfileControlTypes } from '@mdm/model/defaultProfileModel'; import { TabCollection } from '@mdm/model/ui.model'; import { BaseComponent } from '@mdm/shared/base/base.component'; @Component({ selector: 'mdm-data-element', templateUrl: './data-element.component.html', styleUrls: ['./data-element.component.sass'] }) export class DataElementComponent extends BaseComponent implements OnInit, AfterViewInit { @ViewChild('tab', { static: false }) tabGroup: MatTabGroup; dataElementOutput: DataElementDetail; showSecuritySection: boolean; subscription: Subscription; showSearch = false; parentId: string; afterSave: (result: { body: { id: any } }) => void; editMode = false; showEdit = false; showDelete = false; showExtraTabs = false; activeTab: any; dataClass = { id: null }; dataModel = { id: null }; isDataLoaded = false; aliases: any[] = []; max: any; min: any; error: any; newMinText: any; newMaxText: any; pagination: McSelectPagination; descriptionView = 'default'; annotationsView = 'default'; showEditDescription = false; showNewInlineDataType = false; dataTypeErrors = ''; isValid = false; rulesItemCount = 0; isLoadingRules = true; access: any; tabs = new TabCollection([ 'description', 'links', 'summaryMetadata', 'rules', 'annotations' ]); newlyAddedDataType = { label: '', description: '', metadata: [], domainType: 'PrimitiveType', enumerationValues: [], classifiers: [], referencedDataClass: '', referencedTerminology: '' }; constructor( private resourcesService: MdmResourcesService, private messageService: MessageService, private uiRouterGlobals: UIRouterGlobals, private sharedService: SharedService, private stateHandler: StateHandlerService, private messageHandler: MessageHandlerService, private gridService: GridService, private title: Title, private securityHandler: SecurityHandlerService, private editingService: EditingService ) { super(); if ( this.isGuid(this.uiRouterGlobals.params.id) && (!this.uiRouterGlobals.params.id || !this.uiRouterGlobals.params.dataModelId || !this.uiRouterGlobals.params.dataClassId) ) { this.stateHandler.NotFound({ location: false }); return; } if ( this.uiRouterGlobals.params.id && this.uiRouterGlobals.params.dataModelId && this.uiRouterGlobals.params.dataModelId.trim() !== '' ) { this.dataModel = { id: this.uiRouterGlobals.params.dataModelId }; } if ( this.uiRouterGlobals.params.id && this.uiRouterGlobals.params.dataClassId && this.uiRouterGlobals.params.dataClassId.trim() !== '' ) { this.dataClass = { id: this.uiRouterGlobals.params.dataClassId }; } if (this.uiRouterGlobals.params.edit === 'true') { this.editMode = true; } } ngOnInit() { this.activeTab = this.tabs.getByName(this.uiRouterGlobals.params.tabView as string).index; this.tabSelected(this.activeTab); this.showExtraTabs = this.sharedService.isLoggedIn(); this.title.setTitle('Data Element'); this.dataElementDetails( this.uiRouterGlobals.params.dataModelId, this.dataClass.id, this.uiRouterGlobals.params.id ); this.subscription = this.messageService.changeSearch.subscribe( (message: boolean) => { this.showSearch = message; } ); } ngAfterViewInit(): void { this.editingService.setTabGroupClickEvent(this.tabGroup); } fetchDataTypes = (text, loadAll, offset, limit) => { const options = this.gridService.constructOptions( limit, offset, 'label', 'asc', { label: text } ); this.pagination = { limit: options['limit'], offset: options['offset'] }; return this.resourcesService.dataType.list(this.dataModel.id, options); }; getTabDetailByName(tabName) { switch (tabName) { case 'description': return { index: 0, name: 'description' }; case 'annotations': return { index: 1, name: 'annotations' }; case 'links': return { index: 2, name: 'links' }; case 'summaryMetadata': return { index: 3, name: 'summaryMetadata' }; case 'rules': return { index: 4, name: 'rules' }; default: return { index: 0, name: 'description' }; } } save(saveItems: Array<DefaultProfileItem>) { const resource: DataElement = { id: this.dataElementOutput.id, label: this.dataElementOutput.label, domainType: this.dataElementOutput.domainType }; saveItems.forEach((item: DefaultProfileItem) => { if (item.controlType === ProfileControlTypes.multiplicity) { if ((item.minMultiplicity as string) === '*') { item.minMultiplicity = -1; } if ((item.maxMultiplicity as string) === '*') { item.maxMultiplicity = -1; } resource.minMultiplicity = item.minMultiplicity as number; resource.maxMultiplicity = item.maxMultiplicity; } else if (item.controlType === ProfileControlTypes.dataType) { resource.dataType = item.value as DataTypeReference; } else { resource[item.propertyName] = item.value; } }); this.resourcesService.dataElement .update( this.dataModel.id, this.dataClass.id, this.dataElementOutput.id, resource ) .subscribe( (result: DataElementDetailResponse) => { this.dataElementOutput = null; setTimeout(() => { this.dataElementOutput = result.body; }, 250); this.catalogueItem = result.body; this.messageHandler.showSuccess('Data Element updated successfully.'); }, (error) => { this.messageHandler.showError( 'There was a problem updating the Data Element.', error ); } ); } dataElementDetails(dataModelId: any, dataClassId, id) { this.resourcesService.dataElement .get(dataModelId, dataClassId, id) .subscribe((result: DataElementDetailResponse) => { this.dataElementOutput = result.body; this.catalogueItem = result.body; this.dataModel.id = result.body.model; this.dataClass.id = result.body.dataClass; this.watchDataElementObject(); this.messageService.FolderSendMessage(this.dataElementOutput); this.messageService.dataChanged(this.dataElementOutput); if (this.dataElementOutput) { // tslint:disable-next-line: deprecation this.activeTab = this.getTabDetailByName( this.uiRouterGlobals.params.tabView as string ).index; this.tabSelected(this.activeTab); } this.isDataLoaded = true; }); } rulesCountEmitter($event) { this.isLoadingRules = false; this.rulesItemCount = $event; } toggleShowNewInlineDataType() { this.showNewInlineDataType = !this.showNewInlineDataType; this.dataTypeErrors = ''; } toggleShowSearch() { this.messageService.toggleSearch(); } tabSelected(index: number) { const tab = this.tabs.getByIndex(index); this.stateHandler.Go( 'dataElement', { tabView: tab.name }, { notify: false } ); } watchDataElementObject() { this.access = this.securityHandler.elementAccess(this.dataElementOutput); if (this.access !== undefined) { this.showEdit = this.access.showEdit; this.showDelete = this.access.showPermanentDelete || this.access.showSoftDelete; } } }
MauroDataMapper/mdm-ui
src/app/services/utility/user-settings-handler.service.spec.ts
/* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { TestBed } from '@angular/core/testing'; import { UserSettingsHandlerService } from './user-settings-handler.service'; import { HttpClientTestingModule } from '@angular/common/http/testing'; import { UIRouterModule } from '@uirouter/angular'; import { ToastrModule } from 'ngx-toastr'; import { ElementTypesService } from '@mdm/services/element-types.service'; import { MdmResourcesService } from '@mdm/modules/resources'; describe('UserSettingsHandlerService', () => { beforeEach(() => TestBed.configureTestingModule({ imports: [ HttpClientTestingModule, UIRouterModule.forRoot({ useHash: true }), ToastrModule.forRoot() ], providers: [ { provide: MdmResourcesService, useValue: {} }, ElementTypesService ] })); it('should be created', () => { const service: UserSettingsHandlerService = TestBed.inject(UserSettingsHandlerService); expect(service).toBeTruthy(); }); });
MauroDataMapper/mdm-ui
src/app/modals/confirmation-modal/confirmation-modal.component.ts
<gh_stars>1-10 /* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, OnInit, Inject } from '@angular/core'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; import { ModalDialogStatus } from '@mdm/constants/modal-dialog-status'; export interface ConfirmationModalConfig { title?: string; message: string; okBtnTitle?: string; cancelBtnTitle?: string; cancelShown?: boolean; btnType?: string; } export interface ConfirmationModalResult { status: ModalDialogStatus; } @Component({ selector: 'mdm-confirmation-modal', templateUrl: './confirmation-modal.component.html', styleUrls: ['./confirmation-modal.component.sass'] }) export class ConfirmationModalComponent implements OnInit { title: string; message: string; okTitle: string; cancelTitle: string; cancelShown: boolean; btnType: string; constructor( private dialogRef: MatDialogRef<ConfirmationModalComponent, ConfirmationModalResult>, @Inject(MAT_DIALOG_DATA) public data: ConfirmationModalConfig ) { } ngOnInit() { this.okTitle = this.data.okBtnTitle ? this.data.okBtnTitle : 'OK'; this.btnType = this.data.btnType ? this.data.btnType : 'primary'; this.cancelTitle = this.data.cancelBtnTitle ? this.data.cancelBtnTitle : 'Cancel'; this.title = this.data.title; this.message = this.data.message; this.cancelShown = this.data.cancelShown != null ? this.data.cancelShown : true; } ok = () => this.dialogRef.close({ status: ModalDialogStatus.Ok }); cancel = () => this.dialogRef.close({ status: ModalDialogStatus.Cancel }); }
MauroDataMapper/mdm-ui
src/app/subscribed-catalogues/subscribed-catalogue-main/subscribed-catalogue-main.component.ts
<reponame>MauroDataMapper/mdm-ui<gh_stars>1-10 /* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, OnInit } from '@angular/core'; import { Title } from '@angular/platform-browser'; import { SubscribedCatalogue, SubscribedCatalogueResponse } from '@maurodatamapper/mdm-resources'; import { MdmResourcesService } from '@mdm/modules/resources'; import { MessageHandlerService, StateHandlerService } from '@mdm/services'; import { BaseComponent } from '@mdm/shared/base/base.component'; import { UIRouterGlobals } from '@uirouter/core'; @Component({ selector: 'mdm-subscribed-catalogue-main', templateUrl: './subscribed-catalogue-main.component.html', styleUrls: ['./subscribed-catalogue-main.component.scss'] }) export class SubscribedCatalogueMainComponent extends BaseComponent implements OnInit { subscribedCatalogue: SubscribedCatalogue; constructor( private resources: MdmResourcesService, private uiRouterGlobals: UIRouterGlobals, private stateHandler: StateHandlerService, private messageHandler: MessageHandlerService, private title: Title) { super(); } ngOnInit(): void { const catalogueId: string = this.uiRouterGlobals.params.id; if (!catalogueId || !this.isGuid(catalogueId)) { this.stateHandler.NotFound({ location: false }); return; } this.title.setTitle('Subscribed Catalogue'); this.resources.subscribedCatalogues .get(catalogueId) .subscribe( (response: SubscribedCatalogueResponse) => this.subscribedCatalogue = response.body, error => this.messageHandler.showError('There was a problem getting the subscribed catalogue.', error)); } }
MauroDataMapper/mdm-ui
src/app/shared/models/models.component.ts
<reponame>MauroDataMapper/mdm-ui /* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, OnDestroy, OnInit } from '@angular/core'; import { Title } from '@angular/platform-browser'; import { BroadcastService } from '@mdm/services/broadcast.service'; import { SecurityHandlerService } from '@mdm/services/handlers/security-handler.service'; import { StateHandlerService } from '@mdm/services/handlers/state-handler.service'; import { MdmResourcesService } from '@mdm/modules/resources'; import { SharedService } from '@mdm/services/shared.service'; import { MessageHandlerService } from '@mdm/services/utility/message-handler.service'; import { UserSettingsHandlerService } from '@mdm/services/utility/user-settings-handler.service'; import { ValidatorService } from '@mdm/services/validator.service'; import { EMPTY, of, Subject, Subscription } from 'rxjs'; import { catchError, debounceTime, finalize, map, switchMap, takeUntil } from 'rxjs/operators'; import { MatDialog } from '@angular/material/dialog'; import { NodeConfirmClickEvent } from '@mdm/folders-tree/folders-tree.component'; import { ModelTreeService } from '@mdm/services/model-tree.service'; import { CatalogueItemDomainType, Classifier, ClassifierIndexResponse, ContainerDomainType, DataModel, isContainerDomainType, MdmTreeItem, MdmTreeItemListResponse, ModelDomainType } from '@maurodatamapper/mdm-resources'; import { mapCatalogueDomainTypeToContainer, MdmTreeLevelManager } from './models.model'; @Component({ selector: 'mdm-models', templateUrl: './models.component.html', styleUrls: ['./models.component.scss'] }) export class ModelsComponent implements OnInit, OnDestroy { formData: any = {}; activeTab = 0; allModels: MdmTreeItem = null; filteredModels = null; isAdmin = this.securityHandler.isAdmin(); inSearchMode = false; folder = ''; searchboxFocused = false; debounceInputEvent: Subject<KeyboardEvent | InputEvent>; subscriptions: Subscription; // Hard includeModelSuperseded = false; // Soft showSupersededModels = false; includeDeleted = false; showFilters = false; currentTab = 'dataModels'; classifierLoading = false; allClassifiers: Classifier[]; reloading = false; currentClassification: any; allClassifications: any; classifiers: { children: Classifier[]; isRoot: boolean }; searchText: any; levels: MdmTreeLevelManager = { current: 0, currentFocusedElement: null, backToTree: () => { this.levels.current = 0; this.reloadTree(); }, focusTreeItem: (node?: MdmTreeItem) => { if (node) { this.levels.currentFocusedElement = node; } const containerType = mapCatalogueDomainTypeToContainer( this.levels.currentFocusedElement.domainType ); if (containerType) { this.reloading = true; if ( containerType !== ModelDomainType.Folders && containerType !== ModelDomainType.VersionedFolders ) { this.resources.tree .get( containerType, this.levels.currentFocusedElement.domainType, this.levels.currentFocusedElement.id ) .pipe( catchError((error) => { this.messageHandler.showError( 'There was a problem focusing the tree element.', error ); return EMPTY; }), finalize(() => (this.reloading = false)) ) .subscribe((response: MdmTreeItemListResponse) => { const children = response.body; this.levels.currentFocusedElement.children = children; this.levels.currentFocusedElement.open = true; this.levels.currentFocusedElement.selected = true; const curModel = { children: [this.levels.currentFocusedElement], isRoot: true }; this.filteredModels = Object.assign({}, curModel); this.levels.current = 1; }); }else{ this.resources.tree .getFolder( this.levels.currentFocusedElement.id ) .pipe( catchError((error) => { this.messageHandler.showError( 'There was a problem focusing the tree element.', error ); return EMPTY; }), finalize(() => (this.reloading = false)) ) .subscribe((response: MdmTreeItemListResponse) => { const children = response.body; this.levels.currentFocusedElement.children = children; this.levels.currentFocusedElement.open = true; this.levels.currentFocusedElement.selected = true; const curModel = { children: [this.levels.currentFocusedElement], isRoot: true }; this.filteredModels = Object.assign({}, curModel); this.levels.current = 1; }); } } } }; private unsubscribe$ = new Subject(); constructor( private sharedService: SharedService, private validator: ValidatorService, private stateHandler: StateHandlerService, private resources: MdmResourcesService, private title: Title, private securityHandler: SecurityHandlerService, private broadcast: BroadcastService, private userSettingsHandler: UserSettingsHandlerService, protected messageHandler: MessageHandlerService, public dialog: MatDialog, private modelTree: ModelTreeService ) {} ngOnInit() { this.title.setTitle('Models'); if (this.sharedService.isLoggedIn()) { this.includeModelSuperseded = this.userSettingsHandler.get('includeModelSuperseded') || false; this.showSupersededModels = this.userSettingsHandler.get('showSupersededModels') || false; this.includeDeleted = this.userSettingsHandler.get('includeDeleted') || false; } if ( this.sharedService.searchCriteria && this.sharedService.searchCriteria.length > 0 ) { this.formData.filterCriteria = this.sharedService.searchCriteria; } this.initializeModelsTree(); this.broadcast .onReloadCatalogueTree() .pipe(takeUntil(this.unsubscribe$)) .subscribe(() => this.loadModelsTree(true)); this.broadcast .onReloadClassificationTree() .pipe(takeUntil(this.unsubscribe$)) .subscribe(() => this.loadClassifiers()); this.currentClassification = null; this.allClassifications = []; } ngOnDestroy() { if (this.subscriptions) { this.subscriptions.unsubscribe(); } this.unsubscribe$.next(); this.unsubscribe$.complete(); } isLoggedIn() { return this.sharedService.isLoggedIn(); } tabSelected(tabIndex: number) { switch (tabIndex) { case 0: { return (this.currentTab = 'models'); } case 1: { return (this.currentTab = 'classifications'); } case 2: { return (this.currentTab = 'favourites'); } default: { this.currentTab = 'models'; } } } loadClassifiers() { this.classifierLoading = true; this.resources.classifier.list({ all: true }).subscribe( (result: ClassifierIndexResponse) => { const data = result.body.items; this.allClassifiers = data; data.forEach((classifier) => { classifier.domainType = CatalogueItemDomainType.Classifier; }); this.classifiers = { children: data, isRoot: true }; this.classifierLoading = false; }, () => { this.classifierLoading = false; } ); } loadModelsTree(noCache?: boolean) { this.reloading = true; // Fetch tree information from two potential sources - local folder tree and possible (external) // subscribed catalogues // // Fetch one resource at a time to avoid any 404s this.modelTree .getLocalCatalogueTreeNodes(noCache) .pipe( catchError((error) => { this.messageHandler.showError( 'There was a problem loading the model tree.', error ); return EMPTY; }), switchMap((local) => { return this.modelTree.getSubscribedCatalogueTreeNodes().pipe( map((subscribed) => { if ((subscribed?.length ?? 0) === 0) { // Display only local catalogue folders/models return this.modelTree.createRootNode(local); } // Combine sub tree nodes with new parent nodes to build up roots const localParent = this.modelTree.createLocalCatalogueNode( local ); const externalParent = this.modelTree.createExternalCataloguesNode( subscribed ); return this.modelTree.createRootNode([ localParent, externalParent ]); }), catchError(() => { this.messageHandler.showWarning( 'There was a problem loading the model tree with subscribed catalogues. Showing only local instance models.' ); // Display only local catalogue folders/models return of(this.modelTree.createRootNode(local)); }) ); }), finalize(() => (this.reloading = false)) ) .subscribe((node) => { this.allModels = node; this.filteredModels = node; }); } onNodeConfirmClick($event: NodeConfirmClickEvent) { const node = $event.next.node; this.stateHandler .Go(node.domainType, { id: node.id, edit: false, dataModelId: node.modelId, dataClassId: node.parentId || '', terminologyId: node.modelId, parentId: node.parentId }) .then( () => $event.setSelectedNode($event.next), () => $event.setSelectedNode($event.current) ); } onNodeDbClick(node: MdmTreeItem) { if ( isContainerDomainType(node.domainType) || node.domainType === CatalogueItemDomainType.DataModel || node.domainType === CatalogueItemDomainType.Terminology ) { this.levels.focusTreeItem(node); } } onNodeAdded() { this.loadModelsTree(); } loadModelsToCompare(dataModel: DataModel) { this.resources.catalogueItem .listSemanticLinks(dataModel.domainType, dataModel.id, { all: true }) .subscribe((result) => { const compareToList = []; const semanticLinks = result.body; semanticLinks.items.forEach((link) => { if ( ['Superseded By', 'New Version Of'].indexOf(link.linkType) !== -1 && link.source.id === dataModel.id ) { compareToList.push(link.target); } }); }); } onFolderAddModal() { this.modelTree .createNewFolder({ allowVersioning: true }) .pipe( catchError((error) => { this.messageHandler.showError( 'There was a problem creating the Folder.', error ); return EMPTY; }) ) .subscribe((response) => { const item = response.body; this.filteredModels.children.push(item); this.stateHandler.Go(item.domainType, { id: item.id, edit: false }); this.messageHandler.showSuccess( `Folder ${item.label} created successfully.` ); this.folder = ''; this.loadModelsTree(); }); } toggleFilterMenu() { this.showFilters = !this.showFilters; } toggleFilters(filerName: string) { this[filerName] = !this[filerName]; this.reloading = true; if (this.sharedService.isLoggedIn()) { this.userSettingsHandler.update( 'includeModelSuperseded', this.includeModelSuperseded ); this.userSettingsHandler.update( 'showSupersededModels', this.showSupersededModels ); this.userSettingsHandler.update('includeDeleted', this.includeDeleted); this.userSettingsHandler.saveOnServer(); } this.loadModelsTree(); this.showFilters = !this.showFilters; } initializeModelsTree() { this.loadModelsTree(); this.loadClassifiers(); } changeState(newState: string, type?: string, newWindow?: boolean) { if (newWindow) { this.stateHandler.NewWindow(newState); return; } if (newState) { if (newState === 'import') { this.stateHandler.Go(newState, { importType: type }); } else if (newState === 'export') { this.stateHandler.Go(newState, { exportType: type }); } return; } this.stateHandler.Go(newState); } onSearchInputKeyDown(event: KeyboardEvent | InputEvent) { // Initialize debounce listener if necessary if (!this.debounceInputEvent) { this.debounceInputEvent = new Subject<KeyboardEvent | InputEvent>(); this.subscriptions = this.debounceInputEvent .pipe(debounceTime(300)) .subscribe((e) => { if (e instanceof KeyboardEvent) { switch (e.key) { case 'Enter': this.search(); return; case 'Escape': this.formData.filterCriteria = ''; this.search(); this.searchboxFocused = false; return; } } if (this.formData.filterCriteria?.length > 2) { this.search(); } if (this.validator.isEmpty(this.formData.filterCriteria)) { this.search(); } }); } event.preventDefault(); event.stopPropagation(); this.debounceInputEvent.next(event); return false; } search() { if (this.formData.filterCriteria?.trim().length > 2) { this.formData.ClassificationFilterCriteria = ''; this.sharedService.searchCriteria = this.formData.filterCriteria; this.reloading = true; this.inSearchMode = true; this.allModels = null; this.resources.tree .search(ContainerDomainType.Folders, this.sharedService.searchCriteria) .subscribe((res) => { const result: MdmTreeItem[] = res.body; this.reloading = false; this.allModels = { id: '', domainType: CatalogueItemDomainType.Root, children: result, hasChildren: true, isRoot: true, availableActions: [] }; this.filteredModels = Object.assign({}, this.allModels); this.searchText = this.formData.filterCriteria; }); } else { this.inSearchMode = false; this.sharedService.searchCriteria = ''; this.searchText = ''; this.loadModelsTree(); } } classifierTreeOnSelect(node: MdmTreeItem) { this.stateHandler.Go('classification', { id: node.id }); } classificationFilterChange(val: string) { if (val && val.length !== 0 && val.trim().length === 0) { this.filterClassifications(); } else { this.loadClassifiers(); } } filterClassifications() { if (this.formData.ClassificationFilterCriteria.length > 0) { this.formData.filterCriteria = ''; this.sharedService.searchCriteria = this.formData.ClassificationFilterCriteria; } else { this.loadClassifiers(); } } onFavouriteDbClick(node: MdmTreeItem) { this._onFavouriteClick(node); } onFavouriteClick(node: MdmTreeItem) { this._onFavouriteClick(node); } reloadTree() { this.loadModelsTree(true); } onAddClassifier() { this.modelTree .createNewClassifier() .pipe( catchError((error) => { this.messageHandler.showError( 'Classification name can not be empty', error ); return EMPTY; }) ) .subscribe((response) => { this.messageHandler.showSuccess('Classifier saved successfully.'); this.stateHandler.Go('classification', { id: response.body.id }); this.loadClassifiers(); }); } private _onFavouriteClick(node: MdmTreeItem) { this.stateHandler.Go(node.domainType, { id: node.id }); } }
MauroDataMapper/mdm-ui
src/app/wizards/dataType/data-type-step1/data-type-step1.component.ts
/* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, OnInit } from '@angular/core'; import { CreateType } from '@mdm/wizards/wizards.model'; @Component({ selector: 'mdm-data-type-step1', templateUrl: './data-type-step1.component.html', styleUrls: ['./data-type-step1.component.sass'] }) export class DataTypeStep1Component implements OnInit { step: { invalid : boolean; isProcessComplete : boolean; scope : { model: { [key: string]: any; createType: CreateType; }; }; }; modelVal: { [key: string]: any; createType: CreateType; }; constructor() { } get model() { return this.modelVal; } set model(val) { this.modelVal = val; this.validate(); } ngOnInit() { this.model = this.step.scope.model; } validate = () => { if (!this.model.createType) { this.step.invalid = true; return; } if (['copy', 'import'].includes(this.model.createType) && !this.model.copyFromDataModel.length) { this.step.invalid = true; return; } this.step.invalid = false; }; selectCreateType = createType => { this.model.createType = createType; this.validate(); }; // TODO CORRECT onSelect = (dataType) => { this.model.copyFromDataModel = dataType; this.validate(); }; }
MauroDataMapper/mdm-ui
src/app/export-models/export-models.component.ts
<filename>src/app/export-models/export-models.component.ts<gh_stars>1-10 /* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { ChangeDetectorRef, Component, ElementRef, OnInit, Renderer2, ViewChild } from '@angular/core'; import { SecurityHandlerService } from '../services/handlers/security-handler.service'; import { MdmResourcesService } from '@mdm/modules/resources'; import { ExportHandlerService } from '../services/handlers/export-handler.service'; import { HelpDialogueHandlerService } from '../services/helpDialogue.service'; import { MessageHandlerService } from '../services/utility/message-handler.service'; import { Title } from '@angular/platform-browser'; import { StateService } from '@uirouter/core/'; @Component({ selector: 'mdm-data-models-export', templateUrl: './export-models.component.html', styleUrls: ['./export-models.component.scss'] }) export class ExportModelsComponent implements OnInit { @ViewChild('aLink', { static: false }) aLink: ElementRef; step: any; selectedDataModels: any; showExport = null; selectedModels: any[] = []; selectedExporter = null; defaultModels = []; form = {}; selectedExporterObj: any; selectedExporterStr: any; processing = false; exportersList = []; exportedFileIsReady: any; exportType: any; constructor( private changeDedRef: ChangeDetectorRef, private securityHandler: SecurityHandlerService, private resources: MdmResourcesService, private messageHandler: MessageHandlerService, private exportHandler: ExportHandlerService, private helpDialogueHandler: HelpDialogueHandlerService, private renderer: Renderer2, private title: Title, private stateService: StateService ) { } ngOnInit() { // tslint:disable-next-line: deprecation this.exportType = this.stateService.params.exportType ? this.stateService.params.exportType : 'dataModels'; this.loadExporterList(); this.step = 1; this.title.setTitle('Export Models'); } onSelect = select => { if (select && select.length > 0) { this.step = 2; this.showExport = 'true'; this.changeDedRef.detectChanges(); } else { this.step = 1; } }; loadExporterList() { this.exportersList = []; this.securityHandler.isAuthenticated().subscribe(result => { if (!result.body.authenticatedSession) { return; } if (this.exportType === 'dataModels') { this.resources.dataModel.exporters().subscribe(result2 => { this.exportersList = result2.body; }, error => { this.messageHandler.showError('There was a problem loading exporters list.', error); }); } else if (this.exportType === 'terminologies') { this.resources.terminology.exporters().subscribe(result2 => { this.exportersList = result2.body; }, error => { this.messageHandler.showError('There was a problem loading exporters list.', error); }); } else if (this.exportType === 'codeSets') { this.resources.codeSet.exporters().subscribe(result2 => { this.exportersList = result2.body; }, error => { this.messageHandler.showError('There was a problem loading exporters list.', error); }); } else if (this.exportType === 'referenceDataModels') { this.resources.referenceDataModel.exporters().subscribe(result2 => { this.exportersList = result2.body; }, error => { this.messageHandler.showError('There was a problem loading exporters list.', error); }); } }); } exporterChanged() { if (this.selectedExporterStr) { this.selectedExporterObj = this.selectedExporterStr; } else { this.selectedExporterObj = null; } } reset() { this.step = 1; this.selectedDataModels = []; this.selectedExporter = null; this.selectedExporterObj = null; this.defaultModels = []; this.selectedExporterStr = null; Array.from(this.aLink.nativeElement.children).forEach(child => { this.renderer.removeChild(this.aLink.nativeElement, child); }); } export = () => { this.exportedFileIsReady = false; this.processing = true; this.exportHandler.exportDataModel(this.selectedDataModels, this.selectedExporterObj, this.exportType).subscribe(result => { if (result != null) { this.exportedFileIsReady = true; this.processing = false; const label = this.selectedDataModels.length === 1 ? this.selectedDataModels[0].label : this.exportType; const fileName = this.exportHandler.createFileName(label, this.selectedExporterObj); const file = new Blob([result.body], { type: this.selectedExporterObj.fileType }); const link = this.exportHandler.createBlobLink(file, fileName); Array.from(this.aLink.nativeElement.children).forEach(child => { this.renderer.removeChild(this.aLink.nativeElement, child); }); this.processing = false; this.renderer.appendChild(this.aLink.nativeElement, link); this.messageHandler.showSuccess('Data Model(s) exported successfully.'); } else { this.processing = false; this.messageHandler.showError('There was a problem exporting the Data Model(s).', ''); } }, error => { this.processing = false; this.messageHandler.showError('There was a problem exporting the Data Model(s).', error); } ); }; loadHelp = () => { this.helpDialogueHandler.open('Exporting_models'); }; }
MauroDataMapper/mdm-ui
src/app/shared/text-diff/text-diff.component.ts
<filename>src/app/shared/text-diff/text-diff.component.ts /* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { AfterViewInit } from '@angular/core'; import { Component, ElementRef, Input, ViewChild } from '@angular/core'; import { diff_match_patch } from 'diff-match-patch'; @Component({ selector: 'mdm-text-diff', templateUrl: './text-diff.component.html', styleUrls: ['./text-diff.component.scss'] }) export class TextDiffComponent implements AfterViewInit { @Input() left : any; @Input() right : any; // This is new @ViewChild('diff', { static: false }) set diffCon(content: ElementRef) { this.diff = content; } diff: ElementRef; mergeString: any; mergeDiffrl: any; mergeDifflr: any; constructor() {} ngAfterViewInit(): void { if (this.right && this.left) { const diffrl = this.diffLineMode(this.right.toString(), this.left.toString()); this.diff.nativeElement.innerHTML = this.diffPrettyPlain(diffrl); } } diffPrettyPlain = (diffs: any) => { const diffAdded = 1; const diffEqual = 0; const diffDelete = -1; const html = []; for (let x = 0; x < diffs.length; x++) { const op = diffs[x][0]; // Operation (insert, delete, equal) const data = diffs[x][1]; // Text of change. const text = data; switch (op) { case diffAdded: { html[x] = `<div class="diffAdded" >${text}</div>`; break; } case diffEqual: { html[x] = `<div>${text}</div>`; break; } case diffDelete: { html[x] = `<div class="diffDeleted">${text}</div>`; break; } } } return html.join(''); }; diffLineMode(text1, text2) { const dmp = new diff_match_patch(); const a = this.diffLinesToChars(text1, text2); const lineText1 = a.chars1; const lineText2 = a.chars2; const lineArray = a.lineArray; const diffs = dmp.diff_main(lineText1, lineText2, false); dmp.diff_charsToLines_(diffs, lineArray); return diffs; } diffLinesToChars = (text1, text2) => { const lineArray = []; // e.g. lineArray[4] == 'Hello\n' const lineHash = {}; // e.g. lineHash['Hello\n'] == 4 // '\x00' is a valid character, but various debuggers don't like it. // So we'll insert a junk entry to avoid generating a null character. lineArray[0] = ''; /** * Split a text into an array of strings. Reduce the texts to a string of * hashes where each Unicode character represents one line. * Modifies linearray and linehash through being a closure. * * @param {string} text String to encode. * @return {string} Encoded string. * @private */ // Allocate 2/3rds of the space for text1, the rest for text2. let maxLines = 40000; const chars1 = this.diffLinesToCharsMunge( text1, lineArray, lineHash, maxLines ); maxLines = 65535; const chars2 = this.diffLinesToCharsMunge( text2, lineArray, lineHash, maxLines ); return { chars1, chars2, lineArray }; }; diffLinesToCharsMunge = (text, lineArray, lineHash, maxLines) => { let chars = ''; // Walk the text, pulling out a substring for each line. // text.split('\n') would would temporarily double our memory footprint. // Modifying text would create many large strings to garbage collect. let lineStart = 0; let lineEnd = -1; // Keeping our own length variable is faster than looking it up. let lineArrayLength = lineArray.length; while (lineEnd < text.length - 1) { lineEnd = text.indexOf(' ', lineStart); if (lineEnd === -1) { lineEnd = text.length - 1; } let line = text.substring(lineStart, lineEnd + 1); if ( lineHash.hasOwnProperty ? lineHash.hasOwnProperty(line) : lineHash[line] !== undefined ) { chars += String.fromCharCode(lineHash[line]); } else { if (lineArrayLength === maxLines) { // Bail out at 65535 because // String.fromCharCode(65536) == String.fromCharCode(0) line = text.substring(lineStart); lineEnd = text.length; } chars += String.fromCharCode(lineArrayLength); lineHash[line] = lineArrayLength; lineArray[lineArrayLength++] = line; } lineStart = lineEnd + 1; } return chars; }; }
MauroDataMapper/mdm-ui
src/app/services/message.service.ts
<reponame>MauroDataMapper/mdm-ui /* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import {Injectable, EventEmitter, Output, OnDestroy} from '@angular/core'; import {Observable, Subject} from 'rxjs'; @Injectable({ providedIn: 'root' }) export class MessageService implements OnDestroy { @Output() changeUserGroupAccess: EventEmitter<boolean> = new EventEmitter(); @Output() changeSearch: EventEmitter<boolean> = new EventEmitter(); @Output() changeShareReadWithEveryone: EventEmitter<boolean> = new EventEmitter(); @Output() editMode: EventEmitter<boolean> = new EventEmitter(); isUserGroupAccess = false; isSearch = false; isShareReadWithEveryone = false; isEditMode = false; loggedInChange = new Subject<any>(); dataModelDataChange = new Subject<any>(); elementSelectorSendMessage = new Subject<any>(); dataChange = new Subject<any>(); dataChanged$ = this.dataChange.asObservable(); loggedInChanged$ = this.loggedInChange.asObservable(); dataModelDataChange$ = this.dataModelDataChange.asObservable(); elementSelector = this.elementSelectorSendMessage.asObservable(); folderPermissions; private lastErrorVar = {}; private errorMessageVar = {}; private subjUserDetails = new Subject<any>(); private UserGroupAccessSubject = new Subject<any>(); /** Generic message functions */ // A map to store subjects/channels private subjects: Map<string, Subject<any>> = new Map(); private FolderSubject = new Subject<any>(); get lastError(): any { return this.lastErrorVar; } set lastError(value: any) { this.lastErrorVar = value; } // eslint-disable-next-line @typescript-eslint/member-ordering get errorMessage(): {} { return this.errorMessageVar; } set errorMessage(value: {}) { this.errorMessageVar = value; } sendUserDetails(data) { this.subjUserDetails.next(data); } getUserDetails(): Observable<any> { return this.subjUserDetails.asObservable(); } dataChanged(data) { this.dataChange.next(data); } loggedInChanged(data) { this.loggedInChange.next(data); } dataModelDataChanged(data) { this.dataModelDataChange.next(data); } elementSelectorSendData(data) { this.elementSelectorSendMessage.next(data); } toggleUserGroupAccess() { this.isUserGroupAccess = !this.isUserGroupAccess; this.changeUserGroupAccess.emit(this.isUserGroupAccess); if (this.isUserGroupAccess) { this.isSearch = false; this.changeSearch.emit(this.isSearch); } } toggleSearch() { this.isSearch = !this.isSearch; this.changeSearch.emit(this.isSearch); if (this.isSearch) { this.isUserGroupAccess = false; this.changeUserGroupAccess.emit(this.isUserGroupAccess); } } toggleShareReadWithEveryone() { this.isShareReadWithEveryone = !this.isShareReadWithEveryone; this.changeShareReadWithEveryone.emit(this.isShareReadWithEveryone); } showEditMode(showEdit: boolean) { this.editMode.emit(showEdit); } FolderSendMessage(message: any) { this.folderPermissions = message; this.FolderSubject.next(message); } FolderSendClearMessages() { this.FolderSubject.next(); } FolderGetMessage(): Observable<any> { return this.FolderSubject.asObservable(); } getFolderPermissions() { if (this.folderPermissions != null) { return this.folderPermissions; } // else{ add a call in else condition to get folders // this.FoldersPermissionGet(); // return this.permissionsData; // } } DataModelSendMessage(message: any) { this.folderPermissions = message; this.FolderSubject.next(message); } /** * Broadcast to all subscribers of a given subject. * * @param subject name of subject/channel to broadcast to * @param message message to broadcast */ broadcast(subject, ...message: any) { // Create the named Subject if not exists if (!this.subjects.has(subject)) { this.subjects.set(subject, new Subject()); } this.subjects.get(subject).next(message); } /** * Get the named subject * * @param subject name of subject to get */ getSubject(subject) { // Create the named Subject if not exists if (!this.subjects.has(subject)) { this.subjects.set(subject, new Subject()); } return this.subjects.get(subject); } /** * Subscribe to named subject/channel * * @param subject subject to subscribe to * @param callback message handler */ subscribe(subject, handler) { // Create the named Subject if not exists if (!this.subjects.has(subject)) { this.subjects.set(subject, new Subject()); } return this.subjects.get(subject).subscribe(handler); } on(subject, handler) { return this.subscribe(subject, handler); } /** * Clear the subjects map when destroy */ ngOnDestroy(): void { this.subjects.forEach((subject, key) => { subject.complete(); this.subjects.delete(key); }); } }
MauroDataMapper/mdm-ui
src/app/admin/subscribed-catalogues/subscribed-catalogues.component.ts
<filename>src/app/admin/subscribed-catalogues/subscribed-catalogues.component.ts /* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core'; import { MatDialog } from '@angular/material/dialog'; import { MatSort, SortDirection } from '@angular/material/sort'; import { MatTableDataSource } from '@angular/material/table'; import { Title } from '@angular/platform-browser'; import { SubscribedCatalogue, SubscribedCatalogueIndexResponse } from '@maurodatamapper/mdm-resources'; import { MdmHttpHandlerOptions, MdmResourcesService } from '@mdm/modules/resources'; import { GridService, MessageHandlerService, SharedService, StateHandlerService } from '@mdm/services'; import { MdmPaginatorComponent } from '@mdm/shared/mdm-paginator/mdm-paginator'; import { merge, Observable } from 'rxjs'; import { catchError, map, startWith, switchMap } from 'rxjs/operators'; @Component({ selector: 'mdm-subscribed-catalogues', templateUrl: './subscribed-catalogues.component.html', styleUrls: ['./subscribed-catalogues.component.scss'] }) export class SubscribedCataloguesComponent implements OnInit, AfterViewInit { @ViewChild(MatSort, { static: true }) sort: MatSort; @ViewChild(MdmPaginatorComponent, { static: true }) paginator: MdmPaginatorComponent; isLoadingResults: boolean; totalItemCount = 0; dataSource = new MatTableDataSource<any>(); displayedColumns = ['label', 'description', 'connection', 'refreshPeriod', 'icons']; records: SubscribedCatalogue[] = []; constructor( private resources: MdmResourcesService, private gridService: GridService, private stateHandlerService: StateHandlerService, private shared: SharedService, private messageHandler: MessageHandlerService, private title: Title, private dialog: MatDialog) { this.dataSource = new MatTableDataSource(this.records); } ngOnInit(): void { this.title.setTitle('Subscribed catalogues'); } ngAfterViewInit(): void { if (!this.shared.features.useSubscribedCatalogues) { this.stateHandlerService.Go('alldatamodel'); return; } this.sort.sortChange.subscribe(() => this.paginator.pageIndex = 0); this.dataSource.sort = this.sort; this.refreshList(); } refreshList() { merge(this.sort.sortChange, this.paginator.page) .pipe( startWith({}), switchMap(() => { this.isLoadingResults = true; return this.fetchConnections( this.paginator.pageSize, this.paginator.pageOffset, this.sort.active, this.sort.direction ); }), map((data: SubscribedCatalogueIndexResponse) => { this.totalItemCount = data.body.count; this.isLoadingResults = false; return data.body.items; }), catchError(error => { this.isLoadingResults = false; this.messageHandler.showError('There was a problem loading the subscribed catalogues.', error); return []; }) ) .subscribe((data: SubscribedCatalogue[]) => { this.records = data; this.dataSource.data = this.records; }); } fetchConnections( pageSize?: number, pageIndex?: number, sortBy?: string, sortType?: SortDirection): Observable<SubscribedCatalogueIndexResponse> { const options = this.gridService.constructOptions( pageSize, pageIndex, sortBy, sortType); return this.resources.admin.listSubscribedCatalogues(options); } addSubscription = () => { this.stateHandlerService.Go('appContainer.adminArea.subscribedCatalogue', { id: null }); }; editSubscription(record: SubscribedCatalogue) { if (!record) { return; } this.stateHandlerService.Go('appContainer.adminArea.subscribedCatalogue', { id: record.id }); } deleteSubscription(record: SubscribedCatalogue) { this.dialog .openConfirmationAsync({ data: { title: 'Are you sure you want to delete this subscribed catalogue?', okBtnTitle: 'Yes, delete', btnType: 'warn', message: 'Once deleted, the subscription cannot be retrieved.', } }) .pipe( switchMap(() => this.resources.admin.removeSubscribedCatalogue(record.id)) ) .subscribe( () => { this.messageHandler.showSuccess('Subscribed catalogue deleted successfully.'); this.refreshList(); }, error => this.messageHandler.showError('There was a problem deleting the subscribed catalogue.', error)); } testSubscription(record: SubscribedCatalogue) { this.messageHandler.showInfo(`Testing connection to "${record.label}"...`); const requestOptions: MdmHttpHandlerOptions = { handleGetErrors: false }; this.resources.admin .testSubscribedCatalogueConnection(record.id, {}, requestOptions) .subscribe( () => this.messageHandler.showSuccess(`Subscribed catalogue "${record.label}" is functioning as expected.`), error => this.messageHandler.showError(`There was a problem connecting to the subscribed catalogue "${record.label}", please check the configuration.`, error) ); } }
MauroDataMapper/mdm-ui
src/app/subscribed-catalogues/federated-data-model-main/federated-data-model-main.component.ts
<gh_stars>1-10 /* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, OnInit } from '@angular/core'; import { Title } from '@angular/platform-browser'; import { FederatedDataModel } from '@mdm/model/federated-data-model'; import { TabCollection } from '@mdm/model/ui.model'; import { MessageHandlerService, StateHandlerService } from '@mdm/services'; import { BaseComponent } from '@mdm/shared/base/base.component'; import { UIRouterGlobals } from '@uirouter/angular'; import { SubscribedCataloguesService } from '../subscribed-catalogues.service'; @Component({ selector: 'mdm-federated-data-model-main', templateUrl: './federated-data-model-main.component.html', styleUrls: ['./federated-data-model-main.component.scss'] }) export class FederatedDataModelMainComponent extends BaseComponent implements OnInit { catalogueId: string; modelId: string; dataModel: FederatedDataModel; activeTab: any; tabs = new TabCollection([ 'newVersion' ]); showNewerVersionsTab = true; constructor( private uiRouterGlobals: UIRouterGlobals, private stateHandler: StateHandlerService, private messageHandler: MessageHandlerService, private subscribedCatalogues: SubscribedCataloguesService, private title: Title) { super(); } ngOnInit(): void { this.catalogueId = this.uiRouterGlobals.params.parentId; if (!this.catalogueId || !this.isGuid(this.catalogueId)) { this.stateHandler.NotFound({ location: false }); } this.modelId = this.uiRouterGlobals.params.id; if (!this.modelId || !this.isGuid(this.modelId)) { this.stateHandler.NotFound({ location: false }); } this.title.setTitle('Federated Data Model'); // First check if dataModel was provided in state transition const dataModel = this.uiRouterGlobals.params.dataModel; if (dataModel) { this.dataModel = dataModel; return; } // If not from tree, fetch from the server again this.getFederatedDataModel(); } onReloading() { this.getFederatedDataModel(true); } tabSelected(index: number) { const tab = this.tabs.getByIndex(index); this.stateHandler.Go('dataModel', { tabView: tab.name }, { notify: false }); } onNewerVersionsHasErrored() { this.showNewerVersionsTab = false; } private getFederatedDataModel(reloadView?: boolean) { this.subscribedCatalogues .getFederatedDataModels(this.catalogueId) .subscribe( models => { this.dataModel = models.find(model => model.modelId === this.modelId); if (reloadView) { this.reloadView(); } }, errors => this.messageHandler.showError('There was a problem getting the Federated Data Model', errors)); } private reloadView() { this.stateHandler.Go( 'federateddatamodel', { parentId: this.catalogueId, id: this.modelId }, { reload: true }); } }
MauroDataMapper/mdm-ui
src/app/services/theming.service.spec.ts
<reponame>MauroDataMapper/mdm-ui<filename>src/app/services/theming.service.spec.ts /* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { TestBed } from '@angular/core/testing'; import { EnvironmentService } from './environment.service'; import { ThemingService } from './theming.service'; interface EnvironmentStub { themeName?: string; } describe('ThemingService', () => { let service: ThemingService; const environment: EnvironmentStub = { themeName: 'default' }; beforeEach(() => { TestBed.configureTestingModule({ providers: [ { provide: EnvironmentService, useValue: environment } ] }); }); const validThemeNames = [ 'default', 'nhs-digital' ]; const invalidThemeNames = [ '', ' ', 'custom-theme', 'unknown', '123' ]; it('should be created', () => { service = TestBed.inject(ThemingService); expect(service).toBeTruthy(); }); it.each(validThemeNames)('should allow theme name "%s"', (themeName) => { environment.themeName = themeName; service = TestBed.inject(ThemingService); expect(service.themeName).toBe(themeName); }); it.each(invalidThemeNames)('should not allow theme name "%s" and use "default" instead', (themeName) => { environment.themeName = themeName; service = TestBed.inject(ThemingService); expect(service.themeName).toBe('default'); }); it.each(validThemeNames)('should set CSS selector for valid theme name "%s"', (themeName) => { environment.themeName = themeName; service = TestBed.inject(ThemingService); expect(service.themeCssSelector).toBe(themeName + '-theme'); }); it.each(invalidThemeNames)('should set CSS selector for invalid theme name "%s" to be "default-theme"', (themeName) => { environment.themeName = themeName; service = TestBed.inject(ThemingService); expect(service.themeCssSelector).toBe('default-theme'); }); });
MauroDataMapper/mdm-ui
src/app/folders-tree/folders-tree.component.ts
/* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { FlatTreeControl } from '@angular/cdk/tree'; import { Component, EventEmitter, Input, OnChanges, OnDestroy, Output, SimpleChanges, ViewChild } from '@angular/core'; import { MatMenuTrigger } from '@angular/material/menu'; import { MatTreeFlatDataSource, MatTreeFlattener } from '@angular/material/tree'; import { EMPTY, of, Subject, Subscription } from 'rxjs'; import { MdmResourcesService } from '@mdm/modules/resources'; import { MessageHandlerService } from '../services/utility/message-handler.service'; import { FlatNode, getCatalogueItemDomainTypeIcon } from './flat-node'; import { MatDialog } from '@angular/material/dialog'; import { FolderService } from './folder.service'; import { MessageService, SecurityHandlerService, FavouriteHandlerService, StateHandlerService, BroadcastService, SharedService } from '@mdm/services'; import { ModelTreeService } from '@mdm/services/model-tree.service'; import { catchError, takeUntil } from 'rxjs/operators'; import { CatalogueItemDomainType, isContainerDomainType, isModelDomainType, MdmTreeItem } from '@maurodatamapper/mdm-resources'; /** * Event arguments for confirming a click of a node in the FoldersTreeComponent. */ export class NodeConfirmClickEvent { constructor( public current: FlatNode, public next: FlatNode, private broadcast: BroadcastService) { } setSelectedNode = (node: FlatNode) => this.broadcast.catalogueTreeNodeSelected({ node }); } @Component({ selector: 'mdm-folders-tree', templateUrl: './folders-tree.component.html', styleUrls: ['./folders-tree.component.scss'] }) export class FoldersTreeComponent implements OnChanges, OnDestroy { @Input() node: any; @Input() searchCriteria: string; @Input() defaultCheckedMap: any = {}; @Output() nodeClickEvent = new EventEmitter<MdmTreeItem>(); @Output() nodeConfirmClickEvent = new EventEmitter<NodeConfirmClickEvent>(); @Output() nodeDbClickEvent = new EventEmitter<MdmTreeItem>(); @Output() nodeCheckedEvent = new EventEmitter<any>(); @Output() nodeAdded = new EventEmitter<MdmTreeItem>(); @Output() compareToEvent = new EventEmitter<any>(); @Output() loadModelsToCompareEvent = new EventEmitter<any>(); @Input() doNotShowDataClasses: any; @Input() doNotShowTerms: any; @Input() justShowFolders: any; @Input() showCheckboxFor: any; // it is an array of domainTypes like ['DataClass';'DataModel';'Folder'] @Input() propagateCheckbox: any; @Input() enableDragAndDrop = false; @Input() enableContextMenu = false; @Input() rememberExpandedStates = false; @Input() expandOnNodeClickFor: any; @Input() doNotMakeSelectedBold: any; @Input() filterByDomainType: CatalogueItemDomainType[]; @Input() treeName = 'unnamed'; @Input() inSearchMode: any; @Input() initialExpandedPaths: string[]; @Input() isComparisonTree = false; @Input() selectedNode: FlatNode = null; // Control highlighting @ViewChild(MatMenuTrigger, { static: false }) contextMenuTrigger: MatMenuTrigger; contextMenuPosition = { x: '0', y: '0' }; favourites: { [x: string]: any }; subscriptions: Subscription = new Subscription(); checkedList = this.defaultCheckedMap || {}; targetVersions = []; expandedPaths = []; draggableDomains = [ CatalogueItemDomainType.Folder, CatalogueItemDomainType.DataModel, CatalogueItemDomainType.Terminology, CatalogueItemDomainType.CodeSet, CatalogueItemDomainType.ReferenceDataModel ]; droppableDomains = [CatalogueItemDomainType.Folder]; draggedTreeNode: FlatNode; showDropTopPlaceHolder = false; /** The TreeControl controls the expand/collapse state of tree nodes. */ treeControl: FlatTreeControl<FlatNode>; /** The MatTreeFlatDataSource connects the control and flattener to provide data. */ dataSource: MatTreeFlatDataSource<MdmTreeItem, FlatNode>; folder = ''; expandedNodeSet = new Set<string>(); /** The TreeFlattener is used to generate the flat list of items from hierarchical data. */ protected treeFlattener: MatTreeFlattener<MdmTreeItem, FlatNode>; private unsubscribe$ = new Subject(); /** * Get the children for the given node from source data. * * Defined as property to retain reference to `this`. */ constructor( protected messages: MessageService, protected resources: MdmResourcesService, protected securityHandler: SecurityHandlerService, protected favouriteHandler: FavouriteHandlerService, protected folderService: FolderService, protected stateHandler: StateHandlerService, protected messageHandler: MessageHandlerService, private broadcast: BroadcastService, public dialog: MatDialog, private modelTree: ModelTreeService, private shared: SharedService) { this.loadFavourites(); this.subscriptions.add(this.messages.on('favourites', () => { this.loadFavourites(); })); this.treeFlattener = new MatTreeFlattener( (node: MdmTreeItem, level: number) => new FlatNode(node, level, this.securityHandler.elementAccess(node)), (node: FlatNode) => node.level, (node: FlatNode) => node?.hasChildren || node?.hasChildFolders, this.getChildren); this.treeControl = new FlatTreeControl((node: FlatNode) => node.level, (node: FlatNode) => node.hasChildren || node.hasChildFolders); this.dataSource = new MatTreeFlatDataSource(this.treeControl, this.treeFlattener, []); if (this.shared.features.useVersionedFolders) { this.draggableDomains.push(CatalogueItemDomainType.VersionedFolder); this.droppableDomains.push(CatalogueItemDomainType.VersionedFolder); } this.broadcast .onCatalogueTreeNodeSelected() .pipe(takeUntil(this.unsubscribe$)) .subscribe(data => this.selectedNode = data.node); this.broadcast .onFavouritesChanged() .pipe(takeUntil(this.unsubscribe$)) .subscribe(() => this.loadFavourites()); } ngOnChanges(changes: SimpleChanges) { if (changes.node) { if (this.node?.children) { this.refreshTree(); } } if (changes.initialExpandedPaths && this.node?.children) { if (this.initialExpandedPaths?.length > 0) { this.expandedPaths = this.initialExpandedPaths; this.refreshTree(); } } // HACK TO FILTER CLASSIFIERS NEEDS REVISITED // Note 1: The domain model tree uses backend API call to get filtered results. if (changes.searchCriteria) { if (this.treeName && this.treeName === 'Classifiers' && this.searchCriteria && this.searchCriteria.trim().length > 0) { this.filter(this.searchCriteria); } } } loadFavourites() { const fs: any[] = this.favouriteHandler.get(); this.favourites = {}; fs.forEach(f => { this.favourites[f.id] = f; }); } /** Get whether the node has children or not. Tree branch control. */ hasChild(_: number, node: FlatNode) { if (node?.domainType === CatalogueItemDomainType.DataModel && this.doNotShowDataClasses) { return false; } if (this.expandOnNodeClickFor && !this.expandOnNodeClickFor?.includes(node?.domainType)) { return false; } return node?.hasChildFolders || node?.hasChildren; } /** Determine which tree node icon to use based on given node's domain type */ getIcon(fnode: FlatNode) { return getCatalogueItemDomainTypeIcon(fnode.domainType, fnode, this.treeControl); } hasIcon(fnode: FlatNode) { return getCatalogueItemDomainTypeIcon(fnode.domainType, fnode, this.treeControl) !== null; } /** Additional CSS classes to add to the tree node. */ getCssClass(node: FlatNode) { return `fa-sm ${node.deleted ? 'deleted-folder' : ''}`; } /** Asynchronously expand sub-tree */ async toggleChildren(flatNode: FlatNode) { if (this.treeControl.isExpanded(flatNode)) { if (!this.expandedPaths.includes(this.getExpandedPaths(flatNode))) { this.expandedPaths.push(this.getExpandedPaths(flatNode)); this.expandedPaths.sort(); } } else { if (this.expandedPaths.includes(this.getExpandedPaths(flatNode))) { this.expandedPaths.splice(this.expandedPaths.indexOf(this.getExpandedPaths(flatNode)), 1); this.expandedPaths.sort(); } } if (this.rememberExpandedStates) { localStorage.setItem('expandedPaths', JSON.stringify(this.expandedPaths)); } if (!this.inSearchMode && !flatNode.children) { const data = await this.expand(flatNode.node); flatNode.children = data; } this.refreshTree(); } handleClick(fnode: FlatNode) { if (this.nodeConfirmClickEvent.observers.length > 0) { this.nodeConfirmClickEvent.emit(new NodeConfirmClickEvent(this.selectedNode, fnode, this.broadcast)); return; } this.selectedNode = fnode; // Control highlighting selected tree node this.modelTree.currentNode = fnode; this.nodeClickEvent.emit(fnode.node); } handleDbClick(fnode: FlatNode) { this.selectedNode = fnode; // Control highlighting selected tree node this.modelTree.currentNode = fnode; this.focusNode(fnode); } focusNode(fnode: FlatNode) { this.selectedNode = fnode; // Control highlighting selected tree node this.nodeDbClickEvent.emit(fnode.node); } async expand(node: MdmTreeItem) { try { switch (node.domainType) { case CatalogueItemDomainType.Folder: if (this.justShowFolders) { const folderResponse = await this.resources.tree.get('folders', 'folders', node.id).toPromise(); return folderResponse.body; } else { return node.children; } case CatalogueItemDomainType.VersionedFolder: if (this.justShowFolders) { const versionedFolderResponse = await this.resources.tree.get('folders', 'versionedFolders', node.id).toPromise(); return versionedFolderResponse.body; } else { return node.children; } case CatalogueItemDomainType.DataModel: { const dataModelResponse = await this.resources.tree.get('folders', 'dataModels', node.id).toPromise(); return dataModelResponse.body; } case CatalogueItemDomainType.DataClass: { const dataClassResponse = await this.resources.tree.get('folders', 'dataClasses', node.id).toPromise(); return dataClassResponse.body; } case CatalogueItemDomainType.Terminology: { const terminologyResponse = await this.resources.tree.get('folders', 'terminologies', node.id).toPromise(); return terminologyResponse.body; } case CatalogueItemDomainType.Term: { const termResponse = await this.resources.tree.get('folders', 'terms', node.id).toPromise(); return termResponse.body; } case CatalogueItemDomainType.SubscribedCatalogue: return await this.modelTree.getFederatedDataModelNodes(node.id).toPromise(); default: return []; } } catch (error) { console.error(error); return []; } } noop(event: Event) { event.preventDefault(); event.stopPropagation(); } nodeChecked(child: FlatNode) { const element = this.find(this.node, null, child.node.id); this.markChildren(child.node, child, child.checked); if (child.checked) { this.checkedList[element.node.id] = element; } else { delete this.checkedList[element.node.id]; } this.nodeCheckedEvent.emit([child, null, this.checkedList]); } find(node: MdmTreeItem, parent: MdmTreeItem, id: string) { if (node.id === id) { return { node, parent }; } if (node.domainType === CatalogueItemDomainType.Terminology || node.domainType === CatalogueItemDomainType.Folder || node.domainType === CatalogueItemDomainType.VersionedFolder || node.domainType === CatalogueItemDomainType.DataModel || node.domainType === CatalogueItemDomainType.DataClass || node.isRoot) { if (!node.children) { return null; } let i = 0; while (i < node.children.length) { const result = this.find(node.children[i], node, id); if (result !== null) { return result; } i++; } } return null; } markChildren(node: MdmTreeItem, root: FlatNode, status: boolean) { node.checked = status; delete this.checkedList[node.id]; if (this.propagateCheckbox) { node.children?.forEach((n: MdmTreeItem) => { n.disableChecked = status; this.markChildren(n, null, status); }); } } /** Context Menu */ async onContextMenu(fnode: FlatNode, event: MouseEvent) { event.preventDefault(); event.stopPropagation(); // TODO: remove these exceptions when there are suitable actions to use for these domain types if (!this.enableContextMenu || fnode.domainType === CatalogueItemDomainType.Term) { return; } this.contextMenuPosition.x = `${event.clientX}px`; this.contextMenuPosition.y = `${event.clientY}px`; this.contextMenuTrigger.menuData = { node: fnode }; this.contextMenuTrigger.openMenu(); if (fnode.domainType === CatalogueItemDomainType.DataModel) { this.targetVersions = await this.folderService.loadVersions(fnode.node); } } canCreateElements(fnode: FlatNode) { if (!fnode.access.canCreate) { return false; } // TODO: remove these exceptions when there are suitable actions to use for these domain types if (fnode.domainType === CatalogueItemDomainType.CodeSet || fnode.domainType === CatalogueItemDomainType.Terminology || fnode.domainType === CatalogueItemDomainType.ReferenceDataModel) { return false; } return true; } canDeleteElements(fnode: FlatNode) { if (!fnode.access.showDelete) { return false; } // TODO: remove these exceptions when there are suitable ways to accomodate them - these domain // types have `remove` endpoints with multiple parent ids if (fnode.domainType === CatalogueItemDomainType.DataElement || fnode.domainType === CatalogueItemDomainType.DataClass) { return false; } return true; } canCompare(fnode: FlatNode) { return fnode.domainType === CatalogueItemDomainType.DataModel; } canAddToFavorites(fnode: FlatNode) { return isContainerDomainType(fnode.domainType) || isModelDomainType(fnode.domainType); } canSetTreeFocus(fnode: FlatNode) { return isContainerDomainType(fnode.domainType) || fnode.domainType === CatalogueItemDomainType.DataModel || fnode.domainType === CatalogueItemDomainType.Terminology; } handleFavourites(fnode: FlatNode) { this.favouriteHandler.toggle(fnode.node); } handleAddFolder(fnode: FlatNode) { const allowVersioning = fnode.access.canCreateVersionedFolder; this.modelTree .createNewFolder({ parentFolderId: fnode?.id, allowVersioning }) .pipe( catchError(error => { this.messageHandler.showError('There was a problem creating the Folder.', error); return EMPTY; }) ) .subscribe(response => { const node: MdmTreeItem = { id: response.body.id, domainType: response.body.domainType, label: response.body.label, hasChildFolders: response.body.hasChildFolders, hasChildren: response.body.hasChildFolders, availableActions: response.body.availableActions }; this.messageHandler.showSuccess('Folder created successfully.'); this.stateHandler.Go(node.domainType, { id: node.id }); this.nodeAdded.emit(node); }); } handleAddDataModel(fnode: FlatNode) { this.stateHandler.Go( 'NewDataModel', { parentFolderId: fnode.id, parentDomainType: fnode.domainType }); } handleAddCodeSet(fnode: FlatNode) { this.stateHandler.Go( 'NewCodeSet', { parentFolderId: fnode.id, parentDomainType: fnode.domainType }); } handleSoftDelete(fnode: FlatNode) { this.modelTree .deleteCatalogueItemSoft(fnode) .subscribe(() => { fnode.deleted = true; }); } handlePermanentDelete(fnode: FlatNode) { this.modelTree .deleteCatalogueItemPermanent(fnode) .subscribe(() => { this.broadcast.reloadCatalogueTree(); this.stateHandler.Go( 'appContainer.mainApp.twoSidePanel.catalogue.allDataModel' ); }); } handleAddDataClass(fnode: FlatNode) { this.stateHandler.Go('NewDataClass', { grandParentDataClassId: fnode.domainType === CatalogueItemDomainType.DataClass ? fnode.node.parentId : null, parentDataModelId: fnode.domainType === CatalogueItemDomainType.DataModel ? fnode.id : fnode.node.modelId, parentDataClassId: fnode.domainType === CatalogueItemDomainType.DataModel ? null : fnode.id }); } handleAddDataElement(fnode: FlatNode) { this.stateHandler.Go('NewDataElement', { grandParentDataClassId: fnode.node.parentId ? fnode.node.parentId : null, parentDataModelId: fnode.node.modelId, parentDataClassId: fnode.id }); } handleAddDataType(fnode: FlatNode) { this.stateHandler.Go('NewDataType', { parentDataModelId: fnode.id }); } handleDataModelCompare(fnode: FlatNode, targetVersion = null) { this.stateHandler.NewWindow('modelscomparison', { sourceId: fnode.id, targetId: targetVersion ? targetVersion.id : null }); } handleExtendDataClass(fnode: FlatNode) { if (fnode.domainType !== CatalogueItemDomainType.DataModel && fnode.domainType !== CatalogueItemDomainType.DataClass) { throw new Error('Context item is not data model or data class.'); } this.stateHandler.Go('NewDataClass', { grandParentDataClassId: fnode.domainType === CatalogueItemDomainType.DataClass ? fnode.node.parentId : null, parentDataModelId: fnode.domainType === CatalogueItemDomainType.DataModel ? fnode.id : fnode.node.modelId, parentDataClassId: fnode.domainType === CatalogueItemDomainType.DataModel ? null : fnode.id }); } handleImportDataClass(fnode: FlatNode) { if (fnode.domainType !== CatalogueItemDomainType.DataModel && fnode.domainType !== CatalogueItemDomainType.DataClass) { throw new Error('Context item is not data model or data class.'); } this.stateHandler.Go('NewDataClass', { grandParentDataClassId: fnode.domainType === CatalogueItemDomainType.DataClass ? fnode.node.parentId : null, parentDataModelId: fnode.domainType === CatalogueItemDomainType.DataModel ? fnode.id : fnode.node.modelId, parentDataClassId: fnode.domainType === CatalogueItemDomainType.DataModel ? null : fnode.id }); } handleImportDataType(fnode: FlatNode) { if (fnode.domainType !== CatalogueItemDomainType.DataModel) { throw new Error('Context item is not data model.'); } this.stateHandler.Go('NewDataType', { parentDataModelId: fnode.id }); } handleImportDataElement(fnode: FlatNode) { if (fnode.domainType !== CatalogueItemDomainType.DataClass) { throw new Error('Context item is not data class.'); } this.stateHandler.Go('NewDataElement', { grandParentDataClassId: fnode.node.parentId, parentDataModelId: fnode.node.modelId, parentDataClassId: fnode.id }); } openWindow(fnode: FlatNode) { const parameters: any = { id: fnode.id }; if (fnode.domainType === CatalogueItemDomainType.DataClass) { parameters.dataModelId = fnode.modelId; } this.stateHandler.NewWindow(fnode.domainType.toLocaleLowerCase(), { id: fnode.id }); } isFavourited(fnode: FlatNode) { return this.favouriteHandler.isAdded(fnode); } get isUserAdmin() { return this.securityHandler.isAdmin(); } isNodeFinalised(node: FlatNode) { return node.finalised; } ngOnDestroy() { this.subscriptions.unsubscribe(); this.unsubscribe$.next(); this.unsubscribe$.complete(); } // Only used for Classifiers filter(filterText: string, sourceNodes: MdmTreeItem[] = this.node.children) { if (!filterText) { return; } const filteredTreeData: MdmTreeItem[] = sourceNodes.filter(d => d.label.toLocaleLowerCase().includes(filterText.toLocaleLowerCase())); filteredTreeData.forEach(ftd => { let str = (ftd.label); while (str.lastIndexOf('.') > -1) { const index = str.lastIndexOf('.'); str = str.substring(0, index); if (filteredTreeData.findIndex(t => t.code === str) === -1) { const obj = this.dataSource.data.find(d => d.label === str); if (obj) { filteredTreeData.push(obj); } } } }); // Build the tree nodes from Json object. The result is a list of `TodoItemNode` with nested // file node as children. this.node.children = filteredTreeData; this.refreshTree(); } validateLabel = (data: string) => { if (data) { return true; } else { return false; } }; // Drag n Drop dragStart(node: FlatNode, e: DragEvent) { if (!this.enableDragAndDrop) { return; } e.dataTransfer.dropEffect = 'move'; e.dataTransfer.setData('data', node.id); this.draggedTreeNode = node; } dragEnter(parentFolder: FlatNode, e: DragEvent) { if (!this.enableDragAndDrop) { return; } const currentNode = this.draggedTreeNode; if (currentNode.domainType === CatalogueItemDomainType.Folder || currentNode.domainType === CatalogueItemDomainType.VersionedFolder) { this.showDropTopPlaceHolder = true; } const targetElement: Element = (e.target as Element); // if over original node or under original parent folder if (parentFolder.id === currentNode.id || parentFolder.id === currentNode.parentFolder) { return; } // Do not allow versioned folders to be dragged and dropped into other versioned folders if (currentNode.domainType === CatalogueItemDomainType.VersionedFolder && parentFolder.domainType === CatalogueItemDomainType.VersionedFolder) { return; } if (this.droppableDomains.includes(parentFolder?.domainType)) { e.preventDefault(); if (!targetElement.classList.contains('drag-over')) { targetElement.classList.add('drag-over'); } } } dragOver(parentFolder: FlatNode, e: DragEvent) { if (!this.enableDragAndDrop) { return; } // if over original node or under original parent folder if (this.draggedTreeNode.id === parentFolder.id || this.draggedTreeNode.parentFolder === parentFolder.id) { return; } // Do not allow versioned folders to be dragged and dropped into other versioned folders if (this.draggedTreeNode.domainType === CatalogueItemDomainType.VersionedFolder && parentFolder.domainType === CatalogueItemDomainType.VersionedFolder) { return; } // make sure the drop will happen if (this.droppableDomains.includes(parentFolder?.domainType)) { e.preventDefault(); } } dragLeave(e: DragEvent) { if (!this.enableDragAndDrop) { return; } const targetElement: Element = (e.target as Element); // remove highlight if (targetElement.classList.contains('dnd-top-placeholder')) { targetElement.classList.remove('drag-over-top'); } else { targetElement.classList.remove('drag-over'); } } dragEnd() { this.draggedTreeNode = null; this.showDropTopPlaceHolder = false; } async drop(parentFolder: FlatNode, e: DragEvent) { if (!this.enableDragAndDrop) { return; } e.preventDefault(); e.stopPropagation(); const currentNode: FlatNode = this.draggedTreeNode; if (currentNode.id === parentFolder.id || currentNode.parentFolder === parentFolder.id) { return; } // Do not allow versioned folders to be dragged and dropped into other versioned folders if (currentNode.domainType === CatalogueItemDomainType.VersionedFolder && parentFolder.domainType === CatalogueItemDomainType.VersionedFolder) { return; } try { switch (currentNode.domainType) { case CatalogueItemDomainType.Folder: await this.resources.folder.update(currentNode.id, { id: currentNode.id, parentFolder: parentFolder?.id }).toPromise(); break; case CatalogueItemDomainType.VersionedFolder: await this.resources.versionedFolder.update(currentNode.id, { id: currentNode.id, parentFolder: parentFolder?.id }).toPromise(); break; case CatalogueItemDomainType.DataModel: await this.resources.dataModel.moveDataModelToFolder(currentNode.id, parentFolder.id, {}).toPromise(); break; case CatalogueItemDomainType.CodeSet: await this.resources.codeSet.moveCodeSetToFolder(currentNode.id, parentFolder.id, {}).toPromise(); break; case CatalogueItemDomainType.Terminology: await this.resources.terminology.moveTerminologyToFolder(currentNode.id, parentFolder.id, {}).toPromise(); break; case CatalogueItemDomainType.ReferenceDataModel: await this.resources.referenceDataModel.moveReferenceDataModelToFolder(currentNode.id, parentFolder.id, {}).toPromise(); break; default: this.messageHandler.showError(`Invalid domain type: ${currentNode.domainType}`); return; } if (this.rememberExpandedStates) { const newParentPath = parentFolder ? `${this.getExpandedPaths(parentFolder)}/` : ''; this.expandedPaths = this.expandedPaths.map((p: string) => { if (p.includes(currentNode.id)) { return `${newParentPath}${p.slice(p.indexOf(currentNode.id))}`; } return p; }); localStorage.setItem('expandedPaths', JSON.stringify(this.expandedPaths)); } this.messageHandler.showSuccess(`${currentNode.domainType} moved successfully.`); this.broadcast.reloadCatalogueTree(); } catch (error) { this.messageHandler.showError(`There was a problem moving the ${currentNode.domainType}`, error); } // dragleave event did not seem to be triggered consistently on drop this.dragLeave(e); } dragEnterTop(e: DragEvent) { if (!this.enableDragAndDrop) { return; } const targetElement: Element = (e.target as Element); const isTopPlaceHolder = targetElement.classList.contains('dnd-top-placeholder'); if (isTopPlaceHolder) { e.preventDefault(); // Does not seem to enable drop event if (!targetElement.classList.contains('drag-over-top')) { targetElement.classList.add('drag-over-top'); } } } // This is needed to enable drop event. dragOverTop(e: DragEvent) { if (!this.enableDragAndDrop) { return; } const targetElement: Element = (e.target as Element); const isTopPlaceHolder = targetElement.classList.contains('dnd-top-placeholder'); if (isTopPlaceHolder) { e.preventDefault(); } } async dropTop(e: DragEvent) { if (!this.enableDragAndDrop) { return; } e.preventDefault(); e.stopPropagation(); const currentNode: FlatNode = this.draggedTreeNode; if (currentNode.domainType !== CatalogueItemDomainType.Folder && currentNode.domainType !== CatalogueItemDomainType.VersionedFolder) { this.messageHandler.showWarning('Only folders are allowed at the top level.'); return; } try { // Top level tree node has no parent switch (currentNode.domainType) { case CatalogueItemDomainType.Folder: await this.resources.folder.update(currentNode.id, { id: currentNode.id, parentFolder: null }).toPromise(); break; case CatalogueItemDomainType.VersionedFolder: await this.resources.versionedFolder.update(currentNode.id, { id: currentNode.id, parentFolder: null }).toPromise(); break; default: this.messageHandler.showError(`Invalid domain type: ${currentNode.domainType}`); return; } if (this.rememberExpandedStates) { this.expandedPaths = this.expandedPaths.map((p: string) => { if (p.includes(currentNode.id)) { return p.slice(p.indexOf(currentNode.id)); } return p; }); localStorage.setItem('expandedPaths', JSON.stringify(this.expandedPaths)); } this.messageHandler.showSuccess(`${currentNode.domainType} moved successfully.`); this.broadcast.reloadCatalogueTree(); } catch (error) { this.messageHandler.showError(`There was a problem moving the ${currentNode.domainType}`, error); } // dragleave event did not seem to be triggered consistently on drop this.dragLeave(e); } // End Drag n Drop private getChildren = (node: MdmTreeItem) => { if (!node.children) { return []; } let children = []; if (this.justShowFolders && node.children) { children = node.children.filter(c => c.domainType === CatalogueItemDomainType.Folder || (this.shared.features.useVersionedFolders && c.domainType === CatalogueItemDomainType.VersionedFolder)); } else if (this.doNotShowDataClasses && node.children) { children = node.children.filter(c => c.domainType !== CatalogueItemDomainType.DataClass); } else { children = node.children; } if (this.filterByDomainType?.length > 0) { children = children.filter(c => this.filterByDomainType.includes(c.domainType)); } return of(children); }; private async refreshTree() { this.dataSource.data = this.node.children; if (this.rememberExpandedStates) { // Init extended paths if (!this.expandedPaths || this.expandedPaths.length === 0) { const storePaths = JSON.parse(localStorage.getItem('expandedPaths')); this.expandedPaths = storePaths ? storePaths : []; } } for (const expandedPath of this.expandedPaths) { /* `mat-tree` requires the ancestors to be expanded first. dataNodes: Flatten nodes Each extended path follow the pattern `<level0 node>/<level1 node>/.../<target node>. When the path is split, the index will correspond to the level. */ const path: string[] = expandedPath.split('/'); // Skip if parent path not in expandedPaths. if (!this.pathExists(path)) { continue; } for (let j = 0; j < path.length; j++) { const fnode = this.treeControl.dataNodes.find(dn => this.treeControl.getLevel(dn) === j && dn.id === path[j]); // Load children if they are not available if (this.hasChild(-1, fnode) && !fnode?.children) { const data = await this.expand(fnode.node); fnode.children = data; // Manually construct the FlatNodes and insert into the tree's dataNodes array const newNodes = fnode.children?.map((c: any) => { return new FlatNode( c, this.treeControl.getLevel(fnode) + 1, this.securityHandler.elementAccess(c)); }); this.treeControl.dataNodes.splice(this.treeControl.dataNodes.indexOf(fnode) + 1, 0, ...(newNodes || [])); } this.treeControl.expand(fnode); } } } private pathExists(path: string[]) { if (path.length > 1) { const currentPathExists = this.expandedPaths.includes(path.join('/')); if (currentPathExists) { return this.pathExists(path.slice(0, path.length - 1)); } else { // No need to go further if current path does not exists. return false; } } else if (path.length === 1) { return this.expandedPaths.includes(path[0]); } else { return false; } } /** * Construct absolute path from root to given tree node. */ private getExpandedPaths(fnode: FlatNode) { if (this.treeControl.getLevel(fnode) > 0) { const index = this.treeControl.dataNodes.indexOf(fnode) - 1; for (let i = index; i >= 0; i--) { const dn = this.treeControl.dataNodes[i]; if (this.treeControl.getLevel(dn) < this.treeControl.getLevel(fnode)) { return `${this.getExpandedPaths(dn)}/${fnode.id}`; } } } else { return fnode.id; } } }
MauroDataMapper/mdm-ui
src/app/shared/favorite-button/favorite-button.component.ts
<filename>src/app/shared/favorite-button/favorite-button.component.ts /* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, Input, OnDestroy, OnInit } from '@angular/core'; import { CatalogueItem } from '@maurodatamapper/mdm-resources'; import { BroadcastService, FavouriteHandlerService, SecurityHandlerService } from '@mdm/services'; import { Subject } from 'rxjs'; import { filter, takeUntil } from 'rxjs/operators'; @Component({ selector: 'mdm-favorite-button', templateUrl: './favorite-button.component.html', styleUrls: ['./favorite-button.component.scss'] }) export class FavoriteButtonComponent implements OnInit, OnDestroy { @Input() catalogueItem: CatalogueItem; isLoggedIn = false; isFavorite = false; private $unsubscribe = new Subject(); constructor( private securityHandler: SecurityHandlerService, private favorites: FavouriteHandlerService, private broadcast: BroadcastService) { } ngOnInit(): void { if (!this.catalogueItem) { return; } this.isLoggedIn = this.securityHandler.isLoggedIn(); if (!this.isLoggedIn) { return; } this.isFavorite = this.favorites.isAdded(this.catalogueItem); this.broadcast .onFavouritesChanged() .pipe( takeUntil(this.$unsubscribe), filter(data => data.element.id === this.catalogueItem.id) ) .subscribe(data => { this.isFavorite = data.name === 'add'; }); } ngOnDestroy(): void { this.$unsubscribe.next(); this.$unsubscribe.complete(); } toggle() { if (!this.catalogueItem) { return; } if (this.favorites.toggle(this.catalogueItem)) { this.isFavorite = this.favorites.isAdded(this.catalogueItem); } } }
MauroDataMapper/mdm-ui
src/app/diagram/diagram/diagram.model.ts
<filename>src/app/diagram/diagram/diagram.model.ts /* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { CatalogueItem } from '@maurodatamapper/mdm-resources'; export type DiagramMode = 'dataflow-model' | 'dataflow-class' | 'dataflow-element' | 'umlclass' | 'model-merging-graph'; export type DiagramCatalogueItem = CatalogueItem & { [key: string]: any }; export interface DiagramParameters { parent: DiagramCatalogueItem; }
MauroDataMapper/mdm-ui
src/app/utility/download-link/download-link.component.ts
/* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, EventEmitter, Input, OnChanges, Output } from '@angular/core'; import { MatTableDataSource } from '@angular/material/table'; @Component({ selector: 'mdm-download-link', templateUrl: './download-link.component.html', styleUrls: ['./download-link.component.scss'] }) export class DownloadLinkComponent implements OnChanges{ @Input() links: Array<HTMLAnchorElement>; @Output() readonly linksChange = new EventEmitter<Array<HTMLAnchorElement>>(); displayedColumns: string[] = ['link','delete']; dataSource = new MatTableDataSource<HTMLAnchorElement>(); constructor() { } deleteLink(link : HTMLAnchorElement) { const index = this.dataSource.data.indexOf(link); this.dataSource.data.splice(index,1); this.dataSource._updateChangeSubscription(); this.linksChange.emit(this.dataSource.data); } ngOnChanges(): void { this.dataSource = new MatTableDataSource<HTMLAnchorElement>(this.links); } }
MauroDataMapper/mdm-ui
src/app/services/utility/user-settings-handler.service.ts
<reponame>MauroDataMapper/mdm-ui<gh_stars>1-10 /* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Injectable } from '@angular/core'; import { MdmResourcesService } from '@mdm/modules/resources'; import { Observable } from 'rxjs'; import { SecurityHandlerService } from '@mdm/services/handlers/security-handler.service'; @Injectable({ providedIn: 'root' }) export class UserSettingsHandlerService { defaultSettings = { countPerTable: 20, counts: [5, 10, 20, 50], expandMoreDescription: false, favourites: [], includeModelSuperseded: true, includeDocumentSuperseded: false, includeDeleted: false, dataFlowDiagramsSetting: {} }; constructor( private resources: MdmResourcesService, private securityHandler: SecurityHandlerService ) { } getUserSettings() { let settings = JSON.parse(localStorage.getItem('userSettings')); if (!settings) { this.updateUserSettings(this.defaultSettings); settings = this.defaultSettings; } return settings; } updateUserSettings(setting) { localStorage.setItem('userSettings', JSON.stringify(setting)); } initUserSettings() { const promise = new Promise((resolve, reject) => { this.resources.catalogueUser.userPreferences(localStorage.getItem('userId')).subscribe(res => { const result = res.body; let settings = null; if (!result) { settings = this.defaultSettings; } else { // check if we have added new items but they don't exists already, then add them for (const property in this.defaultSettings) { if (this.defaultSettings.hasOwnProperty(property) && !result[property]) { result[property] = this.defaultSettings[property]; } } // save them into the localStorage settings = result; } // save it locally this.updateUserSettings(settings); resolve(settings); }, error => { reject(error); } ); }); return promise; } init() { if (this.securityHandler.isLoggedIn()) { return this.initUserSettings(); } } update(setting, value) { const storage = this.getUserSettings(); storage[setting] = value; this.updateUserSettings(storage); } get(setting) { const storage = this.getUserSettings(); return storage[setting]; } removeAll() { localStorage.removeItem('userSettings'); } saveOnServer(): Observable<any> { return this.resources.catalogueUser.updateUserPreferences(localStorage.getItem('userId'), this.getUserSettings()); } handleCountPerTable(items) { let counts = this.get('counts'); if (items && items.length < 5) { counts = []; } return counts; } }
MauroDataMapper/mdm-ui
src/app/terminology/term-list/create-term-dialog/create-term-dialog.component.ts
<filename>src/app/terminology/term-list/create-term-dialog/create-term-dialog.component.ts /* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, Inject, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; import { MdmResourcesService } from '@mdm/modules/resources'; import { CatalogueItemDomainType, TermDetail } from '@maurodatamapper/mdm-resources'; import { MessageHandlerService } from '@mdm/services'; import { HttpResponse } from '@angular/common/http'; import { catchError, finalize } from 'rxjs/operators'; import { EMPTY } from 'rxjs'; @Component({ selector: 'mdm-create-term-dialog', templateUrl: 'create-term-dialog.component.html', styleUrls: ['create-term-dialog.component.scss'] }) export class CreateTermDialogComponent implements OnInit { form: FormGroup; submitting = false; constructor( private resources: MdmResourcesService, private messageHandler: MessageHandlerService, private formBuilder: FormBuilder, private dialogRef: MatDialogRef<CreateTermDialogComponent>, @Inject(MAT_DIALOG_DATA) public data: any) { } ngOnInit() { this.form = this.formBuilder.group({ // eslint-disable-next-line @typescript-eslint/unbound-method code: [this.data.code, Validators.required], // eslint-disable-next-line @typescript-eslint/unbound-method definition: [this.data.definition, Validators.required], description: [this.data.description] }); } submit(form: FormGroup) { this.submitting = true; this.resources.terms.save(this.data.terminology.id, { domainType: CatalogueItemDomainType.Term, code: form.value.code, definition: form.value.definition, description: form.value.description }).pipe( catchError(error => { this.messageHandler.showError('Unable to create new term'); console.error(error); return EMPTY; }), finalize(() => this.submitting = false) ).subscribe((response: HttpResponse<TermDetail>) => { if (response.ok) { this.dialogRef.close(response.body); } else { this.messageHandler.showWarning(response.body); } this.submitting = false; }); } onCancel(): void { this.dialogRef.close(); } }
MauroDataMapper/mdm-ui
src/app/search/date-from-to/date-from-to.component.ts
<gh_stars>1-10 /* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, OnInit, ViewChild, Output, EventEmitter } from '@angular/core'; import { MatDatepicker } from '@angular/material/datepicker'; @Component({ selector: 'mdm-date-from-to', templateUrl: './date-from-to.component.html' }) export class DateFromToComponent implements OnInit { @Output() selectEvent = new EventEmitter<DateEventInfo>(); @ViewChild('dp1', { static: false }) datePicker1: MatDatepicker<Date>; @ViewChild('dp2', { static: false }) datePicker2: MatDatepicker<Date>; dtFrom: Date; dtTo: Date; oldVal: any; date1Options = { formatYear: 'yy', maxDate: null, minDate: null, startingDay: 1, showWeeks: false, showButtonBar: false }; date2Options = { formatYear: 'yy', maxDate: null, minDate: null, startingDay: 1, showWeeks: false, showButtonBar: false }; constructor() { } ngOnInit(): void { } datePicker1Changed(newValue, oldValue): any { // init for the first time, so NO Action if (oldValue === null && newValue === null) { return; } if (this.selectEvent) { // eslint-disable-next-line @typescript-eslint/no-use-before-define this.selectEvent.emit(new DateEventInfo(newValue, this.dtTo)); } if (newValue) { this.date2Options.minDate = newValue; } } datePicker2Changed(newValue, oldValue): any { // init for the first time, so NO Action if (oldValue === null && newValue === null) { return; } if (this.selectEvent) { // eslint-disable-next-line @typescript-eslint/no-use-before-define this.selectEvent.emit(new DateEventInfo(this.dtFrom, newValue)); } if (newValue) { this.date1Options.maxDate = newValue; } } public today(): any { this.dtFrom = null; this.dtTo = null; } public clear1(): any { this.dtFrom = null; this.date2Options.minDate = null; this.datePicker1Changed(null, this.oldVal); } public clear2(): any { this.dtTo = null; this.date1Options.maxDate = null; this.datePicker2Changed(null, this.oldVal); } public open1() { this.datePicker1.open(); } public open2() { this.datePicker2.open(); } } class DateEventInfo { public from: Date; public to: Date; constructor(from: Date, to: Date) { this.from = from; this.to = to; } }
MauroDataMapper/mdm-ui
src/app/app.component.spec.ts
/* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { TestBed, async } from '@angular/core/testing'; import { AppComponent } from './app.component'; import { ProfilePictureComponent } from './shared/profile-picture/profile-picture.component'; import { NgxSkeletonLoaderModule } from 'ngx-skeleton-loader'; import { ByteArrayToBase64Pipe } from './pipes/byte-array-to-base64.pipe'; import { MatTooltipModule } from '@angular/material/tooltip'; import { NavbarComponent } from './navbar/navbar.component'; import { FooterComponent } from './shared/footer/footer.component'; import { MatMenuModule } from '@angular/material/menu'; import { MatBadgeModule } from '@angular/material/badge'; import { MatToolbarModule } from '@angular/material/toolbar'; import { MatSidenavModule } from '@angular/material/sidenav'; import { UIRouterModule } from '@uirouter/angular'; import { ToastrModule } from 'ngx-toastr'; import { MdmResourcesService } from './modules/resources'; import { MatDialogModule } from '@angular/material/dialog'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { FeaturesService } from './services/features.service'; describe('AppComponent', () => { beforeEach(async(() => { TestBed.configureTestingModule({ imports: [ NgxSkeletonLoaderModule, MatTooltipModule, MatMenuModule, MatDialogModule, MatBadgeModule, MatToolbarModule, NoopAnimationsModule, MatSidenavModule, UIRouterModule.forRoot({ useHash: true }), ToastrModule.forRoot() ], providers: [ { provide: MdmResourcesService, useValue: {}, }, { provide: FeaturesService, useValue: jest.fn() } ], declarations: [ ProfilePictureComponent, ByteArrayToBase64Pipe, NavbarComponent, FooterComponent, AppComponent ], }).compileComponents(); })); it('should create the app', () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; expect(app).toBeTruthy(); }); it('should have as title \'mdm-ui\'', () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; expect(app.title).toEqual('mdm-ui'); }); });
MauroDataMapper/mdm-ui
src/app/services/features.service.spec.ts
<reponame>MauroDataMapper/mdm-ui /* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { MdmResourcesService } from '@mdm/modules/resources'; import { setupTestModuleForService } from '@mdm/testing/testing.helpers'; import { of } from 'rxjs'; import { FeaturesService } from './features.service'; interface MdmApiPropertiesStub { listPublic: jest.Mock; } interface MdmResourcesServiceStub { apiProperties: MdmApiPropertiesStub; } describe('FeaturesService', () => { let service: FeaturesService; const resourcesStub: MdmResourcesServiceStub = { apiProperties: { listPublic: jest.fn() } }; beforeEach(() => { // Default endpoint call resourcesStub.apiProperties.listPublic.mockImplementationOnce(() => of([])); service = setupTestModuleForService( FeaturesService, { providers: [ { provide: MdmResourcesService, useValue: resourcesStub } ] }); }); it('should be created', () => { expect(service).toBeTruthy(); }); });
MauroDataMapper/mdm-ui
src/app/modals/new-folder-modal/new-folder-modal.model.ts
/* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { ThemePalette } from '@angular/material/core'; import { ModalDialogStatus } from '@mdm/constants/modal-dialog-status'; export interface NewFolderModalConfiguration { okBtn?: string; cancelBtn?: string; btnType?: ThemePalette; modalTitle?: string; message?: string; inputLabel?: string; createRootFolder?: boolean; canVersion?: boolean; } export interface NewFolderModalResponse { status: ModalDialogStatus; label?: string; useVersionedFolders?: boolean; isVersioned?: boolean; }
MauroDataMapper/mdm-ui
src/app/shared/element-data-type/element-data-type.component.ts
<filename>src/app/shared/element-data-type/element-data-type.component.ts /* Copyright 2020-2021 University of Oxford and Health and Social Care Information Centre, also known as NHS Digital Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 */ import { Component, OnInit, Input } from '@angular/core'; import { StateHandlerService } from '@mdm/services/handlers/state-handler.service'; import { ElementTypesService } from '@mdm/services/element-types.service'; import { from, Observable } from 'rxjs'; import { groupBy, mergeMap, toArray } from 'rxjs/operators'; import { Categories } from '@mdm/model/model-types.model'; import { CatalogueItem, CatalogueItemDomainType, DataType, MdmResponse, Uuid } from '@maurodatamapper/mdm-resources'; import { MdmResourcesService } from '@mdm/modules/resources'; @Component({ selector: 'mdm-element-data-type', templateUrl: './element-data-type.component.html', styleUrls: ['./element-data-type.component.sass'] }) export class ElementDataTypeComponent implements OnInit { @Input() elementDataType: DataType; @Input() hideName: boolean; @Input() onlyShowRefDataClass: boolean; @Input() hideEnumList: boolean; @Input() initiallyShowEnumList: boolean; @Input() mcParentDataModel: any; @Input() newWindow: boolean; @Input() showTypeName: boolean; showMoreIcon: boolean; showing = false; referenceClass: any; referenceClassLink: any; modelResource: CatalogueItem; link: any; categories: any[]; allRecords: any[]; enumsCount: number; hasCategory: boolean; allRecordsWithGroups: any[]; // default values showCount = 5; toggleShowEnums = false; constructor( private stateHandler: StateHandlerService, private elementTypes: ElementTypesService, private resources: MdmResourcesService ) {} ngOnInit() { if (this.elementDataType !== null && this.elementDataType !== undefined) { let parentDataModelId = this.mcParentDataModel ? this.mcParentDataModel.id : null; if (!parentDataModelId) { parentDataModelId = this.elementDataType.model; } if ( this.elementDataType.domainType === 'ReferenceType' && this.elementDataType.referenceClass ) { this.referenceClass = this.elementDataType.referenceClass; this.referenceClassLink = this.stateHandler.getURL('dataclass', { id: this.elementDataType.referenceClass.id, dataModelId: parentDataModelId }); } this.link = this.elementTypes.getLinkUrl(this.elementDataType); } if (this.elementDataType.domainType === CatalogueItemDomainType.ModelDataType) { this.loadModelResource(); } if (this.elementDataType.enumerationValues) { if ( this.elementDataType && this.elementDataType.domainType === 'EnumerationType' ) { // Handle Category in enum // ........................................................................... this.categories = []; this.allRecords = [].concat(this.elementDataType.enumerationValues); this.enumsCount = this.allRecords.length; this.hasCategory = false; for (const element of this.allRecords) { if (element && element.category) { this.hasCategory = true; break; } } const categories = from(this.allRecords).pipe( groupBy(record => record.category), mergeMap(group => group.pipe(toArray())) ); categories.subscribe((cats: Categories[]) => { const categoryNames = []; let hasEmptyCategory = false; cats.forEach(x => { if (x.category !== null) { categoryNames.push(x.category); } else { hasEmptyCategory = true; } }); if (hasEmptyCategory) { categoryNames.push(null); } this.allRecordsWithGroups = []; categoryNames.forEach(category => { if (category !== null) { this.categories.push({ key: category, value: category }); } this.allRecordsWithGroups.push({ id: category !== null ? category : null, category: category !== null ? category : null, isCategoryRow: true }); cats.filter(x => x.category === category) .forEach(row => { this.allRecordsWithGroups.push(row); }); }); // ........................................................................... if (this.allRecordsWithGroups.length > this.showCount) { this.showMoreIcon = true; this.showing = false; } }); } } } showMore = (element: any) => { if (this.showMoreIcon && !this.showing) { const elements = element.parentElement.offsetParent.getElementsByClassName( 'moreEnumerationKeyValue' ); for (const elem of elements) { elem.classList.remove('hiddenMoreEnumerationKeyValue'); } element.innerHTML = 'hide <i class=\'fas fa-caret-down fa-xs\'></i>'; } else { const elements = element.parentElement.offsetParent.getElementsByClassName( 'moreEnumerationKeyValue' ); for (const elem of elements) { elem.classList.add('hiddenMoreEnumerationKeyValue'); } element.innerHTML = '... more <i class=\'fas fa-caret-down fa-xs\'></i>'; } this.showing = !this.showing; }; showEnums = () => { this.toggleShowEnums = !this.toggleShowEnums; }; private loadModelResource() { const id: Uuid = this.elementDataType.modelResourceId; const domainType: CatalogueItemDomainType = this.elementDataType.modelResourceDomainType; let request: Observable<MdmResponse<CatalogueItem>>; switch (domainType) { case CatalogueItemDomainType.ReferenceDataModel: request = this.resources.referenceDataModel.get(id); break; case CatalogueItemDomainType.CodeSet: request = this.resources.codeSet.get(id); break; case CatalogueItemDomainType.Terminology: request = this.resources.terminology.get(id); break; } if (!request) { return; } request.subscribe(response => this.modelResource = response.body); } }
woolfi182/nestjs-cypher-query-builder
lib/neo4j-config.interface.ts
<reponame>woolfi182/nestjs-cypher-query-builder import { ModuleMetadata } from "@nestjs/common"; import { Connection, DriverConstructor } from "cypher-query-builder"; export type Neo4jScheme = | "neo4j" | "neo4j+s" | "neo4j+scc" | "bolt" | "bolt+s" | "bolt+scc"; export type Neo4jOptions = { scheme: Neo4jScheme; host: string; port: number | string; username: string; password: string; database?: string; }; export type ConnectionWithDriver = Connection & { driver: DriverConstructor; }; export type Neo4jAsyncOptions = Pick<ModuleMetadata, "imports"> & { useFactory: (..._args: any[]) => Promise<Neo4jOptions>; inject?: any[]; };
woolfi182/nestjs-cypher-query-builder
lib/index.ts
<gh_stars>0 export * from "./neo4j.constants"; export * from "./neo4j.errors"; export * from "./neo4j-config.interface"; export * from "./neo4j.module";
woolfi182/nestjs-cypher-query-builder
lib/neo4j.module.ts
<filename>lib/neo4j.module.ts<gh_stars>0 import { DynamicModule, Global, Module } from "@nestjs/common"; import { Connection } from "cypher-query-builder"; import { NEO4J, NEO4J_MODULE_OPTIONS, defaultOptions } from "./neo4j.constants"; import { Neo4jOptions, ConnectionWithDriver, Neo4jAsyncOptions, } from "./neo4j-config.interface"; import { ConnectionError } from "./neo4j.errors"; const createProvider = async ( options: Neo4jOptions = defaultOptions ): Promise<Connection> => { const connection = new Connection( `${options.scheme}://${options.host}:${options.port}`, { username: options.username, password: <PASSWORD>, } ) as ConnectionWithDriver; try { await connection.driver.verifyConnectivity(); } catch (error) { throw new ConnectionError(error); } return connection; }; @Global() @Module({}) export class Neo4jModule { static forRoot(config: Neo4jOptions): DynamicModule { const provider = { provide: NEO4J, useFactory: async (): Promise<Connection> => createProvider(config), }; return { module: Neo4jModule, providers: [provider], exports: [provider], }; } static forRootAsync(asyncOptions: Neo4jAsyncOptions): DynamicModule { const connectionProvider = { provide: NEO4J, useFactory: async (options: Neo4jOptions) => { return createProvider(options); }, inject: [NEO4J_MODULE_OPTIONS], }; return { module: Neo4jModule, imports: asyncOptions.imports, providers: [ { provide: NEO4J_MODULE_OPTIONS, useFactory: asyncOptions.useFactory, inject: asyncOptions.inject || [], }, connectionProvider, ], exports: [connectionProvider], }; } }
woolfi182/nestjs-cypher-query-builder
lib/neo4j.errors.ts
export class ConnectionError extends Error { public details: any; constructor(oldError: Error) { super(); this.message = "Connection to Neo4j DB was not esteblished"; this.name = "Connection error"; this.stack = oldError.stack; this.details = oldError.message; } }
woolfi182/nestjs-cypher-query-builder
lib/neo4j.constants.ts
import { Neo4jOptions } from "./neo4j-config.interface"; export const NEO4J = "NEO4J_CONNECTION"; export const NEO4J_MODULE_OPTIONS = "NEO4J_MODULE_OPTIONS"; export const defaultOptions: Neo4jOptions = { scheme: "neo4j", host: "localhost", port: 7687, username: "neo4j", password: "<PASSWORD>", };
holdenk/luigi-rewrite-rug
.atomist/editors/LuigiTargetHDFSRewrite.ts
import { Project } from "@atomist/rug/model/Project"; import { Editor, Parameter, Tags } from "@atomist/rug/operations/Decorators"; import { EditProject } from "@atomist/rug/operations/ProjectEditor"; import { Pattern } from "@atomist/rug/operations/RugOperation"; /** * Rewrite HDFS targets. */ @Editor("LuigiTargetHDFSRewrite", "Rewrite HDFS targets") @Tags("documentation") export class LuigiTargetHDFSRewrite implements EditProject { @Parameter({ displayName: "Local Target Dir", description: "Local Target Dir to use in place of HDFS", pattern: Pattern.any, validInput: "any file path", minLength: 1, maxLength: 100, }) public inputParameter: string; public edit(project: Project) { project.addFile("hello.txt", "Hello, World!\n" + this.inputParameter + "\n"); } } export const luigiTargetHDFSRewrite = new LuigiTargetHDFSRewrite();
khalifagroup/vscode-docker
src/configureWorkspace/configureNode.ts
<reponame>khalifagroup/vscode-docker /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE.md in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { WorkspaceFolder } from 'vscode'; import { IActionContext } from '../../extension.bundle'; import { DockerDebugScaffoldContext } from '../debugging/DebugHelper'; import { dockerDebugScaffoldingProvider } from '../debugging/DockerDebugScaffoldingProvider'; import { PlatformOS } from '../utils/platform'; import { getComposePorts, getExposeStatements, IPlatformGeneratorInfo, PackageInfo } from './configure'; export let configureNode: IPlatformGeneratorInfo = { genDockerFile, genDockerCompose, genDockerComposeDebug, defaultPorts: [3000], initializeForDebugging, }; function genDockerFile(serviceNameAndRelativePath: string, platform: string, os: string | undefined, ports: number[], { cmd, author, version, artifactName }: Partial<PackageInfo>): string { let exposeStatements = getExposeStatements(ports); return `FROM node:10.13-alpine ENV NODE_ENV production WORKDIR /usr/src/app COPY ["package.json", "package-lock.json*", "npm-shrinkwrap.json*", "./"] RUN npm install --production --silent && mv node_modules ../ COPY . . ${exposeStatements} CMD ${cmd}`; } function genDockerCompose(serviceNameAndRelativePath: string, platform: string, os: string | undefined, ports: number[]): string { return `version: '2.1' services: ${serviceNameAndRelativePath}: image: ${serviceNameAndRelativePath} build: . environment: NODE_ENV: production ${getComposePorts(ports)}`; } function genDockerComposeDebug(serviceNameAndRelativePath: string, platform: string, os: string | undefined, ports: number[], { fullCommand: cmd }: Partial<PackageInfo>): string { const inspectConfig = '--inspect=0.0.0.0:9229'; const cmdArray: string[] = cmd.split(' '); if (cmdArray[0].toLowerCase() === 'node') { cmdArray.splice(1, 0, inspectConfig); cmd = `command: ${cmdArray.join(' ')}`; } else { cmd = `## set your startup file here\n command: node ${inspectConfig} index.js`; } return `version: '2.1' services: ${serviceNameAndRelativePath}: image: ${serviceNameAndRelativePath} build: . environment: NODE_ENV: development ${getComposePorts(ports, 9229)} ${cmd}`; } async function initializeForDebugging(context: IActionContext, folder: WorkspaceFolder, platformOS: PlatformOS, dockerfile: string, packageInfo: PackageInfo): Promise<void> { const scaffoldContext: DockerDebugScaffoldContext = { folder: folder, platform: 'node', actionContext: context, dockerfile: dockerfile, } await dockerDebugScaffoldingProvider.initializeNodeForDebugging(scaffoldContext); }
khalifagroup/vscode-docker
src/configureWorkspace/configureJava.ts
<filename>src/configureWorkspace/configureJava.ts /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE.md in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { getComposePorts, getExposeStatements, IPlatformGeneratorInfo, PackageInfo } from './configure'; export let configureJava: IPlatformGeneratorInfo = { genDockerFile, genDockerCompose, genDockerComposeDebug, defaultPorts: [3000], initializeForDebugging: undefined, }; function genDockerFile(serviceNameAndRelativePath: string, platform: string, os: string | undefined, ports: number[], { cmd, author, version, artifactName }: Partial<PackageInfo>): string { let exposeStatements = getExposeStatements(ports); const artifact = artifactName ? artifactName : `${serviceNameAndRelativePath}.jar`; return ` FROM openjdk:8-jdk-alpine VOLUME /tmp ARG JAVA_OPTS ENV JAVA_OPTS=$JAVA_OPTS ADD ${artifact} ${serviceNameAndRelativePath}.jar ${exposeStatements} ENTRYPOINT exec java $JAVA_OPTS -jar ${serviceNameAndRelativePath}.jar # For Spring-Boot project, use the entrypoint below to reduce Tomcat startup time. #ENTRYPOINT exec java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar ${serviceNameAndRelativePath}.jar `; } function genDockerCompose(serviceNameAndRelativePath: string, platform: string, os: string | undefined, ports: number[]): string { return `version: '2.1' services: ${serviceNameAndRelativePath}: image: ${serviceNameAndRelativePath} build: . ${getComposePorts(ports)}`; } function genDockerComposeDebug(serviceNameAndRelativePath: string, platform: string, os: string | undefined, ports: number[], { fullCommand: cmd }: Partial<PackageInfo>): string { return `version: '2.1' services: ${serviceNameAndRelativePath}: image: ${serviceNameAndRelativePath} build: context: . dockerfile: Dockerfile environment: JAVA_OPTS: -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005,quiet=y ${getComposePorts(ports, 5005)}`; }
khalifagroup/vscode-docker
src/tasks/python/PythonTaskHelper.ts
<gh_stars>0 /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE.md in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as fse from 'fs-extra'; import * as os from 'os'; import * as path from 'path'; import { PythonScaffoldingOptions } from '../../debugging/DockerDebugScaffoldingProvider'; import { inferPythonArgs, PythonDefaultDebugPort, PythonTarget } from '../../utils/pythonUtils'; import { unresolveWorkspaceFolder } from "../../utils/resolveVariables"; import { DockerBuildOptions } from "../DockerBuildTaskDefinitionBase"; import { DockerBuildTaskDefinition } from "../DockerBuildTaskProvider"; import { DockerContainerPort, DockerContainerVolume, DockerRunOptions, DockerRunTaskDefinitionBase } from "../DockerRunTaskDefinitionBase"; import { DockerRunTaskDefinition } from "../DockerRunTaskProvider"; import { addVolumeWithoutConflicts, DockerBuildTaskContext, DockerRunTaskContext, DockerTaskScaffoldContext, getDefaultContainerName, getDefaultImageName, inferImageName, TaskHelper } from "../TaskHelper"; import { PythonExtensionHelper } from "./PythonExtensionHelper"; export interface PythonTaskRunOptions { file?: string; module?: string; args?: string[]; wait?: boolean; debugPort?: number } export interface PythonRunTaskDefinition extends DockerRunTaskDefinitionBase { python?: PythonTaskRunOptions; } export class PythonTaskHelper implements TaskHelper { public async provideDockerBuildTasks(context: DockerTaskScaffoldContext): Promise<DockerBuildTaskDefinition[]> { return [ { type: 'docker-build', label: 'docker-build', platform: 'python', dockerBuild: { tag: getDefaultImageName(context.folder.name), dockerfile: unresolveWorkspaceFolder(context.dockerfile, context.folder), /* eslint-disable no-template-curly-in-string */ context: '${workspaceFolder}' } } ]; } public async provideDockerRunTasks(context: DockerTaskScaffoldContext, options: PythonScaffoldingOptions): Promise<DockerRunTaskDefinition[]> { const runOptions: PythonTaskRunOptions = { args: inferPythonArgs(options.projectType, context.ports) }; if ('file' in options.target) { runOptions.file = options.target.file; } else { runOptions.module = options.target.module; } return [{ type: 'docker-run', label: 'docker-run: debug', dependsOn: ['docker-build'], python: runOptions }]; } public async getDockerBuildOptions(context: DockerBuildTaskContext, buildDefinition: DockerBuildTaskDefinition): Promise<DockerBuildOptions> { const buildOptions = buildDefinition.dockerBuild; /* eslint-disable no-template-curly-in-string */ buildOptions.context = buildOptions.context || '${workspaceFolder}'; buildOptions.dockerfile = buildOptions.dockerfile || '${workspaceFolder}/Dockerfile'; buildOptions.tag = buildOptions.tag || getDefaultImageName(context.folder.name); return buildOptions; } public async getDockerRunOptions(context: DockerRunTaskContext, runDefinition: DockerRunTaskDefinition): Promise<DockerRunOptions> { // tslint:disable no-unsafe-any const helperOptions : PythonTaskRunOptions = runDefinition.python || {}; const runOptions : DockerRunOptions = runDefinition.dockerRun; const target: PythonTarget = helperOptions.file ? { file: helperOptions.file, } : { module: helperOptions.module }; const launcherCommand : string = PythonExtensionHelper.getRemotePtvsdCommand( target, helperOptions.args, { host: '0.0.0.0', port: helperOptions.debugPort || PythonDefaultDebugPort, wait: helperOptions.wait === undefined ? true : helperOptions.wait } ); const launcherFolder: string = await PythonExtensionHelper.getLauncherFolderPath(); runOptions.image = inferImageName( runDefinition, context, context.folder.name ); runOptions.containerName = runOptions.containerName || getDefaultContainerName(context.folder.name); const dbgLogsFolder = path.join(os.tmpdir(), context.folder.name); // The debugger will complain if the logs directory does not exist. if (!(await fse.pathExists(dbgLogsFolder))) { await fse.emptyDir(dbgLogsFolder); } // User input is honored in all of the below. runOptions.volumes = this.inferVolumes(runOptions, launcherFolder, dbgLogsFolder); runOptions.ports = this.inferPorts(runOptions, helperOptions); runOptions.entrypoint = runOptions.entrypoint || 'python'; runOptions.command = runOptions.command || launcherCommand; runOptions.env = this.addDebuggerEnvironmentVars(runOptions.env); runOptions.portsPublishAll = runOptions.portsPublishAll || true; return runOptions; } private inferVolumes(runOptions: DockerRunOptions, launcherFolder: string, dbgLogsFolder: string): DockerContainerVolume[] { if (!launcherFolder || !dbgLogsFolder) { return; } const volumes = runOptions?.volumes ? [...runOptions.volumes] : []; const dbgVolumes: DockerContainerVolume[] = [ { localPath: launcherFolder, containerPath: '/pydbg', permissions: 'ro' }, { localPath: dbgLogsFolder, containerPath: '/dbglogs', permissions: 'rw' }]; dbgVolumes.map(dbgVol => { addVolumeWithoutConflicts(volumes, dbgVol) }); return volumes; } private inferPorts(runOptions: DockerRunOptions, pythonOptions: PythonTaskRunOptions): DockerContainerPort[] { const ports: DockerContainerPort[] = runOptions?.ports ? [...runOptions.ports] : []; const debugPort = pythonOptions.debugPort || PythonDefaultDebugPort; if (ports.find(port => port.containerPort === debugPort) === undefined) { ports.push({ containerPort: debugPort, hostPort: debugPort }); } return ports; } private addDebuggerEnvironmentVars(env: { [key: string]: string }): { [key: string]: string } { env = env ?? {}; const debuggerVars = PythonExtensionHelper.getDebuggerEnvironmentVars(); Object.keys(debuggerVars).map(varName => { env[varName] = debuggerVars[varName]; }); return env; } } export const pythonTaskHelper = new PythonTaskHelper();
khalifagroup/vscode-docker
src/telemetry/TelemetryPublisher.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.md in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; export interface TelemetryEvent { eventName: string; measurements?: { [key: string]: number }; properties?: { [key: string]: string }; } export interface ITelemetryPublisher { onEvent: vscode.Event<TelemetryEvent>; publishEvent(event: TelemetryEvent): void; } export class TelemetryPublisher extends vscode.Disposable implements ITelemetryPublisher { private readonly onEventEmitter: vscode.EventEmitter<TelemetryEvent>; public constructor() { super(() => this.onEventEmitter.dispose()); this.onEventEmitter = new vscode.EventEmitter<TelemetryEvent>(); } public get onEvent(): vscode.Event<TelemetryEvent> { return this.onEventEmitter.event; } public publishEvent(event: TelemetryEvent): void { this.onEventEmitter.fire(event); } }
khalifagroup/vscode-docker
test/buildAndRun.test.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE.md in the project root for license information. *--------------------------------------------------------------------------------------------*/ // The module 'assert' provides assertion methods from node import * as AdmZip from 'adm-zip'; import * as assert from 'assert'; import * as fse from 'fs-extra'; import { Context, Suite } from 'mocha'; import * as path from 'path'; import { commands, Uri } from 'vscode'; import { IActionContext, createAzExtOutputChannel, IAzExtOutputChannel } from 'vscode-azureextensionui'; import { configure, ext, httpsRequestBinary, Platform } from '../extension.bundle'; import * as assertEx from './assertEx'; import { shouldSkipDockerTest } from './dockerInfo'; import { getTestRootFolder, testInEmptyFolder, testUserInput } from './global.test'; import { TestTerminalProvider } from './TestTerminalProvider'; let testRootFolder: string = getTestRootFolder(); /** * Downloads and then extracts only a specific folder and its subfolders. */ async function unzipFileFromUrl(uri: Uri, sourceFolderInZip: string, outputFolder: string): Promise<void> { let zipContents = await httpsRequestBinary(uri.toString()); let zip = new AdmZip(zipContents); await extractFolderTo(zip, sourceFolderInZip, outputFolder); } /** * Extracts only a specific folder and its subfolders. * Not using AdmZip.extractAllTo because depending on the .zip file we may end up with an extraneous top-level folder */ async function extractFolderTo(zip: AdmZip, sourceFolderInZip: string, outputFolder: string): Promise<void> { if (!(sourceFolderInZip.endsWith('/') || sourceFolderInZip.endsWith('\\'))) { sourceFolderInZip += '/'; } var zipEntries = zip.getEntries(); for (let entry of zipEntries) { if (entry.entryName.startsWith(sourceFolderInZip)) { let relativePath = entry.entryName.slice(sourceFolderInZip.length); if (!relativePath) { // root folder continue; } let outPath = path.join(outputFolder, relativePath); if (entry.isDirectory) { //console.log(`Folder: ${entry.entryName}`); await fse.mkdirs(outPath) } else { //console.log(`File: ${entry.entryName}`); let data: Buffer = entry.getData(); await fse.writeFile(outPath, data); } } } } suite("Build Image", function (this: Suite): void { this.timeout(2 * 60 * 1000); const outputChannel: IAzExtOutputChannel = createAzExtOutputChannel('Docker extension tests', 'docker'); ext.outputChannel = outputChannel; async function testConfigureAndBuildImage( platform: Platform, configureInputs: (string | undefined)[], buildInputs: (string | undefined)[] ): Promise<void> { // Set up simulated user input configureInputs.unshift(platform); let testTerminalProvider = new TestTerminalProvider(); ext.terminalProvider = testTerminalProvider; let context: IActionContext = { telemetry: { properties: {}, measurements: {} }, errorHandling: { issueProperties: {} } }; await testUserInput.runWithInputs(configureInputs, async () => { await configure(context, testRootFolder); }); // Build image let dockerFile = Uri.file(path.join(testRootFolder, 'Dockerfile')); await testUserInput.runWithInputs(buildInputs, async () => { await commands.executeCommand('vscode-docker.images.build', dockerFile); }); let { outputText, errorText } = await testTerminalProvider.currentTerminal!.exit(); assert.equal(errorText, '', 'Expected no errors from Build Image'); assertEx.assertContains(outputText, 'Successfully built'); assertEx.assertContains(outputText, 'Successfully tagged') } // Go testInEmptyFolder("Go", async function (this: Context) { let context: IActionContext = { telemetry: { properties: {}, measurements: {} }, errorHandling: { issueProperties: {} } }; if (await shouldSkipDockerTest(context, { linuxContainers: true })) { this.skip(); return; } let uri = 'https://codeload.github.com/cloudfoundry-community/simple-go-web-app/zip/master'; // https://github.com/cloudfoundry-community/simple-go-web-app/archive/master.zip await unzipFileFromUrl(Uri.parse(uri), 'simple-go-web-app-master', testRootFolder); await testConfigureAndBuildImage( 'Go', ['3001'], ['testoutput:latest'] ); // CONSIDER: Run the built image }); // CONSIDER TESTS: // 'Java' // '.NET Core Console' // 'ASP.NET Core' // 'Node.js' // 'Python' // 'Ruby' });
khalifagroup/vscode-docker
src/commands/networks/inspectNetwork.ts
<gh_stars>1-10 /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE.md in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Network } from "dockerode"; import { IActionContext, openReadOnlyJson } from "vscode-azureextensionui"; import { ext } from "../../extensionVariables"; import { NetworkTreeItem } from "../../tree/networks/NetworkTreeItem"; import { callDockerodeWithErrorHandling } from "../../utils/callDockerodeWithErrorHandling"; export async function inspectNetwork(context: IActionContext, node?: NetworkTreeItem): Promise<void> { if (!node) { node = await ext.networksTree.showTreeItemPicker<NetworkTreeItem>(NetworkTreeItem.contextValue, { ...context, noItemFoundErrorMessage: 'No images are availalbe to inspect' }); } const network: Network = node.getNetwork() // eslint-disable-next-line @typescript-eslint/promise-function-async, @typescript-eslint/tslint/config const inspectInfo: {} = await callDockerodeWithErrorHandling(() => network.inspect(), context); // inspect is missing type in @types/dockerode await openReadOnlyJson(node, inspectInfo); }
khalifagroup/vscode-docker
src/commands/containers/viewContainerLogs.ts
<gh_stars>1-10 /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE.md in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IActionContext } from 'vscode-azureextensionui'; import { ext } from '../../extensionVariables'; import { ContainerTreeItem } from '../../tree/containers/ContainerTreeItem'; export async function viewContainerLogs(context: IActionContext, node?: ContainerTreeItem): Promise<void> { if (!node) { node = await ext.containersTree.showTreeItemPicker<ContainerTreeItem>(ContainerTreeItem.allContextRegExp, { ...context, noItemFoundErrorMessage: 'No continers are available to view logs' }); } const terminal = ext.terminalProvider.createTerminal(node.fullTag); terminal.sendText(`docker logs -f ${node.containerId}`); terminal.show(); }
khalifagroup/vscode-docker
src/commands/networks/createNetwork.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE.md in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { window } from 'vscode'; import { IActionContext } from 'vscode-azureextensionui'; import { ext } from '../../extensionVariables'; import { callDockerodeWithErrorHandling } from '../../utils/callDockerodeWithErrorHandling'; export async function createNetwork(context: IActionContext): Promise<void> { const name = await ext.ui.showInputBox({ value: '', prompt: 'Name of the network' }); const engineVersion = await ext.dockerode.version(); const drivers = engineVersion.Os === 'windows' ? [ { label: 'nat' }, { label: 'transparent' } ] : [ { label: 'bridge' }, { label: 'host' }, { label: 'macvlan' } ]; const driverSelection = await ext.ui.showQuickPick( drivers, { canPickMany: false, placeHolder: 'Select the network driver to use (default is "bridge").' } ); /* eslint-disable-next-line @typescript-eslint/promise-function-async */ const result = <{ id: string }>await callDockerodeWithErrorHandling(() => ext.dockerode.createNetwork({ Name: name, Driver: driverSelection.label }), context); /* eslint-disable-next-line @typescript-eslint/no-floating-promises */ window.showInformationMessage(`Network Created with ID ${result.id.substr(0, 12)}`); }
khalifagroup/vscode-docker
src/configureWorkspace/configUtils.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE.md in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as path from 'path'; import vscode = require('vscode'); import { IAzureQuickPickItem, TelemetryProperties } from 'vscode-azureextensionui'; import { DockerOrchestration } from '../constants'; import { ext } from "../extensionVariables"; import { captureCancelStep } from '../utils/captureCancelStep'; import { Platform, PlatformOS } from '../utils/platform'; export type ConfigureTelemetryProperties = { configurePlatform?: Platform; configureOs?: PlatformOS; orchestration?: DockerOrchestration; packageFileType?: string; // 'build.gradle', 'pom.xml', 'package.json', '.csproj', '.fsproj' packageFileSubfolderDepth?: string; // 0 = project/etc file in root folder, 1 = in subfolder, 2 = in subfolder of subfolder, etc. }; export type ConfigureTelemetryCancelStep = 'folder' | 'platform' | 'os' | 'compose' | 'port' | 'project' | 'pythonFile'; export async function captureConfigureCancelStep<TReturn, TPrompt extends (...args: []) => Promise<TReturn>>(cancelStep: ConfigureTelemetryCancelStep, properties: TelemetryProperties, prompt: TPrompt): Promise<TReturn> { return await captureCancelStep(cancelStep, properties, prompt)(); } /** * Prompts for port numbers * @throws `UserCancelledError` if the user cancels. */ export async function promptForPorts(ports: number[]): Promise<number[]> { let opt: vscode.InputBoxOptions = { placeHolder: ports.join(', '), prompt: 'What port(s) does your app listen on? Enter a comma-separated list, or empty for no exposed port.', value: ports.join(', '), validateInput: (value: string): string | undefined => { let result = splitPorts(value); if (!result) { return 'Ports must be a comma-separated list of positive integers (1 to 65535), or empty for no exposed port.'; } return undefined; } } return splitPorts(await ext.ui.showInputBox(opt)); } /** * Splits a comma separated string of port numbers */ export function splitPorts(value: string): number[] | undefined { if (!value || value === '') { return []; } let elements = value.split(',').map(p => p.trim()); let matches = elements.filter(p => p.match(/^-*\d+$/)); if (matches.length < elements.length) { return undefined; } let ports = matches.map(Number); // If anything is non-integral or less than 1 or greater than 65535, it's not valid if (ports.some(p => !Number.isInteger(p) || p < 1 || p > 65535)) { return undefined; } return ports; } /** * Prompts for a platform * @throws `UserCancelledError` if the user cancels. */ export async function quickPickPlatform(platforms?: Platform[]): Promise<Platform> { let opt: vscode.QuickPickOptions = { matchOnDescription: true, matchOnDetail: true, placeHolder: 'Select Application Platform' } platforms = platforms || [ 'Node.js', '.NET: ASP.NET Core', '.NET: Core Console', 'Python: Django', 'Python: Flask', 'Python: General', 'Java', 'C++', 'Go', 'Ruby', 'Other' ]; const items = platforms.map(p => <IAzureQuickPickItem<Platform>>{ label: p, data: p }); let response = await ext.ui.showQuickPick(items, opt); return response.data; } /** * Prompts for an OS * @throws `UserCancelledError` if the user cancels. */ export async function quickPickOS(): Promise<PlatformOS> { let opt: vscode.QuickPickOptions = { matchOnDescription: true, matchOnDetail: true, placeHolder: 'Select Operating System' } const OSes: PlatformOS[] = ['Windows', 'Linux']; const items = OSes.map(p => <IAzureQuickPickItem<PlatformOS>>{ label: p, data: p }); let response = await ext.ui.showQuickPick(items, opt); return response.data; } export async function quickPickGenerateComposeFiles(): Promise<boolean> { let opt: vscode.QuickPickOptions = { placeHolder: 'Include optional Docker Compose files?' } let response = await ext.ui.showQuickPick( [ { label: 'No', data: false }, { label: 'Yes', data: true } ], opt); return response.data; } export function getSubfolderDepth(outputFolder: string, filePath: string): string { let relativeToRoot = path.relative(outputFolder, path.resolve(outputFolder, filePath)); let matches = relativeToRoot.match(/[\/\\]/g); let depth: number = matches ? matches.length : 0; return String(depth); } export function genCommonDockerIgnoreFile(platformType: Platform): string { const ignoredItems = [ '**/.classpath', '**/.dockerignore', '**/.env', '**/.git', '**/.gitignore', '**/.project', '**/.settings', '**/.toolstarget', '**/.vs', '**/.vscode', '**/*.*proj.user', '**/*.dbmdl', '**/*.jfm', '**/azds.yaml', platformType !== 'Node.js' ? '**/bin' : undefined, '**/charts', '**/docker-compose*', '**/Dockerfile*', '**/node_modules', '**/npm-debug.log', '**/obj', '**/secrets.dev.yaml', '**/values.dev.yaml', 'README.md' ]; return ignoredItems.filter(item => item !== undefined).join('\n'); }
khalifagroup/vscode-docker
src/tree/volumes/LocalVolumeInfo.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE.md in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { VolumeInspectInfo } from "dockerode"; import { ILocalItem } from "../LocalRootTreeItemBase"; type VolumeInspectInfoExt = VolumeInspectInfo & { CreatedAt: string }; /** * Wrapper class for Dockerode item, which has inconsistent names/types */ export class LocalVolumeInfo implements ILocalItem { public data: VolumeInspectInfoExt; public constructor(data: VolumeInspectInfo) { this.data = <VolumeInspectInfoExt>data; } public get createdTime(): number { /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ return new Date(this.data.CreatedAt).valueOf(); } public get volumeName(): string { return this.data.Name; } public get treeId(): string { return this.volumeName; } }
khalifagroup/vscode-docker
src/utils/callDockerodeWithErrorHandling.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE.md in the project root for license information. *--------------------------------------------------------------------------------------------*/ /* eslint-disable unicorn/filename-case */ import { IActionContext, parseError } from "vscode-azureextensionui"; export async function callDockerodeWithErrorHandling<T>(dockerodeCallback: () => Promise<T>, context: IActionContext): Promise<T> { try { return await dockerodeCallback(); } catch (err) { context.errorHandling.suppressReportIssue = true; const error = parseError(err); if (error && error.errorType === 'ENOENT') { throw new Error(`Failed to connect. Is Docker installed and running? Error: ${error.message}`); } throw err; } }
khalifagroup/vscode-docker
src/telemetry/TelemetryReporterProxy.ts
<reponame>khalifagroup/vscode-docker /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.md in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { ITelemetryReporter } from "vscode-azureextensionui"; import { ITelemetryPublisher } from "./TelemetryPublisher"; export class TelemetryReporterProxy implements ITelemetryReporter { public constructor( private readonly publisher: ITelemetryPublisher, private readonly wrappedReporter: ITelemetryReporter) { } public sendTelemetryEvent(eventName: string, properties?: { [key: string]: string; }, measurements?: { [key: string]: number; }): void { this.wrappedReporter.sendTelemetryEvent(eventName, properties, measurements); this.publisher.publishEvent({ eventName, measurements, properties }); } }
khalifagroup/vscode-docker
src/commands/registries/dockerHub/openDockerHubInBrowser.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE.md in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IActionContext } from "vscode-azureextensionui"; import { dockerHubUrl } from "../../../constants"; import { ext } from "../../../extensionVariables"; import { DockerHubNamespaceTreeItem } from "../../../tree/registries/dockerHub/DockerHubNamespaceTreeItem"; import { DockerHubRepositoryTreeItem } from "../../../tree/registries/dockerHub/DockerHubRepositoryTreeItem"; import { registryExpectedContextValues } from "../../../tree/registries/registryContextValues"; import { RemoteTagTreeItem } from "../../../tree/registries/RemoteTagTreeItem"; import { openExternal } from "../../../utils/openExternal"; export async function openDockerHubInBrowser(context: IActionContext, node?: DockerHubNamespaceTreeItem | DockerHubRepositoryTreeItem | RemoteTagTreeItem): Promise<void> { if (!node) { node = await ext.registriesTree.showTreeItemPicker<DockerHubNamespaceTreeItem>(registryExpectedContextValues.dockerHub.registry, { ...context, noItemFoundErrorMessage: 'No Docker Hub registries available to browse' }); } let url = dockerHubUrl; if (node instanceof DockerHubNamespaceTreeItem) { url += `u/${node.namespace}`; } else if (node instanceof DockerHubRepositoryTreeItem) { url += `r/${node.parent.namespace}/${node.repoName}`; } else { const repoTI = <DockerHubRepositoryTreeItem>node.parent; url += `r/${repoTI.parent.namespace}/${repoTI.repoName}/tags`; } await openExternal(url); }
khalifagroup/vscode-docker
src/tree/containers/LocalContainerInfo.ts
<reponame>khalifagroup/vscode-docker /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE.md in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { ContainerInfo } from "dockerode"; import { ILocalImageInfo } from "../images/LocalImageInfo"; /** * Wrapper class for Dockerode item, which has inconsistent names/types */ export class LocalContainerInfo implements ILocalImageInfo { private _containerName: string; public data: ContainerInfo; public constructor(data: ContainerInfo) { this.data = data; } public get createdTime(): number { return this.data.Created * 1000; } public get containerId(): string { return this.data.Id; } public get containerName(): string { if (!this._containerName) { const names = this.data.Names.map(name => name.substr(1)); // Remove start '/' // Linked containers may have names containing '/'; their one "canonical" names will not. const canonicalName = names.find(name => name.indexOf('/') === -1); this._containerName = canonicalName ?? names[0]; } return this._containerName; } public get fullTag(): string { return this.data.Image; } public get imageId(): string { return this.data.ImageID; } public get networks(): string[] { return Object.keys(this.data.NetworkSettings.Networks); } public get ports(): number[] { return this.data.Ports.map(p => p.PublicPort); } public get state(): string { return this.data.State; } public get status(): string { return this.data.Status; } public get treeId(): string { // include state in treeId so that auto-refresh will detect and show a new icon when state changes return this.containerId + this.state; } }
khalifagroup/vscode-docker
src/utils/delay.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE.md in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; export async function delay(ms: number, token?: vscode.CancellationToken): Promise<void> { return new Promise<void>((resolve, reject) => { let cancellationListener: vscode.Disposable; const timeout = setTimeout(() => { /* eslint-disable-next-line no-unused-expressions */ cancellationListener?.dispose(); resolve(); }, ms); if (token) { cancellationListener = token.onCancellationRequested(() => { cancellationListener.dispose(); clearTimeout(timeout); reject(); }); } }); }