groupStore.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  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 RequestError from 'sentry/utils/requestError/requestError';
  14. import toArray from 'sentry/utils/toArray';
  15. import SelectedGroupStore from './selectedGroupStore';
  16. import {CommonStoreDefinition} from './types';
  17. function showAlert(msg: string, type: Indicator['type']) {
  18. IndicatorStore.addMessage(msg, type, {duration: 4000});
  19. }
  20. type ChangeId = string;
  21. type Change = {
  22. data: any;
  23. itemIds: string[];
  24. };
  25. type Item = BaseGroup | Group | GroupCollapseRelease;
  26. type ItemIds = string[] | undefined;
  27. interface InternalDefinition {
  28. addActivity: (groupId: string, data: Activity, index?: number) => void;
  29. indexOfActivity: (groupId: string, id: string) => number;
  30. items: Item[];
  31. pendingChanges: Map<ChangeId, Change>;
  32. removeActivity: (groupId: string, id: string) => number;
  33. statuses: Record<string, Record<string, boolean>>;
  34. updateActivity: (groupId: string, id: string, data: Partial<Activity>) => void;
  35. updateItems: (itemIds: ItemIds) => void;
  36. }
  37. interface GroupStoreDefinition extends CommonStoreDefinition<Item[]>, InternalDefinition {
  38. add: (items: Item[]) => void;
  39. addStatus: (id: string, status: string) => void;
  40. addToFront: (items: Item[]) => void;
  41. clearStatus: (id: string, status: string) => void;
  42. get: (id: string) => Item | undefined;
  43. getAllItemIds: () => string[];
  44. getAllItems: () => Item[];
  45. hasStatus: (id: string, status: string) => boolean;
  46. init: () => void;
  47. itemIdsOrAll(itemIds: ItemIds): string[];
  48. loadInitialData: (items: Item[]) => void;
  49. onAssignTo: (changeId: string, itemId: string, data: any) => void;
  50. onAssignToError: (changeId: string, itemId: string, error: RequestError) => void;
  51. onAssignToSuccess: (changeId: string, itemId: string, response: any) => void;
  52. onDelete: (changeId: string, itemIds: ItemIds) => void;
  53. onDeleteError: (changeId: string, itemIds: ItemIds, error: Error) => void;
  54. onDeleteSuccess: (changeId: string, itemIds: ItemIds, response: any) => void;
  55. onDiscard: (changeId: string, itemId: string) => void;
  56. onDiscardError: (changeId: string, itemId: string, response: any) => void;
  57. onDiscardSuccess: (changeId: string, itemId: string, response: any) => void;
  58. onMerge: (changeId: string, itemIds: ItemIds) => void;
  59. onMergeError: (changeId: string, itemIds: ItemIds, response: any) => void;
  60. onMergeSuccess: (changeId: string, itemIds: ItemIds, response: any) => void;
  61. onPopulateReleases: (itemId: string, releaseData: GroupRelease) => void;
  62. onPopulateStats: (itemIds: ItemIds, response: GroupStats[]) => void;
  63. onUpdate: (changeId: string, itemIds: ItemIds, data: any) => void;
  64. onUpdateError: (changeId: string, itemIds: ItemIds, silent: boolean) => void;
  65. onUpdateSuccess: (changeId: string, itemIds: ItemIds, response: Partial<Group>) => void;
  66. remove: (itemIds: ItemIds) => void;
  67. reset: () => void;
  68. }
  69. const storeConfig: GroupStoreDefinition = {
  70. pendingChanges: new Map(),
  71. items: [],
  72. statuses: {},
  73. init() {
  74. // XXX: Do not use `this.listenTo` in this store. We avoid usage of reflux
  75. // listeners due to their leaky nature in tests.
  76. this.reset();
  77. },
  78. reset() {
  79. this.pendingChanges = new Map();
  80. this.items = [];
  81. this.statuses = {};
  82. },
  83. // TODO(dcramer): this should actually come from an action of some sorts
  84. loadInitialData(items) {
  85. this.reset();
  86. const itemIds = new Set<string>();
  87. items.forEach(item => {
  88. itemIds.add(item.id);
  89. this.items.push(item);
  90. });
  91. this.trigger(itemIds);
  92. },
  93. updateItems(itemIds: ItemIds) {
  94. const idSet = new Set(itemIds);
  95. this.trigger(idSet);
  96. SelectedGroupStore.onGroupChange(idSet);
  97. },
  98. mergeItems(items: Item[]) {
  99. const itemsById = items.reduce((acc, item) => ({...acc, [item.id]: item}), {});
  100. // Merge these items into the store and return a mapping of any that aren't already in the store
  101. this.items.forEach((item, itemIndex) => {
  102. if (itemsById[item.id]) {
  103. this.items[itemIndex] = {
  104. ...item,
  105. ...itemsById[item.id],
  106. };
  107. delete itemsById[item.id];
  108. }
  109. });
  110. return items.filter(item => itemsById.hasOwnProperty(item.id));
  111. },
  112. /**
  113. * Adds the provided items to the end of the list.
  114. * If any items already exist, they will merged into the existing item index.
  115. */
  116. add(items) {
  117. items = toArray(items);
  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. items = toArray(items);
  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. if (error.responseJSON?.detail === 'Cannot assign to non-team member') {
  253. showAlert(t('Cannot assign to non-team member'), 'error');
  254. } else {
  255. showAlert(t('Unable to change assignee. Please try again.'), 'error');
  256. }
  257. },
  258. onAssignToSuccess(_changeId, itemId, response) {
  259. const idx = this.items.findIndex(i => i.id === itemId);
  260. if (idx === -1) {
  261. return;
  262. }
  263. this.items[idx] = {...this.items[idx], assignedTo: response.assignedTo};
  264. this.clearStatus(itemId, 'assignTo');
  265. this.updateItems([itemId]);
  266. },
  267. onDelete(_changeId, itemIds) {
  268. const ids = this.itemIdsOrAll(itemIds);
  269. ids.forEach(itemId => this.addStatus(itemId, 'delete'));
  270. this.updateItems(ids);
  271. },
  272. onDeleteError(_changeId, itemIds, _response) {
  273. showAlert(t('Unable to delete events. Please try again.'), 'error');
  274. if (!itemIds) {
  275. return;
  276. }
  277. itemIds.forEach(itemId => this.clearStatus(itemId, 'delete'));
  278. this.updateItems(itemIds);
  279. },
  280. onDeleteSuccess(_changeId, itemIds, _response) {
  281. const ids = this.itemIdsOrAll(itemIds);
  282. if (ids.length > 1) {
  283. showAlert(t('Deleted %d Issues', ids.length), 'success');
  284. } else {
  285. const shortId = ids.map(item => GroupStore.get(item)?.shortId).join('');
  286. showAlert(t('Deleted %s', shortId), 'success');
  287. }
  288. const itemIdSet = new Set(ids);
  289. ids.forEach(itemId => {
  290. delete this.statuses[itemId];
  291. this.clearStatus(itemId, 'delete');
  292. });
  293. this.items = this.items.filter(item => !itemIdSet.has(item.id));
  294. this.updateItems(ids);
  295. },
  296. onDiscard(_changeId, itemId) {
  297. this.addStatus(itemId, 'discard');
  298. this.updateItems([itemId]);
  299. },
  300. onDiscardError(_changeId, itemId, _response) {
  301. this.clearStatus(itemId, 'discard');
  302. showAlert(t('Unable to discard event. Please try again.'), 'error');
  303. this.updateItems([itemId]);
  304. },
  305. onDiscardSuccess(_changeId, itemId, _response) {
  306. delete this.statuses[itemId];
  307. this.clearStatus(itemId, 'discard');
  308. this.items = this.items.filter(item => item.id !== itemId);
  309. showAlert(t('Similar events will be filtered and discarded.'), 'success');
  310. this.updateItems([itemId]);
  311. },
  312. onMerge(_changeId, itemIds) {
  313. const ids = this.itemIdsOrAll(itemIds);
  314. ids.forEach(itemId => this.addStatus(itemId, 'merge'));
  315. // XXX(billy): Not sure if this is a bug or not but do we need to publish all itemIds?
  316. // Seems like we only need to publish parent id
  317. this.updateItems(ids);
  318. },
  319. onMergeError(_changeId, itemIds, _response) {
  320. const ids = this.itemIdsOrAll(itemIds);
  321. ids.forEach(itemId => this.clearStatus(itemId, 'merge'));
  322. showAlert(t('Unable to merge events. Please try again.'), 'error');
  323. this.updateItems(ids);
  324. },
  325. onMergeSuccess(_changeId, itemIds, response) {
  326. const ids = this.itemIdsOrAll(itemIds); // everything on page
  327. ids.forEach(itemId => this.clearStatus(itemId, 'merge'));
  328. // Remove all but parent id (items were merged into this one)
  329. const mergedIdSet = new Set(ids);
  330. // Looks like the `PUT /api/0/projects/:orgId/:projectId/issues/` endpoint
  331. // actually returns a 204, so there is no `response` body
  332. this.items = this.items.filter(
  333. item =>
  334. !mergedIdSet.has(item.id) ||
  335. (response && response.merge && item.id === response.merge.parent)
  336. );
  337. if (ids.length > 0) {
  338. showAlert(t('Merged %d Issues', ids.length), 'success');
  339. }
  340. this.updateItems(ids);
  341. },
  342. onUpdate(changeId, itemIds, data) {
  343. const ids = this.itemIdsOrAll(itemIds);
  344. ids.forEach(itemId => {
  345. this.addStatus(itemId, 'update');
  346. });
  347. this.pendingChanges.set(changeId, {itemIds: ids, data});
  348. this.updateItems(ids);
  349. },
  350. onUpdateError(changeId, itemIds, failSilently) {
  351. const ids = this.itemIdsOrAll(itemIds);
  352. this.pendingChanges.delete(changeId);
  353. ids.forEach(itemId => this.clearStatus(itemId, 'update'));
  354. if (!failSilently) {
  355. showAlert(t('Unable to update events. Please try again.'), 'error');
  356. }
  357. this.updateItems(ids);
  358. },
  359. onUpdateSuccess(changeId, itemIds, response) {
  360. const ids = this.itemIdsOrAll(itemIds);
  361. this.items.forEach((item, idx) => {
  362. if (ids.includes(item.id)) {
  363. this.items[idx] = {
  364. ...item,
  365. ...response,
  366. };
  367. this.clearStatus(item.id, 'update');
  368. }
  369. });
  370. this.pendingChanges.delete(changeId);
  371. this.updateItems(ids);
  372. },
  373. onPopulateStats(itemIds, response) {
  374. // Organize stats by id
  375. const groupStatsMap = response.reduce<Record<string, GroupStats>>(
  376. (map, stats) => ({...map, [stats.id]: stats}),
  377. {}
  378. );
  379. this.items.forEach((item, idx) => {
  380. if (itemIds?.includes(item.id)) {
  381. this.items[idx] = {
  382. ...item,
  383. ...groupStatsMap[item.id],
  384. };
  385. }
  386. });
  387. this.updateItems(itemIds);
  388. },
  389. onPopulateReleases(itemId, releaseData) {
  390. this.items.forEach((item, idx) => {
  391. if (item.id === itemId) {
  392. this.items[idx] = {
  393. ...item,
  394. ...releaseData,
  395. };
  396. }
  397. });
  398. this.updateItems([itemId]);
  399. },
  400. };
  401. const GroupStore = createStore(storeConfig);
  402. export default GroupStore;