<commit_before>/* eslint-disable react/jsx-filename-extension */
/* eslint-disable react/prop-types */
/* eslint-disable react/prefer-stateless-function */
/* eslint-disable import/no-named-as-default */

import React from "react";
import { withStyles } from "@material-ui/core/styles";
import ExpansionPanel from "@material-ui/core/ExpansionPanel";
import ExpansionPanelSummary from "@material-ui/core/ExpansionPanelSummary";
import ExpansionPanelDetails from "@material-ui/core/ExpansionPanelDetails";
import Typography from "@material-ui/core/Typography";
import ExpandMoreIcon from "@material-ui/icons/ExpandMore";
import FormControlLabel from "@material-ui/core/FormControlLabel";
import IconWarning from "@material-ui/icons/Warning";
import IconError from "@material-ui/icons/Error";
import classnames from "classnames";
import InputField from "../InputField";
import InputFieldMultiSelectValue from "../InputField/InputFieldMultiSelectValue";
import InputFieldSelect from "../InputField/InputFieldSelectCustom";
import CustomRow from "../Custom/CustomRow";
import CustomColumn from "../Custom/CustomColumn";
import IconInfo from "../Icon/IconInfo";
import MaterialSwitch from "../MaterialComponents/Switch";
import CheckboxDefault from "../MaterialComponents/Checkbox";
import ButtonCustom from "../Button/ButtonCustom";
import { MultiSelectHolder } from "../";
import MultiSelectContainer from "../MultiSelectHolder/MultiSelectContainer";
import transformStringArrayIntoObjects from "../MultiSelectPanel/helper";

const styles = theme => ({
  root: {
    width: "100%"
  },
  heading: {
    fontSize: theme.typography.pxToRem(15),
    fontWeight: "700"
  },
  customStyle: {
    margin: "0 !important",
    backgroundColor: "transparent",
    boxShadow: "none",
    borderBottom: "1px solid #bcbdc0",
    borderRadius: "0 !important"
  },
  additionalStyles: {
    display: "block"
  },
  helperStyles: {
    paddingBottom: 0
  },
  containerStyles: {
    padding: "10px 24px 10px 24px"
  }
});

class BAForm extends React.Component {
  render() {
    const {
      classes,
      values,
      centreonImages,
      valueChanged = () => {},
      notificationOptionChanged = () => {},
      additionalPollerChanged = () => {},
      errors,
      toggleMultiselect = () => {},
      eventHandlerCommands,
      escalations,
      timeperiods,
      kpis,
      contactGroups,
      businessViews,
      remoteServers,
      selectedMultiselect
    } = this.props;
    return (

          <CustomRow>
            <CustomColumn customColumn="md-6">
              <InputField
                placeholder="Add a description"
                type="text"
                name="description"
                error={errors.description}
                value={values.description}
                onChange={event => {
                  valueChanged("description", event);
                }}
              />
            </CustomColumn>
            <CustomColumn customColumn="md-6">
              <InputFieldSelect
                icons={true}
                options={centreonImages}
                value={values.icon}
                error={errors.icon}
                customStyle="no-margin"
                onChange={event => {
                  valueChanged("icon", event);
                }}
                domainPath={"."}
              />
            </CustomColumn>
            <CustomColumn customColumn="md-6">
              <CustomColumn customColumn="md-12" additionalStyles={["p-0"]}>
                <IconInfo iconText="Automatically inherit KPI downtimes" />
              </CustomColumn>
              <FormControlLabel
                style={{
                  marginLeft: 0
                }}
                control={
                  <MaterialSwitch
                    value={values.inherit_kpi_downtimes}
                    checked={values.inherit_kpi_downtimes}
                    error={errors.inherit_kpi_downtimes}
                    size={"small"}
                    onChange={(event, value) => {
                      valueChanged("inherit_kpi_downtimes", value);
                    }}
                  />
                }
                label={values.inherit_kpi_downtimes ? "Yes" : "No"}
              />
            </CustomColumn>
            <CustomColumn customColumn="md-6">
              <IconInfo iconText="Display on remote server" />
              <InputFieldSelect
                options={remoteServers}
                value={values.additional_poller}
                error={errors.additional_poller}
                onChange={event => {
                  additionalPollerChanged(event);
                }}
              />
            </CustomColumn>
          </CustomRow>

        <ExpansionPanel
          expanded={errors.level_c || errors.level_w}
          className={classes.customStyle}
        >
          <ExpansionPanelSummary
            expandIcon={<ExpandMoreIcon />}
            aria-controls="panel1a-content"
            id="panel1a-header"
          >
            <Typography className={classes.heading}>Indicator</Typography>
          </ExpansionPanelSummary>
          <ExpansionPanelDetails
            className={classnames(
              classes.additionalStyles,
              classes.helperStyles
            )}
          >
            <CustomRow additionalStyles={["mb-0"]}>
              <CustomColumn customColumn="md-6" additionalStyles={["mb-0"]}>
                <IconInfo iconText="Status calculation method" />
                <InputFieldSelect
                  value={1}
                  options={[{ id: 1, name: "Impact", alias: "impact" }]}
                  disabled
                />
              </CustomColumn>
              <CustomColumn customColumn="md-3" additionalStyles={["mb-0"]}>
                <IconInfo iconText="Warning threshold" />
                <CustomRow additionalStyles={["mt-05", "mb-0"]}>
                  <CustomColumn
                    customColumn="md-3"
                    additionalStyles={["mt-03"]}
                  >
                    <IconWarning style={{ color: "#FF9913" }} />
                  </CustomColumn>
                  <CustomColumn customColumn="md-9">
                    <InputField
                      type="number"
                      name="level_w"
                      value={values.level_w}
                      error={errors.level_w}
                      onChange={event => {
                        valueChanged("level_w", event);
                      }}
                    />
                  </CustomColumn>
                </CustomRow>
              </CustomColumn>
              <CustomColumn customColumn="md-3" additionalStyles={["mb-0"]}>
                <IconInfo iconText="Critical threshold" />
                <CustomRow additionalStyles={["mt-05"]}>
                  <CustomColumn
                    customColumn="md-3"
                    additionalStyles={["mt-03"]}
                  >
                    <IconError style={{ color: "#E00B3D" }} />
                  </CustomColumn>
                  <CustomColumn customColumn="md-9">
                    <InputField
                      type="text"
                      name="level_c"
                      value={values.level_c}
                      error={errors.level_c}
                      onChange={event => {
                        valueChanged("level_c", event);
                      }}
                    />
                  </CustomColumn>
                </CustomRow>
              </CustomColumn>
            </CustomRow>
          </ExpansionPanelDetails>
          <ExpansionPanelDetails className={classes.additionalStyles}>
            <MultiSelectContainer
              label={"Indicators"}
              values={values.bam_kpi}
              selected={selectedMultiselect == "bam_kpi"}
              error={errors.bam_kpi}
              onEdit={() => {
                toggleMultiselect("bam_kpi");
              }}
              emptyInfo={"Click to link indicators"}
            />
          </ExpansionPanelDetails>
        </ExpansionPanel>
        <ExpansionPanel className={classes.customStyle}>
          <ExpansionPanelSummary
            expandIcon={<ExpandMoreIcon />}
            aria-controls="panel2a-content"
            id="panel2a-header"
          >
            <Typography className={classes.heading}>Business View</Typography>
          </ExpansionPanelSummary>
          <ExpansionPanelDetails className={classes.additionalStyles}>
            <MultiSelectContainer
              label={"Business views"}
              values={transformStringArrayIntoObjects(values.groups)}
              selected={selectedMultiselect == "groups"}
              error={errors.groups}
              onEdit={() => {
                toggleMultiselect("groups");
              }}
              emptyInfo={"Click to link business view(s)"}
            />
          </ExpansionPanelDetails>
        </ExpansionPanel>
        <ExpansionPanel className={classes.customStyle}>
          <ExpansionPanelSummary
            expandIcon={<ExpandMoreIcon />}
            aria-controls="panel3a-content"
            id="panel3a-header"
          >
            <Typography className={classes.heading}>Notification</Typography>
          </ExpansionPanelSummary>
          <ExpansionPanelDetails className={classes.additionalStyles}>
            <CustomRow>
              <CustomColumn customColumn="md-6">
                <CustomColumn customColumn="md-12" additionalStyles={["p-0"]}>
                  <IconInfo iconText="Activate notifications" />
                </CustomColumn>
                <FormControlLabel
                  style={{
                    marginLeft: 0
                  }}
                  control={
                    <MaterialSwitch
                      value={values.notifications_enabled}
                      checked={values.notifications_enabled}
                      error={errors.notifications_enabled}
                      size={"small"}
                      onChange={(event, value) => {
                        valueChanged("notifications_enabled", value);
                      }}
                    />
                  }
                  label={values.notifications_enabled ? "Yes" : "No"}
                />
              </CustomColumn>
              <CustomColumn customColumn="md-6">
                <InputField
                  placeholder="*60 seconds"
                  type="text"
                  name="test"
                  label="Interval (*60 seconds)"
                  value={values.notification_interval}
                  error={errors.notification_interval}
                  onChange={event => {
                    valueChanged("notification_interval", event);
                  }}
                />
              </CustomColumn>
              <CustomColumn customColumn="md-6" additionalStyles={["pr-0"]}>
                <CustomRow additionalStyles={["m-0"]}>
                  <CustomColumn customColumn="md-6">
                    <CheckboxDefault
                      label="Recovery"
                      checked={values.notification_options.indexOf("r") > -1}
                      onChange={() => {
                        notificationOptionChanged("r");
                      }}
                      error={errors.notification_options}
                    />
                  </CustomColumn>
                  <CustomColumn customColumn="md-6">
                    <CheckboxDefault
                      label="Warning"
                      checked={values.notification_options.indexOf("w") > -1}
                      onChange={() => {
                        notificationOptionChanged("w");
                      }}
                      error={errors.notification_options}
                    />
                  </CustomColumn>
                  <CustomColumn customColumn="md-6">
                    <CheckboxDefault
                      label="Critical"
                      checked={values.notification_options.indexOf("c") > -1}
                      onChange={() => {
                        notificationOptionChanged("c");
                      }}
                      error={errors.notification_options}
                    />
                  </CustomColumn>
                  <CustomColumn customColumn="md-6">
                    <CheckboxDefault
                      label="Flapping"
                      checked={values.notification_options.indexOf("f") > -1}
                      onChange={() => {
                        notificationOptionChanged("f");
                      }}
                      error={errors.notification_options}
                    />
                  </CustomColumn>
                </CustomRow>
              </CustomColumn>
              <CustomColumn customColumn="md-6">
                <IconInfo iconText="Time period" />
                <InputFieldSelect
                  options={timeperiods}
                  value={values.notification_period}
                  error={errors.notification_period}
                  onChange={event => {
                    valueChanged("notification_period", event);
                  }}
                />
              </CustomColumn>
            </CustomRow>
          </ExpansionPanelDetails>
          <ExpansionPanelDetails className={classes.additionalStyles}>
            <MultiSelectContainer
              label={"Contact groups"}
              values={transformStringArrayIntoObjects(values.bam_contact)}
              selected={selectedMultiselect == "bam_contact"}
              error={errors.bam_contact}
              onEdit={() => {
                toggleMultiselect("bam_contact");
              }}
              emptyInfo={"Click to link contact group(s)"}
            />
          </ExpansionPanelDetails>
          <ExpansionPanelDetails className={classes.additionalStyles}>
            <MultiSelectContainer
              label={"Escalations"}
              values={transformStringArrayIntoObjects(values.bam_esc)}
              selected={selectedMultiselect == "bam_esc"}
              onEdit={() => {
                toggleMultiselect("bam_esc");
              }}
              error={errors.bam_esc}
            />
          </ExpansionPanelDetails>
        </ExpansionPanel>
        <ExpansionPanel className={classes.customStyle}>
          <ExpansionPanelSummary
            expandIcon={<ExpandMoreIcon />}
            aria-controls="panel4a-content"
            id="panel4a-header"
          >
            <Typography className={classes.heading}>Reporting</Typography>
          </ExpansionPanelSummary>
          <ExpansionPanelDetails className={classes.additionalStyles}>
            <CustomRow>
              <CustomColumn customColumn="md-6">
                <InputField
                  placeholder="(0-100%)"
                  type="text"
                  name="test"
                  label="SLA warning percentage thresholds"
                  value={values.sla_month_percent_warn}
                  error={errors.sla_month_percent_warn}
                  onChange={event => {
                    valueChanged("sla_month_percent_warn", event);
                  }}
                />
              </CustomColumn>
              <CustomColumn customColumn="md-6">
                <InputField
                  placeholder="minutes"
                  type="text"
                  name="test"
                  label="SLA warning duration threshold"
                  value={values.sla_month_duration_warn}
                  error={errors.sla_month_duration_warn}
                  onChange={event => {
                    valueChanged("sla_month_duration_warn", event);
                  }}
                />
              </CustomColumn>
              <CustomColumn customColumn="md-6">
                <InputField
                  placeholder="(0-100%)"
                  type="text"
                  name="test"
                  label="SLA critical percentage thresholds"
                  value={values.sla_month_percent_crit}
                  error={errors.sla_month_percent_crit}
                  onChange={event => {
                    valueChanged("sla_month_percent_crit", event);
                  }}
                />
              </CustomColumn>
              <CustomColumn customColumn="md-6">
                <InputField
                  placeholder="minutes"
                  type="text"
                  name="test"
                  label="SLA critical duration threshold"
                  value={values.sla_month_duration_crit}
                  error={errors.sla_month_duration_crit}
                  onChange={event => {
                    valueChanged("sla_month_duration_crit", event);
                  }}
                />
              </CustomColumn>
            </CustomRow>
            <MultiSelectContainer
              label={
                "Extra reporting time periods used in Centreon BI indicators"
              }
              values={transformStringArrayIntoObjects(
                values.reporting_timeperiods
              )}
              selected={selectedMultiselect == "reporting_timeperiods"}
              error={errors.reporting_timeperiods}
              onEdit={() => {
                toggleMultiselect("reporting_timeperiods");
              }}
              emptyInfo={"Click to add time period(s)"}
            />
          </ExpansionPanelDetails>
        </ExpansionPanel>
        <ExpansionPanel className={classes.customStyle}>
          <ExpansionPanelSummary
            expandIcon={<ExpandMoreIcon />}
            aria-controls="panel6a-content"
            id="panel6a-header"
          >
            <Typography className={classes.heading}>Event handler</Typography>
          </ExpansionPanelSummary>
          <ExpansionPanelDetails className={classes.additionalStyles}>
            <CustomRow additionalStyles={["w-100"]}>
              <CustomColumn customColumn="md-6">
                <CustomColumn customColumn="md-12" additionalStyles={["p-0"]}>
                  <IconInfo iconText="Activate event handling" />
                </CustomColumn>
                <FormControlLabel
                  style={{
                    marginLeft: 0
                  }}
                  control={
                    <MaterialSwitch
                      value={values.event_handler_enabled}
                      checked={values.event_handler_enabled}
                      error={errors.event_handler_enabled}
                      size={"small"}
                      onChange={(event, value) => {
                        valueChanged("event_handler_enabled", value);
                      }}
                    />
                  }
                  label={values.event_handler_enabled ? "Yes" : "No"}
                />
              </CustomColumn>
              <CustomColumn customColumn="md-6">
                <IconInfo iconText="Event handler command" />
                <InputFieldSelect
                  options={eventHandlerCommands}
                  value={values.event_handler_command}
                  error={errors.event_handler_command}
                  onChange={event => {
                    valueChanged("event_handler_command", event);
                  }}
                />
              </CustomColumn>
            </CustomRow>
          </ExpansionPanelDetails>
        </ExpansionPanel>

    );
  }
}

