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");
18 if (!localeStrings) { /* we can do this because javascript doesn't have block scope */
19 dojo.requireLocalization('openils.acq', 'acq');
20 var localeStrings = dojo.i18n.getLocalization('openils.acq', 'acq');
22 const XUL_OPAC_WRAPPER = 'chrome://open_ils_staff_client/content/cat/opac.xul';
23 var li_exportable_attrs = ["issn", "isbn", "upc"];
25 var fundLabelFormat = [
26 '<span class="fund_${0}">${1} (${2})</span>', 'id', 'code', 'year'
28 var fundSearchFormat = ['${0} (${1})', 'code', 'year'];
30 function nodeByName(name, context) {
31 return dojo.query('[name='+name+']', context)[0];
34 // for caching linked users. e.g. lineitem_detail.receiver
37 var liDetailBatchFields = ['fund', 'owning_lib', 'location', 'collection_code', 'circ_modifier', 'cn_label'];
38 var liDetailFields = liDetailBatchFields.concat(['barcode', 'note']);
40 "stop": "color: #c00; font-weight: bold;",
41 "warning": "color: #c93;"
44 function AcqLiTable() {
51 this.haveFundClass = {}
52 this.fundBalanceState = {};
53 this.realDfaCache = {};
54 this.virtDfaCounts = {};
57 this.claimEligibleLidByLi = {};
58 this.claimEligibleLid = {};
59 this.toggleState = false;
60 this.tbody = dojo.byId('acq-lit-tbody');
63 this.authtoken = openils.User.authtoken;
64 this.pcrud = new openils.PermaCrud();
65 this.rowTemplate = this.tbody.removeChild(dojo.byId('acq-lit-row'));
66 this.copyTbody = dojo.byId('acq-lit-li-details-tbody');
67 this.copyRow = this.copyTbody.removeChild(dojo.byId('acq-lit-li-details-row'));
68 this.copyBatchRow = dojo.byId('acq-lit-li-details-batch-row');
69 this.copyBatchWidgets = {};
70 this.liNotesTbody = dojo.byId('acq-lit-notes-tbody');
71 this.liNotesRow = this.liNotesTbody.removeChild(dojo.byId('acq-lit-notes-row'));
72 this.realCopiesTbody = dojo.byId('acq-lit-real-copies-tbody');
73 this.realCopiesRow = this.realCopiesTbody.removeChild(dojo.byId('acq-lit-real-copies-row'));
74 this._copy_fields_for_acqdf = ['owning_lib', 'location'];
75 this.skipInitialEligibilityCheck = false;
76 this.claimDialog = new ClaimDialogManager(
77 liClaimDialog, finalClaimDialog, this.claimEligibleLidByLi,
78 function(li) { /* callback that fires when claims are made */
79 self.fetchClaimInfo(li.id(), /* force update */ true);
82 this.vlAgent = new VLAgent();
84 dojo.byId("acq-lit-li-actions-selector").onchange = function() {
85 self.applySelectedLiAction(this.options[this.selectedIndex].value);
86 this.selectedIndex = 0;
89 acqLitCreatePoSubmit.onClick = function() {
90 if (!self.createPoProviderSelector.attr("value") ||
91 !self.createPoAgencySelector.attr("value")) {
92 alert(localeStrings.CREATE_PO_INVALID);
94 } else if (self._confirmPoPrepaySituation()) {
95 acqLitPoCreateDialog.hide();
96 self._createPO(acqLitPoCreateDialog.getValues());
102 acqLitSavePlButton.onClick = function() {
103 acqLitSavePlDialog.hide();
104 self._savePl(acqLitSavePlDialog.getValues());
107 acqLitCancelLiStateButton.onClick = function() {
108 acqLitChangeLiStateDialog.hide();
110 acqLitSaveLiStateButton.onClick = function() {
111 acqLitChangeLiStateDialog.hide();
112 self._updateLiState(acqLitChangeLiStateDialog.getValues(), acqLitChangeLiStateDialog.attr('state'));
116 dojo.byId('acq-lit-select-toggle').onclick = function(){self.toggleSelect()};
117 dojo.byId('acq-lit-info-back-button').onclick = function(){self.show('list')};
118 dojo.byId('acq-lit-copies-back-button').onclick = function(){self.show('list')};
119 dojo.byId('acq-lit-notes-back-button').onclick = function(){self.show('list')};
120 dojo.byId('acq-lit-real-copies-back-button').onclick = function(){self.show('list')};
122 this.reset = function(keep_selectors) {
123 while(self.tbody.childNodes[0])
124 self.tbody.removeChild(self.tbody.childNodes[0]);
132 this.setNext = function(handler) {
133 var link = dojo.byId('acq-lit-next');
135 dojo.style(link, 'visibility', 'visible');
136 link.onclick = handler;
138 dojo.style(link, 'visibility', 'hidden');
142 this.setPrev = function(handler) {
143 var link = dojo.byId('acq-lit-prev');
145 dojo.style(link, 'visibility', 'visible');
146 link.onclick = handler;
148 dojo.style(link, 'visibility', 'hidden');
152 this.show = function(div) {
153 openils.Util.hide('acq-lit-table-div');
154 openils.Util.hide('acq-lit-info-div');
155 openils.Util.hide('acq-lit-li-details');
156 openils.Util.hide('acq-lit-notes-div');
157 openils.Util.hide('acq-lit-real-copies-div');
158 openils.Util.hide('acq-lit-asset-creator');
161 openils.Util.show('acq-lit-table-div');
164 openils.Util.show('acq-lit-info-div');
167 openils.Util.show('acq-lit-li-details');
170 openils.Util.show('acq-lit-real-copies-div');
173 openils.Util.show('acq-lit-notes-div');
175 case 'asset-creator':
176 openils.Util.show('acq-lit-asset-creator');
180 openils.Util.show(div);
184 this.hide = function() {
188 this.toggleSelect = function() {
190 dojo.forEach(self.selectors, function(i){i.checked = false});
192 dojo.forEach(self.selectors, function(i){i.checked = true});
193 self.toggleState = !self.toggleState;
197 this.getAll = function(callback, id_only) {
198 /* For some uses of the li table, we may not really know about "all"
199 * the lineitems that the user thinks we know about. If we're a paged
200 * picklist, for example, we only know about the lineitems we've
201 * displayed, but not necessarily all the lineitems on the picklist.
202 * So we reach out to pcrud to inform us.
205 var oncomplete = function(r) {
206 var id_list = openils.Util.readResponse(r);
210 self.fetchLineitemsById(id_list, callback);
215 "jub", {"picklist": this.isPL}, {
216 "id_list": true, /* sic, even if id_only */
218 "oncomplete": oncomplete
222 } else if (this.isPO) {
224 "jub", {"purchase_order": this.isPO}, {
227 "oncomplete": oncomplete
231 } else if (this.isUni && this.pager) {
232 this.pager.getAllLineitemIDs(oncomplete);
236 /* If execution reaches this point, we don't need or can't perform
237 * any special tricks to find out the "real" list of "all" lineitems
238 * in this context, so we fall back to the old method.
240 callback(this.getSelected(true, null, id_only));
243 /** @param all If true, assume all are selected */
244 this.getSelected = function(
246 callback /* If you want a "good" idea of "all" lineitems, you must
247 provide a callback that accepts an array parameter, rather than
248 relying on the return value of this method itself. */,
252 return this.getAll(callback, id_only);
254 var indices = {}; /* use to uniqify. needed in paging situations. */
255 dojo.forEach(this.selectors,
258 indices[i.parentNode.parentNode.getAttribute('li')] = true;
262 var result = openils.Util.objectProperties(indices);
265 result = result.map(function(liId) { return self.liCache[liId]; });
273 this.setRowAttr = function(td, liWrapper, field, type) {
274 var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
275 td.appendChild(document.createTextNode(val));
278 this.setClaimPolicyControl = function(li, row) {
279 if (!self.claimPolicyPicker) {
280 self.claimPolicyPicker = true; /* prevents a race condition */
281 new openils.widget.AutoFieldWidget({
282 "parentNode": "acq-lit-li-claim-policy",
284 "selfReference": true,
285 "dijitArgs": {"required": true}
286 }).build(function(w) { self.claimPolicyPicker = w; });
289 if (!row) row = this._findLiRow(li);
291 var actViewPolicy = nodeByName("action_view_claim_policy", row);
292 if (li.claim_policy())
293 actViewPolicy.innerHTML = localeStrings.CHANGE_CLAIM_POLICY;
295 if (!actViewPolicy.onclick) {
296 actViewPolicy.onclick = function() {
297 if (li.claim_policy())
298 self.claimPolicyPicker.attr("value", li.claim_policy());
299 liClaimPolicyDialog.show();
300 liClaimPolicySave.onClick = function() {
301 self.changeClaimPolicy(
302 [li], self.claimPolicyPicker.attr("value"),
304 self.setClaimPolicyControl(li, row);
305 self.reconsiderClaimControl(li, row);
306 liClaimPolicyDialog.hide();
314 this.fetchClaimInfo = function(liId, force, callback, row) {
316 liId, function(full) {
317 self.liCache[full.id()] = full;
318 self.checkClaimEligibility(full, callback, row);
324 * Inserts a single lineitem into the growing table of lineitems
325 * @param {Object} li The lineitem object to insert
327 this.addLineitem = function(li, skip_final_placement) {
328 this.liCache[li.id()] = li;
330 // insert the row right away so that final order isn't
331 // dependent on how long subsequent async request take
332 // for a given line item
333 var row = self.rowTemplate.cloneNode(true);
334 if (!skip_final_placement) {
335 self.tbody.appendChild(row);
337 self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
339 // sort the lineitem notes on edit_time
340 if(!li.lineitem_notes()) li.lineitem_notes([]);
342 var liWrapper = new openils.acq.Lineitem({lineitem:li});
343 row.setAttribute('li', li.id());
344 var tds = dojo.query('[attr]', row);
345 dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
346 dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
349 liWrapper.findAttr("isbn", "lineitem_marc_attr_definition") ||
350 liWrapper.findAttr("upc", "lineitem_marc_attr_definition");
352 // XXX media prefix for added content
354 nodeByName("jacket", row).setAttribute(
355 "src", "/opac/extras/ac/jacket/small/" + identifier
359 nodeByName("liid", row).innerHTML += li.id();
362 openils.Util.show(nodeByName('catalog', row), 'inline');
363 nodeByName("catalog_link", row).onclick = this.generateMakeRecTab(li.eg_bib_id());
365 openils.Util.show(nodeByName('link_to_catalog', row), 'inline');
366 nodeByName("link_to_catalog_link", row).onclick = function() { self.drawBibFinder(li) };
369 if (li.queued_record()) {
370 this.pcrud.retrieve('vqbr', li.queued_record(),
372 oncomplete : function(r) {
373 var qrec = openils.Util.readResponse(r);
374 openils.Util.show(nodeByName('queue', row), 'inline');
375 var link = nodeByName("queue_link", row);
376 link.onclick = function() {
377 // open a new tab to the vandelay queue for this record
378 openils.XUL.newTabEasy(
379 oilsBasePath + '/vandelay/vandelay?qtype=bib&qid=' + qrec.queue()
387 nodeByName("worksheet_link", row).href =
388 oilsBasePath + "/acq/lineitem/worksheet/" + li.id();
390 nodeByName("show_requests_link", row).href =
391 oilsBasePath + "/acq/picklist/user_request?lineitem=" + li.id();
393 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
394 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
395 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
397 if (!this.skipInitialEligibilityCheck)
401 function(full) { self.setClaimPolicyControl(full, row) },
405 this.updateLiNotesCount(li, row);
407 // show which PO this lineitem is a member of
408 if(li.purchase_order() && !this.isPO) {
410 this.poCache[li.purchase_order()] =
411 this.poCache[li.purchase_order()] ||
412 fieldmapper.standardRequest(
413 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
415 this.authtoken, li.purchase_order(), {
416 "flesh_price_summary": true,
417 "flesh_provider" : true,
418 "flesh_lineitem_count": true
421 if(po && !this.isMeta) {
422 openils.Util.show(nodeByName('po', row), 'inline');
423 var link = nodeByName('po_link', row);
424 link.setAttribute('href', oilsBasePath + '/acq/po/view/' + li.purchase_order());
425 link.innerHTML += po.name();
427 openils.Util.show(nodeByName('pro', row), 'inline');
428 link = nodeByName('pro_link', row);
429 link.setAttribute('href', oilsBasePath + '/conify/global/acq/provider/' + po.provider().id())
430 link.innerHTML += po.provider().code();
434 // show which picklist this lineitem is a member of
435 if(li.picklist() && (this.isPO || this.isMeta || this.isUni)) {
437 this.plCache[li.picklist()] =
438 this.plCache[li.picklist()] ||
439 fieldmapper.standardRequest(
440 ['open-ils.acq', 'open-ils.acq.picklist.retrieve.authoritative'],
441 {params: [this.authtoken, li.picklist()]});
443 if (pl.name() == "") {
444 openils.Util.show(nodeByName("bib_origin", row), "inline");
448 openils.Util.show(nodeByName('pl', row), 'inline');
449 var link = nodeByName('pl_link', row);
450 link.setAttribute('href', oilsBasePath + '/acq/picklist/view/' + li.picklist());
451 link.innerHTML += pl.name();
456 var countNode = nodeByName('count', row);
457 var count = li.item_count() || 0;
458 if (typeof(this._copy_count_cb) == "function") {
459 this._copy_count_cb(li.id(), count);
461 countNode.innerHTML = count;
462 countNode.id = 'acq-lit-copy-count-label-' + li.id();
465 var priceInput = dojo.query('[name=price]', row)[0];
466 priceInput.value = li.estimated_unit_price() || '';
467 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
469 // show either "mark received" or "unreceive" as appropriate
470 this.updateLiState(li, row);
472 if (skip_final_placement) {
477 this._liCountClaims = function(li) {
479 for (var i = 0; i < li.lineitem_details().length; i++)
480 total += li.lineitem_details()[i].claims().length;
484 this._findLiRow = function(li) {
485 return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
488 this.reconsiderClaimControl = function(li, row) {
489 if (!row) row = this._findLiRow(li);
490 var option = nodeByName("action_manage_claims", row);
491 var eligible = this.claimEligibleLidByLi[li.id()].length;
492 var count = this._liCountClaims(li);
494 option.disabled = !(count || eligible);
496 dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
497 option.onclick = function() { self.claimDialog.show(li); };
500 this.clearEligibility = function(li) {
501 this.claimEligibleLidByLi[li.id()] = [];
503 if (li.lineitem_details()) {
504 li.lineitem_details().forEach(
505 function(lid) { delete self.claimEligibleLid[lid.id()]; }
509 if (this.copyCache) {
511 for (var k in this.copyCache) {
512 if (this.copyCache[k].lineitem() == li.id())
516 function(k) { delete self.claimEligibleLid[k]; }
521 this.checkClaimEligibility = function(li, callback, row) {
522 /* Assume always eligible, i.e. from this interface we don't care about
523 * claim eligibility any more. this is where the user would force a
525 this.clearEligibility(li);
526 this.claimEligibleLidByLi[li.id()] = li.lineitem_details().map(
527 function(lid) { return lid.id(); }
529 li.lineitem_details().forEach(
530 function(lid) { self.claimEligibleLid[lid.id()] = true; }
532 this.reconsiderClaimControl(li, row);
533 if (callback) callback(li);
535 this.clearEligibility(li);
536 fieldmapper.standardRequest(
537 ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
538 "params": [openils.User.authtoken, {"lineitem": li.id()}],
540 "onresponse": function(r) {
541 if (r = openils.Util.readResponse(r)) {
542 self.claimEligibleLidByLi[li.id()].push(
545 self.claimEligibleLid[r.lineitem_detail()] = true;
548 "oncomplete": function() {
549 self.reconsiderClaimControl(li, row);
550 if (typeof(callback) == "function")
558 this.updateLiNotesCount = function(li, row) {
559 if (!row) row = this._findLiRow(li);
561 var has_notes = (li.lineitem_notes().filter(
562 function(o) { return Boolean (o.alert_text()); }
565 /* U+2691 is the code point for a filled-in flag character */
566 nodeByName("notes_alert_flag", row).innerHTML =
567 has_notes ? "⚑" : "";
568 nodeByName("noteslink", row).style.fontStyle =
569 has_notes ? "italic" : "normal";
570 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
573 /* XXX NOT related to _updateLiState(). rethink */
574 this.updateLiState = function(li, row) {
575 if (!row) row = this._findLiRow(li);
577 var actReceive = nodeByName("action_mark_recv", row);
578 var actUnRecv = nodeByName("action_mark_unrecv", row);
579 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
580 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
582 var actNewInvoice = nodeByName('action_new_invoice', row);
583 var actLinkInvoice = nodeByName('action_link_invoice', row);
584 var actViewInvoice = nodeByName('action_view_invoice', row);
586 nodeByName('action_view_history', row).onclick =
587 function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
589 var state_cell = nodeByName("li_state", row);
591 if (li.state() == "cancelled") {
592 if (typeof li.cancel_reason() == "object") {
593 var holds_state = dojo.create(
595 "style": "border-bottom: 1px dashed #000;",
596 "innerHTML": li.state()
597 }, state_cell, "only"
601 "label": "<em>" + li.cancel_reason().label() +
602 "</em><br />" + li.cancel_reason().description(),
603 "connectId": [holds_state]
604 }, dojo.create("span", null, state_cell, "last")
607 state_cell.innerHTML = li.state(); // TODO i18n state labels
610 state_cell.innerHTML = li.state(); // TODO i18n state labels
614 /* handle row coloring for based on LI state */
615 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
616 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
618 /* handle links that appear/disappear based on whether LI is received */
622 actNewInvoice.onclick = function() {
623 location.href = oilsBasePath + '/acq/invoice/view?create=1&attach_li=' + li.id();
624 nodeByName("action_none", row).selected = true;
626 actLinkInvoice.onclick = function() {
627 if (!self.invoiceLinkDialogManager) {
628 self.invoiceLinkDialogManager =
629 new InvoiceLinkDialogManager("li");
631 self.invoiceLinkDialogManager.target = li;
632 acqLitLinkInvoiceDialog.show();
633 nodeByName("action_none", row).selected = true;
635 actViewInvoice.onclick = function() {
636 location.href = oilsBasePath +
637 "/acq/search/unified?so=" +
638 base64Encode({"jub":[{"id": li.id()}]}) +
640 nodeByName("action_none", row).selected = true;
643 actNewInvoice.disabled = false;
644 actLinkInvoice.disabled = false;
645 actViewInvoice.disabled = false;
649 actReceive.disabled = false;
650 actReceive.onclick = function() {
651 if (self.checkLiAlerts(li.id()))
652 self.issueReceive(li);
653 nodeByName("action_none", row).selected = true;
658 actUnRecv.disabled = false;
659 actUnRecv.onclick = function() {
660 if (confirm(localeStrings.UNRECEIVE_LI))
661 self.issueReceive(li, /* rollback */ true);
662 nodeByName("action_none", row).selected = true;
664 // TODO we should allow editing before receipt, in which case the
665 // test should be "if 1 or more real (acp) copies exist
666 actUpdateBarcodes.disabled = false;
667 actUpdateBarcodes.onclick = function() {
668 self.showRealCopyEditUI(li);
669 nodeByName("action_none", row).selected = true;
671 actHoldingsMaint.disabled = false;
672 actHoldingsMaint.onclick = self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
680 this._setAlertStore = function() {
681 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
683 "data": acqliat.toStoreData(
685 "acqliat", {"id": {"!=": null}}
690 acqLitAlertAlertText.setValue(); /* make the store "live" */
691 acqLitAlertAlertText._store_ready = true;
695 * Draws and shows the lineitem notes pane
697 this.drawLiNotes = function(li) {
700 if (!acqLitAlertAlertText._store_ready)
701 this._setAlertStore();
704 li.lineitem_notes().sort(
706 if(a.edit_time() < b.edit_time()) return 1;
712 while(this.liNotesTbody.childNodes[0])
713 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
716 acqLitCreateNoteSubmit.onClick = function() {
717 var value = acqLitCreateNoteText.attr('value');
719 var note = new fieldmapper.acqlin();
722 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
725 note.lineitem(li.id());
727 self.updateLiNotes(li, note);
728 acqLitCreateNoteVendorPublic.attr("checked", false);
729 acqLitCreateNoteText.attr("value", "");
732 acqLitCreateAlertSubmit.onClick = function() {
733 if (!acqLitAlertAlertText.item) {
734 alert(localeStrings.ALERT_UNSELECTED);
738 var alert_text = new fieldmapper.acqliat().fromStoreItem(
739 acqLitAlertAlertText.item
741 var value = acqLitAlertNoteValue.attr("value") || "";
743 var note = new fieldmapper.acqlin();
745 note.lineitem(li.id());
747 note.alert_text(alert_text);
749 self.updateLiNotes(li, note);
752 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
756 * Draws a single lineitem note in the notes pane
758 this.addLiNote = function(li, note) {
759 if(note.isdeleted()) return;
761 var row = self.liNotesRow.cloneNode(true);
762 nodeByName("value", row).innerHTML = note.value();
763 var alert_node = nodeByName("alert_code", row);
764 if (note.alert_text()) {
765 alert_node.innerHTML = note.alert_text().code();
766 if (note.alert_text().description()) {
769 "connectId": [alert_node],
770 "label": note.alert_text().description()
771 }, dojo.create("span", null, alert_node, "after")
776 if (openils.Util.isTrue(note.vendor_public()))
777 nodeByName("vendor_public", row).innerHTML =
778 localeStrings.VENDOR_PUBLIC;
780 nodeByName("delete", row).onclick = function() {
781 note.isdeleted(true);
782 self.liNotesTbody.removeChild(row);
783 self.updateLiNotes(li);
786 if(note.edit_time()) {
787 nodeByName("edit_time", row).innerHTML =
788 dojo.date.locale.format(
789 dojo.date.stamp.fromISOString(note.edit_time()),
790 {formatLength:'short'});
793 self.liNotesTbody.appendChild(row);
797 * Updates any new/changed/deleted notes on the server
799 this.updateLiNotes = function(li, newNote) {
805 notes = li.lineitem_notes().filter(
807 if(note.ischanged() || note.isnew() || note.isdeleted())
813 if(notes.length == 0) return;
814 progressDialog.show();
816 fieldmapper.standardRequest(
817 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
819 params : [this.authtoken, notes],
820 onresponse : function(r) {
821 var resp = openils.Util.readResponse(r);
826 // remove the old changed notes
828 dojo.forEach(li.lineitem_notes(),
830 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
834 li.lineitem_notes(list);
837 progressDialog.hide();
838 self.updateLiNotesCount(li);
839 self.drawLiNotes(li);
843 progressDialog.update(resp);
844 var newnote = resp.note;
846 if(!newnote.isdeleted()) {
847 newnote.isnew(false);
848 newnote.ischanged(false);
849 li.lineitem_notes().push(newnote);
856 this.updateLiPrice = function(input, li) {
858 var price = input.value;
859 if(Number(price) == Number(li.estimated_unit_price())) return;
861 fieldmapper.standardRequest(
862 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
863 { async : false, // redundant w/ timeout
865 params : [this.authtoken, li.id(), price],
866 oncomplete : function(r) {
867 openils.Util.readResponse(r);
868 li.estimated_unit_price(price); // update local copy
871 * If this is a PO and every visible lineitem has a price,
872 * check again to see if this PO can be activated. Note that
873 * every visible lineitem having a price does not guarantee it can
874 * be activated, which is why we still make the call. Having a price
875 * set for every visiable lineitem is just the lowest barrier to entry.
878 var priceNodes = dojo.query('[name=price]', dojo.byId('acq-lit-tbody'));
880 dojo.forEach(priceNodes, function(node) { if (node.value == '') allSet = false});
881 if (allSet) checkCouldActivatePo();
888 this.removeLineitem = function(liId) {
889 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
890 delete this.liCache[liId];
891 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
894 this.drawInfo = function(liId) {
895 if (!this._isRelatedViewer) {
896 var d = dojo.byId("acq-lit-info-related");
897 if (!this.relCache[liId]) {
898 fieldmapper.standardRequest(
901 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
904 "params": [openils.User.authtoken, liId],
905 "onresponse": function(r) {
906 self.relCache[liId] = openils.Util.readResponse(r);
907 nodeByName("related_number", d).innerHTML =
910 self.relCache[liId] >1 ? "show" : "hide"
916 nodeByName("related_number", d).innerHTML = this.relCache[liId];
917 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
922 openils.acq.Lineitem.fetchAttrDefs(
924 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
929 /* For a given list of lineitem ids, build a list of full lineitems
930 * re-using the fetching logic that is otherwise typical to use in this
933 * If we've already got a lineitem in the cache, just use that.
935 * Once we've built a list of lineitems, call callback(thatlist).
937 this.fetchLineitemsById = function(id_list, callback) {
938 var total = id_list.length;
939 var result_list = [];
941 var inner = function(li) {
944 callback(result_list);
947 id_list.forEach(function(id) { self._fetchLineitem(id, inner); });
950 this._fetchLineitem = function(liId, handler, force) {
952 var li = this.liCache[liId];
953 if(li && li.marc() && li.lineitem_details() && !force)
956 fieldmapper.standardRequest(
957 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
960 params: [self.authtoken, liId, {
962 flesh_cancel_reason: true,
963 flesh_li_details: true,
965 flesh_fund_debit: true }],
967 oncomplete: function(r) {
968 var li = openils.Util.readResponse(r);
969 self.liCache[liId] = li;
976 this._drawInfo = function(li) {
978 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
981 openils.Util.hide('acq-lit-marc-order-record-label');
982 openils.Util.hide(acqLitEditOrderMarc.domNode);
983 openils.Util.show('acq-lit-marc-real-record-label');
985 openils.Util.show('acq-lit-marc-order-record-label');
986 openils.Util.show(acqLitEditOrderMarc.domNode);
987 openils.Util.hide('acq-lit-marc-real-record-label');
990 this.drawMarcHTML(li);
991 this.infoTbody = dojo.byId('acq-lit-info-tbody');
994 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
995 while(this.infoTbody.childNodes[0])
996 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
998 for(var i = 0; i < li.attributes().length; i++) {
999 var attr = li.attributes()[i];
1000 var row = this.infoRow.cloneNode(true);
1002 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
1003 var name = openils.acq.Lineitem.attrDefs[type].filter(
1005 return (a.code() == attr.attr_name());
1007 ).pop().description();
1009 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
1010 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
1011 this.infoTbody.appendChild(row);
1014 if (!this._isRelatedViewer) {
1015 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
1016 oilsBasePath + "/acq/lineitem/related/" + li.id();
1021 this.generateMakeRecTab = function(bib_id,default_view, row) {
1025 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
1028 show_nav_buttons : true,
1029 show_print_button : true,
1030 opac_url : xulG.url_prefix(xulG.urls.opac_rdetail + bib_id),
1031 default_view : default_view
1035 if(row) nodeByName("action_none", row).selected = true;
1039 this.drawMarcHTML = function(li) {
1040 var params = [null, true, li.marc()];
1042 params = [li.eg_bib_id(), true];
1044 fieldmapper.standardRequest(
1045 ['open-ils.search', 'open-ils.search.biblio.record.html'],
1048 oncomplete: function(r) {
1049 dojo.byId('acq-lit-marc-div').innerHTML =
1050 openils.Util.readResponse(r);
1056 this.drawCopies = function(liId, force_fetch) {
1057 if (typeof force_fetch == "undefined")
1058 force_fetch = false;
1060 openils.acq.Lineitem.fetchAndRender(liId, {},
1061 function(li, html) {
1062 dojo.byId('acq-lit-copies-li-summary').innerHTML = html;
1066 this.show('copies');
1068 this.copyCache = {};
1069 this.copyWidgetCache = {};
1070 this.oldCopyWidgetCache = {};
1071 this.virtDfaCounts = {};
1072 this.realDfaCache = {};
1075 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
1076 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
1077 acqLitCopyCountInput.attr('value', '0');
1079 while(this.copyTbody.childNodes[0])
1080 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
1082 this._drawBatchCopyWidgets();
1084 this._drawDistribApplied(liId);
1086 this._fetchDistribFormulas(
1088 openils.acq.Lineitem.fetchAttrDefs(
1090 self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch);
1097 this._saveDistribAppliedTemplates = function() {
1098 if (!this._appliedDistribTemplate) {
1099 this._appliedDistribTemplate =
1100 dojo.byId("acq-lit-distrib-applied-tbody").
1101 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
1102 dojo.attr(this._appliedDistribTemplate, "id");
1106 this._drawDistribApplied = function(liId) {
1107 /* Build this table while hidden to prevent rendering artifacts */
1108 openils.Util.hide("acq-lit-distrib-applied-tbody");
1110 this._saveDistribAppliedTemplates();
1112 /* Remove any rows in the table from previous populations */
1113 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
1114 forEach(dojo.destroy);
1116 /* Unregister all dijits previously created (for some reason this isn't
1117 * covered by the above destroy calls). */
1118 dijit.registry.forEach(
1119 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
1122 /* Populate the table with our liId */
1124 fieldmapper.standardRequest(
1126 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
1129 "params": [self.authtoken, liId],
1130 "onresponse": function(r) {
1131 var dfa = openils.Util.readResponse(r);
1134 self.realDfaCache[dfa.id()] = dfa;
1135 self._drawDistribAppliedUnit(dfa);
1138 "oncomplete": function() {
1139 /* Reveal built table */
1142 "acq-lit-distrib-applied-tbody", "table-row-group"
1150 this._drawDistribAppliedUnit = function(dfa) {
1151 var new_row = false;
1152 var row = dojo.query(
1153 'tr[formula="' + dfa.formula().id() + '"]',
1154 "acq-lit-distrib-applied-tbody"
1159 row = dojo.clone(this._appliedDistribTemplate);
1160 dojo.attr(row, "formula", dfa.formula().id());
1161 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
1164 var td = dojo.query("td", row)[0];
1166 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1167 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1170 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1172 new dijit.form.Button(
1174 "onClick": function() {
1175 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1176 self.deleteDfa(dfa);
1179 /* XXX I /cannot/ make the following work in as a CSS class
1180 * for some reason. So frustrating... */
1181 "style": function(id) {
1183 "font-weight: bold; color: #c00;" :
1185 }(dfa.id()) + "margin: 0 6px;display: inline;"
1186 }, "dfa-button-" + dfa.id()
1190 "connectId": ["dfa-button-" + dfa.id()],
1191 "label": dojo.string.substitute(
1192 localeStrings.DFA_TIP, dfa.id() > 0 ? [
1193 openils.User.formalName(dfa.creator()),
1194 dojo.date.locale.format(
1195 dojo.date.stamp.fromISOString(dfa.create_time()),
1196 {"formatLength":"short"}
1198 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
1200 }, "dfa-tip-" + dfa.id()
1204 this.deleteDfa = function(dfa) {
1205 if (dfa.id() > 0) { /* real */
1206 this.pcrud.eliminate(
1209 "oncomplete": function() {
1210 self._removeDistribApplied(dfa.id());
1211 delete self.realDfaCache[dfa.id()];
1215 } else { /* virtual */
1216 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
1217 this.virtDfaCounts[dfa.formula().id()] = 0;
1218 /* hasn't been saved yet, so no need to do anything server side */
1219 this._removeDistribApplied(dfa.id());
1224 this._removeDistribApplied = function(dfaId) {
1225 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
1226 dijit.registry.forEach(
1227 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
1229 this._removeDistribAppliedEmptyRows();
1232 this._removeAllDistribAppliedVirtual = function() {
1233 /* Unregister dijits */
1234 dijit.registry.forEach(
1235 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
1237 this._removeDistribAppliedEmptyRows();
1240 this._removeDistribAppliedEmptyRows = function() {
1241 /* Remove any rows with no DFA at all */
1242 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
1244 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
1250 * Insert a new row into the distribution formula selection form
1252 this._addDistribFormulaRow = function() {
1255 if (!self.distribForms) {
1256 // no formulas, hide the form
1257 openils.Util.hide('acq-lit-distrib-formula-table');
1261 if(!this.distribFormulaTemplate)
1262 this.distribFormulaTemplate =
1263 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
1265 var row = this.distribFormulaTemplate.cloneNode(true);
1266 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
1268 this.dfSelector = new dijit.form.FilteringSelect(
1269 {"labelAttr": "dynLabel", "labelType": "html"},
1270 nodeByName("selector", row)
1272 this._updateFormulaStore();
1273 this.dfSelector.fetchProperties =
1274 {"sort": [{"attribute": "use_count", "descending": true}]};
1276 var apply = new dijit.form.Button(
1277 {"label": localeStrings.APPLY},
1278 nodeByName('set_button', row)
1281 var reset = new dijit.form.Button(
1282 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
1283 nodeByName("reset_button", row)
1286 dojo.connect(apply, 'onClick',
1288 var form_id = self.dfSelector.attr("value");
1289 if(!form_id) return;
1290 self._applyDistribFormula(form_id);
1291 reset.attr("disabled", false);
1295 dojo.connect(reset, 'onClick',
1297 self.restoreCopyFieldsBeforeDF();
1298 self.virtDfaCounts = {};
1299 self.virtDfaId = -1;
1301 self._updateFormulaStore();
1302 self._removeAllDistribAppliedVirtual();
1303 reset.attr("disabled", "true");
1310 * Applies a distrib formula to the current set of copies
1312 this._applyDistribFormula = function(formula) {
1313 if(!formula) return;
1315 formula = this.distribForms.filter(
1316 function(form) { return form.id() == formula; }
1319 var copyRows = dojo.query('tr', self.copyTbody);
1321 if (this.dfeOffset >= copyRows.length) {
1322 alert(localeStrings.OUT_OF_COPIES);
1326 var entries_applied = 0;
1328 var rowIndex = this.dfeOffset;
1329 rowIndex < copyRows.length;
1333 var row = copyRows[rowIndex];
1334 var copy_id = row.getAttribute('copy_id');
1335 var copyWidgets = this.copyWidgetCache[copy_id];
1336 var entryIndex = this.dfeOffset;
1339 // find the correct entry for the current row
1340 dojo.forEach(formula.entries(),
1343 entryIndex += e.item_count();
1344 if(entryIndex > rowIndex)
1352 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
1353 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
1356 this.saveCopyFieldsBeforeDF(copy_id);
1357 this._copy_fields_for_acqdf.forEach(
1359 if(entry[field]()) {
1360 copyWidgets[field].attr('value', (entry[field]()));
1367 if (entries_applied) {
1368 this.virtDfaCounts[formula.id()] =
1369 ++(this.virtDfaCounts[formula.id()]) || 1;
1370 this._updateFormulaStore();
1371 this._drawDistribAppliedUnit(
1373 var dfa = new acqdfa();
1374 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
1377 this.dfeOffset += entries_applied;
1382 * This function updates the DF store for the dropdown so that use_counts
1383 * can reflect DF applications from this session before they're saved
1386 this._updateFormulaStore = function() {
1387 this.dfSelector.store = new dojo.data.ItemFileReadStore(
1389 "data": self._labelFormulasWithCounts(
1390 acqdf.toStoreData(self.distribForms)
1396 this.saveCopyFieldsBeforeDF = function(copy_id) {
1398 if (!this.oldCopyWidgetCache[copy_id]) {
1399 var copyWidgets = this.copyWidgetCache[copy_id];
1401 this.oldCopyWidgetCache[copy_id] = {};
1402 this._copy_fields_for_acqdf.forEach(
1404 self.oldCopyWidgetCache[copy_id][f] =
1405 copyWidgets[f].attr("value");
1411 this.restoreCopyFieldsBeforeDF = function() {
1413 for (var copy_id in this.oldCopyWidgetCache) {
1414 this._copy_fields_for_acqdf.forEach(
1416 self.copyWidgetCache[copy_id][f].attr(
1417 "value", self.oldCopyWidgetCache[copy_id][f]
1424 this._labelFormulasWithCounts = function(store_data) {
1425 for (var key in store_data.items) {
1426 var obj = store_data.items[key];
1427 obj.use_count = Number(obj.use_count); /* needed for sorting */
1429 if (this.virtDfaCounts[obj.id])
1430 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
1432 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
1433 obj.use_count + "]</span> " + obj.name;
1439 * This method formerly would not refetch the DF formulas if they'd been
1440 * loaded already, but now it always re-fetches, since use_count changes.
1442 /** TODO: port distrib-formula selector to autofieldwidget+pcrud/dojo store */
1443 this._fetchDistribFormulas = function(onload) {
1444 fieldmapper.standardRequest(
1446 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
1449 "params": [openils.User.authtoken, 0, 500],
1450 "oncomplete": function(r) {
1451 self.distribForms = openils.Util.readResponse(r);
1452 if(!self.distribForms || self.distribForms.length == 0) {
1453 self.distribForms = [];
1455 self._addDistribFormulaRow();
1462 this._drawBatchCopyWidgets = function() {
1463 var row = this.copyBatchRow;
1464 dojo.forEach(liDetailBatchFields,
1466 if(self.copyBatchRowDrawn) {
1467 self.copyBatchWidgets[field].attr('value', null);
1469 var widget = new openils.widget.AutoFieldWidget({
1472 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1473 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1474 searchFilter : (field == 'fund') ? {"active": "t"} : null,
1475 parentNode : dojo.query('[name='+field+']', row)[0],
1476 orgLimitPerms : ['CREATE_PICKLIST'],
1479 "labelType": (field == "fund") ? "html" : null
1481 noCache: (field == "fund"),
1486 if (field == "fund" && w.store)
1487 self._ensureCSSFundClasses(w.store);
1488 self.copyBatchWidgets[field] = w;
1491 if (field == "fund") {
1493 widget.widget, "onChange", function(val) {
1494 self._updateFundSelectorStyle(widget, val);
1501 this.copyBatchRowDrawn = true;
1504 this.batchCopyUpdate = function() {
1506 for(var k in this.copyWidgetCache) {
1507 var cache = this.copyWidgetCache[k];
1508 dojo.forEach(liDetailBatchFields, function(f) {
1509 var newval = self.copyBatchWidgets[f].attr('value');
1510 if(newval) cache[f].attr('value', newval);
1515 this._drawCopies = function(li) {
1518 // this button sets the total number of copies for a given lineitem
1519 acqLitAddCopyCount.onClick = function() {
1520 var count = acqLitCopyCountInput.attr('value');
1523 while(self.copyCount() < count)
1526 // delete rows if necessary
1527 var diff = self.copyCount() - count;
1529 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
1530 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
1531 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
1533 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1539 if(li.lineitem_details().length > 0) {
1540 dojo.forEach(li.lineitem_details(),
1542 self.addCopy(li, copy);
1550 this.copyCount = function() {
1552 for(var id in this.copyCache) {
1553 if(!this.copyCache[id].isdeleted())
1559 this.virtCopyId = -1;
1560 this.addCopy = function(li, copy) {
1561 var row = this.copyRow.cloneNode(true);
1562 this.copyTbody.appendChild(row);
1566 copy = new fieldmapper.acqlid();
1568 copy.id(this.virtCopyId--);
1569 copy.lineitem(li.id());
1572 this.copyCache[copy.id()] = copy;
1573 row.setAttribute('copy_id', copy.id());
1574 self.copyWidgetCache[copy.id()] = {};
1576 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1578 var rcvr = copy.receiver();
1580 if (!userCache[rcvr]) {
1581 if(rcvr == openils.User.user.id()) {
1582 userCache[rcvr] = openils.User.user;
1584 userCache[rcvr] = fieldmapper.standardRequest(
1585 ['open-ils.actor', 'open-ils.actor.user.retrieve'],
1586 {params: [openils.User.authtoken, rcvr]}
1590 dojo.query('[name=receiver]', row)[0].innerHTML = userCache[rcvr].usrname();
1593 dojo.forEach(liDetailFields,
1596 if (field == "fund") {
1597 searchFilter = (copy.fund() ?
1598 {"-or": {"active": "t", "id": copy.fund()}} :
1601 searchFilter = null;
1604 var readOnly = false;
1606 // TODO: Add support for changing the owning_lib after real copies have been made.
1607 // owning_lib is order data as much as its item data
1608 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
1612 // TODO: add support for changing the fund after debits have been created
1613 // Note: invoicing allows the change
1614 if(copy.fund_debit() && field == 'fund') {
1619 var widget = new openils.widget.AutoFieldWidget({
1622 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1623 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1624 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1625 searchFilter : searchFilter,
1626 noCache: (field == "fund"),
1628 parentNode : dojo.query('[name='+field+']', row)[0],
1629 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
1630 readOnly : readOnly,
1631 orgDefaultsToWs : true
1635 // make sure we capture the value from any async widgets
1638 if (field == "fund" && w.store)
1639 self._ensureCSSFundClasses(w.store);
1642 copy[field](ww.getFormattedValue())
1644 self.copyWidgetCache[copy.id()][field] = w;
1646 dojo.connect(w, 'onChange',
1648 if (field == "fund")
1649 self._updateFundSelectorStyle(widget, val);
1651 if (!readOnly && (copy.isnew() || val != copy[field]())) {
1652 // prevent setting ischanged() automatically on widget load for existing copies
1653 copy[field](widget.getFormattedValue())
1654 copy.ischanged(true);
1663 this.updateLidState(copy, row);
1666 this._ensureCSSFundClass = function(id) {
1667 if (!this.fundStyleSheet) {
1669 "style", {"type": "text/css"},
1670 document.getElementsByTagName("head")[0], "last"
1672 this.fundStyleSheet = document.styleSheets[
1673 document.styleSheets.length - 1
1677 var cn = "fund_" + id;
1678 if (!this.haveFundClass[cn]) {
1679 fieldmapper.standardRequest(
1680 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
1682 "params": [openils.User.authtoken, id],
1684 "oncomplete": function(r) {
1685 r = openils.Util.readResponse(r);
1686 self.fundBalanceState[id] = r;
1688 if (r[0] /* stop */)
1689 style = fundStyles.stop;
1690 else if (r[1] /* warning */)
1691 style = fundStyles.warning;
1692 self.fundStyleSheet.insertRule(
1693 "." + cn + " { " + style + " }",
1694 self.fundStyleSheet.cssRules.length
1696 self.haveFundClass[cn] = true;
1703 this._ensureCSSFundClasses = function(store) {
1705 "query": {"id": "*"},
1706 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
1710 this._updateFundSelectorStyle = function(widget, fund_id) {
1711 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
1712 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
1715 this.updateLidState = function(copy, row) {
1716 if (typeof(row) == "undefined") {
1718 'tr[copy_id="' + copy.id() + '"]', this.copyTbody
1723 var recv_link = nodeByName("receive", row);
1724 var unrecv_link = nodeByName("unreceive", row);
1725 var del_link = nodeByName("delete", row);
1726 var cxl_link = nodeByName("cancel", row);
1727 var claim_link = nodeByName("claim", row);
1728 var cxl_reason_link = nodeByName("cancel_reason", row);
1730 if (copy.cancel_reason()) {
1731 openils.Util.hide(del_link.parentNode);
1732 openils.Util.hide(recv_link);
1733 openils.Util.hide(unrecv_link);
1734 openils.Util.hide(cxl_link);
1735 openils.Util.hide(claim_link);
1737 /* XXX the following may leak memory in a long lived table: dijits may not get destroyed... not positive. revisit. */
1738 var holds_reason = dojo.create(
1740 "style": "border-bottom: 1px dashed #000;",
1741 "innerHTML": "Cancelled" /* XXX [sic] and i18n */
1742 }, cxl_reason_link, "only"
1746 "label": "<em>" + copy.cancel_reason().label() +
1747 "</em><br />" + copy.cancel_reason().description(),
1748 "connectId": [holds_reason]
1749 }, dojo.create("span", null, cxl_reason_link, "last")
1751 openils.Util.show(cxl_reason_link, "inline");
1752 } else if (this.isPO) {
1753 /* Only using this in one place so far, but may want it for better
1754 * decisions on when to display certain controls. */
1755 var li_state = this.liCache[copy.lineitem()].state();
1757 openils.Util.hide(del_link.parentNode);
1758 openils.Util.hide(cxl_reason_link);
1760 /* Avoid showing (un)receive links, cancel links, for virt copies */
1761 if (copy.id() > 0) {
1762 if (copy.recv_time()) {
1763 openils.Util.hide(cxl_link);
1764 openils.Util.hide(recv_link);
1765 openils.Util.hide(claim_link);
1767 openils.Util.show(unrecv_link, "inline");
1768 unrecv_link.onclick = function() {
1769 if (confirm(localeStrings.UNRECEIVE_LID))
1770 self.issueReceive(copy, /* rollback */ true);
1773 openils.Util.hide(unrecv_link);
1775 if (this.claimEligibleLid[copy.id()]) {
1776 openils.Util.show(claim_link, "inline");
1777 claim_link.onclick = function() {
1778 self.claimDialog.show(
1779 self.liCache[copy.lineitem()], copy.id()
1783 openils.Util.hide(claim_link);
1786 openils.Util[li_state == "on-order" ? "show" : "hide"](
1789 openils.Util.show(cxl_link, "inline");
1790 recv_link.onclick = function() {
1791 if (self.checkLiAlerts(copy.lineitem()))
1792 self.issueReceive(copy);
1794 cxl_link.onclick = function() {
1795 self.cancelLid(copy.id());
1799 openils.Util.hide(cxl_link);
1800 openils.Util.hide(unrecv_link);
1801 openils.Util.hide(recv_link);
1802 openils.Util.hide(claim_link);
1805 openils.Util.hide(unrecv_link);
1806 openils.Util.hide(recv_link);
1807 openils.Util.hide(cxl_reason_link);
1808 openils.Util.hide(claim_link);
1810 del_link.onclick = function() { self.deleteCopy(row) };
1811 openils.Util.show(del_link.parentNode);
1815 this.cancelLid = function(lid_id) {
1816 lidCancelDialog._lid_id = lid_id;
1817 openils.Util.show(lidCancelDialog.domNode.parentNode);
1818 lidCancelDialog.show();
1819 if (!lidCancelDialog._prepared) {
1820 var widget = new openils.widget.AutoFieldWidget({
1821 "fmField": "cancel_reason",
1822 "fmClass": "acqlid",
1823 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
1824 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1829 acqLidCancelButton.onClick = function() {
1830 if (w.attr("value")) {
1831 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
1833 lidCancelDialog._lid_id,
1837 lidCancelDialog.hide();
1840 lidCancelDialog._prepared = true;
1846 this._cancelLid = function(lid_id, reason) {
1847 fieldmapper.standardRequest(
1848 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
1849 "params": [openils.User.authtoken, lid_id, reason],
1851 "onresponse": function(r) {
1852 if (r = openils.Util.readResponse(r)) {
1854 for (var id in r.lid) {
1855 /* actually this should only iterate once */
1856 self.copyCache[id].cancel_reason(
1857 r.lid[id].cancel_reason
1859 self.updateLidState(self.copyCache[id]);
1868 this._confirmAlert = function(li, lin) {
1870 dojo.string.substitute(
1871 localeStrings.CONFIRM_LI_ALERT, [
1872 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1873 "title", "lineitem_marc_attr_definition"
1875 lin.alert_text().code(),
1876 lin.alert_text().description() || "",
1883 this.checkLiAlerts = function(li_id) {
1884 var li = this.liCache[li_id];
1886 var alert_notes = li.lineitem_notes().filter(
1887 function(o) { return Boolean(o.alert_text()); }
1890 /* this is _intentionally_ not done in a call to forEach() ... */
1891 for (var i = 0; i < alert_notes.length; i++) {
1892 if (this.noteAcks[alert_notes[i].id()])
1894 else if (!this._confirmAlert(li, alert_notes[i]))
1897 this.noteAcks[alert_notes[i].id()] = true;
1903 this.deleteCopy = function(row) {
1904 var copy = this.copyCache[row.getAttribute('copy_id')];
1905 copy.isdeleted(true);
1907 delete this.copyCache[copy.id()];
1908 this.copyTbody.removeChild(row);
1911 this._virtDfaCountsAsList = function() {
1913 for (var key in this.virtDfaCounts) {
1914 for (var i = 0; i < this.virtDfaCounts[key]; i++)
1920 this.confirmBreachedCopyFunds = function(copies) {
1921 var stop = 0, warning = 0;
1925 var state = self.fundBalanceState[o.fund()];
1926 if (state[0] /* stop */)
1928 else if (state[1] /* warning */)
1935 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
1936 } else if (warning) {
1937 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
1942 this.saveCopyChanges = function(liId) {
1948 for(var id in this.copyCache) {
1949 var c = this.copyCache[id];
1950 if(!c.isdeleted()) total++;
1951 if(c.isnew() || c.ischanged() || c.isdeleted()) {
1952 if(c.id() < 0) c.id(null);
1958 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
1961 if (copies.length > 0) {
1962 if (!this.confirmBreachedCopyFunds(copies))
1965 if (typeof(this._copy_count_cb) == "function")
1966 this._copy_count_cb(liId, total);
1968 openils.Util.show("acq-lit-update-copies-progress");
1969 fieldmapper.standardRequest(
1970 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1972 params: [openils.User.authtoken, copies],
1973 onresponse: function(r) {
1974 var res = openils.Util.readResponse(r);
1975 litUpdateCopiesProgress.update(res);
1977 oncomplete: function() {
1978 self.drawCopies(liId, true /* force_fetch */);
1979 openils.Util.hide("acq-lit-update-copies-progress");
1985 var dfa_list = this._virtDfaCountsAsList();
1986 if (dfa_list.length > 0) {
1987 fieldmapper.standardRequest(
1989 "open-ils.acq.distribution_formula.record_application"],
1992 "params": [openils.User.authtoken, dfa_list, liId],
1993 "onresponse": function(r) {
1994 var res = openils.Util.readResponse(r);
1995 if (res && res.length < dfa_list.length)
1996 alert(localeStrings.DFA_NOT_ALL);
2000 this.virtDfaCounts = {};
2004 this._updateCreatePoPrepayCheckbox = function(prepay) {
2005 var prepay = openils.Util.isTrue(prepay);
2006 this._prepayRequiredByVendor = prepay;
2007 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
2010 this._confirmPoPrepaySituation = function() {
2011 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
2012 if (want_prepay != this._prepayRequiredByVendor) {
2015 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
2016 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
2023 this.applySelectedLiAction = function(action) {
2027 case 'delete_selected':
2028 this._deleteLiList(self.getSelected());
2031 case 'create_order':
2032 this._loadPOSelect();
2033 acqLitPoCreateDialog.show();
2036 case 'save_picklist':
2037 acqLitSavePlDialog.show();
2040 case 'selector_ready':
2042 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
2043 acqLitChangeLiStateDialog.show();
2051 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
2058 case 'rollback_receive_po':
2059 this.rollbackPoReceive();
2062 case 'create_assets':
2063 this.showAssetCreator();
2066 case 'export_attr_list':
2067 this.chooseExportAttr();
2070 case 'batch_apply_funds':
2071 this.applyBatchLiFunds();
2074 case 'add_brief_record':
2076 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
2078 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
2082 case "cancel_lineitems":
2083 this.maybeCancelLineitems();
2086 case "change_claim_policy":
2087 var li_list = this.getSelected();
2088 this.claimPolicyPicker.attr("value", null);
2089 liClaimPolicyDialog.show();
2090 liClaimPolicySave.onClick = function() {
2091 self.changeClaimPolicy(
2093 self.claimPolicyPicker.attr("value"),
2097 self.setClaimPolicyControl(li);
2098 self.reconsiderClaimControl(li);
2101 liClaimPolicyDialog.hide();
2109 this.changeClaimPolicy = function(li_list, value, callback) {
2111 function(li) { li.claim_policy(value); }
2113 fieldmapper.standardRequest(
2114 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
2115 "params": [openils.User.authtoken, li_list],
2117 "oncomplete": function(r) {
2118 r = openils.Util.readResponse(r);
2119 if (callback) callback(r);
2125 this.showAssetCreator = function(onAssetsCreated) {
2126 this.show('asset-creator');
2127 if(!this.vlAgent.loaded)
2128 this.vlAgent.init();
2130 dojo.connect(assetCreatorButton, 'onClick',
2131 function() { self.createAssets(onAssetsCreated) });
2134 this.createAssets = function(onAssetsCreated) {
2135 if(!this.isPO) return;
2136 this.show('acq-lit-progress-numbers');
2138 fieldmapper.standardRequest(
2139 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
2141 params: [this.authtoken, this.isPO, {vandelay : this.vlAgent.values()}],
2142 onresponse: function(r) {
2143 var resp = openils.Util.readResponse(r);
2144 self._updateProgressNumbers(resp, !Boolean(onAssetsCreated), onAssetsCreated);
2150 this.maybeCancelLineitems = function() {
2151 openils.Util.show("acq-lit-cancel-reason", "inline");
2152 if (!acqLitCancelLineitemsButton._prepared) {
2153 var widget = new openils.widget.AutoFieldWidget({
2154 "fmField": "cancel_reason",
2156 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
2157 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2162 acqLitCancelLineitemsButton.onClick = function() {
2163 if (w.attr("value")) {
2164 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
2165 self._cancelLineitems(w.attr("value"));
2167 openils.Util.hide("acq-lit-cancel-reason");
2170 acqLitCancelLineitemsButton._prepared = true;
2176 this._cancelLineitems = function(reason) {
2177 var id_list = this.getSelected().map(function(o) { return o.id(); });
2178 fieldmapper.standardRequest(
2179 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
2180 "params": [openils.User.authtoken, id_list, reason],
2182 "onresponse": function(r) {
2183 if (r = openils.Util.readResponse(r)) {
2185 for (var id in r.li) {
2186 self.liCache[id].state(r.li[id].state);
2187 self.liCache[id].cancel_reason(
2188 r.li[id].cancel_reason
2190 self.updateLiState(self.liCache[id]);
2193 if (r.lid && self.copyCache) {
2194 for (var id in r.lid) {
2195 if (self.copyCache[id]) {
2196 self.copyCache[id].cancel_reason(
2197 r.lid[id].cancel_reason
2199 self.updateLidState(self.copyCache[id]);
2209 this.chooseExportAttr = function() {
2210 if (!acqLitExportAttrSelector._li_setup) {
2212 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
2214 "data": acqlimad.toStoreData(
2216 "acqlimad", {"code": li_exportable_attrs}
2221 acqLitExportAttrSelector.setValue();
2222 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
2223 acqLitExportAttrSelector._li_setup = true;
2225 openils.Util.show("acq-lit-export-attr-holder", "inline");
2228 this.exportAttrList = function() {
2229 var attr_def = acqLitExportAttrSelector.item;
2230 var li_list = this.getSelected();
2231 var value_list = li_list.map(
2233 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2234 attr_def.code, "lineitem_marc_attr_definition"
2237 ).filter(function(attr) { return Boolean(attr); });
2239 if (value_list.length > 0) {
2240 if (value_list.length < li_list.length) {
2242 dojo.string.substitute(
2243 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
2250 openils.XUL.contentToFileSaveDialog(
2251 value_list.join("\n"),
2252 localeStrings.EXPORT_SAVE_DIALOG_TITLE
2258 alert(dojo.string.substitute(
2259 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
2263 openils.Util.hide("acq-lit-export-attr-holder");
2266 this.printPO = function() {
2267 if(!this.isPO) return;
2268 progressDialog.show(true);
2269 fieldmapper.standardRequest(
2270 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
2272 params: [this.authtoken, this.isPO, 'html'],
2273 oncomplete: function(r) {
2274 progressDialog.hide();
2275 var evt = openils.Util.readResponse(r);
2276 if(evt && evt.template_output()) {
2277 openils.Util.printHtmlString(evt.template_output().data());
2285 this.receivePO = function() {
2286 if (!this.isPO) return;
2288 for (var id in this.liCache) {
2289 /* assumption: liCache reflects exactly the
2290 * set of LIs that belong to our PO */
2291 if (this.liCache[id].state() != "received" &&
2292 !this.checkLiAlerts(id)) return;
2295 this.show('acq-lit-progress-numbers');
2297 fieldmapper.standardRequest(
2298 ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
2300 params: [this.authtoken, this.isPO],
2301 onresponse : function(r) {
2302 var resp = openils.Util.readResponse(r);
2303 self._updateProgressNumbers(resp, true);
2309 this.issueReceive = function(obj, rollback) {
2310 /* (For now) there shall be no marking LI or LIDs (un)received
2311 * except from the actual "view PO" interface. */
2312 if (!this.isPO) return;
2315 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
2317 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
2319 progressDialog.show(true);
2320 fieldmapper.standardRequest(
2321 ["open-ils.acq", method], {
2323 "params": [this.authtoken, obj.id()],
2324 "onresponse": function(r) {
2325 if (r = openils.Util.readResponse(r)) {
2326 self.fetchClaimInfo(
2327 part == "lineitem" ? obj.id() : obj.lineitem(),
2329 function() { self.handleReceive(r); }
2331 progressDialog.hide();
2339 * Handles the responses from receive and rollback ML calls.
2341 this.handleReceive = function(resp) {
2344 for (var li_id in resp.li) {
2345 for (var key in resp.li[li_id])
2346 self.liCache[li_id][key](resp.li[li_id][key]);
2347 self.updateLiState(self.liCache[li_id]);
2351 if (typeof(self.poUpdateCallback) == "function")
2352 self.poUpdateCallback(resp.po);
2355 for (var lid_id in resp.lid) {
2356 for (var key in resp.lid[lid_id])
2357 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
2358 self.updateLidState(self.copyCache[lid_id]);
2364 this.rollbackPoReceive = function() {
2365 if(!this.isPO) return;
2366 if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
2367 this.show('acq-lit-progress-numbers');
2369 fieldmapper.standardRequest(
2370 ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
2372 params: [this.authtoken, this.isPO],
2373 onresponse : function(r) {
2374 var resp = openils.Util.readResponse(r);
2375 self._updateProgressNumbers(resp, true);
2381 this._updateProgressNumbers = function(resp, reloadOnComplete, onComplete) {
2382 this.vlAgent.handleResponse(resp,
2383 function(resp, res) {
2384 if(reloadOnComplete)
2385 location.href = location.href;
2387 onComplete(resp, res);
2393 this._createPO = function(fields) {
2394 var wantall = (fields.create_from == "all");
2396 /* If we're a picklist or purchase order already and the user wants
2397 * all lineitems, we might have pages' worth of lineitems haven't all
2398 * been loaded yet, so getSelected() won't find them. The server,
2399 * however, should know about all our lineitems, so let's ask the
2400 * server for a complete list.
2405 true, function(list) {
2406 self._createPOFromLineitems(fields, list);
2407 }, /* id_list */ true
2410 this._createPOFromLineitems(fields, this.getSelected(false, null, true /* id_list */));
2414 this._createPOFromLineitems = function(fields, selected) {
2415 if (selected.length == 0) return;
2418 var po = new fieldmapper.acqpo();
2419 po.provider(this.createPoProviderSelector.attr("value"));
2420 po.ordering_agency(this.createPoAgencySelector.attr("value"));
2421 po.prepayment_required(fields.prepayment_required[0] ? true : false);
2423 // if we're creating assets, delay the asset creation
2424 // until after the PO is created. This will allow us to
2425 // use showAssetCreator() directly.
2427 fieldmapper.standardRequest(
2428 ["open-ils.acq", "open-ils.acq.purchase_order.create"],
2431 openils.User.authtoken,
2432 po, {lineitems : selected}
2434 onresponse : function(r) {
2435 var resp = openils.Util.readResponse(r);
2436 if (resp.complete) {
2437 // self.isPO is needed for showAssetCreator();
2438 self.isPO = resp.purchase_order.id();
2439 var redir = oilsBasePath + "/acq/po/view/" + self.isPO;
2440 if (fields.create_assets[0]) {
2441 self.showAssetCreator(
2442 function() {location.href = redir}
2445 location.href = redir;
2454 this.batchFundWidget = null;
2456 this.applyBatchLiFunds = function() {
2458 var liIds = this.getSelected().map(function(li) { return li.id(); });
2459 if(liIds.length == 0) return; // warn?
2462 batchFundUpdateDialog.show();
2464 if(!this.batchFundWidget) {
2465 this.batchFundWidget = new openils.widget.AutoFieldWidget({
2467 selfReference : true,
2468 labelFormat : fundLabelFormat,
2469 searchFormat : fundSearchFormat,
2470 searchFilter : {"active": "t"},
2471 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
2472 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2473 dijitArgs : { "required": true, "labelType": "html" },
2476 this.batchFundWidget.build();
2479 dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
2480 dojo.connect(batchFundUpdateSubmit, 'onClick',
2483 // TODO: call .dry_run first to test thresholds
2484 fieldmapper.standardRequest(
2485 ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
2488 openils.User.authtoken,
2490 self.batchFundWidget.widget.attr('value')
2492 oncomplete : function(r) {
2493 var resp = openils.Util.readResponse(r);
2495 location.href = location.href;
2504 this._deleteLiList = function(list, idx) {
2505 if(idx == null) idx = 0;
2506 if(idx >= list.length) return;
2511 if (this.isPO && (li.state() == "on-order" || li.state() == "received")) {
2512 /* It makes little sense to delete a lineitem from a PO that has
2513 * already been marked 'on-order'. Especially if EDI is in use,
2514 * such a purchase order will probably have already been shipped
2515 * off to a vendor, and mucking with it at this point could leave
2516 * your data in a bad state that doesn't jive with reality.
2518 * I could see making this restriction even firmer.
2520 * I could also see adjusting the li state comparisons, extending
2521 * the comparison to the PO's state, and/or providing functions
2522 * that house the logic for comparing states in a single location.
2524 * Yes, this will be really annoying if you have selected a lot
2525 * of lineitems to cancel that have been ordered. You'll get a
2526 * confirm dialog for each one.
2529 if (!confirm(localeStrings.DEL_LI_FROM_PO)) {
2530 self._deleteLiList(list, ++idx); /* move on to next in list */
2535 fieldmapper.standardRequest(
2537 this.isPO ? 'open-ils.acq.purchase_order.lineitem.delete' : 'open-ils.acq.picklist.lineitem.delete'],
2539 params: [openils.User.authtoken, liId],
2540 oncomplete: function(r) {
2541 self.removeLineitem(liId);
2542 self._deleteLiList(list, ++idx);
2548 this.editOrderMarc = function(li) {
2550 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
2551 to true in about:config */
2553 if(!openils.XUL.enableXPConnect()) return;
2555 if(openils.XUL.isXUL()) {
2556 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
2558 win = window.open('/xul/server/cat/marcedit.xul');
2562 record : {marc : li.marc(), "rtype": "bre"},
2564 label: 'Save Record', // XXX I18N
2565 func: function(xmlString) {
2567 fieldmapper.standardRequest(
2568 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
2570 params: [openils.User.authtoken, li],
2571 oncomplete: function(r) {
2572 openils.Util.readResponse(r);
2574 self.drawInfo(li.id())
2580 'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
2581 'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
2585 this._savePl = function(values) {
2587 (values.which == 'all'),
2588 function(list) { self._savePlFromLineitems(values, list); }
2592 this._savePlFromLineitems = function(values, selected) {
2593 openils.Util.show("acq-lit-generic-progress");
2595 if(values.new_name) {
2596 openils.acq.Picklist.create(
2597 {name: values.new_name},
2603 oilsBasePath + "/acq/picklist/view/" + id;
2608 } else if(values.existing_pl) {
2609 // update lineitems to use an existing picklist
2611 values.existing_pl, selected, 0,
2614 oilsBasePath + "/acq/picklist/view/" +
2621 this._updateLiState = function(values, state) {
2622 progressDialog.show(true);
2624 (values.which == 'all'),
2626 self._updateLiStateFromLineitems(values, state, list);
2631 this._updateLiStateFromLineitems = function(values, state, selected) {
2632 if(!selected.length) return;
2633 dojo.forEach(selected, function(li) {li.state(state);});
2634 self._updateLiList(null, selected, 0,
2635 // TODO consider inline updates for efficiency
2636 function() { location.href = location.href }
2640 this._updateLiList = function(pl, list, idx, oncomplete) {
2641 if(idx >= list.length) return oncomplete();
2643 if(pl != null) li.picklist(pl);
2644 litGenericProgress.update({maximum: list.length, progress: idx});
2645 new openils.acq.Lineitem({lineitem:li}).update(
2647 self._updateLiList(pl, list, ++idx, oncomplete);
2652 this._loadPOSelect = function() {
2653 if (!this.createPoProviderSelector) {
2654 var widget = new openils.widget.AutoFieldWidget({
2655 "fmField": "provider",
2657 "searchFilter": {"active": "t"},
2658 "parentNode": dojo.byId("acq-lit-po-provider"),
2660 "onChange": function() {
2662 self._updateCreatePoPrepayCheckbox(
2663 this.item.prepayment_required()
2669 widget.build(function(w) { self.createPoProviderSelector = w; });
2672 if (!this.createPoAgencySelector) {
2673 var widget = new openils.widget.AutoFieldWidget({
2674 "fmField": "ordering_agency",
2676 "parentNode": dojo.byId("acq-lit-po-agency"),
2677 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2679 widget.build(function(w) { self.createPoAgencySelector = w; });
2683 this.showRealCopyEditUI = function(li) {
2688 this._fetchLineitem(li.id(),
2690 li = self.liCache[li.id()] = fullLi;
2694 id : li.lineitem_details().map(
2695 function(item) { return item.eg_copy_id() }
2699 oncomplete : function(r) {
2701 var r_list = openils.Util.readResponse( r );
2702 for (var i = 0; i < r_list.length; i++) {
2703 var copy = r_list[i];
2704 var volId = copy.call_number();
2705 var volume = self.volCache[volId];
2707 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2709 copy.call_number(volume);
2710 copyList.push(copy);
2713 xulG.volume_item_creator( { 'existing_copies' : copyList } );
2716 alert('error in oncomplete: ' + E);
2725 this.drawBibFinder = function(li) {
2728 var liWrapper = new openils.acq.Lineitem({lineitem:li});
2731 ['isbn', 'upc', 'issn', 'title', 'author'],
2733 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
2735 if(field == 'title' || field == 'author') {
2736 query += field +':' + val + ' ';
2738 query += 'identifier|' + field + ':' + val + ' ';
2745 oilsBasePath + '/acq/lineitem/findbib?query=' + escape(query),
2746 '', 'resizable,scrollbars=1');
2748 win.window.recordFound = function(bibId) {
2751 var attrs = li.attributes();
2752 li.attributes(null);
2753 li.eg_bib_id(bibId);
2755 fieldmapper.standardRequest(
2756 ["open-ils.acq", "open-ils.acq.lineitem.update"],
2758 "params": [openils.User.authtoken, li],
2760 "oncomplete": function(r) {
2761 if(openils.Util.readResponse(r)) {
2762 location.href = location.href;