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 dojo.requireLocalization('openils.acq', 'acq');
19 var localeStrings = dojo.i18n.getLocalization('openils.acq', 'acq');
20 const XUL_OPAC_WRAPPER = 'chrome://open_ils_staff_client/content/cat/opac.xul';
21 var li_exportable_attrs = ["issn", "isbn", "upc"];
23 var fundLabelFormat = [
24 '<span class="fund_${0}">${1} (${2})</span>', 'id', 'code', 'year'
26 var fundSearchFormat = ['${0} (${1})', 'code', 'year'];
28 function nodeByName(name, context) {
29 return dojo.query('[name='+name+']', context)[0];
33 var liDetailBatchFields = ['fund', 'owning_lib', 'location', 'collection_code', 'circ_modifier', 'cn_label'];
34 var liDetailFields = liDetailBatchFields.concat(['barcode', 'note']);
36 "stop": "color: #c00; font-weight: bold;",
37 "warning": "color: #c93;"
40 function AcqLiTable() {
47 this.haveFundClass = {}
48 this.fundBalanceState = {};
49 this.realDfaCache = {};
50 this.virtDfaCounts = {};
53 this.claimEligibleLidByLi = {};
54 this.claimEligibleLid = {};
55 this.toggleState = false;
56 this.tbody = dojo.byId('acq-lit-tbody');
59 this.authtoken = openils.User.authtoken;
60 this.pcrud = new openils.PermaCrud();
61 this.rowTemplate = this.tbody.removeChild(dojo.byId('acq-lit-row'));
62 this.copyTbody = dojo.byId('acq-lit-li-details-tbody');
63 this.copyRow = this.copyTbody.removeChild(dojo.byId('acq-lit-li-details-row'));
64 this.copyBatchRow = dojo.byId('acq-lit-li-details-batch-row');
65 this.copyBatchWidgets = {};
66 this.liNotesTbody = dojo.byId('acq-lit-notes-tbody');
67 this.liNotesRow = this.liNotesTbody.removeChild(dojo.byId('acq-lit-notes-row'));
68 this.realCopiesTbody = dojo.byId('acq-lit-real-copies-tbody');
69 this.realCopiesRow = this.realCopiesTbody.removeChild(dojo.byId('acq-lit-real-copies-row'));
70 this._copy_fields_for_acqdf = ['owning_lib', 'location'];
71 this.skipInitialEligibilityCheck = false;
72 this.claimDialog = new ClaimDialogManager(
73 liClaimDialog, finalClaimDialog, this.claimEligibleLidByLi,
74 function(li) { /* callback that fires when claims are made */
75 self.fetchClaimInfo(li.id(), /* force update */ true);
79 dojo.byId("acq-lit-li-actions-selector").onchange = function() {
80 self.applySelectedLiAction(this.options[this.selectedIndex].value);
81 this.selectedIndex = 0;
84 acqLitCreatePoSubmit.onClick = function() {
85 if (self._confirmPoPrepaySituation()) {
86 acqLitPoCreateDialog.hide();
87 self._createPO(acqLitPoCreateDialog.getValues());
93 acqLitSavePlButton.onClick = function() {
94 acqLitSavePlDialog.hide();
95 self._savePl(acqLitSavePlDialog.getValues());
98 acqLitCancelLiStateButton.onClick = function() {
99 acqLitChangeLiStateDialog.hide();
101 acqLitSaveLiStateButton.onClick = function() {
102 acqLitChangeLiStateDialog.hide();
103 self._updateLiState(acqLitChangeLiStateDialog.getValues(), acqLitChangeLiStateDialog.attr('state'));
107 dojo.byId('acq-lit-select-toggle').onclick = function(){self.toggleSelect()};
108 dojo.byId('acq-lit-info-back-button').onclick = function(){self.show('list')};
109 dojo.byId('acq-lit-copies-back-button').onclick = function(){self.show('list')};
110 dojo.byId('acq-lit-notes-back-button').onclick = function(){self.show('list')};
111 dojo.byId('acq-lit-real-copies-back-button').onclick = function(){self.show('list')};
113 this.reset = function(keep_selectors) {
114 while(self.tbody.childNodes[0])
115 self.tbody.removeChild(self.tbody.childNodes[0]);
123 this.setNext = function(handler) {
124 var link = dojo.byId('acq-lit-next');
126 dojo.style(link, 'visibility', 'visible');
127 link.onclick = handler;
129 dojo.style(link, 'visibility', 'hidden');
133 this.setPrev = function(handler) {
134 var link = dojo.byId('acq-lit-prev');
136 dojo.style(link, 'visibility', 'visible');
137 link.onclick = handler;
139 dojo.style(link, 'visibility', 'hidden');
143 this.show = function(div) {
144 openils.Util.hide('acq-lit-table-div');
145 openils.Util.hide('acq-lit-info-div');
146 openils.Util.hide('acq-lit-li-details');
147 openils.Util.hide('acq-lit-notes-div');
148 openils.Util.hide('acq-lit-real-copies-div');
151 openils.Util.show('acq-lit-table-div');
154 openils.Util.show('acq-lit-info-div');
157 openils.Util.show('acq-lit-li-details');
160 openils.Util.show('acq-lit-real-copies-div');
163 openils.Util.show('acq-lit-notes-div');
167 openils.Util.show(div);
171 this.hide = function() {
175 this.toggleSelect = function() {
177 dojo.forEach(self.selectors, function(i){i.checked = false});
179 dojo.forEach(self.selectors, function(i){i.checked = true});
180 self.toggleState = !self.toggleState;
184 /** @param all If true, assume all are selected */
185 this.getSelected = function(all) {
187 var indices = {}; /* use to uniqify. needed in paging situations. */
188 dojo.forEach(self.selectors,
191 indices[i.parentNode.parentNode.getAttribute('li')] = true;
194 return openils.Util.objectProperties(indices).map(
195 function(liId) { return self.liCache[liId]; }
199 this.setRowAttr = function(td, liWrapper, field, type) {
200 var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
201 td.appendChild(document.createTextNode(val));
204 this.setClaimPolicyControl = function(li, row) {
205 if (!self.claimPolicyPicker) {
206 self.claimPolicyPicker = true; /* prevents a race condition */
207 new openils.widget.AutoFieldWidget({
208 "parentNode": "acq-lit-li-claim-policy",
210 "selfReference": true,
211 "dijitArgs": {"required": true}
212 }).build(function(w) { self.claimPolicyPicker = w; });
215 if (!row) row = this._findLiRow(li);
217 var actViewPolicy = nodeByName("action_view_claim_policy", row);
218 if (li.claim_policy())
219 actViewPolicy.innerHTML = localeStrings.CHANGE_CLAIM_POLICY;
221 if (!actViewPolicy.onclick) {
222 actViewPolicy.onclick = function() {
223 if (li.claim_policy())
224 self.claimPolicyPicker.attr("value", li.claim_policy());
225 liClaimPolicyDialog.show();
226 liClaimPolicySave.onClick = function() {
227 self.changeClaimPolicy(
228 [li], self.claimPolicyPicker.attr("value"),
230 self.setClaimPolicyControl(li, row);
231 liClaimPolicyDialog.hide();
239 this.fetchClaimInfo = function(liId, force, callback, row) {
241 liId, function(full) {
242 self.liCache[full.id()] = full;
243 self.checkClaimEligibility(full, callback, row);
249 * Inserts a single lineitem into the growing table of lineitems
250 * @param {Object} li The lineitem object to insert
252 this.addLineitem = function(li, skip_final_placement) {
253 this.liCache[li.id()] = li;
255 // sort the lineitem notes on edit_time
256 if(!li.lineitem_notes()) li.lineitem_notes([]);
258 var liWrapper = new openils.acq.Lineitem({lineitem:li});
259 var row = self.rowTemplate.cloneNode(true);
260 row.setAttribute('li', li.id());
261 var tds = dojo.query('[attr]', row);
262 dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
263 dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
266 liWrapper.findAttr("isbn", "lineitem_marc_attr_definition") ||
267 liWrapper.findAttr("upc", "lineitem_marc_attr_definition");
269 // XXX media prefix for added content
271 nodeByName("jacket", row).setAttribute(
272 "src", "/opac/extras/ac/jacket/small/" + identifier
276 nodeByName("liid", row).innerHTML += li.id();
279 openils.Util.show(nodeByName('catalog', row), 'inline');
280 nodeByName("catalog_link", row).onclick = this.generateMakeRecTab(li.eg_bib_id());
282 openils.Util.show(nodeByName('link_to_catalog', row), 'inline');
283 nodeByName("link_to_catalog_link", row).onclick = function() { self.drawBibFinder(li) };
286 nodeByName("worksheet_link", row).href =
287 oilsBasePath + "/acq/lineitem/worksheet/" + li.id();
289 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
290 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
291 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
293 if (!this.skipInitialEligibilityCheck)
294 this.fetchClaimInfo(li.id(), false, null, row);
296 this.updateLiNotesCount(li, row);
298 this.setClaimPolicyControl(li, row);
300 // show which PO this lineitem is a member of
301 if(li.purchase_order() && !this.isPO) {
303 this.poCache[li.purchase_order()] =
304 this.poCache[li.purchase_order()] ||
305 fieldmapper.standardRequest(
306 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
308 this.authtoken, li.purchase_order(), {
309 "flesh_price_summary": true,
310 "flesh_lineitem_count": true
313 if(po && !this.isMeta) {
314 openils.Util.show(nodeByName('po', row), 'inline');
315 var link = nodeByName('po_link', row);
316 link.setAttribute('href', oilsBasePath + '/acq/po/view/' + li.purchase_order());
317 link.innerHTML += po.name();
321 // show which picklist this lineitem is a member of
322 if(li.picklist() && (this.isPO || this.isMeta || this.isUni)) {
324 this.plCache[li.picklist()] =
325 this.plCache[li.picklist()] ||
326 fieldmapper.standardRequest(
327 ['open-ils.acq', 'open-ils.acq.picklist.retrieve.authoritative'],
328 {params: [this.authtoken, li.picklist()]});
330 if (pl.name() == "") {
331 openils.Util.show(nodeByName("bib_origin", row), "inline");
335 openils.Util.show(nodeByName('pl', row), 'inline');
336 var link = nodeByName('pl_link', row);
337 link.setAttribute('href', oilsBasePath + '/acq/picklist/view/' + li.picklist());
338 link.innerHTML += pl.name();
343 var countNode = nodeByName('count', row);
344 var count = li.item_count() || 0;
345 if (typeof(this._copy_count_cb) == "function") {
346 this._copy_count_cb(li.id(), count);
348 countNode.innerHTML = count;
349 countNode.id = 'acq-lit-copy-count-label-' + li.id();
352 var priceInput = dojo.query('[name=price]', row)[0];
353 priceInput.value = li.estimated_unit_price() || '';
354 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
356 // show either "mark received" or "unreceive" as appropriate
357 this.updateLiState(li, row);
359 if (!skip_final_placement) {
360 self.tbody.appendChild(row);
361 self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
367 this._liCountClaims = function(li) {
369 for (var i = 0; i < li.lineitem_details().length; i++)
370 total += li.lineitem_details()[i].claims().length;
374 this._findLiRow = function(li) {
375 return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
378 this.reconsiderClaimControl = function(li, row) {
379 if (!row) row = this._findLiRow(li);
380 var option = nodeByName("action_manage_claims", row);
381 var eligible = this.claimEligibleLidByLi[li.id()].length;
382 var count = this._liCountClaims(li);
384 option.disabled = !(count || eligible);
386 dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
387 option.onclick = function() { self.claimDialog.show(li); };
390 this.clearEligibility = function(li) {
391 this.claimEligibleLidByLi[li.id()] = [];
393 if (li.lineitem_details()) {
394 li.lineitem_details().forEach(
395 function(lid) { delete self.claimEligibleLid[lid.id()]; }
399 if (this.copyCache) {
401 for (var k in this.copyCache) {
402 if (this.copyCache[k].lineitem() == li.id())
406 function(k) { delete self.claimEligibleLid[k]; }
411 this.checkClaimEligibility = function(li, callback, row) {
412 /* Assume always eligible, i.e. from this interface we don't care about
413 * claim eligibility any more. this is where the user would force a
415 this.clearEligibility(li);
416 this.claimEligibleLidByLi[li.id()] = li.lineitem_details().map(
417 function(lid) { return lid.id(); }
419 li.lineitem_details().forEach(
420 function(lid) { self.claimEligibleLid[lid.id()] = true; }
422 this.reconsiderClaimControl(li, row);
423 if (callback) callback();
425 this.clearEligibility(li);
426 fieldmapper.standardRequest(
427 ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
428 "params": [openils.User.authtoken, {"lineitem": li.id()}],
430 "onresponse": function(r) {
431 if (r = openils.Util.readResponse(r)) {
432 self.claimEligibleLidByLi[li.id()].push(
435 self.claimEligibleLid[r.lineitem_detail()] = true;
438 "oncomplete": function() {
439 self.reconsiderClaimControl(li, row);
440 if (typeof(callback) == "function")
448 this.updateLiNotesCount = function(li, row) {
449 if (!row) row = this._findLiRow(li);
451 var has_notes = (li.lineitem_notes().filter(
452 function(o) { return Boolean (o.alert_text()); }
455 /* U+2691 is the code point for a filled-in flag character */
456 nodeByName("notes_alert_flag", row).innerHTML =
457 has_notes ? "⚑" : "";
458 nodeByName("noteslink", row).style.fontStyle =
459 has_notes ? "italic" : "normal";
460 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
463 /* XXX NOT related to _updateLiState(). rethink */
464 this.updateLiState = function(li, row) {
465 if (!row) row = this._findLiRow(li);
467 var actReceive = nodeByName("action_mark_recv", row);
468 var actUnRecv = nodeByName("action_mark_unrecv", row);
469 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
470 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
472 var actNewInvoice = nodeByName('action_new_invoice', row);
473 var actLinkInvoice = nodeByName('action_link_invoice', row);
474 var actViewInvoice = nodeByName('action_view_invoice', row);
476 nodeByName('action_view_history', row).onclick =
477 function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
479 var state_cell = nodeByName("li_state", row);
481 if (li.state() == "cancelled") {
482 if (typeof li.cancel_reason() == "object") {
483 var holds_state = dojo.create(
485 "style": "border-bottom: 1px dashed #000;",
486 "innerHTML": li.state()
487 }, state_cell, "only"
491 "label": "<em>" + li.cancel_reason().label() +
492 "</em><br />" + li.cancel_reason().description(),
493 "connectId": [holds_state]
494 }, dojo.create("span", null, state_cell, "last")
497 state_cell.innerHTML = li.state(); // TODO i18n state labels
500 state_cell.innerHTML = li.state(); // TODO i18n state labels
504 /* handle row coloring for based on LI state */
505 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
506 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
508 /* handle links that appear/disappear based on whether LI is received */
512 actNewInvoice.onclick = function() {
513 location.href = oilsBasePath + '/acq/invoice/view?create=1&attach_li=' + li.id();
514 nodeByName("action_none", row).selected = true;
516 actLinkInvoice.onclick = function() {
517 if (!self.invoiceLinkDialogManager) {
518 self.invoiceLinkDialogManager =
519 new InvoiceLinkDialogManager("li");
521 self.invoiceLinkDialogManager.target = li;
522 acqLitLinkInvoiceDialog.show();
523 nodeByName("action_none", row).selected = true;
525 actViewInvoice.onclick = function() {
526 location.href = oilsBasePath +
527 "/acq/search/unified?so=" +
528 base64Encode({"jub":[{"id": li.id()}]}) +
530 nodeByName("action_none", row).selected = true;
533 actNewInvoice.disabled = false;
534 actLinkInvoice.disabled = false;
535 actViewInvoice.disabled = false;
539 actReceive.disabled = false;
540 actReceive.onclick = function() {
541 if (self.checkLiAlerts(li.id()))
542 self.issueReceive(li);
543 nodeByName("action_none", row).selected = true;
548 actUnRecv.disabled = false;
549 actUnRecv.onclick = function() {
550 if (confirm(localeStrings.UNRECEIVE_LI))
551 self.issueReceive(li, /* rollback */ true);
552 nodeByName("action_none", row).selected = true;
554 // TODO we should allow editing before receipt, in which case the
555 // test should be "if 1 or more real (acp) copies exist
556 actUpdateBarcodes.disabled = false;
557 actUpdateBarcodes.onclick = function() {
558 self.showRealCopyEditUI(li);
559 nodeByName("action_none", row).selected = true;
561 actHoldingsMaint.disabled = false;
562 actHoldingsMaint.onclick = self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
570 this._setAlertStore = function() {
571 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
573 "data": acqliat.toStoreData(
575 "acqliat", {"id": {"!=": null}}
580 acqLitAlertAlertText.setValue(); /* make the store "live" */
581 acqLitAlertAlertText._store_ready = true;
585 * Draws and shows the lineitem notes pane
587 this.drawLiNotes = function(li) {
590 if (!acqLitAlertAlertText._store_ready)
591 this._setAlertStore();
594 li.lineitem_notes().sort(
596 if(a.edit_time() < b.edit_time()) return 1;
602 while(this.liNotesTbody.childNodes[0])
603 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
606 acqLitCreateNoteSubmit.onClick = function() {
607 var value = acqLitCreateNoteText.attr('value');
609 var note = new fieldmapper.acqlin();
612 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
615 note.lineitem(li.id());
617 self.updateLiNotes(li, note);
618 acqLitCreateNoteVendorPublic.attr("checked", false);
619 acqLitCreateNoteText.attr("value", "");
622 acqLitCreateAlertSubmit.onClick = function() {
623 if (!acqLitAlertAlertText.item) {
624 alert(localeStrings.ALERT_UNSELECTED);
628 var alert_text = new fieldmapper.acqliat().fromStoreItem(
629 acqLitAlertAlertText.item
631 var value = acqLitAlertNoteValue.attr("value") || "";
633 var note = new fieldmapper.acqlin();
635 note.lineitem(li.id());
637 note.alert_text(alert_text);
639 self.updateLiNotes(li, note);
642 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
646 * Draws a single lineitem note in the notes pane
648 this.addLiNote = function(li, note) {
649 if(note.isdeleted()) return;
651 var row = self.liNotesRow.cloneNode(true);
652 nodeByName("value", row).innerHTML = note.value();
653 var alert_node = nodeByName("alert_code", row);
654 if (note.alert_text()) {
655 alert_node.innerHTML = note.alert_text().code();
656 if (note.alert_text().description()) {
659 "connectId": [alert_node],
660 "label": note.alert_text().description()
661 }, dojo.create("span", null, alert_node, "after")
666 if (openils.Util.isTrue(note.vendor_public()))
667 nodeByName("vendor_public", row).innerHTML =
668 localeStrings.VENDOR_PUBLIC;
670 nodeByName("delete", row).onclick = function() {
671 note.isdeleted(true);
672 self.liNotesTbody.removeChild(row);
673 self.updateLiNotes(li);
676 if(note.edit_time()) {
677 nodeByName("edit_time", row).innerHTML =
678 dojo.date.locale.format(
679 dojo.date.stamp.fromISOString(note.edit_time()),
680 {formatLength:'short'});
683 self.liNotesTbody.appendChild(row);
687 * Updates any new/changed/deleted notes on the server
689 this.updateLiNotes = function(li, newNote) {
695 notes = li.lineitem_notes().filter(
697 if(note.ischanged() || note.isnew() || note.isdeleted())
703 if(notes.length == 0) return;
704 progressDialog.show();
706 fieldmapper.standardRequest(
707 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
709 params : [this.authtoken, notes],
710 onresponse : function(r) {
711 var resp = openils.Util.readResponse(r);
716 // remove the old changed notes
718 dojo.forEach(li.lineitem_notes(),
720 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
724 li.lineitem_notes(list);
727 progressDialog.hide();
728 self.updateLiNotesCount(li);
729 self.drawLiNotes(li);
733 progressDialog.update(resp);
734 var newnote = resp.note;
736 if(!newnote.isdeleted()) {
737 newnote.isnew(false);
738 newnote.ischanged(false);
739 li.lineitem_notes().push(newnote);
746 this.updateLiPrice = function(input, li) {
748 var price = input.value;
749 if(Number(price) == Number(li.estimated_unit_price())) return;
751 fieldmapper.standardRequest(
752 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
753 { async : false, // redundant w/ timeout
755 params : [this.authtoken, li.id(), price],
756 oncomplete : function(r) {
757 openils.Util.readResponse(r);
758 li.estimated_unit_price(price); // update local copy
764 this.removeLineitem = function(liId) {
765 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
766 delete this.liCache[liId];
767 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
770 this.drawInfo = function(liId) {
771 if (!this._isRelatedViewer) {
772 var d = dojo.byId("acq-lit-info-related");
773 if (!this.relCache[liId]) {
774 fieldmapper.standardRequest(
777 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
780 "params": [openils.User.authtoken, liId],
781 "onresponse": function(r) {
782 self.relCache[liId] = openils.Util.readResponse(r);
783 nodeByName("related_number", d).innerHTML =
786 self.relCache[liId] >1 ? "show" : "hide"
792 nodeByName("related_number", d).innerHTML = this.relCache[liId];
793 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
798 openils.acq.Lineitem.fetchAttrDefs(
800 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
805 this._fetchLineitem = function(liId, handler, force) {
807 var li = this.liCache[liId];
808 if(li && li.marc() && li.lineitem_details() && !force)
811 fieldmapper.standardRequest(
812 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
815 params: [self.authtoken, liId, {
817 flesh_cancel_reason: true,
818 flesh_li_details: true,
820 flesh_fund_debit: true }],
822 oncomplete: function(r) {
823 var li = openils.Util.readResponse(r);
824 self.liCache[liId] = li;
831 this._drawInfo = function(li) {
833 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
836 openils.Util.hide('acq-lit-marc-order-record-label');
837 openils.Util.hide(acqLitEditOrderMarc.domNode);
838 openils.Util.show('acq-lit-marc-real-record-label');
840 openils.Util.show('acq-lit-marc-order-record-label');
841 openils.Util.show(acqLitEditOrderMarc.domNode);
842 openils.Util.hide('acq-lit-marc-real-record-label');
845 this.drawMarcHTML(li);
846 this.infoTbody = dojo.byId('acq-lit-info-tbody');
849 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
850 while(this.infoTbody.childNodes[0])
851 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
853 for(var i = 0; i < li.attributes().length; i++) {
854 var attr = li.attributes()[i];
855 var row = this.infoRow.cloneNode(true);
857 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
858 var name = openils.acq.Lineitem.attrDefs[type].filter(
860 return (a.code() == attr.attr_name());
862 ).pop().description();
864 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
865 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
866 this.infoTbody.appendChild(row);
869 if (!this._isRelatedViewer) {
870 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
871 oilsBasePath + "/acq/lineitem/related/" + li.id();
876 this.generateMakeRecTab = function(bib_id,default_view, row) {
880 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
883 show_nav_buttons : true,
884 show_print_button : true,
885 opac_url : xulG.url_prefix(xulG.urls.opac_rdetail + '?r=' + bib_id),
886 default_view : default_view
890 if(row) nodeByName("action_none", row).selected = true;
894 this.drawMarcHTML = function(li) {
895 var params = [null, true, li.marc()];
897 params = [li.eg_bib_id(), true];
899 fieldmapper.standardRequest(
900 ['open-ils.search', 'open-ils.search.biblio.record.html'],
903 oncomplete: function(r) {
904 dojo.byId('acq-lit-marc-div').innerHTML =
905 openils.Util.readResponse(r);
911 this.drawCopies = function(liId, force_fetch) {
912 if (typeof force_fetch == "undefined")
918 this.copyWidgetCache = {};
919 this.oldCopyWidgetCache = {};
920 this.virtDfaCounts = {};
921 this.realDfaCache = {};
924 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
925 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
926 acqLitCopyCountInput.attr('value', '0');
928 while(this.copyTbody.childNodes[0])
929 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
931 this._drawBatchCopyWidgets();
933 this._drawDistribApplied(liId);
935 this._fetchDistribFormulas(
937 openils.acq.Lineitem.fetchAttrDefs(
939 self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch);
946 this._saveDistribAppliedTemplates = function() {
947 if (!this._appliedDistribTemplate) {
948 this._appliedDistribTemplate =
949 dojo.byId("acq-lit-distrib-applied-tbody").
950 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
951 dojo.attr(this._appliedDistribTemplate, "id");
955 this._drawDistribApplied = function(liId) {
956 /* Build this table while hidden to prevent rendering artifacts */
957 openils.Util.hide("acq-lit-distrib-applied-tbody");
959 this._saveDistribAppliedTemplates();
961 /* Remove any rows in the table from previous populations */
962 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
963 forEach(dojo.destroy);
965 /* Unregister all dijits previously created (for some reason this isn't
966 * covered by the above destroy calls). */
967 dijit.registry.forEach(
968 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
971 /* Populate the table with our liId */
973 fieldmapper.standardRequest(
975 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
978 "params": [self.authtoken, liId],
979 "onresponse": function(r) {
980 var dfa = openils.Util.readResponse(r);
983 self.realDfaCache[dfa.id()] = dfa;
984 self._drawDistribAppliedUnit(dfa);
987 "oncomplete": function() {
988 /* Reveal built table */
991 "acq-lit-distrib-applied-tbody", "table-row-group"
999 this._drawDistribAppliedUnit = function(dfa) {
1000 var new_row = false;
1001 var row = dojo.query(
1002 'tr[formula="' + dfa.formula().id() + '"]',
1003 "acq-lit-distrib-applied-tbody"
1008 row = dojo.clone(this._appliedDistribTemplate);
1009 dojo.attr(row, "formula", dfa.formula().id());
1010 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
1013 var td = dojo.query("td", row)[0];
1015 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1016 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1019 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1021 new dijit.form.Button(
1023 "onClick": function() {
1024 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1025 self.deleteDfa(dfa);
1028 /* XXX I /cannot/ make the following work in as a CSS class
1029 * for some reason. So frustrating... */
1030 "style": function(id) {
1032 "font-weight: bold; color: #c00;" :
1034 }(dfa.id()) + "margin: 0 6px;display: inline;"
1035 }, "dfa-button-" + dfa.id()
1039 "connectId": ["dfa-button-" + dfa.id()],
1040 "label": dojo.string.substitute(
1041 localeStrings.DFA_TIP, dfa.id() > 0 ? [
1042 openils.User.formalName(dfa.creator()),
1043 dojo.date.locale.format(
1044 dojo.date.stamp.fromISOString(dfa.create_time()),
1045 {"formatLength":"short"}
1047 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
1049 }, "dfa-tip-" + dfa.id()
1053 this.deleteDfa = function(dfa) {
1054 if (dfa.id() > 0) { /* real */
1055 this.pcrud.eliminate(
1058 "oncomplete": function() {
1059 self._removeDistribApplied(dfa.id());
1060 delete self.realDfaCache[dfa.id()];
1064 } else { /* virtual */
1065 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
1066 this.virtDfaCounts[dfa.formula().id()] = 0;
1067 /* hasn't been saved yet, so no need to do anything server side */
1068 this._removeDistribApplied(dfa.id());
1073 this._removeDistribApplied = function(dfaId) {
1074 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
1075 dijit.registry.forEach(
1076 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
1078 this._removeDistribAppliedEmptyRows();
1081 this._removeAllDistribAppliedVirtual = function() {
1082 /* Unregister dijits */
1083 dijit.registry.forEach(
1084 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
1086 this._removeDistribAppliedEmptyRows();
1089 this._removeDistribAppliedEmptyRows = function() {
1090 /* Remove any rows with no DFA at all */
1091 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
1093 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
1099 * Insert a new row into the distribution formula selection form
1101 this._addDistribFormulaRow = function() {
1104 if (!self.distribForms) {
1105 // no formulas, hide the form
1106 openils.Util.hide('acq-lit-distrib-formula-tbody');
1110 if(!this.distribFormulaTemplate)
1111 this.distribFormulaTemplate =
1112 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
1114 var row = this.distribFormulaTemplate.cloneNode(true);
1115 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
1117 this.dfSelector = new dijit.form.FilteringSelect(
1118 {"labelAttr": "dynLabel", "labelType": "html"},
1119 nodeByName("selector", row)
1121 this._updateFormulaStore();
1122 this.dfSelector.fetchProperties =
1123 {"sort": [{"attribute": "use_count", "descending": true}]};
1125 var apply = new dijit.form.Button(
1126 {"label": localeStrings.APPLY},
1127 nodeByName('set_button', row)
1130 var reset = new dijit.form.Button(
1131 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
1132 nodeByName("reset_button", row)
1135 dojo.connect(apply, 'onClick',
1137 var form_id = self.dfSelector.attr("value");
1138 if(!form_id) return;
1139 self._applyDistribFormula(form_id);
1140 reset.attr("disabled", false);
1144 dojo.connect(reset, 'onClick',
1146 self.restoreCopyFieldsBeforeDF();
1147 self.virtDfaCounts = {};
1148 self.virtDfaId = -1;
1150 self._updateFormulaStore();
1151 self._removeAllDistribAppliedVirtual();
1152 reset.attr("disabled", "true");
1159 * Applies a distrib formula to the current set of copies
1161 this._applyDistribFormula = function(formula) {
1162 if(!formula) return;
1164 formula = this.distribForms.filter(
1165 function(form) { return form.id() == formula; }
1168 var copyRows = dojo.query('tr', self.copyTbody);
1170 if (this.dfeOffset >= copyRows.length) {
1171 alert(localeStrings.OUT_OF_COPIES);
1175 var entries_applied = 0;
1177 var rowIndex = this.dfeOffset;
1178 rowIndex < copyRows.length;
1182 var row = copyRows[rowIndex];
1183 var copy_id = row.getAttribute('copy_id');
1184 var copyWidgets = this.copyWidgetCache[copy_id];
1185 var entryIndex = this.dfeOffset;
1188 // find the correct entry for the current row
1189 dojo.forEach(formula.entries(),
1192 entryIndex += e.item_count();
1193 if(entryIndex > rowIndex)
1201 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
1202 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
1205 this.saveCopyFieldsBeforeDF(copy_id);
1206 this._copy_fields_for_acqdf.forEach(
1208 if(entry[field]()) {
1209 copyWidgets[field].attr('value', (entry[field]()));
1216 if (entries_applied) {
1217 this.virtDfaCounts[formula.id()] =
1218 ++(this.virtDfaCounts[formula.id()]) || 1;
1219 this._updateFormulaStore();
1220 this._drawDistribAppliedUnit(
1222 var dfa = new acqdfa();
1223 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
1226 this.dfeOffset += entries_applied;
1231 * This function updates the DF store for the dropdown so that use_counts
1232 * can reflect DF applications from this session before they're saved
1235 this._updateFormulaStore = function() {
1236 this.dfSelector.store = new dojo.data.ItemFileReadStore(
1238 "data": self._labelFormulasWithCounts(
1239 acqdf.toStoreData(self.distribForms)
1245 this.saveCopyFieldsBeforeDF = function(copy_id) {
1247 if (!this.oldCopyWidgetCache[copy_id]) {
1248 var copyWidgets = this.copyWidgetCache[copy_id];
1250 this.oldCopyWidgetCache[copy_id] = {};
1251 this._copy_fields_for_acqdf.forEach(
1253 self.oldCopyWidgetCache[copy_id][f] =
1254 copyWidgets[f].attr("value");
1260 this.restoreCopyFieldsBeforeDF = function() {
1262 for (var copy_id in this.oldCopyWidgetCache) {
1263 this._copy_fields_for_acqdf.forEach(
1265 self.copyWidgetCache[copy_id][f].attr(
1266 "value", self.oldCopyWidgetCache[copy_id][f]
1273 this._labelFormulasWithCounts = function(store_data) {
1274 for (var key in store_data.items) {
1275 var obj = store_data.items[key];
1276 obj.use_count = Number(obj.use_count); /* needed for sorting */
1278 if (this.virtDfaCounts[obj.id])
1279 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
1281 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
1282 obj.use_count + "]</span> " + obj.name;
1288 * This method formerly would not refetch the DF formulas if they'd been
1289 * loaded already, but now it always re-fetches, since use_count changes.
1291 /** TODO: port distrib-formula selector to autofieldwidget+pcrud/dojo store */
1292 this._fetchDistribFormulas = function(onload) {
1293 fieldmapper.standardRequest(
1295 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
1298 "params": [openils.User.authtoken, 0, 500],
1299 "oncomplete": function(r) {
1300 self.distribForms = openils.Util.readResponse(r);
1301 if(!self.distribForms || self.distribForms.length == 0) {
1302 self.distribForms = [];
1304 self._addDistribFormulaRow();
1311 this._drawBatchCopyWidgets = function() {
1312 var row = this.copyBatchRow;
1313 dojo.forEach(liDetailBatchFields,
1315 if(self.copyBatchRowDrawn) {
1316 self.copyBatchWidgets[field].attr('value', null);
1318 var widget = new openils.widget.AutoFieldWidget({
1321 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1322 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1323 searchFilter : (field == 'fund') ? {"active": "t"} : null,
1324 parentNode : dojo.query('[name='+field+']', row)[0],
1325 orgLimitPerms : ['CREATE_PICKLIST'],
1328 "labelType": (field == "fund") ? "html" : null
1330 noCache: (field == "fund"),
1335 if (field == "fund" && w.store)
1336 self._ensureCSSFundClasses(w.store);
1337 self.copyBatchWidgets[field] = w;
1340 if (field == "fund") {
1342 widget.widget, "onChange", function(val) {
1343 self._updateFundSelectorStyle(widget, val);
1350 this.copyBatchRowDrawn = true;
1353 this.batchCopyUpdate = function() {
1355 for(var k in this.copyWidgetCache) {
1356 var cache = this.copyWidgetCache[k];
1357 dojo.forEach(liDetailBatchFields, function(f) {
1358 var newval = self.copyBatchWidgets[f].attr('value');
1359 if(newval) cache[f].attr('value', newval);
1364 this._drawCopies = function(li) {
1367 // this button sets the total number of copies for a given lineitem
1368 acqLitAddCopyCount.onClick = function() {
1369 var count = acqLitCopyCountInput.attr('value');
1372 while(self.copyCount() < count)
1375 // delete rows if necessary
1376 var diff = self.copyCount() - count;
1378 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
1379 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
1380 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
1382 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1388 if(li.lineitem_details().length > 0) {
1389 dojo.forEach(li.lineitem_details(),
1391 self.addCopy(li, copy);
1399 this.copyCount = function() {
1401 for(var id in this.copyCache) {
1402 if(!this.copyCache[id].isdeleted())
1408 this.virtCopyId = -1;
1409 this.addCopy = function(li, copy) {
1410 var row = this.copyRow.cloneNode(true);
1411 this.copyTbody.appendChild(row);
1415 copy = new fieldmapper.acqlid();
1417 copy.id(this.virtCopyId--);
1418 copy.lineitem(li.id());
1421 this.copyCache[copy.id()] = copy;
1422 row.setAttribute('copy_id', copy.id());
1423 self.copyWidgetCache[copy.id()] = {};
1425 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1427 dojo.forEach(liDetailFields,
1430 if (field == "fund") {
1431 searchFilter = (copy.fund() ?
1432 {"-or": {"active": "t", "id": copy.fund()}} :
1435 searchFilter = null;
1438 var readOnly = false;
1440 // TODO: Add support for changing the owning_lib after real copies have been made.
1441 // owning_lib is order data as much as its item data
1442 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
1446 // TODO: add support for changing the fund after debits have been created
1447 // Note: invoicing allows the change
1448 if(copy.fund_debit() && field == 'fund') {
1452 var widget = new openils.widget.AutoFieldWidget({
1455 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1456 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1457 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1458 searchFilter : searchFilter,
1459 noCache: (field == "fund"),
1461 parentNode : dojo.query('[name='+field+']', row)[0],
1462 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
1463 readOnly : readOnly,
1464 orgDefaultsToWs : true
1468 // make sure we capture the value from any async widgets
1471 if (field == "fund" && w.store)
1472 self._ensureCSSFundClasses(w.store);
1475 copy[field](ww.getFormattedValue())
1477 self.copyWidgetCache[copy.id()][field] = w;
1479 dojo.connect(w, 'onChange',
1481 if (field == "fund")
1482 self._updateFundSelectorStyle(widget, val);
1484 if (!readOnly && (copy.isnew() || val != copy[field]())) {
1485 // prevent setting ischanged() automatically on widget load for existing copies
1486 copy[field](widget.getFormattedValue())
1487 copy.ischanged(true);
1496 this.updateLidState(copy, row);
1499 this._ensureCSSFundClass = function(id) {
1500 if (!this.fundStyleSheet) {
1502 "style", {"type": "text/css"},
1503 document.getElementsByTagName("head")[0], "last"
1505 this.fundStyleSheet = document.styleSheets[
1506 document.styleSheets.length - 1
1510 var cn = "fund_" + id;
1511 if (!this.haveFundClass[cn]) {
1512 fieldmapper.standardRequest(
1513 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
1515 "params": [openils.User.authtoken, id],
1517 "oncomplete": function(r) {
1518 r = openils.Util.readResponse(r);
1519 self.fundBalanceState[id] = r;
1521 if (r[0] /* stop */)
1522 style = fundStyles.stop;
1523 else if (r[1] /* warning */)
1524 style = fundStyles.warning;
1525 self.fundStyleSheet.insertRule(
1526 "." + cn + " { " + style + " }",
1527 self.fundStyleSheet.cssRules.length
1529 self.haveFundClass[cn] = true;
1536 this._ensureCSSFundClasses = function(store) {
1538 "query": {"id": "*"},
1539 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
1543 this._updateFundSelectorStyle = function(widget, fund_id) {
1544 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
1545 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
1548 this.updateLidState = function(copy, row) {
1549 if (typeof(row) == "undefined") {
1551 'tr[copy_id="' + copy.id() + '"]', this.copyTbody
1556 var recv_link = nodeByName("receive", row);
1557 var unrecv_link = nodeByName("unreceive", row);
1558 var del_link = nodeByName("delete", row);
1559 var cxl_link = nodeByName("cancel", row);
1560 var claim_link = nodeByName("claim", row);
1561 var cxl_reason_link = nodeByName("cancel_reason", row);
1563 if (copy.cancel_reason()) {
1564 openils.Util.hide(del_link.parentNode);
1565 openils.Util.hide(recv_link);
1566 openils.Util.hide(unrecv_link);
1567 openils.Util.hide(cxl_link);
1568 openils.Util.hide(claim_link);
1570 /* XXX the following may leak memory in a long lived table: dijits may not get destroyed... not positive. revisit. */
1571 var holds_reason = dojo.create(
1573 "style": "border-bottom: 1px dashed #000;",
1574 "innerHTML": "Cancelled" /* XXX [sic] and i18n */
1575 }, cxl_reason_link, "only"
1579 "label": "<em>" + copy.cancel_reason().label() +
1580 "</em><br />" + copy.cancel_reason().description(),
1581 "connectId": [holds_reason]
1582 }, dojo.create("span", null, cxl_reason_link, "last")
1584 openils.Util.show(cxl_reason_link, "inline");
1585 } else if (this.isPO) {
1586 /* Only using this in one place so far, but may want it for better
1587 * decisions on when to display certain controls. */
1588 var li_state = this.liCache[copy.lineitem()].state();
1590 openils.Util.hide(del_link.parentNode);
1591 openils.Util.hide(cxl_reason_link);
1593 /* Avoid showing (un)receive links, cancel links, for virt copies */
1594 if (copy.id() > 0) {
1595 if (copy.recv_time()) {
1596 openils.Util.hide(cxl_link);
1597 openils.Util.hide(recv_link);
1598 openils.Util.hide(claim_link);
1600 openils.Util.show(unrecv_link, "inline");
1601 unrecv_link.onclick = function() {
1602 if (confirm(localeStrings.UNRECEIVE_LID))
1603 self.issueReceive(copy, /* rollback */ true);
1606 openils.Util.hide(unrecv_link);
1608 if (this.claimEligibleLid[copy.id()]) {
1609 openils.Util.show(claim_link, "inline");
1610 claim_link.onclick = function() {
1611 self.claimDialog.show(
1612 self.liCache[copy.lineitem()], copy.id()
1616 openils.Util.hide(claim_link);
1619 openils.Util[li_state == "on-order" ? "show" : "hide"](
1622 openils.Util.show(cxl_link, "inline");
1623 recv_link.onclick = function() {
1624 if (self.checkLiAlerts(copy.lineitem()))
1625 self.issueReceive(copy);
1627 cxl_link.onclick = function() {
1628 self.cancelLid(copy.id());
1632 openils.Util.hide(cxl_link);
1633 openils.Util.hide(unrecv_link);
1634 openils.Util.hide(recv_link);
1635 openils.Util.hide(claim_link);
1638 openils.Util.hide(unrecv_link);
1639 openils.Util.hide(recv_link);
1640 openils.Util.hide(cxl_reason_link);
1641 openils.Util.hide(claim_link);
1643 del_link.onclick = function() { self.deleteCopy(row) };
1644 openils.Util.show(del_link.parentNode);
1648 this.cancelLid = function(lid_id) {
1649 lidCancelDialog._lid_id = lid_id;
1650 openils.Util.show(lidCancelDialog.domNode.parentNode);
1651 lidCancelDialog.show();
1652 if (!lidCancelDialog._prepared) {
1653 var widget = new openils.widget.AutoFieldWidget({
1654 "fmField": "cancel_reason",
1655 "fmClass": "acqlid",
1656 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
1657 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1662 acqLidCancelButton.onClick = function() {
1663 if (w.attr("value")) {
1664 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
1666 lidCancelDialog._lid_id,
1670 lidCancelDialog.hide();
1673 lidCancelDialog._prepared = true;
1679 this._cancelLid = function(lid_id, reason) {
1680 fieldmapper.standardRequest(
1681 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
1682 "params": [openils.User.authtoken, lid_id, reason],
1684 "onresponse": function(r) {
1685 if (r = openils.Util.readResponse(r)) {
1687 for (var id in r.lid) {
1688 /* actually this should only iterate once */
1689 self.copyCache[id].cancel_reason(
1690 r.lid[id].cancel_reason
1692 self.updateLidState(self.copyCache[id]);
1701 this._confirmAlert = function(li, lin) {
1703 dojo.string.substitute(
1704 localeStrings.CONFIRM_LI_ALERT, [
1705 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1706 "title", "lineitem_marc_attr_definition"
1708 lin.alert_text().code(),
1709 lin.alert_text().description() || "",
1716 this.checkLiAlerts = function(li_id) {
1717 var li = this.liCache[li_id];
1719 var alert_notes = li.lineitem_notes().filter(
1720 function(o) { return Boolean(o.alert_text()); }
1723 /* this is _intentionally_ not done in a call to forEach() ... */
1724 for (var i = 0; i < alert_notes.length; i++) {
1725 if (this.noteAcks[alert_notes[i].id()])
1727 else if (!this._confirmAlert(li, alert_notes[i]))
1730 this.noteAcks[alert_notes[i].id()] = true;
1736 this.deleteCopy = function(row) {
1737 var copy = this.copyCache[row.getAttribute('copy_id')];
1738 copy.isdeleted(true);
1740 delete this.copyCache[copy.id()];
1741 this.copyTbody.removeChild(row);
1744 this._virtDfaCountsAsList = function() {
1746 for (var key in this.virtDfaCounts) {
1747 for (var i = 0; i < this.virtDfaCounts[key]; i++)
1753 this.confirmBreachedCopyFunds = function(copies) {
1754 var stop = 0, warning = 0;
1758 var state = self.fundBalanceState[o.fund()];
1759 if (state[0] /* stop */)
1761 else if (state[1] /* warning */)
1768 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
1769 } else if (warning) {
1770 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
1775 this.saveCopyChanges = function(liId) {
1781 for(var id in this.copyCache) {
1782 var c = this.copyCache[id];
1783 if(!c.isdeleted()) total++;
1784 if(c.isnew() || c.ischanged() || c.isdeleted()) {
1785 if(c.id() < 0) c.id(null);
1791 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
1794 if (copies.length > 0) {
1795 if (!this.confirmBreachedCopyFunds(copies))
1798 if (typeof(this._copy_count_cb) == "function")
1799 this._copy_count_cb(liId, total);
1801 openils.Util.show("acq-lit-update-copies-progress");
1802 fieldmapper.standardRequest(
1803 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1805 params: [openils.User.authtoken, copies],
1806 onresponse: function(r) {
1807 var res = openils.Util.readResponse(r);
1808 litUpdateCopiesProgress.update(res);
1810 oncomplete: function() {
1811 self.drawCopies(liId, true /* force_fetch */);
1812 openils.Util.hide("acq-lit-update-copies-progress");
1818 var dfa_list = this._virtDfaCountsAsList();
1819 if (dfa_list.length > 0) {
1820 fieldmapper.standardRequest(
1822 "open-ils.acq.distribution_formula.record_application"],
1825 "params": [openils.User.authtoken, dfa_list, liId],
1826 "onresponse": function(r) {
1827 var res = openils.Util.readResponse(r);
1828 if (res && res.length < dfa_list.length)
1829 alert(localeStrings.DFA_NOT_ALL);
1833 this.virtDfaCounts = {};
1837 this._updateCreatePoPrepayCheckbox = function(prepay) {
1838 var prepay = openils.Util.isTrue(prepay);
1839 this._prepayRequiredByVendor = prepay;
1840 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
1843 this._confirmPoPrepaySituation = function() {
1844 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
1845 if (want_prepay != this._prepayRequiredByVendor) {
1848 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
1849 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
1856 this.applySelectedLiAction = function(action) {
1860 case 'delete_selected':
1861 this._deleteLiList(self.getSelected());
1864 case 'create_order':
1865 this._loadPOSelect();
1866 acqLitPoCreateDialog.show();
1869 case 'save_picklist':
1870 acqLitSavePlDialog.show();
1873 case 'selector_ready':
1875 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
1876 acqLitChangeLiStateDialog.show();
1884 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
1891 case 'rollback_receive_po':
1892 this.rollbackPoReceive();
1895 case 'create_assets':
1896 this.createAssets();
1899 case 'export_attr_list':
1900 this.chooseExportAttr();
1903 case 'batch_apply_funds':
1904 this.applyBatchLiFunds();
1907 case 'add_brief_record':
1909 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
1911 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
1915 case "cancel_lineitems":
1916 this.maybeCancelLineitems();
1919 case "change_claim_policy":
1920 var li_list = this.getSelected();
1921 this.claimPolicyPicker.attr("value", null);
1922 liClaimPolicyDialog.show();
1923 liClaimPolicySave.onClick = function() {
1924 self.changeClaimPolicy(
1926 self.claimPolicyPicker.attr("value"),
1929 function(li) { self.setClaimPolicyControl(li); }
1931 liClaimPolicyDialog.hide();
1939 this.changeClaimPolicy = function(li_list, value, callback) {
1941 function(li) { li.claim_policy(value); }
1943 fieldmapper.standardRequest(
1944 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
1945 "params": [openils.User.authtoken, li_list],
1947 "oncomplete": function(r) {
1948 r = openils.Util.readResponse(r);
1949 if (callback) callback(r);
1955 this.createAssets = function() {
1956 if(!this.isPO) return;
1957 if(!confirm(localeStrings.CREATE_PO_ASSETS_CONFIRM)) return;
1958 this.show('acq-lit-progress-numbers');
1960 fieldmapper.standardRequest(
1961 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
1963 params: [this.authtoken, this.isPO],
1964 onresponse: function(r) {
1965 var resp = openils.Util.readResponse(r);
1966 self._updateProgressNumbers(resp, true);
1972 this.maybeCancelLineitems = function() {
1973 openils.Util.show("acq-lit-cancel-reason", "inline");
1974 if (!acqLitCancelLineitemsButton._prepared) {
1975 var widget = new openils.widget.AutoFieldWidget({
1976 "fmField": "cancel_reason",
1978 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
1979 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1984 acqLitCancelLineitemsButton.onClick = function() {
1985 if (w.attr("value")) {
1986 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
1987 self._cancelLineitems(w.attr("value"));
1989 openils.Util.hide("acq-lit-cancel-reason");
1992 acqLitCancelLineitemsButton._prepared = true;
1998 this._cancelLineitems = function(reason) {
1999 var id_list = this.getSelected().map(function(o) { return o.id(); });
2000 fieldmapper.standardRequest(
2001 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
2002 "params": [openils.User.authtoken, id_list, reason],
2004 "onresponse": function(r) {
2005 if (r = openils.Util.readResponse(r)) {
2007 for (var id in r.li) {
2008 self.liCache[id].state(r.li[id].state);
2009 self.liCache[id].cancel_reason(
2010 r.li[id].cancel_reason
2012 self.updateLiState(self.liCache[id]);
2015 if (r.lid && self.copyCache) {
2016 for (var id in r.lid) {
2017 if (self.copyCache[id]) {
2018 self.copyCache[id].cancel_reason(
2019 r.lid[id].cancel_reason
2021 self.updateLidState(self.copyCache[id]);
2031 this.chooseExportAttr = function() {
2032 if (!acqLitExportAttrSelector._li_setup) {
2034 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
2036 "data": acqliad.toStoreData(
2038 "acqliad", {"code": li_exportable_attrs}
2043 acqLitExportAttrSelector.setValue();
2044 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
2045 acqLitExportAttrSelector._li_setup = true;
2047 openils.Util.show("acq-lit-export-attr-holder", "inline");
2050 this.exportAttrList = function() {
2051 var attr_def = acqLitExportAttrSelector.item;
2052 var li_list = this.getSelected();
2053 var value_list = li_list.map(
2055 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2056 attr_def.code, "lineitem_marc_attr_definition"
2059 ).filter(function(attr) { return Boolean(attr); });
2061 if (value_list.length > 0) {
2062 if (value_list.length < li_list.length) {
2064 dojo.string.substitute(
2065 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
2072 openils.XUL.contentToFileSaveDialog(
2073 value_list.join("\n"),
2074 localeStrings.EXPORT_SAVE_DIALOG_TITLE
2080 alert(dojo.string.substitute(
2081 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
2085 openils.Util.hide("acq-lit-export-attr-holder");
2088 this.printPO = function() {
2089 if(!this.isPO) return;
2090 progressDialog.show(true);
2091 fieldmapper.standardRequest(
2092 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
2094 params: [this.authtoken, this.isPO, 'html'],
2095 oncomplete: function(r) {
2096 progressDialog.hide();
2097 var evt = openils.Util.readResponse(r);
2098 if(evt && evt.template_output()) {
2099 openils.Util.printHtmlString(evt.template_output().data());
2107 this.receivePO = function() {
2108 if (!this.isPO) return;
2110 for (var id in this.liCache) {
2111 /* assumption: liCache reflects exactly the
2112 * set of LIs that belong to our PO */
2113 if (this.liCache[id].state() != "received" &&
2114 !this.checkLiAlerts(id)) return;
2117 this.show('acq-lit-progress-numbers');
2119 fieldmapper.standardRequest(
2120 ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
2122 params: [this.authtoken, this.isPO],
2123 onresponse : function(r) {
2124 var resp = openils.Util.readResponse(r);
2125 self._updateProgressNumbers(resp, true);
2131 this.issueReceive = function(obj, rollback) {
2132 /* (For now) there shall be no marking LI or LIDs (un)received
2133 * except from the actual "view PO" interface. */
2134 if (!this.isPO) return;
2137 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
2139 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
2141 progressDialog.show(true);
2142 fieldmapper.standardRequest(
2143 ["open-ils.acq", method], {
2145 "params": [this.authtoken, obj.id()],
2146 "onresponse": function(r) {
2147 if (r = openils.Util.readResponse(r)) {
2148 self.fetchClaimInfo(
2149 part == "lineitem" ? obj.id() : obj.lineitem(),
2151 function() { self.handleReceive(r); }
2153 progressDialog.hide();
2161 * Handles the responses from receive and rollback ML calls.
2163 this.handleReceive = function(resp) {
2166 for (var li_id in resp.li) {
2167 for (var key in resp.li[li_id])
2168 self.liCache[li_id][key](resp.li[li_id][key]);
2169 self.updateLiState(self.liCache[li_id]);
2173 if (typeof(self.poUpdateCallback) == "function")
2174 self.poUpdateCallback(resp.po);
2177 for (var lid_id in resp.lid) {
2178 for (var key in resp.lid[lid_id])
2179 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
2180 self.updateLidState(self.copyCache[lid_id]);
2186 this.rollbackPoReceive = function() {
2187 if(!this.isPO) return;
2188 if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
2189 this.show('acq-lit-progress-numbers');
2191 fieldmapper.standardRequest(
2192 ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
2194 params: [this.authtoken, this.isPO],
2195 onresponse : function(r) {
2196 var resp = openils.Util.readResponse(r);
2197 self._updateProgressNumbers(resp, true);
2203 this._updateProgressNumbers = function(resp, reloadOnComplete) {
2205 dojo.byId('acq-pl-lit-li-processed').innerHTML = resp.li;
2206 dojo.byId('acq-pl-lit-lid-processed').innerHTML = resp.lid;
2207 dojo.byId('acq-pl-lit-debits-processed').innerHTML = resp.debits_accrued;
2208 dojo.byId('acq-pl-lit-bibs-processed').innerHTML = resp.bibs;
2209 dojo.byId('acq-pl-lit-indexed-processed').innerHTML = resp.indexed;
2210 dojo.byId('acq-pl-lit-copies-processed').innerHTML = resp.copies;
2211 if(resp.complete && reloadOnComplete)
2212 location.href = location.href;
2216 this._createPO = function(fields) {
2217 this.show('acq-lit-progress-numbers');
2218 var po = new fieldmapper.acqpo();
2219 po.provider(this.createPoProviderSelector.attr('value'));
2220 po.ordering_agency(this.createPoAgencySelector.attr('value'));
2221 po.prepayment_required(fields.prepayment_required[0] ? true : false);
2223 var selected = this.getSelected( (fields.create_from == 'all') );
2224 if(selected.length == 0) return;
2226 var max = selected.length * 3;
2229 fieldmapper.standardRequest(
2230 ['open-ils.acq', 'open-ils.acq.purchase_order.create'],
2233 openils.User.authtoken,
2236 lineitems : selected.map(function(li) { return li.id() }),
2237 create_assets : fields.create_assets[0],
2241 onresponse : function(r) {
2242 var resp = openils.Util.readResponse(r);
2243 self._updateProgressNumbers(resp);
2245 location.href = oilsBasePath + '/acq/po/view/' + resp.purchase_order.id();
2251 this.batchFundWidget = null;
2253 this.applyBatchLiFunds = function() {
2255 var liIds = this.getSelected().map(function(li) { return li.id(); });
2256 if(liIds.length == 0) return; // warn?
2259 batchFundUpdateDialog.show();
2261 if(!this.batchFundWidget) {
2262 this.batchFundWidget = new openils.widget.AutoFieldWidget({
2264 selfReference : true,
2265 labelFormat : fundLabelFormat,
2266 searchFormat : fundSearchFormat,
2267 searchFilter : {"active": "t"},
2268 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
2269 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2270 dijitArgs : { "required": true, "labelType": "html" },
2273 this.batchFundWidget.build();
2276 dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
2277 dojo.connect(batchFundUpdateSubmit, 'onClick',
2280 // TODO: call .dry_run first to test thresholds
2281 fieldmapper.standardRequest(
2282 ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
2285 openils.User.authtoken,
2287 self.batchFundWidget.widget.attr('value')
2289 oncomplete : function(r) {
2290 var resp = openils.Util.readResponse(r);
2292 location.href = location.href;
2301 this._deleteLiList = function(list, idx) {
2302 if(idx == null) idx = 0;
2303 if(idx >= list.length) return;
2304 var liId = list[idx].id();
2305 fieldmapper.standardRequest(
2306 ['open-ils.acq', 'open-ils.acq.lineitem.delete'],
2308 params: [openils.User.authtoken, liId],
2309 oncomplete: function(r) {
2310 self.removeLineitem(liId);
2311 self._deleteLiList(list, ++idx);
2317 this.editOrderMarc = function(li) {
2319 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
2320 to true in about:config */
2322 if(!openils.XUL.enableXPConnect()) return;
2324 if(openils.XUL.isXUL()) {
2325 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
2327 win = window.open('/xul/server/cat/marcedit.xul');
2331 record : {marc : li.marc(), "rtype": "bre"},
2333 label: 'Save Record', // XXX I18N
2334 func: function(xmlString) {
2336 fieldmapper.standardRequest(
2337 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
2339 params: [openils.User.authtoken, li],
2340 oncomplete: function(r) {
2341 openils.Util.readResponse(r);
2343 self.drawInfo(li.id())
2349 'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
2350 'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
2354 this._savePl = function(values) {
2356 var selected = this.getSelected( (values.which == 'all') );
2357 openils.Util.show('acq-lit-generic-progress');
2359 if(values.new_name) {
2360 openils.acq.Picklist.create(
2361 {name: values.new_name},
2363 self._updateLiList(id, selected, 0,
2365 location.href = oilsBasePath + '/acq/picklist/view/' + id;
2369 } else if(values.existing_pl) {
2370 // update lineitems to use an existing picklist
2371 self._updateLiList(values.existing_pl, selected, 0,
2373 location.href = oilsBasePath + '/acq/picklist/view/' + values.existing_pl;
2378 this._updateLiState = function(values, state) {
2380 var selected = this.getSelected( (values.which == 'all') );
2381 if(!selected.length) return;
2382 dojo.forEach(selected, function(li) {li.state(state);});
2383 self._updateLiList(null, selected, 0,
2384 // TODO consider inline updates for efficiency
2385 function() { location.href = location.href }
2389 this._updateLiList = function(pl, list, idx, oncomplete) {
2390 if(idx >= list.length) return oncomplete();
2392 if(pl != null) li.picklist(pl);
2393 litGenericProgress.update({maximum: list.length, progress: idx});
2394 new openils.acq.Lineitem({lineitem:li}).update(
2396 self._updateLiList(pl, list, ++idx, oncomplete);
2401 this._loadPOSelect = function() {
2402 if (!this.createPoProviderSelector) {
2403 var widget = new openils.widget.AutoFieldWidget({
2404 "fmField": "provider",
2406 "searchFilter": {"active": "t"},
2407 "parentNode": dojo.byId("acq-lit-po-provider"),
2409 "onChange": function() {
2411 self._updateCreatePoPrepayCheckbox(
2412 this.item.prepayment_required
2418 widget.build(function(w) { self.createPoProviderSelector = w; });
2421 if (!this.createPoAgencySelector) {
2422 var widget = new openils.widget.AutoFieldWidget({
2423 "fmField": "ordering_agency",
2425 "parentNode": dojo.byId("acq-lit-po-agency"),
2426 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2428 widget.build(function(w) { self.createPoAgencySelector = w; });
2432 this.showRealCopyEditUI = function(li) {
2437 this._fetchLineitem(li.id(),
2439 li = self.liCache[li.id()] = fullLi;
2443 id : li.lineitem_details().map(
2444 function(item) { return item.eg_copy_id() }
2448 oncomplete : function(r) {
2450 var r_list = openils.Util.readResponse( r );
2451 for (var i = 0; i < r_list.length; i++) {
2452 var copy = r_list[i];
2453 var volId = copy.call_number();
2454 var volume = self.volCache[volId];
2456 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2458 copy.call_number(volume);
2459 copyList.push(copy);
2462 // If we need to, we can pass in an update_copy function to handle the update instead of volume_item_creator
2463 xulG.volume_item_creator( { 'existing_copies' : copyList } );
2466 alert('error in oncomplete: ' + E);
2475 this.drawBibFinder = function(li) {
2478 var liWrapper = new openils.acq.Lineitem({lineitem:li});
2481 ['isbn', 'upc', 'issn', 'title', 'author'],
2483 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
2485 if(field == 'title' || field == 'author') {
2486 query += field +':' + val + ' ';
2488 query += 'identifier|' + field + ':' + val + ' ';
2495 oilsBasePath + '/acq/lineitem/findbib?query=' + escape(query),
2496 '', 'resizable,scrollbars=1');
2498 win.window.recordFound = function(bibId) {
2501 var attrs = li.attributes();
2502 li.attributes(null);
2503 li.eg_bib_id(bibId);
2505 fieldmapper.standardRequest(
2506 ["open-ils.acq", "open-ils.acq.lineitem.update"],
2508 "params": [openils.User.authtoken, li],
2510 "oncomplete": function(r) {
2511 if(openils.Util.readResponse(r)) {
2512 location.href = location.href;