<commit_before>import m from 'mithril';
import _ from 'underscore';
import I18n from 'i18n-js';
import h from '../h';
import moment from 'moment';
import models from '../models';
import {
    catarse
} from '../api';
import contributionVM from '../vms/contribution-vm';
import commonPaymentVM from '../vms/common-payment-vm';
import ownerMessageContent from '../c/owner-message-content';
import subscriptionStatusIcon from '../c/subscription-status-icon';
import paymentMethodIcon from '../c/payment-method-icon';
import cancelSubscriptionContent from '../c/cancel-subscription-content';
import modalBox from '../c/modal-box';
import userVM from '../vms/user-vm';

const I18nScope = _.partial(h.i18nScope, 'payment.state');
const contributionScope = _.partial(h.i18nScope, 'users.contribution_row');

const userSubscriptionBox = {
    controller(args) {
        const subscription = args.subscription,
            displayModal = h.toggleProp(false, true),
            displayCancelModal = h.toggleProp(false, true),
            contactModalInfo = m.prop({});

        const filterProjVM = catarse.filtersVM({
                project_id: 'eq'
            }).project_id(subscription.project_external_id),
            lProj = catarse.loaderWithToken(models.project.getRowOptions(filterProjVM.parameters()));

        lProj.load().then((arr) => {
            subscription.project = arr[0];
            contactModalInfo({
                id: subscription.project.project_user_id,
                name: subscription.project.owner_name,
                project_id: subscription.project.project_id
            });
        });

        if (subscription.payment_method === 'boleto' && subscription.last_payment_id) {
            commonPaymentVM.paymentInfo(subscription.last_payment_id).then((info) => {
                subscription.boleto_url = info.boleto_url;
                subscription.boleto_expiration_date = info.boleto_expiration_date;
                subscription.payment_status = info.status;
            });
        }

        if (subscription.reward_external_id) {
            const filterRewVM = catarse.filtersVM({
                    id: 'eq'
                }).id(subscription.reward_external_id),
                lRew = catarse.loaderWithToken(models.rewardDetail.getRowOptions(filterRewVM.parameters()));

            lRew.load().then((arr) => {
                subscription.reward = arr[0];
            });
        }

        const showLastSubscriptionVersionValueIfHasOne = () => {
            const is_active = subscription.status === 'active';
            const current_paid_subscription = subscription.current_paid_subscription;
            const last_paid_sub_amount = is_active || !current_paid_subscription ? subscription.checkout_data.amount : current_paid_subscription.amount;

            // has some subscription edition
            if (is_active && current_paid_subscription && current_paid_subscription.amount != subscription.checkout_data.amount)
            {
                const paid_value = parseFloat(current_paid_subscription.amount) / 100;
                const next_value = parseFloat(subscription.checkout_data.amount) / 100;
                return [
                    `R$ ${h.formatNumber(paid_value)} por mês`,
                    m('span.badge.badge-attention', [
                        m('span.fa.fa-arrow-right', ''),
                        m.trust(' '),
                        `R$ ${h.formatNumber(next_value)}`,
                    ])
                ];
            }
            else
            {
                const paid_value = parseFloat(last_paid_sub_amount) / 100;
                return [`R$ ${h.formatNumber(paid_value)} por mês`];
            }

            return '';
        };

        const showLastSubscriptionVersionPaymentMethodIfHasOne = () => {
            const is_active = subscription.status === 'active';
            const current_paid_subscription = subscription.current_paid_subscription;
            const last_paid_sub_data = is_active || !current_paid_subscription ? subscription : current_paid_subscription;

            if (is_active && current_paid_subscription && subscription.checkout_data.payment_method != current_paid_subscription.payment_method)
            {
                return [
                    m(subscriptionStatusIcon, { subscription }),
                    m.trust('   '),
                    m(paymentMethodIcon, { subscription : current_paid_subscription}),
                    m('span.badge.badge-attention.fontweight-semibold', [
                        m('span.fa.fa-arrow-right', ''),
                        m.trust(' '),
                        m(paymentMethodIcon, { subscription })
                    ])
                ];
            }
            else
            {
                return [
                    m(subscriptionStatusIcon, { subscription }),
                    m.trust('   '),
                    m(paymentMethodIcon, { subscription: last_paid_sub_data })
                ];
            }

            return '';
        };

        const showLastSubscriptionVersionRewardTitleIfHasOne = () => {
            const is_active = subscription.status === 'active';
            const current_paid_subscription = subscription.current_paid_subscription;
            const current_reward_data = subscription.current_reward_data;
            const current_reward_id = subscription.current_reward_id;
            const last_paid_sub_data = is_active || !current_paid_subscription ? subscription : {reward: current_reward_data, reward_id: current_reward_id, reward_external_id: null};

            // first selection was no reward, but now selected one
            if (is_active && !current_reward_data && subscription.reward)
            {
                return [
                    ` ${I18n.t('no_reward', contributionScope())} `,
                    m.trust(' '),
                    m('.fontsize-smallest.fontweight-semibold',
                      m('span.badge.badge-attention', [
                          m('span.fa.fa-arrow-right', ''),
                          m.trust(' '),
                          subscription.reward.title
                      ]))
                ];
            }
	          // selected one rewared on subscription start, now selected another reward and last and current rewards are different
            else if (is_active && current_reward_data && subscription.reward && subscription.reward_id != current_reward_id)
            {
                const reward_description_formated = h.simpleFormat(`${current_reward_data.description.substring(0, 90)} (...)`);
                return [
                    m('.fontsize-smallest.fontweight-semibold', current_reward_data.title),
                    m('p.fontcolor-secondary.fontsize-smallest', m.trust(reward_description_formated)),
			              m('.fontsize-smallest.fontweight-semibold',
                      m('span.badge.badge-attention', [
                          m('span.fa.fa-arrow-right', ''),
                          m.trust(' '),
                          subscription.reward.title
                      ]))
                ];
            }
	          // no edition to rewards yet
            else if (last_paid_sub_data.reward)
            {
                const reward_description = last_paid_sub_data.reward.description.substring(0, 90);
                const reward_description_formated = h.simpleFormat(`${reward_description} (...)`);
                return [
                    m('.fontsize-smallest.fontweight-semibold', last_paid_sub_data.reward.title),
                    m('p.fontcolor-secondary.fontsize-smallest', m.trust(reward_description_formated))
                ];
            }
	          // no editions to reward yet and no reward selected
            else
            {
                return [
                    last_paid_sub_data.reward_external_id ? null : ` ${I18n.t('no_reward', contributionScope())} `
                ];
            }
        };

        const showLastSubscriptionVersionEditionNextCharge = () => {
            const current_reward_data = subscription.current_reward_data;
            const current_reward_id = subscription.current_reward_id;
            const current_paid_subscription = subscription.current_paid_subscription;

            if (current_paid_subscription &&
                (
                    subscription.reward_id != current_reward_id ||
                    subscription.checkout_data.payment_method != current_paid_subscription.payment_method ||
                    subscription.checkout_data.amount != current_paid_subscription.amount
                )
            ) {
                const message = `As alterações destacadas entrarão em vigor na próxima cobrança ${h.momentify(subscription.next_charge_at, 'DD/MM/YYYY')}.`;
                return m('.card-alert.fontsize-smaller.fontweight-semibold.u-marginbottom-10.u-radius', [
                    m('span.fa.fa-exclamation-triangle', ''),
                    m.trust(' '),
                    message
                ]);
            }

            return '';
        };

        return {
            toggleAnonymous: userVM.toggleAnonymous,
            displayModal,
            displayCancelModal,
            subscription,
            contactModalInfo,
            showLastSubscriptionVersionValueIfHasOne,
            showLastSubscriptionVersionPaymentMethodIfHasOne,
            showLastSubscriptionVersionRewardTitleIfHasOne,
            showLastSubscriptionVersionEditionNextCharge
        };
    },
    view(ctrl) {
        const subscription = ctrl.subscription;

        console.log('statuses: ', subscription.status, subscription.project);

        return (!_.isEmpty(subscription) && !_.isEmpty(subscription.project) ? m('div',
            (ctrl.displayCancelModal() && !_.isEmpty(ctrl.contactModalInfo()) ?
                m.component(modalBox, {
                    displayModal: ctrl.displayCancelModal,
                    content: [cancelSubscriptionContent, {
                        displayModal: ctrl.displayCancelModal,
                        subscription
                    }]
                }) : ''
            ),
            (ctrl.displayModal() && !_.isEmpty(ctrl.contactModalInfo()) ?
                m.component(modalBox, {
                    displayModal: ctrl.displayModal,
                    content: [ownerMessageContent, ctrl.contactModalInfo]
                }) : ''
            ), [
                m('.card.w-row', [
                    m('.u-marginbottom-20.w-col.w-col-3', [
                        m('.u-marginbottom-10.w-row', [
                            m('.u-marginbottom-10.w-col.w-col-4',
                                m(`a.w-inline-block[href='/${subscription.project.permalink}']`,
                                    m(`img.thumb-project.u-radius[alt='${subscription.project.project_name}'][src='${subscription.project.project_img}'][width='50']`)
                                )
                            ),
                            m('.w-col.w-col-8',
                                m('.fontsize-small.fontweight-semibold.lineheight-tight', [
                                    m(`a.link-hidden[href='/${subscription.project.permalink}']`,
                                        subscription.project.project_name
                                    ),
                                    m('img[alt="Badge Assinatura"][src="/assets/catarse_bootstrap/badge-sub-h.png"]')
                                ])
                            )
                        ]),
                        m("a.btn.btn-edit.btn-inline.btn-small.w-button[href='javascript:void(0);']", {
                            onclick: () => {
                                ctrl.displayModal.toggle();
                            }
                        },
                            I18n.t('contact_author', contributionScope())
                        )
                    ]),
                    m('.u-marginbottom-20.w-col.w-col-3', [
                        m('.fontsize-base.fontweight-semibold.lineheight-tighter', ctrl.showLastSubscriptionVersionValueIfHasOne()),
                        m('.fontcolor-secondary.fontsize-smaller.fontweight-semibold',
                            `Iniciou há ${moment(subscription.created_at).locale('pt').fromNow(true)}`
                        ),
                        m('.u-marginbottom-10', ctrl.showLastSubscriptionVersionPaymentMethodIfHasOne())
                    ]),
                    m('.u-marginbottom-20.w-col.w-col-3', ctrl.showLastSubscriptionVersionRewardTitleIfHasOne()),
                    m('.u-marginbottom-10.u-text-center.w-col.w-col-3',
                        (subscription.status === 'started' ? [
                            m('.card-alert.fontsize-smaller.fontweight-semibold.u-marginbottom-10.u-radius', [
                                m('span.fa.fa-exclamation-triangle'),
                                m.trust(' '),
                                'Aguardando confirmação do pagamento'
                            ]),
                                (subscription.boleto_url ? m(`a.btn.btn-inline.btn-small.w-button[target=_blank][href=${subscription.boleto_url}]`, 'Imprimir boleto') : null)
                        ] :
                            (subscription.status === 'inactive' ? [
                                (subscription.payment_status === 'pending'
                                    && subscription.boleto_url
                                    && subscription.boleto_expiration_date ? [
                                        m('.card-alert.fontsize-smaller.fontweight-semibold.u-marginbottom-10.u-radius', [
                                            m('span.fa.fa-exclamation-triangle'),
                                            ` O boleto de sua assinatura vence dia ${h.momentify(subscription.boleto_expiration_date)}`
                                        ]),
                                        m(`a.btn.btn-inline.btn-small.w-button[target=_blank][href=${subscription.boleto_url}]`, 'Imprimir boleto')
                                    ] : [
                                        m('.card-alert.fontsize-smaller.fontweight-semibold.u-marginbottom-10.u-radius', [
                                            m('span.fa.fa-exclamation-triangle'),
                                            m.trust(' '),
                                            'Sua assinatura está inativa por falta de pagamento'
                                        ]),
                                        m(`a.btn.btn-inline.btn-small.w-button[target=_blank][href=/projects/${subscription.project_external_id}/subscriptions/start?subscription_id=${subscription.id}${subscription.reward_external_id ? `&reward_id=${subscription.reward_external_id}` : ''}&subscription_status=${subscription.status}]`, 'Assinar novamente')
                                    ])
                            ] : subscription.status === 'canceled' && subscription.project.state == 'online' ? [
                                m('a.btn.btn-inline.btn-small.w-button',
                                        { href: `/projects/${subscription.project_external_id}/subscriptions/start?subscription_id=${subscription.id}${subscription.reward_external_id ? `&reward_id=${subscription.reward_external_id}` : ''}&subscription_status=${subscription.status}` },
                                        'Assinar novamente'
                                 )
                            ] : subscription.status === 'canceling' ?
                                m('.u-radius.fontsize-smaller.u-marginbottom-10.fontweight-semibold.card-error',
                                    m('div', [
                                        m('span.fa.fa-exclamation-triangle',
                                            ' '
                                        ),
                                        ` Sua assinatura será cancelada no dia ${h.momentify(subscription.next_charge_at, 'DD/MM/YYYY')}. Até lá, ela ainda será considerada ativa.`
                                    ])
                                ) : (subscription.status === 'active' ? [
                                    ctrl.showLastSubscriptionVersionEditionNextCharge(),
                                    subscription.payment_status !== 'pending' ? m('a.btn.btn-terciary.u-marginbottom-20.btn-inline.w-button',
                                        { href: `/projects/${subscription.project_external_id}/subscriptions/start?${subscription.reward_external_id ? `reward_id=${subscription.reward_external_id}` : ''}&subscription_id=${subscription.id}&subscription_status=${subscription.status}` },
                                        'Editar assinatura'
                                    ) : '',
                                    subscription.payment_status === 'pending'
                                    && subscription.boleto_url
                                    && subscription.boleto_expiration_date ?
                                    [
                                        moment(subscription.boleto_expiration_date).add(1, 'days').isBefore(Date.now())
                                            ? m('.card-alert.fontsize-smaller.fontweight-semibold.u-marginbottom-10.u-radius', [
                                                m('span.fa.fa-exclamation-triangle'),
                                                ` O boleto de sua assinatura venceu dia ${h.momentify(subscription.boleto_expiration_date)}`
                                            ])
                                            : [
                                                m('.card-alert.fontsize-smaller.fontweight-semibold.u-marginbottom-10.u-radius', [
                                                    m('span.fa.fa-exclamation-triangle'),
                                                    ` O boleto de sua assinatura vence dia ${h.momentify(subscription.boleto_expiration_date)}`
                                                ]),
                                                m(`a.btn.btn-inline.btn-small.u-marginbottom-20.w-button[target=_blank][href=${subscription.boleto_url}]`, 'Imprimir boleto')
                                            ]
                                    ] : '',
                                    m('button.btn-link.fontsize-smallest.link-hidden-light', {
                                        onclick: () => {
                                            ctrl.displayCancelModal.toggle();
                                        }
                                    },
                                        'Cancelar assinatura'
                                    )
                                ] : null)

                            ))
                    )
                ])
            ]
        ) : m('div', ''));
    }
};

