<commit_before>import { extend, includes } from 'lodash'

const findCommunityIds = req => {
  if (req.param('communityId')) {
    return Promise.resolve([req.param('communityId')])
  } else if (req.param('type') === 'communities' && req.param('moderated')) {
    if (Admin.isSignedIn(req)) {
      return Community.query().pluck('id')
    } else {
      return Membership.activeCommunityIds(req.session.userId, true)
    }
  } else {
    return Promise.join(
      Network.activeCommunityIds(req.session.userId),
      Membership.activeCommunityIds(req.session.userId)
    ).then(ids => _(ids).flatten().uniq().value())
  }
}

const getTotal = records =>
  records && records.length > 0 ? Number(records.first().get('total')) : 0

module.exports = {
  show: function (req, res) {
    var term = req.param('q').trim()
    var resultTypes = req.param('include')
    var limit = req.param('limit') || 10
    var offset = req.param('offset') || 0

    return findCommunityIds(req)
    .then(function (communityIds) {
      return Promise.join(
        _.includes(resultTypes, 'posts') && Search.forPosts({
          term: term,
          limit: limit,
          offset: offset,
          communities: communityIds,
          sort: 'post.created_at'
        }).fetchAll({withRelated: PostPresenter.relations(req.session.userId)}),
        _.includes(resultTypes, 'people') && Search.forUsers({
          term: term,
          limit: limit,
          offset: offset,
          communities: communityIds
        }).fetchAll({withRelated: ['skills', 'organizations']})
      )
    })
    .spread(function (posts, people) {
      res.ok({
        posts_total: getTotal(posts),
        posts: posts && posts.map(PostPresenter.present),
        people_total: getTotal(people),
        people: people && people.map(person => _.chain(person.attributes)
          .pick(UserPresenter.shortAttributes)
          .extend({
            skills: Skill.simpleList(person.relations.skills),
            organizations: Organization.simpleList(person.relations.organizations)
          }).value())
      })
    })
    .catch(res.serverError)
  },

  autocomplete: function (req, res) {
    var term = req.param('q').trim()
    var resultType = req.param('type')
    var sort, method, columns

    switch (resultType) {
      case 'posts':
        method = Search.forPosts
        sort = 'post.created_at'
        break
      case 'skills':
        method = Search.forSkills
        columns = ['skill_name']
        break
      case 'organizations':
        method = Search.forOrganizations
        columns = ['org_name']
        break
      case 'communities':
        method = Search.forCommunities
        columns = ['id', 'name', 'avatar_url', 'slug']
        break
      case 'tags':
        method = Search.forTags
        columns = ['tags.id', 'name']
        break
      default:
        method = Search.forUsers
        if (term.startsWith('@')) {
          term = term.slice(1)
        } else if (term.startsWith('#')) {
          method = Search.forTags
          term = term.slice(1)
        }
    }

    return (!includes(['skills', 'organizations'], resultType)
      ? findCommunityIds(req)
        .then(communityIds => ({
          communities: communityIds,
          project: req.param('projectId')
        }))
      : Promise.resolve({}))
    .then(filters => method(extend(filters, {
      autocomplete: term,
      limit: req.param('limit') || 5,
      sort: sort
    })).fetchAll({columns: columns}))
    .then(rows => {
      var present
      switch (resultType) {
        case 'skills':
          present = row => ({name: row.get('skill_name')})
          break
        case 'organizations':
          present = row => ({name: row.get('org_name')})
          break
        default:
          present = row => row.pick('id', 'name', 'avatar_url', 'slug')
      }
      res.ok(rows.map(present))
    })
    .catch(res.serverError)
  },

  showFullText: function (req, res) {
    var term = req.param('q')
    if (!term) return res.badRequest('expected a parameter named "q"')
    var type = req.param('type')
    var limit = req.param('limit')
    var offset = req.param('offset')
    var userId = req.session.userId
    var items

    Membership.activeCommunityIds(userId)
    .then(communityIds =>
      FullTextSearch.searchInCommunities(communityIds, {term, type, limit, offset}))
    .then(items_ => {
      items = items_

      var ids = _.transform(items, (ids, item) => {
        var type = item.post_id ? 'posts'
          : item.comment_id ? 'comments' : 'people'

        if (!ids[type]) ids[type] = []
        var id = item.post_id || item.comment_id || item.user_id
        ids[type].push(id)
      }, {})

      var userColumns = q => q.column('id', 'name', 'avatar_url')

      // FIXME factor out this general-purpose object display/formatting code

      return Promise.join(
        ids.posts && Post.where('id', 'in', ids.posts)
        .fetchAll({withRelated: PostPresenter.relations(userId)}),

        ids.comments && Comment.where('id', 'in', ids.comments)
        .fetchAll({withRelated: [
          {'user': userColumns},
          {'post': q => q.column('id', 'type', 'name', 'user_id')},
          {'post.user': userColumns},
          {'post.relatedUsers': userColumns},
          {'thanks.thankedBy': userColumns}
        ]}),

        ids.people && User.where('id', 'in', ids.people)
        .fetchAll({withRelated: ['skills', 'organizations']})
      )
    })
    .spread((posts, comments, people) => items.map(item => {
      var result = {rank: item.rank}

      if (item.user_id) {
        result.type = 'person'
        var person = people.find(p => p.id === item.user_id)
        result.data = UserPresenter.presentForList(person)
      } else if (item.post_id) {
        result.type = 'post'
        var post = posts.find(p => p.id === item.post_id)
        result.data = PostPresenter.present(post)
      } else {
        result.type = 'comment'
        var comment = comments.find(c => c.id === item.comment_id)
        result.data = comment.toJSON()
      }

      return result
    }))
    .then(results => ({items: results, total: _.get(items, '0.total') || 0}))
    .then(res.ok)
  }
}
<commit_msg>increase autocomplete limit to 10<commit_after>import { extend, includes } from 'lodash'

const findCommunityIds = req => {
  if (req.param('communityId')) {
    return Promise.resolve([req.param('communityId')])
  } else if (req.param('type') === 'communities' && req.param('moderated')) {
    if (Admin.isSignedIn(req)) {
      return Community.query().pluck('id')
    } else {
      return Membership.activeCommunityIds(req.session.userId, true)
    }
  } else {
    return Promise.join(
      Network.activeCommunityIds(req.session.userId),
      Membership.activeCommunityIds(req.session.userId)
    ).then(ids => _(ids).flatten().uniq().value())
  }
}

const getTotal = records =>
  records && records.length > 0 ? Number(records.first().get('total')) : 0

module.exports = {
  show: function (req, res) {
    var term = req.param('q').trim()
    var resultTypes = req.param('include')
    var limit = req.param('limit') || 10
    var offset = req.param('offset') || 0

    return findCommunityIds(req)
    .then(function (communityIds) {
      return Promise.join(
        _.includes(resultTypes, 'posts') && Search.forPosts({
          term: term,
          limit: limit,
          offset: offset,
          communities: communityIds,
          sort: 'post.created_at'
        }).fetchAll({withRelated: PostPresenter.relations(req.session.userId)}),
        _.includes(resultTypes, 'people') && Search.forUsers({
          term: term,
          limit: limit,
          offset: offset,
          communities: communityIds
        }).fetchAll({withRelated: ['skills', 'organizations']})
      )
    })
    .spread(function (posts, people) {
      res.ok({
        posts_total: getTotal(posts),
        posts: posts && posts.map(PostPresenter.present),
        people_total: getTotal(people),
        people: people && people.map(person => _.chain(person.attributes)
          .pick(UserPresenter.shortAttributes)
          .extend({
            skills: Skill.simpleList(person.relations.skills),
            organizations: Organization.simpleList(person.relations.organizations)
          }).value())
      })
    })
    .catch(res.serverError)
  },

  autocomplete: function (req, res) {
    var term = req.param('q').trim()
    var resultType = req.param('type')
    var sort, method, columns

    switch (resultType) {
      case 'posts':
        method = Search.forPosts
        sort = 'post.created_at'
        break
      case 'skills':
        method = Search.forSkills
        columns = ['skill_name']
        break
      case 'organizations':
        method = Search.forOrganizations
        columns = ['org_name']
        break
      case 'communities':
        method = Search.forCommunities
        columns = ['id', 'name', 'avatar_url', 'slug']
        break
      case 'tags':
        method = Search.forTags
        columns = ['tags.id', 'name']
        break
      default:
        method = Search.forUsers
        if (term.startsWith('@')) {
          term = term.slice(1)
        } else if (term.startsWith('#')) {
          method = Search.forTags
          term = term.slice(1)
        }
    }

    return (!includes(['skills', 'organizations'], resultType)
      ? findCommunityIds(req)
        .then(communityIds => ({
          communities: communityIds,
          project: req.param('projectId')
        }))
      : Promise.resolve({}))
    .then(filters => method(extend(filters, {
      autocomplete: term,
      limit: req.param('limit') || 10,
      sort: sort
    })).fetchAll({columns: columns}))
    .then(rows => {
      var present
      switch (resultType) {
        case 'skills':
          present = row => ({name: row.get('skill_name')})
          break
        case 'organizations':
          present = row => ({name: row.get('org_name')})
          break
        default:
          present = row => row.pick('id', 'name', 'avatar_url', 'slug')
      }
      res.ok(rows.map(present))
    })
    .catch(res.serverError)
  },

  showFullText: function (req, res) {
    var term = req.param('q')
    if (!term) return res.badRequest('expected a parameter named "q"')
    var type = req.param('type')
    var limit = req.param('limit')
    var offset = req.param('offset')
    var userId = req.session.userId
    var items

    Membership.activeCommunityIds(userId)
    .then(communityIds =>
      FullTextSearch.searchInCommunities(communityIds, {term, type, limit, offset}))
    .then(items_ => {
      items = items_

      var ids = _.transform(items, (ids, item) => {
        var type = item.post_id ? 'posts'
          : item.comment_id ? 'comments' : 'people'

        if (!ids[type]) ids[type] = []
        var id = item.post_id || item.comment_id || item.user_id
        ids[type].push(id)
      }, {})

      var userColumns = q => q.column('id', 'name', 'avatar_url')

      // FIXME factor out this general-purpose object display/formatting code

      return Promise.join(
        ids.posts && Post.where('id', 'in', ids.posts)
        .fetchAll({withRelated: PostPresenter.relations(userId)}),

        ids.comments && Comment.where('id', 'in', ids.comments)
        .fetchAll({withRelated: [
          {'user': userColumns},
          {'post': q => q.column('id', 'type', 'name', 'user_id')},
          {'post.user': userColumns},
          {'post.relatedUsers': userColumns},
          {'thanks.thankedBy': userColumns}
        ]}),

        ids.people && User.where('id', 'in', ids.people)
        .fetchAll({withRelated: ['skills', 'organizations']})
      )
    })
    .spread((posts, comments, people) => items.map(item => {
      var result = {rank: item.rank}

      if (item.user_id) {
        result.type = 'person'
        var person = people.find(p => p.id === item.user_id)
        result.data = UserPresenter.presentForList(person)
      } else if (item.post_id) {
        result.type = 'post'
        var post = posts.find(p => p.id === item.post_id)
        result.data = PostPresenter.present(post)
      } else {
        result.type = 'comment'
        var comment = comments.find(c => c.id === item.comment_id)
        result.data = comment.toJSON()
      }

      return result
    }))
    .then(results => ({items: results, total: _.get(items, '0.total') || 0}))
    .then(res.ok)
  }
}
<|endoftext|>


