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, MARC_RECORD_TYPE} from './editor-context';
16 import {NgbNav, NgbNavChangeEvent} from '@ng-bootstrap/ng-bootstrap';
17 import {HoldingsService} from '@eg/staff/share/holdings/holdings.service';
20 export interface MarcSavedEvent {
27 * MARC Record editor main interface.
31 selector: 'eg-marc-editor',
32 templateUrl: './editor.component.html'
35 export class MarcEditorComponent implements OnInit {
37 editorTab: 'rich' | 'flat';
38 sources: ComboboxEntry[];
39 context: MarcEditContext;
41 // True if the save request is in flight
44 @Input() recordType: MARC_RECORD_TYPE = 'biblio';
46 _pendingRecordId: number;
47 @Input() set recordId(id: number) {
48 if (this.record && this.record.id === id) { return; }
50 // Avoid fetching the record by ID before OnInit since we may
51 // not yet know our recordType.
52 if (this.initCalled) {
53 this._pendingRecordId = null;
57 // fetch later in OnInit
58 this._pendingRecordId = id;
62 get recordId(): number {
63 return this.record ? this.record.id : this._pendingRecordId;
66 @Input() set recordXml(xml: string) {
72 get record(): MarcRecord {
73 return this.context.record;
76 // Tell us which record source to select by default.
77 // Useful for new records and in-place editing from bare XML.
78 @Input() recordSource: number;
80 // If true, saving records to the database is assumed to
81 // happen externally. IOW, the record editor is just an
82 // in-place MARC modification interface.
83 @Input() inPlaceMode: boolean;
85 // In inPlaceMode, this is emitted in lieu of saving the record
86 // in th database. When inPlaceMode is false, this is emitted after
87 // the record is successfully saved.
88 @Output() recordSaved: EventEmitter<MarcSavedEvent>;
90 @ViewChild('sourceSelector', {static: false}) sourceSelector: ComboboxComponent;
91 @ViewChild('confirmDelete', {static: false}) confirmDelete: ConfirmDialogComponent;
92 @ViewChild('confirmUndelete', {static: false}) confirmUndelete: ConfirmDialogComponent;
93 @ViewChild('cannotDelete', {static: false}) cannotDelete: ConfirmDialogComponent;
94 @ViewChild('successMsg', {static: false}) successMsg: StringComponent;
95 @ViewChild('failMsg', {static: false}) failMsg: StringComponent;
97 fastItemLabel: string;
98 fastItemBarcode: string;
103 private evt: EventService,
104 private idl: IdlService,
105 private net: NetService,
106 private auth: AuthService,
107 private org: OrgService,
108 private pcrud: PcrudService,
109 private toast: ToastService,
110 private holdings: HoldingsService,
111 private store: ServerStoreService
114 this.recordSaved = new EventEmitter<MarcSavedEvent>();
115 this.context = new MarcEditContext();
117 this.recordSaved.subscribe(_ => this.dataSaving = false);
122 this.initCalled = true;
124 this.context.recordType = this.recordType;
126 this.store.getItem('cat.marcedit.flateditor').then(
127 useFlat => this.editorTab = useFlat ? 'flat' : 'rich');
129 if (!this.record && this.recordId) {
130 this.fromId(this.recordId);
133 if (this.recordType !== 'biblio') { return; }
135 this.pcrud.retrieveAll('cbs').subscribe(
136 src => this.sources.push({id: +src.id(), label: src.source()}),
139 this.sources = this.sources.sort((a, b) =>
140 a.label.toLowerCase() < b.label.toLowerCase() ? -1 : 1
143 if (this.recordSource) {
144 this.sourceSelector.applyEntryId(this.recordSource);
150 changesPending(): boolean {
151 return this.context.changesPending;
154 clearPendingChanges() {
155 this.context.changesPending = false;
158 // Remember the last used tab as the preferred tab.
159 tabChange(evt: NgbNavChangeEvent) {
161 // Avoid undo persistence across tabs since that could result
162 // in changes getting lost.
163 this.context.resetUndos();
165 if (evt.nextId === 'flat') {
166 this.store.setItem('cat.marcedit.flateditor', true);
168 this.store.removeItem('cat.marcedit.flateditor');
172 saveRecord(): Promise<any> {
173 const xml = this.record.toXml();
174 this.dataSaving = true;
176 // Save actions clears any pending changes.
177 this.context.changesPending = false;
178 this.context.resetUndos();
180 let sourceName: string = null;
181 let sourceId: number = null;
183 if (this.sourceSelector && this.sourceSelector.selected) {
184 sourceName = this.sourceSelector.selected.label;
185 sourceId = this.sourceSelector.selected.id;
189 marcXml: xml, bibSource: sourceId, recordId: this.recordId};
191 if (this.inPlaceMode) {
192 // Let the caller have the modified XML and move on.
193 this.recordSaved.emit(emission);
194 return Promise.resolve();
199 if (this.record.id) { // Editing an existing record
201 promise = this.modifyRecord(xml, sourceName, sourceId);
205 promise = this.createRecord(xml, sourceName);
208 // NOTE we do not reinitialize our record with the MARC returned
209 // from the server after a create/update, which means our record
210 // may be out of sync, e.g. missing 901* values. It's the
211 // callers responsibility to tear us down and rebuild us.
212 return promise.then(marcXml => {
213 if (!marcXml) { return null; }
214 this.successMsg.current().then(msg => this.toast.success(msg));
215 emission.marcXml = marcXml;
216 emission.recordId = this.recordId;
217 this.recordSaved.emit(emission);
223 modifyRecord(marcXml: string, sourceName: string, sourceId: number): Promise<any> {
224 const method = this.recordType === 'biblio' ?
225 'open-ils.cat.biblio.record.xml.update' :
226 'open-ils.cat.authority.record.overlay';
228 return this.net.request('open-ils.cat', method,
229 this.auth.token(), this.record.id, marcXml, sourceName
231 ).toPromise().then(response => {
233 const evt = this.evt.parse(response);
236 this.failMsg.current().then(msg => this.toast.warning(msg));
237 this.dataSaving = false;
241 // authority.record.overlay resturns a '1' on success.
242 return typeof response === 'object' ? response.marc() : marcXml;
246 createRecord(marcXml: string, sourceName?: string): Promise<any> {
248 const method = this.recordType === 'biblio' ?
249 'open-ils.cat.biblio.record.xml.create' :
250 'open-ils.cat.authority.record.import';
252 return this.net.request('open-ils.cat', method,
253 this.auth.token(), marcXml, sourceName
254 ).toPromise().then(response => {
256 const evt = this.evt.parse(response);
260 this.failMsg.current().then(msg => this.toast.warning(msg));
261 this.dataSaving = false;
265 this.record.id = response.id();
266 return response.marc();
270 fromId(id: number): Promise<any> {
271 const idlClass = this.recordType === 'authority' ? 'are' : 'bre';
273 return this.pcrud.retrieve(idlClass, id)
274 .toPromise().then(rec => {
275 this.context.record = new MarcRecord(rec.marc());
277 this.record.deleted = rec.deleted() === 't';
278 if (idlClass === 'bre' && rec.source()) {
279 this.sourceSelector.applyEntryId(+rec.source());
284 fromXml(xml: string) {
285 this.context.record = new MarcRecord(xml);
286 this.record.id = null;
289 deleteRecord(): Promise<any> {
291 return this.confirmDelete.open().toPromise()
293 if (!yes) { return; }
296 if (this.recordType === 'authority') {
297 promise = this.deleteAuthorityRecord();
299 promise = this.deleteBibRecord();
302 return promise.then(ok => {
305 return this.fromId(this.record.id).then(_ => {
306 this.recordSaved.emit({
307 marcXml: this.record.toXml(),
308 recordId: this.recordId
315 deleteAuthorityRecord(): Promise<boolean> {
316 return this.pcrud.retrieve('are', this.record.id).toPromise()
317 .then(rec => this.pcrud.remove(rec).toPromise())
318 .then(resp => resp !== null);
321 deleteBibRecord(): Promise<boolean> {
323 return this.net.request('open-ils.cat',
324 'open-ils.cat.biblio.record_entry.delete',
325 this.auth.token(), this.record.id).toPromise()
329 const evt = this.evt.parse(resp);
331 if (evt.textcode === 'RECORD_NOT_EMPTY') {
332 return this.cannotDelete.open().toPromise()
345 undeleteRecord(): Promise<any> {
347 return this.confirmUndelete.open().toPromise()
349 if (!yes) { return; }
352 if (this.recordType === 'authority') {
353 promise = this.undeleteAuthorityRecord();
355 promise = this.undeleteBibRecord();
358 return promise.then(ok => {
360 return this.fromId(this.record.id)
362 this.recordSaved.emit({
363 marcXml: this.record.toXml(),
364 recordId: this.recordId
371 undeleteAuthorityRecord(): Promise<any> {
372 return this.pcrud.retrieve('are', this.record.id).toPromise()
375 return this.pcrud.update(rec).toPromise();
376 }).then(resp => resp !== null);
379 undeleteBibRecord(): Promise<any> {
381 return this.net.request('open-ils.cat',
382 'open-ils.cat.biblio.record_entry.undelete',
383 this.auth.token(), this.record.id).toPromise()
387 const evt = this.evt.parse(resp);
398 // Spawns the copy editor with the requested barcode and
399 // call number label. Called after our record is saved.
401 if (this.showFastAdd && this.fastItemLabel && this.fastItemBarcode) {
404 label: this.fastItemLabel,
405 barcode: this.fastItemBarcode,
409 this.holdings.spawnAddHoldingsUi(this.recordId, null, [fastItem]);