{"size": 3859, "ext": "js", "max_stars_repo_path": "server/routes/establishments/shareData.js", "max_stars_repo_name": "NMDSdevopsServiceAdm/SopraSteria-SFC", "max_stars_repo_stars_event_min_datetime": "2019-01-16T15:36:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T11:40:03.000Z", "max_issues_repo_path": "server/routes/establishments/shareData.js", "max_issues_repo_name": "NMDSdevopsServiceAdm/SopraSteria-SFC", "max_issues_repo_issues_event_min_datetime": "2018-12-05T15:19:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:18:12.000Z", "max_forks_repo_path": "server/routes/establishments/shareData.js", "max_forks_repo_name": "NMDSdevopsServiceAdm/SopraSteria-SFC", "max_forks_repo_forks_event_min_datetime": "2019-08-29T14:29:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-11T10:31:27.000Z"}
{"max_stars_count": 7, "max_issues_count": 3000, "max_forks_count": 5, "avg_line_length": 37.4660194175, "max_line_length": 120, "alphanum_fraction": 0.677377559}
const express = require('express');
const router = express.Router({ mergeParams: true });

const Establishment = require('../../models/classes/establishment');
const { hasPermission } = require('../../utils/security/hasPermission');
const filteredProperties = ['Name', 'ShareData'];

// gets current 'share data' options for the known establishment
const getShareData = async (req, res) => {
  const establishmentId = req.establishmentId;

  const showHistory =
    req.query.history === 'full' || req.query.history === 'property' || req.query.history === 'timeline' ? true : false;
  const showHistoryTime = req.query.history === 'timeline' ? true : false;
  const showPropertyHistoryOnly = req.query.history === 'property' ? true : false;

  const thisEstablishment = new Establishment.Establishment(req.username);

  try {
    if (await thisEstablishment.restore(establishmentId, showHistory)) {
      // show only brief info on Establishment
      return res
        .status(200)
        .json(
          thisEstablishment.toJSON(
            showHistory,
            showPropertyHistoryOnly,
            showHistoryTime,
            false,
            false,
            filteredProperties,
          ),
        );
    } else {
      // not found worker
      return res.status(404).send('Not Found');
    }
  } catch (err) {
    const thisError = new Establishment.EstablishmentExceptions.EstablishmentRestoreException(
      thisEstablishment.id,
      thisEstablishment.uid,
      null,
      err,
      null,
      `Failed to retrieve Establishment with id/uid: ${establishmentId}`,
    );

    console.error('establishment::share GET/:eID - failed', thisError.message);
    return res.status(500).send(thisError.safe);
  }
};

// updates the current share options for the known establishment
const updateShareData = async (req, res) => {
  const establishmentId = req.establishmentId;
  const thisEstablishment = new Establishment.Establishment(req.username);

  try {
    // before updating an Establishment, we need to be sure the Establishment is
    //  available to the given user. The best way of doing that
    //  is to restore from given UID
    // by loading the Establishment before updating it, we have all the facts about
    //  an Establishment (if needing to make inter-property decisions)
    if (await thisEstablishment.restore(establishmentId)) {
      // TODO: JSON validation

      // by loading after the restore, only those properties defined in the
      //  POST body will be updated (peristed)
      // With this endpoint we're only interested in share (options)
      const isValidEstablishment = await thisEstablishment.load({
        share: req.body.share,
      });

      // this is an update to an existing Establishment, so no mandatory properties!
      if (isValidEstablishment) {
        await thisEstablishment.save(req.username);

        return res.status(200).json(thisEstablishment.toJSON(false, false, false, true, false, filteredProperties));
      } else {
        return res.status(400).send('Unexpected Input.');
      }
    } else {
      // not found worker
      return res.status(404).send('Not Found');
    }
  } catch (err) {
    if (err instanceof Establishment.EstablishmentExceptions.EstablishmentJsonException) {
      console.error('Establishment::share POST: ', err.message);
      return res.status(400).send(err.safe);
    } else if (err instanceof Establishment.EstablishmentExceptions.EstablishmentSaveException) {
      console.error('Establishment::share POST: ', err.message);
      return res.status(500).send(err.safe);
    } else {
      console.error('Unexpected exception: ', err);
    }
  }
};

router.route('/').get(hasPermission('canViewEstablishment'), getShareData);
router.route('/').post(hasPermission('canEditEstablishment'), updateShareData);

module.exports = router;
