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);
579 * Inserts a single lineitem into the growing table of lineitems
580 * @param {Object} li The lineitem object to insert
582 this.addLineitem = function(li, skip_final_placement) {
583 this.liCache[li.id()] = li;
585 // insert the row right away so that final order isn't
586 // dependent on how long subsequent async request take
587 // for a given line item
588 var row = self.rowTemplate.cloneNode(true);
589 if (!skip_final_placement) {
590 self.tbody.appendChild(row);
592 self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
594 // sort the lineitem notes on edit_time
595 if(!li.lineitem_notes()) li.lineitem_notes([]);
597 var liWrapper = new openils.acq.Lineitem({lineitem:li});
598 row.setAttribute('li', li.id());
599 var tds = dojo.query('[attr]', row);
600 dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
601 dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
603 // so we can scroll to it later
604 dojo.query('[name=bib-info-cell]', row)[0].id = 'li-title-ref-' + li.id();
607 liWrapper.findAttr("isbn", "lineitem_marc_attr_definition") ||
608 liWrapper.findAttr("upc", "lineitem_marc_attr_definition");
610 // XXX media prefix for added content
612 nodeByName("jacket", row).setAttribute(
613 "src", "/opac/extras/ac/jacket/small/" + identifier
617 nodeByName("liid", row).innerHTML += li.id();
620 openils.Util.show(nodeByName('catalog', row), 'inline');
621 nodeByName("catalog_link", row).onclick = this.generateMakeRecTab(li.eg_bib_id());
623 openils.Util.show(nodeByName('link_to_catalog', row), 'inline');
624 nodeByName("link_to_catalog_link", row).onclick = function() { self.drawBibFinder(li) };
627 if (li.queued_record()) {
628 this.pcrud.retrieve('vqbr', li.queued_record(),
630 oncomplete : function(r) {
631 var qrec = openils.Util.readResponse(r);
632 openils.Util.show(nodeByName('queue', row), 'inline');
633 var link = nodeByName("queue_link", row);
634 link.onclick = function() {
635 // open a new tab to the vandelay queue for this record
636 openils.XUL.newTabEasy(
637 oilsBasePath + '/vandelay/vandelay?qtype=bib&qid=' + qrec.queue()
645 nodeByName("worksheet_link", row).href =
646 oilsBasePath + "/acq/lineitem/worksheet/" + li.id() +
647 '?source=' + encodeURIComponent(location.pathname + location.search)
649 nodeByName("show_requests_link", row).href =
650 oilsBasePath + "/acq/picklist/user_request?lineitem=" + li.id() +
651 '?source=' + encodeURIComponent(location.pathname + location.search)
653 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
654 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
655 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
656 dojo.query('[name=expand_inline_copies]', row)[0].onclick =
657 function() {self.drawInlineCopies(li.id())};
659 this.drawOrderIdentSelector(li, row);
661 if (!this.skipInitialEligibilityCheck)
665 function(full) { self.setClaimPolicyControl(full, row) },
669 this.updateLiNotesCount(li, row);
671 // show which PO this lineitem is a member of
672 if(li.purchase_order() && !this.isPO) {
674 this.poCache[li.purchase_order()] =
675 this.poCache[li.purchase_order()] ||
676 fieldmapper.standardRequest(
677 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
679 this.authtoken, li.purchase_order(), {
680 "flesh_price_summary": true,
681 "flesh_provider" : true,
682 "flesh_lineitem_count": true
685 if(po && !this.isMeta) {
686 openils.Util.show(nodeByName('po', row), 'inline');
687 var link = nodeByName('po_link', row);
688 link.setAttribute('href', oilsBasePath +
689 '/acq/po/view/' + li.purchase_order() +
690 '?focus_li=' + li.id() +
691 '&source=' + encodeURIComponent(location.pathname + location.search)
693 link.innerHTML += po.name();
695 openils.Util.show(nodeByName('pro', row), 'inline');
696 link = nodeByName('pro_link', row);
697 link.setAttribute('href', oilsBasePath + '/conify/global/acq/provider/' + po.provider().id())
698 link.innerHTML += po.provider().code();
702 // show which picklist this lineitem is a member of
703 if(li.picklist() && (this.isPO || this.isMeta || this.isUni)) {
705 this.plCache[li.picklist()] =
706 this.plCache[li.picklist()] ||
707 fieldmapper.standardRequest(
708 ['open-ils.acq', 'open-ils.acq.picklist.retrieve.authoritative'],
709 {params: [this.authtoken, li.picklist()]});
711 if (pl.name() == "") {
712 openils.Util.show(nodeByName("bib_origin", row), "inline");
716 openils.Util.show(nodeByName('pl', row), 'inline');
717 var link = nodeByName('pl_link', row);
718 link.setAttribute('href', oilsBasePath +
719 '/acq/picklist/view/' + li.picklist() +
720 '?focus_li=' + li.id() +
721 '&source=' + encodeURIComponent(location.pathname + location.search)
723 link.innerHTML += pl.name();
728 var countNode = nodeByName('count', row);
729 var count = li.item_count() || 0;
730 if (typeof(this._copy_count_cb) == "function") {
731 this._copy_count_cb(li.id(), count);
733 countNode.innerHTML = count;
734 countNode.id = 'acq-lit-copy-count-label-' + li.id();
737 var priceInput = dojo.query('[name=price]', row)[0];
738 priceInput.value = li.estimated_unit_price() || '';
739 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
741 // show either "mark received" or "unreceive" as appropriate
742 this.updateLiState(li, row);
744 if (skip_final_placement) {
748 // the last LI may be rendered after the call to show('list'),
749 // so make sure it's focused if necessary.
750 if (this.focusLineitem == li.id())
754 this._liCountClaims = function(li) {
756 for (var i = 0; i < li.lineitem_details().length; i++)
757 total += li.lineitem_details()[i].claims().length;
761 this._findLiRow = function(li) {
762 return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
765 this.reconsiderClaimControl = function(li, row) {
766 if (!row) row = this._findLiRow(li);
767 var option = nodeByName("action_manage_claims", row);
768 var eligible = this.claimEligibleLidByLi[li.id()].length;
769 var count = this._liCountClaims(li);
771 option.disabled = !(count || eligible);
773 dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
774 option.onclick = function() { self.claimDialog.show(li); };
777 this.clearEligibility = function(li) {
778 this.claimEligibleLidByLi[li.id()] = [];
780 if (li.lineitem_details()) {
781 li.lineitem_details().forEach(
782 function(lid) { delete self.claimEligibleLid[lid.id()]; }
786 if (this.copyCache) {
788 for (var k in this.copyCache) {
789 if (this.copyCache[k].lineitem() == li.id())
793 function(k) { delete self.claimEligibleLid[k]; }
798 this.applyOrderIdentValues = function() {
799 this._identValuesInFlight =
800 openils.Util.objectProperties(this.liCache).length;
801 for (var liId in this.liCache) {
802 this._applyOrderIdentValue(this.liCache[liId]);
806 // returns true if request was sent
807 this._applyOrderIdentValue = function(li) {
810 console.log('applying ident value for lineitem ' + li.id());
813 var row = dojo.query('[li=' + li.id() + ']')[0];
815 // find the selected ident value
816 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
817 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
818 var name = typeSel.options[typeSel.selectedIndex].value;
819 var val = typeSel._cbox.attr('value');
821 console.log("selected ident is " + val);
823 // it differs from the existing ident value, update it
824 var oldIdent = self.getLiOrderIdent(li);
826 oldIdent.attr_name() == name &&
827 oldIdent.attr_value() == val) {
828 console.log('selected ident attr matches existing attr');
829 if (--this._identValuesInFlight == 0)
830 location.href = location.href;
834 // see if the selected ident value is represented
835 // by an existing lineitem attr
838 typeSel._cbox.store.fetch({
839 query : {attr_value : val},
840 onItem : function(item) {
841 console.log('found existing attr for ident value');
842 args.source_attr_id = li.attributes().filter(
843 function(attr) { return attr.id() == item.id[0] }
849 if (!args.source_attr_id) {
850 // user entered new text in the combobox
851 // so we need to create a new attr
852 console.log('creating new ident attr');
853 args.lineitem_id = li.id();
854 args.attr_name = name;
855 args.attr_value = val;
858 fieldmapper.standardRequest(
859 ['open-ils.acq', 'open-ils.acq.lineitem.order_identifier.set'],
861 params : [openils.User.authtoken, args],
862 oncomplete : function() {
863 console.log('order_ident oncomplete');
864 if (--self._identValuesInFlight == 0)
865 location.href = location.href;
873 this.getLiOrderIdent = function(li) {
874 var attrs = li.attributes();
875 if (!attrs) return null;
879 attr.attr_type() == 'lineitem_local_attr_definition' &&
880 openils.Util.isTrue(attr.order_ident())
886 this.drawOrderIdentSelector = function(li, row) {
888 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
889 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
891 var attrs = li.attributes();
893 // limit to MARC attr defs
894 attrs = attrs.filter(
896 return (attr.attr_type() == 'lineitem_marc_attr_definition');
900 var identAttr = this.getLiOrderIdent(li);
903 // collect the values for each type of identifier
904 // find a reasonable default identifier type to render
908 dojo.forEach(['isbn', 'upc', 'issn'],
911 // collect the values for this attr name
912 values[name] = attrs.filter(
914 return (attr.attr_name() == name)
918 // select a reasonable default name in the type-selector
922 if (identAttr.attr_name() == name)
924 } else if (values[name].length) {
929 dojo.forEach(typeSel.options, function(opt) {
930 if (opt.value == name) {
940 function updateOrderIdent(box) {
941 console.log('updating order ident for box ' + box);
944 // replace the ident combobox with a new
945 // one for the selected ident type
946 function changeComboBox(sel) {
947 var name = sel.options[sel.selectedIndex].value;
949 var td = dojo.query('[name=order_ident_value]', row)[0];
950 if (td.childNodes[0])
951 dojo.destroy(td.childNodes[0]);
953 var store = new dojo.data.ItemFileWriteStore({
954 data : acqlia.toStoreData(values[name])
957 var cbox = new dijit.form.ComboBox(
959 labelAttr : 'attr_value',
960 searchAttr : 'attr_value'
962 dojo.create('div', {}, td)
967 // set the value for the cbox
968 if (values[name].length) {
969 var orderIdent = self.getLiOrderIdent(li);
971 if (orderIdent && orderIdent.attr_name() == name) {
972 cbox.attr('value', orderIdent.attr_value());
974 cbox.attr('value', values[name][0].attr_value());
978 if (!self.orderIdentAllowed)
979 cbox.attr('disabled', true);
983 dojo.connect(cbox, 'onChange', updateOrderIdent);
986 changeComboBox(typeSel); // force the initial draw
987 typeSel.onchange = function() {changeComboBox(typeSel)};
990 this.testOrderIdentPerms = function(org, callback) {
992 new openils.User().getPermOrgList(
993 'ACQ_SET_LINEITEM_IDENTIFIER',
995 console.log('found orgs = ' + orgs);
996 for (var i = 0; i < orgs.length; i++) {
997 if (Number(orgs[i]) == Number(org)) {
998 self.orderIdentAllowed = true;
999 if (callback) callback();
1003 if (callback) callback();
1009 this.checkClaimEligibility = function(li, callback, row) {
1010 /* Assume always eligible, i.e. from this interface we don't care about
1011 * claim eligibility any more. this is where the user would force a
1013 this.clearEligibility(li);
1014 this.claimEligibleLidByLi[li.id()] = li.lineitem_details().map(
1015 function(lid) { return lid.id(); }
1017 li.lineitem_details().forEach(
1018 function(lid) { self.claimEligibleLid[lid.id()] = true; }
1020 this.reconsiderClaimControl(li, row);
1021 if (callback) callback(li);
1023 this.clearEligibility(li);
1024 fieldmapper.standardRequest(
1025 ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
1026 "params": [openils.User.authtoken, {"lineitem": li.id()}],
1028 "onresponse": function(r) {
1029 if (r = openils.Util.readResponse(r)) {
1030 self.claimEligibleLidByLi[li.id()].push(
1033 self.claimEligibleLid[r.lineitem_detail()] = true;
1036 "oncomplete": function() {
1037 self.reconsiderClaimControl(li, row);
1038 if (typeof(callback) == "function")
1046 this.updateLiNotesCount = function(li, row) {
1047 if (!row) row = this._findLiRow(li);
1049 var has_notes = (li.lineitem_notes().filter(
1050 function(o) { return Boolean (o.alert_text()); }
1053 /* U+2691 is the code point for a filled-in flag character */
1054 nodeByName("notes_alert_flag", row).innerHTML =
1055 has_notes ? "⚑" : "";
1056 nodeByName("noteslink", row).style.fontStyle =
1057 has_notes ? "italic" : "normal";
1058 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
1061 /* XXX NOT related to _updateLiState(). rethink */
1062 this.updateLiState = function(li, row) {
1063 if (!row) row = this._findLiRow(li);
1065 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
1066 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
1068 // always allow access to LI history
1069 nodeByName('action_view_history', row).onclick =
1070 function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
1072 /* handle row coloring for based on LI state */
1073 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1074 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
1076 // Expose invoice actions for any lineitem that is linked to a PO
1077 if (li.purchase_order()) {
1078 openils.Util.show(nodeByName("invoices_span", row), "inline");
1079 var link = nodeByName("invoices_link", row);
1080 link.onclick = function() {
1081 openils.XUL.newTabEasy(
1082 oilsBasePath + "/acq/search/unified?so=" +
1083 base64Encode({"jub":[{"id": li.id()}]}) + "&rt=invoice"
1091 * If we haven't fleshed the lineitem_details, default to allowing access to the
1092 * holdings maintenence actions. The alternative is to flesh LIDs on every lineitem,
1093 * but that will add to page render time. Let's see if this will suffice...
1095 var lids = li.lineitem_details();
1097 (lids && !lids.filter(function(lid) { return lid.eg_copy_id() })[0] )) {
1099 actUpdateBarcodes.disabled = false;
1100 actUpdateBarcodes.onclick = function() {
1101 self.showRealCopyEditUI(li);
1102 nodeByName("action_none", row).selected = true;
1104 actHoldingsMaint.disabled = false;
1105 actHoldingsMaint.onclick =
1106 self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
1109 var state_cell = nodeByName("li_state", row);
1111 switch(li.state()) {
1114 if(typeof li.cancel_reason() == "object") {
1115 var holds_state = dojo.create(
1117 "style": "border-bottom: 1px dashed #000;",
1118 "innerHTML": li.state()
1119 }, state_cell, "only"
1123 "label": "<em>" + li.cancel_reason().label() +
1124 "</em><br />" + li.cancel_reason().description(),
1125 "connectId": [holds_state]
1126 }, dojo.create("span", null, state_cell, "last")
1138 state_cell.innerHTML = li.state(); // TODO i18n state labels
1142 this._setAlertStore = function() {
1143 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
1145 "data": acqliat.toStoreData(
1148 "owning_lib": aou.orgNodeTrail(
1149 aou.findOrgUnit(openils.User.user.ws_ou())
1150 ).map(function(o) { return o.id(); })
1156 acqLitAlertAlertText.setValue(); /* make the store "live" */
1157 acqLitAlertAlertText._store_ready = true;
1161 * Draws and shows the lineitem notes pane
1163 this.drawLiNotes = function(li) {
1165 this.focusLineitem = li.id();
1167 if (!acqLitAlertAlertText._store_ready)
1168 this._setAlertStore();
1171 li.lineitem_notes().sort(
1173 if(a.edit_time() < b.edit_time()) return 1;
1179 while(this.liNotesTbody.childNodes[0])
1180 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
1183 acqLitCreateNoteSubmit.onClick = function() {
1184 var value = acqLitCreateNoteText.attr('value');
1186 var note = new fieldmapper.acqlin();
1189 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
1192 note.lineitem(li.id());
1194 self.updateLiNotes(li, note);
1195 acqLitCreateNoteVendorPublic.attr("checked", false);
1196 acqLitCreateNoteText.attr("value", "");
1199 acqLitCreateAlertSubmit.onClick = function() {
1200 if (!acqLitAlertAlertText.item) {
1201 alert(localeStrings.ALERT_UNSELECTED);
1205 var alert_text = new fieldmapper.acqliat().fromStoreItem(
1206 acqLitAlertAlertText.item
1208 var value = acqLitAlertNoteValue.attr("value") || "";
1210 var note = new fieldmapper.acqlin();
1212 note.lineitem(li.id());
1214 note.alert_text(alert_text);
1216 self.updateLiNotes(li, note);
1219 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
1223 * Draws a single lineitem note in the notes pane
1225 this.addLiNote = function(li, note) {
1226 if(note.isdeleted()) return;
1228 var row = self.liNotesRow.cloneNode(true);
1229 nodeByName("value", row).innerHTML = note.value();
1230 var alert_node = nodeByName("alert_code", row);
1231 if (note.alert_text()) {
1232 alert_node.innerHTML = dojo.string.substitute(
1234 aou.findOrgUnit(note.alert_text().owning_lib()).shortname(),
1235 note.alert_text().code()
1238 if (note.alert_text().description()) {
1241 "connectId": [alert_node],
1242 "label": note.alert_text().description()
1243 }, dojo.create("span", null, alert_node, "after")
1248 if (openils.Util.isTrue(note.vendor_public()))
1249 nodeByName("vendor_public", row).innerHTML =
1250 localeStrings.VENDOR_PUBLIC;
1252 nodeByName("delete", row).onclick = function() {
1253 note.isdeleted(true);
1254 self.liNotesTbody.removeChild(row);
1255 self.updateLiNotes(li);
1258 if(note.edit_time()) {
1259 nodeByName("edit_time", row).innerHTML =
1260 dojo.date.locale.format(
1261 dojo.date.stamp.fromISOString(note.edit_time()),
1262 {formatLength:'short'});
1265 self.liNotesTbody.appendChild(row);
1269 * Updates any new/changed/deleted notes on the server
1271 this.updateLiNotes = function(li, newNote) {
1277 notes = li.lineitem_notes().filter(
1279 if(note.ischanged() || note.isnew() || note.isdeleted())
1285 if(notes.length == 0) return;
1286 progressDialog.show();
1288 fieldmapper.standardRequest(
1289 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
1291 params : [this.authtoken, notes],
1292 onresponse : function(r) {
1293 var resp = openils.Util.readResponse(r);
1298 // remove the old changed notes
1300 dojo.forEach(li.lineitem_notes(),
1302 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
1306 li.lineitem_notes(list);
1309 progressDialog.hide();
1310 self.updateLiNotesCount(li);
1311 self.drawLiNotes(li);
1315 progressDialog.update(resp);
1316 var newnote = resp.note;
1318 if(!newnote.isdeleted()) {
1319 newnote.isnew(false);
1320 newnote.ischanged(false);
1321 li.lineitem_notes().push(newnote);
1328 this.updateLiPrice = function(input, li) {
1330 var price = input.value;
1331 if(Number(price) == Number(li.estimated_unit_price())) return;
1333 fieldmapper.standardRequest(
1334 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
1335 { async : false, // redundant w/ timeout
1337 params : [this.authtoken, li.id(), price],
1338 oncomplete : function(r) {
1339 openils.Util.readResponse(r);
1340 li.estimated_unit_price(price); // update local copy
1343 * If this is a PO and every visible lineitem has a price,
1344 * check again to see if this PO can be activated. Note that
1345 * every visible lineitem having a price does not guarantee it can
1346 * be activated, which is why we still make the call. Having a price
1347 * set for every visiable lineitem is just the lowest barrier to entry.
1350 var priceNodes = dojo.query('[name=price]', dojo.byId('acq-lit-tbody'));
1352 dojo.forEach(priceNodes, function(node) { if (node.value == '') allSet = false});
1353 if (allSet) checkCouldActivatePo();
1360 this.removeLineitem = function(liId) {
1361 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
1362 delete this.liCache[liId];
1363 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
1366 this.drawInfo = function(liId) {
1367 this.focusLineitem = liId;
1368 if (!this._isRelatedViewer) {
1369 var d = dojo.byId("acq-lit-info-related");
1370 if (!this.relCache[liId]) {
1371 fieldmapper.standardRequest(
1374 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
1377 "params": [openils.User.authtoken, liId],
1378 "onresponse": function(r) {
1379 self.relCache[liId] = openils.Util.readResponse(r);
1380 nodeByName("related_number", d).innerHTML =
1381 self.relCache[liId];
1383 self.relCache[liId] >1 ? "show" : "hide"
1389 nodeByName("related_number", d).innerHTML = this.relCache[liId];
1390 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
1395 openils.acq.Lineitem.fetchAttrDefs(
1397 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
1402 this.toggleInlineCopies = function() {
1403 // if any inline copies are not displayed,
1404 // display them all otherwise, hide them all.
1406 var displayAll = false;
1408 for (var liId in this.liCache) {
1409 if (!this.inlineCopiesVisible(liId)) {
1415 for (var liId in this.liCache) {
1416 var row = dojo.byId('acq-inline-copies-row-' + liId);
1418 if (!row || row._hidden) {
1419 this.drawInlineCopies(liId);
1421 } else { // hide all
1423 // drawInlineCopies() on a visible row will hide it.
1424 this.drawInlineCopies(liId);
1431 this.inlineCopiesVisible = function(liId) {
1432 var row = dojo.byId('acq-inline-copies-row-' + liId);
1433 return (row && !row._hidden);
1436 this.refreshInlineCopies = function(all, reFetch) {
1438 var liIds = this.inlineCopiesNeedingRefresh;
1439 if (all) liIds = openils.Util.objectProperties(liCache);
1440 liIds.forEach(function(liId) {
1441 if (self.inlineCopiesVisible(liId)) {
1442 self.drawInlineCopies(liId, reFetch); // hide
1443 self.drawInlineCopies(liId, reFetch); // re-draw
1448 // draw inline copy table. if the table is
1449 // already visible, hide the table as-is
1450 // reFetch forces a retrieval of the lineitem and
1451 // copies from the server. otherwise the locally
1452 // cached version of each is used.
1453 this.drawInlineCopies = function(liId, reFetch) {
1456 // find or create the row where the inline copies table will live
1457 var containerRow = dojo.byId('acq-inline-copies-row-' + liId);
1458 var liRow = dojo.query('[li=' + liId + ']')[0];
1460 if (!containerRow) {
1462 // build the inline copies container row and add it to
1463 // the DOM directly after the primary lineitem row
1465 containerRow = self.inlineCopyContainer.cloneNode(true);
1466 containerRow.id = 'acq-inline-copies-row-' + liId;
1468 if (liRow.nextSibling) {
1469 self.tbody.insertBefore(containerRow, liRow.nextSibling);
1471 self.tbody.appendChild(containerRow);
1476 // toggle the visible state
1477 containerRow._hidden = !containerRow._hidden;
1478 openils.Util.toggle(containerRow, 'table-row');
1480 if (containerRow._hidden) return; // hide only
1483 var handler = function(li) {
1485 var tbody = dojo.query(
1486 '[name=acq-li-inline-copies-tbody]',
1489 // reset the table before adding copy rows
1490 while (tbody.childNodes[0])
1491 tbody.removeChild(tbody.childNodes[0]);
1493 if(li.lineitem_details().length == 0) {
1495 self.inlineNoCopies.cloneNode(true));
1496 return; // no copies to show
1499 // add a row to the inline copy table for each copy
1500 dojo.forEach(li.lineitem_details(),
1502 var row = self.inlineCopyTemplate.cloneNode(true);
1503 tbody.appendChild(row);
1504 self.addInlineCopy(li, copy, row);
1509 this._fetchLineitem(liId, handler, reFetch);
1512 /** Draw read-only copy widgets for inline copies */
1513 this.addInlineCopy = function(li, copy, row) {
1516 dojo.forEach(liDetailFields,
1519 var widget = new openils.widget.AutoFieldWidget({
1522 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1523 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1524 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1526 parentNode : dojo.query('[name=' + field + ']', row)[0],
1535 /* For a given list of lineitem ids, build a list of full lineitems
1536 * re-using the fetching logic that is otherwise typical to use in this
1539 * If we've already got a lineitem in the cache, just use that.
1541 * Once we've built a list of lineitems, call callback(thatlist).
1543 this.fetchLineitemsById = function(id_list, callback) {
1544 var total = id_list.length;
1545 var result_list = [];
1547 var inner = function(li) {
1548 result_list.push(li)
1550 callback(result_list);
1553 id_list.forEach(function(id) { self._fetchLineitem(id, inner); });
1556 this._fetchLineitem = function(liId, handler, force) {
1558 var li = this.liCache[liId];
1559 if(li && li.marc() && li.lineitem_details() && !force)
1562 fieldmapper.standardRequest(
1563 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
1566 params: [self.authtoken, liId, {
1568 flesh_cancel_reason: true,
1569 flesh_li_details: true,
1571 flesh_fund_debit: true }],
1573 oncomplete: function(r) {
1574 var li = openils.Util.readResponse(r);
1575 self.liCache[liId] = li;
1582 this._drawInfo = function(li) {
1584 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
1586 if(li.eg_bib_id()) {
1587 openils.Util.hide('acq-lit-marc-order-record-label');
1588 openils.Util.hide(acqLitEditOrderMarc.domNode);
1589 openils.Util.show('acq-lit-marc-real-record-label');
1591 openils.Util.show('acq-lit-marc-order-record-label');
1592 openils.Util.show(acqLitEditOrderMarc.domNode);
1593 openils.Util.hide('acq-lit-marc-real-record-label');
1596 this.drawMarcHTML(li);
1597 this.infoTbody = dojo.byId('acq-lit-info-tbody');
1600 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
1601 while(this.infoTbody.childNodes[0])
1602 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
1604 for(var i = 0; i < li.attributes().length; i++) {
1605 var attr = li.attributes()[i];
1606 var row = this.infoRow.cloneNode(true);
1608 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
1609 var name = openils.acq.Lineitem.attrDefs[type].filter(
1611 return (a.code() == attr.attr_name());
1613 ).pop().description();
1615 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
1616 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
1617 this.infoTbody.appendChild(row);
1620 if (!this._isRelatedViewer) {
1621 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
1622 oilsBasePath + "/acq/lineitem/related/" + li.id();
1625 // if a top scroll point is defined, jump up to it here
1626 var node = dojo.byId('oils-scroll-to-top');
1627 if (node) dijit.scrollIntoView(node);
1630 this.generateMakeRecTab = function(bib_id,default_view, row) {
1634 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
1637 show_nav_buttons : true,
1638 show_print_button : true,
1639 opac_url : xulG.url_prefix('opac_rdetail|' + bib_id),
1640 default_view : default_view
1644 if(row) nodeByName("action_none", row).selected = true;
1648 this.drawMarcHTML = function(li) {
1649 var params = [null, true, li.marc()];
1651 params = [li.eg_bib_id(), true];
1653 fieldmapper.standardRequest(
1654 ['open-ils.search', 'open-ils.search.biblio.record.html'],
1657 oncomplete: function(r) {
1658 dojo.byId('acq-lit-marc-div').innerHTML =
1659 openils.Util.readResponse(r);
1665 this.drawCopies = function(liId, force_fetch) {
1666 this.focusLineitem = liId;
1667 if (typeof force_fetch == "undefined")
1668 force_fetch = false;
1670 var cgi = new openils.CGI();
1671 var source = cgi.param('source');
1672 if (source && source.match(/invoice/)) {
1673 // got here from the invoice page, show the 'return-to-invoice' button
1674 var cgi = new openils.CGI({url : source});
1675 cgi.param('focus_li', liId);
1676 openils.Util.show(dojo.byId('acq-lit-copies-back-to-invoice-button-wrapper'), 'inline');
1677 var button = dojo.byId('acq-lit-copies-back-to-invoice-button');
1678 button.onclick = function() { location.href = cgi.url() };
1681 openils.acq.Lineitem.fetchAndRender(liId, {},
1682 function(li, html) {
1683 dojo.byId('acq-lit-copies-li-summary').innerHTML = html;
1687 this.show('copies');
1689 this.copyCache = {};
1690 this.copyWidgetCache = {};
1691 this.oldCopyWidgetCache = {};
1692 this.virtDfaCounts = {};
1693 this.realDfaCache = {};
1696 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
1697 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
1698 acqLitCopyCountInput.attr('value', '0');
1700 while(this.copyTbody.childNodes[0])
1701 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
1703 this._drawBatchCopyWidgets();
1705 this._drawDistribApplied(liId);
1707 this._fetchDistribFormulas(
1709 openils.acq.Lineitem.fetchAttrDefs(
1711 self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch);
1718 this._saveDistribAppliedTemplates = function() {
1719 if (!this._appliedDistribTemplate) {
1720 this._appliedDistribTemplate =
1721 dojo.byId("acq-lit-distrib-applied-tbody").
1722 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
1723 dojo.attr(this._appliedDistribTemplate, "id");
1727 this._drawDistribApplied = function(liId) {
1728 /* Build this table while hidden to prevent rendering artifacts */
1729 openils.Util.hide("acq-lit-distrib-applied-tbody");
1731 this._saveDistribAppliedTemplates();
1733 /* Remove any rows in the table from previous populations */
1734 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
1735 forEach(dojo.destroy);
1737 /* Unregister all dijits previously created (for some reason this isn't
1738 * covered by the above destroy calls). */
1739 dijit.registry.forEach(
1740 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
1743 /* Populate the table with our liId */
1745 fieldmapper.standardRequest(
1747 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
1750 "params": [self.authtoken, liId],
1751 "onresponse": function(r) {
1752 var dfa = openils.Util.readResponse(r);
1755 self.realDfaCache[dfa.id()] = dfa;
1756 self._drawDistribAppliedUnit(dfa);
1759 "oncomplete": function() {
1760 /* Reveal built table */
1763 "acq-lit-distrib-applied-tbody", "table-row-group"
1771 this._drawDistribAppliedUnit = function(dfa) {
1772 var new_row = false;
1773 var row = dojo.query(
1774 'tr[formula="' + dfa.formula().id() + '"]',
1775 "acq-lit-distrib-applied-tbody"
1780 row = dojo.clone(this._appliedDistribTemplate);
1781 dojo.attr(row, "formula", dfa.formula().id());
1782 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
1785 var td = dojo.query("td", row)[0];
1787 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1788 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1791 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1793 new dijit.form.Button(
1795 "onClick": function() {
1796 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1797 self.deleteDfa(dfa);
1800 /* XXX I /cannot/ make the following work in as a CSS class
1801 * for some reason. So frustrating... */
1802 "style": function(id) {
1804 "font-weight: bold; color: #c00;" :
1806 }(dfa.id()) + "margin: 0 6px;display: inline;"
1807 }, "dfa-button-" + dfa.id()
1811 "connectId": ["dfa-button-" + dfa.id()],
1812 "label": dojo.string.substitute(
1813 localeStrings.DFA_TIP, dfa.id() > 0 ? [
1814 openils.User.formalName(dfa.creator()),
1815 dojo.date.locale.format(
1816 dojo.date.stamp.fromISOString(dfa.create_time()),
1817 {"formatLength":"short"}
1819 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
1821 }, "dfa-tip-" + dfa.id()
1825 this.deleteDfa = function(dfa) {
1826 if (dfa.id() > 0) { /* real */
1827 this.pcrud.eliminate(
1830 "oncomplete": function() {
1831 self._removeDistribApplied(dfa.id());
1832 delete self.realDfaCache[dfa.id()];
1836 } else { /* virtual */
1837 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
1838 this.virtDfaCounts[dfa.formula().id()] = 0;
1839 /* hasn't been saved yet, so no need to do anything server side */
1840 this._removeDistribApplied(dfa.id());
1845 this._removeDistribApplied = function(dfaId) {
1846 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
1847 dijit.registry.forEach(
1848 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
1850 this._removeDistribAppliedEmptyRows();
1853 this._removeAllDistribAppliedVirtual = function() {
1854 /* Unregister dijits */
1855 dijit.registry.forEach(
1856 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
1858 this._removeDistribAppliedEmptyRows();
1861 this._removeDistribAppliedEmptyRows = function() {
1862 /* Remove any rows with no DFA at all */
1863 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
1865 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
1871 * Insert a new row into the distribution formula selection form
1873 this._addDistribFormulaRow = function() {
1876 if (!self.distribForms) {
1877 // no formulas, hide the form
1878 openils.Util.hide('acq-lit-distrib-formula-table');
1882 if(!this.distribFormulaTemplate)
1883 this.distribFormulaTemplate =
1884 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
1886 var row = this.distribFormulaTemplate.cloneNode(true);
1887 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
1889 this.dfSelector = new dijit.form.FilteringSelect(
1890 {"labelAttr": "dynLabel", "labelType": "html"},
1891 nodeByName("selector", row)
1893 this._updateFormulaStore();
1894 this.dfSelector.fetchProperties =
1895 {"sort": [{"attribute": "use_count", "descending": true}]};
1897 var apply = new dijit.form.Button(
1898 {"label": localeStrings.APPLY},
1899 nodeByName('set_button', row)
1902 var reset = new dijit.form.Button(
1903 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
1904 nodeByName("reset_button", row)
1907 dojo.connect(apply, 'onClick',
1909 var form_id = self.dfSelector.attr("value");
1910 if(!form_id) return;
1911 self._applyDistribFormula(form_id);
1912 reset.attr("disabled", false);
1916 dojo.connect(reset, 'onClick',
1918 self.restoreCopyFieldsBeforeDF();
1919 self.virtDfaCounts = {};
1920 self.virtDfaId = -1;
1922 self._updateFormulaStore();
1923 self._removeAllDistribAppliedVirtual();
1924 reset.attr("disabled", "true");
1931 * Applies a distrib formula to the current set of copies
1933 this._applyDistribFormula = function(formula) {
1934 if(!formula) return;
1936 formula = this.distribForms.filter(
1937 function(form) { return form.id() == formula; }
1940 var copyRows = dojo.query('tr', self.copyTbody);
1942 if (this.dfeOffset >= copyRows.length) {
1943 alert(localeStrings.OUT_OF_COPIES);
1947 var entries_applied = 0;
1949 var rowIndex = this.dfeOffset;
1950 rowIndex < copyRows.length;
1954 var row = copyRows[rowIndex];
1955 var copy_id = row.getAttribute('copy_id');
1956 var copyWidgets = this.copyWidgetCache[copy_id];
1957 var entryIndex = this.dfeOffset;
1960 // find the correct entry for the current row
1961 dojo.forEach(formula.entries(),
1964 entryIndex += e.item_count();
1965 if(entryIndex > rowIndex)
1973 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
1974 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
1977 this.saveCopyFieldsBeforeDF(copy_id);
1978 this._copy_fields_for_acqdf.forEach(
1980 if(entry[field]()) {
1981 copyWidgets[field].attr('value', (entry[field]()));
1988 if (entries_applied) {
1989 this.virtDfaCounts[formula.id()] =
1990 ++(this.virtDfaCounts[formula.id()]) || 1;
1991 this._updateFormulaStore();
1992 this._drawDistribAppliedUnit(
1994 var dfa = new acqdfa();
1995 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
1998 this.dfeOffset += entries_applied;
2003 * This function updates the DF store for the dropdown so that use_counts
2004 * can reflect DF applications from this session before they're saved
2007 this._updateFormulaStore = function() {
2008 this.dfSelector.store = new dojo.data.ItemFileReadStore(
2010 "data": self._labelFormulasWithCounts(
2011 acqdf.toStoreData(self.distribForms)
2017 this.saveCopyFieldsBeforeDF = function(copy_id) {
2019 if (!this.oldCopyWidgetCache[copy_id]) {
2020 var copyWidgets = this.copyWidgetCache[copy_id];
2022 this.oldCopyWidgetCache[copy_id] = {};
2023 this._copy_fields_for_acqdf.forEach(
2025 self.oldCopyWidgetCache[copy_id][f] =
2026 copyWidgets[f].attr("value");
2032 this.restoreCopyFieldsBeforeDF = function() {
2034 for (var copy_id in this.oldCopyWidgetCache) {
2035 this._copy_fields_for_acqdf.forEach(
2037 self.copyWidgetCache[copy_id][f].attr(
2038 "value", self.oldCopyWidgetCache[copy_id][f]
2045 this._labelFormulasWithCounts = function(store_data) {
2046 for (var key in store_data.items) {
2047 var obj = store_data.items[key];
2048 obj.use_count = Number(obj.use_count); /* needed for sorting */
2050 if (this.virtDfaCounts[obj.id])
2051 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
2053 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
2054 obj.use_count + "]</span> " + obj.name;
2060 * This method formerly would not refetch the DF formulas if they'd been
2061 * loaded already, but now it always re-fetches, since use_count changes.
2063 /** TODO: port distrib-formula selector to autofieldwidget+pcrud/dojo store */
2064 this._fetchDistribFormulas = function(onload) {
2065 fieldmapper.standardRequest(
2067 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
2070 "params": [openils.User.authtoken, 0, 500],
2071 "oncomplete": function(r) {
2072 self.distribForms = openils.Util.readResponse(r);
2073 if(!self.distribForms || self.distribForms.length == 0) {
2074 self.distribForms = [];
2076 self._addDistribFormulaRow();
2083 this._drawBatchCopyWidgets = function() {
2084 var row = this.copyBatchRow;
2085 dojo.forEach(liDetailBatchFields,
2087 if(self.copyBatchRowDrawn) {
2088 self.copyBatchWidgets[field].attr('value', null);
2090 var args = self.afwCopyFieldArgs(field, "CREATE_PICKLIST");
2091 args.parentNode = dojo.query('[name='+field+']', row)[0];
2093 var widget = new openils.widget.AutoFieldWidget(args);
2096 if (field == "fund" && w.store)
2097 self._ensureCSSFundClasses(w.store);
2098 self.copyBatchWidgets[field] = w;
2101 if (field == "fund") {
2103 widget.widget, "onChange", function(val) {
2104 self._updateFundSelectorStyle(widget, val);
2111 this.copyBatchRowDrawn = true;
2114 this.batchCopyUpdate = function() {
2116 for(var k in this.copyWidgetCache) {
2117 var cache = this.copyWidgetCache[k];
2118 dojo.forEach(liDetailBatchFields, function(f) {
2119 var newval = self.copyBatchWidgets[f].attr('value');
2120 if(newval) cache[f].attr('value', newval);
2125 this._drawCopies = function(li) {
2128 // this button sets the total number of copies for a given lineitem
2129 acqLitAddCopyCount.onClick = function() {
2130 var count = acqLitCopyCountInput.attr('value');
2133 while(self.copyCount() < count)
2136 // delete rows if necessary
2137 var diff = self.copyCount() - count;
2139 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
2140 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
2141 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
2143 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2149 if(li.lineitem_details().length > 0) {
2150 dojo.forEach(li.lineitem_details(),
2152 self.addCopy(li, copy);
2160 this.copyCount = function() {
2162 for(var id in this.copyCache) {
2163 if(!this.copyCache[id].isdeleted())
2169 this.virtCopyId = -1;
2170 this.addCopy = function(li, copy) {
2171 var row = this.copyRow.cloneNode(true);
2172 this.copyTbody.appendChild(row);
2176 copy = new fieldmapper.acqlid();
2178 copy.id(this.virtCopyId--);
2179 copy.lineitem(li.id());
2182 this.copyCache[copy.id()] = copy;
2183 row.setAttribute('copy_id', copy.id());
2184 self.copyWidgetCache[copy.id()] = {};
2186 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2188 var rcvr = copy.receiver();
2190 if (!userCache[rcvr]) {
2191 if(rcvr == openils.User.user.id()) {
2192 userCache[rcvr] = openils.User.user;
2194 userCache[rcvr] = fieldmapper.standardRequest(
2195 ['open-ils.actor', 'open-ils.actor.user.retrieve'],
2196 {params: [openils.User.authtoken, rcvr]}
2200 dojo.query('[name=receiver]', row)[0].innerHTML = userCache[rcvr].usrname();
2203 dojo.forEach(liDetailFields,
2206 if (field == "fund") {
2207 searchFilter = (copy.fund() ?
2208 {"-or": {"active": "t", "id": copy.fund()}} :
2211 searchFilter = null;
2214 var readOnly = false;
2216 // TODO: Add support for changing the owning_lib after real copies have been made.
2217 // owning_lib is order data as much as its item data
2218 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
2222 // TODO: add support for changing the fund after debits have been created
2223 // Note: invoicing allows the change
2224 if(copy.fund_debit() && field == 'fund') {
2229 var widget = new openils.widget.AutoFieldWidget({
2232 labelFormat : (field == 'fund') ? fundLabelFormat : null,
2233 searchFormat : (field == 'fund') ? fundSearchFormat : null,
2234 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
2235 searchFilter : searchFilter,
2236 noCache: (field == "fund"),
2238 parentNode : dojo.query('[name='+field+']', row)[0],
2239 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2240 readOnly : readOnly,
2241 orgDefaultsToWs : true
2245 // make sure we capture the value from any async widgets
2248 if (field == "fund" && w.store)
2249 self._ensureCSSFundClasses(w.store);
2252 copy[field](ww.getFormattedValue())
2254 self.copyWidgetCache[copy.id()][field] = w;
2256 dojo.connect(w, 'onChange',
2258 if (field == "fund")
2259 self._updateFundSelectorStyle(widget, val);
2261 if (!readOnly && (copy.isnew() || val != copy[field]())) {
2262 // prevent setting ischanged() automatically on widget load for existing copies
2263 copy[field](widget.getFormattedValue())
2264 copy.ischanged(true);
2273 this.updateLidState(copy, row);
2276 this._ensureCSSFundClass = function(id) {
2277 if (!this.fundStyleSheet) {
2279 "style", {"type": "text/css"},
2280 document.getElementsByTagName("head")[0], "last"
2282 this.fundStyleSheet = document.styleSheets[
2283 document.styleSheets.length - 1
2287 var cn = "fund_" + id;
2288 if (!this.haveFundClass[cn]) {
2289 fieldmapper.standardRequest(
2290 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
2292 "params": [openils.User.authtoken, id],
2294 "oncomplete": function(r) {
2295 r = openils.Util.readResponse(r);
2296 self.fundBalanceState[id] = r;
2298 if (r[0] /* stop */)
2299 style = fundStyles.stop;
2300 else if (r[1] /* warning */)
2301 style = fundStyles.warning;
2302 self.fundStyleSheet.insertRule(
2303 "." + cn + " { " + style + " }",
2304 self.fundStyleSheet.cssRules.length
2306 self.haveFundClass[cn] = true;
2313 this._ensureCSSFundClasses = function(store) {
2315 "query": {"id": "*"},
2316 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
2320 this._updateFundSelectorStyle = function(widget, fund_id) {
2321 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
2322 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
2325 this.updateLidState = function(copy, row) {
2328 if (typeof(row) == "undefined") {
2329 row = dojo.query('tr[copy_id="' + copy.id() + '"]', this.copyTbody)[0];
2333 var recv_link = nodeByName("receive", row);
2334 var unrecv_link = nodeByName("unreceive", row);
2335 var del_link = nodeByName("delete", row);
2336 var cxl_link = nodeByName("cancel", row);
2337 var claim_link = nodeByName("claim", row);
2338 var cxl_reason_link = nodeByName("cancel_reason", row);
2340 // by default, hide all the actions
2341 openils.Util.hide(del_link.parentNode);
2342 openils.Util.hide(recv_link);
2343 openils.Util.hide(unrecv_link);
2344 openils.Util.hide(cxl_link);
2345 openils.Util.hide(claim_link);
2346 openils.Util.hide(cxl_reason_link);
2348 if (copy.id() > 0) { // real copies (LIDs)
2350 if (copy.cancel_reason()) {
2352 /* --------- cancelled -------------------------- */
2354 /* XXX the following may leak memory in a long lived table:
2355 * dijits may not get destroyed... not positive. revisit. */
2356 var holds_reason = dojo.create(
2358 "style": "border-bottom: 1px dashed #000;",
2359 "innerHTML": "Cancelled" /* XXX [sic] and i18n */
2360 }, cxl_reason_link, "only"
2364 "label": "<em>" + copy.cancel_reason().label() +
2365 "</em><br />" + copy.cancel_reason().description(),
2366 "connectId": [holds_reason]
2367 }, dojo.create("span", null, cxl_reason_link, "last")
2369 openils.Util.show(cxl_reason_link, "inline");
2371 } else if (copy.recv_time()) {
2373 /* --------- received -------------------------- */
2375 openils.Util.show(unrecv_link, "inline");
2376 unrecv_link.onclick = function() {
2377 if (confirm(localeStrings.UNRECEIVE_LID))
2378 self.issueReceive(copy, /* rollback */ true);
2381 } else if (this.liCache[copy.lineitem()].state() == 'on-order') {
2383 /* --------- on order -------------------------- */
2385 openils.Util.show(recv_link, 'inline');
2386 openils.Util.show(cxl_link, "inline");
2388 recv_link.onclick = function() {
2389 if (self.checkLiAlerts(copy.lineitem()))
2390 self.issueReceive(copy);
2393 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2397 /* --------- pre-order copies -------------------------- */
2399 del_link.onclick = function() { self.deleteCopy(row) };
2400 openils.Util.show(del_link.parentNode);
2406 /* --------- virtual copies -------------------------- */
2408 del_link.onclick = function() { self.deleteCopy(row) };
2409 openils.Util.show(del_link.parentNode);
2413 this.cancelLid = function(lid_id) {
2414 lidCancelDialog._lid_id = lid_id;
2415 openils.Util.show(lidCancelDialog.domNode.parentNode);
2416 lidCancelDialog.show();
2417 if (!lidCancelDialog._prepared) {
2418 var widget = new openils.widget.AutoFieldWidget({
2419 "fmField": "cancel_reason",
2420 "fmClass": "acqlid",
2421 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
2422 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2427 acqLidCancelButton.onClick = function() {
2428 if (w.attr("value")) {
2429 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
2431 lidCancelDialog._lid_id,
2435 lidCancelDialog.hide();
2438 lidCancelDialog._prepared = true;
2444 this._cancelLid = function(lid_id, reason) {
2445 fieldmapper.standardRequest(
2446 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
2447 "params": [openils.User.authtoken, lid_id, reason],
2449 "onresponse": function(r) {
2450 if (r = openils.Util.readResponse(r)) {
2452 for (var id in r.lid) {
2453 /* actually this should only iterate once */
2454 self.copyCache[id].cancel_reason(
2455 r.lid[id].cancel_reason
2457 self.updateLidState(self.copyCache[id]);
2466 this._confirmAlert = function(li, lin) {
2468 dojo.string.substitute(
2469 localeStrings.CONFIRM_LI_ALERT, [
2470 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2471 "title", "lineitem_marc_attr_definition"
2473 /* XXX it's really better add a parameter and to adjust
2474 * the format string rather than do this concatenation
2475 * here, but if someone wants this for 2.2 in a hurry,
2476 * we can sidestep the problem of updating the strings
2477 * while the translators are working. */
2479 aou.findOrgUnit(lin.alert_text().owning_lib()).shortname() +
2481 lin.alert_text().code()
2483 lin.alert_text().description() || "",
2490 this.checkLiAlerts = function(li_id) {
2491 var li = this.liCache[li_id];
2493 var alert_notes = li.lineitem_notes().filter(
2494 function(o) { return Boolean(o.alert_text()); }
2497 /* this is _intentionally_ not done in a call to forEach() ... */
2498 for (var i = 0; i < alert_notes.length; i++) {
2499 if (this.noteAcks[alert_notes[i].id()])
2501 else if (!this._confirmAlert(li, alert_notes[i]))
2504 this.noteAcks[alert_notes[i].id()] = true;
2510 this.deleteCopy = function(row) {
2511 var copy = this.copyCache[row.getAttribute('copy_id')];
2512 copy.isdeleted(true);
2514 delete this.copyCache[copy.id()];
2515 this.copyTbody.removeChild(row);
2518 this._virtDfaCountsAsList = function() {
2520 for (var key in this.virtDfaCounts) {
2521 for (var i = 0; i < this.virtDfaCounts[key]; i++)
2527 this.confirmBreachedCopyFunds = function(copies) {
2528 var stop = 0, warning = 0;
2532 var state = self.fundBalanceState[o.fund()];
2533 if (state[0] /* stop */)
2535 else if (state[1] /* warning */)
2542 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
2543 } else if (warning) {
2544 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
2549 this.saveCopyChanges = function(liId) {
2555 for(var id in this.copyCache) {
2556 var c = this.copyCache[id];
2557 if(!c.isdeleted()) total++;
2558 if(c.isnew() || c.ischanged() || c.isdeleted()) {
2559 if(c.id() < 0) c.id(null);
2565 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
2568 if (copies.length > 0) {
2569 if (!this.confirmBreachedCopyFunds(copies))
2572 if (typeof(this._copy_count_cb) == "function")
2573 this._copy_count_cb(liId, total);
2575 openils.Util.show("acq-lit-update-copies-progress");
2576 fieldmapper.standardRequest(
2577 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
2579 params: [openils.User.authtoken, copies],
2580 onresponse: function(r) {
2581 var res = openils.Util.readResponse(r);
2582 litUpdateCopiesProgress.update(res);
2584 oncomplete: function() {
2585 self.drawCopies(liId, true /* force_fetch */);
2586 openils.Util.hide("acq-lit-update-copies-progress");
2592 var dfa_list = this._virtDfaCountsAsList();
2593 if (dfa_list.length > 0) {
2594 fieldmapper.standardRequest(
2596 "open-ils.acq.distribution_formula.record_application"],
2599 "params": [openils.User.authtoken, dfa_list, liId],
2600 "onresponse": function(r) {
2601 var res = openils.Util.readResponse(r);
2602 if (res && res.length < dfa_list.length)
2603 alert(localeStrings.DFA_NOT_ALL);
2607 this.virtDfaCounts = {};
2610 if (this.inlineCopiesNeedingRefresh.indexOf(liId) < 0)
2611 this.inlineCopiesNeedingRefresh.push(liId);
2614 this._updateCreatePoPrepayCheckbox = function(prepay) {
2615 var prepay = openils.Util.isTrue(prepay);
2616 this._prepayRequiredByVendor = prepay;
2617 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
2620 this._confirmPoPrepaySituation = function() {
2621 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
2622 if (want_prepay != this._prepayRequiredByVendor) {
2625 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
2626 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
2633 this.applySelectedLiAction = function(action) {
2637 case 'delete_selected':
2638 this._deleteLiList(self.getSelected());
2641 case 'add_to_order':
2642 addToPoDialog._get_li = dojo.hitch(
2644 function() { return this.getSelected(false, null, true); }
2646 addToPoDialog.show();
2649 case 'create_order':
2650 this._loadPOSelect();
2651 acqLitPoCreateDialog.show();
2654 case 'save_picklist':
2655 acqLitSavePlDialog.show();
2658 case 'selector_ready':
2660 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
2661 acqLitChangeLiStateDialog.show();
2669 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
2672 case 'batch_create_invoice':
2673 this.batchCreateInvoice();
2676 case 'batch_link_invoice':
2677 this.batchLinkInvoice();
2680 case 'receive_lineitems':
2681 this.receiveSelectedLineitems();
2684 case 'rollback_receive_lineitems':
2685 this.rollbackReceiveLineitems();
2688 case 'create_assets':
2689 this.showAssetCreator();
2692 case 'export_attr_list':
2693 this.chooseExportAttr();
2696 case 'batch_apply_funds':
2697 this.applyBatchLiFunds();
2700 case 'add_brief_record':
2702 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
2704 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
2708 case "cancel_lineitems":
2709 this.maybeCancelLineitems();
2712 case "apply_claim_policy":
2713 var li_list = this.getSelected();
2714 this.claimPolicyPicker.attr("value", null);
2715 liClaimPolicyDialog.show();
2716 liClaimPolicySave.onClick = function() {
2717 self.changeClaimPolicy(
2719 self.claimPolicyPicker.attr("value"),
2723 self.setClaimPolicyControl(li);
2724 self.reconsiderClaimControl(li);
2727 liClaimPolicyDialog.hide();
2735 this.changeClaimPolicy = function(li_list, value, callback) {
2737 function(li) { li.claim_policy(value); }
2739 fieldmapper.standardRequest(
2740 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
2741 "params": [openils.User.authtoken, li_list],
2743 "oncomplete": function(r) {
2744 r = openils.Util.readResponse(r);
2745 if (callback) callback(r);
2751 this.showAssetCreator = function(onAssetsCreated) {
2752 if(!this.isPO) return;
2755 // first, let's see if this PO has any LI's that need to be merged/imported
2756 self.pcrud.search('jub', {purchase_order : this.isPO, eg_bib_id : null}, {
2758 oncomplete : function(r) {
2759 var resp = openils.Util.readResponse(r);
2760 if (resp && resp.length) {
2761 // PO has some non-linked jubs.
2763 self.show('asset-creator');
2764 if(!self.vlAgent.loaded)
2765 self.vlAgent.init();
2767 dojo.connect(assetCreatorButton, 'onClick',
2768 function() { self.createAssets(onAssetsCreated) });
2772 // all jubs linked, move on to asset creation
2773 self.createAssets(onAssetsCreated, true);
2779 this.createAssets = function(onAssetsCreated, noVl) {
2780 this.show('acq-lit-progress-numbers');
2782 var vlArgs = (noVl) ? {} : {vandelay : this.vlAgent.values()};
2783 fieldmapper.standardRequest(
2784 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
2786 params: [this.authtoken, this.isPO, vlArgs],
2787 onresponse: function(r) {
2788 var resp = openils.Util.readResponse(r);
2789 self._updateProgressNumbers(resp, !Boolean(onAssetsCreated), onAssetsCreated);
2795 this.maybeCancelLineitems = function() {
2796 openils.Util.show("acq-lit-cancel-reason", "inline");
2797 if (!acqLitCancelLineitemsButton._prepared) {
2798 var widget = new openils.widget.AutoFieldWidget({
2799 "fmField": "cancel_reason",
2801 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
2802 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2807 acqLitCancelLineitemsButton.onClick = function() {
2808 if (w.attr("value")) {
2809 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
2810 self._cancelLineitems(w.attr("value"));
2812 openils.Util.hide("acq-lit-cancel-reason");
2815 acqLitCancelLineitemsButton._prepared = true;
2821 this._cancelLineitems = function(reason) {
2822 var id_list = this.getSelected().map(function(o) { return o.id(); });
2823 fieldmapper.standardRequest(
2824 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
2825 "params": [openils.User.authtoken, id_list, reason],
2827 "onresponse": function(r) {
2828 if (r = openils.Util.readResponse(r)) {
2830 for (var id in r.li) {
2831 self.liCache[id].state(r.li[id].state);
2832 self.liCache[id].cancel_reason(
2833 r.li[id].cancel_reason
2835 self.updateLiState(self.liCache[id]);
2838 if (r.lid && self.copyCache) {
2839 for (var id in r.lid) {
2840 if (self.copyCache[id]) {
2841 self.copyCache[id].cancel_reason(
2842 r.lid[id].cancel_reason
2844 self.updateLidState(self.copyCache[id]);
2854 this.chooseExportAttr = function() {
2855 if (!acqLitExportAttrSelector._li_setup) {
2857 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
2859 "data": acqlimad.toStoreData(
2861 "acqlimad", {"code": li_exportable_attrs}
2866 acqLitExportAttrSelector.setValue();
2867 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
2868 acqLitExportAttrSelector._li_setup = true;
2870 openils.Util.show("acq-lit-export-attr-holder", "inline");
2873 this.exportAttrList = function() {
2874 var attr_def = acqLitExportAttrSelector.item;
2875 var li_list = this.getSelected();
2876 var value_list = li_list.map(
2878 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2879 attr_def.code, "lineitem_marc_attr_definition"
2882 ).filter(function(attr) { return Boolean(attr); });
2884 if (value_list.length > 0) {
2885 if (value_list.length < li_list.length) {
2887 dojo.string.substitute(
2888 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
2895 openils.XUL.contentToFileSaveDialog(
2896 value_list.join("\n"),
2897 localeStrings.EXPORT_SAVE_DIALOG_TITLE
2903 alert(dojo.string.substitute(
2904 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
2908 openils.Util.hide("acq-lit-export-attr-holder");
2911 this.printPO = function() {
2912 if(!this.isPO) return;
2913 progressDialog.show(true);
2914 fieldmapper.standardRequest(
2915 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
2917 params: [this.authtoken, this.isPO, 'html'],
2918 oncomplete: function(r) {
2919 progressDialog.hide();
2920 var evt = openils.Util.readResponse(r);
2921 if(evt && evt.template_output()) {
2922 openils.Util.printHtmlString(evt.template_output().data());
2929 this.batchCreateInvoice = function() {
2930 var liIds = this.getSelected(false, null, true /* id_list */)
2931 if (!liIds.length) return;
2932 var path = oilsBasePath + '/acq/invoice/view?create=1';
2933 dojo.forEach(liIds, function(li, idx) { path += '&attach_li=' + li });
2934 if (openils.XUL.isXUL())
2935 openils.XUL.newTabEasy(path, localeStrings.NEW_INVOICE, null, true);
2937 location.href = path;
2940 this.batchLinkInvoice = function(create) {
2941 var liIds = this.getSelected(false, null, true /* id_list */)
2942 if (!liIds.length) return;
2943 if (!self.invoiceLinkDialogManager) {
2944 self.invoiceLinkDialogManager =
2945 new InvoiceLinkDialogManager("li");
2947 self.invoiceLinkDialogManager.target = liIds;
2948 acqLitLinkInvoiceDialog.show();
2951 this.receiveSelectedLineitems = function() {
2952 var li_list = this.getSelected();
2954 if (!li_list.length) {
2955 alert(localeStrings.NO_LI_GENERAL);
2959 for (var i = 0; i < li_list.length; i++) {
2960 var li = li_list[i];
2962 if (li.state() != "received" &&
2963 !this.checkLiAlerts(li.id())) return;
2966 this.show('acq-lit-progress-numbers');
2969 fieldmapper.standardRequest(
2970 ['open-ils.acq', 'open-ils.acq.lineitem.receive.batch'],
2974 li_list.map(function(li) { return li.id(); })
2976 onresponse : function(r) {
2977 var resp = openils.Util.readResponse(r);
2978 self._updateProgressNumbers(resp, true);
2984 this.issueReceive = function(obj, rollback) {
2986 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
2988 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
2990 progressDialog.show(true);
2991 fieldmapper.standardRequest(
2992 ["open-ils.acq", method], {
2994 "params": [this.authtoken, obj.id()],
2995 "onresponse": function(r) {
2996 if (r = openils.Util.readResponse(r)) {
2997 self.fetchClaimInfo(
2998 part == "lineitem" ? obj.id() : obj.lineitem(),
3000 function() { self.handleReceive(r); }
3002 progressDialog.hide();
3010 * Handles the responses from receive and rollback ML calls.
3012 this.handleReceive = function(resp) {
3015 for (var li_id in resp.li) {
3016 for (var key in resp.li[li_id])
3017 self.liCache[li_id][key](resp.li[li_id][key]);
3018 self.updateLiState(self.liCache[li_id]);
3022 if (typeof(self.poUpdateCallback) == "function")
3023 self.poUpdateCallback(resp.po);
3026 for (var lid_id in resp.lid) {
3027 for (var key in resp.lid[lid_id])
3028 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
3029 self.updateLidState(self.copyCache[lid_id]);
3035 this.rollbackReceiveLineitems = function() {
3036 var li_id_list = this.getSelected(false, null, true);
3037 if (!li_id_list.length) {
3038 alert(localeStrings.NO_LI_GENERAL);
3042 if (!confirm(localeStrings.ROLLBACK_LI_RECEIVE_CONFIRM)) return;
3044 this.show('acq-lit-progress-numbers');
3047 fieldmapper.standardRequest(
3048 ['open-ils.acq', 'open-ils.acq.lineitem.receive.rollback.batch'],
3050 params: [this.authtoken, li_id_list],
3051 onresponse : function(r) {
3052 var resp = openils.Util.readResponse(r);
3053 self._updateProgressNumbers(resp, true);
3059 this._updateProgressNumbers = function(resp, reloadOnComplete, onComplete) {
3060 this.vlAgent.handleResponse(resp,
3061 function(resp, res) {
3062 if(reloadOnComplete)
3063 location.href = location.href;
3065 onComplete(resp, res);
3071 this._createPO = function(fields) {
3072 var wantall = (fields.create_from == "all");
3074 /* If we're a picklist or purchase order already and the user wants
3075 * all lineitems, we might have pages' worth of lineitems haven't all
3076 * been loaded yet, so getSelected() won't find them. The server,
3077 * however, should know about all our lineitems, so let's ask the
3078 * server for a complete list.
3083 true, function(list) {
3084 self._createPOFromLineitems(fields, list);
3085 }, /* id_list */ true
3088 this._createPOFromLineitems(fields, this.getSelected(false, null, true /* id_list */));
3092 this._createPOFromLineitems = function(fields, selected) {
3093 if (selected.length == 0) return;
3096 var po = new fieldmapper.acqpo();
3097 po.provider(this.createPoProviderSelector.attr("value"));
3098 po.ordering_agency(this.createPoAgencySelector.attr("value"));
3099 po.prepayment_required(fields.prepayment_required[0] ? true : false);
3101 // if we're creating assets, delay the asset creation
3102 // until after the PO is created. This will allow us to
3103 // use showAssetCreator() directly.
3105 fieldmapper.standardRequest(
3106 ["open-ils.acq", "open-ils.acq.purchase_order.create"],
3109 openils.User.authtoken,
3110 po, {lineitems : selected}
3112 onresponse : function(r) {
3113 var resp = openils.Util.readResponse(r);
3114 if (resp.complete) {
3115 // self.isPO is needed for showAssetCreator();
3116 self.isPO = resp.purchase_order.id();
3117 var redir = oilsBasePath + "/acq/po/view/" + self.isPO;
3118 if (fields.create_assets[0]) {
3119 self.showAssetCreator(
3120 function() {location.href = redir}
3123 location.href = redir;
3132 this.batchFundWidget = null;
3134 this.applyBatchLiFunds = function() {
3136 var liIds = this.getSelected().map(function(li) { return li.id(); });
3137 if(liIds.length == 0) return; // warn?
3140 batchFundUpdateDialog.show();
3142 if(!this.batchFundWidget) {
3143 this.batchFundWidget = new openils.widget.AutoFieldWidget({
3145 selfReference : true,
3146 labelFormat : fundLabelFormat,
3147 searchFormat : fundSearchFormat,
3148 searchFilter : {"active": "t"},
3149 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
3150 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
3151 dijitArgs : { "required": true, "labelType": "html" },
3154 this.batchFundWidget.build();
3157 dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
3158 dojo.connect(batchFundUpdateSubmit, 'onClick',
3161 // TODO: call .dry_run first to test thresholds
3162 fieldmapper.standardRequest(
3163 ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
3166 openils.User.authtoken,
3168 self.batchFundWidget.widget.attr('value')
3170 oncomplete : function(r) {
3171 var resp = openils.Util.readResponse(r);
3173 location.href = location.href;
3182 this._deleteLiList = function(list, idx) {
3183 if(idx == null) idx = 0;
3184 if(idx >= list.length) return;
3189 if (this.isPO && (li.state() == "on-order" || li.state() == "received")) {
3190 /* It makes little sense to delete a lineitem from a PO that has
3191 * already been marked 'on-order'. Especially if EDI is in use,
3192 * such a purchase order will probably have already been shipped
3193 * off to a vendor, and mucking with it at this point could leave
3194 * your data in a bad state that doesn't jive with reality.
3196 * I could see making this restriction even firmer.
3198 * I could also see adjusting the li state comparisons, extending
3199 * the comparison to the PO's state, and/or providing functions
3200 * that house the logic for comparing states in a single location.
3202 * Yes, this will be really annoying if you have selected a lot
3203 * of lineitems to cancel that have been ordered. You'll get a
3204 * confirm dialog for each one.
3207 if (!confirm(localeStrings.DEL_LI_FROM_PO)) {
3208 self._deleteLiList(list, ++idx); /* move on to next in list */
3213 fieldmapper.standardRequest(
3215 this.isPO ? 'open-ils.acq.purchase_order.lineitem.delete' : 'open-ils.acq.picklist.lineitem.delete'],
3217 params: [openils.User.authtoken, liId],
3218 oncomplete: function(r) {
3219 self.removeLineitem(liId);
3220 self._deleteLiList(list, ++idx);
3226 this.editOrderMarc = function(li) {
3228 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
3229 to true in about:config */
3231 if(openils.XUL.isXUL()) {
3232 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul','','chrome');
3234 win = window.open('/xul/server/cat/marcedit.xul','','chrome');
3238 record : {marc : li.marc(), "rtype": "bre"},
3240 label: 'Save Record', // XXX I18N
3241 func: function(xmlString) {
3243 fieldmapper.standardRequest(
3244 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
3246 params: [openils.User.authtoken, li],
3247 oncomplete: function(r) {
3248 openils.Util.readResponse(r);
3250 self.drawInfo(li.id())
3256 'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
3257 'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
3261 this._savePl = function(values) {
3263 (values.which == 'all'),
3264 function(list) { self._savePlFromLineitems(values, list); }
3268 this._savePlFromLineitems = function(values, selected) {
3269 openils.Util.show("acq-lit-generic-progress");
3271 if(values.new_name) {
3272 openils.acq.Picklist.create(
3273 {name: values.new_name},
3279 oilsBasePath + "/acq/picklist/view/" + id;
3284 } else if(values.existing_pl) {
3285 // update lineitems to use an existing picklist
3287 values.existing_pl, selected, 0,
3290 oilsBasePath + "/acq/picklist/view/" +
3297 this._updateLiState = function(values, state) {
3298 progressDialog.show(true);
3300 (values.which == 'all'),
3302 self._updateLiStateFromLineitems(values, state, list);
3307 this._updateLiStateFromLineitems = function(values, state, selected) {
3308 if(!selected.length) return;
3309 dojo.forEach(selected, function(li) {li.state(state);});
3310 self._updateLiList(null, selected, 0,
3311 // TODO consider inline updates for efficiency
3312 function() { location.href = location.href }
3316 this._updateLiList = function(pl, list, idx, oncomplete) {
3317 if(idx >= list.length) return oncomplete();
3319 if(pl != null) li.picklist(pl);
3320 litGenericProgress.update({maximum: list.length, progress: idx});
3321 new openils.acq.Lineitem({lineitem:li}).update(
3323 self._updateLiList(pl, list, ++idx, oncomplete);
3328 this._loadPOSelect = function() {
3329 if (!this.createPoProviderSelector) {
3330 var widget = new openils.widget.AutoFieldWidget({
3331 "fmField": "provider",
3333 "searchFilter": {"active": "t"},
3334 "parentNode": dojo.byId("acq-lit-po-provider"),
3336 "onChange": function() {
3338 self._updateCreatePoPrepayCheckbox(
3339 this.item.prepayment_required()
3345 widget.build(function(w) { self.createPoProviderSelector = w; });
3348 if (!this.createPoAgencySelector) {
3349 var widget = new openils.widget.AutoFieldWidget({
3350 "fmField": "ordering_agency",
3352 "parentNode": dojo.byId("acq-lit-po-agency"),
3353 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3355 widget.build(function(w) { self.createPoAgencySelector = w; });
3359 this.showRealCopyEditUI = function(li) {
3364 this._fetchLineitem(li.id(),
3366 li = self.liCache[li.id()] = fullLi;
3370 id : li.lineitem_details().map(
3371 function(item) { return item.eg_copy_id() }
3375 oncomplete : function(r) {
3377 var r_list = openils.Util.readResponse( r );
3378 for (var i = 0; i < r_list.length; i++) {
3379 var copy = r_list[i];
3380 var volId = copy.call_number();
3381 var volume = self.volCache[volId];
3383 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
3385 copy.call_number(volume);
3386 copyList.push(copy);
3389 xulG.volume_item_creator( { 'existing_copies' : copyList } );
3392 alert('error in oncomplete: ' + E);
3401 this.drawBibFinder = function(li) {
3404 var liWrapper = new openils.acq.Lineitem({lineitem:li});
3407 ['isbn', 'upc', 'issn', 'title', 'author'],
3409 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
3411 if(field == 'title' || field == 'author') {
3412 query += field +':' + val + ' ';
3414 query += 'identifier|' + field + ':' + val + ' ';
3421 oilsBasePath + '/acq/lineitem/findbib?query=' + escape(query),
3422 '', 'resizable,scrollbars=1,chrome');
3424 win.window.recordFound = function(bibId) {
3427 var attrs = li.attributes();
3428 li.attributes(null);
3429 li.eg_bib_id(bibId);
3431 fieldmapper.standardRequest(
3432 ["open-ils.acq", "open-ils.acq.lineitem.update"],
3434 "params": [openils.User.authtoken, li],
3436 "oncomplete": function(r) {
3437 if(openils.Util.readResponse(r)) {
3438 location.href = location.href;