<commit_before>import { GraphQLNonNull, GraphQLBoolean } from 'graphql';
import { get, pick } from 'lodash';

import { Collective } from '../object/Collective';
import { CreateCollectiveInput } from '../input/CreateCollectiveInput';
import { AccountInput, fetchAccountWithInput } from '../input/AccountInput';

import * as errors from '../../errors';
import models from '../../../models';
import roles from '../../../constants/roles';
import activities from '../../../constants/activities';
import * as github from '../../../lib/github';
import { purgeCacheForPage } from '../../../lib/cloudflare';
import { defaultHostCollective } from '../../../lib/utils';

const DEFAULT_COLLECTIVE_SETTINGS = {
  features: { conversations: true },
};

async function createCollective(_, args, req) {
  let shouldAutomaticallyApprove = false;

  const { remoteUser, loaders } = req;

  if (!remoteUser) {
    throw new errors.Unauthorized({ message: 'You need to be logged in to create a collective' });
  }

  const collectiveData = {
    ...pick(args.collective, ['name', 'slug', 'description', 'tags']),
    isActive: false,
    CreatedByUserId: remoteUser.id,
    settings: { ...DEFAULT_COLLECTIVE_SETTINGS },
  };

  const collectiveWithSlug = await models.Collective.findOne({ where: { slug: collectiveData.slug.toLowerCase() } });
  if (collectiveWithSlug) {
    throw new Error(`The slug ${collectiveData.slug} is already taken. Please use another slug for your collective.}.`);
  }

  let host;
  if (args.host) {
    host = await fetchAccountWithInput(args.host, { loaders });
    if (!host) {
      throw new errors.ValidationFailed({ message: 'Host Not Found' });
    }
    if (!host.isHostAccount) {
      throw new errors.ValidationFailed({ message: 'Host account is not activated as Host.' });
    }
  }

  // Handle GitHub automated approval for the Open Source Collective Host
  if (args.automateApprovalWithGithub && args.collective.githubHandle) {
    const githubHandle = args.collective.githubHandle;
    const opensourceHost = defaultHostCollective('opensource');
    if (host.id === opensourceHost.CollectiveId) {
      try {
        const githubAccount = await models.ConnectedAccount.findOne({
          where: { CollectiveId: remoteUser.CollectiveId, service: 'github' },
        });
        if (!githubAccount) {
          throw new Error('You must have a connected GitHub Account to claim a collective');
        }
        await github.handleOpenSourceAutomatedApproval(githubHandle, githubAccount.token);
        shouldAutomaticallyApprove = true;
      } catch (error) {
        throw new errors.ValidationFailed({ message: error.message });
      }
      if (githubHandle.includes('/')) {
        collectiveData.settings.githubRepo = githubHandle;
      } else {
        collectiveData.settings.githubOrg = githubHandle;
      }
      collectiveData.tags = collectiveData.tags || [];
      if (!collectiveData.tags.includes('open source')) {
        collectiveData.tags.push('open source');
      }
    }
  }

  const collective = await models.Collective.create(collectiveData);<commit_msg>enhancement: pick the opensource host automatically<commit_after>import { GraphQLNonNull, GraphQLBoolean } from 'graphql';
import { get, pick } from 'lodash';

import { Collective } from '../object/Collective';
import { CreateCollectiveInput } from '../input/CreateCollectiveInput';
import { AccountInput, fetchAccountWithInput } from '../input/AccountInput';

import * as errors from '../../errors';
import models from '../../../models';
import roles from '../../../constants/roles';
import activities from '../../../constants/activities';
import * as github from '../../../lib/github';
import { purgeCacheForPage } from '../../../lib/cloudflare';
import { defaultHostCollective } from '../../../lib/utils';

const DEFAULT_COLLECTIVE_SETTINGS = {
  features: { conversations: true },
};

async function createCollective(_, args, req) {
  let shouldAutomaticallyApprove = false;

  const { remoteUser, loaders } = req;

  if (!remoteUser) {
    throw new errors.Unauthorized({ message: 'You need to be logged in to create a collective' });
  }

  const collectiveData = {
    ...pick(args.collective, ['name', 'slug', 'description', 'tags']),
    isActive: false,
    CreatedByUserId: remoteUser.id,
    settings: { ...DEFAULT_COLLECTIVE_SETTINGS },
  };

  const collectiveWithSlug = await models.Collective.findOne({ where: { slug: collectiveData.slug.toLowerCase() } });
  if (collectiveWithSlug) {
    throw new Error(`The slug ${collectiveData.slug} is already taken. Please use another slug for your collective.`);
  }

  let host;

  // Handle GitHub automated approval and apply to the Open Source Collective Host
  if (args.automateApprovalWithGithub && args.collective.githubHandle) {
    const githubHandle = args.collective.githubHandle;
    const opensourceHost = defaultHostCollective('opensource');
    host = await loaders.Collective.byId.load(opensourceHost.CollectiveId);
    try {
      const githubAccount = await models.ConnectedAccount.findOne({
        where: { CollectiveId: remoteUser.CollectiveId, service: 'github' },
      });
      if (!githubAccount) {
        throw new Error('You must have a connected GitHub Account to claim a collective');
      }
      await github.handleOpenSourceAutomatedApproval(githubHandle, githubAccount.token);
      shouldAutomaticallyApprove = true;
    } catch (error) {
      throw new errors.ValidationFailed({ message: error.message });
    }
    if (githubHandle.includes('/')) {
      collectiveData.settings.githubRepo = githubHandle;
    } else {
      collectiveData.settings.githubOrg = githubHandle;
    }
    collectiveData.tags = collectiveData.tags || [];
    if (!collectiveData.tags.includes('open source')) {
      collectiveData.tags.push('open source');
    }
  } else if (args.host) {
    host = await fetchAccountWithInput(args.host, { loaders });
    if (!host) {
      throw new errors.ValidationFailed({ message: 'Host Not Found' });
    }
    if (!host.isHostAccount) {
      throw new errors.ValidationFailed({ message: 'Host account is not activated as Host.' });
    }
  }

  const collective = await models.Collective.create(collectiveData);
{'fraction_non_alphanumeric': 0.13303414008655234, 'fraction_numerical': 0.0, 'mean_word_length': 3.4956772334293946, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4040035', 'n_tokens_mistral': 1714, 'n_tokens_neox': 1716, 'n_words': 467}