groupStore.tsx 14 KB

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