<commit_before>import m from 'mithril';
import _ from 'underscore';
import { catarse } from '../api';
import h from '../h';
import models from '../models';
import adminInputAction from './admin-input-action';
import adminRadioAction from './admin-radio-action';
import adminExternalAction from './admin-external-action';
import projectVM from '../vms/project-vm';

const adminProjectDetail = {
    controller(args) {
        let bankl;
        const project_id = args.item.project_id;
        const loadBank = () => {
            const model = models.projectAccount,
                opts = model.getRowOptions(h.idVM.id(project_id).parameters()),
                project = m.prop({});

            bankl = catarse.loaderWithToken(opts);

            if (project_id) {
                bankl.load().then(_.compose(project, _.first));
            }

            return project;
        };
        let l;
        const loadUser = () => {
            const model = models.userDetail,
                user_id = args.item.user_id,
                opts = model.getRowOptions(h.idVM.id(user_id).parameters()),
                user = m.prop({});

            l = catarse.loaderWithToken(opts);

            if (user_id) {
                l.load().then(_.compose(user, _.first));
            }

            return user;
        };

        const changeUserAction = {
            toggler: h.toggleProp(false, true),
            submit: newValue => () => {
                console.log('new value', newValue);
                changeUserAction.complete(false);
                projectVM
                    .updateProject(project_id, { user_id: newValue })
                    .then(() => {
                        changeUserAction.complete(true);
                        changeUserAction.success(true);
                        changeUserAction.error(false);
                    })
                    .catch(() => {
                        changeUserAction.complete(true);
                        changeUserAction.success(true);
                        changeUserAction.error(true);
                    });
                return false;
            },
            complete: m.prop(false),
            error: m.prop(false),
            success: m.prop(false),
            newValue: m.prop('')
        };

        const contributionReport = {
            toggler: h.toggleProp(false, true)
        };

        const actionUnload = action => () => {
            action.complete(false);
            action.error(false);
            action.success(false);
            action.newValue('');
        };

        return {
            user: loadUser(),
            bankAccount: loadBank(),
            actions: {
                changeUserAction
            },
            actionUnload
        };
    },
    view(ctrl, args) {
        const actions = ctrl.actions,
            item = args.item,
            user = ctrl.user(),
            bankAccount = ctrl.bankAccount(),
            userAddress = user.address || {};

        return m('#admin-contribution-detail-box', [
            m('.divider.u-margintop-20.u-marginbottom-20'),
            m('.w-row.u-marginbottom-30', [
                m('.w-col.w-col-2', [
                    m('button.btn.btn-small.btn-terciary', {
                        onclick: ctrl.actions.changeUserAction.toggler.toggle
                    }, 'Trocar realizador'),
                    (ctrl.actions.changeUserAction.toggler() ? 
                        m('.dropdown-list.card.u-radius.dropdown-list-medium.zindex-10', {
                            config: ctrl.actionUnload(ctrl.actions.changeUserAction)
                        }, [
                            m('form.w-form', {
                                onsubmit: ctrl.actions.changeUserAction.submit
                            }, (!ctrl.actions.changeUserAction.complete()) ? [
                                m('label', 'Id do novo realizador:'),
                                m('input.w-input.text-field[type="tel"][placeholder="ex: 239049"]', {
                                    onchange: m.withAttr('value', ctrl.actions.changeUserAction.newValue),
                                    value: ctrl.actions.changeUserAction.newValue()
                                }),
                                m('input.w-button.btn.btn-small[type="submit"][value="Transferir"]', {
                                    onclick: ctrl.actions.changeUserAction.submit(ctrl.actions.changeUserAction.newValue())
                                })
                            ] : (!ctrl.actions.changeUserAction.error()) ? [
                                m('.w-form-done[style="display:block;"]', [
                                    m('p', 'Usuário transferido com sucesso')
                                ])
                            ] : [
                                m('.w-form-error[style="display:block;"]', [
                                    m('p', 'Houve um problema na requisição. Verifique se o usuário que vai receber o projeto possui dados válidos.')
                                ])
                            ])
                        ]) : '')
                ]),
                m('.w-col.w-col-2', [
                    (item.mode === 'sub' ?
                        m('a.btn.btn-small.btn-terciary', { href: `/projects/${item.project_id}/subscriptions_report` }, 'Base de assinantes')
                        : m('a.btn.btn-small.btn-terciary', { href: `/projects/${item.project_id}/contributions_report` }, 'Relatório de apoios'))
                ])
            ]),<commit_msg>add action to admin revert a sub project or finish<commit_after>import m from 'mithril';
import _ from 'underscore';
import {
    catarse,
    commonAnalytics
} from '../api';
import h from '../h';
import models from '../models';
import adminInputAction from './admin-input-action';
import adminRadioAction from './admin-radio-action';
import adminExternalAction from './admin-external-action';
import projectVM from '../vms/project-vm';

const adminProjectDetail = {
    controller(args) {
        let bankl;
        const currentItem = m.prop(args.item);
        const project_id = args.item.project_id;
        const loadBank = () => {
            const model = models.projectAccount,
                opts = model.getRowOptions(h.idVM.id(project_id).parameters()),
                project = m.prop({});

            bankl = catarse.loaderWithToken(opts);

            if (project_id) {
                bankl.load().then(_.compose(project, _.first));
            }

            return project;
        };
        let l;
        const loadUser = () => {
            const model = models.userDetail,
                user_id = args.item.user_id,
                opts = model.getRowOptions(h.idVM.id(user_id).parameters()),
                user = m.prop({});

            l = catarse.loaderWithToken(opts);

            if (user_id) {
                l.load().then(_.compose(user, _.first));
            }

            return user;
        };

        const changeUserAction = {
            toggler: h.toggleProp(false, true),
            submit: newValue => () => {
                changeUserAction.complete(false);
                projectVM
                    .updateProject(project_id, { user_id: newValue })
                    .then(() => {
                        changeUserAction.complete(true);
                        changeUserAction.success(true);
                        changeUserAction.error(false);
                    })
                    .catch(() => {
                        changeUserAction.complete(true);
                        changeUserAction.success(true);
                        changeUserAction.error(true);
                    });
                return false;
            },
            complete: m.prop(false),
            error: m.prop(false),
            success: m.prop(false),
            newValue: m.prop('')
        };

        const contributionReport = {
            toggler: h.toggleProp(false, true)
        };

        const actionUnload = action => () => {
            action.complete(false);
            action.error(false);
            action.success(false);
            action.newValue('');
        };

        const projectSubscriberInfo = m.prop();
        const projectRevert = {
            toggler: h.toggleProp(false, true),
            loading: h.toggleProp(false, true),
            submit: () => {
                projectRevert.loading.toggle();
                m.redraw();
                m.request({
                    method: 'PUT',
                    config: h.setCsrfToken,
                    url: `/admin/projects/${project_id}/revert_or_finish`
                }).then((data) => {
                    console.log(data);
                    catarse.loaderWithToken(
                        models.adminProject.getRowOptions({project_id: `eq.${project_id}`})
                    ).load().then((response) => {
                        currentItem(response);
                        projectRevert.loading.toggle();
                        projectRevert.toggler.toggle();
                    })
                });
            }
        };

        if (args.item.mode === 'sub') {
            commonAnalytics.loaderWithToken(models.projectSubscribersInfo.postOptions({
                id: args.item.common_id
            })).load().then(projectSubscriberInfo);
        }

        return {
            user: loadUser(),
            bankAccount: loadBank(),
            subscriberInfo: projectSubscriberInfo,
            actions: {
                changeUserAction,
                projectRevert
            },
            currentItem,
            actionUnload
        };
    },
    view(ctrl, args) {
        const actions = ctrl.actions,
            item = ctrl.currentItem(),
            user = ctrl.user(),
            bankAccount = ctrl.bankAccount(),
            userAddress = user.address || {},
            subscriberInfo = ctrl.subscriberInfo(),
            totalSubscriptions = subscriberInfo ? subscriberInfo.total_subscriptions : 0;

        return m('#admin-contribution-detail-box', [
            m('.divider.u-margintop-20.u-marginbottom-20'),
            m('.w-row.u-marginbottom-30', [
                m('.w-col.w-col-2', [
                    m('button.btn.btn-small.btn-terciary', {
                        onclick: ctrl.actions.changeUserAction.toggler.toggle
                    }, 'Trocar realizador'),
                    (ctrl.actions.changeUserAction.toggler() ? 
                        m('.dropdown-list.card.u-radius.dropdown-list-medium.zindex-10', {
                            config: ctrl.actionUnload(ctrl.actions.changeUserAction)
                        }, [
                            m('form.w-form', {
                                onsubmit: ctrl.actions.changeUserAction.submit
                            }, (!ctrl.actions.changeUserAction.complete()) ? [
                                m('label', 'Id do novo realizador:'),
                                m('input.w-input.text-field[type="tel"][placeholder="ex: 239049"]', {
                                    onchange: m.withAttr('value', ctrl.actions.changeUserAction.newValue),
                                    value: ctrl.actions.changeUserAction.newValue()
                                }),
                                m('input.w-button.btn.btn-small[type="submit"][value="Transferir"]', {
                                    onclick: ctrl.actions.changeUserAction.submit(ctrl.actions.changeUserAction.newValue())
                                })
                            ] : (!ctrl.actions.changeUserAction.error()) ? [
                                m('.w-form-done[style="display:block;"]', [
                                    m('p', 'Usuário transferido com sucesso')
                                ])
                            ] : [
                                m('.w-form-error[style="display:block;"]', [
                                    m('p', 'Houve um problema na requisição. Verifique se o usuário que vai receber o projeto possui dados válidos.')
                                ])
                            ])
                        ]) : '')
                ]),
                m('.w-col.w-col-2', [
                    (item.mode === 'sub' ?
                        m('a.btn.btn-small.btn-terciary', { href: `/projects/${item.project_id}/subscriptions_report` }, 'Base de assinantes')
                        : m('a.btn.btn-small.btn-terciary', { href: `/projects/${item.project_id}/contributions_report` }, 'Relatório de apoios'))
                ]),
                (item.mode === 'sub' && item.state === 'online' ?
                    m('.w-col.w-col-3', [
                        m('button.btn.btn-small.btn-terciary', {
                            onclick: ctrl.actions.projectRevert.toggler.toggle
                        }, (totalSubscriptions > 0 ? 'Encerrar projeto' : 'Virar projeto para Draft')),
                        (ctrl.actions.projectRevert.toggler() ? 
                            (ctrl.actions.projectRevert.loading() ? h.loader()
                                : m('.dropdown-list.card.u-radius.dropdown-list-medium.zindex-10', [
                                    m('form.w-form', {
                                        onsubmit: ctrl.actions.projectRevert.submit
                                    }, [
                                        m('label', (totalSubscriptions > 0 ? 'Ao encerrar esse projeto, ele será convertido para o status FINALIZADO (Flex) e suas assinaturas serão transformadas em CANCELADAS. Tem certeza que deseja encerrar esse projeto?' : 'Tem certeza que deseja transformar esse projeto em Draft?')),
                                        m('input.w-button.btn.btn-small[type="submit"]', {
                                            value: (totalSubscriptions > 0 ? 'Encerrar projeto' : 'Virar projeto para Draft' )
                                        })
                                    ])
                                ])) : '')
                    ]) : '')
            ]),
{'fraction_non_alphanumeric': 0.12360107663975067, 'fraction_numerical': 0.0027624309392265192, 'mean_word_length': 1.2428911834789516, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 25, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 21, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1052117', 'n_tokens_mistral': 3674, 'n_tokens_neox': 3476, 'n_words': 570}