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