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.Tooltip');
8 dojo.require('dijit.ProgressBar');
9 dojo.require('openils.User');
10 dojo.require('openils.Util');
11 dojo.require('openils.acq.Lineitem');
12 dojo.require('openils.acq.PO');
13 dojo.require('openils.acq.Picklist');
14 dojo.require('openils.widget.AutoFieldWidget');
15 dojo.require('dojo.data.ItemFileReadStore');
16 dojo.require('openils.widget.ProgressDialog');
17 dojo.require('openils.PermaCrud');
18 dojo.require('openils.XUL');
20 dojo.requireLocalization('openils.acq', 'acq');
21 var localeStrings = dojo.i18n.getLocalization('openils.acq', 'acq');
22 const XUL_OPAC_WRAPPER = 'chrome://open_ils_staff_client/content/cat/opac.xul';
23 var li_exportable_attrs = ["issn", "isbn", "upc"];
25 var fundLabelFormat = [
26 '<span class="fund_${0}">${1} (${2})</span>', 'id', 'code', 'year'
28 var fundSearchFormat = ['${0} (${1})', 'code', 'year'];
30 function nodeByName(name, context) {
31 return dojo.query('[name='+name+']', context)[0];
35 var liDetailBatchFields = ['fund', 'owning_lib', 'location', 'collection_code', 'circ_modifier', 'cn_label'];
36 var liDetailFields = liDetailBatchFields.concat(['barcode', 'note']);
38 "stop": "color: #c00; font-weight: bold;",
39 "warning": "color: #c93;"
42 function AcqLiTable() {
49 this.haveFundClass = {}
50 this.fundBalanceState = {};
51 this.realDfaCache = {};
52 this.virtDfaCounts = {};
55 this.toggleState = false;
56 this.tbody = dojo.byId('acq-lit-tbody');
59 this.authtoken = openils.User.authtoken;
60 this.pcrud = new openils.PermaCrud();
61 this.rowTemplate = this.tbody.removeChild(dojo.byId('acq-lit-row'));
62 this.copyTbody = dojo.byId('acq-lit-li-details-tbody');
63 this.copyRow = this.copyTbody.removeChild(dojo.byId('acq-lit-li-details-row'));
64 this.copyBatchRow = dojo.byId('acq-lit-li-details-batch-row');
65 this.copyBatchWidgets = {};
66 this.liNotesTbody = dojo.byId('acq-lit-notes-tbody');
67 this.liNotesRow = this.liNotesTbody.removeChild(dojo.byId('acq-lit-notes-row'));
68 this.realCopiesTbody = dojo.byId('acq-lit-real-copies-tbody');
69 this.realCopiesRow = this.realCopiesTbody.removeChild(dojo.byId('acq-lit-real-copies-row'));
70 this._copy_fields_for_acqdf = ['owning_lib', 'location'];
72 dojo.connect(acqLitLiActionsSelector, 'onChange',
74 self.applySelectedLiAction(this.attr('value'))
75 acqLitLiActionsSelector.attr('value', '_');
78 acqLitCreatePoSubmit.onClick = function() {
79 if (self._confirmPoPrepaySituation()) {
80 acqLitPoCreateDialog.hide();
81 self._createPO(acqLitPoCreateDialog.getValues());
87 acqLitSavePlButton.onClick = function() {
88 acqLitSavePlDialog.hide();
89 self._savePl(acqLitSavePlDialog.getValues());
92 acqLitCancelLiStateButton.onClick = function() {
93 acqLitChangeLiStateDialog.hide();
95 acqLitSaveLiStateButton.onClick = function() {
96 acqLitChangeLiStateDialog.hide();
97 self._updateLiState(acqLitChangeLiStateDialog.getValues(), acqLitChangeLiStateDialog.attr('state'));
101 dojo.byId('acq-lit-select-toggle').onclick = function(){self.toggleSelect()};
102 dojo.byId('acq-lit-info-back-button').onclick = function(){self.show('list')};
103 dojo.byId('acq-lit-copies-back-button').onclick = function(){self.show('list')};
104 dojo.byId('acq-lit-notes-back-button').onclick = function(){self.show('list')};
105 dojo.byId('acq-lit-real-copies-back-button').onclick = function(){self.show('list')};
107 this.reset = function() {
108 while(self.tbody.childNodes[0])
109 self.tbody.removeChild(self.tbody.childNodes[0]);
115 this.setNext = function(handler) {
116 var link = dojo.byId('acq-lit-next');
118 dojo.style(link, 'visibility', 'visible');
119 link.onclick = handler;
121 dojo.style(link, 'visibility', 'hidden');
125 this.setPrev = function(handler) {
126 var link = dojo.byId('acq-lit-prev');
128 dojo.style(link, 'visibility', 'visible');
129 link.onclick = handler;
131 dojo.style(link, 'visibility', 'hidden');
135 this.show = function(div) {
136 openils.Util.hide('acq-lit-table-div');
137 openils.Util.hide('acq-lit-info-div');
138 openils.Util.hide('acq-lit-li-details');
139 openils.Util.hide('acq-lit-notes-div');
140 openils.Util.hide('acq-lit-real-copies-div');
143 openils.Util.show('acq-lit-table-div');
146 openils.Util.show('acq-lit-info-div');
149 openils.Util.show('acq-lit-li-details');
152 openils.Util.show('acq-lit-real-copies-div');
155 openils.Util.show('acq-lit-notes-div');
159 openils.Util.show(div);
163 this.hide = function() {
167 this.toggleSelect = function() {
169 dojo.forEach(self.selectors, function(i){i.checked = false});
171 dojo.forEach(self.selectors, function(i){i.checked = true});
172 self.toggleState = !self.toggleState;
176 /** @param all If true, assume all are selected */
177 this.getSelected = function(all) {
179 dojo.forEach(self.selectors,
182 selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
188 this.setRowAttr = function(td, liWrapper, field, type) {
189 var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
190 td.appendChild(document.createTextNode(val));
194 * Inserts a single lineitem into the growing table of lineitems
195 * @param {Object} li The lineitem object to insert
197 this.addLineitem = function(li, skip_final_placement) {
198 this.liCache[li.id()] = li;
200 // sort the lineitem notes on edit_time
201 if(!li.lineitem_notes()) li.lineitem_notes([]);
203 var liWrapper = new openils.acq.Lineitem({lineitem:li});
204 var row = self.rowTemplate.cloneNode(true);
205 row.setAttribute('li', li.id());
206 var tds = dojo.query('[attr]', row);
207 dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
208 dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
210 var isbn = liWrapper.findAttr('isbn', 'lineitem_marc_attr_definition');
212 // XXX media prefix for added content
213 dojo.query('[name=jacket]', row)[0].setAttribute('src', '/opac/extras/ac/jacket/small/' + isbn);
216 nodeByName("worksheet_link", row).href =
217 "/eg/acq/lineitem/worksheet/" + li.id();
219 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
220 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
221 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
223 this.updateLiNotesCount(li, row);
225 // show which PO this lineitem is a member of
226 if(li.purchase_order() && !this.isPO) {
228 this.poCache[li.purchase_order()] =
229 this.poCache[li.purchase_order()] ||
230 fieldmapper.standardRequest(
231 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
233 this.authtoken, li.purchase_order(), {
234 "flesh_price_summary": true,
235 "flesh_lineitem_count": true
238 if(po && !this.isMeta) {
239 openils.Util.show(nodeByName('po', row), 'inline');
240 var link = nodeByName('po_link', row);
241 link.setAttribute('href', oilsBasePath + '/acq/po/view/' + li.purchase_order());
242 link.innerHTML = 'PO: ' + po.name(); // TODO i18n
246 // show which picklist this lineitem is a member of
247 if(li.picklist() && (this.isPO || this.isMeta)) {
249 this.plCache[li.picklist()] =
250 this.plCache[li.picklist()] ||
251 fieldmapper.standardRequest(
252 ['open-ils.acq', 'open-ils.acq.picklist.retrieve'],
253 {params: [this.authtoken, li.picklist()]});
255 openils.Util.show(nodeByName('pl', row), 'inline');
256 var link = nodeByName('pl_link', row);
257 link.setAttribute('href', oilsBasePath + '/acq/picklist/view/' + li.picklist());
258 link.innerHTML = 'PL: '+pl.name(); // TODO i18n
262 var countNode = nodeByName('count', row);
263 var count = li.item_count() || 0;
264 if (typeof(this._copy_count_cb) == "function") {
265 this._copy_count_cb(li.id(), count);
267 countNode.innerHTML = count;
268 countNode.id = 'acq-lit-copy-count-label-' + li.id();
271 var priceInput = dojo.query('[name=price]', row)[0];
272 priceInput.value = li.estimated_unit_price() || '';
273 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
275 // show either "mark received" or "unreceive" as appropriate
276 this.updateLiState(li, row);
278 if (!skip_final_placement) {
279 self.tbody.appendChild(row);
280 self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
286 this.updateLiNotesCount = function(li, row) {
287 if (typeof(row) == "undefined")
288 row = dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
290 var has_notes = (li.lineitem_notes().filter(
291 function(o) { return Boolean (o.alert_text()); }
294 /* U+2691 is the code point for a filled-in flag character */
295 nodeByName("notes_alert_flag", row).innerHTML =
296 has_notes ? "⚑" : "";
297 nodeByName("noteslink", row).style.fontStyle =
298 has_notes ? "italic" : "normal";
299 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
302 /* XXX NOT related to _updateLiState(). rethink */
303 this.updateLiState = function(li, row) {
304 if (typeof(row) == "undefined")
305 row = dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
307 var recv_link = nodeByName("receive_link", row);
308 var unrecv_link = nodeByName("unreceive_link", row);
309 var real_copies_link = nodeByName("real_copies_link", row);
310 var holdings_maintenance_link = nodeByName("holdings_maintenance_link", row);
311 var state_cell = nodeByName("li_state", row);
313 if (li.state() == "cancelled") {
314 if (typeof li.cancel_reason() == "object") {
315 var holds_state = dojo.create(
317 "style": "border-bottom: 1px dashed #000;",
318 "innerHTML": li.state()
319 }, state_cell, "only"
323 "label": "<em>" + li.cancel_reason().label() +
324 "</em><br />" + li.cancel_reason().description(),
325 "connectId": [holds_state]
326 }, dojo.create("span", null, state_cell, "last")
329 state_cell.innerHTML = li.state(); // TODO i18n state labels
332 state_cell.innerHTML = li.state(); // TODO i18n state labels
336 /* handle row coloring for based on LI state */
337 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
338 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
340 /* handle links that appear/disappear based on whether LI is received */
345 openils.Util.hide(real_copies_link);
346 openils.Util.hide(unrecv_link);
347 openils.Util.show(recv_link, "inline");
348 recv_link.onclick = function() {
349 if (self.checkLiAlerts(li.id()))
350 self.issueReceive(li);
354 openils.Util.hide(recv_link);
355 openils.Util.show(unrecv_link, "inline");
356 unrecv_link.onclick = function() {
357 if (confirm(localeStrings.UNRECEIVE_LI))
358 self.issueReceive(li, /* rollback */ true);
360 // TODO we should allow editing before receipt, in which case the
361 // test should be "if 1 or more real (acp) copies exist
362 openils.Util.show(real_copies_link, "inline");
363 real_copies_link.onclick = function() {
364 self.showRealCopyEditUI(li);
366 openils.Util.show(holdings_maintenance_link, "inline");
367 holdings_maintenance_link.onclick = self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser' );
372 openils.Util.hide(recv_link);
373 openils.Util.hide(unrecv_link);
374 openils.Util.hide(real_copies_link);
378 this._setAlertStore = function() {
379 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
381 "data": acqliat.toStoreData(
383 "acqliat", {"id": {"!=": null}}
388 acqLitAlertAlertText.setValue(); /* make the store "live" */
389 acqLitAlertAlertText._store_ready = true;
393 * Draws and shows the lineitem notes pane
395 this.drawLiNotes = function(li) {
398 if (!acqLitAlertAlertText._store_ready)
399 this._setAlertStore();
402 li.lineitem_notes().sort(
404 if(a.edit_time() < b.edit_time()) return 1;
410 while(this.liNotesTbody.childNodes[0])
411 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
414 acqLitCreateNoteSubmit.onClick = function() {
415 var value = acqLitCreateNoteText.attr('value');
417 var note = new fieldmapper.acqlin();
420 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
423 note.lineitem(li.id());
425 self.updateLiNotes(li, note);
426 acqLitCreateNoteVendorPublic.attr("checked", false);
427 acqLitCreateNoteText.attr("value", "");
430 acqLitCreateAlertSubmit.onClick = function() {
431 if (!acqLitAlertAlertText.item) {
432 alert(localeStrings.ALERT_UNSELECTED);
436 var alert_text = new fieldmapper.acqliat().fromStoreItem(
437 acqLitAlertAlertText.item
439 var value = acqLitAlertNoteValue.attr("value") || "";
441 var note = new fieldmapper.acqlin();
443 note.lineitem(li.id());
445 note.alert_text(alert_text);
447 self.updateLiNotes(li, note);
450 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
454 * Draws a single lineitem note in the notes pane
456 this.addLiNote = function(li, note) {
457 if(note.isdeleted()) return;
459 var row = self.liNotesRow.cloneNode(true);
460 nodeByName("value", row).innerHTML = note.value();
461 var alert_node = nodeByName("alert_code", row);
462 if (note.alert_text()) {
463 alert_node.innerHTML = note.alert_text().code();
464 if (note.alert_text().description()) {
467 "connectId": [alert_node],
468 "label": note.alert_text().description()
469 }, dojo.create("span", null, alert_node, "after")
474 if (openils.Util.isTrue(note.vendor_public()))
475 nodeByName("vendor_public", row).innerHTML =
476 localeStrings.VENDOR_PUBLIC;
478 nodeByName("delete", row).onclick = function() {
479 note.isdeleted(true);
480 self.liNotesTbody.removeChild(row);
481 self.updateLiNotes(li);
484 if(note.edit_time()) {
485 nodeByName("edit_time", row).innerHTML =
486 dojo.date.locale.format(
487 dojo.date.stamp.fromISOString(note.edit_time()),
488 {formatLength:'short'});
491 self.liNotesTbody.appendChild(row);
495 * Updates any new/changed/deleted notes on the server
497 this.updateLiNotes = function(li, newNote) {
503 notes = li.lineitem_notes().filter(
505 if(note.ischanged() || note.isnew() || note.isdeleted())
511 if(notes.length == 0) return;
512 progressDialog.show();
514 fieldmapper.standardRequest(
515 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
517 params : [this.authtoken, notes],
518 onresponse : function(r) {
519 var resp = openils.Util.readResponse(r);
524 // remove the old changed notes
526 dojo.forEach(li.lineitem_notes(),
528 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
532 li.lineitem_notes(list);
535 progressDialog.hide();
536 self.updateLiNotesCount(li);
537 self.drawLiNotes(li);
541 progressDialog.update(resp);
542 var newnote = resp.note;
544 if(!newnote.isdeleted()) {
545 newnote.isnew(false);
546 newnote.ischanged(false);
547 li.lineitem_notes().push(newnote);
554 this.updateLiPrice = function(input, li) {
556 var price = input.value;
557 if(Number(price) == Number(li.estimated_unit_price())) return;
559 fieldmapper.standardRequest(
560 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
562 params : [this.authtoken, li.id(), price],
563 oncomplete : function(r) {
564 openils.Util.readResponse(r);
565 li.estimated_unit_price(price); // update local copy
571 this.removeLineitem = function(liId) {
572 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
573 delete this.liCache[liId];
574 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
577 this.drawInfo = function(liId) {
578 if (!this._isRelatedViewer) {
579 var d = dojo.byId("acq-lit-info-related");
580 if (!this.relCache[liId]) {
581 fieldmapper.standardRequest(
584 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
587 "params": [openils.User.authtoken, liId],
588 "onresponse": function(r) {
589 self.relCache[liId] = openils.Util.readResponse(r);
590 nodeByName("related_number", d).innerHTML =
593 self.relCache[liId] >1 ? "show" : "hide"
599 nodeByName("related_number", d).innerHTML = this.relCache[liId];
600 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
605 openils.acq.Lineitem.fetchAttrDefs(
607 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
612 this._fetchLineitem = function(liId, handler) {
614 var li = this.liCache[liId];
615 if(li && li.marc() && li.lineitem_details())
618 fieldmapper.standardRequest(
619 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve'],
622 params: [self.authtoken, liId, {
624 flesh_cancel_reason: true,
625 flesh_li_details: true,
626 flesh_fund_debit: true }],
628 oncomplete: function(r) {
629 var li = openils.Util.readResponse(r);
636 this._drawInfo = function(li) {
638 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
641 openils.Util.hide('acq-lit-marc-order-record-label');
642 openils.Util.hide(acqLitEditOrderMarc.domNode);
643 openils.Util.show('acq-lit-marc-real-record-label');
645 openils.Util.show('acq-lit-marc-order-record-label');
646 openils.Util.show(acqLitEditOrderMarc.domNode);
647 openils.Util.hide('acq-lit-marc-real-record-label');
650 this.drawMarcHTML(li);
651 this.infoTbody = dojo.byId('acq-lit-info-tbody');
654 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
655 while(this.infoTbody.childNodes[0])
656 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
658 if (!this._isRelatedViewer) {
659 for(var i = 0; i < li.attributes().length; i++) {
660 var attr = li.attributes()[i];
661 var row = this.infoRow.cloneNode(true);
663 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
664 var name = openils.acq.Lineitem.attrDefs[type].filter(
666 return (a.code() == attr.attr_name());
668 ).pop().description();
670 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
671 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
672 this.infoTbody.appendChild(row);
675 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
676 "/eg/acq/lineitem/related/" + li.id();
681 openils.Util.show('acq-lit-info-cat-link');
682 var link = dojo.byId('acq-lit-info-cat-link').getElementsByTagName('a')[0];
684 if(openils.XUL.isXUL()) {
686 link.setAttribute('href', 'javascript:void(0);');
687 link.onclick = this.generateMakeRecTab( li.eg_bib_id() );
690 var href = link.getAttribute('href');
692 link.setAttribute('href', href + li.eg_bib_id());
695 openils.Util.hide('acq-lit-info-cat-link');
699 this.generateMakeRecTab = function(bib_id,default_view) {
703 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
706 show_nav_buttons : true,
707 show_print_button : true,
708 opac_url : xulG.url_prefix(xulG.urls.opac_rdetail + '?r=' + bib_id),
709 default_view : default_view
715 this.drawMarcHTML = function(li) {
716 var params = [null, true, li.marc()];
718 params = [li.eg_bib_id(), true];
720 fieldmapper.standardRequest(
721 ['open-ils.search', 'open-ils.search.biblio.record.html'],
724 oncomplete: function(r) {
725 dojo.byId('acq-lit-marc-div').innerHTML =
726 openils.Util.readResponse(r);
732 this.drawCopies = function(liId) {
736 this.copyWidgetCache = {};
737 this.oldCopyWidgetCache = {};
738 this.virtDfaCounts = {};
739 this.realDfaCache = {};
742 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
743 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
744 acqLitCopyCountInput.attr('value', '0');
746 while(this.copyTbody.childNodes[0])
747 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
749 this._drawBatchCopyWidgets();
751 this._drawDistribApplied(liId);
753 this._fetchDistribFormulas(
755 openils.acq.Lineitem.fetchAttrDefs(
757 self._fetchLineitem(liId, function(li){self._drawCopies(li);});
764 this._saveDistribAppliedTemplates = function() {
765 if (!this._appliedDistribTemplate) {
766 this._appliedDistribTemplate =
767 dojo.byId("acq-lit-distrib-applied-tbody").
768 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
769 dojo.attr(this._appliedDistribTemplate, "id");
773 this._drawDistribApplied = function(liId) {
774 /* Build this table while hidden to prevent rendering artifacts */
775 openils.Util.hide("acq-lit-distrib-applied-tbody");
777 this._saveDistribAppliedTemplates();
779 /* Remove any rows in the table from previous populations */
780 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
781 forEach(dojo.destroy);
783 /* Unregister all dijits previously created (for some reason this isn't
784 * covered by the above destroy calls). */
785 dijit.registry.forEach(
786 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
789 /* Populate the table with our liId */
791 fieldmapper.standardRequest(
793 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
796 "params": [self.authtoken, liId],
797 "onresponse": function(r) {
798 var dfa = openils.Util.readResponse(r);
801 self.realDfaCache[dfa.id()] = dfa;
802 self._drawDistribAppliedUnit(dfa);
805 "oncomplete": function() {
806 /* Reveal built table */
809 "acq-lit-distrib-applied-tbody", "table-row-group"
817 this._drawDistribAppliedUnit = function(dfa) {
819 var row = dojo.query(
820 'tr[formula="' + dfa.formula().id() + '"]',
821 "acq-lit-distrib-applied-tbody"
826 row = dojo.clone(this._appliedDistribTemplate);
827 dojo.attr(row, "formula", dfa.formula().id());
828 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
831 var td = dojo.query("td", row)[0];
833 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
834 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
837 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
839 new dijit.form.Button(
841 "onClick": function() {
842 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
846 /* XXX I /cannot/ make the following work in as a CSS class
847 * for some reason. So frustrating... */
848 "style": function(id) {
850 "font-weight: bold; color: #c00;" :
852 }(dfa.id()) + "margin: 0 6px;display: inline;"
853 }, "dfa-button-" + dfa.id()
857 "connectId": ["dfa-button-" + dfa.id()],
858 "label": dojo.string.substitute(
859 localeStrings.DFA_TIP, dfa.id() > 0 ? [
860 openils.User.formalName(dfa.creator()),
861 dojo.date.locale.format(
862 dojo.date.stamp.fromISOString(dfa.create_time()),
863 {"formatLength":"short"}
865 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
867 }, "dfa-tip-" + dfa.id()
871 this.deleteDfa = function(dfa) {
872 if (dfa.id() > 0) { /* real */
873 this.pcrud.eliminate(
876 "oncomplete": function() {
877 self._removeDistribApplied(dfa.id());
878 delete self.realDfaCache[dfa.id()];
882 } else { /* virtual */
883 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
884 this.virtDfaCounts[dfa.formula().id()] = 0;
885 /* hasn't been saved yet, so no need to do anything server side */
886 this._removeDistribApplied(dfa.id());
891 this._removeDistribApplied = function(dfaId) {
892 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
893 dijit.registry.forEach(
894 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
896 this._removeDistribAppliedEmptyRows();
899 this._removeAllDistribAppliedVirtual = function() {
900 /* Unregister dijits */
901 dijit.registry.forEach(
902 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
904 this._removeDistribAppliedEmptyRows();
907 this._removeDistribAppliedEmptyRows = function() {
908 /* Remove any rows with no DFA at all */
909 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
911 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
917 * Insert a new row into the distribution formula selection form
919 this._addDistribFormulaRow = function() {
922 if (!self.distribForms) {
923 // no formulas, hide the form
924 openils.Util.hide('acq-lit-distrib-formula-tbody');
928 if(!this.distribFormulaTemplate)
929 this.distribFormulaTemplate =
930 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
932 var row = this.distribFormulaTemplate.cloneNode(true);
933 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
935 this.dfSelector = new dijit.form.FilteringSelect(
936 {"labelAttr": "dynLabel", "labelType": "html"},
937 nodeByName("selector", row)
939 this._updateFormulaStore();
940 this.dfSelector.fetchProperties =
941 {"sort": [{"attribute": "use_count", "descending": true}]};
943 var apply = new dijit.form.Button(
944 {"label": localeStrings.APPLY},
945 nodeByName('set_button', row)
948 var reset = new dijit.form.Button(
949 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
950 nodeByName("reset_button", row)
953 dojo.connect(apply, 'onClick',
955 var form_id = self.dfSelector.attr("value");
957 self._applyDistribFormula(form_id);
958 reset.attr("disabled", false);
962 dojo.connect(reset, 'onClick',
964 self.restoreCopyFieldsBeforeDF();
965 self.virtDfaCounts = {};
968 self._updateFormulaStore();
969 self._removeAllDistribAppliedVirtual();
970 reset.attr("disabled", "true");
977 * Applies a distrib formula to the current set of copies
979 this._applyDistribFormula = function(formula) {
982 formula = this.distribForms.filter(
983 function(form) { return form.id() == formula; }
986 var copyRows = dojo.query('tr', self.copyTbody);
988 if (this.dfeOffset >= copyRows.length) {
989 alert(localeStrings.OUT_OF_COPIES);
993 var entries_applied = 0;
995 var rowIndex = this.dfeOffset;
996 rowIndex < copyRows.length;
1000 var row = copyRows[rowIndex];
1001 var copy_id = row.getAttribute('copy_id');
1002 var copyWidgets = this.copyWidgetCache[copy_id];
1003 var entryIndex = this.dfeOffset;
1006 // find the correct entry for the current row
1007 dojo.forEach(formula.entries(),
1010 entryIndex += e.item_count();
1011 if(entryIndex > rowIndex)
1019 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
1020 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
1023 this.saveCopyFieldsBeforeDF(copy_id);
1024 this._copy_fields_for_acqdf.forEach(
1026 if(entry[field]()) {
1027 copyWidgets[field].attr('value', (entry[field]()));
1034 if (entries_applied) {
1035 this.virtDfaCounts[formula.id()] =
1036 ++(this.virtDfaCounts[formula.id()]) || 1;
1037 this._updateFormulaStore();
1038 this._drawDistribAppliedUnit(
1040 var dfa = new acqdfa();
1041 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
1044 this.dfeOffset += entries_applied;
1049 * This function updates the DF store for the dropdown so that use_counts
1050 * can reflect DF applications from this session before they're saved
1053 this._updateFormulaStore = function() {
1054 this.dfSelector.store = new dojo.data.ItemFileReadStore(
1056 "data": self._labelFormulasWithCounts(
1057 acqdf.toStoreData(self.distribForms)
1063 this.saveCopyFieldsBeforeDF = function(copy_id) {
1065 if (!this.oldCopyWidgetCache[copy_id]) {
1066 var copyWidgets = this.copyWidgetCache[copy_id];
1068 this.oldCopyWidgetCache[copy_id] = {};
1069 this._copy_fields_for_acqdf.forEach(
1071 self.oldCopyWidgetCache[copy_id][f] =
1072 copyWidgets[f].attr("value");
1078 this.restoreCopyFieldsBeforeDF = function() {
1080 for (var copy_id in this.oldCopyWidgetCache) {
1081 this._copy_fields_for_acqdf.forEach(
1083 self.copyWidgetCache[copy_id][f].attr(
1084 "value", self.oldCopyWidgetCache[copy_id][f]
1091 this._labelFormulasWithCounts = function(store_data) {
1092 for (var key in store_data.items) {
1093 var obj = store_data.items[key];
1094 obj.use_count = Number(obj.use_count); /* needed for sorting */
1096 if (this.virtDfaCounts[obj.id])
1097 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
1099 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
1100 obj.use_count + "]</span> " + obj.name;
1106 * This method formerly would not refetch the DF formulas if they'd been
1107 * loaded already, but now it always re-fetches, since use_count changes.
1109 this._fetchDistribFormulas = function(onload) {
1110 fieldmapper.standardRequest(
1112 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
1115 "params": [openils.User.authtoken],
1116 "oncomplete": function(r) {
1117 self.distribForms = openils.Util.readResponse(r);
1118 if(!self.distribForms || self.distribForms.length == 0) {
1119 self.distribForms = [];
1121 self._addDistribFormulaRow();
1128 this._drawBatchCopyWidgets = function() {
1129 var row = this.copyBatchRow;
1130 dojo.forEach(liDetailBatchFields,
1132 if(self.copyBatchRowDrawn) {
1133 self.copyBatchWidgets[field].attr('value', null);
1135 var widget = new openils.widget.AutoFieldWidget({
1138 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1139 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1140 searchFilter : (field == 'fund') ? {"active": "t"} : null,
1141 parentNode : dojo.query('[name='+field+']', row)[0],
1142 orgLimitPerms : ['CREATE_PICKLIST'],
1145 "labelType": (field == "fund") ? "html" : null
1147 noCache: (field == "fund"),
1152 if (field == "fund" && w.store)
1153 self._ensureCSSFundClasses(w.store);
1154 self.copyBatchWidgets[field] = w;
1157 if (field == "fund") {
1159 widget.widget, "onChange", function(val) {
1160 self._updateFundSelectorStyle(widget, val);
1167 this.copyBatchRowDrawn = true;
1170 this.batchCopyUpdate = function() {
1172 for(var k in this.copyWidgetCache) {
1173 var cache = this.copyWidgetCache[k];
1174 dojo.forEach(liDetailBatchFields, function(f) {
1175 var newval = self.copyBatchWidgets[f].attr('value');
1176 if(newval) cache[f].attr('value', newval);
1181 this._drawCopies = function(li) {
1184 // this button sets the total number of copies for a given lineitem
1185 acqLitAddCopyCount.onClick = function() {
1186 var count = acqLitCopyCountInput.attr('value');
1189 while(self.copyCount() < count)
1192 // delete rows if necessary
1193 var diff = self.copyCount() - count;
1195 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
1196 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
1197 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
1199 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1205 if(li.lineitem_details().length > 0) {
1206 dojo.forEach(li.lineitem_details(),
1208 self.addCopy(li, copy);
1216 this.copyCount = function() {
1218 for(var id in this.copyCache) {
1219 if(!this.copyCache[id].isdeleted())
1225 this.virtCopyId = -1;
1226 this.addCopy = function(li, copy) {
1227 var row = this.copyRow.cloneNode(true);
1228 this.copyTbody.appendChild(row);
1232 copy = new fieldmapper.acqlid();
1234 copy.id(this.virtCopyId--);
1235 copy.lineitem(li.id());
1238 this.copyCache[copy.id()] = copy;
1239 row.setAttribute('copy_id', copy.id());
1240 self.copyWidgetCache[copy.id()] = {};
1242 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1244 dojo.forEach(liDetailFields,
1247 if (field == "fund") {
1248 searchFilter = (copy.fund() ?
1249 {"-or": {"active": "t", "id": copy.fund()}} :
1252 searchFilter = null;
1254 var widget = new openils.widget.AutoFieldWidget({
1257 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1258 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1259 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1260 searchFilter : searchFilter,
1261 noCache: (field == "fund"),
1263 parentNode : dojo.query('[name='+field+']', row)[0],
1264 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
1265 readOnly : Boolean(copy.eg_copy_id())
1268 // make sure we capture the value from any async widgets
1270 if (field == "fund" && w.store)
1271 self._ensureCSSFundClasses(w.store);
1272 copy[field](ww.getFormattedValue())
1273 self.copyWidgetCache[copy.id()][field] = w;
1276 dojo.connect(widget.widget, 'onChange',
1278 if (field == "fund")
1279 self._updateFundSelectorStyle(widget, val);
1281 if (copy.isnew() || val != copy[field]()) {
1282 // prevent setting ischanged() automatically on widget load for existing copies
1283 copy[field](widget.getFormattedValue())
1284 copy.ischanged(true);
1291 this.updateLidState(copy, row);
1294 this._ensureCSSFundClass = function(id) {
1295 if (!this.fundStyleSheet) {
1297 "style", {"type": "text/css"},
1298 document.getElementsByTagName("head")[0], "last"
1300 this.fundStyleSheet = document.styleSheets[
1301 document.styleSheets.length - 1
1305 var cn = "fund_" + id;
1306 if (!this.haveFundClass[cn]) {
1307 fieldmapper.standardRequest(
1308 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
1310 "params": [openils.User.authtoken, id],
1312 "oncomplete": function(r) {
1313 r = openils.Util.readResponse(r);
1314 self.fundBalanceState[id] = r;
1316 if (r[0] /* stop */)
1317 style = fundStyles.stop;
1318 else if (r[1] /* warning */)
1319 style = fundStyles.warning;
1320 self.fundStyleSheet.insertRule(
1321 "." + cn + " { " + style + " }",
1322 self.fundStyleSheet.cssRules.length
1324 self.haveFundClass[cn] = true;
1331 this._ensureCSSFundClasses = function(store) {
1333 "query": {"id": "*"},
1334 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
1338 this._updateFundSelectorStyle = function(widget, fund_id) {
1339 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
1340 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
1343 this.updateLidState = function(copy, row) {
1344 if (typeof(row) == "undefined") {
1346 'tr[copy_id="' + copy.id() + '"]', this.copyTbody
1351 var recv_link = nodeByName("receive", row);
1352 var unrecv_link = nodeByName("unreceive", row);
1353 var del_link = nodeByName("delete", row);
1354 var cxl_link = nodeByName("cancel", row);
1355 var cxl_reason_link = nodeByName("cancel_reason", row);
1357 if (copy.cancel_reason()) {
1358 openils.Util.hide(del_link.parentNode);
1359 openils.Util.hide(recv_link);
1360 openils.Util.hide(unrecv_link);
1361 openils.Util.hide(cxl_link);
1363 /* XXX the following may leak memory in a long lived table: dijits may not get destroyed... not positive. revisit. */
1364 var holds_reason = dojo.create(
1366 "style": "border-bottom: 1px dashed #000;",
1367 "innerHTML": "Cancelled" /* XXX [sic] and i18n */
1368 }, cxl_reason_link, "only"
1372 "label": "<em>" + copy.cancel_reason().label() +
1373 "</em><br />" + copy.cancel_reason().description(),
1374 "connectId": [holds_reason]
1375 }, dojo.create("span", null, cxl_reason_link, "last")
1377 openils.Util.show(cxl_reason_link, "inline");
1378 } else if (this.isPO) {
1379 openils.Util.hide(del_link.parentNode);
1380 openils.Util.hide(cxl_reason_link);
1382 /* Avoid showing (un)receive links, cancel links, for virt copies */
1383 if (copy.id() > 0) {
1384 if(copy.recv_time()) {
1385 openils.Util.hide(cxl_link);
1386 openils.Util.hide(recv_link);
1387 openils.Util.show(unrecv_link, "inline");
1388 unrecv_link.onclick = function() {
1389 if (confirm(localeStrings.UNRECEIVE_LID))
1390 self.issueReceive(copy, /* rollback */ true);
1393 openils.Util.hide(unrecv_link);
1394 openils.Util.show(recv_link, "inline");
1395 openils.Util.show(cxl_link, "inline");
1396 recv_link.onclick = function() {
1397 if (self.checkLiAlerts(copy.lineitem()))
1398 self.issueReceive(copy);
1400 cxl_link.onclick = function() {
1401 self.cancelLid(copy.id());
1405 openils.Util.hide(cxl_link);
1406 openils.Util.hide(unrecv_link);
1407 openils.Util.hide(recv_link);
1410 openils.Util.hide(unrecv_link);
1411 openils.Util.hide(recv_link);
1412 openils.Util.hide(cxl_reason_link);
1414 del_link.onclick = function() { self.deleteCopy(row) };
1415 openils.Util.show(del_link.parentNode);
1419 this.cancelLid = function(lid_id) {
1420 lidCancelDialog._lid_id = lid_id;
1421 openils.Util.show(lidCancelDialog.domNode.parentNode);
1422 lidCancelDialog.show();
1423 if (!lidCancelDialog._prepared) {
1424 var widget = new openils.widget.AutoFieldWidget({
1425 "fmField": "cancel_reason",
1426 "fmClass": "acqlid",
1427 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
1428 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1433 acqLidCancelButton.onClick = function() {
1434 if (w.attr("value")) {
1435 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
1437 lidCancelDialog._lid_id,
1441 lidCancelDialog.hide();
1444 lidCancelDialog._prepared = true;
1450 this._cancelLid = function(lid_id, reason) {
1451 fieldmapper.standardRequest(
1452 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
1453 "params": [openils.User.authtoken, lid_id, reason],
1455 "onresponse": function(r) {
1456 if (r = openils.Util.readResponse(r)) {
1458 for (var id in r.lid) {
1459 /* actually this should only iterate once */
1460 self.copyCache[id].cancel_reason(
1461 r.lid[id].cancel_reason
1463 self.updateLidState(self.copyCache[id]);
1472 this._confirmAlert = function(li, lin) {
1474 dojo.string.substitute(
1475 localeStrings.CONFIRM_LI_ALERT, [
1476 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1477 "title", "lineitem_marc_attr_definition"
1479 lin.alert_text().code(),
1480 lin.alert_text().description() || "",
1487 this.checkLiAlerts = function(li_id) {
1488 var li = this.liCache[li_id];
1490 var alert_notes = li.lineitem_notes().filter(
1491 function(o) { return Boolean(o.alert_text()); }
1494 /* this is _intentionally_ not done in a call to forEach() ... */
1495 for (var i = 0; i < alert_notes.length; i++) {
1496 if (this.noteAcks[alert_notes[i].id()])
1498 else if (!this._confirmAlert(li, alert_notes[i]))
1501 this.noteAcks[alert_notes[i].id()] = true;
1507 this.deleteCopy = function(row) {
1508 var copy = this.copyCache[row.getAttribute('copy_id')];
1509 copy.isdeleted(true);
1511 delete this.copyCache[copy.id()];
1512 this.copyTbody.removeChild(row);
1515 this._virtDfaCountsAsList = function() {
1517 for (var key in this.virtDfaCounts) {
1518 for (var i = 0; i < this.virtDfaCounts[key]; i++)
1524 this.confirmBreachedCopyFunds = function(copies) {
1525 var stop = 0, warning = 0;
1529 var state = self.fundBalanceState[o.fund()];
1530 if (state[0] /* stop */)
1532 else if (state[1] /* warning */)
1539 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
1540 } else if (warning) {
1541 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
1546 this.saveCopyChanges = function(liId) {
1552 for(var id in this.copyCache) {
1553 var c = this.copyCache[id];
1554 if(!c.isdeleted()) total++;
1555 if(c.isnew() || c.ischanged() || c.isdeleted()) {
1556 if(c.id() < 0) c.id(null);
1562 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
1565 if (copies.length > 0) {
1566 if (!this.confirmBreachedCopyFunds(copies))
1569 if (typeof(this._copy_count_cb) == "function")
1570 this._copy_count_cb(liId, total);
1572 openils.Util.show("acq-lit-update-copies-progress");
1573 fieldmapper.standardRequest(
1574 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1576 params: [openils.User.authtoken, copies],
1577 onresponse: function(r) {
1578 var res = openils.Util.readResponse(r);
1579 litUpdateCopiesProgress.update(res);
1581 oncomplete: function() {
1582 self.drawCopies(liId);
1583 openils.Util.hide("acq-lit-update-copies-progress");
1589 var dfa_list = this._virtDfaCountsAsList();
1590 if (dfa_list.length > 0) {
1591 fieldmapper.standardRequest(
1593 "open-ils.acq.distribution_formula.record_application"],
1596 "params": [openils.User.authtoken, dfa_list, liId],
1597 "onresponse": function(r) {
1598 var res = openils.Util.readResponse(r);
1599 if (res && res.length < dfa_list.length)
1600 alert(localeStrings.DFA_NOT_ALL);
1604 this.virtDfaCounts = {};
1608 this._updateCreatePoPrepayCheckbox = function(prepay) {
1609 var prepay = openils.Util.isTrue(prepay);
1610 this._prepayRequiredByVendor = prepay;
1611 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
1614 this._confirmPoPrepaySituation = function() {
1615 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
1616 if (want_prepay != this._prepayRequiredByVendor) {
1619 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
1620 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
1627 this.applySelectedLiAction = function(action) {
1631 case 'delete_selected':
1632 this._deleteLiList(self.getSelected());
1635 case 'create_order':
1637 if(!this.createPoProviderSelector) {
1638 var widget = new openils.widget.AutoFieldWidget({
1639 fmField : 'provider',
1641 searchFilter: {"active": "t"},
1642 parentNode : dojo.byId('acq-lit-po-provider'),
1644 "onChange": function() {
1646 self._updateCreatePoPrepayCheckbox(
1647 this.item.prepayment_required
1654 function(w) { self.createPoProviderSelector = w; }
1658 if(!this.createPoAgencySelector) {
1659 var widget = new openils.widget.AutoFieldWidget({
1660 fmField : 'ordering_agency',
1662 parentNode : dojo.byId('acq-lit-po-agency'),
1663 orgLimitPerms : ['CREATE_PURCHASE_ORDER'],
1666 function(w) { self.createPoAgencySelector = w; }
1671 acqLitPoCreateDialog.show();
1674 case 'save_picklist':
1675 this._loadPLSelect();
1676 acqLitSavePlDialog.show();
1679 case 'selector_ready':
1681 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
1682 acqLitChangeLiStateDialog.show();
1693 case 'rollback_receive_po':
1694 this.rollbackPoReceive();
1697 case 'create_assets':
1698 this.createAssets();
1701 case 'export_attr_list':
1702 this.chooseExportAttr();
1705 case 'add_brief_record':
1707 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
1709 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
1713 case "cancel_lineitems":
1714 this.maybeCancelLineitems();
1719 this.createAssets = function() {
1720 if(!this.isPO) return;
1721 if(!confirm(localeStrings.CREATE_PO_ASSETS_CONFIRM)) return;
1722 this.show('acq-lit-progress-numbers');
1724 fieldmapper.standardRequest(
1725 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
1727 params: [this.authtoken, this.isPO],
1728 onresponse: function(r) {
1729 var resp = openils.Util.readResponse(r);
1730 self._updateProgressNumbers(resp, true);
1736 this.maybeCancelLineitems = function() {
1737 openils.Util.show("acq-lit-cancel-reason", "inline");
1738 if (!acqLitCancelLineitemsButton._prepared) {
1739 var widget = new openils.widget.AutoFieldWidget({
1740 "fmField": "cancel_reason",
1742 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
1743 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1748 acqLitCancelLineitemsButton.onClick = function() {
1749 if (w.attr("value")) {
1750 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
1751 self._cancelLineitems(w.attr("value"));
1753 openils.Util.hide("acq-lit-cancel-reason");
1756 acqLitCancelLineitemsButton._prepared = true;
1762 this._cancelLineitems = function(reason) {
1763 var id_list = this.getSelected().map(function(o) { return o.id(); });
1764 fieldmapper.standardRequest(
1765 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
1766 "params": [openils.User.authtoken, id_list, reason],
1768 "onresponse": function(r) {
1769 if (r = openils.Util.readResponse(r)) {
1771 for (var id in r.li) {
1772 self.liCache[id].state(r.li[id].state);
1773 self.liCache[id].cancel_reason(
1774 r.li[id].cancel_reason
1776 self.updateLiState(self.liCache[id]);
1779 if (r.lid && self.copyCache) {
1780 for (var id in r.lid) {
1781 if (self.copyCache[id]) {
1782 self.copyCache[id].cancel_reason(
1783 r.lid[id].cancel_reason
1785 self.updateLidState(self.copyCache[id]);
1795 this.chooseExportAttr = function() {
1796 if (!acqLitExportAttrSelector._li_setup) {
1798 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
1800 "data": acqliad.toStoreData(
1802 "acqliad", {"code": li_exportable_attrs}
1807 acqLitExportAttrSelector.setValue();
1808 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
1809 acqLitExportAttrSelector._li_setup = true;
1811 openils.Util.show("acq-lit-export-attr-holder", "inline");
1814 this.exportAttrList = function() {
1815 var attr_def = acqLitExportAttrSelector.item;
1816 var li_list = this.getSelected();
1817 var value_list = li_list.map(
1819 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1820 attr_def.code, "lineitem_marc_attr_definition"
1823 ).filter(function(attr) { return Boolean(attr); });
1825 if (value_list.length > 0) {
1826 if (value_list.length < li_list.length) {
1828 dojo.string.substitute(
1829 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
1836 openils.XUL.contentToFileSaveDialog(
1837 value_list.join("\n"),
1838 localeStrings.EXPORT_SAVE_DIALOG_TITLE
1844 alert(dojo.string.substitute(
1845 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
1849 openils.Util.hide("acq-lit-export-attr-holder");
1852 this.printPO = function() {
1853 if(!this.isPO) return;
1854 progressDialog.show(true);
1855 fieldmapper.standardRequest(
1856 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
1858 params: [this.authtoken, this.isPO, 'html'],
1859 oncomplete: function(r) {
1860 progressDialog.hide();
1861 var evt = openils.Util.readResponse(r);
1862 if(evt && evt.template_output()) {
1863 win = window.open('','', 'resizable,width=800,height=600,scrollbars=1');
1864 win.document.body.innerHTML = evt.template_output().data();
1872 this.receivePO = function() {
1873 if (!this.isPO) return;
1875 for (var id in this.liCache) {
1876 /* assumption: liCache reflects exactly the
1877 * set of LIs that belong to our PO */
1878 if (this.liCache[id].state() != "received" &&
1879 !this.checkLiAlerts(id)) return;
1882 this.show('acq-lit-progress-numbers');
1884 fieldmapper.standardRequest(
1885 ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
1887 params: [this.authtoken, this.isPO],
1888 onresponse : function(r) {
1889 var resp = openils.Util.readResponse(r);
1890 self._updateProgressNumbers(resp, true);
1896 this.issueReceive = function(obj, rollback) {
1897 /* (For now) there shall be no marking LI or LIDs (un)received
1898 * except from the actual "view PO" interface. */
1899 if (!this.isPO) return;
1902 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
1904 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
1906 progressDialog.show(true);
1907 fieldmapper.standardRequest(
1908 ["open-ils.acq", method], {
1910 "params": [this.authtoken, obj.id()],
1911 "onresponse": function(r) {
1912 self.handleReceive(openils.Util.readResponse(r));
1913 progressDialog.hide();
1920 * Handles the responses from receive and rollback ML calls.
1922 this.handleReceive = function(resp) {
1925 for (var li_id in resp.li) {
1926 for (var key in resp.li[li_id])
1927 self.liCache[li_id][key](resp.li[li_id][key]);
1928 self.updateLiState(self.liCache[li_id]);
1932 if (typeof(self.poUpdateCallback) == "function")
1933 self.poUpdateCallback(resp.po);
1936 for (var lid_id in resp.lid) {
1937 for (var key in resp.lid[lid_id])
1938 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
1939 self.updateLidState(self.copyCache[lid_id]);
1945 this.rollbackPoReceive = function() {
1946 if(!this.isPO) return;
1947 if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
1948 this.show('acq-lit-progress-numbers');
1950 fieldmapper.standardRequest(
1951 ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
1953 params: [this.authtoken, this.isPO],
1954 onresponse : function(r) {
1955 var resp = openils.Util.readResponse(r);
1956 self._updateProgressNumbers(resp, true);
1962 this._updateProgressNumbers = function(resp, reloadOnComplete) {
1964 dojo.byId('acq-pl-lit-li-processed').innerHTML = resp.li;
1965 dojo.byId('acq-pl-lit-lid-processed').innerHTML = resp.lid;
1966 dojo.byId('acq-pl-lit-debits-processed').innerHTML = resp.debits_accrued;
1967 dojo.byId('acq-pl-lit-bibs-processed').innerHTML = resp.bibs;
1968 dojo.byId('acq-pl-lit-indexed-processed').innerHTML = resp.indexed;
1969 dojo.byId('acq-pl-lit-copies-processed').innerHTML = resp.copies;
1970 if(resp.complete && reloadOnComplete)
1971 location.href = location.href;
1975 this._createPO = function(fields) {
1976 this.show('acq-lit-progress-numbers');
1977 var po = new fieldmapper.acqpo();
1978 po.provider(this.createPoProviderSelector.attr('value'));
1979 po.ordering_agency(this.createPoAgencySelector.attr('value'));
1980 po.prepayment_required(fields.prepayment_required[0] ? true : false);
1982 var selected = this.getSelected( (fields.create_from == 'all') );
1983 if(selected.length == 0) return;
1985 var max = selected.length * 3;
1988 fieldmapper.standardRequest(
1989 ['open-ils.acq', 'open-ils.acq.purchase_order.create'],
1992 openils.User.authtoken,
1995 lineitems : selected.map(function(li) { return li.id() }),
1996 create_assets : fields.create_assets[0],
2000 onresponse : function(r) {
2001 var resp = openils.Util.readResponse(r);
2002 self._updateProgressNumbers(resp);
2004 location.href = oilsBasePath + '/eg/acq/po/view/' + resp.purchase_order.id();
2010 this._deleteLiList = function(list, idx) {
2011 if(idx == null) idx = 0;
2012 if(idx >= list.length) return;
2013 var liId = list[idx].id();
2014 fieldmapper.standardRequest(
2015 ['open-ils.acq', 'open-ils.acq.lineitem.delete'],
2017 params: [openils.User.authtoken, liId],
2018 oncomplete: function(r) {
2019 self.removeLineitem(liId);
2020 self._deleteLiList(list, ++idx);
2026 this.editOrderMarc = function(li) {
2028 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
2029 to true in about:config */
2031 if(!openils.XUL.enableXPConnect()) return;
2033 if(openils.XUL.isXUL()) {
2034 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
2036 win = window.open('/xul/server/cat/marcedit.xul');
2040 record : {marc : li.marc()},
2042 label: 'Save Record', // XXX I18N
2043 func: function(xmlString) {
2045 fieldmapper.standardRequest(
2046 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
2048 params: [openils.User.authtoken, li],
2049 oncomplete: function(r) {
2050 openils.Util.readResponse(r);
2052 self.drawInfo(li.id())
2061 this._savePl = function(values) {
2063 var selected = this.getSelected( (values.which == 'all') );
2064 openils.Util.show('acq-lit-generic-progress');
2066 if(values.new_name) {
2067 openils.acq.Picklist.create(
2068 {name: values.new_name},
2070 self._updateLiList(id, selected, 0,
2072 location.href = oilsBasePath + '/eg/acq/picklist/view/' + id;
2076 } else if(values.existing_pl) {
2077 // update lineitems to use an existing picklist
2078 self._updateLiList(values.existing_pl, selected, 0,
2080 location.href = oilsBasePath + '/eg/acq/picklist/view/' + values.existing_pl;
2085 this._updateLiState = function(values, state) {
2087 var selected = this.getSelected( (values.which == 'all') );
2088 if(!selected.length) return;
2089 dojo.forEach(selected, function(li) {li.state(state);});
2090 self._updateLiList(null, selected, 0,
2091 // TODO consider inline updates for efficiency
2092 function() { location.href = location.href }
2096 this._updateLiList = function(pl, list, idx, oncomplete) {
2097 if(idx >= list.length) return oncomplete();
2099 if(pl != null) li.picklist(pl);
2100 litGenericProgress.update({maximum: list.length, progress: idx});
2101 new openils.acq.Lineitem({lineitem:li}).update(
2103 self._updateLiList(pl, list, ++idx, oncomplete);
2108 this._loadPLSelect = function() {
2109 if(this._plSelectLoaded) return;
2111 function handleResponse(r) {
2112 plList.push(r.recv().content());
2114 var method = 'open-ils.acq.picklist.user.retrieve';
2115 fieldmapper.standardRequest(
2116 ['open-ils.acq', method],
2118 params: [this.authtoken],
2119 onresponse: handleResponse,
2120 oncomplete: function() {
2121 self._plSelectLoaded = true;
2122 acqLitAddExistingSelect.store =
2123 new dojo.data.ItemFileReadStore({data:acqpl.toStoreData(plList)});
2124 acqLitAddExistingSelect.setValue();
2130 this.showRealCopyEditUI = function(li) {
2135 this._fetchLineitem(li.id(),
2137 li = self.liCache[li.id()] = fullLi;
2141 id : li.lineitem_details().map(
2142 function(item) { return item.eg_copy_id() }
2146 oncomplete : function(r) {
2148 var r_list = openils.Util.readResponse( r );
2149 for (var i = 0; i < r_list.length; i++) {
2150 var copy = r_list[i];
2151 var volId = copy.call_number();
2152 var volume = self.volCache[volId];
2154 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2156 copy.call_number(volume);
2157 copyList.push(copy);
2160 // If we need to, we can pass in an update_copy function to handle the update instead of volume_item_creator
2161 xulG.volume_item_creator( { 'existing_copies' : copyList } );
2164 alert('error in oncomplete: ' + E);
2175 this.saveRealCopies = function() {
2176 progressDialog.show(true);
2177 var list = this.realCopyList.filter(function(copy) { return copy.ischanged(); });
2178 this.pcrud.update(list, {oncomplete: function() {
2179 progressDialog.hide();
2184 // grab the li-details for this lineitem, grab the linked copies and volumes, add them to the table
2185 this.showRealCopies = function(li) {
2186 while(this.realCopiesTbody.childNodes[0])
2187 this.realCopiesTbody.removeChild(this.realCopiesTbody.childNodes[0]);
2188 this.show('real-copies');
2190 this.realCopyList = [];
2192 var tabIndex = 1000;
2195 acqLitSaveRealCopies.onClick = function() {
2196 self.saveRealCopies();
2199 this._fetchLineitem(li.id(),
2201 li = self.liCache[li.id()] = fullLi;
2205 id : li.lineitem_details().map(
2206 function(item) { return item.eg_copy_id() }
2211 onresponse : function(r) {
2212 var copy = openils.Util.readResponse(r);
2213 var volId = copy.call_number();
2214 var volume = self.volCache[volId];
2216 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2218 self.addRealCopy(volume, copy, tabIndex++);
2226 this.addRealCopy = function(volume, copy, tabIndex) {
2227 var row = this.realCopiesRow.cloneNode(true);
2228 this.realCopyList.push(copy);
2232 ['owning_lib', 'location', 'circ_modifier', 'label', 'barcode'],
2235 var isvol = (field == 'owning_lib' || field == 'label');
2236 var widget = new openils.widget.AutoFieldWidget({
2238 fmObject : isvol ? volume : copy,
2239 parentNode : nodeByName(field, row),
2240 readOnly : (field != 'barcode'),
2243 var widgetDrawn = null;
2245 if(field == 'barcode') {
2247 widgetDrawn = function(w, ww) {
2248 var node = w.domNode;
2249 node.setAttribute('tabindex', ''+tabIndex);
2251 // on enter, select the next barcode input
2252 dojo.connect(w, 'onKeyDown',
2254 if(e.keyCode == dojo.keys.ENTER) {
2255 var ti = node.getAttribute('tabindex');
2256 var nextNode = dojo.query('[tabindex=' + String(Number(ti) + 1) + ']', self.realCopiesTbody)[0];
2257 if(nextNode) nextNode.select();
2262 dojo.connect(w, 'onChange',
2264 if(!val || val == copy.barcode()) return;
2265 copy.ischanged(true);
2271 if(self.realCopiesTbody.getElementsByTagName('TR').length == 0)
2276 widget.build(widgetDrawn);
2280 this.realCopiesTbody.appendChild(row);
2281 if(selectNode) selectNode.select();