<commit_before>/*
Copyright 2017 New Vector Ltd.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import sdk from '../../../index';
import dis from '../../../dispatcher';
import React from 'react';
import { _t } from '../../../languageHandler';
import linkifyElement from 'linkifyjs/element';
import linkifyMatrix from '../../../linkify-matrix';
import { ContentRepo } from 'matrix-js-sdk';
import MatrixClientPeg from '../../../MatrixClientPeg';
import PropTypes from 'prop-types';
import classNames from 'classnames';

function getDisplayAliasForRoom(room) {
    return room.canonicalAlias || (room.aliases ? room.aliases[0] : "");
}

export const roomShape = PropTypes.shape({
    name: PropTypes.string,
    topic: PropTypes.string,
    roomId: PropTypes.string,
    avatarUrl: PropTypes.string,
    numJoinedMembers: PropTypes.number,
    canonicalAlias: PropTypes.string,
    aliases: PropTypes.arrayOf(PropTypes.string),

    worldReadable: PropTypes.bool,
    guestCanJoin: PropTypes.bool,
});

export default React.createClass({
    propTypes: {
        room: roomShape,
        // passes ev, room as args
        onClick: PropTypes.func,
        onMouseDown: PropTypes.func,
    },

    _linkifyTopic: function() {
        if (this.refs.topic) {
            linkifyElement(this.refs.topic, linkifyMatrix.options);
        }
    },

    componentDidMount: function() {
        this._linkifyTopic();
    },

    componentDidUpdate: function() {
        this._linkifyTopic();
    },

    onClick: function(ev) {
        ev.preventDefault();
        if (this.props.onClick) {
            this.props.onClick(ev, this.props.room);
        }
    },

    onTopicClick: function(ev) {
        // When clicking a link in the topic, prevent the event being propagated
        // to `onClick`.
        ev.stopPropagation();
    },

    render: function() {
        const BaseAvatar = sdk.getComponent('avatars.BaseAvatar');

        const room = this.props.room;
        const name = room.name || getDisplayAliasForRoom(room) || _t('Unnamed room');

        const guestRead = room.worldReadable ? (

{ _t('World readable') }

            ) :
;
        const guestJoin = room.guestCanJoin ? (

{ _t('Guests can join') }

            ) :
;

        const perms = (guestRead || guestJoin) ? (

            { guestRead }
            { guestJoin }

) :
;

        return

                <BaseAvatar width={24} height={24} resizeMethod='crop'
                    name={name} idName={name}
                    url={ContentRepo.getHttpUriForMxc(
                            MatrixClientPeg.get().getHomeserverUrl(),
                            room.avatarUrl, 24, 24, "crop")} />

{ name }

                { perms }

                    { room.topic }

{ getDisplayAliasForRoom(room) }

                { room.numJoinedMembers }

;
    },
});
<commit_msg>remove unused imports<commit_after>/*
Copyright 2017 New Vector Ltd.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import sdk from '../../../index';
import React from 'react';
import { _t } from '../../../languageHandler';
import linkifyElement from 'linkifyjs/element';
import linkifyMatrix from '../../../linkify-matrix';
import { ContentRepo } from 'matrix-js-sdk';
import MatrixClientPeg from '../../../MatrixClientPeg';
import PropTypes from 'prop-types';

export function getDisplayAliasForRoom(room) {
    return room.canonicalAlias || (room.aliases ? room.aliases[0] : "");
}

export const roomShape = PropTypes.shape({
    name: PropTypes.string,
    topic: PropTypes.string,
    roomId: PropTypes.string,
    avatarUrl: PropTypes.string,
    numJoinedMembers: PropTypes.number,
    canonicalAlias: PropTypes.string,
    aliases: PropTypes.arrayOf(PropTypes.string),

    worldReadable: PropTypes.bool,
    guestCanJoin: PropTypes.bool,
});

export default React.createClass({
    propTypes: {
        room: roomShape,
        // passes ev, room as args
        onClick: PropTypes.func,
        onMouseDown: PropTypes.func,
    },

    _linkifyTopic: function() {
        if (this.refs.topic) {
            linkifyElement(this.refs.topic, linkifyMatrix.options);
        }
    },

    componentDidMount: function() {
        this._linkifyTopic();
    },

    componentDidUpdate: function() {
        this._linkifyTopic();
    },

    onClick: function(ev) {
        ev.preventDefault();
        if (this.props.onClick) {
            this.props.onClick(ev, this.props.room);
        }
    },

    onTopicClick: function(ev) {
        // When clicking a link in the topic, prevent the event being propagated
        // to `onClick`.
        ev.stopPropagation();
    },

    render: function() {
        const BaseAvatar = sdk.getComponent('avatars.BaseAvatar');

        const room = this.props.room;
        const name = room.name || getDisplayAliasForRoom(room) || _t('Unnamed room');

        const guestRead = room.worldReadable ? (

{ _t('World readable') }

            ) :
;
        const guestJoin = room.guestCanJoin ? (

{ _t('Guests can join') }

            ) :
;

        const perms = (guestRead || guestJoin) ? (

            { guestRead }
            { guestJoin }

) :
;

        return

                <BaseAvatar width={24} height={24} resizeMethod='crop'
                    name={name} idName={name}
                    url={ContentRepo.getHttpUriForMxc(
                            MatrixClientPeg.get().getHomeserverUrl(),
                            room.avatarUrl, 24, 24, "crop")} />

{ name }

                { perms }

                    { room.topic }

{ getDisplayAliasForRoom(room) }

                { room.numJoinedMembers }

;
    },
});
<|endoftext|>


<commit_before>/*
Copyright 2018 New Vector Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import React from 'react';
import classNames from 'classnames';
import {_t, _td} from '../../../languageHandler';
import AppTile from '../elements/AppTile';
import {MatrixClientPeg} from '../../../MatrixClientPeg';
import * as sdk from '../../../index';
import dis from '../../../dispatcher/dispatcher';
import AccessibleButton from '../elements/AccessibleButton';
import WidgetUtils from '../../../utils/WidgetUtils';
import PersistedElement from "../elements/PersistedElement";
import {IntegrationManagers} from "../../../integrations/IntegrationManagers";
import SettingsStore from "../../../settings/SettingsStore";
import {ContextMenu} from "../../structures/ContextMenu";
import {WidgetType} from "../../../widgets/WidgetType";
import AccessibleTooltipButton from "../elements/AccessibleTooltipButton";
import {Action} from "../../../dispatcher/actions";
import {WidgetMessagingStore} from "../../../stores/widgets/WidgetMessagingStore";
import {replaceableComponent} from "../../../utils/replaceableComponent";

// This should be below the dialog level (4000), but above the rest of the UI (1000-2000).
// We sit in a context menu, so this should be given to the context menu.
const STICKERPICKER_Z_INDEX = 3500;

// Key to store the widget's AppTile under in PersistedElement
const PERSISTED_ELEMENT_KEY = "stickerPicker";

@replaceableComponent("views.rooms.Stickerpicker")
export default class Stickerpicker extends React.Component {
    static currentWidget;

    constructor(props) {
        super(props);
        this._onShowStickersClick = this._onShowStickersClick.bind(this);
        this._onHideStickersClick = this._onHideStickersClick.bind(this);
        this._launchManageIntegrations = this._launchManageIntegrations.bind(this);
        this._removeStickerpickerWidgets = this._removeStickerpickerWidgets.bind(this);
        this._updateWidget = this._updateWidget.bind(this);
        this._onWidgetAction = this._onWidgetAction.bind(this);
        this._onResize = this._onResize.bind(this);
        this._onFinished = this._onFinished.bind(this);

        this.popoverWidth = 300;
        this.popoverHeight = 300;

        // This is loaded by _acquireScalarClient on an as-needed basis.
        this.scalarClient = null;

        this.state = {
            showStickers: false,
            imError: null,
            stickerpickerX: null,
            stickerpickerY: null,
            stickerpickerWidget: null,
            widgetId: null,
        };
    }

    _acquireScalarClient() {
        if (this.scalarClient) return Promise.resolve(this.scalarClient);
        // TODO: Pick the right manager for the widget
        if (IntegrationManagers.sharedInstance().hasManager()) {
            this.scalarClient = IntegrationManagers.sharedInstance().getPrimaryManager().getScalarClient();
            return this.scalarClient.connect().then(() => {
                this.forceUpdate();
                return this.scalarClient;
            }).catch((e) => {
                this._imError(_td("Failed to connect to integration manager"), e);
            });
        } else {
            IntegrationManagers.sharedInstance().openNoManagerDialog();
        }
    }

    async _removeStickerpickerWidgets() {
        const scalarClient = await this._acquireScalarClient();
        console.log('Removing Stickerpicker widgets');
        if (this.state.widgetId) {
            if (scalarClient) {
                scalarClient.disableWidgetAssets(WidgetType.STICKERPICKER, this.state.widgetId).then(() => {
                    console.log('Assets disabled');
                }).catch((err) => {
                    console.error('Failed to disable assets');
                });
            } else {
                console.error("Cannot disable assets: no scalar client");
            }
        } else {
            console.warn('No widget ID specified, not disabling assets');
        }

        this.setState({showStickers: false});
        WidgetUtils.removeStickerpickerWidgets().then(() => {
            this.forceUpdate();
        }).catch((e) => {
            console.error('Failed to remove sticker picker widget', e);
        });
    }

    componentDidMount() {
        // Close the sticker picker when the window resizes
        window.addEventListener('resize', this._onResize);

        this.dispatcherRef = dis.register(this._onWidgetAction);

        // Track updates to widget state in account data
        MatrixClientPeg.get().on('accountData', this._updateWidget);

        // Initialise widget state from current account data
        this._updateWidget();
    }

    componentWillUnmount() {
        const client = MatrixClientPeg.get();
        if (client) client.removeListener('accountData', this._updateWidget);

        window.removeEventListener('resize', this._onResize);
        if (this.dispatcherRef) {
            dis.unregister(this.dispatcherRef);
        }
    }

    componentDidUpdate(prevProps, prevState) {
        this._sendVisibilityToWidget(this.state.showStickers);
    }

    _imError(errorMsg, e) {
        console.error(errorMsg, e);
        this.setState({
            showStickers: false,
            imError: _t(errorMsg),
        });
    }

    _updateWidget() {
        const stickerpickerWidget = WidgetUtils.getStickerpickerWidgets()[0];
        if (!stickerpickerWidget) {
            Stickerpicker.currentWidget = null;
            this.setState({stickerpickerWidget: null, widgetId: null});
            return;
        }

        const currentWidget = Stickerpicker.currentWidget;
        let currentUrl = null;
        if (currentWidget && currentWidget.content && currentWidget.content.url) {
            currentUrl = currentWidget.content.url;
        }

        let newUrl = null;
        if (stickerpickerWidget && stickerpickerWidget.content && stickerpickerWidget.content.url) {
            newUrl = stickerpickerWidget.content.url;
        }

        if (newUrl !== currentUrl) {
            // Destroy the existing frame so a new one can be created
            PersistedElement.destroyElement(PERSISTED_ELEMENT_KEY);
        }

        Stickerpicker.currentWidget = stickerpickerWidget;
        this.setState({
            stickerpickerWidget,
            widgetId: stickerpickerWidget ? stickerpickerWidget.id : null,
        });
    }

    _onWidgetAction(payload) {
        switch (payload.action) {
            case "user_widget_updated":
                this.forceUpdate();
                break;
            case "stickerpicker_close":
                this.setState({showStickers: false});
                break;
            case Action.AfterRightPanelPhaseChange:
            case "show_left_panel":
            case "hide_left_panel":
                this.setState({showStickers: false});
                break;
        }
    }

    _defaultStickerpickerContent() {
        return (
            <AccessibleButton onClick={this._launchManageIntegrations}
                className='mx_Stickers_contentPlaceholder'>

{ _t("You don't currently have any stickerpacks enabled") }

{ _t("Add some now") }

            </AccessibleButton>
        );
    }

    _errorStickerpickerContent() {
        return (

 { this.state.imError }

        );
    }

    _sendVisibilityToWidget(visible) {
        if (!this.state.stickerpickerWidget) return;
        const messaging = WidgetMessagingStore.instance.getMessagingForId(this.state.stickerpickerWidget.id);
        if (messaging && visible !== this._prevSentVisibility) {
            messaging.updateVisibility(visible).catch(err => {
                console.error("Error updating widget visibility: ", err);
            });
            this._prevSentVisibility = visible;
        }
    }

    _getStickerpickerContent() {
        // Handle Integration Manager errors
        if (this.state._imError) {
            return this._errorStickerpickerContent();
        }

        // Stickers
        // TODO - Add support for Stickerpickers from multiple app stores.
        // Render content from multiple stickerpack sources, each within their
        // own iframe, within the stickerpicker UI element.
        const stickerpickerWidget = this.state.stickerpickerWidget;
        let stickersContent;

        // Use a separate ReactDOM tree to render the AppTile separately so that it persists and does
        // not unmount when we (a) close the sticker picker (b) switch rooms. It's properties are still
        // updated.
        const PersistedElement = sdk.getComponent("elements.PersistedElement");

        // Load stickerpack content
        if (stickerpickerWidget && stickerpickerWidget.content && stickerpickerWidget.content.url) {
            // Set default name
            stickerpickerWidget.content.name = stickerpickerWidget.name || _t("Stickerpack");

            // FIXME: could this use the same code as other apps?
            const stickerApp = {
                id: stickerpickerWidget.id,
                url: stickerpickerWidget.content.url,
                name: stickerpickerWidget.content.name,
                type: stickerpickerWidget.content.type,
                data: stickerpickerWidget.content.data,
            };

            stickersContent = (

                        <PersistedElement persistKey={PERSISTED_ELEMENT_KEY} zIndex={STICKERPICKER_Z_INDEX}>
                            <AppTile
                                app={stickerApp}
                                room={this.props.room}
                                fullWidth={true}
                                userId={MatrixClientPeg.get().credentials.userId}
                                creatorUserId={stickerpickerWidget.sender || MatrixClientPeg.get().credentials.userId}
                                waitForIframeLoad={true}
                                showMenubar={true}
                                onEditClick={this._launchManageIntegrations}
                                onDeleteClick={this._removeStickerpickerWidgets}
                                showTitle={false}
                                showCancel={false}
                                showPopout={false}
                                onMinimiseClick={this._onHideStickersClick}
                                handleMinimisePointerEvents={true}
                                userWidget={true}
                            />
                        </PersistedElement>

            );
        } else {
            // Default content to show if stickerpicker widget not added
            stickersContent = this._defaultStickerpickerContent();
        }
        return stickersContent;
    }

    // Dev note: this isn't jsdoc because it's angry.
    /*
     * Show the sticker picker overlay
     * If no stickerpacks have been added, show a link to the integration manager add sticker packs page.
     */
    _onShowStickersClick(e) {
        if (!SettingsStore.getValue("integrationProvisioning")) {
            // Intercept this case and spawn a warning.
            return IntegrationManagers.sharedInstance().showDisabledDialog();
        }

        // XXX: Simplify by using a context menu that is positioned relative to the sticker picker button

        const buttonRect = e.target.getBoundingClientRect();

        // The window X and Y offsets are to adjust position when zoomed in to page
        let x = buttonRect.right + window.pageXOffset - 41;

        // Amount of horizontal space between the right of menu and the right of the viewport
        //  (10 = amount needed to make chevron centrally aligned)
        const rightPad = 10;

        // When the sticker picker would be displayed off of the viewport, adjust x
        //  (302 = width of context menu, including borders)
        x = Math.min(x, document.body.clientWidth - (302 + rightPad));

        // Offset the chevron location, which is relative to the left of the context menu
        //  (10 = offset when context menu would not be displayed off viewport)
        //  (2 = context menu borders)
        const stickerPickerChevronOffset = Math.max(10, 2 + window.pageXOffset + buttonRect.left - x);

        const y = (buttonRect.top + (buttonRect.height / 2) + window.pageYOffset) - 19;

        this.setState({
            showStickers: true,
            stickerPickerX: x,
            stickerPickerY: y,
            stickerPickerChevronOffset,
        });
    }

    /**
     * Trigger hiding of the sticker picker overlay
     * @param  {Event} ev Event that triggered the function call
     */
    _onHideStickersClick(ev) {
        this.setState({showStickers: false});
    }

    /**
     * Called when the window is resized
     */
    _onResize() {
        this.setState({showStickers: false});
    }

    /**
     * The stickers picker was hidden
     */
    _onFinished() {
        this.setState({showStickers: false});
    }

    /**
     * Launch the integration manager on the stickers integration page
     */
    _launchManageIntegrations() {
        // TODO: Open the right integration manager for the widget
        if (SettingsStore.getValue("feature_many_integration_managers")) {
            IntegrationManagers.sharedInstance().openAll(
                this.props.room,
                `type_${WidgetType.STICKERPICKER.preferred}`,
                this.state.widgetId,
            );
        } else {
            IntegrationManagers.sharedInstance().getPrimaryManager().open(
                this.props.room,
                `type_${WidgetType.STICKERPICKER.preferred}`,
                this.state.widgetId,
            );
        }
    }

    render() {
        let stickerPicker;
        let stickersButton;
        const className = classNames(
            "mx_MessageComposer_button",
            "mx_MessageComposer_stickers",
            "mx_Stickers_hideStickers",
            "mx_MessageComposer_button_highlight",
        );
        if (this.state.showStickers) {
            // Show hide-stickers button
            stickersButton =
                <AccessibleButton
                    id='stickersButton'
                    key="controls_hide_stickers"
                    className={className}
                    onClick={this._onHideStickersClick}
                    active={this.state.showStickers}
                    title={_t("Hide Stickers")}
                >
                </AccessibleButton>;

            const GenericElementContextMenu = sdk.getComponent('context_menus.GenericElementContextMenu');
            stickerPicker = <ContextMenu
                chevronOffset={this.state.stickerPickerChevronOffset}
                chevronFace="bottom"
                left={this.state.stickerPickerX}
                top={this.state.stickerPickerY}
                menuWidth={this.popoverWidth}
                menuHeight={this.popoverHeight}
                onFinished={this._onFinished}
                menuPaddingTop={0}
                menuPaddingLeft={0}
                menuPaddingRight={0}
                zIndex={STICKERPICKER_Z_INDEX}
            >
                <GenericElementContextMenu element={this._getStickerpickerContent()} onResize={this._onFinished} />
            </ContextMenu>;
        } else {
            // Show show-stickers button
            stickersButton =
                <AccessibleTooltipButton
                    id='stickersButton'
                    key="controls_show_stickers"
                    className="mx_MessageComposer_button mx_MessageComposer_stickers"
                    onClick={this._onShowStickersClick}
                    title={_t("Show Stickers")}
                >
                </AccessibleTooltipButton>;
        }
        return <React.Fragment>
            { stickersButton }
            { stickerPicker }
        </React.Fragment>;
    }
}
<commit_msg>Prevent unneeded state updates to hide StickerPicker<commit_after>/*
Copyright 2018 New Vector Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import React from 'react';
import classNames from 'classnames';
import {_t, _td} from '../../../languageHandler';
import AppTile from '../elements/AppTile';
import {MatrixClientPeg} from '../../../MatrixClientPeg';
import * as sdk from '../../../index';
import dis from '../../../dispatcher/dispatcher';
import AccessibleButton from '../elements/AccessibleButton';
import WidgetUtils from '../../../utils/WidgetUtils';
import PersistedElement from "../elements/PersistedElement";
import {IntegrationManagers} from "../../../integrations/IntegrationManagers";
import SettingsStore from "../../../settings/SettingsStore";
import {ContextMenu} from "../../structures/ContextMenu";
import {WidgetType} from "../../../widgets/WidgetType";
import AccessibleTooltipButton from "../elements/AccessibleTooltipButton";
import {Action} from "../../../dispatcher/actions";
import {WidgetMessagingStore} from "../../../stores/widgets/WidgetMessagingStore";
import {replaceableComponent} from "../../../utils/replaceableComponent";

// This should be below the dialog level (4000), but above the rest of the UI (1000-2000).
// We sit in a context menu, so this should be given to the context menu.
const STICKERPICKER_Z_INDEX = 3500;

// Key to store the widget's AppTile under in PersistedElement
const PERSISTED_ELEMENT_KEY = "stickerPicker";

@replaceableComponent("views.rooms.Stickerpicker")
export default class Stickerpicker extends React.PureComponent {
    static currentWidget;

    constructor(props) {
        super(props);
        this._onShowStickersClick = this._onShowStickersClick.bind(this);
        this._onHideStickersClick = this._onHideStickersClick.bind(this);
        this._launchManageIntegrations = this._launchManageIntegrations.bind(this);
        this._removeStickerpickerWidgets = this._removeStickerpickerWidgets.bind(this);
        this._updateWidget = this._updateWidget.bind(this);
        this._onWidgetAction = this._onWidgetAction.bind(this);
        this._onResize = this._onResize.bind(this);
        this._onFinished = this._onFinished.bind(this);

        this.popoverWidth = 300;
        this.popoverHeight = 300;

        // This is loaded by _acquireScalarClient on an as-needed basis.
        this.scalarClient = null;

        this.state = {
            showStickers: false,
            imError: null,
            stickerpickerX: null,
            stickerpickerY: null,
            stickerpickerWidget: null,
            widgetId: null,
        };
    }

    _acquireScalarClient() {
        if (this.scalarClient) return Promise.resolve(this.scalarClient);
        // TODO: Pick the right manager for the widget
        if (IntegrationManagers.sharedInstance().hasManager()) {
            this.scalarClient = IntegrationManagers.sharedInstance().getPrimaryManager().getScalarClient();
            return this.scalarClient.connect().then(() => {
                this.forceUpdate();
                return this.scalarClient;
            }).catch((e) => {
                this._imError(_td("Failed to connect to integration manager"), e);
            });
        } else {
            IntegrationManagers.sharedInstance().openNoManagerDialog();
        }
    }

    async _removeStickerpickerWidgets() {
        const scalarClient = await this._acquireScalarClient();
        console.log('Removing Stickerpicker widgets');
        if (this.state.widgetId) {
            if (scalarClient) {
                scalarClient.disableWidgetAssets(WidgetType.STICKERPICKER, this.state.widgetId).then(() => {
                    console.log('Assets disabled');
                }).catch((err) => {
                    console.error('Failed to disable assets');
                });
            } else {
                console.error("Cannot disable assets: no scalar client");
            }
        } else {
            console.warn('No widget ID specified, not disabling assets');
        }

        this.setState({showStickers: false});
        WidgetUtils.removeStickerpickerWidgets().then(() => {
            this.forceUpdate();
        }).catch((e) => {
            console.error('Failed to remove sticker picker widget', e);
        });
    }

    componentDidMount() {
        // Close the sticker picker when the window resizes
        window.addEventListener('resize', this._onResize);

        this.dispatcherRef = dis.register(this._onWidgetAction);

        // Track updates to widget state in account data
        MatrixClientPeg.get().on('accountData', this._updateWidget);

        // Initialise widget state from current account data
        this._updateWidget();
    }

    componentWillUnmount() {
        const client = MatrixClientPeg.get();
        if (client) client.removeListener('accountData', this._updateWidget);

        window.removeEventListener('resize', this._onResize);
        if (this.dispatcherRef) {
            dis.unregister(this.dispatcherRef);
        }
    }

    componentDidUpdate(prevProps, prevState) {
        this._sendVisibilityToWidget(this.state.showStickers);
    }

    _imError(errorMsg, e) {
        console.error(errorMsg, e);
        this.setState({
            showStickers: false,
            imError: _t(errorMsg),
        });
    }

    _updateWidget() {
        const stickerpickerWidget = WidgetUtils.getStickerpickerWidgets()[0];
        if (!stickerpickerWidget) {
            Stickerpicker.currentWidget = null;
            this.setState({stickerpickerWidget: null, widgetId: null});
            return;
        }

        const currentWidget = Stickerpicker.currentWidget;
        let currentUrl = null;
        if (currentWidget && currentWidget.content && currentWidget.content.url) {
            currentUrl = currentWidget.content.url;
        }

        let newUrl = null;
        if (stickerpickerWidget && stickerpickerWidget.content && stickerpickerWidget.content.url) {
            newUrl = stickerpickerWidget.content.url;
        }

        if (newUrl !== currentUrl) {
            // Destroy the existing frame so a new one can be created
            PersistedElement.destroyElement(PERSISTED_ELEMENT_KEY);
        }

        Stickerpicker.currentWidget = stickerpickerWidget;
        this.setState({
            stickerpickerWidget,
            widgetId: stickerpickerWidget ? stickerpickerWidget.id : null,
        });
    }

    _onWidgetAction(payload) {
        switch (payload.action) {
            case "user_widget_updated":
                this.forceUpdate();
                break;
            case "stickerpicker_close":
                this.setState({showStickers: false});
                break;
            case Action.AfterRightPanelPhaseChange:
            case "show_left_panel":
            case "hide_left_panel":
                this.setState({showStickers: false});
                break;
        }
    }

    _defaultStickerpickerContent() {
        return (
            <AccessibleButton onClick={this._launchManageIntegrations}
                className='mx_Stickers_contentPlaceholder'>

{ _t("You don't currently have any stickerpacks enabled") }

{ _t("Add some now") }

            </AccessibleButton>
        );
    }

    _errorStickerpickerContent() {
        return (

 { this.state.imError }

        );
    }

    _sendVisibilityToWidget(visible) {
        if (!this.state.stickerpickerWidget) return;
        const messaging = WidgetMessagingStore.instance.getMessagingForId(this.state.stickerpickerWidget.id);
        if (messaging && visible !== this._prevSentVisibility) {
            messaging.updateVisibility(visible).catch(err => {
                console.error("Error updating widget visibility: ", err);
            });
            this._prevSentVisibility = visible;
        }
    }

    _getStickerpickerContent() {
        // Handle Integration Manager errors
        if (this.state._imError) {
            return this._errorStickerpickerContent();
        }

        // Stickers
        // TODO - Add support for Stickerpickers from multiple app stores.
        // Render content from multiple stickerpack sources, each within their
        // own iframe, within the stickerpicker UI element.
        const stickerpickerWidget = this.state.stickerpickerWidget;
        let stickersContent;

        // Use a separate ReactDOM tree to render the AppTile separately so that it persists and does
        // not unmount when we (a) close the sticker picker (b) switch rooms. It's properties are still
        // updated.
        const PersistedElement = sdk.getComponent("elements.PersistedElement");

        // Load stickerpack content
        if (stickerpickerWidget && stickerpickerWidget.content && stickerpickerWidget.content.url) {
            // Set default name
            stickerpickerWidget.content.name = stickerpickerWidget.name || _t("Stickerpack");

            // FIXME: could this use the same code as other apps?
            const stickerApp = {
                id: stickerpickerWidget.id,
                url: stickerpickerWidget.content.url,
                name: stickerpickerWidget.content.name,
                type: stickerpickerWidget.content.type,
                data: stickerpickerWidget.content.data,
            };

            stickersContent = (

                        <PersistedElement persistKey={PERSISTED_ELEMENT_KEY} zIndex={STICKERPICKER_Z_INDEX}>
                            <AppTile
                                app={stickerApp}
                                room={this.props.room}
                                fullWidth={true}
                                userId={MatrixClientPeg.get().credentials.userId}
                                creatorUserId={stickerpickerWidget.sender || MatrixClientPeg.get().credentials.userId}
                                waitForIframeLoad={true}
                                showMenubar={true}
                                onEditClick={this._launchManageIntegrations}
                                onDeleteClick={this._removeStickerpickerWidgets}
                                showTitle={false}
                                showCancel={false}
                                showPopout={false}
                                onMinimiseClick={this._onHideStickersClick}
                                handleMinimisePointerEvents={true}
                                userWidget={true}
                            />
                        </PersistedElement>

            );
        } else {
            // Default content to show if stickerpicker widget not added
            stickersContent = this._defaultStickerpickerContent();
        }
        return stickersContent;
    }

    // Dev note: this isn't jsdoc because it's angry.
    /*
     * Show the sticker picker overlay
     * If no stickerpacks have been added, show a link to the integration manager add sticker packs page.
     */
    _onShowStickersClick(e) {
        if (!SettingsStore.getValue("integrationProvisioning")) {
            // Intercept this case and spawn a warning.
            return IntegrationManagers.sharedInstance().showDisabledDialog();
        }

        // XXX: Simplify by using a context menu that is positioned relative to the sticker picker button

        const buttonRect = e.target.getBoundingClientRect();

        // The window X and Y offsets are to adjust position when zoomed in to page
        let x = buttonRect.right + window.pageXOffset - 41;

        // Amount of horizontal space between the right of menu and the right of the viewport
        //  (10 = amount needed to make chevron centrally aligned)
        const rightPad = 10;

        // When the sticker picker would be displayed off of the viewport, adjust x
        //  (302 = width of context menu, including borders)
        x = Math.min(x, document.body.clientWidth - (302 + rightPad));

        // Offset the chevron location, which is relative to the left of the context menu
        //  (10 = offset when context menu would not be displayed off viewport)
        //  (2 = context menu borders)
        const stickerPickerChevronOffset = Math.max(10, 2 + window.pageXOffset + buttonRect.left - x);

        const y = (buttonRect.top + (buttonRect.height / 2) + window.pageYOffset) - 19;

        this.setState({
            showStickers: true,
            stickerPickerX: x,
            stickerPickerY: y,
            stickerPickerChevronOffset,
        });
    }

    /**
     * Trigger hiding of the sticker picker overlay
     * @param  {Event} ev Event that triggered the function call
     */
    _onHideStickersClick(ev) {
        if (this.state.showStickers) {
            this.setState({showStickers: false});
        }
    }

    /**
     * Called when the window is resized
     */
    _onResize() {
        if (this.state.showStickers) {
            this.setState({showStickers: false});
        }
    }

    /**
     * The stickers picker was hidden
     */
    _onFinished() {
        if (this.state.showStickers) {
            this.setState({showStickers: false});
        }
    }

    /**
     * Launch the integration manager on the stickers integration page
     */
    _launchManageIntegrations() {
        // TODO: Open the right integration manager for the widget
        if (SettingsStore.getValue("feature_many_integration_managers")) {
            IntegrationManagers.sharedInstance().openAll(
                this.props.room,
                `type_${WidgetType.STICKERPICKER.preferred}`,
                this.state.widgetId,
            );
        } else {
            IntegrationManagers.sharedInstance().getPrimaryManager().open(
                this.props.room,
                `type_${WidgetType.STICKERPICKER.preferred}`,
                this.state.widgetId,
            );
        }
    }

    render() {
        let stickerPicker;
        let stickersButton;
        const className = classNames(
            "mx_MessageComposer_button",
            "mx_MessageComposer_stickers",
            "mx_Stickers_hideStickers",
            "mx_MessageComposer_button_highlight",
        );
        if (this.state.showStickers) {
            // Show hide-stickers button
            stickersButton =
                <AccessibleButton
                    id='stickersButton'
                    key="controls_hide_stickers"
                    className={className}
                    onClick={this._onHideStickersClick}
                    active={this.state.showStickers}
                    title={_t("Hide Stickers")}
                >
                </AccessibleButton>;

            const GenericElementContextMenu = sdk.getComponent('context_menus.GenericElementContextMenu');
            stickerPicker = <ContextMenu
                chevronOffset={this.state.stickerPickerChevronOffset}
                chevronFace="bottom"
                left={this.state.stickerPickerX}
                top={this.state.stickerPickerY}
                menuWidth={this.popoverWidth}
                menuHeight={this.popoverHeight}
                onFinished={this._onFinished}
                menuPaddingTop={0}
                menuPaddingLeft={0}
                menuPaddingRight={0}
                zIndex={STICKERPICKER_Z_INDEX}
            >
                <GenericElementContextMenu element={this._getStickerpickerContent()} onResize={this._onFinished} />
            </ContextMenu>;
        } else {
            // Show show-stickers button
            stickersButton =
                <AccessibleTooltipButton
                    id='stickersButton'
                    key="controls_show_stickers"
                    className="mx_MessageComposer_button mx_MessageComposer_stickers"
                    onClick={this._onShowStickersClick}
                    title={_t("Show Stickers")}
                >
                </AccessibleTooltipButton>;
        }
        return <React.Fragment>
            { stickersButton }
            { stickerPicker }
        </React.Fragment>;
    }
}
<|endoftext|>


