Commit | Line | Data |
---|---|---|
5145a3b5 CW |
1 | (function(angular, $, _) { |
2 | "use strict"; | |
3 | ||
4 | angular.module('crmSearchActions').component('crmSearchBatchRunner', { | |
5 | bindings: { | |
6 | entity: '<', | |
7 | action: '@', | |
8 | ids: '<', | |
9 | params: '<', | |
10 | success: '&', | |
11 | error: '&' | |
12 | }, | |
13 | templateUrl: '~/crmSearchActions/crmSearchBatchRunner.html', | |
14 | controller: function($scope, $timeout, $interval, crmApi4) { | |
33e81cf6 | 15 | var ts = $scope.ts = CRM.ts('org.civicrm.search_kit'), |
5145a3b5 CW |
16 | ctrl = this, |
17 | currentBatch = 0, | |
18 | totalBatches, | |
19 | incrementer; | |
20 | ||
21 | this.progress = 0; | |
22 | ||
23 | // Number of records to process in each batch | |
24 | var BATCH_SIZE = 500, | |
25 | // Extimated number of seconds each batch will take (for auto-incrementing the progress bar) | |
26 | EST_BATCH_TIME = 5; | |
27 | ||
28 | this.$onInit = function() { | |
29 | totalBatches = Math.ceil(ctrl.ids.length / BATCH_SIZE); | |
30 | runBatch(); | |
31 | }; | |
32 | ||
33 | this.$onDestroy = function() { | |
34 | stopIncrementer(); | |
35 | }; | |
36 | ||
37 | function runBatch() { | |
38 | ctrl.first = currentBatch * BATCH_SIZE; | |
39 | ctrl.last = (currentBatch + 1) * BATCH_SIZE; | |
40 | if (ctrl.last > ctrl.ids.length) { | |
41 | ctrl.last = ctrl.ids.length; | |
42 | } | |
43 | var params = _.cloneDeep(ctrl.params); | |
44 | params.where = params.where || []; | |
45 | params.where.push(['id', 'IN', ctrl.ids.slice(ctrl.first, ctrl.last)]); | |
46 | crmApi4(ctrl.entity, ctrl.action, params).then( | |
47 | function(result) { | |
48 | stopIncrementer(); | |
49 | ctrl.progress = Math.floor(100 * ++currentBatch / totalBatches); | |
50 | if (ctrl.last >= ctrl.ids.length) { | |
51 | $timeout(ctrl.success, 500); | |
52 | } else { | |
53 | runBatch(); | |
54 | } | |
55 | }, function(error) { | |
56 | ctrl.error(); | |
57 | }); | |
58 | // Move the bar every second to simulate progress between batches | |
59 | incrementer = $interval(function(i) { | |
60 | var est = Math.floor(100 * (currentBatch + (i / EST_BATCH_TIME)) / totalBatches); | |
61 | ctrl.progress = est > 100 ? 100 : est; | |
62 | }, 1000, EST_BATCH_TIME); | |
63 | } | |
64 | ||
65 | function stopIncrementer() { | |
66 | if (angular.isDefined(incrementer)) { | |
67 | $interval.cancel(incrementer); | |
68 | incrementer = undefined; | |
69 | } | |
70 | } | |
71 | ||
72 | } | |
73 | }); | |
74 | ||
75 | })(angular, CRM.$, CRM._); |