export default withStyles(styles)(BAForm);
<commit_msg>coordinates<commit_after>/* eslint-disable react/jsx-filename-extension */
/* eslint-disable react/prop-types */
/* eslint-disable react/prefer-stateless-function */
/* eslint-disable import/no-named-as-default */

import React from "react";
import { withStyles } from "@material-ui/core/styles";
import ExpansionPanel from "@material-ui/core/ExpansionPanel";
import ExpansionPanelSummary from "@material-ui/core/ExpansionPanelSummary";
import ExpansionPanelDetails from "@material-ui/core/ExpansionPanelDetails";
import Typography from "@material-ui/core/Typography";
import ExpandMoreIcon from "@material-ui/icons/ExpandMore";
import FormControlLabel from "@material-ui/core/FormControlLabel";
import IconWarning from "@material-ui/icons/Warning";
import IconError from "@material-ui/icons/Error";
import classnames from "classnames";
import InputField from "../InputField";
import InputFieldMultiSelectValue from "../InputField/InputFieldMultiSelectValue";
import InputFieldSelect from "../InputField/InputFieldSelectCustom";
import CustomRow from "../Custom/CustomRow";
import CustomColumn from "../Custom/CustomColumn";
import IconInfo from "../Icon/IconInfo";
import MaterialSwitch from "../MaterialComponents/Switch";
import CheckboxDefault from "../MaterialComponents/Checkbox";
import ButtonCustom from "../Button/ButtonCustom";
import { MultiSelectHolder } from "../";
import MultiSelectContainer from "../MultiSelectHolder/MultiSelectContainer";
import transformStringArrayIntoObjects from "../MultiSelectPanel/helper";

const styles = theme => ({
  root: {
    width: "100%"
  },
  heading: {
    fontSize: theme.typography.pxToRem(15),
    fontWeight: "700"
  },
  customStyle: {
    margin: "0 !important",
    backgroundColor: "transparent",
    boxShadow: "none",
    borderBottom: "1px solid #bcbdc0",
    borderRadius: "0 !important"
  },
  additionalStyles: {
    display: "block"
  },
  helperStyles: {
    paddingBottom: 0
  },
  containerStyles: {
    padding: "10px 24px 10px 24px"
  }
});

