groupStore.tsx 13 KB

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