groupStore.tsx 13 KB

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