1 dojo.require('dojo.date.locale');
2 dojo.require('dojo.date.stamp');
3 dojo.require('dijit.form.Button');
4 dojo.require('dijit.form.TextBox');
5 dojo.require('dijit.form.FilteringSelect');
6 dojo.require('dijit.form.Textarea');
7 dojo.require('dijit.Tooltip');
8 dojo.require('dijit.ProgressBar');
9 dojo.require('dojox.timing.doLater');
10 dojo.require('openils.acq.Lineitem');
11 dojo.require('openils.acq.PO');
12 dojo.require('openils.acq.Picklist');
13 dojo.require('openils.widget.AutoFieldWidget');
14 dojo.require('dojo.data.ItemFileReadStore');
15 dojo.require('openils.widget.ProgressDialog');
16 dojo.require('openils.PermaCrud');
17 dojo.require("openils.widget.PCrudAutocompleteBox");
18 dojo.require('dijit.form.ComboBox');
19 dojo.require('openils.CGI');
21 if (!localeStrings) { /* we can do this because javascript doesn't have block scope */
22 dojo.requireLocalization('openils.acq', 'acq');
23 var localeStrings = dojo.i18n.getLocalization('openils.acq', 'acq');
25 const XUL_OPAC_WRAPPER = 'chrome://open_ils_staff_client/content/cat/opac.xul';
26 var li_exportable_attrs = ["issn", "isbn", "upc"];
28 var fundLabelFormat = [
29 '<span class="fund_${0}">${1} (${2})</span>', 'id', 'code', 'year'
31 var fundSearchFormat = ['${0} (${1})', 'code', 'year'];
32 var fundSearchFilter = {active : 't'};
33 var fundSort = {order_by : {"acqf":"year DESC, code"}};
35 function nodeByName(name, context) {
36 return dojo.query('[name='+name+']', context)[0];
39 // for caching linked users. e.g. lineitem_detail.receiver
42 var liDetailBatchFields = ['fund', 'owning_lib', 'location', 'collection_code', 'circ_modifier', 'cn_label'];
43 var liDetailFields = liDetailBatchFields.concat(['barcode', 'note']);
45 "stop": "color: #c00; font-weight: bold;",
46 "warning": "color: #c93;"
50 * We're not using 'approved' today, but there is API support for it.
51 * I believe it's been replaced by "order-ready".
52 * LIs go new => selector-ready => order-ready/approved => pending-order =>
53 * on-order => received. 'cancelled' can pop up anywhere.
56 var li_pre_po_states = ["new", "selector-ready", "order-ready", "approved"];
57 var li_post_po_states = ["pending-order", "on-order", "received", "cancelled"];
58 var li_active_states = li_pre_po_states.concat(li_post_po_states);
60 function AcqLiTable() {
67 this.haveFundClass = {}
68 this.fundBalanceState = {};
69 this.realDfaCache = {};
70 this.virtDfaCounts = {};
73 this.claimEligibleLidByLi = {};
74 this.claimEligibleLid = {};
75 this.toggleState = false;
76 this.tbody = dojo.byId('acq-lit-tbody');
79 this.authtoken = openils.User.authtoken;
80 this.pcrud = new openils.PermaCrud();
81 this.rowTemplate = this.tbody.removeChild(dojo.byId('acq-lit-row'));
82 this.copyTbody = dojo.byId('acq-lit-li-details-tbody');
83 this.copyRow = this.copyTbody.removeChild(dojo.byId('acq-lit-li-details-row'));
84 this.copyBatchRow = dojo.byId('acq-lit-li-details-batch-row');
85 this.copyBatchWidgets = {};
86 this.liNotesTbody = dojo.byId('acq-lit-notes-tbody');
87 this.liNotesRow = this.liNotesTbody.removeChild(dojo.byId('acq-lit-notes-row'));
88 this.realCopiesTbody = dojo.byId('acq-lit-real-copies-tbody');
89 this.realCopiesRow = this.realCopiesTbody.removeChild(dojo.byId('acq-lit-real-copies-row'));
90 this._copy_fields_for_acqdf = ['owning_lib', 'location', 'fund', 'circ_modifier', 'collection_code'];
91 this.skipInitialEligibilityCheck = false;
92 this.claimDialog = new ClaimDialogManager(
93 liClaimDialog, finalClaimDialog, this.claimEligibleLidByLi,
94 function(li) { /* callback that fires when claims are made */
95 self.fetchClaimInfo(li.id(), /* force update */ true);
98 this.vlAgent = new VLAgent();
99 this.batchProgress = {};
101 if (dojo.byId('acq-lit-apply-idents')) {
102 dojo.byId('acq-lit-apply-idents').onclick = function() {
103 self.applyOrderIdentValues();
107 this.focusLineitem = new openils.CGI().param('focus_li');
109 // capture the inline copy display wrapper and row template
110 this.inlineCopyContainer =
111 this.tbody.removeChild(dojo.byId('acq-inline-copies-row'));
113 '[name=acq-li-inline-copies-tbody]', this.inlineCopyContainer)[0];
114 this.inlineCopyTemplate = tb.removeChild(
115 dojo.query('[name=acq-li-inline-copies-template]', tb)[0]);
116 this.inlineNoCopies = tb.removeChild(
117 dojo.query('[name=acq-li-inline-copies-none]', tb)[0]);
119 // list of LI IDs that should be refreshed at next display time
120 this.inlineCopiesNeedingRefresh = [];
122 dojo.byId("acq-lit-li-actions-selector").onchange = function() {
123 self.applySelectedLiAction(this.options[this.selectedIndex].value);
124 this.selectedIndex = 0;
127 acqLitCreatePoCancel.onClick = function() {
128 acqLitPoCreateDialog.hide();
130 acqLitCreatePoSubmit.onClick = function() {
131 if (!self.createPoProviderSelector.attr("value") ||
132 !self.createPoAgencySelector.attr("value")) {
133 alert(localeStrings.CREATE_PO_INVALID);
135 } else if (self._confirmPoPrepaySituation()) {
136 acqLitPoCreateDialog.hide();
137 self._createPO(acqLitPoCreateDialog.getValues());
143 acqLitSavePlButton.onClick = function() {
144 acqLitSavePlDialog.hide();
145 self._savePl(acqLitSavePlDialog.getValues());
148 acqLitCancelLiStateButton.onClick = function() {
149 acqLitChangeLiStateDialog.hide();
151 acqLitSaveLiStateButton.onClick = function() {
152 acqLitChangeLiStateDialog.hide();
153 var state = acqLitChangeLiStateDialog.attr('state');
154 var state_filter = ['new'];
155 if (state == 'order-ready')
156 state_filter.push('selector-ready');
158 acqLitChangeLiStateDialog.getValues(), state, state_filter);
162 dojo.byId('acq-lit-select-toggle').onclick = function(){self.toggleSelect()};
163 dojo.byId('acq-inline-copies-toggle').onclick = function(){self.toggleInlineCopies()};
164 dojo.byId('acq-lit-info-back-button').onclick = function(){self.show('list')};
165 dojo.byId('acq-lit-copies-back-button').onclick = function(){self.show('list')};
166 dojo.byId('acq-lit-notes-back-button').onclick = function(){self.show('list')};
167 dojo.byId('acq-lit-real-copies-back-button').onclick = function(){self.show('list')};
169 this.setFundSearchFilter = function(callback) {
170 new openils.User().getPermOrgList(
171 ['CREATE_PURCHASE_ORDER', 'MANAGE_FUND'],
173 fundSearchFilter.org = orgs;
174 if (callback) callback();
176 true, true // descendants, id_list
180 this.afwCopyFieldArgs = function(field, perms) {
184 "labelFormat": (field == 'fund') ? fundLabelFormat : null,
185 "searchFormat": (field == 'fund') ? fundSearchFormat : null,
186 "searchFilter": (field == 'fund') ? fundSearchFilter : null,
187 "searchOptions": (field == 'fund') ? fundSort : null,
188 "orgLimitPerms": (field == 'location') ? ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'] : [perms],
191 "labelType": (field == "fund") ? "html" : null
193 "noCache": (field == "fund"),
198 /* This is the "new" batch updater that sits atop all lineitems. It does
199 * use this.afwCopyFieldArgs() to borrow a little common code from the
200 * "old" batch updater atop the copy details view. */
201 this.initBatchUpdater = function(disabled_fields) {
202 openils.Util.show("acq-batch-update", "table");
204 if (!dojo.isArray(disabled_fields)) disabled_fields = [];
206 /* Note that this will directly contain dijits, not the AutoWidget
208 if (!this.batchUpdateWidgets) {
209 this.batchUpdateWidgets = {};
212 if (this.batchUpdateWidgets.item_count) this.batchUpdateWidgets.item_count.destroy();
213 this.batchUpdateWidgets.item_count = new dijit.form.TextBox(
215 "style": {"width": "3em"},
217 dojo.indexOf(disabled_fields, "item_count") != -1
223 if (!this.batchUpdateWidgets.distribution_formula) {
224 (new openils.widget.AutoFieldWidget({
226 "selfReference": true,
227 "dijitArgs": { "required": false },
229 "parentNode": "acq-bu-distribution_formula"
232 dojo.style(w.domNode, {"width": "12em"});
233 self.batchUpdateWidgets.distribution_formula = w;
238 /* dijitArgs to AutoFieldWidget won't work for 'disabled' */
239 self.batchUpdateWidgets.distribution_formula.attr(
241 dojo.indexOf(disabled_fields, "distribution_formula") != -1
244 function buildOneBatchWidget(field, args) {
245 if (!self.batchUpdateWidgets[field]) {
246 (new openils.widget.AutoFieldWidget(args)).build(
248 if (field == "fund") {
250 w, "onChange", function(val) {
251 self._updateFundSelectorStyle(aw, val);
255 self._ensureCSSFundClasses(w.store);
258 dojo.style(w.domNode, {"width": "10em"});
259 self.batchUpdateWidgets[field] = w;
264 if (self.batchUpdateWidgets[field]) {
265 self.batchUpdateWidgets[field].attr(
267 dojo.indexOf(disabled_fields, field) != -1
273 ["owning_lib","location","collection_code","circ_modifier","fund"],
275 var args = self.afwCopyFieldArgs(field,"CREATE_PURCHASE_ORDER");
276 args.parentNode = dojo.byId("acq-bu-" + field);
278 if (field == 'fund') {
279 // The list of funds can be huge. Before fetching
280 // funds for PO modification, see where the user has
281 // perms and limit the retreived funds accordingly.
282 // Note: This is the first instance of fund list
283 // retrieval. All future fund list retrievals will
284 // benefit directly from having applied the fund
285 // search filter org units here.
286 self.setFundSearchFilter(function() {
287 buildOneBatchWidget(field, args);
292 buildOneBatchWidget(field, args);
296 acqBatchUpdateApply.onClick = function() {
297 var li_id_list = self.getSelected(false, null, true /* id list */);
298 if (!li_id_list.length) {
299 alert(localeStrings.NO_LI_TO_UPDATE);
303 progressDialog.show(true);
304 progressDialog.attr("title", localeStrings.LI_BATCH_UPDATE);
305 progressDialog.update({"maximum": li_id_list.length,"progress": 0});
309 var params = [ self.authtoken, {"lineitems": li_id_list},
310 self.batchUpdateChanges(), self.batchUpdateFormula() ];
311 console.log("batch update params: " + dojo.toJson(params));
313 fieldmapper.standardRequest(
314 ["open-ils.acq", "open-ils.acq.lineitem.batch_update"], {
317 "onresponse": function(r) {
318 if ((r = openils.Util.readResponse(r))) { // assignment
319 progressDialog.update({"progress": ++count});
321 progressDialog.hide();
322 progressDialog.attr("title", "");
325 "oncomplete": function() {
326 /* XXX Is the last call to onresponse guaranteed to
327 * finish before oncomplete is fired? */
328 if (count != li_id_list.length) {
329 console.error("lineitem batch update operation failed");
330 progressDialog.hide();
331 progressDialog.attr("title", "");
333 location.href = location.href;
341 this.batchUpdateChanges = function() {
345 openils.Util.objectProperties(this.batchUpdateWidgets),
347 if (k == "distribution_formula") return; /* handled elsewhere */
348 if (self.batchUpdateWidgets[k].attr("disabled")) return;
350 /* It's important that a value of "" should mean that a field
351 * doesn't get used in the arguments to the batch updater API,
352 * but 0 should mean an actual 0. */
353 var value = self.batchUpdateWidgets[k].attr("value");
362 this.batchUpdateFormula = function() {
363 if (this.batchUpdateWidgets.distribution_formula.attr("disabled")) {
367 this.batchUpdateWidgets.distribution_formula.attr("value") ||
373 this.reset = function(keep_selectors) {
374 while(self.tbody.childNodes[0])
375 self.tbody.removeChild(self.tbody.childNodes[0]);
384 this.setNext = function(handler) {
385 var link = dojo.byId('acq-lit-next');
387 dojo.style(link, 'visibility', 'visible');
388 link.onclick = handler;
390 dojo.style(link, 'visibility', 'hidden');
394 this.setPrev = function(handler) {
395 var link = dojo.byId('acq-lit-prev');
397 dojo.style(link, 'visibility', 'visible');
398 link.onclick = handler;
400 dojo.style(link, 'visibility', 'hidden');
404 this.enableActionsDropdownOptions = function(mask) {
405 /* 'mask' is probably a misnomer the way I'm using it, but it needs to
406 * be one of pl,po,ao,gs,vp, or fs. */
407 dojo.query("option", "acq-lit-li-actions-selector").forEach(
409 var opt_mask = dojo.attr(option, "mask");
411 /* For each <option> element, an empty or non-existent mask
412 * attribute, a mask attribute of "*", or a mask attribute that
413 * matches this method's argument should result in that
414 * option's being enabled. */
416 option, "disabled", !(
419 opt_mask.search(mask) != -1
427 * Ensures this.focusLineitem is in view and causes a brief
428 * border around the lineitem to come to life then fade.
430 this.focusLi = function() {
431 if (!this.focusLineitem) return;
433 // set during addLineitem()
434 var node = dojo.byId('li-title-ref-' + this.focusLineitem);
436 // LI may not yet be rendered
439 // prevent numerous re-focuses
440 this.focusLineitem = null;
442 // causes the full row to be visible
443 dijit.scrollIntoView(node);
446 dojo.query('[attr=title]', node)[0].focus();
448 dojo.require('dojox.fx');
452 dojox.fx.highlight({color : '#BB4433', node : node, duration : 2000}).play();
457 this.show = function(div) {
458 openils.Util.hide('acq-lit-table-div');
459 openils.Util.hide('acq-lit-info-div');
460 openils.Util.hide('acq-lit-li-details');
461 openils.Util.hide('acq-lit-notes-div');
462 openils.Util.hide('acq-lit-real-copies-div');
463 openils.Util.hide('acq-lit-asset-creator');
466 openils.Util.show('acq-lit-table-div');
468 this.refreshInlineCopies();
471 openils.Util.show('acq-lit-info-div');
474 openils.Util.show('acq-lit-li-details');
477 openils.Util.show('acq-lit-real-copies-div');
480 openils.Util.show('acq-lit-notes-div');
482 case 'asset-creator':
483 openils.Util.show('acq-lit-asset-creator');
487 openils.Util.show(div);
491 this.hide = function() {
495 this.toggleSelect = function() {
497 dojo.forEach(self.selectors, function(i){i.checked = false});
499 dojo.forEach(self.selectors, function(i){i.checked = true});
500 self.toggleState = !self.toggleState;
504 this.getAll = function(callback, id_only, state) {
505 /* For some uses of the li table, we may not really know about "all"
506 * the lineitems that the user thinks we know about. If we're a paged
507 * picklist, for example, we only know about the lineitems we've
508 * displayed, but not necessarily all the lineitems on the picklist.
509 * So we reach out to pcrud to inform us.
510 * state: string/array. only lineitems in one of these states are
511 * included in the final result set. Not currently supported for
515 var oncomplete = function(r) {
516 var id_list = openils.Util.readResponse(r);
520 self.fetchLineitemsById(id_list, callback);
524 var search = {"picklist": this.isPL};
525 if (state) search.state = state;
528 "id_list": true, /* sic, even if id_only */
530 "oncomplete": oncomplete
534 } else if (this.isPO) {
535 var search = {"purchase_order": this.isPO};
536 if (state) search.state = state;
541 "oncomplete": oncomplete
545 } else if (this.isUni && this.pager) {
546 this.pager.getAllLineitemIDs(oncomplete);
550 /* If execution reaches this point, we don't need or can't perform
551 * any special tricks to find out the "real" list of "all" lineitems
552 * in this context, so we fall back to the old method.
554 callback(this.getSelected(true, null, id_only, state));
557 /** @param all If true, assume all are selected */
558 this.getSelected = function(
560 callback /* If you want a "good" idea of "all" lineitems, you must
561 provide a callback that accepts an array parameter, rather than
562 relying on the return value of this method itself. */,
566 console.log("getSelected states = " + state);
568 return this.getAll(callback, id_only, state);
570 var indices = {}; /* use to uniqify. needed in paging situations. */
571 dojo.forEach(this.selectors,
574 indices[i.parentNode.parentNode.getAttribute('li')] = true;
578 var result = openils.Util.objectProperties(indices);
580 // caller provided a lineitem state filter. remove IDs for lineitems
581 // not in the selected state.
584 if (!dojo.isArray(state)) state = [state];
585 dojo.forEach(result, function(liId) {
586 console.log('filter LI state ' + self.liCache[liId].state());
587 if (state.indexOf(self.liCache[liId].state()) >= 0)
594 result = result.map(function(liId) { return self.liCache[liId]; });
602 this.setRowAttr = function(td, liWrapper, field, type) {
603 var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
604 td.appendChild(document.createTextNode(val));
607 this.setClaimPolicyControl = function(li, row) {
608 if (!self._claimPolicyPickerLoading) {
609 self._claimPolicyPickerLoading = true;
611 new openils.widget.AutoFieldWidget({
612 "parentNode": "acq-lit-li-claim-policy",
614 "selfReference": true,
615 "dijitArgs": {"required": true}
617 function(w) { self.claimPolicyPicker = w; }
621 /* dojox.timing.doLater() is the best thing ever. Resource not yet
622 * ready? Just repeat my whole method when it is. */
623 if (dojox.timing.doLater(self.claimPolicyPicker)) {
627 row = self._findLiRow(li);
629 if (li.claim_policy()) {
630 /* This Dojo data dance is necessary to get a whole fieldmapper
631 * object based on a claim policy ID, since we alreay have the
632 * widget thing loaded with all that data, and can thereby
633 * avoid another request to the server. */
634 self.claimPolicyPicker.store.fetchItemByIdentity({
635 "identity": li.claim_policy(),
636 "onItem": function(a) {
637 var policy = (new acqclp()).fromStoreItem(a);
638 var span = nodeByName("claim_policy", row);
639 var inner = nodeByName("claim_policy_name", row);
641 openils.Util.show(span, "inline");
642 inner.innerHTML = policy.name();
644 "onError": function(e) {
649 openils.Util.hide(nodeByName("claim_policy", row));
650 nodeByName("claim_policy_name", row).innerHTML = "";
655 this.fetchClaimInfo = function(liId, force, callback, row) {
657 liId, function(full) {
658 self.liCache[full.id()] = full;
659 self.checkClaimEligibility(full, callback, row);
664 // fetch an updated copy of the lineitem
665 // and add it back to the lineitem table
666 this.refreshLineitem = function(li, focus) {
668 this._fetchLineitem(li.id(),
671 self.focusLineitem = li.id();
673 self.focusLineitem = null;
675 var row = dojo.query('[li='+li.id()+']', self.tbody)[0];
676 var nextSibling = row.nextSibling;
677 self.tbody.removeChild(row);
678 self.addLineitem(newLi, false, nextSibling);
684 * Inserts a single lineitem into the growing table of lineitems
685 * @param {Object} li The lineitem object to insert
687 this.addLineitem = function(li, skip_final_placement, nextSibling) {
688 this.liCache[li.id()] = li;
690 // insert the row right away so that final order isn't
691 // dependent on how long subsequent async request take
692 // for a given line item
693 var row = self.rowTemplate.cloneNode(true);
694 if (!skip_final_placement) {
696 // either no nextSibling was provided or it was null
697 // meaning the row was already at the end of the table
698 self.tbody.appendChild(row);
700 self.tbody.insertBefore(row, nextSibling);
704 self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
706 // sort the lineitem notes on edit_time
707 if(!li.lineitem_notes()) li.lineitem_notes([]);
709 var liWrapper = new openils.acq.Lineitem({lineitem:li});
710 row.setAttribute('li', li.id());
711 var tds = dojo.query('[attr]', row);
712 dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
713 dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
715 // so we can scroll to it later
716 dojo.query('[name=bib-info-cell]', row)[0].id = 'li-title-ref-' + li.id();
719 liWrapper.findAttr("isbn", "lineitem_marc_attr_definition") ||
720 liWrapper.findAttr("upc", "lineitem_marc_attr_definition");
722 // XXX media prefix for added content
724 nodeByName("jacket", row).setAttribute(
725 "src", "/opac/extras/ac/jacket/small/" + identifier
729 nodeByName("liid", row).innerHTML += li.id();
731 var exist = nodeByName('li_existing_count', row);
732 fieldmapper.standardRequest(
733 ['open-ils.acq', 'open-ils.acq.lineitem.existing_copies.count'],
735 params: [this.authtoken, li.id()],
736 oncomplete : function(r) {
737 var count = openils.Util.readResponse(r);
738 exist.innerHTML = count;
739 if (Number(count) > 0) {
740 openils.Util.addCSSClass(
741 exist, 'acq-existing-count-warn');
745 label : dojo.string.substitute(
746 localeStrings.LI_EXISTING_COPIES, [count])
753 openils.Util.show(nodeByName('catalog', row), 'inline');
754 nodeByName("catalog_link", row).onclick = this.generateMakeRecTab(li.eg_bib_id());
756 openils.Util.show(nodeByName('link_to_catalog', row), 'inline');
757 nodeByName("link_to_catalog_link", row).onclick = function() { self.drawBibFinder(li) };
760 if (li.queued_record()) {
761 this.pcrud.retrieve('vqbr', li.queued_record(),
763 oncomplete : function(r) {
764 var qrec = openils.Util.readResponse(r);
765 openils.Util.show(nodeByName('queue', row), 'inline');
766 var link = nodeByName("queue_link", row);
767 link.onclick = function() {
768 // open a new tab to the vandelay queue for this record
769 openils.XUL.newTabEasy(
770 oilsBasePath + '/vandelay/vandelay?qtype=bib&qid=' + qrec.queue()
778 nodeByName("worksheet_link", row).href =
779 oilsBasePath + "/acq/lineitem/worksheet/" + li.id() +
780 '?source=' + encodeURIComponent(location.pathname + location.search)
782 nodeByName("show_requests_link", row).href =
783 oilsBasePath + "/acq/picklist/user_request?lineitem=" + li.id() +
784 '?source=' + encodeURIComponent(location.pathname + location.search)
786 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
787 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
788 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
789 dojo.query('[name=expand_inline_copies]', row)[0].onclick =
790 function() {self.drawInlineCopies(li.id())};
793 if (sum = li.order_summary()) { // assignment
794 // Only show the paid label if at least one copy is invoiced.
795 // In other words, a lineitem whose every copy is canceled
797 if (sum.invoice_count() > 0) {
798 if (sum.item_count() == (
799 sum.invoice_count() + sum.cancel_count())) {
800 // Lineitem is fully paid. Display the paid-off label
801 openils.Util.show(nodeByName('paid', row), 'inline');
806 this.drawOrderIdentSelector(li, row);
808 if (!this.skipInitialEligibilityCheck)
812 function(full) { self.setClaimPolicyControl(full, row) },
816 this.updateLiNotesCount(li, row);
818 // show which PO this lineitem is a member of
819 if(li.purchase_order() && !this.isPO) {
821 this.poCache[li.purchase_order()] =
822 this.poCache[li.purchase_order()] ||
823 fieldmapper.standardRequest(
824 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
826 this.authtoken, li.purchase_order(), {
827 "flesh_price_summary": true,
828 "flesh_provider" : true,
829 "flesh_lineitem_count": true
832 if(po && !this.isMeta) {
833 openils.Util.show(nodeByName('po', row), 'inline');
834 var link = nodeByName('po_link', row);
835 link.setAttribute('href', oilsBasePath +
836 '/acq/po/view/' + li.purchase_order() +
837 '?focus_li=' + li.id() +
838 '&source=' + encodeURIComponent(location.pathname + location.search)
840 link.innerHTML += po.name();
842 openils.Util.show(nodeByName('pro', row), 'inline');
843 link = nodeByName('pro_link', row);
844 link.setAttribute('href', oilsBasePath + '/conify/global/acq/provider/' + po.provider().id())
845 link.innerHTML += po.provider().code();
849 // show which picklist this lineitem is a member of
850 if(li.picklist() && (this.isPO || this.isMeta || this.isUni)) {
852 this.plCache[li.picklist()] =
853 this.plCache[li.picklist()] ||
854 fieldmapper.standardRequest(
855 ['open-ils.acq', 'open-ils.acq.picklist.retrieve.authoritative'],
856 {params: [this.authtoken, li.picklist()]});
858 if (pl.name() == "") {
859 openils.Util.show(nodeByName("bib_origin", row), "inline");
863 openils.Util.show(nodeByName('pl', row), 'inline');
864 var link = nodeByName('pl_link', row);
865 link.setAttribute('href', oilsBasePath +
866 '/acq/picklist/view/' + li.picklist() +
867 '?focus_li=' + li.id() +
868 '&source=' + encodeURIComponent(location.pathname + location.search)
870 link.innerHTML += pl.name();
875 var countNode = nodeByName('count', row);
876 var count = li.item_count() || 0;
877 if (typeof(this._copy_count_cb) == "function") {
878 this._copy_count_cb(li.id(), count);
880 countNode.innerHTML = count;
881 countNode.id = 'acq-lit-copy-count-label-' + li.id();
884 var priceInput = dojo.query('[name=price]', row)[0];
885 priceInput.value = li.estimated_unit_price() || '';
886 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
888 // show either "mark received" or "unreceive" as appropriate
889 this.updateLiState(li, row);
891 if (skip_final_placement) {
895 // the last LI may be rendered after the call to show('list'),
896 // so make sure it's focused if necessary.
897 if (this.focusLineitem == li.id())
901 this._liCountClaims = function(li) {
903 for (var i = 0; i < li.lineitem_details().length; i++)
904 total += li.lineitem_details()[i].claims().length;
908 this._findLiRow = function(li) {
909 return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
912 this.reconsiderClaimControl = function(li, row) {
913 if (!row) row = this._findLiRow(li);
914 var option = nodeByName("action_manage_claims", row);
915 var eligible = this.claimEligibleLidByLi[li.id()].length;
916 var count = this._liCountClaims(li);
918 option.disabled = !(count || eligible);
920 dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
921 option.onclick = function() { self.claimDialog.show(li); };
924 this.clearEligibility = function(li) {
925 this.claimEligibleLidByLi[li.id()] = [];
927 if (li.lineitem_details()) {
928 li.lineitem_details().forEach(
929 function(lid) { delete self.claimEligibleLid[lid.id()]; }
933 if (this.copyCache) {
935 for (var k in this.copyCache) {
936 if (this.copyCache[k].lineitem() == li.id())
940 function(k) { delete self.claimEligibleLid[k]; }
945 this.applyOrderIdentValues = function() {
946 this._identValuesInFlight =
947 openils.Util.objectProperties(this.liCache).length;
948 for (var liId in this.liCache) {
949 this._applyOrderIdentValue(this.liCache[liId]);
953 // returns true if request was sent
954 this._applyOrderIdentValue = function(li, oncomplete) {
957 console.log('applying ident value for lineitem ' + li.id());
960 var row = dojo.query('[li=' + li.id() + ']')[0];
962 // find the selected ident value
963 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
964 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
965 var name = typeSel.options[typeSel.selectedIndex].value;
966 var val = typeSel._cbox.attr('value');
968 console.log("selected ident is " + val);
970 // it differs from the existing ident value, update it
971 var oldIdent = self.getLiOrderIdent(li);
973 oldIdent.attr_name() == name &&
974 oldIdent.attr_value() == val) {
975 console.log('selected ident attr matches existing attr');
976 if (--this._identValuesInFlight == 0) {
977 if (oncomplete) oncomplete(li);
978 else location.href = location.href;
983 // see if the selected ident value is represented
984 // by an existing lineitem attr
987 typeSel._cbox.store.fetch({
988 query : {attr_value : val},
989 onItem : function(item) {
990 console.log('found existing attr for ident value');
991 args.source_attr_id = li.attributes().filter(
992 function(attr) { return attr.id() == item.id[0] }
998 if (!args.source_attr_id) {
999 // user entered new text in the combobox
1000 // so we need to create a new attr
1001 console.log('creating new ident attr');
1002 args.lineitem_id = li.id();
1003 args.attr_name = name;
1004 args.attr_value = val;
1007 fieldmapper.standardRequest(
1008 ['open-ils.acq', 'open-ils.acq.lineitem.order_identifier.set'],
1010 params : [openils.User.authtoken, args],
1011 oncomplete : function() {
1012 console.log('order_ident oncomplete');
1013 if (--self._identValuesInFlight == 0) {
1014 if (oncomplete) oncomplete(li);
1015 else location.href = location.href;
1017 console.log(self._identValuesInFlight + ' still in flight');
1025 this.getLiOrderIdent = function(li) {
1026 var attrs = li.attributes();
1027 if (!attrs) return null;
1028 return attrs.filter(
1031 attr.attr_type() == 'lineitem_local_attr_definition' &&
1032 openils.Util.isTrue(attr.order_ident())
1038 this.drawOrderIdentSelector = function(li, row) {
1040 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
1041 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
1043 var attrs = li.attributes();
1045 // limit to MARC attr defs
1046 attrs = attrs.filter(
1048 return (attr.attr_type() == 'lineitem_marc_attr_definition');
1052 var identAttr = this.getLiOrderIdent(li);
1055 // collect the values for each type of identifier
1056 // find a reasonable default identifier type to render
1060 dojo.forEach(['isbn', 'upc', 'issn'],
1063 // collect the values for this attr name
1064 values[name] = attrs.filter(
1066 return (attr.attr_name() == name)
1070 // select a reasonable default name in the type-selector
1074 if (identAttr.attr_name() == name)
1076 } else if (values[name].length) {
1081 dojo.forEach(typeSel.options, function(opt) {
1082 if (opt.value == name) {
1083 opt.selected = true;
1092 function updateOrderIdent(val) {
1093 self._identValuesInFlight = 1;
1094 self._applyOrderIdentValue(
1097 self.refreshLineitem(li);
1102 // replace the ident combobox with a new
1103 // one for the selected ident type
1104 function changeComboBox(sel) {
1105 var name = sel.options[sel.selectedIndex].value;
1107 var td = dojo.query('[name=order_ident_value]', row)[0];
1108 if (td.childNodes[0])
1109 dojo.destroy(td.childNodes[0]);
1111 var store = new dojo.data.ItemFileWriteStore({
1112 data : acqlia.toStoreData(values[name])
1115 var cbox = new dijit.form.ComboBox(
1117 labelAttr : 'attr_value',
1118 searchAttr : 'attr_value'
1120 dojo.create('div', {}, td)
1125 // set the value for the cbox
1126 if (values[name].length) {
1127 var orderIdent = self.getLiOrderIdent(li);
1129 if (orderIdent && orderIdent.attr_name() == name) {
1130 cbox.attr('value', orderIdent.attr_value());
1132 cbox.attr('value', values[name][0].attr_value());
1136 if (!self.orderIdentAllowed)
1137 cbox.attr('disabled', true);
1140 cbox._lineitem = li;
1141 dojo.connect(cbox, 'onChange', updateOrderIdent);
1144 changeComboBox(typeSel); // force the initial draw
1145 typeSel.onchange = function() {changeComboBox(typeSel)};
1148 this.testOrderIdentPerms = function(org, callback) {
1150 new openils.User().getPermOrgList(
1151 'ACQ_SET_LINEITEM_IDENTIFIER',
1153 console.log('found orgs = ' + orgs);
1154 for (var i = 0; i < orgs.length; i++) {
1155 if (Number(orgs[i]) == Number(org)) {
1156 self.orderIdentAllowed = true;
1157 if (callback) callback();
1161 if (callback) callback();
1167 this.checkClaimEligibility = function(li, callback, row) {
1168 /* Assume always eligible, i.e. from this interface we don't care about
1169 * claim eligibility any more. this is where the user would force a
1171 this.clearEligibility(li);
1172 this.claimEligibleLidByLi[li.id()] = li.lineitem_details().map(
1173 function(lid) { return lid.id(); }
1175 li.lineitem_details().forEach(
1176 function(lid) { self.claimEligibleLid[lid.id()] = true; }
1178 this.reconsiderClaimControl(li, row);
1179 if (callback) callback(li);
1181 this.clearEligibility(li);
1182 fieldmapper.standardRequest(
1183 ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
1184 "params": [openils.User.authtoken, {"lineitem": li.id()}],
1186 "onresponse": function(r) {
1187 if (r = openils.Util.readResponse(r)) {
1188 self.claimEligibleLidByLi[li.id()].push(
1191 self.claimEligibleLid[r.lineitem_detail()] = true;
1194 "oncomplete": function() {
1195 self.reconsiderClaimControl(li, row);
1196 if (typeof(callback) == "function")
1204 this.updateLiNotesCount = function(li, row) {
1205 if (!row) row = this._findLiRow(li);
1207 var has_notes = (li.lineitem_notes().filter(
1208 function(o) { return Boolean (o.alert_text()); }
1211 /* U+2691 is the code point for a filled-in flag character */
1212 nodeByName("notes_alert_flag", row).innerHTML =
1213 has_notes ? "⚑" : "";
1214 nodeByName("noteslink", row).style.fontStyle =
1215 has_notes ? "italic" : "normal";
1216 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
1219 /* XXX NOT related to _updateLiState(). rethink */
1220 this.updateLiState = function(li, row) {
1221 if (!row) row = this._findLiRow(li);
1223 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
1224 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
1226 // always allow access to LI history
1227 nodeByName('action_view_history', row).onclick =
1228 function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
1230 /* handle row coloring for based on LI state */
1231 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1232 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
1234 // Expose invoice actions for any lineitem that is linked to a PO
1235 if (li.purchase_order()) {
1236 openils.Util.show(nodeByName("invoices_span", row), "inline");
1237 var link = nodeByName("invoices_link", row);
1238 link.onclick = function() {
1239 openils.XUL.newTabEasy(
1240 oilsBasePath + "/acq/search/unified?so=" +
1241 base64Encode({"jub":[{"id": li.id()}]}) + "&rt=invoice"
1249 * If we haven't fleshed the lineitem_details, default to allowing access to the
1250 * holdings maintenence actions. The alternative is to flesh LIDs on every lineitem,
1251 * but that will add to page render time. Let's see if this will suffice...
1253 var lids = li.lineitem_details();
1255 (lids && !lids.filter(function(lid) { return lid.eg_copy_id() })[0] )) {
1257 actUpdateBarcodes.disabled = false;
1258 actUpdateBarcodes.onclick = function() {
1259 self.showRealCopyEditUI(li);
1260 nodeByName("action_none", row).selected = true;
1262 actHoldingsMaint.disabled = false;
1263 actHoldingsMaint.onclick =
1264 self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
1267 var state_cell = nodeByName("li_state_" + li.state(), row);
1269 // re-hide any state label nodes which may have been un-hidden
1270 // through previous actions.
1271 dojo.query('[state-label]', row).forEach(function(node) {
1272 openils.Util.hide(node)
1275 if (li.state() == 'cancelled') {
1276 if(typeof li.cancel_reason() == "object") {
1278 // clear the stock "Canceled" label, since we have more
1279 // information to replace it with.
1280 state_cell.innerHTML = '';
1282 var holds_state = dojo.create(
1284 "style": "border-bottom: 1px dashed #000;",
1285 "innerHTML": li.cancel_reason().label()
1286 }, state_cell, "only"
1290 "label": "<em>" + li.cancel_reason().label() +
1291 "</em><br />" + li.cancel_reason().description(),
1292 "connectId": [holds_state]
1293 }, dojo.create("span", null, state_cell, "last")
1296 if (li.cancel_reason().keep_debits() == 't') {
1297 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1298 openils.Util.addCSSClass(row, "oils-acq-li-state-delayed");
1301 console.log('li cancel_reason is un-fleshed. Please fix');
1305 openils.Util.show(state_cell);
1309 this._setAlertStore = function() {
1310 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
1312 "data": acqliat.toStoreData(
1315 "owning_lib": aou.orgNodeTrail(
1316 aou.findOrgUnit(openils.User.user.ws_ou())
1317 ).map(function(o) { return o.id(); })
1323 acqLitAlertAlertText.setValue(); /* make the store "live" */
1324 acqLitAlertAlertText._store_ready = true;
1328 * Draws and shows the lineitem notes pane
1330 this.drawLiNotes = function(li) {
1332 this.focusLineitem = li.id();
1334 if (!acqLitAlertAlertText._store_ready)
1335 this._setAlertStore();
1338 li.lineitem_notes().sort(
1340 if(a.edit_time() < b.edit_time()) return 1;
1346 while(this.liNotesTbody.childNodes[0])
1347 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
1350 acqLitCreateNoteSubmit.onClick = function() {
1351 var value = acqLitCreateNoteText.attr('value');
1353 var note = new fieldmapper.acqlin();
1356 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
1359 note.lineitem(li.id());
1361 self.updateLiNotes(li, note);
1362 acqLitCreateNoteVendorPublic.attr("checked", false);
1363 acqLitCreateNoteText.attr("value", "");
1366 acqLitCreateAlertSubmit.onClick = function() {
1367 if (!acqLitAlertAlertText.item) {
1368 alert(localeStrings.ALERT_UNSELECTED);
1372 var alert_text = new fieldmapper.acqliat().fromStoreItem(
1373 acqLitAlertAlertText.item
1375 var value = acqLitAlertNoteValue.attr("value") || "";
1377 var note = new fieldmapper.acqlin();
1379 note.lineitem(li.id());
1381 note.alert_text(alert_text);
1383 self.updateLiNotes(li, note);
1386 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
1390 * Draws a single lineitem note in the notes pane
1392 this.addLiNote = function(li, note) {
1393 if(note.isdeleted()) return;
1395 var row = self.liNotesRow.cloneNode(true);
1396 nodeByName("value", row).innerHTML = note.value();
1397 var alert_node = nodeByName("alert_code", row);
1398 if (note.alert_text()) {
1399 alert_node.innerHTML = dojo.string.substitute(
1401 aou.findOrgUnit(note.alert_text().owning_lib()).shortname(),
1402 note.alert_text().code()
1405 if (note.alert_text().description()) {
1408 "connectId": [alert_node],
1409 "label": note.alert_text().description()
1410 }, dojo.create("span", null, alert_node, "after")
1415 if (openils.Util.isTrue(note.vendor_public()))
1416 nodeByName("vendor_public", row).innerHTML =
1417 localeStrings.VENDOR_PUBLIC;
1419 nodeByName("delete", row).onclick = function() {
1420 note.isdeleted(true);
1421 self.liNotesTbody.removeChild(row);
1422 self.updateLiNotes(li);
1425 if(note.edit_time()) {
1426 nodeByName("edit_time", row).innerHTML =
1427 dojo.date.locale.format(
1428 dojo.date.stamp.fromISOString(note.edit_time()),
1429 {formatLength:'short'});
1432 self.liNotesTbody.appendChild(row);
1436 * Updates any new/changed/deleted notes on the server
1438 this.updateLiNotes = function(li, newNote) {
1444 notes = li.lineitem_notes().filter(
1446 if(note.ischanged() || note.isnew() || note.isdeleted())
1452 if(notes.length == 0) return;
1453 progressDialog.show();
1455 fieldmapper.standardRequest(
1456 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
1458 params : [this.authtoken, notes],
1459 onresponse : function(r) {
1460 var resp = openils.Util.readResponse(r);
1465 // remove the old changed notes
1467 dojo.forEach(li.lineitem_notes(),
1469 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
1473 li.lineitem_notes(list);
1476 progressDialog.hide();
1477 self.updateLiNotesCount(li);
1478 self.drawLiNotes(li);
1482 progressDialog.update(resp);
1483 var newnote = resp.note;
1485 if(!newnote.isdeleted()) {
1486 newnote.isnew(false);
1487 newnote.ischanged(false);
1488 li.lineitem_notes().push(newnote);
1495 this.updateLiPrice = function(input, li) {
1497 var price = input.value;
1498 if(Number(price) == Number(li.estimated_unit_price())) return;
1500 fieldmapper.standardRequest(
1501 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
1502 { async : false, // redundant w/ timeout
1504 params : [this.authtoken, li.id(), price],
1505 oncomplete : function(r) {
1506 openils.Util.readResponse(r);
1507 li.estimated_unit_price(price); // update local copy
1510 * If this is a PO and every visible lineitem has a price,
1511 * check again to see if this PO can be activated. Note that
1512 * every visible lineitem having a price does not guarantee it can
1513 * be activated, which is why we still make the call. Having a price
1514 * set for every visiable lineitem is just the lowest barrier to entry.
1517 var priceNodes = dojo.query('[name=price]', dojo.byId('acq-lit-tbody'));
1519 dojo.forEach(priceNodes, function(node) { if (node.value == '') allSet = false});
1520 if (allSet) checkCouldActivatePo();
1521 refreshPOSummaryAmounts();
1528 this.removeLineitem = function(liId) {
1529 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
1530 delete this.liCache[liId];
1531 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
1534 this.drawInfo = function(liId) {
1535 this.focusLineitem = liId;
1536 if (!this._isRelatedViewer) {
1537 var d = dojo.byId("acq-lit-info-related");
1538 if (!this.relCache[liId]) {
1539 fieldmapper.standardRequest(
1542 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
1545 "params": [openils.User.authtoken, liId],
1546 "onresponse": function(r) {
1547 self.relCache[liId] = openils.Util.readResponse(r);
1548 nodeByName("related_number", d).innerHTML =
1549 self.relCache[liId];
1551 self.relCache[liId] >1 ? "show" : "hide"
1557 nodeByName("related_number", d).innerHTML = this.relCache[liId];
1558 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
1563 openils.acq.Lineitem.fetchAttrDefs(
1565 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
1570 this.toggleInlineCopies = function() {
1571 // if any inline copies are not displayed,
1572 // display them all otherwise, hide them all.
1574 var displayAll = false;
1576 for (var liId in this.liCache) {
1577 if (!this.inlineCopiesVisible(liId)) {
1583 for (var liId in this.liCache) {
1584 var row = dojo.byId('acq-inline-copies-row-' + liId);
1586 if (!row || row._hidden) {
1587 this.drawInlineCopies(liId);
1589 } else { // hide all
1591 // drawInlineCopies() on a visible row will hide it.
1592 this.drawInlineCopies(liId);
1599 this.inlineCopiesVisible = function(liId) {
1600 var row = dojo.byId('acq-inline-copies-row-' + liId);
1601 return (row && !row._hidden);
1604 this.refreshInlineCopies = function(all, reFetch) {
1606 var liIds = this.inlineCopiesNeedingRefresh;
1607 if (all) liIds = openils.Util.objectProperties(liCache);
1608 liIds.forEach(function(liId) {
1609 if (self.inlineCopiesVisible(liId)) {
1610 self.drawInlineCopies(liId, reFetch); // hide
1611 self.drawInlineCopies(liId, reFetch); // re-draw
1616 // draw inline copy table. if the table is
1617 // already visible, hide the table as-is
1618 // reFetch forces a retrieval of the lineitem and
1619 // copies from the server. otherwise the locally
1620 // cached version of each is used.
1621 this.drawInlineCopies = function(liId, reFetch) {
1624 // find or create the row where the inline copies table will live
1625 var containerRow = dojo.byId('acq-inline-copies-row-' + liId);
1626 var liRow = dojo.query('[li=' + liId + ']')[0];
1628 if (!containerRow) {
1630 // build the inline copies container row and add it to
1631 // the DOM directly after the primary lineitem row
1633 containerRow = self.inlineCopyContainer.cloneNode(true);
1634 containerRow.id = 'acq-inline-copies-row-' + liId;
1636 if (liRow.nextSibling) {
1637 self.tbody.insertBefore(containerRow, liRow.nextSibling);
1639 self.tbody.appendChild(containerRow);
1644 // toggle the visible state
1645 containerRow._hidden = !containerRow._hidden;
1646 openils.Util.toggle(containerRow, 'table-row');
1648 if (containerRow._hidden) return; // hide only
1651 var handler = function(li) {
1653 var tbody = dojo.query(
1654 '[name=acq-li-inline-copies-tbody]',
1657 // reset the table before adding copy rows
1658 while (tbody.childNodes[0])
1659 tbody.removeChild(tbody.childNodes[0]);
1661 if(li.lineitem_details().length == 0) {
1663 self.inlineNoCopies.cloneNode(true));
1664 return; // no copies to show
1667 // add a row to the inline copy table for each copy
1668 dojo.forEach(li.lineitem_details(),
1670 var row = self.inlineCopyTemplate.cloneNode(true);
1671 tbody.appendChild(row);
1672 self.addInlineCopy(li, copy, row);
1677 this._fetchLineitem(liId, handler, reFetch);
1680 /** Draw read-only copy widgets for inline copies */
1681 this.addInlineCopy = function(li, copy, row) {
1684 dojo.forEach(liDetailFields,
1687 var widget = new openils.widget.AutoFieldWidget({
1690 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1691 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1692 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1694 parentNode : dojo.query('[name=' + field + ']', row)[0],
1703 /* For a given list of lineitem ids, build a list of full lineitems
1704 * re-using the fetching logic that is otherwise typical to use in this
1707 * If we've already got a lineitem in the cache, just use that.
1709 * Once we've built a list of lineitems, call callback(thatlist).
1711 this.fetchLineitemsById = function(id_list, callback) {
1712 var total = id_list.length;
1713 var result_list = [];
1715 var inner = function(li) {
1716 result_list.push(li)
1718 callback(result_list);
1721 id_list.forEach(function(id) { self._fetchLineitem(id, inner); });
1724 this._fetchLineitem = function(liId, handler, force) {
1726 var li = this.liCache[liId];
1727 if(li && li.marc() && li.lineitem_details() && !force)
1730 fieldmapper.standardRequest(
1731 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
1734 params: [self.authtoken, liId, {
1736 flesh_cancel_reason: true,
1737 flesh_li_details: true,
1739 flesh_fund_debit: true }],
1741 oncomplete: function(r) {
1742 var li = openils.Util.readResponse(r);
1743 self.liCache[liId] = li;
1750 this._drawInfo = function(li) {
1752 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
1754 if(li.eg_bib_id()) {
1755 openils.Util.hide('acq-lit-marc-order-record-label');
1756 openils.Util.hide(acqLitEditOrderMarc.domNode);
1757 openils.Util.show('acq-lit-marc-real-record-label');
1759 openils.Util.show('acq-lit-marc-order-record-label');
1760 openils.Util.show(acqLitEditOrderMarc.domNode);
1761 openils.Util.hide('acq-lit-marc-real-record-label');
1764 this.drawMarcHTML(li);
1765 this.infoTbody = dojo.byId('acq-lit-info-tbody');
1768 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
1769 while(this.infoTbody.childNodes[0])
1770 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
1772 for(var i = 0; i < li.attributes().length; i++) {
1773 var attr = li.attributes()[i];
1774 var row = this.infoRow.cloneNode(true);
1776 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
1777 var name = openils.acq.Lineitem.attrDefs[type].filter(
1779 return (a.code() == attr.attr_name());
1781 ).pop().description();
1783 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
1784 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
1785 this.infoTbody.appendChild(row);
1788 if (!this._isRelatedViewer) {
1789 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
1790 oilsBasePath + "/acq/lineitem/related/" + li.id();
1793 // if a top scroll point is defined, jump up to it here
1794 var node = dojo.byId('oils-scroll-to-top');
1795 if (node) dijit.scrollIntoView(node);
1798 this.generateMakeRecTab = function(bib_id,default_view, row) {
1800 if(openils.XUL.isXUL() && !window.IAMBROWSER) {
1803 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
1806 show_nav_buttons : true,
1807 show_print_button : true,
1808 opac_url : xulG.url_prefix('opac_rdetail|' + bib_id),
1809 default_view : default_view
1813 var url = '/eg/staff/cat/catalog/record/' + bib_id;
1814 if (default_view == 'copy_browser') {
1820 if(row) nodeByName("action_none", row).selected = true;
1824 this.drawMarcHTML = function(li) {
1825 var params = [null, true, li.marc()];
1827 params = [li.eg_bib_id(), true];
1829 fieldmapper.standardRequest(
1830 ['open-ils.search', 'open-ils.search.biblio.record.html'],
1833 oncomplete: function(r) {
1834 dojo.byId('acq-lit-marc-div').innerHTML =
1835 openils.Util.readResponse(r);
1841 this.drawCopies = function(liId, force_fetch) {
1842 this.focusLineitem = liId;
1843 if (typeof force_fetch == "undefined")
1844 force_fetch = false;
1846 var cgi = new openils.CGI();
1847 var source = cgi.param('source');
1848 if (source && source.match(/invoice/)) {
1849 // got here from the invoice page, show the 'return-to-invoice' button
1850 var cgi = new openils.CGI({url : source});
1851 cgi.param('focus_li', liId);
1852 openils.Util.show(dojo.byId('acq-lit-copies-back-to-invoice-button-wrapper'), 'inline');
1853 var button = dojo.byId('acq-lit-copies-back-to-invoice-button');
1854 button.onclick = function() { location.href = cgi.url() };
1857 openils.acq.Lineitem.fetchAndRender(liId, {},
1858 function(li, html) {
1859 dojo.byId('acq-lit-copies-li-summary').innerHTML = html;
1863 this.show('copies');
1865 this.copyCache = {};
1866 this.copyWidgetCache = {};
1867 this.oldCopyWidgetCache = {};
1868 this.virtDfaCounts = {};
1869 this.realDfaCache = {};
1872 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
1873 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
1874 acqLitCopyCountInput.attr('value', '0');
1876 if (this.isPO && PO && PO.order_date()) {
1877 // prevent adding copies to activated POs
1878 acqLitCopyCountInput.attr('disabled', true);
1879 acqLitAddCopyCount.attr('disabled', true);
1882 while(this.copyTbody.childNodes[0])
1883 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
1885 this._drawBatchCopyWidgets();
1887 this._drawDistribApplied(liId);
1889 this._fetchDistribFormulas(
1891 openils.acq.Lineitem.fetchAttrDefs(
1893 self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch);
1900 this._saveDistribAppliedTemplates = function() {
1901 if (!this._appliedDistribTemplate) {
1902 this._appliedDistribTemplate =
1903 dojo.byId("acq-lit-distrib-applied-tbody").
1904 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
1905 dojo.attr(this._appliedDistribTemplate, "id");
1909 this._drawDistribApplied = function(liId) {
1910 /* Build this table while hidden to prevent rendering artifacts */
1911 openils.Util.hide("acq-lit-distrib-applied-tbody");
1913 this._saveDistribAppliedTemplates();
1915 /* Remove any rows in the table from previous populations */
1916 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
1917 forEach(dojo.destroy);
1919 /* Unregister all dijits previously created (for some reason this isn't
1920 * covered by the above destroy calls). */
1921 dijit.registry.forEach(
1922 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
1925 /* Populate the table with our liId */
1927 fieldmapper.standardRequest(
1929 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
1932 "params": [self.authtoken, liId],
1933 "onresponse": function(r) {
1934 var dfa = openils.Util.readResponse(r);
1937 self.realDfaCache[dfa.id()] = dfa;
1938 self._drawDistribAppliedUnit(dfa);
1941 "oncomplete": function() {
1942 /* Reveal built table */
1945 "acq-lit-distrib-applied-tbody", "table-row-group"
1953 this._drawDistribAppliedUnit = function(dfa) {
1954 var new_row = false;
1955 var row = dojo.query(
1956 'tr[formula="' + dfa.formula().id() + '"]',
1957 "acq-lit-distrib-applied-tbody"
1962 row = dojo.clone(this._appliedDistribTemplate);
1963 dojo.attr(row, "formula", dfa.formula().id());
1964 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
1967 var td = dojo.query("td", row)[0];
1969 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1970 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1973 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1975 new dijit.form.Button(
1977 "onClick": function() {
1978 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1979 self.deleteDfa(dfa);
1982 /* XXX I /cannot/ make the following work in as a CSS class
1983 * for some reason. So frustrating... */
1984 "style": function(id) {
1986 "font-weight: bold; color: #c00;" :
1988 }(dfa.id()) + "margin: 0 6px;display: inline;"
1989 }, "dfa-button-" + dfa.id()
1993 "connectId": ["dfa-button-" + dfa.id()],
1994 "label": dojo.string.substitute(
1995 localeStrings.DFA_TIP, dfa.id() > 0 ? [
1996 openils.User.formalName(dfa.creator()),
1997 dojo.date.locale.format(
1998 dojo.date.stamp.fromISOString(dfa.create_time()),
1999 {"formatLength":"short"}
2001 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
2003 }, "dfa-tip-" + dfa.id()
2007 this.deleteDfa = function(dfa) {
2008 if (dfa.id() > 0) { /* real */
2009 this.pcrud.eliminate(
2012 "oncomplete": function() {
2013 self._removeDistribApplied(dfa.id());
2014 delete self.realDfaCache[dfa.id()];
2018 } else { /* virtual */
2019 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
2020 this.virtDfaCounts[dfa.formula().id()] = 0;
2021 /* hasn't been saved yet, so no need to do anything server side */
2022 this._removeDistribApplied(dfa.id());
2027 this._removeDistribApplied = function(dfaId) {
2028 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
2029 dijit.registry.forEach(
2030 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
2032 this._removeDistribAppliedEmptyRows();
2035 this._removeAllDistribAppliedVirtual = function() {
2036 /* Unregister dijits */
2037 dijit.registry.forEach(
2038 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
2040 this._removeDistribAppliedEmptyRows();
2043 this._removeDistribAppliedEmptyRows = function() {
2044 /* Remove any rows with no DFA at all */
2045 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
2047 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
2053 * Insert a new row into the distribution formula selection form
2055 this._addDistribFormulaRow = function() {
2058 if (!self.distribForms) {
2059 // no formulas, hide the form
2060 openils.Util.hide('acq-lit-distrib-formula-table');
2064 if(!this.distribFormulaTemplate)
2065 this.distribFormulaTemplate =
2066 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
2068 var row = this.distribFormulaTemplate.cloneNode(true);
2069 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
2071 this.dfSelector = new dijit.form.FilteringSelect(
2072 {"labelAttr": "dynLabel", "labelType": "html"},
2073 nodeByName("selector", row)
2075 this._updateFormulaStore();
2076 this.dfSelector.fetchProperties =
2077 {"sort": [{"attribute": "use_count", "descending": true}]};
2079 var apply = new dijit.form.Button(
2080 {"label": localeStrings.APPLY},
2081 nodeByName('set_button', row)
2084 var reset = new dijit.form.Button(
2085 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
2086 nodeByName("reset_button", row)
2089 dojo.connect(apply, 'onClick',
2091 var form_id = self.dfSelector.attr("value");
2092 if(!form_id) return;
2093 self._applyDistribFormula(form_id);
2094 reset.attr("disabled", false);
2098 dojo.connect(reset, 'onClick',
2100 self.restoreCopyFieldsBeforeDF();
2101 self.virtDfaCounts = {};
2102 self.virtDfaId = -1;
2104 self._updateFormulaStore();
2105 self._removeAllDistribAppliedVirtual();
2106 reset.attr("disabled", "true");
2113 * Applies a distrib formula to the current set of copies
2115 this._applyDistribFormula = function(formula) {
2116 if(!formula) return;
2118 formula = this.distribForms.filter(
2119 function(form) { return form.id() == formula; }
2122 var copyRows = dojo.query('tr', self.copyTbody);
2124 if (this.dfeOffset >= copyRows.length) {
2125 alert(localeStrings.OUT_OF_COPIES);
2129 var entries_applied = 0;
2131 var rowIndex = this.dfeOffset;
2132 rowIndex < copyRows.length;
2136 var row = copyRows[rowIndex];
2137 var copy_id = row.getAttribute('copy_id');
2138 var copyWidgets = this.copyWidgetCache[copy_id];
2139 var entryIndex = this.dfeOffset;
2142 // find the correct entry for the current row
2143 dojo.forEach(formula.entries(),
2146 entryIndex += e.item_count();
2147 if(entryIndex > rowIndex)
2155 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
2156 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
2159 this.saveCopyFieldsBeforeDF(copy_id);
2160 this._copy_fields_for_acqdf.forEach(
2162 if(entry[field]()) {
2163 copyWidgets[field].attr('value', (entry[field]()));
2170 if (entries_applied) {
2171 this.virtDfaCounts[formula.id()] =
2172 ++(this.virtDfaCounts[formula.id()]) || 1;
2173 this._updateFormulaStore();
2174 this._drawDistribAppliedUnit(
2176 var dfa = new acqdfa();
2177 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
2180 this.dfeOffset += entries_applied;
2185 * This function updates the DF store for the dropdown so that use_counts
2186 * can reflect DF applications from this session before they're saved
2189 this._updateFormulaStore = function() {
2190 this.dfSelector.store = new dojo.data.ItemFileReadStore(
2192 "data": self._labelFormulasWithCounts(
2193 acqdf.toStoreData(self.distribForms)
2199 this.saveCopyFieldsBeforeDF = function(copy_id) {
2201 if (!this.oldCopyWidgetCache[copy_id]) {
2202 var copyWidgets = this.copyWidgetCache[copy_id];
2204 this.oldCopyWidgetCache[copy_id] = {};
2205 this._copy_fields_for_acqdf.forEach(
2207 self.oldCopyWidgetCache[copy_id][f] =
2208 copyWidgets[f].attr("value");
2214 this.restoreCopyFieldsBeforeDF = function() {
2216 for (var copy_id in this.oldCopyWidgetCache) {
2217 this._copy_fields_for_acqdf.forEach(
2219 self.copyWidgetCache[copy_id][f].attr(
2220 "value", self.oldCopyWidgetCache[copy_id][f]
2227 this._labelFormulasWithCounts = function(store_data) {
2228 for (var key in store_data.items) {
2229 var obj = store_data.items[key];
2230 obj.use_count = Number(obj.use_count); /* needed for sorting */
2232 if (this.virtDfaCounts[obj.id])
2233 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
2235 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
2236 obj.use_count + "]</span> " + obj.name;
2242 * This method formerly would not refetch the DF formulas if they'd been
2243 * loaded already, but now it always re-fetches, since use_count changes.
2245 /** TODO: port distrib-formula selector to autofieldwidget+pcrud/dojo store */
2246 this._fetchDistribFormulas = function(onload) {
2247 fieldmapper.standardRequest(
2249 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
2252 "params": [openils.User.authtoken, 0, 500],
2253 "oncomplete": function(r) {
2254 self.distribForms = openils.Util.readResponse(r);
2255 if(!self.distribForms || self.distribForms.length == 0) {
2256 self.distribForms = [];
2258 self._addDistribFormulaRow();
2265 this._drawBatchCopyWidgets = function() {
2266 var row = this.copyBatchRow;
2267 dojo.forEach(liDetailBatchFields,
2269 if(self.copyBatchRowDrawn) {
2270 self.copyBatchWidgets[field].attr('value', null);
2272 var args = self.afwCopyFieldArgs(field, "CREATE_PICKLIST");
2273 args.parentNode = dojo.query('[name='+field+']', row)[0];
2275 var widget = new openils.widget.AutoFieldWidget(args);
2278 if (field == "fund" && w.store)
2279 self._ensureCSSFundClasses(w.store);
2280 self.copyBatchWidgets[field] = w;
2283 if (field == "fund") {
2285 widget.widget, "onChange", function(val) {
2286 self._updateFundSelectorStyle(widget, val);
2293 this.copyBatchRowDrawn = true;
2296 this.batchCopyUpdate = function() {
2298 for(var k in this.copyWidgetCache) {
2299 var cache = this.copyWidgetCache[k];
2300 dojo.forEach(liDetailBatchFields, function(f) {
2301 var newval = self.copyBatchWidgets[f].attr('value');
2302 if(newval) cache[f].attr('value', newval);
2307 this._drawCopies = function(li) {
2310 // this button sets the total number of copies for a given lineitem
2311 acqLitAddCopyCount.onClick = function() {
2312 var count = acqLitCopyCountInput.attr('value');
2315 while(self.copyCount() < count)
2318 // delete rows if necessary
2319 var diff = self.copyCount() - count;
2321 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
2322 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
2323 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
2325 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2331 if(li.lineitem_details().length > 0) {
2332 dojo.forEach(li.lineitem_details(),
2334 self.addCopy(li, copy);
2342 this.copyCount = function() {
2344 for(var id in this.copyCache) {
2345 if(!this.copyCache[id].isdeleted())
2351 this.virtCopyId = -1;
2352 this.addCopy = function(li, copy) {
2353 var row = this.copyRow.cloneNode(true);
2354 this.copyTbody.appendChild(row);
2358 copy = new fieldmapper.acqlid();
2360 copy.id(this.virtCopyId--);
2361 copy.lineitem(li.id());
2364 this.copyCache[copy.id()] = copy;
2365 row.setAttribute('copy_id', copy.id());
2366 self.copyWidgetCache[copy.id()] = {};
2368 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2370 var rcvr = copy.receiver();
2372 if (!userCache[rcvr]) {
2373 if(rcvr == openils.User.user.id()) {
2374 userCache[rcvr] = openils.User.user;
2376 userCache[rcvr] = fieldmapper.standardRequest(
2377 ['open-ils.actor', 'open-ils.actor.user.retrieve'],
2378 {params: [openils.User.authtoken, rcvr]}
2382 dojo.query('[name=receiver]', row)[0].innerHTML = userCache[rcvr].usrname();
2385 dojo.forEach(liDetailFields,
2388 if (field == "fund") {
2389 searchFilter = (copy.fund() ?
2390 {"-or": {"active": "t", "id": copy.fund()}} :
2392 searchFilter.org = fundSearchFilter.org;
2394 searchFilter = null;
2397 var readOnly = false;
2399 // TODO: Add support for changing the owning_lib after real copies have been made.
2400 // owning_lib is order data as much as its item data
2401 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
2405 // TODO: add support for changing the fund after debits have been created
2406 // Note: invoicing allows the change
2407 if(copy.fund_debit() && field == 'fund') {
2412 var widget = new openils.widget.AutoFieldWidget({
2415 labelFormat : (field == 'fund') ? fundLabelFormat : null,
2416 searchFormat : (field == 'fund') ? fundSearchFormat : null,
2417 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
2418 searchFilter : searchFilter,
2419 noCache: (field == "fund"),
2421 parentNode : dojo.query('[name='+field+']', row)[0],
2422 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2423 readOnly : readOnly,
2424 orgDefaultsToWs : true
2428 // make sure we capture the value from any async widgets
2431 if (field == "fund" && w.store)
2432 self._ensureCSSFundClasses(w.store);
2435 copy[field](ww.getFormattedValue())
2437 self.copyWidgetCache[copy.id()][field] = w;
2439 dojo.connect(w, 'onChange',
2441 if (field == "fund")
2442 self._updateFundSelectorStyle(widget, val);
2444 if (!readOnly && (copy.isnew() || val != copy[field]())) {
2445 // prevent setting ischanged() automatically on widget load for existing copies
2446 copy[field](widget.getFormattedValue())
2447 copy.ischanged(true);
2456 this.updateLidState(copy, row);
2459 this._ensureCSSFundClass = function(id) {
2460 if (!this.fundStyleSheet) {
2462 "style", {"type": "text/css"},
2463 document.getElementsByTagName("head")[0], "last"
2465 this.fundStyleSheet = document.styleSheets[
2466 document.styleSheets.length - 1
2470 var cn = "fund_" + id;
2471 if (!this.haveFundClass[cn]) {
2472 fieldmapper.standardRequest(
2473 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
2475 "params": [openils.User.authtoken, id],
2477 "oncomplete": function(r) {
2478 r = openils.Util.readResponse(r);
2479 self.fundBalanceState[id] = r;
2481 if (r[0] /* stop */)
2482 style = fundStyles.stop;
2483 else if (r[1] /* warning */)
2484 style = fundStyles.warning;
2485 self.fundStyleSheet.insertRule(
2486 "." + cn + " { " + style + " }",
2487 self.fundStyleSheet.cssRules.length
2489 self.haveFundClass[cn] = true;
2496 this._ensureCSSFundClasses = function(store) {
2498 "query": {"id": "*"},
2499 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
2503 this._updateFundSelectorStyle = function(widget, fund_id) {
2504 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
2505 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
2508 this.updateLidState = function(copy, row) {
2511 if (typeof(row) == "undefined") {
2512 row = dojo.query('tr[copy_id="' + copy.id() + '"]', this.copyTbody)[0];
2516 var recv_link = nodeByName("receive", row);
2517 var unrecv_link = nodeByName("unreceive", row);
2518 var del_link = nodeByName("delete", row);
2519 var cxl_link = nodeByName("cancel", row);
2520 var claim_link = nodeByName("claim", row);
2521 var cxl_reason_link = nodeByName("cancel_reason", row);
2523 // by default, hide all the actions
2524 openils.Util.hide(del_link.parentNode);
2525 openils.Util.hide(recv_link);
2526 openils.Util.hide(unrecv_link);
2527 openils.Util.hide(cxl_link);
2528 openils.Util.hide(claim_link);
2529 openils.Util.hide(cxl_reason_link);
2531 if (copy.id() > 0) { // real copies (LIDs)
2533 if (copy.cancel_reason()) {
2535 /* --------- cancelled -------------------------- */
2537 /* XXX the following may leak memory in a long lived table:
2538 * dijits may not get destroyed... not positive. revisit. */
2539 var holds_reason = dojo.create(
2541 "style": "border-bottom: 1px dashed #000;",
2542 "innerHTML": copy.cancel_reason().label()
2543 }, cxl_reason_link, "only"
2547 "label": "<em>" + copy.cancel_reason().label() +
2548 "</em><br />" + copy.cancel_reason().description(),
2549 "connectId": [holds_reason]
2550 }, dojo.create("span", null, cxl_reason_link, "last")
2552 openils.Util.show(cxl_reason_link, "inline");
2554 if (copy.cancel_reason().keep_debits() == 't' ) {
2555 // allow further cancellation of "delayed" copies
2557 openils.Util.show(cxl_link, "inline");
2558 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2561 } else if (copy.recv_time()) {
2563 /* --------- received -------------------------- */
2565 openils.Util.show(unrecv_link, "inline");
2566 unrecv_link.onclick = function() {
2567 if (confirm(localeStrings.UNRECEIVE_LID))
2568 self.issueReceive(copy, /* rollback */ true);
2571 } else if (this.liCache[copy.lineitem()].state() == 'on-order') {
2573 /* --------- on order -------------------------- */
2575 openils.Util.show(recv_link, 'inline');
2576 openils.Util.show(cxl_link, "inline");
2578 recv_link.onclick = function() {
2579 if (self.checkLiAlerts(copy.lineitem()))
2580 self.issueReceive(copy);
2583 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2587 /* --------- pre-order copies -------------------------- */
2589 del_link.onclick = function() { self.deleteCopy(row) };
2590 openils.Util.show(del_link.parentNode);
2596 /* --------- virtual copies -------------------------- */
2598 del_link.onclick = function() { self.deleteCopy(row) };
2599 openils.Util.show(del_link.parentNode);
2603 this.cancelLid = function(lid_id) {
2604 lidCancelDialog._lid_id = lid_id;
2605 openils.Util.show(lidCancelDialog.domNode.parentNode);
2606 lidCancelDialog.show();
2607 if (!lidCancelDialog._prepared) {
2608 var widget = new openils.widget.AutoFieldWidget({
2609 "fmField": "cancel_reason",
2610 "fmClass": "acqlid",
2611 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
2612 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2614 "searchOptions" : {order_by : {"acqcr":"label"}}
2618 acqLidCancelButton.onClick = function() {
2619 if (w.attr("value")) {
2620 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
2622 lidCancelDialog._lid_id,
2626 lidCancelDialog.hide();
2629 lidCancelDialog._prepared = true;
2635 this._cancelLid = function(lid_id, reason) {
2636 fieldmapper.standardRequest(
2637 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
2638 "params": [openils.User.authtoken, lid_id, reason],
2640 "onresponse": function(r) {
2641 if (r = openils.Util.readResponse(r)) {
2643 for (var id in r.lid) {
2644 /* actually this should only iterate once */
2645 self.copyCache[id].cancel_reason(
2646 r.lid[id].cancel_reason
2648 self.updateLidState(self.copyCache[id]);
2657 this._confirmAlert = function(li, lin) {
2659 dojo.string.substitute(
2660 localeStrings.CONFIRM_LI_ALERT, [
2661 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2662 "title", "lineitem_marc_attr_definition"
2664 /* XXX it's really better add a parameter and to adjust
2665 * the format string rather than do this concatenation
2666 * here, but if someone wants this for 2.2 in a hurry,
2667 * we can sidestep the problem of updating the strings
2668 * while the translators are working. */
2670 aou.findOrgUnit(lin.alert_text().owning_lib()).shortname() +
2672 lin.alert_text().code()
2674 lin.alert_text().description() || "",
2681 this.checkLiAlerts = function(li_id) {
2682 var li = this.liCache[li_id];
2684 var alert_notes = li.lineitem_notes().filter(
2685 function(o) { return Boolean(o.alert_text()); }
2688 /* this is _intentionally_ not done in a call to forEach() ... */
2689 for (var i = 0; i < alert_notes.length; i++) {
2690 if (this.noteAcks[alert_notes[i].id()])
2692 else if (!this._confirmAlert(li, alert_notes[i]))
2695 this.noteAcks[alert_notes[i].id()] = true;
2701 this.deleteCopy = function(row) {
2702 var copy = this.copyCache[row.getAttribute('copy_id')];
2703 copy.isdeleted(true);
2705 delete this.copyCache[copy.id()];
2706 this.copyTbody.removeChild(row);
2709 this._virtDfaCountsAsList = function() {
2711 for (var key in this.virtDfaCounts) {
2712 for (var i = 0; i < this.virtDfaCounts[key]; i++)
2718 this.confirmBreachedCopyFunds = function(copies) {
2719 var stop = 0, warning = 0;
2723 var state = self.fundBalanceState[o.fund()];
2724 if (state[0] /* stop */)
2726 else if (state[1] /* warning */)
2733 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
2734 } else if (warning) {
2735 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
2740 this.saveCopyChanges = function(liId) {
2746 for(var id in this.copyCache) {
2747 var c = this.copyCache[id];
2748 if(!c.isdeleted()) total++;
2749 if(c.isnew() || c.ischanged() || c.isdeleted()) {
2750 if(c.id() < 0) c.id(null);
2756 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
2759 if (copies.length > 0) {
2760 if (!this.confirmBreachedCopyFunds(copies))
2763 if (typeof(this._copy_count_cb) == "function")
2764 this._copy_count_cb(liId, total);
2766 openils.Util.show("acq-lit-update-copies-progress");
2767 fieldmapper.standardRequest(
2768 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
2770 params: [openils.User.authtoken, copies],
2771 onresponse: function(r) {
2772 var res = openils.Util.readResponse(r);
2773 litUpdateCopiesProgress.update(res);
2775 oncomplete: function() {
2776 self.drawCopies(liId, true /* force_fetch */);
2777 openils.Util.hide("acq-lit-update-copies-progress");
2778 refreshPOSummaryAmounts();
2784 var dfa_list = this._virtDfaCountsAsList();
2785 if (dfa_list.length > 0) {
2786 fieldmapper.standardRequest(
2788 "open-ils.acq.distribution_formula.record_application"],
2791 "params": [openils.User.authtoken, dfa_list, liId],
2792 "onresponse": function(r) {
2793 var res = openils.Util.readResponse(r);
2794 if (res && res.length < dfa_list.length)
2795 alert(localeStrings.DFA_NOT_ALL);
2799 this.virtDfaCounts = {};
2802 if (this.inlineCopiesNeedingRefresh.indexOf(liId) < 0)
2803 this.inlineCopiesNeedingRefresh.push(liId);
2806 this._updateCreatePoPrepayCheckbox = function(prepay) {
2807 var prepay = openils.Util.isTrue(prepay);
2808 this._prepayRequiredByVendor = prepay;
2809 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
2812 this._confirmPoPrepaySituation = function() {
2813 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
2814 if (want_prepay != this._prepayRequiredByVendor) {
2817 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
2818 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
2825 this.applySelectedLiAction = function(action) {
2829 case 'delete_selected':
2830 this._deleteLiList(self.getSelected());
2833 case 'add_to_order':
2834 addToPoDialog._get_li = dojo.hitch(
2837 return this.getSelected(
2838 false, null, true, li_pre_po_states);
2841 if (addToPoDialog._get_li().length == 0) {
2842 alert(localeStrings.NO_LI_GENERAL);
2845 addToPoDialog.show();
2848 case 'create_order':
2849 this._loadPOSelect();
2850 acqLitPoCreateDialog.show();
2853 case 'save_picklist':
2854 acqLitSavePlDialog.show();
2857 case 'selector_ready':
2859 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
2860 acqLitChangeLiStateDialog.show();
2868 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
2871 case 'batch_create_invoice':
2872 this.batchCreateInvoice();
2875 case 'batch_link_invoice':
2876 this.batchLinkInvoice();
2879 case 'receive_lineitems':
2880 this.receiveSelectedLineitems();
2883 case 'rollback_receive_lineitems':
2884 this.rollbackReceiveLineitems();
2887 case 'create_assets':
2888 this.showAssetCreator();
2891 case 'export_attr_list':
2892 this.chooseExportAttr();
2895 case 'batch_apply_funds':
2896 this.applyBatchLiFunds();
2899 case 'add_brief_record':
2901 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
2903 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
2907 case "cancel_lineitems":
2908 console.log('HERE');
2909 this.maybeCancelLineitems();
2912 case "apply_claim_policy":
2913 var li_list = this.getSelected();
2914 this.claimPolicyPicker.attr("value", null);
2915 liClaimPolicyDialog.show();
2916 liClaimPolicySave.onClick = function() {
2917 self.changeClaimPolicy(
2919 self.claimPolicyPicker.attr("value"),
2923 self.setClaimPolicyControl(li);
2924 self.reconsiderClaimControl(li);
2927 liClaimPolicyDialog.hide();
2935 this.changeClaimPolicy = function(li_list, value, callback) {
2937 function(li) { li.claim_policy(value); }
2939 fieldmapper.standardRequest(
2940 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
2941 "params": [openils.User.authtoken, li_list],
2943 "oncomplete": function(r) {
2944 r = openils.Util.readResponse(r);
2945 if (callback) callback(r);
2951 this.showAssetCreator = function(onAssetsCreated) {
2952 if(!this.isPO) return;
2955 // first, let's see if this PO has any LI's that need to be merged/imported
2956 self.pcrud.search('jub', {purchase_order : this.isPO, eg_bib_id : null}, {
2958 oncomplete : function(r) {
2959 var resp = openils.Util.readResponse(r);
2960 if (resp && resp.length) {
2961 // PO has some non-linked jubs.
2963 self.show('asset-creator');
2964 if(!self.vlAgent.loaded)
2965 self.vlAgent.init();
2967 dojo.connect(assetCreatorButton, 'onClick',
2968 function() { self.createAssets(onAssetsCreated) });
2972 // all jubs linked, move on to asset creation
2973 self.createAssets(onAssetsCreated, true);
2979 this.createAssets = function(onAssetsCreated, noVl) {
2980 this.show('acq-lit-progress-numbers');
2982 var vlArgs = (noVl) ? {} : {vandelay : this.vlAgent.values()};
2983 this.batchProgress = {};
2984 progressDialog.show(false);
2985 progressDialog.attr("title", localeStrings.LI_CREATING_ASSETS);
2986 fieldmapper.standardRequest(
2987 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
2989 params: [this.authtoken, this.isPO, vlArgs],
2990 onresponse: function(r) {
2991 var resp = openils.Util.readResponse(r);
2992 self._updateProgressNumbers(resp, !Boolean(onAssetsCreated), onAssetsCreated, true);
2998 this.maybeCancelLineitems = function() {
2999 openils.Util.show("acq-lit-cancel-reason", "inline");
3000 if (!acqLitCancelLineitemsButton._prepared) {
3001 var widget = new openils.widget.AutoFieldWidget({
3002 "fmField": "cancel_reason",
3004 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
3005 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3007 "searchOptions" : {order_by : {"acqcr":"label"}}
3011 acqLitCancelLineitemsButton.onClick = function() {
3012 if (w.attr("value")) {
3013 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
3014 self._cancelLineitems(w.attr("value"));
3016 openils.Util.hide("acq-lit-cancel-reason");
3019 acqLitCancelLineitemsButton._prepared = true;
3025 this._cancelLineitems = function(reason) {
3027 var li_list = this.getSelected();
3029 // canceled lineitems may be canceled again if they were
3030 // previously delayed (keep_debits = true).
3031 li_list = li_list.filter(
3034 li.state() != 'cancelled' ||
3035 li.cancel_reason().keep_debits() == 't'
3040 id_list = li_list.map(function(l) {return l.id()});
3042 if (!id_list.length) {
3043 alert(localeStrings.NO_LI_GENERAL);
3046 fieldmapper.standardRequest(
3047 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
3048 "params": [openils.User.authtoken, id_list, reason],
3050 "onresponse": function(r) {
3051 if (r = openils.Util.readResponse(r)) {
3053 for (var id in r.li) {
3054 self.liCache[id].state(r.li[id].state);
3055 self.liCache[id].cancel_reason(
3056 r.li[id].cancel_reason
3058 self.updateLiState(self.liCache[id]);
3061 if (r.lid && self.copyCache) {
3062 for (var id in r.lid) {
3063 if (self.copyCache[id]) {
3064 self.copyCache[id].cancel_reason(
3065 r.lid[id].cancel_reason
3067 self.updateLidState(self.copyCache[id]);
3077 this.chooseExportAttr = function() {
3078 if (!acqLitExportAttrSelector._li_setup) {
3080 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
3082 "data": acqlimad.toStoreData(
3084 "acqlimad", {"code": li_exportable_attrs}
3089 acqLitExportAttrSelector.setValue();
3090 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
3091 acqLitExportAttrSelector._li_setup = true;
3093 openils.Util.show("acq-lit-export-attr-holder", "inline");
3096 this.exportAttrList = function() {
3097 var attr_def = acqLitExportAttrSelector.item;
3098 var li_list = this.getSelected();
3099 var value_list = li_list.map(
3101 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
3102 attr_def.code, "lineitem_marc_attr_definition"
3105 ).filter(function(attr) { return Boolean(attr); });
3107 if (value_list.length > 0) {
3108 if (value_list.length < li_list.length) {
3110 dojo.string.substitute(
3111 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
3118 openils.XUL.contentToFileSaveDialog(
3119 value_list.join("\n"),
3120 localeStrings.EXPORT_SAVE_DIALOG_TITLE
3126 alert(dojo.string.substitute(
3127 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
3131 openils.Util.hide("acq-lit-export-attr-holder");
3134 this.printPO = function() {
3135 if(!this.isPO) return;
3136 progressDialog.show(true);
3137 fieldmapper.standardRequest(
3138 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
3140 params: [this.authtoken, this.isPO, 'html'],
3141 oncomplete: function(r) {
3142 progressDialog.hide();
3143 var evt = openils.Util.readResponse(r);
3144 if(evt && evt.template_output()) {
3145 openils.Util.printHtmlString(evt.template_output().data());
3152 this.batchCreateInvoice = function() {
3153 var liIds = this.getSelected(
3154 false, null, true /* id_list */, li_active_states)
3155 if (!liIds.length) {
3156 alert(localeStrings.NO_LI_GENERAL);
3159 var path = oilsBasePath + '/acq/invoice/view?create=1';
3160 dojo.forEach(liIds, function(li, idx) { path += '&attach_li=' + li });
3161 if (openils.XUL.isXUL())
3162 openils.XUL.newTabEasy(path, localeStrings.NEW_INVOICE, null, true);
3164 location.href = path;
3167 this.batchLinkInvoice = function(create) {
3168 var liIds = this.getSelected(
3169 false, null, true /* id_list */, li_active_states)
3170 if (!liIds.length) {
3171 alert(localeStrings.NO_LI_GENERAL);
3174 if (!self.invoiceLinkDialogManager) {
3175 self.invoiceLinkDialogManager =
3176 new InvoiceLinkDialogManager("li");
3178 self.invoiceLinkDialogManager.target = liIds;
3179 acqLitLinkInvoiceDialog.show();
3182 this.receiveSelectedLineitems = function() {
3183 var states = li_post_po_states.filter(
3184 function(s) { return s != 'received' });
3185 var li_list = this.getSelected(null, null, null, states);
3187 if (!li_list.length) {
3188 alert(localeStrings.NO_LI_GENERAL);
3192 for (var i = 0; i < li_list.length; i++) {
3193 var li = li_list[i];
3195 if (li.state() != "received" &&
3196 !this.checkLiAlerts(li.id())) return;
3199 this.show('acq-lit-progress-numbers');
3202 fieldmapper.standardRequest(
3203 ['open-ils.acq', 'open-ils.acq.lineitem.receive.batch'],
3207 li_list.map(function(li) { return li.id(); })
3209 onresponse : function(r) {
3210 var resp = openils.Util.readResponse(r);
3211 self._updateProgressNumbers(resp, true);
3217 this.issueReceive = function(obj, rollback) {
3219 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
3221 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
3223 progressDialog.show(true);
3224 fieldmapper.standardRequest(
3225 ["open-ils.acq", method], {
3227 "params": [this.authtoken, obj.id()],
3228 "onresponse": function(r) {
3229 if (r = openils.Util.readResponse(r)) {
3230 self.fetchClaimInfo(
3231 part == "lineitem" ? obj.id() : obj.lineitem(),
3233 function() { self.handleReceive(r); }
3235 progressDialog.hide();
3243 * Handles the responses from receive and rollback ML calls.
3245 this.handleReceive = function(resp) {
3248 for (var li_id in resp.li) {
3249 for (var key in resp.li[li_id])
3250 self.liCache[li_id][key](resp.li[li_id][key]);
3251 self.updateLiState(self.liCache[li_id]);
3255 if (typeof(self.poUpdateCallback) == "function")
3256 self.poUpdateCallback(resp.po);
3259 for (var lid_id in resp.lid) {
3260 for (var key in resp.lid[lid_id])
3261 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
3262 self.updateLidState(self.copyCache[lid_id]);
3268 this.rollbackReceiveLineitems = function() {
3269 var li_id_list = this.getSelected(false, null, true);
3270 if (!li_id_list.length) {
3271 alert(localeStrings.NO_LI_GENERAL);
3275 if (!confirm(localeStrings.ROLLBACK_LI_RECEIVE_CONFIRM)) return;
3277 this.show('acq-lit-progress-numbers');
3280 fieldmapper.standardRequest(
3281 ['open-ils.acq', 'open-ils.acq.lineitem.receive.rollback.batch'],
3283 params: [this.authtoken, li_id_list],
3284 onresponse : function(r) {
3285 var resp = openils.Util.readResponse(r);
3286 self._updateProgressNumbers(resp, true);
3292 this._updateProgressNumbers = function(resp, reloadOnComplete, onComplete, clearProgressDialog) {
3293 this._updateProgressDialog(resp);
3294 this.vlAgent.handleResponse(resp,
3295 function(resp, res) {
3296 if (clearProgressDialog) {
3297 progressDialog.update({ "progress": 100});
3298 progressDialog.update_message();
3299 progressDialog.hide();
3300 progressDialog.attr("title", "");
3302 if(reloadOnComplete)
3303 location.href = location.href;
3305 onComplete(resp, res);
3310 this._updateProgressDialog = function(resp) {
3311 progressDialog.update({ "progress": (resp.progress / resp.total) * 100 });
3312 var keys = ['li', 'vqbr', 'bibs', 'lid', 'debits_accrued', 'copies'];
3313 for (var i = 0; i < keys.length; i++) {
3314 if (resp[keys[i]] > (this.batchProgress[keys[i]] || 0)) {
3315 progressDialog.update_message(
3316 dojo.string.substitute(
3317 localeStrings["ACTIVATE_" + keys[i].toUpperCase() + "_PROCESSED"],
3323 this.batchProgress = resp;
3326 this._createPO = function(fields) {
3327 var wantall = (fields.create_from == "all");
3329 /* If we're a picklist or purchase order already and the user wants
3330 * all lineitems, we might have pages' worth of lineitems haven't all
3331 * been loaded yet, so getSelected() won't find them. The server,
3332 * however, should know about all our lineitems, so let's ask the
3333 * server for a complete list.
3338 true, function(list) {
3339 self._createPOFromLineitems(fields, list);
3340 }, /* id_list */ true, li_pre_po_states
3343 this._createPOFromLineitems(
3344 fields, this.getSelected(
3345 false, null, true /* id_list */, li_pre_po_states)
3350 this._createPOFromLineitems = function(fields, selected) {
3351 if (selected.length == 0) {
3352 alert(localeStrings.NO_LI_GENERAL);
3357 var po = new fieldmapper.acqpo();
3358 po.provider(this.createPoProviderSelector.attr("value"));
3359 po.ordering_agency(this.createPoAgencySelector.attr("value"));
3360 po.prepayment_required(fields.prepayment_required[0] ? true : false);
3361 var name = this.createPoNameInput.attr('value');
3362 if (name) po.name(name); // avoid name=""
3364 // if we're creating assets, delay the asset creation
3365 // until after the PO is created. This will allow us to
3366 // use showAssetCreator() directly.
3368 fieldmapper.standardRequest(
3369 ["open-ils.acq", "open-ils.acq.purchase_order.create"],
3372 openils.User.authtoken,
3373 po, {lineitems : selected}
3375 onresponse : function(r) {
3376 var resp = openils.Util.readResponse(r);
3377 if (resp.complete) {
3378 // self.isPO is needed for showAssetCreator();
3379 self.isPO = resp.purchase_order.id();
3380 var redir = oilsBasePath + "/acq/po/view/" + self.isPO;
3381 if (fields.create_assets[0]) {
3382 self.showAssetCreator(
3383 function() {location.href = redir}
3386 location.href = redir;
3395 this.batchFundWidget = null;
3397 this.applyBatchLiFunds = function() {
3399 var liIds = this.getSelected().map(function(li) { return li.id(); });
3400 if(liIds.length == 0) return; // warn?
3403 batchFundUpdateDialog.show();
3405 if(!this.batchFundWidget) {
3406 this.batchFundWidget = new openils.widget.AutoFieldWidget({
3408 selfReference : true,
3409 labelFormat : fundLabelFormat,
3410 searchFormat : fundSearchFormat,
3411 searchFilter : fundSearchFilter,
3412 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
3413 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
3414 dijitArgs : { "required": true, "labelType": "html" },
3417 this.batchFundWidget.build();
3420 dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
3421 dojo.connect(batchFundUpdateSubmit, 'onClick',
3424 // TODO: call .dry_run first to test thresholds
3425 fieldmapper.standardRequest(
3426 ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
3429 openils.User.authtoken,
3431 self.batchFundWidget.widget.attr('value')
3433 oncomplete : function(r) {
3434 var resp = openils.Util.readResponse(r);
3436 location.href = location.href;
3445 this._deleteLiList = function(list, idx) {
3446 if(idx == null) idx = 0;
3447 if(idx >= list.length) return;
3452 if (this.isPO && (li.state() == "on-order" || li.state() == "received")) {
3453 /* It makes little sense to delete a lineitem from a PO that has
3454 * already been marked 'on-order'. Especially if EDI is in use,
3455 * such a purchase order will probably have already been shipped
3456 * off to a vendor, and mucking with it at this point could leave
3457 * your data in a bad state that doesn't jive with reality.
3459 * I could see making this restriction even firmer.
3461 * I could also see adjusting the li state comparisons, extending
3462 * the comparison to the PO's state, and/or providing functions
3463 * that house the logic for comparing states in a single location.
3465 * Yes, this will be really annoying if you have selected a lot
3466 * of lineitems to cancel that have been ordered. You'll get a
3467 * confirm dialog for each one.
3470 if (!confirm(localeStrings.DEL_LI_FROM_PO)) {
3471 self._deleteLiList(list, ++idx); /* move on to next in list */
3476 fieldmapper.standardRequest(
3478 this.isPO ? 'open-ils.acq.purchase_order.lineitem.delete' : 'open-ils.acq.picklist.lineitem.delete'],
3480 params: [openils.User.authtoken, liId],
3481 oncomplete: function(r) {
3482 self.removeLineitem(liId);
3483 self._deleteLiList(list, ++idx);
3489 this.editOrderMarc = function(li) {
3491 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
3492 to true in about:config */
3494 if(openils.XUL.isXUL()) {
3495 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul','','chrome');
3497 win = window.open('/xul/server/cat/marcedit.xul','','chrome');
3501 record : {marc : li.marc(), "rtype": "bre"},
3503 label: 'Save Record', // XXX I18N
3504 func: function(xmlString) {
3506 fieldmapper.standardRequest(
3507 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
3509 params: [openils.User.authtoken, li],
3510 oncomplete: function(r) {
3511 openils.Util.readResponse(r);
3513 self.drawInfo(li.id())
3519 'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
3520 'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
3524 this._savePl = function(values) {
3526 (values.which == 'all'),
3527 function(list) { self._savePlFromLineitems(values, list); }
3531 this._savePlFromLineitems = function(values, selected) {
3532 openils.Util.show("acq-lit-generic-progress");
3534 if(values.new_name) {
3535 openils.acq.Picklist.create(
3536 {name: values.new_name},
3542 oilsBasePath + "/acq/picklist/view/" + id;
3547 } else if(values.existing_pl) {
3548 // update lineitems to use an existing picklist
3550 values.existing_pl, selected, 0,
3553 oilsBasePath + "/acq/picklist/view/" +
3560 this._updateLiState = function(values, state, state_filter) {
3561 progressDialog.show(true);
3563 (values.which == 'all'),
3565 self._updateLiStateFromLineitems(values, state, list);
3566 }, false /* id_list */, state_filter
3570 this._updateLiStateFromLineitems = function(values, state, selected) {
3571 if(!selected.length) {
3572 try { progressDialog.hide() } catch(E) {};
3573 alert(localeStrings.NO_LI_GENERAL);
3576 dojo.forEach(selected, function(li) {li.state(state);});
3577 self._updateLiList(null, selected, 0,
3578 // TODO consider inline updates for efficiency
3579 function() { location.href = location.href }
3583 this._updateLiList = function(pl, list, idx, oncomplete) {
3584 if(idx >= list.length) return oncomplete();
3586 if(pl != null) li.picklist(pl);
3587 litGenericProgress.update({maximum: list.length, progress: idx});
3588 new openils.acq.Lineitem({lineitem:li}).update(
3590 self._updateLiList(pl, list, ++idx, oncomplete);
3595 this._loadPOSelect = function() {
3596 if (!this.createPoProviderSelector) {
3597 var widget = new openils.widget.AutoFieldWidget({
3598 "fmField": "provider",
3600 "searchFilter": {"active": "t"},
3601 "parentNode": dojo.byId("acq-lit-po-provider"),
3603 "onChange": function() {
3605 self._updateCreatePoPrepayCheckbox(
3606 this.item.prepayment_required()
3612 widget.build(function(w) { self.createPoProviderSelector = w; });
3615 this.createPoCheckDupes = function() {
3616 var org = self.createPoAgencySelector.attr('value');
3617 var name = self.createPoNameInput.attr('value');
3618 openils.Util.hide('acq-dupe-po-name');
3621 acqLitCreatePoSubmit.attr('disabled', false);
3625 acqLitCreatePoSubmit.attr('disabled', true);
3626 var orgs = fieldmapper.aou.descendantNodeList(org, true);
3627 new openils.PermaCrud().search('acqpo',
3628 {name : name, ordering_agency : orgs},
3629 {async : true, oncomplete : function(r) {
3630 var po = openils.Util.readResponse(r);
3632 if (po && (po = po[0])) {
3634 var link = dojo.byId('acq-dupe-po-link');
3635 openils.Util.show('acq-dupe-po-name', 'table-row');
3636 var dupe_path = '/acq/po/view/' + po.id();
3640 if (window.IAMBROWSER) {
3641 // TODO: integration
3645 link.onclick = function() {
3647 var loc = xulG.url_prefix('XUL_BROWSER?url=') +
3648 window.encodeURIComponent(
3649 xulG.url_prefix('EG_WEB_BASE' + dupe_path)
3653 {tab_name: '', browser:false},
3656 show_nav_buttons : true,
3657 show_print_button : true,
3664 link.onclick = function() {
3665 window.open(oilsBasePath + dupe_path, '_blank').focus();
3670 acqLitCreatePoSubmit.attr('disabled', false);
3676 if (!this.createPoAgencySelector) {
3677 var widget = new openils.widget.AutoFieldWidget({
3678 "fmField": "ordering_agency",
3680 "parentNode": dojo.byId("acq-lit-po-agency"),
3681 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3683 widget.build(function(w) {
3684 self.createPoAgencySelector = w;
3685 dojo.connect(w, 'onChange', self.createPoCheckDupes);
3689 if (!this.createPoNameInput) {
3690 var widget = new openils.widget.AutoFieldWidget({
3693 "parentNode": dojo.byId("acq-lit-po-name"),
3694 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3696 widget.build(function(w) {
3697 self.createPoNameInput = w;
3698 dojo.connect(w, 'onChange', self.createPoCheckDupes);
3703 this.showRealCopyEditUI = function(li) {
3708 this._fetchLineitem(li.id(),
3710 li = self.liCache[li.id()] = fullLi;
3714 id : li.lineitem_details().map(
3715 function(item) { return item.eg_copy_id() }
3719 oncomplete : function(r) {
3721 var r_list = openils.Util.readResponse( r );
3722 for (var i = 0; i < r_list.length; i++) {
3723 var copy = r_list[i];
3724 var volId = copy.call_number();
3725 var volume = self.volCache[volId];
3727 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
3729 copy.call_number(volume);
3730 copyList.push(copy);
3733 xulG.volume_item_creator( { 'existing_copies' : copyList } );
3736 alert('error in oncomplete: ' + E);
3745 this.drawBibFinder = function(li) {
3748 var liWrapper = new openils.acq.Lineitem({lineitem:li});
3751 ['isbn', 'upc', 'issn', 'title', 'author'],
3753 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
3755 if(field == 'title' || field == 'author') {
3756 query += field +':' + val + ' ';
3758 query += 'identifier|' + field + ':' + val + ' ';
3764 if(openils.XUL.isXUL() && !window.IAMBROWSER) {
3766 oilsBasePath + '/acq/lineitem/findbib?query=' + encodeURIComponent(query),
3767 '', 'resizable,scrollbars=1,chrome');
3769 win = window.open( oilsBasePath + '/acq/lineitem/findbib?query=' + encodeURIComponent(query));
3773 win.window.recordFound = function(bibId) {
3776 var attrs = li.attributes();
3777 li.attributes(null);
3778 li.eg_bib_id(bibId);
3780 fieldmapper.standardRequest(
3781 ["open-ils.acq", "open-ils.acq.lineitem.update"],
3783 "params": [openils.User.authtoken, li],
3785 "oncomplete": function(r) {
3786 if(openils.Util.readResponse(r)) {
3787 location.href = location.href;