<commit_before>const smash = require("../../../../smash.js");
const logger = smash.logger();
const errorUtil = smash.errorUtil();
const Context = require("./context.js");
const DASH = "-";

class Event {
	constructor(rawEvent, context, terminate) {
		if (typeof rawEvent !== 'object') {
			throw new errorUtil.TypeError("First parameter of Event() must be an object, ", rawEvent);
		}
		this._rawEvent = rawEvent;
		Object.assign(this, rawEvent);
		this.context = context;
		if (typeof terminate !== 'object') {
			throw new errorUtil.TypeError("Third parameter of Event() must be a object, ", terminate);
		}
		if (typeof terminate.terminate !== 'function') {
			throw new errorUtil.TypeError("Third parameter of Event() must be an object with a function called terminate, ", terminate.terminate);
		}
		if (terminate.terminate.length !== 2) {
			throw new Error("Third parameter of Event() must be an object with a function called terminate witch takes 2 parameters: error, data, " + terminate.terminate.length + " given");
		}
		this.requestContext = rawEvent.requestContext;
		this.processService();
		this.apiId = this.requestContext.apiId;
		this.httpMethod = this.requestContext.httpMethod;
		this._terminate = terminate;
		this.permissionContext = null;
		this.extraContextData = {};
	}

	processService() {
		if (this.requestContext && this.requestContext.domainPrefix) {
			if (this.requestContext.domainPrefix.indexOf(DASH) > 0) {
				this.service = this.requestContext.domainPrefix.split(DASH);
				this.service.shift();
				this.service = this.service.join(DASH);
			} else {
				this.service = this.requestContext.domainPrefix;
			}
		}
		return this;
	}

	generatePermissionContext(data) {
		this.permissionContext = new Context(data);
		return this;
	}

	_generatePolicy(effect, context) {
		const authResponse = {
			principalId: context.principalId,
			context: { ...this.extraContextData, service: this.service, ...context.rawObject() },
		};
		if (effect && this.methodArn) {
			authResponse.policyDocument = {
				Version: '2012-10-17',
				Statement: [
					{
						Action: 'execute-api:Invoke',
						Effect: effect,
						Resource: smash.getCurrentEvent().methodArn,
					},
				],
			};
		}
		return authResponse;
	}

	terminate(error, data) {
		this._terminate.terminate(error, data);
		return this;
	}

	addExtraContextData(data) {
		this.extraContextData = { ...this.extraContextData, ...data };
		return this;
	}

	allow() {
		if (this.permissionContext) {
			this.terminate(null, this._generatePolicy("Allow", this.permissionContext));
		} else {
			this.internalServerError(errorUtil.internalServerError("Method generatePermissionContext(data) must be called before allow(), " + errorUtil.typeOf(this.permissionContext)));
		}
		return this;
	}

	deny() {
		if (this.permissionContext) {
			this.terminate(null, this._generatePolicy("Deny", this.permissionContext));
		} else {
			this.internalServerError(errorUtil.internalServerError("Method generatePermissionContext(data) must be called before deny(), " + errorUtil.typeOf(this.permissionContext)));
		}
		return this;
	}

	unauthorized(error) {
		if (error) {
			logger.error("Unauthorized", error);
		} else {
			logger.error("Unauthorized");
		}
		this.terminate("Unauthorized");
		return this;
	}

	internalServerError(error) {
		if (errorUtil.isSmashError(error) === false) {
			error = errorUtil.internalServerError("First argument of handleError(error) must ba a SmashError, " + errorUtil.typeOf(error), error);
		}
		error.printError();
		this.terminate("Internal server error");
		return this;
	}

	handleError(error) {
		if (errorUtil.isSmashError(error) === false) {
			error = errorUtil.internalServerError("First argument of handleError(error) must ba a SmashError, " + errorUtil.typeOf(error), error);
		}
		error.printError();
		if (errorUtil.isUnauthorizedError(error) === true) {
			this.unauthorized(error);
		} else if (errorUtil.isForbiddenError(error) === true) {
			this.deny(error);
		} else {
			this.internalServerError(error);
		}
		return this;
	}
}

module.exports = Event;
<commit_msg>Fix bad service name<commit_after>const smash = require("../../../../smash.js");
const logger = smash.logger();
const errorUtil = smash.errorUtil();
const Context = require("./context.js");
const DASH = "-";

class Event {
	constructor(rawEvent, context, terminate) {
		if (typeof rawEvent !== 'object') {
			throw new errorUtil.TypeError("First parameter of Event() must be an object, ", rawEvent);
		}
		this._rawEvent = rawEvent;
		Object.assign(this, rawEvent);
		this.context = context;
		if (typeof terminate !== 'object') {
			throw new errorUtil.TypeError("Third parameter of Event() must be a object, ", terminate);
		}
		if (typeof terminate.terminate !== 'function') {
			throw new errorUtil.TypeError("Third parameter of Event() must be an object with a function called terminate, ", terminate.terminate);
		}
		if (terminate.terminate.length !== 2) {
			throw new Error("Third parameter of Event() must be an object with a function called terminate witch takes 2 parameters: error, data, " + terminate.terminate.length + " given");
		}
		this.requestContext = rawEvent.requestContext;
		this.processService();
		this.apiId = this.requestContext.apiId;
		this.httpMethod = this.requestContext.httpMethod;
		this._terminate = terminate;
		this.permissionContext = null;
		this.extraContextData = {};
	}

	processService() {
		if (this.requestContext && this.requestContext.domainPrefix) {
			if (this.requestContext.domainPrefix.indexOf(DASH) > 0) {
				this.service = this.requestContext.domainPrefix.split(DASH);
				this.service.shift();
				this.service = this.service.join(DASH);
			} else {
				this.service = this.requestContext.domainPrefix;
			}
		}
		return this;
	}

	generatePermissionContext(data) {
		this.permissionContext = new Context(data);
		return this;
	}

	_generatePolicy(effect, context) {
		const authResponse = {
			principalId: context.principalId,
			context: { ...this.extraContextData, ...context.rawObject() },
		};
		if (effect && this.methodArn) {
			authResponse.policyDocument = {
				Version: '2012-10-17',
				Statement: [
					{
						Action: 'execute-api:Invoke',
						Effect: effect,
						Resource: smash.getCurrentEvent().methodArn,
					},
				],
			};
		}
		return authResponse;
	}

	terminate(error, data) {
		this._terminate.terminate(error, data);
		return this;
	}

	addExtraContextData(data) {
		this.extraContextData = { ...this.extraContextData, ...data };
		return this;
	}

	allow() {
		if (this.permissionContext) {
			this.terminate(null, this._generatePolicy("Allow", this.permissionContext));
		} else {
			this.internalServerError(errorUtil.internalServerError("Method generatePermissionContext(data) must be called before allow(), " + errorUtil.typeOf(this.permissionContext)));
		}
		return this;
	}

	deny() {
		if (this.permissionContext) {
			this.terminate(null, this._generatePolicy("Deny", this.permissionContext));
		} else {
			this.internalServerError(errorUtil.internalServerError("Method generatePermissionContext(data) must be called before deny(), " + errorUtil.typeOf(this.permissionContext)));
		}
		return this;
	}

	unauthorized(error) {
		if (error) {
			logger.error("Unauthorized", error);
		} else {
			logger.error("Unauthorized");
		}
		this.terminate("Unauthorized");
		return this;
	}

	internalServerError(error) {
		if (errorUtil.isSmashError(error) === false) {
			error = errorUtil.internalServerError("First argument of handleError(error) must ba a SmashError, " + errorUtil.typeOf(error), error);
		}
		error.printError();
		this.terminate("Internal server error");
		return this;
	}

	handleError(error) {
		if (errorUtil.isSmashError(error) === false) {
			error = errorUtil.internalServerError("First argument of handleError(error) must ba a SmashError, " + errorUtil.typeOf(error), error);
		}
		error.printError();
		if (errorUtil.isUnauthorizedError(error) === true) {
			this.unauthorized(error);
		} else if (errorUtil.isForbiddenError(error) === true) {
			this.deny(error);
		} else {
			this.internalServerError(error);
		}
		return this;
	}
}

module.exports = Event;
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import Formsy from 'formsy-react'
import getStatusIcon from './StatusIcon'

import { TriageStatusList,
         GPStatusList,
         PsychiatristStatusList }  from './StatusList'

import { FormsySelect,
         FormsyText,
         FormsyToggle } from 'formsy-material-ui/lib'

import { RaisedButton,
         MenuItem     } from 'material-ui'

const style = {
    referralOptions :{
        display: 'flex',
    //   justifyContent: 'space-between',
        alignItems: 'center',
    },
    uploadButton :{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center'
    },
    card :{
        marginBottom : 15
    },
    cardActions :{
        textAlign: 'right'
    },
    paperStyle: {
    //   width: 300,
    margin: 'auto',
    padding: 20,
    },
    switchStyle: {
    marginBottom: 16,
    },
    submitStyle: {
    marginTop: 32,
    },
    chip: {
        margin: 4,
    },
    wrapper: {
        display: 'flex',
        flexWrap: 'wrap',
    }
}

class ReferralForm extends Component {
    constructor(props){
        super(props)
        this._processReferral = this._processReferral.bind(this)
        this._renderStatusList = this._renderStatusList.bind(this)
        this._toggleIsEditable = this._toggleIsEditable.bind(this)
        this._renderEditCancelButton = this._renderEditCancelButton.bind(this)

        this.state = {
            isEditable: false
        }
    }

