<commit_before>/**
 * A collection of miscellaneous utility functions.
 *
 * NOTE: these are used also by the Form Builder coffee code (see
 * `jsapp/xlform/src/view.surveyApp.coffee`)
 *
 * TODO: group these functions by what are they doing or where are they mostly
 * (or uniquely) used, and split to smaller files.
 */

import clonedeep from 'lodash.clonedeep';
import moment from 'moment';
import alertify from 'alertifyjs';
import {Cookies} from 'react-cookie';
// imporitng whole constants, as we override ROOT_URL in tests
import constants from 'js/constants';

export const LANGUAGE_COOKIE_NAME = 'django_language';

export var assign = require('object-assign');

alertify.defaults.notifier.delay = 10;
alertify.defaults.notifier.position = 'bottom-left';
alertify.defaults.notifier.closeButton = true;

const cookies = new Cookies();
const modelUtils = require('../xlform/src/model.utils');

const SLUGGIFY_LABEL_OPTIONS = {
  lowerCase: false,
  preventDuplicateUnderscores: true,
  stripSpaces: true,
  lrstrip: true,
  incrementorPadding: 3,
  validXmlTag: true
};

export function notify(msg, atype='success') {
  alertify.notify(msg, atype);
}

export function formatTime(timeStr) {
  var _m = moment(timeStr);
  return _m.calendar(null, {sameElse: 'LL'});
}

export function formatTimeDate(timeStr) {
  var _m = moment(timeStr);
  return _m.format('LLL');
}

export function formatDate(timeStr) {
  var _m = moment(timeStr);
  return _m.format('ll');
}

