]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/eg2/src/app/staff/share/marc-edit/editor.component.ts
LP1852782 Linker links to auth record editor
[Evergreen.git] / Open-ILS / src / eg2 / src / app / staff / share / marc-edit / editor.component.ts
1 import {Component, Input, Output, OnInit, EventEmitter, ViewChild} from '@angular/core';
2 import {IdlService} from '@eg/core/idl.service';
3 import {EventService} from '@eg/core/event.service';
4 import {NetService} from '@eg/core/net.service';
5 import {AuthService} from '@eg/core/auth.service';
6 import {OrgService} from '@eg/core/org.service';
7 import {PcrudService} from '@eg/core/pcrud.service';
8 import {ToastService} from '@eg/share/toast/toast.service';
9 import {ServerStoreService} from '@eg/core/server-store.service';
10 import {StringComponent} from '@eg/share/string/string.component';
11 import {MarcRecord} from './marcrecord';
12 import {ComboboxEntry, ComboboxComponent
13   } from '@eg/share/combobox/combobox.component';
14 import {ConfirmDialogComponent} from '@eg/share/dialog/confirm.component';
15 import {MarcEditContext} from './editor-context';
16 import {NgbTabset, NgbTabChangeEvent} from '@ng-bootstrap/ng-bootstrap';
17 import {HoldingsService} from '@eg/staff/share/holdings/holdings.service';
18
19 export interface MarcSavedEvent {
20     marcXml: string;
21     bibSource?: number;
22     recordId?: number;
23 }
24
25 /**
26  * MARC Record editor main interface.
27  */
28
29 @Component({
30   selector: 'eg-marc-editor',
31   templateUrl: './editor.component.html'
32 })
33
34 export class MarcEditorComponent implements OnInit {
35
36     editorTab: 'rich' | 'flat';
37     sources: ComboboxEntry[];
38     context: MarcEditContext;
39
40     // True if the save request is in flight
41     dataSaving: boolean;
42
43     @Input() recordType: 'biblio' | 'authority' = 'biblio';
44
45     _pendingRecordId: number;
46     @Input() set recordId(id: number) {
47         if (this.record && this.record.id === id) { return; }
48
49         // Avoid fetching the record by ID before OnInit since we may
50         // not yet know our recordType.
51         if (this.initCalled) {
52             this._pendingRecordId = null;
53             this.fromId(id);
54
55          } else {
56             // fetch later in OnInit
57             this._pendingRecordId = id;
58          }
59     }
60
61     get recordId(): number {
62         return this.record ? this.record.id : this._pendingRecordId;
63     }
64
65     @Input() set recordXml(xml: string) {
66         if (xml) {
67             this.fromXml(xml);
68         }
69     }
70
71     get record(): MarcRecord {
72         return this.context.record;
73     }
74
75     // Tell us which record source to select by default.
76     // Useful for new records and in-place editing from bare XML.
77     @Input() recordSource: number;
78
79     // If true, saving records to the database is assumed to
80     // happen externally.  IOW, the record editor is just an
81     // in-place MARC modification interface.
82     @Input() inPlaceMode: boolean;
83
84     // In inPlaceMode, this is emitted in lieu of saving the record
85     // in th database.  When inPlaceMode is false, this is emitted after
86     // the record is successfully saved.
87     @Output() recordSaved: EventEmitter<MarcSavedEvent>;
88
89     @ViewChild('sourceSelector', {static: false}) sourceSelector: ComboboxComponent;
90     @ViewChild('confirmDelete', {static: false}) confirmDelete: ConfirmDialogComponent;
91     @ViewChild('confirmUndelete', {static: false}) confirmUndelete: ConfirmDialogComponent;
92     @ViewChild('cannotDelete', {static: false}) cannotDelete: ConfirmDialogComponent;
93     @ViewChild('successMsg', {static: false}) successMsg: StringComponent;
94     @ViewChild('failMsg', {static: false}) failMsg: StringComponent;
95
96     fastItemLabel: string;
97     fastItemBarcode: string;
98     showFastAdd: boolean;
99     initCalled = false;
100
101     constructor(
102         private evt: EventService,
103         private idl: IdlService,
104         private net: NetService,
105         private auth: AuthService,
106         private org: OrgService,
107         private pcrud: PcrudService,
108         private toast: ToastService,
109         private holdings: HoldingsService,
110         private store: ServerStoreService
111     ) {
112         this.sources = [];
113         this.recordSaved = new EventEmitter<MarcSavedEvent>();
114         this.context = new MarcEditContext();
115
116         this.recordSaved.subscribe(_ => this.dataSaving = false);
117     }
118
119     ngOnInit() {
120
121         this.initCalled = true;
122
123         this.context.recordType = this.recordType;
124
125         this.store.getItem('cat.marcedit.flateditor').then(
126             useFlat => this.editorTab = useFlat ? 'flat' : 'rich');
127
128         if (!this.record && this.recordId) {
129             this.fromId(this.recordId);
130         }
131
132         if (this.recordType !== 'biblio') { return; }
133
134         this.pcrud.retrieveAll('cbs').subscribe(
135             src => this.sources.push({id: +src.id(), label: src.source()}),
136             _ => {},
137             () => {
138                 this.sources = this.sources.sort((a, b) =>
139                     a.label.toLowerCase() < b.label.toLowerCase() ? -1 : 1
140                 );
141
142                 if (this.recordSource) {
143                     this.sourceSelector.applyEntryId(this.recordSource);
144                 }
145             }
146         );
147     }
148
149     changesPending(): boolean {
150         return this.context.changesPending;
151     }
152
153     clearPendingChanges() {
154         this.context.changesPending = false;
155     }
156
157     // Remember the last used tab as the preferred tab.
158     tabChange(evt: NgbTabChangeEvent) {
159
160         // Avoid undo persistence across tabs since that could result
161         // in changes getting lost.
162         this.context.resetUndos();
163
164         if (evt.nextId === 'flat') {
165             this.store.setItem('cat.marcedit.flateditor', true);
166         } else {
167             this.store.removeItem('cat.marcedit.flateditor');
168         }
169     }
170
171     saveRecord(): Promise<any> {
172         const xml = this.record.toXml();
173         this.dataSaving = true;
174
175         // Save actions clears any pending changes.
176         this.context.changesPending = false;
177         this.context.resetUndos();
178
179         let sourceName: string = null;
180         let sourceId: number = null;
181
182         if (this.sourceSelector && this.sourceSelector.selected) {
183             sourceName = this.sourceSelector.selected.label;
184             sourceId = this.sourceSelector.selected.id;
185         }
186
187         const emission = {
188             marcXml: xml, bibSource: sourceId, recordId: this.recordId};
189
190         if (this.inPlaceMode) {
191             // Let the caller have the modified XML and move on.
192             this.recordSaved.emit(emission);
193             return Promise.resolve();
194         }
195
196         let promise;
197
198         if (this.record.id) { // Editing an existing record
199
200             promise = this.modifyRecord(xml, sourceName, sourceId);
201
202         } else {
203
204             promise = this.createRecord(xml, sourceName);
205         }
206
207         // NOTE we do not reinitialize our record with the MARC returned
208         // from the server after a create/update, which means our record
209         // may be out of sync, e.g. missing 901* values.  It's the
210         // callers responsibility to tear us down and rebuild us.
211         return promise.then(marcXml => {
212             if (!marcXml) { return null; }
213             this.successMsg.current().then(msg => this.toast.success(msg));
214             emission.marcXml = marcXml;
215             emission.recordId = this.recordId;
216             this.recordSaved.emit(emission);
217             this.fastAdd();
218             return marcXml;
219         });
220     }
221
222     modifyRecord(marcXml: string, sourceName: string, sourceId: number): Promise<any> {
223         const method = 'open-ils.cat.biblio.record.marc.replace';
224
225         return this.net.request('open-ils.cat', method,
226             this.auth.token(), this.record.id, marcXml, sourceName
227
228         ).toPromise().then(response => {
229
230             const evt = this.evt.parse(response);
231             if (evt) {
232                 console.error(evt);
233                 this.failMsg.current().then(msg => this.toast.warning(msg));
234                 this.dataSaving = false;
235                 return null;
236             }
237
238             return response.marc();
239         });
240     }
241
242     createRecord(marcXml: string, sourceName?: string): Promise<any> {
243
244         const method = this.recordType === 'biblio' ?
245             'open-ils.cat.biblio.record.xml.create' :
246             'open-ils.cat.authority.record.import';
247
248         return this.net.request('open-ils.cat', method,
249             this.auth.token(), marcXml, sourceName
250         ).toPromise().then(response => {
251
252             const evt = this.evt.parse(response);
253
254             if (evt) {
255                 console.error(evt);
256                 this.failMsg.current().then(msg => this.toast.warning(msg));
257                 this.dataSaving = false;
258                 return null;
259             }
260
261             this.record.id = response.id();
262             return response.marc();
263         });
264     }
265
266     fromId(id: number): Promise<any> {
267         const idlClass = this.recordType === 'authority' ? 'are' : 'bre';
268
269         return this.pcrud.retrieve(idlClass, id)
270         .toPromise().then(rec => {
271             this.context.record = new MarcRecord(rec.marc());
272             this.record.id = id;
273             this.record.deleted = rec.deleted() === 't';
274             if (idlClass === 'bre' && rec.source()) {
275                 this.sourceSelector.applyEntryId(+rec.source());
276             }
277         });
278     }
279
280     fromXml(xml: string) {
281         this.context.record = new MarcRecord(xml);
282         this.record.id = null;
283     }
284
285     deleteRecord(): Promise<any> {
286
287         return this.confirmDelete.open().toPromise()
288         .then(yes => {
289             if (!yes) { return; }
290
291             return this.net.request('open-ils.cat',
292                 'open-ils.cat.biblio.record_entry.delete',
293                 this.auth.token(), this.record.id).toPromise()
294
295             .then(resp => {
296
297                 const evt = this.evt.parse(resp);
298                 if (evt) {
299                     if (evt.textcode === 'RECORD_NOT_EMPTY') {
300                         return this.cannotDelete.open().toPromise();
301                     } else {
302                         console.error(evt);
303                         return alert(evt);
304                     }
305                 }
306                 return this.fromId(this.record.id)
307                 .then(_ => this.recordSaved.emit(
308                     {marcXml: this.record.toXml(), recordId: this.recordId}));
309             });
310         });
311     }
312
313     undeleteRecord(): Promise<any> {
314
315         return this.confirmUndelete.open().toPromise()
316         .then(yes => {
317             if (!yes) { return; }
318
319             return this.net.request('open-ils.cat',
320                 'open-ils.cat.biblio.record_entry.undelete',
321                 this.auth.token(), this.record.id).toPromise()
322
323             .then(resp => {
324
325                 const evt = this.evt.parse(resp);
326                 if (evt) { console.error(evt); return alert(evt); }
327
328                 return this.fromId(this.record.id)
329                 .then(_ => this.recordSaved.emit(
330                     {marcXml: this.record.toXml(), recordId: this.recordId}));
331             });
332         });
333     }
334
335     // Spawns the copy editor with the requested barcode and
336     // call number label.  Called after our record is saved.
337     fastAdd() {
338         if (this.showFastAdd && this.fastItemLabel && this.fastItemBarcode) {
339
340             const fastItem = {
341                 label: this.fastItemLabel,
342                 barcode: this.fastItemBarcode,
343                 fast_add: true
344             };
345
346             this.holdings.spawnAddHoldingsUi(this.recordId, null, [fastItem]);
347         }
348     }
349 }
350