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