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 self.reconsiderClaimControl(li, row);
232 liClaimPolicyDialog.hide();
240 this.fetchClaimInfo = function(liId, force, callback, row) {
242 liId, function(full) {
243 self.liCache[full.id()] = full;
244 self.checkClaimEligibility(full, callback, row);
250 * Inserts a single lineitem into the growing table of lineitems
251 * @param {Object} li The lineitem object to insert
253 this.addLineitem = function(li, skip_final_placement) {
254 this.liCache[li.id()] = li;
256 // insert the row right away so that final order isn't
257 // dependent on how long subsequent async request take
258 // for a given line item
259 var row = self.rowTemplate.cloneNode(true);
260 if (!skip_final_placement) {
261 self.tbody.appendChild(row);
262 self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
265 // sort the lineitem notes on edit_time
266 if(!li.lineitem_notes()) li.lineitem_notes([]);
268 var liWrapper = new openils.acq.Lineitem({lineitem:li});
269 row.setAttribute('li', li.id());
270 var tds = dojo.query('[attr]', row);
271 dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
272 dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
275 liWrapper.findAttr("isbn", "lineitem_marc_attr_definition") ||
276 liWrapper.findAttr("upc", "lineitem_marc_attr_definition");
278 // XXX media prefix for added content
280 nodeByName("jacket", row).setAttribute(
281 "src", "/opac/extras/ac/jacket/small/" + identifier
285 nodeByName("liid", row).innerHTML += li.id();
288 openils.Util.show(nodeByName('catalog', row), 'inline');
289 nodeByName("catalog_link", row).onclick = this.generateMakeRecTab(li.eg_bib_id());
291 openils.Util.show(nodeByName('link_to_catalog', row), 'inline');
292 nodeByName("link_to_catalog_link", row).onclick = function() { self.drawBibFinder(li) };
295 nodeByName("worksheet_link", row).href =
296 oilsBasePath + "/acq/lineitem/worksheet/" + li.id();
298 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
299 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
300 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
302 if (!this.skipInitialEligibilityCheck)
306 function(full) { self.setClaimPolicyControl(full, row) },
310 this.updateLiNotesCount(li, row);
312 // show which PO this lineitem is a member of
313 if(li.purchase_order() && !this.isPO) {
315 this.poCache[li.purchase_order()] =
316 this.poCache[li.purchase_order()] ||
317 fieldmapper.standardRequest(
318 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
320 this.authtoken, li.purchase_order(), {
321 "flesh_price_summary": true,
322 "flesh_lineitem_count": true
325 if(po && !this.isMeta) {
326 openils.Util.show(nodeByName('po', row), 'inline');
327 var link = nodeByName('po_link', row);
328 link.setAttribute('href', oilsBasePath + '/acq/po/view/' + li.purchase_order());
329 link.innerHTML += po.name();
333 // show which picklist this lineitem is a member of
334 if(li.picklist() && (this.isPO || this.isMeta || this.isUni)) {
336 this.plCache[li.picklist()] =
337 this.plCache[li.picklist()] ||
338 fieldmapper.standardRequest(
339 ['open-ils.acq', 'open-ils.acq.picklist.retrieve.authoritative'],
340 {params: [this.authtoken, li.picklist()]});
342 if (pl.name() == "") {
343 openils.Util.show(nodeByName("bib_origin", row), "inline");
347 openils.Util.show(nodeByName('pl', row), 'inline');
348 var link = nodeByName('pl_link', row);
349 link.setAttribute('href', oilsBasePath + '/acq/picklist/view/' + li.picklist());
350 link.innerHTML += pl.name();
355 var countNode = nodeByName('count', row);
356 var count = li.item_count() || 0;
357 if (typeof(this._copy_count_cb) == "function") {
358 this._copy_count_cb(li.id(), count);
360 countNode.innerHTML = count;
361 countNode.id = 'acq-lit-copy-count-label-' + li.id();
364 var priceInput = dojo.query('[name=price]', row)[0];
365 priceInput.value = li.estimated_unit_price() || '';
366 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
368 // show either "mark received" or "unreceive" as appropriate
369 this.updateLiState(li, row);
371 if (skip_final_placement) {
376 this._liCountClaims = function(li) {
378 for (var i = 0; i < li.lineitem_details().length; i++)
379 total += li.lineitem_details()[i].claims().length;
383 this._findLiRow = function(li) {
384 return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
387 this.reconsiderClaimControl = function(li, row) {
388 if (!row) row = this._findLiRow(li);
389 var option = nodeByName("action_manage_claims", row);
390 var eligible = this.claimEligibleLidByLi[li.id()].length;
391 var count = this._liCountClaims(li);
393 option.disabled = !(count || eligible);
395 dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
396 option.onclick = function() { self.claimDialog.show(li); };
399 this.clearEligibility = function(li) {
400 this.claimEligibleLidByLi[li.id()] = [];
402 if (li.lineitem_details()) {
403 li.lineitem_details().forEach(
404 function(lid) { delete self.claimEligibleLid[lid.id()]; }
408 if (this.copyCache) {
410 for (var k in this.copyCache) {
411 if (this.copyCache[k].lineitem() == li.id())
415 function(k) { delete self.claimEligibleLid[k]; }
420 this.checkClaimEligibility = function(li, callback, row) {
421 /* Assume always eligible, i.e. from this interface we don't care about
422 * claim eligibility any more. this is where the user would force a
424 this.clearEligibility(li);
425 this.claimEligibleLidByLi[li.id()] = li.lineitem_details().map(
426 function(lid) { return lid.id(); }
428 li.lineitem_details().forEach(
429 function(lid) { self.claimEligibleLid[lid.id()] = true; }
431 this.reconsiderClaimControl(li, row);
432 if (callback) callback(li);
434 this.clearEligibility(li);
435 fieldmapper.standardRequest(
436 ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
437 "params": [openils.User.authtoken, {"lineitem": li.id()}],
439 "onresponse": function(r) {
440 if (r = openils.Util.readResponse(r)) {
441 self.claimEligibleLidByLi[li.id()].push(
444 self.claimEligibleLid[r.lineitem_detail()] = true;
447 "oncomplete": function() {
448 self.reconsiderClaimControl(li, row);
449 if (typeof(callback) == "function")
457 this.updateLiNotesCount = function(li, row) {
458 if (!row) row = this._findLiRow(li);
460 var has_notes = (li.lineitem_notes().filter(
461 function(o) { return Boolean (o.alert_text()); }
464 /* U+2691 is the code point for a filled-in flag character */
465 nodeByName("notes_alert_flag", row).innerHTML =
466 has_notes ? "⚑" : "";
467 nodeByName("noteslink", row).style.fontStyle =
468 has_notes ? "italic" : "normal";
469 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
472 /* XXX NOT related to _updateLiState(). rethink */
473 this.updateLiState = function(li, row) {
474 if (!row) row = this._findLiRow(li);
476 var actReceive = nodeByName("action_mark_recv", row);
477 var actUnRecv = nodeByName("action_mark_unrecv", row);
478 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
479 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
481 var actNewInvoice = nodeByName('action_new_invoice', row);
482 var actLinkInvoice = nodeByName('action_link_invoice', row);
483 var actViewInvoice = nodeByName('action_view_invoice', row);
485 nodeByName('action_view_history', row).onclick =
486 function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
488 var state_cell = nodeByName("li_state", row);
490 if (li.state() == "cancelled") {
491 if (typeof li.cancel_reason() == "object") {
492 var holds_state = dojo.create(
494 "style": "border-bottom: 1px dashed #000;",
495 "innerHTML": li.state()
496 }, state_cell, "only"
500 "label": "<em>" + li.cancel_reason().label() +
501 "</em><br />" + li.cancel_reason().description(),
502 "connectId": [holds_state]
503 }, dojo.create("span", null, state_cell, "last")
506 state_cell.innerHTML = li.state(); // TODO i18n state labels
509 state_cell.innerHTML = li.state(); // TODO i18n state labels
513 /* handle row coloring for based on LI state */
514 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
515 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
517 /* handle links that appear/disappear based on whether LI is received */
521 actNewInvoice.onclick = function() {
522 location.href = oilsBasePath + '/acq/invoice/view?create=1&attach_li=' + li.id();
523 nodeByName("action_none", row).selected = true;
525 actLinkInvoice.onclick = function() {
526 if (!self.invoiceLinkDialogManager) {
527 self.invoiceLinkDialogManager =
528 new InvoiceLinkDialogManager("li");
530 self.invoiceLinkDialogManager.target = li;
531 acqLitLinkInvoiceDialog.show();
532 nodeByName("action_none", row).selected = true;
534 actViewInvoice.onclick = function() {
535 location.href = oilsBasePath +
536 "/acq/search/unified?so=" +
537 base64Encode({"jub":[{"id": li.id()}]}) +
539 nodeByName("action_none", row).selected = true;
542 actNewInvoice.disabled = false;
543 actLinkInvoice.disabled = false;
544 actViewInvoice.disabled = false;
548 actReceive.disabled = false;
549 actReceive.onclick = function() {
550 if (self.checkLiAlerts(li.id()))
551 self.issueReceive(li);
552 nodeByName("action_none", row).selected = true;
557 actUnRecv.disabled = false;
558 actUnRecv.onclick = function() {
559 if (confirm(localeStrings.UNRECEIVE_LI))
560 self.issueReceive(li, /* rollback */ true);
561 nodeByName("action_none", row).selected = true;
563 // TODO we should allow editing before receipt, in which case the
564 // test should be "if 1 or more real (acp) copies exist
565 actUpdateBarcodes.disabled = false;
566 actUpdateBarcodes.onclick = function() {
567 self.showRealCopyEditUI(li);
568 nodeByName("action_none", row).selected = true;
570 actHoldingsMaint.disabled = false;
571 actHoldingsMaint.onclick = self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
579 this._setAlertStore = function() {
580 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
582 "data": acqliat.toStoreData(
584 "acqliat", {"id": {"!=": null}}
589 acqLitAlertAlertText.setValue(); /* make the store "live" */
590 acqLitAlertAlertText._store_ready = true;
594 * Draws and shows the lineitem notes pane
596 this.drawLiNotes = function(li) {
599 if (!acqLitAlertAlertText._store_ready)
600 this._setAlertStore();
603 li.lineitem_notes().sort(
605 if(a.edit_time() < b.edit_time()) return 1;
611 while(this.liNotesTbody.childNodes[0])
612 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
615 acqLitCreateNoteSubmit.onClick = function() {
616 var value = acqLitCreateNoteText.attr('value');
618 var note = new fieldmapper.acqlin();
621 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
624 note.lineitem(li.id());
626 self.updateLiNotes(li, note);
627 acqLitCreateNoteVendorPublic.attr("checked", false);
628 acqLitCreateNoteText.attr("value", "");
631 acqLitCreateAlertSubmit.onClick = function() {
632 if (!acqLitAlertAlertText.item) {
633 alert(localeStrings.ALERT_UNSELECTED);
637 var alert_text = new fieldmapper.acqliat().fromStoreItem(
638 acqLitAlertAlertText.item
640 var value = acqLitAlertNoteValue.attr("value") || "";
642 var note = new fieldmapper.acqlin();
644 note.lineitem(li.id());
646 note.alert_text(alert_text);
648 self.updateLiNotes(li, note);
651 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
655 * Draws a single lineitem note in the notes pane
657 this.addLiNote = function(li, note) {
658 if(note.isdeleted()) return;
660 var row = self.liNotesRow.cloneNode(true);
661 nodeByName("value", row).innerHTML = note.value();
662 var alert_node = nodeByName("alert_code", row);
663 if (note.alert_text()) {
664 alert_node.innerHTML = note.alert_text().code();
665 if (note.alert_text().description()) {
668 "connectId": [alert_node],
669 "label": note.alert_text().description()
670 }, dojo.create("span", null, alert_node, "after")
675 if (openils.Util.isTrue(note.vendor_public()))
676 nodeByName("vendor_public", row).innerHTML =
677 localeStrings.VENDOR_PUBLIC;
679 nodeByName("delete", row).onclick = function() {
680 note.isdeleted(true);
681 self.liNotesTbody.removeChild(row);
682 self.updateLiNotes(li);
685 if(note.edit_time()) {
686 nodeByName("edit_time", row).innerHTML =
687 dojo.date.locale.format(
688 dojo.date.stamp.fromISOString(note.edit_time()),
689 {formatLength:'short'});
692 self.liNotesTbody.appendChild(row);
696 * Updates any new/changed/deleted notes on the server
698 this.updateLiNotes = function(li, newNote) {
704 notes = li.lineitem_notes().filter(
706 if(note.ischanged() || note.isnew() || note.isdeleted())
712 if(notes.length == 0) return;
713 progressDialog.show();
715 fieldmapper.standardRequest(
716 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
718 params : [this.authtoken, notes],
719 onresponse : function(r) {
720 var resp = openils.Util.readResponse(r);
725 // remove the old changed notes
727 dojo.forEach(li.lineitem_notes(),
729 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
733 li.lineitem_notes(list);
736 progressDialog.hide();
737 self.updateLiNotesCount(li);
738 self.drawLiNotes(li);
742 progressDialog.update(resp);
743 var newnote = resp.note;
745 if(!newnote.isdeleted()) {
746 newnote.isnew(false);
747 newnote.ischanged(false);
748 li.lineitem_notes().push(newnote);
755 this.updateLiPrice = function(input, li) {
757 var price = input.value;
758 if(Number(price) == Number(li.estimated_unit_price())) return;
760 fieldmapper.standardRequest(
761 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
762 { async : false, // redundant w/ timeout
764 params : [this.authtoken, li.id(), price],
765 oncomplete : function(r) {
766 openils.Util.readResponse(r);
767 li.estimated_unit_price(price); // update local copy
773 this.removeLineitem = function(liId) {
774 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
775 delete this.liCache[liId];
776 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
779 this.drawInfo = function(liId) {
780 if (!this._isRelatedViewer) {
781 var d = dojo.byId("acq-lit-info-related");
782 if (!this.relCache[liId]) {
783 fieldmapper.standardRequest(
786 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
789 "params": [openils.User.authtoken, liId],
790 "onresponse": function(r) {
791 self.relCache[liId] = openils.Util.readResponse(r);
792 nodeByName("related_number", d).innerHTML =
795 self.relCache[liId] >1 ? "show" : "hide"
801 nodeByName("related_number", d).innerHTML = this.relCache[liId];
802 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
807 openils.acq.Lineitem.fetchAttrDefs(
809 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
814 this._fetchLineitem = function(liId, handler, force) {
816 var li = this.liCache[liId];
817 if(li && li.marc() && li.lineitem_details() && !force)
820 fieldmapper.standardRequest(
821 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
824 params: [self.authtoken, liId, {
826 flesh_cancel_reason: true,
827 flesh_li_details: true,
829 flesh_fund_debit: true }],
831 oncomplete: function(r) {
832 var li = openils.Util.readResponse(r);
833 self.liCache[liId] = li;
840 this._drawInfo = function(li) {
842 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
845 openils.Util.hide('acq-lit-marc-order-record-label');
846 openils.Util.hide(acqLitEditOrderMarc.domNode);
847 openils.Util.show('acq-lit-marc-real-record-label');
849 openils.Util.show('acq-lit-marc-order-record-label');
850 openils.Util.show(acqLitEditOrderMarc.domNode);
851 openils.Util.hide('acq-lit-marc-real-record-label');
854 this.drawMarcHTML(li);
855 this.infoTbody = dojo.byId('acq-lit-info-tbody');
858 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
859 while(this.infoTbody.childNodes[0])
860 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
862 for(var i = 0; i < li.attributes().length; i++) {
863 var attr = li.attributes()[i];
864 var row = this.infoRow.cloneNode(true);
866 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
867 var name = openils.acq.Lineitem.attrDefs[type].filter(
869 return (a.code() == attr.attr_name());
871 ).pop().description();
873 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
874 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
875 this.infoTbody.appendChild(row);
878 if (!this._isRelatedViewer) {
879 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
880 oilsBasePath + "/acq/lineitem/related/" + li.id();
885 this.generateMakeRecTab = function(bib_id,default_view, row) {
889 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
892 show_nav_buttons : true,
893 show_print_button : true,
894 opac_url : xulG.url_prefix(xulG.urls.opac_rdetail + '?r=' + bib_id),
895 default_view : default_view
899 if(row) nodeByName("action_none", row).selected = true;
903 this.drawMarcHTML = function(li) {
904 var params = [null, true, li.marc()];
906 params = [li.eg_bib_id(), true];
908 fieldmapper.standardRequest(
909 ['open-ils.search', 'open-ils.search.biblio.record.html'],
912 oncomplete: function(r) {
913 dojo.byId('acq-lit-marc-div').innerHTML =
914 openils.Util.readResponse(r);
920 this.drawCopies = function(liId, force_fetch) {
921 if (typeof force_fetch == "undefined")
927 this.copyWidgetCache = {};
928 this.oldCopyWidgetCache = {};
929 this.virtDfaCounts = {};
930 this.realDfaCache = {};
933 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
934 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
935 acqLitCopyCountInput.attr('value', '0');
937 while(this.copyTbody.childNodes[0])
938 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
940 this._drawBatchCopyWidgets();
942 this._drawDistribApplied(liId);
944 this._fetchDistribFormulas(
946 openils.acq.Lineitem.fetchAttrDefs(
948 self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch);
955 this._saveDistribAppliedTemplates = function() {
956 if (!this._appliedDistribTemplate) {
957 this._appliedDistribTemplate =
958 dojo.byId("acq-lit-distrib-applied-tbody").
959 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
960 dojo.attr(this._appliedDistribTemplate, "id");
964 this._drawDistribApplied = function(liId) {
965 /* Build this table while hidden to prevent rendering artifacts */
966 openils.Util.hide("acq-lit-distrib-applied-tbody");
968 this._saveDistribAppliedTemplates();
970 /* Remove any rows in the table from previous populations */
971 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
972 forEach(dojo.destroy);
974 /* Unregister all dijits previously created (for some reason this isn't
975 * covered by the above destroy calls). */
976 dijit.registry.forEach(
977 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
980 /* Populate the table with our liId */
982 fieldmapper.standardRequest(
984 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
987 "params": [self.authtoken, liId],
988 "onresponse": function(r) {
989 var dfa = openils.Util.readResponse(r);
992 self.realDfaCache[dfa.id()] = dfa;
993 self._drawDistribAppliedUnit(dfa);
996 "oncomplete": function() {
997 /* Reveal built table */
1000 "acq-lit-distrib-applied-tbody", "table-row-group"
1008 this._drawDistribAppliedUnit = function(dfa) {
1009 var new_row = false;
1010 var row = dojo.query(
1011 'tr[formula="' + dfa.formula().id() + '"]',
1012 "acq-lit-distrib-applied-tbody"
1017 row = dojo.clone(this._appliedDistribTemplate);
1018 dojo.attr(row, "formula", dfa.formula().id());
1019 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
1022 var td = dojo.query("td", row)[0];
1024 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1025 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1028 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1030 new dijit.form.Button(
1032 "onClick": function() {
1033 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1034 self.deleteDfa(dfa);
1037 /* XXX I /cannot/ make the following work in as a CSS class
1038 * for some reason. So frustrating... */
1039 "style": function(id) {
1041 "font-weight: bold; color: #c00;" :
1043 }(dfa.id()) + "margin: 0 6px;display: inline;"
1044 }, "dfa-button-" + dfa.id()
1048 "connectId": ["dfa-button-" + dfa.id()],
1049 "label": dojo.string.substitute(
1050 localeStrings.DFA_TIP, dfa.id() > 0 ? [
1051 openils.User.formalName(dfa.creator()),
1052 dojo.date.locale.format(
1053 dojo.date.stamp.fromISOString(dfa.create_time()),
1054 {"formatLength":"short"}
1056 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
1058 }, "dfa-tip-" + dfa.id()
1062 this.deleteDfa = function(dfa) {
1063 if (dfa.id() > 0) { /* real */
1064 this.pcrud.eliminate(
1067 "oncomplete": function() {
1068 self._removeDistribApplied(dfa.id());
1069 delete self.realDfaCache[dfa.id()];
1073 } else { /* virtual */
1074 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
1075 this.virtDfaCounts[dfa.formula().id()] = 0;
1076 /* hasn't been saved yet, so no need to do anything server side */
1077 this._removeDistribApplied(dfa.id());
1082 this._removeDistribApplied = function(dfaId) {
1083 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
1084 dijit.registry.forEach(
1085 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
1087 this._removeDistribAppliedEmptyRows();
1090 this._removeAllDistribAppliedVirtual = function() {
1091 /* Unregister dijits */
1092 dijit.registry.forEach(
1093 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
1095 this._removeDistribAppliedEmptyRows();
1098 this._removeDistribAppliedEmptyRows = function() {
1099 /* Remove any rows with no DFA at all */
1100 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
1102 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
1108 * Insert a new row into the distribution formula selection form
1110 this._addDistribFormulaRow = function() {
1113 if (!self.distribForms) {
1114 // no formulas, hide the form
1115 openils.Util.hide('acq-lit-distrib-formula-tbody');
1119 if(!this.distribFormulaTemplate)
1120 this.distribFormulaTemplate =
1121 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
1123 var row = this.distribFormulaTemplate.cloneNode(true);
1124 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
1126 this.dfSelector = new dijit.form.FilteringSelect(
1127 {"labelAttr": "dynLabel", "labelType": "html"},
1128 nodeByName("selector", row)
1130 this._updateFormulaStore();
1131 this.dfSelector.fetchProperties =
1132 {"sort": [{"attribute": "use_count", "descending": true}]};
1134 var apply = new dijit.form.Button(
1135 {"label": localeStrings.APPLY},
1136 nodeByName('set_button', row)
1139 var reset = new dijit.form.Button(
1140 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
1141 nodeByName("reset_button", row)
1144 dojo.connect(apply, 'onClick',
1146 var form_id = self.dfSelector.attr("value");
1147 if(!form_id) return;
1148 self._applyDistribFormula(form_id);
1149 reset.attr("disabled", false);
1153 dojo.connect(reset, 'onClick',
1155 self.restoreCopyFieldsBeforeDF();
1156 self.virtDfaCounts = {};
1157 self.virtDfaId = -1;
1159 self._updateFormulaStore();
1160 self._removeAllDistribAppliedVirtual();
1161 reset.attr("disabled", "true");
1168 * Applies a distrib formula to the current set of copies
1170 this._applyDistribFormula = function(formula) {
1171 if(!formula) return;
1173 formula = this.distribForms.filter(
1174 function(form) { return form.id() == formula; }
1177 var copyRows = dojo.query('tr', self.copyTbody);
1179 if (this.dfeOffset >= copyRows.length) {
1180 alert(localeStrings.OUT_OF_COPIES);
1184 var entries_applied = 0;
1186 var rowIndex = this.dfeOffset;
1187 rowIndex < copyRows.length;
1191 var row = copyRows[rowIndex];
1192 var copy_id = row.getAttribute('copy_id');
1193 var copyWidgets = this.copyWidgetCache[copy_id];
1194 var entryIndex = this.dfeOffset;
1197 // find the correct entry for the current row
1198 dojo.forEach(formula.entries(),
1201 entryIndex += e.item_count();
1202 if(entryIndex > rowIndex)
1210 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
1211 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
1214 this.saveCopyFieldsBeforeDF(copy_id);
1215 this._copy_fields_for_acqdf.forEach(
1217 if(entry[field]()) {
1218 copyWidgets[field].attr('value', (entry[field]()));
1225 if (entries_applied) {
1226 this.virtDfaCounts[formula.id()] =
1227 ++(this.virtDfaCounts[formula.id()]) || 1;
1228 this._updateFormulaStore();
1229 this._drawDistribAppliedUnit(
1231 var dfa = new acqdfa();
1232 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
1235 this.dfeOffset += entries_applied;
1240 * This function updates the DF store for the dropdown so that use_counts
1241 * can reflect DF applications from this session before they're saved
1244 this._updateFormulaStore = function() {
1245 this.dfSelector.store = new dojo.data.ItemFileReadStore(
1247 "data": self._labelFormulasWithCounts(
1248 acqdf.toStoreData(self.distribForms)
1254 this.saveCopyFieldsBeforeDF = function(copy_id) {
1256 if (!this.oldCopyWidgetCache[copy_id]) {
1257 var copyWidgets = this.copyWidgetCache[copy_id];
1259 this.oldCopyWidgetCache[copy_id] = {};
1260 this._copy_fields_for_acqdf.forEach(
1262 self.oldCopyWidgetCache[copy_id][f] =
1263 copyWidgets[f].attr("value");
1269 this.restoreCopyFieldsBeforeDF = function() {
1271 for (var copy_id in this.oldCopyWidgetCache) {
1272 this._copy_fields_for_acqdf.forEach(
1274 self.copyWidgetCache[copy_id][f].attr(
1275 "value", self.oldCopyWidgetCache[copy_id][f]
1282 this._labelFormulasWithCounts = function(store_data) {
1283 for (var key in store_data.items) {
1284 var obj = store_data.items[key];
1285 obj.use_count = Number(obj.use_count); /* needed for sorting */
1287 if (this.virtDfaCounts[obj.id])
1288 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
1290 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
1291 obj.use_count + "]</span> " + obj.name;
1297 * This method formerly would not refetch the DF formulas if they'd been
1298 * loaded already, but now it always re-fetches, since use_count changes.
1300 /** TODO: port distrib-formula selector to autofieldwidget+pcrud/dojo store */
1301 this._fetchDistribFormulas = function(onload) {
1302 fieldmapper.standardRequest(
1304 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
1307 "params": [openils.User.authtoken, 0, 500],
1308 "oncomplete": function(r) {
1309 self.distribForms = openils.Util.readResponse(r);
1310 if(!self.distribForms || self.distribForms.length == 0) {
1311 self.distribForms = [];
1313 self._addDistribFormulaRow();
1320 this._drawBatchCopyWidgets = function() {
1321 var row = this.copyBatchRow;
1322 dojo.forEach(liDetailBatchFields,
1324 if(self.copyBatchRowDrawn) {
1325 self.copyBatchWidgets[field].attr('value', null);
1327 var widget = new openils.widget.AutoFieldWidget({
1330 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1331 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1332 searchFilter : (field == 'fund') ? {"active": "t"} : null,
1333 parentNode : dojo.query('[name='+field+']', row)[0],
1334 orgLimitPerms : ['CREATE_PICKLIST'],
1337 "labelType": (field == "fund") ? "html" : null
1339 noCache: (field == "fund"),
1344 if (field == "fund" && w.store)
1345 self._ensureCSSFundClasses(w.store);
1346 self.copyBatchWidgets[field] = w;
1349 if (field == "fund") {
1351 widget.widget, "onChange", function(val) {
1352 self._updateFundSelectorStyle(widget, val);
1359 this.copyBatchRowDrawn = true;
1362 this.batchCopyUpdate = function() {
1364 for(var k in this.copyWidgetCache) {
1365 var cache = this.copyWidgetCache[k];
1366 dojo.forEach(liDetailBatchFields, function(f) {
1367 var newval = self.copyBatchWidgets[f].attr('value');
1368 if(newval) cache[f].attr('value', newval);
1373 this._drawCopies = function(li) {
1376 // this button sets the total number of copies for a given lineitem
1377 acqLitAddCopyCount.onClick = function() {
1378 var count = acqLitCopyCountInput.attr('value');
1381 while(self.copyCount() < count)
1384 // delete rows if necessary
1385 var diff = self.copyCount() - count;
1387 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
1388 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
1389 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
1391 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1397 if(li.lineitem_details().length > 0) {
1398 dojo.forEach(li.lineitem_details(),
1400 self.addCopy(li, copy);
1408 this.copyCount = function() {
1410 for(var id in this.copyCache) {
1411 if(!this.copyCache[id].isdeleted())
1417 this.virtCopyId = -1;
1418 this.addCopy = function(li, copy) {
1419 var row = this.copyRow.cloneNode(true);
1420 this.copyTbody.appendChild(row);
1424 copy = new fieldmapper.acqlid();
1426 copy.id(this.virtCopyId--);
1427 copy.lineitem(li.id());
1430 this.copyCache[copy.id()] = copy;
1431 row.setAttribute('copy_id', copy.id());
1432 self.copyWidgetCache[copy.id()] = {};
1434 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1436 dojo.forEach(liDetailFields,
1439 if (field == "fund") {
1440 searchFilter = (copy.fund() ?
1441 {"-or": {"active": "t", "id": copy.fund()}} :
1444 searchFilter = null;
1447 var readOnly = false;
1449 // TODO: Add support for changing the owning_lib after real copies have been made.
1450 // owning_lib is order data as much as its item data
1451 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
1455 // TODO: add support for changing the fund after debits have been created
1456 // Note: invoicing allows the change
1457 if(copy.fund_debit() && field == 'fund') {
1461 var widget = new openils.widget.AutoFieldWidget({
1464 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1465 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1466 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1467 searchFilter : searchFilter,
1468 noCache: (field == "fund"),
1470 parentNode : dojo.query('[name='+field+']', row)[0],
1471 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
1472 readOnly : readOnly,
1473 orgDefaultsToWs : true
1477 // make sure we capture the value from any async widgets
1480 if (field == "fund" && w.store)
1481 self._ensureCSSFundClasses(w.store);
1484 copy[field](ww.getFormattedValue())
1486 self.copyWidgetCache[copy.id()][field] = w;
1488 dojo.connect(w, 'onChange',
1490 if (field == "fund")
1491 self._updateFundSelectorStyle(widget, val);
1493 if (!readOnly && (copy.isnew() || val != copy[field]())) {
1494 // prevent setting ischanged() automatically on widget load for existing copies
1495 copy[field](widget.getFormattedValue())
1496 copy.ischanged(true);
1505 this.updateLidState(copy, row);
1508 this._ensureCSSFundClass = function(id) {
1509 if (!this.fundStyleSheet) {
1511 "style", {"type": "text/css"},
1512 document.getElementsByTagName("head")[0], "last"
1514 this.fundStyleSheet = document.styleSheets[
1515 document.styleSheets.length - 1
1519 var cn = "fund_" + id;
1520 if (!this.haveFundClass[cn]) {
1521 fieldmapper.standardRequest(
1522 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
1524 "params": [openils.User.authtoken, id],
1526 "oncomplete": function(r) {
1527 r = openils.Util.readResponse(r);
1528 self.fundBalanceState[id] = r;
1530 if (r[0] /* stop */)
1531 style = fundStyles.stop;
1532 else if (r[1] /* warning */)
1533 style = fundStyles.warning;
1534 self.fundStyleSheet.insertRule(
1535 "." + cn + " { " + style + " }",
1536 self.fundStyleSheet.cssRules.length
1538 self.haveFundClass[cn] = true;
1545 this._ensureCSSFundClasses = function(store) {
1547 "query": {"id": "*"},
1548 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
1552 this._updateFundSelectorStyle = function(widget, fund_id) {
1553 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
1554 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
1557 this.updateLidState = function(copy, row) {
1558 if (typeof(row) == "undefined") {
1560 'tr[copy_id="' + copy.id() + '"]', this.copyTbody
1565 var recv_link = nodeByName("receive", row);
1566 var unrecv_link = nodeByName("unreceive", row);
1567 var del_link = nodeByName("delete", row);
1568 var cxl_link = nodeByName("cancel", row);
1569 var claim_link = nodeByName("claim", row);
1570 var cxl_reason_link = nodeByName("cancel_reason", row);
1572 if (copy.cancel_reason()) {
1573 openils.Util.hide(del_link.parentNode);
1574 openils.Util.hide(recv_link);
1575 openils.Util.hide(unrecv_link);
1576 openils.Util.hide(cxl_link);
1577 openils.Util.hide(claim_link);
1579 /* XXX the following may leak memory in a long lived table: dijits may not get destroyed... not positive. revisit. */
1580 var holds_reason = dojo.create(
1582 "style": "border-bottom: 1px dashed #000;",
1583 "innerHTML": "Cancelled" /* XXX [sic] and i18n */
1584 }, cxl_reason_link, "only"
1588 "label": "<em>" + copy.cancel_reason().label() +
1589 "</em><br />" + copy.cancel_reason().description(),
1590 "connectId": [holds_reason]
1591 }, dojo.create("span", null, cxl_reason_link, "last")
1593 openils.Util.show(cxl_reason_link, "inline");
1594 } else if (this.isPO) {
1595 /* Only using this in one place so far, but may want it for better
1596 * decisions on when to display certain controls. */
1597 var li_state = this.liCache[copy.lineitem()].state();
1599 openils.Util.hide(del_link.parentNode);
1600 openils.Util.hide(cxl_reason_link);
1602 /* Avoid showing (un)receive links, cancel links, for virt copies */
1603 if (copy.id() > 0) {
1604 if (copy.recv_time()) {
1605 openils.Util.hide(cxl_link);
1606 openils.Util.hide(recv_link);
1607 openils.Util.hide(claim_link);
1609 openils.Util.show(unrecv_link, "inline");
1610 unrecv_link.onclick = function() {
1611 if (confirm(localeStrings.UNRECEIVE_LID))
1612 self.issueReceive(copy, /* rollback */ true);
1615 openils.Util.hide(unrecv_link);
1617 if (this.claimEligibleLid[copy.id()]) {
1618 openils.Util.show(claim_link, "inline");
1619 claim_link.onclick = function() {
1620 self.claimDialog.show(
1621 self.liCache[copy.lineitem()], copy.id()
1625 openils.Util.hide(claim_link);
1628 openils.Util[li_state == "on-order" ? "show" : "hide"](
1631 openils.Util.show(cxl_link, "inline");
1632 recv_link.onclick = function() {
1633 if (self.checkLiAlerts(copy.lineitem()))
1634 self.issueReceive(copy);
1636 cxl_link.onclick = function() {
1637 self.cancelLid(copy.id());
1641 openils.Util.hide(cxl_link);
1642 openils.Util.hide(unrecv_link);
1643 openils.Util.hide(recv_link);
1644 openils.Util.hide(claim_link);
1647 openils.Util.hide(unrecv_link);
1648 openils.Util.hide(recv_link);
1649 openils.Util.hide(cxl_reason_link);
1650 openils.Util.hide(claim_link);
1652 del_link.onclick = function() { self.deleteCopy(row) };
1653 openils.Util.show(del_link.parentNode);
1657 this.cancelLid = function(lid_id) {
1658 lidCancelDialog._lid_id = lid_id;
1659 openils.Util.show(lidCancelDialog.domNode.parentNode);
1660 lidCancelDialog.show();
1661 if (!lidCancelDialog._prepared) {
1662 var widget = new openils.widget.AutoFieldWidget({
1663 "fmField": "cancel_reason",
1664 "fmClass": "acqlid",
1665 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
1666 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1671 acqLidCancelButton.onClick = function() {
1672 if (w.attr("value")) {
1673 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
1675 lidCancelDialog._lid_id,
1679 lidCancelDialog.hide();
1682 lidCancelDialog._prepared = true;
1688 this._cancelLid = function(lid_id, reason) {
1689 fieldmapper.standardRequest(
1690 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
1691 "params": [openils.User.authtoken, lid_id, reason],
1693 "onresponse": function(r) {
1694 if (r = openils.Util.readResponse(r)) {
1696 for (var id in r.lid) {
1697 /* actually this should only iterate once */
1698 self.copyCache[id].cancel_reason(
1699 r.lid[id].cancel_reason
1701 self.updateLidState(self.copyCache[id]);
1710 this._confirmAlert = function(li, lin) {
1712 dojo.string.substitute(
1713 localeStrings.CONFIRM_LI_ALERT, [
1714 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1715 "title", "lineitem_marc_attr_definition"
1717 lin.alert_text().code(),
1718 lin.alert_text().description() || "",
1725 this.checkLiAlerts = function(li_id) {
1726 var li = this.liCache[li_id];
1728 var alert_notes = li.lineitem_notes().filter(
1729 function(o) { return Boolean(o.alert_text()); }
1732 /* this is _intentionally_ not done in a call to forEach() ... */
1733 for (var i = 0; i < alert_notes.length; i++) {
1734 if (this.noteAcks[alert_notes[i].id()])
1736 else if (!this._confirmAlert(li, alert_notes[i]))
1739 this.noteAcks[alert_notes[i].id()] = true;
1745 this.deleteCopy = function(row) {
1746 var copy = this.copyCache[row.getAttribute('copy_id')];
1747 copy.isdeleted(true);
1749 delete this.copyCache[copy.id()];
1750 this.copyTbody.removeChild(row);
1753 this._virtDfaCountsAsList = function() {
1755 for (var key in this.virtDfaCounts) {
1756 for (var i = 0; i < this.virtDfaCounts[key]; i++)
1762 this.confirmBreachedCopyFunds = function(copies) {
1763 var stop = 0, warning = 0;
1767 var state = self.fundBalanceState[o.fund()];
1768 if (state[0] /* stop */)
1770 else if (state[1] /* warning */)
1777 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
1778 } else if (warning) {
1779 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
1784 this.saveCopyChanges = function(liId) {
1790 for(var id in this.copyCache) {
1791 var c = this.copyCache[id];
1792 if(!c.isdeleted()) total++;
1793 if(c.isnew() || c.ischanged() || c.isdeleted()) {
1794 if(c.id() < 0) c.id(null);
1800 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
1803 if (copies.length > 0) {
1804 if (!this.confirmBreachedCopyFunds(copies))
1807 if (typeof(this._copy_count_cb) == "function")
1808 this._copy_count_cb(liId, total);
1810 openils.Util.show("acq-lit-update-copies-progress");
1811 fieldmapper.standardRequest(
1812 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1814 params: [openils.User.authtoken, copies],
1815 onresponse: function(r) {
1816 var res = openils.Util.readResponse(r);
1817 litUpdateCopiesProgress.update(res);
1819 oncomplete: function() {
1820 self.drawCopies(liId, true /* force_fetch */);
1821 openils.Util.hide("acq-lit-update-copies-progress");
1827 var dfa_list = this._virtDfaCountsAsList();
1828 if (dfa_list.length > 0) {
1829 fieldmapper.standardRequest(
1831 "open-ils.acq.distribution_formula.record_application"],
1834 "params": [openils.User.authtoken, dfa_list, liId],
1835 "onresponse": function(r) {
1836 var res = openils.Util.readResponse(r);
1837 if (res && res.length < dfa_list.length)
1838 alert(localeStrings.DFA_NOT_ALL);
1842 this.virtDfaCounts = {};
1846 this._updateCreatePoPrepayCheckbox = function(prepay) {
1847 var prepay = openils.Util.isTrue(prepay);
1848 this._prepayRequiredByVendor = prepay;
1849 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
1852 this._confirmPoPrepaySituation = function() {
1853 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
1854 if (want_prepay != this._prepayRequiredByVendor) {
1857 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
1858 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
1865 this.applySelectedLiAction = function(action) {
1869 case 'delete_selected':
1870 this._deleteLiList(self.getSelected());
1873 case 'create_order':
1874 this._loadPOSelect();
1875 acqLitPoCreateDialog.show();
1878 case 'save_picklist':
1879 acqLitSavePlDialog.show();
1882 case 'selector_ready':
1884 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
1885 acqLitChangeLiStateDialog.show();
1893 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
1900 case 'rollback_receive_po':
1901 this.rollbackPoReceive();
1904 case 'create_assets':
1905 this.createAssets();
1908 case 'export_attr_list':
1909 this.chooseExportAttr();
1912 case 'batch_apply_funds':
1913 this.applyBatchLiFunds();
1916 case 'add_brief_record':
1918 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
1920 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
1924 case "cancel_lineitems":
1925 this.maybeCancelLineitems();
1928 case "change_claim_policy":
1929 var li_list = this.getSelected();
1930 this.claimPolicyPicker.attr("value", null);
1931 liClaimPolicyDialog.show();
1932 liClaimPolicySave.onClick = function() {
1933 self.changeClaimPolicy(
1935 self.claimPolicyPicker.attr("value"),
1939 self.setClaimPolicyControl(li);
1940 self.reconsiderClaimControl(li);
1943 liClaimPolicyDialog.hide();
1951 this.changeClaimPolicy = function(li_list, value, callback) {
1953 function(li) { li.claim_policy(value); }
1955 fieldmapper.standardRequest(
1956 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
1957 "params": [openils.User.authtoken, li_list],
1959 "oncomplete": function(r) {
1960 r = openils.Util.readResponse(r);
1961 if (callback) callback(r);
1967 this.createAssets = function() {
1968 if(!this.isPO) return;
1969 if(!confirm(localeStrings.CREATE_PO_ASSETS_CONFIRM)) return;
1970 this.show('acq-lit-progress-numbers');
1972 fieldmapper.standardRequest(
1973 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
1975 params: [this.authtoken, this.isPO],
1976 onresponse: function(r) {
1977 var resp = openils.Util.readResponse(r);
1978 self._updateProgressNumbers(resp, true);
1984 this.maybeCancelLineitems = function() {
1985 openils.Util.show("acq-lit-cancel-reason", "inline");
1986 if (!acqLitCancelLineitemsButton._prepared) {
1987 var widget = new openils.widget.AutoFieldWidget({
1988 "fmField": "cancel_reason",
1990 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
1991 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1996 acqLitCancelLineitemsButton.onClick = function() {
1997 if (w.attr("value")) {
1998 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
1999 self._cancelLineitems(w.attr("value"));
2001 openils.Util.hide("acq-lit-cancel-reason");
2004 acqLitCancelLineitemsButton._prepared = true;
2010 this._cancelLineitems = function(reason) {
2011 var id_list = this.getSelected().map(function(o) { return o.id(); });
2012 fieldmapper.standardRequest(
2013 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
2014 "params": [openils.User.authtoken, id_list, reason],
2016 "onresponse": function(r) {
2017 if (r = openils.Util.readResponse(r)) {
2019 for (var id in r.li) {
2020 self.liCache[id].state(r.li[id].state);
2021 self.liCache[id].cancel_reason(
2022 r.li[id].cancel_reason
2024 self.updateLiState(self.liCache[id]);
2027 if (r.lid && self.copyCache) {
2028 for (var id in r.lid) {
2029 if (self.copyCache[id]) {
2030 self.copyCache[id].cancel_reason(
2031 r.lid[id].cancel_reason
2033 self.updateLidState(self.copyCache[id]);
2043 this.chooseExportAttr = function() {
2044 if (!acqLitExportAttrSelector._li_setup) {
2046 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
2048 "data": acqlimad.toStoreData(
2050 "acqlimad", {"code": li_exportable_attrs}
2055 acqLitExportAttrSelector.setValue();
2056 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
2057 acqLitExportAttrSelector._li_setup = true;
2059 openils.Util.show("acq-lit-export-attr-holder", "inline");
2062 this.exportAttrList = function() {
2063 var attr_def = acqLitExportAttrSelector.item;
2064 var li_list = this.getSelected();
2065 var value_list = li_list.map(
2067 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2068 attr_def.code, "lineitem_marc_attr_definition"
2071 ).filter(function(attr) { return Boolean(attr); });
2073 if (value_list.length > 0) {
2074 if (value_list.length < li_list.length) {
2076 dojo.string.substitute(
2077 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
2084 openils.XUL.contentToFileSaveDialog(
2085 value_list.join("\n"),
2086 localeStrings.EXPORT_SAVE_DIALOG_TITLE
2092 alert(dojo.string.substitute(
2093 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
2097 openils.Util.hide("acq-lit-export-attr-holder");
2100 this.printPO = function() {
2101 if(!this.isPO) return;
2102 progressDialog.show(true);
2103 fieldmapper.standardRequest(
2104 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
2106 params: [this.authtoken, this.isPO, 'html'],
2107 oncomplete: function(r) {
2108 progressDialog.hide();
2109 var evt = openils.Util.readResponse(r);
2110 if(evt && evt.template_output()) {
2111 openils.Util.printHtmlString(evt.template_output().data());
2119 this.receivePO = function() {
2120 if (!this.isPO) return;
2122 for (var id in this.liCache) {
2123 /* assumption: liCache reflects exactly the
2124 * set of LIs that belong to our PO */
2125 if (this.liCache[id].state() != "received" &&
2126 !this.checkLiAlerts(id)) return;
2129 this.show('acq-lit-progress-numbers');
2131 fieldmapper.standardRequest(
2132 ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
2134 params: [this.authtoken, this.isPO],
2135 onresponse : function(r) {
2136 var resp = openils.Util.readResponse(r);
2137 self._updateProgressNumbers(resp, true);
2143 this.issueReceive = function(obj, rollback) {
2144 /* (For now) there shall be no marking LI or LIDs (un)received
2145 * except from the actual "view PO" interface. */
2146 if (!this.isPO) return;
2149 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
2151 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
2153 progressDialog.show(true);
2154 fieldmapper.standardRequest(
2155 ["open-ils.acq", method], {
2157 "params": [this.authtoken, obj.id()],
2158 "onresponse": function(r) {
2159 if (r = openils.Util.readResponse(r)) {
2160 self.fetchClaimInfo(
2161 part == "lineitem" ? obj.id() : obj.lineitem(),
2163 function() { self.handleReceive(r); }
2165 progressDialog.hide();
2173 * Handles the responses from receive and rollback ML calls.
2175 this.handleReceive = function(resp) {
2178 for (var li_id in resp.li) {
2179 for (var key in resp.li[li_id])
2180 self.liCache[li_id][key](resp.li[li_id][key]);
2181 self.updateLiState(self.liCache[li_id]);
2185 if (typeof(self.poUpdateCallback) == "function")
2186 self.poUpdateCallback(resp.po);
2189 for (var lid_id in resp.lid) {
2190 for (var key in resp.lid[lid_id])
2191 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
2192 self.updateLidState(self.copyCache[lid_id]);
2198 this.rollbackPoReceive = function() {
2199 if(!this.isPO) return;
2200 if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
2201 this.show('acq-lit-progress-numbers');
2203 fieldmapper.standardRequest(
2204 ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
2206 params: [this.authtoken, this.isPO],
2207 onresponse : function(r) {
2208 var resp = openils.Util.readResponse(r);
2209 self._updateProgressNumbers(resp, true);
2215 this._updateProgressNumbers = function(resp, reloadOnComplete) {
2217 dojo.byId('acq-pl-lit-li-processed').innerHTML = resp.li;
2218 dojo.byId('acq-pl-lit-lid-processed').innerHTML = resp.lid;
2219 dojo.byId('acq-pl-lit-debits-processed').innerHTML = resp.debits_accrued;
2220 dojo.byId('acq-pl-lit-bibs-processed').innerHTML = resp.bibs;
2221 dojo.byId('acq-pl-lit-indexed-processed').innerHTML = resp.indexed;
2222 dojo.byId('acq-pl-lit-copies-processed').innerHTML = resp.copies;
2223 if(resp.complete && reloadOnComplete)
2224 location.href = location.href;
2228 this._createPO = function(fields) {
2229 this.show('acq-lit-progress-numbers');
2230 var po = new fieldmapper.acqpo();
2231 po.provider(this.createPoProviderSelector.attr('value'));
2232 po.ordering_agency(this.createPoAgencySelector.attr('value'));
2233 po.prepayment_required(fields.prepayment_required[0] ? true : false);
2235 var selected = this.getSelected( (fields.create_from == 'all') );
2236 if(selected.length == 0) return;
2238 var max = selected.length * 3;
2241 fieldmapper.standardRequest(
2242 ['open-ils.acq', 'open-ils.acq.purchase_order.create'],
2245 openils.User.authtoken,
2248 lineitems : selected.map(function(li) { return li.id() }),
2249 create_assets : fields.create_assets[0],
2253 onresponse : function(r) {
2254 var resp = openils.Util.readResponse(r);
2255 self._updateProgressNumbers(resp);
2257 location.href = oilsBasePath + '/acq/po/view/' + resp.purchase_order.id();
2263 this.batchFundWidget = null;
2265 this.applyBatchLiFunds = function() {
2267 var liIds = this.getSelected().map(function(li) { return li.id(); });
2268 if(liIds.length == 0) return; // warn?
2271 batchFundUpdateDialog.show();
2273 if(!this.batchFundWidget) {
2274 this.batchFundWidget = new openils.widget.AutoFieldWidget({
2276 selfReference : true,
2277 labelFormat : fundLabelFormat,
2278 searchFormat : fundSearchFormat,
2279 searchFilter : {"active": "t"},
2280 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
2281 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2282 dijitArgs : { "required": true, "labelType": "html" },
2285 this.batchFundWidget.build();
2288 dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
2289 dojo.connect(batchFundUpdateSubmit, 'onClick',
2292 // TODO: call .dry_run first to test thresholds
2293 fieldmapper.standardRequest(
2294 ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
2297 openils.User.authtoken,
2299 self.batchFundWidget.widget.attr('value')
2301 oncomplete : function(r) {
2302 var resp = openils.Util.readResponse(r);
2304 location.href = location.href;
2313 this._deleteLiList = function(list, idx) {
2314 if(idx == null) idx = 0;
2315 if(idx >= list.length) return;
2316 var liId = list[idx].id();
2317 fieldmapper.standardRequest(
2319 this.isPO ? 'open-ils.acq.purchase_order.lineitem.delete' : 'open-ils.acq.picklist.lineitem.delete'],
2321 params: [openils.User.authtoken, liId],
2322 oncomplete: function(r) {
2323 self.removeLineitem(liId);
2324 self._deleteLiList(list, ++idx);
2330 this.editOrderMarc = function(li) {
2332 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
2333 to true in about:config */
2335 if(!openils.XUL.enableXPConnect()) return;
2337 if(openils.XUL.isXUL()) {
2338 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
2340 win = window.open('/xul/server/cat/marcedit.xul');
2344 record : {marc : li.marc(), "rtype": "bre"},
2346 label: 'Save Record', // XXX I18N
2347 func: function(xmlString) {
2349 fieldmapper.standardRequest(
2350 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
2352 params: [openils.User.authtoken, li],
2353 oncomplete: function(r) {
2354 openils.Util.readResponse(r);
2356 self.drawInfo(li.id())
2362 'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
2363 'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
2367 this._savePl = function(values) {
2369 var selected = this.getSelected( (values.which == 'all') );
2370 openils.Util.show('acq-lit-generic-progress');
2372 if(values.new_name) {
2373 openils.acq.Picklist.create(
2374 {name: values.new_name},
2376 self._updateLiList(id, selected, 0,
2378 location.href = oilsBasePath + '/acq/picklist/view/' + id;
2382 } else if(values.existing_pl) {
2383 // update lineitems to use an existing picklist
2384 self._updateLiList(values.existing_pl, selected, 0,
2386 location.href = oilsBasePath + '/acq/picklist/view/' + values.existing_pl;
2391 this._updateLiState = function(values, state) {
2393 var selected = this.getSelected( (values.which == 'all') );
2394 if(!selected.length) return;
2395 dojo.forEach(selected, function(li) {li.state(state);});
2396 self._updateLiList(null, selected, 0,
2397 // TODO consider inline updates for efficiency
2398 function() { location.href = location.href }
2402 this._updateLiList = function(pl, list, idx, oncomplete) {
2403 if(idx >= list.length) return oncomplete();
2405 if(pl != null) li.picklist(pl);
2406 litGenericProgress.update({maximum: list.length, progress: idx});
2407 new openils.acq.Lineitem({lineitem:li}).update(
2409 self._updateLiList(pl, list, ++idx, oncomplete);
2414 this._loadPOSelect = function() {
2415 if (!this.createPoProviderSelector) {
2416 var widget = new openils.widget.AutoFieldWidget({
2417 "fmField": "provider",
2419 "searchFilter": {"active": "t"},
2420 "parentNode": dojo.byId("acq-lit-po-provider"),
2422 "onChange": function() {
2424 self._updateCreatePoPrepayCheckbox(
2425 this.item.prepayment_required()
2431 widget.build(function(w) { self.createPoProviderSelector = w; });
2434 if (!this.createPoAgencySelector) {
2435 var widget = new openils.widget.AutoFieldWidget({
2436 "fmField": "ordering_agency",
2438 "parentNode": dojo.byId("acq-lit-po-agency"),
2439 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2441 widget.build(function(w) { self.createPoAgencySelector = w; });
2445 this.showRealCopyEditUI = function(li) {
2450 this._fetchLineitem(li.id(),
2452 li = self.liCache[li.id()] = fullLi;
2456 id : li.lineitem_details().map(
2457 function(item) { return item.eg_copy_id() }
2461 oncomplete : function(r) {
2463 var r_list = openils.Util.readResponse( r );
2464 for (var i = 0; i < r_list.length; i++) {
2465 var copy = r_list[i];
2466 var volId = copy.call_number();
2467 var volume = self.volCache[volId];
2469 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2471 copy.call_number(volume);
2472 copyList.push(copy);
2475 xulG.volume_item_creator( { 'existing_copies' : copyList } );
2478 alert('error in oncomplete: ' + E);
2487 this.drawBibFinder = function(li) {
2490 var liWrapper = new openils.acq.Lineitem({lineitem:li});
2493 ['isbn', 'upc', 'issn', 'title', 'author'],
2495 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
2497 if(field == 'title' || field == 'author') {
2498 query += field +':' + val + ' ';
2500 query += 'identifier|' + field + ':' + val + ' ';
2507 oilsBasePath + '/acq/lineitem/findbib?query=' + escape(query),
2508 '', 'resizable,scrollbars=1');
2510 win.window.recordFound = function(bibId) {
2513 var attrs = li.attributes();
2514 li.attributes(null);
2515 li.eg_bib_id(bibId);
2517 fieldmapper.standardRequest(
2518 ["open-ils.acq", "open-ils.acq.lineitem.update"],
2520 "params": [openils.User.authtoken, li],
2522 "oncomplete": function(r) {
2523 if(openils.Util.readResponse(r)) {
2524 location.href = location.href;