onDemandBudgetEditModal.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. import {Component, Fragment} from 'react';
  2. import styled from '@emotion/styled';
  3. import {addErrorMessage, addSuccessMessage} from 'sentry/actionCreators/indicator';
  4. import type {ModalRenderProps} from 'sentry/actionCreators/modal';
  5. import type {Client} from 'sentry/api';
  6. import {Button} from 'sentry/components/button';
  7. import ButtonBar from 'sentry/components/buttonBar';
  8. import {Alert} from 'sentry/components/core/alert';
  9. import {Input} from 'sentry/components/core/input';
  10. import {t} from 'sentry/locale';
  11. import {space} from 'sentry/styles/space';
  12. import type {Organization} from 'sentry/types/organization';
  13. import withApi from 'sentry/utils/withApi';
  14. import SubscriptionStore from 'getsentry/stores/subscriptionStore';
  15. import type {OnDemandBudgets, Subscription} from 'getsentry/types';
  16. import {OnDemandBudgetMode, PlanTier} from 'getsentry/types';
  17. import OnDemandBudgetEdit from './onDemandBudgetEdit';
  18. import {
  19. convertOnDemandBudget,
  20. exceedsInvoicedBudgetLimit,
  21. getTotalBudget,
  22. normalizeOnDemandBudget,
  23. parseOnDemandBudgetsFromSubscription,
  24. trackOnDemandBudgetAnalytics,
  25. } from './utils';
  26. const ONDEMAND_BUDGET_SAVE_ERROR = t('Unable to save your on-demand budgets.');
  27. const PAYG_BUDGET_SAVE_ERROR = t('Unable to save your pay-as-you-go budget.');
  28. const ONDEMAND_BUDGET_EXCEEDS_INVOICED_LIMIT = t(
  29. 'Your on-demand budget cannot exceed 5 times your monthly plan price.'
  30. );
  31. const PAYG_BUDGET_EXCEEDS_INVOICED_LIMIT = t(
  32. 'Your pay-as-you-go budget cannot exceed 5 times your monthly plan price.'
  33. );
  34. function coerceValue(value: number): number {
  35. return value / 100;
  36. }
  37. function parseInputValue(e: React.ChangeEvent<HTMLInputElement>) {
  38. let value = parseInt(e.target.value, 10) || 0;
  39. value = Math.max(value, 0);
  40. const cents = value * 100;
  41. return cents;
  42. }
  43. type Props = {
  44. api: Client;
  45. organization: Organization;
  46. subscription: Subscription;
  47. } & ModalRenderProps;
  48. type State = {
  49. currentOnDemandBudget: OnDemandBudgets;
  50. onDemandBudget: OnDemandBudgets;
  51. updateError: undefined | Error | string | Record<string, string[]>;
  52. };
  53. class OnDemandBudgetEditModal extends Component<Props, State> {
  54. constructor(props: Props) {
  55. super(props);
  56. const {subscription} = props;
  57. const onDemandBudget = parseOnDemandBudgetsFromSubscription(subscription);
  58. this.state = {
  59. currentOnDemandBudget: {...onDemandBudget},
  60. onDemandBudget,
  61. updateError: undefined,
  62. };
  63. }
  64. renderError(error: State['updateError']) {
  65. if (!error) {
  66. return null;
  67. }
  68. if (!(error instanceof Error) && typeof error === 'object') {
  69. const listOfErrors = Object.entries(error).map(
  70. ([field, errors]: [string, string[]]) => {
  71. return (
  72. <li key={field}>
  73. <strong>{field}</strong> {errors.join(' ')}
  74. </li>
  75. );
  76. }
  77. );
  78. if (listOfErrors.length === 0) {
  79. return (
  80. <Alert system type="error" showIcon>
  81. {ONDEMAND_BUDGET_SAVE_ERROR}
  82. </Alert>
  83. );
  84. }
  85. return (
  86. <Alert system type="error" showIcon>
  87. <ul>{listOfErrors}</ul>
  88. </Alert>
  89. );
  90. }
  91. return (
  92. <Alert system type="error" showIcon>
  93. {/* TODO(TS): Type says error might be an object */}
  94. {error as React.ReactNode}
  95. </Alert>
  96. );
  97. }
  98. getTotalBudget = (): number => {
  99. const {onDemandBudget} = this.state;
  100. return getTotalBudget(onDemandBudget);
  101. };
  102. setBudgetMode = (nextMode: OnDemandBudgetMode) => {
  103. const {currentOnDemandBudget, onDemandBudget} = this.state;
  104. if (nextMode === onDemandBudget.budgetMode) {
  105. return;
  106. }
  107. this.setState({
  108. onDemandBudget: convertOnDemandBudget(currentOnDemandBudget, nextMode),
  109. });
  110. };
  111. handleSave = () => {
  112. const {subscription} = this.props;
  113. const newOnDemandBudget = normalizeOnDemandBudget(this.state.onDemandBudget);
  114. if (exceedsInvoicedBudgetLimit(subscription, newOnDemandBudget)) {
  115. const message =
  116. subscription.planTier === PlanTier.AM3
  117. ? PAYG_BUDGET_EXCEEDS_INVOICED_LIMIT
  118. : ONDEMAND_BUDGET_EXCEEDS_INVOICED_LIMIT;
  119. this.setState({
  120. updateError: message,
  121. });
  122. addErrorMessage(message);
  123. return;
  124. }
  125. this.saveOnDemandBudget(newOnDemandBudget).then(saveSuccess => {
  126. if (saveSuccess) {
  127. const {organization} = this.props;
  128. trackOnDemandBudgetAnalytics(
  129. organization,
  130. this.state.currentOnDemandBudget,
  131. newOnDemandBudget,
  132. 'ondemand_budget_modal'
  133. );
  134. if (this.getTotalBudget() > 0) {
  135. addSuccessMessage(t('Budget updated'));
  136. } else {
  137. addSuccessMessage(t('Budget turned off'));
  138. }
  139. this.props.closeModal();
  140. }
  141. });
  142. };
  143. saveOnDemandBudget = async (ondemandBudget: OnDemandBudgets): Promise<boolean> => {
  144. const {subscription} = this.props;
  145. try {
  146. await this.props.api.requestPromise(
  147. `/customers/${subscription.slug}/ondemand-budgets/`,
  148. {
  149. method: 'POST',
  150. data: ondemandBudget,
  151. }
  152. );
  153. SubscriptionStore.loadData(subscription.slug);
  154. return true;
  155. } catch (response) {
  156. const updateError =
  157. (response?.responseJSON ?? subscription.planTier === PlanTier.AM3)
  158. ? PAYG_BUDGET_SAVE_ERROR
  159. : ONDEMAND_BUDGET_SAVE_ERROR;
  160. this.setState({
  161. updateError,
  162. });
  163. addErrorMessage(
  164. subscription.planTier === PlanTier.AM3
  165. ? PAYG_BUDGET_SAVE_ERROR
  166. : ONDEMAND_BUDGET_SAVE_ERROR
  167. );
  168. return false;
  169. }
  170. };
  171. renderInputFields = (displayBudgetMode: OnDemandBudgetMode) => {
  172. const {onDemandBudget} = this.state;
  173. if (
  174. onDemandBudget.budgetMode === OnDemandBudgetMode.SHARED &&
  175. displayBudgetMode === OnDemandBudgetMode.SHARED
  176. ) {
  177. return (
  178. <InputFields style={{alignSelf: 'center'}}>
  179. <Currency>
  180. <OnDemandInput
  181. aria-label="shared max budget input"
  182. name="sharedMaxBudget"
  183. type="text"
  184. inputMode="numeric"
  185. pattern="[0-9]*"
  186. maxLength={7}
  187. placeholder="e.g. 50"
  188. value={coerceValue(onDemandBudget.sharedMaxBudget)}
  189. onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
  190. this.setState({
  191. onDemandBudget: {
  192. ...onDemandBudget,
  193. sharedMaxBudget: parseInputValue(e),
  194. },
  195. });
  196. }}
  197. />
  198. </Currency>
  199. </InputFields>
  200. );
  201. }
  202. if (
  203. onDemandBudget.budgetMode === OnDemandBudgetMode.PER_CATEGORY &&
  204. displayBudgetMode === OnDemandBudgetMode.PER_CATEGORY
  205. ) {
  206. return (
  207. <InputFields>
  208. <DetailTitle style={{marginTop: 0}}>{t('Errors')}</DetailTitle>
  209. <Currency>
  210. <OnDemandInput
  211. aria-label="errors budget input"
  212. name="errorsBudget"
  213. type="text"
  214. inputMode="numeric"
  215. pattern="[0-9]*"
  216. maxLength={7}
  217. placeholder="e.g. 50"
  218. value={coerceValue(onDemandBudget.errorsBudget)}
  219. onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
  220. this.setState({
  221. onDemandBudget: {
  222. ...onDemandBudget,
  223. errorsBudget: parseInputValue(e),
  224. },
  225. });
  226. }}
  227. />
  228. </Currency>
  229. <DetailTitle>{t('Transactions')}</DetailTitle>
  230. <Currency>
  231. <OnDemandInput
  232. aria-label="transactions budget input"
  233. name="transactionsBudget"
  234. type="text"
  235. inputMode="numeric"
  236. pattern="[0-9]*"
  237. maxLength={7}
  238. placeholder="e.g. 50"
  239. value={coerceValue(onDemandBudget.transactionsBudget)}
  240. onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
  241. this.setState({
  242. onDemandBudget: {
  243. ...onDemandBudget,
  244. transactionsBudget: parseInputValue(e),
  245. },
  246. });
  247. }}
  248. />
  249. </Currency>
  250. <DetailTitle>{t('Attachments')}</DetailTitle>
  251. <Currency>
  252. <OnDemandInput
  253. aria-label="attachments budget input"
  254. name="attachmentsBudget"
  255. type="text"
  256. inputMode="numeric"
  257. pattern="[0-9]*"
  258. maxLength={7}
  259. placeholder="e.g. 50"
  260. value={coerceValue(onDemandBudget.attachmentsBudget)}
  261. onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
  262. this.setState({
  263. onDemandBudget: {
  264. ...onDemandBudget,
  265. attachmentsBudget: parseInputValue(e),
  266. },
  267. });
  268. }}
  269. />
  270. </Currency>
  271. </InputFields>
  272. );
  273. }
  274. return null;
  275. };
  276. render() {
  277. const {Header, Footer, subscription, organization} = this.props;
  278. const onDemandBudgets = subscription.onDemandBudgets!;
  279. return (
  280. <Fragment>
  281. <Header closeButton>
  282. <h4>
  283. {subscription.planTier === PlanTier.AM3
  284. ? onDemandBudgets.enabled
  285. ? t('Edit Pay-as-you-go Budget')
  286. : t('Set Up pay-as-you-go')
  287. : onDemandBudgets.enabled
  288. ? t('Edit On-Demand Budgets')
  289. : t('Set Up On-Demand')}
  290. </h4>
  291. </Header>
  292. <OffsetBody>
  293. {this.renderError(this.state.updateError)}
  294. <OnDemandBudgetEdit
  295. onDemandEnabled={onDemandBudgets.enabled}
  296. onDemandSupported
  297. currentBudgetMode={onDemandBudgets.budgetMode}
  298. onDemandBudget={this.state.onDemandBudget}
  299. setBudgetMode={this.setBudgetMode}
  300. setOnDemandBudget={onDemandBudget => {
  301. this.setState({
  302. onDemandBudget,
  303. });
  304. }}
  305. activePlan={subscription.planDetails}
  306. organization={organization}
  307. subscription={subscription}
  308. />
  309. </OffsetBody>
  310. <Footer>
  311. <ButtonBar gap={1}>
  312. <Button
  313. onClick={() => {
  314. this.props.closeModal();
  315. }}
  316. >
  317. {t('Cancel')}
  318. </Button>
  319. <Button priority="primary" onClick={this.handleSave}>
  320. {t('Save')}
  321. </Button>
  322. </ButtonBar>
  323. </Footer>
  324. </Fragment>
  325. );
  326. }
  327. }
  328. const InputFields = styled('div')`
  329. display: flex;
  330. flex-direction: column;
  331. gap: ${space(0.5)};
  332. align-items: flex-end;
  333. `;
  334. const Currency = styled('div')`
  335. &::before {
  336. padding: 10px 10px 9px;
  337. position: absolute;
  338. content: '$';
  339. color: ${p => p.theme.textColor};
  340. font-size: ${p => p.theme.fontSizeLarge};
  341. line-height: ${p => p.theme.fontSizeLarge};
  342. }
  343. `;
  344. const OnDemandInput = styled(Input)`
  345. padding-left: ${space(4)};
  346. color: ${p => p.theme.textColor};
  347. max-width: 140px;
  348. height: 36px;
  349. `;
  350. const DetailTitle = styled('div')`
  351. text-transform: uppercase;
  352. font-size: ${p => p.theme.fontSizeSmall};
  353. color: ${p => p.theme.gray300};
  354. margin-top: ${space(0.5)};
  355. `;
  356. const OffsetBody = styled('div')`
  357. margin: -${space(3)} -${space(4)};
  358. @media (max-width: ${p => p.theme.breakpoints.medium}) {
  359. margin: -${space(3)};
  360. }
  361. `;
  362. export default withApi(OnDemandBudgetEditModal);