<commit_before>'use strict';

exports = module.exports = function(services, app) {

    var Gettext = require('node-gettext');
    var gt = new Gettext();

    var service = new services.get(app);

    /**
     * Call the calendar get service
     *
     * @param {Object} params
     * @return {Promise}
     */
    service.getResultPromise = function(params) {

        service.app.db.models.Calendar
        .findOne({ '_id' : params.id}, 'name url type')
        .exec(function(err, document) {
            if (service.handleMongoError(err))
            {
                if (document) {
                    service.outcome.success = true;
                    service.deferred.resolve(document);
                } else {
                    service.notFound(gt.gettext('This calendar does not exists'));
                }
            }
        });

        return service.deferred.promise;
    };

    return service;
};

<commit_msg>Add a test<commit_after>'use strict';

exports = module.exports = function(services, app) {

    var Gettext = require('node-gettext');
    var gt = new Gettext();

    var service = new services.get(app);

    /**
     * Call the calendar get service
     *
     * @param {Object} params
     * @return {Promise}
     */
    service.getResultPromise = function(params) {

        if (params.id === undefined) {
            return service.forbidden('Missing id parameter');
        }

        service.app.db.models.Calendar
        .findOne({ '_id' : params.id}, 'name url type')
        .exec(function(err, document) {
            if (service.handleMongoError(err))
            {
                if (document) {
                    service.outcome.success = true;
                    service.deferred.resolve(document);
                } else {
                    service.notFound(gt.gettext('This calendar does not exists'));
                }
            }
        });

        return service.deferred.promise;
    };

    return service;
};

<|endoftext|>


<commit_before>/* eslint-disable no-unused-expressions */
import React from 'react'
import { expect } from 'chai'
import shallowWithIntl from 'intl/helpers/shallow-with-intl'
import { Pressure } from './__pressure__'

describe('client/mobilizations/widgets/__plugins__/pressure/components/__pressure__', () => {
  let wrapper
  const props = {
    editable: false,
    mobilization: { id: 1 },
    widget: { id: 1, settings: {} },
    filledPressureWidgets: [],
    block: { scrollTopReached: false }
  }

  beforeEach(() => {
    wrapper = shallowWithIntl(<Pressure {...props} />)
  })

  it('should color with main_color, h2, a, PressureForm, PressureCount', () => {
    wrapper.setProps({
      widget: {
        id: 1,
        settings: { main_color: '#fff', count_text: 'pressões' }
      }
    })
    expect(wrapper.find('h2').props().style.backgroundColor).to.equal('#fff')
    expect(wrapper.find('InjectIntl(PressureForm)').props().buttonColor).to.equal('#fff')
    expect(wrapper.find('PressureCount').props().color).to.equal('#fff')
  })

  it('should render h2 with title_text', () => {
    const titleText = 'Envie um e-mail para quem quer tomar essa decisão'
    wrapper.setProps({ widget: { id: 1, settings: { title_text: titleText } } })

    expect(wrapper.find('h2').text()).to.equal(titleText)
  })

  it('should render h2 with call_to_action', () => {
    const titleText = 'Envie um e-mail para quem quer tomar essa decisão'
    const callToAction = 'Envie um e-mail'
    wrapper.setProps({
      widget: {
        id: 1,
        settings: { call_to_action: callToAction, title_text: titleText }
      }
    })

    expect(wrapper.find('h2').text()).to.equal(callToAction)
  })

  it('should render PressureForm with pressure_subject and pressure_body', () => {
    const pressureSubject = 'Não derrubem a escola'
    const pressureBody = 'Sra. Renata da Costa, favor não derrubar...'

    wrapper.setProps({
      widget: {
        id: 1,
        settings: {
          pressure_subject: pressureSubject,
          pressure_body: pressureBody
        }
      }
    })

    expect(wrapper.find('InjectIntl(PressureForm)').props().subject).to.equal(pressureSubject)
    expect(wrapper.find('InjectIntl(PressureForm)').props().body).to.equal(pressureBody)
  })

  it('should render PressureForm with button_text', () => {
    const buttonText = 'Enviar e-mail'
    wrapper.setProps({ widget: { id: 1, settings: { button_text: buttonText } } })

    expect(wrapper.find('InjectIntl(PressureForm)').props().buttonText).to.equal(buttonText)
  })

  it('should render ok with values default when settings is undefined', () => {
    wrapper.setProps({ widget: { id: 1, settings: undefined } })
    expect(wrapper).to.be.ok
  })

  it('should hide PressureCount when show_counter is "false"', () => {
    wrapper.setProps({ widget: { id: 1, settings: { show_counter: 'false' } } })
    expect(wrapper.find('PressureCount').length).to.equal(0)
  })

  it('should render targets received by settings with type string', () => {
    wrapper.setProps({
      widget: {
        id: 1,
        settings: { targets: 'Igor Santos <igor@nossascidades.org>' }
      }
    })
    expect(wrapper.find('TargetList').props().targets)
      .to.deep.equal(['Igor Santos <igor@nossascidades.org>'])

    wrapper.setProps({
      widget: {
        id: 1,
        settings: {
          targets: 'Igor Santos <igor@nossascidades.org>;Lucas Pirola <pirola@nossascidades.org>'
        }
      }
    })
    expect(wrapper.find('TargetList').props().targets)
      .to.deep.equal([
        'Igor Santos <igor@nossascidades.org>',
        'Lucas Pirola <pirola@nossascidades.org>'
      ])
  })

  it('should render PressureTellAFriend when filledPressureWidgets includes the id 1', () => {
    wrapper.setProps({ widget: { ...props.widget }, filledPressureWidgets: [1] })
    expect(wrapper.find('PressureTellAFriend').length).to.equal(1)
  })
})
<commit_msg>fix(admin): pressure console.error<commit_after>/* eslint-disable no-unused-expressions */
import React from 'react'
import { expect } from 'chai'
import shallowWithIntl from 'intl/helpers/shallow-with-intl'
import { Pressure } from './__pressure__'

describe('client/mobilizations/widgets/__plugins__/pressure/components/__pressure__', () => {
  let wrapper
  const props = {
    editable: false,
    mobilization: { id: 1 },
    widget: { id: 1, settings: {} },
    filledPressureWidgets: [],
    block: { scrollTopReached: false }
  }

  beforeEach(() => {
    wrapper = shallowWithIntl(<Pressure {...props} />)
  })

  it('should color with main_color, h2, a, PressureForm, PressureCount', () => {
    wrapper.setProps({
      widget: {
        id: 1,
        settings: { main_color: '#fff', count_text: 'pressões' }
      }
    })
    expect(wrapper.find('h2').props().style.backgroundColor).to.equal('#fff')
    expect(wrapper.find('InjectIntl(PressureForm)').props().buttonColor).to.equal('#fff')
    expect(wrapper.find('PressureCount').props().color).to.equal('#fff')
  })

  it('should render h2 with title_text', () => {
    const titleText = 'Envie um e-mail para quem quer tomar essa decisão'
    wrapper.setProps({ widget: { id: 1, settings: { title_text: titleText } } })

    expect(wrapper.find('h2').text()).to.equal(titleText)
  })

  it('should render h2 with call_to_action', () => {
    const titleText = 'Envie um e-mail para quem quer tomar essa decisão'
    const callToAction = 'Envie um e-mail'
    wrapper.setProps({
      widget: {
        id: 1,
        settings: { call_to_action: callToAction, title_text: titleText }
      }
    })

    expect(wrapper.find('h2').text()).to.equal(callToAction)
  })

  it('should render PressureForm with pressure_subject and pressure_body', () => {
    const pressureSubject = 'Não derrubem a escola'
    const pressureBody = 'Sra. Renata da Costa, favor não derrubar...'

    wrapper.setProps({
      widget: {
        id: 1,
        settings: {
          pressure_subject: pressureSubject,
          pressure_body: pressureBody
        }
      }
    })

    expect(wrapper.find('InjectIntl(PressureForm)').props().subject).to.equal(pressureSubject)
    expect(wrapper.find('InjectIntl(PressureForm)').props().body).to.equal(pressureBody)
  })

  it('should render PressureForm with button_text', () => {
    const buttonText = 'Enviar e-mail'
    wrapper.setProps({ widget: { id: 1, settings: { button_text: buttonText } } })

    expect(wrapper.find('InjectIntl(PressureForm)').props().buttonText).to.equal(buttonText)
  })

  it('should hide PressureCount when show_counter is "false"', () => {
    wrapper.setProps({ widget: { id: 1, settings: { show_counter: 'false' } } })
    expect(wrapper.find('PressureCount').length).to.equal(0)
  })

  it('should render targets received by settings with type string', () => {
    wrapper.setProps({
      widget: {
        id: 1,
        settings: { targets: 'Igor Santos <igor@nossascidades.org>' }
      }
    })
    expect(wrapper.find('TargetList').props().targets)
      .to.deep.equal(['Igor Santos <igor@nossascidades.org>'])

    wrapper.setProps({
      widget: {
        id: 1,
        settings: {
          targets: 'Igor Santos <igor@nossascidades.org>;Lucas Pirola <pirola@nossascidades.org>'
        }
      }
    })
    expect(wrapper.find('TargetList').props().targets)
      .to.deep.equal([
        'Igor Santos <igor@nossascidades.org>',
        'Lucas Pirola <pirola@nossascidades.org>'
      ])
  })

  it('should render PressureTellAFriend when filledPressureWidgets includes the id 1', () => {
    wrapper.setProps({ widget: { ...props.widget }, filledPressureWidgets: [1] })
    expect(wrapper.find('PressureTellAFriend').length).to.equal(1)
  })
})
<|endoftext|>


