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('openils.acq.Lineitem');
10 dojo.require('openils.acq.PO');
11 dojo.require('openils.acq.Picklist');
12 dojo.require('openils.widget.AutoFieldWidget');
13 dojo.require('dojo.data.ItemFileReadStore');
14 dojo.require('openils.widget.ProgressDialog');
15 dojo.require('openils.PermaCrud');
16 dojo.require("openils.widget.PCrudAutocompleteBox");
17 dojo.require('dijit.form.ComboBox');
18 dojo.require('openils.CGI');
20 if (!localeStrings) { /* we can do this because javascript doesn't have block scope */
21 dojo.requireLocalization('openils.acq', 'acq');
22 var localeStrings = dojo.i18n.getLocalization('openils.acq', 'acq');
24 const XUL_OPAC_WRAPPER = 'chrome://open_ils_staff_client/content/cat/opac.xul';
25 var li_exportable_attrs = ["issn", "isbn", "upc"];
27 var fundLabelFormat = [
28 '<span class="fund_${0}">${1} (${2})</span>', 'id', 'code', 'year'
30 var fundSearchFormat = ['${0} (${1})', 'code', 'year'];
32 function nodeByName(name, context) {
33 return dojo.query('[name='+name+']', context)[0];
36 // for caching linked users. e.g. lineitem_detail.receiver
39 var liDetailBatchFields = ['fund', 'owning_lib', 'location', 'collection_code', 'circ_modifier', 'cn_label'];
40 var liDetailFields = liDetailBatchFields.concat(['barcode', 'note']);
42 "stop": "color: #c00; font-weight: bold;",
43 "warning": "color: #c93;"
46 function AcqLiTable() {
53 this.haveFundClass = {}
54 this.fundBalanceState = {};
55 this.realDfaCache = {};
56 this.virtDfaCounts = {};
59 this.claimEligibleLidByLi = {};
60 this.claimEligibleLid = {};
61 this.toggleState = false;
62 this.tbody = dojo.byId('acq-lit-tbody');
65 this.authtoken = openils.User.authtoken;
66 this.pcrud = new openils.PermaCrud();
67 this.rowTemplate = this.tbody.removeChild(dojo.byId('acq-lit-row'));
68 this.copyTbody = dojo.byId('acq-lit-li-details-tbody');
69 this.copyRow = this.copyTbody.removeChild(dojo.byId('acq-lit-li-details-row'));
70 this.copyBatchRow = dojo.byId('acq-lit-li-details-batch-row');
71 this.copyBatchWidgets = {};
72 this.liNotesTbody = dojo.byId('acq-lit-notes-tbody');
73 this.liNotesRow = this.liNotesTbody.removeChild(dojo.byId('acq-lit-notes-row'));
74 this.realCopiesTbody = dojo.byId('acq-lit-real-copies-tbody');
75 this.realCopiesRow = this.realCopiesTbody.removeChild(dojo.byId('acq-lit-real-copies-row'));
76 this._copy_fields_for_acqdf = ['owning_lib', 'location'];
77 this.skipInitialEligibilityCheck = false;
78 this.claimDialog = new ClaimDialogManager(
79 liClaimDialog, finalClaimDialog, this.claimEligibleLidByLi,
80 function(li) { /* callback that fires when claims are made */
81 self.fetchClaimInfo(li.id(), /* force update */ true);
84 this.vlAgent = new VLAgent();
86 if (dojo.byId('acq-lit-apply-idents')) {
87 dojo.byId('acq-lit-apply-idents').onclick = function() {
88 self.applyOrderIdentValues();
92 this.focusLineitem = new openils.CGI().param('focus_li');
94 dojo.byId("acq-lit-li-actions-selector").onchange = function() {
95 self.applySelectedLiAction(this.options[this.selectedIndex].value);
96 this.selectedIndex = 0;
99 acqLitCreatePoSubmit.onClick = function() {
100 if (!self.createPoProviderSelector.attr("value") ||
101 !self.createPoAgencySelector.attr("value")) {
102 alert(localeStrings.CREATE_PO_INVALID);
104 } else if (self._confirmPoPrepaySituation()) {
105 acqLitPoCreateDialog.hide();
106 self._createPO(acqLitPoCreateDialog.getValues());
112 acqLitSavePlButton.onClick = function() {
113 acqLitSavePlDialog.hide();
114 self._savePl(acqLitSavePlDialog.getValues());
117 acqLitCancelLiStateButton.onClick = function() {
118 acqLitChangeLiStateDialog.hide();
120 acqLitSaveLiStateButton.onClick = function() {
121 acqLitChangeLiStateDialog.hide();
122 self._updateLiState(acqLitChangeLiStateDialog.getValues(), acqLitChangeLiStateDialog.attr('state'));
126 dojo.byId('acq-lit-select-toggle').onclick = function(){self.toggleSelect()};
127 dojo.byId('acq-lit-info-back-button').onclick = function(){self.show('list')};
128 dojo.byId('acq-lit-copies-back-button').onclick = function(){self.show('list')};
129 dojo.byId('acq-lit-notes-back-button').onclick = function(){self.show('list')};
130 dojo.byId('acq-lit-real-copies-back-button').onclick = function(){self.show('list')};
132 this.reset = function(keep_selectors) {
133 while(self.tbody.childNodes[0])
134 self.tbody.removeChild(self.tbody.childNodes[0]);
142 this.setNext = function(handler) {
143 var link = dojo.byId('acq-lit-next');
145 dojo.style(link, 'visibility', 'visible');
146 link.onclick = handler;
148 dojo.style(link, 'visibility', 'hidden');
152 this.setPrev = function(handler) {
153 var link = dojo.byId('acq-lit-prev');
155 dojo.style(link, 'visibility', 'visible');
156 link.onclick = handler;
158 dojo.style(link, 'visibility', 'hidden');
163 * Ensures this.focusLineitem is in view and causes a brief
164 * border around the lineitem to come to life then fade.
166 this.focusLi = function() {
167 if (!this.focusLineitem) return;
169 // set during addLineitem()
170 var node = dojo.byId('li-title-ref-' + this.focusLineitem);
172 // LI may not yet be rendered
175 // prevent numerous re-focuses
176 this.focusLineitem = null;
178 // causes the full row to be visible
179 dijit.scrollIntoView(node);
182 dojo.query('[attr=title]', node)[0].focus();
184 dojo.require('dojox.fx');
188 dojox.fx.highlight({color : '#BB4433', node : node, duration : 2000}).play();
193 this.show = function(div) {
194 openils.Util.hide('acq-lit-table-div');
195 openils.Util.hide('acq-lit-info-div');
196 openils.Util.hide('acq-lit-li-details');
197 openils.Util.hide('acq-lit-notes-div');
198 openils.Util.hide('acq-lit-real-copies-div');
199 openils.Util.hide('acq-lit-asset-creator');
202 openils.Util.show('acq-lit-table-div');
206 openils.Util.show('acq-lit-info-div');
209 openils.Util.show('acq-lit-li-details');
212 openils.Util.show('acq-lit-real-copies-div');
215 openils.Util.show('acq-lit-notes-div');
217 case 'asset-creator':
218 openils.Util.show('acq-lit-asset-creator');
222 openils.Util.show(div);
226 this.hide = function() {
230 this.toggleSelect = function() {
232 dojo.forEach(self.selectors, function(i){i.checked = false});
234 dojo.forEach(self.selectors, function(i){i.checked = true});
235 self.toggleState = !self.toggleState;
239 this.getAll = function(callback, id_only) {
240 /* For some uses of the li table, we may not really know about "all"
241 * the lineitems that the user thinks we know about. If we're a paged
242 * picklist, for example, we only know about the lineitems we've
243 * displayed, but not necessarily all the lineitems on the picklist.
244 * So we reach out to pcrud to inform us.
247 var oncomplete = function(r) {
248 var id_list = openils.Util.readResponse(r);
252 self.fetchLineitemsById(id_list, callback);
257 "jub", {"picklist": this.isPL}, {
258 "id_list": true, /* sic, even if id_only */
260 "oncomplete": oncomplete
264 } else if (this.isPO) {
266 "jub", {"purchase_order": this.isPO}, {
269 "oncomplete": oncomplete
273 } else if (this.isUni && this.pager) {
274 this.pager.getAllLineitemIDs(oncomplete);
278 /* If execution reaches this point, we don't need or can't perform
279 * any special tricks to find out the "real" list of "all" lineitems
280 * in this context, so we fall back to the old method.
282 callback(this.getSelected(true, null, id_only));
285 /** @param all If true, assume all are selected */
286 this.getSelected = function(
288 callback /* If you want a "good" idea of "all" lineitems, you must
289 provide a callback that accepts an array parameter, rather than
290 relying on the return value of this method itself. */,
294 return this.getAll(callback, id_only);
296 var indices = {}; /* use to uniqify. needed in paging situations. */
297 dojo.forEach(this.selectors,
300 indices[i.parentNode.parentNode.getAttribute('li')] = true;
304 var result = openils.Util.objectProperties(indices);
307 result = result.map(function(liId) { return self.liCache[liId]; });
315 this.setRowAttr = function(td, liWrapper, field, type) {
316 var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
317 td.appendChild(document.createTextNode(val));
320 this.setClaimPolicyControl = function(li, row) {
321 if (!self.claimPolicyPicker) {
322 self.claimPolicyPicker = true; /* prevents a race condition */
323 new openils.widget.AutoFieldWidget({
324 "parentNode": "acq-lit-li-claim-policy",
326 "selfReference": true,
327 "dijitArgs": {"required": true}
328 }).build(function(w) { self.claimPolicyPicker = w; });
331 if (!row) row = this._findLiRow(li);
333 var actViewPolicy = nodeByName("action_view_claim_policy", row);
334 if (li.claim_policy())
335 actViewPolicy.innerHTML = localeStrings.CHANGE_CLAIM_POLICY;
337 if (!actViewPolicy.onclick) {
338 actViewPolicy.onclick = function() {
339 if (li.claim_policy())
340 self.claimPolicyPicker.attr("value", li.claim_policy());
341 liClaimPolicyDialog.show();
342 liClaimPolicySave.onClick = function() {
343 self.changeClaimPolicy(
344 [li], self.claimPolicyPicker.attr("value"),
346 self.setClaimPolicyControl(li, row);
347 self.reconsiderClaimControl(li, row);
348 liClaimPolicyDialog.hide();
356 this.fetchClaimInfo = function(liId, force, callback, row) {
358 liId, function(full) {
359 self.liCache[full.id()] = full;
360 self.checkClaimEligibility(full, callback, row);
366 * Inserts a single lineitem into the growing table of lineitems
367 * @param {Object} li The lineitem object to insert
369 this.addLineitem = function(li, skip_final_placement) {
370 this.liCache[li.id()] = li;
372 // insert the row right away so that final order isn't
373 // dependent on how long subsequent async request take
374 // for a given line item
375 var row = self.rowTemplate.cloneNode(true);
376 if (!skip_final_placement) {
377 self.tbody.appendChild(row);
379 self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
381 // sort the lineitem notes on edit_time
382 if(!li.lineitem_notes()) li.lineitem_notes([]);
384 var liWrapper = new openils.acq.Lineitem({lineitem:li});
385 row.setAttribute('li', li.id());
386 var tds = dojo.query('[attr]', row);
387 dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
388 dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
390 // so we can scroll to it later
391 dojo.query('[name=bib-info-cell]', row)[0].id = 'li-title-ref-' + li.id();
394 liWrapper.findAttr("isbn", "lineitem_marc_attr_definition") ||
395 liWrapper.findAttr("upc", "lineitem_marc_attr_definition");
397 // XXX media prefix for added content
399 nodeByName("jacket", row).setAttribute(
400 "src", "/opac/extras/ac/jacket/small/" + identifier
404 nodeByName("liid", row).innerHTML += li.id();
407 openils.Util.show(nodeByName('catalog', row), 'inline');
408 nodeByName("catalog_link", row).onclick = this.generateMakeRecTab(li.eg_bib_id());
410 openils.Util.show(nodeByName('link_to_catalog', row), 'inline');
411 nodeByName("link_to_catalog_link", row).onclick = function() { self.drawBibFinder(li) };
414 if (li.queued_record()) {
415 this.pcrud.retrieve('vqbr', li.queued_record(),
417 oncomplete : function(r) {
418 var qrec = openils.Util.readResponse(r);
419 openils.Util.show(nodeByName('queue', row), 'inline');
420 var link = nodeByName("queue_link", row);
421 link.onclick = function() {
422 // open a new tab to the vandelay queue for this record
423 openils.XUL.newTabEasy(
424 oilsBasePath + '/vandelay/vandelay?qtype=bib&qid=' + qrec.queue()
432 nodeByName("worksheet_link", row).href =
433 oilsBasePath + "/acq/lineitem/worksheet/" + li.id() +
434 '?source=' + encodeURIComponent(location.pathname + location.search)
436 nodeByName("show_requests_link", row).href =
437 oilsBasePath + "/acq/picklist/user_request?lineitem=" + li.id() +
438 '?source=' + encodeURIComponent(location.pathname + location.search)
440 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
441 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
442 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
444 this.drawOrderIdentSelector(li, row);
446 if (!this.skipInitialEligibilityCheck)
450 function(full) { self.setClaimPolicyControl(full, row) },
454 this.updateLiNotesCount(li, row);
456 // show which PO this lineitem is a member of
457 if(li.purchase_order() && !this.isPO) {
459 this.poCache[li.purchase_order()] =
460 this.poCache[li.purchase_order()] ||
461 fieldmapper.standardRequest(
462 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
464 this.authtoken, li.purchase_order(), {
465 "flesh_price_summary": true,
466 "flesh_provider" : true,
467 "flesh_lineitem_count": true
470 if(po && !this.isMeta) {
471 openils.Util.show(nodeByName('po', row), 'inline');
472 var link = nodeByName('po_link', row);
473 link.setAttribute('href', oilsBasePath +
474 '/acq/po/view/' + li.purchase_order() +
475 '?focus_li=' + li.id() +
476 '&source=' + encodeURIComponent(location.pathname + location.search)
478 link.innerHTML += po.name();
480 openils.Util.show(nodeByName('pro', row), 'inline');
481 link = nodeByName('pro_link', row);
482 link.setAttribute('href', oilsBasePath + '/conify/global/acq/provider/' + po.provider().id())
483 link.innerHTML += po.provider().code();
487 // show which picklist this lineitem is a member of
488 if(li.picklist() && (this.isPO || this.isMeta || this.isUni)) {
490 this.plCache[li.picklist()] =
491 this.plCache[li.picklist()] ||
492 fieldmapper.standardRequest(
493 ['open-ils.acq', 'open-ils.acq.picklist.retrieve.authoritative'],
494 {params: [this.authtoken, li.picklist()]});
496 if (pl.name() == "") {
497 openils.Util.show(nodeByName("bib_origin", row), "inline");
501 openils.Util.show(nodeByName('pl', row), 'inline');
502 var link = nodeByName('pl_link', row);
503 link.setAttribute('href', oilsBasePath +
504 '/acq/picklist/view/' + li.picklist() +
505 '?focus_li=' + li.id() +
506 '&source=' + encodeURIComponent(location.pathname + location.search)
508 link.innerHTML += pl.name();
513 var countNode = nodeByName('count', row);
514 var count = li.item_count() || 0;
515 if (typeof(this._copy_count_cb) == "function") {
516 this._copy_count_cb(li.id(), count);
518 countNode.innerHTML = count;
519 countNode.id = 'acq-lit-copy-count-label-' + li.id();
522 var priceInput = dojo.query('[name=price]', row)[0];
523 priceInput.value = li.estimated_unit_price() || '';
524 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
526 // show either "mark received" or "unreceive" as appropriate
527 this.updateLiState(li, row);
529 if (skip_final_placement) {
533 // the last LI may be rendered after the call to show('list'),
534 // so make sure it's focused if necessary.
535 if (this.focusLineitem == li.id())
539 this._liCountClaims = function(li) {
541 for (var i = 0; i < li.lineitem_details().length; i++)
542 total += li.lineitem_details()[i].claims().length;
546 this._findLiRow = function(li) {
547 return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
550 this.reconsiderClaimControl = function(li, row) {
551 if (!row) row = this._findLiRow(li);
552 var option = nodeByName("action_manage_claims", row);
553 var eligible = this.claimEligibleLidByLi[li.id()].length;
554 var count = this._liCountClaims(li);
556 option.disabled = !(count || eligible);
558 dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
559 option.onclick = function() { self.claimDialog.show(li); };
562 this.clearEligibility = function(li) {
563 this.claimEligibleLidByLi[li.id()] = [];
565 if (li.lineitem_details()) {
566 li.lineitem_details().forEach(
567 function(lid) { delete self.claimEligibleLid[lid.id()]; }
571 if (this.copyCache) {
573 for (var k in this.copyCache) {
574 if (this.copyCache[k].lineitem() == li.id())
578 function(k) { delete self.claimEligibleLid[k]; }
583 this.applyOrderIdentValues = function() {
584 this._identValuesInFlight =
585 openils.Util.objectProperties(this.liCache).length;
586 for (var liId in this.liCache) {
587 this._applyOrderIdentValue(this.liCache[liId]);
591 // returns true if request was sent
592 this._applyOrderIdentValue = function(li) {
595 console.log('applying ident value for lineitem ' + li.id());
598 var row = dojo.query('[li=' + li.id() + ']')[0];
600 // find the selected ident value
601 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
602 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
603 var name = typeSel.options[typeSel.selectedIndex].value;
604 var val = typeSel._cbox.attr('value');
606 console.log("selected ident is " + val);
608 // it differs from the existing ident value, update it
609 var oldIdent = self.getLiOrderIdent(li);
611 oldIdent.attr_name() == name &&
612 oldIdent.attr_value() == val) {
613 console.log('selected ident attr matches existing attr');
614 if (--this._identValuesInFlight == 0)
615 location.href = location.href;
619 // see if the selected ident value is represented
620 // by an existing lineitem attr
623 typeSel._cbox.store.fetch({
624 query : {attr_value : val},
625 onItem : function(item) {
626 console.log('found existing attr for ident value');
627 args.source_attr_id = li.attributes().filter(
628 function(attr) { return attr.id() == item.id[0] }
634 if (!args.source_attr_id) {
635 // user entered new text in the combobox
636 // so we need to create a new attr
637 console.log('creating new ident attr');
638 args.lineitem_id = li.id();
639 args.attr_name = name;
640 args.attr_value = val;
643 fieldmapper.standardRequest(
644 ['open-ils.acq', 'open-ils.acq.lineitem.order_identifier.set'],
646 params : [openils.User.authtoken, args],
647 oncomplete : function() {
648 console.log('order_ident oncomplete');
649 if (--self._identValuesInFlight == 0)
650 location.href = location.href;
658 this.getLiOrderIdent = function(li) {
659 var attrs = li.attributes();
660 if (!attrs) return null;
664 attr.attr_type() == 'lineitem_local_attr_definition' &&
665 openils.Util.isTrue(attr.order_ident())
671 this.drawOrderIdentSelector = function(li, row) {
673 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
674 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
676 var attrs = li.attributes();
678 // limit to MARC attr defs
679 attrs = attrs.filter(
681 return (attr.attr_type() == 'lineitem_marc_attr_definition');
685 var identAttr = this.getLiOrderIdent(li);
688 // collect the values for each type of identifier
689 // find a reasonable default identifier type to render
693 dojo.forEach(['isbn', 'upc', 'issn'],
696 // collect the values for this attr name
697 values[name] = attrs.filter(
699 return (attr.attr_name() == name)
703 // select a reasonable default name in the type-selector
707 if (identAttr.attr_name() == name)
709 } else if (values[name].length) {
714 dojo.forEach(typeSel.options, function(opt) {
715 if (opt.value == name) {
725 function updateOrderIdent(box) {
726 console.log('updating order ident for box ' + box);
729 // replace the ident combobox with a new
730 // one for the selected ident type
731 function changeComboBox(sel) {
732 var name = sel.options[sel.selectedIndex].value;
734 var td = dojo.query('[name=order_ident_value]', row)[0];
735 if (td.childNodes[0])
736 dojo.destroy(td.childNodes[0]);
738 var store = new dojo.data.ItemFileWriteStore({
739 data : acqlia.toStoreData(values[name])
742 var cbox = new dijit.form.ComboBox(
744 labelAttr : 'attr_value',
745 searchAttr : 'attr_value'
747 dojo.create('div', {}, td)
752 // set the value for the cbox
753 if (values[name].length) {
754 var orderIdent = self.getLiOrderIdent(li);
756 if (orderIdent && orderIdent.attr_name() == name) {
757 cbox.attr('value', orderIdent.attr_value());
759 cbox.attr('value', values[name][0].attr_value());
763 if (!self.orderIdentAllowed)
764 cbox.attr('disabled', true);
768 dojo.connect(cbox, 'onChange', updateOrderIdent);
771 changeComboBox(typeSel); // force the initial draw
772 typeSel.onchange = function() {changeComboBox(typeSel)};
775 this.testOrderIdentPerms = function(org, callback) {
777 new openils.User().getPermOrgList(
778 'ACQ_SET_LINEITEM_IDENTIFIER',
780 console.log('found orgs = ' + orgs);
781 for (var i = 0; i < orgs.length; i++) {
782 if (Number(orgs[i]) == Number(org)) {
783 self.orderIdentAllowed = true;
784 if (callback) callback();
788 if (callback) callback();
794 this.checkClaimEligibility = function(li, callback, row) {
795 /* Assume always eligible, i.e. from this interface we don't care about
796 * claim eligibility any more. this is where the user would force a
798 this.clearEligibility(li);
799 this.claimEligibleLidByLi[li.id()] = li.lineitem_details().map(
800 function(lid) { return lid.id(); }
802 li.lineitem_details().forEach(
803 function(lid) { self.claimEligibleLid[lid.id()] = true; }
805 this.reconsiderClaimControl(li, row);
806 if (callback) callback(li);
808 this.clearEligibility(li);
809 fieldmapper.standardRequest(
810 ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
811 "params": [openils.User.authtoken, {"lineitem": li.id()}],
813 "onresponse": function(r) {
814 if (r = openils.Util.readResponse(r)) {
815 self.claimEligibleLidByLi[li.id()].push(
818 self.claimEligibleLid[r.lineitem_detail()] = true;
821 "oncomplete": function() {
822 self.reconsiderClaimControl(li, row);
823 if (typeof(callback) == "function")
831 this.updateLiNotesCount = function(li, row) {
832 if (!row) row = this._findLiRow(li);
834 var has_notes = (li.lineitem_notes().filter(
835 function(o) { return Boolean (o.alert_text()); }
838 /* U+2691 is the code point for a filled-in flag character */
839 nodeByName("notes_alert_flag", row).innerHTML =
840 has_notes ? "⚑" : "";
841 nodeByName("noteslink", row).style.fontStyle =
842 has_notes ? "italic" : "normal";
843 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
846 /* XXX NOT related to _updateLiState(). rethink */
847 this.updateLiState = function(li, row) {
848 if (!row) row = this._findLiRow(li);
850 var actReceive = nodeByName("action_mark_recv", row);
851 var actUnRecv = nodeByName("action_mark_unrecv", row);
852 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
853 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
854 var actNewInvoice = nodeByName('action_new_invoice', row);
855 var actLinkInvoice = nodeByName('action_link_invoice', row);
856 var actViewInvoice = nodeByName('action_view_invoice', row);
858 // always allow access to LI history
859 nodeByName('action_view_history', row).onclick =
860 function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
862 /* handle row coloring for based on LI state */
863 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
864 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
866 // Expose invoice actions for any lineitem that is linked to a PO
867 if( li.purchase_order() ) {
869 actNewInvoice.disabled = false;
870 actLinkInvoice.disabled = false;
871 actViewInvoice.disabled = false;
873 actNewInvoice.onclick = function() {
874 location.href = oilsBasePath + '/acq/invoice/view?create=1&attach_li=' + li.id();
875 nodeByName("action_none", row).selected = true;
878 actLinkInvoice.onclick = function() {
879 if (!self.invoiceLinkDialogManager) {
880 self.invoiceLinkDialogManager =
881 new InvoiceLinkDialogManager("li");
883 self.invoiceLinkDialogManager.target = li;
884 acqLitLinkInvoiceDialog.show();
885 nodeByName("action_none", row).selected = true;
888 actViewInvoice.onclick = function() {
889 location.href = oilsBasePath +
890 "/acq/search/unified?so=" +
891 base64Encode({"jub":[{"id": li.id()}]}) +
893 nodeByName("action_none", row).selected = true;
899 * If we haven't fleshed the lineitem_details, default to allowing access to the
900 * holdings maintenence actions. The alternative is to flesh LIDs on every lineitem,
901 * but that will add to page render time. Let's see if this will suffice...
903 var lids = li.lineitem_details();
905 (lids && !lids.filter(function(lid) { return lid.eg_copy_id() })[0] )) {
907 actUpdateBarcodes.disabled = false;
908 actUpdateBarcodes.onclick = function() {
909 self.showRealCopyEditUI(li);
910 nodeByName("action_none", row).selected = true;
912 actHoldingsMaint.disabled = false;
913 actHoldingsMaint.onclick =
914 self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
917 var state_cell = nodeByName("li_state", row);
922 if(typeof li.cancel_reason() == "object") {
923 var holds_state = dojo.create(
925 "style": "border-bottom: 1px dashed #000;",
926 "innerHTML": li.state()
927 }, state_cell, "only"
931 "label": "<em>" + li.cancel_reason().label() +
932 "</em><br />" + li.cancel_reason().description(),
933 "connectId": [holds_state]
934 }, dojo.create("span", null, state_cell, "last")
940 actReceive.disabled = false;
941 actReceive.onclick = function() {
942 if (self.checkLiAlerts(li.id()))
943 self.issueReceive(li);
944 nodeByName("action_none", row).selected = true;
949 actUnRecv.disabled = false;
950 actUnRecv.onclick = function() {
951 if (confirm(localeStrings.UNRECEIVE_LI))
952 self.issueReceive(li, /* rollback */ true);
953 nodeByName("action_none", row).selected = true;
958 state_cell.innerHTML = li.state(); // TODO i18n state labels
962 this._setAlertStore = function() {
963 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
965 "data": acqliat.toStoreData(
968 "owning_lib": aou.orgNodeTrail(
969 aou.findOrgUnit(openils.User.user.ws_ou())
970 ).map(function(o) { return o.id(); })
976 acqLitAlertAlertText.setValue(); /* make the store "live" */
977 acqLitAlertAlertText._store_ready = true;
981 * Draws and shows the lineitem notes pane
983 this.drawLiNotes = function(li) {
985 this.focusLineitem = li.id();
987 if (!acqLitAlertAlertText._store_ready)
988 this._setAlertStore();
991 li.lineitem_notes().sort(
993 if(a.edit_time() < b.edit_time()) return 1;
999 while(this.liNotesTbody.childNodes[0])
1000 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
1003 acqLitCreateNoteSubmit.onClick = function() {
1004 var value = acqLitCreateNoteText.attr('value');
1006 var note = new fieldmapper.acqlin();
1009 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
1012 note.lineitem(li.id());
1014 self.updateLiNotes(li, note);
1015 acqLitCreateNoteVendorPublic.attr("checked", false);
1016 acqLitCreateNoteText.attr("value", "");
1019 acqLitCreateAlertSubmit.onClick = function() {
1020 if (!acqLitAlertAlertText.item) {
1021 alert(localeStrings.ALERT_UNSELECTED);
1025 var alert_text = new fieldmapper.acqliat().fromStoreItem(
1026 acqLitAlertAlertText.item
1028 var value = acqLitAlertNoteValue.attr("value") || "";
1030 var note = new fieldmapper.acqlin();
1032 note.lineitem(li.id());
1034 note.alert_text(alert_text);
1036 self.updateLiNotes(li, note);
1039 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
1043 * Draws a single lineitem note in the notes pane
1045 this.addLiNote = function(li, note) {
1046 if(note.isdeleted()) return;
1048 var row = self.liNotesRow.cloneNode(true);
1049 nodeByName("value", row).innerHTML = note.value();
1050 var alert_node = nodeByName("alert_code", row);
1051 if (note.alert_text()) {
1052 alert_node.innerHTML = dojo.string.substitute(
1054 aou.findOrgUnit(note.alert_text().owning_lib()).shortname(),
1055 note.alert_text().code()
1058 if (note.alert_text().description()) {
1061 "connectId": [alert_node],
1062 "label": note.alert_text().description()
1063 }, dojo.create("span", null, alert_node, "after")
1068 if (openils.Util.isTrue(note.vendor_public()))
1069 nodeByName("vendor_public", row).innerHTML =
1070 localeStrings.VENDOR_PUBLIC;
1072 nodeByName("delete", row).onclick = function() {
1073 note.isdeleted(true);
1074 self.liNotesTbody.removeChild(row);
1075 self.updateLiNotes(li);
1078 if(note.edit_time()) {
1079 nodeByName("edit_time", row).innerHTML =
1080 dojo.date.locale.format(
1081 dojo.date.stamp.fromISOString(note.edit_time()),
1082 {formatLength:'short'});
1085 self.liNotesTbody.appendChild(row);
1089 * Updates any new/changed/deleted notes on the server
1091 this.updateLiNotes = function(li, newNote) {
1097 notes = li.lineitem_notes().filter(
1099 if(note.ischanged() || note.isnew() || note.isdeleted())
1105 if(notes.length == 0) return;
1106 progressDialog.show();
1108 fieldmapper.standardRequest(
1109 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
1111 params : [this.authtoken, notes],
1112 onresponse : function(r) {
1113 var resp = openils.Util.readResponse(r);
1118 // remove the old changed notes
1120 dojo.forEach(li.lineitem_notes(),
1122 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
1126 li.lineitem_notes(list);
1129 progressDialog.hide();
1130 self.updateLiNotesCount(li);
1131 self.drawLiNotes(li);
1135 progressDialog.update(resp);
1136 var newnote = resp.note;
1138 if(!newnote.isdeleted()) {
1139 newnote.isnew(false);
1140 newnote.ischanged(false);
1141 li.lineitem_notes().push(newnote);
1148 this.updateLiPrice = function(input, li) {
1150 var price = input.value;
1151 if(Number(price) == Number(li.estimated_unit_price())) return;
1153 fieldmapper.standardRequest(
1154 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
1155 { async : false, // redundant w/ timeout
1157 params : [this.authtoken, li.id(), price],
1158 oncomplete : function(r) {
1159 openils.Util.readResponse(r);
1160 li.estimated_unit_price(price); // update local copy
1163 * If this is a PO and every visible lineitem has a price,
1164 * check again to see if this PO can be activated. Note that
1165 * every visible lineitem having a price does not guarantee it can
1166 * be activated, which is why we still make the call. Having a price
1167 * set for every visiable lineitem is just the lowest barrier to entry.
1170 var priceNodes = dojo.query('[name=price]', dojo.byId('acq-lit-tbody'));
1172 dojo.forEach(priceNodes, function(node) { if (node.value == '') allSet = false});
1173 if (allSet) checkCouldActivatePo();
1180 this.removeLineitem = function(liId) {
1181 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
1182 delete this.liCache[liId];
1183 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
1186 this.drawInfo = function(liId) {
1187 this.focusLineitem = liId;
1188 if (!this._isRelatedViewer) {
1189 var d = dojo.byId("acq-lit-info-related");
1190 if (!this.relCache[liId]) {
1191 fieldmapper.standardRequest(
1194 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
1197 "params": [openils.User.authtoken, liId],
1198 "onresponse": function(r) {
1199 self.relCache[liId] = openils.Util.readResponse(r);
1200 nodeByName("related_number", d).innerHTML =
1201 self.relCache[liId];
1203 self.relCache[liId] >1 ? "show" : "hide"
1209 nodeByName("related_number", d).innerHTML = this.relCache[liId];
1210 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
1215 openils.acq.Lineitem.fetchAttrDefs(
1217 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
1222 /* For a given list of lineitem ids, build a list of full lineitems
1223 * re-using the fetching logic that is otherwise typical to use in this
1226 * If we've already got a lineitem in the cache, just use that.
1228 * Once we've built a list of lineitems, call callback(thatlist).
1230 this.fetchLineitemsById = function(id_list, callback) {
1231 var total = id_list.length;
1232 var result_list = [];
1234 var inner = function(li) {
1235 result_list.push(li)
1237 callback(result_list);
1240 id_list.forEach(function(id) { self._fetchLineitem(id, inner); });
1243 this._fetchLineitem = function(liId, handler, force) {
1245 var li = this.liCache[liId];
1246 if(li && li.marc() && li.lineitem_details() && !force)
1249 fieldmapper.standardRequest(
1250 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
1253 params: [self.authtoken, liId, {
1255 flesh_cancel_reason: true,
1256 flesh_li_details: true,
1258 flesh_fund_debit: true }],
1260 oncomplete: function(r) {
1261 var li = openils.Util.readResponse(r);
1262 self.liCache[liId] = li;
1269 this._drawInfo = function(li) {
1271 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
1273 if(li.eg_bib_id()) {
1274 openils.Util.hide('acq-lit-marc-order-record-label');
1275 openils.Util.hide(acqLitEditOrderMarc.domNode);
1276 openils.Util.show('acq-lit-marc-real-record-label');
1278 openils.Util.show('acq-lit-marc-order-record-label');
1279 openils.Util.show(acqLitEditOrderMarc.domNode);
1280 openils.Util.hide('acq-lit-marc-real-record-label');
1283 this.drawMarcHTML(li);
1284 this.infoTbody = dojo.byId('acq-lit-info-tbody');
1287 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
1288 while(this.infoTbody.childNodes[0])
1289 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
1291 for(var i = 0; i < li.attributes().length; i++) {
1292 var attr = li.attributes()[i];
1293 var row = this.infoRow.cloneNode(true);
1295 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
1296 var name = openils.acq.Lineitem.attrDefs[type].filter(
1298 return (a.code() == attr.attr_name());
1300 ).pop().description();
1302 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
1303 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
1304 this.infoTbody.appendChild(row);
1307 if (!this._isRelatedViewer) {
1308 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
1309 oilsBasePath + "/acq/lineitem/related/" + li.id();
1312 // if a top scroll point is defined, jump up to it here
1313 var node = dojo.byId('oils-scroll-to-top');
1314 if (node) dijit.scrollIntoView(node);
1317 this.generateMakeRecTab = function(bib_id,default_view, row) {
1321 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
1324 show_nav_buttons : true,
1325 show_print_button : true,
1326 opac_url : xulG.url_prefix('opac_rdetail|' + bib_id),
1327 default_view : default_view
1331 if(row) nodeByName("action_none", row).selected = true;
1335 this.drawMarcHTML = function(li) {
1336 var params = [null, true, li.marc()];
1338 params = [li.eg_bib_id(), true];
1340 fieldmapper.standardRequest(
1341 ['open-ils.search', 'open-ils.search.biblio.record.html'],
1344 oncomplete: function(r) {
1345 dojo.byId('acq-lit-marc-div').innerHTML =
1346 openils.Util.readResponse(r);
1352 this.drawCopies = function(liId, force_fetch) {
1353 this.focusLineitem = liId;
1354 if (typeof force_fetch == "undefined")
1355 force_fetch = false;
1357 var cgi = new openils.CGI();
1358 var source = cgi.param('source');
1359 if (source && source.match(/invoice/)) {
1360 // got here from the invoice page, show the 'return-to-invoice' button
1361 var cgi = new openils.CGI({url : source});
1362 cgi.param('focus_li', liId);
1363 openils.Util.show(dojo.byId('acq-lit-copies-back-to-invoice-button-wrapper'), 'inline');
1364 var button = dojo.byId('acq-lit-copies-back-to-invoice-button');
1365 button.onclick = function() { location.href = cgi.url() };
1368 openils.acq.Lineitem.fetchAndRender(liId, {},
1369 function(li, html) {
1370 dojo.byId('acq-lit-copies-li-summary').innerHTML = html;
1374 this.show('copies');
1376 this.copyCache = {};
1377 this.copyWidgetCache = {};
1378 this.oldCopyWidgetCache = {};
1379 this.virtDfaCounts = {};
1380 this.realDfaCache = {};
1383 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
1384 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
1385 acqLitCopyCountInput.attr('value', '0');
1387 while(this.copyTbody.childNodes[0])
1388 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
1390 this._drawBatchCopyWidgets();
1392 this._drawDistribApplied(liId);
1394 this._fetchDistribFormulas(
1396 openils.acq.Lineitem.fetchAttrDefs(
1398 self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch);
1405 this._saveDistribAppliedTemplates = function() {
1406 if (!this._appliedDistribTemplate) {
1407 this._appliedDistribTemplate =
1408 dojo.byId("acq-lit-distrib-applied-tbody").
1409 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
1410 dojo.attr(this._appliedDistribTemplate, "id");
1414 this._drawDistribApplied = function(liId) {
1415 /* Build this table while hidden to prevent rendering artifacts */
1416 openils.Util.hide("acq-lit-distrib-applied-tbody");
1418 this._saveDistribAppliedTemplates();
1420 /* Remove any rows in the table from previous populations */
1421 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
1422 forEach(dojo.destroy);
1424 /* Unregister all dijits previously created (for some reason this isn't
1425 * covered by the above destroy calls). */
1426 dijit.registry.forEach(
1427 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
1430 /* Populate the table with our liId */
1432 fieldmapper.standardRequest(
1434 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
1437 "params": [self.authtoken, liId],
1438 "onresponse": function(r) {
1439 var dfa = openils.Util.readResponse(r);
1442 self.realDfaCache[dfa.id()] = dfa;
1443 self._drawDistribAppliedUnit(dfa);
1446 "oncomplete": function() {
1447 /* Reveal built table */
1450 "acq-lit-distrib-applied-tbody", "table-row-group"
1458 this._drawDistribAppliedUnit = function(dfa) {
1459 var new_row = false;
1460 var row = dojo.query(
1461 'tr[formula="' + dfa.formula().id() + '"]',
1462 "acq-lit-distrib-applied-tbody"
1467 row = dojo.clone(this._appliedDistribTemplate);
1468 dojo.attr(row, "formula", dfa.formula().id());
1469 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
1472 var td = dojo.query("td", row)[0];
1474 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1475 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1478 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1480 new dijit.form.Button(
1482 "onClick": function() {
1483 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1484 self.deleteDfa(dfa);
1487 /* XXX I /cannot/ make the following work in as a CSS class
1488 * for some reason. So frustrating... */
1489 "style": function(id) {
1491 "font-weight: bold; color: #c00;" :
1493 }(dfa.id()) + "margin: 0 6px;display: inline;"
1494 }, "dfa-button-" + dfa.id()
1498 "connectId": ["dfa-button-" + dfa.id()],
1499 "label": dojo.string.substitute(
1500 localeStrings.DFA_TIP, dfa.id() > 0 ? [
1501 openils.User.formalName(dfa.creator()),
1502 dojo.date.locale.format(
1503 dojo.date.stamp.fromISOString(dfa.create_time()),
1504 {"formatLength":"short"}
1506 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
1508 }, "dfa-tip-" + dfa.id()
1512 this.deleteDfa = function(dfa) {
1513 if (dfa.id() > 0) { /* real */
1514 this.pcrud.eliminate(
1517 "oncomplete": function() {
1518 self._removeDistribApplied(dfa.id());
1519 delete self.realDfaCache[dfa.id()];
1523 } else { /* virtual */
1524 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
1525 this.virtDfaCounts[dfa.formula().id()] = 0;
1526 /* hasn't been saved yet, so no need to do anything server side */
1527 this._removeDistribApplied(dfa.id());
1532 this._removeDistribApplied = function(dfaId) {
1533 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
1534 dijit.registry.forEach(
1535 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
1537 this._removeDistribAppliedEmptyRows();
1540 this._removeAllDistribAppliedVirtual = function() {
1541 /* Unregister dijits */
1542 dijit.registry.forEach(
1543 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
1545 this._removeDistribAppliedEmptyRows();
1548 this._removeDistribAppliedEmptyRows = function() {
1549 /* Remove any rows with no DFA at all */
1550 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
1552 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
1558 * Insert a new row into the distribution formula selection form
1560 this._addDistribFormulaRow = function() {
1563 if (!self.distribForms) {
1564 // no formulas, hide the form
1565 openils.Util.hide('acq-lit-distrib-formula-table');
1569 if(!this.distribFormulaTemplate)
1570 this.distribFormulaTemplate =
1571 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
1573 var row = this.distribFormulaTemplate.cloneNode(true);
1574 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
1576 this.dfSelector = new dijit.form.FilteringSelect(
1577 {"labelAttr": "dynLabel", "labelType": "html"},
1578 nodeByName("selector", row)
1580 this._updateFormulaStore();
1581 this.dfSelector.fetchProperties =
1582 {"sort": [{"attribute": "use_count", "descending": true}]};
1584 var apply = new dijit.form.Button(
1585 {"label": localeStrings.APPLY},
1586 nodeByName('set_button', row)
1589 var reset = new dijit.form.Button(
1590 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
1591 nodeByName("reset_button", row)
1594 dojo.connect(apply, 'onClick',
1596 var form_id = self.dfSelector.attr("value");
1597 if(!form_id) return;
1598 self._applyDistribFormula(form_id);
1599 reset.attr("disabled", false);
1603 dojo.connect(reset, 'onClick',
1605 self.restoreCopyFieldsBeforeDF();
1606 self.virtDfaCounts = {};
1607 self.virtDfaId = -1;
1609 self._updateFormulaStore();
1610 self._removeAllDistribAppliedVirtual();
1611 reset.attr("disabled", "true");
1618 * Applies a distrib formula to the current set of copies
1620 this._applyDistribFormula = function(formula) {
1621 if(!formula) return;
1623 formula = this.distribForms.filter(
1624 function(form) { return form.id() == formula; }
1627 var copyRows = dojo.query('tr', self.copyTbody);
1629 if (this.dfeOffset >= copyRows.length) {
1630 alert(localeStrings.OUT_OF_COPIES);
1634 var entries_applied = 0;
1636 var rowIndex = this.dfeOffset;
1637 rowIndex < copyRows.length;
1641 var row = copyRows[rowIndex];
1642 var copy_id = row.getAttribute('copy_id');
1643 var copyWidgets = this.copyWidgetCache[copy_id];
1644 var entryIndex = this.dfeOffset;
1647 // find the correct entry for the current row
1648 dojo.forEach(formula.entries(),
1651 entryIndex += e.item_count();
1652 if(entryIndex > rowIndex)
1660 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
1661 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
1664 this.saveCopyFieldsBeforeDF(copy_id);
1665 this._copy_fields_for_acqdf.forEach(
1667 if(entry[field]()) {
1668 copyWidgets[field].attr('value', (entry[field]()));
1675 if (entries_applied) {
1676 this.virtDfaCounts[formula.id()] =
1677 ++(this.virtDfaCounts[formula.id()]) || 1;
1678 this._updateFormulaStore();
1679 this._drawDistribAppliedUnit(
1681 var dfa = new acqdfa();
1682 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
1685 this.dfeOffset += entries_applied;
1690 * This function updates the DF store for the dropdown so that use_counts
1691 * can reflect DF applications from this session before they're saved
1694 this._updateFormulaStore = function() {
1695 this.dfSelector.store = new dojo.data.ItemFileReadStore(
1697 "data": self._labelFormulasWithCounts(
1698 acqdf.toStoreData(self.distribForms)
1704 this.saveCopyFieldsBeforeDF = function(copy_id) {
1706 if (!this.oldCopyWidgetCache[copy_id]) {
1707 var copyWidgets = this.copyWidgetCache[copy_id];
1709 this.oldCopyWidgetCache[copy_id] = {};
1710 this._copy_fields_for_acqdf.forEach(
1712 self.oldCopyWidgetCache[copy_id][f] =
1713 copyWidgets[f].attr("value");
1719 this.restoreCopyFieldsBeforeDF = function() {
1721 for (var copy_id in this.oldCopyWidgetCache) {
1722 this._copy_fields_for_acqdf.forEach(
1724 self.copyWidgetCache[copy_id][f].attr(
1725 "value", self.oldCopyWidgetCache[copy_id][f]
1732 this._labelFormulasWithCounts = function(store_data) {
1733 for (var key in store_data.items) {
1734 var obj = store_data.items[key];
1735 obj.use_count = Number(obj.use_count); /* needed for sorting */
1737 if (this.virtDfaCounts[obj.id])
1738 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
1740 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
1741 obj.use_count + "]</span> " + obj.name;
1747 * This method formerly would not refetch the DF formulas if they'd been
1748 * loaded already, but now it always re-fetches, since use_count changes.
1750 /** TODO: port distrib-formula selector to autofieldwidget+pcrud/dojo store */
1751 this._fetchDistribFormulas = function(onload) {
1752 fieldmapper.standardRequest(
1754 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
1757 "params": [openils.User.authtoken, 0, 500],
1758 "oncomplete": function(r) {
1759 self.distribForms = openils.Util.readResponse(r);
1760 if(!self.distribForms || self.distribForms.length == 0) {
1761 self.distribForms = [];
1763 self._addDistribFormulaRow();
1770 this._drawBatchCopyWidgets = function() {
1771 var row = this.copyBatchRow;
1772 dojo.forEach(liDetailBatchFields,
1774 if(self.copyBatchRowDrawn) {
1775 self.copyBatchWidgets[field].attr('value', null);
1777 var widget = new openils.widget.AutoFieldWidget({
1780 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1781 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1782 searchFilter : (field == 'fund') ? {"active": "t"} : null,
1783 parentNode : dojo.query('[name='+field+']', row)[0],
1784 orgLimitPerms : ['CREATE_PICKLIST'],
1787 "labelType": (field == "fund") ? "html" : null
1789 noCache: (field == "fund"),
1794 if (field == "fund" && w.store)
1795 self._ensureCSSFundClasses(w.store);
1796 self.copyBatchWidgets[field] = w;
1799 if (field == "fund") {
1801 widget.widget, "onChange", function(val) {
1802 self._updateFundSelectorStyle(widget, val);
1809 this.copyBatchRowDrawn = true;
1812 this.batchCopyUpdate = function() {
1814 for(var k in this.copyWidgetCache) {
1815 var cache = this.copyWidgetCache[k];
1816 dojo.forEach(liDetailBatchFields, function(f) {
1817 var newval = self.copyBatchWidgets[f].attr('value');
1818 if(newval) cache[f].attr('value', newval);
1823 this._drawCopies = function(li) {
1826 // this button sets the total number of copies for a given lineitem
1827 acqLitAddCopyCount.onClick = function() {
1828 var count = acqLitCopyCountInput.attr('value');
1831 while(self.copyCount() < count)
1834 // delete rows if necessary
1835 var diff = self.copyCount() - count;
1837 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
1838 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
1839 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
1841 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1847 if(li.lineitem_details().length > 0) {
1848 dojo.forEach(li.lineitem_details(),
1850 self.addCopy(li, copy);
1858 this.copyCount = function() {
1860 for(var id in this.copyCache) {
1861 if(!this.copyCache[id].isdeleted())
1867 this.virtCopyId = -1;
1868 this.addCopy = function(li, copy) {
1869 var row = this.copyRow.cloneNode(true);
1870 this.copyTbody.appendChild(row);
1874 copy = new fieldmapper.acqlid();
1876 copy.id(this.virtCopyId--);
1877 copy.lineitem(li.id());
1880 this.copyCache[copy.id()] = copy;
1881 row.setAttribute('copy_id', copy.id());
1882 self.copyWidgetCache[copy.id()] = {};
1884 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1886 var rcvr = copy.receiver();
1888 if (!userCache[rcvr]) {
1889 if(rcvr == openils.User.user.id()) {
1890 userCache[rcvr] = openils.User.user;
1892 userCache[rcvr] = fieldmapper.standardRequest(
1893 ['open-ils.actor', 'open-ils.actor.user.retrieve'],
1894 {params: [openils.User.authtoken, rcvr]}
1898 dojo.query('[name=receiver]', row)[0].innerHTML = userCache[rcvr].usrname();
1901 dojo.forEach(liDetailFields,
1904 if (field == "fund") {
1905 searchFilter = (copy.fund() ?
1906 {"-or": {"active": "t", "id": copy.fund()}} :
1909 searchFilter = null;
1912 var readOnly = false;
1914 // TODO: Add support for changing the owning_lib after real copies have been made.
1915 // owning_lib is order data as much as its item data
1916 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
1920 // TODO: add support for changing the fund after debits have been created
1921 // Note: invoicing allows the change
1922 if(copy.fund_debit() && field == 'fund') {
1927 var widget = new openils.widget.AutoFieldWidget({
1930 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1931 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1932 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1933 searchFilter : searchFilter,
1934 noCache: (field == "fund"),
1936 parentNode : dojo.query('[name='+field+']', row)[0],
1937 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
1938 readOnly : readOnly,
1939 orgDefaultsToWs : true
1943 // make sure we capture the value from any async widgets
1946 if (field == "fund" && w.store)
1947 self._ensureCSSFundClasses(w.store);
1950 copy[field](ww.getFormattedValue())
1952 self.copyWidgetCache[copy.id()][field] = w;
1954 dojo.connect(w, 'onChange',
1956 if (field == "fund")
1957 self._updateFundSelectorStyle(widget, val);
1959 if (!readOnly && (copy.isnew() || val != copy[field]())) {
1960 // prevent setting ischanged() automatically on widget load for existing copies
1961 copy[field](widget.getFormattedValue())
1962 copy.ischanged(true);
1971 this.updateLidState(copy, row);
1974 this._ensureCSSFundClass = function(id) {
1975 if (!this.fundStyleSheet) {
1977 "style", {"type": "text/css"},
1978 document.getElementsByTagName("head")[0], "last"
1980 this.fundStyleSheet = document.styleSheets[
1981 document.styleSheets.length - 1
1985 var cn = "fund_" + id;
1986 if (!this.haveFundClass[cn]) {
1987 fieldmapper.standardRequest(
1988 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
1990 "params": [openils.User.authtoken, id],
1992 "oncomplete": function(r) {
1993 r = openils.Util.readResponse(r);
1994 self.fundBalanceState[id] = r;
1996 if (r[0] /* stop */)
1997 style = fundStyles.stop;
1998 else if (r[1] /* warning */)
1999 style = fundStyles.warning;
2000 self.fundStyleSheet.insertRule(
2001 "." + cn + " { " + style + " }",
2002 self.fundStyleSheet.cssRules.length
2004 self.haveFundClass[cn] = true;
2011 this._ensureCSSFundClasses = function(store) {
2013 "query": {"id": "*"},
2014 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
2018 this._updateFundSelectorStyle = function(widget, fund_id) {
2019 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
2020 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
2023 this.updateLidState = function(copy, row) {
2026 if (typeof(row) == "undefined") {
2027 row = dojo.query('tr[copy_id="' + copy.id() + '"]', this.copyTbody)[0];
2031 var recv_link = nodeByName("receive", row);
2032 var unrecv_link = nodeByName("unreceive", row);
2033 var del_link = nodeByName("delete", row);
2034 var cxl_link = nodeByName("cancel", row);
2035 var claim_link = nodeByName("claim", row);
2036 var cxl_reason_link = nodeByName("cancel_reason", row);
2038 // by default, hide all the actions
2039 openils.Util.hide(del_link.parentNode);
2040 openils.Util.hide(recv_link);
2041 openils.Util.hide(unrecv_link);
2042 openils.Util.hide(cxl_link);
2043 openils.Util.hide(claim_link);
2044 openils.Util.hide(cxl_reason_link);
2046 if (copy.id() > 0) { // real copies (LIDs)
2048 if (copy.cancel_reason()) {
2050 /* --------- cancelled -------------------------- */
2052 /* XXX the following may leak memory in a long lived table:
2053 * dijits may not get destroyed... not positive. revisit. */
2054 var holds_reason = dojo.create(
2056 "style": "border-bottom: 1px dashed #000;",
2057 "innerHTML": "Cancelled" /* XXX [sic] and i18n */
2058 }, cxl_reason_link, "only"
2062 "label": "<em>" + copy.cancel_reason().label() +
2063 "</em><br />" + copy.cancel_reason().description(),
2064 "connectId": [holds_reason]
2065 }, dojo.create("span", null, cxl_reason_link, "last")
2067 openils.Util.show(cxl_reason_link, "inline");
2069 } else if (copy.recv_time()) {
2071 /* --------- received -------------------------- */
2073 openils.Util.show(unrecv_link, "inline");
2074 unrecv_link.onclick = function() {
2075 if (confirm(localeStrings.UNRECEIVE_LID))
2076 self.issueReceive(copy, /* rollback */ true);
2079 } else if (this.liCache[copy.lineitem()].state() == 'on-order') {
2081 /* --------- on order -------------------------- */
2083 openils.Util.show(recv_link, 'inline');
2084 openils.Util.show(cxl_link, "inline");
2086 recv_link.onclick = function() {
2087 if (self.checkLiAlerts(copy.lineitem()))
2088 self.issueReceive(copy);
2091 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2095 /* --------- pre-order copies -------------------------- */
2097 del_link.onclick = function() { self.deleteCopy(row) };
2098 openils.Util.show(del_link.parentNode);
2104 /* --------- virtual copies -------------------------- */
2106 del_link.onclick = function() { self.deleteCopy(row) };
2107 openils.Util.show(del_link.parentNode);
2111 this.cancelLid = function(lid_id) {
2112 lidCancelDialog._lid_id = lid_id;
2113 openils.Util.show(lidCancelDialog.domNode.parentNode);
2114 lidCancelDialog.show();
2115 if (!lidCancelDialog._prepared) {
2116 var widget = new openils.widget.AutoFieldWidget({
2117 "fmField": "cancel_reason",
2118 "fmClass": "acqlid",
2119 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
2120 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2125 acqLidCancelButton.onClick = function() {
2126 if (w.attr("value")) {
2127 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
2129 lidCancelDialog._lid_id,
2133 lidCancelDialog.hide();
2136 lidCancelDialog._prepared = true;
2142 this._cancelLid = function(lid_id, reason) {
2143 fieldmapper.standardRequest(
2144 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
2145 "params": [openils.User.authtoken, lid_id, reason],
2147 "onresponse": function(r) {
2148 if (r = openils.Util.readResponse(r)) {
2150 for (var id in r.lid) {
2151 /* actually this should only iterate once */
2152 self.copyCache[id].cancel_reason(
2153 r.lid[id].cancel_reason
2155 self.updateLidState(self.copyCache[id]);
2164 this._confirmAlert = function(li, lin) {
2166 dojo.string.substitute(
2167 localeStrings.CONFIRM_LI_ALERT, [
2168 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2169 "title", "lineitem_marc_attr_definition"
2171 /* XXX it's really better add a parameter and to adjust
2172 * the format string rather than do this concatenation
2173 * here, but if someone wants this for 2.2 in a hurry,
2174 * we can sidestep the problem of updating the strings
2175 * while the translators are working. */
2177 aou.findOrgUnit(lin.alert_text().owning_lib()).shortname() +
2179 lin.alert_text().code()
2181 lin.alert_text().description() || "",
2188 this.checkLiAlerts = function(li_id) {
2189 var li = this.liCache[li_id];
2191 var alert_notes = li.lineitem_notes().filter(
2192 function(o) { return Boolean(o.alert_text()); }
2195 /* this is _intentionally_ not done in a call to forEach() ... */
2196 for (var i = 0; i < alert_notes.length; i++) {
2197 if (this.noteAcks[alert_notes[i].id()])
2199 else if (!this._confirmAlert(li, alert_notes[i]))
2202 this.noteAcks[alert_notes[i].id()] = true;
2208 this.deleteCopy = function(row) {
2209 var copy = this.copyCache[row.getAttribute('copy_id')];
2210 copy.isdeleted(true);
2212 delete this.copyCache[copy.id()];
2213 this.copyTbody.removeChild(row);
2216 this._virtDfaCountsAsList = function() {
2218 for (var key in this.virtDfaCounts) {
2219 for (var i = 0; i < this.virtDfaCounts[key]; i++)
2225 this.confirmBreachedCopyFunds = function(copies) {
2226 var stop = 0, warning = 0;
2230 var state = self.fundBalanceState[o.fund()];
2231 if (state[0] /* stop */)
2233 else if (state[1] /* warning */)
2240 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
2241 } else if (warning) {
2242 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
2247 this.saveCopyChanges = function(liId) {
2253 for(var id in this.copyCache) {
2254 var c = this.copyCache[id];
2255 if(!c.isdeleted()) total++;
2256 if(c.isnew() || c.ischanged() || c.isdeleted()) {
2257 if(c.id() < 0) c.id(null);
2263 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
2266 if (copies.length > 0) {
2267 if (!this.confirmBreachedCopyFunds(copies))
2270 if (typeof(this._copy_count_cb) == "function")
2271 this._copy_count_cb(liId, total);
2273 openils.Util.show("acq-lit-update-copies-progress");
2274 fieldmapper.standardRequest(
2275 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
2277 params: [openils.User.authtoken, copies],
2278 onresponse: function(r) {
2279 var res = openils.Util.readResponse(r);
2280 litUpdateCopiesProgress.update(res);
2282 oncomplete: function() {
2283 self.drawCopies(liId, true /* force_fetch */);
2284 openils.Util.hide("acq-lit-update-copies-progress");
2290 var dfa_list = this._virtDfaCountsAsList();
2291 if (dfa_list.length > 0) {
2292 fieldmapper.standardRequest(
2294 "open-ils.acq.distribution_formula.record_application"],
2297 "params": [openils.User.authtoken, dfa_list, liId],
2298 "onresponse": function(r) {
2299 var res = openils.Util.readResponse(r);
2300 if (res && res.length < dfa_list.length)
2301 alert(localeStrings.DFA_NOT_ALL);
2305 this.virtDfaCounts = {};
2309 this._updateCreatePoPrepayCheckbox = function(prepay) {
2310 var prepay = openils.Util.isTrue(prepay);
2311 this._prepayRequiredByVendor = prepay;
2312 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
2315 this._confirmPoPrepaySituation = function() {
2316 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
2317 if (want_prepay != this._prepayRequiredByVendor) {
2320 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
2321 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
2328 this.applySelectedLiAction = function(action) {
2332 case 'delete_selected':
2333 this._deleteLiList(self.getSelected());
2336 case 'create_order':
2337 this._loadPOSelect();
2338 acqLitPoCreateDialog.show();
2341 case 'save_picklist':
2342 acqLitSavePlDialog.show();
2345 case 'selector_ready':
2347 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
2348 acqLitChangeLiStateDialog.show();
2356 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
2359 case 'batch_create_invoice':
2360 this.batchCreateInvoice();
2363 case 'batch_link_invoice':
2364 this.batchLinkInvoice();
2371 case 'rollback_receive_po':
2372 this.rollbackPoReceive();
2375 case 'create_assets':
2376 this.showAssetCreator();
2379 case 'export_attr_list':
2380 this.chooseExportAttr();
2383 case 'batch_apply_funds':
2384 this.applyBatchLiFunds();
2387 case 'add_brief_record':
2389 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
2391 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
2395 case "cancel_lineitems":
2396 this.maybeCancelLineitems();
2399 case "change_claim_policy":
2400 var li_list = this.getSelected();
2401 this.claimPolicyPicker.attr("value", null);
2402 liClaimPolicyDialog.show();
2403 liClaimPolicySave.onClick = function() {
2404 self.changeClaimPolicy(
2406 self.claimPolicyPicker.attr("value"),
2410 self.setClaimPolicyControl(li);
2411 self.reconsiderClaimControl(li);
2414 liClaimPolicyDialog.hide();
2422 this.changeClaimPolicy = function(li_list, value, callback) {
2424 function(li) { li.claim_policy(value); }
2426 fieldmapper.standardRequest(
2427 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
2428 "params": [openils.User.authtoken, li_list],
2430 "oncomplete": function(r) {
2431 r = openils.Util.readResponse(r);
2432 if (callback) callback(r);
2438 this.showAssetCreator = function(onAssetsCreated) {
2439 if(!this.isPO) return;
2442 // first, let's see if this PO has any LI's that need to be merged/imported
2443 self.pcrud.search('jub', {purchase_order : this.isPO, eg_bib_id : null}, {
2445 oncomplete : function(r) {
2446 var resp = openils.Util.readResponse(r);
2447 if (resp && resp.length) {
2448 // PO has some non-linked jubs.
2450 self.show('asset-creator');
2451 if(!self.vlAgent.loaded)
2452 self.vlAgent.init();
2454 dojo.connect(assetCreatorButton, 'onClick',
2455 function() { self.createAssets(onAssetsCreated) });
2459 // all jubs linked, move on to asset creation
2460 self.createAssets(onAssetsCreated, true);
2466 this.createAssets = function(onAssetsCreated, noVl) {
2467 this.show('acq-lit-progress-numbers');
2469 var vlArgs = (noVl) ? {} : {vandelay : this.vlAgent.values()};
2470 fieldmapper.standardRequest(
2471 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
2473 params: [this.authtoken, this.isPO, vlArgs],
2474 onresponse: function(r) {
2475 var resp = openils.Util.readResponse(r);
2476 self._updateProgressNumbers(resp, !Boolean(onAssetsCreated), onAssetsCreated);
2482 this.maybeCancelLineitems = function() {
2483 openils.Util.show("acq-lit-cancel-reason", "inline");
2484 if (!acqLitCancelLineitemsButton._prepared) {
2485 var widget = new openils.widget.AutoFieldWidget({
2486 "fmField": "cancel_reason",
2488 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
2489 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2494 acqLitCancelLineitemsButton.onClick = function() {
2495 if (w.attr("value")) {
2496 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
2497 self._cancelLineitems(w.attr("value"));
2499 openils.Util.hide("acq-lit-cancel-reason");
2502 acqLitCancelLineitemsButton._prepared = true;
2508 this._cancelLineitems = function(reason) {
2509 var id_list = this.getSelected().map(function(o) { return o.id(); });
2510 fieldmapper.standardRequest(
2511 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
2512 "params": [openils.User.authtoken, id_list, reason],
2514 "onresponse": function(r) {
2515 if (r = openils.Util.readResponse(r)) {
2517 for (var id in r.li) {
2518 self.liCache[id].state(r.li[id].state);
2519 self.liCache[id].cancel_reason(
2520 r.li[id].cancel_reason
2522 self.updateLiState(self.liCache[id]);
2525 if (r.lid && self.copyCache) {
2526 for (var id in r.lid) {
2527 if (self.copyCache[id]) {
2528 self.copyCache[id].cancel_reason(
2529 r.lid[id].cancel_reason
2531 self.updateLidState(self.copyCache[id]);
2541 this.chooseExportAttr = function() {
2542 if (!acqLitExportAttrSelector._li_setup) {
2544 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
2546 "data": acqlimad.toStoreData(
2548 "acqlimad", {"code": li_exportable_attrs}
2553 acqLitExportAttrSelector.setValue();
2554 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
2555 acqLitExportAttrSelector._li_setup = true;
2557 openils.Util.show("acq-lit-export-attr-holder", "inline");
2560 this.exportAttrList = function() {
2561 var attr_def = acqLitExportAttrSelector.item;
2562 var li_list = this.getSelected();
2563 var value_list = li_list.map(
2565 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2566 attr_def.code, "lineitem_marc_attr_definition"
2569 ).filter(function(attr) { return Boolean(attr); });
2571 if (value_list.length > 0) {
2572 if (value_list.length < li_list.length) {
2574 dojo.string.substitute(
2575 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
2582 openils.XUL.contentToFileSaveDialog(
2583 value_list.join("\n"),
2584 localeStrings.EXPORT_SAVE_DIALOG_TITLE
2590 alert(dojo.string.substitute(
2591 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
2595 openils.Util.hide("acq-lit-export-attr-holder");
2598 this.printPO = function() {
2599 if(!this.isPO) return;
2600 progressDialog.show(true);
2601 fieldmapper.standardRequest(
2602 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
2604 params: [this.authtoken, this.isPO, 'html'],
2605 oncomplete: function(r) {
2606 progressDialog.hide();
2607 var evt = openils.Util.readResponse(r);
2608 if(evt && evt.template_output()) {
2609 openils.Util.printHtmlString(evt.template_output().data());
2616 this.batchCreateInvoice = function() {
2617 var liIds = this.getSelected(false, null, true /* id_list */)
2618 if (!liIds.length) return;
2619 var path = oilsBasePath + '/acq/invoice/view?create=1';
2620 dojo.forEach(liIds, function(li, idx) { path += '&attach_li=' + li });
2621 location.href = path;
2624 this.batchLinkInvoice = function(create) {
2625 var liIds = this.getSelected(false, null, true /* id_list */)
2626 if (!liIds.length) return;
2627 if (!self.invoiceLinkDialogManager) {
2628 self.invoiceLinkDialogManager =
2629 new InvoiceLinkDialogManager("li");
2631 self.invoiceLinkDialogManager.target = liIds;
2632 acqLitLinkInvoiceDialog.show();
2635 this.receivePO = function() {
2636 if (!this.isPO) return;
2638 for (var id in this.liCache) {
2639 /* assumption: liCache reflects exactly the
2640 * set of LIs that belong to our PO */
2641 if (this.liCache[id].state() != "received" &&
2642 !this.checkLiAlerts(id)) return;
2645 this.show('acq-lit-progress-numbers');
2647 fieldmapper.standardRequest(
2648 ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
2650 params: [this.authtoken, this.isPO],
2651 onresponse : function(r) {
2652 var resp = openils.Util.readResponse(r);
2653 self._updateProgressNumbers(resp, true);
2659 this.issueReceive = function(obj, rollback) {
2661 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
2663 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
2665 progressDialog.show(true);
2666 fieldmapper.standardRequest(
2667 ["open-ils.acq", method], {
2669 "params": [this.authtoken, obj.id()],
2670 "onresponse": function(r) {
2671 if (r = openils.Util.readResponse(r)) {
2672 self.fetchClaimInfo(
2673 part == "lineitem" ? obj.id() : obj.lineitem(),
2675 function() { self.handleReceive(r); }
2677 progressDialog.hide();
2685 * Handles the responses from receive and rollback ML calls.
2687 this.handleReceive = function(resp) {
2690 for (var li_id in resp.li) {
2691 for (var key in resp.li[li_id])
2692 self.liCache[li_id][key](resp.li[li_id][key]);
2693 self.updateLiState(self.liCache[li_id]);
2697 if (typeof(self.poUpdateCallback) == "function")
2698 self.poUpdateCallback(resp.po);
2701 for (var lid_id in resp.lid) {
2702 for (var key in resp.lid[lid_id])
2703 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
2704 self.updateLidState(self.copyCache[lid_id]);
2710 this.rollbackPoReceive = function() {
2711 if(!this.isPO) return;
2712 if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
2713 this.show('acq-lit-progress-numbers');
2715 fieldmapper.standardRequest(
2716 ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
2718 params: [this.authtoken, this.isPO],
2719 onresponse : function(r) {
2720 var resp = openils.Util.readResponse(r);
2721 self._updateProgressNumbers(resp, true);
2727 this._updateProgressNumbers = function(resp, reloadOnComplete, onComplete) {
2728 this.vlAgent.handleResponse(resp,
2729 function(resp, res) {
2730 if(reloadOnComplete)
2731 location.href = location.href;
2733 onComplete(resp, res);
2739 this._createPO = function(fields) {
2740 var wantall = (fields.create_from == "all");
2742 /* If we're a picklist or purchase order already and the user wants
2743 * all lineitems, we might have pages' worth of lineitems haven't all
2744 * been loaded yet, so getSelected() won't find them. The server,
2745 * however, should know about all our lineitems, so let's ask the
2746 * server for a complete list.
2751 true, function(list) {
2752 self._createPOFromLineitems(fields, list);
2753 }, /* id_list */ true
2756 this._createPOFromLineitems(fields, this.getSelected(false, null, true /* id_list */));
2760 this._createPOFromLineitems = function(fields, selected) {
2761 if (selected.length == 0) return;
2764 var po = new fieldmapper.acqpo();
2765 po.provider(this.createPoProviderSelector.attr("value"));
2766 po.ordering_agency(this.createPoAgencySelector.attr("value"));
2767 po.prepayment_required(fields.prepayment_required[0] ? true : false);
2769 // if we're creating assets, delay the asset creation
2770 // until after the PO is created. This will allow us to
2771 // use showAssetCreator() directly.
2773 fieldmapper.standardRequest(
2774 ["open-ils.acq", "open-ils.acq.purchase_order.create"],
2777 openils.User.authtoken,
2778 po, {lineitems : selected}
2780 onresponse : function(r) {
2781 var resp = openils.Util.readResponse(r);
2782 if (resp.complete) {
2783 // self.isPO is needed for showAssetCreator();
2784 self.isPO = resp.purchase_order.id();
2785 var redir = oilsBasePath + "/acq/po/view/" + self.isPO;
2786 if (fields.create_assets[0]) {
2787 self.showAssetCreator(
2788 function() {location.href = redir}
2791 location.href = redir;
2800 this.batchFundWidget = null;
2802 this.applyBatchLiFunds = function() {
2804 var liIds = this.getSelected().map(function(li) { return li.id(); });
2805 if(liIds.length == 0) return; // warn?
2808 batchFundUpdateDialog.show();
2810 if(!this.batchFundWidget) {
2811 this.batchFundWidget = new openils.widget.AutoFieldWidget({
2813 selfReference : true,
2814 labelFormat : fundLabelFormat,
2815 searchFormat : fundSearchFormat,
2816 searchFilter : {"active": "t"},
2817 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
2818 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2819 dijitArgs : { "required": true, "labelType": "html" },
2822 this.batchFundWidget.build();
2825 dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
2826 dojo.connect(batchFundUpdateSubmit, 'onClick',
2829 // TODO: call .dry_run first to test thresholds
2830 fieldmapper.standardRequest(
2831 ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
2834 openils.User.authtoken,
2836 self.batchFundWidget.widget.attr('value')
2838 oncomplete : function(r) {
2839 var resp = openils.Util.readResponse(r);
2841 location.href = location.href;
2850 this._deleteLiList = function(list, idx) {
2851 if(idx == null) idx = 0;
2852 if(idx >= list.length) return;
2857 if (this.isPO && (li.state() == "on-order" || li.state() == "received")) {
2858 /* It makes little sense to delete a lineitem from a PO that has
2859 * already been marked 'on-order'. Especially if EDI is in use,
2860 * such a purchase order will probably have already been shipped
2861 * off to a vendor, and mucking with it at this point could leave
2862 * your data in a bad state that doesn't jive with reality.
2864 * I could see making this restriction even firmer.
2866 * I could also see adjusting the li state comparisons, extending
2867 * the comparison to the PO's state, and/or providing functions
2868 * that house the logic for comparing states in a single location.
2870 * Yes, this will be really annoying if you have selected a lot
2871 * of lineitems to cancel that have been ordered. You'll get a
2872 * confirm dialog for each one.
2875 if (!confirm(localeStrings.DEL_LI_FROM_PO)) {
2876 self._deleteLiList(list, ++idx); /* move on to next in list */
2881 fieldmapper.standardRequest(
2883 this.isPO ? 'open-ils.acq.purchase_order.lineitem.delete' : 'open-ils.acq.picklist.lineitem.delete'],
2885 params: [openils.User.authtoken, liId],
2886 oncomplete: function(r) {
2887 self.removeLineitem(liId);
2888 self._deleteLiList(list, ++idx);
2894 this.editOrderMarc = function(li) {
2896 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
2897 to true in about:config */
2899 if(openils.XUL.isXUL()) {
2900 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul','','chrome');
2902 win = window.open('/xul/server/cat/marcedit.xul','','chrome');
2906 record : {marc : li.marc(), "rtype": "bre"},
2908 label: 'Save Record', // XXX I18N
2909 func: function(xmlString) {
2911 fieldmapper.standardRequest(
2912 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
2914 params: [openils.User.authtoken, li],
2915 oncomplete: function(r) {
2916 openils.Util.readResponse(r);
2918 self.drawInfo(li.id())
2924 'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
2925 'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
2929 this._savePl = function(values) {
2931 (values.which == 'all'),
2932 function(list) { self._savePlFromLineitems(values, list); }
2936 this._savePlFromLineitems = function(values, selected) {
2937 openils.Util.show("acq-lit-generic-progress");
2939 if(values.new_name) {
2940 openils.acq.Picklist.create(
2941 {name: values.new_name},
2947 oilsBasePath + "/acq/picklist/view/" + id;
2952 } else if(values.existing_pl) {
2953 // update lineitems to use an existing picklist
2955 values.existing_pl, selected, 0,
2958 oilsBasePath + "/acq/picklist/view/" +
2965 this._updateLiState = function(values, state) {
2966 progressDialog.show(true);
2968 (values.which == 'all'),
2970 self._updateLiStateFromLineitems(values, state, list);
2975 this._updateLiStateFromLineitems = function(values, state, selected) {
2976 if(!selected.length) return;
2977 dojo.forEach(selected, function(li) {li.state(state);});
2978 self._updateLiList(null, selected, 0,
2979 // TODO consider inline updates for efficiency
2980 function() { location.href = location.href }
2984 this._updateLiList = function(pl, list, idx, oncomplete) {
2985 if(idx >= list.length) return oncomplete();
2987 if(pl != null) li.picklist(pl);
2988 litGenericProgress.update({maximum: list.length, progress: idx});
2989 new openils.acq.Lineitem({lineitem:li}).update(
2991 self._updateLiList(pl, list, ++idx, oncomplete);
2996 this._loadPOSelect = function() {
2997 if (!this.createPoProviderSelector) {
2998 var widget = new openils.widget.AutoFieldWidget({
2999 "fmField": "provider",
3001 "searchFilter": {"active": "t"},
3002 "parentNode": dojo.byId("acq-lit-po-provider"),
3004 "onChange": function() {
3006 self._updateCreatePoPrepayCheckbox(
3007 this.item.prepayment_required()
3013 widget.build(function(w) { self.createPoProviderSelector = w; });
3016 if (!this.createPoAgencySelector) {
3017 var widget = new openils.widget.AutoFieldWidget({
3018 "fmField": "ordering_agency",
3020 "parentNode": dojo.byId("acq-lit-po-agency"),
3021 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3023 widget.build(function(w) { self.createPoAgencySelector = w; });
3027 this.showRealCopyEditUI = function(li) {
3032 this._fetchLineitem(li.id(),
3034 li = self.liCache[li.id()] = fullLi;
3038 id : li.lineitem_details().map(
3039 function(item) { return item.eg_copy_id() }
3043 oncomplete : function(r) {
3045 var r_list = openils.Util.readResponse( r );
3046 for (var i = 0; i < r_list.length; i++) {
3047 var copy = r_list[i];
3048 var volId = copy.call_number();
3049 var volume = self.volCache[volId];
3051 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
3053 copy.call_number(volume);
3054 copyList.push(copy);
3057 xulG.volume_item_creator( { 'existing_copies' : copyList } );
3060 alert('error in oncomplete: ' + E);
3069 this.drawBibFinder = function(li) {
3072 var liWrapper = new openils.acq.Lineitem({lineitem:li});
3075 ['isbn', 'upc', 'issn', 'title', 'author'],
3077 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
3079 if(field == 'title' || field == 'author') {
3080 query += field +':' + val + ' ';
3082 query += 'identifier|' + field + ':' + val + ' ';
3089 oilsBasePath + '/acq/lineitem/findbib?query=' + escape(query),
3090 '', 'resizable,scrollbars=1,chrome');
3092 win.window.recordFound = function(bibId) {
3095 var attrs = li.attributes();
3096 li.attributes(null);
3097 li.eg_bib_id(bibId);
3099 fieldmapper.standardRequest(
3100 ["open-ils.acq", "open-ils.acq.lineitem.update"],
3102 "params": [openils.User.authtoken, li],
3104 "oncomplete": function(r) {
3105 if(openils.Util.readResponse(r)) {
3106 location.href = location.href;