ronantakizawa/codereview-bench huggingface dataset:
Repository: freeCodeCamp/freeCodeCamp
File: api-server/src/server/boot/challenge.js (JavaScript)

Code before:

    try {
      const msUser = await MsUsername.findOne({
        where: { userId: user.id }
      });

      if (!msUser || !msUser.msUsername) {
        throw new Error('flash.ms.trophy.err-1');
      }

      const { msUsername } = msUser;

      const challenge = msTrophyChallenges.find(
        challenge => challenge.id === id
      );

      if (!challenge) {
        throw new Error('flash.ms.trophy.err-2');
      }

      const { msTrophyId = '' } = challenge;
      const msTrophyApiUrl = `https://learn.microsoft.com/api/gamestatus/achievements/${msTrophyId}?username=${msUsername}&locale=en-us`;
      const msApiRes = await fetch(msTrophyApiUrl);

      if (!msApiRes.ok) {
        return res.status(500).json({
          type: 'danger',
          message: 'flash.ms.trophy.err-3',
          variables: {
            msUsername
          }
        });
      }

      const completedChallenge = pick(body, ['id']);

      completedChallenge.solution = msTrophyApiUrl;
      completedChallenge.completedDate = Date.now();

      try {
        await user.getCompletedChallenges$().toPromise();
      } catch (e) {
        return next(e);
      }

      const { alreadyCompleted, updateData } = buildUserUpdate(
        user,
        completedChallenge.id,
        completedChallenge
      );


Review comment (bug):
```suggestion
        return res.status(404).json({
```
I don't think we should be using 500 here, since we know what's wrong and we know how to handle it. 404 seems like the best since the server looked for evidence they'd completed the trophy and didn't find it.

Code after:

    try {
      const msUser = await MsUsername.findOne({
        where: { userId: user.id }
      });

      if (!msUser || !msUser.msUsername) {
        return res
          .status(403)
          .json({ type: 'error', message: 'flash.ms.trophy.err-1' });
      }

      const { msUsername } = msUser;

      const challenge = msTrophyChallenges.find(
        challenge => challenge.id === id
      );

      if (!challenge) {
        return res
          .status(400)
          .json({ type: 'error', message: 'flash.ms.trophy.err-2' });
      }

      const { msTrophyId = '' } = challenge;
      const msTrophyApiUrl = `https://learn.microsoft.com/api/gamestatus/achievements/${msTrophyId}?username=${msUsername}&locale=en-us`;
      const msApiRes = await fetch(msTrophyApiUrl);
      const msTrophyJson = await msApiRes.json();

      if (!msApiRes.ok || msTrophyJson.awardType !== 'Trophy') {
        return res.status(403).json({
          type: 'error',
          message: 'flash.ms.trophy.err-3',
          variables: {
            msUsername
          }
        });
      }

      const completedChallenge = pick(body, ['id']);

      completedChallenge.solution = msTrophyApiUrl;
      completedChallenge.completedDate = Date.now();

      try {
        await user.getCompletedChallenges$().toPromise();
      } catch (e) {
        return next(e);
      }

      const { alreadyCompleted, updateData } = buildUserUpdate(
Repository: freeCodeCamp/freeCodeCamp
File: client/src/components/Intro/components/intro-description.tsx (TypeScript)

Code before:
      </p>
      <Spacer size='medium' />
      <p data-playwright-test-label='learn-read-this-p'>
        {t('learn.read-this.p1')}
      </p>
      <p data-playwright-test-label='learn-read-this-p'>
        {t('learn.read-this.p2')}
      </p>
      <p data-playwright-test-label='learn-read-this-p'>
        {t('learn.read-this.p3')}
      </p>
      <p data-playwright-test-label='learn-read-this-p'>
        {t('learn.read-this.p4')}
      </p>
      <p data-playwright-test-label='learn-read-this-p'>
        {t('learn.read-this.p5')}
      </p>
      <p data-playwright-test-label='learn-read-this-p'>
        {t('learn.read-this.p6')}
      </p>
      <p data-playwright-test-label='learn-read-this-p'>
        {t('learn.read-this.p7')}
      </p>
      <p data-playwright-test-label='learn-read-this-p'>
        {t('learn.read-this.p8')}
      </p>
      <p>
        <Trans
          i18nKey='learn.read-this.p9'
          data-playwright-test-label='learn-read-this-p'
        >
          <Link className='inline' to='https://youtube.com/freecodecamp' />
        </Trans>
      </p>
      <p data-playwright-test-label='learn-read-this-p'>
        {t('learn.read-this.p10')}
      </p>
      <p>
        <Trans
          i18nKey='learn.read-this.p11'
          data-playwright-test-label='learn-read-this-p'
        >
          <Link className='inline' to={forumLocation} />
        </Trans>
      </p>
      <p data-playwright-test-label='learn-read-this-p'>
        {t('learn.read-this.p12')}
      </p>
      <strong>{t('misc.quincy')}</strong>
    </div>
  );

Review comment (refactor):
```suggestion
      {[...Array(8).keys()].map(i => (
        <p key={i} data-playwright-test-label='learn-read-this-p'>
          {t(`learn.read-this.p${i + 1}`)}
        </p>
      ))}
```
This is getting a little too bulky and repetitive, so let's DRY it.

Code after:
      </p>
      <Spacer size='medium' />
      {[...Array(8).keys()].map(i => (
        <p key={i} data-playwright-test-label='learn-read-this-p'>
          {t(`learn.read-this.p${i + 1}`)}
        </p>
      ))}
      <p>
        <Trans
          i18nKey='learn.read-this.p9'
          data-playwright-test-label='learn-read-this-p'
        >
          <Link className='inline' to='https://youtube.com/freecodecamp' />
        </Trans>
      </p>
      <p data-playwright-test-label='learn-read-this-p'>
        {t('learn.read-this.p10')}
      </p>
      <p>
        <Trans
          i18nKey='learn.read-this.p11'
          data-playwright-test-label='learn-read-this-p'
        >
          <Link className='inline' to={forumLocation} />
        </Trans>
      </p>
      <p data-playwright-test-label='learn-read-this-p'>
        {t('learn.read-this.p12')}
      </p>
      <strong>{t('misc.quincy')}</strong>
    </div>
  );
}