<commit_before>'use strict';

const operations = require('./operations');

// Apply `noOutput` settings:
//   - if true, the action will modify the database, but return an empty
//     response
//   - defaults to true for `delete`, false otherwise
//   - this can also be set for all the actions using:
//      - Prefer: return=minimal HTTP request header
const noOutput = function () {
  return async function noOutput(input) {
    const { operation, log, protocolArgs } = input;
    let response = await this.next(input);
    const perf = log.perf.start('operation.noOutput', 'middleware');

    if (protocolArgs.noOutput) {
      response = operations[operation].noOutput(response);
    }

    perf.stop();
    return response;
  };
};

module.exports = {
  noOutput,
};
<commit_msg>Default delete actions to noOutput true<commit_after>'use strict';

const operations = require('./operations');

// Apply `noOutput` settings:
//   - if true, the action will modify the database, but return an empty
//     response
//   - defaults to true for `delete`, false otherwise
//   - this can also be set for all the actions using:
//      - Prefer: return=minimal HTTP request header
const noOutput = function () {
  return async function noOutput(input) {
    const { operation, log, protocolArgs } = input;
    let response = await this.next(input);
    const perf = log.perf.start('operation.noOutput', 'middleware');

    const isDelete = response.actions &&
      response.actions.some(({ type }) => type === 'delete');
    const shouldRemoveOutput = isDelete || protocolArgs.noOutput;
    if (shouldRemoveOutput) {
      response = operations[operation].noOutput(response);
    }

    perf.stop();
    return response;
  };
};

module.exports = {
  noOutput,
};
<|endoftext|>


<commit_before>export const radiantring = [
    {
        "item": "Brilliant Silverfrost Key",
        "createdBy": "Radiant Ring",
        "orders": [
            {
                "duration": "1d",
                "cost": 300000,
                "output": 2,
                "ingredients": [
                    {"name": "Common Rock", "quantity": 15},
                    {"name": "Advanced Rock", "quantity": 20},
                    {"name": "Rare Material", "quantity": 10},
                    {"name": "Soulstone", "quantity": 60},
                    {"name": "Moonstone", "quantity": 12},
                    {"name": "Sacred Orb", "quantity": 60},
                    {"name": "Elysian Orb", "quantity": 12}
                ]
            },
            {
                "duration": "2d",
                "cost": 600000,
                "output": 5,
                "ingredients": [
                    {"name": "Common Rock", "quantity": 30},
                    {"name": "Advanced Rock", "quantity": 40},
                    {"name": "Rare Material", "quantity": 20},
                    {"name": "Soulstone", "quantity": 130},
                    {"name": "Moonstone", "quantity": 30},
                    {"name": "Sacred Orb", "quantity": 130},
                    {"name": "Elysian Orb", "quantity": 30}
                ]
            },
            {
                "duration": "3d",
                "cost": 1200000,
                "output": 11,
                "ingredients": [
                    {"name": "Common Rock", "quantity": 45},
                    {"name": "Advanced Rock", "quantity": 55},
                    {"name": "Rare Material", "quantity": 30},
                    {"name": "Soulstone", "quantity": 250},
                    {"name": "Moonstone", "quantity": 60},
                    {"name": "Sacred Orb", "quantity": 250},
                    {"name": "Elysian Orb", "quantity": 60}
                ]
            }
        ]
    },
    {
        "item": "Pentagonal Diamond Pouch",
        "createdBy": "Radiant Ring",
        "orders": [

            {
                "duration": "45m",
                "cost": 20000,
                "output": 1,
                "ingredients": [
                    {"name": "Common Rock", "quantity": 1},
                    {"name": "Advanced Rock", "quantity": 1},
                    {"name": "Rare Material", "quantity": 1},
                    {"name": "Soulstone", "quantity": 20},
                    {"name": "Moonstone", "quantity": 4},
                    {"name": "Sacred Orb", "quantity": 20},
                    {"name": "Elysian Orb", "quantity": 4},
                    {"name": "Radiant Energy", "quantity": 10}
                ]
            },
            {
                "duration": "90m",
                "cost": 40000,
                "output": 2,
                "ingredients": [
                    {"name": "Common Rock", "quantity": 1},
                    {"name": "Advanced Rock", "quantity": 2},
                    {"name": "Rare Material", "quantity": 1},
                    {"name": "Soulstone", "quantity": 35},
                    {"name": "Moonstone", "quantity": 7},
                    {"name": "Sacred Orb", "quantity": 35},
                    {"name": "Elysian Orb", "quantity": 7},
                    {"name": "Radiant Energy", "quantity": 15}
                ]
            },
            {
                "duration": "3h",
                "cost": 75000,
                "output": 11,
                "ingredients": [
                    {"name": "Common Rock", "quantity": 2},
                    {"name": "Advanced Rock", "quantity": 3},
                    {"name": "Rare Material", "quantity": 2},
                    {"name": "Soulstone", "quantity": 65},
                    {"name": "Moonstone", "quantity": 15},
                    {"name": "Sacred Orb", "quantity": 65},
                    {"name": "Elysian Orb", "quantity": 15},
                    {"name": "Radiant Energy", "quantity": 5}
                ]
            }
        ]
    },
    {
        "item": "Hexagonal Diamond Pouch",
        "createdBy": "Radiant Ring",
        "orders": [

            {
                "duration": "90m",
                "cost": 20000,
                "output": 1,
                "ingredients": [
                    {"name": "Common Rock", "quantity": 1},
                    {"name": "Advanced Rock", "quantity": 2},
                    {"name": "Rare Material", "quantity": 1},
                    {"name": "Soulstone", "quantity": 40},
                    {"name": "Moonstone", "quantity": 10},
                    {"name": "Sacred Orb", "quantity": 40},
                    {"name": "Elysian Orb", "quantity": 10},
                    {"name": "Radiant Energy", "quantity": 15}
                ]
            },
            {
                "duration": "3h",
                "cost": 75000,
                "output": 2,
                "ingredients": [
                    {"name": "Common Rock", "quantity": 2},
                    {"name": "Advanced Rock", "quantity": 3},
                    {"name": "Rare Material", "quantity": 2},
                    {"name": "Soulstone", "quantity": 65},
                    {"name": "Moonstone", "quantity": 15},
                    {"name": "Sacred Orb", "quantity": 65},
                    {"name": "Elysian Orb", "quantity": 15},
                    {"name": "Radiant Energy", "quantity": 25}
                ]
            },
            {
                "duration": "6h",
                "cost": 150000,
                "output": 5,
                "ingredients": [
                    {"name": "Common Rock", "quantity": 4},
                    {"name": "Advanced Rock", "quantity": 5},
                    {"name": "Rare Material", "quantity": 3},
                    {"name": "Soulstone", "quantity": 130},
                    {"name": "Moonstone", "quantity": 30},
                    {"name": "Sacred Orb", "quantity": 130},
                    {"name": "Elysian Orb", "quantity": 30},
                    {"name": "Radiant Energy", "quantity": 45}
                ]
            }
        ]
    },
    {
        "item": "Heptagonal Diamond Pouch",
        "createdBy": "Radiant Ring",
        "orders": [
            {
                "duration": "1d",
                "cost": 600000,
                "output": 1,
                "ingredients": [
                    {"name": "Common Rock", "quantity": 14},
                    {"name": "Advanced Rock", "quantity": 20},
                    {"name": "Rare Material", "quantity": 10},
                    {"name": "Soulstone", "quantity": 125},
                    {"name": "Moonstone", "quantity": 30},
                    {"name": "Sacred Orb", "quantity": 125},
                    {"name": "Elysian Orb", "quantity": 30},
                    {"name": "Radiant Energy", "quantity": 40}
                ]
            },
            {
                "duration": "2d",
                "cost": 1800000,
                "output": 3,
                "ingredients": [
                    {"name": "Common Rock", "quantity": 30},
                    {"name": "Advanced Rock", "quantity": 40},
                    {"name": "Rare Material", "quantity": 20},
                    {"name": "Soulstone", "quantity": 310},
                    {"name": "Moonstone", "quantity": 80},
                    {"name": "Sacred Orb", "quantity": 310},
                    {"name": "Elysian Orb", "quantity": 80},
                    {"name": "Radiant Energy", "quantity": 100}
                ]
            }
        ]
    },
    {
        "item": "Octagonal Diamond Pouch",
        "createdBy": "Radiant Ring",
        "orders": [
            {
                "duration": "2d",
                "cost": 1800000,
                "output": 1,
                "ingredients": [
                    {"name": "Common Rock", "quantity": 30},
                    {"name": "Advanced Rock", "quantity": 40},
                    {"name": "Rare Material", "quantity": 20},
                    {"name": "Soulstone", "quantity": 400},
                    {"name": "Moonstone", "quantity": 100},
                    {"name": "Sacred Orb", "quantity": 400},
                    {"name": "Elysian Orb", "quantity": 100},
                    {"name": "Radiant Energy", "quantity": 140}
                ]
            },
            {
                "duration": "5d",
                "cost": 3000000,
                "output": 3,
                "ingredients": [
                    {"name": "Common Rock", "quantity": 70},
                    {"name": "Advanced Rock", "quantity": 95},
                    {"name": "Rare Material", "quantity": 50},
                    {"name": "Soulstone", "quantity": 1000},
                    {"name": "Moonstone", "quantity": 250},
                    {"name": "Sacred Orb", "quantity": 1000},
                    {"name": "Elysian Orb", "quantity": 250},
                    {"name": "Radiant Energy", "quantity": 350}
                ]
            }
        ]
    }
];<commit_msg>Update radiantringCrafting.js<commit_after>export const radiantring = [
    {
        "item": "Brilliant Key",
        "createdBy": "Radiant Ring",
        "orders": [
            {
                "duration": "1d",
                "cost": 300000,
                "output": 2,
                "ingredients": [
                    {"name": "Common Rock", "quantity": 15},
                    {"name": "Advanced Rock", "quantity": 20},
                    {"name": "Rare Material", "quantity": 10},
                    {"name": "Soulstone", "quantity": 60},
                    {"name": "Moonstone", "quantity": 12},
                    {"name": "Sacred Orb", "quantity": 60},
                    {"name": "Elysian Orb", "quantity": 12}
                ]
            },
            {
                "duration": "2d",
                "cost": 600000,
                "output": 5,
                "ingredients": [
                    {"name": "Common Rock", "quantity": 30},
                    {"name": "Advanced Rock", "quantity": 40},
                    {"name": "Rare Material", "quantity": 20},
                    {"name": "Soulstone", "quantity": 130},
                    {"name": "Moonstone", "quantity": 30},
                    {"name": "Sacred Orb", "quantity": 130},
                    {"name": "Elysian Orb", "quantity": 30}
                ]
            },
            {
                "duration": "3d",
                "cost": 1200000,
                "output": 11,
                "ingredients": [
                    {"name": "Common Rock", "quantity": 45},
                    {"name": "Advanced Rock", "quantity": 55},
                    {"name": "Rare Material", "quantity": 30},
                    {"name": "Soulstone", "quantity": 250},
                    {"name": "Moonstone", "quantity": 60},
                    {"name": "Sacred Orb", "quantity": 250},
                    {"name": "Elysian Orb", "quantity": 60}
                ]
            }
        ]
    },
    {
        "item": "Pentagonal Diamond Pouch",
        "createdBy": "Radiant Ring",
        "orders": [

            {
                "duration": "45m",
                "cost": 20000,
                "output": 1,
                "ingredients": [
                    {"name": "Common Rock", "quantity": 1},
                    {"name": "Advanced Rock", "quantity": 1},
                    {"name": "Rare Material", "quantity": 1},
                    {"name": "Soulstone", "quantity": 20},
                    {"name": "Moonstone", "quantity": 4},
                    {"name": "Sacred Orb", "quantity": 20},
                    {"name": "Elysian Orb", "quantity": 4},
                    {"name": "Radiant Energy", "quantity": 10}
                ]
            },
            {
                "duration": "90m",
                "cost": 40000,
                "output": 2,
                "ingredients": [
                    {"name": "Common Rock", "quantity": 1},
                    {"name": "Advanced Rock", "quantity": 2},
                    {"name": "Rare Material", "quantity": 1},
                    {"name": "Soulstone", "quantity": 35},
                    {"name": "Moonstone", "quantity": 7},
                    {"name": "Sacred Orb", "quantity": 35},
                    {"name": "Elysian Orb", "quantity": 7},
                    {"name": "Radiant Energy", "quantity": 15}
                ]
            },
            {
                "duration": "3h",
                "cost": 75000,
                "output": 11,
                "ingredients": [
                    {"name": "Common Rock", "quantity": 2},
                    {"name": "Advanced Rock", "quantity": 3},
                    {"name": "Rare Material", "quantity": 2},
                    {"name": "Soulstone", "quantity": 65},
                    {"name": "Moonstone", "quantity": 15},
                    {"name": "Sacred Orb", "quantity": 65},
                    {"name": "Elysian Orb", "quantity": 15},
                    {"name": "Radiant Energy", "quantity": 5}
                ]
            }
        ]
    },
    {
        "item": "Hexagonal Diamond Pouch",
        "createdBy": "Radiant Ring",
        "orders": [

            {
                "duration": "90m",
                "cost": 20000,
                "output": 1,
                "ingredients": [
                    {"name": "Common Rock", "quantity": 1},
                    {"name": "Advanced Rock", "quantity": 2},
                    {"name": "Rare Material", "quantity": 1},
                    {"name": "Soulstone", "quantity": 40},
                    {"name": "Moonstone", "quantity": 10},
                    {"name": "Sacred Orb", "quantity": 40},
                    {"name": "Elysian Orb", "quantity": 10},
                    {"name": "Radiant Energy", "quantity": 15}
                ]
            },
            {
                "duration": "3h",
                "cost": 75000,
                "output": 2,
                "ingredients": [
                    {"name": "Common Rock", "quantity": 2},
                    {"name": "Advanced Rock", "quantity": 3},
                    {"name": "Rare Material", "quantity": 2},
                    {"name": "Soulstone", "quantity": 65},
                    {"name": "Moonstone", "quantity": 15},
                    {"name": "Sacred Orb", "quantity": 65},
                    {"name": "Elysian Orb", "quantity": 15},
                    {"name": "Radiant Energy", "quantity": 25}
                ]
            },
            {
                "duration": "6h",
                "cost": 150000,
                "output": 5,
                "ingredients": [
                    {"name": "Common Rock", "quantity": 4},
                    {"name": "Advanced Rock", "quantity": 5},
                    {"name": "Rare Material", "quantity": 3},
                    {"name": "Soulstone", "quantity": 130},
                    {"name": "Moonstone", "quantity": 30},
                    {"name": "Sacred Orb", "quantity": 130},
                    {"name": "Elysian Orb", "quantity": 30},
                    {"name": "Radiant Energy", "quantity": 45}
                ]
            }
        ]
    },
    {
        "item": "Heptagonal Diamond Pouch",
        "createdBy": "Radiant Ring",
        "orders": [
            {
                "duration": "1d",
                "cost": 600000,
                "output": 1,
                "ingredients": [
                    {"name": "Common Rock", "quantity": 14},
                    {"name": "Advanced Rock", "quantity": 20},
                    {"name": "Rare Material", "quantity": 10},
                    {"name": "Soulstone", "quantity": 125},
                    {"name": "Moonstone", "quantity": 30},
                    {"name": "Sacred Orb", "quantity": 125},
                    {"name": "Elysian Orb", "quantity": 30},
                    {"name": "Radiant Energy", "quantity": 40}
                ]
            },
            {
                "duration": "2d",
                "cost": 1800000,
                "output": 3,
                "ingredients": [
                    {"name": "Common Rock", "quantity": 30},
                    {"name": "Advanced Rock", "quantity": 40},
                    {"name": "Rare Material", "quantity": 20},
                    {"name": "Soulstone", "quantity": 310},
                    {"name": "Moonstone", "quantity": 80},
                    {"name": "Sacred Orb", "quantity": 310},
                    {"name": "Elysian Orb", "quantity": 80},
                    {"name": "Radiant Energy", "quantity": 100}
                ]
            }
        ]
    },
    {
        "item": "Octagonal Diamond Pouch",
        "createdBy": "Radiant Ring",
        "orders": [
            {
                "duration": "2d",
                "cost": 1800000,
                "output": 1,
                "ingredients": [
                    {"name": "Common Rock", "quantity": 30},
                    {"name": "Advanced Rock", "quantity": 40},
                    {"name": "Rare Material", "quantity": 20},
                    {"name": "Soulstone", "quantity": 400},
                    {"name": "Moonstone", "quantity": 100},
                    {"name": "Sacred Orb", "quantity": 400},
                    {"name": "Elysian Orb", "quantity": 100},
                    {"name": "Radiant Energy", "quantity": 140}
                ]
            },
            {
                "duration": "5d",
                "cost": 3000000,
                "output": 3,
                "ingredients": [
                    {"name": "Common Rock", "quantity": 70},
                    {"name": "Advanced Rock", "quantity": 95},
                    {"name": "Rare Material", "quantity": 50},
                    {"name": "Soulstone", "quantity": 1000},
                    {"name": "Moonstone", "quantity": 250},
                    {"name": "Sacred Orb", "quantity": 1000},
                    {"name": "Elysian Orb", "quantity": 250},
                    {"name": "Radiant Energy", "quantity": 350}
                ]
            }
        ]
    }
];
<|endoftext|>


