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 if (li.cancel_reason() && typeof li.cancel_reason() == 'object') {
630 dojo.query('[name=cancel_reason]', row)[0].appendChild(
631 document.createTextNode(li.cancel_reason().label()));
634 // so we can scroll to it later
635 dojo.query('[name=bib-info-cell]', row)[0].id = 'li-title-ref-' + li.id();
638 liWrapper.findAttr("isbn", "lineitem_marc_attr_definition") ||
639 liWrapper.findAttr("upc", "lineitem_marc_attr_definition");
641 // XXX media prefix for added content
643 nodeByName("jacket", row).setAttribute(
644 "src", "/opac/extras/ac/jacket/small/" + identifier
648 nodeByName("liid", row).innerHTML += li.id();
651 openils.Util.show(nodeByName('catalog', row), 'inline');
652 nodeByName("catalog_link", row).onclick = this.generateMakeRecTab(li.eg_bib_id());
654 openils.Util.show(nodeByName('link_to_catalog', row), 'inline');
655 nodeByName("link_to_catalog_link", row).onclick = function() { self.drawBibFinder(li) };
658 if (li.queued_record()) {
659 this.pcrud.retrieve('vqbr', li.queued_record(),
661 oncomplete : function(r) {
662 var qrec = openils.Util.readResponse(r);
663 openils.Util.show(nodeByName('queue', row), 'inline');
664 var link = nodeByName("queue_link", row);
665 link.onclick = function() {
666 // open a new tab to the vandelay queue for this record
667 openils.XUL.newTabEasy(
668 oilsBasePath + '/vandelay/vandelay?qtype=bib&qid=' + qrec.queue()
676 nodeByName("worksheet_link", row).href =
677 oilsBasePath + "/acq/lineitem/worksheet/" + li.id() +
678 '?source=' + encodeURIComponent(location.pathname + location.search)
680 nodeByName("show_requests_link", row).href =
681 oilsBasePath + "/acq/picklist/user_request?lineitem=" + li.id() +
682 '?source=' + encodeURIComponent(location.pathname + location.search)
684 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
685 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
686 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
687 dojo.query('[name=expand_inline_copies]', row)[0].onclick =
688 function() {self.drawInlineCopies(li.id())};
690 this.drawOrderIdentSelector(li, row);
692 if (!this.skipInitialEligibilityCheck)
696 function(full) { self.setClaimPolicyControl(full, row) },
700 this.updateLiNotesCount(li, row);
702 // show which PO this lineitem is a member of
703 if(li.purchase_order() && !this.isPO) {
705 this.poCache[li.purchase_order()] =
706 this.poCache[li.purchase_order()] ||
707 fieldmapper.standardRequest(
708 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
710 this.authtoken, li.purchase_order(), {
711 "flesh_price_summary": true,
712 "flesh_provider" : true,
713 "flesh_lineitem_count": true
716 if(po && !this.isMeta) {
717 openils.Util.show(nodeByName('po', row), 'inline');
718 var link = nodeByName('po_link', row);
719 link.setAttribute('href', oilsBasePath +
720 '/acq/po/view/' + li.purchase_order() +
721 '?focus_li=' + li.id() +
722 '&source=' + encodeURIComponent(location.pathname + location.search)
724 link.innerHTML += po.name();
726 openils.Util.show(nodeByName('pro', row), 'inline');
727 link = nodeByName('pro_link', row);
728 link.setAttribute('href', oilsBasePath + '/conify/global/acq/provider/' + po.provider().id())
729 link.innerHTML += po.provider().code();
733 // show which picklist this lineitem is a member of
734 if(li.picklist() && (this.isPO || this.isMeta || this.isUni)) {
736 this.plCache[li.picklist()] =
737 this.plCache[li.picklist()] ||
738 fieldmapper.standardRequest(
739 ['open-ils.acq', 'open-ils.acq.picklist.retrieve.authoritative'],
740 {params: [this.authtoken, li.picklist()]});
742 if (pl.name() == "") {
743 openils.Util.show(nodeByName("bib_origin", row), "inline");
747 openils.Util.show(nodeByName('pl', row), 'inline');
748 var link = nodeByName('pl_link', row);
749 link.setAttribute('href', oilsBasePath +
750 '/acq/picklist/view/' + li.picklist() +
751 '?focus_li=' + li.id() +
752 '&source=' + encodeURIComponent(location.pathname + location.search)
754 link.innerHTML += pl.name();
759 var countNode = nodeByName('count', row);
760 var count = li.item_count() || 0;
761 if (typeof(this._copy_count_cb) == "function") {
762 this._copy_count_cb(li.id(), count);
764 countNode.innerHTML = count;
765 countNode.id = 'acq-lit-copy-count-label-' + li.id();
768 var priceInput = dojo.query('[name=price]', row)[0];
769 priceInput.value = li.estimated_unit_price() || '';
770 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
772 // show either "mark received" or "unreceive" as appropriate
773 this.updateLiState(li, row);
775 if (skip_final_placement) {
779 // the last LI may be rendered after the call to show('list'),
780 // so make sure it's focused if necessary.
781 if (this.focusLineitem == li.id())
785 this._liCountClaims = function(li) {
787 for (var i = 0; i < li.lineitem_details().length; i++)
788 total += li.lineitem_details()[i].claims().length;
792 this._findLiRow = function(li) {
793 return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
796 this.reconsiderClaimControl = function(li, row) {
797 if (!row) row = this._findLiRow(li);
798 var option = nodeByName("action_manage_claims", row);
799 var eligible = this.claimEligibleLidByLi[li.id()].length;
800 var count = this._liCountClaims(li);
802 option.disabled = !(count || eligible);
804 dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
805 option.onclick = function() { self.claimDialog.show(li); };
808 this.clearEligibility = function(li) {
809 this.claimEligibleLidByLi[li.id()] = [];
811 if (li.lineitem_details()) {
812 li.lineitem_details().forEach(
813 function(lid) { delete self.claimEligibleLid[lid.id()]; }
817 if (this.copyCache) {
819 for (var k in this.copyCache) {
820 if (this.copyCache[k].lineitem() == li.id())
824 function(k) { delete self.claimEligibleLid[k]; }
829 this.applyOrderIdentValues = function() {
830 this._identValuesInFlight =
831 openils.Util.objectProperties(this.liCache).length;
832 for (var liId in this.liCache) {
833 this._applyOrderIdentValue(this.liCache[liId]);
837 // returns true if request was sent
838 this._applyOrderIdentValue = function(li, oncomplete) {
841 console.log('applying ident value for lineitem ' + li.id());
844 var row = dojo.query('[li=' + li.id() + ']')[0];
846 // find the selected ident value
847 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
848 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
849 var name = typeSel.options[typeSel.selectedIndex].value;
850 var val = typeSel._cbox.attr('value');
852 console.log("selected ident is " + val);
854 // it differs from the existing ident value, update it
855 var oldIdent = self.getLiOrderIdent(li);
857 oldIdent.attr_name() == name &&
858 oldIdent.attr_value() == val) {
859 console.log('selected ident attr matches existing attr');
860 if (--this._identValuesInFlight == 0) {
861 if (oncomplete) oncomplete(li);
862 else location.href = location.href;
867 // see if the selected ident value is represented
868 // by an existing lineitem attr
871 typeSel._cbox.store.fetch({
872 query : {attr_value : val},
873 onItem : function(item) {
874 console.log('found existing attr for ident value');
875 args.source_attr_id = li.attributes().filter(
876 function(attr) { return attr.id() == item.id[0] }
882 if (!args.source_attr_id) {
883 // user entered new text in the combobox
884 // so we need to create a new attr
885 console.log('creating new ident attr');
886 args.lineitem_id = li.id();
887 args.attr_name = name;
888 args.attr_value = val;
891 fieldmapper.standardRequest(
892 ['open-ils.acq', 'open-ils.acq.lineitem.order_identifier.set'],
894 params : [openils.User.authtoken, args],
895 oncomplete : function() {
896 console.log('order_ident oncomplete');
897 if (--self._identValuesInFlight == 0) {
898 if (oncomplete) oncomplete(li);
899 else location.href = location.href;
901 console.log(self._identValuesInFlight + ' still in flight');
909 this.getLiOrderIdent = function(li) {
910 var attrs = li.attributes();
911 if (!attrs) return null;
915 attr.attr_type() == 'lineitem_local_attr_definition' &&
916 openils.Util.isTrue(attr.order_ident())
922 this.drawOrderIdentSelector = function(li, row) {
924 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
925 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
927 var attrs = li.attributes();
929 // limit to MARC attr defs
930 attrs = attrs.filter(
932 return (attr.attr_type() == 'lineitem_marc_attr_definition');
936 var identAttr = this.getLiOrderIdent(li);
939 // collect the values for each type of identifier
940 // find a reasonable default identifier type to render
944 dojo.forEach(['isbn', 'upc', 'issn'],
947 // collect the values for this attr name
948 values[name] = attrs.filter(
950 return (attr.attr_name() == name)
954 // select a reasonable default name in the type-selector
958 if (identAttr.attr_name() == name)
960 } else if (values[name].length) {
965 dojo.forEach(typeSel.options, function(opt) {
966 if (opt.value == name) {
976 function updateOrderIdent(val) {
977 self._identValuesInFlight = 1;
978 self._applyOrderIdentValue(
981 self.refreshLineitem(li);
986 // replace the ident combobox with a new
987 // one for the selected ident type
988 function changeComboBox(sel) {
989 var name = sel.options[sel.selectedIndex].value;
991 var td = dojo.query('[name=order_ident_value]', row)[0];
992 if (td.childNodes[0])
993 dojo.destroy(td.childNodes[0]);
995 var store = new dojo.data.ItemFileWriteStore({
996 data : acqlia.toStoreData(values[name])
999 var cbox = new dijit.form.ComboBox(
1001 labelAttr : 'attr_value',
1002 searchAttr : 'attr_value'
1004 dojo.create('div', {}, td)
1009 // set the value for the cbox
1010 if (values[name].length) {
1011 var orderIdent = self.getLiOrderIdent(li);
1013 if (orderIdent && orderIdent.attr_name() == name) {
1014 cbox.attr('value', orderIdent.attr_value());
1016 cbox.attr('value', values[name][0].attr_value());
1020 if (!self.orderIdentAllowed)
1021 cbox.attr('disabled', true);
1024 cbox._lineitem = li;
1025 dojo.connect(cbox, 'onChange', updateOrderIdent);
1028 changeComboBox(typeSel); // force the initial draw
1029 typeSel.onchange = function() {changeComboBox(typeSel)};
1032 this.testOrderIdentPerms = function(org, callback) {
1034 new openils.User().getPermOrgList(
1035 'ACQ_SET_LINEITEM_IDENTIFIER',
1037 console.log('found orgs = ' + orgs);
1038 for (var i = 0; i < orgs.length; i++) {
1039 if (Number(orgs[i]) == Number(org)) {
1040 self.orderIdentAllowed = true;
1041 if (callback) callback();
1045 if (callback) callback();
1051 this.checkClaimEligibility = function(li, callback, row) {
1052 /* Assume always eligible, i.e. from this interface we don't care about
1053 * claim eligibility any more. this is where the user would force a
1055 this.clearEligibility(li);
1056 this.claimEligibleLidByLi[li.id()] = li.lineitem_details().map(
1057 function(lid) { return lid.id(); }
1059 li.lineitem_details().forEach(
1060 function(lid) { self.claimEligibleLid[lid.id()] = true; }
1062 this.reconsiderClaimControl(li, row);
1063 if (callback) callback(li);
1065 this.clearEligibility(li);
1066 fieldmapper.standardRequest(
1067 ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
1068 "params": [openils.User.authtoken, {"lineitem": li.id()}],
1070 "onresponse": function(r) {
1071 if (r = openils.Util.readResponse(r)) {
1072 self.claimEligibleLidByLi[li.id()].push(
1075 self.claimEligibleLid[r.lineitem_detail()] = true;
1078 "oncomplete": function() {
1079 self.reconsiderClaimControl(li, row);
1080 if (typeof(callback) == "function")
1088 this.updateLiNotesCount = function(li, row) {
1089 if (!row) row = this._findLiRow(li);
1091 var has_notes = (li.lineitem_notes().filter(
1092 function(o) { return Boolean (o.alert_text()); }
1095 /* U+2691 is the code point for a filled-in flag character */
1096 nodeByName("notes_alert_flag", row).innerHTML =
1097 has_notes ? "⚑" : "";
1098 nodeByName("noteslink", row).style.fontStyle =
1099 has_notes ? "italic" : "normal";
1100 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
1103 /* XXX NOT related to _updateLiState(). rethink */
1104 this.updateLiState = function(li, row) {
1105 if (!row) row = this._findLiRow(li);
1107 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
1108 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
1110 // always allow access to LI history
1111 nodeByName('action_view_history', row).onclick =
1112 function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
1114 /* handle row coloring for based on LI state */
1115 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1116 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
1118 // Expose invoice actions for any lineitem that is linked to a PO
1119 if (li.purchase_order()) {
1120 openils.Util.show(nodeByName("invoices_span", row), "inline");
1121 var link = nodeByName("invoices_link", row);
1122 link.onclick = function() {
1123 openils.XUL.newTabEasy(
1124 oilsBasePath + "/acq/search/unified?so=" +
1125 base64Encode({"jub":[{"id": li.id()}]}) + "&rt=invoice"
1133 * If we haven't fleshed the lineitem_details, default to allowing access to the
1134 * holdings maintenence actions. The alternative is to flesh LIDs on every lineitem,
1135 * but that will add to page render time. Let's see if this will suffice...
1137 var lids = li.lineitem_details();
1139 (lids && !lids.filter(function(lid) { return lid.eg_copy_id() })[0] )) {
1141 actUpdateBarcodes.disabled = false;
1142 actUpdateBarcodes.onclick = function() {
1143 self.showRealCopyEditUI(li);
1144 nodeByName("action_none", row).selected = true;
1146 actHoldingsMaint.disabled = false;
1147 actHoldingsMaint.onclick =
1148 self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
1151 var state_cell = nodeByName("li_state", row);
1153 switch(li.state()) {
1156 if(typeof li.cancel_reason() == "object") {
1157 var holds_state = dojo.create(
1159 "style": "border-bottom: 1px dashed #000;",
1160 "innerHTML": li.state()
1161 }, state_cell, "only"
1165 "label": "<em>" + li.cancel_reason().label() +
1166 "</em><br />" + li.cancel_reason().description(),
1167 "connectId": [holds_state]
1168 }, dojo.create("span", null, state_cell, "last")
1171 if (li.cancel_reason().keep_debits() == 't') {
1172 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1173 openils.Util.addCSSClass(row, "oils-acq-li-state-delayed");
1185 state_cell.innerHTML = li.state(); // TODO i18n state labels
1189 this._setAlertStore = function() {
1190 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
1192 "data": acqliat.toStoreData(
1195 "owning_lib": aou.orgNodeTrail(
1196 aou.findOrgUnit(openils.User.user.ws_ou())
1197 ).map(function(o) { return o.id(); })
1203 acqLitAlertAlertText.setValue(); /* make the store "live" */
1204 acqLitAlertAlertText._store_ready = true;
1208 * Draws and shows the lineitem notes pane
1210 this.drawLiNotes = function(li) {
1212 this.focusLineitem = li.id();
1214 if (!acqLitAlertAlertText._store_ready)
1215 this._setAlertStore();
1218 li.lineitem_notes().sort(
1220 if(a.edit_time() < b.edit_time()) return 1;
1226 while(this.liNotesTbody.childNodes[0])
1227 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
1230 acqLitCreateNoteSubmit.onClick = function() {
1231 var value = acqLitCreateNoteText.attr('value');
1233 var note = new fieldmapper.acqlin();
1236 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
1239 note.lineitem(li.id());
1241 self.updateLiNotes(li, note);
1242 acqLitCreateNoteVendorPublic.attr("checked", false);
1243 acqLitCreateNoteText.attr("value", "");
1246 acqLitCreateAlertSubmit.onClick = function() {
1247 if (!acqLitAlertAlertText.item) {
1248 alert(localeStrings.ALERT_UNSELECTED);
1252 var alert_text = new fieldmapper.acqliat().fromStoreItem(
1253 acqLitAlertAlertText.item
1255 var value = acqLitAlertNoteValue.attr("value") || "";
1257 var note = new fieldmapper.acqlin();
1259 note.lineitem(li.id());
1261 note.alert_text(alert_text);
1263 self.updateLiNotes(li, note);
1266 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
1270 * Draws a single lineitem note in the notes pane
1272 this.addLiNote = function(li, note) {
1273 if(note.isdeleted()) return;
1275 var row = self.liNotesRow.cloneNode(true);
1276 nodeByName("value", row).innerHTML = note.value();
1277 var alert_node = nodeByName("alert_code", row);
1278 if (note.alert_text()) {
1279 alert_node.innerHTML = dojo.string.substitute(
1281 aou.findOrgUnit(note.alert_text().owning_lib()).shortname(),
1282 note.alert_text().code()
1285 if (note.alert_text().description()) {
1288 "connectId": [alert_node],
1289 "label": note.alert_text().description()
1290 }, dojo.create("span", null, alert_node, "after")
1295 if (openils.Util.isTrue(note.vendor_public()))
1296 nodeByName("vendor_public", row).innerHTML =
1297 localeStrings.VENDOR_PUBLIC;
1299 nodeByName("delete", row).onclick = function() {
1300 note.isdeleted(true);
1301 self.liNotesTbody.removeChild(row);
1302 self.updateLiNotes(li);
1305 if(note.edit_time()) {
1306 nodeByName("edit_time", row).innerHTML =
1307 dojo.date.locale.format(
1308 dojo.date.stamp.fromISOString(note.edit_time()),
1309 {formatLength:'short'});
1312 self.liNotesTbody.appendChild(row);
1316 * Updates any new/changed/deleted notes on the server
1318 this.updateLiNotes = function(li, newNote) {
1324 notes = li.lineitem_notes().filter(
1326 if(note.ischanged() || note.isnew() || note.isdeleted())
1332 if(notes.length == 0) return;
1333 progressDialog.show();
1335 fieldmapper.standardRequest(
1336 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
1338 params : [this.authtoken, notes],
1339 onresponse : function(r) {
1340 var resp = openils.Util.readResponse(r);
1345 // remove the old changed notes
1347 dojo.forEach(li.lineitem_notes(),
1349 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
1353 li.lineitem_notes(list);
1356 progressDialog.hide();
1357 self.updateLiNotesCount(li);
1358 self.drawLiNotes(li);
1362 progressDialog.update(resp);
1363 var newnote = resp.note;
1365 if(!newnote.isdeleted()) {
1366 newnote.isnew(false);
1367 newnote.ischanged(false);
1368 li.lineitem_notes().push(newnote);
1375 this.updateLiPrice = function(input, li) {
1377 var price = input.value;
1378 if(Number(price) == Number(li.estimated_unit_price())) return;
1380 fieldmapper.standardRequest(
1381 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
1382 { async : false, // redundant w/ timeout
1384 params : [this.authtoken, li.id(), price],
1385 oncomplete : function(r) {
1386 openils.Util.readResponse(r);
1387 li.estimated_unit_price(price); // update local copy
1390 * If this is a PO and every visible lineitem has a price,
1391 * check again to see if this PO can be activated. Note that
1392 * every visible lineitem having a price does not guarantee it can
1393 * be activated, which is why we still make the call. Having a price
1394 * set for every visiable lineitem is just the lowest barrier to entry.
1397 var priceNodes = dojo.query('[name=price]', dojo.byId('acq-lit-tbody'));
1399 dojo.forEach(priceNodes, function(node) { if (node.value == '') allSet = false});
1400 if (allSet) checkCouldActivatePo();
1407 this.removeLineitem = function(liId) {
1408 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
1409 delete this.liCache[liId];
1410 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
1413 this.drawInfo = function(liId) {
1414 this.focusLineitem = liId;
1415 if (!this._isRelatedViewer) {
1416 var d = dojo.byId("acq-lit-info-related");
1417 if (!this.relCache[liId]) {
1418 fieldmapper.standardRequest(
1421 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
1424 "params": [openils.User.authtoken, liId],
1425 "onresponse": function(r) {
1426 self.relCache[liId] = openils.Util.readResponse(r);
1427 nodeByName("related_number", d).innerHTML =
1428 self.relCache[liId];
1430 self.relCache[liId] >1 ? "show" : "hide"
1436 nodeByName("related_number", d).innerHTML = this.relCache[liId];
1437 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
1442 openils.acq.Lineitem.fetchAttrDefs(
1444 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
1449 this.toggleInlineCopies = function() {
1450 // if any inline copies are not displayed,
1451 // display them all otherwise, hide them all.
1453 var displayAll = false;
1455 for (var liId in this.liCache) {
1456 if (!this.inlineCopiesVisible(liId)) {
1462 for (var liId in this.liCache) {
1463 var row = dojo.byId('acq-inline-copies-row-' + liId);
1465 if (!row || row._hidden) {
1466 this.drawInlineCopies(liId);
1468 } else { // hide all
1470 // drawInlineCopies() on a visible row will hide it.
1471 this.drawInlineCopies(liId);
1478 this.inlineCopiesVisible = function(liId) {
1479 var row = dojo.byId('acq-inline-copies-row-' + liId);
1480 return (row && !row._hidden);
1483 this.refreshInlineCopies = function(all, reFetch) {
1485 var liIds = this.inlineCopiesNeedingRefresh;
1486 if (all) liIds = openils.Util.objectProperties(liCache);
1487 liIds.forEach(function(liId) {
1488 if (self.inlineCopiesVisible(liId)) {
1489 self.drawInlineCopies(liId, reFetch); // hide
1490 self.drawInlineCopies(liId, reFetch); // re-draw
1495 // draw inline copy table. if the table is
1496 // already visible, hide the table as-is
1497 // reFetch forces a retrieval of the lineitem and
1498 // copies from the server. otherwise the locally
1499 // cached version of each is used.
1500 this.drawInlineCopies = function(liId, reFetch) {
1503 // find or create the row where the inline copies table will live
1504 var containerRow = dojo.byId('acq-inline-copies-row-' + liId);
1505 var liRow = dojo.query('[li=' + liId + ']')[0];
1507 if (!containerRow) {
1509 // build the inline copies container row and add it to
1510 // the DOM directly after the primary lineitem row
1512 containerRow = self.inlineCopyContainer.cloneNode(true);
1513 containerRow.id = 'acq-inline-copies-row-' + liId;
1515 if (liRow.nextSibling) {
1516 self.tbody.insertBefore(containerRow, liRow.nextSibling);
1518 self.tbody.appendChild(containerRow);
1523 // toggle the visible state
1524 containerRow._hidden = !containerRow._hidden;
1525 openils.Util.toggle(containerRow, 'table-row');
1527 if (containerRow._hidden) return; // hide only
1530 var handler = function(li) {
1532 var tbody = dojo.query(
1533 '[name=acq-li-inline-copies-tbody]',
1536 // reset the table before adding copy rows
1537 while (tbody.childNodes[0])
1538 tbody.removeChild(tbody.childNodes[0]);
1540 if(li.lineitem_details().length == 0) {
1542 self.inlineNoCopies.cloneNode(true));
1543 return; // no copies to show
1546 // add a row to the inline copy table for each copy
1547 dojo.forEach(li.lineitem_details(),
1549 var row = self.inlineCopyTemplate.cloneNode(true);
1550 tbody.appendChild(row);
1551 self.addInlineCopy(li, copy, row);
1556 this._fetchLineitem(liId, handler, reFetch);
1559 /** Draw read-only copy widgets for inline copies */
1560 this.addInlineCopy = function(li, copy, row) {
1563 dojo.forEach(liDetailFields,
1566 var widget = new openils.widget.AutoFieldWidget({
1569 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1570 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1571 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1573 parentNode : dojo.query('[name=' + field + ']', row)[0],
1582 /* For a given list of lineitem ids, build a list of full lineitems
1583 * re-using the fetching logic that is otherwise typical to use in this
1586 * If we've already got a lineitem in the cache, just use that.
1588 * Once we've built a list of lineitems, call callback(thatlist).
1590 this.fetchLineitemsById = function(id_list, callback) {
1591 var total = id_list.length;
1592 var result_list = [];
1594 var inner = function(li) {
1595 result_list.push(li)
1597 callback(result_list);
1600 id_list.forEach(function(id) { self._fetchLineitem(id, inner); });
1603 this._fetchLineitem = function(liId, handler, force) {
1605 var li = this.liCache[liId];
1606 if(li && li.marc() && li.lineitem_details() && !force)
1609 fieldmapper.standardRequest(
1610 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
1613 params: [self.authtoken, liId, {
1615 flesh_cancel_reason: true,
1616 flesh_li_details: true,
1618 flesh_fund_debit: true }],
1620 oncomplete: function(r) {
1621 var li = openils.Util.readResponse(r);
1622 self.liCache[liId] = li;
1629 this._drawInfo = function(li) {
1631 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
1633 if(li.eg_bib_id()) {
1634 openils.Util.hide('acq-lit-marc-order-record-label');
1635 openils.Util.hide(acqLitEditOrderMarc.domNode);
1636 openils.Util.show('acq-lit-marc-real-record-label');
1638 openils.Util.show('acq-lit-marc-order-record-label');
1639 openils.Util.show(acqLitEditOrderMarc.domNode);
1640 openils.Util.hide('acq-lit-marc-real-record-label');
1643 this.drawMarcHTML(li);
1644 this.infoTbody = dojo.byId('acq-lit-info-tbody');
1647 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
1648 while(this.infoTbody.childNodes[0])
1649 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
1651 for(var i = 0; i < li.attributes().length; i++) {
1652 var attr = li.attributes()[i];
1653 var row = this.infoRow.cloneNode(true);
1655 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
1656 var name = openils.acq.Lineitem.attrDefs[type].filter(
1658 return (a.code() == attr.attr_name());
1660 ).pop().description();
1662 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
1663 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
1664 this.infoTbody.appendChild(row);
1667 if (!this._isRelatedViewer) {
1668 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
1669 oilsBasePath + "/acq/lineitem/related/" + li.id();
1672 // if a top scroll point is defined, jump up to it here
1673 var node = dojo.byId('oils-scroll-to-top');
1674 if (node) dijit.scrollIntoView(node);
1677 this.generateMakeRecTab = function(bib_id,default_view, row) {
1681 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
1684 show_nav_buttons : true,
1685 show_print_button : true,
1686 opac_url : xulG.url_prefix('opac_rdetail|' + bib_id),
1687 default_view : default_view
1691 if(row) nodeByName("action_none", row).selected = true;
1695 this.drawMarcHTML = function(li) {
1696 var params = [null, true, li.marc()];
1698 params = [li.eg_bib_id(), true];
1700 fieldmapper.standardRequest(
1701 ['open-ils.search', 'open-ils.search.biblio.record.html'],
1704 oncomplete: function(r) {
1705 dojo.byId('acq-lit-marc-div').innerHTML =
1706 openils.Util.readResponse(r);
1712 this.drawCopies = function(liId, force_fetch) {
1713 this.focusLineitem = liId;
1714 if (typeof force_fetch == "undefined")
1715 force_fetch = false;
1717 var cgi = new openils.CGI();
1718 var source = cgi.param('source');
1719 if (source && source.match(/invoice/)) {
1720 // got here from the invoice page, show the 'return-to-invoice' button
1721 var cgi = new openils.CGI({url : source});
1722 cgi.param('focus_li', liId);
1723 openils.Util.show(dojo.byId('acq-lit-copies-back-to-invoice-button-wrapper'), 'inline');
1724 var button = dojo.byId('acq-lit-copies-back-to-invoice-button');
1725 button.onclick = function() { location.href = cgi.url() };
1728 openils.acq.Lineitem.fetchAndRender(liId, {},
1729 function(li, html) {
1730 dojo.byId('acq-lit-copies-li-summary').innerHTML = html;
1734 this.show('copies');
1736 this.copyCache = {};
1737 this.copyWidgetCache = {};
1738 this.oldCopyWidgetCache = {};
1739 this.virtDfaCounts = {};
1740 this.realDfaCache = {};
1743 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
1744 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
1745 acqLitCopyCountInput.attr('value', '0');
1747 if (this.isPO && PO && PO.order_date()) {
1748 // prevent adding copies to activated POs
1749 acqLitCopyCountInput.attr('disabled', true);
1750 acqLitAddCopyCount.attr('disabled', true);
1753 while(this.copyTbody.childNodes[0])
1754 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
1756 this._drawBatchCopyWidgets();
1758 this._drawDistribApplied(liId);
1760 this._fetchDistribFormulas(
1762 openils.acq.Lineitem.fetchAttrDefs(
1764 self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch);
1771 this._saveDistribAppliedTemplates = function() {
1772 if (!this._appliedDistribTemplate) {
1773 this._appliedDistribTemplate =
1774 dojo.byId("acq-lit-distrib-applied-tbody").
1775 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
1776 dojo.attr(this._appliedDistribTemplate, "id");
1780 this._drawDistribApplied = function(liId) {
1781 /* Build this table while hidden to prevent rendering artifacts */
1782 openils.Util.hide("acq-lit-distrib-applied-tbody");
1784 this._saveDistribAppliedTemplates();
1786 /* Remove any rows in the table from previous populations */
1787 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
1788 forEach(dojo.destroy);
1790 /* Unregister all dijits previously created (for some reason this isn't
1791 * covered by the above destroy calls). */
1792 dijit.registry.forEach(
1793 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
1796 /* Populate the table with our liId */
1798 fieldmapper.standardRequest(
1800 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
1803 "params": [self.authtoken, liId],
1804 "onresponse": function(r) {
1805 var dfa = openils.Util.readResponse(r);
1808 self.realDfaCache[dfa.id()] = dfa;
1809 self._drawDistribAppliedUnit(dfa);
1812 "oncomplete": function() {
1813 /* Reveal built table */
1816 "acq-lit-distrib-applied-tbody", "table-row-group"
1824 this._drawDistribAppliedUnit = function(dfa) {
1825 var new_row = false;
1826 var row = dojo.query(
1827 'tr[formula="' + dfa.formula().id() + '"]',
1828 "acq-lit-distrib-applied-tbody"
1833 row = dojo.clone(this._appliedDistribTemplate);
1834 dojo.attr(row, "formula", dfa.formula().id());
1835 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
1838 var td = dojo.query("td", row)[0];
1840 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1841 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1844 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1846 new dijit.form.Button(
1848 "onClick": function() {
1849 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1850 self.deleteDfa(dfa);
1853 /* XXX I /cannot/ make the following work in as a CSS class
1854 * for some reason. So frustrating... */
1855 "style": function(id) {
1857 "font-weight: bold; color: #c00;" :
1859 }(dfa.id()) + "margin: 0 6px;display: inline;"
1860 }, "dfa-button-" + dfa.id()
1864 "connectId": ["dfa-button-" + dfa.id()],
1865 "label": dojo.string.substitute(
1866 localeStrings.DFA_TIP, dfa.id() > 0 ? [
1867 openils.User.formalName(dfa.creator()),
1868 dojo.date.locale.format(
1869 dojo.date.stamp.fromISOString(dfa.create_time()),
1870 {"formatLength":"short"}
1872 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
1874 }, "dfa-tip-" + dfa.id()
1878 this.deleteDfa = function(dfa) {
1879 if (dfa.id() > 0) { /* real */
1880 this.pcrud.eliminate(
1883 "oncomplete": function() {
1884 self._removeDistribApplied(dfa.id());
1885 delete self.realDfaCache[dfa.id()];
1889 } else { /* virtual */
1890 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
1891 this.virtDfaCounts[dfa.formula().id()] = 0;
1892 /* hasn't been saved yet, so no need to do anything server side */
1893 this._removeDistribApplied(dfa.id());
1898 this._removeDistribApplied = function(dfaId) {
1899 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
1900 dijit.registry.forEach(
1901 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
1903 this._removeDistribAppliedEmptyRows();
1906 this._removeAllDistribAppliedVirtual = function() {
1907 /* Unregister dijits */
1908 dijit.registry.forEach(
1909 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
1911 this._removeDistribAppliedEmptyRows();
1914 this._removeDistribAppliedEmptyRows = function() {
1915 /* Remove any rows with no DFA at all */
1916 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
1918 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
1924 * Insert a new row into the distribution formula selection form
1926 this._addDistribFormulaRow = function() {
1929 if (!self.distribForms) {
1930 // no formulas, hide the form
1931 openils.Util.hide('acq-lit-distrib-formula-table');
1935 if(!this.distribFormulaTemplate)
1936 this.distribFormulaTemplate =
1937 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
1939 var row = this.distribFormulaTemplate.cloneNode(true);
1940 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
1942 this.dfSelector = new dijit.form.FilteringSelect(
1943 {"labelAttr": "dynLabel", "labelType": "html"},
1944 nodeByName("selector", row)
1946 this._updateFormulaStore();
1947 this.dfSelector.fetchProperties =
1948 {"sort": [{"attribute": "use_count", "descending": true}]};
1950 var apply = new dijit.form.Button(
1951 {"label": localeStrings.APPLY},
1952 nodeByName('set_button', row)
1955 var reset = new dijit.form.Button(
1956 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
1957 nodeByName("reset_button", row)
1960 dojo.connect(apply, 'onClick',
1962 var form_id = self.dfSelector.attr("value");
1963 if(!form_id) return;
1964 self._applyDistribFormula(form_id);
1965 reset.attr("disabled", false);
1969 dojo.connect(reset, 'onClick',
1971 self.restoreCopyFieldsBeforeDF();
1972 self.virtDfaCounts = {};
1973 self.virtDfaId = -1;
1975 self._updateFormulaStore();
1976 self._removeAllDistribAppliedVirtual();
1977 reset.attr("disabled", "true");
1984 * Applies a distrib formula to the current set of copies
1986 this._applyDistribFormula = function(formula) {
1987 if(!formula) return;
1989 formula = this.distribForms.filter(
1990 function(form) { return form.id() == formula; }
1993 var copyRows = dojo.query('tr', self.copyTbody);
1995 if (this.dfeOffset >= copyRows.length) {
1996 alert(localeStrings.OUT_OF_COPIES);
2000 var entries_applied = 0;
2002 var rowIndex = this.dfeOffset;
2003 rowIndex < copyRows.length;
2007 var row = copyRows[rowIndex];
2008 var copy_id = row.getAttribute('copy_id');
2009 var copyWidgets = this.copyWidgetCache[copy_id];
2010 var entryIndex = this.dfeOffset;
2013 // find the correct entry for the current row
2014 dojo.forEach(formula.entries(),
2017 entryIndex += e.item_count();
2018 if(entryIndex > rowIndex)
2026 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
2027 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
2030 this.saveCopyFieldsBeforeDF(copy_id);
2031 this._copy_fields_for_acqdf.forEach(
2033 if(entry[field]()) {
2034 copyWidgets[field].attr('value', (entry[field]()));
2041 if (entries_applied) {
2042 this.virtDfaCounts[formula.id()] =
2043 ++(this.virtDfaCounts[formula.id()]) || 1;
2044 this._updateFormulaStore();
2045 this._drawDistribAppliedUnit(
2047 var dfa = new acqdfa();
2048 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
2051 this.dfeOffset += entries_applied;
2056 * This function updates the DF store for the dropdown so that use_counts
2057 * can reflect DF applications from this session before they're saved
2060 this._updateFormulaStore = function() {
2061 this.dfSelector.store = new dojo.data.ItemFileReadStore(
2063 "data": self._labelFormulasWithCounts(
2064 acqdf.toStoreData(self.distribForms)
2070 this.saveCopyFieldsBeforeDF = function(copy_id) {
2072 if (!this.oldCopyWidgetCache[copy_id]) {
2073 var copyWidgets = this.copyWidgetCache[copy_id];
2075 this.oldCopyWidgetCache[copy_id] = {};
2076 this._copy_fields_for_acqdf.forEach(
2078 self.oldCopyWidgetCache[copy_id][f] =
2079 copyWidgets[f].attr("value");
2085 this.restoreCopyFieldsBeforeDF = function() {
2087 for (var copy_id in this.oldCopyWidgetCache) {
2088 this._copy_fields_for_acqdf.forEach(
2090 self.copyWidgetCache[copy_id][f].attr(
2091 "value", self.oldCopyWidgetCache[copy_id][f]
2098 this._labelFormulasWithCounts = function(store_data) {
2099 for (var key in store_data.items) {
2100 var obj = store_data.items[key];
2101 obj.use_count = Number(obj.use_count); /* needed for sorting */
2103 if (this.virtDfaCounts[obj.id])
2104 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
2106 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
2107 obj.use_count + "]</span> " + obj.name;
2113 * This method formerly would not refetch the DF formulas if they'd been
2114 * loaded already, but now it always re-fetches, since use_count changes.
2116 /** TODO: port distrib-formula selector to autofieldwidget+pcrud/dojo store */
2117 this._fetchDistribFormulas = function(onload) {
2118 fieldmapper.standardRequest(
2120 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
2123 "params": [openils.User.authtoken, 0, 500],
2124 "oncomplete": function(r) {
2125 self.distribForms = openils.Util.readResponse(r);
2126 if(!self.distribForms || self.distribForms.length == 0) {
2127 self.distribForms = [];
2129 self._addDistribFormulaRow();
2136 this._drawBatchCopyWidgets = function() {
2137 var row = this.copyBatchRow;
2138 dojo.forEach(liDetailBatchFields,
2140 if(self.copyBatchRowDrawn) {
2141 self.copyBatchWidgets[field].attr('value', null);
2143 var args = self.afwCopyFieldArgs(field, "CREATE_PICKLIST");
2144 args.parentNode = dojo.query('[name='+field+']', row)[0];
2146 var widget = new openils.widget.AutoFieldWidget(args);
2149 if (field == "fund" && w.store)
2150 self._ensureCSSFundClasses(w.store);
2151 self.copyBatchWidgets[field] = w;
2154 if (field == "fund") {
2156 widget.widget, "onChange", function(val) {
2157 self._updateFundSelectorStyle(widget, val);
2164 this.copyBatchRowDrawn = true;
2167 this.batchCopyUpdate = function() {
2169 for(var k in this.copyWidgetCache) {
2170 var cache = this.copyWidgetCache[k];
2171 dojo.forEach(liDetailBatchFields, function(f) {
2172 var newval = self.copyBatchWidgets[f].attr('value');
2173 if(newval) cache[f].attr('value', newval);
2178 this._drawCopies = function(li) {
2181 // this button sets the total number of copies for a given lineitem
2182 acqLitAddCopyCount.onClick = function() {
2183 var count = acqLitCopyCountInput.attr('value');
2186 while(self.copyCount() < count)
2189 // delete rows if necessary
2190 var diff = self.copyCount() - count;
2192 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
2193 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
2194 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
2196 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2202 if(li.lineitem_details().length > 0) {
2203 dojo.forEach(li.lineitem_details(),
2205 self.addCopy(li, copy);
2213 this.copyCount = function() {
2215 for(var id in this.copyCache) {
2216 if(!this.copyCache[id].isdeleted())
2222 this.virtCopyId = -1;
2223 this.addCopy = function(li, copy) {
2224 var row = this.copyRow.cloneNode(true);
2225 this.copyTbody.appendChild(row);
2229 copy = new fieldmapper.acqlid();
2231 copy.id(this.virtCopyId--);
2232 copy.lineitem(li.id());
2235 this.copyCache[copy.id()] = copy;
2236 row.setAttribute('copy_id', copy.id());
2237 self.copyWidgetCache[copy.id()] = {};
2239 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2241 var rcvr = copy.receiver();
2243 if (!userCache[rcvr]) {
2244 if(rcvr == openils.User.user.id()) {
2245 userCache[rcvr] = openils.User.user;
2247 userCache[rcvr] = fieldmapper.standardRequest(
2248 ['open-ils.actor', 'open-ils.actor.user.retrieve'],
2249 {params: [openils.User.authtoken, rcvr]}
2253 dojo.query('[name=receiver]', row)[0].innerHTML = userCache[rcvr].usrname();
2256 dojo.forEach(liDetailFields,
2259 if (field == "fund") {
2260 searchFilter = (copy.fund() ?
2261 {"-or": {"active": "t", "id": copy.fund()}} :
2264 searchFilter = null;
2267 var readOnly = false;
2269 // TODO: Add support for changing the owning_lib after real copies have been made.
2270 // owning_lib is order data as much as its item data
2271 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
2275 // TODO: add support for changing the fund after debits have been created
2276 // Note: invoicing allows the change
2277 if(copy.fund_debit() && field == 'fund') {
2282 var widget = new openils.widget.AutoFieldWidget({
2285 labelFormat : (field == 'fund') ? fundLabelFormat : null,
2286 searchFormat : (field == 'fund') ? fundSearchFormat : null,
2287 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
2288 searchFilter : searchFilter,
2289 noCache: (field == "fund"),
2291 parentNode : dojo.query('[name='+field+']', row)[0],
2292 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2293 readOnly : readOnly,
2294 orgDefaultsToWs : true
2298 // make sure we capture the value from any async widgets
2301 if (field == "fund" && w.store)
2302 self._ensureCSSFundClasses(w.store);
2305 copy[field](ww.getFormattedValue())
2307 self.copyWidgetCache[copy.id()][field] = w;
2309 dojo.connect(w, 'onChange',
2311 if (field == "fund")
2312 self._updateFundSelectorStyle(widget, val);
2314 if (!readOnly && (copy.isnew() || val != copy[field]())) {
2315 // prevent setting ischanged() automatically on widget load for existing copies
2316 copy[field](widget.getFormattedValue())
2317 copy.ischanged(true);
2326 this.updateLidState(copy, row);
2329 this._ensureCSSFundClass = function(id) {
2330 if (!this.fundStyleSheet) {
2332 "style", {"type": "text/css"},
2333 document.getElementsByTagName("head")[0], "last"
2335 this.fundStyleSheet = document.styleSheets[
2336 document.styleSheets.length - 1
2340 var cn = "fund_" + id;
2341 if (!this.haveFundClass[cn]) {
2342 fieldmapper.standardRequest(
2343 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
2345 "params": [openils.User.authtoken, id],
2347 "oncomplete": function(r) {
2348 r = openils.Util.readResponse(r);
2349 self.fundBalanceState[id] = r;
2351 if (r[0] /* stop */)
2352 style = fundStyles.stop;
2353 else if (r[1] /* warning */)
2354 style = fundStyles.warning;
2355 self.fundStyleSheet.insertRule(
2356 "." + cn + " { " + style + " }",
2357 self.fundStyleSheet.cssRules.length
2359 self.haveFundClass[cn] = true;
2366 this._ensureCSSFundClasses = function(store) {
2368 "query": {"id": "*"},
2369 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
2373 this._updateFundSelectorStyle = function(widget, fund_id) {
2374 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
2375 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
2378 this.updateLidState = function(copy, row) {
2381 if (typeof(row) == "undefined") {
2382 row = dojo.query('tr[copy_id="' + copy.id() + '"]', this.copyTbody)[0];
2386 var recv_link = nodeByName("receive", row);
2387 var unrecv_link = nodeByName("unreceive", row);
2388 var del_link = nodeByName("delete", row);
2389 var cxl_link = nodeByName("cancel", row);
2390 var claim_link = nodeByName("claim", row);
2391 var cxl_reason_link = nodeByName("cancel_reason", row);
2393 // by default, hide all the actions
2394 openils.Util.hide(del_link.parentNode);
2395 openils.Util.hide(recv_link);
2396 openils.Util.hide(unrecv_link);
2397 openils.Util.hide(cxl_link);
2398 openils.Util.hide(claim_link);
2399 openils.Util.hide(cxl_reason_link);
2401 if (copy.id() > 0) { // real copies (LIDs)
2403 if (copy.cancel_reason()) {
2405 /* --------- cancelled -------------------------- */
2407 /* XXX the following may leak memory in a long lived table:
2408 * dijits may not get destroyed... not positive. revisit. */
2409 var holds_reason = dojo.create(
2411 "style": "border-bottom: 1px dashed #000;",
2412 "innerHTML": "Cancelled" /* XXX [sic] and i18n */
2413 }, cxl_reason_link, "only"
2417 "label": "<em>" + copy.cancel_reason().label() +
2418 "</em><br />" + copy.cancel_reason().description(),
2419 "connectId": [holds_reason]
2420 }, dojo.create("span", null, cxl_reason_link, "last")
2422 openils.Util.show(cxl_reason_link, "inline");
2424 } else if (copy.recv_time()) {
2426 /* --------- received -------------------------- */
2428 openils.Util.show(unrecv_link, "inline");
2429 unrecv_link.onclick = function() {
2430 if (confirm(localeStrings.UNRECEIVE_LID))
2431 self.issueReceive(copy, /* rollback */ true);
2434 } else if (this.liCache[copy.lineitem()].state() == 'on-order') {
2436 /* --------- on order -------------------------- */
2438 openils.Util.show(recv_link, 'inline');
2439 openils.Util.show(cxl_link, "inline");
2441 recv_link.onclick = function() {
2442 if (self.checkLiAlerts(copy.lineitem()))
2443 self.issueReceive(copy);
2446 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2450 /* --------- pre-order copies -------------------------- */
2452 del_link.onclick = function() { self.deleteCopy(row) };
2453 openils.Util.show(del_link.parentNode);
2459 /* --------- virtual copies -------------------------- */
2461 del_link.onclick = function() { self.deleteCopy(row) };
2462 openils.Util.show(del_link.parentNode);
2466 this.cancelLid = function(lid_id) {
2467 lidCancelDialog._lid_id = lid_id;
2468 openils.Util.show(lidCancelDialog.domNode.parentNode);
2469 lidCancelDialog.show();
2470 if (!lidCancelDialog._prepared) {
2471 var widget = new openils.widget.AutoFieldWidget({
2472 "fmField": "cancel_reason",
2473 "fmClass": "acqlid",
2474 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
2475 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2480 acqLidCancelButton.onClick = function() {
2481 if (w.attr("value")) {
2482 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
2484 lidCancelDialog._lid_id,
2488 lidCancelDialog.hide();
2491 lidCancelDialog._prepared = true;
2497 this._cancelLid = function(lid_id, reason) {
2498 fieldmapper.standardRequest(
2499 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
2500 "params": [openils.User.authtoken, lid_id, reason],
2502 "onresponse": function(r) {
2503 if (r = openils.Util.readResponse(r)) {
2505 for (var id in r.lid) {
2506 /* actually this should only iterate once */
2507 self.copyCache[id].cancel_reason(
2508 r.lid[id].cancel_reason
2510 self.updateLidState(self.copyCache[id]);
2519 this._confirmAlert = function(li, lin) {
2521 dojo.string.substitute(
2522 localeStrings.CONFIRM_LI_ALERT, [
2523 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2524 "title", "lineitem_marc_attr_definition"
2526 /* XXX it's really better add a parameter and to adjust
2527 * the format string rather than do this concatenation
2528 * here, but if someone wants this for 2.2 in a hurry,
2529 * we can sidestep the problem of updating the strings
2530 * while the translators are working. */
2532 aou.findOrgUnit(lin.alert_text().owning_lib()).shortname() +
2534 lin.alert_text().code()
2536 lin.alert_text().description() || "",
2543 this.checkLiAlerts = function(li_id) {
2544 var li = this.liCache[li_id];
2546 var alert_notes = li.lineitem_notes().filter(
2547 function(o) { return Boolean(o.alert_text()); }
2550 /* this is _intentionally_ not done in a call to forEach() ... */
2551 for (var i = 0; i < alert_notes.length; i++) {
2552 if (this.noteAcks[alert_notes[i].id()])
2554 else if (!this._confirmAlert(li, alert_notes[i]))
2557 this.noteAcks[alert_notes[i].id()] = true;
2563 this.deleteCopy = function(row) {
2564 var copy = this.copyCache[row.getAttribute('copy_id')];
2565 copy.isdeleted(true);
2567 delete this.copyCache[copy.id()];
2568 this.copyTbody.removeChild(row);
2571 this._virtDfaCountsAsList = function() {
2573 for (var key in this.virtDfaCounts) {
2574 for (var i = 0; i < this.virtDfaCounts[key]; i++)
2580 this.confirmBreachedCopyFunds = function(copies) {
2581 var stop = 0, warning = 0;
2585 var state = self.fundBalanceState[o.fund()];
2586 if (state[0] /* stop */)
2588 else if (state[1] /* warning */)
2595 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
2596 } else if (warning) {
2597 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
2602 this.saveCopyChanges = function(liId) {
2608 for(var id in this.copyCache) {
2609 var c = this.copyCache[id];
2610 if(!c.isdeleted()) total++;
2611 if(c.isnew() || c.ischanged() || c.isdeleted()) {
2612 if(c.id() < 0) c.id(null);
2618 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
2621 if (copies.length > 0) {
2622 if (!this.confirmBreachedCopyFunds(copies))
2625 if (typeof(this._copy_count_cb) == "function")
2626 this._copy_count_cb(liId, total);
2628 openils.Util.show("acq-lit-update-copies-progress");
2629 fieldmapper.standardRequest(
2630 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
2632 params: [openils.User.authtoken, copies],
2633 onresponse: function(r) {
2634 var res = openils.Util.readResponse(r);
2635 litUpdateCopiesProgress.update(res);
2637 oncomplete: function() {
2638 self.drawCopies(liId, true /* force_fetch */);
2639 openils.Util.hide("acq-lit-update-copies-progress");
2645 var dfa_list = this._virtDfaCountsAsList();
2646 if (dfa_list.length > 0) {
2647 fieldmapper.standardRequest(
2649 "open-ils.acq.distribution_formula.record_application"],
2652 "params": [openils.User.authtoken, dfa_list, liId],
2653 "onresponse": function(r) {
2654 var res = openils.Util.readResponse(r);
2655 if (res && res.length < dfa_list.length)
2656 alert(localeStrings.DFA_NOT_ALL);
2660 this.virtDfaCounts = {};
2663 if (this.inlineCopiesNeedingRefresh.indexOf(liId) < 0)
2664 this.inlineCopiesNeedingRefresh.push(liId);
2667 this._updateCreatePoPrepayCheckbox = function(prepay) {
2668 var prepay = openils.Util.isTrue(prepay);
2669 this._prepayRequiredByVendor = prepay;
2670 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
2673 this._confirmPoPrepaySituation = function() {
2674 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
2675 if (want_prepay != this._prepayRequiredByVendor) {
2678 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
2679 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
2686 this.applySelectedLiAction = function(action) {
2690 case 'delete_selected':
2691 this._deleteLiList(self.getSelected());
2694 case 'add_to_order':
2695 addToPoDialog._get_li = dojo.hitch(
2697 function() { return this.getSelected(false, null, true); }
2699 addToPoDialog.show();
2702 case 'create_order':
2703 this._loadPOSelect();
2704 acqLitPoCreateDialog.show();
2707 case 'save_picklist':
2708 acqLitSavePlDialog.show();
2711 case 'selector_ready':
2713 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
2714 acqLitChangeLiStateDialog.show();
2722 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
2725 case 'batch_create_invoice':
2726 this.batchCreateInvoice();
2729 case 'batch_link_invoice':
2730 this.batchLinkInvoice();
2733 case 'receive_lineitems':
2734 this.receiveSelectedLineitems();
2737 case 'rollback_receive_lineitems':
2738 this.rollbackReceiveLineitems();
2741 case 'create_assets':
2742 this.showAssetCreator();
2745 case 'export_attr_list':
2746 this.chooseExportAttr();
2749 case 'batch_apply_funds':
2750 this.applyBatchLiFunds();
2753 case 'add_brief_record':
2755 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
2757 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
2761 case "cancel_lineitems":
2762 this.maybeCancelLineitems();
2765 case "apply_claim_policy":
2766 var li_list = this.getSelected();
2767 this.claimPolicyPicker.attr("value", null);
2768 liClaimPolicyDialog.show();
2769 liClaimPolicySave.onClick = function() {
2770 self.changeClaimPolicy(
2772 self.claimPolicyPicker.attr("value"),
2776 self.setClaimPolicyControl(li);
2777 self.reconsiderClaimControl(li);
2780 liClaimPolicyDialog.hide();
2788 this.changeClaimPolicy = function(li_list, value, callback) {
2790 function(li) { li.claim_policy(value); }
2792 fieldmapper.standardRequest(
2793 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
2794 "params": [openils.User.authtoken, li_list],
2796 "oncomplete": function(r) {
2797 r = openils.Util.readResponse(r);
2798 if (callback) callback(r);
2804 this.showAssetCreator = function(onAssetsCreated) {
2805 if(!this.isPO) return;
2808 // first, let's see if this PO has any LI's that need to be merged/imported
2809 self.pcrud.search('jub', {purchase_order : this.isPO, eg_bib_id : null}, {
2811 oncomplete : function(r) {
2812 var resp = openils.Util.readResponse(r);
2813 if (resp && resp.length) {
2814 // PO has some non-linked jubs.
2816 self.show('asset-creator');
2817 if(!self.vlAgent.loaded)
2818 self.vlAgent.init();
2820 dojo.connect(assetCreatorButton, 'onClick',
2821 function() { self.createAssets(onAssetsCreated) });
2825 // all jubs linked, move on to asset creation
2826 self.createAssets(onAssetsCreated, true);
2832 this.createAssets = function(onAssetsCreated, noVl) {
2833 this.show('acq-lit-progress-numbers');
2835 var vlArgs = (noVl) ? {} : {vandelay : this.vlAgent.values()};
2836 fieldmapper.standardRequest(
2837 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
2839 params: [this.authtoken, this.isPO, vlArgs],
2840 onresponse: function(r) {
2841 var resp = openils.Util.readResponse(r);
2842 self._updateProgressNumbers(resp, !Boolean(onAssetsCreated), onAssetsCreated);
2848 this.maybeCancelLineitems = function() {
2849 openils.Util.show("acq-lit-cancel-reason", "inline");
2850 if (!acqLitCancelLineitemsButton._prepared) {
2851 var widget = new openils.widget.AutoFieldWidget({
2852 "fmField": "cancel_reason",
2854 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
2855 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2860 acqLitCancelLineitemsButton.onClick = function() {
2861 if (w.attr("value")) {
2862 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
2863 self._cancelLineitems(w.attr("value"));
2865 openils.Util.hide("acq-lit-cancel-reason");
2868 acqLitCancelLineitemsButton._prepared = true;
2874 this._cancelLineitems = function(reason) {
2875 var id_list = this.getSelected().map(function(o) { return o.id(); });
2876 fieldmapper.standardRequest(
2877 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
2878 "params": [openils.User.authtoken, id_list, reason],
2880 "onresponse": function(r) {
2881 if (r = openils.Util.readResponse(r)) {
2883 for (var id in r.li) {
2884 self.liCache[id].state(r.li[id].state);
2885 self.liCache[id].cancel_reason(
2886 r.li[id].cancel_reason
2888 self.updateLiState(self.liCache[id]);
2891 if (r.lid && self.copyCache) {
2892 for (var id in r.lid) {
2893 if (self.copyCache[id]) {
2894 self.copyCache[id].cancel_reason(
2895 r.lid[id].cancel_reason
2897 self.updateLidState(self.copyCache[id]);
2907 this.chooseExportAttr = function() {
2908 if (!acqLitExportAttrSelector._li_setup) {
2910 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
2912 "data": acqlimad.toStoreData(
2914 "acqlimad", {"code": li_exportable_attrs}
2919 acqLitExportAttrSelector.setValue();
2920 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
2921 acqLitExportAttrSelector._li_setup = true;
2923 openils.Util.show("acq-lit-export-attr-holder", "inline");
2926 this.exportAttrList = function() {
2927 var attr_def = acqLitExportAttrSelector.item;
2928 var li_list = this.getSelected();
2929 var value_list = li_list.map(
2931 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2932 attr_def.code, "lineitem_marc_attr_definition"
2935 ).filter(function(attr) { return Boolean(attr); });
2937 if (value_list.length > 0) {
2938 if (value_list.length < li_list.length) {
2940 dojo.string.substitute(
2941 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
2948 openils.XUL.contentToFileSaveDialog(
2949 value_list.join("\n"),
2950 localeStrings.EXPORT_SAVE_DIALOG_TITLE
2956 alert(dojo.string.substitute(
2957 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
2961 openils.Util.hide("acq-lit-export-attr-holder");
2964 this.printPO = function() {
2965 if(!this.isPO) return;
2966 progressDialog.show(true);
2967 fieldmapper.standardRequest(
2968 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
2970 params: [this.authtoken, this.isPO, 'html'],
2971 oncomplete: function(r) {
2972 progressDialog.hide();
2973 var evt = openils.Util.readResponse(r);
2974 if(evt && evt.template_output()) {
2975 openils.Util.printHtmlString(evt.template_output().data());
2982 this.batchCreateInvoice = function() {
2983 var liIds = this.getSelected(false, null, true /* id_list */)
2984 if (!liIds.length) return;
2985 var path = oilsBasePath + '/acq/invoice/view?create=1';
2986 dojo.forEach(liIds, function(li, idx) { path += '&attach_li=' + li });
2987 if (openils.XUL.isXUL())
2988 openils.XUL.newTabEasy(path, localeStrings.NEW_INVOICE, null, true);
2990 location.href = path;
2993 this.batchLinkInvoice = function(create) {
2994 var liIds = this.getSelected(false, null, true /* id_list */)
2995 if (!liIds.length) return;
2996 if (!self.invoiceLinkDialogManager) {
2997 self.invoiceLinkDialogManager =
2998 new InvoiceLinkDialogManager("li");
3000 self.invoiceLinkDialogManager.target = liIds;
3001 acqLitLinkInvoiceDialog.show();
3004 this.receiveSelectedLineitems = function() {
3005 var li_list = this.getSelected();
3007 if (!li_list.length) {
3008 alert(localeStrings.NO_LI_GENERAL);
3012 for (var i = 0; i < li_list.length; i++) {
3013 var li = li_list[i];
3015 if (li.state() != "received" &&
3016 !this.checkLiAlerts(li.id())) return;
3019 this.show('acq-lit-progress-numbers');
3022 fieldmapper.standardRequest(
3023 ['open-ils.acq', 'open-ils.acq.lineitem.receive.batch'],
3027 li_list.map(function(li) { return li.id(); })
3029 onresponse : function(r) {
3030 var resp = openils.Util.readResponse(r);
3031 self._updateProgressNumbers(resp, true);
3037 this.issueReceive = function(obj, rollback) {
3039 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
3041 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
3043 progressDialog.show(true);
3044 fieldmapper.standardRequest(
3045 ["open-ils.acq", method], {
3047 "params": [this.authtoken, obj.id()],
3048 "onresponse": function(r) {
3049 if (r = openils.Util.readResponse(r)) {
3050 self.fetchClaimInfo(
3051 part == "lineitem" ? obj.id() : obj.lineitem(),
3053 function() { self.handleReceive(r); }
3055 progressDialog.hide();
3063 * Handles the responses from receive and rollback ML calls.
3065 this.handleReceive = function(resp) {
3068 for (var li_id in resp.li) {
3069 for (var key in resp.li[li_id])
3070 self.liCache[li_id][key](resp.li[li_id][key]);
3071 self.updateLiState(self.liCache[li_id]);
3075 if (typeof(self.poUpdateCallback) == "function")
3076 self.poUpdateCallback(resp.po);
3079 for (var lid_id in resp.lid) {
3080 for (var key in resp.lid[lid_id])
3081 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
3082 self.updateLidState(self.copyCache[lid_id]);
3088 this.rollbackReceiveLineitems = function() {
3089 var li_id_list = this.getSelected(false, null, true);
3090 if (!li_id_list.length) {
3091 alert(localeStrings.NO_LI_GENERAL);
3095 if (!confirm(localeStrings.ROLLBACK_LI_RECEIVE_CONFIRM)) return;
3097 this.show('acq-lit-progress-numbers');
3100 fieldmapper.standardRequest(
3101 ['open-ils.acq', 'open-ils.acq.lineitem.receive.rollback.batch'],
3103 params: [this.authtoken, li_id_list],
3104 onresponse : function(r) {
3105 var resp = openils.Util.readResponse(r);
3106 self._updateProgressNumbers(resp, true);
3112 this._updateProgressNumbers = function(resp, reloadOnComplete, onComplete) {
3113 this.vlAgent.handleResponse(resp,
3114 function(resp, res) {
3115 if(reloadOnComplete)
3116 location.href = location.href;
3118 onComplete(resp, res);
3124 this._createPO = function(fields) {
3125 var wantall = (fields.create_from == "all");
3127 /* If we're a picklist or purchase order already and the user wants
3128 * all lineitems, we might have pages' worth of lineitems haven't all
3129 * been loaded yet, so getSelected() won't find them. The server,
3130 * however, should know about all our lineitems, so let's ask the
3131 * server for a complete list.
3136 true, function(list) {
3137 self._createPOFromLineitems(fields, list);
3138 }, /* id_list */ true
3141 this._createPOFromLineitems(fields, this.getSelected(false, null, true /* id_list */));
3145 this._createPOFromLineitems = function(fields, selected) {
3146 if (selected.length == 0) return;
3149 var po = new fieldmapper.acqpo();
3150 po.provider(this.createPoProviderSelector.attr("value"));
3151 po.ordering_agency(this.createPoAgencySelector.attr("value"));
3152 po.prepayment_required(fields.prepayment_required[0] ? true : false);
3154 // if we're creating assets, delay the asset creation
3155 // until after the PO is created. This will allow us to
3156 // use showAssetCreator() directly.
3158 fieldmapper.standardRequest(
3159 ["open-ils.acq", "open-ils.acq.purchase_order.create"],
3162 openils.User.authtoken,
3163 po, {lineitems : selected}
3165 onresponse : function(r) {
3166 var resp = openils.Util.readResponse(r);
3167 if (resp.complete) {
3168 // self.isPO is needed for showAssetCreator();
3169 self.isPO = resp.purchase_order.id();
3170 var redir = oilsBasePath + "/acq/po/view/" + self.isPO;
3171 if (fields.create_assets[0]) {
3172 self.showAssetCreator(
3173 function() {location.href = redir}
3176 location.href = redir;
3185 this.batchFundWidget = null;
3187 this.applyBatchLiFunds = function() {
3189 var liIds = this.getSelected().map(function(li) { return li.id(); });
3190 if(liIds.length == 0) return; // warn?
3193 batchFundUpdateDialog.show();
3195 if(!this.batchFundWidget) {
3196 this.batchFundWidget = new openils.widget.AutoFieldWidget({
3198 selfReference : true,
3199 labelFormat : fundLabelFormat,
3200 searchFormat : fundSearchFormat,
3201 searchFilter : {"active": "t"},
3202 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
3203 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
3204 dijitArgs : { "required": true, "labelType": "html" },
3207 this.batchFundWidget.build();
3210 dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
3211 dojo.connect(batchFundUpdateSubmit, 'onClick',
3214 // TODO: call .dry_run first to test thresholds
3215 fieldmapper.standardRequest(
3216 ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
3219 openils.User.authtoken,
3221 self.batchFundWidget.widget.attr('value')
3223 oncomplete : function(r) {
3224 var resp = openils.Util.readResponse(r);
3226 location.href = location.href;
3235 this._deleteLiList = function(list, idx) {
3236 if(idx == null) idx = 0;
3237 if(idx >= list.length) return;
3242 if (this.isPO && (li.state() == "on-order" || li.state() == "received")) {
3243 /* It makes little sense to delete a lineitem from a PO that has
3244 * already been marked 'on-order'. Especially if EDI is in use,
3245 * such a purchase order will probably have already been shipped
3246 * off to a vendor, and mucking with it at this point could leave
3247 * your data in a bad state that doesn't jive with reality.
3249 * I could see making this restriction even firmer.
3251 * I could also see adjusting the li state comparisons, extending
3252 * the comparison to the PO's state, and/or providing functions
3253 * that house the logic for comparing states in a single location.
3255 * Yes, this will be really annoying if you have selected a lot
3256 * of lineitems to cancel that have been ordered. You'll get a
3257 * confirm dialog for each one.
3260 if (!confirm(localeStrings.DEL_LI_FROM_PO)) {
3261 self._deleteLiList(list, ++idx); /* move on to next in list */
3266 fieldmapper.standardRequest(
3268 this.isPO ? 'open-ils.acq.purchase_order.lineitem.delete' : 'open-ils.acq.picklist.lineitem.delete'],
3270 params: [openils.User.authtoken, liId],
3271 oncomplete: function(r) {
3272 self.removeLineitem(liId);
3273 self._deleteLiList(list, ++idx);
3279 this.editOrderMarc = function(li) {
3281 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
3282 to true in about:config */
3284 if(openils.XUL.isXUL()) {
3285 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul','','chrome');
3287 win = window.open('/xul/server/cat/marcedit.xul','','chrome');
3291 record : {marc : li.marc(), "rtype": "bre"},
3293 label: 'Save Record', // XXX I18N
3294 func: function(xmlString) {
3296 fieldmapper.standardRequest(
3297 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
3299 params: [openils.User.authtoken, li],
3300 oncomplete: function(r) {
3301 openils.Util.readResponse(r);
3303 self.drawInfo(li.id())
3309 'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
3310 'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
3314 this._savePl = function(values) {
3316 (values.which == 'all'),
3317 function(list) { self._savePlFromLineitems(values, list); }
3321 this._savePlFromLineitems = function(values, selected) {
3322 openils.Util.show("acq-lit-generic-progress");
3324 if(values.new_name) {
3325 openils.acq.Picklist.create(
3326 {name: values.new_name},
3332 oilsBasePath + "/acq/picklist/view/" + id;
3337 } else if(values.existing_pl) {
3338 // update lineitems to use an existing picklist
3340 values.existing_pl, selected, 0,
3343 oilsBasePath + "/acq/picklist/view/" +
3350 this._updateLiState = function(values, state) {
3351 progressDialog.show(true);
3353 (values.which == 'all'),
3355 self._updateLiStateFromLineitems(values, state, list);
3360 this._updateLiStateFromLineitems = function(values, state, selected) {
3361 if(!selected.length) return;
3362 dojo.forEach(selected, function(li) {li.state(state);});
3363 self._updateLiList(null, selected, 0,
3364 // TODO consider inline updates for efficiency
3365 function() { location.href = location.href }
3369 this._updateLiList = function(pl, list, idx, oncomplete) {
3370 if(idx >= list.length) return oncomplete();
3372 if(pl != null) li.picklist(pl);
3373 litGenericProgress.update({maximum: list.length, progress: idx});
3374 new openils.acq.Lineitem({lineitem:li}).update(
3376 self._updateLiList(pl, list, ++idx, oncomplete);
3381 this._loadPOSelect = function() {
3382 if (!this.createPoProviderSelector) {
3383 var widget = new openils.widget.AutoFieldWidget({
3384 "fmField": "provider",
3386 "searchFilter": {"active": "t"},
3387 "parentNode": dojo.byId("acq-lit-po-provider"),
3389 "onChange": function() {
3391 self._updateCreatePoPrepayCheckbox(
3392 this.item.prepayment_required()
3398 widget.build(function(w) { self.createPoProviderSelector = w; });
3401 if (!this.createPoAgencySelector) {
3402 var widget = new openils.widget.AutoFieldWidget({
3403 "fmField": "ordering_agency",
3405 "parentNode": dojo.byId("acq-lit-po-agency"),
3406 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3408 widget.build(function(w) { self.createPoAgencySelector = w; });
3412 this.showRealCopyEditUI = function(li) {
3417 this._fetchLineitem(li.id(),
3419 li = self.liCache[li.id()] = fullLi;
3423 id : li.lineitem_details().map(
3424 function(item) { return item.eg_copy_id() }
3428 oncomplete : function(r) {
3430 var r_list = openils.Util.readResponse( r );
3431 for (var i = 0; i < r_list.length; i++) {
3432 var copy = r_list[i];
3433 var volId = copy.call_number();
3434 var volume = self.volCache[volId];
3436 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
3438 copy.call_number(volume);
3439 copyList.push(copy);
3442 xulG.volume_item_creator( { 'existing_copies' : copyList } );
3445 alert('error in oncomplete: ' + E);
3454 this.drawBibFinder = function(li) {
3457 var liWrapper = new openils.acq.Lineitem({lineitem:li});
3460 ['isbn', 'upc', 'issn', 'title', 'author'],
3462 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
3464 if(field == 'title' || field == 'author') {
3465 query += field +':' + val + ' ';
3467 query += 'identifier|' + field + ':' + val + ' ';
3474 oilsBasePath + '/acq/lineitem/findbib?query=' + escape(query),
3475 '', 'resizable,scrollbars=1,chrome');
3477 win.window.recordFound = function(bibId) {
3480 var attrs = li.attributes();
3481 li.attributes(null);
3482 li.eg_bib_id(bibId);
3484 fieldmapper.standardRequest(
3485 ["open-ils.acq", "open-ils.acq.lineitem.update"],
3487 "params": [openils.User.authtoken, li],
3489 "oncomplete": function(r) {
3490 if(openils.Util.readResponse(r)) {
3491 location.href = location.href;