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'];
33 function nodeByName(name, context) {
34 return dojo.query('[name='+name+']', context)[0];
37 // for caching linked users. e.g. lineitem_detail.receiver
40 var liDetailBatchFields = ['fund', 'owning_lib', 'location', 'collection_code', 'circ_modifier', 'cn_label'];
41 var liDetailFields = liDetailBatchFields.concat(['barcode', 'note']);
43 "stop": "color: #c00; font-weight: bold;",
44 "warning": "color: #c93;"
47 function AcqLiTable() {
54 this.haveFundClass = {}
55 this.fundBalanceState = {};
56 this.realDfaCache = {};
57 this.virtDfaCounts = {};
60 this.claimEligibleLidByLi = {};
61 this.claimEligibleLid = {};
62 this.toggleState = false;
63 this.tbody = dojo.byId('acq-lit-tbody');
66 this.authtoken = openils.User.authtoken;
67 this.pcrud = new openils.PermaCrud();
68 this.rowTemplate = this.tbody.removeChild(dojo.byId('acq-lit-row'));
69 this.copyTbody = dojo.byId('acq-lit-li-details-tbody');
70 this.copyRow = this.copyTbody.removeChild(dojo.byId('acq-lit-li-details-row'));
71 this.copyBatchRow = dojo.byId('acq-lit-li-details-batch-row');
72 this.copyBatchWidgets = {};
73 this.liNotesTbody = dojo.byId('acq-lit-notes-tbody');
74 this.liNotesRow = this.liNotesTbody.removeChild(dojo.byId('acq-lit-notes-row'));
75 this.realCopiesTbody = dojo.byId('acq-lit-real-copies-tbody');
76 this.realCopiesRow = this.realCopiesTbody.removeChild(dojo.byId('acq-lit-real-copies-row'));
77 this._copy_fields_for_acqdf = ['owning_lib', 'location'];
78 this.skipInitialEligibilityCheck = false;
79 this.claimDialog = new ClaimDialogManager(
80 liClaimDialog, finalClaimDialog, this.claimEligibleLidByLi,
81 function(li) { /* callback that fires when claims are made */
82 self.fetchClaimInfo(li.id(), /* force update */ true);
85 this.vlAgent = new VLAgent();
87 if (dojo.byId('acq-lit-apply-idents')) {
88 dojo.byId('acq-lit-apply-idents').onclick = function() {
89 self.applyOrderIdentValues();
93 this.focusLineitem = new openils.CGI().param('focus_li');
95 // capture the inline copy display wrapper and row template
96 this.inlineCopyContainer =
97 this.tbody.removeChild(dojo.byId('acq-inline-copies-row'));
99 '[name=acq-li-inline-copies-tbody]', this.inlineCopyContainer)[0];
100 this.inlineCopyTemplate = tb.removeChild(
101 dojo.query('[name=acq-li-inline-copies-template]', tb)[0]);
102 this.inlineNoCopies = tb.removeChild(
103 dojo.query('[name=acq-li-inline-copies-none]', tb)[0]);
105 // list of LI IDs that should be refreshed at next display time
106 this.inlineCopiesNeedingRefresh = [];
108 dojo.byId("acq-lit-li-actions-selector").onchange = function() {
109 self.applySelectedLiAction(this.options[this.selectedIndex].value);
110 this.selectedIndex = 0;
113 acqLitCreatePoSubmit.onClick = function() {
114 if (!self.createPoProviderSelector.attr("value") ||
115 !self.createPoAgencySelector.attr("value")) {
116 alert(localeStrings.CREATE_PO_INVALID);
118 } else if (self._confirmPoPrepaySituation()) {
119 acqLitPoCreateDialog.hide();
120 self._createPO(acqLitPoCreateDialog.getValues());
126 acqLitSavePlButton.onClick = function() {
127 acqLitSavePlDialog.hide();
128 self._savePl(acqLitSavePlDialog.getValues());
131 acqLitCancelLiStateButton.onClick = function() {
132 acqLitChangeLiStateDialog.hide();
134 acqLitSaveLiStateButton.onClick = function() {
135 acqLitChangeLiStateDialog.hide();
136 self._updateLiState(acqLitChangeLiStateDialog.getValues(), acqLitChangeLiStateDialog.attr('state'));
140 dojo.byId('acq-lit-select-toggle').onclick = function(){self.toggleSelect()};
141 dojo.byId('acq-inline-copies-toggle').onclick = function(){self.toggleInlineCopies()};
142 dojo.byId('acq-lit-info-back-button').onclick = function(){self.show('list')};
143 dojo.byId('acq-lit-copies-back-button').onclick = function(){self.show('list')};
144 dojo.byId('acq-lit-notes-back-button').onclick = function(){self.show('list')};
145 dojo.byId('acq-lit-real-copies-back-button').onclick = function(){self.show('list')};
147 this.afwCopyFieldArgs = function(field, perms) {
151 "labelFormat": (field == 'fund') ? fundLabelFormat : null,
152 "searchFormat": (field == 'fund') ? fundSearchFormat : null,
153 "searchFilter": (field == 'fund') ? {"active": "t"} : null,
154 "orgLimitPerms": [perms],
157 "labelType": (field == "fund") ? "html" : null
159 "noCache": (field == "fund"),
164 /* This is the "new" batch updater that sits atop all lineitems. It does
165 * use this.afwCopyFieldArgs() to borrow a little common code from the
166 * "old" batch updater atop the copy details view. */
167 this.initBatchUpdater = function(disabled_fields) {
168 openils.Util.show("acq-batch-update", "table");
170 if (!dojo.isArray(disabled_fields)) disabled_fields = [];
172 /* Note that this will directly contain dijits, not the AutoWidget
174 this.batchUpdateWidgets = {};
176 this.batchUpdateWidgets.item_count = new dijit.form.TextBox(
178 "style": {"width": "3em"},
180 dojo.indexOf(disabled_fields, "item_count") != -1
186 (new openils.widget.AutoFieldWidget({
188 "selfReference": true,
189 "dijitArgs": { "required": false },
191 "parentNode": "acq-bu-distribution_formula"
194 dojo.style(w.domNode, {"width": "12em"});
195 /* dijitArgs to AutoFieldWidget won't work for 'disabled' */
198 dojo.indexOf(disabled_fields, "distribution_formula") != -1
200 self.batchUpdateWidgets.distribution_formula = w;
205 ["owning_lib","location","collection_code","circ_modifier","fund"],
207 var args = self.afwCopyFieldArgs(field,"CREATE_PURCHASE_ORDER");
208 args.parentNode = dojo.byId("acq-bu-" + field);
210 (new openils.widget.AutoFieldWidget(args)).build(
212 if (field == "fund") {
214 w, "onChange", function(val) {
215 self._updateFundSelectorStyle(aw, val);
219 self._ensureCSSFundClasses(w.store);
222 dojo.style(w.domNode, {"width": "10em"});
225 dojo.indexOf(disabled_fields, field) != -1
227 self.batchUpdateWidgets[field] = w;
233 acqBatchUpdateApply.onClick = function() {
234 var li_id_list = self.getSelected(false, null, true /* id list */);
235 if (!li_id_list.length) {
236 alert(localeStrings.NO_LI_TO_UPDATE);
240 progressDialog.show(true);
241 progressDialog.attr("title", localeStrings.LI_BATCH_UPDATE);
242 progressDialog.update({"maximum": li_id_list.length,"progress": 0});
246 var params = [ self.authtoken, {"lineitems": li_id_list},
247 self.batchUpdateChanges(), self.batchUpdateFormula() ];
248 console.log("batch update params: " + dojo.toJson(params));
250 fieldmapper.standardRequest(
251 ["open-ils.acq", "open-ils.acq.lineitem.batch_update"], {
254 "onresponse": function(r) {
255 if ((r = openils.Util.readResponse(r))) { // assignment
256 progressDialog.update({"progress": ++count});
258 progressDialog.hide();
259 progressDialog.attr("title", "");
262 "oncomplete": function() {
263 /* XXX Is the last call to onresponse guaranteed to
264 * finish before oncomplete is fired? */
265 if (count != li_id_list.length) {
266 console.error("lineitem batch update operation failed");
267 progressDialog.hide();
268 progressDialog.attr("title", "");
270 location.href = location.href;
278 this.batchUpdateChanges = function() {
282 openils.Util.objectProperties(this.batchUpdateWidgets),
284 if (k == "distribution_formula") return; /* handled elsewhere */
285 if (self.batchUpdateWidgets[k].attr("disabled")) return;
287 /* It's important that a value of "" should mean that a field
288 * doesn't get used in the arguments to the batch updater API,
289 * but 0 should mean an actual 0. */
290 var value = self.batchUpdateWidgets[k].attr("value");
299 this.batchUpdateFormula = function() {
300 if (this.batchUpdateWidgets.distribution_formula.attr("disabled")) {
304 this.batchUpdateWidgets.distribution_formula.attr("value") ||
310 this.reset = function(keep_selectors) {
311 while(self.tbody.childNodes[0])
312 self.tbody.removeChild(self.tbody.childNodes[0]);
320 this.setNext = function(handler) {
321 var link = dojo.byId('acq-lit-next');
323 dojo.style(link, 'visibility', 'visible');
324 link.onclick = handler;
326 dojo.style(link, 'visibility', 'hidden');
330 this.setPrev = function(handler) {
331 var link = dojo.byId('acq-lit-prev');
333 dojo.style(link, 'visibility', 'visible');
334 link.onclick = handler;
336 dojo.style(link, 'visibility', 'hidden');
340 this.enableActionsDropdownOptions = function(mask) {
341 /* 'mask' is probably a misnomer the way I'm using it, but it needs to
342 * be one of pl,po,ao,gs,vp, or fs. */
343 dojo.query("option", "acq-lit-li-actions-selector").forEach(
345 var opt_mask = dojo.attr(option, "mask");
347 /* For each <option> element, an empty or non-existent mask
348 * attribute, a mask attribute of "*", or a mask attribute that
349 * matches this method's argument should result in that
350 * option's being enabled. */
352 option, "disabled", !(
355 opt_mask.search(mask) != -1
363 * Ensures this.focusLineitem is in view and causes a brief
364 * border around the lineitem to come to life then fade.
366 this.focusLi = function() {
367 if (!this.focusLineitem) return;
369 // set during addLineitem()
370 var node = dojo.byId('li-title-ref-' + this.focusLineitem);
372 // LI may not yet be rendered
375 // prevent numerous re-focuses
376 this.focusLineitem = null;
378 // causes the full row to be visible
379 dijit.scrollIntoView(node);
382 dojo.query('[attr=title]', node)[0].focus();
384 dojo.require('dojox.fx');
388 dojox.fx.highlight({color : '#BB4433', node : node, duration : 2000}).play();
393 this.show = function(div) {
394 openils.Util.hide('acq-lit-table-div');
395 openils.Util.hide('acq-lit-info-div');
396 openils.Util.hide('acq-lit-li-details');
397 openils.Util.hide('acq-lit-notes-div');
398 openils.Util.hide('acq-lit-real-copies-div');
399 openils.Util.hide('acq-lit-asset-creator');
402 openils.Util.show('acq-lit-table-div');
404 this.refreshInlineCopies();
407 openils.Util.show('acq-lit-info-div');
410 openils.Util.show('acq-lit-li-details');
413 openils.Util.show('acq-lit-real-copies-div');
416 openils.Util.show('acq-lit-notes-div');
418 case 'asset-creator':
419 openils.Util.show('acq-lit-asset-creator');
423 openils.Util.show(div);
427 this.hide = function() {
431 this.toggleSelect = function() {
433 dojo.forEach(self.selectors, function(i){i.checked = false});
435 dojo.forEach(self.selectors, function(i){i.checked = true});
436 self.toggleState = !self.toggleState;
440 this.getAll = function(callback, id_only) {
441 /* For some uses of the li table, we may not really know about "all"
442 * the lineitems that the user thinks we know about. If we're a paged
443 * picklist, for example, we only know about the lineitems we've
444 * displayed, but not necessarily all the lineitems on the picklist.
445 * So we reach out to pcrud to inform us.
448 var oncomplete = function(r) {
449 var id_list = openils.Util.readResponse(r);
453 self.fetchLineitemsById(id_list, callback);
458 "jub", {"picklist": this.isPL}, {
459 "id_list": true, /* sic, even if id_only */
461 "oncomplete": oncomplete
465 } else if (this.isPO) {
467 "jub", {"purchase_order": this.isPO}, {
470 "oncomplete": oncomplete
474 } else if (this.isUni && this.pager) {
475 this.pager.getAllLineitemIDs(oncomplete);
479 /* If execution reaches this point, we don't need or can't perform
480 * any special tricks to find out the "real" list of "all" lineitems
481 * in this context, so we fall back to the old method.
483 callback(this.getSelected(true, null, id_only));
486 /** @param all If true, assume all are selected */
487 this.getSelected = function(
489 callback /* If you want a "good" idea of "all" lineitems, you must
490 provide a callback that accepts an array parameter, rather than
491 relying on the return value of this method itself. */,
495 return this.getAll(callback, id_only);
497 var indices = {}; /* use to uniqify. needed in paging situations. */
498 dojo.forEach(this.selectors,
501 indices[i.parentNode.parentNode.getAttribute('li')] = true;
505 var result = openils.Util.objectProperties(indices);
508 result = result.map(function(liId) { return self.liCache[liId]; });
516 this.setRowAttr = function(td, liWrapper, field, type) {
517 var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
518 td.appendChild(document.createTextNode(val));
521 this.setClaimPolicyControl = function(li, row) {
522 if (!self._claimPolicyPickerLoading) {
523 self._claimPolicyPickerLoading = true;
525 new openils.widget.AutoFieldWidget({
526 "parentNode": "acq-lit-li-claim-policy",
528 "selfReference": true,
529 "dijitArgs": {"required": true}
531 function(w) { self.claimPolicyPicker = w; }
535 /* dojox.timing.doLater() is the best thing ever. Resource not yet
536 * ready? Just repeat my whole method when it is. */
537 if (dojox.timing.doLater(self.claimPolicyPicker)) {
541 row = self._findLiRow(li);
543 if (li.claim_policy()) {
544 /* This Dojo data dance is necessary to get a whole fieldmapper
545 * object based on a claim policy ID, since we alreay have the
546 * widget thing loaded with all that data, and can thereby
547 * avoid another request to the server. */
548 self.claimPolicyPicker.store.fetchItemByIdentity({
549 "identity": li.claim_policy(),
550 "onItem": function(a) {
551 var policy = (new acqclp()).fromStoreItem(a);
552 var span = nodeByName("claim_policy", row);
553 var inner = nodeByName("claim_policy_name", row);
555 openils.Util.show(span, "inline");
556 inner.innerHTML = policy.name();
558 "onError": function(e) {
563 openils.Util.hide(nodeByName("claim_policy", row));
564 nodeByName("claim_policy_name", row).innerHTML = "";
569 this.fetchClaimInfo = function(liId, force, callback, row) {
571 liId, function(full) {
572 self.liCache[full.id()] = full;
573 self.checkClaimEligibility(full, callback, row);
578 // fetch an updated copy of the lineitem
579 // and add it back to the lineitem table
580 this.refreshLineitem = function(li, focus) {
582 this._fetchLineitem(li.id(),
585 self.focusLineitem = li.id();
587 self.focusLineitem = null;
589 var row = dojo.query('[li='+li.id()+']', self.tbody)[0];
590 var nextSibling = row.nextSibling;
591 self.tbody.removeChild(row);
592 self.addLineitem(newLi, false, nextSibling);
598 * Inserts a single lineitem into the growing table of lineitems
599 * @param {Object} li The lineitem object to insert
601 this.addLineitem = function(li, skip_final_placement, nextSibling) {
602 this.liCache[li.id()] = li;
604 // insert the row right away so that final order isn't
605 // dependent on how long subsequent async request take
606 // for a given line item
607 var row = self.rowTemplate.cloneNode(true);
608 if (!skip_final_placement) {
610 // either no nextSibling was provided or it was null
611 // meaning the row was already at the end of the table
612 self.tbody.appendChild(row);
614 self.tbody.insertBefore(row, nextSibling);
618 self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
620 // sort the lineitem notes on edit_time
621 if(!li.lineitem_notes()) li.lineitem_notes([]);
623 var liWrapper = new openils.acq.Lineitem({lineitem:li});
624 row.setAttribute('li', li.id());
625 var tds = dojo.query('[attr]', row);
626 dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
627 dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
629 // so we can scroll to it later
630 dojo.query('[name=bib-info-cell]', row)[0].id = 'li-title-ref-' + li.id();
633 liWrapper.findAttr("isbn", "lineitem_marc_attr_definition") ||
634 liWrapper.findAttr("upc", "lineitem_marc_attr_definition");
636 // XXX media prefix for added content
638 nodeByName("jacket", row).setAttribute(
639 "src", "/opac/extras/ac/jacket/small/" + identifier
643 nodeByName("liid", row).innerHTML += li.id();
646 openils.Util.show(nodeByName('catalog', row), 'inline');
647 nodeByName("catalog_link", row).onclick = this.generateMakeRecTab(li.eg_bib_id());
649 openils.Util.show(nodeByName('link_to_catalog', row), 'inline');
650 nodeByName("link_to_catalog_link", row).onclick = function() { self.drawBibFinder(li) };
653 if (li.queued_record()) {
654 this.pcrud.retrieve('vqbr', li.queued_record(),
656 oncomplete : function(r) {
657 var qrec = openils.Util.readResponse(r);
658 openils.Util.show(nodeByName('queue', row), 'inline');
659 var link = nodeByName("queue_link", row);
660 link.onclick = function() {
661 // open a new tab to the vandelay queue for this record
662 openils.XUL.newTabEasy(
663 oilsBasePath + '/vandelay/vandelay?qtype=bib&qid=' + qrec.queue()
671 nodeByName("worksheet_link", row).href =
672 oilsBasePath + "/acq/lineitem/worksheet/" + li.id() +
673 '?source=' + encodeURIComponent(location.pathname + location.search)
675 nodeByName("show_requests_link", row).href =
676 oilsBasePath + "/acq/picklist/user_request?lineitem=" + li.id() +
677 '?source=' + encodeURIComponent(location.pathname + location.search)
679 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
680 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
681 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
682 dojo.query('[name=expand_inline_copies]', row)[0].onclick =
683 function() {self.drawInlineCopies(li.id())};
685 this.drawOrderIdentSelector(li, row);
687 if (!this.skipInitialEligibilityCheck)
691 function(full) { self.setClaimPolicyControl(full, row) },
695 this.updateLiNotesCount(li, row);
697 // show which PO this lineitem is a member of
698 if(li.purchase_order() && !this.isPO) {
700 this.poCache[li.purchase_order()] =
701 this.poCache[li.purchase_order()] ||
702 fieldmapper.standardRequest(
703 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
705 this.authtoken, li.purchase_order(), {
706 "flesh_price_summary": true,
707 "flesh_provider" : true,
708 "flesh_lineitem_count": true
711 if(po && !this.isMeta) {
712 openils.Util.show(nodeByName('po', row), 'inline');
713 var link = nodeByName('po_link', row);
714 link.setAttribute('href', oilsBasePath +
715 '/acq/po/view/' + li.purchase_order() +
716 '?focus_li=' + li.id() +
717 '&source=' + encodeURIComponent(location.pathname + location.search)
719 link.innerHTML += po.name();
721 openils.Util.show(nodeByName('pro', row), 'inline');
722 link = nodeByName('pro_link', row);
723 link.setAttribute('href', oilsBasePath + '/conify/global/acq/provider/' + po.provider().id())
724 link.innerHTML += po.provider().code();
728 // show which picklist this lineitem is a member of
729 if(li.picklist() && (this.isPO || this.isMeta || this.isUni)) {
731 this.plCache[li.picklist()] =
732 this.plCache[li.picklist()] ||
733 fieldmapper.standardRequest(
734 ['open-ils.acq', 'open-ils.acq.picklist.retrieve.authoritative'],
735 {params: [this.authtoken, li.picklist()]});
737 if (pl.name() == "") {
738 openils.Util.show(nodeByName("bib_origin", row), "inline");
742 openils.Util.show(nodeByName('pl', row), 'inline');
743 var link = nodeByName('pl_link', row);
744 link.setAttribute('href', oilsBasePath +
745 '/acq/picklist/view/' + li.picklist() +
746 '?focus_li=' + li.id() +
747 '&source=' + encodeURIComponent(location.pathname + location.search)
749 link.innerHTML += pl.name();
754 var countNode = nodeByName('count', row);
755 var count = li.item_count() || 0;
756 if (typeof(this._copy_count_cb) == "function") {
757 this._copy_count_cb(li.id(), count);
759 countNode.innerHTML = count;
760 countNode.id = 'acq-lit-copy-count-label-' + li.id();
763 var priceInput = dojo.query('[name=price]', row)[0];
764 priceInput.value = li.estimated_unit_price() || '';
765 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
767 // show either "mark received" or "unreceive" as appropriate
768 this.updateLiState(li, row);
770 if (skip_final_placement) {
774 // the last LI may be rendered after the call to show('list'),
775 // so make sure it's focused if necessary.
776 if (this.focusLineitem == li.id())
780 this._liCountClaims = function(li) {
782 for (var i = 0; i < li.lineitem_details().length; i++)
783 total += li.lineitem_details()[i].claims().length;
787 this._findLiRow = function(li) {
788 return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
791 this.reconsiderClaimControl = function(li, row) {
792 if (!row) row = this._findLiRow(li);
793 var option = nodeByName("action_manage_claims", row);
794 var eligible = this.claimEligibleLidByLi[li.id()].length;
795 var count = this._liCountClaims(li);
797 option.disabled = !(count || eligible);
799 dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
800 option.onclick = function() { self.claimDialog.show(li); };
803 this.clearEligibility = function(li) {
804 this.claimEligibleLidByLi[li.id()] = [];
806 if (li.lineitem_details()) {
807 li.lineitem_details().forEach(
808 function(lid) { delete self.claimEligibleLid[lid.id()]; }
812 if (this.copyCache) {
814 for (var k in this.copyCache) {
815 if (this.copyCache[k].lineitem() == li.id())
819 function(k) { delete self.claimEligibleLid[k]; }
824 this.applyOrderIdentValues = function() {
825 this._identValuesInFlight =
826 openils.Util.objectProperties(this.liCache).length;
827 for (var liId in this.liCache) {
828 this._applyOrderIdentValue(this.liCache[liId]);
832 // returns true if request was sent
833 this._applyOrderIdentValue = function(li, oncomplete) {
836 console.log('applying ident value for lineitem ' + li.id());
839 var row = dojo.query('[li=' + li.id() + ']')[0];
841 // find the selected ident value
842 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
843 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
844 var name = typeSel.options[typeSel.selectedIndex].value;
845 var val = typeSel._cbox.attr('value');
847 console.log("selected ident is " + val);
849 // it differs from the existing ident value, update it
850 var oldIdent = self.getLiOrderIdent(li);
852 oldIdent.attr_name() == name &&
853 oldIdent.attr_value() == val) {
854 console.log('selected ident attr matches existing attr');
855 if (--this._identValuesInFlight == 0) {
856 if (oncomplete) oncomplete(li);
857 else location.href = location.href;
862 // see if the selected ident value is represented
863 // by an existing lineitem attr
866 typeSel._cbox.store.fetch({
867 query : {attr_value : val},
868 onItem : function(item) {
869 console.log('found existing attr for ident value');
870 args.source_attr_id = li.attributes().filter(
871 function(attr) { return attr.id() == item.id[0] }
877 if (!args.source_attr_id) {
878 // user entered new text in the combobox
879 // so we need to create a new attr
880 console.log('creating new ident attr');
881 args.lineitem_id = li.id();
882 args.attr_name = name;
883 args.attr_value = val;
886 fieldmapper.standardRequest(
887 ['open-ils.acq', 'open-ils.acq.lineitem.order_identifier.set'],
889 params : [openils.User.authtoken, args],
890 oncomplete : function() {
891 console.log('order_ident oncomplete');
892 if (--self._identValuesInFlight == 0) {
893 if (oncomplete) oncomplete(li);
894 else location.href = location.href;
896 console.log(self._identValuesInFlight + ' still in flight');
904 this.getLiOrderIdent = function(li) {
905 var attrs = li.attributes();
906 if (!attrs) return null;
910 attr.attr_type() == 'lineitem_local_attr_definition' &&
911 openils.Util.isTrue(attr.order_ident())
917 this.drawOrderIdentSelector = function(li, row) {
919 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
920 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
922 var attrs = li.attributes();
924 // limit to MARC attr defs
925 attrs = attrs.filter(
927 return (attr.attr_type() == 'lineitem_marc_attr_definition');
931 var identAttr = this.getLiOrderIdent(li);
934 // collect the values for each type of identifier
935 // find a reasonable default identifier type to render
939 dojo.forEach(['isbn', 'upc', 'issn'],
942 // collect the values for this attr name
943 values[name] = attrs.filter(
945 return (attr.attr_name() == name)
949 // select a reasonable default name in the type-selector
953 if (identAttr.attr_name() == name)
955 } else if (values[name].length) {
960 dojo.forEach(typeSel.options, function(opt) {
961 if (opt.value == name) {
971 function updateOrderIdent(val) {
972 self._identValuesInFlight = 1;
973 self._applyOrderIdentValue(
976 self.refreshLineitem(li);
981 // replace the ident combobox with a new
982 // one for the selected ident type
983 function changeComboBox(sel) {
984 var name = sel.options[sel.selectedIndex].value;
986 var td = dojo.query('[name=order_ident_value]', row)[0];
987 if (td.childNodes[0])
988 dojo.destroy(td.childNodes[0]);
990 var store = new dojo.data.ItemFileWriteStore({
991 data : acqlia.toStoreData(values[name])
994 var cbox = new dijit.form.ComboBox(
996 labelAttr : 'attr_value',
997 searchAttr : 'attr_value'
999 dojo.create('div', {}, td)
1004 // set the value for the cbox
1005 if (values[name].length) {
1006 var orderIdent = self.getLiOrderIdent(li);
1008 if (orderIdent && orderIdent.attr_name() == name) {
1009 cbox.attr('value', orderIdent.attr_value());
1011 cbox.attr('value', values[name][0].attr_value());
1015 if (!self.orderIdentAllowed)
1016 cbox.attr('disabled', true);
1019 cbox._lineitem = li;
1020 dojo.connect(cbox, 'onChange', updateOrderIdent);
1023 changeComboBox(typeSel); // force the initial draw
1024 typeSel.onchange = function() {changeComboBox(typeSel)};
1027 this.testOrderIdentPerms = function(org, callback) {
1029 new openils.User().getPermOrgList(
1030 'ACQ_SET_LINEITEM_IDENTIFIER',
1032 console.log('found orgs = ' + orgs);
1033 for (var i = 0; i < orgs.length; i++) {
1034 if (Number(orgs[i]) == Number(org)) {
1035 self.orderIdentAllowed = true;
1036 if (callback) callback();
1040 if (callback) callback();
1046 this.checkClaimEligibility = function(li, callback, row) {
1047 /* Assume always eligible, i.e. from this interface we don't care about
1048 * claim eligibility any more. this is where the user would force a
1050 this.clearEligibility(li);
1051 this.claimEligibleLidByLi[li.id()] = li.lineitem_details().map(
1052 function(lid) { return lid.id(); }
1054 li.lineitem_details().forEach(
1055 function(lid) { self.claimEligibleLid[lid.id()] = true; }
1057 this.reconsiderClaimControl(li, row);
1058 if (callback) callback(li);
1060 this.clearEligibility(li);
1061 fieldmapper.standardRequest(
1062 ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
1063 "params": [openils.User.authtoken, {"lineitem": li.id()}],
1065 "onresponse": function(r) {
1066 if (r = openils.Util.readResponse(r)) {
1067 self.claimEligibleLidByLi[li.id()].push(
1070 self.claimEligibleLid[r.lineitem_detail()] = true;
1073 "oncomplete": function() {
1074 self.reconsiderClaimControl(li, row);
1075 if (typeof(callback) == "function")
1083 this.updateLiNotesCount = function(li, row) {
1084 if (!row) row = this._findLiRow(li);
1086 var has_notes = (li.lineitem_notes().filter(
1087 function(o) { return Boolean (o.alert_text()); }
1090 /* U+2691 is the code point for a filled-in flag character */
1091 nodeByName("notes_alert_flag", row).innerHTML =
1092 has_notes ? "⚑" : "";
1093 nodeByName("noteslink", row).style.fontStyle =
1094 has_notes ? "italic" : "normal";
1095 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
1098 /* XXX NOT related to _updateLiState(). rethink */
1099 this.updateLiState = function(li, row) {
1100 if (!row) row = this._findLiRow(li);
1102 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
1103 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
1105 // always allow access to LI history
1106 nodeByName('action_view_history', row).onclick =
1107 function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
1109 /* handle row coloring for based on LI state */
1110 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1111 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
1113 // Expose invoice actions for any lineitem that is linked to a PO
1114 if (li.purchase_order()) {
1115 openils.Util.show(nodeByName("invoices_span", row), "inline");
1116 var link = nodeByName("invoices_link", row);
1117 link.onclick = function() {
1118 openils.XUL.newTabEasy(
1119 oilsBasePath + "/acq/search/unified?so=" +
1120 base64Encode({"jub":[{"id": li.id()}]}) + "&rt=invoice"
1128 * If we haven't fleshed the lineitem_details, default to allowing access to the
1129 * holdings maintenence actions. The alternative is to flesh LIDs on every lineitem,
1130 * but that will add to page render time. Let's see if this will suffice...
1132 var lids = li.lineitem_details();
1134 (lids && !lids.filter(function(lid) { return lid.eg_copy_id() })[0] )) {
1136 actUpdateBarcodes.disabled = false;
1137 actUpdateBarcodes.onclick = function() {
1138 self.showRealCopyEditUI(li);
1139 nodeByName("action_none", row).selected = true;
1141 actHoldingsMaint.disabled = false;
1142 actHoldingsMaint.onclick =
1143 self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
1146 var state_cell = nodeByName("li_state", row);
1148 switch(li.state()) {
1151 if(typeof li.cancel_reason() == "object") {
1152 var holds_state = dojo.create(
1154 "style": "border-bottom: 1px dashed #000;",
1155 "innerHTML": li.state()
1156 }, state_cell, "only"
1160 "label": "<em>" + li.cancel_reason().label() +
1161 "</em><br />" + li.cancel_reason().description(),
1162 "connectId": [holds_state]
1163 }, dojo.create("span", null, state_cell, "last")
1175 state_cell.innerHTML = li.state(); // TODO i18n state labels
1179 this._setAlertStore = function() {
1180 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
1182 "data": acqliat.toStoreData(
1185 "owning_lib": aou.orgNodeTrail(
1186 aou.findOrgUnit(openils.User.user.ws_ou())
1187 ).map(function(o) { return o.id(); })
1193 acqLitAlertAlertText.setValue(); /* make the store "live" */
1194 acqLitAlertAlertText._store_ready = true;
1198 * Draws and shows the lineitem notes pane
1200 this.drawLiNotes = function(li) {
1202 this.focusLineitem = li.id();
1204 if (!acqLitAlertAlertText._store_ready)
1205 this._setAlertStore();
1208 li.lineitem_notes().sort(
1210 if(a.edit_time() < b.edit_time()) return 1;
1216 while(this.liNotesTbody.childNodes[0])
1217 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
1220 acqLitCreateNoteSubmit.onClick = function() {
1221 var value = acqLitCreateNoteText.attr('value');
1223 var note = new fieldmapper.acqlin();
1226 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
1229 note.lineitem(li.id());
1231 self.updateLiNotes(li, note);
1232 acqLitCreateNoteVendorPublic.attr("checked", false);
1233 acqLitCreateNoteText.attr("value", "");
1236 acqLitCreateAlertSubmit.onClick = function() {
1237 if (!acqLitAlertAlertText.item) {
1238 alert(localeStrings.ALERT_UNSELECTED);
1242 var alert_text = new fieldmapper.acqliat().fromStoreItem(
1243 acqLitAlertAlertText.item
1245 var value = acqLitAlertNoteValue.attr("value") || "";
1247 var note = new fieldmapper.acqlin();
1249 note.lineitem(li.id());
1251 note.alert_text(alert_text);
1253 self.updateLiNotes(li, note);
1256 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
1260 * Draws a single lineitem note in the notes pane
1262 this.addLiNote = function(li, note) {
1263 if(note.isdeleted()) return;
1265 var row = self.liNotesRow.cloneNode(true);
1266 nodeByName("value", row).innerHTML = note.value();
1267 var alert_node = nodeByName("alert_code", row);
1268 if (note.alert_text()) {
1269 alert_node.innerHTML = dojo.string.substitute(
1271 aou.findOrgUnit(note.alert_text().owning_lib()).shortname(),
1272 note.alert_text().code()
1275 if (note.alert_text().description()) {
1278 "connectId": [alert_node],
1279 "label": note.alert_text().description()
1280 }, dojo.create("span", null, alert_node, "after")
1285 if (openils.Util.isTrue(note.vendor_public()))
1286 nodeByName("vendor_public", row).innerHTML =
1287 localeStrings.VENDOR_PUBLIC;
1289 nodeByName("delete", row).onclick = function() {
1290 note.isdeleted(true);
1291 self.liNotesTbody.removeChild(row);
1292 self.updateLiNotes(li);
1295 if(note.edit_time()) {
1296 nodeByName("edit_time", row).innerHTML =
1297 dojo.date.locale.format(
1298 dojo.date.stamp.fromISOString(note.edit_time()),
1299 {formatLength:'short'});
1302 self.liNotesTbody.appendChild(row);
1306 * Updates any new/changed/deleted notes on the server
1308 this.updateLiNotes = function(li, newNote) {
1314 notes = li.lineitem_notes().filter(
1316 if(note.ischanged() || note.isnew() || note.isdeleted())
1322 if(notes.length == 0) return;
1323 progressDialog.show();
1325 fieldmapper.standardRequest(
1326 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
1328 params : [this.authtoken, notes],
1329 onresponse : function(r) {
1330 var resp = openils.Util.readResponse(r);
1335 // remove the old changed notes
1337 dojo.forEach(li.lineitem_notes(),
1339 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
1343 li.lineitem_notes(list);
1346 progressDialog.hide();
1347 self.updateLiNotesCount(li);
1348 self.drawLiNotes(li);
1352 progressDialog.update(resp);
1353 var newnote = resp.note;
1355 if(!newnote.isdeleted()) {
1356 newnote.isnew(false);
1357 newnote.ischanged(false);
1358 li.lineitem_notes().push(newnote);
1365 this.updateLiPrice = function(input, li) {
1367 var price = input.value;
1368 if(Number(price) == Number(li.estimated_unit_price())) return;
1370 fieldmapper.standardRequest(
1371 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
1372 { async : false, // redundant w/ timeout
1374 params : [this.authtoken, li.id(), price],
1375 oncomplete : function(r) {
1376 openils.Util.readResponse(r);
1377 li.estimated_unit_price(price); // update local copy
1380 * If this is a PO and every visible lineitem has a price,
1381 * check again to see if this PO can be activated. Note that
1382 * every visible lineitem having a price does not guarantee it can
1383 * be activated, which is why we still make the call. Having a price
1384 * set for every visiable lineitem is just the lowest barrier to entry.
1387 var priceNodes = dojo.query('[name=price]', dojo.byId('acq-lit-tbody'));
1389 dojo.forEach(priceNodes, function(node) { if (node.value == '') allSet = false});
1390 if (allSet) checkCouldActivatePo();
1397 this.removeLineitem = function(liId) {
1398 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
1399 delete this.liCache[liId];
1400 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
1403 this.drawInfo = function(liId) {
1404 this.focusLineitem = liId;
1405 if (!this._isRelatedViewer) {
1406 var d = dojo.byId("acq-lit-info-related");
1407 if (!this.relCache[liId]) {
1408 fieldmapper.standardRequest(
1411 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
1414 "params": [openils.User.authtoken, liId],
1415 "onresponse": function(r) {
1416 self.relCache[liId] = openils.Util.readResponse(r);
1417 nodeByName("related_number", d).innerHTML =
1418 self.relCache[liId];
1420 self.relCache[liId] >1 ? "show" : "hide"
1426 nodeByName("related_number", d).innerHTML = this.relCache[liId];
1427 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
1432 openils.acq.Lineitem.fetchAttrDefs(
1434 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
1439 this.toggleInlineCopies = function() {
1440 // if any inline copies are not displayed,
1441 // display them all otherwise, hide them all.
1443 var displayAll = false;
1445 for (var liId in this.liCache) {
1446 if (!this.inlineCopiesVisible(liId)) {
1452 for (var liId in this.liCache) {
1453 var row = dojo.byId('acq-inline-copies-row-' + liId);
1455 if (!row || row._hidden) {
1456 this.drawInlineCopies(liId);
1458 } else { // hide all
1460 // drawInlineCopies() on a visible row will hide it.
1461 this.drawInlineCopies(liId);
1468 this.inlineCopiesVisible = function(liId) {
1469 var row = dojo.byId('acq-inline-copies-row-' + liId);
1470 return (row && !row._hidden);
1473 this.refreshInlineCopies = function(all, reFetch) {
1475 var liIds = this.inlineCopiesNeedingRefresh;
1476 if (all) liIds = openils.Util.objectProperties(liCache);
1477 liIds.forEach(function(liId) {
1478 if (self.inlineCopiesVisible(liId)) {
1479 self.drawInlineCopies(liId, reFetch); // hide
1480 self.drawInlineCopies(liId, reFetch); // re-draw
1485 // draw inline copy table. if the table is
1486 // already visible, hide the table as-is
1487 // reFetch forces a retrieval of the lineitem and
1488 // copies from the server. otherwise the locally
1489 // cached version of each is used.
1490 this.drawInlineCopies = function(liId, reFetch) {
1493 // find or create the row where the inline copies table will live
1494 var containerRow = dojo.byId('acq-inline-copies-row-' + liId);
1495 var liRow = dojo.query('[li=' + liId + ']')[0];
1497 if (!containerRow) {
1499 // build the inline copies container row and add it to
1500 // the DOM directly after the primary lineitem row
1502 containerRow = self.inlineCopyContainer.cloneNode(true);
1503 containerRow.id = 'acq-inline-copies-row-' + liId;
1505 if (liRow.nextSibling) {
1506 self.tbody.insertBefore(containerRow, liRow.nextSibling);
1508 self.tbody.appendChild(containerRow);
1513 // toggle the visible state
1514 containerRow._hidden = !containerRow._hidden;
1515 openils.Util.toggle(containerRow, 'table-row');
1517 if (containerRow._hidden) return; // hide only
1520 var handler = function(li) {
1522 var tbody = dojo.query(
1523 '[name=acq-li-inline-copies-tbody]',
1526 // reset the table before adding copy rows
1527 while (tbody.childNodes[0])
1528 tbody.removeChild(tbody.childNodes[0]);
1530 if(li.lineitem_details().length == 0) {
1532 self.inlineNoCopies.cloneNode(true));
1533 return; // no copies to show
1536 // add a row to the inline copy table for each copy
1537 dojo.forEach(li.lineitem_details(),
1539 var row = self.inlineCopyTemplate.cloneNode(true);
1540 tbody.appendChild(row);
1541 self.addInlineCopy(li, copy, row);
1546 this._fetchLineitem(liId, handler, reFetch);
1549 /** Draw read-only copy widgets for inline copies */
1550 this.addInlineCopy = function(li, copy, row) {
1553 dojo.forEach(liDetailFields,
1556 var widget = new openils.widget.AutoFieldWidget({
1559 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1560 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1561 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1563 parentNode : dojo.query('[name=' + field + ']', row)[0],
1572 /* For a given list of lineitem ids, build a list of full lineitems
1573 * re-using the fetching logic that is otherwise typical to use in this
1576 * If we've already got a lineitem in the cache, just use that.
1578 * Once we've built a list of lineitems, call callback(thatlist).
1580 this.fetchLineitemsById = function(id_list, callback) {
1581 var total = id_list.length;
1582 var result_list = [];
1584 var inner = function(li) {
1585 result_list.push(li)
1587 callback(result_list);
1590 id_list.forEach(function(id) { self._fetchLineitem(id, inner); });
1593 this._fetchLineitem = function(liId, handler, force) {
1595 var li = this.liCache[liId];
1596 if(li && li.marc() && li.lineitem_details() && !force)
1599 fieldmapper.standardRequest(
1600 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
1603 params: [self.authtoken, liId, {
1605 flesh_cancel_reason: true,
1606 flesh_li_details: true,
1608 flesh_fund_debit: true }],
1610 oncomplete: function(r) {
1611 var li = openils.Util.readResponse(r);
1612 self.liCache[liId] = li;
1619 this._drawInfo = function(li) {
1621 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
1623 if(li.eg_bib_id()) {
1624 openils.Util.hide('acq-lit-marc-order-record-label');
1625 openils.Util.hide(acqLitEditOrderMarc.domNode);
1626 openils.Util.show('acq-lit-marc-real-record-label');
1628 openils.Util.show('acq-lit-marc-order-record-label');
1629 openils.Util.show(acqLitEditOrderMarc.domNode);
1630 openils.Util.hide('acq-lit-marc-real-record-label');
1633 this.drawMarcHTML(li);
1634 this.infoTbody = dojo.byId('acq-lit-info-tbody');
1637 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
1638 while(this.infoTbody.childNodes[0])
1639 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
1641 for(var i = 0; i < li.attributes().length; i++) {
1642 var attr = li.attributes()[i];
1643 var row = this.infoRow.cloneNode(true);
1645 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
1646 var name = openils.acq.Lineitem.attrDefs[type].filter(
1648 return (a.code() == attr.attr_name());
1650 ).pop().description();
1652 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
1653 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
1654 this.infoTbody.appendChild(row);
1657 if (!this._isRelatedViewer) {
1658 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
1659 oilsBasePath + "/acq/lineitem/related/" + li.id();
1662 // if a top scroll point is defined, jump up to it here
1663 var node = dojo.byId('oils-scroll-to-top');
1664 if (node) dijit.scrollIntoView(node);
1667 this.generateMakeRecTab = function(bib_id,default_view, row) {
1671 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
1674 show_nav_buttons : true,
1675 show_print_button : true,
1676 opac_url : xulG.url_prefix('opac_rdetail|' + bib_id),
1677 default_view : default_view
1681 if(row) nodeByName("action_none", row).selected = true;
1685 this.drawMarcHTML = function(li) {
1686 var params = [null, true, li.marc()];
1688 params = [li.eg_bib_id(), true];
1690 fieldmapper.standardRequest(
1691 ['open-ils.search', 'open-ils.search.biblio.record.html'],
1694 oncomplete: function(r) {
1695 dojo.byId('acq-lit-marc-div').innerHTML =
1696 openils.Util.readResponse(r);
1702 this.drawCopies = function(liId, force_fetch) {
1703 this.focusLineitem = liId;
1704 if (typeof force_fetch == "undefined")
1705 force_fetch = false;
1707 var cgi = new openils.CGI();
1708 var source = cgi.param('source');
1709 if (source && source.match(/invoice/)) {
1710 // got here from the invoice page, show the 'return-to-invoice' button
1711 var cgi = new openils.CGI({url : source});
1712 cgi.param('focus_li', liId);
1713 openils.Util.show(dojo.byId('acq-lit-copies-back-to-invoice-button-wrapper'), 'inline');
1714 var button = dojo.byId('acq-lit-copies-back-to-invoice-button');
1715 button.onclick = function() { location.href = cgi.url() };
1718 openils.acq.Lineitem.fetchAndRender(liId, {},
1719 function(li, html) {
1720 dojo.byId('acq-lit-copies-li-summary').innerHTML = html;
1724 this.show('copies');
1726 this.copyCache = {};
1727 this.copyWidgetCache = {};
1728 this.oldCopyWidgetCache = {};
1729 this.virtDfaCounts = {};
1730 this.realDfaCache = {};
1733 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
1734 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
1735 acqLitCopyCountInput.attr('value', '0');
1737 if (this.isPO && PO && PO.order_date()) {
1738 // prevent adding copies to activated POs
1739 acqLitCopyCountInput.attr('disabled', true);
1740 acqLitAddCopyCount.attr('disabled', true);
1743 while(this.copyTbody.childNodes[0])
1744 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
1746 this._drawBatchCopyWidgets();
1748 this._drawDistribApplied(liId);
1750 this._fetchDistribFormulas(
1752 openils.acq.Lineitem.fetchAttrDefs(
1754 self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch);
1761 this._saveDistribAppliedTemplates = function() {
1762 if (!this._appliedDistribTemplate) {
1763 this._appliedDistribTemplate =
1764 dojo.byId("acq-lit-distrib-applied-tbody").
1765 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
1766 dojo.attr(this._appliedDistribTemplate, "id");
1770 this._drawDistribApplied = function(liId) {
1771 /* Build this table while hidden to prevent rendering artifacts */
1772 openils.Util.hide("acq-lit-distrib-applied-tbody");
1774 this._saveDistribAppliedTemplates();
1776 /* Remove any rows in the table from previous populations */
1777 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
1778 forEach(dojo.destroy);
1780 /* Unregister all dijits previously created (for some reason this isn't
1781 * covered by the above destroy calls). */
1782 dijit.registry.forEach(
1783 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
1786 /* Populate the table with our liId */
1788 fieldmapper.standardRequest(
1790 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
1793 "params": [self.authtoken, liId],
1794 "onresponse": function(r) {
1795 var dfa = openils.Util.readResponse(r);
1798 self.realDfaCache[dfa.id()] = dfa;
1799 self._drawDistribAppliedUnit(dfa);
1802 "oncomplete": function() {
1803 /* Reveal built table */
1806 "acq-lit-distrib-applied-tbody", "table-row-group"
1814 this._drawDistribAppliedUnit = function(dfa) {
1815 var new_row = false;
1816 var row = dojo.query(
1817 'tr[formula="' + dfa.formula().id() + '"]',
1818 "acq-lit-distrib-applied-tbody"
1823 row = dojo.clone(this._appliedDistribTemplate);
1824 dojo.attr(row, "formula", dfa.formula().id());
1825 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
1828 var td = dojo.query("td", row)[0];
1830 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1831 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1834 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1836 new dijit.form.Button(
1838 "onClick": function() {
1839 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1840 self.deleteDfa(dfa);
1843 /* XXX I /cannot/ make the following work in as a CSS class
1844 * for some reason. So frustrating... */
1845 "style": function(id) {
1847 "font-weight: bold; color: #c00;" :
1849 }(dfa.id()) + "margin: 0 6px;display: inline;"
1850 }, "dfa-button-" + dfa.id()
1854 "connectId": ["dfa-button-" + dfa.id()],
1855 "label": dojo.string.substitute(
1856 localeStrings.DFA_TIP, dfa.id() > 0 ? [
1857 openils.User.formalName(dfa.creator()),
1858 dojo.date.locale.format(
1859 dojo.date.stamp.fromISOString(dfa.create_time()),
1860 {"formatLength":"short"}
1862 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
1864 }, "dfa-tip-" + dfa.id()
1868 this.deleteDfa = function(dfa) {
1869 if (dfa.id() > 0) { /* real */
1870 this.pcrud.eliminate(
1873 "oncomplete": function() {
1874 self._removeDistribApplied(dfa.id());
1875 delete self.realDfaCache[dfa.id()];
1879 } else { /* virtual */
1880 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
1881 this.virtDfaCounts[dfa.formula().id()] = 0;
1882 /* hasn't been saved yet, so no need to do anything server side */
1883 this._removeDistribApplied(dfa.id());
1888 this._removeDistribApplied = function(dfaId) {
1889 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
1890 dijit.registry.forEach(
1891 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
1893 this._removeDistribAppliedEmptyRows();
1896 this._removeAllDistribAppliedVirtual = function() {
1897 /* Unregister dijits */
1898 dijit.registry.forEach(
1899 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
1901 this._removeDistribAppliedEmptyRows();
1904 this._removeDistribAppliedEmptyRows = function() {
1905 /* Remove any rows with no DFA at all */
1906 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
1908 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
1914 * Insert a new row into the distribution formula selection form
1916 this._addDistribFormulaRow = function() {
1919 if (!self.distribForms) {
1920 // no formulas, hide the form
1921 openils.Util.hide('acq-lit-distrib-formula-table');
1925 if(!this.distribFormulaTemplate)
1926 this.distribFormulaTemplate =
1927 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
1929 var row = this.distribFormulaTemplate.cloneNode(true);
1930 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
1932 this.dfSelector = new dijit.form.FilteringSelect(
1933 {"labelAttr": "dynLabel", "labelType": "html"},
1934 nodeByName("selector", row)
1936 this._updateFormulaStore();
1937 this.dfSelector.fetchProperties =
1938 {"sort": [{"attribute": "use_count", "descending": true}]};
1940 var apply = new dijit.form.Button(
1941 {"label": localeStrings.APPLY},
1942 nodeByName('set_button', row)
1945 var reset = new dijit.form.Button(
1946 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
1947 nodeByName("reset_button", row)
1950 dojo.connect(apply, 'onClick',
1952 var form_id = self.dfSelector.attr("value");
1953 if(!form_id) return;
1954 self._applyDistribFormula(form_id);
1955 reset.attr("disabled", false);
1959 dojo.connect(reset, 'onClick',
1961 self.restoreCopyFieldsBeforeDF();
1962 self.virtDfaCounts = {};
1963 self.virtDfaId = -1;
1965 self._updateFormulaStore();
1966 self._removeAllDistribAppliedVirtual();
1967 reset.attr("disabled", "true");
1974 * Applies a distrib formula to the current set of copies
1976 this._applyDistribFormula = function(formula) {
1977 if(!formula) return;
1979 formula = this.distribForms.filter(
1980 function(form) { return form.id() == formula; }
1983 var copyRows = dojo.query('tr', self.copyTbody);
1985 if (this.dfeOffset >= copyRows.length) {
1986 alert(localeStrings.OUT_OF_COPIES);
1990 var entries_applied = 0;
1992 var rowIndex = this.dfeOffset;
1993 rowIndex < copyRows.length;
1997 var row = copyRows[rowIndex];
1998 var copy_id = row.getAttribute('copy_id');
1999 var copyWidgets = this.copyWidgetCache[copy_id];
2000 var entryIndex = this.dfeOffset;
2003 // find the correct entry for the current row
2004 dojo.forEach(formula.entries(),
2007 entryIndex += e.item_count();
2008 if(entryIndex > rowIndex)
2016 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
2017 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
2020 this.saveCopyFieldsBeforeDF(copy_id);
2021 this._copy_fields_for_acqdf.forEach(
2023 if(entry[field]()) {
2024 copyWidgets[field].attr('value', (entry[field]()));
2031 if (entries_applied) {
2032 this.virtDfaCounts[formula.id()] =
2033 ++(this.virtDfaCounts[formula.id()]) || 1;
2034 this._updateFormulaStore();
2035 this._drawDistribAppliedUnit(
2037 var dfa = new acqdfa();
2038 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
2041 this.dfeOffset += entries_applied;
2046 * This function updates the DF store for the dropdown so that use_counts
2047 * can reflect DF applications from this session before they're saved
2050 this._updateFormulaStore = function() {
2051 this.dfSelector.store = new dojo.data.ItemFileReadStore(
2053 "data": self._labelFormulasWithCounts(
2054 acqdf.toStoreData(self.distribForms)
2060 this.saveCopyFieldsBeforeDF = function(copy_id) {
2062 if (!this.oldCopyWidgetCache[copy_id]) {
2063 var copyWidgets = this.copyWidgetCache[copy_id];
2065 this.oldCopyWidgetCache[copy_id] = {};
2066 this._copy_fields_for_acqdf.forEach(
2068 self.oldCopyWidgetCache[copy_id][f] =
2069 copyWidgets[f].attr("value");
2075 this.restoreCopyFieldsBeforeDF = function() {
2077 for (var copy_id in this.oldCopyWidgetCache) {
2078 this._copy_fields_for_acqdf.forEach(
2080 self.copyWidgetCache[copy_id][f].attr(
2081 "value", self.oldCopyWidgetCache[copy_id][f]
2088 this._labelFormulasWithCounts = function(store_data) {
2089 for (var key in store_data.items) {
2090 var obj = store_data.items[key];
2091 obj.use_count = Number(obj.use_count); /* needed for sorting */
2093 if (this.virtDfaCounts[obj.id])
2094 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
2096 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
2097 obj.use_count + "]</span> " + obj.name;
2103 * This method formerly would not refetch the DF formulas if they'd been
2104 * loaded already, but now it always re-fetches, since use_count changes.
2106 /** TODO: port distrib-formula selector to autofieldwidget+pcrud/dojo store */
2107 this._fetchDistribFormulas = function(onload) {
2108 fieldmapper.standardRequest(
2110 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
2113 "params": [openils.User.authtoken, 0, 500],
2114 "oncomplete": function(r) {
2115 self.distribForms = openils.Util.readResponse(r);
2116 if(!self.distribForms || self.distribForms.length == 0) {
2117 self.distribForms = [];
2119 self._addDistribFormulaRow();
2126 this._drawBatchCopyWidgets = function() {
2127 var row = this.copyBatchRow;
2128 dojo.forEach(liDetailBatchFields,
2130 if(self.copyBatchRowDrawn) {
2131 self.copyBatchWidgets[field].attr('value', null);
2133 var args = self.afwCopyFieldArgs(field, "CREATE_PICKLIST");
2134 args.parentNode = dojo.query('[name='+field+']', row)[0];
2136 var widget = new openils.widget.AutoFieldWidget(args);
2139 if (field == "fund" && w.store)
2140 self._ensureCSSFundClasses(w.store);
2141 self.copyBatchWidgets[field] = w;
2144 if (field == "fund") {
2146 widget.widget, "onChange", function(val) {
2147 self._updateFundSelectorStyle(widget, val);
2154 this.copyBatchRowDrawn = true;
2157 this.batchCopyUpdate = function() {
2159 for(var k in this.copyWidgetCache) {
2160 var cache = this.copyWidgetCache[k];
2161 dojo.forEach(liDetailBatchFields, function(f) {
2162 var newval = self.copyBatchWidgets[f].attr('value');
2163 if(newval) cache[f].attr('value', newval);
2168 this._drawCopies = function(li) {
2171 // this button sets the total number of copies for a given lineitem
2172 acqLitAddCopyCount.onClick = function() {
2173 var count = acqLitCopyCountInput.attr('value');
2176 while(self.copyCount() < count)
2179 // delete rows if necessary
2180 var diff = self.copyCount() - count;
2182 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
2183 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
2184 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
2186 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2192 if(li.lineitem_details().length > 0) {
2193 dojo.forEach(li.lineitem_details(),
2195 self.addCopy(li, copy);
2203 this.copyCount = function() {
2205 for(var id in this.copyCache) {
2206 if(!this.copyCache[id].isdeleted())
2212 this.virtCopyId = -1;
2213 this.addCopy = function(li, copy) {
2214 var row = this.copyRow.cloneNode(true);
2215 this.copyTbody.appendChild(row);
2219 copy = new fieldmapper.acqlid();
2221 copy.id(this.virtCopyId--);
2222 copy.lineitem(li.id());
2225 this.copyCache[copy.id()] = copy;
2226 row.setAttribute('copy_id', copy.id());
2227 self.copyWidgetCache[copy.id()] = {};
2229 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2231 var rcvr = copy.receiver();
2233 if (!userCache[rcvr]) {
2234 if(rcvr == openils.User.user.id()) {
2235 userCache[rcvr] = openils.User.user;
2237 userCache[rcvr] = fieldmapper.standardRequest(
2238 ['open-ils.actor', 'open-ils.actor.user.retrieve'],
2239 {params: [openils.User.authtoken, rcvr]}
2243 dojo.query('[name=receiver]', row)[0].innerHTML = userCache[rcvr].usrname();
2246 dojo.forEach(liDetailFields,
2249 if (field == "fund") {
2250 searchFilter = (copy.fund() ?
2251 {"-or": {"active": "t", "id": copy.fund()}} :
2254 searchFilter = null;
2257 var readOnly = false;
2259 // TODO: Add support for changing the owning_lib after real copies have been made.
2260 // owning_lib is order data as much as its item data
2261 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
2265 // TODO: add support for changing the fund after debits have been created
2266 // Note: invoicing allows the change
2267 if(copy.fund_debit() && field == 'fund') {
2272 var widget = new openils.widget.AutoFieldWidget({
2275 labelFormat : (field == 'fund') ? fundLabelFormat : null,
2276 searchFormat : (field == 'fund') ? fundSearchFormat : null,
2277 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
2278 searchFilter : searchFilter,
2279 noCache: (field == "fund"),
2281 parentNode : dojo.query('[name='+field+']', row)[0],
2282 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2283 readOnly : readOnly,
2284 orgDefaultsToWs : true
2288 // make sure we capture the value from any async widgets
2291 if (field == "fund" && w.store)
2292 self._ensureCSSFundClasses(w.store);
2295 copy[field](ww.getFormattedValue())
2297 self.copyWidgetCache[copy.id()][field] = w;
2299 dojo.connect(w, 'onChange',
2301 if (field == "fund")
2302 self._updateFundSelectorStyle(widget, val);
2304 if (!readOnly && (copy.isnew() || val != copy[field]())) {
2305 // prevent setting ischanged() automatically on widget load for existing copies
2306 copy[field](widget.getFormattedValue())
2307 copy.ischanged(true);
2316 this.updateLidState(copy, row);
2319 this._ensureCSSFundClass = function(id) {
2320 if (!this.fundStyleSheet) {
2322 "style", {"type": "text/css"},
2323 document.getElementsByTagName("head")[0], "last"
2325 this.fundStyleSheet = document.styleSheets[
2326 document.styleSheets.length - 1
2330 var cn = "fund_" + id;
2331 if (!this.haveFundClass[cn]) {
2332 fieldmapper.standardRequest(
2333 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
2335 "params": [openils.User.authtoken, id],
2337 "oncomplete": function(r) {
2338 r = openils.Util.readResponse(r);
2339 self.fundBalanceState[id] = r;
2341 if (r[0] /* stop */)
2342 style = fundStyles.stop;
2343 else if (r[1] /* warning */)
2344 style = fundStyles.warning;
2345 self.fundStyleSheet.insertRule(
2346 "." + cn + " { " + style + " }",
2347 self.fundStyleSheet.cssRules.length
2349 self.haveFundClass[cn] = true;
2356 this._ensureCSSFundClasses = function(store) {
2358 "query": {"id": "*"},
2359 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
2363 this._updateFundSelectorStyle = function(widget, fund_id) {
2364 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
2365 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
2368 this.updateLidState = function(copy, row) {
2371 if (typeof(row) == "undefined") {
2372 row = dojo.query('tr[copy_id="' + copy.id() + '"]', this.copyTbody)[0];
2376 var recv_link = nodeByName("receive", row);
2377 var unrecv_link = nodeByName("unreceive", row);
2378 var del_link = nodeByName("delete", row);
2379 var cxl_link = nodeByName("cancel", row);
2380 var claim_link = nodeByName("claim", row);
2381 var cxl_reason_link = nodeByName("cancel_reason", row);
2383 // by default, hide all the actions
2384 openils.Util.hide(del_link.parentNode);
2385 openils.Util.hide(recv_link);
2386 openils.Util.hide(unrecv_link);
2387 openils.Util.hide(cxl_link);
2388 openils.Util.hide(claim_link);
2389 openils.Util.hide(cxl_reason_link);
2391 if (copy.id() > 0) { // real copies (LIDs)
2393 if (copy.cancel_reason()) {
2395 /* --------- cancelled -------------------------- */
2397 /* XXX the following may leak memory in a long lived table:
2398 * dijits may not get destroyed... not positive. revisit. */
2399 var holds_reason = dojo.create(
2401 "style": "border-bottom: 1px dashed #000;",
2402 "innerHTML": "Cancelled" /* XXX [sic] and i18n */
2403 }, cxl_reason_link, "only"
2407 "label": "<em>" + copy.cancel_reason().label() +
2408 "</em><br />" + copy.cancel_reason().description(),
2409 "connectId": [holds_reason]
2410 }, dojo.create("span", null, cxl_reason_link, "last")
2412 openils.Util.show(cxl_reason_link, "inline");
2414 } else if (copy.recv_time()) {
2416 /* --------- received -------------------------- */
2418 openils.Util.show(unrecv_link, "inline");
2419 unrecv_link.onclick = function() {
2420 if (confirm(localeStrings.UNRECEIVE_LID))
2421 self.issueReceive(copy, /* rollback */ true);
2424 } else if (this.liCache[copy.lineitem()].state() == 'on-order') {
2426 /* --------- on order -------------------------- */
2428 openils.Util.show(recv_link, 'inline');
2429 openils.Util.show(cxl_link, "inline");
2431 recv_link.onclick = function() {
2432 if (self.checkLiAlerts(copy.lineitem()))
2433 self.issueReceive(copy);
2436 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2440 /* --------- pre-order copies -------------------------- */
2442 del_link.onclick = function() { self.deleteCopy(row) };
2443 openils.Util.show(del_link.parentNode);
2449 /* --------- virtual copies -------------------------- */
2451 del_link.onclick = function() { self.deleteCopy(row) };
2452 openils.Util.show(del_link.parentNode);
2456 this.cancelLid = function(lid_id) {
2457 lidCancelDialog._lid_id = lid_id;
2458 openils.Util.show(lidCancelDialog.domNode.parentNode);
2459 lidCancelDialog.show();
2460 if (!lidCancelDialog._prepared) {
2461 var widget = new openils.widget.AutoFieldWidget({
2462 "fmField": "cancel_reason",
2463 "fmClass": "acqlid",
2464 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
2465 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2470 acqLidCancelButton.onClick = function() {
2471 if (w.attr("value")) {
2472 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
2474 lidCancelDialog._lid_id,
2478 lidCancelDialog.hide();
2481 lidCancelDialog._prepared = true;
2487 this._cancelLid = function(lid_id, reason) {
2488 fieldmapper.standardRequest(
2489 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
2490 "params": [openils.User.authtoken, lid_id, reason],
2492 "onresponse": function(r) {
2493 if (r = openils.Util.readResponse(r)) {
2495 for (var id in r.lid) {
2496 /* actually this should only iterate once */
2497 self.copyCache[id].cancel_reason(
2498 r.lid[id].cancel_reason
2500 self.updateLidState(self.copyCache[id]);
2509 this._confirmAlert = function(li, lin) {
2511 dojo.string.substitute(
2512 localeStrings.CONFIRM_LI_ALERT, [
2513 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2514 "title", "lineitem_marc_attr_definition"
2516 /* XXX it's really better add a parameter and to adjust
2517 * the format string rather than do this concatenation
2518 * here, but if someone wants this for 2.2 in a hurry,
2519 * we can sidestep the problem of updating the strings
2520 * while the translators are working. */
2522 aou.findOrgUnit(lin.alert_text().owning_lib()).shortname() +
2524 lin.alert_text().code()
2526 lin.alert_text().description() || "",
2533 this.checkLiAlerts = function(li_id) {
2534 var li = this.liCache[li_id];
2536 var alert_notes = li.lineitem_notes().filter(
2537 function(o) { return Boolean(o.alert_text()); }
2540 /* this is _intentionally_ not done in a call to forEach() ... */
2541 for (var i = 0; i < alert_notes.length; i++) {
2542 if (this.noteAcks[alert_notes[i].id()])
2544 else if (!this._confirmAlert(li, alert_notes[i]))
2547 this.noteAcks[alert_notes[i].id()] = true;
2553 this.deleteCopy = function(row) {
2554 var copy = this.copyCache[row.getAttribute('copy_id')];
2555 copy.isdeleted(true);
2557 delete this.copyCache[copy.id()];
2558 this.copyTbody.removeChild(row);
2561 this._virtDfaCountsAsList = function() {
2563 for (var key in this.virtDfaCounts) {
2564 for (var i = 0; i < this.virtDfaCounts[key]; i++)
2570 this.confirmBreachedCopyFunds = function(copies) {
2571 var stop = 0, warning = 0;
2575 var state = self.fundBalanceState[o.fund()];
2576 if (state[0] /* stop */)
2578 else if (state[1] /* warning */)
2585 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
2586 } else if (warning) {
2587 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
2592 this.saveCopyChanges = function(liId) {
2598 for(var id in this.copyCache) {
2599 var c = this.copyCache[id];
2600 if(!c.isdeleted()) total++;
2601 if(c.isnew() || c.ischanged() || c.isdeleted()) {
2602 if(c.id() < 0) c.id(null);
2608 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
2611 if (copies.length > 0) {
2612 if (!this.confirmBreachedCopyFunds(copies))
2615 if (typeof(this._copy_count_cb) == "function")
2616 this._copy_count_cb(liId, total);
2618 openils.Util.show("acq-lit-update-copies-progress");
2619 fieldmapper.standardRequest(
2620 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
2622 params: [openils.User.authtoken, copies],
2623 onresponse: function(r) {
2624 var res = openils.Util.readResponse(r);
2625 litUpdateCopiesProgress.update(res);
2627 oncomplete: function() {
2628 self.drawCopies(liId, true /* force_fetch */);
2629 openils.Util.hide("acq-lit-update-copies-progress");
2635 var dfa_list = this._virtDfaCountsAsList();
2636 if (dfa_list.length > 0) {
2637 fieldmapper.standardRequest(
2639 "open-ils.acq.distribution_formula.record_application"],
2642 "params": [openils.User.authtoken, dfa_list, liId],
2643 "onresponse": function(r) {
2644 var res = openils.Util.readResponse(r);
2645 if (res && res.length < dfa_list.length)
2646 alert(localeStrings.DFA_NOT_ALL);
2650 this.virtDfaCounts = {};
2653 if (this.inlineCopiesNeedingRefresh.indexOf(liId) < 0)
2654 this.inlineCopiesNeedingRefresh.push(liId);
2657 this._updateCreatePoPrepayCheckbox = function(prepay) {
2658 var prepay = openils.Util.isTrue(prepay);
2659 this._prepayRequiredByVendor = prepay;
2660 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
2663 this._confirmPoPrepaySituation = function() {
2664 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
2665 if (want_prepay != this._prepayRequiredByVendor) {
2668 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
2669 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
2676 this.applySelectedLiAction = function(action) {
2680 case 'delete_selected':
2681 this._deleteLiList(self.getSelected());
2684 case 'add_to_order':
2685 addToPoDialog._get_li = dojo.hitch(
2687 function() { return this.getSelected(false, null, true); }
2689 addToPoDialog.show();
2692 case 'create_order':
2693 this._loadPOSelect();
2694 acqLitPoCreateDialog.show();
2697 case 'save_picklist':
2698 acqLitSavePlDialog.show();
2701 case 'selector_ready':
2703 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
2704 acqLitChangeLiStateDialog.show();
2712 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
2715 case 'batch_create_invoice':
2716 this.batchCreateInvoice();
2719 case 'batch_link_invoice':
2720 this.batchLinkInvoice();
2723 case 'receive_lineitems':
2724 this.receiveSelectedLineitems();
2727 case 'rollback_receive_lineitems':
2728 this.rollbackReceiveLineitems();
2731 case 'create_assets':
2732 this.showAssetCreator();
2735 case 'export_attr_list':
2736 this.chooseExportAttr();
2739 case 'batch_apply_funds':
2740 this.applyBatchLiFunds();
2743 case 'add_brief_record':
2745 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
2747 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
2751 case "cancel_lineitems":
2752 this.maybeCancelLineitems();
2755 case "apply_claim_policy":
2756 var li_list = this.getSelected();
2757 this.claimPolicyPicker.attr("value", null);
2758 liClaimPolicyDialog.show();
2759 liClaimPolicySave.onClick = function() {
2760 self.changeClaimPolicy(
2762 self.claimPolicyPicker.attr("value"),
2766 self.setClaimPolicyControl(li);
2767 self.reconsiderClaimControl(li);
2770 liClaimPolicyDialog.hide();
2778 this.changeClaimPolicy = function(li_list, value, callback) {
2780 function(li) { li.claim_policy(value); }
2782 fieldmapper.standardRequest(
2783 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
2784 "params": [openils.User.authtoken, li_list],
2786 "oncomplete": function(r) {
2787 r = openils.Util.readResponse(r);
2788 if (callback) callback(r);
2794 this.showAssetCreator = function(onAssetsCreated) {
2795 if(!this.isPO) return;
2798 // first, let's see if this PO has any LI's that need to be merged/imported
2799 self.pcrud.search('jub', {purchase_order : this.isPO, eg_bib_id : null}, {
2801 oncomplete : function(r) {
2802 var resp = openils.Util.readResponse(r);
2803 if (resp && resp.length) {
2804 // PO has some non-linked jubs.
2806 self.show('asset-creator');
2807 if(!self.vlAgent.loaded)
2808 self.vlAgent.init();
2810 dojo.connect(assetCreatorButton, 'onClick',
2811 function() { self.createAssets(onAssetsCreated) });
2815 // all jubs linked, move on to asset creation
2816 self.createAssets(onAssetsCreated, true);
2822 this.createAssets = function(onAssetsCreated, noVl) {
2823 this.show('acq-lit-progress-numbers');
2825 var vlArgs = (noVl) ? {} : {vandelay : this.vlAgent.values()};
2826 fieldmapper.standardRequest(
2827 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
2829 params: [this.authtoken, this.isPO, vlArgs],
2830 onresponse: function(r) {
2831 var resp = openils.Util.readResponse(r);
2832 self._updateProgressNumbers(resp, !Boolean(onAssetsCreated), onAssetsCreated);
2838 this.maybeCancelLineitems = function() {
2839 openils.Util.show("acq-lit-cancel-reason", "inline");
2840 if (!acqLitCancelLineitemsButton._prepared) {
2841 var widget = new openils.widget.AutoFieldWidget({
2842 "fmField": "cancel_reason",
2844 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
2845 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2850 acqLitCancelLineitemsButton.onClick = function() {
2851 if (w.attr("value")) {
2852 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
2853 self._cancelLineitems(w.attr("value"));
2855 openils.Util.hide("acq-lit-cancel-reason");
2858 acqLitCancelLineitemsButton._prepared = true;
2864 this._cancelLineitems = function(reason) {
2865 var id_list = this.getSelected().map(function(o) { return o.id(); });
2866 fieldmapper.standardRequest(
2867 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
2868 "params": [openils.User.authtoken, id_list, reason],
2870 "onresponse": function(r) {
2871 if (r = openils.Util.readResponse(r)) {
2873 for (var id in r.li) {
2874 self.liCache[id].state(r.li[id].state);
2875 self.liCache[id].cancel_reason(
2876 r.li[id].cancel_reason
2878 self.updateLiState(self.liCache[id]);
2881 if (r.lid && self.copyCache) {
2882 for (var id in r.lid) {
2883 if (self.copyCache[id]) {
2884 self.copyCache[id].cancel_reason(
2885 r.lid[id].cancel_reason
2887 self.updateLidState(self.copyCache[id]);
2897 this.chooseExportAttr = function() {
2898 if (!acqLitExportAttrSelector._li_setup) {
2900 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
2902 "data": acqlimad.toStoreData(
2904 "acqlimad", {"code": li_exportable_attrs}
2909 acqLitExportAttrSelector.setValue();
2910 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
2911 acqLitExportAttrSelector._li_setup = true;
2913 openils.Util.show("acq-lit-export-attr-holder", "inline");
2916 this.exportAttrList = function() {
2917 var attr_def = acqLitExportAttrSelector.item;
2918 var li_list = this.getSelected();
2919 var value_list = li_list.map(
2921 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2922 attr_def.code, "lineitem_marc_attr_definition"
2925 ).filter(function(attr) { return Boolean(attr); });
2927 if (value_list.length > 0) {
2928 if (value_list.length < li_list.length) {
2930 dojo.string.substitute(
2931 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
2938 openils.XUL.contentToFileSaveDialog(
2939 value_list.join("\n"),
2940 localeStrings.EXPORT_SAVE_DIALOG_TITLE
2946 alert(dojo.string.substitute(
2947 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
2951 openils.Util.hide("acq-lit-export-attr-holder");
2954 this.printPO = function() {
2955 if(!this.isPO) return;
2956 progressDialog.show(true);
2957 fieldmapper.standardRequest(
2958 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
2960 params: [this.authtoken, this.isPO, 'html'],
2961 oncomplete: function(r) {
2962 progressDialog.hide();
2963 var evt = openils.Util.readResponse(r);
2964 if(evt && evt.template_output()) {
2965 openils.Util.printHtmlString(evt.template_output().data());
2972 this.batchCreateInvoice = function() {
2973 var liIds = this.getSelected(false, null, true /* id_list */)
2974 if (!liIds.length) return;
2975 var path = oilsBasePath + '/acq/invoice/view?create=1';
2976 dojo.forEach(liIds, function(li, idx) { path += '&attach_li=' + li });
2977 if (openils.XUL.isXUL())
2978 openils.XUL.newTabEasy(path, localeStrings.NEW_INVOICE, null, true);
2980 location.href = path;
2983 this.batchLinkInvoice = function(create) {
2984 var liIds = this.getSelected(false, null, true /* id_list */)
2985 if (!liIds.length) return;
2986 if (!self.invoiceLinkDialogManager) {
2987 self.invoiceLinkDialogManager =
2988 new InvoiceLinkDialogManager("li");
2990 self.invoiceLinkDialogManager.target = liIds;
2991 acqLitLinkInvoiceDialog.show();
2994 this.receiveSelectedLineitems = function() {
2995 var li_list = this.getSelected();
2997 if (!li_list.length) {
2998 alert(localeStrings.NO_LI_GENERAL);
3002 for (var i = 0; i < li_list.length; i++) {
3003 var li = li_list[i];
3005 if (li.state() != "received" &&
3006 !this.checkLiAlerts(li.id())) return;
3009 this.show('acq-lit-progress-numbers');
3012 fieldmapper.standardRequest(
3013 ['open-ils.acq', 'open-ils.acq.lineitem.receive.batch'],
3017 li_list.map(function(li) { return li.id(); })
3019 onresponse : function(r) {
3020 var resp = openils.Util.readResponse(r);
3021 self._updateProgressNumbers(resp, true);
3027 this.issueReceive = function(obj, rollback) {
3029 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
3031 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
3033 progressDialog.show(true);
3034 fieldmapper.standardRequest(
3035 ["open-ils.acq", method], {
3037 "params": [this.authtoken, obj.id()],
3038 "onresponse": function(r) {
3039 if (r = openils.Util.readResponse(r)) {
3040 self.fetchClaimInfo(
3041 part == "lineitem" ? obj.id() : obj.lineitem(),
3043 function() { self.handleReceive(r); }
3045 progressDialog.hide();
3053 * Handles the responses from receive and rollback ML calls.
3055 this.handleReceive = function(resp) {
3058 for (var li_id in resp.li) {
3059 for (var key in resp.li[li_id])
3060 self.liCache[li_id][key](resp.li[li_id][key]);
3061 self.updateLiState(self.liCache[li_id]);
3065 if (typeof(self.poUpdateCallback) == "function")
3066 self.poUpdateCallback(resp.po);
3069 for (var lid_id in resp.lid) {
3070 for (var key in resp.lid[lid_id])
3071 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
3072 self.updateLidState(self.copyCache[lid_id]);
3078 this.rollbackReceiveLineitems = function() {
3079 var li_id_list = this.getSelected(false, null, true);
3080 if (!li_id_list.length) {
3081 alert(localeStrings.NO_LI_GENERAL);
3085 if (!confirm(localeStrings.ROLLBACK_LI_RECEIVE_CONFIRM)) return;
3087 this.show('acq-lit-progress-numbers');
3090 fieldmapper.standardRequest(
3091 ['open-ils.acq', 'open-ils.acq.lineitem.receive.rollback.batch'],
3093 params: [this.authtoken, li_id_list],
3094 onresponse : function(r) {
3095 var resp = openils.Util.readResponse(r);
3096 self._updateProgressNumbers(resp, true);
3102 this._updateProgressNumbers = function(resp, reloadOnComplete, onComplete) {
3103 this.vlAgent.handleResponse(resp,
3104 function(resp, res) {
3105 if(reloadOnComplete)
3106 location.href = location.href;
3108 onComplete(resp, res);
3114 this._createPO = function(fields) {
3115 var wantall = (fields.create_from == "all");
3117 /* If we're a picklist or purchase order already and the user wants
3118 * all lineitems, we might have pages' worth of lineitems haven't all
3119 * been loaded yet, so getSelected() won't find them. The server,
3120 * however, should know about all our lineitems, so let's ask the
3121 * server for a complete list.
3126 true, function(list) {
3127 self._createPOFromLineitems(fields, list);
3128 }, /* id_list */ true
3131 this._createPOFromLineitems(fields, this.getSelected(false, null, true /* id_list */));
3135 this._createPOFromLineitems = function(fields, selected) {
3136 if (selected.length == 0) return;
3139 var po = new fieldmapper.acqpo();
3140 po.provider(this.createPoProviderSelector.attr("value"));
3141 po.ordering_agency(this.createPoAgencySelector.attr("value"));
3142 po.prepayment_required(fields.prepayment_required[0] ? true : false);
3144 // if we're creating assets, delay the asset creation
3145 // until after the PO is created. This will allow us to
3146 // use showAssetCreator() directly.
3148 fieldmapper.standardRequest(
3149 ["open-ils.acq", "open-ils.acq.purchase_order.create"],
3152 openils.User.authtoken,
3153 po, {lineitems : selected}
3155 onresponse : function(r) {
3156 var resp = openils.Util.readResponse(r);
3157 if (resp.complete) {
3158 // self.isPO is needed for showAssetCreator();
3159 self.isPO = resp.purchase_order.id();
3160 var redir = oilsBasePath + "/acq/po/view/" + self.isPO;
3161 if (fields.create_assets[0]) {
3162 self.showAssetCreator(
3163 function() {location.href = redir}
3166 location.href = redir;
3175 this.batchFundWidget = null;
3177 this.applyBatchLiFunds = function() {
3179 var liIds = this.getSelected().map(function(li) { return li.id(); });
3180 if(liIds.length == 0) return; // warn?
3183 batchFundUpdateDialog.show();
3185 if(!this.batchFundWidget) {
3186 this.batchFundWidget = new openils.widget.AutoFieldWidget({
3188 selfReference : true,
3189 labelFormat : fundLabelFormat,
3190 searchFormat : fundSearchFormat,
3191 searchFilter : {"active": "t"},
3192 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
3193 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
3194 dijitArgs : { "required": true, "labelType": "html" },
3197 this.batchFundWidget.build();
3200 dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
3201 dojo.connect(batchFundUpdateSubmit, 'onClick',
3204 // TODO: call .dry_run first to test thresholds
3205 fieldmapper.standardRequest(
3206 ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
3209 openils.User.authtoken,
3211 self.batchFundWidget.widget.attr('value')
3213 oncomplete : function(r) {
3214 var resp = openils.Util.readResponse(r);
3216 location.href = location.href;
3225 this._deleteLiList = function(list, idx) {
3226 if(idx == null) idx = 0;
3227 if(idx >= list.length) return;
3232 if (this.isPO && (li.state() == "on-order" || li.state() == "received")) {
3233 /* It makes little sense to delete a lineitem from a PO that has
3234 * already been marked 'on-order'. Especially if EDI is in use,
3235 * such a purchase order will probably have already been shipped
3236 * off to a vendor, and mucking with it at this point could leave
3237 * your data in a bad state that doesn't jive with reality.
3239 * I could see making this restriction even firmer.
3241 * I could also see adjusting the li state comparisons, extending
3242 * the comparison to the PO's state, and/or providing functions
3243 * that house the logic for comparing states in a single location.
3245 * Yes, this will be really annoying if you have selected a lot
3246 * of lineitems to cancel that have been ordered. You'll get a
3247 * confirm dialog for each one.
3250 if (!confirm(localeStrings.DEL_LI_FROM_PO)) {
3251 self._deleteLiList(list, ++idx); /* move on to next in list */
3256 fieldmapper.standardRequest(
3258 this.isPO ? 'open-ils.acq.purchase_order.lineitem.delete' : 'open-ils.acq.picklist.lineitem.delete'],
3260 params: [openils.User.authtoken, liId],
3261 oncomplete: function(r) {
3262 self.removeLineitem(liId);
3263 self._deleteLiList(list, ++idx);
3269 this.editOrderMarc = function(li) {
3271 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
3272 to true in about:config */
3274 if(openils.XUL.isXUL()) {
3275 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul','','chrome');
3277 win = window.open('/xul/server/cat/marcedit.xul','','chrome');
3281 record : {marc : li.marc(), "rtype": "bre"},
3283 label: 'Save Record', // XXX I18N
3284 func: function(xmlString) {
3286 fieldmapper.standardRequest(
3287 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
3289 params: [openils.User.authtoken, li],
3290 oncomplete: function(r) {
3291 openils.Util.readResponse(r);
3293 self.drawInfo(li.id())
3299 'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
3300 'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
3304 this._savePl = function(values) {
3306 (values.which == 'all'),
3307 function(list) { self._savePlFromLineitems(values, list); }
3311 this._savePlFromLineitems = function(values, selected) {
3312 openils.Util.show("acq-lit-generic-progress");
3314 if(values.new_name) {
3315 openils.acq.Picklist.create(
3316 {name: values.new_name},
3322 oilsBasePath + "/acq/picklist/view/" + id;
3327 } else if(values.existing_pl) {
3328 // update lineitems to use an existing picklist
3330 values.existing_pl, selected, 0,
3333 oilsBasePath + "/acq/picklist/view/" +
3340 this._updateLiState = function(values, state) {
3341 progressDialog.show(true);
3343 (values.which == 'all'),
3345 self._updateLiStateFromLineitems(values, state, list);
3350 this._updateLiStateFromLineitems = function(values, state, selected) {
3351 if(!selected.length) return;
3352 dojo.forEach(selected, function(li) {li.state(state);});
3353 self._updateLiList(null, selected, 0,
3354 // TODO consider inline updates for efficiency
3355 function() { location.href = location.href }
3359 this._updateLiList = function(pl, list, idx, oncomplete) {
3360 if(idx >= list.length) return oncomplete();
3362 if(pl != null) li.picklist(pl);
3363 litGenericProgress.update({maximum: list.length, progress: idx});
3364 new openils.acq.Lineitem({lineitem:li}).update(
3366 self._updateLiList(pl, list, ++idx, oncomplete);
3371 this._loadPOSelect = function() {
3372 if (!this.createPoProviderSelector) {
3373 var widget = new openils.widget.AutoFieldWidget({
3374 "fmField": "provider",
3376 "searchFilter": {"active": "t"},
3377 "parentNode": dojo.byId("acq-lit-po-provider"),
3379 "onChange": function() {
3381 self._updateCreatePoPrepayCheckbox(
3382 this.item.prepayment_required()
3388 widget.build(function(w) { self.createPoProviderSelector = w; });
3391 if (!this.createPoAgencySelector) {
3392 var widget = new openils.widget.AutoFieldWidget({
3393 "fmField": "ordering_agency",
3395 "parentNode": dojo.byId("acq-lit-po-agency"),
3396 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3398 widget.build(function(w) { self.createPoAgencySelector = w; });
3402 this.showRealCopyEditUI = function(li) {
3407 this._fetchLineitem(li.id(),
3409 li = self.liCache[li.id()] = fullLi;
3413 id : li.lineitem_details().map(
3414 function(item) { return item.eg_copy_id() }
3418 oncomplete : function(r) {
3420 var r_list = openils.Util.readResponse( r );
3421 for (var i = 0; i < r_list.length; i++) {
3422 var copy = r_list[i];
3423 var volId = copy.call_number();
3424 var volume = self.volCache[volId];
3426 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
3428 copy.call_number(volume);
3429 copyList.push(copy);
3432 xulG.volume_item_creator( { 'existing_copies' : copyList } );
3435 alert('error in oncomplete: ' + E);
3444 this.drawBibFinder = function(li) {
3447 var liWrapper = new openils.acq.Lineitem({lineitem:li});
3450 ['isbn', 'upc', 'issn', 'title', 'author'],
3452 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
3454 if(field == 'title' || field == 'author') {
3455 query += field +':' + val + ' ';
3457 query += 'identifier|' + field + ':' + val + ' ';
3464 oilsBasePath + '/acq/lineitem/findbib?query=' + escape(query),
3465 '', 'resizable,scrollbars=1,chrome');
3467 win.window.recordFound = function(bibId) {
3470 var attrs = li.attributes();
3471 li.attributes(null);
3472 li.eg_bib_id(bibId);
3474 fieldmapper.standardRequest(
3475 ["open-ils.acq", "open-ils.acq.lineitem.update"],
3477 "params": [openils.User.authtoken, li],
3479 "oncomplete": function(r) {
3480 if(openils.Util.readResponse(r)) {
3481 location.href = location.href;