Advertisement
Guest User

Untitled

a guest
Feb 8th, 2016
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 27.57 KB | None | 0 0
  1. /* global google */
  2. (function() {
  3. 'use strict';
  4.  
  5. function getEveryTargetWeekdayInDateRange(startDateTime, endDateTime, targetWeekday, eventType) {
  6. var currentDate = startDateTime;
  7. var dates = [];
  8. var biWeeklyEventSwitch = false;
  9.  
  10. // this function calculates the start time and end time for each recurring event occurrence.
  11. // the result of this function will be finally saved in the DB
  12. function calculateDatesObj(startDateTime, endDateTime){
  13. var date = {};
  14. var offset = moment(startDateTime.toISOString()).utcOffset();
  15. moment().utcOffset(offset);
  16. date.startTime = moment.utc(startDateTime).add(startDateTimeOffset, 'minutes');
  17. var mEventDate = moment.utc(startDateTime);
  18. var mEventLastDate = moment.utc(endDateTime).add(endDateTimeOffset, 'minutes');
  19. date.endTime = moment([ mEventDate.get('year'), mEventDate.get('month'), mEventDate.date(),
  20. mEventLastDate.get('hour'), mEventLastDate.get('minute'), mEventLastDate.get('second'), mEventLastDate.get('millisecond') ]).toDate();
  21. return date;
  22. }
  23.  
  24. if(eventType === 'one-off') {
  25. dates.push(calculateDatesObj(currentDate, endDateTime));
  26. } else {
  27. while (currentDate <= endDateTime) {
  28. var currentTime = moment(new Date(currentDate));
  29. currentDate = currentTime.toDate()
  30.  
  31. if (currentDate.getDay() === targetWeekday) {
  32. if (eventType === 'weekly') {
  33. dates.push(calculateDatesObj(currentTime, endDateTime));
  34. } else {
  35. if (!biWeeklyEventSwitch) {
  36. dates.push(calculateDatesObj(currentTime, endDateTime));
  37. biWeeklyEventSwitch = true;
  38. } else {
  39. biWeeklyEventSwitch = false;
  40. }
  41. }
  42. }
  43.  
  44. currentDate = moment.utc(currentDate).add(1, 'days');
  45. }
  46. }
  47.  
  48. return dates;
  49. }
  50.  
  51. function goToManageDojoEvents($state, usSpinnerService, dojoId) {
  52. if(usSpinnerService) {
  53. usSpinnerService.stop('create-event-spinner');
  54. }
  55. $state.go('manage-dojo-events', {
  56. dojoId: dojoId
  57. });
  58. }
  59.  
  60. function goToManageDojoEvent($state, usSpinnerService, dojoId, eventId) {
  61. if(usSpinnerService) {
  62. usSpinnerService.stop('create-event-spinner');
  63. }
  64. $state.go('manage-applications', {
  65. dojoId: dojoId,
  66. eventId: eventId
  67. });
  68. }
  69.  
  70. function goToMyDojos($state, usSpinnerService) {
  71. usSpinnerService.stop('create-event-spinner');
  72. $state.go('my-dojos');
  73. }
  74.  
  75. function fixEventDates(newDate, oldDate){
  76. newDate = moment.utc(newDate);
  77. oldDate = moment.utc(oldDate);
  78. return moment.utc([ newDate.get('year'),newDate.get('month'), newDate.date(),
  79. oldDate.get('hour'), oldDate.get('minute'), oldDate.get('second'), oldDate.get('millisecond') ]);
  80. }
  81.  
  82. function fixEventTime(newTime, date){
  83. newTime = moment.utc(newTime);
  84. date = moment.utc(date);
  85. return moment.utc([ date.get('year'), date.get('month'), date.date(),
  86. newTime.get('hour'), newTime.get('minute'), newTime.get('second'), newTime.get('millisecond') ]);
  87. }
  88.  
  89. function dojoEventFormCtrl($scope, $stateParams, $state, $sce, $localStorage, $modal, cdEventsService, cdDojoService, cdUsersService, auth, $translate, cdLanguagesService, usSpinnerService, alertService, utilsService, ticketTypes, currentUser) {
  90. var dojoId = $stateParams.dojoId;
  91. var now = moment.utc().toDate();
  92. var defaultEventTime = moment.utc(now).add(2, 'hours').toDate();
  93. var defaultEventEndTime = moment.utc(now).add(3, 'hours').toDate();
  94. $scope.today = moment.utc().toDate();
  95. $scope.ticketTypes = ticketTypes.data || [];
  96. $scope.ticketTypesTooltip = '';
  97.  
  98. _.each($scope.ticketTypes, function (ticketType, index) {
  99. ticketType.title = $translate.instant(ticketType.title);
  100. if(index !== 0) {
  101. $scope.ticketTypesTooltip += '<br>' + $translate.instant(ticketType.tooltip);
  102. } else {
  103. $scope.ticketTypesTooltip += $translate.instant(ticketType.tooltip);
  104. }
  105. });
  106.  
  107. $scope.ticketTypesTooltip = $sce.trustAsHtml($scope.ticketTypesTooltip);
  108.  
  109. $scope.eventInfo = {};
  110. $scope.eventInfo.dojoId = dojoId;
  111. $scope.eventInfo.public = true;
  112. $scope.eventInfo.prefillAddress = false;
  113. $scope.eventInfo.recurringType = 'weekly';
  114. $scope.eventInfo.sessions = [{name: null, tickets:[{name: null, type: null, quantity: 0}]}];
  115.  
  116. $scope.eventInfo.date = defaultEventTime;
  117. $scope.eventInfo.toDate = defaultEventEndTime;
  118.  
  119. $scope.eventInfo.startTime = defaultEventTime;
  120. $scope.eventInfo.startTime.setMinutes(0);
  121. $scope.eventInfo.startTime.setSeconds(0);
  122.  
  123. $scope.eventInfo.endTime = defaultEventEndTime;
  124. $scope.eventInfo.endTime.setMinutes(0);
  125. $scope.eventInfo.endTime.setSeconds(0);
  126.  
  127. $scope.eventInfo.fixedStartDateTime = $scope.eventInfo.date;
  128. $scope.eventInfo.fixedEndDateTime = $scope.eventInfo.toDate;
  129.  
  130. $scope.datepicker = {};
  131. $scope.datepicker.minDate = now;
  132. $scope.hasAccess = true;
  133.  
  134.  
  135. $scope.$watch('eventInfo.date', function (date) {
  136. $scope.eventInfo.fixedStartDateTime = fixEventDates(date, $scope.eventInfo.fixedStartDateTime);
  137. $scope.eventInfo.startTime = $scope.eventInfo.fixedStartDateTime;
  138. $scope.eventInfo.endTime = fixEventDates($scope.eventInfo.fixedStartDateTime, $scope.eventInfo.fixedEndDateTime);
  139. });
  140.  
  141. $scope.$watch('eventInfo.toDate', function (toDate) {
  142. $scope.eventInfo.fixedEndDateTime = fixEventDates(toDate, $scope.eventInfo.fixedEndDateTime);
  143. $scope.eventInfo.endTime = $scope.eventInfo.fixedEndDateTime;
  144. });
  145.  
  146. $scope.$watch('eventInfo.startTime', function (startTime) {
  147. $scope.eventInfo.fixedStartDateTime = fixEventTime(startTime, $scope.eventInfo.fixedStartDateTime);
  148. });
  149.  
  150. $scope.$watch('eventInfo.endTime', function (endTime) {
  151. $scope.eventInfo.fixedEndDateTime = fixEventTime(endTime, $scope.eventInfo.fixedEndDateTime);
  152. });
  153.  
  154. $scope.toggleDatepicker = function($event, isOpen) {
  155. $event.preventDefault();
  156. $event.stopPropagation();
  157.  
  158. $scope.datepicker[isOpen] = !$scope.datepicker[isOpen];
  159. };
  160.  
  161. $scope.updateLocalStorage = function (item, value) {
  162. if(!_.isEmpty(currentUser.data) && !$stateParams.eventId) {
  163. if(!$localStorage[currentUser.data.id]) $localStorage[currentUser.data.id] = {};
  164. if(!$localStorage[currentUser.data.id][dojoId]) $localStorage[currentUser.data.id][dojoId] = {};
  165. if(!$localStorage[currentUser.data.id][dojoId].eventForm) $localStorage[currentUser.data.id][dojoId].eventForm = {};
  166.  
  167. // what if the actual value is 'false' or 'null'
  168. if(value === false || value === null || value) {
  169. $localStorage[currentUser.data.id][dojoId].eventForm[item] = value;
  170. }
  171. }
  172. };
  173.  
  174. var deleteLocalStorage = function () {
  175. if(!_.isEmpty(currentUser.data)) {
  176. if($localStorage[currentUser.data.id] && $localStorage[currentUser.data.id][dojoId] && $localStorage[currentUser.data.id][dojoId].eventForm) {
  177. delete $localStorage[currentUser.data.id][dojoId].eventForm;
  178. }
  179. }
  180. }
  181.  
  182. $scope.getLocationFromAddress = function(eventInfo, cb) {
  183. utilsService.getEventLocationFromAddress(eventInfo).then(function (data) {
  184. $scope.googleMaps.mapOptions.center = new google.maps.LatLng(data.lat, data.lng);
  185. $scope.googleMaps.map.panTo($scope.googleMaps.mapOptions.center);
  186. $scope.googleMaps.marker.setMap(null);
  187. $scope.googleMaps.marker = new google.maps.Marker({
  188. map: $scope.googleMaps.map,
  189. position: $scope.googleMaps.mapOptions.center
  190. });
  191. eventInfo.position = {
  192. lat: data.lat,
  193. lng: data.lng
  194. };
  195. if(cb) cb();
  196. }, function (err) {
  197. if(err) console.error(err);
  198. alertService.showError($translate.instant('Please add the event location manually by clicking on the map.'));
  199. if(cb) cb();
  200. });
  201. };
  202.  
  203. $scope.validateSessions = function (sessions) {
  204. return sessions.length !== 0;
  205. };
  206.  
  207. $scope.timepicker = {};
  208. $scope.timepicker.hstep = 1;
  209. $scope.timepicker.mstep = 15;
  210. $scope.timepicker.ismeridian = true;
  211.  
  212. $scope.weekdayPicker = {};
  213. $scope.weekdayPicker.weekdays = [{
  214. id: 0,
  215. name: $translate.instant('Sunday')
  216. }, {
  217. id: 1,
  218. name: $translate.instant('Monday')
  219. }, {
  220. id: 2,
  221. name: $translate.instant('Tuesday')
  222. }, {
  223. id: 3,
  224. name: $translate.instant('Wednesday')
  225. }, {
  226. id: 4,
  227. name: $translate.instant('Thursday')
  228. }, {
  229. id: 5,
  230. name: $translate.instant('Friday')
  231. }, {
  232. id: 6,
  233. name: $translate.instant('Saturday')
  234. }];
  235.  
  236. $scope.searchCity = function($select) {
  237. if($scope.hasAccess) {
  238. return utilsService.getPlaces($scope.eventInfo.country.alpha2, $select).then(function (data) {
  239. $scope.cities = data;
  240. }, function (err) {
  241. $scope.cities = [];
  242. console.error(err);
  243. });
  244. }
  245. };
  246.  
  247. $scope.prefillDojoAddress = function() {
  248. if($scope.eventInfo.prefillAddress) {
  249. $scope.eventInfo.city = $scope.eventInfo.dojoCity;
  250. $scope.eventInfo.address = $scope.eventInfo.dojoAddress;
  251.  
  252. $scope.updateLocalStorage('city', $scope.eventInfo.dojoCity);
  253. $scope.updateLocalStorage('address', $scope.eventInfo.dojoAddress);
  254. $scope.updateLocalStorage('prefillAddress', true);
  255. return;
  256. }
  257.  
  258. $scope.updateLocalStorage('prefillAddress', false);
  259. $scope.eventInfo.city = $scope.eventInfo.address = null;
  260. $scope.updateLocalStorage('city', null);
  261. $scope.updateLocalStorage('address', null);
  262. };
  263.  
  264. $scope.eventInfo.invites = [];
  265.  
  266. $scope.cancel = function($event) {
  267. $event.preventDefault();
  268. $event.stopPropagation();
  269. deleteLocalStorage();
  270. goToManageDojoEvents($state, null, dojoId);
  271. };
  272.  
  273. $scope.addSession = function () {
  274. if($scope.eventInfo.sessions.length === 20) return alertService.showError($translate.instant('You can only create a max of 20 sessions/rooms'));
  275. var session = {
  276. name: null,
  277. tickets: [{name: null, type: null, quantity: 0}]
  278. };
  279. $scope.eventInfo.sessions.push(session);
  280. };
  281.  
  282. $scope.addTicket = function (session) {
  283. if(session.tickets.length === 20) return alertService.showError($translate.instant('You can only create a max of 20 ticket types'));
  284. var ticket = {
  285. name: null,
  286. type: null,
  287. quantity: 0
  288. };
  289. session.tickets.push(ticket);
  290. };
  291.  
  292. $scope.removeTicket = function ($index, session) {
  293. if(session.tickets.length === 1) return alertService.showAlert($translate.instant('Your event must contain at least one ticket.'));
  294. return session.tickets.splice($index, 1);
  295. };
  296.  
  297. $scope.removeSession = function ($index) {
  298. if($scope.eventInfo.sessions.length === 1) return alertService.showAlert($translate.instant('Your event must contain at least one session.'));
  299. return $scope.eventInfo.sessions.splice($index, 1);
  300. };
  301.  
  302. $scope.totalSessionCapacity = function (session) {
  303. var total = 0;
  304. _.each(session.tickets, function (ticket) {
  305. if(ticket.type !== 'other') total += ticket.quantity || 0;
  306. });
  307. return total;
  308. };
  309.  
  310. $scope.totalEventCapacity = function () {
  311. var total = 0;
  312. _.each($scope.eventInfo.sessions, function (session) {
  313. total += $scope.totalSessionCapacity(session);
  314. });
  315. return total;
  316. };
  317.  
  318. $scope.inviteDojoMembers = function (session) {
  319. var emptyTicketsFound = _.find(session.tickets, function (ticket) {
  320. return _.isEmpty(ticket.name) || _.isEmpty(ticket.type);
  321. });
  322. if(emptyTicketsFound) return alertService.showAlert($translate.instant('You must complete all of the ticket details before inviting Dojo members.'));
  323. async.waterfall([
  324. retrieveDojoUsers,
  325. showInviteDojoMembersModal
  326. ], function (err) {
  327. if(err) return console.error(err);
  328. });
  329.  
  330. function retrieveDojoUsers(done) {
  331. cdDojoService.loadDojoUsers({dojoId: dojoId}, function (dojoUsers) {
  332. var eventUserSelection = {};
  333. eventUserSelection[dojoId] = [];
  334. _.each(dojoUsers, function (dojoUser) {
  335. eventUserSelection[dojoId].push({userId: dojoUser.id, title: dojoUser.name});
  336. });
  337. return done(null, eventUserSelection);
  338. }, function (err) {
  339. if(err) {
  340. console.error(err);
  341. return done(err);
  342. }
  343. });
  344. }
  345.  
  346. function showInviteDojoMembersModal(eventUserSelection, done) {
  347. var inviteDojoMembersModalInstance = $modal.open({
  348. animation: true,
  349. templateUrl: '/dojos/template/events/session-invite',
  350. controller: 'session-invite-modal-controller',
  351. size: 'lg',
  352. resolve: {
  353. dojoId: function () {
  354. return dojoId;
  355. },
  356. session: function () {
  357. return session;
  358. },
  359. event: function () {
  360. return $scope.eventInfo;
  361. },
  362. eventUserSelection: function () {
  363. return eventUserSelection;
  364. },
  365. currentUser: function () {
  366. return currentUser.data;
  367. }
  368. }
  369. });
  370.  
  371. inviteDojoMembersModalInstance.result.then(function (result) {
  372. if(result.ok === false) return alertService.showError($translate.instant(result.why));
  373. alertService.showAlert($translate.instant('Dojo members successfully added to invite list. They will be notified of the invite when you publish this event.'));
  374. }, null);
  375. return done();
  376. }
  377.  
  378.  
  379. };
  380.  
  381. $scope.scrollToInvalid = function (form) {
  382. if (form.$invalid) {
  383. angular.element('form[name=' + form.$name + '] .ng-invalid')[0].scrollIntoView();
  384. } else {
  385. $scope.eventInfo.publish=true;
  386. }
  387. };
  388.  
  389.  
  390. $scope.submit = function(eventInfo) {
  391. usSpinnerService.spin('create-event-spinner');
  392.  
  393. if($scope.googleMaps && $scope.googleMaps.marker) {
  394. var eventPosition = {
  395. lat: $scope.googleMaps.marker.getPosition().lat(),
  396. lng: $scope.googleMaps.marker.getPosition().lng()
  397. };
  398.  
  399. // Extend eventInfo
  400. eventInfo.position = eventPosition;
  401. }
  402.  
  403. eventInfo.status = eventInfo.publish ? 'published' : 'saved';
  404. delete eventInfo.publish;
  405. eventInfo.userType = eventInfo.userType && eventInfo.userType.name ? eventInfo.userType.name : '';
  406.  
  407. if(!_.isEmpty(eventInfo.invites)) {
  408. eventInfo.emailSubject = $translate.instant('Event Invitation');
  409. }
  410.  
  411. var isDateRange = !moment.utc(eventInfo.toDate).isSame(eventInfo.date, 'day');
  412.  
  413. if (eventInfo.type === 'recurring' && isDateRange) {
  414. // Extend eventInfo
  415. if(eventInfo.recurringType === 'weekly') {
  416. eventInfo.dates = getEveryTargetWeekdayInDateRange(
  417. eventInfo.fixedStartDateTime,
  418. eventInfo.fixedEndDateTime,
  419. $scope.weekdayPicker.selection.id,
  420. 'weekly'
  421. );
  422. } else {
  423. eventInfo.dates = getEveryTargetWeekdayInDateRange(
  424. eventInfo.fixedStartDateTime,
  425. eventInfo.fixedEndDateTime,
  426. $scope.weekdayPicker.selection.id,
  427. 'biweekly'
  428. );
  429. }
  430. } else {
  431. eventInfo.dates = getEveryTargetWeekdayInDateRange(
  432. eventInfo.fixedStartDateTime,
  433. eventInfo.fixedEndDateTime,
  434. null,
  435. 'one-off'
  436. );
  437. }
  438.  
  439. if(!$scope.dojoInfo) {
  440. loadDojo(function(err){
  441. if(err) {
  442. alertService.showError($translate.instant('An error has occurred while loading Dojo') + ' ' + err);
  443. goToMyDojos($state, usSpinnerService, dojoId)
  444. }
  445. if ($scope.dojoInfo.verified === 1 && $scope.dojoInfo.stage !== 4) {
  446. cdEventsService.saveEvent(
  447. eventInfo,
  448. function (response) {
  449. if(response.ok === false) {
  450. alertService.showError($translate.instant(response.why));
  451. } else {
  452. deleteLocalStorage();
  453. }
  454. if(response.dojoId && response.id) {
  455. goToManageDojoEvent($state, usSpinnerService, response.dojoId, response.id);
  456. } else {
  457. goToManageDojoEvents($state, usSpinnerService, dojoId)
  458. }
  459. },
  460. function(err){
  461. alertService.showError($translate.instant('Error setting up event') + ' ' + err);
  462. goToMyDojos($state, usSpinnerService, dojoId)
  463. }
  464. );
  465. } else {
  466. alertService.showError($translate.instant('Error setting up event'));
  467. goToMyDojos($state, usSpinnerService, dojoId)
  468. }
  469. })
  470. } else {
  471. if ($scope.dojoInfo.verified === 1 && $scope.dojoInfo.stage !== 4) {
  472. cdEventsService.saveEvent(
  473. eventInfo,
  474. function (response) {
  475. if(response.ok === false) {
  476. alertService.showError($translate.instant(response.why));
  477. } else {
  478. deleteLocalStorage();
  479. }
  480. if(response.dojoId && response.id) {
  481. goToManageDojoEvent($state, usSpinnerService, response.dojoId, response.id);
  482. } else {
  483. goToManageDojoEvents($state, usSpinnerService, dojoId)
  484. }
  485. },
  486. function (err){
  487. alertService.showError($translate.instant('Error setting up event') + ' ' + err);
  488. goToMyDojos($state, usSpinnerService, dojoId)
  489. }
  490. );
  491. } else {
  492. alertService.showError($translate.instant('Error setting up event'));
  493. goToMyDojos($state, usSpinnerService, dojoId)
  494. }
  495. }
  496. };
  497.  
  498. function addMap(eventPosition) {
  499. var markerPosition;
  500. if(!$scope.eventInfo.position) {
  501. markerPosition = new google.maps.LatLng(eventPosition.lat, eventPosition.lng);
  502. } else {
  503. markerPosition = new google.maps.LatLng($scope.eventInfo.position.lat, $scope.eventInfo.position.lng);
  504. }
  505.  
  506. $scope.googleMaps = {
  507. mapOptions: {
  508. center: markerPosition,
  509. zoom: 15,
  510. mapTypeId: google.maps.MapTypeId.ROADMAP
  511. },
  512. onTilesLoaded: onTilesLoaded,
  513. addMarker: addMarker
  514. };
  515.  
  516. function onTilesLoaded() {
  517. var map = $scope.googleMaps.map;
  518.  
  519. $scope.googleMaps.marker = new google.maps.Marker({
  520. map: map,
  521. draggable: true,
  522. animation: google.maps.Animation.DROP,
  523. position: markerPosition
  524. });
  525.  
  526. google.maps.event.clearListeners(map, 'tilesloaded');
  527. }
  528.  
  529. function addMarker ($event, $params, eventInfo) {
  530. var map = $scope.googleMaps.map;
  531. $scope.googleMaps.marker.setMap(null);
  532. $scope.googleMaps.marker = new google.maps.Marker({
  533. map: map,
  534. position: $params[0].latLng
  535. });
  536. eventInfo.position = {
  537. lat: $params[0].latLng.lat(),
  538. lng: $params[0].latLng.lng()
  539. };
  540. }
  541. }
  542.  
  543.  
  544. function loadDojo(done) {
  545. cdDojoService.load(dojoId, function(dojo) {
  546.  
  547. if(dojo.place && dojo.place.toponymName){
  548. dojo.place.nameWithHierarchy = dojo.place.toponymName;
  549. delete dojo.place.toponymName;
  550. }
  551. $scope.eventInfo.country = dojo.country;
  552. $scope.eventInfo.dojoCity = dojo.place;
  553. $scope.eventInfo.dojoAddress = dojo.address1;
  554.  
  555. var position = [];
  556. if(dojo.coordinates) {
  557. position = dojo.coordinates.split(',');
  558. }
  559.  
  560. $scope.dojoInfo = dojo;
  561.  
  562. if(position && position.length === 2 && !isNaN(utilsService.filterFloat(position[0])) && !isNaN(utilsService.filterFloat(position[1]))) {
  563. addMap({
  564. lat: parseFloat(position[0]),
  565. lng: parseFloat(position[1])
  566. });
  567. } else if($scope.dojoInfo.geoPoint && $scope.dojoInfo.geoPoint.lat && $scope.dojoInfo.geoPoint.lon) {
  568. //add map using coordinates from geopoint if possible
  569. addMap({
  570. lat: $scope.dojoInfo.geoPoint.lat,
  571. lng: $scope.dojoInfo.geoPoint.lon
  572. })
  573. } else { //add empty map
  574. cdDojoService.loadCountriesLatLongData(function(countries){
  575. var country = countries[dojo.alpha2];
  576. addMap({
  577. lat: country[0],
  578. lng: country[1]
  579. })
  580. }, done)
  581. }
  582.  
  583. done(null, dojo);
  584.  
  585. }, done);
  586. }
  587.  
  588. function loadCurrentUser(done) {
  589. auth.get_loggedin_user(function(user) {
  590. $scope.eventInfo.userId = user.id;
  591. done(null, user);
  592. }, done);
  593. }
  594.  
  595. function validateEventRequest(done) {
  596. cdDojoService.getUsersDojos({userId: currentUser.data.id, dojoId: dojoId}, function (usersDojos) {
  597. if(_.isEmpty(usersDojos)) return done(new Error('No permissions found'));
  598. var ticketingPermissionFound = _.find(usersDojos[0].userPermissions, function (permission) {
  599. return permission.name === 'ticketing-admin';
  600. });
  601. if(!ticketingPermissionFound) return done(new Error('You must have the ticketing admin permission to edit a Dojo event'));
  602. return done();
  603. });
  604. }
  605.  
  606. function loadDojoUsers(done) {
  607. cdDojoService.loadDojoUsers({
  608. dojoId: dojoId,
  609. limit$: 'NULL'
  610. }, function(users) {
  611. $scope.dojoUsers = users;
  612. done(null, users);
  613. }, done);
  614. }
  615.  
  616. function loadUserTypes(done) {
  617. cdUsersService.getInitUserTypes(function(userTypes) {
  618. _.each(userTypes, function (userType) {
  619. userType.title = $translate.instant(userType.title);
  620. });
  621. userTypes.push({title:$translate.instant('Everyone'), name:'all-user-types'});
  622. $scope.eventInfo.userTypes = userTypes;
  623. done(null, userTypes);
  624. }, done);
  625. }
  626.  
  627. function loadEvent(done) {
  628. var eventId = $stateParams.eventId;
  629.  
  630. cdEventsService.getEvent(eventId, function(event) {
  631. console.log(event);
  632. $scope.isEditMode = true;
  633.  
  634. var startTime = _.first(event.dates).startTime || moment.utc().toISOString();
  635. var endTime = _.last(event.dates).endTime || moment.utc().toISOString();
  636.  
  637. var startDateUtcOffset = moment(startTime).utcOffset();
  638. var endDateUtcOffset = moment(endTime).utcOffset();
  639.  
  640. event.startTime = moment(startTime).subtract(startDateUtcOffset, 'minutes').toDate();
  641. event.endTime = moment(endTime).subtract(endDateUtcOffset, 'minutes').toDate();
  642. event.createdAt = new Date(event.createdAt);
  643. event.date = new Date(startTime);
  644. var lastEventOcurrance = _.last(event.dates).startTime || moment.utc().toISOString();
  645. event.toDate = new Date(lastEventOcurrance);
  646.  
  647. var eventDay = moment.utc(_.first(event.dates).startTime, 'YYYY-MM-DD HH:mm:ss').format('dddd');
  648. $scope.weekdayPicker.selection = _.find($scope.weekdayPicker.weekdays, function (dayObject) {
  649. return dayObject.name === $translate.instant(eventDay);
  650. });
  651.  
  652. $scope.eventInfo.fixedStartDateTime = event.startTime;
  653. $scope.eventInfo.fixedEndDateTime = event.endTime;
  654.  
  655. $scope.eventInfo = _.assign($scope.eventInfo, event);
  656. $scope.eventInfo.userType = _.where($scope.eventInfo.userTypes, {name: $scope.eventInfo.userType})[0];
  657. $scope.pastEvent = isEventInPast(_.last(event.dates));
  658.  
  659. //description editor
  660. $scope.editorOptions = {
  661. readOnly: $scope.pastEvent,
  662. language: 'en',
  663. uiColor: '#000000',
  664. height: '200px'
  665. };
  666.  
  667. done(null, event);
  668. }, done);
  669. }
  670.  
  671.  
  672. function loadSessions(done) {
  673. var eventId = $stateParams.eventId;
  674. cdEventsService.searchSessions({eventId: eventId, status: 'active'}, function (sessions) {
  675. $scope.eventInfo.sessions = sessions;
  676. return done();
  677. }, function (err) {
  678. console.error(err);
  679. return done(err);
  680. });
  681. }
  682.  
  683. function loadLocalStorage(done) {
  684. if($localStorage[currentUser.data.id] && $localStorage[currentUser.data.id][dojoId] && $localStorage[currentUser.data.id][dojoId].eventForm) {
  685. if(!_.isEmpty($localStorage[currentUser.data.id][dojoId].eventForm)) {
  686. alertService.showAlert($translate.instant('There are unsaved changes on this page'));
  687.  
  688. var localStorage = $localStorage[currentUser.data.id][dojoId].eventForm;
  689. if(localStorage.name) $scope.eventInfo.name = localStorage.name;
  690. if(localStorage.description) $scope.eventInfo.description = localStorage.description;
  691. if(localStorage.public) $scope.eventInfo.public = localStorage.public;
  692. if(localStorage.prefillAddress) $scope.eventInfo.prefillAddress = localStorage.prefillAddress;
  693. if(localStorage.type) $scope.eventInfo.type = localStorage.type;
  694. if(localStorage.recurringType) $scope.eventInfo.recurringType = localStorage.recurringType;
  695. if(localStorage.weekdaySelection) $scope.weekdayPicker.selection = localStorage.weekdaySelection;
  696. if(localStorage.date) $scope.eventInfo.date = new Date(localStorage.date);
  697. if(localStorage.toDate) $scope.eventInfo.toDate = new Date(localStorage.toDate);
  698. if(localStorage.city) $scope.eventInfo.city = localStorage.city;
  699. if(localStorage.address) $scope.eventInfo.address = localStorage.address;
  700. if(localStorage.sessions) $scope.eventInfo.sessions = localStorage.sessions;
  701. if(localStorage.position) $scope.eventInfo.position = localStorage.position;
  702. }
  703.  
  704. }
  705.  
  706. $scope.$watch('eventInfo.sessions', function (sessions) {
  707. sessions = _.without(sessions, _.findWhere(sessions, {name: null}))
  708. if(!_.isEmpty(sessions)) $scope.updateLocalStorage('sessions', sessions);
  709. }, true);
  710.  
  711. $scope.$watch('eventInfo.position', function (mapLatLng) {
  712. $scope.updateLocalStorage('position', mapLatLng);
  713. });
  714.  
  715. return done();
  716. }
  717.  
  718. function isEventInPast(dateObj) {
  719. var now = moment.utc();
  720. var eventUtcOffset = moment(dateObj.startTime).utcOffset();
  721. var start = moment.utc(dateObj.startTime).subtract(eventUtcOffset, 'minutes');
  722.  
  723. return now.isAfter(start);
  724. }
  725.  
  726. if ($stateParams.eventId) {
  727. if(_.isEmpty(currentUser.data)) return $state.go('error-404-no-headers');
  728.  
  729. return async.series([
  730. validateEventRequest,
  731. loadDojoUsers,
  732. loadUserTypes,
  733. loadEvent,
  734. loadSessions
  735. ], function(err, results) {
  736. if (err) {
  737. $scope.hasAccess = false;
  738. return $state.go('error-404-no-headers');
  739. } else {
  740. var eventPosition = results[3].position;
  741. addMap(eventPosition);
  742. }
  743. });
  744. } else {
  745. cdEventsService.search({dojoId: dojoId, sort$: {createdAt: -1}, limit$: 1}).then(function (events) {
  746. var latestEvent = events[0];
  747. if(latestEvent) $scope.eventInfo.ticketApproval = latestEvent.ticketApproval;
  748. });
  749. }
  750.  
  751. async.parallel([
  752. validateEventRequest,
  753. loadDojo,
  754. loadCurrentUser,
  755. loadDojoUsers,
  756. loadUserTypes,
  757. loadLocalStorage
  758. ], function(err, results) {
  759. if (err) {
  760. $scope.hasAccess = false;
  761. return $state.go('error-404-no-headers');
  762. }
  763. });
  764. }
  765.  
  766. angular.module('cpZenPlatform')
  767. .controller('dojo-event-form-controller', [
  768. '$scope',
  769. '$stateParams',
  770. '$state',
  771. '$sce',
  772. '$localStorage',
  773. '$modal',
  774. 'cdEventsService',
  775. 'cdDojoService',
  776. 'cdUsersService',
  777. 'auth',
  778. '$translate',
  779. 'cdLanguagesService',
  780. 'usSpinnerService',
  781. 'alertService',
  782. 'utilsService',
  783. 'ticketTypes',
  784. 'currentUser',
  785. dojoEventFormCtrl
  786. ]);
  787. })();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement