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