export default userSubscriptionBox;
<commit_msg>fix show re-subscribe again button #157199662<commit_after>import m from 'mithril';
import _ from 'underscore';
import I18n from 'i18n-js';
import h from '../h';
import moment from 'moment';
import models from '../models';
import {
    catarse
} from '../api';
import contributionVM from '../vms/contribution-vm';
import commonPaymentVM from '../vms/common-payment-vm';
import ownerMessageContent from '../c/owner-message-content';
import subscriptionStatusIcon from '../c/subscription-status-icon';
import paymentMethodIcon from '../c/payment-method-icon';
import cancelSubscriptionContent from '../c/cancel-subscription-content';
import modalBox from '../c/modal-box';
import userVM from '../vms/user-vm';

const I18nScope = _.partial(h.i18nScope, 'payment.state');
const contributionScope = _.partial(h.i18nScope, 'users.contribution_row');

const userSubscriptionBox = {
    controller(args) {
        const subscription = args.subscription,
            displayModal = h.toggleProp(false, true),
            displayCancelModal = h.toggleProp(false, true),
            contactModalInfo = m.prop({});

        const filterProjVM = catarse.filtersVM({
                project_id: 'eq'
            }).project_id(subscription.project_external_id),
            lProj = catarse.loaderWithToken(models.project.getRowOptions(filterProjVM.parameters()));

        lProj.load().then((arr) => {
            subscription.project = arr[0];
            contactModalInfo({
                id: subscription.project.project_user_id,
                name: subscription.project.owner_name,
                project_id: subscription.project.project_id
            });
        });

        if (subscription.payment_method === 'boleto' && subscription.last_payment_id) {
            commonPaymentVM.paymentInfo(subscription.last_payment_id).then((info) => {
                subscription.boleto_url = info.boleto_url;
                subscription.boleto_expiration_date = info.boleto_expiration_date;
                subscription.payment_status = info.status;
            });
        }

        if (subscription.reward_external_id) {
            const filterRewVM = catarse.filtersVM({
                    id: 'eq'
                }).id(subscription.reward_external_id),
                lRew = catarse.loaderWithToken(models.rewardDetail.getRowOptions(filterRewVM.parameters()));

            lRew.load().then((arr) => {
                subscription.reward = arr[0];
            });
        }

        const showLastSubscriptionVersionValueIfHasOne = () => {
            const is_active = subscription.status === 'active';
            const current_paid_subscription = subscription.current_paid_subscription;
            const last_paid_sub_amount = is_active || !current_paid_subscription ? subscription.checkout_data.amount : current_paid_subscription.amount;

            // has some subscription edition
            if (is_active && current_paid_subscription && current_paid_subscription.amount != subscription.checkout_data.amount)
            {
                const paid_value = parseFloat(current_paid_subscription.amount) / 100;
                const next_value = parseFloat(subscription.checkout_data.amount) / 100;
                return [
                    `R$ ${h.formatNumber(paid_value)} por mês`,
                    m('span.badge.badge-attention', [
                        m('span.fa.fa-arrow-right', ''),
                        m.trust(' '),
                        `R$ ${h.formatNumber(next_value)}`,
                    ])
                ];
            }
            else
            {
                const paid_value = parseFloat(last_paid_sub_amount) / 100;
                return [`R$ ${h.formatNumber(paid_value)} por mês`];
            }

            return '';
        };

        const showLastSubscriptionVersionPaymentMethodIfHasOne = () => {
            const is_active = subscription.status === 'active';
            const current_paid_subscription = subscription.current_paid_subscription;
            const last_paid_sub_data = is_active || !current_paid_subscription ? subscription : current_paid_subscription;

            if (is_active && current_paid_subscription && subscription.checkout_data.payment_method != current_paid_subscription.payment_method)
            {
                return [
                    m(subscriptionStatusIcon, { subscription }),
                    m.trust('   '),
                    m(paymentMethodIcon, { subscription : current_paid_subscription}),
                    m('span.badge.badge-attention.fontweight-semibold', [
                        m('span.fa.fa-arrow-right', ''),
                        m.trust(' '),
                        m(paymentMethodIcon, { subscription })
                    ])
                ];
            }
            else
            {
                return [
                    m(subscriptionStatusIcon, { subscription }),
                    m.trust('   '),
                    m(paymentMethodIcon, { subscription: last_paid_sub_data })
                ];
            }

            return '';
        };

        const showLastSubscriptionVersionRewardTitleIfHasOne = () => {
            const is_active = subscription.status === 'active';
            const current_paid_subscription = subscription.current_paid_subscription;
            const current_reward_data = subscription.current_reward_data;
            const current_reward_id = subscription.current_reward_id;
            const last_paid_sub_data = is_active || !current_paid_subscription ? subscription : {reward: current_reward_data, reward_id: current_reward_id, reward_external_id: null};

            // first selection was no reward, but now selected one
            if (is_active && !current_reward_data && subscription.reward)
            {
                return [
                    ` ${I18n.t('no_reward', contributionScope())} `,
                    m.trust(' '),
                    m('.fontsize-smallest.fontweight-semibold',
                      m('span.badge.badge-attention', [
                          m('span.fa.fa-arrow-right', ''),
                          m.trust(' '),
                          subscription.reward.title
                      ]))
                ];
            }
	          // selected one rewared on subscription start, now selected another reward and last and current rewards are different
            else if (is_active && current_reward_data && subscription.reward && subscription.reward_id != current_reward_id)
            {
                const reward_description_formated = h.simpleFormat(`${current_reward_data.description.substring(0, 90)} (...)`);
                return [
                    m('.fontsize-smallest.fontweight-semibold', current_reward_data.title),
                    m('p.fontcolor-secondary.fontsize-smallest', m.trust(reward_description_formated)),
			              m('.fontsize-smallest.fontweight-semibold',
                      m('span.badge.badge-attention', [
                          m('span.fa.fa-arrow-right', ''),
                          m.trust(' '),
                          subscription.reward.title
                      ]))
                ];
            }
	          // no edition to rewards yet
            else if (last_paid_sub_data.reward)
            {
                const reward_description = last_paid_sub_data.reward.description.substring(0, 90);
                const reward_description_formated = h.simpleFormat(`${reward_description} (...)`);
                return [
                    m('.fontsize-smallest.fontweight-semibold', last_paid_sub_data.reward.title),
                    m('p.fontcolor-secondary.fontsize-smallest', m.trust(reward_description_formated))
                ];
            }
	          // no editions to reward yet and no reward selected
            else
            {
                return [
                    last_paid_sub_data.reward_external_id ? null : ` ${I18n.t('no_reward', contributionScope())} `
                ];
            }
        };

        const showLastSubscriptionVersionEditionNextCharge = () => {
            const current_reward_data = subscription.current_reward_data;
            const current_reward_id = subscription.current_reward_id;
            const current_paid_subscription = subscription.current_paid_subscription;

            if (current_paid_subscription &&
                (
                    subscription.reward_id != current_reward_id ||
                    subscription.checkout_data.payment_method != current_paid_subscription.payment_method ||
                    subscription.checkout_data.amount != current_paid_subscription.amount
                )
            ) {
                const message = `As alterações destacadas entrarão em vigor na próxima cobrança ${h.momentify(subscription.next_charge_at, 'DD/MM/YYYY')}.`;
                return m('.card-alert.fontsize-smaller.fontweight-semibold.u-marginbottom-10.u-radius', [
                    m('span.fa.fa-exclamation-triangle', ''),
                    m.trust(' '),
                    message
                ]);
            }

            return '';
        };

        return {
            toggleAnonymous: userVM.toggleAnonymous,
            displayModal,
            displayCancelModal,
            subscription,
            contactModalInfo,
            showLastSubscriptionVersionValueIfHasOne,
            showLastSubscriptionVersionPaymentMethodIfHasOne,
            showLastSubscriptionVersionRewardTitleIfHasOne,
            showLastSubscriptionVersionEditionNextCharge
        };
    },
    view(ctrl) {
        const subscription = ctrl.subscription;

        console.log('statuses: ', subscription.status, subscription.project);

        return (!_.isEmpty(subscription) && !_.isEmpty(subscription.project) ? m('div',
            (ctrl.displayCancelModal() && !_.isEmpty(ctrl.contactModalInfo()) ?
                m.component(modalBox, {
                    displayModal: ctrl.displayCancelModal,
                    content: [cancelSubscriptionContent, {
                        displayModal: ctrl.displayCancelModal,
                        subscription
                    }]
                }) : ''
            ),
            (ctrl.displayModal() && !_.isEmpty(ctrl.contactModalInfo()) ?
                m.component(modalBox, {
                    displayModal: ctrl.displayModal,
                    content: [ownerMessageContent, ctrl.contactModalInfo]
                }) : ''
            ), [
                m('.card.w-row', [
                    m('.u-marginbottom-20.w-col.w-col-3', [
                        m('.u-marginbottom-10.w-row', [
                            m('.u-marginbottom-10.w-col.w-col-4',
                                m(`a.w-inline-block[href='/${subscription.project.permalink}']`,
                                    m(`img.thumb-project.u-radius[alt='${subscription.project.project_name}'][src='${subscription.project.project_img}'][width='50']`)
                                )
                            ),
                            m('.w-col.w-col-8',
                                m('.fontsize-small.fontweight-semibold.lineheight-tight', [
                                    m(`a.link-hidden[href='/${subscription.project.permalink}']`,
                                        subscription.project.project_name
                                    ),
                                    m('img[alt="Badge Assinatura"][src="/assets/catarse_bootstrap/badge-sub-h.png"]')
                                ])
                            )
                        ]),
                        m("a.btn.btn-edit.btn-inline.btn-small.w-button[href='javascript:void(0);']", {
                            onclick: () => {
                                ctrl.displayModal.toggle();
                            }
                        },
                            I18n.t('contact_author', contributionScope())
                        )
                    ]),
                    m('.u-marginbottom-20.w-col.w-col-3', [
                        m('.fontsize-base.fontweight-semibold.lineheight-tighter', ctrl.showLastSubscriptionVersionValueIfHasOne()),
                        m('.fontcolor-secondary.fontsize-smaller.fontweight-semibold',
                            `Iniciou há ${moment(subscription.created_at).locale('pt').fromNow(true)}`
                        ),
                        m('.u-marginbottom-10', ctrl.showLastSubscriptionVersionPaymentMethodIfHasOne())
                    ]),
                    m('.u-marginbottom-20.w-col.w-col-3', ctrl.showLastSubscriptionVersionRewardTitleIfHasOne()),
                    m('.u-marginbottom-10.u-text-center.w-col.w-col-3',
                        (subscription.status === 'started' ? [
                            m('.card-alert.fontsize-smaller.fontweight-semibold.u-marginbottom-10.u-radius', [
                                m('span.fa.fa-exclamation-triangle'),
                                m.trust(' '),
                                'Aguardando confirmação do pagamento'
                            ]),
                                (subscription.boleto_url ? m(`a.btn.btn-inline.btn-small.w-button[target=_blank][href=${subscription.boleto_url}]`, 'Imprimir boleto') : null)
                        ] :
                            (subscription.status === 'inactive' ? [
                                (subscription.payment_status === 'pending'
                                    && subscription.boleto_url
                                    && subscription.boleto_expiration_date ? [
                                        m('.card-alert.fontsize-smaller.fontweight-semibold.u-marginbottom-10.u-radius', [
                                            m('span.fa.fa-exclamation-triangle'),
                                            ` O boleto de sua assinatura vence dia ${h.momentify(subscription.boleto_expiration_date)}`
                                        ]),
                                        m(`a.btn.btn-inline.btn-small.w-button[target=_blank][href=${subscription.boleto_url}]`, 'Imprimir boleto')
                                    ] : [
                                        m('.card-alert.fontsize-smaller.fontweight-semibold.u-marginbottom-10.u-radius', [
                                            m('span.fa.fa-exclamation-triangle'),
                                            m.trust(' '),
                                            'Sua assinatura está inativa por falta de pagamento'
                                        ]),
                                        m(`a.btn.btn-inline.btn-small.w-button[target=_blank][href=/projects/${subscription.project_external_id}/subscriptions/start?subscription_id=${subscription.id}${subscription.reward_external_id ? `&reward_id=${subscription.reward_external_id}` : ''}&subscription_status=${subscription.status}]`, 'Assinar novamente')
                                    ])
                            ] : subscription.status === 'canceled' && subscription.project.state == 'online' ? [
                                m('a.btn.btn-terciary.u-marginbottom-20.btn-inline.w-button',
                                        { href: `/projects/${subscription.project_external_id}/subscriptions/start?subscription_id=${subscription.id}${subscription.reward_external_id ? `&reward_id=${subscription.reward_external_id}` : ''}&subscription_status=${subscription.status}` },
                                        'Reativar assinatura'
                                    ),
                                m('.card-error.fontsize-smaller.fontweight-semibold.u-marginbottom-10.u-radius', [
                                    m('span.fa.fa-exclamation-triangle'),
                                    m.trust(' '),
                                    ' Você cancelou sua assinatura'
                                ])
                            ] : subscription.status === 'canceling' ?
                                m('.u-radius.fontsize-smaller.u-marginbottom-10.fontweight-semibold.card-error',
                                    m('div', [
                                        m('span.fa.fa-exclamation-triangle',
                                            ' '
                                        ),
                                        ` Sua assinatura será cancelada no dia ${h.momentify(subscription.next_charge_at, 'DD/MM/YYYY')}. Até lá, ela ainda será considerada ativa.`
                                    ])
                                ) : (subscription.status === 'active' ? [
                                    ctrl.showLastSubscriptionVersionEditionNextCharge(),
                                    subscription.payment_status !== 'pending' ? m('a.btn.btn-terciary.u-marginbottom-20.btn-inline.w-button',
                                        { href: `/projects/${subscription.project_external_id}/subscriptions/start?${subscription.reward_external_id ? `reward_id=${subscription.reward_external_id}` : ''}&subscription_id=${subscription.id}&subscription_status=${subscription.status}` },
                                        'Editar assinatura'
                                    ) : '',
                                    subscription.payment_status === 'pending'
                                    && subscription.boleto_url
                                    && subscription.boleto_expiration_date ?
                                    [
                                        moment(subscription.boleto_expiration_date).add(1, 'days').isBefore(Date.now())
                                            ? m('.card-alert.fontsize-smaller.fontweight-semibold.u-marginbottom-10.u-radius', [
                                                m('span.fa.fa-exclamation-triangle'),
                                                ` O boleto de sua assinatura venceu dia ${h.momentify(subscription.boleto_expiration_date)}`
                                            ])
                                            : [
                                                m('.card-alert.fontsize-smaller.fontweight-semibold.u-marginbottom-10.u-radius', [
                                                    m('span.fa.fa-exclamation-triangle'),
                                                    ` O boleto de sua assinatura vence dia ${h.momentify(subscription.boleto_expiration_date)}`
                                                ]),
                                                m(`a.btn.btn-inline.btn-small.u-marginbottom-20.w-button[target=_blank][href=${subscription.boleto_url}]`, 'Imprimir boleto')
                                            ]
                                    ] : '',
                                    m('button.btn-link.fontsize-smallest.link-hidden-light', {
                                        onclick: () => {
                                            ctrl.displayCancelModal.toggle();
                                        }
                                    },
                                        'Cancelar assinatura'
                                    )
                                ] : null)

                            ))
                    )
                ])
            ]
        ) : m('div', ''));
    }
};

