/
tasks-content.js
104 lines (94 loc) · 3.28 KB
/
tasks-content.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
(function () {
'use strict';
var inboxControllers = angular.module('inboxControllers');
inboxControllers.controller('TasksContentCtrl',
['$log', '$scope', '$state', '$translate', 'DB', 'Enketo', 'TranslateFrom', 'Snackbar',
function ($log, $scope, $state, $translate, DB, Enketo, TranslateFrom, Snackbar) {
var hasOneFormAndNoFields = function(task) {
return Boolean(
task &&
task.actions &&
task.actions.length === 1 &&
(
!task.fields ||
task.fields.length === 0 ||
!task.fields[0].value ||
task.fields[0].value.length === 0
)
);
};
$scope.performAction = function(action, skipDetails) {
$scope.setCancelTarget(function() {
if (skipDetails) {
$state.go('tasks.detail', { id: null });
} else {
Enketo.unload($scope.form);
$scope.form = null;
$scope.loadingForm = false;
$scope.contentError = false;
$scope.clearCancelTarget();
}
});
$scope.contentError = false;
if (action.type === 'report') {
$scope.loadingForm = true;
$scope.formId = action.form;
Enketo.render($('#task-report'), action.form, action.content)
.then(function(form) {
$scope.form = form;
$scope.loadingForm = false;
})
.then(function() {
return DB().query('medic-client/forms', { include_docs: true, key: action.form });
})
.then(function(res) {
if (res.rows[0]) {
$scope.setTitle(TranslateFrom(res.rows[0].doc.title));
}
})
.catch(function(err) {
$scope.contentError = true;
$scope.loadingForm = false;
$log.error('Error loading form.', err);
});
} else if (action.type === 'contact') {
$state.go('contacts.addChild', action.content);
}
};
$scope.save = function() {
$scope.saving = true;
Enketo.save($scope.formId, $scope.form)
.then(function(doc) {
$log.debug('saved report', doc);
$translate('report.created').then(Snackbar);
$scope.saving = false;
Enketo.unload($scope.form);
$scope.clearSelected();
$scope.clearCancelTarget();
$state.go('tasks.detail', { id: null });
})
.catch(function(err) {
$scope.saving = false;
$log.error('Error submitting form data: ', err);
});
};
$scope.$on('$destroy', function() {
if (!$state.includes('tasks.detail')) {
Enketo.unload($scope.form);
$scope.setTitle();
$scope.clearSelected();
}
});
// Wait for `selected` to be set during tasks generation and load the
// form if we have no other description or instructions in the task.
$scope.$watch('selected', function() {
if (hasOneFormAndNoFields($scope.selected)) {
$scope.performAction($scope.selected.actions[0], true);
}
});
$scope.form = null;
$scope.formId = null;
$scope.setSelected($state.params.id);
}
]);
}());