<commit_before>var ws = require('ws');
var transfer = require('./transfer.js');
const vwssserver = require('../config.js').ws

module.exports = function(objinput, callback) {

    switch (objinput.fname) {

        case "get_full_accounts":

            temp2 = {
                "id": 0,
                "method": "call",
                "params": [0, "get_full_accounts", [objinput.vaccount.split(' '), 'false']]
            };
            break;

        case "get_ticker":

            var aux = objinput.vquote.split(' ')
            var temp2 = {
                "id": '2',
                "method": "call",
                "params": [0, "get_ticker", aux]
            };
            break;

        case "get_objects":

            var temp2 = {
                "id": 0,
                "method": "call",
                "params": [0, "get_objects", [objinput.vobject.split(' ')]]
            };
            break;

        case "get_account_history":

            var temp2 = {
                "id": '',
                "method": "call",
                "params": [3, "get_account_history", ['1.2.153811', 100, 100, 100]]
            };
            break;

        case "transfer":

            var objTx = {
                privKey: objinput.privKey,
                fromAccount: objinput.fromAccount,
                memo: objinput.memo,
                toAccount: objinput.toAccount,
                amount: objinput.amount,
                asset: objinput.asset
            };

            transfer(objTx, function(err, tx) {
                if (err) {
                    callback(err, null)
                } else {
                    callback(null, tx);
                }
            });;
            break;

        default:
            callback({
                error: 'no function available'
            }, null)
    }

    var wss = new ws(vwssserver.host);
    var wssOutput = null;

    wss.on('open', () => {
        wss.send(JSON.stringify(temp2));
    });

    wss.on('message', (data) => {
        wssOutput = JSON.parse(data);
        wss.terminate();
    });

    wss.on('error', (error) => {
        wssOutput.error = {};
        wssOutput.error.code = -5;
        wssOutput.error.reason = 'WebSocket tunnel to bitshares node has failed';
        wss.terminate();
    });

    wss.on('close', (vdata) => {
        if (wssOutput.error) {
            callback(wssOutput, null)
        } else {
            callback(null, wssOutput)
        }
    });
};<commit_msg>Update route.js<commit_after>/**
 * route.js for bitsharesAPINode
 * (c) 2017 TheSerranos.
 * This code is released under the
 * terms of the MIT license.
 */
var ws = require('ws');
var transfer = require('./transfer.js');
const vwssserver = require('../config.js').ws

module.exports = function(objinput, callback) {

    switch (objinput.fname) {

        case "get_full_accounts":

            temp2 = {
                "id": 0,
                "method": "call",
                "params": [0, "get_full_accounts", [objinput.vaccount.split(' '), 'false']]
            };
            break;

        case "get_ticker":

            var aux = objinput.vquote.split(' ')
            var temp2 = {
                "id": '2',
                "method": "call",
                "params": [0, "get_ticker", aux]
            };
            break;

        case "get_objects":

            var temp2 = {
                "id": 0,
                "method": "call",
                "params": [0, "get_objects", [objinput.vobject.split(' ')]]
            };
            break;

        case "get_account_history":

            var temp2 = {
                "id": '',
                "method": "call",
                "params": [3, "get_account_history", ['1.2.153811', 100, 100, 100]]
            };
            break;

        case "transfer":

            var objTx = {
                privKey: objinput.privKey,
                fromAccount: objinput.fromAccount,
                memo: objinput.memo,
                toAccount: objinput.toAccount,
                amount: objinput.amount,
                asset: objinput.asset
            };

            transfer(objTx, function(err, tx) {
                if (err) {
                    callback(err, null)
                } else {
                    callback(null, tx);
                }
            });;
            break;

        default:
            callback({
                error: 'no function available'
            }, null)
    }

    var wss = new ws(vwssserver.host);
    var wssOutput = null;

    wss.on('open', () => {
        wss.send(JSON.stringify(temp2));
    });

    wss.on('message', (data) => {
        wssOutput = JSON.parse(data);
        wss.terminate();
    });

    wss.on('error', (error) => {
        wssOutput.error = {};
        wssOutput.error.code = -5;
        wssOutput.error.reason = 'WebSocket tunnel to bitshares node has failed';
        wss.terminate();
    });

    wss.on('close', (vdata) => {
        if (wssOutput.error) {
            callback(wssOutput, null)
        } else {
            callback(null, wssOutput)
        }
    });
};
<|endoftext|>


