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