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