    _processReferral(data, action) {
        // event.preventDefault()
        const referral =
            {
                referralStatus:             data.referralStatus,
                patientSurname:             data.patientSurname,
                patientgivenName:           data.patientgivenName,
                patientGender:              data.patientGender,
                patientBirthDay:            data.patientBirthDay,
                patientBirthMonth:          data.patientBirthMonth,
                patientBirthYear:           data.patientBirthYear,
                patientAddress:             data.patientAddress,
                patientPostcode:            data.patientPostcode,
                patientMedicare:            data.patientMedicare,
                patientContactNumber:       data.patientContactNumber,
                doctorSurname:              data.doctorSurname,
                doctorGivenName:            data.doctorGivenName,
                doctorClinic:               data.doctorClinic,
                doctorAddress:              data.doctorAddress,
                doctorPostcode:             data.doctorPostcode,
                doctorContactNumber:        data.doctorContactNumber,
                referralRequestedService:   data.referralRequestedService,
                referralReasonForReferral:  data.referralReasonForReferral,
                referralUrgent:             data.referralUrgent,
                referralRuralCode:          data.referralRuralCode,
                referralAppointmentDay:     data.referralAppointmentDay,
                referralAppointmentMonth:   data.referralAppointmentMonth,
                referralAppointmentYear:    data.patientBirthYear,
                referralAppointmentHour:    data.referralAppointmentHour,
                referralAppointmentMinute:    data.referralAppointmentMinute,
                referralAppointmentPeriod:    data.referralAppointmentPeriod,
            }

        // console.log(JSON.stringify(referral,null,2))
        // console.log('adding a referral')

        // this.props.action === 'update' ?
        // this.props._updateReferral(this.props.index, referral) :
        // ( this.props._addReferral(referral), this.props._toggleShowNewReferralForm() )

        if (this.props.action === 'update'){
            this.props._updateReferral(this.props.index, referral)
        }
        else {
            this.props._addReferral(referral)
            this.props._toggleShowNewReferralForm()
        }

    }

    _toggleIsEditable() {
        this.setState({ isEditable: !this.state.isEditable })
        console.log('isEditable : ', this.state.isEditable)
    }

    _renderStatusList() {
        console.log('statusList role', this.props.role)
        switch (this.props.role) {
            case 'triage':
                console.log('this is triage')
                return <TriageStatusList />

            case 'gp':
                console.log('this is gp')
                return <GPStatusList />

            case 'psychiatrist':
                console.log('this is psychiatrist')
                return <PsychiatristStatusList />

            default:
                console.log('defaulting to triage')
                return <TriageStatusList />
        }
    }

    _renderEditCancelButton(){

        if (this.props.action === 'new'){
            return(
                <RaisedButton
                    label="Cancel"
                    primary={true}
                    style={style.uploadButton}
                    onClick={this.props._toggleShowNewReferralForm}
                />
            )
        }
        else
        {
            return(
                <RaisedButton
                    label="Edit"
                    primary={true}
                    style={style.uploadButton}
                    onClick={this._toggleIsEditable}
                />
            )
        }
    }

    render(){
        return(

                <Formsy.Form
                    ref={ (input) => this.referralForm = input }
                    onValidSubmit={ (data) => this._processReferral(data, this.props.action) }
                >

                        {this._renderEditCancelButton()}

                        <RaisedButton
                            type="submit"
                            label={this.props.action === 'update' ? 'Update' : 'Submit'}
                        />

Referral status

                    {this._renderStatusList()}

                    {/* patient data form below */}

Patient Data

                    <FormsyText
                        name="patientSurname"
                        hintText="Surname"
                        floatingLabelText="Surname"
                        defaultValue={this.props.action === 'update' ? this.props.referral.patientSurname : null}
                        disabled={this.props.action==='update' ? this.state.isEditable : false}
                    />

                    <FormsyText
                        name="patientgivenName"
                        hintText="Given name"
                        floatingLabelText="Given name"
                        defaultValue={this.props.action === 'update' ? this.props.referral.patientgivenName : null}
                    />

                    <FormsySelect
                            name="patientGender"
                            floatingLabelText="Gender"
                            value={this.props.action === 'update' ? this.props.referral.patientGender : null}
                    >
                            <MenuItem value={'M'} primaryText="Male" />
                            <MenuItem value={'F'} primaryText="Female" />
                    </FormsySelect>

                    <FormsyText
                        name="patientAddress"
                        hintText="Address"
                        floatingLabelText="Address"
                        defaultValue={this.props.action === 'update' ? this.props.referral.patientAddress : null}
                    />

                    <FormsyText
                        name="patientPostcode"
                        hintText="Postcode"
                        floatingLabelText="Postcode"
                        defaultValue={this.props.action === 'update' ? this.props.referral.patientPostcode : null}
                    />

                    <FormsyText
                        name="patientBirthDay"
                        hintText="DOB Day"
                        floatingLabelText="DOB Day"
                        defaultValue={this.props.action === 'update' ? this.props.referral.patientBirthDay : null}
                    />

                    <FormsyText
                        name="patientBirthMonth"
                        hintText="DOB Month"
                        floatingLabelText="DOB Month"
                        defaultValue={this.props.action === 'update' ? this.props.referral.patientBirthMonth : null}
                    />

                    <FormsyText
                        name="patientBirthYear"
                        hintText="DOB Year"
                        floatingLabelText="DOB Year"
                        defaultValue={this.props.action === 'update' ? this.props.referral.patientBirthYear : null}
                    />

                    <FormsyText
                        name="patientMedicare"
                        hintText="Medicare number"
                        floatingLabelText="Medicare number"
                        defaultValue={this.props.action === 'update' ? this.props.referral.patientMedicare : null}
                    />

                    <FormsyText
                        name="patientContactNumber"
                        hintText="Contact number"
                        floatingLabelText="Contact number"
                        defaultValue={this.props.action === 'update' ? this.props.referral.patientContactNumber : null}
                    />

                    {/* doctor data form below */}

Doctor Data

                    <FormsyText
                        name="doctorSurname"
                        hintText="Surname"
                        floatingLabelText="Surname"
                        defaultValue={this.props.action === 'update' ? this.props.referral.doctorSurname : null}
                    />

                    <FormsyText
                        name="doctorGivenName"
                        hintText="Given name"
                        floatingLabelText="Give name"
                        defaultValue={this.props.action === 'update' ? this.props.referral.doctorGivenName : null}
                    />

                    <FormsyText
                        name="doctorClinic"
                        hintText="Clinic"
                        floatingLabelText="Clinic"
                        defaultValue={this.props.action === 'update' ? this.props.referral.doctorClinic : null}
                    />

                    <FormsyText
                        name="doctorAddress"
                        hintText="Address"
                        floatingLabelText="Address"
                        defaultValue={this.props.action === 'update' ? this.props.referral.doctorAddress : null}
                    />

                    <FormsyText
                        name="doctorPostcode"
                        hintText="Postcode"
                        floatingLabelText="Postcode"
                        defaultValue={this.props.action === 'update' ? this.props.referral.doctorPostcode : null}
                    />

                    <FormsyText
                        name="doctorContactNumber"
                        hintText="Contact number"
                        floatingLabelText="Contact number"
                        defaultValue={this.props.action === 'update' ? this.props.referral.doctorContactNumber : null}
                    />

                    {/* referral form below */}

Referral Details

                    <FormsyText
                        name="referralReasonForReferral"
                        hintText="Reason for referral"
                        floatingLabelText="Reason for referral"
                        defaultValue={this.props.action === 'update' ? this.props.referral.referralReasonForReferral : null}
                    />

                    <FormsySelect
                        name="referralRequestedService"
                        floatingLabelText="Requested service"
                        value={this.props.action === 'update' ? this.props.referral.referralRequestedService : null}
                    >
                        <MenuItem value={'mentalHealthAssessment'} primaryText="Mental Health Assessment" />
                        <MenuItem value={'medicationReview'} primaryText="Medication Review" />
                        <MenuItem value={'dianogsticClarification'} primaryText="Diagnostic Clarifiction" />
                        <MenuItem value={'assessmentForManagementOfBPSD'} primaryText="Assessment for Management of BPSD" />
                    </FormsySelect>

                    <FormsyToggle
                        name="referralUrgent"
                        label="Urgent"
                        style={style.switchStyle}
                    />

                        <RaisedButton
                            label="Upload"
                            primary={true}
                            style={style.uploadButton}
                        />

Upload additional information (Limited to one PDF file)

                    {/* triage below */}

Triage

                    <FormsySelect
                        name="referralRuralCode"
                        floatingLabelText="Rural code"
                        value={this.props.action === 'update' ? this.props.referral.referralRuralCode : null}
                    >
                        <MenuItem value={'RA1MajorCities'} primaryText="RA1 MajorCities" />
                        <MenuItem value={'RA2InnerRegional'} primaryText="RA2 Inner Regional" />
                        <MenuItem value={'RA3OuterRegional'} primaryText="RA3 Outer Regional" />
                        <MenuItem value={'RA4Remote'} primaryText="RA4 Remote" />
                        <MenuItem value={'RA5VeryRemote'} primaryText="RA5 Very Remote" />
                    </FormsySelect>

                    <FormsyText
                        name="referralAppointmentDay"
                        hintText="Appointment Day"
                        floatingLabelText="Appointment Day"
                        defaultValue={this.props.action === 'update' ? this.props.referral.referralAppointmentDay : null}
                    />

                    <FormsyText
                        name="referralAppointmentMonth"
                        hintText="Appointment Month"
                        floatingLabelText="Appointment Month"
                        defaultValue={this.props.action === 'update' ? this.props.referral.referralAppointmentMonth : null}
                    />

                    <FormsyText
                        name="referralAppointmentYear"
                        hintText="Appointment Year"
                        floatingLabelText="Appointment Year"
                        defaultValue={this.props.action === 'update' ? this.props.referral.referralAppointmentYear : null}
                    />

                    <FormsyText
                        name="referralAppointmentHour"
                        hintText="Appointment Hour"
                        floatingLabelText="Appointment Month"
                        defaultValue={this.props.action === 'update' ? this.props.referral.referralAppointmentHour : null}
                    />

                    <FormsyText
                        name="referralAppointmentMinute"
                        hintText="Appointment Minute"
                        floatingLabelText="Appointment Year"
                        defaultValue={this.props.action === 'update' ? this.props.referral.referralAppointmentMinute : null}
                    />

                    <FormsySelect
                        name="referralAppointmentPeriod"
                        floatingLabelText="Period"
                        value={this.props.action === 'update' ? this.props.referral.referralAppointmentPeriod : null}
                    >
                        <MenuItem value={'AM'} primaryText="AM" />
                        <MenuItem value={'PM'} primaryText="PM" />
                    </FormsySelect>

Last Date reviewed (placeholder)

                    </Formsy.Form>

        )
    }
}