class BAForm extends React.Component {
  render() {
    const {
      classes,
      values,
      centreonImages,
      valueChanged = () => {},
      notificationOptionChanged = () => {},
      additionalPollerChanged = () => {},
      errors,
      toggleMultiselect = () => {},
      eventHandlerCommands,
      escalations,
      timeperiods,
      kpis,
      contactGroups,
      businessViews,
      remoteServers,
      selectedMultiselect
    } = this.props;
    return (

          <CustomRow>
            <CustomColumn customColumn="md-6">
              <InputField
                placeholder="Add a description"
                type="text"
                name="description"
                error={errors.description}
                value={values.description}
                onChange={event => {
                  valueChanged("description", event);
                }}
              />
            </CustomColumn>
            <CustomColumn customColumn="md-6">
              <InputFieldSelect
                icons={true}
                options={centreonImages}
                value={values.icon}
                error={errors.icon}
                customStyle="no-margin"
                onChange={event => {
                  valueChanged("icon", event);
                }}
                domainPath={"."}
              />
            </CustomColumn>
          </CustomRow>

        <ExpansionPanel
          expanded={errors.level_c || errors.level_w}
          className={classes.customStyle}
        >
          <ExpansionPanelSummary
            expandIcon={<ExpandMoreIcon />}
            aria-controls="panel1a-content"
            id="panel1a-header"
          >
            <Typography className={classes.heading}>Indicator</Typography>
          </ExpansionPanelSummary>
          <ExpansionPanelDetails
            className={classnames(
              classes.additionalStyles,
              classes.helperStyles
            )}
          >
            <CustomRow additionalStyles={["mb-0"]}>
            <CustomColumn customColumn="md-6">
              <CustomColumn customColumn="md-12" additionalStyles={["p-0"]}>
                <IconInfo iconText="Automatically inherit indicators" />
              </CustomColumn>
              <FormControlLabel
                style={{
                  marginLeft: 0
                }}
                control={
                  <MaterialSwitch
                    value={values.inherit_kpi_downtimes}
                    checked={values.inherit_kpi_downtimes}
                    error={errors.inherit_kpi_downtimes}
                    size={"small"}
                    onChange={(event, value) => {
                      valueChanged("inherit_kpi_downtimes", value);
                    }}
                  />
                }
                label={values.inherit_kpi_downtimes ? "Yes" : "No"}
              />
            </CustomColumn>
              <CustomColumn customColumn="md-6" additionalStyles={["mb-0"]}>
                <IconInfo iconText="Status calculation method" />
                <InputFieldSelect
                  value={1}
                  options={[{ id: 1, name: "Impact", alias: "impact" }]}
                  disabled
                />
              </CustomColumn>
              <CustomColumn customColumn="md-3" additionalStyles={["mb-0"]}>
                <IconInfo iconText="Warning threshold" />
                <CustomRow additionalStyles={["mt-05", "mb-0"]}>
                  <CustomColumn
                    customColumn="md-3"
                    additionalStyles={["mt-03"]}
                  >
                    <IconWarning style={{ color: "#FF9913" }} />
                  </CustomColumn>
                  <CustomColumn customColumn="md-9">
                    <InputField
                      type="number"
                      name="level_w"
                      value={values.level_w}
                      error={errors.level_w}
                      onChange={event => {
                        valueChanged("level_w", event);
                      }}
                    />
                  </CustomColumn>
                </CustomRow>
              </CustomColumn>
              <CustomColumn customColumn="md-3" additionalStyles={["mb-0"]}>
                <IconInfo iconText="Critical threshold" />
                <CustomRow additionalStyles={["mt-05"]}>
                  <CustomColumn
                    customColumn="md-3"
                    additionalStyles={["mt-03"]}
                  >
                    <IconError style={{ color: "#E00B3D" }} />
                  </CustomColumn>
                  <CustomColumn customColumn="md-9">
                    <InputField
                      type="text"
                      name="level_c"
                      value={values.level_c}
                      error={errors.level_c}
                      onChange={event => {
                        valueChanged("level_c", event);
                      }}
                    />
                  </CustomColumn>
                </CustomRow>
              </CustomColumn>
            </CustomRow>
          </ExpansionPanelDetails>
          <ExpansionPanelDetails className={classes.additionalStyles}>
            <MultiSelectContainer
              label={"Indicators"}
              values={values.bam_kpi}
              selected={selectedMultiselect == "bam_kpi"}
              error={errors.bam_kpi}
              onEdit={() => {
                toggleMultiselect("bam_kpi");
              }}
              emptyInfo={"Click to link indicators"}
            />
          </ExpansionPanelDetails>
        </ExpansionPanel>
        <ExpansionPanel className={classes.customStyle}>
          <ExpansionPanelSummary
            expandIcon={<ExpandMoreIcon />}
            aria-controls="panel2a-content"
            id="panel2a-header"
          >
            <Typography className={classes.heading}>Business View</Typography>
          </ExpansionPanelSummary>
          <ExpansionPanelDetails className={classes.additionalStyles}>
            <MultiSelectContainer
              label={"Business views"}
              values={transformStringArrayIntoObjects(values.groups)}
              selected={selectedMultiselect == "groups"}
              error={errors.groups}
              onEdit={() => {
                toggleMultiselect("groups");
              }}
              emptyInfo={"Click to link business view(s)"}
            />
          </ExpansionPanelDetails>
        </ExpansionPanel>
        <ExpansionPanel className={classes.customStyle}>
          <ExpansionPanelSummary
            expandIcon={<ExpandMoreIcon />}
            aria-controls="panel2a-content"
            id="panel2a-header"
          >
            <Typography className={classes.heading}>Display</Typography>
          </ExpansionPanelSummary>
          <ExpansionPanelDetails className={classes.additionalStyles}>
          <CustomRow>
            <CustomColumn customColumn="md-6">
              <IconInfo iconText="Display on remote server" />
              <InputFieldSelect
                options={remoteServers}
                value={values.additional_poller}
                error={errors.additional_poller}
                onChange={event => {
                  additionalPollerChanged(event);
                }}
              />
            </CustomColumn>
            <CustomColumn customColumn="md-6">
              <IconInfo iconText="Geo-coordinates" />
              <InputField
                placeholder="Add a geo-coordinates"
                type="text"
                name="ba_geo_coords"
                error={errors.ba_geo_coords}
                value={values.ba_geo_coords}
                style={{
                  marginTop:'6px'
                }}
                onChange={event => {
                  valueChanged("ba_geo_coords", event);
                }}
              />
            </CustomColumn>
          </CustomRow>
          </ExpansionPanelDetails>
        </ExpansionPanel>
        <ExpansionPanel className={classes.customStyle}>
          <ExpansionPanelSummary
            expandIcon={<ExpandMoreIcon />}
            aria-controls="panel3a-content"
            id="panel3a-header"
          >
            <Typography className={classes.heading}>Notification</Typography>
          </ExpansionPanelSummary>
          <ExpansionPanelDetails className={classes.additionalStyles}>
            <CustomRow>
              <CustomColumn customColumn="md-6">
                <CustomColumn customColumn="md-12" additionalStyles={["p-0"]}>
                  <IconInfo iconText="Activate notifications" />
                </CustomColumn>
                <FormControlLabel
                  style={{
                    marginLeft: 0
                  }}
                  control={
                    <MaterialSwitch
                      value={values.notifications_enabled}
                      checked={values.notifications_enabled}
                      error={errors.notifications_enabled}
                      size={"small"}
                      onChange={(event, value) => {
                        valueChanged("notifications_enabled", value);
                      }}
                    />
                  }
                  label={values.notifications_enabled ? "Yes" : "No"}
                />
              </CustomColumn>
              <CustomColumn customColumn="md-6">
                <InputField
                  placeholder="*60 seconds"
                  type="text"
                  name="test"
                  label="Interval (*60 seconds)"
                  value={values.notification_interval}
                  error={errors.notification_interval}
                  onChange={event => {
                    valueChanged("notification_interval", event);
                  }}
                />
              </CustomColumn>
              <CustomColumn customColumn="md-6" additionalStyles={["pr-0"]}>
                <CustomRow additionalStyles={["m-0"]}>
                  <CustomColumn customColumn="md-6">
                    <CheckboxDefault
                      label="Recovery"
                      checked={values.notification_options.indexOf("r") > -1}
                      onChange={() => {
                        notificationOptionChanged("r");
                      }}
                      error={errors.notification_options}
                    />
                  </CustomColumn>
                  <CustomColumn customColumn="md-6">
                    <CheckboxDefault
                      label="Warning"
                      checked={values.notification_options.indexOf("w") > -1}
                      onChange={() => {
                        notificationOptionChanged("w");
                      }}
                      error={errors.notification_options}
                    />
                  </CustomColumn>
                  <CustomColumn customColumn="md-6">
                    <CheckboxDefault
                      label="Critical"
                      checked={values.notification_options.indexOf("c") > -1}
                      onChange={() => {
                        notificationOptionChanged("c");
                      }}
                      error={errors.notification_options}
                    />
                  </CustomColumn>
                  <CustomColumn customColumn="md-6">
                    <CheckboxDefault
                      label="Flapping"
                      checked={values.notification_options.indexOf("f") > -1}
                      onChange={() => {
                        notificationOptionChanged("f");
                      }}
                      error={errors.notification_options}
                    />
                  </CustomColumn>
                </CustomRow>
              </CustomColumn>
              <CustomColumn customColumn="md-6">
                <IconInfo iconText="Time period" />
                <InputFieldSelect
                  options={timeperiods}
                  value={values.notification_period}
                  error={errors.notification_period}
                  onChange={event => {
                    valueChanged("notification_period", event);
                  }}
                />
              </CustomColumn>
            </CustomRow>
          </ExpansionPanelDetails>
          <ExpansionPanelDetails className={classes.additionalStyles}>
            <MultiSelectContainer
              label={"Contact groups"}
              values={transformStringArrayIntoObjects(values.bam_contact)}
              selected={selectedMultiselect == "bam_contact"}
              error={errors.bam_contact}
              onEdit={() => {
                toggleMultiselect("bam_contact");
              }}
              emptyInfo={"Click to link contact group(s)"}
            />
          </ExpansionPanelDetails>
          <ExpansionPanelDetails className={classes.additionalStyles}>
            <MultiSelectContainer
              label={"Escalations"}
              values={transformStringArrayIntoObjects(values.bam_esc)}
              selected={selectedMultiselect == "bam_esc"}
              onEdit={() => {
                toggleMultiselect("bam_esc");
              }}
              error={errors.bam_esc}
            />
          </ExpansionPanelDetails>
        </ExpansionPanel>
        <ExpansionPanel className={classes.customStyle}>
          <ExpansionPanelSummary
            expandIcon={<ExpandMoreIcon />}
            aria-controls="panel4a-content"
            id="panel4a-header"
          >
            <Typography className={classes.heading}>Reporting</Typography>
          </ExpansionPanelSummary>
          <ExpansionPanelDetails className={classes.additionalStyles}>
            <CustomRow>
              <CustomColumn customColumn="md-6">
                <InputField
                  placeholder="(0-100%)"
                  type="text"
                  name="test"
                  label="SLA warning percentage thresholds"
                  value={values.sla_month_percent_warn}
                  error={errors.sla_month_percent_warn}
                  onChange={event => {
                    valueChanged("sla_month_percent_warn", event);
                  }}
                />
              </CustomColumn>
              <CustomColumn customColumn="md-6">
                <InputField
                  placeholder="minutes"
                  type="text"
                  name="test"
                  label="SLA warning duration threshold"
                  value={values.sla_month_duration_warn}
                  error={errors.sla_month_duration_warn}
                  onChange={event => {
                    valueChanged("sla_month_duration_warn", event);
                  }}
                />
              </CustomColumn>
              <CustomColumn customColumn="md-6">
                <InputField
                  placeholder="(0-100%)"
                  type="text"
                  name="test"
                  label="SLA critical percentage thresholds"
                  value={values.sla_month_percent_crit}
                  error={errors.sla_month_percent_crit}
                  onChange={event => {
                    valueChanged("sla_month_percent_crit", event);
                  }}
                />
              </CustomColumn>
              <CustomColumn customColumn="md-6">
                <InputField
                  placeholder="minutes"
                  type="text"
                  name="test"
                  label="SLA critical duration threshold"
                  value={values.sla_month_duration_crit}
                  error={errors.sla_month_duration_crit}
                  onChange={event => {
                    valueChanged("sla_month_duration_crit", event);
                  }}
                />
              </CustomColumn>
            </CustomRow>
            <MultiSelectContainer
              label={
                "Extra reporting time periods used in Centreon BI indicators"
              }
              values={transformStringArrayIntoObjects(
                values.reporting_timeperiods
              )}
              selected={selectedMultiselect == "reporting_timeperiods"}
              error={errors.reporting_timeperiods}
              onEdit={() => {
                toggleMultiselect("reporting_timeperiods");
              }}
              emptyInfo={"Click to add time period(s)"}
            />
          </ExpansionPanelDetails>
        </ExpansionPanel>
        <ExpansionPanel className={classes.customStyle}>
          <ExpansionPanelSummary
            expandIcon={<ExpandMoreIcon />}
            aria-controls="panel6a-content"
            id="panel6a-header"
          >
            <Typography className={classes.heading}>Event handler</Typography>
          </ExpansionPanelSummary>
          <ExpansionPanelDetails className={classes.additionalStyles}>
            <CustomRow additionalStyles={["w-100"]}>
              <CustomColumn customColumn="md-6">
                <CustomColumn customColumn="md-12" additionalStyles={["p-0"]}>
                  <IconInfo iconText="Activate event handling" />
                </CustomColumn>
                <FormControlLabel
                  style={{
                    marginLeft: 0
                  }}
                  control={
                    <MaterialSwitch
                      value={values.event_handler_enabled}
                      checked={values.event_handler_enabled}
                      error={errors.event_handler_enabled}
                      size={"small"}
                      onChange={(event, value) => {
                        valueChanged("event_handler_enabled", value);
                      }}
                    />
                  }
                  label={values.event_handler_enabled ? "Yes" : "No"}
                />
              </CustomColumn>
              <CustomColumn customColumn="md-6">
                <IconInfo iconText="Event handler command" />
                <InputFieldSelect
                  options={eventHandlerCommands}
                  value={values.event_handler_command}
                  error={errors.event_handler_command}
                  onChange={event => {
                    valueChanged("event_handler_command", event);
                  }}
                />
              </CustomColumn>
            </CustomRow>
          </ExpansionPanelDetails>
        </ExpansionPanel>

    );
  }
}

