<commit_before>define(['lodash', 'angular', 'filters/lstring', 'directives/print-smart/print-smart-checkout', './meeting-document', 'authentication',
    // Prefetch optimization
    'directives/print-smart/print-smart-checkout', 'text!directives/print-smart/print-smart-checkout.html',
    'ngDialog','directives/view-injector',
    'moment', 'moment-timezone', 'filters/moment',
    'directives/checkbox', 'text!directives/checkbox.html',
    'views/meetings/documents/meeting-document',
    'angular-cache'
], function(_, ng) {
    //'css!./agenda.css' // moved to template
    var currentUser;
    var STATISTICS = {}; 

	return ["$scope", "$route", "$http", '$q', '$location', '$rootScope', 'authentication', 'showMeeting', 'CacheFactory', function ($scope, $route, $http, $q, $location, $rootScope, authentication, showMeeting, CacheFactory) {

        var _ctrl = $scope.documentsCtrl = this;
        var meetingCode = $route.current.params.meeting.toUpperCase();
        var hardTab = false;
        var httpCache = initCache();

        var groups = {
            'outcome'        : { position: 100 , title : 'Outcomes'      },
            'official'       : { position: 200 , title : 'Official'      },
            'information'    : { position: 300 , title : 'Information'   },
            'statement'      : { position: 400 , title : 'Statements'    },
            'notification'   : { position: 500 , title : 'Notifications' },
            'other'          : { position: 600 , title : 'Other'         },
            'in-session'     : { position: 700 , title : 'Plenary'       },
            'in-session/wg1' : { position: 800 , title : 'WG I'          },
            'in-session/wg2' : { position: 900 , title : 'WG II'         }
        };

        var sections = {
            'outcome/report':         { position: 100 , title : 'Final Report'    },
            'outcome/decision':       { position: 200 , title : 'Decisions'       },
            'outcome/recommendation': { position: 200 , title : 'Recommendations' },
        };

        _ctrl.showMeeting = showMeeting===undefined ? true : !!showMeeting;
        _ctrl.sort = $location.hash() == 'agenda' ? 'agenda' : 'document';
        _ctrl.tabs = [];
        _ctrl.switchTab  = switchTab;

        $scope.$watch('documentsCtrl.sort', function(s){
            $location.hash(s=='agenda' ? 'agenda' : null);
        });

        $scope.$watch('$root.deviceSize', updateMaxTabCount);

        initAffix();
        initSecurity();
        load();

        //==============================
        //
        //==============================
        function load() {

            var meeting = $http.get('/api/v2016/meetings/'+meetingCode, { cache: httpCache, params: { f : { EVT_CD:1, reportDocument:1,  printSmart:1, insession:1, agenda:1, links:1, title:1, venueText:1, dateText:1, EVT_WEB:1, EVT_INFO_PART_URL:1, EVT_REG_NOW_YN:1, EVT_STY_CD:1 } } }).then(function(res){

                meeting = _.defaults(res.data, {
                    code: res.data.EVT_CD,
                    agenda: { items: [] },
                    printSmart : false,
                    isMontreal : /montr.al.*canada/i.test((res.data.venueText||{}).en||'')
                });

                _ctrl.noTabs  = meeting.EVT_STY_CD=='BAR';
                _ctrl.meeting = meeting;
                _ctrl.agenda  = meeting.agenda;

                if(meeting.insession) { // Quick insession fix
                    groups['in-session']    .position = 110;
                    groups['in-session/wg1'].position = 120;
                    groups['in-session/wg2'].position = 130;
                }

                return meeting;
            }).catch(function(err) {

                if(err.status!=404)
                    throw err;

                _ctrl.error = "meetingNotFound";
            });

            $q.when(httpCache.reValidate()).then(function(){

                return $http.get('/api/v2016/meetings/'+encodeURIComponent(meetingCode)+'/documents', { cache: httpCache });

            }).then(function(res) {

                _ctrl.documents = documents = _(res.data).map(normalizeDocument).filter(isDocumentVisible).sortBy(sortKey).value();

                return meeting; // force resolve

            }).then(function(meeting) {

                if(!meeting)
                    return;

                var agendaMap = _.reduce(meeting.agenda.items, function(r,v) { r[v.item] = v;  return r; }, {});

                documents.forEach(function(d) {
                    (d.agendaItems||[]).forEach(function(item) {

                        if(!agendaMap[item]) {
                            meeting.agenda.items.push(agendaMap[item] = { item: item, title: d.title.en + " (AUTO) "}); // LAZY during dev
                        }

                        agendaMap[item].documents = agendaMap[item].documents||[];
                        agendaMap[item].documents.push(d);
                    });
                });


                for(var group in groups) {

                    var docs =  _.where(documents, { displayGroup : group });

                    if(!docs.length)
                        continue;

                    var itemIds = _(docs).map('agendaItems').flatten().uniq().value();
                    var items   = _(meeting.agenda.items).filter(function(item) {
                        return ~itemIds.indexOf(item.item);
                    }).map(function(item){
                        return _.extend({}, item, { documents : _.intersection(item.documents, docs) });
                    }).value();

                    var noAgendaDocs = _(docs).difference(_(items).map('documents').flatten().value()).value();

                    var tab = injectTab(group, docs);

                    if(items.length) {
                        tab.agenda = {
                            items : items,
                            otherDocuments : noAgendaDocs
                        };
                    }
                }

                updateMaxTabCount();
                loadReport();
                loadDecisions();
                loadNotifications();
            }).then(function(){
                switchTab();
            }).catch(console.error).finally(function(){ _ctrl.loaded = true; });
        }

        //==============================
        //
        //==============================
        function normalizeDocument(d){
            
            d.status = d.status||'public';

            d.metadata = _.defaults(d.metadata||{}, { 
                printable: ['crp', 'limited', 'non-paper'].indexOf(d.nature)>=0,
                visible : d.status=='public' && !!(d.files||[]).length
            });
            
            if(d.status!='public')
                delete d.metadata.visible;

            return d;
        }

        //==============================
        //
        //==============================
        function isDocumentVisible(d){

            return d && (_ctrl.editMode || d.metadata.visible);
        }

        //==============================
        //
        //==============================
        function updateMaxTabCount(){

            var size = $rootScope.deviceSize;

                 if(size=='xs') _ctrl.maxTabCount = 2;
            else if(size=='sm') _ctrl.maxTabCount = 4;
            else if(size=='md') _ctrl.maxTabCount = 5;
            else if(size=='lg') _ctrl.maxTabCount = 6;
            else                _ctrl.maxTabCount = 7;

            if(_ctrl.tabs && _ctrl.tabs.length && (_ctrl.tabs.length - _ctrl.maxTabCount) <= 1) {
                _ctrl.maxTabCount = 999;<commit_msg>UI fix<commit_after>define(['lodash', 'angular', 'filters/lstring', 'directives/print-smart/print-smart-checkout', './meeting-document', 'authentication',
    // Prefetch optimization
    'directives/print-smart/print-smart-checkout', 'text!directives/print-smart/print-smart-checkout.html',
    'ngDialog','directives/view-injector',
    'moment', 'moment-timezone', 'filters/moment',
    'directives/checkbox', 'text!directives/checkbox.html',
    'views/meetings/documents/meeting-document',
    'angular-cache'
], function(_, ng) {
    //'css!./agenda.css' // moved to template
    var currentUser;
    var STATISTICS = {}; 

	return ["$scope", "$route", "$http", '$q', '$location', '$rootScope', 'authentication', 'showMeeting', 'CacheFactory', function ($scope, $route, $http, $q, $location, $rootScope, authentication, showMeeting, CacheFactory) {

        var _ctrl = $scope.documentsCtrl = this;
        var meetingCode = $route.current.params.meeting.toUpperCase();
        var hardTab = false;
        var httpCache = initCache();

        var groups = {
            'outcome'        : { position: 100 , title : 'Outcomes'      },
            'official'       : { position: 200 , title : 'Official'      },
            'information'    : { position: 300 , title : 'Information'   },
            'statement'      : { position: 400 , title : 'Statements'    },
            'notification'   : { position: 500 , title : 'Notifications' },
            'other'          : { position: 600 , title : 'Other'         },
            'in-session'     : { position: 700 , title : 'Plenary'       },
            'in-session/wg1' : { position: 800 , title : 'WG I'          },
            'in-session/wg2' : { position: 900 , title : 'WG II'         }
        };

        var sections = {
            'outcome/report':         { position: 100 , title : 'Final Report'    },
            'outcome/decision':       { position: 200 , title : 'Decisions'       },
            'outcome/recommendation': { position: 200 , title : 'Recommendations' },
        };

        _ctrl.showMeeting = showMeeting===undefined ? true : !!showMeeting;
        _ctrl.sort = $location.hash() == 'agenda' ? 'agenda' : 'document';
        _ctrl.tabs = [];
        _ctrl.switchTab  = switchTab;

        $scope.$watch('documentsCtrl.sort', function(s){
            $location.hash(s=='agenda' ? 'agenda' : null);
        });

        $scope.$watch('$root.deviceSize', updateMaxTabCount);

        initAffix();
        initSecurity();
        load();

        //==============================
        //
        //==============================
        function load() {

            var meeting = $http.get('/api/v2016/meetings/'+meetingCode, { cache: httpCache, params: { f : { EVT_CD:1, reportDocument:1,  printSmart:1, insession:1, agenda:1, links:1, title:1, venueText:1, dateText:1, EVT_WEB:1, EVT_INFO_PART_URL:1, EVT_REG_NOW_YN:1, EVT_STY_CD:1 } } }).then(function(res){

                meeting = _.defaults(res.data, {
                    code: res.data.EVT_CD,
                    agenda: { items: [] },
                    printSmart : false,
                    isMontreal : /montr.al.*canada/i.test((res.data.venueText||{}).en||'')
                });

                meeting.printSmart=true;

                _ctrl.noTabs  = meeting.EVT_STY_CD=='BAR';
                _ctrl.meeting = meeting;
                _ctrl.agenda  = meeting.agenda;

                if(meeting.insession) { // Quick insession fix
                    groups['in-session']    .position = 110;
                    groups['in-session/wg1'].position = 120;
                    groups['in-session/wg2'].position = 130;
                }

                return meeting;
            }).catch(function(err) {

                if(err.status!=404)
                    throw err;

                _ctrl.error = "meetingNotFound";
            });

            $q.when(httpCache.reValidate()).then(function(){

                return $http.get('/api/v2016/meetings/'+encodeURIComponent(meetingCode)+'/documents', { cache: httpCache });

            }).then(function(res) {

                _ctrl.documents = documents = _(res.data).map(normalizeDocument).filter(isDocumentVisible).sortBy(sortKey).value();

                return meeting; // force resolve

            }).then(function(meeting) {

                if(!meeting)
                    return;

                var agendaMap = _.reduce(meeting.agenda.items, function(r,v) { r[v.item] = v;  return r; }, {});

                documents.forEach(function(d) {
                    (d.agendaItems||[]).forEach(function(item) {

                        if(!agendaMap[item]) {
                            meeting.agenda.items.push(agendaMap[item] = { item: item, title: d.title.en + " (AUTO) "}); // LAZY during dev
                        }

                        agendaMap[item].documents = agendaMap[item].documents||[];
                        agendaMap[item].documents.push(d);
                    });
                });


                for(var group in groups) {

                    var docs =  _.where(documents, { displayGroup : group });

                    if(!docs.length)
                        continue;

                    var itemIds = _(docs).map('agendaItems').flatten().uniq().value();
                    var items   = _(meeting.agenda.items).filter(function(item) {
                        return ~itemIds.indexOf(item.item);
                    }).map(function(item){
                        return _.extend({}, item, { documents : _.intersection(item.documents, docs) });
                    }).value();

                    var noAgendaDocs = _(docs).difference(_(items).map('documents').flatten().value()).value();

                    var tab = injectTab(group, docs);

                    if(items.length) {
                        tab.agenda = {
                            items : items,
                            otherDocuments : noAgendaDocs
                        };
                    }
                }

                updateMaxTabCount();
                loadReport();
                loadDecisions();
                loadNotifications();
            }).then(function(){
                switchTab();
            }).catch(console.error).finally(function(){ _ctrl.loaded = true; });
        }

        //==============================
        //
        //==============================
        function normalizeDocument(d){
            
            d.status = d.status||'public';

            d.metadata = _.defaults(d.metadata||{}, { 
                printable: ['crp', 'limited', 'non-paper'].indexOf(d.nature)>=0,
                visible : d.status=='public' && !!(d.files||[]).length
            });
            
            d.metadata.printable = true;
            if(d.status!='public')
                delete d.metadata.visible;

            return d;
        }

        //==============================
        //
        //==============================
        function isDocumentVisible(d){

            return d && (_ctrl.editMode || d.metadata.visible);
        }

        //==============================
        //
        //==============================
        function updateMaxTabCount(){

            var size = $rootScope.deviceSize;

                 if(size=='xs') _ctrl.maxTabCount = 2;
            else if(size=='sm') _ctrl.maxTabCount = 4;
            else if(size=='md') _ctrl.maxTabCount = 5;
            else if(size=='lg') _ctrl.maxTabCount = 6;
            else                _ctrl.maxTabCount = 7;

            if(_ctrl.tabs && _ctrl.tabs.length && (_ctrl.tabs.length - _ctrl.maxTabCount) <= 1) {
                _ctrl.maxTabCount = 999;
{'fraction_non_alphanumeric': 0.1736725663716814, 'fraction_numerical': 0.010801665799062988, 'mean_word_length': 1.640721649484536, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1775739', 'n_tokens_mistral': 4477, 'n_tokens_neox': 4039, 'n_words': 703}