-
Notifications
You must be signed in to change notification settings - Fork 479
/
index.js
1232 lines (1058 loc) · 45.8 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* global angular */
/**
* Entry point for teacher-dashboard/index.js bundle
*/
import $ from 'jquery';
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { registerReducers, getStore } from '@cdo/apps/redux';
import SectionProjectsList from '@cdo/apps/templates/projects/SectionProjectsList';
import SectionProgress from '@cdo/apps/templates/sectionProgress/SectionProgress';
import SectionAssessments from '@cdo/apps/templates/sectionAssessments/SectionAssessments';
import experiments from '@cdo/apps/util/experiments';
import firehoseClient from '@cdo/apps/lib/util/firehose';
import {
renderSyncOauthSectionControl,
unmountSyncOauthSectionControl,
renderLoginTypeControls,
unmountLoginTypeControls,
renderSectionTable,
renderStatsTable,
renderTextResponsesTable
} from '@cdo/apps/templates/teacherDashboard/sections';
import logToCloud from '@cdo/apps/logToCloud';
import scriptSelection, { loadValidScripts } from '@cdo/apps/redux/scriptSelectionRedux';
import sectionProgress from '@cdo/apps/templates/sectionProgress/sectionProgressRedux';
import sectionData, { setSection } from '@cdo/apps/redux/sectionDataRedux';
import sectionAssessments,
{ asyncLoadAssessments } from '@cdo/apps/templates/sectionAssessments/sectionAssessmentsRedux';
const script = document.querySelector('script[data-teacherdashboard]');
const scriptData = JSON.parse(script.dataset.teacherdashboard);
main(scriptData);
function renderSectionProjects(sectionId) {
const dataUrl = `/dashboardapi/v1/projects/section/${sectionId}`;
const element = document.getElementById('projects-list');
const studioUrlPrefix = scriptData.studiourlprefix;
$.ajax({
method: 'GET',
url: dataUrl,
dataType: 'json'
}).done(projectsData => {
ReactDOM.render(
<SectionProjectsList
projectsData={projectsData}
studioUrlPrefix={studioUrlPrefix}
showProjectThumbnails={true}
/>,
element);
});
}
function renderSectionAssessments(section, validScripts) {
registerReducers({scriptSelection, sectionData, sectionAssessments});
const store = getStore();
store.dispatch(setSection(section));
const scriptId = store.getState().scriptSelection.scriptId;
store.dispatch(asyncLoadAssessments(section.id, scriptId, ()=>{}));
store.dispatch(loadValidScripts(section, validScripts)).then(() => {
ReactDOM.render(
<Provider store={store}>
<SectionAssessments />
</Provider>,
document.getElementById('section-assessments-react')
);
});
}
function renderSectionProgress(section, validScripts) {
registerReducers({sectionProgress, scriptSelection, sectionData});
const store = getStore();
store.dispatch(setSection(section));
store.dispatch(loadValidScripts(section, validScripts)).then(() => renderSectionProgressReact(store));
}
function renderSectionProgressReact(store) {
ReactDOM.render(
<Provider store={store}>
<SectionProgress />
</Provider>,
document.getElementById('section-progress-react')
);
}
// Everything below was copied wholesale from index.haml, where we had no linting.
// TODO (bjvanminnen): Fix remaining lint errors and re-enable rules.
/* eslint-disable eqeqeq, no-unused-vars */
function main() {
const studioUrlPrefix = scriptData.studiourlprefix;
var valid_scripts = scriptData.valid_scripts;
var disabled_scripts = scriptData.disabled_scripts;
var i18n = scriptData.i18n;
var error_string_none_selected = i18n.error_string_none_selected;
var error_string_other_section = i18n.error_string_other_section;
// Declare app level module which depends on filters, and services
angular.module('teacherDashboard', [
'ngRoute',
'ngResource',
'ngSanitize',
'ngCsv',
'teacherDashboard.controllers',
'teacherDashboard.services',
'teacherDashboard.directives',
'teacherDashboard.filters'
])
// ROUTES
.config(['$routeProvider', function ($routeProvider) {
if (studioUrlPrefix && window.location.search.indexOf("no_home_redirect") === -1) {
$routeProvider.when('/',
{redirectTo: function () {
window.location = `${studioUrlPrefix}/home`;
}});
} else {
$routeProvider.when('/',
{templateUrl: '/teacher-dashboard/landing'});
}
$routeProvider.when('/plan',
{templateUrl: '/teacher-dashboard/plan'});
$routeProvider.when('/sections',
{templateUrl: '/teacher-dashboard/sections', controller: 'SectionsController'});
$routeProvider.when('/sections/:id',
{templateUrl: '/teacher-dashboard/section', controller: 'SectionDetailController'});
$routeProvider.when('/sections/:id/print_signin_cards',
{templateUrl: '/teacher-dashboard/signin_cards', controller: 'SectionSigninCardsController', tab: 'print_signin_cards'});
$routeProvider.when('/sections/:id/progress',
{templateUrl: '/teacher-dashboard/section', controller: 'SectionProgressController', tab: 'progress'});
$routeProvider.when('/sections/:id/projects',
{templateUrl: '/teacher-dashboard/section', controller: 'SectionProjectsController', tab: 'projects'});
$routeProvider.when('/sections/:id/responses',
{templateUrl: '/teacher-dashboard/section', controller: 'SectionResponsesController', tab: 'responses'});
$routeProvider.when('/sections/:id/assessments',
{templateUrl: '/teacher-dashboard/section', controller: 'SectionAssessmentsController', tab: 'assessments'});
$routeProvider.when('/sections/:id/:tab',
{templateUrl: '/teacher-dashboard/section', controller: 'SectionDetailController'});
$routeProvider.when('/sections/:sectionid/student/:studentid',
{templateUrl: '/teacher-dashboard/student', controller: 'StudentDetailController'});
$routeProvider.when('/sections/:sectionid/student/:studentid/script/',
{templateUrl: '/teacher-dashboard/student', controller: 'StudentDetailController'});
$routeProvider.when('/sections/:sectionid/student/:studentid/script/:scriptid',
{templateUrl: '/teacher-dashboard/student', controller: 'StudentDetailController'});
// We have legacy /course routes from a time when course was used synonomously with script
$routeProvider.when('/sections/:sectionid/student/:studentid/course/',
{templateUrl: '/teacher-dashboard/student', controller: 'StudentDetailController'});
$routeProvider.when('/sections/:sectionid/student/:studentid/course/:scriptid',
{templateUrl: '/teacher-dashboard/student', controller: 'StudentDetailController'});
$routeProvider.otherwise({redirectTo: '/'});
}]);
// DIRECTIVES
var directives = angular.module('teacherDashboard.directives', [])
.value('version', '0.1');
directives.directive('teacherNav', ['$location', '$routeParams', function ($location, $routeParams) {
return {
templateUrl: 'teacher-dashboard/nav',
controller: function ($scope) {
var selectedSection = $scope.selectedSection = $scope.section || null;
$scope.sectionNavigate = function (section) {
if (section && section.id) {
$location.path('/sections/' + section.id);
} else {
$location.path('/sections');
}
};
}
};
}]);
// FILTERS
var filters = angular.module('teacherDashboard.filters', [])
.value('version', '0.1');
filters.filter('htmlSafe', function ($sce) {
return function (val) {
return $sce.trustAsHtml(val);
};
});
// SERVICES
var services = angular.module('teacherDashboard.services', [])
.value('version', '0.1');
// Section service. see sites.v3/code.org/routes/v2_section_routes.rb
services.factory('sectionsService', ['$resource',
function ($resource) {
return $resource('/v2/sections/:id', {}, {
// default methods: see https://code.angularjs.org/1.2.21/docs/api/ngResource/service/$resource
// 'get': {method:'GET'},
// 'save': {method:'POST'},
// 'query': {method:'GET', isArray:true},
// 'remove': {method:'DELETE'},
// 'delete': {method:'DELETE'}
update: {method:'POST', url: 'v2/sections/:id/update'},
allStudents: {method:'GET', url:'v2/sections/:id/students', isArray: true},
addStudents: {method:'POST', url:'/v2/sections/:id/students', isArray: true},
moveStudents: {method:'POST', url:'/dashboardapi/sections/transfers'},
removeStudent: {method:'DELETE', url:'/v2/sections/:id/students/:studentId'},
progress: {method:'GET', url:'/dashboardapi/section_progress/:id'},
studentProgress: {method:'GET', url:'/dashboardapi/student_progress/:id/:studentId'},
responses: {method:'GET', url:'/dashboardapi/section_text_responses/:id', isArray: true},
assessments: {method:'GET', url:'/dashboardapi/section_assessments/:id', isArray: true},
surveys: {method:'GET', url:'/dashboardapi/section_surveys/:id', isArray: true},
});
}]).config(['$httpProvider', function ($httpProvider) {
// X-Requested-With header required for CSRF requests protected by Rack::Protection::JsonCsrf included by Sinatra.
// Angular originally set this, but removed it in a breaking change in v1.4 because it is "rarely used in practice":
// https://github.com/angular/angular.js/commit/3a75b1124d062f64093a90b26630938558909e8d
$httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
$httpProvider.defaults.cache = true;
}]);
services.factory('studentsService', ['$resource',
function ($resource) {
return $resource('/v2/students/:id', {}, {
// default methods: see https://code.angularjs.org/1.2.21/docs/api/ngResource/service/$resource
// 'get': {method:'GET'},
// 'save': {method:'POST'},
// 'query': {method:'GET', isArray:true},
// 'remove': {method:'DELETE'},
// 'delete': {method:'DELETE'}
update: {method:'POST', url: 'v2/students/:id/update'},
});
}]);
// For large sections, we're having requests time out before we hear back from
// the server. Instead, lets ask for progress for only N students at a time,
// and populate our table once we have all data. This is a quick and dirty approach
// that may not be the best way to accomplish this in angular, but we expect it
// to be replaced within the next couple of sprints as we move this to React.
services.factory('paginatedSectionProgressService', ['$http', '$q',
function ($http, $q) {
function reinflateDate(data, sectionId) {
// We try to minimize how much data we send back to the client, as this can
// grow large with big sections. This means some additional processing to
// get the data back in a form that we'd like
return {
...data,
students: data.students.map(student => ({
...student,
levels: student.levels.map(([className, title, url]) => ({
class: className,
title,
url: studioUrlPrefix + url + `?section_id=${sectionId}&user_id=${student.id}`
}))
}))
};
}
return {
get: (id, script_id=undefined) => {
const deferred = $q.defer();
let data;
let page = 1;
let pageSize = 50;
const getNextPage = () => {
let queryParams = `page=${page}&per=${pageSize}`;
if (script_id) {
queryParams += `&script_id=${script_id}`;
}
return $http.get(`/dashboardapi/section_progress/${id}?${queryParams}`)
.then(pageSuccess, pageFailure);
};
const pageSuccess = result => {
if (!data) {
data = result.data;
} else {
// append student data
data.students.push(...result.data.students);
}
// resolve once we've received our last page
if (result.data.students.length < pageSize) {
deferred.resolve(reinflateDate(data, id));
} else {
page++;
getNextPage();
}
};
const pageFailure = err => {
deferred.reject(err);
};
// Query the server for the next page, any time we get a full page
// worth of results, assume there are more and ask for the next page.
// Once we get a non-full page, resolve our promise with the concatenated
// data
getNextPage();
// return our promise
return deferred.promise;
}
};
}
]);
// CONTROLLERS
var app = angular.module('teacherDashboard.controllers', []);
app.controller('SectionsController', ['$scope', '$window', 'sectionsService',
function ($scope, $window, sectionsService) {
firehoseClient.putRecord(
{
study: 'teacher-dashboard-tabbing',
event: 'SectionsController'
}
);
// The sections page has been removed, so redirect to the teacher homepage
// which now contains section controls.
// TODO: Tear out this whole controller when we're sure nothing links to
// the sections page anymore.
logToCloud.addPageAction(logToCloud.PageAction.PegasusSectionsRedirect, {});
window.location = scriptData.studiourlprefix + '/home';
}]);
app.controller('StudentDetailController', ['$scope', '$routeParams', 'sectionsService',
function ($scope, $routeParams, sectionsService) {
firehoseClient.putRecord(
{
study: 'teacher-dashboard-tabbing',
event: 'StudentDetailController'
}
);
$scope.section = sectionsService.get({id: $routeParams.sectionid});
$scope.script_id = parseInt($routeParams.scriptid);
$scope.script_list = valid_scripts;
$scope.progress = sectionsService.studentProgress({id: $routeParams.sectionid, studentId: $routeParams.studentid});
$scope.changeProgress = function () {
$scope.progress = sectionsService.studentProgress({id: $routeParams.sectionid, studentId: $routeParams.studentid, script_id: $scope.script_id});
};
}]);
app.controller('SectionDetailController', ['$scope', '$routeParams', '$window', '$q', '$location', 'sectionsService', 'studentsService',
function ($scope, $routeParams, $window, $q, $location, sectionsService, studentsService) {
firehoseClient.putRecord(
{
study: 'teacher-dashboard-tabbing',
event: 'SectionDetailController'
}
);
$scope.section = sectionsService.get({id: $routeParams.id});
$scope.sections = sectionsService.query();
// error handling
$scope.genericError = function (result) {
$window.alert("An unexpected error occurred, please try again. If this keeps happening, try reloading the page.");
};
$scope.section.$promise.catch(function (result) {
if (result.status == 403 || result.status == 404) {
$window.alert("You are not the owner of this section or this section doesn’t exist.");
} else {
$scope.genericError(result);
}
});
$scope.sections.$promise.catch($scope.genericError);
$scope.tab = $routeParams.tab;
$scope.section.$promise.then(
function ( section ) {
if (!$scope.tab) {
if ($scope.section.students.length > 0) {
$location.path('/sections/' + $routeParams.id + '/progress');
} else {
$location.path('/sections/' + $routeParams.id + '/manage');
}
}
}
);
// the ng-select in the nav compares by reference not by value, so we can't just set
// selectedSection to section, we have to find it in sections.
$scope.sections.$promise.then(
function ( sections ) {
$scope.selectedSection = $.grep(sections, function (section) { return (section.id == $routeParams.id);})[0];
}
);
$scope.teacher_managed_section = function (section) {
return ['email', 'word', 'picture'].includes(section.login_type);
};
$scope.age_list = [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, "21+"];
$scope.gender_list = {f: i18n.dashboard_students_female, m: i18n.dashboard_students_male};
$scope.bulk_import = {editing: false, students: ''};
if ($scope.tab === 'stats') {
$scope.$on('stats-table-rendered', () => {
$scope.section.$promise.then(renderStatsTable);
firehoseClient.putRecord(
{
study: 'teacher-dashboard',
study_group: 'react',
event: 'stats'
}
);
});
}
if ($scope.tab === 'manage') {
$scope.$on('react-sync-oauth-section-rendered', () => {
$scope.section.$promise.then(section =>
renderSyncOauthSectionControl({
sectionId: section.id,
provider: scriptData.provider
})
);
});
$scope.$on('login-type-react-rendered', () => {
$scope.section.$promise.then(section => renderLoginTypeControls(section.id));
});
$scope.$on('student-table-react-rendered', () => {
$scope.section.$promise.then(section => renderSectionTable(section));
firehoseClient.putRecord(
{
study: 'teacher-dashboard',
study_group: 'react',
event: 'manage'
}
);
});
$scope.$on('$destroy', () => {
unmountSyncOauthSectionControl();
unmountLoginTypeControls();
});
}
$scope.edit = function (student) {
student.editing = true;
};
$scope.resetSecrets = function (student) {
var newStudent = studentsService.update({id: student.id}, {secrets: 'reset'});
newStudent.$promise.then(
function (student) {
student.showing_password = true;
}
);
newStudent.$promise.catch($scope.genericError);
$scope.section.students[$scope.section.students.indexOf(student)] = newStudent;
};
$scope.save = function (students) {
if (!$.isArray(students)) {
return $scope.save([students]); // heh
}
var newStudents = [];
var modifiedStudents = [];
$.each(students, function (index, student) {
if (student.editing || student.editing_password) {
if (student.id) {
modifiedStudents.push(student);
} else {
newStudents.push(student);
}
}
});
// create new students
if (newStudents && newStudents.length > 0) {
// remove 'new' students from array
$.each(newStudents, function (index, student) {
$scope.section.students.splice($scope.section.students.indexOf(student), 1);
});
// add the results from the service to the array
sectionsService.addStudents({id: $scope.section.id}, newStudents, function (resultStudents) {
$.each(resultStudents, function (index, student) {
$scope.section.students.unshift(student);
});
}).$promise.then(() => {
// If we started with zero students, we need to rerender login type
// controls so the correct options are available.
// Because 'temporary' students are included in $scope.section.students
// before we reach this save() action, if _all_ students are new
// students then we had zero saved students to begin with.
// TODO: Once everything is React this should become unnecessary.
if (newStudents.length === $scope.section.students.length) {
unmountLoginTypeControls();
renderLoginTypeControls($scope.section.id);
}
}).catch($scope.genericError);
}
// update existing students
$.each(modifiedStudents, function (index, student) {
studentsService.update({id: student.id}, student).$promise.then(
function (result_student) {
result_student.editing = false;
$scope.section.students[$scope.section.students.indexOf(student)] = result_student;
}
).catch($scope.genericError);
});
};
$scope.confirm_delete = function (student) {
student.confirmDelete = true;
};
$scope.del = function (student) { // note -- IE doesn't like it when you name things 'delete'
sectionsService.removeStudent({id: $scope.section.id, studentId: student.id}).$promise.then(
function () {
$scope.section.students.splice($scope.section.students.indexOf(student), 1); // remove from array
}
).then(() => {
// If we removed the last student, rerender login type controls so
// the correct options are available.
// TODO: Once everything is React this should become unnecessary.
if ($scope.section.students.length <= 0) {
unmountLoginTypeControls();
renderLoginTypeControls($scope.section.id);
}
}).catch($scope.genericError);
};
$scope.cancel = function (student) {
if (student.id) {
student.editing = false;
} else {
$scope.section.students.splice($scope.section.students.indexOf(student), 1); // remove from array
}
};
$scope.new_student = function () {
$scope.section.students.unshift({editing: true});
};
$scope.clear_bulk_import = function () {
$scope.bulk_import.editing = false;
$scope.bulk_import.students = '';
};
$scope.add_bulk_import = function () {
var student_names = $scope.bulk_import.students.split("\n");
for (var i = 0; i < student_names.length; i++) {
var student_name = student_names[i];
student_name = student_name.trim();
if (student_name.length > 0) {
$scope.section.students.unshift({editing: true, name: student_name});
}
}
$scope.clear_bulk_import();
};
$scope.editingAny = function (things) {
if (!things) {
return false;
}
for (var i = 0; i < things.length; i++) {
if (things[i].editing) {
return true;
}
}
return false;
};
$scope.editingAll = function (things) {
if (!things) {
return false;
}
for (var i = 0; i < things.length; i++) {
if (!things[i].editing) {
return false;
}
}
return true;
};
$scope.print = function () {
$window.print();
};
}]);
app.controller('SectionSigninCardsController', ['$scope', '$routeParams', '$window', '$q', 'sectionsService',
function ($scope, $routeParams, $window, $q, sectionsService) {
firehoseClient.putRecord(
{
study: 'teacher-dashboard-tabbing',
event: 'SectionSigninCardsController'
}
);
$scope.section = sectionsService.get({id: $routeParams.id});
$scope.sections = sectionsService.query();
// error handling
$scope.genericError = function (result) {
$window.alert("An unexpected error occurred, please try again. If this keeps happening, try reloading the page.");
};
$scope.section.$promise.catch($scope.genericError);
$scope.sections.$promise.catch($scope.genericError);
// the ng-select in the nav compares by reference not by value, so we can't just set
// selectedSection to section, we have to find it in sections.
$scope.sections.$promise.then(
function ( sections ) {
$scope.selectedSection = $.grep(sections, function (section) { return (section.id == $routeParams.id);})[0];
}
);
$scope.print = function () {
const content = document.getElementsByClassName('all_cards')[0].innerHTML;
$window.frames.print_frame.document.body.innerHTML = content;
//Want to apply this only to the printing frame, so add here rather than inline
const cards = $window.frames.print_frame.document.getElementsByClassName('signin_card');
for (let i = 0; i < cards.length; i++) {
cards[i].style.width = '300px';
}
$window.frames.print_frame.window.focus();
$window.frames.print_frame.window.print();
};
}]);
app.controller('SectionProjectsController', ['$scope', '$routeParams', 'sectionsService',
function ($scope, $routeParams, sectionsService) {
firehoseClient.putRecord(
{
study: 'teacher-dashboard-tabbing',
event: 'SectionProjectsController'
}
);
firehoseClient.putRecord(
{
study: 'teacher-dashboard',
study_group: 'react',
event: 'projects'
}
);
$scope.sections = sectionsService.query();
$scope.section = sectionsService.get({id: $routeParams.id});
$scope.tab = 'projects';
// Angular does not offer a reliable way to wait for the template to load,
// so do it using a custom event here. The call to listen for the custom
// event must not be nested inside another deferred call or we might
// miss the event.
$scope.$on('section-projects-rendered', function () {
$scope.section.$promise.then(
function (section) {
renderSectionProjects(section.id);
}
);
});
// the ng-select in the nav compares by reference not by value, so we can't just set
// selectedSection to section, we have to find it in sections.
$scope.sections.$promise.then(
function (sections) {
$scope.selectedSection = $.grep(sections, function (section) {
return (section.id == $routeParams.id);
})[0];
}
);
}]);
app.controller('SectionProgressController', ['$scope', '$routeParams', '$window', '$q', '$timeout', '$interval', 'sectionsService', 'studentsService', 'paginatedSectionProgressService',
function ($scope, $routeParams, $window, $q, $timeout, $interval, sectionsService, studentsService, paginatedSectionProgressService) {
firehoseClient.putRecord(
{
study: 'teacher-dashboard-tabbing',
event: 'SectionProgressController'
}
);
firehoseClient.putRecord(
{
study: 'teacher-dashboard',
study_group: experiments.isEnabled(experiments.TEACHER_EXP_2018) ? 'react' : 'angular',
event: 'progress-summary'
}
);
$scope.tab = 'progress';
$scope.page = {zoom: false};
$scope.react_progress = false;
// We want to make our sections service request whether using react or angular
// because our tabs haml (in nav.haml) depends on the section being loaded. It
// could probably be cleaned up to behave differently without too much difficulty,
// which would make this unnecessary.
$scope.section = sectionsService.get({id: $routeParams.id});
// sections is used by our section dropdown, which at least initially will
// still be in angular
$scope.sections = sectionsService.query();
// error handling
$scope.genericError = function (result) {
$window.alert("An unexpected error occurred, please try again. If this keeps happening, try reloading the page.");
};
$scope.section.$promise.catch($scope.genericError);
$scope.sections.$promise.catch($scope.genericError);
// the ng-select in the nav compares by reference not by value, so we can't just set
// selectedSection to section, we have to find it in sections.
$scope.sections.$promise.then(sections => {
$scope.selectedSection = sections.find(section => section.id.toString() === $routeParams.id);
});
// Logs the request for detailed progress and sets the zoom state
$scope.progressDetailRequest = function () {
$scope.page = {zoom: true};
firehoseClient.putRecord(
{
study: 'teacher-dashboard',
study_group: 'angular',
event: 'progress-detailed'
}
);
};
// Logs the request for summarized progress view and sets the zoom state
$scope.progressSummaryRequest = function () {
$scope.page = {zoom: false};
firehoseClient.putRecord(
{
study: 'teacher-dashboard',
study_group: 'angular',
event: 'progress-summary'
}
);
};
if (experiments.isEnabled(experiments.PROGRESS_TAB)) {
$scope.react_progress = true;
$scope.$on('section-progress-rendered', () => {
$scope.section.$promise.then(script =>
renderSectionProgress(script, valid_scripts)
);
});
return;
}
// The below is not run if our experiments.PROGRESS_TAB experiment is not enabled
const paginatedPromise = paginatedSectionProgressService.get($routeParams.id)
.then(result => {
$scope.progress = result;
})
.catch($scope.genericError);
$scope.progressLoadedFirst = false;
$scope.progressLoaded = false;
$scope.script_list = valid_scripts;
$scope.progress_disabled_scripts = disabled_scripts;
// wait until we have both the students and the student progress
$q.all([paginatedPromise, $scope.section.$promise]).then(function () {
$scope.mergeProgress();
$scope.progressLoadedFirst = true;
$scope.progressLoaded = true;
});
$scope.changeProgress = function (scriptId) {
$scope.progressLoadedFirst = false;
// $scope.progressLoaded = false;
// TODO: The hide/show behavior that uses progressLoaded is
// broken on Chrome 45. I am not sure why, but the hide/show
// behavior that uses progressLoadedFirst works fine, so switching
// to using that is a good rough fix. This changes the behavior so
// that the entire table disappears and reappears instead of just
// the progress bar when using the course dropdown.
paginatedSectionProgressService.get($routeParams.id, scriptId)
.then(result => {
$scope.progress = result;
$scope.mergeProgress();
$scope.progressLoadedFirst = true;
$scope.progressLoaded = true;
})
.catch($scope.genericError);
};
$scope.progressWidth = function () {
return $scope.page.zoom ? Math.max(34 * $scope.progress.script.levels_count, 770) : 770;
};
$scope.scrollToStage = function ($event) {
var doScroll = function () {
var element = $( $event.currentTarget );
var wrapper = $('.table-wrapper');
var LEFT_COLUMN_WIDTH = 200; // scrolling the entire table not just this col, so we have to know about the left col width
var LEFT_OFFSET = 20; // a little offset so we can see the previous stage
wrapper.animate({scrollLeft: (element.position().left - wrapper.position().left + wrapper.scrollLeft() - LEFT_COLUMN_WIDTH - LEFT_OFFSET)}, 500);
};
if ($scope.page.zoom) {
doScroll();
} else {
// if we weren't already zoomed we need to zoom and then wait for the zoom to finish
$scope.page.zoom = true;
$timeout(doScroll, 500);
}
};
var isInCategory = function (script_list, script_id, categoryName) {
for (var i = 0; i < script_list.length; i++) {
if (script_list[i].id === script_id) {
return categoryName === script_list[i].category;
}
}
return false;
};
// merge the data returned by progress api into the data returned by the section students api
$scope.mergeProgress = function () {
$scope.script_id = $scope.progress.script.id;
$scope.progress_disabled = $scope.progress_disabled_scripts.indexOf($scope.script_id) !== -1;
var hocCategoryName = i18n.hoc_category_name;
$scope.is_hoc_course = isInCategory($scope.script_list, $scope.script_id, hocCategoryName);
// calculate width of each level in the progress bar assuming the overall width is 780 px
// Takes the level's position in the script, and returns its level number in its stage
var getLevelNumberInStage = function (overallLevel) {
for (var i = 0; i < $scope.progress.script.stages.length; i++) {
var stage = $scope.progress.script.stages[i];
if (overallLevel < stage.length) {return overallLevel + 1;} else {overallLevel -= stage.length;}
}
return 0;
};
// Put levels on the student object
for (var i = 0; i < $scope.section.students.length; i++) {
var student = $scope.section.students[i];
// default is no progress
student.levels = [];
student.highest_level = -1; // not started yet
student.highest_level_in_stage = 0;
// if we have progress
var progress_student = $.grep($scope.progress.students, function (e) { return e.id == student.id; })[0];
if (progress_student) {
student.levels = progress_student.levels;
// find the last level attempted
for (var l = student.levels.length - 1; l >= 0; l--) {
if (student.levels[l] && student.levels[l].class != 'not_tried') {
var delayedSetHighestLevel = function (student, l) {
student.highest_level = l;
student.highest_level_in_stage = getLevelNumberInStage(l);
};
$timeout(delayedSetHighestLevel.bind(this, student, l), 500); // add a delay so we get animation
break;
}
}
}
}
};
}]);
app.controller('SectionResponsesController', ['$scope', '$routeParams', '$window', '$q', '$timeout', '$interval', '$sanitize', 'sectionsService', 'studentsService',
function ($scope, $routeParams, $window, $q, $timeout, $interval, $sanitize, sectionsService, studentsService) {
firehoseClient.putRecord(
{
study: 'teacher-dashboard-tabbing',
event: 'SectionResponsesController'
}
);
firehoseClient.putRecord(
{
study: 'teacher-dashboard',
study_group: experiments.isEnabled(experiments.TEACHER_EXP_2018) ? 'react' : 'angular',
event: 'text-responses'
}
);
$scope.section = sectionsService.get({id: $routeParams.id});
$scope.sections = sectionsService.query();
$scope.tab = 'responses';
if (experiments.isEnabled(experiments.TEXT_RESPONSES_TAB)) {
$scope.react_text_responses = true;
$scope.$on('text-responses-table-rendered', () => {
$scope.section.$promise.then(section => renderTextResponsesTable(section, valid_scripts));
});
return;
}
$scope.responses = sectionsService.responses({id: $routeParams.id});
// error handling
$scope.genericError = function (result) {
$window.alert("An unexpected error occurred, please try again. If this keeps happening, try reloading the page.");
};
$scope.section.$promise.catch($scope.genericError);
$scope.sections.$promise.catch($scope.genericError);
$scope.responses.$promise.catch($scope.genericError);
// fill in the course dropdown with the section's default course
$scope.section.$promise.then(
function (section) {
// TODO:(bjvanminnen) - also handle case where we have a course, but not
// a script assigned, likely by figuring out the first script in that course
if (section.script) {
$scope.script_id = section.script.id;
}
}
);
// the ng-select in the nav compares by reference not by value, so we can't just set
// selectedSection to section, we have to find it in sections.
$scope.sections.$promise.then(
function ( sections ) {
$scope.selectedSection = $.grep(sections, function (section) { return (section.id == $routeParams.id);})[0];
}
);
$scope.responsesLoaded = false;
$scope.stages = [];
$scope.script_list = valid_scripts;
// wait until we have both the students and the student progress
$q.all([$scope.section.$promise, $scope.responses.$promise]).then(function () {
$scope.responsesLoaded = true;
$scope.findStages();
});
$scope.changeScript = function (scriptId) {
$scope.responsesLoaded = false;
$scope.stages = [];
$scope.responses = sectionsService.responses({id: $routeParams.id, script_id: scriptId});
$scope.responses.$promise.then(function () {
$scope.responsesLoaded = true;
$scope.findStages();
});
};
$scope.findStages = function () {
$scope.stages = $.map($scope.responses, function (row) {
return row.stage;
}).filter(function (item, i, array) { // uniquify
return array.indexOf(item) == i;
});
};
}]);
app.controller('SectionAssessmentsController', ['$scope', '$routeParams', '$window', '$q', '$timeout', '$interval', '$sanitize', 'sectionsService', 'studentsService',
function ($scope, $routeParams, $window, $q, $timeout, $interval, $sanitize, sectionsService, studentsService) {
firehoseClient.putRecord(
{
study: 'teacher-dashboard-tabbing',
event: 'SectionAssessmentsController'
}
);
firehoseClient.putRecord(
{
study: 'teacher-dashboard',
study_group: experiments.isEnabled(experiments.TEACHER_EXP_2018) ? 'react' : 'angular',
event: 'assessments'
}
);
// Some strings.
var submission_list = {
submitted: i18n.dashboard_submission_submitted,
in_progress: i18n.dashboard_submission_in_progress,
};