export default withStyles(styles)(BAForm);
<|endoftext|>


<commit_before>$(document).ready(function () {
    let xhttp = new XMLHttpRequest();

    // Settings
    const NB_ENTRIES = 10;

    // Makes the request to get the data
    xhttp.open("GET", "https://raw.githubusercontent.com/lassalleloan/githubAnalytic-static/master/docs/data/data.json");
    xhttp.responseType = "json";
    xhttp.send();

    // Callback function when the state is changed
    xhttp.onreadystatechange = () => {

        // If everything is okay
        if (xhttp.readyState === XMLHttpRequest.DONE && xhttp.status === 200) {

            let object = xhttp.response;

            // Add dynamically all the repos to the table
            for (let i = 0; i < object.length; i++) {
                $("table").append(`<tr><td id="name">${object[i].name}</td><td id="nb_issues">${object[i].nb_issues}</td></tr>`);
            }

            // Call the drawChart function to draw the chart with de acquired data
            drawChart(object);
        }
    };

});<commit_msg>Test to understand<commit_after>$(document).ready(function () {
    let xhttp = new XMLHttpRequest();

    // Settings
    const NB_ENTRIES = 10;

    // Makes the request to get the data
    xhttp.open("GET", "https://raw.githubusercontent.com/lassalleloan/githubAnalytic-static/master/docs/data/data.json");
    xhttp.responseType = "json";
    xhttp.send();

    // Callback function when the state is changed
    xhttp.onreadystatechange = () => {

        // If everything is okay
        if (xhttp.readyState === XMLHttpRequest.DONE && xhttp.status === 200) {

            let object = xhttp.response;

            // Add dynamically all the repos to the table
            for (let i = 0; i < object.length; i++) {
                $("table").append(`<tr><td id="name">${object[i].name}</td><td id="nb_issues">${object[i].nb_issues}</td></tr>`);
            }
        }
    };

});<|endoftext|>


<commit_before>angular.module('catenaccio')
    .controller('PitchController', function (stageService, pitchBuilder, tacticsBuilder, layerService, tactics) {
        'use strict';

        var width = $(window).width() * 0.8;
        var height = $(window).height() * 0.8;
        stageService.newStage(width, height, 'pitch');

        var pitchLayer = pitchBuilder
            .newLayer()
            .addBackground()
            .addGrass()
            .addGoals()
            .addGoalAreas()
            .addPenaltyAreas()
            .addCorners()
            .addHalfwayLine()
            .addCenterCircle()
            .addTouchlineAndGoalLine()
            .build();
        stageService.addLayer(pitchLayer);

        var tacticsLayer = tacticsBuilder
            .newLayer()
            .setTactics(tactics)
            .addFootball()
            .addHomeGoalkeeper()
            .addHomePlayers()
            .addAwayGoalkeeper()
            .addAwayPlayers()
            .addPencils()
            .build();
        layerService.setLayer(tacticsLayer);
    });<commit_msg>Inject<commit_after>angular.module('catenaccio')
    .controller('PitchController',
    function ($window, stageService, pitchBuilder, tacticsBuilder, layerService, tactics) {
        'use strict';

        var width = $($window).width() * 0.8;
        var height = $($window).height() * 0.8;

        stageService.newStage(width, height, 'pitch');

        var pitchLayer = pitchBuilder
            .newLayer()
            .addBackground()
            .addGrass()
            .addGoals()
            .addGoalAreas()
            .addPenaltyAreas()
            .addCorners()
            .addHalfwayLine()
            .addCenterCircle()
            .addTouchlineAndGoalLine()
            .build();
        stageService.addLayer(pitchLayer);

        var tacticsLayer = tacticsBuilder
            .newLayer()
            .setTactics(tactics)
            .addFootball()
            .addHomeGoalkeeper()
            .addHomePlayers()
            .addAwayGoalkeeper()
            .addAwayPlayers()
            .addPencils()
            .build();
        layerService.setLayer(tacticsLayer);
    });<|endoftext|>


<commit_before>/**
 * This file is part of Superdesk.
 *
 * Copyright 2013, 2014 Sourcefabric z.u. and contributors.
 *
 * For the full copyright and license information, please see the
 * AUTHORS and LICENSE files distributed with this source code, or
 * at https://www.sourcefabric.org/superdesk/license
 */
import angular from 'angular';
import _ from 'lodash';
import moment from 'moment';

postsService.$inject = [
    'api',
    '$q',
    'userList'
];