<commit_before>import {connect} from "react-redux";
import Form from '../../components/form';
import React, {Component} from 'react';
import Input from '../../components/input';
import {bindActionCreators} from 'redux';
import {withRouter} from 'react-router';
import {fetchProfiles} from '../../services/api';
import FormGroup from '../../components/formGroup';
import * as ProfilesActions from '../../actionCreators/profilesAction';

const columns = [{key: '_id', name: 'ID'},
    {key: 'name.first', name: 'First'},
    {key: 'name.last', name: 'Last'},
    {key: 'email', name: 'Email'}];

const safeGet = (obj, key, defaultVal) => {
    if ((obj === undefined) || (obj === null)) return defaultVal;
    if (typeof obj[key] !== 'undefined') return obj[key];
    return key.split('.').reduce(function (o, x) {
        return (typeof o == 'undefined' || o === null) ? ((typeof defaultVal !== 'undefined') ? defaultVal : o) : o[x];
    }, obj);
};

export class UserProfiles extends Component {

    constructor(props) {
        super(props);
        this.displayName = 'containers/UserProfiles';
        this.onSubmit = this.onSubmit.bind(this);
        this.onClick = this.onClick.bind(this);
        this.renderRow = this.renderRow.bind(this);
        this.renderCol = this.renderCol.bind(this);
    }

