1 dojo.require('dojo.date.locale');
2 dojo.require('dojo.date.stamp');
3 dojo.require('dijit.form.Button');
4 dojo.require('dijit.form.TextBox');
5 dojo.require('dijit.form.FilteringSelect');
6 dojo.require('dijit.form.Textarea');
7 dojo.require('dijit.ProgressBar');
8 dojo.require('openils.User');
9 dojo.require('openils.Util');
10 dojo.require('openils.acq.Lineitem');
11 dojo.require('openils.acq.PO');
12 dojo.require('openils.acq.Picklist');
13 dojo.require('openils.widget.AutoFieldWidget');
14 dojo.require('dojo.data.ItemFileReadStore');
15 dojo.require('openils.widget.ProgressDialog');
16 dojo.require('openils.PermaCrud');
17 dojo.require('openils.XUL');
19 dojo.requireLocalization('openils.acq', 'acq');
20 var localeStrings = dojo.i18n.getLocalization('openils.acq', 'acq');
21 const XUL_OPAC_WRAPPER = 'chrome://open_ils_staff_client/content/cat/opac.xul';
22 var li_exportable_attrs = ["issn", "isbn", "upc"];
24 function nodeByName(name, context) {
25 return dojo.query('[name='+name+']', context)[0];
29 var liDetailBatchFields = ['fund', 'owning_lib', 'location', 'collection_code', 'circ_modifier', 'cn_label'];
30 var liDetailFields = liDetailBatchFields.concat(['barcode', 'note']);
32 function AcqLiTable() {
40 this.toggleState = false;
41 this.tbody = dojo.byId('acq-lit-tbody');
44 this.authtoken = openils.User.authtoken;
45 this.rowTemplate = this.tbody.removeChild(dojo.byId('acq-lit-row'));
46 this.copyTbody = dojo.byId('acq-lit-li-details-tbody');
47 this.copyRow = this.copyTbody.removeChild(dojo.byId('acq-lit-li-details-row'));
48 this.copyBatchRow = dojo.byId('acq-lit-li-details-batch-row');
49 this.copyBatchWidgets = {};
50 this.liNotesTbody = dojo.byId('acq-lit-notes-tbody');
51 this.liNotesRow = this.liNotesTbody.removeChild(dojo.byId('acq-lit-notes-row'));
52 this.realCopiesTbody = dojo.byId('acq-lit-real-copies-tbody');
53 this.realCopiesRow = this.realCopiesTbody.removeChild(dojo.byId('acq-lit-real-copies-row'));
54 this._copy_fields_for_acqdf = ['owning_lib', 'location'];
56 dojo.connect(acqLitLiActionsSelector, 'onChange',
58 self.applySelectedLiAction(this.attr('value'))
59 acqLitLiActionsSelector.attr('value', '_');
62 acqLitCreatePoSubmit.onClick = function() {
63 acqLitPoCreateDialog.hide();
64 self._createPO(acqLitPoCreateDialog.getValues());
67 acqLitSavePlButton.onClick = function() {
68 acqLitSavePlDialog.hide();
69 self._savePl(acqLitSavePlDialog.getValues());
72 acqLitCancelLiStateButton.onClick = function() {
73 acqLitChangeLiStateDialog.hide();
75 acqLitSaveLiStateButton.onClick = function() {
76 acqLitChangeLiStateDialog.hide();
77 self._updateLiState(acqLitChangeLiStateDialog.getValues(), acqLitChangeLiStateDialog.attr('state'));
81 //dojo.byId('acq-lit-notes-new-button').onclick = function(){acqLitCreateLiNoteDialog.show();}
83 dojo.byId('acq-lit-select-toggle').onclick = function(){self.toggleSelect()};
84 dojo.byId('acq-lit-info-back-button').onclick = function(){self.show('list')};
85 dojo.byId('acq-lit-copies-back-button').onclick = function(){self.show('list')};
86 dojo.byId('acq-lit-notes-back-button').onclick = function(){self.show('list')};
87 dojo.byId('acq-lit-real-copies-back-button').onclick = function(){self.show('list')};
89 this.reset = function() {
90 while(self.tbody.childNodes[0])
91 self.tbody.removeChild(self.tbody.childNodes[0]);
96 this.setNext = function(handler) {
97 var link = dojo.byId('acq-lit-next');
99 dojo.style(link, 'visibility', 'visible');
100 link.onclick = handler;
102 dojo.style(link, 'visibility', 'hidden');
106 this.setPrev = function(handler) {
107 var link = dojo.byId('acq-lit-prev');
109 dojo.style(link, 'visibility', 'visible');
110 link.onclick = handler;
112 dojo.style(link, 'visibility', 'hidden');
116 this.show = function(div) {
117 openils.Util.hide('acq-lit-table-div');
118 openils.Util.hide('acq-lit-info-div');
119 openils.Util.hide('acq-lit-li-details');
120 openils.Util.hide('acq-lit-notes-div');
121 openils.Util.hide('acq-lit-real-copies-div');
124 openils.Util.show('acq-lit-table-div');
127 openils.Util.show('acq-lit-info-div');
130 openils.Util.show('acq-lit-li-details');
133 openils.Util.show('acq-lit-real-copies-div');
136 openils.Util.show('acq-lit-notes-div');
140 openils.Util.show(div);
144 this.hide = function() {
148 this.toggleSelect = function() {
150 dojo.forEach(self.selectors, function(i){i.checked = false});
152 dojo.forEach(self.selectors, function(i){i.checked = true});
153 self.toggleState = !self.toggleState;
157 /** @param all If true, assume all are selected */
158 this.getSelected = function(all) {
160 dojo.forEach(self.selectors,
163 selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
169 this.setRowAttr = function(td, liWrapper, field, type) {
170 var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
171 td.appendChild(document.createTextNode(val));
175 * Inserts a single lineitem into the growing table of lineitems
176 * @param {Object} li The lineitem object to insert
178 this.addLineitem = function(li, skip_final_placement) {
179 this.liCache[li.id()] = li;
181 // sort the lineitem notes on edit_time
182 if(!li.lineitem_notes()) li.lineitem_notes([]);
184 var liWrapper = new openils.acq.Lineitem({lineitem:li});
185 var row = self.rowTemplate.cloneNode(true);
186 row.setAttribute('li', li.id());
187 var tds = dojo.query('[attr]', row);
188 dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
189 dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
191 var isbn = liWrapper.findAttr('isbn', 'lineitem_marc_attr_definition');
193 // XXX media prefix for added content
194 dojo.query('[name=jacket]', row)[0].setAttribute('src', '/opac/extras/ac/jacket/small/' + isbn);
197 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
198 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
199 dojo.query('[name=notes_count]', row)[0].innerHTML = li.lineitem_notes().length;
200 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
202 // show which PO this lineitem is a member of
203 if(li.purchase_order() && !this.isPO) {
205 this.poCache[li.purchase_order()] =
206 this.poCache[li.purchase_order()] ||
207 fieldmapper.standardRequest(
208 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
210 this.authtoken, li.purchase_order(), {
211 "flesh_price_summary": true,
212 "flesh_lineitem_count": true
215 if(po && !this.isMeta) {
216 openils.Util.show(nodeByName('po', row), 'inline');
217 var link = nodeByName('po_link', row);
218 link.setAttribute('href', oilsBasePath + '/acq/po/view/' + li.purchase_order());
219 link.innerHTML = 'PO: ' + po.name(); // TODO i18n
223 // show which picklist this lineitem is a member of
224 if(li.picklist() && (this.isPO || this.isMeta)) {
226 this.plCache[li.picklist()] =
227 this.plCache[li.picklist()] ||
228 fieldmapper.standardRequest(
229 ['open-ils.acq', 'open-ils.acq.picklist.retrieve'],
230 {params: [this.authtoken, li.picklist()]});
232 openils.Util.show(nodeByName('pl', row), 'inline');
233 var link = nodeByName('pl_link', row);
234 link.setAttribute('href', oilsBasePath + '/acq/picklist/view/' + li.picklist());
235 link.innerHTML = 'PL: '+pl.name(); // TODO i18n
239 var countNode = nodeByName('count', row);
240 var count = li.item_count() || 0;
241 if (typeof(this._copy_count_cb) == "function") {
242 this._copy_count_cb(li.id(), count);
244 countNode.innerHTML = count;
245 countNode.id = 'acq-lit-copy-count-label-' + li.id();
248 nodeByName('li_state', row).innerHTML = li.state(); // TODO i18n state labels
250 var priceInput = dojo.query('[name=price]', row)[0];
251 var priceData = liWrapper.getPrice();
252 priceInput.value = (priceData) ? priceData.price : '';
253 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
255 // show either "mark received" or "unreceive" as appropriate
256 this.updateLiReceivedness(li, row);
258 if (!skip_final_placement) {
259 self.tbody.appendChild(row);
260 self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
266 this.updateLiReceivedness = function(li, row) {
267 if (typeof(row) == "undefined")
268 row = dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
270 var recv_link = nodeByName("receive_link", row);
271 var unrecv_link = nodeByName("unreceive_link", row);
272 var real_copies_link = nodeByName("real_copies_link", row);
274 /* handle row coloring for based on LI state */
275 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
276 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
278 /* handle links that appear/disappear based on whether LI is received */
283 openils.Util.hide(real_copies_link);
284 openils.Util.hide(unrecv_link);
285 openils.Util.show(recv_link, "inline");
286 recv_link.onclick = function() {
287 if (self.checkLiAlerts(li.id()))
288 self.issueReceive(li);
292 openils.Util.hide(recv_link);
293 openils.Util.show(unrecv_link, "inline");
294 unrecv_link.onclick = function() {
295 if (confirm(localeStrings.UNRECEIVE_LI))
296 self.issueReceive(li, /* rollback */ true);
298 // TODO we should allow editing before receipt, in which case the
299 // test should be "if 1 or more real (acp) copies exist
300 openils.Util.show(real_copies_link);
301 real_copies_link.onclick = function() {
302 self.showRealCopies(li);
308 openils.Util.hide(recv_link);
309 openils.Util.hide(unrecv_link);
310 openils.Util.hide(real_copies_link);
315 * Draws and shows the lineitem notes pane
317 this.drawLiNotes = function(li) {
321 li.lineitem_notes().sort(
323 if(a.edit_time() < b.edit_time()) return 1;
329 while(this.liNotesTbody.childNodes[0])
330 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
333 acqLitCreateLiNoteSubmit.onClick = function() {
334 var value = acqLitCreateNoteText.attr('value');
336 var note = new fieldmapper.acqlin();
339 note.lineitem(li.id());
340 self.updateLiNotes(li, note);
343 dojo.byId('acq-lit-notes-save-button').onclick = function() {
344 self.updateLiNotes(li);
347 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
351 * Draws a single lineitem note in the notes pane
353 this.addLiNote = function(li, note) {
354 if(note.isdeleted()) return;
356 var row = self.liNotesRow.cloneNode(true);
357 dojo.query('[name=value]', row)[0].innerHTML = note.value();
359 dojo.query('[name=delete]', row)[0].onclick = function() {
360 note.isdeleted(true);
361 self.liNotesTbody.removeChild(row);
364 if(note.edit_time()) {
365 dojo.query('[name=edit_time]', row)[0].innerHTML =
366 dojo.date.locale.format(
367 dojo.date.stamp.fromISOString(note.edit_time()),
368 {formatLength:'short'});
371 self.liNotesTbody.appendChild(row);
375 * Updates any new/changed/deleted notes on the server
377 this.updateLiNotes = function(li, newNote) {
383 notes = li.lineitem_notes().filter(
385 if(note.ischanged() || note.isnew() || note.isdeleted())
391 if(notes.length == 0) return;
392 progressDialog.show();
394 fieldmapper.standardRequest(
395 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
397 params : [this.authtoken, notes],
398 onresponse : function(r) {
399 var resp = openils.Util.readResponse(r);
404 // remove the old changed notes
406 dojo.forEach(li.lineitem_notes(),
408 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
412 li.lineitem_notes(list);
415 progressDialog.hide();
416 self.drawLiNotes(li);
420 progressDialog.update(resp);
421 var newnote = resp.note;
423 if(!newnote.isdeleted()) {
424 newnote.isnew(false);
425 newnote.ischanged(false);
426 li.lineitem_notes().push(newnote);
433 this.updateLiPrice = function(input, li) {
435 var price = input.value;
436 var liWrapper = new openils.acq.Lineitem({lineitem:li});
437 var oldPrice = liWrapper.getPrice() || null;
439 if(oldPrice) oldPrice = oldPrice.price;
440 if(price == oldPrice) return;
442 fieldmapper.standardRequest(
443 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
445 params : [this.authtoken, li.id(), price],
446 oncomplete : function(r) {
447 openils.Util.readResponse(r);
453 this.removeLineitem = function(liId) {
454 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
455 delete this.liCache[liId];
456 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
459 this.drawInfo = function(liId) {
461 openils.acq.Lineitem.fetchAttrDefs(
463 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
468 this._fetchLineitem = function(liId, handler) {
470 var li = this.liCache[liId];
471 if(li && li.marc() && li.lineitem_details())
474 fieldmapper.standardRequest(
475 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve'],
478 params: [self.authtoken, liId, {
480 flesh_li_details: true,
481 flesh_fund_debit: true }],
483 oncomplete: function(r) {
484 var li = openils.Util.readResponse(r);
491 this._drawInfo = function(li) {
493 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
496 openils.Util.hide('acq-lit-marc-order-record-label');
497 openils.Util.hide(acqLitEditOrderMarc.domNode);
498 openils.Util.show('acq-lit-marc-real-record-label');
500 openils.Util.show('acq-lit-marc-order-record-label');
501 openils.Util.show(acqLitEditOrderMarc.domNode);
502 openils.Util.hide('acq-lit-marc-real-record-label');
505 this.drawMarcHTML(li);
506 this.infoTbody = dojo.byId('acq-lit-info-tbody');
509 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
510 while(this.infoTbody.childNodes[0])
511 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
513 for(var i = 0; i < li.attributes().length; i++) {
514 var attr = li.attributes()[i];
515 var row = this.infoRow.cloneNode(true);
517 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
518 var name = openils.acq.Lineitem.attrDefs[type].filter(
520 return (a.code() == attr.attr_name());
522 ).pop().description();
524 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
525 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
526 this.infoTbody.appendChild(row);
530 openils.Util.show('acq-lit-info-cat-link');
531 var link = dojo.byId('acq-lit-info-cat-link').getElementsByTagName('a')[0];
533 if(openils.XUL.isXUL()) {
535 var makeRecTab = function() {
538 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
541 show_nav_buttons : true,
542 show_print_button : true,
543 opac_url : xulG.url_prefix(xulG.urls.opac_rdetail + '?r=' + li.eg_bib_id())
547 link.setAttribute('href', 'javascript:void(0);');
548 link.onclick = makeRecTab;
551 var href = link.getAttribute('href');
553 link.setAttribute('href', href + li.eg_bib_id());
556 openils.Util.hide('acq-lit-info-cat-link');
560 this.drawMarcHTML = function(li) {
561 var params = [null, true, li.marc()];
563 params = [li.eg_bib_id(), true];
565 fieldmapper.standardRequest(
566 ['open-ils.search', 'open-ils.search.biblio.record.html'],
569 oncomplete: function(r) {
570 dojo.byId('acq-lit-marc-div').innerHTML =
571 openils.Util.readResponse(r);
577 this.drawCopies = function(liId) {
581 this.copyWidgetCache = {};
582 this.oldCopyWidgetCache = {};
586 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
587 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
588 acqLitCopyCountInput.attr('value', '0');
590 while(this.copyTbody.childNodes[0])
591 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
593 this._drawBatchCopyWidgets();
595 this._fetchDistribFormulas(
597 openils.acq.Lineitem.fetchAttrDefs(
599 self._fetchLineitem(liId, function(li){self._drawCopies(li);});
607 * Insert a new row into the distribution formula selection form
609 this._addDistribFormulaRow = function() {
612 if (!self.distribForms) {
613 // no formulas, hide the form
614 openils.Util.hide('acq-lit-distrib-formula-tbody');
618 if(!this.distribFormulaTemplate)
619 this.distribFormulaTemplate =
620 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
622 var row = this.distribFormulaTemplate.cloneNode(true);
623 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
625 this.dfSelector = new dijit.form.FilteringSelect(
626 {"labelAttr": "dynLabel", "labelType": "html"},
627 nodeByName("selector", row)
629 this._updateFormulaStore();
630 this.dfSelector.fetchProperties =
631 {"sort": [{"attribute": "use_count", "descending": true}]};
633 var apply = new dijit.form.Button(
634 {"label": localeStrings.APPLY},
635 nodeByName('set_button', row)
638 var reset = new dijit.form.Button(
639 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
640 nodeByName("reset_button", row)
643 dojo.connect(apply, 'onClick',
645 var form_id = self.dfSelector.attr("value");
647 self._applyDistribFormula(form_id);
648 reset.attr("disabled", false);
652 dojo.connect(reset, 'onClick',
654 self.restoreCopyFieldsBeforeDF();
657 self._updateFormulaStore();
658 reset.attr("disabled", "true");
665 * Applies a distrib formula to the current set of copies
667 this._applyDistribFormula = function(formula) {
670 formula = this.distribForms.filter(
671 function(form) { return form.id() == formula; }
674 var copyRows = dojo.query('tr', self.copyTbody);
676 if (this.dfeOffset >= copyRows.length) {
677 alert(localeStrings.OUT_OF_COPIES);
681 var entries_applied = 0;
683 var rowIndex = this.dfeOffset;
684 rowIndex < copyRows.length;
688 var row = copyRows[rowIndex];
689 var copy_id = row.getAttribute('copy_id');
690 var copyWidgets = this.copyWidgetCache[copy_id];
691 var entryIndex = this.dfeOffset;
694 // find the correct entry for the current row
695 dojo.forEach(formula.entries(),
698 entryIndex += e.item_count();
699 if(entryIndex > rowIndex)
707 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
708 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
711 this.saveCopyFieldsBeforeDF(copy_id);
712 this._copy_fields_for_acqdf.forEach(
715 copyWidgets[field].attr('value', (entry[field]()));
722 if (entries_applied) {
723 this.dfaCache[formula.id()] = ++(this.dfaCache[formula.id()]) || 1;
724 this._updateFormulaStore();
725 this.dfeOffset += entries_applied;
730 * This function updates the DF store for the dropdown so that use_counts
731 * can reflect DF applications from this session before they're saved
734 this._updateFormulaStore = function() {
735 this.dfSelector.store = new dojo.data.ItemFileReadStore(
737 "data": self._labelFormulasWithCounts(
738 acqdf.toStoreData(self.distribForms)
744 this.saveCopyFieldsBeforeDF = function(copy_id) {
746 if (!this.oldCopyWidgetCache[copy_id]) {
747 var copyWidgets = this.copyWidgetCache[copy_id];
749 this.oldCopyWidgetCache[copy_id] = {};
750 this._copy_fields_for_acqdf.forEach(
752 self.oldCopyWidgetCache[copy_id][f] =
753 copyWidgets[f].attr("value");
759 this.restoreCopyFieldsBeforeDF = function() {
761 for (var copy_id in this.oldCopyWidgetCache) {
762 this._copy_fields_for_acqdf.forEach(
764 self.copyWidgetCache[copy_id][f].attr(
765 "value", self.oldCopyWidgetCache[copy_id][f]
772 this._labelFormulasWithCounts = function(store_data) {
773 for (var key in store_data.items) {
774 var obj = store_data.items[key];
775 obj.use_count = Number(obj.use_count); /* needed for sorting */
777 if (this.dfaCache[obj.id])
778 obj.use_count = obj.use_count + Number(this.dfaCache[obj.id]);
780 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
781 obj.use_count + "]</span> " + obj.name;
787 * This method formerly would not refetch the DF formulas if they'd been
788 * loaded already, but now it always re-fetches, since use_count changes.
790 this._fetchDistribFormulas = function(onload) {
791 fieldmapper.standardRequest(
793 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
796 "params": [openils.User.authtoken],
797 "oncomplete": function(r) {
798 self.distribForms = openils.Util.readResponse(r);
799 if(!self.distribForms || self.distribForms.length == 0) {
800 self.distribForms = [];
802 self._addDistribFormulaRow();
809 this._drawBatchCopyWidgets = function() {
810 var row = this.copyBatchRow;
811 dojo.forEach(liDetailBatchFields,
813 if(self.copyBatchRowDrawn) {
814 self.copyBatchWidgets[field].attr('value', null);
816 var widget = new openils.widget.AutoFieldWidget({
819 parentNode : dojo.query('[name='+field+']', row)[0],
820 orgLimitPerms : ['CREATE_PICKLIST'],
821 dijitArgs : {required:false},
826 self.copyBatchWidgets[field] = w;
832 this.copyBatchRowDrawn = true;
835 this.batchCopyUpdate = function() {
837 for(var k in this.copyWidgetCache) {
838 var cache = this.copyWidgetCache[k];
839 dojo.forEach(liDetailBatchFields, function(f) {
840 var newval = self.copyBatchWidgets[f].attr('value');
841 if(newval) cache[f].attr('value', newval);
846 this._drawCopies = function(li) {
849 // this button sets the total number of copies for a given lineitem
850 acqLitAddCopyCount.onClick = function() {
851 var count = acqLitCopyCountInput.attr('value');
854 while(self.copyCount() < count)
857 // delete rows if necessary
858 var diff = self.copyCount() - count;
860 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
861 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
862 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
864 acqLitCopyCountInput.attr('value', self.copyCount()+'');
870 if(li.lineitem_details().length > 0) {
871 dojo.forEach(li.lineitem_details(),
873 self.addCopy(li, copy);
881 this.copyCount = function() {
883 for(var id in this.copyCache) {
884 if(!this.copyCache[id].isdeleted())
890 this.virtCopyId = -1;
891 this.addCopy = function(li, copy) {
892 var row = this.copyRow.cloneNode(true);
893 this.copyTbody.appendChild(row);
897 copy = new fieldmapper.acqlid();
899 copy.id(this.virtCopyId--);
900 copy.lineitem(li.id());
903 this.copyCache[copy.id()] = copy;
904 row.setAttribute('copy_id', copy.id());
905 self.copyWidgetCache[copy.id()] = {};
907 acqLitCopyCountInput.attr('value', self.copyCount()+'');
909 dojo.forEach(liDetailFields,
911 var widget = new openils.widget.AutoFieldWidget({
915 parentNode : dojo.query('[name='+field+']', row)[0],
916 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
917 readOnly : Boolean(copy.eg_copy_id())
920 // make sure we capture the value from any async widgets
922 copy[field](ww.getFormattedValue())
923 self.copyWidgetCache[copy.id()][field] = w;
926 dojo.connect(widget.widget, 'onChange',
928 if(copy.isnew() || val != copy[field]()) {
929 // prevent setting ischanged() automatically on widget load for existing copies
930 copy[field](widget.getFormattedValue())
931 copy.ischanged(true);
938 this.updateLidReceivedness(copy, row);
941 this.updateLidReceivedness = function(copy, row) {
942 if (typeof(row) == "undefined") {
944 'tr[copy_id="' + copy.id() + '"]', this.copyTbody
949 var recv_link = nodeByName("receive", row);
950 var unrecv_link = nodeByName("unreceive", row);
951 var del_link = nodeByName("delete", row);
954 openils.Util.hide(del_link.parentNode);
956 /* Avoid showing (un)receive links for virtual copies */
958 if(copy.recv_time()) {
959 openils.Util.hide(recv_link);
960 openils.Util.show(unrecv_link);
961 unrecv_link.onclick = function() {
962 if (confirm(localeStrings.UNRECEIVE_LID))
963 self.issueReceive(copy, /* rollback */ true);
966 openils.Util.hide(unrecv_link);
967 openils.Util.show(recv_link);
968 recv_link.onclick = function() {
969 if (self.checkLiAlerts(copy.lineitem()))
970 self.issueReceive(copy);
974 openils.Util.hide(unrecv_link);
975 openils.Util.hide(recv_link);
978 openils.Util.hide(unrecv_link);
979 openils.Util.hide(recv_link);
981 del_link.onclick = function() { self.deleteCopy(row) };
982 openils.Util.show(del_link.parentNode);
986 this._confirmAlert = function(li, lin) {
988 dojo.string.substitute(
989 localeStrings.CONFIRM_LI_ALERT, [
990 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
991 "title", "lineitem_marc_attr_definition"
993 lin.alert_text().description(), lin.value()
999 this.checkLiAlerts = function(li_id) {
1000 var li = this.liCache[li_id];
1002 var alert_notes = li.lineitem_notes().filter(
1003 function(o) { return Boolean(o.alert_text()); }
1006 /* this is _intentionally_ not done in a call to forEach() ... */
1007 for (var i = 0; i < alert_notes.length; i++) {
1008 if (this.noteAcks[alert_notes[i].id()])
1010 else if (!this._confirmAlert(li, alert_notes[i]))
1013 this.noteAcks[alert_notes[i].id()] = true;
1019 this.deleteCopy = function(row) {
1020 var copy = this.copyCache[row.getAttribute('copy_id')];
1021 copy.isdeleted(true);
1023 delete this.copyCache[copy.id()];
1024 this.copyTbody.removeChild(row);
1027 this._dfaCacheAsList = function() {
1029 for (var key in this.dfaCache) {
1030 for (var i = 0; i < this.dfaCache[key]; i++)
1036 this.saveCopyChanges = function(liId) {
1042 for(var id in this.copyCache) {
1043 var c = this.copyCache[id];
1044 if(!c.isdeleted()) total++;
1045 if(c.isnew() || c.ischanged() || c.isdeleted()) {
1046 if(c.id() < 0) c.id(null);
1051 if (typeof(this._copy_count_cb) == "function") {
1052 this._copy_count_cb(liId, total);
1055 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
1058 if (copies.length > 0) {
1059 openils.Util.show("acq-lit-update-copies-progress");
1060 fieldmapper.standardRequest(
1061 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1063 params: [openils.User.authtoken, copies],
1064 onresponse: function(r) {
1065 var res = openils.Util.readResponse(r);
1066 litUpdateCopiesProgress.update(res);
1068 oncomplete: function() {
1069 self.drawCopies(liId);
1070 openils.Util.hide("acq-lit-update-copies-progress");
1076 var dfa_list = this._dfaCacheAsList();
1077 if (dfa_list.length > 0) {
1078 fieldmapper.standardRequest(
1080 "open-ils.acq.distribution_formula.record_application"],
1083 "params": [openils.User.authtoken, dfa_list, liId],
1084 "onresponse": function(r) {
1085 var res = openils.Util.readResponse(r);
1086 if (res && res.length < dfa_list.length)
1087 alert(localeStrings.DFA_NOT_ALL);
1095 this.applySelectedLiAction = function(action) {
1099 case 'delete_selected':
1100 this._deleteLiList(self.getSelected());
1103 case 'create_order':
1105 if(!this.createPoProviderSelector) {
1106 var widget = new openils.widget.AutoFieldWidget({
1107 fmField : 'provider',
1109 searchFilter: {"active": "t"},
1110 parentNode : dojo.byId('acq-lit-po-provider'),
1113 function(w) { self.createPoProviderSelector = w; }
1117 if(!this.createPoAgencySelector) {
1118 var widget = new openils.widget.AutoFieldWidget({
1119 fmField : 'ordering_agency',
1121 parentNode : dojo.byId('acq-lit-po-agency'),
1122 orgLimitPerms : ['CREATE_PURCHASE_ORDER'],
1125 function(w) { self.createPoAgencySelector = w; }
1130 acqLitPoCreateDialog.show();
1133 case 'save_picklist':
1134 this._loadPLSelect();
1135 acqLitSavePlDialog.show();
1138 case 'selector_ready':
1140 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
1141 acqLitChangeLiStateDialog.show();
1152 case 'rollback_receive_po':
1153 this.rollbackPoReceive();
1156 case 'create_assets':
1157 this.createAssets();
1160 case 'export_attr_list':
1161 this.chooseExportAttr();
1164 case 'add_brief_record':
1166 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
1168 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
1172 this.createAssets = function() {
1173 if(!this.isPO) return;
1174 if(!confirm(localeStrings.CREATE_PO_ASSETS_CONFIRM)) return;
1175 this.show('acq-lit-progress-numbers');
1177 fieldmapper.standardRequest(
1178 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
1180 params: [this.authtoken, this.isPO],
1181 onresponse: function(r) {
1182 var resp = openils.Util.readResponse(r);
1183 self._updateProgressNumbers(resp, true);
1189 this.chooseExportAttr = function() {
1190 if (!acqLitExportAttrSelector._li_setup) {
1192 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
1194 "data": acqliad.toStoreData(
1195 (new openils.PermaCrud()).search(
1196 "acqliad", {"code": li_exportable_attrs}
1201 acqLitExportAttrSelector.setValue();
1202 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
1203 acqLitExportAttrSelector._li_setup = true;
1205 openils.Util.show("acq-lit-export-attr-holder", "inline");
1208 this.exportAttrList = function() {
1209 var attr_def = acqLitExportAttrSelector.item;
1210 var li_list = this.getSelected();
1211 var value_list = li_list.map(
1213 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1214 attr_def.code, "lineitem_marc_attr_definition"
1217 ).filter(function(attr) { return Boolean(attr); });
1219 if (value_list.length > 0) {
1220 if (value_list.length < li_list.length) {
1222 dojo.string.substitute(
1223 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
1230 openils.XUL.contentToFileSaveDialog(
1231 value_list.join("\n"),
1232 localeStrings.EXPORT_SAVE_DIALOG_TITLE
1238 alert(dojo.string.substitute(
1239 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
1243 openils.Util.hide("acq-lit-export-attr-holder");
1246 this.printPO = function() {
1247 if(!this.isPO) return;
1248 progressDialog.show(true);
1249 fieldmapper.standardRequest(
1250 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
1252 params: [this.authtoken, this.isPO, 'html'],
1253 oncomplete: function(r) {
1254 progressDialog.hide();
1255 var evt = openils.Util.readResponse(r);
1256 if(evt && evt.template_output()) {
1257 win = window.open('','', 'resizable,width=800,height=600,scrollbars=1');
1258 win.document.body.innerHTML = evt.template_output().data();
1266 this.receivePO = function() {
1267 if (!this.isPO) return;
1269 for (var id in this.liCache) {
1270 /* assumption: liCache reflects exactly the
1271 * set of LIs that belong to our PO */
1272 if (this.liCache[id].state() != "received" &&
1273 !this.checkLiAlerts(id)) return;
1276 this.show('acq-lit-progress-numbers');
1278 fieldmapper.standardRequest(
1279 ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
1281 params: [this.authtoken, this.isPO],
1282 onresponse : function(r) {
1283 var resp = openils.Util.readResponse(r);
1284 self._updateProgressNumbers(resp, true);
1290 this.issueReceive = function(obj, rollback) {
1291 /* (For now) there shall be no marking LI or LIDs (un)received
1292 * except from the actual "view PO" interface. */
1293 if (!this.isPO) return;
1296 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
1298 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
1300 progressDialog.show(true);
1301 fieldmapper.standardRequest(
1302 ["open-ils.acq", method], {
1304 "params": [this.authtoken, obj.id()],
1305 "onresponse": function(r) {
1306 self.handleReceive(openils.Util.readResponse(r));
1308 "oncomplete": function() { progressDialog.hide(); }
1314 * Handles the responses from receive and rollback ML calls.
1316 this.handleReceive = function(resp) {
1319 for (var li_id in resp.li) {
1320 for (var key in resp.li[li_id])
1321 self.liCache[li_id][key](resp.li[li_id][key]);
1322 self.updateLiReceivedness(self.liCache[li_id]);
1326 if (typeof(self.poUpdateCallback) == "function")
1327 self.poUpdateCallback(resp.po);
1330 for (var lid_id in resp.lid) {
1331 for (var key in resp.lid[lid_id])
1332 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
1333 self.updateLidReceivedness(self.copyCache[lid_id]);
1339 this.rollbackPoReceive = function() {
1340 if(!this.isPO) return;
1341 if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
1342 this.show('acq-lit-progress-numbers');
1344 fieldmapper.standardRequest(
1345 ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
1347 params: [this.authtoken, this.isPO],
1348 onresponse : function(r) {
1349 var resp = openils.Util.readResponse(r);
1350 self._updateProgressNumbers(resp, true);
1356 this._updateProgressNumbers = function(resp, reloadOnComplete) {
1358 dojo.byId('acq-pl-lit-li-processed').innerHTML = resp.li;
1359 dojo.byId('acq-pl-lit-lid-processed').innerHTML = resp.lid;
1360 dojo.byId('acq-pl-lit-debits-processed').innerHTML = resp.debits_accrued;
1361 dojo.byId('acq-pl-lit-bibs-processed').innerHTML = resp.bibs;
1362 dojo.byId('acq-pl-lit-indexed-processed').innerHTML = resp.indexed;
1363 dojo.byId('acq-pl-lit-copies-processed').innerHTML = resp.copies;
1364 if(resp.complete && reloadOnComplete)
1365 location.href = location.href;
1369 this._createPO = function(fields) {
1370 this.show('acq-lit-progress-numbers');
1371 var po = new fieldmapper.acqpo();
1372 po.provider(this.createPoProviderSelector.attr('value'));
1373 po.ordering_agency(this.createPoAgencySelector.attr('value'));
1375 var selected = this.getSelected( (fields.create_from == 'all') );
1376 if(selected.length == 0) return;
1378 var max = selected.length * 3;
1381 fieldmapper.standardRequest(
1382 ['open-ils.acq', 'open-ils.acq.purchase_order.create'],
1385 openils.User.authtoken,
1388 lineitems : selected.map(function(li) { return li.id() }),
1389 create_assets : fields.create_assets[0],
1393 onresponse : function(r) {
1394 var resp = openils.Util.readResponse(r);
1395 self._updateProgressNumbers(resp);
1397 location.href = oilsBasePath + '/eg/acq/po/view/' + resp.purchase_order.id();
1403 this._deleteLiList = function(list, idx) {
1404 if(idx == null) idx = 0;
1405 if(idx >= list.length) return;
1406 var liId = list[idx].id();
1407 fieldmapper.standardRequest(
1408 ['open-ils.acq', 'open-ils.acq.lineitem.delete'],
1410 params: [openils.User.authtoken, liId],
1411 oncomplete: function(r) {
1412 self.removeLineitem(liId);
1413 self._deleteLiList(list, ++idx);
1419 this.editOrderMarc = function(li) {
1421 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
1422 to true in about:config */
1424 if(!openils.XUL.enableXPConnect()) return;
1426 if(openils.XUL.isXUL()) {
1427 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
1429 win = window.open('/xul/server/cat/marcedit.xul');
1433 record : {marc : li.marc()},
1435 label: 'Save Record', // XXX I18N
1436 func: function(xmlString) {
1438 fieldmapper.standardRequest(
1439 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
1441 params: [openils.User.authtoken, li],
1442 oncomplete: function(r) {
1443 openils.Util.readResponse(r);
1445 self.drawInfo(li.id())
1454 this._savePl = function(values) {
1456 var selected = this.getSelected( (values.which == 'all') );
1457 openils.Util.show('acq-lit-generic-progress');
1459 if(values.new_name) {
1460 openils.acq.Picklist.create(
1461 {name: values.new_name},
1463 self._updateLiList(id, selected, 0,
1465 location.href = oilsBasePath + '/eg/acq/picklist/view/' + id;
1469 } else if(values.existing_pl) {
1470 // update lineitems to use an existing picklist
1471 self._updateLiList(values.existing_pl, selected, 0,
1473 location.href = oilsBasePath + '/eg/acq/picklist/view/' + values.existing_pl;
1478 this._updateLiState = function(values, state) {
1480 var selected = this.getSelected( (values.which == 'all') );
1481 if(!selected.length) return;
1482 dojo.forEach(selected, function(li) {li.state(state);});
1483 self._updateLiList(null, selected, 0,
1484 // TODO consider inline updates for efficiency
1485 function() { location.href = location.href }
1489 this._updateLiList = function(pl, list, idx, oncomplete) {
1490 if(idx >= list.length) return oncomplete();
1492 if(pl != null) li.picklist(pl);
1493 litGenericProgress.update({maximum: list.length, progress: idx});
1494 new openils.acq.Lineitem({lineitem:li}).update(
1496 self._updateLiList(pl, list, ++idx, oncomplete);
1501 this._loadPLSelect = function() {
1502 if(this._plSelectLoaded) return;
1504 function handleResponse(r) {
1505 plList.push(r.recv().content());
1507 var method = 'open-ils.acq.picklist.user.retrieve';
1508 fieldmapper.standardRequest(
1509 ['open-ils.acq', method],
1511 params: [this.authtoken],
1512 onresponse: handleResponse,
1513 oncomplete: function() {
1514 self._plSelectLoaded = true;
1515 acqLitAddExistingSelect.store =
1516 new dojo.data.ItemFileReadStore({data:acqpl.toStoreData(plList)});
1517 acqLitAddExistingSelect.setValue();
1523 // grab the li-details for this lineitem, grab the linked copies and volumes, add them to the table
1524 this.showRealCopies = function(li) {
1525 while(this.realCopiesTbody.childNodes[0])
1526 this.realCopiesTbody.removeChild(this.realCopiesTbody.childNodes[0]);
1527 this.show('real-copies');
1529 var pcrud = new openils.PermaCrud({authtoken : this.authtoken});
1530 this.realCopyList = [];
1532 var tabIndex = 1000;
1535 acqLitSaveRealCopies.onClick = function() {
1536 self.saveRealCopies();
1539 this._fetchLineitem(li.id(),
1541 li = self.liCache[li.id()] = fullLi;
1545 id : li.lineitem_details().map(
1546 function(item) { return item.eg_copy_id() }
1551 onresponse : function(r) {
1552 var copy = openils.Util.readResponse(r);
1553 var volId = copy.call_number();
1554 var volume = self.volCache[volId];
1556 volume = self.volCache[volId] = pcrud.retrieve('acn', volId);
1558 self.addRealCopy(volume, copy, tabIndex++);
1566 this.addRealCopy = function(volume, copy, tabIndex) {
1567 var row = this.realCopiesRow.cloneNode(true);
1568 this.realCopyList.push(copy);
1572 ['owning_lib', 'location', 'circ_modifier', 'label', 'barcode'],
1575 var isvol = (field == 'owning_lib' || field == 'label');
1576 var widget = new openils.widget.AutoFieldWidget({
1578 fmObject : isvol ? volume : copy,
1579 parentNode : nodeByName(field, row),
1580 readOnly : (field != 'barcode'),
1583 var widgetDrawn = null;
1585 if(field == 'barcode') {
1587 widgetDrawn = function(w, ww) {
1588 var node = w.domNode;
1589 node.setAttribute('tabindex', ''+tabIndex);
1591 // on enter, select the next barcode input
1592 dojo.connect(w, 'onKeyDown',
1594 if(e.keyCode == dojo.keys.ENTER) {
1595 var ti = node.getAttribute('tabindex');
1596 var nextNode = dojo.query('[tabindex=' + String(Number(ti) + 1) + ']', self.realCopiesTbody)[0];
1597 if(nextNode) nextNode.select();
1602 dojo.connect(w, 'onChange',
1604 if(!val || val == copy.barcode()) return;
1605 copy.ischanged(true);
1611 if(self.realCopiesTbody.getElementsByTagName('TR').length == 0)
1616 widget.build(widgetDrawn);
1620 this.realCopiesTbody.appendChild(row);
1621 if(selectNode) selectNode.select();
1624 this.saveRealCopies = function() {
1625 var pcrud = new openils.PermaCrud({authtoken : this.authtoken});
1626 progressDialog.show(true);
1627 var list = this.realCopyList.filter(function(copy) { return copy.ischanged(); });
1628 pcrud.update(list, {oncomplete: function() {
1629 progressDialog.hide();