my-test123
Version:
A planner front-end for Fabric8.
1,086 lines • 44.9 kB
JavaScript
import { Injectable, Inject } from '@angular/core';
import 'rxjs/add/operator/toPromise';
import 'rxjs/operators/map';
import 'rxjs/add/operator/catch';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { cloneDeep } from 'lodash';
import { Broadcaster, Logger } from 'ngx-base';
import { AuthenticationService, UserService } from 'ngx-login-client';
import { Spaces } from 'ngx-fabric8-wit';
import { WIT_API_URL } from 'ngx-fabric8-wit';
import { Notifications } from 'ngx-base';
import { CommentPost } from '../models/comment';
import { AreaService } from './area.service';
import { IterationService } from './iteration.service';
import { LinkDict, WorkItem } from '../models/work-item';
import { HttpService } from './http-service';
var WorkItemService = /** @class */ (function () {
function WorkItemService(http, broadcaster, logger, areaService, auth, iterationService, userService, notifications, spaces, baseApiUrl) {
var _this = this;
this.http = http;
this.broadcaster = broadcaster;
this.logger = logger;
this.areaService = areaService;
this.auth = auth;
this.iterationService = iterationService;
this.userService = userService;
this.notifications = notifications;
this.spaces = spaces;
this.baseApiUrl = baseApiUrl;
this.workItemUrl = null;
this.workItemTypeUrl = null;
this.linkTypesUrl = null;
this.linksUrl = null;
this.reorderUrl = null;
this.baseSearchUrl = null;
this.renderUrl = null;
this.headers = {};
this.availableStates = [];
this.workItemTypes = [];
this.nextLink = null;
this.initialWorkItemFetchDone = false;
this.userIdMap = {};
this.workItemIdIndexMap = {};
this.prevFilters = [];
this.iterations = [];
this.addWIObservable = new Subject();
this.addWIChildObservable = new Subject();
this.editWIObservable = new Subject();
this.selectedWIObservable = new Subject();
this.showTree = new Subject();
this.spaces.current.subscribe(function (val) { return _this._currentSpace = val; });
this.selfId = this.createId();
this.logger.log('Launching WorkItemService instance id ' + this.selfId);
}
WorkItemService.prototype.notifyError = function (message, httpError) {
this.logger.log('ERROR [WorkItemService] ' + message + (httpError.message ? ' ' + httpError.message : ''));
/*
this.notifications.message({
message: message + (httpError.message?' '+httpError.message:''),
type: NotificationType.DANGER
} as Notification);
*/
};
WorkItemService.prototype.createId = function () {
var id = '';
var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (var i = 0; i < 5; i++)
id += possible.charAt(Math.floor(Math.random() * possible.length));
console.log('Created new id ' + id);
return id;
};
// switchSpace(space: Space) {
// this.logger.log('[WorkItemService] New Space selected: ' + space.name);
// this.workItemUrl = space.spaceBaseUrl + 'workitems';
// this.workItemTypeUrl = space.spaceBaseUrl + 'workitemtypes';
// this.linkTypesUrl = space.spaceBaseUrl + 'workitemlinktypes';
// this.linksUrl = space.spaceBaseUrl + 'workitemlinks';
// this.reorderUrl = space.spaceBaseUrl + 'workitems/reorder';
// this.baseSearchUrl = space.spaceBaseUrl + 'search?q=';
// this.renderUrl = space.spaceBaseUrl + 'render';
// this.logger.log('WorkItemService using url ' + this.workItemUrl);
// }
WorkItemService.prototype.getChildren = function (parent) {
var _this = this;
// TODO: it looks like the children are not retrieved with paging. This may cause problems in the future.
if (parent.relationships.children) {
this.logger.log('Requesting children for work item ' + parent.id);
var url = parent.relationships.children.links.related;
return this.http
.get(url)
.map(function (response) {
var wItems;
wItems = response.json().data;
wItems.forEach(function (item) {
// put the hasChildren on the root level for the tree
if (item.relationships.children.meta)
item.hasChildren = item.relationships.children.meta.hasChildren;
// Resolve the assignee and creator
_this.resolveUsersForWorkItem(item);
_this.resolveIterationForWorkItem(item);
_this.resolveType(item);
_this.resolveAreaForWorkItem(item);
});
return wItems;
}).catch(function (error) {
_this.notifyError('Getting children of work item failed.', error);
return Observable.throw(new Error(error.message));
});
}
else {
this.logger.log('Work item does not have child related link, skipping: ' + parent.id);
return Observable.of([]);
}
};
WorkItemService.prototype.getChildren2 = function (url) {
return this.http
.get(url)
.map(function (response) { return response.json().data; });
};
WorkItemService.prototype.getWorkItems = function (pageSize, filters) {
var _this = this;
if (pageSize === void 0) { pageSize = 20; }
if (filters === void 0) { filters = []; }
if (this._currentSpace) {
this.workItemUrl = this._currentSpace.links.self + '/workitems';
var url_1 = this.workItemUrl + '?page[limit]=' + pageSize;
filters.forEach(function (item) {
url_1 += '&' + item.paramKey + '=' + item.value;
});
return this.http.get(url_1)
.map(function (resp) {
return {
workItems: resp.json().data,
nextLink: resp.json().links.next,
totalCount: resp.json().meta ? resp.json().meta.totalCount : 0,
included: resp.json().included ? resp.json().included : [],
ancestorIDs: resp.json().meta.ancestorIDs ? resp.json().meta.ancestorIDs : [],
};
}).catch(function (error) {
_this.notifyError('Getting work items failed.', error);
return Observable.throw(new Error(error.message));
});
}
else {
return Observable.of({ workItems: [], nextLink: null });
}
};
// TODO Filter temp
WorkItemService.prototype.getWorkItems2 = function (pageSize, filters) {
var _this = this;
if (pageSize === void 0) { pageSize = 20; }
if (this._currentSpace) {
var url = '';
if (process.env.ENV === 'inmemory') {
url = 'http://mock.service/api/spaces/space-id0/workitems?page[limit]=42&filter[space]=space-id0&filter[typegroup.name]=Scenarios';
}
else {
this.workItemUrl = this._currentSpace.links.self.split('spaces')[0] + 'search';
url = this.workItemUrl + '?page[limit]=' + pageSize + '&' + Object.keys(filters).map(function (k) { return 'filter[' + k + ']=' + JSON.stringify(filters[k]); }).join('&');
}
return this.http.get(url)
.map(function (resp) {
return {
workItems: resp.json().data,
nextLink: resp.json().links.next,
totalCount: resp.json().meta ? resp.json().meta.totalCount : 0,
included: resp.json().included ? resp.json().included : [],
ancestorIDs: resp.json().meta.ancestorIDs ? resp.json().meta.ancestorIDs : [],
};
}).catch(function (error) {
_this.notifyError('Getting work items failed.', error);
return Observable.throw(new Error(error.message));
});
}
else {
return Observable.of({ workItems: [], nextLink: null });
}
};
/**
* This function is called from next page onwards in the scroll
* It does pretty much same as the getWorkItems function
*/
WorkItemService.prototype.getMoreWorkItems = function (url) {
var _this = this;
if (url) {
return this.http.get(url)
.map(function (resp) {
return {
workItems: resp.json().data,
nextLink: resp.json().links.next,
included: resp.json().included ? resp.json().included : [],
ancestorIDs: resp.json().meta.ancestorIDs ? resp.json().meta.ancestorIDs : [],
};
}).catch(function (error) {
_this.notifyError('Getting more work items failed.', error);
return Observable.throw(new Error(error.message));
});
}
else {
return Observable.throw('No more item found');
}
};
WorkItemService.prototype.resolveWorkItems = function (workItems, iterations, users, wiTypes, labels, included) {
if (included === void 0) { included = []; }
var resolvedWorkItems = workItems.map(function (item) {
// Resolve assignnees
if (item.relationships.assignees && item.relationships.assignees.data) {
var assignees = item.relationships.assignees.data ? cloneDeep(item.relationships.assignees.data) : [];
item.relationships.assignees.data = assignees.map(function (assignee) {
return users.find(function (user) { return user.id === assignee.id; }) || assignee;
});
}
// Resolve creator
var creator = cloneDeep(item.relationships.creator.data);
item.relationships.creator.data = users.find(function (user) { return user.id === creator.id; }) || creator;
// Resolve iteration
var iteration = cloneDeep(item.relationships.iteration.data);
if (iteration) {
item.relationships.iteration.data = iterations.find(function (it) { return it.id === iteration.id; }) || iteration;
}
// Resolve labels
var WIlabels = item.relationships.labels.data ? cloneDeep(item.relationships.labels.data) : [];
item.relationships.labels.data = WIlabels.map(function (label) {
return labels.find(function (l) { return l.id === label.id; });
});
// Sort labels in alphabetical order
item.relationships.labels.data = item.relationships.labels.data.sort(function (labelA, labelB) {
var labelAName = labelA.attributes.name.toUpperCase();
var labelBName = labelB.attributes.name.toUpperCase();
return labelAName.localeCompare(labelBName);
});
// Resolve work item types
var wiType = cloneDeep(item.relationships.baseType.data);
if (wiType) {
item.relationships.baseType.data = wiTypes.find(function (type) { return type.id === wiType.id; }) || wiType;
}
return item;
});
return resolvedWorkItems;
};
WorkItemService.prototype.getNextLink = function () {
return this.nextLink;
};
WorkItemService.prototype.setNextLink = function (link) {
this.nextLink = link;
};
/*
// converts a any object to a WorkItem (creating the attribute Map)
toWorkItem(input: any): WorkItem {
let newWorkItem = cloneDeep(input) as WorkItem;
newWorkItem.attributes = new Map<string, string | number>();
for (var property in input.attributes) {
if (input.attributes.hasOwnProperty(property)) {
newWorkItem.attributes.set(property, input.attributes[property]);
}
}
return newWorkItem;
}
*/
/**
* Usage: This method gives a single work item by display number.
*
* @param id : string - number
* @param owner : string
* @param space : string
*/
WorkItemService.prototype.getWorkItemByNumber = function (id, owner, space) {
var _this = this;
if (owner === void 0) { owner = ''; }
if (space === void 0) { space = ''; }
if (this._currentSpace) {
if (owner && space) {
return this.http.get(this._currentSpace.links.self.split('/spaces/')[0] +
'/namedspaces' +
'/' + owner +
'/' + space +
'/workitems/' + id)
.map(function (item) { return item.json().data; })
.catch(function (error) {
_this.notifyError('Getting work item data failed.', error);
return Observable.throw(new Error(error.message));
});
}
else {
return this.http.get(this._currentSpace.links.self.split('/spaces/')[0] + '/workitems/' + id)
.map(function (item) { return item.json().data; })
.catch(function (error) {
_this.notifyError('Getting work item data failed.', error);
return Observable.throw(new Error(error.message));
});
}
}
else {
return Observable.of(new WorkItem());
}
};
/**
* Usage: To resolve the users in eact WorkItem
* For now it resolves assignne and creator
*/
WorkItemService.prototype.resolveUsersForWorkItem = function (workItem) {
if (!workItem.hasOwnProperty('relationalData')) {
workItem.relationalData = {};
}
this.resolveAssignee(workItem);
this.resolveCreator(workItem);
};
/**
* Usage: Resolve the list of assignees for a WorkItem
*/
WorkItemService.prototype.resolveAssignee = function (workItem) {
var _this = this;
workItem.relationalData.assignees = [];
if (!workItem.relationships.hasOwnProperty('assignees') || !workItem.relationships.assignees) {
return;
}
if (!workItem.relationships.assignees.hasOwnProperty('data')) {
return;
}
if (!workItem.relationships.assignees.data || !workItem.relationships.assignees.data.length) {
return;
}
workItem.relationships.assignees.data.forEach(function (assignee) {
workItem.relationalData.assignees.push(_this.getUserById(assignee.id));
});
};
WorkItemService.prototype.resolveAssignees = function (assignees) {
var _this = this;
if (Object.keys(assignees).length && assignees.data.length) {
var observableBatch = assignees.data.map(function (assignee) {
return _this.http.get(assignee.links.self)
.map(function (res) { return res.json().data; })
.catch(function (error) {
return Observable.throw(new Error(error.message));
});
});
return Observable.forkJoin(observableBatch);
}
else {
return Observable.of([]);
}
};
WorkItemService.prototype.getUsersByURLs = function (userURLs) {
var _this = this;
var observableBatch = userURLs.map(function (url) {
return _this.http.get(url)
.map(function (res) { return res.json().data; })
.catch(function (error) {
return Observable.throw(new Error(error.message));
});
});
return Observable.forkJoin(observableBatch);
};
WorkItemService.prototype.resolveCreator2 = function (creator) {
var _this = this;
if (Object.keys(creator).length) {
var creatorLink = creator.data.links.self;
return this.http.get(creatorLink)
.map(function (creator) { return creator.json().data; })
.catch(function (error) {
_this.notifyError('Getting work item creator failed.', error);
return Observable.throw(new Error(error.message));
});
}
else {
return Observable.of(creator);
}
};
WorkItemService.prototype.resolveCommentCreator = function (creator) {
var _this = this;
if (Object.keys(creator).length) {
var creatorLink = creator.links.related;
return this.http.get(creatorLink)
.map(function (creator) { return creator.json().data; })
.catch(function (error) {
_this.notifyError('Getting work item creator failed.', error);
return Observable.throw(new Error(error.message));
});
}
else {
return Observable.of(creator);
}
};
/**
* Usage: Resolve the creator for a WorkItem
*/
WorkItemService.prototype.resolveCreator = function (workItem) {
if (!workItem.relationships.hasOwnProperty('creator') || !workItem.relationships.creator) {
workItem.relationalData.creator = null;
return;
}
if (!workItem.relationships.creator.hasOwnProperty('data')) {
workItem.relationalData.creator = null;
return;
}
if (!workItem.relationships.creator.data) {
workItem.relationalData.creator = null;
return;
}
// To handle some old items with no creator
if (workItem.relationships.creator.data.id === 'me') {
workItem.relationalData.creator = null;
return;
}
workItem.relationalData.creator = this.getUserById(workItem.relationships.creator.data.id);
};
/**
* Usage: Resolve the wi type for a WorkItem
*/
WorkItemService.prototype.resolveType = function (workItem) {
this.getWorkItemTypesById(workItem.relationships.baseType.data.id)
.subscribe(function (type) {
workItem.relationships.baseType.data = type;
});
};
/**
* Usage: To resolve the users in eact WorkItem
* For now it resolves assignne and creator
*/
WorkItemService.prototype.resolveIterationForWorkItem = function (workItem) {
if (!workItem.hasOwnProperty('relationalData')) {
workItem.relationalData = {};
}
if (!workItem.relationships.hasOwnProperty('iteration') || !workItem.relationships.iteration) {
workItem.relationalData.iteration = null;
return;
}
if (!workItem.relationships.iteration.hasOwnProperty('data')) {
workItem.relationalData.iteration = null;
return;
}
if (!workItem.relationships.iteration.data) {
workItem.relationalData.iteration = null;
return;
}
this.getIterationById(workItem.relationships.iteration.data.id)
.subscribe(function (iteration) { return workItem.relationalData.iteration = iteration; });
};
/**
* Usage: To resolve the areas in eact WorkItem
* For now it resolves assignne and creator
*/
WorkItemService.prototype.resolveAreaForWorkItem = function (workItem) {
if (!workItem.hasOwnProperty('relationalData')) {
workItem.relationalData = {};
}
if (!workItem.relationships.hasOwnProperty('area') || !workItem.relationships.area) {
workItem.relationalData.area = null;
return;
}
if (!workItem.relationships.area.hasOwnProperty('data')) {
workItem.relationalData.area = null;
return;
}
if (!workItem.relationships.area.data) {
workItem.relationalData.area = null;
return;
}
this.getAreaById(workItem.relationships.area.data.id)
.subscribe(function (area) { return workItem.relationalData.area = area; });
};
/**
* Usage: Build a ID-User map to dynamically access list of users
* This method takes the locally saved list of users from User Service
* Before coming to this method we fetch the list of users using router resolver
* in detail and list component.
*/
WorkItemService.prototype.buildUserIdMap = function () {
var _this = this;
// Fetch the current updated locally saved user list
var users = this.userService.getLocallySavedUsers();
// Check if the map is putdated or not and if yes then rebuild it
if (Object.keys(this.userIdMap).length < users.length) {
this.userIdMap = {};
users.forEach(function (user) {
_this.userIdMap[user.id] = user;
});
}
};
/**
* Usage: Fetch an use by it's ID from the User-ID map
*/
WorkItemService.prototype.getUserById = function (userId) {
if (userId in this.userIdMap) {
return this.userIdMap[userId];
}
else {
return null;
}
};
/**
* Usage: Fetch an area by it's ID from the areas list
*/
WorkItemService.prototype.getAreaById = function (areaId) {
return this.areaService.getAreas().map(function (areas) {
return areas.find(function (item) { return item.id == areaId; });
});
};
/**
* Usage: Fetch an iteration by it's ID from the iterations list
*/
WorkItemService.prototype.getIterationById = function (iterationId) {
return this.iterationService.getIterations().map(function (iterations) {
return iterations.find(function (item) { return item.id == iterationId; });
});
};
/**
* Usage: This method is to resolve the comments for a work item
* This method is only called when a single item is fetched for the
* details page.
*
* @param: WorkItem - wItem
*/
WorkItemService.prototype.resolveComments = function (url) {
return this.http
.get(url)
.map(function (response) {
return { data: response.json().data, meta: response.json().meta, links: response.json().links };
});
};
/**
* Usage: This method is to resolve the linked items for a work item
* This method is only called when a single item is fetched for the
* details page.
*
* @param: WorkItem - wItem
*/
WorkItemService.prototype.resolveLinks = function (url) {
var _this = this;
return this.http
.get(url)
.map(function (response) { return [response.json().data, response.json().included]; })
.catch(function (error) {
_this.notifyError('Getting linked items data failed.', error);
return Observable.throw(new Error(error.message));
});
};
/**
* Usage: This method is to fetch the work item types
* This method will be deprecated and types will come from
* router resolver
* ToDo: Use router resolver to fetch types here
*/
WorkItemService.prototype.getWorkItemTypes = function () {
var _this = this;
if (this._currentSpace) {
this.workItemTypeUrl = this._currentSpace.links.self + '/workitemtypes';
return this.http
.get(this.workItemTypeUrl)
.map(function (response) {
var resultTypes = response.json().data;
// THIS IS A HACK!
for (var i = 0; i < resultTypes.length; i++)
if (resultTypes[i].id === '86af5178-9b41-469b-9096-57e5155c3f31')
resultTypes.splice(i, 1);
_this.workItemTypes = resultTypes;
return _this.workItemTypes;
}).catch(function (error) {
_this.notifyError('Getting work item type information failed.', error);
return Observable.throw(new Error(error.message));
});
}
else {
return Observable.of([]);
}
};
WorkItemService.prototype.getWorkItemTypes2 = function (workItemTypeUrl) {
var _this = this;
return this.http
.get(workItemTypeUrl)
.map(function (response) {
var resultTypes = response.json().data;
// THIS IS A HACK!
for (var i = 0; i < resultTypes.length; i++)
if (resultTypes[i].id === '86af5178-9b41-469b-9096-57e5155c3f31')
resultTypes.splice(i, 1);
_this.workItemTypes = resultTypes;
return _this.workItemTypes;
}).catch(function (error) {
_this.notifyError('Getting work item type information failed.', error);
return Observable.throw(new Error(error.message));
});
};
/**
* Usage: This method is to fetch the work item types by ID
*/
WorkItemService.prototype.getWorkItemTypesById = function (id) {
var _this = this;
if (this._currentSpace && typeof (id) !== 'undefined') {
var workItemType_1 = this.workItemTypes ? this.workItemTypes.find(function (type) { return type.id === id; }) : null;
if (workItemType_1) {
return Observable.of(workItemType_1);
}
else {
var workItemTypeUrl = this._currentSpace.links.self + '/workitemtypes/' + id;
return this.http.get(workItemTypeUrl)
.map(function (response) {
workItemType_1 = response.json().data;
if (_this.workItemTypes) {
var existingType = _this.workItemTypes.find(function (type) { return type.id === workItemType_1.id; });
if (existingType) {
existingType = workItemType_1;
}
else {
_this.workItemTypes.push(workItemType_1);
}
}
return workItemType_1;
}).catch(function (error) {
_this.notifyError('Getting work item type info failed.', error);
return Observable.throw(new Error(error.message));
});
}
}
else {
return Observable.of({});
}
};
/**
* Usage: This method is to fetch the work item states
* This method will be deprecated and states will come from
* router resolver
* ToDo: Use router resolver to fetch states here
*/
WorkItemService.prototype.getStatusOptions = function () {
var _this = this;
if (this.availableStates.length) {
return Observable.of(this.availableStates);
}
else {
return this.getWorkItemTypes()
.map(function (response) {
_this.availableStates = response[0].attributes.fields['system.state'].type.values.map(function (item, index) {
return {
option: item,
};
});
console.log('availableStates = ', _this.availableStates);
return _this.availableStates;
}).catch(function (error) {
_this.notifyError('Getting available status options for work item failed.', error);
return Observable.throw(new Error(error.message));
});
}
};
/**
* Usage: This method deletes an item
* removes the delted item from the big list
* re build the ID-Index map
*
* @param: WorkItem - workItem (Item to be delted)
*/
WorkItemService.prototype.delete = function (workItem) {
var _this = this;
return this.http
.delete(workItem.links.self)
.map(function () {
_this.broadcaster.broadcast('delete_workitem', workItem);
}).catch(function (error) {
_this.notifyError('Deleting work item failed.', error);
return Observable.throw(new Error(error.message));
});
};
/**
* Usage: This method create a new item
* adds the new item to the big list
* resolve the users for the item
* re build the ID-Index map
*
* @param: WorkItem - workItem (Item to be created)
*/
WorkItemService.prototype.create = function (workItem) {
var _this = this;
console.log('work item in create ', workItem);
var payload = JSON.stringify({ data: workItem });
if (this._currentSpace) {
this.workItemUrl = this._currentSpace.links.self + '/workitems';
return this.http
.post(this.workItemUrl, payload)
.map(function (response) {
return response.json().data;
}).catch(function (error) {
_this.notifyError('Creating work item failed.', error);
return Observable.throw(new Error(error.message));
});
}
else {
return Observable.of(new WorkItem());
}
};
/**
* Usage: This method emit a new work item created event
* The list view and board view listens to this event
* and updates the view based on applied filters.
*/
WorkItemService.prototype.emitAddWI = function (workitemDetail) {
this.addWIObservable.next(workitemDetail);
};
WorkItemService.prototype.emitAddWIChild = function (workitemDetail) {
this.addWIChildObservable.next(workitemDetail);
};
/**
* Usage: This method emit a new work item created event
* The list view and board view listens to this event
* and updates the view based on applied filters.
*/
WorkItemService.prototype.emitEditWI = function (workItem) {
this.editWIObservable.next(workItem);
};
/**
* Usage: This method emit a event when WI get seleceted.
*/
WorkItemService.prototype.emitSelectedWI = function (workItem) {
this.selectedWIObservable.next(workItem);
};
/**
* Usage: this method emit a event when showTree is toggled
*/
WorkItemService.prototype.emitShowTree = function (showTree) {
this.showTree.next(showTree);
};
/**
* Usage: This method update an existing item
* updates the item in the big list
* resolve the users for the item
*
* @param: WorkItem - workItem (Item to be created)
*/
WorkItemService.prototype.update = function (workItem) {
var _this = this;
return this.http
.patch(workItem.links.self, JSON.stringify({ data: workItem }))
.map(function (response) {
return response.json().data;
}).catch(function (error) {
_this.notifyError('Updating work item failed.', error);
return Observable.throw(new Error(error.message));
});
};
/**
* Usage: This method create a comment for a workItem
*
* @param: string - id (Work Item ID)
* @param: Comment
*/
WorkItemService.prototype.createComment = function (url, comment) {
var _this = this;
var c = new CommentPost();
c.data = comment;
return this.http
.post(url, c)
.map(function (response) {
return response.json().data;
}).catch(function (error) {
_this.notifyError('Creating comment failed.', error);
return Observable.throw(new Error(error.message));
});
};
WorkItemService.prototype.updateComment = function (comment) {
var _this = this;
var endpoint = comment.links.self;
return this.http
.patch(endpoint, { 'data': comment })
.map(function (response) {
var comment = response.json().data;
var theUser = _this.userService.getSavedLoggedInUser();
comment.relationalData = { 'creator': theUser };
return comment;
}).catch(function (error) {
_this.notifyError('Updating comment failed.', error);
return Observable.throw(new Error(error.message));
});
};
WorkItemService.prototype.deleteComment = function (comment) {
var _this = this;
var endpoint = comment.links.self;
return this.http.delete(endpoint)
.catch(function (error) {
_this.notifyError('Deleting comment failed.', error);
return Observable.throw(new Error(error.message));
});
};
/**
* Usage: This function fetches all the work item link types
* Store it in an instance variable
*
* @return Promise of LinkType[]
*/
WorkItemService.prototype.getAllLinkTypes = function (workItem) {
var _this = this;
var workItemLinkTypesUrl = this._currentSpace.links.self + '/workitemlinktypes';
return this.http.get(workItemLinkTypesUrl)
.catch(function (error) {
_this.notifyError('Getting link meta info failed (forward).', error);
return Observable.throw(new Error(error.message));
});
};
/**
* Usage: This function fetches all the work item link types
* Store it in an instance variable
*
* @return Promise of LinkType[]
*/
WorkItemService.prototype.getLinkTypes = function (workItem) {
var _this = this;
return this.getAllLinkTypes(workItem)
.map(function (item) {
var linkTypes = {};
linkTypes['forwardLinks'] = item.json().data;
linkTypes['backwardLinks'] = item.json().data;
return linkTypes;
})
.map(function (linkTypes) { return _this.formatLinkTypes(linkTypes); })
.catch(function (err) {
console.log(err);
return Observable.of({});
});
};
WorkItemService.prototype.formatLinkTypes = function (linkTypes) {
var opLinkTypes = [];
linkTypes.forwardLinks.forEach(function (linkType) {
opLinkTypes.push({
name: linkType.attributes['forward_name'],
linkId: linkType.id,
linkType: 'forward'
});
});
linkTypes.backwardLinks.forEach(function (linkType) {
opLinkTypes.push({
name: linkType.attributes['reverse_name'],
linkId: linkType.id,
linkType: 'reverse'
});
});
return opLinkTypes;
};
/**
* Usage: This function adds a link to a work item
* Stroes the resolved link in relationalData
* Updates the reference of workItem so doesn't return anything
*
* @param link: Link
* @param includes: any - Data relavent to the link
* @param wItem: WorkItem
*/
WorkItemService.prototype.addLinkToWorkItem = function (link, includes, wItem) {
wItem.relationalData.totalLinkCount += 1;
// Get the link type of this link
var linkType_id = link.relationships.link_type.data.id;
var linkType = includes.find(function (i) { return i.id == linkType_id && i.type == 'workitemlinktypes'; });
// Resolve source
if (link.relationships.source.data.id == wItem.id) {
// Setting target info from the data in included
var targetWItem = includes.find(function (i) { return i.type == 'workitems' && i.id == link.relationships.target.data.id; });
link.relationalData = {
source: {
title: wItem.attributes['system.title'],
id: wItem.id,
number: wItem.attributes['system.number'],
state: wItem.attributes['system.state']
},
target: {
title: targetWItem.attributes['system.title'],
id: targetWItem.id,
number: targetWItem.attributes['system.number'],
state: targetWItem.attributes['system.state']
},
linkType: linkType.attributes.forward_name
};
}
else {
// Setting source info from the data in included
var sourceWItem = includes.find(function (i) { return i.type == 'workitems' && i.id == link.relationships.source.data.id; });
link.relationalData = {
target: {
title: wItem.attributes['system.title'],
id: wItem.id,
number: wItem.attributes['system.number'],
state: wItem.attributes['system.state']
},
source: {
title: sourceWItem.attributes['system.title'],
id: sourceWItem.id,
number: sourceWItem.attributes['system.number'],
state: sourceWItem.attributes['system.state']
},
linkType: linkType.attributes.reverse_name
};
}
var lTypeIndex = wItem.relationalData.linkDicts.findIndex(function (i) { return i.linkName == link.relationalData.linkType; });
if (lTypeIndex > -1) {
// Add this link
wItem.relationalData.linkDicts[lTypeIndex].count += 1;
wItem.relationalData.linkDicts[lTypeIndex].links.splice(wItem.relationalData.linkDicts[lTypeIndex].links.length, 0, link);
}
else {
// Create a new LinkDict item
var newLinkDict = new LinkDict();
newLinkDict.linkName = link.relationalData.linkType;
newLinkDict.count = 1;
newLinkDict.links = [link];
wItem.relationalData.linkDicts.splice(0, 0, newLinkDict);
}
};
/**
* Usage: This function removes a link from a work item
* Removes the link from relationalData
* Updates the reference of workItem so doesn't return anything
*
* @param link: Link
* @param wItem: WorkItem
*/
WorkItemService.prototype.removeLinkFromWorkItem = function (deletedLink, wItem) {
wItem.relationalData.totalLinkCount -= 1;
wItem.relationalData.linkDicts.every(function (item, index) {
var linkIndex = item.links.findIndex(function (link) { return link.id == deletedLink.id; });
if (linkIndex > -1) {
item.links.splice(linkIndex, 1);
if (!item.links.length) {
wItem.relationalData.linkDicts.splice(index, 1);
}
return false;
}
return true;
});
};
/**
* Usage: Makes an API call to create a link
* Recieves the new link response
* Resolves and add the new link to the workItem
*
* @param link: Link - The new link object for request params
* @returns Promise<Link>
*/
WorkItemService.prototype.createLink = function (link) {
if (this._currentSpace) {
// FIXME: make the URL great again (when we know the right API URL for this)!
this.linksUrl = this.baseApiUrl + 'workitemlinks';
// this.linksUrl = currentSpace.links.self + '/workitemlinks';
return this.http
.post(this.linksUrl, JSON.stringify(link))
.map(function (response) { return [response.json().data, response.json().included]; });
// .catch ((e) => {
// if (e.status === 401) {
// this.auth.logout();
// } else {
// this.handleError(e);
// }
// });
}
else {
return Observable.of({});
}
};
/**
* Usage: Makes an API call to delete a link
* Removes the new link to the workItem
*
* @param link: Link
* @param currentWiId: string - The work item ID where the link is created
* @returns Promise<void>
*/
WorkItemService.prototype.deleteLink = function (link, currentWiId) {
if (this._currentSpace) {
// FIXME: make the URL great again (when we know the right API URL for this)!
this.linksUrl = this.baseApiUrl + 'workitemlinks';
// this.linksUrl = currentSpace.links.self + '/workitemlinks';
var url = this.linksUrl + "/" + link.id;
return this.http
.delete(url)
.map(function (response) { });
// .catch ((e) => {
// if (e.status === 401) {
// this.auth.logout();
// } else {
// this.handleError(e);
// }
// });
}
};
WorkItemService.prototype.searchLinkWorkItem = function (term) {
if (this._currentSpace) {
// FIXME: make the URL great again (when we know the right API URL for this)!
// search within selected space
var searchUrl = this.baseApiUrl + 'search?spaceID=' + this._currentSpace.id + '&q=' + term;
//let searchUrl = currentSpace.links.self + 'search?q=' + term;
return this.http
.get(searchUrl)
.map(function (response) { return response.json().data; });
// .catch ((e) => {
// if (e.status === 401) {
// this.auth.logout();
// } else {
// this.handleError(e);
// }
// });
}
else {
return Observable.of([]);
}
};
/**
* Usage: Make a API call to save
* the order of work item.
*
* @param workItemId: string
*/
WorkItemService.prototype.reOrderWorkItem = function (workItem, prevWiId, direction) {
if (prevWiId === void 0) { prevWiId = null; }
var newWItem = new WorkItem();
var arr = [];
newWItem.id = workItem.id.toString();
newWItem.attributes = new Map();
newWItem.attributes['version'] = workItem.attributes['version'];
newWItem.type = workItem.type;
arr.push(newWItem);
if (this._currentSpace) {
var url = this._currentSpace.links.self + "/workitems/reorder";
return this.http
.patch(url, JSON.stringify({ data: arr, position: { direction: direction, id: prevWiId } }))
.map(function (response) {
var updatedWorkItem = response.json().data[0];
return updatedWorkItem;
});
// .catch ((e) => {
// if (e.status === 401) {
// this.auth.logout();
// } else {
// this.handleError(e);
// }
// });
}
else {
Observable.throw('No space selected');
}
};
WorkItemService.prototype.renderMarkDown = function (markDownText) {
var params = {
data: {
attributes: {
content: markDownText,
markup: 'Markdown'
},
type: 'rendering'
}
};
if (this._currentSpace) {
// FIXME: make the URL great again (when we know the right API URL for this)!
this.renderUrl = this.baseApiUrl + 'render';
// this.renderUrl = currentSpace.links.self + '/render';
return this.http
.post(this.renderUrl, JSON.stringify(params))
.map(function (response) { return response.json().data.attributes.renderedContent; });
// .catch ((e) => {
// if (e.status === 401) {
// this.auth.logout();
// } else {
// this.handleError(e);
// }
// });
}
else {
return Observable.of({});
}
};
WorkItemService.decorators = [
{ type: Injectable },
];
/** @nocollapse */
WorkItemService.ctorParameters = function () { return [
{ type: HttpService, },
{ type: Broadcaster, },
{ type: Logger, },
{ type: AreaService, },
{ type: AuthenticationService, },
{ type: IterationService, },
{ type: UserService, },
{ type: Notifications, },
{ type: Spaces, },
{ type: undefined, decorators: [{ type: Inject, args: [WIT_API_URL,] },] },
]; };
return WorkItemService;
}());
export { WorkItemService };
//# sourceMappingURL=work-item.service.js.map