    onClick(row) {
        console.log(row);
    }

    onSubmit(e) {
        fetchProfiles()
            .then((data) => {
                return this.props.profilesActionDispatcher.updateProfiles(data);
            });
    }

    renderCol(row) {
        return (col, ii) => {
            return ( { safeGet(row, col.key) }	 );
        }
    }

    renderRow(row, i) {
        return (

 this.onClick(row)}>{ columns.map(this.renderCol(row)) }

        );
    }

    render() {
        return (

                <Form>
                    <FormGroup inputId="first" label="Search Name">

                            <Input id="first"
                                   type="text"
                                   className="form-control"
                                   aria-describedby="firstHelp"
                                   placeholder="Enter search name"
                                   tabIndex="0"/>
                            Enter a name to search

                    </FormGroup>
                    <button type="button" className="btn btn-primary" onClick={this.onSubmit}>Submit</button>
                </Form>

                        { columns.map((row, i) => {
                            return ({row.name}	)
                        }) }

                    {this.props.profiles.map(this.renderRow)}

        );
    }
}

let mapStateToProps = (store, ownProps) => {
    return {profiles: store.profilesReducer.profiles}
};
let mapDispatchToProps = (dispatch) => {
    return {profilesActionDispatcher: bindActionCreators(ProfilesActions, dispatch)};
};