export default function postsService(api, $q, userList) {
    let producersList = [];
    /**
     * Fetch a page of posts
     * @param {string} blog_id - The id of the blog
     * @param {object} filters - (available: {boolean} 'status', {string} 'updatedAfter')
     * @param {integer} max_results - maximum number of results per page
     * @param {integer} page - page index
     */
    function getPosts(blog_id, filters, max_results, page) {
        filters = filters || {};
        page = page || 1;
        max_results = max_results || 15;

        // excludeDeleted: default set to true
        filters.excludeDeleted = angular.isDefined(filters.excludeDeleted) ? filters.excludeDeleted : true;
        var posts_criteria = {
            source: {
                query: {filtered: {filter: {
                    and: []
                }}}
            },
            page: page,
            max_results: max_results
        };
        // filters.excludeDeleted
        if (filters.excludeDeleted) {
            posts_criteria.source.query.filtered.filter.and.push({not: {term: {deleted: true}}});
        }
        // filters.sort
        if (angular.isDefined(filters.sort)) {
            // this converts the format '-_created' to the elasticsearch one
            var order = 'asc';
            if (filters.sort.charAt(0) === '-') {
                filters.sort = filters.sort.slice(1);
                order = 'desc';
            }
            var sort = {};
            sort[filters.sort] = {order: order, missing: '_last', unmapped_type: 'long'};
            posts_criteria.source.sort = [sort];
        }
        // filters.status
        if (angular.isDefined(filters.status)) {
            posts_criteria.source.query.filtered.filter.and.push({term: {post_status: filters.status}});
        }
        // filters.sticky
        if (angular.isDefined(filters.sticky)) {
            posts_criteria.source.query.filtered.filter.and.push({term: {sticky: filters.sticky}});
        }
        // filters.authors
        if (angular.isDefined(filters.authors) && filters.authors.length > 0) {
            posts_criteria.source.query.filtered.filter.and.push({
                or: {
                    filters: filters.authors.map(function(author) {
                        return {term: {original_creator: author}};
                    })
                }
            });
        }
        // filters.updatedAfter
        if (angular.isDefined(filters.updatedAfter)) {
            posts_criteria.source.query.filtered.filter.and.push({
                range: {
                    _updated: {
                        gt: filters.updatedAfter
                    }
                }
            });
        }
        // filters.highlight
        if (angular.isDefined(filters.highlight)) {
            posts_criteria.source.query.filtered.filter.and.push({term: {lb_highlight: filters.highlight}});
        }
        // filters.sticky
        if (angular.isDefined(filters.sticky)) {
            posts_criteria.source.query.filtered.filter.and.push({term: {sticky: filters.sticky}});
        }

        // filters.status
        if (angular.isDefined(filters.syndicationIn)) {
            posts_criteria.source.query.filtered.filter.and.push({
                term: {syndication_in: filters.syndicationIn}
            });
        }

        if (angular.isDefined(filters.noSyndication)) {
            posts_criteria.source.query.filtered.filter.and.push({
                missing: { field: 'syndication_in' }
            });
        }

        return retrievePosts(blog_id, posts_criteria);
    }

    function _completeUser(obj) {
        if (obj.commenter) {
            obj.user = {display_name: obj.commenter};
        } else {
            userList.getUser(obj.original_creator).then(function(user) {
                obj.user = user;
            });
        }
        return obj;
    }
    function _completePost(post) {
        let multipleItems = false;

        if (post.groups[1].refs.length > 1) {
            multipleItems = post.groups[1].refs.length - 1;
        }

        return $q(function(resolve, reject) {
            angular.extend(post, {
                multipleItems: multipleItems,
                // add a `mainItem` field containing the first item
                mainItem: post.groups[1].refs[0],
                items: post.groups[1].refs
            });

            // if an item has a commenter then that post hasComments.
            post.hasComments = _.reduce(post.groups[1].refs, function(is, val) {
                return is || !_.isUndefined(val.item.commenter);
            }, false);
            // `fullDetails` is a business logic that can be compiled from other objects.
            post.fullDetails = post.hasComments;
            // special cases for comments.
            post.showUpdate = (post.content_updated_date !== post.published_date) &&
                               (!post.hasComments) && (post.mainItem.item.item_type !== 'comment');
            angular.forEach(post.items, function(val) {
                if (post.fullDetails) {
                    _completeUser(val.item);
                }
            });
            _completeUser(post.mainItem.item);

            resolve(post);
            //if (post.syndication_in && api.hasOwnProperty('syndicationIn')) {
            //    let isProducerCached = false;

            //    if (producersList.length > 0) {
            //        producersList.forEach((producer) => {
            //            if (post.syndication_in === producer.syndId) {
            //                post.producer_blog_title = producer.blogTitle;
            //                resolve(post);
            //                isProducerCached = true;
            //            }
            //        });
            //    }

            //    if (!isProducerCached) {
            //        api.syndicationIn.getById(post.syndication_in).then((synd) => {
            //            producersList.push({
            //                syndId: post.syndication_in,
            //                blogTitle: synd.producer_blog_title
            //            });

            //            post.producer_blog_title = synd.producer_blog_title;
            //            resolve(post);
            //        }, () => {
            //            resolve(post);
            //        });
            //    }
            //} else {
            //    resolve(post);
            //}
        });
    }

    function retrievePost(post_id) {
        return api.posts.getById(post_id)
            .then(_completePost)
            .then(function(post) {
                return post;
            });
    }

    function retrieveSyndications(posts) {
        let syndIds = [];

        // This means the syndication module is not enabled
        if (!api.hasOwnProperty('syndicationIn')) {
            return posts;
        }

        posts._items.forEach((post) => {
            if (post.syndication_in && syndIds.indexOf(post.syndication_in) === -1) {
                syndIds.push(post.syndication_in);
            }
        });

        return $q
            .all(syndIds.map((syndId) => api.syndicationIn.getById(syndId)))
            .then((syndList) => angular.extend(posts, {
                _items: posts._items.map((post) => {
                    syndList.forEach((synd) => {
                        if (post.syndication_in === synd._id) {
                            post.producer_blog_title = synd.producer_blog_title;
                        }
                    });

                    return post;
                })
            }));
    }

    function retrievePosts(blog_id, posts_criteria) {
        return api('blogs/<regex(\"[a-f0-9]{24}\"):blog_id>/posts', {_id: blog_id})
            .query(posts_criteria)
            .then(retrieveSyndications)
            .then(function(data) {
                return $q.all(data._items.map(_completePost))
                    .then(function(result) {
                        return angular.extend(data, { _items: result });
                    });
            });
    }

    function getLatestUpdateDate(posts) {
        if (!angular.isDefined(posts) || posts.length < 1) {
            return;
        }
        var latest_date, date;
        posts.forEach(function (post) {
            date = moment(post._updated);
            if (angular.isDefined(latest_date)) {
                if (latest_date.diff(date) < 0) {
                    latest_date = date;
                }
            } else {
                latest_date = date;
            }
        });
        return latest_date.utc().format();
    }

    function savePost(blog_id, post_to_update, items, post) {
        post = post || {};
        post.post_status = post.post_status || _.result(post_to_update, 'post_status') || 'open';
        var dfds = [];
        if (items && items.length > 0) {
            // prepare the list of items if needed
            if (angular.isDefined(items) && items.length > 0) {
                if (_.difference(_.keys(items[0]), ['residRef', 'item']).length === 0) {
                    items = _.map(items, function(item) {
                        return item.item;
                    });
                }
            }
            // save every items
            _.each(items, function(item) {
                // because it fails when item has a `_id` field without `_links`
                if (angular.isDefined(item, '_id')) {
                    item = {
                        blog: blog_id,
                        text: item.text,
                        meta: item.meta,
                        group_type: item.group_type,
                        item_type: item.item_type,
                        commenter: item.meta && item.meta.commenter
                    };
                }
                dfds.push(api.items.save(item));
            });
        }
        // save the post
        return $q.all(dfds).then(function(items) {
            if (dfds.length > 0) {
                angular.extend(post, {
                    blog: blog_id,
                    groups: [
                        {
                            id: 'root',
                            refs: [{idRef: 'main'}],
                            role: 'grpRole:NEP'
                        }, {
                            id: 'main',
                            refs: [],
                            role: 'grpRole:Main'
                        }
                    ]
                });
                // update the post reference (links with items)
                _.each(items, function(item) {
                    post.groups[1].refs.push({residRef: item._id});
                });
            }
            var operation;
            if (angular.isDefined(post_to_update)) {
                operation = function updatePost() {
                    return api.posts.save(post_to_update, post);
                };
            } else {
                operation = function createPost() {
                    return api.posts.save(post);
                };
            }
            // return the post saved
            return operation();
        });
    }

    function removePost(post) {
        var deleted = {deleted: true};
        return savePost(post.blog, post, [], deleted);
    }

    return {
        getPosts: getPosts,
        getLatestUpdateDate: getLatestUpdateDate,
        retrievePost: retrievePost,
        savePost: savePost,
        saveDraft: function(blog_id, post, items, sticky, highlight) {
            return savePost(
                blog_id,
                post,
                items,
                {post_status: 'draft', 'sticky': sticky, 'lb_highlight': highlight}
            );
        },
        saveContribution: function(blog_id, post, items, sticky, highlight) {
            return savePost(
                blog_id,
                post,
                items,
                {post_status: 'submitted', 'sticky': sticky, 'lb_highlight': highlight}
            );
        },
        remove: removePost
    };
}
<commit_msg>Some useful comments<commit_after>/**
 * This file is part of Superdesk.
 *
 * Copyright 2013, 2014 Sourcefabric z.u. and contributors.
 *
 * For the full copyright and license information, please see the
 * AUTHORS and LICENSE files distributed with this source code, or
 * at https://www.sourcefabric.org/superdesk/license
 */
import angular from 'angular';
import _ from 'lodash';
import moment from 'moment';

postsService.$inject = [
    'api',
    '$q',
    'userList'
];