export default ReferralForm

<commit_msg>updated buttons in referral form<commit_after>import React, { Component } from 'react'
import Formsy from 'formsy-react'
// import getStatusIcon from './StatusIcon'

import { TriageStatusList,
         GPStatusList,
         PsychiatristStatusList }  from './StatusList'

import { FormsySelect,
         FormsyText,
         FormsyToggle } from 'formsy-material-ui/lib'

import { RaisedButton,
         MenuItem     } from 'material-ui'

const style = {
    referralOptions :{
        textAlign: 'center'
    },
    uploadButton :{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center'
    },
    card :{
        marginBottom : 15
    },
    cardActions :{
        textAlign: 'right'
    },
    paperStyle: {
    //   width: 300,
    margin: 'auto',
    padding: 20,
    },
    switchStyle: {
    marginBottom: 16,
    },
    submitStyle: {
    marginTop: 32,
    },
    chip: {
        margin: 4,
    },
    wrapper: {
        display: 'flex',
        flexWrap: 'wrap',
    }
}

class ReferralForm extends Component {
    constructor(props){
        super(props)
        this._processReferral = this._processReferral.bind(this)
        this._renderStatusList = this._renderStatusList.bind(this)
        this._toggleIsEditable = this._toggleIsEditable.bind(this)
        this._renderEditCancelButton = this._renderEditCancelButton.bind(this)

        this.state = {
            isEditable: false
        }
    }

    _processReferral(data, action) {
        // event.preventDefault()
        const referral =
            {
                referralStatus:             data.referralStatus,
                patientSurname:             data.patientSurname,
                patientgivenName:           data.patientgivenName,
                patientGender:              data.patientGender,
                patientBirthDay:            data.patientBirthDay,
                patientBirthMonth:          data.patientBirthMonth,
                patientBirthYear:           data.patientBirthYear,
                patientAddress:             data.patientAddress,
                patientPostcode:            data.patientPostcode,
                patientMedicare:            data.patientMedicare,
                patientContactNumber:       data.patientContactNumber,
                doctorSurname:              data.doctorSurname,
                doctorGivenName:            data.doctorGivenName,
                doctorClinic:               data.doctorClinic,
                doctorAddress:              data.doctorAddress,
                doctorPostcode:             data.doctorPostcode,
                doctorContactNumber:        data.doctorContactNumber,
                referralRequestedService:   data.referralRequestedService,
                referralReasonForReferral:  data.referralReasonForReferral,
                referralUrgent:             data.referralUrgent,
                referralRuralCode:          data.referralRuralCode,
                referralAppointmentDay:     data.referralAppointmentDay,
                referralAppointmentMonth:   data.referralAppointmentMonth,
                referralAppointmentYear:    data.patientBirthYear,
                referralAppointmentHour:    data.referralAppointmentHour,
                referralAppointmentMinute:    data.referralAppointmentMinute,
                referralAppointmentPeriod:    data.referralAppointmentPeriod,
            }

        if (this.props.action === 'update'){
            this.props._updateReferral(this.props.index, referral)
        }
        else {
            this.props._addReferral(referral)
            this.props._toggleShowNewReferralForm()
        }

    }

    _toggleIsEditable() {
        this.setState({ isEditable: !this.state.isEditable })
        console.log('isEditable : ', this.state.isEditable)
    }

    _renderStatusList() {
        console.log('statusList role', this.props.role)
        switch (this.props.role) {
            case 'triage':
                console.log('this is triage')
                return <TriageStatusList />

            case 'gp':
                console.log('this is gp')
                return <GPStatusList />

            case 'psychiatrist':
                console.log('this is psychiatrist')
                return <PsychiatristStatusList />

            default:
                console.log('defaulting to triage')
                return <TriageStatusList />
        }
    }

    _renderEditCancelButton(){

        if (this.props.action === 'new'){
            return(
                <RaisedButton
                    label="Cancel"
                    primary={true}
                    onClick={this.props._toggleShowNewReferralForm}
                />
            )
        }
        else
        {
            return(
                <RaisedButton
                    label="Edit"
                    primary={true}
                    onClick={this._toggleIsEditable}
                />
            )
        }
    }

