1 dojo.require('dojo.date.locale');
2 dojo.require('dojo.date.stamp');
3 dojo.require('dijit.form.Button');
4 dojo.require('dijit.form.TextBox');
5 dojo.require('dijit.form.FilteringSelect');
6 dojo.require('dijit.form.Textarea');
7 dojo.require('dijit.Tooltip');
8 dojo.require('dijit.ProgressBar');
9 dojo.require('dojox.timing.doLater');
10 dojo.require('openils.acq.Lineitem');
11 dojo.require('openils.acq.PO');
12 dojo.require('openils.acq.Picklist');
13 dojo.require('openils.widget.AutoFieldWidget');
14 dojo.require('dojo.data.ItemFileReadStore');
15 dojo.require('openils.widget.ProgressDialog');
16 dojo.require('openils.PermaCrud');
17 dojo.require("openils.widget.PCrudAutocompleteBox");
18 dojo.require('dijit.form.ComboBox');
19 dojo.require('openils.CGI');
21 if (!localeStrings) { /* we can do this because javascript doesn't have block scope */
22 dojo.requireLocalization('openils.acq', 'acq');
23 var localeStrings = dojo.i18n.getLocalization('openils.acq', 'acq');
25 const XUL_OPAC_WRAPPER = 'chrome://open_ils_staff_client/content/cat/opac.xul';
26 var li_exportable_attrs = ["issn", "isbn", "upc"];
28 var fundLabelFormat = [
29 '<span class="fund_${0}">${1} (${2})</span>', 'id', 'code', 'year'
31 var fundSearchFormat = ['${0} (${1})', 'code', 'year'];
32 var fundSearchFilter = {active : 't'};
33 var fundSort = {order_by : {"acqf":"year DESC, code"}};
35 function nodeByName(name, context) {
36 return dojo.query('[name='+name+']', context)[0];
39 // for caching linked users. e.g. lineitem_detail.receiver
42 var liDetailBatchFields = ['fund', 'owning_lib', 'location', 'collection_code', 'circ_modifier', 'cn_label'];
43 var liDetailFields = liDetailBatchFields.concat(['barcode', 'note']);
45 "stop": "color: #c00; font-weight: bold;",
46 "warning": "color: #c93;"
50 * We're not using 'approved' today, but there is API support for it.
51 * I believe it's been replaced by "order-ready".
52 * LIs go new => selector-ready => order-ready/approved => pending-order =>
53 * on-order => received. 'cancelled' can pop up anywhere.
56 var li_pre_po_states = ["new", "selector-ready", "order-ready", "approved"];
57 var li_post_po_states = ["pending-order", "on-order", "received", "cancelled"];
58 var li_active_states = li_pre_po_states.concat(li_post_po_states);
60 function AcqLiTable() {
67 this.haveFundClass = {}
68 this.fundBalanceState = {};
69 this.realDfaCache = {};
70 this.virtDfaCounts = {};
73 this.claimEligibleLidByLi = {};
74 this.claimEligibleLid = {};
75 this.toggleState = false;
76 this.tbody = dojo.byId('acq-lit-tbody');
79 this.authtoken = openils.User.authtoken;
80 this.pcrud = new openils.PermaCrud();
81 this.rowTemplate = this.tbody.removeChild(dojo.byId('acq-lit-row'));
82 this.copyTbody = dojo.byId('acq-lit-li-details-tbody');
83 this.copyRow = this.copyTbody.removeChild(dojo.byId('acq-lit-li-details-row'));
84 this.copyBatchRow = dojo.byId('acq-lit-li-details-batch-row');
85 this.copyBatchWidgets = {};
86 this.liNotesTbody = dojo.byId('acq-lit-notes-tbody');
87 this.liNotesRow = this.liNotesTbody.removeChild(dojo.byId('acq-lit-notes-row'));
88 this.realCopiesTbody = dojo.byId('acq-lit-real-copies-tbody');
89 this.realCopiesRow = this.realCopiesTbody.removeChild(dojo.byId('acq-lit-real-copies-row'));
90 this._copy_fields_for_acqdf = ['owning_lib', 'location', 'fund', 'circ_modifier', 'collection_code'];
91 this.skipInitialEligibilityCheck = false;
92 this.claimDialog = new ClaimDialogManager(
93 liClaimDialog, finalClaimDialog, this.claimEligibleLidByLi,
94 function(li) { /* callback that fires when claims are made */
95 self.fetchClaimInfo(li.id(), /* force update */ true);
98 this.vlAgent = new VLAgent();
99 this.batchProgress = {};
101 if (dojo.byId('acq-lit-apply-idents')) {
102 dojo.byId('acq-lit-apply-idents').onclick = function() {
103 self.applyOrderIdentValues();
107 this.focusLineitem = new openils.CGI().param('focus_li');
109 // capture the inline copy display wrapper and row template
110 this.inlineCopyContainer =
111 this.tbody.removeChild(dojo.byId('acq-inline-copies-row'));
113 '[name=acq-li-inline-copies-tbody]', this.inlineCopyContainer)[0];
114 this.inlineCopyTemplate = tb.removeChild(
115 dojo.query('[name=acq-li-inline-copies-template]', tb)[0]);
116 this.inlineNoCopies = tb.removeChild(
117 dojo.query('[name=acq-li-inline-copies-none]', tb)[0]);
119 // list of LI IDs that should be refreshed at next display time
120 this.inlineCopiesNeedingRefresh = [];
122 dojo.byId("acq-lit-li-actions-selector").onchange = function() {
123 self.applySelectedLiAction(this.options[this.selectedIndex].value);
124 this.selectedIndex = 0;
127 acqLitCreatePoCancel.onClick = function() {
128 acqLitPoCreateDialog.hide();
130 acqLitCreatePoSubmit.onClick = function() {
131 if (!self.createPoProviderSelector.attr("value") ||
132 !self.createPoAgencySelector.attr("value")) {
133 alert(localeStrings.CREATE_PO_INVALID);
135 } else if (self._confirmPoPrepaySituation()) {
136 acqLitPoCreateDialog.hide();
137 self._createPO(acqLitPoCreateDialog.getValues());
143 acqLitSavePlButton.onClick = function() {
144 acqLitSavePlDialog.hide();
145 self._savePl(acqLitSavePlDialog.getValues());
148 acqLitCancelLiStateButton.onClick = function() {
149 acqLitChangeLiStateDialog.hide();
151 acqLitSaveLiStateButton.onClick = function() {
152 acqLitChangeLiStateDialog.hide();
153 var state = acqLitChangeLiStateDialog.attr('state');
154 var state_filter = ['new'];
155 if (state == 'order-ready')
156 state_filter.push('selector-ready');
158 acqLitChangeLiStateDialog.getValues(), state, state_filter);
162 dojo.byId('acq-lit-select-toggle').onclick = function(){self.toggleSelect()};
163 dojo.byId('acq-inline-copies-toggle').onclick = function(){self.toggleInlineCopies()};
164 dojo.byId('acq-lit-info-back-button').onclick = function(){self.show('list')};
165 dojo.byId('acq-lit-copies-back-button').onclick = function(){self.show('list')};
166 dojo.byId('acq-lit-notes-back-button').onclick = function(){self.show('list')};
167 dojo.byId('acq-lit-real-copies-back-button').onclick = function(){self.show('list')};
169 this.setFundSearchFilter = function(callback) {
170 new openils.User().getPermOrgList(
171 ['CREATE_PURCHASE_ORDER', 'MANAGE_FUND'],
173 fundSearchFilter.org = orgs;
174 if (callback) callback();
176 true, true // descendants, id_list
180 this.afwCopyFieldArgs = function(field, perms) {
184 "labelFormat": (field == 'fund') ? fundLabelFormat : null,
185 "searchFormat": (field == 'fund') ? fundSearchFormat : null,
186 "searchFilter": (field == 'fund') ? fundSearchFilter : null,
187 "searchOptions": (field == 'fund') ? fundSort : null,
188 "orgLimitPerms": (field == 'location') ? ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'] : [perms],
191 "labelType": (field == "fund") ? "html" : null
193 "noCache": (field == "fund"),
198 /* This is the "new" batch updater that sits atop all lineitems. It does
199 * use this.afwCopyFieldArgs() to borrow a little common code from the
200 * "old" batch updater atop the copy details view. */
201 this.initBatchUpdater = function(disabled_fields) {
202 openils.Util.show("acq-batch-update", "table");
204 if (!dojo.isArray(disabled_fields)) disabled_fields = [];
206 /* Note that this will directly contain dijits, not the AutoWidget
208 this.batchUpdateWidgets = {};
210 this.batchUpdateWidgets.item_count = new dijit.form.TextBox(
212 "style": {"width": "3em"},
214 dojo.indexOf(disabled_fields, "item_count") != -1
220 (new openils.widget.AutoFieldWidget({
222 "selfReference": true,
223 "dijitArgs": { "required": false },
225 "parentNode": "acq-bu-distribution_formula"
228 dojo.style(w.domNode, {"width": "12em"});
229 /* dijitArgs to AutoFieldWidget won't work for 'disabled' */
232 dojo.indexOf(disabled_fields, "distribution_formula") != -1
234 self.batchUpdateWidgets.distribution_formula = w;
238 function buildOneBatchWidget(field, args) {
239 (new openils.widget.AutoFieldWidget(args)).build(
241 if (field == "fund") {
243 w, "onChange", function(val) {
244 self._updateFundSelectorStyle(aw, val);
248 self._ensureCSSFundClasses(w.store);
251 dojo.style(w.domNode, {"width": "10em"});
254 dojo.indexOf(disabled_fields, field) != -1
256 self.batchUpdateWidgets[field] = w;
262 ["owning_lib","location","collection_code","circ_modifier","fund"],
264 var args = self.afwCopyFieldArgs(field,"CREATE_PURCHASE_ORDER");
265 args.parentNode = dojo.byId("acq-bu-" + field);
267 if (field == 'fund') {
268 // The list of funds can be huge. Before fetching
269 // funds for PO modification, see where the user has
270 // perms and limit the retreived funds accordingly.
271 // Note: This is the first instance of fund list
272 // retrieval. All future fund list retrievals will
273 // benefit directly from having applied the fund
274 // search filter org units here.
275 self.setFundSearchFilter(function() {
276 buildOneBatchWidget(field, args);
281 buildOneBatchWidget(field, args);
285 acqBatchUpdateApply.onClick = function() {
286 var li_id_list = self.getSelected(false, null, true /* id list */);
287 if (!li_id_list.length) {
288 alert(localeStrings.NO_LI_TO_UPDATE);
292 progressDialog.show(true);
293 progressDialog.attr("title", localeStrings.LI_BATCH_UPDATE);
294 progressDialog.update({"maximum": li_id_list.length,"progress": 0});
298 var params = [ self.authtoken, {"lineitems": li_id_list},
299 self.batchUpdateChanges(), self.batchUpdateFormula() ];
300 console.log("batch update params: " + dojo.toJson(params));
302 fieldmapper.standardRequest(
303 ["open-ils.acq", "open-ils.acq.lineitem.batch_update"], {
306 "onresponse": function(r) {
307 if ((r = openils.Util.readResponse(r))) { // assignment
308 progressDialog.update({"progress": ++count});
310 progressDialog.hide();
311 progressDialog.attr("title", "");
314 "oncomplete": function() {
315 /* XXX Is the last call to onresponse guaranteed to
316 * finish before oncomplete is fired? */
317 if (count != li_id_list.length) {
318 console.error("lineitem batch update operation failed");
319 progressDialog.hide();
320 progressDialog.attr("title", "");
322 location.href = location.href;
330 this.batchUpdateChanges = function() {
334 openils.Util.objectProperties(this.batchUpdateWidgets),
336 if (k == "distribution_formula") return; /* handled elsewhere */
337 if (self.batchUpdateWidgets[k].attr("disabled")) return;
339 /* It's important that a value of "" should mean that a field
340 * doesn't get used in the arguments to the batch updater API,
341 * but 0 should mean an actual 0. */
342 var value = self.batchUpdateWidgets[k].attr("value");
351 this.batchUpdateFormula = function() {
352 if (this.batchUpdateWidgets.distribution_formula.attr("disabled")) {
356 this.batchUpdateWidgets.distribution_formula.attr("value") ||
362 this.reset = function(keep_selectors) {
363 while(self.tbody.childNodes[0])
364 self.tbody.removeChild(self.tbody.childNodes[0]);
373 this.setNext = function(handler) {
374 var link = dojo.byId('acq-lit-next');
376 dojo.style(link, 'visibility', 'visible');
377 link.onclick = handler;
379 dojo.style(link, 'visibility', 'hidden');
383 this.setPrev = function(handler) {
384 var link = dojo.byId('acq-lit-prev');
386 dojo.style(link, 'visibility', 'visible');
387 link.onclick = handler;
389 dojo.style(link, 'visibility', 'hidden');
393 this.enableActionsDropdownOptions = function(mask) {
394 /* 'mask' is probably a misnomer the way I'm using it, but it needs to
395 * be one of pl,po,ao,gs,vp, or fs. */
396 dojo.query("option", "acq-lit-li-actions-selector").forEach(
398 var opt_mask = dojo.attr(option, "mask");
400 /* For each <option> element, an empty or non-existent mask
401 * attribute, a mask attribute of "*", or a mask attribute that
402 * matches this method's argument should result in that
403 * option's being enabled. */
405 option, "disabled", !(
408 opt_mask.search(mask) != -1
416 * Ensures this.focusLineitem is in view and causes a brief
417 * border around the lineitem to come to life then fade.
419 this.focusLi = function() {
420 if (!this.focusLineitem) return;
422 // set during addLineitem()
423 var node = dojo.byId('li-title-ref-' + this.focusLineitem);
425 // LI may not yet be rendered
428 // prevent numerous re-focuses
429 this.focusLineitem = null;
431 // causes the full row to be visible
432 dijit.scrollIntoView(node);
435 dojo.query('[attr=title]', node)[0].focus();
437 dojo.require('dojox.fx');
441 dojox.fx.highlight({color : '#BB4433', node : node, duration : 2000}).play();
446 this.show = function(div) {
447 openils.Util.hide('acq-lit-table-div');
448 openils.Util.hide('acq-lit-info-div');
449 openils.Util.hide('acq-lit-li-details');
450 openils.Util.hide('acq-lit-notes-div');
451 openils.Util.hide('acq-lit-real-copies-div');
452 openils.Util.hide('acq-lit-asset-creator');
455 openils.Util.show('acq-lit-table-div');
457 this.refreshInlineCopies();
460 openils.Util.show('acq-lit-info-div');
463 openils.Util.show('acq-lit-li-details');
466 openils.Util.show('acq-lit-real-copies-div');
469 openils.Util.show('acq-lit-notes-div');
471 case 'asset-creator':
472 openils.Util.show('acq-lit-asset-creator');
476 openils.Util.show(div);
480 this.hide = function() {
484 this.toggleSelect = function() {
486 dojo.forEach(self.selectors, function(i){i.checked = false});
488 dojo.forEach(self.selectors, function(i){i.checked = true});
489 self.toggleState = !self.toggleState;
493 this.getAll = function(callback, id_only, state) {
494 /* For some uses of the li table, we may not really know about "all"
495 * the lineitems that the user thinks we know about. If we're a paged
496 * picklist, for example, we only know about the lineitems we've
497 * displayed, but not necessarily all the lineitems on the picklist.
498 * So we reach out to pcrud to inform us.
499 * state: string/array. only lineitems in one of these states are
500 * included in the final result set. Not currently supported for
504 var oncomplete = function(r) {
505 var id_list = openils.Util.readResponse(r);
509 self.fetchLineitemsById(id_list, callback);
513 var search = {"picklist": this.isPL};
514 if (state) search.state = state;
517 "id_list": true, /* sic, even if id_only */
519 "oncomplete": oncomplete
523 } else if (this.isPO) {
524 var search = {"purchase_order": this.isPO};
525 if (state) search.state = state;
530 "oncomplete": oncomplete
534 } else if (this.isUni && this.pager) {
535 this.pager.getAllLineitemIDs(oncomplete);
539 /* If execution reaches this point, we don't need or can't perform
540 * any special tricks to find out the "real" list of "all" lineitems
541 * in this context, so we fall back to the old method.
543 callback(this.getSelected(true, null, id_only, state));
546 /** @param all If true, assume all are selected */
547 this.getSelected = function(
549 callback /* If you want a "good" idea of "all" lineitems, you must
550 provide a callback that accepts an array parameter, rather than
551 relying on the return value of this method itself. */,
555 console.log("getSelected states = " + state);
557 return this.getAll(callback, id_only, state);
559 var indices = {}; /* use to uniqify. needed in paging situations. */
560 dojo.forEach(this.selectors,
563 indices[i.parentNode.parentNode.getAttribute('li')] = true;
567 var result = openils.Util.objectProperties(indices);
569 // caller provided a lineitem state filter. remove IDs for lineitems
570 // not in the selected state.
573 if (!dojo.isArray(state)) state = [state];
574 dojo.forEach(result, function(liId) {
575 console.log('filter LI state ' + self.liCache[liId].state());
576 if (state.indexOf(self.liCache[liId].state()) >= 0)
583 result = result.map(function(liId) { return self.liCache[liId]; });
591 this.setRowAttr = function(td, liWrapper, field, type) {
592 var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
593 td.appendChild(document.createTextNode(val));
596 this.setClaimPolicyControl = function(li, row) {
597 if (!self._claimPolicyPickerLoading) {
598 self._claimPolicyPickerLoading = true;
600 new openils.widget.AutoFieldWidget({
601 "parentNode": "acq-lit-li-claim-policy",
603 "selfReference": true,
604 "dijitArgs": {"required": true}
606 function(w) { self.claimPolicyPicker = w; }
610 /* dojox.timing.doLater() is the best thing ever. Resource not yet
611 * ready? Just repeat my whole method when it is. */
612 if (dojox.timing.doLater(self.claimPolicyPicker)) {
616 row = self._findLiRow(li);
618 if (li.claim_policy()) {
619 /* This Dojo data dance is necessary to get a whole fieldmapper
620 * object based on a claim policy ID, since we alreay have the
621 * widget thing loaded with all that data, and can thereby
622 * avoid another request to the server. */
623 self.claimPolicyPicker.store.fetchItemByIdentity({
624 "identity": li.claim_policy(),
625 "onItem": function(a) {
626 var policy = (new acqclp()).fromStoreItem(a);
627 var span = nodeByName("claim_policy", row);
628 var inner = nodeByName("claim_policy_name", row);
630 openils.Util.show(span, "inline");
631 inner.innerHTML = policy.name();
633 "onError": function(e) {
638 openils.Util.hide(nodeByName("claim_policy", row));
639 nodeByName("claim_policy_name", row).innerHTML = "";
644 this.fetchClaimInfo = function(liId, force, callback, row) {
646 liId, function(full) {
647 self.liCache[full.id()] = full;
648 self.checkClaimEligibility(full, callback, row);
653 // fetch an updated copy of the lineitem
654 // and add it back to the lineitem table
655 this.refreshLineitem = function(li, focus) {
657 this._fetchLineitem(li.id(),
660 self.focusLineitem = li.id();
662 self.focusLineitem = null;
664 var row = dojo.query('[li='+li.id()+']', self.tbody)[0];
665 var nextSibling = row.nextSibling;
666 self.tbody.removeChild(row);
667 self.addLineitem(newLi, false, nextSibling);
673 * Inserts a single lineitem into the growing table of lineitems
674 * @param {Object} li The lineitem object to insert
676 this.addLineitem = function(li, skip_final_placement, nextSibling) {
677 this.liCache[li.id()] = li;
679 // insert the row right away so that final order isn't
680 // dependent on how long subsequent async request take
681 // for a given line item
682 var row = self.rowTemplate.cloneNode(true);
683 if (!skip_final_placement) {
685 // either no nextSibling was provided or it was null
686 // meaning the row was already at the end of the table
687 self.tbody.appendChild(row);
689 self.tbody.insertBefore(row, nextSibling);
693 self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
695 // sort the lineitem notes on edit_time
696 if(!li.lineitem_notes()) li.lineitem_notes([]);
698 var liWrapper = new openils.acq.Lineitem({lineitem:li});
699 row.setAttribute('li', li.id());
700 var tds = dojo.query('[attr]', row);
701 dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
702 dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
704 // so we can scroll to it later
705 dojo.query('[name=bib-info-cell]', row)[0].id = 'li-title-ref-' + li.id();
708 liWrapper.findAttr("isbn", "lineitem_marc_attr_definition") ||
709 liWrapper.findAttr("upc", "lineitem_marc_attr_definition");
711 // XXX media prefix for added content
713 nodeByName("jacket", row).setAttribute(
714 "src", "/opac/extras/ac/jacket/small/" + identifier
718 nodeByName("liid", row).innerHTML += li.id();
720 var exist = nodeByName('li_existing_count', row);
721 fieldmapper.standardRequest(
722 ['open-ils.acq', 'open-ils.acq.lineitem.existing_copies.count'],
724 params: [this.authtoken, li.id()],
725 oncomplete : function(r) {
726 var count = openils.Util.readResponse(r);
727 exist.innerHTML = count;
728 if (Number(count) > 0) {
729 openils.Util.addCSSClass(
730 exist, 'acq-existing-count-warn');
734 label : dojo.string.substitute(
735 localeStrings.LI_EXISTING_COPIES, [count])
742 openils.Util.show(nodeByName('catalog', row), 'inline');
743 nodeByName("catalog_link", row).onclick = this.generateMakeRecTab(li.eg_bib_id());
745 openils.Util.show(nodeByName('link_to_catalog', row), 'inline');
746 nodeByName("link_to_catalog_link", row).onclick = function() { self.drawBibFinder(li) };
749 if (li.queued_record()) {
750 this.pcrud.retrieve('vqbr', li.queued_record(),
752 oncomplete : function(r) {
753 var qrec = openils.Util.readResponse(r);
754 openils.Util.show(nodeByName('queue', row), 'inline');
755 var link = nodeByName("queue_link", row);
756 link.onclick = function() {
757 // open a new tab to the vandelay queue for this record
758 openils.XUL.newTabEasy(
759 oilsBasePath + '/vandelay/vandelay?qtype=bib&qid=' + qrec.queue()
767 nodeByName("worksheet_link", row).href =
768 oilsBasePath + "/acq/lineitem/worksheet/" + li.id() +
769 '?source=' + encodeURIComponent(location.pathname + location.search)
771 nodeByName("show_requests_link", row).href =
772 oilsBasePath + "/acq/picklist/user_request?lineitem=" + li.id() +
773 '?source=' + encodeURIComponent(location.pathname + location.search)
775 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
776 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
777 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
778 dojo.query('[name=expand_inline_copies]', row)[0].onclick =
779 function() {self.drawInlineCopies(li.id())};
782 if (sum = li.order_summary()) { // assignment
783 // Only show the paid label if at least one copy is invoiced.
784 // In other words, a lineitem whose every copy is canceled
786 if (sum.invoice_count() > 0) {
787 if (sum.item_count() == (
788 sum.invoice_count() + sum.cancel_count())) {
789 // Lineitem is fully paid. Display the paid-off label
790 openils.Util.show(nodeByName('paid', row), 'inline');
795 this.drawOrderIdentSelector(li, row);
797 if (!this.skipInitialEligibilityCheck)
801 function(full) { self.setClaimPolicyControl(full, row) },
805 this.updateLiNotesCount(li, row);
807 // show which PO this lineitem is a member of
808 if(li.purchase_order() && !this.isPO) {
810 this.poCache[li.purchase_order()] =
811 this.poCache[li.purchase_order()] ||
812 fieldmapper.standardRequest(
813 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
815 this.authtoken, li.purchase_order(), {
816 "flesh_price_summary": true,
817 "flesh_provider" : true,
818 "flesh_lineitem_count": true
821 if(po && !this.isMeta) {
822 openils.Util.show(nodeByName('po', row), 'inline');
823 var link = nodeByName('po_link', row);
824 link.setAttribute('href', oilsBasePath +
825 '/acq/po/view/' + li.purchase_order() +
826 '?focus_li=' + li.id() +
827 '&source=' + encodeURIComponent(location.pathname + location.search)
829 link.innerHTML += po.name();
831 openils.Util.show(nodeByName('pro', row), 'inline');
832 link = nodeByName('pro_link', row);
833 link.setAttribute('href', oilsBasePath + '/conify/global/acq/provider/' + po.provider().id())
834 link.innerHTML += po.provider().code();
838 // show which picklist this lineitem is a member of
839 if(li.picklist() && (this.isPO || this.isMeta || this.isUni)) {
841 this.plCache[li.picklist()] =
842 this.plCache[li.picklist()] ||
843 fieldmapper.standardRequest(
844 ['open-ils.acq', 'open-ils.acq.picklist.retrieve.authoritative'],
845 {params: [this.authtoken, li.picklist()]});
847 if (pl.name() == "") {
848 openils.Util.show(nodeByName("bib_origin", row), "inline");
852 openils.Util.show(nodeByName('pl', row), 'inline');
853 var link = nodeByName('pl_link', row);
854 link.setAttribute('href', oilsBasePath +
855 '/acq/picklist/view/' + li.picklist() +
856 '?focus_li=' + li.id() +
857 '&source=' + encodeURIComponent(location.pathname + location.search)
859 link.innerHTML += pl.name();
864 var countNode = nodeByName('count', row);
865 var count = li.item_count() || 0;
866 if (typeof(this._copy_count_cb) == "function") {
867 this._copy_count_cb(li.id(), count);
869 countNode.innerHTML = count;
870 countNode.id = 'acq-lit-copy-count-label-' + li.id();
873 var priceInput = dojo.query('[name=price]', row)[0];
874 priceInput.value = li.estimated_unit_price() || '';
875 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
877 // show either "mark received" or "unreceive" as appropriate
878 this.updateLiState(li, row);
880 if (skip_final_placement) {
884 // the last LI may be rendered after the call to show('list'),
885 // so make sure it's focused if necessary.
886 if (this.focusLineitem == li.id())
890 this._liCountClaims = function(li) {
892 for (var i = 0; i < li.lineitem_details().length; i++)
893 total += li.lineitem_details()[i].claims().length;
897 this._findLiRow = function(li) {
898 return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
901 this.reconsiderClaimControl = function(li, row) {
902 if (!row) row = this._findLiRow(li);
903 var option = nodeByName("action_manage_claims", row);
904 var eligible = this.claimEligibleLidByLi[li.id()].length;
905 var count = this._liCountClaims(li);
907 option.disabled = !(count || eligible);
909 dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
910 option.onclick = function() { self.claimDialog.show(li); };
913 this.clearEligibility = function(li) {
914 this.claimEligibleLidByLi[li.id()] = [];
916 if (li.lineitem_details()) {
917 li.lineitem_details().forEach(
918 function(lid) { delete self.claimEligibleLid[lid.id()]; }
922 if (this.copyCache) {
924 for (var k in this.copyCache) {
925 if (this.copyCache[k].lineitem() == li.id())
929 function(k) { delete self.claimEligibleLid[k]; }
934 this.applyOrderIdentValues = function() {
935 this._identValuesInFlight =
936 openils.Util.objectProperties(this.liCache).length;
937 for (var liId in this.liCache) {
938 this._applyOrderIdentValue(this.liCache[liId]);
942 // returns true if request was sent
943 this._applyOrderIdentValue = function(li, oncomplete) {
946 console.log('applying ident value for lineitem ' + li.id());
949 var row = dojo.query('[li=' + li.id() + ']')[0];
951 // find the selected ident value
952 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
953 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
954 var name = typeSel.options[typeSel.selectedIndex].value;
955 var val = typeSel._cbox.attr('value');
957 console.log("selected ident is " + val);
959 // it differs from the existing ident value, update it
960 var oldIdent = self.getLiOrderIdent(li);
962 oldIdent.attr_name() == name &&
963 oldIdent.attr_value() == val) {
964 console.log('selected ident attr matches existing attr');
965 if (--this._identValuesInFlight == 0) {
966 if (oncomplete) oncomplete(li);
967 else location.href = location.href;
972 // see if the selected ident value is represented
973 // by an existing lineitem attr
976 typeSel._cbox.store.fetch({
977 query : {attr_value : val},
978 onItem : function(item) {
979 console.log('found existing attr for ident value');
980 args.source_attr_id = li.attributes().filter(
981 function(attr) { return attr.id() == item.id[0] }
987 if (!args.source_attr_id) {
988 // user entered new text in the combobox
989 // so we need to create a new attr
990 console.log('creating new ident attr');
991 args.lineitem_id = li.id();
992 args.attr_name = name;
993 args.attr_value = val;
996 fieldmapper.standardRequest(
997 ['open-ils.acq', 'open-ils.acq.lineitem.order_identifier.set'],
999 params : [openils.User.authtoken, args],
1000 oncomplete : function() {
1001 console.log('order_ident oncomplete');
1002 if (--self._identValuesInFlight == 0) {
1003 if (oncomplete) oncomplete(li);
1004 else location.href = location.href;
1006 console.log(self._identValuesInFlight + ' still in flight');
1014 this.getLiOrderIdent = function(li) {
1015 var attrs = li.attributes();
1016 if (!attrs) return null;
1017 return attrs.filter(
1020 attr.attr_type() == 'lineitem_local_attr_definition' &&
1021 openils.Util.isTrue(attr.order_ident())
1027 this.drawOrderIdentSelector = function(li, row) {
1029 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
1030 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
1032 var attrs = li.attributes();
1034 // limit to MARC attr defs
1035 attrs = attrs.filter(
1037 return (attr.attr_type() == 'lineitem_marc_attr_definition');
1041 var identAttr = this.getLiOrderIdent(li);
1044 // collect the values for each type of identifier
1045 // find a reasonable default identifier type to render
1049 dojo.forEach(['isbn', 'upc', 'issn'],
1052 // collect the values for this attr name
1053 values[name] = attrs.filter(
1055 return (attr.attr_name() == name)
1059 // select a reasonable default name in the type-selector
1063 if (identAttr.attr_name() == name)
1065 } else if (values[name].length) {
1070 dojo.forEach(typeSel.options, function(opt) {
1071 if (opt.value == name) {
1072 opt.selected = true;
1081 function updateOrderIdent(val) {
1082 self._identValuesInFlight = 1;
1083 self._applyOrderIdentValue(
1086 self.refreshLineitem(li);
1091 // replace the ident combobox with a new
1092 // one for the selected ident type
1093 function changeComboBox(sel) {
1094 var name = sel.options[sel.selectedIndex].value;
1096 var td = dojo.query('[name=order_ident_value]', row)[0];
1097 if (td.childNodes[0])
1098 dojo.destroy(td.childNodes[0]);
1100 var store = new dojo.data.ItemFileWriteStore({
1101 data : acqlia.toStoreData(values[name])
1104 var cbox = new dijit.form.ComboBox(
1106 labelAttr : 'attr_value',
1107 searchAttr : 'attr_value'
1109 dojo.create('div', {}, td)
1114 // set the value for the cbox
1115 if (values[name].length) {
1116 var orderIdent = self.getLiOrderIdent(li);
1118 if (orderIdent && orderIdent.attr_name() == name) {
1119 cbox.attr('value', orderIdent.attr_value());
1121 cbox.attr('value', values[name][0].attr_value());
1125 if (!self.orderIdentAllowed)
1126 cbox.attr('disabled', true);
1129 cbox._lineitem = li;
1130 dojo.connect(cbox, 'onChange', updateOrderIdent);
1133 changeComboBox(typeSel); // force the initial draw
1134 typeSel.onchange = function() {changeComboBox(typeSel)};
1137 this.testOrderIdentPerms = function(org, callback) {
1139 new openils.User().getPermOrgList(
1140 'ACQ_SET_LINEITEM_IDENTIFIER',
1142 console.log('found orgs = ' + orgs);
1143 for (var i = 0; i < orgs.length; i++) {
1144 if (Number(orgs[i]) == Number(org)) {
1145 self.orderIdentAllowed = true;
1146 if (callback) callback();
1150 if (callback) callback();
1156 this.checkClaimEligibility = function(li, callback, row) {
1157 /* Assume always eligible, i.e. from this interface we don't care about
1158 * claim eligibility any more. this is where the user would force a
1160 this.clearEligibility(li);
1161 this.claimEligibleLidByLi[li.id()] = li.lineitem_details().map(
1162 function(lid) { return lid.id(); }
1164 li.lineitem_details().forEach(
1165 function(lid) { self.claimEligibleLid[lid.id()] = true; }
1167 this.reconsiderClaimControl(li, row);
1168 if (callback) callback(li);
1170 this.clearEligibility(li);
1171 fieldmapper.standardRequest(
1172 ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
1173 "params": [openils.User.authtoken, {"lineitem": li.id()}],
1175 "onresponse": function(r) {
1176 if (r = openils.Util.readResponse(r)) {
1177 self.claimEligibleLidByLi[li.id()].push(
1180 self.claimEligibleLid[r.lineitem_detail()] = true;
1183 "oncomplete": function() {
1184 self.reconsiderClaimControl(li, row);
1185 if (typeof(callback) == "function")
1193 this.updateLiNotesCount = function(li, row) {
1194 if (!row) row = this._findLiRow(li);
1196 var has_notes = (li.lineitem_notes().filter(
1197 function(o) { return Boolean (o.alert_text()); }
1200 /* U+2691 is the code point for a filled-in flag character */
1201 nodeByName("notes_alert_flag", row).innerHTML =
1202 has_notes ? "⚑" : "";
1203 nodeByName("noteslink", row).style.fontStyle =
1204 has_notes ? "italic" : "normal";
1205 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
1208 /* XXX NOT related to _updateLiState(). rethink */
1209 this.updateLiState = function(li, row) {
1210 if (!row) row = this._findLiRow(li);
1212 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
1213 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
1215 // always allow access to LI history
1216 nodeByName('action_view_history', row).onclick =
1217 function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
1219 /* handle row coloring for based on LI state */
1220 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1221 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
1223 // Expose invoice actions for any lineitem that is linked to a PO
1224 if (li.purchase_order()) {
1225 openils.Util.show(nodeByName("invoices_span", row), "inline");
1226 var link = nodeByName("invoices_link", row);
1227 link.onclick = function() {
1228 openils.XUL.newTabEasy(
1229 oilsBasePath + "/acq/search/unified?so=" +
1230 base64Encode({"jub":[{"id": li.id()}]}) + "&rt=invoice"
1238 * If we haven't fleshed the lineitem_details, default to allowing access to the
1239 * holdings maintenence actions. The alternative is to flesh LIDs on every lineitem,
1240 * but that will add to page render time. Let's see if this will suffice...
1242 var lids = li.lineitem_details();
1244 (lids && !lids.filter(function(lid) { return lid.eg_copy_id() })[0] )) {
1246 actUpdateBarcodes.disabled = false;
1247 actUpdateBarcodes.onclick = function() {
1248 self.showRealCopyEditUI(li);
1249 nodeByName("action_none", row).selected = true;
1251 actHoldingsMaint.disabled = false;
1252 actHoldingsMaint.onclick =
1253 self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
1256 var state_cell = nodeByName("li_state_" + li.state(), row);
1258 // re-hide any state label nodes which may have been un-hidden
1259 // through previous actions.
1260 dojo.query('[state-label]', row).forEach(function(node) {
1261 openils.Util.hide(node)
1264 if (li.state() == 'cancelled') {
1265 if(typeof li.cancel_reason() == "object") {
1267 // clear the stock "Canceled" label, since we have more
1268 // information to replace it with.
1269 state_cell.innerHTML = '';
1271 var holds_state = dojo.create(
1273 "style": "border-bottom: 1px dashed #000;",
1274 "innerHTML": li.cancel_reason().label()
1275 }, state_cell, "only"
1279 "label": "<em>" + li.cancel_reason().label() +
1280 "</em><br />" + li.cancel_reason().description(),
1281 "connectId": [holds_state]
1282 }, dojo.create("span", null, state_cell, "last")
1285 if (li.cancel_reason().keep_debits() == 't') {
1286 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1287 openils.Util.addCSSClass(row, "oils-acq-li-state-delayed");
1290 console.log('li cancel_reason is un-fleshed. Please fix');
1294 openils.Util.show(state_cell);
1298 this._setAlertStore = function() {
1299 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
1301 "data": acqliat.toStoreData(
1304 "owning_lib": aou.orgNodeTrail(
1305 aou.findOrgUnit(openils.User.user.ws_ou())
1306 ).map(function(o) { return o.id(); })
1312 acqLitAlertAlertText.setValue(); /* make the store "live" */
1313 acqLitAlertAlertText._store_ready = true;
1317 * Draws and shows the lineitem notes pane
1319 this.drawLiNotes = function(li) {
1321 this.focusLineitem = li.id();
1323 if (!acqLitAlertAlertText._store_ready)
1324 this._setAlertStore();
1327 li.lineitem_notes().sort(
1329 if(a.edit_time() < b.edit_time()) return 1;
1335 while(this.liNotesTbody.childNodes[0])
1336 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
1339 acqLitCreateNoteSubmit.onClick = function() {
1340 var value = acqLitCreateNoteText.attr('value');
1342 var note = new fieldmapper.acqlin();
1345 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
1348 note.lineitem(li.id());
1350 self.updateLiNotes(li, note);
1351 acqLitCreateNoteVendorPublic.attr("checked", false);
1352 acqLitCreateNoteText.attr("value", "");
1355 acqLitCreateAlertSubmit.onClick = function() {
1356 if (!acqLitAlertAlertText.item) {
1357 alert(localeStrings.ALERT_UNSELECTED);
1361 var alert_text = new fieldmapper.acqliat().fromStoreItem(
1362 acqLitAlertAlertText.item
1364 var value = acqLitAlertNoteValue.attr("value") || "";
1366 var note = new fieldmapper.acqlin();
1368 note.lineitem(li.id());
1370 note.alert_text(alert_text);
1372 self.updateLiNotes(li, note);
1375 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
1379 * Draws a single lineitem note in the notes pane
1381 this.addLiNote = function(li, note) {
1382 if(note.isdeleted()) return;
1384 var row = self.liNotesRow.cloneNode(true);
1385 nodeByName("value", row).innerHTML = note.value();
1386 var alert_node = nodeByName("alert_code", row);
1387 if (note.alert_text()) {
1388 alert_node.innerHTML = dojo.string.substitute(
1390 aou.findOrgUnit(note.alert_text().owning_lib()).shortname(),
1391 note.alert_text().code()
1394 if (note.alert_text().description()) {
1397 "connectId": [alert_node],
1398 "label": note.alert_text().description()
1399 }, dojo.create("span", null, alert_node, "after")
1404 if (openils.Util.isTrue(note.vendor_public()))
1405 nodeByName("vendor_public", row).innerHTML =
1406 localeStrings.VENDOR_PUBLIC;
1408 nodeByName("delete", row).onclick = function() {
1409 note.isdeleted(true);
1410 self.liNotesTbody.removeChild(row);
1411 self.updateLiNotes(li);
1414 if(note.edit_time()) {
1415 nodeByName("edit_time", row).innerHTML =
1416 dojo.date.locale.format(
1417 dojo.date.stamp.fromISOString(note.edit_time()),
1418 {formatLength:'short'});
1421 self.liNotesTbody.appendChild(row);
1425 * Updates any new/changed/deleted notes on the server
1427 this.updateLiNotes = function(li, newNote) {
1433 notes = li.lineitem_notes().filter(
1435 if(note.ischanged() || note.isnew() || note.isdeleted())
1441 if(notes.length == 0) return;
1442 progressDialog.show();
1444 fieldmapper.standardRequest(
1445 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
1447 params : [this.authtoken, notes],
1448 onresponse : function(r) {
1449 var resp = openils.Util.readResponse(r);
1454 // remove the old changed notes
1456 dojo.forEach(li.lineitem_notes(),
1458 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
1462 li.lineitem_notes(list);
1465 progressDialog.hide();
1466 self.updateLiNotesCount(li);
1467 self.drawLiNotes(li);
1471 progressDialog.update(resp);
1472 var newnote = resp.note;
1474 if(!newnote.isdeleted()) {
1475 newnote.isnew(false);
1476 newnote.ischanged(false);
1477 li.lineitem_notes().push(newnote);
1484 this.updateLiPrice = function(input, li) {
1486 var price = input.value;
1487 if(Number(price) == Number(li.estimated_unit_price())) return;
1489 fieldmapper.standardRequest(
1490 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
1491 { async : false, // redundant w/ timeout
1493 params : [this.authtoken, li.id(), price],
1494 oncomplete : function(r) {
1495 openils.Util.readResponse(r);
1496 li.estimated_unit_price(price); // update local copy
1499 * If this is a PO and every visible lineitem has a price,
1500 * check again to see if this PO can be activated. Note that
1501 * every visible lineitem having a price does not guarantee it can
1502 * be activated, which is why we still make the call. Having a price
1503 * set for every visiable lineitem is just the lowest barrier to entry.
1506 var priceNodes = dojo.query('[name=price]', dojo.byId('acq-lit-tbody'));
1508 dojo.forEach(priceNodes, function(node) { if (node.value == '') allSet = false});
1509 if (allSet) checkCouldActivatePo();
1510 refreshPOSummaryAmounts();
1517 this.removeLineitem = function(liId) {
1518 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
1519 delete this.liCache[liId];
1520 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
1523 this.drawInfo = function(liId) {
1524 this.focusLineitem = liId;
1525 if (!this._isRelatedViewer) {
1526 var d = dojo.byId("acq-lit-info-related");
1527 if (!this.relCache[liId]) {
1528 fieldmapper.standardRequest(
1531 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
1534 "params": [openils.User.authtoken, liId],
1535 "onresponse": function(r) {
1536 self.relCache[liId] = openils.Util.readResponse(r);
1537 nodeByName("related_number", d).innerHTML =
1538 self.relCache[liId];
1540 self.relCache[liId] >1 ? "show" : "hide"
1546 nodeByName("related_number", d).innerHTML = this.relCache[liId];
1547 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
1552 openils.acq.Lineitem.fetchAttrDefs(
1554 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
1559 this.toggleInlineCopies = function() {
1560 // if any inline copies are not displayed,
1561 // display them all otherwise, hide them all.
1563 var displayAll = false;
1565 for (var liId in this.liCache) {
1566 if (!this.inlineCopiesVisible(liId)) {
1572 for (var liId in this.liCache) {
1573 var row = dojo.byId('acq-inline-copies-row-' + liId);
1575 if (!row || row._hidden) {
1576 this.drawInlineCopies(liId);
1578 } else { // hide all
1580 // drawInlineCopies() on a visible row will hide it.
1581 this.drawInlineCopies(liId);
1588 this.inlineCopiesVisible = function(liId) {
1589 var row = dojo.byId('acq-inline-copies-row-' + liId);
1590 return (row && !row._hidden);
1593 this.refreshInlineCopies = function(all, reFetch) {
1595 var liIds = this.inlineCopiesNeedingRefresh;
1596 if (all) liIds = openils.Util.objectProperties(liCache);
1597 liIds.forEach(function(liId) {
1598 if (self.inlineCopiesVisible(liId)) {
1599 self.drawInlineCopies(liId, reFetch); // hide
1600 self.drawInlineCopies(liId, reFetch); // re-draw
1605 // draw inline copy table. if the table is
1606 // already visible, hide the table as-is
1607 // reFetch forces a retrieval of the lineitem and
1608 // copies from the server. otherwise the locally
1609 // cached version of each is used.
1610 this.drawInlineCopies = function(liId, reFetch) {
1613 // find or create the row where the inline copies table will live
1614 var containerRow = dojo.byId('acq-inline-copies-row-' + liId);
1615 var liRow = dojo.query('[li=' + liId + ']')[0];
1617 if (!containerRow) {
1619 // build the inline copies container row and add it to
1620 // the DOM directly after the primary lineitem row
1622 containerRow = self.inlineCopyContainer.cloneNode(true);
1623 containerRow.id = 'acq-inline-copies-row-' + liId;
1625 if (liRow.nextSibling) {
1626 self.tbody.insertBefore(containerRow, liRow.nextSibling);
1628 self.tbody.appendChild(containerRow);
1633 // toggle the visible state
1634 containerRow._hidden = !containerRow._hidden;
1635 openils.Util.toggle(containerRow, 'table-row');
1637 if (containerRow._hidden) return; // hide only
1640 var handler = function(li) {
1642 var tbody = dojo.query(
1643 '[name=acq-li-inline-copies-tbody]',
1646 // reset the table before adding copy rows
1647 while (tbody.childNodes[0])
1648 tbody.removeChild(tbody.childNodes[0]);
1650 if(li.lineitem_details().length == 0) {
1652 self.inlineNoCopies.cloneNode(true));
1653 return; // no copies to show
1656 // add a row to the inline copy table for each copy
1657 dojo.forEach(li.lineitem_details(),
1659 var row = self.inlineCopyTemplate.cloneNode(true);
1660 tbody.appendChild(row);
1661 self.addInlineCopy(li, copy, row);
1666 this._fetchLineitem(liId, handler, reFetch);
1669 /** Draw read-only copy widgets for inline copies */
1670 this.addInlineCopy = function(li, copy, row) {
1673 dojo.forEach(liDetailFields,
1676 var widget = new openils.widget.AutoFieldWidget({
1679 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1680 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1681 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1683 parentNode : dojo.query('[name=' + field + ']', row)[0],
1692 /* For a given list of lineitem ids, build a list of full lineitems
1693 * re-using the fetching logic that is otherwise typical to use in this
1696 * If we've already got a lineitem in the cache, just use that.
1698 * Once we've built a list of lineitems, call callback(thatlist).
1700 this.fetchLineitemsById = function(id_list, callback) {
1701 var total = id_list.length;
1702 var result_list = [];
1704 var inner = function(li) {
1705 result_list.push(li)
1707 callback(result_list);
1710 id_list.forEach(function(id) { self._fetchLineitem(id, inner); });
1713 this._fetchLineitem = function(liId, handler, force) {
1715 var li = this.liCache[liId];
1716 if(li && li.marc() && li.lineitem_details() && !force)
1719 fieldmapper.standardRequest(
1720 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
1723 params: [self.authtoken, liId, {
1725 flesh_cancel_reason: true,
1726 flesh_li_details: true,
1728 flesh_fund_debit: true }],
1730 oncomplete: function(r) {
1731 var li = openils.Util.readResponse(r);
1732 self.liCache[liId] = li;
1739 this._drawInfo = function(li) {
1741 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
1743 if(li.eg_bib_id()) {
1744 openils.Util.hide('acq-lit-marc-order-record-label');
1745 openils.Util.hide(acqLitEditOrderMarc.domNode);
1746 openils.Util.show('acq-lit-marc-real-record-label');
1748 openils.Util.show('acq-lit-marc-order-record-label');
1749 openils.Util.show(acqLitEditOrderMarc.domNode);
1750 openils.Util.hide('acq-lit-marc-real-record-label');
1753 this.drawMarcHTML(li);
1754 this.infoTbody = dojo.byId('acq-lit-info-tbody');
1757 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
1758 while(this.infoTbody.childNodes[0])
1759 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
1761 for(var i = 0; i < li.attributes().length; i++) {
1762 var attr = li.attributes()[i];
1763 var row = this.infoRow.cloneNode(true);
1765 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
1766 var name = openils.acq.Lineitem.attrDefs[type].filter(
1768 return (a.code() == attr.attr_name());
1770 ).pop().description();
1772 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
1773 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
1774 this.infoTbody.appendChild(row);
1777 if (!this._isRelatedViewer) {
1778 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
1779 oilsBasePath + "/acq/lineitem/related/" + li.id();
1782 // if a top scroll point is defined, jump up to it here
1783 var node = dojo.byId('oils-scroll-to-top');
1784 if (node) dijit.scrollIntoView(node);
1787 this.generateMakeRecTab = function(bib_id,default_view, row) {
1789 if(openils.XUL.isXUL() && !window.IAMBROWSER) {
1792 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
1795 show_nav_buttons : true,
1796 show_print_button : true,
1797 opac_url : xulG.url_prefix('opac_rdetail|' + bib_id),
1798 default_view : default_view
1802 var url = '/eg/staff/cat/catalog/record/' + bib_id;
1803 if (default_view == 'copy_browser') {
1809 if(row) nodeByName("action_none", row).selected = true;
1813 this.drawMarcHTML = function(li) {
1814 var params = [null, true, li.marc()];
1816 params = [li.eg_bib_id(), true];
1818 fieldmapper.standardRequest(
1819 ['open-ils.search', 'open-ils.search.biblio.record.html'],
1822 oncomplete: function(r) {
1823 dojo.byId('acq-lit-marc-div').innerHTML =
1824 openils.Util.readResponse(r);
1830 this.drawCopies = function(liId, force_fetch) {
1831 this.focusLineitem = liId;
1832 if (typeof force_fetch == "undefined")
1833 force_fetch = false;
1835 var cgi = new openils.CGI();
1836 var source = cgi.param('source');
1837 if (source && source.match(/invoice/)) {
1838 // got here from the invoice page, show the 'return-to-invoice' button
1839 var cgi = new openils.CGI({url : source});
1840 cgi.param('focus_li', liId);
1841 openils.Util.show(dojo.byId('acq-lit-copies-back-to-invoice-button-wrapper'), 'inline');
1842 var button = dojo.byId('acq-lit-copies-back-to-invoice-button');
1843 button.onclick = function() { location.href = cgi.url() };
1846 openils.acq.Lineitem.fetchAndRender(liId, {},
1847 function(li, html) {
1848 dojo.byId('acq-lit-copies-li-summary').innerHTML = html;
1852 this.show('copies');
1854 this.copyCache = {};
1855 this.copyWidgetCache = {};
1856 this.oldCopyWidgetCache = {};
1857 this.virtDfaCounts = {};
1858 this.realDfaCache = {};
1861 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
1862 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
1863 acqLitCopyCountInput.attr('value', '0');
1865 if (this.isPO && PO && PO.order_date()) {
1866 // prevent adding copies to activated POs
1867 acqLitCopyCountInput.attr('disabled', true);
1868 acqLitAddCopyCount.attr('disabled', true);
1871 while(this.copyTbody.childNodes[0])
1872 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
1874 this._drawBatchCopyWidgets();
1876 this._drawDistribApplied(liId);
1878 this._fetchDistribFormulas(
1880 openils.acq.Lineitem.fetchAttrDefs(
1882 self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch);
1889 this._saveDistribAppliedTemplates = function() {
1890 if (!this._appliedDistribTemplate) {
1891 this._appliedDistribTemplate =
1892 dojo.byId("acq-lit-distrib-applied-tbody").
1893 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
1894 dojo.attr(this._appliedDistribTemplate, "id");
1898 this._drawDistribApplied = function(liId) {
1899 /* Build this table while hidden to prevent rendering artifacts */
1900 openils.Util.hide("acq-lit-distrib-applied-tbody");
1902 this._saveDistribAppliedTemplates();
1904 /* Remove any rows in the table from previous populations */
1905 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
1906 forEach(dojo.destroy);
1908 /* Unregister all dijits previously created (for some reason this isn't
1909 * covered by the above destroy calls). */
1910 dijit.registry.forEach(
1911 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
1914 /* Populate the table with our liId */
1916 fieldmapper.standardRequest(
1918 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
1921 "params": [self.authtoken, liId],
1922 "onresponse": function(r) {
1923 var dfa = openils.Util.readResponse(r);
1926 self.realDfaCache[dfa.id()] = dfa;
1927 self._drawDistribAppliedUnit(dfa);
1930 "oncomplete": function() {
1931 /* Reveal built table */
1934 "acq-lit-distrib-applied-tbody", "table-row-group"
1942 this._drawDistribAppliedUnit = function(dfa) {
1943 var new_row = false;
1944 var row = dojo.query(
1945 'tr[formula="' + dfa.formula().id() + '"]',
1946 "acq-lit-distrib-applied-tbody"
1951 row = dojo.clone(this._appliedDistribTemplate);
1952 dojo.attr(row, "formula", dfa.formula().id());
1953 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
1956 var td = dojo.query("td", row)[0];
1958 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1959 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1962 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1964 new dijit.form.Button(
1966 "onClick": function() {
1967 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1968 self.deleteDfa(dfa);
1971 /* XXX I /cannot/ make the following work in as a CSS class
1972 * for some reason. So frustrating... */
1973 "style": function(id) {
1975 "font-weight: bold; color: #c00;" :
1977 }(dfa.id()) + "margin: 0 6px;display: inline;"
1978 }, "dfa-button-" + dfa.id()
1982 "connectId": ["dfa-button-" + dfa.id()],
1983 "label": dojo.string.substitute(
1984 localeStrings.DFA_TIP, dfa.id() > 0 ? [
1985 openils.User.formalName(dfa.creator()),
1986 dojo.date.locale.format(
1987 dojo.date.stamp.fromISOString(dfa.create_time()),
1988 {"formatLength":"short"}
1990 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
1992 }, "dfa-tip-" + dfa.id()
1996 this.deleteDfa = function(dfa) {
1997 if (dfa.id() > 0) { /* real */
1998 this.pcrud.eliminate(
2001 "oncomplete": function() {
2002 self._removeDistribApplied(dfa.id());
2003 delete self.realDfaCache[dfa.id()];
2007 } else { /* virtual */
2008 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
2009 this.virtDfaCounts[dfa.formula().id()] = 0;
2010 /* hasn't been saved yet, so no need to do anything server side */
2011 this._removeDistribApplied(dfa.id());
2016 this._removeDistribApplied = function(dfaId) {
2017 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
2018 dijit.registry.forEach(
2019 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
2021 this._removeDistribAppliedEmptyRows();
2024 this._removeAllDistribAppliedVirtual = function() {
2025 /* Unregister dijits */
2026 dijit.registry.forEach(
2027 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
2029 this._removeDistribAppliedEmptyRows();
2032 this._removeDistribAppliedEmptyRows = function() {
2033 /* Remove any rows with no DFA at all */
2034 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
2036 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
2042 * Insert a new row into the distribution formula selection form
2044 this._addDistribFormulaRow = function() {
2047 if (!self.distribForms) {
2048 // no formulas, hide the form
2049 openils.Util.hide('acq-lit-distrib-formula-table');
2053 if(!this.distribFormulaTemplate)
2054 this.distribFormulaTemplate =
2055 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
2057 var row = this.distribFormulaTemplate.cloneNode(true);
2058 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
2060 this.dfSelector = new dijit.form.FilteringSelect(
2061 {"labelAttr": "dynLabel", "labelType": "html"},
2062 nodeByName("selector", row)
2064 this._updateFormulaStore();
2065 this.dfSelector.fetchProperties =
2066 {"sort": [{"attribute": "use_count", "descending": true}]};
2068 var apply = new dijit.form.Button(
2069 {"label": localeStrings.APPLY},
2070 nodeByName('set_button', row)
2073 var reset = new dijit.form.Button(
2074 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
2075 nodeByName("reset_button", row)
2078 dojo.connect(apply, 'onClick',
2080 var form_id = self.dfSelector.attr("value");
2081 if(!form_id) return;
2082 self._applyDistribFormula(form_id);
2083 reset.attr("disabled", false);
2087 dojo.connect(reset, 'onClick',
2089 self.restoreCopyFieldsBeforeDF();
2090 self.virtDfaCounts = {};
2091 self.virtDfaId = -1;
2093 self._updateFormulaStore();
2094 self._removeAllDistribAppliedVirtual();
2095 reset.attr("disabled", "true");
2102 * Applies a distrib formula to the current set of copies
2104 this._applyDistribFormula = function(formula) {
2105 if(!formula) return;
2107 formula = this.distribForms.filter(
2108 function(form) { return form.id() == formula; }
2111 var copyRows = dojo.query('tr', self.copyTbody);
2113 if (this.dfeOffset >= copyRows.length) {
2114 alert(localeStrings.OUT_OF_COPIES);
2118 var entries_applied = 0;
2120 var rowIndex = this.dfeOffset;
2121 rowIndex < copyRows.length;
2125 var row = copyRows[rowIndex];
2126 var copy_id = row.getAttribute('copy_id');
2127 var copyWidgets = this.copyWidgetCache[copy_id];
2128 var entryIndex = this.dfeOffset;
2131 // find the correct entry for the current row
2132 dojo.forEach(formula.entries(),
2135 entryIndex += e.item_count();
2136 if(entryIndex > rowIndex)
2144 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
2145 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
2148 this.saveCopyFieldsBeforeDF(copy_id);
2149 this._copy_fields_for_acqdf.forEach(
2151 if(entry[field]()) {
2152 copyWidgets[field].attr('value', (entry[field]()));
2159 if (entries_applied) {
2160 this.virtDfaCounts[formula.id()] =
2161 ++(this.virtDfaCounts[formula.id()]) || 1;
2162 this._updateFormulaStore();
2163 this._drawDistribAppliedUnit(
2165 var dfa = new acqdfa();
2166 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
2169 this.dfeOffset += entries_applied;
2174 * This function updates the DF store for the dropdown so that use_counts
2175 * can reflect DF applications from this session before they're saved
2178 this._updateFormulaStore = function() {
2179 this.dfSelector.store = new dojo.data.ItemFileReadStore(
2181 "data": self._labelFormulasWithCounts(
2182 acqdf.toStoreData(self.distribForms)
2188 this.saveCopyFieldsBeforeDF = function(copy_id) {
2190 if (!this.oldCopyWidgetCache[copy_id]) {
2191 var copyWidgets = this.copyWidgetCache[copy_id];
2193 this.oldCopyWidgetCache[copy_id] = {};
2194 this._copy_fields_for_acqdf.forEach(
2196 self.oldCopyWidgetCache[copy_id][f] =
2197 copyWidgets[f].attr("value");
2203 this.restoreCopyFieldsBeforeDF = function() {
2205 for (var copy_id in this.oldCopyWidgetCache) {
2206 this._copy_fields_for_acqdf.forEach(
2208 self.copyWidgetCache[copy_id][f].attr(
2209 "value", self.oldCopyWidgetCache[copy_id][f]
2216 this._labelFormulasWithCounts = function(store_data) {
2217 for (var key in store_data.items) {
2218 var obj = store_data.items[key];
2219 obj.use_count = Number(obj.use_count); /* needed for sorting */
2221 if (this.virtDfaCounts[obj.id])
2222 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
2224 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
2225 obj.use_count + "]</span> " + obj.name;
2231 * This method formerly would not refetch the DF formulas if they'd been
2232 * loaded already, but now it always re-fetches, since use_count changes.
2234 /** TODO: port distrib-formula selector to autofieldwidget+pcrud/dojo store */
2235 this._fetchDistribFormulas = function(onload) {
2236 fieldmapper.standardRequest(
2238 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
2241 "params": [openils.User.authtoken, 0, 500],
2242 "oncomplete": function(r) {
2243 self.distribForms = openils.Util.readResponse(r);
2244 if(!self.distribForms || self.distribForms.length == 0) {
2245 self.distribForms = [];
2247 self._addDistribFormulaRow();
2254 this._drawBatchCopyWidgets = function() {
2255 var row = this.copyBatchRow;
2256 dojo.forEach(liDetailBatchFields,
2258 if(self.copyBatchRowDrawn) {
2259 self.copyBatchWidgets[field].attr('value', null);
2261 var args = self.afwCopyFieldArgs(field, "CREATE_PICKLIST");
2262 args.parentNode = dojo.query('[name='+field+']', row)[0];
2264 var widget = new openils.widget.AutoFieldWidget(args);
2267 if (field == "fund" && w.store)
2268 self._ensureCSSFundClasses(w.store);
2269 self.copyBatchWidgets[field] = w;
2272 if (field == "fund") {
2274 widget.widget, "onChange", function(val) {
2275 self._updateFundSelectorStyle(widget, val);
2282 this.copyBatchRowDrawn = true;
2285 this.batchCopyUpdate = function() {
2287 for(var k in this.copyWidgetCache) {
2288 var cache = this.copyWidgetCache[k];
2289 dojo.forEach(liDetailBatchFields, function(f) {
2290 var newval = self.copyBatchWidgets[f].attr('value');
2291 if(newval) cache[f].attr('value', newval);
2296 this._drawCopies = function(li) {
2299 // this button sets the total number of copies for a given lineitem
2300 acqLitAddCopyCount.onClick = function() {
2301 var count = acqLitCopyCountInput.attr('value');
2304 while(self.copyCount() < count)
2307 // delete rows if necessary
2308 var diff = self.copyCount() - count;
2310 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
2311 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
2312 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
2314 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2320 if(li.lineitem_details().length > 0) {
2321 dojo.forEach(li.lineitem_details(),
2323 self.addCopy(li, copy);
2331 this.copyCount = function() {
2333 for(var id in this.copyCache) {
2334 if(!this.copyCache[id].isdeleted())
2340 this.virtCopyId = -1;
2341 this.addCopy = function(li, copy) {
2342 var row = this.copyRow.cloneNode(true);
2343 this.copyTbody.appendChild(row);
2347 copy = new fieldmapper.acqlid();
2349 copy.id(this.virtCopyId--);
2350 copy.lineitem(li.id());
2353 this.copyCache[copy.id()] = copy;
2354 row.setAttribute('copy_id', copy.id());
2355 self.copyWidgetCache[copy.id()] = {};
2357 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2359 var rcvr = copy.receiver();
2361 if (!userCache[rcvr]) {
2362 if(rcvr == openils.User.user.id()) {
2363 userCache[rcvr] = openils.User.user;
2365 userCache[rcvr] = fieldmapper.standardRequest(
2366 ['open-ils.actor', 'open-ils.actor.user.retrieve'],
2367 {params: [openils.User.authtoken, rcvr]}
2371 dojo.query('[name=receiver]', row)[0].innerHTML = userCache[rcvr].usrname();
2374 dojo.forEach(liDetailFields,
2377 if (field == "fund") {
2378 searchFilter = (copy.fund() ?
2379 {"-or": {"active": "t", "id": copy.fund()}} :
2381 searchFilter.org = fundSearchFilter.org;
2383 searchFilter = null;
2386 var readOnly = false;
2388 // TODO: Add support for changing the owning_lib after real copies have been made.
2389 // owning_lib is order data as much as its item data
2390 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
2394 // TODO: add support for changing the fund after debits have been created
2395 // Note: invoicing allows the change
2396 if(copy.fund_debit() && field == 'fund') {
2401 var widget = new openils.widget.AutoFieldWidget({
2404 labelFormat : (field == 'fund') ? fundLabelFormat : null,
2405 searchFormat : (field == 'fund') ? fundSearchFormat : null,
2406 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
2407 searchFilter : searchFilter,
2408 noCache: (field == "fund"),
2410 parentNode : dojo.query('[name='+field+']', row)[0],
2411 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2412 readOnly : readOnly,
2413 orgDefaultsToWs : true
2417 // make sure we capture the value from any async widgets
2420 if (field == "fund" && w.store)
2421 self._ensureCSSFundClasses(w.store);
2424 copy[field](ww.getFormattedValue())
2426 self.copyWidgetCache[copy.id()][field] = w;
2428 dojo.connect(w, 'onChange',
2430 if (field == "fund")
2431 self._updateFundSelectorStyle(widget, val);
2433 if (!readOnly && (copy.isnew() || val != copy[field]())) {
2434 // prevent setting ischanged() automatically on widget load for existing copies
2435 copy[field](widget.getFormattedValue())
2436 copy.ischanged(true);
2445 this.updateLidState(copy, row);
2448 this._ensureCSSFundClass = function(id) {
2449 if (!this.fundStyleSheet) {
2451 "style", {"type": "text/css"},
2452 document.getElementsByTagName("head")[0], "last"
2454 this.fundStyleSheet = document.styleSheets[
2455 document.styleSheets.length - 1
2459 var cn = "fund_" + id;
2460 if (!this.haveFundClass[cn]) {
2461 fieldmapper.standardRequest(
2462 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
2464 "params": [openils.User.authtoken, id],
2466 "oncomplete": function(r) {
2467 r = openils.Util.readResponse(r);
2468 self.fundBalanceState[id] = r;
2470 if (r[0] /* stop */)
2471 style = fundStyles.stop;
2472 else if (r[1] /* warning */)
2473 style = fundStyles.warning;
2474 self.fundStyleSheet.insertRule(
2475 "." + cn + " { " + style + " }",
2476 self.fundStyleSheet.cssRules.length
2478 self.haveFundClass[cn] = true;
2485 this._ensureCSSFundClasses = function(store) {
2487 "query": {"id": "*"},
2488 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
2492 this._updateFundSelectorStyle = function(widget, fund_id) {
2493 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
2494 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
2497 this.updateLidState = function(copy, row) {
2500 if (typeof(row) == "undefined") {
2501 row = dojo.query('tr[copy_id="' + copy.id() + '"]', this.copyTbody)[0];
2505 var recv_link = nodeByName("receive", row);
2506 var unrecv_link = nodeByName("unreceive", row);
2507 var del_link = nodeByName("delete", row);
2508 var cxl_link = nodeByName("cancel", row);
2509 var claim_link = nodeByName("claim", row);
2510 var cxl_reason_link = nodeByName("cancel_reason", row);
2512 // by default, hide all the actions
2513 openils.Util.hide(del_link.parentNode);
2514 openils.Util.hide(recv_link);
2515 openils.Util.hide(unrecv_link);
2516 openils.Util.hide(cxl_link);
2517 openils.Util.hide(claim_link);
2518 openils.Util.hide(cxl_reason_link);
2520 if (copy.id() > 0) { // real copies (LIDs)
2522 if (copy.cancel_reason()) {
2524 /* --------- cancelled -------------------------- */
2526 /* XXX the following may leak memory in a long lived table:
2527 * dijits may not get destroyed... not positive. revisit. */
2528 var holds_reason = dojo.create(
2530 "style": "border-bottom: 1px dashed #000;",
2531 "innerHTML": copy.cancel_reason().label()
2532 }, cxl_reason_link, "only"
2536 "label": "<em>" + copy.cancel_reason().label() +
2537 "</em><br />" + copy.cancel_reason().description(),
2538 "connectId": [holds_reason]
2539 }, dojo.create("span", null, cxl_reason_link, "last")
2541 openils.Util.show(cxl_reason_link, "inline");
2543 if (copy.cancel_reason().keep_debits() == 't' ) {
2544 // allow further cancellation of "delayed" copies
2546 openils.Util.show(cxl_link, "inline");
2547 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2550 } else if (copy.recv_time()) {
2552 /* --------- received -------------------------- */
2554 openils.Util.show(unrecv_link, "inline");
2555 unrecv_link.onclick = function() {
2556 if (confirm(localeStrings.UNRECEIVE_LID))
2557 self.issueReceive(copy, /* rollback */ true);
2560 } else if (this.liCache[copy.lineitem()].state() == 'on-order') {
2562 /* --------- on order -------------------------- */
2564 openils.Util.show(recv_link, 'inline');
2565 openils.Util.show(cxl_link, "inline");
2567 recv_link.onclick = function() {
2568 if (self.checkLiAlerts(copy.lineitem()))
2569 self.issueReceive(copy);
2572 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2576 /* --------- pre-order copies -------------------------- */
2578 del_link.onclick = function() { self.deleteCopy(row) };
2579 openils.Util.show(del_link.parentNode);
2585 /* --------- virtual copies -------------------------- */
2587 del_link.onclick = function() { self.deleteCopy(row) };
2588 openils.Util.show(del_link.parentNode);
2592 this.cancelLid = function(lid_id) {
2593 lidCancelDialog._lid_id = lid_id;
2594 openils.Util.show(lidCancelDialog.domNode.parentNode);
2595 lidCancelDialog.show();
2596 if (!lidCancelDialog._prepared) {
2597 var widget = new openils.widget.AutoFieldWidget({
2598 "fmField": "cancel_reason",
2599 "fmClass": "acqlid",
2600 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
2601 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2603 "searchOptions" : {order_by : {"acqcr":"label"}}
2607 acqLidCancelButton.onClick = function() {
2608 if (w.attr("value")) {
2609 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
2611 lidCancelDialog._lid_id,
2615 lidCancelDialog.hide();
2618 lidCancelDialog._prepared = true;
2624 this._cancelLid = function(lid_id, reason) {
2625 fieldmapper.standardRequest(
2626 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
2627 "params": [openils.User.authtoken, lid_id, reason],
2629 "onresponse": function(r) {
2630 if (r = openils.Util.readResponse(r)) {
2632 for (var id in r.lid) {
2633 /* actually this should only iterate once */
2634 self.copyCache[id].cancel_reason(
2635 r.lid[id].cancel_reason
2637 self.updateLidState(self.copyCache[id]);
2646 this._confirmAlert = function(li, lin) {
2648 dojo.string.substitute(
2649 localeStrings.CONFIRM_LI_ALERT, [
2650 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2651 "title", "lineitem_marc_attr_definition"
2653 /* XXX it's really better add a parameter and to adjust
2654 * the format string rather than do this concatenation
2655 * here, but if someone wants this for 2.2 in a hurry,
2656 * we can sidestep the problem of updating the strings
2657 * while the translators are working. */
2659 aou.findOrgUnit(lin.alert_text().owning_lib()).shortname() +
2661 lin.alert_text().code()
2663 lin.alert_text().description() || "",
2670 this.checkLiAlerts = function(li_id) {
2671 var li = this.liCache[li_id];
2673 var alert_notes = li.lineitem_notes().filter(
2674 function(o) { return Boolean(o.alert_text()); }
2677 /* this is _intentionally_ not done in a call to forEach() ... */
2678 for (var i = 0; i < alert_notes.length; i++) {
2679 if (this.noteAcks[alert_notes[i].id()])
2681 else if (!this._confirmAlert(li, alert_notes[i]))
2684 this.noteAcks[alert_notes[i].id()] = true;
2690 this.deleteCopy = function(row) {
2691 var copy = this.copyCache[row.getAttribute('copy_id')];
2692 copy.isdeleted(true);
2694 delete this.copyCache[copy.id()];
2695 this.copyTbody.removeChild(row);
2698 this._virtDfaCountsAsList = function() {
2700 for (var key in this.virtDfaCounts) {
2701 for (var i = 0; i < this.virtDfaCounts[key]; i++)
2707 this.confirmBreachedCopyFunds = function(copies) {
2708 var stop = 0, warning = 0;
2712 var state = self.fundBalanceState[o.fund()];
2713 if (state[0] /* stop */)
2715 else if (state[1] /* warning */)
2722 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
2723 } else if (warning) {
2724 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
2729 this.saveCopyChanges = function(liId) {
2735 for(var id in this.copyCache) {
2736 var c = this.copyCache[id];
2737 if(!c.isdeleted()) total++;
2738 if(c.isnew() || c.ischanged() || c.isdeleted()) {
2739 if(c.id() < 0) c.id(null);
2745 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
2748 if (copies.length > 0) {
2749 if (!this.confirmBreachedCopyFunds(copies))
2752 if (typeof(this._copy_count_cb) == "function")
2753 this._copy_count_cb(liId, total);
2755 openils.Util.show("acq-lit-update-copies-progress");
2756 fieldmapper.standardRequest(
2757 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
2759 params: [openils.User.authtoken, copies],
2760 onresponse: function(r) {
2761 var res = openils.Util.readResponse(r);
2762 litUpdateCopiesProgress.update(res);
2764 oncomplete: function() {
2765 self.drawCopies(liId, true /* force_fetch */);
2766 openils.Util.hide("acq-lit-update-copies-progress");
2767 refreshPOSummaryAmounts();
2773 var dfa_list = this._virtDfaCountsAsList();
2774 if (dfa_list.length > 0) {
2775 fieldmapper.standardRequest(
2777 "open-ils.acq.distribution_formula.record_application"],
2780 "params": [openils.User.authtoken, dfa_list, liId],
2781 "onresponse": function(r) {
2782 var res = openils.Util.readResponse(r);
2783 if (res && res.length < dfa_list.length)
2784 alert(localeStrings.DFA_NOT_ALL);
2788 this.virtDfaCounts = {};
2791 if (this.inlineCopiesNeedingRefresh.indexOf(liId) < 0)
2792 this.inlineCopiesNeedingRefresh.push(liId);
2795 this._updateCreatePoPrepayCheckbox = function(prepay) {
2796 var prepay = openils.Util.isTrue(prepay);
2797 this._prepayRequiredByVendor = prepay;
2798 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
2801 this._confirmPoPrepaySituation = function() {
2802 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
2803 if (want_prepay != this._prepayRequiredByVendor) {
2806 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
2807 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
2814 this.applySelectedLiAction = function(action) {
2818 case 'delete_selected':
2819 this._deleteLiList(self.getSelected());
2822 case 'add_to_order':
2823 addToPoDialog._get_li = dojo.hitch(
2826 return this.getSelected(
2827 false, null, true, li_pre_po_states);
2830 if (addToPoDialog._get_li().length == 0) {
2831 alert(localeStrings.NO_LI_GENERAL);
2834 addToPoDialog.show();
2837 case 'create_order':
2838 this._loadPOSelect();
2839 acqLitPoCreateDialog.show();
2842 case 'save_picklist':
2843 acqLitSavePlDialog.show();
2846 case 'selector_ready':
2848 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
2849 acqLitChangeLiStateDialog.show();
2857 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
2860 case 'batch_create_invoice':
2861 this.batchCreateInvoice();
2864 case 'batch_link_invoice':
2865 this.batchLinkInvoice();
2868 case 'receive_lineitems':
2869 this.receiveSelectedLineitems();
2872 case 'rollback_receive_lineitems':
2873 this.rollbackReceiveLineitems();
2876 case 'create_assets':
2877 this.showAssetCreator();
2880 case 'export_attr_list':
2881 this.chooseExportAttr();
2884 case 'batch_apply_funds':
2885 this.applyBatchLiFunds();
2888 case 'add_brief_record':
2890 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
2892 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
2896 case "cancel_lineitems":
2897 console.log('HERE');
2898 this.maybeCancelLineitems();
2901 case "apply_claim_policy":
2902 var li_list = this.getSelected();
2903 this.claimPolicyPicker.attr("value", null);
2904 liClaimPolicyDialog.show();
2905 liClaimPolicySave.onClick = function() {
2906 self.changeClaimPolicy(
2908 self.claimPolicyPicker.attr("value"),
2912 self.setClaimPolicyControl(li);
2913 self.reconsiderClaimControl(li);
2916 liClaimPolicyDialog.hide();
2924 this.changeClaimPolicy = function(li_list, value, callback) {
2926 function(li) { li.claim_policy(value); }
2928 fieldmapper.standardRequest(
2929 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
2930 "params": [openils.User.authtoken, li_list],
2932 "oncomplete": function(r) {
2933 r = openils.Util.readResponse(r);
2934 if (callback) callback(r);
2940 this.showAssetCreator = function(onAssetsCreated) {
2941 if(!this.isPO) return;
2944 // first, let's see if this PO has any LI's that need to be merged/imported
2945 self.pcrud.search('jub', {purchase_order : this.isPO, eg_bib_id : null}, {
2947 oncomplete : function(r) {
2948 var resp = openils.Util.readResponse(r);
2949 if (resp && resp.length) {
2950 // PO has some non-linked jubs.
2952 self.show('asset-creator');
2953 if(!self.vlAgent.loaded)
2954 self.vlAgent.init();
2956 dojo.connect(assetCreatorButton, 'onClick',
2957 function() { self.createAssets(onAssetsCreated) });
2961 // all jubs linked, move on to asset creation
2962 self.createAssets(onAssetsCreated, true);
2968 this.createAssets = function(onAssetsCreated, noVl) {
2969 this.show('acq-lit-progress-numbers');
2971 var vlArgs = (noVl) ? {} : {vandelay : this.vlAgent.values()};
2972 this.batchProgress = {};
2973 progressDialog.show(false);
2974 progressDialog.attr("title", localeStrings.LI_CREATING_ASSETS);
2975 fieldmapper.standardRequest(
2976 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
2978 params: [this.authtoken, this.isPO, vlArgs],
2979 onresponse: function(r) {
2980 var resp = openils.Util.readResponse(r);
2981 self._updateProgressNumbers(resp, !Boolean(onAssetsCreated), onAssetsCreated, true);
2987 this.maybeCancelLineitems = function() {
2988 openils.Util.show("acq-lit-cancel-reason", "inline");
2989 if (!acqLitCancelLineitemsButton._prepared) {
2990 var widget = new openils.widget.AutoFieldWidget({
2991 "fmField": "cancel_reason",
2993 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
2994 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2996 "searchOptions" : {order_by : {"acqcr":"label"}}
3000 acqLitCancelLineitemsButton.onClick = function() {
3001 if (w.attr("value")) {
3002 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
3003 self._cancelLineitems(w.attr("value"));
3005 openils.Util.hide("acq-lit-cancel-reason");
3008 acqLitCancelLineitemsButton._prepared = true;
3014 this._cancelLineitems = function(reason) {
3016 var li_list = this.getSelected();
3018 // canceled lineitems may be canceled again if they were
3019 // previously delayed (keep_debits = true).
3020 li_list = li_list.filter(
3023 li.state() != 'cancelled' ||
3024 li.cancel_reason().keep_debits() == 't'
3029 id_list = li_list.map(function(l) {return l.id()});
3031 if (!id_list.length) {
3032 alert(localeStrings.NO_LI_GENERAL);
3035 fieldmapper.standardRequest(
3036 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
3037 "params": [openils.User.authtoken, id_list, reason],
3039 "onresponse": function(r) {
3040 if (r = openils.Util.readResponse(r)) {
3042 for (var id in r.li) {
3043 self.liCache[id].state(r.li[id].state);
3044 self.liCache[id].cancel_reason(
3045 r.li[id].cancel_reason
3047 self.updateLiState(self.liCache[id]);
3050 if (r.lid && self.copyCache) {
3051 for (var id in r.lid) {
3052 if (self.copyCache[id]) {
3053 self.copyCache[id].cancel_reason(
3054 r.lid[id].cancel_reason
3056 self.updateLidState(self.copyCache[id]);
3066 this.chooseExportAttr = function() {
3067 if (!acqLitExportAttrSelector._li_setup) {
3069 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
3071 "data": acqlimad.toStoreData(
3073 "acqlimad", {"code": li_exportable_attrs}
3078 acqLitExportAttrSelector.setValue();
3079 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
3080 acqLitExportAttrSelector._li_setup = true;
3082 openils.Util.show("acq-lit-export-attr-holder", "inline");
3085 this.exportAttrList = function() {
3086 var attr_def = acqLitExportAttrSelector.item;
3087 var li_list = this.getSelected();
3088 var value_list = li_list.map(
3090 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
3091 attr_def.code, "lineitem_marc_attr_definition"
3094 ).filter(function(attr) { return Boolean(attr); });
3096 if (value_list.length > 0) {
3097 if (value_list.length < li_list.length) {
3099 dojo.string.substitute(
3100 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
3107 openils.XUL.contentToFileSaveDialog(
3108 value_list.join("\n"),
3109 localeStrings.EXPORT_SAVE_DIALOG_TITLE
3115 alert(dojo.string.substitute(
3116 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
3120 openils.Util.hide("acq-lit-export-attr-holder");
3123 this.printPO = function() {
3124 if(!this.isPO) return;
3125 progressDialog.show(true);
3126 fieldmapper.standardRequest(
3127 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
3129 params: [this.authtoken, this.isPO, 'html'],
3130 oncomplete: function(r) {
3131 progressDialog.hide();
3132 var evt = openils.Util.readResponse(r);
3133 if(evt && evt.template_output()) {
3134 openils.Util.printHtmlString(evt.template_output().data());
3141 this.batchCreateInvoice = function() {
3142 var liIds = this.getSelected(
3143 false, null, true /* id_list */, li_active_states)
3144 if (!liIds.length) {
3145 alert(localeStrings.NO_LI_GENERAL);
3148 var path = oilsBasePath + '/acq/invoice/view?create=1';
3149 dojo.forEach(liIds, function(li, idx) { path += '&attach_li=' + li });
3150 if (openils.XUL.isXUL())
3151 openils.XUL.newTabEasy(path, localeStrings.NEW_INVOICE, null, true);
3153 location.href = path;
3156 this.batchLinkInvoice = function(create) {
3157 var liIds = this.getSelected(
3158 false, null, true /* id_list */, li_active_states)
3159 if (!liIds.length) {
3160 alert(localeStrings.NO_LI_GENERAL);
3163 if (!self.invoiceLinkDialogManager) {
3164 self.invoiceLinkDialogManager =
3165 new InvoiceLinkDialogManager("li");
3167 self.invoiceLinkDialogManager.target = liIds;
3168 acqLitLinkInvoiceDialog.show();
3171 this.receiveSelectedLineitems = function() {
3172 var states = li_post_po_states.filter(
3173 function(s) { return s != 'received' });
3174 var li_list = this.getSelected(null, null, null, states);
3176 if (!li_list.length) {
3177 alert(localeStrings.NO_LI_GENERAL);
3181 for (var i = 0; i < li_list.length; i++) {
3182 var li = li_list[i];
3184 if (li.state() != "received" &&
3185 !this.checkLiAlerts(li.id())) return;
3188 this.show('acq-lit-progress-numbers');
3191 fieldmapper.standardRequest(
3192 ['open-ils.acq', 'open-ils.acq.lineitem.receive.batch'],
3196 li_list.map(function(li) { return li.id(); })
3198 onresponse : function(r) {
3199 var resp = openils.Util.readResponse(r);
3200 self._updateProgressNumbers(resp, true);
3206 this.issueReceive = function(obj, rollback) {
3208 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
3210 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
3212 progressDialog.show(true);
3213 fieldmapper.standardRequest(
3214 ["open-ils.acq", method], {
3216 "params": [this.authtoken, obj.id()],
3217 "onresponse": function(r) {
3218 if (r = openils.Util.readResponse(r)) {
3219 self.fetchClaimInfo(
3220 part == "lineitem" ? obj.id() : obj.lineitem(),
3222 function() { self.handleReceive(r); }
3224 progressDialog.hide();
3232 * Handles the responses from receive and rollback ML calls.
3234 this.handleReceive = function(resp) {
3237 for (var li_id in resp.li) {
3238 for (var key in resp.li[li_id])
3239 self.liCache[li_id][key](resp.li[li_id][key]);
3240 self.updateLiState(self.liCache[li_id]);
3244 if (typeof(self.poUpdateCallback) == "function")
3245 self.poUpdateCallback(resp.po);
3248 for (var lid_id in resp.lid) {
3249 for (var key in resp.lid[lid_id])
3250 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
3251 self.updateLidState(self.copyCache[lid_id]);
3257 this.rollbackReceiveLineitems = function() {
3258 var li_id_list = this.getSelected(false, null, true);
3259 if (!li_id_list.length) {
3260 alert(localeStrings.NO_LI_GENERAL);
3264 if (!confirm(localeStrings.ROLLBACK_LI_RECEIVE_CONFIRM)) return;
3266 this.show('acq-lit-progress-numbers');
3269 fieldmapper.standardRequest(
3270 ['open-ils.acq', 'open-ils.acq.lineitem.receive.rollback.batch'],
3272 params: [this.authtoken, li_id_list],
3273 onresponse : function(r) {
3274 var resp = openils.Util.readResponse(r);
3275 self._updateProgressNumbers(resp, true);
3281 this._updateProgressNumbers = function(resp, reloadOnComplete, onComplete, clearProgressDialog) {
3282 this._updateProgressDialog(resp);
3283 this.vlAgent.handleResponse(resp,
3284 function(resp, res) {
3285 if (clearProgressDialog) {
3286 progressDialog.update({ "progress": 100});
3287 progressDialog.update_message();
3288 progressDialog.hide();
3289 progressDialog.attr("title", "");
3291 if(reloadOnComplete)
3292 location.href = location.href;
3294 onComplete(resp, res);
3299 this._updateProgressDialog = function(resp) {
3300 progressDialog.update({ "progress": (resp.progress / resp.total) * 100 });
3301 var keys = ['li', 'vqbr', 'bibs', 'lid', 'debits_accrued', 'copies'];
3302 for (var i = 0; i < keys.length; i++) {
3303 if (resp[keys[i]] > (this.batchProgress[keys[i]] || 0)) {
3304 progressDialog.update_message(
3305 dojo.string.substitute(
3306 localeStrings["ACTIVATE_" + keys[i].toUpperCase() + "_PROCESSED"],
3312 this.batchProgress = resp;
3315 this._createPO = function(fields) {
3316 var wantall = (fields.create_from == "all");
3318 /* If we're a picklist or purchase order already and the user wants
3319 * all lineitems, we might have pages' worth of lineitems haven't all
3320 * been loaded yet, so getSelected() won't find them. The server,
3321 * however, should know about all our lineitems, so let's ask the
3322 * server for a complete list.
3327 true, function(list) {
3328 self._createPOFromLineitems(fields, list);
3329 }, /* id_list */ true, li_pre_po_states
3332 this._createPOFromLineitems(
3333 fields, this.getSelected(
3334 false, null, true /* id_list */, li_pre_po_states)
3339 this._createPOFromLineitems = function(fields, selected) {
3340 if (selected.length == 0) {
3341 alert(localeStrings.NO_LI_GENERAL);
3346 var po = new fieldmapper.acqpo();
3347 po.provider(this.createPoProviderSelector.attr("value"));
3348 po.ordering_agency(this.createPoAgencySelector.attr("value"));
3349 po.prepayment_required(fields.prepayment_required[0] ? true : false);
3350 var name = this.createPoNameInput.attr('value');
3351 if (name) po.name(name); // avoid name=""
3353 // if we're creating assets, delay the asset creation
3354 // until after the PO is created. This will allow us to
3355 // use showAssetCreator() directly.
3357 fieldmapper.standardRequest(
3358 ["open-ils.acq", "open-ils.acq.purchase_order.create"],
3361 openils.User.authtoken,
3362 po, {lineitems : selected}
3364 onresponse : function(r) {
3365 var resp = openils.Util.readResponse(r);
3366 if (resp.complete) {
3367 // self.isPO is needed for showAssetCreator();
3368 self.isPO = resp.purchase_order.id();
3369 var redir = oilsBasePath + "/acq/po/view/" + self.isPO;
3370 if (fields.create_assets[0]) {
3371 self.showAssetCreator(
3372 function() {location.href = redir}
3375 location.href = redir;
3384 this.batchFundWidget = null;
3386 this.applyBatchLiFunds = function() {
3388 var liIds = this.getSelected().map(function(li) { return li.id(); });
3389 if(liIds.length == 0) return; // warn?
3392 batchFundUpdateDialog.show();
3394 if(!this.batchFundWidget) {
3395 this.batchFundWidget = new openils.widget.AutoFieldWidget({
3397 selfReference : true,
3398 labelFormat : fundLabelFormat,
3399 searchFormat : fundSearchFormat,
3400 searchFilter : fundSearchFilter,
3401 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
3402 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
3403 dijitArgs : { "required": true, "labelType": "html" },
3406 this.batchFundWidget.build();
3409 dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
3410 dojo.connect(batchFundUpdateSubmit, 'onClick',
3413 // TODO: call .dry_run first to test thresholds
3414 fieldmapper.standardRequest(
3415 ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
3418 openils.User.authtoken,
3420 self.batchFundWidget.widget.attr('value')
3422 oncomplete : function(r) {
3423 var resp = openils.Util.readResponse(r);
3425 location.href = location.href;
3434 this._deleteLiList = function(list, idx) {
3435 if(idx == null) idx = 0;
3436 if(idx >= list.length) return;
3441 if (this.isPO && (li.state() == "on-order" || li.state() == "received")) {
3442 /* It makes little sense to delete a lineitem from a PO that has
3443 * already been marked 'on-order'. Especially if EDI is in use,
3444 * such a purchase order will probably have already been shipped
3445 * off to a vendor, and mucking with it at this point could leave
3446 * your data in a bad state that doesn't jive with reality.
3448 * I could see making this restriction even firmer.
3450 * I could also see adjusting the li state comparisons, extending
3451 * the comparison to the PO's state, and/or providing functions
3452 * that house the logic for comparing states in a single location.
3454 * Yes, this will be really annoying if you have selected a lot
3455 * of lineitems to cancel that have been ordered. You'll get a
3456 * confirm dialog for each one.
3459 if (!confirm(localeStrings.DEL_LI_FROM_PO)) {
3460 self._deleteLiList(list, ++idx); /* move on to next in list */
3465 fieldmapper.standardRequest(
3467 this.isPO ? 'open-ils.acq.purchase_order.lineitem.delete' : 'open-ils.acq.picklist.lineitem.delete'],
3469 params: [openils.User.authtoken, liId],
3470 oncomplete: function(r) {
3471 self.removeLineitem(liId);
3472 self._deleteLiList(list, ++idx);
3478 this.editOrderMarc = function(li) {
3480 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
3481 to true in about:config */
3483 if(openils.XUL.isXUL()) {
3484 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul','','chrome');
3486 win = window.open('/xul/server/cat/marcedit.xul','','chrome');
3490 record : {marc : li.marc(), "rtype": "bre"},
3492 label: 'Save Record', // XXX I18N
3493 func: function(xmlString) {
3495 fieldmapper.standardRequest(
3496 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
3498 params: [openils.User.authtoken, li],
3499 oncomplete: function(r) {
3500 openils.Util.readResponse(r);
3502 self.drawInfo(li.id())
3508 'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
3509 'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
3513 this._savePl = function(values) {
3515 (values.which == 'all'),
3516 function(list) { self._savePlFromLineitems(values, list); }
3520 this._savePlFromLineitems = function(values, selected) {
3521 openils.Util.show("acq-lit-generic-progress");
3523 if(values.new_name) {
3524 openils.acq.Picklist.create(
3525 {name: values.new_name},
3531 oilsBasePath + "/acq/picklist/view/" + id;
3536 } else if(values.existing_pl) {
3537 // update lineitems to use an existing picklist
3539 values.existing_pl, selected, 0,
3542 oilsBasePath + "/acq/picklist/view/" +
3549 this._updateLiState = function(values, state, state_filter) {
3550 progressDialog.show(true);
3552 (values.which == 'all'),
3554 self._updateLiStateFromLineitems(values, state, list);
3555 }, false /* id_list */, state_filter
3559 this._updateLiStateFromLineitems = function(values, state, selected) {
3560 if(!selected.length) {
3561 try { progressDialog.hide() } catch(E) {};
3562 alert(localeStrings.NO_LI_GENERAL);
3565 dojo.forEach(selected, function(li) {li.state(state);});
3566 self._updateLiList(null, selected, 0,
3567 // TODO consider inline updates for efficiency
3568 function() { location.href = location.href }
3572 this._updateLiList = function(pl, list, idx, oncomplete) {
3573 if(idx >= list.length) return oncomplete();
3575 if(pl != null) li.picklist(pl);
3576 litGenericProgress.update({maximum: list.length, progress: idx});
3577 new openils.acq.Lineitem({lineitem:li}).update(
3579 self._updateLiList(pl, list, ++idx, oncomplete);
3584 this._loadPOSelect = function() {
3585 if (!this.createPoProviderSelector) {
3586 var widget = new openils.widget.AutoFieldWidget({
3587 "fmField": "provider",
3589 "searchFilter": {"active": "t"},
3590 "parentNode": dojo.byId("acq-lit-po-provider"),
3592 "onChange": function() {
3594 self._updateCreatePoPrepayCheckbox(
3595 this.item.prepayment_required()
3601 widget.build(function(w) { self.createPoProviderSelector = w; });
3604 this.createPoCheckDupes = function() {
3605 var org = self.createPoAgencySelector.attr('value');
3606 var name = self.createPoNameInput.attr('value');
3607 openils.Util.hide('acq-dupe-po-name');
3610 acqLitCreatePoSubmit.attr('disabled', false);
3614 acqLitCreatePoSubmit.attr('disabled', true);
3615 var orgs = fieldmapper.aou.descendantNodeList(org, true);
3616 new openils.PermaCrud().search('acqpo',
3617 {name : name, ordering_agency : orgs},
3618 {async : true, oncomplete : function(r) {
3619 var po = openils.Util.readResponse(r);
3621 if (po && (po = po[0])) {
3623 var link = dojo.byId('acq-dupe-po-link');
3624 openils.Util.show('acq-dupe-po-name', 'table-row');
3625 var dupe_path = '/acq/po/view/' + po.id();
3629 if (window.IAMBROWSER) {
3630 // TODO: integration
3634 link.onclick = function() {
3636 var loc = xulG.url_prefix('XUL_BROWSER?url=') +
3637 window.encodeURIComponent(
3638 xulG.url_prefix('EG_WEB_BASE' + dupe_path)
3642 {tab_name: '', browser:false},
3645 show_nav_buttons : true,
3646 show_print_button : true,
3653 link.onclick = function() {
3654 window.open(oilsBasePath + dupe_path, '_blank').focus();
3659 acqLitCreatePoSubmit.attr('disabled', false);
3665 if (!this.createPoAgencySelector) {
3666 var widget = new openils.widget.AutoFieldWidget({
3667 "fmField": "ordering_agency",
3669 "parentNode": dojo.byId("acq-lit-po-agency"),
3670 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3672 widget.build(function(w) {
3673 self.createPoAgencySelector = w;
3674 dojo.connect(w, 'onChange', self.createPoCheckDupes);
3678 if (!this.createPoNameInput) {
3679 var widget = new openils.widget.AutoFieldWidget({
3682 "parentNode": dojo.byId("acq-lit-po-name"),
3683 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3685 widget.build(function(w) {
3686 self.createPoNameInput = w;
3687 dojo.connect(w, 'onChange', self.createPoCheckDupes);
3692 this.showRealCopyEditUI = function(li) {
3697 this._fetchLineitem(li.id(),
3699 li = self.liCache[li.id()] = fullLi;
3703 id : li.lineitem_details().map(
3704 function(item) { return item.eg_copy_id() }
3708 oncomplete : function(r) {
3710 var r_list = openils.Util.readResponse( r );
3711 for (var i = 0; i < r_list.length; i++) {
3712 var copy = r_list[i];
3713 var volId = copy.call_number();
3714 var volume = self.volCache[volId];
3716 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
3718 copy.call_number(volume);
3719 copyList.push(copy);
3722 xulG.volume_item_creator( { 'existing_copies' : copyList } );
3725 alert('error in oncomplete: ' + E);
3734 this.drawBibFinder = function(li) {
3737 var liWrapper = new openils.acq.Lineitem({lineitem:li});
3740 ['isbn', 'upc', 'issn', 'title', 'author'],
3742 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
3744 if(field == 'title' || field == 'author') {
3745 query += field +':' + val + ' ';
3747 query += 'identifier|' + field + ':' + val + ' ';
3753 if(openils.XUL.isXUL() && !window.IAMBROWSER) {
3755 oilsBasePath + '/acq/lineitem/findbib?query=' + encodeURIComponent(query),
3756 '', 'resizable,scrollbars=1,chrome');
3758 win = window.open( oilsBasePath + '/acq/lineitem/findbib?query=' + encodeURIComponent(query));
3762 win.window.recordFound = function(bibId) {
3765 var attrs = li.attributes();
3766 li.attributes(null);
3767 li.eg_bib_id(bibId);
3769 fieldmapper.standardRequest(
3770 ["open-ils.acq", "open-ils.acq.lineitem.update"],
3772 "params": [openils.User.authtoken, li],
3774 "oncomplete": function(r) {
3775 if(openils.Util.readResponse(r)) {
3776 location.href = location.href;