1 dojo.require('dojo.date.locale');
2 dojo.require('dojo.date.stamp');
3 dojo.require('dijit.form.Button');
4 dojo.require('dijit.form.TextBox');
5 dojo.require('dijit.form.FilteringSelect');
6 dojo.require('dijit.form.Textarea');
7 dojo.require('dijit.Tooltip');
8 dojo.require('dijit.ProgressBar');
9 dojo.require('dojox.timing.doLater');
10 dojo.require('openils.acq.Lineitem');
11 dojo.require('openils.acq.PO');
12 dojo.require('openils.acq.Picklist');
13 dojo.require('openils.widget.AutoFieldWidget');
14 dojo.require('dojo.data.ItemFileReadStore');
15 dojo.require('openils.widget.ProgressDialog');
16 dojo.require('openils.PermaCrud');
17 dojo.require("openils.widget.PCrudAutocompleteBox");
18 dojo.require('dijit.form.ComboBox');
19 dojo.require('openils.CGI');
21 if (!localeStrings) { /* we can do this because javascript doesn't have block scope */
22 dojo.requireLocalization('openils.acq', 'acq');
23 var localeStrings = dojo.i18n.getLocalization('openils.acq', 'acq');
25 const XUL_OPAC_WRAPPER = 'chrome://open_ils_staff_client/content/cat/opac.xul';
26 var li_exportable_attrs = ["issn", "isbn", "upc"];
28 var fundLabelFormat = [
29 '<span class="fund_${0}">${1} (${2})</span>', 'id', 'code', 'year'
31 var fundSearchFormat = ['${0} (${1})', 'code', 'year'];
32 var fundSearchFilter = {active : 't'};
33 var fundSort = {order_by : {"acqf":"year DESC, code"}};
35 function nodeByName(name, context) {
36 return dojo.query('[name='+name+']', context)[0];
39 // for caching linked users. e.g. lineitem_detail.receiver
42 var liDetailBatchFields = ['fund', 'owning_lib', 'location', 'collection_code', 'circ_modifier', 'cn_label'];
43 var liDetailFields = liDetailBatchFields.concat(['barcode', 'note']);
45 "stop": "color: #c00; font-weight: bold;",
46 "warning": "color: #c93;"
50 * We're not using 'approved' today, but there is API support for it.
51 * I believe it's been replaced by "order-ready".
52 * LIs go new => selector-ready => order-ready/approved => pending-order =>
53 * on-order => received. 'cancelled' can pop up anywhere.
56 var li_pre_po_states = ["new", "selector-ready", "order-ready", "approved"];
57 var li_post_po_states = ["pending-order", "on-order", "received", "cancelled"];
58 var li_active_states = li_pre_po_states.concat(li_post_po_states);
60 function AcqLiTable() {
67 this.haveFundClass = {}
68 this.fundBalanceState = {};
69 this.realDfaCache = {};
70 this.virtDfaCounts = {};
73 this.claimEligibleLidByLi = {};
74 this.claimEligibleLid = {};
75 this.toggleState = false;
76 this.tbody = dojo.byId('acq-lit-tbody');
79 this.authtoken = openils.User.authtoken;
80 this.pcrud = new openils.PermaCrud();
81 this.rowTemplate = this.tbody.removeChild(dojo.byId('acq-lit-row'));
82 this.copyTbody = dojo.byId('acq-lit-li-details-tbody');
83 this.copyRow = this.copyTbody.removeChild(dojo.byId('acq-lit-li-details-row'));
84 this.copyBatchRow = dojo.byId('acq-lit-li-details-batch-row');
85 this.copyBatchWidgets = {};
86 this.liNotesTbody = dojo.byId('acq-lit-notes-tbody');
87 this.liNotesRow = this.liNotesTbody.removeChild(dojo.byId('acq-lit-notes-row'));
88 this.realCopiesTbody = dojo.byId('acq-lit-real-copies-tbody');
89 this.realCopiesRow = this.realCopiesTbody.removeChild(dojo.byId('acq-lit-real-copies-row'));
90 this._copy_fields_for_acqdf = ['owning_lib', 'location', 'fund', 'circ_modifier', 'collection_code'];
91 this.skipInitialEligibilityCheck = false;
92 this.claimDialog = new ClaimDialogManager(
93 liClaimDialog, finalClaimDialog, this.claimEligibleLidByLi,
94 function(li) { /* callback that fires when claims are made */
95 self.fetchClaimInfo(li.id(), /* force update */ true);
98 this.vlAgent = new VLAgent();
99 this.batchProgress = {};
101 if (dojo.byId('acq-lit-apply-idents')) {
102 dojo.byId('acq-lit-apply-idents').onclick = function() {
103 self.applyOrderIdentValues();
107 this.focusLineitem = new openils.CGI().param('focus_li');
109 // capture the inline copy display wrapper and row template
110 this.inlineCopyContainer =
111 this.tbody.removeChild(dojo.byId('acq-inline-copies-row'));
113 '[name=acq-li-inline-copies-tbody]', this.inlineCopyContainer)[0];
114 this.inlineCopyTemplate = tb.removeChild(
115 dojo.query('[name=acq-li-inline-copies-template]', tb)[0]);
116 this.inlineNoCopies = tb.removeChild(
117 dojo.query('[name=acq-li-inline-copies-none]', tb)[0]);
119 // list of LI IDs that should be refreshed at next display time
120 this.inlineCopiesNeedingRefresh = [];
122 dojo.byId("acq-lit-li-actions-selector").onchange = function() {
123 self.applySelectedLiAction(this.options[this.selectedIndex].value);
124 this.selectedIndex = 0;
127 acqLitCreatePoCancel.onClick = function() {
128 acqLitPoCreateDialog.hide();
130 acqLitCreatePoSubmit.onClick = function() {
131 if (!self.createPoProviderSelector.attr("value") ||
132 !self.createPoAgencySelector.attr("value")) {
133 alert(localeStrings.CREATE_PO_INVALID);
135 } else if (self._confirmPoPrepaySituation()) {
136 acqLitPoCreateDialog.hide();
137 self._createPO(acqLitPoCreateDialog.getValues());
143 acqLitSavePlButton.onClick = function() {
144 acqLitSavePlDialog.hide();
145 self._savePl(acqLitSavePlDialog.getValues());
148 acqLitCancelLiStateButton.onClick = function() {
149 acqLitChangeLiStateDialog.hide();
151 acqLitSaveLiStateButton.onClick = function() {
152 acqLitChangeLiStateDialog.hide();
153 var state = acqLitChangeLiStateDialog.attr('state');
154 var state_filter = ['new'];
155 if (state == 'order-ready')
156 state_filter.push('selector-ready');
158 acqLitChangeLiStateDialog.getValues(), state, state_filter);
162 dojo.byId('acq-lit-select-toggle').onclick = function(){self.toggleSelect()};
163 dojo.byId('acq-inline-copies-toggle').onclick = function(){self.toggleInlineCopies()};
164 dojo.byId('acq-lit-info-back-button').onclick = function(){self.show('list')};
165 dojo.byId('acq-lit-copies-back-button').onclick = function(){self.show('list')};
166 dojo.byId('acq-lit-notes-back-button').onclick = function(){self.show('list')};
167 dojo.byId('acq-lit-real-copies-back-button').onclick = function(){self.show('list')};
169 this.setFundSearchFilter = function(callback) {
170 new openils.User().getPermOrgList(
171 ['CREATE_PURCHASE_ORDER', 'CREATE_PICKLIST', 'MANAGE_FUND'],
173 fundSearchFilter.org = orgs;
174 if (callback) callback();
176 true, true // descendants, id_list
180 this.afwCopyFieldArgs = function(field, perms) {
184 "labelFormat": (field == 'fund') ? fundLabelFormat : null,
185 "searchFormat": (field == 'fund') ? fundSearchFormat : null,
186 "searchFilter": (field == 'fund') ? fundSearchFilter : null,
187 "searchOptions": (field == 'fund') ? fundSort : null,
188 "orgLimitPerms": (field == 'location') ? ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'] : [perms],
191 "labelType": (field == "fund") ? "html" : null
193 "noCache": (field == "fund"),
198 /* This is the "new" batch updater that sits atop all lineitems. It does
199 * use this.afwCopyFieldArgs() to borrow a little common code from the
200 * "old" batch updater atop the copy details view.
201 * @param hidden allows the batch updater to be initialized, activating
202 * fund selectors, while stying invisible for UI's where the batch
203 * updater is not fully integrated.
205 this.initBatchUpdater = function(disabled_fields, hidden) {
206 if (!hidden) openils.Util.show("acq-batch-update", "table");
208 if (!dojo.isArray(disabled_fields)) disabled_fields = [];
210 /* Note that this will directly contain dijits, not the AutoWidget
212 if (!this.batchUpdateWidgets) {
213 this.batchUpdateWidgets = {};
216 if (this.batchUpdateWidgets.item_count) this.batchUpdateWidgets.item_count.destroy();
217 this.batchUpdateWidgets.item_count = new dijit.form.TextBox(
219 "style": {"width": "3em"},
221 dojo.indexOf(disabled_fields, "item_count") != -1
227 if (!this.batchUpdateWidgets.distribution_formula) {
228 (new openils.widget.AutoFieldWidget({
230 "selfReference": true,
231 "dijitArgs": { "required": false },
233 "parentNode": "acq-bu-distribution_formula"
236 dojo.style(w.domNode, {"width": "12em"});
237 self.batchUpdateWidgets.distribution_formula = w;
242 /* dijitArgs to AutoFieldWidget won't work for 'disabled' */
243 self.batchUpdateWidgets.distribution_formula.attr(
245 dojo.indexOf(disabled_fields, "distribution_formula") != -1
248 function buildOneBatchWidget(field, args) {
249 if (!self.batchUpdateWidgets[field]) {
250 (new openils.widget.AutoFieldWidget(args)).build(
252 if (field == "fund") {
254 w, "onChange", function(val) {
255 self._updateFundSelectorStyle(aw, val);
259 self._ensureCSSFundClasses(w.store);
262 dojo.style(w.domNode, {"width": "10em"});
263 self.batchUpdateWidgets[field] = w;
268 if (self.batchUpdateWidgets[field]) {
269 self.batchUpdateWidgets[field].attr(
271 dojo.indexOf(disabled_fields, field) != -1
277 ["owning_lib","location","collection_code","circ_modifier","fund"],
279 var args = self.afwCopyFieldArgs(field, "CREATE_PURCHASE_ORDER");
280 args.parentNode = dojo.byId("acq-bu-" + field);
282 if (field == 'fund') {
283 // The list of funds can be huge. Before fetching
284 // funds for PO or Selection LIst modification, see where the user has
285 // perms and limit the retreived funds accordingly.
286 // Note: This is the first instance of fund list
287 // retrieval. All future fund list retrievals will
288 // benefit directly from having applied the fund
289 // search filter org units here.
290 self.setFundSearchFilter(function() {
291 buildOneBatchWidget(field, args);
296 buildOneBatchWidget(field, args);
300 acqBatchUpdateApply.onClick = function() {
301 var li_id_list = self.getSelected(false, null, true /* id list */);
302 if (!li_id_list.length) {
303 alert(localeStrings.NO_LI_TO_UPDATE);
307 progressDialog.show(true);
308 progressDialog.attr("title", localeStrings.LI_BATCH_UPDATE);
309 progressDialog.update({"maximum": li_id_list.length,"progress": 0});
313 var params = [ self.authtoken, {"lineitems": li_id_list},
314 self.batchUpdateChanges(), self.batchUpdateFormula() ];
315 console.log("batch update params: " + dojo.toJson(params));
317 fieldmapper.standardRequest(
318 ["open-ils.acq", "open-ils.acq.lineitem.batch_update"], {
321 "onresponse": function(r) {
322 if ((r = openils.Util.readResponse(r))) { // assignment
323 progressDialog.update({"progress": ++count});
325 progressDialog.hide();
326 progressDialog.attr("title", "");
329 "oncomplete": function() {
330 /* XXX Is the last call to onresponse guaranteed to
331 * finish before oncomplete is fired? */
332 if (count != li_id_list.length) {
333 console.error("lineitem batch update operation failed");
334 progressDialog.hide();
335 progressDialog.attr("title", "");
337 location.href = location.href;
345 this.batchUpdateChanges = function() {
349 openils.Util.objectProperties(this.batchUpdateWidgets),
351 if (k == "distribution_formula") return; /* handled elsewhere */
352 if (self.batchUpdateWidgets[k].attr("disabled")) return;
354 /* It's important that a value of "" should mean that a field
355 * doesn't get used in the arguments to the batch updater API,
356 * but 0 should mean an actual 0. */
357 var value = self.batchUpdateWidgets[k].attr("value");
366 this.batchUpdateFormula = function() {
367 if (this.batchUpdateWidgets.distribution_formula.attr("disabled")) {
371 this.batchUpdateWidgets.distribution_formula.attr("value") ||
377 this.reset = function(keep_selectors) {
378 while(self.tbody.childNodes[0])
379 self.tbody.removeChild(self.tbody.childNodes[0]);
388 this.setNext = function(handler) {
389 var link = dojo.byId('acq-lit-next');
391 dojo.style(link, 'visibility', 'visible');
392 link.onclick = handler;
394 dojo.style(link, 'visibility', 'hidden');
398 this.setPrev = function(handler) {
399 var link = dojo.byId('acq-lit-prev');
401 dojo.style(link, 'visibility', 'visible');
402 link.onclick = handler;
404 dojo.style(link, 'visibility', 'hidden');
408 this.enableActionsDropdownOptions = function(mask) {
409 /* 'mask' is probably a misnomer the way I'm using it, but it needs to
410 * be one of pl,po,ao,gs,vp, or fs. */
411 dojo.query("option", "acq-lit-li-actions-selector").forEach(
413 var opt_mask = dojo.attr(option, "mask");
415 /* For each <option> element, an empty or non-existent mask
416 * attribute, a mask attribute of "*", or a mask attribute that
417 * matches this method's argument should result in that
418 * option's being enabled. */
420 option, "disabled", !(
423 opt_mask.search(mask) != -1
431 * Ensures this.focusLineitem is in view and causes a brief
432 * border around the lineitem to come to life then fade.
434 this.focusLi = function() {
435 if (!this.focusLineitem) return;
437 // set during addLineitem()
438 var node = dojo.byId('li-title-ref-' + this.focusLineitem);
440 // LI may not yet be rendered
443 // prevent numerous re-focuses
444 this.focusLineitem = null;
446 // causes the full row to be visible
447 dijit.scrollIntoView(node);
450 dojo.query('[attr=title]', node)[0].focus();
452 dojo.require('dojox.fx');
456 dojox.fx.highlight({color : '#BB4433', node : node, duration : 2000}).play();
461 this.show = function(div) {
462 openils.Util.hide('acq-lit-table-div');
463 openils.Util.hide('acq-lit-info-div');
464 openils.Util.hide('acq-lit-li-details');
465 openils.Util.hide('acq-lit-notes-div');
466 openils.Util.hide('acq-lit-real-copies-div');
467 openils.Util.hide('acq-lit-asset-creator');
470 openils.Util.show('acq-lit-table-div');
472 this.refreshInlineCopies();
475 openils.Util.show('acq-lit-info-div');
478 openils.Util.show('acq-lit-li-details');
481 openils.Util.show('acq-lit-real-copies-div');
484 openils.Util.show('acq-lit-notes-div');
486 case 'asset-creator':
487 openils.Util.show('acq-lit-asset-creator');
491 openils.Util.show(div);
495 this.hide = function() {
499 this.toggleSelect = function() {
501 dojo.forEach(self.selectors, function(i){i.checked = false});
503 dojo.forEach(self.selectors, function(i){i.checked = true});
504 self.toggleState = !self.toggleState;
508 this.getAll = function(callback, id_only, state) {
509 /* For some uses of the li table, we may not really know about "all"
510 * the lineitems that the user thinks we know about. If we're a paged
511 * picklist, for example, we only know about the lineitems we've
512 * displayed, but not necessarily all the lineitems on the picklist.
513 * So we reach out to pcrud to inform us.
514 * state: string/array. only lineitems in one of these states are
515 * included in the final result set. Not currently supported for
519 var oncomplete = function(r) {
520 var id_list = openils.Util.readResponse(r);
524 self.fetchLineitemsById(id_list, callback);
528 var search = {"picklist": this.isPL};
529 if (state) search.state = state;
532 "id_list": true, /* sic, even if id_only */
534 "oncomplete": oncomplete
538 } else if (this.isPO) {
539 var search = {"purchase_order": this.isPO};
540 if (state) search.state = state;
545 "oncomplete": oncomplete
549 } else if (this.isUni && this.pager) {
550 this.pager.getAllLineitemIDs(oncomplete);
554 /* If execution reaches this point, we don't need or can't perform
555 * any special tricks to find out the "real" list of "all" lineitems
556 * in this context, so we fall back to the old method.
558 callback(this.getSelected(true, null, id_only, state));
561 /** @param all If true, assume all are selected */
562 this.getSelected = function(
564 callback /* If you want a "good" idea of "all" lineitems, you must
565 provide a callback that accepts an array parameter, rather than
566 relying on the return value of this method itself. */,
570 console.log("getSelected states = " + state);
572 return this.getAll(callback, id_only, state);
574 var indices = {}; /* use to uniqify. needed in paging situations. */
575 dojo.forEach(this.selectors,
578 indices[i.parentNode.parentNode.getAttribute('li')] = true;
582 var result = openils.Util.objectProperties(indices);
584 // caller provided a lineitem state filter. remove IDs for lineitems
585 // not in the selected state.
588 if (!dojo.isArray(state)) state = [state];
589 dojo.forEach(result, function(liId) {
590 console.log('filter LI state ' + self.liCache[liId].state());
591 if (state.indexOf(self.liCache[liId].state()) >= 0)
598 result = result.map(function(liId) { return self.liCache[liId]; });
606 this.setRowAttr = function(td, liWrapper, field, type) {
607 var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
608 td.appendChild(document.createTextNode(val));
611 this.setClaimPolicyControl = function(li, row) {
612 if (!self._claimPolicyPickerLoading) {
613 self._claimPolicyPickerLoading = true;
615 new openils.widget.AutoFieldWidget({
616 "parentNode": "acq-lit-li-claim-policy",
618 "selfReference": true,
619 "dijitArgs": {"required": true}
621 function(w) { self.claimPolicyPicker = w; }
625 /* dojox.timing.doLater() is the best thing ever. Resource not yet
626 * ready? Just repeat my whole method when it is. */
627 if (dojox.timing.doLater(self.claimPolicyPicker)) {
631 row = self._findLiRow(li);
633 if (li.claim_policy()) {
634 /* This Dojo data dance is necessary to get a whole fieldmapper
635 * object based on a claim policy ID, since we alreay have the
636 * widget thing loaded with all that data, and can thereby
637 * avoid another request to the server. */
638 self.claimPolicyPicker.store.fetchItemByIdentity({
639 "identity": li.claim_policy(),
640 "onItem": function(a) {
641 var policy = (new acqclp()).fromStoreItem(a);
642 var span = nodeByName("claim_policy", row);
643 var inner = nodeByName("claim_policy_name", row);
645 openils.Util.show(span, "inline");
646 inner.innerHTML = policy.name();
648 "onError": function(e) {
653 openils.Util.hide(nodeByName("claim_policy", row));
654 nodeByName("claim_policy_name", row).innerHTML = "";
659 this.fetchClaimInfo = function(liId, force, callback, row) {
661 liId, function(full) {
662 self.liCache[full.id()] = full;
663 self.checkClaimEligibility(full, callback, row);
668 // fetch an updated copy of the lineitem
669 // and add it back to the lineitem table
670 this.refreshLineitem = function(li, focus) {
672 this._fetchLineitem(li.id(),
675 self.focusLineitem = li.id();
677 self.focusLineitem = null;
679 var row = dojo.query('[li='+li.id()+']', self.tbody)[0];
680 var nextSibling = row.nextSibling;
681 self.tbody.removeChild(row);
682 self.addLineitem(newLi, false, nextSibling);
688 * Inserts a single lineitem into the growing table of lineitems
689 * @param {Object} li The lineitem object to insert
691 this.addLineitem = function(li, skip_final_placement, nextSibling) {
692 this.liCache[li.id()] = li;
694 // insert the row right away so that final order isn't
695 // dependent on how long subsequent async request take
696 // for a given line item
697 var row = self.rowTemplate.cloneNode(true);
698 if (!skip_final_placement) {
700 // either no nextSibling was provided or it was null
701 // meaning the row was already at the end of the table
702 self.tbody.appendChild(row);
704 self.tbody.insertBefore(row, nextSibling);
708 self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
710 // sort the lineitem notes on edit_time
711 if(!li.lineitem_notes()) li.lineitem_notes([]);
713 var liWrapper = new openils.acq.Lineitem({lineitem:li});
714 row.setAttribute('li', li.id());
715 var tds = dojo.query('[attr]', row);
716 dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
717 if (li.source_label() !== null)
718 dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
720 // so we can scroll to it later
721 dojo.query('[name=bib-info-cell]', row)[0].id = 'li-title-ref-' + li.id();
724 liWrapper.findAttr("isbn", "lineitem_marc_attr_definition") ||
725 liWrapper.findAttr("upc", "lineitem_marc_attr_definition");
727 // XXX media prefix for added content
729 nodeByName("jacket", row).setAttribute(
730 "src", "/opac/extras/ac/jacket/small/" + identifier
734 nodeByName("liid", row).innerHTML += li.id();
736 var exist = nodeByName('li_existing_count', row);
737 fieldmapper.standardRequest(
738 ['open-ils.acq', 'open-ils.acq.lineitem.existing_copies.count'],
740 params: [this.authtoken, li.id()],
741 oncomplete : function(r) {
742 var count = openils.Util.readResponse(r);
743 exist.innerHTML = count;
744 if (Number(count) > 0) {
745 openils.Util.addCSSClass(
746 exist, 'acq-existing-count-warn');
750 label : dojo.string.substitute(
751 localeStrings.LI_EXISTING_COPIES, [count])
758 openils.Util.show(nodeByName('catalog', row), 'inline');
759 nodeByName("catalog_link", row).onclick = this.generateMakeRecTab(li.eg_bib_id());
761 openils.Util.show(nodeByName('link_to_catalog', row), 'inline');
762 nodeByName("link_to_catalog_link", row).onclick = function() { self.drawBibFinder(li) };
765 if (li.queued_record()) {
766 this.pcrud.retrieve('vqbr', li.queued_record(),
768 oncomplete : function(r) {
769 var qrec = openils.Util.readResponse(r);
770 openils.Util.show(nodeByName('queue', row), 'inline');
771 var link = nodeByName("queue_link", row);
772 link.onclick = function() {
773 var url = oilsBasePath + '/vandelay/vandelay?qtype=bib&qid=' + qrec.queue()
774 // open a new tab to the vandelay queue for this record
775 if (window.IAMBROWSER) {
778 openils.XUL.newTabEasy(url);
786 nodeByName("worksheet_link", row).href =
787 oilsBasePath + "/acq/lineitem/worksheet/" + li.id() +
788 '?source=' + encodeURIComponent(location.pathname + location.search)
790 nodeByName("show_requests_link", row).href =
791 oilsBasePath + "/acq/picklist/user_request?lineitem=" + li.id() +
792 '?source=' + encodeURIComponent(location.pathname + location.search)
794 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
795 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
796 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
797 dojo.query('[name=expand_inline_copies]', row)[0].onclick =
798 function() {self.drawInlineCopies(li.id())};
801 if (sum = li.order_summary()) { // assignment
802 // Only show the paid label if at least one copy is invoiced.
803 // In other words, a lineitem whose every copy is canceled
805 if (sum.invoice_count() > 0) {
806 if (sum.item_count() == (
807 sum.invoice_count() + sum.cancel_count())) {
808 // Lineitem is fully paid. Display the paid-off label
809 openils.Util.show(nodeByName('paid', row), 'inline');
814 this.drawOrderIdentSelector(li, row);
816 if (!this.skipInitialEligibilityCheck)
820 function(full) { self.setClaimPolicyControl(full, row) },
824 this.updateLiNotesCount(li, row);
826 // show which PO this lineitem is a member of
827 if(li.purchase_order() && !this.isPO) {
829 this.poCache[li.purchase_order()] =
830 this.poCache[li.purchase_order()] ||
831 fieldmapper.standardRequest(
832 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
834 this.authtoken, li.purchase_order(), {
835 "flesh_price_summary": true,
836 "flesh_provider" : true,
837 "flesh_lineitem_count": true
840 if(po && !this.isMeta) {
841 openils.Util.show(nodeByName('po', row), 'inline');
842 var link = nodeByName('po_link', row);
843 link.setAttribute('href', oilsBasePath +
844 '/acq/po/view/' + li.purchase_order() +
845 '?focus_li=' + li.id() +
846 '&source=' + encodeURIComponent(location.pathname + location.search)
848 link.innerHTML += po.name();
850 openils.Util.show(nodeByName('pro', row), 'inline');
851 link = nodeByName('pro_link', row);
852 link.setAttribute('href', oilsBasePath + '/conify/global/acq/provider/' + po.provider().id())
853 link.innerHTML += po.provider().code();
857 // show which picklist this lineitem is a member of
858 if(li.picklist() && (this.isPO || this.isMeta || this.isUni)) {
860 this.plCache[li.picklist()] =
861 this.plCache[li.picklist()] ||
862 fieldmapper.standardRequest(
863 ['open-ils.acq', 'open-ils.acq.picklist.retrieve.authoritative'],
864 {params: [this.authtoken, li.picklist()]});
866 if (pl.name() == "") {
867 openils.Util.show(nodeByName("bib_origin", row), "inline");
871 openils.Util.show(nodeByName('pl', row), 'inline');
872 var link = nodeByName('pl_link', row);
873 link.setAttribute('href', oilsBasePath +
874 '/acq/picklist/view/' + li.picklist() +
875 '?focus_li=' + li.id() +
876 '&source=' + encodeURIComponent(location.pathname + location.search)
878 link.innerHTML += pl.name();
883 var countNode = nodeByName('count', row);
884 var count = li.item_count() || 0;
885 if (typeof(this._copy_count_cb) == "function") {
886 this._copy_count_cb(li.id(), count);
888 countNode.innerHTML = count;
889 countNode.id = 'acq-lit-copy-count-label-' + li.id();
892 var priceInput = dojo.query('[name=price]', row)[0];
893 priceInput.value = li.estimated_unit_price() || '';
894 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
896 // show either "mark received" or "unreceive" as appropriate
897 this.updateLiState(li, row);
899 if (skip_final_placement) {
903 // the last LI may be rendered after the call to show('list'),
904 // so make sure it's focused if necessary.
905 if (this.focusLineitem == li.id())
909 this._liCountClaims = function(li) {
911 for (var i = 0; i < li.lineitem_details().length; i++)
912 total += li.lineitem_details()[i].claims().length;
916 this._findLiRow = function(li) {
917 return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
920 this.reconsiderClaimControl = function(li, row) {
921 if (!row) row = this._findLiRow(li);
922 var option = nodeByName("action_manage_claims", row);
923 var eligible = this.claimEligibleLidByLi[li.id()].length;
924 var count = this._liCountClaims(li);
926 option.disabled = !(count || eligible);
928 dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
931 this.clearEligibility = function(li) {
932 this.claimEligibleLidByLi[li.id()] = [];
934 if (li.lineitem_details()) {
935 li.lineitem_details().forEach(
936 function(lid) { delete self.claimEligibleLid[lid.id()]; }
940 if (this.copyCache) {
942 for (var k in this.copyCache) {
943 if (this.copyCache[k].lineitem() == li.id())
947 function(k) { delete self.claimEligibleLid[k]; }
952 this.applyOrderIdentValues = function() {
953 this._identValuesInFlight =
954 openils.Util.objectProperties(this.liCache).length;
955 for (var liId in this.liCache) {
956 this._applyOrderIdentValue(this.liCache[liId]);
960 // returns true if request was sent
961 this._applyOrderIdentValue = function(li, oncomplete) {
964 console.log('applying ident value for lineitem ' + li.id());
967 var row = dojo.query('[li=' + li.id() + ']')[0];
969 // find the selected ident value
970 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
971 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
972 var name = typeSel.options[typeSel.selectedIndex].value;
973 var val = typeSel._cbox.attr('value');
975 console.log("selected ident is " + val);
977 // it differs from the existing ident value, update it
978 var oldIdent = self.getLiOrderIdent(li);
980 oldIdent.attr_name() == name &&
981 oldIdent.attr_value() == val) {
982 console.log('selected ident attr matches existing attr');
983 if (--this._identValuesInFlight == 0) {
984 if (oncomplete) oncomplete(li);
985 else location.href = location.href;
990 // see if the selected ident value is represented
991 // by an existing lineitem attr
994 typeSel._cbox.store.fetch({
995 query : {attr_value : val},
996 onItem : function(item) {
997 console.log('found existing attr for ident value');
998 args.source_attr_id = li.attributes().filter(
999 function(attr) { return attr.id() == item.id[0] }
1005 if (!args.source_attr_id) {
1006 // user entered new text in the combobox
1007 // so we need to create a new attr
1008 console.log('creating new ident attr');
1009 args.lineitem_id = li.id();
1010 args.attr_name = name;
1011 args.attr_value = val;
1014 fieldmapper.standardRequest(
1015 ['open-ils.acq', 'open-ils.acq.lineitem.order_identifier.set'],
1017 params : [openils.User.authtoken, args],
1018 oncomplete : function() {
1019 console.log('order_ident oncomplete');
1020 if (--self._identValuesInFlight == 0) {
1021 if (oncomplete) oncomplete(li);
1022 else location.href = location.href;
1024 console.log(self._identValuesInFlight + ' still in flight');
1032 this.getLiOrderIdent = function(li) {
1033 var attrs = li.attributes();
1034 if (!attrs) return null;
1035 return attrs.filter(
1038 attr.attr_type() == 'lineitem_local_attr_definition' &&
1039 openils.Util.isTrue(attr.order_ident())
1045 this.drawOrderIdentSelector = function(li, row) {
1047 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
1048 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
1050 var attrs = li.attributes();
1052 // limit to MARC attr defs
1053 attrs = attrs.filter(
1055 return (attr.attr_type() == 'lineitem_marc_attr_definition');
1059 var identAttr = this.getLiOrderIdent(li);
1062 // collect the values for each type of identifier
1063 // find a reasonable default identifier type to render
1067 dojo.forEach(['isbn', 'upc', 'issn'],
1070 // collect the values for this attr name
1071 values[name] = attrs.filter(
1073 return (attr.attr_name() == name)
1077 // select a reasonable default name in the type-selector
1081 if (identAttr.attr_name() == name)
1083 } else if (values[name].length) {
1088 dojo.forEach(typeSel.options, function(opt) {
1089 if (opt.value == name) {
1090 opt.selected = true;
1099 function updateOrderIdent(val) {
1100 self._identValuesInFlight = 1;
1101 self._applyOrderIdentValue(
1104 self.refreshLineitem(li);
1109 // replace the ident combobox with a new
1110 // one for the selected ident type
1111 function changeComboBox(sel) {
1112 var name = sel.options[sel.selectedIndex].value;
1114 var td = dojo.query('[name=order_ident_value]', row)[0];
1115 if (td.childNodes[0])
1116 dojo.destroy(td.childNodes[0]);
1118 var store = new dojo.data.ItemFileWriteStore({
1119 data : acqlia.toStoreData(values[name])
1122 var cbox = new dijit.form.ComboBox(
1124 labelAttr : 'attr_value',
1125 searchAttr : 'attr_value'
1127 dojo.create('div', {}, td)
1132 // set the value for the cbox
1133 if (values[name].length) {
1134 var orderIdent = self.getLiOrderIdent(li);
1136 if (orderIdent && orderIdent.attr_name() == name) {
1137 cbox.attr('value', orderIdent.attr_value());
1139 cbox.attr('value', values[name][0].attr_value());
1143 if (!self.orderIdentAllowed)
1144 cbox.attr('disabled', true);
1147 cbox._lineitem = li;
1148 dojo.connect(cbox, 'onChange', updateOrderIdent);
1151 changeComboBox(typeSel); // force the initial draw
1152 typeSel.onchange = function() {changeComboBox(typeSel)};
1155 this.testOrderIdentPerms = function(org, callback) {
1157 new openils.User().getPermOrgList(
1158 'ACQ_SET_LINEITEM_IDENTIFIER',
1160 console.log('found orgs = ' + orgs);
1161 for (var i = 0; i < orgs.length; i++) {
1162 if (Number(orgs[i]) == Number(org)) {
1163 self.orderIdentAllowed = true;
1164 if (callback) callback();
1168 if (callback) callback();
1174 this.checkClaimEligibility = function(li, callback, row) {
1175 /* Assume always eligible, i.e. from this interface we don't care about
1176 * claim eligibility any more. this is where the user would force a
1178 this.clearEligibility(li);
1179 this.claimEligibleLidByLi[li.id()] = li.lineitem_details().map(
1180 function(lid) { return lid.id(); }
1182 li.lineitem_details().forEach(
1183 function(lid) { self.claimEligibleLid[lid.id()] = true; }
1185 this.reconsiderClaimControl(li, row);
1186 if (callback) callback(li);
1188 this.clearEligibility(li);
1189 fieldmapper.standardRequest(
1190 ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
1191 "params": [openils.User.authtoken, {"lineitem": li.id()}],
1193 "onresponse": function(r) {
1194 if (r = openils.Util.readResponse(r)) {
1195 self.claimEligibleLidByLi[li.id()].push(
1198 self.claimEligibleLid[r.lineitem_detail()] = true;
1201 "oncomplete": function() {
1202 self.reconsiderClaimControl(li, row);
1203 if (typeof(callback) == "function")
1211 this.updateLiNotesCount = function(li, row) {
1212 if (!row) row = this._findLiRow(li);
1214 var has_notes = (li.lineitem_notes().filter(
1215 function(o) { return Boolean (o.alert_text()); }
1218 /* U+2691 is the code point for a filled-in flag character */
1219 nodeByName("notes_alert_flag", row).innerHTML =
1220 has_notes ? "⚑" : "";
1221 nodeByName("noteslink", row).style.fontStyle =
1222 has_notes ? "italic" : "normal";
1223 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
1226 /* XXX NOT related to _updateLiState(). rethink */
1227 this.updateLiState = function(li, row) {
1228 if (!row) row = this._findLiRow(li);
1230 nodeByName("actions", row).onchange = function() {
1231 switch(this.options[this.selectedIndex].value) {
1232 case 'action_update_barcodes':
1233 self.showRealCopyEditUI(li);
1234 nodeByName("action_none", row).selected = true;
1236 case 'action_holdings_maint':
1237 (self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row ))();
1239 case 'action_manage_claims':
1240 self.fetchClaimInfo(li.id(), true, function(full) { self.claimDialog.show(full) }, row);
1242 case 'action_view_history':
1243 location.href = oilsBasePath + '/acq/lineitem/history/' + li.id();
1247 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
1248 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
1250 /* handle row coloring for based on LI state */
1251 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1252 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
1254 // Expose invoice actions for any lineitem that is linked to a PO
1255 if (li.purchase_order()) {
1256 openils.Util.show(nodeByName("invoices_span", row), "inline");
1257 var link = nodeByName("invoices_link", row);
1258 link.onclick = function() {
1259 var url = oilsBasePath + "/acq/search/unified?so=" +
1260 base64Encode({"jub":[{"id": li.id()}]}) + "&rt=invoice"
1261 if (window.IAMBROWSER) {
1262 xulG.relay_url(url);
1264 openils.XUL.newTabEasy(url);
1272 * If we haven't fleshed the lineitem_details, default to allowing access to the
1273 * holdings maintenence actions. The alternative is to flesh LIDs on every lineitem,
1274 * but that will add to page render time. Let's see if this will suffice...
1276 var lids = li.lineitem_details();
1278 (lids && !lids.filter(function(lid) { return lid.eg_copy_id() })[0] )) {
1280 actUpdateBarcodes.disabled = false;
1281 actHoldingsMaint.disabled = false;
1284 var state_cell = nodeByName("li_state_" + li.state(), row);
1286 // re-hide any state label nodes which may have been un-hidden
1287 // through previous actions.
1288 dojo.query('[state-label]', row).forEach(function(node) {
1289 openils.Util.hide(node)
1292 if (li.state() == 'cancelled') {
1293 if(typeof li.cancel_reason() == "object") {
1295 // clear the stock "Canceled" label, since we have more
1296 // information to replace it with.
1297 state_cell.innerHTML = '';
1299 var holds_state = dojo.create(
1301 "style": "border-bottom: 1px dashed #000;",
1302 "innerHTML": li.cancel_reason().label()
1303 }, state_cell, "only"
1307 "label": "<em>" + li.cancel_reason().label() +
1308 "</em><br />" + li.cancel_reason().description(),
1309 "connectId": [holds_state]
1310 }, dojo.create("span", null, state_cell, "last")
1313 if (li.cancel_reason().keep_debits() == 't') {
1314 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1315 openils.Util.addCSSClass(row, "oils-acq-li-state-delayed");
1318 console.log('li cancel_reason is un-fleshed. Please fix');
1322 openils.Util.show(state_cell);
1326 this._setAlertStore = function() {
1327 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
1329 "data": acqliat.toStoreData(
1332 "owning_lib": aou.orgNodeTrail(
1333 aou.findOrgUnit(openils.User.user.ws_ou())
1334 ).map(function(o) { return o.id(); })
1340 acqLitAlertAlertText.setValue(); /* make the store "live" */
1341 acqLitAlertAlertText._store_ready = true;
1345 * Draws and shows the lineitem notes pane
1347 this.drawLiNotes = function(li) {
1349 this.focusLineitem = li.id();
1351 if (!acqLitAlertAlertText._store_ready)
1352 this._setAlertStore();
1355 li.lineitem_notes().sort(
1357 if(a.edit_time() < b.edit_time()) return 1;
1363 while(this.liNotesTbody.childNodes[0])
1364 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
1367 acqLitCreateNoteSubmit.onClick = function() {
1368 var value = acqLitCreateNoteText.attr('value');
1370 var note = new fieldmapper.acqlin();
1373 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
1376 note.lineitem(li.id());
1378 self.updateLiNotes(li, note);
1379 acqLitCreateNoteVendorPublic.attr("checked", false);
1380 acqLitCreateNoteText.attr("value", "");
1383 acqLitCreateAlertSubmit.onClick = function() {
1384 if (!acqLitAlertAlertText.item) {
1385 alert(localeStrings.ALERT_UNSELECTED);
1389 var alert_text = new fieldmapper.acqliat().fromStoreItem(
1390 acqLitAlertAlertText.item
1392 var value = acqLitAlertNoteValue.attr("value") || "";
1394 var note = new fieldmapper.acqlin();
1396 note.lineitem(li.id());
1398 note.alert_text(alert_text);
1400 self.updateLiNotes(li, note);
1403 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
1407 * Draws a single lineitem note in the notes pane
1409 this.addLiNote = function(li, note) {
1410 if(note.isdeleted()) return;
1412 var row = self.liNotesRow.cloneNode(true);
1413 nodeByName("value", row).innerHTML = note.value();
1414 var alert_node = nodeByName("alert_code", row);
1415 if (note.alert_text()) {
1416 alert_node.innerHTML = dojo.string.substitute(
1418 aou.findOrgUnit(note.alert_text().owning_lib()).shortname(),
1419 note.alert_text().code()
1422 if (note.alert_text().description()) {
1425 "connectId": [alert_node],
1426 "label": note.alert_text().description()
1427 }, dojo.create("span", null, alert_node, "after")
1432 if (openils.Util.isTrue(note.vendor_public()))
1433 nodeByName("vendor_public", row).innerHTML =
1434 localeStrings.VENDOR_PUBLIC;
1436 nodeByName("delete", row).onclick = function() {
1437 note.isdeleted(true);
1438 self.liNotesTbody.removeChild(row);
1439 self.updateLiNotes(li);
1442 if(note.edit_time()) {
1443 nodeByName("edit_time", row).innerHTML =
1444 dojo.date.locale.format(
1445 dojo.date.stamp.fromISOString(note.edit_time()),
1446 {formatLength:'short'});
1449 self.liNotesTbody.appendChild(row);
1453 * Updates any new/changed/deleted notes on the server
1455 this.updateLiNotes = function(li, newNote) {
1461 notes = li.lineitem_notes().filter(
1463 if(note.ischanged() || note.isnew() || note.isdeleted())
1469 if(notes.length == 0) return;
1470 progressDialog.show();
1472 fieldmapper.standardRequest(
1473 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
1475 params : [this.authtoken, notes],
1476 onresponse : function(r) {
1477 var resp = openils.Util.readResponse(r);
1482 // remove the old changed notes
1484 dojo.forEach(li.lineitem_notes(),
1486 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
1490 li.lineitem_notes(list);
1493 progressDialog.hide();
1494 self.updateLiNotesCount(li);
1495 self.drawLiNotes(li);
1499 progressDialog.update(resp);
1500 var newnote = resp.note;
1502 if(!newnote.isdeleted()) {
1503 newnote.isnew(false);
1504 newnote.ischanged(false);
1505 li.lineitem_notes().push(newnote);
1512 this.updateLiPrice = function(input, li) {
1514 var price = input.value;
1515 if(Number(price) == Number(li.estimated_unit_price())) return;
1517 fieldmapper.standardRequest(
1518 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
1519 { async : false, // redundant w/ timeout
1521 params : [this.authtoken, li.id(), price],
1522 oncomplete : function(r) {
1523 openils.Util.readResponse(r);
1524 li.estimated_unit_price(price); // update local copy
1527 * If this is a PO and every visible lineitem has a price,
1528 * check again to see if this PO can be activated. Note that
1529 * every visible lineitem having a price does not guarantee it can
1530 * be activated, which is why we still make the call. Having a price
1531 * set for every visiable lineitem is just the lowest barrier to entry.
1534 var priceNodes = dojo.query('[name=price]', dojo.byId('acq-lit-tbody'));
1536 dojo.forEach(priceNodes, function(node) { if (node.value == '') allSet = false});
1537 if (allSet) checkCouldActivatePo();
1538 refreshPOSummaryAmounts();
1545 this.removeLineitem = function(liId) {
1546 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
1547 delete this.liCache[liId];
1548 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
1551 this.drawInfo = function(liId) {
1552 this.focusLineitem = liId;
1553 if (!this._isRelatedViewer) {
1554 var d = dojo.byId("acq-lit-info-related");
1555 if (!this.relCache[liId]) {
1556 fieldmapper.standardRequest(
1559 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
1562 "params": [openils.User.authtoken, liId],
1563 "onresponse": function(r) {
1564 self.relCache[liId] = openils.Util.readResponse(r);
1565 nodeByName("related_number", d).innerHTML =
1566 self.relCache[liId];
1568 self.relCache[liId] >1 ? "show" : "hide"
1574 nodeByName("related_number", d).innerHTML = this.relCache[liId];
1575 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
1580 openils.acq.Lineitem.fetchAttrDefs(
1582 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
1587 this.toggleInlineCopies = function() {
1588 // if any inline copies are not displayed,
1589 // display them all otherwise, hide them all.
1591 var displayAll = false;
1593 for (var liId in this.liCache) {
1594 if (!this.inlineCopiesVisible(liId)) {
1600 for (var liId in this.liCache) {
1601 var row = dojo.byId('acq-inline-copies-row-' + liId);
1603 if (!row || row._hidden) {
1604 this.drawInlineCopies(liId);
1606 } else { // hide all
1608 // drawInlineCopies() on a visible row will hide it.
1609 this.drawInlineCopies(liId);
1616 this.inlineCopiesVisible = function(liId) {
1617 var row = dojo.byId('acq-inline-copies-row-' + liId);
1618 return (row && !row._hidden);
1621 this.refreshInlineCopies = function(all, reFetch) {
1623 var liIds = this.inlineCopiesNeedingRefresh;
1624 if (all) liIds = openils.Util.objectProperties(liCache);
1625 liIds.forEach(function(liId) {
1626 if (self.inlineCopiesVisible(liId)) {
1627 self.drawInlineCopies(liId, reFetch); // hide
1628 self.drawInlineCopies(liId, reFetch); // re-draw
1633 // draw inline copy table. if the table is
1634 // already visible, hide the table as-is
1635 // reFetch forces a retrieval of the lineitem and
1636 // copies from the server. otherwise the locally
1637 // cached version of each is used.
1638 this.drawInlineCopies = function(liId, reFetch) {
1641 // find or create the row where the inline copies table will live
1642 var containerRow = dojo.byId('acq-inline-copies-row-' + liId);
1643 var liRow = dojo.query('[li=' + liId + ']')[0];
1645 if (!containerRow) {
1647 // build the inline copies container row and add it to
1648 // the DOM directly after the primary lineitem row
1650 containerRow = self.inlineCopyContainer.cloneNode(true);
1651 containerRow.id = 'acq-inline-copies-row-' + liId;
1653 if (liRow.nextSibling) {
1654 self.tbody.insertBefore(containerRow, liRow.nextSibling);
1656 self.tbody.appendChild(containerRow);
1661 // toggle the visible state
1662 containerRow._hidden = !containerRow._hidden;
1663 openils.Util.toggle(containerRow, 'table-row');
1665 if (containerRow._hidden) return; // hide only
1668 var handler = function(li) {
1670 var tbody = dojo.query(
1671 '[name=acq-li-inline-copies-tbody]',
1674 // reset the table before adding copy rows
1675 while (tbody.childNodes[0])
1676 tbody.removeChild(tbody.childNodes[0]);
1678 if(li.lineitem_details().length == 0) {
1680 self.inlineNoCopies.cloneNode(true));
1681 return; // no copies to show
1684 // add a row to the inline copy table for each copy
1685 dojo.forEach(li.lineitem_details(),
1687 var row = self.inlineCopyTemplate.cloneNode(true);
1688 tbody.appendChild(row);
1689 self.addInlineCopy(li, copy, row);
1694 this._fetchLineitem(liId, handler, reFetch);
1697 /** Draw read-only copy widgets for inline copies */
1698 this.addInlineCopy = function(li, copy, row) {
1701 dojo.forEach(liDetailFields,
1704 var widget = new openils.widget.AutoFieldWidget({
1707 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1708 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1709 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1711 parentNode : dojo.query('[name=' + field + ']', row)[0],
1720 /* For a given list of lineitem ids, build a list of full lineitems
1721 * re-using the fetching logic that is otherwise typical to use in this
1724 * If we've already got a lineitem in the cache, just use that.
1726 * Once we've built a list of lineitems, call callback(thatlist).
1728 this.fetchLineitemsById = function(id_list, callback) {
1729 var total = id_list.length;
1730 var result_list = [];
1732 var inner = function(li) {
1733 result_list.push(li)
1735 callback(result_list);
1738 id_list.forEach(function(id) { self._fetchLineitem(id, inner); });
1741 this._fetchLineitem = function(liId, handler, force) {
1743 var li = this.liCache[liId];
1744 if(li && li.marc() && li.lineitem_details() && !force)
1747 fieldmapper.standardRequest(
1748 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
1751 params: [self.authtoken, liId, {
1753 flesh_cancel_reason: true,
1754 flesh_li_details: true,
1756 flesh_fund_debit: true }],
1758 oncomplete: function(r) {
1759 var li = openils.Util.readResponse(r);
1760 self.liCache[liId] = li;
1767 this._drawInfo = function(li) {
1769 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
1771 if(li.eg_bib_id()) {
1772 openils.Util.hide('acq-lit-marc-order-record-label');
1773 openils.Util.hide(acqLitEditOrderMarc.domNode);
1774 openils.Util.show('acq-lit-marc-real-record-label');
1776 openils.Util.show('acq-lit-marc-order-record-label');
1777 openils.Util.show(acqLitEditOrderMarc.domNode);
1778 openils.Util.hide('acq-lit-marc-real-record-label');
1781 this.drawMarcHTML(li);
1782 this.infoTbody = dojo.byId('acq-lit-info-tbody');
1785 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
1786 while(this.infoTbody.childNodes[0])
1787 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
1789 for(var i = 0; i < li.attributes().length; i++) {
1790 var attr = li.attributes()[i];
1791 var row = this.infoRow.cloneNode(true);
1793 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
1794 var name = openils.acq.Lineitem.attrDefs[type].filter(
1796 return (a.code() == attr.attr_name());
1798 ).pop().description();
1800 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
1801 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
1802 this.infoTbody.appendChild(row);
1805 if (!this._isRelatedViewer) {
1806 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
1807 oilsBasePath + "/acq/lineitem/related/" + li.id();
1810 // if a top scroll point is defined, jump up to it here
1811 var node = dojo.byId('oils-scroll-to-top');
1812 if (node) dijit.scrollIntoView(node);
1815 this.generateMakeRecTab = function(bib_id,default_view, row) {
1817 if(openils.XUL.isXUL() && !window.IAMBROWSER) {
1820 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
1823 show_nav_buttons : true,
1824 show_print_button : true,
1825 opac_url : xulG.url_prefix('opac_rdetail|' + bib_id),
1826 default_view : default_view
1830 var url = '/eg/staff/cat/catalog/record/' + bib_id;
1831 if (default_view == 'copy_browser') {
1837 if(row) nodeByName("action_none", row).selected = true;
1841 this.drawMarcHTML = function(li) {
1842 var params = [null, true, li.marc()];
1844 params = [li.eg_bib_id(), true];
1846 fieldmapper.standardRequest(
1847 ['open-ils.search', 'open-ils.search.biblio.record.html'],
1850 oncomplete: function(r) {
1851 dojo.byId('acq-lit-marc-div').innerHTML =
1852 openils.Util.readResponse(r);
1858 this.drawCopies = function(liId, force_fetch) {
1859 this.focusLineitem = liId;
1860 if (typeof force_fetch == "undefined")
1861 force_fetch = false;
1863 var cgi = new openils.CGI();
1864 var source = cgi.param('source');
1865 if (source && source.match(/invoice/)) {
1866 // got here from the invoice page, show the 'return-to-invoice' button
1867 var cgi = new openils.CGI({url : source});
1868 cgi.param('focus_li', liId);
1869 openils.Util.show(dojo.byId('acq-lit-copies-back-to-invoice-button-wrapper'), 'inline');
1870 var button = dojo.byId('acq-lit-copies-back-to-invoice-button');
1871 button.onclick = function() { location.href = cgi.url() };
1874 openils.acq.Lineitem.fetchAndRender(liId, {},
1875 function(li, html) {
1876 dojo.byId('acq-lit-copies-li-summary').innerHTML = html;
1880 this.show('copies');
1882 this.copyCache = {};
1883 this.copyWidgetCache = {};
1884 this.oldCopyWidgetCache = {};
1885 this.virtDfaCounts = {};
1886 this.realDfaCache = {};
1889 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
1890 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
1891 acqLitCopyCountInput.attr('value', '0');
1893 if (this.isPO && PO && PO.order_date()) {
1894 // prevent adding copies to activated POs
1895 acqLitCopyCountInput.attr('disabled', true);
1896 acqLitAddCopyCount.attr('disabled', true);
1899 while(this.copyTbody.childNodes[0])
1900 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
1902 this._drawBatchCopyWidgets();
1904 this._drawDistribApplied(liId);
1906 this._fetchDistribFormulas(
1908 openils.acq.Lineitem.fetchAttrDefs(
1910 self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch);
1917 this._saveDistribAppliedTemplates = function() {
1918 if (!this._appliedDistribTemplate) {
1919 this._appliedDistribTemplate =
1920 dojo.byId("acq-lit-distrib-applied-tbody").
1921 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
1922 dojo.attr(this._appliedDistribTemplate, "id");
1926 this._drawDistribApplied = function(liId) {
1927 /* Build this table while hidden to prevent rendering artifacts */
1928 openils.Util.hide("acq-lit-distrib-applied-tbody");
1930 this._saveDistribAppliedTemplates();
1932 /* Remove any rows in the table from previous populations */
1933 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
1934 forEach(dojo.destroy);
1936 /* Unregister all dijits previously created (for some reason this isn't
1937 * covered by the above destroy calls). */
1938 dijit.registry.forEach(
1939 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
1942 /* Populate the table with our liId */
1944 fieldmapper.standardRequest(
1946 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
1949 "params": [self.authtoken, liId],
1950 "onresponse": function(r) {
1951 var dfa = openils.Util.readResponse(r);
1954 self.realDfaCache[dfa.id()] = dfa;
1955 self._drawDistribAppliedUnit(dfa);
1958 "oncomplete": function() {
1959 /* Reveal built table */
1962 "acq-lit-distrib-applied-tbody", "table-row-group"
1970 this._drawDistribAppliedUnit = function(dfa) {
1971 var new_row = false;
1972 var row = dojo.query(
1973 'tr[formula="' + dfa.formula().id() + '"]',
1974 "acq-lit-distrib-applied-tbody"
1979 row = dojo.clone(this._appliedDistribTemplate);
1980 dojo.attr(row, "formula", dfa.formula().id());
1981 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
1984 var td = dojo.query("td", row)[0];
1986 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1987 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1990 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1992 new dijit.form.Button(
1994 "onClick": function() {
1995 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1996 self.deleteDfa(dfa);
1999 /* XXX I /cannot/ make the following work in as a CSS class
2000 * for some reason. So frustrating... */
2001 "style": function(id) {
2003 "font-weight: bold; color: #c00;" :
2005 }(dfa.id()) + "margin: 0 6px;display: inline;"
2006 }, "dfa-button-" + dfa.id()
2010 "connectId": ["dfa-button-" + dfa.id()],
2011 "label": dojo.string.substitute(
2012 localeStrings.DFA_TIP, dfa.id() > 0 ? [
2013 openils.User.formalName(dfa.creator()),
2014 dojo.date.locale.format(
2015 dojo.date.stamp.fromISOString(dfa.create_time()),
2016 {"formatLength":"short"}
2018 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
2020 }, "dfa-tip-" + dfa.id()
2024 this.deleteDfa = function(dfa) {
2025 if (dfa.id() > 0) { /* real */
2026 this.pcrud.eliminate(
2029 "oncomplete": function() {
2030 self._removeDistribApplied(dfa.id());
2031 delete self.realDfaCache[dfa.id()];
2035 } else { /* virtual */
2036 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
2037 this.virtDfaCounts[dfa.formula().id()] = 0;
2038 /* hasn't been saved yet, so no need to do anything server side */
2039 this._removeDistribApplied(dfa.id());
2044 this._removeDistribApplied = function(dfaId) {
2045 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
2046 dijit.registry.forEach(
2047 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
2049 this._removeDistribAppliedEmptyRows();
2052 this._removeAllDistribAppliedVirtual = function() {
2053 /* Unregister dijits */
2054 dijit.registry.forEach(
2055 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
2057 this._removeDistribAppliedEmptyRows();
2060 this._removeDistribAppliedEmptyRows = function() {
2061 /* Remove any rows with no DFA at all */
2062 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
2064 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
2070 * Insert a new row into the distribution formula selection form
2072 this._addDistribFormulaRow = function() {
2075 if (!self.distribForms) {
2076 // no formulas, hide the form
2077 openils.Util.hide('acq-lit-distrib-formula-table');
2081 if(!this.distribFormulaTemplate)
2082 this.distribFormulaTemplate =
2083 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
2085 var row = this.distribFormulaTemplate.cloneNode(true);
2086 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
2088 this.dfSelector = new dijit.form.FilteringSelect(
2089 {"labelAttr": "dynLabel", "labelType": "html"},
2090 nodeByName("selector", row)
2092 this._updateFormulaStore();
2093 this.dfSelector.fetchProperties =
2094 {"sort": [{"attribute": "use_count", "descending": true}]};
2096 var apply = new dijit.form.Button(
2097 {"label": localeStrings.APPLY},
2098 nodeByName('set_button', row)
2101 var reset = new dijit.form.Button(
2102 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
2103 nodeByName("reset_button", row)
2106 dojo.connect(apply, 'onClick',
2108 var form_id = self.dfSelector.attr("value");
2109 if(!form_id) return;
2110 self._applyDistribFormula(form_id);
2111 reset.attr("disabled", false);
2115 dojo.connect(reset, 'onClick',
2117 self.restoreCopyFieldsBeforeDF();
2118 self.virtDfaCounts = {};
2119 self.virtDfaId = -1;
2121 self._updateFormulaStore();
2122 self._removeAllDistribAppliedVirtual();
2123 reset.attr("disabled", "true");
2130 * Applies a distrib formula to the current set of copies
2132 this._applyDistribFormula = function(formula) {
2133 if(!formula) return;
2135 formula = this.distribForms.filter(
2136 function(form) { return form.id() == formula; }
2139 var copyRows = dojo.query('tr', self.copyTbody);
2141 if (this.dfeOffset >= copyRows.length) {
2142 alert(localeStrings.OUT_OF_COPIES);
2146 var entries_applied = 0;
2148 var rowIndex = this.dfeOffset;
2149 rowIndex < copyRows.length;
2153 var row = copyRows[rowIndex];
2154 var copy_id = row.getAttribute('copy_id');
2155 var copyWidgets = this.copyWidgetCache[copy_id];
2156 var entryIndex = this.dfeOffset;
2159 // find the correct entry for the current row
2160 dojo.forEach(formula.entries(),
2163 entryIndex += e.item_count();
2164 if(entryIndex > rowIndex)
2172 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
2173 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
2176 this.saveCopyFieldsBeforeDF(copy_id);
2177 this._copy_fields_for_acqdf.forEach(
2179 if(entry[field]()) {
2180 copyWidgets[field].attr('value', (entry[field]()));
2187 if (entries_applied) {
2188 this.virtDfaCounts[formula.id()] =
2189 ++(this.virtDfaCounts[formula.id()]) || 1;
2190 this._updateFormulaStore();
2191 this._drawDistribAppliedUnit(
2193 var dfa = new acqdfa();
2194 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
2197 this.dfeOffset += entries_applied;
2202 * This function updates the DF store for the dropdown so that use_counts
2203 * can reflect DF applications from this session before they're saved
2206 this._updateFormulaStore = function() {
2207 this.dfSelector.store = new dojo.data.ItemFileReadStore(
2209 "data": self._labelFormulasWithCounts(
2210 acqdf.toStoreData(self.distribForms)
2216 this.saveCopyFieldsBeforeDF = function(copy_id) {
2218 if (!this.oldCopyWidgetCache[copy_id]) {
2219 var copyWidgets = this.copyWidgetCache[copy_id];
2221 this.oldCopyWidgetCache[copy_id] = {};
2222 this._copy_fields_for_acqdf.forEach(
2224 self.oldCopyWidgetCache[copy_id][f] =
2225 copyWidgets[f].attr("value");
2231 this.restoreCopyFieldsBeforeDF = function() {
2233 for (var copy_id in this.oldCopyWidgetCache) {
2234 this._copy_fields_for_acqdf.forEach(
2236 self.copyWidgetCache[copy_id][f].attr(
2237 "value", self.oldCopyWidgetCache[copy_id][f]
2244 this._labelFormulasWithCounts = function(store_data) {
2245 for (var key in store_data.items) {
2246 var obj = store_data.items[key];
2247 obj.use_count = Number(obj.use_count); /* needed for sorting */
2249 if (this.virtDfaCounts[obj.id])
2250 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
2252 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
2253 obj.use_count + "]</span> " + obj.name;
2259 * This method formerly would not refetch the DF formulas if they'd been
2260 * loaded already, but now it always re-fetches, since use_count changes.
2262 /** TODO: port distrib-formula selector to autofieldwidget+pcrud/dojo store */
2263 this._fetchDistribFormulas = function(onload) {
2264 fieldmapper.standardRequest(
2266 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
2269 "params": [openils.User.authtoken, 0, 500],
2270 "oncomplete": function(r) {
2271 self.distribForms = openils.Util.readResponse(r);
2272 if(!self.distribForms || self.distribForms.length == 0) {
2273 self.distribForms = [];
2275 self._addDistribFormulaRow();
2282 this._drawBatchCopyWidgets = function() {
2283 var row = this.copyBatchRow;
2284 dojo.forEach(liDetailBatchFields,
2286 if(self.copyBatchRowDrawn) {
2287 self.copyBatchWidgets[field].attr('value', null);
2289 var args = self.afwCopyFieldArgs(field, "CREATE_PICKLIST");
2290 args.parentNode = dojo.query('[name='+field+']', row)[0];
2292 var widget = new openils.widget.AutoFieldWidget(args);
2295 if (field == "fund" && w.store)
2296 self._ensureCSSFundClasses(w.store);
2297 self.copyBatchWidgets[field] = w;
2300 if (field == "fund") {
2302 widget.widget, "onChange", function(val) {
2303 self._updateFundSelectorStyle(widget, val);
2310 this.copyBatchRowDrawn = true;
2313 this.batchCopyUpdate = function() {
2315 for(var k in this.copyWidgetCache) {
2316 var cache = this.copyWidgetCache[k];
2317 dojo.forEach(liDetailBatchFields, function(f) {
2318 var newval = self.copyBatchWidgets[f].attr('value');
2319 if(newval) cache[f].attr('value', newval);
2324 this._drawCopies = function(li) {
2327 // this button sets the total number of copies for a given lineitem
2328 acqLitAddCopyCount.onClick = function() {
2329 var count = acqLitCopyCountInput.attr('value');
2332 while(self.copyCount() < count)
2335 // delete rows if necessary
2336 var diff = self.copyCount() - count;
2338 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
2339 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
2340 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
2342 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2348 if(li.lineitem_details().length > 0) {
2349 dojo.forEach(li.lineitem_details(),
2351 self.addCopy(li, copy);
2359 this.copyCount = function() {
2361 for(var id in this.copyCache) {
2362 if(!this.copyCache[id].isdeleted())
2368 this.virtCopyId = -1;
2369 this.addCopy = function(li, copy) {
2370 var row = this.copyRow.cloneNode(true);
2371 this.copyTbody.appendChild(row);
2375 copy = new fieldmapper.acqlid();
2377 copy.id(this.virtCopyId--);
2378 copy.lineitem(li.id());
2381 this.copyCache[copy.id()] = copy;
2382 row.setAttribute('copy_id', copy.id());
2383 self.copyWidgetCache[copy.id()] = {};
2385 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2387 var rcvr = copy.receiver();
2389 if (!userCache[rcvr]) {
2390 if(rcvr == openils.User.user.id()) {
2391 userCache[rcvr] = openils.User.user;
2393 userCache[rcvr] = fieldmapper.standardRequest(
2394 ['open-ils.actor', 'open-ils.actor.user.retrieve'],
2395 {params: [openils.User.authtoken, rcvr]}
2399 dojo.query('[name=receiver]', row)[0].innerHTML = userCache[rcvr].usrname();
2402 dojo.forEach(liDetailFields,
2405 if (field == "fund") {
2406 searchFilter = (copy.fund() ?
2407 {"-or": {"active": "t", "id": copy.fund()}} :
2409 searchFilter.org = fundSearchFilter.org;
2411 searchFilter = null;
2414 var readOnly = false;
2416 // TODO: Add support for changing the owning_lib after real copies have been made.
2417 // owning_lib is order data as much as its item data
2418 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
2422 // TODO: add support for changing the fund after debits have been created
2423 // Note: invoicing allows the change
2424 if(copy.fund_debit() && field == 'fund') {
2429 var widget = new openils.widget.AutoFieldWidget({
2432 labelFormat : (field == 'fund') ? fundLabelFormat : null,
2433 searchFormat : (field == 'fund') ? fundSearchFormat : null,
2434 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
2435 searchFilter : searchFilter,
2436 noCache: (field == "fund"),
2438 parentNode : dojo.query('[name='+field+']', row)[0],
2439 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2440 readOnly : readOnly,
2441 orgDefaultsToWs : true
2445 // make sure we capture the value from any async widgets
2448 if (field == "fund" && w.store)
2449 self._ensureCSSFundClasses(w.store);
2452 copy[field](ww.getFormattedValue())
2454 self.copyWidgetCache[copy.id()][field] = w;
2456 dojo.connect(w, 'onChange',
2458 if (field == "fund")
2459 self._updateFundSelectorStyle(widget, val);
2461 if (!readOnly && (copy.isnew() || val != copy[field]())) {
2462 // prevent setting ischanged() automatically on widget load for existing copies
2463 copy[field](widget.getFormattedValue())
2464 copy.ischanged(true);
2473 this.updateLidState(copy, row);
2476 this._ensureCSSFundClass = function(id) {
2477 if (!this.fundStyleSheet) {
2479 "style", {"type": "text/css"},
2480 document.getElementsByTagName("head")[0], "last"
2482 this.fundStyleSheet = document.styleSheets[
2483 document.styleSheets.length - 1
2487 var cn = "fund_" + id;
2488 if (!this.haveFundClass[cn]) {
2489 fieldmapper.standardRequest(
2490 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
2492 "params": [openils.User.authtoken, id],
2494 "oncomplete": function(r) {
2495 r = openils.Util.readResponse(r);
2496 self.fundBalanceState[id] = r;
2498 if (r[0] /* stop */)
2499 style = fundStyles.stop;
2500 else if (r[1] /* warning */)
2501 style = fundStyles.warning;
2502 self.fundStyleSheet.insertRule(
2503 "." + cn + " { " + style + " }",
2504 self.fundStyleSheet.cssRules.length
2506 self.haveFundClass[cn] = true;
2513 this._ensureCSSFundClasses = function(store) {
2515 "query": {"id": "*"},
2516 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
2520 this._updateFundSelectorStyle = function(widget, fund_id) {
2521 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
2522 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
2525 this.updateLidState = function(copy, row) {
2528 if (typeof(row) == "undefined") {
2529 row = dojo.query('tr[copy_id="' + copy.id() + '"]', this.copyTbody)[0];
2533 var recv_link = nodeByName("receive", row);
2534 var unrecv_link = nodeByName("unreceive", row);
2535 var del_link = nodeByName("delete", row);
2536 var cxl_link = nodeByName("cancel", row);
2537 var claim_link = nodeByName("claim", row);
2538 var cxl_reason_link = nodeByName("cancel_reason", row);
2540 // by default, hide all the actions
2541 openils.Util.hide(del_link.parentNode);
2542 openils.Util.hide(recv_link);
2543 openils.Util.hide(unrecv_link);
2544 openils.Util.hide(cxl_link);
2545 openils.Util.hide(claim_link);
2546 openils.Util.hide(cxl_reason_link);
2548 if (copy.id() > 0) { // real copies (LIDs)
2550 if (copy.cancel_reason()) {
2552 /* --------- cancelled -------------------------- */
2554 /* XXX the following may leak memory in a long lived table:
2555 * dijits may not get destroyed... not positive. revisit. */
2556 var holds_reason = dojo.create(
2558 "style": "border-bottom: 1px dashed #000;",
2559 "innerHTML": copy.cancel_reason().label()
2560 }, cxl_reason_link, "only"
2564 "label": "<em>" + copy.cancel_reason().label() +
2565 "</em><br />" + copy.cancel_reason().description(),
2566 "connectId": [holds_reason]
2567 }, dojo.create("span", null, cxl_reason_link, "last")
2569 openils.Util.show(cxl_reason_link, "inline");
2571 if (copy.cancel_reason().keep_debits() == 't' ) {
2572 // allow further cancellation of "delayed" copies
2574 openils.Util.show(cxl_link, "inline");
2575 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2578 } else if (copy.recv_time()) {
2580 /* --------- received -------------------------- */
2582 openils.Util.show(unrecv_link, "inline");
2583 unrecv_link.onclick = function() {
2584 if (confirm(localeStrings.UNRECEIVE_LID))
2585 self.issueReceive(copy, /* rollback */ true);
2588 } else if (this.liCache[copy.lineitem()].state() == 'on-order') {
2590 /* --------- on order -------------------------- */
2592 openils.Util.show(recv_link, 'inline');
2593 openils.Util.show(cxl_link, "inline");
2595 recv_link.onclick = function() {
2596 if (self.checkLiAlerts(copy.lineitem()))
2597 self.issueReceive(copy);
2600 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2604 /* --------- pre-order copies -------------------------- */
2606 del_link.onclick = function() { self.deleteCopy(row) };
2607 openils.Util.show(del_link.parentNode);
2613 /* --------- virtual copies -------------------------- */
2615 del_link.onclick = function() { self.deleteCopy(row) };
2616 openils.Util.show(del_link.parentNode);
2620 this.cancelLid = function(lid_id) {
2621 lidCancelDialog._lid_id = lid_id;
2622 openils.Util.show(lidCancelDialog.domNode.parentNode);
2623 lidCancelDialog.show();
2624 if (!lidCancelDialog._prepared) {
2625 var widget = new openils.widget.AutoFieldWidget({
2626 "fmField": "cancel_reason",
2627 "fmClass": "acqlid",
2628 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
2629 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2631 "searchOptions" : {order_by : {"acqcr":"label"}}
2635 acqLidCancelButton.onClick = function() {
2636 if (w.attr("value")) {
2637 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
2639 lidCancelDialog._lid_id,
2643 lidCancelDialog.hide();
2646 lidCancelDialog._prepared = true;
2652 this._cancelLid = function(lid_id, reason) {
2653 fieldmapper.standardRequest(
2654 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
2655 "params": [openils.User.authtoken, lid_id, reason],
2657 "onresponse": function(r) {
2658 if (r = openils.Util.readResponse(r)) {
2660 for (var id in r.lid) {
2661 /* actually this should only iterate once */
2662 self.copyCache[id].cancel_reason(
2663 r.lid[id].cancel_reason
2665 self.updateLidState(self.copyCache[id]);
2666 if (r.li_update_needed) {
2667 location.href = location.href; // sledgehammer
2677 this._confirmAlert = function(li, lin) {
2679 dojo.string.substitute(
2680 localeStrings.CONFIRM_LI_ALERT, [
2681 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2682 "title", "lineitem_marc_attr_definition"
2684 /* XXX it's really better add a parameter and to adjust
2685 * the format string rather than do this concatenation
2686 * here, but if someone wants this for 2.2 in a hurry,
2687 * we can sidestep the problem of updating the strings
2688 * while the translators are working. */
2690 aou.findOrgUnit(lin.alert_text().owning_lib()).shortname() +
2692 lin.alert_text().code()
2694 lin.alert_text().description() || "",
2701 this.checkLiAlerts = function(li_id) {
2702 var li = this.liCache[li_id];
2704 var alert_notes = li.lineitem_notes().filter(
2705 function(o) { return Boolean(o.alert_text()); }
2708 /* this is _intentionally_ not done in a call to forEach() ... */
2709 for (var i = 0; i < alert_notes.length; i++) {
2710 if (this.noteAcks[alert_notes[i].id()])
2712 else if (!this._confirmAlert(li, alert_notes[i]))
2715 this.noteAcks[alert_notes[i].id()] = true;
2721 this.deleteCopy = function(row) {
2722 var copy = this.copyCache[row.getAttribute('copy_id')];
2723 copy.isdeleted(true);
2725 delete this.copyCache[copy.id()];
2726 this.copyTbody.removeChild(row);
2729 this._virtDfaCountsAsList = function() {
2731 for (var key in this.virtDfaCounts) {
2732 for (var i = 0; i < this.virtDfaCounts[key]; i++)
2738 this.confirmBreachedCopyFunds = function(copies) {
2739 var stop = 0, warning = 0;
2743 var state = self.fundBalanceState[o.fund()];
2744 if (state[0] /* stop */)
2746 else if (state[1] /* warning */)
2753 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
2754 } else if (warning) {
2755 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
2760 this.saveCopyChanges = function(liId) {
2766 for(var id in this.copyCache) {
2767 var c = this.copyCache[id];
2768 if(!c.isdeleted()) total++;
2769 if(c.isnew() || c.ischanged() || c.isdeleted()) {
2770 if(c.id() < 0) c.id(null);
2776 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
2779 if (copies.length > 0) {
2780 if (!this.confirmBreachedCopyFunds(copies))
2783 if (typeof(this._copy_count_cb) == "function")
2784 this._copy_count_cb(liId, total);
2786 openils.Util.show("acq-lit-update-copies-progress");
2787 fieldmapper.standardRequest(
2788 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
2790 params: [openils.User.authtoken, copies],
2791 onresponse: function(r) {
2792 var res = openils.Util.readResponse(r);
2793 litUpdateCopiesProgress.update(res);
2795 oncomplete: function() {
2796 self.drawCopies(liId, true /* force_fetch */);
2797 openils.Util.hide("acq-lit-update-copies-progress");
2798 refreshPOSummaryAmounts();
2804 var dfa_list = this._virtDfaCountsAsList();
2805 if (dfa_list.length > 0) {
2806 fieldmapper.standardRequest(
2808 "open-ils.acq.distribution_formula.record_application"],
2811 "params": [openils.User.authtoken, dfa_list, liId],
2812 "onresponse": function(r) {
2813 var res = openils.Util.readResponse(r);
2814 if (res && res.length < dfa_list.length)
2815 alert(localeStrings.DFA_NOT_ALL);
2819 this.virtDfaCounts = {};
2822 if (this.inlineCopiesNeedingRefresh.indexOf(liId) < 0)
2823 this.inlineCopiesNeedingRefresh.push(liId);
2826 this._updateCreatePoPrepayCheckbox = function(prepay) {
2827 var prepay = openils.Util.isTrue(prepay);
2828 this._prepayRequiredByVendor = prepay;
2829 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
2832 this._confirmPoPrepaySituation = function() {
2833 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
2834 if (want_prepay != this._prepayRequiredByVendor) {
2837 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
2838 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
2845 this.applySelectedLiAction = function(action) {
2849 case 'delete_selected':
2850 this._deleteLiList(self.getSelected());
2853 case 'add_to_order':
2854 addToPoDialog._get_li = dojo.hitch(
2857 return this.getSelected(
2858 false, null, true, li_pre_po_states);
2861 if (addToPoDialog._get_li().length == 0) {
2862 alert(localeStrings.NO_LI_GENERAL);
2865 addToPoDialog.show();
2868 case 'create_order':
2869 this._loadPOSelect();
2870 acqLitPoCreateDialog.show();
2873 case 'save_picklist':
2874 acqLitSavePlDialog.show();
2877 case 'selector_ready':
2879 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
2880 acqLitChangeLiStateDialog.show();
2888 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
2891 case 'batch_create_invoice':
2892 this.batchCreateInvoice();
2895 case 'batch_link_invoice':
2896 this.batchLinkInvoice();
2899 case 'receive_lineitems':
2900 this.receiveSelectedLineitems();
2903 case 'rollback_receive_lineitems':
2904 this.rollbackReceiveLineitems();
2907 case 'create_assets':
2908 this.showAssetCreator();
2911 case 'export_attr_list':
2912 this.chooseExportAttr();
2915 case 'batch_apply_funds':
2916 this.applyBatchLiFunds();
2919 case 'add_brief_record':
2921 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
2923 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
2927 case "cancel_lineitems":
2928 console.log('HERE');
2929 this.maybeCancelLineitems();
2932 case "apply_claim_policy":
2933 var li_list = this.getSelected();
2934 this.claimPolicyPicker.attr("value", null);
2935 liClaimPolicyDialog.show();
2936 liClaimPolicySave.onClick = function() {
2937 self.changeClaimPolicy(
2939 self.claimPolicyPicker.attr("value"),
2943 self.setClaimPolicyControl(li);
2944 self.reconsiderClaimControl(li);
2947 liClaimPolicyDialog.hide();
2955 this.changeClaimPolicy = function(li_list, value, callback) {
2957 function(li) { li.claim_policy(value); }
2959 fieldmapper.standardRequest(
2960 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
2961 "params": [openils.User.authtoken, li_list],
2963 "oncomplete": function(r) {
2964 r = openils.Util.readResponse(r);
2965 if (callback) callback(r);
2971 this.showAssetCreator = function(onAssetsCreated) {
2972 if(!this.isPO) return;
2975 // first, let's see if this PO has any LI's that need to be merged/imported
2976 self.pcrud.search('jub', {purchase_order : this.isPO, eg_bib_id : null}, {
2978 oncomplete : function(r) {
2979 var resp = openils.Util.readResponse(r);
2980 if (resp && resp.length) {
2981 // PO has some non-linked jubs.
2983 self.show('asset-creator');
2984 if(!self.vlAgent.loaded)
2985 self.vlAgent.init();
2987 dojo.connect(assetCreatorButton, 'onClick',
2988 function() { self.createAssets(onAssetsCreated) });
2992 // all jubs linked, move on to asset creation
2993 self.createAssets(onAssetsCreated, true);
2999 this.createAssets = function(onAssetsCreated, noVl) {
3000 this.show('acq-lit-progress-numbers');
3002 var vlArgs = (noVl) ? {} : {vandelay : this.vlAgent.values()};
3003 this.batchProgress = {};
3004 progressDialog.show(false);
3005 progressDialog.attr("title", localeStrings.LI_CREATING_ASSETS);
3006 fieldmapper.standardRequest(
3007 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
3009 params: [this.authtoken, this.isPO, vlArgs],
3010 onresponse: function(r) {
3011 var resp = openils.Util.readResponse(r);
3012 self._updateProgressNumbers(resp, !Boolean(onAssetsCreated), onAssetsCreated, true);
3018 this.maybeCancelLineitems = function() {
3019 openils.Util.show("acq-lit-cancel-reason", "inline");
3020 if (!acqLitCancelLineitemsButton._prepared) {
3021 var widget = new openils.widget.AutoFieldWidget({
3022 "fmField": "cancel_reason",
3024 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
3025 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3027 "searchOptions" : {order_by : {"acqcr":"label"}}
3031 acqLitCancelLineitemsButton.onClick = function() {
3032 if (w.attr("value")) {
3033 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
3034 self._cancelLineitems(w.attr("value"));
3036 openils.Util.hide("acq-lit-cancel-reason");
3039 acqLitCancelLineitemsButton._prepared = true;
3045 this._cancelLineitems = function(reason) {
3047 var li_list = this.getSelected();
3049 // canceled lineitems may be canceled again if they were
3050 // previously delayed (keep_debits = true).
3051 li_list = li_list.filter(
3054 li.state() != 'cancelled' ||
3055 li.cancel_reason().keep_debits() == 't'
3060 id_list = li_list.map(function(l) {return l.id()});
3062 if (!id_list.length) {
3063 alert(localeStrings.NO_LI_GENERAL);
3066 fieldmapper.standardRequest(
3067 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
3068 "params": [openils.User.authtoken, id_list, reason],
3070 "onresponse": function(r) {
3071 if (r = openils.Util.readResponse(r)) {
3073 for (var id in r.li) {
3074 self.liCache[id].state(r.li[id].state);
3075 self.liCache[id].cancel_reason(
3076 r.li[id].cancel_reason
3078 self.updateLiState(self.liCache[id]);
3081 if (r.lid && self.copyCache) {
3082 for (var id in r.lid) {
3083 if (self.copyCache[id]) {
3084 self.copyCache[id].cancel_reason(
3085 r.lid[id].cancel_reason
3087 self.updateLidState(self.copyCache[id]);
3097 this.chooseExportAttr = function() {
3098 if (!acqLitExportAttrSelector._li_setup) {
3100 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
3102 "data": acqlimad.toStoreData(
3104 "acqlimad", {"code": li_exportable_attrs}
3109 acqLitExportAttrSelector.setValue();
3110 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
3111 acqLitExportAttrSelector._li_setup = true;
3113 openils.Util.show("acq-lit-export-attr-holder", "inline");
3116 this.exportAttrList = function() {
3117 var attr_def = acqLitExportAttrSelector.item;
3118 var li_list = this.getSelected();
3119 var value_list = li_list.map(
3121 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
3122 attr_def.code, "lineitem_marc_attr_definition"
3125 ).filter(function(attr) { return Boolean(attr); });
3127 if (value_list.length > 0) {
3128 if (value_list.length < li_list.length) {
3130 dojo.string.substitute(
3131 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
3138 if (window.IAMBROWSER) {
3139 var blob = new Blob(value_list, {type: "text/plain;charset=utf-8"});
3140 saveAs(blob, "export_attr_list.txt");
3142 openils.XUL.contentToFileSaveDialog(
3143 value_list.join("\n"),
3144 localeStrings.EXPORT_SAVE_DIALOG_TITLE
3151 alert(dojo.string.substitute(
3152 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
3156 openils.Util.hide("acq-lit-export-attr-holder");
3159 this.printPO = function() {
3160 if(!this.isPO) return;
3161 progressDialog.show(true);
3162 fieldmapper.standardRequest(
3163 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
3165 params: [this.authtoken, this.isPO, 'html'],
3166 oncomplete: function(r) {
3167 progressDialog.hide();
3168 var evt = openils.Util.readResponse(r);
3169 if(evt && evt.template_output()) {
3170 openils.Util.printHtmlString(evt.template_output().data());
3177 this.batchCreateInvoice = function() {
3178 var liIds = this.getSelected(
3179 false, null, true /* id_list */, li_active_states)
3180 if (!liIds.length) {
3181 alert(localeStrings.NO_LI_GENERAL);
3184 var path = oilsBasePath + '/acq/invoice/view?create=1';
3185 dojo.forEach(liIds, function(li, idx) { path += '&attach_li=' + li });
3186 if (openils.XUL.isXUL() && !window.IAMBROWSER)
3187 openils.XUL.newTabEasy(path, localeStrings.NEW_INVOICE, null, true);
3189 location.href = path;
3192 this.batchLinkInvoice = function(create) {
3193 var liIds = this.getSelected(
3194 false, null, true /* id_list */, li_active_states)
3195 if (!liIds.length) {
3196 alert(localeStrings.NO_LI_GENERAL);
3199 if (!self.invoiceLinkDialogManager) {
3200 self.invoiceLinkDialogManager =
3201 new InvoiceLinkDialogManager("li");
3203 self.invoiceLinkDialogManager.target = liIds;
3204 acqLitLinkInvoiceDialog.show();
3207 this.receiveSelectedLineitems = function() {
3208 var states = li_post_po_states.filter(
3209 function(s) { return s != 'received' });
3210 var li_list = this.getSelected(null, null, null, states);
3212 if (!li_list.length) {
3213 alert(localeStrings.NO_LI_GENERAL);
3217 for (var i = 0; i < li_list.length; i++) {
3218 var li = li_list[i];
3220 if (li.state() != "received" &&
3221 !this.checkLiAlerts(li.id())) return;
3224 this.show('acq-lit-progress-numbers');
3227 fieldmapper.standardRequest(
3228 ['open-ils.acq', 'open-ils.acq.lineitem.receive.batch'],
3232 li_list.map(function(li) { return li.id(); })
3234 onresponse : function(r) {
3235 var resp = openils.Util.readResponse(r);
3236 self._updateProgressNumbers(resp, true);
3242 this.issueReceive = function(obj, rollback) {
3244 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
3246 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
3248 progressDialog.show(true);
3249 fieldmapper.standardRequest(
3250 ["open-ils.acq", method], {
3252 "params": [this.authtoken, obj.id()],
3253 "onresponse": function(r) {
3254 if (r = openils.Util.readResponse(r)) {
3255 self.fetchClaimInfo(
3256 part == "lineitem" ? obj.id() : obj.lineitem(),
3258 function() { self.handleReceive(r); }
3260 progressDialog.hide();
3268 * Handles the responses from receive and rollback ML calls.
3270 this.handleReceive = function(resp) {
3273 for (var li_id in resp.li) {
3274 for (var key in resp.li[li_id])
3275 self.liCache[li_id][key](resp.li[li_id][key]);
3276 self.updateLiState(self.liCache[li_id]);
3280 if (typeof(self.poUpdateCallback) == "function")
3281 self.poUpdateCallback(resp.po);
3284 for (var lid_id in resp.lid) {
3285 for (var key in resp.lid[lid_id])
3286 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
3287 self.updateLidState(self.copyCache[lid_id]);
3293 this.rollbackReceiveLineitems = function() {
3294 var li_id_list = this.getSelected(false, null, true);
3295 if (!li_id_list.length) {
3296 alert(localeStrings.NO_LI_GENERAL);
3300 if (!confirm(localeStrings.ROLLBACK_LI_RECEIVE_CONFIRM)) return;
3302 this.show('acq-lit-progress-numbers');
3305 fieldmapper.standardRequest(
3306 ['open-ils.acq', 'open-ils.acq.lineitem.receive.rollback.batch'],
3308 params: [this.authtoken, li_id_list],
3309 onresponse : function(r) {
3310 var resp = openils.Util.readResponse(r);
3311 self._updateProgressNumbers(resp, true);
3317 this._updateProgressNumbers = function(resp, reloadOnComplete, onComplete, clearProgressDialog) {
3318 this._updateProgressDialog(resp);
3319 this.vlAgent.handleResponse(resp,
3320 function(resp, res) {
3321 if (clearProgressDialog) {
3322 progressDialog.update({ "progress": 100});
3323 progressDialog.update_message();
3324 progressDialog.hide();
3325 progressDialog.attr("title", "");
3327 if(reloadOnComplete)
3328 location.href = location.href;
3330 onComplete(resp, res);
3335 this._updateProgressDialog = function(resp) {
3336 progressDialog.update({ "progress": (resp.progress / resp.total) * 100 });
3337 var keys = ['li', 'vqbr', 'bibs', 'lid', 'debits_accrued', 'copies'];
3338 for (var i = 0; i < keys.length; i++) {
3339 if (resp[keys[i]] > (this.batchProgress[keys[i]] || 0)) {
3340 progressDialog.update_message(
3341 dojo.string.substitute(
3342 localeStrings["ACTIVATE_" + keys[i].toUpperCase() + "_PROCESSED"],
3348 this.batchProgress = resp;
3351 this._createPO = function(fields) {
3352 var wantall = (fields.create_from == "all");
3354 /* If we're a picklist or purchase order already and the user wants
3355 * all lineitems, we might have pages' worth of lineitems haven't all
3356 * been loaded yet, so getSelected() won't find them. The server,
3357 * however, should know about all our lineitems, so let's ask the
3358 * server for a complete list.
3363 true, function(list) {
3364 self._createPOFromLineitems(fields, list);
3365 }, /* id_list */ true, li_pre_po_states
3368 this._createPOFromLineitems(
3369 fields, this.getSelected(
3370 false, null, true /* id_list */, li_pre_po_states)
3375 this._createPOFromLineitems = function(fields, selected) {
3376 if (selected.length == 0) {
3377 alert(localeStrings.NO_LI_GENERAL);
3382 var po = new fieldmapper.acqpo();
3383 po.provider(this.createPoProviderSelector.attr("value"));
3384 po.ordering_agency(this.createPoAgencySelector.attr("value"));
3385 po.prepayment_required(fields.prepayment_required[0] ? true : false);
3386 var name = this.createPoNameInput.attr('value');
3387 if (name) po.name(name); // avoid name=""
3389 // if we're creating assets, delay the asset creation
3390 // until after the PO is created. This will allow us to
3391 // use showAssetCreator() directly.
3393 fieldmapper.standardRequest(
3394 ["open-ils.acq", "open-ils.acq.purchase_order.create"],
3397 openils.User.authtoken,
3398 po, {lineitems : selected}
3400 onresponse : function(r) {
3401 var resp = openils.Util.readResponse(r);
3402 if (resp.complete) {
3403 // self.isPO is needed for showAssetCreator();
3404 self.isPO = resp.purchase_order.id();
3405 var redir = oilsBasePath + "/acq/po/view/" + self.isPO;
3406 if (fields.create_assets[0]) {
3407 self.showAssetCreator(
3408 function() {location.href = redir}
3411 location.href = redir;
3420 this.batchFundWidget = null;
3422 this.applyBatchLiFunds = function() {
3424 var liIds = this.getSelected().map(function(li) { return li.id(); });
3425 if(liIds.length == 0) return; // warn?
3428 batchFundUpdateDialog.show();
3430 if(!this.batchFundWidget) {
3431 this.batchFundWidget = new openils.widget.AutoFieldWidget({
3433 selfReference : true,
3434 labelFormat : fundLabelFormat,
3435 searchFormat : fundSearchFormat,
3436 searchFilter : fundSearchFilter,
3437 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
3438 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
3439 dijitArgs : { "required": true, "labelType": "html" },
3442 this.batchFundWidget.build();
3445 dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
3446 dojo.connect(batchFundUpdateSubmit, 'onClick',
3449 // TODO: call .dry_run first to test thresholds
3450 fieldmapper.standardRequest(
3451 ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
3454 openils.User.authtoken,
3456 self.batchFundWidget.widget.attr('value')
3458 oncomplete : function(r) {
3459 var resp = openils.Util.readResponse(r);
3461 location.href = location.href;
3470 this._deleteLiList = function(list, idx) {
3471 if(idx == null) idx = 0;
3472 if(idx >= list.length) return;
3477 if (this.isPO && (li.state() == "on-order" || li.state() == "received")) {
3478 /* It makes little sense to delete a lineitem from a PO that has
3479 * already been marked 'on-order'. Especially if EDI is in use,
3480 * such a purchase order will probably have already been shipped
3481 * off to a vendor, and mucking with it at this point could leave
3482 * your data in a bad state that doesn't jive with reality.
3484 * I could see making this restriction even firmer.
3486 * I could also see adjusting the li state comparisons, extending
3487 * the comparison to the PO's state, and/or providing functions
3488 * that house the logic for comparing states in a single location.
3490 * Yes, this will be really annoying if you have selected a lot
3491 * of lineitems to cancel that have been ordered. You'll get a
3492 * confirm dialog for each one.
3495 if (!confirm(localeStrings.DEL_LI_FROM_PO)) {
3496 self._deleteLiList(list, ++idx); /* move on to next in list */
3501 fieldmapper.standardRequest(
3503 this.isPO ? 'open-ils.acq.purchase_order.lineitem.delete' : 'open-ils.acq.picklist.lineitem.delete'],
3505 params: [openils.User.authtoken, liId],
3506 oncomplete: function(r) {
3507 self.removeLineitem(liId);
3508 self._deleteLiList(list, ++idx);
3514 this.editOrderMarc = function(li) {
3517 if(window.IAMBROWSER) {
3518 xulG.edit_marc_order_record(li, function(li) { self.drawInfo(li.id()) });
3522 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
3523 to true in about:config */
3524 if(openils.XUL.isXUL()) {
3525 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul','','chrome');
3527 win = window.open('/xul/server/cat/marcedit.xul','','chrome');
3530 record : {marc : li.marc(), "rtype": "bre"},
3532 label: 'Save Record', // XXX I18N
3533 func: function(xmlString) {
3535 fieldmapper.standardRequest(
3536 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
3538 params: [openils.User.authtoken, li],
3539 oncomplete: function(r) {
3540 openils.Util.readResponse(r);
3542 self.drawInfo(li.id())
3548 'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
3549 'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
3553 this._savePl = function(values) {
3555 (values.which == 'all'),
3556 function(list) { self._savePlFromLineitems(values, list); }
3560 this._savePlFromLineitems = function(values, selected) {
3561 openils.Util.show("acq-lit-generic-progress");
3563 if(values.new_name) {
3564 openils.acq.Picklist.create(
3565 {name: values.new_name},
3571 oilsBasePath + "/acq/picklist/view/" + id;
3576 } else if(values.existing_pl) {
3577 // update lineitems to use an existing picklist
3579 values.existing_pl, selected, 0,
3582 oilsBasePath + "/acq/picklist/view/" +
3589 this._updateLiState = function(values, state, state_filter) {
3590 progressDialog.show(true);
3592 (values.which == 'all'),
3594 self._updateLiStateFromLineitems(values, state, list);
3595 }, false /* id_list */, state_filter
3599 this._updateLiStateFromLineitems = function(values, state, selected) {
3600 if(!selected.length) {
3601 try { progressDialog.hide() } catch(E) {};
3602 alert(localeStrings.NO_LI_GENERAL);
3605 dojo.forEach(selected, function(li) {li.state(state);});
3606 self._updateLiList(null, selected, 0,
3607 // TODO consider inline updates for efficiency
3608 function() { location.href = location.href }
3612 this._updateLiList = function(pl, list, idx, oncomplete) {
3613 if(idx >= list.length) return oncomplete();
3615 if(pl != null) li.picklist(pl);
3616 litGenericProgress.update({maximum: list.length, progress: idx});
3617 new openils.acq.Lineitem({lineitem:li}).update(
3619 self._updateLiList(pl, list, ++idx, oncomplete);
3624 this._loadPOSelect = function() {
3625 if (!this.createPoProviderSelector) {
3626 var widget = new openils.widget.AutoFieldWidget({
3627 "fmField": "provider",
3629 "searchFilter": {"active": "t"},
3630 "parentNode": dojo.byId("acq-lit-po-provider"),
3632 "onChange": function() {
3634 self._updateCreatePoPrepayCheckbox(
3635 this.item.prepayment_required()
3641 widget.build(function(w) { self.createPoProviderSelector = w; });
3644 this.createPoCheckDupes = function() {
3645 var org = self.createPoAgencySelector.attr('value');
3646 var name = self.createPoNameInput.attr('value');
3647 openils.Util.hide('acq-dupe-po-name');
3650 acqLitCreatePoSubmit.attr('disabled', false);
3654 acqLitCreatePoSubmit.attr('disabled', true);
3655 var orgs = fieldmapper.aou.descendantNodeList(org, true);
3656 new openils.PermaCrud().search('acqpo',
3657 {name : name, ordering_agency : orgs},
3658 {async : true, oncomplete : function(r) {
3659 var po = openils.Util.readResponse(r);
3661 if (po && (po = po[0])) {
3663 var link = dojo.byId('acq-dupe-po-link');
3664 openils.Util.show('acq-dupe-po-name', 'table-row');
3665 var dupe_path = '/acq/po/view/' + po.id();
3669 if (window.IAMBROWSER) {
3670 // TODO: integration
3674 link.onclick = function() {
3676 var loc = xulG.url_prefix('XUL_BROWSER?url=') +
3677 window.encodeURIComponent(
3678 xulG.url_prefix('EG_WEB_BASE' + dupe_path)
3682 {tab_name: '', browser:false},
3685 show_nav_buttons : true,
3686 show_print_button : true,
3693 link.onclick = function() {
3694 window.open(oilsBasePath + dupe_path, '_blank').focus();
3699 acqLitCreatePoSubmit.attr('disabled', false);
3705 if (!this.createPoAgencySelector) {
3706 var widget = new openils.widget.AutoFieldWidget({
3707 "fmField": "ordering_agency",
3709 "parentNode": dojo.byId("acq-lit-po-agency"),
3710 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3712 widget.build(function(w) {
3713 self.createPoAgencySelector = w;
3714 dojo.connect(w, 'onChange', self.createPoCheckDupes);
3718 if (!this.createPoNameInput) {
3719 var widget = new openils.widget.AutoFieldWidget({
3722 "parentNode": dojo.byId("acq-lit-po-name"),
3723 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3725 widget.build(function(w) {
3726 self.createPoNameInput = w;
3727 dojo.connect(w, 'onChange', self.createPoCheckDupes);
3732 this.showRealCopyEditUI = function(li) {
3737 this._fetchLineitem(li.id(),
3739 li = self.liCache[li.id()] = fullLi;
3743 id : li.lineitem_details().map(
3744 function(item) { return item.eg_copy_id() }
3748 oncomplete : function(r) {
3750 var r_list = openils.Util.readResponse( r );
3751 for (var i = 0; i < r_list.length; i++) {
3752 var copy = r_list[i];
3753 var volId = copy.call_number();
3754 var volume = self.volCache[volId];
3756 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
3758 copy.call_number(volume);
3759 copyList.push(copy);
3762 xulG.volume_item_creator( { 'existing_copies' : copyList } );
3765 alert('error in oncomplete: ' + E);
3774 this.drawBibFinder = function(li) {
3777 var liWrapper = new openils.acq.Lineitem({lineitem:li});
3780 ['isbn', 'upc', 'issn', 'title', 'author'],
3782 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
3784 if(field == 'title' || field == 'author') {
3785 query += field +':' + val + ' ';
3787 query += 'identifier|' + field + ':' + val + ' ';
3793 if(openils.XUL.isXUL() && !window.IAMBROWSER) {
3795 oilsBasePath + '/acq/lineitem/findbib?query=' + encodeURIComponent(query),
3796 '', 'resizable,scrollbars=1,chrome');
3798 win = window.open( oilsBasePath + '/acq/lineitem/findbib?query=' + encodeURIComponent(query));
3802 win.window.recordFound = function(bibId) {
3805 var attrs = li.attributes();
3806 li.attributes(null);
3807 li.eg_bib_id(bibId);
3809 fieldmapper.standardRequest(
3810 ["open-ils.acq", "open-ils.acq.lineitem.update"],
3812 "params": [openils.User.authtoken, li],
3814 "oncomplete": function(r) {
3815 if(openils.Util.readResponse(r)) {
3816 location.href = location.href;