    render(){
        return(

                <Formsy.Form
                    ref={ (input) => this.referralForm = input }
                    onValidSubmit={ (data) => this._processReferral(data, this.props.action) }
                >

                        {this._renderEditCancelButton()}

                        <RaisedButton
                            type="submit"
                            label={this.props.action === 'update' ? 'Update' : 'Submit'}
                        />

Referral status

                    {this._renderStatusList()}

                    {/* patient data form below */}

Patient Data

                    <FormsyText
                        name="patientSurname"
                        hintText="Surname"
                        floatingLabelText="Surname"
                        defaultValue={this.props.action === 'update' ? this.props.referral.patientSurname : null}
                        disabled={this.props.action==='update' ? this.state.isEditable : false}
                    />

                    <FormsyText
                        name="patientgivenName"
                        hintText="Given name"
                        floatingLabelText="Given name"
                        defaultValue={this.props.action === 'update' ? this.props.referral.patientgivenName : null}
                    />

                    <FormsySelect
                            name="patientGender"
                            floatingLabelText="Gender"
                            value={this.props.action === 'update' ? this.props.referral.patientGender : null}
                    >
                            <MenuItem value={'M'} primaryText="Male" />
                            <MenuItem value={'F'} primaryText="Female" />
                    </FormsySelect>

                    <FormsyText
                        name="patientAddress"
                        hintText="Address"
                        floatingLabelText="Address"
                        defaultValue={this.props.action === 'update' ? this.props.referral.patientAddress : null}
                    />

                    <FormsyText
                        name="patientPostcode"
                        hintText="Postcode"
                        floatingLabelText="Postcode"
                        defaultValue={this.props.action === 'update' ? this.props.referral.patientPostcode : null}
                    />

                    <FormsyText
                        name="patientBirthDay"
                        hintText="DOB Day"
                        floatingLabelText="DOB Day"
                        defaultValue={this.props.action === 'update' ? this.props.referral.patientBirthDay : null}
                    />

                    <FormsyText
                        name="patientBirthMonth"
                        hintText="DOB Month"
                        floatingLabelText="DOB Month"
                        defaultValue={this.props.action === 'update' ? this.props.referral.patientBirthMonth : null}
                    />

                    <FormsyText
                        name="patientBirthYear"
                        hintText="DOB Year"
                        floatingLabelText="DOB Year"
                        defaultValue={this.props.action === 'update' ? this.props.referral.patientBirthYear : null}
                    />

                    <FormsyText
                        name="patientMedicare"
                        hintText="Medicare number"
                        floatingLabelText="Medicare number"
                        defaultValue={this.props.action === 'update' ? this.props.referral.patientMedicare : null}
                    />

                    <FormsyText
                        name="patientContactNumber"
                        hintText="Contact number"
                        floatingLabelText="Contact number"
                        defaultValue={this.props.action === 'update' ? this.props.referral.patientContactNumber : null}
                    />

                    {/* doctor data form below */}

Doctor Data

                    <FormsyText
                        name="doctorSurname"
                        hintText="Surname"
                        floatingLabelText="Surname"
                        defaultValue={this.props.action === 'update' ? this.props.referral.doctorSurname : null}
                    />

                    <FormsyText
                        name="doctorGivenName"
                        hintText="Given name"
                        floatingLabelText="Give name"
                        defaultValue={this.props.action === 'update' ? this.props.referral.doctorGivenName : null}
                    />

                    <FormsyText
                        name="doctorClinic"
                        hintText="Clinic"
                        floatingLabelText="Clinic"
                        defaultValue={this.props.action === 'update' ? this.props.referral.doctorClinic : null}
                    />

                    <FormsyText
                        name="doctorAddress"
                        hintText="Address"
                        floatingLabelText="Address"
                        defaultValue={this.props.action === 'update' ? this.props.referral.doctorAddress : null}
                    />

                    <FormsyText
                        name="doctorPostcode"
                        hintText="Postcode"
                        floatingLabelText="Postcode"
                        defaultValue={this.props.action === 'update' ? this.props.referral.doctorPostcode : null}
                    />

                    <FormsyText
                        name="doctorContactNumber"
                        hintText="Contact number"
                        floatingLabelText="Contact number"
                        defaultValue={this.props.action === 'update' ? this.props.referral.doctorContactNumber : null}
                    />

                    {/* referral form below */}

Referral Details

                    <FormsyText
                        name="referralReasonForReferral"
                        hintText="Reason for referral"
                        floatingLabelText="Reason for referral"
                        defaultValue={this.props.action === 'update' ? this.props.referral.referralReasonForReferral : null}
                    />

                    <FormsySelect
                        name="referralRequestedService"
                        floatingLabelText="Requested service"
                        value={this.props.action === 'update' ? this.props.referral.referralRequestedService : null}
                    >
                        <MenuItem value={'mentalHealthAssessment'} primaryText="Mental Health Assessment" />
                        <MenuItem value={'medicationReview'} primaryText="Medication Review" />
                        <MenuItem value={'dianogsticClarification'} primaryText="Diagnostic Clarifiction" />
                        <MenuItem value={'assessmentForManagementOfBPSD'} primaryText="Assessment for Management of BPSD" />
                    </FormsySelect>

                    <FormsyToggle
                        name="referralUrgent"
                        label="Urgent"
                        style={style.switchStyle}
                    />

                        <RaisedButton
                            label="Upload"
                            primary={true}
                            style={style.uploadButton}
                        />

Upload additional information (Limited to one PDF file)

                    {/* triage below */}

Triage

                    <FormsySelect
                        name="referralRuralCode"
                        floatingLabelText="Rural code"
                        value={this.props.action === 'update' ? this.props.referral.referralRuralCode : null}
                    >
                        <MenuItem value={'RA1MajorCities'} primaryText="RA1 MajorCities" />
                        <MenuItem value={'RA2InnerRegional'} primaryText="RA2 Inner Regional" />
                        <MenuItem value={'RA3OuterRegional'} primaryText="RA3 Outer Regional" />
                        <MenuItem value={'RA4Remote'} primaryText="RA4 Remote" />
                        <MenuItem value={'RA5VeryRemote'} primaryText="RA5 Very Remote" />
                    </FormsySelect>

                    <FormsyText
                        name="referralAppointmentDay"
                        hintText="Appointment Day"
                        floatingLabelText="Appointment Day"
                        defaultValue={this.props.action === 'update' ? this.props.referral.referralAppointmentDay : null}
                    />

                    <FormsyText
                        name="referralAppointmentMonth"
                        hintText="Appointment Month"
                        floatingLabelText="Appointment Month"
                        defaultValue={this.props.action === 'update' ? this.props.referral.referralAppointmentMonth : null}
                    />

                    <FormsyText
                        name="referralAppointmentYear"
                        hintText="Appointment Year"
                        floatingLabelText="Appointment Year"
                        defaultValue={this.props.action === 'update' ? this.props.referral.referralAppointmentYear : null}
                    />

                    <FormsyText
                        name="referralAppointmentHour"
                        hintText="Appointment Hour"
                        floatingLabelText="Appointment Month"
                        defaultValue={this.props.action === 'update' ? this.props.referral.referralAppointmentHour : null}
                    />

                    <FormsyText
                        name="referralAppointmentMinute"
                        hintText="Appointment Minute"
                        floatingLabelText="Appointment Year"
                        defaultValue={this.props.action === 'update' ? this.props.referral.referralAppointmentMinute : null}
                    />

                    <FormsySelect
                        name="referralAppointmentPeriod"
                        floatingLabelText="Period"
                        value={this.props.action === 'update' ? this.props.referral.referralAppointmentPeriod : null}
                    >
                        <MenuItem value={'AM'} primaryText="AM" />
                        <MenuItem value={'PM'} primaryText="PM" />
                    </FormsySelect>

Last Date reviewed (placeholder)

                    </Formsy.Form>

        )
    }
}

export default ReferralForm

<|endoftext|>


<commit_before>/*

    Client side component to send coverage data after each page's test run.  Served up by the "coverage" engine
    wired into gpii.testem, by default this is available at:

    <script src="/coverage/client/coverageSender.js"></script>

    NOTE: This script requires Testem, and must be loaded after Testem loads, but before your tests start.

    Adapted from https://github.com/testem/testem/blob/master/examples/coverage_istanbul/tests.html#L11

    The harness included with this package will concatenate this with a bit of javascript that instantiates the
    sender with the right port information.  If you are using this script in another context, you will need to take
    care of that yourself.

 */
(function (fluid, $, Testem) {
    "use strict";
    var gpii = fluid.registerNamespace("gpii");

    fluid.registerNamespace("gpii.testem.coverage.sender");

    gpii.testem.coverage.sender.wireTestem = function (that) {
        Testem.afterTests(that.sendCoverageData);
    };

    gpii.testem.coverage.sender.sendCoverageData = function (that, config, data, callback) {
        if (window.__coverage__) {
            // TODO: Convert to using fluid.dataSource.AJAX once that's been reviewed.
            var payload = {
                document:  fluid.filterKeys(document, ["title", "URL"]),
                navigator: fluid.filterKeys(navigator, ["userAgent", "vendor", "vendorSub", "product", "productSub", "appCodeName", "appName"]),
                coverage:  window.__coverage__
            };
            var requestOptions = fluid.extend(that.options.ajaxOptions, {
                data: { payload: JSON.stringify(payload, null, 2)},
                complete: function () {
                    // Temporary delay to help us investigate disconnects when sending coverage data.
                    setTimeout(callback, 250);
                }
            });
            $.ajax(requestOptions);
        }
    };

    gpii.testem.coverage.sender.handleSuccess = function (that, data, textStatus, jqXHR) {
        if (jqXHR.status === 200) {
            fluid.log("Successfully saved coverage results...");
        }
        else {
            fluid.log("Coverage results save returned status code:", jqXHR.status);
        }
    };

    gpii.testem.coverage.sender.handleError = function (that, jqXHR, textStatus, errorThrown) {
        fluid.log("Error saving test coverage:", errorThrown);
    };

    fluid.defaults("gpii.testem.coverage.sender", {
        gradeNames: ["fluid.component"],
        ajaxOptions: {
            method:      "POST",
            url:         "{that}.options.coverageUrl"
        },
        coveragePort: 7000,
        coverageUrl: {
            expander: {
                funcName: "fluid.stringTemplate",
                args:     ["http://localhost:%port/coverage", { port: "{that}.options.coveragePort"}]
            }
        },
        listeners: {
            "onCreate.wireTestem": {
                funcName: "gpii.testem.coverage.sender.wireTestem",
                args:     ["{that}"]
            }
        },
        invokers: {
            "sendCoverageData": {
                funcName: "gpii.testem.coverage.sender.sendCoverageData",
                args: ["{that}", "{arguments}.0", "{arguments}.1", "{arguments}.2"] // config, data, callbackn
            },
            "handleSuccess": {
                funcName: "gpii.testem.coverage.sender.handleSuccess",
                args: ["{that}", "{arguments}.0", "{arguments}.1", "{arguments}.2"] // data, textStatus, jqXHR
            },
            "handleError": {
                funcName: "gpii.testem.coverage.sender.handleError",
                args: ["{that}", "{arguments}.0", "{arguments}.1", "{arguments}.2"] // jqXHR, textStatus, errorThrown
            }
        }
    });
})(fluid, jQuery, Testem);
<commit_msg>GPII-2296:  Ensure Testem callback will also fire when no coverage data is available.<commit_after>/*

    Client side component to send coverage data after each page's test run.  Served up by the "coverage" engine
    wired into gpii.testem, by default this is available at:

    <script src="/coverage/client/coverageSender.js"></script>

    NOTE: This script requires Testem, and must be loaded after Testem loads, but before your tests start.

    Adapted from https://github.com/testem/testem/blob/master/examples/coverage_istanbul/tests.html#L11

    The harness included with this package will concatenate this with a bit of javascript that instantiates the
    sender with the right port information.  If you are using this script in another context, you will need to take
    care of that yourself.

 */