/**
 * If you are using withRouter to prevent updates from being blocked by shouldComponentUpdate,
 * it is important that withRouter wraps the component that implements shouldComponentUpate.
 * For example, when using Redux:
 * https://reacttraining.com/react-router/web/api/matchPath
 */
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(UserProfiles));<commit_msg>replaced all custom form code with react-bootstrap. added link to details page<commit_after>
import {connect} from "react-redux";
import {Link} from 'react-router-dom';
import React, {Component} from 'react';
import {withRouter} from 'react-router';
import Form from '../../components/form';
import {bindActionCreators} from 'redux';
import {fetchProfiles} from '../../services/api';
import * as ProfilesActions from '../../actionCreators/profilesAction';
import {FormGroup,ControlLabel,FormControl,HelpBlock,Button} from 'react-bootstrap';

const columns = [{key: '_id', name: 'ID'},
    {key: 'name.first', name: 'First'},
    {key: 'name.last', name: 'Last'},
    {key: 'email', name: 'Email'}];

const safeGet = (obj, key, defaultVal) => {
    if ((obj === undefined) || (obj === null)) return defaultVal;
    if (typeof obj[key] !== 'undefined') return obj[key];
    return key.split('.').reduce(function (o, x) {
        return (typeof o === 'undefined' || o === null) ? ((typeof defaultVal !== 'undefined') ? defaultVal : o) : o[x];
    }, obj);
};

export class UserProfiles extends Component {

    constructor(props) {
        super(props);
        this.displayName = 'containers/UserProfiles';
        this.onSubmit = this.onSubmit.bind(this);
        this.renderRow = this.renderRow.bind(this);
        this.renderCol = this.renderCol.bind(this);
        this.onChange = this.onChange.bind(this);
        this.getValidationState = this.getValidationState.bind(this);
    }

    onSubmit(e) {
        fetchProfiles()
            .then((data) => {
                return this.props.profilesActionDispatcher.updateProfiles(data);
            });
    }

    onChange(){
        console.log('onChange');
    }

    getValidationState(){
        console.log('getValidationState');
        // valid values are ["success","warning","error",null]
        return null;
    }

    /**
     * Well this might not be be the best method of determining the column
     * with the router link (eg  col.key === '_id' ) but it will do for now.
     */
    renderCol(row) {
        return (col, ii) => {
            return (

                    { col.key === '_id' ? (
                        <Link to={{pathname: `/userProfiles/${row._id}`}}>{safeGet(row, col.key)}</Link>
                    ):(

{safeGet(row, col.key)}

                    )}

            );
        }
    }

    renderRow(row, i) {
        return (

{columns.map(this.renderCol(row))}

        );
    }

    render() {
        return (

                <Form>
                    <FormGroup controlId="formBasicText" validationState={this.getValidationState()}>
                        <ControlLabel>Search Name</ControlLabel>
                        <FormControl type="text" placeholder="Enter search name" onChange={this.onChange}/>
                        <FormControl.Feedback />
                        <HelpBlock>Enter a name to search</HelpBlock>
                    </FormGroup>
                    <Button bsStyle="primary" onClick={this.onSubmit}>Submit</Button>
                </Form>

                            {columns.map((row, i) => {
                                return ({row.name}	)
                            })}

                        {this.props.profiles.map(this.renderRow)}

        );
    }
}

let mapStateToProps = (store, ownProps) => {
    return {profiles: store.profilesReducer.profiles}
};
let mapDispatchToProps = (dispatch) => {
    return {profilesActionDispatcher: bindActionCreators(ProfilesActions, dispatch)};
};

/**
 * If you are using withRouter to prevent updates from being blocked by shouldComponentUpdate,
 * it is important that withRouter wraps the component that implements shouldComponentUpate.
 * For example, when using Redux:
 * https://reacttraining.com/react-router/web/api/matchPath
 */
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(UserProfiles));<|endoftext|>


<commit_before>/* @flow */
import { createSelector } from 'reselect';

import { getPrivateMessages } from '../baseSelectors';
import { getOwnEmail } from '../account/accountSelectors';
import { getUnreadByPms, getUnreadByHuddles } from '../unread/unreadSelectors';
import { normalizeRecipientsSansMe, getRecipientsIds } from '../utils/message';

export const getRecentConversations = createSelector(
  getOwnEmail,
  getPrivateMessages,
  getUnreadByPms,
  getUnreadByHuddles,
  (ownEmail, messages, unreadPms, unreadHuddles) => {
    const recipients = messages.map(msg => ({
      ids: getRecipientsIds(msg.display_recipient, ownEmail),
      emails: normalizeRecipientsSansMe(msg.display_recipient, ownEmail),
      timestamp: msg.timestamp,
      msgId: msg.id,
    }));

    const groupedRecipients = recipients.reduce((uniqueMap, recipient) => {
      const prev = uniqueMap.get(recipient.emails);
      if (!prev || recipient.msgId > prev.msgId) {
        uniqueMap.set(recipient.emails, {
          ids: recipient.ids,
          recipients: recipient.emails,
          timestamp: recipient.timestamp || 0,
          msgId: recipient.msgId,
        });
      }
      return uniqueMap;
    }, new Map());

    const sortedByMostRecent = Array.from(groupedRecipients.values()).sort(
      (a, b) => +b.msgId - +a.msgId,
    );

    return sortedByMostRecent.map(recipient => ({
      ...recipient,
      unread: unreadPms[recipient.ids] || unreadHuddles[recipient.ids],
    }));
  },
);

export const getUnreadConversations = createSelector(getRecentConversations, conversations =>
  conversations.filter(c => c.unread > 0),
);
<commit_msg>conversations: Get types on `getRecentConversations`.<commit_after>/* @flow */
import { createSelector } from 'reselect';

import type { Message } from '../types';
import { getPrivateMessages } from '../baseSelectors';
import { getOwnEmail } from '../account/accountSelectors';
import { getUnreadByPms, getUnreadByHuddles } from '../unread/unreadSelectors';
import { normalizeRecipientsSansMe, getRecipientsIds } from '../utils/message';

