groupStore.tsx 13 KB

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