IntroDescription.displayName = 'IntroDescription';

export default IntroDescription;
Repository: freeCodeCamp/freeCodeCamp
File: api-server/src/server/utils/donation.js (JavaScript)

Code before:
      message: 'Request is not valid',
      type: 'InvalidRequest'
    };
  }

  /*
   * if user is already donating and the donation isn't one time only,
   * throw error
   */

  if (user.isDonating && duration !== 'one-time') {
    throw {
      message: `User already has active recurring donation(s).`,
      type: 'AlreadyDonatingError'
    };
  }

  /*
   * card donations is blocked for new users
   */

  const threeChallengesCompleted = user.completedChallenges.length >= 3;
  if (!threeChallengesCompleted) {
    throw {
      message: `Donate using another method`,
      type: 'MethodRistrictionError'
    };
  }

  let customerId;
  try {
    const customer = await stripe.customers.create({
      email,
      payment_method: paymentMethodId,
      invoice_settings: { default_payment_method: paymentMethodId },
      ...(name && { name })
    });
    customerId = customer?.id;
  } catch {
    throw {
      type: 'customerCreationFailed',
      message: 'Failed to create stripe customer'
    };
  }
  log(`Stripe customer with id ${customerId} created`);

  let subscriptionId;
  try {
    const {
      id: subscription_id,
      latest_invoice: {

Review comment (suggestion):
```suggestion
      type: 'MethodRestrictionError'
```
Nit

Code after:
      message: 'Request is not valid',
      type: 'InvalidRequest'
    };
  }

  /*
   * if user is already donating and the donation isn't one time only,
   * throw error
   */

  if (user.isDonating && duration !== 'one-time') {
    throw {
      message: `User already has active recurring donation(s).`,
      type: 'AlreadyDonatingError'
    };
  }

  /*
   * card donations is blocked for new users
   */

  const threeChallengesCompleted = user.completedChallenges.length >= 3;
  if (!threeChallengesCompleted) {
    throw {
      message: `Donate using another method`,
      type: 'MethodRestrictionError'
    };
  }

  let customerId;
  try {
    const customer = await stripe.customers.create({
      email,
      payment_method: paymentMethodId,
      invoice_settings: { default_payment_method: paymentMethodId },
      ...(name && { name })
    });
    customerId = customer?.id;
  } catch {
    throw {
      type: 'customerCreationFailed',
      message: 'Failed to create stripe customer'
    };
  }
  log(`Stripe customer with id ${customerId} created`);

  let subscriptionId;
  try {
    const {
      id: subscription_id,
      latest_invoice: {
Repository: freeCodeCamp/freeCodeCamp
File: api/src/schemas.ts (TypeScript)

Code before:
  updateMyPrivacyTerms: {
    body: Type.Object({
      quincyEmails: Type.Boolean()
    }),
    response: {
      200: Type.Object({
        message: Type.Literal('flash.privacy-updated'),
        type: Type.Literal('success')
      }),
      500: Type.Object({
        message: Type.Literal('flash.wrong-updating'),
        type: Type.Literal('danger')
      })
    }
  },
  updateMyPortfolio: {
    body: Type.Object({
      portfolio: Type.Array(
        Type.Object({
          description: Type.String(),
          id: Type.String(),
          image: Type.String(),
          title: Type.String(),
          url: Type.String()
        })
      )
    }),
    response: {
      200: Type.Object({
        message: Type.Literal('flash.portfolio-item-updated'),
        type: Type.Literal('success')
      }),
      // TODO(Post-MVP): give more detailed response (i.e. which item is
      // missing)
      400: Type.Object({
        message: Type.Literal('flash.wrong-updating'),
        type: Type.Literal('danger')
      }),
      // TODO(Post-MVP): differentiate with more than just the status
      500: Type.Object({
        message: Type.Literal('flash.wrong-updating'),
        type: Type.Literal('danger')
      })
    }
  },
  // User:
  deleteMyAccount: {
    response: {
      200: Type.Object({}),
      500: generic500
    }

Review comment (bug):
in the old api, it doesn't fail if any of the data is missing, it only fails if the user query fails. 

you can have an empty portfolio item https://www.freecodecamp.org/Sboonny 

Code after:
  updateMyPrivacyTerms: {
    body: Type.Object({
      quincyEmails: Type.Boolean()
    }),
    response: {
      200: Type.Object({
        message: Type.Literal('flash.privacy-updated'),
        type: Type.Literal('success')
      }),
      500: Type.Object({
        message: Type.Literal('flash.wrong-updating'),
        type: Type.Literal('danger')
      })
    }
  },
  updateMyPortfolio: {
    body: Type.Object({
      portfolio: Type.Array(
        Type.Object({
          description: Type.Optional(Type.String()),
          id: Type.Optional(Type.String()),
          image: Type.Optional(Type.String()),
          title: Type.Optional(Type.String()),
          url: Type.Optional(Type.String())
        })
      )
    }),
    response: {
      200: Type.Object({
        message: Type.Literal('flash.portfolio-item-updated'),
        type: Type.Literal('success')
      }),
      // TODO(Post-MVP): give more detailed response (i.e. which item is
      // missing)
      400: Type.Object({
        message: Type.Literal('flash.wrong-updating'),
        type: Type.Literal('danger')
      }),
      // TODO(Post-MVP): differentiate with more than just the status
      500: Type.Object({
        message: Type.Literal('flash.wrong-updating'),
        type: Type.Literal('danger')
      })
    }
  },
  // User:
  deleteMyAccount: {
    response: {
      200: Type.Object({}),
      500: generic500
    }
Repository: freeCodeCamp/freeCodeCamp
File: client/src/components/settings/internet.tsx (TypeScript)

Code before:

import { maybeUrlRE } from '../../utils';

import { FullWidthRow } from '../helpers';
import BlockSaveButton from '../helpers/form/block-save-button';
import SectionHeader from './section-header';

export interface Socials {
  githubProfile: string;
  linkedin: string;
  twitter: string;
  website: string;
}

interface InternetProps extends Socials {
  t: TFunction;
  updateSocials: (formValues: Socials) => void;
}

type InternetState = {
  formValues: Socials;
  originalValues: Socials;
};

function Info({ message }: { message: string }) {
  return <>{message ? <HelpBlock>{message}</HelpBlock> : null}</>;
}

class InternetSettings extends Component<InternetProps, InternetState> {
  static displayName: string;
  constructor(props: InternetProps) {
    super(props);
    const {
      githubProfile = '',
      linkedin = '',
      twitter = '',
      website = ''
    } = props;

    this.state = {
      formValues: { githubProfile, linkedin, twitter, website },
      originalValues: { githubProfile, linkedin, twitter, website }
    };
  }

  componentDidUpdate() {
    const {
      githubProfile = '',
      linkedin = '',
      twitter = '',
      website = ''

Review comment (suggestion):
```suggestion
  return message ? <HelpBlock>{message}</HelpBlock> : null;
```
Same thing, but less cluttered.

Code after:

import { maybeUrlRE } from '../../utils';

import { FullWidthRow } from '../helpers';
import BlockSaveButton from '../helpers/form/block-save-button';
import SectionHeader from './section-header';

export interface Socials {
  githubProfile: string;
  linkedin: string;
  twitter: string;
  website: string;
}

interface InternetProps extends Socials {
  t: TFunction;
  updateSocials: (formValues: Socials) => void;
}

type InternetState = {
  formValues: Socials;
  originalValues: Socials;
};

function Info({ message }: { message: string }) {
  return message ? <HelpBlock>{message}</HelpBlock> : null;
}

class InternetSettings extends Component<InternetProps, InternetState> {
  static displayName: string;
  constructor(props: InternetProps) {
    super(props);
    const {
      githubProfile = '',
      linkedin = '',
      twitter = '',
      website = ''
    } = props;

    this.state = {
      formValues: { githubProfile, linkedin, twitter, website },
      originalValues: { githubProfile, linkedin, twitter, website }
    };
  }

  componentDidUpdate() {
    const {
      githubProfile = '',
      linkedin = '',
      twitter = '',
      website = ''
Repository: freeCodeCamp/freeCodeCamp
File: client/src/templates/Challenges/components/tool-panel.tsx (TypeScript)

Code before:
          {isMobile ? t('buttons.reset') : t('buttons.reset-lesson')}
        </Button>
      )}
      <Dropdown dropup>
        <Dropdown.Toggle
          id={'get-help-dropdown'}
          data-playwright-test-label={'get-help-dropdown'}
        >
          {isMobile ? t('buttons.help') : t('buttons.get-help')}
        </Dropdown.Toggle>
        <Dropdown.Menu>
          {guideUrl ? (
            <MenuItem
              href={guideUrl}
              target='_blank'
              data-playwright-test-label={'get-hint'}
            >
              {t('buttons.get-hint')}{' '}
              <FontAwesomeIcon icon={faExternalLinkAlt} />
              <span className='sr-only'>, {t('aria.opens-new-window')}</span>
            </MenuItem>
          ) : null}
          {videoUrl ? (
            <MenuItem
              onClick={openVideoModal}
              data-playwright-test-label={'watch-a-video'}
            >
              {t('buttons.watch-video')}
            </MenuItem>
          ) : null}
          <MenuItem
            onClick={openHelpModal}
            data-playwright-test-label={'ask-for-help'}
          >
            {t('buttons.ask-for-help')}
          </MenuItem>
        </Dropdown.Menu>
      </Dropdown>
    </div>
  );
}

ToolPanel.displayName = 'ToolPanel';

export default connect(mapStateToProps, mapDispatchToProps)(ToolPanel);


Review comment (suggestion):
```suggestion
              data-playwright-test-label='watch-a-video'
```

Code after:
          {isMobile ? t('buttons.reset') : t('buttons.reset-lesson')}
        </Button>
      )}
      <Dropdown dropup>
        <Dropdown.Toggle
          id={'get-help-dropdown'}
          data-playwright-test-label='get-help-dropdown'
        >
          {isMobile ? t('buttons.help') : t('buttons.get-help')}
        </Dropdown.Toggle>
        <Dropdown.Menu>
          {guideUrl ? (
            <MenuItem
              href={guideUrl}
              target='_blank'
              data-playwright-test-label='get-hint'
            >
              {t('buttons.get-hint')}{' '}
              <FontAwesomeIcon icon={faExternalLinkAlt} />
              <span className='sr-only'>, {t('aria.opens-new-window')}</span>
            </MenuItem>
          ) : null}
          {videoUrl ? (
            <MenuItem
              onClick={openVideoModal}
              data-playwright-test-label='watch-a-video'
            >
              {t('buttons.watch-video')}
            </MenuItem>
          ) : null}
          <MenuItem
            onClick={openHelpModal}
            data-playwright-test-label='ask-for-help'
          >
            {t('buttons.ask-for-help')}
          </MenuItem>
        </Dropdown.Menu>
      </Dropdown>
    </div>
  );
}

ToolPanel.displayName = 'ToolPanel';

export default connect(mapStateToProps, mapDispatchToProps)(ToolPanel);
Repository: freeCodeCamp/freeCodeCamp
File: client/src/templates/Challenges/components/tool-panel.tsx (TypeScript)

Code before:
        >
          {isMobile ? t('buttons.help') : t('buttons.get-help')}
        </Dropdown.Toggle>
        <Dropdown.Menu>
          {guideUrl ? (
            <MenuItem
              href={guideUrl}
              target='_blank'
              data-playwright-test-label={'get-hint'}
            >
              {t('buttons.get-hint')}{' '}
              <FontAwesomeIcon icon={faExternalLinkAlt} />
              <span className='sr-only'>, {t('aria.opens-new-window')}</span>
            </MenuItem>
          ) : null}
          {videoUrl ? (
            <MenuItem
              onClick={openVideoModal}
              data-playwright-test-label={'watch-a-video'}
            >
              {t('buttons.watch-video')}
            </MenuItem>
          ) : null}
          <MenuItem
            onClick={openHelpModal}
            data-playwright-test-label={'ask-for-help'}
          >
            {t('buttons.ask-for-help')}
          </MenuItem>
        </Dropdown.Menu>
      </Dropdown>
    </div>
  );
}

ToolPanel.displayName = 'ToolPanel';

export default connect(mapStateToProps, mapDispatchToProps)(ToolPanel);


Review comment (suggestion):
```suggestion
            data-playwright-test-label='ask-for-help'
```

Code after:
        >
          {isMobile ? t('buttons.help') : t('buttons.get-help')}
        </Dropdown.Toggle>
        <Dropdown.Menu>
          {guideUrl ? (
            <MenuItem
              href={guideUrl}
              target='_blank'
              data-playwright-test-label='get-hint'
            >
              {t('buttons.get-hint')}{' '}
              <FontAwesomeIcon icon={faExternalLinkAlt} />
              <span className='sr-only'>, {t('aria.opens-new-window')}</span>
            </MenuItem>
          ) : null}
          {videoUrl ? (
            <MenuItem
              onClick={openVideoModal}
              data-playwright-test-label='watch-a-video'
            >
              {t('buttons.watch-video')}
            </MenuItem>
          ) : null}
          <MenuItem
            onClick={openHelpModal}
            data-playwright-test-label='ask-for-help'
          >
            {t('buttons.ask-for-help')}
          </MenuItem>
        </Dropdown.Menu>
      </Dropdown>
    </div>
  );
}

