<commit_before>window.InputController = (() => {
  return {
    init: () => {

      const formToJSON = elements => [].reduce.call(elements, (data, element) => {

        data[element.name] = element.value;
        return data;

      }, {});

      const handleFormSubmit = event => {

        const data = formToJSON(form.elements);

        // Trying Ajax:
        $.ajax({
          type: 'POST',
          url: "http://localhost:3000/case",
          data: JSON.stringify(data, null, "  "),
          contentType: "application/json",
          dataType: "json",
          accept: "application/json",
          processData: false,
          contentType: false,
          crossDomain: true, // Added
          success: function(data){
            alert(data);
          },
          complete: function () {
            console.log("DEBUG: Found data:")
            console.log(JSON.stringify(data, null, "  "));;
          }
        });

        // Trying request:
        // request('http://localhost:3000/case', { json: data }, (err, res, body) => {
        //   if (err) { return console.log(err); }
        //   console.log(body.url);
        //   console.log(body.explanation);
        // });

        // Trying Axios:
        // axios.post('http://localhost:3000/case', {firstName: 'joe'})
        //   .then(function(response) {
        //     console.log(response);
        //   })
        //   .catch(function(error) {
        //     console.log(error);
        //   });

      }

      const form = document.getElementsByClassName('caseForm')[0]
      form.addEventListener('submit', handleFormSubmit);

      $('#button-submit-forms').on('click', function(){
        handleFormSubmit();
      })

    }

  };

})();
<commit_msg>Refactored form submission, linked inputs<commit_after>window.InputController = (() => {
  return {
    init: () => {

      // Link UI inputs
      var drNumInput = $("#drNumInput");
      var masterDrNumInput = $("#masterDrNumInput");
      var divisionInput = $("#divisionInput");
      var bureauInput = $("#bureauInput");
      var notesInput = $("#notesInput");
      var dateOccuredInput = $("#dateOccuredInput");
      var dateReportedInput = $("#dateReportedInput");
      var reportingDistrictInput = $("#reportingDistrictInput");
      var caseStatusInput = $("#caseStatusInput");
      var caseStatusDateInput = $("#caseStatusDateInput");
      var solvabilityFactorInput = $("#solvabilityFactorInput");
      var weaponInput_handgun = $("#weaponInput_handgun");
      var weaponInput_rifle = $("#weaponInput_rifle");
      var weaponInput_bluntForce = $("#weaponInput_bluntForce");
      var weaponInput_bodilyForce = $("#weaponInput_bodilyForce");
      var weaponInput_knife = $("#weaponInput_knife");
      var weaponInput_unknown = $("#weaponInput_unknown");
      var motiveInput_robbery = $("#motiveInput_robbery");
      var motiveInput_burglary = $("#motiveInput_burglary");
      var motiveInput_gang = $("#motiveInput_gang");
      var motiveInput_narcotics = $("#motiveInput_narcotics");
      var motiveInput_domesticViolence = $("#motiveInput_domesticViolence");
      var motiveInput_dispute = $("#motiveInput_dispute");
      var motiveInput_accidental = $("#motiveInput_accidental");
      var motiveInput_selfDefense = $("#motiveInput_selfDefense");
      var motiveInput_unknown = $("#motiveInput_unknown");
      var streetNumberInput = $("#streetNumberInput");
      var streetNameInput = $("#streetNameInput");
      var cityInput = $("#cityInput");
      var zipCodeInput = $("#zipCodeInput");
      var victNameInput = $("#victNameInput");
      var victSexInput = $("#victSexInput");
      var victSupervisedReleaseStatusInput = $("#victSupervisedReleaseStatusInput");
      var victDescInput = $("#victDescInput");
      var victAgeInput = $("#victAgeInput");
      var victIdInput = $("#victIdInput");
      var suspNameInput = $("#suspNameInput");
      var suspSexInput = $("#suspSexInput");
      var suspSupervisedReleaseStatusInput = $("#suspSupervisedReleaseStatusInput");
      var suspDescInput = $("#suspDescInput");
      var suspAgeInput = $("#suspAgeInput");
      var suspIdInput = $("#suspIdInput");
      var newOrExistingVictimInput = $("#newOrExistingVictimInput");
      var newOrExistingSuspectInput = $("#newOrExistingSuspectInput");

      const formToJSON = elements => [].reduce.call(elements, (data, element) => {
        data[element.name] = element.value;
        return data;
      }, {});

      function attemptFormSubmission() {
        if (checkFormValidityAndAnnotate()) {
          submitCaseForm(getCaseDataAsJSON());
        }
      }

      function checkFormValidityAndAnnotate() {
        var isValid = true;
        if () {
          // TODO: Highlight UI
          isValid = false;
        } else if () {
          // TODO: Highlight UI
          isValid = false;
        }
        else {
          return isValid;
        }
      }

      function submitCaseForm(data) {

        const caseForm = document.getElementsByClassName('caseForm')[0]
        const caseData = formToJSON(caseForm.elements);

        // Trying Ajax:
        $.ajax({
          type: 'POST',
          url: "http://localhost:3000/case",
          data: JSON.stringify(data, null, "  "),
          contentType: "application/json",
          dataType: "json",
          accept: "application/json",
          processData: false,
          contentType: false,
          crossDomain: true, // Added
          success: function(data){
            alert(data);
          },
          complete: function () {
            console.log("DEBUG: Found data:")
            console.log(JSON.stringify(data, null, "  "));;
          }
        });

        // Trying request:
        // request('http://localhost:3000/case', { json: data }, (err, res, body) => {
        //   if (err) { return console.log(err); }
        //   console.log(body.url);
        //   console.log(body.explanation);
        // });

        // Trying Axios:
        // axios.post('http://localhost:3000/case', {firstName: 'joe'})
        //   .then(function(response) {
        //     console.log(response);
        //   })
        //   .catch(function(error) {
        //     console.log(error);
        //   });

      }

      function submitVictimForm(data) {
        // TODO
      }

      function submitSuspectForm(data) {
        // TODO
      }

      function getCaseDataAsJSON() {
        // TODO
      }

      // UI functionality

      $('#button-submit-forms').on('click', function(){
        attemptFormSubmission();
      })

      // TODO: hide/show UI

    }

  };

})();
<|endoftext|>


<commit_before>import _ from 'underscore';
import { shallowMount, createLocalVue } from '@vue/test-utils';
import createStore from '~/notes/stores';
import issueNote from '~/notes/components/noteable_note.vue';
import NoteHeader from '~/notes/components/note_header.vue';
import UserAvatarLink from '~/vue_shared/components/user_avatar/user_avatar_link.vue';
import NoteActions from '~/notes/components/note_actions.vue';
import NoteBody from '~/notes/components/note_body.vue';
import { noteableDataMock, notesDataMock, note } from '../mock_data';

describe('issue_note', () => {
  let store;
  let wrapper;

  beforeEach(() => {
    store = createStore();
    store.dispatch('setNoteableData', noteableDataMock);
    store.dispatch('setNotesData', notesDataMock);

    const localVue = createLocalVue();
    wrapper = shallowMount(issueNote, {
      store,
      propsData: {
        note,
      },
      sync: false,
      localVue,
    });
  });

  afterEach(() => {
    wrapper.destroy();
  });

  it('should render user information', () => {
    const { author } = note;
    const avatar = wrapper.find(UserAvatarLink);
    const avatarProps = avatar.props();

    expect(avatarProps.linkHref).toBe(author.path);
    expect(avatarProps.imgSrc).toBe(author.avatar_url);
    expect(avatarProps.imgAlt).toBe(author.name);
    expect(avatarProps.imgSize).toBe(40);
  });

  it('should render note header content', () => {
    const noteHeader = wrapper.find(NoteHeader);
    const noteHeaderProps = noteHeader.props();

    expect(noteHeaderProps.author).toEqual(note.author);
    expect(noteHeaderProps.createdAt).toEqual(note.created_at);
    expect(noteHeaderProps.noteId).toEqual(note.id);
  });

  it('should render note actions', () => {
    const { author } = note;
    const noteActions = wrapper.find(NoteActions);
    const noteActionsProps = noteActions.props();

    expect(noteActionsProps.authorId).toBe(author.id);
    expect(noteActionsProps.noteId).toBe(note.id);
    expect(noteActionsProps.noteUrl).toBe(note.noteable_note_url);
    expect(noteActionsProps.accessLevel).toBe(note.human_access);
    expect(noteActionsProps.canEdit).toBe(note.current_user.can_edit);
    expect(noteActionsProps.canAwardEmoji).toBe(note.current_user.can_award_emoji);
    expect(noteActionsProps.canDelete).toBe(note.current_user.can_edit);
    expect(noteActionsProps.canReportAsAbuse).toBe(true);
    expect(noteActionsProps.canResolve).toBe(false);
    expect(noteActionsProps.reportAbusePath).toBe(note.report_abuse_path);
    expect(noteActionsProps.resolvable).toBe(false);
    expect(noteActionsProps.isResolved).toBe(false);
    expect(noteActionsProps.isResolving).toBe(false);
    expect(noteActionsProps.resolvedBy).toEqual({});
  });

  it('should render issue body', () => {
    const noteBody = wrapper.find(NoteBody);
    const noteBodyProps = noteBody.props();

    expect(noteBodyProps.note).toEqual(note);
    expect(noteBodyProps.line).toBe(null);
    expect(noteBodyProps.canEdit).toBe(note.current_user.can_edit);
    expect(noteBodyProps.isEditing).toBe(false);
    expect(noteBodyProps.helpPagePath).toBe('');
  });

  it('prevents note preview xss', done => {
    const imgSrc = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
    const noteBody = `<img src="${imgSrc}" onload="alert(1)" />`;
    const alertSpy = spyOn(window, 'alert');
    store.hotUpdate({
      actions: {
        updateNote() {},
      },
    });
    const noteBodyComponent = wrapper.find(NoteBody);

    noteBodyComponent.vm.$emit('handleFormUpdate', noteBody, null, () => {});

    setTimeout(() => {
      expect(alertSpy).not.toHaveBeenCalled();
      expect(wrapper.vm.note.note_html).toEqual(_.escape(noteBody));
      done();
    }, 0);
  });

  describe('cancel edit', () => {
    it('restores content of updated note', done => {
      const noteBody = 'updated note text';
      store.hotUpdate({
        actions: {
          updateNote() {},
        },
      });
      const noteBodyComponent = wrapper.find(NoteBody);
      noteBodyComponent.vm.resetAutoSave = () => {};

      noteBodyComponent.vm.$emit('handleFormUpdate', noteBody, null, () => {});

      setTimeout(() => {
        expect(wrapper.vm.note.note_html).toEqual(noteBody);

        noteBodyComponent.vm.$emit('cancelForm');

        setTimeout(() => {
          expect(wrapper.vm.note.note_html).toEqual(noteBody);

          done();
        });
      });
    });
  });
});
<commit_msg>Revert "Convert noteable_note_spec.js to Vue test utils"<commit_after>import $ from 'jquery';
import _ from 'underscore';
import Vue from 'vue';
import createStore from '~/notes/stores';
import issueNote from '~/notes/components/noteable_note.vue';
import { noteableDataMock, notesDataMock, note } from '../mock_data';