<commit_before>/* eslint-disable prefer-promise-reject-errors */
import downloadjs from 'downloadjs'
import { toast } from 'react-toastify'
// TO DO: remove before migration notification to react-toastify
//import { addNotification as notify, removeNotification as dismiss } from 'reapop'
import * as notifications from 'utils/notifications'

const asyncDownloadActivistActions = ({ id, name, ...community }) => (dispatch, getState, { api, intl }) => {
  const { auth: { credentials } } = getState()

  const filename = `[Relatório][Ações dos Ativistas] ${name}.csv`
  // const notificationId = Math.random()
  const notifySuccess = () => {
    toast.success(notifications.reportDownloadSuccess(intl, { filename }).message, {
      autoClose: 5000,
      hideProgressBar: true,
    })
    // TO DO: remove before migration notification to react-toastify
    // dispatch(notify(notifications.reportDownloadSuccess(intl, { filename })))
    // dispatch(dismiss(notificationId))
  }
  const notifyError = () => {
    toast.error(notifications.reportDownloadError(intl, { filename }).message, {
      autoClose: 5000,
      hideProgressBar: true,
    })
    // TO DO: remove before migration notification to react-toastify
    // dispatch(notify(notifications.reportDownloadError(intl, { filename })))
    // dispatch(dismiss(notificationId))
  }

    // TO DO: remove before migration notification to react-toastify
  // const warningOptions = { filename, notificationId }
  // dispatch(notify(notifications.reportDownloadInProgressWarning(intl, warningOptions)))

  return api
    .get(`/communities/${id}/activist_actions.csv`, { headers: credentials })
    .then(({ status, data }) => {
      if (status === 400 && data.errors) {
        notifyError()
        return Promise.reject({ ...data.errors })
      } else if (status === 200) {
        if (data.length > 0) {
          notifySuccess()
          downloadjs(new Blob([data]), filename, 'text/csv')
          return Promise.resolve()
        }
      }
    })
    .catch(error => {
      notifyError()
      Promise.reject(error)
    })
}

export default asyncDownloadActivistActions
<commit_msg>feat(admin): refactor notification in async-download-activist-action<commit_after>/* eslint-disable prefer-promise-reject-errors */
import downloadjs from 'downloadjs'
import { toast } from 'react-toastify'
// TO DO: remove before migration notification to react-toastify
//import { addNotification as notify, removeNotification as dismiss } from 'reapop'
import * as notifications from 'utils/notifications'

const asyncDownloadActivistActions = ({ id, name, ...community }) => (dispatch, getState, { api, intl }) => {
  const { auth: { credentials } } = getState()

  const filename = `[Relatório][Ações dos Ativistas] ${name}.csv`
  // const notificationId = Math.random()
  const notifySuccess = () => {
    toast.success(notifications.reportDownloadSuccess(intl, { filename }).message, {
      autoClose: 5000,
      hideProgressBar: true,
    })
    // TO DO: remove before migration notification to react-toastify
    // dispatch(notify(notifications.reportDownloadSuccess(intl, { filename })))
    // dispatch(dismiss(notificationId))
  }
  const notifyError = () => {
    toast.error(notifications.reportDownloadError(intl, { filename }).message, {
      autoClose: 5000,
      hideProgressBar: true,
    })
    // TO DO: remove before migration notification to react-toastify
    // dispatch(notify(notifications.reportDownloadError(intl, { filename })))
    // dispatch(dismiss(notificationId))
  }

  // TO DO: remove before migration notification to react-toastify
  // const warningOptions = { filename, notificationId }
  // dispatch(notify(notifications.reportDownloadInProgressWarning(intl, warningOptions)))

  return api
    .get(`/communities/${id}/activist_actions.csv`, { headers: credentials })
    .then(({ status, data }) => {
      if (status === 400 && data.errors) {
        notifyError()
        return Promise.reject({ ...data.errors })
      } else if (status === 200) {
        if (data.length > 0) {
          notifySuccess()
          downloadjs(new Blob([data]), filename, 'text/csv')
          return Promise.resolve()
        }
      }
    })
    .catch(error => {
      notifyError()
      Promise.reject(error)
    })
}

export default asyncDownloadActivistActions
<|endoftext|>


<commit_before>import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render, triggerEvent, waitFor } from '@ember/test-helpers';
import Object from '@ember/object';
import hbs from 'htmlbars-inline-precompile';

module('Integration | Component | field editors/integer editor', function(hooks) {
  setupRenderingTest(hooks);

  test('it renders', async function(assert) {
    this.setProperties({
      model: Object.create({ rating: 3 }),
      onchange() {}
    });
    await render(hbs`
      {{field-editors/integer-editor
        content=model
        field="rating"
        onchange=onchange
      }}`);
    assert.dom('input[type=number]').hasValue('3', 'number input has correct value');
    assert.dom('input').isNotDisabled('input is not disabled');
  });

  test('it updates the value correctly', async function(assert) {
    this.setProperties({
      model: Object.create({ rating: 3 }),
      onchange() {}
    });
    await render(hbs`
      {{field-editors/integer-editor
        content=model
        field="rating"
        onchange=onchange
      }}`);
    this.set('model.rating', 5);
    await triggerEvent('.field-editor > input', 'input');
    assert.dom('input[type=number]').hasValue('5', 'input is updated');
    assert.dom('input').isNotDisabled('input is not disabled');
    assert.equal(this.get('model.rating'), '5', 'model attribute is updated');
  });

  test('it can be disabled', async function(assert) {
    this.setProperties({
      model: Object.create({ rating: 3 }),
      onchange() {}
    });
    await render(hbs`
      {{field-editors/integer-editor
        content=model
        field="rating"
        onchange=onchange
        disabled=true
      }}`);
    assert.dom('input').isDisabled('integer input is disabled');
  });
});
<commit_msg>Simplify test assertions and helpers<commit_after>import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render, triggerEvent, fillIn } from '@ember/test-helpers';
import EmberObject from '@ember/object';
import hbs from 'htmlbars-inline-precompile';

module('Integration | Component | field editors/integer editor', function(hooks) {
  setupRenderingTest(hooks);

  test('it renders', async function(assert) {
    this.setProperties({
      model: EmberObject.create({ rating: 3 }),
      onchange() {}
    });
    await render(hbs`
      {{field-editors/integer-editor
        content=model
        field="rating"
        onchange=onchange
      }}`);
    assert.dom('input[type=number]').hasValue('3', 'number input has correct value');
    assert.dom('input').isNotDisabled();
  });

  test('it updates the value correctly', async function(assert) {
    this.setProperties({
      model: EmberObject.create({ rating: 3 }),
      onchange() {}
    });
    await render(hbs`
      {{field-editors/integer-editor
        content=model
        field="rating"
        onchange=onchange
      }}`);
    await fillIn('.field-editor > input', '5');
    assert.dom('input[type=number]').hasValue('5', 'input is updated');
    assert.dom('input').isNotDisabled();
    assert.equal(this.get('model.rating'), '5', 'model attribute is updated');
  });

  test('it can be disabled', async function(assert) {
    this.setProperties({
      model: EmberObject.create({ rating: 3 }),
      onchange() {}
    });
    await render(hbs`
      {{field-editors/integer-editor
        content=model
        field="rating"
        onchange=onchange
        disabled=true
      }}`);
    assert.dom('input').isDisabled();
  });
});
<|endoftext|>


