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