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]);
927 this.clearEligibility = function(li) {
928 this.claimEligibleLidByLi[li.id()] = [];
930 if (li.lineitem_details()) {
931 li.lineitem_details().forEach(
932 function(lid) { delete self.claimEligibleLid[lid.id()]; }
936 if (this.copyCache) {
938 for (var k in this.copyCache) {
939 if (this.copyCache[k].lineitem() == li.id())
943 function(k) { delete self.claimEligibleLid[k]; }
948 this.applyOrderIdentValues = function() {
949 this._identValuesInFlight =
950 openils.Util.objectProperties(this.liCache).length;
951 for (var liId in this.liCache) {
952 this._applyOrderIdentValue(this.liCache[liId]);
956 // returns true if request was sent
957 this._applyOrderIdentValue = function(li, oncomplete) {
960 console.log('applying ident value for lineitem ' + li.id());
963 var row = dojo.query('[li=' + li.id() + ']')[0];
965 // find the selected ident value
966 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
967 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
968 var name = typeSel.options[typeSel.selectedIndex].value;
969 var val = typeSel._cbox.attr('value');
971 console.log("selected ident is " + val);
973 // it differs from the existing ident value, update it
974 var oldIdent = self.getLiOrderIdent(li);
976 oldIdent.attr_name() == name &&
977 oldIdent.attr_value() == val) {
978 console.log('selected ident attr matches existing attr');
979 if (--this._identValuesInFlight == 0) {
980 if (oncomplete) oncomplete(li);
981 else location.href = location.href;
986 // see if the selected ident value is represented
987 // by an existing lineitem attr
990 typeSel._cbox.store.fetch({
991 query : {attr_value : val},
992 onItem : function(item) {
993 console.log('found existing attr for ident value');
994 args.source_attr_id = li.attributes().filter(
995 function(attr) { return attr.id() == item.id[0] }
1001 if (!args.source_attr_id) {
1002 // user entered new text in the combobox
1003 // so we need to create a new attr
1004 console.log('creating new ident attr');
1005 args.lineitem_id = li.id();
1006 args.attr_name = name;
1007 args.attr_value = val;
1010 fieldmapper.standardRequest(
1011 ['open-ils.acq', 'open-ils.acq.lineitem.order_identifier.set'],
1013 params : [openils.User.authtoken, args],
1014 oncomplete : function() {
1015 console.log('order_ident oncomplete');
1016 if (--self._identValuesInFlight == 0) {
1017 if (oncomplete) oncomplete(li);
1018 else location.href = location.href;
1020 console.log(self._identValuesInFlight + ' still in flight');
1028 this.getLiOrderIdent = function(li) {
1029 var attrs = li.attributes();
1030 if (!attrs) return null;
1031 return attrs.filter(
1034 attr.attr_type() == 'lineitem_local_attr_definition' &&
1035 openils.Util.isTrue(attr.order_ident())
1041 this.drawOrderIdentSelector = function(li, row) {
1043 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
1044 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
1046 var attrs = li.attributes();
1048 // limit to MARC attr defs
1049 attrs = attrs.filter(
1051 return (attr.attr_type() == 'lineitem_marc_attr_definition');
1055 var identAttr = this.getLiOrderIdent(li);
1058 // collect the values for each type of identifier
1059 // find a reasonable default identifier type to render
1063 dojo.forEach(['isbn', 'upc', 'issn'],
1066 // collect the values for this attr name
1067 values[name] = attrs.filter(
1069 return (attr.attr_name() == name)
1073 // select a reasonable default name in the type-selector
1077 if (identAttr.attr_name() == name)
1079 } else if (values[name].length) {
1084 dojo.forEach(typeSel.options, function(opt) {
1085 if (opt.value == name) {
1086 opt.selected = true;
1095 function updateOrderIdent(val) {
1096 self._identValuesInFlight = 1;
1097 self._applyOrderIdentValue(
1100 self.refreshLineitem(li);
1105 // replace the ident combobox with a new
1106 // one for the selected ident type
1107 function changeComboBox(sel) {
1108 var name = sel.options[sel.selectedIndex].value;
1110 var td = dojo.query('[name=order_ident_value]', row)[0];
1111 if (td.childNodes[0])
1112 dojo.destroy(td.childNodes[0]);
1114 var store = new dojo.data.ItemFileWriteStore({
1115 data : acqlia.toStoreData(values[name])
1118 var cbox = new dijit.form.ComboBox(
1120 labelAttr : 'attr_value',
1121 searchAttr : 'attr_value'
1123 dojo.create('div', {}, td)
1128 // set the value for the cbox
1129 if (values[name].length) {
1130 var orderIdent = self.getLiOrderIdent(li);
1132 if (orderIdent && orderIdent.attr_name() == name) {
1133 cbox.attr('value', orderIdent.attr_value());
1135 cbox.attr('value', values[name][0].attr_value());
1139 if (!self.orderIdentAllowed)
1140 cbox.attr('disabled', true);
1143 cbox._lineitem = li;
1144 dojo.connect(cbox, 'onChange', updateOrderIdent);
1147 changeComboBox(typeSel); // force the initial draw
1148 typeSel.onchange = function() {changeComboBox(typeSel)};
1151 this.testOrderIdentPerms = function(org, callback) {
1153 new openils.User().getPermOrgList(
1154 'ACQ_SET_LINEITEM_IDENTIFIER',
1156 console.log('found orgs = ' + orgs);
1157 for (var i = 0; i < orgs.length; i++) {
1158 if (Number(orgs[i]) == Number(org)) {
1159 self.orderIdentAllowed = true;
1160 if (callback) callback();
1164 if (callback) callback();
1170 this.checkClaimEligibility = function(li, callback, row) {
1171 /* Assume always eligible, i.e. from this interface we don't care about
1172 * claim eligibility any more. this is where the user would force a
1174 this.clearEligibility(li);
1175 this.claimEligibleLidByLi[li.id()] = li.lineitem_details().map(
1176 function(lid) { return lid.id(); }
1178 li.lineitem_details().forEach(
1179 function(lid) { self.claimEligibleLid[lid.id()] = true; }
1181 this.reconsiderClaimControl(li, row);
1182 if (callback) callback(li);
1184 this.clearEligibility(li);
1185 fieldmapper.standardRequest(
1186 ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
1187 "params": [openils.User.authtoken, {"lineitem": li.id()}],
1189 "onresponse": function(r) {
1190 if (r = openils.Util.readResponse(r)) {
1191 self.claimEligibleLidByLi[li.id()].push(
1194 self.claimEligibleLid[r.lineitem_detail()] = true;
1197 "oncomplete": function() {
1198 self.reconsiderClaimControl(li, row);
1199 if (typeof(callback) == "function")
1207 this.updateLiNotesCount = function(li, row) {
1208 if (!row) row = this._findLiRow(li);
1210 var has_notes = (li.lineitem_notes().filter(
1211 function(o) { return Boolean (o.alert_text()); }
1214 /* U+2691 is the code point for a filled-in flag character */
1215 nodeByName("notes_alert_flag", row).innerHTML =
1216 has_notes ? "⚑" : "";
1217 nodeByName("noteslink", row).style.fontStyle =
1218 has_notes ? "italic" : "normal";
1219 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
1222 /* XXX NOT related to _updateLiState(). rethink */
1223 this.updateLiState = function(li, row) {
1224 if (!row) row = this._findLiRow(li);
1226 nodeByName("actions", row).onchange = function() {
1227 switch(this.options[this.selectedIndex].value) {
1228 case 'action_update_barcodes':
1229 self.showRealCopyEditUI(li);
1230 nodeByName("action_none", row).selected = true;
1232 case 'action_holdings_maint':
1233 (self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row ))();
1235 case 'action_manage_claims':
1236 self.fetchClaimInfo(li.id(), true, function(full) { self.claimDialog.show(full) }, row);
1238 case 'action_view_history':
1239 location.href = oilsBasePath + '/acq/lineitem/history/' + li.id();
1243 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
1244 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
1246 /* handle row coloring for based on LI state */
1247 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1248 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
1250 // Expose invoice actions for any lineitem that is linked to a PO
1251 if (li.purchase_order()) {
1252 openils.Util.show(nodeByName("invoices_span", row), "inline");
1253 var link = nodeByName("invoices_link", row);
1254 link.onclick = function() {
1255 var url = oilsBasePath + "/acq/search/unified?so=" +
1256 base64Encode({"jub":[{"id": li.id()}]}) + "&rt=invoice"
1257 if (window.IAMBROWSER) {
1258 xulG.relay_url(url);
1260 openils.XUL.newTabEasy(url);
1268 * If we haven't fleshed the lineitem_details, default to allowing access to the
1269 * holdings maintenence actions. The alternative is to flesh LIDs on every lineitem,
1270 * but that will add to page render time. Let's see if this will suffice...
1272 var lids = li.lineitem_details();
1274 (lids && !lids.filter(function(lid) { return lid.eg_copy_id() })[0] )) {
1276 actUpdateBarcodes.disabled = false;
1277 actHoldingsMaint.disabled = false;
1280 var state_cell = nodeByName("li_state_" + li.state(), row);
1282 // re-hide any state label nodes which may have been un-hidden
1283 // through previous actions.
1284 dojo.query('[state-label]', row).forEach(function(node) {
1285 openils.Util.hide(node)
1288 if (li.state() == 'cancelled') {
1289 if(typeof li.cancel_reason() == "object") {
1291 // clear the stock "Canceled" label, since we have more
1292 // information to replace it with.
1293 state_cell.innerHTML = '';
1295 var holds_state = dojo.create(
1297 "style": "border-bottom: 1px dashed #000;",
1298 "innerHTML": li.cancel_reason().label()
1299 }, state_cell, "only"
1303 "label": "<em>" + li.cancel_reason().label() +
1304 "</em><br />" + li.cancel_reason().description(),
1305 "connectId": [holds_state]
1306 }, dojo.create("span", null, state_cell, "last")
1309 if (li.cancel_reason().keep_debits() == 't') {
1310 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1311 openils.Util.addCSSClass(row, "oils-acq-li-state-delayed");
1314 console.log('li cancel_reason is un-fleshed. Please fix');
1318 openils.Util.show(state_cell);
1322 this._setAlertStore = function() {
1323 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
1325 "data": acqliat.toStoreData(
1328 "owning_lib": aou.orgNodeTrail(
1329 aou.findOrgUnit(openils.User.user.ws_ou())
1330 ).map(function(o) { return o.id(); })
1336 acqLitAlertAlertText.setValue(); /* make the store "live" */
1337 acqLitAlertAlertText._store_ready = true;
1341 * Draws and shows the lineitem notes pane
1343 this.drawLiNotes = function(li) {
1345 this.focusLineitem = li.id();
1347 if (!acqLitAlertAlertText._store_ready)
1348 this._setAlertStore();
1351 li.lineitem_notes().sort(
1353 if(a.edit_time() < b.edit_time()) return 1;
1359 while(this.liNotesTbody.childNodes[0])
1360 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
1363 acqLitCreateNoteSubmit.onClick = function() {
1364 var value = acqLitCreateNoteText.attr('value');
1366 var note = new fieldmapper.acqlin();
1369 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
1372 note.lineitem(li.id());
1374 self.updateLiNotes(li, note);
1375 acqLitCreateNoteVendorPublic.attr("checked", false);
1376 acqLitCreateNoteText.attr("value", "");
1379 acqLitCreateAlertSubmit.onClick = function() {
1380 if (!acqLitAlertAlertText.item) {
1381 alert(localeStrings.ALERT_UNSELECTED);
1385 var alert_text = new fieldmapper.acqliat().fromStoreItem(
1386 acqLitAlertAlertText.item
1388 var value = acqLitAlertNoteValue.attr("value") || "";
1390 var note = new fieldmapper.acqlin();
1392 note.lineitem(li.id());
1394 note.alert_text(alert_text);
1396 self.updateLiNotes(li, note);
1399 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
1403 * Draws a single lineitem note in the notes pane
1405 this.addLiNote = function(li, note) {
1406 if(note.isdeleted()) return;
1408 var row = self.liNotesRow.cloneNode(true);
1409 nodeByName("value", row).innerHTML = note.value();
1410 var alert_node = nodeByName("alert_code", row);
1411 if (note.alert_text()) {
1412 alert_node.innerHTML = dojo.string.substitute(
1414 aou.findOrgUnit(note.alert_text().owning_lib()).shortname(),
1415 note.alert_text().code()
1418 if (note.alert_text().description()) {
1421 "connectId": [alert_node],
1422 "label": note.alert_text().description()
1423 }, dojo.create("span", null, alert_node, "after")
1428 if (openils.Util.isTrue(note.vendor_public()))
1429 nodeByName("vendor_public", row).innerHTML =
1430 localeStrings.VENDOR_PUBLIC;
1432 nodeByName("delete", row).onclick = function() {
1433 note.isdeleted(true);
1434 self.liNotesTbody.removeChild(row);
1435 self.updateLiNotes(li);
1438 if(note.edit_time()) {
1439 nodeByName("edit_time", row).innerHTML =
1440 dojo.date.locale.format(
1441 dojo.date.stamp.fromISOString(note.edit_time()),
1442 {formatLength:'short'});
1445 self.liNotesTbody.appendChild(row);
1449 * Updates any new/changed/deleted notes on the server
1451 this.updateLiNotes = function(li, newNote) {
1457 notes = li.lineitem_notes().filter(
1459 if(note.ischanged() || note.isnew() || note.isdeleted())
1465 if(notes.length == 0) return;
1466 progressDialog.show();
1468 fieldmapper.standardRequest(
1469 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
1471 params : [this.authtoken, notes],
1472 onresponse : function(r) {
1473 var resp = openils.Util.readResponse(r);
1478 // remove the old changed notes
1480 dojo.forEach(li.lineitem_notes(),
1482 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
1486 li.lineitem_notes(list);
1489 progressDialog.hide();
1490 self.updateLiNotesCount(li);
1491 self.drawLiNotes(li);
1495 progressDialog.update(resp);
1496 var newnote = resp.note;
1498 if(!newnote.isdeleted()) {
1499 newnote.isnew(false);
1500 newnote.ischanged(false);
1501 li.lineitem_notes().push(newnote);
1508 this.updateLiPrice = function(input, li) {
1510 var price = input.value;
1511 if(Number(price) == Number(li.estimated_unit_price())) return;
1513 fieldmapper.standardRequest(
1514 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
1515 { async : false, // redundant w/ timeout
1517 params : [this.authtoken, li.id(), price],
1518 oncomplete : function(r) {
1519 openils.Util.readResponse(r);
1520 li.estimated_unit_price(price); // update local copy
1523 * If this is a PO and every visible lineitem has a price,
1524 * check again to see if this PO can be activated. Note that
1525 * every visible lineitem having a price does not guarantee it can
1526 * be activated, which is why we still make the call. Having a price
1527 * set for every visiable lineitem is just the lowest barrier to entry.
1530 var priceNodes = dojo.query('[name=price]', dojo.byId('acq-lit-tbody'));
1532 dojo.forEach(priceNodes, function(node) { if (node.value == '') allSet = false});
1533 if (allSet) checkCouldActivatePo();
1534 refreshPOSummaryAmounts();
1541 this.removeLineitem = function(liId) {
1542 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
1543 delete this.liCache[liId];
1544 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
1547 this.drawInfo = function(liId) {
1548 this.focusLineitem = liId;
1549 if (!this._isRelatedViewer) {
1550 var d = dojo.byId("acq-lit-info-related");
1551 if (!this.relCache[liId]) {
1552 fieldmapper.standardRequest(
1555 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
1558 "params": [openils.User.authtoken, liId],
1559 "onresponse": function(r) {
1560 self.relCache[liId] = openils.Util.readResponse(r);
1561 nodeByName("related_number", d).innerHTML =
1562 self.relCache[liId];
1564 self.relCache[liId] >1 ? "show" : "hide"
1570 nodeByName("related_number", d).innerHTML = this.relCache[liId];
1571 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
1576 openils.acq.Lineitem.fetchAttrDefs(
1578 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
1583 this.toggleInlineCopies = function() {
1584 // if any inline copies are not displayed,
1585 // display them all otherwise, hide them all.
1587 var displayAll = false;
1589 for (var liId in this.liCache) {
1590 if (!this.inlineCopiesVisible(liId)) {
1596 for (var liId in this.liCache) {
1597 var row = dojo.byId('acq-inline-copies-row-' + liId);
1599 if (!row || row._hidden) {
1600 this.drawInlineCopies(liId);
1602 } else { // hide all
1604 // drawInlineCopies() on a visible row will hide it.
1605 this.drawInlineCopies(liId);
1612 this.inlineCopiesVisible = function(liId) {
1613 var row = dojo.byId('acq-inline-copies-row-' + liId);
1614 return (row && !row._hidden);
1617 this.refreshInlineCopies = function(all, reFetch) {
1619 var liIds = this.inlineCopiesNeedingRefresh;
1620 if (all) liIds = openils.Util.objectProperties(liCache);
1621 liIds.forEach(function(liId) {
1622 if (self.inlineCopiesVisible(liId)) {
1623 self.drawInlineCopies(liId, reFetch); // hide
1624 self.drawInlineCopies(liId, reFetch); // re-draw
1629 // draw inline copy table. if the table is
1630 // already visible, hide the table as-is
1631 // reFetch forces a retrieval of the lineitem and
1632 // copies from the server. otherwise the locally
1633 // cached version of each is used.
1634 this.drawInlineCopies = function(liId, reFetch) {
1637 // find or create the row where the inline copies table will live
1638 var containerRow = dojo.byId('acq-inline-copies-row-' + liId);
1639 var liRow = dojo.query('[li=' + liId + ']')[0];
1641 if (!containerRow) {
1643 // build the inline copies container row and add it to
1644 // the DOM directly after the primary lineitem row
1646 containerRow = self.inlineCopyContainer.cloneNode(true);
1647 containerRow.id = 'acq-inline-copies-row-' + liId;
1649 if (liRow.nextSibling) {
1650 self.tbody.insertBefore(containerRow, liRow.nextSibling);
1652 self.tbody.appendChild(containerRow);
1657 // toggle the visible state
1658 containerRow._hidden = !containerRow._hidden;
1659 openils.Util.toggle(containerRow, 'table-row');
1661 if (containerRow._hidden) return; // hide only
1664 var handler = function(li) {
1666 var tbody = dojo.query(
1667 '[name=acq-li-inline-copies-tbody]',
1670 // reset the table before adding copy rows
1671 while (tbody.childNodes[0])
1672 tbody.removeChild(tbody.childNodes[0]);
1674 if(li.lineitem_details().length == 0) {
1676 self.inlineNoCopies.cloneNode(true));
1677 return; // no copies to show
1680 // add a row to the inline copy table for each copy
1681 dojo.forEach(li.lineitem_details(),
1683 var row = self.inlineCopyTemplate.cloneNode(true);
1684 tbody.appendChild(row);
1685 self.addInlineCopy(li, copy, row);
1690 this._fetchLineitem(liId, handler, reFetch);
1693 /** Draw read-only copy widgets for inline copies */
1694 this.addInlineCopy = function(li, copy, row) {
1697 dojo.forEach(liDetailFields,
1700 var widget = new openils.widget.AutoFieldWidget({
1703 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1704 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1705 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1707 parentNode : dojo.query('[name=' + field + ']', row)[0],
1716 /* For a given list of lineitem ids, build a list of full lineitems
1717 * re-using the fetching logic that is otherwise typical to use in this
1720 * If we've already got a lineitem in the cache, just use that.
1722 * Once we've built a list of lineitems, call callback(thatlist).
1724 this.fetchLineitemsById = function(id_list, callback) {
1725 var total = id_list.length;
1726 var result_list = [];
1728 var inner = function(li) {
1729 result_list.push(li)
1731 callback(result_list);
1734 id_list.forEach(function(id) { self._fetchLineitem(id, inner); });
1737 this._fetchLineitem = function(liId, handler, force) {
1739 var li = this.liCache[liId];
1740 if(li && li.marc() && li.lineitem_details() && !force)
1743 fieldmapper.standardRequest(
1744 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
1747 params: [self.authtoken, liId, {
1749 flesh_cancel_reason: true,
1750 flesh_li_details: true,
1752 flesh_fund_debit: true }],
1754 oncomplete: function(r) {
1755 var li = openils.Util.readResponse(r);
1756 self.liCache[liId] = li;
1763 this._drawInfo = function(li) {
1765 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
1767 if(li.eg_bib_id()) {
1768 openils.Util.hide('acq-lit-marc-order-record-label');
1769 openils.Util.hide(acqLitEditOrderMarc.domNode);
1770 openils.Util.show('acq-lit-marc-real-record-label');
1772 openils.Util.show('acq-lit-marc-order-record-label');
1773 openils.Util.show(acqLitEditOrderMarc.domNode);
1774 openils.Util.hide('acq-lit-marc-real-record-label');
1777 this.drawMarcHTML(li);
1778 this.infoTbody = dojo.byId('acq-lit-info-tbody');
1781 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
1782 while(this.infoTbody.childNodes[0])
1783 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
1785 for(var i = 0; i < li.attributes().length; i++) {
1786 var attr = li.attributes()[i];
1787 var row = this.infoRow.cloneNode(true);
1789 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
1790 var name = openils.acq.Lineitem.attrDefs[type].filter(
1792 return (a.code() == attr.attr_name());
1794 ).pop().description();
1796 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
1797 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
1798 this.infoTbody.appendChild(row);
1801 if (!this._isRelatedViewer) {
1802 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
1803 oilsBasePath + "/acq/lineitem/related/" + li.id();
1806 // if a top scroll point is defined, jump up to it here
1807 var node = dojo.byId('oils-scroll-to-top');
1808 if (node) dijit.scrollIntoView(node);
1811 this.generateMakeRecTab = function(bib_id,default_view, row) {
1813 if(openils.XUL.isXUL() && !window.IAMBROWSER) {
1816 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
1819 show_nav_buttons : true,
1820 show_print_button : true,
1821 opac_url : xulG.url_prefix('opac_rdetail|' + bib_id),
1822 default_view : default_view
1826 var url = '/eg/staff/cat/catalog/record/' + bib_id;
1827 if (default_view == 'copy_browser') {
1833 if(row) nodeByName("action_none", row).selected = true;
1837 this.drawMarcHTML = function(li) {
1838 var params = [null, true, li.marc()];
1840 params = [li.eg_bib_id(), true];
1842 fieldmapper.standardRequest(
1843 ['open-ils.search', 'open-ils.search.biblio.record.html'],
1846 oncomplete: function(r) {
1847 dojo.byId('acq-lit-marc-div').innerHTML =
1848 openils.Util.readResponse(r);
1854 this.drawCopies = function(liId, force_fetch) {
1855 this.focusLineitem = liId;
1856 if (typeof force_fetch == "undefined")
1857 force_fetch = false;
1859 var cgi = new openils.CGI();
1860 var source = cgi.param('source');
1861 if (source && source.match(/invoice/)) {
1862 // got here from the invoice page, show the 'return-to-invoice' button
1863 var cgi = new openils.CGI({url : source});
1864 cgi.param('focus_li', liId);
1865 openils.Util.show(dojo.byId('acq-lit-copies-back-to-invoice-button-wrapper'), 'inline');
1866 var button = dojo.byId('acq-lit-copies-back-to-invoice-button');
1867 button.onclick = function() { location.href = cgi.url() };
1870 openils.acq.Lineitem.fetchAndRender(liId, {},
1871 function(li, html) {
1872 dojo.byId('acq-lit-copies-li-summary').innerHTML = html;
1876 this.show('copies');
1878 this.copyCache = {};
1879 this.copyWidgetCache = {};
1880 this.oldCopyWidgetCache = {};
1881 this.virtDfaCounts = {};
1882 this.realDfaCache = {};
1885 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
1886 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
1887 acqLitCopyCountInput.attr('value', '0');
1889 if (this.isPO && PO && PO.order_date()) {
1890 // prevent adding copies to activated POs
1891 acqLitCopyCountInput.attr('disabled', true);
1892 acqLitAddCopyCount.attr('disabled', true);
1895 while(this.copyTbody.childNodes[0])
1896 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
1898 this._drawBatchCopyWidgets();
1900 this._drawDistribApplied(liId);
1902 this._fetchDistribFormulas(
1904 openils.acq.Lineitem.fetchAttrDefs(
1906 self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch);
1913 this._saveDistribAppliedTemplates = function() {
1914 if (!this._appliedDistribTemplate) {
1915 this._appliedDistribTemplate =
1916 dojo.byId("acq-lit-distrib-applied-tbody").
1917 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
1918 dojo.attr(this._appliedDistribTemplate, "id");
1922 this._drawDistribApplied = function(liId) {
1923 /* Build this table while hidden to prevent rendering artifacts */
1924 openils.Util.hide("acq-lit-distrib-applied-tbody");
1926 this._saveDistribAppliedTemplates();
1928 /* Remove any rows in the table from previous populations */
1929 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
1930 forEach(dojo.destroy);
1932 /* Unregister all dijits previously created (for some reason this isn't
1933 * covered by the above destroy calls). */
1934 dijit.registry.forEach(
1935 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
1938 /* Populate the table with our liId */
1940 fieldmapper.standardRequest(
1942 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
1945 "params": [self.authtoken, liId],
1946 "onresponse": function(r) {
1947 var dfa = openils.Util.readResponse(r);
1950 self.realDfaCache[dfa.id()] = dfa;
1951 self._drawDistribAppliedUnit(dfa);
1954 "oncomplete": function() {
1955 /* Reveal built table */
1958 "acq-lit-distrib-applied-tbody", "table-row-group"
1966 this._drawDistribAppliedUnit = function(dfa) {
1967 var new_row = false;
1968 var row = dojo.query(
1969 'tr[formula="' + dfa.formula().id() + '"]',
1970 "acq-lit-distrib-applied-tbody"
1975 row = dojo.clone(this._appliedDistribTemplate);
1976 dojo.attr(row, "formula", dfa.formula().id());
1977 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
1980 var td = dojo.query("td", row)[0];
1982 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1983 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1986 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1988 new dijit.form.Button(
1990 "onClick": function() {
1991 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1992 self.deleteDfa(dfa);
1995 /* XXX I /cannot/ make the following work in as a CSS class
1996 * for some reason. So frustrating... */
1997 "style": function(id) {
1999 "font-weight: bold; color: #c00;" :
2001 }(dfa.id()) + "margin: 0 6px;display: inline;"
2002 }, "dfa-button-" + dfa.id()
2006 "connectId": ["dfa-button-" + dfa.id()],
2007 "label": dojo.string.substitute(
2008 localeStrings.DFA_TIP, dfa.id() > 0 ? [
2009 openils.User.formalName(dfa.creator()),
2010 dojo.date.locale.format(
2011 dojo.date.stamp.fromISOString(dfa.create_time()),
2012 {"formatLength":"short"}
2014 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
2016 }, "dfa-tip-" + dfa.id()
2020 this.deleteDfa = function(dfa) {
2021 if (dfa.id() > 0) { /* real */
2022 this.pcrud.eliminate(
2025 "oncomplete": function() {
2026 self._removeDistribApplied(dfa.id());
2027 delete self.realDfaCache[dfa.id()];
2031 } else { /* virtual */
2032 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
2033 this.virtDfaCounts[dfa.formula().id()] = 0;
2034 /* hasn't been saved yet, so no need to do anything server side */
2035 this._removeDistribApplied(dfa.id());
2040 this._removeDistribApplied = function(dfaId) {
2041 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
2042 dijit.registry.forEach(
2043 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
2045 this._removeDistribAppliedEmptyRows();
2048 this._removeAllDistribAppliedVirtual = function() {
2049 /* Unregister dijits */
2050 dijit.registry.forEach(
2051 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
2053 this._removeDistribAppliedEmptyRows();
2056 this._removeDistribAppliedEmptyRows = function() {
2057 /* Remove any rows with no DFA at all */
2058 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
2060 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
2066 * Insert a new row into the distribution formula selection form
2068 this._addDistribFormulaRow = function() {
2071 if (!self.distribForms) {
2072 // no formulas, hide the form
2073 openils.Util.hide('acq-lit-distrib-formula-table');
2077 if(!this.distribFormulaTemplate)
2078 this.distribFormulaTemplate =
2079 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
2081 var row = this.distribFormulaTemplate.cloneNode(true);
2082 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
2084 this.dfSelector = new dijit.form.FilteringSelect(
2085 {"labelAttr": "dynLabel", "labelType": "html"},
2086 nodeByName("selector", row)
2088 this._updateFormulaStore();
2089 this.dfSelector.fetchProperties =
2090 {"sort": [{"attribute": "use_count", "descending": true}]};
2092 var apply = new dijit.form.Button(
2093 {"label": localeStrings.APPLY},
2094 nodeByName('set_button', row)
2097 var reset = new dijit.form.Button(
2098 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
2099 nodeByName("reset_button", row)
2102 dojo.connect(apply, 'onClick',
2104 var form_id = self.dfSelector.attr("value");
2105 if(!form_id) return;
2106 self._applyDistribFormula(form_id);
2107 reset.attr("disabled", false);
2111 dojo.connect(reset, 'onClick',
2113 self.restoreCopyFieldsBeforeDF();
2114 self.virtDfaCounts = {};
2115 self.virtDfaId = -1;
2117 self._updateFormulaStore();
2118 self._removeAllDistribAppliedVirtual();
2119 reset.attr("disabled", "true");
2126 * Applies a distrib formula to the current set of copies
2128 this._applyDistribFormula = function(formula) {
2129 if(!formula) return;
2131 formula = this.distribForms.filter(
2132 function(form) { return form.id() == formula; }
2135 var copyRows = dojo.query('tr', self.copyTbody);
2137 if (this.dfeOffset >= copyRows.length) {
2138 alert(localeStrings.OUT_OF_COPIES);
2142 var entries_applied = 0;
2144 var rowIndex = this.dfeOffset;
2145 rowIndex < copyRows.length;
2149 var row = copyRows[rowIndex];
2150 var copy_id = row.getAttribute('copy_id');
2151 var copyWidgets = this.copyWidgetCache[copy_id];
2152 var entryIndex = this.dfeOffset;
2155 // find the correct entry for the current row
2156 dojo.forEach(formula.entries(),
2159 entryIndex += e.item_count();
2160 if(entryIndex > rowIndex)
2168 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
2169 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
2172 this.saveCopyFieldsBeforeDF(copy_id);
2173 this._copy_fields_for_acqdf.forEach(
2175 if(entry[field]()) {
2176 copyWidgets[field].attr('value', (entry[field]()));
2183 if (entries_applied) {
2184 this.virtDfaCounts[formula.id()] =
2185 ++(this.virtDfaCounts[formula.id()]) || 1;
2186 this._updateFormulaStore();
2187 this._drawDistribAppliedUnit(
2189 var dfa = new acqdfa();
2190 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
2193 this.dfeOffset += entries_applied;
2198 * This function updates the DF store for the dropdown so that use_counts
2199 * can reflect DF applications from this session before they're saved
2202 this._updateFormulaStore = function() {
2203 this.dfSelector.store = new dojo.data.ItemFileReadStore(
2205 "data": self._labelFormulasWithCounts(
2206 acqdf.toStoreData(self.distribForms)
2212 this.saveCopyFieldsBeforeDF = function(copy_id) {
2214 if (!this.oldCopyWidgetCache[copy_id]) {
2215 var copyWidgets = this.copyWidgetCache[copy_id];
2217 this.oldCopyWidgetCache[copy_id] = {};
2218 this._copy_fields_for_acqdf.forEach(
2220 self.oldCopyWidgetCache[copy_id][f] =
2221 copyWidgets[f].attr("value");
2227 this.restoreCopyFieldsBeforeDF = function() {
2229 for (var copy_id in this.oldCopyWidgetCache) {
2230 this._copy_fields_for_acqdf.forEach(
2232 self.copyWidgetCache[copy_id][f].attr(
2233 "value", self.oldCopyWidgetCache[copy_id][f]
2240 this._labelFormulasWithCounts = function(store_data) {
2241 for (var key in store_data.items) {
2242 var obj = store_data.items[key];
2243 obj.use_count = Number(obj.use_count); /* needed for sorting */
2245 if (this.virtDfaCounts[obj.id])
2246 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
2248 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
2249 obj.use_count + "]</span> " + obj.name;
2255 * This method formerly would not refetch the DF formulas if they'd been
2256 * loaded already, but now it always re-fetches, since use_count changes.
2258 /** TODO: port distrib-formula selector to autofieldwidget+pcrud/dojo store */
2259 this._fetchDistribFormulas = function(onload) {
2260 fieldmapper.standardRequest(
2262 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
2265 "params": [openils.User.authtoken, 0, 500],
2266 "oncomplete": function(r) {
2267 self.distribForms = openils.Util.readResponse(r);
2268 if(!self.distribForms || self.distribForms.length == 0) {
2269 self.distribForms = [];
2271 self._addDistribFormulaRow();
2278 this._drawBatchCopyWidgets = function() {
2279 var row = this.copyBatchRow;
2280 dojo.forEach(liDetailBatchFields,
2282 if(self.copyBatchRowDrawn) {
2283 self.copyBatchWidgets[field].attr('value', null);
2285 var args = self.afwCopyFieldArgs(field, "CREATE_PICKLIST");
2286 args.parentNode = dojo.query('[name='+field+']', row)[0];
2288 var widget = new openils.widget.AutoFieldWidget(args);
2291 if (field == "fund" && w.store)
2292 self._ensureCSSFundClasses(w.store);
2293 self.copyBatchWidgets[field] = w;
2296 if (field == "fund") {
2298 widget.widget, "onChange", function(val) {
2299 self._updateFundSelectorStyle(widget, val);
2306 this.copyBatchRowDrawn = true;
2309 this.batchCopyUpdate = function() {
2311 for(var k in this.copyWidgetCache) {
2312 var cache = this.copyWidgetCache[k];
2313 dojo.forEach(liDetailBatchFields, function(f) {
2314 var newval = self.copyBatchWidgets[f].attr('value');
2315 if(newval) cache[f].attr('value', newval);
2320 this._drawCopies = function(li) {
2323 // this button sets the total number of copies for a given lineitem
2324 acqLitAddCopyCount.onClick = function() {
2325 var count = acqLitCopyCountInput.attr('value');
2328 while(self.copyCount() < count)
2331 // delete rows if necessary
2332 var diff = self.copyCount() - count;
2334 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
2335 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
2336 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
2338 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2344 if(li.lineitem_details().length > 0) {
2345 dojo.forEach(li.lineitem_details(),
2347 self.addCopy(li, copy);
2355 this.copyCount = function() {
2357 for(var id in this.copyCache) {
2358 if(!this.copyCache[id].isdeleted())
2364 this.virtCopyId = -1;
2365 this.addCopy = function(li, copy) {
2366 var row = this.copyRow.cloneNode(true);
2367 this.copyTbody.appendChild(row);
2371 copy = new fieldmapper.acqlid();
2373 copy.id(this.virtCopyId--);
2374 copy.lineitem(li.id());
2377 this.copyCache[copy.id()] = copy;
2378 row.setAttribute('copy_id', copy.id());
2379 self.copyWidgetCache[copy.id()] = {};
2381 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2383 var rcvr = copy.receiver();
2385 if (!userCache[rcvr]) {
2386 if(rcvr == openils.User.user.id()) {
2387 userCache[rcvr] = openils.User.user;
2389 userCache[rcvr] = fieldmapper.standardRequest(
2390 ['open-ils.actor', 'open-ils.actor.user.retrieve'],
2391 {params: [openils.User.authtoken, rcvr]}
2395 dojo.query('[name=receiver]', row)[0].innerHTML = userCache[rcvr].usrname();
2398 dojo.forEach(liDetailFields,
2401 if (field == "fund") {
2402 searchFilter = (copy.fund() ?
2403 {"-or": {"active": "t", "id": copy.fund()}} :
2405 searchFilter.org = fundSearchFilter.org;
2407 searchFilter = null;
2410 var readOnly = false;
2412 // TODO: Add support for changing the owning_lib after real copies have been made.
2413 // owning_lib is order data as much as its item data
2414 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
2418 // TODO: add support for changing the fund after debits have been created
2419 // Note: invoicing allows the change
2420 if(copy.fund_debit() && field == 'fund') {
2425 var widget = new openils.widget.AutoFieldWidget({
2428 labelFormat : (field == 'fund') ? fundLabelFormat : null,
2429 searchFormat : (field == 'fund') ? fundSearchFormat : null,
2430 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
2431 searchFilter : searchFilter,
2432 noCache: (field == "fund"),
2434 parentNode : dojo.query('[name='+field+']', row)[0],
2435 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2436 readOnly : readOnly,
2437 orgDefaultsToWs : true
2441 // make sure we capture the value from any async widgets
2444 if (field == "fund" && w.store)
2445 self._ensureCSSFundClasses(w.store);
2448 copy[field](ww.getFormattedValue())
2450 self.copyWidgetCache[copy.id()][field] = w;
2452 dojo.connect(w, 'onChange',
2454 if (field == "fund")
2455 self._updateFundSelectorStyle(widget, val);
2457 if (!readOnly && (copy.isnew() || val != copy[field]())) {
2458 // prevent setting ischanged() automatically on widget load for existing copies
2459 copy[field](widget.getFormattedValue())
2460 copy.ischanged(true);
2469 this.updateLidState(copy, row);
2472 this._ensureCSSFundClass = function(id) {
2473 if (!this.fundStyleSheet) {
2475 "style", {"type": "text/css"},
2476 document.getElementsByTagName("head")[0], "last"
2478 this.fundStyleSheet = document.styleSheets[
2479 document.styleSheets.length - 1
2483 var cn = "fund_" + id;
2484 if (!this.haveFundClass[cn]) {
2485 fieldmapper.standardRequest(
2486 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
2488 "params": [openils.User.authtoken, id],
2490 "oncomplete": function(r) {
2491 r = openils.Util.readResponse(r);
2492 self.fundBalanceState[id] = r;
2494 if (r[0] /* stop */)
2495 style = fundStyles.stop;
2496 else if (r[1] /* warning */)
2497 style = fundStyles.warning;
2498 self.fundStyleSheet.insertRule(
2499 "." + cn + " { " + style + " }",
2500 self.fundStyleSheet.cssRules.length
2502 self.haveFundClass[cn] = true;
2509 this._ensureCSSFundClasses = function(store) {
2511 "query": {"id": "*"},
2512 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
2516 this._updateFundSelectorStyle = function(widget, fund_id) {
2517 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
2518 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
2521 this.updateLidState = function(copy, row) {
2524 if (typeof(row) == "undefined") {
2525 row = dojo.query('tr[copy_id="' + copy.id() + '"]', this.copyTbody)[0];
2529 var recv_link = nodeByName("receive", row);
2530 var unrecv_link = nodeByName("unreceive", row);
2531 var del_link = nodeByName("delete", row);
2532 var cxl_link = nodeByName("cancel", row);
2533 var claim_link = nodeByName("claim", row);
2534 var cxl_reason_link = nodeByName("cancel_reason", row);
2536 // by default, hide all the actions
2537 openils.Util.hide(del_link.parentNode);
2538 openils.Util.hide(recv_link);
2539 openils.Util.hide(unrecv_link);
2540 openils.Util.hide(cxl_link);
2541 openils.Util.hide(claim_link);
2542 openils.Util.hide(cxl_reason_link);
2544 if (copy.id() > 0) { // real copies (LIDs)
2546 if (copy.cancel_reason()) {
2548 /* --------- cancelled -------------------------- */
2550 /* XXX the following may leak memory in a long lived table:
2551 * dijits may not get destroyed... not positive. revisit. */
2552 var holds_reason = dojo.create(
2554 "style": "border-bottom: 1px dashed #000;",
2555 "innerHTML": copy.cancel_reason().label()
2556 }, cxl_reason_link, "only"
2560 "label": "<em>" + copy.cancel_reason().label() +
2561 "</em><br />" + copy.cancel_reason().description(),
2562 "connectId": [holds_reason]
2563 }, dojo.create("span", null, cxl_reason_link, "last")
2565 openils.Util.show(cxl_reason_link, "inline");
2567 if (copy.cancel_reason().keep_debits() == 't' ) {
2568 // allow further cancellation of "delayed" copies
2570 openils.Util.show(cxl_link, "inline");
2571 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2574 } else if (copy.recv_time()) {
2576 /* --------- received -------------------------- */
2578 openils.Util.show(unrecv_link, "inline");
2579 unrecv_link.onclick = function() {
2580 if (confirm(localeStrings.UNRECEIVE_LID))
2581 self.issueReceive(copy, /* rollback */ true);
2584 } else if (this.liCache[copy.lineitem()].state() == 'on-order') {
2586 /* --------- on order -------------------------- */
2588 openils.Util.show(recv_link, 'inline');
2589 openils.Util.show(cxl_link, "inline");
2591 recv_link.onclick = function() {
2592 if (self.checkLiAlerts(copy.lineitem()))
2593 self.issueReceive(copy);
2596 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2600 /* --------- pre-order copies -------------------------- */
2602 del_link.onclick = function() { self.deleteCopy(row) };
2603 openils.Util.show(del_link.parentNode);
2609 /* --------- virtual copies -------------------------- */
2611 del_link.onclick = function() { self.deleteCopy(row) };
2612 openils.Util.show(del_link.parentNode);
2616 this.cancelLid = function(lid_id) {
2617 lidCancelDialog._lid_id = lid_id;
2618 openils.Util.show(lidCancelDialog.domNode.parentNode);
2619 lidCancelDialog.show();
2620 if (!lidCancelDialog._prepared) {
2621 var widget = new openils.widget.AutoFieldWidget({
2622 "fmField": "cancel_reason",
2623 "fmClass": "acqlid",
2624 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
2625 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2627 "searchOptions" : {order_by : {"acqcr":"label"}}
2631 acqLidCancelButton.onClick = function() {
2632 if (w.attr("value")) {
2633 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
2635 lidCancelDialog._lid_id,
2639 lidCancelDialog.hide();
2642 lidCancelDialog._prepared = true;
2648 this._cancelLid = function(lid_id, reason) {
2649 fieldmapper.standardRequest(
2650 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
2651 "params": [openils.User.authtoken, lid_id, reason],
2653 "onresponse": function(r) {
2654 if (r = openils.Util.readResponse(r)) {
2656 for (var id in r.lid) {
2657 /* actually this should only iterate once */
2658 self.copyCache[id].cancel_reason(
2659 r.lid[id].cancel_reason
2661 self.updateLidState(self.copyCache[id]);
2670 this._confirmAlert = function(li, lin) {
2672 dojo.string.substitute(
2673 localeStrings.CONFIRM_LI_ALERT, [
2674 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2675 "title", "lineitem_marc_attr_definition"
2677 /* XXX it's really better add a parameter and to adjust
2678 * the format string rather than do this concatenation
2679 * here, but if someone wants this for 2.2 in a hurry,
2680 * we can sidestep the problem of updating the strings
2681 * while the translators are working. */
2683 aou.findOrgUnit(lin.alert_text().owning_lib()).shortname() +
2685 lin.alert_text().code()
2687 lin.alert_text().description() || "",
2694 this.checkLiAlerts = function(li_id) {
2695 var li = this.liCache[li_id];
2697 var alert_notes = li.lineitem_notes().filter(
2698 function(o) { return Boolean(o.alert_text()); }
2701 /* this is _intentionally_ not done in a call to forEach() ... */
2702 for (var i = 0; i < alert_notes.length; i++) {
2703 if (this.noteAcks[alert_notes[i].id()])
2705 else if (!this._confirmAlert(li, alert_notes[i]))
2708 this.noteAcks[alert_notes[i].id()] = true;
2714 this.deleteCopy = function(row) {
2715 var copy = this.copyCache[row.getAttribute('copy_id')];
2716 copy.isdeleted(true);
2718 delete this.copyCache[copy.id()];
2719 this.copyTbody.removeChild(row);
2722 this._virtDfaCountsAsList = function() {
2724 for (var key in this.virtDfaCounts) {
2725 for (var i = 0; i < this.virtDfaCounts[key]; i++)
2731 this.confirmBreachedCopyFunds = function(copies) {
2732 var stop = 0, warning = 0;
2736 var state = self.fundBalanceState[o.fund()];
2737 if (state[0] /* stop */)
2739 else if (state[1] /* warning */)
2746 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
2747 } else if (warning) {
2748 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
2753 this.saveCopyChanges = function(liId) {
2759 for(var id in this.copyCache) {
2760 var c = this.copyCache[id];
2761 if(!c.isdeleted()) total++;
2762 if(c.isnew() || c.ischanged() || c.isdeleted()) {
2763 if(c.id() < 0) c.id(null);
2769 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
2772 if (copies.length > 0) {
2773 if (!this.confirmBreachedCopyFunds(copies))
2776 if (typeof(this._copy_count_cb) == "function")
2777 this._copy_count_cb(liId, total);
2779 openils.Util.show("acq-lit-update-copies-progress");
2780 fieldmapper.standardRequest(
2781 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
2783 params: [openils.User.authtoken, copies],
2784 onresponse: function(r) {
2785 var res = openils.Util.readResponse(r);
2786 litUpdateCopiesProgress.update(res);
2788 oncomplete: function() {
2789 self.drawCopies(liId, true /* force_fetch */);
2790 openils.Util.hide("acq-lit-update-copies-progress");
2791 refreshPOSummaryAmounts();
2797 var dfa_list = this._virtDfaCountsAsList();
2798 if (dfa_list.length > 0) {
2799 fieldmapper.standardRequest(
2801 "open-ils.acq.distribution_formula.record_application"],
2804 "params": [openils.User.authtoken, dfa_list, liId],
2805 "onresponse": function(r) {
2806 var res = openils.Util.readResponse(r);
2807 if (res && res.length < dfa_list.length)
2808 alert(localeStrings.DFA_NOT_ALL);
2812 this.virtDfaCounts = {};
2815 if (this.inlineCopiesNeedingRefresh.indexOf(liId) < 0)
2816 this.inlineCopiesNeedingRefresh.push(liId);
2819 this._updateCreatePoPrepayCheckbox = function(prepay) {
2820 var prepay = openils.Util.isTrue(prepay);
2821 this._prepayRequiredByVendor = prepay;
2822 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
2825 this._confirmPoPrepaySituation = function() {
2826 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
2827 if (want_prepay != this._prepayRequiredByVendor) {
2830 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
2831 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
2838 this.applySelectedLiAction = function(action) {
2842 case 'delete_selected':
2843 this._deleteLiList(self.getSelected());
2846 case 'add_to_order':
2847 addToPoDialog._get_li = dojo.hitch(
2850 return this.getSelected(
2851 false, null, true, li_pre_po_states);
2854 if (addToPoDialog._get_li().length == 0) {
2855 alert(localeStrings.NO_LI_GENERAL);
2858 addToPoDialog.show();
2861 case 'create_order':
2862 this._loadPOSelect();
2863 acqLitPoCreateDialog.show();
2866 case 'save_picklist':
2867 acqLitSavePlDialog.show();
2870 case 'selector_ready':
2872 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
2873 acqLitChangeLiStateDialog.show();
2881 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
2884 case 'batch_create_invoice':
2885 this.batchCreateInvoice();
2888 case 'batch_link_invoice':
2889 this.batchLinkInvoice();
2892 case 'receive_lineitems':
2893 this.receiveSelectedLineitems();
2896 case 'rollback_receive_lineitems':
2897 this.rollbackReceiveLineitems();
2900 case 'create_assets':
2901 this.showAssetCreator();
2904 case 'export_attr_list':
2905 this.chooseExportAttr();
2908 case 'batch_apply_funds':
2909 this.applyBatchLiFunds();
2912 case 'add_brief_record':
2914 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
2916 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
2920 case "cancel_lineitems":
2921 console.log('HERE');
2922 this.maybeCancelLineitems();
2925 case "apply_claim_policy":
2926 var li_list = this.getSelected();
2927 this.claimPolicyPicker.attr("value", null);
2928 liClaimPolicyDialog.show();
2929 liClaimPolicySave.onClick = function() {
2930 self.changeClaimPolicy(
2932 self.claimPolicyPicker.attr("value"),
2936 self.setClaimPolicyControl(li);
2937 self.reconsiderClaimControl(li);
2940 liClaimPolicyDialog.hide();
2948 this.changeClaimPolicy = function(li_list, value, callback) {
2950 function(li) { li.claim_policy(value); }
2952 fieldmapper.standardRequest(
2953 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
2954 "params": [openils.User.authtoken, li_list],
2956 "oncomplete": function(r) {
2957 r = openils.Util.readResponse(r);
2958 if (callback) callback(r);
2964 this.showAssetCreator = function(onAssetsCreated) {
2965 if(!this.isPO) return;
2968 // first, let's see if this PO has any LI's that need to be merged/imported
2969 self.pcrud.search('jub', {purchase_order : this.isPO, eg_bib_id : null}, {
2971 oncomplete : function(r) {
2972 var resp = openils.Util.readResponse(r);
2973 if (resp && resp.length) {
2974 // PO has some non-linked jubs.
2976 self.show('asset-creator');
2977 if(!self.vlAgent.loaded)
2978 self.vlAgent.init();
2980 dojo.connect(assetCreatorButton, 'onClick',
2981 function() { self.createAssets(onAssetsCreated) });
2985 // all jubs linked, move on to asset creation
2986 self.createAssets(onAssetsCreated, true);
2992 this.createAssets = function(onAssetsCreated, noVl) {
2993 this.show('acq-lit-progress-numbers');
2995 var vlArgs = (noVl) ? {} : {vandelay : this.vlAgent.values()};
2996 this.batchProgress = {};
2997 progressDialog.show(false);
2998 progressDialog.attr("title", localeStrings.LI_CREATING_ASSETS);
2999 fieldmapper.standardRequest(
3000 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
3002 params: [this.authtoken, this.isPO, vlArgs],
3003 onresponse: function(r) {
3004 var resp = openils.Util.readResponse(r);
3005 self._updateProgressNumbers(resp, !Boolean(onAssetsCreated), onAssetsCreated, true);
3011 this.maybeCancelLineitems = function() {
3012 openils.Util.show("acq-lit-cancel-reason", "inline");
3013 if (!acqLitCancelLineitemsButton._prepared) {
3014 var widget = new openils.widget.AutoFieldWidget({
3015 "fmField": "cancel_reason",
3017 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
3018 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3020 "searchOptions" : {order_by : {"acqcr":"label"}}
3024 acqLitCancelLineitemsButton.onClick = function() {
3025 if (w.attr("value")) {
3026 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
3027 self._cancelLineitems(w.attr("value"));
3029 openils.Util.hide("acq-lit-cancel-reason");
3032 acqLitCancelLineitemsButton._prepared = true;
3038 this._cancelLineitems = function(reason) {
3040 var li_list = this.getSelected();
3042 // canceled lineitems may be canceled again if they were
3043 // previously delayed (keep_debits = true).
3044 li_list = li_list.filter(
3047 li.state() != 'cancelled' ||
3048 li.cancel_reason().keep_debits() == 't'
3053 id_list = li_list.map(function(l) {return l.id()});
3055 if (!id_list.length) {
3056 alert(localeStrings.NO_LI_GENERAL);
3059 fieldmapper.standardRequest(
3060 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
3061 "params": [openils.User.authtoken, id_list, reason],
3063 "onresponse": function(r) {
3064 if (r = openils.Util.readResponse(r)) {
3066 for (var id in r.li) {
3067 self.liCache[id].state(r.li[id].state);
3068 self.liCache[id].cancel_reason(
3069 r.li[id].cancel_reason
3071 self.updateLiState(self.liCache[id]);
3074 if (r.lid && self.copyCache) {
3075 for (var id in r.lid) {
3076 if (self.copyCache[id]) {
3077 self.copyCache[id].cancel_reason(
3078 r.lid[id].cancel_reason
3080 self.updateLidState(self.copyCache[id]);
3090 this.chooseExportAttr = function() {
3091 if (!acqLitExportAttrSelector._li_setup) {
3093 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
3095 "data": acqlimad.toStoreData(
3097 "acqlimad", {"code": li_exportable_attrs}
3102 acqLitExportAttrSelector.setValue();
3103 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
3104 acqLitExportAttrSelector._li_setup = true;
3106 openils.Util.show("acq-lit-export-attr-holder", "inline");
3109 this.exportAttrList = function() {
3110 var attr_def = acqLitExportAttrSelector.item;
3111 var li_list = this.getSelected();
3112 var value_list = li_list.map(
3114 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
3115 attr_def.code, "lineitem_marc_attr_definition"
3118 ).filter(function(attr) { return Boolean(attr); });
3120 if (value_list.length > 0) {
3121 if (value_list.length < li_list.length) {
3123 dojo.string.substitute(
3124 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
3131 if (window.IAMBROWSER) {
3132 var blob = new Blob(value_list, {type: "text/plain;charset=utf-8"});
3133 saveAs(blob, "export_attr_list.txt");
3135 openils.XUL.contentToFileSaveDialog(
3136 value_list.join("\n"),
3137 localeStrings.EXPORT_SAVE_DIALOG_TITLE
3144 alert(dojo.string.substitute(
3145 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
3149 openils.Util.hide("acq-lit-export-attr-holder");
3152 this.printPO = function() {
3153 if(!this.isPO) return;
3154 progressDialog.show(true);
3155 fieldmapper.standardRequest(
3156 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
3158 params: [this.authtoken, this.isPO, 'html'],
3159 oncomplete: function(r) {
3160 progressDialog.hide();
3161 var evt = openils.Util.readResponse(r);
3162 if(evt && evt.template_output()) {
3163 openils.Util.printHtmlString(evt.template_output().data());
3170 this.batchCreateInvoice = function() {
3171 var liIds = this.getSelected(
3172 false, null, true /* id_list */, li_active_states)
3173 if (!liIds.length) {
3174 alert(localeStrings.NO_LI_GENERAL);
3177 var path = oilsBasePath + '/acq/invoice/view?create=1';
3178 dojo.forEach(liIds, function(li, idx) { path += '&attach_li=' + li });
3179 if (openils.XUL.isXUL() && !window.IAMBROWSER)
3180 openils.XUL.newTabEasy(path, localeStrings.NEW_INVOICE, null, true);
3182 location.href = path;
3185 this.batchLinkInvoice = function(create) {
3186 var liIds = this.getSelected(
3187 false, null, true /* id_list */, li_active_states)
3188 if (!liIds.length) {
3189 alert(localeStrings.NO_LI_GENERAL);
3192 if (!self.invoiceLinkDialogManager) {
3193 self.invoiceLinkDialogManager =
3194 new InvoiceLinkDialogManager("li");
3196 self.invoiceLinkDialogManager.target = liIds;
3197 acqLitLinkInvoiceDialog.show();
3200 this.receiveSelectedLineitems = function() {
3201 var states = li_post_po_states.filter(
3202 function(s) { return s != 'received' });
3203 var li_list = this.getSelected(null, null, null, states);
3205 if (!li_list.length) {
3206 alert(localeStrings.NO_LI_GENERAL);
3210 for (var i = 0; i < li_list.length; i++) {
3211 var li = li_list[i];
3213 if (li.state() != "received" &&
3214 !this.checkLiAlerts(li.id())) return;
3217 this.show('acq-lit-progress-numbers');
3220 fieldmapper.standardRequest(
3221 ['open-ils.acq', 'open-ils.acq.lineitem.receive.batch'],
3225 li_list.map(function(li) { return li.id(); })
3227 onresponse : function(r) {
3228 var resp = openils.Util.readResponse(r);
3229 self._updateProgressNumbers(resp, true);
3235 this.issueReceive = function(obj, rollback) {
3237 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
3239 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
3241 progressDialog.show(true);
3242 fieldmapper.standardRequest(
3243 ["open-ils.acq", method], {
3245 "params": [this.authtoken, obj.id()],
3246 "onresponse": function(r) {
3247 if (r = openils.Util.readResponse(r)) {
3248 self.fetchClaimInfo(
3249 part == "lineitem" ? obj.id() : obj.lineitem(),
3251 function() { self.handleReceive(r); }
3253 progressDialog.hide();
3261 * Handles the responses from receive and rollback ML calls.
3263 this.handleReceive = function(resp) {
3266 for (var li_id in resp.li) {
3267 for (var key in resp.li[li_id])
3268 self.liCache[li_id][key](resp.li[li_id][key]);
3269 self.updateLiState(self.liCache[li_id]);
3273 if (typeof(self.poUpdateCallback) == "function")
3274 self.poUpdateCallback(resp.po);
3277 for (var lid_id in resp.lid) {
3278 for (var key in resp.lid[lid_id])
3279 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
3280 self.updateLidState(self.copyCache[lid_id]);
3286 this.rollbackReceiveLineitems = function() {
3287 var li_id_list = this.getSelected(false, null, true);
3288 if (!li_id_list.length) {
3289 alert(localeStrings.NO_LI_GENERAL);
3293 if (!confirm(localeStrings.ROLLBACK_LI_RECEIVE_CONFIRM)) return;
3295 this.show('acq-lit-progress-numbers');
3298 fieldmapper.standardRequest(
3299 ['open-ils.acq', 'open-ils.acq.lineitem.receive.rollback.batch'],
3301 params: [this.authtoken, li_id_list],
3302 onresponse : function(r) {
3303 var resp = openils.Util.readResponse(r);
3304 self._updateProgressNumbers(resp, true);
3310 this._updateProgressNumbers = function(resp, reloadOnComplete, onComplete, clearProgressDialog) {
3311 this._updateProgressDialog(resp);
3312 this.vlAgent.handleResponse(resp,
3313 function(resp, res) {
3314 if (clearProgressDialog) {
3315 progressDialog.update({ "progress": 100});
3316 progressDialog.update_message();
3317 progressDialog.hide();
3318 progressDialog.attr("title", "");
3320 if(reloadOnComplete)
3321 location.href = location.href;
3323 onComplete(resp, res);
3328 this._updateProgressDialog = function(resp) {
3329 progressDialog.update({ "progress": (resp.progress / resp.total) * 100 });
3330 var keys = ['li', 'vqbr', 'bibs', 'lid', 'debits_accrued', 'copies'];
3331 for (var i = 0; i < keys.length; i++) {
3332 if (resp[keys[i]] > (this.batchProgress[keys[i]] || 0)) {
3333 progressDialog.update_message(
3334 dojo.string.substitute(
3335 localeStrings["ACTIVATE_" + keys[i].toUpperCase() + "_PROCESSED"],
3341 this.batchProgress = resp;
3344 this._createPO = function(fields) {
3345 var wantall = (fields.create_from == "all");
3347 /* If we're a picklist or purchase order already and the user wants
3348 * all lineitems, we might have pages' worth of lineitems haven't all
3349 * been loaded yet, so getSelected() won't find them. The server,
3350 * however, should know about all our lineitems, so let's ask the
3351 * server for a complete list.
3356 true, function(list) {
3357 self._createPOFromLineitems(fields, list);
3358 }, /* id_list */ true, li_pre_po_states
3361 this._createPOFromLineitems(
3362 fields, this.getSelected(
3363 false, null, true /* id_list */, li_pre_po_states)
3368 this._createPOFromLineitems = function(fields, selected) {
3369 if (selected.length == 0) {
3370 alert(localeStrings.NO_LI_GENERAL);
3375 var po = new fieldmapper.acqpo();
3376 po.provider(this.createPoProviderSelector.attr("value"));
3377 po.ordering_agency(this.createPoAgencySelector.attr("value"));
3378 po.prepayment_required(fields.prepayment_required[0] ? true : false);
3379 var name = this.createPoNameInput.attr('value');
3380 if (name) po.name(name); // avoid name=""
3382 // if we're creating assets, delay the asset creation
3383 // until after the PO is created. This will allow us to
3384 // use showAssetCreator() directly.
3386 fieldmapper.standardRequest(
3387 ["open-ils.acq", "open-ils.acq.purchase_order.create"],
3390 openils.User.authtoken,
3391 po, {lineitems : selected}
3393 onresponse : function(r) {
3394 var resp = openils.Util.readResponse(r);
3395 if (resp.complete) {
3396 // self.isPO is needed for showAssetCreator();
3397 self.isPO = resp.purchase_order.id();
3398 var redir = oilsBasePath + "/acq/po/view/" + self.isPO;
3399 if (fields.create_assets[0]) {
3400 self.showAssetCreator(
3401 function() {location.href = redir}
3404 location.href = redir;
3413 this.batchFundWidget = null;
3415 this.applyBatchLiFunds = function() {
3417 var liIds = this.getSelected().map(function(li) { return li.id(); });
3418 if(liIds.length == 0) return; // warn?
3421 batchFundUpdateDialog.show();
3423 if(!this.batchFundWidget) {
3424 this.batchFundWidget = new openils.widget.AutoFieldWidget({
3426 selfReference : true,
3427 labelFormat : fundLabelFormat,
3428 searchFormat : fundSearchFormat,
3429 searchFilter : fundSearchFilter,
3430 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
3431 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
3432 dijitArgs : { "required": true, "labelType": "html" },
3435 this.batchFundWidget.build();
3438 dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
3439 dojo.connect(batchFundUpdateSubmit, 'onClick',
3442 // TODO: call .dry_run first to test thresholds
3443 fieldmapper.standardRequest(
3444 ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
3447 openils.User.authtoken,
3449 self.batchFundWidget.widget.attr('value')
3451 oncomplete : function(r) {
3452 var resp = openils.Util.readResponse(r);
3454 location.href = location.href;
3463 this._deleteLiList = function(list, idx) {
3464 if(idx == null) idx = 0;
3465 if(idx >= list.length) return;
3470 if (this.isPO && (li.state() == "on-order" || li.state() == "received")) {
3471 /* It makes little sense to delete a lineitem from a PO that has
3472 * already been marked 'on-order'. Especially if EDI is in use,
3473 * such a purchase order will probably have already been shipped
3474 * off to a vendor, and mucking with it at this point could leave
3475 * your data in a bad state that doesn't jive with reality.
3477 * I could see making this restriction even firmer.
3479 * I could also see adjusting the li state comparisons, extending
3480 * the comparison to the PO's state, and/or providing functions
3481 * that house the logic for comparing states in a single location.
3483 * Yes, this will be really annoying if you have selected a lot
3484 * of lineitems to cancel that have been ordered. You'll get a
3485 * confirm dialog for each one.
3488 if (!confirm(localeStrings.DEL_LI_FROM_PO)) {
3489 self._deleteLiList(list, ++idx); /* move on to next in list */
3494 fieldmapper.standardRequest(
3496 this.isPO ? 'open-ils.acq.purchase_order.lineitem.delete' : 'open-ils.acq.picklist.lineitem.delete'],
3498 params: [openils.User.authtoken, liId],
3499 oncomplete: function(r) {
3500 self.removeLineitem(liId);
3501 self._deleteLiList(list, ++idx);
3507 this.editOrderMarc = function(li) {
3509 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
3510 to true in about:config */
3512 if(openils.XUL.isXUL()) {
3513 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul','','chrome');
3515 win = window.open('/xul/server/cat/marcedit.xul','','chrome');
3519 record : {marc : li.marc(), "rtype": "bre"},
3521 label: 'Save Record', // XXX I18N
3522 func: function(xmlString) {
3524 fieldmapper.standardRequest(
3525 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
3527 params: [openils.User.authtoken, li],
3528 oncomplete: function(r) {
3529 openils.Util.readResponse(r);
3531 self.drawInfo(li.id())
3537 'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
3538 'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
3542 this._savePl = function(values) {
3544 (values.which == 'all'),
3545 function(list) { self._savePlFromLineitems(values, list); }
3549 this._savePlFromLineitems = function(values, selected) {
3550 openils.Util.show("acq-lit-generic-progress");
3552 if(values.new_name) {
3553 openils.acq.Picklist.create(
3554 {name: values.new_name},
3560 oilsBasePath + "/acq/picklist/view/" + id;
3565 } else if(values.existing_pl) {
3566 // update lineitems to use an existing picklist
3568 values.existing_pl, selected, 0,
3571 oilsBasePath + "/acq/picklist/view/" +
3578 this._updateLiState = function(values, state, state_filter) {
3579 progressDialog.show(true);
3581 (values.which == 'all'),
3583 self._updateLiStateFromLineitems(values, state, list);
3584 }, false /* id_list */, state_filter
3588 this._updateLiStateFromLineitems = function(values, state, selected) {
3589 if(!selected.length) {
3590 try { progressDialog.hide() } catch(E) {};
3591 alert(localeStrings.NO_LI_GENERAL);
3594 dojo.forEach(selected, function(li) {li.state(state);});
3595 self._updateLiList(null, selected, 0,
3596 // TODO consider inline updates for efficiency
3597 function() { location.href = location.href }
3601 this._updateLiList = function(pl, list, idx, oncomplete) {
3602 if(idx >= list.length) return oncomplete();
3604 if(pl != null) li.picklist(pl);
3605 litGenericProgress.update({maximum: list.length, progress: idx});
3606 new openils.acq.Lineitem({lineitem:li}).update(
3608 self._updateLiList(pl, list, ++idx, oncomplete);
3613 this._loadPOSelect = function() {
3614 if (!this.createPoProviderSelector) {
3615 var widget = new openils.widget.AutoFieldWidget({
3616 "fmField": "provider",
3618 "searchFilter": {"active": "t"},
3619 "parentNode": dojo.byId("acq-lit-po-provider"),
3621 "onChange": function() {
3623 self._updateCreatePoPrepayCheckbox(
3624 this.item.prepayment_required()
3630 widget.build(function(w) { self.createPoProviderSelector = w; });
3633 this.createPoCheckDupes = function() {
3634 var org = self.createPoAgencySelector.attr('value');
3635 var name = self.createPoNameInput.attr('value');
3636 openils.Util.hide('acq-dupe-po-name');
3639 acqLitCreatePoSubmit.attr('disabled', false);
3643 acqLitCreatePoSubmit.attr('disabled', true);
3644 var orgs = fieldmapper.aou.descendantNodeList(org, true);
3645 new openils.PermaCrud().search('acqpo',
3646 {name : name, ordering_agency : orgs},
3647 {async : true, oncomplete : function(r) {
3648 var po = openils.Util.readResponse(r);
3650 if (po && (po = po[0])) {
3652 var link = dojo.byId('acq-dupe-po-link');
3653 openils.Util.show('acq-dupe-po-name', 'table-row');
3654 var dupe_path = '/acq/po/view/' + po.id();
3658 if (window.IAMBROWSER) {
3659 // TODO: integration
3663 link.onclick = function() {
3665 var loc = xulG.url_prefix('XUL_BROWSER?url=') +
3666 window.encodeURIComponent(
3667 xulG.url_prefix('EG_WEB_BASE' + dupe_path)
3671 {tab_name: '', browser:false},
3674 show_nav_buttons : true,
3675 show_print_button : true,
3682 link.onclick = function() {
3683 window.open(oilsBasePath + dupe_path, '_blank').focus();
3688 acqLitCreatePoSubmit.attr('disabled', false);
3694 if (!this.createPoAgencySelector) {
3695 var widget = new openils.widget.AutoFieldWidget({
3696 "fmField": "ordering_agency",
3698 "parentNode": dojo.byId("acq-lit-po-agency"),
3699 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3701 widget.build(function(w) {
3702 self.createPoAgencySelector = w;
3703 dojo.connect(w, 'onChange', self.createPoCheckDupes);
3707 if (!this.createPoNameInput) {
3708 var widget = new openils.widget.AutoFieldWidget({
3711 "parentNode": dojo.byId("acq-lit-po-name"),
3712 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3714 widget.build(function(w) {
3715 self.createPoNameInput = w;
3716 dojo.connect(w, 'onChange', self.createPoCheckDupes);
3721 this.showRealCopyEditUI = function(li) {
3726 this._fetchLineitem(li.id(),
3728 li = self.liCache[li.id()] = fullLi;
3732 id : li.lineitem_details().map(
3733 function(item) { return item.eg_copy_id() }
3737 oncomplete : function(r) {
3739 var r_list = openils.Util.readResponse( r );
3740 for (var i = 0; i < r_list.length; i++) {
3741 var copy = r_list[i];
3742 var volId = copy.call_number();
3743 var volume = self.volCache[volId];
3745 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
3747 copy.call_number(volume);
3748 copyList.push(copy);
3751 xulG.volume_item_creator( { 'existing_copies' : copyList } );
3754 alert('error in oncomplete: ' + E);
3763 this.drawBibFinder = function(li) {
3766 var liWrapper = new openils.acq.Lineitem({lineitem:li});
3769 ['isbn', 'upc', 'issn', 'title', 'author'],
3771 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
3773 if(field == 'title' || field == 'author') {
3774 query += field +':' + val + ' ';
3776 query += 'identifier|' + field + ':' + val + ' ';
3782 if(openils.XUL.isXUL() && !window.IAMBROWSER) {
3784 oilsBasePath + '/acq/lineitem/findbib?query=' + encodeURIComponent(query),
3785 '', 'resizable,scrollbars=1,chrome');
3787 win = window.open( oilsBasePath + '/acq/lineitem/findbib?query=' + encodeURIComponent(query));
3791 win.window.recordFound = function(bibId) {
3794 var attrs = li.attributes();
3795 li.attributes(null);
3796 li.eg_bib_id(bibId);
3798 fieldmapper.standardRequest(
3799 ["open-ils.acq", "open-ils.acq.lineitem.update"],
3801 "params": [openils.User.authtoken, li],
3803 "oncomplete": function(r) {
3804 if(openils.Util.readResponse(r)) {
3805 location.href = location.href;