export default function postsService(api, $q, userList) {
    let producersList = [];
    /**
     * Fetch a page of posts
     * @param {string} blog_id - The id of the blog
     * @param {object} filters - (available: {boolean} 'status', {string} 'updatedAfter')
     * @param {integer} max_results - maximum number of results per page
     * @param {integer} page - page index
     */
    function getPosts(blog_id, filters, max_results, page) {
        filters = filters || {};
        page = page || 1;
        max_results = max_results || 15;

        // excludeDeleted: default set to true
        filters.excludeDeleted = angular.isDefined(filters.excludeDeleted) ? filters.excludeDeleted : true;
        var posts_criteria = {
            source: {
                query: {filtered: {filter: {
                    and: []
                }}}
            },
            page: page,
            max_results: max_results
        };

        // filters.excludeDeleted
        if (filters.excludeDeleted) {
            posts_criteria.source.query.filtered.filter.and.push({not: {term: {deleted: true}}});
        }
        // filters.sort
        if (angular.isDefined(filters.sort)) {
            // this converts the format '-_created' to the elasticsearch one
            var order = 'asc';

            if (filters.sort.charAt(0) === '-') {
                filters.sort = filters.sort.slice(1);
                order = 'desc';
            }
            var sort = {};

            sort[filters.sort] = {order: order, missing: '_last', unmapped_type: 'long'};
            posts_criteria.source.sort = [sort];
        }
        // filters.status
        if (angular.isDefined(filters.status)) {
            posts_criteria.source.query.filtered.filter.and.push({term: {post_status: filters.status}});
        }
        // filters.sticky
        if (angular.isDefined(filters.sticky)) {
            posts_criteria.source.query.filtered.filter.and.push({term: {sticky: filters.sticky}});
        }
        // filters.authors
        if (angular.isDefined(filters.authors) && filters.authors.length > 0) {
            posts_criteria.source.query.filtered.filter.and.push({
                or: {
                    filters: filters.authors.map(function(author) {
                        return {term: {original_creator: author}};
                    })
                }
            });
        }
        // filters.updatedAfter
        if (angular.isDefined(filters.updatedAfter)) {
            posts_criteria.source.query.filtered.filter.and.push({
                range: {
                    _updated: {
                        gt: filters.updatedAfter
                    }
                }
            });
        }
        // filters.highlight
        if (angular.isDefined(filters.highlight)) {
            posts_criteria.source.query.filtered.filter.and.push({term: {lb_highlight: filters.highlight}});
        }
        // filters.sticky
        if (angular.isDefined(filters.sticky)) {
            posts_criteria.source.query.filtered.filter.and.push({term: {sticky: filters.sticky}});
        }

        // filters.status
        if (angular.isDefined(filters.syndicationIn)) {
            posts_criteria.source.query.filtered.filter.and.push({
                term: {syndication_in: filters.syndicationIn}
            });
        }

        if (angular.isDefined(filters.noSyndication)) {
            posts_criteria.source.query.filtered.filter.and.push({
                missing: {field: 'syndication_in'}
            });
        }

        return retrievePosts(blog_id, posts_criteria);
    }

    function _completeUser(obj) {
        if (obj.commenter) {
            obj.user = {display_name: obj.commenter};
        } else {
            // TODO: way too many requests in there
            // This getUser func is returning a list of users,
            // who would have thought?
            userList.getUser(obj.original_creator).then((user) => {
                obj.user = user;
            });
        }
        return obj;
    }
    function _completePost(post) {
        let multipleItems = false;

        if (post.groups[1].refs.length > 1) {
            multipleItems = post.groups[1].refs.length - 1;
        }

        return $q(function(resolve, reject) {
            angular.extend(post, {
                multipleItems: multipleItems,
                // add a `mainItem` field containing the first item
                mainItem: post.groups[1].refs[0],
                items: post.groups[1].refs
            });

            // if an item has a commenter then that post hasComments.
            post.hasComments = _.reduce(post.groups[1].refs, function(is, val) {
                return is || !_.isUndefined(val.item.commenter);
            }, false);
            // `fullDetails` is a business logic that can be compiled from other objects.
            post.fullDetails = post.hasComments;
            // special cases for comments.
            post.showUpdate = (post.content_updated_date !== post.published_date) &&
                               (!post.hasComments) && (post.mainItem.item.item_type !== 'comment');
            angular.forEach(post.items, function(val) {
                if (post.fullDetails) {
                    _completeUser(val.item);
                }
            });
            _completeUser(post.mainItem.item);

            resolve(post);
        });
    }

    function retrievePost(post_id) {
        return api.posts.getById(post_id)
            .then(_completePost)
            .then(function(post) {
                return post;
            });
    }

    function retrieveSyndications(posts) {
        let syndIds = [];

        // This means the syndication module is not enabled
        if (!api.hasOwnProperty('syndicationIn')) {
            return posts;
        }

        posts._items.forEach((post) => {
            if (post.syndication_in && syndIds.indexOf(post.syndication_in) === -1) {
                syndIds.push(post.syndication_in);
            }
        });

        return $q
            .all(syndIds.map((syndId) => api.syndicationIn.getById(syndId)))
            .then((syndList) => angular.extend(posts, {
                _items: posts._items.map((post) => {
                    syndList.forEach((synd) => {
                        if (post.syndication_in === synd._id) {
                            post.producer_blog_title = synd.producer_blog_title;
                        }
                    });

                    return post;
                })
            }));
    }

    function retrievePosts(blog_id, posts_criteria) {
        return api('blogs/<regex(\"[a-f0-9]{24}\"):blog_id>/posts', {_id: blog_id})
            .query(posts_criteria)
            .then(retrieveSyndications)
            .then(function(data) {
                return $q.all(data._items.map(_completePost))
                    .then(function(result) {
                        return angular.extend(data, { _items: result });
                    });
            });
    }

    function getLatestUpdateDate(posts) {
        if (!angular.isDefined(posts) || posts.length < 1) {
            return;
        }
        var latest_date, date;

        posts.forEach((post) => {
            date = moment(post._updated);
            if (angular.isDefined(latest_date)) {
                if (latest_date.diff(date) < 0) {
                    latest_date = date;
                }
            } else {
                latest_date = date;
            }
        });
        return latest_date.utc().format();
    }

    function savePost(blog_id, post_to_update, items, post) {
        post = post || {};
        post.post_status = post.post_status || _.result(post_to_update, 'post_status') || 'open';
        var dfds = [];
        if (items && items.length > 0) {
            // prepare the list of items if needed
            if (angular.isDefined(items) && items.length > 0) {
                if (_.difference(_.keys(items[0]), ['residRef', 'item']).length === 0) {
                    items = _.map(items, function(item) {
                        return item.item;
                    });
                }
            }
            // save every items
            _.each(items, function(item) {
                // because it fails when item has a `_id` field without `_links`
                if (angular.isDefined(item, '_id')) {
                    item = {
                        blog: blog_id,
                        text: item.text,
                        meta: item.meta,
                        group_type: item.group_type,
                        item_type: item.item_type,
                        commenter: item.meta && item.meta.commenter
                    };
                }
                dfds.push(api.items.save(item));
            });
        }
        // save the post
        return $q.all(dfds).then(function(items) {
            if (dfds.length > 0) {
                angular.extend(post, {
                    blog: blog_id,
                    groups: [
                        {
                            id: 'root',
                            refs: [{idRef: 'main'}],
                            role: 'grpRole:NEP'
                        }, {
                            id: 'main',
                            refs: [],
                            role: 'grpRole:Main'
                        }
                    ]
                });
                // update the post reference (links with items)
                _.each(items, function(item) {
                    post.groups[1].refs.push({residRef: item._id});
                });
            }
            var operation;
            if (angular.isDefined(post_to_update)) {
                operation = function updatePost() {
                    return api.posts.save(post_to_update, post);
                };
            } else {
                operation = function createPost() {
                    return api.posts.save(post);
                };
            }
            // return the post saved
            return operation();
        });
    }

    function removePost(post) {
        var deleted = {deleted: true};

        return savePost(post.blog, post, [], deleted);
    }

    return {
        getPosts: getPosts,
        getLatestUpdateDate: getLatestUpdateDate,
        retrievePost: retrievePost,
        savePost: savePost,
        saveDraft: function(blog_id, post, items, sticky, highlight) {
            return savePost(
                blog_id,
                post,
                items,
                {post_status: 'draft', 'sticky': sticky, 'lb_highlight': highlight}
            );
        },
        saveContribution: function(blog_id, post, items, sticky, highlight) {
            return savePost(
                blog_id,
                post,
                items,
                {post_status: 'submitted', 'sticky': sticky, 'lb_highlight': highlight}
            );
        },
        remove: removePost
    };
}
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { Tree } from 'antd';
import { connect } from 'react-redux';
import { fetchVariableParamsList } from '../../reducer/modules/interfaceCol.js'
const TreeNode = Tree.TreeNode;
const CanSelectPathPrefix = 'CanSelectPath-';

function deleteLast(str) {
  return str.split('.').slice(0, -1).join('.');

}

@connect(
  state => {
    return {
      currColId: state.interfaceCol.currColId
    }
  },
  {
    fetchVariableParamsList
  }
)
class VariablesSelect extends Component {

  static propTypes = {
    click: PropTypes.func,
    currColId: PropTypes.number,
    fetchVariableParamsList: PropTypes.func

  }
  state = {
    records: [],
    expandedKeys: []
  }

  async componentDidMount() {
    const { currColId, fetchVariableParamsList } = this.props
    let result = await fetchVariableParamsList(currColId);
    this.setState({
      records: result.payload.data.data
      // records:record
    })
    // console.log(deleteLast('$.www.rertttty.ffghhh.dddd.wwwww'));

  }

  handleSelect = (key) => {
    if (key && key.indexOf(CanSelectPathPrefix) === 0) {
      key = key.substr(CanSelectPathPrefix.length)
      console.log(key)
      this.props.click(key);
    } else {
      this.setState({
        expandedKeys: [key]
      })
    }

  }

  onExpand = (keys) => {
    this.setState({ expandedKeys: keys })
  }

  render() {
    const pathSelctByTree = (data, elementKeyPrefix = '$', deepLevel = 0) => {
      let keys = Object.keys(data);
      let TreeComponents = keys.map((key, index) => {
        let item = data[key], casename;
        if (deepLevel === 0) {
          elementKeyPrefix = '$'
          elementKeyPrefix = elementKeyPrefix + '.' + item._id;
          casename = item.casename;
          item = {
            params: item.params,
            body: item.body
          }
        } else if (Array.isArray(data)) {
          elementKeyPrefix = index === 0 ?
            elementKeyPrefix + '[' + key + ']' : deleteLast(elementKeyPrefix) + '[' + key + ']';

        } else {
          elementKeyPrefix = index === 0 ?
            elementKeyPrefix + '.' + key : deleteLast(elementKeyPrefix) + '.' + key;

        }
        // console.log('elementKeyPrefix',elementKeyPrefix);
        if (item && typeof item === 'object') {
          return <TreeNode key={elementKeyPrefix} title={casename || key}>{pathSelctByTree(item, elementKeyPrefix, deepLevel + 1)}</TreeNode>;
        }
        // elementKeyPrefix =
        return <TreeNode key={CanSelectPathPrefix + elementKeyPrefix} title={key} />;

      })

      // elementKeyPrefix = deleteLast(elementKeyPrefix);
      return TreeComponents
    }
    return (

        <Tree
          expandedKeys={this.state.expandedKeys}
          onSelect={([key]) => this.handleSelect(key)}
          onExpand={this.onExpand}
        >
          {pathSelctByTree(this.state.records)}
        </Tree>

    )
  }
}

