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