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