(function (fluid, $, Testem) {
    "use strict";
    var gpii = fluid.registerNamespace("gpii");

    fluid.registerNamespace("gpii.testem.coverage.sender");

    gpii.testem.coverage.sender.wireTestem = function (that) {
        Testem.afterTests(that.sendCoverageData);
    };

    gpii.testem.coverage.sender.sendCoverageData = function (that, config, data, callback) {
        if (window.__coverage__) {
            // TODO: Convert to using fluid.dataSource.AJAX once that's been reviewed.
            var payload = {
                document:  fluid.filterKeys(document, ["title", "URL"]),
                navigator: fluid.filterKeys(navigator, ["userAgent", "vendor", "vendorSub", "product", "productSub", "appCodeName", "appName"]),
                coverage:  window.__coverage__
            };
            var requestOptions = fluid.extend(that.options.ajaxOptions, {
                data: { payload: JSON.stringify(payload, null, 2)},
                complete: function () {
                    // Temporary delay to help us investigate disconnects when sending coverage data.
                    setTimeout(callback, 250);
                }
            });
            $.ajax(requestOptions);
        }
        else {
            fluid.log("No coverage data, firing test completion callback immediately...");
            callback();
        }
    };

    gpii.testem.coverage.sender.handleSuccess = function (that, data, textStatus, jqXHR) {
        if (jqXHR.status === 200) {
            fluid.log("Successfully saved coverage results...");
        }
        else {
            fluid.log("Coverage results save returned status code:", jqXHR.status);
        }
    };

    gpii.testem.coverage.sender.handleError = function (that, jqXHR, textStatus, errorThrown) {
        fluid.log("Error saving test coverage:", errorThrown);
    };

    fluid.defaults("gpii.testem.coverage.sender", {
        gradeNames: ["fluid.component"],
        ajaxOptions: {
            method:      "POST",
            url:         "{that}.options.coverageUrl"
        },
        coveragePort: 7000,
        coverageUrl: {
            expander: {
                funcName: "fluid.stringTemplate",
                args:     ["http://localhost:%port/coverage", { port: "{that}.options.coveragePort"}]
            }
        },
        listeners: {
            "onCreate.wireTestem": {
                funcName: "gpii.testem.coverage.sender.wireTestem",
                args:     ["{that}"]
            }
        },
        invokers: {
            "sendCoverageData": {
                funcName: "gpii.testem.coverage.sender.sendCoverageData",
                args: ["{that}", "{arguments}.0", "{arguments}.1", "{arguments}.2"] // config, data, callbackn
            },
            "handleSuccess": {
                funcName: "gpii.testem.coverage.sender.handleSuccess",
                args: ["{that}", "{arguments}.0", "{arguments}.1", "{arguments}.2"] // data, textStatus, jqXHR
            },
            "handleError": {
                funcName: "gpii.testem.coverage.sender.handleError",
                args: ["{that}", "{arguments}.0", "{arguments}.1", "{arguments}.2"] // jqXHR, textStatus, errorThrown
            }
        }
    });
})(fluid, jQuery, Testem);
<|endoftext|>


<commit_before>import DesktopNotifications from '../libs/notifications';
import Session from '../libs/session';
import Config from '../libs/config';

/**
 * Manager alerts counter (set, get or clear)
 */
class Notifications
{
    constructor() {
        this._counter = 0;
        this._self = $('#btn-alerts');
        this._dropdown = $('#dropdown-alerts');
        this._modal = this._dropdown.find('.dropdown-modal');

        // original page title
        this._pageTitle = $('head title').text();

        this._self.find('a[data-toggle="dropdown"]').click(this._onDropdownClick.bind(this));
        this._dropdown.on('mousedown', 'li a', this._onItemClick.bind(this)).on('click', '#btn-mark-read', this._onMarkClick.bind(this)).on('click', '.btn-delete-alert', this._onDeleteClick.bind(this));
    }

    /**
     * Set alerts counter
     *
     * @param counter
     */
    set(counter) {
        this._counter = parseInt(counter);

        if (this._counter > 0) {
            this._setTitle('(' + (this._counter) + ') ' + this._pageTitle);
            this._setIcon(Config.cdn(`/img/xicon/favicon${Math.min(this._counter, 6)}.png`));
        } else {
            this._setTitle(this._pageTitle);
            this._setIcon(Config.cdn('/img/favicon.png'));
        }

        this._setBadge();
    }

    /**
     * Set alerts counter and save it in local storage.
     *
     * @param counter
     */
    store(counter) {
        this.set(counter);

        Session.setItem('alerts', this._counter);
    }

    /**
     * Get notifications counter
     *
     * @returns {Number|number}
     */
    get() {
        return this._counter;
    }

    /**
     * Remove alerts list
     */
    clear() {
        $('li', this._dropdown).remove();

        if (this._self.hasClass('open')) {
            this._self.dropdown('toggle');
        }
    }

    /**
     * Set unread notification's counter.
     *
     * @private
     */
    _setBadge() {
        let badge = $('.badge', this._self);

        if (this._counter === 0) {
            badge.remove();
        }
        else {
            if (!badge.length) {
                $('> a:first', this._self).prepend(`<span class="badge">${this._counter}</span>`);
            } else {
                badge.text(this._counter);
            }
        }
    }

    /**
     * Set <title> tag.
     *
     * @param title
     * @private
     */
    _setTitle(title) {
        $('head title').text(title);
    }

    /**
     * Set favicon with number of unread notifications.
     *
     * @param url
     * @private
     */
    _setIcon(url) {
        $('head link[rel="shortcut icon"]').attr('href', url);
    }

    /**
     * Bind onclick on notification element.
     *
     * @param e
     * @private
     */
    _onDropdownClick(e) {
        DesktopNotifications.requestPermission();

        let items = this._modal.find('ul');
        const url = $(e.currentTarget).data('url');

        if ($('li', items).length <= 1) {
            $('

').appendTo(items);

            $.get(url, (json) => {
                items.html(json.html);
                this.store(json.unread);

                // default max height of alerts area
                let maxHeight = 420;

                if (parseInt(Session.getItem('box-notify-h'))) {
                    // min height is 190px. max height is (one item height * number of items)
                    maxHeight = Math.min(items.height(), Math.max(190, parseInt(Session.getItem('box-notify-h'))));
                }

                this._modal.css('max-height', maxHeight); // max wysokosc obszaru powiadomien

                // on mobile devices width must be set on 100%
                if (parseInt(Session.getItem('box-notify-w'))  && $(window).width() > 768) {
                    this._dropdown.width(parseInt(Session.getItem('box-notify-w')));
                }

                require.ensure([], (require) => {
                    require('perfect-scrollbar/jquery')($);

                    this._modal.perfectScrollbar({suppressScrollX: true}).on('ps-y-reach-end', {url: url}, this._onScroll);
                });
            });
        }

        e.preventDefault();
    }

    /**
     * Click on notification.
     *
     * @param e
     * @return {boolean}
     * @private
     */
    _onItemClick(e) {
        let $this = $(e.currentTarget);

        $this.parent().removeClass('unread');
        $this.attr('href', $this.data('url'));

        return false;
    }

    /**
     * Mark notification as read.
     *
     * @param e
     * @return {boolean}
     * @private
     */
    _onMarkClick(e) {
        $('li', this._self).removeClass('unread');
        this.store(0);

        $.post($(e.currentTarget).attr('href'));

        return false;
    }

    /**
     * Delete notification.
     *
     * @param e
     * @return {boolean}
     * @private
     */
    _onDeleteClick(e) {
        let $this = $(e.currentTarget);

        $.post($this.attr('href'));
        $this.parent().fadeOut();

        return false;
    }

    /**
     * Infinity scroll.
     *
     * @param e
     * @private
     */
    _onScroll(e) {
        if (this._isRequestOngoing) {
            return;
        }

        let items = $(e.currentTarget).find('ul');
        this._isRequestOngoing = true;

        $.get(e.data.url + '?offset=' + $('li', items).length, json => {
            items.append(json.html);

            if (json.count < 10) {
                $(e.currentTarget).off('ps-y-reach-end');
            }

            this._isRequestOngoing = false;
        });
    }
}

$(function () {
    'use strict';

    let notifications = new Notifications();

    Session.addListener(function (e) {
        if (e.key === 'alerts' && e.newValue !== notifications.get()) {
            notifications.set(e.newValue);
            notifications.clear();
        }
    });

    ws.on('alert', data => {
        notifications.set(notifications.get() + 1);
        notifications.clear();

        DesktopNotifications.doNotify(data.headline, data.subject, data.url);

        // ugly hack to firefox: store counter in session storage with a lille bit of delay.
        // if we have two open tabs both with websocket connection, then each tab will receive it's own
        // notification. saving counter in local storage will call session listener (see above).
        // make a long story short: without setTimeout() one notification will be shown as two if user
        // has two open tabs.
        setTimeout(() => Session.setItem('alerts', notifications.get()), 500);
    });

    setInterval(() => {
        // send ping request to the server just to extend session cookie lifetime.
        $.get(Config.get('ping'), token => {
            $('meta[name="csrf-token"]').attr('content', token);
            $(':hidden[name="_token"]').val(token);

            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': token
                }
            });
        });
    }, Config.get('ping_interval') * 60 * 1000);
});
<commit_msg>zmiana nazwy kanalu websocket<commit_after>import DesktopNotifications from '../libs/notifications';
import Session from '../libs/session';
import Config from '../libs/config';

/**
 * Manager alerts counter (set, get or clear)
 */
class Notifications
{
    constructor() {
        this._counter = 0;
        this._self = $('#btn-alerts');
        this._dropdown = $('#dropdown-alerts');
        this._modal = this._dropdown.find('.dropdown-modal');

        // original page title
        this._pageTitle = $('head title').text();

        this._self.find('a[data-toggle="dropdown"]').click(this._onDropdownClick.bind(this));
        this._dropdown.on('mousedown', 'li a', this._onItemClick.bind(this)).on('click', '#btn-mark-read', this._onMarkClick.bind(this)).on('click', '.btn-delete-alert', this._onDeleteClick.bind(this));
    }

    /**
     * Set alerts counter
     *
     * @param counter
     */
    set(counter) {
        this._counter = parseInt(counter);

        if (this._counter > 0) {
            this._setTitle('(' + (this._counter) + ') ' + this._pageTitle);
            this._setIcon(Config.cdn(`/img/xicon/favicon${Math.min(this._counter, 6)}.png`));
        } else {
            this._setTitle(this._pageTitle);
            this._setIcon(Config.cdn('/img/favicon.png'));
        }

        this._setBadge();
    }

