<commit_before>/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "config" }]*/

import Controller from '@ember/controller';
import { computed } from 'ember-decorators/object';
import { alias, sort, filterBy } from 'ember-decorators/object/computed';
import config from 'travis/config/environment';
import { service } from 'ember-decorators/service';

export default Controller.extend({
  @service externalLinks: null,

  @computed('unsortedEnvVars')
  envVars(envVars) {
    return envVars.sortBy('name');
  },

  config,

  @filterBy('model.envVars', 'isNew', false)
  unsortedEnvVars: null,

  @alias('model.cronJobs.jobs.[]')
  cronJobs: null,

  @computed('cronJobs', 'model.branches.@each.exists_on_github')
  branchesWithoutCron(cronJobs, branches) {
    return branches
      .filter(branch => branch.get('exists_on_github'))
      .filter(branch => {
        const branchName = branch.get('name');
        return ! cronJobs.any(cron => branchName === cron.get('branch.name'));
      });
  },

  @sort('branchesWithoutCron', (a, b) => {
    if (a.get('defaultBranch')) {
      return -1;
    } else if (b.get('defaultBranch')) {
      return 1;
    } else {
      return a.get('name') > b.get('name');
    }
  })
  sortedBranchesWithoutCron: null,

  @computed('model.settings')
  showAutoCancellationSwitches(settings) {
    return settings.hasOwnProperty('auto_cancel_pushes')
      || settings.hasOwnProperty('auto_cancel_pull_requests');
  },

  @computed('repo.slug')
  migratedRepositorySettingsLink(slug) {
    return this.get('externalLinks').migratedToComSettingsLink(slug);
  },

  @computed('features.{proVersion,enterpriseVersion}', 'repo.migrationStatus')
  displaySettingsDisabledAfterMigrationModal(pro, enterprise, migrationStatus) {
    return !pro && !enterprise && ['migrating', 'migrated'].includes(migrationStatus);
  },

  actions: {
    sshKeyAdded(sshKey) {
      return this.set('model.customSshKey', sshKey);
    },

    sshKeyDeleted() {
      return this.set('model.customSshKey', null);
    }
  }
});
<commit_msg>Fix broken settings page after migration (#1907)<commit_after>/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "config" }]*/

import Controller from '@ember/controller';
import { computed } from 'ember-decorators/object';
import { alias, sort, filterBy } from 'ember-decorators/object/computed';
import config from 'travis/config/environment';
import { service } from 'ember-decorators/service';

export default Controller.extend({
  @service externalLinks: null,
  @service features: null,

  @computed('unsortedEnvVars')
  envVars(envVars) {
    return envVars.sortBy('name');
  },

  config,

  @filterBy('model.envVars', 'isNew', false)
  unsortedEnvVars: null,

  @alias('model.cronJobs.jobs.[]')
  cronJobs: null,

  @computed('cronJobs', 'model.branches.@each.exists_on_github')
  branchesWithoutCron(cronJobs, branches) {
    return branches
      .filter(branch => branch.get('exists_on_github'))
      .filter(branch => {
        const branchName = branch.get('name');
        return ! cronJobs.any(cron => branchName === cron.get('branch.name'));
      });
  },

  @sort('branchesWithoutCron', (a, b) => {
    if (a.get('defaultBranch')) {
      return -1;
    } else if (b.get('defaultBranch')) {
      return 1;
    } else {
      return a.get('name') > b.get('name');
    }
  })
  sortedBranchesWithoutCron: null,

  @computed('model.settings')
  showAutoCancellationSwitches(settings) {
    return settings.hasOwnProperty('auto_cancel_pushes')
      || settings.hasOwnProperty('auto_cancel_pull_requests');
  },

  @computed('repo.slug')
  migratedRepositorySettingsLink(slug) {
    return this.get('externalLinks').migratedToComSettingsLink(slug);
  },

  @computed('features.{proVersion,enterpriseVersion}', 'repo.migrationStatus')
  displaySettingsDisabledAfterMigrationModal(pro, enterprise, migrationStatus) {
    return !pro && !enterprise && ['migrating', 'migrated'].includes(migrationStatus);
  },

  actions: {
    sshKeyAdded(sshKey) {
      return this.set('model.customSshKey', sshKey);
    },

    sshKeyDeleted() {
      return this.set('model.customSshKey', null);
    }
  }
});
<|endoftext|>


<commit_before>$(function() {
	var dataTable = $("#table").DataTable({});

	$("#dialog-confirm-delete").dialog({
		"resizable" : false,
		"autoOpen" : false,
		"modal" : true
	});
	$("#form-delete").attr("action", $("#link-action-delete").attr("href"));

	function create_delete_message(label) {
		var dialog = $("#dialog-confirm-delete");
		var text = $(".dialog-message-template", dialog).text();
		var data = {
			"id" : label
		};
		var template = Hogan.compile(text);
		var rendered = template.render(data);
		$(".dialog-message", dialog).text(rendered);
	}

	function table_delete_row(link) {
		var tr = link.parents("tr");
		var label = $(".list-item-label", tr).text();
		var id = $(".list-item-id", tr).text();
		create_delete_message(label);
		$("#form-delete-id").val(id);
		delete_row(tr, label);
		return false;

		function delete_row(tr, label) {
			var element = $("#dialog-confirm-delete");
			var buttons = {};
			element.dialog("option", "buttons", [ {
				"id" : "dialog-confirm-delete-button-no",
				"text" : $("#dialog-confirm-delete-label-no").text(),
				"click" : function() {
					$(this).dialog("close");
				}
			}, {
				"id" : "dialog-confirm-delete-button-yes",
				"text" : $("#dialog-confirm-delete-label-yes").text(),
				"click" : function() {
					$(this).dialog("close");
					execute_delete(tr, label);
				}
			} ]);
			element.dialog("open");

		}
		function execute_delete(tr, label) {
			var options = {
				"dataType" : "json",
				"success" : function(object, statusText, xhr, $form) {
					if (object.status == "success") {
						var row = dataTable.row(tr);
						row.remove().draw();
					} else {
						var msg = "Unable to delete [" + label + "].\n"
								+ object.message;
						alert(msg);
					}
				}
			};
			$("#form-delete").ajaxSubmit(options);
		}

	}
	;
	$("#table").on("click", "a.link-remove", table_delete_row($(this)));

})<commit_msg>fixed table click link remove<commit_after>$(function() {
	var dataTable = $("#table").DataTable({});

	$("#dialog-confirm-delete").dialog({
		"resizable" : false,
		"autoOpen" : false,
		"modal" : true
	});
	$("#form-delete").attr("action", $("#link-action-delete").attr("href"));

	function create_delete_message(label) {
		var dialog = $("#dialog-confirm-delete");
		var text = $(".dialog-message-template", dialog).text();
		var data = {
			"id" : label
		};
		var template = Hogan.compile(text);
		var rendered = template.render(data);
		$(".dialog-message", dialog).text(rendered);
	}

	function table_delete_row(link) {
		var tr = link.parents("tr");
		var label = $(".list-item-label", tr).text();
		var id = $(".list-item-id", tr).text();
		create_delete_message(label);
		$("#form-delete-id").val(id);
		delete_row(tr, label);
		return false;

		function delete_row(tr, label) {
			var element = $("#dialog-confirm-delete");
			var buttons = {};
			element.dialog("option", "buttons", [ {
				"id" : "dialog-confirm-delete-button-no",
				"text" : $("#dialog-confirm-delete-label-no").text(),
				"click" : function() {
					$(this).dialog("close");
				}
			}, {
				"id" : "dialog-confirm-delete-button-yes",
				"text" : $("#dialog-confirm-delete-label-yes").text(),
				"click" : function() {
					$(this).dialog("close");
					execute_delete(tr, label);
				}
			} ]);
			element.dialog("open");

		}
		function execute_delete(tr, label) {
			var options = {
				"dataType" : "json",
				"success" : function(object, statusText, xhr, $form) {
					if (object.status == "success") {
						var row = dataTable.row(tr);
						row.remove().draw();
					} else {
						var msg = "Unable to delete [" + label + "].\n"
								+ object.message;
						alert(msg);
					}
				}
			};
			$("#form-delete").ajaxSubmit(options);
		}

	}
	$("#table").on("click", "a.link-remove", function() {
		table_delete_row($(this));
	});

})<|endoftext|>


<commit_before>
import moment from 'moment';

import Sinister from "../models/sinister";
import SinisterGeneral from "../models/sinisterGeneral";
import SinisterGeneralDocumentation from "../models/sinisterGeneralDocumentation";
import SinisterCar from "../models/sinisterCar";

import Ramo from "../models/ramo";
import Policy from "../models/policy";

import JSZip from 'jszip';
import Docxtemplater from 'docxtemplater';
import excelbuilder from 'msexcel-builder';
import fs from 'fs';
import path from 'path';

const pathRender = `download`;
const pathDownload = `./public/${pathRender}`;

if (!fs.existsSync(pathDownload)){
    fs.mkdirSync(pathDownload);
}

let sinisterController = function (app, control={auth, passport, acl}){

   function controller (req, res, next) {
      req.controller = "sinister";
      return next();
   }

   function findAction (callback){
      Sinister.find({}, function (err, docs) {
         if (!err) {

            Ramo.populate(docs, {path: "ramo"},function(err, docs){
               callback(docs);
            });
         }
      });
   }

   app.get('/sinister/filter',[control.auth, controller], (req, res) => {
      let $filter =  global.filter(req.query.filter);
      Sinister.find($filter, function (err, docs) {
         if (typeof docs !== 'undefined') {
            control.log(req.route.path, req.user);

            Ramo.populate(docs, {path: "ramo"},function(err, docs){
               res.send({msg: "OK", sinisters: docs});
            });

         } else {
            let error=global.error(err, 0, req.controller);
            res.send({msg: 'ERROR', err: error});
         }
      });

   });

   app.get('/sinister/list', [control.auth, controller, control.acl], (req, res) => {

      let typeList = app.locals.typeList;
      let filter = {};
      if(typeList=="99097f2c1f"){
         filter = {"userCreate": req.user.idUser};
      } else if(typeList=="99097f2c1c"){
         filter = {"branchCreate": req.user.idBranch};
      } else {
         filter = {};
      }

      Sinister.find(filter, function (err, docs) {
         if (typeof docs !== 'undefined') {
            control.log(req.route.path, req.user);
            Policy.populate(docs, {path: "policy"},function(err, docs){
                res.send({msg: "OK", sinisters: docs});
             });

         } else {
            let error=global.error(err, 0, req.controller);
            res.send({msg: 'ERROR', err: error});
         }
      });

   });

   app.get('/sinister/view/:id', [control.auth, controller, control.acl], (req, res) => {

      Sinister.findById(req.params.id, function (err, doc) {
         if (!err) {
            control.log(req.route.path, req.user);
            res.send({msg: "OK", sinister: doc});
         } else {
            let error=global.error(err, 0, req.controller);
            res.send({msg: 'ERROR', err: error});
         }
      });

   });

   app.post('/sinister/add', [control.auth, controller, control.acl], (req, res) => {

      let $data = req.body.sinister;
      console.log($data);
      let $sinisterData = $data;
      let $sinisterGeneral = $data.item;
      let $sinisterGeneralDocumentation = $data.item.items;
      let $moment = moment();
      delete($sinisterData.item);
      delete($sinisterGeneralDocumentation.items);
      $sinisterData["dateCreate"] = $moment;
      $sinisterData["userCreate"] = req.user.idUser;
      $sinisterData["branchCreate"] = req.user.idBranch;
      $sinisterData["dateUpdate"] = $moment;
      $sinisterData["userUpdate"] = req.user.idUser;
      let sinister = new Sinister($sinisterData);

      sinister.save((err, doc) => {
         if(!err){
            control.log(req.route.path, req.user);
            $sinisterGeneral["idSinister"] = doc._id;
            $sinisterGeneral["sinister"] = doc._id;
            $sinisterGeneral["dateCreate"] = $moment;
            $sinisterGeneral["userCreate"] = req.user.idUser;
            $sinisterGeneral["dateUpdate"] = $moment;
            $sinisterGeneral["userUpdate"] = req.user.idUser;
            let sinisterGeneral = new SinisterGeneral($sinisterGeneral);
            sinisterGeneral.save((err, doc) => {
               if(!err){
                  $sinisterGeneralDocumentation.forEach(function (item, index) {
                     $sinisterGeneralDocumentation[index]["idSinisterGeneral"]=doc._id;
                     $sinisterGeneralDocumentation[index]["sinisterGeneral"]=doc._id;
                     $sinisterGeneralDocumentation[index]["dateCreate"] = $moment;
                     $sinisterGeneralDocumentation[index]["userCreate"] = req.user.idUser;
                     $sinisterGeneralDocumentation[index]["dateUpdate"] = $moment;
                     $sinisterGeneralDocumentation[index]["userUpdate"] = req.user.idUser;
                  })
                  //let sinisterGeneralDocumentation = new SinisterGeneralDocumentation();
                  SinisterGeneralDocumentation.insertMany($sinisterGeneralDocumentation, (err, docs) => {
                  });
               }
            });
            findAction(function(docs){
               res.send({msg: "OK", update: docs});
            });
         } else {
            let error=global.error(err, 0, req.controller);
            res.send({msg: 'ERROR', err: error});
         }
      });

   });

   app.post('/sinister/edit/:id', [control.auth, controller, control.acl], (req, res) => {

      let filter = {
         _id: req.params.id
      }

      let update = {
         idPolicy: req.body.idPolicy,
         policyData: req.body.policyData,
         idPolicyAnnex: req.body.idPolicyAnnex,
         annexData: req.body.annexData,
         idClient: req.body.idClient,
         clientData: req.body.clientData,
         compName: req.body.compName,
         clientInsured: req.body.clientInsured,
         beneficiary: req.body.beneficiary,
         dateSinester: req.body.dateSinester,
         dateNotification: req.body.dateNotification,
         trackingDate: req.body.trackingDate,
         beneficiary: req.body.beneficiary,
         idRamo: req.body.idRamo,
         ramo: req.body.idRamo,
         sinisterState: req.body.sinisterState,
         settlementDate: req.body.settlementDate,
         approvalDate: req.body.approvalDate,
         checkApproved: req.body.checkApproved,
         dateUpdate: moment(),
         userUpdate: req.user.idUser
      };

      Sinister.findOneAndUpdate(filter, update, function (err, doc) {
         if (!err) {
            findAction(function(docs){
               control.log(req.route.path, req.user);
               res.send({msg: "OK", update: docs});
            });
         } else {
            let error=global.error(err, 0, req.controller);
            res.send({msg: 'ERROR', err: error});
         }
      });

   });

   app.delete('/sinister/delete/:id', [control.auth, controller, control.acl], (req, res) => {

      let filter = {
         _id: req.params.id
      }

      Sinister.findByIdAndRemove(filter, function (err, doc) {
         if(!err){
            findAction(function(docs){
               control.log(req.route.path, req.user);
               res.send({msg: "OK", update: docs});
            });
         } else {
            let error=global.error(err, 0, req.controller);
            res.send({msg: 'ERROR', err: error});
         }
      });

   });

   app.post('/sinister/report', [control.auth, controller, control.acl], (req, res) => {

      let $filter =  global.filter(req.body.filter);
      Sinister.find($filter, function (err, docs) {
         if (typeof docs !== 'undefined') {

         /*Ramo.populate(docs, {path: "ramo"},function(err, docs){
         City.populate(docs, {path: "city"},function(err, docs){
         Branch.populate(docs, {path: "branchCreate"},function(err, docs){
         PolicyType.populate(docs, {path: "policyType"},function(err, docs){*/

            var file = 'sinister.xlsx';
            var outPutFile = moment().format('YYYY-MM-DD-h:mm:ss') + file;
            var pathDownload = __dirname+'/../../public/download/';
            var workbook = excelbuilder.createWorkbook(pathDownload, outPutFile)
            var sheet1 = workbook.createSheet('sheet1', 15, 17);

            var cols = [2,3,4,5,6,7,8,9,10,11,12,13,14,15];
            var rowIni = 2;
            sheet1.set(cols[0], rowIni, 'Agencia');
            sheet1.set(cols[1], rowIni, 'Ciudad');
            sheet1.set(cols[2], rowIni, 'Nombre Cliente');
            sheet1.set(cols[4], rowIni, 'Numero de Poliza');
            sheet1.set(cols[5], rowIni, 'Numero de Siniestro');
            sheet1.set(cols[6], rowIni, 'Nombre Ramo');
            sheet1.set(cols[7], rowIni, 'Fecha de Inicio de Vigencia');
            sheet1.set(cols[8], rowIni, 'Fecha de fin de Vigencia');
            sheet1.set(cols[9], rowIni, 'Fecha de Siniestro');
            sheet1.set(cols[10], rowIni, 'Fecha de Notificacion');

            console.log(docs);
            let $length = docs.length;
            for (var i = 0; i < $length; i++) {
               rowIni++;
               let $cliente = '';
                  if(docs[i].typeRecipient == 'CLIENTE'){
                     $cliente = docs[i].recipient.name+' '+docs[i].recipient.lastName
                  }
               sheet1.set(cols[0], rowIni, docs[i]);
               /*sheet1.set(cols[0], rowIni, docs[i].branchCreate.name);
               sheet1.set(cols[1], rowIni, docs[i].city.name);
               sheet1.set(cols[2], rowIni, $cliente);
               sheet1.set(cols[3], rowIni, docs[i].policyNumber);
               sheet1.set(cols[4], rowIni, docs[i].ramo.name);
               sheet1.set(cols[5], rowIni, docs[i].policyType.name);
               sheet1.set(cols[6], rowIni, docs[i].startDate);
               sheet1.set(cols[7], rowIni, docs[i].finishDate);*/
            }

            workbook.save(function(err1, resp1){
               if (!err1){
                  console.log('congratulations, your workbook created');
                  res.send({msg: "OK", doc_name: outPutFile});
               }
               else{
                  workbook.cancel();
                  res.send({msg: "ERROR", err: err1});
               }
            });

         /*});
         });
         });
         });*/

         } else {
            let error=global.error(err, 0, req.controller);
            res.send({msg: 'ERROR', err: error});
         }
      });

   });

}

export default sinisterController
<commit_msg>fixed send data<commit_after>
import moment from 'moment';

import Sinister from "../models/sinister";
import SinisterGeneral from "../models/sinisterGeneral";
import SinisterGeneralDocumentation from "../models/sinisterGeneralDocumentation";
import SinisterCar from "../models/sinisterCar";

import Ramo from "../models/ramo";
import Policy from "../models/policy";

import JSZip from 'jszip';
import Docxtemplater from 'docxtemplater';
import excelbuilder from 'msexcel-builder';
import fs from 'fs';
import path from 'path';

const pathRender = `download`;
const pathDownload = `./public/${pathRender}`;

if (!fs.existsSync(pathDownload)){
    fs.mkdirSync(pathDownload);
}

let sinisterController = function (app, control={auth, passport, acl}){

   function controller (req, res, next) {
      req.controller = "sinister";
      return next();
   }

   function findAction (callback){
      Sinister.find({}, function (err, docs) {
         if (!err) {

            Ramo.populate(docs, {path: "ramo"},function(err, docs){
               callback(docs);
            });
         }
      });
   }

   app.get('/sinister/filter',[control.auth, controller], (req, res) => {
      let $filter =  global.filter(req.query.filter);
      Sinister.find($filter, function (err, docs) {
         if (typeof docs !== 'undefined') {
            control.log(req.route.path, req.user);

            Ramo.populate(docs, {path: "ramo"},function(err, docs){
               res.send({msg: "OK", sinisters: docs});
            });

         } else {
            let error=global.error(err, 0, req.controller);
            res.send({msg: 'ERROR', err: error});
         }
      });

   });

   app.get('/sinister/list', (req, res) => {

      let typeList = app.locals.typeList;
      let filter = {};
      if(typeList=="99097f2c1f"){
         filter = {"userCreate": req.user.idUser};
      } else if(typeList=="99097f2c1c"){
         filter = {"branchCreate": req.user.idBranch};
      } else {
         filter = {};
      }

      Sinister.find(filter, function (err, docs) {
         if (typeof docs !== 'undefined') {
            control.log(req.route.path, req.user);
            Ramo.populate(docs, {path: "ramo"},function(err, docs){
               res.send({msg: "OK", sinisters: docs});
            });

         } else {
            let error=global.error(err, 0, req.controller);
            res.send({msg: 'ERROR', err: error});
         }
      });

   });

   app.get('/sinister/view/:id', [control.auth, controller, control.acl], (req, res) => {

      Sinister.findById(req.params.id, function (err, doc) {
         if (!err) {
            control.log(req.route.path, req.user);
            res.send({msg: "OK", sinister: doc});
         } else {
            let error=global.error(err, 0, req.controller);
            res.send({msg: 'ERROR', err: error});
         }
      });

   });

   app.post('/sinister/add', [control.auth, controller, control.acl], (req, res) => {

      let $data = req.body.sinister;
      console.log($data);
      let $sinisterData = $data;
      $sinisterData.ramo = $sinisterData.idRamo;
      let $sinisterGeneral = $data.item;
      let $sinisterGeneralDocumentation = $data.item.items;
      let $moment = moment();
      delete($sinisterData.item);
      delete($sinisterGeneralDocumentation.items);
      $sinisterData["dateCreate"] = $moment;
      $sinisterData["userCreate"] = req.user.idUser;
      $sinisterData["branchCreate"] = req.user.idBranch;
      $sinisterData["dateUpdate"] = $moment;
      $sinisterData["userUpdate"] = req.user.idUser;
      let sinister = new Sinister($sinisterData);

      sinister.save((err, doc) => {
         if(!err){
            control.log(req.route.path, req.user);
            $sinisterGeneral["idSinister"] = doc._id;
            $sinisterGeneral["sinister"] = doc._id;
            $sinisterGeneral["dateCreate"] = $moment;
            $sinisterGeneral["userCreate"] = req.user.idUser;
            $sinisterGeneral["dateUpdate"] = $moment;
            $sinisterGeneral["userUpdate"] = req.user.idUser;
            let sinisterGeneral = new SinisterGeneral($sinisterGeneral);
            sinisterGeneral.save((err, doc) => {
               if(!err){
                  $sinisterGeneralDocumentation.forEach(function (item, index) {
                     $sinisterGeneralDocumentation[index]["idSinisterGeneral"]=doc._id;
                     $sinisterGeneralDocumentation[index]["sinisterGeneral"]=doc._id;
                     $sinisterGeneralDocumentation[index]["dateCreate"] = $moment;
                     $sinisterGeneralDocumentation[index]["userCreate"] = req.user.idUser;
                     $sinisterGeneralDocumentation[index]["dateUpdate"] = $moment;
                     $sinisterGeneralDocumentation[index]["userUpdate"] = req.user.idUser;
                  })
                  //let sinisterGeneralDocumentation = new SinisterGeneralDocumentation();
                  SinisterGeneralDocumentation.insertMany($sinisterGeneralDocumentation, (err, docs) => {
                  });
               }
            });
            findAction(function(docs){
               res.send({msg: "OK", update: docs});
            });
         } else {
            let error=global.error(err, 0, req.controller);
            res.send({msg: 'ERROR', err: error});
         }
      });

   });

   app.post('/sinister/edit/:id', [control.auth, controller, control.acl], (req, res) => {

      let filter = {
         _id: req.params.id
      }

      let update = {
         idPolicy: req.body.idPolicy,
         policyData: req.body.policyData,
         idPolicyAnnex: req.body.idPolicyAnnex,
         annexData: req.body.annexData,
         idClient: req.body.idClient,
         clientData: req.body.clientData,
         compName: req.body.compName,
         clientInsured: req.body.clientInsured,
         beneficiary: req.body.beneficiary,
         dateSinester: req.body.dateSinester,
         dateNotification: req.body.dateNotification,
         trackingDate: req.body.trackingDate,
         beneficiary: req.body.beneficiary,
         idRamo: req.body.idRamo,
         ramo: req.body.idRamo,
         sinisterState: req.body.sinisterState,
         settlementDate: req.body.settlementDate,
         approvalDate: req.body.approvalDate,
         checkApproved: req.body.checkApproved,
         dateUpdate: moment(),
         userUpdate: req.user.idUser
      };

      Sinister.findOneAndUpdate(filter, update, function (err, doc) {
         if (!err) {
            findAction(function(docs){
               control.log(req.route.path, req.user);
               res.send({msg: "OK", update: docs});
            });
         } else {
            let error=global.error(err, 0, req.controller);
            res.send({msg: 'ERROR', err: error});
         }
      });

   });

   app.delete('/sinister/delete/:id', [control.auth, controller, control.acl], (req, res) => {

      let filter = {
         _id: req.params.id
      }

      Sinister.findByIdAndRemove(filter, function (err, doc) {
         if(!err){
            findAction(function(docs){
               control.log(req.route.path, req.user);
               res.send({msg: "OK", update: docs});
            });
         } else {
            let error=global.error(err, 0, req.controller);
            res.send({msg: 'ERROR', err: error});
         }
      });

   });

   app.post('/sinister/report', [control.auth, controller, control.acl], (req, res) => {

      let $filter =  global.filter(req.body.filter);
      Sinister.find($filter, function (err, docs) {
         if (typeof docs !== 'undefined') {

         /*Ramo.populate(docs, {path: "ramo"},function(err, docs){
         City.populate(docs, {path: "city"},function(err, docs){
         Branch.populate(docs, {path: "branchCreate"},function(err, docs){
         PolicyType.populate(docs, {path: "policyType"},function(err, docs){*/

            var file = 'sinister.xlsx';
            var outPutFile = moment().format('YYYY-MM-DD-h:mm:ss') + file;
            var pathDownload = __dirname+'/../../public/download/';
            var workbook = excelbuilder.createWorkbook(pathDownload, outPutFile)
            var sheet1 = workbook.createSheet('sheet1', 15, 17);

            var cols = [2,3,4,5,6,7,8,9,10,11,12,13,14,15];
            var rowIni = 2;
            sheet1.set(cols[0], rowIni, 'Agencia');
            sheet1.set(cols[1], rowIni, 'Ciudad');
            sheet1.set(cols[2], rowIni, 'Nombre Cliente');
            sheet1.set(cols[4], rowIni, 'Numero de Poliza');
            sheet1.set(cols[5], rowIni, 'Numero de Siniestro');
            sheet1.set(cols[6], rowIni, 'Nombre Ramo');
            sheet1.set(cols[7], rowIni, 'Fecha de Inicio de Vigencia');
            sheet1.set(cols[8], rowIni, 'Fecha de fin de Vigencia');
            sheet1.set(cols[9], rowIni, 'Fecha de Siniestro');
            sheet1.set(cols[10], rowIni, 'Fecha de Notificacion');

            console.log(docs);
            let $length = docs.length;
            for (var i = 0; i < $length; i++) {
               rowIni++;
               let $cliente = '';
                  if(docs[i].typeRecipient == 'CLIENTE'){
                     $cliente = docs[i].recipient.name+' '+docs[i].recipient.lastName
                  }
               sheet1.set(cols[0], rowIni, docs[i]);
               /*sheet1.set(cols[0], rowIni, docs[i].branchCreate.name);
               sheet1.set(cols[1], rowIni, docs[i].city.name);
               sheet1.set(cols[2], rowIni, $cliente);
               sheet1.set(cols[3], rowIni, docs[i].policyNumber);
               sheet1.set(cols[4], rowIni, docs[i].ramo.name);
               sheet1.set(cols[5], rowIni, docs[i].policyType.name);
               sheet1.set(cols[6], rowIni, docs[i].startDate);
               sheet1.set(cols[7], rowIni, docs[i].finishDate);*/
            }

            workbook.save(function(err1, resp1){
               if (!err1){
                  console.log('congratulations, your workbook created');
                  res.send({msg: "OK", doc_name: outPutFile});
               }
               else{
                  workbook.cancel();
                  res.send({msg: "ERROR", err: err1});
               }
            });

         /*});
         });
         });
         });*/

         } else {
            let error=global.error(err, 0, req.controller);
            res.send({msg: 'ERROR', err: error});
         }
      });

   });

}

export default sinisterController
<|endoftext|>


<commit_before>/**
* @overview
* This is the controller file for the ToDoList View. The todolist view loads data from
* a model (sqlite), and derives a Sectioned and Indexed (iOS) ListView displaying all items.
* The todolist has one ListView Template for showing list item.
* Also, the ToDoList View have search bar to seaerch item.
*/
var _args = arguments[0] || {}, // Any passed in arguments will fall into this property
	moment = require('alloy/moment'),
	status = 'Pending',
	flag = false;

var colToDoList = Alloy.Collections.instance('todolist');

/**
 * Appcelerator Analytics Call
 */
var title = _args.title ? _args.title.toLowerCase() : "todolist";
Ti.Analytics.featureEvent(Ti.Platform.osname+"."+title+".viewed");

/**
 * This function handles the click events for the rows in the ListView.
 * We want to capture the list property associated with the row, and pass
 * it into the next View
 *
 * @param {Object} Event data passed to the function
 */
function onItemClick(e){
	console.log("e ==> " + JSON.stringify(e));
	if(!flag) {
		flag = true;
		return;
	}
	/**
	 * Appcelerator Analytics Call
	 */
	Ti.Analytics.featureEvent(Ti.Platform.osname+"."+title+".contact.clicked");

	/**
	 * Get the Item that was clicked
	 */
	var item = $.listView.sections[e.sectionIndex].items[e.itemIndex];

	/**
	 * Open the profile view, and pass in the user data for this contact
	 */
	var data = colToDoList.toJSON();

	_.each(data, function(value, key) {
		if(value.id === item.todo.id) {
			Alloy.Globals.Navigator.open("todoform", {obj: value});
		}
	});
}

/**
 * This code is only relevant to iOS - to make it cleaner, we are declaring variables, and
 * then assigning them to functions within an iOS Block. On MobileWeb, Android, etc this code block will not
 * exist
 */
var onSearchChange, onSearchFocus, onSearchCancel;

if(OS_IOS){

	/**
	 * Handles the SearchBar OnChange event
	 *
	 * @description On iOS we want the search bar to always be on top, so we use the onchange event to tie it back
	 * 				to the ListView
	 *
	 * @param {Object} Event data passed to the function
	 */
	onSearchChange = function onChange(e){
		$.listView.searchText = $.searchBar.value;
	};

	/**
	 * Updates the UI when the SearchBar gains focus. Shows
	 * the Cancel button.
	 *
	 * @description We used the focus event to show the Cancel button.
	 *
	 * @param {Object} Event data passed to the function
	 */
	onSearchFocus = function onFocus(e){
		$.searchBar.showCancel = true;
	};

	/**
	 * Updates the UI when the Cancel button is clicked within the search bar. Hides the Cancel button.
	 *
	 * @param {Object} Event data passed to the function
	 */
	onSearchCancel = function onCancel(e){
		$.searchBar.showCancel = false;
		$.searchBar.blur();
	};
}
else if(OS_ANDROID){
	/**
	 * Handles the SearchBar OnChange event
	 *
	 * @description On iOS we want the search bar to always be on top, so we use the onchange event to tie it back
	 * 				to the ListView
	 *
	 * @param {Object} Event data passed to the function
	 */
	onSearchChange = function onChange(e){
		if($.searchBar.value !==''){
			$.closeBtn.visible = true;
		}
		else{
			$.closeBtn.visible = false;
		}

		$.listView.searchText = $.searchBar.value;
	};
	/**
	 * Hides the keyboard when the cancel button is clicked
	 *
	 * @param {Object} Event data passed to the function
	 */
	onSearchCancel = function onCancel(e){
		$.closeBtn.visible = false;
		$.searchBar.value = '';
		$.searchBar.blur();
	};
}

function onWinFocus() {
	if(status === "Pending") {
		$.btnPending.fireEvent("click");
	} else {
		$.btnCompleted.fireEvent("click");
	}
}

function init() {
	colToDoList.fetch({query: "SELECT * FROM todolist ORDER BY dt_modified DESC"});
	// while (colToDoList.length > 0)
		// colToDoList.at(0).destroy();
}

function doTransform(model) {
    // Need to convert the model to a JSON object
    var transform = model.toJSON();
    transform.dt_modified = moment(transform.dt_modified).fromNow();
    return transform;
}

function addToDoItem() {
	Alloy.Globals.Navigator.open("todoform");
	return;
}

function filterOutput(collection) {
	return collection.where({status: status});
}

function emlShare(e) {
	flag = false; // Just a hack since bubbleParent is not working.
	var item = $.listView.sections[e.sectionIndex].items[e.itemIndex];
	var data = colToDoList.toJSON();

	_.each(data, function(value, key) {
		if(value.id === item.todo.id) {
			var emailDialog = Ti.UI.createEmailDialog();
			emailDialog.subject = "To Do List";
			emailDialog.toRecipients = ['pablo.guevara@propelics.com', 'carolina.lopez@propelics.com', 'cesar.cavazos@propelics.com'];
			emailDialog.messageBody = '' + value.status + '
' + value.content;
			if(value.image && value.image != "") {
				emailDialog.addAttachment(value.image);
			}
			emailDialog.open();
		}
	});
}

function smsShare(e) {
	flag = false; // Just a hack since bubbleParent is not working.
	var item = $.listView.sections[e.sectionIndex].items[e.itemIndex];
	var data = colToDoList.toJSON();

	_.each(data, function(value, key) {
		if(value.id === item.todo.id) {
			if(OS_IOS) {
				sendSMS("+91 1234567890", value.content + "\n" + value.status, value.image);
			} else {
				openSMSIntent("+91 1234567890", value.content);
			}
		}
	});
}

function openSMSIntent(phone, content) {
	var intent = Ti.Android.createIntent({
		action: Ti.Android.ACTION_SENDTO,
		data: 'smsto:' + phone
	});
	intent.putExtra('sms_body', content);
	Ti.Android.currentActivity.startActivity(intent);
}

function sendSMS(phone, content, imageBlob) {
    var module = require('com.omorandi');
    Ti.API.info("module is => " + module);

    //create the smsDialog object
    var smsDialog = module.createSMSDialog();
    //check if the feature is available on the device at hand
    if (!smsDialog.isSupported()) {
        //falls here when executed on iOS versions < 4.0 and in the emulator
        var a = Ti.UI.createAlertDialog({title: 'warning', message: 'the required feature is not available on your device'});
        a.show();
    }
    else
    {
        //pre-populate the dialog with the info provided in the following properties
        smsDialog.recipients = phone ? ['+14151234567'] : [phone];
        smsDialog.messageBody = content;

        //set the color of the title-bar
        smsDialog.barColor = '#E5E4E2';

        //add attachments if supported
        if (smsDialog.canSendAttachments()) {
            Ti.API.info('We can send attachments');
            //add an attachment as a file path
            //smsDialog.addAttachment('images/01.jpg', 'image1.jpg');
			if(imageBlob) {
				var fileName = "" + ".png";
	            smsDialog.addAttachment(imageBlob, filename);
			}
        }
        else {
            Ti.API.info('We cannot send attachments');
        }

        //add an event listener for the 'complete' event, in order to be notified about the result of the operation
        smsDialog.addEventListener('complete', function(e){
            Ti.API.info("Result: " + e.resultMessage);
            var a = Ti.UI.createAlertDialog({title: 'complete', message: 'Result: ' + e.resultMessage});
            a.show();
            if (e.result == smsDialog.SENT)
            {
                //do something
            }
            else if (e.result == smsDialog.FAILED)
            {
               //do something else
            }
            else if (e.result == smsDialog.CANCELLED)
            {
               //don't bother
            }
        });

        //open the SMS dialog window with slide-up animation
        smsDialog.open({animated: true});
    }

}

function sortData(e) {
	status = e.source.title;
	$.addClass(e.source, "fontBold");
	if(status === "Pending") {
		$.removeClass($.btnCompleted, "fontBold");
	} else {
		$.removeClass($.btnPending, "fontBold");
	}
	init();
}

function delRow(e) {
	/**
	 * Get the Item that was clicked
	 */
	var item = $.listView.sections[e.sectionIndex].items[e.itemIndex];
	var model = Alloy.createModel('todolist', {id: item.todo.id});
	model.destroy();
}

function openPic(e) {
	flag = false;
	Alloy.Globals.Navigator.open("taskpic", {image: e.source.image});
}
<commit_msg>Added status in SMS.<commit_after>/**
* @overview
* This is the controller file for the ToDoList View. The todolist view loads data from
* a model (sqlite), and derives a Sectioned and Indexed (iOS) ListView displaying all items.
* The todolist has one ListView Template for showing list item.
* Also, the ToDoList View have search bar to seaerch item.
*/
var _args = arguments[0] || {}, // Any passed in arguments will fall into this property
	moment = require('alloy/moment'),
	status = 'Pending',
	flag = false;

var colToDoList = Alloy.Collections.instance('todolist');

/**
 * Appcelerator Analytics Call
 */
var title = _args.title ? _args.title.toLowerCase() : "todolist";
Ti.Analytics.featureEvent(Ti.Platform.osname+"."+title+".viewed");

/**
 * This function handles the click events for the rows in the ListView.
 * We want to capture the list property associated with the row, and pass
 * it into the next View
 *
 * @param {Object} Event data passed to the function
 */
function onItemClick(e){
	console.log("e ==> " + JSON.stringify(e));
	if(!flag) {
		flag = true;
		return;
	}
	/**
	 * Appcelerator Analytics Call
	 */
	Ti.Analytics.featureEvent(Ti.Platform.osname+"."+title+".contact.clicked");

	/**
	 * Get the Item that was clicked
	 */
	var item = $.listView.sections[e.sectionIndex].items[e.itemIndex];

	/**
	 * Open the profile view, and pass in the user data for this contact
	 */
	var data = colToDoList.toJSON();

	_.each(data, function(value, key) {
		if(value.id === item.todo.id) {
			Alloy.Globals.Navigator.open("todoform", {obj: value});
		}
	});
}

/**
 * This code is only relevant to iOS - to make it cleaner, we are declaring variables, and
 * then assigning them to functions within an iOS Block. On MobileWeb, Android, etc this code block will not
 * exist
 */
var onSearchChange, onSearchFocus, onSearchCancel;

if(OS_IOS){

	/**
	 * Handles the SearchBar OnChange event
	 *
	 * @description On iOS we want the search bar to always be on top, so we use the onchange event to tie it back
	 * 				to the ListView
	 *
	 * @param {Object} Event data passed to the function
	 */
	onSearchChange = function onChange(e){
		$.listView.searchText = $.searchBar.value;
	};

	/**
	 * Updates the UI when the SearchBar gains focus. Shows
	 * the Cancel button.
	 *
	 * @description We used the focus event to show the Cancel button.
	 *
	 * @param {Object} Event data passed to the function
	 */
	onSearchFocus = function onFocus(e){
		$.searchBar.showCancel = true;
	};

	/**
	 * Updates the UI when the Cancel button is clicked within the search bar. Hides the Cancel button.
	 *
	 * @param {Object} Event data passed to the function
	 */
	onSearchCancel = function onCancel(e){
		$.searchBar.showCancel = false;
		$.searchBar.blur();
	};
}
else if(OS_ANDROID){
	/**
	 * Handles the SearchBar OnChange event
	 *
	 * @description On iOS we want the search bar to always be on top, so we use the onchange event to tie it back
	 * 				to the ListView
	 *
	 * @param {Object} Event data passed to the function
	 */
	onSearchChange = function onChange(e){
		if($.searchBar.value !==''){
			$.closeBtn.visible = true;
		}
		else{
			$.closeBtn.visible = false;
		}

		$.listView.searchText = $.searchBar.value;
	};
	/**
	 * Hides the keyboard when the cancel button is clicked
	 *
	 * @param {Object} Event data passed to the function
	 */
	onSearchCancel = function onCancel(e){
		$.closeBtn.visible = false;
		$.searchBar.value = '';
		$.searchBar.blur();
	};
}

function onWinFocus() {
	if(status === "Pending") {
		$.btnPending.fireEvent("click");
	} else {
		$.btnCompleted.fireEvent("click");
	}
}

function init() {
	colToDoList.fetch({query: "SELECT * FROM todolist ORDER BY dt_modified DESC"});
	// while (colToDoList.length > 0)
		// colToDoList.at(0).destroy();
}

function doTransform(model) {
    // Need to convert the model to a JSON object
    var transform = model.toJSON();
    transform.dt_modified = moment(transform.dt_modified).fromNow();
    return transform;
}

function addToDoItem() {
	Alloy.Globals.Navigator.open("todoform");
	return;
}

function filterOutput(collection) {
	return collection.where({status: status});
}

function emlShare(e) {
	flag = false; // Just a hack since bubbleParent is not working.
	var item = $.listView.sections[e.sectionIndex].items[e.itemIndex];
	var data = colToDoList.toJSON();

	_.each(data, function(value, key) {
		if(value.id === item.todo.id) {
			var emailDialog = Ti.UI.createEmailDialog();
			emailDialog.subject = "To Do List";
			emailDialog.toRecipients = ['pablo.guevara@propelics.com', 'carolina.lopez@propelics.com', 'cesar.cavazos@propelics.com'];
			emailDialog.messageBody = '' + value.status + '
' + value.content;
			if(value.image && value.image != "") {
				emailDialog.addAttachment(value.image);
			}
			emailDialog.open();
		}
	});
}

function smsShare(e) {
	flag = false; // Just a hack since bubbleParent is not working.
	var item = $.listView.sections[e.sectionIndex].items[e.itemIndex];
	var data = colToDoList.toJSON();

	_.each(data, function(value, key) {
		if(value.id === item.todo.id) {
			if(OS_IOS) {
				sendSMS("+91 1234567890", value.content + "\n" + value.status, value.image);
			} else {
				openSMSIntent("+91 1234567890", value.content, value.status);
			}
		}
	});
}

function openSMSIntent(phone, content, status) {
	var intent = Ti.Android.createIntent({
		action: Ti.Android.ACTION_SENDTO,
		data: 'smsto:' + phone
	});
	intent.putExtra('sms_body', content + " - " + status);
	Ti.Android.currentActivity.startActivity(intent);
}

function sendSMS(phone, content, imageBlob) {
    var module = require('com.omorandi');
    Ti.API.info("module is => " + module);

    //create the smsDialog object
    var smsDialog = module.createSMSDialog();
    //check if the feature is available on the device at hand
    if (!smsDialog.isSupported()) {
        //falls here when executed on iOS versions < 4.0 and in the emulator
        var a = Ti.UI.createAlertDialog({title: 'warning', message: 'the required feature is not available on your device'});
        a.show();
    }
    else
    {
        //pre-populate the dialog with the info provided in the following properties
        smsDialog.recipients = phone ? ['+14151234567'] : [phone];
        smsDialog.messageBody = content;

        //set the color of the title-bar
        smsDialog.barColor = '#E5E4E2';

        //add attachments if supported
        if (smsDialog.canSendAttachments()) {
            Ti.API.info('We can send attachments');
            //add an attachment as a file path
            //smsDialog.addAttachment('images/01.jpg', 'image1.jpg');
			if(imageBlob) {
				var fileName = "" + ".png";
	            smsDialog.addAttachment(imageBlob, filename);
			}
        }
        else {
            Ti.API.info('We cannot send attachments');
        }

        //add an event listener for the 'complete' event, in order to be notified about the result of the operation
        smsDialog.addEventListener('complete', function(e){
            Ti.API.info("Result: " + e.resultMessage);
            var a = Ti.UI.createAlertDialog({title: 'complete', message: 'Result: ' + e.resultMessage});
            a.show();
            if (e.result == smsDialog.SENT)
            {
                //do something
            }
            else if (e.result == smsDialog.FAILED)
            {
               //do something else
            }
            else if (e.result == smsDialog.CANCELLED)
            {
               //don't bother
            }
        });

        //open the SMS dialog window with slide-up animation
        smsDialog.open({animated: true});
    }

}

function sortData(e) {
	status = e.source.title;
	$.addClass(e.source, "fontBold");
	if(status === "Pending") {
		$.removeClass($.btnCompleted, "fontBold");
	} else {
		$.removeClass($.btnPending, "fontBold");
	}
	init();
}

function delRow(e) {
	/**
	 * Get the Item that was clicked
	 */
	var item = $.listView.sections[e.sectionIndex].items[e.itemIndex];
	var model = Alloy.createModel('todolist', {id: item.todo.id});
	model.destroy();
}

function openPic(e) {
	flag = false;
	Alloy.Globals.Navigator.open("taskpic", {image: e.source.image});
}
<|endoftext|>


<commit_before>/**
 * Created by filip on 3.6.15..
 */
'use strict';
define(['lodash'], function (_) {

//@body

var Common = {
    objectPropExists: function (prop) {
        return typeof prop !== 'undefined';
    },

    checkObjectKeys: function (obj) {
        return this.objectPropExists(obj) && _.size(obj) > 0;
    },

    getPropType: function (prop) {
        var type = typeof prop,
            result;

        result = type;

        if (type === 'object') {
            if (_.isArray(prop)) {
                result = 'array';
            }
        }

        return result;
    },

    setConstraints: function (instance, constraints) {

        _.forEach(constraints, function(constraint, prop) {

            if (Common.objectPropExists(constraint)) {
                if (Common.getPropType(constraint) == 'object') {
                    _.forEach(constraint, function(value, key) {
                        instance[prop][key] = value;
                    });
                } else {
                    instance[prop] = constraint;
                }
            }

        });
    }
};

//@body
return Common;

});<commit_msg>reformat ALL THE CODE<commit_after>/**
 * Created by filip on 3.6.15..
 */
'use strict';
define(['lodash'], function(_) {

//@body

  var Common = {
    objectPropExists: function(prop) {
      return typeof prop !== 'undefined';
    },

    checkObjectKeys: function(obj) {
      return this.objectPropExists(obj) && _.size(obj) > 0;
    },

    getPropType: function(prop) {
      var type = typeof prop,
        result;

      result = type;

      if (type === 'object') {
        if (_.isArray(prop)) {
          result = 'array';
        }
      }

      return result;
    },

    setConstraints: function(instance, constraints) {

      _.forEach(constraints, function(constraint, prop) {

        if (Common.objectPropExists(constraint)) {
          if (Common.getPropType(constraint) == 'object') {
            _.forEach(constraint, function(value, key) {
              instance[prop][key] = value;
            });
          } else {
            instance[prop] = constraint;
          }
        }

      });
    }
  };

//@body
  return Common;

});
<|endoftext|>


<commit_before>// @todo adapt this to a file checker on an adapter folder.
var builtIn = ['S3'];

var AdapterInjector = function(config) {
    this.config = config;
};

AdapterInjector.prototype.inject = function() {
    var adapter = this.config.retrieve().adapter;
    var bottle = require('bottlejs').pop('main');
    var adapterImpl;
    var path = builtIn.indexOf(adapter) >= 0 ?
        __dirname + '/adapters/' + adapter :
        adapter;
    if (!adapter) {
        console.error('No upload adapter defined.');
        process.exit(1);
    }
    try {
        adapterImpl = require(path);
        bottle.factory('adapter', adapterImpl);
    } catch(e) {
        bottle.factory('adapter', function() {
            return function() {
                console.error('Invalid adapter [%s]', path);
            };
        });
    }
};

module.exports = AdapterInjector;
module.exports.$name = 'adapter_injector';
module.exports.$inject = ['config'];
<commit_msg>Allow init command to bypass.<commit_after>// @todo adapt this to a file checker on an adapter folder.
var builtIn = ['S3'];

var AdapterInjector = function(config) {
    this.config = config;
};

AdapterInjector.prototype.inject = function() {
    var config = this.config.retrieve();
    var adapter = config.adapter;
    var bottle = require('bottlejs').pop('main');
    var adapterImpl;
    var path = builtIn.indexOf(adapter) >= 0 ?
        __dirname + '/adapters/' + adapter :
        adapter;
    if (!config.isDefault && !adapter) {
        console.error('No upload adapter defined.');
        process.exit(1);
    }
    try {
        adapterImpl = require(path);
        bottle.factory('adapter', adapterImpl);
    } catch(e) {
        bottle.factory('adapter', function() {
            return function() {
                console.error('Invalid adapter [%s]', path);
            };
        });
    }
};

module.exports = AdapterInjector;
module.exports.$name = 'adapter_injector';
module.exports.$inject = ['config'];
<|endoftext|>


<commit_before>/**
 * Created by mjul on 18/09/14.
 */

"use strict";

var Value = React.createClass({
    displayName: 'Value',
    handleDeleteValue: function(evt) {
        evt.preventDefault();
        this.props.onValueDeleted(this.props.data);
    },
    render: function () {
        return React.DOM.li({className: 'value'},
            this.props.data.text,
            React.DOM.button({onClick: this.handleDeleteValue, className: 'delete'}, "X"));
    }
});

var Group = React.createClass({
    displayName: 'Group',
    getInitialState: function () {
        return {newValue: ''};
    },
    handleChange: function (evt) {
        this.setState({newValue: evt.target.value});
    },
    handleAddValue: function (evt) {
        evt.preventDefault();
        var nextNewValue = '';
        this.setState({newValue: nextNewValue});
        this.props.onGroupValueAdded(this.props.data, {text: this.state.newValue});
    },
    handleValueDeleted: function(value) {
        this.props.onGroupValueDeleted(this.props.data, value);
    },
    render: function () {
        var deletedCallback = this.handleValueDeleted;
        var values = this.props.data.values.map(function (v, index) {
            return Value({data: v, key: "value_" + v.valueId, onValueDeleted: deletedCallback});
        });
        return React.DOM.div({className: 'group'},
            React.DOM.h2(null, this.props.data.name),
            React.DOM.div({className: 'values'},
                React.DOM.ul(null, values),
                React.DOM.div(null,
                    React.DOM.form({onSubmit: this.handleAddValue},
                        React.DOM.input({onChange: this.handleChange, value: this.state.newValue}),
                        React.DOM.button(null, "Add Value")))
                ));
    }
});

var GroupsAndValues = React.createClass({
    displayName: 'GroupsAndValues',
    getInitialState: function () {
        return {
            data: this.props.data,
            newGroup: ''
        };
    },
    handleChange: function (evt) {
        this.setState({newGroup: evt.target.value});
    },
    handleGroupValueAdded: function (group, newValue) {
        var groups = this.state.data;
        var groupPos = groups.indexOf(group);
        var maxValueId = -1;
        groups.forEach(function (group) {
            var vals = group.values.map(function (v) {
                return v.valueId;
            });
            var maxInGroup = Math.max.apply(Math, vals);
            maxValueId = Math.max(maxValueId, maxInGroup);
        });
        newValue.valueId = maxValueId + 1;
        var group = groups[groupPos];
        var newGroup = React.addons.update(group, {values: {$push: [newValue]}});
        var newGroups = React.addons.update(groups, {$splice: [[groupPos,1,newGroup]]});
        this.setState({data: newGroups});
    },
    handleGroupValueDeleted: function (group, valueToDelete) {
        var groups = this.state.data;
        var valuePos = group.values.indexOf(valueToDelete);
        var groupPos = groups.indexOf(group);
        var newGroup = React.addons.update(group, {values: {$splice: [[valuePos, 1]]}});
        var newGroups = React.addons.update(groups, {$splice: [[groupPos, 1, newGroup]]});
        this.setState({data: newGroups});
    },
    handleAddGroup: function (evt) {
        evt.preventDefault();
        var groups = this.state.data;
        var maxGroupId = groups.length + 1;
        //var maxGroupId = Math.max.apply(groups.map(function (g) { return g.groupId; }));
        var newGroup = {groupId: maxGroupId + 1, name: this.state.newGroup, values: []};
        this.state.newGroup = '';
        this.setState({data: groups.concat([newGroup])});
    },
    render: function () {
        var groupValueCallback = this.handleGroupValueAdded;
        var groupValueDeletedCallback = this.handleGroupValueDeleted;
        var groupCallback = this.handleGroupAdded;
        var items = this.state.data.map(function (group, index) {
            return Group(
                {data: group, key: "group_" + group.groupId,
                    onGroupValueAdded: groupValueCallback,
                    onGroupValueDeleted: groupValueDeletedCallback,
                    onGroupAdded: groupCallback});
        });
        return React.DOM.div({className: 'groupsAndValues'}, items,
            React.DOM.div(null,
                React.DOM.form({onSubmit: this.handleAddGroup},
                    React.DOM.input({onChange: this.handleChange, value: this.state.newGroup}),
                    React.DOM.button(null, "Add Group")
                )
            )
        );
    }
});

function renderGroupsAndValues(dom_id) {
    var target_div = document.getElementById(dom_id);
    var data = [
        {groupId: 1,
            name: 'How many hours?',
            values: [
                {valueId: 1, text: '54'},
                {valueId: 2, text: '62'},
                {valueId: 3, text: '48'}
            ]},
        {groupId: 2,
            name: 'How many cities?',
            values: [
                {valueId: 4, text: '2'},
                {valueId: 5, text: '6'},
                {valueId: 6, text: '5'}
            ]},
        {groupId: 3,
            name: 'Which of these companies?',
            values: [
                {valueId: 7, text: 'Swipe'},
                {valueId: 8, text: 'Wimp'},
                {valueId: 9, text: 'Appear.in'}
            ]}
    ];
    React.renderComponent(GroupsAndValues({data: data}), target_div);
}

window.addEventListener('load', function (evt) {
    renderGroupsAndValues('content');
});
<commit_msg>Extracted ListItem and List components<commit_after>/**
 * Created by mjul on 18/09/14.
 */

"use strict";

var ListItem = React.createClass({
    displayName: 'ListItem',

    propTypes: {
        index: React.PropTypes.number.isRequired,
        data: React.PropTypes.object.isRequired,
        onListItemDeleted: React.PropTypes.func
    },

    handleDelete: function (evt) {
        evt.preventDefault();
        if (this.props.onListItemDeleted) {
            this.props.onListItemDeleted(this.props.index, this.props.data)
        }
    },

    render: function () {
        return React.DOM.li({className: 'listItem'},
            React.DOM.div({className: 'listItemChildren'}, this.props.children),
            React.DOM.div({className: 'listItemControls'},
                React.DOM.button({className: 'delete', onClick: this.handleDelete}, 'Delete')));
    }
});

var List = React.createClass({
    displayName: 'List',

    propTypes: {
        data: React.PropTypes.array.isRequired,
        onListItemDeleted: React.PropTypes.func
    },

    handleListItemDeleted: function (itemNumber, itemData) {
        var newItems = React.addons.update(this.props.data, {$splice: [[itemNumber,1]]});
        if (this.props.onListItemDeleted) {
            this.props.onListItemDeleted(itemNumber, newItems, itemData);
        }
    },

    render: function () {
        var deletedCallback = this.handleListItemDeleted;
        var dataItems = this.props.data;
        var items = React.Children.map(this.props.children, function (c, index) {
            var d = dataItems[index];
            return ListItem({key: 'LI_key_' + index, onListItemDeleted: deletedCallback,
                             index: index, data: d}, c);
        });
        return React.DOM.ul({className: 'list', data: this.props.data},
            items
        );
    }
});

var Value = React.createClass({
    displayName: 'Value',
    propTypes: {
        data: React.PropTypes.shape({text: React.PropTypes.string.isRequired}).isRequired,
        onListItemDeleted: React.PropTypes.func
    },
    render: function () {
        return React.DOM.div({className: 'value'}, this.props.data.text);
    }
});

var Group = React.createClass({
    displayName: 'Group',

    propTypes: {
        index: React.PropTypes.number.isRequired,
        data: React.PropTypes.shape({
            groupId: React.PropTypes.number.isRequired,
            name: React.PropTypes.string.isRequired,
            values: React.PropTypes.array.isRequired
        }).isRequired,
        onGroupValueDeleted: React.PropTypes.func,
        onGroupValueAdded: React.PropTypes.func
    },

    getInitialState: function () {
        return {newValue: ''};
    },
    handleChange: function (evt) {
        var newValue = evt.target.value;
        this.setState({newValue: newValue});
    },
    handleAddValue: function (evt) {
        evt.preventDefault();
        var nextNewValue = '';
        var group = this.props.data;
        var newValue = {text: this.state.newValue};
        var newGroup = React.addons.update(group, {values: {$push: [newValue]}});
        this.state.newValue = '';
        this.props.onGroupValueAdded(this.props.index, newGroup, newValue);
    },
    handleValueDeleted: function (valueIndex, newValues, deletedValue) {
        var newGroup = React.addons.update(this.props.data, {values: {$set: newValues}});
        if (this.props.onGroupValueDeleted) {
            this.props.onGroupValueDeleted(this.props.index, newGroup, deletedValue);
        }
    },
    render: function () {
        var deletedCallback = this.handleValueDeleted;
        var dataValues = this.props.data.values;
        var values = dataValues.map(function (v, index) {
            return Value({data: v});
        });
        return React.DOM.div({className: 'group'},
            React.DOM.h2(null, this.props.data.name),
            React.DOM.div({className: 'values'},
                List({onListItemDeleted: deletedCallback, data: dataValues}, values),
                React.DOM.div(null,
                    React.DOM.form({onSubmit: this.handleAddValue},
                        React.DOM.input({onChange: this.handleChange, value: this.state.newValue}),
                        React.DOM.button({disabled: (this.state.newValue.length == 0)}, "Add Value")))
            ));
    }
});

var GroupsAndValues = React.createClass({
    displayName: 'GroupsAndValues',
    getInitialState: function () {
        return {
            data: this.props.data,
            newGroup: ''
        };
    },
    handleChange: function (evt) {
        this.setState({newGroup: evt.target.value});
    },

    handleGroupValueAdded: function (index, newGroup, newValue) {
        var groups = this.state.data;
        var maxValueId = -1;
        groups.forEach(function (group) {
            var vals = group.values.map(function (v) {
                return v.valueId;
            });
            var maxInGroup = Math.max.apply(Math, vals);
            maxValueId = Math.max(maxValueId, maxInGroup);
        });
        var valueIndex = newGroup.values.indexOf(newValue);
        newValue.valueId = maxValueId;
        newGroup[valueIndex] = newValue;
        var newGroups = React.addons.update(groups, {$splice: [[index, 1, newGroup]]});
        this.setState({data: newGroups});
    },

    handleGroupValueDeleted: function (index, newGroup, deletedValue) {
        var groups = this.state.data;
        var newGroups = React.addons.update(groups, {$splice: [[index, 1, newGroup]]});
        this.setState({data: newGroups});
    },

    handleAddGroup: function (evt) {
        evt.preventDefault();
        var groups = this.state.data;
        var maxGroupId = Math.max.apply(groups.map(function (g) { return g.groupId; }));
        var newGroup = {groupId: maxGroupId + 1, name: this.state.newGroup, values: []};
        this.state.newGroup = '';
        this.setState({data: groups.concat([newGroup])});
    },

    render: function () {
        var groupValueCallback = this.handleGroupValueAdded;
        var groupValueDeletedCallback = this.handleGroupValueDeleted;
        var groupCallback = this.handleGroupAdded;
        var items = this.state.data.map(function (group, index) {
            return Group(
                {data: group,
                 index: index,
                 key: "group_" + group.groupId,
                 onGroupValueAdded: groupValueCallback,
                 onGroupValueDeleted: groupValueDeletedCallback,
                 onGroupAdded: groupCallback});
        });
        return React.DOM.div({className: 'groupsAndValues'}, items,
            React.DOM.div(null,
                React.DOM.form({onSubmit: this.handleAddGroup},
                    React.DOM.input({onChange: this.handleChange, value: this.state.newGroup}),
                    React.DOM.button({disabled: (this.state.newGroup.length == 0)}, "Add Group")
                )
            )
        );
    }
});

function renderGroupsAndValues(dom_id) {
    var target_div = document.getElementById(dom_id);
    var data = [
        {groupId: 1,
            name: 'How many hours?',
            values: [
                {valueId: 1, text: '54'},
                {valueId: 2, text: '62'},
                {valueId: 3, text: '48'}
            ]},
        {groupId: 2,
            name: 'How many cities?',
            values: [
                {valueId: 4, text: '2'},
                {valueId: 5, text: '6'},
                {valueId: 6, text: '5'}
            ]},
        {groupId: 3,
            name: 'Which of these companies?',
            values: [
                {valueId: 7, text: 'Swipe'},
                {valueId: 8, text: 'Wimp'},
                {valueId: 9, text: 'Appear.in'}
            ]}
    ];
    React.renderComponent(GroupsAndValues({data: data}), target_div);
}

window.addEventListener('load', function (evt) {
    renderGroupsAndValues('content');
});
<|endoftext|>


<commit_before>// Copyright (c) 2016 Gamaiel Zavala. All rights reserved. Copyrights licensed under the MIT License.
// See the accompanying LICENSE file for terms.

(function(){

var util = SimpleUtil,
    WALK_DIST  = 1,
    WALK_TIME  = 25,

    CHAR_START = 2,
    CHAR_END   = 6,
    CHAR_LR    = 1,
    CHAR_DOWN  = 2,
    CHAR_UP    = 3,

    // dir values based on arrow keycodes
    DIR_N = 38,
    DIR_S = 40,
    DIR_W = 37,
    DIR_E = 39,
    DIR_IDLE = 32; // space

AdventurePlayer = function (path, opts, cb)
{
    var self = this,
        keyFunc = function(e){ self.animateWalk(e); };

    opts ? null : opts = {};

    AdventurePlayer.parent.constructor.apply(self, arguments);

    util.setStyles(self.container, {
        transitionProperty: 'top, left',
        transitionTimingFunction: 'linear'
        //transformOrigin: '50% 100%'
    }, true);

    // must be called after self.container is set
    self.setDuration();

    //util.listen(window, 'keydown', keyFunc);
    //util.listen(window, 'keyup', keyFunc);

    util.listen(self.container, util.resolvePrefix('transitionend'), function(e)
    {
        var prop = e.propertyName,
            value;

        switch(prop)
        {
            case 'left':
            case 'top':
                self.walkPath();
        }
    });

    //setInterval(function(){ self.walk(); }, WALK_TIME);
}

util.extend(AdventurePlayer, AdventureItem,
{
    walkSpeed: 100,
    prevFrame: CHAR_DOWN,
    path: [],
    lastDir: null,
    lastZ: 0,
    objective: null,
    movePayload: null,

    getPublicMethods: function()
    {
        return ['cycleDialog', 'collidesWith', 'get', 'getBounds', 'getCoords', 'getHeight', 'getWidth', 'getXY',
                'has', 'isAt', 'on', 'say', 'setObjective', 'setXY', 'walkTo'];
    },

    animateWalk: function(e)
    {
        var self = this,
            dir = e.dir || e.keyCode,
            handled;

        if(dir === DIR_IDLE || e.type === 'keyup')
        {
            self.setFrame(self._sprite.cols*(self.prevFrame-1)+1);
            self.stop();
            self.lastDir = null;
        }
        else if(dir && dir !== self.lastDir)
        {
            if (self.lastDir == DIR_W || self.lastDir === null) {
                self.mirror(false);
            }

            switch(dir)
            {
                case DIR_N:
                    self.setFrameBounds((CHAR_UP-1)*self._sprite.cols+CHAR_START, (CHAR_UP-1)*self._sprite.cols+CHAR_END);
                    self.prevFrame = CHAR_UP;
                    handled = true;
                break;
                case DIR_S:
                    self.setFrameBounds((CHAR_DOWN-1)*self._sprite.cols+CHAR_START, (CHAR_DOWN-1)*self._sprite.cols+CHAR_END);
                    self.prevFrame = CHAR_DOWN;
                    handled = true;
                break;
                case DIR_W:
                    self.mirror();
                    self.setFrameBounds(CHAR_LR*CHAR_START, CHAR_LR*CHAR_END);
                    self.prevFrame = CHAR_LR;
                    handled = true;
                break;
                case DIR_E:
                    self.setFrameBounds(CHAR_LR*CHAR_START, CHAR_LR*CHAR_END);
                    self.prevFrame = CHAR_LR;
                    handled = true;
                break;
            }

            self.play();

            self.lastDir = handled ? dir : null;
        }

        if(self.lastDir && e.keyCode){
            util.processEvent(e, true);
        }
    },

    walkPath: function()
    {
        var self = this,
            path = self.path;

        if (self.movePayload) {
            self.fire('aftermove', self.movePayload);
        }

        if(path.length)
        {
            var node = path.shift(),
                size = self.getTileSize(),
                origin = self.getOrigin(),
                intVal = parseInt,
                // find center xy of tile
                // TODO: make sense out of transposed x/y
                x = intVal(node.y * size + size / 2 - origin[0]),
                y = intVal(node.x * size + size / 2 - origin[1]),
                curX = self.getX(),
                curY = self.getY(),
                isDiagonal = curX !== x && curY !== y,
                duration = isDiagonal ? 2.0 : 1.0,
                dir = self.coordsToDir([x, y]);

            //self.tileAt([x, y], true); // debug
            self.movePayload = {from: [curX, curY], to: [x, y], done: path.length === 1};
            self.setDuration(duration);
            self.animateWalk({dir: dir});
            self.fire('beforemove', self.movePayload);
            self.setXY(x, y);
        }
        else
        {
            var target = self.target;

            self.animateWalk({dir: DIR_IDLE});

            // face the target if present
            if (target) {
                self.face(target);
                self.target = null;
            }

            self.completeObjective();
        }
    },

    walkTo: function(coords, objective)
    {
        var self = this,
            path;

        if (coords instanceof AdventureItem) {
            self.target = coords;
            coords = self.target.getWalkTo();
        } else if (objective) {
            self.target = objective.target;
        }

        path = self.coordsToPath(coords);
        if (path && path.length) {
            self.setPath(path);
        // TODO verify player walked to target?
        } else {
            self.completeObjective();
        }

        self.setObjective(objective);
    },

    completeObjective: function()
    {
        var self = this,
            objective = self.objective || {};

        if (util.isFunc(objective)) {
            objective();
        } else if (objective.target) {
            objective.target.fire(objective.action);
        }

        // clear objective
        self.setObjective(null);
    },

    face: function(obj)
    {
        var self = this;
        self.animateWalk({dir: self.coordsToDir(obj)});
        self.animateWalk({dir: DIR_IDLE});
    },

    coordsToDir: function(obj)
    {
        var self = this, x, y,
            curX = self.getX(),
            curY = self.getY(),
            collides = true,
            coords,
            dir;

        if (obj instanceof AdventureItem) {
            coords = [obj.getX(), obj.getY()];
            collides = obj.collidesWith(self.getBounds());
        } else {
            coords = obj;
        }

        x = coords[0];
        y = coords[1];

        switch(true)
        {
            case curY > y && collides:
                dir = DIR_N; break;
            case curX > x:
                dir = DIR_W; break;
            case curX < x:
                dir = DIR_E; break;
            case curY < y:
                dir = DIR_S; break;
        }

        return dir;
    },

    setPath: function(path)
    {
        var self = this;
        self.path = path;
        self.setObjective(null);
        self.walkPath();
    },

    setObjective: function(objective)
    {
        var self = this;
        self.objective = objective;
    },

    isAt: function(asset)
    {
        if (!(asset instanceof AdventureAsset)) {
            //return false;
        }

        var self = this,
            walkTo = asset.getWalkTo(),
            player = asset.getPlayer(),
            playerCoords = self.getCoords(),
            size = self.getTileSize(),
            abs = Math.abs;

        // check if the player is on point
        if (abs(playerCoords[0]-walkTo[0]) < size
         && abs(playerCoords[1]-walkTo[1]) < size) {
            return true;
        }

        return false;
    },

    setDuration: function(multiplier)
    {
        var self = this,
            duration = self.walkSpeed / 1000 * (multiplier||1) + 's';

        util.setStyle(self.container, 'transitionDuration', duration, true);

        return duration;
    },

    getCoords: function()
    {
        var self = this,
            origin = self.getOrigin(),
            x = self.getX() + origin[0],
            y = self.getY() + origin[1];

        return [x, y];
    },

    getOrigin: function()
    {
        var self = this,
            w = self.width,
            h = self.height,
            x = Math.round(w/2),
            y = h;

        return [x, y];
    },

    isWalkable: function(x, y, dir)
    {
        var self = this,
            h = self.height,
            w = self.width;

        return self.tileAt([x, y + h])[2];
    },

    isWalking: function()
    {
        return this.isPlaying();
    },

    setXY: function(x, y, rel)
    {
        var self = this;
        AdventurePlayer.parent.setXY.apply(self, arguments);
        self.setZ();
    },

    setZ: function()
    {
        var self = this;
        util.setStyle(self.container, 'zIndex', self.getMaxZ());
    },

    serialize: function()
    {
        var self = this;
        AdventurePlayer.parent.serialize.apply(self, arguments);
        // set attrs directly since `set` will end up calling setX
        // TODO setAttr?
        self.attrs.x = parseInt(self.getStyle('left'), 10);
        self.attrs.y = parseInt(self.getStyle('top'), 10);
    },

    /*
    walk: function()
    {
        var self = this,
            dir = self.lastDir,
            sprite = self,
            x = self.getX(),
            y = self.getY();

        if(!dir) return;

        switch(dir)
        {
            case DIR_N:
                if(self.isWalkable(x - WALK_DIST, y - WALK_DIST)) {
                    sprite.setY(-(WALK_DIST), true);
                }
            break;
            case DIR_S:
                if(self.isWalkable(x - WALK_DIST, y + WALK_DIST)) {
                    sprite.setY(WALK_DIST, true);
                }
            break;
            case DIR_W:
                if(self.isWalkable(x - WALK_DIST, y - WALK_DIST)) {
                    sprite.setX(-(WALK_DIST), true);
                }
            break;
            case DIR_E:
                if(self.isWalkable(x + WALK_DIST, y - WALK_DIST)) {
                    sprite.setX(WALK_DIST, true);
                }
            break;
        }
    },
    */

    // the following methods are augmented by Adventure

    say: function(msg)
    {
    },

    tileAt: function()
    {
    },

    getTileSize: function()
    {
    },

    getMaxZ: function()
    {
    }
});

}());
<commit_msg>Call setObjective in correct order<commit_after>// Copyright (c) 2016 Gamaiel Zavala. All rights reserved. Copyrights licensed under the MIT License.
// See the accompanying LICENSE file for terms.

(function(){

var util = SimpleUtil,
    WALK_DIST  = 1,
    WALK_TIME  = 25,

    CHAR_START = 2,
    CHAR_END   = 6,
    CHAR_LR    = 1,
    CHAR_DOWN  = 2,
    CHAR_UP    = 3,

    // dir values based on arrow keycodes
    DIR_N = 38,
    DIR_S = 40,
    DIR_W = 37,
    DIR_E = 39,
    DIR_IDLE = 32; // space

AdventurePlayer = function (path, opts, cb)
{
    var self = this,
        keyFunc = function(e){ self.animateWalk(e); };

    opts ? null : opts = {};

    AdventurePlayer.parent.constructor.apply(self, arguments);

    util.setStyles(self.container, {
        transitionProperty: 'top, left',
        transitionTimingFunction: 'linear'
        //transformOrigin: '50% 100%'
    }, true);

    // must be called after self.container is set
    self.setDuration();

    //util.listen(window, 'keydown', keyFunc);
    //util.listen(window, 'keyup', keyFunc);

    util.listen(self.container, util.resolvePrefix('transitionend'), function(e)
    {
        var prop = e.propertyName,
            value;

        switch(prop)
        {
            case 'left':
            case 'top':
                self.walkPath();
        }
    });

    //setInterval(function(){ self.walk(); }, WALK_TIME);
}

util.extend(AdventurePlayer, AdventureItem,
{
    walkSpeed: 100,
    prevFrame: CHAR_DOWN,
    path: [],
    lastDir: null,
    lastZ: 0,
    objective: null,
    movePayload: null,

    getPublicMethods: function()
    {
        return ['cycleDialog', 'collidesWith', 'get', 'getBounds', 'getCoords', 'getHeight', 'getWidth', 'getXY',
                'has', 'isAt', 'on', 'say', 'setObjective', 'setXY', 'walkTo'];
    },

    animateWalk: function(e)
    {
        var self = this,
            dir = e.dir || e.keyCode,
            handled;

        if(dir === DIR_IDLE || e.type === 'keyup')
        {
            self.setFrame(self._sprite.cols*(self.prevFrame-1)+1);
            self.stop();
            self.lastDir = null;
        }
        else if(dir && dir !== self.lastDir)
        {
            if (self.lastDir == DIR_W || self.lastDir === null) {
                self.mirror(false);
            }

            switch(dir)
            {
                case DIR_N:
                    self.setFrameBounds((CHAR_UP-1)*self._sprite.cols+CHAR_START, (CHAR_UP-1)*self._sprite.cols+CHAR_END);
                    self.prevFrame = CHAR_UP;
                    handled = true;
                break;
                case DIR_S:
                    self.setFrameBounds((CHAR_DOWN-1)*self._sprite.cols+CHAR_START, (CHAR_DOWN-1)*self._sprite.cols+CHAR_END);
                    self.prevFrame = CHAR_DOWN;
                    handled = true;
                break;
                case DIR_W:
                    self.mirror();
                    self.setFrameBounds(CHAR_LR*CHAR_START, CHAR_LR*CHAR_END);
                    self.prevFrame = CHAR_LR;
                    handled = true;
                break;
                case DIR_E:
                    self.setFrameBounds(CHAR_LR*CHAR_START, CHAR_LR*CHAR_END);
                    self.prevFrame = CHAR_LR;
                    handled = true;
                break;
            }

            self.play();

            self.lastDir = handled ? dir : null;
        }

        if(self.lastDir && e.keyCode){
            util.processEvent(e, true);
        }
    },

    walkPath: function()
    {
        var self = this,
            path = self.path;

        if (self.movePayload) {
            self.fire('aftermove', self.movePayload);
        }

        if(path.length)
        {
            var node = path.shift(),
                size = self.getTileSize(),
                origin = self.getOrigin(),
                intVal = parseInt,
                // find center xy of tile
                // TODO: make sense out of transposed x/y
                x = intVal(node.y * size + size / 2 - origin[0]),
                y = intVal(node.x * size + size / 2 - origin[1]),
                curX = self.getX(),
                curY = self.getY(),
                isDiagonal = curX !== x && curY !== y,
                duration = isDiagonal ? 2.0 : 1.0,
                dir = self.coordsToDir([x, y]);

            //self.tileAt([x, y], true); // debug
            self.movePayload = {from: [curX, curY], to: [x, y], done: path.length === 1};
            self.setDuration(duration);
            self.animateWalk({dir: dir});
            self.fire('beforemove', self.movePayload);
            self.setXY(x, y);
        }
        else
        {
            var target = self.target;

            self.animateWalk({dir: DIR_IDLE});

            // face the target if present
            if (target) {
                self.face(target);
                self.target = null;
            }

            self.completeObjective();
        }
    },

    walkTo: function(coords, objective)
    {
        var self = this,
            path;

        if (coords instanceof AdventureItem) {
            self.target = coords;
            coords = self.target.getWalkTo();
        } else if (objective) {
            self.target = objective.target;
        }

        path = self.coordsToPath(coords);
        if (path && path.length) {
            self.setPath(path);
            self.setObjective(objective);
        // TODO verify player walked to target?
        } else {
            self.setObjective(objective);
            self.completeObjective();
        }

    },

    completeObjective: function()
    {
        var self = this,
            objective = self.objective || {};

        if (util.isFunc(objective)) {
            objective();
        } else if (objective.target) {
            objective.target.fire(objective.action);
        }

        // clear objective
        self.setObjective(null);
    },

    face: function(obj)
    {
        var self = this;
        self.animateWalk({dir: self.coordsToDir(obj)});
        self.animateWalk({dir: DIR_IDLE});
    },

    coordsToDir: function(obj)
    {
        var self = this, x, y,
            curX = self.getX(),
            curY = self.getY(),
            collides = true,
            coords,
            dir;

        if (obj instanceof AdventureItem) {
            coords = [obj.getX(), obj.getY()];
            collides = obj.collidesWith(self.getBounds());
        } else {
            coords = obj;
        }

        x = coords[0];
        y = coords[1];

        switch(true)
        {
            case curY > y && collides:
                dir = DIR_N; break;
            case curX > x:
                dir = DIR_W; break;
            case curX < x:
                dir = DIR_E; break;
            case curY < y:
                dir = DIR_S; break;
        }

        return dir;
    },

    setPath: function(path)
    {
        var self = this;
        self.path = path;
        self.setObjective(null);
        self.walkPath();
    },

    setObjective: function(objective)
    {
        var self = this;
        self.objective = objective;
    },

    isAt: function(asset)
    {
        if (!(asset instanceof AdventureAsset)) {
            //return false;
        }

        var self = this,
            walkTo = asset.getWalkTo(),
            player = asset.getPlayer(),
            playerCoords = self.getCoords(),
            size = self.getTileSize(),
            abs = Math.abs;

        // check if the player is on point
        if (abs(playerCoords[0]-walkTo[0]) < size
         && abs(playerCoords[1]-walkTo[1]) < size) {
            return true;
        }

        return false;
    },

    setDuration: function(multiplier)
    {
        var self = this,
            duration = self.walkSpeed / 1000 * (multiplier||1) + 's';

        util.setStyle(self.container, 'transitionDuration', duration, true);

        return duration;
    },

    getCoords: function()
    {
        var self = this,
            origin = self.getOrigin(),
            x = self.getX() + origin[0],
            y = self.getY() + origin[1];

        return [x, y];
    },

    getOrigin: function()
    {
        var self = this,
            w = self.width,
            h = self.height,
            x = Math.round(w/2),
            y = h;

        return [x, y];
    },

    isWalkable: function(x, y, dir)
    {
        var self = this,
            h = self.height,
            w = self.width;

        return self.tileAt([x, y + h])[2];
    },

    isWalking: function()
    {
        return this.isPlaying();
    },

    setXY: function(x, y, rel)
    {
        var self = this;
        AdventurePlayer.parent.setXY.apply(self, arguments);
        self.setZ();
    },

    setZ: function()
    {
        var self = this;
        util.setStyle(self.container, 'zIndex', self.getMaxZ());
    },

    serialize: function()
    {
        var self = this;
        AdventurePlayer.parent.serialize.apply(self, arguments);
        // set attrs directly since `set` will end up calling setX
        // TODO setAttr?
        self.attrs.x = parseInt(self.getStyle('left'), 10);
        self.attrs.y = parseInt(self.getStyle('top'), 10);
    },

    /*
    walk: function()
    {
        var self = this,
            dir = self.lastDir,
            sprite = self,
            x = self.getX(),
            y = self.getY();

        if(!dir) return;

        switch(dir)
        {
            case DIR_N:
                if(self.isWalkable(x - WALK_DIST, y - WALK_DIST)) {
                    sprite.setY(-(WALK_DIST), true);
                }
            break;
            case DIR_S:
                if(self.isWalkable(x - WALK_DIST, y + WALK_DIST)) {
                    sprite.setY(WALK_DIST, true);
                }
            break;
            case DIR_W:
                if(self.isWalkable(x - WALK_DIST, y - WALK_DIST)) {
                    sprite.setX(-(WALK_DIST), true);
                }
            break;
            case DIR_E:
                if(self.isWalkable(x + WALK_DIST, y - WALK_DIST)) {
                    sprite.setX(WALK_DIST, true);
                }
            break;
        }
    },
    */

    // the following methods are augmented by Adventure

    say: function(msg)
    {
    },

    tileAt: function()
    {
    },

    getTileSize: function()
    {
    },

    getMaxZ: function()
    {
    }
});

}());
<|endoftext|>