ToolPanel.displayName = 'ToolPanel';

export default connect(mapStateToProps, mapDispatchToProps)(ToolPanel);
Repository: freeCodeCamp/freeCodeCamp
File: e2e/help-button.spec.ts (TypeScript)

Code before:
import { test, expect, type Page } from '@playwright/test';

test.describe('help-button tests for a page with three links', () => {
  let page: Page;
  // visit the page with the video link
  test.beforeAll(async ({ browser }) => {
    page = await browser.newPage();
    await page.goto(
      '/learn/responsive-web-design/basic-html-and-html5/say-hello-to-html-elements'
    );
  });

  test.afterAll(async () => {
    await page.close();
  });

  test('should render the button, menu and the three links when video is available', async () => {
    //The button is visible
    const helpButton = page.getByTestId('get-help-dropdown');
    await expect(helpButton).toBeVisible();
    //The button is clickable
    await helpButton.click();
    //The menu items are visible
    await expect(page.getByTestId('get-hint')).toBeVisible();
    await expect(page.getByTestId('ask-for-help')).toBeVisible();
    await expect(page.getByTestId('watch-a-video')).toBeVisible();
  });
});

test.describe('help-button tests for a page with two links when video is not available', () => {
  let page: Page;
  // visit the page without the video link
  test.beforeAll(async ({ browser }) => {
    page = await browser.newPage();
    await page.goto(
      '/learn/front-end-development-libraries/bootstrap/apply-the-default-bootstrap-button-style'
    );

Review comment (refactor):
@Fahdkassim 

I can see we are repeating the same code in both the tests. 
I suggest we move the implementation in a function here and keep it DRY.

Code after:
import { test, expect } from '@playwright/test';

test.describe('help-button tests for a page with three links (hint, help and video)', () => {
  test('should render the button, menu and the three links when video is available', async ({
    page
  }) => {
    // visit the page with the video link
    await page.goto(
      '/learn/responsive-web-design/basic-html-and-html5/say-hello-to-html-elements'
    );
    //The button is visible
    const helpButton = page.getByTestId('get-help-dropdown');
    await expect(helpButton).toBeVisible();
    //The button is clickable
    await helpButton.click();
    //The menu items are visible
    await expect(page.getByTestId('get-hint')).toBeVisible();
    await expect(page.getByTestId('ask-for-help')).toBeVisible();
    await expect(page.getByTestId('watch-a-video')).toBeVisible();
  });
});

test.describe('help-button tests for a page with two links when video is not available', () => {
  test('should render the button, menu and the two links when video is not available', async ({
    page
  }) => {
    // visit the page without the video link
    await page.goto(
      '/learn/front-end-development-libraries/bootstrap/apply-the-default-bootstrap-button-style'
    );
    //The button is visible
    const helpButton = page.getByTestId('get-help-dropdown');
    await expect(helpButton).toBeVisible();
    //The button is clickable
    await helpButton.click();
    //The menu items are visible
    await expect(page.getByTestId('get-hint')).toBeVisible();