1 dojo.require('dojo.date.locale');
2 dojo.require('dojo.date.stamp');
3 dojo.require('dijit.form.Button');
4 dojo.require('dijit.form.TextBox');
5 dojo.require('dijit.form.FilteringSelect');
6 dojo.require('dijit.form.Textarea');
7 dojo.require('dijit.Tooltip');
8 dojo.require('dijit.ProgressBar');
9 dojo.require('dojox.timing.doLater');
10 dojo.require('openils.acq.Lineitem');
11 dojo.require('openils.acq.PO');
12 dojo.require('openils.acq.Picklist');
13 dojo.require('openils.widget.AutoFieldWidget');
14 dojo.require('dojo.data.ItemFileReadStore');
15 dojo.require('openils.widget.ProgressDialog');
16 dojo.require('openils.PermaCrud');
17 dojo.require("openils.widget.PCrudAutocompleteBox");
18 dojo.require('dijit.form.ComboBox');
19 dojo.require('openils.CGI');
21 if (!localeStrings) { /* we can do this because javascript doesn't have block scope */
22 dojo.requireLocalization('openils.acq', 'acq');
23 var localeStrings = dojo.i18n.getLocalization('openils.acq', 'acq');
25 const XUL_OPAC_WRAPPER = 'chrome://open_ils_staff_client/content/cat/opac.xul';
26 var li_exportable_attrs = ["issn", "isbn", "upc"];
28 var fundLabelFormat = [
29 '<span class="fund_${0}">${1} (${2})</span>', 'id', 'code', 'year'
31 var fundSearchFormat = ['${0} (${1})', 'code', 'year'];
32 var fundSearchFilter = {active : 't'};
34 function nodeByName(name, context) {
35 return dojo.query('[name='+name+']', context)[0];
38 // for caching linked users. e.g. lineitem_detail.receiver
41 var liDetailBatchFields = ['fund', 'owning_lib', 'location', 'collection_code', 'circ_modifier', 'cn_label'];
42 var liDetailFields = liDetailBatchFields.concat(['barcode', 'note']);
44 "stop": "color: #c00; font-weight: bold;",
45 "warning": "color: #c93;"
49 * We're not using 'approved' today, but there is API support for it.
50 * I believe it's been replaced by "order-ready".
51 * LIs go new => selector-ready => order-ready/approved => pending-order =>
52 * on-order => received. 'cancelled' can pop up anywhere.
55 var li_pre_po_states = ["new", "selector-ready", "order-ready", "approved"];
56 var li_post_po_states = ["pending-order", "on-order", "received", "cancelled"];
57 var li_active_states = li_pre_po_states.concat(li_post_po_states);
59 function AcqLiTable() {
66 this.haveFundClass = {}
67 this.fundBalanceState = {};
68 this.realDfaCache = {};
69 this.virtDfaCounts = {};
72 this.claimEligibleLidByLi = {};
73 this.claimEligibleLid = {};
74 this.toggleState = false;
75 this.tbody = dojo.byId('acq-lit-tbody');
78 this.authtoken = openils.User.authtoken;
79 this.pcrud = new openils.PermaCrud();
80 this.rowTemplate = this.tbody.removeChild(dojo.byId('acq-lit-row'));
81 this.copyTbody = dojo.byId('acq-lit-li-details-tbody');
82 this.copyRow = this.copyTbody.removeChild(dojo.byId('acq-lit-li-details-row'));
83 this.copyBatchRow = dojo.byId('acq-lit-li-details-batch-row');
84 this.copyBatchWidgets = {};
85 this.liNotesTbody = dojo.byId('acq-lit-notes-tbody');
86 this.liNotesRow = this.liNotesTbody.removeChild(dojo.byId('acq-lit-notes-row'));
87 this.realCopiesTbody = dojo.byId('acq-lit-real-copies-tbody');
88 this.realCopiesRow = this.realCopiesTbody.removeChild(dojo.byId('acq-lit-real-copies-row'));
89 this._copy_fields_for_acqdf = ['owning_lib', 'location', 'fund', 'circ_modifier', 'collection_code'];
90 this.skipInitialEligibilityCheck = false;
91 this.claimDialog = new ClaimDialogManager(
92 liClaimDialog, finalClaimDialog, this.claimEligibleLidByLi,
93 function(li) { /* callback that fires when claims are made */
94 self.fetchClaimInfo(li.id(), /* force update */ true);
97 this.vlAgent = new VLAgent();
98 this.batchProgress = {};
100 if (dojo.byId('acq-lit-apply-idents')) {
101 dojo.byId('acq-lit-apply-idents').onclick = function() {
102 self.applyOrderIdentValues();
106 this.focusLineitem = new openils.CGI().param('focus_li');
108 // capture the inline copy display wrapper and row template
109 this.inlineCopyContainer =
110 this.tbody.removeChild(dojo.byId('acq-inline-copies-row'));
112 '[name=acq-li-inline-copies-tbody]', this.inlineCopyContainer)[0];
113 this.inlineCopyTemplate = tb.removeChild(
114 dojo.query('[name=acq-li-inline-copies-template]', tb)[0]);
115 this.inlineNoCopies = tb.removeChild(
116 dojo.query('[name=acq-li-inline-copies-none]', tb)[0]);
118 // list of LI IDs that should be refreshed at next display time
119 this.inlineCopiesNeedingRefresh = [];
121 dojo.byId("acq-lit-li-actions-selector").onchange = function() {
122 self.applySelectedLiAction(this.options[this.selectedIndex].value);
123 this.selectedIndex = 0;
126 acqLitCreatePoCancel.onClick = function() {
127 acqLitPoCreateDialog.hide();
129 acqLitCreatePoSubmit.onClick = function() {
130 if (!self.createPoProviderSelector.attr("value") ||
131 !self.createPoAgencySelector.attr("value")) {
132 alert(localeStrings.CREATE_PO_INVALID);
134 } else if (self._confirmPoPrepaySituation()) {
135 acqLitPoCreateDialog.hide();
136 self._createPO(acqLitPoCreateDialog.getValues());
142 acqLitSavePlButton.onClick = function() {
143 acqLitSavePlDialog.hide();
144 self._savePl(acqLitSavePlDialog.getValues());
147 acqLitCancelLiStateButton.onClick = function() {
148 acqLitChangeLiStateDialog.hide();
150 acqLitSaveLiStateButton.onClick = function() {
151 acqLitChangeLiStateDialog.hide();
152 var state = acqLitChangeLiStateDialog.attr('state');
153 var state_filter = ['new'];
154 if (state == 'order-ready')
155 state_filter.push('selector-ready');
157 acqLitChangeLiStateDialog.getValues(), state, state_filter);
161 dojo.byId('acq-lit-select-toggle').onclick = function(){self.toggleSelect()};
162 dojo.byId('acq-inline-copies-toggle').onclick = function(){self.toggleInlineCopies()};
163 dojo.byId('acq-lit-info-back-button').onclick = function(){self.show('list')};
164 dojo.byId('acq-lit-copies-back-button').onclick = function(){self.show('list')};
165 dojo.byId('acq-lit-notes-back-button').onclick = function(){self.show('list')};
166 dojo.byId('acq-lit-real-copies-back-button').onclick = function(){self.show('list')};
168 this.setFundSearchFilter = function(callback) {
169 new openils.User().getPermOrgList(
170 ['CREATE_PURCHASE_ORDER', 'MANAGE_FUND'],
172 fundSearchFilter.org = orgs;
173 if (callback) callback();
175 true, true // descendants, id_list
179 this.afwCopyFieldArgs = function(field, perms) {
183 "labelFormat": (field == 'fund') ? fundLabelFormat : null,
184 "searchFormat": (field == 'fund') ? fundSearchFormat : null,
185 "searchFilter": (field == 'fund') ? fundSearchFilter : null,
186 "orgLimitPerms": (field == 'location') ? ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'] : [perms],
189 "labelType": (field == "fund") ? "html" : null
191 "noCache": (field == "fund"),
196 /* This is the "new" batch updater that sits atop all lineitems. It does
197 * use this.afwCopyFieldArgs() to borrow a little common code from the
198 * "old" batch updater atop the copy details view. */
199 this.initBatchUpdater = function(disabled_fields) {
200 openils.Util.show("acq-batch-update", "table");
202 if (!dojo.isArray(disabled_fields)) disabled_fields = [];
204 /* Note that this will directly contain dijits, not the AutoWidget
206 this.batchUpdateWidgets = {};
208 this.batchUpdateWidgets.item_count = new dijit.form.TextBox(
210 "style": {"width": "3em"},
212 dojo.indexOf(disabled_fields, "item_count") != -1
218 (new openils.widget.AutoFieldWidget({
220 "selfReference": true,
221 "dijitArgs": { "required": false },
223 "parentNode": "acq-bu-distribution_formula"
226 dojo.style(w.domNode, {"width": "12em"});
227 /* dijitArgs to AutoFieldWidget won't work for 'disabled' */
230 dojo.indexOf(disabled_fields, "distribution_formula") != -1
232 self.batchUpdateWidgets.distribution_formula = w;
236 function buildOneBatchWidget(field, args) {
237 (new openils.widget.AutoFieldWidget(args)).build(
239 if (field == "fund") {
241 w, "onChange", function(val) {
242 self._updateFundSelectorStyle(aw, val);
246 self._ensureCSSFundClasses(w.store);
249 dojo.style(w.domNode, {"width": "10em"});
252 dojo.indexOf(disabled_fields, field) != -1
254 self.batchUpdateWidgets[field] = w;
260 ["owning_lib","location","collection_code","circ_modifier","fund"],
262 var args = self.afwCopyFieldArgs(field,"CREATE_PURCHASE_ORDER");
263 args.parentNode = dojo.byId("acq-bu-" + field);
265 if (field == 'fund') {
266 // The list of funds can be huge. Before fetching
267 // funds for PO modification, see where the user has
268 // perms and limit the retreived funds accordingly.
269 // Note: This is the first instance of fund list
270 // retrieval. All future fund list retrievals will
271 // benefit directly from having applied the fund
272 // search filter org units here.
273 self.setFundSearchFilter(function() {
274 buildOneBatchWidget(field, args);
279 buildOneBatchWidget(field, args);
283 acqBatchUpdateApply.onClick = function() {
284 var li_id_list = self.getSelected(false, null, true /* id list */);
285 if (!li_id_list.length) {
286 alert(localeStrings.NO_LI_TO_UPDATE);
290 progressDialog.show(true);
291 progressDialog.attr("title", localeStrings.LI_BATCH_UPDATE);
292 progressDialog.update({"maximum": li_id_list.length,"progress": 0});
296 var params = [ self.authtoken, {"lineitems": li_id_list},
297 self.batchUpdateChanges(), self.batchUpdateFormula() ];
298 console.log("batch update params: " + dojo.toJson(params));
300 fieldmapper.standardRequest(
301 ["open-ils.acq", "open-ils.acq.lineitem.batch_update"], {
304 "onresponse": function(r) {
305 if ((r = openils.Util.readResponse(r))) { // assignment
306 progressDialog.update({"progress": ++count});
308 progressDialog.hide();
309 progressDialog.attr("title", "");
312 "oncomplete": function() {
313 /* XXX Is the last call to onresponse guaranteed to
314 * finish before oncomplete is fired? */
315 if (count != li_id_list.length) {
316 console.error("lineitem batch update operation failed");
317 progressDialog.hide();
318 progressDialog.attr("title", "");
320 location.href = location.href;
328 this.batchUpdateChanges = function() {
332 openils.Util.objectProperties(this.batchUpdateWidgets),
334 if (k == "distribution_formula") return; /* handled elsewhere */
335 if (self.batchUpdateWidgets[k].attr("disabled")) return;
337 /* It's important that a value of "" should mean that a field
338 * doesn't get used in the arguments to the batch updater API,
339 * but 0 should mean an actual 0. */
340 var value = self.batchUpdateWidgets[k].attr("value");
349 this.batchUpdateFormula = function() {
350 if (this.batchUpdateWidgets.distribution_formula.attr("disabled")) {
354 this.batchUpdateWidgets.distribution_formula.attr("value") ||
360 this.reset = function(keep_selectors) {
361 while(self.tbody.childNodes[0])
362 self.tbody.removeChild(self.tbody.childNodes[0]);
371 this.setNext = function(handler) {
372 var link = dojo.byId('acq-lit-next');
374 dojo.style(link, 'visibility', 'visible');
375 link.onclick = handler;
377 dojo.style(link, 'visibility', 'hidden');
381 this.setPrev = function(handler) {
382 var link = dojo.byId('acq-lit-prev');
384 dojo.style(link, 'visibility', 'visible');
385 link.onclick = handler;
387 dojo.style(link, 'visibility', 'hidden');
391 this.enableActionsDropdownOptions = function(mask) {
392 /* 'mask' is probably a misnomer the way I'm using it, but it needs to
393 * be one of pl,po,ao,gs,vp, or fs. */
394 dojo.query("option", "acq-lit-li-actions-selector").forEach(
396 var opt_mask = dojo.attr(option, "mask");
398 /* For each <option> element, an empty or non-existent mask
399 * attribute, a mask attribute of "*", or a mask attribute that
400 * matches this method's argument should result in that
401 * option's being enabled. */
403 option, "disabled", !(
406 opt_mask.search(mask) != -1
414 * Ensures this.focusLineitem is in view and causes a brief
415 * border around the lineitem to come to life then fade.
417 this.focusLi = function() {
418 if (!this.focusLineitem) return;
420 // set during addLineitem()
421 var node = dojo.byId('li-title-ref-' + this.focusLineitem);
423 // LI may not yet be rendered
426 // prevent numerous re-focuses
427 this.focusLineitem = null;
429 // causes the full row to be visible
430 dijit.scrollIntoView(node);
433 dojo.query('[attr=title]', node)[0].focus();
435 dojo.require('dojox.fx');
439 dojox.fx.highlight({color : '#BB4433', node : node, duration : 2000}).play();
444 this.show = function(div) {
445 openils.Util.hide('acq-lit-table-div');
446 openils.Util.hide('acq-lit-info-div');
447 openils.Util.hide('acq-lit-li-details');
448 openils.Util.hide('acq-lit-notes-div');
449 openils.Util.hide('acq-lit-real-copies-div');
450 openils.Util.hide('acq-lit-asset-creator');
453 openils.Util.show('acq-lit-table-div');
455 this.refreshInlineCopies();
458 openils.Util.show('acq-lit-info-div');
461 openils.Util.show('acq-lit-li-details');
464 openils.Util.show('acq-lit-real-copies-div');
467 openils.Util.show('acq-lit-notes-div');
469 case 'asset-creator':
470 openils.Util.show('acq-lit-asset-creator');
474 openils.Util.show(div);
478 this.hide = function() {
482 this.toggleSelect = function() {
484 dojo.forEach(self.selectors, function(i){i.checked = false});
486 dojo.forEach(self.selectors, function(i){i.checked = true});
487 self.toggleState = !self.toggleState;
491 this.getAll = function(callback, id_only, state) {
492 /* For some uses of the li table, we may not really know about "all"
493 * the lineitems that the user thinks we know about. If we're a paged
494 * picklist, for example, we only know about the lineitems we've
495 * displayed, but not necessarily all the lineitems on the picklist.
496 * So we reach out to pcrud to inform us.
497 * state: string/array. only lineitems in one of these states are
498 * included in the final result set. Not currently supported for
502 var oncomplete = function(r) {
503 var id_list = openils.Util.readResponse(r);
507 self.fetchLineitemsById(id_list, callback);
511 var search = {"picklist": this.isPL};
512 if (state) search.state = state;
515 "id_list": true, /* sic, even if id_only */
517 "oncomplete": oncomplete
521 } else if (this.isPO) {
522 var search = {"purchase_order": this.isPO};
523 if (state) search.state = state;
528 "oncomplete": oncomplete
532 } else if (this.isUni && this.pager) {
533 this.pager.getAllLineitemIDs(oncomplete);
537 /* If execution reaches this point, we don't need or can't perform
538 * any special tricks to find out the "real" list of "all" lineitems
539 * in this context, so we fall back to the old method.
541 callback(this.getSelected(true, null, id_only, state));
544 /** @param all If true, assume all are selected */
545 this.getSelected = function(
547 callback /* If you want a "good" idea of "all" lineitems, you must
548 provide a callback that accepts an array parameter, rather than
549 relying on the return value of this method itself. */,
553 console.log("getSelected states = " + state);
555 return this.getAll(callback, id_only, state);
557 var indices = {}; /* use to uniqify. needed in paging situations. */
558 dojo.forEach(this.selectors,
561 indices[i.parentNode.parentNode.getAttribute('li')] = true;
565 var result = openils.Util.objectProperties(indices);
567 // caller provided a lineitem state filter. remove IDs for lineitems
568 // not in the selected state.
571 if (!dojo.isArray(state)) state = [state];
572 dojo.forEach(result, function(liId) {
573 console.log('filter LI state ' + self.liCache[liId].state());
574 if (state.indexOf(self.liCache[liId].state()) >= 0)
581 result = result.map(function(liId) { return self.liCache[liId]; });
589 this.setRowAttr = function(td, liWrapper, field, type) {
590 var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
591 td.appendChild(document.createTextNode(val));
594 this.setClaimPolicyControl = function(li, row) {
595 if (!self._claimPolicyPickerLoading) {
596 self._claimPolicyPickerLoading = true;
598 new openils.widget.AutoFieldWidget({
599 "parentNode": "acq-lit-li-claim-policy",
601 "selfReference": true,
602 "dijitArgs": {"required": true}
604 function(w) { self.claimPolicyPicker = w; }
608 /* dojox.timing.doLater() is the best thing ever. Resource not yet
609 * ready? Just repeat my whole method when it is. */
610 if (dojox.timing.doLater(self.claimPolicyPicker)) {
614 row = self._findLiRow(li);
616 if (li.claim_policy()) {
617 /* This Dojo data dance is necessary to get a whole fieldmapper
618 * object based on a claim policy ID, since we alreay have the
619 * widget thing loaded with all that data, and can thereby
620 * avoid another request to the server. */
621 self.claimPolicyPicker.store.fetchItemByIdentity({
622 "identity": li.claim_policy(),
623 "onItem": function(a) {
624 var policy = (new acqclp()).fromStoreItem(a);
625 var span = nodeByName("claim_policy", row);
626 var inner = nodeByName("claim_policy_name", row);
628 openils.Util.show(span, "inline");
629 inner.innerHTML = policy.name();
631 "onError": function(e) {
636 openils.Util.hide(nodeByName("claim_policy", row));
637 nodeByName("claim_policy_name", row).innerHTML = "";
642 this.fetchClaimInfo = function(liId, force, callback, row) {
644 liId, function(full) {
645 self.liCache[full.id()] = full;
646 self.checkClaimEligibility(full, callback, row);
651 // fetch an updated copy of the lineitem
652 // and add it back to the lineitem table
653 this.refreshLineitem = function(li, focus) {
655 this._fetchLineitem(li.id(),
658 self.focusLineitem = li.id();
660 self.focusLineitem = null;
662 var row = dojo.query('[li='+li.id()+']', self.tbody)[0];
663 var nextSibling = row.nextSibling;
664 self.tbody.removeChild(row);
665 self.addLineitem(newLi, false, nextSibling);
671 * Inserts a single lineitem into the growing table of lineitems
672 * @param {Object} li The lineitem object to insert
674 this.addLineitem = function(li, skip_final_placement, nextSibling) {
675 this.liCache[li.id()] = li;
677 // insert the row right away so that final order isn't
678 // dependent on how long subsequent async request take
679 // for a given line item
680 var row = self.rowTemplate.cloneNode(true);
681 if (!skip_final_placement) {
683 // either no nextSibling was provided or it was null
684 // meaning the row was already at the end of the table
685 self.tbody.appendChild(row);
687 self.tbody.insertBefore(row, nextSibling);
691 self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
693 // sort the lineitem notes on edit_time
694 if(!li.lineitem_notes()) li.lineitem_notes([]);
696 var liWrapper = new openils.acq.Lineitem({lineitem:li});
697 row.setAttribute('li', li.id());
698 var tds = dojo.query('[attr]', row);
699 dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
700 dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
702 // so we can scroll to it later
703 dojo.query('[name=bib-info-cell]', row)[0].id = 'li-title-ref-' + li.id();
706 liWrapper.findAttr("isbn", "lineitem_marc_attr_definition") ||
707 liWrapper.findAttr("upc", "lineitem_marc_attr_definition");
709 // XXX media prefix for added content
711 nodeByName("jacket", row).setAttribute(
712 "src", "/opac/extras/ac/jacket/small/" + identifier
716 nodeByName("liid", row).innerHTML += li.id();
718 var exist = nodeByName('li_existing_count', row);
719 fieldmapper.standardRequest(
720 ['open-ils.acq', 'open-ils.acq.lineitem.existing_copies.count'],
722 params: [this.authtoken, li.id()],
723 oncomplete : function(r) {
724 var count = openils.Util.readResponse(r);
725 exist.innerHTML = count;
726 if (Number(count) > 0) {
727 openils.Util.addCSSClass(
728 exist, 'acq-existing-count-warn');
732 label : dojo.string.substitute(
733 localeStrings.LI_EXISTING_COPIES, [count])
740 openils.Util.show(nodeByName('catalog', row), 'inline');
741 nodeByName("catalog_link", row).onclick = this.generateMakeRecTab(li.eg_bib_id());
743 openils.Util.show(nodeByName('link_to_catalog', row), 'inline');
744 nodeByName("link_to_catalog_link", row).onclick = function() { self.drawBibFinder(li) };
747 if (li.queued_record()) {
748 this.pcrud.retrieve('vqbr', li.queued_record(),
750 oncomplete : function(r) {
751 var qrec = openils.Util.readResponse(r);
752 openils.Util.show(nodeByName('queue', row), 'inline');
753 var link = nodeByName("queue_link", row);
754 link.onclick = function() {
755 // open a new tab to the vandelay queue for this record
756 openils.XUL.newTabEasy(
757 oilsBasePath + '/vandelay/vandelay?qtype=bib&qid=' + qrec.queue()
765 nodeByName("worksheet_link", row).href =
766 oilsBasePath + "/acq/lineitem/worksheet/" + li.id() +
767 '?source=' + encodeURIComponent(location.pathname + location.search)
769 nodeByName("show_requests_link", row).href =
770 oilsBasePath + "/acq/picklist/user_request?lineitem=" + li.id() +
771 '?source=' + encodeURIComponent(location.pathname + location.search)
773 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
774 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
775 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
776 dojo.query('[name=expand_inline_copies]', row)[0].onclick =
777 function() {self.drawInlineCopies(li.id())};
780 if (sum = li.order_summary()) { // assignment
781 // Only show the paid label if at least one copy is invoiced.
782 // In other words, a lineitem whose every copy is canceled
784 if (sum.invoice_count() > 0) {
785 if (sum.item_count() == (
786 sum.invoice_count() + sum.cancel_count())) {
787 // Lineitem is fully paid. Display the paid-off label
788 openils.Util.show(nodeByName('paid', row), 'inline');
793 this.drawOrderIdentSelector(li, row);
795 if (!this.skipInitialEligibilityCheck)
799 function(full) { self.setClaimPolicyControl(full, row) },
803 this.updateLiNotesCount(li, row);
805 // show which PO this lineitem is a member of
806 if(li.purchase_order() && !this.isPO) {
808 this.poCache[li.purchase_order()] =
809 this.poCache[li.purchase_order()] ||
810 fieldmapper.standardRequest(
811 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
813 this.authtoken, li.purchase_order(), {
814 "flesh_price_summary": true,
815 "flesh_provider" : true,
816 "flesh_lineitem_count": true
819 if(po && !this.isMeta) {
820 openils.Util.show(nodeByName('po', row), 'inline');
821 var link = nodeByName('po_link', row);
822 link.setAttribute('href', oilsBasePath +
823 '/acq/po/view/' + li.purchase_order() +
824 '?focus_li=' + li.id() +
825 '&source=' + encodeURIComponent(location.pathname + location.search)
827 link.innerHTML += po.name();
829 openils.Util.show(nodeByName('pro', row), 'inline');
830 link = nodeByName('pro_link', row);
831 link.setAttribute('href', oilsBasePath + '/conify/global/acq/provider/' + po.provider().id())
832 link.innerHTML += po.provider().code();
836 // show which picklist this lineitem is a member of
837 if(li.picklist() && (this.isPO || this.isMeta || this.isUni)) {
839 this.plCache[li.picklist()] =
840 this.plCache[li.picklist()] ||
841 fieldmapper.standardRequest(
842 ['open-ils.acq', 'open-ils.acq.picklist.retrieve.authoritative'],
843 {params: [this.authtoken, li.picklist()]});
845 if (pl.name() == "") {
846 openils.Util.show(nodeByName("bib_origin", row), "inline");
850 openils.Util.show(nodeByName('pl', row), 'inline');
851 var link = nodeByName('pl_link', row);
852 link.setAttribute('href', oilsBasePath +
853 '/acq/picklist/view/' + li.picklist() +
854 '?focus_li=' + li.id() +
855 '&source=' + encodeURIComponent(location.pathname + location.search)
857 link.innerHTML += pl.name();
862 var countNode = nodeByName('count', row);
863 var count = li.item_count() || 0;
864 if (typeof(this._copy_count_cb) == "function") {
865 this._copy_count_cb(li.id(), count);
867 countNode.innerHTML = count;
868 countNode.id = 'acq-lit-copy-count-label-' + li.id();
871 var priceInput = dojo.query('[name=price]', row)[0];
872 priceInput.value = li.estimated_unit_price() || '';
873 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
875 // show either "mark received" or "unreceive" as appropriate
876 this.updateLiState(li, row);
878 if (skip_final_placement) {
882 // the last LI may be rendered after the call to show('list'),
883 // so make sure it's focused if necessary.
884 if (this.focusLineitem == li.id())
888 this._liCountClaims = function(li) {
890 for (var i = 0; i < li.lineitem_details().length; i++)
891 total += li.lineitem_details()[i].claims().length;
895 this._findLiRow = function(li) {
896 return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
899 this.reconsiderClaimControl = function(li, row) {
900 if (!row) row = this._findLiRow(li);
901 var option = nodeByName("action_manage_claims", row);
902 var eligible = this.claimEligibleLidByLi[li.id()].length;
903 var count = this._liCountClaims(li);
905 option.disabled = !(count || eligible);
907 dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
908 option.onclick = function() { self.claimDialog.show(li); };
911 this.clearEligibility = function(li) {
912 this.claimEligibleLidByLi[li.id()] = [];
914 if (li.lineitem_details()) {
915 li.lineitem_details().forEach(
916 function(lid) { delete self.claimEligibleLid[lid.id()]; }
920 if (this.copyCache) {
922 for (var k in this.copyCache) {
923 if (this.copyCache[k].lineitem() == li.id())
927 function(k) { delete self.claimEligibleLid[k]; }
932 this.applyOrderIdentValues = function() {
933 this._identValuesInFlight =
934 openils.Util.objectProperties(this.liCache).length;
935 for (var liId in this.liCache) {
936 this._applyOrderIdentValue(this.liCache[liId]);
940 // returns true if request was sent
941 this._applyOrderIdentValue = function(li, oncomplete) {
944 console.log('applying ident value for lineitem ' + li.id());
947 var row = dojo.query('[li=' + li.id() + ']')[0];
949 // find the selected ident value
950 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
951 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
952 var name = typeSel.options[typeSel.selectedIndex].value;
953 var val = typeSel._cbox.attr('value');
955 console.log("selected ident is " + val);
957 // it differs from the existing ident value, update it
958 var oldIdent = self.getLiOrderIdent(li);
960 oldIdent.attr_name() == name &&
961 oldIdent.attr_value() == val) {
962 console.log('selected ident attr matches existing attr');
963 if (--this._identValuesInFlight == 0) {
964 if (oncomplete) oncomplete(li);
965 else location.href = location.href;
970 // see if the selected ident value is represented
971 // by an existing lineitem attr
974 typeSel._cbox.store.fetch({
975 query : {attr_value : val},
976 onItem : function(item) {
977 console.log('found existing attr for ident value');
978 args.source_attr_id = li.attributes().filter(
979 function(attr) { return attr.id() == item.id[0] }
985 if (!args.source_attr_id) {
986 // user entered new text in the combobox
987 // so we need to create a new attr
988 console.log('creating new ident attr');
989 args.lineitem_id = li.id();
990 args.attr_name = name;
991 args.attr_value = val;
994 fieldmapper.standardRequest(
995 ['open-ils.acq', 'open-ils.acq.lineitem.order_identifier.set'],
997 params : [openils.User.authtoken, args],
998 oncomplete : function() {
999 console.log('order_ident oncomplete');
1000 if (--self._identValuesInFlight == 0) {
1001 if (oncomplete) oncomplete(li);
1002 else location.href = location.href;
1004 console.log(self._identValuesInFlight + ' still in flight');
1012 this.getLiOrderIdent = function(li) {
1013 var attrs = li.attributes();
1014 if (!attrs) return null;
1015 return attrs.filter(
1018 attr.attr_type() == 'lineitem_local_attr_definition' &&
1019 openils.Util.isTrue(attr.order_ident())
1025 this.drawOrderIdentSelector = function(li, row) {
1027 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
1028 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
1030 var attrs = li.attributes();
1032 // limit to MARC attr defs
1033 attrs = attrs.filter(
1035 return (attr.attr_type() == 'lineitem_marc_attr_definition');
1039 var identAttr = this.getLiOrderIdent(li);
1042 // collect the values for each type of identifier
1043 // find a reasonable default identifier type to render
1047 dojo.forEach(['isbn', 'upc', 'issn'],
1050 // collect the values for this attr name
1051 values[name] = attrs.filter(
1053 return (attr.attr_name() == name)
1057 // select a reasonable default name in the type-selector
1061 if (identAttr.attr_name() == name)
1063 } else if (values[name].length) {
1068 dojo.forEach(typeSel.options, function(opt) {
1069 if (opt.value == name) {
1070 opt.selected = true;
1079 function updateOrderIdent(val) {
1080 self._identValuesInFlight = 1;
1081 self._applyOrderIdentValue(
1084 self.refreshLineitem(li);
1089 // replace the ident combobox with a new
1090 // one for the selected ident type
1091 function changeComboBox(sel) {
1092 var name = sel.options[sel.selectedIndex].value;
1094 var td = dojo.query('[name=order_ident_value]', row)[0];
1095 if (td.childNodes[0])
1096 dojo.destroy(td.childNodes[0]);
1098 var store = new dojo.data.ItemFileWriteStore({
1099 data : acqlia.toStoreData(values[name])
1102 var cbox = new dijit.form.ComboBox(
1104 labelAttr : 'attr_value',
1105 searchAttr : 'attr_value'
1107 dojo.create('div', {}, td)
1112 // set the value for the cbox
1113 if (values[name].length) {
1114 var orderIdent = self.getLiOrderIdent(li);
1116 if (orderIdent && orderIdent.attr_name() == name) {
1117 cbox.attr('value', orderIdent.attr_value());
1119 cbox.attr('value', values[name][0].attr_value());
1123 if (!self.orderIdentAllowed)
1124 cbox.attr('disabled', true);
1127 cbox._lineitem = li;
1128 dojo.connect(cbox, 'onChange', updateOrderIdent);
1131 changeComboBox(typeSel); // force the initial draw
1132 typeSel.onchange = function() {changeComboBox(typeSel)};
1135 this.testOrderIdentPerms = function(org, callback) {
1137 new openils.User().getPermOrgList(
1138 'ACQ_SET_LINEITEM_IDENTIFIER',
1140 console.log('found orgs = ' + orgs);
1141 for (var i = 0; i < orgs.length; i++) {
1142 if (Number(orgs[i]) == Number(org)) {
1143 self.orderIdentAllowed = true;
1144 if (callback) callback();
1148 if (callback) callback();
1154 this.checkClaimEligibility = function(li, callback, row) {
1155 /* Assume always eligible, i.e. from this interface we don't care about
1156 * claim eligibility any more. this is where the user would force a
1158 this.clearEligibility(li);
1159 this.claimEligibleLidByLi[li.id()] = li.lineitem_details().map(
1160 function(lid) { return lid.id(); }
1162 li.lineitem_details().forEach(
1163 function(lid) { self.claimEligibleLid[lid.id()] = true; }
1165 this.reconsiderClaimControl(li, row);
1166 if (callback) callback(li);
1168 this.clearEligibility(li);
1169 fieldmapper.standardRequest(
1170 ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
1171 "params": [openils.User.authtoken, {"lineitem": li.id()}],
1173 "onresponse": function(r) {
1174 if (r = openils.Util.readResponse(r)) {
1175 self.claimEligibleLidByLi[li.id()].push(
1178 self.claimEligibleLid[r.lineitem_detail()] = true;
1181 "oncomplete": function() {
1182 self.reconsiderClaimControl(li, row);
1183 if (typeof(callback) == "function")
1191 this.updateLiNotesCount = function(li, row) {
1192 if (!row) row = this._findLiRow(li);
1194 var has_notes = (li.lineitem_notes().filter(
1195 function(o) { return Boolean (o.alert_text()); }
1198 /* U+2691 is the code point for a filled-in flag character */
1199 nodeByName("notes_alert_flag", row).innerHTML =
1200 has_notes ? "⚑" : "";
1201 nodeByName("noteslink", row).style.fontStyle =
1202 has_notes ? "italic" : "normal";
1203 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
1206 /* XXX NOT related to _updateLiState(). rethink */
1207 this.updateLiState = function(li, row) {
1208 if (!row) row = this._findLiRow(li);
1210 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
1211 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
1213 // always allow access to LI history
1214 nodeByName('action_view_history', row).onclick =
1215 function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
1217 /* handle row coloring for based on LI state */
1218 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1219 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
1221 // Expose invoice actions for any lineitem that is linked to a PO
1222 if (li.purchase_order()) {
1223 openils.Util.show(nodeByName("invoices_span", row), "inline");
1224 var link = nodeByName("invoices_link", row);
1225 link.onclick = function() {
1226 openils.XUL.newTabEasy(
1227 oilsBasePath + "/acq/search/unified?so=" +
1228 base64Encode({"jub":[{"id": li.id()}]}) + "&rt=invoice"
1236 * If we haven't fleshed the lineitem_details, default to allowing access to the
1237 * holdings maintenence actions. The alternative is to flesh LIDs on every lineitem,
1238 * but that will add to page render time. Let's see if this will suffice...
1240 var lids = li.lineitem_details();
1242 (lids && !lids.filter(function(lid) { return lid.eg_copy_id() })[0] )) {
1244 actUpdateBarcodes.disabled = false;
1245 actUpdateBarcodes.onclick = function() {
1246 self.showRealCopyEditUI(li);
1247 nodeByName("action_none", row).selected = true;
1249 actHoldingsMaint.disabled = false;
1250 actHoldingsMaint.onclick =
1251 self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
1254 var state_cell = nodeByName("li_state_" + li.state(), row);
1256 // re-hide any state label nodes which may have been un-hidden
1257 // through previous actions.
1258 dojo.query('[state-label]', row).forEach(function(node) {
1259 openils.Util.hide(node)
1262 if (li.state() == 'cancelled') {
1263 if(typeof li.cancel_reason() == "object") {
1265 // clear the stock "Canceled" label, since we have more
1266 // information to replace it with.
1267 state_cell.innerHTML = '';
1269 var holds_state = dojo.create(
1271 "style": "border-bottom: 1px dashed #000;",
1272 "innerHTML": li.cancel_reason().label()
1273 }, state_cell, "only"
1277 "label": "<em>" + li.cancel_reason().label() +
1278 "</em><br />" + li.cancel_reason().description(),
1279 "connectId": [holds_state]
1280 }, dojo.create("span", null, state_cell, "last")
1283 if (li.cancel_reason().keep_debits() == 't') {
1284 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1285 openils.Util.addCSSClass(row, "oils-acq-li-state-delayed");
1288 console.log('li cancel_reason is un-fleshed. Please fix');
1292 openils.Util.show(state_cell);
1296 this._setAlertStore = function() {
1297 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
1299 "data": acqliat.toStoreData(
1302 "owning_lib": aou.orgNodeTrail(
1303 aou.findOrgUnit(openils.User.user.ws_ou())
1304 ).map(function(o) { return o.id(); })
1310 acqLitAlertAlertText.setValue(); /* make the store "live" */
1311 acqLitAlertAlertText._store_ready = true;
1315 * Draws and shows the lineitem notes pane
1317 this.drawLiNotes = function(li) {
1319 this.focusLineitem = li.id();
1321 if (!acqLitAlertAlertText._store_ready)
1322 this._setAlertStore();
1325 li.lineitem_notes().sort(
1327 if(a.edit_time() < b.edit_time()) return 1;
1333 while(this.liNotesTbody.childNodes[0])
1334 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
1337 acqLitCreateNoteSubmit.onClick = function() {
1338 var value = acqLitCreateNoteText.attr('value');
1340 var note = new fieldmapper.acqlin();
1343 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
1346 note.lineitem(li.id());
1348 self.updateLiNotes(li, note);
1349 acqLitCreateNoteVendorPublic.attr("checked", false);
1350 acqLitCreateNoteText.attr("value", "");
1353 acqLitCreateAlertSubmit.onClick = function() {
1354 if (!acqLitAlertAlertText.item) {
1355 alert(localeStrings.ALERT_UNSELECTED);
1359 var alert_text = new fieldmapper.acqliat().fromStoreItem(
1360 acqLitAlertAlertText.item
1362 var value = acqLitAlertNoteValue.attr("value") || "";
1364 var note = new fieldmapper.acqlin();
1366 note.lineitem(li.id());
1368 note.alert_text(alert_text);
1370 self.updateLiNotes(li, note);
1373 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
1377 * Draws a single lineitem note in the notes pane
1379 this.addLiNote = function(li, note) {
1380 if(note.isdeleted()) return;
1382 var row = self.liNotesRow.cloneNode(true);
1383 nodeByName("value", row).innerHTML = note.value();
1384 var alert_node = nodeByName("alert_code", row);
1385 if (note.alert_text()) {
1386 alert_node.innerHTML = dojo.string.substitute(
1388 aou.findOrgUnit(note.alert_text().owning_lib()).shortname(),
1389 note.alert_text().code()
1392 if (note.alert_text().description()) {
1395 "connectId": [alert_node],
1396 "label": note.alert_text().description()
1397 }, dojo.create("span", null, alert_node, "after")
1402 if (openils.Util.isTrue(note.vendor_public()))
1403 nodeByName("vendor_public", row).innerHTML =
1404 localeStrings.VENDOR_PUBLIC;
1406 nodeByName("delete", row).onclick = function() {
1407 note.isdeleted(true);
1408 self.liNotesTbody.removeChild(row);
1409 self.updateLiNotes(li);
1412 if(note.edit_time()) {
1413 nodeByName("edit_time", row).innerHTML =
1414 dojo.date.locale.format(
1415 dojo.date.stamp.fromISOString(note.edit_time()),
1416 {formatLength:'short'});
1419 self.liNotesTbody.appendChild(row);
1423 * Updates any new/changed/deleted notes on the server
1425 this.updateLiNotes = function(li, newNote) {
1431 notes = li.lineitem_notes().filter(
1433 if(note.ischanged() || note.isnew() || note.isdeleted())
1439 if(notes.length == 0) return;
1440 progressDialog.show();
1442 fieldmapper.standardRequest(
1443 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
1445 params : [this.authtoken, notes],
1446 onresponse : function(r) {
1447 var resp = openils.Util.readResponse(r);
1452 // remove the old changed notes
1454 dojo.forEach(li.lineitem_notes(),
1456 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
1460 li.lineitem_notes(list);
1463 progressDialog.hide();
1464 self.updateLiNotesCount(li);
1465 self.drawLiNotes(li);
1469 progressDialog.update(resp);
1470 var newnote = resp.note;
1472 if(!newnote.isdeleted()) {
1473 newnote.isnew(false);
1474 newnote.ischanged(false);
1475 li.lineitem_notes().push(newnote);
1482 this.updateLiPrice = function(input, li) {
1484 var price = input.value;
1485 if(Number(price) == Number(li.estimated_unit_price())) return;
1487 fieldmapper.standardRequest(
1488 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
1489 { async : false, // redundant w/ timeout
1491 params : [this.authtoken, li.id(), price],
1492 oncomplete : function(r) {
1493 openils.Util.readResponse(r);
1494 li.estimated_unit_price(price); // update local copy
1497 * If this is a PO and every visible lineitem has a price,
1498 * check again to see if this PO can be activated. Note that
1499 * every visible lineitem having a price does not guarantee it can
1500 * be activated, which is why we still make the call. Having a price
1501 * set for every visiable lineitem is just the lowest barrier to entry.
1504 var priceNodes = dojo.query('[name=price]', dojo.byId('acq-lit-tbody'));
1506 dojo.forEach(priceNodes, function(node) { if (node.value == '') allSet = false});
1507 if (allSet) checkCouldActivatePo();
1508 refreshPOSummaryAmounts();
1515 this.removeLineitem = function(liId) {
1516 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
1517 delete this.liCache[liId];
1518 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
1521 this.drawInfo = function(liId) {
1522 this.focusLineitem = liId;
1523 if (!this._isRelatedViewer) {
1524 var d = dojo.byId("acq-lit-info-related");
1525 if (!this.relCache[liId]) {
1526 fieldmapper.standardRequest(
1529 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
1532 "params": [openils.User.authtoken, liId],
1533 "onresponse": function(r) {
1534 self.relCache[liId] = openils.Util.readResponse(r);
1535 nodeByName("related_number", d).innerHTML =
1536 self.relCache[liId];
1538 self.relCache[liId] >1 ? "show" : "hide"
1544 nodeByName("related_number", d).innerHTML = this.relCache[liId];
1545 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
1550 openils.acq.Lineitem.fetchAttrDefs(
1552 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
1557 this.toggleInlineCopies = function() {
1558 // if any inline copies are not displayed,
1559 // display them all otherwise, hide them all.
1561 var displayAll = false;
1563 for (var liId in this.liCache) {
1564 if (!this.inlineCopiesVisible(liId)) {
1570 for (var liId in this.liCache) {
1571 var row = dojo.byId('acq-inline-copies-row-' + liId);
1573 if (!row || row._hidden) {
1574 this.drawInlineCopies(liId);
1576 } else { // hide all
1578 // drawInlineCopies() on a visible row will hide it.
1579 this.drawInlineCopies(liId);
1586 this.inlineCopiesVisible = function(liId) {
1587 var row = dojo.byId('acq-inline-copies-row-' + liId);
1588 return (row && !row._hidden);
1591 this.refreshInlineCopies = function(all, reFetch) {
1593 var liIds = this.inlineCopiesNeedingRefresh;
1594 if (all) liIds = openils.Util.objectProperties(liCache);
1595 liIds.forEach(function(liId) {
1596 if (self.inlineCopiesVisible(liId)) {
1597 self.drawInlineCopies(liId, reFetch); // hide
1598 self.drawInlineCopies(liId, reFetch); // re-draw
1603 // draw inline copy table. if the table is
1604 // already visible, hide the table as-is
1605 // reFetch forces a retrieval of the lineitem and
1606 // copies from the server. otherwise the locally
1607 // cached version of each is used.
1608 this.drawInlineCopies = function(liId, reFetch) {
1611 // find or create the row where the inline copies table will live
1612 var containerRow = dojo.byId('acq-inline-copies-row-' + liId);
1613 var liRow = dojo.query('[li=' + liId + ']')[0];
1615 if (!containerRow) {
1617 // build the inline copies container row and add it to
1618 // the DOM directly after the primary lineitem row
1620 containerRow = self.inlineCopyContainer.cloneNode(true);
1621 containerRow.id = 'acq-inline-copies-row-' + liId;
1623 if (liRow.nextSibling) {
1624 self.tbody.insertBefore(containerRow, liRow.nextSibling);
1626 self.tbody.appendChild(containerRow);
1631 // toggle the visible state
1632 containerRow._hidden = !containerRow._hidden;
1633 openils.Util.toggle(containerRow, 'table-row');
1635 if (containerRow._hidden) return; // hide only
1638 var handler = function(li) {
1640 var tbody = dojo.query(
1641 '[name=acq-li-inline-copies-tbody]',
1644 // reset the table before adding copy rows
1645 while (tbody.childNodes[0])
1646 tbody.removeChild(tbody.childNodes[0]);
1648 if(li.lineitem_details().length == 0) {
1650 self.inlineNoCopies.cloneNode(true));
1651 return; // no copies to show
1654 // add a row to the inline copy table for each copy
1655 dojo.forEach(li.lineitem_details(),
1657 var row = self.inlineCopyTemplate.cloneNode(true);
1658 tbody.appendChild(row);
1659 self.addInlineCopy(li, copy, row);
1664 this._fetchLineitem(liId, handler, reFetch);
1667 /** Draw read-only copy widgets for inline copies */
1668 this.addInlineCopy = function(li, copy, row) {
1671 dojo.forEach(liDetailFields,
1674 var widget = new openils.widget.AutoFieldWidget({
1677 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1678 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1679 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1681 parentNode : dojo.query('[name=' + field + ']', row)[0],
1690 /* For a given list of lineitem ids, build a list of full lineitems
1691 * re-using the fetching logic that is otherwise typical to use in this
1694 * If we've already got a lineitem in the cache, just use that.
1696 * Once we've built a list of lineitems, call callback(thatlist).
1698 this.fetchLineitemsById = function(id_list, callback) {
1699 var total = id_list.length;
1700 var result_list = [];
1702 var inner = function(li) {
1703 result_list.push(li)
1705 callback(result_list);
1708 id_list.forEach(function(id) { self._fetchLineitem(id, inner); });
1711 this._fetchLineitem = function(liId, handler, force) {
1713 var li = this.liCache[liId];
1714 if(li && li.marc() && li.lineitem_details() && !force)
1717 fieldmapper.standardRequest(
1718 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
1721 params: [self.authtoken, liId, {
1723 flesh_cancel_reason: true,
1724 flesh_li_details: true,
1726 flesh_fund_debit: true }],
1728 oncomplete: function(r) {
1729 var li = openils.Util.readResponse(r);
1730 self.liCache[liId] = li;
1737 this._drawInfo = function(li) {
1739 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
1741 if(li.eg_bib_id()) {
1742 openils.Util.hide('acq-lit-marc-order-record-label');
1743 openils.Util.hide(acqLitEditOrderMarc.domNode);
1744 openils.Util.show('acq-lit-marc-real-record-label');
1746 openils.Util.show('acq-lit-marc-order-record-label');
1747 openils.Util.show(acqLitEditOrderMarc.domNode);
1748 openils.Util.hide('acq-lit-marc-real-record-label');
1751 this.drawMarcHTML(li);
1752 this.infoTbody = dojo.byId('acq-lit-info-tbody');
1755 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
1756 while(this.infoTbody.childNodes[0])
1757 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
1759 for(var i = 0; i < li.attributes().length; i++) {
1760 var attr = li.attributes()[i];
1761 var row = this.infoRow.cloneNode(true);
1763 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
1764 var name = openils.acq.Lineitem.attrDefs[type].filter(
1766 return (a.code() == attr.attr_name());
1768 ).pop().description();
1770 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
1771 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
1772 this.infoTbody.appendChild(row);
1775 if (!this._isRelatedViewer) {
1776 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
1777 oilsBasePath + "/acq/lineitem/related/" + li.id();
1780 // if a top scroll point is defined, jump up to it here
1781 var node = dojo.byId('oils-scroll-to-top');
1782 if (node) dijit.scrollIntoView(node);
1785 this.generateMakeRecTab = function(bib_id,default_view, row) {
1789 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
1792 show_nav_buttons : true,
1793 show_print_button : true,
1794 opac_url : xulG.url_prefix('opac_rdetail|' + bib_id),
1795 default_view : default_view
1799 if(row) nodeByName("action_none", row).selected = true;
1803 this.drawMarcHTML = function(li) {
1804 var params = [null, true, li.marc()];
1806 params = [li.eg_bib_id(), true];
1808 fieldmapper.standardRequest(
1809 ['open-ils.search', 'open-ils.search.biblio.record.html'],
1812 oncomplete: function(r) {
1813 dojo.byId('acq-lit-marc-div').innerHTML =
1814 openils.Util.readResponse(r);
1820 this.drawCopies = function(liId, force_fetch) {
1821 this.focusLineitem = liId;
1822 if (typeof force_fetch == "undefined")
1823 force_fetch = false;
1825 var cgi = new openils.CGI();
1826 var source = cgi.param('source');
1827 if (source && source.match(/invoice/)) {
1828 // got here from the invoice page, show the 'return-to-invoice' button
1829 var cgi = new openils.CGI({url : source});
1830 cgi.param('focus_li', liId);
1831 openils.Util.show(dojo.byId('acq-lit-copies-back-to-invoice-button-wrapper'), 'inline');
1832 var button = dojo.byId('acq-lit-copies-back-to-invoice-button');
1833 button.onclick = function() { location.href = cgi.url() };
1836 openils.acq.Lineitem.fetchAndRender(liId, {},
1837 function(li, html) {
1838 dojo.byId('acq-lit-copies-li-summary').innerHTML = html;
1842 this.show('copies');
1844 this.copyCache = {};
1845 this.copyWidgetCache = {};
1846 this.oldCopyWidgetCache = {};
1847 this.virtDfaCounts = {};
1848 this.realDfaCache = {};
1851 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
1852 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
1853 acqLitCopyCountInput.attr('value', '0');
1855 if (this.isPO && PO && PO.order_date()) {
1856 // prevent adding copies to activated POs
1857 acqLitCopyCountInput.attr('disabled', true);
1858 acqLitAddCopyCount.attr('disabled', true);
1861 while(this.copyTbody.childNodes[0])
1862 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
1864 this._drawBatchCopyWidgets();
1866 this._drawDistribApplied(liId);
1868 this._fetchDistribFormulas(
1870 openils.acq.Lineitem.fetchAttrDefs(
1872 self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch);
1879 this._saveDistribAppliedTemplates = function() {
1880 if (!this._appliedDistribTemplate) {
1881 this._appliedDistribTemplate =
1882 dojo.byId("acq-lit-distrib-applied-tbody").
1883 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
1884 dojo.attr(this._appliedDistribTemplate, "id");
1888 this._drawDistribApplied = function(liId) {
1889 /* Build this table while hidden to prevent rendering artifacts */
1890 openils.Util.hide("acq-lit-distrib-applied-tbody");
1892 this._saveDistribAppliedTemplates();
1894 /* Remove any rows in the table from previous populations */
1895 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
1896 forEach(dojo.destroy);
1898 /* Unregister all dijits previously created (for some reason this isn't
1899 * covered by the above destroy calls). */
1900 dijit.registry.forEach(
1901 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
1904 /* Populate the table with our liId */
1906 fieldmapper.standardRequest(
1908 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
1911 "params": [self.authtoken, liId],
1912 "onresponse": function(r) {
1913 var dfa = openils.Util.readResponse(r);
1916 self.realDfaCache[dfa.id()] = dfa;
1917 self._drawDistribAppliedUnit(dfa);
1920 "oncomplete": function() {
1921 /* Reveal built table */
1924 "acq-lit-distrib-applied-tbody", "table-row-group"
1932 this._drawDistribAppliedUnit = function(dfa) {
1933 var new_row = false;
1934 var row = dojo.query(
1935 'tr[formula="' + dfa.formula().id() + '"]',
1936 "acq-lit-distrib-applied-tbody"
1941 row = dojo.clone(this._appliedDistribTemplate);
1942 dojo.attr(row, "formula", dfa.formula().id());
1943 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
1946 var td = dojo.query("td", row)[0];
1948 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1949 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1952 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1954 new dijit.form.Button(
1956 "onClick": function() {
1957 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1958 self.deleteDfa(dfa);
1961 /* XXX I /cannot/ make the following work in as a CSS class
1962 * for some reason. So frustrating... */
1963 "style": function(id) {
1965 "font-weight: bold; color: #c00;" :
1967 }(dfa.id()) + "margin: 0 6px;display: inline;"
1968 }, "dfa-button-" + dfa.id()
1972 "connectId": ["dfa-button-" + dfa.id()],
1973 "label": dojo.string.substitute(
1974 localeStrings.DFA_TIP, dfa.id() > 0 ? [
1975 openils.User.formalName(dfa.creator()),
1976 dojo.date.locale.format(
1977 dojo.date.stamp.fromISOString(dfa.create_time()),
1978 {"formatLength":"short"}
1980 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
1982 }, "dfa-tip-" + dfa.id()
1986 this.deleteDfa = function(dfa) {
1987 if (dfa.id() > 0) { /* real */
1988 this.pcrud.eliminate(
1991 "oncomplete": function() {
1992 self._removeDistribApplied(dfa.id());
1993 delete self.realDfaCache[dfa.id()];
1997 } else { /* virtual */
1998 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
1999 this.virtDfaCounts[dfa.formula().id()] = 0;
2000 /* hasn't been saved yet, so no need to do anything server side */
2001 this._removeDistribApplied(dfa.id());
2006 this._removeDistribApplied = function(dfaId) {
2007 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
2008 dijit.registry.forEach(
2009 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
2011 this._removeDistribAppliedEmptyRows();
2014 this._removeAllDistribAppliedVirtual = function() {
2015 /* Unregister dijits */
2016 dijit.registry.forEach(
2017 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
2019 this._removeDistribAppliedEmptyRows();
2022 this._removeDistribAppliedEmptyRows = function() {
2023 /* Remove any rows with no DFA at all */
2024 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
2026 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
2032 * Insert a new row into the distribution formula selection form
2034 this._addDistribFormulaRow = function() {
2037 if (!self.distribForms) {
2038 // no formulas, hide the form
2039 openils.Util.hide('acq-lit-distrib-formula-table');
2043 if(!this.distribFormulaTemplate)
2044 this.distribFormulaTemplate =
2045 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
2047 var row = this.distribFormulaTemplate.cloneNode(true);
2048 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
2050 this.dfSelector = new dijit.form.FilteringSelect(
2051 {"labelAttr": "dynLabel", "labelType": "html"},
2052 nodeByName("selector", row)
2054 this._updateFormulaStore();
2055 this.dfSelector.fetchProperties =
2056 {"sort": [{"attribute": "use_count", "descending": true}]};
2058 var apply = new dijit.form.Button(
2059 {"label": localeStrings.APPLY},
2060 nodeByName('set_button', row)
2063 var reset = new dijit.form.Button(
2064 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
2065 nodeByName("reset_button", row)
2068 dojo.connect(apply, 'onClick',
2070 var form_id = self.dfSelector.attr("value");
2071 if(!form_id) return;
2072 self._applyDistribFormula(form_id);
2073 reset.attr("disabled", false);
2077 dojo.connect(reset, 'onClick',
2079 self.restoreCopyFieldsBeforeDF();
2080 self.virtDfaCounts = {};
2081 self.virtDfaId = -1;
2083 self._updateFormulaStore();
2084 self._removeAllDistribAppliedVirtual();
2085 reset.attr("disabled", "true");
2092 * Applies a distrib formula to the current set of copies
2094 this._applyDistribFormula = function(formula) {
2095 if(!formula) return;
2097 formula = this.distribForms.filter(
2098 function(form) { return form.id() == formula; }
2101 var copyRows = dojo.query('tr', self.copyTbody);
2103 if (this.dfeOffset >= copyRows.length) {
2104 alert(localeStrings.OUT_OF_COPIES);
2108 var entries_applied = 0;
2110 var rowIndex = this.dfeOffset;
2111 rowIndex < copyRows.length;
2115 var row = copyRows[rowIndex];
2116 var copy_id = row.getAttribute('copy_id');
2117 var copyWidgets = this.copyWidgetCache[copy_id];
2118 var entryIndex = this.dfeOffset;
2121 // find the correct entry for the current row
2122 dojo.forEach(formula.entries(),
2125 entryIndex += e.item_count();
2126 if(entryIndex > rowIndex)
2134 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
2135 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
2138 this.saveCopyFieldsBeforeDF(copy_id);
2139 this._copy_fields_for_acqdf.forEach(
2141 if(entry[field]()) {
2142 copyWidgets[field].attr('value', (entry[field]()));
2149 if (entries_applied) {
2150 this.virtDfaCounts[formula.id()] =
2151 ++(this.virtDfaCounts[formula.id()]) || 1;
2152 this._updateFormulaStore();
2153 this._drawDistribAppliedUnit(
2155 var dfa = new acqdfa();
2156 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
2159 this.dfeOffset += entries_applied;
2164 * This function updates the DF store for the dropdown so that use_counts
2165 * can reflect DF applications from this session before they're saved
2168 this._updateFormulaStore = function() {
2169 this.dfSelector.store = new dojo.data.ItemFileReadStore(
2171 "data": self._labelFormulasWithCounts(
2172 acqdf.toStoreData(self.distribForms)
2178 this.saveCopyFieldsBeforeDF = function(copy_id) {
2180 if (!this.oldCopyWidgetCache[copy_id]) {
2181 var copyWidgets = this.copyWidgetCache[copy_id];
2183 this.oldCopyWidgetCache[copy_id] = {};
2184 this._copy_fields_for_acqdf.forEach(
2186 self.oldCopyWidgetCache[copy_id][f] =
2187 copyWidgets[f].attr("value");
2193 this.restoreCopyFieldsBeforeDF = function() {
2195 for (var copy_id in this.oldCopyWidgetCache) {
2196 this._copy_fields_for_acqdf.forEach(
2198 self.copyWidgetCache[copy_id][f].attr(
2199 "value", self.oldCopyWidgetCache[copy_id][f]
2206 this._labelFormulasWithCounts = function(store_data) {
2207 for (var key in store_data.items) {
2208 var obj = store_data.items[key];
2209 obj.use_count = Number(obj.use_count); /* needed for sorting */
2211 if (this.virtDfaCounts[obj.id])
2212 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
2214 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
2215 obj.use_count + "]</span> " + obj.name;
2221 * This method formerly would not refetch the DF formulas if they'd been
2222 * loaded already, but now it always re-fetches, since use_count changes.
2224 /** TODO: port distrib-formula selector to autofieldwidget+pcrud/dojo store */
2225 this._fetchDistribFormulas = function(onload) {
2226 fieldmapper.standardRequest(
2228 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
2231 "params": [openils.User.authtoken, 0, 500],
2232 "oncomplete": function(r) {
2233 self.distribForms = openils.Util.readResponse(r);
2234 if(!self.distribForms || self.distribForms.length == 0) {
2235 self.distribForms = [];
2237 self._addDistribFormulaRow();
2244 this._drawBatchCopyWidgets = function() {
2245 var row = this.copyBatchRow;
2246 dojo.forEach(liDetailBatchFields,
2248 if(self.copyBatchRowDrawn) {
2249 self.copyBatchWidgets[field].attr('value', null);
2251 var args = self.afwCopyFieldArgs(field, "CREATE_PICKLIST");
2252 args.parentNode = dojo.query('[name='+field+']', row)[0];
2254 var widget = new openils.widget.AutoFieldWidget(args);
2257 if (field == "fund" && w.store)
2258 self._ensureCSSFundClasses(w.store);
2259 self.copyBatchWidgets[field] = w;
2262 if (field == "fund") {
2264 widget.widget, "onChange", function(val) {
2265 self._updateFundSelectorStyle(widget, val);
2272 this.copyBatchRowDrawn = true;
2275 this.batchCopyUpdate = function() {
2277 for(var k in this.copyWidgetCache) {
2278 var cache = this.copyWidgetCache[k];
2279 dojo.forEach(liDetailBatchFields, function(f) {
2280 var newval = self.copyBatchWidgets[f].attr('value');
2281 if(newval) cache[f].attr('value', newval);
2286 this._drawCopies = function(li) {
2289 // this button sets the total number of copies for a given lineitem
2290 acqLitAddCopyCount.onClick = function() {
2291 var count = acqLitCopyCountInput.attr('value');
2294 while(self.copyCount() < count)
2297 // delete rows if necessary
2298 var diff = self.copyCount() - count;
2300 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
2301 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
2302 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
2304 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2310 if(li.lineitem_details().length > 0) {
2311 dojo.forEach(li.lineitem_details(),
2313 self.addCopy(li, copy);
2321 this.copyCount = function() {
2323 for(var id in this.copyCache) {
2324 if(!this.copyCache[id].isdeleted())
2330 this.virtCopyId = -1;
2331 this.addCopy = function(li, copy) {
2332 var row = this.copyRow.cloneNode(true);
2333 this.copyTbody.appendChild(row);
2337 copy = new fieldmapper.acqlid();
2339 copy.id(this.virtCopyId--);
2340 copy.lineitem(li.id());
2343 this.copyCache[copy.id()] = copy;
2344 row.setAttribute('copy_id', copy.id());
2345 self.copyWidgetCache[copy.id()] = {};
2347 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2349 var rcvr = copy.receiver();
2351 if (!userCache[rcvr]) {
2352 if(rcvr == openils.User.user.id()) {
2353 userCache[rcvr] = openils.User.user;
2355 userCache[rcvr] = fieldmapper.standardRequest(
2356 ['open-ils.actor', 'open-ils.actor.user.retrieve'],
2357 {params: [openils.User.authtoken, rcvr]}
2361 dojo.query('[name=receiver]', row)[0].innerHTML = userCache[rcvr].usrname();
2364 dojo.forEach(liDetailFields,
2367 if (field == "fund") {
2368 searchFilter = (copy.fund() ?
2369 {"-or": {"active": "t", "id": copy.fund()}} :
2371 searchFilter.org = fundSearchFilter.org;
2373 searchFilter = null;
2376 var readOnly = false;
2378 // TODO: Add support for changing the owning_lib after real copies have been made.
2379 // owning_lib is order data as much as its item data
2380 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
2384 // TODO: add support for changing the fund after debits have been created
2385 // Note: invoicing allows the change
2386 if(copy.fund_debit() && field == 'fund') {
2391 var widget = new openils.widget.AutoFieldWidget({
2394 labelFormat : (field == 'fund') ? fundLabelFormat : null,
2395 searchFormat : (field == 'fund') ? fundSearchFormat : null,
2396 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
2397 searchFilter : searchFilter,
2398 noCache: (field == "fund"),
2400 parentNode : dojo.query('[name='+field+']', row)[0],
2401 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2402 readOnly : readOnly,
2403 orgDefaultsToWs : true
2407 // make sure we capture the value from any async widgets
2410 if (field == "fund" && w.store)
2411 self._ensureCSSFundClasses(w.store);
2414 copy[field](ww.getFormattedValue())
2416 self.copyWidgetCache[copy.id()][field] = w;
2418 dojo.connect(w, 'onChange',
2420 if (field == "fund")
2421 self._updateFundSelectorStyle(widget, val);
2423 if (!readOnly && (copy.isnew() || val != copy[field]())) {
2424 // prevent setting ischanged() automatically on widget load for existing copies
2425 copy[field](widget.getFormattedValue())
2426 copy.ischanged(true);
2435 this.updateLidState(copy, row);
2438 this._ensureCSSFundClass = function(id) {
2439 if (!this.fundStyleSheet) {
2441 "style", {"type": "text/css"},
2442 document.getElementsByTagName("head")[0], "last"
2444 this.fundStyleSheet = document.styleSheets[
2445 document.styleSheets.length - 1
2449 var cn = "fund_" + id;
2450 if (!this.haveFundClass[cn]) {
2451 fieldmapper.standardRequest(
2452 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
2454 "params": [openils.User.authtoken, id],
2456 "oncomplete": function(r) {
2457 r = openils.Util.readResponse(r);
2458 self.fundBalanceState[id] = r;
2460 if (r[0] /* stop */)
2461 style = fundStyles.stop;
2462 else if (r[1] /* warning */)
2463 style = fundStyles.warning;
2464 self.fundStyleSheet.insertRule(
2465 "." + cn + " { " + style + " }",
2466 self.fundStyleSheet.cssRules.length
2468 self.haveFundClass[cn] = true;
2475 this._ensureCSSFundClasses = function(store) {
2477 "query": {"id": "*"},
2478 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
2482 this._updateFundSelectorStyle = function(widget, fund_id) {
2483 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
2484 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
2487 this.updateLidState = function(copy, row) {
2490 if (typeof(row) == "undefined") {
2491 row = dojo.query('tr[copy_id="' + copy.id() + '"]', this.copyTbody)[0];
2495 var recv_link = nodeByName("receive", row);
2496 var unrecv_link = nodeByName("unreceive", row);
2497 var del_link = nodeByName("delete", row);
2498 var cxl_link = nodeByName("cancel", row);
2499 var claim_link = nodeByName("claim", row);
2500 var cxl_reason_link = nodeByName("cancel_reason", row);
2502 // by default, hide all the actions
2503 openils.Util.hide(del_link.parentNode);
2504 openils.Util.hide(recv_link);
2505 openils.Util.hide(unrecv_link);
2506 openils.Util.hide(cxl_link);
2507 openils.Util.hide(claim_link);
2508 openils.Util.hide(cxl_reason_link);
2510 if (copy.id() > 0) { // real copies (LIDs)
2512 if (copy.cancel_reason()) {
2514 /* --------- cancelled -------------------------- */
2516 /* XXX the following may leak memory in a long lived table:
2517 * dijits may not get destroyed... not positive. revisit. */
2518 var holds_reason = dojo.create(
2520 "style": "border-bottom: 1px dashed #000;",
2521 "innerHTML": copy.cancel_reason().label()
2522 }, cxl_reason_link, "only"
2526 "label": "<em>" + copy.cancel_reason().label() +
2527 "</em><br />" + copy.cancel_reason().description(),
2528 "connectId": [holds_reason]
2529 }, dojo.create("span", null, cxl_reason_link, "last")
2531 openils.Util.show(cxl_reason_link, "inline");
2533 if (copy.cancel_reason().keep_debits() == 't' ) {
2534 // allow further cancellation of "delayed" copies
2536 openils.Util.show(cxl_link, "inline");
2537 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2540 } else if (copy.recv_time()) {
2542 /* --------- received -------------------------- */
2544 openils.Util.show(unrecv_link, "inline");
2545 unrecv_link.onclick = function() {
2546 if (confirm(localeStrings.UNRECEIVE_LID))
2547 self.issueReceive(copy, /* rollback */ true);
2550 } else if (this.liCache[copy.lineitem()].state() == 'on-order') {
2552 /* --------- on order -------------------------- */
2554 openils.Util.show(recv_link, 'inline');
2555 openils.Util.show(cxl_link, "inline");
2557 recv_link.onclick = function() {
2558 if (self.checkLiAlerts(copy.lineitem()))
2559 self.issueReceive(copy);
2562 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2566 /* --------- pre-order copies -------------------------- */
2568 del_link.onclick = function() { self.deleteCopy(row) };
2569 openils.Util.show(del_link.parentNode);
2575 /* --------- virtual copies -------------------------- */
2577 del_link.onclick = function() { self.deleteCopy(row) };
2578 openils.Util.show(del_link.parentNode);
2582 this.cancelLid = function(lid_id) {
2583 lidCancelDialog._lid_id = lid_id;
2584 openils.Util.show(lidCancelDialog.domNode.parentNode);
2585 lidCancelDialog.show();
2586 if (!lidCancelDialog._prepared) {
2587 var widget = new openils.widget.AutoFieldWidget({
2588 "fmField": "cancel_reason",
2589 "fmClass": "acqlid",
2590 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
2591 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2593 "searchOptions" : {order_by : {"acqcr":"label"}}
2597 acqLidCancelButton.onClick = function() {
2598 if (w.attr("value")) {
2599 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
2601 lidCancelDialog._lid_id,
2605 lidCancelDialog.hide();
2608 lidCancelDialog._prepared = true;
2614 this._cancelLid = function(lid_id, reason) {
2615 fieldmapper.standardRequest(
2616 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
2617 "params": [openils.User.authtoken, lid_id, reason],
2619 "onresponse": function(r) {
2620 if (r = openils.Util.readResponse(r)) {
2622 for (var id in r.lid) {
2623 /* actually this should only iterate once */
2624 self.copyCache[id].cancel_reason(
2625 r.lid[id].cancel_reason
2627 self.updateLidState(self.copyCache[id]);
2636 this._confirmAlert = function(li, lin) {
2638 dojo.string.substitute(
2639 localeStrings.CONFIRM_LI_ALERT, [
2640 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2641 "title", "lineitem_marc_attr_definition"
2643 /* XXX it's really better add a parameter and to adjust
2644 * the format string rather than do this concatenation
2645 * here, but if someone wants this for 2.2 in a hurry,
2646 * we can sidestep the problem of updating the strings
2647 * while the translators are working. */
2649 aou.findOrgUnit(lin.alert_text().owning_lib()).shortname() +
2651 lin.alert_text().code()
2653 lin.alert_text().description() || "",
2660 this.checkLiAlerts = function(li_id) {
2661 var li = this.liCache[li_id];
2663 var alert_notes = li.lineitem_notes().filter(
2664 function(o) { return Boolean(o.alert_text()); }
2667 /* this is _intentionally_ not done in a call to forEach() ... */
2668 for (var i = 0; i < alert_notes.length; i++) {
2669 if (this.noteAcks[alert_notes[i].id()])
2671 else if (!this._confirmAlert(li, alert_notes[i]))
2674 this.noteAcks[alert_notes[i].id()] = true;
2680 this.deleteCopy = function(row) {
2681 var copy = this.copyCache[row.getAttribute('copy_id')];
2682 copy.isdeleted(true);
2684 delete this.copyCache[copy.id()];
2685 this.copyTbody.removeChild(row);
2688 this._virtDfaCountsAsList = function() {
2690 for (var key in this.virtDfaCounts) {
2691 for (var i = 0; i < this.virtDfaCounts[key]; i++)
2697 this.confirmBreachedCopyFunds = function(copies) {
2698 var stop = 0, warning = 0;
2702 var state = self.fundBalanceState[o.fund()];
2703 if (state[0] /* stop */)
2705 else if (state[1] /* warning */)
2712 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
2713 } else if (warning) {
2714 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
2719 this.saveCopyChanges = function(liId) {
2725 for(var id in this.copyCache) {
2726 var c = this.copyCache[id];
2727 if(!c.isdeleted()) total++;
2728 if(c.isnew() || c.ischanged() || c.isdeleted()) {
2729 if(c.id() < 0) c.id(null);
2735 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
2738 if (copies.length > 0) {
2739 if (!this.confirmBreachedCopyFunds(copies))
2742 if (typeof(this._copy_count_cb) == "function")
2743 this._copy_count_cb(liId, total);
2745 openils.Util.show("acq-lit-update-copies-progress");
2746 fieldmapper.standardRequest(
2747 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
2749 params: [openils.User.authtoken, copies],
2750 onresponse: function(r) {
2751 var res = openils.Util.readResponse(r);
2752 litUpdateCopiesProgress.update(res);
2754 oncomplete: function() {
2755 self.drawCopies(liId, true /* force_fetch */);
2756 openils.Util.hide("acq-lit-update-copies-progress");
2757 refreshPOSummaryAmounts();
2763 var dfa_list = this._virtDfaCountsAsList();
2764 if (dfa_list.length > 0) {
2765 fieldmapper.standardRequest(
2767 "open-ils.acq.distribution_formula.record_application"],
2770 "params": [openils.User.authtoken, dfa_list, liId],
2771 "onresponse": function(r) {
2772 var res = openils.Util.readResponse(r);
2773 if (res && res.length < dfa_list.length)
2774 alert(localeStrings.DFA_NOT_ALL);
2778 this.virtDfaCounts = {};
2781 if (this.inlineCopiesNeedingRefresh.indexOf(liId) < 0)
2782 this.inlineCopiesNeedingRefresh.push(liId);
2785 this._updateCreatePoPrepayCheckbox = function(prepay) {
2786 var prepay = openils.Util.isTrue(prepay);
2787 this._prepayRequiredByVendor = prepay;
2788 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
2791 this._confirmPoPrepaySituation = function() {
2792 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
2793 if (want_prepay != this._prepayRequiredByVendor) {
2796 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
2797 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
2804 this.applySelectedLiAction = function(action) {
2808 case 'delete_selected':
2809 this._deleteLiList(self.getSelected());
2812 case 'add_to_order':
2813 addToPoDialog._get_li = dojo.hitch(
2816 return this.getSelected(
2817 false, null, true, li_pre_po_states);
2820 if (addToPoDialog._get_li().length == 0) {
2821 alert(localeStrings.NO_LI_GENERAL);
2824 addToPoDialog.show();
2827 case 'create_order':
2828 this._loadPOSelect();
2829 acqLitPoCreateDialog.show();
2832 case 'save_picklist':
2833 acqLitSavePlDialog.show();
2836 case 'selector_ready':
2838 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
2839 acqLitChangeLiStateDialog.show();
2847 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
2850 case 'batch_create_invoice':
2851 this.batchCreateInvoice();
2854 case 'batch_link_invoice':
2855 this.batchLinkInvoice();
2858 case 'receive_lineitems':
2859 this.receiveSelectedLineitems();
2862 case 'rollback_receive_lineitems':
2863 this.rollbackReceiveLineitems();
2866 case 'create_assets':
2867 this.showAssetCreator();
2870 case 'export_attr_list':
2871 this.chooseExportAttr();
2874 case 'batch_apply_funds':
2875 this.applyBatchLiFunds();
2878 case 'add_brief_record':
2880 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
2882 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
2886 case "cancel_lineitems":
2887 console.log('HERE');
2888 this.maybeCancelLineitems();
2891 case "apply_claim_policy":
2892 var li_list = this.getSelected();
2893 this.claimPolicyPicker.attr("value", null);
2894 liClaimPolicyDialog.show();
2895 liClaimPolicySave.onClick = function() {
2896 self.changeClaimPolicy(
2898 self.claimPolicyPicker.attr("value"),
2902 self.setClaimPolicyControl(li);
2903 self.reconsiderClaimControl(li);
2906 liClaimPolicyDialog.hide();
2914 this.changeClaimPolicy = function(li_list, value, callback) {
2916 function(li) { li.claim_policy(value); }
2918 fieldmapper.standardRequest(
2919 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
2920 "params": [openils.User.authtoken, li_list],
2922 "oncomplete": function(r) {
2923 r = openils.Util.readResponse(r);
2924 if (callback) callback(r);
2930 this.showAssetCreator = function(onAssetsCreated) {
2931 if(!this.isPO) return;
2934 // first, let's see if this PO has any LI's that need to be merged/imported
2935 self.pcrud.search('jub', {purchase_order : this.isPO, eg_bib_id : null}, {
2937 oncomplete : function(r) {
2938 var resp = openils.Util.readResponse(r);
2939 if (resp && resp.length) {
2940 // PO has some non-linked jubs.
2942 self.show('asset-creator');
2943 if(!self.vlAgent.loaded)
2944 self.vlAgent.init();
2946 dojo.connect(assetCreatorButton, 'onClick',
2947 function() { self.createAssets(onAssetsCreated) });
2951 // all jubs linked, move on to asset creation
2952 self.createAssets(onAssetsCreated, true);
2958 this.createAssets = function(onAssetsCreated, noVl) {
2959 this.show('acq-lit-progress-numbers');
2961 var vlArgs = (noVl) ? {} : {vandelay : this.vlAgent.values()};
2962 this.batchProgress = {};
2963 progressDialog.show(false);
2964 progressDialog.attr("title", localeStrings.LI_CREATING_ASSETS);
2965 fieldmapper.standardRequest(
2966 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
2968 params: [this.authtoken, this.isPO, vlArgs],
2969 onresponse: function(r) {
2970 var resp = openils.Util.readResponse(r);
2971 self._updateProgressNumbers(resp, !Boolean(onAssetsCreated), onAssetsCreated, true);
2977 this.maybeCancelLineitems = function() {
2978 openils.Util.show("acq-lit-cancel-reason", "inline");
2979 if (!acqLitCancelLineitemsButton._prepared) {
2980 var widget = new openils.widget.AutoFieldWidget({
2981 "fmField": "cancel_reason",
2983 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
2984 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2986 "searchOptions" : {order_by : {"acqcr":"label"}}
2990 acqLitCancelLineitemsButton.onClick = function() {
2991 if (w.attr("value")) {
2992 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
2993 self._cancelLineitems(w.attr("value"));
2995 openils.Util.hide("acq-lit-cancel-reason");
2998 acqLitCancelLineitemsButton._prepared = true;
3004 this._cancelLineitems = function(reason) {
3006 var li_list = this.getSelected();
3008 // canceled lineitems may be canceled again if they were
3009 // previously delayed (keep_debits = true).
3010 li_list = li_list.filter(
3013 li.state() != 'cancelled' ||
3014 li.cancel_reason().keep_debits() == 't'
3019 id_list = li_list.map(function(l) {return l.id()});
3021 if (!id_list.length) {
3022 alert(localeStrings.NO_LI_GENERAL);
3025 fieldmapper.standardRequest(
3026 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
3027 "params": [openils.User.authtoken, id_list, reason],
3029 "onresponse": function(r) {
3030 if (r = openils.Util.readResponse(r)) {
3032 for (var id in r.li) {
3033 self.liCache[id].state(r.li[id].state);
3034 self.liCache[id].cancel_reason(
3035 r.li[id].cancel_reason
3037 self.updateLiState(self.liCache[id]);
3040 if (r.lid && self.copyCache) {
3041 for (var id in r.lid) {
3042 if (self.copyCache[id]) {
3043 self.copyCache[id].cancel_reason(
3044 r.lid[id].cancel_reason
3046 self.updateLidState(self.copyCache[id]);
3056 this.chooseExportAttr = function() {
3057 if (!acqLitExportAttrSelector._li_setup) {
3059 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
3061 "data": acqlimad.toStoreData(
3063 "acqlimad", {"code": li_exportable_attrs}
3068 acqLitExportAttrSelector.setValue();
3069 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
3070 acqLitExportAttrSelector._li_setup = true;
3072 openils.Util.show("acq-lit-export-attr-holder", "inline");
3075 this.exportAttrList = function() {
3076 var attr_def = acqLitExportAttrSelector.item;
3077 var li_list = this.getSelected();
3078 var value_list = li_list.map(
3080 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
3081 attr_def.code, "lineitem_marc_attr_definition"
3084 ).filter(function(attr) { return Boolean(attr); });
3086 if (value_list.length > 0) {
3087 if (value_list.length < li_list.length) {
3089 dojo.string.substitute(
3090 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
3097 openils.XUL.contentToFileSaveDialog(
3098 value_list.join("\n"),
3099 localeStrings.EXPORT_SAVE_DIALOG_TITLE
3105 alert(dojo.string.substitute(
3106 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
3110 openils.Util.hide("acq-lit-export-attr-holder");
3113 this.printPO = function() {
3114 if(!this.isPO) return;
3115 progressDialog.show(true);
3116 fieldmapper.standardRequest(
3117 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
3119 params: [this.authtoken, this.isPO, 'html'],
3120 oncomplete: function(r) {
3121 progressDialog.hide();
3122 var evt = openils.Util.readResponse(r);
3123 if(evt && evt.template_output()) {
3124 openils.Util.printHtmlString(evt.template_output().data());
3131 this.batchCreateInvoice = function() {
3132 var liIds = this.getSelected(
3133 false, null, true /* id_list */, li_active_states)
3134 if (!liIds.length) {
3135 alert(localeStrings.NO_LI_GENERAL);
3138 var path = oilsBasePath + '/acq/invoice/view?create=1';
3139 dojo.forEach(liIds, function(li, idx) { path += '&attach_li=' + li });
3140 if (openils.XUL.isXUL())
3141 openils.XUL.newTabEasy(path, localeStrings.NEW_INVOICE, null, true);
3143 location.href = path;
3146 this.batchLinkInvoice = function(create) {
3147 var liIds = this.getSelected(
3148 false, null, true /* id_list */, li_active_states)
3149 if (!liIds.length) {
3150 alert(localeStrings.NO_LI_GENERAL);
3153 if (!self.invoiceLinkDialogManager) {
3154 self.invoiceLinkDialogManager =
3155 new InvoiceLinkDialogManager("li");
3157 self.invoiceLinkDialogManager.target = liIds;
3158 acqLitLinkInvoiceDialog.show();
3161 this.receiveSelectedLineitems = function() {
3162 var states = li_post_po_states.filter(
3163 function(s) { return s != 'received' });
3164 var li_list = this.getSelected(null, null, null, states);
3166 if (!li_list.length) {
3167 alert(localeStrings.NO_LI_GENERAL);
3171 for (var i = 0; i < li_list.length; i++) {
3172 var li = li_list[i];
3174 if (li.state() != "received" &&
3175 !this.checkLiAlerts(li.id())) return;
3178 this.show('acq-lit-progress-numbers');
3181 fieldmapper.standardRequest(
3182 ['open-ils.acq', 'open-ils.acq.lineitem.receive.batch'],
3186 li_list.map(function(li) { return li.id(); })
3188 onresponse : function(r) {
3189 var resp = openils.Util.readResponse(r);
3190 self._updateProgressNumbers(resp, true);
3196 this.issueReceive = function(obj, rollback) {
3198 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
3200 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
3202 progressDialog.show(true);
3203 fieldmapper.standardRequest(
3204 ["open-ils.acq", method], {
3206 "params": [this.authtoken, obj.id()],
3207 "onresponse": function(r) {
3208 if (r = openils.Util.readResponse(r)) {
3209 self.fetchClaimInfo(
3210 part == "lineitem" ? obj.id() : obj.lineitem(),
3212 function() { self.handleReceive(r); }
3214 progressDialog.hide();
3222 * Handles the responses from receive and rollback ML calls.
3224 this.handleReceive = function(resp) {
3227 for (var li_id in resp.li) {
3228 for (var key in resp.li[li_id])
3229 self.liCache[li_id][key](resp.li[li_id][key]);
3230 self.updateLiState(self.liCache[li_id]);
3234 if (typeof(self.poUpdateCallback) == "function")
3235 self.poUpdateCallback(resp.po);
3238 for (var lid_id in resp.lid) {
3239 for (var key in resp.lid[lid_id])
3240 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
3241 self.updateLidState(self.copyCache[lid_id]);
3247 this.rollbackReceiveLineitems = function() {
3248 var li_id_list = this.getSelected(false, null, true);
3249 if (!li_id_list.length) {
3250 alert(localeStrings.NO_LI_GENERAL);
3254 if (!confirm(localeStrings.ROLLBACK_LI_RECEIVE_CONFIRM)) return;
3256 this.show('acq-lit-progress-numbers');
3259 fieldmapper.standardRequest(
3260 ['open-ils.acq', 'open-ils.acq.lineitem.receive.rollback.batch'],
3262 params: [this.authtoken, li_id_list],
3263 onresponse : function(r) {
3264 var resp = openils.Util.readResponse(r);
3265 self._updateProgressNumbers(resp, true);
3271 this._updateProgressNumbers = function(resp, reloadOnComplete, onComplete, clearProgressDialog) {
3272 this._updateProgressDialog(resp);
3273 this.vlAgent.handleResponse(resp,
3274 function(resp, res) {
3275 if (clearProgressDialog) {
3276 progressDialog.update({ "progress": 100});
3277 progressDialog.update_message();
3278 progressDialog.hide();
3279 progressDialog.attr("title", "");
3281 if(reloadOnComplete)
3282 location.href = location.href;
3284 onComplete(resp, res);
3289 this._updateProgressDialog = function(resp) {
3290 progressDialog.update({ "progress": (resp.progress / resp.total) * 100 });
3291 var keys = ['li', 'vqbr', 'bibs', 'lid', 'debits_accrued', 'copies'];
3292 for (var i = 0; i < keys.length; i++) {
3293 if (resp[keys[i]] > (this.batchProgress[keys[i]] || 0)) {
3294 progressDialog.update_message(
3295 dojo.string.substitute(
3296 localeStrings["ACTIVATE_" + keys[i].toUpperCase() + "_PROCESSED"],
3302 this.batchProgress = resp;
3305 this._createPO = function(fields) {
3306 var wantall = (fields.create_from == "all");
3308 /* If we're a picklist or purchase order already and the user wants
3309 * all lineitems, we might have pages' worth of lineitems haven't all
3310 * been loaded yet, so getSelected() won't find them. The server,
3311 * however, should know about all our lineitems, so let's ask the
3312 * server for a complete list.
3317 true, function(list) {
3318 self._createPOFromLineitems(fields, list);
3319 }, /* id_list */ true, li_pre_po_states
3322 this._createPOFromLineitems(
3323 fields, this.getSelected(
3324 false, null, true /* id_list */, li_pre_po_states)
3329 this._createPOFromLineitems = function(fields, selected) {
3330 if (selected.length == 0) {
3331 alert(localeStrings.NO_LI_GENERAL);
3336 var po = new fieldmapper.acqpo();
3337 po.provider(this.createPoProviderSelector.attr("value"));
3338 po.ordering_agency(this.createPoAgencySelector.attr("value"));
3339 po.prepayment_required(fields.prepayment_required[0] ? true : false);
3340 var name = this.createPoNameInput.attr('value');
3341 if (name) po.name(name); // avoid name=""
3343 // if we're creating assets, delay the asset creation
3344 // until after the PO is created. This will allow us to
3345 // use showAssetCreator() directly.
3347 fieldmapper.standardRequest(
3348 ["open-ils.acq", "open-ils.acq.purchase_order.create"],
3351 openils.User.authtoken,
3352 po, {lineitems : selected}
3354 onresponse : function(r) {
3355 var resp = openils.Util.readResponse(r);
3356 if (resp.complete) {
3357 // self.isPO is needed for showAssetCreator();
3358 self.isPO = resp.purchase_order.id();
3359 var redir = oilsBasePath + "/acq/po/view/" + self.isPO;
3360 if (fields.create_assets[0]) {
3361 self.showAssetCreator(
3362 function() {location.href = redir}
3365 location.href = redir;
3374 this.batchFundWidget = null;
3376 this.applyBatchLiFunds = function() {
3378 var liIds = this.getSelected().map(function(li) { return li.id(); });
3379 if(liIds.length == 0) return; // warn?
3382 batchFundUpdateDialog.show();
3384 if(!this.batchFundWidget) {
3385 this.batchFundWidget = new openils.widget.AutoFieldWidget({
3387 selfReference : true,
3388 labelFormat : fundLabelFormat,
3389 searchFormat : fundSearchFormat,
3390 searchFilter : fundSearchFilter,
3391 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
3392 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
3393 dijitArgs : { "required": true, "labelType": "html" },
3396 this.batchFundWidget.build();
3399 dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
3400 dojo.connect(batchFundUpdateSubmit, 'onClick',
3403 // TODO: call .dry_run first to test thresholds
3404 fieldmapper.standardRequest(
3405 ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
3408 openils.User.authtoken,
3410 self.batchFundWidget.widget.attr('value')
3412 oncomplete : function(r) {
3413 var resp = openils.Util.readResponse(r);
3415 location.href = location.href;
3424 this._deleteLiList = function(list, idx) {
3425 if(idx == null) idx = 0;
3426 if(idx >= list.length) return;
3431 if (this.isPO && (li.state() == "on-order" || li.state() == "received")) {
3432 /* It makes little sense to delete a lineitem from a PO that has
3433 * already been marked 'on-order'. Especially if EDI is in use,
3434 * such a purchase order will probably have already been shipped
3435 * off to a vendor, and mucking with it at this point could leave
3436 * your data in a bad state that doesn't jive with reality.
3438 * I could see making this restriction even firmer.
3440 * I could also see adjusting the li state comparisons, extending
3441 * the comparison to the PO's state, and/or providing functions
3442 * that house the logic for comparing states in a single location.
3444 * Yes, this will be really annoying if you have selected a lot
3445 * of lineitems to cancel that have been ordered. You'll get a
3446 * confirm dialog for each one.
3449 if (!confirm(localeStrings.DEL_LI_FROM_PO)) {
3450 self._deleteLiList(list, ++idx); /* move on to next in list */
3455 fieldmapper.standardRequest(
3457 this.isPO ? 'open-ils.acq.purchase_order.lineitem.delete' : 'open-ils.acq.picklist.lineitem.delete'],
3459 params: [openils.User.authtoken, liId],
3460 oncomplete: function(r) {
3461 self.removeLineitem(liId);
3462 self._deleteLiList(list, ++idx);
3468 this.editOrderMarc = function(li) {
3470 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
3471 to true in about:config */
3473 if(openils.XUL.isXUL()) {
3474 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul','','chrome');
3476 win = window.open('/xul/server/cat/marcedit.xul','','chrome');
3480 record : {marc : li.marc(), "rtype": "bre"},
3482 label: 'Save Record', // XXX I18N
3483 func: function(xmlString) {
3485 fieldmapper.standardRequest(
3486 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
3488 params: [openils.User.authtoken, li],
3489 oncomplete: function(r) {
3490 openils.Util.readResponse(r);
3492 self.drawInfo(li.id())
3498 'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
3499 'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
3503 this._savePl = function(values) {
3505 (values.which == 'all'),
3506 function(list) { self._savePlFromLineitems(values, list); }
3510 this._savePlFromLineitems = function(values, selected) {
3511 openils.Util.show("acq-lit-generic-progress");
3513 if(values.new_name) {
3514 openils.acq.Picklist.create(
3515 {name: values.new_name},
3521 oilsBasePath + "/acq/picklist/view/" + id;
3526 } else if(values.existing_pl) {
3527 // update lineitems to use an existing picklist
3529 values.existing_pl, selected, 0,
3532 oilsBasePath + "/acq/picklist/view/" +
3539 this._updateLiState = function(values, state, state_filter) {
3540 progressDialog.show(true);
3542 (values.which == 'all'),
3544 self._updateLiStateFromLineitems(values, state, list);
3545 }, false /* id_list */, state_filter
3549 this._updateLiStateFromLineitems = function(values, state, selected) {
3550 if(!selected.length) {
3551 try { progressDialog.hide() } catch(E) {};
3552 alert(localeStrings.NO_LI_GENERAL);
3555 dojo.forEach(selected, function(li) {li.state(state);});
3556 self._updateLiList(null, selected, 0,
3557 // TODO consider inline updates for efficiency
3558 function() { location.href = location.href }
3562 this._updateLiList = function(pl, list, idx, oncomplete) {
3563 if(idx >= list.length) return oncomplete();
3565 if(pl != null) li.picklist(pl);
3566 litGenericProgress.update({maximum: list.length, progress: idx});
3567 new openils.acq.Lineitem({lineitem:li}).update(
3569 self._updateLiList(pl, list, ++idx, oncomplete);
3574 this._loadPOSelect = function() {
3575 if (!this.createPoProviderSelector) {
3576 var widget = new openils.widget.AutoFieldWidget({
3577 "fmField": "provider",
3579 "searchFilter": {"active": "t"},
3580 "parentNode": dojo.byId("acq-lit-po-provider"),
3582 "onChange": function() {
3584 self._updateCreatePoPrepayCheckbox(
3585 this.item.prepayment_required()
3591 widget.build(function(w) { self.createPoProviderSelector = w; });
3594 this.createPoCheckDupes = function() {
3595 var org = self.createPoAgencySelector.attr('value');
3596 var name = self.createPoNameInput.attr('value');
3597 openils.Util.hide('acq-dupe-po-name');
3600 acqLitCreatePoSubmit.attr('disabled', false);
3604 acqLitCreatePoSubmit.attr('disabled', true);
3605 var orgs = fieldmapper.aou.descendantNodeList(org, true);
3606 new openils.PermaCrud().search('acqpo',
3607 {name : name, ordering_agency : orgs},
3608 {async : true, oncomplete : function(r) {
3609 var po = openils.Util.readResponse(r);
3611 if (po && (po = po[0])) {
3613 var link = dojo.byId('acq-dupe-po-link');
3614 openils.Util.show('acq-dupe-po-name', 'table-row');
3615 var dupe_path = '/acq/po/view/' + po.id();
3619 if (window.IAMBROWSER) {
3620 // TODO: integration
3624 link.onclick = function() {
3626 var loc = xulG.url_prefix('XUL_BROWSER?url=') +
3627 window.encodeURIComponent(
3628 xulG.url_prefix('EG_WEB_BASE' + dupe_path)
3632 {tab_name: '', browser:false},
3635 show_nav_buttons : true,
3636 show_print_button : true,
3643 link.onclick = function() {
3644 window.open(oilsBasePath + dupe_path, '_blank').focus();
3649 acqLitCreatePoSubmit.attr('disabled', false);
3655 if (!this.createPoAgencySelector) {
3656 var widget = new openils.widget.AutoFieldWidget({
3657 "fmField": "ordering_agency",
3659 "parentNode": dojo.byId("acq-lit-po-agency"),
3660 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3662 widget.build(function(w) {
3663 self.createPoAgencySelector = w;
3664 dojo.connect(w, 'onChange', self.createPoCheckDupes);
3668 if (!this.createPoNameInput) {
3669 var widget = new openils.widget.AutoFieldWidget({
3672 "parentNode": dojo.byId("acq-lit-po-name"),
3673 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3675 widget.build(function(w) {
3676 self.createPoNameInput = w;
3677 dojo.connect(w, 'onChange', self.createPoCheckDupes);
3682 this.showRealCopyEditUI = function(li) {
3687 this._fetchLineitem(li.id(),
3689 li = self.liCache[li.id()] = fullLi;
3693 id : li.lineitem_details().map(
3694 function(item) { return item.eg_copy_id() }
3698 oncomplete : function(r) {
3700 var r_list = openils.Util.readResponse( r );
3701 for (var i = 0; i < r_list.length; i++) {
3702 var copy = r_list[i];
3703 var volId = copy.call_number();
3704 var volume = self.volCache[volId];
3706 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
3708 copy.call_number(volume);
3709 copyList.push(copy);
3712 xulG.volume_item_creator( { 'existing_copies' : copyList } );
3715 alert('error in oncomplete: ' + E);
3724 this.drawBibFinder = function(li) {
3727 var liWrapper = new openils.acq.Lineitem({lineitem:li});
3730 ['isbn', 'upc', 'issn', 'title', 'author'],
3732 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
3734 if(field == 'title' || field == 'author') {
3735 query += field +':' + val + ' ';
3737 query += 'identifier|' + field + ':' + val + ' ';
3744 oilsBasePath + '/acq/lineitem/findbib?query=' + encodeURIComponent(query),
3745 '', 'resizable,scrollbars=1,chrome');
3747 win.window.recordFound = function(bibId) {
3750 var attrs = li.attributes();
3751 li.attributes(null);
3752 li.eg_bib_id(bibId);
3754 fieldmapper.standardRequest(
3755 ["open-ils.acq", "open-ils.acq.lineitem.update"],
3757 "params": [openils.User.authtoken, li],
3759 "oncomplete": function(r) {
3760 if(openils.Util.readResponse(r)) {
3761 location.href = location.href;