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