export const getRecentConversations = createSelector(
  getOwnEmail,
  getPrivateMessages,
  getUnreadByPms,
  getUnreadByHuddles,
  (
    ownEmail: string,
    messages: Message[],
    unreadPms: { [number]: number },
    unreadHuddles: { [string]: number },
  ) => {
    const recipients = messages.map(msg => ({
      ids: getRecipientsIds(msg.display_recipient, ownEmail),
      emails: normalizeRecipientsSansMe(msg.display_recipient, ownEmail),
      timestamp: msg.timestamp,
      msgId: msg.id,
    }));

    const groupedRecipients = recipients.reduce((uniqueMap, recipient) => {
      const prev = uniqueMap.get(recipient.emails);
      if (!prev || recipient.msgId > prev.msgId) {
        uniqueMap.set(recipient.emails, {
          ids: recipient.ids,
          recipients: recipient.emails,
          timestamp: recipient.timestamp || 0,
          msgId: recipient.msgId,
        });
      }
      return uniqueMap;
    }, new Map());

    const sortedByMostRecent = Array.from(groupedRecipients.values()).sort(
      (a, b) => +b.msgId - +a.msgId,
    );

    return sortedByMostRecent.map(recipient => ({
      ...recipient,
      unread:
        /* $FlowFixMe: The keys of unreadPms are logically numbers, but because it's an object they
         end up converted to strings, so this access with string keys works.  We should probably use
         a Map for this and similar maps. */
        unreadPms[recipient.ids] || unreadHuddles[recipient.ids],
    }));
  },
);

export const getUnreadConversations = createSelector(getRecentConversations, conversations =>
  conversations.filter(c => c.unread > 0),
);
<|endoftext|>


<commit_before>import util from 'util'
import zlib from 'zlib'
import { isNull, isArray } from "lodash"
import config from "config"
import { error, verbose } from "./loggers"
import redis from "redis"
import url from "url"

const {
  NODE_ENV,
  REDIS_URL,
  CACHE_LIFETIME_IN_SECONDS,
  CACHE_QUERY_LOGGING_THRESHOLD_MS,
  CACHE_RETRIEVAL_TIMEOUT_MS,
} = config

const isTest = NODE_ENV === "test"

const VerboseEvents = ["connect", "ready", "reconnecting", "end", "warning"]

const deflateP = (dataz) => {
  return new Promise((resolve, reject) =>
    zlib.deflate(JSON.stringify(dataz), (er, deflatedData) => {
      if (er) {
        error(er)
      } else {
        resolve(deflatedData)
      }
    })
  )
}

function createMockClient() {
  const store = {}
  return {
    store,
    get: (key, cb) => cb(null, store[key]),
    set: (key, data) => (store[key] = data),
    del: key => delete store[key],
  }
}

function createRedisClient() {
  const redisURL = url.parse(REDIS_URL)
  const client = redis.createClient({
    host: redisURL.hostname,
    port: redisURL.port,
    retryStrategy: options => {
      if (options.error) {
        // Errors that lead to the connection being dropped are not emitted to
        // the error event handler, so send it there ourselves so we can handle
        // it in one place.
        // See https://github.com/NodeRedis/node_redis/issues/1202#issuecomment-363116620
        client.emit("error", error)
        // End reconnecting on a specific error and flush all commands with a
        // individual error.
        if (options.error.code === "ECONNREFUSED") {
          return new Error("[Cache] The server refused the connection")
        }
      }
      // End reconnecting after a specific timeout and flush all commands with a
      // individual error.
      if (options.total_retry_time > 1000 * 60 * 60) {
        return new Error("[Cache] Retry time exhausted")
      }
      // End reconnecting with built in error.
      if (options.attempt > 10) {
        return undefined
      }
      // Reconnect after:
      return Math.min(options.attempt * 100, 3000)
    },
  })
  if (redisURL.auth) {
    client.auth(redisURL.auth.split(":")[1])
  }
  client.on("error", error)
  VerboseEvents.forEach(event => {
    client.on(event, () => verbose(`[Cache] ${event}`))
  })
  return client
}

export const client = isTest ? createMockClient() : createRedisClient()

export default {
  get: key => {
    return new Promise((resolve, reject) => {
      if (isNull(client)) return reject(new Error("[Cache] `client` is `null`"))

      let timeoutId = setTimeout(() => {
        timeoutId = null
        const err = new Error(`[Cache#get] Timeout for key ${key}`)
        error(err)
        reject(err)
      }, CACHE_RETRIEVAL_TIMEOUT_MS)

      const start = Date.now()
      client.get(key, (err, data) => {
        const time = Date.now() - start
        if (time > CACHE_QUERY_LOGGING_THRESHOLD_MS) {
          error(`[Cache#get] Slow read of ${time}ms for key ${key}`)

          const clientInfo = {
            ready: client.ready,
            connected: client.connected,
            shouldBuffer: client.shouldBuffer,
            commandQueueLength: client.commandQueueLength,
            offlineQueueLength: client.offlineQueueLength,
            pipelineQueueLength: client.pipeline_queue.length
          }
          error(`Redis Client Info: ${util.inspect(clientInfo)}`)
          error(`Redis Client commandQueue: ${util.inspect(client.command_queue.toArray())}`)
        }

        if (timeoutId) {
          clearTimeout(timeoutId)
        } else {
          // timed out and already rejected promise, no need to continue
          return
        }

        if (err) {
          error(err)
          reject(err)
        } else if (data) {
            zlib.inflate(new Buffer(data, 'base64'), (er, inflatedData) => {
              if (er) {
                reject(er)
              } else {
                resolve(JSON.parse(inflatedData.toString()))
              }
            })
        } else {
          reject(new Error("[Cache#get] Cache miss"))
        }
      })
    })
  },

  set: (key, data) => {
    if (isNull(client)) return false

    const timestamp = new Date().getTime()
    /* eslint-disable no-param-reassign */
    if (isArray(data)) {
      data.forEach(datum => (datum.cached = timestamp))
    } else {
      data.cached = timestamp
    }
    /* eslint-enable no-param-reassign */

    return deflateP(data).then(deflatedData => {
      const payload = deflatedData.toString('base64')
      verbose(`CACHE SET: ${key}: ${payload}`)
      return client.set(
        key,
        payload,
        "EX",
        CACHE_LIFETIME_IN_SECONDS,
        err => {
          if (err) error(err)
        }
      )
    })
  },

  delete: key =>
    new Promise((resolve, reject) =>
      client.del(key, (err, response) => {
        if (err) return reject(err)
        resolve(response)
      })
    ),
}
<commit_msg>catch and log errors in cache.set promise<commit_after>import util from 'util'
import zlib from 'zlib'
import { isNull, isArray } from "lodash"
import config from "config"
import { error, verbose } from "./loggers"
import redis from "redis"
import url from "url"

const {
  NODE_ENV,
  REDIS_URL,
  CACHE_LIFETIME_IN_SECONDS,
  CACHE_QUERY_LOGGING_THRESHOLD_MS,
  CACHE_RETRIEVAL_TIMEOUT_MS,
} = config

const isTest = NODE_ENV === "test"

const VerboseEvents = ["connect", "ready", "reconnecting", "end", "warning"]

const deflateP = (dataz) => {
  return new Promise((resolve, reject) =>
    zlib.deflate(JSON.stringify(dataz), (er, deflatedData) => {
      if (er) {
        error(er)
      } else {
        resolve(deflatedData)
      }
    })
  )
}

function createMockClient() {
  const store = {}
  return {
    store,
    get: (key, cb) => cb(null, store[key]),
    set: (key, data) => (store[key] = data),
    del: key => delete store[key],
  }
}

function createRedisClient() {
  const redisURL = url.parse(REDIS_URL)
  const client = redis.createClient({
    host: redisURL.hostname,
    port: redisURL.port,
    retryStrategy: options => {
      if (options.error) {
        // Errors that lead to the connection being dropped are not emitted to
        // the error event handler, so send it there ourselves so we can handle
        // it in one place.
        // See https://github.com/NodeRedis/node_redis/issues/1202#issuecomment-363116620
        client.emit("error", error)
        // End reconnecting on a specific error and flush all commands with a
        // individual error.
        if (options.error.code === "ECONNREFUSED") {
          return new Error("[Cache] The server refused the connection")
        }
      }
      // End reconnecting after a specific timeout and flush all commands with a
      // individual error.
      if (options.total_retry_time > 1000 * 60 * 60) {
        return new Error("[Cache] Retry time exhausted")
      }
      // End reconnecting with built in error.
      if (options.attempt > 10) {
        return undefined
      }
      // Reconnect after:
      return Math.min(options.attempt * 100, 3000)
    },
  })
  if (redisURL.auth) {
    client.auth(redisURL.auth.split(":")[1])
  }
  client.on("error", error)
  VerboseEvents.forEach(event => {
    client.on(event, () => verbose(`[Cache] ${event}`))
  })
  return client
}

export const client = isTest ? createMockClient() : createRedisClient()

export default {
  get: key => {
    return new Promise((resolve, reject) => {
      if (isNull(client)) return reject(new Error("[Cache] `client` is `null`"))

      let timeoutId = setTimeout(() => {
        timeoutId = null
        const err = new Error(`[Cache#get] Timeout for key ${key}`)
        error(err)
        reject(err)
      }, CACHE_RETRIEVAL_TIMEOUT_MS)

      const start = Date.now()
      client.get(key, (err, data) => {
        const time = Date.now() - start
        if (time > CACHE_QUERY_LOGGING_THRESHOLD_MS) {
          error(`[Cache#get] Slow read of ${time}ms for key ${key}`)

          const clientInfo = {
            ready: client.ready,
            connected: client.connected,
            shouldBuffer: client.shouldBuffer,
            commandQueueLength: client.commandQueueLength,
            offlineQueueLength: client.offlineQueueLength,
            pipelineQueueLength: client.pipeline_queue.length
          }
          error(`Redis Client Info: ${util.inspect(clientInfo)}`)
          error(`Redis Client commandQueue: ${util.inspect(client.command_queue.toArray())}`)
        }

        if (timeoutId) {
          clearTimeout(timeoutId)
        } else {
          // timed out and already rejected promise, no need to continue
          return
        }

        if (err) {
          error(err)
          reject(err)
        } else if (data) {
            zlib.inflate(new Buffer(data, 'base64'), (er, inflatedData) => {
              if (er) {
                reject(er)
              } else {
                resolve(JSON.parse(inflatedData.toString()))
              }
            })
        } else {
          reject(new Error("[Cache#get] Cache miss"))
        }
      })
    })
  },

  set: (key, data) => {
    if (isNull(client)) return false

    const timestamp = new Date().getTime()
    /* eslint-disable no-param-reassign */
    if (isArray(data)) {
      data.forEach(datum => (datum.cached = timestamp))
    } else {
      data.cached = timestamp
    }
    /* eslint-enable no-param-reassign */

    return deflateP(data).then(deflatedData => {
      const payload = deflatedData.toString('base64')
      verbose(`CACHE SET: ${key}: ${payload}`)
      return client.set(
        key,
        payload,
        "EX",
        CACHE_LIFETIME_IN_SECONDS,
        err => {
          if (err) error(err)
        }
      )
    }).catch(err => {
      error(err)
    })
  },

  delete: key =>
    new Promise((resolve, reject) =>
      client.del(key, (err, response) => {
        if (err) return reject(err)
        resolve(response)
      })
    ),
}
<|endoftext|>