<commit_before>(function ($, DataTable) {
    "use strict";

    var _buildParams = function (dt, action) {
        var params = dt.ajax.params();
        params.action = action;
        params._token = $('meta[name="csrf-token"]').attr('content');

        return params;
    };

    var _downloadFromUrl = function (url, params) {
        var postUrl = url + '/export';
        var xhr = new XMLHttpRequest();
        xhr.open('POST', postUrl, true);
        xhr.responseType = 'arraybuffer';
        xhr.onload = function () {
            if (this.status === 200) {
                var filename = "";
                var disposition = xhr.getResponseHeader('Content-Disposition');
                if (disposition && disposition.indexOf('attachment') !== -1) {
                    var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                    var matches = filenameRegex.exec(disposition);
                    if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
                }
                var type = xhr.getResponseHeader('Content-Type');

                var blob = new Blob([this.response], {type: type});
                if (typeof window.navigator.msSaveBlob !== 'undefined') {
                    // IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
                    window.navigator.msSaveBlob(blob, filename);
                } else {
                    var URL = window.URL || window.webkitURL;
                    var downloadUrl = URL.createObjectURL(blob);

                    if (filename) {
                        // use HTML5 a[download] attribute to specify filename
                        var a = document.createElement("a");
                        // safari doesn't support this yet
                        if (typeof a.download === 'undefined') {
                            window.location = downloadUrl;
                        } else {
                            a.href = downloadUrl;
                            a.download = filename;
                            document.body.appendChild(a);
                            a.click();
                        }
                    } else {
                        window.location = downloadUrl;
                    }

                    setTimeout(function () {
                        URL.revokeObjectURL(downloadUrl);
                    }, 100); // cleanup
                }
            }
        };
        xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        xhr.send($.param(params));
    };

    var _buildUrl = function(dt, action) {
        var url = dt.ajax.url() || '';
        var params = dt.ajax.params();
        params.action = action;

        if (url.indexOf('?') > -1) {
            return url + '&' + $.param(params);
        }

        return url + '?' + $.param(params);
    };

    DataTable.ext.buttons.excel = {
        className: 'buttons-excel',

        text: function (dt) {
            return ' ' + dt.i18n('buttons.excel', 'Excel');
        },

        action: function (e, dt, button, config) {
            var url = _buildUrl(dt, 'excel');
            window.location = url;
        }
    };

    DataTable.ext.buttons.postExcel = {
        className: 'buttons-excel',

        text: function (dt) {
            return ' ' + dt.i18n('buttons.excel', 'Excel');
        },

        action: function (e, dt, button, config) {
            var url = dt.ajax.url() || window.location.href;
            var params = _buildParams(dt, 'excel');

            _downloadFromUrl(url, params);
        }
    };

    DataTable.ext.buttons.export = {
        extend: 'collection',

        className: 'buttons-export',

        text: function (dt) {
            return ' ' + dt.i18n('buttons.export', 'Export') + ' ';
        },

        buttons: ['csv', 'excel', 'pdf']
    };

    DataTable.ext.buttons.csv = {
        className: 'buttons-csv',

        text: function (dt) {
            return ' ' + dt.i18n('buttons.csv', 'CSV');
        },

        action: function (e, dt, button, config) {
            var url = _buildUrl(dt, 'csv');
            window.location = url;
        }
    };

    DataTable.ext.buttons.postCsv = {
        className: 'buttons-csv',

        text: function (dt) {
            return ' ' + dt.i18n('buttons.csv', 'CSV');
        },

        action: function (e, dt, button, config) {
            var url = dt.ajax.url() || window.location.href;
            var params = _buildParams(dt, 'csv');

            _downloadFromUrl(url, params);
        }
    };

    DataTable.ext.buttons.pdf = {
        className: 'buttons-pdf',

        text: function (dt) {
            return ' ' + dt.i18n('buttons.pdf', 'PDF');
        },

        action: function (e, dt, button, config) {
            var url = _buildUrl(dt, 'pdf');
            window.location = url;
        }
    };

    DataTable.ext.buttons.postPdf = {
        className: 'buttons-pdf',

        text: function (dt) {
            return ' ' + dt.i18n('buttons.pdf', 'PDF');
        },

        action: function (e, dt, button, config) {
            var url = dt.ajax.url() || window.location.href;
            var params = _buildParams(dt, 'pdf');

            _downloadFromUrl(url, params);
        }
    };

    DataTable.ext.buttons.print = {
        className: 'buttons-print',

        text: function (dt) {
            return  ' ' + dt.i18n('buttons.print', 'Print');
        },

        action: function (e, dt, button, config) {
            var url = _buildUrl(dt, 'print');
            window.location = url;
        }
    };

    DataTable.ext.buttons.reset = {
        className: 'buttons-reset',

        text: function (dt) {
            return ' ' + dt.i18n('buttons.reset', 'Reset');
        },

        action: function (e, dt, button, config) {
            dt.search('');
            dt.columns().search('');
            dt.draw();
        }
    };

    DataTable.ext.buttons.reload = {
        className: 'buttons-reload',

        text: function (dt) {
            return ' ' + dt.i18n('buttons.reload', 'Reload');
        },

        action: function (e, dt, button, config) {
            dt.draw(false);
        }
    };

    DataTable.ext.buttons.create = {
        className: 'buttons-create',

        text: function (dt) {
            return ' ' + dt.i18n('buttons.create', 'Create');
        },

        action: function (e, dt, button, config) {
            window.location = window.location.href.replace(/\/+$/, "") + '/create';
        }
    };
})(jQuery, jQuery.fn.dataTable);
<commit_msg>Adds icons for the copyHtml5 and colvis buttons<commit_after>(function ($, DataTable) {
    "use strict";

    var _buildParams = function (dt, action) {
        var params = dt.ajax.params();
        params.action = action;
        params._token = $('meta[name="csrf-token"]').attr('content');

        return params;
    };

    var _downloadFromUrl = function (url, params) {
        var postUrl = url + '/export';
        var xhr = new XMLHttpRequest();
        xhr.open('POST', postUrl, true);
        xhr.responseType = 'arraybuffer';
        xhr.onload = function () {
            if (this.status === 200) {
                var filename = "";
                var disposition = xhr.getResponseHeader('Content-Disposition');
                if (disposition && disposition.indexOf('attachment') !== -1) {
                    var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                    var matches = filenameRegex.exec(disposition);
                    if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
                }
                var type = xhr.getResponseHeader('Content-Type');

                var blob = new Blob([this.response], {type: type});
                if (typeof window.navigator.msSaveBlob !== 'undefined') {
                    // IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
                    window.navigator.msSaveBlob(blob, filename);
                } else {
                    var URL = window.URL || window.webkitURL;
                    var downloadUrl = URL.createObjectURL(blob);

                    if (filename) {
                        // use HTML5 a[download] attribute to specify filename
                        var a = document.createElement("a");
                        // safari doesn't support this yet
                        if (typeof a.download === 'undefined') {
                            window.location = downloadUrl;
                        } else {
                            a.href = downloadUrl;
                            a.download = filename;
                            document.body.appendChild(a);
                            a.click();
                        }
                    } else {
                        window.location = downloadUrl;
                    }

                    setTimeout(function () {
                        URL.revokeObjectURL(downloadUrl);
                    }, 100); // cleanup
                }
            }
        };
        xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        xhr.send($.param(params));
    };

    var _buildUrl = function(dt, action) {
        var url = dt.ajax.url() || '';
        var params = dt.ajax.params();
        params.action = action;

        if (url.indexOf('?') > -1) {
            return url + '&' + $.param(params);
        }

        return url + '?' + $.param(params);
    };

    DataTable.ext.buttons.excel = {
        className: 'buttons-excel',

        text: function (dt) {
            return ' ' + dt.i18n('buttons.excel', 'Excel');
        },

        action: function (e, dt, button, config) {
            var url = _buildUrl(dt, 'excel');
            window.location = url;
        }
    };

    DataTable.ext.buttons.postExcel = {
        className: 'buttons-excel',

        text: function (dt) {
            return ' ' + dt.i18n('buttons.excel', 'Excel');
        },

        action: function (e, dt, button, config) {
            var url = dt.ajax.url() || window.location.href;
            var params = _buildParams(dt, 'excel');

            _downloadFromUrl(url, params);
        }
    };

    DataTable.ext.buttons.export = {
        extend: 'collection',

        className: 'buttons-export',

        text: function (dt) {
            return ' ' + dt.i18n('buttons.export', 'Export') + ' ';
        },

        buttons: ['csv', 'excel', 'pdf']
    };

    DataTable.ext.buttons.csv = {
        className: 'buttons-csv',

        text: function (dt) {
            return ' ' + dt.i18n('buttons.csv', 'CSV');
        },

        action: function (e, dt, button, config) {
            var url = _buildUrl(dt, 'csv');
            window.location = url;
        }
    };

    DataTable.ext.buttons.postCsv = {
        className: 'buttons-csv',

        text: function (dt) {
            return ' ' + dt.i18n('buttons.csv', 'CSV');
        },

        action: function (e, dt, button, config) {
            var url = dt.ajax.url() || window.location.href;
            var params = _buildParams(dt, 'csv');

            _downloadFromUrl(url, params);
        }
    };

    DataTable.ext.buttons.pdf = {
        className: 'buttons-pdf',

        text: function (dt) {
            return ' ' + dt.i18n('buttons.pdf', 'PDF');
        },

        action: function (e, dt, button, config) {
            var url = _buildUrl(dt, 'pdf');
            window.location = url;
        }
    };

    DataTable.ext.buttons.postPdf = {
        className: 'buttons-pdf',

        text: function (dt) {
            return ' ' + dt.i18n('buttons.pdf', 'PDF');
        },

        action: function (e, dt, button, config) {
            var url = dt.ajax.url() || window.location.href;
            var params = _buildParams(dt, 'pdf');

            _downloadFromUrl(url, params);
        }
    };

    DataTable.ext.buttons.print = {
        className: 'buttons-print',

        text: function (dt) {
            return  ' ' + dt.i18n('buttons.print', 'Print');
        },

        action: function (e, dt, button, config) {
            var url = _buildUrl(dt, 'print');
            window.location = url;
        }
    };

    DataTable.ext.buttons.reset = {
        className: 'buttons-reset',

        text: function (dt) {
            return ' ' + dt.i18n('buttons.reset', 'Reset');
        },

        action: function (e, dt, button, config) {
            dt.search('');
            dt.columns().search('');
            dt.draw();
        }
    };

    DataTable.ext.buttons.reload = {
        className: 'buttons-reload',

        text: function (dt) {
            return ' ' + dt.i18n('buttons.reload', 'Reload');
        },

        action: function (e, dt, button, config) {
            dt.draw(false);
        }
    };

    DataTable.ext.buttons.create = {
        className: 'buttons-create',

        text: function (dt) {
            return ' ' + dt.i18n('buttons.create', 'Create');
        },

        action: function (e, dt, button, config) {
            window.location = window.location.href.replace(/\/+$/, "") + '/create';
        }
    };

    if (typeof DataTable.ext.buttons.copyHtml5 !== 'undefined') {
        $.extend(DataTable.ext.buttons.copyHtml5, {
            text: function (dt) {
                return ' ' + dt.i18n('buttons.copy', 'Copy');
            }
        });
    }

    if (typeof DataTable.ext.buttons.colvis !== 'undefined') {
        $.extend(DataTable.ext.buttons.colvis, {
            text: function (dt) {
                return ' ' + dt.i18n('buttons.colvis', 'Column visibility');
            }
        });
    }
})(jQuery, jQuery.fn.dataTable);
<|endoftext|>


<commit_before>var jsface = require('jsface'),
	log    = require('../utilities/Logger'),
	helper    = require('../utilities/Helpers'),
	_und   = require('underscore'),
	vm = require('vm'),
	AbstractResponseHandler = require('./AbstractResponseHandler');

/**
 * @class TestResponseHandler
 * @classdesc
 */
