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