groupStore.tsx 13 KB

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