export default userSubscriptionBox;
<|endoftext|>


<commit_before>/*eslint no-unused-vars: 0*/
/*eslint no-shadow: 0*/

import { get, now } from 'lodash';
import { Keyboard } from 'phaser';
import Entity from 'shared/game/entity';
import InputComponent from '../game/components/input';
import SpriteComponent from '../game/components/sprite';
import TextComponent from '../game/components/text';
import SoundComponent from '../game/components/sound';
import AttackComponent from '../game/components/attack';
import { createSprite } from './sprite';
import { createNameTag } from './text';
import { isEntityMoving, resolveActionAnimation } from '../helpers/game';
import {
  CONTEXT_SERVER,
  setPosition,
  setVelocity,
  setAnimation,
  setFacing,
  beginAttack,
  endAttack,
  damageEntity,
  tagFlag
} from '../actions/game';

export const PLAYER = 'player';
export const FLAG = 'flag';
export const TEAM = 'team';

const SOUND_VOLUME = 0.03;

/**
 *
 * @param {Phaser.State} state
 * @param {Object} props
 * @returns {Entity}
 */
export function createLocalPlayer(state, props) {
  const entity = new Entity(props);

  const wallLayer = state.getLayer('Walls');
  const rootGroup = state.getGroup('root');
  const knightGroup = state.getGroup('knights');
  const flagGroup = state.getGroup('flags');
  const attackGroup = state.getGroup('attacks');

  const cursorKeys = state.input.keyboard.createCursorKeys();
  const attackKey = state.input.keyboard.addKey(Keyboard.SPACEBAR);
  const sprintKey = state.input.keyboard.addKey(Keyboard.SHIFT);

  const onInputComponentUpdate = function(updateProps, dispatch) {
    const cursors = this.getKey('cursors');
    const attack = this.getKey('attack');
    const sprint = this.getKey('sprint');

    const attackComponent = this.getComponent('attack');

    if (attack.isDown && attackComponent.canAttack()) {
      dispatch(beginAttack(updateProps.id));
    }

    const velocity = sprint.isDown ? updateProps.runSpeed * 1.5 : updateProps.runSpeed;

    // TODO: Add constants for facing directions to game/actions.

    if (cursors.left.isDown) {
      dispatch(setVelocity(updateProps.id, -velocity, 0));
      dispatch(setFacing(updateProps.id, 'left'));
    } else if (cursors.right.isDown) {
      dispatch(setVelocity(updateProps.id, velocity, 0));
      dispatch(setFacing(updateProps.id, 'right'));
    } else if (cursors.up.isDown) {
      dispatch(setVelocity(updateProps.id, 0, -velocity));
      dispatch(setFacing(updateProps.id, 'up'));
    } else if (cursors.down.isDown) {
      dispatch(setVelocity(updateProps.id, 0, velocity));
      dispatch(setFacing(updateProps.id, 'down'));
    } else if (!isEntityMoving(updateProps)) {
      dispatch(setVelocity(updateProps.id, 0, 0));
      dispatch(setFacing(updateProps.id, null));
    }
  };

  entity.addComponent(new InputComponent({ cursors: cursorKeys, attack: attackKey, sprint: sprintKey }, onInputComponentUpdate));

  const knightSprite = createSprite(state, null, props);
  const graveSprite = createSprite(state, rootGroup, { type: 'grave' });

  // Add the player to the root group so that it's rendered in the correct order.
  rootGroup.add(knightSprite);

  state.physics.arcade.enable(knightSprite);
  state.camera.follow(knightSprite);

  knightSprite.body.collideWorldBounds = true;

  const onSpriteComponentUpdate = function(updateProps, dispatch) {
    const knight = this.getSprite('knight');
    const grave = this.getSprite('grave');

    state.physics.arcade.collide(knight, wallLayer);

    state.physics.arcade.collide(knight, flagGroup, null/* collideCallback */, (knight, flag) => {
      dispatch(tagFlag(updateProps.id, flag.name));
      return false; // allows passing through flags
    }/* processCallback */);

    knight.body.velocity.set(0);

    if (updateProps.vx) {
      knight.body.velocity.x = updateProps.vx;
    } else if (updateProps.vy) {
      knight.body.velocity.y = updateProps.vy;
    }

    // TODO: Clean up code related to determining the current animation.

    const animation = resolveActionAnimation(updateProps.isAttacking ? 'attack' : 'run', updateProps.facing);
    const currentAnimation = get(knight, 'animations.currentAnim.name');

    if (animation && animation !== currentAnimation) {
      knight.animations.play(animation);
      dispatch(setAnimation(updateProps.id, animation, CONTEXT_SERVER));
    }

    if (updateProps.isDead && knight.alive) {
      const dieSound = this.getComponent('sound').getSound('die');
      knight.kill();
      grave.reset(updateProps.x, updateProps.y);
      dieSound.play();
    } else if (!updateProps.isDead && !knight.alive) {
      grave.kill();
      knight.revive();
    }

    if (!updateProps.isDead && knight.x !== updateProps.x || knight.y !== updateProps.y) {
      if (!updateProps.isReviving) {
        dispatch(setPosition(updateProps.id, knight.x, knight.y, CONTEXT_SERVER));
      } else {
        knight.x = updateProps.x;
        knight.y = updateProps.y;
      }
    }

    // const nameText = this.getComponent('text').getText('name');
    //
    // nameText.x = knightSprite.x + (knightSprite.width / 2);
    // nameText.y = knightSprite.y;

    // state.game.debug.body(knightSprite);
  };

  entity.addComponent(new SpriteComponent({ knight: knightSprite, grave: graveSprite }, onSpriteComponentUpdate));

  const hitSound = state.add.audio('knight-hit', SOUND_VOLUME);
  const dieSound = state.add.audio('knight-die', SOUND_VOLUME);

  entity.addComponent(new SoundComponent({ hit: hitSound, die: dieSound }));

  for (let i = 0; i < 20; i++) {
    createSprite(state, attackGroup, { type: 'attack' });
  }

  const onAttackComponentUpdate = function(updateProps, dispatch) {
    if (updateProps.isAttacking && this.canAttack()) {
      const attack = this.getAttackSprite();

      if (attack) {
        const hit = this.getComponent('sound').getSound('hit');
        const { x, y } = this.calculateAttackTarget(attack, updateProps);

        attack.reset(x, y);
        hit.play();

        state.physics.arcade.collide(attack, knightGroup, null/* collideCallback */, (attack, knight) => {
          dispatch(damageEntity(updateProps.id, knight.name));
          return false; // allows passing through attacks
        });

        attack.kill();

        this.attackPerformed();

        setTimeout(() => {
          dispatch(endAttack(updateProps.id));
        }, 100);

        // state.game.debug.body(attack);
      }
    }
  };

  entity.addComponent(new AttackComponent(attackGroup, onAttackComponentUpdate));

  // TODO: Fix name tag positioning
  // const nameText = createNameTag(state, props);
  // entity.addComponent(new Text({name: nameText}));

  return entity;
}