var TestResponseHandler = jsface.Class(AbstractResponseHandler, {
	$singleton: true,

	// function called when the event "requestExecuted" is fired. Takes 4 self-explanatory parameters
	_onRequestExecuted: function(error, response, body, request) {
		if (error) {
			log.error(request.id + " terminated with the error " + error.code + "\n");
		} else {
			if (response.statusCode >= 200 && response.statusCode < 300) {
				log.success(response.statusCode);
			} else {
				log.error(response.statusCode);
			}
			log
			.notice(" " + response.stats.timeTaken + "ms")
			.normal(" " + request.name + " ")
			.light(request.url + "\n");
			this._runAndLogTestCases(error, response, body, request);
		}
	},

	_runAndLogTestCases: function(error, response, body, request) {
		if (this._hasTestCases(request)) {
			var tests = this._getValidTestCases(request.tests);
			var sandbox = this._createSandboxedEnvironment(error, response, body, request);
			var results = this._runAndGenerateTestResults(tests, sandbox);
			this._logTestResults(results);
		}
	},

	_hasTestCases: function(request) {
		return (request.tests !== undefined);
	},

	_getValidTestCases: function(tests) {
		return _und.reduce(tests.split(';'), function(listOfTests, testCase) {
			var t = testCase.trim();
			if (t.length > 0) {
				listOfTests.push(t);
			}
			return listOfTests;
		}, []);
	},

	_runAndGenerateTestResults: function(testCases, sandbox) {
		return this._evaluateInSandboxedEnvironment(testCases, sandbox);
	},

	_evaluateInSandboxedEnvironment: function(testCase, sandbox) {
		testCase = 'String.prototype.has = function(value){ return this.indexOf(value) > -1};' + testCase.join(";");
		try {
			vm.runInNewContext(testCase, sandbox);
		} catch (err) {
			log.exceptionError(err);
		}
		return sandbox.tests;
	},

	_createSandboxedEnvironment: function(error, response, body, request) {
		// TODO: @prakhar1989, figure out how to load the environment & globals here.
		// Also figure how this data comes in, probably its a enviornment variable.
		return {
			tests: {},
			responseHeaders: response.headers,
			responseBody: body,
			responseTime: response.stats.timeTaken,
			responseCode: {
				code: response.statusCode,
				name: request.name,
				detail: request.description
			},
			data: {},
			iteration: 0,
			environment: {},
			globals: {},
			$: require("jquery"),
			_: require("lodash"),
			Backbone: require("backbone"),
			sugar: require("sugar"),
			xmlToJson: require("xml2js"),
			tv4: require("tv4"),
			console: {log: function(){}}
		};
	},

	_logTestResults: function(results) {
		_und.each(_und.keys(results), function(key) {
			if (results[key]) {
				log.testCaseSuccess(key);
			} else {
				log.testCaseError(key);
			}
		});
	}
});

module.exports = TestResponseHandler;
<commit_msg>Fixed bug for valid test cases<commit_after>var jsface = require('jsface'),
	log    = require('../utilities/Logger'),
	helper    = require('../utilities/Helpers'),
	_und   = require('underscore'),
	vm = require('vm'),
	AbstractResponseHandler = require('./AbstractResponseHandler');

/**
 * @class TestResponseHandler
 * @classdesc
 */
var TestResponseHandler = jsface.Class(AbstractResponseHandler, {
	$singleton: true,

	// function called when the event "requestExecuted" is fired. Takes 4 self-explanatory parameters
	_onRequestExecuted: function(error, response, body, request) {
		if (error) {
			log.error(request.id + " terminated with the error " + error.code + "\n");
		} else {
			if (response.statusCode >= 200 && response.statusCode < 300) {
				log.success(response.statusCode);
			} else {
				log.error(response.statusCode);
			}
			log
			.notice(" " + response.stats.timeTaken + "ms")
			.normal(" " + request.name + " ")
			.light(request.url + "\n");
			this._runAndLogTestCases(error, response, body, request);
		}
	},

	_runAndLogTestCases: function(error, response, body, request) {
		if (this._hasTestCases(request)) {
			var tests = this._getValidTestCases(request.tests);
			var sandbox = this._createSandboxedEnvironment(error, response, body, request);
			var results = this._runAndGenerateTestResults(tests, sandbox);
			this._logTestResults(results);
		}
	},

	_hasTestCases: function(request) {
		return (request.tests !== "");
	},

	_getValidTestCases: function(tests) {
		return _und.reduce(tests.split(';'), function(listOfTests, testCase) {
			var t = testCase.trim();
			if (t.length > 0) {
				listOfTests.push(t);
			}
			return listOfTests;
		}, []);
	},

	_runAndGenerateTestResults: function(testCases, sandbox) {
		return this._evaluateInSandboxedEnvironment(testCases, sandbox);
	},

	_evaluateInSandboxedEnvironment: function(testCase, sandbox) {
		testCase = 'String.prototype.has = function(value){ return this.indexOf(value) > -1};' + testCase.join(";");
		try {
			vm.runInNewContext(testCase, sandbox);
		} catch (err) {
			log.exceptionError(err);
		}
		return sandbox.tests;
	},

	_createSandboxedEnvironment: function(error, response, body, request) {
		// TODO: @prakhar1989, figure out how to load the environment & globals here.
		return {
			tests: {},
			responseHeaders: response.headers,
			responseBody: body,
			responseTime: response.stats.timeTaken,
			responseCode: {
				code: response.statusCode,
				name: request.name,
				detail: request.description
			},
			data: {},
			iteration: 0,
			environment: {},
			globals: {},
			$: require("jquery"),
			_: require("lodash"),
			Backbone: require("backbone"),
			sugar: require("sugar"),
			xmlToJson: require("xml2js"),
			tv4: require("tv4"),
			console: {log: function(){}}
		};
	},

	_logTestResults: function(results) {
		_und.each(_und.keys(results), function(key) {
			if (results[key]) {
				log.testCaseSuccess(key);
			} else {
				log.testCaseError(key);
			}
		});
	}
});

module.exports = TestResponseHandler;
<|endoftext|>


<commit_before>import m from 'mithril';
import _ from 'underscore';
import I18n from 'i18n-js';
import h from '../h';
import facebookButton from '../c/facebook-button';
import projectShareBox from '../c/project-share-box';
import projectRow from '../c/project-row';
import UserVM from '../vms/user-vm';
import ProjectVM from '../vms/project-vm';

const I18nScope = _.partial(h.i18nScope, 'projects.contributions');
const ProjectsSubscriptionThankYou = {
    controller(args) {
        const paymentMethod = m.route.param('payment_method');
        const projectId = m.route.param('project_id');
        const project = m.prop({});
        const projectUser = m.prop();
        const recommendedProjects = UserVM.getUserRecommendedProjects();

        ProjectVM
            .fetchProject(projectId, false)
            .then(projectData => {
                project(_.first(projectData));
                return UserVM.fetchUser(project().user.id, false);
            })
            .then(projectUserData => projectUser(_.first(projectUserData)));

        return {
            displayShareBox: h.toggleProp(false, true),
            recommendedProjects,
            paymentMethod,
            project,
            projectUser
        };
    },
    view(ctrl, args) {
        const project = ctrl.project();
        const user = h.getUser();
        const projectUser = ctrl.projectUser();

        return m('#thank-you', !project ? h.loader() : [
            m('.page-header.u-marginbottom-30',
                m('.w-container',
                    m('.w-row',
                        m('.w-col.w-col-10.w-col-push-1', [
                            m('.u-marginbottom-20.u-text-center',
                                projectUser ? m(`img.big.thumb.u-round[src='${projectUser.profile_img_thumbnail}']`) : h.loader()
                            ),
                            m('#thank-you.u-text-center', [
                                m('#creditcard-thank-you.fontsize-larger.text-success.u-marginbottom-20',
                                    I18n.t('thank_you.thank_you', I18nScope())
                                ),
                                m('.fontsize-base.u-marginbottom-40',
                                    m.trust(
                                        I18n.t(
                                            ctrl.paymentMethod === 'credit_card'
                                                ? 'thank_you.thank_you_text_html'
                                                : 'thank_you.thank_you_slip_text_html',
                                            I18nScope({
                                                total: project.total_contributions,
                                                email: user.email,
                                                link2: `/pt/users/${user.user_id}/edit#contributions`,
                                                link_email: `/pt/users/${user.user_id}/edit#about_me`
                                            })
                                        )
                                    )
                                ),
                                m('.fontsize-base.fontweight-semibold.u-marginbottom-20',
                                    'Compartilhe com seus amigos e ajude esse projeto a bater a meta!'
                                )
                            ]),
                            m('.w-row', [
                                m('.w-hidden-small.w-hidden-tiny', [
                                    m('.w-sub-col.w-col.w-col-4', m.component(facebookButton, {
                                        url: `https://www.catarse.me/${project.permalink}?ref=ctrse_thankyou&utm_source=facebook.com&utm_medium=social&utm_campaign=project_share`,
                                        big: true
                                    })),
                                    m('.w-sub-col.w-col.w-col-4', m.component(facebookButton, {
                                        messenger: true,
                                        big: true,
                                        url: `https://www.catarse.me/${project.permalink}?ref=ctrse_thankyou&utm_source=facebook.com&utm_medium=messenger&utm_campaign=thanks_share`
                                    })),
                                    m('.w-col.w-col-4', m(`a.btn.btn-large.btn-tweet.u-marginbottom-20[href="https://twitter.com/intent/tweet?text=Acabei%20de%20apoiar%20o%20projeto%20${encodeURIComponent(project.name)}%20https://www.catarse.me/${project.permalink}%3Fref%3Dtwitter%26utm_source%3Dtwitter.com%26utm_medium%3Dsocial%26utm_campaign%3Dproject_share"][target="_blank"]`, [
                                        m('span.fa.fa-twitter'), ' Twitter'
                                    ]))
                                ]),
                                m('.w-hidden-main.w-hidden-medium', [
                                    m('.u-marginbottom-30.u-text-center-small-only', m('button.btn.btn-large.btn-terciary.u-marginbottom-40', {
                                        onclick: ctrl.displayShareBox.toggle
                                    }, 'Compartilhe')),
                                    ctrl.displayShareBox() ? m(projectShareBox, {
                                        project: m.prop({
                                            permalink: project.permalink,
                                            name: project.name
                                        }),
                                        displayShareBox: ctrl.displayShareBox
                                    }) : ''
                                ])
                            ]),
                        ])

                    )
                )
            ),
            m('.section.u-marginbottom-40',
                m('.w-container', [
                    m('.fontsize-large.fontweight-semibold.u-marginbottom-30.u-text-center',
                        I18n.t('thank_you.project_recommendations', I18nScope())
                    ),
                    m.component(projectRow, {
                        collection: ctrl.recommendedProjects,
                        ref: 'ctrse_thankyou_r'
                    })
                ])
            )
        ]);
    }
};

export default ProjectsSubscriptionThankYou;
<commit_msg>fix thank you facebook button page<commit_after>import m from 'mithril';
import _ from 'underscore';
import I18n from 'i18n-js';
import h from '../h';
import facebookButton from '../c/facebook-button';
import projectShareBox from '../c/project-share-box';
import projectRow from '../c/project-row';
import UserVM from '../vms/user-vm';
import ProjectVM from '../vms/project-vm';

