thresholdGroupRows.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. import {Fragment, useMemo, useState} from 'react';
  2. import styled from '@emotion/styled';
  3. import capitalize from 'lodash/capitalize';
  4. import moment from 'moment';
  5. import {APIRequestMethod} from 'sentry/api';
  6. import {Button} from 'sentry/components/button';
  7. import {CompactSelect} from 'sentry/components/compactSelect';
  8. import ProjectBadge from 'sentry/components/idBadge/projectBadge';
  9. import Input from 'sentry/components/input';
  10. import {IconAdd, IconClose, IconDelete, IconEdit} from 'sentry/icons';
  11. import {t} from 'sentry/locale';
  12. import {space} from 'sentry/styles/space';
  13. import {Environment, Project} from 'sentry/types';
  14. import {getExactDuration, parseLargestSuffix} from 'sentry/utils/formatters';
  15. import useApi from 'sentry/utils/useApi';
  16. import {Threshold} from '../utils/types';
  17. const NEW_THRESHOLD_PREFIX = 'newthreshold';
  18. type Props = {
  19. columns: number;
  20. orgSlug: string;
  21. refetch: () => void;
  22. setError: (msg: string) => void;
  23. thresholds: Threshold[];
  24. };
  25. type EditingThreshold = {
  26. environment: Environment;
  27. id: string;
  28. project: Project;
  29. threshold_type: string;
  30. trigger_type: string;
  31. value: number;
  32. windowSuffix: moment.unitOfTime.DurationConstructor;
  33. windowValue: number;
  34. date_added?: string;
  35. hasError?: boolean;
  36. window_in_seconds?: number;
  37. };
  38. export function ThresholdGroupRows({
  39. thresholds,
  40. columns,
  41. orgSlug,
  42. refetch,
  43. setError,
  44. }: Props) {
  45. const [editingThresholds, setEditingThresholds] = useState<{
  46. [key: string]: EditingThreshold;
  47. }>({});
  48. const [newThresholdIterator, setNewThresholdIterator] = useState<number>(0); // used simply to initialize new threshold
  49. const api = useApi();
  50. const project = thresholds[0].project;
  51. const environment = thresholds[0].environment;
  52. const defaultWindow = thresholds[0].window_in_seconds;
  53. const thresholdsById: {[id: string]: Threshold} = useMemo(() => {
  54. const byId = {};
  55. thresholds.forEach(threshold => {
  56. byId[threshold.id] = threshold;
  57. });
  58. return byId;
  59. }, [thresholds]);
  60. const thresholdIdSet = useMemo(() => {
  61. return new Set([
  62. ...thresholds.map(threshold => threshold.id),
  63. ...Object.keys(editingThresholds),
  64. ]);
  65. }, [thresholds, editingThresholds]);
  66. const initializeNewThreshold = () => {
  67. const thresholdId = `${NEW_THRESHOLD_PREFIX}-${newThresholdIterator}`;
  68. const [windowValue, windowSuffix] = parseLargestSuffix(defaultWindow);
  69. const newThreshold: EditingThreshold = {
  70. id: thresholdId,
  71. project,
  72. environment,
  73. windowValue,
  74. windowSuffix,
  75. threshold_type: 'total_error_count',
  76. trigger_type: 'over',
  77. value: 0,
  78. hasError: false,
  79. };
  80. const updatedEditingThresholds = {...editingThresholds};
  81. updatedEditingThresholds[thresholdId] = newThreshold;
  82. setEditingThresholds(updatedEditingThresholds);
  83. setNewThresholdIterator(newThresholdIterator + 1);
  84. };
  85. const enableEditThreshold = thresholdId => {
  86. const updatedEditingThresholds = {...editingThresholds};
  87. const threshold = JSON.parse(JSON.stringify(thresholdsById[thresholdId]));
  88. const [windowValue, windowSuffix] = parseLargestSuffix(threshold.window_in_seconds);
  89. updatedEditingThresholds[thresholdId] = {
  90. ...threshold,
  91. windowValue,
  92. windowSuffix,
  93. hasError: false,
  94. };
  95. setEditingThresholds(updatedEditingThresholds);
  96. };
  97. const saveThreshold = (thresholdIds: string[]) => {
  98. thresholdIds.forEach(id => {
  99. const thresholdData = editingThresholds[id];
  100. const seconds = moment
  101. .duration(thresholdData.windowValue, thresholdData.windowSuffix)
  102. .as('seconds');
  103. const submitData = {
  104. ...thresholdData,
  105. window_in_seconds: seconds,
  106. environment: thresholdData.environment.name, // api expects environment as a string
  107. };
  108. let path = `/projects/${orgSlug}/${thresholdData.project.slug}/release-thresholds/${id}/`;
  109. let method: APIRequestMethod = 'PUT';
  110. if (id.includes(NEW_THRESHOLD_PREFIX)) {
  111. path = `/projects/${orgSlug}/${thresholdData.project.slug}/release-thresholds/`;
  112. method = 'POST';
  113. }
  114. const request = api.requestPromise(path, {
  115. method,
  116. data: submitData,
  117. });
  118. request
  119. .then(() => {
  120. refetch();
  121. closeEditForm(id);
  122. })
  123. .catch(_err => {
  124. setError('Issue saving threshold');
  125. setEditingThresholds(prevState => {
  126. const errorThreshold = {
  127. ...submitData,
  128. hasError: true,
  129. environment: thresholdData.environment, // convert local state environment back to object
  130. };
  131. const updatedEditingThresholds = {...prevState};
  132. updatedEditingThresholds[id] = errorThreshold;
  133. return updatedEditingThresholds;
  134. });
  135. });
  136. });
  137. };
  138. const deleteThreshold = thresholdId => {
  139. const updatedEditingThresholds = {...editingThresholds};
  140. const thresholdData = editingThresholds[thresholdId];
  141. const path = `/projects/${orgSlug}/${thresholdData.project.slug}/release-thresholds/${thresholdId}/`;
  142. const method = 'DELETE';
  143. if (!thresholdId.includes(NEW_THRESHOLD_PREFIX)) {
  144. const request = api.requestPromise(path, {
  145. method,
  146. });
  147. request
  148. .then(() => {
  149. refetch();
  150. })
  151. .catch(_err => {
  152. setError('Issue deleting threshold');
  153. const errorThreshold = {
  154. ...thresholdData,
  155. hasError: true,
  156. };
  157. updatedEditingThresholds[thresholdId] = errorThreshold as EditingThreshold;
  158. setEditingThresholds(updatedEditingThresholds);
  159. });
  160. }
  161. delete updatedEditingThresholds[thresholdId];
  162. setEditingThresholds(updatedEditingThresholds);
  163. };
  164. const closeEditForm = thresholdId => {
  165. const updatedEditingThresholds = {...editingThresholds};
  166. delete updatedEditingThresholds[thresholdId];
  167. setEditingThresholds(updatedEditingThresholds);
  168. };
  169. const editThresholdState = (thresholdId, key, value) => {
  170. if (editingThresholds[thresholdId]) {
  171. const updateEditing = JSON.parse(JSON.stringify(editingThresholds));
  172. updateEditing[thresholdId][key] = value;
  173. setEditingThresholds(updateEditing);
  174. }
  175. };
  176. return (
  177. <StyledThresholdGroup columns={columns}>
  178. {Array.from(thresholdIdSet).map((tId: string, idx: number) => {
  179. const threshold = editingThresholds[tId] || thresholdsById[tId];
  180. return (
  181. <StyledRow
  182. key={threshold.id}
  183. lastRow={idx === thresholdIdSet.size - 1}
  184. hasError={threshold.hasError}
  185. >
  186. <FlexCenter style={{borderBottom: 0}}>
  187. {idx === 0 ? (
  188. <ProjectBadge
  189. project={threshold.project}
  190. avatarSize={16}
  191. hideOverflow
  192. disableLink
  193. />
  194. ) : (
  195. ''
  196. )}
  197. </FlexCenter>
  198. <FlexCenter style={{borderBottom: 0}}>
  199. {idx === 0 ? threshold.environment.name || 'None' : ''}
  200. </FlexCenter>
  201. {/* FOLLOWING COLUMNS ARE EDITABLE */}
  202. {editingThresholds[threshold.id] ? (
  203. <Fragment>
  204. <FlexCenter>
  205. <Input
  206. style={{width: '50%'}}
  207. value={threshold.windowValue}
  208. type="number"
  209. min={0}
  210. onChange={e =>
  211. editThresholdState(threshold.id, 'windowValue', e.target.value)
  212. }
  213. />
  214. <CompactSelect
  215. style={{width: '50%'}}
  216. value={threshold.windowSuffix}
  217. onChange={selectedOption =>
  218. editThresholdState(
  219. threshold.id,
  220. 'windowSuffix',
  221. selectedOption.value
  222. )
  223. }
  224. options={[
  225. {
  226. value: 'seconds',
  227. textValue: 'seconds',
  228. label: 's',
  229. },
  230. {
  231. value: 'minutes',
  232. textValue: 'minutes',
  233. label: 'min',
  234. },
  235. {
  236. value: 'hours',
  237. textValue: 'hours',
  238. label: 'hrs',
  239. },
  240. {
  241. value: 'days',
  242. textValue: 'days',
  243. label: 'days',
  244. },
  245. ]}
  246. />
  247. </FlexCenter>
  248. <FlexCenter>
  249. <CompactSelect
  250. value={threshold.threshold_type}
  251. onChange={selectedOption =>
  252. editThresholdState(
  253. threshold.id,
  254. 'threshold_type',
  255. selectedOption.value
  256. )
  257. }
  258. options={[
  259. {
  260. value: 'total_error_count',
  261. textValue: 'Errors',
  262. label: 'Error Count',
  263. },
  264. ]}
  265. />
  266. {threshold.trigger_type === 'over' ? (
  267. <Button
  268. onClick={() =>
  269. editThresholdState(threshold.id, 'trigger_type', 'under')
  270. }
  271. >
  272. &gt;
  273. </Button>
  274. ) : (
  275. <Button
  276. onClick={() =>
  277. editThresholdState(threshold.id, 'trigger_type', 'over')
  278. }
  279. >
  280. &lt;
  281. </Button>
  282. )}
  283. <Input
  284. value={threshold.value}
  285. type="number"
  286. min={0}
  287. onChange={e =>
  288. editThresholdState(threshold.id, 'value', e.target.value)
  289. }
  290. />
  291. </FlexCenter>
  292. </Fragment>
  293. ) : (
  294. <Fragment>
  295. <FlexCenter>
  296. {getExactDuration(threshold.window_in_seconds || 0, false, 'seconds')}
  297. </FlexCenter>
  298. <FlexCenter>
  299. <div>
  300. {threshold.threshold_type
  301. .split('_')
  302. .map(word => capitalize(word))
  303. .join(' ')}
  304. </div>
  305. <div>&nbsp;{threshold.trigger_type === 'over' ? '>' : '<'}&nbsp;</div>
  306. <div>{threshold.value}</div>
  307. </FlexCenter>
  308. </Fragment>
  309. )}
  310. {/* END OF EDITABLE COLUMNS */}
  311. <ActionsColumn>
  312. {editingThresholds[threshold.id] ? (
  313. <Fragment>
  314. <Button size="xs" onClick={() => saveThreshold([threshold.id])}>
  315. Save
  316. </Button>
  317. {!threshold.id.includes(NEW_THRESHOLD_PREFIX) && (
  318. <Button
  319. aria-label={t('Delete threshold')}
  320. borderless
  321. icon={<IconDelete color="danger" />}
  322. onClick={() => deleteThreshold(threshold.id)}
  323. size="xs"
  324. />
  325. )}
  326. <Button
  327. aria-label={t('Close')}
  328. borderless
  329. icon={<IconClose />}
  330. onClick={() => closeEditForm(threshold.id)}
  331. size="xs"
  332. />
  333. </Fragment>
  334. ) : (
  335. <Button
  336. aria-label={t('Edit threshold')}
  337. borderless
  338. icon={<IconEdit />}
  339. onClick={() => enableEditThreshold(threshold.id)}
  340. size="xs"
  341. />
  342. )}
  343. </ActionsColumn>
  344. </StyledRow>
  345. );
  346. })}
  347. <NewRowBtn
  348. aria-label={t('Add new row')}
  349. borderless
  350. icon={<IconAdd color="activeText" isCircled />}
  351. onClick={initializeNewThreshold}
  352. size="xs"
  353. />
  354. </StyledThresholdGroup>
  355. );
  356. }
  357. type StyledThresholdGroupProps = {
  358. columns: number;
  359. };
  360. const StyledThresholdGroup = styled('div')<StyledThresholdGroupProps>`
  361. display: contents;
  362. `;
  363. type StyledThresholdRowProps = {
  364. lastRow: boolean;
  365. hasError?: boolean;
  366. };
  367. const StyledRow = styled('div')<StyledThresholdRowProps>`
  368. display: contents;
  369. > * {
  370. padding: ${space(2)};
  371. border-bottom: ${p => (p.lastRow ? 0 : '1px solid ' + p.theme.border)};
  372. background-color: ${p =>
  373. p.hasError ? 'rgba(255, 0, 0, 0.1)' : 'rgba(255, 255, 255, 0)'};
  374. }
  375. `;
  376. const NewRowBtn = styled(Button)`
  377. display: flex;
  378. grid-column-start: 3;
  379. grid-column-end: -1;
  380. align-items: center;
  381. justify-content: center;
  382. background: ${p => p.theme.backgroundSecondary};
  383. border-radius: 0;
  384. `;
  385. const FlexCenter = styled('div')`
  386. display: flex;
  387. align-items: center;
  388. > * {
  389. margin: 0 ${space(1)};
  390. }
  391. `;
  392. const ActionsColumn = styled('div')`
  393. display: flex;
  394. align-items: center;
  395. justify-content: space-around;
  396. `;