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'};
34 function nodeByName(name, context) {
35 return dojo.query('[name='+name+']', context)[0];
38 // for caching linked users. e.g. lineitem_detail.receiver
41 var liDetailBatchFields = ['fund', 'owning_lib', 'location', 'collection_code', 'circ_modifier', 'cn_label'];
42 var liDetailFields = liDetailBatchFields.concat(['barcode', 'note']);
44 "stop": "color: #c00; font-weight: bold;",
45 "warning": "color: #c93;"
49 * We're not using 'approved' today, but there is API support for it.
50 * I believe it's been replaced by "order-ready".
51 * LIs go new => selector-ready => order-ready/approved => pending-order =>
52 * on-order => received. 'cancelled' can pop up anywhere.
55 var li_pre_po_states = ["new", "selector-ready", "order-ready", "approved"];
56 var li_post_po_states = ["pending-order", "on-order", "received", "cancelled"];
57 var li_active_states = li_pre_po_states.concat(li_post_po_states);
59 function AcqLiTable() {
66 this.haveFundClass = {}
67 this.fundBalanceState = {};
68 this.realDfaCache = {};
69 this.virtDfaCounts = {};
72 this.claimEligibleLidByLi = {};
73 this.claimEligibleLid = {};
74 this.toggleState = false;
75 this.tbody = dojo.byId('acq-lit-tbody');
78 this.authtoken = openils.User.authtoken;
79 this.pcrud = new openils.PermaCrud();
80 this.rowTemplate = this.tbody.removeChild(dojo.byId('acq-lit-row'));
81 this.copyTbody = dojo.byId('acq-lit-li-details-tbody');
82 this.copyRow = this.copyTbody.removeChild(dojo.byId('acq-lit-li-details-row'));
83 this.copyBatchRow = dojo.byId('acq-lit-li-details-batch-row');
84 this.copyBatchWidgets = {};
85 this.liNotesTbody = dojo.byId('acq-lit-notes-tbody');
86 this.liNotesRow = this.liNotesTbody.removeChild(dojo.byId('acq-lit-notes-row'));
87 this.realCopiesTbody = dojo.byId('acq-lit-real-copies-tbody');
88 this.realCopiesRow = this.realCopiesTbody.removeChild(dojo.byId('acq-lit-real-copies-row'));
89 this._copy_fields_for_acqdf = ['owning_lib', 'location', 'fund', 'circ_modifier', 'collection_code'];
90 this.skipInitialEligibilityCheck = false;
91 this.claimDialog = new ClaimDialogManager(
92 liClaimDialog, finalClaimDialog, this.claimEligibleLidByLi,
93 function(li) { /* callback that fires when claims are made */
94 self.fetchClaimInfo(li.id(), /* force update */ true);
97 this.vlAgent = new VLAgent();
99 if (dojo.byId('acq-lit-apply-idents')) {
100 dojo.byId('acq-lit-apply-idents').onclick = function() {
101 self.applyOrderIdentValues();
105 this.focusLineitem = new openils.CGI().param('focus_li');
107 // capture the inline copy display wrapper and row template
108 this.inlineCopyContainer =
109 this.tbody.removeChild(dojo.byId('acq-inline-copies-row'));
111 '[name=acq-li-inline-copies-tbody]', this.inlineCopyContainer)[0];
112 this.inlineCopyTemplate = tb.removeChild(
113 dojo.query('[name=acq-li-inline-copies-template]', tb)[0]);
114 this.inlineNoCopies = tb.removeChild(
115 dojo.query('[name=acq-li-inline-copies-none]', tb)[0]);
117 // list of LI IDs that should be refreshed at next display time
118 this.inlineCopiesNeedingRefresh = [];
120 dojo.byId("acq-lit-li-actions-selector").onchange = function() {
121 self.applySelectedLiAction(this.options[this.selectedIndex].value);
122 this.selectedIndex = 0;
125 acqLitCreatePoCancel.onClick = function() {
126 acqLitPoCreateDialog.hide();
128 acqLitCreatePoSubmit.onClick = function() {
129 if (!self.createPoProviderSelector.attr("value") ||
130 !self.createPoAgencySelector.attr("value")) {
131 alert(localeStrings.CREATE_PO_INVALID);
133 } else if (self._confirmPoPrepaySituation()) {
134 acqLitPoCreateDialog.hide();
135 self._createPO(acqLitPoCreateDialog.getValues());
141 acqLitSavePlButton.onClick = function() {
142 acqLitSavePlDialog.hide();
143 self._savePl(acqLitSavePlDialog.getValues());
146 acqLitCancelLiStateButton.onClick = function() {
147 acqLitChangeLiStateDialog.hide();
149 acqLitSaveLiStateButton.onClick = function() {
150 acqLitChangeLiStateDialog.hide();
151 var state = acqLitChangeLiStateDialog.attr('state');
152 var state_filter = ['new'];
153 if (state == 'order-ready')
154 state_filter.push('selector-ready');
156 acqLitChangeLiStateDialog.getValues(), state, state_filter);
160 dojo.byId('acq-lit-select-toggle').onclick = function(){self.toggleSelect()};
161 dojo.byId('acq-inline-copies-toggle').onclick = function(){self.toggleInlineCopies()};
162 dojo.byId('acq-lit-info-back-button').onclick = function(){self.show('list')};
163 dojo.byId('acq-lit-copies-back-button').onclick = function(){self.show('list')};
164 dojo.byId('acq-lit-notes-back-button').onclick = function(){self.show('list')};
165 dojo.byId('acq-lit-real-copies-back-button').onclick = function(){self.show('list')};
167 this.setFundSearchFilter = function(callback) {
168 new openils.User().getPermOrgList(
169 ['CREATE_PURCHASE_ORDER', 'MANAGE_FUND'],
171 fundSearchFilter.org = orgs;
172 if (callback) callback();
174 true, true // descendants, id_list
178 this.afwCopyFieldArgs = function(field, perms) {
182 "labelFormat": (field == 'fund') ? fundLabelFormat : null,
183 "searchFormat": (field == 'fund') ? fundSearchFormat : null,
184 "searchFilter": (field == 'fund') ? fundSearchFilter : null,
185 "orgLimitPerms": [perms],
188 "labelType": (field == "fund") ? "html" : null
190 "noCache": (field == "fund"),
195 /* This is the "new" batch updater that sits atop all lineitems. It does
196 * use this.afwCopyFieldArgs() to borrow a little common code from the
197 * "old" batch updater atop the copy details view. */
198 this.initBatchUpdater = function(disabled_fields) {
199 openils.Util.show("acq-batch-update", "table");
201 if (!dojo.isArray(disabled_fields)) disabled_fields = [];
203 /* Note that this will directly contain dijits, not the AutoWidget
205 this.batchUpdateWidgets = {};
207 this.batchUpdateWidgets.item_count = new dijit.form.TextBox(
209 "style": {"width": "3em"},
211 dojo.indexOf(disabled_fields, "item_count") != -1
217 (new openils.widget.AutoFieldWidget({
219 "selfReference": true,
220 "dijitArgs": { "required": false },
222 "parentNode": "acq-bu-distribution_formula"
225 dojo.style(w.domNode, {"width": "12em"});
226 /* dijitArgs to AutoFieldWidget won't work for 'disabled' */
229 dojo.indexOf(disabled_fields, "distribution_formula") != -1
231 self.batchUpdateWidgets.distribution_formula = w;
235 function buildOneBatchWidget(field, args) {
236 (new openils.widget.AutoFieldWidget(args)).build(
238 if (field == "fund") {
240 w, "onChange", function(val) {
241 self._updateFundSelectorStyle(aw, val);
245 self._ensureCSSFundClasses(w.store);
248 dojo.style(w.domNode, {"width": "10em"});
251 dojo.indexOf(disabled_fields, field) != -1
253 self.batchUpdateWidgets[field] = w;
259 ["owning_lib","location","collection_code","circ_modifier","fund"],
261 var args = self.afwCopyFieldArgs(field,"CREATE_PURCHASE_ORDER");
262 args.parentNode = dojo.byId("acq-bu-" + field);
264 if (field == 'fund') {
265 // The list of funds can be huge. Before fetching
266 // funds for PO modification, see where the user has
267 // perms and limit the retreived funds accordingly.
268 // Note: This is the first instance of fund list
269 // retrieval. All future fund list retrievals will
270 // benefit directly from having applied the fund
271 // search filter org units here.
272 self.setFundSearchFilter(function() {
273 buildOneBatchWidget(field, args);
278 buildOneBatchWidget(field, args);
282 acqBatchUpdateApply.onClick = function() {
283 var li_id_list = self.getSelected(false, null, true /* id list */);
284 if (!li_id_list.length) {
285 alert(localeStrings.NO_LI_TO_UPDATE);
289 progressDialog.show(true);
290 progressDialog.attr("title", localeStrings.LI_BATCH_UPDATE);
291 progressDialog.update({"maximum": li_id_list.length,"progress": 0});
295 var params = [ self.authtoken, {"lineitems": li_id_list},
296 self.batchUpdateChanges(), self.batchUpdateFormula() ];
297 console.log("batch update params: " + dojo.toJson(params));
299 fieldmapper.standardRequest(
300 ["open-ils.acq", "open-ils.acq.lineitem.batch_update"], {
303 "onresponse": function(r) {
304 if ((r = openils.Util.readResponse(r))) { // assignment
305 progressDialog.update({"progress": ++count});
307 progressDialog.hide();
308 progressDialog.attr("title", "");
311 "oncomplete": function() {
312 /* XXX Is the last call to onresponse guaranteed to
313 * finish before oncomplete is fired? */
314 if (count != li_id_list.length) {
315 console.error("lineitem batch update operation failed");
316 progressDialog.hide();
317 progressDialog.attr("title", "");
319 location.href = location.href;
327 this.batchUpdateChanges = function() {
331 openils.Util.objectProperties(this.batchUpdateWidgets),
333 if (k == "distribution_formula") return; /* handled elsewhere */
334 if (self.batchUpdateWidgets[k].attr("disabled")) return;
336 /* It's important that a value of "" should mean that a field
337 * doesn't get used in the arguments to the batch updater API,
338 * but 0 should mean an actual 0. */
339 var value = self.batchUpdateWidgets[k].attr("value");
348 this.batchUpdateFormula = function() {
349 if (this.batchUpdateWidgets.distribution_formula.attr("disabled")) {
353 this.batchUpdateWidgets.distribution_formula.attr("value") ||
359 this.reset = function(keep_selectors) {
360 while(self.tbody.childNodes[0])
361 self.tbody.removeChild(self.tbody.childNodes[0]);
369 this.setNext = function(handler) {
370 var link = dojo.byId('acq-lit-next');
372 dojo.style(link, 'visibility', 'visible');
373 link.onclick = handler;
375 dojo.style(link, 'visibility', 'hidden');
379 this.setPrev = function(handler) {
380 var link = dojo.byId('acq-lit-prev');
382 dojo.style(link, 'visibility', 'visible');
383 link.onclick = handler;
385 dojo.style(link, 'visibility', 'hidden');
389 this.enableActionsDropdownOptions = function(mask) {
390 /* 'mask' is probably a misnomer the way I'm using it, but it needs to
391 * be one of pl,po,ao,gs,vp, or fs. */
392 dojo.query("option", "acq-lit-li-actions-selector").forEach(
394 var opt_mask = dojo.attr(option, "mask");
396 /* For each <option> element, an empty or non-existent mask
397 * attribute, a mask attribute of "*", or a mask attribute that
398 * matches this method's argument should result in that
399 * option's being enabled. */
401 option, "disabled", !(
404 opt_mask.search(mask) != -1
412 * Ensures this.focusLineitem is in view and causes a brief
413 * border around the lineitem to come to life then fade.
415 this.focusLi = function() {
416 if (!this.focusLineitem) return;
418 // set during addLineitem()
419 var node = dojo.byId('li-title-ref-' + this.focusLineitem);
421 // LI may not yet be rendered
424 // prevent numerous re-focuses
425 this.focusLineitem = null;
427 // causes the full row to be visible
428 dijit.scrollIntoView(node);
431 dojo.query('[attr=title]', node)[0].focus();
433 dojo.require('dojox.fx');
437 dojox.fx.highlight({color : '#BB4433', node : node, duration : 2000}).play();
442 this.show = function(div) {
443 openils.Util.hide('acq-lit-table-div');
444 openils.Util.hide('acq-lit-info-div');
445 openils.Util.hide('acq-lit-li-details');
446 openils.Util.hide('acq-lit-notes-div');
447 openils.Util.hide('acq-lit-real-copies-div');
448 openils.Util.hide('acq-lit-asset-creator');
451 openils.Util.show('acq-lit-table-div');
453 this.refreshInlineCopies();
456 openils.Util.show('acq-lit-info-div');
459 openils.Util.show('acq-lit-li-details');
462 openils.Util.show('acq-lit-real-copies-div');
465 openils.Util.show('acq-lit-notes-div');
467 case 'asset-creator':
468 openils.Util.show('acq-lit-asset-creator');
472 openils.Util.show(div);
476 this.hide = function() {
480 this.toggleSelect = function() {
482 dojo.forEach(self.selectors, function(i){i.checked = false});
484 dojo.forEach(self.selectors, function(i){i.checked = true});
485 self.toggleState = !self.toggleState;
489 this.getAll = function(callback, id_only, state) {
490 /* For some uses of the li table, we may not really know about "all"
491 * the lineitems that the user thinks we know about. If we're a paged
492 * picklist, for example, we only know about the lineitems we've
493 * displayed, but not necessarily all the lineitems on the picklist.
494 * So we reach out to pcrud to inform us.
495 * state: string/array. only lineitems in one of these states are
496 * included in the final result set. Not currently supported for
500 var oncomplete = function(r) {
501 var id_list = openils.Util.readResponse(r);
505 self.fetchLineitemsById(id_list, callback);
509 var search = {"picklist": this.isPL};
510 if (state) search.state = state;
513 "id_list": true, /* sic, even if id_only */
515 "oncomplete": oncomplete
519 } else if (this.isPO) {
520 var search = {"purchase_order": this.isPO};
521 if (state) search.state = state;
526 "oncomplete": oncomplete
530 } else if (this.isUni && this.pager) {
531 this.pager.getAllLineitemIDs(oncomplete);
535 /* If execution reaches this point, we don't need or can't perform
536 * any special tricks to find out the "real" list of "all" lineitems
537 * in this context, so we fall back to the old method.
539 callback(this.getSelected(true, null, id_only, state));
542 /** @param all If true, assume all are selected */
543 this.getSelected = function(
545 callback /* If you want a "good" idea of "all" lineitems, you must
546 provide a callback that accepts an array parameter, rather than
547 relying on the return value of this method itself. */,
551 console.log("getSelected states = " + state);
553 return this.getAll(callback, id_only, state);
555 var indices = {}; /* use to uniqify. needed in paging situations. */
556 dojo.forEach(this.selectors,
559 indices[i.parentNode.parentNode.getAttribute('li')] = true;
563 var result = openils.Util.objectProperties(indices);
565 // caller provided a lineitem state filter. remove IDs for lineitems
566 // not in the selected state.
569 if (!dojo.isArray(state)) state = [state];
570 dojo.forEach(result, function(liId) {
571 console.log('filter LI state ' + self.liCache[liId].state());
572 if (state.indexOf(self.liCache[liId].state()) >= 0)
579 result = result.map(function(liId) { return self.liCache[liId]; });
587 this.setRowAttr = function(td, liWrapper, field, type) {
588 var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
589 td.appendChild(document.createTextNode(val));
592 this.setClaimPolicyControl = function(li, row) {
593 if (!self._claimPolicyPickerLoading) {
594 self._claimPolicyPickerLoading = true;
596 new openils.widget.AutoFieldWidget({
597 "parentNode": "acq-lit-li-claim-policy",
599 "selfReference": true,
600 "dijitArgs": {"required": true}
602 function(w) { self.claimPolicyPicker = w; }
606 /* dojox.timing.doLater() is the best thing ever. Resource not yet
607 * ready? Just repeat my whole method when it is. */
608 if (dojox.timing.doLater(self.claimPolicyPicker)) {
612 row = self._findLiRow(li);
614 if (li.claim_policy()) {
615 /* This Dojo data dance is necessary to get a whole fieldmapper
616 * object based on a claim policy ID, since we alreay have the
617 * widget thing loaded with all that data, and can thereby
618 * avoid another request to the server. */
619 self.claimPolicyPicker.store.fetchItemByIdentity({
620 "identity": li.claim_policy(),
621 "onItem": function(a) {
622 var policy = (new acqclp()).fromStoreItem(a);
623 var span = nodeByName("claim_policy", row);
624 var inner = nodeByName("claim_policy_name", row);
626 openils.Util.show(span, "inline");
627 inner.innerHTML = policy.name();
629 "onError": function(e) {
634 openils.Util.hide(nodeByName("claim_policy", row));
635 nodeByName("claim_policy_name", row).innerHTML = "";
640 this.fetchClaimInfo = function(liId, force, callback, row) {
642 liId, function(full) {
643 self.liCache[full.id()] = full;
644 self.checkClaimEligibility(full, callback, row);
649 // fetch an updated copy of the lineitem
650 // and add it back to the lineitem table
651 this.refreshLineitem = function(li, focus) {
653 this._fetchLineitem(li.id(),
656 self.focusLineitem = li.id();
658 self.focusLineitem = null;
660 var row = dojo.query('[li='+li.id()+']', self.tbody)[0];
661 var nextSibling = row.nextSibling;
662 self.tbody.removeChild(row);
663 self.addLineitem(newLi, false, nextSibling);
669 * Inserts a single lineitem into the growing table of lineitems
670 * @param {Object} li The lineitem object to insert
672 this.addLineitem = function(li, skip_final_placement, nextSibling) {
673 this.liCache[li.id()] = li;
675 // insert the row right away so that final order isn't
676 // dependent on how long subsequent async request take
677 // for a given line item
678 var row = self.rowTemplate.cloneNode(true);
679 if (!skip_final_placement) {
681 // either no nextSibling was provided or it was null
682 // meaning the row was already at the end of the table
683 self.tbody.appendChild(row);
685 self.tbody.insertBefore(row, nextSibling);
689 self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
691 // sort the lineitem notes on edit_time
692 if(!li.lineitem_notes()) li.lineitem_notes([]);
694 var liWrapper = new openils.acq.Lineitem({lineitem:li});
695 row.setAttribute('li', li.id());
696 var tds = dojo.query('[attr]', row);
697 dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
698 dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
700 // so we can scroll to it later
701 dojo.query('[name=bib-info-cell]', row)[0].id = 'li-title-ref-' + li.id();
704 liWrapper.findAttr("isbn", "lineitem_marc_attr_definition") ||
705 liWrapper.findAttr("upc", "lineitem_marc_attr_definition");
707 // XXX media prefix for added content
709 nodeByName("jacket", row).setAttribute(
710 "src", "/opac/extras/ac/jacket/small/" + identifier
714 nodeByName("liid", row).innerHTML += li.id();
717 openils.Util.show(nodeByName('catalog', row), 'inline');
718 nodeByName("catalog_link", row).onclick = this.generateMakeRecTab(li.eg_bib_id());
720 openils.Util.show(nodeByName('link_to_catalog', row), 'inline');
721 nodeByName("link_to_catalog_link", row).onclick = function() { self.drawBibFinder(li) };
724 if (li.queued_record()) {
725 this.pcrud.retrieve('vqbr', li.queued_record(),
727 oncomplete : function(r) {
728 var qrec = openils.Util.readResponse(r);
729 openils.Util.show(nodeByName('queue', row), 'inline');
730 var link = nodeByName("queue_link", row);
731 link.onclick = function() {
732 // open a new tab to the vandelay queue for this record
733 openils.XUL.newTabEasy(
734 oilsBasePath + '/vandelay/vandelay?qtype=bib&qid=' + qrec.queue()
742 nodeByName("worksheet_link", row).href =
743 oilsBasePath + "/acq/lineitem/worksheet/" + li.id() +
744 '?source=' + encodeURIComponent(location.pathname + location.search)
746 nodeByName("show_requests_link", row).href =
747 oilsBasePath + "/acq/picklist/user_request?lineitem=" + li.id() +
748 '?source=' + encodeURIComponent(location.pathname + location.search)
750 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
751 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
752 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
753 dojo.query('[name=expand_inline_copies]', row)[0].onclick =
754 function() {self.drawInlineCopies(li.id())};
756 this.drawOrderIdentSelector(li, row);
758 if (!this.skipInitialEligibilityCheck)
762 function(full) { self.setClaimPolicyControl(full, row) },
766 this.updateLiNotesCount(li, row);
768 // show which PO this lineitem is a member of
769 if(li.purchase_order() && !this.isPO) {
771 this.poCache[li.purchase_order()] =
772 this.poCache[li.purchase_order()] ||
773 fieldmapper.standardRequest(
774 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
776 this.authtoken, li.purchase_order(), {
777 "flesh_price_summary": true,
778 "flesh_provider" : true,
779 "flesh_lineitem_count": true
782 if(po && !this.isMeta) {
783 openils.Util.show(nodeByName('po', row), 'inline');
784 var link = nodeByName('po_link', row);
785 link.setAttribute('href', oilsBasePath +
786 '/acq/po/view/' + li.purchase_order() +
787 '?focus_li=' + li.id() +
788 '&source=' + encodeURIComponent(location.pathname + location.search)
790 link.innerHTML += po.name();
792 openils.Util.show(nodeByName('pro', row), 'inline');
793 link = nodeByName('pro_link', row);
794 link.setAttribute('href', oilsBasePath + '/conify/global/acq/provider/' + po.provider().id())
795 link.innerHTML += po.provider().code();
799 // show which picklist this lineitem is a member of
800 if(li.picklist() && (this.isPO || this.isMeta || this.isUni)) {
802 this.plCache[li.picklist()] =
803 this.plCache[li.picklist()] ||
804 fieldmapper.standardRequest(
805 ['open-ils.acq', 'open-ils.acq.picklist.retrieve.authoritative'],
806 {params: [this.authtoken, li.picklist()]});
808 if (pl.name() == "") {
809 openils.Util.show(nodeByName("bib_origin", row), "inline");
813 openils.Util.show(nodeByName('pl', row), 'inline');
814 var link = nodeByName('pl_link', row);
815 link.setAttribute('href', oilsBasePath +
816 '/acq/picklist/view/' + li.picklist() +
817 '?focus_li=' + li.id() +
818 '&source=' + encodeURIComponent(location.pathname + location.search)
820 link.innerHTML += pl.name();
825 var countNode = nodeByName('count', row);
826 var count = li.item_count() || 0;
827 if (typeof(this._copy_count_cb) == "function") {
828 this._copy_count_cb(li.id(), count);
830 countNode.innerHTML = count;
831 countNode.id = 'acq-lit-copy-count-label-' + li.id();
834 var priceInput = dojo.query('[name=price]', row)[0];
835 priceInput.value = li.estimated_unit_price() || '';
836 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
838 // show either "mark received" or "unreceive" as appropriate
839 this.updateLiState(li, row);
841 if (skip_final_placement) {
845 // the last LI may be rendered after the call to show('list'),
846 // so make sure it's focused if necessary.
847 if (this.focusLineitem == li.id())
851 this._liCountClaims = function(li) {
853 for (var i = 0; i < li.lineitem_details().length; i++)
854 total += li.lineitem_details()[i].claims().length;
858 this._findLiRow = function(li) {
859 return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
862 this.reconsiderClaimControl = function(li, row) {
863 if (!row) row = this._findLiRow(li);
864 var option = nodeByName("action_manage_claims", row);
865 var eligible = this.claimEligibleLidByLi[li.id()].length;
866 var count = this._liCountClaims(li);
868 option.disabled = !(count || eligible);
870 dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
871 option.onclick = function() { self.claimDialog.show(li); };
874 this.clearEligibility = function(li) {
875 this.claimEligibleLidByLi[li.id()] = [];
877 if (li.lineitem_details()) {
878 li.lineitem_details().forEach(
879 function(lid) { delete self.claimEligibleLid[lid.id()]; }
883 if (this.copyCache) {
885 for (var k in this.copyCache) {
886 if (this.copyCache[k].lineitem() == li.id())
890 function(k) { delete self.claimEligibleLid[k]; }
895 this.applyOrderIdentValues = function() {
896 this._identValuesInFlight =
897 openils.Util.objectProperties(this.liCache).length;
898 for (var liId in this.liCache) {
899 this._applyOrderIdentValue(this.liCache[liId]);
903 // returns true if request was sent
904 this._applyOrderIdentValue = function(li, oncomplete) {
907 console.log('applying ident value for lineitem ' + li.id());
910 var row = dojo.query('[li=' + li.id() + ']')[0];
912 // find the selected ident value
913 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
914 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
915 var name = typeSel.options[typeSel.selectedIndex].value;
916 var val = typeSel._cbox.attr('value');
918 console.log("selected ident is " + val);
920 // it differs from the existing ident value, update it
921 var oldIdent = self.getLiOrderIdent(li);
923 oldIdent.attr_name() == name &&
924 oldIdent.attr_value() == val) {
925 console.log('selected ident attr matches existing attr');
926 if (--this._identValuesInFlight == 0) {
927 if (oncomplete) oncomplete(li);
928 else location.href = location.href;
933 // see if the selected ident value is represented
934 // by an existing lineitem attr
937 typeSel._cbox.store.fetch({
938 query : {attr_value : val},
939 onItem : function(item) {
940 console.log('found existing attr for ident value');
941 args.source_attr_id = li.attributes().filter(
942 function(attr) { return attr.id() == item.id[0] }
948 if (!args.source_attr_id) {
949 // user entered new text in the combobox
950 // so we need to create a new attr
951 console.log('creating new ident attr');
952 args.lineitem_id = li.id();
953 args.attr_name = name;
954 args.attr_value = val;
957 fieldmapper.standardRequest(
958 ['open-ils.acq', 'open-ils.acq.lineitem.order_identifier.set'],
960 params : [openils.User.authtoken, args],
961 oncomplete : function() {
962 console.log('order_ident oncomplete');
963 if (--self._identValuesInFlight == 0) {
964 if (oncomplete) oncomplete(li);
965 else location.href = location.href;
967 console.log(self._identValuesInFlight + ' still in flight');
975 this.getLiOrderIdent = function(li) {
976 var attrs = li.attributes();
977 if (!attrs) return null;
981 attr.attr_type() == 'lineitem_local_attr_definition' &&
982 openils.Util.isTrue(attr.order_ident())
988 this.drawOrderIdentSelector = function(li, row) {
990 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
991 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
993 var attrs = li.attributes();
995 // limit to MARC attr defs
996 attrs = attrs.filter(
998 return (attr.attr_type() == 'lineitem_marc_attr_definition');
1002 var identAttr = this.getLiOrderIdent(li);
1005 // collect the values for each type of identifier
1006 // find a reasonable default identifier type to render
1010 dojo.forEach(['isbn', 'upc', 'issn'],
1013 // collect the values for this attr name
1014 values[name] = attrs.filter(
1016 return (attr.attr_name() == name)
1020 // select a reasonable default name in the type-selector
1024 if (identAttr.attr_name() == name)
1026 } else if (values[name].length) {
1031 dojo.forEach(typeSel.options, function(opt) {
1032 if (opt.value == name) {
1033 opt.selected = true;
1042 function updateOrderIdent(val) {
1043 self._identValuesInFlight = 1;
1044 self._applyOrderIdentValue(
1047 self.refreshLineitem(li);
1052 // replace the ident combobox with a new
1053 // one for the selected ident type
1054 function changeComboBox(sel) {
1055 var name = sel.options[sel.selectedIndex].value;
1057 var td = dojo.query('[name=order_ident_value]', row)[0];
1058 if (td.childNodes[0])
1059 dojo.destroy(td.childNodes[0]);
1061 var store = new dojo.data.ItemFileWriteStore({
1062 data : acqlia.toStoreData(values[name])
1065 var cbox = new dijit.form.ComboBox(
1067 labelAttr : 'attr_value',
1068 searchAttr : 'attr_value'
1070 dojo.create('div', {}, td)
1075 // set the value for the cbox
1076 if (values[name].length) {
1077 var orderIdent = self.getLiOrderIdent(li);
1079 if (orderIdent && orderIdent.attr_name() == name) {
1080 cbox.attr('value', orderIdent.attr_value());
1082 cbox.attr('value', values[name][0].attr_value());
1086 if (!self.orderIdentAllowed)
1087 cbox.attr('disabled', true);
1090 cbox._lineitem = li;
1091 dojo.connect(cbox, 'onChange', updateOrderIdent);
1094 changeComboBox(typeSel); // force the initial draw
1095 typeSel.onchange = function() {changeComboBox(typeSel)};
1098 this.testOrderIdentPerms = function(org, callback) {
1100 new openils.User().getPermOrgList(
1101 'ACQ_SET_LINEITEM_IDENTIFIER',
1103 console.log('found orgs = ' + orgs);
1104 for (var i = 0; i < orgs.length; i++) {
1105 if (Number(orgs[i]) == Number(org)) {
1106 self.orderIdentAllowed = true;
1107 if (callback) callback();
1111 if (callback) callback();
1117 this.checkClaimEligibility = function(li, callback, row) {
1118 /* Assume always eligible, i.e. from this interface we don't care about
1119 * claim eligibility any more. this is where the user would force a
1121 this.clearEligibility(li);
1122 this.claimEligibleLidByLi[li.id()] = li.lineitem_details().map(
1123 function(lid) { return lid.id(); }
1125 li.lineitem_details().forEach(
1126 function(lid) { self.claimEligibleLid[lid.id()] = true; }
1128 this.reconsiderClaimControl(li, row);
1129 if (callback) callback(li);
1131 this.clearEligibility(li);
1132 fieldmapper.standardRequest(
1133 ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
1134 "params": [openils.User.authtoken, {"lineitem": li.id()}],
1136 "onresponse": function(r) {
1137 if (r = openils.Util.readResponse(r)) {
1138 self.claimEligibleLidByLi[li.id()].push(
1141 self.claimEligibleLid[r.lineitem_detail()] = true;
1144 "oncomplete": function() {
1145 self.reconsiderClaimControl(li, row);
1146 if (typeof(callback) == "function")
1154 this.updateLiNotesCount = function(li, row) {
1155 if (!row) row = this._findLiRow(li);
1157 var has_notes = (li.lineitem_notes().filter(
1158 function(o) { return Boolean (o.alert_text()); }
1161 /* U+2691 is the code point for a filled-in flag character */
1162 nodeByName("notes_alert_flag", row).innerHTML =
1163 has_notes ? "⚑" : "";
1164 nodeByName("noteslink", row).style.fontStyle =
1165 has_notes ? "italic" : "normal";
1166 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
1169 /* XXX NOT related to _updateLiState(). rethink */
1170 this.updateLiState = function(li, row) {
1171 if (!row) row = this._findLiRow(li);
1173 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
1174 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
1176 // always allow access to LI history
1177 nodeByName('action_view_history', row).onclick =
1178 function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
1180 /* handle row coloring for based on LI state */
1181 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1182 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
1184 // Expose invoice actions for any lineitem that is linked to a PO
1185 if (li.purchase_order()) {
1186 openils.Util.show(nodeByName("invoices_span", row), "inline");
1187 var link = nodeByName("invoices_link", row);
1188 link.onclick = function() {
1189 openils.XUL.newTabEasy(
1190 oilsBasePath + "/acq/search/unified?so=" +
1191 base64Encode({"jub":[{"id": li.id()}]}) + "&rt=invoice"
1199 * If we haven't fleshed the lineitem_details, default to allowing access to the
1200 * holdings maintenence actions. The alternative is to flesh LIDs on every lineitem,
1201 * but that will add to page render time. Let's see if this will suffice...
1203 var lids = li.lineitem_details();
1205 (lids && !lids.filter(function(lid) { return lid.eg_copy_id() })[0] )) {
1207 actUpdateBarcodes.disabled = false;
1208 actUpdateBarcodes.onclick = function() {
1209 self.showRealCopyEditUI(li);
1210 nodeByName("action_none", row).selected = true;
1212 actHoldingsMaint.disabled = false;
1213 actHoldingsMaint.onclick =
1214 self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
1217 var state_cell = nodeByName("li_state_" + li.state(), row);
1219 // re-hide any state label nodes which may have been un-hidden
1220 // through previous actions.
1221 dojo.query('[state-label]', row).forEach(function(node) {
1222 openils.Util.hide(node)
1225 if (li.state() == 'cancelled') {
1226 if(typeof li.cancel_reason() == "object") {
1228 // clear the stock "Canceled" label, since we have more
1229 // information to replace it with.
1230 state_cell.innerHTML = '';
1232 var holds_state = dojo.create(
1234 "style": "border-bottom: 1px dashed #000;",
1235 "innerHTML": li.cancel_reason().label()
1236 }, state_cell, "only"
1240 "label": "<em>" + li.cancel_reason().label() +
1241 "</em><br />" + li.cancel_reason().description(),
1242 "connectId": [holds_state]
1243 }, dojo.create("span", null, state_cell, "last")
1246 if (li.cancel_reason().keep_debits() == 't') {
1247 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1248 openils.Util.addCSSClass(row, "oils-acq-li-state-delayed");
1251 console.log('li cancel_reason is un-fleshed. Please fix');
1255 openils.Util.show(state_cell);
1259 this._setAlertStore = function() {
1260 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
1262 "data": acqliat.toStoreData(
1265 "owning_lib": aou.orgNodeTrail(
1266 aou.findOrgUnit(openils.User.user.ws_ou())
1267 ).map(function(o) { return o.id(); })
1273 acqLitAlertAlertText.setValue(); /* make the store "live" */
1274 acqLitAlertAlertText._store_ready = true;
1278 * Draws and shows the lineitem notes pane
1280 this.drawLiNotes = function(li) {
1282 this.focusLineitem = li.id();
1284 if (!acqLitAlertAlertText._store_ready)
1285 this._setAlertStore();
1288 li.lineitem_notes().sort(
1290 if(a.edit_time() < b.edit_time()) return 1;
1296 while(this.liNotesTbody.childNodes[0])
1297 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
1300 acqLitCreateNoteSubmit.onClick = function() {
1301 var value = acqLitCreateNoteText.attr('value');
1303 var note = new fieldmapper.acqlin();
1306 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
1309 note.lineitem(li.id());
1311 self.updateLiNotes(li, note);
1312 acqLitCreateNoteVendorPublic.attr("checked", false);
1313 acqLitCreateNoteText.attr("value", "");
1316 acqLitCreateAlertSubmit.onClick = function() {
1317 if (!acqLitAlertAlertText.item) {
1318 alert(localeStrings.ALERT_UNSELECTED);
1322 var alert_text = new fieldmapper.acqliat().fromStoreItem(
1323 acqLitAlertAlertText.item
1325 var value = acqLitAlertNoteValue.attr("value") || "";
1327 var note = new fieldmapper.acqlin();
1329 note.lineitem(li.id());
1331 note.alert_text(alert_text);
1333 self.updateLiNotes(li, note);
1336 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
1340 * Draws a single lineitem note in the notes pane
1342 this.addLiNote = function(li, note) {
1343 if(note.isdeleted()) return;
1345 var row = self.liNotesRow.cloneNode(true);
1346 nodeByName("value", row).innerHTML = note.value();
1347 var alert_node = nodeByName("alert_code", row);
1348 if (note.alert_text()) {
1349 alert_node.innerHTML = dojo.string.substitute(
1351 aou.findOrgUnit(note.alert_text().owning_lib()).shortname(),
1352 note.alert_text().code()
1355 if (note.alert_text().description()) {
1358 "connectId": [alert_node],
1359 "label": note.alert_text().description()
1360 }, dojo.create("span", null, alert_node, "after")
1365 if (openils.Util.isTrue(note.vendor_public()))
1366 nodeByName("vendor_public", row).innerHTML =
1367 localeStrings.VENDOR_PUBLIC;
1369 nodeByName("delete", row).onclick = function() {
1370 note.isdeleted(true);
1371 self.liNotesTbody.removeChild(row);
1372 self.updateLiNotes(li);
1375 if(note.edit_time()) {
1376 nodeByName("edit_time", row).innerHTML =
1377 dojo.date.locale.format(
1378 dojo.date.stamp.fromISOString(note.edit_time()),
1379 {formatLength:'short'});
1382 self.liNotesTbody.appendChild(row);
1386 * Updates any new/changed/deleted notes on the server
1388 this.updateLiNotes = function(li, newNote) {
1394 notes = li.lineitem_notes().filter(
1396 if(note.ischanged() || note.isnew() || note.isdeleted())
1402 if(notes.length == 0) return;
1403 progressDialog.show();
1405 fieldmapper.standardRequest(
1406 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
1408 params : [this.authtoken, notes],
1409 onresponse : function(r) {
1410 var resp = openils.Util.readResponse(r);
1415 // remove the old changed notes
1417 dojo.forEach(li.lineitem_notes(),
1419 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
1423 li.lineitem_notes(list);
1426 progressDialog.hide();
1427 self.updateLiNotesCount(li);
1428 self.drawLiNotes(li);
1432 progressDialog.update(resp);
1433 var newnote = resp.note;
1435 if(!newnote.isdeleted()) {
1436 newnote.isnew(false);
1437 newnote.ischanged(false);
1438 li.lineitem_notes().push(newnote);
1445 this.updateLiPrice = function(input, li) {
1447 var price = input.value;
1448 if(Number(price) == Number(li.estimated_unit_price())) return;
1450 fieldmapper.standardRequest(
1451 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
1452 { async : false, // redundant w/ timeout
1454 params : [this.authtoken, li.id(), price],
1455 oncomplete : function(r) {
1456 openils.Util.readResponse(r);
1457 li.estimated_unit_price(price); // update local copy
1460 * If this is a PO and every visible lineitem has a price,
1461 * check again to see if this PO can be activated. Note that
1462 * every visible lineitem having a price does not guarantee it can
1463 * be activated, which is why we still make the call. Having a price
1464 * set for every visiable lineitem is just the lowest barrier to entry.
1467 var priceNodes = dojo.query('[name=price]', dojo.byId('acq-lit-tbody'));
1469 dojo.forEach(priceNodes, function(node) { if (node.value == '') allSet = false});
1470 if (allSet) checkCouldActivatePo();
1477 this.removeLineitem = function(liId) {
1478 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
1479 delete this.liCache[liId];
1480 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
1483 this.drawInfo = function(liId) {
1484 this.focusLineitem = liId;
1485 if (!this._isRelatedViewer) {
1486 var d = dojo.byId("acq-lit-info-related");
1487 if (!this.relCache[liId]) {
1488 fieldmapper.standardRequest(
1491 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
1494 "params": [openils.User.authtoken, liId],
1495 "onresponse": function(r) {
1496 self.relCache[liId] = openils.Util.readResponse(r);
1497 nodeByName("related_number", d).innerHTML =
1498 self.relCache[liId];
1500 self.relCache[liId] >1 ? "show" : "hide"
1506 nodeByName("related_number", d).innerHTML = this.relCache[liId];
1507 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
1512 openils.acq.Lineitem.fetchAttrDefs(
1514 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
1519 this.toggleInlineCopies = function() {
1520 // if any inline copies are not displayed,
1521 // display them all otherwise, hide them all.
1523 var displayAll = false;
1525 for (var liId in this.liCache) {
1526 if (!this.inlineCopiesVisible(liId)) {
1532 for (var liId in this.liCache) {
1533 var row = dojo.byId('acq-inline-copies-row-' + liId);
1535 if (!row || row._hidden) {
1536 this.drawInlineCopies(liId);
1538 } else { // hide all
1540 // drawInlineCopies() on a visible row will hide it.
1541 this.drawInlineCopies(liId);
1548 this.inlineCopiesVisible = function(liId) {
1549 var row = dojo.byId('acq-inline-copies-row-' + liId);
1550 return (row && !row._hidden);
1553 this.refreshInlineCopies = function(all, reFetch) {
1555 var liIds = this.inlineCopiesNeedingRefresh;
1556 if (all) liIds = openils.Util.objectProperties(liCache);
1557 liIds.forEach(function(liId) {
1558 if (self.inlineCopiesVisible(liId)) {
1559 self.drawInlineCopies(liId, reFetch); // hide
1560 self.drawInlineCopies(liId, reFetch); // re-draw
1565 // draw inline copy table. if the table is
1566 // already visible, hide the table as-is
1567 // reFetch forces a retrieval of the lineitem and
1568 // copies from the server. otherwise the locally
1569 // cached version of each is used.
1570 this.drawInlineCopies = function(liId, reFetch) {
1573 // find or create the row where the inline copies table will live
1574 var containerRow = dojo.byId('acq-inline-copies-row-' + liId);
1575 var liRow = dojo.query('[li=' + liId + ']')[0];
1577 if (!containerRow) {
1579 // build the inline copies container row and add it to
1580 // the DOM directly after the primary lineitem row
1582 containerRow = self.inlineCopyContainer.cloneNode(true);
1583 containerRow.id = 'acq-inline-copies-row-' + liId;
1585 if (liRow.nextSibling) {
1586 self.tbody.insertBefore(containerRow, liRow.nextSibling);
1588 self.tbody.appendChild(containerRow);
1593 // toggle the visible state
1594 containerRow._hidden = !containerRow._hidden;
1595 openils.Util.toggle(containerRow, 'table-row');
1597 if (containerRow._hidden) return; // hide only
1600 var handler = function(li) {
1602 var tbody = dojo.query(
1603 '[name=acq-li-inline-copies-tbody]',
1606 // reset the table before adding copy rows
1607 while (tbody.childNodes[0])
1608 tbody.removeChild(tbody.childNodes[0]);
1610 if(li.lineitem_details().length == 0) {
1612 self.inlineNoCopies.cloneNode(true));
1613 return; // no copies to show
1616 // add a row to the inline copy table for each copy
1617 dojo.forEach(li.lineitem_details(),
1619 var row = self.inlineCopyTemplate.cloneNode(true);
1620 tbody.appendChild(row);
1621 self.addInlineCopy(li, copy, row);
1626 this._fetchLineitem(liId, handler, reFetch);
1629 /** Draw read-only copy widgets for inline copies */
1630 this.addInlineCopy = function(li, copy, row) {
1633 dojo.forEach(liDetailFields,
1636 var widget = new openils.widget.AutoFieldWidget({
1639 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1640 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1641 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1643 parentNode : dojo.query('[name=' + field + ']', row)[0],
1652 /* For a given list of lineitem ids, build a list of full lineitems
1653 * re-using the fetching logic that is otherwise typical to use in this
1656 * If we've already got a lineitem in the cache, just use that.
1658 * Once we've built a list of lineitems, call callback(thatlist).
1660 this.fetchLineitemsById = function(id_list, callback) {
1661 var total = id_list.length;
1662 var result_list = [];
1664 var inner = function(li) {
1665 result_list.push(li)
1667 callback(result_list);
1670 id_list.forEach(function(id) { self._fetchLineitem(id, inner); });
1673 this._fetchLineitem = function(liId, handler, force) {
1675 var li = this.liCache[liId];
1676 if(li && li.marc() && li.lineitem_details() && !force)
1679 fieldmapper.standardRequest(
1680 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
1683 params: [self.authtoken, liId, {
1685 flesh_cancel_reason: true,
1686 flesh_li_details: true,
1688 flesh_fund_debit: true }],
1690 oncomplete: function(r) {
1691 var li = openils.Util.readResponse(r);
1692 self.liCache[liId] = li;
1699 this._drawInfo = function(li) {
1701 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
1703 if(li.eg_bib_id()) {
1704 openils.Util.hide('acq-lit-marc-order-record-label');
1705 openils.Util.hide(acqLitEditOrderMarc.domNode);
1706 openils.Util.show('acq-lit-marc-real-record-label');
1708 openils.Util.show('acq-lit-marc-order-record-label');
1709 openils.Util.show(acqLitEditOrderMarc.domNode);
1710 openils.Util.hide('acq-lit-marc-real-record-label');
1713 this.drawMarcHTML(li);
1714 this.infoTbody = dojo.byId('acq-lit-info-tbody');
1717 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
1718 while(this.infoTbody.childNodes[0])
1719 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
1721 for(var i = 0; i < li.attributes().length; i++) {
1722 var attr = li.attributes()[i];
1723 var row = this.infoRow.cloneNode(true);
1725 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
1726 var name = openils.acq.Lineitem.attrDefs[type].filter(
1728 return (a.code() == attr.attr_name());
1730 ).pop().description();
1732 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
1733 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
1734 this.infoTbody.appendChild(row);
1737 if (!this._isRelatedViewer) {
1738 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
1739 oilsBasePath + "/acq/lineitem/related/" + li.id();
1742 // if a top scroll point is defined, jump up to it here
1743 var node = dojo.byId('oils-scroll-to-top');
1744 if (node) dijit.scrollIntoView(node);
1747 this.generateMakeRecTab = function(bib_id,default_view, row) {
1751 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
1754 show_nav_buttons : true,
1755 show_print_button : true,
1756 opac_url : xulG.url_prefix('opac_rdetail|' + bib_id),
1757 default_view : default_view
1761 if(row) nodeByName("action_none", row).selected = true;
1765 this.drawMarcHTML = function(li) {
1766 var params = [null, true, li.marc()];
1768 params = [li.eg_bib_id(), true];
1770 fieldmapper.standardRequest(
1771 ['open-ils.search', 'open-ils.search.biblio.record.html'],
1774 oncomplete: function(r) {
1775 dojo.byId('acq-lit-marc-div').innerHTML =
1776 openils.Util.readResponse(r);
1782 this.drawCopies = function(liId, force_fetch) {
1783 this.focusLineitem = liId;
1784 if (typeof force_fetch == "undefined")
1785 force_fetch = false;
1787 var cgi = new openils.CGI();
1788 var source = cgi.param('source');
1789 if (source && source.match(/invoice/)) {
1790 // got here from the invoice page, show the 'return-to-invoice' button
1791 var cgi = new openils.CGI({url : source});
1792 cgi.param('focus_li', liId);
1793 openils.Util.show(dojo.byId('acq-lit-copies-back-to-invoice-button-wrapper'), 'inline');
1794 var button = dojo.byId('acq-lit-copies-back-to-invoice-button');
1795 button.onclick = function() { location.href = cgi.url() };
1798 openils.acq.Lineitem.fetchAndRender(liId, {},
1799 function(li, html) {
1800 dojo.byId('acq-lit-copies-li-summary').innerHTML = html;
1804 this.show('copies');
1806 this.copyCache = {};
1807 this.copyWidgetCache = {};
1808 this.oldCopyWidgetCache = {};
1809 this.virtDfaCounts = {};
1810 this.realDfaCache = {};
1813 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
1814 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
1815 acqLitCopyCountInput.attr('value', '0');
1817 if (this.isPO && PO && PO.order_date()) {
1818 // prevent adding copies to activated POs
1819 acqLitCopyCountInput.attr('disabled', true);
1820 acqLitAddCopyCount.attr('disabled', true);
1823 while(this.copyTbody.childNodes[0])
1824 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
1826 this._drawBatchCopyWidgets();
1828 this._drawDistribApplied(liId);
1830 this._fetchDistribFormulas(
1832 openils.acq.Lineitem.fetchAttrDefs(
1834 self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch);
1841 this._saveDistribAppliedTemplates = function() {
1842 if (!this._appliedDistribTemplate) {
1843 this._appliedDistribTemplate =
1844 dojo.byId("acq-lit-distrib-applied-tbody").
1845 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
1846 dojo.attr(this._appliedDistribTemplate, "id");
1850 this._drawDistribApplied = function(liId) {
1851 /* Build this table while hidden to prevent rendering artifacts */
1852 openils.Util.hide("acq-lit-distrib-applied-tbody");
1854 this._saveDistribAppliedTemplates();
1856 /* Remove any rows in the table from previous populations */
1857 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
1858 forEach(dojo.destroy);
1860 /* Unregister all dijits previously created (for some reason this isn't
1861 * covered by the above destroy calls). */
1862 dijit.registry.forEach(
1863 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
1866 /* Populate the table with our liId */
1868 fieldmapper.standardRequest(
1870 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
1873 "params": [self.authtoken, liId],
1874 "onresponse": function(r) {
1875 var dfa = openils.Util.readResponse(r);
1878 self.realDfaCache[dfa.id()] = dfa;
1879 self._drawDistribAppliedUnit(dfa);
1882 "oncomplete": function() {
1883 /* Reveal built table */
1886 "acq-lit-distrib-applied-tbody", "table-row-group"
1894 this._drawDistribAppliedUnit = function(dfa) {
1895 var new_row = false;
1896 var row = dojo.query(
1897 'tr[formula="' + dfa.formula().id() + '"]',
1898 "acq-lit-distrib-applied-tbody"
1903 row = dojo.clone(this._appliedDistribTemplate);
1904 dojo.attr(row, "formula", dfa.formula().id());
1905 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
1908 var td = dojo.query("td", row)[0];
1910 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1911 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1914 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1916 new dijit.form.Button(
1918 "onClick": function() {
1919 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1920 self.deleteDfa(dfa);
1923 /* XXX I /cannot/ make the following work in as a CSS class
1924 * for some reason. So frustrating... */
1925 "style": function(id) {
1927 "font-weight: bold; color: #c00;" :
1929 }(dfa.id()) + "margin: 0 6px;display: inline;"
1930 }, "dfa-button-" + dfa.id()
1934 "connectId": ["dfa-button-" + dfa.id()],
1935 "label": dojo.string.substitute(
1936 localeStrings.DFA_TIP, dfa.id() > 0 ? [
1937 openils.User.formalName(dfa.creator()),
1938 dojo.date.locale.format(
1939 dojo.date.stamp.fromISOString(dfa.create_time()),
1940 {"formatLength":"short"}
1942 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
1944 }, "dfa-tip-" + dfa.id()
1948 this.deleteDfa = function(dfa) {
1949 if (dfa.id() > 0) { /* real */
1950 this.pcrud.eliminate(
1953 "oncomplete": function() {
1954 self._removeDistribApplied(dfa.id());
1955 delete self.realDfaCache[dfa.id()];
1959 } else { /* virtual */
1960 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
1961 this.virtDfaCounts[dfa.formula().id()] = 0;
1962 /* hasn't been saved yet, so no need to do anything server side */
1963 this._removeDistribApplied(dfa.id());
1968 this._removeDistribApplied = function(dfaId) {
1969 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
1970 dijit.registry.forEach(
1971 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
1973 this._removeDistribAppliedEmptyRows();
1976 this._removeAllDistribAppliedVirtual = function() {
1977 /* Unregister dijits */
1978 dijit.registry.forEach(
1979 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
1981 this._removeDistribAppliedEmptyRows();
1984 this._removeDistribAppliedEmptyRows = function() {
1985 /* Remove any rows with no DFA at all */
1986 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
1988 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
1994 * Insert a new row into the distribution formula selection form
1996 this._addDistribFormulaRow = function() {
1999 if (!self.distribForms) {
2000 // no formulas, hide the form
2001 openils.Util.hide('acq-lit-distrib-formula-table');
2005 if(!this.distribFormulaTemplate)
2006 this.distribFormulaTemplate =
2007 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
2009 var row = this.distribFormulaTemplate.cloneNode(true);
2010 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
2012 this.dfSelector = new dijit.form.FilteringSelect(
2013 {"labelAttr": "dynLabel", "labelType": "html"},
2014 nodeByName("selector", row)
2016 this._updateFormulaStore();
2017 this.dfSelector.fetchProperties =
2018 {"sort": [{"attribute": "use_count", "descending": true}]};
2020 var apply = new dijit.form.Button(
2021 {"label": localeStrings.APPLY},
2022 nodeByName('set_button', row)
2025 var reset = new dijit.form.Button(
2026 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
2027 nodeByName("reset_button", row)
2030 dojo.connect(apply, 'onClick',
2032 var form_id = self.dfSelector.attr("value");
2033 if(!form_id) return;
2034 self._applyDistribFormula(form_id);
2035 reset.attr("disabled", false);
2039 dojo.connect(reset, 'onClick',
2041 self.restoreCopyFieldsBeforeDF();
2042 self.virtDfaCounts = {};
2043 self.virtDfaId = -1;
2045 self._updateFormulaStore();
2046 self._removeAllDistribAppliedVirtual();
2047 reset.attr("disabled", "true");
2054 * Applies a distrib formula to the current set of copies
2056 this._applyDistribFormula = function(formula) {
2057 if(!formula) return;
2059 formula = this.distribForms.filter(
2060 function(form) { return form.id() == formula; }
2063 var copyRows = dojo.query('tr', self.copyTbody);
2065 if (this.dfeOffset >= copyRows.length) {
2066 alert(localeStrings.OUT_OF_COPIES);
2070 var entries_applied = 0;
2072 var rowIndex = this.dfeOffset;
2073 rowIndex < copyRows.length;
2077 var row = copyRows[rowIndex];
2078 var copy_id = row.getAttribute('copy_id');
2079 var copyWidgets = this.copyWidgetCache[copy_id];
2080 var entryIndex = this.dfeOffset;
2083 // find the correct entry for the current row
2084 dojo.forEach(formula.entries(),
2087 entryIndex += e.item_count();
2088 if(entryIndex > rowIndex)
2096 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
2097 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
2100 this.saveCopyFieldsBeforeDF(copy_id);
2101 this._copy_fields_for_acqdf.forEach(
2103 if(entry[field]()) {
2104 copyWidgets[field].attr('value', (entry[field]()));
2111 if (entries_applied) {
2112 this.virtDfaCounts[formula.id()] =
2113 ++(this.virtDfaCounts[formula.id()]) || 1;
2114 this._updateFormulaStore();
2115 this._drawDistribAppliedUnit(
2117 var dfa = new acqdfa();
2118 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
2121 this.dfeOffset += entries_applied;
2126 * This function updates the DF store for the dropdown so that use_counts
2127 * can reflect DF applications from this session before they're saved
2130 this._updateFormulaStore = function() {
2131 this.dfSelector.store = new dojo.data.ItemFileReadStore(
2133 "data": self._labelFormulasWithCounts(
2134 acqdf.toStoreData(self.distribForms)
2140 this.saveCopyFieldsBeforeDF = function(copy_id) {
2142 if (!this.oldCopyWidgetCache[copy_id]) {
2143 var copyWidgets = this.copyWidgetCache[copy_id];
2145 this.oldCopyWidgetCache[copy_id] = {};
2146 this._copy_fields_for_acqdf.forEach(
2148 self.oldCopyWidgetCache[copy_id][f] =
2149 copyWidgets[f].attr("value");
2155 this.restoreCopyFieldsBeforeDF = function() {
2157 for (var copy_id in this.oldCopyWidgetCache) {
2158 this._copy_fields_for_acqdf.forEach(
2160 self.copyWidgetCache[copy_id][f].attr(
2161 "value", self.oldCopyWidgetCache[copy_id][f]
2168 this._labelFormulasWithCounts = function(store_data) {
2169 for (var key in store_data.items) {
2170 var obj = store_data.items[key];
2171 obj.use_count = Number(obj.use_count); /* needed for sorting */
2173 if (this.virtDfaCounts[obj.id])
2174 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
2176 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
2177 obj.use_count + "]</span> " + obj.name;
2183 * This method formerly would not refetch the DF formulas if they'd been
2184 * loaded already, but now it always re-fetches, since use_count changes.
2186 /** TODO: port distrib-formula selector to autofieldwidget+pcrud/dojo store */
2187 this._fetchDistribFormulas = function(onload) {
2188 fieldmapper.standardRequest(
2190 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
2193 "params": [openils.User.authtoken, 0, 500],
2194 "oncomplete": function(r) {
2195 self.distribForms = openils.Util.readResponse(r);
2196 if(!self.distribForms || self.distribForms.length == 0) {
2197 self.distribForms = [];
2199 self._addDistribFormulaRow();
2206 this._drawBatchCopyWidgets = function() {
2207 var row = this.copyBatchRow;
2208 dojo.forEach(liDetailBatchFields,
2210 if(self.copyBatchRowDrawn) {
2211 self.copyBatchWidgets[field].attr('value', null);
2213 var args = self.afwCopyFieldArgs(field, "CREATE_PICKLIST");
2214 args.parentNode = dojo.query('[name='+field+']', row)[0];
2216 var widget = new openils.widget.AutoFieldWidget(args);
2219 if (field == "fund" && w.store)
2220 self._ensureCSSFundClasses(w.store);
2221 self.copyBatchWidgets[field] = w;
2224 if (field == "fund") {
2226 widget.widget, "onChange", function(val) {
2227 self._updateFundSelectorStyle(widget, val);
2234 this.copyBatchRowDrawn = true;
2237 this.batchCopyUpdate = function() {
2239 for(var k in this.copyWidgetCache) {
2240 var cache = this.copyWidgetCache[k];
2241 dojo.forEach(liDetailBatchFields, function(f) {
2242 var newval = self.copyBatchWidgets[f].attr('value');
2243 if(newval) cache[f].attr('value', newval);
2248 this._drawCopies = function(li) {
2251 // this button sets the total number of copies for a given lineitem
2252 acqLitAddCopyCount.onClick = function() {
2253 var count = acqLitCopyCountInput.attr('value');
2256 while(self.copyCount() < count)
2259 // delete rows if necessary
2260 var diff = self.copyCount() - count;
2262 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
2263 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
2264 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
2266 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2272 if(li.lineitem_details().length > 0) {
2273 dojo.forEach(li.lineitem_details(),
2275 self.addCopy(li, copy);
2283 this.copyCount = function() {
2285 for(var id in this.copyCache) {
2286 if(!this.copyCache[id].isdeleted())
2292 this.virtCopyId = -1;
2293 this.addCopy = function(li, copy) {
2294 var row = this.copyRow.cloneNode(true);
2295 this.copyTbody.appendChild(row);
2299 copy = new fieldmapper.acqlid();
2301 copy.id(this.virtCopyId--);
2302 copy.lineitem(li.id());
2305 this.copyCache[copy.id()] = copy;
2306 row.setAttribute('copy_id', copy.id());
2307 self.copyWidgetCache[copy.id()] = {};
2309 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2311 var rcvr = copy.receiver();
2313 if (!userCache[rcvr]) {
2314 if(rcvr == openils.User.user.id()) {
2315 userCache[rcvr] = openils.User.user;
2317 userCache[rcvr] = fieldmapper.standardRequest(
2318 ['open-ils.actor', 'open-ils.actor.user.retrieve'],
2319 {params: [openils.User.authtoken, rcvr]}
2323 dojo.query('[name=receiver]', row)[0].innerHTML = userCache[rcvr].usrname();
2326 dojo.forEach(liDetailFields,
2329 if (field == "fund") {
2330 searchFilter = (copy.fund() ?
2331 {"-or": {"active": "t", "id": copy.fund()}} :
2333 searchFilter.org = fundSearchFilter.org;
2335 searchFilter = null;
2338 var readOnly = false;
2340 // TODO: Add support for changing the owning_lib after real copies have been made.
2341 // owning_lib is order data as much as its item data
2342 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
2346 // TODO: add support for changing the fund after debits have been created
2347 // Note: invoicing allows the change
2348 if(copy.fund_debit() && field == 'fund') {
2353 var widget = new openils.widget.AutoFieldWidget({
2356 labelFormat : (field == 'fund') ? fundLabelFormat : null,
2357 searchFormat : (field == 'fund') ? fundSearchFormat : null,
2358 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
2359 searchFilter : searchFilter,
2360 noCache: (field == "fund"),
2362 parentNode : dojo.query('[name='+field+']', row)[0],
2363 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2364 readOnly : readOnly,
2365 orgDefaultsToWs : true
2369 // make sure we capture the value from any async widgets
2372 if (field == "fund" && w.store)
2373 self._ensureCSSFundClasses(w.store);
2376 copy[field](ww.getFormattedValue())
2378 self.copyWidgetCache[copy.id()][field] = w;
2380 dojo.connect(w, 'onChange',
2382 if (field == "fund")
2383 self._updateFundSelectorStyle(widget, val);
2385 if (!readOnly && (copy.isnew() || val != copy[field]())) {
2386 // prevent setting ischanged() automatically on widget load for existing copies
2387 copy[field](widget.getFormattedValue())
2388 copy.ischanged(true);
2397 this.updateLidState(copy, row);
2400 this._ensureCSSFundClass = function(id) {
2401 if (!this.fundStyleSheet) {
2403 "style", {"type": "text/css"},
2404 document.getElementsByTagName("head")[0], "last"
2406 this.fundStyleSheet = document.styleSheets[
2407 document.styleSheets.length - 1
2411 var cn = "fund_" + id;
2412 if (!this.haveFundClass[cn]) {
2413 fieldmapper.standardRequest(
2414 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
2416 "params": [openils.User.authtoken, id],
2418 "oncomplete": function(r) {
2419 r = openils.Util.readResponse(r);
2420 self.fundBalanceState[id] = r;
2422 if (r[0] /* stop */)
2423 style = fundStyles.stop;
2424 else if (r[1] /* warning */)
2425 style = fundStyles.warning;
2426 self.fundStyleSheet.insertRule(
2427 "." + cn + " { " + style + " }",
2428 self.fundStyleSheet.cssRules.length
2430 self.haveFundClass[cn] = true;
2437 this._ensureCSSFundClasses = function(store) {
2439 "query": {"id": "*"},
2440 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
2444 this._updateFundSelectorStyle = function(widget, fund_id) {
2445 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
2446 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
2449 this.updateLidState = function(copy, row) {
2452 if (typeof(row) == "undefined") {
2453 row = dojo.query('tr[copy_id="' + copy.id() + '"]', this.copyTbody)[0];
2457 var recv_link = nodeByName("receive", row);
2458 var unrecv_link = nodeByName("unreceive", row);
2459 var del_link = nodeByName("delete", row);
2460 var cxl_link = nodeByName("cancel", row);
2461 var claim_link = nodeByName("claim", row);
2462 var cxl_reason_link = nodeByName("cancel_reason", row);
2464 // by default, hide all the actions
2465 openils.Util.hide(del_link.parentNode);
2466 openils.Util.hide(recv_link);
2467 openils.Util.hide(unrecv_link);
2468 openils.Util.hide(cxl_link);
2469 openils.Util.hide(claim_link);
2470 openils.Util.hide(cxl_reason_link);
2472 if (copy.id() > 0) { // real copies (LIDs)
2474 if (copy.cancel_reason()) {
2476 /* --------- cancelled -------------------------- */
2478 /* XXX the following may leak memory in a long lived table:
2479 * dijits may not get destroyed... not positive. revisit. */
2480 var holds_reason = dojo.create(
2482 "style": "border-bottom: 1px dashed #000;",
2483 "innerHTML": copy.cancel_reason().label()
2484 }, cxl_reason_link, "only"
2488 "label": "<em>" + copy.cancel_reason().label() +
2489 "</em><br />" + copy.cancel_reason().description(),
2490 "connectId": [holds_reason]
2491 }, dojo.create("span", null, cxl_reason_link, "last")
2493 openils.Util.show(cxl_reason_link, "inline");
2495 if (copy.cancel_reason().keep_debits() == 't' ) {
2496 // allow further cancellation of "delayed" copies
2498 openils.Util.show(cxl_link, "inline");
2499 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2502 } else if (copy.recv_time()) {
2504 /* --------- received -------------------------- */
2506 openils.Util.show(unrecv_link, "inline");
2507 unrecv_link.onclick = function() {
2508 if (confirm(localeStrings.UNRECEIVE_LID))
2509 self.issueReceive(copy, /* rollback */ true);
2512 } else if (this.liCache[copy.lineitem()].state() == 'on-order') {
2514 /* --------- on order -------------------------- */
2516 openils.Util.show(recv_link, 'inline');
2517 openils.Util.show(cxl_link, "inline");
2519 recv_link.onclick = function() {
2520 if (self.checkLiAlerts(copy.lineitem()))
2521 self.issueReceive(copy);
2524 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2528 /* --------- pre-order copies -------------------------- */
2530 del_link.onclick = function() { self.deleteCopy(row) };
2531 openils.Util.show(del_link.parentNode);
2537 /* --------- virtual copies -------------------------- */
2539 del_link.onclick = function() { self.deleteCopy(row) };
2540 openils.Util.show(del_link.parentNode);
2544 this.cancelLid = function(lid_id) {
2545 lidCancelDialog._lid_id = lid_id;
2546 openils.Util.show(lidCancelDialog.domNode.parentNode);
2547 lidCancelDialog.show();
2548 if (!lidCancelDialog._prepared) {
2549 var widget = new openils.widget.AutoFieldWidget({
2550 "fmField": "cancel_reason",
2551 "fmClass": "acqlid",
2552 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
2553 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2555 "searchOptions" : {order_by : {"acqcr":"label"}}
2559 acqLidCancelButton.onClick = function() {
2560 if (w.attr("value")) {
2561 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
2563 lidCancelDialog._lid_id,
2567 lidCancelDialog.hide();
2570 lidCancelDialog._prepared = true;
2576 this._cancelLid = function(lid_id, reason) {
2577 fieldmapper.standardRequest(
2578 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
2579 "params": [openils.User.authtoken, lid_id, reason],
2581 "onresponse": function(r) {
2582 if (r = openils.Util.readResponse(r)) {
2584 for (var id in r.lid) {
2585 /* actually this should only iterate once */
2586 self.copyCache[id].cancel_reason(
2587 r.lid[id].cancel_reason
2589 self.updateLidState(self.copyCache[id]);
2598 this._confirmAlert = function(li, lin) {
2600 dojo.string.substitute(
2601 localeStrings.CONFIRM_LI_ALERT, [
2602 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2603 "title", "lineitem_marc_attr_definition"
2605 /* XXX it's really better add a parameter and to adjust
2606 * the format string rather than do this concatenation
2607 * here, but if someone wants this for 2.2 in a hurry,
2608 * we can sidestep the problem of updating the strings
2609 * while the translators are working. */
2611 aou.findOrgUnit(lin.alert_text().owning_lib()).shortname() +
2613 lin.alert_text().code()
2615 lin.alert_text().description() || "",
2622 this.checkLiAlerts = function(li_id) {
2623 var li = this.liCache[li_id];
2625 var alert_notes = li.lineitem_notes().filter(
2626 function(o) { return Boolean(o.alert_text()); }
2629 /* this is _intentionally_ not done in a call to forEach() ... */
2630 for (var i = 0; i < alert_notes.length; i++) {
2631 if (this.noteAcks[alert_notes[i].id()])
2633 else if (!this._confirmAlert(li, alert_notes[i]))
2636 this.noteAcks[alert_notes[i].id()] = true;
2642 this.deleteCopy = function(row) {
2643 var copy = this.copyCache[row.getAttribute('copy_id')];
2644 copy.isdeleted(true);
2646 delete this.copyCache[copy.id()];
2647 this.copyTbody.removeChild(row);
2650 this._virtDfaCountsAsList = function() {
2652 for (var key in this.virtDfaCounts) {
2653 for (var i = 0; i < this.virtDfaCounts[key]; i++)
2659 this.confirmBreachedCopyFunds = function(copies) {
2660 var stop = 0, warning = 0;
2664 var state = self.fundBalanceState[o.fund()];
2665 if (state[0] /* stop */)
2667 else if (state[1] /* warning */)
2674 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
2675 } else if (warning) {
2676 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
2681 this.saveCopyChanges = function(liId) {
2687 for(var id in this.copyCache) {
2688 var c = this.copyCache[id];
2689 if(!c.isdeleted()) total++;
2690 if(c.isnew() || c.ischanged() || c.isdeleted()) {
2691 if(c.id() < 0) c.id(null);
2697 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
2700 if (copies.length > 0) {
2701 if (!this.confirmBreachedCopyFunds(copies))
2704 if (typeof(this._copy_count_cb) == "function")
2705 this._copy_count_cb(liId, total);
2707 openils.Util.show("acq-lit-update-copies-progress");
2708 fieldmapper.standardRequest(
2709 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
2711 params: [openils.User.authtoken, copies],
2712 onresponse: function(r) {
2713 var res = openils.Util.readResponse(r);
2714 litUpdateCopiesProgress.update(res);
2716 oncomplete: function() {
2717 self.drawCopies(liId, true /* force_fetch */);
2718 openils.Util.hide("acq-lit-update-copies-progress");
2724 var dfa_list = this._virtDfaCountsAsList();
2725 if (dfa_list.length > 0) {
2726 fieldmapper.standardRequest(
2728 "open-ils.acq.distribution_formula.record_application"],
2731 "params": [openils.User.authtoken, dfa_list, liId],
2732 "onresponse": function(r) {
2733 var res = openils.Util.readResponse(r);
2734 if (res && res.length < dfa_list.length)
2735 alert(localeStrings.DFA_NOT_ALL);
2739 this.virtDfaCounts = {};
2742 if (this.inlineCopiesNeedingRefresh.indexOf(liId) < 0)
2743 this.inlineCopiesNeedingRefresh.push(liId);
2746 this._updateCreatePoPrepayCheckbox = function(prepay) {
2747 var prepay = openils.Util.isTrue(prepay);
2748 this._prepayRequiredByVendor = prepay;
2749 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
2752 this._confirmPoPrepaySituation = function() {
2753 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
2754 if (want_prepay != this._prepayRequiredByVendor) {
2757 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
2758 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
2765 this.applySelectedLiAction = function(action) {
2769 case 'delete_selected':
2770 this._deleteLiList(self.getSelected());
2773 case 'add_to_order':
2774 addToPoDialog._get_li = dojo.hitch(
2777 return this.getSelected(
2778 false, null, true, li_pre_po_states);
2781 if (addToPoDialog._get_li().length == 0) {
2782 alert(localeStrings.NO_LI_GENERAL);
2785 addToPoDialog.show();
2788 case 'create_order':
2789 this._loadPOSelect();
2790 acqLitPoCreateDialog.show();
2793 case 'save_picklist':
2794 acqLitSavePlDialog.show();
2797 case 'selector_ready':
2799 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
2800 acqLitChangeLiStateDialog.show();
2808 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
2811 case 'batch_create_invoice':
2812 this.batchCreateInvoice();
2815 case 'batch_link_invoice':
2816 this.batchLinkInvoice();
2819 case 'receive_lineitems':
2820 this.receiveSelectedLineitems();
2823 case 'rollback_receive_lineitems':
2824 this.rollbackReceiveLineitems();
2827 case 'create_assets':
2828 this.showAssetCreator();
2831 case 'export_attr_list':
2832 this.chooseExportAttr();
2835 case 'batch_apply_funds':
2836 this.applyBatchLiFunds();
2839 case 'add_brief_record':
2841 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
2843 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
2847 case "cancel_lineitems":
2848 console.log('HERE');
2849 this.maybeCancelLineitems();
2852 case "apply_claim_policy":
2853 var li_list = this.getSelected();
2854 this.claimPolicyPicker.attr("value", null);
2855 liClaimPolicyDialog.show();
2856 liClaimPolicySave.onClick = function() {
2857 self.changeClaimPolicy(
2859 self.claimPolicyPicker.attr("value"),
2863 self.setClaimPolicyControl(li);
2864 self.reconsiderClaimControl(li);
2867 liClaimPolicyDialog.hide();
2875 this.changeClaimPolicy = function(li_list, value, callback) {
2877 function(li) { li.claim_policy(value); }
2879 fieldmapper.standardRequest(
2880 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
2881 "params": [openils.User.authtoken, li_list],
2883 "oncomplete": function(r) {
2884 r = openils.Util.readResponse(r);
2885 if (callback) callback(r);
2891 this.showAssetCreator = function(onAssetsCreated) {
2892 if(!this.isPO) return;
2895 // first, let's see if this PO has any LI's that need to be merged/imported
2896 self.pcrud.search('jub', {purchase_order : this.isPO, eg_bib_id : null}, {
2898 oncomplete : function(r) {
2899 var resp = openils.Util.readResponse(r);
2900 if (resp && resp.length) {
2901 // PO has some non-linked jubs.
2903 self.show('asset-creator');
2904 if(!self.vlAgent.loaded)
2905 self.vlAgent.init();
2907 dojo.connect(assetCreatorButton, 'onClick',
2908 function() { self.createAssets(onAssetsCreated) });
2912 // all jubs linked, move on to asset creation
2913 self.createAssets(onAssetsCreated, true);
2919 this.createAssets = function(onAssetsCreated, noVl) {
2920 this.show('acq-lit-progress-numbers');
2922 var vlArgs = (noVl) ? {} : {vandelay : this.vlAgent.values()};
2923 fieldmapper.standardRequest(
2924 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
2926 params: [this.authtoken, this.isPO, vlArgs],
2927 onresponse: function(r) {
2928 var resp = openils.Util.readResponse(r);
2929 self._updateProgressNumbers(resp, !Boolean(onAssetsCreated), onAssetsCreated);
2935 this.maybeCancelLineitems = function() {
2936 openils.Util.show("acq-lit-cancel-reason", "inline");
2937 if (!acqLitCancelLineitemsButton._prepared) {
2938 var widget = new openils.widget.AutoFieldWidget({
2939 "fmField": "cancel_reason",
2941 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
2942 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2944 "searchOptions" : {order_by : {"acqcr":"label"}}
2948 acqLitCancelLineitemsButton.onClick = function() {
2949 if (w.attr("value")) {
2950 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
2951 self._cancelLineitems(w.attr("value"));
2953 openils.Util.hide("acq-lit-cancel-reason");
2956 acqLitCancelLineitemsButton._prepared = true;
2962 this._cancelLineitems = function(reason) {
2964 var li_list = this.getSelected();
2966 // canceled lineitems may be canceled again if they were
2967 // previously delayed (keep_debits = true).
2968 li_list = li_list.filter(
2971 li.state() != 'cancelled' ||
2972 li.cancel_reason().keep_debits() == 't'
2977 id_list = li_list.map(function(l) {return l.id()});
2979 if (!id_list.length) {
2980 alert(localeStrings.NO_LI_GENERAL);
2983 fieldmapper.standardRequest(
2984 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
2985 "params": [openils.User.authtoken, id_list, reason],
2987 "onresponse": function(r) {
2988 if (r = openils.Util.readResponse(r)) {
2990 for (var id in r.li) {
2991 self.liCache[id].state(r.li[id].state);
2992 self.liCache[id].cancel_reason(
2993 r.li[id].cancel_reason
2995 self.updateLiState(self.liCache[id]);
2998 if (r.lid && self.copyCache) {
2999 for (var id in r.lid) {
3000 if (self.copyCache[id]) {
3001 self.copyCache[id].cancel_reason(
3002 r.lid[id].cancel_reason
3004 self.updateLidState(self.copyCache[id]);
3014 this.chooseExportAttr = function() {
3015 if (!acqLitExportAttrSelector._li_setup) {
3017 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
3019 "data": acqlimad.toStoreData(
3021 "acqlimad", {"code": li_exportable_attrs}
3026 acqLitExportAttrSelector.setValue();
3027 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
3028 acqLitExportAttrSelector._li_setup = true;
3030 openils.Util.show("acq-lit-export-attr-holder", "inline");
3033 this.exportAttrList = function() {
3034 var attr_def = acqLitExportAttrSelector.item;
3035 var li_list = this.getSelected();
3036 var value_list = li_list.map(
3038 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
3039 attr_def.code, "lineitem_marc_attr_definition"
3042 ).filter(function(attr) { return Boolean(attr); });
3044 if (value_list.length > 0) {
3045 if (value_list.length < li_list.length) {
3047 dojo.string.substitute(
3048 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
3055 openils.XUL.contentToFileSaveDialog(
3056 value_list.join("\n"),
3057 localeStrings.EXPORT_SAVE_DIALOG_TITLE
3063 alert(dojo.string.substitute(
3064 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
3068 openils.Util.hide("acq-lit-export-attr-holder");
3071 this.printPO = function() {
3072 if(!this.isPO) return;
3073 progressDialog.show(true);
3074 fieldmapper.standardRequest(
3075 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
3077 params: [this.authtoken, this.isPO, 'html'],
3078 oncomplete: function(r) {
3079 progressDialog.hide();
3080 var evt = openils.Util.readResponse(r);
3081 if(evt && evt.template_output()) {
3082 openils.Util.printHtmlString(evt.template_output().data());
3089 this.batchCreateInvoice = function() {
3090 var liIds = this.getSelected(
3091 false, null, true /* id_list */, li_active_states)
3092 if (!liIds.length) {
3093 alert(localeStrings.NO_LI_GENERAL);
3096 var path = oilsBasePath + '/acq/invoice/view?create=1';
3097 dojo.forEach(liIds, function(li, idx) { path += '&attach_li=' + li });
3098 if (openils.XUL.isXUL())
3099 openils.XUL.newTabEasy(path, localeStrings.NEW_INVOICE, null, true);
3101 location.href = path;
3104 this.batchLinkInvoice = function(create) {
3105 var liIds = this.getSelected(
3106 false, null, true /* id_list */, li_active_states)
3107 if (!liIds.length) {
3108 alert(localeStrings.NO_LI_GENERAL);
3111 if (!self.invoiceLinkDialogManager) {
3112 self.invoiceLinkDialogManager =
3113 new InvoiceLinkDialogManager("li");
3115 self.invoiceLinkDialogManager.target = liIds;
3116 acqLitLinkInvoiceDialog.show();
3119 this.receiveSelectedLineitems = function() {
3120 var states = li_post_po_states.filter(
3121 function(s) { return s != 'received' });
3122 var li_list = this.getSelected(null, null, null, states);
3124 if (!li_list.length) {
3125 alert(localeStrings.NO_LI_GENERAL);
3129 for (var i = 0; i < li_list.length; i++) {
3130 var li = li_list[i];
3132 if (li.state() != "received" &&
3133 !this.checkLiAlerts(li.id())) return;
3136 this.show('acq-lit-progress-numbers');
3139 fieldmapper.standardRequest(
3140 ['open-ils.acq', 'open-ils.acq.lineitem.receive.batch'],
3144 li_list.map(function(li) { return li.id(); })
3146 onresponse : function(r) {
3147 var resp = openils.Util.readResponse(r);
3148 self._updateProgressNumbers(resp, true);
3154 this.issueReceive = function(obj, rollback) {
3156 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
3158 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
3160 progressDialog.show(true);
3161 fieldmapper.standardRequest(
3162 ["open-ils.acq", method], {
3164 "params": [this.authtoken, obj.id()],
3165 "onresponse": function(r) {
3166 if (r = openils.Util.readResponse(r)) {
3167 self.fetchClaimInfo(
3168 part == "lineitem" ? obj.id() : obj.lineitem(),
3170 function() { self.handleReceive(r); }
3172 progressDialog.hide();
3180 * Handles the responses from receive and rollback ML calls.
3182 this.handleReceive = function(resp) {
3185 for (var li_id in resp.li) {
3186 for (var key in resp.li[li_id])
3187 self.liCache[li_id][key](resp.li[li_id][key]);
3188 self.updateLiState(self.liCache[li_id]);
3192 if (typeof(self.poUpdateCallback) == "function")
3193 self.poUpdateCallback(resp.po);
3196 for (var lid_id in resp.lid) {
3197 for (var key in resp.lid[lid_id])
3198 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
3199 self.updateLidState(self.copyCache[lid_id]);
3205 this.rollbackReceiveLineitems = function() {
3206 var li_id_list = this.getSelected(false, null, true);
3207 if (!li_id_list.length) {
3208 alert(localeStrings.NO_LI_GENERAL);
3212 if (!confirm(localeStrings.ROLLBACK_LI_RECEIVE_CONFIRM)) return;
3214 this.show('acq-lit-progress-numbers');
3217 fieldmapper.standardRequest(
3218 ['open-ils.acq', 'open-ils.acq.lineitem.receive.rollback.batch'],
3220 params: [this.authtoken, li_id_list],
3221 onresponse : function(r) {
3222 var resp = openils.Util.readResponse(r);
3223 self._updateProgressNumbers(resp, true);
3229 this._updateProgressNumbers = function(resp, reloadOnComplete, onComplete) {
3230 this.vlAgent.handleResponse(resp,
3231 function(resp, res) {
3232 if(reloadOnComplete)
3233 location.href = location.href;
3235 onComplete(resp, res);
3241 this._createPO = function(fields) {
3242 var wantall = (fields.create_from == "all");
3244 /* If we're a picklist or purchase order already and the user wants
3245 * all lineitems, we might have pages' worth of lineitems haven't all
3246 * been loaded yet, so getSelected() won't find them. The server,
3247 * however, should know about all our lineitems, so let's ask the
3248 * server for a complete list.
3253 true, function(list) {
3254 self._createPOFromLineitems(fields, list);
3255 }, /* id_list */ true, li_pre_po_states
3258 this._createPOFromLineitems(
3259 fields, this.getSelected(
3260 false, null, true /* id_list */, li_pre_po_states)
3265 this._createPOFromLineitems = function(fields, selected) {
3266 if (selected.length == 0) {
3267 alert(localeStrings.NO_LI_GENERAL);
3272 var po = new fieldmapper.acqpo();
3273 po.provider(this.createPoProviderSelector.attr("value"));
3274 po.ordering_agency(this.createPoAgencySelector.attr("value"));
3275 po.prepayment_required(fields.prepayment_required[0] ? true : false);
3276 var name = this.createPoNameInput.attr('value');
3277 if (name) po.name(name); // avoid name=""
3279 // if we're creating assets, delay the asset creation
3280 // until after the PO is created. This will allow us to
3281 // use showAssetCreator() directly.
3283 fieldmapper.standardRequest(
3284 ["open-ils.acq", "open-ils.acq.purchase_order.create"],
3287 openils.User.authtoken,
3288 po, {lineitems : selected}
3290 onresponse : function(r) {
3291 var resp = openils.Util.readResponse(r);
3292 if (resp.complete) {
3293 // self.isPO is needed for showAssetCreator();
3294 self.isPO = resp.purchase_order.id();
3295 var redir = oilsBasePath + "/acq/po/view/" + self.isPO;
3296 if (fields.create_assets[0]) {
3297 self.showAssetCreator(
3298 function() {location.href = redir}
3301 location.href = redir;
3310 this.batchFundWidget = null;
3312 this.applyBatchLiFunds = function() {
3314 var liIds = this.getSelected().map(function(li) { return li.id(); });
3315 if(liIds.length == 0) return; // warn?
3318 batchFundUpdateDialog.show();
3320 if(!this.batchFundWidget) {
3321 this.batchFundWidget = new openils.widget.AutoFieldWidget({
3323 selfReference : true,
3324 labelFormat : fundLabelFormat,
3325 searchFormat : fundSearchFormat,
3326 searchFilter : fundSearchFilter,
3327 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
3328 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
3329 dijitArgs : { "required": true, "labelType": "html" },
3332 this.batchFundWidget.build();
3335 dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
3336 dojo.connect(batchFundUpdateSubmit, 'onClick',
3339 // TODO: call .dry_run first to test thresholds
3340 fieldmapper.standardRequest(
3341 ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
3344 openils.User.authtoken,
3346 self.batchFundWidget.widget.attr('value')
3348 oncomplete : function(r) {
3349 var resp = openils.Util.readResponse(r);
3351 location.href = location.href;
3360 this._deleteLiList = function(list, idx) {
3361 if(idx == null) idx = 0;
3362 if(idx >= list.length) return;
3367 if (this.isPO && (li.state() == "on-order" || li.state() == "received")) {
3368 /* It makes little sense to delete a lineitem from a PO that has
3369 * already been marked 'on-order'. Especially if EDI is in use,
3370 * such a purchase order will probably have already been shipped
3371 * off to a vendor, and mucking with it at this point could leave
3372 * your data in a bad state that doesn't jive with reality.
3374 * I could see making this restriction even firmer.
3376 * I could also see adjusting the li state comparisons, extending
3377 * the comparison to the PO's state, and/or providing functions
3378 * that house the logic for comparing states in a single location.
3380 * Yes, this will be really annoying if you have selected a lot
3381 * of lineitems to cancel that have been ordered. You'll get a
3382 * confirm dialog for each one.
3385 if (!confirm(localeStrings.DEL_LI_FROM_PO)) {
3386 self._deleteLiList(list, ++idx); /* move on to next in list */
3391 fieldmapper.standardRequest(
3393 this.isPO ? 'open-ils.acq.purchase_order.lineitem.delete' : 'open-ils.acq.picklist.lineitem.delete'],
3395 params: [openils.User.authtoken, liId],
3396 oncomplete: function(r) {
3397 self.removeLineitem(liId);
3398 self._deleteLiList(list, ++idx);
3404 this.editOrderMarc = function(li) {
3406 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
3407 to true in about:config */
3409 if(openils.XUL.isXUL()) {
3410 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul','','chrome');
3412 win = window.open('/xul/server/cat/marcedit.xul','','chrome');
3416 record : {marc : li.marc(), "rtype": "bre"},
3418 label: 'Save Record', // XXX I18N
3419 func: function(xmlString) {
3421 fieldmapper.standardRequest(
3422 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
3424 params: [openils.User.authtoken, li],
3425 oncomplete: function(r) {
3426 openils.Util.readResponse(r);
3428 self.drawInfo(li.id())
3434 'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
3435 'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
3439 this._savePl = function(values) {
3441 (values.which == 'all'),
3442 function(list) { self._savePlFromLineitems(values, list); }
3446 this._savePlFromLineitems = function(values, selected) {
3447 openils.Util.show("acq-lit-generic-progress");
3449 if(values.new_name) {
3450 openils.acq.Picklist.create(
3451 {name: values.new_name},
3457 oilsBasePath + "/acq/picklist/view/" + id;
3462 } else if(values.existing_pl) {
3463 // update lineitems to use an existing picklist
3465 values.existing_pl, selected, 0,
3468 oilsBasePath + "/acq/picklist/view/" +
3475 this._updateLiState = function(values, state, state_filter) {
3476 progressDialog.show(true);
3478 (values.which == 'all'),
3480 self._updateLiStateFromLineitems(values, state, list);
3481 }, false /* id_list */, state_filter
3485 this._updateLiStateFromLineitems = function(values, state, selected) {
3486 if(!selected.length) {
3487 try { progressDialog.hide() } catch(E) {};
3488 alert(localeStrings.NO_LI_GENERAL);
3491 dojo.forEach(selected, function(li) {li.state(state);});
3492 self._updateLiList(null, selected, 0,
3493 // TODO consider inline updates for efficiency
3494 function() { location.href = location.href }
3498 this._updateLiList = function(pl, list, idx, oncomplete) {
3499 if(idx >= list.length) return oncomplete();
3501 if(pl != null) li.picklist(pl);
3502 litGenericProgress.update({maximum: list.length, progress: idx});
3503 new openils.acq.Lineitem({lineitem:li}).update(
3505 self._updateLiList(pl, list, ++idx, oncomplete);
3510 this._loadPOSelect = function() {
3511 if (!this.createPoProviderSelector) {
3512 var widget = new openils.widget.AutoFieldWidget({
3513 "fmField": "provider",
3515 "searchFilter": {"active": "t"},
3516 "parentNode": dojo.byId("acq-lit-po-provider"),
3518 "onChange": function() {
3520 self._updateCreatePoPrepayCheckbox(
3521 this.item.prepayment_required()
3527 widget.build(function(w) { self.createPoProviderSelector = w; });
3530 this.createPoCheckDupes = function() {
3531 var org = self.createPoAgencySelector.attr('value');
3532 var name = self.createPoNameInput.attr('value');
3533 openils.Util.hide('acq-dupe-po-name');
3536 acqLitCreatePoSubmit.attr('disabled', false);
3540 acqLitCreatePoSubmit.attr('disabled', true);
3541 var orgs = fieldmapper.aou.descendantNodeList(org, true);
3542 new openils.PermaCrud().search('acqpo',
3543 {name : name, ordering_agency : orgs},
3544 {async : true, oncomplete : function(r) {
3545 var po = openils.Util.readResponse(r);
3547 if (po && (po = po[0])) {
3549 var link = dojo.byId('acq-dupe-po-link');
3550 openils.Util.show('acq-dupe-po-name', 'table-row');
3551 var dupe_path = '/acq/po/view/' + po.id();
3555 if (window.IAMBROWSER) {
3556 // TODO: integration
3560 link.onclick = function() {
3562 var loc = xulG.url_prefix('XUL_BROWSER?url=') +
3563 window.encodeURIComponent(
3564 xulG.url_prefix('EG_WEB_BASE' + dupe_path)
3568 {tab_name: '', browser:false},
3571 show_nav_buttons : true,
3572 show_print_button : true,
3579 link.onclick = function() {
3580 window.open(oilsBasePath + dupe_path, '_blank').focus();
3585 acqLitCreatePoSubmit.attr('disabled', false);
3591 if (!this.createPoAgencySelector) {
3592 var widget = new openils.widget.AutoFieldWidget({
3593 "fmField": "ordering_agency",
3595 "parentNode": dojo.byId("acq-lit-po-agency"),
3596 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3598 widget.build(function(w) {
3599 self.createPoAgencySelector = w;
3600 dojo.connect(w, 'onChange', self.createPoCheckDupes);
3604 if (!this.createPoNameInput) {
3605 var widget = new openils.widget.AutoFieldWidget({
3608 "parentNode": dojo.byId("acq-lit-po-name"),
3609 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3611 widget.build(function(w) {
3612 self.createPoNameInput = w;
3613 dojo.connect(w, 'onChange', self.createPoCheckDupes);
3618 this.showRealCopyEditUI = function(li) {
3623 this._fetchLineitem(li.id(),
3625 li = self.liCache[li.id()] = fullLi;
3629 id : li.lineitem_details().map(
3630 function(item) { return item.eg_copy_id() }
3634 oncomplete : function(r) {
3636 var r_list = openils.Util.readResponse( r );
3637 for (var i = 0; i < r_list.length; i++) {
3638 var copy = r_list[i];
3639 var volId = copy.call_number();
3640 var volume = self.volCache[volId];
3642 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
3644 copy.call_number(volume);
3645 copyList.push(copy);
3648 xulG.volume_item_creator( { 'existing_copies' : copyList } );
3651 alert('error in oncomplete: ' + E);
3660 this.drawBibFinder = function(li) {
3663 var liWrapper = new openils.acq.Lineitem({lineitem:li});
3666 ['isbn', 'upc', 'issn', 'title', 'author'],
3668 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
3670 if(field == 'title' || field == 'author') {
3671 query += field +':' + val + ' ';
3673 query += 'identifier|' + field + ':' + val + ' ';
3680 oilsBasePath + '/acq/lineitem/findbib?query=' + encodeURIComponent(query),
3681 '', 'resizable,scrollbars=1,chrome');
3683 win.window.recordFound = function(bibId) {
3686 var attrs = li.attributes();
3687 li.attributes(null);
3688 li.eg_bib_id(bibId);
3690 fieldmapper.standardRequest(
3691 ["open-ils.acq", "open-ils.acq.lineitem.update"],
3693 "params": [openils.User.authtoken, li],
3695 "oncomplete": function(r) {
3696 if(openils.Util.readResponse(r)) {
3697 location.href = location.href;