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;"
48 * We're not using 'approved' today, but there is API support for it.
49 * I believe it's been replaced by "order-ready".
50 * LIs go new => selector-ready => order-ready/approved => pending-order =>
51 * on-order => received. 'cancelled' can pop up anywhere.
54 var li_pre_po_states = ["new", "selector-ready", "order-ready", "approved"];
55 var li_post_po_states = ["pending-order", "on-order", "received"];
56 // i.e. not-canceled ("cancelled") lineitems
57 var li_active_states = li_pre_po_states.concat(li_post_po_states);
59 function AcqLiTable() {
66 this.haveFundClass = {}
67 this.fundBalanceState = {};
68 this.realDfaCache = {};
69 this.virtDfaCounts = {};
72 this.claimEligibleLidByLi = {};
73 this.claimEligibleLid = {};
74 this.toggleState = false;
75 this.tbody = dojo.byId('acq-lit-tbody');
78 this.authtoken = openils.User.authtoken;
79 this.pcrud = new openils.PermaCrud();
80 this.rowTemplate = this.tbody.removeChild(dojo.byId('acq-lit-row'));
81 this.copyTbody = dojo.byId('acq-lit-li-details-tbody');
82 this.copyRow = this.copyTbody.removeChild(dojo.byId('acq-lit-li-details-row'));
83 this.copyBatchRow = dojo.byId('acq-lit-li-details-batch-row');
84 this.copyBatchWidgets = {};
85 this.liNotesTbody = dojo.byId('acq-lit-notes-tbody');
86 this.liNotesRow = this.liNotesTbody.removeChild(dojo.byId('acq-lit-notes-row'));
87 this.realCopiesTbody = dojo.byId('acq-lit-real-copies-tbody');
88 this.realCopiesRow = this.realCopiesTbody.removeChild(dojo.byId('acq-lit-real-copies-row'));
89 this._copy_fields_for_acqdf = ['owning_lib', 'location', 'fund', 'circ_modifier', 'collection_code'];
90 this.skipInitialEligibilityCheck = false;
91 this.claimDialog = new ClaimDialogManager(
92 liClaimDialog, finalClaimDialog, this.claimEligibleLidByLi,
93 function(li) { /* callback that fires when claims are made */
94 self.fetchClaimInfo(li.id(), /* force update */ true);
97 this.vlAgent = new VLAgent();
99 if (dojo.byId('acq-lit-apply-idents')) {
100 dojo.byId('acq-lit-apply-idents').onclick = function() {
101 self.applyOrderIdentValues();
105 this.focusLineitem = new openils.CGI().param('focus_li');
107 // capture the inline copy display wrapper and row template
108 this.inlineCopyContainer =
109 this.tbody.removeChild(dojo.byId('acq-inline-copies-row'));
111 '[name=acq-li-inline-copies-tbody]', this.inlineCopyContainer)[0];
112 this.inlineCopyTemplate = tb.removeChild(
113 dojo.query('[name=acq-li-inline-copies-template]', tb)[0]);
114 this.inlineNoCopies = tb.removeChild(
115 dojo.query('[name=acq-li-inline-copies-none]', tb)[0]);
117 // list of LI IDs that should be refreshed at next display time
118 this.inlineCopiesNeedingRefresh = [];
120 dojo.byId("acq-lit-li-actions-selector").onchange = function() {
121 self.applySelectedLiAction(this.options[this.selectedIndex].value);
122 this.selectedIndex = 0;
125 acqLitCreatePoSubmit.onClick = function() {
126 if (!self.createPoProviderSelector.attr("value") ||
127 !self.createPoAgencySelector.attr("value")) {
128 alert(localeStrings.CREATE_PO_INVALID);
130 } else if (self._confirmPoPrepaySituation()) {
131 acqLitPoCreateDialog.hide();
132 self._createPO(acqLitPoCreateDialog.getValues());
138 acqLitSavePlButton.onClick = function() {
139 acqLitSavePlDialog.hide();
140 self._savePl(acqLitSavePlDialog.getValues());
143 acqLitCancelLiStateButton.onClick = function() {
144 acqLitChangeLiStateDialog.hide();
146 acqLitSaveLiStateButton.onClick = function() {
147 acqLitChangeLiStateDialog.hide();
148 var state = acqLitChangeLiStateDialog.attr('state');
149 var state_filter = ['new'];
150 if (state == 'order-ready')
151 state_filter.push('selector-ready');
153 acqLitChangeLiStateDialog.getValues(), state, state_filter);
157 dojo.byId('acq-lit-select-toggle').onclick = function(){self.toggleSelect()};
158 dojo.byId('acq-inline-copies-toggle').onclick = function(){self.toggleInlineCopies()};
159 dojo.byId('acq-lit-info-back-button').onclick = function(){self.show('list')};
160 dojo.byId('acq-lit-copies-back-button').onclick = function(){self.show('list')};
161 dojo.byId('acq-lit-notes-back-button').onclick = function(){self.show('list')};
162 dojo.byId('acq-lit-real-copies-back-button').onclick = function(){self.show('list')};
164 this.afwCopyFieldArgs = function(field, perms) {
168 "labelFormat": (field == 'fund') ? fundLabelFormat : null,
169 "searchFormat": (field == 'fund') ? fundSearchFormat : null,
170 "searchFilter": (field == 'fund') ? {"active": "t"} : null,
171 "orgLimitPerms": [perms],
174 "labelType": (field == "fund") ? "html" : null
176 "noCache": (field == "fund"),
181 /* This is the "new" batch updater that sits atop all lineitems. It does
182 * use this.afwCopyFieldArgs() to borrow a little common code from the
183 * "old" batch updater atop the copy details view. */
184 this.initBatchUpdater = function(disabled_fields) {
185 openils.Util.show("acq-batch-update", "table");
187 if (!dojo.isArray(disabled_fields)) disabled_fields = [];
189 /* Note that this will directly contain dijits, not the AutoWidget
191 this.batchUpdateWidgets = {};
193 this.batchUpdateWidgets.item_count = new dijit.form.TextBox(
195 "style": {"width": "3em"},
197 dojo.indexOf(disabled_fields, "item_count") != -1
203 (new openils.widget.AutoFieldWidget({
205 "selfReference": true,
206 "dijitArgs": { "required": false },
208 "parentNode": "acq-bu-distribution_formula"
211 dojo.style(w.domNode, {"width": "12em"});
212 /* dijitArgs to AutoFieldWidget won't work for 'disabled' */
215 dojo.indexOf(disabled_fields, "distribution_formula") != -1
217 self.batchUpdateWidgets.distribution_formula = w;
222 ["owning_lib","location","collection_code","circ_modifier","fund"],
224 var args = self.afwCopyFieldArgs(field,"CREATE_PURCHASE_ORDER");
225 args.parentNode = dojo.byId("acq-bu-" + field);
227 (new openils.widget.AutoFieldWidget(args)).build(
229 if (field == "fund") {
231 w, "onChange", function(val) {
232 self._updateFundSelectorStyle(aw, val);
236 self._ensureCSSFundClasses(w.store);
239 dojo.style(w.domNode, {"width": "10em"});
242 dojo.indexOf(disabled_fields, field) != -1
244 self.batchUpdateWidgets[field] = w;
250 acqBatchUpdateApply.onClick = function() {
251 var li_id_list = self.getSelected(false, null, true /* id list */);
252 if (!li_id_list.length) {
253 alert(localeStrings.NO_LI_TO_UPDATE);
257 progressDialog.show(true);
258 progressDialog.attr("title", localeStrings.LI_BATCH_UPDATE);
259 progressDialog.update({"maximum": li_id_list.length,"progress": 0});
263 var params = [ self.authtoken, {"lineitems": li_id_list},
264 self.batchUpdateChanges(), self.batchUpdateFormula() ];
265 console.log("batch update params: " + dojo.toJson(params));
267 fieldmapper.standardRequest(
268 ["open-ils.acq", "open-ils.acq.lineitem.batch_update"], {
271 "onresponse": function(r) {
272 if ((r = openils.Util.readResponse(r))) { // assignment
273 progressDialog.update({"progress": ++count});
275 progressDialog.hide();
276 progressDialog.attr("title", "");
279 "oncomplete": function() {
280 /* XXX Is the last call to onresponse guaranteed to
281 * finish before oncomplete is fired? */
282 if (count != li_id_list.length) {
283 console.error("lineitem batch update operation failed");
284 progressDialog.hide();
285 progressDialog.attr("title", "");
287 location.href = location.href;
295 this.batchUpdateChanges = function() {
299 openils.Util.objectProperties(this.batchUpdateWidgets),
301 if (k == "distribution_formula") return; /* handled elsewhere */
302 if (self.batchUpdateWidgets[k].attr("disabled")) return;
304 /* It's important that a value of "" should mean that a field
305 * doesn't get used in the arguments to the batch updater API,
306 * but 0 should mean an actual 0. */
307 var value = self.batchUpdateWidgets[k].attr("value");
316 this.batchUpdateFormula = function() {
317 if (this.batchUpdateWidgets.distribution_formula.attr("disabled")) {
321 this.batchUpdateWidgets.distribution_formula.attr("value") ||
327 this.reset = function(keep_selectors) {
328 while(self.tbody.childNodes[0])
329 self.tbody.removeChild(self.tbody.childNodes[0]);
337 this.setNext = function(handler) {
338 var link = dojo.byId('acq-lit-next');
340 dojo.style(link, 'visibility', 'visible');
341 link.onclick = handler;
343 dojo.style(link, 'visibility', 'hidden');
347 this.setPrev = function(handler) {
348 var link = dojo.byId('acq-lit-prev');
350 dojo.style(link, 'visibility', 'visible');
351 link.onclick = handler;
353 dojo.style(link, 'visibility', 'hidden');
357 this.enableActionsDropdownOptions = function(mask) {
358 /* 'mask' is probably a misnomer the way I'm using it, but it needs to
359 * be one of pl,po,ao,gs,vp, or fs. */
360 dojo.query("option", "acq-lit-li-actions-selector").forEach(
362 var opt_mask = dojo.attr(option, "mask");
364 /* For each <option> element, an empty or non-existent mask
365 * attribute, a mask attribute of "*", or a mask attribute that
366 * matches this method's argument should result in that
367 * option's being enabled. */
369 option, "disabled", !(
372 opt_mask.search(mask) != -1
380 * Ensures this.focusLineitem is in view and causes a brief
381 * border around the lineitem to come to life then fade.
383 this.focusLi = function() {
384 if (!this.focusLineitem) return;
386 // set during addLineitem()
387 var node = dojo.byId('li-title-ref-' + this.focusLineitem);
389 // LI may not yet be rendered
392 // prevent numerous re-focuses
393 this.focusLineitem = null;
395 // causes the full row to be visible
396 dijit.scrollIntoView(node);
399 dojo.query('[attr=title]', node)[0].focus();
401 dojo.require('dojox.fx');
405 dojox.fx.highlight({color : '#BB4433', node : node, duration : 2000}).play();
410 this.show = function(div) {
411 openils.Util.hide('acq-lit-table-div');
412 openils.Util.hide('acq-lit-info-div');
413 openils.Util.hide('acq-lit-li-details');
414 openils.Util.hide('acq-lit-notes-div');
415 openils.Util.hide('acq-lit-real-copies-div');
416 openils.Util.hide('acq-lit-asset-creator');
419 openils.Util.show('acq-lit-table-div');
421 this.refreshInlineCopies();
424 openils.Util.show('acq-lit-info-div');
427 openils.Util.show('acq-lit-li-details');
430 openils.Util.show('acq-lit-real-copies-div');
433 openils.Util.show('acq-lit-notes-div');
435 case 'asset-creator':
436 openils.Util.show('acq-lit-asset-creator');
440 openils.Util.show(div);
444 this.hide = function() {
448 this.toggleSelect = function() {
450 dojo.forEach(self.selectors, function(i){i.checked = false});
452 dojo.forEach(self.selectors, function(i){i.checked = true});
453 self.toggleState = !self.toggleState;
457 this.getAll = function(callback, id_only, state) {
458 /* For some uses of the li table, we may not really know about "all"
459 * the lineitems that the user thinks we know about. If we're a paged
460 * picklist, for example, we only know about the lineitems we've
461 * displayed, but not necessarily all the lineitems on the picklist.
462 * So we reach out to pcrud to inform us.
463 * state: string/array. only lineitems in one of these states are
464 * included in the final result set. Not currently supported for
468 var oncomplete = function(r) {
469 var id_list = openils.Util.readResponse(r);
473 self.fetchLineitemsById(id_list, callback);
477 var search = {"picklist": this.isPL};
478 if (state) search.state = state;
481 "id_list": true, /* sic, even if id_only */
483 "oncomplete": oncomplete
487 } else if (this.isPO) {
488 var search = {"purchase_order": this.isPO};
489 if (state) search.state = state;
494 "oncomplete": oncomplete
498 } else if (this.isUni && this.pager) {
499 this.pager.getAllLineitemIDs(oncomplete);
503 /* If execution reaches this point, we don't need or can't perform
504 * any special tricks to find out the "real" list of "all" lineitems
505 * in this context, so we fall back to the old method.
507 callback(this.getSelected(true, null, id_only, state));
510 /** @param all If true, assume all are selected */
511 this.getSelected = function(
513 callback /* If you want a "good" idea of "all" lineitems, you must
514 provide a callback that accepts an array parameter, rather than
515 relying on the return value of this method itself. */,
519 console.log("getSelected states = " + state);
521 return this.getAll(callback, id_only, state);
523 var indices = {}; /* use to uniqify. needed in paging situations. */
524 dojo.forEach(this.selectors,
527 indices[i.parentNode.parentNode.getAttribute('li')] = true;
531 var result = openils.Util.objectProperties(indices);
533 // caller provided a lineitem state filter. remove IDs for lineitems
534 // not in the selected state.
537 if (!dojo.isArray(state)) state = [state];
538 dojo.forEach(result, function(liId) {
539 console.log('filter LI state ' + self.liCache[liId].state());
540 if (state.indexOf(self.liCache[liId].state()) >= 0)
547 result = result.map(function(liId) { return self.liCache[liId]; });
555 this.setRowAttr = function(td, liWrapper, field, type) {
556 var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
557 td.appendChild(document.createTextNode(val));
560 this.setClaimPolicyControl = function(li, row) {
561 if (!self._claimPolicyPickerLoading) {
562 self._claimPolicyPickerLoading = true;
564 new openils.widget.AutoFieldWidget({
565 "parentNode": "acq-lit-li-claim-policy",
567 "selfReference": true,
568 "dijitArgs": {"required": true}
570 function(w) { self.claimPolicyPicker = w; }
574 /* dojox.timing.doLater() is the best thing ever. Resource not yet
575 * ready? Just repeat my whole method when it is. */
576 if (dojox.timing.doLater(self.claimPolicyPicker)) {
580 row = self._findLiRow(li);
582 if (li.claim_policy()) {
583 /* This Dojo data dance is necessary to get a whole fieldmapper
584 * object based on a claim policy ID, since we alreay have the
585 * widget thing loaded with all that data, and can thereby
586 * avoid another request to the server. */
587 self.claimPolicyPicker.store.fetchItemByIdentity({
588 "identity": li.claim_policy(),
589 "onItem": function(a) {
590 var policy = (new acqclp()).fromStoreItem(a);
591 var span = nodeByName("claim_policy", row);
592 var inner = nodeByName("claim_policy_name", row);
594 openils.Util.show(span, "inline");
595 inner.innerHTML = policy.name();
597 "onError": function(e) {
602 openils.Util.hide(nodeByName("claim_policy", row));
603 nodeByName("claim_policy_name", row).innerHTML = "";
608 this.fetchClaimInfo = function(liId, force, callback, row) {
610 liId, function(full) {
611 self.liCache[full.id()] = full;
612 self.checkClaimEligibility(full, callback, row);
617 // fetch an updated copy of the lineitem
618 // and add it back to the lineitem table
619 this.refreshLineitem = function(li, focus) {
621 this._fetchLineitem(li.id(),
624 self.focusLineitem = li.id();
626 self.focusLineitem = null;
628 var row = dojo.query('[li='+li.id()+']', self.tbody)[0];
629 var nextSibling = row.nextSibling;
630 self.tbody.removeChild(row);
631 self.addLineitem(newLi, false, nextSibling);
637 * Inserts a single lineitem into the growing table of lineitems
638 * @param {Object} li The lineitem object to insert
640 this.addLineitem = function(li, skip_final_placement, nextSibling) {
641 this.liCache[li.id()] = li;
643 // insert the row right away so that final order isn't
644 // dependent on how long subsequent async request take
645 // for a given line item
646 var row = self.rowTemplate.cloneNode(true);
647 if (!skip_final_placement) {
649 // either no nextSibling was provided or it was null
650 // meaning the row was already at the end of the table
651 self.tbody.appendChild(row);
653 self.tbody.insertBefore(row, nextSibling);
657 self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
659 // sort the lineitem notes on edit_time
660 if(!li.lineitem_notes()) li.lineitem_notes([]);
662 var liWrapper = new openils.acq.Lineitem({lineitem:li});
663 row.setAttribute('li', li.id());
664 var tds = dojo.query('[attr]', row);
665 dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
666 dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
668 // so we can scroll to it later
669 dojo.query('[name=bib-info-cell]', row)[0].id = 'li-title-ref-' + li.id();
672 liWrapper.findAttr("isbn", "lineitem_marc_attr_definition") ||
673 liWrapper.findAttr("upc", "lineitem_marc_attr_definition");
675 // XXX media prefix for added content
677 nodeByName("jacket", row).setAttribute(
678 "src", "/opac/extras/ac/jacket/small/" + identifier
682 nodeByName("liid", row).innerHTML += li.id();
685 openils.Util.show(nodeByName('catalog', row), 'inline');
686 nodeByName("catalog_link", row).onclick = this.generateMakeRecTab(li.eg_bib_id());
688 openils.Util.show(nodeByName('link_to_catalog', row), 'inline');
689 nodeByName("link_to_catalog_link", row).onclick = function() { self.drawBibFinder(li) };
692 if (li.queued_record()) {
693 this.pcrud.retrieve('vqbr', li.queued_record(),
695 oncomplete : function(r) {
696 var qrec = openils.Util.readResponse(r);
697 openils.Util.show(nodeByName('queue', row), 'inline');
698 var link = nodeByName("queue_link", row);
699 link.onclick = function() {
700 // open a new tab to the vandelay queue for this record
701 openils.XUL.newTabEasy(
702 oilsBasePath + '/vandelay/vandelay?qtype=bib&qid=' + qrec.queue()
710 nodeByName("worksheet_link", row).href =
711 oilsBasePath + "/acq/lineitem/worksheet/" + li.id() +
712 '?source=' + encodeURIComponent(location.pathname + location.search)
714 nodeByName("show_requests_link", row).href =
715 oilsBasePath + "/acq/picklist/user_request?lineitem=" + li.id() +
716 '?source=' + encodeURIComponent(location.pathname + location.search)
718 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
719 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
720 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
721 dojo.query('[name=expand_inline_copies]', row)[0].onclick =
722 function() {self.drawInlineCopies(li.id())};
724 this.drawOrderIdentSelector(li, row);
726 if (!this.skipInitialEligibilityCheck)
730 function(full) { self.setClaimPolicyControl(full, row) },
734 this.updateLiNotesCount(li, row);
736 // show which PO this lineitem is a member of
737 if(li.purchase_order() && !this.isPO) {
739 this.poCache[li.purchase_order()] =
740 this.poCache[li.purchase_order()] ||
741 fieldmapper.standardRequest(
742 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
744 this.authtoken, li.purchase_order(), {
745 "flesh_price_summary": true,
746 "flesh_provider" : true,
747 "flesh_lineitem_count": true
750 if(po && !this.isMeta) {
751 openils.Util.show(nodeByName('po', row), 'inline');
752 var link = nodeByName('po_link', row);
753 link.setAttribute('href', oilsBasePath +
754 '/acq/po/view/' + li.purchase_order() +
755 '?focus_li=' + li.id() +
756 '&source=' + encodeURIComponent(location.pathname + location.search)
758 link.innerHTML += po.name();
760 openils.Util.show(nodeByName('pro', row), 'inline');
761 link = nodeByName('pro_link', row);
762 link.setAttribute('href', oilsBasePath + '/conify/global/acq/provider/' + po.provider().id())
763 link.innerHTML += po.provider().code();
767 // show which picklist this lineitem is a member of
768 if(li.picklist() && (this.isPO || this.isMeta || this.isUni)) {
770 this.plCache[li.picklist()] =
771 this.plCache[li.picklist()] ||
772 fieldmapper.standardRequest(
773 ['open-ils.acq', 'open-ils.acq.picklist.retrieve.authoritative'],
774 {params: [this.authtoken, li.picklist()]});
776 if (pl.name() == "") {
777 openils.Util.show(nodeByName("bib_origin", row), "inline");
781 openils.Util.show(nodeByName('pl', row), 'inline');
782 var link = nodeByName('pl_link', row);
783 link.setAttribute('href', oilsBasePath +
784 '/acq/picklist/view/' + li.picklist() +
785 '?focus_li=' + li.id() +
786 '&source=' + encodeURIComponent(location.pathname + location.search)
788 link.innerHTML += pl.name();
793 var countNode = nodeByName('count', row);
794 var count = li.item_count() || 0;
795 if (typeof(this._copy_count_cb) == "function") {
796 this._copy_count_cb(li.id(), count);
798 countNode.innerHTML = count;
799 countNode.id = 'acq-lit-copy-count-label-' + li.id();
802 var priceInput = dojo.query('[name=price]', row)[0];
803 priceInput.value = li.estimated_unit_price() || '';
804 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
806 // show either "mark received" or "unreceive" as appropriate
807 this.updateLiState(li, row);
809 if (skip_final_placement) {
813 // the last LI may be rendered after the call to show('list'),
814 // so make sure it's focused if necessary.
815 if (this.focusLineitem == li.id())
819 this._liCountClaims = function(li) {
821 for (var i = 0; i < li.lineitem_details().length; i++)
822 total += li.lineitem_details()[i].claims().length;
826 this._findLiRow = function(li) {
827 return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
830 this.reconsiderClaimControl = function(li, row) {
831 if (!row) row = this._findLiRow(li);
832 var option = nodeByName("action_manage_claims", row);
833 var eligible = this.claimEligibleLidByLi[li.id()].length;
834 var count = this._liCountClaims(li);
836 option.disabled = !(count || eligible);
838 dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
839 option.onclick = function() { self.claimDialog.show(li); };
842 this.clearEligibility = function(li) {
843 this.claimEligibleLidByLi[li.id()] = [];
845 if (li.lineitem_details()) {
846 li.lineitem_details().forEach(
847 function(lid) { delete self.claimEligibleLid[lid.id()]; }
851 if (this.copyCache) {
853 for (var k in this.copyCache) {
854 if (this.copyCache[k].lineitem() == li.id())
858 function(k) { delete self.claimEligibleLid[k]; }
863 this.applyOrderIdentValues = function() {
864 this._identValuesInFlight =
865 openils.Util.objectProperties(this.liCache).length;
866 for (var liId in this.liCache) {
867 this._applyOrderIdentValue(this.liCache[liId]);
871 // returns true if request was sent
872 this._applyOrderIdentValue = function(li, oncomplete) {
875 console.log('applying ident value for lineitem ' + li.id());
878 var row = dojo.query('[li=' + li.id() + ']')[0];
880 // find the selected ident value
881 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
882 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
883 var name = typeSel.options[typeSel.selectedIndex].value;
884 var val = typeSel._cbox.attr('value');
886 console.log("selected ident is " + val);
888 // it differs from the existing ident value, update it
889 var oldIdent = self.getLiOrderIdent(li);
891 oldIdent.attr_name() == name &&
892 oldIdent.attr_value() == val) {
893 console.log('selected ident attr matches existing attr');
894 if (--this._identValuesInFlight == 0) {
895 if (oncomplete) oncomplete(li);
896 else location.href = location.href;
901 // see if the selected ident value is represented
902 // by an existing lineitem attr
905 typeSel._cbox.store.fetch({
906 query : {attr_value : val},
907 onItem : function(item) {
908 console.log('found existing attr for ident value');
909 args.source_attr_id = li.attributes().filter(
910 function(attr) { return attr.id() == item.id[0] }
916 if (!args.source_attr_id) {
917 // user entered new text in the combobox
918 // so we need to create a new attr
919 console.log('creating new ident attr');
920 args.lineitem_id = li.id();
921 args.attr_name = name;
922 args.attr_value = val;
925 fieldmapper.standardRequest(
926 ['open-ils.acq', 'open-ils.acq.lineitem.order_identifier.set'],
928 params : [openils.User.authtoken, args],
929 oncomplete : function() {
930 console.log('order_ident oncomplete');
931 if (--self._identValuesInFlight == 0) {
932 if (oncomplete) oncomplete(li);
933 else location.href = location.href;
935 console.log(self._identValuesInFlight + ' still in flight');
943 this.getLiOrderIdent = function(li) {
944 var attrs = li.attributes();
945 if (!attrs) return null;
949 attr.attr_type() == 'lineitem_local_attr_definition' &&
950 openils.Util.isTrue(attr.order_ident())
956 this.drawOrderIdentSelector = function(li, row) {
958 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
959 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
961 var attrs = li.attributes();
963 // limit to MARC attr defs
964 attrs = attrs.filter(
966 return (attr.attr_type() == 'lineitem_marc_attr_definition');
970 var identAttr = this.getLiOrderIdent(li);
973 // collect the values for each type of identifier
974 // find a reasonable default identifier type to render
978 dojo.forEach(['isbn', 'upc', 'issn'],
981 // collect the values for this attr name
982 values[name] = attrs.filter(
984 return (attr.attr_name() == name)
988 // select a reasonable default name in the type-selector
992 if (identAttr.attr_name() == name)
994 } else if (values[name].length) {
999 dojo.forEach(typeSel.options, function(opt) {
1000 if (opt.value == name) {
1001 opt.selected = true;
1010 function updateOrderIdent(val) {
1011 self._identValuesInFlight = 1;
1012 self._applyOrderIdentValue(
1015 self.refreshLineitem(li);
1020 // replace the ident combobox with a new
1021 // one for the selected ident type
1022 function changeComboBox(sel) {
1023 var name = sel.options[sel.selectedIndex].value;
1025 var td = dojo.query('[name=order_ident_value]', row)[0];
1026 if (td.childNodes[0])
1027 dojo.destroy(td.childNodes[0]);
1029 var store = new dojo.data.ItemFileWriteStore({
1030 data : acqlia.toStoreData(values[name])
1033 var cbox = new dijit.form.ComboBox(
1035 labelAttr : 'attr_value',
1036 searchAttr : 'attr_value'
1038 dojo.create('div', {}, td)
1043 // set the value for the cbox
1044 if (values[name].length) {
1045 var orderIdent = self.getLiOrderIdent(li);
1047 if (orderIdent && orderIdent.attr_name() == name) {
1048 cbox.attr('value', orderIdent.attr_value());
1050 cbox.attr('value', values[name][0].attr_value());
1054 if (!self.orderIdentAllowed)
1055 cbox.attr('disabled', true);
1058 cbox._lineitem = li;
1059 dojo.connect(cbox, 'onChange', updateOrderIdent);
1062 changeComboBox(typeSel); // force the initial draw
1063 typeSel.onchange = function() {changeComboBox(typeSel)};
1066 this.testOrderIdentPerms = function(org, callback) {
1068 new openils.User().getPermOrgList(
1069 'ACQ_SET_LINEITEM_IDENTIFIER',
1071 console.log('found orgs = ' + orgs);
1072 for (var i = 0; i < orgs.length; i++) {
1073 if (Number(orgs[i]) == Number(org)) {
1074 self.orderIdentAllowed = true;
1075 if (callback) callback();
1079 if (callback) callback();
1085 this.checkClaimEligibility = function(li, callback, row) {
1086 /* Assume always eligible, i.e. from this interface we don't care about
1087 * claim eligibility any more. this is where the user would force a
1089 this.clearEligibility(li);
1090 this.claimEligibleLidByLi[li.id()] = li.lineitem_details().map(
1091 function(lid) { return lid.id(); }
1093 li.lineitem_details().forEach(
1094 function(lid) { self.claimEligibleLid[lid.id()] = true; }
1096 this.reconsiderClaimControl(li, row);
1097 if (callback) callback(li);
1099 this.clearEligibility(li);
1100 fieldmapper.standardRequest(
1101 ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
1102 "params": [openils.User.authtoken, {"lineitem": li.id()}],
1104 "onresponse": function(r) {
1105 if (r = openils.Util.readResponse(r)) {
1106 self.claimEligibleLidByLi[li.id()].push(
1109 self.claimEligibleLid[r.lineitem_detail()] = true;
1112 "oncomplete": function() {
1113 self.reconsiderClaimControl(li, row);
1114 if (typeof(callback) == "function")
1122 this.updateLiNotesCount = function(li, row) {
1123 if (!row) row = this._findLiRow(li);
1125 var has_notes = (li.lineitem_notes().filter(
1126 function(o) { return Boolean (o.alert_text()); }
1129 /* U+2691 is the code point for a filled-in flag character */
1130 nodeByName("notes_alert_flag", row).innerHTML =
1131 has_notes ? "⚑" : "";
1132 nodeByName("noteslink", row).style.fontStyle =
1133 has_notes ? "italic" : "normal";
1134 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
1137 /* XXX NOT related to _updateLiState(). rethink */
1138 this.updateLiState = function(li, row) {
1139 if (!row) row = this._findLiRow(li);
1141 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
1142 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
1144 // always allow access to LI history
1145 nodeByName('action_view_history', row).onclick =
1146 function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
1148 /* handle row coloring for based on LI state */
1149 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1150 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
1152 // Expose invoice actions for any lineitem that is linked to a PO
1153 if (li.purchase_order()) {
1154 openils.Util.show(nodeByName("invoices_span", row), "inline");
1155 var link = nodeByName("invoices_link", row);
1156 link.onclick = function() {
1157 openils.XUL.newTabEasy(
1158 oilsBasePath + "/acq/search/unified?so=" +
1159 base64Encode({"jub":[{"id": li.id()}]}) + "&rt=invoice"
1167 * If we haven't fleshed the lineitem_details, default to allowing access to the
1168 * holdings maintenence actions. The alternative is to flesh LIDs on every lineitem,
1169 * but that will add to page render time. Let's see if this will suffice...
1171 var lids = li.lineitem_details();
1173 (lids && !lids.filter(function(lid) { return lid.eg_copy_id() })[0] )) {
1175 actUpdateBarcodes.disabled = false;
1176 actUpdateBarcodes.onclick = function() {
1177 self.showRealCopyEditUI(li);
1178 nodeByName("action_none", row).selected = true;
1180 actHoldingsMaint.disabled = false;
1181 actHoldingsMaint.onclick =
1182 self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
1185 var state_cell = nodeByName("li_state", row);
1187 switch(li.state()) {
1190 if(typeof li.cancel_reason() == "object") {
1191 var holds_state = dojo.create(
1193 "style": "border-bottom: 1px dashed #000;",
1194 "innerHTML": li.state()
1195 }, state_cell, "only"
1199 "label": "<em>" + li.cancel_reason().label() +
1200 "</em><br />" + li.cancel_reason().description(),
1201 "connectId": [holds_state]
1202 }, dojo.create("span", null, state_cell, "last")
1214 state_cell.innerHTML = li.state(); // TODO i18n state labels
1218 this._setAlertStore = function() {
1219 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
1221 "data": acqliat.toStoreData(
1224 "owning_lib": aou.orgNodeTrail(
1225 aou.findOrgUnit(openils.User.user.ws_ou())
1226 ).map(function(o) { return o.id(); })
1232 acqLitAlertAlertText.setValue(); /* make the store "live" */
1233 acqLitAlertAlertText._store_ready = true;
1237 * Draws and shows the lineitem notes pane
1239 this.drawLiNotes = function(li) {
1241 this.focusLineitem = li.id();
1243 if (!acqLitAlertAlertText._store_ready)
1244 this._setAlertStore();
1247 li.lineitem_notes().sort(
1249 if(a.edit_time() < b.edit_time()) return 1;
1255 while(this.liNotesTbody.childNodes[0])
1256 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
1259 acqLitCreateNoteSubmit.onClick = function() {
1260 var value = acqLitCreateNoteText.attr('value');
1262 var note = new fieldmapper.acqlin();
1265 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
1268 note.lineitem(li.id());
1270 self.updateLiNotes(li, note);
1271 acqLitCreateNoteVendorPublic.attr("checked", false);
1272 acqLitCreateNoteText.attr("value", "");
1275 acqLitCreateAlertSubmit.onClick = function() {
1276 if (!acqLitAlertAlertText.item) {
1277 alert(localeStrings.ALERT_UNSELECTED);
1281 var alert_text = new fieldmapper.acqliat().fromStoreItem(
1282 acqLitAlertAlertText.item
1284 var value = acqLitAlertNoteValue.attr("value") || "";
1286 var note = new fieldmapper.acqlin();
1288 note.lineitem(li.id());
1290 note.alert_text(alert_text);
1292 self.updateLiNotes(li, note);
1295 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
1299 * Draws a single lineitem note in the notes pane
1301 this.addLiNote = function(li, note) {
1302 if(note.isdeleted()) return;
1304 var row = self.liNotesRow.cloneNode(true);
1305 nodeByName("value", row).innerHTML = note.value();
1306 var alert_node = nodeByName("alert_code", row);
1307 if (note.alert_text()) {
1308 alert_node.innerHTML = dojo.string.substitute(
1310 aou.findOrgUnit(note.alert_text().owning_lib()).shortname(),
1311 note.alert_text().code()
1314 if (note.alert_text().description()) {
1317 "connectId": [alert_node],
1318 "label": note.alert_text().description()
1319 }, dojo.create("span", null, alert_node, "after")
1324 if (openils.Util.isTrue(note.vendor_public()))
1325 nodeByName("vendor_public", row).innerHTML =
1326 localeStrings.VENDOR_PUBLIC;
1328 nodeByName("delete", row).onclick = function() {
1329 note.isdeleted(true);
1330 self.liNotesTbody.removeChild(row);
1331 self.updateLiNotes(li);
1334 if(note.edit_time()) {
1335 nodeByName("edit_time", row).innerHTML =
1336 dojo.date.locale.format(
1337 dojo.date.stamp.fromISOString(note.edit_time()),
1338 {formatLength:'short'});
1341 self.liNotesTbody.appendChild(row);
1345 * Updates any new/changed/deleted notes on the server
1347 this.updateLiNotes = function(li, newNote) {
1353 notes = li.lineitem_notes().filter(
1355 if(note.ischanged() || note.isnew() || note.isdeleted())
1361 if(notes.length == 0) return;
1362 progressDialog.show();
1364 fieldmapper.standardRequest(
1365 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
1367 params : [this.authtoken, notes],
1368 onresponse : function(r) {
1369 var resp = openils.Util.readResponse(r);
1374 // remove the old changed notes
1376 dojo.forEach(li.lineitem_notes(),
1378 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
1382 li.lineitem_notes(list);
1385 progressDialog.hide();
1386 self.updateLiNotesCount(li);
1387 self.drawLiNotes(li);
1391 progressDialog.update(resp);
1392 var newnote = resp.note;
1394 if(!newnote.isdeleted()) {
1395 newnote.isnew(false);
1396 newnote.ischanged(false);
1397 li.lineitem_notes().push(newnote);
1404 this.updateLiPrice = function(input, li) {
1406 var price = input.value;
1407 if(Number(price) == Number(li.estimated_unit_price())) return;
1409 fieldmapper.standardRequest(
1410 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
1411 { async : false, // redundant w/ timeout
1413 params : [this.authtoken, li.id(), price],
1414 oncomplete : function(r) {
1415 openils.Util.readResponse(r);
1416 li.estimated_unit_price(price); // update local copy
1419 * If this is a PO and every visible lineitem has a price,
1420 * check again to see if this PO can be activated. Note that
1421 * every visible lineitem having a price does not guarantee it can
1422 * be activated, which is why we still make the call. Having a price
1423 * set for every visiable lineitem is just the lowest barrier to entry.
1426 var priceNodes = dojo.query('[name=price]', dojo.byId('acq-lit-tbody'));
1428 dojo.forEach(priceNodes, function(node) { if (node.value == '') allSet = false});
1429 if (allSet) checkCouldActivatePo();
1436 this.removeLineitem = function(liId) {
1437 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
1438 delete this.liCache[liId];
1439 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
1442 this.drawInfo = function(liId) {
1443 this.focusLineitem = liId;
1444 if (!this._isRelatedViewer) {
1445 var d = dojo.byId("acq-lit-info-related");
1446 if (!this.relCache[liId]) {
1447 fieldmapper.standardRequest(
1450 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
1453 "params": [openils.User.authtoken, liId],
1454 "onresponse": function(r) {
1455 self.relCache[liId] = openils.Util.readResponse(r);
1456 nodeByName("related_number", d).innerHTML =
1457 self.relCache[liId];
1459 self.relCache[liId] >1 ? "show" : "hide"
1465 nodeByName("related_number", d).innerHTML = this.relCache[liId];
1466 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
1471 openils.acq.Lineitem.fetchAttrDefs(
1473 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
1478 this.toggleInlineCopies = function() {
1479 // if any inline copies are not displayed,
1480 // display them all otherwise, hide them all.
1482 var displayAll = false;
1484 for (var liId in this.liCache) {
1485 if (!this.inlineCopiesVisible(liId)) {
1491 for (var liId in this.liCache) {
1492 var row = dojo.byId('acq-inline-copies-row-' + liId);
1494 if (!row || row._hidden) {
1495 this.drawInlineCopies(liId);
1497 } else { // hide all
1499 // drawInlineCopies() on a visible row will hide it.
1500 this.drawInlineCopies(liId);
1507 this.inlineCopiesVisible = function(liId) {
1508 var row = dojo.byId('acq-inline-copies-row-' + liId);
1509 return (row && !row._hidden);
1512 this.refreshInlineCopies = function(all, reFetch) {
1514 var liIds = this.inlineCopiesNeedingRefresh;
1515 if (all) liIds = openils.Util.objectProperties(liCache);
1516 liIds.forEach(function(liId) {
1517 if (self.inlineCopiesVisible(liId)) {
1518 self.drawInlineCopies(liId, reFetch); // hide
1519 self.drawInlineCopies(liId, reFetch); // re-draw
1524 // draw inline copy table. if the table is
1525 // already visible, hide the table as-is
1526 // reFetch forces a retrieval of the lineitem and
1527 // copies from the server. otherwise the locally
1528 // cached version of each is used.
1529 this.drawInlineCopies = function(liId, reFetch) {
1532 // find or create the row where the inline copies table will live
1533 var containerRow = dojo.byId('acq-inline-copies-row-' + liId);
1534 var liRow = dojo.query('[li=' + liId + ']')[0];
1536 if (!containerRow) {
1538 // build the inline copies container row and add it to
1539 // the DOM directly after the primary lineitem row
1541 containerRow = self.inlineCopyContainer.cloneNode(true);
1542 containerRow.id = 'acq-inline-copies-row-' + liId;
1544 if (liRow.nextSibling) {
1545 self.tbody.insertBefore(containerRow, liRow.nextSibling);
1547 self.tbody.appendChild(containerRow);
1552 // toggle the visible state
1553 containerRow._hidden = !containerRow._hidden;
1554 openils.Util.toggle(containerRow, 'table-row');
1556 if (containerRow._hidden) return; // hide only
1559 var handler = function(li) {
1561 var tbody = dojo.query(
1562 '[name=acq-li-inline-copies-tbody]',
1565 // reset the table before adding copy rows
1566 while (tbody.childNodes[0])
1567 tbody.removeChild(tbody.childNodes[0]);
1569 if(li.lineitem_details().length == 0) {
1571 self.inlineNoCopies.cloneNode(true));
1572 return; // no copies to show
1575 // add a row to the inline copy table for each copy
1576 dojo.forEach(li.lineitem_details(),
1578 var row = self.inlineCopyTemplate.cloneNode(true);
1579 tbody.appendChild(row);
1580 self.addInlineCopy(li, copy, row);
1585 this._fetchLineitem(liId, handler, reFetch);
1588 /** Draw read-only copy widgets for inline copies */
1589 this.addInlineCopy = function(li, copy, row) {
1592 dojo.forEach(liDetailFields,
1595 var widget = new openils.widget.AutoFieldWidget({
1598 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1599 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1600 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1602 parentNode : dojo.query('[name=' + field + ']', row)[0],
1611 /* For a given list of lineitem ids, build a list of full lineitems
1612 * re-using the fetching logic that is otherwise typical to use in this
1615 * If we've already got a lineitem in the cache, just use that.
1617 * Once we've built a list of lineitems, call callback(thatlist).
1619 this.fetchLineitemsById = function(id_list, callback) {
1620 var total = id_list.length;
1621 var result_list = [];
1623 var inner = function(li) {
1624 result_list.push(li)
1626 callback(result_list);
1629 id_list.forEach(function(id) { self._fetchLineitem(id, inner); });
1632 this._fetchLineitem = function(liId, handler, force) {
1634 var li = this.liCache[liId];
1635 if(li && li.marc() && li.lineitem_details() && !force)
1638 fieldmapper.standardRequest(
1639 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
1642 params: [self.authtoken, liId, {
1644 flesh_cancel_reason: true,
1645 flesh_li_details: true,
1647 flesh_fund_debit: true }],
1649 oncomplete: function(r) {
1650 var li = openils.Util.readResponse(r);
1651 self.liCache[liId] = li;
1658 this._drawInfo = function(li) {
1660 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
1662 if(li.eg_bib_id()) {
1663 openils.Util.hide('acq-lit-marc-order-record-label');
1664 openils.Util.hide(acqLitEditOrderMarc.domNode);
1665 openils.Util.show('acq-lit-marc-real-record-label');
1667 openils.Util.show('acq-lit-marc-order-record-label');
1668 openils.Util.show(acqLitEditOrderMarc.domNode);
1669 openils.Util.hide('acq-lit-marc-real-record-label');
1672 this.drawMarcHTML(li);
1673 this.infoTbody = dojo.byId('acq-lit-info-tbody');
1676 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
1677 while(this.infoTbody.childNodes[0])
1678 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
1680 for(var i = 0; i < li.attributes().length; i++) {
1681 var attr = li.attributes()[i];
1682 var row = this.infoRow.cloneNode(true);
1684 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
1685 var name = openils.acq.Lineitem.attrDefs[type].filter(
1687 return (a.code() == attr.attr_name());
1689 ).pop().description();
1691 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
1692 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
1693 this.infoTbody.appendChild(row);
1696 if (!this._isRelatedViewer) {
1697 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
1698 oilsBasePath + "/acq/lineitem/related/" + li.id();
1701 // if a top scroll point is defined, jump up to it here
1702 var node = dojo.byId('oils-scroll-to-top');
1703 if (node) dijit.scrollIntoView(node);
1706 this.generateMakeRecTab = function(bib_id,default_view, row) {
1710 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
1713 show_nav_buttons : true,
1714 show_print_button : true,
1715 opac_url : xulG.url_prefix('opac_rdetail|' + bib_id),
1716 default_view : default_view
1720 if(row) nodeByName("action_none", row).selected = true;
1724 this.drawMarcHTML = function(li) {
1725 var params = [null, true, li.marc()];
1727 params = [li.eg_bib_id(), true];
1729 fieldmapper.standardRequest(
1730 ['open-ils.search', 'open-ils.search.biblio.record.html'],
1733 oncomplete: function(r) {
1734 dojo.byId('acq-lit-marc-div').innerHTML =
1735 openils.Util.readResponse(r);
1741 this.drawCopies = function(liId, force_fetch) {
1742 this.focusLineitem = liId;
1743 if (typeof force_fetch == "undefined")
1744 force_fetch = false;
1746 var cgi = new openils.CGI();
1747 var source = cgi.param('source');
1748 if (source && source.match(/invoice/)) {
1749 // got here from the invoice page, show the 'return-to-invoice' button
1750 var cgi = new openils.CGI({url : source});
1751 cgi.param('focus_li', liId);
1752 openils.Util.show(dojo.byId('acq-lit-copies-back-to-invoice-button-wrapper'), 'inline');
1753 var button = dojo.byId('acq-lit-copies-back-to-invoice-button');
1754 button.onclick = function() { location.href = cgi.url() };
1757 openils.acq.Lineitem.fetchAndRender(liId, {},
1758 function(li, html) {
1759 dojo.byId('acq-lit-copies-li-summary').innerHTML = html;
1763 this.show('copies');
1765 this.copyCache = {};
1766 this.copyWidgetCache = {};
1767 this.oldCopyWidgetCache = {};
1768 this.virtDfaCounts = {};
1769 this.realDfaCache = {};
1772 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
1773 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
1774 acqLitCopyCountInput.attr('value', '0');
1776 if (this.isPO && PO && PO.order_date()) {
1777 // prevent adding copies to activated POs
1778 acqLitCopyCountInput.attr('disabled', true);
1779 acqLitAddCopyCount.attr('disabled', true);
1782 while(this.copyTbody.childNodes[0])
1783 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
1785 this._drawBatchCopyWidgets();
1787 this._drawDistribApplied(liId);
1789 this._fetchDistribFormulas(
1791 openils.acq.Lineitem.fetchAttrDefs(
1793 self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch);
1800 this._saveDistribAppliedTemplates = function() {
1801 if (!this._appliedDistribTemplate) {
1802 this._appliedDistribTemplate =
1803 dojo.byId("acq-lit-distrib-applied-tbody").
1804 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
1805 dojo.attr(this._appliedDistribTemplate, "id");
1809 this._drawDistribApplied = function(liId) {
1810 /* Build this table while hidden to prevent rendering artifacts */
1811 openils.Util.hide("acq-lit-distrib-applied-tbody");
1813 this._saveDistribAppliedTemplates();
1815 /* Remove any rows in the table from previous populations */
1816 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
1817 forEach(dojo.destroy);
1819 /* Unregister all dijits previously created (for some reason this isn't
1820 * covered by the above destroy calls). */
1821 dijit.registry.forEach(
1822 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
1825 /* Populate the table with our liId */
1827 fieldmapper.standardRequest(
1829 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
1832 "params": [self.authtoken, liId],
1833 "onresponse": function(r) {
1834 var dfa = openils.Util.readResponse(r);
1837 self.realDfaCache[dfa.id()] = dfa;
1838 self._drawDistribAppliedUnit(dfa);
1841 "oncomplete": function() {
1842 /* Reveal built table */
1845 "acq-lit-distrib-applied-tbody", "table-row-group"
1853 this._drawDistribAppliedUnit = function(dfa) {
1854 var new_row = false;
1855 var row = dojo.query(
1856 'tr[formula="' + dfa.formula().id() + '"]',
1857 "acq-lit-distrib-applied-tbody"
1862 row = dojo.clone(this._appliedDistribTemplate);
1863 dojo.attr(row, "formula", dfa.formula().id());
1864 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
1867 var td = dojo.query("td", row)[0];
1869 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1870 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1873 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1875 new dijit.form.Button(
1877 "onClick": function() {
1878 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1879 self.deleteDfa(dfa);
1882 /* XXX I /cannot/ make the following work in as a CSS class
1883 * for some reason. So frustrating... */
1884 "style": function(id) {
1886 "font-weight: bold; color: #c00;" :
1888 }(dfa.id()) + "margin: 0 6px;display: inline;"
1889 }, "dfa-button-" + dfa.id()
1893 "connectId": ["dfa-button-" + dfa.id()],
1894 "label": dojo.string.substitute(
1895 localeStrings.DFA_TIP, dfa.id() > 0 ? [
1896 openils.User.formalName(dfa.creator()),
1897 dojo.date.locale.format(
1898 dojo.date.stamp.fromISOString(dfa.create_time()),
1899 {"formatLength":"short"}
1901 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
1903 }, "dfa-tip-" + dfa.id()
1907 this.deleteDfa = function(dfa) {
1908 if (dfa.id() > 0) { /* real */
1909 this.pcrud.eliminate(
1912 "oncomplete": function() {
1913 self._removeDistribApplied(dfa.id());
1914 delete self.realDfaCache[dfa.id()];
1918 } else { /* virtual */
1919 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
1920 this.virtDfaCounts[dfa.formula().id()] = 0;
1921 /* hasn't been saved yet, so no need to do anything server side */
1922 this._removeDistribApplied(dfa.id());
1927 this._removeDistribApplied = function(dfaId) {
1928 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
1929 dijit.registry.forEach(
1930 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
1932 this._removeDistribAppliedEmptyRows();
1935 this._removeAllDistribAppliedVirtual = function() {
1936 /* Unregister dijits */
1937 dijit.registry.forEach(
1938 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
1940 this._removeDistribAppliedEmptyRows();
1943 this._removeDistribAppliedEmptyRows = function() {
1944 /* Remove any rows with no DFA at all */
1945 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
1947 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
1953 * Insert a new row into the distribution formula selection form
1955 this._addDistribFormulaRow = function() {
1958 if (!self.distribForms) {
1959 // no formulas, hide the form
1960 openils.Util.hide('acq-lit-distrib-formula-table');
1964 if(!this.distribFormulaTemplate)
1965 this.distribFormulaTemplate =
1966 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
1968 var row = this.distribFormulaTemplate.cloneNode(true);
1969 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
1971 this.dfSelector = new dijit.form.FilteringSelect(
1972 {"labelAttr": "dynLabel", "labelType": "html"},
1973 nodeByName("selector", row)
1975 this._updateFormulaStore();
1976 this.dfSelector.fetchProperties =
1977 {"sort": [{"attribute": "use_count", "descending": true}]};
1979 var apply = new dijit.form.Button(
1980 {"label": localeStrings.APPLY},
1981 nodeByName('set_button', row)
1984 var reset = new dijit.form.Button(
1985 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
1986 nodeByName("reset_button", row)
1989 dojo.connect(apply, 'onClick',
1991 var form_id = self.dfSelector.attr("value");
1992 if(!form_id) return;
1993 self._applyDistribFormula(form_id);
1994 reset.attr("disabled", false);
1998 dojo.connect(reset, 'onClick',
2000 self.restoreCopyFieldsBeforeDF();
2001 self.virtDfaCounts = {};
2002 self.virtDfaId = -1;
2004 self._updateFormulaStore();
2005 self._removeAllDistribAppliedVirtual();
2006 reset.attr("disabled", "true");
2013 * Applies a distrib formula to the current set of copies
2015 this._applyDistribFormula = function(formula) {
2016 if(!formula) return;
2018 formula = this.distribForms.filter(
2019 function(form) { return form.id() == formula; }
2022 var copyRows = dojo.query('tr', self.copyTbody);
2024 if (this.dfeOffset >= copyRows.length) {
2025 alert(localeStrings.OUT_OF_COPIES);
2029 var entries_applied = 0;
2031 var rowIndex = this.dfeOffset;
2032 rowIndex < copyRows.length;
2036 var row = copyRows[rowIndex];
2037 var copy_id = row.getAttribute('copy_id');
2038 var copyWidgets = this.copyWidgetCache[copy_id];
2039 var entryIndex = this.dfeOffset;
2042 // find the correct entry for the current row
2043 dojo.forEach(formula.entries(),
2046 entryIndex += e.item_count();
2047 if(entryIndex > rowIndex)
2055 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
2056 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
2059 this.saveCopyFieldsBeforeDF(copy_id);
2060 this._copy_fields_for_acqdf.forEach(
2062 if(entry[field]()) {
2063 copyWidgets[field].attr('value', (entry[field]()));
2070 if (entries_applied) {
2071 this.virtDfaCounts[formula.id()] =
2072 ++(this.virtDfaCounts[formula.id()]) || 1;
2073 this._updateFormulaStore();
2074 this._drawDistribAppliedUnit(
2076 var dfa = new acqdfa();
2077 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
2080 this.dfeOffset += entries_applied;
2085 * This function updates the DF store for the dropdown so that use_counts
2086 * can reflect DF applications from this session before they're saved
2089 this._updateFormulaStore = function() {
2090 this.dfSelector.store = new dojo.data.ItemFileReadStore(
2092 "data": self._labelFormulasWithCounts(
2093 acqdf.toStoreData(self.distribForms)
2099 this.saveCopyFieldsBeforeDF = function(copy_id) {
2101 if (!this.oldCopyWidgetCache[copy_id]) {
2102 var copyWidgets = this.copyWidgetCache[copy_id];
2104 this.oldCopyWidgetCache[copy_id] = {};
2105 this._copy_fields_for_acqdf.forEach(
2107 self.oldCopyWidgetCache[copy_id][f] =
2108 copyWidgets[f].attr("value");
2114 this.restoreCopyFieldsBeforeDF = function() {
2116 for (var copy_id in this.oldCopyWidgetCache) {
2117 this._copy_fields_for_acqdf.forEach(
2119 self.copyWidgetCache[copy_id][f].attr(
2120 "value", self.oldCopyWidgetCache[copy_id][f]
2127 this._labelFormulasWithCounts = function(store_data) {
2128 for (var key in store_data.items) {
2129 var obj = store_data.items[key];
2130 obj.use_count = Number(obj.use_count); /* needed for sorting */
2132 if (this.virtDfaCounts[obj.id])
2133 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
2135 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
2136 obj.use_count + "]</span> " + obj.name;
2142 * This method formerly would not refetch the DF formulas if they'd been
2143 * loaded already, but now it always re-fetches, since use_count changes.
2145 /** TODO: port distrib-formula selector to autofieldwidget+pcrud/dojo store */
2146 this._fetchDistribFormulas = function(onload) {
2147 fieldmapper.standardRequest(
2149 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
2152 "params": [openils.User.authtoken, 0, 500],
2153 "oncomplete": function(r) {
2154 self.distribForms = openils.Util.readResponse(r);
2155 if(!self.distribForms || self.distribForms.length == 0) {
2156 self.distribForms = [];
2158 self._addDistribFormulaRow();
2165 this._drawBatchCopyWidgets = function() {
2166 var row = this.copyBatchRow;
2167 dojo.forEach(liDetailBatchFields,
2169 if(self.copyBatchRowDrawn) {
2170 self.copyBatchWidgets[field].attr('value', null);
2172 var args = self.afwCopyFieldArgs(field, "CREATE_PICKLIST");
2173 args.parentNode = dojo.query('[name='+field+']', row)[0];
2175 var widget = new openils.widget.AutoFieldWidget(args);
2178 if (field == "fund" && w.store)
2179 self._ensureCSSFundClasses(w.store);
2180 self.copyBatchWidgets[field] = w;
2183 if (field == "fund") {
2185 widget.widget, "onChange", function(val) {
2186 self._updateFundSelectorStyle(widget, val);
2193 this.copyBatchRowDrawn = true;
2196 this.batchCopyUpdate = function() {
2198 for(var k in this.copyWidgetCache) {
2199 var cache = this.copyWidgetCache[k];
2200 dojo.forEach(liDetailBatchFields, function(f) {
2201 var newval = self.copyBatchWidgets[f].attr('value');
2202 if(newval) cache[f].attr('value', newval);
2207 this._drawCopies = function(li) {
2210 // this button sets the total number of copies for a given lineitem
2211 acqLitAddCopyCount.onClick = function() {
2212 var count = acqLitCopyCountInput.attr('value');
2215 while(self.copyCount() < count)
2218 // delete rows if necessary
2219 var diff = self.copyCount() - count;
2221 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
2222 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
2223 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
2225 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2231 if(li.lineitem_details().length > 0) {
2232 dojo.forEach(li.lineitem_details(),
2234 self.addCopy(li, copy);
2242 this.copyCount = function() {
2244 for(var id in this.copyCache) {
2245 if(!this.copyCache[id].isdeleted())
2251 this.virtCopyId = -1;
2252 this.addCopy = function(li, copy) {
2253 var row = this.copyRow.cloneNode(true);
2254 this.copyTbody.appendChild(row);
2258 copy = new fieldmapper.acqlid();
2260 copy.id(this.virtCopyId--);
2261 copy.lineitem(li.id());
2264 this.copyCache[copy.id()] = copy;
2265 row.setAttribute('copy_id', copy.id());
2266 self.copyWidgetCache[copy.id()] = {};
2268 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2270 var rcvr = copy.receiver();
2272 if (!userCache[rcvr]) {
2273 if(rcvr == openils.User.user.id()) {
2274 userCache[rcvr] = openils.User.user;
2276 userCache[rcvr] = fieldmapper.standardRequest(
2277 ['open-ils.actor', 'open-ils.actor.user.retrieve'],
2278 {params: [openils.User.authtoken, rcvr]}
2282 dojo.query('[name=receiver]', row)[0].innerHTML = userCache[rcvr].usrname();
2285 dojo.forEach(liDetailFields,
2288 if (field == "fund") {
2289 searchFilter = (copy.fund() ?
2290 {"-or": {"active": "t", "id": copy.fund()}} :
2293 searchFilter = null;
2296 var readOnly = false;
2298 // TODO: Add support for changing the owning_lib after real copies have been made.
2299 // owning_lib is order data as much as its item data
2300 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
2304 // TODO: add support for changing the fund after debits have been created
2305 // Note: invoicing allows the change
2306 if(copy.fund_debit() && field == 'fund') {
2311 var widget = new openils.widget.AutoFieldWidget({
2314 labelFormat : (field == 'fund') ? fundLabelFormat : null,
2315 searchFormat : (field == 'fund') ? fundSearchFormat : null,
2316 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
2317 searchFilter : searchFilter,
2318 noCache: (field == "fund"),
2320 parentNode : dojo.query('[name='+field+']', row)[0],
2321 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2322 readOnly : readOnly,
2323 orgDefaultsToWs : true
2327 // make sure we capture the value from any async widgets
2330 if (field == "fund" && w.store)
2331 self._ensureCSSFundClasses(w.store);
2334 copy[field](ww.getFormattedValue())
2336 self.copyWidgetCache[copy.id()][field] = w;
2338 dojo.connect(w, 'onChange',
2340 if (field == "fund")
2341 self._updateFundSelectorStyle(widget, val);
2343 if (!readOnly && (copy.isnew() || val != copy[field]())) {
2344 // prevent setting ischanged() automatically on widget load for existing copies
2345 copy[field](widget.getFormattedValue())
2346 copy.ischanged(true);
2355 this.updateLidState(copy, row);
2358 this._ensureCSSFundClass = function(id) {
2359 if (!this.fundStyleSheet) {
2361 "style", {"type": "text/css"},
2362 document.getElementsByTagName("head")[0], "last"
2364 this.fundStyleSheet = document.styleSheets[
2365 document.styleSheets.length - 1
2369 var cn = "fund_" + id;
2370 if (!this.haveFundClass[cn]) {
2371 fieldmapper.standardRequest(
2372 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
2374 "params": [openils.User.authtoken, id],
2376 "oncomplete": function(r) {
2377 r = openils.Util.readResponse(r);
2378 self.fundBalanceState[id] = r;
2380 if (r[0] /* stop */)
2381 style = fundStyles.stop;
2382 else if (r[1] /* warning */)
2383 style = fundStyles.warning;
2384 self.fundStyleSheet.insertRule(
2385 "." + cn + " { " + style + " }",
2386 self.fundStyleSheet.cssRules.length
2388 self.haveFundClass[cn] = true;
2395 this._ensureCSSFundClasses = function(store) {
2397 "query": {"id": "*"},
2398 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
2402 this._updateFundSelectorStyle = function(widget, fund_id) {
2403 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
2404 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
2407 this.updateLidState = function(copy, row) {
2410 if (typeof(row) == "undefined") {
2411 row = dojo.query('tr[copy_id="' + copy.id() + '"]', this.copyTbody)[0];
2415 var recv_link = nodeByName("receive", row);
2416 var unrecv_link = nodeByName("unreceive", row);
2417 var del_link = nodeByName("delete", row);
2418 var cxl_link = nodeByName("cancel", row);
2419 var claim_link = nodeByName("claim", row);
2420 var cxl_reason_link = nodeByName("cancel_reason", row);
2422 // by default, hide all the actions
2423 openils.Util.hide(del_link.parentNode);
2424 openils.Util.hide(recv_link);
2425 openils.Util.hide(unrecv_link);
2426 openils.Util.hide(cxl_link);
2427 openils.Util.hide(claim_link);
2428 openils.Util.hide(cxl_reason_link);
2430 if (copy.id() > 0) { // real copies (LIDs)
2432 if (copy.cancel_reason()) {
2434 /* --------- cancelled -------------------------- */
2436 /* XXX the following may leak memory in a long lived table:
2437 * dijits may not get destroyed... not positive. revisit. */
2438 var holds_reason = dojo.create(
2440 "style": "border-bottom: 1px dashed #000;",
2441 "innerHTML": "Cancelled" /* XXX [sic] and i18n */
2442 }, cxl_reason_link, "only"
2446 "label": "<em>" + copy.cancel_reason().label() +
2447 "</em><br />" + copy.cancel_reason().description(),
2448 "connectId": [holds_reason]
2449 }, dojo.create("span", null, cxl_reason_link, "last")
2451 openils.Util.show(cxl_reason_link, "inline");
2453 } else if (copy.recv_time()) {
2455 /* --------- received -------------------------- */
2457 openils.Util.show(unrecv_link, "inline");
2458 unrecv_link.onclick = function() {
2459 if (confirm(localeStrings.UNRECEIVE_LID))
2460 self.issueReceive(copy, /* rollback */ true);
2463 } else if (this.liCache[copy.lineitem()].state() == 'on-order') {
2465 /* --------- on order -------------------------- */
2467 openils.Util.show(recv_link, 'inline');
2468 openils.Util.show(cxl_link, "inline");
2470 recv_link.onclick = function() {
2471 if (self.checkLiAlerts(copy.lineitem()))
2472 self.issueReceive(copy);
2475 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2479 /* --------- pre-order copies -------------------------- */
2481 del_link.onclick = function() { self.deleteCopy(row) };
2482 openils.Util.show(del_link.parentNode);
2488 /* --------- virtual copies -------------------------- */
2490 del_link.onclick = function() { self.deleteCopy(row) };
2491 openils.Util.show(del_link.parentNode);
2495 this.cancelLid = function(lid_id) {
2496 lidCancelDialog._lid_id = lid_id;
2497 openils.Util.show(lidCancelDialog.domNode.parentNode);
2498 lidCancelDialog.show();
2499 if (!lidCancelDialog._prepared) {
2500 var widget = new openils.widget.AutoFieldWidget({
2501 "fmField": "cancel_reason",
2502 "fmClass": "acqlid",
2503 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
2504 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2509 acqLidCancelButton.onClick = function() {
2510 if (w.attr("value")) {
2511 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
2513 lidCancelDialog._lid_id,
2517 lidCancelDialog.hide();
2520 lidCancelDialog._prepared = true;
2526 this._cancelLid = function(lid_id, reason) {
2527 fieldmapper.standardRequest(
2528 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
2529 "params": [openils.User.authtoken, lid_id, reason],
2531 "onresponse": function(r) {
2532 if (r = openils.Util.readResponse(r)) {
2534 for (var id in r.lid) {
2535 /* actually this should only iterate once */
2536 self.copyCache[id].cancel_reason(
2537 r.lid[id].cancel_reason
2539 self.updateLidState(self.copyCache[id]);
2548 this._confirmAlert = function(li, lin) {
2550 dojo.string.substitute(
2551 localeStrings.CONFIRM_LI_ALERT, [
2552 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2553 "title", "lineitem_marc_attr_definition"
2555 /* XXX it's really better add a parameter and to adjust
2556 * the format string rather than do this concatenation
2557 * here, but if someone wants this for 2.2 in a hurry,
2558 * we can sidestep the problem of updating the strings
2559 * while the translators are working. */
2561 aou.findOrgUnit(lin.alert_text().owning_lib()).shortname() +
2563 lin.alert_text().code()
2565 lin.alert_text().description() || "",
2572 this.checkLiAlerts = function(li_id) {
2573 var li = this.liCache[li_id];
2575 var alert_notes = li.lineitem_notes().filter(
2576 function(o) { return Boolean(o.alert_text()); }
2579 /* this is _intentionally_ not done in a call to forEach() ... */
2580 for (var i = 0; i < alert_notes.length; i++) {
2581 if (this.noteAcks[alert_notes[i].id()])
2583 else if (!this._confirmAlert(li, alert_notes[i]))
2586 this.noteAcks[alert_notes[i].id()] = true;
2592 this.deleteCopy = function(row) {
2593 var copy = this.copyCache[row.getAttribute('copy_id')];
2594 copy.isdeleted(true);
2596 delete this.copyCache[copy.id()];
2597 this.copyTbody.removeChild(row);
2600 this._virtDfaCountsAsList = function() {
2602 for (var key in this.virtDfaCounts) {
2603 for (var i = 0; i < this.virtDfaCounts[key]; i++)
2609 this.confirmBreachedCopyFunds = function(copies) {
2610 var stop = 0, warning = 0;
2614 var state = self.fundBalanceState[o.fund()];
2615 if (state[0] /* stop */)
2617 else if (state[1] /* warning */)
2624 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
2625 } else if (warning) {
2626 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
2631 this.saveCopyChanges = function(liId) {
2637 for(var id in this.copyCache) {
2638 var c = this.copyCache[id];
2639 if(!c.isdeleted()) total++;
2640 if(c.isnew() || c.ischanged() || c.isdeleted()) {
2641 if(c.id() < 0) c.id(null);
2647 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
2650 if (copies.length > 0) {
2651 if (!this.confirmBreachedCopyFunds(copies))
2654 if (typeof(this._copy_count_cb) == "function")
2655 this._copy_count_cb(liId, total);
2657 openils.Util.show("acq-lit-update-copies-progress");
2658 fieldmapper.standardRequest(
2659 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
2661 params: [openils.User.authtoken, copies],
2662 onresponse: function(r) {
2663 var res = openils.Util.readResponse(r);
2664 litUpdateCopiesProgress.update(res);
2666 oncomplete: function() {
2667 self.drawCopies(liId, true /* force_fetch */);
2668 openils.Util.hide("acq-lit-update-copies-progress");
2674 var dfa_list = this._virtDfaCountsAsList();
2675 if (dfa_list.length > 0) {
2676 fieldmapper.standardRequest(
2678 "open-ils.acq.distribution_formula.record_application"],
2681 "params": [openils.User.authtoken, dfa_list, liId],
2682 "onresponse": function(r) {
2683 var res = openils.Util.readResponse(r);
2684 if (res && res.length < dfa_list.length)
2685 alert(localeStrings.DFA_NOT_ALL);
2689 this.virtDfaCounts = {};
2692 if (this.inlineCopiesNeedingRefresh.indexOf(liId) < 0)
2693 this.inlineCopiesNeedingRefresh.push(liId);
2696 this._updateCreatePoPrepayCheckbox = function(prepay) {
2697 var prepay = openils.Util.isTrue(prepay);
2698 this._prepayRequiredByVendor = prepay;
2699 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
2702 this._confirmPoPrepaySituation = function() {
2703 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
2704 if (want_prepay != this._prepayRequiredByVendor) {
2707 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
2708 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
2715 this.applySelectedLiAction = function(action) {
2719 case 'delete_selected':
2720 this._deleteLiList(self.getSelected());
2723 case 'add_to_order':
2724 addToPoDialog._get_li = dojo.hitch(
2727 return this.getSelected(
2728 false, null, true, li_pre_po_states);
2731 if (addToPoDialog._get_li().length == 0) {
2732 alert(localeStrings.NO_LI_GENERAL);
2735 addToPoDialog.show();
2738 case 'create_order':
2739 this._loadPOSelect();
2740 acqLitPoCreateDialog.show();
2743 case 'save_picklist':
2744 acqLitSavePlDialog.show();
2747 case 'selector_ready':
2749 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
2750 acqLitChangeLiStateDialog.show();
2758 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
2761 case 'batch_create_invoice':
2762 this.batchCreateInvoice();
2765 case 'batch_link_invoice':
2766 this.batchLinkInvoice();
2769 case 'receive_lineitems':
2770 this.receiveSelectedLineitems();
2773 case 'rollback_receive_lineitems':
2774 this.rollbackReceiveLineitems();
2777 case 'create_assets':
2778 this.showAssetCreator();
2781 case 'export_attr_list':
2782 this.chooseExportAttr();
2785 case 'batch_apply_funds':
2786 this.applyBatchLiFunds();
2789 case 'add_brief_record':
2791 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
2793 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
2797 case "cancel_lineitems":
2798 console.log('HERE');
2799 this.maybeCancelLineitems();
2802 case "apply_claim_policy":
2803 var li_list = this.getSelected();
2804 this.claimPolicyPicker.attr("value", null);
2805 liClaimPolicyDialog.show();
2806 liClaimPolicySave.onClick = function() {
2807 self.changeClaimPolicy(
2809 self.claimPolicyPicker.attr("value"),
2813 self.setClaimPolicyControl(li);
2814 self.reconsiderClaimControl(li);
2817 liClaimPolicyDialog.hide();
2825 this.changeClaimPolicy = function(li_list, value, callback) {
2827 function(li) { li.claim_policy(value); }
2829 fieldmapper.standardRequest(
2830 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
2831 "params": [openils.User.authtoken, li_list],
2833 "oncomplete": function(r) {
2834 r = openils.Util.readResponse(r);
2835 if (callback) callback(r);
2841 this.showAssetCreator = function(onAssetsCreated) {
2842 if(!this.isPO) return;
2845 // first, let's see if this PO has any LI's that need to be merged/imported
2846 self.pcrud.search('jub', {purchase_order : this.isPO, eg_bib_id : null}, {
2848 oncomplete : function(r) {
2849 var resp = openils.Util.readResponse(r);
2850 if (resp && resp.length) {
2851 // PO has some non-linked jubs.
2853 self.show('asset-creator');
2854 if(!self.vlAgent.loaded)
2855 self.vlAgent.init();
2857 dojo.connect(assetCreatorButton, 'onClick',
2858 function() { self.createAssets(onAssetsCreated) });
2862 // all jubs linked, move on to asset creation
2863 self.createAssets(onAssetsCreated, true);
2869 this.createAssets = function(onAssetsCreated, noVl) {
2870 this.show('acq-lit-progress-numbers');
2872 var vlArgs = (noVl) ? {} : {vandelay : this.vlAgent.values()};
2873 fieldmapper.standardRequest(
2874 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
2876 params: [this.authtoken, this.isPO, vlArgs],
2877 onresponse: function(r) {
2878 var resp = openils.Util.readResponse(r);
2879 self._updateProgressNumbers(resp, !Boolean(onAssetsCreated), onAssetsCreated);
2885 this.maybeCancelLineitems = function() {
2886 openils.Util.show("acq-lit-cancel-reason", "inline");
2887 if (!acqLitCancelLineitemsButton._prepared) {
2888 var widget = new openils.widget.AutoFieldWidget({
2889 "fmField": "cancel_reason",
2891 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
2892 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2897 acqLitCancelLineitemsButton.onClick = function() {
2898 if (w.attr("value")) {
2899 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
2900 self._cancelLineitems(w.attr("value"));
2902 openils.Util.hide("acq-lit-cancel-reason");
2905 acqLitCancelLineitemsButton._prepared = true;
2911 this._cancelLineitems = function(reason) {
2912 var id_list = this.getSelected(
2913 null, null, true, li_active_states);
2914 if (!id_list.length) {
2915 alert(localeStrings.NO_LI_GENERAL);
2918 fieldmapper.standardRequest(
2919 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
2920 "params": [openils.User.authtoken, id_list, reason],
2922 "onresponse": function(r) {
2923 if (r = openils.Util.readResponse(r)) {
2925 for (var id in r.li) {
2926 self.liCache[id].state(r.li[id].state);
2927 self.liCache[id].cancel_reason(
2928 r.li[id].cancel_reason
2930 self.updateLiState(self.liCache[id]);
2933 if (r.lid && self.copyCache) {
2934 for (var id in r.lid) {
2935 if (self.copyCache[id]) {
2936 self.copyCache[id].cancel_reason(
2937 r.lid[id].cancel_reason
2939 self.updateLidState(self.copyCache[id]);
2949 this.chooseExportAttr = function() {
2950 if (!acqLitExportAttrSelector._li_setup) {
2952 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
2954 "data": acqlimad.toStoreData(
2956 "acqlimad", {"code": li_exportable_attrs}
2961 acqLitExportAttrSelector.setValue();
2962 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
2963 acqLitExportAttrSelector._li_setup = true;
2965 openils.Util.show("acq-lit-export-attr-holder", "inline");
2968 this.exportAttrList = function() {
2969 var attr_def = acqLitExportAttrSelector.item;
2970 var li_list = this.getSelected();
2971 var value_list = li_list.map(
2973 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2974 attr_def.code, "lineitem_marc_attr_definition"
2977 ).filter(function(attr) { return Boolean(attr); });
2979 if (value_list.length > 0) {
2980 if (value_list.length < li_list.length) {
2982 dojo.string.substitute(
2983 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
2990 openils.XUL.contentToFileSaveDialog(
2991 value_list.join("\n"),
2992 localeStrings.EXPORT_SAVE_DIALOG_TITLE
2998 alert(dojo.string.substitute(
2999 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
3003 openils.Util.hide("acq-lit-export-attr-holder");
3006 this.printPO = function() {
3007 if(!this.isPO) return;
3008 progressDialog.show(true);
3009 fieldmapper.standardRequest(
3010 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
3012 params: [this.authtoken, this.isPO, 'html'],
3013 oncomplete: function(r) {
3014 progressDialog.hide();
3015 var evt = openils.Util.readResponse(r);
3016 if(evt && evt.template_output()) {
3017 openils.Util.printHtmlString(evt.template_output().data());
3024 this.batchCreateInvoice = function() {
3025 var liIds = this.getSelected(
3026 false, null, true /* id_list */, li_active_states)
3027 if (!liIds.length) {
3028 alert(localeStrings.NO_LI_GENERAL);
3031 var path = oilsBasePath + '/acq/invoice/view?create=1';
3032 dojo.forEach(liIds, function(li, idx) { path += '&attach_li=' + li });
3033 if (openils.XUL.isXUL())
3034 openils.XUL.newTabEasy(path, localeStrings.NEW_INVOICE, null, true);
3036 location.href = path;
3039 this.batchLinkInvoice = function(create) {
3040 var liIds = this.getSelected(
3041 false, null, true /* id_list */, li_active_states)
3042 if (!liIds.length) {
3043 alert(localeStrings.NO_LI_GENERAL);
3046 if (!self.invoiceLinkDialogManager) {
3047 self.invoiceLinkDialogManager =
3048 new InvoiceLinkDialogManager("li");
3050 self.invoiceLinkDialogManager.target = liIds;
3051 acqLitLinkInvoiceDialog.show();
3054 this.receiveSelectedLineitems = function() {
3055 var states = li_post_po_states.filter(
3056 function(s) { return s != 'received' });
3057 var li_list = this.getSelected(null, null, null, states);
3059 if (!li_list.length) {
3060 alert(localeStrings.NO_LI_GENERAL);
3064 for (var i = 0; i < li_list.length; i++) {
3065 var li = li_list[i];
3067 if (li.state() != "received" &&
3068 !this.checkLiAlerts(li.id())) return;
3071 this.show('acq-lit-progress-numbers');
3074 fieldmapper.standardRequest(
3075 ['open-ils.acq', 'open-ils.acq.lineitem.receive.batch'],
3079 li_list.map(function(li) { return li.id(); })
3081 onresponse : function(r) {
3082 var resp = openils.Util.readResponse(r);
3083 self._updateProgressNumbers(resp, true);
3089 this.issueReceive = function(obj, rollback) {
3091 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
3093 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
3095 progressDialog.show(true);
3096 fieldmapper.standardRequest(
3097 ["open-ils.acq", method], {
3099 "params": [this.authtoken, obj.id()],
3100 "onresponse": function(r) {
3101 if (r = openils.Util.readResponse(r)) {
3102 self.fetchClaimInfo(
3103 part == "lineitem" ? obj.id() : obj.lineitem(),
3105 function() { self.handleReceive(r); }
3107 progressDialog.hide();
3115 * Handles the responses from receive and rollback ML calls.
3117 this.handleReceive = function(resp) {
3120 for (var li_id in resp.li) {
3121 for (var key in resp.li[li_id])
3122 self.liCache[li_id][key](resp.li[li_id][key]);
3123 self.updateLiState(self.liCache[li_id]);
3127 if (typeof(self.poUpdateCallback) == "function")
3128 self.poUpdateCallback(resp.po);
3131 for (var lid_id in resp.lid) {
3132 for (var key in resp.lid[lid_id])
3133 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
3134 self.updateLidState(self.copyCache[lid_id]);
3140 this.rollbackReceiveLineitems = function() {
3141 var li_id_list = this.getSelected(false, null, true);
3142 if (!li_id_list.length) {
3143 alert(localeStrings.NO_LI_GENERAL);
3147 if (!confirm(localeStrings.ROLLBACK_LI_RECEIVE_CONFIRM)) return;
3149 this.show('acq-lit-progress-numbers');
3152 fieldmapper.standardRequest(
3153 ['open-ils.acq', 'open-ils.acq.lineitem.receive.rollback.batch'],
3155 params: [this.authtoken, li_id_list],
3156 onresponse : function(r) {
3157 var resp = openils.Util.readResponse(r);
3158 self._updateProgressNumbers(resp, true);
3164 this._updateProgressNumbers = function(resp, reloadOnComplete, onComplete) {
3165 this.vlAgent.handleResponse(resp,
3166 function(resp, res) {
3167 if(reloadOnComplete)
3168 location.href = location.href;
3170 onComplete(resp, res);
3176 this._createPO = function(fields) {
3177 var wantall = (fields.create_from == "all");
3179 /* If we're a picklist or purchase order already and the user wants
3180 * all lineitems, we might have pages' worth of lineitems haven't all
3181 * been loaded yet, so getSelected() won't find them. The server,
3182 * however, should know about all our lineitems, so let's ask the
3183 * server for a complete list.
3188 true, function(list) {
3189 self._createPOFromLineitems(fields, list);
3190 }, /* id_list */ true, li_pre_po_states
3193 this._createPOFromLineitems(
3194 fields, this.getSelected(
3195 false, null, true /* id_list */, li_pre_po_states)
3200 this._createPOFromLineitems = function(fields, selected) {
3201 if (selected.length == 0) {
3202 alert(localeStrings.NO_LI_GENERAL);
3207 var po = new fieldmapper.acqpo();
3208 po.provider(this.createPoProviderSelector.attr("value"));
3209 po.ordering_agency(this.createPoAgencySelector.attr("value"));
3210 po.prepayment_required(fields.prepayment_required[0] ? true : false);
3212 // if we're creating assets, delay the asset creation
3213 // until after the PO is created. This will allow us to
3214 // use showAssetCreator() directly.
3216 fieldmapper.standardRequest(
3217 ["open-ils.acq", "open-ils.acq.purchase_order.create"],
3220 openils.User.authtoken,
3221 po, {lineitems : selected}
3223 onresponse : function(r) {
3224 var resp = openils.Util.readResponse(r);
3225 if (resp.complete) {
3226 // self.isPO is needed for showAssetCreator();
3227 self.isPO = resp.purchase_order.id();
3228 var redir = oilsBasePath + "/acq/po/view/" + self.isPO;
3229 if (fields.create_assets[0]) {
3230 self.showAssetCreator(
3231 function() {location.href = redir}
3234 location.href = redir;
3243 this.batchFundWidget = null;
3245 this.applyBatchLiFunds = function() {
3247 var liIds = this.getSelected().map(function(li) { return li.id(); });
3248 if(liIds.length == 0) return; // warn?
3251 batchFundUpdateDialog.show();
3253 if(!this.batchFundWidget) {
3254 this.batchFundWidget = new openils.widget.AutoFieldWidget({
3256 selfReference : true,
3257 labelFormat : fundLabelFormat,
3258 searchFormat : fundSearchFormat,
3259 searchFilter : {"active": "t"},
3260 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
3261 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
3262 dijitArgs : { "required": true, "labelType": "html" },
3265 this.batchFundWidget.build();
3268 dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
3269 dojo.connect(batchFundUpdateSubmit, 'onClick',
3272 // TODO: call .dry_run first to test thresholds
3273 fieldmapper.standardRequest(
3274 ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
3277 openils.User.authtoken,
3279 self.batchFundWidget.widget.attr('value')
3281 oncomplete : function(r) {
3282 var resp = openils.Util.readResponse(r);
3284 location.href = location.href;
3293 this._deleteLiList = function(list, idx) {
3294 if(idx == null) idx = 0;
3295 if(idx >= list.length) return;
3300 if (this.isPO && (li.state() == "on-order" || li.state() == "received")) {
3301 /* It makes little sense to delete a lineitem from a PO that has
3302 * already been marked 'on-order'. Especially if EDI is in use,
3303 * such a purchase order will probably have already been shipped
3304 * off to a vendor, and mucking with it at this point could leave
3305 * your data in a bad state that doesn't jive with reality.
3307 * I could see making this restriction even firmer.
3309 * I could also see adjusting the li state comparisons, extending
3310 * the comparison to the PO's state, and/or providing functions
3311 * that house the logic for comparing states in a single location.
3313 * Yes, this will be really annoying if you have selected a lot
3314 * of lineitems to cancel that have been ordered. You'll get a
3315 * confirm dialog for each one.
3318 if (!confirm(localeStrings.DEL_LI_FROM_PO)) {
3319 self._deleteLiList(list, ++idx); /* move on to next in list */
3324 fieldmapper.standardRequest(
3326 this.isPO ? 'open-ils.acq.purchase_order.lineitem.delete' : 'open-ils.acq.picklist.lineitem.delete'],
3328 params: [openils.User.authtoken, liId],
3329 oncomplete: function(r) {
3330 self.removeLineitem(liId);
3331 self._deleteLiList(list, ++idx);
3337 this.editOrderMarc = function(li) {
3339 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
3340 to true in about:config */
3342 if(openils.XUL.isXUL()) {
3343 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul','','chrome');
3345 win = window.open('/xul/server/cat/marcedit.xul','','chrome');
3349 record : {marc : li.marc(), "rtype": "bre"},
3351 label: 'Save Record', // XXX I18N
3352 func: function(xmlString) {
3354 fieldmapper.standardRequest(
3355 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
3357 params: [openils.User.authtoken, li],
3358 oncomplete: function(r) {
3359 openils.Util.readResponse(r);
3361 self.drawInfo(li.id())
3367 'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
3368 'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
3372 this._savePl = function(values) {
3374 (values.which == 'all'),
3375 function(list) { self._savePlFromLineitems(values, list); }
3379 this._savePlFromLineitems = function(values, selected) {
3380 openils.Util.show("acq-lit-generic-progress");
3382 if(values.new_name) {
3383 openils.acq.Picklist.create(
3384 {name: values.new_name},
3390 oilsBasePath + "/acq/picklist/view/" + id;
3395 } else if(values.existing_pl) {
3396 // update lineitems to use an existing picklist
3398 values.existing_pl, selected, 0,
3401 oilsBasePath + "/acq/picklist/view/" +
3408 this._updateLiState = function(values, state, state_filter) {
3409 progressDialog.show(true);
3411 (values.which == 'all'),
3413 self._updateLiStateFromLineitems(values, state, list);
3414 }, false /* id_list */, state_filter
3418 this._updateLiStateFromLineitems = function(values, state, selected) {
3419 if(!selected.length) {
3420 try { progressDialog.hide() } catch(E) {};
3421 alert(localeStrings.NO_LI_GENERAL);
3424 dojo.forEach(selected, function(li) {li.state(state);});
3425 self._updateLiList(null, selected, 0,
3426 // TODO consider inline updates for efficiency
3427 function() { location.href = location.href }
3431 this._updateLiList = function(pl, list, idx, oncomplete) {
3432 if(idx >= list.length) return oncomplete();
3434 if(pl != null) li.picklist(pl);
3435 litGenericProgress.update({maximum: list.length, progress: idx});
3436 new openils.acq.Lineitem({lineitem:li}).update(
3438 self._updateLiList(pl, list, ++idx, oncomplete);
3443 this._loadPOSelect = function() {
3444 if (!this.createPoProviderSelector) {
3445 var widget = new openils.widget.AutoFieldWidget({
3446 "fmField": "provider",
3448 "searchFilter": {"active": "t"},
3449 "parentNode": dojo.byId("acq-lit-po-provider"),
3451 "onChange": function() {
3453 self._updateCreatePoPrepayCheckbox(
3454 this.item.prepayment_required()
3460 widget.build(function(w) { self.createPoProviderSelector = w; });
3463 if (!this.createPoAgencySelector) {
3464 var widget = new openils.widget.AutoFieldWidget({
3465 "fmField": "ordering_agency",
3467 "parentNode": dojo.byId("acq-lit-po-agency"),
3468 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3470 widget.build(function(w) { self.createPoAgencySelector = w; });
3474 this.showRealCopyEditUI = function(li) {
3479 this._fetchLineitem(li.id(),
3481 li = self.liCache[li.id()] = fullLi;
3485 id : li.lineitem_details().map(
3486 function(item) { return item.eg_copy_id() }
3490 oncomplete : function(r) {
3492 var r_list = openils.Util.readResponse( r );
3493 for (var i = 0; i < r_list.length; i++) {
3494 var copy = r_list[i];
3495 var volId = copy.call_number();
3496 var volume = self.volCache[volId];
3498 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
3500 copy.call_number(volume);
3501 copyList.push(copy);
3504 xulG.volume_item_creator( { 'existing_copies' : copyList } );
3507 alert('error in oncomplete: ' + E);
3516 this.drawBibFinder = function(li) {
3519 var liWrapper = new openils.acq.Lineitem({lineitem:li});
3522 ['isbn', 'upc', 'issn', 'title', 'author'],
3524 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
3526 if(field == 'title' || field == 'author') {
3527 query += field +':' + val + ' ';
3529 query += 'identifier|' + field + ':' + val + ' ';
3536 oilsBasePath + '/acq/lineitem/findbib?query=' + escape(query),
3537 '', 'resizable,scrollbars=1,chrome');
3539 win.window.recordFound = function(bibId) {
3542 var attrs = li.attributes();
3543 li.attributes(null);
3544 li.eg_bib_id(bibId);
3546 fieldmapper.standardRequest(
3547 ["open-ils.acq", "open-ils.acq.lineitem.update"],
3549 "params": [openils.User.authtoken, li],
3551 "oncomplete": function(r) {
3552 if(openils.Util.readResponse(r)) {
3553 location.href = location.href;