blob: 880ebbcbda396ff8ea6a5c444dac3b1c56b460fc [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,
17 fieldValuesToMap} from 'shared/issue-fields.js';
18import {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ínezde942802022-07-15 14:06:55 +0200496const MIGRATED_ISSUE_PREFIX = 'migrated-to-b-';
Copybara854996b2021-09-07 19:36:02 +0000497
498/**
499 * Selector to retrieve all normalized Issue data in the Redux store,
500 * keyed by IssueRefString.
501 * @param {any} state
502 * @return {Object<IssueRefString, Issue>}
503 */
504const issuesByRefString = (state) => state.issue.issuesByRefString;
505
506/**
507 * Selector to return a function to retrieve an Issue from the Redux store.
508 * @param {any} state
509 * @return {function(string): ?Issue}
510 */
511export const issue = createSelector(issuesByRefString, (issuesByRefString) =>
512 (name) => issuesByRefString[issueNameToRefString(name)]);
513
514/**
515 * Selector to return a function to retrieve a given Issue Object from
516 * the Redux store.
517 * @param {any} state
518 * @return {function(IssueRefString, string): Issue}
519 */
520export const issueForRefString = createSelector(issuesByRefString,
521 (issuesByRefString) => (issueRefString, projectName = undefined) => {
522 // In some contexts, an issue ref string will omit a project name,
523 // assuming the default project to be the project name. We never
524 // omit the project name in strings used as keys, so we have to
525 // make sure issue ref strings contain the project name.
526 const ref = issueStringToRef(issueRefString, projectName);
527 const refString = issueRefToString(ref);
528 if (issuesByRefString.hasOwnProperty(refString)) {
529 return issuesByRefString[refString];
530 }
531 return issueStringToRef(refString, projectName);
532 });
533
534/**
535 * Selector to get a reference to the currently viewed issue, in string form.
536 * @param {any} state
537 * @return {IssueRefString}
538 */
539const viewedIssueRefString = (state) => state.issue.viewedIssueRef;
540
541/**
542 * Selector to get a reference to the currently viewed issue.
543 * @param {any} state
544 * @return {IssueRef}
545 */
546export const viewedIssueRef = createSelector(viewedIssueRefString,
547 (viewedIssueRefString) => issueStringToRef(viewedIssueRefString));
548
549/**
550 * Selector to get the full Issue data for the currently viewed issue.
551 * @param {any} state
552 * @return {Issue}
553 */
554export const viewedIssue = createSelector(issuesByRefString,
555 viewedIssueRefString,
556 (issuesByRefString, viewedIssueRefString) =>
557 issuesByRefString[viewedIssueRefString] || {});
558
559export const comments = (state) => state.issue.comments;
560export const commentsLoaded = (state) => state.issue.commentsLoaded;
561
562const _commentReferences = (state) => state.issue.commentReferences;
563export const commentReferences = createSelector(_commentReferences,
564 (commentReferences) => objectToMap(commentReferences));
565
566export const hotlists = (state) => state.issue.hotlists;
567
568const stateIssueList = (state) => state.issue.issueList;
569export const issueList = createSelector(
570 issuesByRefString,
571 stateIssueList,
572 (issuesByRefString, stateIssueList) => {
573 return (stateIssueList.issueRefs || []).map((issueRef) => {
574 return issuesByRefString[issueRef];
575 });
576 },
577);
578export const totalIssues = (state) => state.issue.issueList.totalResults;
579export const issueListProgress = (state) => state.issue.issueList.progress;
580export const issueListPhaseNames = createSelector(issueList, (issueList) => {
581 const phaseNamesSet = new Set();
582 if (issueList) {
583 issueList.forEach(({phases}) => {
584 if (phases) {
585 phases.forEach(({phaseRef: {phaseName}}) => {
586 phaseNamesSet.add(phaseName.toLowerCase());
587 });
588 }
589 });
590 }
591 return Array.from(phaseNamesSet);
592});
593
594/**
595 * @param {any} state
596 * @return {boolean} Whether the currently viewed issue list
597 * has loaded.
598 */
599export const issueListLoaded = createSelector(
600 stateIssueList,
601 (stateIssueList) => stateIssueList.issueRefs !== undefined);
602
603export const permissions = (state) => state.issue.permissions;
604export const presubmitResponse = (state) => state.issue.presubmitResponse;
605
606const _relatedIssues = (state) => state.issue.relatedIssues || {};
607export const relatedIssues = createSelector(_relatedIssues,
608 (relatedIssues) => objectToMap(relatedIssues));
609
610const _referencedUsers = (state) => state.issue.referencedUsers || {};
611export const referencedUsers = createSelector(_referencedUsers,
612 (referencedUsers) => objectToMap(referencedUsers));
613
614export const isStarred = (state) => state.issue.isStarred;
615export const _starredIssues = (state) => state.issue.starredIssues;
616
617export const requests = (state) => state.issue.requests;
618
619// Returns a Map of in flight StarIssues requests, keyed by issueRef.
620export const starringIssues = createSelector(requests, (requests) =>
621 objectToMap(requests.starringIssues));
622
623export const starredIssues = createSelector(
624 _starredIssues,
625 (starredIssues) => {
626 const stars = new Set();
627 for (const [ref, starred] of Object.entries(starredIssues)) {
628 if (starred) stars.add(ref);
629 }
630 return stars;
631 },
632);
633
634// TODO(zhangtiff): Split up either comments or approvals into their own "duck".
635export const commentsByApprovalName = createSelector(
636 comments,
637 (comments) => {
638 const map = new Map();
639 comments.forEach((comment) => {
640 const key = (comment.approvalRef && comment.approvalRef.fieldName) ||
641 '';
642 if (map.has(key)) {
643 map.get(key).push(comment);
644 } else {
645 map.set(key, [comment]);
646 }
647 });
648 return map;
649 },
650);
651
652export const fieldValues = createSelector(
653 viewedIssue,
654 (issue) => issue && issue.fieldValues,
655);
656
657export const labelRefs = createSelector(
658 viewedIssue,
659 (issue) => issue && issue.labelRefs,
660);
661
662export const type = createSelector(
663 fieldValues,
664 labelRefs,
665 (fieldValues, labelRefs) => extractTypeForIssue(fieldValues, labelRefs),
666);
667
668export const restrictions = createSelector(
669 labelRefs,
670 (labelRefs) => {
671 if (!labelRefs) return {};
672
673 const restrictions = {};
674
675 labelRefs.forEach((labelRef) => {
676 const label = labelRef.label;
677 const lowerCaseLabel = label.toLowerCase();
678
679 if (lowerCaseLabel.startsWith(RESTRICT_VIEW_PREFIX)) {
680 const permissionType = removePrefix(label, RESTRICT_VIEW_PREFIX);
681 if (!('view' in restrictions)) {
682 restrictions['view'] = [permissionType];
683 } else {
684 restrictions['view'].push(permissionType);
685 }
686 } else if (lowerCaseLabel.startsWith(RESTRICT_EDIT_PREFIX)) {
687 const permissionType = removePrefix(label, RESTRICT_EDIT_PREFIX);
688 if (!('edit' in restrictions)) {
689 restrictions['edit'] = [permissionType];
690 } else {
691 restrictions['edit'].push(permissionType);
692 }
693 } else if (lowerCaseLabel.startsWith(RESTRICT_COMMENT_PREFIX)) {
694 const permissionType = removePrefix(label, RESTRICT_COMMENT_PREFIX);
695 if (!('comment' in restrictions)) {
696 restrictions['comment'] = [permissionType];
697 } else {
698 restrictions['comment'].push(permissionType);
699 }
700 }
701 });
702
703 return restrictions;
704 },
705);
706
Adrià Vilanova Martínezde942802022-07-15 14:06:55 +0200707// Gets the Issue Tracker ID of a moved issue.
708export const migratedId = createSelector(
709 labelRefs,
710 (labelRefs) => {
711 if (!labelRefs) return '';
712
713 // Assume that there's only one migrated-to-b-* label. Or at least drop any
714 // labels besides the first one.
715 const migrationLabel = labelRefs.find((labelRef) => {
716 return labelRef.label.toLowerCase().startsWith(MIGRATED_ISSUE_PREFIX);
717 });
718
719 if (migrationLabel) {
720 return migrationLabel.label.substring(MIGRATED_ISSUE_PREFIX.length);
721 }
722 return '';
723 },
724);
725
Copybara854996b2021-09-07 19:36:02 +0000726export const isOpen = createSelector(
727 viewedIssue,
728 (issue) => issue && issue.statusRef && issue.statusRef.meansOpen || false);
729
730// Returns a function that, given an issue and its related issues,
731// returns a combined list of issue ref strings including related issues,
732// blocking or blocked on issues, and federated references.
733const mapRefsWithRelated = (blocking) => {
734 return (issue, relatedIssues) => {
735 let refs = [];
736 if (blocking) {
737 if (issue.blockingIssueRefs) {
738 refs = refs.concat(issue.blockingIssueRefs);
739 }
740 if (issue.danglingBlockingRefs) {
741 refs = refs.concat(issue.danglingBlockingRefs);
742 }
743 } else {
744 if (issue.blockedOnIssueRefs) {
745 refs = refs.concat(issue.blockedOnIssueRefs);
746 }
747 if (issue.danglingBlockedOnRefs) {
748 refs = refs.concat(issue.danglingBlockedOnRefs);
749 }
750 }
751
752 // Note: relatedIssues is a Redux generated key for issues, not part of the
753 // pRPC Issue object.
754 if (issue.relatedIssues) {
755 refs = refs.concat(issue.relatedIssues);
756 }
757 return refs.map((ref) => {
758 const key = issueRefToString(ref);
759 if (relatedIssues.has(key)) {
760 return relatedIssues.get(key);
761 }
762 return ref;
763 });
764 };
765};
766
767export const blockingIssues = createSelector(
768 viewedIssue, relatedIssues,
769 mapRefsWithRelated(true),
770);
771
772export const blockedOnIssues = createSelector(
773 viewedIssue, relatedIssues,
774 mapRefsWithRelated(false),
775);
776
777export const mergedInto = createSelector(
778 viewedIssue, relatedIssues,
779 (issue, relatedIssues) => {
780 if (!issue || !issue.mergedIntoIssueRef) return {};
781 const key = issueRefToString(issue.mergedIntoIssueRef);
782 if (relatedIssues && relatedIssues.has(key)) {
783 return relatedIssues.get(key);
784 }
785 return issue.mergedIntoIssueRef;
786 },
787);
788
789export const sortedBlockedOn = createSelector(
790 blockedOnIssues,
791 (blockedOn) => blockedOn.sort((a, b) => {
792 const aIsOpen = a.statusRef && a.statusRef.meansOpen ? 1 : 0;
793 const bIsOpen = b.statusRef && b.statusRef.meansOpen ? 1 : 0;
794 return bIsOpen - aIsOpen;
795 }),
796);
797
798// values (from issue.fieldValues) is an array with one entry per value.
799// We want to turn this into a map of fieldNames -> values.
800export const fieldValueMap = createSelector(
801 fieldValues,
802 (fieldValues) => fieldValuesToMap(fieldValues),
803);
804
805// Get the list of full componentDefs for the viewed issue.
806export const components = createSelector(
807 viewedIssue,
808 projectV0.componentsMap,
809 (issue, components) => {
810 if (!issue || !issue.componentRefs) return [];
811 return issue.componentRefs.map(
812 (comp) => components.get(comp.path) || comp);
813 },
814);
815
816// Get custom fields that apply to a specific issue.
817export const fieldDefs = createSelector(
818 projectV0.fieldDefs,
819 type,
820 fieldValueMap,
821 (fieldDefs, type, fieldValues) => {
822 if (!fieldDefs) return [];
823 type = type || '';
824 return fieldDefs.filter((f) => {
825 const fieldValueKey = fieldValueMapKey(f.fieldRef.fieldName,
826 f.phaseRef && f.phaseRef.phaseName);
827 if (fieldValues && fieldValues.has(fieldValueKey)) {
828 // Regardless of other checks, include a particular field def if the
829 // issue has a value defined.
830 return true;
831 }
832 // Skip approval type and phase fields here.
833 if (f.fieldRef.approvalName ||
834 f.fieldRef.type === fieldTypes.APPROVAL_TYPE ||
835 f.isPhaseField) {
836 return false;
837 }
838
839 // If this fieldDef belongs to only one type, filter out the field if
840 // that type isn't the specified type.
841 if (f.applicableType && type.toLowerCase() !==
842 f.applicableType.toLowerCase()) {
843 return false;
844 }
845
846 return true;
847 });
848 },
849);
850
851// Action Creators
852/**
853 * Tells Redux that the user has navigated to an issue page and is now
854 * viewing a new issue.
855 * @param {IssueRef} issueRef The issue that the user is viewing.
856 * @return {AnyAction}
857 */
858export const viewIssue = (issueRef) => ({type: VIEW_ISSUE, issueRef});
859
860export const fetchCommentReferences = (comments, projectName) => {
861 return async (dispatch) => {
862 dispatch({type: FETCH_COMMENT_REFERENCES_START});
863
864 try {
865 const refs = await autolink.getReferencedArtifacts(comments, projectName);
866 const commentRefs = {};
867 refs.forEach(({componentName, existingRefs}) => {
868 commentRefs[componentName] = existingRefs;
869 });
870 dispatch({
871 type: FETCH_COMMENT_REFERENCES_SUCCESS,
872 commentReferences: commentRefs,
873 });
874 } catch (error) {
875 dispatch({type: FETCH_COMMENT_REFERENCES_FAILURE, error});
876 }
877 };
878};
879
880export const fetchReferencedUsers = (issue) => async (dispatch) => {
881 if (!issue) return;
882 dispatch({type: FETCH_REFERENCED_USERS_START});
883
884 // TODO(zhangtiff): Make this function account for custom fields
885 // of type user.
886 const userRefs = [...(issue.ccRefs || [])];
887 if (issue.ownerRef) {
888 userRefs.push(issue.ownerRef);
889 }
890 (issue.approvalValues || []).forEach((approval) => {
891 userRefs.push(...(approval.approverRefs || []));
892 if (approval.setterRef) {
893 userRefs.push(approval.setterRef);
894 }
895 });
896
897 try {
898 const resp = await prpcClient.call(
899 'monorail.Users', 'ListReferencedUsers', {userRefs});
900
901 const referencedUsers = {};
902 (resp.users || []).forEach((user) => {
903 referencedUsers[user.displayName] = user;
904 });
905 dispatch({type: FETCH_REFERENCED_USERS_SUCCESS, referencedUsers});
906 } catch (error) {
907 dispatch({type: FETCH_REFERENCED_USERS_FAILURE, error});
908 }
909};
910
911export const fetchFederatedReferences = (issue) => async (dispatch) => {
912 dispatch({type: FETCH_FEDERATED_REFERENCES_START});
913
914 // Concat all potential fedrefs together, convert from shortlink to classes,
915 // then fire off a request to fetch the status of each.
916 const fedRefs = []
917 .concat(issue.danglingBlockingRefs || [])
918 .concat(issue.danglingBlockedOnRefs || [])
919 .concat(issue.mergedIntoIssueRef ? [issue.mergedIntoIssueRef] : [])
920 .filter((ref) => ref && ref.extIdentifier)
921 .map((ref) => fromShortlink(ref.extIdentifier))
922 .filter((fedRef) => fedRef);
923
924 // If no FedRefs, return empty Map.
925 if (fedRefs.length === 0) {
926 return;
927 }
928
929 try {
930 // Load email separately since it might have changed.
931 await loadGapi();
932 const email = await fetchGapiEmail();
933
934 // If already logged in, dispatch login success event.
935 dispatch({
936 type: userV0.GAPI_LOGIN_SUCCESS,
937 email: email,
938 });
939
940 await Promise.all(fedRefs.map((fedRef) => fedRef.getFederatedDetails()));
941 const fedRefIssueRefs = fedRefs.map((fedRef) => fedRef.toIssueRef());
942
943 dispatch({
944 type: FETCH_FEDERATED_REFERENCES_SUCCESS,
945 fedRefIssueRefs: fedRefIssueRefs,
946 });
947 } catch (error) {
948 dispatch({type: FETCH_FEDERATED_REFERENCES_FAILURE, error});
949 }
950};
951
952// TODO(zhangtiff): Figure out if we can reduce request/response sizes by
953// diffing issues to fetch against issues we already know about to avoid
954// fetching duplicate info.
955export const fetchRelatedIssues = (issue) => async (dispatch) => {
956 if (!issue) return;
957 dispatch({type: FETCH_RELATED_ISSUES_START});
958
959 const refsToFetch = (issue.blockedOnIssueRefs || []).concat(
960 issue.blockingIssueRefs || []);
961 // Add mergedinto ref, exclude FedRefs which are fetched separately.
962 if (issue.mergedIntoIssueRef && !issue.mergedIntoIssueRef.extIdentifier) {
963 refsToFetch.push(issue.mergedIntoIssueRef);
964 }
965
966 const message = {
967 issueRefs: refsToFetch,
968 };
969 try {
970 // Fire off call to fetch FedRefs. Since it might take longer it is
971 // handled by a separate reducer.
972 dispatch(fetchFederatedReferences(issue));
973
974 const resp = await prpcClient.call(
975 'monorail.Issues', 'ListReferencedIssues', message);
976
977 const relatedIssues = {};
978
979 const openIssues = resp.openRefs || [];
980 const closedIssues = resp.closedRefs || [];
981 openIssues.forEach((issue) => {
982 issue.statusRef.meansOpen = true;
983 relatedIssues[issueRefToString(issue)] = issue;
984 });
985 closedIssues.forEach((issue) => {
986 issue.statusRef.meansOpen = false;
987 relatedIssues[issueRefToString(issue)] = issue;
988 });
989 dispatch({
990 type: FETCH_RELATED_ISSUES_SUCCESS,
991 relatedIssues: relatedIssues,
992 });
993 } catch (error) {
994 dispatch({type: FETCH_RELATED_ISSUES_FAILURE, error});
995 };
996};
997
998/**
999 * Fetches issue data needed to display a detailed view of a single
1000 * issue. This function dispatches many actions to handle the fetching
1001 * of issue comments, permissions, star state, and more.
1002 * @param {IssueRef} issueRef The issue that the user is viewing.
1003 * @return {function(function): Promise<void>}
1004 */
1005export const fetchIssuePageData = (issueRef) => async (dispatch) => {
1006 dispatch(fetchComments(issueRef));
1007 dispatch(fetch(issueRef));
1008 dispatch(fetchPermissions(issueRef));
1009 dispatch(fetchIsStarred(issueRef));
1010};
1011
1012/**
1013 * @param {IssueRef} issueRef Which issue to fetch.
1014 * @return {function(function): Promise<void>}
1015 */
1016export const fetch = (issueRef) => async (dispatch) => {
1017 dispatch({type: FETCH_START});
1018
1019 try {
1020 const resp = await prpcClient.call(
1021 'monorail.Issues', 'GetIssue', {issueRef},
1022 );
1023
1024 const movedToRef = resp.movedToRef;
1025
1026 // The API can return deleted issue objects that don't have issueRef data
1027 // specified. For this case, we want to make sure a projectName and localId
1028 // are still provided to the frontend to ensure that keying issues still
1029 // works.
1030 const issue = {...issueRef, ...resp.issue};
1031 if (movedToRef) {
1032 issue.movedToRef = movedToRef;
1033 }
1034
1035 dispatch({type: FETCH_SUCCESS, issue});
1036
1037 if (!issue.isDeleted && !movedToRef) {
1038 dispatch(fetchRelatedIssues(issue));
1039 dispatch(fetchHotlists(issueRef));
1040 dispatch(fetchReferencedUsers(issue));
1041 dispatch(userV0.fetchProjects([issue.reporterRef]));
1042 }
1043 } catch (error) {
1044 dispatch({type: FETCH_FAILURE, error});
1045 }
1046};
1047
1048/**
1049 * Action creator to fetch multiple Issues.
1050 * @param {Array<IssueRef>} issueRefs An Array of Issue references to fetch.
1051 * @return {function(function): Promise<void>}
1052 */
1053export const fetchIssues = (issueRefs) => async (dispatch) => {
1054 dispatch({type: FETCH_ISSUES_START});
1055
1056 try {
1057 const {openRefs, closedRefs} = await prpcClient.call(
1058 'monorail.Issues', 'ListReferencedIssues', {issueRefs});
1059 const issues = [...openRefs || [], ...closedRefs || []];
1060
1061 dispatch({type: FETCH_ISSUES_SUCCESS, issues});
1062 } catch (error) {
1063 dispatch({type: FETCH_ISSUES_FAILURE, error});
1064 }
1065};
1066
1067/**
1068 * Gets the hotlists that a given issue is in.
1069 * @param {IssueRef} issueRef
1070 * @return {function(function): Promise<void>}
1071 */
1072export const fetchHotlists = (issueRef) => async (dispatch) => {
1073 dispatch({type: FETCH_HOTLISTS_START});
1074
1075 try {
1076 const resp = await prpcClient.call(
1077 'monorail.Features', 'ListHotlistsByIssue', {issue: issueRef});
1078
1079 const hotlists = (resp.hotlists || []);
1080 hotlists.sort((hotlistA, hotlistB) => {
1081 return hotlistA.name.localeCompare(hotlistB.name);
1082 });
1083 dispatch({type: FETCH_HOTLISTS_SUCCESS, hotlists});
1084 } catch (error) {
1085 dispatch({type: FETCH_HOTLISTS_FAILURE, error});
1086 };
1087};
1088
1089/**
1090 * Async action creator to fetch issues in the issue list and grid pages. This
1091 * action creator supports batching multiple async requests to support the grid
1092 * view's ability to load up to 6,000 issues in one page load.
1093 *
1094 * @param {string} projectName The project to fetch issues from.
1095 * @param {Object} params Options for which issues to fetch.
1096 * @param {string=} params.q The query string for the search.
1097 * @param {string=} params.can The ID of the canned query for the search.
1098 * @param {string=} params.groupby The spec of which fields to group by.
1099 * @param {string=} params.sort The spec of which fields to sort by.
1100 * @param {number=} params.start What cursor index to start at.
1101 * @param {number=} params.maxItems How many items to fetch per page.
1102 * @param {number=} params.maxCalls The maximum number of API calls to make.
1103 * Combined with pagination.maxItems, this defines the maximum number of
1104 * issues this method can fetch.
1105 * @return {function(function): Promise<void>}
1106 */
1107export const fetchIssueList =
1108 (projectName, {q = undefined, can = undefined, groupby = undefined,
1109 sort = undefined, start = undefined, maxItems = undefined,
1110 maxCalls = 1,
1111 }) => async (dispatch) => {
1112 let updateData = {};
1113 const promises = [];
1114 const issuesByRequest = [];
1115 let issueLimit;
1116 let totalIssues;
1117 let totalCalls;
1118 const itemsPerCall = maxItems || 1000;
1119
1120 const cannedQuery = Number.parseInt(can) || undefined;
1121
1122 const pagination = {
1123 ...(start && {start}),
1124 ...(maxItems && {maxItems}),
1125 };
1126
1127 const message = {
1128 projectNames: [projectName],
1129 query: q,
1130 cannedQuery,
1131 groupBySpec: groupby,
1132 sortSpec: sort,
1133 pagination,
1134 };
1135
1136 dispatch({type: FETCH_ISSUE_LIST_START});
1137
1138 // initial api call made to determine total number of issues matching
1139 // the query.
1140 try {
1141 // TODO(zhangtiff): Refactor this action creator when adding issue
1142 // list pagination.
1143 const resp = await prpcClient.call(
1144 'monorail.Issues', 'ListIssues', message);
1145
1146 // prpcClient is not actually a protobuf client and therefore not
1147 // hydrating default values. See crbug.com/monorail/6641
1148 // Until that is fixed, we have to explicitly define it.
1149 const defaultFetchListResponse = {totalResults: 0, issues: []};
1150
1151 updateData =
1152 Object.entries(resp).length === 0 ?
1153 defaultFetchListResponse :
1154 resp;
1155 issuesByRequest[0] = updateData.issues;
1156 issueLimit = updateData.totalResults;
1157
1158 // determine correct issues to load and number of calls to be made.
1159 if (issueLimit > (itemsPerCall * maxCalls)) {
1160 totalIssues = itemsPerCall * maxCalls;
1161 totalCalls = maxCalls - 1;
1162 } else {
1163 totalIssues = issueLimit;
1164 totalCalls = Math.ceil(issueLimit / itemsPerCall) - 1;
1165 }
1166
1167 if (totalIssues) {
1168 updateData.progress = updateData.issues.length / totalIssues;
1169 } else {
1170 updateData.progress = 1;
1171 }
1172
1173 dispatch({type: FETCH_ISSUE_LIST_UPDATE, ...updateData});
1174
1175 // remaining api calls are made.
1176 for (let i = 1; i <= totalCalls; i++) {
1177 promises[i - 1] = (async () => {
1178 const resp = await prpcClient.call(
1179 'monorail.Issues', 'ListIssues', {
1180 ...message,
1181 pagination: {start: i * itemsPerCall, maxItems: itemsPerCall},
1182 });
1183 issuesByRequest[i] = (resp.issues || []);
1184 // sort the issues in the correct order.
1185 updateData.issues = [];
1186 issuesByRequest.forEach((issue) => {
1187 updateData.issues = updateData.issues.concat(issue);
1188 });
1189 updateData.progress = updateData.issues.length / totalIssues;
1190 dispatch({type: FETCH_ISSUE_LIST_UPDATE, ...updateData});
1191 })();
1192 }
1193
1194 await Promise.all(promises);
1195
1196 // TODO(zhangtiff): Try to delete FETCH_ISSUE_LIST_SUCCESS in favor of
1197 // just FETCH_ISSUE_LIST_UPDATE.
1198 dispatch({type: FETCH_ISSUE_LIST_SUCCESS});
1199 } catch (error) {
1200 dispatch({type: FETCH_ISSUE_LIST_FAILURE, error});
1201 };
1202 };
1203
1204/**
1205 * Fetches the currently logged in user's permissions for a given issue.
1206 * @param {Issue} issueRef
1207 * @return {function(function): Promise<void>}
1208 */
1209export const fetchPermissions = (issueRef) => async (dispatch) => {
1210 dispatch({type: FETCH_PERMISSIONS_START});
1211
1212 try {
1213 const resp = await prpcClient.call(
1214 'monorail.Issues', 'ListIssuePermissions', {issueRef},
1215 );
1216
1217 dispatch({type: FETCH_PERMISSIONS_SUCCESS, permissions: resp.permissions});
1218 } catch (error) {
1219 dispatch({type: FETCH_PERMISSIONS_FAILURE, error});
1220 };
1221};
1222
1223/**
1224 * Fetches comments for an issue. Note that issue descriptions are also
1225 * comments.
1226 * @param {IssueRef} issueRef
1227 * @return {function(function): Promise<void>}
1228 */
1229export const fetchComments = (issueRef) => async (dispatch) => {
1230 dispatch({type: FETCH_COMMENTS_START});
1231
1232 try {
1233 const resp = await prpcClient.call(
1234 'monorail.Issues', 'ListComments', {issueRef});
1235
1236 dispatch({type: FETCH_COMMENTS_SUCCESS, comments: resp.comments});
1237 dispatch(fetchCommentReferences(
1238 resp.comments, issueRef.projectName));
1239
1240 const commenterRefs = (resp.comments || []).map(
1241 (comment) => comment.commenter);
1242 dispatch(userV0.fetchProjects(commenterRefs));
1243 } catch (error) {
1244 dispatch({type: FETCH_COMMENTS_FAILURE, error});
1245 };
1246};
1247
1248/**
1249 * Gets whether the logged in user has starred a given issue.
1250 * @param {IssueRef} issueRef
1251 * @return {function(function): Promise<void>}
1252 */
1253export const fetchIsStarred = (issueRef) => async (dispatch) => {
1254 dispatch({type: FETCH_IS_STARRED_START});
1255 try {
1256 const resp = await prpcClient.call(
1257 'monorail.Issues', 'IsIssueStarred', {issueRef},
1258 );
1259
1260 dispatch({
1261 type: FETCH_IS_STARRED_SUCCESS,
1262 starred: resp.isStarred,
1263 issueRef: issueRef,
1264 });
1265 } catch (error) {
1266 dispatch({type: FETCH_IS_STARRED_FAILURE, error});
1267 };
1268};
1269
1270/**
1271 * Fetch all of a logged in user's starred issues.
1272 * @return {function(function): Promise<void>}
1273 */
1274export const fetchStarredIssues = () => async (dispatch) => {
1275 dispatch({type: FETCH_ISSUES_STARRED_START});
1276
1277 try {
1278 const resp = await prpcClient.call(
1279 'monorail.Issues', 'ListStarredIssues', {},
1280 );
1281 dispatch({type: FETCH_ISSUES_STARRED_SUCCESS,
1282 starredIssueRefs: resp.starredIssueRefs});
1283 } catch (error) {
1284 dispatch({type: FETCH_ISSUES_STARRED_FAILURE, error});
1285 };
1286};
1287
1288/**
1289 * Stars or unstars an issue.
1290 * @param {IssueRef} issueRef The issue to star.
1291 * @param {boolean} starred Whether to star or unstar.
1292 * @return {function(function): Promise<void>}
1293 */
1294export const star = (issueRef, starred) => async (dispatch) => {
1295 const requestKey = issueRefToString(issueRef);
1296
1297 dispatch({type: STAR_START, requestKey});
1298 const message = {issueRef, starred};
1299
1300 try {
1301 const resp = await prpcClient.call(
1302 'monorail.Issues', 'StarIssue', message,
1303 );
1304
1305 dispatch({
1306 type: STAR_SUCCESS,
1307 starCount: resp.starCount,
1308 issueRef,
1309 starred,
1310 requestKey,
1311 });
1312 } catch (error) {
1313 dispatch({type: STAR_FAILURE, error, requestKey});
1314 }
1315};
1316
1317/**
1318 * Runs a presubmit request to find warnings to show the user before an issue
1319 * edit is saved.
1320 * @param {IssueRef} issueRef The issue being edited.
1321 * @param {IssueDelta} issueDelta The user's in flight changes to the issue.
1322 * @return {function(function): Promise<void>}
1323 */
1324export const presubmit = (issueRef, issueDelta) => async (dispatch) => {
1325 dispatch({type: PRESUBMIT_START});
1326
1327 try {
1328 const resp = await prpcClient.call(
1329 'monorail.Issues', 'PresubmitIssue', {issueRef, issueDelta});
1330
1331 dispatch({type: PRESUBMIT_SUCCESS, presubmitResponse: resp});
1332 } catch (error) {
1333 dispatch({type: PRESUBMIT_FAILURE, error: error});
1334 }
1335};
1336
1337/**
1338 * Async action creator to update an issue's approval.
1339 *
1340 * @param {Object} params Options for the approval update.
1341 * @param {IssueRef} params.issueRef
1342 * @param {FieldRef} params.fieldRef
1343 * @param {ApprovalDelta=} params.approvalDelta
1344 * @param {string=} params.commentContent
1345 * @param {boolean=} params.sendEmail
1346 * @param {boolean=} params.isDescription
1347 * @param {AttachmentUpload=} params.uploads
1348 * @return {function(function): Promise<void>}
1349 */
1350export const updateApproval = ({issueRef, fieldRef, approvalDelta,
1351 commentContent, sendEmail, isDescription, uploads}) => async (dispatch) => {
1352 dispatch({type: UPDATE_APPROVAL_START});
1353 try {
1354 const {approval} = await prpcClient.call(
1355 'monorail.Issues', 'UpdateApproval', {
1356 ...(issueRef && {issueRef}),
1357 ...(fieldRef && {fieldRef}),
1358 ...(approvalDelta && {approvalDelta}),
1359 ...(commentContent && {commentContent}),
1360 ...(sendEmail && {sendEmail}),
1361 ...(isDescription && {isDescription}),
1362 ...(uploads && {uploads}),
1363 });
1364
1365 dispatch({type: UPDATE_APPROVAL_SUCCESS, approval, issueRef});
1366 dispatch(fetch(issueRef));
1367 dispatch(fetchComments(issueRef));
1368 } catch (error) {
1369 dispatch({type: UPDATE_APPROVAL_FAILURE, error: error});
1370 };
1371};
1372
1373/**
1374 * Async action creator to update an issue.
1375 *
1376 * @param {Object} params Options for the issue update.
1377 * @param {IssueRef} params.issueRef
1378 * @param {IssueDelta=} params.delta
1379 * @param {string=} params.commentContent
1380 * @param {boolean=} params.sendEmail
1381 * @param {boolean=} params.isDescription
1382 * @param {AttachmentUpload=} params.uploads
1383 * @param {Array<number>=} params.keptAttachments
1384 * @return {function(function): Promise<void>}
1385 */
1386export const update = ({issueRef, delta, commentContent, sendEmail,
1387 isDescription, uploads, keptAttachments}) => async (dispatch) => {
1388 dispatch({type: UPDATE_START});
1389
1390 try {
1391 const {issue} = await prpcClient.call(
1392 'monorail.Issues', 'UpdateIssue', {issueRef, delta,
1393 commentContent, sendEmail, isDescription, uploads,
1394 keptAttachments});
1395
1396 dispatch({type: UPDATE_SUCCESS, issue});
1397 dispatch(fetchComments(issueRef));
1398 dispatch(fetchRelatedIssues(issue));
1399 dispatch(fetchReferencedUsers(issue));
1400 } catch (error) {
1401 dispatch({type: UPDATE_FAILURE, error: error});
1402 };
1403};
1404
1405/**
1406 * Converts an issue from one template to another. This is used for changing
1407 * launch issues.
1408 * @param {IssueRef} issueRef
1409 * @param {Object} options
1410 * @param {string=} options.templateName
1411 * @param {string=} options.commentContent
1412 * @param {boolean=} options.sendEmail
1413 * @return {function(function): Promise<void>}
1414 */
1415export const convert = (issueRef, {templateName = '',
1416 commentContent = '', sendEmail = true},
1417) => async (dispatch) => {
1418 dispatch({type: CONVERT_START});
1419
1420 try {
1421 const resp = await prpcClient.call(
1422 'monorail.Issues', 'ConvertIssueApprovalsTemplate',
1423 {issueRef, templateName, commentContent, sendEmail});
1424
1425 dispatch({type: CONVERT_SUCCESS, issue: resp.issue});
1426 const fetchCommentsMessage = {issueRef};
1427 dispatch(fetchComments(fetchCommentsMessage));
1428 } catch (error) {
1429 dispatch({type: CONVERT_FAILURE, error: error});
1430 };
1431};