/**
 *
 * @param {Phaser.State} state
 * @param {Object} props
 * @returns {Entity}
 */
function createRemotePlayer(state, props) {
  const entity = new Entity(props);

  const rootGroup = state.getGroup('root');
  const knightGroup = state.getGroup('knights');

  const knightSprite = createSprite(state, knightGroup, props);
  const graveSprite = createSprite(state, rootGroup, { type: 'grave' });

  const onSpriteComponentUpdate = function(updateProps) {
    const knight = this.getSprite('knight');
    const grave = this.getSprite('grave');

    knight.x = updateProps.x;
    knight.y = updateProps.y;

    const currentAnimation = get(knight, 'animations.currentAnim.name');

    // TODO: Ensure that this works as intended.

    if (updateProps.animation && updateProps.animation !== currentAnimation) {
      knight.animations.play(updateProps.animation);
    }

    if (updateProps.isDead && knight.alive) {
      const dieSound = this.getComponent('sound').getSound('die');
      knight.kill();
      grave.reset(updateProps.x, updateProps.y);
      dieSound.play();
    } else if (!updateProps.isDead && !knight.alive) {
      grave.kill();
      knight.revive();
    }

    const name = this.getComponent('text').getText('name');

    name.x = knight.x + (knight.width / 2);
    name.y = knight.y;

    // state.game.debug.body(knight);
  };

  entity.addComponent(new SpriteComponent({ knight: knightSprite, grave: graveSprite }, onSpriteComponentUpdate));

  const hitSound = state.add.audio('knight-hit', SOUND_VOLUME);
  const dieSound = state.add.audio('knight-die', SOUND_VOLUME);

  entity.addComponent(new SoundComponent({ hit: hitSound, die: dieSound }));

  const nameText = createNameTag(state, props);
  entity.addComponent(new TextComponent({ name: nameText }));

  return entity;
}

/**
 *
 * @param {Phaser.State} state
 * @param {Object} props
 * @returns {Entity}
 */
function createFlag(state, props) {
  const entity = new Entity(props);

  const flagGroup = state.getGroup('flags');

  const flagSprite = createSprite(state, flagGroup, props);

  const onSpriteComponentUpdate = function(updateProps) {
    const flag = this.getSprite('flag');

    if (updateProps.color !== this.getProp('color')) {
      flag.animations.play(updateProps.color);
    }
  };

  entity.addComponent(new SpriteComponent({ flag: flagSprite }, onSpriteComponentUpdate));

  return entity;
}

/**
 * @param {Phaser.State} state
 * @param {Object} props
 * @returns {Entity}
 */