<commit_before>require('./scss/index.scss');
require('./assets/icons.svg');
require('./assets/avatar.svg');
<commit_msg>Fix default project icon not being pushed to production<commit_after>require('./scss/index.scss')
require('./assets/icons.svg')
require('./assets/avatar.svg')
require('./assets/no-work-icon')
<|endoftext|>


<commit_before>import AbstractEditController from 'hospitalrun/controllers/abstract-edit-controller';
import AddNewPatient from 'hospitalrun/mixins/add-new-patient';
import ChargeActions from 'hospitalrun/mixins/charge-actions';
import DiagnosisActions from 'hospitalrun/mixins/diagnosis-actions';
import Ember from 'ember';
import moment from 'moment';
import PatientNotes from 'hospitalrun/mixins/patient-notes';
import PatientSubmodule from 'hospitalrun/mixins/patient-submodule';
import UserSession from 'hospitalrun/mixins/user-session';
import VisitStatus from 'hospitalrun/utils/visit-statuses';
import VisitTypes from 'hospitalrun/mixins/visit-types';

const {
  computed,
  get,
  isEmpty,
  set
} = Ember;

export default AbstractEditController.extend(AddNewPatient, ChargeActions, DiagnosisActions, PatientSubmodule, PatientNotes, UserSession, VisitTypes, {
  visitsController: Ember.inject.controller('visits'),
  additionalButtons: computed('model.status', function() {
    let buttonProps = {
      buttonIcon: 'glyphicon glyphicon-log-out',
      class: 'btn btn-primary on-white'
    };
    let i18n = this.get('i18n');
    let status = this.get('model.status');
    if (status === VisitStatus.ADMITTED) {
      buttonProps.buttonAction = 'discharge';
      buttonProps.buttonText = i18n.t('visits.buttons.discharge');
      return [buttonProps];
    } else if (status === VisitStatus.CHECKED_IN) {
      buttonProps.buttonAction = 'checkout';
      buttonProps.buttonText = i18n.t('visits.buttons.checkOut');
      return [buttonProps];
    }
  }),

  canAddAppointment: computed('model.isNew', function() {
    return (!this.get('model.isNew') && this.currentUserCan('add_appointment'));
  }),

  canAddBillingDiagnosis: computed('model.isNew', function() {
    return (!this.get('model.isNew') && this.currentUserCan('add_billing_diagnosis'));
  }),

  canAddImaging: function() {
    return this.currentUserCan('add_imaging');
  }.property(),

  canAddLab: function() {
    return this.currentUserCan('add_lab');
  }.property(),

  canAddMedication: function() {
    return this.currentUserCan('add_medication');
  }.property(),

  canAddProcedure: function() {
    return this.currentUserCan('add_procedure');
  }.property(),

  canAddVitals: function() {
    return this.currentUserCan('add_vitals');
  }.property(),

  canDeleteImaging: function() {
    return this.currentUserCan('delete_imaging');
  }.property(),

  canDeleteLab: function() {
    return this.currentUserCan('delete_lab');
  }.property(),

  canDeleteMedication: function() {
    return this.currentUserCan('delete_medication');
  }.property(),

  canDeleteProcedure: function() {
    return this.currentUserCan('delete_procedure');
  }.property(),

  canDeleteVitals: function() {
    return this.currentUserCan('delete_vitals');
  }.property(),

  isAdmissionVisit: function() {
    let visitType = this.get('model.visitType');
    let isAdmission = (visitType === 'Admission');
    return isAdmission;
  }.property('model.visitType'),

  cancelAction: function() {
    let returnTo = this.get('model.returnTo');
    if (!isEmpty(returnTo)) {
      return 'returnTo';
    } else if (!isEmpty(this.get('model.returnToPatient'))) {
      return 'returnToPatient';
    } else {
      return this._super();
    }
  }.property('model.returnTo', 'model.returnToPatient'),

  allowAddAllergy: computed.not('model.isNew'),
  allowAddDiagnosis: computed.not('model.isNew'),
  allowAddOperativePlan: computed.not('model.isNew'),
  chargePricingCategory: 'Ward',
  chargeRoute: 'visits.charge',
  diagnosisList: Ember.computed.alias('visitsController.diagnosisList'),
  findPatientVisits: false,
  hideChargeHeader: true,
  patientImaging: Ember.computed.alias('model.imaging'),
  patientLabs: Ember.computed.alias('model.labs'),
  patientMedications: Ember.computed.alias('model.medication'),
  pricingList: null, // This gets filled in by the route
  pricingTypes: Ember.computed.alias('visitsController.wardPricingTypes'),
  physicianList: Ember.computed.alias('visitsController.physicianList'),
  locationList: Ember.computed.alias('visitsController.locationList'),
  sexList: computed.alias('visitsController.sexList'),
  visitTypesList: Ember.computed.alias('visitsController.visitTypesList'),
  lookupListsToUpdate: [{
    name: 'physicianList',
    property: 'model.examiner',
    id: 'physician_list'
  }, {
    name: 'locationList',
    property: 'model.location',
    id: 'visit_location_list'
  }],

  updateCapability: 'add_visit',

  showPatientSelection: computed('model.checkIn', 'model.hidePatientSelection', function() {
    return this.get('model.checkIn') && !this.get('model.hidePatientSelection');
  }),

  updateButtonIcon: computed('model.checkIn', function() {
    if (this.get('model.checkIn')) {
      return 'glyphicon glyphicon-log-in';
    }
  }),

  updateButtonText: function() {
    let i18n = this.get('i18n');
    if (this.get('model.checkIn')) {
      return i18n.t('visits.buttons.checkIn');
    } else {
      return this._super();
    }
  }.property('model.checkIn'),

  validVisitTypes: function() {
    let outPatient = this.get('model.outPatient');
    let visitTypes = this.get('visitTypes');
    if (outPatient === true) {
      visitTypes = visitTypes.filter(function(visitType) {
        return (visitType.id !== 'Admission');
      });
    }
    return visitTypes;
  }.property('visitTypes', 'model.outPatient'),

  _addChildObject(route, afterTransition) {
    this.transitionToRoute(route, 'new').then(function(newRoute) {
      newRoute.currentModel.setProperties({
        patient: this.get('model.patient'),
        visit: this.get('model'),
        selectPatient: false,
        returnToVisit: this.get('model.id')
      });
      if (afterTransition) {
        afterTransition(newRoute);
      }
    }.bind(this));
  },

  _finishAfterUpdate() {
    let addedNewPatient = this.get('addedNewPatient');
    let checkIn = this.get('model.checkIn');
    let i18n = this.get('i18n');
    let updateMesage = i18n.t('visits.messages.visitSaved');
    let updateTitle = i18n.t('visits.titles.visitSaved');
    if (checkIn === true) {
      let model = this.get('model');
      model.set('checkIn');
      this.send('setSectionHeader', {
        currentScreenTitle: i18n.t('visits.titles.editVisit')
      });
    }

    if (checkIn) {
      updateTitle = i18n.t('visits.titles.checkedIn');
      let patientDetails = {
        patientName: this.get('model.patient.displayName')
      };
      if (addedNewPatient === true) {
        this.set('addedNewPatient');
        updateMesage = i18n.t('visits.messages.patientCreatedAndCheckedIn', patientDetails);
      } else {
        updateMesage = i18n.t('visits.messages.patientCheckedIn', patientDetails);
      }
    }
    this.displayAlert(updateTitle, updateMesage);
  },

  _findAssociatedAppointment(newVisit) {
    let appointment = newVisit.get('appointment');
    let beginningOfToday = moment().startOf('day').valueOf();
    let database = this.get('database');
    let endOfToday = moment().endOf('day').valueOf();
    let maxId = database.getMaxPouchId('appointment');
    let minId = database.getMinPouchId('appointment');
    let patientId = newVisit.get('patient.id');
    if (!isEmpty(appointment)) {
      return Ember.RSVP.resolve(appointment);
    } else {
      return this.store.query('appointment', {
        options: {
          startkey: [patientId, beginningOfToday, beginningOfToday, minId],
          endkey: [patientId, endOfToday, endOfToday, maxId]
        },
        mapReduce: 'appointments_by_patient'
      }).then((appointments) => {
        if (isEmpty(appointments)) {
          return;
        } else {
          return appointments.get('firstObject');
        }
      });
    }
  },

  _saveAssociatedAppointment(newVisit) {
    return this._findAssociatedAppointment(newVisit).then((appointment) => {
      if (isEmpty(appointment)) {
        newVisit.set('hasAppointment', false);
        return Ember.RSVP.resolve();
      } else {
        newVisit.set('hasAppointment', true);
        appointment.set('status', 'Attended');
        return appointment.save();
      }
    });
  },

  haveAdditionalDiagnoses: function() {
    return !isEmpty(this.get('model.additionalDiagnoses'));
  }.property('model.additionalDiagnoses.[]'),

  afterUpdate(visit) {
    this.updatePatientVisitFlags(visit).then(this._finishAfterUpdate.bind(this));
  },

  beforeUpdate() {
    let isNew = this.get('model.isNew');
    if (isNew) {
      return new Ember.RSVP.Promise((resolve, reject) => {
        let newVisit = this.get('model');
        return newVisit.validate().then(() => {
          if (newVisit.get('isValid')) {
            let patient = newVisit.get('patient');
            if (isEmpty(patient)) {
              this.addNewPatient();
              return reject({
                ignore: true,
                message: 'creating new patient first'
              });
            }
            let visitType = newVisit.get('visitType');
            let visitStatus;
            if (visitType === 'Admission') {
              visitStatus = VisitStatus.ADMITTED;
            } else {
              visitStatus = VisitStatus.CHECKED_IN;
            }
            newVisit.set('status', visitStatus);
            if (this.get('model.checkIn')) {
              this._saveAssociatedAppointment(newVisit).then(() => {
                this.saveNewDiagnoses().then(resolve, reject);
              });
            } else {
              this.saveNewDiagnoses().then(resolve, reject);
            }
          }
        });
      });
    } else {
      return this.updateCharges();
    }
  },

  checkoutPatient(status) {
    let visit = this.get('model');
    this.checkoutVisit(visit, status);
  },

  patientSelected(patient) {
    if (isEmpty(patient)) {
      set(this, 'model.createNewPatient', true);
    } else {
      set(this, 'model.createNewPatient', false);
      this.getPatientDiagnoses(patient, get(this, 'model'));
    }
  },

  /**
   * Adds or removes the specified object from the specified list.
   * @param {String} listName The name of the list to operate on.
   * @param {Object} listObject The object to add or removed from the
   * specified list.
   * @param {boolean} removeObject If true remove the object from the list;
   * otherwise add the specified object to the list.
   */
  updateList(listName, listObject, removeObject) {
    let model = this.get('model');
    model.get(listName).then(function(list) {
      if (removeObject) {
        list.removeObject(listObject);
      } else {
        list.addObject(listObject);
      }
      this.send('update', true);
      this.send('closeModal');
    }.bind(this));
  },

  actions: {
    addDiagnosis(newDiagnosis) {
      this.addDiagnosisToModelAndPatient(newDiagnosis);
    },

    addVitals(newVitals) {
      this.updateList('vitals', newVitals);
    },

    cancel() {
      let cancelledItem = this.get('model');
      if (this.get('model.isNew')) {
        cancelledItem.deleteRecord();
      } else {
        cancelledItem.rollbackAttributes();
      }
      this.send(this.get('cancelAction'));
    },

    checkout() {
      this.checkoutPatient(VisitStatus.CHECKED_OUT);
    },

    deleteProcedure(procedure) {
      this.updateList('procedures', procedure, true);
    },

    deleteVitals(vitals) {
      this.updateList('vitals', vitals, true);
    },

    discharge() {
      this.checkoutPatient(VisitStatus.DISCHARGED);
    },

    editImaging(imaging) {
      if (imaging.get('canEdit')) {
        imaging.setProperties('returnToVisit', this.get('model.id'));
      }
      this.transitionToRoute('imaging.edit', imaging);
    },

    editLab(lab) {
      if (lab.get('canEdit')) {
        lab.setProperties('returnToVisit', this.get('model.id'));
        this.transitionToRoute('labs.edit', lab);
      }
    },

    editMedication(medication) {
      if (medication.get('canEdit')) {
        medication.set('returnToVisit', this.get('model.id'));
        this.transitionToRoute('medication.edit', medication);
      }
    },

    editOperativePlan(operativePlan) {
      let model = operativePlan;
      if (isEmpty(model)) {
        this._addChildObject('patients.operative-plan', (route) =>{
          route.controller.getPatientDiagnoses(this.get('model.patient'), route.currentModel);
        });
      } else {
        model.set('returnToVisit', this.get('model.id'));
        this.transitionToRoute('patients.operative-plan', model);
      }
    },

    newPatientChanged(createNewPatient) {
      set(this, 'model.createNewPatient', createNewPatient);
      let model = this.get('model');
      let patient = model.get('patient');
      if (createNewPatient && !isEmpty(patient)) {
        model.set('patientTypeAhead', patient.get('displayName'));
        model.set('patient');
      }
    },

    showAddVitals() {
      let newVitals = this.get('store').createRecord('vital', {
        dateRecorded: new Date()
      });
      this.send('openModal', 'visits.vitals.edit', newVitals);
    },

    showAddPatientNote(model) {
      if (isEmpty(model)) {
        model = this.get('store').createRecord('patient-note', {
          visit: this.get('model'),
          createdBy: this.getUserName(),
          patient: this.get('model').get('patient'),
          noteType: this._computeNoteType(this.get('model'))
        });
      }
      this.send('openModal', 'patients.notes', model);
    },

    newAppointment() {
      this._addChildObject('appointments.edit');
    },

    newImaging() {
      this._addChildObject('imaging.edit');
    },

    newLab() {
      this._addChildObject('labs.edit');
    },

    newMedication() {
      this._addChildObject('medication.edit');
    },

    showAddProcedure() {
      this._addChildObject('procedures.edit');
    },

    showDeleteImaging(imaging) {
      this.send('openModal', 'imaging.delete', imaging);
    },

    showDeleteLab(lab) {
      this.send('openModal', 'labs.delete', lab);
    },

    showDeleteMedication(medication) {
      this.send('openModal', 'medication.delete', medication);
    },

    showDeleteProcedure(procedure) {
      this.send('openModal', 'visits.procedures.delete', procedure);
    },

    showDeleteVitals(vitals) {
      this.send('openModal', 'visits.vitals.delete', vitals);
    },

    showEditProcedure(procedure) {
      if (isEmpty(procedure.get('visit'))) {
        procedure.set('visit', this.get('model'));
      }
      procedure.set('returnToVisit', this.get('model.id'));
      procedure.set('returnToPatient');
      this.transitionToRoute('procedures.edit', procedure);
    },

    showEditVitals(vitals) {
      this.send('openModal', 'visits.vitals.edit', vitals);
    },

    showDeletePatientNote(note) {
      this.send('openModal', 'dialog', Ember.Object.create({
        confirmAction: 'deletePatientNote',
        title: 'Delete Note',
        message: 'Are you sure you want to delete this note?',
        noteToDelete: note,
        updateButtonAction: 'confirm',
        updateButtonText: this.get('i18n').t('buttons.ok')
      }));
    },

    deletePatientNote(model) {
      let note = model.get('noteToDelete');
      let patientNotes = this.get('model.patientNotes');
      patientNotes.removeObject(note);
      this.send('update', true);
    },

    startDateChanged(startDate) {
      let isAdmissionVisit = this.get('isAdmissionVisit');
      let visit = this.get('model');
      if (!isAdmissionVisit) {
        visit.set('endDate', startDate);
      }
    }

  }
});
<commit_msg>Make sure outPatient flag gets properly set.<commit_after>import AbstractEditController from 'hospitalrun/controllers/abstract-edit-controller';
import AddNewPatient from 'hospitalrun/mixins/add-new-patient';
import ChargeActions from 'hospitalrun/mixins/charge-actions';
import DiagnosisActions from 'hospitalrun/mixins/diagnosis-actions';
import Ember from 'ember';
import moment from 'moment';
import PatientNotes from 'hospitalrun/mixins/patient-notes';
import PatientSubmodule from 'hospitalrun/mixins/patient-submodule';
import UserSession from 'hospitalrun/mixins/user-session';
import VisitStatus from 'hospitalrun/utils/visit-statuses';
import VisitTypes from 'hospitalrun/mixins/visit-types';

