groupStore.tsx 13 KB

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