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);
314 this._setAlertStore = function() {
315 acqLitNoteAlertSelector.store = new dojo.data.ItemFileReadStore(
317 "data": acqliat.toStoreData(
318 (new openils.PermaCrud()).search(
319 "acqliat", {"id": {"!=": null}}
324 acqLitNoteAlertSelector.setValue(); /* make the store "live" */
325 acqLitNoteAlertSelector._store_ready = true;
329 * Draws and shows the lineitem notes pane
331 this.drawLiNotes = function(li) {
334 if (!acqLitNoteAlertSelector._store_ready) {
335 this._setAlertStore();
339 li.lineitem_notes().sort(
341 if(a.edit_time() < b.edit_time()) return 1;
347 while(this.liNotesTbody.childNodes[0])
348 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
351 acqLitCreateLiNoteSubmit.onClick = function() {
352 var value = acqLitCreateNoteText.attr('value');
354 var note = new fieldmapper.acqlin();
357 note.lineitem(li.id());
358 if (acqLitNoteAlertSelector.item)
359 note.alert_text(Number(acqLitNoteAlertSelector.item.id));
361 self.updateLiNotes(li, note);
364 dojo.byId('acq-lit-notes-save-button').onclick = function() {
365 self.updateLiNotes(li);
368 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
372 * Draws a single lineitem note in the notes pane
374 this.addLiNote = function(li, note) {
375 if(note.isdeleted()) return;
377 var row = self.liNotesRow.cloneNode(true);
378 dojo.query('[name=value]', row)[0].innerHTML = note.value();
380 dojo.query('[name=delete]', row)[0].onclick = function() {
381 note.isdeleted(true);
382 self.liNotesTbody.removeChild(row);
385 if(note.edit_time()) {
386 dojo.query('[name=edit_time]', row)[0].innerHTML =
387 dojo.date.locale.format(
388 dojo.date.stamp.fromISOString(note.edit_time()),
389 {formatLength:'short'});
392 self.liNotesTbody.appendChild(row);
396 * Updates any new/changed/deleted notes on the server
398 this.updateLiNotes = function(li, newNote) {
404 notes = li.lineitem_notes().filter(
406 if(note.ischanged() || note.isnew() || note.isdeleted())
412 if(notes.length == 0) return;
413 progressDialog.show();
415 fieldmapper.standardRequest(
416 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
418 params : [this.authtoken, notes],
419 onresponse : function(r) {
420 var resp = openils.Util.readResponse(r);
425 // remove the old changed notes
427 dojo.forEach(li.lineitem_notes(),
429 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
433 li.lineitem_notes(list);
436 progressDialog.hide();
437 self.drawLiNotes(li);
441 progressDialog.update(resp);
442 var newnote = resp.note;
444 if(!newnote.isdeleted()) {
445 newnote.isnew(false);
446 newnote.ischanged(false);
447 li.lineitem_notes().push(newnote);
454 this.updateLiPrice = function(input, li) {
456 var price = input.value;
457 var liWrapper = new openils.acq.Lineitem({lineitem:li});
458 var oldPrice = liWrapper.getPrice() || null;
460 if(oldPrice) oldPrice = oldPrice.price;
461 if(price == oldPrice) return;
463 fieldmapper.standardRequest(
464 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
466 params : [this.authtoken, li.id(), price],
467 oncomplete : function(r) {
468 openils.Util.readResponse(r);
474 this.removeLineitem = function(liId) {
475 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
476 delete this.liCache[liId];
477 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
480 this.drawInfo = function(liId) {
482 openils.acq.Lineitem.fetchAttrDefs(
484 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
489 this._fetchLineitem = function(liId, handler) {
491 var li = this.liCache[liId];
492 if(li && li.marc() && li.lineitem_details())
495 fieldmapper.standardRequest(
496 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve'],
499 params: [self.authtoken, liId, {
501 flesh_li_details: true,
502 flesh_fund_debit: true }],
504 oncomplete: function(r) {
505 var li = openils.Util.readResponse(r);
512 this._drawInfo = function(li) {
514 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
517 openils.Util.hide('acq-lit-marc-order-record-label');
518 openils.Util.hide(acqLitEditOrderMarc.domNode);
519 openils.Util.show('acq-lit-marc-real-record-label');
521 openils.Util.show('acq-lit-marc-order-record-label');
522 openils.Util.show(acqLitEditOrderMarc.domNode);
523 openils.Util.hide('acq-lit-marc-real-record-label');
526 this.drawMarcHTML(li);
527 this.infoTbody = dojo.byId('acq-lit-info-tbody');
530 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
531 while(this.infoTbody.childNodes[0])
532 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
534 for(var i = 0; i < li.attributes().length; i++) {
535 var attr = li.attributes()[i];
536 var row = this.infoRow.cloneNode(true);
538 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
539 var name = openils.acq.Lineitem.attrDefs[type].filter(
541 return (a.code() == attr.attr_name());
543 ).pop().description();
545 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
546 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
547 this.infoTbody.appendChild(row);
551 openils.Util.show('acq-lit-info-cat-link');
552 var link = dojo.byId('acq-lit-info-cat-link').getElementsByTagName('a')[0];
554 if(openils.XUL.isXUL()) {
556 var makeRecTab = function() {
559 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
562 show_nav_buttons : true,
563 show_print_button : true,
564 opac_url : xulG.url_prefix(xulG.urls.opac_rdetail + '?r=' + li.eg_bib_id())
568 link.setAttribute('href', 'javascript:void(0);');
569 link.onclick = makeRecTab;
572 var href = link.getAttribute('href');
574 link.setAttribute('href', href + li.eg_bib_id());
577 openils.Util.hide('acq-lit-info-cat-link');
581 this.drawMarcHTML = function(li) {
582 var params = [null, true, li.marc()];
584 params = [li.eg_bib_id(), true];
586 fieldmapper.standardRequest(
587 ['open-ils.search', 'open-ils.search.biblio.record.html'],
590 oncomplete: function(r) {
591 dojo.byId('acq-lit-marc-div').innerHTML =
592 openils.Util.readResponse(r);
598 this.drawCopies = function(liId) {
602 this.copyWidgetCache = {};
603 this.oldCopyWidgetCache = {};
607 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
608 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
609 acqLitCopyCountInput.attr('value', '0');
611 while(this.copyTbody.childNodes[0])
612 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
614 this._drawBatchCopyWidgets();
616 this._fetchDistribFormulas(
618 openils.acq.Lineitem.fetchAttrDefs(
620 self._fetchLineitem(liId, function(li){self._drawCopies(li);});
628 * Insert a new row into the distribution formula selection form
630 this._addDistribFormulaRow = function() {
633 if (!self.distribForms) {
634 // no formulas, hide the form
635 openils.Util.hide('acq-lit-distrib-formula-tbody');
639 if(!this.distribFormulaTemplate)
640 this.distribFormulaTemplate =
641 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
643 var row = this.distribFormulaTemplate.cloneNode(true);
644 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
646 this.dfSelector = new dijit.form.FilteringSelect(
647 {"labelAttr": "dynLabel", "labelType": "html"},
648 nodeByName("selector", row)
650 this._updateFormulaStore();
651 this.dfSelector.fetchProperties =
652 {"sort": [{"attribute": "use_count", "descending": true}]};
654 var apply = new dijit.form.Button(
655 {"label": localeStrings.APPLY},
656 nodeByName('set_button', row)
659 var reset = new dijit.form.Button(
660 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
661 nodeByName("reset_button", row)
664 dojo.connect(apply, 'onClick',
666 var form_id = self.dfSelector.attr("value");
668 self._applyDistribFormula(form_id);
669 reset.attr("disabled", false);
673 dojo.connect(reset, 'onClick',
675 self.restoreCopyFieldsBeforeDF();
678 self._updateFormulaStore();
679 reset.attr("disabled", "true");
686 * Applies a distrib formula to the current set of copies
688 this._applyDistribFormula = function(formula) {
691 formula = this.distribForms.filter(
692 function(form) { return form.id() == formula; }
695 var copyRows = dojo.query('tr', self.copyTbody);
697 if (this.dfeOffset >= copyRows.length) {
698 alert(localeStrings.OUT_OF_COPIES);
702 var entries_applied = 0;
704 var rowIndex = this.dfeOffset;
705 rowIndex < copyRows.length;
709 var row = copyRows[rowIndex];
710 var copy_id = row.getAttribute('copy_id');
711 var copyWidgets = this.copyWidgetCache[copy_id];
712 var entryIndex = this.dfeOffset;
715 // find the correct entry for the current row
716 dojo.forEach(formula.entries(),
719 entryIndex += e.item_count();
720 if(entryIndex > rowIndex)
728 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
729 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
732 this.saveCopyFieldsBeforeDF(copy_id);
733 this._copy_fields_for_acqdf.forEach(
736 copyWidgets[field].attr('value', (entry[field]()));
743 if (entries_applied) {
744 this.dfaCache[formula.id()] = ++(this.dfaCache[formula.id()]) || 1;
745 this._updateFormulaStore();
746 this.dfeOffset += entries_applied;
751 * This function updates the DF store for the dropdown so that use_counts
752 * can reflect DF applications from this session before they're saved
755 this._updateFormulaStore = function() {
756 this.dfSelector.store = new dojo.data.ItemFileReadStore(
758 "data": self._labelFormulasWithCounts(
759 acqdf.toStoreData(self.distribForms)
765 this.saveCopyFieldsBeforeDF = function(copy_id) {
767 if (!this.oldCopyWidgetCache[copy_id]) {
768 var copyWidgets = this.copyWidgetCache[copy_id];
770 this.oldCopyWidgetCache[copy_id] = {};
771 this._copy_fields_for_acqdf.forEach(
773 self.oldCopyWidgetCache[copy_id][f] =
774 copyWidgets[f].attr("value");
780 this.restoreCopyFieldsBeforeDF = function() {
782 for (var copy_id in this.oldCopyWidgetCache) {
783 this._copy_fields_for_acqdf.forEach(
785 self.copyWidgetCache[copy_id][f].attr(
786 "value", self.oldCopyWidgetCache[copy_id][f]
793 this._labelFormulasWithCounts = function(store_data) {
794 for (var key in store_data.items) {
795 var obj = store_data.items[key];
796 obj.use_count = Number(obj.use_count); /* needed for sorting */
798 if (this.dfaCache[obj.id])
799 obj.use_count = obj.use_count + Number(this.dfaCache[obj.id]);
801 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
802 obj.use_count + "]</span> " + obj.name;
808 * This method formerly would not refetch the DF formulas if they'd been
809 * loaded already, but now it always re-fetches, since use_count changes.
811 this._fetchDistribFormulas = function(onload) {
812 fieldmapper.standardRequest(
814 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
817 "params": [openils.User.authtoken],
818 "oncomplete": function(r) {
819 self.distribForms = openils.Util.readResponse(r);
820 if(!self.distribForms || self.distribForms.length == 0) {
821 self.distribForms = [];
823 self._addDistribFormulaRow();
830 this._drawBatchCopyWidgets = function() {
831 var row = this.copyBatchRow;
832 dojo.forEach(liDetailBatchFields,
834 if(self.copyBatchRowDrawn) {
835 self.copyBatchWidgets[field].attr('value', null);
837 var widget = new openils.widget.AutoFieldWidget({
840 parentNode : dojo.query('[name='+field+']', row)[0],
841 orgLimitPerms : ['CREATE_PICKLIST'],
842 dijitArgs : {required:false},
847 self.copyBatchWidgets[field] = w;
853 this.copyBatchRowDrawn = true;
856 this.batchCopyUpdate = function() {
858 for(var k in this.copyWidgetCache) {
859 var cache = this.copyWidgetCache[k];
860 dojo.forEach(liDetailBatchFields, function(f) {
861 var newval = self.copyBatchWidgets[f].attr('value');
862 if(newval) cache[f].attr('value', newval);
867 this._drawCopies = function(li) {
870 // this button sets the total number of copies for a given lineitem
871 acqLitAddCopyCount.onClick = function() {
872 var count = acqLitCopyCountInput.attr('value');
875 while(self.copyCount() < count)
878 // delete rows if necessary
879 var diff = self.copyCount() - count;
881 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
882 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
883 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
885 acqLitCopyCountInput.attr('value', self.copyCount()+'');
891 if(li.lineitem_details().length > 0) {
892 dojo.forEach(li.lineitem_details(),
894 self.addCopy(li, copy);
902 this.copyCount = function() {
904 for(var id in this.copyCache) {
905 if(!this.copyCache[id].isdeleted())
911 this.virtCopyId = -1;
912 this.addCopy = function(li, copy) {
913 var row = this.copyRow.cloneNode(true);
914 this.copyTbody.appendChild(row);
918 copy = new fieldmapper.acqlid();
920 copy.id(this.virtCopyId--);
921 copy.lineitem(li.id());
924 this.copyCache[copy.id()] = copy;
925 row.setAttribute('copy_id', copy.id());
926 self.copyWidgetCache[copy.id()] = {};
928 acqLitCopyCountInput.attr('value', self.copyCount()+'');
930 dojo.forEach(liDetailFields,
932 var widget = new openils.widget.AutoFieldWidget({
936 parentNode : dojo.query('[name='+field+']', row)[0],
937 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
938 readOnly : Boolean(copy.eg_copy_id())
941 // make sure we capture the value from any async widgets
943 copy[field](ww.getFormattedValue())
944 self.copyWidgetCache[copy.id()][field] = w;
947 dojo.connect(widget.widget, 'onChange',
949 if(copy.isnew() || val != copy[field]()) {
950 // prevent setting ischanged() automatically on widget load for existing copies
951 copy[field](widget.getFormattedValue())
952 copy.ischanged(true);
959 this.updateLidReceivedness(copy, row);
962 this.updateLidReceivedness = function(copy, row) {
963 if (typeof(row) == "undefined") {
965 'tr[copy_id="' + copy.id() + '"]', this.copyTbody
970 var recv_link = nodeByName("receive", row);
971 var unrecv_link = nodeByName("unreceive", row);
972 var del_link = nodeByName("delete", row);
975 openils.Util.hide(del_link.parentNode);
977 /* Avoid showing (un)receive links for virtual copies */
979 if(copy.recv_time()) {
980 openils.Util.hide(recv_link);
981 openils.Util.show(unrecv_link);
982 unrecv_link.onclick = function() {
983 if (confirm(localeStrings.UNRECEIVE_LID))
984 self.issueReceive(copy, /* rollback */ true);
987 openils.Util.hide(unrecv_link);
988 openils.Util.show(recv_link);
989 recv_link.onclick = function() {
990 if (self.checkLiAlerts(copy.lineitem()))
991 self.issueReceive(copy);
995 openils.Util.hide(unrecv_link);
996 openils.Util.hide(recv_link);
999 openils.Util.hide(unrecv_link);
1000 openils.Util.hide(recv_link);
1002 del_link.onclick = function() { self.deleteCopy(row) };
1003 openils.Util.show(del_link.parentNode);
1007 this._confirmAlert = function(li, lin) {
1009 dojo.string.substitute(
1010 localeStrings.CONFIRM_LI_ALERT, [
1011 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1012 "title", "lineitem_marc_attr_definition"
1014 lin.alert_text().description(), lin.value()
1020 this.checkLiAlerts = function(li_id) {
1021 var li = this.liCache[li_id];
1023 var alert_notes = li.lineitem_notes().filter(
1024 function(o) { return Boolean(o.alert_text()); }
1027 /* this is _intentionally_ not done in a call to forEach() ... */
1028 for (var i = 0; i < alert_notes.length; i++) {
1029 if (this.noteAcks[alert_notes[i].id()])
1031 else if (!this._confirmAlert(li, alert_notes[i]))
1034 this.noteAcks[alert_notes[i].id()] = true;
1040 this.deleteCopy = function(row) {
1041 var copy = this.copyCache[row.getAttribute('copy_id')];
1042 copy.isdeleted(true);
1044 delete this.copyCache[copy.id()];
1045 this.copyTbody.removeChild(row);
1048 this._dfaCacheAsList = function() {
1050 for (var key in this.dfaCache) {
1051 for (var i = 0; i < this.dfaCache[key]; i++)
1057 this.saveCopyChanges = function(liId) {
1063 for(var id in this.copyCache) {
1064 var c = this.copyCache[id];
1065 if(!c.isdeleted()) total++;
1066 if(c.isnew() || c.ischanged() || c.isdeleted()) {
1067 if(c.id() < 0) c.id(null);
1072 if (typeof(this._copy_count_cb) == "function") {
1073 this._copy_count_cb(liId, total);
1076 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
1079 if (copies.length > 0) {
1080 openils.Util.show("acq-lit-update-copies-progress");
1081 fieldmapper.standardRequest(
1082 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1084 params: [openils.User.authtoken, copies],
1085 onresponse: function(r) {
1086 var res = openils.Util.readResponse(r);
1087 litUpdateCopiesProgress.update(res);
1089 oncomplete: function() {
1090 self.drawCopies(liId);
1091 openils.Util.hide("acq-lit-update-copies-progress");
1097 var dfa_list = this._dfaCacheAsList();
1098 if (dfa_list.length > 0) {
1099 fieldmapper.standardRequest(
1101 "open-ils.acq.distribution_formula.record_application"],
1104 "params": [openils.User.authtoken, dfa_list, liId],
1105 "onresponse": function(r) {
1106 var res = openils.Util.readResponse(r);
1107 if (res && res.length < dfa_list.length)
1108 alert(localeStrings.DFA_NOT_ALL);
1116 this.applySelectedLiAction = function(action) {
1120 case 'delete_selected':
1121 this._deleteLiList(self.getSelected());
1124 case 'create_order':
1126 if(!this.createPoProviderSelector) {
1127 var widget = new openils.widget.AutoFieldWidget({
1128 fmField : 'provider',
1130 searchFilter: {"active": "t"},
1131 parentNode : dojo.byId('acq-lit-po-provider'),
1134 function(w) { self.createPoProviderSelector = w; }
1138 if(!this.createPoAgencySelector) {
1139 var widget = new openils.widget.AutoFieldWidget({
1140 fmField : 'ordering_agency',
1142 parentNode : dojo.byId('acq-lit-po-agency'),
1143 orgLimitPerms : ['CREATE_PURCHASE_ORDER'],
1146 function(w) { self.createPoAgencySelector = w; }
1151 acqLitPoCreateDialog.show();
1154 case 'save_picklist':
1155 this._loadPLSelect();
1156 acqLitSavePlDialog.show();
1159 case 'selector_ready':
1161 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
1162 acqLitChangeLiStateDialog.show();
1173 case 'rollback_receive_po':
1174 this.rollbackPoReceive();
1177 case 'create_assets':
1178 this.createAssets();
1181 case 'export_attr_list':
1182 this.chooseExportAttr();
1185 case 'add_brief_record':
1187 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
1189 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
1193 this.createAssets = function() {
1194 if(!this.isPO) return;
1195 if(!confirm(localeStrings.CREATE_PO_ASSETS_CONFIRM)) return;
1196 this.show('acq-lit-progress-numbers');
1198 fieldmapper.standardRequest(
1199 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
1201 params: [this.authtoken, this.isPO],
1202 onresponse: function(r) {
1203 var resp = openils.Util.readResponse(r);
1204 self._updateProgressNumbers(resp, true);
1210 this.chooseExportAttr = function() {
1211 if (!acqLitExportAttrSelector._li_setup) {
1213 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
1215 "data": acqliad.toStoreData(
1216 (new openils.PermaCrud()).search(
1217 "acqliad", {"code": li_exportable_attrs}
1222 acqLitExportAttrSelector.setValue();
1223 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
1224 acqLitExportAttrSelector._li_setup = true;
1226 openils.Util.show("acq-lit-export-attr-holder", "inline");
1229 this.exportAttrList = function() {
1230 var attr_def = acqLitExportAttrSelector.item;
1231 var li_list = this.getSelected();
1232 var value_list = li_list.map(
1234 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1235 attr_def.code, "lineitem_marc_attr_definition"
1238 ).filter(function(attr) { return Boolean(attr); });
1240 if (value_list.length > 0) {
1241 if (value_list.length < li_list.length) {
1243 dojo.string.substitute(
1244 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
1251 openils.XUL.contentToFileSaveDialog(
1252 value_list.join("\n"),
1253 localeStrings.EXPORT_SAVE_DIALOG_TITLE
1259 alert(dojo.string.substitute(
1260 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
1264 openils.Util.hide("acq-lit-export-attr-holder");
1267 this.printPO = function() {
1268 if(!this.isPO) return;
1269 progressDialog.show(true);
1270 fieldmapper.standardRequest(
1271 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
1273 params: [this.authtoken, this.isPO, 'html'],
1274 oncomplete: function(r) {
1275 progressDialog.hide();
1276 var evt = openils.Util.readResponse(r);
1277 if(evt && evt.template_output()) {
1278 win = window.open('','', 'resizable,width=800,height=600,scrollbars=1');
1279 win.document.body.innerHTML = evt.template_output().data();
1287 this.receivePO = function() {
1288 if (!this.isPO) return;
1290 for (var id in this.liCache) {
1291 /* assumption: liCache reflects exactly the
1292 * set of LIs that belong to our PO */
1293 if (this.liCache[id].state() != "received" &&
1294 !this.checkLiAlerts(id)) return;
1297 this.show('acq-lit-progress-numbers');
1299 fieldmapper.standardRequest(
1300 ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
1302 params: [this.authtoken, this.isPO],
1303 onresponse : function(r) {
1304 var resp = openils.Util.readResponse(r);
1305 self._updateProgressNumbers(resp, true);
1311 this.issueReceive = function(obj, rollback) {
1312 /* (For now) there shall be no marking LI or LIDs (un)received
1313 * except from the actual "view PO" interface. */
1314 if (!this.isPO) return;
1317 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
1319 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
1321 progressDialog.show(true);
1322 fieldmapper.standardRequest(
1323 ["open-ils.acq", method], {
1325 "params": [this.authtoken, obj.id()],
1326 "onresponse": function(r) {
1327 self.handleReceive(openils.Util.readResponse(r));
1329 "oncomplete": function() { progressDialog.hide(); }
1335 * Handles the responses from receive and rollback ML calls.
1337 this.handleReceive = function(resp) {
1340 for (var li_id in resp.li) {
1341 for (var key in resp.li[li_id])
1342 self.liCache[li_id][key](resp.li[li_id][key]);
1343 self.updateLiReceivedness(self.liCache[li_id]);
1347 if (typeof(self.poUpdateCallback) == "function")
1348 self.poUpdateCallback(resp.po);
1351 for (var lid_id in resp.lid) {
1352 for (var key in resp.lid[lid_id])
1353 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
1354 self.updateLidReceivedness(self.copyCache[lid_id]);
1360 this.rollbackPoReceive = function() {
1361 if(!this.isPO) return;
1362 if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
1363 this.show('acq-lit-progress-numbers');
1365 fieldmapper.standardRequest(
1366 ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
1368 params: [this.authtoken, this.isPO],
1369 onresponse : function(r) {
1370 var resp = openils.Util.readResponse(r);
1371 self._updateProgressNumbers(resp, true);
1377 this._updateProgressNumbers = function(resp, reloadOnComplete) {
1379 dojo.byId('acq-pl-lit-li-processed').innerHTML = resp.li;
1380 dojo.byId('acq-pl-lit-lid-processed').innerHTML = resp.lid;
1381 dojo.byId('acq-pl-lit-debits-processed').innerHTML = resp.debits_accrued;
1382 dojo.byId('acq-pl-lit-bibs-processed').innerHTML = resp.bibs;
1383 dojo.byId('acq-pl-lit-indexed-processed').innerHTML = resp.indexed;
1384 dojo.byId('acq-pl-lit-copies-processed').innerHTML = resp.copies;
1385 if(resp.complete && reloadOnComplete)
1386 location.href = location.href;
1390 this._createPO = function(fields) {
1391 this.show('acq-lit-progress-numbers');
1392 var po = new fieldmapper.acqpo();
1393 po.provider(this.createPoProviderSelector.attr('value'));
1394 po.ordering_agency(this.createPoAgencySelector.attr('value'));
1396 var selected = this.getSelected( (fields.create_from == 'all') );
1397 if(selected.length == 0) return;
1399 var max = selected.length * 3;
1402 fieldmapper.standardRequest(
1403 ['open-ils.acq', 'open-ils.acq.purchase_order.create'],
1406 openils.User.authtoken,
1409 lineitems : selected.map(function(li) { return li.id() }),
1410 create_assets : fields.create_assets[0],
1414 onresponse : function(r) {
1415 var resp = openils.Util.readResponse(r);
1416 self._updateProgressNumbers(resp);
1418 location.href = oilsBasePath + '/eg/acq/po/view/' + resp.purchase_order.id();
1424 this._deleteLiList = function(list, idx) {
1425 if(idx == null) idx = 0;
1426 if(idx >= list.length) return;
1427 var liId = list[idx].id();
1428 fieldmapper.standardRequest(
1429 ['open-ils.acq', 'open-ils.acq.lineitem.delete'],
1431 params: [openils.User.authtoken, liId],
1432 oncomplete: function(r) {
1433 self.removeLineitem(liId);
1434 self._deleteLiList(list, ++idx);
1440 this.editOrderMarc = function(li) {
1442 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
1443 to true in about:config */
1445 if(!openils.XUL.enableXPConnect()) return;
1447 if(openils.XUL.isXUL()) {
1448 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
1450 win = window.open('/xul/server/cat/marcedit.xul');
1454 record : {marc : li.marc()},
1456 label: 'Save Record', // XXX I18N
1457 func: function(xmlString) {
1459 fieldmapper.standardRequest(
1460 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
1462 params: [openils.User.authtoken, li],
1463 oncomplete: function(r) {
1464 openils.Util.readResponse(r);
1466 self.drawInfo(li.id())
1475 this._savePl = function(values) {
1477 var selected = this.getSelected( (values.which == 'all') );
1478 openils.Util.show('acq-lit-generic-progress');
1480 if(values.new_name) {
1481 openils.acq.Picklist.create(
1482 {name: values.new_name},
1484 self._updateLiList(id, selected, 0,
1486 location.href = oilsBasePath + '/eg/acq/picklist/view/' + id;
1490 } else if(values.existing_pl) {
1491 // update lineitems to use an existing picklist
1492 self._updateLiList(values.existing_pl, selected, 0,
1494 location.href = oilsBasePath + '/eg/acq/picklist/view/' + values.existing_pl;
1499 this._updateLiState = function(values, state) {
1501 var selected = this.getSelected( (values.which == 'all') );
1502 if(!selected.length) return;
1503 dojo.forEach(selected, function(li) {li.state(state);});
1504 self._updateLiList(null, selected, 0,
1505 // TODO consider inline updates for efficiency
1506 function() { location.href = location.href }
1510 this._updateLiList = function(pl, list, idx, oncomplete) {
1511 if(idx >= list.length) return oncomplete();
1513 if(pl != null) li.picklist(pl);
1514 litGenericProgress.update({maximum: list.length, progress: idx});
1515 new openils.acq.Lineitem({lineitem:li}).update(
1517 self._updateLiList(pl, list, ++idx, oncomplete);
1522 this._loadPLSelect = function() {
1523 if(this._plSelectLoaded) return;
1525 function handleResponse(r) {
1526 plList.push(r.recv().content());
1528 var method = 'open-ils.acq.picklist.user.retrieve';
1529 fieldmapper.standardRequest(
1530 ['open-ils.acq', method],
1532 params: [this.authtoken],
1533 onresponse: handleResponse,
1534 oncomplete: function() {
1535 self._plSelectLoaded = true;
1536 acqLitAddExistingSelect.store =
1537 new dojo.data.ItemFileReadStore({data:acqpl.toStoreData(plList)});
1538 acqLitAddExistingSelect.setValue();
1544 // grab the li-details for this lineitem, grab the linked copies and volumes, add them to the table
1545 this.showRealCopies = function(li) {
1546 while(this.realCopiesTbody.childNodes[0])
1547 this.realCopiesTbody.removeChild(this.realCopiesTbody.childNodes[0]);
1548 this.show('real-copies');
1550 var pcrud = new openils.PermaCrud({authtoken : this.authtoken});
1551 this.realCopyList = [];
1553 var tabIndex = 1000;
1556 acqLitSaveRealCopies.onClick = function() {
1557 self.saveRealCopies();
1560 this._fetchLineitem(li.id(),
1562 li = self.liCache[li.id()] = fullLi;
1566 id : li.lineitem_details().map(
1567 function(item) { return item.eg_copy_id() }
1572 onresponse : function(r) {
1573 var copy = openils.Util.readResponse(r);
1574 var volId = copy.call_number();
1575 var volume = self.volCache[volId];
1577 volume = self.volCache[volId] = pcrud.retrieve('acn', volId);
1579 self.addRealCopy(volume, copy, tabIndex++);
1587 this.addRealCopy = function(volume, copy, tabIndex) {
1588 var row = this.realCopiesRow.cloneNode(true);
1589 this.realCopyList.push(copy);
1593 ['owning_lib', 'location', 'circ_modifier', 'label', 'barcode'],
1596 var isvol = (field == 'owning_lib' || field == 'label');
1597 var widget = new openils.widget.AutoFieldWidget({
1599 fmObject : isvol ? volume : copy,
1600 parentNode : nodeByName(field, row),
1601 readOnly : (field != 'barcode'),
1604 var widgetDrawn = null;
1606 if(field == 'barcode') {
1608 widgetDrawn = function(w, ww) {
1609 var node = w.domNode;
1610 node.setAttribute('tabindex', ''+tabIndex);
1612 // on enter, select the next barcode input
1613 dojo.connect(w, 'onKeyDown',
1615 if(e.keyCode == dojo.keys.ENTER) {
1616 var ti = node.getAttribute('tabindex');
1617 var nextNode = dojo.query('[tabindex=' + String(Number(ti) + 1) + ']', self.realCopiesTbody)[0];
1618 if(nextNode) nextNode.select();
1623 dojo.connect(w, 'onChange',
1625 if(!val || val == copy.barcode()) return;
1626 copy.ischanged(true);
1632 if(self.realCopiesTbody.getElementsByTagName('TR').length == 0)
1637 widget.build(widgetDrawn);
1641 this.realCopiesTbody.appendChild(row);
1642 if(selectNode) selectNode.select();
1645 this.saveRealCopies = function() {
1646 var pcrud = new openils.PermaCrud({authtoken : this.authtoken});
1647 progressDialog.show(true);
1648 var list = this.realCopyList.filter(function(copy) { return copy.ischanged(); });
1649 pcrud.update(list, {oncomplete: function() {
1650 progressDialog.hide();