const {
  computed,
  get,
  isEmpty,
  set
} = Ember;

export default AbstractEditController.extend(AddNewPatient, ChargeActions, DiagnosisActions, PatientSubmodule, PatientNotes, UserSession, VisitTypes, {
  visitsController: Ember.inject.controller('visits'),
  additionalButtons: computed('model.status', function() {
    let buttonProps = {
      buttonIcon: 'glyphicon glyphicon-log-out',
      class: 'btn btn-primary on-white'
    };
    let i18n = this.get('i18n');
    let status = this.get('model.status');
    if (status === VisitStatus.ADMITTED) {
      buttonProps.buttonAction = 'discharge';
      buttonProps.buttonText = i18n.t('visits.buttons.discharge');
      return [buttonProps];
    } else if (status === VisitStatus.CHECKED_IN) {
      buttonProps.buttonAction = 'checkout';
      buttonProps.buttonText = i18n.t('visits.buttons.checkOut');
      return [buttonProps];
    }
  }),

  canAddAppointment: computed('model.isNew', function() {
    return (!this.get('model.isNew') && this.currentUserCan('add_appointment'));
  }),

  canAddBillingDiagnosis: computed('model.isNew', function() {
    return (!this.get('model.isNew') && this.currentUserCan('add_billing_diagnosis'));
  }),

  canAddImaging: function() {
    return this.currentUserCan('add_imaging');
  }.property(),

  canAddLab: function() {
    return this.currentUserCan('add_lab');
  }.property(),

  canAddMedication: function() {
    return this.currentUserCan('add_medication');
  }.property(),

  canAddProcedure: function() {
    return this.currentUserCan('add_procedure');
  }.property(),

  canAddVitals: function() {
    return this.currentUserCan('add_vitals');
  }.property(),

  canDeleteImaging: function() {
    return this.currentUserCan('delete_imaging');
  }.property(),

  canDeleteLab: function() {
    return this.currentUserCan('delete_lab');
  }.property(),

  canDeleteMedication: function() {
    return this.currentUserCan('delete_medication');
  }.property(),

  canDeleteProcedure: function() {
    return this.currentUserCan('delete_procedure');
  }.property(),

  canDeleteVitals: function() {
    return this.currentUserCan('delete_vitals');
  }.property(),

  isAdmissionVisit: function() {
    let visitType = this.get('model.visitType');
    let isAdmission = (visitType === 'Admission');
    return isAdmission;
  }.property('model.visitType'),

  cancelAction: function() {
    let returnTo = this.get('model.returnTo');
    if (!isEmpty(returnTo)) {
      return 'returnTo';
    } else if (!isEmpty(this.get('model.returnToPatient'))) {
      return 'returnToPatient';
    } else {
      return this._super();
    }
  }.property('model.returnTo', 'model.returnToPatient'),

  allowAddAllergy: computed.not('model.isNew'),
  allowAddDiagnosis: computed.not('model.isNew'),
  allowAddOperativePlan: computed.not('model.isNew'),
  chargePricingCategory: 'Ward',
  chargeRoute: 'visits.charge',
  diagnosisList: Ember.computed.alias('visitsController.diagnosisList'),
  findPatientVisits: false,
  hideChargeHeader: true,
  patientImaging: Ember.computed.alias('model.imaging'),
  patientLabs: Ember.computed.alias('model.labs'),
  patientMedications: Ember.computed.alias('model.medication'),
  pricingList: null, // This gets filled in by the route
  pricingTypes: Ember.computed.alias('visitsController.wardPricingTypes'),
  physicianList: Ember.computed.alias('visitsController.physicianList'),
  locationList: Ember.computed.alias('visitsController.locationList'),
  sexList: computed.alias('visitsController.sexList'),
  visitTypesList: Ember.computed.alias('visitsController.visitTypesList'),
  lookupListsToUpdate: [{
    name: 'physicianList',
    property: 'model.examiner',
    id: 'physician_list'
  }, {
    name: 'locationList',
    property: 'model.location',
    id: 'visit_location_list'
  }],

  updateCapability: 'add_visit',

  showPatientSelection: computed('model.checkIn', 'model.hidePatientSelection', function() {
    return this.get('model.checkIn') && !this.get('model.hidePatientSelection');
  }),

  updateButtonIcon: computed('model.checkIn', function() {
    if (this.get('model.checkIn')) {
      return 'glyphicon glyphicon-log-in';
    }
  }),

  updateButtonText: function() {
    let i18n = this.get('i18n');
    if (this.get('model.checkIn')) {
      return i18n.t('visits.buttons.checkIn');
    } else {
      return this._super();
    }
  }.property('model.checkIn'),

  validVisitTypes: function() {
    let outPatient = this.get('model.outPatient');
    let visitTypes = this.get('visitTypes');
    if (outPatient === true) {
      visitTypes = visitTypes.filter(function(visitType) {
        return (visitType.id !== 'Admission');
      });
    }
    return visitTypes;
  }.property('visitTypes', 'model.outPatient'),

  _addChildObject(route, afterTransition) {
    this.transitionToRoute(route, 'new').then(function(newRoute) {
      newRoute.currentModel.setProperties({
        patient: this.get('model.patient'),
        visit: this.get('model'),
        selectPatient: false,
        returnToVisit: this.get('model.id')
      });
      if (afterTransition) {
        afterTransition(newRoute);
      }
    }.bind(this));
  },

  _finishAfterUpdate() {
    let addedNewPatient = this.get('addedNewPatient');
    let checkIn = this.get('model.checkIn');
    let i18n = this.get('i18n');
    let updateMesage = i18n.t('visits.messages.visitSaved');
    let updateTitle = i18n.t('visits.titles.visitSaved');
    if (checkIn === true) {
      let model = this.get('model');
      model.set('checkIn');
      this.send('setSectionHeader', {
        currentScreenTitle: i18n.t('visits.titles.editVisit')
      });
    }

    if (checkIn) {
      updateTitle = i18n.t('visits.titles.checkedIn');
      let patientDetails = {
        patientName: this.get('model.patient.displayName')
      };
      if (addedNewPatient === true) {
        this.set('addedNewPatient');
        updateMesage = i18n.t('visits.messages.patientCreatedAndCheckedIn', patientDetails);
      } else {
        updateMesage = i18n.t('visits.messages.patientCheckedIn', patientDetails);
      }
    }
    this.displayAlert(updateTitle, updateMesage);
  },

  _findAssociatedAppointment(newVisit) {
    let appointment = newVisit.get('appointment');
    let beginningOfToday = moment().startOf('day').valueOf();
    let database = this.get('database');
    let endOfToday = moment().endOf('day').valueOf();
    let maxId = database.getMaxPouchId('appointment');
    let minId = database.getMinPouchId('appointment');
    let patientId = newVisit.get('patient.id');
    if (!isEmpty(appointment)) {
      return Ember.RSVP.resolve(appointment);
    } else {
      return this.store.query('appointment', {
        options: {
          startkey: [patientId, beginningOfToday, beginningOfToday, minId],
          endkey: [patientId, endOfToday, endOfToday, maxId]
        },
        mapReduce: 'appointments_by_patient'
      }).then((appointments) => {
        if (isEmpty(appointments)) {
          return;
        } else {
          return appointments.get('firstObject');
        }
      });
    }
  },

  _saveAssociatedAppointment(newVisit) {
    return this._findAssociatedAppointment(newVisit).then((appointment) => {
      if (isEmpty(appointment)) {
        newVisit.set('hasAppointment', false);
        return Ember.RSVP.resolve();
      } else {
        newVisit.set('hasAppointment', true);
        appointment.set('status', 'Attended');
        return appointment.save();
      }
    });
  },

  haveAdditionalDiagnoses: function() {
    return !isEmpty(this.get('model.additionalDiagnoses'));
  }.property('model.additionalDiagnoses.[]'),

  afterUpdate(visit) {
    this.updatePatientVisitFlags(visit).then(this._finishAfterUpdate.bind(this));
  },

  beforeUpdate() {
    let isNew = this.get('model.isNew');
    if (isNew) {
      return new Ember.RSVP.Promise((resolve, reject) => {
        let newVisit = this.get('model');
        return newVisit.validate().then(() => {
          if (newVisit.get('isValid')) {
            let patient = newVisit.get('patient');
            if (isEmpty(patient)) {
              this.addNewPatient();
              return reject({
                ignore: true,
                message: 'creating new patient first'
              });
            }
            let outPatient = false;
            let visitType = newVisit.get('visitType');
            let visitStatus;
            if (visitType === 'Admission') {
              visitStatus = VisitStatus.ADMITTED;
            } else {
              outPatient = true;
              visitStatus = VisitStatus.CHECKED_IN;
            }
            newVisit.setProperties({
              outPatient,
              status: visitStatus
            });
            if (this.get('model.checkIn')) {
              this._saveAssociatedAppointment(newVisit).then(() => {
                this.saveNewDiagnoses().then(resolve, reject);
              });
            } else {
              this.saveNewDiagnoses().then(resolve, reject);
            }
          }
        });
      });
    } else {
      return this.updateCharges();
    }
  },

  checkoutPatient(status) {
    let visit = this.get('model');
    this.checkoutVisit(visit, status);
  },

  patientSelected(patient) {
    if (isEmpty(patient)) {
      set(this, 'model.createNewPatient', true);
    } else {
      set(this, 'model.createNewPatient', false);
      this.getPatientDiagnoses(patient, get(this, 'model'));
    }
  },

  /**
   * Adds or removes the specified object from the specified list.
   * @param {String} listName The name of the list to operate on.
   * @param {Object} listObject The object to add or removed from the
   * specified list.
   * @param {boolean} removeObject If true remove the object from the list;
   * otherwise add the specified object to the list.
   */
  updateList(listName, listObject, removeObject) {
    let model = this.get('model');
    model.get(listName).then(function(list) {
      if (removeObject) {
        list.removeObject(listObject);
      } else {
        list.addObject(listObject);
      }
      this.send('update', true);
      this.send('closeModal');
    }.bind(this));
  },

  actions: {
    addDiagnosis(newDiagnosis) {
      this.addDiagnosisToModelAndPatient(newDiagnosis);
    },

    addVitals(newVitals) {
      this.updateList('vitals', newVitals);
    },

    cancel() {
      let cancelledItem = this.get('model');
      if (this.get('model.isNew')) {
        cancelledItem.deleteRecord();
      } else {
        cancelledItem.rollbackAttributes();
      }
      this.send(this.get('cancelAction'));
    },

    checkout() {
      this.checkoutPatient(VisitStatus.CHECKED_OUT);
    },

    deleteProcedure(procedure) {
      this.updateList('procedures', procedure, true);
    },

    deleteVitals(vitals) {
      this.updateList('vitals', vitals, true);
    },

    discharge() {
      this.checkoutPatient(VisitStatus.DISCHARGED);
    },

    editImaging(imaging) {
      if (imaging.get('canEdit')) {
        imaging.setProperties('returnToVisit', this.get('model.id'));
      }
      this.transitionToRoute('imaging.edit', imaging);
    },

    editLab(lab) {
      if (lab.get('canEdit')) {
        lab.setProperties('returnToVisit', this.get('model.id'));
        this.transitionToRoute('labs.edit', lab);
      }
    },

    editMedication(medication) {
      if (medication.get('canEdit')) {
        medication.set('returnToVisit', this.get('model.id'));
        this.transitionToRoute('medication.edit', medication);
      }
    },

    editOperativePlan(operativePlan) {
      let model = operativePlan;
      if (isEmpty(model)) {
        this._addChildObject('patients.operative-plan', (route) =>{
          route.controller.getPatientDiagnoses(this.get('model.patient'), route.currentModel);
        });
      } else {
        model.set('returnToVisit', this.get('model.id'));
        this.transitionToRoute('patients.operative-plan', model);
      }
    },

    newPatientChanged(createNewPatient) {
      set(this, 'model.createNewPatient', createNewPatient);
      let model = this.get('model');
      let patient = model.get('patient');
      if (createNewPatient && !isEmpty(patient)) {
        model.set('patientTypeAhead', patient.get('displayName'));
        model.set('patient');
      }
    },

    showAddVitals() {
      let newVitals = this.get('store').createRecord('vital', {
        dateRecorded: new Date()
      });
      this.send('openModal', 'visits.vitals.edit', newVitals);
    },

    showAddPatientNote(model) {
      if (isEmpty(model)) {
        model = this.get('store').createRecord('patient-note', {
          visit: this.get('model'),
          createdBy: this.getUserName(),
          patient: this.get('model').get('patient'),
          noteType: this._computeNoteType(this.get('model'))
        });
      }
      this.send('openModal', 'patients.notes', model);
    },

    newAppointment() {
      this._addChildObject('appointments.edit');
    },

    newImaging() {
      this._addChildObject('imaging.edit');
    },

    newLab() {
      this._addChildObject('labs.edit');
    },

    newMedication() {
      this._addChildObject('medication.edit');
    },

    showAddProcedure() {
      this._addChildObject('procedures.edit');
    },

    showDeleteImaging(imaging) {
      this.send('openModal', 'imaging.delete', imaging);
    },

    showDeleteLab(lab) {
      this.send('openModal', 'labs.delete', lab);
    },

    showDeleteMedication(medication) {
      this.send('openModal', 'medication.delete', medication);
    },

    showDeleteProcedure(procedure) {
      this.send('openModal', 'visits.procedures.delete', procedure);
    },

    showDeleteVitals(vitals) {
      this.send('openModal', 'visits.vitals.delete', vitals);
    },

    showEditProcedure(procedure) {
      if (isEmpty(procedure.get('visit'))) {
        procedure.set('visit', this.get('model'));
      }
      procedure.set('returnToVisit', this.get('model.id'));
      procedure.set('returnToPatient');
      this.transitionToRoute('procedures.edit', procedure);
    },

    showEditVitals(vitals) {
      this.send('openModal', 'visits.vitals.edit', vitals);
    },

    showDeletePatientNote(note) {
      this.send('openModal', 'dialog', Ember.Object.create({
        confirmAction: 'deletePatientNote',
        title: 'Delete Note',
        message: 'Are you sure you want to delete this note?',
        noteToDelete: note,
        updateButtonAction: 'confirm',
        updateButtonText: this.get('i18n').t('buttons.ok')
      }));
    },

    deletePatientNote(model) {
      let note = model.get('noteToDelete');
      let patientNotes = this.get('model.patientNotes');
      patientNotes.removeObject(note);
      this.send('update', true);
    },

    startDateChanged(startDate) {
      let isAdmissionVisit = this.get('isAdmissionVisit');
      let visit = this.get('model');
      if (!isAdmissionVisit) {
        visit.set('endDate', startDate);
      }
    }

  }
});
<|endoftext|>