index.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. import {Fragment, useState} from 'react';
  2. import styled from '@emotion/styled';
  3. import {addErrorMessage, addSuccessMessage} from 'sentry/actionCreators/indicator';
  4. import {ModalRenderProps} from 'sentry/actionCreators/modal';
  5. import {Client} from 'sentry/api';
  6. import Alert from 'sentry/components/alert';
  7. import Button from 'sentry/components/button';
  8. import ButtonBar from 'sentry/components/buttonBar';
  9. import LoadingIndicator from 'sentry/components/loadingIndicator';
  10. import {DEFAULT_TOAST_DURATION} from 'sentry/constants';
  11. import {t, tct} from 'sentry/locale';
  12. import space from 'sentry/styles/space';
  13. import {Organization, Project} from 'sentry/types';
  14. import {
  15. AppStoreConnectStatusData,
  16. CustomRepoAppStoreConnect,
  17. } from 'sentry/types/debugFiles';
  18. import {unexpectedErrorMessage} from 'sentry/utils/appStoreValidationErrorMessage';
  19. import withApi from 'sentry/utils/withApi';
  20. import StepOne from './stepOne';
  21. import StepTwo from './stepTwo';
  22. import {AppStoreApp, StepOneData, StepTwoData} from './types';
  23. import {getAppStoreErrorMessage} from './utils';
  24. type Props = Pick<ModalRenderProps, 'Header' | 'Body' | 'Footer'> & {
  25. api: Client;
  26. onSubmit: () => void;
  27. orgSlug: Organization['slug'];
  28. projectSlug: Project['slug'];
  29. appStoreConnectStatusData?: AppStoreConnectStatusData;
  30. initialData?: CustomRepoAppStoreConnect;
  31. };
  32. const steps = [t('App Store Connect credentials'), t('Choose an application')];
  33. function AppStoreConnect({
  34. Header,
  35. Body,
  36. Footer,
  37. api,
  38. initialData,
  39. orgSlug,
  40. projectSlug,
  41. onSubmit,
  42. appStoreConnectStatusData,
  43. }: Props) {
  44. const {credentials} = appStoreConnectStatusData ?? {};
  45. const [isLoading, setIsLoading] = useState(false);
  46. const [activeStep, setActiveStep] = useState(0);
  47. const [appStoreApps, setAppStoreApps] = useState<AppStoreApp[]>([]);
  48. const [stepOneData, setStepOneData] = useState<StepOneData>({
  49. issuer: initialData?.appconnectIssuer,
  50. keyId: initialData?.appconnectKey,
  51. privateKey: typeof initialData?.appconnectPrivateKey === 'object' ? undefined : '',
  52. errors: undefined,
  53. });
  54. const [stepTwoData, setStepTwoData] = useState<StepTwoData>({
  55. app: undefined,
  56. });
  57. async function checkCredentials() {
  58. setIsLoading(true);
  59. try {
  60. const response = await api.requestPromise(
  61. `/projects/${orgSlug}/${projectSlug}/appstoreconnect/apps/`,
  62. {
  63. method: 'POST',
  64. data: {
  65. id: stepOneData.privateKey !== undefined ? undefined : initialData?.id,
  66. appconnectIssuer: stepOneData.issuer,
  67. appconnectKey: stepOneData.keyId,
  68. appconnectPrivateKey: stepOneData.privateKey,
  69. },
  70. }
  71. );
  72. const storeApps: AppStoreApp[] = response.apps;
  73. if (!!initialData && !storeApps.find(app => app.appId === initialData.appId)) {
  74. addErrorMessage(t('Credentials not authorized for this application'));
  75. setIsLoading(false);
  76. return;
  77. }
  78. setAppStoreApps(storeApps);
  79. if (
  80. stepTwoData.app?.appId &&
  81. !storeApps.find(app => app.appId === stepTwoData.app?.appId)
  82. ) {
  83. setStepTwoData({app: storeApps[0]});
  84. }
  85. if (!!initialData) {
  86. updateCredentials();
  87. return;
  88. }
  89. setIsLoading(false);
  90. goNext();
  91. } catch (error) {
  92. setIsLoading(false);
  93. const appStoreConnnectError = getAppStoreErrorMessage(error);
  94. if (typeof appStoreConnnectError === 'string') {
  95. // app-connect-authentication-error
  96. // app-connect-forbidden-error
  97. addErrorMessage(appStoreConnnectError);
  98. return;
  99. }
  100. setStepOneData({...stepOneData, errors: appStoreConnnectError});
  101. }
  102. }
  103. function closeModal() {
  104. setTimeout(() => onSubmit(), DEFAULT_TOAST_DURATION);
  105. }
  106. async function updateCredentials() {
  107. if (!initialData) {
  108. return;
  109. }
  110. try {
  111. await api.requestPromise(
  112. `/projects/${orgSlug}/${projectSlug}/appstoreconnect/${initialData.id}/`,
  113. {
  114. method: 'POST',
  115. data: {
  116. appconnectIssuer: stepOneData.issuer,
  117. appconnectKey: stepOneData.keyId,
  118. appconnectPrivateKey: stepOneData.privateKey,
  119. appName: initialData.appName,
  120. appId: initialData.appId,
  121. bundleId: initialData.bundleId,
  122. },
  123. }
  124. );
  125. addSuccessMessage(t('Successfully updated custom repository'));
  126. closeModal();
  127. } catch (error) {
  128. setIsLoading(false);
  129. const appStoreConnnectError = getAppStoreErrorMessage(error);
  130. if (typeof appStoreConnnectError === 'string') {
  131. if (appStoreConnnectError === unexpectedErrorMessage) {
  132. addErrorMessage(t('An error occurred while updating the custom repository'));
  133. return;
  134. }
  135. addErrorMessage(appStoreConnnectError);
  136. }
  137. }
  138. }
  139. async function persistData() {
  140. if (!stepTwoData.app) {
  141. return;
  142. }
  143. setIsLoading(true);
  144. try {
  145. await api.requestPromise(`/projects/${orgSlug}/${projectSlug}/appstoreconnect/`, {
  146. method: 'POST',
  147. data: {
  148. appconnectIssuer: stepOneData.issuer,
  149. appconnectKey: stepOneData.keyId,
  150. appconnectPrivateKey: stepOneData.privateKey,
  151. appName: stepTwoData.app.name,
  152. appId: stepTwoData.app.appId,
  153. bundleId: stepTwoData.app.bundleId,
  154. },
  155. });
  156. addSuccessMessage(t('Successfully added custom repository'));
  157. closeModal();
  158. } catch (error) {
  159. setIsLoading(false);
  160. const appStoreConnnectError = getAppStoreErrorMessage(error);
  161. if (typeof appStoreConnnectError === 'string') {
  162. if (appStoreConnnectError === unexpectedErrorMessage) {
  163. addErrorMessage(t('An error occurred while adding the custom repository'));
  164. return;
  165. }
  166. addErrorMessage(appStoreConnnectError);
  167. }
  168. }
  169. }
  170. function isFormInvalid() {
  171. switch (activeStep) {
  172. case 0:
  173. return Object.keys(stepOneData).some(key => {
  174. if (key === 'errors') {
  175. const errors = stepOneData[key] ?? {};
  176. return Object.keys(errors).some(error => !!errors[error]);
  177. }
  178. if (key === 'privateKey' && stepOneData[key] === undefined) {
  179. return false;
  180. }
  181. return !stepOneData[key];
  182. });
  183. case 1:
  184. return Object.keys(stepTwoData).some(key => !stepTwoData[key]);
  185. default:
  186. return false;
  187. }
  188. }
  189. function goNext() {
  190. setActiveStep(activeStep + 1);
  191. }
  192. function handleGoBack() {
  193. const newActiveStep = activeStep - 1;
  194. setActiveStep(newActiveStep);
  195. }
  196. function handleGoNext() {
  197. switch (activeStep) {
  198. case 0:
  199. checkCredentials();
  200. break;
  201. case 1:
  202. persistData();
  203. break;
  204. default:
  205. break;
  206. }
  207. }
  208. function renderCurrentStep() {
  209. switch (activeStep) {
  210. case 0:
  211. return <StepOne stepOneData={stepOneData} onSetStepOneData={setStepOneData} />;
  212. case 1:
  213. return (
  214. <StepTwo
  215. appStoreApps={appStoreApps}
  216. stepTwoData={stepTwoData}
  217. onSetStepTwoData={setStepTwoData}
  218. />
  219. );
  220. default:
  221. return (
  222. <Alert type="error" showIcon>
  223. {t('This step could not be found.')}
  224. </Alert>
  225. );
  226. }
  227. }
  228. function getAlerts() {
  229. const alerts: React.ReactElement[] = [];
  230. if (activeStep !== 0) {
  231. return alerts;
  232. }
  233. if (credentials?.status === 'invalid') {
  234. alerts.push(
  235. <StyledAlert type="warning" showIcon>
  236. {credentials.code === 'app-connect-forbidden-error'
  237. ? t(
  238. 'Your App Store Connect credentials have insufficient permissions. To reconnect, update your credentials.'
  239. )
  240. : t(
  241. 'Your App Store Connect credentials are invalid. To reconnect, update your credentials.'
  242. )}
  243. </StyledAlert>
  244. );
  245. }
  246. return alerts;
  247. }
  248. function renderBodyContent() {
  249. const alerts = getAlerts();
  250. return (
  251. <Fragment>
  252. {!!alerts.length && (
  253. <Alerts>
  254. {alerts.map((alert, index) => (
  255. <Fragment key={index}>{alert}</Fragment>
  256. ))}
  257. </Alerts>
  258. )}
  259. {renderCurrentStep()}
  260. </Fragment>
  261. );
  262. }
  263. if (initialData && !appStoreConnectStatusData) {
  264. return <LoadingIndicator />;
  265. }
  266. return (
  267. <Fragment>
  268. <Header closeButton>
  269. <HeaderContent>
  270. <NumericSymbol>{activeStep + 1}</NumericSymbol>
  271. <HeaderContentTitle>{steps[activeStep]}</HeaderContentTitle>
  272. <StepsOverview>
  273. {tct('[currentStep] of [totalSteps]', {
  274. currentStep: activeStep + 1,
  275. totalSteps: !!initialData ? 1 : steps.length,
  276. })}
  277. </StepsOverview>
  278. </HeaderContent>
  279. </Header>
  280. <Body>{renderBodyContent()}</Body>
  281. <Footer>
  282. <ButtonBar gap={1}>
  283. {activeStep !== 0 && <Button onClick={handleGoBack}>{t('Back')}</Button>}
  284. <StyledButton
  285. priority="primary"
  286. onClick={handleGoNext}
  287. disabled={isLoading || isFormInvalid()}
  288. >
  289. {isLoading && (
  290. <LoadingIndicatorWrapper>
  291. <LoadingIndicator mini />
  292. </LoadingIndicatorWrapper>
  293. )}
  294. {!!initialData
  295. ? t('Update')
  296. : activeStep + 1 === steps.length
  297. ? t('Save')
  298. : steps[activeStep + 1]}
  299. </StyledButton>
  300. </ButtonBar>
  301. </Footer>
  302. </Fragment>
  303. );
  304. }
  305. export default withApi(AppStoreConnect);
  306. const HeaderContent = styled('div')`
  307. display: grid;
  308. grid-template-columns: max-content max-content 1fr;
  309. align-items: center;
  310. gap: ${space(1)};
  311. `;
  312. const NumericSymbol = styled('div')`
  313. border-radius: 50%;
  314. display: flex;
  315. align-items: center;
  316. justify-content: center;
  317. width: 24px;
  318. height: 24px;
  319. font-weight: 700;
  320. font-size: ${p => p.theme.fontSizeMedium};
  321. background-color: ${p => p.theme.yellow300};
  322. `;
  323. const HeaderContentTitle = styled('div')`
  324. font-weight: 700;
  325. font-size: ${p => p.theme.fontSizeExtraLarge};
  326. `;
  327. const StepsOverview = styled('div')`
  328. color: ${p => p.theme.gray300};
  329. display: flex;
  330. justify-content: flex-end;
  331. `;
  332. const LoadingIndicatorWrapper = styled('div')`
  333. height: 100%;
  334. position: absolute;
  335. width: 100%;
  336. top: 0;
  337. left: 0;
  338. display: flex;
  339. align-items: center;
  340. justify-content: center;
  341. `;
  342. const StyledButton = styled(Button)`
  343. position: relative;
  344. `;
  345. const Alerts = styled('div')`
  346. display: grid;
  347. gap: ${space(1.5)};
  348. margin-bottom: ${space(3)};
  349. `;
  350. const StyledAlert = styled(Alert)`
  351. margin: 0;
  352. `;