export default VariablesSelect;<commit_msg>fix: 修改变量选择为空<commit_after>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { Tree } from 'antd';
import { connect } from 'react-redux';
import { fetchVariableParamsList } from '../../reducer/modules/interfaceCol.js'
const TreeNode = Tree.TreeNode;
const CanSelectPathPrefix = 'CanSelectPath-';

function deleteLast(str) {
  return str.split('.').slice(0, -1).join('.');

}

@connect(
  state => {
    return {
      currColId: state.interfaceCol.currColId
    }
  },
  {
    fetchVariableParamsList
  }
)
class VariablesSelect extends Component {

  static propTypes = {
    click: PropTypes.func,
    currColId: PropTypes.number,
    fetchVariableParamsList: PropTypes.func

  }
  state = {
    records: [],
    expandedKeys: []
  }

  async componentDidMount() {
    const { currColId, fetchVariableParamsList } = this.props
    let result = await fetchVariableParamsList(currColId);
    this.setState({
      records: result.payload.data.data
      // records:record
    })
    // console.log(deleteLast('$.www.rertttty.ffghhh.dddd.wwwww'));

  }

  handleSelect = (key) => {
    if (key && key.indexOf(CanSelectPathPrefix) === 0) {
      key = key.substr(CanSelectPathPrefix.length)
      console.log(key)
      this.props.click(key);
    } else {
      this.setState({
        expandedKeys: [key]
      })
    }

  }

  onExpand = (keys) => {
    this.setState({ expandedKeys: keys })
  }

  render() {
    const pathSelctByTree = (data, elementKeyPrefix = '$', deepLevel = 0) => {
      let keys = Object.keys(data);
      let TreeComponents = keys.map((key, index) => {
        let item = data[key], casename;
        if (deepLevel === 0) {
          elementKeyPrefix = '$'
          elementKeyPrefix = elementKeyPrefix + '.' + item._id;
          casename = item.casename;
          item = {
            params: item.params,
            body: item.body
          }
        } else if (Array.isArray(data)) {
          elementKeyPrefix = index === 0 ?
            elementKeyPrefix + '[' + key + ']' : deleteLast(elementKeyPrefix) + '[' + key + ']';

        } else {
          elementKeyPrefix = index === 0 ?
            elementKeyPrefix + '.' + key : deleteLast(elementKeyPrefix) + '.' + key;

        }
        if (item && typeof item === 'object') {
          const isDisable = Array.isArray(item) && item.length === 0;
          return <TreeNode key={elementKeyPrefix} disabled={isDisable} title={casename || key}>{pathSelctByTree(item, elementKeyPrefix, deepLevel + 1)}</TreeNode>;
        }
        return <TreeNode key={CanSelectPathPrefix + elementKeyPrefix} title={key} />;

      })

      return TreeComponents
    }
    return (

        <Tree
          expandedKeys={this.state.expandedKeys}
          onSelect={([key]) => this.handleSelect(key)}
          onExpand={this.onExpand}
        >
          {pathSelctByTree(this.state.records)}
        </Tree>

    )
  }
}

export default VariablesSelect;<|endoftext|>


<commit_before>"use strict";

define(['js/Utils/GMEConcepts',
    'js/DragDrop/DragHelper',
    'js/NodePropertyNames',
    'js/RegistryKeys',
    './../Crosscut/CrosscutConstants',
    'js/Panels/ControllerBase/DiagramDesignerWidgetMultiTabMemberListControllerBase'], function (
                                               GMEConcepts,
                                               DragHelper,
                                               nodePropertyNames,
                                               REGISTRY_KEYS,
                                               ManualAspectConstants,
                                               DiagramDesignerWidgetMultiTabMemberListControllerBase) {

    var SetEditorController;

    SetEditorController = function (options) {
        options = options || {};
        options.loggerName = "SetEditorController";

        DiagramDesignerWidgetMultiTabMemberListControllerBase.call(this, options);

        this.logger.debug("SetEditorController ctor finished");
    };

    _.extend(SetEditorController.prototype, DiagramDesignerWidgetMultiTabMemberListControllerBase.prototype);

    SetEditorController.prototype.getOrderedMemberListInfo = function (memberListContainerObject) {
        var result = [],
            setNames = memberListContainerObject.getSetNames() || [],
            manualAspectsRegistry = memberListContainerObject.getRegistry(REGISTRY_KEYS.CROSSCUTS) || [],
            manualAspectSetNames = [],
            len;

        //filter out ManualAspects from the list
        _.each(manualAspectsRegistry, function (element/*, index, list*/) {
            manualAspectSetNames.push(element.SetID);
        });

        setNames = _.difference(setNames, manualAspectSetNames);

        len = setNames.length;
        while (len--) {
            result.push({'memberListID': setNames[len],
                'title': setNames[len],
                'enableDeleteTab': false,
                'enableRenameTab': false});
        }

        result.sort(function (a,b) {
            if (a.title.toLowerCase() < b.title.toLowerCase()) {
                return -1;
            } else {
                return 1;
            }
        });

        return result;
    };

    /**********************************************************/
    /*         HANDLE OBJECT DRAG & DROP ACCEPTANCE           */
    /**********************************************************/
    SetEditorController.prototype._onBackgroundDroppableAccept = function(event, dragInfo) {
        var gmeIDList = DragHelper.getDragItems(dragInfo),
            accept = DiagramDesignerWidgetMultiTabMemberListControllerBase.prototype._onBackgroundDroppableAccept.call(this, event, dragInfo);

        if (accept === true) {
            //if based on the DiagramDesignerWidgetMultiTabMemberListControllerBase check it could be accepted, ie items are not members of the set so far
            //we need to see if we can accept them based on the META rules
            accept = GMEConcepts.canAddToSet(this._memberListContainerID, this._selectedMemberListID, gmeIDList);
        }

        return accept;
    };
    /**********************************************************/
    /*  END OF --- HANDLE OBJECT DRAG & DROP ACCEPTANCE       */
    /**********************************************************/

    /*
     * Overwrite 'no tab' warning message to the user
     */
    SetEditorController.prototype.displayNoTabMessage = function () {
        var msg = 'The currently selected object does not contain any sets.';

        this._widget.setBackgroundText(msg);
    };

    return SetEditorController;
});
<commit_msg>bugfix: filter out aspect names from getSetNames<commit_after>"use strict";

define(['js/Utils/GMEConcepts',
    'js/DragDrop/DragHelper',
    'js/NodePropertyNames',
    'js/RegistryKeys',
    './../Crosscut/CrosscutConstants',
    'js/Panels/ControllerBase/DiagramDesignerWidgetMultiTabMemberListControllerBase'], function (
                                               GMEConcepts,
                                               DragHelper,
                                               nodePropertyNames,
                                               REGISTRY_KEYS,
                                               ManualAspectConstants,
                                               DiagramDesignerWidgetMultiTabMemberListControllerBase) {

    var SetEditorController;

    SetEditorController = function (options) {
        options = options || {};
        options.loggerName = "SetEditorController";

        DiagramDesignerWidgetMultiTabMemberListControllerBase.call(this, options);

        this.logger.debug("SetEditorController ctor finished");
    };

    _.extend(SetEditorController.prototype, DiagramDesignerWidgetMultiTabMemberListControllerBase.prototype);

    SetEditorController.prototype.getOrderedMemberListInfo = function (memberListContainerObject) {
        var result = [],
            aspects = this._client.getMetaAspectNames(this._memberListContainerID) || [],
            setNames = memberListContainerObject.getSetNames() || [],
            manualAspectsRegistry = memberListContainerObject.getRegistry(REGISTRY_KEYS.CROSSCUTS) || [],
            manualAspectSetNames = [],
            len;

        //filter out ManualAspects from the list
        _.each(manualAspectsRegistry, function (element/*, index, list*/) {
            manualAspectSetNames.push(element.SetID);
        });

        setNames = _.difference(setNames, manualAspectSetNames, aspects);

        len = setNames.length;
        while (len--) {
            result.push({'memberListID': setNames[len],
                'title': setNames[len],
                'enableDeleteTab': false,
                'enableRenameTab': false});
        }

        result.sort(function (a,b) {
            if (a.title.toLowerCase() < b.title.toLowerCase()) {
                return -1;
            } else {
                return 1;
            }
        });

        return result;
    };

    /**********************************************************/
    /*         HANDLE OBJECT DRAG & DROP ACCEPTANCE           */
    /**********************************************************/
    SetEditorController.prototype._onBackgroundDroppableAccept = function(event, dragInfo) {
        var gmeIDList = DragHelper.getDragItems(dragInfo),
            accept = DiagramDesignerWidgetMultiTabMemberListControllerBase.prototype._onBackgroundDroppableAccept.call(this, event, dragInfo);

        if (accept === true) {
            //if based on the DiagramDesignerWidgetMultiTabMemberListControllerBase check it could be accepted, ie items are not members of the set so far
            //we need to see if we can accept them based on the META rules
            accept = GMEConcepts.canAddToSet(this._memberListContainerID, this._selectedMemberListID, gmeIDList);
        }

        return accept;
    };
    /**********************************************************/
    /*  END OF --- HANDLE OBJECT DRAG & DROP ACCEPTANCE       */
    /**********************************************************/

    /*
     * Overwrite 'no tab' warning message to the user
     */
    SetEditorController.prototype.displayNoTabMessage = function () {
        var msg = 'The currently selected object does not contain any sets.';

        this._widget.setBackgroundText(msg);
    };

    return SetEditorController;
});
<|endoftext|>


