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 if (li.cancel_reason() && typeof li.cancel_reason() == 'object') {
689 dojo.query('[name=cancel_reason]', row)[0].appendChild(
690 document.createTextNode(li.cancel_reason().label()));
693 // so we can scroll to it later
694 dojo.query('[name=bib-info-cell]', row)[0].id = 'li-title-ref-' + li.id();
697 liWrapper.findAttr("isbn", "lineitem_marc_attr_definition") ||
698 liWrapper.findAttr("upc", "lineitem_marc_attr_definition");
700 // XXX media prefix for added content
702 nodeByName("jacket", row).setAttribute(
703 "src", "/opac/extras/ac/jacket/small/" + identifier
707 nodeByName("liid", row).innerHTML += li.id();
710 openils.Util.show(nodeByName('catalog', row), 'inline');
711 nodeByName("catalog_link", row).onclick = this.generateMakeRecTab(li.eg_bib_id());
713 openils.Util.show(nodeByName('link_to_catalog', row), 'inline');
714 nodeByName("link_to_catalog_link", row).onclick = function() { self.drawBibFinder(li) };
717 if (li.queued_record()) {
718 this.pcrud.retrieve('vqbr', li.queued_record(),
720 oncomplete : function(r) {
721 var qrec = openils.Util.readResponse(r);
722 openils.Util.show(nodeByName('queue', row), 'inline');
723 var link = nodeByName("queue_link", row);
724 link.onclick = function() {
725 // open a new tab to the vandelay queue for this record
726 openils.XUL.newTabEasy(
727 oilsBasePath + '/vandelay/vandelay?qtype=bib&qid=' + qrec.queue()
735 nodeByName("worksheet_link", row).href =
736 oilsBasePath + "/acq/lineitem/worksheet/" + li.id() +
737 '?source=' + encodeURIComponent(location.pathname + location.search)
739 nodeByName("show_requests_link", row).href =
740 oilsBasePath + "/acq/picklist/user_request?lineitem=" + li.id() +
741 '?source=' + encodeURIComponent(location.pathname + location.search)
743 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
744 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
745 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
746 dojo.query('[name=expand_inline_copies]', row)[0].onclick =
747 function() {self.drawInlineCopies(li.id())};
749 this.drawOrderIdentSelector(li, row);
751 if (!this.skipInitialEligibilityCheck)
755 function(full) { self.setClaimPolicyControl(full, row) },
759 this.updateLiNotesCount(li, row);
761 // show which PO this lineitem is a member of
762 if(li.purchase_order() && !this.isPO) {
764 this.poCache[li.purchase_order()] =
765 this.poCache[li.purchase_order()] ||
766 fieldmapper.standardRequest(
767 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
769 this.authtoken, li.purchase_order(), {
770 "flesh_price_summary": true,
771 "flesh_provider" : true,
772 "flesh_lineitem_count": true
775 if(po && !this.isMeta) {
776 openils.Util.show(nodeByName('po', row), 'inline');
777 var link = nodeByName('po_link', row);
778 link.setAttribute('href', oilsBasePath +
779 '/acq/po/view/' + li.purchase_order() +
780 '?focus_li=' + li.id() +
781 '&source=' + encodeURIComponent(location.pathname + location.search)
783 link.innerHTML += po.name();
785 openils.Util.show(nodeByName('pro', row), 'inline');
786 link = nodeByName('pro_link', row);
787 link.setAttribute('href', oilsBasePath + '/conify/global/acq/provider/' + po.provider().id())
788 link.innerHTML += po.provider().code();
792 // show which picklist this lineitem is a member of
793 if(li.picklist() && (this.isPO || this.isMeta || this.isUni)) {
795 this.plCache[li.picklist()] =
796 this.plCache[li.picklist()] ||
797 fieldmapper.standardRequest(
798 ['open-ils.acq', 'open-ils.acq.picklist.retrieve.authoritative'],
799 {params: [this.authtoken, li.picklist()]});
801 if (pl.name() == "") {
802 openils.Util.show(nodeByName("bib_origin", row), "inline");
806 openils.Util.show(nodeByName('pl', row), 'inline');
807 var link = nodeByName('pl_link', row);
808 link.setAttribute('href', oilsBasePath +
809 '/acq/picklist/view/' + li.picklist() +
810 '?focus_li=' + li.id() +
811 '&source=' + encodeURIComponent(location.pathname + location.search)
813 link.innerHTML += pl.name();
818 var countNode = nodeByName('count', row);
819 var count = li.item_count() || 0;
820 if (typeof(this._copy_count_cb) == "function") {
821 this._copy_count_cb(li.id(), count);
823 countNode.innerHTML = count;
824 countNode.id = 'acq-lit-copy-count-label-' + li.id();
827 var priceInput = dojo.query('[name=price]', row)[0];
828 priceInput.value = li.estimated_unit_price() || '';
829 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
831 // show either "mark received" or "unreceive" as appropriate
832 this.updateLiState(li, row);
834 if (skip_final_placement) {
838 // the last LI may be rendered after the call to show('list'),
839 // so make sure it's focused if necessary.
840 if (this.focusLineitem == li.id())
844 this._liCountClaims = function(li) {
846 for (var i = 0; i < li.lineitem_details().length; i++)
847 total += li.lineitem_details()[i].claims().length;
851 this._findLiRow = function(li) {
852 return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
855 this.reconsiderClaimControl = function(li, row) {
856 if (!row) row = this._findLiRow(li);
857 var option = nodeByName("action_manage_claims", row);
858 var eligible = this.claimEligibleLidByLi[li.id()].length;
859 var count = this._liCountClaims(li);
861 option.disabled = !(count || eligible);
863 dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
864 option.onclick = function() { self.claimDialog.show(li); };
867 this.clearEligibility = function(li) {
868 this.claimEligibleLidByLi[li.id()] = [];
870 if (li.lineitem_details()) {
871 li.lineitem_details().forEach(
872 function(lid) { delete self.claimEligibleLid[lid.id()]; }
876 if (this.copyCache) {
878 for (var k in this.copyCache) {
879 if (this.copyCache[k].lineitem() == li.id())
883 function(k) { delete self.claimEligibleLid[k]; }
888 this.applyOrderIdentValues = function() {
889 this._identValuesInFlight =
890 openils.Util.objectProperties(this.liCache).length;
891 for (var liId in this.liCache) {
892 this._applyOrderIdentValue(this.liCache[liId]);
896 // returns true if request was sent
897 this._applyOrderIdentValue = function(li, oncomplete) {
900 console.log('applying ident value for lineitem ' + li.id());
903 var row = dojo.query('[li=' + li.id() + ']')[0];
905 // find the selected ident value
906 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
907 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
908 var name = typeSel.options[typeSel.selectedIndex].value;
909 var val = typeSel._cbox.attr('value');
911 console.log("selected ident is " + val);
913 // it differs from the existing ident value, update it
914 var oldIdent = self.getLiOrderIdent(li);
916 oldIdent.attr_name() == name &&
917 oldIdent.attr_value() == val) {
918 console.log('selected ident attr matches existing attr');
919 if (--this._identValuesInFlight == 0) {
920 if (oncomplete) oncomplete(li);
921 else location.href = location.href;
926 // see if the selected ident value is represented
927 // by an existing lineitem attr
930 typeSel._cbox.store.fetch({
931 query : {attr_value : val},
932 onItem : function(item) {
933 console.log('found existing attr for ident value');
934 args.source_attr_id = li.attributes().filter(
935 function(attr) { return attr.id() == item.id[0] }
941 if (!args.source_attr_id) {
942 // user entered new text in the combobox
943 // so we need to create a new attr
944 console.log('creating new ident attr');
945 args.lineitem_id = li.id();
946 args.attr_name = name;
947 args.attr_value = val;
950 fieldmapper.standardRequest(
951 ['open-ils.acq', 'open-ils.acq.lineitem.order_identifier.set'],
953 params : [openils.User.authtoken, args],
954 oncomplete : function() {
955 console.log('order_ident oncomplete');
956 if (--self._identValuesInFlight == 0) {
957 if (oncomplete) oncomplete(li);
958 else location.href = location.href;
960 console.log(self._identValuesInFlight + ' still in flight');
968 this.getLiOrderIdent = function(li) {
969 var attrs = li.attributes();
970 if (!attrs) return null;
974 attr.attr_type() == 'lineitem_local_attr_definition' &&
975 openils.Util.isTrue(attr.order_ident())
981 this.drawOrderIdentSelector = function(li, row) {
983 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
984 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
986 var attrs = li.attributes();
988 // limit to MARC attr defs
989 attrs = attrs.filter(
991 return (attr.attr_type() == 'lineitem_marc_attr_definition');
995 var identAttr = this.getLiOrderIdent(li);
998 // collect the values for each type of identifier
999 // find a reasonable default identifier type to render
1003 dojo.forEach(['isbn', 'upc', 'issn'],
1006 // collect the values for this attr name
1007 values[name] = attrs.filter(
1009 return (attr.attr_name() == name)
1013 // select a reasonable default name in the type-selector
1017 if (identAttr.attr_name() == name)
1019 } else if (values[name].length) {
1024 dojo.forEach(typeSel.options, function(opt) {
1025 if (opt.value == name) {
1026 opt.selected = true;
1035 function updateOrderIdent(val) {
1036 self._identValuesInFlight = 1;
1037 self._applyOrderIdentValue(
1040 self.refreshLineitem(li);
1045 // replace the ident combobox with a new
1046 // one for the selected ident type
1047 function changeComboBox(sel) {
1048 var name = sel.options[sel.selectedIndex].value;
1050 var td = dojo.query('[name=order_ident_value]', row)[0];
1051 if (td.childNodes[0])
1052 dojo.destroy(td.childNodes[0]);
1054 var store = new dojo.data.ItemFileWriteStore({
1055 data : acqlia.toStoreData(values[name])
1058 var cbox = new dijit.form.ComboBox(
1060 labelAttr : 'attr_value',
1061 searchAttr : 'attr_value'
1063 dojo.create('div', {}, td)
1068 // set the value for the cbox
1069 if (values[name].length) {
1070 var orderIdent = self.getLiOrderIdent(li);
1072 if (orderIdent && orderIdent.attr_name() == name) {
1073 cbox.attr('value', orderIdent.attr_value());
1075 cbox.attr('value', values[name][0].attr_value());
1079 if (!self.orderIdentAllowed)
1080 cbox.attr('disabled', true);
1083 cbox._lineitem = li;
1084 dojo.connect(cbox, 'onChange', updateOrderIdent);
1087 changeComboBox(typeSel); // force the initial draw
1088 typeSel.onchange = function() {changeComboBox(typeSel)};
1091 this.testOrderIdentPerms = function(org, callback) {
1093 new openils.User().getPermOrgList(
1094 'ACQ_SET_LINEITEM_IDENTIFIER',
1096 console.log('found orgs = ' + orgs);
1097 for (var i = 0; i < orgs.length; i++) {
1098 if (Number(orgs[i]) == Number(org)) {
1099 self.orderIdentAllowed = true;
1100 if (callback) callback();
1104 if (callback) callback();
1110 this.checkClaimEligibility = function(li, callback, row) {
1111 /* Assume always eligible, i.e. from this interface we don't care about
1112 * claim eligibility any more. this is where the user would force a
1114 this.clearEligibility(li);
1115 this.claimEligibleLidByLi[li.id()] = li.lineitem_details().map(
1116 function(lid) { return lid.id(); }
1118 li.lineitem_details().forEach(
1119 function(lid) { self.claimEligibleLid[lid.id()] = true; }
1121 this.reconsiderClaimControl(li, row);
1122 if (callback) callback(li);
1124 this.clearEligibility(li);
1125 fieldmapper.standardRequest(
1126 ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
1127 "params": [openils.User.authtoken, {"lineitem": li.id()}],
1129 "onresponse": function(r) {
1130 if (r = openils.Util.readResponse(r)) {
1131 self.claimEligibleLidByLi[li.id()].push(
1134 self.claimEligibleLid[r.lineitem_detail()] = true;
1137 "oncomplete": function() {
1138 self.reconsiderClaimControl(li, row);
1139 if (typeof(callback) == "function")
1147 this.updateLiNotesCount = function(li, row) {
1148 if (!row) row = this._findLiRow(li);
1150 var has_notes = (li.lineitem_notes().filter(
1151 function(o) { return Boolean (o.alert_text()); }
1154 /* U+2691 is the code point for a filled-in flag character */
1155 nodeByName("notes_alert_flag", row).innerHTML =
1156 has_notes ? "⚑" : "";
1157 nodeByName("noteslink", row).style.fontStyle =
1158 has_notes ? "italic" : "normal";
1159 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
1162 /* XXX NOT related to _updateLiState(). rethink */
1163 this.updateLiState = function(li, row) {
1164 if (!row) row = this._findLiRow(li);
1166 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
1167 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
1169 // always allow access to LI history
1170 nodeByName('action_view_history', row).onclick =
1171 function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
1173 /* handle row coloring for based on LI state */
1174 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1175 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
1177 // Expose invoice actions for any lineitem that is linked to a PO
1178 if (li.purchase_order()) {
1179 openils.Util.show(nodeByName("invoices_span", row), "inline");
1180 var link = nodeByName("invoices_link", row);
1181 link.onclick = function() {
1182 openils.XUL.newTabEasy(
1183 oilsBasePath + "/acq/search/unified?so=" +
1184 base64Encode({"jub":[{"id": li.id()}]}) + "&rt=invoice"
1192 * If we haven't fleshed the lineitem_details, default to allowing access to the
1193 * holdings maintenence actions. The alternative is to flesh LIDs on every lineitem,
1194 * but that will add to page render time. Let's see if this will suffice...
1196 var lids = li.lineitem_details();
1198 (lids && !lids.filter(function(lid) { return lid.eg_copy_id() })[0] )) {
1200 actUpdateBarcodes.disabled = false;
1201 actUpdateBarcodes.onclick = function() {
1202 self.showRealCopyEditUI(li);
1203 nodeByName("action_none", row).selected = true;
1205 actHoldingsMaint.disabled = false;
1206 actHoldingsMaint.onclick =
1207 self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
1210 var state_cell = nodeByName("li_state_" + li.state(), row);
1212 // re-hide any state label nodes which may have been un-hidden
1213 // through previous actions.
1214 dojo.query('[state-label]', row).forEach(function(node) {
1215 openils.Util.hide(node)
1218 if (li.state() == 'cancelled') {
1219 if(typeof li.cancel_reason() == "object") {
1221 // clear the stock "Canceled" label, since we have more
1222 // information to replace it with.
1223 state_cell.innerHTML = '';
1225 var holds_state = dojo.create(
1227 "style": "border-bottom: 1px dashed #000;",
1228 "innerHTML": li.cancel_reason().label()
1229 }, state_cell, "only"
1233 "label": "<em>" + li.cancel_reason().label() +
1234 "</em><br />" + li.cancel_reason().description(),
1235 "connectId": [holds_state]
1236 }, dojo.create("span", null, state_cell, "last")
1239 if (li.cancel_reason().keep_debits() == 't') {
1240 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1241 openils.Util.addCSSClass(row, "oils-acq-li-state-delayed");
1244 console.log('li cancel_reason is un-fleshed. Please fix');
1248 openils.Util.show(state_cell);
1252 this._setAlertStore = function() {
1253 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
1255 "data": acqliat.toStoreData(
1258 "owning_lib": aou.orgNodeTrail(
1259 aou.findOrgUnit(openils.User.user.ws_ou())
1260 ).map(function(o) { return o.id(); })
1266 acqLitAlertAlertText.setValue(); /* make the store "live" */
1267 acqLitAlertAlertText._store_ready = true;
1271 * Draws and shows the lineitem notes pane
1273 this.drawLiNotes = function(li) {
1275 this.focusLineitem = li.id();
1277 if (!acqLitAlertAlertText._store_ready)
1278 this._setAlertStore();
1281 li.lineitem_notes().sort(
1283 if(a.edit_time() < b.edit_time()) return 1;
1289 while(this.liNotesTbody.childNodes[0])
1290 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
1293 acqLitCreateNoteSubmit.onClick = function() {
1294 var value = acqLitCreateNoteText.attr('value');
1296 var note = new fieldmapper.acqlin();
1299 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
1302 note.lineitem(li.id());
1304 self.updateLiNotes(li, note);
1305 acqLitCreateNoteVendorPublic.attr("checked", false);
1306 acqLitCreateNoteText.attr("value", "");
1309 acqLitCreateAlertSubmit.onClick = function() {
1310 if (!acqLitAlertAlertText.item) {
1311 alert(localeStrings.ALERT_UNSELECTED);
1315 var alert_text = new fieldmapper.acqliat().fromStoreItem(
1316 acqLitAlertAlertText.item
1318 var value = acqLitAlertNoteValue.attr("value") || "";
1320 var note = new fieldmapper.acqlin();
1322 note.lineitem(li.id());
1324 note.alert_text(alert_text);
1326 self.updateLiNotes(li, note);
1329 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
1333 * Draws a single lineitem note in the notes pane
1335 this.addLiNote = function(li, note) {
1336 if(note.isdeleted()) return;
1338 var row = self.liNotesRow.cloneNode(true);
1339 nodeByName("value", row).innerHTML = note.value();
1340 var alert_node = nodeByName("alert_code", row);
1341 if (note.alert_text()) {
1342 alert_node.innerHTML = dojo.string.substitute(
1344 aou.findOrgUnit(note.alert_text().owning_lib()).shortname(),
1345 note.alert_text().code()
1348 if (note.alert_text().description()) {
1351 "connectId": [alert_node],
1352 "label": note.alert_text().description()
1353 }, dojo.create("span", null, alert_node, "after")
1358 if (openils.Util.isTrue(note.vendor_public()))
1359 nodeByName("vendor_public", row).innerHTML =
1360 localeStrings.VENDOR_PUBLIC;
1362 nodeByName("delete", row).onclick = function() {
1363 note.isdeleted(true);
1364 self.liNotesTbody.removeChild(row);
1365 self.updateLiNotes(li);
1368 if(note.edit_time()) {
1369 nodeByName("edit_time", row).innerHTML =
1370 dojo.date.locale.format(
1371 dojo.date.stamp.fromISOString(note.edit_time()),
1372 {formatLength:'short'});
1375 self.liNotesTbody.appendChild(row);
1379 * Updates any new/changed/deleted notes on the server
1381 this.updateLiNotes = function(li, newNote) {
1387 notes = li.lineitem_notes().filter(
1389 if(note.ischanged() || note.isnew() || note.isdeleted())
1395 if(notes.length == 0) return;
1396 progressDialog.show();
1398 fieldmapper.standardRequest(
1399 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
1401 params : [this.authtoken, notes],
1402 onresponse : function(r) {
1403 var resp = openils.Util.readResponse(r);
1408 // remove the old changed notes
1410 dojo.forEach(li.lineitem_notes(),
1412 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
1416 li.lineitem_notes(list);
1419 progressDialog.hide();
1420 self.updateLiNotesCount(li);
1421 self.drawLiNotes(li);
1425 progressDialog.update(resp);
1426 var newnote = resp.note;
1428 if(!newnote.isdeleted()) {
1429 newnote.isnew(false);
1430 newnote.ischanged(false);
1431 li.lineitem_notes().push(newnote);
1438 this.updateLiPrice = function(input, li) {
1440 var price = input.value;
1441 if(Number(price) == Number(li.estimated_unit_price())) return;
1443 fieldmapper.standardRequest(
1444 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
1445 { async : false, // redundant w/ timeout
1447 params : [this.authtoken, li.id(), price],
1448 oncomplete : function(r) {
1449 openils.Util.readResponse(r);
1450 li.estimated_unit_price(price); // update local copy
1453 * If this is a PO and every visible lineitem has a price,
1454 * check again to see if this PO can be activated. Note that
1455 * every visible lineitem having a price does not guarantee it can
1456 * be activated, which is why we still make the call. Having a price
1457 * set for every visiable lineitem is just the lowest barrier to entry.
1460 var priceNodes = dojo.query('[name=price]', dojo.byId('acq-lit-tbody'));
1462 dojo.forEach(priceNodes, function(node) { if (node.value == '') allSet = false});
1463 if (allSet) checkCouldActivatePo();
1470 this.removeLineitem = function(liId) {
1471 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
1472 delete this.liCache[liId];
1473 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
1476 this.drawInfo = function(liId) {
1477 this.focusLineitem = liId;
1478 if (!this._isRelatedViewer) {
1479 var d = dojo.byId("acq-lit-info-related");
1480 if (!this.relCache[liId]) {
1481 fieldmapper.standardRequest(
1484 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
1487 "params": [openils.User.authtoken, liId],
1488 "onresponse": function(r) {
1489 self.relCache[liId] = openils.Util.readResponse(r);
1490 nodeByName("related_number", d).innerHTML =
1491 self.relCache[liId];
1493 self.relCache[liId] >1 ? "show" : "hide"
1499 nodeByName("related_number", d).innerHTML = this.relCache[liId];
1500 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
1505 openils.acq.Lineitem.fetchAttrDefs(
1507 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
1512 this.toggleInlineCopies = function() {
1513 // if any inline copies are not displayed,
1514 // display them all otherwise, hide them all.
1516 var displayAll = false;
1518 for (var liId in this.liCache) {
1519 if (!this.inlineCopiesVisible(liId)) {
1525 for (var liId in this.liCache) {
1526 var row = dojo.byId('acq-inline-copies-row-' + liId);
1528 if (!row || row._hidden) {
1529 this.drawInlineCopies(liId);
1531 } else { // hide all
1533 // drawInlineCopies() on a visible row will hide it.
1534 this.drawInlineCopies(liId);
1541 this.inlineCopiesVisible = function(liId) {
1542 var row = dojo.byId('acq-inline-copies-row-' + liId);
1543 return (row && !row._hidden);
1546 this.refreshInlineCopies = function(all, reFetch) {
1548 var liIds = this.inlineCopiesNeedingRefresh;
1549 if (all) liIds = openils.Util.objectProperties(liCache);
1550 liIds.forEach(function(liId) {
1551 if (self.inlineCopiesVisible(liId)) {
1552 self.drawInlineCopies(liId, reFetch); // hide
1553 self.drawInlineCopies(liId, reFetch); // re-draw
1558 // draw inline copy table. if the table is
1559 // already visible, hide the table as-is
1560 // reFetch forces a retrieval of the lineitem and
1561 // copies from the server. otherwise the locally
1562 // cached version of each is used.
1563 this.drawInlineCopies = function(liId, reFetch) {
1566 // find or create the row where the inline copies table will live
1567 var containerRow = dojo.byId('acq-inline-copies-row-' + liId);
1568 var liRow = dojo.query('[li=' + liId + ']')[0];
1570 if (!containerRow) {
1572 // build the inline copies container row and add it to
1573 // the DOM directly after the primary lineitem row
1575 containerRow = self.inlineCopyContainer.cloneNode(true);
1576 containerRow.id = 'acq-inline-copies-row-' + liId;
1578 if (liRow.nextSibling) {
1579 self.tbody.insertBefore(containerRow, liRow.nextSibling);
1581 self.tbody.appendChild(containerRow);
1586 // toggle the visible state
1587 containerRow._hidden = !containerRow._hidden;
1588 openils.Util.toggle(containerRow, 'table-row');
1590 if (containerRow._hidden) return; // hide only
1593 var handler = function(li) {
1595 var tbody = dojo.query(
1596 '[name=acq-li-inline-copies-tbody]',
1599 // reset the table before adding copy rows
1600 while (tbody.childNodes[0])
1601 tbody.removeChild(tbody.childNodes[0]);
1603 if(li.lineitem_details().length == 0) {
1605 self.inlineNoCopies.cloneNode(true));
1606 return; // no copies to show
1609 // add a row to the inline copy table for each copy
1610 dojo.forEach(li.lineitem_details(),
1612 var row = self.inlineCopyTemplate.cloneNode(true);
1613 tbody.appendChild(row);
1614 self.addInlineCopy(li, copy, row);
1619 this._fetchLineitem(liId, handler, reFetch);
1622 /** Draw read-only copy widgets for inline copies */
1623 this.addInlineCopy = function(li, copy, row) {
1626 dojo.forEach(liDetailFields,
1629 var widget = new openils.widget.AutoFieldWidget({
1632 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1633 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1634 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1636 parentNode : dojo.query('[name=' + field + ']', row)[0],
1645 /* For a given list of lineitem ids, build a list of full lineitems
1646 * re-using the fetching logic that is otherwise typical to use in this
1649 * If we've already got a lineitem in the cache, just use that.
1651 * Once we've built a list of lineitems, call callback(thatlist).
1653 this.fetchLineitemsById = function(id_list, callback) {
1654 var total = id_list.length;
1655 var result_list = [];
1657 var inner = function(li) {
1658 result_list.push(li)
1660 callback(result_list);
1663 id_list.forEach(function(id) { self._fetchLineitem(id, inner); });
1666 this._fetchLineitem = function(liId, handler, force) {
1668 var li = this.liCache[liId];
1669 if(li && li.marc() && li.lineitem_details() && !force)
1672 fieldmapper.standardRequest(
1673 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
1676 params: [self.authtoken, liId, {
1678 flesh_cancel_reason: true,
1679 flesh_li_details: true,
1681 flesh_fund_debit: true }],
1683 oncomplete: function(r) {
1684 var li = openils.Util.readResponse(r);
1685 self.liCache[liId] = li;
1692 this._drawInfo = function(li) {
1694 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
1696 if(li.eg_bib_id()) {
1697 openils.Util.hide('acq-lit-marc-order-record-label');
1698 openils.Util.hide(acqLitEditOrderMarc.domNode);
1699 openils.Util.show('acq-lit-marc-real-record-label');
1701 openils.Util.show('acq-lit-marc-order-record-label');
1702 openils.Util.show(acqLitEditOrderMarc.domNode);
1703 openils.Util.hide('acq-lit-marc-real-record-label');
1706 this.drawMarcHTML(li);
1707 this.infoTbody = dojo.byId('acq-lit-info-tbody');
1710 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
1711 while(this.infoTbody.childNodes[0])
1712 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
1714 for(var i = 0; i < li.attributes().length; i++) {
1715 var attr = li.attributes()[i];
1716 var row = this.infoRow.cloneNode(true);
1718 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
1719 var name = openils.acq.Lineitem.attrDefs[type].filter(
1721 return (a.code() == attr.attr_name());
1723 ).pop().description();
1725 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
1726 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
1727 this.infoTbody.appendChild(row);
1730 if (!this._isRelatedViewer) {
1731 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
1732 oilsBasePath + "/acq/lineitem/related/" + li.id();
1735 // if a top scroll point is defined, jump up to it here
1736 var node = dojo.byId('oils-scroll-to-top');
1737 if (node) dijit.scrollIntoView(node);
1740 this.generateMakeRecTab = function(bib_id,default_view, row) {
1744 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
1747 show_nav_buttons : true,
1748 show_print_button : true,
1749 opac_url : xulG.url_prefix('opac_rdetail|' + bib_id),
1750 default_view : default_view
1754 if(row) nodeByName("action_none", row).selected = true;
1758 this.drawMarcHTML = function(li) {
1759 var params = [null, true, li.marc()];
1761 params = [li.eg_bib_id(), true];
1763 fieldmapper.standardRequest(
1764 ['open-ils.search', 'open-ils.search.biblio.record.html'],
1767 oncomplete: function(r) {
1768 dojo.byId('acq-lit-marc-div').innerHTML =
1769 openils.Util.readResponse(r);
1775 this.drawCopies = function(liId, force_fetch) {
1776 this.focusLineitem = liId;
1777 if (typeof force_fetch == "undefined")
1778 force_fetch = false;
1780 var cgi = new openils.CGI();
1781 var source = cgi.param('source');
1782 if (source && source.match(/invoice/)) {
1783 // got here from the invoice page, show the 'return-to-invoice' button
1784 var cgi = new openils.CGI({url : source});
1785 cgi.param('focus_li', liId);
1786 openils.Util.show(dojo.byId('acq-lit-copies-back-to-invoice-button-wrapper'), 'inline');
1787 var button = dojo.byId('acq-lit-copies-back-to-invoice-button');
1788 button.onclick = function() { location.href = cgi.url() };
1791 openils.acq.Lineitem.fetchAndRender(liId, {},
1792 function(li, html) {
1793 dojo.byId('acq-lit-copies-li-summary').innerHTML = html;
1797 this.show('copies');
1799 this.copyCache = {};
1800 this.copyWidgetCache = {};
1801 this.oldCopyWidgetCache = {};
1802 this.virtDfaCounts = {};
1803 this.realDfaCache = {};
1806 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
1807 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
1808 acqLitCopyCountInput.attr('value', '0');
1810 if (this.isPO && PO && PO.order_date()) {
1811 // prevent adding copies to activated POs
1812 acqLitCopyCountInput.attr('disabled', true);
1813 acqLitAddCopyCount.attr('disabled', true);
1816 while(this.copyTbody.childNodes[0])
1817 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
1819 this._drawBatchCopyWidgets();
1821 this._drawDistribApplied(liId);
1823 this._fetchDistribFormulas(
1825 openils.acq.Lineitem.fetchAttrDefs(
1827 self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch);
1834 this._saveDistribAppliedTemplates = function() {
1835 if (!this._appliedDistribTemplate) {
1836 this._appliedDistribTemplate =
1837 dojo.byId("acq-lit-distrib-applied-tbody").
1838 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
1839 dojo.attr(this._appliedDistribTemplate, "id");
1843 this._drawDistribApplied = function(liId) {
1844 /* Build this table while hidden to prevent rendering artifacts */
1845 openils.Util.hide("acq-lit-distrib-applied-tbody");
1847 this._saveDistribAppliedTemplates();
1849 /* Remove any rows in the table from previous populations */
1850 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
1851 forEach(dojo.destroy);
1853 /* Unregister all dijits previously created (for some reason this isn't
1854 * covered by the above destroy calls). */
1855 dijit.registry.forEach(
1856 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
1859 /* Populate the table with our liId */
1861 fieldmapper.standardRequest(
1863 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
1866 "params": [self.authtoken, liId],
1867 "onresponse": function(r) {
1868 var dfa = openils.Util.readResponse(r);
1871 self.realDfaCache[dfa.id()] = dfa;
1872 self._drawDistribAppliedUnit(dfa);
1875 "oncomplete": function() {
1876 /* Reveal built table */
1879 "acq-lit-distrib-applied-tbody", "table-row-group"
1887 this._drawDistribAppliedUnit = function(dfa) {
1888 var new_row = false;
1889 var row = dojo.query(
1890 'tr[formula="' + dfa.formula().id() + '"]',
1891 "acq-lit-distrib-applied-tbody"
1896 row = dojo.clone(this._appliedDistribTemplate);
1897 dojo.attr(row, "formula", dfa.formula().id());
1898 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
1901 var td = dojo.query("td", row)[0];
1903 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1904 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1907 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1909 new dijit.form.Button(
1911 "onClick": function() {
1912 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1913 self.deleteDfa(dfa);
1916 /* XXX I /cannot/ make the following work in as a CSS class
1917 * for some reason. So frustrating... */
1918 "style": function(id) {
1920 "font-weight: bold; color: #c00;" :
1922 }(dfa.id()) + "margin: 0 6px;display: inline;"
1923 }, "dfa-button-" + dfa.id()
1927 "connectId": ["dfa-button-" + dfa.id()],
1928 "label": dojo.string.substitute(
1929 localeStrings.DFA_TIP, dfa.id() > 0 ? [
1930 openils.User.formalName(dfa.creator()),
1931 dojo.date.locale.format(
1932 dojo.date.stamp.fromISOString(dfa.create_time()),
1933 {"formatLength":"short"}
1935 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
1937 }, "dfa-tip-" + dfa.id()
1941 this.deleteDfa = function(dfa) {
1942 if (dfa.id() > 0) { /* real */
1943 this.pcrud.eliminate(
1946 "oncomplete": function() {
1947 self._removeDistribApplied(dfa.id());
1948 delete self.realDfaCache[dfa.id()];
1952 } else { /* virtual */
1953 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
1954 this.virtDfaCounts[dfa.formula().id()] = 0;
1955 /* hasn't been saved yet, so no need to do anything server side */
1956 this._removeDistribApplied(dfa.id());
1961 this._removeDistribApplied = function(dfaId) {
1962 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
1963 dijit.registry.forEach(
1964 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
1966 this._removeDistribAppliedEmptyRows();
1969 this._removeAllDistribAppliedVirtual = function() {
1970 /* Unregister dijits */
1971 dijit.registry.forEach(
1972 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
1974 this._removeDistribAppliedEmptyRows();
1977 this._removeDistribAppliedEmptyRows = function() {
1978 /* Remove any rows with no DFA at all */
1979 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
1981 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
1987 * Insert a new row into the distribution formula selection form
1989 this._addDistribFormulaRow = function() {
1992 if (!self.distribForms) {
1993 // no formulas, hide the form
1994 openils.Util.hide('acq-lit-distrib-formula-table');
1998 if(!this.distribFormulaTemplate)
1999 this.distribFormulaTemplate =
2000 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
2002 var row = this.distribFormulaTemplate.cloneNode(true);
2003 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
2005 this.dfSelector = new dijit.form.FilteringSelect(
2006 {"labelAttr": "dynLabel", "labelType": "html"},
2007 nodeByName("selector", row)
2009 this._updateFormulaStore();
2010 this.dfSelector.fetchProperties =
2011 {"sort": [{"attribute": "use_count", "descending": true}]};
2013 var apply = new dijit.form.Button(
2014 {"label": localeStrings.APPLY},
2015 nodeByName('set_button', row)
2018 var reset = new dijit.form.Button(
2019 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
2020 nodeByName("reset_button", row)
2023 dojo.connect(apply, 'onClick',
2025 var form_id = self.dfSelector.attr("value");
2026 if(!form_id) return;
2027 self._applyDistribFormula(form_id);
2028 reset.attr("disabled", false);
2032 dojo.connect(reset, 'onClick',
2034 self.restoreCopyFieldsBeforeDF();
2035 self.virtDfaCounts = {};
2036 self.virtDfaId = -1;
2038 self._updateFormulaStore();
2039 self._removeAllDistribAppliedVirtual();
2040 reset.attr("disabled", "true");
2047 * Applies a distrib formula to the current set of copies
2049 this._applyDistribFormula = function(formula) {
2050 if(!formula) return;
2052 formula = this.distribForms.filter(
2053 function(form) { return form.id() == formula; }
2056 var copyRows = dojo.query('tr', self.copyTbody);
2058 if (this.dfeOffset >= copyRows.length) {
2059 alert(localeStrings.OUT_OF_COPIES);
2063 var entries_applied = 0;
2065 var rowIndex = this.dfeOffset;
2066 rowIndex < copyRows.length;
2070 var row = copyRows[rowIndex];
2071 var copy_id = row.getAttribute('copy_id');
2072 var copyWidgets = this.copyWidgetCache[copy_id];
2073 var entryIndex = this.dfeOffset;
2076 // find the correct entry for the current row
2077 dojo.forEach(formula.entries(),
2080 entryIndex += e.item_count();
2081 if(entryIndex > rowIndex)
2089 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
2090 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
2093 this.saveCopyFieldsBeforeDF(copy_id);
2094 this._copy_fields_for_acqdf.forEach(
2096 if(entry[field]()) {
2097 copyWidgets[field].attr('value', (entry[field]()));
2104 if (entries_applied) {
2105 this.virtDfaCounts[formula.id()] =
2106 ++(this.virtDfaCounts[formula.id()]) || 1;
2107 this._updateFormulaStore();
2108 this._drawDistribAppliedUnit(
2110 var dfa = new acqdfa();
2111 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
2114 this.dfeOffset += entries_applied;
2119 * This function updates the DF store for the dropdown so that use_counts
2120 * can reflect DF applications from this session before they're saved
2123 this._updateFormulaStore = function() {
2124 this.dfSelector.store = new dojo.data.ItemFileReadStore(
2126 "data": self._labelFormulasWithCounts(
2127 acqdf.toStoreData(self.distribForms)
2133 this.saveCopyFieldsBeforeDF = function(copy_id) {
2135 if (!this.oldCopyWidgetCache[copy_id]) {
2136 var copyWidgets = this.copyWidgetCache[copy_id];
2138 this.oldCopyWidgetCache[copy_id] = {};
2139 this._copy_fields_for_acqdf.forEach(
2141 self.oldCopyWidgetCache[copy_id][f] =
2142 copyWidgets[f].attr("value");
2148 this.restoreCopyFieldsBeforeDF = function() {
2150 for (var copy_id in this.oldCopyWidgetCache) {
2151 this._copy_fields_for_acqdf.forEach(
2153 self.copyWidgetCache[copy_id][f].attr(
2154 "value", self.oldCopyWidgetCache[copy_id][f]
2161 this._labelFormulasWithCounts = function(store_data) {
2162 for (var key in store_data.items) {
2163 var obj = store_data.items[key];
2164 obj.use_count = Number(obj.use_count); /* needed for sorting */
2166 if (this.virtDfaCounts[obj.id])
2167 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
2169 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
2170 obj.use_count + "]</span> " + obj.name;
2176 * This method formerly would not refetch the DF formulas if they'd been
2177 * loaded already, but now it always re-fetches, since use_count changes.
2179 /** TODO: port distrib-formula selector to autofieldwidget+pcrud/dojo store */
2180 this._fetchDistribFormulas = function(onload) {
2181 fieldmapper.standardRequest(
2183 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
2186 "params": [openils.User.authtoken, 0, 500],
2187 "oncomplete": function(r) {
2188 self.distribForms = openils.Util.readResponse(r);
2189 if(!self.distribForms || self.distribForms.length == 0) {
2190 self.distribForms = [];
2192 self._addDistribFormulaRow();
2199 this._drawBatchCopyWidgets = function() {
2200 var row = this.copyBatchRow;
2201 dojo.forEach(liDetailBatchFields,
2203 if(self.copyBatchRowDrawn) {
2204 self.copyBatchWidgets[field].attr('value', null);
2206 var args = self.afwCopyFieldArgs(field, "CREATE_PICKLIST");
2207 args.parentNode = dojo.query('[name='+field+']', row)[0];
2209 var widget = new openils.widget.AutoFieldWidget(args);
2212 if (field == "fund" && w.store)
2213 self._ensureCSSFundClasses(w.store);
2214 self.copyBatchWidgets[field] = w;
2217 if (field == "fund") {
2219 widget.widget, "onChange", function(val) {
2220 self._updateFundSelectorStyle(widget, val);
2227 this.copyBatchRowDrawn = true;
2230 this.batchCopyUpdate = function() {
2232 for(var k in this.copyWidgetCache) {
2233 var cache = this.copyWidgetCache[k];
2234 dojo.forEach(liDetailBatchFields, function(f) {
2235 var newval = self.copyBatchWidgets[f].attr('value');
2236 if(newval) cache[f].attr('value', newval);
2241 this._drawCopies = function(li) {
2244 // this button sets the total number of copies for a given lineitem
2245 acqLitAddCopyCount.onClick = function() {
2246 var count = acqLitCopyCountInput.attr('value');
2249 while(self.copyCount() < count)
2252 // delete rows if necessary
2253 var diff = self.copyCount() - count;
2255 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
2256 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
2257 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
2259 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2265 if(li.lineitem_details().length > 0) {
2266 dojo.forEach(li.lineitem_details(),
2268 self.addCopy(li, copy);
2276 this.copyCount = function() {
2278 for(var id in this.copyCache) {
2279 if(!this.copyCache[id].isdeleted())
2285 this.virtCopyId = -1;
2286 this.addCopy = function(li, copy) {
2287 var row = this.copyRow.cloneNode(true);
2288 this.copyTbody.appendChild(row);
2292 copy = new fieldmapper.acqlid();
2294 copy.id(this.virtCopyId--);
2295 copy.lineitem(li.id());
2298 this.copyCache[copy.id()] = copy;
2299 row.setAttribute('copy_id', copy.id());
2300 self.copyWidgetCache[copy.id()] = {};
2302 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2304 var rcvr = copy.receiver();
2306 if (!userCache[rcvr]) {
2307 if(rcvr == openils.User.user.id()) {
2308 userCache[rcvr] = openils.User.user;
2310 userCache[rcvr] = fieldmapper.standardRequest(
2311 ['open-ils.actor', 'open-ils.actor.user.retrieve'],
2312 {params: [openils.User.authtoken, rcvr]}
2316 dojo.query('[name=receiver]', row)[0].innerHTML = userCache[rcvr].usrname();
2319 dojo.forEach(liDetailFields,
2322 if (field == "fund") {
2323 searchFilter = (copy.fund() ?
2324 {"-or": {"active": "t", "id": copy.fund()}} :
2327 searchFilter = null;
2330 var readOnly = false;
2332 // TODO: Add support for changing the owning_lib after real copies have been made.
2333 // owning_lib is order data as much as its item data
2334 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
2338 // TODO: add support for changing the fund after debits have been created
2339 // Note: invoicing allows the change
2340 if(copy.fund_debit() && field == 'fund') {
2345 var widget = new openils.widget.AutoFieldWidget({
2348 labelFormat : (field == 'fund') ? fundLabelFormat : null,
2349 searchFormat : (field == 'fund') ? fundSearchFormat : null,
2350 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
2351 searchFilter : searchFilter,
2352 noCache: (field == "fund"),
2354 parentNode : dojo.query('[name='+field+']', row)[0],
2355 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2356 readOnly : readOnly,
2357 orgDefaultsToWs : true
2361 // make sure we capture the value from any async widgets
2364 if (field == "fund" && w.store)
2365 self._ensureCSSFundClasses(w.store);
2368 copy[field](ww.getFormattedValue())
2370 self.copyWidgetCache[copy.id()][field] = w;
2372 dojo.connect(w, 'onChange',
2374 if (field == "fund")
2375 self._updateFundSelectorStyle(widget, val);
2377 if (!readOnly && (copy.isnew() || val != copy[field]())) {
2378 // prevent setting ischanged() automatically on widget load for existing copies
2379 copy[field](widget.getFormattedValue())
2380 copy.ischanged(true);
2389 this.updateLidState(copy, row);
2392 this._ensureCSSFundClass = function(id) {
2393 if (!this.fundStyleSheet) {
2395 "style", {"type": "text/css"},
2396 document.getElementsByTagName("head")[0], "last"
2398 this.fundStyleSheet = document.styleSheets[
2399 document.styleSheets.length - 1
2403 var cn = "fund_" + id;
2404 if (!this.haveFundClass[cn]) {
2405 fieldmapper.standardRequest(
2406 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
2408 "params": [openils.User.authtoken, id],
2410 "oncomplete": function(r) {
2411 r = openils.Util.readResponse(r);
2412 self.fundBalanceState[id] = r;
2414 if (r[0] /* stop */)
2415 style = fundStyles.stop;
2416 else if (r[1] /* warning */)
2417 style = fundStyles.warning;
2418 self.fundStyleSheet.insertRule(
2419 "." + cn + " { " + style + " }",
2420 self.fundStyleSheet.cssRules.length
2422 self.haveFundClass[cn] = true;
2429 this._ensureCSSFundClasses = function(store) {
2431 "query": {"id": "*"},
2432 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
2436 this._updateFundSelectorStyle = function(widget, fund_id) {
2437 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
2438 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
2441 this.updateLidState = function(copy, row) {
2444 if (typeof(row) == "undefined") {
2445 row = dojo.query('tr[copy_id="' + copy.id() + '"]', this.copyTbody)[0];
2449 var recv_link = nodeByName("receive", row);
2450 var unrecv_link = nodeByName("unreceive", row);
2451 var del_link = nodeByName("delete", row);
2452 var cxl_link = nodeByName("cancel", row);
2453 var claim_link = nodeByName("claim", row);
2454 var cxl_reason_link = nodeByName("cancel_reason", row);
2456 // by default, hide all the actions
2457 openils.Util.hide(del_link.parentNode);
2458 openils.Util.hide(recv_link);
2459 openils.Util.hide(unrecv_link);
2460 openils.Util.hide(cxl_link);
2461 openils.Util.hide(claim_link);
2462 openils.Util.hide(cxl_reason_link);
2464 if (copy.id() > 0) { // real copies (LIDs)
2466 if (copy.cancel_reason()) {
2468 /* --------- cancelled -------------------------- */
2470 /* XXX the following may leak memory in a long lived table:
2471 * dijits may not get destroyed... not positive. revisit. */
2472 var holds_reason = dojo.create(
2474 "style": "border-bottom: 1px dashed #000;",
2475 "innerHTML": copy.cancel_reason().label()
2476 }, cxl_reason_link, "only"
2480 "label": "<em>" + copy.cancel_reason().label() +
2481 "</em><br />" + copy.cancel_reason().description(),
2482 "connectId": [holds_reason]
2483 }, dojo.create("span", null, cxl_reason_link, "last")
2485 openils.Util.show(cxl_reason_link, "inline");
2487 if (copy.cancel_reason().keep_debits() == 't' ) {
2488 // allow further cancellation of "delayed" copies
2490 openils.Util.show(cxl_link, "inline");
2491 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2494 } else if (copy.recv_time()) {
2496 /* --------- received -------------------------- */
2498 openils.Util.show(unrecv_link, "inline");
2499 unrecv_link.onclick = function() {
2500 if (confirm(localeStrings.UNRECEIVE_LID))
2501 self.issueReceive(copy, /* rollback */ true);
2504 } else if (this.liCache[copy.lineitem()].state() == 'on-order') {
2506 /* --------- on order -------------------------- */
2508 openils.Util.show(recv_link, 'inline');
2509 openils.Util.show(cxl_link, "inline");
2511 recv_link.onclick = function() {
2512 if (self.checkLiAlerts(copy.lineitem()))
2513 self.issueReceive(copy);
2516 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2520 /* --------- pre-order copies -------------------------- */
2522 del_link.onclick = function() { self.deleteCopy(row) };
2523 openils.Util.show(del_link.parentNode);
2529 /* --------- virtual copies -------------------------- */
2531 del_link.onclick = function() { self.deleteCopy(row) };
2532 openils.Util.show(del_link.parentNode);
2536 this.cancelLid = function(lid_id) {
2537 lidCancelDialog._lid_id = lid_id;
2538 openils.Util.show(lidCancelDialog.domNode.parentNode);
2539 lidCancelDialog.show();
2540 if (!lidCancelDialog._prepared) {
2541 var widget = new openils.widget.AutoFieldWidget({
2542 "fmField": "cancel_reason",
2543 "fmClass": "acqlid",
2544 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
2545 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2547 "searchOptions" : {order_by : {"acqcr":"label"}}
2551 acqLidCancelButton.onClick = function() {
2552 if (w.attr("value")) {
2553 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
2555 lidCancelDialog._lid_id,
2559 lidCancelDialog.hide();
2562 lidCancelDialog._prepared = true;
2568 this._cancelLid = function(lid_id, reason) {
2569 fieldmapper.standardRequest(
2570 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
2571 "params": [openils.User.authtoken, lid_id, reason],
2573 "onresponse": function(r) {
2574 if (r = openils.Util.readResponse(r)) {
2576 for (var id in r.lid) {
2577 /* actually this should only iterate once */
2578 self.copyCache[id].cancel_reason(
2579 r.lid[id].cancel_reason
2581 self.updateLidState(self.copyCache[id]);
2590 this._confirmAlert = function(li, lin) {
2592 dojo.string.substitute(
2593 localeStrings.CONFIRM_LI_ALERT, [
2594 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2595 "title", "lineitem_marc_attr_definition"
2597 /* XXX it's really better add a parameter and to adjust
2598 * the format string rather than do this concatenation
2599 * here, but if someone wants this for 2.2 in a hurry,
2600 * we can sidestep the problem of updating the strings
2601 * while the translators are working. */
2603 aou.findOrgUnit(lin.alert_text().owning_lib()).shortname() +
2605 lin.alert_text().code()
2607 lin.alert_text().description() || "",
2614 this.checkLiAlerts = function(li_id) {
2615 var li = this.liCache[li_id];
2617 var alert_notes = li.lineitem_notes().filter(
2618 function(o) { return Boolean(o.alert_text()); }
2621 /* this is _intentionally_ not done in a call to forEach() ... */
2622 for (var i = 0; i < alert_notes.length; i++) {
2623 if (this.noteAcks[alert_notes[i].id()])
2625 else if (!this._confirmAlert(li, alert_notes[i]))
2628 this.noteAcks[alert_notes[i].id()] = true;
2634 this.deleteCopy = function(row) {
2635 var copy = this.copyCache[row.getAttribute('copy_id')];
2636 copy.isdeleted(true);
2638 delete this.copyCache[copy.id()];
2639 this.copyTbody.removeChild(row);
2642 this._virtDfaCountsAsList = function() {
2644 for (var key in this.virtDfaCounts) {
2645 for (var i = 0; i < this.virtDfaCounts[key]; i++)
2651 this.confirmBreachedCopyFunds = function(copies) {
2652 var stop = 0, warning = 0;
2656 var state = self.fundBalanceState[o.fund()];
2657 if (state[0] /* stop */)
2659 else if (state[1] /* warning */)
2666 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
2667 } else if (warning) {
2668 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
2673 this.saveCopyChanges = function(liId) {
2679 for(var id in this.copyCache) {
2680 var c = this.copyCache[id];
2681 if(!c.isdeleted()) total++;
2682 if(c.isnew() || c.ischanged() || c.isdeleted()) {
2683 if(c.id() < 0) c.id(null);
2689 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
2692 if (copies.length > 0) {
2693 if (!this.confirmBreachedCopyFunds(copies))
2696 if (typeof(this._copy_count_cb) == "function")
2697 this._copy_count_cb(liId, total);
2699 openils.Util.show("acq-lit-update-copies-progress");
2700 fieldmapper.standardRequest(
2701 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
2703 params: [openils.User.authtoken, copies],
2704 onresponse: function(r) {
2705 var res = openils.Util.readResponse(r);
2706 litUpdateCopiesProgress.update(res);
2708 oncomplete: function() {
2709 self.drawCopies(liId, true /* force_fetch */);
2710 openils.Util.hide("acq-lit-update-copies-progress");
2716 var dfa_list = this._virtDfaCountsAsList();
2717 if (dfa_list.length > 0) {
2718 fieldmapper.standardRequest(
2720 "open-ils.acq.distribution_formula.record_application"],
2723 "params": [openils.User.authtoken, dfa_list, liId],
2724 "onresponse": function(r) {
2725 var res = openils.Util.readResponse(r);
2726 if (res && res.length < dfa_list.length)
2727 alert(localeStrings.DFA_NOT_ALL);
2731 this.virtDfaCounts = {};
2734 if (this.inlineCopiesNeedingRefresh.indexOf(liId) < 0)
2735 this.inlineCopiesNeedingRefresh.push(liId);
2738 this._updateCreatePoPrepayCheckbox = function(prepay) {
2739 var prepay = openils.Util.isTrue(prepay);
2740 this._prepayRequiredByVendor = prepay;
2741 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
2744 this._confirmPoPrepaySituation = function() {
2745 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
2746 if (want_prepay != this._prepayRequiredByVendor) {
2749 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
2750 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
2757 this.applySelectedLiAction = function(action) {
2761 case 'delete_selected':
2762 this._deleteLiList(self.getSelected());
2765 case 'add_to_order':
2766 addToPoDialog._get_li = dojo.hitch(
2769 return this.getSelected(
2770 false, null, true, li_pre_po_states);
2773 if (addToPoDialog._get_li().length == 0) {
2774 alert(localeStrings.NO_LI_GENERAL);
2777 addToPoDialog.show();
2780 case 'create_order':
2781 this._loadPOSelect();
2782 acqLitPoCreateDialog.show();
2785 case 'save_picklist':
2786 acqLitSavePlDialog.show();
2789 case 'selector_ready':
2791 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
2792 acqLitChangeLiStateDialog.show();
2800 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
2803 case 'batch_create_invoice':
2804 this.batchCreateInvoice();
2807 case 'batch_link_invoice':
2808 this.batchLinkInvoice();
2811 case 'receive_lineitems':
2812 this.receiveSelectedLineitems();
2815 case 'rollback_receive_lineitems':
2816 this.rollbackReceiveLineitems();
2819 case 'create_assets':
2820 this.showAssetCreator();
2823 case 'export_attr_list':
2824 this.chooseExportAttr();
2827 case 'batch_apply_funds':
2828 this.applyBatchLiFunds();
2831 case 'add_brief_record':
2833 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
2835 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
2839 case "cancel_lineitems":
2840 console.log('HERE');
2841 this.maybeCancelLineitems();
2844 case "apply_claim_policy":
2845 var li_list = this.getSelected();
2846 this.claimPolicyPicker.attr("value", null);
2847 liClaimPolicyDialog.show();
2848 liClaimPolicySave.onClick = function() {
2849 self.changeClaimPolicy(
2851 self.claimPolicyPicker.attr("value"),
2855 self.setClaimPolicyControl(li);
2856 self.reconsiderClaimControl(li);
2859 liClaimPolicyDialog.hide();
2867 this.changeClaimPolicy = function(li_list, value, callback) {
2869 function(li) { li.claim_policy(value); }
2871 fieldmapper.standardRequest(
2872 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
2873 "params": [openils.User.authtoken, li_list],
2875 "oncomplete": function(r) {
2876 r = openils.Util.readResponse(r);
2877 if (callback) callback(r);
2883 this.showAssetCreator = function(onAssetsCreated) {
2884 if(!this.isPO) return;
2887 // first, let's see if this PO has any LI's that need to be merged/imported
2888 self.pcrud.search('jub', {purchase_order : this.isPO, eg_bib_id : null}, {
2890 oncomplete : function(r) {
2891 var resp = openils.Util.readResponse(r);
2892 if (resp && resp.length) {
2893 // PO has some non-linked jubs.
2895 self.show('asset-creator');
2896 if(!self.vlAgent.loaded)
2897 self.vlAgent.init();
2899 dojo.connect(assetCreatorButton, 'onClick',
2900 function() { self.createAssets(onAssetsCreated) });
2904 // all jubs linked, move on to asset creation
2905 self.createAssets(onAssetsCreated, true);
2911 this.createAssets = function(onAssetsCreated, noVl) {
2912 this.show('acq-lit-progress-numbers');
2914 var vlArgs = (noVl) ? {} : {vandelay : this.vlAgent.values()};
2915 fieldmapper.standardRequest(
2916 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
2918 params: [this.authtoken, this.isPO, vlArgs],
2919 onresponse: function(r) {
2920 var resp = openils.Util.readResponse(r);
2921 self._updateProgressNumbers(resp, !Boolean(onAssetsCreated), onAssetsCreated);
2927 this.maybeCancelLineitems = function() {
2928 openils.Util.show("acq-lit-cancel-reason", "inline");
2929 if (!acqLitCancelLineitemsButton._prepared) {
2930 var widget = new openils.widget.AutoFieldWidget({
2931 "fmField": "cancel_reason",
2933 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
2934 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2936 "searchOptions" : {order_by : {"acqcr":"label"}}
2940 acqLitCancelLineitemsButton.onClick = function() {
2941 if (w.attr("value")) {
2942 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
2943 self._cancelLineitems(w.attr("value"));
2945 openils.Util.hide("acq-lit-cancel-reason");
2948 acqLitCancelLineitemsButton._prepared = true;
2954 this._cancelLineitems = function(reason) {
2956 var li_list = this.getSelected();
2958 // canceled lineitems may be canceled again if they were
2959 // previously delayed (keep_debits = true).
2960 li_list = li_list.filter(
2963 li.state() != 'cancelled' ||
2964 li.cancel_reason().keep_debits() == 't'
2969 id_list = li_list.map(function(l) {return l.id()});
2971 if (!id_list.length) {
2972 alert(localeStrings.NO_LI_GENERAL);
2975 fieldmapper.standardRequest(
2976 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
2977 "params": [openils.User.authtoken, id_list, reason],
2979 "onresponse": function(r) {
2980 if (r = openils.Util.readResponse(r)) {
2982 for (var id in r.li) {
2983 self.liCache[id].state(r.li[id].state);
2984 self.liCache[id].cancel_reason(
2985 r.li[id].cancel_reason
2987 self.updateLiState(self.liCache[id]);
2990 if (r.lid && self.copyCache) {
2991 for (var id in r.lid) {
2992 if (self.copyCache[id]) {
2993 self.copyCache[id].cancel_reason(
2994 r.lid[id].cancel_reason
2996 self.updateLidState(self.copyCache[id]);
3006 this.chooseExportAttr = function() {
3007 if (!acqLitExportAttrSelector._li_setup) {
3009 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
3011 "data": acqlimad.toStoreData(
3013 "acqlimad", {"code": li_exportable_attrs}
3018 acqLitExportAttrSelector.setValue();
3019 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
3020 acqLitExportAttrSelector._li_setup = true;
3022 openils.Util.show("acq-lit-export-attr-holder", "inline");
3025 this.exportAttrList = function() {
3026 var attr_def = acqLitExportAttrSelector.item;
3027 var li_list = this.getSelected();
3028 var value_list = li_list.map(
3030 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
3031 attr_def.code, "lineitem_marc_attr_definition"
3034 ).filter(function(attr) { return Boolean(attr); });
3036 if (value_list.length > 0) {
3037 if (value_list.length < li_list.length) {
3039 dojo.string.substitute(
3040 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
3047 openils.XUL.contentToFileSaveDialog(
3048 value_list.join("\n"),
3049 localeStrings.EXPORT_SAVE_DIALOG_TITLE
3055 alert(dojo.string.substitute(
3056 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
3060 openils.Util.hide("acq-lit-export-attr-holder");
3063 this.printPO = function() {
3064 if(!this.isPO) return;
3065 progressDialog.show(true);
3066 fieldmapper.standardRequest(
3067 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
3069 params: [this.authtoken, this.isPO, 'html'],
3070 oncomplete: function(r) {
3071 progressDialog.hide();
3072 var evt = openils.Util.readResponse(r);
3073 if(evt && evt.template_output()) {
3074 openils.Util.printHtmlString(evt.template_output().data());
3081 this.batchCreateInvoice = function() {
3082 var liIds = this.getSelected(
3083 false, null, true /* id_list */, li_active_states)
3084 if (!liIds.length) {
3085 alert(localeStrings.NO_LI_GENERAL);
3088 var path = oilsBasePath + '/acq/invoice/view?create=1';
3089 dojo.forEach(liIds, function(li, idx) { path += '&attach_li=' + li });
3090 if (openils.XUL.isXUL())
3091 openils.XUL.newTabEasy(path, localeStrings.NEW_INVOICE, null, true);
3093 location.href = path;
3096 this.batchLinkInvoice = function(create) {
3097 var liIds = this.getSelected(
3098 false, null, true /* id_list */, li_active_states)
3099 if (!liIds.length) {
3100 alert(localeStrings.NO_LI_GENERAL);
3103 if (!self.invoiceLinkDialogManager) {
3104 self.invoiceLinkDialogManager =
3105 new InvoiceLinkDialogManager("li");
3107 self.invoiceLinkDialogManager.target = liIds;
3108 acqLitLinkInvoiceDialog.show();
3111 this.receiveSelectedLineitems = function() {
3112 var states = li_post_po_states.filter(
3113 function(s) { return s != 'received' });
3114 var li_list = this.getSelected(null, null, null, states);
3116 if (!li_list.length) {
3117 alert(localeStrings.NO_LI_GENERAL);
3121 for (var i = 0; i < li_list.length; i++) {
3122 var li = li_list[i];
3124 if (li.state() != "received" &&
3125 !this.checkLiAlerts(li.id())) return;
3128 this.show('acq-lit-progress-numbers');
3131 fieldmapper.standardRequest(
3132 ['open-ils.acq', 'open-ils.acq.lineitem.receive.batch'],
3136 li_list.map(function(li) { return li.id(); })
3138 onresponse : function(r) {
3139 var resp = openils.Util.readResponse(r);
3140 self._updateProgressNumbers(resp, true);
3146 this.issueReceive = function(obj, rollback) {
3148 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
3150 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
3152 progressDialog.show(true);
3153 fieldmapper.standardRequest(
3154 ["open-ils.acq", method], {
3156 "params": [this.authtoken, obj.id()],
3157 "onresponse": function(r) {
3158 if (r = openils.Util.readResponse(r)) {
3159 self.fetchClaimInfo(
3160 part == "lineitem" ? obj.id() : obj.lineitem(),
3162 function() { self.handleReceive(r); }
3164 progressDialog.hide();
3172 * Handles the responses from receive and rollback ML calls.
3174 this.handleReceive = function(resp) {
3177 for (var li_id in resp.li) {
3178 for (var key in resp.li[li_id])
3179 self.liCache[li_id][key](resp.li[li_id][key]);
3180 self.updateLiState(self.liCache[li_id]);
3184 if (typeof(self.poUpdateCallback) == "function")
3185 self.poUpdateCallback(resp.po);
3188 for (var lid_id in resp.lid) {
3189 for (var key in resp.lid[lid_id])
3190 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
3191 self.updateLidState(self.copyCache[lid_id]);
3197 this.rollbackReceiveLineitems = function() {
3198 var li_id_list = this.getSelected(false, null, true);
3199 if (!li_id_list.length) {
3200 alert(localeStrings.NO_LI_GENERAL);
3204 if (!confirm(localeStrings.ROLLBACK_LI_RECEIVE_CONFIRM)) return;
3206 this.show('acq-lit-progress-numbers');
3209 fieldmapper.standardRequest(
3210 ['open-ils.acq', 'open-ils.acq.lineitem.receive.rollback.batch'],
3212 params: [this.authtoken, li_id_list],
3213 onresponse : function(r) {
3214 var resp = openils.Util.readResponse(r);
3215 self._updateProgressNumbers(resp, true);
3221 this._updateProgressNumbers = function(resp, reloadOnComplete, onComplete) {
3222 this.vlAgent.handleResponse(resp,
3223 function(resp, res) {
3224 if(reloadOnComplete)
3225 location.href = location.href;
3227 onComplete(resp, res);
3233 this._createPO = function(fields) {
3234 var wantall = (fields.create_from == "all");
3236 /* If we're a picklist or purchase order already and the user wants
3237 * all lineitems, we might have pages' worth of lineitems haven't all
3238 * been loaded yet, so getSelected() won't find them. The server,
3239 * however, should know about all our lineitems, so let's ask the
3240 * server for a complete list.
3245 true, function(list) {
3246 self._createPOFromLineitems(fields, list);
3247 }, /* id_list */ true, li_pre_po_states
3250 this._createPOFromLineitems(
3251 fields, this.getSelected(
3252 false, null, true /* id_list */, li_pre_po_states)
3257 this._createPOFromLineitems = function(fields, selected) {
3258 if (selected.length == 0) {
3259 alert(localeStrings.NO_LI_GENERAL);
3264 var po = new fieldmapper.acqpo();
3265 po.provider(this.createPoProviderSelector.attr("value"));
3266 po.ordering_agency(this.createPoAgencySelector.attr("value"));
3267 po.prepayment_required(fields.prepayment_required[0] ? true : false);
3269 // if we're creating assets, delay the asset creation
3270 // until after the PO is created. This will allow us to
3271 // use showAssetCreator() directly.
3273 fieldmapper.standardRequest(
3274 ["open-ils.acq", "open-ils.acq.purchase_order.create"],
3277 openils.User.authtoken,
3278 po, {lineitems : selected}
3280 onresponse : function(r) {
3281 var resp = openils.Util.readResponse(r);
3282 if (resp.complete) {
3283 // self.isPO is needed for showAssetCreator();
3284 self.isPO = resp.purchase_order.id();
3285 var redir = oilsBasePath + "/acq/po/view/" + self.isPO;
3286 if (fields.create_assets[0]) {
3287 self.showAssetCreator(
3288 function() {location.href = redir}
3291 location.href = redir;
3300 this.batchFundWidget = null;
3302 this.applyBatchLiFunds = function() {
3304 var liIds = this.getSelected().map(function(li) { return li.id(); });
3305 if(liIds.length == 0) return; // warn?
3308 batchFundUpdateDialog.show();
3310 if(!this.batchFundWidget) {
3311 this.batchFundWidget = new openils.widget.AutoFieldWidget({
3313 selfReference : true,
3314 labelFormat : fundLabelFormat,
3315 searchFormat : fundSearchFormat,
3316 searchFilter : {"active": "t"},
3317 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
3318 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
3319 dijitArgs : { "required": true, "labelType": "html" },
3322 this.batchFundWidget.build();
3325 dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
3326 dojo.connect(batchFundUpdateSubmit, 'onClick',
3329 // TODO: call .dry_run first to test thresholds
3330 fieldmapper.standardRequest(
3331 ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
3334 openils.User.authtoken,
3336 self.batchFundWidget.widget.attr('value')
3338 oncomplete : function(r) {
3339 var resp = openils.Util.readResponse(r);
3341 location.href = location.href;
3350 this._deleteLiList = function(list, idx) {
3351 if(idx == null) idx = 0;
3352 if(idx >= list.length) return;
3357 if (this.isPO && (li.state() == "on-order" || li.state() == "received")) {
3358 /* It makes little sense to delete a lineitem from a PO that has
3359 * already been marked 'on-order'. Especially if EDI is in use,
3360 * such a purchase order will probably have already been shipped
3361 * off to a vendor, and mucking with it at this point could leave
3362 * your data in a bad state that doesn't jive with reality.
3364 * I could see making this restriction even firmer.
3366 * I could also see adjusting the li state comparisons, extending
3367 * the comparison to the PO's state, and/or providing functions
3368 * that house the logic for comparing states in a single location.
3370 * Yes, this will be really annoying if you have selected a lot
3371 * of lineitems to cancel that have been ordered. You'll get a
3372 * confirm dialog for each one.
3375 if (!confirm(localeStrings.DEL_LI_FROM_PO)) {
3376 self._deleteLiList(list, ++idx); /* move on to next in list */
3381 fieldmapper.standardRequest(
3383 this.isPO ? 'open-ils.acq.purchase_order.lineitem.delete' : 'open-ils.acq.picklist.lineitem.delete'],
3385 params: [openils.User.authtoken, liId],
3386 oncomplete: function(r) {
3387 self.removeLineitem(liId);
3388 self._deleteLiList(list, ++idx);
3394 this.editOrderMarc = function(li) {
3396 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
3397 to true in about:config */
3399 if(openils.XUL.isXUL()) {
3400 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul','','chrome');
3402 win = window.open('/xul/server/cat/marcedit.xul','','chrome');
3406 record : {marc : li.marc(), "rtype": "bre"},
3408 label: 'Save Record', // XXX I18N
3409 func: function(xmlString) {
3411 fieldmapper.standardRequest(
3412 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
3414 params: [openils.User.authtoken, li],
3415 oncomplete: function(r) {
3416 openils.Util.readResponse(r);
3418 self.drawInfo(li.id())
3424 'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
3425 'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
3429 this._savePl = function(values) {
3431 (values.which == 'all'),
3432 function(list) { self._savePlFromLineitems(values, list); }
3436 this._savePlFromLineitems = function(values, selected) {
3437 openils.Util.show("acq-lit-generic-progress");
3439 if(values.new_name) {
3440 openils.acq.Picklist.create(
3441 {name: values.new_name},
3447 oilsBasePath + "/acq/picklist/view/" + id;
3452 } else if(values.existing_pl) {
3453 // update lineitems to use an existing picklist
3455 values.existing_pl, selected, 0,
3458 oilsBasePath + "/acq/picklist/view/" +
3465 this._updateLiState = function(values, state, state_filter) {
3466 progressDialog.show(true);
3468 (values.which == 'all'),
3470 self._updateLiStateFromLineitems(values, state, list);
3471 }, false /* id_list */, state_filter
3475 this._updateLiStateFromLineitems = function(values, state, selected) {
3476 if(!selected.length) {
3477 try { progressDialog.hide() } catch(E) {};
3478 alert(localeStrings.NO_LI_GENERAL);
3481 dojo.forEach(selected, function(li) {li.state(state);});
3482 self._updateLiList(null, selected, 0,
3483 // TODO consider inline updates for efficiency
3484 function() { location.href = location.href }
3488 this._updateLiList = function(pl, list, idx, oncomplete) {
3489 if(idx >= list.length) return oncomplete();
3491 if(pl != null) li.picklist(pl);
3492 litGenericProgress.update({maximum: list.length, progress: idx});
3493 new openils.acq.Lineitem({lineitem:li}).update(
3495 self._updateLiList(pl, list, ++idx, oncomplete);
3500 this._loadPOSelect = function() {
3501 if (!this.createPoProviderSelector) {
3502 var widget = new openils.widget.AutoFieldWidget({
3503 "fmField": "provider",
3505 "searchFilter": {"active": "t"},
3506 "parentNode": dojo.byId("acq-lit-po-provider"),
3508 "onChange": function() {
3510 self._updateCreatePoPrepayCheckbox(
3511 this.item.prepayment_required()
3517 widget.build(function(w) { self.createPoProviderSelector = w; });
3520 if (!this.createPoAgencySelector) {
3521 var widget = new openils.widget.AutoFieldWidget({
3522 "fmField": "ordering_agency",
3524 "parentNode": dojo.byId("acq-lit-po-agency"),
3525 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3527 widget.build(function(w) { self.createPoAgencySelector = w; });
3531 this.showRealCopyEditUI = function(li) {
3536 this._fetchLineitem(li.id(),
3538 li = self.liCache[li.id()] = fullLi;
3542 id : li.lineitem_details().map(
3543 function(item) { return item.eg_copy_id() }
3547 oncomplete : function(r) {
3549 var r_list = openils.Util.readResponse( r );
3550 for (var i = 0; i < r_list.length; i++) {
3551 var copy = r_list[i];
3552 var volId = copy.call_number();
3553 var volume = self.volCache[volId];
3555 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
3557 copy.call_number(volume);
3558 copyList.push(copy);
3561 xulG.volume_item_creator( { 'existing_copies' : copyList } );
3564 alert('error in oncomplete: ' + E);
3573 this.drawBibFinder = function(li) {
3576 var liWrapper = new openils.acq.Lineitem({lineitem:li});
3579 ['isbn', 'upc', 'issn', 'title', 'author'],
3581 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
3583 if(field == 'title' || field == 'author') {
3584 query += field +':' + val + ' ';
3586 query += 'identifier|' + field + ':' + val + ' ';
3593 oilsBasePath + '/acq/lineitem/findbib?query=' + encodeURIComponent(query),
3594 '', 'resizable,scrollbars=1,chrome');
3596 win.window.recordFound = function(bibId) {
3599 var attrs = li.attributes();
3600 li.attributes(null);
3601 li.eg_bib_id(bibId);
3603 fieldmapper.standardRequest(
3604 ["open-ils.acq", "open-ils.acq.lineitem.update"],
3606 "params": [openils.User.authtoken, li],
3608 "oncomplete": function(r) {
3609 if(openils.Util.readResponse(r)) {
3610 location.href = location.href;