1 dojo.require('dojo.date.locale');
2 dojo.require('dojo.date.stamp');
3 dojo.require('dijit.form.Button');
4 dojo.require('dijit.form.TextBox');
5 dojo.require('dijit.form.FilteringSelect');
6 dojo.require('dijit.form.Textarea');
7 dojo.require('dijit.Tooltip');
8 dojo.require('dijit.ProgressBar');
9 dojo.require('dojox.timing.doLater');
10 dojo.require('openils.acq.Lineitem');
11 dojo.require('openils.acq.PO');
12 dojo.require('openils.acq.Picklist');
13 dojo.require('openils.widget.AutoFieldWidget');
14 dojo.require('dojo.data.ItemFileReadStore');
15 dojo.require('openils.widget.ProgressDialog');
16 dojo.require('openils.PermaCrud');
17 dojo.require("openils.widget.PCrudAutocompleteBox");
18 dojo.require('dijit.form.ComboBox');
19 dojo.require('openils.CGI');
21 if (!localeStrings) { /* we can do this because javascript doesn't have block scope */
22 dojo.requireLocalization('openils.acq', 'acq');
23 var localeStrings = dojo.i18n.getLocalization('openils.acq', 'acq');
25 const XUL_OPAC_WRAPPER = 'chrome://open_ils_staff_client/content/cat/opac.xul';
26 var li_exportable_attrs = ["issn", "isbn", "upc"];
28 var fundLabelFormat = [
29 '<span class="fund_${0}">${1} (${2})</span>', 'id', 'code', 'year'
31 var fundSearchFormat = ['${0} (${1})', 'code', 'year'];
32 var fundSearchFilter = {active : 't'};
34 function nodeByName(name, context) {
35 return dojo.query('[name='+name+']', context)[0];
38 // for caching linked users. e.g. lineitem_detail.receiver
41 var liDetailBatchFields = ['fund', 'owning_lib', 'location', 'collection_code', 'circ_modifier', 'cn_label'];
42 var liDetailFields = liDetailBatchFields.concat(['barcode', 'note']);
44 "stop": "color: #c00; font-weight: bold;",
45 "warning": "color: #c93;"
49 * We're not using 'approved' today, but there is API support for it.
50 * I believe it's been replaced by "order-ready".
51 * LIs go new => selector-ready => order-ready/approved => pending-order =>
52 * on-order => received. 'cancelled' can pop up anywhere.
55 var li_pre_po_states = ["new", "selector-ready", "order-ready", "approved"];
56 var li_post_po_states = ["pending-order", "on-order", "received", "cancelled"];
57 var li_active_states = li_pre_po_states.concat(li_post_po_states);
59 function AcqLiTable() {
66 this.haveFundClass = {}
67 this.fundBalanceState = {};
68 this.realDfaCache = {};
69 this.virtDfaCounts = {};
72 this.claimEligibleLidByLi = {};
73 this.claimEligibleLid = {};
74 this.toggleState = false;
75 this.tbody = dojo.byId('acq-lit-tbody');
78 this.authtoken = openils.User.authtoken;
79 this.pcrud = new openils.PermaCrud();
80 this.rowTemplate = this.tbody.removeChild(dojo.byId('acq-lit-row'));
81 this.copyTbody = dojo.byId('acq-lit-li-details-tbody');
82 this.copyRow = this.copyTbody.removeChild(dojo.byId('acq-lit-li-details-row'));
83 this.copyBatchRow = dojo.byId('acq-lit-li-details-batch-row');
84 this.copyBatchWidgets = {};
85 this.liNotesTbody = dojo.byId('acq-lit-notes-tbody');
86 this.liNotesRow = this.liNotesTbody.removeChild(dojo.byId('acq-lit-notes-row'));
87 this.realCopiesTbody = dojo.byId('acq-lit-real-copies-tbody');
88 this.realCopiesRow = this.realCopiesTbody.removeChild(dojo.byId('acq-lit-real-copies-row'));
89 this._copy_fields_for_acqdf = ['owning_lib', 'location', 'fund', 'circ_modifier', 'collection_code'];
90 this.skipInitialEligibilityCheck = false;
91 this.claimDialog = new ClaimDialogManager(
92 liClaimDialog, finalClaimDialog, this.claimEligibleLidByLi,
93 function(li) { /* callback that fires when claims are made */
94 self.fetchClaimInfo(li.id(), /* force update */ true);
97 this.vlAgent = new VLAgent();
98 this.batchProgress = {};
100 if (dojo.byId('acq-lit-apply-idents')) {
101 dojo.byId('acq-lit-apply-idents').onclick = function() {
102 self.applyOrderIdentValues();
106 this.focusLineitem = new openils.CGI().param('focus_li');
108 // capture the inline copy display wrapper and row template
109 this.inlineCopyContainer =
110 this.tbody.removeChild(dojo.byId('acq-inline-copies-row'));
112 '[name=acq-li-inline-copies-tbody]', this.inlineCopyContainer)[0];
113 this.inlineCopyTemplate = tb.removeChild(
114 dojo.query('[name=acq-li-inline-copies-template]', tb)[0]);
115 this.inlineNoCopies = tb.removeChild(
116 dojo.query('[name=acq-li-inline-copies-none]', tb)[0]);
118 // list of LI IDs that should be refreshed at next display time
119 this.inlineCopiesNeedingRefresh = [];
121 dojo.byId("acq-lit-li-actions-selector").onchange = function() {
122 self.applySelectedLiAction(this.options[this.selectedIndex].value);
123 this.selectedIndex = 0;
126 acqLitCreatePoCancel.onClick = function() {
127 acqLitPoCreateDialog.hide();
129 acqLitCreatePoSubmit.onClick = function() {
130 if (!self.createPoProviderSelector.attr("value") ||
131 !self.createPoAgencySelector.attr("value")) {
132 alert(localeStrings.CREATE_PO_INVALID);
134 } else if (self._confirmPoPrepaySituation()) {
135 acqLitPoCreateDialog.hide();
136 self._createPO(acqLitPoCreateDialog.getValues());
142 acqLitSavePlButton.onClick = function() {
143 acqLitSavePlDialog.hide();
144 self._savePl(acqLitSavePlDialog.getValues());
147 acqLitCancelLiStateButton.onClick = function() {
148 acqLitChangeLiStateDialog.hide();
150 acqLitSaveLiStateButton.onClick = function() {
151 acqLitChangeLiStateDialog.hide();
152 var state = acqLitChangeLiStateDialog.attr('state');
153 var state_filter = ['new'];
154 if (state == 'order-ready')
155 state_filter.push('selector-ready');
157 acqLitChangeLiStateDialog.getValues(), state, state_filter);
161 dojo.byId('acq-lit-select-toggle').onclick = function(){self.toggleSelect()};
162 dojo.byId('acq-inline-copies-toggle').onclick = function(){self.toggleInlineCopies()};
163 dojo.byId('acq-lit-info-back-button').onclick = function(){self.show('list')};
164 dojo.byId('acq-lit-copies-back-button').onclick = function(){self.show('list')};
165 dojo.byId('acq-lit-notes-back-button').onclick = function(){self.show('list')};
166 dojo.byId('acq-lit-real-copies-back-button').onclick = function(){self.show('list')};
168 this.setFundSearchFilter = function(callback) {
169 new openils.User().getPermOrgList(
170 ['CREATE_PURCHASE_ORDER', 'MANAGE_FUND'],
172 fundSearchFilter.org = orgs;
173 if (callback) callback();
175 true, true // descendants, id_list
179 this.afwCopyFieldArgs = function(field, perms) {
183 "labelFormat": (field == 'fund') ? fundLabelFormat : null,
184 "searchFormat": (field == 'fund') ? fundSearchFormat : null,
185 "searchFilter": (field == 'fund') ? fundSearchFilter : null,
186 "orgLimitPerms": (field == 'location') ? ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'] : [perms],
189 "labelType": (field == "fund") ? "html" : null
191 "noCache": (field == "fund"),
196 /* This is the "new" batch updater that sits atop all lineitems. It does
197 * use this.afwCopyFieldArgs() to borrow a little common code from the
198 * "old" batch updater atop the copy details view. */
199 this.initBatchUpdater = function(disabled_fields) {
200 openils.Util.show("acq-batch-update", "table");
202 if (!dojo.isArray(disabled_fields)) disabled_fields = [];
204 /* Note that this will directly contain dijits, not the AutoWidget
206 this.batchUpdateWidgets = {};
208 this.batchUpdateWidgets.item_count = new dijit.form.TextBox(
210 "style": {"width": "3em"},
212 dojo.indexOf(disabled_fields, "item_count") != -1
218 (new openils.widget.AutoFieldWidget({
220 "selfReference": true,
221 "dijitArgs": { "required": false },
223 "parentNode": "acq-bu-distribution_formula"
226 dojo.style(w.domNode, {"width": "12em"});
227 /* dijitArgs to AutoFieldWidget won't work for 'disabled' */
230 dojo.indexOf(disabled_fields, "distribution_formula") != -1
232 self.batchUpdateWidgets.distribution_formula = w;
236 function buildOneBatchWidget(field, args) {
237 (new openils.widget.AutoFieldWidget(args)).build(
239 if (field == "fund") {
241 w, "onChange", function(val) {
242 self._updateFundSelectorStyle(aw, val);
246 self._ensureCSSFundClasses(w.store);
249 dojo.style(w.domNode, {"width": "10em"});
252 dojo.indexOf(disabled_fields, field) != -1
254 self.batchUpdateWidgets[field] = w;
260 ["owning_lib","location","collection_code","circ_modifier","fund"],
262 var args = self.afwCopyFieldArgs(field,"CREATE_PURCHASE_ORDER");
263 args.parentNode = dojo.byId("acq-bu-" + field);
265 if (field == 'fund') {
266 // The list of funds can be huge. Before fetching
267 // funds for PO modification, see where the user has
268 // perms and limit the retreived funds accordingly.
269 // Note: This is the first instance of fund list
270 // retrieval. All future fund list retrievals will
271 // benefit directly from having applied the fund
272 // search filter org units here.
273 self.setFundSearchFilter(function() {
274 buildOneBatchWidget(field, args);
279 buildOneBatchWidget(field, args);
283 acqBatchUpdateApply.onClick = function() {
284 var li_id_list = self.getSelected(false, null, true /* id list */);
285 if (!li_id_list.length) {
286 alert(localeStrings.NO_LI_TO_UPDATE);
290 progressDialog.show(true);
291 progressDialog.attr("title", localeStrings.LI_BATCH_UPDATE);
292 progressDialog.update({"maximum": li_id_list.length,"progress": 0});
296 var params = [ self.authtoken, {"lineitems": li_id_list},
297 self.batchUpdateChanges(), self.batchUpdateFormula() ];
298 console.log("batch update params: " + dojo.toJson(params));
300 fieldmapper.standardRequest(
301 ["open-ils.acq", "open-ils.acq.lineitem.batch_update"], {
304 "onresponse": function(r) {
305 if ((r = openils.Util.readResponse(r))) { // assignment
306 progressDialog.update({"progress": ++count});
308 progressDialog.hide();
309 progressDialog.attr("title", "");
312 "oncomplete": function() {
313 /* XXX Is the last call to onresponse guaranteed to
314 * finish before oncomplete is fired? */
315 if (count != li_id_list.length) {
316 console.error("lineitem batch update operation failed");
317 progressDialog.hide();
318 progressDialog.attr("title", "");
320 location.href = location.href;
328 this.batchUpdateChanges = function() {
332 openils.Util.objectProperties(this.batchUpdateWidgets),
334 if (k == "distribution_formula") return; /* handled elsewhere */
335 if (self.batchUpdateWidgets[k].attr("disabled")) return;
337 /* It's important that a value of "" should mean that a field
338 * doesn't get used in the arguments to the batch updater API,
339 * but 0 should mean an actual 0. */
340 var value = self.batchUpdateWidgets[k].attr("value");
349 this.batchUpdateFormula = function() {
350 if (this.batchUpdateWidgets.distribution_formula.attr("disabled")) {
354 this.batchUpdateWidgets.distribution_formula.attr("value") ||
360 this.reset = function(keep_selectors) {
361 while(self.tbody.childNodes[0])
362 self.tbody.removeChild(self.tbody.childNodes[0]);
370 this.setNext = function(handler) {
371 var link = dojo.byId('acq-lit-next');
373 dojo.style(link, 'visibility', 'visible');
374 link.onclick = handler;
376 dojo.style(link, 'visibility', 'hidden');
380 this.setPrev = function(handler) {
381 var link = dojo.byId('acq-lit-prev');
383 dojo.style(link, 'visibility', 'visible');
384 link.onclick = handler;
386 dojo.style(link, 'visibility', 'hidden');
390 this.enableActionsDropdownOptions = function(mask) {
391 /* 'mask' is probably a misnomer the way I'm using it, but it needs to
392 * be one of pl,po,ao,gs,vp, or fs. */
393 dojo.query("option", "acq-lit-li-actions-selector").forEach(
395 var opt_mask = dojo.attr(option, "mask");
397 /* For each <option> element, an empty or non-existent mask
398 * attribute, a mask attribute of "*", or a mask attribute that
399 * matches this method's argument should result in that
400 * option's being enabled. */
402 option, "disabled", !(
405 opt_mask.search(mask) != -1
413 * Ensures this.focusLineitem is in view and causes a brief
414 * border around the lineitem to come to life then fade.
416 this.focusLi = function() {
417 if (!this.focusLineitem) return;
419 // set during addLineitem()
420 var node = dojo.byId('li-title-ref-' + this.focusLineitem);
422 // LI may not yet be rendered
425 // prevent numerous re-focuses
426 this.focusLineitem = null;
428 // causes the full row to be visible
429 dijit.scrollIntoView(node);
432 dojo.query('[attr=title]', node)[0].focus();
434 dojo.require('dojox.fx');
438 dojox.fx.highlight({color : '#BB4433', node : node, duration : 2000}).play();
443 this.show = function(div) {
444 openils.Util.hide('acq-lit-table-div');
445 openils.Util.hide('acq-lit-info-div');
446 openils.Util.hide('acq-lit-li-details');
447 openils.Util.hide('acq-lit-notes-div');
448 openils.Util.hide('acq-lit-real-copies-div');
449 openils.Util.hide('acq-lit-asset-creator');
452 openils.Util.show('acq-lit-table-div');
454 this.refreshInlineCopies();
457 openils.Util.show('acq-lit-info-div');
460 openils.Util.show('acq-lit-li-details');
463 openils.Util.show('acq-lit-real-copies-div');
466 openils.Util.show('acq-lit-notes-div');
468 case 'asset-creator':
469 openils.Util.show('acq-lit-asset-creator');
473 openils.Util.show(div);
477 this.hide = function() {
481 this.toggleSelect = function() {
483 dojo.forEach(self.selectors, function(i){i.checked = false});
485 dojo.forEach(self.selectors, function(i){i.checked = true});
486 self.toggleState = !self.toggleState;
490 this.getAll = function(callback, id_only, state) {
491 /* For some uses of the li table, we may not really know about "all"
492 * the lineitems that the user thinks we know about. If we're a paged
493 * picklist, for example, we only know about the lineitems we've
494 * displayed, but not necessarily all the lineitems on the picklist.
495 * So we reach out to pcrud to inform us.
496 * state: string/array. only lineitems in one of these states are
497 * included in the final result set. Not currently supported for
501 var oncomplete = function(r) {
502 var id_list = openils.Util.readResponse(r);
506 self.fetchLineitemsById(id_list, callback);
510 var search = {"picklist": this.isPL};
511 if (state) search.state = state;
514 "id_list": true, /* sic, even if id_only */
516 "oncomplete": oncomplete
520 } else if (this.isPO) {
521 var search = {"purchase_order": this.isPO};
522 if (state) search.state = state;
527 "oncomplete": oncomplete
531 } else if (this.isUni && this.pager) {
532 this.pager.getAllLineitemIDs(oncomplete);
536 /* If execution reaches this point, we don't need or can't perform
537 * any special tricks to find out the "real" list of "all" lineitems
538 * in this context, so we fall back to the old method.
540 callback(this.getSelected(true, null, id_only, state));
543 /** @param all If true, assume all are selected */
544 this.getSelected = function(
546 callback /* If you want a "good" idea of "all" lineitems, you must
547 provide a callback that accepts an array parameter, rather than
548 relying on the return value of this method itself. */,
552 console.log("getSelected states = " + state);
554 return this.getAll(callback, id_only, state);
556 var indices = {}; /* use to uniqify. needed in paging situations. */
557 dojo.forEach(this.selectors,
560 indices[i.parentNode.parentNode.getAttribute('li')] = true;
564 var result = openils.Util.objectProperties(indices);
566 // caller provided a lineitem state filter. remove IDs for lineitems
567 // not in the selected state.
570 if (!dojo.isArray(state)) state = [state];
571 dojo.forEach(result, function(liId) {
572 console.log('filter LI state ' + self.liCache[liId].state());
573 if (state.indexOf(self.liCache[liId].state()) >= 0)
580 result = result.map(function(liId) { return self.liCache[liId]; });
588 this.setRowAttr = function(td, liWrapper, field, type) {
589 var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
590 td.appendChild(document.createTextNode(val));
593 this.setClaimPolicyControl = function(li, row) {
594 if (!self._claimPolicyPickerLoading) {
595 self._claimPolicyPickerLoading = true;
597 new openils.widget.AutoFieldWidget({
598 "parentNode": "acq-lit-li-claim-policy",
600 "selfReference": true,
601 "dijitArgs": {"required": true}
603 function(w) { self.claimPolicyPicker = w; }
607 /* dojox.timing.doLater() is the best thing ever. Resource not yet
608 * ready? Just repeat my whole method when it is. */
609 if (dojox.timing.doLater(self.claimPolicyPicker)) {
613 row = self._findLiRow(li);
615 if (li.claim_policy()) {
616 /* This Dojo data dance is necessary to get a whole fieldmapper
617 * object based on a claim policy ID, since we alreay have the
618 * widget thing loaded with all that data, and can thereby
619 * avoid another request to the server. */
620 self.claimPolicyPicker.store.fetchItemByIdentity({
621 "identity": li.claim_policy(),
622 "onItem": function(a) {
623 var policy = (new acqclp()).fromStoreItem(a);
624 var span = nodeByName("claim_policy", row);
625 var inner = nodeByName("claim_policy_name", row);
627 openils.Util.show(span, "inline");
628 inner.innerHTML = policy.name();
630 "onError": function(e) {
635 openils.Util.hide(nodeByName("claim_policy", row));
636 nodeByName("claim_policy_name", row).innerHTML = "";
641 this.fetchClaimInfo = function(liId, force, callback, row) {
643 liId, function(full) {
644 self.liCache[full.id()] = full;
645 self.checkClaimEligibility(full, callback, row);
650 // fetch an updated copy of the lineitem
651 // and add it back to the lineitem table
652 this.refreshLineitem = function(li, focus) {
654 this._fetchLineitem(li.id(),
657 self.focusLineitem = li.id();
659 self.focusLineitem = null;
661 var row = dojo.query('[li='+li.id()+']', self.tbody)[0];
662 var nextSibling = row.nextSibling;
663 self.tbody.removeChild(row);
664 self.addLineitem(newLi, false, nextSibling);
670 * Inserts a single lineitem into the growing table of lineitems
671 * @param {Object} li The lineitem object to insert
673 this.addLineitem = function(li, skip_final_placement, nextSibling) {
674 this.liCache[li.id()] = li;
676 // insert the row right away so that final order isn't
677 // dependent on how long subsequent async request take
678 // for a given line item
679 var row = self.rowTemplate.cloneNode(true);
680 if (!skip_final_placement) {
682 // either no nextSibling was provided or it was null
683 // meaning the row was already at the end of the table
684 self.tbody.appendChild(row);
686 self.tbody.insertBefore(row, nextSibling);
690 self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
692 // sort the lineitem notes on edit_time
693 if(!li.lineitem_notes()) li.lineitem_notes([]);
695 var liWrapper = new openils.acq.Lineitem({lineitem:li});
696 row.setAttribute('li', li.id());
697 var tds = dojo.query('[attr]', row);
698 dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
699 dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
701 // so we can scroll to it later
702 dojo.query('[name=bib-info-cell]', row)[0].id = 'li-title-ref-' + li.id();
705 liWrapper.findAttr("isbn", "lineitem_marc_attr_definition") ||
706 liWrapper.findAttr("upc", "lineitem_marc_attr_definition");
708 // XXX media prefix for added content
710 nodeByName("jacket", row).setAttribute(
711 "src", "/opac/extras/ac/jacket/small/" + identifier
715 nodeByName("liid", row).innerHTML += li.id();
717 var exist = nodeByName('li_existing_count', row);
718 fieldmapper.standardRequest(
719 ['open-ils.acq', 'open-ils.acq.lineitem.existing_copies.count'],
721 params: [this.authtoken, li.id()],
722 oncomplete : function(r) {
723 var count = openils.Util.readResponse(r);
724 exist.innerHTML = count;
725 if (Number(count) > 0) {
726 openils.Util.addCSSClass(
727 exist, 'acq-existing-count-warn');
731 label : dojo.string.substitute(
732 localeStrings.LI_EXISTING_COPIES, [count])
739 openils.Util.show(nodeByName('catalog', row), 'inline');
740 nodeByName("catalog_link", row).onclick = this.generateMakeRecTab(li.eg_bib_id());
742 openils.Util.show(nodeByName('link_to_catalog', row), 'inline');
743 nodeByName("link_to_catalog_link", row).onclick = function() { self.drawBibFinder(li) };
746 if (li.queued_record()) {
747 this.pcrud.retrieve('vqbr', li.queued_record(),
749 oncomplete : function(r) {
750 var qrec = openils.Util.readResponse(r);
751 openils.Util.show(nodeByName('queue', row), 'inline');
752 var link = nodeByName("queue_link", row);
753 link.onclick = function() {
754 // open a new tab to the vandelay queue for this record
755 openils.XUL.newTabEasy(
756 oilsBasePath + '/vandelay/vandelay?qtype=bib&qid=' + qrec.queue()
764 nodeByName("worksheet_link", row).href =
765 oilsBasePath + "/acq/lineitem/worksheet/" + li.id() +
766 '?source=' + encodeURIComponent(location.pathname + location.search)
768 nodeByName("show_requests_link", row).href =
769 oilsBasePath + "/acq/picklist/user_request?lineitem=" + li.id() +
770 '?source=' + encodeURIComponent(location.pathname + location.search)
772 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
773 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
774 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
775 dojo.query('[name=expand_inline_copies]', row)[0].onclick =
776 function() {self.drawInlineCopies(li.id())};
779 if (sum = li.order_summary()) { // assignment
780 // Only show the paid label if at least one copy is invoiced.
781 // In other words, a lineitem whose every copy is canceled
783 if (sum.invoice_count() > 0) {
784 if (sum.item_count() == (
785 sum.invoice_count() + sum.cancel_count())) {
786 // Lineitem is fully paid. Display the paid-off label
787 openils.Util.show(nodeByName('paid', row), 'inline');
792 this.drawOrderIdentSelector(li, row);
794 if (!this.skipInitialEligibilityCheck)
798 function(full) { self.setClaimPolicyControl(full, row) },
802 this.updateLiNotesCount(li, row);
804 // show which PO this lineitem is a member of
805 if(li.purchase_order() && !this.isPO) {
807 this.poCache[li.purchase_order()] =
808 this.poCache[li.purchase_order()] ||
809 fieldmapper.standardRequest(
810 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
812 this.authtoken, li.purchase_order(), {
813 "flesh_price_summary": true,
814 "flesh_provider" : true,
815 "flesh_lineitem_count": true
818 if(po && !this.isMeta) {
819 openils.Util.show(nodeByName('po', row), 'inline');
820 var link = nodeByName('po_link', row);
821 link.setAttribute('href', oilsBasePath +
822 '/acq/po/view/' + li.purchase_order() +
823 '?focus_li=' + li.id() +
824 '&source=' + encodeURIComponent(location.pathname + location.search)
826 link.innerHTML += po.name();
828 openils.Util.show(nodeByName('pro', row), 'inline');
829 link = nodeByName('pro_link', row);
830 link.setAttribute('href', oilsBasePath + '/conify/global/acq/provider/' + po.provider().id())
831 link.innerHTML += po.provider().code();
835 // show which picklist this lineitem is a member of
836 if(li.picklist() && (this.isPO || this.isMeta || this.isUni)) {
838 this.plCache[li.picklist()] =
839 this.plCache[li.picklist()] ||
840 fieldmapper.standardRequest(
841 ['open-ils.acq', 'open-ils.acq.picklist.retrieve.authoritative'],
842 {params: [this.authtoken, li.picklist()]});
844 if (pl.name() == "") {
845 openils.Util.show(nodeByName("bib_origin", row), "inline");
849 openils.Util.show(nodeByName('pl', row), 'inline');
850 var link = nodeByName('pl_link', row);
851 link.setAttribute('href', oilsBasePath +
852 '/acq/picklist/view/' + li.picklist() +
853 '?focus_li=' + li.id() +
854 '&source=' + encodeURIComponent(location.pathname + location.search)
856 link.innerHTML += pl.name();
861 var countNode = nodeByName('count', row);
862 var count = li.item_count() || 0;
863 if (typeof(this._copy_count_cb) == "function") {
864 this._copy_count_cb(li.id(), count);
866 countNode.innerHTML = count;
867 countNode.id = 'acq-lit-copy-count-label-' + li.id();
870 var priceInput = dojo.query('[name=price]', row)[0];
871 priceInput.value = li.estimated_unit_price() || '';
872 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
874 // show either "mark received" or "unreceive" as appropriate
875 this.updateLiState(li, row);
877 if (skip_final_placement) {
881 // the last LI may be rendered after the call to show('list'),
882 // so make sure it's focused if necessary.
883 if (this.focusLineitem == li.id())
887 this._liCountClaims = function(li) {
889 for (var i = 0; i < li.lineitem_details().length; i++)
890 total += li.lineitem_details()[i].claims().length;
894 this._findLiRow = function(li) {
895 return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
898 this.reconsiderClaimControl = function(li, row) {
899 if (!row) row = this._findLiRow(li);
900 var option = nodeByName("action_manage_claims", row);
901 var eligible = this.claimEligibleLidByLi[li.id()].length;
902 var count = this._liCountClaims(li);
904 option.disabled = !(count || eligible);
906 dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
907 option.onclick = function() { self.claimDialog.show(li); };
910 this.clearEligibility = function(li) {
911 this.claimEligibleLidByLi[li.id()] = [];
913 if (li.lineitem_details()) {
914 li.lineitem_details().forEach(
915 function(lid) { delete self.claimEligibleLid[lid.id()]; }
919 if (this.copyCache) {
921 for (var k in this.copyCache) {
922 if (this.copyCache[k].lineitem() == li.id())
926 function(k) { delete self.claimEligibleLid[k]; }
931 this.applyOrderIdentValues = function() {
932 this._identValuesInFlight =
933 openils.Util.objectProperties(this.liCache).length;
934 for (var liId in this.liCache) {
935 this._applyOrderIdentValue(this.liCache[liId]);
939 // returns true if request was sent
940 this._applyOrderIdentValue = function(li, oncomplete) {
943 console.log('applying ident value for lineitem ' + li.id());
946 var row = dojo.query('[li=' + li.id() + ']')[0];
948 // find the selected ident value
949 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
950 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
951 var name = typeSel.options[typeSel.selectedIndex].value;
952 var val = typeSel._cbox.attr('value');
954 console.log("selected ident is " + val);
956 // it differs from the existing ident value, update it
957 var oldIdent = self.getLiOrderIdent(li);
959 oldIdent.attr_name() == name &&
960 oldIdent.attr_value() == val) {
961 console.log('selected ident attr matches existing attr');
962 if (--this._identValuesInFlight == 0) {
963 if (oncomplete) oncomplete(li);
964 else location.href = location.href;
969 // see if the selected ident value is represented
970 // by an existing lineitem attr
973 typeSel._cbox.store.fetch({
974 query : {attr_value : val},
975 onItem : function(item) {
976 console.log('found existing attr for ident value');
977 args.source_attr_id = li.attributes().filter(
978 function(attr) { return attr.id() == item.id[0] }
984 if (!args.source_attr_id) {
985 // user entered new text in the combobox
986 // so we need to create a new attr
987 console.log('creating new ident attr');
988 args.lineitem_id = li.id();
989 args.attr_name = name;
990 args.attr_value = val;
993 fieldmapper.standardRequest(
994 ['open-ils.acq', 'open-ils.acq.lineitem.order_identifier.set'],
996 params : [openils.User.authtoken, args],
997 oncomplete : function() {
998 console.log('order_ident oncomplete');
999 if (--self._identValuesInFlight == 0) {
1000 if (oncomplete) oncomplete(li);
1001 else location.href = location.href;
1003 console.log(self._identValuesInFlight + ' still in flight');
1011 this.getLiOrderIdent = function(li) {
1012 var attrs = li.attributes();
1013 if (!attrs) return null;
1014 return attrs.filter(
1017 attr.attr_type() == 'lineitem_local_attr_definition' &&
1018 openils.Util.isTrue(attr.order_ident())
1024 this.drawOrderIdentSelector = function(li, row) {
1026 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
1027 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
1029 var attrs = li.attributes();
1031 // limit to MARC attr defs
1032 attrs = attrs.filter(
1034 return (attr.attr_type() == 'lineitem_marc_attr_definition');
1038 var identAttr = this.getLiOrderIdent(li);
1041 // collect the values for each type of identifier
1042 // find a reasonable default identifier type to render
1046 dojo.forEach(['isbn', 'upc', 'issn'],
1049 // collect the values for this attr name
1050 values[name] = attrs.filter(
1052 return (attr.attr_name() == name)
1056 // select a reasonable default name in the type-selector
1060 if (identAttr.attr_name() == name)
1062 } else if (values[name].length) {
1067 dojo.forEach(typeSel.options, function(opt) {
1068 if (opt.value == name) {
1069 opt.selected = true;
1078 function updateOrderIdent(val) {
1079 self._identValuesInFlight = 1;
1080 self._applyOrderIdentValue(
1083 self.refreshLineitem(li);
1088 // replace the ident combobox with a new
1089 // one for the selected ident type
1090 function changeComboBox(sel) {
1091 var name = sel.options[sel.selectedIndex].value;
1093 var td = dojo.query('[name=order_ident_value]', row)[0];
1094 if (td.childNodes[0])
1095 dojo.destroy(td.childNodes[0]);
1097 var store = new dojo.data.ItemFileWriteStore({
1098 data : acqlia.toStoreData(values[name])
1101 var cbox = new dijit.form.ComboBox(
1103 labelAttr : 'attr_value',
1104 searchAttr : 'attr_value'
1106 dojo.create('div', {}, td)
1111 // set the value for the cbox
1112 if (values[name].length) {
1113 var orderIdent = self.getLiOrderIdent(li);
1115 if (orderIdent && orderIdent.attr_name() == name) {
1116 cbox.attr('value', orderIdent.attr_value());
1118 cbox.attr('value', values[name][0].attr_value());
1122 if (!self.orderIdentAllowed)
1123 cbox.attr('disabled', true);
1126 cbox._lineitem = li;
1127 dojo.connect(cbox, 'onChange', updateOrderIdent);
1130 changeComboBox(typeSel); // force the initial draw
1131 typeSel.onchange = function() {changeComboBox(typeSel)};
1134 this.testOrderIdentPerms = function(org, callback) {
1136 new openils.User().getPermOrgList(
1137 'ACQ_SET_LINEITEM_IDENTIFIER',
1139 console.log('found orgs = ' + orgs);
1140 for (var i = 0; i < orgs.length; i++) {
1141 if (Number(orgs[i]) == Number(org)) {
1142 self.orderIdentAllowed = true;
1143 if (callback) callback();
1147 if (callback) callback();
1153 this.checkClaimEligibility = function(li, callback, row) {
1154 /* Assume always eligible, i.e. from this interface we don't care about
1155 * claim eligibility any more. this is where the user would force a
1157 this.clearEligibility(li);
1158 this.claimEligibleLidByLi[li.id()] = li.lineitem_details().map(
1159 function(lid) { return lid.id(); }
1161 li.lineitem_details().forEach(
1162 function(lid) { self.claimEligibleLid[lid.id()] = true; }
1164 this.reconsiderClaimControl(li, row);
1165 if (callback) callback(li);
1167 this.clearEligibility(li);
1168 fieldmapper.standardRequest(
1169 ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
1170 "params": [openils.User.authtoken, {"lineitem": li.id()}],
1172 "onresponse": function(r) {
1173 if (r = openils.Util.readResponse(r)) {
1174 self.claimEligibleLidByLi[li.id()].push(
1177 self.claimEligibleLid[r.lineitem_detail()] = true;
1180 "oncomplete": function() {
1181 self.reconsiderClaimControl(li, row);
1182 if (typeof(callback) == "function")
1190 this.updateLiNotesCount = function(li, row) {
1191 if (!row) row = this._findLiRow(li);
1193 var has_notes = (li.lineitem_notes().filter(
1194 function(o) { return Boolean (o.alert_text()); }
1197 /* U+2691 is the code point for a filled-in flag character */
1198 nodeByName("notes_alert_flag", row).innerHTML =
1199 has_notes ? "⚑" : "";
1200 nodeByName("noteslink", row).style.fontStyle =
1201 has_notes ? "italic" : "normal";
1202 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
1205 /* XXX NOT related to _updateLiState(). rethink */
1206 this.updateLiState = function(li, row) {
1207 if (!row) row = this._findLiRow(li);
1209 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
1210 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
1212 // always allow access to LI history
1213 nodeByName('action_view_history', row).onclick =
1214 function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
1216 /* handle row coloring for based on LI state */
1217 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1218 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
1220 // Expose invoice actions for any lineitem that is linked to a PO
1221 if (li.purchase_order()) {
1222 openils.Util.show(nodeByName("invoices_span", row), "inline");
1223 var link = nodeByName("invoices_link", row);
1224 link.onclick = function() {
1225 openils.XUL.newTabEasy(
1226 oilsBasePath + "/acq/search/unified?so=" +
1227 base64Encode({"jub":[{"id": li.id()}]}) + "&rt=invoice"
1235 * If we haven't fleshed the lineitem_details, default to allowing access to the
1236 * holdings maintenence actions. The alternative is to flesh LIDs on every lineitem,
1237 * but that will add to page render time. Let's see if this will suffice...
1239 var lids = li.lineitem_details();
1241 (lids && !lids.filter(function(lid) { return lid.eg_copy_id() })[0] )) {
1243 actUpdateBarcodes.disabled = false;
1244 actUpdateBarcodes.onclick = function() {
1245 self.showRealCopyEditUI(li);
1246 nodeByName("action_none", row).selected = true;
1248 actHoldingsMaint.disabled = false;
1249 actHoldingsMaint.onclick =
1250 self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
1253 var state_cell = nodeByName("li_state_" + li.state(), row);
1255 // re-hide any state label nodes which may have been un-hidden
1256 // through previous actions.
1257 dojo.query('[state-label]', row).forEach(function(node) {
1258 openils.Util.hide(node)
1261 if (li.state() == 'cancelled') {
1262 if(typeof li.cancel_reason() == "object") {
1264 // clear the stock "Canceled" label, since we have more
1265 // information to replace it with.
1266 state_cell.innerHTML = '';
1268 var holds_state = dojo.create(
1270 "style": "border-bottom: 1px dashed #000;",
1271 "innerHTML": li.cancel_reason().label()
1272 }, state_cell, "only"
1276 "label": "<em>" + li.cancel_reason().label() +
1277 "</em><br />" + li.cancel_reason().description(),
1278 "connectId": [holds_state]
1279 }, dojo.create("span", null, state_cell, "last")
1282 if (li.cancel_reason().keep_debits() == 't') {
1283 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1284 openils.Util.addCSSClass(row, "oils-acq-li-state-delayed");
1287 console.log('li cancel_reason is un-fleshed. Please fix');
1291 openils.Util.show(state_cell);
1295 this._setAlertStore = function() {
1296 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
1298 "data": acqliat.toStoreData(
1301 "owning_lib": aou.orgNodeTrail(
1302 aou.findOrgUnit(openils.User.user.ws_ou())
1303 ).map(function(o) { return o.id(); })
1309 acqLitAlertAlertText.setValue(); /* make the store "live" */
1310 acqLitAlertAlertText._store_ready = true;
1314 * Draws and shows the lineitem notes pane
1316 this.drawLiNotes = function(li) {
1318 this.focusLineitem = li.id();
1320 if (!acqLitAlertAlertText._store_ready)
1321 this._setAlertStore();
1324 li.lineitem_notes().sort(
1326 if(a.edit_time() < b.edit_time()) return 1;
1332 while(this.liNotesTbody.childNodes[0])
1333 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
1336 acqLitCreateNoteSubmit.onClick = function() {
1337 var value = acqLitCreateNoteText.attr('value');
1339 var note = new fieldmapper.acqlin();
1342 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
1345 note.lineitem(li.id());
1347 self.updateLiNotes(li, note);
1348 acqLitCreateNoteVendorPublic.attr("checked", false);
1349 acqLitCreateNoteText.attr("value", "");
1352 acqLitCreateAlertSubmit.onClick = function() {
1353 if (!acqLitAlertAlertText.item) {
1354 alert(localeStrings.ALERT_UNSELECTED);
1358 var alert_text = new fieldmapper.acqliat().fromStoreItem(
1359 acqLitAlertAlertText.item
1361 var value = acqLitAlertNoteValue.attr("value") || "";
1363 var note = new fieldmapper.acqlin();
1365 note.lineitem(li.id());
1367 note.alert_text(alert_text);
1369 self.updateLiNotes(li, note);
1372 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
1376 * Draws a single lineitem note in the notes pane
1378 this.addLiNote = function(li, note) {
1379 if(note.isdeleted()) return;
1381 var row = self.liNotesRow.cloneNode(true);
1382 nodeByName("value", row).innerHTML = note.value();
1383 var alert_node = nodeByName("alert_code", row);
1384 if (note.alert_text()) {
1385 alert_node.innerHTML = dojo.string.substitute(
1387 aou.findOrgUnit(note.alert_text().owning_lib()).shortname(),
1388 note.alert_text().code()
1391 if (note.alert_text().description()) {
1394 "connectId": [alert_node],
1395 "label": note.alert_text().description()
1396 }, dojo.create("span", null, alert_node, "after")
1401 if (openils.Util.isTrue(note.vendor_public()))
1402 nodeByName("vendor_public", row).innerHTML =
1403 localeStrings.VENDOR_PUBLIC;
1405 nodeByName("delete", row).onclick = function() {
1406 note.isdeleted(true);
1407 self.liNotesTbody.removeChild(row);
1408 self.updateLiNotes(li);
1411 if(note.edit_time()) {
1412 nodeByName("edit_time", row).innerHTML =
1413 dojo.date.locale.format(
1414 dojo.date.stamp.fromISOString(note.edit_time()),
1415 {formatLength:'short'});
1418 self.liNotesTbody.appendChild(row);
1422 * Updates any new/changed/deleted notes on the server
1424 this.updateLiNotes = function(li, newNote) {
1430 notes = li.lineitem_notes().filter(
1432 if(note.ischanged() || note.isnew() || note.isdeleted())
1438 if(notes.length == 0) return;
1439 progressDialog.show();
1441 fieldmapper.standardRequest(
1442 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
1444 params : [this.authtoken, notes],
1445 onresponse : function(r) {
1446 var resp = openils.Util.readResponse(r);
1451 // remove the old changed notes
1453 dojo.forEach(li.lineitem_notes(),
1455 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
1459 li.lineitem_notes(list);
1462 progressDialog.hide();
1463 self.updateLiNotesCount(li);
1464 self.drawLiNotes(li);
1468 progressDialog.update(resp);
1469 var newnote = resp.note;
1471 if(!newnote.isdeleted()) {
1472 newnote.isnew(false);
1473 newnote.ischanged(false);
1474 li.lineitem_notes().push(newnote);
1481 this.updateLiPrice = function(input, li) {
1483 var price = input.value;
1484 if(Number(price) == Number(li.estimated_unit_price())) return;
1486 fieldmapper.standardRequest(
1487 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
1488 { async : false, // redundant w/ timeout
1490 params : [this.authtoken, li.id(), price],
1491 oncomplete : function(r) {
1492 openils.Util.readResponse(r);
1493 li.estimated_unit_price(price); // update local copy
1496 * If this is a PO and every visible lineitem has a price,
1497 * check again to see if this PO can be activated. Note that
1498 * every visible lineitem having a price does not guarantee it can
1499 * be activated, which is why we still make the call. Having a price
1500 * set for every visiable lineitem is just the lowest barrier to entry.
1503 var priceNodes = dojo.query('[name=price]', dojo.byId('acq-lit-tbody'));
1505 dojo.forEach(priceNodes, function(node) { if (node.value == '') allSet = false});
1506 if (allSet) checkCouldActivatePo();
1507 refreshPOSummaryAmounts();
1514 this.removeLineitem = function(liId) {
1515 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
1516 delete this.liCache[liId];
1517 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
1520 this.drawInfo = function(liId) {
1521 this.focusLineitem = liId;
1522 if (!this._isRelatedViewer) {
1523 var d = dojo.byId("acq-lit-info-related");
1524 if (!this.relCache[liId]) {
1525 fieldmapper.standardRequest(
1528 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
1531 "params": [openils.User.authtoken, liId],
1532 "onresponse": function(r) {
1533 self.relCache[liId] = openils.Util.readResponse(r);
1534 nodeByName("related_number", d).innerHTML =
1535 self.relCache[liId];
1537 self.relCache[liId] >1 ? "show" : "hide"
1543 nodeByName("related_number", d).innerHTML = this.relCache[liId];
1544 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
1549 openils.acq.Lineitem.fetchAttrDefs(
1551 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
1556 this.toggleInlineCopies = function() {
1557 // if any inline copies are not displayed,
1558 // display them all otherwise, hide them all.
1560 var displayAll = false;
1562 for (var liId in this.liCache) {
1563 if (!this.inlineCopiesVisible(liId)) {
1569 for (var liId in this.liCache) {
1570 var row = dojo.byId('acq-inline-copies-row-' + liId);
1572 if (!row || row._hidden) {
1573 this.drawInlineCopies(liId);
1575 } else { // hide all
1577 // drawInlineCopies() on a visible row will hide it.
1578 this.drawInlineCopies(liId);
1585 this.inlineCopiesVisible = function(liId) {
1586 var row = dojo.byId('acq-inline-copies-row-' + liId);
1587 return (row && !row._hidden);
1590 this.refreshInlineCopies = function(all, reFetch) {
1592 var liIds = this.inlineCopiesNeedingRefresh;
1593 if (all) liIds = openils.Util.objectProperties(liCache);
1594 liIds.forEach(function(liId) {
1595 if (self.inlineCopiesVisible(liId)) {
1596 self.drawInlineCopies(liId, reFetch); // hide
1597 self.drawInlineCopies(liId, reFetch); // re-draw
1602 // draw inline copy table. if the table is
1603 // already visible, hide the table as-is
1604 // reFetch forces a retrieval of the lineitem and
1605 // copies from the server. otherwise the locally
1606 // cached version of each is used.
1607 this.drawInlineCopies = function(liId, reFetch) {
1610 // find or create the row where the inline copies table will live
1611 var containerRow = dojo.byId('acq-inline-copies-row-' + liId);
1612 var liRow = dojo.query('[li=' + liId + ']')[0];
1614 if (!containerRow) {
1616 // build the inline copies container row and add it to
1617 // the DOM directly after the primary lineitem row
1619 containerRow = self.inlineCopyContainer.cloneNode(true);
1620 containerRow.id = 'acq-inline-copies-row-' + liId;
1622 if (liRow.nextSibling) {
1623 self.tbody.insertBefore(containerRow, liRow.nextSibling);
1625 self.tbody.appendChild(containerRow);
1630 // toggle the visible state
1631 containerRow._hidden = !containerRow._hidden;
1632 openils.Util.toggle(containerRow, 'table-row');
1634 if (containerRow._hidden) return; // hide only
1637 var handler = function(li) {
1639 var tbody = dojo.query(
1640 '[name=acq-li-inline-copies-tbody]',
1643 // reset the table before adding copy rows
1644 while (tbody.childNodes[0])
1645 tbody.removeChild(tbody.childNodes[0]);
1647 if(li.lineitem_details().length == 0) {
1649 self.inlineNoCopies.cloneNode(true));
1650 return; // no copies to show
1653 // add a row to the inline copy table for each copy
1654 dojo.forEach(li.lineitem_details(),
1656 var row = self.inlineCopyTemplate.cloneNode(true);
1657 tbody.appendChild(row);
1658 self.addInlineCopy(li, copy, row);
1663 this._fetchLineitem(liId, handler, reFetch);
1666 /** Draw read-only copy widgets for inline copies */
1667 this.addInlineCopy = function(li, copy, row) {
1670 dojo.forEach(liDetailFields,
1673 var widget = new openils.widget.AutoFieldWidget({
1676 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1677 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1678 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1680 parentNode : dojo.query('[name=' + field + ']', row)[0],
1689 /* For a given list of lineitem ids, build a list of full lineitems
1690 * re-using the fetching logic that is otherwise typical to use in this
1693 * If we've already got a lineitem in the cache, just use that.
1695 * Once we've built a list of lineitems, call callback(thatlist).
1697 this.fetchLineitemsById = function(id_list, callback) {
1698 var total = id_list.length;
1699 var result_list = [];
1701 var inner = function(li) {
1702 result_list.push(li)
1704 callback(result_list);
1707 id_list.forEach(function(id) { self._fetchLineitem(id, inner); });
1710 this._fetchLineitem = function(liId, handler, force) {
1712 var li = this.liCache[liId];
1713 if(li && li.marc() && li.lineitem_details() && !force)
1716 fieldmapper.standardRequest(
1717 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
1720 params: [self.authtoken, liId, {
1722 flesh_cancel_reason: true,
1723 flesh_li_details: true,
1725 flesh_fund_debit: true }],
1727 oncomplete: function(r) {
1728 var li = openils.Util.readResponse(r);
1729 self.liCache[liId] = li;
1736 this._drawInfo = function(li) {
1738 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
1740 if(li.eg_bib_id()) {
1741 openils.Util.hide('acq-lit-marc-order-record-label');
1742 openils.Util.hide(acqLitEditOrderMarc.domNode);
1743 openils.Util.show('acq-lit-marc-real-record-label');
1745 openils.Util.show('acq-lit-marc-order-record-label');
1746 openils.Util.show(acqLitEditOrderMarc.domNode);
1747 openils.Util.hide('acq-lit-marc-real-record-label');
1750 this.drawMarcHTML(li);
1751 this.infoTbody = dojo.byId('acq-lit-info-tbody');
1754 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
1755 while(this.infoTbody.childNodes[0])
1756 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
1758 for(var i = 0; i < li.attributes().length; i++) {
1759 var attr = li.attributes()[i];
1760 var row = this.infoRow.cloneNode(true);
1762 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
1763 var name = openils.acq.Lineitem.attrDefs[type].filter(
1765 return (a.code() == attr.attr_name());
1767 ).pop().description();
1769 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
1770 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
1771 this.infoTbody.appendChild(row);
1774 if (!this._isRelatedViewer) {
1775 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
1776 oilsBasePath + "/acq/lineitem/related/" + li.id();
1779 // if a top scroll point is defined, jump up to it here
1780 var node = dojo.byId('oils-scroll-to-top');
1781 if (node) dijit.scrollIntoView(node);
1784 this.generateMakeRecTab = function(bib_id,default_view, row) {
1788 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
1791 show_nav_buttons : true,
1792 show_print_button : true,
1793 opac_url : xulG.url_prefix('opac_rdetail|' + bib_id),
1794 default_view : default_view
1798 if(row) nodeByName("action_none", row).selected = true;
1802 this.drawMarcHTML = function(li) {
1803 var params = [null, true, li.marc()];
1805 params = [li.eg_bib_id(), true];
1807 fieldmapper.standardRequest(
1808 ['open-ils.search', 'open-ils.search.biblio.record.html'],
1811 oncomplete: function(r) {
1812 dojo.byId('acq-lit-marc-div').innerHTML =
1813 openils.Util.readResponse(r);
1819 this.drawCopies = function(liId, force_fetch) {
1820 this.focusLineitem = liId;
1821 if (typeof force_fetch == "undefined")
1822 force_fetch = false;
1824 var cgi = new openils.CGI();
1825 var source = cgi.param('source');
1826 if (source && source.match(/invoice/)) {
1827 // got here from the invoice page, show the 'return-to-invoice' button
1828 var cgi = new openils.CGI({url : source});
1829 cgi.param('focus_li', liId);
1830 openils.Util.show(dojo.byId('acq-lit-copies-back-to-invoice-button-wrapper'), 'inline');
1831 var button = dojo.byId('acq-lit-copies-back-to-invoice-button');
1832 button.onclick = function() { location.href = cgi.url() };
1835 openils.acq.Lineitem.fetchAndRender(liId, {},
1836 function(li, html) {
1837 dojo.byId('acq-lit-copies-li-summary').innerHTML = html;
1841 this.show('copies');
1843 this.copyCache = {};
1844 this.copyWidgetCache = {};
1845 this.oldCopyWidgetCache = {};
1846 this.virtDfaCounts = {};
1847 this.realDfaCache = {};
1850 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
1851 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
1852 acqLitCopyCountInput.attr('value', '0');
1854 if (this.isPO && PO && PO.order_date()) {
1855 // prevent adding copies to activated POs
1856 acqLitCopyCountInput.attr('disabled', true);
1857 acqLitAddCopyCount.attr('disabled', true);
1860 while(this.copyTbody.childNodes[0])
1861 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
1863 this._drawBatchCopyWidgets();
1865 this._drawDistribApplied(liId);
1867 this._fetchDistribFormulas(
1869 openils.acq.Lineitem.fetchAttrDefs(
1871 self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch);
1878 this._saveDistribAppliedTemplates = function() {
1879 if (!this._appliedDistribTemplate) {
1880 this._appliedDistribTemplate =
1881 dojo.byId("acq-lit-distrib-applied-tbody").
1882 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
1883 dojo.attr(this._appliedDistribTemplate, "id");
1887 this._drawDistribApplied = function(liId) {
1888 /* Build this table while hidden to prevent rendering artifacts */
1889 openils.Util.hide("acq-lit-distrib-applied-tbody");
1891 this._saveDistribAppliedTemplates();
1893 /* Remove any rows in the table from previous populations */
1894 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
1895 forEach(dojo.destroy);
1897 /* Unregister all dijits previously created (for some reason this isn't
1898 * covered by the above destroy calls). */
1899 dijit.registry.forEach(
1900 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
1903 /* Populate the table with our liId */
1905 fieldmapper.standardRequest(
1907 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
1910 "params": [self.authtoken, liId],
1911 "onresponse": function(r) {
1912 var dfa = openils.Util.readResponse(r);
1915 self.realDfaCache[dfa.id()] = dfa;
1916 self._drawDistribAppliedUnit(dfa);
1919 "oncomplete": function() {
1920 /* Reveal built table */
1923 "acq-lit-distrib-applied-tbody", "table-row-group"
1931 this._drawDistribAppliedUnit = function(dfa) {
1932 var new_row = false;
1933 var row = dojo.query(
1934 'tr[formula="' + dfa.formula().id() + '"]',
1935 "acq-lit-distrib-applied-tbody"
1940 row = dojo.clone(this._appliedDistribTemplate);
1941 dojo.attr(row, "formula", dfa.formula().id());
1942 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
1945 var td = dojo.query("td", row)[0];
1947 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1948 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1951 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1953 new dijit.form.Button(
1955 "onClick": function() {
1956 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1957 self.deleteDfa(dfa);
1960 /* XXX I /cannot/ make the following work in as a CSS class
1961 * for some reason. So frustrating... */
1962 "style": function(id) {
1964 "font-weight: bold; color: #c00;" :
1966 }(dfa.id()) + "margin: 0 6px;display: inline;"
1967 }, "dfa-button-" + dfa.id()
1971 "connectId": ["dfa-button-" + dfa.id()],
1972 "label": dojo.string.substitute(
1973 localeStrings.DFA_TIP, dfa.id() > 0 ? [
1974 openils.User.formalName(dfa.creator()),
1975 dojo.date.locale.format(
1976 dojo.date.stamp.fromISOString(dfa.create_time()),
1977 {"formatLength":"short"}
1979 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
1981 }, "dfa-tip-" + dfa.id()
1985 this.deleteDfa = function(dfa) {
1986 if (dfa.id() > 0) { /* real */
1987 this.pcrud.eliminate(
1990 "oncomplete": function() {
1991 self._removeDistribApplied(dfa.id());
1992 delete self.realDfaCache[dfa.id()];
1996 } else { /* virtual */
1997 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
1998 this.virtDfaCounts[dfa.formula().id()] = 0;
1999 /* hasn't been saved yet, so no need to do anything server side */
2000 this._removeDistribApplied(dfa.id());
2005 this._removeDistribApplied = function(dfaId) {
2006 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
2007 dijit.registry.forEach(
2008 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
2010 this._removeDistribAppliedEmptyRows();
2013 this._removeAllDistribAppliedVirtual = function() {
2014 /* Unregister dijits */
2015 dijit.registry.forEach(
2016 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
2018 this._removeDistribAppliedEmptyRows();
2021 this._removeDistribAppliedEmptyRows = function() {
2022 /* Remove any rows with no DFA at all */
2023 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
2025 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
2031 * Insert a new row into the distribution formula selection form
2033 this._addDistribFormulaRow = function() {
2036 if (!self.distribForms) {
2037 // no formulas, hide the form
2038 openils.Util.hide('acq-lit-distrib-formula-table');
2042 if(!this.distribFormulaTemplate)
2043 this.distribFormulaTemplate =
2044 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
2046 var row = this.distribFormulaTemplate.cloneNode(true);
2047 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
2049 this.dfSelector = new dijit.form.FilteringSelect(
2050 {"labelAttr": "dynLabel", "labelType": "html"},
2051 nodeByName("selector", row)
2053 this._updateFormulaStore();
2054 this.dfSelector.fetchProperties =
2055 {"sort": [{"attribute": "use_count", "descending": true}]};
2057 var apply = new dijit.form.Button(
2058 {"label": localeStrings.APPLY},
2059 nodeByName('set_button', row)
2062 var reset = new dijit.form.Button(
2063 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
2064 nodeByName("reset_button", row)
2067 dojo.connect(apply, 'onClick',
2069 var form_id = self.dfSelector.attr("value");
2070 if(!form_id) return;
2071 self._applyDistribFormula(form_id);
2072 reset.attr("disabled", false);
2076 dojo.connect(reset, 'onClick',
2078 self.restoreCopyFieldsBeforeDF();
2079 self.virtDfaCounts = {};
2080 self.virtDfaId = -1;
2082 self._updateFormulaStore();
2083 self._removeAllDistribAppliedVirtual();
2084 reset.attr("disabled", "true");
2091 * Applies a distrib formula to the current set of copies
2093 this._applyDistribFormula = function(formula) {
2094 if(!formula) return;
2096 formula = this.distribForms.filter(
2097 function(form) { return form.id() == formula; }
2100 var copyRows = dojo.query('tr', self.copyTbody);
2102 if (this.dfeOffset >= copyRows.length) {
2103 alert(localeStrings.OUT_OF_COPIES);
2107 var entries_applied = 0;
2109 var rowIndex = this.dfeOffset;
2110 rowIndex < copyRows.length;
2114 var row = copyRows[rowIndex];
2115 var copy_id = row.getAttribute('copy_id');
2116 var copyWidgets = this.copyWidgetCache[copy_id];
2117 var entryIndex = this.dfeOffset;
2120 // find the correct entry for the current row
2121 dojo.forEach(formula.entries(),
2124 entryIndex += e.item_count();
2125 if(entryIndex > rowIndex)
2133 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
2134 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
2137 this.saveCopyFieldsBeforeDF(copy_id);
2138 this._copy_fields_for_acqdf.forEach(
2140 if(entry[field]()) {
2141 copyWidgets[field].attr('value', (entry[field]()));
2148 if (entries_applied) {
2149 this.virtDfaCounts[formula.id()] =
2150 ++(this.virtDfaCounts[formula.id()]) || 1;
2151 this._updateFormulaStore();
2152 this._drawDistribAppliedUnit(
2154 var dfa = new acqdfa();
2155 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
2158 this.dfeOffset += entries_applied;
2163 * This function updates the DF store for the dropdown so that use_counts
2164 * can reflect DF applications from this session before they're saved
2167 this._updateFormulaStore = function() {
2168 this.dfSelector.store = new dojo.data.ItemFileReadStore(
2170 "data": self._labelFormulasWithCounts(
2171 acqdf.toStoreData(self.distribForms)
2177 this.saveCopyFieldsBeforeDF = function(copy_id) {
2179 if (!this.oldCopyWidgetCache[copy_id]) {
2180 var copyWidgets = this.copyWidgetCache[copy_id];
2182 this.oldCopyWidgetCache[copy_id] = {};
2183 this._copy_fields_for_acqdf.forEach(
2185 self.oldCopyWidgetCache[copy_id][f] =
2186 copyWidgets[f].attr("value");
2192 this.restoreCopyFieldsBeforeDF = function() {
2194 for (var copy_id in this.oldCopyWidgetCache) {
2195 this._copy_fields_for_acqdf.forEach(
2197 self.copyWidgetCache[copy_id][f].attr(
2198 "value", self.oldCopyWidgetCache[copy_id][f]
2205 this._labelFormulasWithCounts = function(store_data) {
2206 for (var key in store_data.items) {
2207 var obj = store_data.items[key];
2208 obj.use_count = Number(obj.use_count); /* needed for sorting */
2210 if (this.virtDfaCounts[obj.id])
2211 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
2213 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
2214 obj.use_count + "]</span> " + obj.name;
2220 * This method formerly would not refetch the DF formulas if they'd been
2221 * loaded already, but now it always re-fetches, since use_count changes.
2223 /** TODO: port distrib-formula selector to autofieldwidget+pcrud/dojo store */
2224 this._fetchDistribFormulas = function(onload) {
2225 fieldmapper.standardRequest(
2227 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
2230 "params": [openils.User.authtoken, 0, 500],
2231 "oncomplete": function(r) {
2232 self.distribForms = openils.Util.readResponse(r);
2233 if(!self.distribForms || self.distribForms.length == 0) {
2234 self.distribForms = [];
2236 self._addDistribFormulaRow();
2243 this._drawBatchCopyWidgets = function() {
2244 var row = this.copyBatchRow;
2245 dojo.forEach(liDetailBatchFields,
2247 if(self.copyBatchRowDrawn) {
2248 self.copyBatchWidgets[field].attr('value', null);
2250 var args = self.afwCopyFieldArgs(field, "CREATE_PICKLIST");
2251 args.parentNode = dojo.query('[name='+field+']', row)[0];
2253 var widget = new openils.widget.AutoFieldWidget(args);
2256 if (field == "fund" && w.store)
2257 self._ensureCSSFundClasses(w.store);
2258 self.copyBatchWidgets[field] = w;
2261 if (field == "fund") {
2263 widget.widget, "onChange", function(val) {
2264 self._updateFundSelectorStyle(widget, val);
2271 this.copyBatchRowDrawn = true;
2274 this.batchCopyUpdate = function() {
2276 for(var k in this.copyWidgetCache) {
2277 var cache = this.copyWidgetCache[k];
2278 dojo.forEach(liDetailBatchFields, function(f) {
2279 var newval = self.copyBatchWidgets[f].attr('value');
2280 if(newval) cache[f].attr('value', newval);
2285 this._drawCopies = function(li) {
2288 // this button sets the total number of copies for a given lineitem
2289 acqLitAddCopyCount.onClick = function() {
2290 var count = acqLitCopyCountInput.attr('value');
2293 while(self.copyCount() < count)
2296 // delete rows if necessary
2297 var diff = self.copyCount() - count;
2299 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
2300 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
2301 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
2303 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2309 if(li.lineitem_details().length > 0) {
2310 dojo.forEach(li.lineitem_details(),
2312 self.addCopy(li, copy);
2320 this.copyCount = function() {
2322 for(var id in this.copyCache) {
2323 if(!this.copyCache[id].isdeleted())
2329 this.virtCopyId = -1;
2330 this.addCopy = function(li, copy) {
2331 var row = this.copyRow.cloneNode(true);
2332 this.copyTbody.appendChild(row);
2336 copy = new fieldmapper.acqlid();
2338 copy.id(this.virtCopyId--);
2339 copy.lineitem(li.id());
2342 this.copyCache[copy.id()] = copy;
2343 row.setAttribute('copy_id', copy.id());
2344 self.copyWidgetCache[copy.id()] = {};
2346 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2348 var rcvr = copy.receiver();
2350 if (!userCache[rcvr]) {
2351 if(rcvr == openils.User.user.id()) {
2352 userCache[rcvr] = openils.User.user;
2354 userCache[rcvr] = fieldmapper.standardRequest(
2355 ['open-ils.actor', 'open-ils.actor.user.retrieve'],
2356 {params: [openils.User.authtoken, rcvr]}
2360 dojo.query('[name=receiver]', row)[0].innerHTML = userCache[rcvr].usrname();
2363 dojo.forEach(liDetailFields,
2366 if (field == "fund") {
2367 searchFilter = (copy.fund() ?
2368 {"-or": {"active": "t", "id": copy.fund()}} :
2370 searchFilter.org = fundSearchFilter.org;
2372 searchFilter = null;
2375 var readOnly = false;
2377 // TODO: Add support for changing the owning_lib after real copies have been made.
2378 // owning_lib is order data as much as its item data
2379 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
2383 // TODO: add support for changing the fund after debits have been created
2384 // Note: invoicing allows the change
2385 if(copy.fund_debit() && field == 'fund') {
2390 var widget = new openils.widget.AutoFieldWidget({
2393 labelFormat : (field == 'fund') ? fundLabelFormat : null,
2394 searchFormat : (field == 'fund') ? fundSearchFormat : null,
2395 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
2396 searchFilter : searchFilter,
2397 noCache: (field == "fund"),
2399 parentNode : dojo.query('[name='+field+']', row)[0],
2400 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2401 readOnly : readOnly,
2402 orgDefaultsToWs : true
2406 // make sure we capture the value from any async widgets
2409 if (field == "fund" && w.store)
2410 self._ensureCSSFundClasses(w.store);
2413 copy[field](ww.getFormattedValue())
2415 self.copyWidgetCache[copy.id()][field] = w;
2417 dojo.connect(w, 'onChange',
2419 if (field == "fund")
2420 self._updateFundSelectorStyle(widget, val);
2422 if (!readOnly && (copy.isnew() || val != copy[field]())) {
2423 // prevent setting ischanged() automatically on widget load for existing copies
2424 copy[field](widget.getFormattedValue())
2425 copy.ischanged(true);
2434 this.updateLidState(copy, row);
2437 this._ensureCSSFundClass = function(id) {
2438 if (!this.fundStyleSheet) {
2440 "style", {"type": "text/css"},
2441 document.getElementsByTagName("head")[0], "last"
2443 this.fundStyleSheet = document.styleSheets[
2444 document.styleSheets.length - 1
2448 var cn = "fund_" + id;
2449 if (!this.haveFundClass[cn]) {
2450 fieldmapper.standardRequest(
2451 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
2453 "params": [openils.User.authtoken, id],
2455 "oncomplete": function(r) {
2456 r = openils.Util.readResponse(r);
2457 self.fundBalanceState[id] = r;
2459 if (r[0] /* stop */)
2460 style = fundStyles.stop;
2461 else if (r[1] /* warning */)
2462 style = fundStyles.warning;
2463 self.fundStyleSheet.insertRule(
2464 "." + cn + " { " + style + " }",
2465 self.fundStyleSheet.cssRules.length
2467 self.haveFundClass[cn] = true;
2474 this._ensureCSSFundClasses = function(store) {
2476 "query": {"id": "*"},
2477 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
2481 this._updateFundSelectorStyle = function(widget, fund_id) {
2482 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
2483 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
2486 this.updateLidState = function(copy, row) {
2489 if (typeof(row) == "undefined") {
2490 row = dojo.query('tr[copy_id="' + copy.id() + '"]', this.copyTbody)[0];
2494 var recv_link = nodeByName("receive", row);
2495 var unrecv_link = nodeByName("unreceive", row);
2496 var del_link = nodeByName("delete", row);
2497 var cxl_link = nodeByName("cancel", row);
2498 var claim_link = nodeByName("claim", row);
2499 var cxl_reason_link = nodeByName("cancel_reason", row);
2501 // by default, hide all the actions
2502 openils.Util.hide(del_link.parentNode);
2503 openils.Util.hide(recv_link);
2504 openils.Util.hide(unrecv_link);
2505 openils.Util.hide(cxl_link);
2506 openils.Util.hide(claim_link);
2507 openils.Util.hide(cxl_reason_link);
2509 if (copy.id() > 0) { // real copies (LIDs)
2511 if (copy.cancel_reason()) {
2513 /* --------- cancelled -------------------------- */
2515 /* XXX the following may leak memory in a long lived table:
2516 * dijits may not get destroyed... not positive. revisit. */
2517 var holds_reason = dojo.create(
2519 "style": "border-bottom: 1px dashed #000;",
2520 "innerHTML": copy.cancel_reason().label()
2521 }, cxl_reason_link, "only"
2525 "label": "<em>" + copy.cancel_reason().label() +
2526 "</em><br />" + copy.cancel_reason().description(),
2527 "connectId": [holds_reason]
2528 }, dojo.create("span", null, cxl_reason_link, "last")
2530 openils.Util.show(cxl_reason_link, "inline");
2532 if (copy.cancel_reason().keep_debits() == 't' ) {
2533 // allow further cancellation of "delayed" copies
2535 openils.Util.show(cxl_link, "inline");
2536 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2539 } else if (copy.recv_time()) {
2541 /* --------- received -------------------------- */
2543 openils.Util.show(unrecv_link, "inline");
2544 unrecv_link.onclick = function() {
2545 if (confirm(localeStrings.UNRECEIVE_LID))
2546 self.issueReceive(copy, /* rollback */ true);
2549 } else if (this.liCache[copy.lineitem()].state() == 'on-order') {
2551 /* --------- on order -------------------------- */
2553 openils.Util.show(recv_link, 'inline');
2554 openils.Util.show(cxl_link, "inline");
2556 recv_link.onclick = function() {
2557 if (self.checkLiAlerts(copy.lineitem()))
2558 self.issueReceive(copy);
2561 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2565 /* --------- pre-order copies -------------------------- */
2567 del_link.onclick = function() { self.deleteCopy(row) };
2568 openils.Util.show(del_link.parentNode);
2574 /* --------- virtual copies -------------------------- */
2576 del_link.onclick = function() { self.deleteCopy(row) };
2577 openils.Util.show(del_link.parentNode);
2581 this.cancelLid = function(lid_id) {
2582 lidCancelDialog._lid_id = lid_id;
2583 openils.Util.show(lidCancelDialog.domNode.parentNode);
2584 lidCancelDialog.show();
2585 if (!lidCancelDialog._prepared) {
2586 var widget = new openils.widget.AutoFieldWidget({
2587 "fmField": "cancel_reason",
2588 "fmClass": "acqlid",
2589 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
2590 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2592 "searchOptions" : {order_by : {"acqcr":"label"}}
2596 acqLidCancelButton.onClick = function() {
2597 if (w.attr("value")) {
2598 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
2600 lidCancelDialog._lid_id,
2604 lidCancelDialog.hide();
2607 lidCancelDialog._prepared = true;
2613 this._cancelLid = function(lid_id, reason) {
2614 fieldmapper.standardRequest(
2615 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
2616 "params": [openils.User.authtoken, lid_id, reason],
2618 "onresponse": function(r) {
2619 if (r = openils.Util.readResponse(r)) {
2621 for (var id in r.lid) {
2622 /* actually this should only iterate once */
2623 self.copyCache[id].cancel_reason(
2624 r.lid[id].cancel_reason
2626 self.updateLidState(self.copyCache[id]);
2635 this._confirmAlert = function(li, lin) {
2637 dojo.string.substitute(
2638 localeStrings.CONFIRM_LI_ALERT, [
2639 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2640 "title", "lineitem_marc_attr_definition"
2642 /* XXX it's really better add a parameter and to adjust
2643 * the format string rather than do this concatenation
2644 * here, but if someone wants this for 2.2 in a hurry,
2645 * we can sidestep the problem of updating the strings
2646 * while the translators are working. */
2648 aou.findOrgUnit(lin.alert_text().owning_lib()).shortname() +
2650 lin.alert_text().code()
2652 lin.alert_text().description() || "",
2659 this.checkLiAlerts = function(li_id) {
2660 var li = this.liCache[li_id];
2662 var alert_notes = li.lineitem_notes().filter(
2663 function(o) { return Boolean(o.alert_text()); }
2666 /* this is _intentionally_ not done in a call to forEach() ... */
2667 for (var i = 0; i < alert_notes.length; i++) {
2668 if (this.noteAcks[alert_notes[i].id()])
2670 else if (!this._confirmAlert(li, alert_notes[i]))
2673 this.noteAcks[alert_notes[i].id()] = true;
2679 this.deleteCopy = function(row) {
2680 var copy = this.copyCache[row.getAttribute('copy_id')];
2681 copy.isdeleted(true);
2683 delete this.copyCache[copy.id()];
2684 this.copyTbody.removeChild(row);
2687 this._virtDfaCountsAsList = function() {
2689 for (var key in this.virtDfaCounts) {
2690 for (var i = 0; i < this.virtDfaCounts[key]; i++)
2696 this.confirmBreachedCopyFunds = function(copies) {
2697 var stop = 0, warning = 0;
2701 var state = self.fundBalanceState[o.fund()];
2702 if (state[0] /* stop */)
2704 else if (state[1] /* warning */)
2711 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
2712 } else if (warning) {
2713 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
2718 this.saveCopyChanges = function(liId) {
2724 for(var id in this.copyCache) {
2725 var c = this.copyCache[id];
2726 if(!c.isdeleted()) total++;
2727 if(c.isnew() || c.ischanged() || c.isdeleted()) {
2728 if(c.id() < 0) c.id(null);
2734 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
2737 if (copies.length > 0) {
2738 if (!this.confirmBreachedCopyFunds(copies))
2741 if (typeof(this._copy_count_cb) == "function")
2742 this._copy_count_cb(liId, total);
2744 openils.Util.show("acq-lit-update-copies-progress");
2745 fieldmapper.standardRequest(
2746 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
2748 params: [openils.User.authtoken, copies],
2749 onresponse: function(r) {
2750 var res = openils.Util.readResponse(r);
2751 litUpdateCopiesProgress.update(res);
2753 oncomplete: function() {
2754 self.drawCopies(liId, true /* force_fetch */);
2755 openils.Util.hide("acq-lit-update-copies-progress");
2756 refreshPOSummaryAmounts();
2762 var dfa_list = this._virtDfaCountsAsList();
2763 if (dfa_list.length > 0) {
2764 fieldmapper.standardRequest(
2766 "open-ils.acq.distribution_formula.record_application"],
2769 "params": [openils.User.authtoken, dfa_list, liId],
2770 "onresponse": function(r) {
2771 var res = openils.Util.readResponse(r);
2772 if (res && res.length < dfa_list.length)
2773 alert(localeStrings.DFA_NOT_ALL);
2777 this.virtDfaCounts = {};
2780 if (this.inlineCopiesNeedingRefresh.indexOf(liId) < 0)
2781 this.inlineCopiesNeedingRefresh.push(liId);
2784 this._updateCreatePoPrepayCheckbox = function(prepay) {
2785 var prepay = openils.Util.isTrue(prepay);
2786 this._prepayRequiredByVendor = prepay;
2787 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
2790 this._confirmPoPrepaySituation = function() {
2791 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
2792 if (want_prepay != this._prepayRequiredByVendor) {
2795 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
2796 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
2803 this.applySelectedLiAction = function(action) {
2807 case 'delete_selected':
2808 this._deleteLiList(self.getSelected());
2811 case 'add_to_order':
2812 addToPoDialog._get_li = dojo.hitch(
2815 return this.getSelected(
2816 false, null, true, li_pre_po_states);
2819 if (addToPoDialog._get_li().length == 0) {
2820 alert(localeStrings.NO_LI_GENERAL);
2823 addToPoDialog.show();
2826 case 'create_order':
2827 this._loadPOSelect();
2828 acqLitPoCreateDialog.show();
2831 case 'save_picklist':
2832 acqLitSavePlDialog.show();
2835 case 'selector_ready':
2837 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
2838 acqLitChangeLiStateDialog.show();
2846 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
2849 case 'batch_create_invoice':
2850 this.batchCreateInvoice();
2853 case 'batch_link_invoice':
2854 this.batchLinkInvoice();
2857 case 'receive_lineitems':
2858 this.receiveSelectedLineitems();
2861 case 'rollback_receive_lineitems':
2862 this.rollbackReceiveLineitems();
2865 case 'create_assets':
2866 this.showAssetCreator();
2869 case 'export_attr_list':
2870 this.chooseExportAttr();
2873 case 'batch_apply_funds':
2874 this.applyBatchLiFunds();
2877 case 'add_brief_record':
2879 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
2881 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
2885 case "cancel_lineitems":
2886 console.log('HERE');
2887 this.maybeCancelLineitems();
2890 case "apply_claim_policy":
2891 var li_list = this.getSelected();
2892 this.claimPolicyPicker.attr("value", null);
2893 liClaimPolicyDialog.show();
2894 liClaimPolicySave.onClick = function() {
2895 self.changeClaimPolicy(
2897 self.claimPolicyPicker.attr("value"),
2901 self.setClaimPolicyControl(li);
2902 self.reconsiderClaimControl(li);
2905 liClaimPolicyDialog.hide();
2913 this.changeClaimPolicy = function(li_list, value, callback) {
2915 function(li) { li.claim_policy(value); }
2917 fieldmapper.standardRequest(
2918 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
2919 "params": [openils.User.authtoken, li_list],
2921 "oncomplete": function(r) {
2922 r = openils.Util.readResponse(r);
2923 if (callback) callback(r);
2929 this.showAssetCreator = function(onAssetsCreated) {
2930 if(!this.isPO) return;
2933 // first, let's see if this PO has any LI's that need to be merged/imported
2934 self.pcrud.search('jub', {purchase_order : this.isPO, eg_bib_id : null}, {
2936 oncomplete : function(r) {
2937 var resp = openils.Util.readResponse(r);
2938 if (resp && resp.length) {
2939 // PO has some non-linked jubs.
2941 self.show('asset-creator');
2942 if(!self.vlAgent.loaded)
2943 self.vlAgent.init();
2945 dojo.connect(assetCreatorButton, 'onClick',
2946 function() { self.createAssets(onAssetsCreated) });
2950 // all jubs linked, move on to asset creation
2951 self.createAssets(onAssetsCreated, true);
2957 this.createAssets = function(onAssetsCreated, noVl) {
2958 this.show('acq-lit-progress-numbers');
2960 var vlArgs = (noVl) ? {} : {vandelay : this.vlAgent.values()};
2961 this.batchProgress = {};
2962 progressDialog.show(false);
2963 progressDialog.attr("title", localeStrings.LI_CREATING_ASSETS);
2964 fieldmapper.standardRequest(
2965 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
2967 params: [this.authtoken, this.isPO, vlArgs],
2968 onresponse: function(r) {
2969 var resp = openils.Util.readResponse(r);
2970 self._updateProgressNumbers(resp, !Boolean(onAssetsCreated), onAssetsCreated, true);
2976 this.maybeCancelLineitems = function() {
2977 openils.Util.show("acq-lit-cancel-reason", "inline");
2978 if (!acqLitCancelLineitemsButton._prepared) {
2979 var widget = new openils.widget.AutoFieldWidget({
2980 "fmField": "cancel_reason",
2982 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
2983 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2985 "searchOptions" : {order_by : {"acqcr":"label"}}
2989 acqLitCancelLineitemsButton.onClick = function() {
2990 if (w.attr("value")) {
2991 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
2992 self._cancelLineitems(w.attr("value"));
2994 openils.Util.hide("acq-lit-cancel-reason");
2997 acqLitCancelLineitemsButton._prepared = true;
3003 this._cancelLineitems = function(reason) {
3005 var li_list = this.getSelected();
3007 // canceled lineitems may be canceled again if they were
3008 // previously delayed (keep_debits = true).
3009 li_list = li_list.filter(
3012 li.state() != 'cancelled' ||
3013 li.cancel_reason().keep_debits() == 't'
3018 id_list = li_list.map(function(l) {return l.id()});
3020 if (!id_list.length) {
3021 alert(localeStrings.NO_LI_GENERAL);
3024 fieldmapper.standardRequest(
3025 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
3026 "params": [openils.User.authtoken, id_list, reason],
3028 "onresponse": function(r) {
3029 if (r = openils.Util.readResponse(r)) {
3031 for (var id in r.li) {
3032 self.liCache[id].state(r.li[id].state);
3033 self.liCache[id].cancel_reason(
3034 r.li[id].cancel_reason
3036 self.updateLiState(self.liCache[id]);
3039 if (r.lid && self.copyCache) {
3040 for (var id in r.lid) {
3041 if (self.copyCache[id]) {
3042 self.copyCache[id].cancel_reason(
3043 r.lid[id].cancel_reason
3045 self.updateLidState(self.copyCache[id]);
3055 this.chooseExportAttr = function() {
3056 if (!acqLitExportAttrSelector._li_setup) {
3058 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
3060 "data": acqlimad.toStoreData(
3062 "acqlimad", {"code": li_exportable_attrs}
3067 acqLitExportAttrSelector.setValue();
3068 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
3069 acqLitExportAttrSelector._li_setup = true;
3071 openils.Util.show("acq-lit-export-attr-holder", "inline");
3074 this.exportAttrList = function() {
3075 var attr_def = acqLitExportAttrSelector.item;
3076 var li_list = this.getSelected();
3077 var value_list = li_list.map(
3079 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
3080 attr_def.code, "lineitem_marc_attr_definition"
3083 ).filter(function(attr) { return Boolean(attr); });
3085 if (value_list.length > 0) {
3086 if (value_list.length < li_list.length) {
3088 dojo.string.substitute(
3089 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
3096 openils.XUL.contentToFileSaveDialog(
3097 value_list.join("\n"),
3098 localeStrings.EXPORT_SAVE_DIALOG_TITLE
3104 alert(dojo.string.substitute(
3105 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
3109 openils.Util.hide("acq-lit-export-attr-holder");
3112 this.printPO = function() {
3113 if(!this.isPO) return;
3114 progressDialog.show(true);
3115 fieldmapper.standardRequest(
3116 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
3118 params: [this.authtoken, this.isPO, 'html'],
3119 oncomplete: function(r) {
3120 progressDialog.hide();
3121 var evt = openils.Util.readResponse(r);
3122 if(evt && evt.template_output()) {
3123 openils.Util.printHtmlString(evt.template_output().data());
3130 this.batchCreateInvoice = function() {
3131 var liIds = this.getSelected(
3132 false, null, true /* id_list */, li_active_states)
3133 if (!liIds.length) {
3134 alert(localeStrings.NO_LI_GENERAL);
3137 var path = oilsBasePath + '/acq/invoice/view?create=1';
3138 dojo.forEach(liIds, function(li, idx) { path += '&attach_li=' + li });
3139 if (openils.XUL.isXUL())
3140 openils.XUL.newTabEasy(path, localeStrings.NEW_INVOICE, null, true);
3142 location.href = path;
3145 this.batchLinkInvoice = function(create) {
3146 var liIds = this.getSelected(
3147 false, null, true /* id_list */, li_active_states)
3148 if (!liIds.length) {
3149 alert(localeStrings.NO_LI_GENERAL);
3152 if (!self.invoiceLinkDialogManager) {
3153 self.invoiceLinkDialogManager =
3154 new InvoiceLinkDialogManager("li");
3156 self.invoiceLinkDialogManager.target = liIds;
3157 acqLitLinkInvoiceDialog.show();
3160 this.receiveSelectedLineitems = function() {
3161 var states = li_post_po_states.filter(
3162 function(s) { return s != 'received' });
3163 var li_list = this.getSelected(null, null, null, states);
3165 if (!li_list.length) {
3166 alert(localeStrings.NO_LI_GENERAL);
3170 for (var i = 0; i < li_list.length; i++) {
3171 var li = li_list[i];
3173 if (li.state() != "received" &&
3174 !this.checkLiAlerts(li.id())) return;
3177 this.show('acq-lit-progress-numbers');
3180 fieldmapper.standardRequest(
3181 ['open-ils.acq', 'open-ils.acq.lineitem.receive.batch'],
3185 li_list.map(function(li) { return li.id(); })
3187 onresponse : function(r) {
3188 var resp = openils.Util.readResponse(r);
3189 self._updateProgressNumbers(resp, true);
3195 this.issueReceive = function(obj, rollback) {
3197 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
3199 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
3201 progressDialog.show(true);
3202 fieldmapper.standardRequest(
3203 ["open-ils.acq", method], {
3205 "params": [this.authtoken, obj.id()],
3206 "onresponse": function(r) {
3207 if (r = openils.Util.readResponse(r)) {
3208 self.fetchClaimInfo(
3209 part == "lineitem" ? obj.id() : obj.lineitem(),
3211 function() { self.handleReceive(r); }
3213 progressDialog.hide();
3221 * Handles the responses from receive and rollback ML calls.
3223 this.handleReceive = function(resp) {
3226 for (var li_id in resp.li) {
3227 for (var key in resp.li[li_id])
3228 self.liCache[li_id][key](resp.li[li_id][key]);
3229 self.updateLiState(self.liCache[li_id]);
3233 if (typeof(self.poUpdateCallback) == "function")
3234 self.poUpdateCallback(resp.po);
3237 for (var lid_id in resp.lid) {
3238 for (var key in resp.lid[lid_id])
3239 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
3240 self.updateLidState(self.copyCache[lid_id]);
3246 this.rollbackReceiveLineitems = function() {
3247 var li_id_list = this.getSelected(false, null, true);
3248 if (!li_id_list.length) {
3249 alert(localeStrings.NO_LI_GENERAL);
3253 if (!confirm(localeStrings.ROLLBACK_LI_RECEIVE_CONFIRM)) return;
3255 this.show('acq-lit-progress-numbers');
3258 fieldmapper.standardRequest(
3259 ['open-ils.acq', 'open-ils.acq.lineitem.receive.rollback.batch'],
3261 params: [this.authtoken, li_id_list],
3262 onresponse : function(r) {
3263 var resp = openils.Util.readResponse(r);
3264 self._updateProgressNumbers(resp, true);
3270 this._updateProgressNumbers = function(resp, reloadOnComplete, onComplete, clearProgressDialog) {
3271 this._updateProgressDialog(resp);
3272 this.vlAgent.handleResponse(resp,
3273 function(resp, res) {
3274 if (clearProgressDialog) {
3275 progressDialog.update({ "progress": 100});
3276 progressDialog.update_message();
3277 progressDialog.hide();
3278 progressDialog.attr("title", "");
3280 if(reloadOnComplete)
3281 location.href = location.href;
3283 onComplete(resp, res);
3288 this._updateProgressDialog = function(resp) {
3289 progressDialog.update({ "progress": (resp.progress / resp.total) * 100 });
3290 var keys = ['li', 'vqbr', 'bibs', 'lid', 'debits_accrued', 'copies'];
3291 for (var i = 0; i < keys.length; i++) {
3292 if (resp[keys[i]] > (this.batchProgress[keys[i]] || 0)) {
3293 progressDialog.update_message(
3294 dojo.string.substitute(
3295 localeStrings["ACTIVATE_" + keys[i].toUpperCase() + "_PROCESSED"],
3301 this.batchProgress = resp;
3304 this._createPO = function(fields) {
3305 var wantall = (fields.create_from == "all");
3307 /* If we're a picklist or purchase order already and the user wants
3308 * all lineitems, we might have pages' worth of lineitems haven't all
3309 * been loaded yet, so getSelected() won't find them. The server,
3310 * however, should know about all our lineitems, so let's ask the
3311 * server for a complete list.
3316 true, function(list) {
3317 self._createPOFromLineitems(fields, list);
3318 }, /* id_list */ true, li_pre_po_states
3321 this._createPOFromLineitems(
3322 fields, this.getSelected(
3323 false, null, true /* id_list */, li_pre_po_states)
3328 this._createPOFromLineitems = function(fields, selected) {
3329 if (selected.length == 0) {
3330 alert(localeStrings.NO_LI_GENERAL);
3335 var po = new fieldmapper.acqpo();
3336 po.provider(this.createPoProviderSelector.attr("value"));
3337 po.ordering_agency(this.createPoAgencySelector.attr("value"));
3338 po.prepayment_required(fields.prepayment_required[0] ? true : false);
3339 var name = this.createPoNameInput.attr('value');
3340 if (name) po.name(name); // avoid name=""
3342 // if we're creating assets, delay the asset creation
3343 // until after the PO is created. This will allow us to
3344 // use showAssetCreator() directly.
3346 fieldmapper.standardRequest(
3347 ["open-ils.acq", "open-ils.acq.purchase_order.create"],
3350 openils.User.authtoken,
3351 po, {lineitems : selected}
3353 onresponse : function(r) {
3354 var resp = openils.Util.readResponse(r);
3355 if (resp.complete) {
3356 // self.isPO is needed for showAssetCreator();
3357 self.isPO = resp.purchase_order.id();
3358 var redir = oilsBasePath + "/acq/po/view/" + self.isPO;
3359 if (fields.create_assets[0]) {
3360 self.showAssetCreator(
3361 function() {location.href = redir}
3364 location.href = redir;
3373 this.batchFundWidget = null;
3375 this.applyBatchLiFunds = function() {
3377 var liIds = this.getSelected().map(function(li) { return li.id(); });
3378 if(liIds.length == 0) return; // warn?
3381 batchFundUpdateDialog.show();
3383 if(!this.batchFundWidget) {
3384 this.batchFundWidget = new openils.widget.AutoFieldWidget({
3386 selfReference : true,
3387 labelFormat : fundLabelFormat,
3388 searchFormat : fundSearchFormat,
3389 searchFilter : fundSearchFilter,
3390 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
3391 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
3392 dijitArgs : { "required": true, "labelType": "html" },
3395 this.batchFundWidget.build();
3398 dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
3399 dojo.connect(batchFundUpdateSubmit, 'onClick',
3402 // TODO: call .dry_run first to test thresholds
3403 fieldmapper.standardRequest(
3404 ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
3407 openils.User.authtoken,
3409 self.batchFundWidget.widget.attr('value')
3411 oncomplete : function(r) {
3412 var resp = openils.Util.readResponse(r);
3414 location.href = location.href;
3423 this._deleteLiList = function(list, idx) {
3424 if(idx == null) idx = 0;
3425 if(idx >= list.length) return;
3430 if (this.isPO && (li.state() == "on-order" || li.state() == "received")) {
3431 /* It makes little sense to delete a lineitem from a PO that has
3432 * already been marked 'on-order'. Especially if EDI is in use,
3433 * such a purchase order will probably have already been shipped
3434 * off to a vendor, and mucking with it at this point could leave
3435 * your data in a bad state that doesn't jive with reality.
3437 * I could see making this restriction even firmer.
3439 * I could also see adjusting the li state comparisons, extending
3440 * the comparison to the PO's state, and/or providing functions
3441 * that house the logic for comparing states in a single location.
3443 * Yes, this will be really annoying if you have selected a lot
3444 * of lineitems to cancel that have been ordered. You'll get a
3445 * confirm dialog for each one.
3448 if (!confirm(localeStrings.DEL_LI_FROM_PO)) {
3449 self._deleteLiList(list, ++idx); /* move on to next in list */
3454 fieldmapper.standardRequest(
3456 this.isPO ? 'open-ils.acq.purchase_order.lineitem.delete' : 'open-ils.acq.picklist.lineitem.delete'],
3458 params: [openils.User.authtoken, liId],
3459 oncomplete: function(r) {
3460 self.removeLineitem(liId);
3461 self._deleteLiList(list, ++idx);
3467 this.editOrderMarc = function(li) {
3469 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
3470 to true in about:config */
3472 if(openils.XUL.isXUL()) {
3473 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul','','chrome');
3475 win = window.open('/xul/server/cat/marcedit.xul','','chrome');
3479 record : {marc : li.marc(), "rtype": "bre"},
3481 label: 'Save Record', // XXX I18N
3482 func: function(xmlString) {
3484 fieldmapper.standardRequest(
3485 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
3487 params: [openils.User.authtoken, li],
3488 oncomplete: function(r) {
3489 openils.Util.readResponse(r);
3491 self.drawInfo(li.id())
3497 'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
3498 'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
3502 this._savePl = function(values) {
3504 (values.which == 'all'),
3505 function(list) { self._savePlFromLineitems(values, list); }
3509 this._savePlFromLineitems = function(values, selected) {
3510 openils.Util.show("acq-lit-generic-progress");
3512 if(values.new_name) {
3513 openils.acq.Picklist.create(
3514 {name: values.new_name},
3520 oilsBasePath + "/acq/picklist/view/" + id;
3525 } else if(values.existing_pl) {
3526 // update lineitems to use an existing picklist
3528 values.existing_pl, selected, 0,
3531 oilsBasePath + "/acq/picklist/view/" +
3538 this._updateLiState = function(values, state, state_filter) {
3539 progressDialog.show(true);
3541 (values.which == 'all'),
3543 self._updateLiStateFromLineitems(values, state, list);
3544 }, false /* id_list */, state_filter
3548 this._updateLiStateFromLineitems = function(values, state, selected) {
3549 if(!selected.length) {
3550 try { progressDialog.hide() } catch(E) {};
3551 alert(localeStrings.NO_LI_GENERAL);
3554 dojo.forEach(selected, function(li) {li.state(state);});
3555 self._updateLiList(null, selected, 0,
3556 // TODO consider inline updates for efficiency
3557 function() { location.href = location.href }
3561 this._updateLiList = function(pl, list, idx, oncomplete) {
3562 if(idx >= list.length) return oncomplete();
3564 if(pl != null) li.picklist(pl);
3565 litGenericProgress.update({maximum: list.length, progress: idx});
3566 new openils.acq.Lineitem({lineitem:li}).update(
3568 self._updateLiList(pl, list, ++idx, oncomplete);
3573 this._loadPOSelect = function() {
3574 if (!this.createPoProviderSelector) {
3575 var widget = new openils.widget.AutoFieldWidget({
3576 "fmField": "provider",
3578 "searchFilter": {"active": "t"},
3579 "parentNode": dojo.byId("acq-lit-po-provider"),
3581 "onChange": function() {
3583 self._updateCreatePoPrepayCheckbox(
3584 this.item.prepayment_required()
3590 widget.build(function(w) { self.createPoProviderSelector = w; });
3593 this.createPoCheckDupes = function() {
3594 var org = self.createPoAgencySelector.attr('value');
3595 var name = self.createPoNameInput.attr('value');
3596 openils.Util.hide('acq-dupe-po-name');
3599 acqLitCreatePoSubmit.attr('disabled', false);
3603 acqLitCreatePoSubmit.attr('disabled', true);
3604 var orgs = fieldmapper.aou.descendantNodeList(org, true);
3605 new openils.PermaCrud().search('acqpo',
3606 {name : name, ordering_agency : orgs},
3607 {async : true, oncomplete : function(r) {
3608 var po = openils.Util.readResponse(r);
3610 if (po && (po = po[0])) {
3612 var link = dojo.byId('acq-dupe-po-link');
3613 openils.Util.show('acq-dupe-po-name', 'table-row');
3614 var dupe_path = '/acq/po/view/' + po.id();
3618 if (window.IAMBROWSER) {
3619 // TODO: integration
3623 link.onclick = function() {
3625 var loc = xulG.url_prefix('XUL_BROWSER?url=') +
3626 window.encodeURIComponent(
3627 xulG.url_prefix('EG_WEB_BASE' + dupe_path)
3631 {tab_name: '', browser:false},
3634 show_nav_buttons : true,
3635 show_print_button : true,
3642 link.onclick = function() {
3643 window.open(oilsBasePath + dupe_path, '_blank').focus();
3648 acqLitCreatePoSubmit.attr('disabled', false);
3654 if (!this.createPoAgencySelector) {
3655 var widget = new openils.widget.AutoFieldWidget({
3656 "fmField": "ordering_agency",
3658 "parentNode": dojo.byId("acq-lit-po-agency"),
3659 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3661 widget.build(function(w) {
3662 self.createPoAgencySelector = w;
3663 dojo.connect(w, 'onChange', self.createPoCheckDupes);
3667 if (!this.createPoNameInput) {
3668 var widget = new openils.widget.AutoFieldWidget({
3671 "parentNode": dojo.byId("acq-lit-po-name"),
3672 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3674 widget.build(function(w) {
3675 self.createPoNameInput = w;
3676 dojo.connect(w, 'onChange', self.createPoCheckDupes);
3681 this.showRealCopyEditUI = function(li) {
3686 this._fetchLineitem(li.id(),
3688 li = self.liCache[li.id()] = fullLi;
3692 id : li.lineitem_details().map(
3693 function(item) { return item.eg_copy_id() }
3697 oncomplete : function(r) {
3699 var r_list = openils.Util.readResponse( r );
3700 for (var i = 0; i < r_list.length; i++) {
3701 var copy = r_list[i];
3702 var volId = copy.call_number();
3703 var volume = self.volCache[volId];
3705 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
3707 copy.call_number(volume);
3708 copyList.push(copy);
3711 xulG.volume_item_creator( { 'existing_copies' : copyList } );
3714 alert('error in oncomplete: ' + E);
3723 this.drawBibFinder = function(li) {
3726 var liWrapper = new openils.acq.Lineitem({lineitem:li});
3729 ['isbn', 'upc', 'issn', 'title', 'author'],
3731 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
3733 if(field == 'title' || field == 'author') {
3734 query += field +':' + val + ' ';
3736 query += 'identifier|' + field + ':' + val + ' ';
3743 oilsBasePath + '/acq/lineitem/findbib?query=' + encodeURIComponent(query),
3744 '', 'resizable,scrollbars=1,chrome');
3746 win.window.recordFound = function(bibId) {
3749 var attrs = li.attributes();
3750 li.attributes(null);
3751 li.eg_bib_id(bibId);
3753 fieldmapper.standardRequest(
3754 ["open-ils.acq", "open-ils.acq.lineitem.update"],
3756 "params": [openils.User.authtoken, li],
3758 "oncomplete": function(r) {
3759 if(openils.Util.readResponse(r)) {
3760 location.href = location.href;