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();
716 var exist = nodeByName('li_existing_count', row);
717 fieldmapper.standardRequest(
718 ['open-ils.acq', 'open-ils.acq.lineitem.existing_copies.count'],
720 params: [this.authtoken, li.id()],
721 oncomplete : function(r) {
722 var count = openils.Util.readResponse(r);
723 exist.innerHTML = count;
724 if (Number(count) > 0) {
725 openils.Util.addCSSClass(
726 exist, 'acq-existing-count-warn');
730 label : dojo.string.substitute(
731 localeStrings.LI_EXISTING_COPIES, [count])
738 openils.Util.show(nodeByName('catalog', row), 'inline');
739 nodeByName("catalog_link", row).onclick = this.generateMakeRecTab(li.eg_bib_id());
741 openils.Util.show(nodeByName('link_to_catalog', row), 'inline');
742 nodeByName("link_to_catalog_link", row).onclick = function() { self.drawBibFinder(li) };
745 if (li.queued_record()) {
746 this.pcrud.retrieve('vqbr', li.queued_record(),
748 oncomplete : function(r) {
749 var qrec = openils.Util.readResponse(r);
750 openils.Util.show(nodeByName('queue', row), 'inline');
751 var link = nodeByName("queue_link", row);
752 link.onclick = function() {
753 // open a new tab to the vandelay queue for this record
754 openils.XUL.newTabEasy(
755 oilsBasePath + '/vandelay/vandelay?qtype=bib&qid=' + qrec.queue()
763 nodeByName("worksheet_link", row).href =
764 oilsBasePath + "/acq/lineitem/worksheet/" + li.id() +
765 '?source=' + encodeURIComponent(location.pathname + location.search)
767 nodeByName("show_requests_link", row).href =
768 oilsBasePath + "/acq/picklist/user_request?lineitem=" + li.id() +
769 '?source=' + encodeURIComponent(location.pathname + location.search)
771 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
772 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
773 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
774 dojo.query('[name=expand_inline_copies]', row)[0].onclick =
775 function() {self.drawInlineCopies(li.id())};
777 this.drawOrderIdentSelector(li, row);
779 if (!this.skipInitialEligibilityCheck)
783 function(full) { self.setClaimPolicyControl(full, row) },
787 this.updateLiNotesCount(li, row);
789 // show which PO this lineitem is a member of
790 if(li.purchase_order() && !this.isPO) {
792 this.poCache[li.purchase_order()] =
793 this.poCache[li.purchase_order()] ||
794 fieldmapper.standardRequest(
795 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
797 this.authtoken, li.purchase_order(), {
798 "flesh_price_summary": true,
799 "flesh_provider" : true,
800 "flesh_lineitem_count": true
803 if(po && !this.isMeta) {
804 openils.Util.show(nodeByName('po', row), 'inline');
805 var link = nodeByName('po_link', row);
806 link.setAttribute('href', oilsBasePath +
807 '/acq/po/view/' + li.purchase_order() +
808 '?focus_li=' + li.id() +
809 '&source=' + encodeURIComponent(location.pathname + location.search)
811 link.innerHTML += po.name();
813 openils.Util.show(nodeByName('pro', row), 'inline');
814 link = nodeByName('pro_link', row);
815 link.setAttribute('href', oilsBasePath + '/conify/global/acq/provider/' + po.provider().id())
816 link.innerHTML += po.provider().code();
820 // show which picklist this lineitem is a member of
821 if(li.picklist() && (this.isPO || this.isMeta || this.isUni)) {
823 this.plCache[li.picklist()] =
824 this.plCache[li.picklist()] ||
825 fieldmapper.standardRequest(
826 ['open-ils.acq', 'open-ils.acq.picklist.retrieve.authoritative'],
827 {params: [this.authtoken, li.picklist()]});
829 if (pl.name() == "") {
830 openils.Util.show(nodeByName("bib_origin", row), "inline");
834 openils.Util.show(nodeByName('pl', row), 'inline');
835 var link = nodeByName('pl_link', row);
836 link.setAttribute('href', oilsBasePath +
837 '/acq/picklist/view/' + li.picklist() +
838 '?focus_li=' + li.id() +
839 '&source=' + encodeURIComponent(location.pathname + location.search)
841 link.innerHTML += pl.name();
846 var countNode = nodeByName('count', row);
847 var count = li.item_count() || 0;
848 if (typeof(this._copy_count_cb) == "function") {
849 this._copy_count_cb(li.id(), count);
851 countNode.innerHTML = count;
852 countNode.id = 'acq-lit-copy-count-label-' + li.id();
855 var priceInput = dojo.query('[name=price]', row)[0];
856 priceInput.value = li.estimated_unit_price() || '';
857 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
859 // show either "mark received" or "unreceive" as appropriate
860 this.updateLiState(li, row);
862 if (skip_final_placement) {
866 // the last LI may be rendered after the call to show('list'),
867 // so make sure it's focused if necessary.
868 if (this.focusLineitem == li.id())
872 this._liCountClaims = function(li) {
874 for (var i = 0; i < li.lineitem_details().length; i++)
875 total += li.lineitem_details()[i].claims().length;
879 this._findLiRow = function(li) {
880 return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
883 this.reconsiderClaimControl = function(li, row) {
884 if (!row) row = this._findLiRow(li);
885 var option = nodeByName("action_manage_claims", row);
886 var eligible = this.claimEligibleLidByLi[li.id()].length;
887 var count = this._liCountClaims(li);
889 option.disabled = !(count || eligible);
891 dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
892 option.onclick = function() { self.claimDialog.show(li); };
895 this.clearEligibility = function(li) {
896 this.claimEligibleLidByLi[li.id()] = [];
898 if (li.lineitem_details()) {
899 li.lineitem_details().forEach(
900 function(lid) { delete self.claimEligibleLid[lid.id()]; }
904 if (this.copyCache) {
906 for (var k in this.copyCache) {
907 if (this.copyCache[k].lineitem() == li.id())
911 function(k) { delete self.claimEligibleLid[k]; }
916 this.applyOrderIdentValues = function() {
917 this._identValuesInFlight =
918 openils.Util.objectProperties(this.liCache).length;
919 for (var liId in this.liCache) {
920 this._applyOrderIdentValue(this.liCache[liId]);
924 // returns true if request was sent
925 this._applyOrderIdentValue = function(li, oncomplete) {
928 console.log('applying ident value for lineitem ' + li.id());
931 var row = dojo.query('[li=' + li.id() + ']')[0];
933 // find the selected ident value
934 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
935 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
936 var name = typeSel.options[typeSel.selectedIndex].value;
937 var val = typeSel._cbox.attr('value');
939 console.log("selected ident is " + val);
941 // it differs from the existing ident value, update it
942 var oldIdent = self.getLiOrderIdent(li);
944 oldIdent.attr_name() == name &&
945 oldIdent.attr_value() == val) {
946 console.log('selected ident attr matches existing attr');
947 if (--this._identValuesInFlight == 0) {
948 if (oncomplete) oncomplete(li);
949 else location.href = location.href;
954 // see if the selected ident value is represented
955 // by an existing lineitem attr
958 typeSel._cbox.store.fetch({
959 query : {attr_value : val},
960 onItem : function(item) {
961 console.log('found existing attr for ident value');
962 args.source_attr_id = li.attributes().filter(
963 function(attr) { return attr.id() == item.id[0] }
969 if (!args.source_attr_id) {
970 // user entered new text in the combobox
971 // so we need to create a new attr
972 console.log('creating new ident attr');
973 args.lineitem_id = li.id();
974 args.attr_name = name;
975 args.attr_value = val;
978 fieldmapper.standardRequest(
979 ['open-ils.acq', 'open-ils.acq.lineitem.order_identifier.set'],
981 params : [openils.User.authtoken, args],
982 oncomplete : function() {
983 console.log('order_ident oncomplete');
984 if (--self._identValuesInFlight == 0) {
985 if (oncomplete) oncomplete(li);
986 else location.href = location.href;
988 console.log(self._identValuesInFlight + ' still in flight');
996 this.getLiOrderIdent = function(li) {
997 var attrs = li.attributes();
998 if (!attrs) return null;
1002 attr.attr_type() == 'lineitem_local_attr_definition' &&
1003 openils.Util.isTrue(attr.order_ident())
1009 this.drawOrderIdentSelector = function(li, row) {
1011 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
1012 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
1014 var attrs = li.attributes();
1016 // limit to MARC attr defs
1017 attrs = attrs.filter(
1019 return (attr.attr_type() == 'lineitem_marc_attr_definition');
1023 var identAttr = this.getLiOrderIdent(li);
1026 // collect the values for each type of identifier
1027 // find a reasonable default identifier type to render
1031 dojo.forEach(['isbn', 'upc', 'issn'],
1034 // collect the values for this attr name
1035 values[name] = attrs.filter(
1037 return (attr.attr_name() == name)
1041 // select a reasonable default name in the type-selector
1045 if (identAttr.attr_name() == name)
1047 } else if (values[name].length) {
1052 dojo.forEach(typeSel.options, function(opt) {
1053 if (opt.value == name) {
1054 opt.selected = true;
1063 function updateOrderIdent(val) {
1064 self._identValuesInFlight = 1;
1065 self._applyOrderIdentValue(
1068 self.refreshLineitem(li);
1073 // replace the ident combobox with a new
1074 // one for the selected ident type
1075 function changeComboBox(sel) {
1076 var name = sel.options[sel.selectedIndex].value;
1078 var td = dojo.query('[name=order_ident_value]', row)[0];
1079 if (td.childNodes[0])
1080 dojo.destroy(td.childNodes[0]);
1082 var store = new dojo.data.ItemFileWriteStore({
1083 data : acqlia.toStoreData(values[name])
1086 var cbox = new dijit.form.ComboBox(
1088 labelAttr : 'attr_value',
1089 searchAttr : 'attr_value'
1091 dojo.create('div', {}, td)
1096 // set the value for the cbox
1097 if (values[name].length) {
1098 var orderIdent = self.getLiOrderIdent(li);
1100 if (orderIdent && orderIdent.attr_name() == name) {
1101 cbox.attr('value', orderIdent.attr_value());
1103 cbox.attr('value', values[name][0].attr_value());
1107 if (!self.orderIdentAllowed)
1108 cbox.attr('disabled', true);
1111 cbox._lineitem = li;
1112 dojo.connect(cbox, 'onChange', updateOrderIdent);
1115 changeComboBox(typeSel); // force the initial draw
1116 typeSel.onchange = function() {changeComboBox(typeSel)};
1119 this.testOrderIdentPerms = function(org, callback) {
1121 new openils.User().getPermOrgList(
1122 'ACQ_SET_LINEITEM_IDENTIFIER',
1124 console.log('found orgs = ' + orgs);
1125 for (var i = 0; i < orgs.length; i++) {
1126 if (Number(orgs[i]) == Number(org)) {
1127 self.orderIdentAllowed = true;
1128 if (callback) callback();
1132 if (callback) callback();
1138 this.checkClaimEligibility = function(li, callback, row) {
1139 /* Assume always eligible, i.e. from this interface we don't care about
1140 * claim eligibility any more. this is where the user would force a
1142 this.clearEligibility(li);
1143 this.claimEligibleLidByLi[li.id()] = li.lineitem_details().map(
1144 function(lid) { return lid.id(); }
1146 li.lineitem_details().forEach(
1147 function(lid) { self.claimEligibleLid[lid.id()] = true; }
1149 this.reconsiderClaimControl(li, row);
1150 if (callback) callback(li);
1152 this.clearEligibility(li);
1153 fieldmapper.standardRequest(
1154 ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
1155 "params": [openils.User.authtoken, {"lineitem": li.id()}],
1157 "onresponse": function(r) {
1158 if (r = openils.Util.readResponse(r)) {
1159 self.claimEligibleLidByLi[li.id()].push(
1162 self.claimEligibleLid[r.lineitem_detail()] = true;
1165 "oncomplete": function() {
1166 self.reconsiderClaimControl(li, row);
1167 if (typeof(callback) == "function")
1175 this.updateLiNotesCount = function(li, row) {
1176 if (!row) row = this._findLiRow(li);
1178 var has_notes = (li.lineitem_notes().filter(
1179 function(o) { return Boolean (o.alert_text()); }
1182 /* U+2691 is the code point for a filled-in flag character */
1183 nodeByName("notes_alert_flag", row).innerHTML =
1184 has_notes ? "⚑" : "";
1185 nodeByName("noteslink", row).style.fontStyle =
1186 has_notes ? "italic" : "normal";
1187 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
1190 /* XXX NOT related to _updateLiState(). rethink */
1191 this.updateLiState = function(li, row) {
1192 if (!row) row = this._findLiRow(li);
1194 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
1195 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
1197 // always allow access to LI history
1198 nodeByName('action_view_history', row).onclick =
1199 function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
1201 /* handle row coloring for based on LI state */
1202 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1203 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
1205 // Expose invoice actions for any lineitem that is linked to a PO
1206 if (li.purchase_order()) {
1207 openils.Util.show(nodeByName("invoices_span", row), "inline");
1208 var link = nodeByName("invoices_link", row);
1209 link.onclick = function() {
1210 openils.XUL.newTabEasy(
1211 oilsBasePath + "/acq/search/unified?so=" +
1212 base64Encode({"jub":[{"id": li.id()}]}) + "&rt=invoice"
1220 * If we haven't fleshed the lineitem_details, default to allowing access to the
1221 * holdings maintenence actions. The alternative is to flesh LIDs on every lineitem,
1222 * but that will add to page render time. Let's see if this will suffice...
1224 var lids = li.lineitem_details();
1226 (lids && !lids.filter(function(lid) { return lid.eg_copy_id() })[0] )) {
1228 actUpdateBarcodes.disabled = false;
1229 actUpdateBarcodes.onclick = function() {
1230 self.showRealCopyEditUI(li);
1231 nodeByName("action_none", row).selected = true;
1233 actHoldingsMaint.disabled = false;
1234 actHoldingsMaint.onclick =
1235 self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
1238 var state_cell = nodeByName("li_state_" + li.state(), row);
1240 // re-hide any state label nodes which may have been un-hidden
1241 // through previous actions.
1242 dojo.query('[state-label]', row).forEach(function(node) {
1243 openils.Util.hide(node)
1246 if (li.state() == 'cancelled') {
1247 if(typeof li.cancel_reason() == "object") {
1249 // clear the stock "Canceled" label, since we have more
1250 // information to replace it with.
1251 state_cell.innerHTML = '';
1253 var holds_state = dojo.create(
1255 "style": "border-bottom: 1px dashed #000;",
1256 "innerHTML": li.cancel_reason().label()
1257 }, state_cell, "only"
1261 "label": "<em>" + li.cancel_reason().label() +
1262 "</em><br />" + li.cancel_reason().description(),
1263 "connectId": [holds_state]
1264 }, dojo.create("span", null, state_cell, "last")
1267 if (li.cancel_reason().keep_debits() == 't') {
1268 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1269 openils.Util.addCSSClass(row, "oils-acq-li-state-delayed");
1272 console.log('li cancel_reason is un-fleshed. Please fix');
1276 openils.Util.show(state_cell);
1280 this._setAlertStore = function() {
1281 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
1283 "data": acqliat.toStoreData(
1286 "owning_lib": aou.orgNodeTrail(
1287 aou.findOrgUnit(openils.User.user.ws_ou())
1288 ).map(function(o) { return o.id(); })
1294 acqLitAlertAlertText.setValue(); /* make the store "live" */
1295 acqLitAlertAlertText._store_ready = true;
1299 * Draws and shows the lineitem notes pane
1301 this.drawLiNotes = function(li) {
1303 this.focusLineitem = li.id();
1305 if (!acqLitAlertAlertText._store_ready)
1306 this._setAlertStore();
1309 li.lineitem_notes().sort(
1311 if(a.edit_time() < b.edit_time()) return 1;
1317 while(this.liNotesTbody.childNodes[0])
1318 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
1321 acqLitCreateNoteSubmit.onClick = function() {
1322 var value = acqLitCreateNoteText.attr('value');
1324 var note = new fieldmapper.acqlin();
1327 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
1330 note.lineitem(li.id());
1332 self.updateLiNotes(li, note);
1333 acqLitCreateNoteVendorPublic.attr("checked", false);
1334 acqLitCreateNoteText.attr("value", "");
1337 acqLitCreateAlertSubmit.onClick = function() {
1338 if (!acqLitAlertAlertText.item) {
1339 alert(localeStrings.ALERT_UNSELECTED);
1343 var alert_text = new fieldmapper.acqliat().fromStoreItem(
1344 acqLitAlertAlertText.item
1346 var value = acqLitAlertNoteValue.attr("value") || "";
1348 var note = new fieldmapper.acqlin();
1350 note.lineitem(li.id());
1352 note.alert_text(alert_text);
1354 self.updateLiNotes(li, note);
1357 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
1361 * Draws a single lineitem note in the notes pane
1363 this.addLiNote = function(li, note) {
1364 if(note.isdeleted()) return;
1366 var row = self.liNotesRow.cloneNode(true);
1367 nodeByName("value", row).innerHTML = note.value();
1368 var alert_node = nodeByName("alert_code", row);
1369 if (note.alert_text()) {
1370 alert_node.innerHTML = dojo.string.substitute(
1372 aou.findOrgUnit(note.alert_text().owning_lib()).shortname(),
1373 note.alert_text().code()
1376 if (note.alert_text().description()) {
1379 "connectId": [alert_node],
1380 "label": note.alert_text().description()
1381 }, dojo.create("span", null, alert_node, "after")
1386 if (openils.Util.isTrue(note.vendor_public()))
1387 nodeByName("vendor_public", row).innerHTML =
1388 localeStrings.VENDOR_PUBLIC;
1390 nodeByName("delete", row).onclick = function() {
1391 note.isdeleted(true);
1392 self.liNotesTbody.removeChild(row);
1393 self.updateLiNotes(li);
1396 if(note.edit_time()) {
1397 nodeByName("edit_time", row).innerHTML =
1398 dojo.date.locale.format(
1399 dojo.date.stamp.fromISOString(note.edit_time()),
1400 {formatLength:'short'});
1403 self.liNotesTbody.appendChild(row);
1407 * Updates any new/changed/deleted notes on the server
1409 this.updateLiNotes = function(li, newNote) {
1415 notes = li.lineitem_notes().filter(
1417 if(note.ischanged() || note.isnew() || note.isdeleted())
1423 if(notes.length == 0) return;
1424 progressDialog.show();
1426 fieldmapper.standardRequest(
1427 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
1429 params : [this.authtoken, notes],
1430 onresponse : function(r) {
1431 var resp = openils.Util.readResponse(r);
1436 // remove the old changed notes
1438 dojo.forEach(li.lineitem_notes(),
1440 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
1444 li.lineitem_notes(list);
1447 progressDialog.hide();
1448 self.updateLiNotesCount(li);
1449 self.drawLiNotes(li);
1453 progressDialog.update(resp);
1454 var newnote = resp.note;
1456 if(!newnote.isdeleted()) {
1457 newnote.isnew(false);
1458 newnote.ischanged(false);
1459 li.lineitem_notes().push(newnote);
1466 this.updateLiPrice = function(input, li) {
1468 var price = input.value;
1469 if(Number(price) == Number(li.estimated_unit_price())) return;
1471 fieldmapper.standardRequest(
1472 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
1473 { async : false, // redundant w/ timeout
1475 params : [this.authtoken, li.id(), price],
1476 oncomplete : function(r) {
1477 openils.Util.readResponse(r);
1478 li.estimated_unit_price(price); // update local copy
1481 * If this is a PO and every visible lineitem has a price,
1482 * check again to see if this PO can be activated. Note that
1483 * every visible lineitem having a price does not guarantee it can
1484 * be activated, which is why we still make the call. Having a price
1485 * set for every visiable lineitem is just the lowest barrier to entry.
1488 var priceNodes = dojo.query('[name=price]', dojo.byId('acq-lit-tbody'));
1490 dojo.forEach(priceNodes, function(node) { if (node.value == '') allSet = false});
1491 if (allSet) checkCouldActivatePo();
1492 refreshPOSummaryAmounts();
1499 this.removeLineitem = function(liId) {
1500 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
1501 delete this.liCache[liId];
1502 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
1505 this.drawInfo = function(liId) {
1506 this.focusLineitem = liId;
1507 if (!this._isRelatedViewer) {
1508 var d = dojo.byId("acq-lit-info-related");
1509 if (!this.relCache[liId]) {
1510 fieldmapper.standardRequest(
1513 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
1516 "params": [openils.User.authtoken, liId],
1517 "onresponse": function(r) {
1518 self.relCache[liId] = openils.Util.readResponse(r);
1519 nodeByName("related_number", d).innerHTML =
1520 self.relCache[liId];
1522 self.relCache[liId] >1 ? "show" : "hide"
1528 nodeByName("related_number", d).innerHTML = this.relCache[liId];
1529 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
1534 openils.acq.Lineitem.fetchAttrDefs(
1536 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
1541 this.toggleInlineCopies = function() {
1542 // if any inline copies are not displayed,
1543 // display them all otherwise, hide them all.
1545 var displayAll = false;
1547 for (var liId in this.liCache) {
1548 if (!this.inlineCopiesVisible(liId)) {
1554 for (var liId in this.liCache) {
1555 var row = dojo.byId('acq-inline-copies-row-' + liId);
1557 if (!row || row._hidden) {
1558 this.drawInlineCopies(liId);
1560 } else { // hide all
1562 // drawInlineCopies() on a visible row will hide it.
1563 this.drawInlineCopies(liId);
1570 this.inlineCopiesVisible = function(liId) {
1571 var row = dojo.byId('acq-inline-copies-row-' + liId);
1572 return (row && !row._hidden);
1575 this.refreshInlineCopies = function(all, reFetch) {
1577 var liIds = this.inlineCopiesNeedingRefresh;
1578 if (all) liIds = openils.Util.objectProperties(liCache);
1579 liIds.forEach(function(liId) {
1580 if (self.inlineCopiesVisible(liId)) {
1581 self.drawInlineCopies(liId, reFetch); // hide
1582 self.drawInlineCopies(liId, reFetch); // re-draw
1587 // draw inline copy table. if the table is
1588 // already visible, hide the table as-is
1589 // reFetch forces a retrieval of the lineitem and
1590 // copies from the server. otherwise the locally
1591 // cached version of each is used.
1592 this.drawInlineCopies = function(liId, reFetch) {
1595 // find or create the row where the inline copies table will live
1596 var containerRow = dojo.byId('acq-inline-copies-row-' + liId);
1597 var liRow = dojo.query('[li=' + liId + ']')[0];
1599 if (!containerRow) {
1601 // build the inline copies container row and add it to
1602 // the DOM directly after the primary lineitem row
1604 containerRow = self.inlineCopyContainer.cloneNode(true);
1605 containerRow.id = 'acq-inline-copies-row-' + liId;
1607 if (liRow.nextSibling) {
1608 self.tbody.insertBefore(containerRow, liRow.nextSibling);
1610 self.tbody.appendChild(containerRow);
1615 // toggle the visible state
1616 containerRow._hidden = !containerRow._hidden;
1617 openils.Util.toggle(containerRow, 'table-row');
1619 if (containerRow._hidden) return; // hide only
1622 var handler = function(li) {
1624 var tbody = dojo.query(
1625 '[name=acq-li-inline-copies-tbody]',
1628 // reset the table before adding copy rows
1629 while (tbody.childNodes[0])
1630 tbody.removeChild(tbody.childNodes[0]);
1632 if(li.lineitem_details().length == 0) {
1634 self.inlineNoCopies.cloneNode(true));
1635 return; // no copies to show
1638 // add a row to the inline copy table for each copy
1639 dojo.forEach(li.lineitem_details(),
1641 var row = self.inlineCopyTemplate.cloneNode(true);
1642 tbody.appendChild(row);
1643 self.addInlineCopy(li, copy, row);
1648 this._fetchLineitem(liId, handler, reFetch);
1651 /** Draw read-only copy widgets for inline copies */
1652 this.addInlineCopy = function(li, copy, row) {
1655 dojo.forEach(liDetailFields,
1658 var widget = new openils.widget.AutoFieldWidget({
1661 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1662 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1663 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1665 parentNode : dojo.query('[name=' + field + ']', row)[0],
1674 /* For a given list of lineitem ids, build a list of full lineitems
1675 * re-using the fetching logic that is otherwise typical to use in this
1678 * If we've already got a lineitem in the cache, just use that.
1680 * Once we've built a list of lineitems, call callback(thatlist).
1682 this.fetchLineitemsById = function(id_list, callback) {
1683 var total = id_list.length;
1684 var result_list = [];
1686 var inner = function(li) {
1687 result_list.push(li)
1689 callback(result_list);
1692 id_list.forEach(function(id) { self._fetchLineitem(id, inner); });
1695 this._fetchLineitem = function(liId, handler, force) {
1697 var li = this.liCache[liId];
1698 if(li && li.marc() && li.lineitem_details() && !force)
1701 fieldmapper.standardRequest(
1702 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
1705 params: [self.authtoken, liId, {
1707 flesh_cancel_reason: true,
1708 flesh_li_details: true,
1710 flesh_fund_debit: true }],
1712 oncomplete: function(r) {
1713 var li = openils.Util.readResponse(r);
1714 self.liCache[liId] = li;
1721 this._drawInfo = function(li) {
1723 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
1725 if(li.eg_bib_id()) {
1726 openils.Util.hide('acq-lit-marc-order-record-label');
1727 openils.Util.hide(acqLitEditOrderMarc.domNode);
1728 openils.Util.show('acq-lit-marc-real-record-label');
1730 openils.Util.show('acq-lit-marc-order-record-label');
1731 openils.Util.show(acqLitEditOrderMarc.domNode);
1732 openils.Util.hide('acq-lit-marc-real-record-label');
1735 this.drawMarcHTML(li);
1736 this.infoTbody = dojo.byId('acq-lit-info-tbody');
1739 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
1740 while(this.infoTbody.childNodes[0])
1741 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
1743 for(var i = 0; i < li.attributes().length; i++) {
1744 var attr = li.attributes()[i];
1745 var row = this.infoRow.cloneNode(true);
1747 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
1748 var name = openils.acq.Lineitem.attrDefs[type].filter(
1750 return (a.code() == attr.attr_name());
1752 ).pop().description();
1754 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
1755 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
1756 this.infoTbody.appendChild(row);
1759 if (!this._isRelatedViewer) {
1760 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
1761 oilsBasePath + "/acq/lineitem/related/" + li.id();
1764 // if a top scroll point is defined, jump up to it here
1765 var node = dojo.byId('oils-scroll-to-top');
1766 if (node) dijit.scrollIntoView(node);
1769 this.generateMakeRecTab = function(bib_id,default_view, row) {
1773 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
1776 show_nav_buttons : true,
1777 show_print_button : true,
1778 opac_url : xulG.url_prefix('opac_rdetail|' + bib_id),
1779 default_view : default_view
1783 if(row) nodeByName("action_none", row).selected = true;
1787 this.drawMarcHTML = function(li) {
1788 var params = [null, true, li.marc()];
1790 params = [li.eg_bib_id(), true];
1792 fieldmapper.standardRequest(
1793 ['open-ils.search', 'open-ils.search.biblio.record.html'],
1796 oncomplete: function(r) {
1797 dojo.byId('acq-lit-marc-div').innerHTML =
1798 openils.Util.readResponse(r);
1804 this.drawCopies = function(liId, force_fetch) {
1805 this.focusLineitem = liId;
1806 if (typeof force_fetch == "undefined")
1807 force_fetch = false;
1809 var cgi = new openils.CGI();
1810 var source = cgi.param('source');
1811 if (source && source.match(/invoice/)) {
1812 // got here from the invoice page, show the 'return-to-invoice' button
1813 var cgi = new openils.CGI({url : source});
1814 cgi.param('focus_li', liId);
1815 openils.Util.show(dojo.byId('acq-lit-copies-back-to-invoice-button-wrapper'), 'inline');
1816 var button = dojo.byId('acq-lit-copies-back-to-invoice-button');
1817 button.onclick = function() { location.href = cgi.url() };
1820 openils.acq.Lineitem.fetchAndRender(liId, {},
1821 function(li, html) {
1822 dojo.byId('acq-lit-copies-li-summary').innerHTML = html;
1826 this.show('copies');
1828 this.copyCache = {};
1829 this.copyWidgetCache = {};
1830 this.oldCopyWidgetCache = {};
1831 this.virtDfaCounts = {};
1832 this.realDfaCache = {};
1835 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
1836 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
1837 acqLitCopyCountInput.attr('value', '0');
1839 if (this.isPO && PO && PO.order_date()) {
1840 // prevent adding copies to activated POs
1841 acqLitCopyCountInput.attr('disabled', true);
1842 acqLitAddCopyCount.attr('disabled', true);
1845 while(this.copyTbody.childNodes[0])
1846 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
1848 this._drawBatchCopyWidgets();
1850 this._drawDistribApplied(liId);
1852 this._fetchDistribFormulas(
1854 openils.acq.Lineitem.fetchAttrDefs(
1856 self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch);
1863 this._saveDistribAppliedTemplates = function() {
1864 if (!this._appliedDistribTemplate) {
1865 this._appliedDistribTemplate =
1866 dojo.byId("acq-lit-distrib-applied-tbody").
1867 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
1868 dojo.attr(this._appliedDistribTemplate, "id");
1872 this._drawDistribApplied = function(liId) {
1873 /* Build this table while hidden to prevent rendering artifacts */
1874 openils.Util.hide("acq-lit-distrib-applied-tbody");
1876 this._saveDistribAppliedTemplates();
1878 /* Remove any rows in the table from previous populations */
1879 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
1880 forEach(dojo.destroy);
1882 /* Unregister all dijits previously created (for some reason this isn't
1883 * covered by the above destroy calls). */
1884 dijit.registry.forEach(
1885 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
1888 /* Populate the table with our liId */
1890 fieldmapper.standardRequest(
1892 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
1895 "params": [self.authtoken, liId],
1896 "onresponse": function(r) {
1897 var dfa = openils.Util.readResponse(r);
1900 self.realDfaCache[dfa.id()] = dfa;
1901 self._drawDistribAppliedUnit(dfa);
1904 "oncomplete": function() {
1905 /* Reveal built table */
1908 "acq-lit-distrib-applied-tbody", "table-row-group"
1916 this._drawDistribAppliedUnit = function(dfa) {
1917 var new_row = false;
1918 var row = dojo.query(
1919 'tr[formula="' + dfa.formula().id() + '"]',
1920 "acq-lit-distrib-applied-tbody"
1925 row = dojo.clone(this._appliedDistribTemplate);
1926 dojo.attr(row, "formula", dfa.formula().id());
1927 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
1930 var td = dojo.query("td", row)[0];
1932 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1933 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1936 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1938 new dijit.form.Button(
1940 "onClick": function() {
1941 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1942 self.deleteDfa(dfa);
1945 /* XXX I /cannot/ make the following work in as a CSS class
1946 * for some reason. So frustrating... */
1947 "style": function(id) {
1949 "font-weight: bold; color: #c00;" :
1951 }(dfa.id()) + "margin: 0 6px;display: inline;"
1952 }, "dfa-button-" + dfa.id()
1956 "connectId": ["dfa-button-" + dfa.id()],
1957 "label": dojo.string.substitute(
1958 localeStrings.DFA_TIP, dfa.id() > 0 ? [
1959 openils.User.formalName(dfa.creator()),
1960 dojo.date.locale.format(
1961 dojo.date.stamp.fromISOString(dfa.create_time()),
1962 {"formatLength":"short"}
1964 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
1966 }, "dfa-tip-" + dfa.id()
1970 this.deleteDfa = function(dfa) {
1971 if (dfa.id() > 0) { /* real */
1972 this.pcrud.eliminate(
1975 "oncomplete": function() {
1976 self._removeDistribApplied(dfa.id());
1977 delete self.realDfaCache[dfa.id()];
1981 } else { /* virtual */
1982 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
1983 this.virtDfaCounts[dfa.formula().id()] = 0;
1984 /* hasn't been saved yet, so no need to do anything server side */
1985 this._removeDistribApplied(dfa.id());
1990 this._removeDistribApplied = function(dfaId) {
1991 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
1992 dijit.registry.forEach(
1993 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
1995 this._removeDistribAppliedEmptyRows();
1998 this._removeAllDistribAppliedVirtual = function() {
1999 /* Unregister dijits */
2000 dijit.registry.forEach(
2001 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
2003 this._removeDistribAppliedEmptyRows();
2006 this._removeDistribAppliedEmptyRows = function() {
2007 /* Remove any rows with no DFA at all */
2008 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
2010 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
2016 * Insert a new row into the distribution formula selection form
2018 this._addDistribFormulaRow = function() {
2021 if (!self.distribForms) {
2022 // no formulas, hide the form
2023 openils.Util.hide('acq-lit-distrib-formula-table');
2027 if(!this.distribFormulaTemplate)
2028 this.distribFormulaTemplate =
2029 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
2031 var row = this.distribFormulaTemplate.cloneNode(true);
2032 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
2034 this.dfSelector = new dijit.form.FilteringSelect(
2035 {"labelAttr": "dynLabel", "labelType": "html"},
2036 nodeByName("selector", row)
2038 this._updateFormulaStore();
2039 this.dfSelector.fetchProperties =
2040 {"sort": [{"attribute": "use_count", "descending": true}]};
2042 var apply = new dijit.form.Button(
2043 {"label": localeStrings.APPLY},
2044 nodeByName('set_button', row)
2047 var reset = new dijit.form.Button(
2048 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
2049 nodeByName("reset_button", row)
2052 dojo.connect(apply, 'onClick',
2054 var form_id = self.dfSelector.attr("value");
2055 if(!form_id) return;
2056 self._applyDistribFormula(form_id);
2057 reset.attr("disabled", false);
2061 dojo.connect(reset, 'onClick',
2063 self.restoreCopyFieldsBeforeDF();
2064 self.virtDfaCounts = {};
2065 self.virtDfaId = -1;
2067 self._updateFormulaStore();
2068 self._removeAllDistribAppliedVirtual();
2069 reset.attr("disabled", "true");
2076 * Applies a distrib formula to the current set of copies
2078 this._applyDistribFormula = function(formula) {
2079 if(!formula) return;
2081 formula = this.distribForms.filter(
2082 function(form) { return form.id() == formula; }
2085 var copyRows = dojo.query('tr', self.copyTbody);
2087 if (this.dfeOffset >= copyRows.length) {
2088 alert(localeStrings.OUT_OF_COPIES);
2092 var entries_applied = 0;
2094 var rowIndex = this.dfeOffset;
2095 rowIndex < copyRows.length;
2099 var row = copyRows[rowIndex];
2100 var copy_id = row.getAttribute('copy_id');
2101 var copyWidgets = this.copyWidgetCache[copy_id];
2102 var entryIndex = this.dfeOffset;
2105 // find the correct entry for the current row
2106 dojo.forEach(formula.entries(),
2109 entryIndex += e.item_count();
2110 if(entryIndex > rowIndex)
2118 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
2119 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
2122 this.saveCopyFieldsBeforeDF(copy_id);
2123 this._copy_fields_for_acqdf.forEach(
2125 if(entry[field]()) {
2126 copyWidgets[field].attr('value', (entry[field]()));
2133 if (entries_applied) {
2134 this.virtDfaCounts[formula.id()] =
2135 ++(this.virtDfaCounts[formula.id()]) || 1;
2136 this._updateFormulaStore();
2137 this._drawDistribAppliedUnit(
2139 var dfa = new acqdfa();
2140 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
2143 this.dfeOffset += entries_applied;
2148 * This function updates the DF store for the dropdown so that use_counts
2149 * can reflect DF applications from this session before they're saved
2152 this._updateFormulaStore = function() {
2153 this.dfSelector.store = new dojo.data.ItemFileReadStore(
2155 "data": self._labelFormulasWithCounts(
2156 acqdf.toStoreData(self.distribForms)
2162 this.saveCopyFieldsBeforeDF = function(copy_id) {
2164 if (!this.oldCopyWidgetCache[copy_id]) {
2165 var copyWidgets = this.copyWidgetCache[copy_id];
2167 this.oldCopyWidgetCache[copy_id] = {};
2168 this._copy_fields_for_acqdf.forEach(
2170 self.oldCopyWidgetCache[copy_id][f] =
2171 copyWidgets[f].attr("value");
2177 this.restoreCopyFieldsBeforeDF = function() {
2179 for (var copy_id in this.oldCopyWidgetCache) {
2180 this._copy_fields_for_acqdf.forEach(
2182 self.copyWidgetCache[copy_id][f].attr(
2183 "value", self.oldCopyWidgetCache[copy_id][f]
2190 this._labelFormulasWithCounts = function(store_data) {
2191 for (var key in store_data.items) {
2192 var obj = store_data.items[key];
2193 obj.use_count = Number(obj.use_count); /* needed for sorting */
2195 if (this.virtDfaCounts[obj.id])
2196 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
2198 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
2199 obj.use_count + "]</span> " + obj.name;
2205 * This method formerly would not refetch the DF formulas if they'd been
2206 * loaded already, but now it always re-fetches, since use_count changes.
2208 /** TODO: port distrib-formula selector to autofieldwidget+pcrud/dojo store */
2209 this._fetchDistribFormulas = function(onload) {
2210 fieldmapper.standardRequest(
2212 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
2215 "params": [openils.User.authtoken, 0, 500],
2216 "oncomplete": function(r) {
2217 self.distribForms = openils.Util.readResponse(r);
2218 if(!self.distribForms || self.distribForms.length == 0) {
2219 self.distribForms = [];
2221 self._addDistribFormulaRow();
2228 this._drawBatchCopyWidgets = function() {
2229 var row = this.copyBatchRow;
2230 dojo.forEach(liDetailBatchFields,
2232 if(self.copyBatchRowDrawn) {
2233 self.copyBatchWidgets[field].attr('value', null);
2235 var args = self.afwCopyFieldArgs(field, "CREATE_PICKLIST");
2236 args.parentNode = dojo.query('[name='+field+']', row)[0];
2238 var widget = new openils.widget.AutoFieldWidget(args);
2241 if (field == "fund" && w.store)
2242 self._ensureCSSFundClasses(w.store);
2243 self.copyBatchWidgets[field] = w;
2246 if (field == "fund") {
2248 widget.widget, "onChange", function(val) {
2249 self._updateFundSelectorStyle(widget, val);
2256 this.copyBatchRowDrawn = true;
2259 this.batchCopyUpdate = function() {
2261 for(var k in this.copyWidgetCache) {
2262 var cache = this.copyWidgetCache[k];
2263 dojo.forEach(liDetailBatchFields, function(f) {
2264 var newval = self.copyBatchWidgets[f].attr('value');
2265 if(newval) cache[f].attr('value', newval);
2270 this._drawCopies = function(li) {
2273 // this button sets the total number of copies for a given lineitem
2274 acqLitAddCopyCount.onClick = function() {
2275 var count = acqLitCopyCountInput.attr('value');
2278 while(self.copyCount() < count)
2281 // delete rows if necessary
2282 var diff = self.copyCount() - count;
2284 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
2285 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
2286 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
2288 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2294 if(li.lineitem_details().length > 0) {
2295 dojo.forEach(li.lineitem_details(),
2297 self.addCopy(li, copy);
2305 this.copyCount = function() {
2307 for(var id in this.copyCache) {
2308 if(!this.copyCache[id].isdeleted())
2314 this.virtCopyId = -1;
2315 this.addCopy = function(li, copy) {
2316 var row = this.copyRow.cloneNode(true);
2317 this.copyTbody.appendChild(row);
2321 copy = new fieldmapper.acqlid();
2323 copy.id(this.virtCopyId--);
2324 copy.lineitem(li.id());
2327 this.copyCache[copy.id()] = copy;
2328 row.setAttribute('copy_id', copy.id());
2329 self.copyWidgetCache[copy.id()] = {};
2331 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2333 var rcvr = copy.receiver();
2335 if (!userCache[rcvr]) {
2336 if(rcvr == openils.User.user.id()) {
2337 userCache[rcvr] = openils.User.user;
2339 userCache[rcvr] = fieldmapper.standardRequest(
2340 ['open-ils.actor', 'open-ils.actor.user.retrieve'],
2341 {params: [openils.User.authtoken, rcvr]}
2345 dojo.query('[name=receiver]', row)[0].innerHTML = userCache[rcvr].usrname();
2348 dojo.forEach(liDetailFields,
2351 if (field == "fund") {
2352 searchFilter = (copy.fund() ?
2353 {"-or": {"active": "t", "id": copy.fund()}} :
2355 searchFilter.org = fundSearchFilter.org;
2357 searchFilter = null;
2360 var readOnly = false;
2362 // TODO: Add support for changing the owning_lib after real copies have been made.
2363 // owning_lib is order data as much as its item data
2364 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
2368 // TODO: add support for changing the fund after debits have been created
2369 // Note: invoicing allows the change
2370 if(copy.fund_debit() && field == 'fund') {
2375 var widget = new openils.widget.AutoFieldWidget({
2378 labelFormat : (field == 'fund') ? fundLabelFormat : null,
2379 searchFormat : (field == 'fund') ? fundSearchFormat : null,
2380 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
2381 searchFilter : searchFilter,
2382 noCache: (field == "fund"),
2384 parentNode : dojo.query('[name='+field+']', row)[0],
2385 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2386 readOnly : readOnly,
2387 orgDefaultsToWs : true
2391 // make sure we capture the value from any async widgets
2394 if (field == "fund" && w.store)
2395 self._ensureCSSFundClasses(w.store);
2398 copy[field](ww.getFormattedValue())
2400 self.copyWidgetCache[copy.id()][field] = w;
2402 dojo.connect(w, 'onChange',
2404 if (field == "fund")
2405 self._updateFundSelectorStyle(widget, val);
2407 if (!readOnly && (copy.isnew() || val != copy[field]())) {
2408 // prevent setting ischanged() automatically on widget load for existing copies
2409 copy[field](widget.getFormattedValue())
2410 copy.ischanged(true);
2419 this.updateLidState(copy, row);
2422 this._ensureCSSFundClass = function(id) {
2423 if (!this.fundStyleSheet) {
2425 "style", {"type": "text/css"},
2426 document.getElementsByTagName("head")[0], "last"
2428 this.fundStyleSheet = document.styleSheets[
2429 document.styleSheets.length - 1
2433 var cn = "fund_" + id;
2434 if (!this.haveFundClass[cn]) {
2435 fieldmapper.standardRequest(
2436 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
2438 "params": [openils.User.authtoken, id],
2440 "oncomplete": function(r) {
2441 r = openils.Util.readResponse(r);
2442 self.fundBalanceState[id] = r;
2444 if (r[0] /* stop */)
2445 style = fundStyles.stop;
2446 else if (r[1] /* warning */)
2447 style = fundStyles.warning;
2448 self.fundStyleSheet.insertRule(
2449 "." + cn + " { " + style + " }",
2450 self.fundStyleSheet.cssRules.length
2452 self.haveFundClass[cn] = true;
2459 this._ensureCSSFundClasses = function(store) {
2461 "query": {"id": "*"},
2462 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
2466 this._updateFundSelectorStyle = function(widget, fund_id) {
2467 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
2468 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
2471 this.updateLidState = function(copy, row) {
2474 if (typeof(row) == "undefined") {
2475 row = dojo.query('tr[copy_id="' + copy.id() + '"]', this.copyTbody)[0];
2479 var recv_link = nodeByName("receive", row);
2480 var unrecv_link = nodeByName("unreceive", row);
2481 var del_link = nodeByName("delete", row);
2482 var cxl_link = nodeByName("cancel", row);
2483 var claim_link = nodeByName("claim", row);
2484 var cxl_reason_link = nodeByName("cancel_reason", row);
2486 // by default, hide all the actions
2487 openils.Util.hide(del_link.parentNode);
2488 openils.Util.hide(recv_link);
2489 openils.Util.hide(unrecv_link);
2490 openils.Util.hide(cxl_link);
2491 openils.Util.hide(claim_link);
2492 openils.Util.hide(cxl_reason_link);
2494 if (copy.id() > 0) { // real copies (LIDs)
2496 if (copy.cancel_reason()) {
2498 /* --------- cancelled -------------------------- */
2500 /* XXX the following may leak memory in a long lived table:
2501 * dijits may not get destroyed... not positive. revisit. */
2502 var holds_reason = dojo.create(
2504 "style": "border-bottom: 1px dashed #000;",
2505 "innerHTML": copy.cancel_reason().label()
2506 }, cxl_reason_link, "only"
2510 "label": "<em>" + copy.cancel_reason().label() +
2511 "</em><br />" + copy.cancel_reason().description(),
2512 "connectId": [holds_reason]
2513 }, dojo.create("span", null, cxl_reason_link, "last")
2515 openils.Util.show(cxl_reason_link, "inline");
2517 if (copy.cancel_reason().keep_debits() == 't' ) {
2518 // allow further cancellation of "delayed" copies
2520 openils.Util.show(cxl_link, "inline");
2521 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2524 } else if (copy.recv_time()) {
2526 /* --------- received -------------------------- */
2528 openils.Util.show(unrecv_link, "inline");
2529 unrecv_link.onclick = function() {
2530 if (confirm(localeStrings.UNRECEIVE_LID))
2531 self.issueReceive(copy, /* rollback */ true);
2534 } else if (this.liCache[copy.lineitem()].state() == 'on-order') {
2536 /* --------- on order -------------------------- */
2538 openils.Util.show(recv_link, 'inline');
2539 openils.Util.show(cxl_link, "inline");
2541 recv_link.onclick = function() {
2542 if (self.checkLiAlerts(copy.lineitem()))
2543 self.issueReceive(copy);
2546 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2550 /* --------- pre-order copies -------------------------- */
2552 del_link.onclick = function() { self.deleteCopy(row) };
2553 openils.Util.show(del_link.parentNode);
2559 /* --------- virtual copies -------------------------- */
2561 del_link.onclick = function() { self.deleteCopy(row) };
2562 openils.Util.show(del_link.parentNode);
2566 this.cancelLid = function(lid_id) {
2567 lidCancelDialog._lid_id = lid_id;
2568 openils.Util.show(lidCancelDialog.domNode.parentNode);
2569 lidCancelDialog.show();
2570 if (!lidCancelDialog._prepared) {
2571 var widget = new openils.widget.AutoFieldWidget({
2572 "fmField": "cancel_reason",
2573 "fmClass": "acqlid",
2574 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
2575 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2577 "searchOptions" : {order_by : {"acqcr":"label"}}
2581 acqLidCancelButton.onClick = function() {
2582 if (w.attr("value")) {
2583 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
2585 lidCancelDialog._lid_id,
2589 lidCancelDialog.hide();
2592 lidCancelDialog._prepared = true;
2598 this._cancelLid = function(lid_id, reason) {
2599 fieldmapper.standardRequest(
2600 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
2601 "params": [openils.User.authtoken, lid_id, reason],
2603 "onresponse": function(r) {
2604 if (r = openils.Util.readResponse(r)) {
2606 for (var id in r.lid) {
2607 /* actually this should only iterate once */
2608 self.copyCache[id].cancel_reason(
2609 r.lid[id].cancel_reason
2611 self.updateLidState(self.copyCache[id]);
2620 this._confirmAlert = function(li, lin) {
2622 dojo.string.substitute(
2623 localeStrings.CONFIRM_LI_ALERT, [
2624 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2625 "title", "lineitem_marc_attr_definition"
2627 /* XXX it's really better add a parameter and to adjust
2628 * the format string rather than do this concatenation
2629 * here, but if someone wants this for 2.2 in a hurry,
2630 * we can sidestep the problem of updating the strings
2631 * while the translators are working. */
2633 aou.findOrgUnit(lin.alert_text().owning_lib()).shortname() +
2635 lin.alert_text().code()
2637 lin.alert_text().description() || "",
2644 this.checkLiAlerts = function(li_id) {
2645 var li = this.liCache[li_id];
2647 var alert_notes = li.lineitem_notes().filter(
2648 function(o) { return Boolean(o.alert_text()); }
2651 /* this is _intentionally_ not done in a call to forEach() ... */
2652 for (var i = 0; i < alert_notes.length; i++) {
2653 if (this.noteAcks[alert_notes[i].id()])
2655 else if (!this._confirmAlert(li, alert_notes[i]))
2658 this.noteAcks[alert_notes[i].id()] = true;
2664 this.deleteCopy = function(row) {
2665 var copy = this.copyCache[row.getAttribute('copy_id')];
2666 copy.isdeleted(true);
2668 delete this.copyCache[copy.id()];
2669 this.copyTbody.removeChild(row);
2672 this._virtDfaCountsAsList = function() {
2674 for (var key in this.virtDfaCounts) {
2675 for (var i = 0; i < this.virtDfaCounts[key]; i++)
2681 this.confirmBreachedCopyFunds = function(copies) {
2682 var stop = 0, warning = 0;
2686 var state = self.fundBalanceState[o.fund()];
2687 if (state[0] /* stop */)
2689 else if (state[1] /* warning */)
2696 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
2697 } else if (warning) {
2698 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
2703 this.saveCopyChanges = function(liId) {
2709 for(var id in this.copyCache) {
2710 var c = this.copyCache[id];
2711 if(!c.isdeleted()) total++;
2712 if(c.isnew() || c.ischanged() || c.isdeleted()) {
2713 if(c.id() < 0) c.id(null);
2719 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
2722 if (copies.length > 0) {
2723 if (!this.confirmBreachedCopyFunds(copies))
2726 if (typeof(this._copy_count_cb) == "function")
2727 this._copy_count_cb(liId, total);
2729 openils.Util.show("acq-lit-update-copies-progress");
2730 fieldmapper.standardRequest(
2731 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
2733 params: [openils.User.authtoken, copies],
2734 onresponse: function(r) {
2735 var res = openils.Util.readResponse(r);
2736 litUpdateCopiesProgress.update(res);
2738 oncomplete: function() {
2739 self.drawCopies(liId, true /* force_fetch */);
2740 openils.Util.hide("acq-lit-update-copies-progress");
2741 refreshPOSummaryAmounts();
2747 var dfa_list = this._virtDfaCountsAsList();
2748 if (dfa_list.length > 0) {
2749 fieldmapper.standardRequest(
2751 "open-ils.acq.distribution_formula.record_application"],
2754 "params": [openils.User.authtoken, dfa_list, liId],
2755 "onresponse": function(r) {
2756 var res = openils.Util.readResponse(r);
2757 if (res && res.length < dfa_list.length)
2758 alert(localeStrings.DFA_NOT_ALL);
2762 this.virtDfaCounts = {};
2765 if (this.inlineCopiesNeedingRefresh.indexOf(liId) < 0)
2766 this.inlineCopiesNeedingRefresh.push(liId);
2769 this._updateCreatePoPrepayCheckbox = function(prepay) {
2770 var prepay = openils.Util.isTrue(prepay);
2771 this._prepayRequiredByVendor = prepay;
2772 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
2775 this._confirmPoPrepaySituation = function() {
2776 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
2777 if (want_prepay != this._prepayRequiredByVendor) {
2780 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
2781 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
2788 this.applySelectedLiAction = function(action) {
2792 case 'delete_selected':
2793 this._deleteLiList(self.getSelected());
2796 case 'add_to_order':
2797 addToPoDialog._get_li = dojo.hitch(
2800 return this.getSelected(
2801 false, null, true, li_pre_po_states);
2804 if (addToPoDialog._get_li().length == 0) {
2805 alert(localeStrings.NO_LI_GENERAL);
2808 addToPoDialog.show();
2811 case 'create_order':
2812 this._loadPOSelect();
2813 acqLitPoCreateDialog.show();
2816 case 'save_picklist':
2817 acqLitSavePlDialog.show();
2820 case 'selector_ready':
2822 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
2823 acqLitChangeLiStateDialog.show();
2831 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
2834 case 'batch_create_invoice':
2835 this.batchCreateInvoice();
2838 case 'batch_link_invoice':
2839 this.batchLinkInvoice();
2842 case 'receive_lineitems':
2843 this.receiveSelectedLineitems();
2846 case 'rollback_receive_lineitems':
2847 this.rollbackReceiveLineitems();
2850 case 'create_assets':
2851 this.showAssetCreator();
2854 case 'export_attr_list':
2855 this.chooseExportAttr();
2858 case 'batch_apply_funds':
2859 this.applyBatchLiFunds();
2862 case 'add_brief_record':
2864 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
2866 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
2870 case "cancel_lineitems":
2871 console.log('HERE');
2872 this.maybeCancelLineitems();
2875 case "apply_claim_policy":
2876 var li_list = this.getSelected();
2877 this.claimPolicyPicker.attr("value", null);
2878 liClaimPolicyDialog.show();
2879 liClaimPolicySave.onClick = function() {
2880 self.changeClaimPolicy(
2882 self.claimPolicyPicker.attr("value"),
2886 self.setClaimPolicyControl(li);
2887 self.reconsiderClaimControl(li);
2890 liClaimPolicyDialog.hide();
2898 this.changeClaimPolicy = function(li_list, value, callback) {
2900 function(li) { li.claim_policy(value); }
2902 fieldmapper.standardRequest(
2903 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
2904 "params": [openils.User.authtoken, li_list],
2906 "oncomplete": function(r) {
2907 r = openils.Util.readResponse(r);
2908 if (callback) callback(r);
2914 this.showAssetCreator = function(onAssetsCreated) {
2915 if(!this.isPO) return;
2918 // first, let's see if this PO has any LI's that need to be merged/imported
2919 self.pcrud.search('jub', {purchase_order : this.isPO, eg_bib_id : null}, {
2921 oncomplete : function(r) {
2922 var resp = openils.Util.readResponse(r);
2923 if (resp && resp.length) {
2924 // PO has some non-linked jubs.
2926 self.show('asset-creator');
2927 if(!self.vlAgent.loaded)
2928 self.vlAgent.init();
2930 dojo.connect(assetCreatorButton, 'onClick',
2931 function() { self.createAssets(onAssetsCreated) });
2935 // all jubs linked, move on to asset creation
2936 self.createAssets(onAssetsCreated, true);
2942 this.createAssets = function(onAssetsCreated, noVl) {
2943 this.show('acq-lit-progress-numbers');
2945 var vlArgs = (noVl) ? {} : {vandelay : this.vlAgent.values()};
2946 fieldmapper.standardRequest(
2947 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
2949 params: [this.authtoken, this.isPO, vlArgs],
2950 onresponse: function(r) {
2951 var resp = openils.Util.readResponse(r);
2952 self._updateProgressNumbers(resp, !Boolean(onAssetsCreated), onAssetsCreated);
2958 this.maybeCancelLineitems = function() {
2959 openils.Util.show("acq-lit-cancel-reason", "inline");
2960 if (!acqLitCancelLineitemsButton._prepared) {
2961 var widget = new openils.widget.AutoFieldWidget({
2962 "fmField": "cancel_reason",
2964 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
2965 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2967 "searchOptions" : {order_by : {"acqcr":"label"}}
2971 acqLitCancelLineitemsButton.onClick = function() {
2972 if (w.attr("value")) {
2973 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
2974 self._cancelLineitems(w.attr("value"));
2976 openils.Util.hide("acq-lit-cancel-reason");
2979 acqLitCancelLineitemsButton._prepared = true;
2985 this._cancelLineitems = function(reason) {
2987 var li_list = this.getSelected();
2989 // canceled lineitems may be canceled again if they were
2990 // previously delayed (keep_debits = true).
2991 li_list = li_list.filter(
2994 li.state() != 'cancelled' ||
2995 li.cancel_reason().keep_debits() == 't'
3000 id_list = li_list.map(function(l) {return l.id()});
3002 if (!id_list.length) {
3003 alert(localeStrings.NO_LI_GENERAL);
3006 fieldmapper.standardRequest(
3007 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
3008 "params": [openils.User.authtoken, id_list, reason],
3010 "onresponse": function(r) {
3011 if (r = openils.Util.readResponse(r)) {
3013 for (var id in r.li) {
3014 self.liCache[id].state(r.li[id].state);
3015 self.liCache[id].cancel_reason(
3016 r.li[id].cancel_reason
3018 self.updateLiState(self.liCache[id]);
3021 if (r.lid && self.copyCache) {
3022 for (var id in r.lid) {
3023 if (self.copyCache[id]) {
3024 self.copyCache[id].cancel_reason(
3025 r.lid[id].cancel_reason
3027 self.updateLidState(self.copyCache[id]);
3037 this.chooseExportAttr = function() {
3038 if (!acqLitExportAttrSelector._li_setup) {
3040 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
3042 "data": acqlimad.toStoreData(
3044 "acqlimad", {"code": li_exportable_attrs}
3049 acqLitExportAttrSelector.setValue();
3050 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
3051 acqLitExportAttrSelector._li_setup = true;
3053 openils.Util.show("acq-lit-export-attr-holder", "inline");
3056 this.exportAttrList = function() {
3057 var attr_def = acqLitExportAttrSelector.item;
3058 var li_list = this.getSelected();
3059 var value_list = li_list.map(
3061 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
3062 attr_def.code, "lineitem_marc_attr_definition"
3065 ).filter(function(attr) { return Boolean(attr); });
3067 if (value_list.length > 0) {
3068 if (value_list.length < li_list.length) {
3070 dojo.string.substitute(
3071 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
3078 openils.XUL.contentToFileSaveDialog(
3079 value_list.join("\n"),
3080 localeStrings.EXPORT_SAVE_DIALOG_TITLE
3086 alert(dojo.string.substitute(
3087 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
3091 openils.Util.hide("acq-lit-export-attr-holder");
3094 this.printPO = function() {
3095 if(!this.isPO) return;
3096 progressDialog.show(true);
3097 fieldmapper.standardRequest(
3098 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
3100 params: [this.authtoken, this.isPO, 'html'],
3101 oncomplete: function(r) {
3102 progressDialog.hide();
3103 var evt = openils.Util.readResponse(r);
3104 if(evt && evt.template_output()) {
3105 openils.Util.printHtmlString(evt.template_output().data());
3112 this.batchCreateInvoice = function() {
3113 var liIds = this.getSelected(
3114 false, null, true /* id_list */, li_active_states)
3115 if (!liIds.length) {
3116 alert(localeStrings.NO_LI_GENERAL);
3119 var path = oilsBasePath + '/acq/invoice/view?create=1';
3120 dojo.forEach(liIds, function(li, idx) { path += '&attach_li=' + li });
3121 if (openils.XUL.isXUL())
3122 openils.XUL.newTabEasy(path, localeStrings.NEW_INVOICE, null, true);
3124 location.href = path;
3127 this.batchLinkInvoice = function(create) {
3128 var liIds = this.getSelected(
3129 false, null, true /* id_list */, li_active_states)
3130 if (!liIds.length) {
3131 alert(localeStrings.NO_LI_GENERAL);
3134 if (!self.invoiceLinkDialogManager) {
3135 self.invoiceLinkDialogManager =
3136 new InvoiceLinkDialogManager("li");
3138 self.invoiceLinkDialogManager.target = liIds;
3139 acqLitLinkInvoiceDialog.show();
3142 this.receiveSelectedLineitems = function() {
3143 var states = li_post_po_states.filter(
3144 function(s) { return s != 'received' });
3145 var li_list = this.getSelected(null, null, null, states);
3147 if (!li_list.length) {
3148 alert(localeStrings.NO_LI_GENERAL);
3152 for (var i = 0; i < li_list.length; i++) {
3153 var li = li_list[i];
3155 if (li.state() != "received" &&
3156 !this.checkLiAlerts(li.id())) return;
3159 this.show('acq-lit-progress-numbers');
3162 fieldmapper.standardRequest(
3163 ['open-ils.acq', 'open-ils.acq.lineitem.receive.batch'],
3167 li_list.map(function(li) { return li.id(); })
3169 onresponse : function(r) {
3170 var resp = openils.Util.readResponse(r);
3171 self._updateProgressNumbers(resp, true);
3177 this.issueReceive = function(obj, rollback) {
3179 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
3181 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
3183 progressDialog.show(true);
3184 fieldmapper.standardRequest(
3185 ["open-ils.acq", method], {
3187 "params": [this.authtoken, obj.id()],
3188 "onresponse": function(r) {
3189 if (r = openils.Util.readResponse(r)) {
3190 self.fetchClaimInfo(
3191 part == "lineitem" ? obj.id() : obj.lineitem(),
3193 function() { self.handleReceive(r); }
3195 progressDialog.hide();
3203 * Handles the responses from receive and rollback ML calls.
3205 this.handleReceive = function(resp) {
3208 for (var li_id in resp.li) {
3209 for (var key in resp.li[li_id])
3210 self.liCache[li_id][key](resp.li[li_id][key]);
3211 self.updateLiState(self.liCache[li_id]);
3215 if (typeof(self.poUpdateCallback) == "function")
3216 self.poUpdateCallback(resp.po);
3219 for (var lid_id in resp.lid) {
3220 for (var key in resp.lid[lid_id])
3221 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
3222 self.updateLidState(self.copyCache[lid_id]);
3228 this.rollbackReceiveLineitems = function() {
3229 var li_id_list = this.getSelected(false, null, true);
3230 if (!li_id_list.length) {
3231 alert(localeStrings.NO_LI_GENERAL);
3235 if (!confirm(localeStrings.ROLLBACK_LI_RECEIVE_CONFIRM)) return;
3237 this.show('acq-lit-progress-numbers');
3240 fieldmapper.standardRequest(
3241 ['open-ils.acq', 'open-ils.acq.lineitem.receive.rollback.batch'],
3243 params: [this.authtoken, li_id_list],
3244 onresponse : function(r) {
3245 var resp = openils.Util.readResponse(r);
3246 self._updateProgressNumbers(resp, true);
3252 this._updateProgressNumbers = function(resp, reloadOnComplete, onComplete) {
3253 this.vlAgent.handleResponse(resp,
3254 function(resp, res) {
3255 if(reloadOnComplete)
3256 location.href = location.href;
3258 onComplete(resp, res);
3264 this._createPO = function(fields) {
3265 var wantall = (fields.create_from == "all");
3267 /* If we're a picklist or purchase order already and the user wants
3268 * all lineitems, we might have pages' worth of lineitems haven't all
3269 * been loaded yet, so getSelected() won't find them. The server,
3270 * however, should know about all our lineitems, so let's ask the
3271 * server for a complete list.
3276 true, function(list) {
3277 self._createPOFromLineitems(fields, list);
3278 }, /* id_list */ true, li_pre_po_states
3281 this._createPOFromLineitems(
3282 fields, this.getSelected(
3283 false, null, true /* id_list */, li_pre_po_states)
3288 this._createPOFromLineitems = function(fields, selected) {
3289 if (selected.length == 0) {
3290 alert(localeStrings.NO_LI_GENERAL);
3295 var po = new fieldmapper.acqpo();
3296 po.provider(this.createPoProviderSelector.attr("value"));
3297 po.ordering_agency(this.createPoAgencySelector.attr("value"));
3298 po.prepayment_required(fields.prepayment_required[0] ? true : false);
3299 var name = this.createPoNameInput.attr('value');
3300 if (name) po.name(name); // avoid name=""
3302 // if we're creating assets, delay the asset creation
3303 // until after the PO is created. This will allow us to
3304 // use showAssetCreator() directly.
3306 fieldmapper.standardRequest(
3307 ["open-ils.acq", "open-ils.acq.purchase_order.create"],
3310 openils.User.authtoken,
3311 po, {lineitems : selected}
3313 onresponse : function(r) {
3314 var resp = openils.Util.readResponse(r);
3315 if (resp.complete) {
3316 // self.isPO is needed for showAssetCreator();
3317 self.isPO = resp.purchase_order.id();
3318 var redir = oilsBasePath + "/acq/po/view/" + self.isPO;
3319 if (fields.create_assets[0]) {
3320 self.showAssetCreator(
3321 function() {location.href = redir}
3324 location.href = redir;
3333 this.batchFundWidget = null;
3335 this.applyBatchLiFunds = function() {
3337 var liIds = this.getSelected().map(function(li) { return li.id(); });
3338 if(liIds.length == 0) return; // warn?
3341 batchFundUpdateDialog.show();
3343 if(!this.batchFundWidget) {
3344 this.batchFundWidget = new openils.widget.AutoFieldWidget({
3346 selfReference : true,
3347 labelFormat : fundLabelFormat,
3348 searchFormat : fundSearchFormat,
3349 searchFilter : fundSearchFilter,
3350 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
3351 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
3352 dijitArgs : { "required": true, "labelType": "html" },
3355 this.batchFundWidget.build();
3358 dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
3359 dojo.connect(batchFundUpdateSubmit, 'onClick',
3362 // TODO: call .dry_run first to test thresholds
3363 fieldmapper.standardRequest(
3364 ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
3367 openils.User.authtoken,
3369 self.batchFundWidget.widget.attr('value')
3371 oncomplete : function(r) {
3372 var resp = openils.Util.readResponse(r);
3374 location.href = location.href;
3383 this._deleteLiList = function(list, idx) {
3384 if(idx == null) idx = 0;
3385 if(idx >= list.length) return;
3390 if (this.isPO && (li.state() == "on-order" || li.state() == "received")) {
3391 /* It makes little sense to delete a lineitem from a PO that has
3392 * already been marked 'on-order'. Especially if EDI is in use,
3393 * such a purchase order will probably have already been shipped
3394 * off to a vendor, and mucking with it at this point could leave
3395 * your data in a bad state that doesn't jive with reality.
3397 * I could see making this restriction even firmer.
3399 * I could also see adjusting the li state comparisons, extending
3400 * the comparison to the PO's state, and/or providing functions
3401 * that house the logic for comparing states in a single location.
3403 * Yes, this will be really annoying if you have selected a lot
3404 * of lineitems to cancel that have been ordered. You'll get a
3405 * confirm dialog for each one.
3408 if (!confirm(localeStrings.DEL_LI_FROM_PO)) {
3409 self._deleteLiList(list, ++idx); /* move on to next in list */
3414 fieldmapper.standardRequest(
3416 this.isPO ? 'open-ils.acq.purchase_order.lineitem.delete' : 'open-ils.acq.picklist.lineitem.delete'],
3418 params: [openils.User.authtoken, liId],
3419 oncomplete: function(r) {
3420 self.removeLineitem(liId);
3421 self._deleteLiList(list, ++idx);
3427 this.editOrderMarc = function(li) {
3429 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
3430 to true in about:config */
3432 if(openils.XUL.isXUL()) {
3433 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul','','chrome');
3435 win = window.open('/xul/server/cat/marcedit.xul','','chrome');
3439 record : {marc : li.marc(), "rtype": "bre"},
3441 label: 'Save Record', // XXX I18N
3442 func: function(xmlString) {
3444 fieldmapper.standardRequest(
3445 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
3447 params: [openils.User.authtoken, li],
3448 oncomplete: function(r) {
3449 openils.Util.readResponse(r);
3451 self.drawInfo(li.id())
3457 'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
3458 'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
3462 this._savePl = function(values) {
3464 (values.which == 'all'),
3465 function(list) { self._savePlFromLineitems(values, list); }
3469 this._savePlFromLineitems = function(values, selected) {
3470 openils.Util.show("acq-lit-generic-progress");
3472 if(values.new_name) {
3473 openils.acq.Picklist.create(
3474 {name: values.new_name},
3480 oilsBasePath + "/acq/picklist/view/" + id;
3485 } else if(values.existing_pl) {
3486 // update lineitems to use an existing picklist
3488 values.existing_pl, selected, 0,
3491 oilsBasePath + "/acq/picklist/view/" +
3498 this._updateLiState = function(values, state, state_filter) {
3499 progressDialog.show(true);
3501 (values.which == 'all'),
3503 self._updateLiStateFromLineitems(values, state, list);
3504 }, false /* id_list */, state_filter
3508 this._updateLiStateFromLineitems = function(values, state, selected) {
3509 if(!selected.length) {
3510 try { progressDialog.hide() } catch(E) {};
3511 alert(localeStrings.NO_LI_GENERAL);
3514 dojo.forEach(selected, function(li) {li.state(state);});
3515 self._updateLiList(null, selected, 0,
3516 // TODO consider inline updates for efficiency
3517 function() { location.href = location.href }
3521 this._updateLiList = function(pl, list, idx, oncomplete) {
3522 if(idx >= list.length) return oncomplete();
3524 if(pl != null) li.picklist(pl);
3525 litGenericProgress.update({maximum: list.length, progress: idx});
3526 new openils.acq.Lineitem({lineitem:li}).update(
3528 self._updateLiList(pl, list, ++idx, oncomplete);
3533 this._loadPOSelect = function() {
3534 if (!this.createPoProviderSelector) {
3535 var widget = new openils.widget.AutoFieldWidget({
3536 "fmField": "provider",
3538 "searchFilter": {"active": "t"},
3539 "parentNode": dojo.byId("acq-lit-po-provider"),
3541 "onChange": function() {
3543 self._updateCreatePoPrepayCheckbox(
3544 this.item.prepayment_required()
3550 widget.build(function(w) { self.createPoProviderSelector = w; });
3553 this.createPoCheckDupes = function() {
3554 var org = self.createPoAgencySelector.attr('value');
3555 var name = self.createPoNameInput.attr('value');
3556 openils.Util.hide('acq-dupe-po-name');
3559 acqLitCreatePoSubmit.attr('disabled', false);
3563 acqLitCreatePoSubmit.attr('disabled', true);
3564 var orgs = fieldmapper.aou.descendantNodeList(org, true);
3565 new openils.PermaCrud().search('acqpo',
3566 {name : name, ordering_agency : orgs},
3567 {async : true, oncomplete : function(r) {
3568 var po = openils.Util.readResponse(r);
3570 if (po && (po = po[0])) {
3572 var link = dojo.byId('acq-dupe-po-link');
3573 openils.Util.show('acq-dupe-po-name', 'table-row');
3574 var dupe_path = '/acq/po/view/' + po.id();
3578 if (window.IAMBROWSER) {
3579 // TODO: integration
3583 link.onclick = function() {
3585 var loc = xulG.url_prefix('XUL_BROWSER?url=') +
3586 window.encodeURIComponent(
3587 xulG.url_prefix('EG_WEB_BASE' + dupe_path)
3591 {tab_name: '', browser:false},
3594 show_nav_buttons : true,
3595 show_print_button : true,
3602 link.onclick = function() {
3603 window.open(oilsBasePath + dupe_path, '_blank').focus();
3608 acqLitCreatePoSubmit.attr('disabled', false);
3614 if (!this.createPoAgencySelector) {
3615 var widget = new openils.widget.AutoFieldWidget({
3616 "fmField": "ordering_agency",
3618 "parentNode": dojo.byId("acq-lit-po-agency"),
3619 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3621 widget.build(function(w) {
3622 self.createPoAgencySelector = w;
3623 dojo.connect(w, 'onChange', self.createPoCheckDupes);
3627 if (!this.createPoNameInput) {
3628 var widget = new openils.widget.AutoFieldWidget({
3631 "parentNode": dojo.byId("acq-lit-po-name"),
3632 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3634 widget.build(function(w) {
3635 self.createPoNameInput = w;
3636 dojo.connect(w, 'onChange', self.createPoCheckDupes);
3641 this.showRealCopyEditUI = function(li) {
3646 this._fetchLineitem(li.id(),
3648 li = self.liCache[li.id()] = fullLi;
3652 id : li.lineitem_details().map(
3653 function(item) { return item.eg_copy_id() }
3657 oncomplete : function(r) {
3659 var r_list = openils.Util.readResponse( r );
3660 for (var i = 0; i < r_list.length; i++) {
3661 var copy = r_list[i];
3662 var volId = copy.call_number();
3663 var volume = self.volCache[volId];
3665 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
3667 copy.call_number(volume);
3668 copyList.push(copy);
3671 xulG.volume_item_creator( { 'existing_copies' : copyList } );
3674 alert('error in oncomplete: ' + E);
3683 this.drawBibFinder = function(li) {
3686 var liWrapper = new openils.acq.Lineitem({lineitem:li});
3689 ['isbn', 'upc', 'issn', 'title', 'author'],
3691 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
3693 if(field == 'title' || field == 'author') {
3694 query += field +':' + val + ' ';
3696 query += 'identifier|' + field + ':' + val + ' ';
3703 oilsBasePath + '/acq/lineitem/findbib?query=' + encodeURIComponent(query),
3704 '', 'resizable,scrollbars=1,chrome');
3706 win.window.recordFound = function(bibId) {
3709 var attrs = li.attributes();
3710 li.attributes(null);
3711 li.eg_bib_id(bibId);
3713 fieldmapper.standardRequest(
3714 ["open-ils.acq", "open-ils.acq.lineitem.update"],
3716 "params": [openils.User.authtoken, li],
3718 "oncomplete": function(r) {
3719 if(openils.Util.readResponse(r)) {
3720 location.href = location.href;