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);
581 var actNewInvoice = nodeByName('action_new_invoice', row);
582 var actLinkInvoice = nodeByName('action_link_invoice', row);
583 var actViewInvoice = nodeByName('action_view_invoice', row);
585 // always allow access to LI history
586 nodeByName('action_view_history', row).onclick =
587 function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
589 /* handle row coloring for based on LI state */
590 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
591 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
593 // Expose invoice actions for any lineitem that is linked to a PO
594 if( li.purchase_order() ) {
596 actNewInvoice.disabled = false;
597 actLinkInvoice.disabled = false;
598 actViewInvoice.disabled = false;
600 actNewInvoice.onclick = function() {
601 location.href = oilsBasePath + '/acq/invoice/view?create=1&attach_li=' + li.id();
602 nodeByName("action_none", row).selected = true;
605 actLinkInvoice.onclick = function() {
606 if (!self.invoiceLinkDialogManager) {
607 self.invoiceLinkDialogManager =
608 new InvoiceLinkDialogManager("li");
610 self.invoiceLinkDialogManager.target = li;
611 acqLitLinkInvoiceDialog.show();
612 nodeByName("action_none", row).selected = true;
615 actViewInvoice.onclick = function() {
616 location.href = oilsBasePath +
617 "/acq/search/unified?so=" +
618 base64Encode({"jub":[{"id": li.id()}]}) +
620 nodeByName("action_none", row).selected = true;
626 * If we haven't fleshed the lineitem_details, default to allowing access to the
627 * holdings maintenence actions. The alternative is to flesh LIDs on every lineitem,
628 * but that will add to page render time. Let's see if this will suffice...
630 var lids = li.lineitem_details();
632 (lids && !lids.filter(function(lid) { return lid.eg_copy_id() })[0] )) {
634 actUpdateBarcodes.disabled = false;
635 actUpdateBarcodes.onclick = function() {
636 self.showRealCopyEditUI(li);
637 nodeByName("action_none", row).selected = true;
639 actHoldingsMaint.disabled = false;
640 actHoldingsMaint.onclick =
641 self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
644 var state_cell = nodeByName("li_state", row);
649 if(typeof li.cancel_reason() == "object") {
650 var holds_state = dojo.create(
652 "style": "border-bottom: 1px dashed #000;",
653 "innerHTML": li.state()
654 }, state_cell, "only"
658 "label": "<em>" + li.cancel_reason().label() +
659 "</em><br />" + li.cancel_reason().description(),
660 "connectId": [holds_state]
661 }, dojo.create("span", null, state_cell, "last")
667 actReceive.disabled = false;
668 actReceive.onclick = function() {
669 if (self.checkLiAlerts(li.id()))
670 self.issueReceive(li);
671 nodeByName("action_none", row).selected = true;
676 actUnRecv.disabled = false;
677 actUnRecv.onclick = function() {
678 if (confirm(localeStrings.UNRECEIVE_LI))
679 self.issueReceive(li, /* rollback */ true);
680 nodeByName("action_none", row).selected = true;
685 state_cell.innerHTML = li.state(); // TODO i18n state labels
689 this._setAlertStore = function() {
690 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
692 "data": acqliat.toStoreData(
694 "acqliat", {"id": {"!=": null}}
699 acqLitAlertAlertText.setValue(); /* make the store "live" */
700 acqLitAlertAlertText._store_ready = true;
704 * Draws and shows the lineitem notes pane
706 this.drawLiNotes = function(li) {
709 if (!acqLitAlertAlertText._store_ready)
710 this._setAlertStore();
713 li.lineitem_notes().sort(
715 if(a.edit_time() < b.edit_time()) return 1;
721 while(this.liNotesTbody.childNodes[0])
722 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
725 acqLitCreateNoteSubmit.onClick = function() {
726 var value = acqLitCreateNoteText.attr('value');
728 var note = new fieldmapper.acqlin();
731 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
734 note.lineitem(li.id());
736 self.updateLiNotes(li, note);
737 acqLitCreateNoteVendorPublic.attr("checked", false);
738 acqLitCreateNoteText.attr("value", "");
741 acqLitCreateAlertSubmit.onClick = function() {
742 if (!acqLitAlertAlertText.item) {
743 alert(localeStrings.ALERT_UNSELECTED);
747 var alert_text = new fieldmapper.acqliat().fromStoreItem(
748 acqLitAlertAlertText.item
750 var value = acqLitAlertNoteValue.attr("value") || "";
752 var note = new fieldmapper.acqlin();
754 note.lineitem(li.id());
756 note.alert_text(alert_text);
758 self.updateLiNotes(li, note);
761 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
765 * Draws a single lineitem note in the notes pane
767 this.addLiNote = function(li, note) {
768 if(note.isdeleted()) return;
770 var row = self.liNotesRow.cloneNode(true);
771 nodeByName("value", row).innerHTML = note.value();
772 var alert_node = nodeByName("alert_code", row);
773 if (note.alert_text()) {
774 alert_node.innerHTML = note.alert_text().code();
775 if (note.alert_text().description()) {
778 "connectId": [alert_node],
779 "label": note.alert_text().description()
780 }, dojo.create("span", null, alert_node, "after")
785 if (openils.Util.isTrue(note.vendor_public()))
786 nodeByName("vendor_public", row).innerHTML =
787 localeStrings.VENDOR_PUBLIC;
789 nodeByName("delete", row).onclick = function() {
790 note.isdeleted(true);
791 self.liNotesTbody.removeChild(row);
792 self.updateLiNotes(li);
795 if(note.edit_time()) {
796 nodeByName("edit_time", row).innerHTML =
797 dojo.date.locale.format(
798 dojo.date.stamp.fromISOString(note.edit_time()),
799 {formatLength:'short'});
802 self.liNotesTbody.appendChild(row);
806 * Updates any new/changed/deleted notes on the server
808 this.updateLiNotes = function(li, newNote) {
814 notes = li.lineitem_notes().filter(
816 if(note.ischanged() || note.isnew() || note.isdeleted())
822 if(notes.length == 0) return;
823 progressDialog.show();
825 fieldmapper.standardRequest(
826 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
828 params : [this.authtoken, notes],
829 onresponse : function(r) {
830 var resp = openils.Util.readResponse(r);
835 // remove the old changed notes
837 dojo.forEach(li.lineitem_notes(),
839 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
843 li.lineitem_notes(list);
846 progressDialog.hide();
847 self.updateLiNotesCount(li);
848 self.drawLiNotes(li);
852 progressDialog.update(resp);
853 var newnote = resp.note;
855 if(!newnote.isdeleted()) {
856 newnote.isnew(false);
857 newnote.ischanged(false);
858 li.lineitem_notes().push(newnote);
865 this.updateLiPrice = function(input, li) {
867 var price = input.value;
868 if(Number(price) == Number(li.estimated_unit_price())) return;
870 fieldmapper.standardRequest(
871 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
872 { async : false, // redundant w/ timeout
874 params : [this.authtoken, li.id(), price],
875 oncomplete : function(r) {
876 openils.Util.readResponse(r);
877 li.estimated_unit_price(price); // update local copy
880 * If this is a PO and every visible lineitem has a price,
881 * check again to see if this PO can be activated. Note that
882 * every visible lineitem having a price does not guarantee it can
883 * be activated, which is why we still make the call. Having a price
884 * set for every visiable lineitem is just the lowest barrier to entry.
887 var priceNodes = dojo.query('[name=price]', dojo.byId('acq-lit-tbody'));
889 dojo.forEach(priceNodes, function(node) { if (node.value == '') allSet = false});
890 if (allSet) checkCouldActivatePo();
897 this.removeLineitem = function(liId) {
898 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
899 delete this.liCache[liId];
900 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
903 this.drawInfo = function(liId) {
904 if (!this._isRelatedViewer) {
905 var d = dojo.byId("acq-lit-info-related");
906 if (!this.relCache[liId]) {
907 fieldmapper.standardRequest(
910 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
913 "params": [openils.User.authtoken, liId],
914 "onresponse": function(r) {
915 self.relCache[liId] = openils.Util.readResponse(r);
916 nodeByName("related_number", d).innerHTML =
919 self.relCache[liId] >1 ? "show" : "hide"
925 nodeByName("related_number", d).innerHTML = this.relCache[liId];
926 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
931 openils.acq.Lineitem.fetchAttrDefs(
933 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
938 /* For a given list of lineitem ids, build a list of full lineitems
939 * re-using the fetching logic that is otherwise typical to use in this
942 * If we've already got a lineitem in the cache, just use that.
944 * Once we've built a list of lineitems, call callback(thatlist).
946 this.fetchLineitemsById = function(id_list, callback) {
947 var total = id_list.length;
948 var result_list = [];
950 var inner = function(li) {
953 callback(result_list);
956 id_list.forEach(function(id) { self._fetchLineitem(id, inner); });
959 this._fetchLineitem = function(liId, handler, force) {
961 var li = this.liCache[liId];
962 if(li && li.marc() && li.lineitem_details() && !force)
965 fieldmapper.standardRequest(
966 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
969 params: [self.authtoken, liId, {
971 flesh_cancel_reason: true,
972 flesh_li_details: true,
974 flesh_fund_debit: true }],
976 oncomplete: function(r) {
977 var li = openils.Util.readResponse(r);
978 self.liCache[liId] = li;
985 this._drawInfo = function(li) {
987 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
990 openils.Util.hide('acq-lit-marc-order-record-label');
991 openils.Util.hide(acqLitEditOrderMarc.domNode);
992 openils.Util.show('acq-lit-marc-real-record-label');
994 openils.Util.show('acq-lit-marc-order-record-label');
995 openils.Util.show(acqLitEditOrderMarc.domNode);
996 openils.Util.hide('acq-lit-marc-real-record-label');
999 this.drawMarcHTML(li);
1000 this.infoTbody = dojo.byId('acq-lit-info-tbody');
1003 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
1004 while(this.infoTbody.childNodes[0])
1005 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
1007 for(var i = 0; i < li.attributes().length; i++) {
1008 var attr = li.attributes()[i];
1009 var row = this.infoRow.cloneNode(true);
1011 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
1012 var name = openils.acq.Lineitem.attrDefs[type].filter(
1014 return (a.code() == attr.attr_name());
1016 ).pop().description();
1018 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
1019 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
1020 this.infoTbody.appendChild(row);
1023 if (!this._isRelatedViewer) {
1024 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
1025 oilsBasePath + "/acq/lineitem/related/" + li.id();
1030 this.generateMakeRecTab = function(bib_id,default_view, row) {
1034 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
1037 show_nav_buttons : true,
1038 show_print_button : true,
1039 opac_url : xulG.url_prefix(xulG.urls.opac_rdetail + bib_id),
1040 default_view : default_view
1044 if(row) nodeByName("action_none", row).selected = true;
1048 this.drawMarcHTML = function(li) {
1049 var params = [null, true, li.marc()];
1051 params = [li.eg_bib_id(), true];
1053 fieldmapper.standardRequest(
1054 ['open-ils.search', 'open-ils.search.biblio.record.html'],
1057 oncomplete: function(r) {
1058 dojo.byId('acq-lit-marc-div').innerHTML =
1059 openils.Util.readResponse(r);
1065 this.drawCopies = function(liId, force_fetch) {
1066 if (typeof force_fetch == "undefined")
1067 force_fetch = false;
1069 openils.acq.Lineitem.fetchAndRender(liId, {},
1070 function(li, html) {
1071 dojo.byId('acq-lit-copies-li-summary').innerHTML = html;
1075 this.show('copies');
1077 this.copyCache = {};
1078 this.copyWidgetCache = {};
1079 this.oldCopyWidgetCache = {};
1080 this.virtDfaCounts = {};
1081 this.realDfaCache = {};
1084 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
1085 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
1086 acqLitCopyCountInput.attr('value', '0');
1088 while(this.copyTbody.childNodes[0])
1089 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
1091 this._drawBatchCopyWidgets();
1093 this._drawDistribApplied(liId);
1095 this._fetchDistribFormulas(
1097 openils.acq.Lineitem.fetchAttrDefs(
1099 self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch);
1106 this._saveDistribAppliedTemplates = function() {
1107 if (!this._appliedDistribTemplate) {
1108 this._appliedDistribTemplate =
1109 dojo.byId("acq-lit-distrib-applied-tbody").
1110 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
1111 dojo.attr(this._appliedDistribTemplate, "id");
1115 this._drawDistribApplied = function(liId) {
1116 /* Build this table while hidden to prevent rendering artifacts */
1117 openils.Util.hide("acq-lit-distrib-applied-tbody");
1119 this._saveDistribAppliedTemplates();
1121 /* Remove any rows in the table from previous populations */
1122 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
1123 forEach(dojo.destroy);
1125 /* Unregister all dijits previously created (for some reason this isn't
1126 * covered by the above destroy calls). */
1127 dijit.registry.forEach(
1128 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
1131 /* Populate the table with our liId */
1133 fieldmapper.standardRequest(
1135 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
1138 "params": [self.authtoken, liId],
1139 "onresponse": function(r) {
1140 var dfa = openils.Util.readResponse(r);
1143 self.realDfaCache[dfa.id()] = dfa;
1144 self._drawDistribAppliedUnit(dfa);
1147 "oncomplete": function() {
1148 /* Reveal built table */
1151 "acq-lit-distrib-applied-tbody", "table-row-group"
1159 this._drawDistribAppliedUnit = function(dfa) {
1160 var new_row = false;
1161 var row = dojo.query(
1162 'tr[formula="' + dfa.formula().id() + '"]',
1163 "acq-lit-distrib-applied-tbody"
1168 row = dojo.clone(this._appliedDistribTemplate);
1169 dojo.attr(row, "formula", dfa.formula().id());
1170 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
1173 var td = dojo.query("td", row)[0];
1175 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1176 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1179 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1181 new dijit.form.Button(
1183 "onClick": function() {
1184 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1185 self.deleteDfa(dfa);
1188 /* XXX I /cannot/ make the following work in as a CSS class
1189 * for some reason. So frustrating... */
1190 "style": function(id) {
1192 "font-weight: bold; color: #c00;" :
1194 }(dfa.id()) + "margin: 0 6px;display: inline;"
1195 }, "dfa-button-" + dfa.id()
1199 "connectId": ["dfa-button-" + dfa.id()],
1200 "label": dojo.string.substitute(
1201 localeStrings.DFA_TIP, dfa.id() > 0 ? [
1202 openils.User.formalName(dfa.creator()),
1203 dojo.date.locale.format(
1204 dojo.date.stamp.fromISOString(dfa.create_time()),
1205 {"formatLength":"short"}
1207 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
1209 }, "dfa-tip-" + dfa.id()
1213 this.deleteDfa = function(dfa) {
1214 if (dfa.id() > 0) { /* real */
1215 this.pcrud.eliminate(
1218 "oncomplete": function() {
1219 self._removeDistribApplied(dfa.id());
1220 delete self.realDfaCache[dfa.id()];
1224 } else { /* virtual */
1225 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
1226 this.virtDfaCounts[dfa.formula().id()] = 0;
1227 /* hasn't been saved yet, so no need to do anything server side */
1228 this._removeDistribApplied(dfa.id());
1233 this._removeDistribApplied = function(dfaId) {
1234 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
1235 dijit.registry.forEach(
1236 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
1238 this._removeDistribAppliedEmptyRows();
1241 this._removeAllDistribAppliedVirtual = function() {
1242 /* Unregister dijits */
1243 dijit.registry.forEach(
1244 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
1246 this._removeDistribAppliedEmptyRows();
1249 this._removeDistribAppliedEmptyRows = function() {
1250 /* Remove any rows with no DFA at all */
1251 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
1253 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
1259 * Insert a new row into the distribution formula selection form
1261 this._addDistribFormulaRow = function() {
1264 if (!self.distribForms) {
1265 // no formulas, hide the form
1266 openils.Util.hide('acq-lit-distrib-formula-table');
1270 if(!this.distribFormulaTemplate)
1271 this.distribFormulaTemplate =
1272 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
1274 var row = this.distribFormulaTemplate.cloneNode(true);
1275 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
1277 this.dfSelector = new dijit.form.FilteringSelect(
1278 {"labelAttr": "dynLabel", "labelType": "html"},
1279 nodeByName("selector", row)
1281 this._updateFormulaStore();
1282 this.dfSelector.fetchProperties =
1283 {"sort": [{"attribute": "use_count", "descending": true}]};
1285 var apply = new dijit.form.Button(
1286 {"label": localeStrings.APPLY},
1287 nodeByName('set_button', row)
1290 var reset = new dijit.form.Button(
1291 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
1292 nodeByName("reset_button", row)
1295 dojo.connect(apply, 'onClick',
1297 var form_id = self.dfSelector.attr("value");
1298 if(!form_id) return;
1299 self._applyDistribFormula(form_id);
1300 reset.attr("disabled", false);
1304 dojo.connect(reset, 'onClick',
1306 self.restoreCopyFieldsBeforeDF();
1307 self.virtDfaCounts = {};
1308 self.virtDfaId = -1;
1310 self._updateFormulaStore();
1311 self._removeAllDistribAppliedVirtual();
1312 reset.attr("disabled", "true");
1319 * Applies a distrib formula to the current set of copies
1321 this._applyDistribFormula = function(formula) {
1322 if(!formula) return;
1324 formula = this.distribForms.filter(
1325 function(form) { return form.id() == formula; }
1328 var copyRows = dojo.query('tr', self.copyTbody);
1330 if (this.dfeOffset >= copyRows.length) {
1331 alert(localeStrings.OUT_OF_COPIES);
1335 var entries_applied = 0;
1337 var rowIndex = this.dfeOffset;
1338 rowIndex < copyRows.length;
1342 var row = copyRows[rowIndex];
1343 var copy_id = row.getAttribute('copy_id');
1344 var copyWidgets = this.copyWidgetCache[copy_id];
1345 var entryIndex = this.dfeOffset;
1348 // find the correct entry for the current row
1349 dojo.forEach(formula.entries(),
1352 entryIndex += e.item_count();
1353 if(entryIndex > rowIndex)
1361 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
1362 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
1365 this.saveCopyFieldsBeforeDF(copy_id);
1366 this._copy_fields_for_acqdf.forEach(
1368 if(entry[field]()) {
1369 copyWidgets[field].attr('value', (entry[field]()));
1376 if (entries_applied) {
1377 this.virtDfaCounts[formula.id()] =
1378 ++(this.virtDfaCounts[formula.id()]) || 1;
1379 this._updateFormulaStore();
1380 this._drawDistribAppliedUnit(
1382 var dfa = new acqdfa();
1383 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
1386 this.dfeOffset += entries_applied;
1391 * This function updates the DF store for the dropdown so that use_counts
1392 * can reflect DF applications from this session before they're saved
1395 this._updateFormulaStore = function() {
1396 this.dfSelector.store = new dojo.data.ItemFileReadStore(
1398 "data": self._labelFormulasWithCounts(
1399 acqdf.toStoreData(self.distribForms)
1405 this.saveCopyFieldsBeforeDF = function(copy_id) {
1407 if (!this.oldCopyWidgetCache[copy_id]) {
1408 var copyWidgets = this.copyWidgetCache[copy_id];
1410 this.oldCopyWidgetCache[copy_id] = {};
1411 this._copy_fields_for_acqdf.forEach(
1413 self.oldCopyWidgetCache[copy_id][f] =
1414 copyWidgets[f].attr("value");
1420 this.restoreCopyFieldsBeforeDF = function() {
1422 for (var copy_id in this.oldCopyWidgetCache) {
1423 this._copy_fields_for_acqdf.forEach(
1425 self.copyWidgetCache[copy_id][f].attr(
1426 "value", self.oldCopyWidgetCache[copy_id][f]
1433 this._labelFormulasWithCounts = function(store_data) {
1434 for (var key in store_data.items) {
1435 var obj = store_data.items[key];
1436 obj.use_count = Number(obj.use_count); /* needed for sorting */
1438 if (this.virtDfaCounts[obj.id])
1439 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
1441 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
1442 obj.use_count + "]</span> " + obj.name;
1448 * This method formerly would not refetch the DF formulas if they'd been
1449 * loaded already, but now it always re-fetches, since use_count changes.
1451 /** TODO: port distrib-formula selector to autofieldwidget+pcrud/dojo store */
1452 this._fetchDistribFormulas = function(onload) {
1453 fieldmapper.standardRequest(
1455 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
1458 "params": [openils.User.authtoken, 0, 500],
1459 "oncomplete": function(r) {
1460 self.distribForms = openils.Util.readResponse(r);
1461 if(!self.distribForms || self.distribForms.length == 0) {
1462 self.distribForms = [];
1464 self._addDistribFormulaRow();
1471 this._drawBatchCopyWidgets = function() {
1472 var row = this.copyBatchRow;
1473 dojo.forEach(liDetailBatchFields,
1475 if(self.copyBatchRowDrawn) {
1476 self.copyBatchWidgets[field].attr('value', null);
1478 var widget = new openils.widget.AutoFieldWidget({
1481 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1482 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1483 searchFilter : (field == 'fund') ? {"active": "t"} : null,
1484 parentNode : dojo.query('[name='+field+']', row)[0],
1485 orgLimitPerms : ['CREATE_PICKLIST'],
1488 "labelType": (field == "fund") ? "html" : null
1490 noCache: (field == "fund"),
1495 if (field == "fund" && w.store)
1496 self._ensureCSSFundClasses(w.store);
1497 self.copyBatchWidgets[field] = w;
1500 if (field == "fund") {
1502 widget.widget, "onChange", function(val) {
1503 self._updateFundSelectorStyle(widget, val);
1510 this.copyBatchRowDrawn = true;
1513 this.batchCopyUpdate = function() {
1515 for(var k in this.copyWidgetCache) {
1516 var cache = this.copyWidgetCache[k];
1517 dojo.forEach(liDetailBatchFields, function(f) {
1518 var newval = self.copyBatchWidgets[f].attr('value');
1519 if(newval) cache[f].attr('value', newval);
1524 this._drawCopies = function(li) {
1527 // this button sets the total number of copies for a given lineitem
1528 acqLitAddCopyCount.onClick = function() {
1529 var count = acqLitCopyCountInput.attr('value');
1532 while(self.copyCount() < count)
1535 // delete rows if necessary
1536 var diff = self.copyCount() - count;
1538 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
1539 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
1540 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
1542 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1548 if(li.lineitem_details().length > 0) {
1549 dojo.forEach(li.lineitem_details(),
1551 self.addCopy(li, copy);
1559 this.copyCount = function() {
1561 for(var id in this.copyCache) {
1562 if(!this.copyCache[id].isdeleted())
1568 this.virtCopyId = -1;
1569 this.addCopy = function(li, copy) {
1570 var row = this.copyRow.cloneNode(true);
1571 this.copyTbody.appendChild(row);
1575 copy = new fieldmapper.acqlid();
1577 copy.id(this.virtCopyId--);
1578 copy.lineitem(li.id());
1581 this.copyCache[copy.id()] = copy;
1582 row.setAttribute('copy_id', copy.id());
1583 self.copyWidgetCache[copy.id()] = {};
1585 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1587 var rcvr = copy.receiver();
1589 if (!userCache[rcvr]) {
1590 if(rcvr == openils.User.user.id()) {
1591 userCache[rcvr] = openils.User.user;
1593 userCache[rcvr] = fieldmapper.standardRequest(
1594 ['open-ils.actor', 'open-ils.actor.user.retrieve'],
1595 {params: [openils.User.authtoken, rcvr]}
1599 dojo.query('[name=receiver]', row)[0].innerHTML = userCache[rcvr].usrname();
1602 dojo.forEach(liDetailFields,
1605 if (field == "fund") {
1606 searchFilter = (copy.fund() ?
1607 {"-or": {"active": "t", "id": copy.fund()}} :
1610 searchFilter = null;
1613 var readOnly = false;
1615 // TODO: Add support for changing the owning_lib after real copies have been made.
1616 // owning_lib is order data as much as its item data
1617 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
1621 // TODO: add support for changing the fund after debits have been created
1622 // Note: invoicing allows the change
1623 if(copy.fund_debit() && field == 'fund') {
1628 var widget = new openils.widget.AutoFieldWidget({
1631 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1632 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1633 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1634 searchFilter : searchFilter,
1635 noCache: (field == "fund"),
1637 parentNode : dojo.query('[name='+field+']', row)[0],
1638 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
1639 readOnly : readOnly,
1640 orgDefaultsToWs : true
1644 // make sure we capture the value from any async widgets
1647 if (field == "fund" && w.store)
1648 self._ensureCSSFundClasses(w.store);
1651 copy[field](ww.getFormattedValue())
1653 self.copyWidgetCache[copy.id()][field] = w;
1655 dojo.connect(w, 'onChange',
1657 if (field == "fund")
1658 self._updateFundSelectorStyle(widget, val);
1660 if (!readOnly && (copy.isnew() || val != copy[field]())) {
1661 // prevent setting ischanged() automatically on widget load for existing copies
1662 copy[field](widget.getFormattedValue())
1663 copy.ischanged(true);
1672 this.updateLidState(copy, row);
1675 this._ensureCSSFundClass = function(id) {
1676 if (!this.fundStyleSheet) {
1678 "style", {"type": "text/css"},
1679 document.getElementsByTagName("head")[0], "last"
1681 this.fundStyleSheet = document.styleSheets[
1682 document.styleSheets.length - 1
1686 var cn = "fund_" + id;
1687 if (!this.haveFundClass[cn]) {
1688 fieldmapper.standardRequest(
1689 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
1691 "params": [openils.User.authtoken, id],
1693 "oncomplete": function(r) {
1694 r = openils.Util.readResponse(r);
1695 self.fundBalanceState[id] = r;
1697 if (r[0] /* stop */)
1698 style = fundStyles.stop;
1699 else if (r[1] /* warning */)
1700 style = fundStyles.warning;
1701 self.fundStyleSheet.insertRule(
1702 "." + cn + " { " + style + " }",
1703 self.fundStyleSheet.cssRules.length
1705 self.haveFundClass[cn] = true;
1712 this._ensureCSSFundClasses = function(store) {
1714 "query": {"id": "*"},
1715 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
1719 this._updateFundSelectorStyle = function(widget, fund_id) {
1720 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
1721 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
1724 this.updateLidState = function(copy, row) {
1725 if (typeof(row) == "undefined") {
1727 'tr[copy_id="' + copy.id() + '"]', this.copyTbody
1732 var recv_link = nodeByName("receive", row);
1733 var unrecv_link = nodeByName("unreceive", row);
1734 var del_link = nodeByName("delete", row);
1735 var cxl_link = nodeByName("cancel", row);
1736 var claim_link = nodeByName("claim", row);
1737 var cxl_reason_link = nodeByName("cancel_reason", row);
1739 if (copy.cancel_reason()) {
1740 openils.Util.hide(del_link.parentNode);
1741 openils.Util.hide(recv_link);
1742 openils.Util.hide(unrecv_link);
1743 openils.Util.hide(cxl_link);
1744 openils.Util.hide(claim_link);
1746 /* XXX the following may leak memory in a long lived table: dijits may not get destroyed... not positive. revisit. */
1747 var holds_reason = dojo.create(
1749 "style": "border-bottom: 1px dashed #000;",
1750 "innerHTML": "Cancelled" /* XXX [sic] and i18n */
1751 }, cxl_reason_link, "only"
1755 "label": "<em>" + copy.cancel_reason().label() +
1756 "</em><br />" + copy.cancel_reason().description(),
1757 "connectId": [holds_reason]
1758 }, dojo.create("span", null, cxl_reason_link, "last")
1760 openils.Util.show(cxl_reason_link, "inline");
1761 } else if (this.isPO) {
1762 /* Only using this in one place so far, but may want it for better
1763 * decisions on when to display certain controls. */
1764 var li_state = this.liCache[copy.lineitem()].state();
1766 openils.Util.hide(del_link.parentNode);
1767 openils.Util.hide(cxl_reason_link);
1769 /* Avoid showing (un)receive links, cancel links, for virt copies */
1770 if (copy.id() > 0) {
1771 if (copy.recv_time()) {
1772 openils.Util.hide(cxl_link);
1773 openils.Util.hide(recv_link);
1774 openils.Util.hide(claim_link);
1776 openils.Util.show(unrecv_link, "inline");
1777 unrecv_link.onclick = function() {
1778 if (confirm(localeStrings.UNRECEIVE_LID))
1779 self.issueReceive(copy, /* rollback */ true);
1782 openils.Util.hide(unrecv_link);
1784 if (this.claimEligibleLid[copy.id()]) {
1785 openils.Util.show(claim_link, "inline");
1786 claim_link.onclick = function() {
1787 self.claimDialog.show(
1788 self.liCache[copy.lineitem()], copy.id()
1792 openils.Util.hide(claim_link);
1795 openils.Util[li_state == "on-order" ? "show" : "hide"](
1798 openils.Util.show(cxl_link, "inline");
1799 recv_link.onclick = function() {
1800 if (self.checkLiAlerts(copy.lineitem()))
1801 self.issueReceive(copy);
1803 cxl_link.onclick = function() {
1804 self.cancelLid(copy.id());
1808 openils.Util.hide(cxl_link);
1809 openils.Util.hide(unrecv_link);
1810 openils.Util.hide(recv_link);
1811 openils.Util.hide(claim_link);
1814 openils.Util.hide(unrecv_link);
1815 openils.Util.hide(recv_link);
1816 openils.Util.hide(cxl_reason_link);
1817 openils.Util.hide(claim_link);
1819 del_link.onclick = function() { self.deleteCopy(row) };
1820 openils.Util.show(del_link.parentNode);
1824 this.cancelLid = function(lid_id) {
1825 lidCancelDialog._lid_id = lid_id;
1826 openils.Util.show(lidCancelDialog.domNode.parentNode);
1827 lidCancelDialog.show();
1828 if (!lidCancelDialog._prepared) {
1829 var widget = new openils.widget.AutoFieldWidget({
1830 "fmField": "cancel_reason",
1831 "fmClass": "acqlid",
1832 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
1833 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1838 acqLidCancelButton.onClick = function() {
1839 if (w.attr("value")) {
1840 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
1842 lidCancelDialog._lid_id,
1846 lidCancelDialog.hide();
1849 lidCancelDialog._prepared = true;
1855 this._cancelLid = function(lid_id, reason) {
1856 fieldmapper.standardRequest(
1857 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
1858 "params": [openils.User.authtoken, lid_id, reason],
1860 "onresponse": function(r) {
1861 if (r = openils.Util.readResponse(r)) {
1863 for (var id in r.lid) {
1864 /* actually this should only iterate once */
1865 self.copyCache[id].cancel_reason(
1866 r.lid[id].cancel_reason
1868 self.updateLidState(self.copyCache[id]);
1877 this._confirmAlert = function(li, lin) {
1879 dojo.string.substitute(
1880 localeStrings.CONFIRM_LI_ALERT, [
1881 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1882 "title", "lineitem_marc_attr_definition"
1884 lin.alert_text().code(),
1885 lin.alert_text().description() || "",
1892 this.checkLiAlerts = function(li_id) {
1893 var li = this.liCache[li_id];
1895 var alert_notes = li.lineitem_notes().filter(
1896 function(o) { return Boolean(o.alert_text()); }
1899 /* this is _intentionally_ not done in a call to forEach() ... */
1900 for (var i = 0; i < alert_notes.length; i++) {
1901 if (this.noteAcks[alert_notes[i].id()])
1903 else if (!this._confirmAlert(li, alert_notes[i]))
1906 this.noteAcks[alert_notes[i].id()] = true;
1912 this.deleteCopy = function(row) {
1913 var copy = this.copyCache[row.getAttribute('copy_id')];
1914 copy.isdeleted(true);
1916 delete this.copyCache[copy.id()];
1917 this.copyTbody.removeChild(row);
1920 this._virtDfaCountsAsList = function() {
1922 for (var key in this.virtDfaCounts) {
1923 for (var i = 0; i < this.virtDfaCounts[key]; i++)
1929 this.confirmBreachedCopyFunds = function(copies) {
1930 var stop = 0, warning = 0;
1934 var state = self.fundBalanceState[o.fund()];
1935 if (state[0] /* stop */)
1937 else if (state[1] /* warning */)
1944 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
1945 } else if (warning) {
1946 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
1951 this.saveCopyChanges = function(liId) {
1957 for(var id in this.copyCache) {
1958 var c = this.copyCache[id];
1959 if(!c.isdeleted()) total++;
1960 if(c.isnew() || c.ischanged() || c.isdeleted()) {
1961 if(c.id() < 0) c.id(null);
1967 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
1970 if (copies.length > 0) {
1971 if (!this.confirmBreachedCopyFunds(copies))
1974 if (typeof(this._copy_count_cb) == "function")
1975 this._copy_count_cb(liId, total);
1977 openils.Util.show("acq-lit-update-copies-progress");
1978 fieldmapper.standardRequest(
1979 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1981 params: [openils.User.authtoken, copies],
1982 onresponse: function(r) {
1983 var res = openils.Util.readResponse(r);
1984 litUpdateCopiesProgress.update(res);
1986 oncomplete: function() {
1987 self.drawCopies(liId, true /* force_fetch */);
1988 openils.Util.hide("acq-lit-update-copies-progress");
1994 var dfa_list = this._virtDfaCountsAsList();
1995 if (dfa_list.length > 0) {
1996 fieldmapper.standardRequest(
1998 "open-ils.acq.distribution_formula.record_application"],
2001 "params": [openils.User.authtoken, dfa_list, liId],
2002 "onresponse": function(r) {
2003 var res = openils.Util.readResponse(r);
2004 if (res && res.length < dfa_list.length)
2005 alert(localeStrings.DFA_NOT_ALL);
2009 this.virtDfaCounts = {};
2013 this._updateCreatePoPrepayCheckbox = function(prepay) {
2014 var prepay = openils.Util.isTrue(prepay);
2015 this._prepayRequiredByVendor = prepay;
2016 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
2019 this._confirmPoPrepaySituation = function() {
2020 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
2021 if (want_prepay != this._prepayRequiredByVendor) {
2024 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
2025 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
2032 this.applySelectedLiAction = function(action) {
2036 case 'delete_selected':
2037 this._deleteLiList(self.getSelected());
2040 case 'create_order':
2041 this._loadPOSelect();
2042 acqLitPoCreateDialog.show();
2045 case 'save_picklist':
2046 acqLitSavePlDialog.show();
2049 case 'selector_ready':
2051 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
2052 acqLitChangeLiStateDialog.show();
2060 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
2067 case 'rollback_receive_po':
2068 this.rollbackPoReceive();
2071 case 'create_assets':
2072 this.showAssetCreator();
2075 case 'export_attr_list':
2076 this.chooseExportAttr();
2079 case 'batch_apply_funds':
2080 this.applyBatchLiFunds();
2083 case 'add_brief_record':
2085 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
2087 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
2091 case "cancel_lineitems":
2092 this.maybeCancelLineitems();
2095 case "change_claim_policy":
2096 var li_list = this.getSelected();
2097 this.claimPolicyPicker.attr("value", null);
2098 liClaimPolicyDialog.show();
2099 liClaimPolicySave.onClick = function() {
2100 self.changeClaimPolicy(
2102 self.claimPolicyPicker.attr("value"),
2106 self.setClaimPolicyControl(li);
2107 self.reconsiderClaimControl(li);
2110 liClaimPolicyDialog.hide();
2118 this.changeClaimPolicy = function(li_list, value, callback) {
2120 function(li) { li.claim_policy(value); }
2122 fieldmapper.standardRequest(
2123 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
2124 "params": [openils.User.authtoken, li_list],
2126 "oncomplete": function(r) {
2127 r = openils.Util.readResponse(r);
2128 if (callback) callback(r);
2134 this.showAssetCreator = function(onAssetsCreated) {
2135 if(!this.isPO) return;
2138 // first, let's see if this PO has any LI's that need to be merged/imported
2139 self.pcrud.search('jub', {purchase_order : this.isPO, eg_bib_id : null}, {
2141 oncomplete : function(r) {
2142 var resp = openils.Util.readResponse(r);
2143 if (resp && resp.length) {
2144 // PO has some non-linked jubs.
2146 self.show('asset-creator');
2147 if(!self.vlAgent.loaded)
2148 self.vlAgent.init();
2150 dojo.connect(assetCreatorButton, 'onClick',
2151 function() { self.createAssets(onAssetsCreated) });
2155 // all jubs linked, move on to asset creation
2156 self.createAssets(onAssetsCreated, true);
2162 this.createAssets = function(onAssetsCreated, noVl) {
2163 this.show('acq-lit-progress-numbers');
2165 var vlArgs = (noVl) ? {} : {vandelay : this.vlAgent.values()};
2166 fieldmapper.standardRequest(
2167 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
2169 params: [this.authtoken, this.isPO, vlArgs],
2170 onresponse: function(r) {
2171 var resp = openils.Util.readResponse(r);
2172 self._updateProgressNumbers(resp, !Boolean(onAssetsCreated), onAssetsCreated);
2178 this.maybeCancelLineitems = function() {
2179 openils.Util.show("acq-lit-cancel-reason", "inline");
2180 if (!acqLitCancelLineitemsButton._prepared) {
2181 var widget = new openils.widget.AutoFieldWidget({
2182 "fmField": "cancel_reason",
2184 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
2185 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2190 acqLitCancelLineitemsButton.onClick = function() {
2191 if (w.attr("value")) {
2192 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
2193 self._cancelLineitems(w.attr("value"));
2195 openils.Util.hide("acq-lit-cancel-reason");
2198 acqLitCancelLineitemsButton._prepared = true;
2204 this._cancelLineitems = function(reason) {
2205 var id_list = this.getSelected().map(function(o) { return o.id(); });
2206 fieldmapper.standardRequest(
2207 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
2208 "params": [openils.User.authtoken, id_list, reason],
2210 "onresponse": function(r) {
2211 if (r = openils.Util.readResponse(r)) {
2213 for (var id in r.li) {
2214 self.liCache[id].state(r.li[id].state);
2215 self.liCache[id].cancel_reason(
2216 r.li[id].cancel_reason
2218 self.updateLiState(self.liCache[id]);
2221 if (r.lid && self.copyCache) {
2222 for (var id in r.lid) {
2223 if (self.copyCache[id]) {
2224 self.copyCache[id].cancel_reason(
2225 r.lid[id].cancel_reason
2227 self.updateLidState(self.copyCache[id]);
2237 this.chooseExportAttr = function() {
2238 if (!acqLitExportAttrSelector._li_setup) {
2240 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
2242 "data": acqlimad.toStoreData(
2244 "acqlimad", {"code": li_exportable_attrs}
2249 acqLitExportAttrSelector.setValue();
2250 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
2251 acqLitExportAttrSelector._li_setup = true;
2253 openils.Util.show("acq-lit-export-attr-holder", "inline");
2256 this.exportAttrList = function() {
2257 var attr_def = acqLitExportAttrSelector.item;
2258 var li_list = this.getSelected();
2259 var value_list = li_list.map(
2261 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2262 attr_def.code, "lineitem_marc_attr_definition"
2265 ).filter(function(attr) { return Boolean(attr); });
2267 if (value_list.length > 0) {
2268 if (value_list.length < li_list.length) {
2270 dojo.string.substitute(
2271 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
2278 openils.XUL.contentToFileSaveDialog(
2279 value_list.join("\n"),
2280 localeStrings.EXPORT_SAVE_DIALOG_TITLE
2286 alert(dojo.string.substitute(
2287 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
2291 openils.Util.hide("acq-lit-export-attr-holder");
2294 this.printPO = function() {
2295 if(!this.isPO) return;
2296 progressDialog.show(true);
2297 fieldmapper.standardRequest(
2298 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
2300 params: [this.authtoken, this.isPO, 'html'],
2301 oncomplete: function(r) {
2302 progressDialog.hide();
2303 var evt = openils.Util.readResponse(r);
2304 if(evt && evt.template_output()) {
2305 openils.Util.printHtmlString(evt.template_output().data());
2313 this.receivePO = function() {
2314 if (!this.isPO) return;
2316 for (var id in this.liCache) {
2317 /* assumption: liCache reflects exactly the
2318 * set of LIs that belong to our PO */
2319 if (this.liCache[id].state() != "received" &&
2320 !this.checkLiAlerts(id)) return;
2323 this.show('acq-lit-progress-numbers');
2325 fieldmapper.standardRequest(
2326 ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
2328 params: [this.authtoken, this.isPO],
2329 onresponse : function(r) {
2330 var resp = openils.Util.readResponse(r);
2331 self._updateProgressNumbers(resp, true);
2337 this.issueReceive = function(obj, rollback) {
2338 /* (For now) there shall be no marking LI or LIDs (un)received
2339 * except from the actual "view PO" interface. */
2340 if (!this.isPO) return;
2343 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
2345 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
2347 progressDialog.show(true);
2348 fieldmapper.standardRequest(
2349 ["open-ils.acq", method], {
2351 "params": [this.authtoken, obj.id()],
2352 "onresponse": function(r) {
2353 if (r = openils.Util.readResponse(r)) {
2354 self.fetchClaimInfo(
2355 part == "lineitem" ? obj.id() : obj.lineitem(),
2357 function() { self.handleReceive(r); }
2359 progressDialog.hide();
2367 * Handles the responses from receive and rollback ML calls.
2369 this.handleReceive = function(resp) {
2372 for (var li_id in resp.li) {
2373 for (var key in resp.li[li_id])
2374 self.liCache[li_id][key](resp.li[li_id][key]);
2375 self.updateLiState(self.liCache[li_id]);
2379 if (typeof(self.poUpdateCallback) == "function")
2380 self.poUpdateCallback(resp.po);
2383 for (var lid_id in resp.lid) {
2384 for (var key in resp.lid[lid_id])
2385 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
2386 self.updateLidState(self.copyCache[lid_id]);
2392 this.rollbackPoReceive = function() {
2393 if(!this.isPO) return;
2394 if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
2395 this.show('acq-lit-progress-numbers');
2397 fieldmapper.standardRequest(
2398 ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
2400 params: [this.authtoken, this.isPO],
2401 onresponse : function(r) {
2402 var resp = openils.Util.readResponse(r);
2403 self._updateProgressNumbers(resp, true);
2409 this._updateProgressNumbers = function(resp, reloadOnComplete, onComplete) {
2410 this.vlAgent.handleResponse(resp,
2411 function(resp, res) {
2412 if(reloadOnComplete)
2413 location.href = location.href;
2415 onComplete(resp, res);
2421 this._createPO = function(fields) {
2422 var wantall = (fields.create_from == "all");
2424 /* If we're a picklist or purchase order already and the user wants
2425 * all lineitems, we might have pages' worth of lineitems haven't all
2426 * been loaded yet, so getSelected() won't find them. The server,
2427 * however, should know about all our lineitems, so let's ask the
2428 * server for a complete list.
2433 true, function(list) {
2434 self._createPOFromLineitems(fields, list);
2435 }, /* id_list */ true
2438 this._createPOFromLineitems(fields, this.getSelected(false, null, true /* id_list */));
2442 this._createPOFromLineitems = function(fields, selected) {
2443 if (selected.length == 0) return;
2446 var po = new fieldmapper.acqpo();
2447 po.provider(this.createPoProviderSelector.attr("value"));
2448 po.ordering_agency(this.createPoAgencySelector.attr("value"));
2449 po.prepayment_required(fields.prepayment_required[0] ? true : false);
2451 // if we're creating assets, delay the asset creation
2452 // until after the PO is created. This will allow us to
2453 // use showAssetCreator() directly.
2455 fieldmapper.standardRequest(
2456 ["open-ils.acq", "open-ils.acq.purchase_order.create"],
2459 openils.User.authtoken,
2460 po, {lineitems : selected}
2462 onresponse : function(r) {
2463 var resp = openils.Util.readResponse(r);
2464 if (resp.complete) {
2465 // self.isPO is needed for showAssetCreator();
2466 self.isPO = resp.purchase_order.id();
2467 var redir = oilsBasePath + "/acq/po/view/" + self.isPO;
2468 if (fields.create_assets[0]) {
2469 self.showAssetCreator(
2470 function() {location.href = redir}
2473 location.href = redir;
2482 this.batchFundWidget = null;
2484 this.applyBatchLiFunds = function() {
2486 var liIds = this.getSelected().map(function(li) { return li.id(); });
2487 if(liIds.length == 0) return; // warn?
2490 batchFundUpdateDialog.show();
2492 if(!this.batchFundWidget) {
2493 this.batchFundWidget = new openils.widget.AutoFieldWidget({
2495 selfReference : true,
2496 labelFormat : fundLabelFormat,
2497 searchFormat : fundSearchFormat,
2498 searchFilter : {"active": "t"},
2499 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
2500 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2501 dijitArgs : { "required": true, "labelType": "html" },
2504 this.batchFundWidget.build();
2507 dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
2508 dojo.connect(batchFundUpdateSubmit, 'onClick',
2511 // TODO: call .dry_run first to test thresholds
2512 fieldmapper.standardRequest(
2513 ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
2516 openils.User.authtoken,
2518 self.batchFundWidget.widget.attr('value')
2520 oncomplete : function(r) {
2521 var resp = openils.Util.readResponse(r);
2523 location.href = location.href;
2532 this._deleteLiList = function(list, idx) {
2533 if(idx == null) idx = 0;
2534 if(idx >= list.length) return;
2539 if (this.isPO && (li.state() == "on-order" || li.state() == "received")) {
2540 /* It makes little sense to delete a lineitem from a PO that has
2541 * already been marked 'on-order'. Especially if EDI is in use,
2542 * such a purchase order will probably have already been shipped
2543 * off to a vendor, and mucking with it at this point could leave
2544 * your data in a bad state that doesn't jive with reality.
2546 * I could see making this restriction even firmer.
2548 * I could also see adjusting the li state comparisons, extending
2549 * the comparison to the PO's state, and/or providing functions
2550 * that house the logic for comparing states in a single location.
2552 * Yes, this will be really annoying if you have selected a lot
2553 * of lineitems to cancel that have been ordered. You'll get a
2554 * confirm dialog for each one.
2557 if (!confirm(localeStrings.DEL_LI_FROM_PO)) {
2558 self._deleteLiList(list, ++idx); /* move on to next in list */
2563 fieldmapper.standardRequest(
2565 this.isPO ? 'open-ils.acq.purchase_order.lineitem.delete' : 'open-ils.acq.picklist.lineitem.delete'],
2567 params: [openils.User.authtoken, liId],
2568 oncomplete: function(r) {
2569 self.removeLineitem(liId);
2570 self._deleteLiList(list, ++idx);
2576 this.editOrderMarc = function(li) {
2578 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
2579 to true in about:config */
2581 if(!openils.XUL.enableXPConnect()) return;
2583 if(openils.XUL.isXUL()) {
2584 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
2586 win = window.open('/xul/server/cat/marcedit.xul');
2590 record : {marc : li.marc(), "rtype": "bre"},
2592 label: 'Save Record', // XXX I18N
2593 func: function(xmlString) {
2595 fieldmapper.standardRequest(
2596 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
2598 params: [openils.User.authtoken, li],
2599 oncomplete: function(r) {
2600 openils.Util.readResponse(r);
2602 self.drawInfo(li.id())
2608 'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
2609 'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
2613 this._savePl = function(values) {
2615 (values.which == 'all'),
2616 function(list) { self._savePlFromLineitems(values, list); }
2620 this._savePlFromLineitems = function(values, selected) {
2621 openils.Util.show("acq-lit-generic-progress");
2623 if(values.new_name) {
2624 openils.acq.Picklist.create(
2625 {name: values.new_name},
2631 oilsBasePath + "/acq/picklist/view/" + id;
2636 } else if(values.existing_pl) {
2637 // update lineitems to use an existing picklist
2639 values.existing_pl, selected, 0,
2642 oilsBasePath + "/acq/picklist/view/" +
2649 this._updateLiState = function(values, state) {
2650 progressDialog.show(true);
2652 (values.which == 'all'),
2654 self._updateLiStateFromLineitems(values, state, list);
2659 this._updateLiStateFromLineitems = function(values, state, selected) {
2660 if(!selected.length) return;
2661 dojo.forEach(selected, function(li) {li.state(state);});
2662 self._updateLiList(null, selected, 0,
2663 // TODO consider inline updates for efficiency
2664 function() { location.href = location.href }
2668 this._updateLiList = function(pl, list, idx, oncomplete) {
2669 if(idx >= list.length) return oncomplete();
2671 if(pl != null) li.picklist(pl);
2672 litGenericProgress.update({maximum: list.length, progress: idx});
2673 new openils.acq.Lineitem({lineitem:li}).update(
2675 self._updateLiList(pl, list, ++idx, oncomplete);
2680 this._loadPOSelect = function() {
2681 if (!this.createPoProviderSelector) {
2682 var widget = new openils.widget.AutoFieldWidget({
2683 "fmField": "provider",
2685 "searchFilter": {"active": "t"},
2686 "parentNode": dojo.byId("acq-lit-po-provider"),
2688 "onChange": function() {
2690 self._updateCreatePoPrepayCheckbox(
2691 this.item.prepayment_required()
2697 widget.build(function(w) { self.createPoProviderSelector = w; });
2700 if (!this.createPoAgencySelector) {
2701 var widget = new openils.widget.AutoFieldWidget({
2702 "fmField": "ordering_agency",
2704 "parentNode": dojo.byId("acq-lit-po-agency"),
2705 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2707 widget.build(function(w) { self.createPoAgencySelector = w; });
2711 this.showRealCopyEditUI = function(li) {
2716 this._fetchLineitem(li.id(),
2718 li = self.liCache[li.id()] = fullLi;
2722 id : li.lineitem_details().map(
2723 function(item) { return item.eg_copy_id() }
2727 oncomplete : function(r) {
2729 var r_list = openils.Util.readResponse( r );
2730 for (var i = 0; i < r_list.length; i++) {
2731 var copy = r_list[i];
2732 var volId = copy.call_number();
2733 var volume = self.volCache[volId];
2735 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2737 copy.call_number(volume);
2738 copyList.push(copy);
2741 xulG.volume_item_creator( { 'existing_copies' : copyList } );
2744 alert('error in oncomplete: ' + E);
2753 this.drawBibFinder = function(li) {
2756 var liWrapper = new openils.acq.Lineitem({lineitem:li});
2759 ['isbn', 'upc', 'issn', 'title', 'author'],
2761 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
2763 if(field == 'title' || field == 'author') {
2764 query += field +':' + val + ' ';
2766 query += 'identifier|' + field + ':' + val + ' ';
2773 oilsBasePath + '/acq/lineitem/findbib?query=' + escape(query),
2774 '', 'resizable,scrollbars=1');
2776 win.window.recordFound = function(bibId) {
2779 var attrs = li.attributes();
2780 li.attributes(null);
2781 li.eg_bib_id(bibId);
2783 fieldmapper.standardRequest(
2784 ["open-ils.acq", "open-ils.acq.lineitem.update"],
2786 "params": [openils.User.authtoken, li],
2788 "oncomplete": function(r) {
2789 if(openils.Util.readResponse(r)) {
2790 location.href = location.href;