lp1942647 Provide Warning when deleting Term linked to Courses
[evergreen-equinox.git] / Open-ILS / src / eg2 / src / app / staff / share / course.service.ts
1 import {Observable} from 'rxjs';
2 import {tap} from 'rxjs/operators';
3 import {Injectable} from '@angular/core';
4 import {AuthService} from '@eg/core/auth.service';
5 import {EventService} from '@eg/core/event.service';
6 import {IdlObject, IdlService} from '@eg/core/idl.service';
7 import {NetService} from '@eg/core/net.service';
8 import {OrgService} from '@eg/core/org.service';
9 import {PcrudService} from '@eg/core/pcrud.service';
10
11 @Injectable()
12 export class CourseService {
13
14     constructor(
15         private auth: AuthService,
16         private evt: EventService,
17         private idl: IdlService,
18         private net: NetService,
19         private org: OrgService,
20         private pcrud: PcrudService
21     ) {}
22
23     isOptedIn(): Promise<any> {
24         return new Promise((resolve) => {
25             this.org.settings('circ.course_materials_opt_in').then(res => {
26                 resolve(res['circ.course_materials_opt_in']);
27             });
28         });
29     }
30     getCourses(course_ids?: Number[]): Promise<IdlObject[]> {
31         const flesher = {flesh: 2, flesh_fields: {
32             'acmc': ['owning_lib'],
33             'aou': ['ou_type']}};
34         if (!course_ids) {
35             return this.pcrud.retrieveAll('acmc',
36                 flesher, {atomic: true}).toPromise();
37         } else {
38             return this.pcrud.search('acmc', {id: course_ids},
39                 flesher, {atomic: true}).toPromise();
40         }
41     }
42
43     getMaterials(course_ids?: Number[]): Promise<IdlObject[]> {
44         if (!course_ids) {
45             return this.pcrud.retrieveAll('acmcm',
46                 {}, {atomic: true}).toPromise();
47         } else {
48             return this.pcrud.search('acmcm', {course: course_ids},
49                 {}, {atomic: true}).toPromise();
50         }
51     }
52
53     getUsers(course_ids?: Number[]): Observable<IdlObject> {
54         const flesher = {
55             flesh: 1,
56             flesh_fields: {'acmcu': ['usr', 'usr_role']}
57         };
58         if (!course_ids) {
59             return this.pcrud.retrieveAll('acmcu',
60                 flesher);
61         } else {
62             return this.pcrud.search('acmcu', {course: course_ids},
63                 flesher);
64         }
65     }
66
67     getCoursesFromMaterial(copy_id): Promise<any> {
68         const id_list = [];
69         return new Promise((resolve, reject) => {
70
71             return this.pcrud.search('acmcm', {item: copy_id})
72             .subscribe(materials => {
73                 if (materials) {
74                     id_list.push(materials.course());
75                 }
76             }, err => {
77                 console.debug(err);
78                 reject(err);
79             }, () => {
80                 if (id_list.length) {
81                     return this.getCourses(id_list).then(courses => {
82                         resolve(courses);
83                     });
84                 }
85             });
86         });
87     }
88
89     getTermMaps(term_ids) {
90         const flesher = {flesh: 2, flesh_fields: {
91             'acmtcm': ['course']}};
92
93         if (!term_ids) {
94             return this.pcrud.retrieveAll('acmtcm',
95                 flesher);
96         } else {
97             return this.pcrud.search('acmtcm', {term: term_ids},
98                 flesher);
99         }
100     }
101
102     fetchCoursesForRecord(recordId) {
103         const courseIds = new Set<number>();
104         return this.pcrud.search(
105             'acmcm', {record: recordId}, {atomic: false}
106         ).pipe(tap(material => {
107             courseIds.add(material.course());
108         })).toPromise()
109         .then(() => {
110             if (courseIds.size) {
111                 return this.getCourses(Array.from(courseIds));
112             }
113         });
114     }
115
116     // Creating a new acmcm Entry
117     associateMaterials(item, args) {
118         const material = this.idl.create('acmcm');
119         material.item(item.id());
120         if (item.call_number() && item.call_number().record()) {
121             material.record(item.call_number().record());
122         }
123         material.course(args.currentCourse.id());
124         if (args.relationship) { material.relationship(args.relationship); }
125
126         // Apply temporary fields to the item
127         if (args.isModifyingStatus && args.tempStatus) {
128             material.original_status(item.status());
129             item.status(args.tempStatus);
130         }
131         if (args.isModifyingLocation && args.tempLocation) {
132             material.original_location(item.location());
133             item.location(args.tempLocation);
134         }
135         if (args.isModifyingCircMod) {
136             material.original_circ_modifier(item.circ_modifier());
137             item.circ_modifier(args.tempCircMod);
138             if (!args.tempCircMod) { item.circ_modifier(null); }
139         }
140         if (args.isModifyingCallNumber) {
141             material.original_callnumber(item.call_number());
142         }
143         const response = {
144             item: item,
145             material: this.pcrud.create(material).toPromise()
146         };
147
148         return response;
149     }
150
151     associateUsers(patron_id, args) {
152         const new_user = this.idl.create('acmcu');
153         if (args.role) { new_user.usr_role(args.role); }
154         new_user.course(args.currentCourse.id());
155         new_user.usr(patron_id);
156         return this.pcrud.create(new_user).toPromise();
157     }
158
159     disassociateMaterials(courses) {
160         return new Promise((resolve, reject) => {
161             const course_ids = [];
162             const course_library_hash = {};
163             courses.forEach(course => {
164                 course_ids.push(course.id());
165                 course_library_hash[course.id()] = course.owning_lib();
166             });
167             this.pcrud.search('acmcm', {course: course_ids}).subscribe(material => {
168                 material.isdeleted(true);
169                 this.resetItemFields(material, course_library_hash[material.course()]);
170                 this.pcrud.autoApply(material).subscribe(() => {
171                 }, err => {
172                     reject(err);
173                 }, () => {
174                     resolve(material);
175                 });
176             }, err => {
177                 reject(err);
178             }, () => {
179                 resolve(courses);
180             });
181         });
182     }
183
184     disassociateUsers(user) {
185         return new Promise((resolve, reject) => {
186             const user_ids = [];
187             const course_library_hash = {};
188             user.forEach(course => {
189                 user_ids.push(course.id());
190                 course_library_hash[course.id()] = course.owning_lib();
191             });
192             this.pcrud.search('acmcu', {user: user_ids}).subscribe(u => {
193                 u.course(user_ids);
194                 this.pcrud.autoApply(user).subscribe(res => {
195                     console.debug(res);
196                 }, err => {
197                     reject(err);
198                 }, () => {
199                     resolve(user);
200                 });
201             }, err => {
202                 reject(err);
203             }, () => {
204                 resolve(user_ids);
205             });
206         });
207     }
208
209     resetItemFields(material, course_lib) {
210         this.pcrud.retrieve('acp', material.item(),
211             {flesh: 3, flesh_fields: {acp: ['call_number']}}).subscribe(copy => {
212             if (material.original_status()) {
213                 copy.status(material.original_status());
214             }
215             if (copy.circ_modifier() !== material.original_circ_modifier()) {
216                 copy.circ_modifier(material.original_circ_modifier());
217             }
218             if (material.original_location()) {
219                 copy.location(material.original_location());
220             }
221             if (material.original_callnumber()) {
222                 this.pcrud.retrieve('acn', material.original_callnumber()).subscribe(cn => {
223                     this.updateItem(copy, course_lib, cn.label(), true);
224                 });
225             } else {
226                 this.updateItem(copy, course_lib, copy.call_number().label(), false);
227             }
228         });
229     }
230
231
232     updateItem(item: IdlObject, courseLib, callNumber, updatingVolume) {
233         return new Promise((resolve, reject) => {
234             this.pcrud.update(item).subscribe(() => {
235                 if (updatingVolume) {
236                     const cn = item.call_number();
237                     const callNumberLibrary = this.org.canHaveVolumes(courseLib) ? courseLib.id() : cn.owning_lib();
238                     return this.net.request(
239                         'open-ils.cat', 'open-ils.cat.call_number.find_or_create',
240                         this.auth.token(), callNumber, cn.record(),
241                         callNumberLibrary, cn.prefix(), cn.suffix(),
242                         cn.label_class()
243                     ).subscribe(res => {
244                         const event = this.evt.parse(res);
245                         if (event) { return; }
246                         return this.net.request(
247                             'open-ils.cat', 'open-ils.cat.transfer_copies_to_volume',
248                             this.auth.token(), res.acn_id, [item.id()]
249                         ).subscribe(transfered_res => {
250                             console.debug('Copy transferred to volume with code ' + transfered_res);
251                         }, err => {
252                             reject(err);
253                         }, () => {
254                             resolve(item);
255                         });
256                     }, err => {
257                         reject(err);
258                     }, () => {
259                         resolve(item);
260                     });
261                 } else {
262                     this.pcrud.update(item).subscribe(() => {
263                         resolve(item);
264                     }, () => {
265                         reject(item);
266                     });
267                 }
268             });
269         });
270     }
271
272 }