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