export function createEntity(state, props) {
  switch (props.type) {
    case PLAYER:
      return createRemotePlayer(state, props);

    case FLAG:
      return createFlag(state, props);

    default:
      return null;
  }
}
<commit_msg>Remove commented code from entity factory (client)<commit_after>/*eslint no-unused-vars: 0*/
/*eslint no-shadow: 0*/

import { get, now } from 'lodash';
import { Keyboard } from 'phaser';
import Entity from 'shared/game/entity';
import InputComponent from '../game/components/input';
import SpriteComponent from '../game/components/sprite';
import TextComponent from '../game/components/text';
import SoundComponent from '../game/components/sound';
import AttackComponent from '../game/components/attack';
import { createSprite } from './sprite';
import { createNameTag } from './text';
import { isEntityMoving, resolveActionAnimation } from '../helpers/game';
import {
  CONTEXT_SERVER,
  setPosition,
  setVelocity,
  setAnimation,
  setFacing,
  beginAttack,
  endAttack,
  damageEntity,
  tagFlag
} from '../actions/game';

export const PLAYER = 'player';
export const FLAG = 'flag';
export const TEAM = 'team';

const SOUND_VOLUME = 0.03;

/**
 *
 * @param {Phaser.State} state
 * @param {Object} props
 * @returns {Entity}
 */
export function createLocalPlayer(state, props) {
  const entity = new Entity(props);

  const wallLayer = state.getLayer('Walls');
  const rootGroup = state.getGroup('root');
  const knightGroup = state.getGroup('knights');
  const flagGroup = state.getGroup('flags');
  const attackGroup = state.getGroup('attacks');

  const cursorKeys = state.input.keyboard.createCursorKeys();
  const attackKey = state.input.keyboard.addKey(Keyboard.SPACEBAR);
  const sprintKey = state.input.keyboard.addKey(Keyboard.SHIFT);

  const onInputComponentUpdate = function(updateProps, dispatch) {
    const cursors = this.getKey('cursors');
    const attack = this.getKey('attack');
    const sprint = this.getKey('sprint');

    const attackComponent = this.getComponent('attack');

    if (attack.isDown && attackComponent.canAttack()) {
      dispatch(beginAttack(updateProps.id));
    }

    const velocity = sprint.isDown ? updateProps.runSpeed * 1.5 : updateProps.runSpeed;

    // TODO: Add constants for facing directions to game/actions.

    if (cursors.left.isDown) {
      dispatch(setVelocity(updateProps.id, -velocity, 0));
      dispatch(setFacing(updateProps.id, 'left'));
    } else if (cursors.right.isDown) {
      dispatch(setVelocity(updateProps.id, velocity, 0));
      dispatch(setFacing(updateProps.id, 'right'));
    } else if (cursors.up.isDown) {
      dispatch(setVelocity(updateProps.id, 0, -velocity));
      dispatch(setFacing(updateProps.id, 'up'));
    } else if (cursors.down.isDown) {
      dispatch(setVelocity(updateProps.id, 0, velocity));
      dispatch(setFacing(updateProps.id, 'down'));
    } else if (!isEntityMoving(updateProps)) {
      dispatch(setVelocity(updateProps.id, 0, 0));
      dispatch(setFacing(updateProps.id, null));
    }
  };

  entity.addComponent(new InputComponent({ cursors: cursorKeys, attack: attackKey, sprint: sprintKey }, onInputComponentUpdate));

  const knightSprite = createSprite(state, null, props);
  const graveSprite = createSprite(state, rootGroup, { type: 'grave' });

  // Add the player to the root group so that it's rendered in the correct order.
  rootGroup.add(knightSprite);

  state.physics.arcade.enable(knightSprite);
  state.camera.follow(knightSprite);

  knightSprite.body.collideWorldBounds = true;

  const onSpriteComponentUpdate = function(updateProps, dispatch) {
    const knight = this.getSprite('knight');
    const grave = this.getSprite('grave');

    state.physics.arcade.collide(knight, wallLayer);

    state.physics.arcade.collide(knight, flagGroup, null/* collideCallback */, (knight, flag) => {
      dispatch(tagFlag(updateProps.id, flag.name));
      return false; // allows passing through flags
    }/* processCallback */);

    knight.body.velocity.set(0);

    if (updateProps.vx) {
      knight.body.velocity.x = updateProps.vx;
    } else if (updateProps.vy) {
      knight.body.velocity.y = updateProps.vy;
    }

    // TODO: Clean up code related to determining the current animation.

    const animation = resolveActionAnimation(updateProps.isAttacking ? 'attack' : 'run', updateProps.facing);
    const currentAnimation = get(knight, 'animations.currentAnim.name');

    if (animation && animation !== currentAnimation) {
      knight.animations.play(animation);
      dispatch(setAnimation(updateProps.id, animation, CONTEXT_SERVER));
    }

    if (updateProps.isDead && knight.alive) {
      const dieSound = this.getComponent('sound').getSound('die');
      knight.kill();
      grave.reset(updateProps.x, updateProps.y);
      dieSound.play();
    } else if (!updateProps.isDead && !knight.alive) {
      grave.kill();
      knight.revive();
    }

    if (!updateProps.isDead && knight.x !== updateProps.x || knight.y !== updateProps.y) {
      if (!updateProps.isReviving) {
        dispatch(setPosition(updateProps.id, knight.x, knight.y, CONTEXT_SERVER));
      } else {
        knight.x = updateProps.x;
        knight.y = updateProps.y;
      }
    }
  };

  entity.addComponent(new SpriteComponent({ knight: knightSprite, grave: graveSprite }, onSpriteComponentUpdate));

  const hitSound = state.add.audio('knight-hit', SOUND_VOLUME);
  const dieSound = state.add.audio('knight-die', SOUND_VOLUME);

  entity.addComponent(new SoundComponent({ hit: hitSound, die: dieSound }));

  for (let i = 0; i < 20; i++) {
    createSprite(state, attackGroup, { type: 'attack' });
  }

  const onAttackComponentUpdate = function(updateProps, dispatch) {
    if (updateProps.isAttacking && this.canAttack()) {
      const attack = this.getAttackSprite();

      if (attack) {
        const hit = this.getComponent('sound').getSound('hit');
        const { x, y } = this.calculateAttackTarget(attack, updateProps);

        attack.reset(x, y);
        hit.play();

        state.physics.arcade.collide(attack, knightGroup, null/* collideCallback */, (attack, knight) => {
          dispatch(damageEntity(updateProps.id, knight.name));
          return false; // allows passing through attacks
        });

        attack.kill();

        this.attackPerformed();

        setTimeout(() => {
          dispatch(endAttack(updateProps.id));
        }, 100);

        // state.game.debug.body(attack);
      }
    }
  };

  entity.addComponent(new AttackComponent(attackGroup, onAttackComponentUpdate));

  return entity;
}

/**
 *
 * @param {Phaser.State} state
 * @param {Object} props
 * @returns {Entity}
 */
function createRemotePlayer(state, props) {
  const entity = new Entity(props);

  const rootGroup = state.getGroup('root');
  const knightGroup = state.getGroup('knights');

  const knightSprite = createSprite(state, knightGroup, props);
  const graveSprite = createSprite(state, rootGroup, { type: 'grave' });

  const onSpriteComponentUpdate = function(updateProps) {
    const knight = this.getSprite('knight');
    const grave = this.getSprite('grave');

    knight.x = updateProps.x;
    knight.y = updateProps.y;

    const currentAnimation = get(knight, 'animations.currentAnim.name');

    // TODO: Ensure that this works as intended.

    if (updateProps.animation && updateProps.animation !== currentAnimation) {
      knight.animations.play(updateProps.animation);
    }

    if (updateProps.isDead && knight.alive) {
      const dieSound = this.getComponent('sound').getSound('die');
      knight.kill();
      grave.reset(updateProps.x, updateProps.y);
      dieSound.play();
    } else if (!updateProps.isDead && !knight.alive) {
      grave.kill();
      knight.revive();
    }

    const name = this.getComponent('text').getText('name');

    name.x = knight.x + (knight.width / 2);
    name.y = knight.y;

    // state.game.debug.body(knight);
  };

  entity.addComponent(new SpriteComponent({ knight: knightSprite, grave: graveSprite }, onSpriteComponentUpdate));

  const hitSound = state.add.audio('knight-hit', SOUND_VOLUME);
  const dieSound = state.add.audio('knight-die', SOUND_VOLUME);

  entity.addComponent(new SoundComponent({ hit: hitSound, die: dieSound }));

  const nameText = createNameTag(state, props);
  entity.addComponent(new TextComponent({ name: nameText }));

  return entity;
}

/**
 *
 * @param {Phaser.State} state
 * @param {Object} props
 * @returns {Entity}
 */
function createFlag(state, props) {
  const entity = new Entity(props);

  const flagGroup = state.getGroup('flags');

  const flagSprite = createSprite(state, flagGroup, props);

  const onSpriteComponentUpdate = function(updateProps) {
    const flag = this.getSprite('flag');

    if (updateProps.color !== this.getProp('color')) {
      flag.animations.play(updateProps.color);
    }
  };

  entity.addComponent(new SpriteComponent({ flag: flagSprite }, onSpriteComponentUpdate));

  return entity;
}

/**
 * @param {Phaser.State} state
 * @param {Object} props
 * @returns {Entity}
 */
export function createEntity(state, props) {
  switch (props.type) {
    case PLAYER:
      return createRemotePlayer(state, props);

    case FLAG:
      return createFlag(state, props);

    default:
      return null;
  }
}
<|endoftext|>


<commit_before>import React from "react";
import { connect } from "react-redux";
import { push } from "redux-router";

import Drawer from "material-ui/Drawer";
import Subheader from "material-ui/Subheader";
import { List, ListItem } from "material-ui/List";

import { ServiceManager } from "../../services/servicemanager/index";

import {
    Actions as InterfaceActions,
    ActionKeyStore as InterfaceActionKeyStore
} from "./redux/actions";

import {
    Actions as ServiceActions,
    ActionKeyStore as ServiceActionKeyStore
} from "../../services/servicemanager/redux/actions";

import style from "./styles";
import Logo from "./logo.png";