<commit_before>define(['marionette',
    'backgrid',
    'views/table',
    'modules/dc/collections/apstatuses',
    'modules/dc/views/reprocess',
    'templates/dc/apstatussummary.html'],
    function(Marionette,
        Backgrid,
        TableView,
        APStatuses,
        ReprocessView,
        template) {

    var APCell = Backgrid.Cell.extend({
        initialize: function(options) {
            APCell.__super__.initialize.call(this,options)
            this.listenTo(this.model, 'change reset', this.render, this)
            this.template = options.column.get('template')
        },

        render: function() {
            this.$el.empty();

            if (this.model.get('APLOADED') == true) {
                var tmpl = _.template(this.template)
                this.$el.html(tmpl(this.model.toJSON()))

            }

            this.delegateEvents();
            return this;
        }
    })

    var RPCell = APCell.extend({
        events: {
            'click a.reprocess': 'reprocess',
        },

        reprocess: function(e) {
            e.preventDefault()

            if (app.dialog.currentView instanceof ReprocessView) app.dialog.currentView.collection.add(this.model)
            else app.dialog.show(new ReprocessView({ model: this.model, visit: this.model.get('VISIT') }))
        }

    })

    var APItemCell = Backgrid.Cell.extend({
        initialize: function(options) {
            APItemCell.__super__.initialize.call(this,options)
            this.listenTo(this.model, 'change reset', this.render, this)
            this.template = ''
        },

        render: function() {
            this.$el.empty();

            var id = this.model.get('ID')
            var res = this.model.get('STATES')

            var val = ['',
                    '',
                    '',
                    '']

            var label = this.column.get('program')
            this.$el.html(_.template(this.template))
            if (this.model.get('APLOADED') == true) {
                var ap = res[this.column.get('group')][label]
                var ress = {}
                _.each(ap, function(a) {
                    if (!(a in ress)) ress[a] = 0
                    ress[a]++
                })
                this.$el.html(_.map(ress, function(c, st) { return c > 1 ? ''+c+'x '+val[st] : val[st]}))
            }
            this.delegateEvents();
            return this;
        }
    })

    return Marionette.LayoutView.extend({
        className: 'content',
        template: template,
        regions: { wrap: '.wrapper' },

        collectionEvents: {
            'update sync reset': 'updateStatus',
        },

        initialize: function(options) {
            this.statuses = new APStatuses()
            this.columns = [
                { name: 'FILETEMPLATETRIM', label: 'Prefix', cell: 'string', editable: false },
                { label: 'Sample', cell: APCell, template: '<% if (BLSAMPLEID) { %><a href="/samples/sid/<%-BLSAMPLEID%>" class="wrap sample"><%-SAMPLE%><% } %>', editable: false },
                { name: 'ST', label: 'Date', cell: 'string', editable: false },
            ]

            this.columns.push.apply(this.columns, [
                { label: '', cell: RPCell, template: ' Reprocess', editable: false },
                { label: '', cell: APCell, template: '<a href="/dc/visit/'+this.model.escape('VISIT')+'/id/<%-ID%>" class="button button-notext dll" title="Open data collection"> Open data collection', editable: false },
            ])

            this.table = new TableView({
                collection: this.collection,
                columns: this.columns,
                tableClass: 'break-header',
                filter: 's',
                loading: true,
                backgrid: {
                    row: Backgrid.Row,
                    emptyText: 'No data collections found',
                }
            })

        },

        updateColumns: function() {
            var states = this.statuses.pluck('STATES')
            var group_names = _.keys(states[0])
            var groups = {}
            _.each(group_names, function(group) {
                groups[group] = _.unique(_.map(states, function(state) { return _.keys(state[group]) }).flat())
            })

            _.each(groups, function(programs, group) {
                _.each(programs, function(program) {
                    var id = group+program
                    var col = this.table.grid.columns.where({ pid: id });
                    var title = program.replace('+', '+ ').replace('.', '. ')
                    console.log(group, program, col)
                    if (!col.length) {
                        this.table.grid.insertColumn(
                            { label: title , cell: APItemCell, editable: false, group: group, program: program, pid: id }
                        )
                    }
                }, this)
            }, this)
        },

        updateStatus: function() {
            var self = this
            this.statuses.fetch({ type: 'POST', data: { ids: this.collection.pluck('ID') } }).done(function() {
                self.collection.each(function(dc) {
                    var s = self.statuses.findWhere({ ID: dc.get('ID') })
                    var st = s.get('STATES')
                    dc.set({
                        STATES: st,
                        APLOADED: true
                    })
                })
                self.updateColumns()
            })
        },

        onRender: function() {
            this.updateStatus()
            this.wrap.show(this.table)
        }
    })
})<commit_msg>remove debug<commit_after>define(['marionette',
    'backgrid',
    'views/table',
    'modules/dc/collections/apstatuses',
    'modules/dc/views/reprocess',
    'templates/dc/apstatussummary.html'],
    function(Marionette,
        Backgrid,
        TableView,
        APStatuses,
        ReprocessView,
        template) {

    var APCell = Backgrid.Cell.extend({
        initialize: function(options) {
            APCell.__super__.initialize.call(this,options)
            this.listenTo(this.model, 'change reset', this.render, this)
            this.template = options.column.get('template')
        },

        render: function() {
            this.$el.empty();

            if (this.model.get('APLOADED') == true) {
                var tmpl = _.template(this.template)
                this.$el.html(tmpl(this.model.toJSON()))

            }

            this.delegateEvents();
            return this;
        }
    })

    var RPCell = APCell.extend({
        events: {
            'click a.reprocess': 'reprocess',
        },

        reprocess: function(e) {
            e.preventDefault()

            if (app.dialog.currentView instanceof ReprocessView) app.dialog.currentView.collection.add(this.model)
            else app.dialog.show(new ReprocessView({ model: this.model, visit: this.model.get('VISIT') }))
        }

    })

    var APItemCell = Backgrid.Cell.extend({
        initialize: function(options) {
            APItemCell.__super__.initialize.call(this,options)
            this.listenTo(this.model, 'change reset', this.render, this)
            this.template = ''
        },

        render: function() {
            this.$el.empty();

            var id = this.model.get('ID')
            var res = this.model.get('STATES')

            var val = ['',
                    '',
                    '',
                    '']

            var label = this.column.get('program')
            this.$el.html(_.template(this.template))
            if (this.model.get('APLOADED') == true) {
                var ap = res[this.column.get('group')][label]
                var ress = {}
                _.each(ap, function(a) {
                    if (!(a in ress)) ress[a] = 0
                    ress[a]++
                })
                this.$el.html(_.map(ress, function(c, st) { return c > 1 ? ''+c+'x '+val[st] : val[st]}))
            }
            this.delegateEvents();
            return this;
        }
    })

    return Marionette.LayoutView.extend({
        className: 'content',
        template: template,
        regions: { wrap: '.wrapper' },

        collectionEvents: {
            'update sync reset': 'updateStatus',
        },

        initialize: function(options) {
            this.statuses = new APStatuses()
            this.columns = [
                { name: 'FILETEMPLATETRIM', label: 'Prefix', cell: 'string', editable: false },
                { label: 'Sample', cell: APCell, template: '<% if (BLSAMPLEID) { %><a href="/samples/sid/<%-BLSAMPLEID%>" class="wrap sample"><%-SAMPLE%><% } %>', editable: false },
                { name: 'ST', label: 'Date', cell: 'string', editable: false },
            ]

            this.columns.push.apply(this.columns, [
                { label: '', cell: RPCell, template: ' Reprocess', editable: false },
                { label: '', cell: APCell, template: '<a href="/dc/visit/'+this.model.escape('VISIT')+'/id/<%-ID%>" class="button button-notext dll" title="Open data collection"> Open data collection', editable: false },
            ])

            this.table = new TableView({
                collection: this.collection,
                columns: this.columns,
                tableClass: 'break-header',
                filter: 's',
                loading: true,
                backgrid: {
                    row: Backgrid.Row,
                    emptyText: 'No data collections found',
                }
            })

        },

        updateColumns: function() {
            var states = this.statuses.pluck('STATES')
            var group_names = _.keys(states[0])
            var groups = {}
            _.each(group_names, function(group) {
                groups[group] = _.unique(_.map(states, function(state) { return _.keys(state[group]) }).flat())
            })

            _.each(groups, function(programs, group) {
                _.each(programs, function(program) {
                    var id = group+program
                    var col = this.table.grid.columns.where({ pid: id });
                    var title = program.replace('+', '+ ').replace('.', '. ')
                    if (!col.length) {
                        this.table.grid.insertColumn(
                            { label: title , cell: APItemCell, editable: false, group: group, program: program, pid: id }
                        )
                    }
                }, this)
            }, this)
        },

        updateStatus: function() {
            var self = this
            this.statuses.fetch({ type: 'POST', data: { ids: this.collection.pluck('ID') } }).done(function() {
                self.collection.each(function(dc) {
                    var s = self.statuses.findWhere({ ID: dc.get('ID') })
                    var st = s.get('STATES')
                    dc.set({
                        STATES: st,
                        APLOADED: true
                    })
                })
                self.updateColumns()
            })
        },

        onRender: function() {
            this.updateStatus()
            this.wrap.show(this.table)
        }
    })
})<|endoftext|>