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'};
33 var fundSort = {order_by : {"acqf":"year DESC, code"}};
35 function nodeByName(name, context) {
36 return dojo.query('[name='+name+']', context)[0];
39 // for caching linked users. e.g. lineitem_detail.receiver
42 var liDetailBatchFields = ['fund', 'owning_lib', 'location', 'collection_code', 'circ_modifier', 'cn_label'];
43 var liDetailFields = liDetailBatchFields.concat(['barcode', 'note']);
45 "stop": "color: #c00; font-weight: bold;",
46 "warning": "color: #c93;"
50 * We're not using 'approved' today, but there is API support for it.
51 * I believe it's been replaced by "order-ready".
52 * LIs go new => selector-ready => order-ready/approved => pending-order =>
53 * on-order => received. 'cancelled' can pop up anywhere.
56 var li_pre_po_states = ["new", "selector-ready", "order-ready", "approved"];
57 var li_post_po_states = ["pending-order", "on-order", "received", "cancelled"];
58 var li_active_states = li_pre_po_states.concat(li_post_po_states);
60 function AcqLiTable() {
67 this.haveFundClass = {}
68 this.fundBalanceState = {};
69 this.realDfaCache = {};
70 this.virtDfaCounts = {};
73 this.claimEligibleLidByLi = {};
74 this.claimEligibleLid = {};
75 this.toggleState = false;
76 this.tbody = dojo.byId('acq-lit-tbody');
79 this.authtoken = openils.User.authtoken;
80 this.pcrud = new openils.PermaCrud();
81 this.rowTemplate = this.tbody.removeChild(dojo.byId('acq-lit-row'));
82 this.copyTbody = dojo.byId('acq-lit-li-details-tbody');
83 this.copyRow = this.copyTbody.removeChild(dojo.byId('acq-lit-li-details-row'));
84 this.copyBatchRow = dojo.byId('acq-lit-li-details-batch-row');
85 this.copyBatchWidgets = {};
86 this.liNotesTbody = dojo.byId('acq-lit-notes-tbody');
87 this.liNotesRow = this.liNotesTbody.removeChild(dojo.byId('acq-lit-notes-row'));
88 this.realCopiesTbody = dojo.byId('acq-lit-real-copies-tbody');
89 this.realCopiesRow = this.realCopiesTbody.removeChild(dojo.byId('acq-lit-real-copies-row'));
90 this._copy_fields_for_acqdf = ['owning_lib', 'location', 'fund', 'circ_modifier', 'collection_code'];
91 this.skipInitialEligibilityCheck = false;
92 this.claimDialog = new ClaimDialogManager(
93 liClaimDialog, finalClaimDialog, this.claimEligibleLidByLi,
94 function(li) { /* callback that fires when claims are made */
95 self.fetchClaimInfo(li.id(), /* force update */ true);
98 this.vlAgent = new VLAgent();
99 this.batchProgress = {};
101 if (dojo.byId('acq-lit-apply-idents')) {
102 dojo.byId('acq-lit-apply-idents').onclick = function() {
103 self.applyOrderIdentValues();
107 this.focusLineitem = new openils.CGI().param('focus_li');
109 // capture the inline copy display wrapper and row template
110 this.inlineCopyContainer =
111 this.tbody.removeChild(dojo.byId('acq-inline-copies-row'));
113 '[name=acq-li-inline-copies-tbody]', this.inlineCopyContainer)[0];
114 this.inlineCopyTemplate = tb.removeChild(
115 dojo.query('[name=acq-li-inline-copies-template]', tb)[0]);
116 this.inlineNoCopies = tb.removeChild(
117 dojo.query('[name=acq-li-inline-copies-none]', tb)[0]);
119 // list of LI IDs that should be refreshed at next display time
120 this.inlineCopiesNeedingRefresh = [];
122 dojo.byId("acq-lit-li-actions-selector").onchange = function() {
123 self.applySelectedLiAction(this.options[this.selectedIndex].value);
124 this.selectedIndex = 0;
127 acqLitCreatePoCancel.onClick = function() {
128 acqLitPoCreateDialog.hide();
130 acqLitCreatePoSubmit.onClick = function() {
131 if (!self.createPoProviderSelector.attr("value") ||
132 !self.createPoAgencySelector.attr("value")) {
133 alert(localeStrings.CREATE_PO_INVALID);
135 } else if (self._confirmPoPrepaySituation()) {
136 acqLitPoCreateDialog.hide();
137 self._createPO(acqLitPoCreateDialog.getValues());
143 acqLitSavePlButton.onClick = function() {
144 acqLitSavePlDialog.hide();
145 self._savePl(acqLitSavePlDialog.getValues());
148 acqLitCancelLiStateButton.onClick = function() {
149 acqLitChangeLiStateDialog.hide();
151 acqLitSaveLiStateButton.onClick = function() {
152 acqLitChangeLiStateDialog.hide();
153 var state = acqLitChangeLiStateDialog.attr('state');
154 var state_filter = ['new'];
155 if (state == 'order-ready')
156 state_filter.push('selector-ready');
158 acqLitChangeLiStateDialog.getValues(), state, state_filter);
162 dojo.byId('acq-lit-select-toggle').onclick = function(){self.toggleSelect()};
163 dojo.byId('acq-inline-copies-toggle').onclick = function(){self.toggleInlineCopies()};
164 dojo.byId('acq-lit-info-back-button').onclick = function(){self.show('list')};
165 dojo.byId('acq-lit-copies-back-button').onclick = function(){self.show('list')};
166 dojo.byId('acq-lit-notes-back-button').onclick = function(){self.show('list')};
167 dojo.byId('acq-lit-real-copies-back-button').onclick = function(){self.show('list')};
169 this.setFundSearchFilter = function(callback) {
170 new openils.User().getPermOrgList(
171 ['CREATE_PURCHASE_ORDER', 'MANAGE_FUND'],
173 fundSearchFilter.org = orgs;
174 if (callback) callback();
176 true, true // descendants, id_list
180 this.afwCopyFieldArgs = function(field, perms) {
184 "labelFormat": (field == 'fund') ? fundLabelFormat : null,
185 "searchFormat": (field == 'fund') ? fundSearchFormat : null,
186 "searchFilter": (field == 'fund') ? fundSearchFilter : null,
187 "searchOptions": (field == 'fund') ? fundSort : null,
188 "orgLimitPerms": (field == 'location') ? ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'] : [perms],
191 "labelType": (field == "fund") ? "html" : null
193 "noCache": (field == "fund"),
198 /* This is the "new" batch updater that sits atop all lineitems. It does
199 * use this.afwCopyFieldArgs() to borrow a little common code from the
200 * "old" batch updater atop the copy details view. */
201 this.initBatchUpdater = function(disabled_fields) {
202 openils.Util.show("acq-batch-update", "table");
204 if (!dojo.isArray(disabled_fields)) disabled_fields = [];
206 /* Note that this will directly contain dijits, not the AutoWidget
208 this.batchUpdateWidgets = {};
210 this.batchUpdateWidgets.item_count = new dijit.form.TextBox(
212 "style": {"width": "3em"},
214 dojo.indexOf(disabled_fields, "item_count") != -1
220 (new openils.widget.AutoFieldWidget({
222 "selfReference": true,
223 "dijitArgs": { "required": false },
225 "parentNode": "acq-bu-distribution_formula"
228 dojo.style(w.domNode, {"width": "12em"});
229 /* dijitArgs to AutoFieldWidget won't work for 'disabled' */
232 dojo.indexOf(disabled_fields, "distribution_formula") != -1
234 self.batchUpdateWidgets.distribution_formula = w;
238 function buildOneBatchWidget(field, args) {
239 (new openils.widget.AutoFieldWidget(args)).build(
241 if (field == "fund") {
243 w, "onChange", function(val) {
244 self._updateFundSelectorStyle(aw, val);
248 self._ensureCSSFundClasses(w.store);
251 dojo.style(w.domNode, {"width": "10em"});
254 dojo.indexOf(disabled_fields, field) != -1
256 self.batchUpdateWidgets[field] = w;
262 ["owning_lib","location","collection_code","circ_modifier","fund"],
264 var args = self.afwCopyFieldArgs(field,"CREATE_PURCHASE_ORDER");
265 args.parentNode = dojo.byId("acq-bu-" + field);
267 if (field == 'fund') {
268 // The list of funds can be huge. Before fetching
269 // funds for PO modification, see where the user has
270 // perms and limit the retreived funds accordingly.
271 // Note: This is the first instance of fund list
272 // retrieval. All future fund list retrievals will
273 // benefit directly from having applied the fund
274 // search filter org units here.
275 self.setFundSearchFilter(function() {
276 buildOneBatchWidget(field, args);
281 buildOneBatchWidget(field, args);
285 acqBatchUpdateApply.onClick = function() {
286 var li_id_list = self.getSelected(false, null, true /* id list */);
287 if (!li_id_list.length) {
288 alert(localeStrings.NO_LI_TO_UPDATE);
292 progressDialog.show(true);
293 progressDialog.attr("title", localeStrings.LI_BATCH_UPDATE);
294 progressDialog.update({"maximum": li_id_list.length,"progress": 0});
298 var params = [ self.authtoken, {"lineitems": li_id_list},
299 self.batchUpdateChanges(), self.batchUpdateFormula() ];
300 console.log("batch update params: " + dojo.toJson(params));
302 fieldmapper.standardRequest(
303 ["open-ils.acq", "open-ils.acq.lineitem.batch_update"], {
306 "onresponse": function(r) {
307 if ((r = openils.Util.readResponse(r))) { // assignment
308 progressDialog.update({"progress": ++count});
310 progressDialog.hide();
311 progressDialog.attr("title", "");
314 "oncomplete": function() {
315 /* XXX Is the last call to onresponse guaranteed to
316 * finish before oncomplete is fired? */
317 if (count != li_id_list.length) {
318 console.error("lineitem batch update operation failed");
319 progressDialog.hide();
320 progressDialog.attr("title", "");
322 location.href = location.href;
330 this.batchUpdateChanges = function() {
334 openils.Util.objectProperties(this.batchUpdateWidgets),
336 if (k == "distribution_formula") return; /* handled elsewhere */
337 if (self.batchUpdateWidgets[k].attr("disabled")) return;
339 /* It's important that a value of "" should mean that a field
340 * doesn't get used in the arguments to the batch updater API,
341 * but 0 should mean an actual 0. */
342 var value = self.batchUpdateWidgets[k].attr("value");
351 this.batchUpdateFormula = function() {
352 if (this.batchUpdateWidgets.distribution_formula.attr("disabled")) {
356 this.batchUpdateWidgets.distribution_formula.attr("value") ||
362 this.reset = function(keep_selectors) {
363 while(self.tbody.childNodes[0])
364 self.tbody.removeChild(self.tbody.childNodes[0]);
373 this.setNext = function(handler) {
374 var link = dojo.byId('acq-lit-next');
376 dojo.style(link, 'visibility', 'visible');
377 link.onclick = handler;
379 dojo.style(link, 'visibility', 'hidden');
383 this.setPrev = function(handler) {
384 var link = dojo.byId('acq-lit-prev');
386 dojo.style(link, 'visibility', 'visible');
387 link.onclick = handler;
389 dojo.style(link, 'visibility', 'hidden');
393 this.enableActionsDropdownOptions = function(mask) {
394 /* 'mask' is probably a misnomer the way I'm using it, but it needs to
395 * be one of pl,po,ao,gs,vp, or fs. */
396 dojo.query("option", "acq-lit-li-actions-selector").forEach(
398 var opt_mask = dojo.attr(option, "mask");
400 /* For each <option> element, an empty or non-existent mask
401 * attribute, a mask attribute of "*", or a mask attribute that
402 * matches this method's argument should result in that
403 * option's being enabled. */
405 option, "disabled", !(
408 opt_mask.search(mask) != -1
416 * Ensures this.focusLineitem is in view and causes a brief
417 * border around the lineitem to come to life then fade.
419 this.focusLi = function() {
420 if (!this.focusLineitem) return;
422 // set during addLineitem()
423 var node = dojo.byId('li-title-ref-' + this.focusLineitem);
425 // LI may not yet be rendered
428 // prevent numerous re-focuses
429 this.focusLineitem = null;
431 // causes the full row to be visible
432 dijit.scrollIntoView(node);
435 dojo.query('[attr=title]', node)[0].focus();
437 dojo.require('dojox.fx');
441 dojox.fx.highlight({color : '#BB4433', node : node, duration : 2000}).play();
446 this.show = function(div) {
447 openils.Util.hide('acq-lit-table-div');
448 openils.Util.hide('acq-lit-info-div');
449 openils.Util.hide('acq-lit-li-details');
450 openils.Util.hide('acq-lit-notes-div');
451 openils.Util.hide('acq-lit-real-copies-div');
452 openils.Util.hide('acq-lit-asset-creator');
455 openils.Util.show('acq-lit-table-div');
457 this.refreshInlineCopies();
460 openils.Util.show('acq-lit-info-div');
463 openils.Util.show('acq-lit-li-details');
466 openils.Util.show('acq-lit-real-copies-div');
469 openils.Util.show('acq-lit-notes-div');
471 case 'asset-creator':
472 openils.Util.show('acq-lit-asset-creator');
476 openils.Util.show(div);
480 this.hide = function() {
484 this.toggleSelect = function() {
486 dojo.forEach(self.selectors, function(i){i.checked = false});
488 dojo.forEach(self.selectors, function(i){i.checked = true});
489 self.toggleState = !self.toggleState;
493 this.getAll = function(callback, id_only, state) {
494 /* For some uses of the li table, we may not really know about "all"
495 * the lineitems that the user thinks we know about. If we're a paged
496 * picklist, for example, we only know about the lineitems we've
497 * displayed, but not necessarily all the lineitems on the picklist.
498 * So we reach out to pcrud to inform us.
499 * state: string/array. only lineitems in one of these states are
500 * included in the final result set. Not currently supported for
504 var oncomplete = function(r) {
505 var id_list = openils.Util.readResponse(r);
509 self.fetchLineitemsById(id_list, callback);
513 var search = {"picklist": this.isPL};
514 if (state) search.state = state;
517 "id_list": true, /* sic, even if id_only */
519 "oncomplete": oncomplete
523 } else if (this.isPO) {
524 var search = {"purchase_order": this.isPO};
525 if (state) search.state = state;
530 "oncomplete": oncomplete
534 } else if (this.isUni && this.pager) {
535 this.pager.getAllLineitemIDs(oncomplete);
539 /* If execution reaches this point, we don't need or can't perform
540 * any special tricks to find out the "real" list of "all" lineitems
541 * in this context, so we fall back to the old method.
543 callback(this.getSelected(true, null, id_only, state));
546 /** @param all If true, assume all are selected */
547 this.getSelected = function(
549 callback /* If you want a "good" idea of "all" lineitems, you must
550 provide a callback that accepts an array parameter, rather than
551 relying on the return value of this method itself. */,
555 console.log("getSelected states = " + state);
557 return this.getAll(callback, id_only, state);
559 var indices = {}; /* use to uniqify. needed in paging situations. */
560 dojo.forEach(this.selectors,
563 indices[i.parentNode.parentNode.getAttribute('li')] = true;
567 var result = openils.Util.objectProperties(indices);
569 // caller provided a lineitem state filter. remove IDs for lineitems
570 // not in the selected state.
573 if (!dojo.isArray(state)) state = [state];
574 dojo.forEach(result, function(liId) {
575 console.log('filter LI state ' + self.liCache[liId].state());
576 if (state.indexOf(self.liCache[liId].state()) >= 0)
583 result = result.map(function(liId) { return self.liCache[liId]; });
591 this.setRowAttr = function(td, liWrapper, field, type) {
592 var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
593 td.appendChild(document.createTextNode(val));
596 this.setClaimPolicyControl = function(li, row) {
597 if (!self._claimPolicyPickerLoading) {
598 self._claimPolicyPickerLoading = true;
600 new openils.widget.AutoFieldWidget({
601 "parentNode": "acq-lit-li-claim-policy",
603 "selfReference": true,
604 "dijitArgs": {"required": true}
606 function(w) { self.claimPolicyPicker = w; }
610 /* dojox.timing.doLater() is the best thing ever. Resource not yet
611 * ready? Just repeat my whole method when it is. */
612 if (dojox.timing.doLater(self.claimPolicyPicker)) {
616 row = self._findLiRow(li);
618 if (li.claim_policy()) {
619 /* This Dojo data dance is necessary to get a whole fieldmapper
620 * object based on a claim policy ID, since we alreay have the
621 * widget thing loaded with all that data, and can thereby
622 * avoid another request to the server. */
623 self.claimPolicyPicker.store.fetchItemByIdentity({
624 "identity": li.claim_policy(),
625 "onItem": function(a) {
626 var policy = (new acqclp()).fromStoreItem(a);
627 var span = nodeByName("claim_policy", row);
628 var inner = nodeByName("claim_policy_name", row);
630 openils.Util.show(span, "inline");
631 inner.innerHTML = policy.name();
633 "onError": function(e) {
638 openils.Util.hide(nodeByName("claim_policy", row));
639 nodeByName("claim_policy_name", row).innerHTML = "";
644 this.fetchClaimInfo = function(liId, force, callback, row) {
646 liId, function(full) {
647 self.liCache[full.id()] = full;
648 self.checkClaimEligibility(full, callback, row);
653 // fetch an updated copy of the lineitem
654 // and add it back to the lineitem table
655 this.refreshLineitem = function(li, focus) {
657 this._fetchLineitem(li.id(),
660 self.focusLineitem = li.id();
662 self.focusLineitem = null;
664 var row = dojo.query('[li='+li.id()+']', self.tbody)[0];
665 var nextSibling = row.nextSibling;
666 self.tbody.removeChild(row);
667 self.addLineitem(newLi, false, nextSibling);
673 * Inserts a single lineitem into the growing table of lineitems
674 * @param {Object} li The lineitem object to insert
676 this.addLineitem = function(li, skip_final_placement, nextSibling) {
677 this.liCache[li.id()] = li;
679 // insert the row right away so that final order isn't
680 // dependent on how long subsequent async request take
681 // for a given line item
682 var row = self.rowTemplate.cloneNode(true);
683 if (!skip_final_placement) {
685 // either no nextSibling was provided or it was null
686 // meaning the row was already at the end of the table
687 self.tbody.appendChild(row);
689 self.tbody.insertBefore(row, nextSibling);
693 self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
695 // sort the lineitem notes on edit_time
696 if(!li.lineitem_notes()) li.lineitem_notes([]);
698 var liWrapper = new openils.acq.Lineitem({lineitem:li});
699 row.setAttribute('li', li.id());
700 var tds = dojo.query('[attr]', row);
701 dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
702 dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
704 // so we can scroll to it later
705 dojo.query('[name=bib-info-cell]', row)[0].id = 'li-title-ref-' + li.id();
708 liWrapper.findAttr("isbn", "lineitem_marc_attr_definition") ||
709 liWrapper.findAttr("upc", "lineitem_marc_attr_definition");
711 // XXX media prefix for added content
713 nodeByName("jacket", row).setAttribute(
714 "src", "/opac/extras/ac/jacket/small/" + identifier
718 nodeByName("liid", row).innerHTML += li.id();
720 var exist = nodeByName('li_existing_count', row);
721 fieldmapper.standardRequest(
722 ['open-ils.acq', 'open-ils.acq.lineitem.existing_copies.count'],
724 params: [this.authtoken, li.id()],
725 oncomplete : function(r) {
726 var count = openils.Util.readResponse(r);
727 exist.innerHTML = count;
728 if (Number(count) > 0) {
729 openils.Util.addCSSClass(
730 exist, 'acq-existing-count-warn');
734 label : dojo.string.substitute(
735 localeStrings.LI_EXISTING_COPIES, [count])
742 openils.Util.show(nodeByName('catalog', row), 'inline');
743 nodeByName("catalog_link", row).onclick = this.generateMakeRecTab(li.eg_bib_id());
745 openils.Util.show(nodeByName('link_to_catalog', row), 'inline');
746 nodeByName("link_to_catalog_link", row).onclick = function() { self.drawBibFinder(li) };
749 if (li.queued_record()) {
750 this.pcrud.retrieve('vqbr', li.queued_record(),
752 oncomplete : function(r) {
753 var qrec = openils.Util.readResponse(r);
754 openils.Util.show(nodeByName('queue', row), 'inline');
755 var link = nodeByName("queue_link", row);
756 link.onclick = function() {
757 // open a new tab to the vandelay queue for this record
758 openils.XUL.newTabEasy(
759 oilsBasePath + '/vandelay/vandelay?qtype=bib&qid=' + qrec.queue()
767 nodeByName("worksheet_link", row).href =
768 oilsBasePath + "/acq/lineitem/worksheet/" + li.id() +
769 '?source=' + encodeURIComponent(location.pathname + location.search)
771 nodeByName("show_requests_link", row).href =
772 oilsBasePath + "/acq/picklist/user_request?lineitem=" + li.id() +
773 '?source=' + encodeURIComponent(location.pathname + location.search)
775 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
776 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
777 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
778 dojo.query('[name=expand_inline_copies]', row)[0].onclick =
779 function() {self.drawInlineCopies(li.id())};
782 if (sum = li.order_summary()) { // assignment
783 // Only show the paid label if at least one copy is invoiced.
784 // In other words, a lineitem whose every copy is canceled
786 if (sum.invoice_count() > 0) {
787 if (sum.item_count() == (
788 sum.invoice_count() + sum.cancel_count())) {
789 // Lineitem is fully paid. Display the paid-off label
790 openils.Util.show(nodeByName('paid', row), 'inline');
795 this.drawOrderIdentSelector(li, row);
797 if (!this.skipInitialEligibilityCheck)
801 function(full) { self.setClaimPolicyControl(full, row) },
805 this.updateLiNotesCount(li, row);
807 // show which PO this lineitem is a member of
808 if(li.purchase_order() && !this.isPO) {
810 this.poCache[li.purchase_order()] =
811 this.poCache[li.purchase_order()] ||
812 fieldmapper.standardRequest(
813 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
815 this.authtoken, li.purchase_order(), {
816 "flesh_price_summary": true,
817 "flesh_provider" : true,
818 "flesh_lineitem_count": true
821 if(po && !this.isMeta) {
822 openils.Util.show(nodeByName('po', row), 'inline');
823 var link = nodeByName('po_link', row);
824 link.setAttribute('href', oilsBasePath +
825 '/acq/po/view/' + li.purchase_order() +
826 '?focus_li=' + li.id() +
827 '&source=' + encodeURIComponent(location.pathname + location.search)
829 link.innerHTML += po.name();
831 openils.Util.show(nodeByName('pro', row), 'inline');
832 link = nodeByName('pro_link', row);
833 link.setAttribute('href', oilsBasePath + '/conify/global/acq/provider/' + po.provider().id())
834 link.innerHTML += po.provider().code();
838 // show which picklist this lineitem is a member of
839 if(li.picklist() && (this.isPO || this.isMeta || this.isUni)) {
841 this.plCache[li.picklist()] =
842 this.plCache[li.picklist()] ||
843 fieldmapper.standardRequest(
844 ['open-ils.acq', 'open-ils.acq.picklist.retrieve.authoritative'],
845 {params: [this.authtoken, li.picklist()]});
847 if (pl.name() == "") {
848 openils.Util.show(nodeByName("bib_origin", row), "inline");
852 openils.Util.show(nodeByName('pl', row), 'inline');
853 var link = nodeByName('pl_link', row);
854 link.setAttribute('href', oilsBasePath +
855 '/acq/picklist/view/' + li.picklist() +
856 '?focus_li=' + li.id() +
857 '&source=' + encodeURIComponent(location.pathname + location.search)
859 link.innerHTML += pl.name();
864 var countNode = nodeByName('count', row);
865 var count = li.item_count() || 0;
866 if (typeof(this._copy_count_cb) == "function") {
867 this._copy_count_cb(li.id(), count);
869 countNode.innerHTML = count;
870 countNode.id = 'acq-lit-copy-count-label-' + li.id();
873 var priceInput = dojo.query('[name=price]', row)[0];
874 priceInput.value = li.estimated_unit_price() || '';
875 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
877 // show either "mark received" or "unreceive" as appropriate
878 this.updateLiState(li, row);
880 if (skip_final_placement) {
884 // the last LI may be rendered after the call to show('list'),
885 // so make sure it's focused if necessary.
886 if (this.focusLineitem == li.id())
890 this._liCountClaims = function(li) {
892 for (var i = 0; i < li.lineitem_details().length; i++)
893 total += li.lineitem_details()[i].claims().length;
897 this._findLiRow = function(li) {
898 return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
901 this.reconsiderClaimControl = function(li, row) {
902 if (!row) row = this._findLiRow(li);
903 var option = nodeByName("action_manage_claims", row);
904 var eligible = this.claimEligibleLidByLi[li.id()].length;
905 var count = this._liCountClaims(li);
907 option.disabled = !(count || eligible);
909 dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
910 option.onclick = function() { self.claimDialog.show(li); };
913 this.clearEligibility = function(li) {
914 this.claimEligibleLidByLi[li.id()] = [];
916 if (li.lineitem_details()) {
917 li.lineitem_details().forEach(
918 function(lid) { delete self.claimEligibleLid[lid.id()]; }
922 if (this.copyCache) {
924 for (var k in this.copyCache) {
925 if (this.copyCache[k].lineitem() == li.id())
929 function(k) { delete self.claimEligibleLid[k]; }
934 this.applyOrderIdentValues = function() {
935 this._identValuesInFlight =
936 openils.Util.objectProperties(this.liCache).length;
937 for (var liId in this.liCache) {
938 this._applyOrderIdentValue(this.liCache[liId]);
942 // returns true if request was sent
943 this._applyOrderIdentValue = function(li, oncomplete) {
946 console.log('applying ident value for lineitem ' + li.id());
949 var row = dojo.query('[li=' + li.id() + ']')[0];
951 // find the selected ident value
952 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
953 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
954 var name = typeSel.options[typeSel.selectedIndex].value;
955 var val = typeSel._cbox.attr('value');
957 console.log("selected ident is " + val);
959 // it differs from the existing ident value, update it
960 var oldIdent = self.getLiOrderIdent(li);
962 oldIdent.attr_name() == name &&
963 oldIdent.attr_value() == val) {
964 console.log('selected ident attr matches existing attr');
965 if (--this._identValuesInFlight == 0) {
966 if (oncomplete) oncomplete(li);
967 else location.href = location.href;
972 // see if the selected ident value is represented
973 // by an existing lineitem attr
976 typeSel._cbox.store.fetch({
977 query : {attr_value : val},
978 onItem : function(item) {
979 console.log('found existing attr for ident value');
980 args.source_attr_id = li.attributes().filter(
981 function(attr) { return attr.id() == item.id[0] }
987 if (!args.source_attr_id) {
988 // user entered new text in the combobox
989 // so we need to create a new attr
990 console.log('creating new ident attr');
991 args.lineitem_id = li.id();
992 args.attr_name = name;
993 args.attr_value = val;
996 fieldmapper.standardRequest(
997 ['open-ils.acq', 'open-ils.acq.lineitem.order_identifier.set'],
999 params : [openils.User.authtoken, args],
1000 oncomplete : function() {
1001 console.log('order_ident oncomplete');
1002 if (--self._identValuesInFlight == 0) {
1003 if (oncomplete) oncomplete(li);
1004 else location.href = location.href;
1006 console.log(self._identValuesInFlight + ' still in flight');
1014 this.getLiOrderIdent = function(li) {
1015 var attrs = li.attributes();
1016 if (!attrs) return null;
1017 return attrs.filter(
1020 attr.attr_type() == 'lineitem_local_attr_definition' &&
1021 openils.Util.isTrue(attr.order_ident())
1027 this.drawOrderIdentSelector = function(li, row) {
1029 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
1030 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
1032 var attrs = li.attributes();
1034 // limit to MARC attr defs
1035 attrs = attrs.filter(
1037 return (attr.attr_type() == 'lineitem_marc_attr_definition');
1041 var identAttr = this.getLiOrderIdent(li);
1044 // collect the values for each type of identifier
1045 // find a reasonable default identifier type to render
1049 dojo.forEach(['isbn', 'upc', 'issn'],
1052 // collect the values for this attr name
1053 values[name] = attrs.filter(
1055 return (attr.attr_name() == name)
1059 // select a reasonable default name in the type-selector
1063 if (identAttr.attr_name() == name)
1065 } else if (values[name].length) {
1070 dojo.forEach(typeSel.options, function(opt) {
1071 if (opt.value == name) {
1072 opt.selected = true;
1081 function updateOrderIdent(val) {
1082 self._identValuesInFlight = 1;
1083 self._applyOrderIdentValue(
1086 self.refreshLineitem(li);
1091 // replace the ident combobox with a new
1092 // one for the selected ident type
1093 function changeComboBox(sel) {
1094 var name = sel.options[sel.selectedIndex].value;
1096 var td = dojo.query('[name=order_ident_value]', row)[0];
1097 if (td.childNodes[0])
1098 dojo.destroy(td.childNodes[0]);
1100 var store = new dojo.data.ItemFileWriteStore({
1101 data : acqlia.toStoreData(values[name])
1104 var cbox = new dijit.form.ComboBox(
1106 labelAttr : 'attr_value',
1107 searchAttr : 'attr_value'
1109 dojo.create('div', {}, td)
1114 // set the value for the cbox
1115 if (values[name].length) {
1116 var orderIdent = self.getLiOrderIdent(li);
1118 if (orderIdent && orderIdent.attr_name() == name) {
1119 cbox.attr('value', orderIdent.attr_value());
1121 cbox.attr('value', values[name][0].attr_value());
1125 if (!self.orderIdentAllowed)
1126 cbox.attr('disabled', true);
1129 cbox._lineitem = li;
1130 dojo.connect(cbox, 'onChange', updateOrderIdent);
1133 changeComboBox(typeSel); // force the initial draw
1134 typeSel.onchange = function() {changeComboBox(typeSel)};
1137 this.testOrderIdentPerms = function(org, callback) {
1139 new openils.User().getPermOrgList(
1140 'ACQ_SET_LINEITEM_IDENTIFIER',
1142 console.log('found orgs = ' + orgs);
1143 for (var i = 0; i < orgs.length; i++) {
1144 if (Number(orgs[i]) == Number(org)) {
1145 self.orderIdentAllowed = true;
1146 if (callback) callback();
1150 if (callback) callback();
1156 this.checkClaimEligibility = function(li, callback, row) {
1157 /* Assume always eligible, i.e. from this interface we don't care about
1158 * claim eligibility any more. this is where the user would force a
1160 this.clearEligibility(li);
1161 this.claimEligibleLidByLi[li.id()] = li.lineitem_details().map(
1162 function(lid) { return lid.id(); }
1164 li.lineitem_details().forEach(
1165 function(lid) { self.claimEligibleLid[lid.id()] = true; }
1167 this.reconsiderClaimControl(li, row);
1168 if (callback) callback(li);
1170 this.clearEligibility(li);
1171 fieldmapper.standardRequest(
1172 ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
1173 "params": [openils.User.authtoken, {"lineitem": li.id()}],
1175 "onresponse": function(r) {
1176 if (r = openils.Util.readResponse(r)) {
1177 self.claimEligibleLidByLi[li.id()].push(
1180 self.claimEligibleLid[r.lineitem_detail()] = true;
1183 "oncomplete": function() {
1184 self.reconsiderClaimControl(li, row);
1185 if (typeof(callback) == "function")
1193 this.updateLiNotesCount = function(li, row) {
1194 if (!row) row = this._findLiRow(li);
1196 var has_notes = (li.lineitem_notes().filter(
1197 function(o) { return Boolean (o.alert_text()); }
1200 /* U+2691 is the code point for a filled-in flag character */
1201 nodeByName("notes_alert_flag", row).innerHTML =
1202 has_notes ? "⚑" : "";
1203 nodeByName("noteslink", row).style.fontStyle =
1204 has_notes ? "italic" : "normal";
1205 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
1208 /* XXX NOT related to _updateLiState(). rethink */
1209 this.updateLiState = function(li, row) {
1210 if (!row) row = this._findLiRow(li);
1212 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
1213 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
1215 // always allow access to LI history
1216 nodeByName('action_view_history', row).onclick =
1217 function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
1219 /* handle row coloring for based on LI state */
1220 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1221 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
1223 // Expose invoice actions for any lineitem that is linked to a PO
1224 if (li.purchase_order()) {
1225 openils.Util.show(nodeByName("invoices_span", row), "inline");
1226 var link = nodeByName("invoices_link", row);
1227 link.onclick = function() {
1228 openils.XUL.newTabEasy(
1229 oilsBasePath + "/acq/search/unified?so=" +
1230 base64Encode({"jub":[{"id": li.id()}]}) + "&rt=invoice"
1238 * If we haven't fleshed the lineitem_details, default to allowing access to the
1239 * holdings maintenence actions. The alternative is to flesh LIDs on every lineitem,
1240 * but that will add to page render time. Let's see if this will suffice...
1242 var lids = li.lineitem_details();
1244 (lids && !lids.filter(function(lid) { return lid.eg_copy_id() })[0] )) {
1246 actUpdateBarcodes.disabled = false;
1247 actUpdateBarcodes.onclick = function() {
1248 self.showRealCopyEditUI(li);
1249 nodeByName("action_none", row).selected = true;
1251 actHoldingsMaint.disabled = false;
1252 actHoldingsMaint.onclick =
1253 self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
1256 var state_cell = nodeByName("li_state_" + li.state(), row);
1258 // re-hide any state label nodes which may have been un-hidden
1259 // through previous actions.
1260 dojo.query('[state-label]', row).forEach(function(node) {
1261 openils.Util.hide(node)
1264 if (li.state() == 'cancelled') {
1265 if(typeof li.cancel_reason() == "object") {
1267 // clear the stock "Canceled" label, since we have more
1268 // information to replace it with.
1269 state_cell.innerHTML = '';
1271 var holds_state = dojo.create(
1273 "style": "border-bottom: 1px dashed #000;",
1274 "innerHTML": li.cancel_reason().label()
1275 }, state_cell, "only"
1279 "label": "<em>" + li.cancel_reason().label() +
1280 "</em><br />" + li.cancel_reason().description(),
1281 "connectId": [holds_state]
1282 }, dojo.create("span", null, state_cell, "last")
1285 if (li.cancel_reason().keep_debits() == 't') {
1286 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1287 openils.Util.addCSSClass(row, "oils-acq-li-state-delayed");
1290 console.log('li cancel_reason is un-fleshed. Please fix');
1294 openils.Util.show(state_cell);
1298 this._setAlertStore = function() {
1299 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
1301 "data": acqliat.toStoreData(
1304 "owning_lib": aou.orgNodeTrail(
1305 aou.findOrgUnit(openils.User.user.ws_ou())
1306 ).map(function(o) { return o.id(); })
1312 acqLitAlertAlertText.setValue(); /* make the store "live" */
1313 acqLitAlertAlertText._store_ready = true;
1317 * Draws and shows the lineitem notes pane
1319 this.drawLiNotes = function(li) {
1321 this.focusLineitem = li.id();
1323 if (!acqLitAlertAlertText._store_ready)
1324 this._setAlertStore();
1327 li.lineitem_notes().sort(
1329 if(a.edit_time() < b.edit_time()) return 1;
1335 while(this.liNotesTbody.childNodes[0])
1336 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
1339 acqLitCreateNoteSubmit.onClick = function() {
1340 var value = acqLitCreateNoteText.attr('value');
1342 var note = new fieldmapper.acqlin();
1345 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
1348 note.lineitem(li.id());
1350 self.updateLiNotes(li, note);
1351 acqLitCreateNoteVendorPublic.attr("checked", false);
1352 acqLitCreateNoteText.attr("value", "");
1355 acqLitCreateAlertSubmit.onClick = function() {
1356 if (!acqLitAlertAlertText.item) {
1357 alert(localeStrings.ALERT_UNSELECTED);
1361 var alert_text = new fieldmapper.acqliat().fromStoreItem(
1362 acqLitAlertAlertText.item
1364 var value = acqLitAlertNoteValue.attr("value") || "";
1366 var note = new fieldmapper.acqlin();
1368 note.lineitem(li.id());
1370 note.alert_text(alert_text);
1372 self.updateLiNotes(li, note);
1375 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
1379 * Draws a single lineitem note in the notes pane
1381 this.addLiNote = function(li, note) {
1382 if(note.isdeleted()) return;
1384 var row = self.liNotesRow.cloneNode(true);
1385 nodeByName("value", row).innerHTML = note.value();
1386 var alert_node = nodeByName("alert_code", row);
1387 if (note.alert_text()) {
1388 alert_node.innerHTML = dojo.string.substitute(
1390 aou.findOrgUnit(note.alert_text().owning_lib()).shortname(),
1391 note.alert_text().code()
1394 if (note.alert_text().description()) {
1397 "connectId": [alert_node],
1398 "label": note.alert_text().description()
1399 }, dojo.create("span", null, alert_node, "after")
1404 if (openils.Util.isTrue(note.vendor_public()))
1405 nodeByName("vendor_public", row).innerHTML =
1406 localeStrings.VENDOR_PUBLIC;
1408 nodeByName("delete", row).onclick = function() {
1409 note.isdeleted(true);
1410 self.liNotesTbody.removeChild(row);
1411 self.updateLiNotes(li);
1414 if(note.edit_time()) {
1415 nodeByName("edit_time", row).innerHTML =
1416 dojo.date.locale.format(
1417 dojo.date.stamp.fromISOString(note.edit_time()),
1418 {formatLength:'short'});
1421 self.liNotesTbody.appendChild(row);
1425 * Updates any new/changed/deleted notes on the server
1427 this.updateLiNotes = function(li, newNote) {
1433 notes = li.lineitem_notes().filter(
1435 if(note.ischanged() || note.isnew() || note.isdeleted())
1441 if(notes.length == 0) return;
1442 progressDialog.show();
1444 fieldmapper.standardRequest(
1445 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
1447 params : [this.authtoken, notes],
1448 onresponse : function(r) {
1449 var resp = openils.Util.readResponse(r);
1454 // remove the old changed notes
1456 dojo.forEach(li.lineitem_notes(),
1458 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
1462 li.lineitem_notes(list);
1465 progressDialog.hide();
1466 self.updateLiNotesCount(li);
1467 self.drawLiNotes(li);
1471 progressDialog.update(resp);
1472 var newnote = resp.note;
1474 if(!newnote.isdeleted()) {
1475 newnote.isnew(false);
1476 newnote.ischanged(false);
1477 li.lineitem_notes().push(newnote);
1484 this.updateLiPrice = function(input, li) {
1486 var price = input.value;
1487 if(Number(price) == Number(li.estimated_unit_price())) return;
1489 fieldmapper.standardRequest(
1490 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
1491 { async : false, // redundant w/ timeout
1493 params : [this.authtoken, li.id(), price],
1494 oncomplete : function(r) {
1495 openils.Util.readResponse(r);
1496 li.estimated_unit_price(price); // update local copy
1499 * If this is a PO and every visible lineitem has a price,
1500 * check again to see if this PO can be activated. Note that
1501 * every visible lineitem having a price does not guarantee it can
1502 * be activated, which is why we still make the call. Having a price
1503 * set for every visiable lineitem is just the lowest barrier to entry.
1506 var priceNodes = dojo.query('[name=price]', dojo.byId('acq-lit-tbody'));
1508 dojo.forEach(priceNodes, function(node) { if (node.value == '') allSet = false});
1509 if (allSet) checkCouldActivatePo();
1510 refreshPOSummaryAmounts();
1517 this.removeLineitem = function(liId) {
1518 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
1519 delete this.liCache[liId];
1520 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
1523 this.drawInfo = function(liId) {
1524 this.focusLineitem = liId;
1525 if (!this._isRelatedViewer) {
1526 var d = dojo.byId("acq-lit-info-related");
1527 if (!this.relCache[liId]) {
1528 fieldmapper.standardRequest(
1531 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
1534 "params": [openils.User.authtoken, liId],
1535 "onresponse": function(r) {
1536 self.relCache[liId] = openils.Util.readResponse(r);
1537 nodeByName("related_number", d).innerHTML =
1538 self.relCache[liId];
1540 self.relCache[liId] >1 ? "show" : "hide"
1546 nodeByName("related_number", d).innerHTML = this.relCache[liId];
1547 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
1552 openils.acq.Lineitem.fetchAttrDefs(
1554 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
1559 this.toggleInlineCopies = function() {
1560 // if any inline copies are not displayed,
1561 // display them all otherwise, hide them all.
1563 var displayAll = false;
1565 for (var liId in this.liCache) {
1566 if (!this.inlineCopiesVisible(liId)) {
1572 for (var liId in this.liCache) {
1573 var row = dojo.byId('acq-inline-copies-row-' + liId);
1575 if (!row || row._hidden) {
1576 this.drawInlineCopies(liId);
1578 } else { // hide all
1580 // drawInlineCopies() on a visible row will hide it.
1581 this.drawInlineCopies(liId);
1588 this.inlineCopiesVisible = function(liId) {
1589 var row = dojo.byId('acq-inline-copies-row-' + liId);
1590 return (row && !row._hidden);
1593 this.refreshInlineCopies = function(all, reFetch) {
1595 var liIds = this.inlineCopiesNeedingRefresh;
1596 if (all) liIds = openils.Util.objectProperties(liCache);
1597 liIds.forEach(function(liId) {
1598 if (self.inlineCopiesVisible(liId)) {
1599 self.drawInlineCopies(liId, reFetch); // hide
1600 self.drawInlineCopies(liId, reFetch); // re-draw
1605 // draw inline copy table. if the table is
1606 // already visible, hide the table as-is
1607 // reFetch forces a retrieval of the lineitem and
1608 // copies from the server. otherwise the locally
1609 // cached version of each is used.
1610 this.drawInlineCopies = function(liId, reFetch) {
1613 // find or create the row where the inline copies table will live
1614 var containerRow = dojo.byId('acq-inline-copies-row-' + liId);
1615 var liRow = dojo.query('[li=' + liId + ']')[0];
1617 if (!containerRow) {
1619 // build the inline copies container row and add it to
1620 // the DOM directly after the primary lineitem row
1622 containerRow = self.inlineCopyContainer.cloneNode(true);
1623 containerRow.id = 'acq-inline-copies-row-' + liId;
1625 if (liRow.nextSibling) {
1626 self.tbody.insertBefore(containerRow, liRow.nextSibling);
1628 self.tbody.appendChild(containerRow);
1633 // toggle the visible state
1634 containerRow._hidden = !containerRow._hidden;
1635 openils.Util.toggle(containerRow, 'table-row');
1637 if (containerRow._hidden) return; // hide only
1640 var handler = function(li) {
1642 var tbody = dojo.query(
1643 '[name=acq-li-inline-copies-tbody]',
1646 // reset the table before adding copy rows
1647 while (tbody.childNodes[0])
1648 tbody.removeChild(tbody.childNodes[0]);
1650 if(li.lineitem_details().length == 0) {
1652 self.inlineNoCopies.cloneNode(true));
1653 return; // no copies to show
1656 // add a row to the inline copy table for each copy
1657 dojo.forEach(li.lineitem_details(),
1659 var row = self.inlineCopyTemplate.cloneNode(true);
1660 tbody.appendChild(row);
1661 self.addInlineCopy(li, copy, row);
1666 this._fetchLineitem(liId, handler, reFetch);
1669 /** Draw read-only copy widgets for inline copies */
1670 this.addInlineCopy = function(li, copy, row) {
1673 dojo.forEach(liDetailFields,
1676 var widget = new openils.widget.AutoFieldWidget({
1679 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1680 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1681 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1683 parentNode : dojo.query('[name=' + field + ']', row)[0],
1692 /* For a given list of lineitem ids, build a list of full lineitems
1693 * re-using the fetching logic that is otherwise typical to use in this
1696 * If we've already got a lineitem in the cache, just use that.
1698 * Once we've built a list of lineitems, call callback(thatlist).
1700 this.fetchLineitemsById = function(id_list, callback) {
1701 var total = id_list.length;
1702 var result_list = [];
1704 var inner = function(li) {
1705 result_list.push(li)
1707 callback(result_list);
1710 id_list.forEach(function(id) { self._fetchLineitem(id, inner); });
1713 this._fetchLineitem = function(liId, handler, force) {
1715 var li = this.liCache[liId];
1716 if(li && li.marc() && li.lineitem_details() && !force)
1719 fieldmapper.standardRequest(
1720 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
1723 params: [self.authtoken, liId, {
1725 flesh_cancel_reason: true,
1726 flesh_li_details: true,
1728 flesh_fund_debit: true }],
1730 oncomplete: function(r) {
1731 var li = openils.Util.readResponse(r);
1732 self.liCache[liId] = li;
1739 this._drawInfo = function(li) {
1741 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
1743 if(li.eg_bib_id()) {
1744 openils.Util.hide('acq-lit-marc-order-record-label');
1745 openils.Util.hide(acqLitEditOrderMarc.domNode);
1746 openils.Util.show('acq-lit-marc-real-record-label');
1748 openils.Util.show('acq-lit-marc-order-record-label');
1749 openils.Util.show(acqLitEditOrderMarc.domNode);
1750 openils.Util.hide('acq-lit-marc-real-record-label');
1753 this.drawMarcHTML(li);
1754 this.infoTbody = dojo.byId('acq-lit-info-tbody');
1757 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
1758 while(this.infoTbody.childNodes[0])
1759 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
1761 for(var i = 0; i < li.attributes().length; i++) {
1762 var attr = li.attributes()[i];
1763 var row = this.infoRow.cloneNode(true);
1765 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
1766 var name = openils.acq.Lineitem.attrDefs[type].filter(
1768 return (a.code() == attr.attr_name());
1770 ).pop().description();
1772 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
1773 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
1774 this.infoTbody.appendChild(row);
1777 if (!this._isRelatedViewer) {
1778 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
1779 oilsBasePath + "/acq/lineitem/related/" + li.id();
1782 // if a top scroll point is defined, jump up to it here
1783 var node = dojo.byId('oils-scroll-to-top');
1784 if (node) dijit.scrollIntoView(node);
1787 this.generateMakeRecTab = function(bib_id,default_view, row) {
1791 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
1794 show_nav_buttons : true,
1795 show_print_button : true,
1796 opac_url : xulG.url_prefix('opac_rdetail|' + bib_id),
1797 default_view : default_view
1801 if(row) nodeByName("action_none", row).selected = true;
1805 this.drawMarcHTML = function(li) {
1806 var params = [null, true, li.marc()];
1808 params = [li.eg_bib_id(), true];
1810 fieldmapper.standardRequest(
1811 ['open-ils.search', 'open-ils.search.biblio.record.html'],
1814 oncomplete: function(r) {
1815 dojo.byId('acq-lit-marc-div').innerHTML =
1816 openils.Util.readResponse(r);
1822 this.drawCopies = function(liId, force_fetch) {
1823 this.focusLineitem = liId;
1824 if (typeof force_fetch == "undefined")
1825 force_fetch = false;
1827 var cgi = new openils.CGI();
1828 var source = cgi.param('source');
1829 if (source && source.match(/invoice/)) {
1830 // got here from the invoice page, show the 'return-to-invoice' button
1831 var cgi = new openils.CGI({url : source});
1832 cgi.param('focus_li', liId);
1833 openils.Util.show(dojo.byId('acq-lit-copies-back-to-invoice-button-wrapper'), 'inline');
1834 var button = dojo.byId('acq-lit-copies-back-to-invoice-button');
1835 button.onclick = function() { location.href = cgi.url() };
1838 openils.acq.Lineitem.fetchAndRender(liId, {},
1839 function(li, html) {
1840 dojo.byId('acq-lit-copies-li-summary').innerHTML = html;
1844 this.show('copies');
1846 this.copyCache = {};
1847 this.copyWidgetCache = {};
1848 this.oldCopyWidgetCache = {};
1849 this.virtDfaCounts = {};
1850 this.realDfaCache = {};
1853 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
1854 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
1855 acqLitCopyCountInput.attr('value', '0');
1857 if (this.isPO && PO && PO.order_date()) {
1858 // prevent adding copies to activated POs
1859 acqLitCopyCountInput.attr('disabled', true);
1860 acqLitAddCopyCount.attr('disabled', true);
1863 while(this.copyTbody.childNodes[0])
1864 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
1866 this._drawBatchCopyWidgets();
1868 this._drawDistribApplied(liId);
1870 this._fetchDistribFormulas(
1872 openils.acq.Lineitem.fetchAttrDefs(
1874 self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch);
1881 this._saveDistribAppliedTemplates = function() {
1882 if (!this._appliedDistribTemplate) {
1883 this._appliedDistribTemplate =
1884 dojo.byId("acq-lit-distrib-applied-tbody").
1885 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
1886 dojo.attr(this._appliedDistribTemplate, "id");
1890 this._drawDistribApplied = function(liId) {
1891 /* Build this table while hidden to prevent rendering artifacts */
1892 openils.Util.hide("acq-lit-distrib-applied-tbody");
1894 this._saveDistribAppliedTemplates();
1896 /* Remove any rows in the table from previous populations */
1897 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
1898 forEach(dojo.destroy);
1900 /* Unregister all dijits previously created (for some reason this isn't
1901 * covered by the above destroy calls). */
1902 dijit.registry.forEach(
1903 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
1906 /* Populate the table with our liId */
1908 fieldmapper.standardRequest(
1910 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
1913 "params": [self.authtoken, liId],
1914 "onresponse": function(r) {
1915 var dfa = openils.Util.readResponse(r);
1918 self.realDfaCache[dfa.id()] = dfa;
1919 self._drawDistribAppliedUnit(dfa);
1922 "oncomplete": function() {
1923 /* Reveal built table */
1926 "acq-lit-distrib-applied-tbody", "table-row-group"
1934 this._drawDistribAppliedUnit = function(dfa) {
1935 var new_row = false;
1936 var row = dojo.query(
1937 'tr[formula="' + dfa.formula().id() + '"]',
1938 "acq-lit-distrib-applied-tbody"
1943 row = dojo.clone(this._appliedDistribTemplate);
1944 dojo.attr(row, "formula", dfa.formula().id());
1945 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
1948 var td = dojo.query("td", row)[0];
1950 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1951 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1954 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1956 new dijit.form.Button(
1958 "onClick": function() {
1959 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1960 self.deleteDfa(dfa);
1963 /* XXX I /cannot/ make the following work in as a CSS class
1964 * for some reason. So frustrating... */
1965 "style": function(id) {
1967 "font-weight: bold; color: #c00;" :
1969 }(dfa.id()) + "margin: 0 6px;display: inline;"
1970 }, "dfa-button-" + dfa.id()
1974 "connectId": ["dfa-button-" + dfa.id()],
1975 "label": dojo.string.substitute(
1976 localeStrings.DFA_TIP, dfa.id() > 0 ? [
1977 openils.User.formalName(dfa.creator()),
1978 dojo.date.locale.format(
1979 dojo.date.stamp.fromISOString(dfa.create_time()),
1980 {"formatLength":"short"}
1982 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
1984 }, "dfa-tip-" + dfa.id()
1988 this.deleteDfa = function(dfa) {
1989 if (dfa.id() > 0) { /* real */
1990 this.pcrud.eliminate(
1993 "oncomplete": function() {
1994 self._removeDistribApplied(dfa.id());
1995 delete self.realDfaCache[dfa.id()];
1999 } else { /* virtual */
2000 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
2001 this.virtDfaCounts[dfa.formula().id()] = 0;
2002 /* hasn't been saved yet, so no need to do anything server side */
2003 this._removeDistribApplied(dfa.id());
2008 this._removeDistribApplied = function(dfaId) {
2009 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
2010 dijit.registry.forEach(
2011 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
2013 this._removeDistribAppliedEmptyRows();
2016 this._removeAllDistribAppliedVirtual = function() {
2017 /* Unregister dijits */
2018 dijit.registry.forEach(
2019 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
2021 this._removeDistribAppliedEmptyRows();
2024 this._removeDistribAppliedEmptyRows = function() {
2025 /* Remove any rows with no DFA at all */
2026 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
2028 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
2034 * Insert a new row into the distribution formula selection form
2036 this._addDistribFormulaRow = function() {
2039 if (!self.distribForms) {
2040 // no formulas, hide the form
2041 openils.Util.hide('acq-lit-distrib-formula-table');
2045 if(!this.distribFormulaTemplate)
2046 this.distribFormulaTemplate =
2047 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
2049 var row = this.distribFormulaTemplate.cloneNode(true);
2050 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
2052 this.dfSelector = new dijit.form.FilteringSelect(
2053 {"labelAttr": "dynLabel", "labelType": "html"},
2054 nodeByName("selector", row)
2056 this._updateFormulaStore();
2057 this.dfSelector.fetchProperties =
2058 {"sort": [{"attribute": "use_count", "descending": true}]};
2060 var apply = new dijit.form.Button(
2061 {"label": localeStrings.APPLY},
2062 nodeByName('set_button', row)
2065 var reset = new dijit.form.Button(
2066 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
2067 nodeByName("reset_button", row)
2070 dojo.connect(apply, 'onClick',
2072 var form_id = self.dfSelector.attr("value");
2073 if(!form_id) return;
2074 self._applyDistribFormula(form_id);
2075 reset.attr("disabled", false);
2079 dojo.connect(reset, 'onClick',
2081 self.restoreCopyFieldsBeforeDF();
2082 self.virtDfaCounts = {};
2083 self.virtDfaId = -1;
2085 self._updateFormulaStore();
2086 self._removeAllDistribAppliedVirtual();
2087 reset.attr("disabled", "true");
2094 * Applies a distrib formula to the current set of copies
2096 this._applyDistribFormula = function(formula) {
2097 if(!formula) return;
2099 formula = this.distribForms.filter(
2100 function(form) { return form.id() == formula; }
2103 var copyRows = dojo.query('tr', self.copyTbody);
2105 if (this.dfeOffset >= copyRows.length) {
2106 alert(localeStrings.OUT_OF_COPIES);
2110 var entries_applied = 0;
2112 var rowIndex = this.dfeOffset;
2113 rowIndex < copyRows.length;
2117 var row = copyRows[rowIndex];
2118 var copy_id = row.getAttribute('copy_id');
2119 var copyWidgets = this.copyWidgetCache[copy_id];
2120 var entryIndex = this.dfeOffset;
2123 // find the correct entry for the current row
2124 dojo.forEach(formula.entries(),
2127 entryIndex += e.item_count();
2128 if(entryIndex > rowIndex)
2136 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
2137 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
2140 this.saveCopyFieldsBeforeDF(copy_id);
2141 this._copy_fields_for_acqdf.forEach(
2143 if(entry[field]()) {
2144 copyWidgets[field].attr('value', (entry[field]()));
2151 if (entries_applied) {
2152 this.virtDfaCounts[formula.id()] =
2153 ++(this.virtDfaCounts[formula.id()]) || 1;
2154 this._updateFormulaStore();
2155 this._drawDistribAppliedUnit(
2157 var dfa = new acqdfa();
2158 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
2161 this.dfeOffset += entries_applied;
2166 * This function updates the DF store for the dropdown so that use_counts
2167 * can reflect DF applications from this session before they're saved
2170 this._updateFormulaStore = function() {
2171 this.dfSelector.store = new dojo.data.ItemFileReadStore(
2173 "data": self._labelFormulasWithCounts(
2174 acqdf.toStoreData(self.distribForms)
2180 this.saveCopyFieldsBeforeDF = function(copy_id) {
2182 if (!this.oldCopyWidgetCache[copy_id]) {
2183 var copyWidgets = this.copyWidgetCache[copy_id];
2185 this.oldCopyWidgetCache[copy_id] = {};
2186 this._copy_fields_for_acqdf.forEach(
2188 self.oldCopyWidgetCache[copy_id][f] =
2189 copyWidgets[f].attr("value");
2195 this.restoreCopyFieldsBeforeDF = function() {
2197 for (var copy_id in this.oldCopyWidgetCache) {
2198 this._copy_fields_for_acqdf.forEach(
2200 self.copyWidgetCache[copy_id][f].attr(
2201 "value", self.oldCopyWidgetCache[copy_id][f]
2208 this._labelFormulasWithCounts = function(store_data) {
2209 for (var key in store_data.items) {
2210 var obj = store_data.items[key];
2211 obj.use_count = Number(obj.use_count); /* needed for sorting */
2213 if (this.virtDfaCounts[obj.id])
2214 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
2216 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
2217 obj.use_count + "]</span> " + obj.name;
2223 * This method formerly would not refetch the DF formulas if they'd been
2224 * loaded already, but now it always re-fetches, since use_count changes.
2226 /** TODO: port distrib-formula selector to autofieldwidget+pcrud/dojo store */
2227 this._fetchDistribFormulas = function(onload) {
2228 fieldmapper.standardRequest(
2230 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
2233 "params": [openils.User.authtoken, 0, 500],
2234 "oncomplete": function(r) {
2235 self.distribForms = openils.Util.readResponse(r);
2236 if(!self.distribForms || self.distribForms.length == 0) {
2237 self.distribForms = [];
2239 self._addDistribFormulaRow();
2246 this._drawBatchCopyWidgets = function() {
2247 var row = this.copyBatchRow;
2248 dojo.forEach(liDetailBatchFields,
2250 if(self.copyBatchRowDrawn) {
2251 self.copyBatchWidgets[field].attr('value', null);
2253 var args = self.afwCopyFieldArgs(field, "CREATE_PICKLIST");
2254 args.parentNode = dojo.query('[name='+field+']', row)[0];
2256 var widget = new openils.widget.AutoFieldWidget(args);
2259 if (field == "fund" && w.store)
2260 self._ensureCSSFundClasses(w.store);
2261 self.copyBatchWidgets[field] = w;
2264 if (field == "fund") {
2266 widget.widget, "onChange", function(val) {
2267 self._updateFundSelectorStyle(widget, val);
2274 this.copyBatchRowDrawn = true;
2277 this.batchCopyUpdate = function() {
2279 for(var k in this.copyWidgetCache) {
2280 var cache = this.copyWidgetCache[k];
2281 dojo.forEach(liDetailBatchFields, function(f) {
2282 var newval = self.copyBatchWidgets[f].attr('value');
2283 if(newval) cache[f].attr('value', newval);
2288 this._drawCopies = function(li) {
2291 // this button sets the total number of copies for a given lineitem
2292 acqLitAddCopyCount.onClick = function() {
2293 var count = acqLitCopyCountInput.attr('value');
2296 while(self.copyCount() < count)
2299 // delete rows if necessary
2300 var diff = self.copyCount() - count;
2302 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
2303 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
2304 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
2306 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2312 if(li.lineitem_details().length > 0) {
2313 dojo.forEach(li.lineitem_details(),
2315 self.addCopy(li, copy);
2323 this.copyCount = function() {
2325 for(var id in this.copyCache) {
2326 if(!this.copyCache[id].isdeleted())
2332 this.virtCopyId = -1;
2333 this.addCopy = function(li, copy) {
2334 var row = this.copyRow.cloneNode(true);
2335 this.copyTbody.appendChild(row);
2339 copy = new fieldmapper.acqlid();
2341 copy.id(this.virtCopyId--);
2342 copy.lineitem(li.id());
2345 this.copyCache[copy.id()] = copy;
2346 row.setAttribute('copy_id', copy.id());
2347 self.copyWidgetCache[copy.id()] = {};
2349 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2351 var rcvr = copy.receiver();
2353 if (!userCache[rcvr]) {
2354 if(rcvr == openils.User.user.id()) {
2355 userCache[rcvr] = openils.User.user;
2357 userCache[rcvr] = fieldmapper.standardRequest(
2358 ['open-ils.actor', 'open-ils.actor.user.retrieve'],
2359 {params: [openils.User.authtoken, rcvr]}
2363 dojo.query('[name=receiver]', row)[0].innerHTML = userCache[rcvr].usrname();
2366 dojo.forEach(liDetailFields,
2369 if (field == "fund") {
2370 searchFilter = (copy.fund() ?
2371 {"-or": {"active": "t", "id": copy.fund()}} :
2373 searchFilter.org = fundSearchFilter.org;
2375 searchFilter = null;
2378 var readOnly = false;
2380 // TODO: Add support for changing the owning_lib after real copies have been made.
2381 // owning_lib is order data as much as its item data
2382 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
2386 // TODO: add support for changing the fund after debits have been created
2387 // Note: invoicing allows the change
2388 if(copy.fund_debit() && field == 'fund') {
2393 var widget = new openils.widget.AutoFieldWidget({
2396 labelFormat : (field == 'fund') ? fundLabelFormat : null,
2397 searchFormat : (field == 'fund') ? fundSearchFormat : null,
2398 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
2399 searchFilter : searchFilter,
2400 noCache: (field == "fund"),
2402 parentNode : dojo.query('[name='+field+']', row)[0],
2403 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2404 readOnly : readOnly,
2405 orgDefaultsToWs : true
2409 // make sure we capture the value from any async widgets
2412 if (field == "fund" && w.store)
2413 self._ensureCSSFundClasses(w.store);
2416 copy[field](ww.getFormattedValue())
2418 self.copyWidgetCache[copy.id()][field] = w;
2420 dojo.connect(w, 'onChange',
2422 if (field == "fund")
2423 self._updateFundSelectorStyle(widget, val);
2425 if (!readOnly && (copy.isnew() || val != copy[field]())) {
2426 // prevent setting ischanged() automatically on widget load for existing copies
2427 copy[field](widget.getFormattedValue())
2428 copy.ischanged(true);
2437 this.updateLidState(copy, row);
2440 this._ensureCSSFundClass = function(id) {
2441 if (!this.fundStyleSheet) {
2443 "style", {"type": "text/css"},
2444 document.getElementsByTagName("head")[0], "last"
2446 this.fundStyleSheet = document.styleSheets[
2447 document.styleSheets.length - 1
2451 var cn = "fund_" + id;
2452 if (!this.haveFundClass[cn]) {
2453 fieldmapper.standardRequest(
2454 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
2456 "params": [openils.User.authtoken, id],
2458 "oncomplete": function(r) {
2459 r = openils.Util.readResponse(r);
2460 self.fundBalanceState[id] = r;
2462 if (r[0] /* stop */)
2463 style = fundStyles.stop;
2464 else if (r[1] /* warning */)
2465 style = fundStyles.warning;
2466 self.fundStyleSheet.insertRule(
2467 "." + cn + " { " + style + " }",
2468 self.fundStyleSheet.cssRules.length
2470 self.haveFundClass[cn] = true;
2477 this._ensureCSSFundClasses = function(store) {
2479 "query": {"id": "*"},
2480 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
2484 this._updateFundSelectorStyle = function(widget, fund_id) {
2485 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
2486 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
2489 this.updateLidState = function(copy, row) {
2492 if (typeof(row) == "undefined") {
2493 row = dojo.query('tr[copy_id="' + copy.id() + '"]', this.copyTbody)[0];
2497 var recv_link = nodeByName("receive", row);
2498 var unrecv_link = nodeByName("unreceive", row);
2499 var del_link = nodeByName("delete", row);
2500 var cxl_link = nodeByName("cancel", row);
2501 var claim_link = nodeByName("claim", row);
2502 var cxl_reason_link = nodeByName("cancel_reason", row);
2504 // by default, hide all the actions
2505 openils.Util.hide(del_link.parentNode);
2506 openils.Util.hide(recv_link);
2507 openils.Util.hide(unrecv_link);
2508 openils.Util.hide(cxl_link);
2509 openils.Util.hide(claim_link);
2510 openils.Util.hide(cxl_reason_link);
2512 if (copy.id() > 0) { // real copies (LIDs)
2514 if (copy.cancel_reason()) {
2516 /* --------- cancelled -------------------------- */
2518 /* XXX the following may leak memory in a long lived table:
2519 * dijits may not get destroyed... not positive. revisit. */
2520 var holds_reason = dojo.create(
2522 "style": "border-bottom: 1px dashed #000;",
2523 "innerHTML": copy.cancel_reason().label()
2524 }, cxl_reason_link, "only"
2528 "label": "<em>" + copy.cancel_reason().label() +
2529 "</em><br />" + copy.cancel_reason().description(),
2530 "connectId": [holds_reason]
2531 }, dojo.create("span", null, cxl_reason_link, "last")
2533 openils.Util.show(cxl_reason_link, "inline");
2535 if (copy.cancel_reason().keep_debits() == 't' ) {
2536 // allow further cancellation of "delayed" copies
2538 openils.Util.show(cxl_link, "inline");
2539 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2542 } else if (copy.recv_time()) {
2544 /* --------- received -------------------------- */
2546 openils.Util.show(unrecv_link, "inline");
2547 unrecv_link.onclick = function() {
2548 if (confirm(localeStrings.UNRECEIVE_LID))
2549 self.issueReceive(copy, /* rollback */ true);
2552 } else if (this.liCache[copy.lineitem()].state() == 'on-order') {
2554 /* --------- on order -------------------------- */
2556 openils.Util.show(recv_link, 'inline');
2557 openils.Util.show(cxl_link, "inline");
2559 recv_link.onclick = function() {
2560 if (self.checkLiAlerts(copy.lineitem()))
2561 self.issueReceive(copy);
2564 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2568 /* --------- pre-order copies -------------------------- */
2570 del_link.onclick = function() { self.deleteCopy(row) };
2571 openils.Util.show(del_link.parentNode);
2577 /* --------- virtual copies -------------------------- */
2579 del_link.onclick = function() { self.deleteCopy(row) };
2580 openils.Util.show(del_link.parentNode);
2584 this.cancelLid = function(lid_id) {
2585 lidCancelDialog._lid_id = lid_id;
2586 openils.Util.show(lidCancelDialog.domNode.parentNode);
2587 lidCancelDialog.show();
2588 if (!lidCancelDialog._prepared) {
2589 var widget = new openils.widget.AutoFieldWidget({
2590 "fmField": "cancel_reason",
2591 "fmClass": "acqlid",
2592 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
2593 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2595 "searchOptions" : {order_by : {"acqcr":"label"}}
2599 acqLidCancelButton.onClick = function() {
2600 if (w.attr("value")) {
2601 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
2603 lidCancelDialog._lid_id,
2607 lidCancelDialog.hide();
2610 lidCancelDialog._prepared = true;
2616 this._cancelLid = function(lid_id, reason) {
2617 fieldmapper.standardRequest(
2618 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
2619 "params": [openils.User.authtoken, lid_id, reason],
2621 "onresponse": function(r) {
2622 if (r = openils.Util.readResponse(r)) {
2624 for (var id in r.lid) {
2625 /* actually this should only iterate once */
2626 self.copyCache[id].cancel_reason(
2627 r.lid[id].cancel_reason
2629 self.updateLidState(self.copyCache[id]);
2638 this._confirmAlert = function(li, lin) {
2640 dojo.string.substitute(
2641 localeStrings.CONFIRM_LI_ALERT, [
2642 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2643 "title", "lineitem_marc_attr_definition"
2645 /* XXX it's really better add a parameter and to adjust
2646 * the format string rather than do this concatenation
2647 * here, but if someone wants this for 2.2 in a hurry,
2648 * we can sidestep the problem of updating the strings
2649 * while the translators are working. */
2651 aou.findOrgUnit(lin.alert_text().owning_lib()).shortname() +
2653 lin.alert_text().code()
2655 lin.alert_text().description() || "",
2662 this.checkLiAlerts = function(li_id) {
2663 var li = this.liCache[li_id];
2665 var alert_notes = li.lineitem_notes().filter(
2666 function(o) { return Boolean(o.alert_text()); }
2669 /* this is _intentionally_ not done in a call to forEach() ... */
2670 for (var i = 0; i < alert_notes.length; i++) {
2671 if (this.noteAcks[alert_notes[i].id()])
2673 else if (!this._confirmAlert(li, alert_notes[i]))
2676 this.noteAcks[alert_notes[i].id()] = true;
2682 this.deleteCopy = function(row) {
2683 var copy = this.copyCache[row.getAttribute('copy_id')];
2684 copy.isdeleted(true);
2686 delete this.copyCache[copy.id()];
2687 this.copyTbody.removeChild(row);
2690 this._virtDfaCountsAsList = function() {
2692 for (var key in this.virtDfaCounts) {
2693 for (var i = 0; i < this.virtDfaCounts[key]; i++)
2699 this.confirmBreachedCopyFunds = function(copies) {
2700 var stop = 0, warning = 0;
2704 var state = self.fundBalanceState[o.fund()];
2705 if (state[0] /* stop */)
2707 else if (state[1] /* warning */)
2714 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
2715 } else if (warning) {
2716 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
2721 this.saveCopyChanges = function(liId) {
2727 for(var id in this.copyCache) {
2728 var c = this.copyCache[id];
2729 if(!c.isdeleted()) total++;
2730 if(c.isnew() || c.ischanged() || c.isdeleted()) {
2731 if(c.id() < 0) c.id(null);
2737 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
2740 if (copies.length > 0) {
2741 if (!this.confirmBreachedCopyFunds(copies))
2744 if (typeof(this._copy_count_cb) == "function")
2745 this._copy_count_cb(liId, total);
2747 openils.Util.show("acq-lit-update-copies-progress");
2748 fieldmapper.standardRequest(
2749 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
2751 params: [openils.User.authtoken, copies],
2752 onresponse: function(r) {
2753 var res = openils.Util.readResponse(r);
2754 litUpdateCopiesProgress.update(res);
2756 oncomplete: function() {
2757 self.drawCopies(liId, true /* force_fetch */);
2758 openils.Util.hide("acq-lit-update-copies-progress");
2759 refreshPOSummaryAmounts();
2765 var dfa_list = this._virtDfaCountsAsList();
2766 if (dfa_list.length > 0) {
2767 fieldmapper.standardRequest(
2769 "open-ils.acq.distribution_formula.record_application"],
2772 "params": [openils.User.authtoken, dfa_list, liId],
2773 "onresponse": function(r) {
2774 var res = openils.Util.readResponse(r);
2775 if (res && res.length < dfa_list.length)
2776 alert(localeStrings.DFA_NOT_ALL);
2780 this.virtDfaCounts = {};
2783 if (this.inlineCopiesNeedingRefresh.indexOf(liId) < 0)
2784 this.inlineCopiesNeedingRefresh.push(liId);
2787 this._updateCreatePoPrepayCheckbox = function(prepay) {
2788 var prepay = openils.Util.isTrue(prepay);
2789 this._prepayRequiredByVendor = prepay;
2790 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
2793 this._confirmPoPrepaySituation = function() {
2794 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
2795 if (want_prepay != this._prepayRequiredByVendor) {
2798 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
2799 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
2806 this.applySelectedLiAction = function(action) {
2810 case 'delete_selected':
2811 this._deleteLiList(self.getSelected());
2814 case 'add_to_order':
2815 addToPoDialog._get_li = dojo.hitch(
2818 return this.getSelected(
2819 false, null, true, li_pre_po_states);
2822 if (addToPoDialog._get_li().length == 0) {
2823 alert(localeStrings.NO_LI_GENERAL);
2826 addToPoDialog.show();
2829 case 'create_order':
2830 this._loadPOSelect();
2831 acqLitPoCreateDialog.show();
2834 case 'save_picklist':
2835 acqLitSavePlDialog.show();
2838 case 'selector_ready':
2840 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
2841 acqLitChangeLiStateDialog.show();
2849 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
2852 case 'batch_create_invoice':
2853 this.batchCreateInvoice();
2856 case 'batch_link_invoice':
2857 this.batchLinkInvoice();
2860 case 'receive_lineitems':
2861 this.receiveSelectedLineitems();
2864 case 'rollback_receive_lineitems':
2865 this.rollbackReceiveLineitems();
2868 case 'create_assets':
2869 this.showAssetCreator();
2872 case 'export_attr_list':
2873 this.chooseExportAttr();
2876 case 'batch_apply_funds':
2877 this.applyBatchLiFunds();
2880 case 'add_brief_record':
2882 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
2884 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
2888 case "cancel_lineitems":
2889 console.log('HERE');
2890 this.maybeCancelLineitems();
2893 case "apply_claim_policy":
2894 var li_list = this.getSelected();
2895 this.claimPolicyPicker.attr("value", null);
2896 liClaimPolicyDialog.show();
2897 liClaimPolicySave.onClick = function() {
2898 self.changeClaimPolicy(
2900 self.claimPolicyPicker.attr("value"),
2904 self.setClaimPolicyControl(li);
2905 self.reconsiderClaimControl(li);
2908 liClaimPolicyDialog.hide();
2916 this.changeClaimPolicy = function(li_list, value, callback) {
2918 function(li) { li.claim_policy(value); }
2920 fieldmapper.standardRequest(
2921 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
2922 "params": [openils.User.authtoken, li_list],
2924 "oncomplete": function(r) {
2925 r = openils.Util.readResponse(r);
2926 if (callback) callback(r);
2932 this.showAssetCreator = function(onAssetsCreated) {
2933 if(!this.isPO) return;
2936 // first, let's see if this PO has any LI's that need to be merged/imported
2937 self.pcrud.search('jub', {purchase_order : this.isPO, eg_bib_id : null}, {
2939 oncomplete : function(r) {
2940 var resp = openils.Util.readResponse(r);
2941 if (resp && resp.length) {
2942 // PO has some non-linked jubs.
2944 self.show('asset-creator');
2945 if(!self.vlAgent.loaded)
2946 self.vlAgent.init();
2948 dojo.connect(assetCreatorButton, 'onClick',
2949 function() { self.createAssets(onAssetsCreated) });
2953 // all jubs linked, move on to asset creation
2954 self.createAssets(onAssetsCreated, true);
2960 this.createAssets = function(onAssetsCreated, noVl) {
2961 this.show('acq-lit-progress-numbers');
2963 var vlArgs = (noVl) ? {} : {vandelay : this.vlAgent.values()};
2964 this.batchProgress = {};
2965 progressDialog.show(false);
2966 progressDialog.attr("title", localeStrings.LI_CREATING_ASSETS);
2967 fieldmapper.standardRequest(
2968 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
2970 params: [this.authtoken, this.isPO, vlArgs],
2971 onresponse: function(r) {
2972 var resp = openils.Util.readResponse(r);
2973 self._updateProgressNumbers(resp, !Boolean(onAssetsCreated), onAssetsCreated, true);
2979 this.maybeCancelLineitems = function() {
2980 openils.Util.show("acq-lit-cancel-reason", "inline");
2981 if (!acqLitCancelLineitemsButton._prepared) {
2982 var widget = new openils.widget.AutoFieldWidget({
2983 "fmField": "cancel_reason",
2985 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
2986 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2988 "searchOptions" : {order_by : {"acqcr":"label"}}
2992 acqLitCancelLineitemsButton.onClick = function() {
2993 if (w.attr("value")) {
2994 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
2995 self._cancelLineitems(w.attr("value"));
2997 openils.Util.hide("acq-lit-cancel-reason");
3000 acqLitCancelLineitemsButton._prepared = true;
3006 this._cancelLineitems = function(reason) {
3008 var li_list = this.getSelected();
3010 // canceled lineitems may be canceled again if they were
3011 // previously delayed (keep_debits = true).
3012 li_list = li_list.filter(
3015 li.state() != 'cancelled' ||
3016 li.cancel_reason().keep_debits() == 't'
3021 id_list = li_list.map(function(l) {return l.id()});
3023 if (!id_list.length) {
3024 alert(localeStrings.NO_LI_GENERAL);
3027 fieldmapper.standardRequest(
3028 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
3029 "params": [openils.User.authtoken, id_list, reason],
3031 "onresponse": function(r) {
3032 if (r = openils.Util.readResponse(r)) {
3034 for (var id in r.li) {
3035 self.liCache[id].state(r.li[id].state);
3036 self.liCache[id].cancel_reason(
3037 r.li[id].cancel_reason
3039 self.updateLiState(self.liCache[id]);
3042 if (r.lid && self.copyCache) {
3043 for (var id in r.lid) {
3044 if (self.copyCache[id]) {
3045 self.copyCache[id].cancel_reason(
3046 r.lid[id].cancel_reason
3048 self.updateLidState(self.copyCache[id]);
3058 this.chooseExportAttr = function() {
3059 if (!acqLitExportAttrSelector._li_setup) {
3061 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
3063 "data": acqlimad.toStoreData(
3065 "acqlimad", {"code": li_exportable_attrs}
3070 acqLitExportAttrSelector.setValue();
3071 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
3072 acqLitExportAttrSelector._li_setup = true;
3074 openils.Util.show("acq-lit-export-attr-holder", "inline");
3077 this.exportAttrList = function() {
3078 var attr_def = acqLitExportAttrSelector.item;
3079 var li_list = this.getSelected();
3080 var value_list = li_list.map(
3082 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
3083 attr_def.code, "lineitem_marc_attr_definition"
3086 ).filter(function(attr) { return Boolean(attr); });
3088 if (value_list.length > 0) {
3089 if (value_list.length < li_list.length) {
3091 dojo.string.substitute(
3092 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
3099 openils.XUL.contentToFileSaveDialog(
3100 value_list.join("\n"),
3101 localeStrings.EXPORT_SAVE_DIALOG_TITLE
3107 alert(dojo.string.substitute(
3108 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
3112 openils.Util.hide("acq-lit-export-attr-holder");
3115 this.printPO = function() {
3116 if(!this.isPO) return;
3117 progressDialog.show(true);
3118 fieldmapper.standardRequest(
3119 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
3121 params: [this.authtoken, this.isPO, 'html'],
3122 oncomplete: function(r) {
3123 progressDialog.hide();
3124 var evt = openils.Util.readResponse(r);
3125 if(evt && evt.template_output()) {
3126 openils.Util.printHtmlString(evt.template_output().data());
3133 this.batchCreateInvoice = function() {
3134 var liIds = this.getSelected(
3135 false, null, true /* id_list */, li_active_states)
3136 if (!liIds.length) {
3137 alert(localeStrings.NO_LI_GENERAL);
3140 var path = oilsBasePath + '/acq/invoice/view?create=1';
3141 dojo.forEach(liIds, function(li, idx) { path += '&attach_li=' + li });
3142 if (openils.XUL.isXUL())
3143 openils.XUL.newTabEasy(path, localeStrings.NEW_INVOICE, null, true);
3145 location.href = path;
3148 this.batchLinkInvoice = function(create) {
3149 var liIds = this.getSelected(
3150 false, null, true /* id_list */, li_active_states)
3151 if (!liIds.length) {
3152 alert(localeStrings.NO_LI_GENERAL);
3155 if (!self.invoiceLinkDialogManager) {
3156 self.invoiceLinkDialogManager =
3157 new InvoiceLinkDialogManager("li");
3159 self.invoiceLinkDialogManager.target = liIds;
3160 acqLitLinkInvoiceDialog.show();
3163 this.receiveSelectedLineitems = function() {
3164 var states = li_post_po_states.filter(
3165 function(s) { return s != 'received' });
3166 var li_list = this.getSelected(null, null, null, states);
3168 if (!li_list.length) {
3169 alert(localeStrings.NO_LI_GENERAL);
3173 for (var i = 0; i < li_list.length; i++) {
3174 var li = li_list[i];
3176 if (li.state() != "received" &&
3177 !this.checkLiAlerts(li.id())) return;
3180 this.show('acq-lit-progress-numbers');
3183 fieldmapper.standardRequest(
3184 ['open-ils.acq', 'open-ils.acq.lineitem.receive.batch'],
3188 li_list.map(function(li) { return li.id(); })
3190 onresponse : function(r) {
3191 var resp = openils.Util.readResponse(r);
3192 self._updateProgressNumbers(resp, true);
3198 this.issueReceive = function(obj, rollback) {
3200 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
3202 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
3204 progressDialog.show(true);
3205 fieldmapper.standardRequest(
3206 ["open-ils.acq", method], {
3208 "params": [this.authtoken, obj.id()],
3209 "onresponse": function(r) {
3210 if (r = openils.Util.readResponse(r)) {
3211 self.fetchClaimInfo(
3212 part == "lineitem" ? obj.id() : obj.lineitem(),
3214 function() { self.handleReceive(r); }
3216 progressDialog.hide();
3224 * Handles the responses from receive and rollback ML calls.
3226 this.handleReceive = function(resp) {
3229 for (var li_id in resp.li) {
3230 for (var key in resp.li[li_id])
3231 self.liCache[li_id][key](resp.li[li_id][key]);
3232 self.updateLiState(self.liCache[li_id]);
3236 if (typeof(self.poUpdateCallback) == "function")
3237 self.poUpdateCallback(resp.po);
3240 for (var lid_id in resp.lid) {
3241 for (var key in resp.lid[lid_id])
3242 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
3243 self.updateLidState(self.copyCache[lid_id]);
3249 this.rollbackReceiveLineitems = function() {
3250 var li_id_list = this.getSelected(false, null, true);
3251 if (!li_id_list.length) {
3252 alert(localeStrings.NO_LI_GENERAL);
3256 if (!confirm(localeStrings.ROLLBACK_LI_RECEIVE_CONFIRM)) return;
3258 this.show('acq-lit-progress-numbers');
3261 fieldmapper.standardRequest(
3262 ['open-ils.acq', 'open-ils.acq.lineitem.receive.rollback.batch'],
3264 params: [this.authtoken, li_id_list],
3265 onresponse : function(r) {
3266 var resp = openils.Util.readResponse(r);
3267 self._updateProgressNumbers(resp, true);
3273 this._updateProgressNumbers = function(resp, reloadOnComplete, onComplete, clearProgressDialog) {
3274 this._updateProgressDialog(resp);
3275 this.vlAgent.handleResponse(resp,
3276 function(resp, res) {
3277 if (clearProgressDialog) {
3278 progressDialog.update({ "progress": 100});
3279 progressDialog.update_message();
3280 progressDialog.hide();
3281 progressDialog.attr("title", "");
3283 if(reloadOnComplete)
3284 location.href = location.href;
3286 onComplete(resp, res);
3291 this._updateProgressDialog = function(resp) {
3292 progressDialog.update({ "progress": (resp.progress / resp.total) * 100 });
3293 var keys = ['li', 'vqbr', 'bibs', 'lid', 'debits_accrued', 'copies'];
3294 for (var i = 0; i < keys.length; i++) {
3295 if (resp[keys[i]] > (this.batchProgress[keys[i]] || 0)) {
3296 progressDialog.update_message(
3297 dojo.string.substitute(
3298 localeStrings["ACTIVATE_" + keys[i].toUpperCase() + "_PROCESSED"],
3304 this.batchProgress = resp;
3307 this._createPO = function(fields) {
3308 var wantall = (fields.create_from == "all");
3310 /* If we're a picklist or purchase order already and the user wants
3311 * all lineitems, we might have pages' worth of lineitems haven't all
3312 * been loaded yet, so getSelected() won't find them. The server,
3313 * however, should know about all our lineitems, so let's ask the
3314 * server for a complete list.
3319 true, function(list) {
3320 self._createPOFromLineitems(fields, list);
3321 }, /* id_list */ true, li_pre_po_states
3324 this._createPOFromLineitems(
3325 fields, this.getSelected(
3326 false, null, true /* id_list */, li_pre_po_states)
3331 this._createPOFromLineitems = function(fields, selected) {
3332 if (selected.length == 0) {
3333 alert(localeStrings.NO_LI_GENERAL);
3338 var po = new fieldmapper.acqpo();
3339 po.provider(this.createPoProviderSelector.attr("value"));
3340 po.ordering_agency(this.createPoAgencySelector.attr("value"));
3341 po.prepayment_required(fields.prepayment_required[0] ? true : false);
3342 var name = this.createPoNameInput.attr('value');
3343 if (name) po.name(name); // avoid name=""
3345 // if we're creating assets, delay the asset creation
3346 // until after the PO is created. This will allow us to
3347 // use showAssetCreator() directly.
3349 fieldmapper.standardRequest(
3350 ["open-ils.acq", "open-ils.acq.purchase_order.create"],
3353 openils.User.authtoken,
3354 po, {lineitems : selected}
3356 onresponse : function(r) {
3357 var resp = openils.Util.readResponse(r);
3358 if (resp.complete) {
3359 // self.isPO is needed for showAssetCreator();
3360 self.isPO = resp.purchase_order.id();
3361 var redir = oilsBasePath + "/acq/po/view/" + self.isPO;
3362 if (fields.create_assets[0]) {
3363 self.showAssetCreator(
3364 function() {location.href = redir}
3367 location.href = redir;
3376 this.batchFundWidget = null;
3378 this.applyBatchLiFunds = function() {
3380 var liIds = this.getSelected().map(function(li) { return li.id(); });
3381 if(liIds.length == 0) return; // warn?
3384 batchFundUpdateDialog.show();
3386 if(!this.batchFundWidget) {
3387 this.batchFundWidget = new openils.widget.AutoFieldWidget({
3389 selfReference : true,
3390 labelFormat : fundLabelFormat,
3391 searchFormat : fundSearchFormat,
3392 searchFilter : fundSearchFilter,
3393 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
3394 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
3395 dijitArgs : { "required": true, "labelType": "html" },
3398 this.batchFundWidget.build();
3401 dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
3402 dojo.connect(batchFundUpdateSubmit, 'onClick',
3405 // TODO: call .dry_run first to test thresholds
3406 fieldmapper.standardRequest(
3407 ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
3410 openils.User.authtoken,
3412 self.batchFundWidget.widget.attr('value')
3414 oncomplete : function(r) {
3415 var resp = openils.Util.readResponse(r);
3417 location.href = location.href;
3426 this._deleteLiList = function(list, idx) {
3427 if(idx == null) idx = 0;
3428 if(idx >= list.length) return;
3433 if (this.isPO && (li.state() == "on-order" || li.state() == "received")) {
3434 /* It makes little sense to delete a lineitem from a PO that has
3435 * already been marked 'on-order'. Especially if EDI is in use,
3436 * such a purchase order will probably have already been shipped
3437 * off to a vendor, and mucking with it at this point could leave
3438 * your data in a bad state that doesn't jive with reality.
3440 * I could see making this restriction even firmer.
3442 * I could also see adjusting the li state comparisons, extending
3443 * the comparison to the PO's state, and/or providing functions
3444 * that house the logic for comparing states in a single location.
3446 * Yes, this will be really annoying if you have selected a lot
3447 * of lineitems to cancel that have been ordered. You'll get a
3448 * confirm dialog for each one.
3451 if (!confirm(localeStrings.DEL_LI_FROM_PO)) {
3452 self._deleteLiList(list, ++idx); /* move on to next in list */
3457 fieldmapper.standardRequest(
3459 this.isPO ? 'open-ils.acq.purchase_order.lineitem.delete' : 'open-ils.acq.picklist.lineitem.delete'],
3461 params: [openils.User.authtoken, liId],
3462 oncomplete: function(r) {
3463 self.removeLineitem(liId);
3464 self._deleteLiList(list, ++idx);
3470 this.editOrderMarc = function(li) {
3472 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
3473 to true in about:config */
3475 if(openils.XUL.isXUL()) {
3476 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul','','chrome');
3478 win = window.open('/xul/server/cat/marcedit.xul','','chrome');
3482 record : {marc : li.marc(), "rtype": "bre"},
3484 label: 'Save Record', // XXX I18N
3485 func: function(xmlString) {
3487 fieldmapper.standardRequest(
3488 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
3490 params: [openils.User.authtoken, li],
3491 oncomplete: function(r) {
3492 openils.Util.readResponse(r);
3494 self.drawInfo(li.id())
3500 'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
3501 'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
3505 this._savePl = function(values) {
3507 (values.which == 'all'),
3508 function(list) { self._savePlFromLineitems(values, list); }
3512 this._savePlFromLineitems = function(values, selected) {
3513 openils.Util.show("acq-lit-generic-progress");
3515 if(values.new_name) {
3516 openils.acq.Picklist.create(
3517 {name: values.new_name},
3523 oilsBasePath + "/acq/picklist/view/" + id;
3528 } else if(values.existing_pl) {
3529 // update lineitems to use an existing picklist
3531 values.existing_pl, selected, 0,
3534 oilsBasePath + "/acq/picklist/view/" +
3541 this._updateLiState = function(values, state, state_filter) {
3542 progressDialog.show(true);
3544 (values.which == 'all'),
3546 self._updateLiStateFromLineitems(values, state, list);
3547 }, false /* id_list */, state_filter
3551 this._updateLiStateFromLineitems = function(values, state, selected) {
3552 if(!selected.length) {
3553 try { progressDialog.hide() } catch(E) {};
3554 alert(localeStrings.NO_LI_GENERAL);
3557 dojo.forEach(selected, function(li) {li.state(state);});
3558 self._updateLiList(null, selected, 0,
3559 // TODO consider inline updates for efficiency
3560 function() { location.href = location.href }
3564 this._updateLiList = function(pl, list, idx, oncomplete) {
3565 if(idx >= list.length) return oncomplete();
3567 if(pl != null) li.picklist(pl);
3568 litGenericProgress.update({maximum: list.length, progress: idx});
3569 new openils.acq.Lineitem({lineitem:li}).update(
3571 self._updateLiList(pl, list, ++idx, oncomplete);
3576 this._loadPOSelect = function() {
3577 if (!this.createPoProviderSelector) {
3578 var widget = new openils.widget.AutoFieldWidget({
3579 "fmField": "provider",
3581 "searchFilter": {"active": "t"},
3582 "parentNode": dojo.byId("acq-lit-po-provider"),
3584 "onChange": function() {
3586 self._updateCreatePoPrepayCheckbox(
3587 this.item.prepayment_required()
3593 widget.build(function(w) { self.createPoProviderSelector = w; });
3596 this.createPoCheckDupes = function() {
3597 var org = self.createPoAgencySelector.attr('value');
3598 var name = self.createPoNameInput.attr('value');
3599 openils.Util.hide('acq-dupe-po-name');
3602 acqLitCreatePoSubmit.attr('disabled', false);
3606 acqLitCreatePoSubmit.attr('disabled', true);
3607 var orgs = fieldmapper.aou.descendantNodeList(org, true);
3608 new openils.PermaCrud().search('acqpo',
3609 {name : name, ordering_agency : orgs},
3610 {async : true, oncomplete : function(r) {
3611 var po = openils.Util.readResponse(r);
3613 if (po && (po = po[0])) {
3615 var link = dojo.byId('acq-dupe-po-link');
3616 openils.Util.show('acq-dupe-po-name', 'table-row');
3617 var dupe_path = '/acq/po/view/' + po.id();
3621 if (window.IAMBROWSER) {
3622 // TODO: integration
3626 link.onclick = function() {
3628 var loc = xulG.url_prefix('XUL_BROWSER?url=') +
3629 window.encodeURIComponent(
3630 xulG.url_prefix('EG_WEB_BASE' + dupe_path)
3634 {tab_name: '', browser:false},
3637 show_nav_buttons : true,
3638 show_print_button : true,
3645 link.onclick = function() {
3646 window.open(oilsBasePath + dupe_path, '_blank').focus();
3651 acqLitCreatePoSubmit.attr('disabled', false);
3657 if (!this.createPoAgencySelector) {
3658 var widget = new openils.widget.AutoFieldWidget({
3659 "fmField": "ordering_agency",
3661 "parentNode": dojo.byId("acq-lit-po-agency"),
3662 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3664 widget.build(function(w) {
3665 self.createPoAgencySelector = w;
3666 dojo.connect(w, 'onChange', self.createPoCheckDupes);
3670 if (!this.createPoNameInput) {
3671 var widget = new openils.widget.AutoFieldWidget({
3674 "parentNode": dojo.byId("acq-lit-po-name"),
3675 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3677 widget.build(function(w) {
3678 self.createPoNameInput = w;
3679 dojo.connect(w, 'onChange', self.createPoCheckDupes);
3684 this.showRealCopyEditUI = function(li) {
3689 this._fetchLineitem(li.id(),
3691 li = self.liCache[li.id()] = fullLi;
3695 id : li.lineitem_details().map(
3696 function(item) { return item.eg_copy_id() }
3700 oncomplete : function(r) {
3702 var r_list = openils.Util.readResponse( r );
3703 for (var i = 0; i < r_list.length; i++) {
3704 var copy = r_list[i];
3705 var volId = copy.call_number();
3706 var volume = self.volCache[volId];
3708 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
3710 copy.call_number(volume);
3711 copyList.push(copy);
3714 xulG.volume_item_creator( { 'existing_copies' : copyList } );
3717 alert('error in oncomplete: ' + E);
3726 this.drawBibFinder = function(li) {
3729 var liWrapper = new openils.acq.Lineitem({lineitem:li});
3732 ['isbn', 'upc', 'issn', 'title', 'author'],
3734 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
3736 if(field == 'title' || field == 'author') {
3737 query += field +':' + val + ' ';
3739 query += 'identifier|' + field + ':' + val + ' ';
3746 oilsBasePath + '/acq/lineitem/findbib?query=' + encodeURIComponent(query),
3747 '', 'resizable,scrollbars=1,chrome');
3749 win.window.recordFound = function(bibId) {
3752 var attrs = li.attributes();
3753 li.attributes(null);
3754 li.eg_bib_id(bibId);
3756 fieldmapper.standardRequest(
3757 ["open-ils.acq", "open-ils.acq.lineitem.update"],
3759 "params": [openils.User.authtoken, li],
3761 "oncomplete": function(r) {
3762 if(openils.Util.readResponse(r)) {
3763 location.href = location.href;