1 import {Injectable, EventEmitter, TemplateRef} from '@angular/core';
2 import {tap} from 'rxjs/operators';
3 import {StoreService} from '@eg/core/store.service';
4 import {LocaleService} from '@eg/core/locale.service';
5 import {AuthService} from '@eg/core/auth.service';
7 declare var js2JSON: (jsThing: any) => string;
10 const PRINT_TEMPLATE_PATH = '/print_template';
12 export interface PrintRequest {
13 template?: TemplateRef<any>;
14 templateName?: string;
15 templateOwner?: number; // org unit ID, follows ancestors
16 templateId?: number; // useful for testing templates
20 contentType?: string; // defaults to text/html
24 export interface PrintTemplateResponse {
30 export class PrintService {
32 onPrintRequest$: EventEmitter<PrintRequest>;
34 // Emitted after a print request has been delivered to Hatch or
35 // window.print() has completed. Note window.print() returning
36 // is not necessarily an indication the job has completed.
37 printJobQueued$: EventEmitter<PrintRequest>;
40 private locale: LocaleService,
41 private auth: AuthService,
42 private store: StoreService
44 this.onPrintRequest$ = new EventEmitter<PrintRequest>();
45 this.printJobQueued$ = new EventEmitter<PrintRequest>();
48 print(printReq: PrintRequest) {
49 this.onPrintRequest$.emit(printReq);
53 const prev = this.store.getLocalItem('eg.print.last_printed');
56 const req: PrintRequest = {
58 printContext: prev.context || 'default',
59 contentType: prev.content_type || 'text/html',
60 showDialog: Boolean(prev.show_dialog)
67 compileRemoteTemplate(printReq: PrintRequest): Promise<PrintTemplateResponse> {
69 const formData: FormData = new FormData();
71 formData.append('ses', this.auth.token());
72 if (printReq.templateName) {
73 formData.append('template_name', printReq.templateName);
75 if (printReq.templateId) {
76 formData.append('template_id', '' + printReq.templateId);
78 if (printReq.templateOwner) {
79 formData.append('template_owner', '' + printReq.templateOwner);
81 formData.append('template_data', js2JSON(printReq.contextData));
82 formData.append('template_locale', this.locale.currentLocaleCode());
84 // Sometimes we want to know the time zone of the browser/user,
85 // regardless of any org unit settings.
87 formData.append('client_timezone', OpenSRF.tz);
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);