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=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
201 this.updateLiNotesCount(li, row);
203 // show which PO this lineitem is a member of
204 if(li.purchase_order() && !this.isPO) {
206 this.poCache[li.purchase_order()] =
207 this.poCache[li.purchase_order()] ||
208 fieldmapper.standardRequest(
209 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
211 this.authtoken, li.purchase_order(), {
212 "flesh_price_summary": true,
213 "flesh_lineitem_count": true
216 if(po && !this.isMeta) {
217 openils.Util.show(nodeByName('po', row), 'inline');
218 var link = nodeByName('po_link', row);
219 link.setAttribute('href', oilsBasePath + '/acq/po/view/' + li.purchase_order());
220 link.innerHTML = 'PO: ' + po.name(); // TODO i18n
224 // show which picklist this lineitem is a member of
225 if(li.picklist() && (this.isPO || this.isMeta)) {
227 this.plCache[li.picklist()] =
228 this.plCache[li.picklist()] ||
229 fieldmapper.standardRequest(
230 ['open-ils.acq', 'open-ils.acq.picklist.retrieve'],
231 {params: [this.authtoken, li.picklist()]});
233 openils.Util.show(nodeByName('pl', row), 'inline');
234 var link = nodeByName('pl_link', row);
235 link.setAttribute('href', oilsBasePath + '/acq/picklist/view/' + li.picklist());
236 link.innerHTML = 'PL: '+pl.name(); // TODO i18n
240 var countNode = nodeByName('count', row);
241 var count = li.item_count() || 0;
242 if (typeof(this._copy_count_cb) == "function") {
243 this._copy_count_cb(li.id(), count);
245 countNode.innerHTML = count;
246 countNode.id = 'acq-lit-copy-count-label-' + li.id();
249 nodeByName('li_state', row).innerHTML = li.state(); // TODO i18n state labels
251 var priceInput = dojo.query('[name=price]', row)[0];
252 var priceData = liWrapper.getPrice();
253 priceInput.value = (priceData) ? priceData.price : '';
254 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
256 // show either "mark received" or "unreceive" as appropriate
257 this.updateLiReceivedness(li, row);
259 if (!skip_final_placement) {
260 self.tbody.appendChild(row);
261 self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
267 this.updateLiNotesCount = function(li, row) {
268 if (typeof(row) == "undefined")
269 row = dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
270 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
273 this.updateLiReceivedness = function(li, row) {
274 if (typeof(row) == "undefined")
275 row = dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
277 var recv_link = nodeByName("receive_link", row);
278 var unrecv_link = nodeByName("unreceive_link", row);
279 var real_copies_link = nodeByName("real_copies_link", row);
281 /* handle row coloring for based on LI state */
282 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
283 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
285 /* handle links that appear/disappear based on whether LI is received */
290 openils.Util.hide(real_copies_link);
291 openils.Util.hide(unrecv_link);
292 openils.Util.show(recv_link, "inline");
293 recv_link.onclick = function() {
294 if (self.checkLiAlerts(li.id()))
295 self.issueReceive(li);
299 openils.Util.hide(recv_link);
300 openils.Util.show(unrecv_link, "inline");
301 unrecv_link.onclick = function() {
302 if (confirm(localeStrings.UNRECEIVE_LI))
303 self.issueReceive(li, /* rollback */ true);
305 // TODO we should allow editing before receipt, in which case the
306 // test should be "if 1 or more real (acp) copies exist
307 openils.Util.show(real_copies_link);
308 real_copies_link.onclick = function() {
309 self.showRealCopies(li);
315 openils.Util.hide(recv_link);
316 openils.Util.hide(unrecv_link);
317 openils.Util.hide(real_copies_link);
321 this._setAlertStore = function() {
322 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
324 "data": acqliat.toStoreData(
325 (new openils.PermaCrud()).search(
326 "acqliat", {"id": {"!=": null}}
331 acqLitAlertAlertText.setValue(); /* make the store "live" */
332 acqLitAlertAlertText._store_ready = true;
336 * Draws and shows the lineitem notes pane
338 this.drawLiNotes = function(li) {
341 if (!acqLitAlertAlertText._store_ready)
342 this._setAlertStore();
345 li.lineitem_notes().sort(
347 if(a.edit_time() < b.edit_time()) return 1;
353 while(this.liNotesTbody.childNodes[0])
354 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
357 acqLitCreateLiNoteSubmit.onClick = function() {
358 var value = acqLitCreateNoteText.attr('value');
360 var note = new fieldmapper.acqlin();
363 note.lineitem(li.id());
365 self.updateLiNotes(li, note);
368 acqLitCreateAlertSubmit.onClick = function() {
369 if (!acqLitAlertAlertText.item) {
370 alert(localeStrings.ALERT_UNSELECTED);
374 var alert_text = new fieldmapper.acqliat().fromStoreItem(
375 acqLitAlertAlertText.item
377 var value = acqLitAlertNoteValue.attr("value") || "";
379 var note = new fieldmapper.acqlin();
381 note.lineitem(li.id());
383 note.alert_text(alert_text);
385 self.updateLiNotes(li, note);
388 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
392 * Draws a single lineitem note in the notes pane
394 this.addLiNote = function(li, note) {
395 if(note.isdeleted()) return;
397 var row = self.liNotesRow.cloneNode(true);
398 nodeByName("value", row).innerHTML = note.value();
399 if (note.alert_text())
400 nodeByName("alert_code", row).innerHTML = note.alert_text().code();
402 nodeByName("delete", row).onclick = function() {
403 note.isdeleted(true);
404 self.liNotesTbody.removeChild(row);
405 self.updateLiNotes(li);
408 if(note.edit_time()) {
409 nodeByName("edit_time", row).innerHTML =
410 dojo.date.locale.format(
411 dojo.date.stamp.fromISOString(note.edit_time()),
412 {formatLength:'short'});
415 self.liNotesTbody.appendChild(row);
419 * Updates any new/changed/deleted notes on the server
421 this.updateLiNotes = function(li, newNote) {
427 notes = li.lineitem_notes().filter(
429 if(note.ischanged() || note.isnew() || note.isdeleted())
435 if(notes.length == 0) return;
436 progressDialog.show();
438 fieldmapper.standardRequest(
439 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
441 params : [this.authtoken, notes],
442 onresponse : function(r) {
443 var resp = openils.Util.readResponse(r);
448 // remove the old changed notes
450 dojo.forEach(li.lineitem_notes(),
452 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
456 li.lineitem_notes(list);
459 progressDialog.hide();
460 self.updateLiNotesCount(li);
461 self.drawLiNotes(li);
465 progressDialog.update(resp);
466 var newnote = resp.note;
468 if(!newnote.isdeleted()) {
469 newnote.isnew(false);
470 newnote.ischanged(false);
471 li.lineitem_notes().push(newnote);
478 this.updateLiPrice = function(input, li) {
480 var price = input.value;
481 var liWrapper = new openils.acq.Lineitem({lineitem:li});
482 var oldPrice = liWrapper.getPrice() || null;
484 if(oldPrice) oldPrice = oldPrice.price;
485 if(price == oldPrice) return;
487 fieldmapper.standardRequest(
488 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
490 params : [this.authtoken, li.id(), price],
491 oncomplete : function(r) {
492 openils.Util.readResponse(r);
498 this.removeLineitem = function(liId) {
499 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
500 delete this.liCache[liId];
501 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
504 this.drawInfo = function(liId) {
506 openils.acq.Lineitem.fetchAttrDefs(
508 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
513 this._fetchLineitem = function(liId, handler) {
515 var li = this.liCache[liId];
516 if(li && li.marc() && li.lineitem_details())
519 fieldmapper.standardRequest(
520 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve'],
523 params: [self.authtoken, liId, {
525 flesh_li_details: true,
526 flesh_fund_debit: true }],
528 oncomplete: function(r) {
529 var li = openils.Util.readResponse(r);
536 this._drawInfo = function(li) {
538 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
541 openils.Util.hide('acq-lit-marc-order-record-label');
542 openils.Util.hide(acqLitEditOrderMarc.domNode);
543 openils.Util.show('acq-lit-marc-real-record-label');
545 openils.Util.show('acq-lit-marc-order-record-label');
546 openils.Util.show(acqLitEditOrderMarc.domNode);
547 openils.Util.hide('acq-lit-marc-real-record-label');
550 this.drawMarcHTML(li);
551 this.infoTbody = dojo.byId('acq-lit-info-tbody');
554 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
555 while(this.infoTbody.childNodes[0])
556 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
558 for(var i = 0; i < li.attributes().length; i++) {
559 var attr = li.attributes()[i];
560 var row = this.infoRow.cloneNode(true);
562 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
563 var name = openils.acq.Lineitem.attrDefs[type].filter(
565 return (a.code() == attr.attr_name());
567 ).pop().description();
569 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
570 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
571 this.infoTbody.appendChild(row);
575 openils.Util.show('acq-lit-info-cat-link');
576 var link = dojo.byId('acq-lit-info-cat-link').getElementsByTagName('a')[0];
578 if(openils.XUL.isXUL()) {
580 var makeRecTab = function() {
583 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
586 show_nav_buttons : true,
587 show_print_button : true,
588 opac_url : xulG.url_prefix(xulG.urls.opac_rdetail + '?r=' + li.eg_bib_id())
592 link.setAttribute('href', 'javascript:void(0);');
593 link.onclick = makeRecTab;
596 var href = link.getAttribute('href');
598 link.setAttribute('href', href + li.eg_bib_id());
601 openils.Util.hide('acq-lit-info-cat-link');
605 this.drawMarcHTML = function(li) {
606 var params = [null, true, li.marc()];
608 params = [li.eg_bib_id(), true];
610 fieldmapper.standardRequest(
611 ['open-ils.search', 'open-ils.search.biblio.record.html'],
614 oncomplete: function(r) {
615 dojo.byId('acq-lit-marc-div').innerHTML =
616 openils.Util.readResponse(r);
622 this.drawCopies = function(liId) {
626 this.copyWidgetCache = {};
627 this.oldCopyWidgetCache = {};
631 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
632 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
633 acqLitCopyCountInput.attr('value', '0');
635 while(this.copyTbody.childNodes[0])
636 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
638 this._drawBatchCopyWidgets();
640 this._fetchDistribFormulas(
642 openils.acq.Lineitem.fetchAttrDefs(
644 self._fetchLineitem(liId, function(li){self._drawCopies(li);});
652 * Insert a new row into the distribution formula selection form
654 this._addDistribFormulaRow = function() {
657 if (!self.distribForms) {
658 // no formulas, hide the form
659 openils.Util.hide('acq-lit-distrib-formula-tbody');
663 if(!this.distribFormulaTemplate)
664 this.distribFormulaTemplate =
665 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
667 var row = this.distribFormulaTemplate.cloneNode(true);
668 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
670 this.dfSelector = new dijit.form.FilteringSelect(
671 {"labelAttr": "dynLabel", "labelType": "html"},
672 nodeByName("selector", row)
674 this._updateFormulaStore();
675 this.dfSelector.fetchProperties =
676 {"sort": [{"attribute": "use_count", "descending": true}]};
678 var apply = new dijit.form.Button(
679 {"label": localeStrings.APPLY},
680 nodeByName('set_button', row)
683 var reset = new dijit.form.Button(
684 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
685 nodeByName("reset_button", row)
688 dojo.connect(apply, 'onClick',
690 var form_id = self.dfSelector.attr("value");
692 self._applyDistribFormula(form_id);
693 reset.attr("disabled", false);
697 dojo.connect(reset, 'onClick',
699 self.restoreCopyFieldsBeforeDF();
702 self._updateFormulaStore();
703 reset.attr("disabled", "true");
710 * Applies a distrib formula to the current set of copies
712 this._applyDistribFormula = function(formula) {
715 formula = this.distribForms.filter(
716 function(form) { return form.id() == formula; }
719 var copyRows = dojo.query('tr', self.copyTbody);
721 if (this.dfeOffset >= copyRows.length) {
722 alert(localeStrings.OUT_OF_COPIES);
726 var entries_applied = 0;
728 var rowIndex = this.dfeOffset;
729 rowIndex < copyRows.length;
733 var row = copyRows[rowIndex];
734 var copy_id = row.getAttribute('copy_id');
735 var copyWidgets = this.copyWidgetCache[copy_id];
736 var entryIndex = this.dfeOffset;
739 // find the correct entry for the current row
740 dojo.forEach(formula.entries(),
743 entryIndex += e.item_count();
744 if(entryIndex > rowIndex)
752 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
753 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
756 this.saveCopyFieldsBeforeDF(copy_id);
757 this._copy_fields_for_acqdf.forEach(
760 copyWidgets[field].attr('value', (entry[field]()));
767 if (entries_applied) {
768 this.dfaCache[formula.id()] = ++(this.dfaCache[formula.id()]) || 1;
769 this._updateFormulaStore();
770 this.dfeOffset += entries_applied;
775 * This function updates the DF store for the dropdown so that use_counts
776 * can reflect DF applications from this session before they're saved
779 this._updateFormulaStore = function() {
780 this.dfSelector.store = new dojo.data.ItemFileReadStore(
782 "data": self._labelFormulasWithCounts(
783 acqdf.toStoreData(self.distribForms)
789 this.saveCopyFieldsBeforeDF = function(copy_id) {
791 if (!this.oldCopyWidgetCache[copy_id]) {
792 var copyWidgets = this.copyWidgetCache[copy_id];
794 this.oldCopyWidgetCache[copy_id] = {};
795 this._copy_fields_for_acqdf.forEach(
797 self.oldCopyWidgetCache[copy_id][f] =
798 copyWidgets[f].attr("value");
804 this.restoreCopyFieldsBeforeDF = function() {
806 for (var copy_id in this.oldCopyWidgetCache) {
807 this._copy_fields_for_acqdf.forEach(
809 self.copyWidgetCache[copy_id][f].attr(
810 "value", self.oldCopyWidgetCache[copy_id][f]
817 this._labelFormulasWithCounts = function(store_data) {
818 for (var key in store_data.items) {
819 var obj = store_data.items[key];
820 obj.use_count = Number(obj.use_count); /* needed for sorting */
822 if (this.dfaCache[obj.id])
823 obj.use_count = obj.use_count + Number(this.dfaCache[obj.id]);
825 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
826 obj.use_count + "]</span> " + obj.name;
832 * This method formerly would not refetch the DF formulas if they'd been
833 * loaded already, but now it always re-fetches, since use_count changes.
835 this._fetchDistribFormulas = function(onload) {
836 fieldmapper.standardRequest(
838 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
841 "params": [openils.User.authtoken],
842 "oncomplete": function(r) {
843 self.distribForms = openils.Util.readResponse(r);
844 if(!self.distribForms || self.distribForms.length == 0) {
845 self.distribForms = [];
847 self._addDistribFormulaRow();
854 this._drawBatchCopyWidgets = function() {
855 var row = this.copyBatchRow;
856 dojo.forEach(liDetailBatchFields,
858 if(self.copyBatchRowDrawn) {
859 self.copyBatchWidgets[field].attr('value', null);
861 var widget = new openils.widget.AutoFieldWidget({
864 parentNode : dojo.query('[name='+field+']', row)[0],
865 orgLimitPerms : ['CREATE_PICKLIST'],
866 dijitArgs : {required:false},
871 self.copyBatchWidgets[field] = w;
877 this.copyBatchRowDrawn = true;
880 this.batchCopyUpdate = function() {
882 for(var k in this.copyWidgetCache) {
883 var cache = this.copyWidgetCache[k];
884 dojo.forEach(liDetailBatchFields, function(f) {
885 var newval = self.copyBatchWidgets[f].attr('value');
886 if(newval) cache[f].attr('value', newval);
891 this._drawCopies = function(li) {
894 // this button sets the total number of copies for a given lineitem
895 acqLitAddCopyCount.onClick = function() {
896 var count = acqLitCopyCountInput.attr('value');
899 while(self.copyCount() < count)
902 // delete rows if necessary
903 var diff = self.copyCount() - count;
905 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
906 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
907 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
909 acqLitCopyCountInput.attr('value', self.copyCount()+'');
915 if(li.lineitem_details().length > 0) {
916 dojo.forEach(li.lineitem_details(),
918 self.addCopy(li, copy);
926 this.copyCount = function() {
928 for(var id in this.copyCache) {
929 if(!this.copyCache[id].isdeleted())
935 this.virtCopyId = -1;
936 this.addCopy = function(li, copy) {
937 var row = this.copyRow.cloneNode(true);
938 this.copyTbody.appendChild(row);
942 copy = new fieldmapper.acqlid();
944 copy.id(this.virtCopyId--);
945 copy.lineitem(li.id());
948 this.copyCache[copy.id()] = copy;
949 row.setAttribute('copy_id', copy.id());
950 self.copyWidgetCache[copy.id()] = {};
952 acqLitCopyCountInput.attr('value', self.copyCount()+'');
954 dojo.forEach(liDetailFields,
956 var widget = new openils.widget.AutoFieldWidget({
960 parentNode : dojo.query('[name='+field+']', row)[0],
961 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
962 readOnly : Boolean(copy.eg_copy_id())
965 // make sure we capture the value from any async widgets
967 copy[field](ww.getFormattedValue())
968 self.copyWidgetCache[copy.id()][field] = w;
971 dojo.connect(widget.widget, 'onChange',
973 if(copy.isnew() || val != copy[field]()) {
974 // prevent setting ischanged() automatically on widget load for existing copies
975 copy[field](widget.getFormattedValue())
976 copy.ischanged(true);
983 this.updateLidReceivedness(copy, row);
986 this.updateLidReceivedness = function(copy, row) {
987 if (typeof(row) == "undefined") {
989 'tr[copy_id="' + copy.id() + '"]', this.copyTbody
994 var recv_link = nodeByName("receive", row);
995 var unrecv_link = nodeByName("unreceive", row);
996 var del_link = nodeByName("delete", row);
999 openils.Util.hide(del_link.parentNode);
1001 /* Avoid showing (un)receive links for virtual copies */
1002 if (copy.id() > 0) {
1003 if(copy.recv_time()) {
1004 openils.Util.hide(recv_link);
1005 openils.Util.show(unrecv_link);
1006 unrecv_link.onclick = function() {
1007 if (confirm(localeStrings.UNRECEIVE_LID))
1008 self.issueReceive(copy, /* rollback */ true);
1011 openils.Util.hide(unrecv_link);
1012 openils.Util.show(recv_link);
1013 recv_link.onclick = function() {
1014 if (self.checkLiAlerts(copy.lineitem()))
1015 self.issueReceive(copy);
1019 openils.Util.hide(unrecv_link);
1020 openils.Util.hide(recv_link);
1023 openils.Util.hide(unrecv_link);
1024 openils.Util.hide(recv_link);
1026 del_link.onclick = function() { self.deleteCopy(row) };
1027 openils.Util.show(del_link.parentNode);
1031 this._confirmAlert = function(li, lin) {
1033 dojo.string.substitute(
1034 localeStrings.CONFIRM_LI_ALERT, [
1035 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1036 "title", "lineitem_marc_attr_definition"
1038 lin.alert_text().code(),
1039 lin.alert_text().description() || "",
1046 this.checkLiAlerts = function(li_id) {
1047 var li = this.liCache[li_id];
1049 var alert_notes = li.lineitem_notes().filter(
1050 function(o) { return Boolean(o.alert_text()); }
1053 /* this is _intentionally_ not done in a call to forEach() ... */
1054 for (var i = 0; i < alert_notes.length; i++) {
1055 if (this.noteAcks[alert_notes[i].id()])
1057 else if (!this._confirmAlert(li, alert_notes[i]))
1060 this.noteAcks[alert_notes[i].id()] = true;
1066 this.deleteCopy = function(row) {
1067 var copy = this.copyCache[row.getAttribute('copy_id')];
1068 copy.isdeleted(true);
1070 delete this.copyCache[copy.id()];
1071 this.copyTbody.removeChild(row);
1074 this._dfaCacheAsList = function() {
1076 for (var key in this.dfaCache) {
1077 for (var i = 0; i < this.dfaCache[key]; i++)
1083 this.saveCopyChanges = function(liId) {
1089 for(var id in this.copyCache) {
1090 var c = this.copyCache[id];
1091 if(!c.isdeleted()) total++;
1092 if(c.isnew() || c.ischanged() || c.isdeleted()) {
1093 if(c.id() < 0) c.id(null);
1098 if (typeof(this._copy_count_cb) == "function") {
1099 this._copy_count_cb(liId, total);
1102 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
1105 if (copies.length > 0) {
1106 openils.Util.show("acq-lit-update-copies-progress");
1107 fieldmapper.standardRequest(
1108 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1110 params: [openils.User.authtoken, copies],
1111 onresponse: function(r) {
1112 var res = openils.Util.readResponse(r);
1113 litUpdateCopiesProgress.update(res);
1115 oncomplete: function() {
1116 self.drawCopies(liId);
1117 openils.Util.hide("acq-lit-update-copies-progress");
1123 var dfa_list = this._dfaCacheAsList();
1124 if (dfa_list.length > 0) {
1125 fieldmapper.standardRequest(
1127 "open-ils.acq.distribution_formula.record_application"],
1130 "params": [openils.User.authtoken, dfa_list, liId],
1131 "onresponse": function(r) {
1132 var res = openils.Util.readResponse(r);
1133 if (res && res.length < dfa_list.length)
1134 alert(localeStrings.DFA_NOT_ALL);
1142 this.applySelectedLiAction = function(action) {
1146 case 'delete_selected':
1147 this._deleteLiList(self.getSelected());
1150 case 'create_order':
1152 if(!this.createPoProviderSelector) {
1153 var widget = new openils.widget.AutoFieldWidget({
1154 fmField : 'provider',
1156 searchFilter: {"active": "t"},
1157 parentNode : dojo.byId('acq-lit-po-provider'),
1160 function(w) { self.createPoProviderSelector = w; }
1164 if(!this.createPoAgencySelector) {
1165 var widget = new openils.widget.AutoFieldWidget({
1166 fmField : 'ordering_agency',
1168 parentNode : dojo.byId('acq-lit-po-agency'),
1169 orgLimitPerms : ['CREATE_PURCHASE_ORDER'],
1172 function(w) { self.createPoAgencySelector = w; }
1177 acqLitPoCreateDialog.show();
1180 case 'save_picklist':
1181 this._loadPLSelect();
1182 acqLitSavePlDialog.show();
1185 case 'selector_ready':
1187 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
1188 acqLitChangeLiStateDialog.show();
1199 case 'rollback_receive_po':
1200 this.rollbackPoReceive();
1203 case 'create_assets':
1204 this.createAssets();
1207 case 'export_attr_list':
1208 this.chooseExportAttr();
1211 case 'add_brief_record':
1213 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
1215 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
1219 this.createAssets = function() {
1220 if(!this.isPO) return;
1221 if(!confirm(localeStrings.CREATE_PO_ASSETS_CONFIRM)) return;
1222 this.show('acq-lit-progress-numbers');
1224 fieldmapper.standardRequest(
1225 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
1227 params: [this.authtoken, this.isPO],
1228 onresponse: function(r) {
1229 var resp = openils.Util.readResponse(r);
1230 self._updateProgressNumbers(resp, true);
1236 this.chooseExportAttr = function() {
1237 if (!acqLitExportAttrSelector._li_setup) {
1239 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
1241 "data": acqliad.toStoreData(
1242 (new openils.PermaCrud()).search(
1243 "acqliad", {"code": li_exportable_attrs}
1248 acqLitExportAttrSelector.setValue();
1249 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
1250 acqLitExportAttrSelector._li_setup = true;
1252 openils.Util.show("acq-lit-export-attr-holder", "inline");
1255 this.exportAttrList = function() {
1256 var attr_def = acqLitExportAttrSelector.item;
1257 var li_list = this.getSelected();
1258 var value_list = li_list.map(
1260 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1261 attr_def.code, "lineitem_marc_attr_definition"
1264 ).filter(function(attr) { return Boolean(attr); });
1266 if (value_list.length > 0) {
1267 if (value_list.length < li_list.length) {
1269 dojo.string.substitute(
1270 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
1277 openils.XUL.contentToFileSaveDialog(
1278 value_list.join("\n"),
1279 localeStrings.EXPORT_SAVE_DIALOG_TITLE
1285 alert(dojo.string.substitute(
1286 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
1290 openils.Util.hide("acq-lit-export-attr-holder");
1293 this.printPO = function() {
1294 if(!this.isPO) return;
1295 progressDialog.show(true);
1296 fieldmapper.standardRequest(
1297 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
1299 params: [this.authtoken, this.isPO, 'html'],
1300 oncomplete: function(r) {
1301 progressDialog.hide();
1302 var evt = openils.Util.readResponse(r);
1303 if(evt && evt.template_output()) {
1304 win = window.open('','', 'resizable,width=800,height=600,scrollbars=1');
1305 win.document.body.innerHTML = evt.template_output().data();
1313 this.receivePO = function() {
1314 if (!this.isPO) return;
1316 for (var id in this.liCache) {
1317 /* assumption: liCache reflects exactly the
1318 * set of LIs that belong to our PO */
1319 if (this.liCache[id].state() != "received" &&
1320 !this.checkLiAlerts(id)) return;
1323 this.show('acq-lit-progress-numbers');
1325 fieldmapper.standardRequest(
1326 ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
1328 params: [this.authtoken, this.isPO],
1329 onresponse : function(r) {
1330 var resp = openils.Util.readResponse(r);
1331 self._updateProgressNumbers(resp, true);
1337 this.issueReceive = function(obj, rollback) {
1338 /* (For now) there shall be no marking LI or LIDs (un)received
1339 * except from the actual "view PO" interface. */
1340 if (!this.isPO) return;
1343 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
1345 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
1347 progressDialog.show(true);
1348 fieldmapper.standardRequest(
1349 ["open-ils.acq", method], {
1351 "params": [this.authtoken, obj.id()],
1352 "onresponse": function(r) {
1353 self.handleReceive(openils.Util.readResponse(r));
1355 "oncomplete": function() { progressDialog.hide(); }
1361 * Handles the responses from receive and rollback ML calls.
1363 this.handleReceive = function(resp) {
1366 for (var li_id in resp.li) {
1367 for (var key in resp.li[li_id])
1368 self.liCache[li_id][key](resp.li[li_id][key]);
1369 self.updateLiReceivedness(self.liCache[li_id]);
1373 if (typeof(self.poUpdateCallback) == "function")
1374 self.poUpdateCallback(resp.po);
1377 for (var lid_id in resp.lid) {
1378 for (var key in resp.lid[lid_id])
1379 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
1380 self.updateLidReceivedness(self.copyCache[lid_id]);
1386 this.rollbackPoReceive = function() {
1387 if(!this.isPO) return;
1388 if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
1389 this.show('acq-lit-progress-numbers');
1391 fieldmapper.standardRequest(
1392 ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
1394 params: [this.authtoken, this.isPO],
1395 onresponse : function(r) {
1396 var resp = openils.Util.readResponse(r);
1397 self._updateProgressNumbers(resp, true);
1403 this._updateProgressNumbers = function(resp, reloadOnComplete) {
1405 dojo.byId('acq-pl-lit-li-processed').innerHTML = resp.li;
1406 dojo.byId('acq-pl-lit-lid-processed').innerHTML = resp.lid;
1407 dojo.byId('acq-pl-lit-debits-processed').innerHTML = resp.debits_accrued;
1408 dojo.byId('acq-pl-lit-bibs-processed').innerHTML = resp.bibs;
1409 dojo.byId('acq-pl-lit-indexed-processed').innerHTML = resp.indexed;
1410 dojo.byId('acq-pl-lit-copies-processed').innerHTML = resp.copies;
1411 if(resp.complete && reloadOnComplete)
1412 location.href = location.href;
1416 this._createPO = function(fields) {
1417 this.show('acq-lit-progress-numbers');
1418 var po = new fieldmapper.acqpo();
1419 po.provider(this.createPoProviderSelector.attr('value'));
1420 po.ordering_agency(this.createPoAgencySelector.attr('value'));
1422 var selected = this.getSelected( (fields.create_from == 'all') );
1423 if(selected.length == 0) return;
1425 var max = selected.length * 3;
1428 fieldmapper.standardRequest(
1429 ['open-ils.acq', 'open-ils.acq.purchase_order.create'],
1432 openils.User.authtoken,
1435 lineitems : selected.map(function(li) { return li.id() }),
1436 create_assets : fields.create_assets[0],
1440 onresponse : function(r) {
1441 var resp = openils.Util.readResponse(r);
1442 self._updateProgressNumbers(resp);
1444 location.href = oilsBasePath + '/eg/acq/po/view/' + resp.purchase_order.id();
1450 this._deleteLiList = function(list, idx) {
1451 if(idx == null) idx = 0;
1452 if(idx >= list.length) return;
1453 var liId = list[idx].id();
1454 fieldmapper.standardRequest(
1455 ['open-ils.acq', 'open-ils.acq.lineitem.delete'],
1457 params: [openils.User.authtoken, liId],
1458 oncomplete: function(r) {
1459 self.removeLineitem(liId);
1460 self._deleteLiList(list, ++idx);
1466 this.editOrderMarc = function(li) {
1468 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
1469 to true in about:config */
1471 if(!openils.XUL.enableXPConnect()) return;
1473 if(openils.XUL.isXUL()) {
1474 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
1476 win = window.open('/xul/server/cat/marcedit.xul');
1480 record : {marc : li.marc()},
1482 label: 'Save Record', // XXX I18N
1483 func: function(xmlString) {
1485 fieldmapper.standardRequest(
1486 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
1488 params: [openils.User.authtoken, li],
1489 oncomplete: function(r) {
1490 openils.Util.readResponse(r);
1492 self.drawInfo(li.id())
1501 this._savePl = function(values) {
1503 var selected = this.getSelected( (values.which == 'all') );
1504 openils.Util.show('acq-lit-generic-progress');
1506 if(values.new_name) {
1507 openils.acq.Picklist.create(
1508 {name: values.new_name},
1510 self._updateLiList(id, selected, 0,
1512 location.href = oilsBasePath + '/eg/acq/picklist/view/' + id;
1516 } else if(values.existing_pl) {
1517 // update lineitems to use an existing picklist
1518 self._updateLiList(values.existing_pl, selected, 0,
1520 location.href = oilsBasePath + '/eg/acq/picklist/view/' + values.existing_pl;
1525 this._updateLiState = function(values, state) {
1527 var selected = this.getSelected( (values.which == 'all') );
1528 if(!selected.length) return;
1529 dojo.forEach(selected, function(li) {li.state(state);});
1530 self._updateLiList(null, selected, 0,
1531 // TODO consider inline updates for efficiency
1532 function() { location.href = location.href }
1536 this._updateLiList = function(pl, list, idx, oncomplete) {
1537 if(idx >= list.length) return oncomplete();
1539 if(pl != null) li.picklist(pl);
1540 litGenericProgress.update({maximum: list.length, progress: idx});
1541 new openils.acq.Lineitem({lineitem:li}).update(
1543 self._updateLiList(pl, list, ++idx, oncomplete);
1548 this._loadPLSelect = function() {
1549 if(this._plSelectLoaded) return;
1551 function handleResponse(r) {
1552 plList.push(r.recv().content());
1554 var method = 'open-ils.acq.picklist.user.retrieve';
1555 fieldmapper.standardRequest(
1556 ['open-ils.acq', method],
1558 params: [this.authtoken],
1559 onresponse: handleResponse,
1560 oncomplete: function() {
1561 self._plSelectLoaded = true;
1562 acqLitAddExistingSelect.store =
1563 new dojo.data.ItemFileReadStore({data:acqpl.toStoreData(plList)});
1564 acqLitAddExistingSelect.setValue();
1570 // grab the li-details for this lineitem, grab the linked copies and volumes, add them to the table
1571 this.showRealCopies = function(li) {
1572 while(this.realCopiesTbody.childNodes[0])
1573 this.realCopiesTbody.removeChild(this.realCopiesTbody.childNodes[0]);
1574 this.show('real-copies');
1576 var pcrud = new openils.PermaCrud({authtoken : this.authtoken});
1577 this.realCopyList = [];
1579 var tabIndex = 1000;
1582 acqLitSaveRealCopies.onClick = function() {
1583 self.saveRealCopies();
1586 this._fetchLineitem(li.id(),
1588 li = self.liCache[li.id()] = fullLi;
1592 id : li.lineitem_details().map(
1593 function(item) { return item.eg_copy_id() }
1598 onresponse : function(r) {
1599 var copy = openils.Util.readResponse(r);
1600 var volId = copy.call_number();
1601 var volume = self.volCache[volId];
1603 volume = self.volCache[volId] = pcrud.retrieve('acn', volId);
1605 self.addRealCopy(volume, copy, tabIndex++);
1613 this.addRealCopy = function(volume, copy, tabIndex) {
1614 var row = this.realCopiesRow.cloneNode(true);
1615 this.realCopyList.push(copy);
1619 ['owning_lib', 'location', 'circ_modifier', 'label', 'barcode'],
1622 var isvol = (field == 'owning_lib' || field == 'label');
1623 var widget = new openils.widget.AutoFieldWidget({
1625 fmObject : isvol ? volume : copy,
1626 parentNode : nodeByName(field, row),
1627 readOnly : (field != 'barcode'),
1630 var widgetDrawn = null;
1632 if(field == 'barcode') {
1634 widgetDrawn = function(w, ww) {
1635 var node = w.domNode;
1636 node.setAttribute('tabindex', ''+tabIndex);
1638 // on enter, select the next barcode input
1639 dojo.connect(w, 'onKeyDown',
1641 if(e.keyCode == dojo.keys.ENTER) {
1642 var ti = node.getAttribute('tabindex');
1643 var nextNode = dojo.query('[tabindex=' + String(Number(ti) + 1) + ']', self.realCopiesTbody)[0];
1644 if(nextNode) nextNode.select();
1649 dojo.connect(w, 'onChange',
1651 if(!val || val == copy.barcode()) return;
1652 copy.ischanged(true);
1658 if(self.realCopiesTbody.getElementsByTagName('TR').length == 0)
1663 widget.build(widgetDrawn);
1667 this.realCopiesTbody.appendChild(row);
1668 if(selectNode) selectNode.select();
1671 this.saveRealCopies = function() {
1672 var pcrud = new openils.PermaCrud({authtoken : this.authtoken});
1673 progressDialog.show(true);
1674 var list = this.realCopyList.filter(function(copy) { return copy.ischanged(); });
1675 pcrud.update(list, {oncomplete: function() {
1676 progressDialog.hide();