1 import {Injectable, EventEmitter, TemplateRef} from '@angular/core';
2 import {StoreService} from '@eg/core/store.service';
3 import {LocaleService} from '@eg/core/locale.service';
4 import {AuthService} from '@eg/core/auth.service';
6 declare var js2JSON: (jsThing: any) => string; // eslint-disable-line no-var
7 declare var OpenSRF; // eslint-disable-line no-var
9 const PRINT_TEMPLATE_PATH = '/print_template';
11 export interface PrintRequest {
12 template?: TemplateRef<any>;
13 templateName?: string;
14 templateOwner?: number; // org unit ID, follows ancestors
15 templateId?: number; // useful for testing templates
19 contentType?: string; // defaults to text/html
23 export interface PrintTemplateResponse {
29 export class PrintService {
31 onPrintRequest$: EventEmitter<PrintRequest>;
33 // Emitted after a print request has been delivered to Hatch or
34 // window.print() has completed. Note window.print() returning
35 // is not necessarily an indication the job has completed.
36 printJobQueued$: EventEmitter<PrintRequest>;
39 private locale: LocaleService,
40 private auth: AuthService,
41 private store: StoreService
43 this.onPrintRequest$ = new EventEmitter<PrintRequest>();
44 this.printJobQueued$ = new EventEmitter<PrintRequest>();
47 print(printReq: PrintRequest) {
48 this.onPrintRequest$.emit(printReq);
52 const prev = this.store.getLocalItem('eg.print.last_printed');
55 const req: PrintRequest = {
57 printContext: prev.context || 'default',
58 contentType: prev.content_type || 'text/html',
59 showDialog: Boolean(prev.show_dialog)
66 compileRemoteTemplate(printReq: PrintRequest): Promise<PrintTemplateResponse> {
68 const formData: FormData = new FormData();
70 formData.append('ses', this.auth.token());
71 if (printReq.templateName) {
72 formData.append('template_name', printReq.templateName);
74 if (printReq.templateId) {
75 formData.append('template_id', '' + printReq.templateId);
77 if (printReq.templateOwner) {
78 formData.append('template_owner', '' + printReq.templateOwner);
80 formData.append('template_data', js2JSON(printReq.contextData));
81 formData.append('template_locale', this.locale.currentLocaleCode());
83 // Sometimes we want to know the time zone of the browser/user,
84 // regardless of any org unit settings.
86 formData.append('client_timezone', OpenSRF.tz);
89 /* eslint-disable no-magic-numbers */
90 return new Promise((resolve, reject) => {
91 const xhttp = new XMLHttpRequest();
92 xhttp.onreadystatechange = function() {
93 if (this.readyState === 4) {
94 if (this.status === 200) {
96 content: xhttp.responseText,
97 contentType: this.getResponseHeader('content-type')
99 } else if (this.status === 404) {
100 console.error('No active template found: ', printReq);
101 reject({notFound: true});
106 xhttp.open('POST', PRINT_TEMPLATE_PATH, true);
107 xhttp.send(formData);
109 /* eslint-enable no-magic-numbers */