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) {
1727 if (typeof(row) == "undefined") {
1728 row = dojo.query('tr[copy_id="' + copy.id() + '"]', this.copyTbody)[0];
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 // by default, hide all the actions
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);
1745 openils.Util.hide(cxl_reason_link);
1747 if (copy.id() > 0) { // real copies (LIDs)
1749 if (copy.cancel_reason()) {
1751 /* --------- cancelled -------------------------- */
1753 /* XXX the following may leak memory in a long lived table:
1754 * dijits may not get destroyed... not positive. revisit. */
1755 var holds_reason = dojo.create(
1757 "style": "border-bottom: 1px dashed #000;",
1758 "innerHTML": "Cancelled" /* XXX [sic] and i18n */
1759 }, cxl_reason_link, "only"
1763 "label": "<em>" + copy.cancel_reason().label() +
1764 "</em><br />" + copy.cancel_reason().description(),
1765 "connectId": [holds_reason]
1766 }, dojo.create("span", null, cxl_reason_link, "last")
1768 openils.Util.show(cxl_reason_link, "inline");
1770 } else if (copy.recv_time()) {
1772 /* --------- received -------------------------- */
1774 openils.Util.show(unrecv_link, "inline");
1775 unrecv_link.onclick = function() {
1776 if (confirm(localeStrings.UNRECEIVE_LID))
1777 self.issueReceive(copy, /* rollback */ true);
1780 } else if (this.liCache[copy.lineitem()].state() == 'on-order') {
1782 /* --------- on order -------------------------- */
1784 openils.Util.show(recv_link, 'inline');
1785 openils.Util.show(cxl_link, "inline");
1787 recv_link.onclick = function() {
1788 if (self.checkLiAlerts(copy.lineitem()))
1789 self.issueReceive(copy);
1792 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
1796 /* --------- pre-order copies -------------------------- */
1798 del_link.onclick = function() { self.deleteCopy(row) };
1799 openils.Util.show(del_link.parentNode);
1805 /* --------- virtual copies -------------------------- */
1807 del_link.onclick = function() { self.deleteCopy(row) };
1808 openils.Util.show(del_link.parentNode);
1812 this.cancelLid = function(lid_id) {
1813 lidCancelDialog._lid_id = lid_id;
1814 openils.Util.show(lidCancelDialog.domNode.parentNode);
1815 lidCancelDialog.show();
1816 if (!lidCancelDialog._prepared) {
1817 var widget = new openils.widget.AutoFieldWidget({
1818 "fmField": "cancel_reason",
1819 "fmClass": "acqlid",
1820 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
1821 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1826 acqLidCancelButton.onClick = function() {
1827 if (w.attr("value")) {
1828 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
1830 lidCancelDialog._lid_id,
1834 lidCancelDialog.hide();
1837 lidCancelDialog._prepared = true;
1843 this._cancelLid = function(lid_id, reason) {
1844 fieldmapper.standardRequest(
1845 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
1846 "params": [openils.User.authtoken, lid_id, reason],
1848 "onresponse": function(r) {
1849 if (r = openils.Util.readResponse(r)) {
1851 for (var id in r.lid) {
1852 /* actually this should only iterate once */
1853 self.copyCache[id].cancel_reason(
1854 r.lid[id].cancel_reason
1856 self.updateLidState(self.copyCache[id]);
1865 this._confirmAlert = function(li, lin) {
1867 dojo.string.substitute(
1868 localeStrings.CONFIRM_LI_ALERT, [
1869 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1870 "title", "lineitem_marc_attr_definition"
1872 lin.alert_text().code(),
1873 lin.alert_text().description() || "",
1880 this.checkLiAlerts = function(li_id) {
1881 var li = this.liCache[li_id];
1883 var alert_notes = li.lineitem_notes().filter(
1884 function(o) { return Boolean(o.alert_text()); }
1887 /* this is _intentionally_ not done in a call to forEach() ... */
1888 for (var i = 0; i < alert_notes.length; i++) {
1889 if (this.noteAcks[alert_notes[i].id()])
1891 else if (!this._confirmAlert(li, alert_notes[i]))
1894 this.noteAcks[alert_notes[i].id()] = true;
1900 this.deleteCopy = function(row) {
1901 var copy = this.copyCache[row.getAttribute('copy_id')];
1902 copy.isdeleted(true);
1904 delete this.copyCache[copy.id()];
1905 this.copyTbody.removeChild(row);
1908 this._virtDfaCountsAsList = function() {
1910 for (var key in this.virtDfaCounts) {
1911 for (var i = 0; i < this.virtDfaCounts[key]; i++)
1917 this.confirmBreachedCopyFunds = function(copies) {
1918 var stop = 0, warning = 0;
1922 var state = self.fundBalanceState[o.fund()];
1923 if (state[0] /* stop */)
1925 else if (state[1] /* warning */)
1932 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
1933 } else if (warning) {
1934 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
1939 this.saveCopyChanges = function(liId) {
1945 for(var id in this.copyCache) {
1946 var c = this.copyCache[id];
1947 if(!c.isdeleted()) total++;
1948 if(c.isnew() || c.ischanged() || c.isdeleted()) {
1949 if(c.id() < 0) c.id(null);
1955 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
1958 if (copies.length > 0) {
1959 if (!this.confirmBreachedCopyFunds(copies))
1962 if (typeof(this._copy_count_cb) == "function")
1963 this._copy_count_cb(liId, total);
1965 openils.Util.show("acq-lit-update-copies-progress");
1966 fieldmapper.standardRequest(
1967 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1969 params: [openils.User.authtoken, copies],
1970 onresponse: function(r) {
1971 var res = openils.Util.readResponse(r);
1972 litUpdateCopiesProgress.update(res);
1974 oncomplete: function() {
1975 self.drawCopies(liId, true /* force_fetch */);
1976 openils.Util.hide("acq-lit-update-copies-progress");
1982 var dfa_list = this._virtDfaCountsAsList();
1983 if (dfa_list.length > 0) {
1984 fieldmapper.standardRequest(
1986 "open-ils.acq.distribution_formula.record_application"],
1989 "params": [openils.User.authtoken, dfa_list, liId],
1990 "onresponse": function(r) {
1991 var res = openils.Util.readResponse(r);
1992 if (res && res.length < dfa_list.length)
1993 alert(localeStrings.DFA_NOT_ALL);
1997 this.virtDfaCounts = {};
2001 this._updateCreatePoPrepayCheckbox = function(prepay) {
2002 var prepay = openils.Util.isTrue(prepay);
2003 this._prepayRequiredByVendor = prepay;
2004 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
2007 this._confirmPoPrepaySituation = function() {
2008 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
2009 if (want_prepay != this._prepayRequiredByVendor) {
2012 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
2013 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
2020 this.applySelectedLiAction = function(action) {
2024 case 'delete_selected':
2025 this._deleteLiList(self.getSelected());
2028 case 'create_order':
2029 this._loadPOSelect();
2030 acqLitPoCreateDialog.show();
2033 case 'save_picklist':
2034 acqLitSavePlDialog.show();
2037 case 'selector_ready':
2039 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
2040 acqLitChangeLiStateDialog.show();
2048 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
2055 case 'rollback_receive_po':
2056 this.rollbackPoReceive();
2059 case 'create_assets':
2060 this.showAssetCreator();
2063 case 'export_attr_list':
2064 this.chooseExportAttr();
2067 case 'batch_apply_funds':
2068 this.applyBatchLiFunds();
2071 case 'add_brief_record':
2073 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
2075 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
2079 case "cancel_lineitems":
2080 this.maybeCancelLineitems();
2083 case "change_claim_policy":
2084 var li_list = this.getSelected();
2085 this.claimPolicyPicker.attr("value", null);
2086 liClaimPolicyDialog.show();
2087 liClaimPolicySave.onClick = function() {
2088 self.changeClaimPolicy(
2090 self.claimPolicyPicker.attr("value"),
2094 self.setClaimPolicyControl(li);
2095 self.reconsiderClaimControl(li);
2098 liClaimPolicyDialog.hide();
2106 this.changeClaimPolicy = function(li_list, value, callback) {
2108 function(li) { li.claim_policy(value); }
2110 fieldmapper.standardRequest(
2111 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
2112 "params": [openils.User.authtoken, li_list],
2114 "oncomplete": function(r) {
2115 r = openils.Util.readResponse(r);
2116 if (callback) callback(r);
2122 this.showAssetCreator = function(onAssetsCreated) {
2123 if(!this.isPO) return;
2126 // first, let's see if this PO has any LI's that need to be merged/imported
2127 self.pcrud.search('jub', {purchase_order : this.isPO, eg_bib_id : null}, {
2129 oncomplete : function(r) {
2130 var resp = openils.Util.readResponse(r);
2131 if (resp && resp.length) {
2132 // PO has some non-linked jubs.
2134 self.show('asset-creator');
2135 if(!self.vlAgent.loaded)
2136 self.vlAgent.init();
2138 dojo.connect(assetCreatorButton, 'onClick',
2139 function() { self.createAssets(onAssetsCreated) });
2143 // all jubs linked, move on to asset creation
2144 self.createAssets(onAssetsCreated, true);
2150 this.createAssets = function(onAssetsCreated, noVl) {
2151 this.show('acq-lit-progress-numbers');
2153 var vlArgs = (noVl) ? {} : {vandelay : this.vlAgent.values()};
2154 fieldmapper.standardRequest(
2155 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
2157 params: [this.authtoken, this.isPO, vlArgs],
2158 onresponse: function(r) {
2159 var resp = openils.Util.readResponse(r);
2160 self._updateProgressNumbers(resp, !Boolean(onAssetsCreated), onAssetsCreated);
2166 this.maybeCancelLineitems = function() {
2167 openils.Util.show("acq-lit-cancel-reason", "inline");
2168 if (!acqLitCancelLineitemsButton._prepared) {
2169 var widget = new openils.widget.AutoFieldWidget({
2170 "fmField": "cancel_reason",
2172 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
2173 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2178 acqLitCancelLineitemsButton.onClick = function() {
2179 if (w.attr("value")) {
2180 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
2181 self._cancelLineitems(w.attr("value"));
2183 openils.Util.hide("acq-lit-cancel-reason");
2186 acqLitCancelLineitemsButton._prepared = true;
2192 this._cancelLineitems = function(reason) {
2193 var id_list = this.getSelected().map(function(o) { return o.id(); });
2194 fieldmapper.standardRequest(
2195 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
2196 "params": [openils.User.authtoken, id_list, reason],
2198 "onresponse": function(r) {
2199 if (r = openils.Util.readResponse(r)) {
2201 for (var id in r.li) {
2202 self.liCache[id].state(r.li[id].state);
2203 self.liCache[id].cancel_reason(
2204 r.li[id].cancel_reason
2206 self.updateLiState(self.liCache[id]);
2209 if (r.lid && self.copyCache) {
2210 for (var id in r.lid) {
2211 if (self.copyCache[id]) {
2212 self.copyCache[id].cancel_reason(
2213 r.lid[id].cancel_reason
2215 self.updateLidState(self.copyCache[id]);
2225 this.chooseExportAttr = function() {
2226 if (!acqLitExportAttrSelector._li_setup) {
2228 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
2230 "data": acqlimad.toStoreData(
2232 "acqlimad", {"code": li_exportable_attrs}
2237 acqLitExportAttrSelector.setValue();
2238 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
2239 acqLitExportAttrSelector._li_setup = true;
2241 openils.Util.show("acq-lit-export-attr-holder", "inline");
2244 this.exportAttrList = function() {
2245 var attr_def = acqLitExportAttrSelector.item;
2246 var li_list = this.getSelected();
2247 var value_list = li_list.map(
2249 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2250 attr_def.code, "lineitem_marc_attr_definition"
2253 ).filter(function(attr) { return Boolean(attr); });
2255 if (value_list.length > 0) {
2256 if (value_list.length < li_list.length) {
2258 dojo.string.substitute(
2259 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
2266 openils.XUL.contentToFileSaveDialog(
2267 value_list.join("\n"),
2268 localeStrings.EXPORT_SAVE_DIALOG_TITLE
2274 alert(dojo.string.substitute(
2275 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
2279 openils.Util.hide("acq-lit-export-attr-holder");
2282 this.printPO = function() {
2283 if(!this.isPO) return;
2284 progressDialog.show(true);
2285 fieldmapper.standardRequest(
2286 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
2288 params: [this.authtoken, this.isPO, 'html'],
2289 oncomplete: function(r) {
2290 progressDialog.hide();
2291 var evt = openils.Util.readResponse(r);
2292 if(evt && evt.template_output()) {
2293 openils.Util.printHtmlString(evt.template_output().data());
2301 this.receivePO = function() {
2302 if (!this.isPO) return;
2304 for (var id in this.liCache) {
2305 /* assumption: liCache reflects exactly the
2306 * set of LIs that belong to our PO */
2307 if (this.liCache[id].state() != "received" &&
2308 !this.checkLiAlerts(id)) return;
2311 this.show('acq-lit-progress-numbers');
2313 fieldmapper.standardRequest(
2314 ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
2316 params: [this.authtoken, this.isPO],
2317 onresponse : function(r) {
2318 var resp = openils.Util.readResponse(r);
2319 self._updateProgressNumbers(resp, true);
2325 this.issueReceive = function(obj, rollback) {
2327 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
2329 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
2331 progressDialog.show(true);
2332 fieldmapper.standardRequest(
2333 ["open-ils.acq", method], {
2335 "params": [this.authtoken, obj.id()],
2336 "onresponse": function(r) {
2337 if (r = openils.Util.readResponse(r)) {
2338 self.fetchClaimInfo(
2339 part == "lineitem" ? obj.id() : obj.lineitem(),
2341 function() { self.handleReceive(r); }
2343 progressDialog.hide();
2351 * Handles the responses from receive and rollback ML calls.
2353 this.handleReceive = function(resp) {
2356 for (var li_id in resp.li) {
2357 for (var key in resp.li[li_id])
2358 self.liCache[li_id][key](resp.li[li_id][key]);
2359 self.updateLiState(self.liCache[li_id]);
2363 if (typeof(self.poUpdateCallback) == "function")
2364 self.poUpdateCallback(resp.po);
2367 for (var lid_id in resp.lid) {
2368 for (var key in resp.lid[lid_id])
2369 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
2370 self.updateLidState(self.copyCache[lid_id]);
2376 this.rollbackPoReceive = function() {
2377 if(!this.isPO) return;
2378 if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
2379 this.show('acq-lit-progress-numbers');
2381 fieldmapper.standardRequest(
2382 ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
2384 params: [this.authtoken, this.isPO],
2385 onresponse : function(r) {
2386 var resp = openils.Util.readResponse(r);
2387 self._updateProgressNumbers(resp, true);
2393 this._updateProgressNumbers = function(resp, reloadOnComplete, onComplete) {
2394 this.vlAgent.handleResponse(resp,
2395 function(resp, res) {
2396 if(reloadOnComplete)
2397 location.href = location.href;
2399 onComplete(resp, res);
2405 this._createPO = function(fields) {
2406 var wantall = (fields.create_from == "all");
2408 /* If we're a picklist or purchase order already and the user wants
2409 * all lineitems, we might have pages' worth of lineitems haven't all
2410 * been loaded yet, so getSelected() won't find them. The server,
2411 * however, should know about all our lineitems, so let's ask the
2412 * server for a complete list.
2417 true, function(list) {
2418 self._createPOFromLineitems(fields, list);
2419 }, /* id_list */ true
2422 this._createPOFromLineitems(fields, this.getSelected(false, null, true /* id_list */));
2426 this._createPOFromLineitems = function(fields, selected) {
2427 if (selected.length == 0) return;
2430 var po = new fieldmapper.acqpo();
2431 po.provider(this.createPoProviderSelector.attr("value"));
2432 po.ordering_agency(this.createPoAgencySelector.attr("value"));
2433 po.prepayment_required(fields.prepayment_required[0] ? true : false);
2435 // if we're creating assets, delay the asset creation
2436 // until after the PO is created. This will allow us to
2437 // use showAssetCreator() directly.
2439 fieldmapper.standardRequest(
2440 ["open-ils.acq", "open-ils.acq.purchase_order.create"],
2443 openils.User.authtoken,
2444 po, {lineitems : selected}
2446 onresponse : function(r) {
2447 var resp = openils.Util.readResponse(r);
2448 if (resp.complete) {
2449 // self.isPO is needed for showAssetCreator();
2450 self.isPO = resp.purchase_order.id();
2451 var redir = oilsBasePath + "/acq/po/view/" + self.isPO;
2452 if (fields.create_assets[0]) {
2453 self.showAssetCreator(
2454 function() {location.href = redir}
2457 location.href = redir;
2466 this.batchFundWidget = null;
2468 this.applyBatchLiFunds = function() {
2470 var liIds = this.getSelected().map(function(li) { return li.id(); });
2471 if(liIds.length == 0) return; // warn?
2474 batchFundUpdateDialog.show();
2476 if(!this.batchFundWidget) {
2477 this.batchFundWidget = new openils.widget.AutoFieldWidget({
2479 selfReference : true,
2480 labelFormat : fundLabelFormat,
2481 searchFormat : fundSearchFormat,
2482 searchFilter : {"active": "t"},
2483 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
2484 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2485 dijitArgs : { "required": true, "labelType": "html" },
2488 this.batchFundWidget.build();
2491 dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
2492 dojo.connect(batchFundUpdateSubmit, 'onClick',
2495 // TODO: call .dry_run first to test thresholds
2496 fieldmapper.standardRequest(
2497 ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
2500 openils.User.authtoken,
2502 self.batchFundWidget.widget.attr('value')
2504 oncomplete : function(r) {
2505 var resp = openils.Util.readResponse(r);
2507 location.href = location.href;
2516 this._deleteLiList = function(list, idx) {
2517 if(idx == null) idx = 0;
2518 if(idx >= list.length) return;
2523 if (this.isPO && (li.state() == "on-order" || li.state() == "received")) {
2524 /* It makes little sense to delete a lineitem from a PO that has
2525 * already been marked 'on-order'. Especially if EDI is in use,
2526 * such a purchase order will probably have already been shipped
2527 * off to a vendor, and mucking with it at this point could leave
2528 * your data in a bad state that doesn't jive with reality.
2530 * I could see making this restriction even firmer.
2532 * I could also see adjusting the li state comparisons, extending
2533 * the comparison to the PO's state, and/or providing functions
2534 * that house the logic for comparing states in a single location.
2536 * Yes, this will be really annoying if you have selected a lot
2537 * of lineitems to cancel that have been ordered. You'll get a
2538 * confirm dialog for each one.
2541 if (!confirm(localeStrings.DEL_LI_FROM_PO)) {
2542 self._deleteLiList(list, ++idx); /* move on to next in list */
2547 fieldmapper.standardRequest(
2549 this.isPO ? 'open-ils.acq.purchase_order.lineitem.delete' : 'open-ils.acq.picklist.lineitem.delete'],
2551 params: [openils.User.authtoken, liId],
2552 oncomplete: function(r) {
2553 self.removeLineitem(liId);
2554 self._deleteLiList(list, ++idx);
2560 this.editOrderMarc = function(li) {
2562 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
2563 to true in about:config */
2565 if(!openils.XUL.enableXPConnect()) return;
2567 if(openils.XUL.isXUL()) {
2568 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
2570 win = window.open('/xul/server/cat/marcedit.xul');
2574 record : {marc : li.marc(), "rtype": "bre"},
2576 label: 'Save Record', // XXX I18N
2577 func: function(xmlString) {
2579 fieldmapper.standardRequest(
2580 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
2582 params: [openils.User.authtoken, li],
2583 oncomplete: function(r) {
2584 openils.Util.readResponse(r);
2586 self.drawInfo(li.id())
2592 'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
2593 'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
2597 this._savePl = function(values) {
2599 (values.which == 'all'),
2600 function(list) { self._savePlFromLineitems(values, list); }
2604 this._savePlFromLineitems = function(values, selected) {
2605 openils.Util.show("acq-lit-generic-progress");
2607 if(values.new_name) {
2608 openils.acq.Picklist.create(
2609 {name: values.new_name},
2615 oilsBasePath + "/acq/picklist/view/" + id;
2620 } else if(values.existing_pl) {
2621 // update lineitems to use an existing picklist
2623 values.existing_pl, selected, 0,
2626 oilsBasePath + "/acq/picklist/view/" +
2633 this._updateLiState = function(values, state) {
2634 progressDialog.show(true);
2636 (values.which == 'all'),
2638 self._updateLiStateFromLineitems(values, state, list);
2643 this._updateLiStateFromLineitems = function(values, state, selected) {
2644 if(!selected.length) return;
2645 dojo.forEach(selected, function(li) {li.state(state);});
2646 self._updateLiList(null, selected, 0,
2647 // TODO consider inline updates for efficiency
2648 function() { location.href = location.href }
2652 this._updateLiList = function(pl, list, idx, oncomplete) {
2653 if(idx >= list.length) return oncomplete();
2655 if(pl != null) li.picklist(pl);
2656 litGenericProgress.update({maximum: list.length, progress: idx});
2657 new openils.acq.Lineitem({lineitem:li}).update(
2659 self._updateLiList(pl, list, ++idx, oncomplete);
2664 this._loadPOSelect = function() {
2665 if (!this.createPoProviderSelector) {
2666 var widget = new openils.widget.AutoFieldWidget({
2667 "fmField": "provider",
2669 "searchFilter": {"active": "t"},
2670 "parentNode": dojo.byId("acq-lit-po-provider"),
2672 "onChange": function() {
2674 self._updateCreatePoPrepayCheckbox(
2675 this.item.prepayment_required()
2681 widget.build(function(w) { self.createPoProviderSelector = w; });
2684 if (!this.createPoAgencySelector) {
2685 var widget = new openils.widget.AutoFieldWidget({
2686 "fmField": "ordering_agency",
2688 "parentNode": dojo.byId("acq-lit-po-agency"),
2689 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2691 widget.build(function(w) { self.createPoAgencySelector = w; });
2695 this.showRealCopyEditUI = function(li) {
2700 this._fetchLineitem(li.id(),
2702 li = self.liCache[li.id()] = fullLi;
2706 id : li.lineitem_details().map(
2707 function(item) { return item.eg_copy_id() }
2711 oncomplete : function(r) {
2713 var r_list = openils.Util.readResponse( r );
2714 for (var i = 0; i < r_list.length; i++) {
2715 var copy = r_list[i];
2716 var volId = copy.call_number();
2717 var volume = self.volCache[volId];
2719 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2721 copy.call_number(volume);
2722 copyList.push(copy);
2725 xulG.volume_item_creator( { 'existing_copies' : copyList } );
2728 alert('error in oncomplete: ' + E);
2737 this.drawBibFinder = function(li) {
2740 var liWrapper = new openils.acq.Lineitem({lineitem:li});
2743 ['isbn', 'upc', 'issn', 'title', 'author'],
2745 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
2747 if(field == 'title' || field == 'author') {
2748 query += field +':' + val + ' ';
2750 query += 'identifier|' + field + ':' + val + ' ';
2757 oilsBasePath + '/acq/lineitem/findbib?query=' + escape(query),
2758 '', 'resizable,scrollbars=1');
2760 win.window.recordFound = function(bibId) {
2763 var attrs = li.attributes();
2764 li.attributes(null);
2765 li.eg_bib_id(bibId);
2767 fieldmapper.standardRequest(
2768 ["open-ils.acq", "open-ils.acq.lineitem.update"],
2770 "params": [openils.User.authtoken, li],
2772 "oncomplete": function(r) {
2773 if(openils.Util.readResponse(r)) {
2774 location.href = location.href;