groupStore.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. import {createStore} from 'reflux';
  2. import type {Indicator} from 'sentry/actionCreators/indicator';
  3. import {t} from 'sentry/locale';
  4. import IndicatorStore from 'sentry/stores/indicatorStore';
  5. import type {Activity, BaseGroup, Group, GroupStats} from 'sentry/types/group';
  6. import toArray from 'sentry/utils/array/toArray';
  7. import type RequestError from 'sentry/utils/requestError/requestError';
  8. import SelectedGroupStore from './selectedGroupStore';
  9. import type {StrictStoreDefinition} from './types';
  10. function showAlert(msg: string, type: Indicator['type']) {
  11. IndicatorStore.addMessage(msg, type, {duration: 4000});
  12. }
  13. type ChangeId = string;
  14. type Change = {
  15. data: any;
  16. itemIds: string[];
  17. };
  18. type Item = BaseGroup | Group;
  19. type ItemIds = string[] | undefined;
  20. interface InternalDefinition {
  21. addActivity: (groupId: string, data: Activity, index?: number) => void;
  22. indexOfActivity: (groupId: string, id: string) => number;
  23. /**
  24. * Does not include pending changes
  25. * TODO: Remove mutation and replace state with items
  26. */
  27. items: Item[];
  28. pendingChanges: Map<ChangeId, Change>;
  29. removeActivity: (groupId: string, id: string) => number;
  30. statuses: Record<string, Record<string, boolean>>;
  31. updateActivity: (groupId: string, id: string, data: Partial<Activity['data']>) => void;
  32. updateItems: (itemIds: ItemIds) => void;
  33. }
  34. interface GroupStoreDefinition extends StrictStoreDefinition<Item[]>, InternalDefinition {
  35. add: (items: Item[]) => void;
  36. addStatus: (id: string, status: string) => void;
  37. addToFront: (items: Item[]) => void;
  38. clearStatus: (id: string, status: string) => void;
  39. get: (id: string) => Readonly<Item> | undefined;
  40. getAllItemIds: () => string[];
  41. getAllItems: () => readonly Item[];
  42. hasStatus: (id: string, status: string) => boolean;
  43. init: () => void;
  44. itemIdsOrAll(itemIds: ItemIds): string[];
  45. loadInitialData: (items: Item[]) => void;
  46. mergeItems: (items: Item[]) => Item[];
  47. onAssignTo: (changeId: string, itemId: string, data: any) => void;
  48. onAssignToError: (changeId: string, itemId: string, error: RequestError) => void;
  49. onAssignToSuccess: (changeId: string, itemId: string, response: any) => void;
  50. onDelete: (changeId: string, itemIds: ItemIds) => void;
  51. onDeleteError: (changeId: string, itemIds: ItemIds, error: Error) => void;
  52. onDeleteSuccess: (changeId: string, itemIds: ItemIds, response: any) => void;
  53. onDiscard: (changeId: string, itemId: string) => void;
  54. onDiscardError: (changeId: string, itemId: string, response: any) => void;
  55. onDiscardSuccess: (changeId: string, itemId: string, response: any) => void;
  56. onMerge: (changeId: string, itemIds: ItemIds) => void;
  57. onMergeError: (changeId: string, itemIds: ItemIds, response: any) => void;
  58. onMergeSuccess: (changeId: string, itemIds: ItemIds, response: any) => void;
  59. onPopulateStats: (itemIds: ItemIds, response: GroupStats[]) => void;
  60. onUpdate: (changeId: string, itemIds: ItemIds, data: any) => void;
  61. onUpdateError: (changeId: string, itemIds: ItemIds, silent: boolean) => void;
  62. onUpdateSuccess: (changeId: string, itemIds: ItemIds, response: Partial<Group>) => void;
  63. remove: (itemIds: ItemIds) => void;
  64. reset: () => void;
  65. }
  66. function mergePendingChanges(
  67. items: readonly Item[],
  68. pendingChanges: Map<ChangeId, Change>
  69. ): readonly Item[] {
  70. // Merge pending changes into the existing group items. This gives the
  71. // apperance of optimistic updates
  72. const pendingById: Record<string, Change[]> = {};
  73. pendingChanges.forEach(change => {
  74. change.itemIds.forEach(itemId => {
  75. const existing = pendingById[itemId] ?? [];
  76. pendingById[itemId] = [...existing, change];
  77. });
  78. });
  79. // Merge pending changes into the item if it has them
  80. return items.map(item =>
  81. pendingById[item.id] === undefined
  82. ? item
  83. : {
  84. ...item,
  85. ...pendingById[item.id]!.reduce((a, change) => ({...a, ...change.data}), {}),
  86. }
  87. );
  88. }
  89. const storeConfig: GroupStoreDefinition = {
  90. pendingChanges: new Map(),
  91. items: [],
  92. state: [],
  93. statuses: {},
  94. init() {
  95. // XXX: Do not use `this.listenTo` in this store. We avoid usage of reflux
  96. // listeners due to their leaky nature in tests.
  97. this.reset();
  98. },
  99. reset() {
  100. this.pendingChanges = new Map();
  101. this.items = [];
  102. this.state = [];
  103. this.statuses = {};
  104. },
  105. loadInitialData(items) {
  106. this.reset();
  107. const itemIds = items.map(item => item.id);
  108. this.items = [...this.items, ...items];
  109. this.updateItems(itemIds);
  110. },
  111. updateItems(itemIds: ItemIds) {
  112. const idSet = new Set(itemIds);
  113. this.state = mergePendingChanges(this.items, this.pendingChanges);
  114. this.trigger(idSet);
  115. SelectedGroupStore.onGroupChange(idSet);
  116. },
  117. mergeItems(items: Item[]) {
  118. const itemsById = items.reduce((acc, item) => ({...acc, [item.id]: item}), {});
  119. // Merge these items into the store and return a mapping of any that aren't already in the store
  120. this.items.forEach((item, itemIndex) => {
  121. // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  122. if (itemsById[item.id]) {
  123. this.items[itemIndex] = {
  124. ...item,
  125. // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  126. ...itemsById[item.id],
  127. };
  128. // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  129. delete itemsById[item.id];
  130. }
  131. });
  132. return items.filter(item => itemsById.hasOwnProperty(item.id));
  133. },
  134. /**
  135. * Adds the provided items to the end of the list.
  136. * If any items already exist, they will merged into the existing item index.
  137. */
  138. add(items) {
  139. items = toArray(items);
  140. const newItems = this.mergeItems(items);
  141. this.items = [...this.items, ...newItems];
  142. this.updateItems(items.map(item => item.id));
  143. },
  144. /**
  145. * Adds the provided items to the front of the list.
  146. * If any items already exist, they will be moved to the front in the order provided.
  147. */
  148. addToFront(items) {
  149. items = toArray(items);
  150. const itemMap = items.reduce((acc, item) => ({...acc, [item.id]: item}), {});
  151. // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  152. this.items = [...items, ...this.items.filter(item => !itemMap[item.id])];
  153. this.updateItems(items.map(item => item.id));
  154. },
  155. /**
  156. * If itemIds is undefined, returns all ids in the store
  157. */
  158. itemIdsOrAll(itemIds: ItemIds) {
  159. return itemIds === undefined ? this.getAllItemIds() : itemIds;
  160. },
  161. remove(itemIds) {
  162. this.items = this.items.filter(item => !itemIds?.includes(item.id));
  163. this.updateItems(itemIds);
  164. },
  165. addStatus(id, status) {
  166. if (this.statuses[id] === undefined) {
  167. this.statuses[id] = {};
  168. }
  169. this.statuses[id][status] = true;
  170. },
  171. clearStatus(id, status) {
  172. if (this.statuses[id] === undefined) {
  173. return;
  174. }
  175. this.statuses[id][status] = false;
  176. },
  177. hasStatus(id, status) {
  178. return this.statuses[id]?.[status] || false;
  179. },
  180. indexOfActivity(groupId, id) {
  181. const group = this.items.find(item => item.id === groupId);
  182. if (!group) {
  183. return -1;
  184. }
  185. for (let i = 0; i < group.activity.length; i++) {
  186. if (group.activity[i]!.id === id) {
  187. return i;
  188. }
  189. }
  190. return -1;
  191. },
  192. addActivity(groupId, data, index = -1) {
  193. const group = this.items.find(item => item.id === groupId);
  194. if (!group) {
  195. return;
  196. }
  197. // insert into beginning by default
  198. if (index === -1) {
  199. group.activity.unshift(data);
  200. } else {
  201. group.activity.splice(index, 0, data);
  202. }
  203. if (data.type === 'note') {
  204. group.numComments++;
  205. }
  206. this.updateItems([groupId]);
  207. },
  208. updateActivity(groupId, id, data) {
  209. const group = this.items.find(item => item.id === groupId);
  210. if (!group) {
  211. return;
  212. }
  213. const index = this.indexOfActivity(groupId, id);
  214. if (index === -1) {
  215. return;
  216. }
  217. // Here, we want to merge the new `data` being passed in
  218. // into the existing `data` object. This effectively
  219. // allows passing in an object of only changes.
  220. group.activity[index]!.data = Object.assign(group.activity[index]!.data, data);
  221. this.updateItems([group.id]);
  222. },
  223. removeActivity(groupId, id) {
  224. const group = this.items.find(item => item.id === groupId);
  225. if (!group) {
  226. return -1;
  227. }
  228. const index = this.indexOfActivity(group.id, id);
  229. if (index === -1) {
  230. return -1;
  231. }
  232. const activity = group.activity.splice(index, 1);
  233. if (activity[0]!.type === 'note') {
  234. group.numComments--;
  235. }
  236. this.updateItems([group.id]);
  237. return index;
  238. },
  239. get(id) {
  240. return this.getAllItems().find(item => item.id === id);
  241. },
  242. getAllItemIds() {
  243. return this.items.map(item => item.id);
  244. },
  245. getAllItems() {
  246. return this.state;
  247. },
  248. getState() {
  249. return this.state;
  250. },
  251. onAssignTo(_changeId, itemId, _data) {
  252. this.addStatus(itemId, 'assignTo');
  253. this.updateItems([itemId]);
  254. },
  255. // TODO(dcramer): This is not really the best place for this
  256. onAssignToError(_changeId, itemId, error) {
  257. this.clearStatus(itemId, 'assignTo');
  258. if (error.responseJSON?.detail === 'Cannot assign to non-team member') {
  259. showAlert(t('Cannot assign to non-team member'), 'error');
  260. } else {
  261. showAlert(t('Unable to change assignee. Please try again.'), 'error');
  262. }
  263. },
  264. onAssignToSuccess(_changeId, itemId, response) {
  265. const idx = this.items.findIndex(i => i.id === itemId);
  266. if (idx === -1) {
  267. return;
  268. }
  269. this.items[idx] = {...this.items[idx]!, assignedTo: response.assignedTo};
  270. this.clearStatus(itemId, 'assignTo');
  271. this.updateItems([itemId]);
  272. },
  273. onDelete(_changeId, itemIds) {
  274. const ids = this.itemIdsOrAll(itemIds);
  275. ids.forEach(itemId => this.addStatus(itemId, 'delete'));
  276. this.updateItems(ids);
  277. },
  278. onDeleteError(_changeId, itemIds, _response) {
  279. showAlert(t('Unable to delete events. Please try again.'), 'error');
  280. if (!itemIds) {
  281. return;
  282. }
  283. itemIds.forEach(itemId => this.clearStatus(itemId, 'delete'));
  284. this.updateItems(itemIds);
  285. },
  286. onDeleteSuccess(_changeId, itemIds, _response) {
  287. const ids = this.itemIdsOrAll(itemIds);
  288. if (ids.length > 1) {
  289. showAlert(t('Deleted %d Issues', ids.length), 'success');
  290. } else {
  291. const shortId = ids.map(item => GroupStore.get(item)?.shortId).join('');
  292. showAlert(t('Deleted %s', shortId), 'success');
  293. }
  294. const itemIdSet = new Set(ids);
  295. ids.forEach(itemId => {
  296. delete this.statuses[itemId];
  297. this.clearStatus(itemId, 'delete');
  298. });
  299. this.items = this.items.filter(item => !itemIdSet.has(item.id));
  300. this.updateItems(ids);
  301. },
  302. onDiscard(_changeId, itemId) {
  303. this.addStatus(itemId, 'discard');
  304. this.updateItems([itemId]);
  305. },
  306. onDiscardError(_changeId, itemId, _response) {
  307. this.clearStatus(itemId, 'discard');
  308. showAlert(t('Unable to discard event. Please try again.'), 'error');
  309. this.updateItems([itemId]);
  310. },
  311. onDiscardSuccess(_changeId, itemId, _response) {
  312. delete this.statuses[itemId];
  313. this.clearStatus(itemId, 'discard');
  314. this.items = this.items.filter(item => item.id !== itemId);
  315. showAlert(t('Similar events will be filtered and discarded.'), 'success');
  316. this.updateItems([itemId]);
  317. },
  318. onMerge(_changeId, itemIds) {
  319. const ids = this.itemIdsOrAll(itemIds);
  320. ids.forEach(itemId => this.addStatus(itemId, 'merge'));
  321. // XXX(billy): Not sure if this is a bug or not but do we need to publish all itemIds?
  322. // Seems like we only need to publish parent id
  323. this.updateItems(ids);
  324. },
  325. onMergeError(_changeId, itemIds, _response) {
  326. const ids = this.itemIdsOrAll(itemIds);
  327. ids.forEach(itemId => this.clearStatus(itemId, 'merge'));
  328. showAlert(t('Unable to merge events. Please try again.'), 'error');
  329. this.updateItems(ids);
  330. },
  331. onMergeSuccess(_changeId, itemIds, response) {
  332. const ids = this.itemIdsOrAll(itemIds); // everything on page
  333. ids.forEach(itemId => this.clearStatus(itemId, 'merge'));
  334. // Remove all but parent id (items were merged into this one)
  335. const mergedIdSet = new Set(ids);
  336. // Looks like the `PUT /api/0/projects/:orgId/:projectId/issues/` endpoint
  337. // actually returns a 204, so there is no `response` body
  338. this.items = this.items.filter(
  339. item =>
  340. !mergedIdSet.has(item.id) ||
  341. (response?.merge && item.id === response.merge.parent)
  342. );
  343. if (ids.length > 0) {
  344. showAlert(t('Merged %d Issues', ids.length), 'success');
  345. }
  346. this.updateItems(ids);
  347. },
  348. onUpdate(changeId, itemIds, data) {
  349. const ids = this.itemIdsOrAll(itemIds);
  350. ids.forEach(itemId => {
  351. this.addStatus(itemId, 'update');
  352. });
  353. this.pendingChanges.set(changeId, {itemIds: ids, data});
  354. this.updateItems(ids);
  355. },
  356. onUpdateError(changeId, itemIds, failSilently) {
  357. const ids = this.itemIdsOrAll(itemIds);
  358. this.pendingChanges.delete(changeId);
  359. ids.forEach(itemId => this.clearStatus(itemId, 'update'));
  360. if (!failSilently) {
  361. showAlert(t('Unable to update events. Please try again.'), 'error');
  362. }
  363. this.updateItems(ids);
  364. },
  365. onUpdateSuccess(changeId, itemIds, response) {
  366. const ids = this.itemIdsOrAll(itemIds);
  367. this.items.forEach((item, idx) => {
  368. if (ids.includes(item.id)) {
  369. this.items[idx] = {
  370. ...item,
  371. ...response,
  372. };
  373. this.clearStatus(item.id, 'update');
  374. }
  375. });
  376. this.pendingChanges.delete(changeId);
  377. this.updateItems(ids);
  378. },
  379. onPopulateStats(itemIds, response) {
  380. // Organize stats by id
  381. const groupStatsMap = response.reduce<Record<string, GroupStats>>(
  382. (map, stats) => ({...map, [stats.id]: stats}),
  383. {}
  384. );
  385. this.items.forEach((item, idx) => {
  386. if (itemIds?.includes(item.id)) {
  387. this.items[idx] = {
  388. ...item,
  389. ...groupStatsMap[item.id],
  390. };
  391. }
  392. });
  393. this.updateItems(itemIds);
  394. },
  395. };
  396. const GroupStore = createStore(storeConfig);
  397. export default GroupStore;