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 // capture the inline copy display wrapper and row template
95 this.inlineCopyContainer =
96 this.tbody.removeChild(dojo.byId('acq-inline-copies-row'));
98 '[name=acq-li-inline-copies-tbody]', this.inlineCopyContainer)[0];
99 this.inlineCopyTemplate = tb.removeChild(
100 dojo.query('[name=acq-li-inline-copies-template]', tb)[0]);
101 this.inlineNoCopies = tb.removeChild(
102 dojo.query('[name=acq-li-inline-copies-none]', tb)[0]);
104 // list of LI IDs that should be refreshed at next display time
105 this.inlineCopiesNeedingRefresh = [];
107 dojo.byId("acq-lit-li-actions-selector").onchange = function() {
108 self.applySelectedLiAction(this.options[this.selectedIndex].value);
109 this.selectedIndex = 0;
112 acqLitCreatePoSubmit.onClick = function() {
113 if (!self.createPoProviderSelector.attr("value") ||
114 !self.createPoAgencySelector.attr("value")) {
115 alert(localeStrings.CREATE_PO_INVALID);
117 } else if (self._confirmPoPrepaySituation()) {
118 acqLitPoCreateDialog.hide();
119 self._createPO(acqLitPoCreateDialog.getValues());
125 acqLitSavePlButton.onClick = function() {
126 acqLitSavePlDialog.hide();
127 self._savePl(acqLitSavePlDialog.getValues());
130 acqLitCancelLiStateButton.onClick = function() {
131 acqLitChangeLiStateDialog.hide();
133 acqLitSaveLiStateButton.onClick = function() {
134 acqLitChangeLiStateDialog.hide();
135 self._updateLiState(acqLitChangeLiStateDialog.getValues(), acqLitChangeLiStateDialog.attr('state'));
139 dojo.byId('acq-lit-select-toggle').onclick = function(){self.toggleSelect()};
140 dojo.byId('acq-inline-copies-toggle').onclick = function(){self.toggleInlineCopies()};
141 dojo.byId('acq-lit-info-back-button').onclick = function(){self.show('list')};
142 dojo.byId('acq-lit-copies-back-button').onclick = function(){self.show('list')};
143 dojo.byId('acq-lit-notes-back-button').onclick = function(){self.show('list')};
144 dojo.byId('acq-lit-real-copies-back-button').onclick = function(){self.show('list')};
146 this.reset = function(keep_selectors) {
147 while(self.tbody.childNodes[0])
148 self.tbody.removeChild(self.tbody.childNodes[0]);
156 this.setNext = function(handler) {
157 var link = dojo.byId('acq-lit-next');
159 dojo.style(link, 'visibility', 'visible');
160 link.onclick = handler;
162 dojo.style(link, 'visibility', 'hidden');
166 this.setPrev = function(handler) {
167 var link = dojo.byId('acq-lit-prev');
169 dojo.style(link, 'visibility', 'visible');
170 link.onclick = handler;
172 dojo.style(link, 'visibility', 'hidden');
177 * Ensures this.focusLineitem is in view and causes a brief
178 * border around the lineitem to come to life then fade.
180 this.focusLi = function() {
181 if (!this.focusLineitem) return;
183 // set during addLineitem()
184 var node = dojo.byId('li-title-ref-' + this.focusLineitem);
186 // LI may not yet be rendered
189 // prevent numerous re-focuses
190 this.focusLineitem = null;
192 // causes the full row to be visible
193 dijit.scrollIntoView(node);
196 dojo.query('[attr=title]', node)[0].focus();
198 dojo.require('dojox.fx');
202 dojox.fx.highlight({color : '#BB4433', node : node, duration : 2000}).play();
207 this.show = function(div) {
208 openils.Util.hide('acq-lit-table-div');
209 openils.Util.hide('acq-lit-info-div');
210 openils.Util.hide('acq-lit-li-details');
211 openils.Util.hide('acq-lit-notes-div');
212 openils.Util.hide('acq-lit-real-copies-div');
213 openils.Util.hide('acq-lit-asset-creator');
216 openils.Util.show('acq-lit-table-div');
218 this.refreshInlineCopies();
221 openils.Util.show('acq-lit-info-div');
224 openils.Util.show('acq-lit-li-details');
227 openils.Util.show('acq-lit-real-copies-div');
230 openils.Util.show('acq-lit-notes-div');
232 case 'asset-creator':
233 openils.Util.show('acq-lit-asset-creator');
237 openils.Util.show(div);
241 this.hide = function() {
245 this.toggleSelect = function() {
247 dojo.forEach(self.selectors, function(i){i.checked = false});
249 dojo.forEach(self.selectors, function(i){i.checked = true});
250 self.toggleState = !self.toggleState;
254 this.getAll = function(callback, id_only) {
255 /* For some uses of the li table, we may not really know about "all"
256 * the lineitems that the user thinks we know about. If we're a paged
257 * picklist, for example, we only know about the lineitems we've
258 * displayed, but not necessarily all the lineitems on the picklist.
259 * So we reach out to pcrud to inform us.
262 var oncomplete = function(r) {
263 var id_list = openils.Util.readResponse(r);
267 self.fetchLineitemsById(id_list, callback);
272 "jub", {"picklist": this.isPL}, {
273 "id_list": true, /* sic, even if id_only */
275 "oncomplete": oncomplete
279 } else if (this.isPO) {
281 "jub", {"purchase_order": this.isPO}, {
284 "oncomplete": oncomplete
288 } else if (this.isUni && this.pager) {
289 this.pager.getAllLineitemIDs(oncomplete);
293 /* If execution reaches this point, we don't need or can't perform
294 * any special tricks to find out the "real" list of "all" lineitems
295 * in this context, so we fall back to the old method.
297 callback(this.getSelected(true, null, id_only));
300 /** @param all If true, assume all are selected */
301 this.getSelected = function(
303 callback /* If you want a "good" idea of "all" lineitems, you must
304 provide a callback that accepts an array parameter, rather than
305 relying on the return value of this method itself. */,
309 return this.getAll(callback, id_only);
311 var indices = {}; /* use to uniqify. needed in paging situations. */
312 dojo.forEach(this.selectors,
315 indices[i.parentNode.parentNode.getAttribute('li')] = true;
319 var result = openils.Util.objectProperties(indices);
322 result = result.map(function(liId) { return self.liCache[liId]; });
330 this.setRowAttr = function(td, liWrapper, field, type) {
331 var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
332 td.appendChild(document.createTextNode(val));
335 this.setClaimPolicyControl = function(li, row) {
336 if (!self.claimPolicyPicker) {
337 self.claimPolicyPicker = true; /* prevents a race condition */
338 new openils.widget.AutoFieldWidget({
339 "parentNode": "acq-lit-li-claim-policy",
341 "selfReference": true,
342 "dijitArgs": {"required": true}
343 }).build(function(w) { self.claimPolicyPicker = w; });
346 if (!row) row = this._findLiRow(li);
348 var actViewPolicy = nodeByName("action_view_claim_policy", row);
349 if (li.claim_policy())
350 actViewPolicy.innerHTML = localeStrings.CHANGE_CLAIM_POLICY;
352 if (!actViewPolicy.onclick) {
353 actViewPolicy.onclick = function() {
354 if (li.claim_policy())
355 self.claimPolicyPicker.attr("value", li.claim_policy());
356 liClaimPolicyDialog.show();
357 liClaimPolicySave.onClick = function() {
358 self.changeClaimPolicy(
359 [li], self.claimPolicyPicker.attr("value"),
361 self.setClaimPolicyControl(li, row);
362 self.reconsiderClaimControl(li, row);
363 liClaimPolicyDialog.hide();
371 this.fetchClaimInfo = function(liId, force, callback, row) {
373 liId, function(full) {
374 self.liCache[full.id()] = full;
375 self.checkClaimEligibility(full, callback, row);
381 * Inserts a single lineitem into the growing table of lineitems
382 * @param {Object} li The lineitem object to insert
384 this.addLineitem = function(li, skip_final_placement) {
385 this.liCache[li.id()] = li;
387 // insert the row right away so that final order isn't
388 // dependent on how long subsequent async request take
389 // for a given line item
390 var row = self.rowTemplate.cloneNode(true);
391 if (!skip_final_placement) {
392 self.tbody.appendChild(row);
394 self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
396 // sort the lineitem notes on edit_time
397 if(!li.lineitem_notes()) li.lineitem_notes([]);
399 var liWrapper = new openils.acq.Lineitem({lineitem:li});
400 row.setAttribute('li', li.id());
401 var tds = dojo.query('[attr]', row);
402 dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
403 dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
405 // so we can scroll to it later
406 dojo.query('[name=bib-info-cell]', row)[0].id = 'li-title-ref-' + li.id();
409 liWrapper.findAttr("isbn", "lineitem_marc_attr_definition") ||
410 liWrapper.findAttr("upc", "lineitem_marc_attr_definition");
412 // XXX media prefix for added content
414 nodeByName("jacket", row).setAttribute(
415 "src", "/opac/extras/ac/jacket/small/" + identifier
419 nodeByName("liid", row).innerHTML += li.id();
422 openils.Util.show(nodeByName('catalog', row), 'inline');
423 nodeByName("catalog_link", row).onclick = this.generateMakeRecTab(li.eg_bib_id());
425 openils.Util.show(nodeByName('link_to_catalog', row), 'inline');
426 nodeByName("link_to_catalog_link", row).onclick = function() { self.drawBibFinder(li) };
429 if (li.queued_record()) {
430 this.pcrud.retrieve('vqbr', li.queued_record(),
432 oncomplete : function(r) {
433 var qrec = openils.Util.readResponse(r);
434 openils.Util.show(nodeByName('queue', row), 'inline');
435 var link = nodeByName("queue_link", row);
436 link.onclick = function() {
437 // open a new tab to the vandelay queue for this record
438 openils.XUL.newTabEasy(
439 oilsBasePath + '/vandelay/vandelay?qtype=bib&qid=' + qrec.queue()
447 nodeByName("worksheet_link", row).href =
448 oilsBasePath + "/acq/lineitem/worksheet/" + li.id() +
449 '?source=' + encodeURIComponent(location.pathname + location.search)
451 nodeByName("show_requests_link", row).href =
452 oilsBasePath + "/acq/picklist/user_request?lineitem=" + li.id() +
453 '?source=' + encodeURIComponent(location.pathname + location.search)
455 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
456 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
457 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
458 dojo.query('[name=expand_inline_copies]', row)[0].onclick =
459 function() {self.drawInlineCopies(li.id())};
461 this.drawOrderIdentSelector(li, row);
463 if (!this.skipInitialEligibilityCheck)
467 function(full) { self.setClaimPolicyControl(full, row) },
471 this.updateLiNotesCount(li, row);
473 // show which PO this lineitem is a member of
474 if(li.purchase_order() && !this.isPO) {
476 this.poCache[li.purchase_order()] =
477 this.poCache[li.purchase_order()] ||
478 fieldmapper.standardRequest(
479 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
481 this.authtoken, li.purchase_order(), {
482 "flesh_price_summary": true,
483 "flesh_provider" : true,
484 "flesh_lineitem_count": true
487 if(po && !this.isMeta) {
488 openils.Util.show(nodeByName('po', row), 'inline');
489 var link = nodeByName('po_link', row);
490 link.setAttribute('href', oilsBasePath +
491 '/acq/po/view/' + li.purchase_order() +
492 '?focus_li=' + li.id() +
493 '&source=' + encodeURIComponent(location.pathname + location.search)
495 link.innerHTML += po.name();
497 openils.Util.show(nodeByName('pro', row), 'inline');
498 link = nodeByName('pro_link', row);
499 link.setAttribute('href', oilsBasePath + '/conify/global/acq/provider/' + po.provider().id())
500 link.innerHTML += po.provider().code();
504 // show which picklist this lineitem is a member of
505 if(li.picklist() && (this.isPO || this.isMeta || this.isUni)) {
507 this.plCache[li.picklist()] =
508 this.plCache[li.picklist()] ||
509 fieldmapper.standardRequest(
510 ['open-ils.acq', 'open-ils.acq.picklist.retrieve.authoritative'],
511 {params: [this.authtoken, li.picklist()]});
513 if (pl.name() == "") {
514 openils.Util.show(nodeByName("bib_origin", row), "inline");
518 openils.Util.show(nodeByName('pl', row), 'inline');
519 var link = nodeByName('pl_link', row);
520 link.setAttribute('href', oilsBasePath +
521 '/acq/picklist/view/' + li.picklist() +
522 '?focus_li=' + li.id() +
523 '&source=' + encodeURIComponent(location.pathname + location.search)
525 link.innerHTML += pl.name();
530 var countNode = nodeByName('count', row);
531 var count = li.item_count() || 0;
532 if (typeof(this._copy_count_cb) == "function") {
533 this._copy_count_cb(li.id(), count);
535 countNode.innerHTML = count;
536 countNode.id = 'acq-lit-copy-count-label-' + li.id();
539 var priceInput = dojo.query('[name=price]', row)[0];
540 priceInput.value = li.estimated_unit_price() || '';
541 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
543 // show either "mark received" or "unreceive" as appropriate
544 this.updateLiState(li, row);
546 if (skip_final_placement) {
550 // the last LI may be rendered after the call to show('list'),
551 // so make sure it's focused if necessary.
552 if (this.focusLineitem == li.id())
556 this._liCountClaims = function(li) {
558 for (var i = 0; i < li.lineitem_details().length; i++)
559 total += li.lineitem_details()[i].claims().length;
563 this._findLiRow = function(li) {
564 return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
567 this.reconsiderClaimControl = function(li, row) {
568 if (!row) row = this._findLiRow(li);
569 var option = nodeByName("action_manage_claims", row);
570 var eligible = this.claimEligibleLidByLi[li.id()].length;
571 var count = this._liCountClaims(li);
573 option.disabled = !(count || eligible);
575 dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
576 option.onclick = function() { self.claimDialog.show(li); };
579 this.clearEligibility = function(li) {
580 this.claimEligibleLidByLi[li.id()] = [];
582 if (li.lineitem_details()) {
583 li.lineitem_details().forEach(
584 function(lid) { delete self.claimEligibleLid[lid.id()]; }
588 if (this.copyCache) {
590 for (var k in this.copyCache) {
591 if (this.copyCache[k].lineitem() == li.id())
595 function(k) { delete self.claimEligibleLid[k]; }
600 this.applyOrderIdentValues = function() {
601 this._identValuesInFlight =
602 openils.Util.objectProperties(this.liCache).length;
603 for (var liId in this.liCache) {
604 this._applyOrderIdentValue(this.liCache[liId]);
608 // returns true if request was sent
609 this._applyOrderIdentValue = function(li) {
612 console.log('applying ident value for lineitem ' + li.id());
615 var row = dojo.query('[li=' + li.id() + ']')[0];
617 // find the selected ident value
618 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
619 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
620 var name = typeSel.options[typeSel.selectedIndex].value;
621 var val = typeSel._cbox.attr('value');
623 console.log("selected ident is " + val);
625 // it differs from the existing ident value, update it
626 var oldIdent = self.getLiOrderIdent(li);
628 oldIdent.attr_name() == name &&
629 oldIdent.attr_value() == val) {
630 console.log('selected ident attr matches existing attr');
631 if (--this._identValuesInFlight == 0)
632 location.href = location.href;
636 // see if the selected ident value is represented
637 // by an existing lineitem attr
640 typeSel._cbox.store.fetch({
641 query : {attr_value : val},
642 onItem : function(item) {
643 console.log('found existing attr for ident value');
644 args.source_attr_id = li.attributes().filter(
645 function(attr) { return attr.id() == item.id[0] }
651 if (!args.source_attr_id) {
652 // user entered new text in the combobox
653 // so we need to create a new attr
654 console.log('creating new ident attr');
655 args.lineitem_id = li.id();
656 args.attr_name = name;
657 args.attr_value = val;
660 fieldmapper.standardRequest(
661 ['open-ils.acq', 'open-ils.acq.lineitem.order_identifier.set'],
663 params : [openils.User.authtoken, args],
664 oncomplete : function() {
665 console.log('order_ident oncomplete');
666 if (--self._identValuesInFlight == 0)
667 location.href = location.href;
675 this.getLiOrderIdent = function(li) {
676 var attrs = li.attributes();
677 if (!attrs) return null;
681 attr.attr_type() == 'lineitem_local_attr_definition' &&
682 openils.Util.isTrue(attr.order_ident())
688 this.drawOrderIdentSelector = function(li, row) {
690 var typeSel = dojo.query('[name=order_ident_type]', row)[0];
691 var valueSel = dojo.query('[name=order_ident_value]', row)[0];
693 var attrs = li.attributes();
695 // limit to MARC attr defs
696 attrs = attrs.filter(
698 return (attr.attr_type() == 'lineitem_marc_attr_definition');
702 var identAttr = this.getLiOrderIdent(li);
705 // collect the values for each type of identifier
706 // find a reasonable default identifier type to render
710 dojo.forEach(['isbn', 'upc', 'issn'],
713 // collect the values for this attr name
714 values[name] = attrs.filter(
716 return (attr.attr_name() == name)
720 // select a reasonable default name in the type-selector
724 if (identAttr.attr_name() == name)
726 } else if (values[name].length) {
731 dojo.forEach(typeSel.options, function(opt) {
732 if (opt.value == name) {
742 function updateOrderIdent(box) {
743 console.log('updating order ident for box ' + box);
746 // replace the ident combobox with a new
747 // one for the selected ident type
748 function changeComboBox(sel) {
749 var name = sel.options[sel.selectedIndex].value;
751 var td = dojo.query('[name=order_ident_value]', row)[0];
752 if (td.childNodes[0])
753 dojo.destroy(td.childNodes[0]);
755 var store = new dojo.data.ItemFileWriteStore({
756 data : acqlia.toStoreData(values[name])
759 var cbox = new dijit.form.ComboBox(
761 labelAttr : 'attr_value',
762 searchAttr : 'attr_value'
764 dojo.create('div', {}, td)
769 // set the value for the cbox
770 if (values[name].length) {
771 var orderIdent = self.getLiOrderIdent(li);
773 if (orderIdent && orderIdent.attr_name() == name) {
774 cbox.attr('value', orderIdent.attr_value());
776 cbox.attr('value', values[name][0].attr_value());
780 if (!self.orderIdentAllowed)
781 cbox.attr('disabled', true);
785 dojo.connect(cbox, 'onChange', updateOrderIdent);
788 changeComboBox(typeSel); // force the initial draw
789 typeSel.onchange = function() {changeComboBox(typeSel)};
792 this.testOrderIdentPerms = function(org, callback) {
794 new openils.User().getPermOrgList(
795 'ACQ_SET_LINEITEM_IDENTIFIER',
797 console.log('found orgs = ' + orgs);
798 for (var i = 0; i < orgs.length; i++) {
799 if (Number(orgs[i]) == Number(org)) {
800 self.orderIdentAllowed = true;
801 if (callback) callback();
805 if (callback) callback();
811 this.checkClaimEligibility = function(li, callback, row) {
812 /* Assume always eligible, i.e. from this interface we don't care about
813 * claim eligibility any more. this is where the user would force a
815 this.clearEligibility(li);
816 this.claimEligibleLidByLi[li.id()] = li.lineitem_details().map(
817 function(lid) { return lid.id(); }
819 li.lineitem_details().forEach(
820 function(lid) { self.claimEligibleLid[lid.id()] = true; }
822 this.reconsiderClaimControl(li, row);
823 if (callback) callback(li);
825 this.clearEligibility(li);
826 fieldmapper.standardRequest(
827 ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
828 "params": [openils.User.authtoken, {"lineitem": li.id()}],
830 "onresponse": function(r) {
831 if (r = openils.Util.readResponse(r)) {
832 self.claimEligibleLidByLi[li.id()].push(
835 self.claimEligibleLid[r.lineitem_detail()] = true;
838 "oncomplete": function() {
839 self.reconsiderClaimControl(li, row);
840 if (typeof(callback) == "function")
848 this.updateLiNotesCount = function(li, row) {
849 if (!row) row = this._findLiRow(li);
851 var has_notes = (li.lineitem_notes().filter(
852 function(o) { return Boolean (o.alert_text()); }
855 /* U+2691 is the code point for a filled-in flag character */
856 nodeByName("notes_alert_flag", row).innerHTML =
857 has_notes ? "⚑" : "";
858 nodeByName("noteslink", row).style.fontStyle =
859 has_notes ? "italic" : "normal";
860 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
863 /* XXX NOT related to _updateLiState(). rethink */
864 this.updateLiState = function(li, row) {
865 if (!row) row = this._findLiRow(li);
867 var actReceive = nodeByName("action_mark_recv", row);
868 var actUnRecv = nodeByName("action_mark_unrecv", row);
869 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
870 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
871 var actNewInvoice = nodeByName('action_new_invoice', row);
872 var actLinkInvoice = nodeByName('action_link_invoice', row);
873 var actViewInvoice = nodeByName('action_view_invoice', row);
875 // always allow access to LI history
876 nodeByName('action_view_history', row).onclick =
877 function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
879 /* handle row coloring for based on LI state */
880 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
881 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
883 // Expose invoice actions for any lineitem that is linked to a PO
884 if( li.purchase_order() ) {
886 actNewInvoice.disabled = false;
887 actLinkInvoice.disabled = false;
888 actViewInvoice.disabled = false;
890 actNewInvoice.onclick = function() {
891 location.href = oilsBasePath + '/acq/invoice/view?create=1&attach_li=' + li.id();
892 nodeByName("action_none", row).selected = true;
895 actLinkInvoice.onclick = function() {
896 if (!self.invoiceLinkDialogManager) {
897 self.invoiceLinkDialogManager =
898 new InvoiceLinkDialogManager("li");
900 self.invoiceLinkDialogManager.target = li;
901 acqLitLinkInvoiceDialog.show();
902 nodeByName("action_none", row).selected = true;
905 actViewInvoice.onclick = function() {
906 location.href = oilsBasePath +
907 "/acq/search/unified?so=" +
908 base64Encode({"jub":[{"id": li.id()}]}) +
910 nodeByName("action_none", row).selected = true;
916 * If we haven't fleshed the lineitem_details, default to allowing access to the
917 * holdings maintenence actions. The alternative is to flesh LIDs on every lineitem,
918 * but that will add to page render time. Let's see if this will suffice...
920 var lids = li.lineitem_details();
922 (lids && !lids.filter(function(lid) { return lid.eg_copy_id() })[0] )) {
924 actUpdateBarcodes.disabled = false;
925 actUpdateBarcodes.onclick = function() {
926 self.showRealCopyEditUI(li);
927 nodeByName("action_none", row).selected = true;
929 actHoldingsMaint.disabled = false;
930 actHoldingsMaint.onclick =
931 self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
934 var state_cell = nodeByName("li_state", row);
939 if(typeof li.cancel_reason() == "object") {
940 var holds_state = dojo.create(
942 "style": "border-bottom: 1px dashed #000;",
943 "innerHTML": li.state()
944 }, state_cell, "only"
948 "label": "<em>" + li.cancel_reason().label() +
949 "</em><br />" + li.cancel_reason().description(),
950 "connectId": [holds_state]
951 }, dojo.create("span", null, state_cell, "last")
957 actReceive.disabled = false;
958 actReceive.onclick = function() {
959 if (self.checkLiAlerts(li.id()))
960 self.issueReceive(li);
961 nodeByName("action_none", row).selected = true;
966 actUnRecv.disabled = false;
967 actUnRecv.onclick = function() {
968 if (confirm(localeStrings.UNRECEIVE_LI))
969 self.issueReceive(li, /* rollback */ true);
970 nodeByName("action_none", row).selected = true;
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 'create_order':
2490 this._loadPOSelect();
2491 acqLitPoCreateDialog.show();
2494 case 'save_picklist':
2495 acqLitSavePlDialog.show();
2498 case 'selector_ready':
2500 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
2501 acqLitChangeLiStateDialog.show();
2509 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
2512 case 'batch_create_invoice':
2513 this.batchCreateInvoice();
2516 case 'batch_link_invoice':
2517 this.batchLinkInvoice();
2524 case 'rollback_receive_po':
2525 this.rollbackPoReceive();
2528 case 'create_assets':
2529 this.showAssetCreator();
2532 case 'export_attr_list':
2533 this.chooseExportAttr();
2536 case 'batch_apply_funds':
2537 this.applyBatchLiFunds();
2540 case 'add_brief_record':
2542 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
2544 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
2548 case "cancel_lineitems":
2549 this.maybeCancelLineitems();
2552 case "change_claim_policy":
2553 var li_list = this.getSelected();
2554 this.claimPolicyPicker.attr("value", null);
2555 liClaimPolicyDialog.show();
2556 liClaimPolicySave.onClick = function() {
2557 self.changeClaimPolicy(
2559 self.claimPolicyPicker.attr("value"),
2563 self.setClaimPolicyControl(li);
2564 self.reconsiderClaimControl(li);
2567 liClaimPolicyDialog.hide();
2575 this.changeClaimPolicy = function(li_list, value, callback) {
2577 function(li) { li.claim_policy(value); }
2579 fieldmapper.standardRequest(
2580 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
2581 "params": [openils.User.authtoken, li_list],
2583 "oncomplete": function(r) {
2584 r = openils.Util.readResponse(r);
2585 if (callback) callback(r);
2591 this.showAssetCreator = function(onAssetsCreated) {
2592 if(!this.isPO) return;
2595 // first, let's see if this PO has any LI's that need to be merged/imported
2596 self.pcrud.search('jub', {purchase_order : this.isPO, eg_bib_id : null}, {
2598 oncomplete : function(r) {
2599 var resp = openils.Util.readResponse(r);
2600 if (resp && resp.length) {
2601 // PO has some non-linked jubs.
2603 self.show('asset-creator');
2604 if(!self.vlAgent.loaded)
2605 self.vlAgent.init();
2607 dojo.connect(assetCreatorButton, 'onClick',
2608 function() { self.createAssets(onAssetsCreated) });
2612 // all jubs linked, move on to asset creation
2613 self.createAssets(onAssetsCreated, true);
2619 this.createAssets = function(onAssetsCreated, noVl) {
2620 this.show('acq-lit-progress-numbers');
2622 var vlArgs = (noVl) ? {} : {vandelay : this.vlAgent.values()};
2623 fieldmapper.standardRequest(
2624 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
2626 params: [this.authtoken, this.isPO, vlArgs],
2627 onresponse: function(r) {
2628 var resp = openils.Util.readResponse(r);
2629 self._updateProgressNumbers(resp, !Boolean(onAssetsCreated), onAssetsCreated);
2635 this.maybeCancelLineitems = function() {
2636 openils.Util.show("acq-lit-cancel-reason", "inline");
2637 if (!acqLitCancelLineitemsButton._prepared) {
2638 var widget = new openils.widget.AutoFieldWidget({
2639 "fmField": "cancel_reason",
2641 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
2642 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2647 acqLitCancelLineitemsButton.onClick = function() {
2648 if (w.attr("value")) {
2649 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
2650 self._cancelLineitems(w.attr("value"));
2652 openils.Util.hide("acq-lit-cancel-reason");
2655 acqLitCancelLineitemsButton._prepared = true;
2661 this._cancelLineitems = function(reason) {
2662 var id_list = this.getSelected().map(function(o) { return o.id(); });
2663 fieldmapper.standardRequest(
2664 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
2665 "params": [openils.User.authtoken, id_list, reason],
2667 "onresponse": function(r) {
2668 if (r = openils.Util.readResponse(r)) {
2670 for (var id in r.li) {
2671 self.liCache[id].state(r.li[id].state);
2672 self.liCache[id].cancel_reason(
2673 r.li[id].cancel_reason
2675 self.updateLiState(self.liCache[id]);
2678 if (r.lid && self.copyCache) {
2679 for (var id in r.lid) {
2680 if (self.copyCache[id]) {
2681 self.copyCache[id].cancel_reason(
2682 r.lid[id].cancel_reason
2684 self.updateLidState(self.copyCache[id]);
2694 this.chooseExportAttr = function() {
2695 if (!acqLitExportAttrSelector._li_setup) {
2697 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
2699 "data": acqlimad.toStoreData(
2701 "acqlimad", {"code": li_exportable_attrs}
2706 acqLitExportAttrSelector.setValue();
2707 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
2708 acqLitExportAttrSelector._li_setup = true;
2710 openils.Util.show("acq-lit-export-attr-holder", "inline");
2713 this.exportAttrList = function() {
2714 var attr_def = acqLitExportAttrSelector.item;
2715 var li_list = this.getSelected();
2716 var value_list = li_list.map(
2718 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2719 attr_def.code, "lineitem_marc_attr_definition"
2722 ).filter(function(attr) { return Boolean(attr); });
2724 if (value_list.length > 0) {
2725 if (value_list.length < li_list.length) {
2727 dojo.string.substitute(
2728 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
2735 openils.XUL.contentToFileSaveDialog(
2736 value_list.join("\n"),
2737 localeStrings.EXPORT_SAVE_DIALOG_TITLE
2743 alert(dojo.string.substitute(
2744 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
2748 openils.Util.hide("acq-lit-export-attr-holder");
2751 this.printPO = function() {
2752 if(!this.isPO) return;
2753 progressDialog.show(true);
2754 fieldmapper.standardRequest(
2755 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
2757 params: [this.authtoken, this.isPO, 'html'],
2758 oncomplete: function(r) {
2759 progressDialog.hide();
2760 var evt = openils.Util.readResponse(r);
2761 if(evt && evt.template_output()) {
2762 openils.Util.printHtmlString(evt.template_output().data());
2769 this.batchCreateInvoice = function() {
2770 var liIds = this.getSelected(false, null, true /* id_list */)
2771 if (!liIds.length) return;
2772 var path = oilsBasePath + '/acq/invoice/view?create=1';
2773 dojo.forEach(liIds, function(li, idx) { path += '&attach_li=' + li });
2774 location.href = path;
2777 this.batchLinkInvoice = function(create) {
2778 var liIds = this.getSelected(false, null, true /* id_list */)
2779 if (!liIds.length) return;
2780 if (!self.invoiceLinkDialogManager) {
2781 self.invoiceLinkDialogManager =
2782 new InvoiceLinkDialogManager("li");
2784 self.invoiceLinkDialogManager.target = liIds;
2785 acqLitLinkInvoiceDialog.show();
2788 this.receivePO = function() {
2789 if (!this.isPO) return;
2791 for (var id in this.liCache) {
2792 /* assumption: liCache reflects exactly the
2793 * set of LIs that belong to our PO */
2794 if (this.liCache[id].state() != "received" &&
2795 !this.checkLiAlerts(id)) return;
2798 this.show('acq-lit-progress-numbers');
2800 fieldmapper.standardRequest(
2801 ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
2803 params: [this.authtoken, this.isPO],
2804 onresponse : function(r) {
2805 var resp = openils.Util.readResponse(r);
2806 self._updateProgressNumbers(resp, true);
2812 this.issueReceive = function(obj, rollback) {
2814 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
2816 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
2818 progressDialog.show(true);
2819 fieldmapper.standardRequest(
2820 ["open-ils.acq", method], {
2822 "params": [this.authtoken, obj.id()],
2823 "onresponse": function(r) {
2824 if (r = openils.Util.readResponse(r)) {
2825 self.fetchClaimInfo(
2826 part == "lineitem" ? obj.id() : obj.lineitem(),
2828 function() { self.handleReceive(r); }
2830 progressDialog.hide();
2838 * Handles the responses from receive and rollback ML calls.
2840 this.handleReceive = function(resp) {
2843 for (var li_id in resp.li) {
2844 for (var key in resp.li[li_id])
2845 self.liCache[li_id][key](resp.li[li_id][key]);
2846 self.updateLiState(self.liCache[li_id]);
2850 if (typeof(self.poUpdateCallback) == "function")
2851 self.poUpdateCallback(resp.po);
2854 for (var lid_id in resp.lid) {
2855 for (var key in resp.lid[lid_id])
2856 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
2857 self.updateLidState(self.copyCache[lid_id]);
2863 this.rollbackPoReceive = function() {
2864 if(!this.isPO) return;
2865 if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
2866 this.show('acq-lit-progress-numbers');
2868 fieldmapper.standardRequest(
2869 ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
2871 params: [this.authtoken, this.isPO],
2872 onresponse : function(r) {
2873 var resp = openils.Util.readResponse(r);
2874 self._updateProgressNumbers(resp, true);
2880 this._updateProgressNumbers = function(resp, reloadOnComplete, onComplete) {
2881 this.vlAgent.handleResponse(resp,
2882 function(resp, res) {
2883 if(reloadOnComplete)
2884 location.href = location.href;
2886 onComplete(resp, res);
2892 this._createPO = function(fields) {
2893 var wantall = (fields.create_from == "all");
2895 /* If we're a picklist or purchase order already and the user wants
2896 * all lineitems, we might have pages' worth of lineitems haven't all
2897 * been loaded yet, so getSelected() won't find them. The server,
2898 * however, should know about all our lineitems, so let's ask the
2899 * server for a complete list.
2904 true, function(list) {
2905 self._createPOFromLineitems(fields, list);
2906 }, /* id_list */ true
2909 this._createPOFromLineitems(fields, this.getSelected(false, null, true /* id_list */));
2913 this._createPOFromLineitems = function(fields, selected) {
2914 if (selected.length == 0) return;
2917 var po = new fieldmapper.acqpo();
2918 po.provider(this.createPoProviderSelector.attr("value"));
2919 po.ordering_agency(this.createPoAgencySelector.attr("value"));
2920 po.prepayment_required(fields.prepayment_required[0] ? true : false);
2922 // if we're creating assets, delay the asset creation
2923 // until after the PO is created. This will allow us to
2924 // use showAssetCreator() directly.
2926 fieldmapper.standardRequest(
2927 ["open-ils.acq", "open-ils.acq.purchase_order.create"],
2930 openils.User.authtoken,
2931 po, {lineitems : selected}
2933 onresponse : function(r) {
2934 var resp = openils.Util.readResponse(r);
2935 if (resp.complete) {
2936 // self.isPO is needed for showAssetCreator();
2937 self.isPO = resp.purchase_order.id();
2938 var redir = oilsBasePath + "/acq/po/view/" + self.isPO;
2939 if (fields.create_assets[0]) {
2940 self.showAssetCreator(
2941 function() {location.href = redir}
2944 location.href = redir;
2953 this.batchFundWidget = null;
2955 this.applyBatchLiFunds = function() {
2957 var liIds = this.getSelected().map(function(li) { return li.id(); });
2958 if(liIds.length == 0) return; // warn?
2961 batchFundUpdateDialog.show();
2963 if(!this.batchFundWidget) {
2964 this.batchFundWidget = new openils.widget.AutoFieldWidget({
2966 selfReference : true,
2967 labelFormat : fundLabelFormat,
2968 searchFormat : fundSearchFormat,
2969 searchFilter : {"active": "t"},
2970 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
2971 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2972 dijitArgs : { "required": true, "labelType": "html" },
2975 this.batchFundWidget.build();
2978 dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
2979 dojo.connect(batchFundUpdateSubmit, 'onClick',
2982 // TODO: call .dry_run first to test thresholds
2983 fieldmapper.standardRequest(
2984 ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
2987 openils.User.authtoken,
2989 self.batchFundWidget.widget.attr('value')
2991 oncomplete : function(r) {
2992 var resp = openils.Util.readResponse(r);
2994 location.href = location.href;
3003 this._deleteLiList = function(list, idx) {
3004 if(idx == null) idx = 0;
3005 if(idx >= list.length) return;
3010 if (this.isPO && (li.state() == "on-order" || li.state() == "received")) {
3011 /* It makes little sense to delete a lineitem from a PO that has
3012 * already been marked 'on-order'. Especially if EDI is in use,
3013 * such a purchase order will probably have already been shipped
3014 * off to a vendor, and mucking with it at this point could leave
3015 * your data in a bad state that doesn't jive with reality.
3017 * I could see making this restriction even firmer.
3019 * I could also see adjusting the li state comparisons, extending
3020 * the comparison to the PO's state, and/or providing functions
3021 * that house the logic for comparing states in a single location.
3023 * Yes, this will be really annoying if you have selected a lot
3024 * of lineitems to cancel that have been ordered. You'll get a
3025 * confirm dialog for each one.
3028 if (!confirm(localeStrings.DEL_LI_FROM_PO)) {
3029 self._deleteLiList(list, ++idx); /* move on to next in list */
3034 fieldmapper.standardRequest(
3036 this.isPO ? 'open-ils.acq.purchase_order.lineitem.delete' : 'open-ils.acq.picklist.lineitem.delete'],
3038 params: [openils.User.authtoken, liId],
3039 oncomplete: function(r) {
3040 self.removeLineitem(liId);
3041 self._deleteLiList(list, ++idx);
3047 this.editOrderMarc = function(li) {
3049 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
3050 to true in about:config */
3052 if(openils.XUL.isXUL()) {
3053 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul','','chrome');
3055 win = window.open('/xul/server/cat/marcedit.xul','','chrome');
3059 record : {marc : li.marc(), "rtype": "bre"},
3061 label: 'Save Record', // XXX I18N
3062 func: function(xmlString) {
3064 fieldmapper.standardRequest(
3065 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
3067 params: [openils.User.authtoken, li],
3068 oncomplete: function(r) {
3069 openils.Util.readResponse(r);
3071 self.drawInfo(li.id())
3077 'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
3078 'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
3082 this._savePl = function(values) {
3084 (values.which == 'all'),
3085 function(list) { self._savePlFromLineitems(values, list); }
3089 this._savePlFromLineitems = function(values, selected) {
3090 openils.Util.show("acq-lit-generic-progress");
3092 if(values.new_name) {
3093 openils.acq.Picklist.create(
3094 {name: values.new_name},
3100 oilsBasePath + "/acq/picklist/view/" + id;
3105 } else if(values.existing_pl) {
3106 // update lineitems to use an existing picklist
3108 values.existing_pl, selected, 0,
3111 oilsBasePath + "/acq/picklist/view/" +
3118 this._updateLiState = function(values, state) {
3119 progressDialog.show(true);
3121 (values.which == 'all'),
3123 self._updateLiStateFromLineitems(values, state, list);
3128 this._updateLiStateFromLineitems = function(values, state, selected) {
3129 if(!selected.length) return;
3130 dojo.forEach(selected, function(li) {li.state(state);});
3131 self._updateLiList(null, selected, 0,
3132 // TODO consider inline updates for efficiency
3133 function() { location.href = location.href }
3137 this._updateLiList = function(pl, list, idx, oncomplete) {
3138 if(idx >= list.length) return oncomplete();
3140 if(pl != null) li.picklist(pl);
3141 litGenericProgress.update({maximum: list.length, progress: idx});
3142 new openils.acq.Lineitem({lineitem:li}).update(
3144 self._updateLiList(pl, list, ++idx, oncomplete);
3149 this._loadPOSelect = function() {
3150 if (!this.createPoProviderSelector) {
3151 var widget = new openils.widget.AutoFieldWidget({
3152 "fmField": "provider",
3154 "searchFilter": {"active": "t"},
3155 "parentNode": dojo.byId("acq-lit-po-provider"),
3157 "onChange": function() {
3159 self._updateCreatePoPrepayCheckbox(
3160 this.item.prepayment_required()
3166 widget.build(function(w) { self.createPoProviderSelector = w; });
3169 if (!this.createPoAgencySelector) {
3170 var widget = new openils.widget.AutoFieldWidget({
3171 "fmField": "ordering_agency",
3173 "parentNode": dojo.byId("acq-lit-po-agency"),
3174 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3176 widget.build(function(w) { self.createPoAgencySelector = w; });
3180 this.showRealCopyEditUI = function(li) {
3185 this._fetchLineitem(li.id(),
3187 li = self.liCache[li.id()] = fullLi;
3191 id : li.lineitem_details().map(
3192 function(item) { return item.eg_copy_id() }
3196 oncomplete : function(r) {
3198 var r_list = openils.Util.readResponse( r );
3199 for (var i = 0; i < r_list.length; i++) {
3200 var copy = r_list[i];
3201 var volId = copy.call_number();
3202 var volume = self.volCache[volId];
3204 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
3206 copy.call_number(volume);
3207 copyList.push(copy);
3210 xulG.volume_item_creator( { 'existing_copies' : copyList } );
3213 alert('error in oncomplete: ' + E);
3222 this.drawBibFinder = function(li) {
3225 var liWrapper = new openils.acq.Lineitem({lineitem:li});
3228 ['isbn', 'upc', 'issn', 'title', 'author'],
3230 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
3232 if(field == 'title' || field == 'author') {
3233 query += field +':' + val + ' ';
3235 query += 'identifier|' + field + ':' + val + ' ';
3242 oilsBasePath + '/acq/lineitem/findbib?query=' + escape(query),
3243 '', 'resizable,scrollbars=1,chrome');
3245 win.window.recordFound = function(bibId) {
3248 var attrs = li.attributes();
3249 li.attributes(null);
3250 li.eg_bib_id(bibId);
3252 fieldmapper.standardRequest(
3253 ["open-ils.acq", "open-ils.acq.lineitem.update"],
3255 "params": [openils.User.authtoken, li],
3257 "oncomplete": function(r) {
3258 if(openils.Util.readResponse(r)) {
3259 location.href = location.href;