]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/services/print.js
LP1858118 Hatch enabled check repairs
[working/Evergreen.git] / Open-ILS / web / js / ui / default / staff / services / print.js
1 /**
2  * egPrint : manage print templates, process templates, print content
3  *
4  */
5 angular.module('egCoreMod')
6
7 .factory('egPrint',
8        ['$q','$window','$timeout','$http','egHatch','egAuth','egIDL','egOrg','egEnv',
9 function($q , $window , $timeout , $http , egHatch , egAuth , egIDL , egOrg , egEnv) {
10
11     var service = {
12         include_settings : [
13             'circ.staff_client.receipt.alert_text',
14             'circ.staff_client.receipt.event_text',
15             'circ.staff_client.receipt.footer_text',
16             'circ.staff_client.receipt.header_text',
17             'circ.staff_client.receipt.notice_text'
18         ]
19     };
20
21
22     service.template_base_path = 'share/print_templates/t_';
23
24     /*
25      * context  : 'default', 'receipt','label', etc. 
26      * scope    : data loaded into the template environment
27      * template : template name (e.g. 'checkout', 'transit_slip'
28      * content  : content to print.  If 'template' is set, content is
29      *            derived from the template.
30      * content_type : 'text/html', 'text/plain', 'text/csv'
31      * show_dialog  : boolean, if true, print dialog is shown.  This setting
32      *                only affects remote printers, since browser printers
33      *                do not allow such control
34      */
35     service.print = function(args) {
36         if (!args) return $q.when();
37
38         if (args.template) {
39             // fetch the template, then proceed to printing
40
41             return service.getPrintTemplate(args.template)
42             .then(function(content) {
43                 args.content = content;
44                 if (!args.content_type) args.content_type = 'text/html';
45                 service.getPrintTemplateContext(args.template)
46                 .then(function(context) {
47                     args.context = context;
48                     return service.print_content(args);
49                 });
50             });
51
52         } 
53
54         return service.print_content(args);
55     }
56
57     // add commonly used attributes to the print scope
58     service.fleshPrintScope = function(scope) {
59         if (!scope) scope = {};
60         scope.today = new Date().toISOString();
61
62         if (!lf.isOffline) {
63             scope.staff = egIDL.toHash(egAuth.user());
64             scope.current_location = 
65                 egIDL.toHash(egOrg.get(egAuth.user().ws_ou()));
66         }
67
68         return service.fetch_includes(scope);
69     }
70
71     // Retrieve org settings for receipt includes and add them
72     // to the print scope under scope.includes.<name>
73     service.fetch_includes = function(scope) {
74         // org settings for the workstation org are cached
75         // within egOrg.  No need to cache them locally.
76         return egOrg.settings(service.include_settings).then(
77
78             function(settings) {
79                 scope.includes = {};
80                 angular.forEach(settings, function(val, key) {
81                     // strip the settings prefix so you just have
82                     // e.g. scope.includes.alert_text
83                     scope.includes[key.split(/\./).pop()] = val;
84                 });
85             }
86         );
87     }
88
89     service.last_print = {};
90
91     // Template has been fetched (or no template needed) 
92     // Process the template and send the result off to the printer.
93     service.print_content = function(args) {
94         return service.fleshPrintScope(args.scope)
95         .then(function() { return egHatch.usePrinting(); })
96         .then(function(useHatch) {
97             var promise = useHatch ?
98                 service.print_via_hatch(args) :
99                 service.print_via_browser(args);
100
101             return promise['finally'](
102                 function() { service.clear_print_content() });
103         });
104     }
105
106     service.print_via_hatch = function(args) {
107         var promise;
108
109         if (args.content_type == 'text/html') {
110             promise = service.ingest_print_content(
111                 args.content_type, args.content, args.scope
112             ).then(function(html) {
113                 // For good measure, wrap the compiled HTML in container tags.
114                 return "<html><body>" + html + "</body></html>";
115             });
116         } else {
117             // text content requires no compilation for remote printing.
118             promise = $q.when(args.content);
119         }
120
121         return promise.then(function(content) {
122             service.last_print.content = content;
123             service.last_print.context = args.context || 'default';
124             service.last_print.content_type = args.content_type;
125             service.last_print.show_dialog = args.show_dialog;
126
127             egHatch.setLocalItem('eg.print.last_printed', service.last_print);
128
129             return service._remotePrint();
130         });
131     }
132
133     service._remotePrint = function () {
134         return egHatch.remotePrint(
135             service.last_print.context,
136             service.last_print.content_type,
137             service.last_print.content, 
138             service.last_print.show_dialog
139         );
140     }
141
142     service.print_via_browser = function(args) {
143         var type = args.content_type;
144         var content = args.content;
145         var printScope = args.scope;
146
147         if (type == 'text/csv' || type == 'text/plain') {
148             // preserve newlines, spaces, etc.
149             content = '<pre>' + content + '</pre>';
150         }
151
152         // Fetch the print CSS required for in-browser printing.
153         return $http.get(egEnv.basePath + 'css/print.css')
154         .then(function(response) {
155
156             // Add the bare CSS to the content
157             return '<style type="text/css" media="print">' +
158                   response.data +
159                   '</style>' +
160                   content;
161
162         }).then(function(content) {
163
164             // Ingest the content into the page DOM.
165             return service.ingest_print_content(type, content, printScope);
166
167         }).then(function(html) { 
168
169             // Note browser ignores print context
170             service.last_print.content = html;
171             service.last_print.content_type = type;
172             egHatch.setLocalItem('eg.print.last_printed', service.last_print);
173
174             $window.print();
175         });
176     }
177
178     service.reprintLast = function () {
179         var last = egHatch.getLocalItem('eg.print.last_printed');
180         if (!last || !last.content) { return $q.reject(); }
181
182         service.last_print = last;
183
184         return egHatch.usePrinting().then(function(useHatch) {
185
186             if (useHatch) {
187                 return service._remotePrint();
188             } else {
189                 return service.ingest_print_content(
190                     null, null, null, service.last_print.content)
191                 .then(function() { $window.print(); });
192             }
193
194         }).finally(function() { service.clear_print_content(); });
195     }
196
197     // loads an HTML print template by name from the server
198     // If no template is available in local/hatch storage, 
199     // fetch the template as an HTML file from the server.
200     service.getPrintTemplate = function(name) {
201         var deferred = $q.defer();
202
203         egHatch.getItem('eg.print.template.' + name)
204         .then(function(html) {
205
206             if (html) {
207                 // we have a locally stored template
208                 deferred.resolve(html);
209                 return;
210             }
211
212             var path = service.template_base_path + name;
213             console.debug('fetching template ' + path);
214
215             $http.get(path).then(
216                 function(data) { deferred.resolve(data.data) },
217                 function() {
218                     console.error('unable to locate print template: ' + name);
219                     deferred.reject();
220                 }
221             );
222         });
223
224         return deferred.promise;
225     }
226
227     service.storePrintTemplate = function(name, html) {
228         return egHatch.setItem('eg.print.template.' + name, html);
229     }
230
231     service.removePrintTemplate = function(name) {
232         return egHatch.removeItem('eg.print.template.' + name);
233     }
234
235     service.getPrintTemplateContext = function(name) {
236         var deferred = $q.defer();
237
238         egHatch.getItem('eg.print.template_context.' + name)
239         .then(
240             function(context) { deferred.resolve(context); },
241             function()        { deferred.resolve('default'); }
242         );
243
244         return deferred.promise;
245     }
246     service.storePrintTemplateContext = function(name, context) {
247         return egHatch.setItem('eg.print.template_context.' + name, context);
248     }
249     service.removePrintTemplateContext = function(name) {
250         return egHatch.removeItem('eg.print.template_context.' + name);
251     }
252
253     return service;
254 }])
255
256
257 /**
258  * Container for inserting print data into the browser page.
259  * On insert, $window.print() is called to print the data.
260  * The div housing eg-print-container must apply the correct
261  * print media CSS to ensure this content (and not the rest
262  * of the page) is printed.
263  *
264  * NOTE: There should only ever be 1 egPrintContainer instance per page.
265  * egPrintContainer attaches functions to the egPrint service with
266  * closures around the egPrintContainer instance's $scope (including its
267  * DOM element). Having multiple egPrintContainers could result in chaos.
268  */
269
270 .directive('egPrintContainer', ['$compile', function($compile) {
271     return {
272         restrict : 'AE',
273         scope : {}, // isolate our scope
274         link : function(scope, element, attrs) {
275             scope.elm = element;
276         },
277         controller : 
278                    ['$scope','$q','$window','$timeout','egHatch','egPrint','egEnv',
279             function($scope , $q , $window , $timeout , egHatch , egPrint , egEnv) {
280
281                 egPrint.clear_print_content = function() {
282                     $scope.elm.html('');
283                     $compile($scope.elm.contents())($scope.$new(true));
284                 }
285
286                 // Insert the printable content into the DOM.
287                 // For remote printing, this lets us exract the compiled HTML
288                 // from the DOM.
289                 // For local printing, this lets us print directly from the
290                 // DOM with print CSS.
291                 // Returns a promise reolved with the compiled HTML as a string.
292                 //
293                 // If a pre-compiled HTML string is provided, it's inserted
294                 // as-is into the DOM for browser printing without any 
295                 // additional interpolation.  This is useful for reprinting,
296                 // previously compiled content.
297                 egPrint.ingest_print_content = 
298                     function(type, content, printScope, compiledHtml) {
299
300                     if (compiledHtml) {
301                         $scope.elm.html(compiledHtml);
302                         return $q.when(compiledHtml);
303                     }
304                         
305                     $scope.elm.html(content);
306
307                     var sub_scope = $scope.$new(true);
308                     angular.forEach(printScope, function(val, key) {
309                         sub_scope[key] = val;
310                     })
311
312                     var resp = $compile($scope.elm.contents())(sub_scope);
313
314
315                     var deferred = $q.defer();
316                     $timeout(function(){
317                         // give the $digest a chance to complete then resolve
318                         // with the compiled HTML from our print container
319                         deferred.resolve($scope.elm.html());
320                     });
321
322                     return deferred.promise;
323                 }
324             }
325         ]
326     }
327 }])
328