class MainMenuView extends React.Component {

    componentWillMount() {
        this.initialize();
    }

    componentWillReceiveProps(nextProps) {
        this.initialize();
    }

    initialize() {

        const {
            context,
            fetchDomainsIfNeeded,
            fetchEnterpriseIfNeeded,
            fetchL2DomainsIfNeeded,
            fetchNSGsIfNeeded,
            isConnected,
            visualizationType
        } = this.props;

        if (!isConnected)
            return;

        if (!context.enterpriseID)
            return;

        fetchEnterpriseIfNeeded(context.enterpriseID).then((enterprises) => {
            if (!enterprises)
                return;

            for (let index in enterprises) { // eslint-disable-line
                let enterprise = enterprises[index];
                fetchDomainsIfNeeded(enterprise.ID);
                fetchL2DomainsIfNeeded(enterprise.ID);

                if (visualizationType === "AAR")
                    fetchNSGsIfNeeded(enterprise.ID);
            }
        });
    }

    renderDomainsMenu() {
        const {
            context,
            domains,
            visualizationType
        } = this.props;

        if (!domains || domains.length === 0)
            return;

        const targetedDashboard = visualizationType === "VSS" ? "vssDomainFlow" : "aarDomain";
        const domainType = visualizationType === "VSS" ? "nuage_metadata.domainName" : "Domain";

        return (

                {domains.map((domain) => {

                    let queryParams = Object.assign({}, context, {domainName: domain.name, domainType: domainType});

                    return (
                        <ListItem
                            key={domain.ID}
                            primaryText={domain.name}
                            style={style.nestedItem}
                            innerDivStyle={style.innerNestedItem}
                            onTouchTap={() => { this.props.goTo(`${process.env.PUBLIC_URL}/dashboards/${targetedDashboard}`, queryParams)}}
                            leftIcon={
                                <img style={style.iconMenu} src={`${process.env.PUBLIC_URL}/icons/icon-domain.png`} alt="D" />
                            }
                        />
                    )
                })}

        )
    }

    renderL2DomainsMenu() {
        const {
            context,
            l2Domains,
            visualizationType
        } = this.props;

        if (!l2Domains || l2Domains.length === 0)
            return;

        const targetedDashboard = visualizationType === "VSS" ? "vssDomainFlow" : "aarDomain";
        const domainType = visualizationType === "VSS" ? "nuage_metadata.l2domainName" : "L2Domain";

        return (

                {l2Domains.map((l2Domain) => {

                    let queryParams = Object.assign({}, context, {domainName: l2Domain.name, domainType: domainType});

                    return (
                        <ListItem
                            key={l2Domain.ID}
                            primaryText={l2Domain.name}
                            style={style.nestedItem}
                            innerDivStyle={style.innerNestedItem}
                            onTouchTap={() => { this.props.goTo(`${process.env.PUBLIC_URL}/dashboards/${targetedDashboard}`, queryParams)}}
                            leftIcon={
                                <img style={style.iconMenu} src={`${process.env.PUBLIC_URL}/icons/icon-l2domain.png`} alt="L2D" />
                            }
                        />
                    )
                })}

        )
    }

    renderNSGsMenu() {
        const {
            context,
            nsgs,
        } = this.props;

        if (!nsgs || nsgs.length === 0)
            return;

        return (

                {nsgs.map((nsg) => {

                    let queryParams = Object.assign({}, context, {snsg: nsg.name, dnsg: nsg.name});

                    return (
                        <ListItem
                            key={nsg.ID}
                            primaryText={nsg.name}
                            style={style.nestedItem}
                            innerDivStyle={style.innerNestedItem}
                            initiallyOpen={true}
                            open={true}
                            onTouchTap={() => { this.props.goTo(`${process.env.PUBLIC_URL}/dashboards/aarNSG`, queryParams)}}
                            leftIcon={
                                <img style={style.iconMenu} src={`${process.env.PUBLIC_URL}/icons/icon-nsgateway.png`} alt="N" />
                            }
                        />
                    )
                })}

        )
    }

    renderEnterprisesMenu() {
        const {
            context,
            enterprises,
            visualizationType
        } = this.props;

        if (!enterprises)
            return;

        const targetedDashboard = visualizationType === "VSS" ? "vssEnterprise" : "aarEnterprise";

        return (

                {enterprises.map((enterprise) => {
                    return (
                        <ListItem
                            key={enterprise.ID}
                            primaryText={enterprise.name}
                            style={style.listItem}
                            onTouchTap={() => { this.props.goTo(`${process.env.PUBLIC_URL}/dashboards/${targetedDashboard}`, context)}}
                            nestedItems={[

                                    {this.renderDomainsMenu()}
                                    {this.renderL2DomainsMenu()}
                                    {this.renderNSGsMenu()}

                            ]}
                        />
                    )
                })}

        )
    }

    render() {
        const {
            visualizationType,
        } = this.props;

        return (
            <Drawer open={this.props.open} docked={false} onRequestChange={this.props.onRequestChange} width={300}>

{visualizationType} Analytics

                <Subheader style={style.subHeader}>
                    ENTERPRISES

                      <img style={style.iconSubMenu} src={`${process.env.PUBLIC_URL}/icons/icon-enterprise.png`} alt="" />

                </Subheader>

                <List>
                    {this.renderEnterprisesMenu()}
                </List>
            </Drawer>
        );
    }
}

MainMenuView.propTypes = {
  open: React.PropTypes.bool,
  onRequestChange: React.PropTypes.func
};

const mapStateToProps = (state) => {
    const queryConfiguration = {
        service: "VSD",
        query: {
            parentResource: "enterprises",
        }
    };

    const props = {
        context: state.interface.get(InterfaceActionKeyStore.CONTEXT),
        visualizationType: state.interface.get(InterfaceActionKeyStore.VISUALIZATION_TYPE),
        open: state.interface.get(InterfaceActionKeyStore.MAIN_MENU_OPENED),
        isConnected: state.services.getIn([ServiceActionKeyStore.REQUESTS, ServiceManager.getRequestID(queryConfiguration), ServiceActionKeyStore.RESULTS]),
    };

    if (props.context && props.context.enterpriseID) {
        props.enterprises = state.services.getIn([ServiceActionKeyStore.REQUESTS, "enterprises/" + props.context.enterpriseID, ServiceActionKeyStore.RESULTS]);
        props.domains = state.services.getIn([ServiceActionKeyStore.REQUESTS, "enterprises/" + props.context.enterpriseID + "/domains", ServiceActionKeyStore.RESULTS]);
        props.l2Domains = state.services.getIn([ServiceActionKeyStore.REQUESTS, "enterprises/" + props.context.enterpriseID + "/l2domains", ServiceActionKeyStore.RESULTS]);

        if (props.visualizationType === "AAR")
            props.nsgs = state.services.getIn([ServiceActionKeyStore.REQUESTS, "enterprises/" + props.context.enterpriseID + "/nsgateways", ServiceActionKeyStore.RESULTS]);
    }

    return props;

};

const actionCreators = (dispatch) => ({
    onRequestChange: () => {
      dispatch(InterfaceActions.toggleMainMenu());
    },

    setPageTitle: (aTitle) => {
      dispatch(InterfaceActions.updateTitle(aTitle));
    },

    goTo: function(link, context) {
        dispatch(push({pathname:link, query:context}));
    },

    fetchEnterpriseIfNeeded: (enterpriseID) => {
      let configuration = {
          service: "VSD",
          query: {
              parentResource: "enterprises",
              parentID: enterpriseID
          }
      }
      return dispatch(ServiceActions.fetchIfNeeded(configuration));
    },

    fetchDomainsIfNeeded: (enterpriseID) => {
        let configuration = {
            service: "VSD",
            query: {
                parentResource: "enterprises",
                parentID: enterpriseID,
            resource: "domains"
            }
        }
        return dispatch(ServiceActions.fetchIfNeeded(configuration));
    },

    fetchL2DomainsIfNeeded: (enterpriseID) => {
        let configuration = {
            service: "VSD",
            query: {
                parentResource: "enterprises",
                parentID: enterpriseID,
            resource: "l2domains"
            }
        }
        return dispatch(ServiceActions.fetchIfNeeded(configuration));
    },

    fetchNSGsIfNeeded: (enterpriseID) => {
        let configuration = {
            service: "VSD",
            query: {
                parentResource: "enterprises",
                parentID: enterpriseID,
            resource: "nsgateways"
            }
        }
        return dispatch(ServiceActions.fetchIfNeeded(configuration));
    }
});

export default connect(mapStateToProps, actionCreators)(MainMenuView);
<commit_msg>Add domainID to the context<commit_after>import React from "react";
import { connect } from "react-redux";
import { push } from "redux-router";

import Drawer from "material-ui/Drawer";
import Subheader from "material-ui/Subheader";
import { List, ListItem } from "material-ui/List";

import { ServiceManager } from "../../services/servicemanager/index";

import {
    Actions as InterfaceActions,
    ActionKeyStore as InterfaceActionKeyStore
} from "./redux/actions";

import {
    Actions as ServiceActions,
    ActionKeyStore as ServiceActionKeyStore
} from "../../services/servicemanager/redux/actions";

import style from "./styles";
import Logo from "./logo.png";

class MainMenuView extends React.Component {

    componentWillMount() {
        this.initialize();
    }

    componentWillReceiveProps(nextProps) {
        this.initialize();
    }

    initialize() {

        const {
            context,
            fetchDomainsIfNeeded,
            fetchEnterpriseIfNeeded,
            fetchL2DomainsIfNeeded,
            fetchNSGsIfNeeded,
            isConnected,
            visualizationType
        } = this.props;

        if (!isConnected)
            return;

        if (!context.enterpriseID)
            return;

        fetchEnterpriseIfNeeded(context.enterpriseID).then((enterprises) => {
            if (!enterprises)
                return;

            for (let index in enterprises) { // eslint-disable-line
                let enterprise = enterprises[index];
                fetchDomainsIfNeeded(enterprise.ID);
                fetchL2DomainsIfNeeded(enterprise.ID);

                if (visualizationType === "AAR")
                    fetchNSGsIfNeeded(enterprise.ID);
            }
        });
    }

