blob: 8f670c924bc6623ed8a32a686c0cbeeeddbb6fdf [file] [log] [blame]
Copybara854996b2021-09-07 19:36:02 +00001// Copyright 2019 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5/**
6 * @fileoverview Issue actions, selectors, and reducers organized into
7 * a single Redux "Duck" that manages updating and retrieving issue state
8 * on the frontend.
9 *
10 * Reference: https://github.com/erikras/ducks-modular-redux
11 */
12
13import {combineReducers} from 'redux';
14import {createSelector} from 'reselect';
15import {autolink} from 'autolink.js';
16import {fieldTypes, extractTypeForIssue,
Adrià Vilanova Martínez9f9ade52022-10-10 23:20:11 +020017 fieldValuesToMap, migratedTypes} from 'shared/issue-fields.js';
Copybara854996b2021-09-07 19:36:02 +000018import {removePrefix, objectToMap} from 'shared/helpers.js';
19import {issueRefToString, issueToIssueRefString,
20 issueStringToRef, issueNameToRefString} from 'shared/convertersV0.js';
21import {fromShortlink} from 'shared/federated.js';
22import {createReducer, createRequestReducer,
23 createKeyedRequestReducer} from './redux-helpers.js';
24import * as projectV0 from './projectV0.js';
25import * as userV0 from './userV0.js';
26import {fieldValueMapKey} from 'shared/metadata-helpers.js';
27import {prpcClient} from 'prpc-client-instance.js';
28import loadGapi, {fetchGapiEmail} from 'shared/gapi-loader.js';
29import 'shared/typedef.js';
30
31/** @typedef {import('redux').AnyAction} AnyAction */
32
33// Actions
34export const VIEW_ISSUE = 'VIEW_ISSUE';
35
36export const FETCH_START = 'issueV0/FETCH_START';
37export const FETCH_SUCCESS = 'issueV0/FETCH_SUCCESS';
38export const FETCH_FAILURE = 'issueV0/FETCH_FAILURE';
39
40export const FETCH_ISSUES_START = 'issueV0/FETCH_ISSUES_START';
41export const FETCH_ISSUES_SUCCESS = 'issueV0/FETCH_ISSUES_SUCCESS';
42export const FETCH_ISSUES_FAILURE = 'issueV0/FETCH_ISSUES_FAILURE';
43
44const FETCH_HOTLISTS_START = 'FETCH_HOTLISTS_START';
45export const FETCH_HOTLISTS_SUCCESS = 'FETCH_HOTLISTS_SUCCESS';
46const FETCH_HOTLISTS_FAILURE = 'FETCH_HOTLISTS_FAILURE';
47
48const FETCH_ISSUE_LIST_START = 'FETCH_ISSUE_LIST_START';
49export const FETCH_ISSUE_LIST_UPDATE = 'FETCH_ISSUE_LIST_UPDATE';
50const FETCH_ISSUE_LIST_SUCCESS = 'FETCH_ISSUE_LIST_SUCCESS';
51const FETCH_ISSUE_LIST_FAILURE = 'FETCH_ISSUE_LIST_FAILURE';
52
53const FETCH_PERMISSIONS_START = 'FETCH_PERMISSIONS_START';
54const FETCH_PERMISSIONS_SUCCESS = 'FETCH_PERMISSIONS_SUCCESS';
55const FETCH_PERMISSIONS_FAILURE = 'FETCH_PERMISSIONS_FAILURE';
56
57export const STAR_START = 'STAR_START';
58export const STAR_SUCCESS = 'STAR_SUCCESS';
59const STAR_FAILURE = 'STAR_FAILURE';
60
61const PRESUBMIT_START = 'PRESUBMIT_START';
62const PRESUBMIT_SUCCESS = 'PRESUBMIT_SUCCESS';
63const PRESUBMIT_FAILURE = 'PRESUBMIT_FAILURE';
64
65export const FETCH_IS_STARRED_START = 'FETCH_IS_STARRED_START';
66export const FETCH_IS_STARRED_SUCCESS = 'FETCH_IS_STARRED_SUCCESS';
67const FETCH_IS_STARRED_FAILURE = 'FETCH_IS_STARRED_FAILURE';
68
69const FETCH_ISSUES_STARRED_START = 'FETCH_ISSUES_STARRED_START';
70export const FETCH_ISSUES_STARRED_SUCCESS = 'FETCH_ISSUES_STARRED_SUCCESS';
71const FETCH_ISSUES_STARRED_FAILURE = 'FETCH_ISSUES_STARRED_FAILURE';
72
73const FETCH_COMMENTS_START = 'FETCH_COMMENTS_START';
74export const FETCH_COMMENTS_SUCCESS = 'FETCH_COMMENTS_SUCCESS';
75const FETCH_COMMENTS_FAILURE = 'FETCH_COMMENTS_FAILURE';
76
77const FETCH_COMMENT_REFERENCES_START = 'FETCH_COMMENT_REFERENCES_START';
78const FETCH_COMMENT_REFERENCES_SUCCESS = 'FETCH_COMMENT_REFERENCES_SUCCESS';
79const FETCH_COMMENT_REFERENCES_FAILURE = 'FETCH_COMMENT_REFERENCES_FAILURE';
80
81const FETCH_REFERENCED_USERS_START = 'FETCH_REFERENCED_USERS_START';
82const FETCH_REFERENCED_USERS_SUCCESS = 'FETCH_REFERENCED_USERS_SUCCESS';
83const FETCH_REFERENCED_USERS_FAILURE = 'FETCH_REFERENCED_USERS_FAILURE';
84
85const FETCH_RELATED_ISSUES_START = 'FETCH_RELATED_ISSUES_START';
86const FETCH_RELATED_ISSUES_SUCCESS = 'FETCH_RELATED_ISSUES_SUCCESS';
87const FETCH_RELATED_ISSUES_FAILURE = 'FETCH_RELATED_ISSUES_FAILURE';
88
89const FETCH_FEDERATED_REFERENCES_START = 'FETCH_FEDERATED_REFERENCES_START';
90const FETCH_FEDERATED_REFERENCES_SUCCESS = 'FETCH_FEDERATED_REFERENCES_SUCCESS';
91const FETCH_FEDERATED_REFERENCES_FAILURE = 'FETCH_FEDERATED_REFERENCES_FAILURE';
92
93const CONVERT_START = 'CONVERT_START';
94const CONVERT_SUCCESS = 'CONVERT_SUCCESS';
95const CONVERT_FAILURE = 'CONVERT_FAILURE';
96
97const UPDATE_START = 'UPDATE_START';
98const UPDATE_SUCCESS = 'UPDATE_SUCCESS';
99const UPDATE_FAILURE = 'UPDATE_FAILURE';
100
101const UPDATE_APPROVAL_START = 'UPDATE_APPROVAL_START';
102const UPDATE_APPROVAL_SUCCESS = 'UPDATE_APPROVAL_SUCCESS';
103const UPDATE_APPROVAL_FAILURE = 'UPDATE_APPROVAL_FAILURE';
104
105/* State Shape
106{
107 issuesByRefString: Object<IssueRefString, Issue>,
108
109 viewedIssueRef: IssueRefString,
110
111 hotlists: Array<HotlistV0>,
112 issueList: {
113 issueRefs: Array<IssueRefString>,
114 progress: number,
115 totalResults: number,
116 }
117 comments: Array<IssueComment>,
118 commentReferences: Object,
119 relatedIssues: Object,
120 referencedUsers: Array<UserV0>,
121 starredIssues: Object<IssueRefString, Boolean>,
122 permissions: Array<string>,
123 presubmitResponse: Object,
124
125 requests: {
126 fetch: ReduxRequestState,
127 fetchHotlists: ReduxRequestState,
128 fetchIssueList: ReduxRequestState,
129 fetchPermissions: ReduxRequestState,
130 starringIssues: Object<string, ReduxRequestState>,
131 presubmit: ReduxRequestState,
132 fetchComments: ReduxRequestState,
133 fetchCommentReferences: ReduxRequestState,
134 fetchFederatedReferences: ReduxRequestState,
135 fetchRelatedIssues: ReduxRequestState,
136 fetchStarredIssues: ReduxRequestState,
137 fetchStarredIssues: ReduxRequestState,
138 convert: ReduxRequestState,
139 update: ReduxRequestState,
140 updateApproval: ReduxRequestState,
141 },
142}
143*/
144
145// Helpers for the reducers.
146
147/**
148 * Overrides local data for single approval on an Issue object with fresh data.
149 * Note that while an Issue can have multiple approvals, this function only
150 * refreshes data for a single approval.
151 * @param {Issue} issue Issue Object being updated.
152 * @param {ApprovalDef} approval A single approval to override in the issue.
153 * @return {Issue} Issue with updated approval data.
154 */
155const updateApprovalValues = (issue, approval) => {
156 if (!issue.approvalValues) return issue;
157 const newApprovals = issue.approvalValues.map((item) => {
158 if (item.fieldRef.fieldName === approval.fieldRef.fieldName) {
159 // PhaseRef isn't populated on the response so we want to make sure
160 // it doesn't overwrite the original phaseRef with {}.
161 return {...approval, phaseRef: item.phaseRef};
162 }
163 return item;
164 });
165 return {...issue, approvalValues: newApprovals};
166};
167
168// Reducers
169
170/**
171 * Creates a new issuesByRefString Object with a single issue's data
172 * edited.
173 * @param {Object<IssueRefString, Issue>} issuesByRefString
174 * @param {Issue} issue The new issue data to add to the state.
175 * @return {Object<IssueRefString, Issue>}
176 */
177const updateSingleIssueInState = (issuesByRefString, issue) => {
178 return {
179 ...issuesByRefString,
180 [issueToIssueRefString(issue)]: issue,
181 };
182};
183
184// TODO(crbug.com/monorail/6882): Finish converting all other issue
185// actions to use this format.
186/**
187 * Adds issues fetched by a ListIssues request to the Redux store in a
188 * normalized format.
189 * @param {Object<IssueRefString, Issue>} state Redux state.
190 * @param {AnyAction} action
191 * @param {Array<Issue>} action.issues The list of issues that was fetched.
192 * @param {Issue=} action.issue The issue being updated.
193 * @param {number=} action.starCount Number of stars the issue has. This changes
194 * when a user stars an issue and needs to be updated.
195 * @param {ApprovalDef=} action.approval A new approval to update the issue
196 * with.
197 * @param {IssueRef=} action.issueRef A specific IssueRef to update.
198 */
199export const issuesByRefStringReducer = createReducer({}, {
200 [FETCH_ISSUE_LIST_UPDATE]: (state, {issues}) => {
201 const newState = {...state};
202
203 issues.forEach((issue) => {
204 const refString = issueToIssueRefString(issue);
205 newState[refString] = {...newState[refString], ...issue};
206 });
207
208 return newState;
209 },
210 [FETCH_SUCCESS]: (state, {issue}) => updateSingleIssueInState(state, issue),
211 [FETCH_ISSUES_SUCCESS]: (state, {issues}) => {
212 const newState = {...state};
213
214 issues.forEach((issue) => {
215 const refString = issueToIssueRefString(issue);
216 newState[refString] = {...newState[refString], ...issue};
217 });
218
219 return newState;
220 },
221 [CONVERT_SUCCESS]: (state, {issue}) => updateSingleIssueInState(state, issue),
222 [UPDATE_SUCCESS]: (state, {issue}) => updateSingleIssueInState(state, issue),
223 [UPDATE_APPROVAL_SUCCESS]: (state, {issueRef, approval}) => {
224 const issueRefString = issueToIssueRefString(issueRef);
225 const originalIssue = state[issueRefString] || {};
226 const newIssue = updateApprovalValues(originalIssue, approval);
227 return {
228 ...state,
229 [issueRefString]: {
230 ...newIssue,
231 },
232 };
233 },
234 [STAR_SUCCESS]: (state, {issueRef, starCount}) => {
235 const issueRefString = issueToIssueRefString(issueRef);
236 const originalIssue = state[issueRefString] || {};
237 return {
238 ...state,
239 [issueRefString]: {
240 ...originalIssue,
241 starCount,
242 },
243 };
244 },
245});
246
247/**
248 * Sets a reference for the issue that the user is currently viewing.
249 * @param {IssueRefString} state Currently viewed issue.
250 * @param {AnyAction} action
251 * @param {IssueRef} action.issueRef The updated localId to view.
252 * @return {IssueRefString}
253 */
254const viewedIssueRefReducer = createReducer('', {
255 [VIEW_ISSUE]: (state, {issueRef}) => issueRefToString(issueRef) || state,
256});
257
258/**
259 * Reducer to manage updating the list of hotlists attached to an Issue.
260 * @param {Array<HotlistV0>} state List of issue hotlists.
261 * @param {AnyAction} action
262 * @param {Array<HotlistV0>} action.hotlists New list of hotlists.
263 * @return {Array<HotlistV0>}
264 */
265const hotlistsReducer = createReducer([], {
266 [FETCH_HOTLISTS_SUCCESS]: (_, {hotlists}) => hotlists,
267});
268
269/**
270 * @typedef {Object} IssueListState
271 * @property {Array<IssueRefString>} issues The list of issues being viewed,
272 * in a normalized form.
273 * @property {number} progress The percentage of issues loaded. Used for
274 * incremental loading of issues in the grid view.
275 * @property {number} totalResults The total number of issues matching the
276 * query.
277 */
278
279/**
280 * Handles the state of the currently viewed issue list. This reducer
281 * stores this data in normalized form.
282 * @param {IssueListState} state
283 * @param {AnyAction} action
284 * @param {Array<Issue>} action.issues Issues that were fetched.
285 * @param {number} state.progress New percentage of issues have been loaded.
286 * @param {number} state.totalResults The total number of issues matching the
287 * query.
288 * @return {IssueListState}
289 */
290export const issueListReducer = createReducer({}, {
291 [FETCH_ISSUE_LIST_UPDATE]: (_state, {issues, progress, totalResults}) => ({
292 issueRefs: issues.map(issueToIssueRefString), progress, totalResults,
293 }),
294});
295
296/**
297 * Updates the comments attached to the currently viewed issue.
298 * @param {Array<IssueComment>} state The list of comments in an issue.
299 * @param {AnyAction} action
300 * @param {Array<IssueComment>} action.comments Fetched comments.
301 * @return {Array<IssueComment>}
302 */
303const commentsReducer = createReducer([], {
304 [FETCH_COMMENTS_SUCCESS]: (_state, {comments}) => comments,
305});
306
307// TODO(crbug.com/monorail/5953): Come up with some way to refactor
308// autolink.js's reference code to allow avoiding duplicate lookups
309// with data already in Redux state.
310/**
311 * For autolinking, this reducer stores the dereferenced data for bits
312 * of data that were referenced in comments. For example, comments might
313 * include user emails or IDs for other issues, and this state slice would
314 * store the full Objects for that data.
315 * @param {Array<CommentReference>} state
316 * @param {AnyAction} action
317 * @param {Array<CommentReference>} action.commentReferences New references
318 * to store.
319 * @return {Array<CommentReference>}
320 */
321const commentReferencesReducer = createReducer({}, {
322 [FETCH_COMMENTS_START]: (_state, _action) => ({}),
323 [FETCH_COMMENT_REFERENCES_SUCCESS]: (_state, {commentReferences}) => {
324 return commentReferences;
325 },
326});
327
328/**
329 * Handles state for related issues such as blocking and blocked on issues,
330 * including federated references that could reference external issues outside
331 * Monorail.
332 * @param {Object<IssueRefString, Issue>} state
333 * @param {AnyAction} action
334 * @param {Object<IssueRefString, Issue>=} action.relatedIssues New related
335 * issues.
336 * @param {Array<IssueRef>=} action.fedRefIssueRefs List of fetched federated
337 * issue references.
338 * @return {Object<IssueRefString, Issue>}
339 */
340export const relatedIssuesReducer = createReducer({}, {
341 [FETCH_RELATED_ISSUES_SUCCESS]: (_state, {relatedIssues}) => relatedIssues,
342 [FETCH_FEDERATED_REFERENCES_SUCCESS]: (state, {fedRefIssueRefs}) => {
343 if (!fedRefIssueRefs) {
344 return state;
345 }
346
347 const fedRefStates = {};
348 fedRefIssueRefs.forEach((ref) => {
349 fedRefStates[ref.extIdentifier] = ref;
350 });
351
352 // Return a new object, in Redux fashion.
353 return Object.assign(fedRefStates, state);
354 },
355});
356
357/**
358 * Stores data for users referenced by issue. ie: Owner, CC, etc.
359 * @param {Object<string, UserV0>} state
360 * @param {AnyAction} action
361 * @param {Object<string, UserV0>} action.referencedUsers
362 * @return {Object<string, UserV0>}
363 */
364const referencedUsersReducer = createReducer({}, {
365 [FETCH_REFERENCED_USERS_SUCCESS]: (_state, {referencedUsers}) =>
366 referencedUsers,
367});
368
369/**
370 * Handles updating state of all starred issues.
371 * @param {Object<IssueRefString, boolean>} state Set of starred issues,
372 * stored in a serializeable Object form.
373 * @param {AnyAction} action
374 * @param {IssueRef=} action.issueRef An issue with a star state being updated.
375 * @param {boolean=} action.starred Whether the issue is starred or unstarred.
376 * @param {Array<IssueRef>=} action.starredIssueRefs A list of starred issues.
377 * @return {Object<IssueRefString, boolean>}
378 */
379export const starredIssuesReducer = createReducer({}, {
380 [STAR_SUCCESS]: (state, {issueRef, starred}) => {
381 return {...state, [issueRefToString(issueRef)]: starred};
382 },
383 [FETCH_ISSUES_STARRED_SUCCESS]: (_state, {starredIssueRefs}) => {
384 const normalizedStars = {};
385 starredIssueRefs.forEach((issueRef) => {
386 normalizedStars[issueRefToString(issueRef)] = true;
387 });
388 return normalizedStars;
389 },
390 [FETCH_IS_STARRED_SUCCESS]: (state, {issueRef, starred}) => {
391 const refString = issueRefToString(issueRef);
392 return {...state, [refString]: starred};
393 },
394});
395
396/**
397 * Adds the result of an IssuePresubmit response to the Redux store.
398 * @param {Object} state Initial Redux state.
399 * @param {AnyAction} action
400 * @param {Object} action.presubmitResponse The issue
401 * presubmit response Object.
402 * @return {Object}
403 */
404const presubmitResponseReducer = createReducer({}, {
405 [PRESUBMIT_SUCCESS]: (_state, {presubmitResponse}) => presubmitResponse,
406});
407
408/**
409 * Stores the user's permissions for a given issue.
410 * @param {Array<string>} state Permission list. Each permission is a string
411 * with the name of the permission.
412 * @param {AnyAction} action
413 * @param {Array<string>} action.permissions The fetched permission data.
414 * @return {Array<string>}
415 */
416const permissionsReducer = createReducer([], {
417 [FETCH_PERMISSIONS_SUCCESS]: (_state, {permissions}) => permissions,
418});
419
420const requestsReducer = combineReducers({
421 fetch: createRequestReducer(
422 FETCH_START, FETCH_SUCCESS, FETCH_FAILURE),
423 fetchIssues: createRequestReducer(
424 FETCH_ISSUES_START, FETCH_ISSUES_SUCCESS, FETCH_ISSUES_FAILURE),
425 fetchHotlists: createRequestReducer(
426 FETCH_HOTLISTS_START, FETCH_HOTLISTS_SUCCESS, FETCH_HOTLISTS_FAILURE),
427 fetchIssueList: createRequestReducer(
428 FETCH_ISSUE_LIST_START,
429 FETCH_ISSUE_LIST_SUCCESS,
430 FETCH_ISSUE_LIST_FAILURE),
431 fetchPermissions: createRequestReducer(
432 FETCH_PERMISSIONS_START,
433 FETCH_PERMISSIONS_SUCCESS,
434 FETCH_PERMISSIONS_FAILURE),
435 starringIssues: createKeyedRequestReducer(
436 STAR_START, STAR_SUCCESS, STAR_FAILURE),
437 presubmit: createRequestReducer(
438 PRESUBMIT_START, PRESUBMIT_SUCCESS, PRESUBMIT_FAILURE),
439 fetchComments: createRequestReducer(
440 FETCH_COMMENTS_START, FETCH_COMMENTS_SUCCESS, FETCH_COMMENTS_FAILURE),
441 fetchCommentReferences: createRequestReducer(
442 FETCH_COMMENT_REFERENCES_START,
443 FETCH_COMMENT_REFERENCES_SUCCESS,
444 FETCH_COMMENT_REFERENCES_FAILURE),
445 fetchFederatedReferences: createRequestReducer(
446 FETCH_FEDERATED_REFERENCES_START,
447 FETCH_FEDERATED_REFERENCES_SUCCESS,
448 FETCH_FEDERATED_REFERENCES_FAILURE),
449 fetchRelatedIssues: createRequestReducer(
450 FETCH_RELATED_ISSUES_START,
451 FETCH_RELATED_ISSUES_SUCCESS,
452 FETCH_RELATED_ISSUES_FAILURE),
453 fetchReferencedUsers: createRequestReducer(
454 FETCH_REFERENCED_USERS_START,
455 FETCH_REFERENCED_USERS_SUCCESS,
456 FETCH_REFERENCED_USERS_FAILURE),
457 fetchIsStarred: createRequestReducer(
458 FETCH_IS_STARRED_START, FETCH_IS_STARRED_SUCCESS,
459 FETCH_IS_STARRED_FAILURE),
460 fetchStarredIssues: createRequestReducer(
461 FETCH_ISSUES_STARRED_START, FETCH_ISSUES_STARRED_SUCCESS,
462 FETCH_ISSUES_STARRED_FAILURE,
463 ),
464 convert: createRequestReducer(
465 CONVERT_START, CONVERT_SUCCESS, CONVERT_FAILURE),
466 update: createRequestReducer(
467 UPDATE_START, UPDATE_SUCCESS, UPDATE_FAILURE),
468 // TODO(zhangtiff): Update this to use createKeyedRequestReducer() instead, so
469 // users can update multiple approvals at once.
470 updateApproval: createRequestReducer(
471 UPDATE_APPROVAL_START, UPDATE_APPROVAL_SUCCESS, UPDATE_APPROVAL_FAILURE),
472});
473
474export const reducer = combineReducers({
475 viewedIssueRef: viewedIssueRefReducer,
476
477 issuesByRefString: issuesByRefStringReducer,
478
479 hotlists: hotlistsReducer,
480 issueList: issueListReducer,
481 comments: commentsReducer,
482 commentReferences: commentReferencesReducer,
483 relatedIssues: relatedIssuesReducer,
484 referencedUsers: referencedUsersReducer,
485 starredIssues: starredIssuesReducer,
486 permissions: permissionsReducer,
487 presubmitResponse: presubmitResponseReducer,
488
489 requests: requestsReducer,
490});
491
492// Selectors
493const RESTRICT_VIEW_PREFIX = 'restrict-view-';
494const RESTRICT_EDIT_PREFIX = 'restrict-editissue-';
495const RESTRICT_COMMENT_PREFIX = 'restrict-addissuecomment-';
Adrià Vilanova Martínez9f9ade52022-10-10 23:20:11 +0200496const MIGRATED_ISSUE_PREFIX = 'migrated-to-';
497const MIGRATED_BUGANIZER_ISSUE_PREFIX = 'migrated-to-b-';
498const MIGRATED_LAUNCH_ISSUE_PREFIX = 'migrated-to-launch-';
Copybara854996b2021-09-07 19:36:02 +0000499
500/**
501 * Selector to retrieve all normalized Issue data in the Redux store,
502 * keyed by IssueRefString.
503 * @param {any} state
504 * @return {Object<IssueRefString, Issue>}
505 */
506const issuesByRefString = (state) => state.issue.issuesByRefString;
507
508/**
509 * Selector to return a function to retrieve an Issue from the Redux store.
510 * @param {any} state
511 * @return {function(string): ?Issue}
512 */
513export const issue = createSelector(issuesByRefString, (issuesByRefString) =>
514 (name) => issuesByRefString[issueNameToRefString(name)]);
515
516/**
517 * Selector to return a function to retrieve a given Issue Object from
518 * the Redux store.
519 * @param {any} state
520 * @return {function(IssueRefString, string): Issue}
521 */
522export const issueForRefString = createSelector(issuesByRefString,
523 (issuesByRefString) => (issueRefString, projectName = undefined) => {
524 // In some contexts, an issue ref string will omit a project name,
525 // assuming the default project to be the project name. We never
526 // omit the project name in strings used as keys, so we have to
527 // make sure issue ref strings contain the project name.
528 const ref = issueStringToRef(issueRefString, projectName);
529 const refString = issueRefToString(ref);
530 if (issuesByRefString.hasOwnProperty(refString)) {
531 return issuesByRefString[refString];
532 }
533 return issueStringToRef(refString, projectName);
534 });
535
536/**
537 * Selector to get a reference to the currently viewed issue, in string form.
538 * @param {any} state
539 * @return {IssueRefString}
540 */
541const viewedIssueRefString = (state) => state.issue.viewedIssueRef;
542
543/**
544 * Selector to get a reference to the currently viewed issue.
545 * @param {any} state
546 * @return {IssueRef}
547 */
548export const viewedIssueRef = createSelector(viewedIssueRefString,
549 (viewedIssueRefString) => issueStringToRef(viewedIssueRefString));
550
551/**
552 * Selector to get the full Issue data for the currently viewed issue.
553 * @param {any} state
554 * @return {Issue}
555 */
556export const viewedIssue = createSelector(issuesByRefString,
557 viewedIssueRefString,
558 (issuesByRefString, viewedIssueRefString) =>
559 issuesByRefString[viewedIssueRefString] || {});
560
561export const comments = (state) => state.issue.comments;
562export const commentsLoaded = (state) => state.issue.commentsLoaded;
563
564const _commentReferences = (state) => state.issue.commentReferences;
565export const commentReferences = createSelector(_commentReferences,
566 (commentReferences) => objectToMap(commentReferences));
567
568export const hotlists = (state) => state.issue.hotlists;
569
570const stateIssueList = (state) => state.issue.issueList;
571export const issueList = createSelector(
572 issuesByRefString,
573 stateIssueList,
574 (issuesByRefString, stateIssueList) => {
575 return (stateIssueList.issueRefs || []).map((issueRef) => {
576 return issuesByRefString[issueRef];
577 });
578 },
579);
580export const totalIssues = (state) => state.issue.issueList.totalResults;
581export const issueListProgress = (state) => state.issue.issueList.progress;
582export const issueListPhaseNames = createSelector(issueList, (issueList) => {
583 const phaseNamesSet = new Set();
584 if (issueList) {
585 issueList.forEach(({phases}) => {
586 if (phases) {
587 phases.forEach(({phaseRef: {phaseName}}) => {
588 phaseNamesSet.add(phaseName.toLowerCase());
589 });
590 }
591 });
592 }
593 return Array.from(phaseNamesSet);
594});
595
596/**
597 * @param {any} state
598 * @return {boolean} Whether the currently viewed issue list
599 * has loaded.
600 */
601export const issueListLoaded = createSelector(
602 stateIssueList,
603 (stateIssueList) => stateIssueList.issueRefs !== undefined);
604
605export const permissions = (state) => state.issue.permissions;
606export const presubmitResponse = (state) => state.issue.presubmitResponse;
607
608const _relatedIssues = (state) => state.issue.relatedIssues || {};
609export const relatedIssues = createSelector(_relatedIssues,
610 (relatedIssues) => objectToMap(relatedIssues));
611
612const _referencedUsers = (state) => state.issue.referencedUsers || {};
613export const referencedUsers = createSelector(_referencedUsers,
614 (referencedUsers) => objectToMap(referencedUsers));
615
616export const isStarred = (state) => state.issue.isStarred;
617export const _starredIssues = (state) => state.issue.starredIssues;
618
619export const requests = (state) => state.issue.requests;
620
621// Returns a Map of in flight StarIssues requests, keyed by issueRef.
622export const starringIssues = createSelector(requests, (requests) =>
623 objectToMap(requests.starringIssues));
624
625export const starredIssues = createSelector(
626 _starredIssues,
627 (starredIssues) => {
628 const stars = new Set();
629 for (const [ref, starred] of Object.entries(starredIssues)) {
630 if (starred) stars.add(ref);
631 }
632 return stars;
633 },
634);
635
636// TODO(zhangtiff): Split up either comments or approvals into their own "duck".
637export const commentsByApprovalName = createSelector(
638 comments,
639 (comments) => {
640 const map = new Map();
641 comments.forEach((comment) => {
642 const key = (comment.approvalRef && comment.approvalRef.fieldName) ||
643 '';
644 if (map.has(key)) {
645 map.get(key).push(comment);
646 } else {
647 map.set(key, [comment]);
648 }
649 });
650 return map;
651 },
652);
653
654export const fieldValues = createSelector(
655 viewedIssue,
656 (issue) => issue && issue.fieldValues,
657);
658
659export const labelRefs = createSelector(
660 viewedIssue,
661 (issue) => issue && issue.labelRefs,
662);
663
664export const type = createSelector(
665 fieldValues,
666 labelRefs,
667 (fieldValues, labelRefs) => extractTypeForIssue(fieldValues, labelRefs),
668);
669
670export const restrictions = createSelector(
671 labelRefs,
672 (labelRefs) => {
673 if (!labelRefs) return {};
674
675 const restrictions = {};
676
677 labelRefs.forEach((labelRef) => {
678 const label = labelRef.label;
679 const lowerCaseLabel = label.toLowerCase();
680
681 if (lowerCaseLabel.startsWith(RESTRICT_VIEW_PREFIX)) {
682 const permissionType = removePrefix(label, RESTRICT_VIEW_PREFIX);
683 if (!('view' in restrictions)) {
684 restrictions['view'] = [permissionType];
685 } else {
686 restrictions['view'].push(permissionType);
687 }
688 } else if (lowerCaseLabel.startsWith(RESTRICT_EDIT_PREFIX)) {
689 const permissionType = removePrefix(label, RESTRICT_EDIT_PREFIX);
690 if (!('edit' in restrictions)) {
691 restrictions['edit'] = [permissionType];
692 } else {
693 restrictions['edit'].push(permissionType);
694 }
695 } else if (lowerCaseLabel.startsWith(RESTRICT_COMMENT_PREFIX)) {
696 const permissionType = removePrefix(label, RESTRICT_COMMENT_PREFIX);
697 if (!('comment' in restrictions)) {
698 restrictions['comment'] = [permissionType];
699 } else {
700 restrictions['comment'].push(permissionType);
701 }
702 }
703 });
704
705 return restrictions;
706 },
707);
708
Adrià Vilanova Martínez9f9ade52022-10-10 23:20:11 +0200709// Gets the Issue Tracker or Launch ID of a moved issue.
Adrià Vilanova Martínezde942802022-07-15 14:06:55 +0200710export const migratedId = createSelector(
711 labelRefs,
712 (labelRefs) => {
713 if (!labelRefs) return '';
714
Adrià Vilanova Martínez9f9ade52022-10-10 23:20:11 +0200715 // Assume that there's only one migrated-to-* label. Or at least drop any
716 // labels besides the first one.
717 const migrationLabel = labelRefs.find((labelRef) => {
718 return labelRef.label.toLowerCase().startsWith(MIGRATED_ISSUE_PREFIX);
719 });
720
721 if (migrationLabel) {
722 if (migrationLabel.label.toLowerCase().startsWith(MIGRATED_BUGANIZER_ISSUE_PREFIX)) {
723 return migrationLabel.label.substring(MIGRATED_BUGANIZER_ISSUE_PREFIX.length);
724 } else if (migrationLabel.label.toLowerCase().startsWith(MIGRATED_LAUNCH_ISSUE_PREFIX)) {
725 return migrationLabel.label.substring(MIGRATED_LAUNCH_ISSUE_PREFIX.length);
726 }
727 }
728 return '';
729 },
730);
731
732// Gets the Issue Migrated Type of a moved issue.
733export const migratedType = createSelector(
734 labelRefs,
735 (labelRefs) => {
736 if (!labelRefs) return migratedTypes.NONE;
737
738 // Assume that there's only one migrated-to-* label. Or at least drop any
Adrià Vilanova Martínezde942802022-07-15 14:06:55 +0200739 // labels besides the first one.
740 const migrationLabel = labelRefs.find((labelRef) => {
741 return labelRef.label.toLowerCase().startsWith(MIGRATED_ISSUE_PREFIX);
742 });
743
744 if (migrationLabel) {
Adrià Vilanova Martínez9f9ade52022-10-10 23:20:11 +0200745 if (migrationLabel.label.toLowerCase().startsWith(MIGRATED_BUGANIZER_ISSUE_PREFIX)) {
746 return migratedTypes.BUGANIZER_TYPE;
747 } else if (migrationLabel.label.toLowerCase().startsWith(MIGRATED_LAUNCH_ISSUE_PREFIX)) {
748 return migratedTypes.LAUNCH_TYPE;
749 }
Adrià Vilanova Martínezde942802022-07-15 14:06:55 +0200750 }
Adrià Vilanova Martínez9f9ade52022-10-10 23:20:11 +0200751 return migratedTypes.NONE;
Adrià Vilanova Martínezde942802022-07-15 14:06:55 +0200752 },
753);
754
Copybara854996b2021-09-07 19:36:02 +0000755export const isOpen = createSelector(
756 viewedIssue,
757 (issue) => issue && issue.statusRef && issue.statusRef.meansOpen || false);
758
759// Returns a function that, given an issue and its related issues,
760// returns a combined list of issue ref strings including related issues,
761// blocking or blocked on issues, and federated references.
762const mapRefsWithRelated = (blocking) => {
763 return (issue, relatedIssues) => {
764 let refs = [];
765 if (blocking) {
766 if (issue.blockingIssueRefs) {
767 refs = refs.concat(issue.blockingIssueRefs);
768 }
769 if (issue.danglingBlockingRefs) {
770 refs = refs.concat(issue.danglingBlockingRefs);
771 }
772 } else {
773 if (issue.blockedOnIssueRefs) {
774 refs = refs.concat(issue.blockedOnIssueRefs);
775 }
776 if (issue.danglingBlockedOnRefs) {
777 refs = refs.concat(issue.danglingBlockedOnRefs);
778 }
779 }
780
781 // Note: relatedIssues is a Redux generated key for issues, not part of the
782 // pRPC Issue object.
783 if (issue.relatedIssues) {
784 refs = refs.concat(issue.relatedIssues);
785 }
786 return refs.map((ref) => {
787 const key = issueRefToString(ref);
788 if (relatedIssues.has(key)) {
789 return relatedIssues.get(key);
790 }
791 return ref;
792 });
793 };
794};
795
796export const blockingIssues = createSelector(
797 viewedIssue, relatedIssues,
798 mapRefsWithRelated(true),
799);
800
801export const blockedOnIssues = createSelector(
802 viewedIssue, relatedIssues,
803 mapRefsWithRelated(false),
804);
805
806export const mergedInto = createSelector(
807 viewedIssue, relatedIssues,
808 (issue, relatedIssues) => {
809 if (!issue || !issue.mergedIntoIssueRef) return {};
810 const key = issueRefToString(issue.mergedIntoIssueRef);
811 if (relatedIssues && relatedIssues.has(key)) {
812 return relatedIssues.get(key);
813 }
814 return issue.mergedIntoIssueRef;
815 },
816);
817
818export const sortedBlockedOn = createSelector(
819 blockedOnIssues,
820 (blockedOn) => blockedOn.sort((a, b) => {
821 const aIsOpen = a.statusRef && a.statusRef.meansOpen ? 1 : 0;
822 const bIsOpen = b.statusRef && b.statusRef.meansOpen ? 1 : 0;
823 return bIsOpen - aIsOpen;
824 }),
825);
826
827// values (from issue.fieldValues) is an array with one entry per value.
828// We want to turn this into a map of fieldNames -> values.
829export const fieldValueMap = createSelector(
830 fieldValues,
831 (fieldValues) => fieldValuesToMap(fieldValues),
832);
833
834// Get the list of full componentDefs for the viewed issue.
835export const components = createSelector(
836 viewedIssue,
837 projectV0.componentsMap,
838 (issue, components) => {
839 if (!issue || !issue.componentRefs) return [];
840 return issue.componentRefs.map(
841 (comp) => components.get(comp.path) || comp);
842 },
843);
844
845// Get custom fields that apply to a specific issue.
846export const fieldDefs = createSelector(
847 projectV0.fieldDefs,
848 type,
849 fieldValueMap,
850 (fieldDefs, type, fieldValues) => {
851 if (!fieldDefs) return [];
852 type = type || '';
853 return fieldDefs.filter((f) => {
854 const fieldValueKey = fieldValueMapKey(f.fieldRef.fieldName,
855 f.phaseRef && f.phaseRef.phaseName);
856 if (fieldValues && fieldValues.has(fieldValueKey)) {
857 // Regardless of other checks, include a particular field def if the
858 // issue has a value defined.
859 return true;
860 }
861 // Skip approval type and phase fields here.
862 if (f.fieldRef.approvalName ||
863 f.fieldRef.type === fieldTypes.APPROVAL_TYPE ||
864 f.isPhaseField) {
865 return false;
866 }
867
868 // If this fieldDef belongs to only one type, filter out the field if
869 // that type isn't the specified type.
870 if (f.applicableType && type.toLowerCase() !==
871 f.applicableType.toLowerCase()) {
872 return false;
873 }
874
875 return true;
876 });
877 },
878);
879
880// Action Creators
881/**
882 * Tells Redux that the user has navigated to an issue page and is now
883 * viewing a new issue.
884 * @param {IssueRef} issueRef The issue that the user is viewing.
885 * @return {AnyAction}
886 */
887export const viewIssue = (issueRef) => ({type: VIEW_ISSUE, issueRef});
888
889export const fetchCommentReferences = (comments, projectName) => {
890 return async (dispatch) => {
891 dispatch({type: FETCH_COMMENT_REFERENCES_START});
892
893 try {
894 const refs = await autolink.getReferencedArtifacts(comments, projectName);
895 const commentRefs = {};
896 refs.forEach(({componentName, existingRefs}) => {
897 commentRefs[componentName] = existingRefs;
898 });
899 dispatch({
900 type: FETCH_COMMENT_REFERENCES_SUCCESS,
901 commentReferences: commentRefs,
902 });
903 } catch (error) {
904 dispatch({type: FETCH_COMMENT_REFERENCES_FAILURE, error});
905 }
906 };
907};
908
909export const fetchReferencedUsers = (issue) => async (dispatch) => {
910 if (!issue) return;
911 dispatch({type: FETCH_REFERENCED_USERS_START});
912
913 // TODO(zhangtiff): Make this function account for custom fields
914 // of type user.
915 const userRefs = [...(issue.ccRefs || [])];
916 if (issue.ownerRef) {
917 userRefs.push(issue.ownerRef);
918 }
919 (issue.approvalValues || []).forEach((approval) => {
920 userRefs.push(...(approval.approverRefs || []));
921 if (approval.setterRef) {
922 userRefs.push(approval.setterRef);
923 }
924 });
925
926 try {
927 const resp = await prpcClient.call(
928 'monorail.Users', 'ListReferencedUsers', {userRefs});
929
930 const referencedUsers = {};
931 (resp.users || []).forEach((user) => {
932 referencedUsers[user.displayName] = user;
933 });
934 dispatch({type: FETCH_REFERENCED_USERS_SUCCESS, referencedUsers});
935 } catch (error) {
936 dispatch({type: FETCH_REFERENCED_USERS_FAILURE, error});
937 }
938};
939
940export const fetchFederatedReferences = (issue) => async (dispatch) => {
941 dispatch({type: FETCH_FEDERATED_REFERENCES_START});
942
943 // Concat all potential fedrefs together, convert from shortlink to classes,
944 // then fire off a request to fetch the status of each.
945 const fedRefs = []
946 .concat(issue.danglingBlockingRefs || [])
947 .concat(issue.danglingBlockedOnRefs || [])
948 .concat(issue.mergedIntoIssueRef ? [issue.mergedIntoIssueRef] : [])
949 .filter((ref) => ref && ref.extIdentifier)
950 .map((ref) => fromShortlink(ref.extIdentifier))
951 .filter((fedRef) => fedRef);
952
953 // If no FedRefs, return empty Map.
954 if (fedRefs.length === 0) {
955 return;
956 }
957
958 try {
959 // Load email separately since it might have changed.
960 await loadGapi();
961 const email = await fetchGapiEmail();
962
963 // If already logged in, dispatch login success event.
964 dispatch({
965 type: userV0.GAPI_LOGIN_SUCCESS,
966 email: email,
967 });
968
969 await Promise.all(fedRefs.map((fedRef) => fedRef.getFederatedDetails()));
970 const fedRefIssueRefs = fedRefs.map((fedRef) => fedRef.toIssueRef());
971
972 dispatch({
973 type: FETCH_FEDERATED_REFERENCES_SUCCESS,
974 fedRefIssueRefs: fedRefIssueRefs,
975 });
976 } catch (error) {
977 dispatch({type: FETCH_FEDERATED_REFERENCES_FAILURE, error});
978 }
979};
980
981// TODO(zhangtiff): Figure out if we can reduce request/response sizes by
982// diffing issues to fetch against issues we already know about to avoid
983// fetching duplicate info.
984export const fetchRelatedIssues = (issue) => async (dispatch) => {
985 if (!issue) return;
986 dispatch({type: FETCH_RELATED_ISSUES_START});
987
988 const refsToFetch = (issue.blockedOnIssueRefs || []).concat(
989 issue.blockingIssueRefs || []);
990 // Add mergedinto ref, exclude FedRefs which are fetched separately.
991 if (issue.mergedIntoIssueRef && !issue.mergedIntoIssueRef.extIdentifier) {
992 refsToFetch.push(issue.mergedIntoIssueRef);
993 }
994
995 const message = {
996 issueRefs: refsToFetch,
997 };
998 try {
999 // Fire off call to fetch FedRefs. Since it might take longer it is
1000 // handled by a separate reducer.
1001 dispatch(fetchFederatedReferences(issue));
1002
1003 const resp = await prpcClient.call(
1004 'monorail.Issues', 'ListReferencedIssues', message);
1005
1006 const relatedIssues = {};
1007
1008 const openIssues = resp.openRefs || [];
1009 const closedIssues = resp.closedRefs || [];
1010 openIssues.forEach((issue) => {
1011 issue.statusRef.meansOpen = true;
1012 relatedIssues[issueRefToString(issue)] = issue;
1013 });
1014 closedIssues.forEach((issue) => {
1015 issue.statusRef.meansOpen = false;
1016 relatedIssues[issueRefToString(issue)] = issue;
1017 });
1018 dispatch({
1019 type: FETCH_RELATED_ISSUES_SUCCESS,
1020 relatedIssues: relatedIssues,
1021 });
1022 } catch (error) {
1023 dispatch({type: FETCH_RELATED_ISSUES_FAILURE, error});
1024 };
1025};
1026
1027/**
1028 * Fetches issue data needed to display a detailed view of a single
1029 * issue. This function dispatches many actions to handle the fetching
1030 * of issue comments, permissions, star state, and more.
1031 * @param {IssueRef} issueRef The issue that the user is viewing.
1032 * @return {function(function): Promise<void>}
1033 */
1034export const fetchIssuePageData = (issueRef) => async (dispatch) => {
1035 dispatch(fetchComments(issueRef));
1036 dispatch(fetch(issueRef));
1037 dispatch(fetchPermissions(issueRef));
1038 dispatch(fetchIsStarred(issueRef));
1039};
1040
1041/**
1042 * @param {IssueRef} issueRef Which issue to fetch.
1043 * @return {function(function): Promise<void>}
1044 */
1045export const fetch = (issueRef) => async (dispatch) => {
1046 dispatch({type: FETCH_START});
1047
1048 try {
1049 const resp = await prpcClient.call(
1050 'monorail.Issues', 'GetIssue', {issueRef},
1051 );
1052
1053 const movedToRef = resp.movedToRef;
1054
1055 // The API can return deleted issue objects that don't have issueRef data
1056 // specified. For this case, we want to make sure a projectName and localId
1057 // are still provided to the frontend to ensure that keying issues still
1058 // works.
1059 const issue = {...issueRef, ...resp.issue};
1060 if (movedToRef) {
1061 issue.movedToRef = movedToRef;
1062 }
1063
1064 dispatch({type: FETCH_SUCCESS, issue});
1065
1066 if (!issue.isDeleted && !movedToRef) {
1067 dispatch(fetchRelatedIssues(issue));
1068 dispatch(fetchHotlists(issueRef));
1069 dispatch(fetchReferencedUsers(issue));
1070 dispatch(userV0.fetchProjects([issue.reporterRef]));
1071 }
1072 } catch (error) {
1073 dispatch({type: FETCH_FAILURE, error});
1074 }
1075};
1076
1077/**
1078 * Action creator to fetch multiple Issues.
1079 * @param {Array<IssueRef>} issueRefs An Array of Issue references to fetch.
1080 * @return {function(function): Promise<void>}
1081 */
1082export const fetchIssues = (issueRefs) => async (dispatch) => {
1083 dispatch({type: FETCH_ISSUES_START});
1084
1085 try {
1086 const {openRefs, closedRefs} = await prpcClient.call(
1087 'monorail.Issues', 'ListReferencedIssues', {issueRefs});
1088 const issues = [...openRefs || [], ...closedRefs || []];
1089
1090 dispatch({type: FETCH_ISSUES_SUCCESS, issues});
1091 } catch (error) {
1092 dispatch({type: FETCH_ISSUES_FAILURE, error});
1093 }
1094};
1095
1096/**
1097 * Gets the hotlists that a given issue is in.
1098 * @param {IssueRef} issueRef
1099 * @return {function(function): Promise<void>}
1100 */
1101export const fetchHotlists = (issueRef) => async (dispatch) => {
1102 dispatch({type: FETCH_HOTLISTS_START});
1103
1104 try {
1105 const resp = await prpcClient.call(
1106 'monorail.Features', 'ListHotlistsByIssue', {issue: issueRef});
1107
1108 const hotlists = (resp.hotlists || []);
1109 hotlists.sort((hotlistA, hotlistB) => {
1110 return hotlistA.name.localeCompare(hotlistB.name);
1111 });
1112 dispatch({type: FETCH_HOTLISTS_SUCCESS, hotlists});
1113 } catch (error) {
1114 dispatch({type: FETCH_HOTLISTS_FAILURE, error});
1115 };
1116};
1117
1118/**
1119 * Async action creator to fetch issues in the issue list and grid pages. This
1120 * action creator supports batching multiple async requests to support the grid
1121 * view's ability to load up to 6,000 issues in one page load.
1122 *
1123 * @param {string} projectName The project to fetch issues from.
1124 * @param {Object} params Options for which issues to fetch.
1125 * @param {string=} params.q The query string for the search.
1126 * @param {string=} params.can The ID of the canned query for the search.
1127 * @param {string=} params.groupby The spec of which fields to group by.
1128 * @param {string=} params.sort The spec of which fields to sort by.
1129 * @param {number=} params.start What cursor index to start at.
1130 * @param {number=} params.maxItems How many items to fetch per page.
1131 * @param {number=} params.maxCalls The maximum number of API calls to make.
1132 * Combined with pagination.maxItems, this defines the maximum number of
1133 * issues this method can fetch.
1134 * @return {function(function): Promise<void>}
1135 */
1136export const fetchIssueList =
1137 (projectName, {q = undefined, can = undefined, groupby = undefined,
1138 sort = undefined, start = undefined, maxItems = undefined,
1139 maxCalls = 1,
1140 }) => async (dispatch) => {
1141 let updateData = {};
1142 const promises = [];
1143 const issuesByRequest = [];
1144 let issueLimit;
1145 let totalIssues;
1146 let totalCalls;
1147 const itemsPerCall = maxItems || 1000;
1148
1149 const cannedQuery = Number.parseInt(can) || undefined;
1150
1151 const pagination = {
1152 ...(start && {start}),
1153 ...(maxItems && {maxItems}),
1154 };
1155
1156 const message = {
1157 projectNames: [projectName],
1158 query: q,
1159 cannedQuery,
1160 groupBySpec: groupby,
1161 sortSpec: sort,
1162 pagination,
1163 };
1164
1165 dispatch({type: FETCH_ISSUE_LIST_START});
1166
1167 // initial api call made to determine total number of issues matching
1168 // the query.
1169 try {
1170 // TODO(zhangtiff): Refactor this action creator when adding issue
1171 // list pagination.
1172 const resp = await prpcClient.call(
1173 'monorail.Issues', 'ListIssues', message);
1174
1175 // prpcClient is not actually a protobuf client and therefore not
1176 // hydrating default values. See crbug.com/monorail/6641
1177 // Until that is fixed, we have to explicitly define it.
1178 const defaultFetchListResponse = {totalResults: 0, issues: []};
1179
1180 updateData =
1181 Object.entries(resp).length === 0 ?
1182 defaultFetchListResponse :
1183 resp;
1184 issuesByRequest[0] = updateData.issues;
1185 issueLimit = updateData.totalResults;
1186
1187 // determine correct issues to load and number of calls to be made.
1188 if (issueLimit > (itemsPerCall * maxCalls)) {
1189 totalIssues = itemsPerCall * maxCalls;
1190 totalCalls = maxCalls - 1;
1191 } else {
1192 totalIssues = issueLimit;
1193 totalCalls = Math.ceil(issueLimit / itemsPerCall) - 1;
1194 }
1195
1196 if (totalIssues) {
1197 updateData.progress = updateData.issues.length / totalIssues;
1198 } else {
1199 updateData.progress = 1;
1200 }
1201
1202 dispatch({type: FETCH_ISSUE_LIST_UPDATE, ...updateData});
1203
1204 // remaining api calls are made.
1205 for (let i = 1; i <= totalCalls; i++) {
1206 promises[i - 1] = (async () => {
1207 const resp = await prpcClient.call(
1208 'monorail.Issues', 'ListIssues', {
1209 ...message,
1210 pagination: {start: i * itemsPerCall, maxItems: itemsPerCall},
1211 });
1212 issuesByRequest[i] = (resp.issues || []);
1213 // sort the issues in the correct order.
1214 updateData.issues = [];
1215 issuesByRequest.forEach((issue) => {
1216 updateData.issues = updateData.issues.concat(issue);
1217 });
1218 updateData.progress = updateData.issues.length / totalIssues;
1219 dispatch({type: FETCH_ISSUE_LIST_UPDATE, ...updateData});
1220 })();
1221 }
1222
1223 await Promise.all(promises);
1224
1225 // TODO(zhangtiff): Try to delete FETCH_ISSUE_LIST_SUCCESS in favor of
1226 // just FETCH_ISSUE_LIST_UPDATE.
1227 dispatch({type: FETCH_ISSUE_LIST_SUCCESS});
1228 } catch (error) {
1229 dispatch({type: FETCH_ISSUE_LIST_FAILURE, error});
1230 };
1231 };
1232
1233/**
1234 * Fetches the currently logged in user's permissions for a given issue.
1235 * @param {Issue} issueRef
1236 * @return {function(function): Promise<void>}
1237 */
1238export const fetchPermissions = (issueRef) => async (dispatch) => {
1239 dispatch({type: FETCH_PERMISSIONS_START});
1240
1241 try {
1242 const resp = await prpcClient.call(
1243 'monorail.Issues', 'ListIssuePermissions', {issueRef},
1244 );
1245
1246 dispatch({type: FETCH_PERMISSIONS_SUCCESS, permissions: resp.permissions});
1247 } catch (error) {
1248 dispatch({type: FETCH_PERMISSIONS_FAILURE, error});
1249 };
1250};
1251
1252/**
1253 * Fetches comments for an issue. Note that issue descriptions are also
1254 * comments.
1255 * @param {IssueRef} issueRef
1256 * @return {function(function): Promise<void>}
1257 */
1258export const fetchComments = (issueRef) => async (dispatch) => {
1259 dispatch({type: FETCH_COMMENTS_START});
1260
1261 try {
1262 const resp = await prpcClient.call(
1263 'monorail.Issues', 'ListComments', {issueRef});
1264
1265 dispatch({type: FETCH_COMMENTS_SUCCESS, comments: resp.comments});
1266 dispatch(fetchCommentReferences(
1267 resp.comments, issueRef.projectName));
1268
1269 const commenterRefs = (resp.comments || []).map(
1270 (comment) => comment.commenter);
1271 dispatch(userV0.fetchProjects(commenterRefs));
1272 } catch (error) {
1273 dispatch({type: FETCH_COMMENTS_FAILURE, error});
1274 };
1275};
1276
1277/**
1278 * Gets whether the logged in user has starred a given issue.
1279 * @param {IssueRef} issueRef
1280 * @return {function(function): Promise<void>}
1281 */
1282export const fetchIsStarred = (issueRef) => async (dispatch) => {
1283 dispatch({type: FETCH_IS_STARRED_START});
1284 try {
1285 const resp = await prpcClient.call(
1286 'monorail.Issues', 'IsIssueStarred', {issueRef},
1287 );
1288
1289 dispatch({
1290 type: FETCH_IS_STARRED_SUCCESS,
1291 starred: resp.isStarred,
1292 issueRef: issueRef,
1293 });
1294 } catch (error) {
1295 dispatch({type: FETCH_IS_STARRED_FAILURE, error});
1296 };
1297};
1298
1299/**
1300 * Fetch all of a logged in user's starred issues.
1301 * @return {function(function): Promise<void>}
1302 */
1303export const fetchStarredIssues = () => async (dispatch) => {
1304 dispatch({type: FETCH_ISSUES_STARRED_START});
1305
1306 try {
1307 const resp = await prpcClient.call(
1308 'monorail.Issues', 'ListStarredIssues', {},
1309 );
1310 dispatch({type: FETCH_ISSUES_STARRED_SUCCESS,
1311 starredIssueRefs: resp.starredIssueRefs});
1312 } catch (error) {
1313 dispatch({type: FETCH_ISSUES_STARRED_FAILURE, error});
1314 };
1315};
1316
1317/**
1318 * Stars or unstars an issue.
1319 * @param {IssueRef} issueRef The issue to star.
1320 * @param {boolean} starred Whether to star or unstar.
1321 * @return {function(function): Promise<void>}
1322 */
1323export const star = (issueRef, starred) => async (dispatch) => {
1324 const requestKey = issueRefToString(issueRef);
1325
1326 dispatch({type: STAR_START, requestKey});
1327 const message = {issueRef, starred};
1328
1329 try {
1330 const resp = await prpcClient.call(
1331 'monorail.Issues', 'StarIssue', message,
1332 );
1333
1334 dispatch({
1335 type: STAR_SUCCESS,
1336 starCount: resp.starCount,
1337 issueRef,
1338 starred,
1339 requestKey,
1340 });
1341 } catch (error) {
1342 dispatch({type: STAR_FAILURE, error, requestKey});
1343 }
1344};
1345
1346/**
1347 * Runs a presubmit request to find warnings to show the user before an issue
1348 * edit is saved.
1349 * @param {IssueRef} issueRef The issue being edited.
1350 * @param {IssueDelta} issueDelta The user's in flight changes to the issue.
1351 * @return {function(function): Promise<void>}
1352 */
1353export const presubmit = (issueRef, issueDelta) => async (dispatch) => {
1354 dispatch({type: PRESUBMIT_START});
1355
1356 try {
1357 const resp = await prpcClient.call(
1358 'monorail.Issues', 'PresubmitIssue', {issueRef, issueDelta});
1359
1360 dispatch({type: PRESUBMIT_SUCCESS, presubmitResponse: resp});
1361 } catch (error) {
1362 dispatch({type: PRESUBMIT_FAILURE, error: error});
1363 }
1364};
1365
1366/**
1367 * Async action creator to update an issue's approval.
1368 *
1369 * @param {Object} params Options for the approval update.
1370 * @param {IssueRef} params.issueRef
1371 * @param {FieldRef} params.fieldRef
1372 * @param {ApprovalDelta=} params.approvalDelta
1373 * @param {string=} params.commentContent
1374 * @param {boolean=} params.sendEmail
1375 * @param {boolean=} params.isDescription
1376 * @param {AttachmentUpload=} params.uploads
1377 * @return {function(function): Promise<void>}
1378 */
1379export const updateApproval = ({issueRef, fieldRef, approvalDelta,
1380 commentContent, sendEmail, isDescription, uploads}) => async (dispatch) => {
1381 dispatch({type: UPDATE_APPROVAL_START});
1382 try {
1383 const {approval} = await prpcClient.call(
1384 'monorail.Issues', 'UpdateApproval', {
1385 ...(issueRef && {issueRef}),
1386 ...(fieldRef && {fieldRef}),
1387 ...(approvalDelta && {approvalDelta}),
1388 ...(commentContent && {commentContent}),
1389 ...(sendEmail && {sendEmail}),
1390 ...(isDescription && {isDescription}),
1391 ...(uploads && {uploads}),
1392 });
1393
1394 dispatch({type: UPDATE_APPROVAL_SUCCESS, approval, issueRef});
1395 dispatch(fetch(issueRef));
1396 dispatch(fetchComments(issueRef));
1397 } catch (error) {
1398 dispatch({type: UPDATE_APPROVAL_FAILURE, error: error});
1399 };
1400};
1401
1402/**
1403 * Async action creator to update an issue.
1404 *
1405 * @param {Object} params Options for the issue update.
1406 * @param {IssueRef} params.issueRef
1407 * @param {IssueDelta=} params.delta
1408 * @param {string=} params.commentContent
1409 * @param {boolean=} params.sendEmail
1410 * @param {boolean=} params.isDescription
1411 * @param {AttachmentUpload=} params.uploads
1412 * @param {Array<number>=} params.keptAttachments
1413 * @return {function(function): Promise<void>}
1414 */
1415export const update = ({issueRef, delta, commentContent, sendEmail,
1416 isDescription, uploads, keptAttachments}) => async (dispatch) => {
1417 dispatch({type: UPDATE_START});
1418
1419 try {
1420 const {issue} = await prpcClient.call(
1421 'monorail.Issues', 'UpdateIssue', {issueRef, delta,
1422 commentContent, sendEmail, isDescription, uploads,
1423 keptAttachments});
1424
1425 dispatch({type: UPDATE_SUCCESS, issue});
1426 dispatch(fetchComments(issueRef));
1427 dispatch(fetchRelatedIssues(issue));
1428 dispatch(fetchReferencedUsers(issue));
1429 } catch (error) {
1430 dispatch({type: UPDATE_FAILURE, error: error});
1431 };
1432};
1433
1434/**
1435 * Converts an issue from one template to another. This is used for changing
1436 * launch issues.
1437 * @param {IssueRef} issueRef
1438 * @param {Object} options
1439 * @param {string=} options.templateName
1440 * @param {string=} options.commentContent
1441 * @param {boolean=} options.sendEmail
1442 * @return {function(function): Promise<void>}
1443 */
1444export const convert = (issueRef, {templateName = '',
1445 commentContent = '', sendEmail = true},
1446) => async (dispatch) => {
1447 dispatch({type: CONVERT_START});
1448
1449 try {
1450 const resp = await prpcClient.call(
1451 'monorail.Issues', 'ConvertIssueApprovalsTemplate',
1452 {issueRef, templateName, commentContent, sendEmail});
1453
1454 dispatch({type: CONVERT_SUCCESS, issue: resp.issue});
1455 const fetchCommentsMessage = {issueRef};
1456 dispatch(fetchComments(fetchCommentsMessage));
1457 } catch (error) {
1458 dispatch({type: CONVERT_FAILURE, error: error});
1459 };
1460};