article.service.js 13.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
(function() {
  'use strict';

  angular
  .module('dialoga')
  .factory('ArticleService', ArticleService);

  /** @ngInject */
  function ArticleService($http, $q, $rootScope, API, UtilService, Slug, GUID, $log) {
    $log.debug('ArticleService');

    var service = {
      apiArticles: $rootScope.basePath + '/api/v1/articles/',
      apiCommunities: $rootScope.basePath + '/api/v1/communities/',
      apiProposals: $rootScope.basePath + '/api/v1/proposals_discussion_plugin/',
      apiSearch: $rootScope.basePath + '/api/v1/search/',
      getArticleById: getArticleById,
      getArticleBySlug: getArticleBySlug,
      getArtcilesByParentId: getArtcilesByParentId,
      getCategories: getCategories,
      getCategoryBySlug: getCategoryBySlug,
      getTopics: getTopics,
      getTopicById: getTopicById,
      getProposals: getProposals,
      getProposalById: getProposalById,
      getProposalsByTopicId: getProposalsByTopicId,
      getProposalsByTopicIdRanked: getProposalsByTopicIdRanked,
      getResponseByProposalId: getResponseByProposalId,
      createProposal: createProposal,
      voteProposal: voteProposal,
      getEvents: getEvents,
      subscribeToEvent: subscribeToEvent,
      searchTopics: searchTopics,
      searchProposals: searchProposals,
      sendContactForm: sendContactForm,
      getRankedProposalsByTopicId: getRankedProposalsByTopicId
    };

    return service;

    function _getArticleById (articleId, params, cbSuccess, cbError) {

      var url = service.apiArticles + articleId;
      var paramsExtended = angular.extend({}, params);

      UtilService.get(url, {params: paramsExtended})
      .then(function(data){
        cbSuccess(data);
      }).catch(function(error){
        cbError(error);
      });
    }

    function getArticleById (articleId, params, cbSuccess, cbError) {
      _getArticleById(articleId, params, cbSuccess, cbError);
    }

    function getArticleBySlug (/*slug, params, cbSuccess, cbError*/) {
      throw { name: 'NotImplementedYet', message: 'The service "getArticleBySlug" is not implemented yet.'};
    }

    function getArtcilesByParentId (parentId, params) {
      // Ex.: /api/v1/articles/103358/children?fields=

      var url = service.apiArticles + parentId + '/children';
      var paramsExtended = angular.extend({
        'fields[]': ['id', 'slug', 'title', 'body']
      }, params);

      return UtilService.get(url, {params: paramsExtended});
    }

    function getCategories (articleId, params, cbSuccess, cbError) {
      // Ex.: /api/v1/articles/103358?fields=

      var url = service.apiArticles + articleId;
      var paramsExtended = angular.extend({
        'fields[]': ['id', 'categories']
      }, params);

      UtilService.get(url, {params: paramsExtended})
      .then(function(data){
        cbSuccess(data);
      }).catch(function(error){
        cbError(error);
      });
    }

    function getCategoryBySlug (/*slug, params, cbSuccess, cbError*/) {
      throw { name: 'NotImplementedYet', message: 'The service "getArticleBySlug" is not implemented yet.'};
    }

    function getTopics (params, cbSuccess, cbError) {
      // Ex.: /api/v1/articles/103358/children?fields=
      getTopicById(API.articleId.home, params, cbSuccess, cbError);
    }

    function getTopicById (topicId, params, cbSuccess, cbError) {
      // Ex.: /api/v1/articles/103358/children?fields=

      var url = service.apiArticles + topicId + '/children';
      var paramsExtended = angular.extend({
        'fields[]': ['id', 'categories']
        // 'fields[]': ['id', 'title', 'body', 'slug', 'abstract', 'categories', 'setting', 'children_count', 'hits']
      }, params);

      UtilService.get(url, {params: paramsExtended})
      .then(function(data){
        cbSuccess(data);
      }).catch(function(error){
        cbError(error);
      });
    }

    function getProposals (params, cbSuccess, cbError) {
      var paramsExtended = angular.extend({
        query: ''
      }, params);

      searchProposals(paramsExtended, cbSuccess, cbError);
    }

    function getProposalById (proposalId, params, cbSuccess, cbError) {
      var url = service.apiArticles + proposalId;

      var paramsExtended = angular.extend({
        // 'fields[]': ['id', 'title', 'abstract', 'children', 'children_count', 'ranking_position', 'hits', 'votes_for', 'votes_against'],
        // 'per_page':'1',
        'limit':'1',
        'content_type':'ProposalsDiscussionPlugin::Proposal'
      }, params);

      UtilService.get(url, {params: paramsExtended}).then(function(data){
        _pipeInjectSlugIntoParentProgram(data);
        cbSuccess(data);
      }).catch(function(error){
        cbError(error);
      });

    }

    function getRankedProposalsByTopicId (proposalId, params, cbSuccess, cbError) {
      var url = service.apiProposals + proposalId + '/ranking';
      var paramsExtended = angular.extend({
        page: 1,
        per_page: 10,
        type: 'ProposalsDiscussionPlugin::Proposal',
        'fields[]': [
        'id',
        'abstract',
        'hits',
        'ranking_position',
        'votes_against',
        'votes_count',
        'votes_for',
        'parent',
        'categories',
        'slug',
        'url', // parent.image.url
        'image',
        'title',
        'archived',
        ]
      }, params);

      UtilService.get(url, {params: paramsExtended}).then(function(data){
        cbSuccess(data);
      }).catch(function(error){
        cbError(error);
      });
    }

    function getProposalByIdRanked (proposalId, params, cbSuccess, cbError) {
      var url = service.apiProposals + proposalId + '/ranking?per_page=5&page=1';
      var paramsExtended = angular.extend({
        // 'fields[]': ['id', 'title', 'abstract', 'children', 'children_count', 'ranking_position', 'hits', 'votes_for', 'votes_against'],
        // 'per_page':'1',
        'limit':'1',
        'content_type':'ProposalsDiscussionPlugin::Proposal'
      }, params);

      UtilService.get(url, {params: paramsExtended}).then(function(data){
        _pipeInjectSlugIntoParentProgramRanked(data);
        cbSuccess(data);
      }).catch(function(error){
        cbError(error);
      });

    }

    /**
     * Ex.: /api/v1/articles/[article_id]/children?[params]content_type=ProposalsDiscussionPlugin::Proposal
     * Ex.: /api/v1/articles/103644/children?limit=20&fields=id,name,slug,abstract,created_by&content_type=ProposalsDiscussionPlugin::Proposal
     *
     * @param  {Integer}  topicId   topic where has those proposals
     * @param  {Object}   params    params for pagination ant others
     * @param  {Function} cbSuccess callback for success
     * @param  {Function} cbError   callback for error
     * @return {Array}           [description]
     */
     function getProposalsByTopicId (topicId, params, cbSuccess, cbError) {
      getProposalById(topicId + '/children', params, cbSuccess, cbError);
    }

    function getProposalsByTopicIdRanked (topicId, params, cbSuccess, cbError) {
      getProposalByIdRanked(topicId, params, cbSuccess, cbError);
    }

    function getResponseByProposalId (proposalId) {
      var url = service.apiArticles + proposalId + '/children?content_type=ProposalsDiscussionPlugin::Response&limit=1';

      // var paramsExtended = {};
      
      return UtilService.get(url);
    }

    function createProposal (proposal, targetId, categoryId, cbSuccess, cbError){

      if(!$rootScope.currentUser){
        cbError({message: 'Usuário não logado.'});
      }else{
        // /api/v1/proposals_discussion_plugin/' + targetId + '/propose
        var url = service.apiProposals + targetId + '/propose';

        var encodedParams = [];
        encodedParams.push('article%5Babstract%5D=' + proposal);
        encodedParams.push('article%5Bcategory_ids%5D%5B%5D=' + categoryId);
        encodedParams.push('article%5Btype%5D=ProposalsDiscussionPlugin%3A%3AProposal');
        encodedParams.push('content_type=ProposalsDiscussionPlugin%3A%3AProposal');
        encodedParams.push('private_token=' + $rootScope.currentUser.private_token);
        encodedParams.push('fields=id');
        encodedParams.push('article[name]=article_' + GUID.generate());
        encodedParams = encodedParams.join('&');

        UtilService.post(url, encodedParams).then(function(response){
          cbSuccess(response);
        }).catch(function(error){
          cbError(error);
        });
      }
    }

    function voteProposal (proposal_id, params){
      var url = service.apiArticles + proposal_id + '/vote';

      var private_token = null;
      if($rootScope.currentUser && $rootScope.currentUser.private_token){
        private_token = $rootScope.currentUser.private_token;
      }else{
        private_token = $rootScope.temporaryToken;
      }

      var paramsExtended = angular.extend({
        private_token: private_token
      }, params);

      var encodedParams = angular.element.param(paramsExtended);

      return UtilService.post(url, encodedParams);
    }

    function getEvents (community_id, params) {
      // Ex.: /api/v1/communities/19195/articles?categories_ids[]=' + cat_id + '&content_type=Event';
      // Ex.: /api/v1/communities/' + community_id + '/articles?categories_ids[]=' + cat_id + '&content_type=Event';

      var url = service.apiCommunities + community_id + '/articles';
      var paramsExtended = angular.extend({
        'fields[]': ['id', 'title', 'abstract', 'body', 'setting', 'presenter', 'created_at', 'update_at', 'start_date', 'end_date', 'followers_count', 'image', 'url'],
        'content_type':'Event'
      }, params);

      return UtilService.get(url, {params: paramsExtended}).then(function(data){
        _pipeRemoveOldEvents(data);
        return data;
      });
    }

    // function getSubscribers (event_id, params, cbSuccess, cbError) {
    //   var url = service.apiArticles + event_id + '/followers?_=' + new Date().getTime();
    //   var paramsExtended = angular.extend({
    //     // 'fields[]': ['id', 'slug', 'title', 'abstract', 'body', 'categories', 'created_at', 'start_date', 'end_date', 'hits'],
    //     'content_type':'Event'
    //   }, params);

    //   UtilService.get(url, {params: paramsExtended}).then(function(data){
    //     cbSuccess(data.articles);
    //   }).catch(function(error){
    //     cbError(error);
    //   });
    // }

    function subscribeToEvent (event_id) {
      var url = service.apiArticles + event_id + '/follow';
      var encodedParams = 'private_token=' + $rootScope.currentUser.private_token;

      return UtilService.post(url, encodedParams);
    }

    function sendContactForm (community_id, data){
      var url = service.apiCommunities + community_id + '/contact';
      var encodedParams = [
      'contact[name]=' + data.name,
      'contact[email]=' + data.email,
      'contact[subject]=' + data.subject,
      'contact[message]=' + data.message
      ].join('&');

      return UtilService.post(url, encodedParams);
    }

    function searchTopics (params, cbSuccess, cbError) {
      // Ex.: /api/v1/search/article?type=ProposalsDiscussionPlugin::Topic&query=cisternas
      var url = service.apiSearch + 'article';
      var paramsExtended = angular.extend({
        // 'fields[]': ['id', 'title', 'slug', 'abstract', 'categories', 'setting', 'children_count', 'hits'],
        'type': 'ProposalsDiscussionPlugin::Topic'
      }, params);

      UtilService.get(url, {params: paramsExtended}).then(function(data){
        cbSuccess(data);
      }).catch(function(error){
        cbError(error);
      });
    }

    function searchProposals (params, cbSuccess, cbError) {
      // Ex.: /api/v1/search/article?type=ProposalsDiscussionPlugin::Proposal&query=cisternas
      var url = service.apiSearch + 'article';
      var paramsExtended = angular.extend({
        page: 1,
        per_page: 10,
        type: 'ProposalsDiscussionPlugin::Proposal',
        'fields[]': [
        'id',
        'abstract',
        'hits',
        'ranking_position',
        'votes_against',
        'votes_count',
        'votes_for',
        'parent',
        'categories',
        'slug',
        'url', // parent.image.url
        'image',
        'title',
        'archived',
        ]
      }, params);

      UtilService.get(url, {params: paramsExtended}).then(function(data){
        _pipeInjectSlugIntoParentProgram(data);
        cbSuccess(data);
      }).catch(function(error){
        cbError(error);
      });
    }

    function _pipeInjectSlugIntoParentProgram(data){
      if(!data.articles && data.article){
        data.articles = [data.article];
      }
      var proposals = data.articles;
      for (var i = proposals.length - 1; i >= 0; i--) {
        var proposal = proposals[i];
        if(proposal.parent && !proposal.parent.slug){
          proposal.parent.slug = Slug.slugify(proposal.parent.title);
        }
      }
    }

//Refazer esse método. Não faz sentido
function _pipeInjectSlugIntoParentProgramRanked(data){
  if(!data.proposals && data.proposals){
    data.proposals = [data.proposals];
  }
  var proposals = data.proposals;
  for (var i = proposals.length - 1; i >= 0; i--) {
    var proposal = proposals[i];
    if(proposal.parent && !proposal.parent.slug){
      proposal.parent.slug = Slug.slugify(proposal.parent.title);
    }
  }
}

function _pipeRemoveOldEvents(data){
  if(!data.articles && data.article){
    data.articles = [data.article];
    data.article = null;
  }

  var now = (new Date()).getTime();
  var eventDate = null;
  var events = data.articles;

  var results = [];
  for (var i = events.length - 1; i >= 0; i--) {
    var event = events[i];

    if(event.end_date){
      eventDate = new Date(event.end_date);
    }

        // if(eventDate.getTime() < now){
        //   event.isOld = true;
        // }
        if(eventDate.getTime() >= now){
          results.push(event);
        }
      }

      data.articles = results;
    }
  }
})();