    renderDomainsMenu() {
        const {
            context,
            domains,
            visualizationType
        } = this.props;

        if (!domains || domains.length === 0)
            return;

        const targetedDashboard = visualizationType === "VSS" ? "vssDomainFlow" : "aarDomain";
        const domainType = visualizationType === "VSS" ? "nuage_metadata.domainName" : "Domain";

        return (

                {domains.map((domain) => {

                    let queryParams = Object.assign({}, context, {domainName: domain.name, domainType: domainType, domainID: domain.ID});

                    return (
                        <ListItem
                            key={domain.ID}
                            primaryText={domain.name}
                            style={style.nestedItem}
                            innerDivStyle={style.innerNestedItem}
                            onTouchTap={() => { this.props.goTo(`${process.env.PUBLIC_URL}/dashboards/${targetedDashboard}`, queryParams)}}
                            leftIcon={
                                <img style={style.iconMenu} src={`${process.env.PUBLIC_URL}/icons/icon-domain.png`} alt="D" />
                            }
                        />
                    )
                })}

        )
    }

    renderL2DomainsMenu() {
        const {
            context,
            l2Domains,
            visualizationType
        } = this.props;

        if (!l2Domains || l2Domains.length === 0)
            return;

        const targetedDashboard = visualizationType === "VSS" ? "vssDomainFlow" : "aarDomain";
        const domainType = visualizationType === "VSS" ? "nuage_metadata.l2domainName" : "L2Domain";

        return (

                {l2Domains.map((l2Domain) => {

                    let queryParams = Object.assign({}, context, {domainName: l2Domain.name, domainType: domainType, domainID: l2Domain.ID});

                    return (
                        <ListItem
                            key={l2Domain.ID}
                            primaryText={l2Domain.name}
                            style={style.nestedItem}
                            innerDivStyle={style.innerNestedItem}
                            onTouchTap={() => { this.props.goTo(`${process.env.PUBLIC_URL}/dashboards/${targetedDashboard}`, queryParams)}}
                            leftIcon={
                                <img style={style.iconMenu} src={`${process.env.PUBLIC_URL}/icons/icon-l2domain.png`} alt="L2D" />
                            }
                        />
                    )
                })}

        )
    }

    renderNSGsMenu() {
        const {
            context,
            nsgs,
        } = this.props;

        if (!nsgs || nsgs.length === 0)
            return;

        return (

                {nsgs.map((nsg) => {

                    let queryParams = Object.assign({}, context, {snsg: nsg.name, dnsg: nsg.name});

                    return (
                        <ListItem
                            key={nsg.ID}
                            primaryText={nsg.name}
                            style={style.nestedItem}
                            innerDivStyle={style.innerNestedItem}
                            initiallyOpen={true}
                            open={true}
                            onTouchTap={() => { this.props.goTo(`${process.env.PUBLIC_URL}/dashboards/aarNSG`, queryParams)}}
                            leftIcon={
                                <img style={style.iconMenu} src={`${process.env.PUBLIC_URL}/icons/icon-nsgateway.png`} alt="N" />
                            }
                        />
                    )
                })}

        )
    }

    renderEnterprisesMenu() {
        const {
            context,
            enterprises,
            visualizationType
        } = this.props;

        if (!enterprises)
            return;

        const targetedDashboard = visualizationType === "VSS" ? "vssEnterprise" : "aarEnterprise";

        return (

                {enterprises.map((enterprise) => {
                    return (
                        <ListItem
                            key={enterprise.ID}
                            primaryText={enterprise.name}
                            style={style.listItem}
                            onTouchTap={() => { this.props.goTo(`${process.env.PUBLIC_URL}/dashboards/${targetedDashboard}`, context)}}
                            nestedItems={[

                                    {this.renderDomainsMenu()}
                                    {this.renderL2DomainsMenu()}
                                    {this.renderNSGsMenu()}

                            ]}
                        />
                    )
                })}

        )
    }

    render() {
        const {
            visualizationType,
        } = this.props;

        return (
            <Drawer open={this.props.open} docked={false} onRequestChange={this.props.onRequestChange} width={300}>

{visualizationType} Analytics

                <Subheader style={style.subHeader}>
                    ENTERPRISES

                      <img style={style.iconSubMenu} src={`${process.env.PUBLIC_URL}/icons/icon-enterprise.png`} alt="" />

                </Subheader>

                <List>
                    {this.renderEnterprisesMenu()}
                </List>
            </Drawer>
        );
    }
}

MainMenuView.propTypes = {
  open: React.PropTypes.bool,
  onRequestChange: React.PropTypes.func
};

const mapStateToProps = (state) => {
    const queryConfiguration = {
        service: "VSD",
        query: {
            parentResource: "enterprises",
        }
    };

    const props = {
        context: state.interface.get(InterfaceActionKeyStore.CONTEXT),
        visualizationType: state.interface.get(InterfaceActionKeyStore.VISUALIZATION_TYPE),
        open: state.interface.get(InterfaceActionKeyStore.MAIN_MENU_OPENED),
        isConnected: state.services.getIn([ServiceActionKeyStore.REQUESTS, ServiceManager.getRequestID(queryConfiguration), ServiceActionKeyStore.RESULTS]),
    };

    if (props.context && props.context.enterpriseID) {
        props.enterprises = state.services.getIn([ServiceActionKeyStore.REQUESTS, "enterprises/" + props.context.enterpriseID, ServiceActionKeyStore.RESULTS]);
        props.domains = state.services.getIn([ServiceActionKeyStore.REQUESTS, "enterprises/" + props.context.enterpriseID + "/domains", ServiceActionKeyStore.RESULTS]);
        props.l2Domains = state.services.getIn([ServiceActionKeyStore.REQUESTS, "enterprises/" + props.context.enterpriseID + "/l2domains", ServiceActionKeyStore.RESULTS]);

        if (props.visualizationType === "AAR")
            props.nsgs = state.services.getIn([ServiceActionKeyStore.REQUESTS, "enterprises/" + props.context.enterpriseID + "/nsgateways", ServiceActionKeyStore.RESULTS]);
    }

    return props;

};

const actionCreators = (dispatch) => ({
    onRequestChange: () => {
      dispatch(InterfaceActions.toggleMainMenu());
    },

    setPageTitle: (aTitle) => {
      dispatch(InterfaceActions.updateTitle(aTitle));
    },

    goTo: function(link, context) {
        dispatch(push({pathname:link, query:context}));
    },

    fetchEnterpriseIfNeeded: (enterpriseID) => {
      let configuration = {
          service: "VSD",
          query: {
              parentResource: "enterprises",
              parentID: enterpriseID
          }
      }
      return dispatch(ServiceActions.fetchIfNeeded(configuration));
    },

    fetchDomainsIfNeeded: (enterpriseID) => {
        let configuration = {
            service: "VSD",
            query: {
                parentResource: "enterprises",
                parentID: enterpriseID,
            resource: "domains"
            }
        }
        return dispatch(ServiceActions.fetchIfNeeded(configuration));
    },

    fetchL2DomainsIfNeeded: (enterpriseID) => {
        let configuration = {
            service: "VSD",
            query: {
                parentResource: "enterprises",
                parentID: enterpriseID,
            resource: "l2domains"
            }
        }
        return dispatch(ServiceActions.fetchIfNeeded(configuration));
    },

    fetchNSGsIfNeeded: (enterpriseID) => {
        let configuration = {
            service: "VSD",
            query: {
                parentResource: "enterprises",
                parentID: enterpriseID,
            resource: "nsgateways"
            }
        }
        return dispatch(ServiceActions.fetchIfNeeded(configuration));
    }
});

export default connect(mapStateToProps, actionCreators)(MainMenuView);
<|endoftext|>


<commit_before>const React = require('react');
const PropTypes = require('prop-types');
const Radium = require('radium');
const _uniqueId = require('lodash/uniqueId');

const StyleConstants = require('../constants/Style');

const Column = require('../components/grid/Column');
const Container = require('../components/grid/Container');
const Row = require('../components/grid/Row');

class DisplayInput extends React.Component {
  static propTypes = {
    childrenStyle: PropTypes.object,
    elementProps: PropTypes.object,
    hint: PropTypes.string,
    isFocused: PropTypes.bool,
    label: PropTypes.string,
    labelStyle: PropTypes.object,
    placeholder: PropTypes.string,
    primaryColor: PropTypes.string,
    showHint: PropTypes.bool,
    status: PropTypes.shape({
      type: PropTypes.string,
      message: PropTypes.string
    }),
    valid: PropTypes.bool
  };

  static defaultProps = {
    elementProps: {},
    isFocused: false,
    primaryColor: StyleConstants.Colors.PRIMARY,
    valid: true
  };

  componentWillMount () {
    this._labelId = _uniqueId('DI');
    this._inputId = this.props.elementProps.id || _uniqueId('DI');
  }

  _isLargeOrMediumWindowSize = () => {
    const windowSize = StyleConstants.getWindowSize();

    return windowSize === 'large' || windowSize === 'medium';
  };

  render () {
    // Input properties
    const { elementProps } = this.props;

    // Methods
    const hasChildren = !!this.props.children;
    const isLargeOrMediumWindowSize = this._isLargeOrMediumWindowSize();
    const showHint = this.props.showHint && !this.props.status && isLargeOrMediumWindowSize;

    // Column Sizes
    const twoWidthColumn = { large: 2, medium: 2, small: 0 };
    const inputColumn = showHint ? { large: 8, medium: 8, small: 12 } : { large: 10, medium: 10, small: 12 };
    const labelColumn = { large: 2, medium: 2, small: 12 };
    const statusColumn = { large: 10, medium: 10, small: 12 };

    // Styles
    const styles = this.styles();

    return (
      <Container>

          <Row>
            {this.props.label ? (
              <Column span={labelColumn}>

                  {this.props.label}

              </Column>
            ) : null }

            <Column relative={!hasChildren} span={inputColumn}>
              {hasChildren ? (

                  {this.props.children}

              ) : (

                  <input
                    {...elementProps}
                    aria-labelledby={this.props.label ? this._labelId : null}
                    id={this._inputId}
                    key='input'
                    style={styles.input}
                  />

              )}
            </Column>

            {showHint ? (
              <Column span={twoWidthColumn}>

                  {this.props.showHint && !this.props.status ? (
{this.props.hint}
) : null}

              </Column>
            ) : null }
          </Row>

        <Row>
          {this.props.status ? (
            <Column offset={twoWidthColumn} span={statusColumn} >

{this.props.status.message}

            </Column>
          ) : null}
        </Row>
      </Container>
    );
  }

