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)
791 nodeByName("show_requests_link", row).href =
792 oilsBasePath + "/acq/picklist/user_request?lineitem=" + li.id() +
793 '?source=' + encodeURIComponent(location.pathname + location.search);
795 nodeByName("show_requests_link", row).href =
796 "/eg/staff/acq/requests/lineitem/" + li.id();
797 nodeByName("show_requests_link", row).setAttribute('target','_top');
800 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
801 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
802 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
803 dojo.query('[name=expand_inline_copies]', row)[0].onclick =
804 function() {self.drawInlineCopies(li.id())};
807 if (sum = li.order_summary()) { // assignment
808 // Only show the paid label if at least one copy is invoiced.
809 // In other words, a lineitem whose every copy is canceled
811 if (sum.invoice_count() > 0) {
812 if (sum.item_count() == (
813 sum.invoice_count() + sum.cancel_count())) {
814 // Lineitem is fully paid. Display the paid-off label
815 openils.Util.show(nodeByName('paid', row), 'inline');
820 this.drawOrderIdentSelector(li, row);
822 if (!this.skipInitialEligibilityCheck)
826 function(full) { self.setClaimPolicyControl(full, row) },
830 this.updateLiNotesCount(li, row);
832 // show which PO this lineitem is a member of
833 if(li.purchase_order() && !this.isPO) {
835 this.poCache[li.purchase_order()] =
836 this.poCache[li.purchase_order()] ||
837 fieldmapper.standardRequest(
838 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
840 this.authtoken, li.purchase_order(), {
841 "flesh_price_summary": true,
842 "flesh_provider" : true,
843 "flesh_lineitem_count": true
846 if(po && !this.isMeta) {
847 openils.Util.show(nodeByName('po', row), 'inline');
848 var link = nodeByName('po_link', row);
849 link.setAttribute('href', oilsBasePath +
850 '/acq/po/view/' + li.purchase_order() +
851 '?focus_li=' + li.id() +
852 '&source=' + encodeURIComponent(location.pathname + location.search)
854 link.innerHTML += po.name();
856 openils.Util.show(nodeByName('pro', row), 'inline');
857 link = nodeByName('pro_link', row);
858 link.setAttribute('href', oilsBasePath + '/conify/global/acq/provider/' + po.provider().id())
859 link.innerHTML += po.provider().code();
863 // show which picklist this lineitem is a member of
864 if(li.picklist() && (this.isPO || this.isMeta || this.isUni)) {
866 this.plCache[li.picklist()] =
867 this.plCache[li.picklist()] ||
868 fieldmapper.standardRequest(
869 ['open-ils.acq', 'open-ils.acq.picklist.retrieve.authoritative'],
870 {params: [this.authtoken, li.picklist()]});
872 if (pl.name() == "") {
873 openils.Util.show(nodeByName("bib_origin", row), "inline");
877 openils.Util.show(nodeByName('pl', row), 'inline');
878 var link = nodeByName('pl_link', row);
879 link.setAttribute('href', oilsBasePath +
880 '/acq/picklist/view/' + li.picklist() +
881 '?focus_li=' + li.id() +
882 '&source=' + encodeURIComponent(location.pathname + location.search)
884 link.innerHTML += pl.name();
889 var countNode = nodeByName('count', row);
890 var count = li.item_count() || 0;
891 if (typeof(this._copy_count_cb) == "function") {
892 this._copy_count_cb(li.id(), count);
894 countNode.innerHTML = count;
895 countNode.id = 'acq-lit-copy-count-label-' + li.id();
898 var priceInput = dojo.query('[name=price]', row)[0];
899 priceInput.value = li.estimated_unit_price() || '';
900 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
902 // show either "mark received" or "unreceive" as appropriate
903 this.updateLiState(li, row);
905 if (skip_final_placement) {
909 // the last LI may be rendered after the call to show('list'),
910 // so make sure it's focused if necessary.
911 if (this.focusLineitem == li.id())
915 this._liCountClaims = function(li) {
917 for (var i = 0; i < li.lineitem_details().length; i++)
918 total += li.lineitem_details()[i].claims().length;
922 this._findLiRow = function(li) {
923 return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
926 this.reconsiderClaimControl = function(li, row) {
927 if (!row) row = this._findLiRow(li);
928 var option = nodeByName("action_manage_claims", row);
929 var eligible = this.claimEligibleLidByLi[li.id()].length;
930 var count = this._liCountClaims(li);
932 option.disabled = !(count || eligible);
934 dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
937 this.clearEligibility = function(li) {
938 this.claimEligibleLidByLi[li.id()] = [];
940 if (li.lineitem_details()) {
941 li.lineitem_details().forEach(
942 function(lid) { delete self.claimEligibleLid[lid.id()]; }
946 if (this.copyCache) {
948 for (var k in this.copyCache) {
949 if (this.copyCache[k].lineitem() == li.id())
953 function(k) { delete self.claimEligibleLid[k]; }
958 this.applyOrderIdentValues = function() {
959 this._identValuesInFlight =
960 openils.Util.objectProperties(this.liCache).length;
961 for (var liId in this.liCache) {
962 this._applyOrderIdentValue(this.liCache[liId]);
966 // returns true if request was sent
967 this._applyOrderIdentValue = function(li, oncomplete) {
970 console.log('applying ident value for lineitem ' + li.id());
973 var row = dojo.query('[li=' + li.id() + ']')[0];
975 // find the selected ident value
976 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
977 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
978 var name = typeSel.options[typeSel.selectedIndex].value;
979 var val = typeSel._cbox.attr('value');
981 console.log("selected ident is " + val);
983 // it differs from the existing ident value, update it
984 var oldIdent = self.getLiOrderIdent(li);
986 oldIdent.attr_name() == name &&
987 oldIdent.attr_value() == val) {
988 console.log('selected ident attr matches existing attr');
989 if (--this._identValuesInFlight == 0) {
990 if (oncomplete) oncomplete(li);
991 else location.href = location.href;
996 // see if the selected ident value is represented
997 // by an existing lineitem attr
1000 typeSel._cbox.store.fetch({
1001 query : {attr_value : val},
1002 onItem : function(item) {
1003 console.log('found existing attr for ident value');
1004 args.source_attr_id = li.attributes().filter(
1005 function(attr) { return attr.id() == item.id[0] }
1011 if (!args.source_attr_id) {
1012 // user entered new text in the combobox
1013 // so we need to create a new attr
1014 console.log('creating new ident attr');
1015 args.lineitem_id = li.id();
1016 args.attr_name = name;
1017 args.attr_value = val;
1020 fieldmapper.standardRequest(
1021 ['open-ils.acq', 'open-ils.acq.lineitem.order_identifier.set'],
1023 params : [openils.User.authtoken, args],
1024 oncomplete : function() {
1025 console.log('order_ident oncomplete');
1026 if (--self._identValuesInFlight == 0) {
1027 if (oncomplete) oncomplete(li);
1028 else location.href = location.href;
1030 console.log(self._identValuesInFlight + ' still in flight');
1038 this.getLiOrderIdent = function(li) {
1039 var attrs = li.attributes();
1040 if (!attrs) return null;
1041 return attrs.filter(
1044 attr.attr_type() == 'lineitem_local_attr_definition' &&
1045 openils.Util.isTrue(attr.order_ident())
1051 this.drawOrderIdentSelector = function(li, row) {
1053 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
1054 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
1056 var attrs = li.attributes();
1058 // limit to MARC attr defs
1059 attrs = attrs.filter(
1061 return (attr.attr_type() == 'lineitem_marc_attr_definition');
1065 var identAttr = this.getLiOrderIdent(li);
1068 // collect the values for each type of identifier
1069 // find a reasonable default identifier type to render
1073 dojo.forEach(['isbn', 'upc', 'issn'],
1076 // collect the values for this attr name
1077 values[name] = attrs.filter(
1079 return (attr.attr_name() == name)
1083 // select a reasonable default name in the type-selector
1087 if (identAttr.attr_name() == name)
1089 } else if (values[name].length) {
1094 dojo.forEach(typeSel.options, function(opt) {
1095 if (opt.value == name) {
1096 opt.selected = true;
1105 function updateOrderIdent(val) {
1106 self._identValuesInFlight = 1;
1107 self._applyOrderIdentValue(
1110 self.refreshLineitem(li);
1115 // replace the ident combobox with a new
1116 // one for the selected ident type
1117 function changeComboBox(sel) {
1118 var name = sel.options[sel.selectedIndex].value;
1120 var td = dojo.query('[name=order_ident_value]', row)[0];
1121 if (td.childNodes[0])
1122 dojo.destroy(td.childNodes[0]);
1124 var store = new dojo.data.ItemFileWriteStore({
1125 data : acqlia.toStoreData(values[name])
1128 var cbox = new dijit.form.ComboBox(
1130 labelAttr : 'attr_value',
1131 searchAttr : 'attr_value'
1133 dojo.create('div', {}, td)
1138 // set the value for the cbox
1139 if (values[name].length) {
1140 var orderIdent = self.getLiOrderIdent(li);
1142 if (orderIdent && orderIdent.attr_name() == name) {
1143 cbox.attr('value', orderIdent.attr_value());
1145 cbox.attr('value', values[name][0].attr_value());
1149 if (!self.orderIdentAllowed)
1150 cbox.attr('disabled', true);
1153 cbox._lineitem = li;
1154 dojo.connect(cbox, 'onChange', updateOrderIdent);
1157 changeComboBox(typeSel); // force the initial draw
1158 typeSel.onchange = function() {changeComboBox(typeSel)};
1161 this.testOrderIdentPerms = function(org, callback) {
1163 new openils.User().getPermOrgList(
1164 'ACQ_SET_LINEITEM_IDENTIFIER',
1166 console.log('found orgs = ' + orgs);
1167 for (var i = 0; i < orgs.length; i++) {
1168 if (Number(orgs[i]) == Number(org)) {
1169 self.orderIdentAllowed = true;
1170 if (callback) callback();
1174 if (callback) callback();
1180 this.checkClaimEligibility = function(li, callback, row) {
1181 /* Assume always eligible, i.e. from this interface we don't care about
1182 * claim eligibility any more. this is where the user would force a
1184 this.clearEligibility(li);
1185 this.claimEligibleLidByLi[li.id()] = li.lineitem_details().map(
1186 function(lid) { return lid.id(); }
1188 li.lineitem_details().forEach(
1189 function(lid) { self.claimEligibleLid[lid.id()] = true; }
1191 this.reconsiderClaimControl(li, row);
1192 if (callback) callback(li);
1194 this.clearEligibility(li);
1195 fieldmapper.standardRequest(
1196 ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
1197 "params": [openils.User.authtoken, {"lineitem": li.id()}],
1199 "onresponse": function(r) {
1200 if (r = openils.Util.readResponse(r)) {
1201 self.claimEligibleLidByLi[li.id()].push(
1204 self.claimEligibleLid[r.lineitem_detail()] = true;
1207 "oncomplete": function() {
1208 self.reconsiderClaimControl(li, row);
1209 if (typeof(callback) == "function")
1217 this.updateLiNotesCount = function(li, row) {
1218 if (!row) row = this._findLiRow(li);
1220 var has_notes = (li.lineitem_notes().filter(
1221 function(o) { return Boolean (o.alert_text()); }
1224 /* U+2691 is the code point for a filled-in flag character */
1225 nodeByName("notes_alert_flag", row).innerHTML =
1226 has_notes ? "⚑" : "";
1227 nodeByName("noteslink", row).style.fontStyle =
1228 has_notes ? "italic" : "normal";
1229 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
1232 /* XXX NOT related to _updateLiState(). rethink */
1233 this.updateLiState = function(li, row) {
1234 if (!row) row = this._findLiRow(li);
1236 nodeByName("actions", row).onchange = function() {
1237 switch(this.options[this.selectedIndex].value) {
1238 case 'action_update_barcodes':
1239 self.showRealCopyEditUI(li);
1240 nodeByName("action_none", row).selected = true;
1242 case 'action_holdings_maint':
1243 (self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row ))();
1245 case 'action_manage_claims':
1246 self.fetchClaimInfo(li.id(), true, function(full) { self.claimDialog.show(full) }, row);
1248 case 'action_view_history':
1249 location.href = oilsBasePath + '/acq/lineitem/history/' + li.id();
1253 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
1254 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
1256 /* handle row coloring for based on LI state */
1257 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1258 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
1260 // Expose invoice actions for any lineitem that is linked to a PO
1261 if (li.purchase_order()) {
1262 openils.Util.show(nodeByName("invoices_span", row), "inline");
1263 var link = nodeByName("invoices_link", row);
1264 link.onclick = function() {
1265 var url = oilsBasePath + "/acq/search/unified?so=" +
1266 base64Encode({"jub":[{"id": li.id()}]}) + "&rt=invoice"
1267 if (window.IAMBROWSER) {
1268 xulG.relay_url(url);
1270 openils.XUL.newTabEasy(url);
1278 * If we haven't fleshed the lineitem_details, default to allowing access to the
1279 * holdings maintenence actions. The alternative is to flesh LIDs on every lineitem,
1280 * but that will add to page render time. Let's see if this will suffice...
1282 var lids = li.lineitem_details();
1284 (lids && !lids.filter(function(lid) { return lid.eg_copy_id() })[0] )) {
1286 actUpdateBarcodes.disabled = false;
1287 actHoldingsMaint.disabled = false;
1290 var state_cell = nodeByName("li_state_" + li.state(), row);
1292 // re-hide any state label nodes which may have been un-hidden
1293 // through previous actions.
1294 dojo.query('[state-label]', row).forEach(function(node) {
1295 openils.Util.hide(node)
1298 if (li.state() == 'cancelled') {
1299 if(typeof li.cancel_reason() == "object") {
1301 // clear the stock "Canceled" label, since we have more
1302 // information to replace it with.
1303 state_cell.innerHTML = '';
1305 var holds_state = dojo.create(
1307 "style": "border-bottom: 1px dashed #000;",
1308 "innerHTML": li.cancel_reason().label()
1309 }, state_cell, "only"
1313 "label": "<em>" + li.cancel_reason().label() +
1314 "</em><br />" + li.cancel_reason().description(),
1315 "connectId": [holds_state]
1316 }, dojo.create("span", null, state_cell, "last")
1319 if (li.cancel_reason().keep_debits() == 't') {
1320 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1321 openils.Util.addCSSClass(row, "oils-acq-li-state-delayed");
1324 console.log('li cancel_reason is un-fleshed. Please fix');
1328 openils.Util.show(state_cell);
1332 this._setAlertStore = function() {
1333 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
1335 "data": acqliat.toStoreData(
1338 "owning_lib": aou.orgNodeTrail(
1339 aou.findOrgUnit(openils.User.user.ws_ou())
1340 ).map(function(o) { return o.id(); })
1346 acqLitAlertAlertText.setValue(); /* make the store "live" */
1347 acqLitAlertAlertText._store_ready = true;
1351 * Draws and shows the lineitem notes pane
1353 this.drawLiNotes = function(li) {
1355 this.focusLineitem = li.id();
1357 if (!acqLitAlertAlertText._store_ready)
1358 this._setAlertStore();
1361 li.lineitem_notes().sort(
1363 if(a.edit_time() < b.edit_time()) return 1;
1369 while(this.liNotesTbody.childNodes[0])
1370 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
1373 acqLitCreateNoteSubmit.onClick = function() {
1374 var value = acqLitCreateNoteText.attr('value');
1376 var note = new fieldmapper.acqlin();
1379 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
1382 note.lineitem(li.id());
1384 self.updateLiNotes(li, note);
1385 acqLitCreateNoteVendorPublic.attr("checked", false);
1386 acqLitCreateNoteText.attr("value", "");
1389 acqLitCreateAlertSubmit.onClick = function() {
1390 if (!acqLitAlertAlertText.item) {
1391 alert(localeStrings.ALERT_UNSELECTED);
1395 var alert_text = new fieldmapper.acqliat().fromStoreItem(
1396 acqLitAlertAlertText.item
1398 var value = acqLitAlertNoteValue.attr("value") || "";
1400 var note = new fieldmapper.acqlin();
1402 note.lineitem(li.id());
1404 note.alert_text(alert_text);
1406 self.updateLiNotes(li, note);
1409 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
1413 * Draws a single lineitem note in the notes pane
1415 this.addLiNote = function(li, note) {
1416 if(note.isdeleted()) return;
1418 var row = self.liNotesRow.cloneNode(true);
1419 nodeByName("value", row).innerHTML = note.value();
1420 var alert_node = nodeByName("alert_code", row);
1421 if (note.alert_text()) {
1422 alert_node.innerHTML = dojo.string.substitute(
1424 aou.findOrgUnit(note.alert_text().owning_lib()).shortname(),
1425 note.alert_text().code()
1428 if (note.alert_text().description()) {
1431 "connectId": [alert_node],
1432 "label": note.alert_text().description()
1433 }, dojo.create("span", null, alert_node, "after")
1438 if (openils.Util.isTrue(note.vendor_public()))
1439 nodeByName("vendor_public", row).innerHTML =
1440 localeStrings.VENDOR_PUBLIC;
1442 nodeByName("delete", row).onclick = function() {
1443 note.isdeleted(true);
1444 self.liNotesTbody.removeChild(row);
1445 self.updateLiNotes(li);
1448 if(note.edit_time()) {
1449 nodeByName("edit_time", row).innerHTML =
1450 dojo.date.locale.format(
1451 dojo.date.stamp.fromISOString(note.edit_time()),
1452 {formatLength:'short'});
1455 self.liNotesTbody.appendChild(row);
1459 * Updates any new/changed/deleted notes on the server
1461 this.updateLiNotes = function(li, newNote) {
1467 notes = li.lineitem_notes().filter(
1469 if(note.ischanged() || note.isnew() || note.isdeleted())
1475 if(notes.length == 0) return;
1476 progressDialog.show();
1478 fieldmapper.standardRequest(
1479 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
1481 params : [this.authtoken, notes],
1482 onresponse : function(r) {
1483 var resp = openils.Util.readResponse(r);
1488 // remove the old changed notes
1490 dojo.forEach(li.lineitem_notes(),
1492 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
1496 li.lineitem_notes(list);
1499 progressDialog.hide();
1500 self.updateLiNotesCount(li);
1501 self.drawLiNotes(li);
1505 progressDialog.update(resp);
1506 var newnote = resp.note;
1508 if(!newnote.isdeleted()) {
1509 newnote.isnew(false);
1510 newnote.ischanged(false);
1511 li.lineitem_notes().push(newnote);
1518 this.updateLiPrice = function(input, li) {
1520 var price = input.value;
1521 if(Number(price) == Number(li.estimated_unit_price())) return;
1523 fieldmapper.standardRequest(
1524 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
1525 { async : false, // redundant w/ timeout
1527 params : [this.authtoken, li.id(), price],
1528 oncomplete : function(r) {
1529 openils.Util.readResponse(r);
1530 li.estimated_unit_price(price); // update local copy
1533 * If this is a PO and every visible lineitem has a price,
1534 * check again to see if this PO can be activated. Note that
1535 * every visible lineitem having a price does not guarantee it can
1536 * be activated, which is why we still make the call. Having a price
1537 * set for every visiable lineitem is just the lowest barrier to entry.
1540 var priceNodes = dojo.query('[name=price]', dojo.byId('acq-lit-tbody'));
1542 dojo.forEach(priceNodes, function(node) { if (node.value == '') allSet = false});
1543 if (allSet) checkCouldActivatePo();
1544 refreshPOSummaryAmounts();
1551 this.removeLineitem = function(liId) {
1552 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
1553 delete this.liCache[liId];
1554 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
1557 this.drawInfo = function(liId) {
1558 this.focusLineitem = liId;
1559 if (!this._isRelatedViewer) {
1560 var d = dojo.byId("acq-lit-info-related");
1561 if (!this.relCache[liId]) {
1562 fieldmapper.standardRequest(
1565 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
1568 "params": [openils.User.authtoken, liId],
1569 "onresponse": function(r) {
1570 self.relCache[liId] = openils.Util.readResponse(r);
1571 nodeByName("related_number", d).innerHTML =
1572 self.relCache[liId];
1574 self.relCache[liId] >1 ? "show" : "hide"
1580 nodeByName("related_number", d).innerHTML = this.relCache[liId];
1581 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
1586 openils.acq.Lineitem.fetchAttrDefs(
1588 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
1593 this.toggleInlineCopies = function() {
1594 // if any inline copies are not displayed,
1595 // display them all otherwise, hide them all.
1597 var displayAll = false;
1599 for (var liId in this.liCache) {
1600 if (!this.inlineCopiesVisible(liId)) {
1606 for (var liId in this.liCache) {
1607 var row = dojo.byId('acq-inline-copies-row-' + liId);
1609 if (!row || row._hidden) {
1610 this.drawInlineCopies(liId);
1612 } else { // hide all
1614 // drawInlineCopies() on a visible row will hide it.
1615 this.drawInlineCopies(liId);
1622 this.inlineCopiesVisible = function(liId) {
1623 var row = dojo.byId('acq-inline-copies-row-' + liId);
1624 return (row && !row._hidden);
1627 this.refreshInlineCopies = function(all, reFetch) {
1629 var liIds = this.inlineCopiesNeedingRefresh;
1630 if (all) liIds = openils.Util.objectProperties(liCache);
1631 liIds.forEach(function(liId) {
1632 if (self.inlineCopiesVisible(liId)) {
1633 self.drawInlineCopies(liId, reFetch); // hide
1634 self.drawInlineCopies(liId, reFetch); // re-draw
1639 // draw inline copy table. if the table is
1640 // already visible, hide the table as-is
1641 // reFetch forces a retrieval of the lineitem and
1642 // copies from the server. otherwise the locally
1643 // cached version of each is used.
1644 this.drawInlineCopies = function(liId, reFetch) {
1647 // find or create the row where the inline copies table will live
1648 var containerRow = dojo.byId('acq-inline-copies-row-' + liId);
1649 var liRow = dojo.query('[li=' + liId + ']')[0];
1651 if (!containerRow) {
1653 // build the inline copies container row and add it to
1654 // the DOM directly after the primary lineitem row
1656 containerRow = self.inlineCopyContainer.cloneNode(true);
1657 containerRow.id = 'acq-inline-copies-row-' + liId;
1659 if (liRow.nextSibling) {
1660 self.tbody.insertBefore(containerRow, liRow.nextSibling);
1662 self.tbody.appendChild(containerRow);
1667 // toggle the visible state
1668 containerRow._hidden = !containerRow._hidden;
1669 openils.Util.toggle(containerRow, 'table-row');
1671 if (containerRow._hidden) return; // hide only
1674 var handler = function(li) {
1676 var tbody = dojo.query(
1677 '[name=acq-li-inline-copies-tbody]',
1680 // reset the table before adding copy rows
1681 while (tbody.childNodes[0])
1682 tbody.removeChild(tbody.childNodes[0]);
1684 if(li.lineitem_details().length == 0) {
1686 self.inlineNoCopies.cloneNode(true));
1687 return; // no copies to show
1690 // add a row to the inline copy table for each copy
1691 dojo.forEach(li.lineitem_details(),
1693 var row = self.inlineCopyTemplate.cloneNode(true);
1694 tbody.appendChild(row);
1695 self.addInlineCopy(li, copy, row);
1700 this._fetchLineitem(liId, handler, reFetch);
1703 /** Draw read-only copy widgets for inline copies */
1704 this.addInlineCopy = function(li, copy, row) {
1707 dojo.forEach(liDetailFields,
1710 var widget = new openils.widget.AutoFieldWidget({
1713 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1714 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1715 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1717 parentNode : dojo.query('[name=' + field + ']', row)[0],
1726 /* For a given list of lineitem ids, build a list of full lineitems
1727 * re-using the fetching logic that is otherwise typical to use in this
1730 * If we've already got a lineitem in the cache, just use that.
1732 * Once we've built a list of lineitems, call callback(thatlist).
1734 this.fetchLineitemsById = function(id_list, callback) {
1735 var total = id_list.length;
1736 var result_list = [];
1738 var inner = function(li) {
1739 result_list.push(li)
1741 callback(result_list);
1744 id_list.forEach(function(id) { self._fetchLineitem(id, inner); });
1747 this._fetchLineitem = function(liId, handler, force) {
1749 var li = this.liCache[liId];
1750 if(li && li.marc() && li.lineitem_details() && !force)
1753 fieldmapper.standardRequest(
1754 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
1757 params: [self.authtoken, liId, {
1759 flesh_cancel_reason: true,
1760 flesh_li_details: true,
1762 flesh_fund_debit: true }],
1764 oncomplete: function(r) {
1765 var li = openils.Util.readResponse(r);
1766 self.liCache[liId] = li;
1773 this._drawInfo = function(li) {
1775 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
1777 if(li.eg_bib_id()) {
1778 openils.Util.hide('acq-lit-marc-order-record-label');
1779 openils.Util.hide(acqLitEditOrderMarc.domNode);
1780 openils.Util.show('acq-lit-marc-real-record-label');
1782 openils.Util.show('acq-lit-marc-order-record-label');
1783 openils.Util.show(acqLitEditOrderMarc.domNode);
1784 openils.Util.hide('acq-lit-marc-real-record-label');
1787 this.drawMarcHTML(li);
1788 this.infoTbody = dojo.byId('acq-lit-info-tbody');
1791 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
1792 while(this.infoTbody.childNodes[0])
1793 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
1795 for(var i = 0; i < li.attributes().length; i++) {
1796 var attr = li.attributes()[i];
1797 var row = this.infoRow.cloneNode(true);
1799 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
1800 var name = openils.acq.Lineitem.attrDefs[type].filter(
1802 return (a.code() == attr.attr_name());
1804 ).pop().description();
1806 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
1807 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
1808 this.infoTbody.appendChild(row);
1811 if (!this._isRelatedViewer) {
1812 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
1813 oilsBasePath + "/acq/lineitem/related/" + li.id();
1816 // if a top scroll point is defined, jump up to it here
1817 var node = dojo.byId('oils-scroll-to-top');
1818 if (node) dijit.scrollIntoView(node);
1821 this.generateMakeRecTab = function(bib_id,default_view, row) {
1823 if(openils.XUL.isXUL() && !window.IAMBROWSER) {
1826 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
1829 show_nav_buttons : true,
1830 show_print_button : true,
1831 opac_url : xulG.url_prefix('opac_rdetail|' + bib_id),
1832 default_view : default_view
1836 var url = '/eg/staff/cat/catalog/record/' + bib_id;
1837 if (default_view == 'copy_browser') {
1843 if(row) nodeByName("action_none", row).selected = true;
1847 this.drawMarcHTML = function(li) {
1848 var params = [null, true, li.marc()];
1850 params = [li.eg_bib_id(), true];
1852 fieldmapper.standardRequest(
1853 ['open-ils.search', 'open-ils.search.biblio.record.html'],
1856 oncomplete: function(r) {
1857 dojo.byId('acq-lit-marc-div').innerHTML =
1858 openils.Util.readResponse(r);
1864 this.drawCopies = function(liId, force_fetch) {
1865 this.focusLineitem = liId;
1866 if (typeof force_fetch == "undefined")
1867 force_fetch = false;
1869 var cgi = new openils.CGI();
1870 var source = cgi.param('source');
1871 if (source && source.match(/invoice/)) {
1872 // got here from the invoice page, show the 'return-to-invoice' button
1873 var cgi = new openils.CGI({url : source});
1874 cgi.param('focus_li', liId);
1875 openils.Util.show(dojo.byId('acq-lit-copies-back-to-invoice-button-wrapper'), 'inline');
1876 var button = dojo.byId('acq-lit-copies-back-to-invoice-button');
1877 button.onclick = function() { location.href = cgi.url() };
1880 openils.acq.Lineitem.fetchAndRender(liId, {},
1881 function(li, html) {
1882 dojo.byId('acq-lit-copies-li-summary').innerHTML = html;
1886 this.show('copies');
1888 this.copyCache = {};
1889 this.copyWidgetCache = {};
1890 this.oldCopyWidgetCache = {};
1891 this.virtDfaCounts = {};
1892 this.realDfaCache = {};
1895 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
1896 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
1897 acqLitCopyCountInput.attr('value', '0');
1899 if (this.isPO && PO && PO.order_date()) {
1900 // prevent adding copies to activated POs
1901 acqLitCopyCountInput.attr('disabled', true);
1902 acqLitAddCopyCount.attr('disabled', true);
1905 while(this.copyTbody.childNodes[0])
1906 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
1908 this._drawBatchCopyWidgets();
1910 this._drawDistribApplied(liId);
1912 this._fetchDistribFormulas(
1914 openils.acq.Lineitem.fetchAttrDefs(
1916 self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch);
1923 this._saveDistribAppliedTemplates = function() {
1924 if (!this._appliedDistribTemplate) {
1925 this._appliedDistribTemplate =
1926 dojo.byId("acq-lit-distrib-applied-tbody").
1927 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
1928 dojo.attr(this._appliedDistribTemplate, "id");
1932 this._drawDistribApplied = function(liId) {
1933 /* Build this table while hidden to prevent rendering artifacts */
1934 openils.Util.hide("acq-lit-distrib-applied-tbody");
1936 this._saveDistribAppliedTemplates();
1938 /* Remove any rows in the table from previous populations */
1939 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
1940 forEach(dojo.destroy);
1942 /* Unregister all dijits previously created (for some reason this isn't
1943 * covered by the above destroy calls). */
1944 dijit.registry.forEach(
1945 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
1948 /* Populate the table with our liId */
1950 fieldmapper.standardRequest(
1952 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
1955 "params": [self.authtoken, liId],
1956 "onresponse": function(r) {
1957 var dfa = openils.Util.readResponse(r);
1960 self.realDfaCache[dfa.id()] = dfa;
1961 self._drawDistribAppliedUnit(dfa);
1964 "oncomplete": function() {
1965 /* Reveal built table */
1968 "acq-lit-distrib-applied-tbody", "table-row-group"
1976 this._drawDistribAppliedUnit = function(dfa) {
1977 var new_row = false;
1978 var row = dojo.query(
1979 'tr[formula="' + dfa.formula().id() + '"]',
1980 "acq-lit-distrib-applied-tbody"
1985 row = dojo.clone(this._appliedDistribTemplate);
1986 dojo.attr(row, "formula", dfa.formula().id());
1987 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
1990 var td = dojo.query("td", row)[0];
1992 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1993 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1996 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1998 new dijit.form.Button(
2000 "onClick": function() {
2001 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
2002 self.deleteDfa(dfa);
2005 /* XXX I /cannot/ make the following work in as a CSS class
2006 * for some reason. So frustrating... */
2007 "style": function(id) {
2009 "font-weight: bold; color: #c00;" :
2011 }(dfa.id()) + "margin: 0 6px;display: inline;"
2012 }, "dfa-button-" + dfa.id()
2016 "connectId": ["dfa-button-" + dfa.id()],
2017 "label": dojo.string.substitute(
2018 localeStrings.DFA_TIP, dfa.id() > 0 ? [
2019 openils.User.formalName(dfa.creator()),
2020 dojo.date.locale.format(
2021 dojo.date.stamp.fromISOString(dfa.create_time()),
2022 {"formatLength":"short"}
2024 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
2026 }, "dfa-tip-" + dfa.id()
2030 this.deleteDfa = function(dfa) {
2031 if (dfa.id() > 0) { /* real */
2032 this.pcrud.eliminate(
2035 "oncomplete": function() {
2036 self._removeDistribApplied(dfa.id());
2037 delete self.realDfaCache[dfa.id()];
2041 } else { /* virtual */
2042 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
2043 this.virtDfaCounts[dfa.formula().id()] = 0;
2044 /* hasn't been saved yet, so no need to do anything server side */
2045 this._removeDistribApplied(dfa.id());
2050 this._removeDistribApplied = function(dfaId) {
2051 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
2052 dijit.registry.forEach(
2053 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
2055 this._removeDistribAppliedEmptyRows();
2058 this._removeAllDistribAppliedVirtual = function() {
2059 /* Unregister dijits */
2060 dijit.registry.forEach(
2061 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
2063 this._removeDistribAppliedEmptyRows();
2066 this._removeDistribAppliedEmptyRows = function() {
2067 /* Remove any rows with no DFA at all */
2068 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
2070 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
2076 * Insert a new row into the distribution formula selection form
2078 this._addDistribFormulaRow = function() {
2081 if (!self.distribForms) {
2082 // no formulas, hide the form
2083 openils.Util.hide('acq-lit-distrib-formula-table');
2087 if(!this.distribFormulaTemplate)
2088 this.distribFormulaTemplate =
2089 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
2091 var row = this.distribFormulaTemplate.cloneNode(true);
2092 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
2094 this.dfSelector = new dijit.form.FilteringSelect(
2095 {"labelAttr": "dynLabel", "labelType": "html"},
2096 nodeByName("selector", row)
2098 this._updateFormulaStore();
2099 this.dfSelector.fetchProperties =
2100 {"sort": [{"attribute": "use_count", "descending": true}]};
2102 var apply = new dijit.form.Button(
2103 {"label": localeStrings.APPLY},
2104 nodeByName('set_button', row)
2107 var reset = new dijit.form.Button(
2108 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
2109 nodeByName("reset_button", row)
2112 dojo.connect(apply, 'onClick',
2114 var form_id = self.dfSelector.attr("value");
2115 if(!form_id) return;
2116 self._applyDistribFormula(form_id);
2117 reset.attr("disabled", false);
2121 dojo.connect(reset, 'onClick',
2123 self.restoreCopyFieldsBeforeDF();
2124 self.virtDfaCounts = {};
2125 self.virtDfaId = -1;
2127 self._updateFormulaStore();
2128 self._removeAllDistribAppliedVirtual();
2129 reset.attr("disabled", "true");
2136 * Applies a distrib formula to the current set of copies
2138 this._applyDistribFormula = function(formula) {
2139 if(!formula) return;
2141 formula = this.distribForms.filter(
2142 function(form) { return form.id() == formula; }
2145 var copyRows = dojo.query('tr', self.copyTbody);
2147 if (this.dfeOffset >= copyRows.length) {
2148 alert(localeStrings.OUT_OF_COPIES);
2152 var entries_applied = 0;
2154 var rowIndex = this.dfeOffset;
2155 rowIndex < copyRows.length;
2159 var row = copyRows[rowIndex];
2160 var copy_id = row.getAttribute('copy_id');
2161 var copyWidgets = this.copyWidgetCache[copy_id];
2162 var entryIndex = this.dfeOffset;
2165 // find the correct entry for the current row
2166 dojo.forEach(formula.entries(),
2169 entryIndex += e.item_count();
2170 if(entryIndex > rowIndex)
2178 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
2179 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
2182 this.saveCopyFieldsBeforeDF(copy_id);
2183 this._copy_fields_for_acqdf.forEach(
2185 if(entry[field]()) {
2186 copyWidgets[field].attr('value', (entry[field]()));
2193 if (entries_applied) {
2194 this.virtDfaCounts[formula.id()] =
2195 ++(this.virtDfaCounts[formula.id()]) || 1;
2196 this._updateFormulaStore();
2197 this._drawDistribAppliedUnit(
2199 var dfa = new acqdfa();
2200 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
2203 this.dfeOffset += entries_applied;
2208 * This function updates the DF store for the dropdown so that use_counts
2209 * can reflect DF applications from this session before they're saved
2212 this._updateFormulaStore = function() {
2213 this.dfSelector.store = new dojo.data.ItemFileReadStore(
2215 "data": self._labelFormulasWithCounts(
2216 acqdf.toStoreData(self.distribForms)
2222 this.saveCopyFieldsBeforeDF = function(copy_id) {
2224 if (!this.oldCopyWidgetCache[copy_id]) {
2225 var copyWidgets = this.copyWidgetCache[copy_id];
2227 this.oldCopyWidgetCache[copy_id] = {};
2228 this._copy_fields_for_acqdf.forEach(
2230 self.oldCopyWidgetCache[copy_id][f] =
2231 copyWidgets[f].attr("value");
2237 this.restoreCopyFieldsBeforeDF = function() {
2239 for (var copy_id in this.oldCopyWidgetCache) {
2240 this._copy_fields_for_acqdf.forEach(
2242 self.copyWidgetCache[copy_id][f].attr(
2243 "value", self.oldCopyWidgetCache[copy_id][f]
2250 this._labelFormulasWithCounts = function(store_data) {
2251 for (var key in store_data.items) {
2252 var obj = store_data.items[key];
2253 obj.use_count = Number(obj.use_count); /* needed for sorting */
2255 if (this.virtDfaCounts[obj.id])
2256 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
2258 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
2259 obj.use_count + "]</span> " + obj.name;
2265 * This method formerly would not refetch the DF formulas if they'd been
2266 * loaded already, but now it always re-fetches, since use_count changes.
2268 /** TODO: port distrib-formula selector to autofieldwidget+pcrud/dojo store */
2269 this._fetchDistribFormulas = function(onload) {
2270 fieldmapper.standardRequest(
2272 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
2275 "params": [openils.User.authtoken, 0, 500],
2276 "oncomplete": function(r) {
2277 self.distribForms = openils.Util.readResponse(r);
2278 if(!self.distribForms || self.distribForms.length == 0) {
2279 self.distribForms = [];
2281 self._addDistribFormulaRow();
2288 this._drawBatchCopyWidgets = function() {
2289 var row = this.copyBatchRow;
2290 dojo.forEach(liDetailBatchFields,
2292 if(self.copyBatchRowDrawn) {
2293 self.copyBatchWidgets[field].attr('value', null);
2295 var args = self.afwCopyFieldArgs(field, "CREATE_PICKLIST");
2296 args.parentNode = dojo.query('[name='+field+']', row)[0];
2298 var widget = new openils.widget.AutoFieldWidget(args);
2301 if (field == "fund" && w.store)
2302 self._ensureCSSFundClasses(w.store);
2303 self.copyBatchWidgets[field] = w;
2306 if (field == "fund") {
2308 widget.widget, "onChange", function(val) {
2309 self._updateFundSelectorStyle(widget, val);
2316 this.copyBatchRowDrawn = true;
2319 this.batchCopyUpdate = function() {
2321 for(var k in this.copyWidgetCache) {
2322 var cache = this.copyWidgetCache[k];
2323 dojo.forEach(liDetailBatchFields, function(f) {
2324 var newval = self.copyBatchWidgets[f].attr('value');
2325 if(newval) cache[f].attr('value', newval);
2330 this._drawCopies = function(li) {
2333 // this button sets the total number of copies for a given lineitem
2334 acqLitAddCopyCount.onClick = function() {
2335 var count = acqLitCopyCountInput.attr('value');
2338 while(self.copyCount() < count)
2341 // delete rows if necessary
2342 var diff = self.copyCount() - count;
2344 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
2345 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
2346 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
2348 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2354 if(li.lineitem_details().length > 0) {
2355 dojo.forEach(li.lineitem_details(),
2357 self.addCopy(li, copy);
2365 this.copyCount = function() {
2367 for(var id in this.copyCache) {
2368 if(!this.copyCache[id].isdeleted())
2374 this.virtCopyId = -1;
2375 this.addCopy = function(li, copy) {
2376 var row = this.copyRow.cloneNode(true);
2377 this.copyTbody.appendChild(row);
2381 copy = new fieldmapper.acqlid();
2383 copy.id(this.virtCopyId--);
2384 copy.lineitem(li.id());
2387 this.copyCache[copy.id()] = copy;
2388 row.setAttribute('copy_id', copy.id());
2389 self.copyWidgetCache[copy.id()] = {};
2391 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2393 var rcvr = copy.receiver();
2395 if (!userCache[rcvr]) {
2396 if(rcvr == openils.User.user.id()) {
2397 userCache[rcvr] = openils.User.user;
2399 userCache[rcvr] = fieldmapper.standardRequest(
2400 ['open-ils.actor', 'open-ils.actor.user.retrieve'],
2401 {params: [openils.User.authtoken, rcvr]}
2405 dojo.query('[name=receiver]', row)[0].innerHTML = userCache[rcvr].usrname();
2408 dojo.forEach(liDetailFields,
2411 if (field == "fund") {
2412 searchFilter = (copy.fund() ?
2413 {"-or": {"active": "t", "id": copy.fund()}} :
2415 searchFilter.org = fundSearchFilter.org;
2417 searchFilter = null;
2420 var readOnly = false;
2422 // TODO: Add support for changing the owning_lib after real copies have been made.
2423 // owning_lib is order data as much as its item data
2424 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
2428 // TODO: add support for changing the fund after debits have been created
2429 // Note: invoicing allows the change
2430 if(copy.fund_debit() && field == 'fund') {
2435 var widget = new openils.widget.AutoFieldWidget({
2438 labelFormat : (field == 'fund') ? fundLabelFormat : null,
2439 searchFormat : (field == 'fund') ? fundSearchFormat : null,
2440 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
2441 searchFilter : searchFilter,
2442 noCache: (field == "fund"),
2444 parentNode : dojo.query('[name='+field+']', row)[0],
2445 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2446 readOnly : readOnly,
2447 orgDefaultsToWs : true
2451 // make sure we capture the value from any async widgets
2454 if (field == "fund" && w.store)
2455 self._ensureCSSFundClasses(w.store);
2458 copy[field](ww.getFormattedValue())
2460 self.copyWidgetCache[copy.id()][field] = w;
2462 dojo.connect(w, 'onChange',
2464 if (field == "fund")
2465 self._updateFundSelectorStyle(widget, val);
2467 if (!readOnly && (copy.isnew() || val != copy[field]())) {
2468 // prevent setting ischanged() automatically on widget load for existing copies
2469 copy[field](widget.getFormattedValue())
2470 copy.ischanged(true);
2479 this.updateLidState(copy, row);
2482 this._ensureCSSFundClass = function(id) {
2483 if (!this.fundStyleSheet) {
2485 "style", {"type": "text/css"},
2486 document.getElementsByTagName("head")[0], "last"
2488 this.fundStyleSheet = document.styleSheets[
2489 document.styleSheets.length - 1
2493 var cn = "fund_" + id;
2494 if (!this.haveFundClass[cn]) {
2495 fieldmapper.standardRequest(
2496 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
2498 "params": [openils.User.authtoken, id],
2500 "oncomplete": function(r) {
2501 r = openils.Util.readResponse(r);
2502 self.fundBalanceState[id] = r;
2504 if (r[0] /* stop */)
2505 style = fundStyles.stop;
2506 else if (r[1] /* warning */)
2507 style = fundStyles.warning;
2508 self.fundStyleSheet.insertRule(
2509 "." + cn + " { " + style + " }",
2510 self.fundStyleSheet.cssRules.length
2512 self.haveFundClass[cn] = true;
2519 this._ensureCSSFundClasses = function(store) {
2521 "query": {"id": "*"},
2522 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
2526 this._updateFundSelectorStyle = function(widget, fund_id) {
2527 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
2528 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
2531 this.updateLidState = function(copy, row) {
2534 if (typeof(row) == "undefined") {
2535 row = dojo.query('tr[copy_id="' + copy.id() + '"]', this.copyTbody)[0];
2539 var recv_link = nodeByName("receive", row);
2540 var unrecv_link = nodeByName("unreceive", row);
2541 var del_link = nodeByName("delete", row);
2542 var cxl_link = nodeByName("cancel", row);
2543 var claim_link = nodeByName("claim", row);
2544 var cxl_reason_link = nodeByName("cancel_reason", row);
2546 // by default, hide all the actions
2547 openils.Util.hide(del_link.parentNode);
2548 openils.Util.hide(recv_link);
2549 openils.Util.hide(unrecv_link);
2550 openils.Util.hide(cxl_link);
2551 openils.Util.hide(claim_link);
2552 openils.Util.hide(cxl_reason_link);
2554 if (copy.id() > 0) { // real copies (LIDs)
2556 if (copy.cancel_reason()) {
2558 /* --------- cancelled -------------------------- */
2560 /* XXX the following may leak memory in a long lived table:
2561 * dijits may not get destroyed... not positive. revisit. */
2562 var holds_reason = dojo.create(
2564 "style": "border-bottom: 1px dashed #000;",
2565 "innerHTML": copy.cancel_reason().label()
2566 }, cxl_reason_link, "only"
2570 "label": "<em>" + copy.cancel_reason().label() +
2571 "</em><br />" + copy.cancel_reason().description(),
2572 "connectId": [holds_reason]
2573 }, dojo.create("span", null, cxl_reason_link, "last")
2575 openils.Util.show(cxl_reason_link, "inline");
2577 if (copy.cancel_reason().keep_debits() == 't' ) {
2578 // allow further cancellation of "delayed" copies
2580 openils.Util.show(cxl_link, "inline");
2581 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2584 } else if (copy.recv_time()) {
2586 /* --------- received -------------------------- */
2588 openils.Util.show(unrecv_link, "inline");
2589 unrecv_link.onclick = function() {
2590 if (confirm(localeStrings.UNRECEIVE_LID))
2591 self.issueReceive(copy, /* rollback */ true);
2594 } else if (this.liCache[copy.lineitem()].state() == 'on-order') {
2596 /* --------- on order -------------------------- */
2598 openils.Util.show(recv_link, 'inline');
2599 openils.Util.show(cxl_link, "inline");
2601 recv_link.onclick = function() {
2602 if (self.checkLiAlerts(copy.lineitem()))
2603 self.issueReceive(copy);
2606 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2610 /* --------- pre-order copies -------------------------- */
2612 del_link.onclick = function() { self.deleteCopy(row) };
2613 openils.Util.show(del_link.parentNode);
2619 /* --------- virtual copies -------------------------- */
2621 del_link.onclick = function() { self.deleteCopy(row) };
2622 openils.Util.show(del_link.parentNode);
2626 this.cancelLid = function(lid_id) {
2627 lidCancelDialog._lid_id = lid_id;
2628 openils.Util.show(lidCancelDialog.domNode.parentNode);
2629 lidCancelDialog.show();
2630 if (!lidCancelDialog._prepared) {
2631 var widget = new openils.widget.AutoFieldWidget({
2632 "fmField": "cancel_reason",
2633 "fmClass": "acqlid",
2634 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
2635 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2637 "searchOptions" : {order_by : {"acqcr":"label"}}
2641 acqLidCancelButton.onClick = function() {
2642 if (w.attr("value")) {
2643 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
2645 lidCancelDialog._lid_id,
2649 lidCancelDialog.hide();
2652 lidCancelDialog._prepared = true;
2658 this._cancelLid = function(lid_id, reason) {
2659 fieldmapper.standardRequest(
2660 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
2661 "params": [openils.User.authtoken, lid_id, reason],
2663 "onresponse": function(r) {
2664 if (r = openils.Util.readResponse(r)) {
2666 for (var id in r.lid) {
2667 /* actually this should only iterate once */
2668 self.copyCache[id].cancel_reason(
2669 r.lid[id].cancel_reason
2671 self.updateLidState(self.copyCache[id]);
2672 if (r.li_update_needed) {
2673 location.href = location.href; // sledgehammer
2683 this._confirmAlert = function(li, lin) {
2685 dojo.string.substitute(
2686 localeStrings.CONFIRM_LI_ALERT, [
2687 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2688 "title", "lineitem_marc_attr_definition"
2690 /* XXX it's really better add a parameter and to adjust
2691 * the format string rather than do this concatenation
2692 * here, but if someone wants this for 2.2 in a hurry,
2693 * we can sidestep the problem of updating the strings
2694 * while the translators are working. */
2696 aou.findOrgUnit(lin.alert_text().owning_lib()).shortname() +
2698 lin.alert_text().code()
2700 lin.alert_text().description() || "",
2707 this.checkLiAlerts = function(li_id) {
2708 var li = this.liCache[li_id];
2710 var alert_notes = li.lineitem_notes().filter(
2711 function(o) { return Boolean(o.alert_text()); }
2714 /* this is _intentionally_ not done in a call to forEach() ... */
2715 for (var i = 0; i < alert_notes.length; i++) {
2716 if (this.noteAcks[alert_notes[i].id()])
2718 else if (!this._confirmAlert(li, alert_notes[i]))
2721 this.noteAcks[alert_notes[i].id()] = true;
2727 this.deleteCopy = function(row) {
2728 var copy = this.copyCache[row.getAttribute('copy_id')];
2729 copy.isdeleted(true);
2731 delete this.copyCache[copy.id()];
2732 this.copyTbody.removeChild(row);
2735 this._virtDfaCountsAsList = function() {
2737 for (var key in this.virtDfaCounts) {
2738 for (var i = 0; i < this.virtDfaCounts[key]; i++)
2744 this.confirmBreachedCopyFunds = function(copies) {
2745 var stop = 0, warning = 0;
2749 var state = self.fundBalanceState[o.fund()];
2750 if (state[0] /* stop */)
2752 else if (state[1] /* warning */)
2759 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
2760 } else if (warning) {
2761 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
2766 this.saveCopyChanges = function(liId) {
2772 for(var id in this.copyCache) {
2773 var c = this.copyCache[id];
2774 if(!c.isdeleted()) total++;
2775 if(c.isnew() || c.ischanged() || c.isdeleted()) {
2776 if(c.id() < 0) c.id(null);
2782 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
2785 if (copies.length > 0) {
2786 if (!this.confirmBreachedCopyFunds(copies))
2789 if (typeof(this._copy_count_cb) == "function")
2790 this._copy_count_cb(liId, total);
2792 openils.Util.show("acq-lit-update-copies-progress");
2793 fieldmapper.standardRequest(
2794 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
2796 params: [openils.User.authtoken, copies],
2797 onresponse: function(r) {
2798 var res = openils.Util.readResponse(r);
2799 litUpdateCopiesProgress.update(res);
2801 oncomplete: function() {
2802 self.drawCopies(liId, true /* force_fetch */);
2803 openils.Util.hide("acq-lit-update-copies-progress");
2804 refreshPOSummaryAmounts();
2810 var dfa_list = this._virtDfaCountsAsList();
2811 if (dfa_list.length > 0) {
2812 fieldmapper.standardRequest(
2814 "open-ils.acq.distribution_formula.record_application"],
2817 "params": [openils.User.authtoken, dfa_list, liId],
2818 "onresponse": function(r) {
2819 var res = openils.Util.readResponse(r);
2820 if (res && res.length < dfa_list.length)
2821 alert(localeStrings.DFA_NOT_ALL);
2825 this.virtDfaCounts = {};
2828 if (this.inlineCopiesNeedingRefresh.indexOf(liId) < 0)
2829 this.inlineCopiesNeedingRefresh.push(liId);
2832 this._updateCreatePoPrepayCheckbox = function(prepay) {
2833 var prepay = openils.Util.isTrue(prepay);
2834 this._prepayRequiredByVendor = prepay;
2835 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
2838 this._confirmPoPrepaySituation = function() {
2839 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
2840 if (want_prepay != this._prepayRequiredByVendor) {
2843 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
2844 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
2851 this.applySelectedLiAction = function(action) {
2855 case 'delete_selected':
2856 this._deleteLiList(self.getSelected());
2859 case 'add_to_order':
2860 addToPoDialog._get_li = dojo.hitch(
2863 return this.getSelected(
2864 false, null, true, li_pre_po_states);
2867 if (addToPoDialog._get_li().length == 0) {
2868 alert(localeStrings.NO_LI_GENERAL);
2871 addToPoDialog.show();
2874 case 'create_order':
2875 this._loadPOSelect();
2876 acqLitPoCreateDialog.show();
2879 case 'save_picklist':
2880 acqLitSavePlDialog.show();
2883 case 'selector_ready':
2885 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
2886 acqLitChangeLiStateDialog.show();
2894 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
2897 case 'batch_create_invoice':
2898 this.batchCreateInvoice();
2901 case 'batch_link_invoice':
2902 this.batchLinkInvoice();
2905 case 'receive_lineitems':
2906 this.receiveSelectedLineitems();
2909 case 'rollback_receive_lineitems':
2910 this.rollbackReceiveLineitems();
2913 case 'create_assets':
2914 this.showAssetCreator();
2917 case 'export_attr_list':
2918 this.chooseExportAttr();
2921 case 'batch_apply_funds':
2922 this.applyBatchLiFunds();
2925 case 'add_brief_record':
2927 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
2929 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
2933 case "cancel_lineitems":
2934 console.log('HERE');
2935 this.maybeCancelLineitems();
2938 case "apply_claim_policy":
2939 var li_list = this.getSelected();
2940 this.claimPolicyPicker.attr("value", null);
2941 liClaimPolicyDialog.show();
2942 liClaimPolicySave.onClick = function() {
2943 self.changeClaimPolicy(
2945 self.claimPolicyPicker.attr("value"),
2949 self.setClaimPolicyControl(li);
2950 self.reconsiderClaimControl(li);
2953 liClaimPolicyDialog.hide();
2961 this.changeClaimPolicy = function(li_list, value, callback) {
2963 function(li) { li.claim_policy(value); }
2965 fieldmapper.standardRequest(
2966 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
2967 "params": [openils.User.authtoken, li_list],
2969 "oncomplete": function(r) {
2970 r = openils.Util.readResponse(r);
2971 if (callback) callback(r);
2977 this.showAssetCreator = function(onAssetsCreated) {
2978 if(!this.isPO) return;
2981 // first, let's see if this PO has any LI's that need to be merged/imported
2982 self.pcrud.search('jub', {purchase_order : this.isPO, eg_bib_id : null}, {
2984 oncomplete : function(r) {
2985 var resp = openils.Util.readResponse(r);
2986 if (resp && resp.length) {
2987 // PO has some non-linked jubs.
2989 self.show('asset-creator');
2990 if(!self.vlAgent.loaded)
2991 self.vlAgent.init();
2993 dojo.connect(assetCreatorButton, 'onClick',
2994 function() { self.createAssets(onAssetsCreated) });
2998 // all jubs linked, move on to asset creation
2999 self.createAssets(onAssetsCreated, true);
3005 this.createAssets = function(onAssetsCreated, noVl) {
3006 this.show('acq-lit-progress-numbers');
3008 var vlArgs = (noVl) ? {} : {vandelay : this.vlAgent.values()};
3009 this.batchProgress = {};
3010 progressDialog.show(false);
3011 progressDialog.attr("title", localeStrings.LI_CREATING_ASSETS);
3012 fieldmapper.standardRequest(
3013 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
3015 params: [this.authtoken, this.isPO, vlArgs],
3016 onresponse: function(r) {
3017 var resp = openils.Util.readResponse(r);
3018 self._updateProgressNumbers(resp, !Boolean(onAssetsCreated), onAssetsCreated, true);
3024 this.maybeCancelLineitems = function() {
3025 openils.Util.show("acq-lit-cancel-reason", "inline");
3026 if (!acqLitCancelLineitemsButton._prepared) {
3027 var widget = new openils.widget.AutoFieldWidget({
3028 "fmField": "cancel_reason",
3030 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
3031 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3033 "searchOptions" : {order_by : {"acqcr":"label"}}
3037 acqLitCancelLineitemsButton.onClick = function() {
3038 if (w.attr("value")) {
3039 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
3040 self._cancelLineitems(w.attr("value"));
3042 openils.Util.hide("acq-lit-cancel-reason");
3045 acqLitCancelLineitemsButton._prepared = true;
3051 this._cancelLineitems = function(reason) {
3053 var li_list = this.getSelected();
3055 // canceled lineitems may be canceled again if they were
3056 // previously delayed (keep_debits = true).
3057 li_list = li_list.filter(
3060 li.state() != 'cancelled' ||
3061 li.cancel_reason().keep_debits() == 't'
3066 id_list = li_list.map(function(l) {return l.id()});
3068 if (!id_list.length) {
3069 alert(localeStrings.NO_LI_GENERAL);
3072 fieldmapper.standardRequest(
3073 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
3074 "params": [openils.User.authtoken, id_list, reason],
3076 "onresponse": function(r) {
3077 if (r = openils.Util.readResponse(r)) {
3079 for (var id in r.li) {
3080 self.liCache[id].state(r.li[id].state);
3081 self.liCache[id].cancel_reason(
3082 r.li[id].cancel_reason
3084 self.updateLiState(self.liCache[id]);
3087 if (r.lid && self.copyCache) {
3088 for (var id in r.lid) {
3089 if (self.copyCache[id]) {
3090 self.copyCache[id].cancel_reason(
3091 r.lid[id].cancel_reason
3093 self.updateLidState(self.copyCache[id]);
3103 this.chooseExportAttr = function() {
3104 if (!acqLitExportAttrSelector._li_setup) {
3106 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
3108 "data": acqlimad.toStoreData(
3110 "acqlimad", {"code": li_exportable_attrs}
3115 acqLitExportAttrSelector.setValue();
3116 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
3117 acqLitExportAttrSelector._li_setup = true;
3119 openils.Util.show("acq-lit-export-attr-holder", "inline");
3122 this.exportAttrList = function() {
3123 var attr_def = acqLitExportAttrSelector.item;
3124 var li_list = this.getSelected();
3125 var value_list = li_list.map(
3127 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
3128 attr_def.code, "lineitem_marc_attr_definition"
3131 ).filter(function(attr) { return Boolean(attr); });
3133 if (value_list.length > 0) {
3134 if (value_list.length < li_list.length) {
3136 dojo.string.substitute(
3137 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
3144 if (window.IAMBROWSER) {
3145 var blob = new Blob(value_list, {type: "text/plain;charset=utf-8"});
3146 saveAs(blob, "export_attr_list.txt");
3148 openils.XUL.contentToFileSaveDialog(
3149 value_list.join("\n"),
3150 localeStrings.EXPORT_SAVE_DIALOG_TITLE
3157 alert(dojo.string.substitute(
3158 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
3162 openils.Util.hide("acq-lit-export-attr-holder");
3165 this.printPO = function() {
3166 if(!this.isPO) return;
3167 progressDialog.show(true);
3168 fieldmapper.standardRequest(
3169 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
3171 params: [this.authtoken, this.isPO, 'html'],
3172 oncomplete: function(r) {
3173 progressDialog.hide();
3174 var evt = openils.Util.readResponse(r);
3175 if(evt && evt.template_output()) {
3176 openils.Util.printHtmlString(evt.template_output().data());
3183 this.batchCreateInvoice = function() {
3184 var liIds = this.getSelected(
3185 false, null, true /* id_list */, li_active_states)
3186 if (!liIds.length) {
3187 alert(localeStrings.NO_LI_GENERAL);
3190 var path = oilsBasePath + '/acq/invoice/view?create=1';
3191 dojo.forEach(liIds, function(li, idx) { path += '&attach_li=' + li });
3192 if (openils.XUL.isXUL() && !window.IAMBROWSER)
3193 openils.XUL.newTabEasy(path, localeStrings.NEW_INVOICE, null, true);
3195 location.href = path;
3198 this.batchLinkInvoice = function(create) {
3199 var liIds = this.getSelected(
3200 false, null, true /* id_list */, li_active_states)
3201 if (!liIds.length) {
3202 alert(localeStrings.NO_LI_GENERAL);
3205 if (!self.invoiceLinkDialogManager) {
3206 self.invoiceLinkDialogManager =
3207 new InvoiceLinkDialogManager("li");
3209 self.invoiceLinkDialogManager.target = liIds;
3210 acqLitLinkInvoiceDialog.show();
3213 this.receiveSelectedLineitems = function() {
3214 var states = li_post_po_states.filter(
3215 function(s) { return s != 'received' });
3216 var li_list = this.getSelected(null, null, null, states);
3218 if (!li_list.length) {
3219 alert(localeStrings.NO_LI_GENERAL);
3223 for (var i = 0; i < li_list.length; i++) {
3224 var li = li_list[i];
3226 if (li.state() != "received" &&
3227 !this.checkLiAlerts(li.id())) return;
3230 this.show('acq-lit-progress-numbers');
3233 fieldmapper.standardRequest(
3234 ['open-ils.acq', 'open-ils.acq.lineitem.receive.batch'],
3238 li_list.map(function(li) { return li.id(); })
3240 onresponse : function(r) {
3241 var resp = openils.Util.readResponse(r);
3242 self._updateProgressNumbers(resp, true);
3248 this.issueReceive = function(obj, rollback) {
3250 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
3252 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
3254 progressDialog.show(true);
3255 fieldmapper.standardRequest(
3256 ["open-ils.acq", method], {
3258 "params": [this.authtoken, obj.id()],
3259 "onresponse": function(r) {
3260 if (r = openils.Util.readResponse(r)) {
3261 self.fetchClaimInfo(
3262 part == "lineitem" ? obj.id() : obj.lineitem(),
3264 function() { self.handleReceive(r); }
3266 progressDialog.hide();
3274 * Handles the responses from receive and rollback ML calls.
3276 this.handleReceive = function(resp) {
3279 for (var li_id in resp.li) {
3280 for (var key in resp.li[li_id])
3281 self.liCache[li_id][key](resp.li[li_id][key]);
3282 self.updateLiState(self.liCache[li_id]);
3286 if (typeof(self.poUpdateCallback) == "function")
3287 self.poUpdateCallback(resp.po);
3290 for (var lid_id in resp.lid) {
3291 for (var key in resp.lid[lid_id])
3292 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
3293 self.updateLidState(self.copyCache[lid_id]);
3299 this.rollbackReceiveLineitems = function() {
3300 var li_id_list = this.getSelected(false, null, true);
3301 if (!li_id_list.length) {
3302 alert(localeStrings.NO_LI_GENERAL);
3306 if (!confirm(localeStrings.ROLLBACK_LI_RECEIVE_CONFIRM)) return;
3308 this.show('acq-lit-progress-numbers');
3311 fieldmapper.standardRequest(
3312 ['open-ils.acq', 'open-ils.acq.lineitem.receive.rollback.batch'],
3314 params: [this.authtoken, li_id_list],
3315 onresponse : function(r) {
3316 var resp = openils.Util.readResponse(r);
3317 self._updateProgressNumbers(resp, true);
3323 this._updateProgressNumbers = function(resp, reloadOnComplete, onComplete, clearProgressDialog) {
3324 this._updateProgressDialog(resp);
3325 this.vlAgent.handleResponse(resp,
3326 function(resp, res) {
3327 if (clearProgressDialog) {
3328 progressDialog.update({ "progress": 100});
3329 progressDialog.update_message();
3330 progressDialog.hide();
3331 progressDialog.attr("title", "");
3333 if(reloadOnComplete)
3334 location.href = location.href;
3336 onComplete(resp, res);
3341 this._updateProgressDialog = function(resp) {
3342 progressDialog.update({ "progress": (resp.progress / resp.total) * 100 });
3343 var keys = ['li', 'vqbr', 'bibs', 'lid', 'debits_accrued', 'copies'];
3344 for (var i = 0; i < keys.length; i++) {
3345 if (resp[keys[i]] > (this.batchProgress[keys[i]] || 0)) {
3346 progressDialog.update_message(
3347 dojo.string.substitute(
3348 localeStrings["ACTIVATE_" + keys[i].toUpperCase() + "_PROCESSED"],
3354 this.batchProgress = resp;
3357 this._createPO = function(fields) {
3358 var wantall = (fields.create_from == "all");
3360 /* If we're a picklist or purchase order already and the user wants
3361 * all lineitems, we might have pages' worth of lineitems haven't all
3362 * been loaded yet, so getSelected() won't find them. The server,
3363 * however, should know about all our lineitems, so let's ask the
3364 * server for a complete list.
3369 true, function(list) {
3370 self._createPOFromLineitems(fields, list);
3371 }, /* id_list */ true, li_pre_po_states
3374 this._createPOFromLineitems(
3375 fields, this.getSelected(
3376 false, null, true /* id_list */, li_pre_po_states)
3381 this._createPOFromLineitems = function(fields, selected) {
3382 if (selected.length == 0) {
3383 alert(localeStrings.NO_LI_GENERAL);
3388 var po = new fieldmapper.acqpo();
3389 po.provider(this.createPoProviderSelector.attr("value"));
3390 po.ordering_agency(this.createPoAgencySelector.attr("value"));
3391 po.prepayment_required(fields.prepayment_required[0] ? true : false);
3392 var name = this.createPoNameInput.attr('value');
3393 if (name) po.name(name); // avoid name=""
3395 // if we're creating assets, delay the asset creation
3396 // until after the PO is created. This will allow us to
3397 // use showAssetCreator() directly.
3399 fieldmapper.standardRequest(
3400 ["open-ils.acq", "open-ils.acq.purchase_order.create"],
3403 openils.User.authtoken,
3404 po, {lineitems : selected}
3406 onresponse : function(r) {
3407 var resp = openils.Util.readResponse(r);
3408 if (resp.complete) {
3409 // self.isPO is needed for showAssetCreator();
3410 self.isPO = resp.purchase_order.id();
3411 var redir = oilsBasePath + "/acq/po/view/" + self.isPO;
3412 if (fields.create_assets[0]) {
3413 self.showAssetCreator(
3414 function() {location.href = redir}
3417 location.href = redir;
3426 this.batchFundWidget = null;
3428 this.applyBatchLiFunds = function() {
3430 var liIds = this.getSelected().map(function(li) { return li.id(); });
3431 if(liIds.length == 0) return; // warn?
3434 batchFundUpdateDialog.show();
3436 if(!this.batchFundWidget) {
3437 this.batchFundWidget = new openils.widget.AutoFieldWidget({
3439 selfReference : true,
3440 labelFormat : fundLabelFormat,
3441 searchFormat : fundSearchFormat,
3442 searchFilter : fundSearchFilter,
3443 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
3444 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
3445 dijitArgs : { "required": true, "labelType": "html" },
3448 this.batchFundWidget.build();
3451 dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
3452 dojo.connect(batchFundUpdateSubmit, 'onClick',
3455 // TODO: call .dry_run first to test thresholds
3456 fieldmapper.standardRequest(
3457 ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
3460 openils.User.authtoken,
3462 self.batchFundWidget.widget.attr('value')
3464 oncomplete : function(r) {
3465 var resp = openils.Util.readResponse(r);
3467 location.href = location.href;
3476 this._deleteLiList = function(list, idx) {
3477 if(idx == null) idx = 0;
3478 if(idx >= list.length) return;
3483 if (this.isPO && (li.state() == "on-order" || li.state() == "received")) {
3484 /* It makes little sense to delete a lineitem from a PO that has
3485 * already been marked 'on-order'. Especially if EDI is in use,
3486 * such a purchase order will probably have already been shipped
3487 * off to a vendor, and mucking with it at this point could leave
3488 * your data in a bad state that doesn't jive with reality.
3490 * I could see making this restriction even firmer.
3492 * I could also see adjusting the li state comparisons, extending
3493 * the comparison to the PO's state, and/or providing functions
3494 * that house the logic for comparing states in a single location.
3496 * Yes, this will be really annoying if you have selected a lot
3497 * of lineitems to cancel that have been ordered. You'll get a
3498 * confirm dialog for each one.
3501 if (!confirm(localeStrings.DEL_LI_FROM_PO)) {
3502 self._deleteLiList(list, ++idx); /* move on to next in list */
3507 fieldmapper.standardRequest(
3509 this.isPO ? 'open-ils.acq.purchase_order.lineitem.delete' : 'open-ils.acq.picklist.lineitem.delete'],
3511 params: [openils.User.authtoken, liId],
3512 oncomplete: function(r) {
3513 self.removeLineitem(liId);
3514 self._deleteLiList(list, ++idx);
3520 this.editOrderMarc = function(li) {
3523 if(window.IAMBROWSER) {
3524 xulG.edit_marc_order_record(li, function(li) { self.drawInfo(li.id()) });
3528 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
3529 to true in about:config */
3530 if(openils.XUL.isXUL()) {
3531 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul','','chrome');
3533 win = window.open('/xul/server/cat/marcedit.xul','','chrome');
3536 record : {marc : li.marc(), "rtype": "bre"},
3538 label: 'Save Record', // XXX I18N
3539 func: function(xmlString) {
3541 fieldmapper.standardRequest(
3542 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
3544 params: [openils.User.authtoken, li],
3545 oncomplete: function(r) {
3546 openils.Util.readResponse(r);
3548 self.drawInfo(li.id())
3554 'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
3555 'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
3559 this._savePl = function(values) {
3561 (values.which == 'all'),
3562 function(list) { self._savePlFromLineitems(values, list); }
3566 this._savePlFromLineitems = function(values, selected) {
3567 openils.Util.show("acq-lit-generic-progress");
3569 if(values.new_name) {
3570 openils.acq.Picklist.create(
3571 {name: values.new_name},
3577 oilsBasePath + "/acq/picklist/view/" + id;
3582 } else if(values.existing_pl) {
3583 // update lineitems to use an existing picklist
3585 values.existing_pl, selected, 0,
3588 oilsBasePath + "/acq/picklist/view/" +
3595 this._updateLiState = function(values, state, state_filter) {
3596 progressDialog.show(true);
3598 (values.which == 'all'),
3600 self._updateLiStateFromLineitems(values, state, list);
3601 }, false /* id_list */, state_filter
3605 this._updateLiStateFromLineitems = function(values, state, selected) {
3606 if(!selected.length) {
3607 try { progressDialog.hide() } catch(E) {};
3608 alert(localeStrings.NO_LI_GENERAL);
3611 dojo.forEach(selected, function(li) {li.state(state);});
3612 self._updateLiList(null, selected, 0,
3613 // TODO consider inline updates for efficiency
3614 function() { location.href = location.href }
3618 this._updateLiList = function(pl, list, idx, oncomplete) {
3619 if(idx >= list.length) return oncomplete();
3621 if(pl != null) li.picklist(pl);
3622 litGenericProgress.update({maximum: list.length, progress: idx});
3623 new openils.acq.Lineitem({lineitem:li}).update(
3625 self._updateLiList(pl, list, ++idx, oncomplete);
3630 this._loadPOSelect = function() {
3631 if (!this.createPoProviderSelector) {
3632 var widget = new openils.widget.AutoFieldWidget({
3633 "fmField": "provider",
3635 "searchFilter": {"active": "t"},
3636 "parentNode": dojo.byId("acq-lit-po-provider"),
3638 "onChange": function() {
3640 self._updateCreatePoPrepayCheckbox(
3641 this.item.prepayment_required()
3647 widget.build(function(w) { self.createPoProviderSelector = w; });
3650 this.createPoCheckDupes = function() {
3651 var org = self.createPoAgencySelector.attr('value');
3652 var name = self.createPoNameInput.attr('value');
3653 openils.Util.hide('acq-dupe-po-name');
3656 acqLitCreatePoSubmit.attr('disabled', false);
3660 acqLitCreatePoSubmit.attr('disabled', true);
3661 var orgs = fieldmapper.aou.descendantNodeList(org, true);
3662 new openils.PermaCrud().search('acqpo',
3663 {name : name, ordering_agency : orgs},
3664 {async : true, oncomplete : function(r) {
3665 var po = openils.Util.readResponse(r);
3667 if (po && (po = po[0])) {
3669 var link = dojo.byId('acq-dupe-po-link');
3670 openils.Util.show('acq-dupe-po-name', 'table-row');
3671 var dupe_path = '/acq/po/view/' + po.id();
3675 if (window.IAMBROWSER) {
3676 // TODO: integration
3680 link.onclick = function() {
3682 var loc = xulG.url_prefix('XUL_BROWSER?url=') +
3683 window.encodeURIComponent(
3684 xulG.url_prefix('EG_WEB_BASE' + dupe_path)
3688 {tab_name: '', browser:false},
3691 show_nav_buttons : true,
3692 show_print_button : true,
3699 link.onclick = function() {
3700 window.open(oilsBasePath + dupe_path, '_blank').focus();
3705 acqLitCreatePoSubmit.attr('disabled', false);
3711 if (!this.createPoAgencySelector) {
3712 var widget = new openils.widget.AutoFieldWidget({
3713 "fmField": "ordering_agency",
3715 "parentNode": dojo.byId("acq-lit-po-agency"),
3716 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3718 widget.build(function(w) {
3719 self.createPoAgencySelector = w;
3720 dojo.connect(w, 'onChange', self.createPoCheckDupes);
3724 if (!this.createPoNameInput) {
3725 var widget = new openils.widget.AutoFieldWidget({
3728 "parentNode": dojo.byId("acq-lit-po-name"),
3729 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3731 widget.build(function(w) {
3732 self.createPoNameInput = w;
3733 dojo.connect(w, 'onChange', self.createPoCheckDupes);
3738 this.showRealCopyEditUI = function(li) {
3743 this._fetchLineitem(li.id(),
3745 li = self.liCache[li.id()] = fullLi;
3749 id : li.lineitem_details().map(
3750 function(item) { return item.eg_copy_id() }
3754 oncomplete : function(r) {
3756 var r_list = openils.Util.readResponse( r );
3757 for (var i = 0; i < r_list.length; i++) {
3758 var copy = r_list[i];
3759 var volId = copy.call_number();
3760 var volume = self.volCache[volId];
3762 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
3764 copy.call_number(volume);
3765 copyList.push(copy);
3768 xulG.volume_item_creator( { 'existing_copies' : copyList } );
3771 alert('error in oncomplete: ' + E);
3780 this.drawBibFinder = function(li) {
3783 var liWrapper = new openils.acq.Lineitem({lineitem:li});
3786 ['isbn', 'upc', 'issn', 'title', 'author'],
3788 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
3790 if(field == 'title' || field == 'author') {
3791 query += field +':' + val + ' ';
3793 query += 'identifier|' + field + ':' + val + ' ';
3799 if(openils.XUL.isXUL() && !window.IAMBROWSER) {
3801 oilsBasePath + '/acq/lineitem/findbib?query=' + encodeURIComponent(query),
3802 '', 'resizable,scrollbars=1,chrome');
3804 win = window.open( oilsBasePath + '/acq/lineitem/findbib?query=' + encodeURIComponent(query));
3808 win.window.recordFound = function(bibId) {
3811 var attrs = li.attributes();
3812 li.attributes(null);
3813 li.eg_bib_id(bibId);
3815 fieldmapper.standardRequest(
3816 ["open-ils.acq", "open-ils.acq.lineitem.update"],
3818 "params": [openils.User.authtoken, li],
3820 "oncomplete": function(r) {
3821 if(openils.Util.readResponse(r)) {
3822 location.href = location.href;