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": [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())};
778 this.drawOrderIdentSelector(li, row);
780 if (!this.skipInitialEligibilityCheck)
784 function(full) { self.setClaimPolicyControl(full, row) },
788 this.updateLiNotesCount(li, row);
790 // show which PO this lineitem is a member of
791 if(li.purchase_order() && !this.isPO) {
793 this.poCache[li.purchase_order()] =
794 this.poCache[li.purchase_order()] ||
795 fieldmapper.standardRequest(
796 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
798 this.authtoken, li.purchase_order(), {
799 "flesh_price_summary": true,
800 "flesh_provider" : true,
801 "flesh_lineitem_count": true
804 if(po && !this.isMeta) {
805 openils.Util.show(nodeByName('po', row), 'inline');
806 var link = nodeByName('po_link', row);
807 link.setAttribute('href', oilsBasePath +
808 '/acq/po/view/' + li.purchase_order() +
809 '?focus_li=' + li.id() +
810 '&source=' + encodeURIComponent(location.pathname + location.search)
812 link.innerHTML += po.name();
814 openils.Util.show(nodeByName('pro', row), 'inline');
815 link = nodeByName('pro_link', row);
816 link.setAttribute('href', oilsBasePath + '/conify/global/acq/provider/' + po.provider().id())
817 link.innerHTML += po.provider().code();
821 // show which picklist this lineitem is a member of
822 if(li.picklist() && (this.isPO || this.isMeta || this.isUni)) {
824 this.plCache[li.picklist()] =
825 this.plCache[li.picklist()] ||
826 fieldmapper.standardRequest(
827 ['open-ils.acq', 'open-ils.acq.picklist.retrieve.authoritative'],
828 {params: [this.authtoken, li.picklist()]});
830 if (pl.name() == "") {
831 openils.Util.show(nodeByName("bib_origin", row), "inline");
835 openils.Util.show(nodeByName('pl', row), 'inline');
836 var link = nodeByName('pl_link', row);
837 link.setAttribute('href', oilsBasePath +
838 '/acq/picklist/view/' + li.picklist() +
839 '?focus_li=' + li.id() +
840 '&source=' + encodeURIComponent(location.pathname + location.search)
842 link.innerHTML += pl.name();
847 var countNode = nodeByName('count', row);
848 var count = li.item_count() || 0;
849 if (typeof(this._copy_count_cb) == "function") {
850 this._copy_count_cb(li.id(), count);
852 countNode.innerHTML = count;
853 countNode.id = 'acq-lit-copy-count-label-' + li.id();
856 var priceInput = dojo.query('[name=price]', row)[0];
857 priceInput.value = li.estimated_unit_price() || '';
858 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
860 // show either "mark received" or "unreceive" as appropriate
861 this.updateLiState(li, row);
863 if (skip_final_placement) {
867 // the last LI may be rendered after the call to show('list'),
868 // so make sure it's focused if necessary.
869 if (this.focusLineitem == li.id())
873 this._liCountClaims = function(li) {
875 for (var i = 0; i < li.lineitem_details().length; i++)
876 total += li.lineitem_details()[i].claims().length;
880 this._findLiRow = function(li) {
881 return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
884 this.reconsiderClaimControl = function(li, row) {
885 if (!row) row = this._findLiRow(li);
886 var option = nodeByName("action_manage_claims", row);
887 var eligible = this.claimEligibleLidByLi[li.id()].length;
888 var count = this._liCountClaims(li);
890 option.disabled = !(count || eligible);
892 dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
893 option.onclick = function() { self.claimDialog.show(li); };
896 this.clearEligibility = function(li) {
897 this.claimEligibleLidByLi[li.id()] = [];
899 if (li.lineitem_details()) {
900 li.lineitem_details().forEach(
901 function(lid) { delete self.claimEligibleLid[lid.id()]; }
905 if (this.copyCache) {
907 for (var k in this.copyCache) {
908 if (this.copyCache[k].lineitem() == li.id())
912 function(k) { delete self.claimEligibleLid[k]; }
917 this.applyOrderIdentValues = function() {
918 this._identValuesInFlight =
919 openils.Util.objectProperties(this.liCache).length;
920 for (var liId in this.liCache) {
921 this._applyOrderIdentValue(this.liCache[liId]);
925 // returns true if request was sent
926 this._applyOrderIdentValue = function(li, oncomplete) {
929 console.log('applying ident value for lineitem ' + li.id());
932 var row = dojo.query('[li=' + li.id() + ']')[0];
934 // find the selected ident value
935 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
936 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
937 var name = typeSel.options[typeSel.selectedIndex].value;
938 var val = typeSel._cbox.attr('value');
940 console.log("selected ident is " + val);
942 // it differs from the existing ident value, update it
943 var oldIdent = self.getLiOrderIdent(li);
945 oldIdent.attr_name() == name &&
946 oldIdent.attr_value() == val) {
947 console.log('selected ident attr matches existing attr');
948 if (--this._identValuesInFlight == 0) {
949 if (oncomplete) oncomplete(li);
950 else location.href = location.href;
955 // see if the selected ident value is represented
956 // by an existing lineitem attr
959 typeSel._cbox.store.fetch({
960 query : {attr_value : val},
961 onItem : function(item) {
962 console.log('found existing attr for ident value');
963 args.source_attr_id = li.attributes().filter(
964 function(attr) { return attr.id() == item.id[0] }
970 if (!args.source_attr_id) {
971 // user entered new text in the combobox
972 // so we need to create a new attr
973 console.log('creating new ident attr');
974 args.lineitem_id = li.id();
975 args.attr_name = name;
976 args.attr_value = val;
979 fieldmapper.standardRequest(
980 ['open-ils.acq', 'open-ils.acq.lineitem.order_identifier.set'],
982 params : [openils.User.authtoken, args],
983 oncomplete : function() {
984 console.log('order_ident oncomplete');
985 if (--self._identValuesInFlight == 0) {
986 if (oncomplete) oncomplete(li);
987 else location.href = location.href;
989 console.log(self._identValuesInFlight + ' still in flight');
997 this.getLiOrderIdent = function(li) {
998 var attrs = li.attributes();
999 if (!attrs) return null;
1000 return attrs.filter(
1003 attr.attr_type() == 'lineitem_local_attr_definition' &&
1004 openils.Util.isTrue(attr.order_ident())
1010 this.drawOrderIdentSelector = function(li, row) {
1012 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
1013 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
1015 var attrs = li.attributes();
1017 // limit to MARC attr defs
1018 attrs = attrs.filter(
1020 return (attr.attr_type() == 'lineitem_marc_attr_definition');
1024 var identAttr = this.getLiOrderIdent(li);
1027 // collect the values for each type of identifier
1028 // find a reasonable default identifier type to render
1032 dojo.forEach(['isbn', 'upc', 'issn'],
1035 // collect the values for this attr name
1036 values[name] = attrs.filter(
1038 return (attr.attr_name() == name)
1042 // select a reasonable default name in the type-selector
1046 if (identAttr.attr_name() == name)
1048 } else if (values[name].length) {
1053 dojo.forEach(typeSel.options, function(opt) {
1054 if (opt.value == name) {
1055 opt.selected = true;
1064 function updateOrderIdent(val) {
1065 self._identValuesInFlight = 1;
1066 self._applyOrderIdentValue(
1069 self.refreshLineitem(li);
1074 // replace the ident combobox with a new
1075 // one for the selected ident type
1076 function changeComboBox(sel) {
1077 var name = sel.options[sel.selectedIndex].value;
1079 var td = dojo.query('[name=order_ident_value]', row)[0];
1080 if (td.childNodes[0])
1081 dojo.destroy(td.childNodes[0]);
1083 var store = new dojo.data.ItemFileWriteStore({
1084 data : acqlia.toStoreData(values[name])
1087 var cbox = new dijit.form.ComboBox(
1089 labelAttr : 'attr_value',
1090 searchAttr : 'attr_value'
1092 dojo.create('div', {}, td)
1097 // set the value for the cbox
1098 if (values[name].length) {
1099 var orderIdent = self.getLiOrderIdent(li);
1101 if (orderIdent && orderIdent.attr_name() == name) {
1102 cbox.attr('value', orderIdent.attr_value());
1104 cbox.attr('value', values[name][0].attr_value());
1108 if (!self.orderIdentAllowed)
1109 cbox.attr('disabled', true);
1112 cbox._lineitem = li;
1113 dojo.connect(cbox, 'onChange', updateOrderIdent);
1116 changeComboBox(typeSel); // force the initial draw
1117 typeSel.onchange = function() {changeComboBox(typeSel)};
1120 this.testOrderIdentPerms = function(org, callback) {
1122 new openils.User().getPermOrgList(
1123 'ACQ_SET_LINEITEM_IDENTIFIER',
1125 console.log('found orgs = ' + orgs);
1126 for (var i = 0; i < orgs.length; i++) {
1127 if (Number(orgs[i]) == Number(org)) {
1128 self.orderIdentAllowed = true;
1129 if (callback) callback();
1133 if (callback) callback();
1139 this.checkClaimEligibility = function(li, callback, row) {
1140 /* Assume always eligible, i.e. from this interface we don't care about
1141 * claim eligibility any more. this is where the user would force a
1143 this.clearEligibility(li);
1144 this.claimEligibleLidByLi[li.id()] = li.lineitem_details().map(
1145 function(lid) { return lid.id(); }
1147 li.lineitem_details().forEach(
1148 function(lid) { self.claimEligibleLid[lid.id()] = true; }
1150 this.reconsiderClaimControl(li, row);
1151 if (callback) callback(li);
1153 this.clearEligibility(li);
1154 fieldmapper.standardRequest(
1155 ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
1156 "params": [openils.User.authtoken, {"lineitem": li.id()}],
1158 "onresponse": function(r) {
1159 if (r = openils.Util.readResponse(r)) {
1160 self.claimEligibleLidByLi[li.id()].push(
1163 self.claimEligibleLid[r.lineitem_detail()] = true;
1166 "oncomplete": function() {
1167 self.reconsiderClaimControl(li, row);
1168 if (typeof(callback) == "function")
1176 this.updateLiNotesCount = function(li, row) {
1177 if (!row) row = this._findLiRow(li);
1179 var has_notes = (li.lineitem_notes().filter(
1180 function(o) { return Boolean (o.alert_text()); }
1183 /* U+2691 is the code point for a filled-in flag character */
1184 nodeByName("notes_alert_flag", row).innerHTML =
1185 has_notes ? "⚑" : "";
1186 nodeByName("noteslink", row).style.fontStyle =
1187 has_notes ? "italic" : "normal";
1188 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
1191 /* XXX NOT related to _updateLiState(). rethink */
1192 this.updateLiState = function(li, row) {
1193 if (!row) row = this._findLiRow(li);
1195 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
1196 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
1198 // always allow access to LI history
1199 nodeByName('action_view_history', row).onclick =
1200 function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
1202 /* handle row coloring for based on LI state */
1203 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1204 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
1206 // Expose invoice actions for any lineitem that is linked to a PO
1207 if (li.purchase_order()) {
1208 openils.Util.show(nodeByName("invoices_span", row), "inline");
1209 var link = nodeByName("invoices_link", row);
1210 link.onclick = function() {
1211 openils.XUL.newTabEasy(
1212 oilsBasePath + "/acq/search/unified?so=" +
1213 base64Encode({"jub":[{"id": li.id()}]}) + "&rt=invoice"
1221 * If we haven't fleshed the lineitem_details, default to allowing access to the
1222 * holdings maintenence actions. The alternative is to flesh LIDs on every lineitem,
1223 * but that will add to page render time. Let's see if this will suffice...
1225 var lids = li.lineitem_details();
1227 (lids && !lids.filter(function(lid) { return lid.eg_copy_id() })[0] )) {
1229 actUpdateBarcodes.disabled = false;
1230 actUpdateBarcodes.onclick = function() {
1231 self.showRealCopyEditUI(li);
1232 nodeByName("action_none", row).selected = true;
1234 actHoldingsMaint.disabled = false;
1235 actHoldingsMaint.onclick =
1236 self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
1239 var state_cell = nodeByName("li_state_" + li.state(), row);
1241 // re-hide any state label nodes which may have been un-hidden
1242 // through previous actions.
1243 dojo.query('[state-label]', row).forEach(function(node) {
1244 openils.Util.hide(node)
1247 if (li.state() == 'cancelled') {
1248 if(typeof li.cancel_reason() == "object") {
1250 // clear the stock "Canceled" label, since we have more
1251 // information to replace it with.
1252 state_cell.innerHTML = '';
1254 var holds_state = dojo.create(
1256 "style": "border-bottom: 1px dashed #000;",
1257 "innerHTML": li.cancel_reason().label()
1258 }, state_cell, "only"
1262 "label": "<em>" + li.cancel_reason().label() +
1263 "</em><br />" + li.cancel_reason().description(),
1264 "connectId": [holds_state]
1265 }, dojo.create("span", null, state_cell, "last")
1268 if (li.cancel_reason().keep_debits() == 't') {
1269 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1270 openils.Util.addCSSClass(row, "oils-acq-li-state-delayed");
1273 console.log('li cancel_reason is un-fleshed. Please fix');
1277 openils.Util.show(state_cell);
1281 this._setAlertStore = function() {
1282 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
1284 "data": acqliat.toStoreData(
1287 "owning_lib": aou.orgNodeTrail(
1288 aou.findOrgUnit(openils.User.user.ws_ou())
1289 ).map(function(o) { return o.id(); })
1295 acqLitAlertAlertText.setValue(); /* make the store "live" */
1296 acqLitAlertAlertText._store_ready = true;
1300 * Draws and shows the lineitem notes pane
1302 this.drawLiNotes = function(li) {
1304 this.focusLineitem = li.id();
1306 if (!acqLitAlertAlertText._store_ready)
1307 this._setAlertStore();
1310 li.lineitem_notes().sort(
1312 if(a.edit_time() < b.edit_time()) return 1;
1318 while(this.liNotesTbody.childNodes[0])
1319 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
1322 acqLitCreateNoteSubmit.onClick = function() {
1323 var value = acqLitCreateNoteText.attr('value');
1325 var note = new fieldmapper.acqlin();
1328 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
1331 note.lineitem(li.id());
1333 self.updateLiNotes(li, note);
1334 acqLitCreateNoteVendorPublic.attr("checked", false);
1335 acqLitCreateNoteText.attr("value", "");
1338 acqLitCreateAlertSubmit.onClick = function() {
1339 if (!acqLitAlertAlertText.item) {
1340 alert(localeStrings.ALERT_UNSELECTED);
1344 var alert_text = new fieldmapper.acqliat().fromStoreItem(
1345 acqLitAlertAlertText.item
1347 var value = acqLitAlertNoteValue.attr("value") || "";
1349 var note = new fieldmapper.acqlin();
1351 note.lineitem(li.id());
1353 note.alert_text(alert_text);
1355 self.updateLiNotes(li, note);
1358 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
1362 * Draws a single lineitem note in the notes pane
1364 this.addLiNote = function(li, note) {
1365 if(note.isdeleted()) return;
1367 var row = self.liNotesRow.cloneNode(true);
1368 nodeByName("value", row).innerHTML = note.value();
1369 var alert_node = nodeByName("alert_code", row);
1370 if (note.alert_text()) {
1371 alert_node.innerHTML = dojo.string.substitute(
1373 aou.findOrgUnit(note.alert_text().owning_lib()).shortname(),
1374 note.alert_text().code()
1377 if (note.alert_text().description()) {
1380 "connectId": [alert_node],
1381 "label": note.alert_text().description()
1382 }, dojo.create("span", null, alert_node, "after")
1387 if (openils.Util.isTrue(note.vendor_public()))
1388 nodeByName("vendor_public", row).innerHTML =
1389 localeStrings.VENDOR_PUBLIC;
1391 nodeByName("delete", row).onclick = function() {
1392 note.isdeleted(true);
1393 self.liNotesTbody.removeChild(row);
1394 self.updateLiNotes(li);
1397 if(note.edit_time()) {
1398 nodeByName("edit_time", row).innerHTML =
1399 dojo.date.locale.format(
1400 dojo.date.stamp.fromISOString(note.edit_time()),
1401 {formatLength:'short'});
1404 self.liNotesTbody.appendChild(row);
1408 * Updates any new/changed/deleted notes on the server
1410 this.updateLiNotes = function(li, newNote) {
1416 notes = li.lineitem_notes().filter(
1418 if(note.ischanged() || note.isnew() || note.isdeleted())
1424 if(notes.length == 0) return;
1425 progressDialog.show();
1427 fieldmapper.standardRequest(
1428 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
1430 params : [this.authtoken, notes],
1431 onresponse : function(r) {
1432 var resp = openils.Util.readResponse(r);
1437 // remove the old changed notes
1439 dojo.forEach(li.lineitem_notes(),
1441 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
1445 li.lineitem_notes(list);
1448 progressDialog.hide();
1449 self.updateLiNotesCount(li);
1450 self.drawLiNotes(li);
1454 progressDialog.update(resp);
1455 var newnote = resp.note;
1457 if(!newnote.isdeleted()) {
1458 newnote.isnew(false);
1459 newnote.ischanged(false);
1460 li.lineitem_notes().push(newnote);
1467 this.updateLiPrice = function(input, li) {
1469 var price = input.value;
1470 if(Number(price) == Number(li.estimated_unit_price())) return;
1472 fieldmapper.standardRequest(
1473 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
1474 { async : false, // redundant w/ timeout
1476 params : [this.authtoken, li.id(), price],
1477 oncomplete : function(r) {
1478 openils.Util.readResponse(r);
1479 li.estimated_unit_price(price); // update local copy
1482 * If this is a PO and every visible lineitem has a price,
1483 * check again to see if this PO can be activated. Note that
1484 * every visible lineitem having a price does not guarantee it can
1485 * be activated, which is why we still make the call. Having a price
1486 * set for every visiable lineitem is just the lowest barrier to entry.
1489 var priceNodes = dojo.query('[name=price]', dojo.byId('acq-lit-tbody'));
1491 dojo.forEach(priceNodes, function(node) { if (node.value == '') allSet = false});
1492 if (allSet) checkCouldActivatePo();
1493 refreshPOSummaryAmounts();
1500 this.removeLineitem = function(liId) {
1501 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
1502 delete this.liCache[liId];
1503 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
1506 this.drawInfo = function(liId) {
1507 this.focusLineitem = liId;
1508 if (!this._isRelatedViewer) {
1509 var d = dojo.byId("acq-lit-info-related");
1510 if (!this.relCache[liId]) {
1511 fieldmapper.standardRequest(
1514 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
1517 "params": [openils.User.authtoken, liId],
1518 "onresponse": function(r) {
1519 self.relCache[liId] = openils.Util.readResponse(r);
1520 nodeByName("related_number", d).innerHTML =
1521 self.relCache[liId];
1523 self.relCache[liId] >1 ? "show" : "hide"
1529 nodeByName("related_number", d).innerHTML = this.relCache[liId];
1530 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
1535 openils.acq.Lineitem.fetchAttrDefs(
1537 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
1542 this.toggleInlineCopies = function() {
1543 // if any inline copies are not displayed,
1544 // display them all otherwise, hide them all.
1546 var displayAll = false;
1548 for (var liId in this.liCache) {
1549 if (!this.inlineCopiesVisible(liId)) {
1555 for (var liId in this.liCache) {
1556 var row = dojo.byId('acq-inline-copies-row-' + liId);
1558 if (!row || row._hidden) {
1559 this.drawInlineCopies(liId);
1561 } else { // hide all
1563 // drawInlineCopies() on a visible row will hide it.
1564 this.drawInlineCopies(liId);
1571 this.inlineCopiesVisible = function(liId) {
1572 var row = dojo.byId('acq-inline-copies-row-' + liId);
1573 return (row && !row._hidden);
1576 this.refreshInlineCopies = function(all, reFetch) {
1578 var liIds = this.inlineCopiesNeedingRefresh;
1579 if (all) liIds = openils.Util.objectProperties(liCache);
1580 liIds.forEach(function(liId) {
1581 if (self.inlineCopiesVisible(liId)) {
1582 self.drawInlineCopies(liId, reFetch); // hide
1583 self.drawInlineCopies(liId, reFetch); // re-draw
1588 // draw inline copy table. if the table is
1589 // already visible, hide the table as-is
1590 // reFetch forces a retrieval of the lineitem and
1591 // copies from the server. otherwise the locally
1592 // cached version of each is used.
1593 this.drawInlineCopies = function(liId, reFetch) {
1596 // find or create the row where the inline copies table will live
1597 var containerRow = dojo.byId('acq-inline-copies-row-' + liId);
1598 var liRow = dojo.query('[li=' + liId + ']')[0];
1600 if (!containerRow) {
1602 // build the inline copies container row and add it to
1603 // the DOM directly after the primary lineitem row
1605 containerRow = self.inlineCopyContainer.cloneNode(true);
1606 containerRow.id = 'acq-inline-copies-row-' + liId;
1608 if (liRow.nextSibling) {
1609 self.tbody.insertBefore(containerRow, liRow.nextSibling);
1611 self.tbody.appendChild(containerRow);
1616 // toggle the visible state
1617 containerRow._hidden = !containerRow._hidden;
1618 openils.Util.toggle(containerRow, 'table-row');
1620 if (containerRow._hidden) return; // hide only
1623 var handler = function(li) {
1625 var tbody = dojo.query(
1626 '[name=acq-li-inline-copies-tbody]',
1629 // reset the table before adding copy rows
1630 while (tbody.childNodes[0])
1631 tbody.removeChild(tbody.childNodes[0]);
1633 if(li.lineitem_details().length == 0) {
1635 self.inlineNoCopies.cloneNode(true));
1636 return; // no copies to show
1639 // add a row to the inline copy table for each copy
1640 dojo.forEach(li.lineitem_details(),
1642 var row = self.inlineCopyTemplate.cloneNode(true);
1643 tbody.appendChild(row);
1644 self.addInlineCopy(li, copy, row);
1649 this._fetchLineitem(liId, handler, reFetch);
1652 /** Draw read-only copy widgets for inline copies */
1653 this.addInlineCopy = function(li, copy, row) {
1656 dojo.forEach(liDetailFields,
1659 var widget = new openils.widget.AutoFieldWidget({
1662 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1663 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1664 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1666 parentNode : dojo.query('[name=' + field + ']', row)[0],
1675 /* For a given list of lineitem ids, build a list of full lineitems
1676 * re-using the fetching logic that is otherwise typical to use in this
1679 * If we've already got a lineitem in the cache, just use that.
1681 * Once we've built a list of lineitems, call callback(thatlist).
1683 this.fetchLineitemsById = function(id_list, callback) {
1684 var total = id_list.length;
1685 var result_list = [];
1687 var inner = function(li) {
1688 result_list.push(li)
1690 callback(result_list);
1693 id_list.forEach(function(id) { self._fetchLineitem(id, inner); });
1696 this._fetchLineitem = function(liId, handler, force) {
1698 var li = this.liCache[liId];
1699 if(li && li.marc() && li.lineitem_details() && !force)
1702 fieldmapper.standardRequest(
1703 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
1706 params: [self.authtoken, liId, {
1708 flesh_cancel_reason: true,
1709 flesh_li_details: true,
1711 flesh_fund_debit: true }],
1713 oncomplete: function(r) {
1714 var li = openils.Util.readResponse(r);
1715 self.liCache[liId] = li;
1722 this._drawInfo = function(li) {
1724 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
1726 if(li.eg_bib_id()) {
1727 openils.Util.hide('acq-lit-marc-order-record-label');
1728 openils.Util.hide(acqLitEditOrderMarc.domNode);
1729 openils.Util.show('acq-lit-marc-real-record-label');
1731 openils.Util.show('acq-lit-marc-order-record-label');
1732 openils.Util.show(acqLitEditOrderMarc.domNode);
1733 openils.Util.hide('acq-lit-marc-real-record-label');
1736 this.drawMarcHTML(li);
1737 this.infoTbody = dojo.byId('acq-lit-info-tbody');
1740 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
1741 while(this.infoTbody.childNodes[0])
1742 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
1744 for(var i = 0; i < li.attributes().length; i++) {
1745 var attr = li.attributes()[i];
1746 var row = this.infoRow.cloneNode(true);
1748 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
1749 var name = openils.acq.Lineitem.attrDefs[type].filter(
1751 return (a.code() == attr.attr_name());
1753 ).pop().description();
1755 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
1756 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
1757 this.infoTbody.appendChild(row);
1760 if (!this._isRelatedViewer) {
1761 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
1762 oilsBasePath + "/acq/lineitem/related/" + li.id();
1765 // if a top scroll point is defined, jump up to it here
1766 var node = dojo.byId('oils-scroll-to-top');
1767 if (node) dijit.scrollIntoView(node);
1770 this.generateMakeRecTab = function(bib_id,default_view, row) {
1774 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
1777 show_nav_buttons : true,
1778 show_print_button : true,
1779 opac_url : xulG.url_prefix('opac_rdetail|' + bib_id),
1780 default_view : default_view
1784 if(row) nodeByName("action_none", row).selected = true;
1788 this.drawMarcHTML = function(li) {
1789 var params = [null, true, li.marc()];
1791 params = [li.eg_bib_id(), true];
1793 fieldmapper.standardRequest(
1794 ['open-ils.search', 'open-ils.search.biblio.record.html'],
1797 oncomplete: function(r) {
1798 dojo.byId('acq-lit-marc-div').innerHTML =
1799 openils.Util.readResponse(r);
1805 this.drawCopies = function(liId, force_fetch) {
1806 this.focusLineitem = liId;
1807 if (typeof force_fetch == "undefined")
1808 force_fetch = false;
1810 var cgi = new openils.CGI();
1811 var source = cgi.param('source');
1812 if (source && source.match(/invoice/)) {
1813 // got here from the invoice page, show the 'return-to-invoice' button
1814 var cgi = new openils.CGI({url : source});
1815 cgi.param('focus_li', liId);
1816 openils.Util.show(dojo.byId('acq-lit-copies-back-to-invoice-button-wrapper'), 'inline');
1817 var button = dojo.byId('acq-lit-copies-back-to-invoice-button');
1818 button.onclick = function() { location.href = cgi.url() };
1821 openils.acq.Lineitem.fetchAndRender(liId, {},
1822 function(li, html) {
1823 dojo.byId('acq-lit-copies-li-summary').innerHTML = html;
1827 this.show('copies');
1829 this.copyCache = {};
1830 this.copyWidgetCache = {};
1831 this.oldCopyWidgetCache = {};
1832 this.virtDfaCounts = {};
1833 this.realDfaCache = {};
1836 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
1837 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
1838 acqLitCopyCountInput.attr('value', '0');
1840 if (this.isPO && PO && PO.order_date()) {
1841 // prevent adding copies to activated POs
1842 acqLitCopyCountInput.attr('disabled', true);
1843 acqLitAddCopyCount.attr('disabled', true);
1846 while(this.copyTbody.childNodes[0])
1847 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
1849 this._drawBatchCopyWidgets();
1851 this._drawDistribApplied(liId);
1853 this._fetchDistribFormulas(
1855 openils.acq.Lineitem.fetchAttrDefs(
1857 self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch);
1864 this._saveDistribAppliedTemplates = function() {
1865 if (!this._appliedDistribTemplate) {
1866 this._appliedDistribTemplate =
1867 dojo.byId("acq-lit-distrib-applied-tbody").
1868 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
1869 dojo.attr(this._appliedDistribTemplate, "id");
1873 this._drawDistribApplied = function(liId) {
1874 /* Build this table while hidden to prevent rendering artifacts */
1875 openils.Util.hide("acq-lit-distrib-applied-tbody");
1877 this._saveDistribAppliedTemplates();
1879 /* Remove any rows in the table from previous populations */
1880 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
1881 forEach(dojo.destroy);
1883 /* Unregister all dijits previously created (for some reason this isn't
1884 * covered by the above destroy calls). */
1885 dijit.registry.forEach(
1886 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
1889 /* Populate the table with our liId */
1891 fieldmapper.standardRequest(
1893 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
1896 "params": [self.authtoken, liId],
1897 "onresponse": function(r) {
1898 var dfa = openils.Util.readResponse(r);
1901 self.realDfaCache[dfa.id()] = dfa;
1902 self._drawDistribAppliedUnit(dfa);
1905 "oncomplete": function() {
1906 /* Reveal built table */
1909 "acq-lit-distrib-applied-tbody", "table-row-group"
1917 this._drawDistribAppliedUnit = function(dfa) {
1918 var new_row = false;
1919 var row = dojo.query(
1920 'tr[formula="' + dfa.formula().id() + '"]',
1921 "acq-lit-distrib-applied-tbody"
1926 row = dojo.clone(this._appliedDistribTemplate);
1927 dojo.attr(row, "formula", dfa.formula().id());
1928 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
1931 var td = dojo.query("td", row)[0];
1933 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1934 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1937 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1939 new dijit.form.Button(
1941 "onClick": function() {
1942 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1943 self.deleteDfa(dfa);
1946 /* XXX I /cannot/ make the following work in as a CSS class
1947 * for some reason. So frustrating... */
1948 "style": function(id) {
1950 "font-weight: bold; color: #c00;" :
1952 }(dfa.id()) + "margin: 0 6px;display: inline;"
1953 }, "dfa-button-" + dfa.id()
1957 "connectId": ["dfa-button-" + dfa.id()],
1958 "label": dojo.string.substitute(
1959 localeStrings.DFA_TIP, dfa.id() > 0 ? [
1960 openils.User.formalName(dfa.creator()),
1961 dojo.date.locale.format(
1962 dojo.date.stamp.fromISOString(dfa.create_time()),
1963 {"formatLength":"short"}
1965 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
1967 }, "dfa-tip-" + dfa.id()
1971 this.deleteDfa = function(dfa) {
1972 if (dfa.id() > 0) { /* real */
1973 this.pcrud.eliminate(
1976 "oncomplete": function() {
1977 self._removeDistribApplied(dfa.id());
1978 delete self.realDfaCache[dfa.id()];
1982 } else { /* virtual */
1983 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
1984 this.virtDfaCounts[dfa.formula().id()] = 0;
1985 /* hasn't been saved yet, so no need to do anything server side */
1986 this._removeDistribApplied(dfa.id());
1991 this._removeDistribApplied = function(dfaId) {
1992 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
1993 dijit.registry.forEach(
1994 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
1996 this._removeDistribAppliedEmptyRows();
1999 this._removeAllDistribAppliedVirtual = function() {
2000 /* Unregister dijits */
2001 dijit.registry.forEach(
2002 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
2004 this._removeDistribAppliedEmptyRows();
2007 this._removeDistribAppliedEmptyRows = function() {
2008 /* Remove any rows with no DFA at all */
2009 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
2011 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
2017 * Insert a new row into the distribution formula selection form
2019 this._addDistribFormulaRow = function() {
2022 if (!self.distribForms) {
2023 // no formulas, hide the form
2024 openils.Util.hide('acq-lit-distrib-formula-table');
2028 if(!this.distribFormulaTemplate)
2029 this.distribFormulaTemplate =
2030 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
2032 var row = this.distribFormulaTemplate.cloneNode(true);
2033 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
2035 this.dfSelector = new dijit.form.FilteringSelect(
2036 {"labelAttr": "dynLabel", "labelType": "html"},
2037 nodeByName("selector", row)
2039 this._updateFormulaStore();
2040 this.dfSelector.fetchProperties =
2041 {"sort": [{"attribute": "use_count", "descending": true}]};
2043 var apply = new dijit.form.Button(
2044 {"label": localeStrings.APPLY},
2045 nodeByName('set_button', row)
2048 var reset = new dijit.form.Button(
2049 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
2050 nodeByName("reset_button", row)
2053 dojo.connect(apply, 'onClick',
2055 var form_id = self.dfSelector.attr("value");
2056 if(!form_id) return;
2057 self._applyDistribFormula(form_id);
2058 reset.attr("disabled", false);
2062 dojo.connect(reset, 'onClick',
2064 self.restoreCopyFieldsBeforeDF();
2065 self.virtDfaCounts = {};
2066 self.virtDfaId = -1;
2068 self._updateFormulaStore();
2069 self._removeAllDistribAppliedVirtual();
2070 reset.attr("disabled", "true");
2077 * Applies a distrib formula to the current set of copies
2079 this._applyDistribFormula = function(formula) {
2080 if(!formula) return;
2082 formula = this.distribForms.filter(
2083 function(form) { return form.id() == formula; }
2086 var copyRows = dojo.query('tr', self.copyTbody);
2088 if (this.dfeOffset >= copyRows.length) {
2089 alert(localeStrings.OUT_OF_COPIES);
2093 var entries_applied = 0;
2095 var rowIndex = this.dfeOffset;
2096 rowIndex < copyRows.length;
2100 var row = copyRows[rowIndex];
2101 var copy_id = row.getAttribute('copy_id');
2102 var copyWidgets = this.copyWidgetCache[copy_id];
2103 var entryIndex = this.dfeOffset;
2106 // find the correct entry for the current row
2107 dojo.forEach(formula.entries(),
2110 entryIndex += e.item_count();
2111 if(entryIndex > rowIndex)
2119 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
2120 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
2123 this.saveCopyFieldsBeforeDF(copy_id);
2124 this._copy_fields_for_acqdf.forEach(
2126 if(entry[field]()) {
2127 copyWidgets[field].attr('value', (entry[field]()));
2134 if (entries_applied) {
2135 this.virtDfaCounts[formula.id()] =
2136 ++(this.virtDfaCounts[formula.id()]) || 1;
2137 this._updateFormulaStore();
2138 this._drawDistribAppliedUnit(
2140 var dfa = new acqdfa();
2141 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
2144 this.dfeOffset += entries_applied;
2149 * This function updates the DF store for the dropdown so that use_counts
2150 * can reflect DF applications from this session before they're saved
2153 this._updateFormulaStore = function() {
2154 this.dfSelector.store = new dojo.data.ItemFileReadStore(
2156 "data": self._labelFormulasWithCounts(
2157 acqdf.toStoreData(self.distribForms)
2163 this.saveCopyFieldsBeforeDF = function(copy_id) {
2165 if (!this.oldCopyWidgetCache[copy_id]) {
2166 var copyWidgets = this.copyWidgetCache[copy_id];
2168 this.oldCopyWidgetCache[copy_id] = {};
2169 this._copy_fields_for_acqdf.forEach(
2171 self.oldCopyWidgetCache[copy_id][f] =
2172 copyWidgets[f].attr("value");
2178 this.restoreCopyFieldsBeforeDF = function() {
2180 for (var copy_id in this.oldCopyWidgetCache) {
2181 this._copy_fields_for_acqdf.forEach(
2183 self.copyWidgetCache[copy_id][f].attr(
2184 "value", self.oldCopyWidgetCache[copy_id][f]
2191 this._labelFormulasWithCounts = function(store_data) {
2192 for (var key in store_data.items) {
2193 var obj = store_data.items[key];
2194 obj.use_count = Number(obj.use_count); /* needed for sorting */
2196 if (this.virtDfaCounts[obj.id])
2197 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
2199 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
2200 obj.use_count + "]</span> " + obj.name;
2206 * This method formerly would not refetch the DF formulas if they'd been
2207 * loaded already, but now it always re-fetches, since use_count changes.
2209 /** TODO: port distrib-formula selector to autofieldwidget+pcrud/dojo store */
2210 this._fetchDistribFormulas = function(onload) {
2211 fieldmapper.standardRequest(
2213 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
2216 "params": [openils.User.authtoken, 0, 500],
2217 "oncomplete": function(r) {
2218 self.distribForms = openils.Util.readResponse(r);
2219 if(!self.distribForms || self.distribForms.length == 0) {
2220 self.distribForms = [];
2222 self._addDistribFormulaRow();
2229 this._drawBatchCopyWidgets = function() {
2230 var row = this.copyBatchRow;
2231 dojo.forEach(liDetailBatchFields,
2233 if(self.copyBatchRowDrawn) {
2234 self.copyBatchWidgets[field].attr('value', null);
2236 var args = self.afwCopyFieldArgs(field, "CREATE_PICKLIST");
2237 args.parentNode = dojo.query('[name='+field+']', row)[0];
2239 var widget = new openils.widget.AutoFieldWidget(args);
2242 if (field == "fund" && w.store)
2243 self._ensureCSSFundClasses(w.store);
2244 self.copyBatchWidgets[field] = w;
2247 if (field == "fund") {
2249 widget.widget, "onChange", function(val) {
2250 self._updateFundSelectorStyle(widget, val);
2257 this.copyBatchRowDrawn = true;
2260 this.batchCopyUpdate = function() {
2262 for(var k in this.copyWidgetCache) {
2263 var cache = this.copyWidgetCache[k];
2264 dojo.forEach(liDetailBatchFields, function(f) {
2265 var newval = self.copyBatchWidgets[f].attr('value');
2266 if(newval) cache[f].attr('value', newval);
2271 this._drawCopies = function(li) {
2274 // this button sets the total number of copies for a given lineitem
2275 acqLitAddCopyCount.onClick = function() {
2276 var count = acqLitCopyCountInput.attr('value');
2279 while(self.copyCount() < count)
2282 // delete rows if necessary
2283 var diff = self.copyCount() - count;
2285 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
2286 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
2287 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
2289 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2295 if(li.lineitem_details().length > 0) {
2296 dojo.forEach(li.lineitem_details(),
2298 self.addCopy(li, copy);
2306 this.copyCount = function() {
2308 for(var id in this.copyCache) {
2309 if(!this.copyCache[id].isdeleted())
2315 this.virtCopyId = -1;
2316 this.addCopy = function(li, copy) {
2317 var row = this.copyRow.cloneNode(true);
2318 this.copyTbody.appendChild(row);
2322 copy = new fieldmapper.acqlid();
2324 copy.id(this.virtCopyId--);
2325 copy.lineitem(li.id());
2328 this.copyCache[copy.id()] = copy;
2329 row.setAttribute('copy_id', copy.id());
2330 self.copyWidgetCache[copy.id()] = {};
2332 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2334 var rcvr = copy.receiver();
2336 if (!userCache[rcvr]) {
2337 if(rcvr == openils.User.user.id()) {
2338 userCache[rcvr] = openils.User.user;
2340 userCache[rcvr] = fieldmapper.standardRequest(
2341 ['open-ils.actor', 'open-ils.actor.user.retrieve'],
2342 {params: [openils.User.authtoken, rcvr]}
2346 dojo.query('[name=receiver]', row)[0].innerHTML = userCache[rcvr].usrname();
2349 dojo.forEach(liDetailFields,
2352 if (field == "fund") {
2353 searchFilter = (copy.fund() ?
2354 {"-or": {"active": "t", "id": copy.fund()}} :
2356 searchFilter.org = fundSearchFilter.org;
2358 searchFilter = null;
2361 var readOnly = false;
2363 // TODO: Add support for changing the owning_lib after real copies have been made.
2364 // owning_lib is order data as much as its item data
2365 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
2369 // TODO: add support for changing the fund after debits have been created
2370 // Note: invoicing allows the change
2371 if(copy.fund_debit() && field == 'fund') {
2376 var widget = new openils.widget.AutoFieldWidget({
2379 labelFormat : (field == 'fund') ? fundLabelFormat : null,
2380 searchFormat : (field == 'fund') ? fundSearchFormat : null,
2381 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
2382 searchFilter : searchFilter,
2383 noCache: (field == "fund"),
2385 parentNode : dojo.query('[name='+field+']', row)[0],
2386 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2387 readOnly : readOnly,
2388 orgDefaultsToWs : true
2392 // make sure we capture the value from any async widgets
2395 if (field == "fund" && w.store)
2396 self._ensureCSSFundClasses(w.store);
2399 copy[field](ww.getFormattedValue())
2401 self.copyWidgetCache[copy.id()][field] = w;
2403 dojo.connect(w, 'onChange',
2405 if (field == "fund")
2406 self._updateFundSelectorStyle(widget, val);
2408 if (!readOnly && (copy.isnew() || val != copy[field]())) {
2409 // prevent setting ischanged() automatically on widget load for existing copies
2410 copy[field](widget.getFormattedValue())
2411 copy.ischanged(true);
2420 this.updateLidState(copy, row);
2423 this._ensureCSSFundClass = function(id) {
2424 if (!this.fundStyleSheet) {
2426 "style", {"type": "text/css"},
2427 document.getElementsByTagName("head")[0], "last"
2429 this.fundStyleSheet = document.styleSheets[
2430 document.styleSheets.length - 1
2434 var cn = "fund_" + id;
2435 if (!this.haveFundClass[cn]) {
2436 fieldmapper.standardRequest(
2437 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
2439 "params": [openils.User.authtoken, id],
2441 "oncomplete": function(r) {
2442 r = openils.Util.readResponse(r);
2443 self.fundBalanceState[id] = r;
2445 if (r[0] /* stop */)
2446 style = fundStyles.stop;
2447 else if (r[1] /* warning */)
2448 style = fundStyles.warning;
2449 self.fundStyleSheet.insertRule(
2450 "." + cn + " { " + style + " }",
2451 self.fundStyleSheet.cssRules.length
2453 self.haveFundClass[cn] = true;
2460 this._ensureCSSFundClasses = function(store) {
2462 "query": {"id": "*"},
2463 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
2467 this._updateFundSelectorStyle = function(widget, fund_id) {
2468 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
2469 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
2472 this.updateLidState = function(copy, row) {
2475 if (typeof(row) == "undefined") {
2476 row = dojo.query('tr[copy_id="' + copy.id() + '"]', this.copyTbody)[0];
2480 var recv_link = nodeByName("receive", row);
2481 var unrecv_link = nodeByName("unreceive", row);
2482 var del_link = nodeByName("delete", row);
2483 var cxl_link = nodeByName("cancel", row);
2484 var claim_link = nodeByName("claim", row);
2485 var cxl_reason_link = nodeByName("cancel_reason", row);
2487 // by default, hide all the actions
2488 openils.Util.hide(del_link.parentNode);
2489 openils.Util.hide(recv_link);
2490 openils.Util.hide(unrecv_link);
2491 openils.Util.hide(cxl_link);
2492 openils.Util.hide(claim_link);
2493 openils.Util.hide(cxl_reason_link);
2495 if (copy.id() > 0) { // real copies (LIDs)
2497 if (copy.cancel_reason()) {
2499 /* --------- cancelled -------------------------- */
2501 /* XXX the following may leak memory in a long lived table:
2502 * dijits may not get destroyed... not positive. revisit. */
2503 var holds_reason = dojo.create(
2505 "style": "border-bottom: 1px dashed #000;",
2506 "innerHTML": copy.cancel_reason().label()
2507 }, cxl_reason_link, "only"
2511 "label": "<em>" + copy.cancel_reason().label() +
2512 "</em><br />" + copy.cancel_reason().description(),
2513 "connectId": [holds_reason]
2514 }, dojo.create("span", null, cxl_reason_link, "last")
2516 openils.Util.show(cxl_reason_link, "inline");
2518 if (copy.cancel_reason().keep_debits() == 't' ) {
2519 // allow further cancellation of "delayed" copies
2521 openils.Util.show(cxl_link, "inline");
2522 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2525 } else if (copy.recv_time()) {
2527 /* --------- received -------------------------- */
2529 openils.Util.show(unrecv_link, "inline");
2530 unrecv_link.onclick = function() {
2531 if (confirm(localeStrings.UNRECEIVE_LID))
2532 self.issueReceive(copy, /* rollback */ true);
2535 } else if (this.liCache[copy.lineitem()].state() == 'on-order') {
2537 /* --------- on order -------------------------- */
2539 openils.Util.show(recv_link, 'inline');
2540 openils.Util.show(cxl_link, "inline");
2542 recv_link.onclick = function() {
2543 if (self.checkLiAlerts(copy.lineitem()))
2544 self.issueReceive(copy);
2547 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2551 /* --------- pre-order copies -------------------------- */
2553 del_link.onclick = function() { self.deleteCopy(row) };
2554 openils.Util.show(del_link.parentNode);
2560 /* --------- virtual copies -------------------------- */
2562 del_link.onclick = function() { self.deleteCopy(row) };
2563 openils.Util.show(del_link.parentNode);
2567 this.cancelLid = function(lid_id) {
2568 lidCancelDialog._lid_id = lid_id;
2569 openils.Util.show(lidCancelDialog.domNode.parentNode);
2570 lidCancelDialog.show();
2571 if (!lidCancelDialog._prepared) {
2572 var widget = new openils.widget.AutoFieldWidget({
2573 "fmField": "cancel_reason",
2574 "fmClass": "acqlid",
2575 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
2576 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2578 "searchOptions" : {order_by : {"acqcr":"label"}}
2582 acqLidCancelButton.onClick = function() {
2583 if (w.attr("value")) {
2584 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
2586 lidCancelDialog._lid_id,
2590 lidCancelDialog.hide();
2593 lidCancelDialog._prepared = true;
2599 this._cancelLid = function(lid_id, reason) {
2600 fieldmapper.standardRequest(
2601 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
2602 "params": [openils.User.authtoken, lid_id, reason],
2604 "onresponse": function(r) {
2605 if (r = openils.Util.readResponse(r)) {
2607 for (var id in r.lid) {
2608 /* actually this should only iterate once */
2609 self.copyCache[id].cancel_reason(
2610 r.lid[id].cancel_reason
2612 self.updateLidState(self.copyCache[id]);
2621 this._confirmAlert = function(li, lin) {
2623 dojo.string.substitute(
2624 localeStrings.CONFIRM_LI_ALERT, [
2625 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2626 "title", "lineitem_marc_attr_definition"
2628 /* XXX it's really better add a parameter and to adjust
2629 * the format string rather than do this concatenation
2630 * here, but if someone wants this for 2.2 in a hurry,
2631 * we can sidestep the problem of updating the strings
2632 * while the translators are working. */
2634 aou.findOrgUnit(lin.alert_text().owning_lib()).shortname() +
2636 lin.alert_text().code()
2638 lin.alert_text().description() || "",
2645 this.checkLiAlerts = function(li_id) {
2646 var li = this.liCache[li_id];
2648 var alert_notes = li.lineitem_notes().filter(
2649 function(o) { return Boolean(o.alert_text()); }
2652 /* this is _intentionally_ not done in a call to forEach() ... */
2653 for (var i = 0; i < alert_notes.length; i++) {
2654 if (this.noteAcks[alert_notes[i].id()])
2656 else if (!this._confirmAlert(li, alert_notes[i]))
2659 this.noteAcks[alert_notes[i].id()] = true;
2665 this.deleteCopy = function(row) {
2666 var copy = this.copyCache[row.getAttribute('copy_id')];
2667 copy.isdeleted(true);
2669 delete this.copyCache[copy.id()];
2670 this.copyTbody.removeChild(row);
2673 this._virtDfaCountsAsList = function() {
2675 for (var key in this.virtDfaCounts) {
2676 for (var i = 0; i < this.virtDfaCounts[key]; i++)
2682 this.confirmBreachedCopyFunds = function(copies) {
2683 var stop = 0, warning = 0;
2687 var state = self.fundBalanceState[o.fund()];
2688 if (state[0] /* stop */)
2690 else if (state[1] /* warning */)
2697 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
2698 } else if (warning) {
2699 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
2704 this.saveCopyChanges = function(liId) {
2710 for(var id in this.copyCache) {
2711 var c = this.copyCache[id];
2712 if(!c.isdeleted()) total++;
2713 if(c.isnew() || c.ischanged() || c.isdeleted()) {
2714 if(c.id() < 0) c.id(null);
2720 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
2723 if (copies.length > 0) {
2724 if (!this.confirmBreachedCopyFunds(copies))
2727 if (typeof(this._copy_count_cb) == "function")
2728 this._copy_count_cb(liId, total);
2730 openils.Util.show("acq-lit-update-copies-progress");
2731 fieldmapper.standardRequest(
2732 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
2734 params: [openils.User.authtoken, copies],
2735 onresponse: function(r) {
2736 var res = openils.Util.readResponse(r);
2737 litUpdateCopiesProgress.update(res);
2739 oncomplete: function() {
2740 self.drawCopies(liId, true /* force_fetch */);
2741 openils.Util.hide("acq-lit-update-copies-progress");
2742 refreshPOSummaryAmounts();
2748 var dfa_list = this._virtDfaCountsAsList();
2749 if (dfa_list.length > 0) {
2750 fieldmapper.standardRequest(
2752 "open-ils.acq.distribution_formula.record_application"],
2755 "params": [openils.User.authtoken, dfa_list, liId],
2756 "onresponse": function(r) {
2757 var res = openils.Util.readResponse(r);
2758 if (res && res.length < dfa_list.length)
2759 alert(localeStrings.DFA_NOT_ALL);
2763 this.virtDfaCounts = {};
2766 if (this.inlineCopiesNeedingRefresh.indexOf(liId) < 0)
2767 this.inlineCopiesNeedingRefresh.push(liId);
2770 this._updateCreatePoPrepayCheckbox = function(prepay) {
2771 var prepay = openils.Util.isTrue(prepay);
2772 this._prepayRequiredByVendor = prepay;
2773 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
2776 this._confirmPoPrepaySituation = function() {
2777 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
2778 if (want_prepay != this._prepayRequiredByVendor) {
2781 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
2782 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
2789 this.applySelectedLiAction = function(action) {
2793 case 'delete_selected':
2794 this._deleteLiList(self.getSelected());
2797 case 'add_to_order':
2798 addToPoDialog._get_li = dojo.hitch(
2801 return this.getSelected(
2802 false, null, true, li_pre_po_states);
2805 if (addToPoDialog._get_li().length == 0) {
2806 alert(localeStrings.NO_LI_GENERAL);
2809 addToPoDialog.show();
2812 case 'create_order':
2813 this._loadPOSelect();
2814 acqLitPoCreateDialog.show();
2817 case 'save_picklist':
2818 acqLitSavePlDialog.show();
2821 case 'selector_ready':
2823 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
2824 acqLitChangeLiStateDialog.show();
2832 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
2835 case 'batch_create_invoice':
2836 this.batchCreateInvoice();
2839 case 'batch_link_invoice':
2840 this.batchLinkInvoice();
2843 case 'receive_lineitems':
2844 this.receiveSelectedLineitems();
2847 case 'rollback_receive_lineitems':
2848 this.rollbackReceiveLineitems();
2851 case 'create_assets':
2852 this.showAssetCreator();
2855 case 'export_attr_list':
2856 this.chooseExportAttr();
2859 case 'batch_apply_funds':
2860 this.applyBatchLiFunds();
2863 case 'add_brief_record':
2865 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
2867 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
2871 case "cancel_lineitems":
2872 console.log('HERE');
2873 this.maybeCancelLineitems();
2876 case "apply_claim_policy":
2877 var li_list = this.getSelected();
2878 this.claimPolicyPicker.attr("value", null);
2879 liClaimPolicyDialog.show();
2880 liClaimPolicySave.onClick = function() {
2881 self.changeClaimPolicy(
2883 self.claimPolicyPicker.attr("value"),
2887 self.setClaimPolicyControl(li);
2888 self.reconsiderClaimControl(li);
2891 liClaimPolicyDialog.hide();
2899 this.changeClaimPolicy = function(li_list, value, callback) {
2901 function(li) { li.claim_policy(value); }
2903 fieldmapper.standardRequest(
2904 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
2905 "params": [openils.User.authtoken, li_list],
2907 "oncomplete": function(r) {
2908 r = openils.Util.readResponse(r);
2909 if (callback) callback(r);
2915 this.showAssetCreator = function(onAssetsCreated) {
2916 if(!this.isPO) return;
2919 // first, let's see if this PO has any LI's that need to be merged/imported
2920 self.pcrud.search('jub', {purchase_order : this.isPO, eg_bib_id : null}, {
2922 oncomplete : function(r) {
2923 var resp = openils.Util.readResponse(r);
2924 if (resp && resp.length) {
2925 // PO has some non-linked jubs.
2927 self.show('asset-creator');
2928 if(!self.vlAgent.loaded)
2929 self.vlAgent.init();
2931 dojo.connect(assetCreatorButton, 'onClick',
2932 function() { self.createAssets(onAssetsCreated) });
2936 // all jubs linked, move on to asset creation
2937 self.createAssets(onAssetsCreated, true);
2943 this.createAssets = function(onAssetsCreated, noVl) {
2944 this.show('acq-lit-progress-numbers');
2946 var vlArgs = (noVl) ? {} : {vandelay : this.vlAgent.values()};
2947 this.batchProgress = {};
2948 progressDialog.show(false);
2949 progressDialog.attr("title", localeStrings.LI_CREATING_ASSETS);
2950 fieldmapper.standardRequest(
2951 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
2953 params: [this.authtoken, this.isPO, vlArgs],
2954 onresponse: function(r) {
2955 var resp = openils.Util.readResponse(r);
2956 self._updateProgressNumbers(resp, !Boolean(onAssetsCreated), onAssetsCreated, true);
2962 this.maybeCancelLineitems = function() {
2963 openils.Util.show("acq-lit-cancel-reason", "inline");
2964 if (!acqLitCancelLineitemsButton._prepared) {
2965 var widget = new openils.widget.AutoFieldWidget({
2966 "fmField": "cancel_reason",
2968 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
2969 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2971 "searchOptions" : {order_by : {"acqcr":"label"}}
2975 acqLitCancelLineitemsButton.onClick = function() {
2976 if (w.attr("value")) {
2977 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
2978 self._cancelLineitems(w.attr("value"));
2980 openils.Util.hide("acq-lit-cancel-reason");
2983 acqLitCancelLineitemsButton._prepared = true;
2989 this._cancelLineitems = function(reason) {
2991 var li_list = this.getSelected();
2993 // canceled lineitems may be canceled again if they were
2994 // previously delayed (keep_debits = true).
2995 li_list = li_list.filter(
2998 li.state() != 'cancelled' ||
2999 li.cancel_reason().keep_debits() == 't'
3004 id_list = li_list.map(function(l) {return l.id()});
3006 if (!id_list.length) {
3007 alert(localeStrings.NO_LI_GENERAL);
3010 fieldmapper.standardRequest(
3011 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
3012 "params": [openils.User.authtoken, id_list, reason],
3014 "onresponse": function(r) {
3015 if (r = openils.Util.readResponse(r)) {
3017 for (var id in r.li) {
3018 self.liCache[id].state(r.li[id].state);
3019 self.liCache[id].cancel_reason(
3020 r.li[id].cancel_reason
3022 self.updateLiState(self.liCache[id]);
3025 if (r.lid && self.copyCache) {
3026 for (var id in r.lid) {
3027 if (self.copyCache[id]) {
3028 self.copyCache[id].cancel_reason(
3029 r.lid[id].cancel_reason
3031 self.updateLidState(self.copyCache[id]);
3041 this.chooseExportAttr = function() {
3042 if (!acqLitExportAttrSelector._li_setup) {
3044 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
3046 "data": acqlimad.toStoreData(
3048 "acqlimad", {"code": li_exportable_attrs}
3053 acqLitExportAttrSelector.setValue();
3054 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
3055 acqLitExportAttrSelector._li_setup = true;
3057 openils.Util.show("acq-lit-export-attr-holder", "inline");
3060 this.exportAttrList = function() {
3061 var attr_def = acqLitExportAttrSelector.item;
3062 var li_list = this.getSelected();
3063 var value_list = li_list.map(
3065 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
3066 attr_def.code, "lineitem_marc_attr_definition"
3069 ).filter(function(attr) { return Boolean(attr); });
3071 if (value_list.length > 0) {
3072 if (value_list.length < li_list.length) {
3074 dojo.string.substitute(
3075 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
3082 openils.XUL.contentToFileSaveDialog(
3083 value_list.join("\n"),
3084 localeStrings.EXPORT_SAVE_DIALOG_TITLE
3090 alert(dojo.string.substitute(
3091 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
3095 openils.Util.hide("acq-lit-export-attr-holder");
3098 this.printPO = function() {
3099 if(!this.isPO) return;
3100 progressDialog.show(true);
3101 fieldmapper.standardRequest(
3102 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
3104 params: [this.authtoken, this.isPO, 'html'],
3105 oncomplete: function(r) {
3106 progressDialog.hide();
3107 var evt = openils.Util.readResponse(r);
3108 if(evt && evt.template_output()) {
3109 openils.Util.printHtmlString(evt.template_output().data());
3116 this.batchCreateInvoice = function() {
3117 var liIds = this.getSelected(
3118 false, null, true /* id_list */, li_active_states)
3119 if (!liIds.length) {
3120 alert(localeStrings.NO_LI_GENERAL);
3123 var path = oilsBasePath + '/acq/invoice/view?create=1';
3124 dojo.forEach(liIds, function(li, idx) { path += '&attach_li=' + li });
3125 if (openils.XUL.isXUL())
3126 openils.XUL.newTabEasy(path, localeStrings.NEW_INVOICE, null, true);
3128 location.href = path;
3131 this.batchLinkInvoice = function(create) {
3132 var liIds = this.getSelected(
3133 false, null, true /* id_list */, li_active_states)
3134 if (!liIds.length) {
3135 alert(localeStrings.NO_LI_GENERAL);
3138 if (!self.invoiceLinkDialogManager) {
3139 self.invoiceLinkDialogManager =
3140 new InvoiceLinkDialogManager("li");
3142 self.invoiceLinkDialogManager.target = liIds;
3143 acqLitLinkInvoiceDialog.show();
3146 this.receiveSelectedLineitems = function() {
3147 var states = li_post_po_states.filter(
3148 function(s) { return s != 'received' });
3149 var li_list = this.getSelected(null, null, null, states);
3151 if (!li_list.length) {
3152 alert(localeStrings.NO_LI_GENERAL);
3156 for (var i = 0; i < li_list.length; i++) {
3157 var li = li_list[i];
3159 if (li.state() != "received" &&
3160 !this.checkLiAlerts(li.id())) return;
3163 this.show('acq-lit-progress-numbers');
3166 fieldmapper.standardRequest(
3167 ['open-ils.acq', 'open-ils.acq.lineitem.receive.batch'],
3171 li_list.map(function(li) { return li.id(); })
3173 onresponse : function(r) {
3174 var resp = openils.Util.readResponse(r);
3175 self._updateProgressNumbers(resp, true);
3181 this.issueReceive = function(obj, rollback) {
3183 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
3185 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
3187 progressDialog.show(true);
3188 fieldmapper.standardRequest(
3189 ["open-ils.acq", method], {
3191 "params": [this.authtoken, obj.id()],
3192 "onresponse": function(r) {
3193 if (r = openils.Util.readResponse(r)) {
3194 self.fetchClaimInfo(
3195 part == "lineitem" ? obj.id() : obj.lineitem(),
3197 function() { self.handleReceive(r); }
3199 progressDialog.hide();
3207 * Handles the responses from receive and rollback ML calls.
3209 this.handleReceive = function(resp) {
3212 for (var li_id in resp.li) {
3213 for (var key in resp.li[li_id])
3214 self.liCache[li_id][key](resp.li[li_id][key]);
3215 self.updateLiState(self.liCache[li_id]);
3219 if (typeof(self.poUpdateCallback) == "function")
3220 self.poUpdateCallback(resp.po);
3223 for (var lid_id in resp.lid) {
3224 for (var key in resp.lid[lid_id])
3225 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
3226 self.updateLidState(self.copyCache[lid_id]);
3232 this.rollbackReceiveLineitems = function() {
3233 var li_id_list = this.getSelected(false, null, true);
3234 if (!li_id_list.length) {
3235 alert(localeStrings.NO_LI_GENERAL);
3239 if (!confirm(localeStrings.ROLLBACK_LI_RECEIVE_CONFIRM)) return;
3241 this.show('acq-lit-progress-numbers');
3244 fieldmapper.standardRequest(
3245 ['open-ils.acq', 'open-ils.acq.lineitem.receive.rollback.batch'],
3247 params: [this.authtoken, li_id_list],
3248 onresponse : function(r) {
3249 var resp = openils.Util.readResponse(r);
3250 self._updateProgressNumbers(resp, true);
3256 this._updateProgressNumbers = function(resp, reloadOnComplete, onComplete, clearProgressDialog) {
3257 this._updateProgressDialog(resp);
3258 this.vlAgent.handleResponse(resp,
3259 function(resp, res) {
3260 if (clearProgressDialog) {
3261 progressDialog.update({ "progress": 100});
3262 progressDialog.update_message();
3263 progressDialog.hide();
3264 progressDialog.attr("title", "");
3266 if(reloadOnComplete)
3267 location.href = location.href;
3269 onComplete(resp, res);
3274 this._updateProgressDialog = function(resp) {
3275 progressDialog.update({ "progress": (resp.progress / resp.total) * 100 });
3276 var keys = ['li', 'vqbr', 'bibs', 'lid', 'debits_accrued', 'copies'];
3277 for (var i = 0; i < keys.length; i++) {
3278 if (resp[keys[i]] > (this.batchProgress[keys[i]] || 0)) {
3279 progressDialog.update_message(
3280 dojo.string.substitute(
3281 localeStrings["ACTIVATE_" + keys[i].toUpperCase() + "_PROCESSED"],
3287 this.batchProgress = resp;
3290 this._createPO = function(fields) {
3291 var wantall = (fields.create_from == "all");
3293 /* If we're a picklist or purchase order already and the user wants
3294 * all lineitems, we might have pages' worth of lineitems haven't all
3295 * been loaded yet, so getSelected() won't find them. The server,
3296 * however, should know about all our lineitems, so let's ask the
3297 * server for a complete list.
3302 true, function(list) {
3303 self._createPOFromLineitems(fields, list);
3304 }, /* id_list */ true, li_pre_po_states
3307 this._createPOFromLineitems(
3308 fields, this.getSelected(
3309 false, null, true /* id_list */, li_pre_po_states)
3314 this._createPOFromLineitems = function(fields, selected) {
3315 if (selected.length == 0) {
3316 alert(localeStrings.NO_LI_GENERAL);
3321 var po = new fieldmapper.acqpo();
3322 po.provider(this.createPoProviderSelector.attr("value"));
3323 po.ordering_agency(this.createPoAgencySelector.attr("value"));
3324 po.prepayment_required(fields.prepayment_required[0] ? true : false);
3325 var name = this.createPoNameInput.attr('value');
3326 if (name) po.name(name); // avoid name=""
3328 // if we're creating assets, delay the asset creation
3329 // until after the PO is created. This will allow us to
3330 // use showAssetCreator() directly.
3332 fieldmapper.standardRequest(
3333 ["open-ils.acq", "open-ils.acq.purchase_order.create"],
3336 openils.User.authtoken,
3337 po, {lineitems : selected}
3339 onresponse : function(r) {
3340 var resp = openils.Util.readResponse(r);
3341 if (resp.complete) {
3342 // self.isPO is needed for showAssetCreator();
3343 self.isPO = resp.purchase_order.id();
3344 var redir = oilsBasePath + "/acq/po/view/" + self.isPO;
3345 if (fields.create_assets[0]) {
3346 self.showAssetCreator(
3347 function() {location.href = redir}
3350 location.href = redir;
3359 this.batchFundWidget = null;
3361 this.applyBatchLiFunds = function() {
3363 var liIds = this.getSelected().map(function(li) { return li.id(); });
3364 if(liIds.length == 0) return; // warn?
3367 batchFundUpdateDialog.show();
3369 if(!this.batchFundWidget) {
3370 this.batchFundWidget = new openils.widget.AutoFieldWidget({
3372 selfReference : true,
3373 labelFormat : fundLabelFormat,
3374 searchFormat : fundSearchFormat,
3375 searchFilter : fundSearchFilter,
3376 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
3377 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
3378 dijitArgs : { "required": true, "labelType": "html" },
3381 this.batchFundWidget.build();
3384 dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
3385 dojo.connect(batchFundUpdateSubmit, 'onClick',
3388 // TODO: call .dry_run first to test thresholds
3389 fieldmapper.standardRequest(
3390 ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
3393 openils.User.authtoken,
3395 self.batchFundWidget.widget.attr('value')
3397 oncomplete : function(r) {
3398 var resp = openils.Util.readResponse(r);
3400 location.href = location.href;
3409 this._deleteLiList = function(list, idx) {
3410 if(idx == null) idx = 0;
3411 if(idx >= list.length) return;
3416 if (this.isPO && (li.state() == "on-order" || li.state() == "received")) {
3417 /* It makes little sense to delete a lineitem from a PO that has
3418 * already been marked 'on-order'. Especially if EDI is in use,
3419 * such a purchase order will probably have already been shipped
3420 * off to a vendor, and mucking with it at this point could leave
3421 * your data in a bad state that doesn't jive with reality.
3423 * I could see making this restriction even firmer.
3425 * I could also see adjusting the li state comparisons, extending
3426 * the comparison to the PO's state, and/or providing functions
3427 * that house the logic for comparing states in a single location.
3429 * Yes, this will be really annoying if you have selected a lot
3430 * of lineitems to cancel that have been ordered. You'll get a
3431 * confirm dialog for each one.
3434 if (!confirm(localeStrings.DEL_LI_FROM_PO)) {
3435 self._deleteLiList(list, ++idx); /* move on to next in list */
3440 fieldmapper.standardRequest(
3442 this.isPO ? 'open-ils.acq.purchase_order.lineitem.delete' : 'open-ils.acq.picklist.lineitem.delete'],
3444 params: [openils.User.authtoken, liId],
3445 oncomplete: function(r) {
3446 self.removeLineitem(liId);
3447 self._deleteLiList(list, ++idx);
3453 this.editOrderMarc = function(li) {
3455 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
3456 to true in about:config */
3458 if(openils.XUL.isXUL()) {
3459 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul','','chrome');
3461 win = window.open('/xul/server/cat/marcedit.xul','','chrome');
3465 record : {marc : li.marc(), "rtype": "bre"},
3467 label: 'Save Record', // XXX I18N
3468 func: function(xmlString) {
3470 fieldmapper.standardRequest(
3471 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
3473 params: [openils.User.authtoken, li],
3474 oncomplete: function(r) {
3475 openils.Util.readResponse(r);
3477 self.drawInfo(li.id())
3483 'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
3484 'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
3488 this._savePl = function(values) {
3490 (values.which == 'all'),
3491 function(list) { self._savePlFromLineitems(values, list); }
3495 this._savePlFromLineitems = function(values, selected) {
3496 openils.Util.show("acq-lit-generic-progress");
3498 if(values.new_name) {
3499 openils.acq.Picklist.create(
3500 {name: values.new_name},
3506 oilsBasePath + "/acq/picklist/view/" + id;
3511 } else if(values.existing_pl) {
3512 // update lineitems to use an existing picklist
3514 values.existing_pl, selected, 0,
3517 oilsBasePath + "/acq/picklist/view/" +
3524 this._updateLiState = function(values, state, state_filter) {
3525 progressDialog.show(true);
3527 (values.which == 'all'),
3529 self._updateLiStateFromLineitems(values, state, list);
3530 }, false /* id_list */, state_filter
3534 this._updateLiStateFromLineitems = function(values, state, selected) {
3535 if(!selected.length) {
3536 try { progressDialog.hide() } catch(E) {};
3537 alert(localeStrings.NO_LI_GENERAL);
3540 dojo.forEach(selected, function(li) {li.state(state);});
3541 self._updateLiList(null, selected, 0,
3542 // TODO consider inline updates for efficiency
3543 function() { location.href = location.href }
3547 this._updateLiList = function(pl, list, idx, oncomplete) {
3548 if(idx >= list.length) return oncomplete();
3550 if(pl != null) li.picklist(pl);
3551 litGenericProgress.update({maximum: list.length, progress: idx});
3552 new openils.acq.Lineitem({lineitem:li}).update(
3554 self._updateLiList(pl, list, ++idx, oncomplete);
3559 this._loadPOSelect = function() {
3560 if (!this.createPoProviderSelector) {
3561 var widget = new openils.widget.AutoFieldWidget({
3562 "fmField": "provider",
3564 "searchFilter": {"active": "t"},
3565 "parentNode": dojo.byId("acq-lit-po-provider"),
3567 "onChange": function() {
3569 self._updateCreatePoPrepayCheckbox(
3570 this.item.prepayment_required()
3576 widget.build(function(w) { self.createPoProviderSelector = w; });
3579 this.createPoCheckDupes = function() {
3580 var org = self.createPoAgencySelector.attr('value');
3581 var name = self.createPoNameInput.attr('value');
3582 openils.Util.hide('acq-dupe-po-name');
3585 acqLitCreatePoSubmit.attr('disabled', false);
3589 acqLitCreatePoSubmit.attr('disabled', true);
3590 var orgs = fieldmapper.aou.descendantNodeList(org, true);
3591 new openils.PermaCrud().search('acqpo',
3592 {name : name, ordering_agency : orgs},
3593 {async : true, oncomplete : function(r) {
3594 var po = openils.Util.readResponse(r);
3596 if (po && (po = po[0])) {
3598 var link = dojo.byId('acq-dupe-po-link');
3599 openils.Util.show('acq-dupe-po-name', 'table-row');
3600 var dupe_path = '/acq/po/view/' + po.id();
3604 if (window.IAMBROWSER) {
3605 // TODO: integration
3609 link.onclick = function() {
3611 var loc = xulG.url_prefix('XUL_BROWSER?url=') +
3612 window.encodeURIComponent(
3613 xulG.url_prefix('EG_WEB_BASE' + dupe_path)
3617 {tab_name: '', browser:false},
3620 show_nav_buttons : true,
3621 show_print_button : true,
3628 link.onclick = function() {
3629 window.open(oilsBasePath + dupe_path, '_blank').focus();
3634 acqLitCreatePoSubmit.attr('disabled', false);
3640 if (!this.createPoAgencySelector) {
3641 var widget = new openils.widget.AutoFieldWidget({
3642 "fmField": "ordering_agency",
3644 "parentNode": dojo.byId("acq-lit-po-agency"),
3645 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3647 widget.build(function(w) {
3648 self.createPoAgencySelector = w;
3649 dojo.connect(w, 'onChange', self.createPoCheckDupes);
3653 if (!this.createPoNameInput) {
3654 var widget = new openils.widget.AutoFieldWidget({
3657 "parentNode": dojo.byId("acq-lit-po-name"),
3658 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3660 widget.build(function(w) {
3661 self.createPoNameInput = w;
3662 dojo.connect(w, 'onChange', self.createPoCheckDupes);
3667 this.showRealCopyEditUI = function(li) {
3672 this._fetchLineitem(li.id(),
3674 li = self.liCache[li.id()] = fullLi;
3678 id : li.lineitem_details().map(
3679 function(item) { return item.eg_copy_id() }
3683 oncomplete : function(r) {
3685 var r_list = openils.Util.readResponse( r );
3686 for (var i = 0; i < r_list.length; i++) {
3687 var copy = r_list[i];
3688 var volId = copy.call_number();
3689 var volume = self.volCache[volId];
3691 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
3693 copy.call_number(volume);
3694 copyList.push(copy);
3697 xulG.volume_item_creator( { 'existing_copies' : copyList } );
3700 alert('error in oncomplete: ' + E);
3709 this.drawBibFinder = function(li) {
3712 var liWrapper = new openils.acq.Lineitem({lineitem:li});
3715 ['isbn', 'upc', 'issn', 'title', 'author'],
3717 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
3719 if(field == 'title' || field == 'author') {
3720 query += field +':' + val + ' ';
3722 query += 'identifier|' + field + ':' + val + ' ';
3729 oilsBasePath + '/acq/lineitem/findbib?query=' + encodeURIComponent(query),
3730 '', 'resizable,scrollbars=1,chrome');
3732 win.window.recordFound = function(bibId) {
3735 var attrs = li.attributes();
3736 li.attributes(null);
3737 li.eg_bib_id(bibId);
3739 fieldmapper.standardRequest(
3740 ["open-ils.acq", "open-ils.acq.lineitem.update"],
3742 "params": [openils.User.authtoken, li],
3744 "oncomplete": function(r) {
3745 if(openils.Util.readResponse(r)) {
3746 location.href = location.href;