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