<commit_before>import m from 'mithril';
import _ from 'underscore';
import { catarse, commonProject } from '../api';
import models from '../models';
import h from '../h';
import projectDataTable from './project-data-table';
import projectDataChart from './project-data-chart';
import UserFollowBtn from './user-follow-btn';
import userVM from '../vms/user-vm';
import projectVM from '../vms/project-vm';

const projectContributions = {
    controller(args) {
        const contributionsPerDay = m.prop([]),
            listVM = projectVM.isSubscription(args.project()) ? commonProject.paginationVM(models.projectSubscriber) : catarse.paginationVM(models.contributor),
            filterStats = catarse.filtersVM({
                project_id: 'eq'
            }),
            filterVM = catarse.filtersVM({
                project_id: 'eq'
            }),
            groupedCollection = (collection = []) => {
                let grouped = [
                        []
                    ],
                    group = 0;

                _.map(collection, (item, index) => {
                    if (grouped[group].length >= 3) {
                        group += 1;
                        grouped[group] = [];
                    }

                    grouped[group].push(item);
                });

                return grouped;
            },
            contributionsStats = m.prop({});

        filterVM.project_id(projectVM.isSubscription(args.project()) ? args.project().common_id : args.project().project_id);
        filterStats.project_id(args.project().project_id);

        if (!listVM.collection().length) {
            listVM.firstPage(filterVM.parameters());
        }
        // TODO: Abstract table fetch and contruction logic to contributions-vm to avoid insights.js duplicated code.
        const lContributionsPerDay = catarse.loader(models.projectContributionsPerDay.getRowOptions(filterStats.parameters()));
        lContributionsPerDay.load().then(contributionsPerDay);

        const contributionsPerLocationTable = [
            ['Estado', 'Apoios', 'R$ apoiados (% do total)']
        ];
        const buildPerLocationTable = contributions => (!_.isEmpty(contributions)) ? _.map(_.first(contributions).source, (contribution) => {
            const column = [];

            column.push(contribution.state_acronym || 'Outro/other');
            column.push(contribution.total_contributions);
            column.push([contribution.total_contributed, [ // Adding row with custom comparator => read project-data-table description
                m(`input[type="hidden"][value="${contribution.total_contributed}"`),
                'R$ ',
                h.formatNumber(contribution.total_contributed, 2, 3),
                m('span.w-hidden-small.w-hidden-tiny', ` (${contribution.total_on_percentage.toFixed(2)}%)`)
            ]]);
            return contributionsPerLocationTable.push(column);
        }) : [];

        const lContributionsPerLocation = catarse.loader(models.projectContributionsPerLocation.getRowOptions(filterStats.parameters()));
        lContributionsPerLocation.load().then(buildPerLocationTable);

        const lContributionsStats = catarse.loader(models.projectContributiorsStat.getRowOptions(filterStats.parameters()));
        lContributionsStats.load().then(data => contributionsStats(_.first(data)));

        return {
            listVM,
            filterVM,
            groupedCollection,
            lContributionsStats,
            contributionsPerLocationTable,
            lContributionsPerLocation,
            contributionsPerDay,
            lContributionsPerDay,
            contributionsStats
        };
    },
    view(ctrl, args) {
        const list = ctrl.listVM,
            stats = projectVM.isSubscription(args.project()) ? args.subscriptionData() : ctrl.contributionsStats(),
            groupedCollection = ctrl.groupedCollection(list.collection());

        return m('#project_contributions', m('#contributions_top', [
            m('.section.w-section',
                    m('.w-container',
                        m('.w-row', ctrl.lContributionsStats() ? h.loader() : !_.isEmpty(stats) ? [
                            m('.u-marginbottom-20.u-text-center-small-only.w-col.w-col-6', [
                                m('.fontsize-megajumbo',
                                    projectVM.isSubscription(args.project()) ? stats.total_subscriptions : stats.total
                                ),
                                m('.fontsize-large',
                                    'pessoas apoiam este projeto'
                                )
                            ]),
                            m('.w-col.w-col-6',
                                m('.card.card-terciary.u-radius',
                                    m('.w-row', [
                                        m('.u-marginbottom-20.w-col.w-sub-col.w-col-6.w-col-small-6', [
                                            m('.fontweight-semibold.u-marginbottom-10',
                                                'Apoiadores novos'
                                            ),
                                            m('.fontsize-largest.u-marginbottom-10',
                                                `${Math.floor(stats.new_percent)}%`
                                            ),
                                            m('.fontsize-smallest',
                                                'apoiadores que nunca tinham apoiado um projeto no Catarse'
                                            )
                                        ]),
                                        m('.w-col.w-sub-col.w-col-6.w-col-small-6', [
                                            m('.divider.u-marginbottom-20.w-hidden-main.w-hidden-medium.w-hidden-small'),
                                            m('.fontweight-semibold.u-marginbottom-10',
                                                'Apoiadores recorrentes'
                                            ),
                                            m('.fontsize-largest.u-marginbottom-10',
                                                `${Math.ceil(stats.returning_percent)}%`
                                            ),
                                            m('.fontsize-smallest',
                                                'apoiadores que já tinham apoiado um projeto no Catarse'
                                            )
                                        ])
                                    ])
                                )
                            )
                        ] : '')
                    )
                ),
            m('.divider.w-section'),
            m('.section.w-section', m('.w-container', [
                m('.fontsize-large.fontweight-semibold.u-marginbottom-40.u-text-center', 'Apoiadores'),
                m('.project-contributions.w-clearfix', _.map(groupedCollection, (group, idx) => m('.w-row', _.map(group, contribution => m('.project-contribution-item.w-col.w-col-4', [
                        // here new card
                    m('.card.card-backer.u-marginbottom-20.u-radius.u-text-center', [
                        m(`a[href="/users/${contribution.user_id}"][style="display: block;"]`, {
                            onclick: h.analytics.event({
                                cat: 'project_view',
                                act: 'project_backer_link',
                                lbl: contribution.user_id,
                                project: args.project()
                            })
                        }, [
                            m(`img.thumb.u-marginbottom-10.u-round[src="${!_.isEmpty(contribution.data.profile_img_thumbnail) ? contribution.data.profile_img_thumbnail : '/assets/catarse_bootstrap/user.jpg'}"]`)
                        ]),
                        m(`a.fontsize-base.fontweight-semibold.lineheigh-tight.link-hidden-dark[href="/users/${contribution.user_id}"]`, {
                            onclick: h.analytics.event({
                                cat: 'project_view',
                                act: 'project_backer_link',
                                lbl: contribution.user_id,
                                project: args.project()
                            })
                        }, userVM.displayName(contribution.data)),
                        m('.fontcolor-secondary.fontsize-smallest.u-marginbottom-10', `${h.selfOrEmpty(contribution.data.city)}, ${h.selfOrEmpty(contribution.data.state)}`),
                        m('.fontsize-smaller', [
                            m('span.fontweight-semibold', contribution.data.total_contributed_projects), ' apoiados  |  ',
                            m('span.fontweight-semibold', contribution.data.total_published_projects), ' criado'
                        ]),
                        m('.btn-bottom-card.w-row', [
                            m('.w-col.w-col-3.w-col-small-4.w-col-tiny-3'),
                            m('.w-col.w-col-6.w-col-small-4.w-col-tiny-6', [<commit_msg>sub copy<commit_after>import m from 'mithril';
import _ from 'underscore';
import I18n from 'i18n-js';
import { catarse, commonProject } from '../api';
import models from '../models';
import h from '../h';
import projectDataTable from './project-data-table';
import projectDataChart from './project-data-chart';
import UserFollowBtn from './user-follow-btn';
import userVM from '../vms/user-vm';
import projectVM from '../vms/project-vm';

const I18nScope = _.partial(h.i18nScope, 'projects.contributions');

const projectContributions = {
    controller(args) {
        const contributionsPerDay = m.prop([]),
            listVM = projectVM.isSubscription(args.project()) ? commonProject.paginationVM(models.projectSubscriber) : catarse.paginationVM(models.contributor),
            filterStats = catarse.filtersVM({
                project_id: 'eq'
            }),
            filterVM = catarse.filtersVM({
                project_id: 'eq'
            }),
            groupedCollection = (collection = []) => {
                let grouped = [
                        []
                    ],
                    group = 0;

                _.map(collection, (item, index) => {
                    if (grouped[group].length >= 3) {
                        group += 1;
                        grouped[group] = [];
                    }

                    grouped[group].push(item);
                });

                return grouped;
            },
            contributionsStats = m.prop({});

        filterVM.project_id(projectVM.isSubscription(args.project()) ? args.project().common_id : args.project().project_id);
        filterStats.project_id(args.project().project_id);

        if (!listVM.collection().length) {
            listVM.firstPage(filterVM.parameters());
        }
        // TODO: Abstract table fetch and contruction logic to contributions-vm to avoid insights.js duplicated code.
        const lContributionsPerDay = catarse.loader(models.projectContributionsPerDay.getRowOptions(filterStats.parameters()));
        lContributionsPerDay.load().then(contributionsPerDay);

        const contributionsPerLocationTable = [
            ['Estado', 'Apoios', 'R$ apoiados (% do total)']
        ];
        const buildPerLocationTable = contributions => (!_.isEmpty(contributions)) ? _.map(_.first(contributions).source, (contribution) => {
            const column = [];

            column.push(contribution.state_acronym || 'Outro/other');
            column.push(contribution.total_contributions);
            column.push([contribution.total_contributed, [ // Adding row with custom comparator => read project-data-table description
                m(`input[type="hidden"][value="${contribution.total_contributed}"`),
                'R$ ',
                h.formatNumber(contribution.total_contributed, 2, 3),
                m('span.w-hidden-small.w-hidden-tiny', ` (${contribution.total_on_percentage.toFixed(2)}%)`)
            ]]);
            return contributionsPerLocationTable.push(column);
        }) : [];

        const lContributionsPerLocation = catarse.loader(models.projectContributionsPerLocation.getRowOptions(filterStats.parameters()));
        lContributionsPerLocation.load().then(buildPerLocationTable);

        const lContributionsStats = catarse.loader(models.projectContributiorsStat.getRowOptions(filterStats.parameters()));
        lContributionsStats.load().then(data => contributionsStats(_.first(data)));

        return {
            listVM,
            filterVM,
            groupedCollection,
            lContributionsStats,
            contributionsPerLocationTable,
            lContributionsPerLocation,
            contributionsPerDay,
            lContributionsPerDay,
            contributionsStats
        };
    },
    view(ctrl, args) {
        const list = ctrl.listVM,
            stats = projectVM.isSubscription(args.project()) ? args.subscriptionData() : ctrl.contributionsStats(),
            groupedCollection = ctrl.groupedCollection(list.collection());

        return m('#project_contributions', m('#contributions_top', [
            m('.section.w-section',
                    m('.w-container',
                        m('.w-row', ctrl.lContributionsStats() ? h.loader() : !_.isEmpty(stats) ? [
                            m('.u-marginbottom-20.u-text-center-small-only.w-col.w-col-6', [
                                m('.fontsize-megajumbo',
                                    projectVM.isSubscription(args.project()) ? stats.total_subscriptions : stats.total
                                ),
                                m('.fontsize-large',
                                    I18n.t(`people_back.${args.project().mode}`, I18nScope())
                                )
                            ]),
                            m('.w-col.w-col-6',
                                m('.card.card-terciary.u-radius',
                                    m('.w-row', [
                                        m('.u-marginbottom-20.w-col.w-sub-col.w-col-6.w-col-small-6', [
                                            m('.fontweight-semibold.u-marginbottom-10',
                                                I18n.t(`new_backers.${args.project().mode}`, I18nScope())
                                            ),
                                            m('.fontsize-largest.u-marginbottom-10',
                                                `${Math.floor(stats.new_percent)}%`
                                            ),
                                            m('.fontsize-smallest',
                                                I18n.t(`new_backers_explanation.${args.project().mode}`, I18nScope())
                                            )
                                        ]),
                                        m('.w-col.w-sub-col.w-col-6.w-col-small-6', [
                                            m('.divider.u-marginbottom-20.w-hidden-main.w-hidden-medium.w-hidden-small'),
                                            m('.fontweight-semibold.u-marginbottom-10',
                                                I18n.t(`recurring_backers.${args.project().mode}`, I18nScope())
                                            ),
                                            m('.fontsize-largest.u-marginbottom-10',
                                                `${Math.ceil(stats.returning_percent)}%`
                                            ),
                                            m('.fontsize-smallest',
                                                I18n.t(`recurring_backers_explanation.${args.project().mode}`, I18nScope())
                                            )
                                        ])
                                    ])
                                )
                            )
                        ] : '')
                    )
                ),
            m('.divider.w-section'),
            m('.section.w-section', m('.w-container', [
                m('.fontsize-large.fontweight-semibold.u-marginbottom-40.u-text-center', I18n.t(`backers.${args.project().mode}`, I18nScope())),
                m('.project-contributions.w-clearfix', _.map(groupedCollection, (group, idx) => m('.w-row', _.map(group, contribution => m('.project-contribution-item.w-col.w-col-4', [
                        // here new card
                    m('.card.card-backer.u-marginbottom-20.u-radius.u-text-center', [
                        m(`a[href="/users/${contribution.user_id}"][style="display: block;"]`, {
                            onclick: h.analytics.event({
                                cat: 'project_view',
                                act: 'project_backer_link',
                                lbl: contribution.user_id,
                                project: args.project()
                            })
                        }, [
                            m(`img.thumb.u-marginbottom-10.u-round[src="${!_.isEmpty(contribution.data.profile_img_thumbnail) ? contribution.data.profile_img_thumbnail : '/assets/catarse_bootstrap/user.jpg'}"]`)
                        ]),
                        m(`a.fontsize-base.fontweight-semibold.lineheigh-tight.link-hidden-dark[href="/users/${contribution.user_id}"]`, {
                            onclick: h.analytics.event({
                                cat: 'project_view',
                                act: 'project_backer_link',
                                lbl: contribution.user_id,
                                project: args.project()
                            })
                        }, userVM.displayName(contribution.data)),
                        m('.fontcolor-secondary.fontsize-smallest.u-marginbottom-10', `${h.selfOrEmpty(contribution.data.city)}, ${h.selfOrEmpty(contribution.data.state)}`),
                        m('.fontsize-smaller', [
                            m('span.fontweight-semibold', contribution.data.total_contributed_projects), ' apoiados  |  ',
                            m('span.fontweight-semibold', contribution.data.total_published_projects), ' criado'
                        ]),
                        m('.btn-bottom-card.w-row', [
                            m('.w-col.w-col-3.w-col-small-4.w-col-tiny-3'),
                            m('.w-col.w-col-6.w-col-small-4.w-col-tiny-6', [
{'fraction_non_alphanumeric': 0.12455361973812358, 'fraction_numerical': 0.006168163618655989, 'mean_word_length': 1.2877831414779057, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 21, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 92, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1660874', 'n_tokens_mistral': 4661, 'n_tokens_neox': 4398, 'n_words': 558}