const I18nScope = _.partial(h.i18nScope, 'projects.contributions');
const ProjectsSubscriptionThankYou = {
    controller(args) {
        const paymentMethod = m.route.param('payment_method');
        const projectId = m.route.param('project_id');
        const project = m.prop({});
        const projectUser = m.prop();
        const recommendedProjects = UserVM.getUserRecommendedProjects();

        ProjectVM
            .fetchProject(projectId, false)
            .then(projectData => {
                project(_.first(projectData));
                return UserVM.fetchUser(project().user.id, false);
            })
            .then(projectUserData => projectUser(_.first(projectUserData)));

        return {
            displayShareBox: h.toggleProp(false, true),
            recommendedProjects,
            paymentMethod,
            project,
            projectUser
        };
    },
    view(ctrl, args) {
        const project = ctrl.project();
        const user = h.getUser();
        const projectUser = ctrl.projectUser();

        return m('#thank-you', !project ? h.loader() : [
            m('.page-header.u-marginbottom-30',
                m('.w-container',
                    m('.w-row',
                        m('.w-col.w-col-10.w-col-push-1', [
                            m('.u-marginbottom-20.u-text-center',
                                projectUser ? m(`img.big.thumb.u-round[src='${projectUser.profile_img_thumbnail}']`) : h.loader()
                            ),
                            m('#thank-you.u-text-center', [
                                m('#creditcard-thank-you.fontsize-larger.text-success.u-marginbottom-20',
                                    I18n.t('thank_you.thank_you', I18nScope())
                                ),
                                m('.fontsize-base.u-marginbottom-40',
                                    m.trust(
                                        I18n.t(
                                            ctrl.paymentMethod === 'credit_card'
                                                ? 'thank_you.thank_you_text_html'
                                                : 'thank_you.thank_you_slip_text_html',
                                            I18nScope({
                                                total: project.total_contributions,
                                                email: user.email,
                                                link2: `/pt/users/${user.user_id}/edit#contributions`,
                                                link_email: `/pt/users/${user.user_id}/edit#about_me`
                                            })
                                        )
                                    )
                                ),
                                m('.fontsize-base.fontweight-semibold.u-marginbottom-20',
                                    'Compartilhe com seus amigos e ajude esse projeto a bater a meta!'
                                )
                            ]),
                            m('.w-row', [
                                m('.w-hidden-small.w-hidden-tiny', _.isEmpty(project) ? h.loader() : [
                                    m('.w-sub-col.w-col.w-col-4', m.component(facebookButton, {
                                        url: `https://www.catarse.me/${project.permalink}?ref=ctrse_thankyou&utm_source=facebook.com&utm_medium=social&utm_campaign=project_share`,
                                        big: true
                                    })),
                                    m('.w-sub-col.w-col.w-col-4', m.component(facebookButton, {
                                        messenger: true,
                                        big: true,
                                        url: `https://www.catarse.me/${project.permalink}?ref=ctrse_thankyou&utm_source=facebook.com&utm_medium=messenger&utm_campaign=thanks_share`
                                    })),
                                    m('.w-col.w-col-4', m(`a.btn.btn-large.btn-tweet.u-marginbottom-20[href="https://twitter.com/intent/tweet?text=Acabei%20de%20apoiar%20o%20projeto%20${encodeURIComponent(project.name)}%20https://www.catarse.me/${project.permalink}%3Fref%3Dtwitter%26utm_source%3Dtwitter.com%26utm_medium%3Dsocial%26utm_campaign%3Dproject_share"][target="_blank"]`, [
                                        m('span.fa.fa-twitter'), ' Twitter'
                                    ]))
                                ]),
                                m('.w-hidden-main.w-hidden-medium', [
                                    m('.u-marginbottom-30.u-text-center-small-only', m('button.btn.btn-large.btn-terciary.u-marginbottom-40', {
                                        onclick: ctrl.displayShareBox.toggle
                                    }, 'Compartilhe')),
                                    ctrl.displayShareBox() ? m(projectShareBox, {
                                        project: m.prop({
                                            permalink: project.permalink,
                                            name: project.name
                                        }),
                                        displayShareBox: ctrl.displayShareBox
                                    }) : ''
                                ])
                            ]),
                        ])

                    )
                )
            ),
            m('.section.u-marginbottom-40',
                m('.w-container', [
                    m('.fontsize-large.fontweight-semibold.u-marginbottom-30.u-text-center',
                        I18n.t('thank_you.project_recommendations', I18nScope())
                    ),
                    m.component(projectRow, {
                        collection: ctrl.recommendedProjects,
                        ref: 'ctrse_thankyou_r'
                    })
                ])
            )
        ]);
    }
};

export default ProjectsSubscriptionThankYou;
<|endoftext|>


<commit_before>/**
 * Created by jack on 16-11-28.
 */

import path from 'path';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import MFS from 'memory-fs';
import { PassThrough } from 'stream';

import { serverBundleFileName, clientManifestFileName } from '../../../config/webpack/setting';
import clientConfig from '../../../config/webpack/client';
import serverConfig from '../../../config/webpack/server';
import { createRenderer } from './server-render';

const mfs = new MFS();
const clientManifestFilePath = path.join(clientConfig.output.path, clientManifestFileName);
const serverBundleFilePath = path.join(serverConfig.output.path, serverBundleFileName);
let expressDevMiddleware;

/**
 * setRenderer
 * whenever client file or server file change, renderer should be update
 */
const updateRenderer = () => {
	try {
		const options = {
			clientManifest: JSON.parse(expressDevMiddleware.fileSystem.readFileSync(clientManifestFilePath, 'utf-8'))
		};
		createRenderer(JSON.parse(mfs.readFileSync(serverBundleFilePath, 'utf-8')), options);
	} catch(e) {
		createRenderer(JSON.parse(mfs.readFileSync(serverBundleFilePath, 'utf-8')));
	}
	console.log('Renderer is updated.');
};

const koaWebpackDevMiddleware = (compiler, opts) => {
	expressDevMiddleware = webpackDevMiddleware(compiler, opts);
	return async (ctx, next) => {
		await new Promise(resolve =>
			expressDevMiddleware(ctx.req, {
				end: (content) => {
					ctx.body = content;
					resolve();
				},
				setHeader: ctx.set.bind(ctx)
			}, () => resolve(next()))
		);
	};
};

const koaWebpackHotMiddleware = (compiler, opts) => {
	const expressMiddleware = webpackHotMiddleware(compiler, opts);
	return async (ctx, next) => {
		let stream = new PassThrough();
		ctx.body = stream;
		await expressMiddleware(ctx.req, {
			write: stream.write.bind(stream),
			writeHead: (state, headers) => {
				ctx.state = state;
				ctx.set(headers);
			}
		}, next);
	}
};

const clientCompiler = webpack(clientConfig);

const devMiddleware = koaWebpackDevMiddleware(clientCompiler, {
	// display no info to console (only warnings and errors)
	noInfo: false,
	stats: {
		colors: true,
		cached: false
	},
	contentBase: clientConfig.output.path,
	publicPath: clientConfig.output.publicPath
});

clientCompiler.plugin('done', updateRenderer);

const hotMiddleware = koaWebpackHotMiddleware(clientCompiler, {});

// watch and update server renderer
const serverCompiler = webpack(serverConfig);
serverCompiler.outputFileSystem = mfs;
serverCompiler.watch({}, (err, stats) => {
	if (err) throw err;
	stats = stats.toJson();
	stats.errors.forEach(err => console.error(err));
	stats.warnings.forEach(err => console.warn(err));
	updateRenderer();
});

export {devMiddleware, hotMiddleware};
<commit_msg>Fix server build issue.<commit_after>/**
 * Created by jack on 16-11-28.
 */

import path from 'path';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import MFS from 'memory-fs';
import { PassThrough } from 'stream';

import { serverBundleFileName, clientManifestFileName } from '../../../config/webpack/setting';
import clientConfig from '../../../config/webpack/client';
import serverConfig from '../../../config/webpack/server';
import { createRenderer } from './server-render';

const mfs = new MFS();
const clientManifestFilePath = path.join(clientConfig.output.path, clientManifestFileName);
const serverBundleFilePath = path.join(serverConfig.output.path, serverBundleFileName);
let expressDevMiddleware;
let serverBundleComplete = false;

/**
 * setRenderer
 * whenever client file or server file change, renderer should be update
 */
const updateRenderer = () => {
	if (!serverBundleComplete) return;
	try {
		const options = {
			clientManifest: JSON.parse(expressDevMiddleware.fileSystem.readFileSync(clientManifestFilePath, 'utf-8'))
		};
		createRenderer(JSON.parse(mfs.readFileSync(serverBundleFilePath, 'utf-8')), options);
	} catch (e) {
		createRenderer(JSON.parse(mfs.readFileSync(serverBundleFilePath, 'utf-8')));
	}
};

// watch and update server renderer
const serverCompiler = webpack(serverConfig);
serverCompiler.outputFileSystem = mfs;
serverCompiler.watch({}, (err, stats) => {
	if (err) throw err;
	stats = stats.toJson();
	stats.errors.forEach(err => console.error(err));
	stats.warnings.forEach(err => console.warn(err));
	if (!serverBundleComplete) serverBundleComplete = true;
	setImmediate(updateRenderer);
});

const koaWebpackDevMiddleware = (compiler, opts) => {
	expressDevMiddleware = webpackDevMiddleware(compiler, opts);
	return async (ctx, next) => {
		await new Promise(resolve =>
			expressDevMiddleware(ctx.req, {
				end: (content) => {
					ctx.body = content;
					resolve();
				},
				setHeader: ctx.set.bind(ctx)
			}, () => resolve(next()))
		);
	};
};

const koaWebpackHotMiddleware = (compiler, opts) => {
	const expressMiddleware = webpackHotMiddleware(compiler, opts);
	return async (ctx, next) => {
		let stream = new PassThrough();
		ctx.body = stream;
		await expressMiddleware(ctx.req, {
			write: stream.write.bind(stream),
			writeHead: (state, headers) => {
				ctx.state = state;
				ctx.set(headers);
			}
		}, next);
	}
};

const clientCompiler = webpack(clientConfig);

const devMiddleware = koaWebpackDevMiddleware(clientCompiler, {
	// display no info to console (only warnings and errors)
	noInfo: false,
	stats: {
		colors: true,
		cached: false
	},
	contentBase: clientConfig.output.path,
	publicPath: clientConfig.output.publicPath
});

clientCompiler.plugin('done', updateRenderer);

const hotMiddleware = koaWebpackHotMiddleware(clientCompiler, {});

export {devMiddleware, hotMiddleware};
<|endoftext|>