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('dojox.timing.doLater');
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.widget.PCrudAutocompleteBox");
18 dojo.require('dijit.form.ComboBox');
19 dojo.require('openils.CGI');
21 if (!localeStrings) { /* we can do this because javascript doesn't have block scope */
22 dojo.requireLocalization('openils.acq', 'acq');
23 var localeStrings = dojo.i18n.getLocalization('openils.acq', 'acq');
25 const XUL_OPAC_WRAPPER = 'chrome://open_ils_staff_client/content/cat/opac.xul';
26 var li_exportable_attrs = ["issn", "isbn", "upc"];
28 var fundLabelFormat = [
29 '<span class="fund_${0}">${1} (${2})</span>', 'id', 'code', 'year'
31 var fundSearchFormat = ['${0} (${1})', 'code', 'year'];
33 function nodeByName(name, context) {
34 return dojo.query('[name='+name+']', context)[0];
37 // for caching linked users. e.g. lineitem_detail.receiver
40 var liDetailBatchFields = ['fund', 'owning_lib', 'location', 'collection_code', 'circ_modifier', 'cn_label'];
41 var liDetailFields = liDetailBatchFields.concat(['barcode', 'note']);
43 "stop": "color: #c00; font-weight: bold;",
44 "warning": "color: #c93;"
48 * We're not using 'approved' today, but there is API support for it.
49 * I believe it's been replaced by "order-ready".
50 * LIs go new => selector-ready => order-ready/approved => pending-order =>
51 * on-order => received. 'cancelled' can pop up anywhere.
54 var li_pre_po_states = ["new", "selector-ready", "order-ready", "approved"];
55 var li_post_po_states = ["pending-order", "on-order", "received", "cancelled"];
56 var li_active_states = li_pre_po_states.concat(li_post_po_states);
58 function AcqLiTable() {
65 this.haveFundClass = {}
66 this.fundBalanceState = {};
67 this.realDfaCache = {};
68 this.virtDfaCounts = {};
71 this.claimEligibleLidByLi = {};
72 this.claimEligibleLid = {};
73 this.toggleState = false;
74 this.tbody = dojo.byId('acq-lit-tbody');
77 this.authtoken = openils.User.authtoken;
78 this.pcrud = new openils.PermaCrud();
79 this.rowTemplate = this.tbody.removeChild(dojo.byId('acq-lit-row'));
80 this.copyTbody = dojo.byId('acq-lit-li-details-tbody');
81 this.copyRow = this.copyTbody.removeChild(dojo.byId('acq-lit-li-details-row'));
82 this.copyBatchRow = dojo.byId('acq-lit-li-details-batch-row');
83 this.copyBatchWidgets = {};
84 this.liNotesTbody = dojo.byId('acq-lit-notes-tbody');
85 this.liNotesRow = this.liNotesTbody.removeChild(dojo.byId('acq-lit-notes-row'));
86 this.realCopiesTbody = dojo.byId('acq-lit-real-copies-tbody');
87 this.realCopiesRow = this.realCopiesTbody.removeChild(dojo.byId('acq-lit-real-copies-row'));
88 this._copy_fields_for_acqdf = ['owning_lib', 'location', 'fund', 'circ_modifier', 'collection_code'];
89 this.skipInitialEligibilityCheck = false;
90 this.claimDialog = new ClaimDialogManager(
91 liClaimDialog, finalClaimDialog, this.claimEligibleLidByLi,
92 function(li) { /* callback that fires when claims are made */
93 self.fetchClaimInfo(li.id(), /* force update */ true);
96 this.vlAgent = new VLAgent();
98 if (dojo.byId('acq-lit-apply-idents')) {
99 dojo.byId('acq-lit-apply-idents').onclick = function() {
100 self.applyOrderIdentValues();
104 this.focusLineitem = new openils.CGI().param('focus_li');
106 // capture the inline copy display wrapper and row template
107 this.inlineCopyContainer =
108 this.tbody.removeChild(dojo.byId('acq-inline-copies-row'));
110 '[name=acq-li-inline-copies-tbody]', this.inlineCopyContainer)[0];
111 this.inlineCopyTemplate = tb.removeChild(
112 dojo.query('[name=acq-li-inline-copies-template]', tb)[0]);
113 this.inlineNoCopies = tb.removeChild(
114 dojo.query('[name=acq-li-inline-copies-none]', tb)[0]);
116 // list of LI IDs that should be refreshed at next display time
117 this.inlineCopiesNeedingRefresh = [];
119 dojo.byId("acq-lit-li-actions-selector").onchange = function() {
120 self.applySelectedLiAction(this.options[this.selectedIndex].value);
121 this.selectedIndex = 0;
124 acqLitCreatePoSubmit.onClick = function() {
125 if (!self.createPoProviderSelector.attr("value") ||
126 !self.createPoAgencySelector.attr("value")) {
127 alert(localeStrings.CREATE_PO_INVALID);
129 } else if (self._confirmPoPrepaySituation()) {
130 acqLitPoCreateDialog.hide();
131 self._createPO(acqLitPoCreateDialog.getValues());
137 acqLitSavePlButton.onClick = function() {
138 acqLitSavePlDialog.hide();
139 self._savePl(acqLitSavePlDialog.getValues());
142 acqLitCancelLiStateButton.onClick = function() {
143 acqLitChangeLiStateDialog.hide();
145 acqLitSaveLiStateButton.onClick = function() {
146 acqLitChangeLiStateDialog.hide();
147 var state = acqLitChangeLiStateDialog.attr('state');
148 var state_filter = ['new'];
149 if (state == 'order-ready')
150 state_filter.push('selector-ready');
152 acqLitChangeLiStateDialog.getValues(), state, state_filter);
156 dojo.byId('acq-lit-select-toggle').onclick = function(){self.toggleSelect()};
157 dojo.byId('acq-inline-copies-toggle').onclick = function(){self.toggleInlineCopies()};
158 dojo.byId('acq-lit-info-back-button').onclick = function(){self.show('list')};
159 dojo.byId('acq-lit-copies-back-button').onclick = function(){self.show('list')};
160 dojo.byId('acq-lit-notes-back-button').onclick = function(){self.show('list')};
161 dojo.byId('acq-lit-real-copies-back-button').onclick = function(){self.show('list')};
163 this.afwCopyFieldArgs = function(field, perms) {
167 "labelFormat": (field == 'fund') ? fundLabelFormat : null,
168 "searchFormat": (field == 'fund') ? fundSearchFormat : null,
169 "searchFilter": (field == 'fund') ? {"active": "t"} : null,
170 "orgLimitPerms": [perms],
173 "labelType": (field == "fund") ? "html" : null
175 "noCache": (field == "fund"),
180 /* This is the "new" batch updater that sits atop all lineitems. It does
181 * use this.afwCopyFieldArgs() to borrow a little common code from the
182 * "old" batch updater atop the copy details view. */
183 this.initBatchUpdater = function(disabled_fields) {
184 openils.Util.show("acq-batch-update", "table");
186 if (!dojo.isArray(disabled_fields)) disabled_fields = [];
188 /* Note that this will directly contain dijits, not the AutoWidget
190 this.batchUpdateWidgets = {};
192 this.batchUpdateWidgets.item_count = new dijit.form.TextBox(
194 "style": {"width": "3em"},
196 dojo.indexOf(disabled_fields, "item_count") != -1
202 (new openils.widget.AutoFieldWidget({
204 "selfReference": true,
205 "dijitArgs": { "required": false },
207 "parentNode": "acq-bu-distribution_formula"
210 dojo.style(w.domNode, {"width": "12em"});
211 /* dijitArgs to AutoFieldWidget won't work for 'disabled' */
214 dojo.indexOf(disabled_fields, "distribution_formula") != -1
216 self.batchUpdateWidgets.distribution_formula = w;
220 function buildOneBatchWidget(field, args) {
221 (new openils.widget.AutoFieldWidget(args)).build(
223 if (field == "fund") {
225 w, "onChange", function(val) {
226 self._updateFundSelectorStyle(aw, val);
230 self._ensureCSSFundClasses(w.store);
233 dojo.style(w.domNode, {"width": "10em"});
236 dojo.indexOf(disabled_fields, field) != -1
238 self.batchUpdateWidgets[field] = w;
244 ["owning_lib","location","collection_code","circ_modifier","fund"],
246 var args = self.afwCopyFieldArgs(field,"CREATE_PURCHASE_ORDER");
247 args.parentNode = dojo.byId("acq-bu-" + field);
249 if (field == 'fund') {
250 // The list of funds can be huge. Before fetching
251 // funds for PO modification, see where the user has
252 // perms and limit the retreived funds accordingly.
253 // Note: this code only runs once per page load, so
254 // no caching is required.
255 new openils.User().getPermOrgList(
256 ['CREATE_PURCHASE_ORDER', 'MANAGE_FUND'],
258 args.searchFilter.org = orgs;
259 buildOneBatchWidget(field, args);
261 true, true // descendants, id_list
266 buildOneBatchWidget(field, args);
270 acqBatchUpdateApply.onClick = function() {
271 var li_id_list = self.getSelected(false, null, true /* id list */);
272 if (!li_id_list.length) {
273 alert(localeStrings.NO_LI_TO_UPDATE);
277 progressDialog.show(true);
278 progressDialog.attr("title", localeStrings.LI_BATCH_UPDATE);
279 progressDialog.update({"maximum": li_id_list.length,"progress": 0});
283 var params = [ self.authtoken, {"lineitems": li_id_list},
284 self.batchUpdateChanges(), self.batchUpdateFormula() ];
285 console.log("batch update params: " + dojo.toJson(params));
287 fieldmapper.standardRequest(
288 ["open-ils.acq", "open-ils.acq.lineitem.batch_update"], {
291 "onresponse": function(r) {
292 if ((r = openils.Util.readResponse(r))) { // assignment
293 progressDialog.update({"progress": ++count});
295 progressDialog.hide();
296 progressDialog.attr("title", "");
299 "oncomplete": function() {
300 /* XXX Is the last call to onresponse guaranteed to
301 * finish before oncomplete is fired? */
302 if (count != li_id_list.length) {
303 console.error("lineitem batch update operation failed");
304 progressDialog.hide();
305 progressDialog.attr("title", "");
307 location.href = location.href;
315 this.batchUpdateChanges = function() {
319 openils.Util.objectProperties(this.batchUpdateWidgets),
321 if (k == "distribution_formula") return; /* handled elsewhere */
322 if (self.batchUpdateWidgets[k].attr("disabled")) return;
324 /* It's important that a value of "" should mean that a field
325 * doesn't get used in the arguments to the batch updater API,
326 * but 0 should mean an actual 0. */
327 var value = self.batchUpdateWidgets[k].attr("value");
336 this.batchUpdateFormula = function() {
337 if (this.batchUpdateWidgets.distribution_formula.attr("disabled")) {
341 this.batchUpdateWidgets.distribution_formula.attr("value") ||
347 this.reset = function(keep_selectors) {
348 while(self.tbody.childNodes[0])
349 self.tbody.removeChild(self.tbody.childNodes[0]);
357 this.setNext = function(handler) {
358 var link = dojo.byId('acq-lit-next');
360 dojo.style(link, 'visibility', 'visible');
361 link.onclick = handler;
363 dojo.style(link, 'visibility', 'hidden');
367 this.setPrev = function(handler) {
368 var link = dojo.byId('acq-lit-prev');
370 dojo.style(link, 'visibility', 'visible');
371 link.onclick = handler;
373 dojo.style(link, 'visibility', 'hidden');
377 this.enableActionsDropdownOptions = function(mask) {
378 /* 'mask' is probably a misnomer the way I'm using it, but it needs to
379 * be one of pl,po,ao,gs,vp, or fs. */
380 dojo.query("option", "acq-lit-li-actions-selector").forEach(
382 var opt_mask = dojo.attr(option, "mask");
384 /* For each <option> element, an empty or non-existent mask
385 * attribute, a mask attribute of "*", or a mask attribute that
386 * matches this method's argument should result in that
387 * option's being enabled. */
389 option, "disabled", !(
392 opt_mask.search(mask) != -1
400 * Ensures this.focusLineitem is in view and causes a brief
401 * border around the lineitem to come to life then fade.
403 this.focusLi = function() {
404 if (!this.focusLineitem) return;
406 // set during addLineitem()
407 var node = dojo.byId('li-title-ref-' + this.focusLineitem);
409 // LI may not yet be rendered
412 // prevent numerous re-focuses
413 this.focusLineitem = null;
415 // causes the full row to be visible
416 dijit.scrollIntoView(node);
419 dojo.query('[attr=title]', node)[0].focus();
421 dojo.require('dojox.fx');
425 dojox.fx.highlight({color : '#BB4433', node : node, duration : 2000}).play();
430 this.show = function(div) {
431 openils.Util.hide('acq-lit-table-div');
432 openils.Util.hide('acq-lit-info-div');
433 openils.Util.hide('acq-lit-li-details');
434 openils.Util.hide('acq-lit-notes-div');
435 openils.Util.hide('acq-lit-real-copies-div');
436 openils.Util.hide('acq-lit-asset-creator');
439 openils.Util.show('acq-lit-table-div');
441 this.refreshInlineCopies();
444 openils.Util.show('acq-lit-info-div');
447 openils.Util.show('acq-lit-li-details');
450 openils.Util.show('acq-lit-real-copies-div');
453 openils.Util.show('acq-lit-notes-div');
455 case 'asset-creator':
456 openils.Util.show('acq-lit-asset-creator');
460 openils.Util.show(div);
464 this.hide = function() {
468 this.toggleSelect = function() {
470 dojo.forEach(self.selectors, function(i){i.checked = false});
472 dojo.forEach(self.selectors, function(i){i.checked = true});
473 self.toggleState = !self.toggleState;
477 this.getAll = function(callback, id_only, state) {
478 /* For some uses of the li table, we may not really know about "all"
479 * the lineitems that the user thinks we know about. If we're a paged
480 * picklist, for example, we only know about the lineitems we've
481 * displayed, but not necessarily all the lineitems on the picklist.
482 * So we reach out to pcrud to inform us.
483 * state: string/array. only lineitems in one of these states are
484 * included in the final result set. Not currently supported for
488 var oncomplete = function(r) {
489 var id_list = openils.Util.readResponse(r);
493 self.fetchLineitemsById(id_list, callback);
497 var search = {"picklist": this.isPL};
498 if (state) search.state = state;
501 "id_list": true, /* sic, even if id_only */
503 "oncomplete": oncomplete
507 } else if (this.isPO) {
508 var search = {"purchase_order": this.isPO};
509 if (state) search.state = state;
514 "oncomplete": oncomplete
518 } else if (this.isUni && this.pager) {
519 this.pager.getAllLineitemIDs(oncomplete);
523 /* If execution reaches this point, we don't need or can't perform
524 * any special tricks to find out the "real" list of "all" lineitems
525 * in this context, so we fall back to the old method.
527 callback(this.getSelected(true, null, id_only, state));
530 /** @param all If true, assume all are selected */
531 this.getSelected = function(
533 callback /* If you want a "good" idea of "all" lineitems, you must
534 provide a callback that accepts an array parameter, rather than
535 relying on the return value of this method itself. */,
539 console.log("getSelected states = " + state);
541 return this.getAll(callback, id_only, state);
543 var indices = {}; /* use to uniqify. needed in paging situations. */
544 dojo.forEach(this.selectors,
547 indices[i.parentNode.parentNode.getAttribute('li')] = true;
551 var result = openils.Util.objectProperties(indices);
553 // caller provided a lineitem state filter. remove IDs for lineitems
554 // not in the selected state.
557 if (!dojo.isArray(state)) state = [state];
558 dojo.forEach(result, function(liId) {
559 console.log('filter LI state ' + self.liCache[liId].state());
560 if (state.indexOf(self.liCache[liId].state()) >= 0)
567 result = result.map(function(liId) { return self.liCache[liId]; });
575 this.setRowAttr = function(td, liWrapper, field, type) {
576 var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
577 td.appendChild(document.createTextNode(val));
580 this.setClaimPolicyControl = function(li, row) {
581 if (!self._claimPolicyPickerLoading) {
582 self._claimPolicyPickerLoading = true;
584 new openils.widget.AutoFieldWidget({
585 "parentNode": "acq-lit-li-claim-policy",
587 "selfReference": true,
588 "dijitArgs": {"required": true}
590 function(w) { self.claimPolicyPicker = w; }
594 /* dojox.timing.doLater() is the best thing ever. Resource not yet
595 * ready? Just repeat my whole method when it is. */
596 if (dojox.timing.doLater(self.claimPolicyPicker)) {
600 row = self._findLiRow(li);
602 if (li.claim_policy()) {
603 /* This Dojo data dance is necessary to get a whole fieldmapper
604 * object based on a claim policy ID, since we alreay have the
605 * widget thing loaded with all that data, and can thereby
606 * avoid another request to the server. */
607 self.claimPolicyPicker.store.fetchItemByIdentity({
608 "identity": li.claim_policy(),
609 "onItem": function(a) {
610 var policy = (new acqclp()).fromStoreItem(a);
611 var span = nodeByName("claim_policy", row);
612 var inner = nodeByName("claim_policy_name", row);
614 openils.Util.show(span, "inline");
615 inner.innerHTML = policy.name();
617 "onError": function(e) {
622 openils.Util.hide(nodeByName("claim_policy", row));
623 nodeByName("claim_policy_name", row).innerHTML = "";
628 this.fetchClaimInfo = function(liId, force, callback, row) {
630 liId, function(full) {
631 self.liCache[full.id()] = full;
632 self.checkClaimEligibility(full, callback, row);
637 // fetch an updated copy of the lineitem
638 // and add it back to the lineitem table
639 this.refreshLineitem = function(li, focus) {
641 this._fetchLineitem(li.id(),
644 self.focusLineitem = li.id();
646 self.focusLineitem = null;
648 var row = dojo.query('[li='+li.id()+']', self.tbody)[0];
649 var nextSibling = row.nextSibling;
650 self.tbody.removeChild(row);
651 self.addLineitem(newLi, false, nextSibling);
657 * Inserts a single lineitem into the growing table of lineitems
658 * @param {Object} li The lineitem object to insert
660 this.addLineitem = function(li, skip_final_placement, nextSibling) {
661 this.liCache[li.id()] = li;
663 // insert the row right away so that final order isn't
664 // dependent on how long subsequent async request take
665 // for a given line item
666 var row = self.rowTemplate.cloneNode(true);
667 if (!skip_final_placement) {
669 // either no nextSibling was provided or it was null
670 // meaning the row was already at the end of the table
671 self.tbody.appendChild(row);
673 self.tbody.insertBefore(row, nextSibling);
677 self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
679 // sort the lineitem notes on edit_time
680 if(!li.lineitem_notes()) li.lineitem_notes([]);
682 var liWrapper = new openils.acq.Lineitem({lineitem:li});
683 row.setAttribute('li', li.id());
684 var tds = dojo.query('[attr]', row);
685 dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
686 dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
688 // so we can scroll to it later
689 dojo.query('[name=bib-info-cell]', row)[0].id = 'li-title-ref-' + li.id();
692 liWrapper.findAttr("isbn", "lineitem_marc_attr_definition") ||
693 liWrapper.findAttr("upc", "lineitem_marc_attr_definition");
695 // XXX media prefix for added content
697 nodeByName("jacket", row).setAttribute(
698 "src", "/opac/extras/ac/jacket/small/" + identifier
702 nodeByName("liid", row).innerHTML += li.id();
705 openils.Util.show(nodeByName('catalog', row), 'inline');
706 nodeByName("catalog_link", row).onclick = this.generateMakeRecTab(li.eg_bib_id());
708 openils.Util.show(nodeByName('link_to_catalog', row), 'inline');
709 nodeByName("link_to_catalog_link", row).onclick = function() { self.drawBibFinder(li) };
712 if (li.queued_record()) {
713 this.pcrud.retrieve('vqbr', li.queued_record(),
715 oncomplete : function(r) {
716 var qrec = openils.Util.readResponse(r);
717 openils.Util.show(nodeByName('queue', row), 'inline');
718 var link = nodeByName("queue_link", row);
719 link.onclick = function() {
720 // open a new tab to the vandelay queue for this record
721 openils.XUL.newTabEasy(
722 oilsBasePath + '/vandelay/vandelay?qtype=bib&qid=' + qrec.queue()
730 nodeByName("worksheet_link", row).href =
731 oilsBasePath + "/acq/lineitem/worksheet/" + li.id() +
732 '?source=' + encodeURIComponent(location.pathname + location.search)
734 nodeByName("show_requests_link", row).href =
735 oilsBasePath + "/acq/picklist/user_request?lineitem=" + li.id() +
736 '?source=' + encodeURIComponent(location.pathname + location.search)
738 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
739 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
740 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
741 dojo.query('[name=expand_inline_copies]', row)[0].onclick =
742 function() {self.drawInlineCopies(li.id())};
744 this.drawOrderIdentSelector(li, row);
746 if (!this.skipInitialEligibilityCheck)
750 function(full) { self.setClaimPolicyControl(full, row) },
754 this.updateLiNotesCount(li, row);
756 // show which PO this lineitem is a member of
757 if(li.purchase_order() && !this.isPO) {
759 this.poCache[li.purchase_order()] =
760 this.poCache[li.purchase_order()] ||
761 fieldmapper.standardRequest(
762 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
764 this.authtoken, li.purchase_order(), {
765 "flesh_price_summary": true,
766 "flesh_provider" : true,
767 "flesh_lineitem_count": true
770 if(po && !this.isMeta) {
771 openils.Util.show(nodeByName('po', row), 'inline');
772 var link = nodeByName('po_link', row);
773 link.setAttribute('href', oilsBasePath +
774 '/acq/po/view/' + li.purchase_order() +
775 '?focus_li=' + li.id() +
776 '&source=' + encodeURIComponent(location.pathname + location.search)
778 link.innerHTML += po.name();
780 openils.Util.show(nodeByName('pro', row), 'inline');
781 link = nodeByName('pro_link', row);
782 link.setAttribute('href', oilsBasePath + '/conify/global/acq/provider/' + po.provider().id())
783 link.innerHTML += po.provider().code();
787 // show which picklist this lineitem is a member of
788 if(li.picklist() && (this.isPO || this.isMeta || this.isUni)) {
790 this.plCache[li.picklist()] =
791 this.plCache[li.picklist()] ||
792 fieldmapper.standardRequest(
793 ['open-ils.acq', 'open-ils.acq.picklist.retrieve.authoritative'],
794 {params: [this.authtoken, li.picklist()]});
796 if (pl.name() == "") {
797 openils.Util.show(nodeByName("bib_origin", row), "inline");
801 openils.Util.show(nodeByName('pl', row), 'inline');
802 var link = nodeByName('pl_link', row);
803 link.setAttribute('href', oilsBasePath +
804 '/acq/picklist/view/' + li.picklist() +
805 '?focus_li=' + li.id() +
806 '&source=' + encodeURIComponent(location.pathname + location.search)
808 link.innerHTML += pl.name();
813 var countNode = nodeByName('count', row);
814 var count = li.item_count() || 0;
815 if (typeof(this._copy_count_cb) == "function") {
816 this._copy_count_cb(li.id(), count);
818 countNode.innerHTML = count;
819 countNode.id = 'acq-lit-copy-count-label-' + li.id();
822 var priceInput = dojo.query('[name=price]', row)[0];
823 priceInput.value = li.estimated_unit_price() || '';
824 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
826 // show either "mark received" or "unreceive" as appropriate
827 this.updateLiState(li, row);
829 if (skip_final_placement) {
833 // the last LI may be rendered after the call to show('list'),
834 // so make sure it's focused if necessary.
835 if (this.focusLineitem == li.id())
839 this._liCountClaims = function(li) {
841 for (var i = 0; i < li.lineitem_details().length; i++)
842 total += li.lineitem_details()[i].claims().length;
846 this._findLiRow = function(li) {
847 return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
850 this.reconsiderClaimControl = function(li, row) {
851 if (!row) row = this._findLiRow(li);
852 var option = nodeByName("action_manage_claims", row);
853 var eligible = this.claimEligibleLidByLi[li.id()].length;
854 var count = this._liCountClaims(li);
856 option.disabled = !(count || eligible);
858 dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
859 option.onclick = function() { self.claimDialog.show(li); };
862 this.clearEligibility = function(li) {
863 this.claimEligibleLidByLi[li.id()] = [];
865 if (li.lineitem_details()) {
866 li.lineitem_details().forEach(
867 function(lid) { delete self.claimEligibleLid[lid.id()]; }
871 if (this.copyCache) {
873 for (var k in this.copyCache) {
874 if (this.copyCache[k].lineitem() == li.id())
878 function(k) { delete self.claimEligibleLid[k]; }
883 this.applyOrderIdentValues = function() {
884 this._identValuesInFlight =
885 openils.Util.objectProperties(this.liCache).length;
886 for (var liId in this.liCache) {
887 this._applyOrderIdentValue(this.liCache[liId]);
891 // returns true if request was sent
892 this._applyOrderIdentValue = function(li, oncomplete) {
895 console.log('applying ident value for lineitem ' + li.id());
898 var row = dojo.query('[li=' + li.id() + ']')[0];
900 // find the selected ident value
901 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
902 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
903 var name = typeSel.options[typeSel.selectedIndex].value;
904 var val = typeSel._cbox.attr('value');
906 console.log("selected ident is " + val);
908 // it differs from the existing ident value, update it
909 var oldIdent = self.getLiOrderIdent(li);
911 oldIdent.attr_name() == name &&
912 oldIdent.attr_value() == val) {
913 console.log('selected ident attr matches existing attr');
914 if (--this._identValuesInFlight == 0) {
915 if (oncomplete) oncomplete(li);
916 else location.href = location.href;
921 // see if the selected ident value is represented
922 // by an existing lineitem attr
925 typeSel._cbox.store.fetch({
926 query : {attr_value : val},
927 onItem : function(item) {
928 console.log('found existing attr for ident value');
929 args.source_attr_id = li.attributes().filter(
930 function(attr) { return attr.id() == item.id[0] }
936 if (!args.source_attr_id) {
937 // user entered new text in the combobox
938 // so we need to create a new attr
939 console.log('creating new ident attr');
940 args.lineitem_id = li.id();
941 args.attr_name = name;
942 args.attr_value = val;
945 fieldmapper.standardRequest(
946 ['open-ils.acq', 'open-ils.acq.lineitem.order_identifier.set'],
948 params : [openils.User.authtoken, args],
949 oncomplete : function() {
950 console.log('order_ident oncomplete');
951 if (--self._identValuesInFlight == 0) {
952 if (oncomplete) oncomplete(li);
953 else location.href = location.href;
955 console.log(self._identValuesInFlight + ' still in flight');
963 this.getLiOrderIdent = function(li) {
964 var attrs = li.attributes();
965 if (!attrs) return null;
969 attr.attr_type() == 'lineitem_local_attr_definition' &&
970 openils.Util.isTrue(attr.order_ident())
976 this.drawOrderIdentSelector = function(li, row) {
978 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
979 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
981 var attrs = li.attributes();
983 // limit to MARC attr defs
984 attrs = attrs.filter(
986 return (attr.attr_type() == 'lineitem_marc_attr_definition');
990 var identAttr = this.getLiOrderIdent(li);
993 // collect the values for each type of identifier
994 // find a reasonable default identifier type to render
998 dojo.forEach(['isbn', 'upc', 'issn'],
1001 // collect the values for this attr name
1002 values[name] = attrs.filter(
1004 return (attr.attr_name() == name)
1008 // select a reasonable default name in the type-selector
1012 if (identAttr.attr_name() == name)
1014 } else if (values[name].length) {
1019 dojo.forEach(typeSel.options, function(opt) {
1020 if (opt.value == name) {
1021 opt.selected = true;
1030 function updateOrderIdent(val) {
1031 self._identValuesInFlight = 1;
1032 self._applyOrderIdentValue(
1035 self.refreshLineitem(li);
1040 // replace the ident combobox with a new
1041 // one for the selected ident type
1042 function changeComboBox(sel) {
1043 var name = sel.options[sel.selectedIndex].value;
1045 var td = dojo.query('[name=order_ident_value]', row)[0];
1046 if (td.childNodes[0])
1047 dojo.destroy(td.childNodes[0]);
1049 var store = new dojo.data.ItemFileWriteStore({
1050 data : acqlia.toStoreData(values[name])
1053 var cbox = new dijit.form.ComboBox(
1055 labelAttr : 'attr_value',
1056 searchAttr : 'attr_value'
1058 dojo.create('div', {}, td)
1063 // set the value for the cbox
1064 if (values[name].length) {
1065 var orderIdent = self.getLiOrderIdent(li);
1067 if (orderIdent && orderIdent.attr_name() == name) {
1068 cbox.attr('value', orderIdent.attr_value());
1070 cbox.attr('value', values[name][0].attr_value());
1074 if (!self.orderIdentAllowed)
1075 cbox.attr('disabled', true);
1078 cbox._lineitem = li;
1079 dojo.connect(cbox, 'onChange', updateOrderIdent);
1082 changeComboBox(typeSel); // force the initial draw
1083 typeSel.onchange = function() {changeComboBox(typeSel)};
1086 this.testOrderIdentPerms = function(org, callback) {
1088 new openils.User().getPermOrgList(
1089 'ACQ_SET_LINEITEM_IDENTIFIER',
1091 console.log('found orgs = ' + orgs);
1092 for (var i = 0; i < orgs.length; i++) {
1093 if (Number(orgs[i]) == Number(org)) {
1094 self.orderIdentAllowed = true;
1095 if (callback) callback();
1099 if (callback) callback();
1105 this.checkClaimEligibility = function(li, callback, row) {
1106 /* Assume always eligible, i.e. from this interface we don't care about
1107 * claim eligibility any more. this is where the user would force a
1109 this.clearEligibility(li);
1110 this.claimEligibleLidByLi[li.id()] = li.lineitem_details().map(
1111 function(lid) { return lid.id(); }
1113 li.lineitem_details().forEach(
1114 function(lid) { self.claimEligibleLid[lid.id()] = true; }
1116 this.reconsiderClaimControl(li, row);
1117 if (callback) callback(li);
1119 this.clearEligibility(li);
1120 fieldmapper.standardRequest(
1121 ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
1122 "params": [openils.User.authtoken, {"lineitem": li.id()}],
1124 "onresponse": function(r) {
1125 if (r = openils.Util.readResponse(r)) {
1126 self.claimEligibleLidByLi[li.id()].push(
1129 self.claimEligibleLid[r.lineitem_detail()] = true;
1132 "oncomplete": function() {
1133 self.reconsiderClaimControl(li, row);
1134 if (typeof(callback) == "function")
1142 this.updateLiNotesCount = function(li, row) {
1143 if (!row) row = this._findLiRow(li);
1145 var has_notes = (li.lineitem_notes().filter(
1146 function(o) { return Boolean (o.alert_text()); }
1149 /* U+2691 is the code point for a filled-in flag character */
1150 nodeByName("notes_alert_flag", row).innerHTML =
1151 has_notes ? "⚑" : "";
1152 nodeByName("noteslink", row).style.fontStyle =
1153 has_notes ? "italic" : "normal";
1154 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
1157 /* XXX NOT related to _updateLiState(). rethink */
1158 this.updateLiState = function(li, row) {
1159 if (!row) row = this._findLiRow(li);
1161 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
1162 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
1164 // always allow access to LI history
1165 nodeByName('action_view_history', row).onclick =
1166 function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
1168 /* handle row coloring for based on LI state */
1169 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1170 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
1172 // Expose invoice actions for any lineitem that is linked to a PO
1173 if (li.purchase_order()) {
1174 openils.Util.show(nodeByName("invoices_span", row), "inline");
1175 var link = nodeByName("invoices_link", row);
1176 link.onclick = function() {
1177 openils.XUL.newTabEasy(
1178 oilsBasePath + "/acq/search/unified?so=" +
1179 base64Encode({"jub":[{"id": li.id()}]}) + "&rt=invoice"
1187 * If we haven't fleshed the lineitem_details, default to allowing access to the
1188 * holdings maintenence actions. The alternative is to flesh LIDs on every lineitem,
1189 * but that will add to page render time. Let's see if this will suffice...
1191 var lids = li.lineitem_details();
1193 (lids && !lids.filter(function(lid) { return lid.eg_copy_id() })[0] )) {
1195 actUpdateBarcodes.disabled = false;
1196 actUpdateBarcodes.onclick = function() {
1197 self.showRealCopyEditUI(li);
1198 nodeByName("action_none", row).selected = true;
1200 actHoldingsMaint.disabled = false;
1201 actHoldingsMaint.onclick =
1202 self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
1205 var state_cell = nodeByName("li_state_" + li.state(), row);
1207 // re-hide any state label nodes which may have been un-hidden
1208 // through previous actions.
1209 dojo.query('[state-label]', row).forEach(function(node) {
1210 openils.Util.hide(node)
1213 if (li.state() == 'cancelled') {
1214 if(typeof li.cancel_reason() == "object") {
1216 // clear the stock "Canceled" label, since we have more
1217 // information to replace it with.
1218 state_cell.innerHTML = '';
1220 var holds_state = dojo.create(
1222 "style": "border-bottom: 1px dashed #000;",
1223 "innerHTML": li.cancel_reason().label()
1224 }, state_cell, "only"
1228 "label": "<em>" + li.cancel_reason().label() +
1229 "</em><br />" + li.cancel_reason().description(),
1230 "connectId": [holds_state]
1231 }, dojo.create("span", null, state_cell, "last")
1234 if (li.cancel_reason().keep_debits() == 't') {
1235 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1236 openils.Util.addCSSClass(row, "oils-acq-li-state-delayed");
1239 console.log('li cancel_reason is un-fleshed. Please fix');
1243 openils.Util.show(state_cell);
1247 this._setAlertStore = function() {
1248 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
1250 "data": acqliat.toStoreData(
1253 "owning_lib": aou.orgNodeTrail(
1254 aou.findOrgUnit(openils.User.user.ws_ou())
1255 ).map(function(o) { return o.id(); })
1261 acqLitAlertAlertText.setValue(); /* make the store "live" */
1262 acqLitAlertAlertText._store_ready = true;
1266 * Draws and shows the lineitem notes pane
1268 this.drawLiNotes = function(li) {
1270 this.focusLineitem = li.id();
1272 if (!acqLitAlertAlertText._store_ready)
1273 this._setAlertStore();
1276 li.lineitem_notes().sort(
1278 if(a.edit_time() < b.edit_time()) return 1;
1284 while(this.liNotesTbody.childNodes[0])
1285 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
1288 acqLitCreateNoteSubmit.onClick = function() {
1289 var value = acqLitCreateNoteText.attr('value');
1291 var note = new fieldmapper.acqlin();
1294 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
1297 note.lineitem(li.id());
1299 self.updateLiNotes(li, note);
1300 acqLitCreateNoteVendorPublic.attr("checked", false);
1301 acqLitCreateNoteText.attr("value", "");
1304 acqLitCreateAlertSubmit.onClick = function() {
1305 if (!acqLitAlertAlertText.item) {
1306 alert(localeStrings.ALERT_UNSELECTED);
1310 var alert_text = new fieldmapper.acqliat().fromStoreItem(
1311 acqLitAlertAlertText.item
1313 var value = acqLitAlertNoteValue.attr("value") || "";
1315 var note = new fieldmapper.acqlin();
1317 note.lineitem(li.id());
1319 note.alert_text(alert_text);
1321 self.updateLiNotes(li, note);
1324 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
1328 * Draws a single lineitem note in the notes pane
1330 this.addLiNote = function(li, note) {
1331 if(note.isdeleted()) return;
1333 var row = self.liNotesRow.cloneNode(true);
1334 nodeByName("value", row).innerHTML = note.value();
1335 var alert_node = nodeByName("alert_code", row);
1336 if (note.alert_text()) {
1337 alert_node.innerHTML = dojo.string.substitute(
1339 aou.findOrgUnit(note.alert_text().owning_lib()).shortname(),
1340 note.alert_text().code()
1343 if (note.alert_text().description()) {
1346 "connectId": [alert_node],
1347 "label": note.alert_text().description()
1348 }, dojo.create("span", null, alert_node, "after")
1353 if (openils.Util.isTrue(note.vendor_public()))
1354 nodeByName("vendor_public", row).innerHTML =
1355 localeStrings.VENDOR_PUBLIC;
1357 nodeByName("delete", row).onclick = function() {
1358 note.isdeleted(true);
1359 self.liNotesTbody.removeChild(row);
1360 self.updateLiNotes(li);
1363 if(note.edit_time()) {
1364 nodeByName("edit_time", row).innerHTML =
1365 dojo.date.locale.format(
1366 dojo.date.stamp.fromISOString(note.edit_time()),
1367 {formatLength:'short'});
1370 self.liNotesTbody.appendChild(row);
1374 * Updates any new/changed/deleted notes on the server
1376 this.updateLiNotes = function(li, newNote) {
1382 notes = li.lineitem_notes().filter(
1384 if(note.ischanged() || note.isnew() || note.isdeleted())
1390 if(notes.length == 0) return;
1391 progressDialog.show();
1393 fieldmapper.standardRequest(
1394 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
1396 params : [this.authtoken, notes],
1397 onresponse : function(r) {
1398 var resp = openils.Util.readResponse(r);
1403 // remove the old changed notes
1405 dojo.forEach(li.lineitem_notes(),
1407 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
1411 li.lineitem_notes(list);
1414 progressDialog.hide();
1415 self.updateLiNotesCount(li);
1416 self.drawLiNotes(li);
1420 progressDialog.update(resp);
1421 var newnote = resp.note;
1423 if(!newnote.isdeleted()) {
1424 newnote.isnew(false);
1425 newnote.ischanged(false);
1426 li.lineitem_notes().push(newnote);
1433 this.updateLiPrice = function(input, li) {
1435 var price = input.value;
1436 if(Number(price) == Number(li.estimated_unit_price())) return;
1438 fieldmapper.standardRequest(
1439 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
1440 { async : false, // redundant w/ timeout
1442 params : [this.authtoken, li.id(), price],
1443 oncomplete : function(r) {
1444 openils.Util.readResponse(r);
1445 li.estimated_unit_price(price); // update local copy
1448 * If this is a PO and every visible lineitem has a price,
1449 * check again to see if this PO can be activated. Note that
1450 * every visible lineitem having a price does not guarantee it can
1451 * be activated, which is why we still make the call. Having a price
1452 * set for every visiable lineitem is just the lowest barrier to entry.
1455 var priceNodes = dojo.query('[name=price]', dojo.byId('acq-lit-tbody'));
1457 dojo.forEach(priceNodes, function(node) { if (node.value == '') allSet = false});
1458 if (allSet) checkCouldActivatePo();
1465 this.removeLineitem = function(liId) {
1466 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
1467 delete this.liCache[liId];
1468 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
1471 this.drawInfo = function(liId) {
1472 this.focusLineitem = liId;
1473 if (!this._isRelatedViewer) {
1474 var d = dojo.byId("acq-lit-info-related");
1475 if (!this.relCache[liId]) {
1476 fieldmapper.standardRequest(
1479 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
1482 "params": [openils.User.authtoken, liId],
1483 "onresponse": function(r) {
1484 self.relCache[liId] = openils.Util.readResponse(r);
1485 nodeByName("related_number", d).innerHTML =
1486 self.relCache[liId];
1488 self.relCache[liId] >1 ? "show" : "hide"
1494 nodeByName("related_number", d).innerHTML = this.relCache[liId];
1495 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
1500 openils.acq.Lineitem.fetchAttrDefs(
1502 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
1507 this.toggleInlineCopies = function() {
1508 // if any inline copies are not displayed,
1509 // display them all otherwise, hide them all.
1511 var displayAll = false;
1513 for (var liId in this.liCache) {
1514 if (!this.inlineCopiesVisible(liId)) {
1520 for (var liId in this.liCache) {
1521 var row = dojo.byId('acq-inline-copies-row-' + liId);
1523 if (!row || row._hidden) {
1524 this.drawInlineCopies(liId);
1526 } else { // hide all
1528 // drawInlineCopies() on a visible row will hide it.
1529 this.drawInlineCopies(liId);
1536 this.inlineCopiesVisible = function(liId) {
1537 var row = dojo.byId('acq-inline-copies-row-' + liId);
1538 return (row && !row._hidden);
1541 this.refreshInlineCopies = function(all, reFetch) {
1543 var liIds = this.inlineCopiesNeedingRefresh;
1544 if (all) liIds = openils.Util.objectProperties(liCache);
1545 liIds.forEach(function(liId) {
1546 if (self.inlineCopiesVisible(liId)) {
1547 self.drawInlineCopies(liId, reFetch); // hide
1548 self.drawInlineCopies(liId, reFetch); // re-draw
1553 // draw inline copy table. if the table is
1554 // already visible, hide the table as-is
1555 // reFetch forces a retrieval of the lineitem and
1556 // copies from the server. otherwise the locally
1557 // cached version of each is used.
1558 this.drawInlineCopies = function(liId, reFetch) {
1561 // find or create the row where the inline copies table will live
1562 var containerRow = dojo.byId('acq-inline-copies-row-' + liId);
1563 var liRow = dojo.query('[li=' + liId + ']')[0];
1565 if (!containerRow) {
1567 // build the inline copies container row and add it to
1568 // the DOM directly after the primary lineitem row
1570 containerRow = self.inlineCopyContainer.cloneNode(true);
1571 containerRow.id = 'acq-inline-copies-row-' + liId;
1573 if (liRow.nextSibling) {
1574 self.tbody.insertBefore(containerRow, liRow.nextSibling);
1576 self.tbody.appendChild(containerRow);
1581 // toggle the visible state
1582 containerRow._hidden = !containerRow._hidden;
1583 openils.Util.toggle(containerRow, 'table-row');
1585 if (containerRow._hidden) return; // hide only
1588 var handler = function(li) {
1590 var tbody = dojo.query(
1591 '[name=acq-li-inline-copies-tbody]',
1594 // reset the table before adding copy rows
1595 while (tbody.childNodes[0])
1596 tbody.removeChild(tbody.childNodes[0]);
1598 if(li.lineitem_details().length == 0) {
1600 self.inlineNoCopies.cloneNode(true));
1601 return; // no copies to show
1604 // add a row to the inline copy table for each copy
1605 dojo.forEach(li.lineitem_details(),
1607 var row = self.inlineCopyTemplate.cloneNode(true);
1608 tbody.appendChild(row);
1609 self.addInlineCopy(li, copy, row);
1614 this._fetchLineitem(liId, handler, reFetch);
1617 /** Draw read-only copy widgets for inline copies */
1618 this.addInlineCopy = function(li, copy, row) {
1621 dojo.forEach(liDetailFields,
1624 var widget = new openils.widget.AutoFieldWidget({
1627 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1628 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1629 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1631 parentNode : dojo.query('[name=' + field + ']', row)[0],
1640 /* For a given list of lineitem ids, build a list of full lineitems
1641 * re-using the fetching logic that is otherwise typical to use in this
1644 * If we've already got a lineitem in the cache, just use that.
1646 * Once we've built a list of lineitems, call callback(thatlist).
1648 this.fetchLineitemsById = function(id_list, callback) {
1649 var total = id_list.length;
1650 var result_list = [];
1652 var inner = function(li) {
1653 result_list.push(li)
1655 callback(result_list);
1658 id_list.forEach(function(id) { self._fetchLineitem(id, inner); });
1661 this._fetchLineitem = function(liId, handler, force) {
1663 var li = this.liCache[liId];
1664 if(li && li.marc() && li.lineitem_details() && !force)
1667 fieldmapper.standardRequest(
1668 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
1671 params: [self.authtoken, liId, {
1673 flesh_cancel_reason: true,
1674 flesh_li_details: true,
1676 flesh_fund_debit: true }],
1678 oncomplete: function(r) {
1679 var li = openils.Util.readResponse(r);
1680 self.liCache[liId] = li;
1687 this._drawInfo = function(li) {
1689 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
1691 if(li.eg_bib_id()) {
1692 openils.Util.hide('acq-lit-marc-order-record-label');
1693 openils.Util.hide(acqLitEditOrderMarc.domNode);
1694 openils.Util.show('acq-lit-marc-real-record-label');
1696 openils.Util.show('acq-lit-marc-order-record-label');
1697 openils.Util.show(acqLitEditOrderMarc.domNode);
1698 openils.Util.hide('acq-lit-marc-real-record-label');
1701 this.drawMarcHTML(li);
1702 this.infoTbody = dojo.byId('acq-lit-info-tbody');
1705 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
1706 while(this.infoTbody.childNodes[0])
1707 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
1709 for(var i = 0; i < li.attributes().length; i++) {
1710 var attr = li.attributes()[i];
1711 var row = this.infoRow.cloneNode(true);
1713 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
1714 var name = openils.acq.Lineitem.attrDefs[type].filter(
1716 return (a.code() == attr.attr_name());
1718 ).pop().description();
1720 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
1721 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
1722 this.infoTbody.appendChild(row);
1725 if (!this._isRelatedViewer) {
1726 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
1727 oilsBasePath + "/acq/lineitem/related/" + li.id();
1730 // if a top scroll point is defined, jump up to it here
1731 var node = dojo.byId('oils-scroll-to-top');
1732 if (node) dijit.scrollIntoView(node);
1735 this.generateMakeRecTab = function(bib_id,default_view, row) {
1739 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
1742 show_nav_buttons : true,
1743 show_print_button : true,
1744 opac_url : xulG.url_prefix('opac_rdetail|' + bib_id),
1745 default_view : default_view
1749 if(row) nodeByName("action_none", row).selected = true;
1753 this.drawMarcHTML = function(li) {
1754 var params = [null, true, li.marc()];
1756 params = [li.eg_bib_id(), true];
1758 fieldmapper.standardRequest(
1759 ['open-ils.search', 'open-ils.search.biblio.record.html'],
1762 oncomplete: function(r) {
1763 dojo.byId('acq-lit-marc-div').innerHTML =
1764 openils.Util.readResponse(r);
1770 this.drawCopies = function(liId, force_fetch) {
1771 this.focusLineitem = liId;
1772 if (typeof force_fetch == "undefined")
1773 force_fetch = false;
1775 var cgi = new openils.CGI();
1776 var source = cgi.param('source');
1777 if (source && source.match(/invoice/)) {
1778 // got here from the invoice page, show the 'return-to-invoice' button
1779 var cgi = new openils.CGI({url : source});
1780 cgi.param('focus_li', liId);
1781 openils.Util.show(dojo.byId('acq-lit-copies-back-to-invoice-button-wrapper'), 'inline');
1782 var button = dojo.byId('acq-lit-copies-back-to-invoice-button');
1783 button.onclick = function() { location.href = cgi.url() };
1786 openils.acq.Lineitem.fetchAndRender(liId, {},
1787 function(li, html) {
1788 dojo.byId('acq-lit-copies-li-summary').innerHTML = html;
1792 this.show('copies');
1794 this.copyCache = {};
1795 this.copyWidgetCache = {};
1796 this.oldCopyWidgetCache = {};
1797 this.virtDfaCounts = {};
1798 this.realDfaCache = {};
1801 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
1802 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
1803 acqLitCopyCountInput.attr('value', '0');
1805 if (this.isPO && PO && PO.order_date()) {
1806 // prevent adding copies to activated POs
1807 acqLitCopyCountInput.attr('disabled', true);
1808 acqLitAddCopyCount.attr('disabled', true);
1811 while(this.copyTbody.childNodes[0])
1812 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
1814 this._drawBatchCopyWidgets();
1816 this._drawDistribApplied(liId);
1818 this._fetchDistribFormulas(
1820 openils.acq.Lineitem.fetchAttrDefs(
1822 self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch);
1829 this._saveDistribAppliedTemplates = function() {
1830 if (!this._appliedDistribTemplate) {
1831 this._appliedDistribTemplate =
1832 dojo.byId("acq-lit-distrib-applied-tbody").
1833 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
1834 dojo.attr(this._appliedDistribTemplate, "id");
1838 this._drawDistribApplied = function(liId) {
1839 /* Build this table while hidden to prevent rendering artifacts */
1840 openils.Util.hide("acq-lit-distrib-applied-tbody");
1842 this._saveDistribAppliedTemplates();
1844 /* Remove any rows in the table from previous populations */
1845 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
1846 forEach(dojo.destroy);
1848 /* Unregister all dijits previously created (for some reason this isn't
1849 * covered by the above destroy calls). */
1850 dijit.registry.forEach(
1851 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
1854 /* Populate the table with our liId */
1856 fieldmapper.standardRequest(
1858 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
1861 "params": [self.authtoken, liId],
1862 "onresponse": function(r) {
1863 var dfa = openils.Util.readResponse(r);
1866 self.realDfaCache[dfa.id()] = dfa;
1867 self._drawDistribAppliedUnit(dfa);
1870 "oncomplete": function() {
1871 /* Reveal built table */
1874 "acq-lit-distrib-applied-tbody", "table-row-group"
1882 this._drawDistribAppliedUnit = function(dfa) {
1883 var new_row = false;
1884 var row = dojo.query(
1885 'tr[formula="' + dfa.formula().id() + '"]',
1886 "acq-lit-distrib-applied-tbody"
1891 row = dojo.clone(this._appliedDistribTemplate);
1892 dojo.attr(row, "formula", dfa.formula().id());
1893 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
1896 var td = dojo.query("td", row)[0];
1898 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1899 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1902 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1904 new dijit.form.Button(
1906 "onClick": function() {
1907 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1908 self.deleteDfa(dfa);
1911 /* XXX I /cannot/ make the following work in as a CSS class
1912 * for some reason. So frustrating... */
1913 "style": function(id) {
1915 "font-weight: bold; color: #c00;" :
1917 }(dfa.id()) + "margin: 0 6px;display: inline;"
1918 }, "dfa-button-" + dfa.id()
1922 "connectId": ["dfa-button-" + dfa.id()],
1923 "label": dojo.string.substitute(
1924 localeStrings.DFA_TIP, dfa.id() > 0 ? [
1925 openils.User.formalName(dfa.creator()),
1926 dojo.date.locale.format(
1927 dojo.date.stamp.fromISOString(dfa.create_time()),
1928 {"formatLength":"short"}
1930 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
1932 }, "dfa-tip-" + dfa.id()
1936 this.deleteDfa = function(dfa) {
1937 if (dfa.id() > 0) { /* real */
1938 this.pcrud.eliminate(
1941 "oncomplete": function() {
1942 self._removeDistribApplied(dfa.id());
1943 delete self.realDfaCache[dfa.id()];
1947 } else { /* virtual */
1948 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
1949 this.virtDfaCounts[dfa.formula().id()] = 0;
1950 /* hasn't been saved yet, so no need to do anything server side */
1951 this._removeDistribApplied(dfa.id());
1956 this._removeDistribApplied = function(dfaId) {
1957 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
1958 dijit.registry.forEach(
1959 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
1961 this._removeDistribAppliedEmptyRows();
1964 this._removeAllDistribAppliedVirtual = function() {
1965 /* Unregister dijits */
1966 dijit.registry.forEach(
1967 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
1969 this._removeDistribAppliedEmptyRows();
1972 this._removeDistribAppliedEmptyRows = function() {
1973 /* Remove any rows with no DFA at all */
1974 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
1976 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
1982 * Insert a new row into the distribution formula selection form
1984 this._addDistribFormulaRow = function() {
1987 if (!self.distribForms) {
1988 // no formulas, hide the form
1989 openils.Util.hide('acq-lit-distrib-formula-table');
1993 if(!this.distribFormulaTemplate)
1994 this.distribFormulaTemplate =
1995 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
1997 var row = this.distribFormulaTemplate.cloneNode(true);
1998 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
2000 this.dfSelector = new dijit.form.FilteringSelect(
2001 {"labelAttr": "dynLabel", "labelType": "html"},
2002 nodeByName("selector", row)
2004 this._updateFormulaStore();
2005 this.dfSelector.fetchProperties =
2006 {"sort": [{"attribute": "use_count", "descending": true}]};
2008 var apply = new dijit.form.Button(
2009 {"label": localeStrings.APPLY},
2010 nodeByName('set_button', row)
2013 var reset = new dijit.form.Button(
2014 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
2015 nodeByName("reset_button", row)
2018 dojo.connect(apply, 'onClick',
2020 var form_id = self.dfSelector.attr("value");
2021 if(!form_id) return;
2022 self._applyDistribFormula(form_id);
2023 reset.attr("disabled", false);
2027 dojo.connect(reset, 'onClick',
2029 self.restoreCopyFieldsBeforeDF();
2030 self.virtDfaCounts = {};
2031 self.virtDfaId = -1;
2033 self._updateFormulaStore();
2034 self._removeAllDistribAppliedVirtual();
2035 reset.attr("disabled", "true");
2042 * Applies a distrib formula to the current set of copies
2044 this._applyDistribFormula = function(formula) {
2045 if(!formula) return;
2047 formula = this.distribForms.filter(
2048 function(form) { return form.id() == formula; }
2051 var copyRows = dojo.query('tr', self.copyTbody);
2053 if (this.dfeOffset >= copyRows.length) {
2054 alert(localeStrings.OUT_OF_COPIES);
2058 var entries_applied = 0;
2060 var rowIndex = this.dfeOffset;
2061 rowIndex < copyRows.length;
2065 var row = copyRows[rowIndex];
2066 var copy_id = row.getAttribute('copy_id');
2067 var copyWidgets = this.copyWidgetCache[copy_id];
2068 var entryIndex = this.dfeOffset;
2071 // find the correct entry for the current row
2072 dojo.forEach(formula.entries(),
2075 entryIndex += e.item_count();
2076 if(entryIndex > rowIndex)
2084 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
2085 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
2088 this.saveCopyFieldsBeforeDF(copy_id);
2089 this._copy_fields_for_acqdf.forEach(
2091 if(entry[field]()) {
2092 copyWidgets[field].attr('value', (entry[field]()));
2099 if (entries_applied) {
2100 this.virtDfaCounts[formula.id()] =
2101 ++(this.virtDfaCounts[formula.id()]) || 1;
2102 this._updateFormulaStore();
2103 this._drawDistribAppliedUnit(
2105 var dfa = new acqdfa();
2106 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
2109 this.dfeOffset += entries_applied;
2114 * This function updates the DF store for the dropdown so that use_counts
2115 * can reflect DF applications from this session before they're saved
2118 this._updateFormulaStore = function() {
2119 this.dfSelector.store = new dojo.data.ItemFileReadStore(
2121 "data": self._labelFormulasWithCounts(
2122 acqdf.toStoreData(self.distribForms)
2128 this.saveCopyFieldsBeforeDF = function(copy_id) {
2130 if (!this.oldCopyWidgetCache[copy_id]) {
2131 var copyWidgets = this.copyWidgetCache[copy_id];
2133 this.oldCopyWidgetCache[copy_id] = {};
2134 this._copy_fields_for_acqdf.forEach(
2136 self.oldCopyWidgetCache[copy_id][f] =
2137 copyWidgets[f].attr("value");
2143 this.restoreCopyFieldsBeforeDF = function() {
2145 for (var copy_id in this.oldCopyWidgetCache) {
2146 this._copy_fields_for_acqdf.forEach(
2148 self.copyWidgetCache[copy_id][f].attr(
2149 "value", self.oldCopyWidgetCache[copy_id][f]
2156 this._labelFormulasWithCounts = function(store_data) {
2157 for (var key in store_data.items) {
2158 var obj = store_data.items[key];
2159 obj.use_count = Number(obj.use_count); /* needed for sorting */
2161 if (this.virtDfaCounts[obj.id])
2162 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
2164 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
2165 obj.use_count + "]</span> " + obj.name;
2171 * This method formerly would not refetch the DF formulas if they'd been
2172 * loaded already, but now it always re-fetches, since use_count changes.
2174 /** TODO: port distrib-formula selector to autofieldwidget+pcrud/dojo store */
2175 this._fetchDistribFormulas = function(onload) {
2176 fieldmapper.standardRequest(
2178 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
2181 "params": [openils.User.authtoken, 0, 500],
2182 "oncomplete": function(r) {
2183 self.distribForms = openils.Util.readResponse(r);
2184 if(!self.distribForms || self.distribForms.length == 0) {
2185 self.distribForms = [];
2187 self._addDistribFormulaRow();
2194 this._drawBatchCopyWidgets = function() {
2195 var row = this.copyBatchRow;
2196 dojo.forEach(liDetailBatchFields,
2198 if(self.copyBatchRowDrawn) {
2199 self.copyBatchWidgets[field].attr('value', null);
2201 var args = self.afwCopyFieldArgs(field, "CREATE_PICKLIST");
2202 args.parentNode = dojo.query('[name='+field+']', row)[0];
2204 var widget = new openils.widget.AutoFieldWidget(args);
2207 if (field == "fund" && w.store)
2208 self._ensureCSSFundClasses(w.store);
2209 self.copyBatchWidgets[field] = w;
2212 if (field == "fund") {
2214 widget.widget, "onChange", function(val) {
2215 self._updateFundSelectorStyle(widget, val);
2222 this.copyBatchRowDrawn = true;
2225 this.batchCopyUpdate = function() {
2227 for(var k in this.copyWidgetCache) {
2228 var cache = this.copyWidgetCache[k];
2229 dojo.forEach(liDetailBatchFields, function(f) {
2230 var newval = self.copyBatchWidgets[f].attr('value');
2231 if(newval) cache[f].attr('value', newval);
2236 this._drawCopies = function(li) {
2239 // this button sets the total number of copies for a given lineitem
2240 acqLitAddCopyCount.onClick = function() {
2241 var count = acqLitCopyCountInput.attr('value');
2244 while(self.copyCount() < count)
2247 // delete rows if necessary
2248 var diff = self.copyCount() - count;
2250 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
2251 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
2252 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
2254 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2260 if(li.lineitem_details().length > 0) {
2261 dojo.forEach(li.lineitem_details(),
2263 self.addCopy(li, copy);
2271 this.copyCount = function() {
2273 for(var id in this.copyCache) {
2274 if(!this.copyCache[id].isdeleted())
2280 this.virtCopyId = -1;
2281 this.addCopy = function(li, copy) {
2282 var row = this.copyRow.cloneNode(true);
2283 this.copyTbody.appendChild(row);
2287 copy = new fieldmapper.acqlid();
2289 copy.id(this.virtCopyId--);
2290 copy.lineitem(li.id());
2293 this.copyCache[copy.id()] = copy;
2294 row.setAttribute('copy_id', copy.id());
2295 self.copyWidgetCache[copy.id()] = {};
2297 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2299 var rcvr = copy.receiver();
2301 if (!userCache[rcvr]) {
2302 if(rcvr == openils.User.user.id()) {
2303 userCache[rcvr] = openils.User.user;
2305 userCache[rcvr] = fieldmapper.standardRequest(
2306 ['open-ils.actor', 'open-ils.actor.user.retrieve'],
2307 {params: [openils.User.authtoken, rcvr]}
2311 dojo.query('[name=receiver]', row)[0].innerHTML = userCache[rcvr].usrname();
2314 dojo.forEach(liDetailFields,
2317 if (field == "fund") {
2318 searchFilter = (copy.fund() ?
2319 {"-or": {"active": "t", "id": copy.fund()}} :
2322 searchFilter = null;
2325 var readOnly = false;
2327 // TODO: Add support for changing the owning_lib after real copies have been made.
2328 // owning_lib is order data as much as its item data
2329 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
2333 // TODO: add support for changing the fund after debits have been created
2334 // Note: invoicing allows the change
2335 if(copy.fund_debit() && field == 'fund') {
2340 var widget = new openils.widget.AutoFieldWidget({
2343 labelFormat : (field == 'fund') ? fundLabelFormat : null,
2344 searchFormat : (field == 'fund') ? fundSearchFormat : null,
2345 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
2346 searchFilter : searchFilter,
2347 noCache: (field == "fund"),
2349 parentNode : dojo.query('[name='+field+']', row)[0],
2350 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2351 readOnly : readOnly,
2352 orgDefaultsToWs : true
2356 // make sure we capture the value from any async widgets
2359 if (field == "fund" && w.store)
2360 self._ensureCSSFundClasses(w.store);
2363 copy[field](ww.getFormattedValue())
2365 self.copyWidgetCache[copy.id()][field] = w;
2367 dojo.connect(w, 'onChange',
2369 if (field == "fund")
2370 self._updateFundSelectorStyle(widget, val);
2372 if (!readOnly && (copy.isnew() || val != copy[field]())) {
2373 // prevent setting ischanged() automatically on widget load for existing copies
2374 copy[field](widget.getFormattedValue())
2375 copy.ischanged(true);
2384 this.updateLidState(copy, row);
2387 this._ensureCSSFundClass = function(id) {
2388 if (!this.fundStyleSheet) {
2390 "style", {"type": "text/css"},
2391 document.getElementsByTagName("head")[0], "last"
2393 this.fundStyleSheet = document.styleSheets[
2394 document.styleSheets.length - 1
2398 var cn = "fund_" + id;
2399 if (!this.haveFundClass[cn]) {
2400 fieldmapper.standardRequest(
2401 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
2403 "params": [openils.User.authtoken, id],
2405 "oncomplete": function(r) {
2406 r = openils.Util.readResponse(r);
2407 self.fundBalanceState[id] = r;
2409 if (r[0] /* stop */)
2410 style = fundStyles.stop;
2411 else if (r[1] /* warning */)
2412 style = fundStyles.warning;
2413 self.fundStyleSheet.insertRule(
2414 "." + cn + " { " + style + " }",
2415 self.fundStyleSheet.cssRules.length
2417 self.haveFundClass[cn] = true;
2424 this._ensureCSSFundClasses = function(store) {
2426 "query": {"id": "*"},
2427 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
2431 this._updateFundSelectorStyle = function(widget, fund_id) {
2432 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
2433 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
2436 this.updateLidState = function(copy, row) {
2439 if (typeof(row) == "undefined") {
2440 row = dojo.query('tr[copy_id="' + copy.id() + '"]', this.copyTbody)[0];
2444 var recv_link = nodeByName("receive", row);
2445 var unrecv_link = nodeByName("unreceive", row);
2446 var del_link = nodeByName("delete", row);
2447 var cxl_link = nodeByName("cancel", row);
2448 var claim_link = nodeByName("claim", row);
2449 var cxl_reason_link = nodeByName("cancel_reason", row);
2451 // by default, hide all the actions
2452 openils.Util.hide(del_link.parentNode);
2453 openils.Util.hide(recv_link);
2454 openils.Util.hide(unrecv_link);
2455 openils.Util.hide(cxl_link);
2456 openils.Util.hide(claim_link);
2457 openils.Util.hide(cxl_reason_link);
2459 if (copy.id() > 0) { // real copies (LIDs)
2461 if (copy.cancel_reason()) {
2463 /* --------- cancelled -------------------------- */
2465 /* XXX the following may leak memory in a long lived table:
2466 * dijits may not get destroyed... not positive. revisit. */
2467 var holds_reason = dojo.create(
2469 "style": "border-bottom: 1px dashed #000;",
2470 "innerHTML": copy.cancel_reason().label()
2471 }, cxl_reason_link, "only"
2475 "label": "<em>" + copy.cancel_reason().label() +
2476 "</em><br />" + copy.cancel_reason().description(),
2477 "connectId": [holds_reason]
2478 }, dojo.create("span", null, cxl_reason_link, "last")
2480 openils.Util.show(cxl_reason_link, "inline");
2482 if (copy.cancel_reason().keep_debits() == 't' ) {
2483 // allow further cancellation of "delayed" copies
2485 openils.Util.show(cxl_link, "inline");
2486 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2489 } else if (copy.recv_time()) {
2491 /* --------- received -------------------------- */
2493 openils.Util.show(unrecv_link, "inline");
2494 unrecv_link.onclick = function() {
2495 if (confirm(localeStrings.UNRECEIVE_LID))
2496 self.issueReceive(copy, /* rollback */ true);
2499 } else if (this.liCache[copy.lineitem()].state() == 'on-order') {
2501 /* --------- on order -------------------------- */
2503 openils.Util.show(recv_link, 'inline');
2504 openils.Util.show(cxl_link, "inline");
2506 recv_link.onclick = function() {
2507 if (self.checkLiAlerts(copy.lineitem()))
2508 self.issueReceive(copy);
2511 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2515 /* --------- pre-order copies -------------------------- */
2517 del_link.onclick = function() { self.deleteCopy(row) };
2518 openils.Util.show(del_link.parentNode);
2524 /* --------- virtual copies -------------------------- */
2526 del_link.onclick = function() { self.deleteCopy(row) };
2527 openils.Util.show(del_link.parentNode);
2531 this.cancelLid = function(lid_id) {
2532 lidCancelDialog._lid_id = lid_id;
2533 openils.Util.show(lidCancelDialog.domNode.parentNode);
2534 lidCancelDialog.show();
2535 if (!lidCancelDialog._prepared) {
2536 var widget = new openils.widget.AutoFieldWidget({
2537 "fmField": "cancel_reason",
2538 "fmClass": "acqlid",
2539 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
2540 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2542 "searchOptions" : {order_by : {"acqcr":"label"}}
2546 acqLidCancelButton.onClick = function() {
2547 if (w.attr("value")) {
2548 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
2550 lidCancelDialog._lid_id,
2554 lidCancelDialog.hide();
2557 lidCancelDialog._prepared = true;
2563 this._cancelLid = function(lid_id, reason) {
2564 fieldmapper.standardRequest(
2565 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
2566 "params": [openils.User.authtoken, lid_id, reason],
2568 "onresponse": function(r) {
2569 if (r = openils.Util.readResponse(r)) {
2571 for (var id in r.lid) {
2572 /* actually this should only iterate once */
2573 self.copyCache[id].cancel_reason(
2574 r.lid[id].cancel_reason
2576 self.updateLidState(self.copyCache[id]);
2585 this._confirmAlert = function(li, lin) {
2587 dojo.string.substitute(
2588 localeStrings.CONFIRM_LI_ALERT, [
2589 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2590 "title", "lineitem_marc_attr_definition"
2592 /* XXX it's really better add a parameter and to adjust
2593 * the format string rather than do this concatenation
2594 * here, but if someone wants this for 2.2 in a hurry,
2595 * we can sidestep the problem of updating the strings
2596 * while the translators are working. */
2598 aou.findOrgUnit(lin.alert_text().owning_lib()).shortname() +
2600 lin.alert_text().code()
2602 lin.alert_text().description() || "",
2609 this.checkLiAlerts = function(li_id) {
2610 var li = this.liCache[li_id];
2612 var alert_notes = li.lineitem_notes().filter(
2613 function(o) { return Boolean(o.alert_text()); }
2616 /* this is _intentionally_ not done in a call to forEach() ... */
2617 for (var i = 0; i < alert_notes.length; i++) {
2618 if (this.noteAcks[alert_notes[i].id()])
2620 else if (!this._confirmAlert(li, alert_notes[i]))
2623 this.noteAcks[alert_notes[i].id()] = true;
2629 this.deleteCopy = function(row) {
2630 var copy = this.copyCache[row.getAttribute('copy_id')];
2631 copy.isdeleted(true);
2633 delete this.copyCache[copy.id()];
2634 this.copyTbody.removeChild(row);
2637 this._virtDfaCountsAsList = function() {
2639 for (var key in this.virtDfaCounts) {
2640 for (var i = 0; i < this.virtDfaCounts[key]; i++)
2646 this.confirmBreachedCopyFunds = function(copies) {
2647 var stop = 0, warning = 0;
2651 var state = self.fundBalanceState[o.fund()];
2652 if (state[0] /* stop */)
2654 else if (state[1] /* warning */)
2661 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
2662 } else if (warning) {
2663 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
2668 this.saveCopyChanges = function(liId) {
2674 for(var id in this.copyCache) {
2675 var c = this.copyCache[id];
2676 if(!c.isdeleted()) total++;
2677 if(c.isnew() || c.ischanged() || c.isdeleted()) {
2678 if(c.id() < 0) c.id(null);
2684 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
2687 if (copies.length > 0) {
2688 if (!this.confirmBreachedCopyFunds(copies))
2691 if (typeof(this._copy_count_cb) == "function")
2692 this._copy_count_cb(liId, total);
2694 openils.Util.show("acq-lit-update-copies-progress");
2695 fieldmapper.standardRequest(
2696 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
2698 params: [openils.User.authtoken, copies],
2699 onresponse: function(r) {
2700 var res = openils.Util.readResponse(r);
2701 litUpdateCopiesProgress.update(res);
2703 oncomplete: function() {
2704 self.drawCopies(liId, true /* force_fetch */);
2705 openils.Util.hide("acq-lit-update-copies-progress");
2711 var dfa_list = this._virtDfaCountsAsList();
2712 if (dfa_list.length > 0) {
2713 fieldmapper.standardRequest(
2715 "open-ils.acq.distribution_formula.record_application"],
2718 "params": [openils.User.authtoken, dfa_list, liId],
2719 "onresponse": function(r) {
2720 var res = openils.Util.readResponse(r);
2721 if (res && res.length < dfa_list.length)
2722 alert(localeStrings.DFA_NOT_ALL);
2726 this.virtDfaCounts = {};
2729 if (this.inlineCopiesNeedingRefresh.indexOf(liId) < 0)
2730 this.inlineCopiesNeedingRefresh.push(liId);
2733 this._updateCreatePoPrepayCheckbox = function(prepay) {
2734 var prepay = openils.Util.isTrue(prepay);
2735 this._prepayRequiredByVendor = prepay;
2736 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
2739 this._confirmPoPrepaySituation = function() {
2740 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
2741 if (want_prepay != this._prepayRequiredByVendor) {
2744 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
2745 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
2752 this.applySelectedLiAction = function(action) {
2756 case 'delete_selected':
2757 this._deleteLiList(self.getSelected());
2760 case 'add_to_order':
2761 addToPoDialog._get_li = dojo.hitch(
2764 return this.getSelected(
2765 false, null, true, li_pre_po_states);
2768 if (addToPoDialog._get_li().length == 0) {
2769 alert(localeStrings.NO_LI_GENERAL);
2772 addToPoDialog.show();
2775 case 'create_order':
2776 this._loadPOSelect();
2777 acqLitPoCreateDialog.show();
2780 case 'save_picklist':
2781 acqLitSavePlDialog.show();
2784 case 'selector_ready':
2786 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
2787 acqLitChangeLiStateDialog.show();
2795 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
2798 case 'batch_create_invoice':
2799 this.batchCreateInvoice();
2802 case 'batch_link_invoice':
2803 this.batchLinkInvoice();
2806 case 'receive_lineitems':
2807 this.receiveSelectedLineitems();
2810 case 'rollback_receive_lineitems':
2811 this.rollbackReceiveLineitems();
2814 case 'create_assets':
2815 this.showAssetCreator();
2818 case 'export_attr_list':
2819 this.chooseExportAttr();
2822 case 'batch_apply_funds':
2823 this.applyBatchLiFunds();
2826 case 'add_brief_record':
2828 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
2830 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
2834 case "cancel_lineitems":
2835 console.log('HERE');
2836 this.maybeCancelLineitems();
2839 case "apply_claim_policy":
2840 var li_list = this.getSelected();
2841 this.claimPolicyPicker.attr("value", null);
2842 liClaimPolicyDialog.show();
2843 liClaimPolicySave.onClick = function() {
2844 self.changeClaimPolicy(
2846 self.claimPolicyPicker.attr("value"),
2850 self.setClaimPolicyControl(li);
2851 self.reconsiderClaimControl(li);
2854 liClaimPolicyDialog.hide();
2862 this.changeClaimPolicy = function(li_list, value, callback) {
2864 function(li) { li.claim_policy(value); }
2866 fieldmapper.standardRequest(
2867 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
2868 "params": [openils.User.authtoken, li_list],
2870 "oncomplete": function(r) {
2871 r = openils.Util.readResponse(r);
2872 if (callback) callback(r);
2878 this.showAssetCreator = function(onAssetsCreated) {
2879 if(!this.isPO) return;
2882 // first, let's see if this PO has any LI's that need to be merged/imported
2883 self.pcrud.search('jub', {purchase_order : this.isPO, eg_bib_id : null}, {
2885 oncomplete : function(r) {
2886 var resp = openils.Util.readResponse(r);
2887 if (resp && resp.length) {
2888 // PO has some non-linked jubs.
2890 self.show('asset-creator');
2891 if(!self.vlAgent.loaded)
2892 self.vlAgent.init();
2894 dojo.connect(assetCreatorButton, 'onClick',
2895 function() { self.createAssets(onAssetsCreated) });
2899 // all jubs linked, move on to asset creation
2900 self.createAssets(onAssetsCreated, true);
2906 this.createAssets = function(onAssetsCreated, noVl) {
2907 this.show('acq-lit-progress-numbers');
2909 var vlArgs = (noVl) ? {} : {vandelay : this.vlAgent.values()};
2910 fieldmapper.standardRequest(
2911 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
2913 params: [this.authtoken, this.isPO, vlArgs],
2914 onresponse: function(r) {
2915 var resp = openils.Util.readResponse(r);
2916 self._updateProgressNumbers(resp, !Boolean(onAssetsCreated), onAssetsCreated);
2922 this.maybeCancelLineitems = function() {
2923 openils.Util.show("acq-lit-cancel-reason", "inline");
2924 if (!acqLitCancelLineitemsButton._prepared) {
2925 var widget = new openils.widget.AutoFieldWidget({
2926 "fmField": "cancel_reason",
2928 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
2929 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2931 "searchOptions" : {order_by : {"acqcr":"label"}}
2935 acqLitCancelLineitemsButton.onClick = function() {
2936 if (w.attr("value")) {
2937 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
2938 self._cancelLineitems(w.attr("value"));
2940 openils.Util.hide("acq-lit-cancel-reason");
2943 acqLitCancelLineitemsButton._prepared = true;
2949 this._cancelLineitems = function(reason) {
2951 var li_list = this.getSelected();
2953 // canceled lineitems may be canceled again if they were
2954 // previously delayed (keep_debits = true).
2955 li_list = li_list.filter(
2958 li.state() != 'cancelled' ||
2959 li.cancel_reason().keep_debits() == 't'
2964 id_list = li_list.map(function(l) {return l.id()});
2966 if (!id_list.length) {
2967 alert(localeStrings.NO_LI_GENERAL);
2970 fieldmapper.standardRequest(
2971 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
2972 "params": [openils.User.authtoken, id_list, reason],
2974 "onresponse": function(r) {
2975 if (r = openils.Util.readResponse(r)) {
2977 for (var id in r.li) {
2978 self.liCache[id].state(r.li[id].state);
2979 self.liCache[id].cancel_reason(
2980 r.li[id].cancel_reason
2982 self.updateLiState(self.liCache[id]);
2985 if (r.lid && self.copyCache) {
2986 for (var id in r.lid) {
2987 if (self.copyCache[id]) {
2988 self.copyCache[id].cancel_reason(
2989 r.lid[id].cancel_reason
2991 self.updateLidState(self.copyCache[id]);
3001 this.chooseExportAttr = function() {
3002 if (!acqLitExportAttrSelector._li_setup) {
3004 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
3006 "data": acqlimad.toStoreData(
3008 "acqlimad", {"code": li_exportable_attrs}
3013 acqLitExportAttrSelector.setValue();
3014 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
3015 acqLitExportAttrSelector._li_setup = true;
3017 openils.Util.show("acq-lit-export-attr-holder", "inline");
3020 this.exportAttrList = function() {
3021 var attr_def = acqLitExportAttrSelector.item;
3022 var li_list = this.getSelected();
3023 var value_list = li_list.map(
3025 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
3026 attr_def.code, "lineitem_marc_attr_definition"
3029 ).filter(function(attr) { return Boolean(attr); });
3031 if (value_list.length > 0) {
3032 if (value_list.length < li_list.length) {
3034 dojo.string.substitute(
3035 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
3042 openils.XUL.contentToFileSaveDialog(
3043 value_list.join("\n"),
3044 localeStrings.EXPORT_SAVE_DIALOG_TITLE
3050 alert(dojo.string.substitute(
3051 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
3055 openils.Util.hide("acq-lit-export-attr-holder");
3058 this.printPO = function() {
3059 if(!this.isPO) return;
3060 progressDialog.show(true);
3061 fieldmapper.standardRequest(
3062 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
3064 params: [this.authtoken, this.isPO, 'html'],
3065 oncomplete: function(r) {
3066 progressDialog.hide();
3067 var evt = openils.Util.readResponse(r);
3068 if(evt && evt.template_output()) {
3069 openils.Util.printHtmlString(evt.template_output().data());
3076 this.batchCreateInvoice = function() {
3077 var liIds = this.getSelected(
3078 false, null, true /* id_list */, li_active_states)
3079 if (!liIds.length) {
3080 alert(localeStrings.NO_LI_GENERAL);
3083 var path = oilsBasePath + '/acq/invoice/view?create=1';
3084 dojo.forEach(liIds, function(li, idx) { path += '&attach_li=' + li });
3085 if (openils.XUL.isXUL())
3086 openils.XUL.newTabEasy(path, localeStrings.NEW_INVOICE, null, true);
3088 location.href = path;
3091 this.batchLinkInvoice = function(create) {
3092 var liIds = this.getSelected(
3093 false, null, true /* id_list */, li_active_states)
3094 if (!liIds.length) {
3095 alert(localeStrings.NO_LI_GENERAL);
3098 if (!self.invoiceLinkDialogManager) {
3099 self.invoiceLinkDialogManager =
3100 new InvoiceLinkDialogManager("li");
3102 self.invoiceLinkDialogManager.target = liIds;
3103 acqLitLinkInvoiceDialog.show();
3106 this.receiveSelectedLineitems = function() {
3107 var states = li_post_po_states.filter(
3108 function(s) { return s != 'received' });
3109 var li_list = this.getSelected(null, null, null, states);
3111 if (!li_list.length) {
3112 alert(localeStrings.NO_LI_GENERAL);
3116 for (var i = 0; i < li_list.length; i++) {
3117 var li = li_list[i];
3119 if (li.state() != "received" &&
3120 !this.checkLiAlerts(li.id())) return;
3123 this.show('acq-lit-progress-numbers');
3126 fieldmapper.standardRequest(
3127 ['open-ils.acq', 'open-ils.acq.lineitem.receive.batch'],
3131 li_list.map(function(li) { return li.id(); })
3133 onresponse : function(r) {
3134 var resp = openils.Util.readResponse(r);
3135 self._updateProgressNumbers(resp, true);
3141 this.issueReceive = function(obj, rollback) {
3143 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
3145 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
3147 progressDialog.show(true);
3148 fieldmapper.standardRequest(
3149 ["open-ils.acq", method], {
3151 "params": [this.authtoken, obj.id()],
3152 "onresponse": function(r) {
3153 if (r = openils.Util.readResponse(r)) {
3154 self.fetchClaimInfo(
3155 part == "lineitem" ? obj.id() : obj.lineitem(),
3157 function() { self.handleReceive(r); }
3159 progressDialog.hide();
3167 * Handles the responses from receive and rollback ML calls.
3169 this.handleReceive = function(resp) {
3172 for (var li_id in resp.li) {
3173 for (var key in resp.li[li_id])
3174 self.liCache[li_id][key](resp.li[li_id][key]);
3175 self.updateLiState(self.liCache[li_id]);
3179 if (typeof(self.poUpdateCallback) == "function")
3180 self.poUpdateCallback(resp.po);
3183 for (var lid_id in resp.lid) {
3184 for (var key in resp.lid[lid_id])
3185 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
3186 self.updateLidState(self.copyCache[lid_id]);
3192 this.rollbackReceiveLineitems = function() {
3193 var li_id_list = this.getSelected(false, null, true);
3194 if (!li_id_list.length) {
3195 alert(localeStrings.NO_LI_GENERAL);
3199 if (!confirm(localeStrings.ROLLBACK_LI_RECEIVE_CONFIRM)) return;
3201 this.show('acq-lit-progress-numbers');
3204 fieldmapper.standardRequest(
3205 ['open-ils.acq', 'open-ils.acq.lineitem.receive.rollback.batch'],
3207 params: [this.authtoken, li_id_list],
3208 onresponse : function(r) {
3209 var resp = openils.Util.readResponse(r);
3210 self._updateProgressNumbers(resp, true);
3216 this._updateProgressNumbers = function(resp, reloadOnComplete, onComplete) {
3217 this.vlAgent.handleResponse(resp,
3218 function(resp, res) {
3219 if(reloadOnComplete)
3220 location.href = location.href;
3222 onComplete(resp, res);
3228 this._createPO = function(fields) {
3229 var wantall = (fields.create_from == "all");
3231 /* If we're a picklist or purchase order already and the user wants
3232 * all lineitems, we might have pages' worth of lineitems haven't all
3233 * been loaded yet, so getSelected() won't find them. The server,
3234 * however, should know about all our lineitems, so let's ask the
3235 * server for a complete list.
3240 true, function(list) {
3241 self._createPOFromLineitems(fields, list);
3242 }, /* id_list */ true, li_pre_po_states
3245 this._createPOFromLineitems(
3246 fields, this.getSelected(
3247 false, null, true /* id_list */, li_pre_po_states)
3252 this._createPOFromLineitems = function(fields, selected) {
3253 if (selected.length == 0) {
3254 alert(localeStrings.NO_LI_GENERAL);
3259 var po = new fieldmapper.acqpo();
3260 po.provider(this.createPoProviderSelector.attr("value"));
3261 po.ordering_agency(this.createPoAgencySelector.attr("value"));
3262 po.prepayment_required(fields.prepayment_required[0] ? true : false);
3264 // if we're creating assets, delay the asset creation
3265 // until after the PO is created. This will allow us to
3266 // use showAssetCreator() directly.
3268 fieldmapper.standardRequest(
3269 ["open-ils.acq", "open-ils.acq.purchase_order.create"],
3272 openils.User.authtoken,
3273 po, {lineitems : selected}
3275 onresponse : function(r) {
3276 var resp = openils.Util.readResponse(r);
3277 if (resp.complete) {
3278 // self.isPO is needed for showAssetCreator();
3279 self.isPO = resp.purchase_order.id();
3280 var redir = oilsBasePath + "/acq/po/view/" + self.isPO;
3281 if (fields.create_assets[0]) {
3282 self.showAssetCreator(
3283 function() {location.href = redir}
3286 location.href = redir;
3295 this.batchFundWidget = null;
3297 this.applyBatchLiFunds = function() {
3299 var liIds = this.getSelected().map(function(li) { return li.id(); });
3300 if(liIds.length == 0) return; // warn?
3303 batchFundUpdateDialog.show();
3305 if(!this.batchFundWidget) {
3306 this.batchFundWidget = new openils.widget.AutoFieldWidget({
3308 selfReference : true,
3309 labelFormat : fundLabelFormat,
3310 searchFormat : fundSearchFormat,
3311 searchFilter : {"active": "t"},
3312 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
3313 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
3314 dijitArgs : { "required": true, "labelType": "html" },
3317 this.batchFundWidget.build();
3320 dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
3321 dojo.connect(batchFundUpdateSubmit, 'onClick',
3324 // TODO: call .dry_run first to test thresholds
3325 fieldmapper.standardRequest(
3326 ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
3329 openils.User.authtoken,
3331 self.batchFundWidget.widget.attr('value')
3333 oncomplete : function(r) {
3334 var resp = openils.Util.readResponse(r);
3336 location.href = location.href;
3345 this._deleteLiList = function(list, idx) {
3346 if(idx == null) idx = 0;
3347 if(idx >= list.length) return;
3352 if (this.isPO && (li.state() == "on-order" || li.state() == "received")) {
3353 /* It makes little sense to delete a lineitem from a PO that has
3354 * already been marked 'on-order'. Especially if EDI is in use,
3355 * such a purchase order will probably have already been shipped
3356 * off to a vendor, and mucking with it at this point could leave
3357 * your data in a bad state that doesn't jive with reality.
3359 * I could see making this restriction even firmer.
3361 * I could also see adjusting the li state comparisons, extending
3362 * the comparison to the PO's state, and/or providing functions
3363 * that house the logic for comparing states in a single location.
3365 * Yes, this will be really annoying if you have selected a lot
3366 * of lineitems to cancel that have been ordered. You'll get a
3367 * confirm dialog for each one.
3370 if (!confirm(localeStrings.DEL_LI_FROM_PO)) {
3371 self._deleteLiList(list, ++idx); /* move on to next in list */
3376 fieldmapper.standardRequest(
3378 this.isPO ? 'open-ils.acq.purchase_order.lineitem.delete' : 'open-ils.acq.picklist.lineitem.delete'],
3380 params: [openils.User.authtoken, liId],
3381 oncomplete: function(r) {
3382 self.removeLineitem(liId);
3383 self._deleteLiList(list, ++idx);
3389 this.editOrderMarc = function(li) {
3391 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
3392 to true in about:config */
3394 if(openils.XUL.isXUL()) {
3395 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul','','chrome');
3397 win = window.open('/xul/server/cat/marcedit.xul','','chrome');
3401 record : {marc : li.marc(), "rtype": "bre"},
3403 label: 'Save Record', // XXX I18N
3404 func: function(xmlString) {
3406 fieldmapper.standardRequest(
3407 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
3409 params: [openils.User.authtoken, li],
3410 oncomplete: function(r) {
3411 openils.Util.readResponse(r);
3413 self.drawInfo(li.id())
3419 'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
3420 'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
3424 this._savePl = function(values) {
3426 (values.which == 'all'),
3427 function(list) { self._savePlFromLineitems(values, list); }
3431 this._savePlFromLineitems = function(values, selected) {
3432 openils.Util.show("acq-lit-generic-progress");
3434 if(values.new_name) {
3435 openils.acq.Picklist.create(
3436 {name: values.new_name},
3442 oilsBasePath + "/acq/picklist/view/" + id;
3447 } else if(values.existing_pl) {
3448 // update lineitems to use an existing picklist
3450 values.existing_pl, selected, 0,
3453 oilsBasePath + "/acq/picklist/view/" +
3460 this._updateLiState = function(values, state, state_filter) {
3461 progressDialog.show(true);
3463 (values.which == 'all'),
3465 self._updateLiStateFromLineitems(values, state, list);
3466 }, false /* id_list */, state_filter
3470 this._updateLiStateFromLineitems = function(values, state, selected) {
3471 if(!selected.length) {
3472 try { progressDialog.hide() } catch(E) {};
3473 alert(localeStrings.NO_LI_GENERAL);
3476 dojo.forEach(selected, function(li) {li.state(state);});
3477 self._updateLiList(null, selected, 0,
3478 // TODO consider inline updates for efficiency
3479 function() { location.href = location.href }
3483 this._updateLiList = function(pl, list, idx, oncomplete) {
3484 if(idx >= list.length) return oncomplete();
3486 if(pl != null) li.picklist(pl);
3487 litGenericProgress.update({maximum: list.length, progress: idx});
3488 new openils.acq.Lineitem({lineitem:li}).update(
3490 self._updateLiList(pl, list, ++idx, oncomplete);
3495 this._loadPOSelect = function() {
3496 if (!this.createPoProviderSelector) {
3497 var widget = new openils.widget.AutoFieldWidget({
3498 "fmField": "provider",
3500 "searchFilter": {"active": "t"},
3501 "parentNode": dojo.byId("acq-lit-po-provider"),
3503 "onChange": function() {
3505 self._updateCreatePoPrepayCheckbox(
3506 this.item.prepayment_required()
3512 widget.build(function(w) { self.createPoProviderSelector = w; });
3515 if (!this.createPoAgencySelector) {
3516 var widget = new openils.widget.AutoFieldWidget({
3517 "fmField": "ordering_agency",
3519 "parentNode": dojo.byId("acq-lit-po-agency"),
3520 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3522 widget.build(function(w) { self.createPoAgencySelector = w; });
3526 this.showRealCopyEditUI = function(li) {
3531 this._fetchLineitem(li.id(),
3533 li = self.liCache[li.id()] = fullLi;
3537 id : li.lineitem_details().map(
3538 function(item) { return item.eg_copy_id() }
3542 oncomplete : function(r) {
3544 var r_list = openils.Util.readResponse( r );
3545 for (var i = 0; i < r_list.length; i++) {
3546 var copy = r_list[i];
3547 var volId = copy.call_number();
3548 var volume = self.volCache[volId];
3550 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
3552 copy.call_number(volume);
3553 copyList.push(copy);
3556 xulG.volume_item_creator( { 'existing_copies' : copyList } );
3559 alert('error in oncomplete: ' + E);
3568 this.drawBibFinder = function(li) {
3571 var liWrapper = new openils.acq.Lineitem({lineitem:li});
3574 ['isbn', 'upc', 'issn', 'title', 'author'],
3576 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
3578 if(field == 'title' || field == 'author') {
3579 query += field +':' + val + ' ';
3581 query += 'identifier|' + field + ':' + val + ' ';
3588 oilsBasePath + '/acq/lineitem/findbib?query=' + encodeURIComponent(query),
3589 '', 'resizable,scrollbars=1,chrome');
3591 win.window.recordFound = function(bibId) {
3594 var attrs = li.attributes();
3595 li.attributes(null);
3596 li.eg_bib_id(bibId);
3598 fieldmapper.standardRequest(
3599 ["open-ils.acq", "open-ils.acq.lineitem.update"],
3601 "params": [openils.User.authtoken, li],
3603 "oncomplete": function(r) {
3604 if(openils.Util.readResponse(r)) {
3605 location.href = location.href;