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