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.reset = function(keep_selectors) {
148 while(self.tbody.childNodes[0])
149 self.tbody.removeChild(self.tbody.childNodes[0]);
157 this.setNext = function(handler) {
158 var link = dojo.byId('acq-lit-next');
160 dojo.style(link, 'visibility', 'visible');
161 link.onclick = handler;
163 dojo.style(link, 'visibility', 'hidden');
167 this.setPrev = function(handler) {
168 var link = dojo.byId('acq-lit-prev');
170 dojo.style(link, 'visibility', 'visible');
171 link.onclick = handler;
173 dojo.style(link, 'visibility', 'hidden');
177 this.enableActionsDropdownOptions = function(mask) {
178 /* 'mask' is probably a minomer the way I'm using it, but it needs to
179 * be one of pl,po,ao,gs,vp, or fs. */
180 dojo.query("option", "acq-lit-li-actions-selector").forEach(
182 var opt_mask = dojo.attr(option, "mask");
184 /* For each <option> element, an empty or non-existent mask
185 * attribute, a mask attribute of "*", or a mask attribute that
186 * matches this method's argument should result in that
187 * option's being enabled. */
189 option, "disabled", !(
192 opt_mask.search(mask) != -1
200 * Ensures this.focusLineitem is in view and causes a brief
201 * border around the lineitem to come to life then fade.
203 this.focusLi = function() {
204 if (!this.focusLineitem) return;
206 // set during addLineitem()
207 var node = dojo.byId('li-title-ref-' + this.focusLineitem);
209 // LI may not yet be rendered
212 // prevent numerous re-focuses
213 this.focusLineitem = null;
215 // causes the full row to be visible
216 dijit.scrollIntoView(node);
219 dojo.query('[attr=title]', node)[0].focus();
221 dojo.require('dojox.fx');
225 dojox.fx.highlight({color : '#BB4433', node : node, duration : 2000}).play();
230 this.show = function(div) {
231 openils.Util.hide('acq-lit-table-div');
232 openils.Util.hide('acq-lit-info-div');
233 openils.Util.hide('acq-lit-li-details');
234 openils.Util.hide('acq-lit-notes-div');
235 openils.Util.hide('acq-lit-real-copies-div');
236 openils.Util.hide('acq-lit-asset-creator');
239 openils.Util.show('acq-lit-table-div');
241 this.refreshInlineCopies();
244 openils.Util.show('acq-lit-info-div');
247 openils.Util.show('acq-lit-li-details');
250 openils.Util.show('acq-lit-real-copies-div');
253 openils.Util.show('acq-lit-notes-div');
255 case 'asset-creator':
256 openils.Util.show('acq-lit-asset-creator');
260 openils.Util.show(div);
264 this.hide = function() {
268 this.toggleSelect = function() {
270 dojo.forEach(self.selectors, function(i){i.checked = false});
272 dojo.forEach(self.selectors, function(i){i.checked = true});
273 self.toggleState = !self.toggleState;
277 this.getAll = function(callback, id_only) {
278 /* For some uses of the li table, we may not really know about "all"
279 * the lineitems that the user thinks we know about. If we're a paged
280 * picklist, for example, we only know about the lineitems we've
281 * displayed, but not necessarily all the lineitems on the picklist.
282 * So we reach out to pcrud to inform us.
285 var oncomplete = function(r) {
286 var id_list = openils.Util.readResponse(r);
290 self.fetchLineitemsById(id_list, callback);
295 "jub", {"picklist": this.isPL}, {
296 "id_list": true, /* sic, even if id_only */
298 "oncomplete": oncomplete
302 } else if (this.isPO) {
304 "jub", {"purchase_order": this.isPO}, {
307 "oncomplete": oncomplete
311 } else if (this.isUni && this.pager) {
312 this.pager.getAllLineitemIDs(oncomplete);
316 /* If execution reaches this point, we don't need or can't perform
317 * any special tricks to find out the "real" list of "all" lineitems
318 * in this context, so we fall back to the old method.
320 callback(this.getSelected(true, null, id_only));
323 /** @param all If true, assume all are selected */
324 this.getSelected = function(
326 callback /* If you want a "good" idea of "all" lineitems, you must
327 provide a callback that accepts an array parameter, rather than
328 relying on the return value of this method itself. */,
332 return this.getAll(callback, id_only);
334 var indices = {}; /* use to uniqify. needed in paging situations. */
335 dojo.forEach(this.selectors,
338 indices[i.parentNode.parentNode.getAttribute('li')] = true;
342 var result = openils.Util.objectProperties(indices);
345 result = result.map(function(liId) { return self.liCache[liId]; });
353 this.setRowAttr = function(td, liWrapper, field, type) {
354 var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
355 td.appendChild(document.createTextNode(val));
358 this.setClaimPolicyControl = function(li, row) {
359 if (!self._claimPolicyPickerLoading) {
360 self._claimPolicyPickerLoading = true;
362 new openils.widget.AutoFieldWidget({
363 "parentNode": "acq-lit-li-claim-policy",
365 "selfReference": true,
366 "dijitArgs": {"required": true}
368 function(w) { self.claimPolicyPicker = w; }
372 /* dojox.timing.doLater() is the best thing ever. Resource not yet
373 * ready? Just repeat my whole method when it is. */
374 if (dojox.timing.doLater(self.claimPolicyPicker)) {
378 row = self._findLiRow(li);
380 if (li.claim_policy()) {
381 /* This Dojo data dance is necessary to get a whole fieldmapper
382 * object based on a claim policy ID, since we alreay have the
383 * widget thing loaded with all that data, and can thereby
384 * avoid another request to the server. */
385 self.claimPolicyPicker.store.fetchItemByIdentity({
386 "identity": li.claim_policy(),
387 "onItem": function(a) {
388 var policy = (new acqclp()).fromStoreItem(a);
389 var span = nodeByName("claim_policy", row);
390 var inner = nodeByName("claim_policy_name", row);
392 openils.Util.show(span, "inline");
393 inner.innerHTML = policy.name();
395 "onError": function(e) {
400 openils.Util.hide(nodeByName("claim_policy", row));
401 nodeByName("claim_policy_name", row).innerHTML = "";
406 this.fetchClaimInfo = function(liId, force, callback, row) {
408 liId, function(full) {
409 self.liCache[full.id()] = full;
410 self.checkClaimEligibility(full, callback, row);
416 * Inserts a single lineitem into the growing table of lineitems
417 * @param {Object} li The lineitem object to insert
419 this.addLineitem = function(li, skip_final_placement) {
420 this.liCache[li.id()] = li;
422 // insert the row right away so that final order isn't
423 // dependent on how long subsequent async request take
424 // for a given line item
425 var row = self.rowTemplate.cloneNode(true);
426 if (!skip_final_placement) {
427 self.tbody.appendChild(row);
429 self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
431 // sort the lineitem notes on edit_time
432 if(!li.lineitem_notes()) li.lineitem_notes([]);
434 var liWrapper = new openils.acq.Lineitem({lineitem:li});
435 row.setAttribute('li', li.id());
436 var tds = dojo.query('[attr]', row);
437 dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
438 dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
440 // so we can scroll to it later
441 dojo.query('[name=bib-info-cell]', row)[0].id = 'li-title-ref-' + li.id();
444 liWrapper.findAttr("isbn", "lineitem_marc_attr_definition") ||
445 liWrapper.findAttr("upc", "lineitem_marc_attr_definition");
447 // XXX media prefix for added content
449 nodeByName("jacket", row).setAttribute(
450 "src", "/opac/extras/ac/jacket/small/" + identifier
454 nodeByName("liid", row).innerHTML += li.id();
457 openils.Util.show(nodeByName('catalog', row), 'inline');
458 nodeByName("catalog_link", row).onclick = this.generateMakeRecTab(li.eg_bib_id());
460 openils.Util.show(nodeByName('link_to_catalog', row), 'inline');
461 nodeByName("link_to_catalog_link", row).onclick = function() { self.drawBibFinder(li) };
464 if (li.queued_record()) {
465 this.pcrud.retrieve('vqbr', li.queued_record(),
467 oncomplete : function(r) {
468 var qrec = openils.Util.readResponse(r);
469 openils.Util.show(nodeByName('queue', row), 'inline');
470 var link = nodeByName("queue_link", row);
471 link.onclick = function() {
472 // open a new tab to the vandelay queue for this record
473 openils.XUL.newTabEasy(
474 oilsBasePath + '/vandelay/vandelay?qtype=bib&qid=' + qrec.queue()
482 nodeByName("worksheet_link", row).href =
483 oilsBasePath + "/acq/lineitem/worksheet/" + li.id() +
484 '?source=' + encodeURIComponent(location.pathname + location.search)
486 nodeByName("show_requests_link", row).href =
487 oilsBasePath + "/acq/picklist/user_request?lineitem=" + li.id() +
488 '?source=' + encodeURIComponent(location.pathname + location.search)
490 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
491 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
492 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
493 dojo.query('[name=expand_inline_copies]', row)[0].onclick =
494 function() {self.drawInlineCopies(li.id())};
496 this.drawOrderIdentSelector(li, row);
498 if (!this.skipInitialEligibilityCheck)
502 function(full) { self.setClaimPolicyControl(full, row) },
506 this.updateLiNotesCount(li, row);
508 // show which PO this lineitem is a member of
509 if(li.purchase_order() && !this.isPO) {
511 this.poCache[li.purchase_order()] =
512 this.poCache[li.purchase_order()] ||
513 fieldmapper.standardRequest(
514 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
516 this.authtoken, li.purchase_order(), {
517 "flesh_price_summary": true,
518 "flesh_provider" : true,
519 "flesh_lineitem_count": true
522 if(po && !this.isMeta) {
523 openils.Util.show(nodeByName('po', row), 'inline');
524 var link = nodeByName('po_link', row);
525 link.setAttribute('href', oilsBasePath +
526 '/acq/po/view/' + li.purchase_order() +
527 '?focus_li=' + li.id() +
528 '&source=' + encodeURIComponent(location.pathname + location.search)
530 link.innerHTML += po.name();
532 openils.Util.show(nodeByName('pro', row), 'inline');
533 link = nodeByName('pro_link', row);
534 link.setAttribute('href', oilsBasePath + '/conify/global/acq/provider/' + po.provider().id())
535 link.innerHTML += po.provider().code();
539 // show which picklist this lineitem is a member of
540 if(li.picklist() && (this.isPO || this.isMeta || this.isUni)) {
542 this.plCache[li.picklist()] =
543 this.plCache[li.picklist()] ||
544 fieldmapper.standardRequest(
545 ['open-ils.acq', 'open-ils.acq.picklist.retrieve.authoritative'],
546 {params: [this.authtoken, li.picklist()]});
548 if (pl.name() == "") {
549 openils.Util.show(nodeByName("bib_origin", row), "inline");
553 openils.Util.show(nodeByName('pl', row), 'inline');
554 var link = nodeByName('pl_link', row);
555 link.setAttribute('href', oilsBasePath +
556 '/acq/picklist/view/' + li.picklist() +
557 '?focus_li=' + li.id() +
558 '&source=' + encodeURIComponent(location.pathname + location.search)
560 link.innerHTML += pl.name();
565 var countNode = nodeByName('count', row);
566 var count = li.item_count() || 0;
567 if (typeof(this._copy_count_cb) == "function") {
568 this._copy_count_cb(li.id(), count);
570 countNode.innerHTML = count;
571 countNode.id = 'acq-lit-copy-count-label-' + li.id();
574 var priceInput = dojo.query('[name=price]', row)[0];
575 priceInput.value = li.estimated_unit_price() || '';
576 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
578 // show either "mark received" or "unreceive" as appropriate
579 this.updateLiState(li, row);
581 if (skip_final_placement) {
585 // the last LI may be rendered after the call to show('list'),
586 // so make sure it's focused if necessary.
587 if (this.focusLineitem == li.id())
591 this._liCountClaims = function(li) {
593 for (var i = 0; i < li.lineitem_details().length; i++)
594 total += li.lineitem_details()[i].claims().length;
598 this._findLiRow = function(li) {
599 return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
602 this.reconsiderClaimControl = function(li, row) {
603 if (!row) row = this._findLiRow(li);
604 var option = nodeByName("action_manage_claims", row);
605 var eligible = this.claimEligibleLidByLi[li.id()].length;
606 var count = this._liCountClaims(li);
608 option.disabled = !(count || eligible);
610 dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
611 option.onclick = function() { self.claimDialog.show(li); };
614 this.clearEligibility = function(li) {
615 this.claimEligibleLidByLi[li.id()] = [];
617 if (li.lineitem_details()) {
618 li.lineitem_details().forEach(
619 function(lid) { delete self.claimEligibleLid[lid.id()]; }
623 if (this.copyCache) {
625 for (var k in this.copyCache) {
626 if (this.copyCache[k].lineitem() == li.id())
630 function(k) { delete self.claimEligibleLid[k]; }
635 this.applyOrderIdentValues = function() {
636 this._identValuesInFlight =
637 openils.Util.objectProperties(this.liCache).length;
638 for (var liId in this.liCache) {
639 this._applyOrderIdentValue(this.liCache[liId]);
643 // returns true if request was sent
644 this._applyOrderIdentValue = function(li) {
647 console.log('applying ident value for lineitem ' + li.id());
650 var row = dojo.query('[li=' + li.id() + ']')[0];
652 // find the selected ident value
653 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
654 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
655 var name = typeSel.options[typeSel.selectedIndex].value;
656 var val = typeSel._cbox.attr('value');
658 console.log("selected ident is " + val);
660 // it differs from the existing ident value, update it
661 var oldIdent = self.getLiOrderIdent(li);
663 oldIdent.attr_name() == name &&
664 oldIdent.attr_value() == val) {
665 console.log('selected ident attr matches existing attr');
666 if (--this._identValuesInFlight == 0)
667 location.href = location.href;
671 // see if the selected ident value is represented
672 // by an existing lineitem attr
675 typeSel._cbox.store.fetch({
676 query : {attr_value : val},
677 onItem : function(item) {
678 console.log('found existing attr for ident value');
679 args.source_attr_id = li.attributes().filter(
680 function(attr) { return attr.id() == item.id[0] }
686 if (!args.source_attr_id) {
687 // user entered new text in the combobox
688 // so we need to create a new attr
689 console.log('creating new ident attr');
690 args.lineitem_id = li.id();
691 args.attr_name = name;
692 args.attr_value = val;
695 fieldmapper.standardRequest(
696 ['open-ils.acq', 'open-ils.acq.lineitem.order_identifier.set'],
698 params : [openils.User.authtoken, args],
699 oncomplete : function() {
700 console.log('order_ident oncomplete');
701 if (--self._identValuesInFlight == 0)
702 location.href = location.href;
710 this.getLiOrderIdent = function(li) {
711 var attrs = li.attributes();
712 if (!attrs) return null;
716 attr.attr_type() == 'lineitem_local_attr_definition' &&
717 openils.Util.isTrue(attr.order_ident())
723 this.drawOrderIdentSelector = function(li, row) {
725 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
726 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
728 var attrs = li.attributes();
730 // limit to MARC attr defs
731 attrs = attrs.filter(
733 return (attr.attr_type() == 'lineitem_marc_attr_definition');
737 var identAttr = this.getLiOrderIdent(li);
740 // collect the values for each type of identifier
741 // find a reasonable default identifier type to render
745 dojo.forEach(['isbn', 'upc', 'issn'],
748 // collect the values for this attr name
749 values[name] = attrs.filter(
751 return (attr.attr_name() == name)
755 // select a reasonable default name in the type-selector
759 if (identAttr.attr_name() == name)
761 } else if (values[name].length) {
766 dojo.forEach(typeSel.options, function(opt) {
767 if (opt.value == name) {
777 function updateOrderIdent(box) {
778 console.log('updating order ident for box ' + box);
781 // replace the ident combobox with a new
782 // one for the selected ident type
783 function changeComboBox(sel) {
784 var name = sel.options[sel.selectedIndex].value;
786 var td = dojo.query('[name=order_ident_value]', row)[0];
787 if (td.childNodes[0])
788 dojo.destroy(td.childNodes[0]);
790 var store = new dojo.data.ItemFileWriteStore({
791 data : acqlia.toStoreData(values[name])
794 var cbox = new dijit.form.ComboBox(
796 labelAttr : 'attr_value',
797 searchAttr : 'attr_value'
799 dojo.create('div', {}, td)
804 // set the value for the cbox
805 if (values[name].length) {
806 var orderIdent = self.getLiOrderIdent(li);
808 if (orderIdent && orderIdent.attr_name() == name) {
809 cbox.attr('value', orderIdent.attr_value());
811 cbox.attr('value', values[name][0].attr_value());
815 if (!self.orderIdentAllowed)
816 cbox.attr('disabled', true);
820 dojo.connect(cbox, 'onChange', updateOrderIdent);
823 changeComboBox(typeSel); // force the initial draw
824 typeSel.onchange = function() {changeComboBox(typeSel)};
827 this.testOrderIdentPerms = function(org, callback) {
829 new openils.User().getPermOrgList(
830 'ACQ_SET_LINEITEM_IDENTIFIER',
832 console.log('found orgs = ' + orgs);
833 for (var i = 0; i < orgs.length; i++) {
834 if (Number(orgs[i]) == Number(org)) {
835 self.orderIdentAllowed = true;
836 if (callback) callback();
840 if (callback) callback();
846 this.checkClaimEligibility = function(li, callback, row) {
847 /* Assume always eligible, i.e. from this interface we don't care about
848 * claim eligibility any more. this is where the user would force a
850 this.clearEligibility(li);
851 this.claimEligibleLidByLi[li.id()] = li.lineitem_details().map(
852 function(lid) { return lid.id(); }
854 li.lineitem_details().forEach(
855 function(lid) { self.claimEligibleLid[lid.id()] = true; }
857 this.reconsiderClaimControl(li, row);
858 if (callback) callback(li);
860 this.clearEligibility(li);
861 fieldmapper.standardRequest(
862 ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
863 "params": [openils.User.authtoken, {"lineitem": li.id()}],
865 "onresponse": function(r) {
866 if (r = openils.Util.readResponse(r)) {
867 self.claimEligibleLidByLi[li.id()].push(
870 self.claimEligibleLid[r.lineitem_detail()] = true;
873 "oncomplete": function() {
874 self.reconsiderClaimControl(li, row);
875 if (typeof(callback) == "function")
883 this.updateLiNotesCount = function(li, row) {
884 if (!row) row = this._findLiRow(li);
886 var has_notes = (li.lineitem_notes().filter(
887 function(o) { return Boolean (o.alert_text()); }
890 /* U+2691 is the code point for a filled-in flag character */
891 nodeByName("notes_alert_flag", row).innerHTML =
892 has_notes ? "⚑" : "";
893 nodeByName("noteslink", row).style.fontStyle =
894 has_notes ? "italic" : "normal";
895 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
898 /* XXX NOT related to _updateLiState(). rethink */
899 this.updateLiState = function(li, row) {
900 if (!row) row = this._findLiRow(li);
902 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
903 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
905 // always allow access to LI history
906 nodeByName('action_view_history', row).onclick =
907 function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
909 /* handle row coloring for based on LI state */
910 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
911 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
913 // Expose invoice actions for any lineitem that is linked to a PO
914 if (li.purchase_order()) {
915 openils.Util.show(nodeByName("invoices_span", row), "inline");
916 var link = nodeByName("invoices_link", row);
917 link.onclick = function() {
918 openils.XUL.newTabEasy(
919 oilsBasePath + "/acq/search/unified?so=" +
920 base64Encode({"jub":[{"id": li.id()}]}) + "&rt=invoice"
928 * If we haven't fleshed the lineitem_details, default to allowing access to the
929 * holdings maintenence actions. The alternative is to flesh LIDs on every lineitem,
930 * but that will add to page render time. Let's see if this will suffice...
932 var lids = li.lineitem_details();
934 (lids && !lids.filter(function(lid) { return lid.eg_copy_id() })[0] )) {
936 actUpdateBarcodes.disabled = false;
937 actUpdateBarcodes.onclick = function() {
938 self.showRealCopyEditUI(li);
939 nodeByName("action_none", row).selected = true;
941 actHoldingsMaint.disabled = false;
942 actHoldingsMaint.onclick =
943 self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
946 var state_cell = nodeByName("li_state", row);
951 if(typeof li.cancel_reason() == "object") {
952 var holds_state = dojo.create(
954 "style": "border-bottom: 1px dashed #000;",
955 "innerHTML": li.state()
956 }, state_cell, "only"
960 "label": "<em>" + li.cancel_reason().label() +
961 "</em><br />" + li.cancel_reason().description(),
962 "connectId": [holds_state]
963 }, dojo.create("span", null, state_cell, "last")
975 state_cell.innerHTML = li.state(); // TODO i18n state labels
979 this._setAlertStore = function() {
980 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
982 "data": acqliat.toStoreData(
985 "owning_lib": aou.orgNodeTrail(
986 aou.findOrgUnit(openils.User.user.ws_ou())
987 ).map(function(o) { return o.id(); })
993 acqLitAlertAlertText.setValue(); /* make the store "live" */
994 acqLitAlertAlertText._store_ready = true;
998 * Draws and shows the lineitem notes pane
1000 this.drawLiNotes = function(li) {
1002 this.focusLineitem = li.id();
1004 if (!acqLitAlertAlertText._store_ready)
1005 this._setAlertStore();
1008 li.lineitem_notes().sort(
1010 if(a.edit_time() < b.edit_time()) return 1;
1016 while(this.liNotesTbody.childNodes[0])
1017 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
1020 acqLitCreateNoteSubmit.onClick = function() {
1021 var value = acqLitCreateNoteText.attr('value');
1023 var note = new fieldmapper.acqlin();
1026 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
1029 note.lineitem(li.id());
1031 self.updateLiNotes(li, note);
1032 acqLitCreateNoteVendorPublic.attr("checked", false);
1033 acqLitCreateNoteText.attr("value", "");
1036 acqLitCreateAlertSubmit.onClick = function() {
1037 if (!acqLitAlertAlertText.item) {
1038 alert(localeStrings.ALERT_UNSELECTED);
1042 var alert_text = new fieldmapper.acqliat().fromStoreItem(
1043 acqLitAlertAlertText.item
1045 var value = acqLitAlertNoteValue.attr("value") || "";
1047 var note = new fieldmapper.acqlin();
1049 note.lineitem(li.id());
1051 note.alert_text(alert_text);
1053 self.updateLiNotes(li, note);
1056 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
1060 * Draws a single lineitem note in the notes pane
1062 this.addLiNote = function(li, note) {
1063 if(note.isdeleted()) return;
1065 var row = self.liNotesRow.cloneNode(true);
1066 nodeByName("value", row).innerHTML = note.value();
1067 var alert_node = nodeByName("alert_code", row);
1068 if (note.alert_text()) {
1069 alert_node.innerHTML = dojo.string.substitute(
1071 aou.findOrgUnit(note.alert_text().owning_lib()).shortname(),
1072 note.alert_text().code()
1075 if (note.alert_text().description()) {
1078 "connectId": [alert_node],
1079 "label": note.alert_text().description()
1080 }, dojo.create("span", null, alert_node, "after")
1085 if (openils.Util.isTrue(note.vendor_public()))
1086 nodeByName("vendor_public", row).innerHTML =
1087 localeStrings.VENDOR_PUBLIC;
1089 nodeByName("delete", row).onclick = function() {
1090 note.isdeleted(true);
1091 self.liNotesTbody.removeChild(row);
1092 self.updateLiNotes(li);
1095 if(note.edit_time()) {
1096 nodeByName("edit_time", row).innerHTML =
1097 dojo.date.locale.format(
1098 dojo.date.stamp.fromISOString(note.edit_time()),
1099 {formatLength:'short'});
1102 self.liNotesTbody.appendChild(row);
1106 * Updates any new/changed/deleted notes on the server
1108 this.updateLiNotes = function(li, newNote) {
1114 notes = li.lineitem_notes().filter(
1116 if(note.ischanged() || note.isnew() || note.isdeleted())
1122 if(notes.length == 0) return;
1123 progressDialog.show();
1125 fieldmapper.standardRequest(
1126 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
1128 params : [this.authtoken, notes],
1129 onresponse : function(r) {
1130 var resp = openils.Util.readResponse(r);
1135 // remove the old changed notes
1137 dojo.forEach(li.lineitem_notes(),
1139 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
1143 li.lineitem_notes(list);
1146 progressDialog.hide();
1147 self.updateLiNotesCount(li);
1148 self.drawLiNotes(li);
1152 progressDialog.update(resp);
1153 var newnote = resp.note;
1155 if(!newnote.isdeleted()) {
1156 newnote.isnew(false);
1157 newnote.ischanged(false);
1158 li.lineitem_notes().push(newnote);
1165 this.updateLiPrice = function(input, li) {
1167 var price = input.value;
1168 if(Number(price) == Number(li.estimated_unit_price())) return;
1170 fieldmapper.standardRequest(
1171 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
1172 { async : false, // redundant w/ timeout
1174 params : [this.authtoken, li.id(), price],
1175 oncomplete : function(r) {
1176 openils.Util.readResponse(r);
1177 li.estimated_unit_price(price); // update local copy
1180 * If this is a PO and every visible lineitem has a price,
1181 * check again to see if this PO can be activated. Note that
1182 * every visible lineitem having a price does not guarantee it can
1183 * be activated, which is why we still make the call. Having a price
1184 * set for every visiable lineitem is just the lowest barrier to entry.
1187 var priceNodes = dojo.query('[name=price]', dojo.byId('acq-lit-tbody'));
1189 dojo.forEach(priceNodes, function(node) { if (node.value == '') allSet = false});
1190 if (allSet) checkCouldActivatePo();
1197 this.removeLineitem = function(liId) {
1198 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
1199 delete this.liCache[liId];
1200 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
1203 this.drawInfo = function(liId) {
1204 this.focusLineitem = liId;
1205 if (!this._isRelatedViewer) {
1206 var d = dojo.byId("acq-lit-info-related");
1207 if (!this.relCache[liId]) {
1208 fieldmapper.standardRequest(
1211 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
1214 "params": [openils.User.authtoken, liId],
1215 "onresponse": function(r) {
1216 self.relCache[liId] = openils.Util.readResponse(r);
1217 nodeByName("related_number", d).innerHTML =
1218 self.relCache[liId];
1220 self.relCache[liId] >1 ? "show" : "hide"
1226 nodeByName("related_number", d).innerHTML = this.relCache[liId];
1227 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
1232 openils.acq.Lineitem.fetchAttrDefs(
1234 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
1239 this.toggleInlineCopies = function() {
1240 // if any inline copies are not displayed,
1241 // display them all otherwise, hide them all.
1243 var displayAll = false;
1245 for (var liId in this.liCache) {
1246 if (!this.inlineCopiesVisible(liId)) {
1252 for (var liId in this.liCache) {
1253 var row = dojo.byId('acq-inline-copies-row-' + liId);
1255 if (!row || row._hidden) {
1256 this.drawInlineCopies(liId);
1258 } else { // hide all
1260 // drawInlineCopies() on a visible row will hide it.
1261 this.drawInlineCopies(liId);
1268 this.inlineCopiesVisible = function(liId) {
1269 var row = dojo.byId('acq-inline-copies-row-' + liId);
1270 return (row && !row._hidden);
1273 this.refreshInlineCopies = function(all, reFetch) {
1275 var liIds = this.inlineCopiesNeedingRefresh;
1276 if (all) liIds = openils.Util.objectProperties(liCache);
1277 liIds.forEach(function(liId) {
1278 if (self.inlineCopiesVisible(liId)) {
1279 self.drawInlineCopies(liId, reFetch); // hide
1280 self.drawInlineCopies(liId, reFetch); // re-draw
1285 // draw inline copy table. if the table is
1286 // already visible, hide the table as-is
1287 // reFetch forces a retrieval of the lineitem and
1288 // copies from the server. otherwise the locally
1289 // cached version of each is used.
1290 this.drawInlineCopies = function(liId, reFetch) {
1293 // find or create the row where the inline copies table will live
1294 var containerRow = dojo.byId('acq-inline-copies-row-' + liId);
1295 var liRow = dojo.query('[li=' + liId + ']')[0];
1297 if (!containerRow) {
1299 // build the inline copies container row and add it to
1300 // the DOM directly after the primary lineitem row
1302 containerRow = self.inlineCopyContainer.cloneNode(true);
1303 containerRow.id = 'acq-inline-copies-row-' + liId;
1305 if (liRow.nextSibling) {
1306 self.tbody.insertBefore(containerRow, liRow.nextSibling);
1308 self.tbody.appendChild(containerRow);
1313 // toggle the visible state
1314 containerRow._hidden = !containerRow._hidden;
1315 openils.Util.toggle(containerRow, 'table-row');
1317 if (containerRow._hidden) return; // hide only
1320 var handler = function(li) {
1322 var tbody = dojo.query(
1323 '[name=acq-li-inline-copies-tbody]',
1326 // reset the table before adding copy rows
1327 while (tbody.childNodes[0])
1328 tbody.removeChild(tbody.childNodes[0]);
1330 if(li.lineitem_details().length == 0) {
1332 self.inlineNoCopies.cloneNode(true));
1333 return; // no copies to show
1336 // add a row to the inline copy table for each copy
1337 dojo.forEach(li.lineitem_details(),
1339 var row = self.inlineCopyTemplate.cloneNode(true);
1340 tbody.appendChild(row);
1341 self.addInlineCopy(li, copy, row);
1346 this._fetchLineitem(liId, handler, reFetch);
1349 /** Draw read-only copy widgets for inline copies */
1350 this.addInlineCopy = function(li, copy, row) {
1353 dojo.forEach(liDetailFields,
1356 var widget = new openils.widget.AutoFieldWidget({
1359 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1360 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1361 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1363 parentNode : dojo.query('[name=' + field + ']', row)[0],
1372 /* For a given list of lineitem ids, build a list of full lineitems
1373 * re-using the fetching logic that is otherwise typical to use in this
1376 * If we've already got a lineitem in the cache, just use that.
1378 * Once we've built a list of lineitems, call callback(thatlist).
1380 this.fetchLineitemsById = function(id_list, callback) {
1381 var total = id_list.length;
1382 var result_list = [];
1384 var inner = function(li) {
1385 result_list.push(li)
1387 callback(result_list);
1390 id_list.forEach(function(id) { self._fetchLineitem(id, inner); });
1393 this._fetchLineitem = function(liId, handler, force) {
1395 var li = this.liCache[liId];
1396 if(li && li.marc() && li.lineitem_details() && !force)
1399 fieldmapper.standardRequest(
1400 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
1403 params: [self.authtoken, liId, {
1405 flesh_cancel_reason: true,
1406 flesh_li_details: true,
1408 flesh_fund_debit: true }],
1410 oncomplete: function(r) {
1411 var li = openils.Util.readResponse(r);
1412 self.liCache[liId] = li;
1419 this._drawInfo = function(li) {
1421 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
1423 if(li.eg_bib_id()) {
1424 openils.Util.hide('acq-lit-marc-order-record-label');
1425 openils.Util.hide(acqLitEditOrderMarc.domNode);
1426 openils.Util.show('acq-lit-marc-real-record-label');
1428 openils.Util.show('acq-lit-marc-order-record-label');
1429 openils.Util.show(acqLitEditOrderMarc.domNode);
1430 openils.Util.hide('acq-lit-marc-real-record-label');
1433 this.drawMarcHTML(li);
1434 this.infoTbody = dojo.byId('acq-lit-info-tbody');
1437 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
1438 while(this.infoTbody.childNodes[0])
1439 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
1441 for(var i = 0; i < li.attributes().length; i++) {
1442 var attr = li.attributes()[i];
1443 var row = this.infoRow.cloneNode(true);
1445 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
1446 var name = openils.acq.Lineitem.attrDefs[type].filter(
1448 return (a.code() == attr.attr_name());
1450 ).pop().description();
1452 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
1453 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
1454 this.infoTbody.appendChild(row);
1457 if (!this._isRelatedViewer) {
1458 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
1459 oilsBasePath + "/acq/lineitem/related/" + li.id();
1462 // if a top scroll point is defined, jump up to it here
1463 var node = dojo.byId('oils-scroll-to-top');
1464 if (node) dijit.scrollIntoView(node);
1467 this.generateMakeRecTab = function(bib_id,default_view, row) {
1471 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
1474 show_nav_buttons : true,
1475 show_print_button : true,
1476 opac_url : xulG.url_prefix('opac_rdetail|' + bib_id),
1477 default_view : default_view
1481 if(row) nodeByName("action_none", row).selected = true;
1485 this.drawMarcHTML = function(li) {
1486 var params = [null, true, li.marc()];
1488 params = [li.eg_bib_id(), true];
1490 fieldmapper.standardRequest(
1491 ['open-ils.search', 'open-ils.search.biblio.record.html'],
1494 oncomplete: function(r) {
1495 dojo.byId('acq-lit-marc-div').innerHTML =
1496 openils.Util.readResponse(r);
1502 this.drawCopies = function(liId, force_fetch) {
1503 this.focusLineitem = liId;
1504 if (typeof force_fetch == "undefined")
1505 force_fetch = false;
1507 var cgi = new openils.CGI();
1508 var source = cgi.param('source');
1509 if (source && source.match(/invoice/)) {
1510 // got here from the invoice page, show the 'return-to-invoice' button
1511 var cgi = new openils.CGI({url : source});
1512 cgi.param('focus_li', liId);
1513 openils.Util.show(dojo.byId('acq-lit-copies-back-to-invoice-button-wrapper'), 'inline');
1514 var button = dojo.byId('acq-lit-copies-back-to-invoice-button');
1515 button.onclick = function() { location.href = cgi.url() };
1518 openils.acq.Lineitem.fetchAndRender(liId, {},
1519 function(li, html) {
1520 dojo.byId('acq-lit-copies-li-summary').innerHTML = html;
1524 this.show('copies');
1526 this.copyCache = {};
1527 this.copyWidgetCache = {};
1528 this.oldCopyWidgetCache = {};
1529 this.virtDfaCounts = {};
1530 this.realDfaCache = {};
1533 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
1534 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
1535 acqLitCopyCountInput.attr('value', '0');
1537 while(this.copyTbody.childNodes[0])
1538 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
1540 this._drawBatchCopyWidgets();
1542 this._drawDistribApplied(liId);
1544 this._fetchDistribFormulas(
1546 openils.acq.Lineitem.fetchAttrDefs(
1548 self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch);
1555 this._saveDistribAppliedTemplates = function() {
1556 if (!this._appliedDistribTemplate) {
1557 this._appliedDistribTemplate =
1558 dojo.byId("acq-lit-distrib-applied-tbody").
1559 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
1560 dojo.attr(this._appliedDistribTemplate, "id");
1564 this._drawDistribApplied = function(liId) {
1565 /* Build this table while hidden to prevent rendering artifacts */
1566 openils.Util.hide("acq-lit-distrib-applied-tbody");
1568 this._saveDistribAppliedTemplates();
1570 /* Remove any rows in the table from previous populations */
1571 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
1572 forEach(dojo.destroy);
1574 /* Unregister all dijits previously created (for some reason this isn't
1575 * covered by the above destroy calls). */
1576 dijit.registry.forEach(
1577 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
1580 /* Populate the table with our liId */
1582 fieldmapper.standardRequest(
1584 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
1587 "params": [self.authtoken, liId],
1588 "onresponse": function(r) {
1589 var dfa = openils.Util.readResponse(r);
1592 self.realDfaCache[dfa.id()] = dfa;
1593 self._drawDistribAppliedUnit(dfa);
1596 "oncomplete": function() {
1597 /* Reveal built table */
1600 "acq-lit-distrib-applied-tbody", "table-row-group"
1608 this._drawDistribAppliedUnit = function(dfa) {
1609 var new_row = false;
1610 var row = dojo.query(
1611 'tr[formula="' + dfa.formula().id() + '"]',
1612 "acq-lit-distrib-applied-tbody"
1617 row = dojo.clone(this._appliedDistribTemplate);
1618 dojo.attr(row, "formula", dfa.formula().id());
1619 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
1622 var td = dojo.query("td", row)[0];
1624 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1625 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1628 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1630 new dijit.form.Button(
1632 "onClick": function() {
1633 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1634 self.deleteDfa(dfa);
1637 /* XXX I /cannot/ make the following work in as a CSS class
1638 * for some reason. So frustrating... */
1639 "style": function(id) {
1641 "font-weight: bold; color: #c00;" :
1643 }(dfa.id()) + "margin: 0 6px;display: inline;"
1644 }, "dfa-button-" + dfa.id()
1648 "connectId": ["dfa-button-" + dfa.id()],
1649 "label": dojo.string.substitute(
1650 localeStrings.DFA_TIP, dfa.id() > 0 ? [
1651 openils.User.formalName(dfa.creator()),
1652 dojo.date.locale.format(
1653 dojo.date.stamp.fromISOString(dfa.create_time()),
1654 {"formatLength":"short"}
1656 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
1658 }, "dfa-tip-" + dfa.id()
1662 this.deleteDfa = function(dfa) {
1663 if (dfa.id() > 0) { /* real */
1664 this.pcrud.eliminate(
1667 "oncomplete": function() {
1668 self._removeDistribApplied(dfa.id());
1669 delete self.realDfaCache[dfa.id()];
1673 } else { /* virtual */
1674 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
1675 this.virtDfaCounts[dfa.formula().id()] = 0;
1676 /* hasn't been saved yet, so no need to do anything server side */
1677 this._removeDistribApplied(dfa.id());
1682 this._removeDistribApplied = function(dfaId) {
1683 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
1684 dijit.registry.forEach(
1685 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
1687 this._removeDistribAppliedEmptyRows();
1690 this._removeAllDistribAppliedVirtual = function() {
1691 /* Unregister dijits */
1692 dijit.registry.forEach(
1693 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
1695 this._removeDistribAppliedEmptyRows();
1698 this._removeDistribAppliedEmptyRows = function() {
1699 /* Remove any rows with no DFA at all */
1700 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
1702 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
1708 * Insert a new row into the distribution formula selection form
1710 this._addDistribFormulaRow = function() {
1713 if (!self.distribForms) {
1714 // no formulas, hide the form
1715 openils.Util.hide('acq-lit-distrib-formula-table');
1719 if(!this.distribFormulaTemplate)
1720 this.distribFormulaTemplate =
1721 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
1723 var row = this.distribFormulaTemplate.cloneNode(true);
1724 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
1726 this.dfSelector = new dijit.form.FilteringSelect(
1727 {"labelAttr": "dynLabel", "labelType": "html"},
1728 nodeByName("selector", row)
1730 this._updateFormulaStore();
1731 this.dfSelector.fetchProperties =
1732 {"sort": [{"attribute": "use_count", "descending": true}]};
1734 var apply = new dijit.form.Button(
1735 {"label": localeStrings.APPLY},
1736 nodeByName('set_button', row)
1739 var reset = new dijit.form.Button(
1740 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
1741 nodeByName("reset_button", row)
1744 dojo.connect(apply, 'onClick',
1746 var form_id = self.dfSelector.attr("value");
1747 if(!form_id) return;
1748 self._applyDistribFormula(form_id);
1749 reset.attr("disabled", false);
1753 dojo.connect(reset, 'onClick',
1755 self.restoreCopyFieldsBeforeDF();
1756 self.virtDfaCounts = {};
1757 self.virtDfaId = -1;
1759 self._updateFormulaStore();
1760 self._removeAllDistribAppliedVirtual();
1761 reset.attr("disabled", "true");
1768 * Applies a distrib formula to the current set of copies
1770 this._applyDistribFormula = function(formula) {
1771 if(!formula) return;
1773 formula = this.distribForms.filter(
1774 function(form) { return form.id() == formula; }
1777 var copyRows = dojo.query('tr', self.copyTbody);
1779 if (this.dfeOffset >= copyRows.length) {
1780 alert(localeStrings.OUT_OF_COPIES);
1784 var entries_applied = 0;
1786 var rowIndex = this.dfeOffset;
1787 rowIndex < copyRows.length;
1791 var row = copyRows[rowIndex];
1792 var copy_id = row.getAttribute('copy_id');
1793 var copyWidgets = this.copyWidgetCache[copy_id];
1794 var entryIndex = this.dfeOffset;
1797 // find the correct entry for the current row
1798 dojo.forEach(formula.entries(),
1801 entryIndex += e.item_count();
1802 if(entryIndex > rowIndex)
1810 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
1811 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
1814 this.saveCopyFieldsBeforeDF(copy_id);
1815 this._copy_fields_for_acqdf.forEach(
1817 if(entry[field]()) {
1818 copyWidgets[field].attr('value', (entry[field]()));
1825 if (entries_applied) {
1826 this.virtDfaCounts[formula.id()] =
1827 ++(this.virtDfaCounts[formula.id()]) || 1;
1828 this._updateFormulaStore();
1829 this._drawDistribAppliedUnit(
1831 var dfa = new acqdfa();
1832 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
1835 this.dfeOffset += entries_applied;
1840 * This function updates the DF store for the dropdown so that use_counts
1841 * can reflect DF applications from this session before they're saved
1844 this._updateFormulaStore = function() {
1845 this.dfSelector.store = new dojo.data.ItemFileReadStore(
1847 "data": self._labelFormulasWithCounts(
1848 acqdf.toStoreData(self.distribForms)
1854 this.saveCopyFieldsBeforeDF = function(copy_id) {
1856 if (!this.oldCopyWidgetCache[copy_id]) {
1857 var copyWidgets = this.copyWidgetCache[copy_id];
1859 this.oldCopyWidgetCache[copy_id] = {};
1860 this._copy_fields_for_acqdf.forEach(
1862 self.oldCopyWidgetCache[copy_id][f] =
1863 copyWidgets[f].attr("value");
1869 this.restoreCopyFieldsBeforeDF = function() {
1871 for (var copy_id in this.oldCopyWidgetCache) {
1872 this._copy_fields_for_acqdf.forEach(
1874 self.copyWidgetCache[copy_id][f].attr(
1875 "value", self.oldCopyWidgetCache[copy_id][f]
1882 this._labelFormulasWithCounts = function(store_data) {
1883 for (var key in store_data.items) {
1884 var obj = store_data.items[key];
1885 obj.use_count = Number(obj.use_count); /* needed for sorting */
1887 if (this.virtDfaCounts[obj.id])
1888 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
1890 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
1891 obj.use_count + "]</span> " + obj.name;
1897 * This method formerly would not refetch the DF formulas if they'd been
1898 * loaded already, but now it always re-fetches, since use_count changes.
1900 /** TODO: port distrib-formula selector to autofieldwidget+pcrud/dojo store */
1901 this._fetchDistribFormulas = function(onload) {
1902 fieldmapper.standardRequest(
1904 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
1907 "params": [openils.User.authtoken, 0, 500],
1908 "oncomplete": function(r) {
1909 self.distribForms = openils.Util.readResponse(r);
1910 if(!self.distribForms || self.distribForms.length == 0) {
1911 self.distribForms = [];
1913 self._addDistribFormulaRow();
1920 this._drawBatchCopyWidgets = function() {
1921 var row = this.copyBatchRow;
1922 dojo.forEach(liDetailBatchFields,
1924 if(self.copyBatchRowDrawn) {
1925 self.copyBatchWidgets[field].attr('value', null);
1927 var widget = new openils.widget.AutoFieldWidget({
1930 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1931 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1932 searchFilter : (field == 'fund') ? {"active": "t"} : null,
1933 parentNode : dojo.query('[name='+field+']', row)[0],
1934 orgLimitPerms : ['CREATE_PICKLIST'],
1937 "labelType": (field == "fund") ? "html" : null
1939 noCache: (field == "fund"),
1944 if (field == "fund" && w.store)
1945 self._ensureCSSFundClasses(w.store);
1946 self.copyBatchWidgets[field] = w;
1949 if (field == "fund") {
1951 widget.widget, "onChange", function(val) {
1952 self._updateFundSelectorStyle(widget, val);
1959 this.copyBatchRowDrawn = true;
1962 this.batchCopyUpdate = function() {
1964 for(var k in this.copyWidgetCache) {
1965 var cache = this.copyWidgetCache[k];
1966 dojo.forEach(liDetailBatchFields, function(f) {
1967 var newval = self.copyBatchWidgets[f].attr('value');
1968 if(newval) cache[f].attr('value', newval);
1973 this._drawCopies = function(li) {
1976 // this button sets the total number of copies for a given lineitem
1977 acqLitAddCopyCount.onClick = function() {
1978 var count = acqLitCopyCountInput.attr('value');
1981 while(self.copyCount() < count)
1984 // delete rows if necessary
1985 var diff = self.copyCount() - count;
1987 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
1988 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
1989 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
1991 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1997 if(li.lineitem_details().length > 0) {
1998 dojo.forEach(li.lineitem_details(),
2000 self.addCopy(li, copy);
2008 this.copyCount = function() {
2010 for(var id in this.copyCache) {
2011 if(!this.copyCache[id].isdeleted())
2017 this.virtCopyId = -1;
2018 this.addCopy = function(li, copy) {
2019 var row = this.copyRow.cloneNode(true);
2020 this.copyTbody.appendChild(row);
2024 copy = new fieldmapper.acqlid();
2026 copy.id(this.virtCopyId--);
2027 copy.lineitem(li.id());
2030 this.copyCache[copy.id()] = copy;
2031 row.setAttribute('copy_id', copy.id());
2032 self.copyWidgetCache[copy.id()] = {};
2034 acqLitCopyCountInput.attr('value', self.copyCount()+'');
2036 var rcvr = copy.receiver();
2038 if (!userCache[rcvr]) {
2039 if(rcvr == openils.User.user.id()) {
2040 userCache[rcvr] = openils.User.user;
2042 userCache[rcvr] = fieldmapper.standardRequest(
2043 ['open-ils.actor', 'open-ils.actor.user.retrieve'],
2044 {params: [openils.User.authtoken, rcvr]}
2048 dojo.query('[name=receiver]', row)[0].innerHTML = userCache[rcvr].usrname();
2051 dojo.forEach(liDetailFields,
2054 if (field == "fund") {
2055 searchFilter = (copy.fund() ?
2056 {"-or": {"active": "t", "id": copy.fund()}} :
2059 searchFilter = null;
2062 var readOnly = false;
2064 // TODO: Add support for changing the owning_lib after real copies have been made.
2065 // owning_lib is order data as much as its item data
2066 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
2070 // TODO: add support for changing the fund after debits have been created
2071 // Note: invoicing allows the change
2072 if(copy.fund_debit() && field == 'fund') {
2077 var widget = new openils.widget.AutoFieldWidget({
2080 labelFormat : (field == 'fund') ? fundLabelFormat : null,
2081 searchFormat : (field == 'fund') ? fundSearchFormat : null,
2082 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
2083 searchFilter : searchFilter,
2084 noCache: (field == "fund"),
2086 parentNode : dojo.query('[name='+field+']', row)[0],
2087 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2088 readOnly : readOnly,
2089 orgDefaultsToWs : true
2093 // make sure we capture the value from any async widgets
2096 if (field == "fund" && w.store)
2097 self._ensureCSSFundClasses(w.store);
2100 copy[field](ww.getFormattedValue())
2102 self.copyWidgetCache[copy.id()][field] = w;
2104 dojo.connect(w, 'onChange',
2106 if (field == "fund")
2107 self._updateFundSelectorStyle(widget, val);
2109 if (!readOnly && (copy.isnew() || val != copy[field]())) {
2110 // prevent setting ischanged() automatically on widget load for existing copies
2111 copy[field](widget.getFormattedValue())
2112 copy.ischanged(true);
2121 this.updateLidState(copy, row);
2124 this._ensureCSSFundClass = function(id) {
2125 if (!this.fundStyleSheet) {
2127 "style", {"type": "text/css"},
2128 document.getElementsByTagName("head")[0], "last"
2130 this.fundStyleSheet = document.styleSheets[
2131 document.styleSheets.length - 1
2135 var cn = "fund_" + id;
2136 if (!this.haveFundClass[cn]) {
2137 fieldmapper.standardRequest(
2138 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
2140 "params": [openils.User.authtoken, id],
2142 "oncomplete": function(r) {
2143 r = openils.Util.readResponse(r);
2144 self.fundBalanceState[id] = r;
2146 if (r[0] /* stop */)
2147 style = fundStyles.stop;
2148 else if (r[1] /* warning */)
2149 style = fundStyles.warning;
2150 self.fundStyleSheet.insertRule(
2151 "." + cn + " { " + style + " }",
2152 self.fundStyleSheet.cssRules.length
2154 self.haveFundClass[cn] = true;
2161 this._ensureCSSFundClasses = function(store) {
2163 "query": {"id": "*"},
2164 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
2168 this._updateFundSelectorStyle = function(widget, fund_id) {
2169 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
2170 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
2173 this.updateLidState = function(copy, row) {
2176 if (typeof(row) == "undefined") {
2177 row = dojo.query('tr[copy_id="' + copy.id() + '"]', this.copyTbody)[0];
2181 var recv_link = nodeByName("receive", row);
2182 var unrecv_link = nodeByName("unreceive", row);
2183 var del_link = nodeByName("delete", row);
2184 var cxl_link = nodeByName("cancel", row);
2185 var claim_link = nodeByName("claim", row);
2186 var cxl_reason_link = nodeByName("cancel_reason", row);
2188 // by default, hide all the actions
2189 openils.Util.hide(del_link.parentNode);
2190 openils.Util.hide(recv_link);
2191 openils.Util.hide(unrecv_link);
2192 openils.Util.hide(cxl_link);
2193 openils.Util.hide(claim_link);
2194 openils.Util.hide(cxl_reason_link);
2196 if (copy.id() > 0) { // real copies (LIDs)
2198 if (copy.cancel_reason()) {
2200 /* --------- cancelled -------------------------- */
2202 /* XXX the following may leak memory in a long lived table:
2203 * dijits may not get destroyed... not positive. revisit. */
2204 var holds_reason = dojo.create(
2206 "style": "border-bottom: 1px dashed #000;",
2207 "innerHTML": "Cancelled" /* XXX [sic] and i18n */
2208 }, cxl_reason_link, "only"
2212 "label": "<em>" + copy.cancel_reason().label() +
2213 "</em><br />" + copy.cancel_reason().description(),
2214 "connectId": [holds_reason]
2215 }, dojo.create("span", null, cxl_reason_link, "last")
2217 openils.Util.show(cxl_reason_link, "inline");
2219 } else if (copy.recv_time()) {
2221 /* --------- received -------------------------- */
2223 openils.Util.show(unrecv_link, "inline");
2224 unrecv_link.onclick = function() {
2225 if (confirm(localeStrings.UNRECEIVE_LID))
2226 self.issueReceive(copy, /* rollback */ true);
2229 } else if (this.liCache[copy.lineitem()].state() == 'on-order') {
2231 /* --------- on order -------------------------- */
2233 openils.Util.show(recv_link, 'inline');
2234 openils.Util.show(cxl_link, "inline");
2236 recv_link.onclick = function() {
2237 if (self.checkLiAlerts(copy.lineitem()))
2238 self.issueReceive(copy);
2241 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2245 /* --------- pre-order copies -------------------------- */
2247 del_link.onclick = function() { self.deleteCopy(row) };
2248 openils.Util.show(del_link.parentNode);
2254 /* --------- virtual copies -------------------------- */
2256 del_link.onclick = function() { self.deleteCopy(row) };
2257 openils.Util.show(del_link.parentNode);
2261 this.cancelLid = function(lid_id) {
2262 lidCancelDialog._lid_id = lid_id;
2263 openils.Util.show(lidCancelDialog.domNode.parentNode);
2264 lidCancelDialog.show();
2265 if (!lidCancelDialog._prepared) {
2266 var widget = new openils.widget.AutoFieldWidget({
2267 "fmField": "cancel_reason",
2268 "fmClass": "acqlid",
2269 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
2270 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2275 acqLidCancelButton.onClick = function() {
2276 if (w.attr("value")) {
2277 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
2279 lidCancelDialog._lid_id,
2283 lidCancelDialog.hide();
2286 lidCancelDialog._prepared = true;
2292 this._cancelLid = function(lid_id, reason) {
2293 fieldmapper.standardRequest(
2294 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
2295 "params": [openils.User.authtoken, lid_id, reason],
2297 "onresponse": function(r) {
2298 if (r = openils.Util.readResponse(r)) {
2300 for (var id in r.lid) {
2301 /* actually this should only iterate once */
2302 self.copyCache[id].cancel_reason(
2303 r.lid[id].cancel_reason
2305 self.updateLidState(self.copyCache[id]);
2314 this._confirmAlert = function(li, lin) {
2316 dojo.string.substitute(
2317 localeStrings.CONFIRM_LI_ALERT, [
2318 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2319 "title", "lineitem_marc_attr_definition"
2321 /* XXX it's really better add a parameter and to adjust
2322 * the format string rather than do this concatenation
2323 * here, but if someone wants this for 2.2 in a hurry,
2324 * we can sidestep the problem of updating the strings
2325 * while the translators are working. */
2327 aou.findOrgUnit(lin.alert_text().owning_lib()).shortname() +
2329 lin.alert_text().code()
2331 lin.alert_text().description() || "",
2338 this.checkLiAlerts = function(li_id) {
2339 var li = this.liCache[li_id];
2341 var alert_notes = li.lineitem_notes().filter(
2342 function(o) { return Boolean(o.alert_text()); }
2345 /* this is _intentionally_ not done in a call to forEach() ... */
2346 for (var i = 0; i < alert_notes.length; i++) {
2347 if (this.noteAcks[alert_notes[i].id()])
2349 else if (!this._confirmAlert(li, alert_notes[i]))
2352 this.noteAcks[alert_notes[i].id()] = true;
2358 this.deleteCopy = function(row) {
2359 var copy = this.copyCache[row.getAttribute('copy_id')];
2360 copy.isdeleted(true);
2362 delete this.copyCache[copy.id()];
2363 this.copyTbody.removeChild(row);
2366 this._virtDfaCountsAsList = function() {
2368 for (var key in this.virtDfaCounts) {
2369 for (var i = 0; i < this.virtDfaCounts[key]; i++)
2375 this.confirmBreachedCopyFunds = function(copies) {
2376 var stop = 0, warning = 0;
2380 var state = self.fundBalanceState[o.fund()];
2381 if (state[0] /* stop */)
2383 else if (state[1] /* warning */)
2390 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
2391 } else if (warning) {
2392 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
2397 this.saveCopyChanges = function(liId) {
2403 for(var id in this.copyCache) {
2404 var c = this.copyCache[id];
2405 if(!c.isdeleted()) total++;
2406 if(c.isnew() || c.ischanged() || c.isdeleted()) {
2407 if(c.id() < 0) c.id(null);
2413 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
2416 if (copies.length > 0) {
2417 if (!this.confirmBreachedCopyFunds(copies))
2420 if (typeof(this._copy_count_cb) == "function")
2421 this._copy_count_cb(liId, total);
2423 openils.Util.show("acq-lit-update-copies-progress");
2424 fieldmapper.standardRequest(
2425 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
2427 params: [openils.User.authtoken, copies],
2428 onresponse: function(r) {
2429 var res = openils.Util.readResponse(r);
2430 litUpdateCopiesProgress.update(res);
2432 oncomplete: function() {
2433 self.drawCopies(liId, true /* force_fetch */);
2434 openils.Util.hide("acq-lit-update-copies-progress");
2440 var dfa_list = this._virtDfaCountsAsList();
2441 if (dfa_list.length > 0) {
2442 fieldmapper.standardRequest(
2444 "open-ils.acq.distribution_formula.record_application"],
2447 "params": [openils.User.authtoken, dfa_list, liId],
2448 "onresponse": function(r) {
2449 var res = openils.Util.readResponse(r);
2450 if (res && res.length < dfa_list.length)
2451 alert(localeStrings.DFA_NOT_ALL);
2455 this.virtDfaCounts = {};
2458 if (this.inlineCopiesNeedingRefresh.indexOf(liId) < 0)
2459 this.inlineCopiesNeedingRefresh.push(liId);
2462 this._updateCreatePoPrepayCheckbox = function(prepay) {
2463 var prepay = openils.Util.isTrue(prepay);
2464 this._prepayRequiredByVendor = prepay;
2465 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
2468 this._confirmPoPrepaySituation = function() {
2469 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
2470 if (want_prepay != this._prepayRequiredByVendor) {
2473 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
2474 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
2481 this.applySelectedLiAction = function(action) {
2485 case 'delete_selected':
2486 this._deleteLiList(self.getSelected());
2489 case 'add_to_order':
2490 addToPoDialog._get_li = dojo.hitch(
2492 function() { return this.getSelected(false, null, true); }
2494 addToPoDialog.show();
2497 case 'create_order':
2498 this._loadPOSelect();
2499 acqLitPoCreateDialog.show();
2502 case 'save_picklist':
2503 acqLitSavePlDialog.show();
2506 case 'selector_ready':
2508 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
2509 acqLitChangeLiStateDialog.show();
2517 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
2520 case 'batch_create_invoice':
2521 this.batchCreateInvoice();
2524 case 'batch_link_invoice':
2525 this.batchLinkInvoice();
2528 case 'receive_lineitems':
2529 this.receiveSelectedLineitems();
2532 case 'rollback_receive_lineitems':
2533 this.rollbackReceiveLineitems();
2536 case 'create_assets':
2537 this.showAssetCreator();
2540 case 'export_attr_list':
2541 this.chooseExportAttr();
2544 case 'batch_apply_funds':
2545 this.applyBatchLiFunds();
2548 case 'add_brief_record':
2550 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
2552 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
2556 case "cancel_lineitems":
2557 this.maybeCancelLineitems();
2560 case "apply_claim_policy":
2561 var li_list = this.getSelected();
2562 this.claimPolicyPicker.attr("value", null);
2563 liClaimPolicyDialog.show();
2564 liClaimPolicySave.onClick = function() {
2565 self.changeClaimPolicy(
2567 self.claimPolicyPicker.attr("value"),
2571 self.setClaimPolicyControl(li);
2572 self.reconsiderClaimControl(li);
2575 liClaimPolicyDialog.hide();
2583 this.changeClaimPolicy = function(li_list, value, callback) {
2585 function(li) { li.claim_policy(value); }
2587 fieldmapper.standardRequest(
2588 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
2589 "params": [openils.User.authtoken, li_list],
2591 "oncomplete": function(r) {
2592 r = openils.Util.readResponse(r);
2593 if (callback) callback(r);
2599 this.showAssetCreator = function(onAssetsCreated) {
2600 if(!this.isPO) return;
2603 // first, let's see if this PO has any LI's that need to be merged/imported
2604 self.pcrud.search('jub', {purchase_order : this.isPO, eg_bib_id : null}, {
2606 oncomplete : function(r) {
2607 var resp = openils.Util.readResponse(r);
2608 if (resp && resp.length) {
2609 // PO has some non-linked jubs.
2611 self.show('asset-creator');
2612 if(!self.vlAgent.loaded)
2613 self.vlAgent.init();
2615 dojo.connect(assetCreatorButton, 'onClick',
2616 function() { self.createAssets(onAssetsCreated) });
2620 // all jubs linked, move on to asset creation
2621 self.createAssets(onAssetsCreated, true);
2627 this.createAssets = function(onAssetsCreated, noVl) {
2628 this.show('acq-lit-progress-numbers');
2630 var vlArgs = (noVl) ? {} : {vandelay : this.vlAgent.values()};
2631 fieldmapper.standardRequest(
2632 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
2634 params: [this.authtoken, this.isPO, vlArgs],
2635 onresponse: function(r) {
2636 var resp = openils.Util.readResponse(r);
2637 self._updateProgressNumbers(resp, !Boolean(onAssetsCreated), onAssetsCreated);
2643 this.maybeCancelLineitems = function() {
2644 openils.Util.show("acq-lit-cancel-reason", "inline");
2645 if (!acqLitCancelLineitemsButton._prepared) {
2646 var widget = new openils.widget.AutoFieldWidget({
2647 "fmField": "cancel_reason",
2649 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
2650 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2655 acqLitCancelLineitemsButton.onClick = function() {
2656 if (w.attr("value")) {
2657 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
2658 self._cancelLineitems(w.attr("value"));
2660 openils.Util.hide("acq-lit-cancel-reason");
2663 acqLitCancelLineitemsButton._prepared = true;
2669 this._cancelLineitems = function(reason) {
2670 var id_list = this.getSelected().map(function(o) { return o.id(); });
2671 fieldmapper.standardRequest(
2672 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
2673 "params": [openils.User.authtoken, id_list, reason],
2675 "onresponse": function(r) {
2676 if (r = openils.Util.readResponse(r)) {
2678 for (var id in r.li) {
2679 self.liCache[id].state(r.li[id].state);
2680 self.liCache[id].cancel_reason(
2681 r.li[id].cancel_reason
2683 self.updateLiState(self.liCache[id]);
2686 if (r.lid && self.copyCache) {
2687 for (var id in r.lid) {
2688 if (self.copyCache[id]) {
2689 self.copyCache[id].cancel_reason(
2690 r.lid[id].cancel_reason
2692 self.updateLidState(self.copyCache[id]);
2702 this.chooseExportAttr = function() {
2703 if (!acqLitExportAttrSelector._li_setup) {
2705 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
2707 "data": acqlimad.toStoreData(
2709 "acqlimad", {"code": li_exportable_attrs}
2714 acqLitExportAttrSelector.setValue();
2715 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
2716 acqLitExportAttrSelector._li_setup = true;
2718 openils.Util.show("acq-lit-export-attr-holder", "inline");
2721 this.exportAttrList = function() {
2722 var attr_def = acqLitExportAttrSelector.item;
2723 var li_list = this.getSelected();
2724 var value_list = li_list.map(
2726 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2727 attr_def.code, "lineitem_marc_attr_definition"
2730 ).filter(function(attr) { return Boolean(attr); });
2732 if (value_list.length > 0) {
2733 if (value_list.length < li_list.length) {
2735 dojo.string.substitute(
2736 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
2743 openils.XUL.contentToFileSaveDialog(
2744 value_list.join("\n"),
2745 localeStrings.EXPORT_SAVE_DIALOG_TITLE
2751 alert(dojo.string.substitute(
2752 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
2756 openils.Util.hide("acq-lit-export-attr-holder");
2759 this.printPO = function() {
2760 if(!this.isPO) return;
2761 progressDialog.show(true);
2762 fieldmapper.standardRequest(
2763 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
2765 params: [this.authtoken, this.isPO, 'html'],
2766 oncomplete: function(r) {
2767 progressDialog.hide();
2768 var evt = openils.Util.readResponse(r);
2769 if(evt && evt.template_output()) {
2770 openils.Util.printHtmlString(evt.template_output().data());
2777 this.batchCreateInvoice = function() {
2778 var liIds = this.getSelected(false, null, true /* id_list */)
2779 if (!liIds.length) return;
2780 var path = oilsBasePath + '/acq/invoice/view?create=1';
2781 dojo.forEach(liIds, function(li, idx) { path += '&attach_li=' + li });
2782 if (openils.XUL.isXUL())
2783 openils.XUL.newTabEasy(path, localeStrings.NEW_INVOICE, null, true);
2785 location.href = path;
2788 this.batchLinkInvoice = function(create) {
2789 var liIds = this.getSelected(false, null, true /* id_list */)
2790 if (!liIds.length) return;
2791 if (!self.invoiceLinkDialogManager) {
2792 self.invoiceLinkDialogManager =
2793 new InvoiceLinkDialogManager("li");
2795 self.invoiceLinkDialogManager.target = liIds;
2796 acqLitLinkInvoiceDialog.show();
2799 this.receiveSelectedLineitems = function() {
2800 var li_list = this.getSelected();
2802 if (!li_list.length) {
2803 alert(localeStrings.NO_LI_GENERAL);
2807 for (var i = 0; i < li_list.length; i++) {
2808 var li = li_list[i];
2810 if (li.state() != "received" &&
2811 !this.checkLiAlerts(li.id())) return;
2814 this.show('acq-lit-progress-numbers');
2817 fieldmapper.standardRequest(
2818 ['open-ils.acq', 'open-ils.acq.lineitem.receive.batch'],
2822 li_list.map(function(li) { return li.id(); })
2824 onresponse : function(r) {
2825 var resp = openils.Util.readResponse(r);
2826 self._updateProgressNumbers(resp, true);
2832 this.issueReceive = function(obj, rollback) {
2834 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
2836 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
2838 progressDialog.show(true);
2839 fieldmapper.standardRequest(
2840 ["open-ils.acq", method], {
2842 "params": [this.authtoken, obj.id()],
2843 "onresponse": function(r) {
2844 if (r = openils.Util.readResponse(r)) {
2845 self.fetchClaimInfo(
2846 part == "lineitem" ? obj.id() : obj.lineitem(),
2848 function() { self.handleReceive(r); }
2850 progressDialog.hide();
2858 * Handles the responses from receive and rollback ML calls.
2860 this.handleReceive = function(resp) {
2863 for (var li_id in resp.li) {
2864 for (var key in resp.li[li_id])
2865 self.liCache[li_id][key](resp.li[li_id][key]);
2866 self.updateLiState(self.liCache[li_id]);
2870 if (typeof(self.poUpdateCallback) == "function")
2871 self.poUpdateCallback(resp.po);
2874 for (var lid_id in resp.lid) {
2875 for (var key in resp.lid[lid_id])
2876 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
2877 self.updateLidState(self.copyCache[lid_id]);
2883 this.rollbackReceiveLineitems = function() {
2884 var li_id_list = this.getSelected(false, null, true);
2885 if (!li_id_list.length) {
2886 alert(localeStrings.NO_LI_GENERAL);
2890 if (!confirm(localeStrings.ROLLBACK_LI_RECEIVE_CONFIRM)) return;
2892 this.show('acq-lit-progress-numbers');
2895 fieldmapper.standardRequest(
2896 ['open-ils.acq', 'open-ils.acq.lineitem.receive.rollback.batch'],
2898 params: [this.authtoken, li_id_list],
2899 onresponse : function(r) {
2900 var resp = openils.Util.readResponse(r);
2901 self._updateProgressNumbers(resp, true);
2907 this._updateProgressNumbers = function(resp, reloadOnComplete, onComplete) {
2908 this.vlAgent.handleResponse(resp,
2909 function(resp, res) {
2910 if(reloadOnComplete)
2911 location.href = location.href;
2913 onComplete(resp, res);
2919 this._createPO = function(fields) {
2920 var wantall = (fields.create_from == "all");
2922 /* If we're a picklist or purchase order already and the user wants
2923 * all lineitems, we might have pages' worth of lineitems haven't all
2924 * been loaded yet, so getSelected() won't find them. The server,
2925 * however, should know about all our lineitems, so let's ask the
2926 * server for a complete list.
2931 true, function(list) {
2932 self._createPOFromLineitems(fields, list);
2933 }, /* id_list */ true
2936 this._createPOFromLineitems(fields, this.getSelected(false, null, true /* id_list */));
2940 this._createPOFromLineitems = function(fields, selected) {
2941 if (selected.length == 0) return;
2944 var po = new fieldmapper.acqpo();
2945 po.provider(this.createPoProviderSelector.attr("value"));
2946 po.ordering_agency(this.createPoAgencySelector.attr("value"));
2947 po.prepayment_required(fields.prepayment_required[0] ? true : false);
2949 // if we're creating assets, delay the asset creation
2950 // until after the PO is created. This will allow us to
2951 // use showAssetCreator() directly.
2953 fieldmapper.standardRequest(
2954 ["open-ils.acq", "open-ils.acq.purchase_order.create"],
2957 openils.User.authtoken,
2958 po, {lineitems : selected}
2960 onresponse : function(r) {
2961 var resp = openils.Util.readResponse(r);
2962 if (resp.complete) {
2963 // self.isPO is needed for showAssetCreator();
2964 self.isPO = resp.purchase_order.id();
2965 var redir = oilsBasePath + "/acq/po/view/" + self.isPO;
2966 if (fields.create_assets[0]) {
2967 self.showAssetCreator(
2968 function() {location.href = redir}
2971 location.href = redir;
2980 this.batchFundWidget = null;
2982 this.applyBatchLiFunds = function() {
2984 var liIds = this.getSelected().map(function(li) { return li.id(); });
2985 if(liIds.length == 0) return; // warn?
2988 batchFundUpdateDialog.show();
2990 if(!this.batchFundWidget) {
2991 this.batchFundWidget = new openils.widget.AutoFieldWidget({
2993 selfReference : true,
2994 labelFormat : fundLabelFormat,
2995 searchFormat : fundSearchFormat,
2996 searchFilter : {"active": "t"},
2997 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
2998 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2999 dijitArgs : { "required": true, "labelType": "html" },
3002 this.batchFundWidget.build();
3005 dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
3006 dojo.connect(batchFundUpdateSubmit, 'onClick',
3009 // TODO: call .dry_run first to test thresholds
3010 fieldmapper.standardRequest(
3011 ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
3014 openils.User.authtoken,
3016 self.batchFundWidget.widget.attr('value')
3018 oncomplete : function(r) {
3019 var resp = openils.Util.readResponse(r);
3021 location.href = location.href;
3030 this._deleteLiList = function(list, idx) {
3031 if(idx == null) idx = 0;
3032 if(idx >= list.length) return;
3037 if (this.isPO && (li.state() == "on-order" || li.state() == "received")) {
3038 /* It makes little sense to delete a lineitem from a PO that has
3039 * already been marked 'on-order'. Especially if EDI is in use,
3040 * such a purchase order will probably have already been shipped
3041 * off to a vendor, and mucking with it at this point could leave
3042 * your data in a bad state that doesn't jive with reality.
3044 * I could see making this restriction even firmer.
3046 * I could also see adjusting the li state comparisons, extending
3047 * the comparison to the PO's state, and/or providing functions
3048 * that house the logic for comparing states in a single location.
3050 * Yes, this will be really annoying if you have selected a lot
3051 * of lineitems to cancel that have been ordered. You'll get a
3052 * confirm dialog for each one.
3055 if (!confirm(localeStrings.DEL_LI_FROM_PO)) {
3056 self._deleteLiList(list, ++idx); /* move on to next in list */
3061 fieldmapper.standardRequest(
3063 this.isPO ? 'open-ils.acq.purchase_order.lineitem.delete' : 'open-ils.acq.picklist.lineitem.delete'],
3065 params: [openils.User.authtoken, liId],
3066 oncomplete: function(r) {
3067 self.removeLineitem(liId);
3068 self._deleteLiList(list, ++idx);
3074 this.editOrderMarc = function(li) {
3076 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
3077 to true in about:config */
3079 if(openils.XUL.isXUL()) {
3080 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul','','chrome');
3082 win = window.open('/xul/server/cat/marcedit.xul','','chrome');
3086 record : {marc : li.marc(), "rtype": "bre"},
3088 label: 'Save Record', // XXX I18N
3089 func: function(xmlString) {
3091 fieldmapper.standardRequest(
3092 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
3094 params: [openils.User.authtoken, li],
3095 oncomplete: function(r) {
3096 openils.Util.readResponse(r);
3098 self.drawInfo(li.id())
3104 'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
3105 'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
3109 this._savePl = function(values) {
3111 (values.which == 'all'),
3112 function(list) { self._savePlFromLineitems(values, list); }
3116 this._savePlFromLineitems = function(values, selected) {
3117 openils.Util.show("acq-lit-generic-progress");
3119 if(values.new_name) {
3120 openils.acq.Picklist.create(
3121 {name: values.new_name},
3127 oilsBasePath + "/acq/picklist/view/" + id;
3132 } else if(values.existing_pl) {
3133 // update lineitems to use an existing picklist
3135 values.existing_pl, selected, 0,
3138 oilsBasePath + "/acq/picklist/view/" +
3145 this._updateLiState = function(values, state) {
3146 progressDialog.show(true);
3148 (values.which == 'all'),
3150 self._updateLiStateFromLineitems(values, state, list);
3155 this._updateLiStateFromLineitems = function(values, state, selected) {
3156 if(!selected.length) return;
3157 dojo.forEach(selected, function(li) {li.state(state);});
3158 self._updateLiList(null, selected, 0,
3159 // TODO consider inline updates for efficiency
3160 function() { location.href = location.href }
3164 this._updateLiList = function(pl, list, idx, oncomplete) {
3165 if(idx >= list.length) return oncomplete();
3167 if(pl != null) li.picklist(pl);
3168 litGenericProgress.update({maximum: list.length, progress: idx});
3169 new openils.acq.Lineitem({lineitem:li}).update(
3171 self._updateLiList(pl, list, ++idx, oncomplete);
3176 this._loadPOSelect = function() {
3177 if (!this.createPoProviderSelector) {
3178 var widget = new openils.widget.AutoFieldWidget({
3179 "fmField": "provider",
3181 "searchFilter": {"active": "t"},
3182 "parentNode": dojo.byId("acq-lit-po-provider"),
3184 "onChange": function() {
3186 self._updateCreatePoPrepayCheckbox(
3187 this.item.prepayment_required()
3193 widget.build(function(w) { self.createPoProviderSelector = w; });
3196 if (!this.createPoAgencySelector) {
3197 var widget = new openils.widget.AutoFieldWidget({
3198 "fmField": "ordering_agency",
3200 "parentNode": dojo.byId("acq-lit-po-agency"),
3201 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3203 widget.build(function(w) { self.createPoAgencySelector = w; });
3207 this.showRealCopyEditUI = function(li) {
3212 this._fetchLineitem(li.id(),
3214 li = self.liCache[li.id()] = fullLi;
3218 id : li.lineitem_details().map(
3219 function(item) { return item.eg_copy_id() }
3223 oncomplete : function(r) {
3225 var r_list = openils.Util.readResponse( r );
3226 for (var i = 0; i < r_list.length; i++) {
3227 var copy = r_list[i];
3228 var volId = copy.call_number();
3229 var volume = self.volCache[volId];
3231 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
3233 copy.call_number(volume);
3234 copyList.push(copy);
3237 xulG.volume_item_creator( { 'existing_copies' : copyList } );
3240 alert('error in oncomplete: ' + E);
3249 this.drawBibFinder = function(li) {
3252 var liWrapper = new openils.acq.Lineitem({lineitem:li});
3255 ['isbn', 'upc', 'issn', 'title', 'author'],
3257 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
3259 if(field == 'title' || field == 'author') {
3260 query += field +':' + val + ' ';
3262 query += 'identifier|' + field + ':' + val + ' ';
3269 oilsBasePath + '/acq/lineitem/findbib?query=' + escape(query),
3270 '', 'resizable,scrollbars=1,chrome');
3272 win.window.recordFound = function(bibId) {
3275 var attrs = li.attributes();
3276 li.attributes(null);
3277 li.eg_bib_id(bibId);
3279 fieldmapper.standardRequest(
3280 ["open-ils.acq", "open-ils.acq.lineitem.update"],
3282 "params": [openils.User.authtoken, li],
3284 "oncomplete": function(r) {
3285 if(openils.Util.readResponse(r)) {
3286 location.href = location.href;