ronantakizawa/codereview-bench huggingface dataset:
Repository: freeCodeCamp/freeCodeCamp
File: api/src/schemas.ts (TypeScript)

Code before:
      }),
      500: generic500
    }
  },
  // Deprecated endpoints:
  deprecatedEndpoints: {
    response: {
      410: Type.Object({
        message: Type.Object({
          type: Type.Literal('info'),
          message: Type.Literal(
            'Please reload the app, this feature is no longer available.'
          )
        })
      })
    }
  },
  // Challenges:
  projectCompleted: {
    body: Type.Object({
      id: Type.String({ format: 'objectid', maxLength: 24, minLength: 24 }),
      challengeType: Type.Optional(Type.Number()),
      solution: Type.String({ format: 'url', maxLength: 1024 }),
      // TODO(Post-MVP): require format: 'url' for githubLink
      githubLink: Type.Optional(Type.String())
    }),
    response: {
      200: Type.Object({
        // TODO(Post-MVP): delete completedDate and alreadyCompleted? As far as
        // I can tell, they are not used anywhere
        completedDate: Type.Number(),
        points: Type.Number(),
        alreadyCompleted: Type.Boolean()
      }),
      400: Type.Object({
        type: Type.Literal('error'),
        message: Type.Union([
          Type.Literal(
            'That does not appear to be a valid challenge submission.'
          ),
          Type.Literal(
            'You have not provided the valid links for us to inspect your work.'
          )
        ])
      }),
      403: Type.Object({
        type: Type.Literal('error'),
        message: Type.Literal(
          'You have to complete the project before you can submit a URL.'
        )
      }),

Review comment (suggestion):
```suggestion
      username: Type.String({ minLength: 1 }),
      reportDescription: Type.String({ minLength: 1 })
```
So the `''` case is excluded by validation.

Code after:
        user: Type.Object({}),
        result: Type.Literal('')
      })
    }
  },
  deleteUserToken: {
    response: {
      200: Type.Object({
        userToken: Type.Null()
      }),
      404: Type.Object({
        message: Type.Literal('userToken not found'),
        type: Type.Literal('info')
      }),
      500: Type.Object({
        message: Type.Literal(
          'Oops! Something went wrong. Please try again in a moment or contact support@freecodecamp.org if the error persists.'
        ),
        type: Type.Literal('danger')
      })
    }
  },
  reportUser: {
    body: Type.Object({
      username: Type.String(),
      reportDescription: Type.String()
    }),
    response: {
      200: Type.Object({
        type: Type.Literal('info'),
        message: Type.Literal('flash.report-sent'),
        variables: Type.Object({
          email: Type.String()
        })
      }),
      400: Type.Object({
        type: Type.Literal('danger'),
        message: Type.Literal('flash.provide-username')
      }),
      500: generic500
    }
  },
  // Deprecated endpoints:
  deprecatedEndpoints: {
    response: {
      410: Type.Object({
        message: Type.Object({
          type: Type.Literal('info'),
          message: Type.Literal(
            'Please reload the app, this feature is no longer available.'
          )
Repository: freeCodeCamp/freeCodeCamp
File: api/src/routes/user.test.ts (TypeScript)

Code before:
          reportDescription:
            '<script>const breath = "loud"</script>Luke, I am your father'
        });

        expect(sendEmailSpy).toBeCalledTimes(1);
        expect(sendEmailSpy).toBeCalledWith(
          expect.objectContaining({
            text: expect.stringContaining(
              'Report Details:\n\nLuke, I am your father'
            )
          })
        );
      });

      test('POST returns 200 status code with "success" message', async () => {
        const response = await superRequest('/user/report-user', {
          method: 'POST',
          setCookies
        }).send({
          username: 'darth-vader',
          reportDescription: 'Luke, I am your father'
        });

        const user = await fastifyTestInstance.prisma.user.findFirstOrThrow({
          where: { email: 'foo@bar.com' }
        });

        expect(sendEmailSpy).toBeCalledTimes(1);
        expect(sendEmailSpy).toBeCalledWith({
          from: 'team@freecodecamp.org',
          to: 'support@freecodecamp.org',
          cc: user.email,
          subject: "Abuse Report: Reporting darth-vader's profile",
          text: generateReportEmail(
            user,
            'darth-vader',
            'Luke, I am your father'
          )
        });

        expect(response.statusCode).toBe(200);
        expect(response.body).toStrictEqual({
          type: 'info',
          message: 'flash.report-sent',
          variables: { email: user.email }
        });
      });
    });
  });

  describe('Unauthenticated user', () => {

Review comment (suggestion):
It looks like this is unnecessary since we're only using the `email` property of `user`, but we already have that.

Code after:
            '<script>const breath = "loud"</script>Luke, I am your father'
        });

        expect(sendEmailSpy).toBeCalledTimes(1);
        expect(sendEmailSpy).toBeCalledWith(
          expect.objectContaining({
            text: expect.stringContaining(
              'Report Details:\n\nLuke, I am your father'
            )
          })
        );
      });

      test('POST returns 200 status code with "success" message', async () => {
        const response = await superRequest('/user/report-user', {
          method: 'POST',
          setCookies
        }).send({
          username: 'darth-vader',
          reportDescription: 'Luke, I am your father'
        });

        expect(sendEmailSpy).toBeCalledTimes(1);
        expect(sendEmailSpy).toBeCalledWith({
          from: 'team@freecodecamp.org',
          to: 'support@freecodecamp.org',
          cc: 'foo@bar.com',
          subject: "Abuse Report: Reporting darth-vader's profile",
          text: `
Hello Team,

This is to report the profile of darth-vader.

Report Details:

Luke, I am your father


Reported by:
Username: 
Name: 
Email: foo@bar.com

Thanks and regards,
`
        });

        expect(response.statusCode).toBe(200);
        expect(response.body).toStrictEqual({
          type: 'info',
          message: 'flash.report-sent',
Repository: freeCodeCamp/freeCodeCamp
File: tools/ui-components/src/form-control/form-control.tsx (TypeScript)

Code before:
import { FormControlFeedback } from './form-control-feedback';
import { FormControlStatic } from './form-control-static';
import { FormControlProps } from './types';

// Uses controlId from <FormGroup> if not explicitly specified.
// type Only relevant if componentClass is 'input'.
let variantClass: string;
const defaultClasses =
  'outline-0 block w-full py-1.5 px-2.5 text-md text-foreground-primary bg-background-primary bg-none rounded-none border-1 border-solid border-background-quaternary shadow-none transition ease-in-out duration-150 focus:border-foreground-tertiary';

const FormControl = ({
  componentClass,
  ...props
}: FormControlProps<'input' | 'textarea'>): JSX.Element => {
  const { controlId } = useContext(FormContext);
  const { id, className } = props;

  const Component = componentClass || 'input';
  if (Component !== 'textarea') variantClass = ' h-8';

  //row and componentClass
  const classes = [className, defaultClasses, variantClass].join(' ');

  return <Component id={id || controlId} className={classes} {...props} />;
};
<FormControl />;

FormControl.Feedback = FormControlFeedback;
FormControl.Static = FormControlStatic;

export { FormControl };


Review comment (suggestion):
I'm not sure what this line is for. Probably an accidental change?

```suggestion
```

Code after:
import { FormControlFeedback } from './form-control-feedback';
import { FormControlStatic } from './form-control-static';
import { FormControlProps } from './types';

// Uses controlId from <FormGroup> if not explicitly specified.
// type Only relevant if componentClass is 'input'.
let variantClass: string;
const defaultClasses =
  'outline-0 block w-full py-1.5 px-2.5 text-md text-foreground-primary bg-background-primary bg-none rounded-none border-1 border-solid border-background-quaternary shadow-none transition ease-in-out duration-150 focus:border-foreground-tertiary';

const FormControl = ({
  componentClass,
  ...props
}: FormControlProps<'input' | 'textarea'>): JSX.Element => {
  const { controlId } = useContext(FormContext);
  const { id, className } = props;

  const Component = componentClass || 'input';
  if (Component !== 'textarea') variantClass = ' h-8';

  //row and componentClass
  const classes = [className, defaultClasses, variantClass].join(' ');

  return <Component id={id || controlId} className={classes} {...props} />;
};

FormControl.Feedback = FormControlFeedback;
FormControl.Static = FormControlStatic;

export { FormControl };
Repository: freeCodeCamp/freeCodeCamp
File: utils/is-audited.ts (TypeScript)

Code before:
import { type SuperBlocks, getAuditedSuperBlocks } from '../config/superblocks';

export function isAuditedSuperblock(
  language: string,
  superblock: SuperBlocks,
  {
    showNewCurriculum,
    showUpcomingChanges
  }: { showNewCurriculum: boolean; showUpcomingChanges: boolean }
) {
  // TODO: when all the consumers of this function use TypeScript we can remove
  // this check
  if (!language || !superblock)
    throw Error('Both arguments must be provided for auditing');

  const auditedSuperBlocks = getAuditedSuperBlocks({
    showNewCurriculum,
    showUpcomingChanges,
    language
  });
  return auditedSuperBlocks.includes(superblock);
}


Review comment (suggestion):
Not sure if we want to capitalize the word "block" here (it's just that most of the variables are `SuperBlock` instead of `Superblock` 😄)

Code after:
import { type SuperBlocks, getAuditedSuperBlocks } from '../config/superblocks';

export function isAuditedSuperBlock(
  language: string,
  superblock: SuperBlocks,
  {
    showNewCurriculum,
    showUpcomingChanges
  }: { showNewCurriculum: boolean; showUpcomingChanges: boolean }
) {
  // TODO: when all the consumers of this function use TypeScript we can remove
  // this check
  if (!language || !superblock)
    throw Error('Both arguments must be provided for auditing');

  const auditedSuperBlocks = getAuditedSuperBlocks({
    showNewCurriculum,
    showUpcomingChanges,
    language
  });
  return auditedSuperBlocks.includes(superblock);
}
Repository: freeCodeCamp/freeCodeCamp
File: api/src/routes/donate.ts (TypeScript)

Code before:
        void reply.code(500);
        return {
          type: 'danger',
          message: 'Something went wrong.'
        } as const;
      }
    }
  );

  fastify.post(
    '/donate/charge-stripe-card',
    {
      schema: schemas.chargeStripeCard
    },
    async (req, reply) => {
      try {
        const { paymentMethodId, amount, duration } = req.body;
        const { id } = req.session.user;

        const user = await fastify.prisma.user.findUnique({
          where: { id }
        });

        if (!user) {
          void reply.code(500);
          return {
            type: 'danger',
            message: 'Something went wrong.'
          } as const;
        }

        const { email, name } = user;

        if (user.isDonating) {
          void reply.code(400);
          return {
            type: 'info',
            message: 'User is already donating.'
          } as const;
        }

        // Create Stripe Customer
        let customerId;
        try {
          const customer = await stripe.customers.create({
            email,
            payment_method: paymentMethodId,
            invoice_settings: { default_payment_method: paymentMethodId },
            ...(name && { name })
          });
          customerId = customer?.id;

Review comment (suggestion):
```suggestion
        if (user.isDonating && duration !== 'one-time') {
```
That's the current logic.

Code after:
        void reply.code(500);
        return {
          type: 'danger',
          message: 'Something went wrong.'
        } as const;
      }
    }
  );

  fastify.post(
    '/donate/charge-stripe-card',
    {
      schema: schemas.chargeStripeCard
    },
    async (req, reply) => {
      try {
        const { paymentMethodId, amount, duration } = req.body;
        const { id } = req.session.user;

        const user = await fastify.prisma.user.findUniqueOrThrow({
          where: { id }
        });

        const { email, name } = user;

        if (user.isDonating) {
          void reply.code(400);
          return {
            type: 'info',
            message: 'User is already donating.'
          } as const;
        }

        // Create Stripe Customer
        const { id: customerId } = await stripe.customers.create({
          email,
          payment_method: paymentMethodId,
          invoice_settings: { default_payment_method: paymentMethodId },
          ...(name && { name })
        });

        // //Create Stripe Subscription
        const plan = `${donationSubscriptionConfig.duration[
          duration
        ].toLowerCase()}-donation-${amount}`;

        const {
          id: subscriptionId,
          latest_invoice: {
            // For older api versions, @ts-ignore is recommended by Stripe. More info: https://github.com/stripe/stripe-node/blob/fe81d1f28064c9b468c7b380ab09f7a93054ba63/README.md?plain=1#L91
            // eslint-disable-next-line @typescript-eslint/ban-ts-comment
Repository: freeCodeCamp/freeCodeCamp
File: api/src/routes/donate.ts (TypeScript)

Code before:
          isDonating: true
        } as const;
      } catch (error) {
        fastify.log.error(error);
        void reply.code(500);
        return {
          type: 'danger',
          message: 'Something went wrong.'
        } as const;
      }
    }
  );

  fastify.post(
    '/donate/charge-stripe-card',
    {
      schema: schemas.chargeStripeCard
    },
    async (req, reply) => {
      try {
        const { paymentMethodId, amount, duration } = req.body;
        const { id } = req.session.user;

        const user = await fastify.prisma.user.findUnique({
          where: { id }
        });

        if (!user) {
          void reply.code(500);
          return {
            type: 'danger',
            message: 'Something went wrong.'
          } as const;
        }

        const { email, name } = user;

        if (user.isDonating) {
          void reply.code(400);
          return {
            type: 'info',
            message: 'User is already donating.'
          } as const;
        }

        // Create Stripe Customer
        let customerId;
        try {
          const customer = await stripe.customers.create({
            email,
            payment_method: paymentMethodId,

Review comment (suggestion):
```suggestion
        const user = await fastify.prisma.user.findUniqueOrThrow({
          where: { id }
        });
```
That way you can drop the `!user` check.

Code after:
          isDonating: true
        } as const;
      } catch (error) {
        fastify.log.error(error);
        void reply.code(500);
        return {
          type: 'danger',
          message: 'Something went wrong.'
        } as const;
      }
    }
  );

  fastify.post(
    '/donate/charge-stripe-card',
    {
      schema: schemas.chargeStripeCard
    },
    async (req, reply) => {
      try {
        const { paymentMethodId, amount, duration } = req.body;
        const { id } = req.session.user;

        const user = await fastify.prisma.user.findUniqueOrThrow({
          where: { id }
        });

        const { email, name } = user;

        if (user.isDonating) {
          void reply.code(400);
          return {
            type: 'info',
            message: 'User is already donating.'
          } as const;
        }

        // Create Stripe Customer
        const { id: customerId } = await stripe.customers.create({
          email,
          payment_method: paymentMethodId,
          invoice_settings: { default_payment_method: paymentMethodId },
          ...(name && { name })
        });

        // //Create Stripe Subscription
        const plan = `${donationSubscriptionConfig.duration[
          duration
        ].toLowerCase()}-donation-${amount}`;

        const {
Repository: freeCodeCamp/freeCodeCamp
File: api/src/routes/donate.ts (TypeScript)

Code before:
            payment_behavior: 'allow_incomplete',
            items: [{ plan }],
            expand: ['latest_invoice.payment_intent']
          });
          if (status === 'requires_source_action') {
            void reply.code(402);
            return {
              type: 'UserActionRequired',
              message: 'Payment requires user action',
              // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
              client_secret
            } as const;
          } else if (status === 'requires_source') {
            void reply.code(402);
            return {
              type: 'PaymentMethodRequired',
              message: 'Card has been declined'
            } as const;
          }
          subscriptionId = subscription_id;
        } catch (err) {
          throw {
            type: 'SubscriptionCreationFailed',
            message: 'Failed to create stripe subscription'
          };
        }

        // update record in database
        const donation = {
          userId: id,
          email,
          amount,
          duration,
          provider: 'stripe',
          subscriptionId,
          customerId: id,
          startDate: {
            date: new Date().toISOString(),
            when: new Date().toISOString().replace(/.$/, '+00:00')
          }
        };

        await fastify.prisma.donation.create({
          data: donation
        });

        await fastify.prisma.user.update({
          where: { id },
          data: {
            isDonating: true
          }

Review comment (suggestion):
Same as above: unless we want to log this error, please drop the try-catch .

Code after:
        const donation = {
          userId: id,
          email,
          amount,
          duration,
          provider: 'stripe',
          subscriptionId,
          customerId: id,
          // TODO(Post-MVP) migrate to startDate: new Date()
          startDate: {
            date: new Date().toISOString(),
            when: new Date().toISOString().replace(/.$/, '+00:00')
          }
        };

        await fastify.prisma.donation.create({
          data: donation
        });

        await fastify.prisma.user.update({
          where: { id },
          data: {
            isDonating: true
          }
        });

        return {
          type: 'success',
          isDonating: true
        } as const;
      } catch (error) {
        fastify.log.error(error);
        void reply.code(500);
        return {
          type: 'danger',
          message: 'Donation failed due to a server error.'
        } as const;
      }
    }
  );

  done();
};
Repository: freeCodeCamp/freeCodeCamp
File: api/src/routes/donate.test.ts (TypeScript)

Code before:
      });

      it('should return 400 if the user is already donating', async () => {
        const successResponse = await superRequest('/donate/add-donation', {
          method: 'POST',
          setCookies
        }).send({});
        expect(successResponse.status).toBe(200);
        const failResponse = await superRequest('/donate/add-donation', {
          method: 'POST',
          setCookies
        }).send({});
        expect(failResponse.status).toBe(400);
      });
    });
  });

  describe('Unauthenticated User', () => {
    let setCookies: string[];
    // Get the CSRF cookies from an unprotected route
    beforeAll(async () => {
      const res = await superRequest('/status/ping', { method: 'GET' });
      setCookies = res.get('Set-Cookie');
    });
    const endpoints: { path: string; method: 'POST' }[] = [
      { path: '/donate/add-donation', method: 'POST' }
    ];
    endpoints.forEach(({ path, method }) => {
      test(`${method} ${path} returns 401 status code with error message`, async () => {
        const response = await superRequest(path, {
          method,
          setCookies
        });
        expect(response.statusCode).toBe(401);
      });
    });
    describe('POST /donate/charge-stripe-card', () => {
      it('should return 403', async () => {
        const response = await superRequest('/donate/charge-stripe-card', {
          method: 'POST'
        }).send(chargeStripeCardReqBody);
        expect(response.status).toBe(403);
      });
    });
  });
});


Review comment (suggestion):
```suggestion
      { path: '/donate/add-donation', method: 'POST' },
      { path: '/donate/charge-stripe-card', method: 'POST' }
```

Code after:
          method: 'POST',
          setCookies
        }).send({});
        expect(failResponse.status).toBe(400);
      });
    });
  });

  describe('Unauthenticated User', () => {
    let setCookies: string[];
    // Get the CSRF cookies from an unprotected route
    beforeAll(async () => {
      const res = await superRequest('/status/ping', { method: 'GET' });
      setCookies = res.get('Set-Cookie');
    });
    const endpoints: { path: string; method: 'POST' }[] = [
      { path: '/donate/add-donation', method: 'POST' },
      { path: '/donate/charge-stripe-card', method: 'POST' }
    ];
    endpoints.forEach(({ path, method }) => {
      test(`${method} ${path} returns 401 status code with error message`, async () => {
        const response = await superRequest(path, {
          method,
          setCookies
        });
        expect(response.statusCode).toBe(401);
      });
    });
  });
});