]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/eg2/src/app/staff/admin/server/org-unit.component.ts
Merge branch 'master' of git.evergreen-ils.org:Evergreen
[Evergreen.git] / Open-ILS / src / eg2 / src / app / staff / admin / server / org-unit.component.ts
1 import {Component, Input, ViewChild, OnInit} from '@angular/core';
2 import {Tree, TreeNode} from '@eg/share/tree/tree';
3 import {IdlService, IdlObject} from '@eg/core/idl.service';
4 import {NgbTabset, NgbTabChangeEvent} from '@ng-bootstrap/ng-bootstrap';
5 import {OrgService} from '@eg/core/org.service';
6 import {AuthService} from '@eg/core/auth.service';
7 import {PcrudService} from '@eg/core/pcrud.service';
8 import {ToastService} from '@eg/share/toast/toast.service';
9 import {StringComponent} from '@eg/share/string/string.component';
10 import {StringService} from '@eg/share/string/string.service';
11 import {ConfirmDialogComponent} from '@eg/share/dialog/confirm.component';
12 import {FmRecordEditorComponent} from '@eg/share/fm-editor/fm-editor.component';
13 import {ComboboxEntry} from '@eg/share/combobox/combobox.component';
14
15 @Component({
16     templateUrl: './org-unit.component.html'
17 })
18 export class OrgUnitComponent implements OnInit {
19
20     tree: Tree;
21     selected: TreeNode;
22     @ViewChild('editString', { static: true }) editString: StringComponent;
23     @ViewChild('errorString', { static: true }) errorString: StringComponent;
24     @ViewChild('delConfirm', { static: true }) delConfirm: ConfirmDialogComponent;
25
26     constructor(
27         private idl: IdlService,
28         private org: OrgService,
29         private auth: AuthService,
30         private pcrud: PcrudService,
31         private strings: StringService,
32         private toast: ToastService
33     ) {}
34
35
36     ngOnInit() {
37         this.loadAouTree(this.org.root().id());
38     }
39
40     tabChanged(evt: NgbTabChangeEvent) {
41         const tab = evt.nextId;
42         // stubbing out in case we need it.
43     }
44
45     orgSaved(orgId: number | IdlObject) {
46         let id;
47
48         if (orgId) { // new org created, focus it.
49             id = typeof orgId === 'object' ? orgId.id() : orgId;
50         } else if (this.currentOrg()) {
51             id = this.currentOrg().id();
52         }
53
54         this.loadAouTree(id).then(_ => this.postUpdate(this.editString));
55     }
56
57     orgDeleted() {
58         this.loadAouTree();
59     }
60
61     loadAouTree(selectNodeId?: number): Promise<any> {
62
63         const flesh = ['children', 'ou_type', 'hours_of_operation'];
64
65         return this.pcrud.search('aou', {parent_ou : null},
66             {flesh : -1, flesh_fields : {aou : flesh}}, {authoritative: true}
67
68         ).toPromise().then(tree => {
69             this.ingestAouTree(tree);
70             if (!selectNodeId) { selectNodeId = this.org.root().id(); }
71
72             const node = this.tree.findNode(selectNodeId);
73             this.selected = node;
74             this.tree.selectNode(node);
75         });
76     }
77
78     // Translate the org unt type tree into a structure EgTree can use.
79     ingestAouTree(aouTree) {
80
81         const handleNode = (orgNode: IdlObject): TreeNode => {
82             if (!orgNode) { return; }
83
84             if (!orgNode.hours_of_operation()) {
85                 this.generateHours(orgNode);
86             }
87
88             const treeNode = new TreeNode({
89                 id: orgNode.id(),
90                 label: orgNode.name(),
91                 callerData: {orgUnit: orgNode}
92             });
93
94             // Apply the compiled label asynchronously
95             this.strings.interpolate(
96                 'admin.server.org_unit.treenode', {org: orgNode}
97             ).then(label => treeNode.label = label);
98
99             orgNode.children().forEach(childNode =>
100                 treeNode.children.push(handleNode(childNode))
101             );
102
103             return treeNode;
104         };
105
106         const rootNode = handleNode(aouTree);
107         this.tree = new Tree(rootNode);
108     }
109
110     nodeClicked($event: any) {
111         this.selected = $event;
112     }
113
114     generateHours(org: IdlObject) {
115         const hours = this.idl.create('aouhoo');
116         hours.id(org.id());
117         hours.isnew(true);
118
119         [0, 1, 2, 3, 4, 5, 6].forEach(dow => {
120             this.hours(dow, 'open', '09:00:00', hours);
121             this.hours(dow, 'close', '17:00:00', hours);
122         });
123
124         org.hours_of_operation(hours);
125     }
126
127     // if a 'value' is passed, it will be applied to the optional
128     // hours-of-operation object, otherwise the hours on the currently
129     // selected org unit.
130     hours(dow: number, which: 'open' | 'close', value?: string, hoo?: IdlObject): string {
131         if (!hoo && !this.selected) { return null; }
132
133         const hours = hoo || this.selected.callerData.orgUnit.hours_of_operation();
134
135         if (value) {
136             hours[`dow_${dow}_${which}`](value);
137             hours.ischanged(true);
138         }
139
140         return hours[`dow_${dow}_${which}`]();
141     }
142
143     isClosed(dow: number): boolean {
144         return (
145             this.hours(dow, 'open') === '00:00:00' &&
146             this.hours(dow, 'close') === '00:00:00'
147         );
148     }
149
150     closedOn(dow: number) {
151         this.hours(dow, 'open', '00:00:00');
152         this.hours(dow, 'close', '00:00:00');
153     }
154
155     saveHours() {
156         const org = this.currentOrg();
157         const hours = org.hours_of_operation();
158         this.pcrud.autoApply(hours).subscribe(
159             result => {
160                 console.debug('Hours saved ', result);
161                 this.editString.current()
162                     .then(msg => this.toast.success(msg));
163             },
164             error => {
165                 this.errorString.current()
166                     .then(msg => this.toast.danger(msg));
167             },
168             () => this.loadAouTree(this.selected.id)
169         );
170     }
171
172     deleteHours() {
173         const hours = this.currentOrg().hours_of_operation();
174         const promise = hours.isnew() ? Promise.resolve() :
175             this.pcrud.remove(hours).toPromise();
176
177         promise.then(_ => this.generateHours(this.currentOrg()));
178     }
179
180     currentOrg(): IdlObject {
181         return this.selected ? this.selected.callerData.orgUnit : null;
182     }
183
184     orgHasChildren(): boolean {
185         const org = this.currentOrg();
186         return (org && org.children().length > 0);
187     }
188
189     postUpdate(message: StringComponent) {
190         // Modifying org unit types means refetching the org unit
191         // data normally fetched on page load, since it includes
192         // org unit type data.
193         this.org.fetchOrgs().then(() =>
194             message.current().then(str => this.toast.success(str)));
195     }
196
197     remove() {
198         this.delConfirm.open().subscribe(confirmed => {
199             if (!confirmed) { return; }
200
201             const org = this.selected.callerData.orgUnit;
202
203             this.pcrud.remove(org).subscribe(
204                 ok2 => {},
205                 err => {
206                     this.errorString.current()
207                       .then(str => this.toast.danger(str));
208                 },
209                 ()  => {
210                     // Avoid updating until we know the entire
211                     // pcrud action/transaction completed.
212                     // After removal, select the parent org if available
213                     // otherwise the root org.
214                     const orgId = org.parent_ou() ?
215                         org.parent_ou() : this.org.root().id();
216                     this.loadAouTree(orgId).then(_ =>
217                         this.postUpdate(this.editString));
218                 }
219             );
220         });
221     }
222
223     orgTypeOptions(): ComboboxEntry[] {
224         let ouType = this.currentOrg().ou_type();
225
226         if (typeof ouType === 'number') {
227             // May not be fleshed for new org units
228             ouType = this.org.typeMap()[ouType];
229         }
230         const curDepth = ouType.depth();
231
232         return this.org.typeList()
233             .filter(type_ => type_.depth() === curDepth)
234             .map(type_ => ({id: type_.id(), label: type_.name()}));
235     }
236
237     orgChildTypes(): IdlObject[] {
238         let ouType = this.currentOrg().ou_type();
239
240         if (typeof ouType === 'number') {
241             // May not be fleshed for new org units
242             ouType = this.org.typeMap()[ouType];
243         }
244
245         const depth = ouType.depth();
246         return this.org.typeList()
247             .filter(type_ => type_.depth() === depth + 1);
248     }
249
250     addChild() {
251         const parentTreeNode = this.selected;
252         const parentOrg = this.currentOrg();
253         const newType = this.orgChildTypes()[0];
254
255         const org = this.idl.create('aou');
256         org.isnew(true);
257         org.parent_ou(parentOrg.id());
258         org.ou_type(newType.id());
259         org.children([]);
260
261         // Create a dummy, detached org node to keep the UI happy.
262         this.selected = new TreeNode({
263             id: org.id(),
264             label: org.name(),
265             callerData: {orgUnit: org}
266         });
267     }
268
269     addressChanged(thing: any) {
270         // Reload to pick up org unit address changes.
271         this.orgSaved(this.currentOrg().id());
272     }
273 }
274