groupStore.tsx 12 KB

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