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'];
32 var fundSearchFilter = {active : 't'};
34 function nodeByName(name, context) {
35 return dojo.query('[name='+name+']', context)[0];
38 // for caching linked users. e.g. lineitem_detail.receiver
41 var liDetailBatchFields = ['fund', 'owning_lib', 'location', 'collection_code', 'circ_modifier', 'cn_label'];
42 var liDetailFields = liDetailBatchFields.concat(['barcode', 'note']);
44 "stop": "color: #c00; font-weight: bold;",
45 "warning": "color: #c93;"
49 * We're not using 'approved' today, but there is API support for it.
50 * I believe it's been replaced by "order-ready".
51 * LIs go new => selector-ready => order-ready/approved => pending-order =>
52 * on-order => received. 'cancelled' can pop up anywhere.
55 var li_pre_po_states = ["new", "selector-ready", "order-ready", "approved"];
56 var li_post_po_states = ["pending-order", "on-order", "received", "cancelled"];
57 var li_active_states = li_pre_po_states.concat(li_post_po_states);
59 function AcqLiTable() {
66 this.haveFundClass = {}
67 this.fundBalanceState = {};
68 this.realDfaCache = {};
69 this.virtDfaCounts = {};
72 this.claimEligibleLidByLi = {};
73 this.claimEligibleLid = {};
74 this.toggleState = false;
75 this.tbody = dojo.byId('acq-lit-tbody');
78 this.authtoken = openils.User.authtoken;
79 this.pcrud = new openils.PermaCrud();
80 this.rowTemplate = this.tbody.removeChild(dojo.byId('acq-lit-row'));
81 this.copyTbody = dojo.byId('acq-lit-li-details-tbody');
82 this.copyRow = this.copyTbody.removeChild(dojo.byId('acq-lit-li-details-row'));
83 this.copyBatchRow = dojo.byId('acq-lit-li-details-batch-row');
84 this.copyBatchWidgets = {};
85 this.liNotesTbody = dojo.byId('acq-lit-notes-tbody');
86 this.liNotesRow = this.liNotesTbody.removeChild(dojo.byId('acq-lit-notes-row'));
87 this.realCopiesTbody = dojo.byId('acq-lit-real-copies-tbody');
88 this.realCopiesRow = this.realCopiesTbody.removeChild(dojo.byId('acq-lit-real-copies-row'));
89 this._copy_fields_for_acqdf = ['owning_lib', 'location', 'fund', 'circ_modifier', 'collection_code'];
90 this.skipInitialEligibilityCheck = false;
91 this.claimDialog = new ClaimDialogManager(
92 liClaimDialog, finalClaimDialog, this.claimEligibleLidByLi,
93 function(li) { /* callback that fires when claims are made */
94 self.fetchClaimInfo(li.id(), /* force update */ true);
97 this.vlAgent = new VLAgent();
99 if (dojo.byId('acq-lit-apply-idents')) {
100 dojo.byId('acq-lit-apply-idents').onclick = function() {
101 self.applyOrderIdentValues();
105 this.focusLineitem = new openils.CGI().param('focus_li');
107 // capture the inline copy display wrapper and row template
108 this.inlineCopyContainer =
109 this.tbody.removeChild(dojo.byId('acq-inline-copies-row'));
111 '[name=acq-li-inline-copies-tbody]', this.inlineCopyContainer)[0];
112 this.inlineCopyTemplate = tb.removeChild(
113 dojo.query('[name=acq-li-inline-copies-template]', tb)[0]);
114 this.inlineNoCopies = tb.removeChild(
115 dojo.query('[name=acq-li-inline-copies-none]', tb)[0]);
117 // list of LI IDs that should be refreshed at next display time
118 this.inlineCopiesNeedingRefresh = [];
120 dojo.byId("acq-lit-li-actions-selector").onchange = function() {
121 self.applySelectedLiAction(this.options[this.selectedIndex].value);
122 this.selectedIndex = 0;
125 acqLitCreatePoSubmit.onClick = function() {
126 if (!self.createPoProviderSelector.attr("value") ||
127 !self.createPoAgencySelector.attr("value")) {
128 alert(localeStrings.CREATE_PO_INVALID);
130 } else if (self._confirmPoPrepaySituation()) {
131 acqLitPoCreateDialog.hide();
132 self._createPO(acqLitPoCreateDialog.getValues());
138 acqLitSavePlButton.onClick = function() {
139 acqLitSavePlDialog.hide();
140 self._savePl(acqLitSavePlDialog.getValues());
143 acqLitCancelLiStateButton.onClick = function() {
144 acqLitChangeLiStateDialog.hide();
146 acqLitSaveLiStateButton.onClick = function() {
147 acqLitChangeLiStateDialog.hide();
148 var state = acqLitChangeLiStateDialog.attr('state');
149 var state_filter = ['new'];
150 if (state == 'order-ready')
151 state_filter.push('selector-ready');
153 acqLitChangeLiStateDialog.getValues(), state, state_filter);
157 dojo.byId('acq-lit-select-toggle').onclick = function(){self.toggleSelect()};
158 dojo.byId('acq-inline-copies-toggle').onclick = function(){self.toggleInlineCopies()};
159 dojo.byId('acq-lit-info-back-button').onclick = function(){self.show('list')};
160 dojo.byId('acq-lit-copies-back-button').onclick = function(){self.show('list')};
161 dojo.byId('acq-lit-notes-back-button').onclick = function(){self.show('list')};
162 dojo.byId('acq-lit-real-copies-back-button').onclick = function(){self.show('list')};
164 this.setFundSearchFilter = function(callback) {
165 new openils.User().getPermOrgList(
166 ['CREATE_PURCHASE_ORDER', 'MANAGE_FUND'],
168 fundSearchFilter.org = orgs;
169 if (callback) callback();
171 true, true // descendants, id_list
175 this.afwCopyFieldArgs = function(field, perms) {
179 "labelFormat": (field == 'fund') ? fundLabelFormat : null,
180 "searchFormat": (field == 'fund') ? fundSearchFormat : null,
181 "searchFilter": (field == 'fund') ? fundSearchFilter : null,
182 "orgLimitPerms": [perms],
185 "labelType": (field == "fund") ? "html" : null
187 "noCache": (field == "fund"),
192 /* This is the "new" batch updater that sits atop all lineitems. It does
193 * use this.afwCopyFieldArgs() to borrow a little common code from the
194 * "old" batch updater atop the copy details view. */
195 this.initBatchUpdater = function(disabled_fields) {
196 openils.Util.show("acq-batch-update", "table");
198 if (!dojo.isArray(disabled_fields)) disabled_fields = [];
200 /* Note that this will directly contain dijits, not the AutoWidget
202 this.batchUpdateWidgets = {};
204 this.batchUpdateWidgets.item_count = new dijit.form.TextBox(
206 "style": {"width": "3em"},
208 dojo.indexOf(disabled_fields, "item_count") != -1
214 (new openils.widget.AutoFieldWidget({
216 "selfReference": true,
217 "dijitArgs": { "required": false },
219 "parentNode": "acq-bu-distribution_formula"
222 dojo.style(w.domNode, {"width": "12em"});
223 /* dijitArgs to AutoFieldWidget won't work for 'disabled' */
226 dojo.indexOf(disabled_fields, "distribution_formula") != -1
228 self.batchUpdateWidgets.distribution_formula = w;
232 function buildOneBatchWidget(field, args) {
233 (new openils.widget.AutoFieldWidget(args)).build(
235 if (field == "fund") {
237 w, "onChange", function(val) {
238 self._updateFundSelectorStyle(aw, val);
242 self._ensureCSSFundClasses(w.store);
245 dojo.style(w.domNode, {"width": "10em"});
248 dojo.indexOf(disabled_fields, field) != -1
250 self.batchUpdateWidgets[field] = w;
256 ["owning_lib","location","collection_code","circ_modifier","fund"],
258 var args = self.afwCopyFieldArgs(field,"CREATE_PURCHASE_ORDER");
259 args.parentNode = dojo.byId("acq-bu-" + field);
261 if (field == 'fund') {
262 // The list of funds can be huge. Before fetching
263 // funds for PO modification, see where the user has
264 // perms and limit the retreived funds accordingly.
265 // Note: This is the first instance of fund list
266 // retrieval. All future fund list retrievals will
267 // benefit directly from having applied the fund
268 // search filter org units here.
269 self.setFundSearchFilter(function() {
270 buildOneBatchWidget(field, args);
275 buildOneBatchWidget(field, args);
279 acqBatchUpdateApply.onClick = function() {
280 var li_id_list = self.getSelected(false, null, true /* id list */);
281 if (!li_id_list.length) {
282 alert(localeStrings.NO_LI_TO_UPDATE);
286 progressDialog.show(true);
287 progressDialog.attr("title", localeStrings.LI_BATCH_UPDATE);
288 progressDialog.update({"maximum": li_id_list.length,"progress": 0});
292 var params = [ self.authtoken, {"lineitems": li_id_list},
293 self.batchUpdateChanges(), self.batchUpdateFormula() ];
294 console.log("batch update params: " + dojo.toJson(params));
296 fieldmapper.standardRequest(
297 ["open-ils.acq", "open-ils.acq.lineitem.batch_update"], {
300 "onresponse": function(r) {
301 if ((r = openils.Util.readResponse(r))) { // assignment
302 progressDialog.update({"progress": ++count});
304 progressDialog.hide();
305 progressDialog.attr("title", "");
308 "oncomplete": function() {
309 /* XXX Is the last call to onresponse guaranteed to
310 * finish before oncomplete is fired? */
311 if (count != li_id_list.length) {
312 console.error("lineitem batch update operation failed");
313 progressDialog.hide();
314 progressDialog.attr("title", "");
316 location.href = location.href;
324 this.batchUpdateChanges = function() {
328 openils.Util.objectProperties(this.batchUpdateWidgets),
330 if (k == "distribution_formula") return; /* handled elsewhere */
331 if (self.batchUpdateWidgets[k].attr("disabled")) return;
333 /* It's important that a value of "" should mean that a field
334 * doesn't get used in the arguments to the batch updater API,
335 * but 0 should mean an actual 0. */
336 var value = self.batchUpdateWidgets[k].attr("value");
345 this.batchUpdateFormula = function() {
346 if (this.batchUpdateWidgets.distribution_formula.attr("disabled")) {
350 this.batchUpdateWidgets.distribution_formula.attr("value") ||
356 this.reset = function(keep_selectors) {
357 while(self.tbody.childNodes[0])
358 self.tbody.removeChild(self.tbody.childNodes[0]);
366 this.setNext = function(handler) {
367 var link = dojo.byId('acq-lit-next');
369 dojo.style(link, 'visibility', 'visible');
370 link.onclick = handler;
372 dojo.style(link, 'visibility', 'hidden');
376 this.setPrev = function(handler) {
377 var link = dojo.byId('acq-lit-prev');
379 dojo.style(link, 'visibility', 'visible');
380 link.onclick = handler;
382 dojo.style(link, 'visibility', 'hidden');
386 this.enableActionsDropdownOptions = function(mask) {
387 /* 'mask' is probably a misnomer the way I'm using it, but it needs to
388 * be one of pl,po,ao,gs,vp, or fs. */
389 dojo.query("option", "acq-lit-li-actions-selector").forEach(
391 var opt_mask = dojo.attr(option, "mask");
393 /* For each <option> element, an empty or non-existent mask
394 * attribute, a mask attribute of "*", or a mask attribute that
395 * matches this method's argument should result in that
396 * option's being enabled. */
398 option, "disabled", !(
401 opt_mask.search(mask) != -1
409 * Ensures this.focusLineitem is in view and causes a brief
410 * border around the lineitem to come to life then fade.
412 this.focusLi = function() {
413 if (!this.focusLineitem) return;
415 // set during addLineitem()
416 var node = dojo.byId('li-title-ref-' + this.focusLineitem);
418 // LI may not yet be rendered
421 // prevent numerous re-focuses
422 this.focusLineitem = null;
424 // causes the full row to be visible
425 dijit.scrollIntoView(node);
428 dojo.query('[attr=title]', node)[0].focus();
430 dojo.require('dojox.fx');
434 dojox.fx.highlight({color : '#BB4433', node : node, duration : 2000}).play();
439 this.show = function(div) {
440 openils.Util.hide('acq-lit-table-div');
441 openils.Util.hide('acq-lit-info-div');
442 openils.Util.hide('acq-lit-li-details');
443 openils.Util.hide('acq-lit-notes-div');
444 openils.Util.hide('acq-lit-real-copies-div');
445 openils.Util.hide('acq-lit-asset-creator');
448 openils.Util.show('acq-lit-table-div');
450 this.refreshInlineCopies();
453 openils.Util.show('acq-lit-info-div');
456 openils.Util.show('acq-lit-li-details');
459 openils.Util.show('acq-lit-real-copies-div');
462 openils.Util.show('acq-lit-notes-div');
464 case 'asset-creator':
465 openils.Util.show('acq-lit-asset-creator');
469 openils.Util.show(div);
473 this.hide = function() {
477 this.toggleSelect = function() {
479 dojo.forEach(self.selectors, function(i){i.checked = false});
481 dojo.forEach(self.selectors, function(i){i.checked = true});
482 self.toggleState = !self.toggleState;
486 this.getAll = function(callback, id_only, state) {
487 /* For some uses of the li table, we may not really know about "all"
488 * the lineitems that the user thinks we know about. If we're a paged
489 * picklist, for example, we only know about the lineitems we've
490 * displayed, but not necessarily all the lineitems on the picklist.
491 * So we reach out to pcrud to inform us.
492 * state: string/array. only lineitems in one of these states are
493 * included in the final result set. Not currently supported for
497 var oncomplete = function(r) {
498 var id_list = openils.Util.readResponse(r);
502 self.fetchLineitemsById(id_list, callback);
506 var search = {"picklist": this.isPL};
507 if (state) search.state = state;
510 "id_list": true, /* sic, even if id_only */
512 "oncomplete": oncomplete
516 } else if (this.isPO) {
517 var search = {"purchase_order": this.isPO};
518 if (state) search.state = state;
523 "oncomplete": oncomplete
527 } else if (this.isUni && this.pager) {
528 this.pager.getAllLineitemIDs(oncomplete);
532 /* If execution reaches this point, we don't need or can't perform
533 * any special tricks to find out the "real" list of "all" lineitems
534 * in this context, so we fall back to the old method.
536 callback(this.getSelected(true, null, id_only, state));
539 /** @param all If true, assume all are selected */
540 this.getSelected = function(
542 callback /* If you want a "good" idea of "all" lineitems, you must
543 provide a callback that accepts an array parameter, rather than
544 relying on the return value of this method itself. */,
548 console.log("getSelected states = " + state);
550 return this.getAll(callback, id_only, state);
552 var indices = {}; /* use to uniqify. needed in paging situations. */
553 dojo.forEach(this.selectors,
556 indices[i.parentNode.parentNode.getAttribute('li')] = true;
560 var result = openils.Util.objectProperties(indices);
562 // caller provided a lineitem state filter. remove IDs for lineitems
563 // not in the selected state.
566 if (!dojo.isArray(state)) state = [state];
567 dojo.forEach(result, function(liId) {
568 console.log('filter LI state ' + self.liCache[liId].state());
569 if (state.indexOf(self.liCache[liId].state()) >= 0)
576 result = result.map(function(liId) { return self.liCache[liId]; });
584 this.setRowAttr = function(td, liWrapper, field, type) {
585 var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
586 td.appendChild(document.createTextNode(val));
589 this.setClaimPolicyControl = function(li, row) {
590 if (!self._claimPolicyPickerLoading) {
591 self._claimPolicyPickerLoading = true;
593 new openils.widget.AutoFieldWidget({
594 "parentNode": "acq-lit-li-claim-policy",
596 "selfReference": true,
597 "dijitArgs": {"required": true}
599 function(w) { self.claimPolicyPicker = w; }
603 /* dojox.timing.doLater() is the best thing ever. Resource not yet
604 * ready? Just repeat my whole method when it is. */
605 if (dojox.timing.doLater(self.claimPolicyPicker)) {
609 row = self._findLiRow(li);
611 if (li.claim_policy()) {
612 /* This Dojo data dance is necessary to get a whole fieldmapper
613 * object based on a claim policy ID, since we alreay have the
614 * widget thing loaded with all that data, and can thereby
615 * avoid another request to the server. */
616 self.claimPolicyPicker.store.fetchItemByIdentity({
617 "identity": li.claim_policy(),
618 "onItem": function(a) {
619 var policy = (new acqclp()).fromStoreItem(a);
620 var span = nodeByName("claim_policy", row);
621 var inner = nodeByName("claim_policy_name", row);
623 openils.Util.show(span, "inline");
624 inner.innerHTML = policy.name();
626 "onError": function(e) {
631 openils.Util.hide(nodeByName("claim_policy", row));
632 nodeByName("claim_policy_name", row).innerHTML = "";
637 this.fetchClaimInfo = function(liId, force, callback, row) {
639 liId, function(full) {
640 self.liCache[full.id()] = full;
641 self.checkClaimEligibility(full, callback, row);
646 // fetch an updated copy of the lineitem
647 // and add it back to the lineitem table
648 this.refreshLineitem = function(li, focus) {
650 this._fetchLineitem(li.id(),
653 self.focusLineitem = li.id();
655 self.focusLineitem = null;
657 var row = dojo.query('[li='+li.id()+']', self.tbody)[0];
658 var nextSibling = row.nextSibling;
659 self.tbody.removeChild(row);
660 self.addLineitem(newLi, false, nextSibling);
666 * Inserts a single lineitem into the growing table of lineitems
667 * @param {Object} li The lineitem object to insert
669 this.addLineitem = function(li, skip_final_placement, nextSibling) {
670 this.liCache[li.id()] = li;
672 // insert the row right away so that final order isn't
673 // dependent on how long subsequent async request take
674 // for a given line item
675 var row = self.rowTemplate.cloneNode(true);
676 if (!skip_final_placement) {
678 // either no nextSibling was provided or it was null
679 // meaning the row was already at the end of the table
680 self.tbody.appendChild(row);
682 self.tbody.insertBefore(row, nextSibling);
686 self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
688 // sort the lineitem notes on edit_time
689 if(!li.lineitem_notes()) li.lineitem_notes([]);
691 var liWrapper = new openils.acq.Lineitem({lineitem:li});
692 row.setAttribute('li', li.id());
693 var tds = dojo.query('[attr]', row);
694 dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
695 dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
697 // so we can scroll to it later
698 dojo.query('[name=bib-info-cell]', row)[0].id = 'li-title-ref-' + li.id();
701 liWrapper.findAttr("isbn", "lineitem_marc_attr_definition") ||
702 liWrapper.findAttr("upc", "lineitem_marc_attr_definition");
704 // XXX media prefix for added content
706 nodeByName("jacket", row).setAttribute(
707 "src", "/opac/extras/ac/jacket/small/" + identifier
711 nodeByName("liid", row).innerHTML += li.id();
714 openils.Util.show(nodeByName('catalog', row), 'inline');
715 nodeByName("catalog_link", row).onclick = this.generateMakeRecTab(li.eg_bib_id());
717 openils.Util.show(nodeByName('link_to_catalog', row), 'inline');
718 nodeByName("link_to_catalog_link", row).onclick = function() { self.drawBibFinder(li) };
721 if (li.queued_record()) {
722 this.pcrud.retrieve('vqbr', li.queued_record(),
724 oncomplete : function(r) {
725 var qrec = openils.Util.readResponse(r);
726 openils.Util.show(nodeByName('queue', row), 'inline');
727 var link = nodeByName("queue_link", row);
728 link.onclick = function() {
729 // open a new tab to the vandelay queue for this record
730 openils.XUL.newTabEasy(
731 oilsBasePath + '/vandelay/vandelay?qtype=bib&qid=' + qrec.queue()
739 nodeByName("worksheet_link", row).href =
740 oilsBasePath + "/acq/lineitem/worksheet/" + li.id() +
741 '?source=' + encodeURIComponent(location.pathname + location.search)
743 nodeByName("show_requests_link", row).href =
744 oilsBasePath + "/acq/picklist/user_request?lineitem=" + li.id() +
745 '?source=' + encodeURIComponent(location.pathname + location.search)
747 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
748 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
749 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
750 dojo.query('[name=expand_inline_copies]', row)[0].onclick =
751 function() {self.drawInlineCopies(li.id())};
753 this.drawOrderIdentSelector(li, row);
755 if (!this.skipInitialEligibilityCheck)
759 function(full) { self.setClaimPolicyControl(full, row) },
763 this.updateLiNotesCount(li, row);
765 // show which PO this lineitem is a member of
766 if(li.purchase_order() && !this.isPO) {
768 this.poCache[li.purchase_order()] =
769 this.poCache[li.purchase_order()] ||
770 fieldmapper.standardRequest(
771 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
773 this.authtoken, li.purchase_order(), {
774 "flesh_price_summary": true,
775 "flesh_provider" : true,
776 "flesh_lineitem_count": true
779 if(po && !this.isMeta) {
780 openils.Util.show(nodeByName('po', row), 'inline');
781 var link = nodeByName('po_link', row);
782 link.setAttribute('href', oilsBasePath +
783 '/acq/po/view/' + li.purchase_order() +
784 '?focus_li=' + li.id() +
785 '&source=' + encodeURIComponent(location.pathname + location.search)
787 link.innerHTML += po.name();
789 openils.Util.show(nodeByName('pro', row), 'inline');
790 link = nodeByName('pro_link', row);
791 link.setAttribute('href', oilsBasePath + '/conify/global/acq/provider/' + po.provider().id())
792 link.innerHTML += po.provider().code();
796 // show which picklist this lineitem is a member of
797 if(li.picklist() && (this.isPO || this.isMeta || this.isUni)) {
799 this.plCache[li.picklist()] =
800 this.plCache[li.picklist()] ||
801 fieldmapper.standardRequest(
802 ['open-ils.acq', 'open-ils.acq.picklist.retrieve.authoritative'],
803 {params: [this.authtoken, li.picklist()]});
805 if (pl.name() == "") {
806 openils.Util.show(nodeByName("bib_origin", row), "inline");
810 openils.Util.show(nodeByName('pl', row), 'inline');
811 var link = nodeByName('pl_link', row);
812 link.setAttribute('href', oilsBasePath +
813 '/acq/picklist/view/' + li.picklist() +
814 '?focus_li=' + li.id() +
815 '&source=' + encodeURIComponent(location.pathname + location.search)
817 link.innerHTML += pl.name();
822 var countNode = nodeByName('count', row);
823 var count = li.item_count() || 0;
824 if (typeof(this._copy_count_cb) == "function") {
825 this._copy_count_cb(li.id(), count);
827 countNode.innerHTML = count;
828 countNode.id = 'acq-lit-copy-count-label-' + li.id();
831 var priceInput = dojo.query('[name=price]', row)[0];
832 priceInput.value = li.estimated_unit_price() || '';
833 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
835 // show either "mark received" or "unreceive" as appropriate
836 this.updateLiState(li, row);
838 if (skip_final_placement) {
842 // the last LI may be rendered after the call to show('list'),
843 // so make sure it's focused if necessary.
844 if (this.focusLineitem == li.id())
848 this._liCountClaims = function(li) {
850 for (var i = 0; i < li.lineitem_details().length; i++)
851 total += li.lineitem_details()[i].claims().length;
855 this._findLiRow = function(li) {
856 return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
859 this.reconsiderClaimControl = function(li, row) {
860 if (!row) row = this._findLiRow(li);
861 var option = nodeByName("action_manage_claims", row);
862 var eligible = this.claimEligibleLidByLi[li.id()].length;
863 var count = this._liCountClaims(li);
865 option.disabled = !(count || eligible);
867 dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
868 option.onclick = function() { self.claimDialog.show(li); };
871 this.clearEligibility = function(li) {
872 this.claimEligibleLidByLi[li.id()] = [];
874 if (li.lineitem_details()) {
875 li.lineitem_details().forEach(
876 function(lid) { delete self.claimEligibleLid[lid.id()]; }
880 if (this.copyCache) {
882 for (var k in this.copyCache) {
883 if (this.copyCache[k].lineitem() == li.id())
887 function(k) { delete self.claimEligibleLid[k]; }
892 this.applyOrderIdentValues = function() {
893 this._identValuesInFlight =
894 openils.Util.objectProperties(this.liCache).length;
895 for (var liId in this.liCache) {
896 this._applyOrderIdentValue(this.liCache[liId]);
900 // returns true if request was sent
901 this._applyOrderIdentValue = function(li, oncomplete) {
904 console.log('applying ident value for lineitem ' + li.id());
907 var row = dojo.query('[li=' + li.id() + ']')[0];
909 // find the selected ident value
910 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
911 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
912 var name = typeSel.options[typeSel.selectedIndex].value;
913 var val = typeSel._cbox.attr('value');
915 console.log("selected ident is " + val);
917 // it differs from the existing ident value, update it
918 var oldIdent = self.getLiOrderIdent(li);
920 oldIdent.attr_name() == name &&
921 oldIdent.attr_value() == val) {
922 console.log('selected ident attr matches existing attr');
923 if (--this._identValuesInFlight == 0) {
924 if (oncomplete) oncomplete(li);
925 else location.href = location.href;
930 // see if the selected ident value is represented
931 // by an existing lineitem attr
934 typeSel._cbox.store.fetch({
935 query : {attr_value : val},
936 onItem : function(item) {
937 console.log('found existing attr for ident value');
938 args.source_attr_id = li.attributes().filter(
939 function(attr) { return attr.id() == item.id[0] }
945 if (!args.source_attr_id) {
946 // user entered new text in the combobox
947 // so we need to create a new attr
948 console.log('creating new ident attr');
949 args.lineitem_id = li.id();
950 args.attr_name = name;
951 args.attr_value = val;
954 fieldmapper.standardRequest(
955 ['open-ils.acq', 'open-ils.acq.lineitem.order_identifier.set'],
957 params : [openils.User.authtoken, args],
958 oncomplete : function() {
959 console.log('order_ident oncomplete');
960 if (--self._identValuesInFlight == 0) {
961 if (oncomplete) oncomplete(li);
962 else location.href = location.href;
964 console.log(self._identValuesInFlight + ' still in flight');
972 this.getLiOrderIdent = function(li) {
973 var attrs = li.attributes();
974 if (!attrs) return null;
978 attr.attr_type() == 'lineitem_local_attr_definition' &&
979 openils.Util.isTrue(attr.order_ident())
985 this.drawOrderIdentSelector = function(li, row) {
987 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
988 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
990 var attrs = li.attributes();
992 // limit to MARC attr defs
993 attrs = attrs.filter(
995 return (attr.attr_type() == 'lineitem_marc_attr_definition');
999 var identAttr = this.getLiOrderIdent(li);
1002 // collect the values for each type of identifier
1003 // find a reasonable default identifier type to render
1007 dojo.forEach(['isbn', 'upc', 'issn'],
1010 // collect the values for this attr name
1011 values[name] = attrs.filter(
1013 return (attr.attr_name() == name)
1017 // select a reasonable default name in the type-selector
1021 if (identAttr.attr_name() == name)
1023 } else if (values[name].length) {
1028 dojo.forEach(typeSel.options, function(opt) {
1029 if (opt.value == name) {
1030 opt.selected = true;
1039 function updateOrderIdent(val) {
1040 self._identValuesInFlight = 1;
1041 self._applyOrderIdentValue(
1044 self.refreshLineitem(li);
1049 // replace the ident combobox with a new
1050 // one for the selected ident type
1051 function changeComboBox(sel) {
1052 var name = sel.options[sel.selectedIndex].value;
1054 var td = dojo.query('[name=order_ident_value]', row)[0];
1055 if (td.childNodes[0])
1056 dojo.destroy(td.childNodes[0]);
1058 var store = new dojo.data.ItemFileWriteStore({
1059 data : acqlia.toStoreData(values[name])
1062 var cbox = new dijit.form.ComboBox(
1064 labelAttr : 'attr_value',
1065 searchAttr : 'attr_value'
1067 dojo.create('div', {}, td)
1072 // set the value for the cbox
1073 if (values[name].length) {
1074 var orderIdent = self.getLiOrderIdent(li);
1076 if (orderIdent && orderIdent.attr_name() == name) {
1077 cbox.attr('value', orderIdent.attr_value());
1079 cbox.attr('value', values[name][0].attr_value());
1083 if (!self.orderIdentAllowed)
1084 cbox.attr('disabled', true);
1087 cbox._lineitem = li;
1088 dojo.connect(cbox, 'onChange', updateOrderIdent);
1091 changeComboBox(typeSel); // force the initial draw
1092 typeSel.onchange = function() {changeComboBox(typeSel)};
1095 this.testOrderIdentPerms = function(org, callback) {
1097 new openils.User().getPermOrgList(
1098 'ACQ_SET_LINEITEM_IDENTIFIER',
1100 console.log('found orgs = ' + orgs);
1101 for (var i = 0; i < orgs.length; i++) {
1102 if (Number(orgs[i]) == Number(org)) {
1103 self.orderIdentAllowed = true;
1104 if (callback) callback();
1108 if (callback) callback();
1114 this.checkClaimEligibility = function(li, callback, row) {
1115 /* Assume always eligible, i.e. from this interface we don't care about
1116 * claim eligibility any more. this is where the user would force a
1118 this.clearEligibility(li);
1119 this.claimEligibleLidByLi[li.id()] = li.lineitem_details().map(
1120 function(lid) { return lid.id(); }
1122 li.lineitem_details().forEach(
1123 function(lid) { self.claimEligibleLid[lid.id()] = true; }
1125 this.reconsiderClaimControl(li, row);
1126 if (callback) callback(li);
1128 this.clearEligibility(li);
1129 fieldmapper.standardRequest(
1130 ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
1131 "params": [openils.User.authtoken, {"lineitem": li.id()}],
1133 "onresponse": function(r) {
1134 if (r = openils.Util.readResponse(r)) {
1135 self.claimEligibleLidByLi[li.id()].push(
1138 self.claimEligibleLid[r.lineitem_detail()] = true;
1141 "oncomplete": function() {
1142 self.reconsiderClaimControl(li, row);
1143 if (typeof(callback) == "function")
1151 this.updateLiNotesCount = function(li, row) {
1152 if (!row) row = this._findLiRow(li);
1154 var has_notes = (li.lineitem_notes().filter(
1155 function(o) { return Boolean (o.alert_text()); }
1158 /* U+2691 is the code point for a filled-in flag character */
1159 nodeByName("notes_alert_flag", row).innerHTML =
1160 has_notes ? "⚑" : "";
1161 nodeByName("noteslink", row).style.fontStyle =
1162 has_notes ? "italic" : "normal";
1163 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
1166 /* XXX NOT related to _updateLiState(). rethink */
1167 this.updateLiState = function(li, row) {
1168 if (!row) row = this._findLiRow(li);
1170 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
1171 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
1173 // always allow access to LI history
1174 nodeByName('action_view_history', row).onclick =
1175 function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
1177 /* handle row coloring for based on LI state */
1178 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1179 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
1181 // Expose invoice actions for any lineitem that is linked to a PO
1182 if (li.purchase_order()) {
1183 openils.Util.show(nodeByName("invoices_span", row), "inline");
1184 var link = nodeByName("invoices_link", row);
1185 link.onclick = function() {
1186 openils.XUL.newTabEasy(
1187 oilsBasePath + "/acq/search/unified?so=" +
1188 base64Encode({"jub":[{"id": li.id()}]}) + "&rt=invoice"
1196 * If we haven't fleshed the lineitem_details, default to allowing access to the
1197 * holdings maintenence actions. The alternative is to flesh LIDs on every lineitem,
1198 * but that will add to page render time. Let's see if this will suffice...
1200 var lids = li.lineitem_details();
1202 (lids && !lids.filter(function(lid) { return lid.eg_copy_id() })[0] )) {
1204 actUpdateBarcodes.disabled = false;
1205 actUpdateBarcodes.onclick = function() {
1206 self.showRealCopyEditUI(li);
1207 nodeByName("action_none", row).selected = true;
1209 actHoldingsMaint.disabled = false;
1210 actHoldingsMaint.onclick =
1211 self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
1214 var state_cell = nodeByName("li_state_" + li.state(), row);
1216 // re-hide any state label nodes which may have been un-hidden
1217 // through previous actions.
1218 dojo.query('[state-label]', row).forEach(function(node) {
1219 openils.Util.hide(node)
1222 if (li.state() == 'cancelled') {
1223 if(typeof li.cancel_reason() == "object") {
1225 // clear the stock "Canceled" label, since we have more
1226 // information to replace it with.
1227 state_cell.innerHTML = '';
1229 var holds_state = dojo.create(
1231 "style": "border-bottom: 1px dashed #000;",
1232 "innerHTML": li.cancel_reason().label()
1233 }, state_cell, "only"
1237 "label": "<em>" + li.cancel_reason().label() +
1238 "</em><br />" + li.cancel_reason().description(),
1239 "connectId": [holds_state]
1240 }, dojo.create("span", null, state_cell, "last")
1243 if (li.cancel_reason().keep_debits() == 't') {
1244 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1245 openils.Util.addCSSClass(row, "oils-acq-li-state-delayed");
1248 console.log('li cancel_reason is un-fleshed. Please fix');
1252 openils.Util.show(state_cell);
1256 this._setAlertStore = function() {
1257 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
1259 "data": acqliat.toStoreData(
1262 "owning_lib": aou.orgNodeTrail(
1263 aou.findOrgUnit(openils.User.user.ws_ou())
1264 ).map(function(o) { return o.id(); })
1270 acqLitAlertAlertText.setValue(); /* make the store "live" */
1271 acqLitAlertAlertText._store_ready = true;
1275 * Draws and shows the lineitem notes pane
1277 this.drawLiNotes = function(li) {
1279 this.focusLineitem = li.id();
1281 if (!acqLitAlertAlertText._store_ready)
1282 this._setAlertStore();
1285 li.lineitem_notes().sort(
1287 if(a.edit_time() < b.edit_time()) return 1;
1293 while(this.liNotesTbody.childNodes[0])
1294 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
1297 acqLitCreateNoteSubmit.onClick = function() {
1298 var value = acqLitCreateNoteText.attr('value');
1300 var note = new fieldmapper.acqlin();
1303 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
1306 note.lineitem(li.id());
1308 self.updateLiNotes(li, note);
1309 acqLitCreateNoteVendorPublic.attr("checked", false);
1310 acqLitCreateNoteText.attr("value", "");
1313 acqLitCreateAlertSubmit.onClick = function() {
1314 if (!acqLitAlertAlertText.item) {
1315 alert(localeStrings.ALERT_UNSELECTED);
1319 var alert_text = new fieldmapper.acqliat().fromStoreItem(
1320 acqLitAlertAlertText.item
1322 var value = acqLitAlertNoteValue.attr("value") || "";
1324 var note = new fieldmapper.acqlin();
1326 note.lineitem(li.id());
1328 note.alert_text(alert_text);
1330 self.updateLiNotes(li, note);
1333 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
1337 * Draws a single lineitem note in the notes pane
1339 this.addLiNote = function(li, note) {
1340 if(note.isdeleted()) return;
1342 var row = self.liNotesRow.cloneNode(true);
1343 nodeByName("value", row).innerHTML = note.value();
1344 var alert_node = nodeByName("alert_code", row);
1345 if (note.alert_text()) {
1346 alert_node.innerHTML = dojo.string.substitute(
1348 aou.findOrgUnit(note.alert_text().owning_lib()).shortname(),
1349 note.alert_text().code()
1352 if (note.alert_text().description()) {
1355 "connectId": [alert_node],
1356 "label": note.alert_text().description()
1357 }, dojo.create("span", null, alert_node, "after")
1362 if (openils.Util.isTrue(note.vendor_public()))
1363 nodeByName("vendor_public", row).innerHTML =
1364 localeStrings.VENDOR_PUBLIC;
1366 nodeByName("delete", row).onclick = function() {
1367 note.isdeleted(true);
1368 self.liNotesTbody.removeChild(row);
1369 self.updateLiNotes(li);
1372 if(note.edit_time()) {
1373 nodeByName("edit_time", row).innerHTML =
1374 dojo.date.locale.format(
1375 dojo.date.stamp.fromISOString(note.edit_time()),
1376 {formatLength:'short'});
1379 self.liNotesTbody.appendChild(row);
1383 * Updates any new/changed/deleted notes on the server
1385 this.updateLiNotes = function(li, newNote) {
1391 notes = li.lineitem_notes().filter(
1393 if(note.ischanged() || note.isnew() || note.isdeleted())
1399 if(notes.length == 0) return;
1400 progressDialog.show();
1402 fieldmapper.standardRequest(
1403 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
1405 params : [this.authtoken, notes],
1406 onresponse : function(r) {
1407 var resp = openils.Util.readResponse(r);
1412 // remove the old changed notes
1414 dojo.forEach(li.lineitem_notes(),
1416 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
1420 li.lineitem_notes(list);
1423 progressDialog.hide();
1424 self.updateLiNotesCount(li);
1425 self.drawLiNotes(li);
1429 progressDialog.update(resp);
1430 var newnote = resp.note;
1432 if(!newnote.isdeleted()) {
1433 newnote.isnew(false);
1434 newnote.ischanged(false);
1435 li.lineitem_notes().push(newnote);
1442 this.updateLiPrice = function(input, li) {
1444 var price = input.value;
1445 if(Number(price) == Number(li.estimated_unit_price())) return;
1447 fieldmapper.standardRequest(
1448 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
1449 { async : false, // redundant w/ timeout
1451 params : [this.authtoken, li.id(), price],
1452 oncomplete : function(r) {
1453 openils.Util.readResponse(r);
1454 li.estimated_unit_price(price); // update local copy
1457 * If this is a PO and every visible lineitem has a price,
1458 * check again to see if this PO can be activated. Note that
1459 * every visible lineitem having a price does not guarantee it can
1460 * be activated, which is why we still make the call. Having a price
1461 * set for every visiable lineitem is just the lowest barrier to entry.
1464 var priceNodes = dojo.query('[name=price]', dojo.byId('acq-lit-tbody'));
1466 dojo.forEach(priceNodes, function(node) { if (node.value == '') allSet = false});
1467 if (allSet) checkCouldActivatePo();
1474 this.removeLineitem = function(liId) {
1475 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
1476 delete this.liCache[liId];
1477 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
1480 this.drawInfo = function(liId) {
1481 this.focusLineitem = liId;
1482 if (!this._isRelatedViewer) {
1483 var d = dojo.byId("acq-lit-info-related");
1484 if (!this.relCache[liId]) {
1485 fieldmapper.standardRequest(
1488 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
1491 "params": [openils.User.authtoken, liId],
1492 "onresponse": function(r) {
1493 self.relCache[liId] = openils.Util.readResponse(r);
1494 nodeByName("related_number", d).innerHTML =
1495 self.relCache[liId];
1497 self.relCache[liId] >1 ? "show" : "hide"
1503 nodeByName("related_number", d).innerHTML = this.relCache[liId];
1504 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
1509 openils.acq.Lineitem.fetchAttrDefs(
1511 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
1516 this.toggleInlineCopies = function() {
1517 // if any inline copies are not displayed,
1518 // display them all otherwise, hide them all.
1520 var displayAll = false;
1522 for (var liId in this.liCache) {
1523 if (!this.inlineCopiesVisible(liId)) {
1529 for (var liId in this.liCache) {
1530 var row = dojo.byId('acq-inline-copies-row-' + liId);
1532 if (!row || row._hidden) {
1533 this.drawInlineCopies(liId);
1535 } else { // hide all
1537 // drawInlineCopies() on a visible row will hide it.
1538 this.drawInlineCopies(liId);
1545 this.inlineCopiesVisible = function(liId) {
1546 var row = dojo.byId('acq-inline-copies-row-' + liId);
1547 return (row && !row._hidden);
1550 this.refreshInlineCopies = function(all, reFetch) {
1552 var liIds = this.inlineCopiesNeedingRefresh;
1553 if (all) liIds = openils.Util.objectProperties(liCache);
1554 liIds.forEach(function(liId) {
1555 if (self.inlineCopiesVisible(liId)) {
1556 self.drawInlineCopies(liId, reFetch); // hide
1557 self.drawInlineCopies(liId, reFetch); // re-draw
1562 // draw inline copy table. if the table is
1563 // already visible, hide the table as-is
1564 // reFetch forces a retrieval of the lineitem and
1565 // copies from the server. otherwise the locally
1566 // cached version of each is used.
1567 this.drawInlineCopies = function(liId, reFetch) {
1570 // find or create the row where the inline copies table will live
1571 var containerRow = dojo.byId('acq-inline-copies-row-' + liId);
1572 var liRow = dojo.query('[li=' + liId + ']')[0];
1574 if (!containerRow) {
1576 // build the inline copies container row and add it to
1577 // the DOM directly after the primary lineitem row
1579 containerRow = self.inlineCopyContainer.cloneNode(true);
1580 containerRow.id = 'acq-inline-copies-row-' + liId;
1582 if (liRow.nextSibling) {
1583 self.tbody.insertBefore(containerRow, liRow.nextSibling);
1585 self.tbody.appendChild(containerRow);
1590 // toggle the visible state
1591 containerRow._hidden = !containerRow._hidden;
1592 openils.Util.toggle(containerRow, 'table-row');
1594 if (containerRow._hidden) return; // hide only
1597 var handler = function(li) {
1599 var tbody = dojo.query(
1600 '[name=acq-li-inline-copies-tbody]',
1603 // reset the table before adding copy rows
1604 while (tbody.childNodes[0])
1605 tbody.removeChild(tbody.childNodes[0]);
1607 if(li.lineitem_details().length == 0) {
1609 self.inlineNoCopies.cloneNode(true));
1610 return; // no copies to show
1613 // add a row to the inline copy table for each copy
1614 dojo.forEach(li.lineitem_details(),
1616 var row = self.inlineCopyTemplate.cloneNode(true);
1617 tbody.appendChild(row);
1618 self.addInlineCopy(li, copy, row);
1623 this._fetchLineitem(liId, handler, reFetch);
1626 /** Draw read-only copy widgets for inline copies */
1627 this.addInlineCopy = function(li, copy, row) {
1630 dojo.forEach(liDetailFields,
1633 var widget = new openils.widget.AutoFieldWidget({
1636 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1637 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1638 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1640 parentNode : dojo.query('[name=' + field + ']', row)[0],
1649 /* For a given list of lineitem ids, build a list of full lineitems
1650 * re-using the fetching logic that is otherwise typical to use in this
1653 * If we've already got a lineitem in the cache, just use that.
1655 * Once we've built a list of lineitems, call callback(thatlist).
1657 this.fetchLineitemsById = function(id_list, callback) {
1658 var total = id_list.length;
1659 var result_list = [];
1661 var inner = function(li) {
1662 result_list.push(li)
1664 callback(result_list);
1667 id_list.forEach(function(id) { self._fetchLineitem(id, inner); });
1670 this._fetchLineitem = function(liId, handler, force) {
1672 var li = this.liCache[liId];
1673 if(li && li.marc() && li.lineitem_details() && !force)
1676 fieldmapper.standardRequest(
1677 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
1680 params: [self.authtoken, liId, {
1682 flesh_cancel_reason: true,
1683 flesh_li_details: true,
1685 flesh_fund_debit: true }],
1687 oncomplete: function(r) {
1688 var li = openils.Util.readResponse(r);
1689 self.liCache[liId] = li;
1696 this._drawInfo = function(li) {
1698 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
1700 if(li.eg_bib_id()) {
1701 openils.Util.hide('acq-lit-marc-order-record-label');
1702 openils.Util.hide(acqLitEditOrderMarc.domNode);
1703 openils.Util.show('acq-lit-marc-real-record-label');
1705 openils.Util.show('acq-lit-marc-order-record-label');
1706 openils.Util.show(acqLitEditOrderMarc.domNode);
1707 openils.Util.hide('acq-lit-marc-real-record-label');
1710 this.drawMarcHTML(li);
1711 this.infoTbody = dojo.byId('acq-lit-info-tbody');
1714 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
1715 while(this.infoTbody.childNodes[0])
1716 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
1718 for(var i = 0; i < li.attributes().length; i++) {
1719 var attr = li.attributes()[i];
1720 var row = this.infoRow.cloneNode(true);
1722 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
1723 var name = openils.acq.Lineitem.attrDefs[type].filter(
1725 return (a.code() == attr.attr_name());
1727 ).pop().description();
1729 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
1730 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
1731 this.infoTbody.appendChild(row);
1734 if (!this._isRelatedViewer) {
1735 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
1736 oilsBasePath + "/acq/lineitem/related/" + li.id();
1739 // if a top scroll point is defined, jump up to it here
1740 var node = dojo.byId('oils-scroll-to-top');
1741 if (node) dijit.scrollIntoView(node);
1744 this.generateMakeRecTab = function(bib_id,default_view, row) {
1748 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
1751 show_nav_buttons : true,
1752 show_print_button : true,
1753 opac_url : xulG.url_prefix('opac_rdetail|' + bib_id),
1754 default_view : default_view
1758 if(row) nodeByName("action_none", row).selected = true;
1762 this.drawMarcHTML = function(li) {
1763 var params = [null, true, li.marc()];
1765 params = [li.eg_bib_id(), true];
1767 fieldmapper.standardRequest(
1768 ['open-ils.search', 'open-ils.search.biblio.record.html'],
1771 oncomplete: function(r) {
1772 dojo.byId('acq-lit-marc-div').innerHTML =
1773 openils.Util.readResponse(r);
1779 this.drawCopies = function(liId, force_fetch) {
1780 this.focusLineitem = liId;
1781 if (typeof force_fetch == "undefined")
1782 force_fetch = false;
1784 var cgi = new openils.CGI();
1785 var source = cgi.param('source');
1786 if (source && source.match(/invoice/)) {
1787 // got here from the invoice page, show the 'return-to-invoice' button
1788 var cgi = new openils.CGI({url : source});
1789 cgi.param('focus_li', liId);
1790 openils.Util.show(dojo.byId('acq-lit-copies-back-to-invoice-button-wrapper'), 'inline');
1791 var button = dojo.byId('acq-lit-copies-back-to-invoice-button');
1792 button.onclick = function() { location.href = cgi.url() };
1795 openils.acq.Lineitem.fetchAndRender(liId, {},
1796 function(li, html) {
1797 dojo.byId('acq-lit-copies-li-summary').innerHTML = html;
1801 this.show('copies');
1803 this.copyCache = {};
1804 this.copyWidgetCache = {};
1805 this.oldCopyWidgetCache = {};
1806 this.virtDfaCounts = {};
1807 this.realDfaCache = {};
1810 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
1811 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
1812 acqLitCopyCountInput.attr('value', '0');
1814 if (this.isPO && PO && PO.order_date()) {
1815 // prevent adding copies to activated POs
1816 acqLitCopyCountInput.attr('disabled', true);
1817 acqLitAddCopyCount.attr('disabled', true);
1820 while(this.copyTbody.childNodes[0])
1821 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
1823 this._drawBatchCopyWidgets();
1825 this._drawDistribApplied(liId);
1827 this._fetchDistribFormulas(
1829 openils.acq.Lineitem.fetchAttrDefs(
1831 self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch);
1838 this._saveDistribAppliedTemplates = function() {
1839 if (!this._appliedDistribTemplate) {
1840 this._appliedDistribTemplate =
1841 dojo.byId("acq-lit-distrib-applied-tbody").
1842 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
1843 dojo.attr(this._appliedDistribTemplate, "id");
1847 this._drawDistribApplied = function(liId) {
1848 /* Build this table while hidden to prevent rendering artifacts */
1849 openils.Util.hide("acq-lit-distrib-applied-tbody");
1851 this._saveDistribAppliedTemplates();
1853 /* Remove any rows in the table from previous populations */
1854 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
1855 forEach(dojo.destroy);
1857 /* Unregister all dijits previously created (for some reason this isn't
1858 * covered by the above destroy calls). */
1859 dijit.registry.forEach(
1860 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
1863 /* Populate the table with our liId */
1865 fieldmapper.standardRequest(
1867 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
1870 "params": [self.authtoken, liId],
1871 "onresponse": function(r) {
1872 var dfa = openils.Util.readResponse(r);
1875 self.realDfaCache[dfa.id()] = dfa;
1876 self._drawDistribAppliedUnit(dfa);
1879 "oncomplete": function() {
1880 /* Reveal built table */
1883 "acq-lit-distrib-applied-tbody", "table-row-group"
1891 this._drawDistribAppliedUnit = function(dfa) {
1892 var new_row = false;
1893 var row = dojo.query(
1894 'tr[formula="' + dfa.formula().id() + '"]',
1895 "acq-lit-distrib-applied-tbody"
1900 row = dojo.clone(this._appliedDistribTemplate);
1901 dojo.attr(row, "formula", dfa.formula().id());
1902 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
1905 var td = dojo.query("td", row)[0];
1907 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1908 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1911 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1913 new dijit.form.Button(
1915 "onClick": function() {
1916 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1917 self.deleteDfa(dfa);
1920 /* XXX I /cannot/ make the following work in as a CSS class
1921 * for some reason. So frustrating... */
1922 "style": function(id) {
1924 "font-weight: bold; color: #c00;" :
1926 }(dfa.id()) + "margin: 0 6px;display: inline;"
1927 }, "dfa-button-" + dfa.id()
1931 "connectId": ["dfa-button-" + dfa.id()],
1932 "label": dojo.string.substitute(
1933 localeStrings.DFA_TIP, dfa.id() > 0 ? [
1934 openils.User.formalName(dfa.creator()),
1935 dojo.date.locale.format(
1936 dojo.date.stamp.fromISOString(dfa.create_time()),
1937 {"formatLength":"short"}
1939 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
1941 }, "dfa-tip-" + dfa.id()
1945 this.deleteDfa = function(dfa) {
1946 if (dfa.id() > 0) { /* real */
1947 this.pcrud.eliminate(
1950 "oncomplete": function() {
1951 self._removeDistribApplied(dfa.id());
1952 delete self.realDfaCache[dfa.id()];
1956 } else { /* virtual */
1957 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
1958 this.virtDfaCounts[dfa.formula().id()] = 0;
1959 /* hasn't been saved yet, so no need to do anything server side */
1960 this._removeDistribApplied(dfa.id());
1965 this._removeDistribApplied = function(dfaId) {
1966 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
1967 dijit.registry.forEach(
1968 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
1970 this._removeDistribAppliedEmptyRows();
1973 this._removeAllDistribAppliedVirtual = function() {
1974 /* Unregister dijits */
1975 dijit.registry.forEach(
1976 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
1978 this._removeDistribAppliedEmptyRows();
1981 this._removeDistribAppliedEmptyRows = function() {
1982 /* Remove any rows with no DFA at all */
1983 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
1985 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
1991 * Insert a new row into the distribution formula selection form
1993 this._addDistribFormulaRow = function() {
1996 if (!self.distribForms) {
1997 // no formulas, hide the form
1998 openils.Util.hide('acq-lit-distrib-formula-table');
2002 if(!this.distribFormulaTemplate)
2003 this.distribFormulaTemplate =
2004 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
2006 var row = this.distribFormulaTemplate.cloneNode(true);
2007 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
2009 this.dfSelector = new dijit.form.FilteringSelect(
2010 {"labelAttr": "dynLabel", "labelType": "html"},
2011 nodeByName("selector", row)
2013 this._updateFormulaStore();
2014 this.dfSelector.fetchProperties =
2015 {"sort": [{"attribute": "use_count", "descending": true}]};
2017 var apply = new dijit.form.Button(
2018 {"label": localeStrings.APPLY},
2019 nodeByName('set_button', row)
2022 var reset = new dijit.form.Button(
2023 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
2024 nodeByName("reset_button", row)
2027 dojo.connect(apply, 'onClick',
2029 var form_id = self.dfSelector.attr("value");
2030 if(!form_id) return;
2031 self._applyDistribFormula(form_id);
2032 reset.attr("disabled", false);
2036 dojo.connect(reset, 'onClick',
2038 self.restoreCopyFieldsBeforeDF();
2039 self.virtDfaCounts = {};
2040 self.virtDfaId = -1;
2042 self._updateFormulaStore();
2043 self._removeAllDistribAppliedVirtual();
2044 reset.attr("disabled", "true");
2051 * Applies a distrib formula to the current set of copies
2053 this._applyDistribFormula = function(formula) {
2054 if(!formula) return;
2056 formula = this.distribForms.filter(
2057 function(form) { return form.id() == formula; }
2060 var copyRows = dojo.query('tr', self.copyTbody);
2062 if (this.dfeOffset >= copyRows.length) {
2063 alert(localeStrings.OUT_OF_COPIES);
2067 var entries_applied = 0;
2069 var rowIndex = this.dfeOffset;
2070 rowIndex < copyRows.length;
2074 var row = copyRows[rowIndex];
2075 var copy_id = row.getAttribute('copy_id');
2076 var copyWidgets = this.copyWidgetCache[copy_id];
2077 var entryIndex = this.dfeOffset;
2080 // find the correct entry for the current row
2081 dojo.forEach(formula.entries(),
2084 entryIndex += e.item_count();
2085 if(entryIndex > rowIndex)
2093 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
2094 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
2097 this.saveCopyFieldsBeforeDF(copy_id);
2098 this._copy_fields_for_acqdf.forEach(
2100 if(entry[field]()) {
2101 copyWidgets[field].attr('value', (entry[field]()));
2108 if (entries_applied) {
2109 this.virtDfaCounts[formula.id()] =
2110 ++(this.virtDfaCounts[formula.id()]) || 1;
2111 this._updateFormulaStore();
2112 this._drawDistribAppliedUnit(
2114 var dfa = new acqdfa();
2115 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
2118 this.dfeOffset += entries_applied;
2123 * This function updates the DF store for the dropdown so that use_counts
2124 * can reflect DF applications from this session before they're saved
2127 this._updateFormulaStore = function() {
2128 this.dfSelector.store = new dojo.data.ItemFileReadStore(
2130 "data": self._labelFormulasWithCounts(
2131 acqdf.toStoreData(self.distribForms)
2137 this.saveCopyFieldsBeforeDF = function(copy_id) {
2139 if (!this.oldCopyWidgetCache[copy_id]) {
2140 var copyWidgets = this.copyWidgetCache[copy_id];
2142 this.oldCopyWidgetCache[copy_id] = {};
2143 this._copy_fields_for_acqdf.forEach(
2145 self.oldCopyWidgetCache[copy_id][f] =
2146 copyWidgets[f].attr("value");
2152 this.restoreCopyFieldsBeforeDF = function() {
2154 for (var copy_id in this.oldCopyWidgetCache) {
2155 this._copy_fields_for_acqdf.forEach(
2157 self.copyWidgetCache[copy_id][f].attr(
2158 "value", self.oldCopyWidgetCache[copy_id][f]
2165 this._labelFormulasWithCounts = function(store_data) {
2166 for (var key in store_data.items) {
2167 var obj = store_data.items[key];
2168 obj.use_count = Number(obj.use_count); /* needed for sorting */
2170 if (this.virtDfaCounts[obj.id])
2171 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
2173 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
2174 obj.use_count + "]</span> " + obj.name;
2180 * This method formerly would not refetch the DF formulas if they'd been
2181 * loaded already, but now it always re-fetches, since use_count changes.
2183 /** TODO: port distrib-formula selector to autofieldwidget+pcrud/dojo store */
2184 this._fetchDistribFormulas = function(onload) {
2185 fieldmapper.standardRequest(
2187 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
2190 "params": [openils.User.authtoken, 0, 500],
2191 "oncomplete": function(r) {
2192 self.distribForms = openils.Util.readResponse(r);
2193 if(!self.distribForms || self.distribForms.length == 0) {
2194 self.distribForms = [];
2196 self._addDistribFormulaRow();
2203 this._drawBatchCopyWidgets = function() {
2204 var row = this.copyBatchRow;
2205 dojo.forEach(liDetailBatchFields,
2207 if(self.copyBatchRowDrawn) {
2208 self.copyBatchWidgets[field].attr('value', null);
2210 var args = self.afwCopyFieldArgs(field, "CREATE_PICKLIST");
2211 args.parentNode = dojo.query('[name='+field+']', row)[0];
2213 var widget = new openils.widget.AutoFieldWidget(args);
2216 if (field == "fund" && w.store)
2217 self._ensureCSSFundClasses(w.store);
2218 self.copyBatchWidgets[field] = w;
2221 if (field == "fund") {
2223 widget.widget, "onChange", function(val) {
2224 self._updateFundSelectorStyle(widget, val);
2231 this.copyBatchRowDrawn = true;
2234 this.batchCopyUpdate = function() {
2236 for(var k in this.copyWidgetCache) {
2237 var cache = this.copyWidgetCache[k];
2238 dojo.forEach(liDetailBatchFields, function(f) {
2239 var newval = self.copyBatchWidgets[f].attr('value');
2240 if(newval) cache[f].attr('value', newval);
2245 this._drawCopies = function(li) {
2248 // this button sets the total number of copies for a given lineitem
2249 acqLitAddCopyCount.onClick = function() {
2250 var count = acqLitCopyCountInput.attr('value');
2253 while(self.copyCount() < count)
2256 // delete rows if necessary
2257 var diff = self.copyCount() - count;
2259 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
2260 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
2261 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
2263 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2269 if(li.lineitem_details().length > 0) {
2270 dojo.forEach(li.lineitem_details(),
2272 self.addCopy(li, copy);
2280 this.copyCount = function() {
2282 for(var id in this.copyCache) {
2283 if(!this.copyCache[id].isdeleted())
2289 this.virtCopyId = -1;
2290 this.addCopy = function(li, copy) {
2291 var row = this.copyRow.cloneNode(true);
2292 this.copyTbody.appendChild(row);
2296 copy = new fieldmapper.acqlid();
2298 copy.id(this.virtCopyId--);
2299 copy.lineitem(li.id());
2302 this.copyCache[copy.id()] = copy;
2303 row.setAttribute('copy_id', copy.id());
2304 self.copyWidgetCache[copy.id()] = {};
2306 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2308 var rcvr = copy.receiver();
2310 if (!userCache[rcvr]) {
2311 if(rcvr == openils.User.user.id()) {
2312 userCache[rcvr] = openils.User.user;
2314 userCache[rcvr] = fieldmapper.standardRequest(
2315 ['open-ils.actor', 'open-ils.actor.user.retrieve'],
2316 {params: [openils.User.authtoken, rcvr]}
2320 dojo.query('[name=receiver]', row)[0].innerHTML = userCache[rcvr].usrname();
2323 dojo.forEach(liDetailFields,
2326 if (field == "fund") {
2327 searchFilter = (copy.fund() ?
2328 {"-or": {"active": "t", "id": copy.fund()}} :
2330 searchFilter.org = fundSearchFilter.org;
2332 searchFilter = null;
2335 var readOnly = false;
2337 // TODO: Add support for changing the owning_lib after real copies have been made.
2338 // owning_lib is order data as much as its item data
2339 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
2343 // TODO: add support for changing the fund after debits have been created
2344 // Note: invoicing allows the change
2345 if(copy.fund_debit() && field == 'fund') {
2350 var widget = new openils.widget.AutoFieldWidget({
2353 labelFormat : (field == 'fund') ? fundLabelFormat : null,
2354 searchFormat : (field == 'fund') ? fundSearchFormat : null,
2355 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
2356 searchFilter : searchFilter,
2357 noCache: (field == "fund"),
2359 parentNode : dojo.query('[name='+field+']', row)[0],
2360 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2361 readOnly : readOnly,
2362 orgDefaultsToWs : true
2366 // make sure we capture the value from any async widgets
2369 if (field == "fund" && w.store)
2370 self._ensureCSSFundClasses(w.store);
2373 copy[field](ww.getFormattedValue())
2375 self.copyWidgetCache[copy.id()][field] = w;
2377 dojo.connect(w, 'onChange',
2379 if (field == "fund")
2380 self._updateFundSelectorStyle(widget, val);
2382 if (!readOnly && (copy.isnew() || val != copy[field]())) {
2383 // prevent setting ischanged() automatically on widget load for existing copies
2384 copy[field](widget.getFormattedValue())
2385 copy.ischanged(true);
2394 this.updateLidState(copy, row);
2397 this._ensureCSSFundClass = function(id) {
2398 if (!this.fundStyleSheet) {
2400 "style", {"type": "text/css"},
2401 document.getElementsByTagName("head")[0], "last"
2403 this.fundStyleSheet = document.styleSheets[
2404 document.styleSheets.length - 1
2408 var cn = "fund_" + id;
2409 if (!this.haveFundClass[cn]) {
2410 fieldmapper.standardRequest(
2411 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
2413 "params": [openils.User.authtoken, id],
2415 "oncomplete": function(r) {
2416 r = openils.Util.readResponse(r);
2417 self.fundBalanceState[id] = r;
2419 if (r[0] /* stop */)
2420 style = fundStyles.stop;
2421 else if (r[1] /* warning */)
2422 style = fundStyles.warning;
2423 self.fundStyleSheet.insertRule(
2424 "." + cn + " { " + style + " }",
2425 self.fundStyleSheet.cssRules.length
2427 self.haveFundClass[cn] = true;
2434 this._ensureCSSFundClasses = function(store) {
2436 "query": {"id": "*"},
2437 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
2441 this._updateFundSelectorStyle = function(widget, fund_id) {
2442 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
2443 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
2446 this.updateLidState = function(copy, row) {
2449 if (typeof(row) == "undefined") {
2450 row = dojo.query('tr[copy_id="' + copy.id() + '"]', this.copyTbody)[0];
2454 var recv_link = nodeByName("receive", row);
2455 var unrecv_link = nodeByName("unreceive", row);
2456 var del_link = nodeByName("delete", row);
2457 var cxl_link = nodeByName("cancel", row);
2458 var claim_link = nodeByName("claim", row);
2459 var cxl_reason_link = nodeByName("cancel_reason", row);
2461 // by default, hide all the actions
2462 openils.Util.hide(del_link.parentNode);
2463 openils.Util.hide(recv_link);
2464 openils.Util.hide(unrecv_link);
2465 openils.Util.hide(cxl_link);
2466 openils.Util.hide(claim_link);
2467 openils.Util.hide(cxl_reason_link);
2469 if (copy.id() > 0) { // real copies (LIDs)
2471 if (copy.cancel_reason()) {
2473 /* --------- cancelled -------------------------- */
2475 /* XXX the following may leak memory in a long lived table:
2476 * dijits may not get destroyed... not positive. revisit. */
2477 var holds_reason = dojo.create(
2479 "style": "border-bottom: 1px dashed #000;",
2480 "innerHTML": copy.cancel_reason().label()
2481 }, cxl_reason_link, "only"
2485 "label": "<em>" + copy.cancel_reason().label() +
2486 "</em><br />" + copy.cancel_reason().description(),
2487 "connectId": [holds_reason]
2488 }, dojo.create("span", null, cxl_reason_link, "last")
2490 openils.Util.show(cxl_reason_link, "inline");
2492 if (copy.cancel_reason().keep_debits() == 't' ) {
2493 // allow further cancellation of "delayed" copies
2495 openils.Util.show(cxl_link, "inline");
2496 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2499 } else if (copy.recv_time()) {
2501 /* --------- received -------------------------- */
2503 openils.Util.show(unrecv_link, "inline");
2504 unrecv_link.onclick = function() {
2505 if (confirm(localeStrings.UNRECEIVE_LID))
2506 self.issueReceive(copy, /* rollback */ true);
2509 } else if (this.liCache[copy.lineitem()].state() == 'on-order') {
2511 /* --------- on order -------------------------- */
2513 openils.Util.show(recv_link, 'inline');
2514 openils.Util.show(cxl_link, "inline");
2516 recv_link.onclick = function() {
2517 if (self.checkLiAlerts(copy.lineitem()))
2518 self.issueReceive(copy);
2521 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2525 /* --------- pre-order copies -------------------------- */
2527 del_link.onclick = function() { self.deleteCopy(row) };
2528 openils.Util.show(del_link.parentNode);
2534 /* --------- virtual copies -------------------------- */
2536 del_link.onclick = function() { self.deleteCopy(row) };
2537 openils.Util.show(del_link.parentNode);
2541 this.cancelLid = function(lid_id) {
2542 lidCancelDialog._lid_id = lid_id;
2543 openils.Util.show(lidCancelDialog.domNode.parentNode);
2544 lidCancelDialog.show();
2545 if (!lidCancelDialog._prepared) {
2546 var widget = new openils.widget.AutoFieldWidget({
2547 "fmField": "cancel_reason",
2548 "fmClass": "acqlid",
2549 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
2550 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2552 "searchOptions" : {order_by : {"acqcr":"label"}}
2556 acqLidCancelButton.onClick = function() {
2557 if (w.attr("value")) {
2558 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
2560 lidCancelDialog._lid_id,
2564 lidCancelDialog.hide();
2567 lidCancelDialog._prepared = true;
2573 this._cancelLid = function(lid_id, reason) {
2574 fieldmapper.standardRequest(
2575 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
2576 "params": [openils.User.authtoken, lid_id, reason],
2578 "onresponse": function(r) {
2579 if (r = openils.Util.readResponse(r)) {
2581 for (var id in r.lid) {
2582 /* actually this should only iterate once */
2583 self.copyCache[id].cancel_reason(
2584 r.lid[id].cancel_reason
2586 self.updateLidState(self.copyCache[id]);
2595 this._confirmAlert = function(li, lin) {
2597 dojo.string.substitute(
2598 localeStrings.CONFIRM_LI_ALERT, [
2599 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2600 "title", "lineitem_marc_attr_definition"
2602 /* XXX it's really better add a parameter and to adjust
2603 * the format string rather than do this concatenation
2604 * here, but if someone wants this for 2.2 in a hurry,
2605 * we can sidestep the problem of updating the strings
2606 * while the translators are working. */
2608 aou.findOrgUnit(lin.alert_text().owning_lib()).shortname() +
2610 lin.alert_text().code()
2612 lin.alert_text().description() || "",
2619 this.checkLiAlerts = function(li_id) {
2620 var li = this.liCache[li_id];
2622 var alert_notes = li.lineitem_notes().filter(
2623 function(o) { return Boolean(o.alert_text()); }
2626 /* this is _intentionally_ not done in a call to forEach() ... */
2627 for (var i = 0; i < alert_notes.length; i++) {
2628 if (this.noteAcks[alert_notes[i].id()])
2630 else if (!this._confirmAlert(li, alert_notes[i]))
2633 this.noteAcks[alert_notes[i].id()] = true;
2639 this.deleteCopy = function(row) {
2640 var copy = this.copyCache[row.getAttribute('copy_id')];
2641 copy.isdeleted(true);
2643 delete this.copyCache[copy.id()];
2644 this.copyTbody.removeChild(row);
2647 this._virtDfaCountsAsList = function() {
2649 for (var key in this.virtDfaCounts) {
2650 for (var i = 0; i < this.virtDfaCounts[key]; i++)
2656 this.confirmBreachedCopyFunds = function(copies) {
2657 var stop = 0, warning = 0;
2661 var state = self.fundBalanceState[o.fund()];
2662 if (state[0] /* stop */)
2664 else if (state[1] /* warning */)
2671 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
2672 } else if (warning) {
2673 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
2678 this.saveCopyChanges = function(liId) {
2684 for(var id in this.copyCache) {
2685 var c = this.copyCache[id];
2686 if(!c.isdeleted()) total++;
2687 if(c.isnew() || c.ischanged() || c.isdeleted()) {
2688 if(c.id() < 0) c.id(null);
2694 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
2697 if (copies.length > 0) {
2698 if (!this.confirmBreachedCopyFunds(copies))
2701 if (typeof(this._copy_count_cb) == "function")
2702 this._copy_count_cb(liId, total);
2704 openils.Util.show("acq-lit-update-copies-progress");
2705 fieldmapper.standardRequest(
2706 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
2708 params: [openils.User.authtoken, copies],
2709 onresponse: function(r) {
2710 var res = openils.Util.readResponse(r);
2711 litUpdateCopiesProgress.update(res);
2713 oncomplete: function() {
2714 self.drawCopies(liId, true /* force_fetch */);
2715 openils.Util.hide("acq-lit-update-copies-progress");
2721 var dfa_list = this._virtDfaCountsAsList();
2722 if (dfa_list.length > 0) {
2723 fieldmapper.standardRequest(
2725 "open-ils.acq.distribution_formula.record_application"],
2728 "params": [openils.User.authtoken, dfa_list, liId],
2729 "onresponse": function(r) {
2730 var res = openils.Util.readResponse(r);
2731 if (res && res.length < dfa_list.length)
2732 alert(localeStrings.DFA_NOT_ALL);
2736 this.virtDfaCounts = {};
2739 if (this.inlineCopiesNeedingRefresh.indexOf(liId) < 0)
2740 this.inlineCopiesNeedingRefresh.push(liId);
2743 this._updateCreatePoPrepayCheckbox = function(prepay) {
2744 var prepay = openils.Util.isTrue(prepay);
2745 this._prepayRequiredByVendor = prepay;
2746 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
2749 this._confirmPoPrepaySituation = function() {
2750 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
2751 if (want_prepay != this._prepayRequiredByVendor) {
2754 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
2755 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
2762 this.applySelectedLiAction = function(action) {
2766 case 'delete_selected':
2767 this._deleteLiList(self.getSelected());
2770 case 'add_to_order':
2771 addToPoDialog._get_li = dojo.hitch(
2774 return this.getSelected(
2775 false, null, true, li_pre_po_states);
2778 if (addToPoDialog._get_li().length == 0) {
2779 alert(localeStrings.NO_LI_GENERAL);
2782 addToPoDialog.show();
2785 case 'create_order':
2786 this._loadPOSelect();
2787 acqLitPoCreateDialog.show();
2790 case 'save_picklist':
2791 acqLitSavePlDialog.show();
2794 case 'selector_ready':
2796 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
2797 acqLitChangeLiStateDialog.show();
2805 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
2808 case 'batch_create_invoice':
2809 this.batchCreateInvoice();
2812 case 'batch_link_invoice':
2813 this.batchLinkInvoice();
2816 case 'receive_lineitems':
2817 this.receiveSelectedLineitems();
2820 case 'rollback_receive_lineitems':
2821 this.rollbackReceiveLineitems();
2824 case 'create_assets':
2825 this.showAssetCreator();
2828 case 'export_attr_list':
2829 this.chooseExportAttr();
2832 case 'batch_apply_funds':
2833 this.applyBatchLiFunds();
2836 case 'add_brief_record':
2838 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
2840 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
2844 case "cancel_lineitems":
2845 console.log('HERE');
2846 this.maybeCancelLineitems();
2849 case "apply_claim_policy":
2850 var li_list = this.getSelected();
2851 this.claimPolicyPicker.attr("value", null);
2852 liClaimPolicyDialog.show();
2853 liClaimPolicySave.onClick = function() {
2854 self.changeClaimPolicy(
2856 self.claimPolicyPicker.attr("value"),
2860 self.setClaimPolicyControl(li);
2861 self.reconsiderClaimControl(li);
2864 liClaimPolicyDialog.hide();
2872 this.changeClaimPolicy = function(li_list, value, callback) {
2874 function(li) { li.claim_policy(value); }
2876 fieldmapper.standardRequest(
2877 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
2878 "params": [openils.User.authtoken, li_list],
2880 "oncomplete": function(r) {
2881 r = openils.Util.readResponse(r);
2882 if (callback) callback(r);
2888 this.showAssetCreator = function(onAssetsCreated) {
2889 if(!this.isPO) return;
2892 // first, let's see if this PO has any LI's that need to be merged/imported
2893 self.pcrud.search('jub', {purchase_order : this.isPO, eg_bib_id : null}, {
2895 oncomplete : function(r) {
2896 var resp = openils.Util.readResponse(r);
2897 if (resp && resp.length) {
2898 // PO has some non-linked jubs.
2900 self.show('asset-creator');
2901 if(!self.vlAgent.loaded)
2902 self.vlAgent.init();
2904 dojo.connect(assetCreatorButton, 'onClick',
2905 function() { self.createAssets(onAssetsCreated) });
2909 // all jubs linked, move on to asset creation
2910 self.createAssets(onAssetsCreated, true);
2916 this.createAssets = function(onAssetsCreated, noVl) {
2917 this.show('acq-lit-progress-numbers');
2919 var vlArgs = (noVl) ? {} : {vandelay : this.vlAgent.values()};
2920 fieldmapper.standardRequest(
2921 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
2923 params: [this.authtoken, this.isPO, vlArgs],
2924 onresponse: function(r) {
2925 var resp = openils.Util.readResponse(r);
2926 self._updateProgressNumbers(resp, !Boolean(onAssetsCreated), onAssetsCreated);
2932 this.maybeCancelLineitems = function() {
2933 openils.Util.show("acq-lit-cancel-reason", "inline");
2934 if (!acqLitCancelLineitemsButton._prepared) {
2935 var widget = new openils.widget.AutoFieldWidget({
2936 "fmField": "cancel_reason",
2938 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
2939 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2941 "searchOptions" : {order_by : {"acqcr":"label"}}
2945 acqLitCancelLineitemsButton.onClick = function() {
2946 if (w.attr("value")) {
2947 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
2948 self._cancelLineitems(w.attr("value"));
2950 openils.Util.hide("acq-lit-cancel-reason");
2953 acqLitCancelLineitemsButton._prepared = true;
2959 this._cancelLineitems = function(reason) {
2961 var li_list = this.getSelected();
2963 // canceled lineitems may be canceled again if they were
2964 // previously delayed (keep_debits = true).
2965 li_list = li_list.filter(
2968 li.state() != 'cancelled' ||
2969 li.cancel_reason().keep_debits() == 't'
2974 id_list = li_list.map(function(l) {return l.id()});
2976 if (!id_list.length) {
2977 alert(localeStrings.NO_LI_GENERAL);
2980 fieldmapper.standardRequest(
2981 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
2982 "params": [openils.User.authtoken, id_list, reason],
2984 "onresponse": function(r) {
2985 if (r = openils.Util.readResponse(r)) {
2987 for (var id in r.li) {
2988 self.liCache[id].state(r.li[id].state);
2989 self.liCache[id].cancel_reason(
2990 r.li[id].cancel_reason
2992 self.updateLiState(self.liCache[id]);
2995 if (r.lid && self.copyCache) {
2996 for (var id in r.lid) {
2997 if (self.copyCache[id]) {
2998 self.copyCache[id].cancel_reason(
2999 r.lid[id].cancel_reason
3001 self.updateLidState(self.copyCache[id]);
3011 this.chooseExportAttr = function() {
3012 if (!acqLitExportAttrSelector._li_setup) {
3014 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
3016 "data": acqlimad.toStoreData(
3018 "acqlimad", {"code": li_exportable_attrs}
3023 acqLitExportAttrSelector.setValue();
3024 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
3025 acqLitExportAttrSelector._li_setup = true;
3027 openils.Util.show("acq-lit-export-attr-holder", "inline");
3030 this.exportAttrList = function() {
3031 var attr_def = acqLitExportAttrSelector.item;
3032 var li_list = this.getSelected();
3033 var value_list = li_list.map(
3035 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
3036 attr_def.code, "lineitem_marc_attr_definition"
3039 ).filter(function(attr) { return Boolean(attr); });
3041 if (value_list.length > 0) {
3042 if (value_list.length < li_list.length) {
3044 dojo.string.substitute(
3045 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
3052 openils.XUL.contentToFileSaveDialog(
3053 value_list.join("\n"),
3054 localeStrings.EXPORT_SAVE_DIALOG_TITLE
3060 alert(dojo.string.substitute(
3061 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
3065 openils.Util.hide("acq-lit-export-attr-holder");
3068 this.printPO = function() {
3069 if(!this.isPO) return;
3070 progressDialog.show(true);
3071 fieldmapper.standardRequest(
3072 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
3074 params: [this.authtoken, this.isPO, 'html'],
3075 oncomplete: function(r) {
3076 progressDialog.hide();
3077 var evt = openils.Util.readResponse(r);
3078 if(evt && evt.template_output()) {
3079 openils.Util.printHtmlString(evt.template_output().data());
3086 this.batchCreateInvoice = function() {
3087 var liIds = this.getSelected(
3088 false, null, true /* id_list */, li_active_states)
3089 if (!liIds.length) {
3090 alert(localeStrings.NO_LI_GENERAL);
3093 var path = oilsBasePath + '/acq/invoice/view?create=1';
3094 dojo.forEach(liIds, function(li, idx) { path += '&attach_li=' + li });
3095 if (openils.XUL.isXUL())
3096 openils.XUL.newTabEasy(path, localeStrings.NEW_INVOICE, null, true);
3098 location.href = path;
3101 this.batchLinkInvoice = function(create) {
3102 var liIds = this.getSelected(
3103 false, null, true /* id_list */, li_active_states)
3104 if (!liIds.length) {
3105 alert(localeStrings.NO_LI_GENERAL);
3108 if (!self.invoiceLinkDialogManager) {
3109 self.invoiceLinkDialogManager =
3110 new InvoiceLinkDialogManager("li");
3112 self.invoiceLinkDialogManager.target = liIds;
3113 acqLitLinkInvoiceDialog.show();
3116 this.receiveSelectedLineitems = function() {
3117 var states = li_post_po_states.filter(
3118 function(s) { return s != 'received' });
3119 var li_list = this.getSelected(null, null, null, states);
3121 if (!li_list.length) {
3122 alert(localeStrings.NO_LI_GENERAL);
3126 for (var i = 0; i < li_list.length; i++) {
3127 var li = li_list[i];
3129 if (li.state() != "received" &&
3130 !this.checkLiAlerts(li.id())) return;
3133 this.show('acq-lit-progress-numbers');
3136 fieldmapper.standardRequest(
3137 ['open-ils.acq', 'open-ils.acq.lineitem.receive.batch'],
3141 li_list.map(function(li) { return li.id(); })
3143 onresponse : function(r) {
3144 var resp = openils.Util.readResponse(r);
3145 self._updateProgressNumbers(resp, true);
3151 this.issueReceive = function(obj, rollback) {
3153 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
3155 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
3157 progressDialog.show(true);
3158 fieldmapper.standardRequest(
3159 ["open-ils.acq", method], {
3161 "params": [this.authtoken, obj.id()],
3162 "onresponse": function(r) {
3163 if (r = openils.Util.readResponse(r)) {
3164 self.fetchClaimInfo(
3165 part == "lineitem" ? obj.id() : obj.lineitem(),
3167 function() { self.handleReceive(r); }
3169 progressDialog.hide();
3177 * Handles the responses from receive and rollback ML calls.
3179 this.handleReceive = function(resp) {
3182 for (var li_id in resp.li) {
3183 for (var key in resp.li[li_id])
3184 self.liCache[li_id][key](resp.li[li_id][key]);
3185 self.updateLiState(self.liCache[li_id]);
3189 if (typeof(self.poUpdateCallback) == "function")
3190 self.poUpdateCallback(resp.po);
3193 for (var lid_id in resp.lid) {
3194 for (var key in resp.lid[lid_id])
3195 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
3196 self.updateLidState(self.copyCache[lid_id]);
3202 this.rollbackReceiveLineitems = function() {
3203 var li_id_list = this.getSelected(false, null, true);
3204 if (!li_id_list.length) {
3205 alert(localeStrings.NO_LI_GENERAL);
3209 if (!confirm(localeStrings.ROLLBACK_LI_RECEIVE_CONFIRM)) return;
3211 this.show('acq-lit-progress-numbers');
3214 fieldmapper.standardRequest(
3215 ['open-ils.acq', 'open-ils.acq.lineitem.receive.rollback.batch'],
3217 params: [this.authtoken, li_id_list],
3218 onresponse : function(r) {
3219 var resp = openils.Util.readResponse(r);
3220 self._updateProgressNumbers(resp, true);
3226 this._updateProgressNumbers = function(resp, reloadOnComplete, onComplete) {
3227 this.vlAgent.handleResponse(resp,
3228 function(resp, res) {
3229 if(reloadOnComplete)
3230 location.href = location.href;
3232 onComplete(resp, res);
3238 this._createPO = function(fields) {
3239 var wantall = (fields.create_from == "all");
3241 /* If we're a picklist or purchase order already and the user wants
3242 * all lineitems, we might have pages' worth of lineitems haven't all
3243 * been loaded yet, so getSelected() won't find them. The server,
3244 * however, should know about all our lineitems, so let's ask the
3245 * server for a complete list.
3250 true, function(list) {
3251 self._createPOFromLineitems(fields, list);
3252 }, /* id_list */ true, li_pre_po_states
3255 this._createPOFromLineitems(
3256 fields, this.getSelected(
3257 false, null, true /* id_list */, li_pre_po_states)
3262 this._createPOFromLineitems = function(fields, selected) {
3263 if (selected.length == 0) {
3264 alert(localeStrings.NO_LI_GENERAL);
3269 var po = new fieldmapper.acqpo();
3270 po.provider(this.createPoProviderSelector.attr("value"));
3271 po.ordering_agency(this.createPoAgencySelector.attr("value"));
3272 po.prepayment_required(fields.prepayment_required[0] ? true : false);
3274 // if we're creating assets, delay the asset creation
3275 // until after the PO is created. This will allow us to
3276 // use showAssetCreator() directly.
3278 fieldmapper.standardRequest(
3279 ["open-ils.acq", "open-ils.acq.purchase_order.create"],
3282 openils.User.authtoken,
3283 po, {lineitems : selected}
3285 onresponse : function(r) {
3286 var resp = openils.Util.readResponse(r);
3287 if (resp.complete) {
3288 // self.isPO is needed for showAssetCreator();
3289 self.isPO = resp.purchase_order.id();
3290 var redir = oilsBasePath + "/acq/po/view/" + self.isPO;
3291 if (fields.create_assets[0]) {
3292 self.showAssetCreator(
3293 function() {location.href = redir}
3296 location.href = redir;
3305 this.batchFundWidget = null;
3307 this.applyBatchLiFunds = function() {
3309 var liIds = this.getSelected().map(function(li) { return li.id(); });
3310 if(liIds.length == 0) return; // warn?
3313 batchFundUpdateDialog.show();
3315 if(!this.batchFundWidget) {
3316 this.batchFundWidget = new openils.widget.AutoFieldWidget({
3318 selfReference : true,
3319 labelFormat : fundLabelFormat,
3320 searchFormat : fundSearchFormat,
3321 searchFilter : fundSearchFilter,
3322 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
3323 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
3324 dijitArgs : { "required": true, "labelType": "html" },
3327 this.batchFundWidget.build();
3330 dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
3331 dojo.connect(batchFundUpdateSubmit, 'onClick',
3334 // TODO: call .dry_run first to test thresholds
3335 fieldmapper.standardRequest(
3336 ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
3339 openils.User.authtoken,
3341 self.batchFundWidget.widget.attr('value')
3343 oncomplete : function(r) {
3344 var resp = openils.Util.readResponse(r);
3346 location.href = location.href;
3355 this._deleteLiList = function(list, idx) {
3356 if(idx == null) idx = 0;
3357 if(idx >= list.length) return;
3362 if (this.isPO && (li.state() == "on-order" || li.state() == "received")) {
3363 /* It makes little sense to delete a lineitem from a PO that has
3364 * already been marked 'on-order'. Especially if EDI is in use,
3365 * such a purchase order will probably have already been shipped
3366 * off to a vendor, and mucking with it at this point could leave
3367 * your data in a bad state that doesn't jive with reality.
3369 * I could see making this restriction even firmer.
3371 * I could also see adjusting the li state comparisons, extending
3372 * the comparison to the PO's state, and/or providing functions
3373 * that house the logic for comparing states in a single location.
3375 * Yes, this will be really annoying if you have selected a lot
3376 * of lineitems to cancel that have been ordered. You'll get a
3377 * confirm dialog for each one.
3380 if (!confirm(localeStrings.DEL_LI_FROM_PO)) {
3381 self._deleteLiList(list, ++idx); /* move on to next in list */
3386 fieldmapper.standardRequest(
3388 this.isPO ? 'open-ils.acq.purchase_order.lineitem.delete' : 'open-ils.acq.picklist.lineitem.delete'],
3390 params: [openils.User.authtoken, liId],
3391 oncomplete: function(r) {
3392 self.removeLineitem(liId);
3393 self._deleteLiList(list, ++idx);
3399 this.editOrderMarc = function(li) {
3401 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
3402 to true in about:config */
3404 if(openils.XUL.isXUL()) {
3405 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul','','chrome');
3407 win = window.open('/xul/server/cat/marcedit.xul','','chrome');
3411 record : {marc : li.marc(), "rtype": "bre"},
3413 label: 'Save Record', // XXX I18N
3414 func: function(xmlString) {
3416 fieldmapper.standardRequest(
3417 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
3419 params: [openils.User.authtoken, li],
3420 oncomplete: function(r) {
3421 openils.Util.readResponse(r);
3423 self.drawInfo(li.id())
3429 'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
3430 'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
3434 this._savePl = function(values) {
3436 (values.which == 'all'),
3437 function(list) { self._savePlFromLineitems(values, list); }
3441 this._savePlFromLineitems = function(values, selected) {
3442 openils.Util.show("acq-lit-generic-progress");
3444 if(values.new_name) {
3445 openils.acq.Picklist.create(
3446 {name: values.new_name},
3452 oilsBasePath + "/acq/picklist/view/" + id;
3457 } else if(values.existing_pl) {
3458 // update lineitems to use an existing picklist
3460 values.existing_pl, selected, 0,
3463 oilsBasePath + "/acq/picklist/view/" +
3470 this._updateLiState = function(values, state, state_filter) {
3471 progressDialog.show(true);
3473 (values.which == 'all'),
3475 self._updateLiStateFromLineitems(values, state, list);
3476 }, false /* id_list */, state_filter
3480 this._updateLiStateFromLineitems = function(values, state, selected) {
3481 if(!selected.length) {
3482 try { progressDialog.hide() } catch(E) {};
3483 alert(localeStrings.NO_LI_GENERAL);
3486 dojo.forEach(selected, function(li) {li.state(state);});
3487 self._updateLiList(null, selected, 0,
3488 // TODO consider inline updates for efficiency
3489 function() { location.href = location.href }
3493 this._updateLiList = function(pl, list, idx, oncomplete) {
3494 if(idx >= list.length) return oncomplete();
3496 if(pl != null) li.picklist(pl);
3497 litGenericProgress.update({maximum: list.length, progress: idx});
3498 new openils.acq.Lineitem({lineitem:li}).update(
3500 self._updateLiList(pl, list, ++idx, oncomplete);
3505 this._loadPOSelect = function() {
3506 if (!this.createPoProviderSelector) {
3507 var widget = new openils.widget.AutoFieldWidget({
3508 "fmField": "provider",
3510 "searchFilter": {"active": "t"},
3511 "parentNode": dojo.byId("acq-lit-po-provider"),
3513 "onChange": function() {
3515 self._updateCreatePoPrepayCheckbox(
3516 this.item.prepayment_required()
3522 widget.build(function(w) { self.createPoProviderSelector = w; });
3525 if (!this.createPoAgencySelector) {
3526 var widget = new openils.widget.AutoFieldWidget({
3527 "fmField": "ordering_agency",
3529 "parentNode": dojo.byId("acq-lit-po-agency"),
3530 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3532 widget.build(function(w) { self.createPoAgencySelector = w; });
3536 this.showRealCopyEditUI = function(li) {
3541 this._fetchLineitem(li.id(),
3543 li = self.liCache[li.id()] = fullLi;
3547 id : li.lineitem_details().map(
3548 function(item) { return item.eg_copy_id() }
3552 oncomplete : function(r) {
3554 var r_list = openils.Util.readResponse( r );
3555 for (var i = 0; i < r_list.length; i++) {
3556 var copy = r_list[i];
3557 var volId = copy.call_number();
3558 var volume = self.volCache[volId];
3560 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
3562 copy.call_number(volume);
3563 copyList.push(copy);
3566 xulG.volume_item_creator( { 'existing_copies' : copyList } );
3569 alert('error in oncomplete: ' + E);
3578 this.drawBibFinder = function(li) {
3581 var liWrapper = new openils.acq.Lineitem({lineitem:li});
3584 ['isbn', 'upc', 'issn', 'title', 'author'],
3586 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
3588 if(field == 'title' || field == 'author') {
3589 query += field +':' + val + ' ';
3591 query += 'identifier|' + field + ':' + val + ' ';
3598 oilsBasePath + '/acq/lineitem/findbib?query=' + encodeURIComponent(query),
3599 '', 'resizable,scrollbars=1,chrome');
3601 win.window.recordFound = function(bibId) {
3604 var attrs = li.attributes();
3605 li.attributes(null);
3606 li.eg_bib_id(bibId);
3608 fieldmapper.standardRequest(
3609 ["open-ils.acq", "open-ils.acq.lineitem.update"],
3611 "params": [openils.User.authtoken, li],
3613 "oncomplete": function(r) {
3614 if(openils.Util.readResponse(r)) {
3615 location.href = location.href;