LP1825851 Server managed/processed print templates
[working/Evergreen.git] / Open-ILS / src / eg2 / src / app / staff / sandbox / sandbox.component.ts
1
2 import {timer as observableTimer, Observable, of} from 'rxjs';
3 import {Component, OnInit, ViewChild, Input, TemplateRef} from '@angular/core';
4 import {ProgressDialogComponent} from '@eg/share/dialog/progress.component';
5 import {ToastService} from '@eg/share/toast/toast.service';
6 import {StringService} from '@eg/share/string/string.service';
7 import {map, take} from 'rxjs/operators';
8 import {GridDataSource, GridColumn, GridRowFlairEntry} from '@eg/share/grid/grid';
9 import {IdlService, IdlObject} from '@eg/core/idl.service';
10 import {PcrudService} from '@eg/core/pcrud.service';
11 import {OrgService} from '@eg/core/org.service';
12 import {Pager} from '@eg/share/util/pager';
13 import {DateSelectComponent} from '@eg/share/date-select/date-select.component';
14 import {PrintService} from '@eg/share/print/print.service';
15 import {ComboboxEntry} from '@eg/share/combobox/combobox.component';
16 import {FmRecordEditorComponent} from '@eg/share/fm-editor/fm-editor.component';
17 import {NgbDate} from '@ng-bootstrap/ng-bootstrap';
18 import {FormGroup, FormControl} from '@angular/forms';
19 import {ConfirmDialogComponent} from '@eg/share/dialog/confirm.component';
20 import {FormatService} from '@eg/core/format.service';
21 import {StringComponent} from '@eg/share/string/string.component';
22 import {GridComponent} from '@eg/share/grid/grid.component';
23 import * as Moment from 'moment-timezone';
24 import {SampleDataService} from '@eg/share/util/sample-data.service';
25
26 @Component({
27   templateUrl: 'sandbox.component.html',
28   styles: ['.date-time-input.ng-invalid {border: 5px purple solid;}',
29     '.date-time-input.ng-valid {border: 5px green solid; animation: slide 5s linear 1s infinite alternate;}',
30     '@keyframes slide {0% {margin-left:0px;} 50% {margin-left:200px;}']
31 })
32 export class SandboxComponent implements OnInit {
33
34     @ViewChild('progressDialog')
35     private progressDialog: ProgressDialogComponent;
36
37     @ViewChild('dateSelect')
38     private dateSelector: DateSelectComponent;
39
40     @ViewChild('printTemplate')
41     private printTemplate: TemplateRef<any>;
42
43     @ViewChild('fmRecordEditor')
44     private fmRecordEditor: FmRecordEditorComponent;
45
46     @ViewChild('numConfirmDialog')
47     private numConfirmDialog: ConfirmDialogComponent;
48
49     public numThings = 0;
50
51     @ViewChild('bresvEditor')
52     private bresvEditor: FmRecordEditorComponent;
53
54
55     // @ViewChild('helloStr') private helloStr: StringComponent;
56
57     gridDataSource: GridDataSource = new GridDataSource();
58
59     cbEntries: ComboboxEntry[];
60     // supplier of async combobox data
61     cbAsyncSource: (term: string) => Observable<ComboboxEntry>;
62
63     btSource: GridDataSource = new GridDataSource();
64     acpSource: GridDataSource = new GridDataSource();
65     editSelected: (rows: IdlObject[]) => void;
66     @ViewChild('acpGrid') acpGrid: GridComponent;
67     @ViewChild('acpEditDialog') editDialog: FmRecordEditorComponent;
68     @ViewChild('successString') successString: StringComponent;
69     @ViewChild('updateFailedString') updateFailedString: StringComponent;
70     world = 'world'; // for local template version
71     btGridTestContext: any = {hello : this.world};
72
73     renderLocal = false;
74
75     testDate: any;
76
77     testStr: string;
78     @Input() set testString(str: string) {
79         this.testStr = str;
80     }
81
82     oneBtype: IdlObject;
83
84     name = 'Jane';
85
86     dynamicTitleText: string;
87
88     badOrgForm: FormGroup;
89
90     ranganathan: FormGroup;
91
92     dateObject: Date = new Date();
93
94     simpleCombo: ComboboxEntry;
95     kingdom: ComboboxEntry;
96
97     complimentEvergreen: (rows: IdlObject[]) => void;
98     notOneSelectedRow: (rows: IdlObject[]) => boolean;
99
100     // selector field value on metarecord object
101     aMetarecord: string;
102
103     // cross-tab communications example
104     private sbChannel: any;
105     sbChannelText: string;
106
107     myTimeForm: FormGroup;
108
109     constructor(
110         private idl: IdlService,
111         private org: OrgService,
112         private pcrud: PcrudService,
113         private strings: StringService,
114         private toast: ToastService,
115         private format: FormatService,
116         private printer: PrintService,
117         private samples: SampleDataService
118     ) {
119         // BroadcastChannel is not yet defined in PhantomJS and elsewhere
120         this.sbChannel = (typeof BroadcastChannel === 'undefined') ?
121             {} : new BroadcastChannel('eg.sbChannel');
122         this.sbChannel.onmessage = (e) => this.sbChannelHandler(e);
123     }
124
125     ngOnInit() {
126         this.badOrgForm = new FormGroup({
127             'badOrgSelector': new FormControl(
128                 {'id': 4, 'includeAncestors': false, 'includeDescendants': true}, (c: FormControl) => {
129                     // An Angular custom validator
130                     if (c.value.orgIds && c.value.orgIds.length > 5) {
131                         return { tooMany: 'That\'s too many fancy libraries!' };
132                     } else {
133                         return null;
134                     }
135             } )
136         });
137
138         this.ranganathan = new FormGroup({
139             'law': new FormControl('second', (c: FormControl) => {
140                 // An Angular custom validator
141                 if ('wrong' === c.value.id || c.value.freetext) {
142                     return { notALaw: 'That\'s not a real law of library science!' };
143                     } else {
144                         return null;
145                     }
146             } )
147         });
148
149         this.badOrgForm.get('badOrgSelector').valueChanges.subscribe(bad => {
150             this.toast.danger('The fanciest libraries are: ' + JSON.stringify(bad.orgIds));
151         });
152
153         this.ranganathan.get('law').valueChanges.subscribe(l => {
154             this.toast.success('You chose: ' + l.label);
155         });
156
157         this.kingdom = {id: 'Bacteria', label: 'Bacteria'};
158
159         this.gridDataSource.data = [
160             {name: 'Jane', state: 'AZ'},
161             {name: 'Al', state: 'CA'},
162             {name: 'The Tick', state: 'TX'}
163         ];
164
165         this.pcrud.retrieveAll('cmrcfld', {order_by: {cmrcfld: 'name'}})
166         .subscribe(format => {
167             if (!this.cbEntries) { this.cbEntries = []; }
168             this.cbEntries.push({id: format.id(), label: format.name()});
169         });
170
171         this.cbAsyncSource = term => {
172             return this.pcrud.search(
173                 'cmrcfld',
174                 {name: {'ilike': `%${term}%`}}, // could -or search on label
175                 {order_by: {cmrcfld: 'name'}}
176             ).pipe(map(marcField => {
177                 return {id: marcField.id(), label: marcField.name()};
178             }));
179         };
180
181         this.btSource.getRows = (pager: Pager, sort: any[]) => {
182
183             const orderBy: any = {cbt: 'name'};
184             if (sort.length) {
185                 orderBy.cbt = sort[0].name + ' ' + sort[0].dir;
186             }
187
188             return this.pcrud.retrieveAll('cbt', {
189                 offset: pager.offset,
190                 limit: pager.limit,
191                 order_by: orderBy
192             }).pipe(map(cbt => {
193                 // example of inline fleshing
194                 cbt.owner(this.org.get(cbt.owner()));
195                 cbt.datetime_test = new Date();
196                 this.oneBtype = cbt;
197                 return cbt;
198             }));
199         };
200
201         this.acpSource.getRows = (pager: Pager, sort: any[]) => {
202             const orderBy: any = {acp: 'id'};
203             if (sort.length) {
204                 orderBy.acp = sort[0].name + ' ' + sort[0].dir;
205             }
206
207             // base query to grab everything
208             const base: Object = {};
209             base[this.idl.classes['acp'].pkey] = {'!=' : null};
210             const query: any = new Array();
211             query.push(base);
212
213             // and add any filters
214             Object.keys(this.acpSource.filters).forEach(key => {
215                 Object.keys(this.acpSource.filters[key]).forEach(key2 => {
216                     query.push(this.acpSource.filters[key][key2]);
217                 });
218             });
219             return this.pcrud.search('acp',
220                 query, {
221                 flesh: 1,
222                 flesh_fields: {acp: ['location', 'status']},
223                 offset: pager.offset,
224                 limit: pager.limit,
225                 order_by: orderBy
226             });
227         };
228
229         this.editSelected = (idlThings: IdlObject[]) => {
230
231             // Edit each IDL thing one at a time
232             const editOneThing = (thing: IdlObject) => {
233                 if (!thing) { return; }
234
235                 this.showEditDialog(thing).then(
236                     () => editOneThing(idlThings.shift()));
237             };
238
239             editOneThing(idlThings.shift());
240         };
241         this.acpGrid.onRowActivate.subscribe(
242             (acpRec: IdlObject) => { this.showEditDialog(acpRec); }
243         );
244
245         this.complimentEvergreen = (rows: IdlObject[]) => alert('Evergreen is great!');
246         this.notOneSelectedRow = (rows: IdlObject[]) => (rows.length !== 1);
247
248         this.pcrud.retrieve('bre', 1, {}, {fleshSelectors: true})
249         .subscribe(bib => {
250             // Format service will automatically find the selector
251             // value to display from our fleshed metarecord field.
252             this.aMetarecord = this.format.transform({
253                 value: bib.metarecord(),
254                 idlClass: 'bre',
255                 idlField: 'metarecord'
256             });
257         });
258
259         const b = this.idl.create('bresv');
260         b.cancel_time('2019-03-25T11:07:59-0400');
261         this.bresvEditor.mode = 'create';
262         this.bresvEditor.record = b;
263
264         this.myTimeForm = new FormGroup({
265             'datetime': new FormControl(Moment([]), (c: FormControl) => {
266                 // An Angular custom validator
267                 if (c.value.year() < 2019) {
268                     return { tooLongAgo: 'That\'s before 2019' };
269                     } else {
270                         return null;
271                     }
272             } )
273         });
274     }
275
276     sbChannelHandler = msg => {
277         setTimeout(() => { this.sbChannelText = msg.data.msg; });
278     }
279
280     sendMessage($event) {
281         this.sbChannel.postMessage({msg : $event.target.value});
282     }
283
284     // Example of click handler for row action
285     complimentEvergreen2(rows: IdlObject[]) {
286         alert('I know, right?');
287     }
288
289     openEditor() {
290         this.fmRecordEditor.open({size: 'lg'}).subscribe(
291             pcrudResult => console.debug('Record editor performed action'),
292             err => console.error(err),
293             () => console.debug('Dialog closed')
294         );
295     }
296
297     btGridRowClassCallback(row: any): string {
298         if (row.id() === 1) {
299             return 'text-uppercase font-weight-bold text-danger';
300         }
301     }
302
303     btGridRowFlairCallback(row: any): GridRowFlairEntry {
304         const flair = {icon: null, title: null};
305         if (row.id() === 2) {
306             flair.icon = 'priority_high';
307             flair.title = 'I Am ID 2';
308         } else if (row.id() === 3) {
309             flair.icon = 'not_interested';
310         }
311         return flair;
312     }
313
314     // apply to all 'name' columns regardless of row
315     btGridCellClassCallback(row: any, col: GridColumn): string {
316         if (col.name === 'name') {
317             if (row.id() === 7) {
318                 return 'text-lowercase font-weight-bold text-info';
319             }
320             return 'text-uppercase font-weight-bold text-success';
321         }
322     }
323
324     doPrint() {
325         this.printer.print({
326             template: this.printTemplate,
327             contextData: {world : this.world},
328             printContext: 'default'
329         });
330
331         this.printer.print({
332             text: '<b>hello</b>',
333             printContext: 'default'
334         });
335     }
336
337     printWithDialog() {
338         this.printer.print({
339             template: this.printTemplate,
340             contextData: {world : this.world},
341             printContext: 'default',
342             showDialog: true
343         });
344     }
345
346     changeDate(date) {
347         console.log('HERE WITH ' + date);
348         this.testDate = date;
349     }
350
351     showProgress() {
352         this.progressDialog.open();
353
354         // every 250ms emit x*10 for 0-10
355         observableTimer(0, 250).pipe(
356             map(x => x * 10),
357             take(11)
358         ).subscribe(
359             val => this.progressDialog.update({value: val, max: 100}),
360             err => {},
361             ()  => this.progressDialog.close()
362         );
363     }
364
365     testToast() {
366         this.toast.success('HELLO TOAST TEST');
367         setTimeout(() => this.toast.danger('DANGER TEST AHHH!'), 4000);
368     }
369
370     testStrings() {
371         this.strings.interpolate('staff.sandbox.test', {name : 'janey'})
372             .then(txt => this.toast.success(txt));
373
374         setTimeout(() => {
375             this.strings.interpolate('staff.sandbox.test', {name : 'johnny'})
376                 .then(txt => this.toast.success(txt));
377         }, 4000);
378     }
379
380     confirmNumber(num: number): void {
381       this.numThings = num;
382       console.log(this.numThings);
383       this.numConfirmDialog.open();
384     }
385
386     showEditDialog(idlThing: IdlObject): Promise<any> {
387         this.editDialog.mode = 'update';
388         this.editDialog.recId = idlThing['id']();
389         return new Promise((resolve, reject) => {
390             this.editDialog.open({size: 'lg'}).subscribe(
391                 ok => {
392                     this.successString.current()
393                         .then(str => this.toast.success(str));
394                     this.acpGrid.reloadWithoutPagerReset();
395                     resolve(ok);
396                 },
397                 rejection => {
398                     this.updateFailedString.current()
399                         .then(str => this.toast.danger(str));
400                     reject(rejection);
401                 }
402             );
403         });
404     }
405
406     allFutureDates(date: NgbDate, current: { year: number; month: number; }) {
407         const currentTime = new Date();
408         const today = new NgbDate(currentTime.getFullYear(), currentTime.getMonth() + 1, currentTime.getDate());
409         return date.after(today);
410     }
411
412     sevenDaysAgo() {
413         const d = new Date();
414         d.setDate(d.getDate() - 7);
415         return d;
416     }
417
418     testServerPrint() {
419
420         // Note these values can be IDL objects or plain hashes.
421         const templateData = {
422             patron:  this.samples.listOfThings('au')[0],
423             address: this.samples.listOfThings('aua')[0]
424         };
425
426         // NOTE: eventually this will be baked into the print service.
427         this.printer.print({
428             templateName: 'patron_address',
429             contextData: templateData,
430             printContext: 'default'
431         });
432     }
433 }
434