groupStore.tsx 13 KB

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