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 if (li.source_label() !== null)
714 dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
716 // so we can scroll to it later
717 dojo.query('[name=bib-info-cell]', row)[0].id = 'li-title-ref-' + li.id();
720 liWrapper.findAttr("isbn", "lineitem_marc_attr_definition") ||
721 liWrapper.findAttr("upc", "lineitem_marc_attr_definition");
723 // XXX media prefix for added content
725 nodeByName("jacket", row).setAttribute(
726 "src", "/opac/extras/ac/jacket/small/" + identifier
730 nodeByName("liid", row).innerHTML += li.id();
732 var exist = nodeByName('li_existing_count', row);
733 fieldmapper.standardRequest(
734 ['open-ils.acq', 'open-ils.acq.lineitem.existing_copies.count'],
736 params: [this.authtoken, li.id()],
737 oncomplete : function(r) {
738 var count = openils.Util.readResponse(r);
739 exist.innerHTML = count;
740 if (Number(count) > 0) {
741 openils.Util.addCSSClass(
742 exist, 'acq-existing-count-warn');
746 label : dojo.string.substitute(
747 localeStrings.LI_EXISTING_COPIES, [count])
754 openils.Util.show(nodeByName('catalog', row), 'inline');
755 nodeByName("catalog_link", row).onclick = this.generateMakeRecTab(li.eg_bib_id());
757 openils.Util.show(nodeByName('link_to_catalog', row), 'inline');
758 nodeByName("link_to_catalog_link", row).onclick = function() { self.drawBibFinder(li) };
761 if (li.queued_record()) {
762 this.pcrud.retrieve('vqbr', li.queued_record(),
764 oncomplete : function(r) {
765 var qrec = openils.Util.readResponse(r);
766 openils.Util.show(nodeByName('queue', row), 'inline');
767 var link = nodeByName("queue_link", row);
768 link.onclick = function() {
769 var url = oilsBasePath + '/vandelay/vandelay?qtype=bib&qid=' + qrec.queue()
770 // open a new tab to the vandelay queue for this record
771 if (window.IAMBROWSER) {
774 openils.XUL.newTabEasy(url);
782 nodeByName("worksheet_link", row).href =
783 oilsBasePath + "/acq/lineitem/worksheet/" + li.id() +
784 '?source=' + encodeURIComponent(location.pathname + location.search)
786 nodeByName("show_requests_link", row).href =
787 oilsBasePath + "/acq/picklist/user_request?lineitem=" + li.id() +
788 '?source=' + encodeURIComponent(location.pathname + location.search)
790 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
791 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
792 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
793 dojo.query('[name=expand_inline_copies]', row)[0].onclick =
794 function() {self.drawInlineCopies(li.id())};
797 if (sum = li.order_summary()) { // assignment
798 // Only show the paid label if at least one copy is invoiced.
799 // In other words, a lineitem whose every copy is canceled
801 if (sum.invoice_count() > 0) {
802 if (sum.item_count() == (
803 sum.invoice_count() + sum.cancel_count())) {
804 // Lineitem is fully paid. Display the paid-off label
805 openils.Util.show(nodeByName('paid', row), 'inline');
810 this.drawOrderIdentSelector(li, row);
812 if (!this.skipInitialEligibilityCheck)
816 function(full) { self.setClaimPolicyControl(full, row) },
820 this.updateLiNotesCount(li, row);
822 // show which PO this lineitem is a member of
823 if(li.purchase_order() && !this.isPO) {
825 this.poCache[li.purchase_order()] =
826 this.poCache[li.purchase_order()] ||
827 fieldmapper.standardRequest(
828 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
830 this.authtoken, li.purchase_order(), {
831 "flesh_price_summary": true,
832 "flesh_provider" : true,
833 "flesh_lineitem_count": true
836 if(po && !this.isMeta) {
837 openils.Util.show(nodeByName('po', row), 'inline');
838 var link = nodeByName('po_link', row);
839 link.setAttribute('href', oilsBasePath +
840 '/acq/po/view/' + li.purchase_order() +
841 '?focus_li=' + li.id() +
842 '&source=' + encodeURIComponent(location.pathname + location.search)
844 link.innerHTML += po.name();
846 openils.Util.show(nodeByName('pro', row), 'inline');
847 link = nodeByName('pro_link', row);
848 link.setAttribute('href', oilsBasePath + '/conify/global/acq/provider/' + po.provider().id())
849 link.innerHTML += po.provider().code();
853 // show which picklist this lineitem is a member of
854 if(li.picklist() && (this.isPO || this.isMeta || this.isUni)) {
856 this.plCache[li.picklist()] =
857 this.plCache[li.picklist()] ||
858 fieldmapper.standardRequest(
859 ['open-ils.acq', 'open-ils.acq.picklist.retrieve.authoritative'],
860 {params: [this.authtoken, li.picklist()]});
862 if (pl.name() == "") {
863 openils.Util.show(nodeByName("bib_origin", row), "inline");
867 openils.Util.show(nodeByName('pl', row), 'inline');
868 var link = nodeByName('pl_link', row);
869 link.setAttribute('href', oilsBasePath +
870 '/acq/picklist/view/' + li.picklist() +
871 '?focus_li=' + li.id() +
872 '&source=' + encodeURIComponent(location.pathname + location.search)
874 link.innerHTML += pl.name();
879 var countNode = nodeByName('count', row);
880 var count = li.item_count() || 0;
881 if (typeof(this._copy_count_cb) == "function") {
882 this._copy_count_cb(li.id(), count);
884 countNode.innerHTML = count;
885 countNode.id = 'acq-lit-copy-count-label-' + li.id();
888 var priceInput = dojo.query('[name=price]', row)[0];
889 priceInput.value = li.estimated_unit_price() || '';
890 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
892 // show either "mark received" or "unreceive" as appropriate
893 this.updateLiState(li, row);
895 if (skip_final_placement) {
899 // the last LI may be rendered after the call to show('list'),
900 // so make sure it's focused if necessary.
901 if (this.focusLineitem == li.id())
905 this._liCountClaims = function(li) {
907 for (var i = 0; i < li.lineitem_details().length; i++)
908 total += li.lineitem_details()[i].claims().length;
912 this._findLiRow = function(li) {
913 return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
916 this.reconsiderClaimControl = function(li, row) {
917 if (!row) row = this._findLiRow(li);
918 var option = nodeByName("action_manage_claims", row);
919 var eligible = this.claimEligibleLidByLi[li.id()].length;
920 var count = this._liCountClaims(li);
922 option.disabled = !(count || eligible);
924 dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
925 option.onclick = function() { self.claimDialog.show(li); };
928 this.clearEligibility = function(li) {
929 this.claimEligibleLidByLi[li.id()] = [];
931 if (li.lineitem_details()) {
932 li.lineitem_details().forEach(
933 function(lid) { delete self.claimEligibleLid[lid.id()]; }
937 if (this.copyCache) {
939 for (var k in this.copyCache) {
940 if (this.copyCache[k].lineitem() == li.id())
944 function(k) { delete self.claimEligibleLid[k]; }
949 this.applyOrderIdentValues = function() {
950 this._identValuesInFlight =
951 openils.Util.objectProperties(this.liCache).length;
952 for (var liId in this.liCache) {
953 this._applyOrderIdentValue(this.liCache[liId]);
957 // returns true if request was sent
958 this._applyOrderIdentValue = function(li, oncomplete) {
961 console.log('applying ident value for lineitem ' + li.id());
964 var row = dojo.query('[li=' + li.id() + ']')[0];
966 // find the selected ident value
967 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
968 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
969 var name = typeSel.options[typeSel.selectedIndex].value;
970 var val = typeSel._cbox.attr('value');
972 console.log("selected ident is " + val);
974 // it differs from the existing ident value, update it
975 var oldIdent = self.getLiOrderIdent(li);
977 oldIdent.attr_name() == name &&
978 oldIdent.attr_value() == val) {
979 console.log('selected ident attr matches existing attr');
980 if (--this._identValuesInFlight == 0) {
981 if (oncomplete) oncomplete(li);
982 else location.href = location.href;
987 // see if the selected ident value is represented
988 // by an existing lineitem attr
991 typeSel._cbox.store.fetch({
992 query : {attr_value : val},
993 onItem : function(item) {
994 console.log('found existing attr for ident value');
995 args.source_attr_id = li.attributes().filter(
996 function(attr) { return attr.id() == item.id[0] }
1002 if (!args.source_attr_id) {
1003 // user entered new text in the combobox
1004 // so we need to create a new attr
1005 console.log('creating new ident attr');
1006 args.lineitem_id = li.id();
1007 args.attr_name = name;
1008 args.attr_value = val;
1011 fieldmapper.standardRequest(
1012 ['open-ils.acq', 'open-ils.acq.lineitem.order_identifier.set'],
1014 params : [openils.User.authtoken, args],
1015 oncomplete : function() {
1016 console.log('order_ident oncomplete');
1017 if (--self._identValuesInFlight == 0) {
1018 if (oncomplete) oncomplete(li);
1019 else location.href = location.href;
1021 console.log(self._identValuesInFlight + ' still in flight');
1029 this.getLiOrderIdent = function(li) {
1030 var attrs = li.attributes();
1031 if (!attrs) return null;
1032 return attrs.filter(
1035 attr.attr_type() == 'lineitem_local_attr_definition' &&
1036 openils.Util.isTrue(attr.order_ident())
1042 this.drawOrderIdentSelector = function(li, row) {
1044 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
1045 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
1047 var attrs = li.attributes();
1049 // limit to MARC attr defs
1050 attrs = attrs.filter(
1052 return (attr.attr_type() == 'lineitem_marc_attr_definition');
1056 var identAttr = this.getLiOrderIdent(li);
1059 // collect the values for each type of identifier
1060 // find a reasonable default identifier type to render
1064 dojo.forEach(['isbn', 'upc', 'issn'],
1067 // collect the values for this attr name
1068 values[name] = attrs.filter(
1070 return (attr.attr_name() == name)
1074 // select a reasonable default name in the type-selector
1078 if (identAttr.attr_name() == name)
1080 } else if (values[name].length) {
1085 dojo.forEach(typeSel.options, function(opt) {
1086 if (opt.value == name) {
1087 opt.selected = true;
1096 function updateOrderIdent(val) {
1097 self._identValuesInFlight = 1;
1098 self._applyOrderIdentValue(
1101 self.refreshLineitem(li);
1106 // replace the ident combobox with a new
1107 // one for the selected ident type
1108 function changeComboBox(sel) {
1109 var name = sel.options[sel.selectedIndex].value;
1111 var td = dojo.query('[name=order_ident_value]', row)[0];
1112 if (td.childNodes[0])
1113 dojo.destroy(td.childNodes[0]);
1115 var store = new dojo.data.ItemFileWriteStore({
1116 data : acqlia.toStoreData(values[name])
1119 var cbox = new dijit.form.ComboBox(
1121 labelAttr : 'attr_value',
1122 searchAttr : 'attr_value'
1124 dojo.create('div', {}, td)
1129 // set the value for the cbox
1130 if (values[name].length) {
1131 var orderIdent = self.getLiOrderIdent(li);
1133 if (orderIdent && orderIdent.attr_name() == name) {
1134 cbox.attr('value', orderIdent.attr_value());
1136 cbox.attr('value', values[name][0].attr_value());
1140 if (!self.orderIdentAllowed)
1141 cbox.attr('disabled', true);
1144 cbox._lineitem = li;
1145 dojo.connect(cbox, 'onChange', updateOrderIdent);
1148 changeComboBox(typeSel); // force the initial draw
1149 typeSel.onchange = function() {changeComboBox(typeSel)};
1152 this.testOrderIdentPerms = function(org, callback) {
1154 new openils.User().getPermOrgList(
1155 'ACQ_SET_LINEITEM_IDENTIFIER',
1157 console.log('found orgs = ' + orgs);
1158 for (var i = 0; i < orgs.length; i++) {
1159 if (Number(orgs[i]) == Number(org)) {
1160 self.orderIdentAllowed = true;
1161 if (callback) callback();
1165 if (callback) callback();
1171 this.checkClaimEligibility = function(li, callback, row) {
1172 /* Assume always eligible, i.e. from this interface we don't care about
1173 * claim eligibility any more. this is where the user would force a
1175 this.clearEligibility(li);
1176 this.claimEligibleLidByLi[li.id()] = li.lineitem_details().map(
1177 function(lid) { return lid.id(); }
1179 li.lineitem_details().forEach(
1180 function(lid) { self.claimEligibleLid[lid.id()] = true; }
1182 this.reconsiderClaimControl(li, row);
1183 if (callback) callback(li);
1185 this.clearEligibility(li);
1186 fieldmapper.standardRequest(
1187 ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
1188 "params": [openils.User.authtoken, {"lineitem": li.id()}],
1190 "onresponse": function(r) {
1191 if (r = openils.Util.readResponse(r)) {
1192 self.claimEligibleLidByLi[li.id()].push(
1195 self.claimEligibleLid[r.lineitem_detail()] = true;
1198 "oncomplete": function() {
1199 self.reconsiderClaimControl(li, row);
1200 if (typeof(callback) == "function")
1208 this.updateLiNotesCount = function(li, row) {
1209 if (!row) row = this._findLiRow(li);
1211 var has_notes = (li.lineitem_notes().filter(
1212 function(o) { return Boolean (o.alert_text()); }
1215 /* U+2691 is the code point for a filled-in flag character */
1216 nodeByName("notes_alert_flag", row).innerHTML =
1217 has_notes ? "⚑" : "";
1218 nodeByName("noteslink", row).style.fontStyle =
1219 has_notes ? "italic" : "normal";
1220 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
1223 /* XXX NOT related to _updateLiState(). rethink */
1224 this.updateLiState = function(li, row) {
1225 if (!row) row = this._findLiRow(li);
1227 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
1228 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
1230 // always allow access to LI history
1231 nodeByName('action_view_history', row).onclick =
1232 function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
1234 /* handle row coloring for based on LI state */
1235 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1236 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
1238 // Expose invoice actions for any lineitem that is linked to a PO
1239 if (li.purchase_order()) {
1240 openils.Util.show(nodeByName("invoices_span", row), "inline");
1241 var link = nodeByName("invoices_link", row);
1242 link.onclick = function() {
1243 var url = oilsBasePath + "/acq/search/unified?so=" +
1244 base64Encode({"jub":[{"id": li.id()}]}) + "&rt=invoice"
1245 if (window.IAMBROWSER) {
1246 xulG.relay_url(url);
1248 openils.XUL.newTabEasy(url);
1256 * If we haven't fleshed the lineitem_details, default to allowing access to the
1257 * holdings maintenence actions. The alternative is to flesh LIDs on every lineitem,
1258 * but that will add to page render time. Let's see if this will suffice...
1260 var lids = li.lineitem_details();
1262 (lids && !lids.filter(function(lid) { return lid.eg_copy_id() })[0] )) {
1264 actUpdateBarcodes.disabled = false;
1265 actUpdateBarcodes.onclick = function() {
1266 self.showRealCopyEditUI(li);
1267 nodeByName("action_none", row).selected = true;
1269 actHoldingsMaint.disabled = false;
1270 actHoldingsMaint.onclick =
1271 self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
1274 var state_cell = nodeByName("li_state_" + li.state(), row);
1276 // re-hide any state label nodes which may have been un-hidden
1277 // through previous actions.
1278 dojo.query('[state-label]', row).forEach(function(node) {
1279 openils.Util.hide(node)
1282 if (li.state() == 'cancelled') {
1283 if(typeof li.cancel_reason() == "object") {
1285 // clear the stock "Canceled" label, since we have more
1286 // information to replace it with.
1287 state_cell.innerHTML = '';
1289 var holds_state = dojo.create(
1291 "style": "border-bottom: 1px dashed #000;",
1292 "innerHTML": li.cancel_reason().label()
1293 }, state_cell, "only"
1297 "label": "<em>" + li.cancel_reason().label() +
1298 "</em><br />" + li.cancel_reason().description(),
1299 "connectId": [holds_state]
1300 }, dojo.create("span", null, state_cell, "last")
1303 if (li.cancel_reason().keep_debits() == 't') {
1304 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1305 openils.Util.addCSSClass(row, "oils-acq-li-state-delayed");
1308 console.log('li cancel_reason is un-fleshed. Please fix');
1312 openils.Util.show(state_cell);
1316 this._setAlertStore = function() {
1317 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
1319 "data": acqliat.toStoreData(
1322 "owning_lib": aou.orgNodeTrail(
1323 aou.findOrgUnit(openils.User.user.ws_ou())
1324 ).map(function(o) { return o.id(); })
1330 acqLitAlertAlertText.setValue(); /* make the store "live" */
1331 acqLitAlertAlertText._store_ready = true;
1335 * Draws and shows the lineitem notes pane
1337 this.drawLiNotes = function(li) {
1339 this.focusLineitem = li.id();
1341 if (!acqLitAlertAlertText._store_ready)
1342 this._setAlertStore();
1345 li.lineitem_notes().sort(
1347 if(a.edit_time() < b.edit_time()) return 1;
1353 while(this.liNotesTbody.childNodes[0])
1354 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
1357 acqLitCreateNoteSubmit.onClick = function() {
1358 var value = acqLitCreateNoteText.attr('value');
1360 var note = new fieldmapper.acqlin();
1363 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
1366 note.lineitem(li.id());
1368 self.updateLiNotes(li, note);
1369 acqLitCreateNoteVendorPublic.attr("checked", false);
1370 acqLitCreateNoteText.attr("value", "");
1373 acqLitCreateAlertSubmit.onClick = function() {
1374 if (!acqLitAlertAlertText.item) {
1375 alert(localeStrings.ALERT_UNSELECTED);
1379 var alert_text = new fieldmapper.acqliat().fromStoreItem(
1380 acqLitAlertAlertText.item
1382 var value = acqLitAlertNoteValue.attr("value") || "";
1384 var note = new fieldmapper.acqlin();
1386 note.lineitem(li.id());
1388 note.alert_text(alert_text);
1390 self.updateLiNotes(li, note);
1393 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
1397 * Draws a single lineitem note in the notes pane
1399 this.addLiNote = function(li, note) {
1400 if(note.isdeleted()) return;
1402 var row = self.liNotesRow.cloneNode(true);
1403 nodeByName("value", row).innerHTML = note.value();
1404 var alert_node = nodeByName("alert_code", row);
1405 if (note.alert_text()) {
1406 alert_node.innerHTML = dojo.string.substitute(
1408 aou.findOrgUnit(note.alert_text().owning_lib()).shortname(),
1409 note.alert_text().code()
1412 if (note.alert_text().description()) {
1415 "connectId": [alert_node],
1416 "label": note.alert_text().description()
1417 }, dojo.create("span", null, alert_node, "after")
1422 if (openils.Util.isTrue(note.vendor_public()))
1423 nodeByName("vendor_public", row).innerHTML =
1424 localeStrings.VENDOR_PUBLIC;
1426 nodeByName("delete", row).onclick = function() {
1427 note.isdeleted(true);
1428 self.liNotesTbody.removeChild(row);
1429 self.updateLiNotes(li);
1432 if(note.edit_time()) {
1433 nodeByName("edit_time", row).innerHTML =
1434 dojo.date.locale.format(
1435 dojo.date.stamp.fromISOString(note.edit_time()),
1436 {formatLength:'short'});
1439 self.liNotesTbody.appendChild(row);
1443 * Updates any new/changed/deleted notes on the server
1445 this.updateLiNotes = function(li, newNote) {
1451 notes = li.lineitem_notes().filter(
1453 if(note.ischanged() || note.isnew() || note.isdeleted())
1459 if(notes.length == 0) return;
1460 progressDialog.show();
1462 fieldmapper.standardRequest(
1463 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
1465 params : [this.authtoken, notes],
1466 onresponse : function(r) {
1467 var resp = openils.Util.readResponse(r);
1472 // remove the old changed notes
1474 dojo.forEach(li.lineitem_notes(),
1476 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
1480 li.lineitem_notes(list);
1483 progressDialog.hide();
1484 self.updateLiNotesCount(li);
1485 self.drawLiNotes(li);
1489 progressDialog.update(resp);
1490 var newnote = resp.note;
1492 if(!newnote.isdeleted()) {
1493 newnote.isnew(false);
1494 newnote.ischanged(false);
1495 li.lineitem_notes().push(newnote);
1502 this.updateLiPrice = function(input, li) {
1504 var price = input.value;
1505 if(Number(price) == Number(li.estimated_unit_price())) return;
1507 fieldmapper.standardRequest(
1508 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
1509 { async : false, // redundant w/ timeout
1511 params : [this.authtoken, li.id(), price],
1512 oncomplete : function(r) {
1513 openils.Util.readResponse(r);
1514 li.estimated_unit_price(price); // update local copy
1517 * If this is a PO and every visible lineitem has a price,
1518 * check again to see if this PO can be activated. Note that
1519 * every visible lineitem having a price does not guarantee it can
1520 * be activated, which is why we still make the call. Having a price
1521 * set for every visiable lineitem is just the lowest barrier to entry.
1524 var priceNodes = dojo.query('[name=price]', dojo.byId('acq-lit-tbody'));
1526 dojo.forEach(priceNodes, function(node) { if (node.value == '') allSet = false});
1527 if (allSet) checkCouldActivatePo();
1528 refreshPOSummaryAmounts();
1535 this.removeLineitem = function(liId) {
1536 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
1537 delete this.liCache[liId];
1538 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
1541 this.drawInfo = function(liId) {
1542 this.focusLineitem = liId;
1543 if (!this._isRelatedViewer) {
1544 var d = dojo.byId("acq-lit-info-related");
1545 if (!this.relCache[liId]) {
1546 fieldmapper.standardRequest(
1549 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
1552 "params": [openils.User.authtoken, liId],
1553 "onresponse": function(r) {
1554 self.relCache[liId] = openils.Util.readResponse(r);
1555 nodeByName("related_number", d).innerHTML =
1556 self.relCache[liId];
1558 self.relCache[liId] >1 ? "show" : "hide"
1564 nodeByName("related_number", d).innerHTML = this.relCache[liId];
1565 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
1570 openils.acq.Lineitem.fetchAttrDefs(
1572 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
1577 this.toggleInlineCopies = function() {
1578 // if any inline copies are not displayed,
1579 // display them all otherwise, hide them all.
1581 var displayAll = false;
1583 for (var liId in this.liCache) {
1584 if (!this.inlineCopiesVisible(liId)) {
1590 for (var liId in this.liCache) {
1591 var row = dojo.byId('acq-inline-copies-row-' + liId);
1593 if (!row || row._hidden) {
1594 this.drawInlineCopies(liId);
1596 } else { // hide all
1598 // drawInlineCopies() on a visible row will hide it.
1599 this.drawInlineCopies(liId);
1606 this.inlineCopiesVisible = function(liId) {
1607 var row = dojo.byId('acq-inline-copies-row-' + liId);
1608 return (row && !row._hidden);
1611 this.refreshInlineCopies = function(all, reFetch) {
1613 var liIds = this.inlineCopiesNeedingRefresh;
1614 if (all) liIds = openils.Util.objectProperties(liCache);
1615 liIds.forEach(function(liId) {
1616 if (self.inlineCopiesVisible(liId)) {
1617 self.drawInlineCopies(liId, reFetch); // hide
1618 self.drawInlineCopies(liId, reFetch); // re-draw
1623 // draw inline copy table. if the table is
1624 // already visible, hide the table as-is
1625 // reFetch forces a retrieval of the lineitem and
1626 // copies from the server. otherwise the locally
1627 // cached version of each is used.
1628 this.drawInlineCopies = function(liId, reFetch) {
1631 // find or create the row where the inline copies table will live
1632 var containerRow = dojo.byId('acq-inline-copies-row-' + liId);
1633 var liRow = dojo.query('[li=' + liId + ']')[0];
1635 if (!containerRow) {
1637 // build the inline copies container row and add it to
1638 // the DOM directly after the primary lineitem row
1640 containerRow = self.inlineCopyContainer.cloneNode(true);
1641 containerRow.id = 'acq-inline-copies-row-' + liId;
1643 if (liRow.nextSibling) {
1644 self.tbody.insertBefore(containerRow, liRow.nextSibling);
1646 self.tbody.appendChild(containerRow);
1651 // toggle the visible state
1652 containerRow._hidden = !containerRow._hidden;
1653 openils.Util.toggle(containerRow, 'table-row');
1655 if (containerRow._hidden) return; // hide only
1658 var handler = function(li) {
1660 var tbody = dojo.query(
1661 '[name=acq-li-inline-copies-tbody]',
1664 // reset the table before adding copy rows
1665 while (tbody.childNodes[0])
1666 tbody.removeChild(tbody.childNodes[0]);
1668 if(li.lineitem_details().length == 0) {
1670 self.inlineNoCopies.cloneNode(true));
1671 return; // no copies to show
1674 // add a row to the inline copy table for each copy
1675 dojo.forEach(li.lineitem_details(),
1677 var row = self.inlineCopyTemplate.cloneNode(true);
1678 tbody.appendChild(row);
1679 self.addInlineCopy(li, copy, row);
1684 this._fetchLineitem(liId, handler, reFetch);
1687 /** Draw read-only copy widgets for inline copies */
1688 this.addInlineCopy = function(li, copy, row) {
1691 dojo.forEach(liDetailFields,
1694 var widget = new openils.widget.AutoFieldWidget({
1697 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1698 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1699 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1701 parentNode : dojo.query('[name=' + field + ']', row)[0],
1710 /* For a given list of lineitem ids, build a list of full lineitems
1711 * re-using the fetching logic that is otherwise typical to use in this
1714 * If we've already got a lineitem in the cache, just use that.
1716 * Once we've built a list of lineitems, call callback(thatlist).
1718 this.fetchLineitemsById = function(id_list, callback) {
1719 var total = id_list.length;
1720 var result_list = [];
1722 var inner = function(li) {
1723 result_list.push(li)
1725 callback(result_list);
1728 id_list.forEach(function(id) { self._fetchLineitem(id, inner); });
1731 this._fetchLineitem = function(liId, handler, force) {
1733 var li = this.liCache[liId];
1734 if(li && li.marc() && li.lineitem_details() && !force)
1737 fieldmapper.standardRequest(
1738 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
1741 params: [self.authtoken, liId, {
1743 flesh_cancel_reason: true,
1744 flesh_li_details: true,
1746 flesh_fund_debit: true }],
1748 oncomplete: function(r) {
1749 var li = openils.Util.readResponse(r);
1750 self.liCache[liId] = li;
1757 this._drawInfo = function(li) {
1759 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
1761 if(li.eg_bib_id()) {
1762 openils.Util.hide('acq-lit-marc-order-record-label');
1763 openils.Util.hide(acqLitEditOrderMarc.domNode);
1764 openils.Util.show('acq-lit-marc-real-record-label');
1766 openils.Util.show('acq-lit-marc-order-record-label');
1767 openils.Util.show(acqLitEditOrderMarc.domNode);
1768 openils.Util.hide('acq-lit-marc-real-record-label');
1771 this.drawMarcHTML(li);
1772 this.infoTbody = dojo.byId('acq-lit-info-tbody');
1775 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
1776 while(this.infoTbody.childNodes[0])
1777 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
1779 for(var i = 0; i < li.attributes().length; i++) {
1780 var attr = li.attributes()[i];
1781 var row = this.infoRow.cloneNode(true);
1783 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
1784 var name = openils.acq.Lineitem.attrDefs[type].filter(
1786 return (a.code() == attr.attr_name());
1788 ).pop().description();
1790 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
1791 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
1792 this.infoTbody.appendChild(row);
1795 if (!this._isRelatedViewer) {
1796 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
1797 oilsBasePath + "/acq/lineitem/related/" + li.id();
1800 // if a top scroll point is defined, jump up to it here
1801 var node = dojo.byId('oils-scroll-to-top');
1802 if (node) dijit.scrollIntoView(node);
1805 this.generateMakeRecTab = function(bib_id,default_view, row) {
1807 if(openils.XUL.isXUL() && !window.IAMBROWSER) {
1810 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
1813 show_nav_buttons : true,
1814 show_print_button : true,
1815 opac_url : xulG.url_prefix('opac_rdetail|' + bib_id),
1816 default_view : default_view
1820 var url = '/eg/staff/cat/catalog/record/' + bib_id;
1821 if (default_view == 'copy_browser') {
1827 if(row) nodeByName("action_none", row).selected = true;
1831 this.drawMarcHTML = function(li) {
1832 var params = [null, true, li.marc()];
1834 params = [li.eg_bib_id(), true];
1836 fieldmapper.standardRequest(
1837 ['open-ils.search', 'open-ils.search.biblio.record.html'],
1840 oncomplete: function(r) {
1841 dojo.byId('acq-lit-marc-div').innerHTML =
1842 openils.Util.readResponse(r);
1848 this.drawCopies = function(liId, force_fetch) {
1849 this.focusLineitem = liId;
1850 if (typeof force_fetch == "undefined")
1851 force_fetch = false;
1853 var cgi = new openils.CGI();
1854 var source = cgi.param('source');
1855 if (source && source.match(/invoice/)) {
1856 // got here from the invoice page, show the 'return-to-invoice' button
1857 var cgi = new openils.CGI({url : source});
1858 cgi.param('focus_li', liId);
1859 openils.Util.show(dojo.byId('acq-lit-copies-back-to-invoice-button-wrapper'), 'inline');
1860 var button = dojo.byId('acq-lit-copies-back-to-invoice-button');
1861 button.onclick = function() { location.href = cgi.url() };
1864 openils.acq.Lineitem.fetchAndRender(liId, {},
1865 function(li, html) {
1866 dojo.byId('acq-lit-copies-li-summary').innerHTML = html;
1870 this.show('copies');
1872 this.copyCache = {};
1873 this.copyWidgetCache = {};
1874 this.oldCopyWidgetCache = {};
1875 this.virtDfaCounts = {};
1876 this.realDfaCache = {};
1879 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
1880 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
1881 acqLitCopyCountInput.attr('value', '0');
1883 if (this.isPO && PO && PO.order_date()) {
1884 // prevent adding copies to activated POs
1885 acqLitCopyCountInput.attr('disabled', true);
1886 acqLitAddCopyCount.attr('disabled', true);
1889 while(this.copyTbody.childNodes[0])
1890 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
1892 this._drawBatchCopyWidgets();
1894 this._drawDistribApplied(liId);
1896 this._fetchDistribFormulas(
1898 openils.acq.Lineitem.fetchAttrDefs(
1900 self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch);
1907 this._saveDistribAppliedTemplates = function() {
1908 if (!this._appliedDistribTemplate) {
1909 this._appliedDistribTemplate =
1910 dojo.byId("acq-lit-distrib-applied-tbody").
1911 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
1912 dojo.attr(this._appliedDistribTemplate, "id");
1916 this._drawDistribApplied = function(liId) {
1917 /* Build this table while hidden to prevent rendering artifacts */
1918 openils.Util.hide("acq-lit-distrib-applied-tbody");
1920 this._saveDistribAppliedTemplates();
1922 /* Remove any rows in the table from previous populations */
1923 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
1924 forEach(dojo.destroy);
1926 /* Unregister all dijits previously created (for some reason this isn't
1927 * covered by the above destroy calls). */
1928 dijit.registry.forEach(
1929 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
1932 /* Populate the table with our liId */
1934 fieldmapper.standardRequest(
1936 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
1939 "params": [self.authtoken, liId],
1940 "onresponse": function(r) {
1941 var dfa = openils.Util.readResponse(r);
1944 self.realDfaCache[dfa.id()] = dfa;
1945 self._drawDistribAppliedUnit(dfa);
1948 "oncomplete": function() {
1949 /* Reveal built table */
1952 "acq-lit-distrib-applied-tbody", "table-row-group"
1960 this._drawDistribAppliedUnit = function(dfa) {
1961 var new_row = false;
1962 var row = dojo.query(
1963 'tr[formula="' + dfa.formula().id() + '"]',
1964 "acq-lit-distrib-applied-tbody"
1969 row = dojo.clone(this._appliedDistribTemplate);
1970 dojo.attr(row, "formula", dfa.formula().id());
1971 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
1974 var td = dojo.query("td", row)[0];
1976 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1977 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1980 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1982 new dijit.form.Button(
1984 "onClick": function() {
1985 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1986 self.deleteDfa(dfa);
1989 /* XXX I /cannot/ make the following work in as a CSS class
1990 * for some reason. So frustrating... */
1991 "style": function(id) {
1993 "font-weight: bold; color: #c00;" :
1995 }(dfa.id()) + "margin: 0 6px;display: inline;"
1996 }, "dfa-button-" + dfa.id()
2000 "connectId": ["dfa-button-" + dfa.id()],
2001 "label": dojo.string.substitute(
2002 localeStrings.DFA_TIP, dfa.id() > 0 ? [
2003 openils.User.formalName(dfa.creator()),
2004 dojo.date.locale.format(
2005 dojo.date.stamp.fromISOString(dfa.create_time()),
2006 {"formatLength":"short"}
2008 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
2010 }, "dfa-tip-" + dfa.id()
2014 this.deleteDfa = function(dfa) {
2015 if (dfa.id() > 0) { /* real */
2016 this.pcrud.eliminate(
2019 "oncomplete": function() {
2020 self._removeDistribApplied(dfa.id());
2021 delete self.realDfaCache[dfa.id()];
2025 } else { /* virtual */
2026 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
2027 this.virtDfaCounts[dfa.formula().id()] = 0;
2028 /* hasn't been saved yet, so no need to do anything server side */
2029 this._removeDistribApplied(dfa.id());
2034 this._removeDistribApplied = function(dfaId) {
2035 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
2036 dijit.registry.forEach(
2037 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
2039 this._removeDistribAppliedEmptyRows();
2042 this._removeAllDistribAppliedVirtual = function() {
2043 /* Unregister dijits */
2044 dijit.registry.forEach(
2045 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
2047 this._removeDistribAppliedEmptyRows();
2050 this._removeDistribAppliedEmptyRows = function() {
2051 /* Remove any rows with no DFA at all */
2052 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
2054 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
2060 * Insert a new row into the distribution formula selection form
2062 this._addDistribFormulaRow = function() {
2065 if (!self.distribForms) {
2066 // no formulas, hide the form
2067 openils.Util.hide('acq-lit-distrib-formula-table');
2071 if(!this.distribFormulaTemplate)
2072 this.distribFormulaTemplate =
2073 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
2075 var row = this.distribFormulaTemplate.cloneNode(true);
2076 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
2078 this.dfSelector = new dijit.form.FilteringSelect(
2079 {"labelAttr": "dynLabel", "labelType": "html"},
2080 nodeByName("selector", row)
2082 this._updateFormulaStore();
2083 this.dfSelector.fetchProperties =
2084 {"sort": [{"attribute": "use_count", "descending": true}]};
2086 var apply = new dijit.form.Button(
2087 {"label": localeStrings.APPLY},
2088 nodeByName('set_button', row)
2091 var reset = new dijit.form.Button(
2092 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
2093 nodeByName("reset_button", row)
2096 dojo.connect(apply, 'onClick',
2098 var form_id = self.dfSelector.attr("value");
2099 if(!form_id) return;
2100 self._applyDistribFormula(form_id);
2101 reset.attr("disabled", false);
2105 dojo.connect(reset, 'onClick',
2107 self.restoreCopyFieldsBeforeDF();
2108 self.virtDfaCounts = {};
2109 self.virtDfaId = -1;
2111 self._updateFormulaStore();
2112 self._removeAllDistribAppliedVirtual();
2113 reset.attr("disabled", "true");
2120 * Applies a distrib formula to the current set of copies
2122 this._applyDistribFormula = function(formula) {
2123 if(!formula) return;
2125 formula = this.distribForms.filter(
2126 function(form) { return form.id() == formula; }
2129 var copyRows = dojo.query('tr', self.copyTbody);
2131 if (this.dfeOffset >= copyRows.length) {
2132 alert(localeStrings.OUT_OF_COPIES);
2136 var entries_applied = 0;
2138 var rowIndex = this.dfeOffset;
2139 rowIndex < copyRows.length;
2143 var row = copyRows[rowIndex];
2144 var copy_id = row.getAttribute('copy_id');
2145 var copyWidgets = this.copyWidgetCache[copy_id];
2146 var entryIndex = this.dfeOffset;
2149 // find the correct entry for the current row
2150 dojo.forEach(formula.entries(),
2153 entryIndex += e.item_count();
2154 if(entryIndex > rowIndex)
2162 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
2163 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
2166 this.saveCopyFieldsBeforeDF(copy_id);
2167 this._copy_fields_for_acqdf.forEach(
2169 if(entry[field]()) {
2170 copyWidgets[field].attr('value', (entry[field]()));
2177 if (entries_applied) {
2178 this.virtDfaCounts[formula.id()] =
2179 ++(this.virtDfaCounts[formula.id()]) || 1;
2180 this._updateFormulaStore();
2181 this._drawDistribAppliedUnit(
2183 var dfa = new acqdfa();
2184 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
2187 this.dfeOffset += entries_applied;
2192 * This function updates the DF store for the dropdown so that use_counts
2193 * can reflect DF applications from this session before they're saved
2196 this._updateFormulaStore = function() {
2197 this.dfSelector.store = new dojo.data.ItemFileReadStore(
2199 "data": self._labelFormulasWithCounts(
2200 acqdf.toStoreData(self.distribForms)
2206 this.saveCopyFieldsBeforeDF = function(copy_id) {
2208 if (!this.oldCopyWidgetCache[copy_id]) {
2209 var copyWidgets = this.copyWidgetCache[copy_id];
2211 this.oldCopyWidgetCache[copy_id] = {};
2212 this._copy_fields_for_acqdf.forEach(
2214 self.oldCopyWidgetCache[copy_id][f] =
2215 copyWidgets[f].attr("value");
2221 this.restoreCopyFieldsBeforeDF = function() {
2223 for (var copy_id in this.oldCopyWidgetCache) {
2224 this._copy_fields_for_acqdf.forEach(
2226 self.copyWidgetCache[copy_id][f].attr(
2227 "value", self.oldCopyWidgetCache[copy_id][f]
2234 this._labelFormulasWithCounts = function(store_data) {
2235 for (var key in store_data.items) {
2236 var obj = store_data.items[key];
2237 obj.use_count = Number(obj.use_count); /* needed for sorting */
2239 if (this.virtDfaCounts[obj.id])
2240 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
2242 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
2243 obj.use_count + "]</span> " + obj.name;
2249 * This method formerly would not refetch the DF formulas if they'd been
2250 * loaded already, but now it always re-fetches, since use_count changes.
2252 /** TODO: port distrib-formula selector to autofieldwidget+pcrud/dojo store */
2253 this._fetchDistribFormulas = function(onload) {
2254 fieldmapper.standardRequest(
2256 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
2259 "params": [openils.User.authtoken, 0, 500],
2260 "oncomplete": function(r) {
2261 self.distribForms = openils.Util.readResponse(r);
2262 if(!self.distribForms || self.distribForms.length == 0) {
2263 self.distribForms = [];
2265 self._addDistribFormulaRow();
2272 this._drawBatchCopyWidgets = function() {
2273 var row = this.copyBatchRow;
2274 dojo.forEach(liDetailBatchFields,
2276 if(self.copyBatchRowDrawn) {
2277 self.copyBatchWidgets[field].attr('value', null);
2279 var args = self.afwCopyFieldArgs(field, "CREATE_PICKLIST");
2280 args.parentNode = dojo.query('[name='+field+']', row)[0];
2282 var widget = new openils.widget.AutoFieldWidget(args);
2285 if (field == "fund" && w.store)
2286 self._ensureCSSFundClasses(w.store);
2287 self.copyBatchWidgets[field] = w;
2290 if (field == "fund") {
2292 widget.widget, "onChange", function(val) {
2293 self._updateFundSelectorStyle(widget, val);
2300 this.copyBatchRowDrawn = true;
2303 this.batchCopyUpdate = function() {
2305 for(var k in this.copyWidgetCache) {
2306 var cache = this.copyWidgetCache[k];
2307 dojo.forEach(liDetailBatchFields, function(f) {
2308 var newval = self.copyBatchWidgets[f].attr('value');
2309 if(newval) cache[f].attr('value', newval);
2314 this._drawCopies = function(li) {
2317 // this button sets the total number of copies for a given lineitem
2318 acqLitAddCopyCount.onClick = function() {
2319 var count = acqLitCopyCountInput.attr('value');
2322 while(self.copyCount() < count)
2325 // delete rows if necessary
2326 var diff = self.copyCount() - count;
2328 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
2329 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
2330 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
2332 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2338 if(li.lineitem_details().length > 0) {
2339 dojo.forEach(li.lineitem_details(),
2341 self.addCopy(li, copy);
2349 this.copyCount = function() {
2351 for(var id in this.copyCache) {
2352 if(!this.copyCache[id].isdeleted())
2358 this.virtCopyId = -1;
2359 this.addCopy = function(li, copy) {
2360 var row = this.copyRow.cloneNode(true);
2361 this.copyTbody.appendChild(row);
2365 copy = new fieldmapper.acqlid();
2367 copy.id(this.virtCopyId--);
2368 copy.lineitem(li.id());
2371 this.copyCache[copy.id()] = copy;
2372 row.setAttribute('copy_id', copy.id());
2373 self.copyWidgetCache[copy.id()] = {};
2375 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2377 var rcvr = copy.receiver();
2379 if (!userCache[rcvr]) {
2380 if(rcvr == openils.User.user.id()) {
2381 userCache[rcvr] = openils.User.user;
2383 userCache[rcvr] = fieldmapper.standardRequest(
2384 ['open-ils.actor', 'open-ils.actor.user.retrieve'],
2385 {params: [openils.User.authtoken, rcvr]}
2389 dojo.query('[name=receiver]', row)[0].innerHTML = userCache[rcvr].usrname();
2392 dojo.forEach(liDetailFields,
2395 if (field == "fund") {
2396 searchFilter = (copy.fund() ?
2397 {"-or": {"active": "t", "id": copy.fund()}} :
2399 searchFilter.org = fundSearchFilter.org;
2401 searchFilter = null;
2404 var readOnly = false;
2406 // TODO: Add support for changing the owning_lib after real copies have been made.
2407 // owning_lib is order data as much as its item data
2408 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
2412 // TODO: add support for changing the fund after debits have been created
2413 // Note: invoicing allows the change
2414 if(copy.fund_debit() && field == 'fund') {
2419 var widget = new openils.widget.AutoFieldWidget({
2422 labelFormat : (field == 'fund') ? fundLabelFormat : null,
2423 searchFormat : (field == 'fund') ? fundSearchFormat : null,
2424 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
2425 searchFilter : searchFilter,
2426 noCache: (field == "fund"),
2428 parentNode : dojo.query('[name='+field+']', row)[0],
2429 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2430 readOnly : readOnly,
2431 orgDefaultsToWs : true
2435 // make sure we capture the value from any async widgets
2438 if (field == "fund" && w.store)
2439 self._ensureCSSFundClasses(w.store);
2442 copy[field](ww.getFormattedValue())
2444 self.copyWidgetCache[copy.id()][field] = w;
2446 dojo.connect(w, 'onChange',
2448 if (field == "fund")
2449 self._updateFundSelectorStyle(widget, val);
2451 if (!readOnly && (copy.isnew() || val != copy[field]())) {
2452 // prevent setting ischanged() automatically on widget load for existing copies
2453 copy[field](widget.getFormattedValue())
2454 copy.ischanged(true);
2463 this.updateLidState(copy, row);
2466 this._ensureCSSFundClass = function(id) {
2467 if (!this.fundStyleSheet) {
2469 "style", {"type": "text/css"},
2470 document.getElementsByTagName("head")[0], "last"
2472 this.fundStyleSheet = document.styleSheets[
2473 document.styleSheets.length - 1
2477 var cn = "fund_" + id;
2478 if (!this.haveFundClass[cn]) {
2479 fieldmapper.standardRequest(
2480 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
2482 "params": [openils.User.authtoken, id],
2484 "oncomplete": function(r) {
2485 r = openils.Util.readResponse(r);
2486 self.fundBalanceState[id] = r;
2488 if (r[0] /* stop */)
2489 style = fundStyles.stop;
2490 else if (r[1] /* warning */)
2491 style = fundStyles.warning;
2492 self.fundStyleSheet.insertRule(
2493 "." + cn + " { " + style + " }",
2494 self.fundStyleSheet.cssRules.length
2496 self.haveFundClass[cn] = true;
2503 this._ensureCSSFundClasses = function(store) {
2505 "query": {"id": "*"},
2506 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
2510 this._updateFundSelectorStyle = function(widget, fund_id) {
2511 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
2512 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
2515 this.updateLidState = function(copy, row) {
2518 if (typeof(row) == "undefined") {
2519 row = dojo.query('tr[copy_id="' + copy.id() + '"]', this.copyTbody)[0];
2523 var recv_link = nodeByName("receive", row);
2524 var unrecv_link = nodeByName("unreceive", row);
2525 var del_link = nodeByName("delete", row);
2526 var cxl_link = nodeByName("cancel", row);
2527 var claim_link = nodeByName("claim", row);
2528 var cxl_reason_link = nodeByName("cancel_reason", row);
2530 // by default, hide all the actions
2531 openils.Util.hide(del_link.parentNode);
2532 openils.Util.hide(recv_link);
2533 openils.Util.hide(unrecv_link);
2534 openils.Util.hide(cxl_link);
2535 openils.Util.hide(claim_link);
2536 openils.Util.hide(cxl_reason_link);
2538 if (copy.id() > 0) { // real copies (LIDs)
2540 if (copy.cancel_reason()) {
2542 /* --------- cancelled -------------------------- */
2544 /* XXX the following may leak memory in a long lived table:
2545 * dijits may not get destroyed... not positive. revisit. */
2546 var holds_reason = dojo.create(
2548 "style": "border-bottom: 1px dashed #000;",
2549 "innerHTML": copy.cancel_reason().label()
2550 }, cxl_reason_link, "only"
2554 "label": "<em>" + copy.cancel_reason().label() +
2555 "</em><br />" + copy.cancel_reason().description(),
2556 "connectId": [holds_reason]
2557 }, dojo.create("span", null, cxl_reason_link, "last")
2559 openils.Util.show(cxl_reason_link, "inline");
2561 if (copy.cancel_reason().keep_debits() == 't' ) {
2562 // allow further cancellation of "delayed" copies
2564 openils.Util.show(cxl_link, "inline");
2565 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2568 } else if (copy.recv_time()) {
2570 /* --------- received -------------------------- */
2572 openils.Util.show(unrecv_link, "inline");
2573 unrecv_link.onclick = function() {
2574 if (confirm(localeStrings.UNRECEIVE_LID))
2575 self.issueReceive(copy, /* rollback */ true);
2578 } else if (this.liCache[copy.lineitem()].state() == 'on-order') {
2580 /* --------- on order -------------------------- */
2582 openils.Util.show(recv_link, 'inline');
2583 openils.Util.show(cxl_link, "inline");
2585 recv_link.onclick = function() {
2586 if (self.checkLiAlerts(copy.lineitem()))
2587 self.issueReceive(copy);
2590 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2594 /* --------- pre-order copies -------------------------- */
2596 del_link.onclick = function() { self.deleteCopy(row) };
2597 openils.Util.show(del_link.parentNode);
2603 /* --------- virtual copies -------------------------- */
2605 del_link.onclick = function() { self.deleteCopy(row) };
2606 openils.Util.show(del_link.parentNode);
2610 this.cancelLid = function(lid_id) {
2611 lidCancelDialog._lid_id = lid_id;
2612 openils.Util.show(lidCancelDialog.domNode.parentNode);
2613 lidCancelDialog.show();
2614 if (!lidCancelDialog._prepared) {
2615 var widget = new openils.widget.AutoFieldWidget({
2616 "fmField": "cancel_reason",
2617 "fmClass": "acqlid",
2618 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
2619 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2621 "searchOptions" : {order_by : {"acqcr":"label"}}
2625 acqLidCancelButton.onClick = function() {
2626 if (w.attr("value")) {
2627 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
2629 lidCancelDialog._lid_id,
2633 lidCancelDialog.hide();
2636 lidCancelDialog._prepared = true;
2642 this._cancelLid = function(lid_id, reason) {
2643 fieldmapper.standardRequest(
2644 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
2645 "params": [openils.User.authtoken, lid_id, reason],
2647 "onresponse": function(r) {
2648 if (r = openils.Util.readResponse(r)) {
2650 for (var id in r.lid) {
2651 /* actually this should only iterate once */
2652 self.copyCache[id].cancel_reason(
2653 r.lid[id].cancel_reason
2655 self.updateLidState(self.copyCache[id]);
2664 this._confirmAlert = function(li, lin) {
2666 dojo.string.substitute(
2667 localeStrings.CONFIRM_LI_ALERT, [
2668 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2669 "title", "lineitem_marc_attr_definition"
2671 /* XXX it's really better add a parameter and to adjust
2672 * the format string rather than do this concatenation
2673 * here, but if someone wants this for 2.2 in a hurry,
2674 * we can sidestep the problem of updating the strings
2675 * while the translators are working. */
2677 aou.findOrgUnit(lin.alert_text().owning_lib()).shortname() +
2679 lin.alert_text().code()
2681 lin.alert_text().description() || "",
2688 this.checkLiAlerts = function(li_id) {
2689 var li = this.liCache[li_id];
2691 var alert_notes = li.lineitem_notes().filter(
2692 function(o) { return Boolean(o.alert_text()); }
2695 /* this is _intentionally_ not done in a call to forEach() ... */
2696 for (var i = 0; i < alert_notes.length; i++) {
2697 if (this.noteAcks[alert_notes[i].id()])
2699 else if (!this._confirmAlert(li, alert_notes[i]))
2702 this.noteAcks[alert_notes[i].id()] = true;
2708 this.deleteCopy = function(row) {
2709 var copy = this.copyCache[row.getAttribute('copy_id')];
2710 copy.isdeleted(true);
2712 delete this.copyCache[copy.id()];
2713 this.copyTbody.removeChild(row);
2716 this._virtDfaCountsAsList = function() {
2718 for (var key in this.virtDfaCounts) {
2719 for (var i = 0; i < this.virtDfaCounts[key]; i++)
2725 this.confirmBreachedCopyFunds = function(copies) {
2726 var stop = 0, warning = 0;
2730 var state = self.fundBalanceState[o.fund()];
2731 if (state[0] /* stop */)
2733 else if (state[1] /* warning */)
2740 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
2741 } else if (warning) {
2742 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
2747 this.saveCopyChanges = function(liId) {
2753 for(var id in this.copyCache) {
2754 var c = this.copyCache[id];
2755 if(!c.isdeleted()) total++;
2756 if(c.isnew() || c.ischanged() || c.isdeleted()) {
2757 if(c.id() < 0) c.id(null);
2763 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
2766 if (copies.length > 0) {
2767 if (!this.confirmBreachedCopyFunds(copies))
2770 if (typeof(this._copy_count_cb) == "function")
2771 this._copy_count_cb(liId, total);
2773 openils.Util.show("acq-lit-update-copies-progress");
2774 fieldmapper.standardRequest(
2775 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
2777 params: [openils.User.authtoken, copies],
2778 onresponse: function(r) {
2779 var res = openils.Util.readResponse(r);
2780 litUpdateCopiesProgress.update(res);
2782 oncomplete: function() {
2783 self.drawCopies(liId, true /* force_fetch */);
2784 openils.Util.hide("acq-lit-update-copies-progress");
2785 refreshPOSummaryAmounts();
2791 var dfa_list = this._virtDfaCountsAsList();
2792 if (dfa_list.length > 0) {
2793 fieldmapper.standardRequest(
2795 "open-ils.acq.distribution_formula.record_application"],
2798 "params": [openils.User.authtoken, dfa_list, liId],
2799 "onresponse": function(r) {
2800 var res = openils.Util.readResponse(r);
2801 if (res && res.length < dfa_list.length)
2802 alert(localeStrings.DFA_NOT_ALL);
2806 this.virtDfaCounts = {};
2809 if (this.inlineCopiesNeedingRefresh.indexOf(liId) < 0)
2810 this.inlineCopiesNeedingRefresh.push(liId);
2813 this._updateCreatePoPrepayCheckbox = function(prepay) {
2814 var prepay = openils.Util.isTrue(prepay);
2815 this._prepayRequiredByVendor = prepay;
2816 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
2819 this._confirmPoPrepaySituation = function() {
2820 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
2821 if (want_prepay != this._prepayRequiredByVendor) {
2824 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
2825 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
2832 this.applySelectedLiAction = function(action) {
2836 case 'delete_selected':
2837 this._deleteLiList(self.getSelected());
2840 case 'add_to_order':
2841 addToPoDialog._get_li = dojo.hitch(
2844 return this.getSelected(
2845 false, null, true, li_pre_po_states);
2848 if (addToPoDialog._get_li().length == 0) {
2849 alert(localeStrings.NO_LI_GENERAL);
2852 addToPoDialog.show();
2855 case 'create_order':
2856 this._loadPOSelect();
2857 acqLitPoCreateDialog.show();
2860 case 'save_picklist':
2861 acqLitSavePlDialog.show();
2864 case 'selector_ready':
2866 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
2867 acqLitChangeLiStateDialog.show();
2875 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
2878 case 'batch_create_invoice':
2879 this.batchCreateInvoice();
2882 case 'batch_link_invoice':
2883 this.batchLinkInvoice();
2886 case 'receive_lineitems':
2887 this.receiveSelectedLineitems();
2890 case 'rollback_receive_lineitems':
2891 this.rollbackReceiveLineitems();
2894 case 'create_assets':
2895 this.showAssetCreator();
2898 case 'export_attr_list':
2899 this.chooseExportAttr();
2902 case 'batch_apply_funds':
2903 this.applyBatchLiFunds();
2906 case 'add_brief_record':
2908 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
2910 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
2914 case "cancel_lineitems":
2915 console.log('HERE');
2916 this.maybeCancelLineitems();
2919 case "apply_claim_policy":
2920 var li_list = this.getSelected();
2921 this.claimPolicyPicker.attr("value", null);
2922 liClaimPolicyDialog.show();
2923 liClaimPolicySave.onClick = function() {
2924 self.changeClaimPolicy(
2926 self.claimPolicyPicker.attr("value"),
2930 self.setClaimPolicyControl(li);
2931 self.reconsiderClaimControl(li);
2934 liClaimPolicyDialog.hide();
2942 this.changeClaimPolicy = function(li_list, value, callback) {
2944 function(li) { li.claim_policy(value); }
2946 fieldmapper.standardRequest(
2947 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
2948 "params": [openils.User.authtoken, li_list],
2950 "oncomplete": function(r) {
2951 r = openils.Util.readResponse(r);
2952 if (callback) callback(r);
2958 this.showAssetCreator = function(onAssetsCreated) {
2959 if(!this.isPO) return;
2962 // first, let's see if this PO has any LI's that need to be merged/imported
2963 self.pcrud.search('jub', {purchase_order : this.isPO, eg_bib_id : null}, {
2965 oncomplete : function(r) {
2966 var resp = openils.Util.readResponse(r);
2967 if (resp && resp.length) {
2968 // PO has some non-linked jubs.
2970 self.show('asset-creator');
2971 if(!self.vlAgent.loaded)
2972 self.vlAgent.init();
2974 dojo.connect(assetCreatorButton, 'onClick',
2975 function() { self.createAssets(onAssetsCreated) });
2979 // all jubs linked, move on to asset creation
2980 self.createAssets(onAssetsCreated, true);
2986 this.createAssets = function(onAssetsCreated, noVl) {
2987 this.show('acq-lit-progress-numbers');
2989 var vlArgs = (noVl) ? {} : {vandelay : this.vlAgent.values()};
2990 this.batchProgress = {};
2991 progressDialog.show(false);
2992 progressDialog.attr("title", localeStrings.LI_CREATING_ASSETS);
2993 fieldmapper.standardRequest(
2994 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
2996 params: [this.authtoken, this.isPO, vlArgs],
2997 onresponse: function(r) {
2998 var resp = openils.Util.readResponse(r);
2999 self._updateProgressNumbers(resp, !Boolean(onAssetsCreated), onAssetsCreated, true);
3005 this.maybeCancelLineitems = function() {
3006 openils.Util.show("acq-lit-cancel-reason", "inline");
3007 if (!acqLitCancelLineitemsButton._prepared) {
3008 var widget = new openils.widget.AutoFieldWidget({
3009 "fmField": "cancel_reason",
3011 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
3012 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3014 "searchOptions" : {order_by : {"acqcr":"label"}}
3018 acqLitCancelLineitemsButton.onClick = function() {
3019 if (w.attr("value")) {
3020 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
3021 self._cancelLineitems(w.attr("value"));
3023 openils.Util.hide("acq-lit-cancel-reason");
3026 acqLitCancelLineitemsButton._prepared = true;
3032 this._cancelLineitems = function(reason) {
3034 var li_list = this.getSelected();
3036 // canceled lineitems may be canceled again if they were
3037 // previously delayed (keep_debits = true).
3038 li_list = li_list.filter(
3041 li.state() != 'cancelled' ||
3042 li.cancel_reason().keep_debits() == 't'
3047 id_list = li_list.map(function(l) {return l.id()});
3049 if (!id_list.length) {
3050 alert(localeStrings.NO_LI_GENERAL);
3053 fieldmapper.standardRequest(
3054 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
3055 "params": [openils.User.authtoken, id_list, reason],
3057 "onresponse": function(r) {
3058 if (r = openils.Util.readResponse(r)) {
3060 for (var id in r.li) {
3061 self.liCache[id].state(r.li[id].state);
3062 self.liCache[id].cancel_reason(
3063 r.li[id].cancel_reason
3065 self.updateLiState(self.liCache[id]);
3068 if (r.lid && self.copyCache) {
3069 for (var id in r.lid) {
3070 if (self.copyCache[id]) {
3071 self.copyCache[id].cancel_reason(
3072 r.lid[id].cancel_reason
3074 self.updateLidState(self.copyCache[id]);
3084 this.chooseExportAttr = function() {
3085 if (!acqLitExportAttrSelector._li_setup) {
3087 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
3089 "data": acqlimad.toStoreData(
3091 "acqlimad", {"code": li_exportable_attrs}
3096 acqLitExportAttrSelector.setValue();
3097 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
3098 acqLitExportAttrSelector._li_setup = true;
3100 openils.Util.show("acq-lit-export-attr-holder", "inline");
3103 this.exportAttrList = function() {
3104 var attr_def = acqLitExportAttrSelector.item;
3105 var li_list = this.getSelected();
3106 var value_list = li_list.map(
3108 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
3109 attr_def.code, "lineitem_marc_attr_definition"
3112 ).filter(function(attr) { return Boolean(attr); });
3114 if (value_list.length > 0) {
3115 if (value_list.length < li_list.length) {
3117 dojo.string.substitute(
3118 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
3125 openils.XUL.contentToFileSaveDialog(
3126 value_list.join("\n"),
3127 localeStrings.EXPORT_SAVE_DIALOG_TITLE
3133 alert(dojo.string.substitute(
3134 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
3138 openils.Util.hide("acq-lit-export-attr-holder");
3141 this.printPO = function() {
3142 if(!this.isPO) return;
3143 progressDialog.show(true);
3144 fieldmapper.standardRequest(
3145 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
3147 params: [this.authtoken, this.isPO, 'html'],
3148 oncomplete: function(r) {
3149 progressDialog.hide();
3150 var evt = openils.Util.readResponse(r);
3151 if(evt && evt.template_output()) {
3152 openils.Util.printHtmlString(evt.template_output().data());
3159 this.batchCreateInvoice = function() {
3160 var liIds = this.getSelected(
3161 false, null, true /* id_list */, li_active_states)
3162 if (!liIds.length) {
3163 alert(localeStrings.NO_LI_GENERAL);
3166 var path = oilsBasePath + '/acq/invoice/view?create=1';
3167 dojo.forEach(liIds, function(li, idx) { path += '&attach_li=' + li });
3168 if (openils.XUL.isXUL() && !window.IAMBROWSER)
3169 openils.XUL.newTabEasy(path, localeStrings.NEW_INVOICE, null, true);
3171 location.href = path;
3174 this.batchLinkInvoice = function(create) {
3175 var liIds = this.getSelected(
3176 false, null, true /* id_list */, li_active_states)
3177 if (!liIds.length) {
3178 alert(localeStrings.NO_LI_GENERAL);
3181 if (!self.invoiceLinkDialogManager) {
3182 self.invoiceLinkDialogManager =
3183 new InvoiceLinkDialogManager("li");
3185 self.invoiceLinkDialogManager.target = liIds;
3186 acqLitLinkInvoiceDialog.show();
3189 this.receiveSelectedLineitems = function() {
3190 var states = li_post_po_states.filter(
3191 function(s) { return s != 'received' });
3192 var li_list = this.getSelected(null, null, null, states);
3194 if (!li_list.length) {
3195 alert(localeStrings.NO_LI_GENERAL);
3199 for (var i = 0; i < li_list.length; i++) {
3200 var li = li_list[i];
3202 if (li.state() != "received" &&
3203 !this.checkLiAlerts(li.id())) return;
3206 this.show('acq-lit-progress-numbers');
3209 fieldmapper.standardRequest(
3210 ['open-ils.acq', 'open-ils.acq.lineitem.receive.batch'],
3214 li_list.map(function(li) { return li.id(); })
3216 onresponse : function(r) {
3217 var resp = openils.Util.readResponse(r);
3218 self._updateProgressNumbers(resp, true);
3224 this.issueReceive = function(obj, rollback) {
3226 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
3228 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
3230 progressDialog.show(true);
3231 fieldmapper.standardRequest(
3232 ["open-ils.acq", method], {
3234 "params": [this.authtoken, obj.id()],
3235 "onresponse": function(r) {
3236 if (r = openils.Util.readResponse(r)) {
3237 self.fetchClaimInfo(
3238 part == "lineitem" ? obj.id() : obj.lineitem(),
3240 function() { self.handleReceive(r); }
3242 progressDialog.hide();
3250 * Handles the responses from receive and rollback ML calls.
3252 this.handleReceive = function(resp) {
3255 for (var li_id in resp.li) {
3256 for (var key in resp.li[li_id])
3257 self.liCache[li_id][key](resp.li[li_id][key]);
3258 self.updateLiState(self.liCache[li_id]);
3262 if (typeof(self.poUpdateCallback) == "function")
3263 self.poUpdateCallback(resp.po);
3266 for (var lid_id in resp.lid) {
3267 for (var key in resp.lid[lid_id])
3268 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
3269 self.updateLidState(self.copyCache[lid_id]);
3275 this.rollbackReceiveLineitems = function() {
3276 var li_id_list = this.getSelected(false, null, true);
3277 if (!li_id_list.length) {
3278 alert(localeStrings.NO_LI_GENERAL);
3282 if (!confirm(localeStrings.ROLLBACK_LI_RECEIVE_CONFIRM)) return;
3284 this.show('acq-lit-progress-numbers');
3287 fieldmapper.standardRequest(
3288 ['open-ils.acq', 'open-ils.acq.lineitem.receive.rollback.batch'],
3290 params: [this.authtoken, li_id_list],
3291 onresponse : function(r) {
3292 var resp = openils.Util.readResponse(r);
3293 self._updateProgressNumbers(resp, true);
3299 this._updateProgressNumbers = function(resp, reloadOnComplete, onComplete, clearProgressDialog) {
3300 this._updateProgressDialog(resp);
3301 this.vlAgent.handleResponse(resp,
3302 function(resp, res) {
3303 if (clearProgressDialog) {
3304 progressDialog.update({ "progress": 100});
3305 progressDialog.update_message();
3306 progressDialog.hide();
3307 progressDialog.attr("title", "");
3309 if(reloadOnComplete)
3310 location.href = location.href;
3312 onComplete(resp, res);
3317 this._updateProgressDialog = function(resp) {
3318 progressDialog.update({ "progress": (resp.progress / resp.total) * 100 });
3319 var keys = ['li', 'vqbr', 'bibs', 'lid', 'debits_accrued', 'copies'];
3320 for (var i = 0; i < keys.length; i++) {
3321 if (resp[keys[i]] > (this.batchProgress[keys[i]] || 0)) {
3322 progressDialog.update_message(
3323 dojo.string.substitute(
3324 localeStrings["ACTIVATE_" + keys[i].toUpperCase() + "_PROCESSED"],
3330 this.batchProgress = resp;
3333 this._createPO = function(fields) {
3334 var wantall = (fields.create_from == "all");
3336 /* If we're a picklist or purchase order already and the user wants
3337 * all lineitems, we might have pages' worth of lineitems haven't all
3338 * been loaded yet, so getSelected() won't find them. The server,
3339 * however, should know about all our lineitems, so let's ask the
3340 * server for a complete list.
3345 true, function(list) {
3346 self._createPOFromLineitems(fields, list);
3347 }, /* id_list */ true, li_pre_po_states
3350 this._createPOFromLineitems(
3351 fields, this.getSelected(
3352 false, null, true /* id_list */, li_pre_po_states)
3357 this._createPOFromLineitems = function(fields, selected) {
3358 if (selected.length == 0) {
3359 alert(localeStrings.NO_LI_GENERAL);
3364 var po = new fieldmapper.acqpo();
3365 po.provider(this.createPoProviderSelector.attr("value"));
3366 po.ordering_agency(this.createPoAgencySelector.attr("value"));
3367 po.prepayment_required(fields.prepayment_required[0] ? true : false);
3368 var name = this.createPoNameInput.attr('value');
3369 if (name) po.name(name); // avoid name=""
3371 // if we're creating assets, delay the asset creation
3372 // until after the PO is created. This will allow us to
3373 // use showAssetCreator() directly.
3375 fieldmapper.standardRequest(
3376 ["open-ils.acq", "open-ils.acq.purchase_order.create"],
3379 openils.User.authtoken,
3380 po, {lineitems : selected}
3382 onresponse : function(r) {
3383 var resp = openils.Util.readResponse(r);
3384 if (resp.complete) {
3385 // self.isPO is needed for showAssetCreator();
3386 self.isPO = resp.purchase_order.id();
3387 var redir = oilsBasePath + "/acq/po/view/" + self.isPO;
3388 if (fields.create_assets[0]) {
3389 self.showAssetCreator(
3390 function() {location.href = redir}
3393 location.href = redir;
3402 this.batchFundWidget = null;
3404 this.applyBatchLiFunds = function() {
3406 var liIds = this.getSelected().map(function(li) { return li.id(); });
3407 if(liIds.length == 0) return; // warn?
3410 batchFundUpdateDialog.show();
3412 if(!this.batchFundWidget) {
3413 this.batchFundWidget = new openils.widget.AutoFieldWidget({
3415 selfReference : true,
3416 labelFormat : fundLabelFormat,
3417 searchFormat : fundSearchFormat,
3418 searchFilter : fundSearchFilter,
3419 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
3420 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
3421 dijitArgs : { "required": true, "labelType": "html" },
3424 this.batchFundWidget.build();
3427 dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
3428 dojo.connect(batchFundUpdateSubmit, 'onClick',
3431 // TODO: call .dry_run first to test thresholds
3432 fieldmapper.standardRequest(
3433 ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
3436 openils.User.authtoken,
3438 self.batchFundWidget.widget.attr('value')
3440 oncomplete : function(r) {
3441 var resp = openils.Util.readResponse(r);
3443 location.href = location.href;
3452 this._deleteLiList = function(list, idx) {
3453 if(idx == null) idx = 0;
3454 if(idx >= list.length) return;
3459 if (this.isPO && (li.state() == "on-order" || li.state() == "received")) {
3460 /* It makes little sense to delete a lineitem from a PO that has
3461 * already been marked 'on-order'. Especially if EDI is in use,
3462 * such a purchase order will probably have already been shipped
3463 * off to a vendor, and mucking with it at this point could leave
3464 * your data in a bad state that doesn't jive with reality.
3466 * I could see making this restriction even firmer.
3468 * I could also see adjusting the li state comparisons, extending
3469 * the comparison to the PO's state, and/or providing functions
3470 * that house the logic for comparing states in a single location.
3472 * Yes, this will be really annoying if you have selected a lot
3473 * of lineitems to cancel that have been ordered. You'll get a
3474 * confirm dialog for each one.
3477 if (!confirm(localeStrings.DEL_LI_FROM_PO)) {
3478 self._deleteLiList(list, ++idx); /* move on to next in list */
3483 fieldmapper.standardRequest(
3485 this.isPO ? 'open-ils.acq.purchase_order.lineitem.delete' : 'open-ils.acq.picklist.lineitem.delete'],
3487 params: [openils.User.authtoken, liId],
3488 oncomplete: function(r) {
3489 self.removeLineitem(liId);
3490 self._deleteLiList(list, ++idx);
3496 this.editOrderMarc = function(li) {
3498 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
3499 to true in about:config */
3501 if(openils.XUL.isXUL()) {
3502 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul','','chrome');
3504 win = window.open('/xul/server/cat/marcedit.xul','','chrome');
3508 record : {marc : li.marc(), "rtype": "bre"},
3510 label: 'Save Record', // XXX I18N
3511 func: function(xmlString) {
3513 fieldmapper.standardRequest(
3514 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
3516 params: [openils.User.authtoken, li],
3517 oncomplete: function(r) {
3518 openils.Util.readResponse(r);
3520 self.drawInfo(li.id())
3526 'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
3527 'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
3531 this._savePl = function(values) {
3533 (values.which == 'all'),
3534 function(list) { self._savePlFromLineitems(values, list); }
3538 this._savePlFromLineitems = function(values, selected) {
3539 openils.Util.show("acq-lit-generic-progress");
3541 if(values.new_name) {
3542 openils.acq.Picklist.create(
3543 {name: values.new_name},
3549 oilsBasePath + "/acq/picklist/view/" + id;
3554 } else if(values.existing_pl) {
3555 // update lineitems to use an existing picklist
3557 values.existing_pl, selected, 0,
3560 oilsBasePath + "/acq/picklist/view/" +
3567 this._updateLiState = function(values, state, state_filter) {
3568 progressDialog.show(true);
3570 (values.which == 'all'),
3572 self._updateLiStateFromLineitems(values, state, list);
3573 }, false /* id_list */, state_filter
3577 this._updateLiStateFromLineitems = function(values, state, selected) {
3578 if(!selected.length) {
3579 try { progressDialog.hide() } catch(E) {};
3580 alert(localeStrings.NO_LI_GENERAL);
3583 dojo.forEach(selected, function(li) {li.state(state);});
3584 self._updateLiList(null, selected, 0,
3585 // TODO consider inline updates for efficiency
3586 function() { location.href = location.href }
3590 this._updateLiList = function(pl, list, idx, oncomplete) {
3591 if(idx >= list.length) return oncomplete();
3593 if(pl != null) li.picklist(pl);
3594 litGenericProgress.update({maximum: list.length, progress: idx});
3595 new openils.acq.Lineitem({lineitem:li}).update(
3597 self._updateLiList(pl, list, ++idx, oncomplete);
3602 this._loadPOSelect = function() {
3603 if (!this.createPoProviderSelector) {
3604 var widget = new openils.widget.AutoFieldWidget({
3605 "fmField": "provider",
3607 "searchFilter": {"active": "t"},
3608 "parentNode": dojo.byId("acq-lit-po-provider"),
3610 "onChange": function() {
3612 self._updateCreatePoPrepayCheckbox(
3613 this.item.prepayment_required()
3619 widget.build(function(w) { self.createPoProviderSelector = w; });
3622 this.createPoCheckDupes = function() {
3623 var org = self.createPoAgencySelector.attr('value');
3624 var name = self.createPoNameInput.attr('value');
3625 openils.Util.hide('acq-dupe-po-name');
3628 acqLitCreatePoSubmit.attr('disabled', false);
3632 acqLitCreatePoSubmit.attr('disabled', true);
3633 var orgs = fieldmapper.aou.descendantNodeList(org, true);
3634 new openils.PermaCrud().search('acqpo',
3635 {name : name, ordering_agency : orgs},
3636 {async : true, oncomplete : function(r) {
3637 var po = openils.Util.readResponse(r);
3639 if (po && (po = po[0])) {
3641 var link = dojo.byId('acq-dupe-po-link');
3642 openils.Util.show('acq-dupe-po-name', 'table-row');
3643 var dupe_path = '/acq/po/view/' + po.id();
3647 if (window.IAMBROWSER) {
3648 // TODO: integration
3652 link.onclick = function() {
3654 var loc = xulG.url_prefix('XUL_BROWSER?url=') +
3655 window.encodeURIComponent(
3656 xulG.url_prefix('EG_WEB_BASE' + dupe_path)
3660 {tab_name: '', browser:false},
3663 show_nav_buttons : true,
3664 show_print_button : true,
3671 link.onclick = function() {
3672 window.open(oilsBasePath + dupe_path, '_blank').focus();
3677 acqLitCreatePoSubmit.attr('disabled', false);
3683 if (!this.createPoAgencySelector) {
3684 var widget = new openils.widget.AutoFieldWidget({
3685 "fmField": "ordering_agency",
3687 "parentNode": dojo.byId("acq-lit-po-agency"),
3688 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3690 widget.build(function(w) {
3691 self.createPoAgencySelector = w;
3692 dojo.connect(w, 'onChange', self.createPoCheckDupes);
3696 if (!this.createPoNameInput) {
3697 var widget = new openils.widget.AutoFieldWidget({
3700 "parentNode": dojo.byId("acq-lit-po-name"),
3701 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3703 widget.build(function(w) {
3704 self.createPoNameInput = w;
3705 dojo.connect(w, 'onChange', self.createPoCheckDupes);
3710 this.showRealCopyEditUI = function(li) {
3715 this._fetchLineitem(li.id(),
3717 li = self.liCache[li.id()] = fullLi;
3721 id : li.lineitem_details().map(
3722 function(item) { return item.eg_copy_id() }
3726 oncomplete : function(r) {
3728 var r_list = openils.Util.readResponse( r );
3729 for (var i = 0; i < r_list.length; i++) {
3730 var copy = r_list[i];
3731 var volId = copy.call_number();
3732 var volume = self.volCache[volId];
3734 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
3736 copy.call_number(volume);
3737 copyList.push(copy);
3740 xulG.volume_item_creator( { 'existing_copies' : copyList } );
3743 alert('error in oncomplete: ' + E);
3752 this.drawBibFinder = function(li) {
3755 var liWrapper = new openils.acq.Lineitem({lineitem:li});
3758 ['isbn', 'upc', 'issn', 'title', 'author'],
3760 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
3762 if(field == 'title' || field == 'author') {
3763 query += field +':' + val + ' ';
3765 query += 'identifier|' + field + ':' + val + ' ';
3771 if(openils.XUL.isXUL() && !window.IAMBROWSER) {
3773 oilsBasePath + '/acq/lineitem/findbib?query=' + encodeURIComponent(query),
3774 '', 'resizable,scrollbars=1,chrome');
3776 win = window.open( oilsBasePath + '/acq/lineitem/findbib?query=' + encodeURIComponent(query));
3780 win.window.recordFound = function(bibId) {
3783 var attrs = li.attributes();
3784 li.attributes(null);
3785 li.eg_bib_id(bibId);
3787 fieldmapper.standardRequest(
3788 ["open-ils.acq", "open-ils.acq.lineitem.update"],
3790 "params": [openils.User.authtoken, li],
3792 "oncomplete": function(r) {
3793 if(openils.Util.readResponse(r)) {
3794 location.href = location.href;