export function getAnonymousUserPermission(permissions) {
  return permissions.filter(function(perm){
    if (perm.user__username === undefined) {
      perm.user__username = perm.user.match(/\/users\/(.*)\//)[1];
    }
    return perm.user__username === constants.ANON_USERNAME;
  })[0];
}

export function surveyToValidJson(survey) {
  // skip logic references only preserved after initial call
  // to "survey.toFlatJSON()"
  survey.toFlatJSON();
  // returning the result of the second call to "toFlatJSON()"
  return JSON.stringify(survey.toFlatJSON());
}


/**
 * This function reverses what `nullifyTranslations` did to the form data.
 * @param {string} surveyDataJSON
 * @param {object} assetContent
 * @return {string} fixed surveyDataJSON
 */
export function unnullifyTranslations(surveyDataJSON, assetContent) {
  let surveyData = JSON.parse(surveyDataJSON);

  let translatedProps = [];
  if (assetContent.translated) {
     translatedProps = assetContent.translated;
  }

  // TRANSLATIONS HACK (Part 2/2):
  // set default_language
  let defaultLang = assetContent.translations_0;
  if (!defaultLang) {
    defaultLang = null;
  }
  if (!surveyData.settings[0].default_language && defaultLang !== null) {
    surveyData.settings[0].default_language = defaultLang;
  }

  if (defaultLang !== null) {
    // replace every "translatedProp" with "translatedProp::defaultLang"
    if (surveyData.choices) {
      surveyData.choices.forEach((choice) => {
        translatedProps.forEach((translatedProp) => {
          if (typeof choice[translatedProp] !== 'undefined') {
            choice[`${translatedProp}::${defaultLang}`] = choice[translatedProp];
            delete choice[translatedProp];
          }
        });
      });
    }
    if (surveyData.survey) {
      surveyData.survey.forEach((surveyRow) => {
        translatedProps.forEach((translatedProp) => {
          if (typeof surveyRow[translatedProp] !== 'undefined') {
            if (typeof surveyData.settings[0] !== 'undefined'
                && typeof surveyData.settings[0].style === 'string'
                && surveyData.settings[0].style.includes('theme-grid')
                && surveyRow.type === 'begin_group') {
              delete surveyRow[translatedProp];
            }
            surveyRow[`${translatedProp}::${defaultLang}`] = surveyRow[translatedProp];
            delete surveyRow[translatedProp];
          }
        });
      });
    }
  }

  return JSON.stringify(surveyData);
}<commit_msg>Added fix for group labels being deleted<commit_after>/**
 * A collection of miscellaneous utility functions.
 *
 * NOTE: these are used also by the Form Builder coffee code (see
 * `jsapp/xlform/src/view.surveyApp.coffee`)
 *
 * TODO: group these functions by what are they doing or where are they mostly
 * (or uniquely) used, and split to smaller files.
 */

import clonedeep from 'lodash.clonedeep';
import moment from 'moment';
import alertify from 'alertifyjs';
import {Cookies} from 'react-cookie';
// imporitng whole constants, as we override ROOT_URL in tests
import constants from 'js/constants';

export const LANGUAGE_COOKIE_NAME = 'django_language';

export var assign = require('object-assign');

alertify.defaults.notifier.delay = 10;
alertify.defaults.notifier.position = 'bottom-left';
alertify.defaults.notifier.closeButton = true;

const cookies = new Cookies();
const modelUtils = require('../xlform/src/model.utils');

const SLUGGIFY_LABEL_OPTIONS = {
  lowerCase: false,
  preventDuplicateUnderscores: true,
  stripSpaces: true,
  lrstrip: true,
  incrementorPadding: 3,
  validXmlTag: true
};

export function notify(msg, atype='success') {
  alertify.notify(msg, atype);
}

export function formatTime(timeStr) {
  var _m = moment(timeStr);
  return _m.calendar(null, {sameElse: 'LL'});
}

export function formatTimeDate(timeStr) {
  var _m = moment(timeStr);
  return _m.format('LLL');
}

export function formatDate(timeStr) {
  var _m = moment(timeStr);
  return _m.format('ll');
}

export function getAnonymousUserPermission(permissions) {
  return permissions.filter(function(perm){
    if (perm.user__username === undefined) {
      perm.user__username = perm.user.match(/\/users\/(.*)\//)[1];
    }
    return perm.user__username === constants.ANON_USERNAME;
  })[0];
}

export function surveyToValidJson(survey) {
  // skip logic references only preserved after initial call
  // to "survey.toFlatJSON()"
  survey.toFlatJSON();
  // returning the result of the second call to "toFlatJSON()"
  return JSON.stringify(survey.toFlatJSON());
}


/**
 * This function reverses what `nullifyTranslations` did to the form data.
 * @param {string} surveyDataJSON
 * @param {object} assetContent
 * @return {string} fixed surveyDataJSON
 */
export function unnullifyTranslations(surveyDataJSON, assetContent) {
  let surveyData = JSON.parse(surveyDataJSON);

  let translatedProps = [];
  if (assetContent.translated) {
     translatedProps = assetContent.translated;
  }

  // TRANSLATIONS HACK (Part 2/2):
  // set default_language
  let defaultLang = assetContent.translations_0;
  if (!defaultLang) {
    defaultLang = null;
  }
  if (!surveyData.settings[0].default_language && defaultLang !== null) {
    surveyData.settings[0].default_language = defaultLang;
  }

  if (defaultLang !== null) {
    // replace every "translatedProp" with "translatedProp::defaultLang"
    if (surveyData.choices) {
      surveyData.choices.forEach((choice) => {
        translatedProps.forEach((translatedProp) => {
          if (typeof choice[translatedProp] !== 'undefined') {
            choice[`${translatedProp}::${defaultLang}`] = choice[translatedProp];
            delete choice[translatedProp];
          }
        });
      });
    }
    if (surveyData.survey) {
      surveyData.survey.forEach((surveyRow) => {
        translatedProps.forEach((translatedProp) => {
          if (typeof surveyRow[translatedProp] !== 'undefined') {
            if (typeof surveyData.settings[0] !== 'undefined'
                && typeof surveyData.settings[0].style === 'string'
                && surveyData.settings[0].style.includes('theme-grid')
                && surveyRow.type === 'begin_group'
                && surveyRow[translatedProp] === null || surveyRow[translatedProp] === '') {
              delete surveyRow[translatedProp];
            }
            surveyRow[`${translatedProp}::${defaultLang}`] = surveyRow[translatedProp];
            delete surveyRow[translatedProp];
          }
        });
      });
    }
  }

  return JSON.stringify(surveyData);
}
{'fraction_non_alphanumeric': 0.12893590541381456, 'fraction_numerical': 0.003235843186060983, 'mean_word_length': 3.6263672999424297, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 11, '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': '2803139', 'n_tokens_mistral': 2446, 'n_tokens_neox': 2375, 'n_words': 559}