1 dojo.require('dojo.date.locale');
2 dojo.require('dojo.date.stamp');
3 dojo.require('dijit.form.Button');
4 dojo.require('dijit.form.TextBox');
5 dojo.require('dijit.form.FilteringSelect');
6 dojo.require('dijit.form.Textarea');
7 dojo.require('dijit.Tooltip');
8 dojo.require('dijit.ProgressBar');
9 dojo.require('dojox.timing.doLater');
10 dojo.require('openils.acq.Lineitem');
11 dojo.require('openils.acq.PO');
12 dojo.require('openils.acq.Picklist');
13 dojo.require('openils.widget.AutoFieldWidget');
14 dojo.require('dojo.data.ItemFileReadStore');
15 dojo.require('openils.widget.ProgressDialog');
16 dojo.require('openils.PermaCrud');
17 dojo.require("openils.widget.PCrudAutocompleteBox");
18 dojo.require('dijit.form.ComboBox');
19 dojo.require('openils.CGI');
21 if (!localeStrings) { /* we can do this because javascript doesn't have block scope */
22 dojo.requireLocalization('openils.acq', 'acq');
23 var localeStrings = dojo.i18n.getLocalization('openils.acq', 'acq');
25 const XUL_OPAC_WRAPPER = 'chrome://open_ils_staff_client/content/cat/opac.xul';
26 var li_exportable_attrs = ["issn", "isbn", "upc"];
28 var fundLabelFormat = [
29 '<span class="fund_${0}">${1} (${2})</span>', 'id', 'code', 'year'
31 var fundSearchFormat = ['${0} (${1})', 'code', 'year'];
32 var fundSearchFilter = {active : 't'};
33 var fundSort = {order_by : {"acqf":"year DESC, code"}};
35 function nodeByName(name, context) {
36 return dojo.query('[name='+name+']', context)[0];
39 // for caching linked users. e.g. lineitem_detail.receiver
42 var liDetailBatchFields = ['fund', 'owning_lib', 'location', 'collection_code', 'circ_modifier', 'cn_label'];
43 var liDetailFields = liDetailBatchFields.concat(['barcode', 'note']);
45 "stop": "color: #c00; font-weight: bold;",
46 "warning": "color: #c93;"
50 * We're not using 'approved' today, but there is API support for it.
51 * I believe it's been replaced by "order-ready".
52 * LIs go new => selector-ready => order-ready/approved => pending-order =>
53 * on-order => received. 'cancelled' can pop up anywhere.
56 var li_pre_po_states = ["new", "selector-ready", "order-ready", "approved"];
57 var li_post_po_states = ["pending-order", "on-order", "received", "cancelled"];
58 var li_active_states = li_pre_po_states.concat(li_post_po_states);
60 function AcqLiTable() {
67 this.haveFundClass = {}
68 this.fundBalanceState = {};
69 this.realDfaCache = {};
70 this.virtDfaCounts = {};
73 this.claimEligibleLidByLi = {};
74 this.claimEligibleLid = {};
75 this.toggleState = false;
76 this.tbody = dojo.byId('acq-lit-tbody');
79 this.authtoken = openils.User.authtoken;
80 this.pcrud = new openils.PermaCrud();
81 this.rowTemplate = this.tbody.removeChild(dojo.byId('acq-lit-row'));
82 this.copyTbody = dojo.byId('acq-lit-li-details-tbody');
83 this.copyRow = this.copyTbody.removeChild(dojo.byId('acq-lit-li-details-row'));
84 this.copyBatchRow = dojo.byId('acq-lit-li-details-batch-row');
85 this.copyBatchWidgets = {};
86 this.liNotesTbody = dojo.byId('acq-lit-notes-tbody');
87 this.liNotesRow = this.liNotesTbody.removeChild(dojo.byId('acq-lit-notes-row'));
88 this.realCopiesTbody = dojo.byId('acq-lit-real-copies-tbody');
89 this.realCopiesRow = this.realCopiesTbody.removeChild(dojo.byId('acq-lit-real-copies-row'));
90 this._copy_fields_for_acqdf = ['owning_lib', 'location', 'fund', 'circ_modifier', 'collection_code'];
91 this.skipInitialEligibilityCheck = false;
92 this.claimDialog = new ClaimDialogManager(
93 liClaimDialog, finalClaimDialog, this.claimEligibleLidByLi,
94 function(li) { /* callback that fires when claims are made */
95 self.fetchClaimInfo(li.id(), /* force update */ true);
98 this.vlAgent = new VLAgent();
99 this.batchProgress = {};
101 if (dojo.byId('acq-lit-apply-idents')) {
102 dojo.byId('acq-lit-apply-idents').onclick = function() {
103 self.applyOrderIdentValues();
107 this.focusLineitem = new openils.CGI().param('focus_li');
109 // capture the inline copy display wrapper and row template
110 this.inlineCopyContainer =
111 this.tbody.removeChild(dojo.byId('acq-inline-copies-row'));
113 '[name=acq-li-inline-copies-tbody]', this.inlineCopyContainer)[0];
114 this.inlineCopyTemplate = tb.removeChild(
115 dojo.query('[name=acq-li-inline-copies-template]', tb)[0]);
116 this.inlineNoCopies = tb.removeChild(
117 dojo.query('[name=acq-li-inline-copies-none]', tb)[0]);
119 // list of LI IDs that should be refreshed at next display time
120 this.inlineCopiesNeedingRefresh = [];
122 dojo.byId("acq-lit-li-actions-selector").onchange = function() {
123 self.applySelectedLiAction(this.options[this.selectedIndex].value);
124 this.selectedIndex = 0;
127 acqLitCreatePoCancel.onClick = function() {
128 acqLitPoCreateDialog.hide();
130 acqLitCreatePoSubmit.onClick = function() {
131 if (!self.createPoProviderSelector.attr("value") ||
132 !self.createPoAgencySelector.attr("value")) {
133 alert(localeStrings.CREATE_PO_INVALID);
135 } else if (self._confirmPoPrepaySituation()) {
136 acqLitPoCreateDialog.hide();
137 self._createPO(acqLitPoCreateDialog.getValues());
143 acqLitSavePlButton.onClick = function() {
144 acqLitSavePlDialog.hide();
145 self._savePl(acqLitSavePlDialog.getValues());
148 acqLitCancelLiStateButton.onClick = function() {
149 acqLitChangeLiStateDialog.hide();
151 acqLitSaveLiStateButton.onClick = function() {
152 acqLitChangeLiStateDialog.hide();
153 var state = acqLitChangeLiStateDialog.attr('state');
154 var state_filter = ['new'];
155 if (state == 'order-ready')
156 state_filter.push('selector-ready');
158 acqLitChangeLiStateDialog.getValues(), state, state_filter);
162 dojo.byId('acq-lit-select-toggle').onclick = function(){self.toggleSelect()};
163 dojo.byId('acq-inline-copies-toggle').onclick = function(){self.toggleInlineCopies()};
164 dojo.byId('acq-lit-info-back-button').onclick = function(){self.show('list')};
165 dojo.byId('acq-lit-copies-back-button').onclick = function(){self.show('list')};
166 dojo.byId('acq-lit-notes-back-button').onclick = function(){self.show('list')};
167 dojo.byId('acq-lit-real-copies-back-button').onclick = function(){self.show('list')};
169 this.setFundSearchFilter = function(callback) {
170 new openils.User().getPermOrgList(
171 ['CREATE_PURCHASE_ORDER', 'MANAGE_FUND'],
173 fundSearchFilter.org = orgs;
174 if (callback) callback();
176 true, true // descendants, id_list
180 this.afwCopyFieldArgs = function(field, perms) {
184 "labelFormat": (field == 'fund') ? fundLabelFormat : null,
185 "searchFormat": (field == 'fund') ? fundSearchFormat : null,
186 "searchFilter": (field == 'fund') ? fundSearchFilter : null,
187 "searchOptions": (field == 'fund') ? fundSort : null,
188 "orgLimitPerms": (field == 'location') ? ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'] : [perms],
191 "labelType": (field == "fund") ? "html" : null
193 "noCache": (field == "fund"),
198 /* This is the "new" batch updater that sits atop all lineitems. It does
199 * use this.afwCopyFieldArgs() to borrow a little common code from the
200 * "old" batch updater atop the copy details view. */
201 this.initBatchUpdater = function(disabled_fields) {
202 openils.Util.show("acq-batch-update", "table");
204 if (!dojo.isArray(disabled_fields)) disabled_fields = [];
206 /* Note that this will directly contain dijits, not the AutoWidget
208 if (!this.batchUpdateWidgets) {
209 this.batchUpdateWidgets = {};
212 if (this.batchUpdateWidgets.item_count) this.batchUpdateWidgets.item_count.destroy();
213 this.batchUpdateWidgets.item_count = new dijit.form.TextBox(
215 "style": {"width": "3em"},
217 dojo.indexOf(disabled_fields, "item_count") != -1
223 if (!this.batchUpdateWidgets.distribution_formula) {
224 (new openils.widget.AutoFieldWidget({
226 "selfReference": true,
227 "dijitArgs": { "required": false },
229 "parentNode": "acq-bu-distribution_formula"
232 dojo.style(w.domNode, {"width": "12em"});
233 self.batchUpdateWidgets.distribution_formula = w;
238 /* dijitArgs to AutoFieldWidget won't work for 'disabled' */
239 self.batchUpdateWidgets.distribution_formula.attr(
241 dojo.indexOf(disabled_fields, "distribution_formula") != -1
244 function buildOneBatchWidget(field, args) {
245 if (!self.batchUpdateWidgets[field]) {
246 (new openils.widget.AutoFieldWidget(args)).build(
248 if (field == "fund") {
250 w, "onChange", function(val) {
251 self._updateFundSelectorStyle(aw, val);
255 self._ensureCSSFundClasses(w.store);
258 dojo.style(w.domNode, {"width": "10em"});
259 self.batchUpdateWidgets[field] = w;
264 if (self.batchUpdateWidgets[field]) {
265 self.batchUpdateWidgets[field].attr(
267 dojo.indexOf(disabled_fields, field) != -1
273 ["owning_lib","location","collection_code","circ_modifier","fund"],
275 var args = self.afwCopyFieldArgs(field,"CREATE_PURCHASE_ORDER");
276 args.parentNode = dojo.byId("acq-bu-" + field);
278 if (field == 'fund') {
279 // The list of funds can be huge. Before fetching
280 // funds for PO modification, see where the user has
281 // perms and limit the retreived funds accordingly.
282 // Note: This is the first instance of fund list
283 // retrieval. All future fund list retrievals will
284 // benefit directly from having applied the fund
285 // search filter org units here.
286 self.setFundSearchFilter(function() {
287 buildOneBatchWidget(field, args);
292 buildOneBatchWidget(field, args);
296 acqBatchUpdateApply.onClick = function() {
297 var li_id_list = self.getSelected(false, null, true /* id list */);
298 if (!li_id_list.length) {
299 alert(localeStrings.NO_LI_TO_UPDATE);
303 progressDialog.show(true);
304 progressDialog.attr("title", localeStrings.LI_BATCH_UPDATE);
305 progressDialog.update({"maximum": li_id_list.length,"progress": 0});
309 var params = [ self.authtoken, {"lineitems": li_id_list},
310 self.batchUpdateChanges(), self.batchUpdateFormula() ];
311 console.log("batch update params: " + dojo.toJson(params));
313 fieldmapper.standardRequest(
314 ["open-ils.acq", "open-ils.acq.lineitem.batch_update"], {
317 "onresponse": function(r) {
318 if ((r = openils.Util.readResponse(r))) { // assignment
319 progressDialog.update({"progress": ++count});
321 progressDialog.hide();
322 progressDialog.attr("title", "");
325 "oncomplete": function() {
326 /* XXX Is the last call to onresponse guaranteed to
327 * finish before oncomplete is fired? */
328 if (count != li_id_list.length) {
329 console.error("lineitem batch update operation failed");
330 progressDialog.hide();
331 progressDialog.attr("title", "");
333 location.href = location.href;
341 this.batchUpdateChanges = function() {
345 openils.Util.objectProperties(this.batchUpdateWidgets),
347 if (k == "distribution_formula") return; /* handled elsewhere */
348 if (self.batchUpdateWidgets[k].attr("disabled")) return;
350 /* It's important that a value of "" should mean that a field
351 * doesn't get used in the arguments to the batch updater API,
352 * but 0 should mean an actual 0. */
353 var value = self.batchUpdateWidgets[k].attr("value");
362 this.batchUpdateFormula = function() {
363 if (this.batchUpdateWidgets.distribution_formula.attr("disabled")) {
367 this.batchUpdateWidgets.distribution_formula.attr("value") ||
373 this.reset = function(keep_selectors) {
374 while(self.tbody.childNodes[0])
375 self.tbody.removeChild(self.tbody.childNodes[0]);
384 this.setNext = function(handler) {
385 var link = dojo.byId('acq-lit-next');
387 dojo.style(link, 'visibility', 'visible');
388 link.onclick = handler;
390 dojo.style(link, 'visibility', 'hidden');
394 this.setPrev = function(handler) {
395 var link = dojo.byId('acq-lit-prev');
397 dojo.style(link, 'visibility', 'visible');
398 link.onclick = handler;
400 dojo.style(link, 'visibility', 'hidden');
404 this.enableActionsDropdownOptions = function(mask) {
405 /* 'mask' is probably a misnomer the way I'm using it, but it needs to
406 * be one of pl,po,ao,gs,vp, or fs. */
407 dojo.query("option", "acq-lit-li-actions-selector").forEach(
409 var opt_mask = dojo.attr(option, "mask");
411 /* For each <option> element, an empty or non-existent mask
412 * attribute, a mask attribute of "*", or a mask attribute that
413 * matches this method's argument should result in that
414 * option's being enabled. */
416 option, "disabled", !(
419 opt_mask.search(mask) != -1
427 * Ensures this.focusLineitem is in view and causes a brief
428 * border around the lineitem to come to life then fade.
430 this.focusLi = function() {
431 if (!this.focusLineitem) return;
433 // set during addLineitem()
434 var node = dojo.byId('li-title-ref-' + this.focusLineitem);
436 // LI may not yet be rendered
439 // prevent numerous re-focuses
440 this.focusLineitem = null;
442 // causes the full row to be visible
443 dijit.scrollIntoView(node);
446 dojo.query('[attr=title]', node)[0].focus();
448 dojo.require('dojox.fx');
452 dojox.fx.highlight({color : '#BB4433', node : node, duration : 2000}).play();
457 this.show = function(div) {
458 openils.Util.hide('acq-lit-table-div');
459 openils.Util.hide('acq-lit-info-div');
460 openils.Util.hide('acq-lit-li-details');
461 openils.Util.hide('acq-lit-notes-div');
462 openils.Util.hide('acq-lit-real-copies-div');
463 openils.Util.hide('acq-lit-asset-creator');
466 openils.Util.show('acq-lit-table-div');
468 this.refreshInlineCopies();
471 openils.Util.show('acq-lit-info-div');
474 openils.Util.show('acq-lit-li-details');
477 openils.Util.show('acq-lit-real-copies-div');
480 openils.Util.show('acq-lit-notes-div');
482 case 'asset-creator':
483 openils.Util.show('acq-lit-asset-creator');
487 openils.Util.show(div);
491 this.hide = function() {
495 this.toggleSelect = function() {
497 dojo.forEach(self.selectors, function(i){i.checked = false});
499 dojo.forEach(self.selectors, function(i){i.checked = true});
500 self.toggleState = !self.toggleState;
504 this.getAll = function(callback, id_only, state) {
505 /* For some uses of the li table, we may not really know about "all"
506 * the lineitems that the user thinks we know about. If we're a paged
507 * picklist, for example, we only know about the lineitems we've
508 * displayed, but not necessarily all the lineitems on the picklist.
509 * So we reach out to pcrud to inform us.
510 * state: string/array. only lineitems in one of these states are
511 * included in the final result set. Not currently supported for
515 var oncomplete = function(r) {
516 var id_list = openils.Util.readResponse(r);
520 self.fetchLineitemsById(id_list, callback);
524 var search = {"picklist": this.isPL};
525 if (state) search.state = state;
528 "id_list": true, /* sic, even if id_only */
530 "oncomplete": oncomplete
534 } else if (this.isPO) {
535 var search = {"purchase_order": this.isPO};
536 if (state) search.state = state;
541 "oncomplete": oncomplete
545 } else if (this.isUni && this.pager) {
546 this.pager.getAllLineitemIDs(oncomplete);
550 /* If execution reaches this point, we don't need or can't perform
551 * any special tricks to find out the "real" list of "all" lineitems
552 * in this context, so we fall back to the old method.
554 callback(this.getSelected(true, null, id_only, state));
557 /** @param all If true, assume all are selected */
558 this.getSelected = function(
560 callback /* If you want a "good" idea of "all" lineitems, you must
561 provide a callback that accepts an array parameter, rather than
562 relying on the return value of this method itself. */,
566 console.log("getSelected states = " + state);
568 return this.getAll(callback, id_only, state);
570 var indices = {}; /* use to uniqify. needed in paging situations. */
571 dojo.forEach(this.selectors,
574 indices[i.parentNode.parentNode.getAttribute('li')] = true;
578 var result = openils.Util.objectProperties(indices);
580 // caller provided a lineitem state filter. remove IDs for lineitems
581 // not in the selected state.
584 if (!dojo.isArray(state)) state = [state];
585 dojo.forEach(result, function(liId) {
586 console.log('filter LI state ' + self.liCache[liId].state());
587 if (state.indexOf(self.liCache[liId].state()) >= 0)
594 result = result.map(function(liId) { return self.liCache[liId]; });
602 this.setRowAttr = function(td, liWrapper, field, type) {
603 var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
604 td.appendChild(document.createTextNode(val));
607 this.setClaimPolicyControl = function(li, row) {
608 if (!self._claimPolicyPickerLoading) {
609 self._claimPolicyPickerLoading = true;
611 new openils.widget.AutoFieldWidget({
612 "parentNode": "acq-lit-li-claim-policy",
614 "selfReference": true,
615 "dijitArgs": {"required": true}
617 function(w) { self.claimPolicyPicker = w; }
621 /* dojox.timing.doLater() is the best thing ever. Resource not yet
622 * ready? Just repeat my whole method when it is. */
623 if (dojox.timing.doLater(self.claimPolicyPicker)) {
627 row = self._findLiRow(li);
629 if (li.claim_policy()) {
630 /* This Dojo data dance is necessary to get a whole fieldmapper
631 * object based on a claim policy ID, since we alreay have the
632 * widget thing loaded with all that data, and can thereby
633 * avoid another request to the server. */
634 self.claimPolicyPicker.store.fetchItemByIdentity({
635 "identity": li.claim_policy(),
636 "onItem": function(a) {
637 var policy = (new acqclp()).fromStoreItem(a);
638 var span = nodeByName("claim_policy", row);
639 var inner = nodeByName("claim_policy_name", row);
641 openils.Util.show(span, "inline");
642 inner.innerHTML = policy.name();
644 "onError": function(e) {
649 openils.Util.hide(nodeByName("claim_policy", row));
650 nodeByName("claim_policy_name", row).innerHTML = "";
655 this.fetchClaimInfo = function(liId, force, callback, row) {
657 liId, function(full) {
658 self.liCache[full.id()] = full;
659 self.checkClaimEligibility(full, callback, row);
664 // fetch an updated copy of the lineitem
665 // and add it back to the lineitem table
666 this.refreshLineitem = function(li, focus) {
668 this._fetchLineitem(li.id(),
671 self.focusLineitem = li.id();
673 self.focusLineitem = null;
675 var row = dojo.query('[li='+li.id()+']', self.tbody)[0];
676 var nextSibling = row.nextSibling;
677 self.tbody.removeChild(row);
678 self.addLineitem(newLi, false, nextSibling);
684 * Inserts a single lineitem into the growing table of lineitems
685 * @param {Object} li The lineitem object to insert
687 this.addLineitem = function(li, skip_final_placement, nextSibling) {
688 this.liCache[li.id()] = li;
690 // insert the row right away so that final order isn't
691 // dependent on how long subsequent async request take
692 // for a given line item
693 var row = self.rowTemplate.cloneNode(true);
694 if (!skip_final_placement) {
696 // either no nextSibling was provided or it was null
697 // meaning the row was already at the end of the table
698 self.tbody.appendChild(row);
700 self.tbody.insertBefore(row, nextSibling);
704 self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
706 // sort the lineitem notes on edit_time
707 if(!li.lineitem_notes()) li.lineitem_notes([]);
709 var liWrapper = new openils.acq.Lineitem({lineitem:li});
710 row.setAttribute('li', li.id());
711 var tds = dojo.query('[attr]', row);
712 dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
713 dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
715 // so we can scroll to it later
716 dojo.query('[name=bib-info-cell]', row)[0].id = 'li-title-ref-' + li.id();
719 liWrapper.findAttr("isbn", "lineitem_marc_attr_definition") ||
720 liWrapper.findAttr("upc", "lineitem_marc_attr_definition");
722 // XXX media prefix for added content
724 nodeByName("jacket", row).setAttribute(
725 "src", "/opac/extras/ac/jacket/small/" + identifier
729 nodeByName("liid", row).innerHTML += li.id();
731 var exist = nodeByName('li_existing_count', row);
732 fieldmapper.standardRequest(
733 ['open-ils.acq', 'open-ils.acq.lineitem.existing_copies.count'],
735 params: [this.authtoken, li.id()],
736 oncomplete : function(r) {
737 var count = openils.Util.readResponse(r);
738 exist.innerHTML = count;
739 if (Number(count) > 0) {
740 openils.Util.addCSSClass(
741 exist, 'acq-existing-count-warn');
745 label : dojo.string.substitute(
746 localeStrings.LI_EXISTING_COPIES, [count])
753 openils.Util.show(nodeByName('catalog', row), 'inline');
754 nodeByName("catalog_link", row).onclick = this.generateMakeRecTab(li.eg_bib_id());
756 openils.Util.show(nodeByName('link_to_catalog', row), 'inline');
757 nodeByName("link_to_catalog_link", row).onclick = function() { self.drawBibFinder(li) };
760 if (li.queued_record()) {
761 this.pcrud.retrieve('vqbr', li.queued_record(),
763 oncomplete : function(r) {
764 var qrec = openils.Util.readResponse(r);
765 openils.Util.show(nodeByName('queue', row), 'inline');
766 var link = nodeByName("queue_link", row);
767 link.onclick = function() {
768 var url = oilsBasePath + '/vandelay/vandelay?qtype=bib&qid=' + qrec.queue()
769 // open a new tab to the vandelay queue for this record
770 if (window.IAMBROWSER) {
773 openils.XUL.newTabEasy(url);
781 nodeByName("worksheet_link", row).href =
782 oilsBasePath + "/acq/lineitem/worksheet/" + li.id() +
783 '?source=' + encodeURIComponent(location.pathname + location.search)
785 nodeByName("show_requests_link", row).href =
786 oilsBasePath + "/acq/picklist/user_request?lineitem=" + li.id() +
787 '?source=' + encodeURIComponent(location.pathname + location.search)
789 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
790 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
791 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
792 dojo.query('[name=expand_inline_copies]', row)[0].onclick =
793 function() {self.drawInlineCopies(li.id())};
796 if (sum = li.order_summary()) { // assignment
797 // Only show the paid label if at least one copy is invoiced.
798 // In other words, a lineitem whose every copy is canceled
800 if (sum.invoice_count() > 0) {
801 if (sum.item_count() == (
802 sum.invoice_count() + sum.cancel_count())) {
803 // Lineitem is fully paid. Display the paid-off label
804 openils.Util.show(nodeByName('paid', row), 'inline');
809 this.drawOrderIdentSelector(li, row);
811 if (!this.skipInitialEligibilityCheck)
815 function(full) { self.setClaimPolicyControl(full, row) },
819 this.updateLiNotesCount(li, row);
821 // show which PO this lineitem is a member of
822 if(li.purchase_order() && !this.isPO) {
824 this.poCache[li.purchase_order()] =
825 this.poCache[li.purchase_order()] ||
826 fieldmapper.standardRequest(
827 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
829 this.authtoken, li.purchase_order(), {
830 "flesh_price_summary": true,
831 "flesh_provider" : true,
832 "flesh_lineitem_count": true
835 if(po && !this.isMeta) {
836 openils.Util.show(nodeByName('po', row), 'inline');
837 var link = nodeByName('po_link', row);
838 link.setAttribute('href', oilsBasePath +
839 '/acq/po/view/' + li.purchase_order() +
840 '?focus_li=' + li.id() +
841 '&source=' + encodeURIComponent(location.pathname + location.search)
843 link.innerHTML += po.name();
845 openils.Util.show(nodeByName('pro', row), 'inline');
846 link = nodeByName('pro_link', row);
847 link.setAttribute('href', oilsBasePath + '/conify/global/acq/provider/' + po.provider().id())
848 link.innerHTML += po.provider().code();
852 // show which picklist this lineitem is a member of
853 if(li.picklist() && (this.isPO || this.isMeta || this.isUni)) {
855 this.plCache[li.picklist()] =
856 this.plCache[li.picklist()] ||
857 fieldmapper.standardRequest(
858 ['open-ils.acq', 'open-ils.acq.picklist.retrieve.authoritative'],
859 {params: [this.authtoken, li.picklist()]});
861 if (pl.name() == "") {
862 openils.Util.show(nodeByName("bib_origin", row), "inline");
866 openils.Util.show(nodeByName('pl', row), 'inline');
867 var link = nodeByName('pl_link', row);
868 link.setAttribute('href', oilsBasePath +
869 '/acq/picklist/view/' + li.picklist() +
870 '?focus_li=' + li.id() +
871 '&source=' + encodeURIComponent(location.pathname + location.search)
873 link.innerHTML += pl.name();
878 var countNode = nodeByName('count', row);
879 var count = li.item_count() || 0;
880 if (typeof(this._copy_count_cb) == "function") {
881 this._copy_count_cb(li.id(), count);
883 countNode.innerHTML = count;
884 countNode.id = 'acq-lit-copy-count-label-' + li.id();
887 var priceInput = dojo.query('[name=price]', row)[0];
888 priceInput.value = li.estimated_unit_price() || '';
889 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
891 // show either "mark received" or "unreceive" as appropriate
892 this.updateLiState(li, row);
894 if (skip_final_placement) {
898 // the last LI may be rendered after the call to show('list'),
899 // so make sure it's focused if necessary.
900 if (this.focusLineitem == li.id())
904 this._liCountClaims = function(li) {
906 for (var i = 0; i < li.lineitem_details().length; i++)
907 total += li.lineitem_details()[i].claims().length;
911 this._findLiRow = function(li) {
912 return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
915 this.reconsiderClaimControl = function(li, row) {
916 if (!row) row = this._findLiRow(li);
917 var option = nodeByName("action_manage_claims", row);
918 var eligible = this.claimEligibleLidByLi[li.id()].length;
919 var count = this._liCountClaims(li);
921 option.disabled = !(count || eligible);
923 dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
924 option.onclick = function() { self.claimDialog.show(li); };
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 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
1227 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
1229 // always allow access to LI history
1230 nodeByName('action_view_history', row).onclick =
1231 function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
1233 /* handle row coloring for based on LI state */
1234 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1235 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
1237 // Expose invoice actions for any lineitem that is linked to a PO
1238 if (li.purchase_order()) {
1239 openils.Util.show(nodeByName("invoices_span", row), "inline");
1240 var link = nodeByName("invoices_link", row);
1241 link.onclick = function() {
1242 var url = oilsBasePath + "/acq/search/unified?so=" +
1243 base64Encode({"jub":[{"id": li.id()}]}) + "&rt=invoice"
1244 if (window.IAMBROWSER) {
1245 xulG.relay_url(url);
1247 openils.XUL.newTabEasy(url);
1255 * If we haven't fleshed the lineitem_details, default to allowing access to the
1256 * holdings maintenence actions. The alternative is to flesh LIDs on every lineitem,
1257 * but that will add to page render time. Let's see if this will suffice...
1259 var lids = li.lineitem_details();
1261 (lids && !lids.filter(function(lid) { return lid.eg_copy_id() })[0] )) {
1263 actUpdateBarcodes.disabled = false;
1264 actUpdateBarcodes.onclick = function() {
1265 self.showRealCopyEditUI(li);
1266 nodeByName("action_none", row).selected = true;
1268 actHoldingsMaint.disabled = false;
1269 actHoldingsMaint.onclick =
1270 self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
1273 var state_cell = nodeByName("li_state_" + li.state(), row);
1275 // re-hide any state label nodes which may have been un-hidden
1276 // through previous actions.
1277 dojo.query('[state-label]', row).forEach(function(node) {
1278 openils.Util.hide(node)
1281 if (li.state() == 'cancelled') {
1282 if(typeof li.cancel_reason() == "object") {
1284 // clear the stock "Canceled" label, since we have more
1285 // information to replace it with.
1286 state_cell.innerHTML = '';
1288 var holds_state = dojo.create(
1290 "style": "border-bottom: 1px dashed #000;",
1291 "innerHTML": li.cancel_reason().label()
1292 }, state_cell, "only"
1296 "label": "<em>" + li.cancel_reason().label() +
1297 "</em><br />" + li.cancel_reason().description(),
1298 "connectId": [holds_state]
1299 }, dojo.create("span", null, state_cell, "last")
1302 if (li.cancel_reason().keep_debits() == 't') {
1303 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1304 openils.Util.addCSSClass(row, "oils-acq-li-state-delayed");
1307 console.log('li cancel_reason is un-fleshed. Please fix');
1311 openils.Util.show(state_cell);
1315 this._setAlertStore = function() {
1316 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
1318 "data": acqliat.toStoreData(
1321 "owning_lib": aou.orgNodeTrail(
1322 aou.findOrgUnit(openils.User.user.ws_ou())
1323 ).map(function(o) { return o.id(); })
1329 acqLitAlertAlertText.setValue(); /* make the store "live" */
1330 acqLitAlertAlertText._store_ready = true;
1334 * Draws and shows the lineitem notes pane
1336 this.drawLiNotes = function(li) {
1338 this.focusLineitem = li.id();
1340 if (!acqLitAlertAlertText._store_ready)
1341 this._setAlertStore();
1344 li.lineitem_notes().sort(
1346 if(a.edit_time() < b.edit_time()) return 1;
1352 while(this.liNotesTbody.childNodes[0])
1353 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
1356 acqLitCreateNoteSubmit.onClick = function() {
1357 var value = acqLitCreateNoteText.attr('value');
1359 var note = new fieldmapper.acqlin();
1362 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
1365 note.lineitem(li.id());
1367 self.updateLiNotes(li, note);
1368 acqLitCreateNoteVendorPublic.attr("checked", false);
1369 acqLitCreateNoteText.attr("value", "");
1372 acqLitCreateAlertSubmit.onClick = function() {
1373 if (!acqLitAlertAlertText.item) {
1374 alert(localeStrings.ALERT_UNSELECTED);
1378 var alert_text = new fieldmapper.acqliat().fromStoreItem(
1379 acqLitAlertAlertText.item
1381 var value = acqLitAlertNoteValue.attr("value") || "";
1383 var note = new fieldmapper.acqlin();
1385 note.lineitem(li.id());
1387 note.alert_text(alert_text);
1389 self.updateLiNotes(li, note);
1392 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
1396 * Draws a single lineitem note in the notes pane
1398 this.addLiNote = function(li, note) {
1399 if(note.isdeleted()) return;
1401 var row = self.liNotesRow.cloneNode(true);
1402 nodeByName("value", row).innerHTML = note.value();
1403 var alert_node = nodeByName("alert_code", row);
1404 if (note.alert_text()) {
1405 alert_node.innerHTML = dojo.string.substitute(
1407 aou.findOrgUnit(note.alert_text().owning_lib()).shortname(),
1408 note.alert_text().code()
1411 if (note.alert_text().description()) {
1414 "connectId": [alert_node],
1415 "label": note.alert_text().description()
1416 }, dojo.create("span", null, alert_node, "after")
1421 if (openils.Util.isTrue(note.vendor_public()))
1422 nodeByName("vendor_public", row).innerHTML =
1423 localeStrings.VENDOR_PUBLIC;
1425 nodeByName("delete", row).onclick = function() {
1426 note.isdeleted(true);
1427 self.liNotesTbody.removeChild(row);
1428 self.updateLiNotes(li);
1431 if(note.edit_time()) {
1432 nodeByName("edit_time", row).innerHTML =
1433 dojo.date.locale.format(
1434 dojo.date.stamp.fromISOString(note.edit_time()),
1435 {formatLength:'short'});
1438 self.liNotesTbody.appendChild(row);
1442 * Updates any new/changed/deleted notes on the server
1444 this.updateLiNotes = function(li, newNote) {
1450 notes = li.lineitem_notes().filter(
1452 if(note.ischanged() || note.isnew() || note.isdeleted())
1458 if(notes.length == 0) return;
1459 progressDialog.show();
1461 fieldmapper.standardRequest(
1462 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
1464 params : [this.authtoken, notes],
1465 onresponse : function(r) {
1466 var resp = openils.Util.readResponse(r);
1471 // remove the old changed notes
1473 dojo.forEach(li.lineitem_notes(),
1475 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
1479 li.lineitem_notes(list);
1482 progressDialog.hide();
1483 self.updateLiNotesCount(li);
1484 self.drawLiNotes(li);
1488 progressDialog.update(resp);
1489 var newnote = resp.note;
1491 if(!newnote.isdeleted()) {
1492 newnote.isnew(false);
1493 newnote.ischanged(false);
1494 li.lineitem_notes().push(newnote);
1501 this.updateLiPrice = function(input, li) {
1503 var price = input.value;
1504 if(Number(price) == Number(li.estimated_unit_price())) return;
1506 fieldmapper.standardRequest(
1507 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
1508 { async : false, // redundant w/ timeout
1510 params : [this.authtoken, li.id(), price],
1511 oncomplete : function(r) {
1512 openils.Util.readResponse(r);
1513 li.estimated_unit_price(price); // update local copy
1516 * If this is a PO and every visible lineitem has a price,
1517 * check again to see if this PO can be activated. Note that
1518 * every visible lineitem having a price does not guarantee it can
1519 * be activated, which is why we still make the call. Having a price
1520 * set for every visiable lineitem is just the lowest barrier to entry.
1523 var priceNodes = dojo.query('[name=price]', dojo.byId('acq-lit-tbody'));
1525 dojo.forEach(priceNodes, function(node) { if (node.value == '') allSet = false});
1526 if (allSet) checkCouldActivatePo();
1527 refreshPOSummaryAmounts();
1534 this.removeLineitem = function(liId) {
1535 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
1536 delete this.liCache[liId];
1537 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
1540 this.drawInfo = function(liId) {
1541 this.focusLineitem = liId;
1542 if (!this._isRelatedViewer) {
1543 var d = dojo.byId("acq-lit-info-related");
1544 if (!this.relCache[liId]) {
1545 fieldmapper.standardRequest(
1548 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
1551 "params": [openils.User.authtoken, liId],
1552 "onresponse": function(r) {
1553 self.relCache[liId] = openils.Util.readResponse(r);
1554 nodeByName("related_number", d).innerHTML =
1555 self.relCache[liId];
1557 self.relCache[liId] >1 ? "show" : "hide"
1563 nodeByName("related_number", d).innerHTML = this.relCache[liId];
1564 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
1569 openils.acq.Lineitem.fetchAttrDefs(
1571 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
1576 this.toggleInlineCopies = function() {
1577 // if any inline copies are not displayed,
1578 // display them all otherwise, hide them all.
1580 var displayAll = false;
1582 for (var liId in this.liCache) {
1583 if (!this.inlineCopiesVisible(liId)) {
1589 for (var liId in this.liCache) {
1590 var row = dojo.byId('acq-inline-copies-row-' + liId);
1592 if (!row || row._hidden) {
1593 this.drawInlineCopies(liId);
1595 } else { // hide all
1597 // drawInlineCopies() on a visible row will hide it.
1598 this.drawInlineCopies(liId);
1605 this.inlineCopiesVisible = function(liId) {
1606 var row = dojo.byId('acq-inline-copies-row-' + liId);
1607 return (row && !row._hidden);
1610 this.refreshInlineCopies = function(all, reFetch) {
1612 var liIds = this.inlineCopiesNeedingRefresh;
1613 if (all) liIds = openils.Util.objectProperties(liCache);
1614 liIds.forEach(function(liId) {
1615 if (self.inlineCopiesVisible(liId)) {
1616 self.drawInlineCopies(liId, reFetch); // hide
1617 self.drawInlineCopies(liId, reFetch); // re-draw
1622 // draw inline copy table. if the table is
1623 // already visible, hide the table as-is
1624 // reFetch forces a retrieval of the lineitem and
1625 // copies from the server. otherwise the locally
1626 // cached version of each is used.
1627 this.drawInlineCopies = function(liId, reFetch) {
1630 // find or create the row where the inline copies table will live
1631 var containerRow = dojo.byId('acq-inline-copies-row-' + liId);
1632 var liRow = dojo.query('[li=' + liId + ']')[0];
1634 if (!containerRow) {
1636 // build the inline copies container row and add it to
1637 // the DOM directly after the primary lineitem row
1639 containerRow = self.inlineCopyContainer.cloneNode(true);
1640 containerRow.id = 'acq-inline-copies-row-' + liId;
1642 if (liRow.nextSibling) {
1643 self.tbody.insertBefore(containerRow, liRow.nextSibling);
1645 self.tbody.appendChild(containerRow);
1650 // toggle the visible state
1651 containerRow._hidden = !containerRow._hidden;
1652 openils.Util.toggle(containerRow, 'table-row');
1654 if (containerRow._hidden) return; // hide only
1657 var handler = function(li) {
1659 var tbody = dojo.query(
1660 '[name=acq-li-inline-copies-tbody]',
1663 // reset the table before adding copy rows
1664 while (tbody.childNodes[0])
1665 tbody.removeChild(tbody.childNodes[0]);
1667 if(li.lineitem_details().length == 0) {
1669 self.inlineNoCopies.cloneNode(true));
1670 return; // no copies to show
1673 // add a row to the inline copy table for each copy
1674 dojo.forEach(li.lineitem_details(),
1676 var row = self.inlineCopyTemplate.cloneNode(true);
1677 tbody.appendChild(row);
1678 self.addInlineCopy(li, copy, row);
1683 this._fetchLineitem(liId, handler, reFetch);
1686 /** Draw read-only copy widgets for inline copies */
1687 this.addInlineCopy = function(li, copy, row) {
1690 dojo.forEach(liDetailFields,
1693 var widget = new openils.widget.AutoFieldWidget({
1696 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1697 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1698 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1700 parentNode : dojo.query('[name=' + field + ']', row)[0],
1709 /* For a given list of lineitem ids, build a list of full lineitems
1710 * re-using the fetching logic that is otherwise typical to use in this
1713 * If we've already got a lineitem in the cache, just use that.
1715 * Once we've built a list of lineitems, call callback(thatlist).
1717 this.fetchLineitemsById = function(id_list, callback) {
1718 var total = id_list.length;
1719 var result_list = [];
1721 var inner = function(li) {
1722 result_list.push(li)
1724 callback(result_list);
1727 id_list.forEach(function(id) { self._fetchLineitem(id, inner); });
1730 this._fetchLineitem = function(liId, handler, force) {
1732 var li = this.liCache[liId];
1733 if(li && li.marc() && li.lineitem_details() && !force)
1736 fieldmapper.standardRequest(
1737 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
1740 params: [self.authtoken, liId, {
1742 flesh_cancel_reason: true,
1743 flesh_li_details: true,
1745 flesh_fund_debit: true }],
1747 oncomplete: function(r) {
1748 var li = openils.Util.readResponse(r);
1749 self.liCache[liId] = li;
1756 this._drawInfo = function(li) {
1758 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
1760 if(li.eg_bib_id()) {
1761 openils.Util.hide('acq-lit-marc-order-record-label');
1762 openils.Util.hide(acqLitEditOrderMarc.domNode);
1763 openils.Util.show('acq-lit-marc-real-record-label');
1765 openils.Util.show('acq-lit-marc-order-record-label');
1766 openils.Util.show(acqLitEditOrderMarc.domNode);
1767 openils.Util.hide('acq-lit-marc-real-record-label');
1770 this.drawMarcHTML(li);
1771 this.infoTbody = dojo.byId('acq-lit-info-tbody');
1774 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
1775 while(this.infoTbody.childNodes[0])
1776 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
1778 for(var i = 0; i < li.attributes().length; i++) {
1779 var attr = li.attributes()[i];
1780 var row = this.infoRow.cloneNode(true);
1782 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
1783 var name = openils.acq.Lineitem.attrDefs[type].filter(
1785 return (a.code() == attr.attr_name());
1787 ).pop().description();
1789 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
1790 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
1791 this.infoTbody.appendChild(row);
1794 if (!this._isRelatedViewer) {
1795 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
1796 oilsBasePath + "/acq/lineitem/related/" + li.id();
1799 // if a top scroll point is defined, jump up to it here
1800 var node = dojo.byId('oils-scroll-to-top');
1801 if (node) dijit.scrollIntoView(node);
1804 this.generateMakeRecTab = function(bib_id,default_view, row) {
1806 if(openils.XUL.isXUL() && !window.IAMBROWSER) {
1809 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
1812 show_nav_buttons : true,
1813 show_print_button : true,
1814 opac_url : xulG.url_prefix('opac_rdetail|' + bib_id),
1815 default_view : default_view
1819 var url = '/eg/staff/cat/catalog/record/' + bib_id;
1820 if (default_view == 'copy_browser') {
1826 if(row) nodeByName("action_none", row).selected = true;
1830 this.drawMarcHTML = function(li) {
1831 var params = [null, true, li.marc()];
1833 params = [li.eg_bib_id(), true];
1835 fieldmapper.standardRequest(
1836 ['open-ils.search', 'open-ils.search.biblio.record.html'],
1839 oncomplete: function(r) {
1840 dojo.byId('acq-lit-marc-div').innerHTML =
1841 openils.Util.readResponse(r);
1847 this.drawCopies = function(liId, force_fetch) {
1848 this.focusLineitem = liId;
1849 if (typeof force_fetch == "undefined")
1850 force_fetch = false;
1852 var cgi = new openils.CGI();
1853 var source = cgi.param('source');
1854 if (source && source.match(/invoice/)) {
1855 // got here from the invoice page, show the 'return-to-invoice' button
1856 var cgi = new openils.CGI({url : source});
1857 cgi.param('focus_li', liId);
1858 openils.Util.show(dojo.byId('acq-lit-copies-back-to-invoice-button-wrapper'), 'inline');
1859 var button = dojo.byId('acq-lit-copies-back-to-invoice-button');
1860 button.onclick = function() { location.href = cgi.url() };
1863 openils.acq.Lineitem.fetchAndRender(liId, {},
1864 function(li, html) {
1865 dojo.byId('acq-lit-copies-li-summary').innerHTML = html;
1869 this.show('copies');
1871 this.copyCache = {};
1872 this.copyWidgetCache = {};
1873 this.oldCopyWidgetCache = {};
1874 this.virtDfaCounts = {};
1875 this.realDfaCache = {};
1878 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
1879 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
1880 acqLitCopyCountInput.attr('value', '0');
1882 if (this.isPO && PO && PO.order_date()) {
1883 // prevent adding copies to activated POs
1884 acqLitCopyCountInput.attr('disabled', true);
1885 acqLitAddCopyCount.attr('disabled', true);
1888 while(this.copyTbody.childNodes[0])
1889 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
1891 this._drawBatchCopyWidgets();
1893 this._drawDistribApplied(liId);
1895 this._fetchDistribFormulas(
1897 openils.acq.Lineitem.fetchAttrDefs(
1899 self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch);
1906 this._saveDistribAppliedTemplates = function() {
1907 if (!this._appliedDistribTemplate) {
1908 this._appliedDistribTemplate =
1909 dojo.byId("acq-lit-distrib-applied-tbody").
1910 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
1911 dojo.attr(this._appliedDistribTemplate, "id");
1915 this._drawDistribApplied = function(liId) {
1916 /* Build this table while hidden to prevent rendering artifacts */
1917 openils.Util.hide("acq-lit-distrib-applied-tbody");
1919 this._saveDistribAppliedTemplates();
1921 /* Remove any rows in the table from previous populations */
1922 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
1923 forEach(dojo.destroy);
1925 /* Unregister all dijits previously created (for some reason this isn't
1926 * covered by the above destroy calls). */
1927 dijit.registry.forEach(
1928 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
1931 /* Populate the table with our liId */
1933 fieldmapper.standardRequest(
1935 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
1938 "params": [self.authtoken, liId],
1939 "onresponse": function(r) {
1940 var dfa = openils.Util.readResponse(r);
1943 self.realDfaCache[dfa.id()] = dfa;
1944 self._drawDistribAppliedUnit(dfa);
1947 "oncomplete": function() {
1948 /* Reveal built table */
1951 "acq-lit-distrib-applied-tbody", "table-row-group"
1959 this._drawDistribAppliedUnit = function(dfa) {
1960 var new_row = false;
1961 var row = dojo.query(
1962 'tr[formula="' + dfa.formula().id() + '"]',
1963 "acq-lit-distrib-applied-tbody"
1968 row = dojo.clone(this._appliedDistribTemplate);
1969 dojo.attr(row, "formula", dfa.formula().id());
1970 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
1973 var td = dojo.query("td", row)[0];
1975 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1976 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1979 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1981 new dijit.form.Button(
1983 "onClick": function() {
1984 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1985 self.deleteDfa(dfa);
1988 /* XXX I /cannot/ make the following work in as a CSS class
1989 * for some reason. So frustrating... */
1990 "style": function(id) {
1992 "font-weight: bold; color: #c00;" :
1994 }(dfa.id()) + "margin: 0 6px;display: inline;"
1995 }, "dfa-button-" + dfa.id()
1999 "connectId": ["dfa-button-" + dfa.id()],
2000 "label": dojo.string.substitute(
2001 localeStrings.DFA_TIP, dfa.id() > 0 ? [
2002 openils.User.formalName(dfa.creator()),
2003 dojo.date.locale.format(
2004 dojo.date.stamp.fromISOString(dfa.create_time()),
2005 {"formatLength":"short"}
2007 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
2009 }, "dfa-tip-" + dfa.id()
2013 this.deleteDfa = function(dfa) {
2014 if (dfa.id() > 0) { /* real */
2015 this.pcrud.eliminate(
2018 "oncomplete": function() {
2019 self._removeDistribApplied(dfa.id());
2020 delete self.realDfaCache[dfa.id()];
2024 } else { /* virtual */
2025 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
2026 this.virtDfaCounts[dfa.formula().id()] = 0;
2027 /* hasn't been saved yet, so no need to do anything server side */
2028 this._removeDistribApplied(dfa.id());
2033 this._removeDistribApplied = function(dfaId) {
2034 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
2035 dijit.registry.forEach(
2036 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
2038 this._removeDistribAppliedEmptyRows();
2041 this._removeAllDistribAppliedVirtual = function() {
2042 /* Unregister dijits */
2043 dijit.registry.forEach(
2044 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
2046 this._removeDistribAppliedEmptyRows();
2049 this._removeDistribAppliedEmptyRows = function() {
2050 /* Remove any rows with no DFA at all */
2051 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
2053 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
2059 * Insert a new row into the distribution formula selection form
2061 this._addDistribFormulaRow = function() {
2064 if (!self.distribForms) {
2065 // no formulas, hide the form
2066 openils.Util.hide('acq-lit-distrib-formula-table');
2070 if(!this.distribFormulaTemplate)
2071 this.distribFormulaTemplate =
2072 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
2074 var row = this.distribFormulaTemplate.cloneNode(true);
2075 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
2077 this.dfSelector = new dijit.form.FilteringSelect(
2078 {"labelAttr": "dynLabel", "labelType": "html"},
2079 nodeByName("selector", row)
2081 this._updateFormulaStore();
2082 this.dfSelector.fetchProperties =
2083 {"sort": [{"attribute": "use_count", "descending": true}]};
2085 var apply = new dijit.form.Button(
2086 {"label": localeStrings.APPLY},
2087 nodeByName('set_button', row)
2090 var reset = new dijit.form.Button(
2091 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
2092 nodeByName("reset_button", row)
2095 dojo.connect(apply, 'onClick',
2097 var form_id = self.dfSelector.attr("value");
2098 if(!form_id) return;
2099 self._applyDistribFormula(form_id);
2100 reset.attr("disabled", false);
2104 dojo.connect(reset, 'onClick',
2106 self.restoreCopyFieldsBeforeDF();
2107 self.virtDfaCounts = {};
2108 self.virtDfaId = -1;
2110 self._updateFormulaStore();
2111 self._removeAllDistribAppliedVirtual();
2112 reset.attr("disabled", "true");
2119 * Applies a distrib formula to the current set of copies
2121 this._applyDistribFormula = function(formula) {
2122 if(!formula) return;
2124 formula = this.distribForms.filter(
2125 function(form) { return form.id() == formula; }
2128 var copyRows = dojo.query('tr', self.copyTbody);
2130 if (this.dfeOffset >= copyRows.length) {
2131 alert(localeStrings.OUT_OF_COPIES);
2135 var entries_applied = 0;
2137 var rowIndex = this.dfeOffset;
2138 rowIndex < copyRows.length;
2142 var row = copyRows[rowIndex];
2143 var copy_id = row.getAttribute('copy_id');
2144 var copyWidgets = this.copyWidgetCache[copy_id];
2145 var entryIndex = this.dfeOffset;
2148 // find the correct entry for the current row
2149 dojo.forEach(formula.entries(),
2152 entryIndex += e.item_count();
2153 if(entryIndex > rowIndex)
2161 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
2162 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
2165 this.saveCopyFieldsBeforeDF(copy_id);
2166 this._copy_fields_for_acqdf.forEach(
2168 if(entry[field]()) {
2169 copyWidgets[field].attr('value', (entry[field]()));
2176 if (entries_applied) {
2177 this.virtDfaCounts[formula.id()] =
2178 ++(this.virtDfaCounts[formula.id()]) || 1;
2179 this._updateFormulaStore();
2180 this._drawDistribAppliedUnit(
2182 var dfa = new acqdfa();
2183 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
2186 this.dfeOffset += entries_applied;
2191 * This function updates the DF store for the dropdown so that use_counts
2192 * can reflect DF applications from this session before they're saved
2195 this._updateFormulaStore = function() {
2196 this.dfSelector.store = new dojo.data.ItemFileReadStore(
2198 "data": self._labelFormulasWithCounts(
2199 acqdf.toStoreData(self.distribForms)
2205 this.saveCopyFieldsBeforeDF = function(copy_id) {
2207 if (!this.oldCopyWidgetCache[copy_id]) {
2208 var copyWidgets = this.copyWidgetCache[copy_id];
2210 this.oldCopyWidgetCache[copy_id] = {};
2211 this._copy_fields_for_acqdf.forEach(
2213 self.oldCopyWidgetCache[copy_id][f] =
2214 copyWidgets[f].attr("value");
2220 this.restoreCopyFieldsBeforeDF = function() {
2222 for (var copy_id in this.oldCopyWidgetCache) {
2223 this._copy_fields_for_acqdf.forEach(
2225 self.copyWidgetCache[copy_id][f].attr(
2226 "value", self.oldCopyWidgetCache[copy_id][f]
2233 this._labelFormulasWithCounts = function(store_data) {
2234 for (var key in store_data.items) {
2235 var obj = store_data.items[key];
2236 obj.use_count = Number(obj.use_count); /* needed for sorting */
2238 if (this.virtDfaCounts[obj.id])
2239 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
2241 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
2242 obj.use_count + "]</span> " + obj.name;
2248 * This method formerly would not refetch the DF formulas if they'd been
2249 * loaded already, but now it always re-fetches, since use_count changes.
2251 /** TODO: port distrib-formula selector to autofieldwidget+pcrud/dojo store */
2252 this._fetchDistribFormulas = function(onload) {
2253 fieldmapper.standardRequest(
2255 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
2258 "params": [openils.User.authtoken, 0, 500],
2259 "oncomplete": function(r) {
2260 self.distribForms = openils.Util.readResponse(r);
2261 if(!self.distribForms || self.distribForms.length == 0) {
2262 self.distribForms = [];
2264 self._addDistribFormulaRow();
2271 this._drawBatchCopyWidgets = function() {
2272 var row = this.copyBatchRow;
2273 dojo.forEach(liDetailBatchFields,
2275 if(self.copyBatchRowDrawn) {
2276 self.copyBatchWidgets[field].attr('value', null);
2278 var args = self.afwCopyFieldArgs(field, "CREATE_PICKLIST");
2279 args.parentNode = dojo.query('[name='+field+']', row)[0];
2281 var widget = new openils.widget.AutoFieldWidget(args);
2284 if (field == "fund" && w.store)
2285 self._ensureCSSFundClasses(w.store);
2286 self.copyBatchWidgets[field] = w;
2289 if (field == "fund") {
2291 widget.widget, "onChange", function(val) {
2292 self._updateFundSelectorStyle(widget, val);
2299 this.copyBatchRowDrawn = true;
2302 this.batchCopyUpdate = function() {
2304 for(var k in this.copyWidgetCache) {
2305 var cache = this.copyWidgetCache[k];
2306 dojo.forEach(liDetailBatchFields, function(f) {
2307 var newval = self.copyBatchWidgets[f].attr('value');
2308 if(newval) cache[f].attr('value', newval);
2313 this._drawCopies = function(li) {
2316 // this button sets the total number of copies for a given lineitem
2317 acqLitAddCopyCount.onClick = function() {
2318 var count = acqLitCopyCountInput.attr('value');
2321 while(self.copyCount() < count)
2324 // delete rows if necessary
2325 var diff = self.copyCount() - count;
2327 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
2328 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
2329 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
2331 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2337 if(li.lineitem_details().length > 0) {
2338 dojo.forEach(li.lineitem_details(),
2340 self.addCopy(li, copy);
2348 this.copyCount = function() {
2350 for(var id in this.copyCache) {
2351 if(!this.copyCache[id].isdeleted())
2357 this.virtCopyId = -1;
2358 this.addCopy = function(li, copy) {
2359 var row = this.copyRow.cloneNode(true);
2360 this.copyTbody.appendChild(row);
2364 copy = new fieldmapper.acqlid();
2366 copy.id(this.virtCopyId--);
2367 copy.lineitem(li.id());
2370 this.copyCache[copy.id()] = copy;
2371 row.setAttribute('copy_id', copy.id());
2372 self.copyWidgetCache[copy.id()] = {};
2374 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2376 var rcvr = copy.receiver();
2378 if (!userCache[rcvr]) {
2379 if(rcvr == openils.User.user.id()) {
2380 userCache[rcvr] = openils.User.user;
2382 userCache[rcvr] = fieldmapper.standardRequest(
2383 ['open-ils.actor', 'open-ils.actor.user.retrieve'],
2384 {params: [openils.User.authtoken, rcvr]}
2388 dojo.query('[name=receiver]', row)[0].innerHTML = userCache[rcvr].usrname();
2391 dojo.forEach(liDetailFields,
2394 if (field == "fund") {
2395 searchFilter = (copy.fund() ?
2396 {"-or": {"active": "t", "id": copy.fund()}} :
2398 searchFilter.org = fundSearchFilter.org;
2400 searchFilter = null;
2403 var readOnly = false;
2405 // TODO: Add support for changing the owning_lib after real copies have been made.
2406 // owning_lib is order data as much as its item data
2407 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
2411 // TODO: add support for changing the fund after debits have been created
2412 // Note: invoicing allows the change
2413 if(copy.fund_debit() && field == 'fund') {
2418 var widget = new openils.widget.AutoFieldWidget({
2421 labelFormat : (field == 'fund') ? fundLabelFormat : null,
2422 searchFormat : (field == 'fund') ? fundSearchFormat : null,
2423 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
2424 searchFilter : searchFilter,
2425 noCache: (field == "fund"),
2427 parentNode : dojo.query('[name='+field+']', row)[0],
2428 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2429 readOnly : readOnly,
2430 orgDefaultsToWs : true
2434 // make sure we capture the value from any async widgets
2437 if (field == "fund" && w.store)
2438 self._ensureCSSFundClasses(w.store);
2441 copy[field](ww.getFormattedValue())
2443 self.copyWidgetCache[copy.id()][field] = w;
2445 dojo.connect(w, 'onChange',
2447 if (field == "fund")
2448 self._updateFundSelectorStyle(widget, val);
2450 if (!readOnly && (copy.isnew() || val != copy[field]())) {
2451 // prevent setting ischanged() automatically on widget load for existing copies
2452 copy[field](widget.getFormattedValue())
2453 copy.ischanged(true);
2462 this.updateLidState(copy, row);
2465 this._ensureCSSFundClass = function(id) {
2466 if (!this.fundStyleSheet) {
2468 "style", {"type": "text/css"},
2469 document.getElementsByTagName("head")[0], "last"
2471 this.fundStyleSheet = document.styleSheets[
2472 document.styleSheets.length - 1
2476 var cn = "fund_" + id;
2477 if (!this.haveFundClass[cn]) {
2478 fieldmapper.standardRequest(
2479 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
2481 "params": [openils.User.authtoken, id],
2483 "oncomplete": function(r) {
2484 r = openils.Util.readResponse(r);
2485 self.fundBalanceState[id] = r;
2487 if (r[0] /* stop */)
2488 style = fundStyles.stop;
2489 else if (r[1] /* warning */)
2490 style = fundStyles.warning;
2491 self.fundStyleSheet.insertRule(
2492 "." + cn + " { " + style + " }",
2493 self.fundStyleSheet.cssRules.length
2495 self.haveFundClass[cn] = true;
2502 this._ensureCSSFundClasses = function(store) {
2504 "query": {"id": "*"},
2505 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
2509 this._updateFundSelectorStyle = function(widget, fund_id) {
2510 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
2511 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
2514 this.updateLidState = function(copy, row) {
2517 if (typeof(row) == "undefined") {
2518 row = dojo.query('tr[copy_id="' + copy.id() + '"]', this.copyTbody)[0];
2522 var recv_link = nodeByName("receive", row);
2523 var unrecv_link = nodeByName("unreceive", row);
2524 var del_link = nodeByName("delete", row);
2525 var cxl_link = nodeByName("cancel", row);
2526 var claim_link = nodeByName("claim", row);
2527 var cxl_reason_link = nodeByName("cancel_reason", row);
2529 // by default, hide all the actions
2530 openils.Util.hide(del_link.parentNode);
2531 openils.Util.hide(recv_link);
2532 openils.Util.hide(unrecv_link);
2533 openils.Util.hide(cxl_link);
2534 openils.Util.hide(claim_link);
2535 openils.Util.hide(cxl_reason_link);
2537 if (copy.id() > 0) { // real copies (LIDs)
2539 if (copy.cancel_reason()) {
2541 /* --------- cancelled -------------------------- */
2543 /* XXX the following may leak memory in a long lived table:
2544 * dijits may not get destroyed... not positive. revisit. */
2545 var holds_reason = dojo.create(
2547 "style": "border-bottom: 1px dashed #000;",
2548 "innerHTML": copy.cancel_reason().label()
2549 }, cxl_reason_link, "only"
2553 "label": "<em>" + copy.cancel_reason().label() +
2554 "</em><br />" + copy.cancel_reason().description(),
2555 "connectId": [holds_reason]
2556 }, dojo.create("span", null, cxl_reason_link, "last")
2558 openils.Util.show(cxl_reason_link, "inline");
2560 if (copy.cancel_reason().keep_debits() == 't' ) {
2561 // allow further cancellation of "delayed" copies
2563 openils.Util.show(cxl_link, "inline");
2564 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2567 } else if (copy.recv_time()) {
2569 /* --------- received -------------------------- */
2571 openils.Util.show(unrecv_link, "inline");
2572 unrecv_link.onclick = function() {
2573 if (confirm(localeStrings.UNRECEIVE_LID))
2574 self.issueReceive(copy, /* rollback */ true);
2577 } else if (this.liCache[copy.lineitem()].state() == 'on-order') {
2579 /* --------- on order -------------------------- */
2581 openils.Util.show(recv_link, 'inline');
2582 openils.Util.show(cxl_link, "inline");
2584 recv_link.onclick = function() {
2585 if (self.checkLiAlerts(copy.lineitem()))
2586 self.issueReceive(copy);
2589 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2593 /* --------- pre-order copies -------------------------- */
2595 del_link.onclick = function() { self.deleteCopy(row) };
2596 openils.Util.show(del_link.parentNode);
2602 /* --------- virtual copies -------------------------- */
2604 del_link.onclick = function() { self.deleteCopy(row) };
2605 openils.Util.show(del_link.parentNode);
2609 this.cancelLid = function(lid_id) {
2610 lidCancelDialog._lid_id = lid_id;
2611 openils.Util.show(lidCancelDialog.domNode.parentNode);
2612 lidCancelDialog.show();
2613 if (!lidCancelDialog._prepared) {
2614 var widget = new openils.widget.AutoFieldWidget({
2615 "fmField": "cancel_reason",
2616 "fmClass": "acqlid",
2617 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
2618 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2620 "searchOptions" : {order_by : {"acqcr":"label"}}
2624 acqLidCancelButton.onClick = function() {
2625 if (w.attr("value")) {
2626 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
2628 lidCancelDialog._lid_id,
2632 lidCancelDialog.hide();
2635 lidCancelDialog._prepared = true;
2641 this._cancelLid = function(lid_id, reason) {
2642 fieldmapper.standardRequest(
2643 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
2644 "params": [openils.User.authtoken, lid_id, reason],
2646 "onresponse": function(r) {
2647 if (r = openils.Util.readResponse(r)) {
2649 for (var id in r.lid) {
2650 /* actually this should only iterate once */
2651 self.copyCache[id].cancel_reason(
2652 r.lid[id].cancel_reason
2654 self.updateLidState(self.copyCache[id]);
2663 this._confirmAlert = function(li, lin) {
2665 dojo.string.substitute(
2666 localeStrings.CONFIRM_LI_ALERT, [
2667 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2668 "title", "lineitem_marc_attr_definition"
2670 /* XXX it's really better add a parameter and to adjust
2671 * the format string rather than do this concatenation
2672 * here, but if someone wants this for 2.2 in a hurry,
2673 * we can sidestep the problem of updating the strings
2674 * while the translators are working. */
2676 aou.findOrgUnit(lin.alert_text().owning_lib()).shortname() +
2678 lin.alert_text().code()
2680 lin.alert_text().description() || "",
2687 this.checkLiAlerts = function(li_id) {
2688 var li = this.liCache[li_id];
2690 var alert_notes = li.lineitem_notes().filter(
2691 function(o) { return Boolean(o.alert_text()); }
2694 /* this is _intentionally_ not done in a call to forEach() ... */
2695 for (var i = 0; i < alert_notes.length; i++) {
2696 if (this.noteAcks[alert_notes[i].id()])
2698 else if (!this._confirmAlert(li, alert_notes[i]))
2701 this.noteAcks[alert_notes[i].id()] = true;
2707 this.deleteCopy = function(row) {
2708 var copy = this.copyCache[row.getAttribute('copy_id')];
2709 copy.isdeleted(true);
2711 delete this.copyCache[copy.id()];
2712 this.copyTbody.removeChild(row);
2715 this._virtDfaCountsAsList = function() {
2717 for (var key in this.virtDfaCounts) {
2718 for (var i = 0; i < this.virtDfaCounts[key]; i++)
2724 this.confirmBreachedCopyFunds = function(copies) {
2725 var stop = 0, warning = 0;
2729 var state = self.fundBalanceState[o.fund()];
2730 if (state[0] /* stop */)
2732 else if (state[1] /* warning */)
2739 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
2740 } else if (warning) {
2741 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
2746 this.saveCopyChanges = function(liId) {
2752 for(var id in this.copyCache) {
2753 var c = this.copyCache[id];
2754 if(!c.isdeleted()) total++;
2755 if(c.isnew() || c.ischanged() || c.isdeleted()) {
2756 if(c.id() < 0) c.id(null);
2762 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
2765 if (copies.length > 0) {
2766 if (!this.confirmBreachedCopyFunds(copies))
2769 if (typeof(this._copy_count_cb) == "function")
2770 this._copy_count_cb(liId, total);
2772 openils.Util.show("acq-lit-update-copies-progress");
2773 fieldmapper.standardRequest(
2774 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
2776 params: [openils.User.authtoken, copies],
2777 onresponse: function(r) {
2778 var res = openils.Util.readResponse(r);
2779 litUpdateCopiesProgress.update(res);
2781 oncomplete: function() {
2782 self.drawCopies(liId, true /* force_fetch */);
2783 openils.Util.hide("acq-lit-update-copies-progress");
2784 refreshPOSummaryAmounts();
2790 var dfa_list = this._virtDfaCountsAsList();
2791 if (dfa_list.length > 0) {
2792 fieldmapper.standardRequest(
2794 "open-ils.acq.distribution_formula.record_application"],
2797 "params": [openils.User.authtoken, dfa_list, liId],
2798 "onresponse": function(r) {
2799 var res = openils.Util.readResponse(r);
2800 if (res && res.length < dfa_list.length)
2801 alert(localeStrings.DFA_NOT_ALL);
2805 this.virtDfaCounts = {};
2808 if (this.inlineCopiesNeedingRefresh.indexOf(liId) < 0)
2809 this.inlineCopiesNeedingRefresh.push(liId);
2812 this._updateCreatePoPrepayCheckbox = function(prepay) {
2813 var prepay = openils.Util.isTrue(prepay);
2814 this._prepayRequiredByVendor = prepay;
2815 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
2818 this._confirmPoPrepaySituation = function() {
2819 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
2820 if (want_prepay != this._prepayRequiredByVendor) {
2823 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
2824 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
2831 this.applySelectedLiAction = function(action) {
2835 case 'delete_selected':
2836 this._deleteLiList(self.getSelected());
2839 case 'add_to_order':
2840 addToPoDialog._get_li = dojo.hitch(
2843 return this.getSelected(
2844 false, null, true, li_pre_po_states);
2847 if (addToPoDialog._get_li().length == 0) {
2848 alert(localeStrings.NO_LI_GENERAL);
2851 addToPoDialog.show();
2854 case 'create_order':
2855 this._loadPOSelect();
2856 acqLitPoCreateDialog.show();
2859 case 'save_picklist':
2860 acqLitSavePlDialog.show();
2863 case 'selector_ready':
2865 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
2866 acqLitChangeLiStateDialog.show();
2874 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
2877 case 'batch_create_invoice':
2878 this.batchCreateInvoice();
2881 case 'batch_link_invoice':
2882 this.batchLinkInvoice();
2885 case 'receive_lineitems':
2886 this.receiveSelectedLineitems();
2889 case 'rollback_receive_lineitems':
2890 this.rollbackReceiveLineitems();
2893 case 'create_assets':
2894 this.showAssetCreator();
2897 case 'export_attr_list':
2898 this.chooseExportAttr();
2901 case 'batch_apply_funds':
2902 this.applyBatchLiFunds();
2905 case 'add_brief_record':
2907 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
2909 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
2913 case "cancel_lineitems":
2914 console.log('HERE');
2915 this.maybeCancelLineitems();
2918 case "apply_claim_policy":
2919 var li_list = this.getSelected();
2920 this.claimPolicyPicker.attr("value", null);
2921 liClaimPolicyDialog.show();
2922 liClaimPolicySave.onClick = function() {
2923 self.changeClaimPolicy(
2925 self.claimPolicyPicker.attr("value"),
2929 self.setClaimPolicyControl(li);
2930 self.reconsiderClaimControl(li);
2933 liClaimPolicyDialog.hide();
2941 this.changeClaimPolicy = function(li_list, value, callback) {
2943 function(li) { li.claim_policy(value); }
2945 fieldmapper.standardRequest(
2946 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
2947 "params": [openils.User.authtoken, li_list],
2949 "oncomplete": function(r) {
2950 r = openils.Util.readResponse(r);
2951 if (callback) callback(r);
2957 this.showAssetCreator = function(onAssetsCreated) {
2958 if(!this.isPO) return;
2961 // first, let's see if this PO has any LI's that need to be merged/imported
2962 self.pcrud.search('jub', {purchase_order : this.isPO, eg_bib_id : null}, {
2964 oncomplete : function(r) {
2965 var resp = openils.Util.readResponse(r);
2966 if (resp && resp.length) {
2967 // PO has some non-linked jubs.
2969 self.show('asset-creator');
2970 if(!self.vlAgent.loaded)
2971 self.vlAgent.init();
2973 dojo.connect(assetCreatorButton, 'onClick',
2974 function() { self.createAssets(onAssetsCreated) });
2978 // all jubs linked, move on to asset creation
2979 self.createAssets(onAssetsCreated, true);
2985 this.createAssets = function(onAssetsCreated, noVl) {
2986 this.show('acq-lit-progress-numbers');
2988 var vlArgs = (noVl) ? {} : {vandelay : this.vlAgent.values()};
2989 this.batchProgress = {};
2990 progressDialog.show(false);
2991 progressDialog.attr("title", localeStrings.LI_CREATING_ASSETS);
2992 fieldmapper.standardRequest(
2993 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
2995 params: [this.authtoken, this.isPO, vlArgs],
2996 onresponse: function(r) {
2997 var resp = openils.Util.readResponse(r);
2998 self._updateProgressNumbers(resp, !Boolean(onAssetsCreated), onAssetsCreated, true);
3004 this.maybeCancelLineitems = function() {
3005 openils.Util.show("acq-lit-cancel-reason", "inline");
3006 if (!acqLitCancelLineitemsButton._prepared) {
3007 var widget = new openils.widget.AutoFieldWidget({
3008 "fmField": "cancel_reason",
3010 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
3011 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3013 "searchOptions" : {order_by : {"acqcr":"label"}}
3017 acqLitCancelLineitemsButton.onClick = function() {
3018 if (w.attr("value")) {
3019 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
3020 self._cancelLineitems(w.attr("value"));
3022 openils.Util.hide("acq-lit-cancel-reason");
3025 acqLitCancelLineitemsButton._prepared = true;
3031 this._cancelLineitems = function(reason) {
3033 var li_list = this.getSelected();
3035 // canceled lineitems may be canceled again if they were
3036 // previously delayed (keep_debits = true).
3037 li_list = li_list.filter(
3040 li.state() != 'cancelled' ||
3041 li.cancel_reason().keep_debits() == 't'
3046 id_list = li_list.map(function(l) {return l.id()});
3048 if (!id_list.length) {
3049 alert(localeStrings.NO_LI_GENERAL);
3052 fieldmapper.standardRequest(
3053 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
3054 "params": [openils.User.authtoken, id_list, reason],
3056 "onresponse": function(r) {
3057 if (r = openils.Util.readResponse(r)) {
3059 for (var id in r.li) {
3060 self.liCache[id].state(r.li[id].state);
3061 self.liCache[id].cancel_reason(
3062 r.li[id].cancel_reason
3064 self.updateLiState(self.liCache[id]);
3067 if (r.lid && self.copyCache) {
3068 for (var id in r.lid) {
3069 if (self.copyCache[id]) {
3070 self.copyCache[id].cancel_reason(
3071 r.lid[id].cancel_reason
3073 self.updateLidState(self.copyCache[id]);
3083 this.chooseExportAttr = function() {
3084 if (!acqLitExportAttrSelector._li_setup) {
3086 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
3088 "data": acqlimad.toStoreData(
3090 "acqlimad", {"code": li_exportable_attrs}
3095 acqLitExportAttrSelector.setValue();
3096 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
3097 acqLitExportAttrSelector._li_setup = true;
3099 openils.Util.show("acq-lit-export-attr-holder", "inline");
3102 this.exportAttrList = function() {
3103 var attr_def = acqLitExportAttrSelector.item;
3104 var li_list = this.getSelected();
3105 var value_list = li_list.map(
3107 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
3108 attr_def.code, "lineitem_marc_attr_definition"
3111 ).filter(function(attr) { return Boolean(attr); });
3113 if (value_list.length > 0) {
3114 if (value_list.length < li_list.length) {
3116 dojo.string.substitute(
3117 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
3124 openils.XUL.contentToFileSaveDialog(
3125 value_list.join("\n"),
3126 localeStrings.EXPORT_SAVE_DIALOG_TITLE
3132 alert(dojo.string.substitute(
3133 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
3137 openils.Util.hide("acq-lit-export-attr-holder");
3140 this.printPO = function() {
3141 if(!this.isPO) return;
3142 progressDialog.show(true);
3143 fieldmapper.standardRequest(
3144 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
3146 params: [this.authtoken, this.isPO, 'html'],
3147 oncomplete: function(r) {
3148 progressDialog.hide();
3149 var evt = openils.Util.readResponse(r);
3150 if(evt && evt.template_output()) {
3151 openils.Util.printHtmlString(evt.template_output().data());
3158 this.batchCreateInvoice = function() {
3159 var liIds = this.getSelected(
3160 false, null, true /* id_list */, li_active_states)
3161 if (!liIds.length) {
3162 alert(localeStrings.NO_LI_GENERAL);
3165 var path = oilsBasePath + '/acq/invoice/view?create=1';
3166 dojo.forEach(liIds, function(li, idx) { path += '&attach_li=' + li });
3167 if (openils.XUL.isXUL() && !window.IAMBROWSER)
3168 openils.XUL.newTabEasy(path, localeStrings.NEW_INVOICE, null, true);
3170 location.href = path;
3173 this.batchLinkInvoice = function(create) {
3174 var liIds = this.getSelected(
3175 false, null, true /* id_list */, li_active_states)
3176 if (!liIds.length) {
3177 alert(localeStrings.NO_LI_GENERAL);
3180 if (!self.invoiceLinkDialogManager) {
3181 self.invoiceLinkDialogManager =
3182 new InvoiceLinkDialogManager("li");
3184 self.invoiceLinkDialogManager.target = liIds;
3185 acqLitLinkInvoiceDialog.show();
3188 this.receiveSelectedLineitems = function() {
3189 var states = li_post_po_states.filter(
3190 function(s) { return s != 'received' });
3191 var li_list = this.getSelected(null, null, null, states);
3193 if (!li_list.length) {
3194 alert(localeStrings.NO_LI_GENERAL);
3198 for (var i = 0; i < li_list.length; i++) {
3199 var li = li_list[i];
3201 if (li.state() != "received" &&
3202 !this.checkLiAlerts(li.id())) return;
3205 this.show('acq-lit-progress-numbers');
3208 fieldmapper.standardRequest(
3209 ['open-ils.acq', 'open-ils.acq.lineitem.receive.batch'],
3213 li_list.map(function(li) { return li.id(); })
3215 onresponse : function(r) {
3216 var resp = openils.Util.readResponse(r);
3217 self._updateProgressNumbers(resp, true);
3223 this.issueReceive = function(obj, rollback) {
3225 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
3227 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
3229 progressDialog.show(true);
3230 fieldmapper.standardRequest(
3231 ["open-ils.acq", method], {
3233 "params": [this.authtoken, obj.id()],
3234 "onresponse": function(r) {
3235 if (r = openils.Util.readResponse(r)) {
3236 self.fetchClaimInfo(
3237 part == "lineitem" ? obj.id() : obj.lineitem(),
3239 function() { self.handleReceive(r); }
3241 progressDialog.hide();
3249 * Handles the responses from receive and rollback ML calls.
3251 this.handleReceive = function(resp) {
3254 for (var li_id in resp.li) {
3255 for (var key in resp.li[li_id])
3256 self.liCache[li_id][key](resp.li[li_id][key]);
3257 self.updateLiState(self.liCache[li_id]);
3261 if (typeof(self.poUpdateCallback) == "function")
3262 self.poUpdateCallback(resp.po);
3265 for (var lid_id in resp.lid) {
3266 for (var key in resp.lid[lid_id])
3267 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
3268 self.updateLidState(self.copyCache[lid_id]);
3274 this.rollbackReceiveLineitems = function() {
3275 var li_id_list = this.getSelected(false, null, true);
3276 if (!li_id_list.length) {
3277 alert(localeStrings.NO_LI_GENERAL);
3281 if (!confirm(localeStrings.ROLLBACK_LI_RECEIVE_CONFIRM)) return;
3283 this.show('acq-lit-progress-numbers');
3286 fieldmapper.standardRequest(
3287 ['open-ils.acq', 'open-ils.acq.lineitem.receive.rollback.batch'],
3289 params: [this.authtoken, li_id_list],
3290 onresponse : function(r) {
3291 var resp = openils.Util.readResponse(r);
3292 self._updateProgressNumbers(resp, true);
3298 this._updateProgressNumbers = function(resp, reloadOnComplete, onComplete, clearProgressDialog) {
3299 this._updateProgressDialog(resp);
3300 this.vlAgent.handleResponse(resp,
3301 function(resp, res) {
3302 if (clearProgressDialog) {
3303 progressDialog.update({ "progress": 100});
3304 progressDialog.update_message();
3305 progressDialog.hide();
3306 progressDialog.attr("title", "");
3308 if(reloadOnComplete)
3309 location.href = location.href;
3311 onComplete(resp, res);
3316 this._updateProgressDialog = function(resp) {
3317 progressDialog.update({ "progress": (resp.progress / resp.total) * 100 });
3318 var keys = ['li', 'vqbr', 'bibs', 'lid', 'debits_accrued', 'copies'];
3319 for (var i = 0; i < keys.length; i++) {
3320 if (resp[keys[i]] > (this.batchProgress[keys[i]] || 0)) {
3321 progressDialog.update_message(
3322 dojo.string.substitute(
3323 localeStrings["ACTIVATE_" + keys[i].toUpperCase() + "_PROCESSED"],
3329 this.batchProgress = resp;
3332 this._createPO = function(fields) {
3333 var wantall = (fields.create_from == "all");
3335 /* If we're a picklist or purchase order already and the user wants
3336 * all lineitems, we might have pages' worth of lineitems haven't all
3337 * been loaded yet, so getSelected() won't find them. The server,
3338 * however, should know about all our lineitems, so let's ask the
3339 * server for a complete list.
3344 true, function(list) {
3345 self._createPOFromLineitems(fields, list);
3346 }, /* id_list */ true, li_pre_po_states
3349 this._createPOFromLineitems(
3350 fields, this.getSelected(
3351 false, null, true /* id_list */, li_pre_po_states)
3356 this._createPOFromLineitems = function(fields, selected) {
3357 if (selected.length == 0) {
3358 alert(localeStrings.NO_LI_GENERAL);
3363 var po = new fieldmapper.acqpo();
3364 po.provider(this.createPoProviderSelector.attr("value"));
3365 po.ordering_agency(this.createPoAgencySelector.attr("value"));
3366 po.prepayment_required(fields.prepayment_required[0] ? true : false);
3367 var name = this.createPoNameInput.attr('value');
3368 if (name) po.name(name); // avoid name=""
3370 // if we're creating assets, delay the asset creation
3371 // until after the PO is created. This will allow us to
3372 // use showAssetCreator() directly.
3374 fieldmapper.standardRequest(
3375 ["open-ils.acq", "open-ils.acq.purchase_order.create"],
3378 openils.User.authtoken,
3379 po, {lineitems : selected}
3381 onresponse : function(r) {
3382 var resp = openils.Util.readResponse(r);
3383 if (resp.complete) {
3384 // self.isPO is needed for showAssetCreator();
3385 self.isPO = resp.purchase_order.id();
3386 var redir = oilsBasePath + "/acq/po/view/" + self.isPO;
3387 if (fields.create_assets[0]) {
3388 self.showAssetCreator(
3389 function() {location.href = redir}
3392 location.href = redir;
3401 this.batchFundWidget = null;
3403 this.applyBatchLiFunds = function() {
3405 var liIds = this.getSelected().map(function(li) { return li.id(); });
3406 if(liIds.length == 0) return; // warn?
3409 batchFundUpdateDialog.show();
3411 if(!this.batchFundWidget) {
3412 this.batchFundWidget = new openils.widget.AutoFieldWidget({
3414 selfReference : true,
3415 labelFormat : fundLabelFormat,
3416 searchFormat : fundSearchFormat,
3417 searchFilter : fundSearchFilter,
3418 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
3419 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
3420 dijitArgs : { "required": true, "labelType": "html" },
3423 this.batchFundWidget.build();
3426 dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
3427 dojo.connect(batchFundUpdateSubmit, 'onClick',
3430 // TODO: call .dry_run first to test thresholds
3431 fieldmapper.standardRequest(
3432 ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
3435 openils.User.authtoken,
3437 self.batchFundWidget.widget.attr('value')
3439 oncomplete : function(r) {
3440 var resp = openils.Util.readResponse(r);
3442 location.href = location.href;
3451 this._deleteLiList = function(list, idx) {
3452 if(idx == null) idx = 0;
3453 if(idx >= list.length) return;
3458 if (this.isPO && (li.state() == "on-order" || li.state() == "received")) {
3459 /* It makes little sense to delete a lineitem from a PO that has
3460 * already been marked 'on-order'. Especially if EDI is in use,
3461 * such a purchase order will probably have already been shipped
3462 * off to a vendor, and mucking with it at this point could leave
3463 * your data in a bad state that doesn't jive with reality.
3465 * I could see making this restriction even firmer.
3467 * I could also see adjusting the li state comparisons, extending
3468 * the comparison to the PO's state, and/or providing functions
3469 * that house the logic for comparing states in a single location.
3471 * Yes, this will be really annoying if you have selected a lot
3472 * of lineitems to cancel that have been ordered. You'll get a
3473 * confirm dialog for each one.
3476 if (!confirm(localeStrings.DEL_LI_FROM_PO)) {
3477 self._deleteLiList(list, ++idx); /* move on to next in list */
3482 fieldmapper.standardRequest(
3484 this.isPO ? 'open-ils.acq.purchase_order.lineitem.delete' : 'open-ils.acq.picklist.lineitem.delete'],
3486 params: [openils.User.authtoken, liId],
3487 oncomplete: function(r) {
3488 self.removeLineitem(liId);
3489 self._deleteLiList(list, ++idx);
3495 this.editOrderMarc = function(li) {
3497 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
3498 to true in about:config */
3500 if(openils.XUL.isXUL()) {
3501 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul','','chrome');
3503 win = window.open('/xul/server/cat/marcedit.xul','','chrome');
3507 record : {marc : li.marc(), "rtype": "bre"},
3509 label: 'Save Record', // XXX I18N
3510 func: function(xmlString) {
3512 fieldmapper.standardRequest(
3513 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
3515 params: [openils.User.authtoken, li],
3516 oncomplete: function(r) {
3517 openils.Util.readResponse(r);
3519 self.drawInfo(li.id())
3525 'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
3526 'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
3530 this._savePl = function(values) {
3532 (values.which == 'all'),
3533 function(list) { self._savePlFromLineitems(values, list); }
3537 this._savePlFromLineitems = function(values, selected) {
3538 openils.Util.show("acq-lit-generic-progress");
3540 if(values.new_name) {
3541 openils.acq.Picklist.create(
3542 {name: values.new_name},
3548 oilsBasePath + "/acq/picklist/view/" + id;
3553 } else if(values.existing_pl) {
3554 // update lineitems to use an existing picklist
3556 values.existing_pl, selected, 0,
3559 oilsBasePath + "/acq/picklist/view/" +
3566 this._updateLiState = function(values, state, state_filter) {
3567 progressDialog.show(true);
3569 (values.which == 'all'),
3571 self._updateLiStateFromLineitems(values, state, list);
3572 }, false /* id_list */, state_filter
3576 this._updateLiStateFromLineitems = function(values, state, selected) {
3577 if(!selected.length) {
3578 try { progressDialog.hide() } catch(E) {};
3579 alert(localeStrings.NO_LI_GENERAL);
3582 dojo.forEach(selected, function(li) {li.state(state);});
3583 self._updateLiList(null, selected, 0,
3584 // TODO consider inline updates for efficiency
3585 function() { location.href = location.href }
3589 this._updateLiList = function(pl, list, idx, oncomplete) {
3590 if(idx >= list.length) return oncomplete();
3592 if(pl != null) li.picklist(pl);
3593 litGenericProgress.update({maximum: list.length, progress: idx});
3594 new openils.acq.Lineitem({lineitem:li}).update(
3596 self._updateLiList(pl, list, ++idx, oncomplete);
3601 this._loadPOSelect = function() {
3602 if (!this.createPoProviderSelector) {
3603 var widget = new openils.widget.AutoFieldWidget({
3604 "fmField": "provider",
3606 "searchFilter": {"active": "t"},
3607 "parentNode": dojo.byId("acq-lit-po-provider"),
3609 "onChange": function() {
3611 self._updateCreatePoPrepayCheckbox(
3612 this.item.prepayment_required()
3618 widget.build(function(w) { self.createPoProviderSelector = w; });
3621 this.createPoCheckDupes = function() {
3622 var org = self.createPoAgencySelector.attr('value');
3623 var name = self.createPoNameInput.attr('value');
3624 openils.Util.hide('acq-dupe-po-name');
3627 acqLitCreatePoSubmit.attr('disabled', false);
3631 acqLitCreatePoSubmit.attr('disabled', true);
3632 var orgs = fieldmapper.aou.descendantNodeList(org, true);
3633 new openils.PermaCrud().search('acqpo',
3634 {name : name, ordering_agency : orgs},
3635 {async : true, oncomplete : function(r) {
3636 var po = openils.Util.readResponse(r);
3638 if (po && (po = po[0])) {
3640 var link = dojo.byId('acq-dupe-po-link');
3641 openils.Util.show('acq-dupe-po-name', 'table-row');
3642 var dupe_path = '/acq/po/view/' + po.id();
3646 if (window.IAMBROWSER) {
3647 // TODO: integration
3651 link.onclick = function() {
3653 var loc = xulG.url_prefix('XUL_BROWSER?url=') +
3654 window.encodeURIComponent(
3655 xulG.url_prefix('EG_WEB_BASE' + dupe_path)
3659 {tab_name: '', browser:false},
3662 show_nav_buttons : true,
3663 show_print_button : true,
3670 link.onclick = function() {
3671 window.open(oilsBasePath + dupe_path, '_blank').focus();
3676 acqLitCreatePoSubmit.attr('disabled', false);
3682 if (!this.createPoAgencySelector) {
3683 var widget = new openils.widget.AutoFieldWidget({
3684 "fmField": "ordering_agency",
3686 "parentNode": dojo.byId("acq-lit-po-agency"),
3687 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3689 widget.build(function(w) {
3690 self.createPoAgencySelector = w;
3691 dojo.connect(w, 'onChange', self.createPoCheckDupes);
3695 if (!this.createPoNameInput) {
3696 var widget = new openils.widget.AutoFieldWidget({
3699 "parentNode": dojo.byId("acq-lit-po-name"),
3700 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3702 widget.build(function(w) {
3703 self.createPoNameInput = w;
3704 dojo.connect(w, 'onChange', self.createPoCheckDupes);
3709 this.showRealCopyEditUI = function(li) {
3714 this._fetchLineitem(li.id(),
3716 li = self.liCache[li.id()] = fullLi;
3720 id : li.lineitem_details().map(
3721 function(item) { return item.eg_copy_id() }
3725 oncomplete : function(r) {
3727 var r_list = openils.Util.readResponse( r );
3728 for (var i = 0; i < r_list.length; i++) {
3729 var copy = r_list[i];
3730 var volId = copy.call_number();
3731 var volume = self.volCache[volId];
3733 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
3735 copy.call_number(volume);
3736 copyList.push(copy);
3739 xulG.volume_item_creator( { 'existing_copies' : copyList } );
3742 alert('error in oncomplete: ' + E);
3751 this.drawBibFinder = function(li) {
3754 var liWrapper = new openils.acq.Lineitem({lineitem:li});
3757 ['isbn', 'upc', 'issn', 'title', 'author'],
3759 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
3761 if(field == 'title' || field == 'author') {
3762 query += field +':' + val + ' ';
3764 query += 'identifier|' + field + ':' + val + ' ';
3770 if(openils.XUL.isXUL() && !window.IAMBROWSER) {
3772 oilsBasePath + '/acq/lineitem/findbib?query=' + encodeURIComponent(query),
3773 '', 'resizable,scrollbars=1,chrome');
3775 win = window.open( oilsBasePath + '/acq/lineitem/findbib?query=' + encodeURIComponent(query));
3779 win.window.recordFound = function(bibId) {
3782 var attrs = li.attributes();
3783 li.attributes(null);
3784 li.eg_bib_id(bibId);
3786 fieldmapper.standardRequest(
3787 ["open-ils.acq", "open-ils.acq.lineitem.update"],
3789 "params": [openils.User.authtoken, li],
3791 "oncomplete": function(r) {
3792 if(openils.Util.readResponse(r)) {
3793 location.href = location.href;