    /**
     * Set alerts counter and save it in local storage.
     *
     * @param counter
     */
    store(counter) {
        this.set(counter);

        Session.setItem('notifications', this._counter);
    }

    /**
     * Get notifications counter
     *
     * @returns {Number|number}
     */
    get() {
        return this._counter;
    }

    /**
     * Remove alerts list
     */
    clear() {
        $('li', this._dropdown).remove();

        if (this._self.hasClass('open')) {
            this._self.dropdown('toggle');
        }
    }

    /**
     * Set unread notification's counter.
     *
     * @private
     */
    _setBadge() {
        let badge = $('.badge', this._self);

        if (this._counter === 0) {
            badge.remove();
        }
        else {
            if (!badge.length) {
                $('> a:first', this._self).prepend(`<span class="badge">${this._counter}</span>`);
            } else {
                badge.text(this._counter);
            }
        }
    }

    /**
     * Set <title> tag.
     *
     * @param title
     * @private
     */
    _setTitle(title) {
        $('head title').text(title);
    }

    /**
     * Set favicon with number of unread notifications.
     *
     * @param url
     * @private
     */
    _setIcon(url) {
        $('head link[rel="shortcut icon"]').attr('href', url);
    }

    /**
     * Bind onclick on notification element.
     *
     * @param e
     * @private
     */
    _onDropdownClick(e) {
        DesktopNotifications.requestPermission();

        let items = this._modal.find('ul');
        const url = $(e.currentTarget).data('url');

        if ($('li', items).length <= 1) {
            $('

').appendTo(items);

            $.get(url, (json) => {
                items.html(json.html);
                this.store(json.unread);

                // default max height of alerts area
                let maxHeight = 420;

                if (parseInt(Session.getItem('box-notify-h'))) {
                    // min height is 190px. max height is (one item height * number of items)
                    maxHeight = Math.min(items.height(), Math.max(190, parseInt(Session.getItem('box-notify-h'))));
                }

                this._modal.css('max-height', maxHeight); // max wysokosc obszaru powiadomien

                // on mobile devices width must be set on 100%
                if (parseInt(Session.getItem('box-notify-w'))  && $(window).width() > 768) {
                    this._dropdown.width(parseInt(Session.getItem('box-notify-w')));
                }

                require.ensure([], (require) => {
                    require('perfect-scrollbar/jquery')($);

                    this._modal.perfectScrollbar({suppressScrollX: true}).on('ps-y-reach-end', {url: url}, this._onScroll);
                });
            });
        }

        e.preventDefault();
    }

    /**
     * Click on notification.
     *
     * @param e
     * @return {boolean}
     * @private
     */
    _onItemClick(e) {
        let $this = $(e.currentTarget);

        $this.parent().removeClass('unread');
        $this.attr('href', $this.data('url'));

        return false;
    }

    /**
     * Mark notification as read.
     *
     * @param e
     * @return {boolean}
     * @private
     */
    _onMarkClick(e) {
        $('li', this._self).removeClass('unread');
        this.store(0);

        $.post($(e.currentTarget).attr('href'));

        return false;
    }

    /**
     * Delete notification.
     *
     * @param e
     * @return {boolean}
     * @private
     */
    _onDeleteClick(e) {
        let $this = $(e.currentTarget);

        $.post($this.attr('href'));
        $this.parent().fadeOut();

        return false;
    }

    /**
     * Infinity scroll.
     *
     * @param e
     * @private
     */
    _onScroll(e) {
        if (this._isRequestOngoing) {
            return;
        }

        let items = $(e.currentTarget).find('ul');
        this._isRequestOngoing = true;

        $.get(e.data.url + '?offset=' + $('li', items).length, json => {
            items.append(json.html);

            if (json.count < 10) {
                $(e.currentTarget).off('ps-y-reach-end');
            }

            this._isRequestOngoing = false;
        });
    }
}

$(function () {
    'use strict';

    let notifications = new Notifications();

    Session.addListener(function (e) {
        if (e.key === 'notifications' && e.newValue !== notifications.get()) {
            notifications.set(e.newValue);
            notifications.clear();
        }
    });

    ws.on('notification', data => {
        notifications.set(notifications.get() + 1);
        notifications.clear();

        DesktopNotifications.doNotify(data.headline, data.subject, data.url);

        // ugly hack to firefox: store counter in session storage with a lille bit of delay.
        // if we have two open tabs both with websocket connection, then each tab will receive it's own
        // notification. saving counter in local storage will call session listener (see above).
        // make a long story short: without setTimeout() one notification will be shown as two if user
        // has two open tabs.
        setTimeout(() => Session.setItem('notifications', notifications.get()), 500);
    });

    setInterval(() => {
        // send ping request to the server just to extend session cookie lifetime.
        $.get(Config.get('ping'), token => {
            $('meta[name="csrf-token"]').attr('content', token);
            $(':hidden[name="_token"]').val(token);

            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': token
                }
            });
        });
    }, Config.get('ping_interval') * 60 * 1000);
});
<|endoftext|>


