groupStore.tsx 13 KB

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