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