<commit_before>(function ($) {
  var queryParser = function (a) {
      var i, p, b = {};
      if (a === "") {
        return {};
      }
      for (i = 0; i < a.length; i += 1) {
        p = a[i].split('=');
        if (p.length === 2) {
          b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
        }
      }
      return b;
    };
  $.queryParams = function () {
    return queryParser(window.location.search.substr(1).split('&'));
  };
  $.hashParams = function () {
    return queryParser(window.location.hash.substr(1).split('&'));
  };

  window.Swiftype = window.Swiftype || {};
  Swiftype.root_url = Swiftype.root_url || 'http://api.swiftype.com';
  Swiftype.pingUrl = function (endpoint, callback) {
    var img = new Image();
    img.onload = img.onerror = callback;
    img.src = endpoint;
    setTimeout(callback, 350);
    return false;
  };
  Swiftype.pingSearchResultClick = function (engineKey, docId, callback) {
    var params = {
      t: new Date().getTime(),
      engine_key: engineKey,
      doc_id: docId,
      q: Swiftype.currentQuery
    };
    var url = Swiftype.root_url + '/api/v1/public/analytics/pc?' + $.param(params);
    Swiftype.pingUrl(url, callback);
  };

  $.fn.swiftypeSearch = function (options) {
    var options = $.extend({}, $.fn.swiftypeSearch.defaults, options);

    return this.each(function () {
      var $this = $(this);
      var config = $.meta ? $.extend({}, options, $this.data()) : options;
      $this.data('swiftype-config', config);

      $this.selectedCallback = function (data) {
        return function (e) {
          var $el = $(this);
          e.preventDefault();
          Swiftype.pingSearchResultClick(config.engineKey, data['id'], function() {
            window.location = $el.attr('href');
          });
        };
      };

      $this.registerResult = function ($element, data) {
        $element.data('swiftype-item', data);
        $('a', $element).click($this.selectedCallback(data));
      };

      $this.getContentCache = function () {
        return $('#' + contentCacheId);
      };

      var $resultContainer = $(config.resultContainingElement),
        initialContentOfResultContainer = $resultContainer.html(),
        contentCacheId = 'st-content-cache',
        $contentCache = $this.getContentCache();

      var setSearchHash = function (query, page) {
          location.hash = "stq=" + query + "&stp=" + page;
        };

      var submitSearch = function (query, options) {
          options = $.extend({
            per_page: 10,
            page: 1
          }, options);
          var params = {};

          if (!$contentCache.length) {
            $resultContainer.after("

");
            $contentCache.html(initialContentOfResultContainer).hide();
          }
          $resultContainer.html('
loading...
');

          Swiftype.currentQuery = query;
          params['q'] = query;
          params['engine_key'] = config.engineKey;
          params['page'] = options.page;
          params['per_page'] = options.per_page;

          if (config.searchFields !== undefined) {
            params['search_fields'] = config.searchFields;
          }
          if (config.fetchFields !== undefined) {
            params['fetch_fields'] = config.fetchFields;
          }
          if (config.filters !== undefined) {
            var filters = config.filters;
            if (typeof filters === 'function') {
              filters = filters.call();
            }
            params['filters'] = filters;
          }
          if (config.documentTypes !== undefined) {
            params['document_types'] = config.documentTypes;
          }
          if (config.functionalBoosts !== undefined) {
            params['functional_boosts'] = config.functionalBoosts;
          }
          if (config.sortField !== undefined) {
            var sortField = config.sortField;
            if (typeof sortField === 'function') {
              sortField = sortField.call();
            }
            params['sort_field'] = sortField;
          }
          if (config.sortDirection !== undefined) {
            var sortDirection = config.sortDirection;
            if (typeof sortDirection === 'function') {
              sortDirection = sortDirection.call();
            }
            params['sort_direction'] = sortDirection;
          }

          $.getJSON(Swiftype.root_url + "/api/v1/public/engines/search.json?callback=?", params).success(renderSearchResults);
        };

      $(window).hashchange(function () {
        var params = $.hashParams();
        if (params.stq) {
          submitSearch(params.stq, {
            page: params.stp
          });
        } else {
          var $contentCache = $this.getContentCache();
          if ($contentCache.length) {
            $resultContainer.html(contentCache.html());
            $contentCache.remove();
          }
        }
      });

      var $containingForm = $this.parents('form');
      if ($containingForm) {
        $containingForm.bind('submit', function (e) {
          e.preventDefault();
          var searchQuery = $this.val();
          setSearchHash(searchQuery, 1);
        });
      }

      $('[data-hash][data-page]').live('click', function (e) {
        e.preventDefault();
        var $this = $(this);
        setSearchHash($.hashParams().stq, $this.data('page'));
      });

      var renderSearchResults = function (data) {
          $resultContainer.html('');
          var firstType, info = data.info;
          for (var key in info) {
            if (info.hasOwnProperty(key)) {
              firstType = info[key];
              break;
            }
          }
          var query = firstType.query,
            currentPage = firstType.current_page,
            totalPages = firstType.num_pages;
          $.each(data.records, function (document_type, items) {
            $.each(items, function (idx, item) {
              $this.registerResult($(config.renderFunction(document_type, item)).appendTo($resultContainer), item);
            });
          });
          $(renderPagination(currentPage, totalPages)).appendTo($resultContainer);
        };

      $this.getContext = function () {
        return {
          config: config,
          list: $list,
          registerResult: $this.registerResult
        };
      };

      $(window).hashchange(); // if the swiftype query hash is present onload (maybe the user is pressing the back button), submit a query onload
    });
  };

  var renderPagination = function (currentPage, totalPages) {
      var pages = '',
        previousPage, nextPage;
      if (currentPage != 1) {
        previousPage = currentPage - 1;
        pages = pages + '« previous'
      }
      if (currentPage < totalPages) {
        nextPage = currentPage + 1;
        pages = pages + 'next »'
      }
      return pages;
    };

  var normalize = function (str) {
      return $.trim(str).toLowerCase();
    };

  var defaultRenderFunction = function (document_type, item) {
      return '

' + item['title'] + '

';
    };

  $.fn.swiftypeSearch.defaults = {
    attachTo: undefined,
    documentTypes: undefined,
    filters: undefined,
    engineKey: undefined,
    searchFields: undefined,
    functionalBoosts: undefined,
    sortField: undefined,
    sortDirection: undefined,
    fetchFields: undefined,
    renderFunction: defaultRenderFunction
  };
})(jQuery);<commit_msg>generalize pagination.  default to document type with the most pages<commit_after>(function ($) {
  var queryParser = function (a) {
      var i, p, b = {};
      if (a === "") {
        return {};
      }
      for (i = 0; i < a.length; i += 1) {
        p = a[i].split('=');
        if (p.length === 2) {
          b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
        }
      }
      return b;
    };
  $.queryParams = function () {
    return queryParser(window.location.search.substr(1).split('&'));
  };
  $.hashParams = function () {
    return queryParser(window.location.hash.substr(1).split('&'));
  };

  window.Swiftype = window.Swiftype || {};
  Swiftype.root_url = Swiftype.root_url || 'http://api.swiftype.com';
  Swiftype.pingUrl = function (endpoint, callback) {
    var img = new Image();
    img.onload = img.onerror = callback;
    img.src = endpoint;
    setTimeout(callback, 350);
    return false;
  };
  Swiftype.pingSearchResultClick = function (engineKey, docId, callback) {
    var params = {
      t: new Date().getTime(),
      engine_key: engineKey,
      doc_id: docId,
      q: Swiftype.currentQuery
    };
    var url = Swiftype.root_url + '/api/v1/public/analytics/pc?' + $.param(params);
    Swiftype.pingUrl(url, callback);
  };

  $.fn.swiftypeSearch = function (options) {
    var options = $.extend({}, $.fn.swiftypeSearch.defaults, options);

    return this.each(function () {
      var $this = $(this);
      var config = $.meta ? $.extend({}, options, $this.data()) : options;
      $this.data('swiftype-config', config);

      $this.selectedCallback = function (data) {
        return function (e) {
          var $el = $(this);
          e.preventDefault();
          Swiftype.pingSearchResultClick(config.engineKey, data['id'], function() {
            window.location = $el.attr('href');
          });
        };
      };

      $this.registerResult = function ($element, data) {
        $element.data('swiftype-item', data);
        $('a', $element).click($this.selectedCallback(data));
      };

      $this.getContentCache = function () {
        return $('#' + contentCacheId);
      };

      var $resultContainer = $(config.resultContainingElement),
        initialContentOfResultContainer = $resultContainer.html(),
        contentCacheId = 'st-content-cache',
        $contentCache = $this.getContentCache();

      var setSearchHash = function (query, page) {
          location.hash = "stq=" + query + "&stp=" + page;
        };

      var submitSearch = function (query, options) {
          options = $.extend({
            per_page: 10,
            page: 1
          }, options);
          var params = {};

          if (!$contentCache.length) {
            $resultContainer.after("

");
            $contentCache.html(initialContentOfResultContainer).hide();
          }
          $resultContainer.html('
loading...
');

          Swiftype.currentQuery = query;
          params['q'] = query;
          params['engine_key'] = config.engineKey;
          params['page'] = options.page;
          params['per_page'] = options.per_page;

          if (config.searchFields !== undefined) {
            params['search_fields'] = config.searchFields;
          }
          if (config.fetchFields !== undefined) {
            params['fetch_fields'] = config.fetchFields;
          }
          if (config.filters !== undefined) {
            var filters = config.filters;
            if (typeof filters === 'function') {
              filters = filters.call();
            }
            params['filters'] = filters;
          }
          if (config.documentTypes !== undefined) {
            params['document_types'] = config.documentTypes;
          }
          if (config.functionalBoosts !== undefined) {
            params['functional_boosts'] = config.functionalBoosts;
          }
          if (config.sortField !== undefined) {
            var sortField = config.sortField;
            if (typeof sortField === 'function') {
              sortField = sortField.call();
            }
            params['sort_field'] = sortField;
          }
          if (config.sortDirection !== undefined) {
            var sortDirection = config.sortDirection;
            if (typeof sortDirection === 'function') {
              sortDirection = sortDirection.call();
            }
            params['sort_direction'] = sortDirection;
          }

          $.getJSON(Swiftype.root_url + "/api/v1/public/engines/search.json?callback=?", params).success(renderSearchResults);
        };

      $(window).hashchange(function () {
        var params = $.hashParams();
        if (params.stq) {
          submitSearch(params.stq, {
            page: params.stp
          });
        } else {
          var $contentCache = $this.getContentCache();
          if ($contentCache.length) {
            $resultContainer.html(contentCache.html());
            $contentCache.remove();
          }
        }
      });

      var $containingForm = $this.parents('form');
      if ($containingForm) {
        $containingForm.bind('submit', function (e) {
          e.preventDefault();
          var searchQuery = $this.val();
          setSearchHash(searchQuery, 1);
        });
      }

      $('[data-hash][data-page]').live('click', function (e) {
        e.preventDefault();
        var $this = $(this);
        setSearchHash($.hashParams().stq, $this.data('page'));
      });

      var renderSearchResults = function (data) {
          $resultContainer.html('');
          $.each(data.records, function (documentType, items) {
            $.each(items, function (idx, item) {
              $this.registerResult($(config.renderFunction(documentType, item)).appendTo($resultContainer), item);
            });
          });
          renderPagination($this.getContext(), data.info);
        };

      $this.getContext = function () {
        return {
          config: config,
          resultContainer: $resultContainer,
          registerResult: $this.registerResult
        };
      };

      $(window).hashchange(); // if the swiftype query hash is present onload (maybe the user is pressing the back button), submit a query onload
    });
  };

  var renderPagination = function (ctx, resultInfo) {
    var maxPagesType, maxPages = 0;
    $.each(resultInfo, function(documentType, typeInfo) {
      if (typeInfo.num_pages > maxPages) {
        maxPagesType = documentType;
      }
    });
    var currentPage = resultInfo[maxPagesType].current_page,
      totalPages = resultInfo[maxPagesType].num_pages;
    $(renderPaginationForType(maxPagesType, currentPage, totalPages)).appendTo(ctx.resultContainer);
  };

  var renderPaginationForType = function (type, currentPage, totalPages) {
      var pages = '',
        previousPage, nextPage;
      if (currentPage != 1) {
        previousPage = currentPage - 1;
        pages = pages + '« previous'
      }
      if (currentPage < totalPages) {
        nextPage = currentPage + 1;
        pages = pages + 'next »'
      }
      return pages;
    };

  var normalize = function (str) {
      return $.trim(str).toLowerCase();
    };

  var defaultRenderFunction = function (document_type, item) {
      return '

' + item['title'] + '

';
    };

  $.fn.swiftypeSearch.defaults = {
    attachTo: undefined,
    documentTypes: undefined,
    filters: undefined,
    engineKey: undefined,
    searchFields: undefined,
    functionalBoosts: undefined,
    sortField: undefined,
    sortDirection: undefined,
    fetchFields: undefined,
    renderFunction: defaultRenderFunction
  };
})(jQuery);<|endoftext|>


<commit_before>var expect = require('expect.js'),
    common = require('./common');
    _ = require('underscore')._,
    sinon = require("sinon"),
    models = require("../lib/server-models"),
    request = require('superagent'),
    mandrill = require("mandrill-api"),
    outbox = [],

describe("SUPERUSER SENDS FOLLOWUP EMAILS (BROWSER)", function() {
    var browser = null;

    if (process.env.SKIP_SELENIUM_TESTS) {
        return;
    }
    this.timeout(60000); // Extra long timeout for selenium :(

    before(function(done) {
        this.timeout(240000);

        /* Mock Mandrill's API here */

        mandrill.Mandrill = function(apiKey) {

            this.messages = {
                send: function(messageObj) {
                    outbox.push(messageObj.message);
                }
            }
        };

        common.getSeleniumBrowser(function (theBrowser) {
            browser = theBrowser;
            common.standardSetup(function() {
                event = common.server.db.events.findWhere({shortName: "writers-at-work"});
                event.set("open", true);
                done();
            });
        });
    });

    after(function(done) {
        browser.quit().then(function() {
            common.standardShutdown(done);
        });
    });

    function generateUserData() {
        var clock = sinon.useFakeTimers(1, "setTimeout", "clearTimeout", "Date");

        var session = event.get("sessions").at(1);
        session.set("approved", true);

        session.set("hangout-url", "http://example.com");

        var user_one = common.server.db.users.get(1);
        user_one.set("displayName", "Srishti");
        user_one.set("picture", "http://pldb.media.mit.edu/face/srishti");

        var preferredContact = {};
        preferredContact.emailInfo = "srishakatux@gmail.com";
        preferredContact.twitterHandle = "srishakatux";

        user_one.set("preferredContact", preferredContact)

        var user_two = common.server.db.users.get(2);
        user_two.set("displayName", "Unhangout Developer");
        user_two.set("picture", "https://lh3.googleusercontent.com/-OP7MAxbSCvs/AAAAAAAAAAI/AAAAAAAAAEA/js2MqRDWiJk/photo.jpg");

        var user_three = common.server.db.users.get(3);
        user_three.set("displayName", "Jules");
        user_three.set("picture", "http://lh4.googleusercontent.com/-8NHi4O5-AF0/AAAAAAAAAAI/AAAAAAAAAAA/8kJJNYEwztM/s32-c/photo.jpg");

        var superuser1 = common.server.db.users.findWhere({"sock-key": "superuser1"});

        event.get("connectedUsers").add(user_one);
        event.get("connectedUsers").add(user_two);
        event.get("connectedUsers").add(user_three);
        event.get("connectedUsers").add(superuser1);

        session.addConnectedParticipant(user_one);
        session.addConnectedParticipant(user_two);
        session.addConnectedParticipant(user_three);

        var history = {events: {}, sessions: {}};

        history.event = {"1" : {start: 0, total: 1000}, "2": {start: 0, total: 1000}, "3" : {start: 0, total: 1000}};

        history.sessions[session.id] = {"1": {"1": {total: 2346, start: 0}, "2": {total: 2346, start: 0}, "3": {total: 2346, start: 0}}};

        clock.restore();

        var userData = [];

        _.each(history, function(elapsedTime, userId) {

            //Get the user object for a specific ID
            var user = common.server.db.users.get(userId);

            // Find all userIDs for users who shared sessions with me at this event.
            var userIds = event.getUserIdsSharingSessionsWith(userId);

            // get user objects for the IDs.
            var users = _.map(userIds, function(userId) {
                return common.server.db.users.get(userId);
            });

            userData.push({ user: user, users: users });

        });

        return userData;

    };

    it("Is prompted to login when unauthenticated", function(done) {
        browser.get(common.URL);
        browser.byCss("#login-first-button").click();
        browser.waitForSelector("#login-first-modal h4");
        browser.byCss("#login-first-modal h4").getText().then(function(text) {
            expect(text).to.eql("Please log in!");
            done();
        });
    });

    it("Super User sends followup emails", function(done) {

        browser.mockAuthenticate("superuser1");
        //Superuser goes to the event page.  Connect a socket to a session.
        browser.get(common.URL + "/event/" + event.id)
        browser.waitForEventReady(event, "superuser1");
        browser.byCss("#submit-contact-info").click();

        userData = generateUserData();
        userData.unshift(null);

        request.get(common.URL + '/followup/event/' + event.id + '/participant_1')
            .send({userData: userData, participantIndex: 1})
            .redirects(0)
            .end(function(res) {
                done();
            });

        browser.byCss(".admin-button").click();
        browser.waitForSelector("#superuser-page-for-followupemail");
        browser.byCss("#superuser-page-for-followupemail").click();

        browser.get(common.URL + '/followup/event/' + event.id + '/participant_1');

        browser.byCss("#send-email-to-all").click();

        browser.waitForSelector("#send-now-button");

        browser.byCss("#send-now-button").click().then(function() {
            generateUserData();

            var noOfUsers = event.get("connectedUsers").length;

            expect(outbox.length).to.be(noOfUsers);

            expect(outbox[0].to[0].email).to.be("regular2@example.com");
            expect(outbox[0].from_email).to.be("noreply@media.mit.edu");
            expect(outbox[0].subject).to.be("Unhangout Event: Followup");
            expect(outbox[0].html).to.not.eql(-1);
            //expect(outbox[0].html).to.be("Unhangout Event: Followup");

            outbox.length =  0;

        });

    });

});
<commit_msg>removed the view code from email test<commit_after>var expect = require('expect.js'),
    common = require('./common');
    _ = require('underscore')._,
    sinon = require("sinon"),
    models = require("../lib/server-models"),
    request = require('superagent'),
    mandrill = require("mandrill-api"),
    outbox = [];

describe("SUPERUSER SENDS FOLLOWUP EMAILS (BROWSER)", function() {
    var browser = null;

    if (process.env.SKIP_SELENIUM_TESTS) {
        return;
    }
    this.timeout(60000); // Extra long timeout for selenium :(

    before(function(done) {
        this.timeout(240000);

        /* Mock Mandrill's API here */

        mandrill.Mandrill = function(apiKey) {

            this.messages = {
                send: function(messageObj) {
                    outbox.push(messageObj.message);
                }
            }
        };

        common.getSeleniumBrowser(function (theBrowser) {
            browser = theBrowser;
            common.standardSetup(function() {
                event = common.server.db.events.findWhere({shortName: "writers-at-work"});
                event.set("open", true);
                done();
            });
        });
    });

    after(function(done) {
        browser.quit().then(function() {
            common.standardShutdown(done);
        });
    });

    function setEvent() {
        var session = event.get("sessions").at(1);
        session.set("approved", true);

        session.set("hangout-url", "http://example.com");

        var user_one = common.server.db.users.get(1);
        user_one.set("displayName", "Srishti");
        user_one.set("picture", "http://pldb.media.mit.edu/face/srishti");

        var preferredContact = {};
        preferredContact.emailInfo = "srishakatux@gmail.com";
        preferredContact.twitterHandle = "srishakatux";

        user_one.set("preferredContact", preferredContact)

        var user_two = common.server.db.users.get(2);
        user_two.set("displayName", "Unhangout Developer");
        user_two.set("picture", "https://lh3.googleusercontent.com/-OP7MAxbSCvs/AAAAAAAAAAI/AAAAAAAAAEA/js2MqRDWiJk/photo.jpg");

        var user_three = common.server.db.users.get(3);
        user_three.set("displayName", "Jules");
        user_three.set("picture", "http://lh4.googleusercontent.com/-8NHi4O5-AF0/AAAAAAAAAAI/AAAAAAAAAAA/8kJJNYEwztM/s32-c/photo.jpg");

        var superuser1 = common.server.db.users.findWhere({"sock-key": "superuser1"});

        event.get("connectedUsers").add(user_one);
        event.get("connectedUsers").add(user_two);
        event.get("connectedUsers").add(user_three);
        event.get("connectedUsers").add(superuser1);

        session.addConnectedParticipant(user_one);
        session.addConnectedParticipant(user_two);
        session.addConnectedParticipant(user_three);

        var history = {events: {}, sessions: {}};

        history.event = {"1" : {start: 0, total: 1000}, "2": {start: 0, total: 1000}, "3" : {start: 0, total: 1000}};

        history.sessions[session.id] = {"1": {"1": {total: 2346, start: 0}, "2": {total: 2346, start: 0}, "3": {total: 2346, start: 0}}};

    };

    it("Is prompted to login when unauthenticated", function(done) {
        browser.get(common.URL);
        browser.byCss("#login-first-button").click();
        browser.waitForSelector("#login-first-modal h4");
        browser.byCss("#login-first-modal h4").getText().then(function(text) {
            expect(text).to.eql("Please log in!");
            done();
        });
    });

    it("Super User sends followup emails", function(done) {

        browser.mockAuthenticate("superuser1");
        //Superuser goes to the event page.  Connect a socket to a session.
        browser.get(common.URL + "/event/" + event.id)
        browser.waitForEventReady(event, "superuser1");

        //Set event function sets the state of the event
        //and related user models
        setEvent();

        browser.byCss("#submit-contact-info").click();

        browser.byCss(".admin-button").click();
        browser.waitForSelector("#superuser-page-for-followupemail");
        browser.byCss("#superuser-page-for-followupemail").click();

        browser.get(common.URL + '/followup/event/' + event.id + '/participant_1');

        browser.byCss("#send-email-to-all").click();

        browser.waitForSelector("#send-now-button");

        browser.byCss("#send-now-button").click().then(function() {
            setEvent();

            var noOfUsers = event.get("connectedUsers").length;
            expect(outbox.length).to.be(noOfUsers);

            expect(outbox[0].to[0].email).to.be("regular2@example.com");
            expect(outbox[0].from_email).to.be("noreply@media.mit.edu");
            expect(outbox[0].subject).to.be("Unhangout Event: Followup");
            expect(outbox[0].html).to.not.eql(-1);

            outbox.length =  0;
            done();
        });

    });

});
<|endoftext|>