describe('issue_note', () => {
  let store;
  let vm;

  beforeEach(() => {
    const Component = Vue.extend(issueNote);

    store = createStore();
    store.dispatch('setNoteableData', noteableDataMock);
    store.dispatch('setNotesData', notesDataMock);

    vm = new Component({
      store,
      propsData: {
        note,
      },
    }).$mount();
  });

  afterEach(() => {
    vm.$destroy();
  });

  it('should render user information', () => {
    expect(vm.$el.querySelector('.user-avatar-link img').getAttribute('src')).toEqual(
      note.author.avatar_url,
    );
  });

  it('should render note header content', () => {
    const el = vm.$el.querySelector('.note-header .note-header-author-name');

    expect(el.textContent.trim()).toEqual(note.author.name);
  });

  it('should render note actions', () => {
    expect(vm.$el.querySelector('.note-actions')).toBeDefined();
  });

  it('should render issue body', () => {
    expect(vm.$el.querySelector('.note-text').innerHTML).toEqual(note.note_html);
  });

  it('prevents note preview xss', done => {
    const imgSrc = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
    const noteBody = `<img src="${imgSrc}" onload="alert(1)" />`;
    const alertSpy = spyOn(window, 'alert');
    vm.updateNote = () => new Promise($.noop);

    vm.formUpdateHandler(noteBody, null, $.noop);

    setTimeout(() => {
      expect(alertSpy).not.toHaveBeenCalled();
      expect(vm.note.note_html).toEqual(_.escape(noteBody));
      done();
    }, 0);
  });

  describe('cancel edit', () => {
    it('restores content of updated note', done => {
      const noteBody = 'updated note text';
      vm.updateNote = () => Promise.resolve();

      vm.formUpdateHandler(noteBody, null, $.noop);

      setTimeout(() => {
        expect(vm.note.note_html).toEqual(noteBody);

        vm.formCancelHandler();

        setTimeout(() => {
          expect(vm.note.note_html).toEqual(noteBody);

          done();
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc service
 * @name dormManagementToolApp.userService
 * @description
 * # userService
 * Service in the dormManagementToolApp.
 */
angular.module('dormManagementToolApp')
  .service('UserService', function () {
    this.getName = function () {
      return localStorage.getItem('user').name;
    }
  });
<commit_msg>Fix bug<commit_after>'use strict';

/**
 * @ngdoc service
 * @name dormManagementToolApp.userService
 * @description
 * # userService
 * Service in the dormManagementToolApp.
 */
angular.module('dormManagementToolApp')
  .service('UserService', function () {
    this.getName = function () {
      return JSON.parse(localStorage.getItem('user')).name;
    }
  });
<|endoftext|>


<commit_before>/*
 * dropDownSreachType.js 文件功能是
 *	在用户用了图书搜索功能后，页面先是会把匹配到 关键字的数据进行输出，
 *	此时，坐上方的 “搜索类型下拉框” 和 “搜索框” 依旧要保持用户搜索时的样子，不能恢复默认。
 *
 *	举个例子：用户选择了 “按书架” 搜索类型去搜索 “小说区” 然后点击了搜索按钮，之后
 *				页面显示出了数据，页面上方的 “搜索类型下拉框” 要自动选择 “按书架” 还有
 *				“ 搜索框” 也要自动填上用户之前输入的 “小说区”
 */

/*
 * 在 “ 搜索类型下拉框 ” 选定了搜索类型后，将此类型的文本（例如：按书架），放入到
 * javascript 的 session 中，以便查询出数据后的页面刷新后 “ 搜索类型下拉框 ” 还能自动选择
 * 搜索类型。
 */
function recordSreachType()
{
	options = $('.options li');
	//sessionStorage.sreachType = null; // 默认
	options.click(function(){
		sessionStorage.sreachType = $(this).text();
	});

	// 在初进入到 图书搜索页面时, 将默认选择的搜索类型放入到 session，以防止使用搜索功能后，因为 session 的值
	// 还是上一次的，而导致搜索前 和 搜索后 的搜索类型下拉框的值不匹配的问题 ( 要是不懂，可以把下面的小段注释掉)
	options.each(function(){
		if ( $(this).attr('class') = 'selected' ){
			sessionStorage.sreachType = $(this).text();
		}
	});
}

/*
 * 根据 session 中的 sreachType 在 " 搜索类型下拉框 " 中选择相应的类型。
 * 因为我引用了一个外部的下拉框样式, 因此选中的时候有两层, 一层是真实的 <select><option>,
 * 而另外一层则是使用

 和 jQuery 所模拟出来的下拉框样式
 * 因此，在下面的程序中选择下拉框样式，一要给真实层加上 class='select' (为了提交时能匹配搜索
 * 类型) , 二要给
 中相应的
 模拟层加上 class='selected' ( 为了页面上能显示出来我们
 * 选中了哪个)
 */
function selectOptionBySession()
{

	// 当图书搜索 是已经进行了一次搜索后跳转到的页面才需要记住 “ 搜索类型下拉框 ” 的类型, 由其他
	// 页面的第一次进入则不用提前选择，只要默认的就好啦。
	if ( document.referrer != 'http://localhost/Library-Management-System/web/book-sreach/sreach'){
		return;
	}

	var sreachType = sessionStorage.sreachType;

	// 模拟层的 options
	options = $('.options li');
	options.each(function(){

		var optionText = $(this).text();
		if( sreachType == optionText ){

			$(this).addClass('selected');
			$('.trigger').text( sreachType );
			$('.trigger').addClass('selected');
		}

	});

	// 真实层的 optionList
	optionList = $('.basic-usage-demo option');
	optionList.each(function(){

		var optionText =$(this).text();
		if( sreachType == optionText ){

			$(this).attr('selected', 'selected');
		}
	});

}

<commit_msg> 图书搜索类型下拉框 的 js 交互逻辑 优化<commit_after>/*
 * dropDownSreachType.js 文件功能是
 *	在用户用了图书搜索功能后，页面先是会把匹配到 关键字的数据进行输出，
 *	此时，坐上方的 “搜索类型下拉框” 和 “搜索框” 依旧要保持用户搜索时的样子，不能恢复默认。
 *
 *	举个例子：用户选择了 “按书架” 搜索类型去搜索 “小说区” 然后点击了搜索按钮，之后
 *				页面显示出了数据，页面上方的 “搜索类型下拉框” 要自动选择 “按书架” 还有
 *				“ 搜索框” 也要自动填上用户之前输入的 “小说区”
 */

/*
 * 在 “ 搜索类型下拉框 ” 选定了搜索类型后，将此类型的文本（例如：按书架），放入到
 * javascript 的 session 中，以便查询出数据后的页面刷新后 “ 搜索类型下拉框 ” 还能自动选择
 * 搜索类型。
 */
function recordSreachType()
{
	options = $('.options li');
	//sessionStorage.sreachType = null; // 默认
	options.click(function(){
		sessionStorage.sreachType = $(this).text();
	});

}

/**
 * 在点击 图书搜索 页面的搜索按钮时，把当时 " 搜索类型下拉框 " 的值放入 session
 */
function recordSreachTypeByClickSreachBtn()
{
	options   = $('.options li');
	sreachBtn = $('.sreach-btn');

	sreachBtn.click(function(){
		options.each(function(){

			if ( $(this).attr('class') == 'selected' ){
				sessionStorage.sreachType = $(this).text();
				//alert( sessionStorage.sreachType );
				//return false;
			}
		});
	});

}

/*
 * 根据 session 中的 sreachType 在 " 搜索类型下拉框 " 中选择相应的类型。
 * 因为我引用了一个外部的下拉框样式, 因此选中的时候有两层, 一层是真实的 <select><option>,
 * 而另外一层则是使用

 和 jQuery 所模拟出来的下拉框样式
 * 因此，在下面的程序中选择下拉框样式，一要给真实层加上 class='select' (为了提交时能匹配搜索
 * 类型) , 二要给
 中相应的
 模拟层加上 class='selected' ( 为了页面上能显示出来我们
 * 选中了哪个)
 */
function selectOptionBySession()
{

	var sreachType = sessionStorage.sreachType;

	// 模拟层的 options
	options = $('.options li');
	options.each(function(){

		var optionText = $(this).text();
		if( sreachType == optionText ){

			$(this).addClass('selected');
			$('.trigger').text( sreachType );
			$('.trigger').addClass('selected');
		}

	});

	// 真实层的 optionList
	optionList = $('.basic-usage-demo option');
	optionList.each(function(){

		var optionText =$(this).text();
		if( sreachType == optionText ){

			$(this).attr('selected', 'selected');
		}
	});

}

<|endoftext|>


<commit_before>var drawNodes = [];
var svgWrapper = null;
var start = null;
var outline = null;
var offset = null;

// $('#svgArea').svg({onLoad: function(svg) {
//         svgWrapper = svg;
//         var surface = svg.rect(0, 0, '100%', '100%', {id: 'surface', fill: 'white'});
//         $(surface).mousedown(startDrag).mousemove(dragging).mouseup(endDrag);
//         resetSize(svg, '100%', '100%');
//     }
// });

/* Remember where we started */
function startDrag(event) {
    // offset = ($.browser.msie ? {left: 0, top: 0} : $('#svgArea').offset());
    offset = (!$.support.opacity ? {left: 0, top: 0} : $('#svgArea').offset());
    // if (!$.browser.msie) {
    if ($.support.opacity) {
        offset.left -= document.documentElement.scrollLeft || document.body.scrollLeft;
        offset.top -= document.documentElement.scrollTop || document.body.scrollTop;
    }
    start = {X: event.clientX - offset.left, Y: event.clientY - offset.top};
    event.preventDefault();
}

/* Provide feedback as we drag */
function dragging(event) {
    if (!start) {
        return;
    }
    if (!outline) {
        outline = svgWrapper.rect(0, 0, 0, 0,
            {fill: 'none', stroke: '#c0c0c0', strokeWidth: 1, strokeDashArray: '2,2'});
        $(outline).mouseup(endDrag);
    }
    svgWrapper.change(outline, {x: Math.min(event.clientX - offset.left, start.X),
        y: Math.min(event.clientY - offset.top, start.Y),
        width: Math.abs(event.clientX - offset.left - start.X),
        height: Math.abs(event.clientY - offset.top - start.Y)});
    event.preventDefault();
}

/* Draw where we finish */
function endDrag(event) {
    if (!start) {
        return;
    }
    $(outline).remove();
    outline = null;
    var end = {X: event.clientX - offset.left, Y:event.clientY - offset.top};
    if (start.X != end.X) {
        // 開始／終了の予定X座標が同じ場合はなにもしない（幅がない）
        drawShape(start.X, start.Y, end.X, end.Y);

        var $scope = angular.element('#content').scope();
        // $scope.export2canvas();
        if ($scope.conf.autoSave) {
          $scope.savePNG();
        }
    }
    start = null;
    event.preventDefault();

}

/* Draw the selected element on the canvas */
function drawShape(x1, y1, x2, y2) {
    var left = Math.min(x1, x2);
    var top = Math.min(y1, y2);
    var right = Math.max(x1, x2);
    var bottom = Math.max(y1, y2);
    var settings = {fill: $('#fill').val(), stroke: $('#stroke').val(),
        strokeWidth: $('#swidth').val()};
    var shape = $('#shape').val();
    var node = null;

    var scale = ((right - left)/95);
    var $scope = angular.element('#content').scope();
    var mayugeColor = $('select[name="colorpicker4mayuge"]').val();
    var rinkakuColor = $('select[name="colorpicker4rinkaku"]').val();
    var rinkakuWidth = $('select[name="rinkakuWidth"]').val();
    if ($scope.conf.optionsLR == "r") {
        node = svgWrapper.group({class_: "draggable", transform: "translate(" + right + "," + bottom + ")"});
        svgWrapper.use(node, "#path-r-mayuge-" + $scope.conf.mayugeType, {fill: mayugeColor, transform: "scale(" + scale + ")", stroke: rinkakuColor, strokeWidth: rinkakuWidth});
    } else {
        node = svgWrapper.group({class_: "draggable", transform: "translate(" + (right - (right - left)) + "," + bottom + ")"});
        svgWrapper.use(node, "#path-r-mayuge-" + $scope.conf.mayugeType, {fill: mayugeColor, transform: "scale(-" + scale + "," + scale + ")", stroke: rinkakuColor, strokeWidth: rinkakuWidth});
    }

    var makeSVGElementDraggable = svgDrag.setupCanvasForDragging();
    makeSVGElementDraggable(node);
    // node.addEventListener("mouseup", $scope.export2canvas);
    node.addEventListener("click", function() {$scope.selectMayuge($(node))});
    node.addEventListener("dblclick", function() {$scope.removeMayuge($(node));});
    $scope.export2canvas();
    // if ($scope.conf.autoSave) {
    //   $scope.savePNG();
    // }

    drawNodes[drawNodes.length] = node;
    // $(node).mousedown(startDrag).mousemove(dragging).mouseup(endDrag);
    $('#svgArea').focus();
};

/* Remove the last drawn element */
$('#undo').click(function() {
    if (!drawNodes.length) {
        return;
    }
    svgWrapper.remove(drawNodes[drawNodes.length - 1]);
    drawNodes.splice(drawNodes.length - 1, 1);
});

/* Clear the canvas */
$('#clear2').click(function() {
    while (drawNodes.length) {
        $('#undo').trigger('click');
    }
});

/* Convert to text */
$('#toSVG').click(function() {
    alert(svgWrapper.toSVG());
});<commit_msg>drag開始点の取得ロジックを修正。<commit_after>var drawNodes = [];
var svgWrapper = null;
var start = null;
var outline = null;
var offset = null;

/* Remember where we started */
function startDrag(event) {
    offset = $('#svgArea').offset();
    start = {X: event.clientX - offset.left, Y: event.clientY - offset.top};
    event.preventDefault();
}

/* Provide feedback as we drag */
function dragging(event) {
    if (!start) {
        return;
    }
    if (!outline) {
        outline = svgWrapper.rect(0, 0, 0, 0,
            {fill: 'none', stroke: '#c0c0c0', strokeWidth: 1, strokeDashArray: '2,2'});
        $(outline).mouseup(endDrag);
    }
    svgWrapper.change(outline, {x: Math.min(event.clientX - offset.left, start.X),
        y: Math.min(event.clientY - offset.top, start.Y),
        width: Math.abs(event.clientX - offset.left - start.X),
        height: Math.abs(event.clientY - offset.top - start.Y)});
    event.preventDefault();
}

/* Draw where we finish */
function endDrag(event) {
    if (!start) {
        return;
    }
    $(outline).remove();
    outline = null;
    var end = {X: event.clientX - offset.left, Y:event.clientY - offset.top};
    if (start.X != end.X) {
        // 開始／終了の予定X座標が同じ場合はなにもしない（幅がない）
        drawShape(start.X, start.Y, end.X, end.Y);

        var $scope = angular.element('#content').scope();
        // $scope.export2canvas();
        if ($scope.conf.autoSave) {
          $scope.savePNG();
        }
    }
    start = null;
    event.preventDefault();

}

/* Draw the selected element on the canvas */
function drawShape(x1, y1, x2, y2) {
    var left = Math.min(x1, x2);
    var top = Math.min(y1, y2);
    var right = Math.max(x1, x2);
    var bottom = Math.max(y1, y2);
    var settings = {fill: $('#fill').val(), stroke: $('#stroke').val(),
        strokeWidth: $('#swidth').val()};
    var shape = $('#shape').val();
    var node = null;

    var scale = ((right - left)/95);
    var $scope = angular.element('#content').scope();
    var mayugeColor = $('select[name="colorpicker4mayuge"]').val();
    var rinkakuColor = $('select[name="colorpicker4rinkaku"]').val();
    var rinkakuWidth = $('select[name="rinkakuWidth"]').val();
    if ($scope.conf.optionsLR == "r") {
        node = svgWrapper.group({class_: "draggable", transform: "translate(" + right + "," + bottom + ")"});
        svgWrapper.use(node, "#path-r-mayuge-" + $scope.conf.mayugeType, {fill: mayugeColor, transform: "scale(" + scale + ")", stroke: rinkakuColor, strokeWidth: rinkakuWidth});
    } else {
        node = svgWrapper.group({class_: "draggable", transform: "translate(" + (right - (right - left)) + "," + bottom + ")"});
        svgWrapper.use(node, "#path-r-mayuge-" + $scope.conf.mayugeType, {fill: mayugeColor, transform: "scale(-" + scale + "," + scale + ")", stroke: rinkakuColor, strokeWidth: rinkakuWidth});
    }

    var makeSVGElementDraggable = svgDrag.setupCanvasForDragging();
    makeSVGElementDraggable(node);
    // node.addEventListener("mouseup", $scope.export2canvas);
    node.addEventListener("click", function() {$scope.selectMayuge($(node))});
    node.addEventListener("dblclick", function() {$scope.removeMayuge($(node));});
    $scope.export2canvas();
    // if ($scope.conf.autoSave) {
    //   $scope.savePNG();
    // }

    drawNodes[drawNodes.length] = node;
    // $(node).mousedown(startDrag).mousemove(dragging).mouseup(endDrag);
    $('#svgArea').focus();
};

/* Remove the last drawn element */
$('#undo').click(function() {
    if (!drawNodes.length) {
        return;
    }
    svgWrapper.remove(drawNodes[drawNodes.length - 1]);
    drawNodes.splice(drawNodes.length - 1, 1);
});

/* Clear the canvas */
$('#clear2').click(function() {
    while (drawNodes.length) {
        $('#undo').trigger('click');
    }
});

/* Convert to text */
$('#toSVG').click(function() {
    alert(svgWrapper.toSVG());
});<|endoftext|>


<commit_before>import React, {PropTypes}         from 'react';
import Tock                       from 'tocktimer';
import moment                     from 'moment';
import { connect }                from 'react-redux';
import classnames                 from 'classnames';
import Actions                    from '../../actions/timer';
import { appendTimeEntry }        from '../../actions/time_entries';
import {
  timexDateTimeToString,
  setDocumentTitle,
  formatDuration }                from '../../utils';

class Timer extends React.Component {
  componentDidMount() {
    const { timeEntry } = this.props;

    if (timeEntry != null) this._startTimer(timeEntry);
  }

  componentDidUpdate() {
    const { timeEntry, started } = this.props;

    if (timeEntry != null && !started) this._startTimer(timeEntry);
  }

  componentWillUnmount() {
    if (!this.timer) return false;

    this.timer.stop();
    this.timer = null;
  }

  _handleButtonClick() {
    this.props.started ? this._stop() : this._start();
  }

  _start() {
    const startedAt = moment.utc().toISOString();
    const { time, description } = this.refs;
    const { start, dispatch, duration, channel } = this.props;

    const timeEntry = {
      started_at: startedAt,
      description: description.value.trim(),
      workspace_id: null,
    };

    channel.push('time_entry:start', timeEntry)
    .receive('ok', (data) => {
      this._startTimer(data);
    });
  }

  _stop() {
    const stoppedAt = moment().toISOString();
    const { timeEntry, channel, dispatch } = this.props;

    timeEntry.stopped_at = stoppedAt;

    channel.push('time_entry:stop', timeEntry)
    .receive('ok', (data) => {
      dispatch(appendTimeEntry(data));

      this._resetTimer();
    });

  }

  _handleDiscardClick(e) {
    e.preventDefault();

    const { timeEntry, channel } = this.props;

    channel.push('time_entry:discard', timeEntry)
    .receive('ok', (data) => {
      this._resetTimer();
    });
  }

  _resetTimer() {
    const { time, description } = this.refs;
    const { dispatch } = this.props;

    this.timer.stop();
    this.timer = null;
    time.value = '0 sec';
    description.value = '';

    setDocumentTitle('Home');
    dispatch(Actions.stop());
  }

  _startTimer(timeEntry) {
    const { dispatch, started } = this.props;
    const { time, description, duration } = this.refs;

    description.value = timeEntry.description;

    const timer = new Tock({
      start: '00:00:00',
      callback: () => {
        const currentTime = moment.duration(timer.lap());
        const timeText = formatDuration(currentTime);
        time.value = timeText;

        setDocumentTitle(`${timeText} - ${description.value.trim()}`);
      },
    });

    if (timeEntry.restarted_at != null) {
      const timeEntryStart = moment.utc(timexDateTimeToString(timeEntry.restarted_at), 'YYYY-M-D H:m:s');
      const initialTime = moment.utc().diff(moment(timeEntryStart), 'milliseconds');

      timer.start((timeEntry.duration * 1000) + initialTime);
    } else {
      const timeEntryStart = moment.utc(timexDateTimeToString(timeEntry.started_at), 'YYYY-M-D H:m:s');
      const initialTime = moment.utc().diff(moment(timeEntryStart), 'milliseconds');

      timer.start(initialTime);
    }

    this.timer = timer;

    dispatch(Actions.start(timeEntry));
  }

  _timeValue(value) {
    if (value < 10) return '0' + value;

    return value;
  }

  _buttonText() {
    const { started } = this.props;

    return started ? 'Stop' : 'Start';
  }

  _updateTimeEntryDescription() {
    const { timeEntry, channel } = this.props;
    const { description } = this.refs;

    if (timeEntry == null) return false;
    if (timeEntry != null && timeEntry.description === description.value) return false;

    channel.push('time_entry:update', { description: description.value.trim() });
  }

  _handleDescriptionKeyUp(e) {
    if (e.which != 13) return false;

    this._updateTimeEntryDescription();
  }

  _renderDiscardLink() {
    const { started } = this.props;

    if (!started) return false;

    return (
      Discard
    );
  }

  render() {
    const { started } = this.props;

    const buttonClasses = classnames({
      'btn-start': true,
      started: !started,
    });

    return (

          {::this._renderDiscardLink()}

            <input
              type="text"
              ref="description"
              placeholder="What are you working on?"
              tabIndex="1"
              onBlur={::this._updateTimeEntryDescription}
              onKeyUp={::this._handleDescriptionKeyUp}/>

            <input
              ref="time"
              placeholder="0 sec"
              type="text"
              maxLength="10"
              tabIndex="2"
              readOnly={true}/>

            <button
              tabIndex="3"
              className={buttonClasses}
              onClick={::this._handleButtonClick}>{::this._buttonText()}</button>

    );
  }
}

const mapStateToProps = (state) => (
  { ...state.timeEntry, channel: state.session.channel }
);

export default connect(mapStateToProps)(Timer);
<commit_msg>Renamed stop method<commit_after>import React, {PropTypes}         from 'react';
import Tock                       from 'tocktimer';
import moment                     from 'moment';
import { connect }                from 'react-redux';
import classnames                 from 'classnames';
import Actions                    from '../../actions/timer';
import { appendTimeEntry }        from '../../actions/time_entries';
import {
  timexDateTimeToString,
  setDocumentTitle,
  formatDuration }                from '../../utils';

export default class Timer extends React.Component {
  componentDidMount() {
    const { timeEntry } = this.props;

    if (timeEntry != null) this._startTimer(timeEntry);
  }

  componentDidUpdate() {
    const { timeEntry, started } = this.props;

    if (timeEntry != null && !started) this._startTimer(timeEntry);
  }

  componentWillUnmount() {
    if (!this.timer) return false;

    this.timer.stop();
    this.timer = null;
  }

  _handleButtonClick() {
    this.props.started ? this.stop() : this._start();
  }

  _start() {
    const startedAt = moment.utc().toISOString();
    const { time, description } = this.refs;
    const { start, dispatch, duration, channel } = this.props;

    const timeEntry = {
      started_at: startedAt,
      description: description.value.trim(),
      workspace_id: null,
    };

    channel.push('time_entry:start', timeEntry)
    .receive('ok', (data) => {
      this._startTimer(data);
    });
  }

  stop() {
    const stoppedAt = moment().toISOString();
    const { timeEntry, channel, dispatch } = this.props;

    timeEntry.stopped_at = stoppedAt;

    channel.push('time_entry:stop', timeEntry)
    .receive('ok', (data) => {
      dispatch(appendTimeEntry(data));

      this._resetTimer();
    });

  }

  _handleDiscardClick(e) {
    e.preventDefault();

    const { timeEntry, channel } = this.props;

    channel.push('time_entry:discard', timeEntry)
    .receive('ok', (data) => {
      this._resetTimer();
    });
  }

  _resetTimer() {
    const { time, description } = this.refs;
    const { dispatch } = this.props;

    this.timer.stop();
    this.timer = null;
    time.value = '0 sec';
    description.value = '';

    setDocumentTitle('Home');
    dispatch(Actions.stop());
  }

  _startTimer(timeEntry) {
    const { dispatch, started } = this.props;
    const { time, description, duration } = this.refs;

    description.value = timeEntry.description;

    const timer = new Tock({
      start: '00:00:00',
      callback: () => {
        const currentTime = moment.duration(timer.lap());
        const timeText = formatDuration(currentTime);
        time.value = timeText;

        setDocumentTitle(`${timeText} - ${description.value.trim()}`);
      },
    });

    if (timeEntry.restarted_at != null) {
      const timeEntryStart = moment.utc(timexDateTimeToString(timeEntry.restarted_at), 'YYYY-M-D H:m:s');
      const initialTime = moment.utc().diff(moment(timeEntryStart), 'milliseconds');

      timer.start((timeEntry.duration * 1000) + initialTime);
    } else {
      const timeEntryStart = moment.utc(timexDateTimeToString(timeEntry.started_at), 'YYYY-M-D H:m:s');
      const initialTime = moment.utc().diff(moment(timeEntryStart), 'milliseconds');

      timer.start(initialTime);
    }

    this.timer = timer;

    dispatch(Actions.start(timeEntry));
  }

  _timeValue(value) {
    if (value < 10) return '0' + value;

    return value;
  }

  _buttonText() {
    const { started } = this.props;

    return started ? 'Stop' : 'Start';
  }

  _updateTimeEntryDescription() {
    const { timeEntry, channel } = this.props;
    const { description } = this.refs;

    if (timeEntry == null) return false;
    if (timeEntry != null && timeEntry.description === description.value) return false;

    channel.push('time_entry:update', { description: description.value.trim() });
  }

  _handleDescriptionKeyUp(e) {
    if (e.which != 13) return false;

    this._updateTimeEntryDescription();
  }

  _renderDiscardLink() {
    const { started } = this.props;

    if (!started) return false;

    return (
      Discard
    );
  }

  render() {
    const { started } = this.props;

    const buttonClasses = classnames({
      'btn-start': true,
      started: !started,
    });

    return (

          {::this._renderDiscardLink()}

            <input
              type="text"
              ref="description"
              placeholder="What are you working on?"
              tabIndex="1"
              onBlur={::this._updateTimeEntryDescription}
              onKeyUp={::this._handleDescriptionKeyUp}/>

            <input
              ref="time"
              placeholder="0 sec"
              type="text"
              maxLength="10"
              tabIndex="2"
              readOnly={true}/>

            <button
              tabIndex="3"
              className={buttonClasses}
              onClick={::this._handleButtonClick}>{::this._buttonText()}</button>

    );
  }
}
<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc service
 * @name oncokbApp.importer
 * @description
 * # importer
 * Service in the oncokbApp.
 */
angular.module('oncokbApp')
    .service('importer', function importer($timeout, documents, S, storage, OncoKB, $q, _, stringUtils) {
        var self = {};
        self.docs = [];
        self.docsL = 0;
        self.newFolder = '';
        self.parentFolder = OncoKB.config.backupFolderId; // backup folder under knowledgebase
        self.status = {
            backupIndex: -1,
            migrateIndex: -1
        };

        function backup(callback) {
            if (self.parentFolder) {
                if (!angular.isFunction(callback)) {
                    callback = undefined;
                }

                createFolder().then(function(result) {
                    if (result && result.error) {
                        console.error('Create folder failed.', result);
                        if (callback) {
                            callback();
                        }
                    } else {
                        // var docs = documents.get({title: 'BRAF'});
                        self.docs = documents.get();
                        self.docsL = self.docs.length;
                        copyData(0, callback);
                    }
                });
            } else {
                console.log('Backup folder ID needed.');
            }
        }

        function createFolder() {
            var deferred = $q.defer();

            storage.requireAuth(true).then(function(result) {
                if (result && !result.error) {
                    storage.createFolder(self.parentFolder).then(function(result) {
                        if (result.id) {
                            self.newFolder = result.id;
                            deferred.resolve(result);
                        } else {
                            deferred.reject(result);
                        }
                    });
                }
            });

            return deferred.promise;
        }

        function copyData(index, callback) {
            if (index < self.docs.length) {
                var doc = self.docs[index];
                copyFileData(self.newFolder, doc.id, doc.title, index).then(function() {
                    if ((index + 1) % 50 === 0) {
                        console.log('copied another 50 genes, waiting 5s...');
                        $timeout(function() {
                            copyData(++index, callback);
                        }, 5000, false);
                    } else {
                        copyData(++index, callback);
                    }
                });
            } else {
                if (callback) {
                    callback();
                }
                console.log('finished');
            }
        }

        function migrate() {
            var destinationFolderId = '';
            var deferred = $q.defer();

            destinationFolderId = '0BzBfo69g8fP6RmczanJFSVlNSjA';

            if (destinationFolderId) {
                self.newFolder = destinationFolderId;
                self.docs = documents.get();
                self.docsL = self.docs.length;

                // copy foler permissions
                // assignPermission(OncoKB.config.folderId, self.newFolder)
                //    .then(function(result){
                //      if(result && result.error){
                //        console.log('Error when assigning folder permissions', result);
                //      }else{
                migrateOneFileProcess(0, deferred);
                // }
                // });
            } else {
                createFolder().then(function(result) {
                    if (result && result.error) {
                        console.log('Unable create folder.', result);
                    } else {
                        self.docs = documents.get();
                        self.docsL = self.docs.length;

                        // copy foler permissions
                        assignPermission(OncoKB.config.folderId, self.newFolder)
                            .then(function(result) {
                                if (result && result.error) {
                                    console.log('Error when assigning folder permissions', result);
                                } else {
                                    migrateOneFileProcess(0, deferred);
                                }
                            });
                    }
                });
            }

            return deferred.promise;
        }

        function migrateOneFileProcess(docIndex, deferred) {
            if (docIndex < self.docsL) {
                var doc = self.docs[docIndex];
                copyFileData(self.newFolder, doc.id, doc.title, docIndex)
                    .then(function(result) {
                        if (result && result.error) {
                            console.log(result);
                            migrateOneFileProcess(++docIndex, deferred);
                        } else {
                            assignPermission(doc.id, result.id)
                                .then(function(result) {
                                    if (result && result.error) {
                                        console.log('error', result);
                                    } else {
                                        migrateOneFileProcess(++docIndex, deferred);
                                    }
                                });
                        }
                    });
            } else {
                console.log('Migrating finished.');
                deferred.resolve();
            }
        }

        function assignPermission(oldDocId, newDocId) {
            var deferred = $q.defer();
            console.log('\t Giving permissions');
            storage.getPermission(oldDocId).then(function(result) {
                if (result && result.error) {
                    deferred.reject(result);
                } else {
                    assignIndividualPermission(newDocId, result.items, 0, deferred);
                    // var promises = [];
                    // promises = result.items.forEach(function(permission, i){
                    //  if(permission.id && permission.emailAddress && permission.role && permission.type && permission.role !== 'owner'){
                    //    promises.push();
                    //  }
                    // });
                    // $q.all(promises).then(function(){
                    //  deferred.resolve();
                    // });
                }
            });
            return deferred.promise;
        }

        function assignIndividualPermission(newDocId, items, itemIndex, deferred) {
            if (itemIndex < items.length) {
                var permission = items[itemIndex];
                console.log('\t\t\tp-', itemIndex + 1);
                if (permission.id && permission.emailAddress && permission.role && permission.type && permission.role !== 'owner') {
                    storage.insertPermission(newDocId, permission.emailAddress, permission.type, permission.role).then(function() {
                        // $timeout(function () {
                        assignIndividualPermission(newDocId, items, ++itemIndex, deferred);
                        // }, 100);
                    });
                } else {
                    console.log('\t\t\tskip-', permission);
                    // $timeout(function () {
                    assignIndividualPermission(newDocId, items, ++itemIndex, deferred);
                    // }, 100);
                }
            } else {
                deferred.resolve();
                console.log('\t\tAll permissions are assigned.');
            }
        }

        function createVUSItem(vusItem, vusModel, model) {
            var vus = model.create(OncoKB.VUSItem);

            vus.name.setText(vusItem.name);
            _.each(vusItem.time, function(time) {
                var timeStamp = model.create(OncoKB.TimeStampWithCurator);
                timeStamp.value.setText(time.value);
                timeStamp.by.name.setText(time.by.name);
                timeStamp.by.email.setText(time.by.email);
                vus.time.push(timeStamp);
            });

            if (vusItem.nameComments) {
                _.each(vusItem.nameComments, function(comment) {
                    var _comment = model.create('Comment');
                    _comment.date.setText(comment.date);
                    _comment.userName.setText(comment.userName);
                    _comment.email.setText(comment.email);
                    _comment.content.setText(comment.content);
                    _comment.resolved.setText(comment.resolved);
                    vus.name_comments.push(_comment);
                });
            }
            vusModel.push(vus);
        }

        function copyFileData(folderId, fileId, fileTitle, docIndex) {
            var deferred = $q.defer();
            storage.requireAuth(true).then(function() {
                storage.createDocument(fileTitle, folderId).then(function(file) {
                    console.log('Created file ', fileTitle, docIndex + 1);
                    storage.getRealtimeDocument(fileId).then(function(realtime) {
                        if (realtime && realtime.error) {
                            console.log('did not get realtime document.');
                        } else {
                            console.log('\t Copying');
                            var gene = realtime.getModel().getRoot().get('gene');
                            var vus = realtime.getModel().getRoot().get('vus');
                            if (gene) {
                                var geneData = stringUtils.getGeneData(gene);
                                var vusData = stringUtils.getVUSFullData(vus);
                                storage.getRealtimeDocument(file.id).then(function(newRealtime) {
                                    var model = createModel(newRealtime.getModel());
                                    var geneModel = model.getRoot().get('gene');
                                    var vusModel = model.getRoot().get('vus');

                                    model.beginCompoundOperation();
                                    for (var key in geneData) {
                                        if (geneModel[key]) {
                                            geneModel = setValue(model, geneModel, geneData[key], key);
                                        }
                                    }

                                    if (vusData) {
                                        _.each(vusData, function(vusItem) {
                                            createVUSItem(vusItem, vusModel, newRealtime.getModel());
                                        });
                                    }
                                    model.endCompoundOperation();
                                    console.log('\t Done.');
                                    $timeout(function() {
                                        deferred.resolve(file);
                                    }, 500, false);
                                });
                            } else {
                                console.log('\t\tNo gene model.');
                                $timeout(function() {
                                    deferred.resolve(file);
                                }, 500, false);
                            }
                        }
                    });
                });
            });
            return deferred.promise;
        }

        function setValue(rootModel, model, value, key) {
            if (angular.isString(value)) {
                if (model[key] && model[key].type) {
                    model[key].setText(value);
                } else if (model.type === 'Map') {
                    model.set(key, value);
                } else {
                    console.log('Unknown key', key);
                }
            } else if (angular.isArray(value)) {
                value.forEach(function(e) {
                    var _datum;
                    switch (key) {
                    case 'curators':
                        _datum = rootModel.create('Curator');
                        break;
                    case 'mutations':
                        _datum = rootModel.create('Mutation');
                        break;
                    case 'transcripts':
                        _datum = rootModel.create('ISOForm');
                        break;
                    case 'tumors':
                        _datum = rootModel.create('Tumor');
                        break;
                    case 'TI':
                        _datum = rootModel.create('TI');
                        break;
                    case 'treatments':
                        _datum = rootModel.create('Treatment');
                        break;
                    case 'cancerTypes':
                        _datum = rootModel.create('CancerType');
                        break;
                    case 'trials':
                        _datum = e;
                        break;
                    default:
                        break;
                    }

                    if (key.indexOf('_comments') !== -1) {
                        _datum = rootModel.create('Comment');
                    }

                    if (key === 'TI') {
                        _datum.types.set('status', e.status);
                        _datum.types.set('type', e.type);
                        delete e.status;
                        delete e.type;
                    }
                    if (key !== 'trials') {
                        _.each(e, function(item, _key) {
                            _datum = setValue(rootModel, _datum, item, _key);
                        });
                    }
                    model[key].push(_datum);
                });
            } else if (angular.isObject(value)) {
                var _datum;
                switch (key) {
                case 'nccn':
                    _datum = rootModel.create('NCCN');
                    break;
                case 'effect':
                    _datum = rootModel.create('ME');
                    break;
                case 'interactAlts':
                    _datum = rootModel.create('InteractAlts');
                    break;
                case 'type':
                    _datum = rootModel.createMap(OncoKB.keyMappings.type);
                    break;
                default:
                    break;
                }

                if (key.indexOf('_eStatus') !== -1) {
                    _.each(value, function(item, _key) {
                        model[key].set(_key, item);
                    });
                } else if (key.indexOf('_review') !== -1) {
                    model[key] = createMap(rootModel, value);
                } else if (key.indexOf('_timeStamp') === -1) {
                    _.each(value, function(item, _key) {
                        _datum = setValue(rootModel, _datum, item, _key);
                    });
                    model[key] = _datum;
                } else {
                    _.each(value, function(item, _key) {
                        _datum = rootModel.create('TimeStamp');
                        _datum.value.setText(item.value || '');
                        _datum.by.setText(item.by || '');
                        model[key].set(_key, _datum);
                    });
                }
            } else {
                console.log('Error value type.');
            }
            return model;
        }

        function createMap(rootModel, value) {
            var _datum = rootModel.createMap();
            _.each(value, function(item, _key) {
                if (_.isObject(item)) {
                    _datum.set(_key, createMap(rootModel, item));
                } else {
                    _datum.set(_key, item);
                }
            });
            return _datum;
        }

        function createModel(model) {
            model = createGeneModel(model);
            model = createVUSModel(model);
            return model;
        }

        function createGeneModel(model) {
            if (!model.getRoot().get('gene')) {
                var gene = model.create('Gene');
                model.getRoot().set('gene', gene);
            }
            return model;
        }

        function createVUSModel(model) {
            if (!model.getRoot().get('vus')) {
                var vus = model.createList();
                model.getRoot().set('vus', vus);
            }
            return model;
        }

        return {
            backup: backup,
            migrate: migrate
        };
    });
<commit_msg>save propagation to gene model<commit_after>'use strict';

/**
 * @ngdoc service
 * @name oncokbApp.importer
 * @description
 * # importer
 * Service in the oncokbApp.
 */
angular.module('oncokbApp')
    .service('importer', function importer($timeout, documents, S, storage, OncoKB, $q, _, stringUtils) {
        var self = {};
        self.docs = [];
        self.docsL = 0;
        self.newFolder = '';
        self.parentFolder = OncoKB.config.backupFolderId; // backup folder under knowledgebase
        self.status = {
            backupIndex: -1,
            migrateIndex: -1
        };

        function backup(callback) {
            if (self.parentFolder) {
                if (!angular.isFunction(callback)) {
                    callback = undefined;
                }

                createFolder().then(function(result) {
                    if (result && result.error) {
                        console.error('Create folder failed.', result);
                        if (callback) {
                            callback();
                        }
                    } else {
                        // var docs = documents.get({title: 'BRAF'});
                        self.docs = documents.get();
                        self.docsL = self.docs.length;
                        copyData(0, callback);
                    }
                });
            } else {
                console.log('Backup folder ID needed.');
            }
        }

        function createFolder() {
            var deferred = $q.defer();

            storage.requireAuth(true).then(function(result) {
                if (result && !result.error) {
                    storage.createFolder(self.parentFolder).then(function(result) {
                        if (result.id) {
                            self.newFolder = result.id;
                            deferred.resolve(result);
                        } else {
                            deferred.reject(result);
                        }
                    });
                }
            });

            return deferred.promise;
        }

        function copyData(index, callback) {
            if (index < self.docs.length) {
                var doc = self.docs[index];
                copyFileData(self.newFolder, doc.id, doc.title, index).then(function() {
                    if ((index + 1) % 50 === 0) {
                        console.log('copied another 50 genes, waiting 5s...');
                        $timeout(function() {
                            copyData(++index, callback);
                        }, 5000, false);
                    } else {
                        copyData(++index, callback);
                    }
                });
            } else {
                if (callback) {
                    callback();
                }
                console.log('finished');
            }
        }

        function migrate() {
            var destinationFolderId = '';
            var deferred = $q.defer();

            destinationFolderId = '0BzBfo69g8fP6RmczanJFSVlNSjA';

            if (destinationFolderId) {
                self.newFolder = destinationFolderId;
                self.docs = documents.get();
                self.docsL = self.docs.length;

                // copy foler permissions
                // assignPermission(OncoKB.config.folderId, self.newFolder)
                //    .then(function(result){
                //      if(result && result.error){
                //        console.log('Error when assigning folder permissions', result);
                //      }else{
                migrateOneFileProcess(0, deferred);
                // }
                // });
            } else {
                createFolder().then(function(result) {
                    if (result && result.error) {
                        console.log('Unable create folder.', result);
                    } else {
                        self.docs = documents.get();
                        self.docsL = self.docs.length;

                        // copy foler permissions
                        assignPermission(OncoKB.config.folderId, self.newFolder)
                            .then(function(result) {
                                if (result && result.error) {
                                    console.log('Error when assigning folder permissions', result);
                                } else {
                                    migrateOneFileProcess(0, deferred);
                                }
                            });
                    }
                });
            }

            return deferred.promise;
        }

        function migrateOneFileProcess(docIndex, deferred) {
            if (docIndex < self.docsL) {
                var doc = self.docs[docIndex];
                copyFileData(self.newFolder, doc.id, doc.title, docIndex)
                    .then(function(result) {
                        if (result && result.error) {
                            console.log(result);
                            migrateOneFileProcess(++docIndex, deferred);
                        } else {
                            assignPermission(doc.id, result.id)
                                .then(function(result) {
                                    if (result && result.error) {
                                        console.log('error', result);
                                    } else {
                                        migrateOneFileProcess(++docIndex, deferred);
                                    }
                                });
                        }
                    });
            } else {
                console.log('Migrating finished.');
                deferred.resolve();
            }
        }

        function assignPermission(oldDocId, newDocId) {
            var deferred = $q.defer();
            console.log('\t Giving permissions');
            storage.getPermission(oldDocId).then(function(result) {
                if (result && result.error) {
                    deferred.reject(result);
                } else {
                    assignIndividualPermission(newDocId, result.items, 0, deferred);
                    // var promises = [];
                    // promises = result.items.forEach(function(permission, i){
                    //  if(permission.id && permission.emailAddress && permission.role && permission.type && permission.role !== 'owner'){
                    //    promises.push();
                    //  }
                    // });
                    // $q.all(promises).then(function(){
                    //  deferred.resolve();
                    // });
                }
            });
            return deferred.promise;
        }

        function assignIndividualPermission(newDocId, items, itemIndex, deferred) {
            if (itemIndex < items.length) {
                var permission = items[itemIndex];
                console.log('\t\t\tp-', itemIndex + 1);
                if (permission.id && permission.emailAddress && permission.role && permission.type && permission.role !== 'owner') {
                    storage.insertPermission(newDocId, permission.emailAddress, permission.type, permission.role).then(function() {
                        // $timeout(function () {
                        assignIndividualPermission(newDocId, items, ++itemIndex, deferred);
                        // }, 100);
                    });
                } else {
                    console.log('\t\t\tskip-', permission);
                    // $timeout(function () {
                    assignIndividualPermission(newDocId, items, ++itemIndex, deferred);
                    // }, 100);
                }
            } else {
                deferred.resolve();
                console.log('\t\tAll permissions are assigned.');
            }
        }

        function createVUSItem(vusItem, vusModel, model) {
            var vus = model.create(OncoKB.VUSItem);

            vus.name.setText(vusItem.name);
            _.each(vusItem.time, function(time) {
                var timeStamp = model.create(OncoKB.TimeStampWithCurator);
                timeStamp.value.setText(time.value);
                timeStamp.by.name.setText(time.by.name);
                timeStamp.by.email.setText(time.by.email);
                vus.time.push(timeStamp);
            });

            if (vusItem.nameComments) {
                _.each(vusItem.nameComments, function(comment) {
                    var _comment = model.create('Comment');
                    _comment.date.setText(comment.date);
                    _comment.userName.setText(comment.userName);
                    _comment.email.setText(comment.email);
                    _comment.content.setText(comment.content);
                    _comment.resolved.setText(comment.resolved);
                    vus.name_comments.push(_comment);
                });
            }
            vusModel.push(vus);
        }

        function copyFileData(folderId, fileId, fileTitle, docIndex) {
            var deferred = $q.defer();
            storage.requireAuth(true).then(function() {
                storage.createDocument(fileTitle, folderId).then(function(file) {
                    console.log('Created file ', fileTitle, docIndex + 1);
                    storage.getRealtimeDocument(fileId).then(function(realtime) {
                        if (realtime && realtime.error) {
                            console.log('did not get realtime document.');
                        } else {
                            console.log('\t Copying');
                            var gene = realtime.getModel().getRoot().get('gene');
                            var vus = realtime.getModel().getRoot().get('vus');
                            if (gene) {
                                var geneData = stringUtils.getGeneData(gene);
                                var vusData = stringUtils.getVUSFullData(vus);
                                storage.getRealtimeDocument(file.id).then(function(newRealtime) {
                                    var model = createModel(newRealtime.getModel());
                                    var geneModel = model.getRoot().get('gene');
                                    var vusModel = model.getRoot().get('vus');

                                    model.beginCompoundOperation();
                                    for (var key in geneData) {
                                        if (geneModel[key]) {
                                            geneModel = setValue(model, geneModel, geneData[key], key);
                                        }
                                    }

                                    if (vusData) {
                                        _.each(vusData, function(vusItem) {
                                            createVUSItem(vusItem, vusModel, newRealtime.getModel());
                                        });
                                    }
                                    model.endCompoundOperation();
                                    console.log('\t Done.');
                                    $timeout(function() {
                                        deferred.resolve(file);
                                    }, 500, false);
                                });
                            } else {
                                console.log('\t\tNo gene model.');
                                $timeout(function() {
                                    deferred.resolve(file);
                                }, 500, false);
                            }
                        }
                    });
                });
            });
            return deferred.promise;
        }

        function setValue(rootModel, model, value, key) {
            if (angular.isString(value)) {
                if (model[key] && model[key].type) {
                    model[key].setText(value);
                } else if (model.type === 'Map') {
                    model.set(key, value);
                } else if(key === 'propagation') {
                    model.name_eStatus.set('propagation', value);
                } else {
                    console.log('Unknown key', key);
                }
            } else if (angular.isArray(value)) {
                value.forEach(function(e) {
                    var _datum;
                    switch (key) {
                    case 'curators':
                        _datum = rootModel.create('Curator');
                        break;
                    case 'mutations':
                        _datum = rootModel.create('Mutation');
                        break;
                    case 'transcripts':
                        _datum = rootModel.create('ISOForm');
                        break;
                    case 'tumors':
                        _datum = rootModel.create('Tumor');
                        break;
                    case 'TI':
                        _datum = rootModel.create('TI');
                        break;
                    case 'treatments':
                        _datum = rootModel.create('Treatment');
                        break;
                    case 'cancerTypes':
                        _datum = rootModel.create('CancerType');
                        break;
                    case 'trials':
                        _datum = e;
                        break;
                    default:
                        break;
                    }

                    if (key.indexOf('_comments') !== -1) {
                        _datum = rootModel.create('Comment');
                    }

                    if (key === 'TI') {
                        _datum.types.set('status', e.status);
                        _datum.types.set('type', e.type);
                        delete e.status;
                        delete e.type;
                    }
                    if (key !== 'trials') {
                        _.each(e, function(item, _key) {
                            _datum = setValue(rootModel, _datum, item, _key);
                        });
                    }
                    model[key].push(_datum);
                });
            } else if (angular.isObject(value)) {
                var _datum;
                switch (key) {
                case 'nccn':
                    _datum = rootModel.create('NCCN');
                    break;
                case 'effect':
                    _datum = rootModel.create('ME');
                    break;
                case 'interactAlts':
                    _datum = rootModel.create('InteractAlts');
                    break;
                case 'type':
                    _datum = rootModel.createMap(OncoKB.keyMappings.type);
                    break;
                default:
                    break;
                }

                if (key.indexOf('_eStatus') !== -1) {
                    _.each(value, function(item, _key) {
                        model[key].set(_key, item);
                    });
                } else if (key.indexOf('_review') !== -1) {
                    model[key] = createMap(rootModel, value);
                } else if (key.indexOf('_timeStamp') === -1) {
                    _.each(value, function(item, _key) {
                        _datum = setValue(rootModel, _datum, item, _key);
                    });
                    model[key] = _datum;
                } else {
                    _.each(value, function(item, _key) {
                        _datum = rootModel.create('TimeStamp');
                        _datum.value.setText(item.value || '');
                        _datum.by.setText(item.by || '');
                        model[key].set(_key, _datum);
                    });
                }
            } else {
                console.log('Error value type.');
            }
            return model;
        }

        function createMap(rootModel, value) {
            var _datum = rootModel.createMap();
            _.each(value, function(item, _key) {
                if (_.isObject(item)) {
                    _datum.set(_key, createMap(rootModel, item));
                } else {
                    _datum.set(_key, item);
                }
            });
            return _datum;
        }

        function createModel(model) {
            model = createGeneModel(model);
            model = createVUSModel(model);
            return model;
        }

        function createGeneModel(model) {
            if (!model.getRoot().get('gene')) {
                var gene = model.create('Gene');
                model.getRoot().set('gene', gene);
            }
            return model;
        }

        function createVUSModel(model) {
            if (!model.getRoot().get('vus')) {
                var vus = model.createList();
                model.getRoot().set('vus', vus);
            }
            return model;
        }

        return {
            backup: backup,
            migrate: migrate
        };
    });
<|endoftext|>


<commit_before>// # bionode-template
// > Template module to use as a base for quickly creating bionode modules.
// >
// > doi: [?](?)
// > author: [Bruno Vieira](http://bmpvieira.com)
// > email: <mail@bmpvieira.com>
// > license: [MIT](https://raw.githubusercontent.com/bionode/bionode-template/master/LICENSE)
//
// ---
//
// ## Usage
// This module can be used in Node.js/browsers, as described further below, or as a command line tool.
// Examples:
//
//     $ npm install -g bionode-template
//
//     # bionode-template [command] [arguments]
//     $ bionode-template greet World
//     $ echo World | bionode-template greet
//     $ echo World | bionode-template greet |dat import --json

var through = require('through2')
var debug = require('debug')('bionode-template')

module.exports = exports = template = new Template()

function Template() {
  this.CONSTANT = 'Hello'
  return this
}

// ## Greet
// Returns a stream that transforms name strings into greeting messages:
//
//     template.greet('World').on('data', console.log)
//     => {"greeting":"Hello World"}
//
// The name can also be passed with write:
//
//     var greet = template.greet()
//     greet.on('data', console.log)
//     greet.write('World')
//     greet.write('Foo')
//     => {"greeting":"Hello World"}
//     => {"greeting":"Hello Foo"}
//
// Or piped, for example, from a file:
//
//     var split = require('split')
//
//     fs.createReadStream('names.txt')
//     .pipe(split())
//     .pipe(greet)
//     .on('data', console.log)

Template.prototype.greet = function(name) {
  var stream = through.obj(transform)
  if (name) { stream.write(name); stream.end() }
  return stream

  function transform(obj, enc, next) {
    var self = this
    var name = obj.toString().replace('\n', '')
    var message = [
      template.CONSTANT,
      name
    ].join(' ')

    debug('greet message', message)

    this.push({greeting: message})
    next()
  }
}
<commit_msg>Remove prototype<commit_after>// # bionode-template
// > Template module to use as a base for quickly creating bionode modules.
// >
// > doi: [?](?)
// > author: [Bruno Vieira](http://bmpvieira.com)
// > email: <mail@bmpvieira.com>
// > license: [MIT](https://raw.githubusercontent.com/bionode/bionode-template/master/LICENSE)
//
// ---
//
// ## Usage
// This module can be used in Node.js/browsers, as described further below, or as a command line tool.
// Examples:
//
//     $ npm install -g bionode-template
//
//     # bionode-template [command] [arguments]
//     $ bionode-template greet World
//     $ echo World | bionode-template greet
//     $ echo World | bionode-template greet |dat import --json

var through = require('through2')
var debug = require('debug')('bionode-template')

var template = module.exports

CONSTANT = 'Hello'

// ## Greet
// Returns a stream that transforms name strings into greeting messages:
//
//     template.greet('World').on('data', console.log)
//     => {"greeting":"Hello World"}
//
// The name can also be passed with write:
//
//     var greet = template.greet()
//     greet.on('data', console.log)
//     greet.write('World')
//     greet.write('Foo')
//     => {"greeting":"Hello World"}
//     => {"greeting":"Hello Foo"}
//
// Or piped, for example, from a file:
//
//     var split = require('split')
//
//     fs.createReadStream('names.txt')
//     .pipe(split())
//     .pipe(greet)
//     .on('data', console.log)

template.greet = function(name) {
  var stream = through.obj(transform)
  if (name) { stream.write(name); stream.end() }
  return stream

  function transform(obj, enc, next) {
    var self = this
    var name = obj.toString().replace('\n', '')
    var message = [
      CONSTANT,
      name
    ].join(' ')

    debug('greet message', message)

    this.push({greeting: message})
    next()
  }
}
<|endoftext|>


<commit_before>var _ = require('lodash')
var d3 = require('d3')
var moment = require('moment')
var React = require('react')

var series = function (values, name) {
  return {
    name: name,
    values: _.sortBy(values, _.result('campaign.start_date.getTime'))
  }
}

var percentage = function (dataset) {
  var total = _(dataset).pluck('value').sum()

  _.forEach(dataset, function (d) {
    d.value /= total
  })

  return dataset
}

function generateMissedChildrenChartData (original) {
  var stack = d3.layout.stack()
    .order('default')
    .offset('zero')
    .values(_.property('values'))
    .x(_.property('campaign.start_date'))
    .y(_.property('value'))

  var missed
  try {
    missed = _(original)
      .groupBy('indicator.short_name')
      .map(series)
      .thru(stack)
      .value()
  } catch (err) {
    console.error(err)
    console.log(`Data error in ${original}`)
    missed = []
  }

  return missed
}

function preparePolioCasesData (original) {
  var campaign = original.campaign
  var year = ''
  var totalCases = null
  var newCases = null

  if (campaign) {
    var m = moment(campaign.start_date, 'YYYY-MM-DD')
    year = m.format('YYYY')
    month = m.format('MMM')

    // Sum all of the reported Polio cases for the year
    totalCases = _(original.data)
      .filter(function (d) { return d.campaign.start_date.getFullYear() === year })
      .pluck('value')
      .sum()

    // Find the number of reported cases for this campaign
    newCases = _.get(
      _.find(
        original.data,
        function (d) { return d.campaign.start_date.getTime() === m.valueOf() }),
      'value')
  }

  // Set the title based on whether there is data
  var title =

        {totalCases} Polio cases this year

  var newCaseLabel = ''

  if (_.isFinite(newCases) && newCases > 0) {
    var plural = newCases !== 1 ? 's' : ''
    newCaseLabel = (

        {newCases} new case{plural}

    )
  }

  var color = d3.scale.ordinal()
    .range(['#377EA4', '#F15046', '#82888e', '#98a0a8', '#b6c0cc'])
    .domain(_(original.data)
      .map(_.method('campaign.start_date.getFullYear'))
      .uniq()
      .sortBy()
      .reverse()
      .value())

  return {
    title: title,
    newCaseLabel: newCaseLabel,
    data: original.data,
    colors: color
  }
}

function prepareMissedChildrenData (original) {
  var data = original.data
  var campaign = original.campaign
  var location = original.location

  var upper = moment(campaign.start_date, 'YYYY-MM-DD')
  var lower = upper.clone().startOf('month').subtract(1, 'year')

  var missed = generateMissedChildrenChartData(data.missedChildren)

  var missedScale = [lower.valueOf(), upper.valueOf()]

  var missedChildrenMap = data.missedChildrenByProvince

  return {
    missedChildrenMap: missedChildrenMap,
    missed: missed,
    missedScale: missedScale,
    location: location
  }
}

function prepareUnderImmunizedData (original) {
  var stack = d3.layout.stack()
    .offset('zero')
    .values(function (d) { return d.values })
    .x(function (d) { return d.campaign.start_date })
    .y(function (d) { return d.value })

  var data = _(original.data)
    .each(function (d) {
      // Add a property to each datapoint indicating the fiscal quarter
      d.quarter = moment(d.campaign.start_date).format('[Q]Q YYYY')
    })
    .groupBy(function (d) {
      return d.indicator.id + '-' + d.quarter
    })
    .map(function (datapoints) {
      // Calculate the total number of children with X doses of OPV for
      // each quarter
      return _.assign({}, datapoints[0], {
        'value': _(datapoints).pluck('value').sum()
      })
    })
    .groupBy('quarter')
    .map(percentage)
    .flatten()
    .reject(function (d) {
      // Exclude 4+ doses, because that is implied as 1 - <0 doses> - <1–3 doses>
      return d.indicator.id === 433
    })
    .groupBy('indicator.short_name')
    .map(function (values, name) {
      return {
        name: name,
        values: values
      }
    })
    .sortBy('name')
    .value()

  var start = moment(original.campaign.start_date)
  var lower = start.clone().startOf('quarter').subtract(3, 'years')
  var upper = start.clone().endOf('quarter')

  var immunityScale = _.map(d3.time.scale()
      .domain([lower.valueOf(), upper.valueOf()])
      .ticks(d3.time.month, 3),
    _.method('getTime')
  )

  var color = _.flow(
    _.property('name'),
    d3.scale.ordinal()
      .domain(_(data).pluck('name').sortBy().value())
      .range(['#D95449', '#B6D0D4'])
  )

  return {
    data: stack(data),
    immunityScale: immunityScale,
    color: color
  }
}

module.exports = {
  preparePolioCasesData: preparePolioCasesData,
  prepareMissedChildrenData: prepareMissedChildrenData,
  prepareUnderImmunizedData: prepareUnderImmunizedData
}
<commit_msg>fix the month error issue.<commit_after>var _ = require('lodash')
var d3 = require('d3')
var moment = require('moment')
var React = require('react')

var series = function (values, name) {
  return {
    name: name,
    values: _.sortBy(values, _.result('campaign.start_date.getTime'))
  }
}

var percentage = function (dataset) {
  var total = _(dataset).pluck('value').sum()

  _.forEach(dataset, function (d) {
    d.value /= total
  })

  return dataset
}

function generateMissedChildrenChartData (original) {
  var stack = d3.layout.stack()
    .order('default')
    .offset('zero')
    .values(_.property('values'))
    .x(_.property('campaign.start_date'))
    .y(_.property('value'))

  var missed
  try {
    missed = _(original)
      .groupBy('indicator.short_name')
      .map(series)
      .thru(stack)
      .value()
  } catch (err) {
    console.error(err)
    console.log(`Data error in ${original}`)
    missed = []
  }

  return missed
}

function preparePolioCasesData (original) {
  var campaign = original.campaign
  var year = ''
  var totalCases = null
  var newCases = null
  var month = null

  if (campaign) {
    var m = moment(campaign.start_date, 'YYYY-MM-DD')
    year = m.format('YYYY')
    month = m.format('MMM')

    // Sum all of the reported Polio cases for the year
    totalCases = _(original.data)
      .filter(function (d) { return d.campaign.start_date.getFullYear() === year })
      .pluck('value')
      .sum()

    // Find the number of reported cases for this campaign
    newCases = _.get(
      _.find(
        original.data,
        function (d) { return d.campaign.start_date.getTime() === m.valueOf() }),
      'value')
  }

  // Set the title based on whether there is data
  var title =

        {totalCases} Polio cases this year

  var newCaseLabel = ''

  if (_.isFinite(newCases) && newCases > 0) {
    var plural = newCases !== 1 ? 's' : ''
    newCaseLabel = (

        {newCases} new case{plural}

    )
  }

  var color = d3.scale.ordinal()
    .range(['#377EA4', '#F15046', '#82888e', '#98a0a8', '#b6c0cc'])
    .domain(_(original.data)
      .map(_.method('campaign.start_date.getFullYear'))
      .uniq()
      .sortBy()
      .reverse()
      .value())

  return {
    title: title,
    newCaseLabel: newCaseLabel,
    data: original.data,
    colors: color
  }
}

function prepareMissedChildrenData (original) {
  var data = original.data
  var campaign = original.campaign
  var location = original.location

  var upper = moment(campaign.start_date, 'YYYY-MM-DD')
  var lower = upper.clone().startOf('month').subtract(1, 'year')

  var missed = generateMissedChildrenChartData(data.missedChildren)

  var missedScale = [lower.valueOf(), upper.valueOf()]

  var missedChildrenMap = data.missedChildrenByProvince

  return {
    missedChildrenMap: missedChildrenMap,
    missed: missed,
    missedScale: missedScale,
    location: location
  }
}

function prepareUnderImmunizedData (original) {
  var stack = d3.layout.stack()
    .offset('zero')
    .values(function (d) { return d.values })
    .x(function (d) { return d.campaign.start_date })
    .y(function (d) { return d.value })

  var data = _(original.data)
    .each(function (d) {
      // Add a property to each datapoint indicating the fiscal quarter
      d.quarter = moment(d.campaign.start_date).format('[Q]Q YYYY')
    })
    .groupBy(function (d) {
      return d.indicator.id + '-' + d.quarter
    })
    .map(function (datapoints) {
      // Calculate the total number of children with X doses of OPV for
      // each quarter
      return _.assign({}, datapoints[0], {
        'value': _(datapoints).pluck('value').sum()
      })
    })
    .groupBy('quarter')
    .map(percentage)
    .flatten()
    .reject(function (d) {
      // Exclude 4+ doses, because that is implied as 1 - <0 doses> - <1–3 doses>
      return d.indicator.id === 433
    })
    .groupBy('indicator.short_name')
    .map(function (values, name) {
      return {
        name: name,
        values: values
      }
    })
    .sortBy('name')
    .value()

  var start = moment(original.campaign.start_date)
  var lower = start.clone().startOf('quarter').subtract(3, 'years')
  var upper = start.clone().endOf('quarter')

  var immunityScale = _.map(d3.time.scale()
      .domain([lower.valueOf(), upper.valueOf()])
      .ticks(d3.time.month, 3),
    _.method('getTime')
  )

  var color = _.flow(
    _.property('name'),
    d3.scale.ordinal()
      .domain(_(data).pluck('name').sortBy().value())
      .range(['#D95449', '#B6D0D4'])
  )

  return {
    data: stack(data),
    immunityScale: immunityScale,
    color: color
  }
}

module.exports = {
  preparePolioCasesData: preparePolioCasesData,
  prepareMissedChildrenData: prepareMissedChildrenData,
  prepareUnderImmunizedData: prepareUnderImmunizedData
}
<|endoftext|>


<commit_before>/*
 Copyright 2014 OpenMarket Ltd

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

'use strict';

// XXX FIXME TODO
// We should NOT be dumping things into $rootScope!!!! We should NOT be
// making any requests here, and should READ what is already in the
// rootScope from the event handler service!!!
// XXX FIXME TODO

angular.module('RecentsController', ['matrixService', 'matrixFilter', 'eventHandlerService'])
.controller('RecentsController', ['$rootScope', '$scope', 'matrixService', 'eventHandlerService',
                               function($rootScope, $scope, matrixService, eventHandlerService) {

    // FIXME: Angularjs reloads the controller (and resets its $scope) each time
    // the page URL changes, use $rootScope to avoid to have to reload data
    $rootScope.rooms;

    // $rootScope of the parent where the recents component is included can override this value
    // in order to highlight a specific room in the list
    $rootScope.recentsSelectedRoomID;

    // XXX FIXME TODO : We should NOT be doing this here, which could be
    // repeated for every controller instance. We should be doing this in
    // event handler service instead. In additon, this will break if there
    // isn't a recents controller visible when the last message comes in :/

    var listenToEventStream = function() {
        // Refresh the list on matrix invitation and message event
        $rootScope.$on(eventHandlerService.MEMBER_EVENT, function(ngEvent, event, isLive) {
            if (isLive) {
                $rootScope.rooms[event.room_id].lastMsg = event;
            }
        });
        $rootScope.$on(eventHandlerService.MSG_EVENT, function(ngEvent, event, isLive) {
            if (isLive) {
                $rootScope.rooms[event.room_id].lastMsg = event;
            }
        });
        $rootScope.$on(eventHandlerService.CALL_EVENT, function(ngEvent, event, isLive) {
            if (isLive) {
                $rootScope.rooms[event.room_id].lastMsg = event;
            }
        });
        $rootScope.$on(eventHandlerService.ROOM_CREATE_EVENT, function(ngEvent, event, isLive) {
            if (isLive) {
                $rootScope.rooms[event.room_id] = event;
            }
        });
    };

    $scope.onInit = function() {
        // Init recents list only once
        if ($rootScope.rooms) {
            return;
        }

        // XXX FIXME TODO
        // We should NOT be dumping things into $rootScope!!!! We should NOT be
        // making any requests here, and should READ what is already in the
        // rootScope from the event handler service!!!
        // XXX FIXME TODO

        $rootScope.rooms = {};

        // Use initialSync data to init the recents list
        eventHandlerService.waitForInitialSyncCompletion().then(
            function(initialSyncData) {

                // XXX FIXME TODO:
                // Any assignments to the rootScope here should be done in
                // event handler service and not here, because we could have
                // many controllers manipulating and clobbering each other, and
                // are unecessarily repeating http requests.
                var rooms = initialSyncData.data.rooms;
                for (var i=0; i<rooms.length; i++) {
                    var room = rooms[i];

                    // Add room_alias & room_display_name members
                    $rootScope.rooms[room.room_id] = angular.extend(room, matrixService.getRoomAliasAndDisplayName(room));

                    // Create a shortcut for the last message of this room
                    if (room.messages && room.messages.chunk && room.messages.chunk[0]) {
                        $rootScope.rooms[room.room_id].lastMsg = room.messages.chunk[0];
                    }

                    var numUsersInRoom = 0;
                    if (room.state) {
                        for (var j=0; j<room.state.length; j++) {
                            var stateEvent = room.state[j];
                            if (stateEvent.type == "m.room.member" && stateEvent.content.membership == "join") {
                                numUsersInRoom += 1;
                            }
                        }
                    }
                    $rootScope.rooms[room.room_id].numUsersInRoom = numUsersInRoom;
                }

                var presence = initialSyncData.data.presence;
                for (var i = 0; i < presence.length; ++i) {
                    eventHandlerService.handleEvent(presence[i], false);
                }

                // From now, update recents from the stream
                listenToEventStream();
            },
            function(error) {
                $rootScope.feedback = "Failure: " + error.data;
            }
        );
    };

}]);

<commit_msg>Removed historical code: recents does not need to manage presences. It is already done by initialSync in eventStreamService<commit_after>/*
 Copyright 2014 OpenMarket Ltd

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

'use strict';

// XXX FIXME TODO
// We should NOT be dumping things into $rootScope!!!! We should NOT be
// making any requests here, and should READ what is already in the
// rootScope from the event handler service!!!
// XXX FIXME TODO

angular.module('RecentsController', ['matrixService', 'matrixFilter', 'eventHandlerService'])
.controller('RecentsController', ['$rootScope', '$scope', 'matrixService', 'eventHandlerService',
                               function($rootScope, $scope, matrixService, eventHandlerService) {

    // FIXME: Angularjs reloads the controller (and resets its $scope) each time
    // the page URL changes, use $rootScope to avoid to have to reload data
    $rootScope.rooms;

    // $rootScope of the parent where the recents component is included can override this value
    // in order to highlight a specific room in the list
    $rootScope.recentsSelectedRoomID;

    // XXX FIXME TODO : We should NOT be doing this here, which could be
    // repeated for every controller instance. We should be doing this in
    // event handler service instead. In additon, this will break if there
    // isn't a recents controller visible when the last message comes in :/

    var listenToEventStream = function() {
        // Refresh the list on matrix invitation and message event
        $rootScope.$on(eventHandlerService.MEMBER_EVENT, function(ngEvent, event, isLive) {
            if (isLive) {
                $rootScope.rooms[event.room_id].lastMsg = event;
            }
        });
        $rootScope.$on(eventHandlerService.MSG_EVENT, function(ngEvent, event, isLive) {
            if (isLive) {
                $rootScope.rooms[event.room_id].lastMsg = event;
            }
        });
        $rootScope.$on(eventHandlerService.CALL_EVENT, function(ngEvent, event, isLive) {
            if (isLive) {
                $rootScope.rooms[event.room_id].lastMsg = event;
            }
        });
        $rootScope.$on(eventHandlerService.ROOM_CREATE_EVENT, function(ngEvent, event, isLive) {
            if (isLive) {
                $rootScope.rooms[event.room_id] = event;
            }
        });
    };

    $scope.onInit = function() {
        // Init recents list only once
        if ($rootScope.rooms) {
            return;
        }

        // XXX FIXME TODO
        // We should NOT be dumping things into $rootScope!!!! We should NOT be
        // making any requests here, and should READ what is already in the
        // rootScope from the event handler service!!!
        // XXX FIXME TODO

        $rootScope.rooms = {};

        // Use initialSync data to init the recents list
        eventHandlerService.waitForInitialSyncCompletion().then(
            function(initialSyncData) {

                // XXX FIXME TODO:
                // Any assignments to the rootScope here should be done in
                // event handler service and not here, because we could have
                // many controllers manipulating and clobbering each other, and
                // are unecessarily repeating http requests.
                var rooms = initialSyncData.data.rooms;
                for (var i=0; i<rooms.length; i++) {
                    var room = rooms[i];

                    // Add room_alias & room_display_name members
                    $rootScope.rooms[room.room_id] = angular.extend(room, matrixService.getRoomAliasAndDisplayName(room));

                    // Create a shortcut for the last message of this room
                    if (room.messages && room.messages.chunk && room.messages.chunk[0]) {
                        $rootScope.rooms[room.room_id].lastMsg = room.messages.chunk[0];
                    }

                    var numUsersInRoom = 0;
                    if (room.state) {
                        for (var j=0; j<room.state.length; j++) {
                            var stateEvent = room.state[j];
                            if (stateEvent.type == "m.room.member" && stateEvent.content.membership == "join") {
                                numUsersInRoom += 1;
                            }
                        }
                    }
                    $rootScope.rooms[room.room_id].numUsersInRoom = numUsersInRoom;
                }

                // From now, update recents from the stream
                listenToEventStream();
            },
            function(error) {
                $rootScope.feedback = "Failure: " + error.data;
            }
        );
    };

}]);

<|endoftext|>