d9971b00196cd16a37bfac0f36fdf8ce1341de57
[evergreen-equinox.git] / Open-ILS / src / eg2 / src / app / staff / circ / patron / checkout.component.ts
1 import {Component, OnInit, AfterViewInit, Input, ViewChild} from '@angular/core';
2 import {Router, ActivatedRoute, ParamMap} from '@angular/router';
3 import {Subscription, Observable, empty, of, from} from 'rxjs';
4 import {tap, switchMap} from 'rxjs/operators';
5 import {NgbNav, NgbNavChangeEvent} from '@ng-bootstrap/ng-bootstrap';
6 import {IdlObject} from '@eg/core/idl.service';
7 import {OrgService} from '@eg/core/org.service';
8 import {PcrudService} from '@eg/core/pcrud.service';
9 import {NetService} from '@eg/core/net.service';
10 import {PatronService} from '@eg/staff/share/patron/patron.service';
11 import {PatronContextService, CircGridEntry} from './patron.service';
12 import {CheckoutParams, CheckoutResult, CircService
13     } from '@eg/staff/share/circ/circ.service';
14 import {PromptDialogComponent} from '@eg/share/dialog/prompt.component';
15 import {GridDataSource, GridColumn, GridCellTextGenerator} from '@eg/share/grid/grid';
16 import {GridComponent} from '@eg/share/grid/grid.component';
17 import {Pager} from '@eg/share/util/pager';
18 import {StoreService} from '@eg/core/store.service';
19 import {ServerStoreService} from '@eg/core/server-store.service';
20 import {AudioService} from '@eg/share/util/audio.service';
21 import {CopyAlertsDialogComponent
22     } from '@eg/staff/share/holdings/copy-alerts-dialog.component';
23 import {BarcodeSelectComponent
24     } from '@eg/staff/share/barcodes/barcode-select.component';
25 import {ToastService} from '@eg/share/toast/toast.service';
26 import {StringComponent} from '@eg/share/string/string.component';
27 import {AuthService} from '@eg/core/auth.service';
28 import {PrintService} from '@eg/share/print/print.service';
29
30 const SESSION_DUE_DATE = 'eg.circ.checkout.is_until_logout';
31
32 @Component({
33   templateUrl: 'checkout.component.html',
34   selector: 'eg-patron-checkout'
35 })
36 export class CheckoutComponent implements OnInit, AfterViewInit {
37     static autoId = 0;
38
39     maxNoncats = 99; // Matches AngJS version
40     checkoutNoncat: IdlObject = null;
41     checkoutBarcode = '';
42     gridDataSource: GridDataSource = new GridDataSource();
43     cellTextGenerator: GridCellTextGenerator;
44     dueDate: string;
45     dueDateOptions: 0 | 1 | 2 = 0; // auto date; specific date; session date
46     printOnComplete = true;
47     strictBarcode = false;
48
49     private copiesInFlight: {[barcode: string]: boolean} = {};
50
51     @ViewChild('nonCatCount')
52         private nonCatCount: PromptDialogComponent;
53     @ViewChild('checkoutsGrid')
54         private checkoutsGrid: GridComponent;
55     @ViewChild('copyAlertsDialog')
56         private copyAlertsDialog: CopyAlertsDialogComponent;
57     @ViewChild('barcodeSelect')
58         private barcodeSelect: BarcodeSelectComponent;
59     @ViewChild('receiptEmailed')
60         private receiptEmailed: StringComponent;
61
62     constructor(
63         private router: Router,
64         private store: StoreService,
65         private serverStore: ServerStoreService,
66         private org: OrgService,
67         private pcrud: PcrudService,
68         private net: NetService,
69         public circ: CircService,
70         public patronService: PatronService,
71         public context: PatronContextService,
72         private toast: ToastService,
73         private auth: AuthService,
74         private printer: PrintService,
75         private audio: AudioService
76     ) {}
77
78     ngOnInit() {
79         this.circ.getNonCatTypes();
80
81         this.gridDataSource.getRows = (pager: Pager, sort: any[]) => {
82             return from(this.context.checkouts);
83         };
84
85         this.cellTextGenerator = {
86             title: row => row.title
87         };
88
89         if (this.store.getSessionItem(SESSION_DUE_DATE)) {
90             this.dueDate = this.store.getSessionItem('eg.circ.checkout.due_date');
91             this.toggleDateOptions(2);
92         }
93
94         this.serverStore.getItem('circ.staff_client.do_not_auto_attempt_print')
95         .then(noPrint => {
96             this.printOnComplete = !(
97                 noPrint &&
98                 noPrint.includes('Checkout')
99             );
100         });
101
102         this.serverStore.getItem('circ.checkout.strict_barcode')
103         .then(strict => this.strictBarcode = strict);
104     }
105
106     ngAfterViewInit() {
107         this.focusInput();
108     }
109
110     focusInput() {
111         const input = document.getElementById('barcode-input');
112         if (input) { input.focus(); }
113     }
114
115     collectParams(): Promise<CheckoutParams> {
116
117         const params: CheckoutParams = {
118             patron_id: this.context.summary.id,
119             _checkbarcode: this.strictBarcode,
120             _worklog: {
121                 user: this.context.summary.patron.family_name(),
122                 patron_id: this.context.summary.id
123             }
124         };
125
126         if (this.checkoutNoncat) {
127
128             return this.noncatPrompt().toPromise().then(count => {
129                 if (!count) { return null; }
130                 params.noncat = true;
131                 params.noncat_count = count;
132                 params.noncat_type = this.checkoutNoncat.id();
133                 return params;
134             });
135
136         } else if (this.checkoutBarcode) {
137
138             if (this.dueDateOptions > 0) { params.due_date = this.dueDate; }
139
140             return this.barcodeSelect.getBarcode('asset', this.checkoutBarcode)
141             .then(selection => {
142                 if (selection) {
143                     params.copy_id = selection.id;
144                     params.copy_barcode = selection.barcode;
145                     return params;
146                 } else {
147                     // User canceled the multi-match selection dialog.
148                     return null;
149                 }
150             });
151         }
152
153         return Promise.resolve(null);
154     }
155
156     checkout(params?: CheckoutParams, override?: boolean): Promise<CheckoutResult> {
157
158         let barcode;
159         const promise = params ? Promise.resolve(params) : this.collectParams();
160
161         return promise.then((collectedParams: CheckoutParams) => {
162             if (!collectedParams) { return null; }
163
164             barcode = collectedParams.copy_barcode || '';
165
166             if (barcode) {
167
168                 if (this.copiesInFlight[barcode]) {
169                     console.debug('Item ' + barcode + ' is already mid-checkout');
170                     return null;
171                 }
172
173                 this.copiesInFlight[barcode] = true;
174             }
175
176             return this.circ.checkout(collectedParams);
177         })
178
179         .then((result: CheckoutResult) => {
180             if (result && result.success) {
181                 this.gridifyResult(result);
182             }
183             delete this.copiesInFlight[barcode];
184             this.resetForm();
185             return result;
186         })
187
188         .finally(() => delete this.copiesInFlight[barcode]);
189     }
190
191     resetForm() {
192         this.checkoutBarcode = '';
193         this.checkoutNoncat = null;
194         this.focusInput();
195     }
196
197     gridifyResult(result: CheckoutResult) {
198         const entry: CircGridEntry = {
199             index: CheckoutComponent.autoId++,
200             copy: result.copy,
201             circ: result.circ,
202             dueDate: null,
203             copyAlertCount: 0,
204             nonCatCount: 0,
205             record: result.record,
206             volume: result.volume,
207             title: result.title,
208             author: result.author,
209             isbn: result.isbn
210         };
211
212         if (result.nonCatCirc) {
213
214             entry.title = this.checkoutNoncat.name();
215             entry.dueDate = result.nonCatCirc.duedate();
216             entry.nonCatCount = result.params.noncat_count;
217
218         } else if (result.circ) {
219             entry.dueDate = result.circ.due_date();
220         }
221
222         if (entry.copy) {
223             // Fire and forget this one
224
225             this.pcrud.search('aca',
226                 {copy : entry.copy.id(), ack_time : null}, {}, {atomic: true}
227             ).subscribe(alerts => entry.copyAlertCount = alerts.length);
228         }
229
230         this.context.checkouts.unshift(entry);
231         this.checkoutsGrid.reload();
232
233         // update summary data
234         this.context.refreshPatron();
235     }
236
237     noncatPrompt(): Observable<number> {
238         return this.nonCatCount.open()
239         .pipe(switchMap(count => {
240
241             if (count === null || count === undefined) {
242                 return empty(); // dialog canceled
243             }
244
245             // Even though the prompt has a type and min/max values,
246             // users can still manually enter bogus values.
247             count = Number(count);
248             if (count > 0 && count < this.maxNoncats) {
249                 return of(count);
250             } else {
251                 // Bogus value.  Try again
252                 return this.noncatPrompt();
253             }
254         }));
255     }
256
257     setDueDate(iso: string) {
258         this.dueDate = iso;
259         this.store.setSessionItem('eg.circ.checkout.due_date', this.dueDate);
260     }
261
262
263     // 0: use server due date
264     // 1: use specific due date once
265     // 2: use specific due date until the end of the session.
266     toggleDateOptions(value: 1 | 2) {
267         if (this.dueDateOptions > 0) {
268
269             if (value === 1) { // 1 or 2 -> 0
270                 this.dueDateOptions = 0;
271                 this.store.removeSessionItem(SESSION_DUE_DATE);
272
273             } else if (this.dueDateOptions === 1) { // 1 -> 2
274
275                 this.dueDateOptions = 2;
276                 this.store.setSessionItem(SESSION_DUE_DATE, true);
277
278             } else { // 2 -> 1
279
280                 this.dueDateOptions = 1;
281                 this.store.removeSessionItem(SESSION_DUE_DATE);
282             }
283
284         } else {
285
286             this.dueDateOptions = value;
287             if (value === 2) {
288                 this.store.setSessionItem(SESSION_DUE_DATE, true);
289             }
290         }
291     }
292
293     selectedCopyIds(rows: CircGridEntry[]): number[] {
294         return rows
295             .filter(row => row.copy)
296             .map(row => Number(row.copy.id()));
297     }
298
299     openItemAlerts(rows: CircGridEntry[], mode: string) {
300         const copyIds = this.selectedCopyIds(rows);
301         if (copyIds.length === 0) { return; }
302
303         this.copyAlertsDialog.copyIds = copyIds;
304         this.copyAlertsDialog.mode = mode;
305         this.copyAlertsDialog.open({size: 'lg'}).subscribe(
306             modified => {
307                 if (modified) {
308                     rows.forEach(row => row.copyAlertCount++);
309                     this.checkoutsGrid.reload();
310                 }
311             }
312         );
313     }
314
315     toggleStrictBarcode(active: boolean) {
316         if (active) {
317             this.serverStore.setItem('circ.checkout.strict_barcode', true);
318         } else {
319             this.serverStore.removeItem('circ.checkout.strict_barcode');
320         }
321     }
322
323     patronHasEmail(): boolean {
324         if (!this.context.summary) { return false; }
325         const patron = this.context.summary.patron;
326         return (
327             patron.email() &&
328             patron.email().match(/.*@.*/) !== null
329         );
330     }
331
332     mayEmailReceipt(): boolean {
333         if (!this.context.summary) { return false; }
334         const patron = this.context.summary.patron;
335         const setting = patron.settings()
336             .filter(s => s.name() === 'circ.send_email_checkout_receipts')[0];
337
338         return (
339             this.patronHasEmail() &&
340             setting &&
341             setting.value() === 'true' // JSON encoded
342         );
343     }
344
345     quickReceipt() {
346         if (this.mayEmailReceipt()) {
347             this.emailReceipt();
348         } else {
349             this.printReceipt();
350         }
351     }
352
353     doneAutoReceipt() {
354         if (this.mayEmailReceipt()) {
355             this.emailReceipt(true);
356         } else if (this.printOnComplete) {
357             this.printReceipt(true);
358         }
359     }
360
361     emailReceipt(redirect?: boolean) {
362         if (this.patronHasEmail() && this.context.checkouts.length > 0) {
363             return this.net.request(
364                 'open-ils.circ',
365                 'open-ils.circ.checkout.batch_notify.session.atomic',
366                 this.auth.token(),
367                 this.context.summary.id,
368                 this.context.checkouts.map(c => c.circ.id())
369             ).subscribe(_ => {
370                 this.toast.success(this.receiptEmailed.text);
371                 if (redirect) { this.doneRedirect(); }
372             });
373         }
374     }
375
376     printReceipt(redirect?: boolean) {
377         if (this.context.checkouts.length === 0) { return; }
378
379         if (redirect) {
380             // Wait for the print job to be queued before redirecting
381             const sub: Subscription =
382                 this.printer.printJobQueued$.subscribe(_ => {
383                 sub.unsubscribe();
384                 this.doneRedirect();
385             });
386         }
387
388         this.printer.print({
389             printContext: 'default',
390             templateName: 'checkout',
391             contextData: {checkouts: this.context.checkouts}
392         });
393     }
394
395     doneRedirect() {
396         this.router.navigate(['/staff/circ/patron/bcsearch']);
397     }
398
399 }
400