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