SmartIT_Extensions/BMC/smart-it-full-helix/scripts/app/change/ci-relations-directive.js

1015 lines
67 KiB
JavaScript

"use strict";
(function () {
'use strict';
angular.module('changeModule')
.directive('ciRelations', ['assetService', 'categoriesService', 'configurationModel', 'userModel', '$q', 'metadataModel', '$filter', 'ciRelationsModel', 'events', 'systemAlertService', '$timeout', '$rootScope', 'assetConsoleModel', 'consoleService', 'relationModel',
function (assetService, categoriesService, configurationModel, userModel, $q, metadataModel, $filter, ciRelationsModel, events, systemAlertService, $timeout, $rootScope, assetConsoleModel, consoleService, relationModel) {
return {
restrict: 'E',
replace: true,
templateUrl: 'views/change/ci-relations.html',
scope: {
company: '=company',
model: '=',
displayLimit: '=displaylimit',
parent: '@parent',
context: '='
},
controller: ['$scope', '$modal', function ($scope, $modal) {
$scope.currentRelatedCIs = [];
$scope.currentRelatedCIsData = [];
$scope.getTableStyle = function () {
var rowHeight = 43;
var headerHeight = 40;
return {
height: ($scope.currentRelatedCIs.length * rowHeight + headerHeight) + "px",
'border-left': '1px solid #d4d4d4',
'border-right': '1px solid #d4d4d4',
overflow: 'hidden'
};
};
if ($scope.context && $scope.context.id) {
$scope.selectedItems = [];
$scope.relatedCIgridOtions = {
headerRowHeight: 43,
rowHeight: 40,
showSelectionCheckbox: true,
selectWithCheckboxOnly: true,
selectedItems: $scope.selectedItems,
enableColumnResize: true,
data: 'currentRelatedCIsData',
columnDefs: [{
field: "name",
displayName: $filter('i18n')('asset.attributes.name'),
cellTemplate: '<div class=\"ngCellText ci-search-section__results_name_col\" ng-class=\"col.colIndex()\">' +
'<a href="" ng-click= "showPreview(row.entity);" class=\"ci-search-section__results_name_col\"><span class=\"ngCellText ci-search-section__results_name_col\">{{row.getProperty(col.field)}}</span></a></div>',
}, {
field: "status.value",
displayName: $filter('i18n')('asset.status')
}, {
field: "assetType",
displayName: $filter('i18n')('asset.attributes.type')
}, {
field: "manufacturer",
displayName: $filter('i18n')('asset.attributes.manufacturer')
}, {
field: "model",
displayName: $filter('i18n')('asset.attributes.model')
}, {
field: "related",
displayName: $filter('i18n')('asset.attributes.related')
},
]
};
relationModel.getRelations($scope.context.id, $scope.context.type).then(function (data) {
$scope.currentRelatedCIs = data;
_.each(data, function (item) {
var obj = item.realObject;
obj.relationshipType = item.relationshipType;
obj.related = $filter('i18n')('common.relationship.type.' + item.relationshipType);
obj.ticketType = item.type;
obj.desc = item.desc;
obj.tag = item.tag;
$scope.currentRelatedCIsData.push(obj);
});
$scope.model.templateRelatedCIsData = $scope.currentRelatedCIsData;
});
}
$scope.showCINameAsLink = ($scope.parent === 'changeWizard');
$scope.chunkInfos = [];
$scope.userModel = userModel;
$scope.selections = {
relations: ['relatedto', 'upgrades', 'repairs', 'impacts', 'installs', 'moves', 'changes', 'removes']
};
//DRSMX-43931: Setting searchTextCharLimit to 0 Because TransUnion customer has CIs with more than 255 characters in the name.In the later Hotfixes we have plan to handle it through CCS settings.
$scope.searchTextCharLimit = 0;
var assetMetadata, filterDictionary, modalInstance;
$scope.filterConfig = angular.copy(configurationModel.get('ciSearch.assetConsoleFilter'));
filterDictionary = _.keyBy($scope.filterConfig, 'label');
$scope.filterPreferenceGroup = 'CIFilter';
//get saved presets from the backend
var userPreference = userModel.getUserPreferences($scope.filterPreferenceGroup).then(function (config) {
$scope.userSavedSearchPresets = _.uniqBy(config, 'name') || [];
var configIndex = _.findIndex($scope.filterConfig, { name: 'custom' });
_.forEach($scope.userSavedSearchPresets, function (userPreset) {
if (!userPreset.systemgenerated) {
var savedPreset = {
name: userPreset.name,
id: userPreset.id,
type: 'custom',
filters: _.map(userPreset.value, function (value) {
var filterValue, filterName, filterLabel, option;
filterName = value.option;
if (filterDictionary[value.filter]) {
option = _.find(filterDictionary[value.filter].options, { name: value.option });
}
else if (value.filter === 'sites' && filterDictionary.site) {
option = _.find(filterDictionary.site.options, { name: value.option });
}
if (value.realOption && value.realOption.criteria) {
filterValue = value.realOption.criteria.value;
}
else if (option && option.criteria) {
filterValue = option.criteria.value;
}
else {
filterValue = value;
}
var item = {
active: true,
criteria: { name: value.filter, value: filterValue },
name: filterName,
label: filterLabel,
type: value.filter !== 'keywords' ? 'dynamic' : 'keywords'
};
return item;
})
};
if (configIndex !== -1 && savedPreset.id !== 'allAssets') {
$scope.filterConfig[configIndex].expanded = true;
$scope.filterConfig[configIndex].options.push(savedPreset);
}
}
});
});
var userPromise = userModel.getFullCurrentUserData().then(function () {
var userData = userModel.userFullData, filterApprovedByMe = _.find(filterDictionary.approvedBy.options, { label: 'me' }), filterCreatedByMe = _.find(filterDictionary.createdBy.options, { label: 'me' }), filterManagedByMe = _.find(filterDictionary.managedBy.options, { label: 'me' }), filterOwnedByMe = _.find(filterDictionary.owner.options, { label: 'me' }), filterSupportedByMe = _.find(filterDictionary.supportedBy.options, { label: 'me' }), filterUsedByMe = _.find(filterDictionary.usedBy.options, { label: 'me' });
filterApprovedByMe.subLabel = filterCreatedByMe.subLabel = filterManagedByMe.subLabel =
filterOwnedByMe.subLabel = filterSupportedByMe.subLabel = filterUsedByMe.subLabel = userData.fullName;
filterApprovedByMe.criteria.value = filterCreatedByMe.criteria.value = filterManagedByMe.criteria.value =
filterOwnedByMe.criteria.value = filterSupportedByMe.criteria.value = filterUsedByMe.criteria.value =
[{ id: userData.personId }];
var mySiteFilter = _.find(filterDictionary.site.options, { label: 'mySite' });
mySiteFilter.criteria.value = [{
name: userModel.userFullData.site.name,
companyName: userModel.userFullData.company.name,
region: userModel.userFullData.site.region,
siteGroup: userModel.userFullData.site.siteGroup
}];
mySiteFilter.subLabel = userModel.userFullData.site.name;
var mySiteGroupFilter = _.find(filterDictionary.siteGroup.options, { label: 'mySiteGroup' });
mySiteGroupFilter.criteria.value = [{
companyName: userModel.userFullData.company.name,
region: userModel.userFullData.site.region,
siteGroup: userModel.userFullData.site.siteGroup
}];
mySiteGroupFilter.subLabel = userModel.userFullData.site.siteGroup;
var myRegionFilter = _.find(filterDictionary.region.options, { label: 'myRegion' });
myRegionFilter.criteria.value = [{
companyName: userModel.userFullData.company.name,
region: userModel.userFullData.site.region
}];
myRegionFilter.subLabel = userModel.userFullData.site.region;
});
//for defect SW00514456
$scope.changeMetadata = {};
metadataModel.getMetadataByType(EntityVO.TYPE_CHANGE).then(function (metadata) {
angular.extend($scope.changeMetadata, metadata);
});
var assetPromise = metadataModel.getMetadataByType(EntityVO.TYPE_ASSET).then(function (metadata) {
assetMetadata = metadata;
_.forEach(metadata.statuses, function (status) {
filterDictionary.statuses.options.push({
name: status.label,
type: 'dynamic',
criteria: {
name: 'ticketSpecificStatuses',
value: [status.name]
}
});
});
_.forEach(metadata.assetTypes, function (assetType) {
filterDictionary.ciType.options.push({
name: assetType.label,
type: 'dynamic',
criteria: {
name: 'assetTypes',
value: [assetType.name]
},
criteriaValue: assetType.name
});
//add subtypes
assetType.subType.forEach(function (subType) {
filterDictionary.assetSubType.options.push({
name: subType.label,
type: 'dynamic',
filterName: 'assetSubTypes',
isHidden: false,
criteria: {
name: 'assetSubTypes',
value: [subType.name],
typeName: assetType.name
}
});
});
});
});
$q.all([userPromise, assetPromise, userPreference]).then(function () {
$q.all([ciRelationsModel.populateConfiguration()])
.then(function () {
//on initial load, pass the index as 0 for searches object
addRow(0);
});
});
function addRow(index) {
var emptyrow = _.find($scope.model.searches, function (row) {
return row.selectedFilters.length === 0 && row.searchKeywords.length === 0;
});
$scope.chunkInfos[index] = {
chunkInfo: {
startIndex: 0,
chunkSize: 100
}
};
if (!emptyrow) {
$scope.model.searches.push({
config: angular.copy($scope.filterConfig),
selectedFilters: [],
searchKeywords: [],
showResults: false,
selectedCount: 0,
linkedCount: null,
isSearching: false,
sortInfo: { fields: [], directions: [], columns: [] },
criteria: { sortInfo: [] },
selectedItems: [],
relationsMap: [],
results: [],
gridColumns: [],
//tableColumns are used for html table
tableColumns: [{
attributeName: 'name',
displayName: $filter('i18n')('asset.attributes.name'),
visible: true
}, {
attributeName: 'classId',
displayName: $filter('i18n')('asset.attributes.classId'),
visible: true
}, {
attributeName: 'type',
displayName: $filter('i18n')('asset.attributes.type'),
visible: true
}, {
attributeName: 'status.value',
displayName: $filter('i18n')('asset.status'),
visible: true
}, {
attributeName: 'assetExtension.serialNumber',
displayName: $filter('i18n')('asset.attributes.serialNumber'),
visible: true
}, {
attributeName: 'site.name',
displayName: $filter('i18n')('asset.attributes.site'),
visible: true
}, {
attributeName: 'product.name',
displayName: $filter('i18n')('asset.attributes.productName'),
visible: true
}]
});
$scope.model.searches[index].gridColumns = angular.copy(_.sortBy(_.filter(ciRelationsModel.columnsConfig, 'visible'), 'order'));
if (window.isRtl) {
$scope.model.searches[index].gridColumns.reverse();
}
//gridOptions are used in the ng-grid table
$scope.model.searches[index].gridOptions = {
data: 'model.searches[' + index + '].results',
index: index,
headerRowHeight: 43,
rowHeight: 40,
sortInfo: $scope.model.searches[index].sortInfo,
useExternalSorting: true,
enableColumnResize: true,
showSelectionCheckbox: true,
virtualizationThreshold: 100,
// without this the ng-grid loads only the first 6 rows
selectWithCheckboxOnly: true,
checkboxHeaderTemplate: '<label class="ngSelectionHeaderLabel"><input class="ngSelectionHeader" type="checkbox" ng-show="multiSelect" ng-model="allSelected" ng-change="selectAllCIs(search,allSelected, \'grid\')"/></label>',
selectedItems: $scope.model.searches[index].selectedItems,
afterSelectionChange: function (rowItem) {
if (rowItem.length) {
_.forEach(rowItem, function (row) {
$scope.selectCI($scope.model.searches[index], row, 'grid');
});
}
else {
$scope.selectCI($scope.model.searches[index], rowItem, 'grid');
}
},
columnDefs: $scope.model.searches[index].gridColumns
};
}
}
$scope.setGridWidth = {};
function buildFilterCriteria(filters, searchKeywords) {
var filterCriteria = {}, regionKey, siteGroupKey, sitesKey = 'sites', sites = [], regionValueObj = {}, siteGroupValueObj = {}, siteValueObj = {};
_.forEach(filters, function (filter) {
var criteria = filter.criteria, isMultiSelect = _.isArray(criteria.value), name = criteria.name;
if (filterCriteria[name]) {
if (isMultiSelect) {
filterCriteria[name] = _.union(filterCriteria[name], criteria.value);
}
else {
filters.splice(_.findIndex(filters, { name: filter.name }), 1);
filterCriteria[name] = criteria.value;
}
}
else {
if (criteria.name === 'region' || criteria.name === 'siteGroup' || criteria.name === 'sites') {
if (criteria.name === 'region') {
regionKey = criteria.name;
regionValueObj = criteria.value[0];
regionValueObj.id = regionKey;
sites.push(regionValueObj);
}
else if (criteria.name === 'siteGroup') {
siteGroupKey = criteria.name;
siteGroupValueObj = criteria.value[0];
siteGroupValueObj.id = siteGroupKey;
sites.push(siteGroupValueObj);
}
else if (criteria.name === 'sites') {
siteValueObj = criteria.value[0];
sites.push(siteValueObj);
}
filterCriteria[sitesKey] = sites;
}
else {
filterCriteria[name] = criteria.value;
}
}
});
if (searchKeywords && searchKeywords.length > 0) {
searchKeywords = _.map(searchKeywords.split(','), _.trim);
filterCriteria.keywords = searchKeywords;
}
return filterCriteria;
}
$scope.toggleResultsGrid = function (search) {
search.showResults = !search.showResults;
if (search.showResults) {
$timeout(function () {
//This is a hack to make ng-grid render all items
$(window).resize();
});
}
};
$scope.getProductCategoriesByCompany = function (searchText) {
var categoryName = 'product', params = {
entityType: EntityVO.TYPE_ASSET,
categoryType: categoryName,
searchText: searchText,
criteria: {
company: $scope.company
}
};
return categoriesService.searchCategories(params).then(function (result) {
var category = _.find(assetMetadata.categories, function (category) {
return category.name === categoryName;
});
return _.map(result.items, function (item) {
if (item.length) {
var serializedValue = _.compact(item).join(' > '), tiers = {};
for (var i = 0; i < category.listOfTiers.length; i++) {
tiers[category.listOfTiers[i].name] = item[i];
}
return {
value: serializedValue,
attributeMap: { categorizations: [{ name: categoryName, tiers: tiers }] }
};
}
});
});
};
$scope.isWindowRtl = function () {
return window.isRtl;
};
$scope.searchCIs = function (filter) {
filter.isSearching = true;
filter.showResults = false;
filter.selectedCount = 0;
filter.gridColumns = angular.copy(_.sortBy(_.filter(ciRelationsModel.columnsConfig, 'visible'), 'order'));
if (window.isRtl) {
filter.gridColumns.reverse();
}
filter.gridOptions.columnDefs = filter.gridColumns;
filter.gridOptions.sortInfo.directions[0] = 'ASC';
$scope.chunkInfos[filter.gridOptions.index] = {
chunkInfo: {
startIndex: 0,
chunkSize: 100
}
};
var filterCriteria = {
filterCriteria: buildFilterCriteria(filter.selectedFilters, filter.searchKeywords),
chunkInfo: $scope.chunkInfos[filter.gridOptions.index].chunkInfo,
sortInfo: {
sortFieldName: 'name',
sortFieldOrder: 'ASC'
},
attributeNames: ['name', 'desc', 'status', 'classId']
},
// calculate ng-grid width
gridWidth = 100;
filter.lastUsedFilterCriteria = filterCriteria;
consoleService.getAssetList(filterCriteria, 'cisearch').then(function (result) {
filter.results = result.itemList;
filter.totalMatchCount = result.totalCount;
filter.isSearching = false;
filter.linkedCount = 0;
$scope.$emit(events.LINKED_COUNT, $scope.model.searches);
$scope.$emit(events.CI_SEARCH, $scope.model.searches);
//This is a hack to make ng-grid render all items
$timeout(function () {
$(window).resize();
});
}).finally(function () {
filter.isSearching = false;
});
_.forEach(filter.gridColumns, function (column) {
gridWidth += column.width;
});
$scope.setGridWidth = { width: gridWidth + 'px' };
};
$scope.showMoreCIs = function (filter) {
filter.isSearching = true;
filter.dataLoading = true;
$scope.chunkInfos[filter.gridOptions.index].chunkInfo.startIndex += $scope.chunkInfos[filter.gridOptions.index].chunkInfo.chunkSize;
var filterCriteria = {
filterCriteria: buildFilterCriteria(filter.selectedFilters, filter.searchKeywords),
chunkInfo: $scope.chunkInfos[filter.gridOptions.index].chunkInfo,
sortInfo: {
sortFieldName: 'name',
sortFieldOrder: 'ASC'
},
attributeNames: ['name', 'desc', 'status', 'classId']
};
if (!_.isArray(filter.criteria.sortInfo)) {
filterCriteria.sortInfo = filter.criteria.sortInfo;
}
filter.lastUsedFilterCriteria = filterCriteria;
consoleService.getAssetList(filterCriteria, 'cisearch').then(function (result) {
result.itemList.forEach(function (item) {
item.status.value = $filter('localizeLabel')(item.status.value, EntityVO.TYPE_STATUS, EntityVO.TYPE_ASSET);
item.type = $filter('localizeLabel')(item.type, 'type', EntityVO.TYPE_ASSET);
$scope.model.searches[filter.gridOptions.index].results.push(item);
});
if (filter.allQueryResultsSelected || filter.allQueryItemsRelation && filter.allQueryItemsRelation.length > 0) {
$timeout(function () {
if (filter.allQueryResultsSelected) {
$scope.selectAllCIs(filter, true, 'grid');
}
if (filter.allQueryItemsRelation && filter.allQueryItemsRelation.length > 0) {
_.forEach(filter.allQueryItemsRelation, function (relationInfo) {
$scope.linkCIs(filter, relationInfo.relationshipType, true);
});
}
});
}
//This is a hack to make ng-grid render all items
$timeout(function () {
$(window).resize();
});
$scope.$emit(events.LINKED_COUNT, $scope.model.searches);
}).finally(function () {
filter.isSearching = false;
filter.dataLoading = false;
});
};
$scope.addAdditionalQuery = function () {
var index = $scope.model.searches.length;
addRow(index);
};
$scope.unlinkRelatedCIs = function () {
var parent = {}, ciToRemove = [];
parent.parentType = $scope.context.type;
parent.parentId = $scope.context.id;
_.each($scope.selectedItems, function (selectedCI) {
var obj = {};
obj.id = selectedCI.reconciliationId;
obj.type = selectedCI.ticketType;
obj.details = { 'parentDisplayId': $scope.context.displayId };
obj.relationshipType = selectedCI.relationshipType;
ciToRemove.push(obj);
$scope.currentRelatedCIsData = _.filter($scope.currentRelatedCIsData, function (element) { return element.instanceId != selectedCI.instanceId; });
});
relationModel.removeRelation(parent, ciToRemove).then(function () {
$scope.selectedItems.splice(0, $scope.selectedItems.length);
$scope.model.templateRelatedCIsData = $scope.currentRelatedCIsData;
ciToRemove = [];
});
};
$scope.linkCIs = function (filter, relation, ignoreSelectedState) {
filter.linked = true;
filter.linkedCount = 0;
_.forEach(filter.results, function (ci) {
if (ci.selected || ignoreSelectedState) {
if (!ci.relations) {
ci.relations = [];
}
if (ci.relations.indexOf(relation) < 0) {
ci.relations.push(relation);
var index = _.findIndex(filter.relationsMap, { resultID: ci.instanceId });
if (index !== -1) {
filter.relationsMap[index].type.push(relation);
}
else {
var relationArr = { type: [relation], resultID: ci.instanceId };
filter.relationsMap.push(relationArr);
}
}
}
if (ci.relations && ci.relations.length > 0) {
filter.linkedCount++;
}
});
//Saving information about relation of all CIs matching search criteria
if (filter.allQueryResultsSelected) {
var relationInfo = {
relationshipType: relation,
tag: EntityVO.TYPE_LINKEDITEM,
type: EntityVO.TYPE_ASSET,
searchCriteria: filter.lastUsedFilterCriteria,
matchesCount: filter.totalMatchCount
};
if (!filter.allQueryItemsRelation) {
filter.allQueryItemsRelation = [relationInfo];
}
else {
if (!_.find(filter.allQueryItemsRelation, { relationshipType: relation })) {
filter.allQueryItemsRelation.push(relationInfo);
}
}
}
if (filter.allQueryItemsRelation && filter.allQueryItemsRelation.length > 0) {
filter.linkedCount = filter.totalMatchCount;
}
$scope.$emit(events.LINKED_COUNT, $scope.model.searches);
};
$scope.unlinkCIs = function (filter) {
_.forEach(filter.results, function (ci) {
if (ci.selected && ci.relations && ci.relations.length > 0) {
ci.relations = [];
filter.linkedCount--;
}
});
if (filter.relationsMap) {
filter.relationsMap = [];
}
filter.allQueryItemsRelation = [];
var itemsList = filter.results;
filter.linkedCount = 0;
for (var i = 0; i < itemsList.length; i++) {
if (itemsList[i].relations && itemsList[i].relations.length > 0) {
filter.linkedCount++;
}
}
$scope.$emit(events.LINKED_COUNT, $scope.model.searches);
};
$scope.removeLink = function (filter, item, tag) {
item.relations = _.reject(item.relations, function (relation) {
return relation === tag;
});
if (item.relations.length === 0) {
filter.linkedCount--;
}
var index = _.findIndex(filter.relationsMap, { resultID: item.instanceId });
if (index !== -1) {
filter.relationsMap[index].type = _.reject(filter.relationsMap[index].type, function (relation) {
return relation === tag;
});
}
filter.allQueryItemsRelation = _.reject(filter.allQueryItemsRelation, { relationshipType: tag });
if (filter.allQueryItemsRelation.length === 0) {
var itemsList = filter.results;
filter.linkedCount = 0;
for (var i = 0; i < itemsList.length; i++) {
if (itemsList[i].relations && itemsList[i].relations.length > 0) {
filter.linkedCount++;
}
}
}
$scope.$emit(events.LINKED_COUNT, $scope.model.searches);
};
$scope.selectCI = function (filter, item, origin) {
if (!item.selected && (filter.allQueryResultsSelected || filter.allVisibleItemsSelected)) {
filter.allQueryResultsSelected = false;
filter.allVisibleItemsSelected = false;
}
else {
item.selected ? filter.selectedCount++ : filter.selectedCount--;
}
if (origin === 'grid') {
filter.selectedCount = 0;
var itemsList = filter.results;
for (var i = 0; i < itemsList.length; i++) {
if (itemsList[i].instanceId === item.entity.instanceId) {
itemsList[i].selected = item.selected;
}
if (itemsList[i].selected) {
filter.selectedCount++;
}
}
}
};
$scope.selectAllCIs = function (filter, selectAll, origin) {
filter.allVisibleItemsSelected = selectAll;
var itemsList = filter.results;
for (var i = 0; i < itemsList.length; i++) {
itemsList[i].selected = selectAll;
}
if (!filter.allQueryResultsSelected) {
filter.selectedCount = selectAll ? i : 0;
}
if (origin === 'grid') {
if (filter.gridOptions && filter.gridOptions.ngGrid && filter.gridOptions.ngGrid.filteredRows) {
var rows = filter.gridOptions.ngGrid.filteredRows;
for (i = 0; i < rows.length; i++) {
rows[i].selected = selectAll;
if (rows[i].clone) {
rows[i].clone.selected = selectAll;
}
if (selectAll) {
if (!_.find(filter.selectedItems, { id: rows[i].entity.id })) {
filter.selectedItems.push(rows[i].entity);
}
}
}
}
}
if (!selectAll) {
filter.allQueryResultsSelected = false;
filter.selectedItems = [];
filter.selectedCount = 0;
}
};
$scope.selectAllItemsInThisQuery = function (filter, selectAll) {
filter.allQueryResultsSelected = selectAll;
if (selectAll) {
filter.selectedCount = filter.totalMatchCount;
$timeout(function () {
$scope.selectAllCIs(filter, selectAll, 'grid');
});
}
else {
filter.selectedCount = 0;
var itemsList = filter.results;
for (var i = 0; i < itemsList.length; i++) {
if (itemsList[i].selected) {
filter.selectedCount++;
}
}
$scope.$emit(events.LINKED_COUNT, $scope.model.searches);
}
};
$scope.$watch('userModel.isAccessibleUser', function () {
_.forEach($scope.model.searches, function (search) {
var itemsList = search.results;
for (var i = 0; i < itemsList.length; i++) {
itemsList[i].selected = false;
}
if (search.gridOptions && search.gridOptions.ngGrid && search.gridOptions.ngGrid.filteredRows) {
var rows = search.gridOptions.ngGrid.filteredRows;
for (i = 0; i < rows.length; i++) {
rows[i].selected = false;
if (rows[i].clone) {
rows[i].clone.selected = false;
}
}
search.gridOptions.ngGrid.filteredRows = [];
}
if (search.gridOptions && search.gridOptions.$gridScope && search.gridOptions.$gridScope.selectedItems) {
search.gridOptions.$gridScope.selectedItems = [];
}
if (search.gridOptions && search.gridOptions.selectedItems) {
search.gridOptions.selectedItems = [];
}
if (search.selectedItems && search.selectedItems.length > 0) {
search.selectedItems = [];
}
search.selectedCount = 0;
});
}, true);
$scope.sortColumn = function (filter, column) {
filter.dataLoading = true;
var columns = {
name: 'name', assetId: 'CIid', 'status.value': 'status',
'serialNumber': 'serialNumber', 'product.name': 'productName',
'site.name': 'siteName'
};
if (column.field) {
if (!filter.gridOptions.sortInfo.directions[0]) {
filter.gridOptions.sortInfo.directions[0] = 'asc';
}
else {
if (filter.gridOptions.sortInfo.columns.length === 0) {
filter.gridOptions.sortInfo.directions[0] = 'DESC';
}
else {
if (filter.gridOptions.sortInfo.columns[0].field !== column.field) {
filter.gridOptions.sortInfo.directions[0] = 'DESC';
}
}
}
filter.criteria.sortInfo = {
sortFieldName: columns[column.field],
sortFieldOrder: filter.gridOptions.sortInfo.directions[0].toUpperCase()
};
}
else if (column.attributeName) {
var sortColumnIndex = _.findIndex(filter.tableColumns, { attributeName: filter.criteria.sortInfo.sortFieldName });
if (filter.criteria.sortInfo.sortFieldName === column.attributeName) {
filter.tableColumns[sortColumnIndex].sortOrder =
filter.tableColumns[sortColumnIndex].sortOrder === 'ASC' ? 'DESC' : 'ASC';
}
else {
if (sortColumnIndex !== -1) {
delete filter.tableColumns[sortColumnIndex].sortOrder;
}
sortColumnIndex = _.findIndex(filter.tableColumns, { attributeName: column.attributeName });
filter.tableColumns[sortColumnIndex].sortOrder = 'ASC';
}
filter.criteria.sortInfo = {
sortFieldName: columns[column.attributeName],
sortFieldOrder: filter.tableColumns[sortColumnIndex].sortOrder
};
}
var filterCriteria = {
filterCriteria: buildFilterCriteria(filter.selectedFilters, filter.searchKeywords),
chunkInfo: {
startIndex: 0,
chunkSize: ($scope.chunkInfos[filter.gridOptions.index].chunkInfo.startIndex + $scope.chunkInfos[filter.gridOptions.index].chunkInfo.chunkSize)
},
sortInfo: filter.criteria.sortInfo,
attributeNames: ['name', 'desc', 'status', 'classId']
};
filter.lastUsedFilterCriteria = filterCriteria;
consoleService.getAssetList(filterCriteria, 'cisearch').then(function (result) {
filter.results = result.itemList;
filter.linkedCount = 0;
filter.selectedCount = 0;
filter.allQueryResultsSelected = false;
filter.allVisibleItemsSelected = false;
filter.dataLoading = false;
if (filter.allQueryResultsSelected || filter.allQueryItemsRelation && filter.allQueryItemsRelation.length > 0) {
$timeout(function () {
if (filter.allQueryResultsSelected) {
$scope.selectAllCIs(filter, true, 'grid');
}
if (filter.allQueryItemsRelation && filter.allQueryItemsRelation.length > 0) {
_.forEach(filter.allQueryItemsRelation, function (relationInfo) {
$scope.linkCIs(filter, relationInfo.relationshipType, true);
});
}
});
}
_.forEach(filter.relationsMap, function (relationMap) {
var index = _.findIndex(filter.results, { instanceId: relationMap.resultID });
if (index >= 0) {
if (!filter.results[index].relations) {
filter.results[index].relations = [];
}
filter.results[index].relations = relationMap.type;
}
});
$scope.$emit(events.LINKED_COUNT, $scope.model.searches);
});
};
$scope.columnResizeonMouseDown = function (event, filter, col) {
$(document).mouseup({ filter: filter, col: col }, $scope.columnResizing);
};
$scope.columnResizing = function (e) {
var filter = e.data.filter, col = e.data.col;
$(document).off('mouseup', $scope.columnResizing);
filter.gridOptions.$gridScope.hasUserChangedGridColumnWidths = false;
var colsToUpdate = {}, gridWidth = 100;
_.forEach(filter.gridOptions.$gridScope.columns, function (column) {
if (col.field === column.field && column.width !== column.colDef.width) {
if (ciRelationsModel.columnsConfig[column.colDef.name]) {
ciRelationsModel.columnsConfig[column.colDef.name].width = column.width;
}
colsToUpdate[column.colDef.name] = {
width: column.width
};
_.forEach(filter.gridOptions.columnDefs, function (columnDef) {
if (col.field === columnDef.field && columnDef.width !== column.width) {
columnDef.width = column.width;
}
});
}
// calculate ng-grid new width
gridWidth += column.width;
});
ciRelationsModel.updateColumnConfig(colsToUpdate);
$scope.setGridWidth = { width: gridWidth + 'px' };
};
$scope.showPreview = function (row) {
modalInstance = $modal.open({
templateUrl: 'views/change/ci-relation-preview.html',
windowClass: 'action-blade',
size: 'extra-lg',
controller: ['$scope', 'rowData', function ($scope, rowData) {
$scope.assetIdsObject = {
assetId: rowData.reconciliationId,
assetClassId: rowData.classId
};
}],
resolve: {
rowData: function () {
return row;
}
}
});
};
$scope.$on('$stateChangeStart', function () {
if (modalInstance) {
modalInstance.dismiss();
}
});
$scope.savePresets = function (filter, wizardMode) {
if (wizardMode === false) {
var parentElem = angular.element('#link-CI_action-blade-id').parent().parent();
parentElem.addClass('ci-search-section__relations_action_blade');
}
var modalInstance = $modal.open({
templateUrl: 'views/change/ci-relation-save-preset-action-blade.html',
windowClass: 'action-blade',
size: 'sm',
controller: ['$scope', 'filter', '$modalInstance', function ($scope, filter, $modalInstance) {
$scope.selectedFilters = filter.selectedFilters;
$scope.searchKeywords = filter.searchKeywords.length ? _.map(filter.searchKeywords.split(','), _.trim) : filter.searchKeywords;
$scope.saveDisabled = $scope.presetFilterName ? false : true;
$scope.$watch('presetFilterName', function () {
$scope.saveDisabled = $scope.presetFilterName ? false : true;
});
$scope.submit = function () {
$scope.savingFilterPreset = true;
//check if the preset name already exists
var configIndex = _.findIndex(filter.config, { name: 'custom' }), presetExists = false;
for (var x = 0; x < filter.config[configIndex].options.length; x++) {
var opt = filter.config[configIndex].options[x];
if ($scope.presetFilterName && opt.name.toLowerCase() === $scope.presetFilterName.toLowerCase()) {
presetExists = true;
break;
}
}
if (presetExists) {
$scope.savingFilterPreset = false;
systemAlertService.warning({
text: $filter('i18n')('console.saveFilter.nameConflict'),
hide: 10000
});
return;
}
//disable save button
$scope.saveDisabled = true;
//generate json for backend calls
var filterPreferenceGroup = 'CIFilter', copySelectedFilters = _.cloneDeep($scope.selectedFilters), copySelectedKeywords = _.cloneDeep($scope.searchKeywords), filterSet = {
name: $scope.presetFilterName,
value: _.map(copySelectedFilters.reverse(), function (filterOption) {
var cfg = {
filter: filterOption.filterName || filterOption.criteria.name,
option: filterOption.name
};
if (filterOption.type === 'dynamic') {
cfg.type = 'dynamic';
cfg.realOption = angular.copy(filterOption);
delete cfg.realOption.active;
}
return cfg;
})
}, valueKeywords = _.map(copySelectedKeywords, function (keywordOption) {
return {
filter: 'keywords',
option: keywordOption,
type: 'dynamic',
realOption: {
name: keywordOption,
type: 'dynamic',
criteria: {
name: 'keywords',
value: [
keywordOption
]
}
}
};
});
filterSet.value = _.union(filterSet.value, valueKeywords);
var valueFilterCriteria = {}, valueKeywordCriteria = {
keywords: copySelectedKeywords
};
_.forEach(copySelectedFilters, function (filterOption) {
if (!valueFilterCriteria[filterOption.criteria.name]) {
valueFilterCriteria[filterOption.criteria.name] = [];
}
valueFilterCriteria[filterOption.criteria.name].push(filterOption.criteria.value[0]);
});
var saveTicketfilterConfig = _.extend(valueFilterCriteria, valueKeywordCriteria);
return $q.all([
userModel.updateUserPreferences(filterPreferenceGroup, filterSet), consoleService.saveCIFilterConfiguration($scope.presetFilterName, saveTicketfilterConfig)
]).then(function (userProps) {
$scope.savingFilterPreset = false;
var newPreset = { name: $scope.presetFilterName, userProps: userProps };
$modalInstance.close(newPreset);
if (wizardMode === false) {
var parentElem = angular.element('#link-CI_action-blade-id').parent().parent();
parentElem.removeClass('ci-search-section__relations_action_blade');
}
}).catch(function () {
systemAlertService.warning({
text: $filter('i18n')('error.unknown'),
hide: 10000
});
});
};
$scope.close = function () {
$modalInstance.dismiss();
if (wizardMode === false) {
var parentElem = angular.element('#link-CI_action-blade-id').parent().parent();
parentElem.removeClass('ci-search-section__relations_action_blade');
}
};
}],
resolve: {
filter: function () {
return filter;
}
}
});
modalInstance.result.then(function (response) {
var name = response.name, userProps = response.userProps[0], newUserPropIndex = _.findIndex(userProps, { name: name }), configIndex = _.findIndex(filter.config, { name: 'custom' }), filterConfigIndex = _.findIndex($scope.filterConfig, { name: 'custom' });
_.forEach(filter.config[configIndex].options, function (configOpt) {
if (configOpt.name !== name) {
configOpt.selected = false;
}
});
function NewPreset() {
var allFilters = _.map(filter.selectedFilters);
this.id = userProps[newUserPropIndex].id;
this.name = name;
this.type = 'custom';
this.expanded = true;
this.selected = false;
this.setSelected = function () {
this.selected = true;
};
if (filter.searchKeywords.length) {
var searchKeywordsArr = _.map(filter.searchKeywords.split(','), _.trim);
_.forEach(searchKeywordsArr, function (keyword) {
var filterValue = [], f;
filterValue.push(keyword);
f = {
name: keyword,
active: true,
criteria: { name: 'keywords', value: filterValue },
type: 'keywords'
};
allFilters.push(f);
});
}
this.filters = allFilters;
}
if (configIndex !== -1) {
_.forEach($scope.model.searches, function (searchFilter) {
var searchFilterConfigIndex = _.findIndex(searchFilter.config, { name: 'custom' });
searchFilter.config[searchFilterConfigIndex].options.push(new NewPreset());
});
}
_.forEach(filter.config[configIndex].options, function (configOpt) {
if (configOpt.name === name) {
configOpt.setSelected();
}
});
if (filterConfigIndex !== -1) {
$scope.filterConfig[filterConfigIndex].options.push(new NewPreset());
}
});
};
var cancelRootScopeListener = $rootScope.$on(events.CI_REMOVE_CUSTOM_FILTER, function (e, option) {
_.forEach($scope.model.searches, function (searchFilter) {
var filterConfigIndex = _.findIndex(searchFilter.config, { name: 'custom' });
if (filterConfigIndex !== -1) {
searchFilter.config[filterConfigIndex].options
= _.reject(searchFilter.config[filterConfigIndex].options, { name: option.name });
}
});
});
$scope.onSearchTextChange = function (searchObject) {
if ($scope.searchTextCharLimit > 0 && searchObject.searchKeywords.length > $scope.searchTextCharLimit) {
searchObject.searchKeywords = searchObject.searchKeywords.slice(0, $scope.searchTextCharLimit);
searchObject.isTooltipOpen = true;
}
else {
searchObject.isTooltipOpen = false;
}
};
$scope.$on('$destroy', function () {
cancelRootScopeListener();
});
}]
};
}
]);
})();