  styles = () => {
    const isLargeOrMediumWindowSize = this._isLargeOrMediumWindowSize();
    const wrapperFocus = {
      borderBottom: this.props.valid ? '1px solid ' + this.props.primaryColor : '1px solid ' + StyleConstants.Colors.STRAWBERRY,
      boxShadow: 'none',
      outline: 'none'
    };

    return {
      error: {
        color: StyleConstants.Colors.STRAWBERRY
      },

      hint: {
        color: this.props.primaryColor,
        height: 20,
        paddingTop: 15,
        textAlign: 'right'
      },

      input: {
        backgroundColor: 'transparent',
        border: 0,
        color: StyleConstants.Colors.CHARCOAL,
        fontSize: StyleConstants.FontSizes.LARGE,
        lineHeight: 1,
        textAlign: 'left',
        width: '100%',

        ':focus': {
          boxShadow: 'none',
          outline: 'none'
        }
      },

      inputWrapper: {
        alignItems: 'center',
        display: 'flex',
        padding: StyleConstants.Spacing.SMALL
      },

      children: {
        alignItems: 'center',
        color: StyleConstants.Colors.CHARCOAL,
        display: 'flex',
        fontSize: StyleConstants.FontSizes.LARGE,
        height: StyleConstants.Spacing.LARGE,
        padding: StyleConstants.Spacing.SMALL
      },

      labelText: {
        alignItems: 'center',
        color: StyleConstants.Colors.CHARCOAL,
        display: 'flex',
        fontSize: StyleConstants.FontSizes.SMALL,
        fontFamily: StyleConstants.Fonts.SEMIBOLD,
        paddingBottom: isLargeOrMediumWindowSize ? StyleConstants.Spacing.MEDIUM : StyleConstants.Spacing.XSMALL,
        paddingLeft: StyleConstants.Spacing.SMALL,
        paddingRight: StyleConstants.Spacing.SMALL,
        paddingTop: isLargeOrMediumWindowSize ? StyleConstants.Spacing.MEDIUM : StyleConstants.Spacing.XSMALL,
        textAlign: 'left'
      },

      status: {
        paddingBottom: StyleConstants.Spacing.XSMALL,
        paddingLeft: isLargeOrMediumWindowSize ? StyleConstants.Spacing.SMALL : StyleConstants.Spacing.XSMALL,
        paddingRight: StyleConstants.Spacing.SMALL,
        paddingTop: StyleConstants.Spacing.XSMALL
      },

      success: {
        color: this.props.primaryColor
      },

      wrapper: Object.assign({
        borderBottom: this.props.valid ? '1px solid ' + StyleConstants.Colors.FOG : '1px solid ' + StyleConstants.Colors.STRAWBERRY,
        boxSizing: 'border-box',
        paddingBottom: StyleConstants.Spacing.XSMALL,
        marginLeft: isLargeOrMediumWindowSize ? 0 : -10,
        marginRight: isLargeOrMediumWindowSize ? 0 : -10,
        paddingTop: StyleConstants.Spacing.XSMALL,
        transition: 'all .2s ease-in',
        WebkitAppearance: 'none',
        whiteSpace: 'nowrap',

        ':focus': wrapperFocus
      }, this.props.style),

      wrapperFocus
    };
  };
}

module.exports = Radium(DisplayInput);
<commit_msg>sets default input type<commit_after>const React = require('react');
const PropTypes = require('prop-types');
const Radium = require('radium');
const _uniqueId = require('lodash/uniqueId');

const StyleConstants = require('../constants/Style');

const Column = require('../components/grid/Column');
const Container = require('../components/grid/Container');
const Row = require('../components/grid/Row');

class DisplayInput extends React.Component {
  static propTypes = {
    childrenStyle: PropTypes.object,
    elementProps: PropTypes.object,
    hint: PropTypes.string,
    isFocused: PropTypes.bool,
    label: PropTypes.string,
    labelStyle: PropTypes.object,
    placeholder: PropTypes.string,
    primaryColor: PropTypes.string,
    showHint: PropTypes.bool,
    status: PropTypes.shape({
      type: PropTypes.string,
      message: PropTypes.string
    }),
    valid: PropTypes.bool
  };

  static defaultProps = {
    elementProps: {
      type: 'text'
    },
    isFocused: false,
    primaryColor: StyleConstants.Colors.PRIMARY,
    valid: true
  };

  componentWillMount () {
    this._labelId = _uniqueId('DI');
    this._inputId = this.props.elementProps.id || _uniqueId('DI');
  }

  _isLargeOrMediumWindowSize = () => {
    const windowSize = StyleConstants.getWindowSize();

    return windowSize === 'large' || windowSize === 'medium';
  };

  render () {
    // Input properties
    const { elementProps } = this.props;

    // Methods
    const hasChildren = !!this.props.children;
    const isLargeOrMediumWindowSize = this._isLargeOrMediumWindowSize();
    const showHint = this.props.showHint && !this.props.status && isLargeOrMediumWindowSize;

    // Column Sizes
    const twoWidthColumn = { large: 2, medium: 2, small: 0 };
    const inputColumn = showHint ? { large: 8, medium: 8, small: 12 } : { large: 10, medium: 10, small: 12 };
    const labelColumn = { large: 2, medium: 2, small: 12 };
    const statusColumn = { large: 10, medium: 10, small: 12 };

    // Styles
    const styles = this.styles();

    return (
      <Container>

          <Row>
            {this.props.label ? (
              <Column span={labelColumn}>

                  {this.props.label}

              </Column>
            ) : null }

            <Column relative={!hasChildren} span={inputColumn}>
              {hasChildren ? (

                  {this.props.children}

              ) : (

                  <input
                    {...elementProps}
                    aria-labelledby={this.props.label ? this._labelId : null}
                    id={this._inputId}
                    key='input'
                    style={styles.input}
                    type='text'
                  />

              )}
            </Column>

            {showHint ? (
              <Column span={twoWidthColumn}>

                  {this.props.showHint && !this.props.status ? (
{this.props.hint}
) : null}

              </Column>
            ) : null }
          </Row>

        <Row>
          {this.props.status ? (
            <Column offset={twoWidthColumn} span={statusColumn} >

{this.props.status.message}

            </Column>
          ) : null}
        </Row>
      </Container>
    );
  }

  styles = () => {
    const isLargeOrMediumWindowSize = this._isLargeOrMediumWindowSize();
    const wrapperFocus = {
      borderBottom: this.props.valid ? '1px solid ' + this.props.primaryColor : '1px solid ' + StyleConstants.Colors.STRAWBERRY,
      boxShadow: 'none',
      outline: 'none'
    };

    return {
      error: {
        color: StyleConstants.Colors.STRAWBERRY
      },

      hint: {
        color: this.props.primaryColor,
        height: 20,
        paddingTop: 15,
        textAlign: 'right'
      },

      input: {
        backgroundColor: 'transparent',
        border: 0,
        color: StyleConstants.Colors.CHARCOAL,
        fontSize: StyleConstants.FontSizes.LARGE,
        lineHeight: 1,
        textAlign: 'left',
        width: '100%',

        ':focus': {
          boxShadow: 'none',
          outline: 'none'
        }
      },

      inputWrapper: {
        alignItems: 'center',
        display: 'flex',
        padding: StyleConstants.Spacing.SMALL
      },

      children: {
        alignItems: 'center',
        color: StyleConstants.Colors.CHARCOAL,
        display: 'flex',
        fontSize: StyleConstants.FontSizes.LARGE,
        height: StyleConstants.Spacing.LARGE,
        padding: StyleConstants.Spacing.SMALL
      },

      labelText: {
        alignItems: 'center',
        color: StyleConstants.Colors.CHARCOAL,
        display: 'flex',
        fontSize: StyleConstants.FontSizes.SMALL,
        fontFamily: StyleConstants.Fonts.SEMIBOLD,
        paddingBottom: isLargeOrMediumWindowSize ? StyleConstants.Spacing.MEDIUM : StyleConstants.Spacing.XSMALL,
        paddingLeft: StyleConstants.Spacing.SMALL,
        paddingRight: StyleConstants.Spacing.SMALL,
        paddingTop: isLargeOrMediumWindowSize ? StyleConstants.Spacing.MEDIUM : StyleConstants.Spacing.XSMALL,
        textAlign: 'left'
      },

      status: {
        paddingBottom: StyleConstants.Spacing.XSMALL,
        paddingLeft: isLargeOrMediumWindowSize ? StyleConstants.Spacing.SMALL : StyleConstants.Spacing.XSMALL,
        paddingRight: StyleConstants.Spacing.SMALL,
        paddingTop: StyleConstants.Spacing.XSMALL
      },

      success: {
        color: this.props.primaryColor
      },

      wrapper: Object.assign({
        borderBottom: this.props.valid ? '1px solid ' + StyleConstants.Colors.FOG : '1px solid ' + StyleConstants.Colors.STRAWBERRY,
        boxSizing: 'border-box',
        paddingBottom: StyleConstants.Spacing.XSMALL,
        marginLeft: isLargeOrMediumWindowSize ? 0 : -10,
        marginRight: isLargeOrMediumWindowSize ? 0 : -10,
        paddingTop: StyleConstants.Spacing.XSMALL,
        transition: 'all .2s ease-in',
        WebkitAppearance: 'none',
        whiteSpace: 'nowrap',

        ':focus': wrapperFocus
      }, this.props.style),

      wrapperFocus
    };
  };
}

module.exports = Radium(DisplayInput);
<|endoftext|>