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 // sort the lineitem notes on edit_time
257 if(!li.lineitem_notes()) li.lineitem_notes([]);
259 var liWrapper = new openils.acq.Lineitem({lineitem:li});
260 var row = self.rowTemplate.cloneNode(true);
261 row.setAttribute('li', li.id());
262 var tds = dojo.query('[attr]', row);
263 dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
264 dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
267 liWrapper.findAttr("isbn", "lineitem_marc_attr_definition") ||
268 liWrapper.findAttr("upc", "lineitem_marc_attr_definition");
270 // XXX media prefix for added content
272 nodeByName("jacket", row).setAttribute(
273 "src", "/opac/extras/ac/jacket/small/" + identifier
277 nodeByName("liid", row).innerHTML += li.id();
280 openils.Util.show(nodeByName('catalog', row), 'inline');
281 nodeByName("catalog_link", row).onclick = this.generateMakeRecTab(li.eg_bib_id());
283 openils.Util.show(nodeByName('link_to_catalog', row), 'inline');
284 nodeByName("link_to_catalog_link", row).onclick = function() { self.drawBibFinder(li) };
287 nodeByName("worksheet_link", row).href =
288 oilsBasePath + "/acq/lineitem/worksheet/" + li.id();
290 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
291 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
292 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
294 if (!this.skipInitialEligibilityCheck)
298 function(full) { self.setClaimPolicyControl(full, row) },
302 this.updateLiNotesCount(li, row);
304 // show which PO this lineitem is a member of
305 if(li.purchase_order() && !this.isPO) {
307 this.poCache[li.purchase_order()] =
308 this.poCache[li.purchase_order()] ||
309 fieldmapper.standardRequest(
310 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
312 this.authtoken, li.purchase_order(), {
313 "flesh_price_summary": true,
314 "flesh_lineitem_count": true
317 if(po && !this.isMeta) {
318 openils.Util.show(nodeByName('po', row), 'inline');
319 var link = nodeByName('po_link', row);
320 link.setAttribute('href', oilsBasePath + '/acq/po/view/' + li.purchase_order());
321 link.innerHTML += po.name();
325 // show which picklist this lineitem is a member of
326 if(li.picklist() && (this.isPO || this.isMeta || this.isUni)) {
328 this.plCache[li.picklist()] =
329 this.plCache[li.picklist()] ||
330 fieldmapper.standardRequest(
331 ['open-ils.acq', 'open-ils.acq.picklist.retrieve.authoritative'],
332 {params: [this.authtoken, li.picklist()]});
334 if (pl.name() == "") {
335 openils.Util.show(nodeByName("bib_origin", row), "inline");
339 openils.Util.show(nodeByName('pl', row), 'inline');
340 var link = nodeByName('pl_link', row);
341 link.setAttribute('href', oilsBasePath + '/acq/picklist/view/' + li.picklist());
342 link.innerHTML += pl.name();
347 var countNode = nodeByName('count', row);
348 var count = li.item_count() || 0;
349 if (typeof(this._copy_count_cb) == "function") {
350 this._copy_count_cb(li.id(), count);
352 countNode.innerHTML = count;
353 countNode.id = 'acq-lit-copy-count-label-' + li.id();
356 var priceInput = dojo.query('[name=price]', row)[0];
357 priceInput.value = li.estimated_unit_price() || '';
358 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
360 // show either "mark received" or "unreceive" as appropriate
361 this.updateLiState(li, row);
363 if (!skip_final_placement) {
364 self.tbody.appendChild(row);
365 self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
371 this._liCountClaims = function(li) {
373 for (var i = 0; i < li.lineitem_details().length; i++)
374 total += li.lineitem_details()[i].claims().length;
378 this._findLiRow = function(li) {
379 return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
382 this.reconsiderClaimControl = function(li, row) {
383 if (!row) row = this._findLiRow(li);
384 var option = nodeByName("action_manage_claims", row);
385 var eligible = this.claimEligibleLidByLi[li.id()].length;
386 var count = this._liCountClaims(li);
388 option.disabled = !(count || eligible);
390 dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
391 option.onclick = function() { self.claimDialog.show(li); };
394 this.clearEligibility = function(li) {
395 this.claimEligibleLidByLi[li.id()] = [];
397 if (li.lineitem_details()) {
398 li.lineitem_details().forEach(
399 function(lid) { delete self.claimEligibleLid[lid.id()]; }
403 if (this.copyCache) {
405 for (var k in this.copyCache) {
406 if (this.copyCache[k].lineitem() == li.id())
410 function(k) { delete self.claimEligibleLid[k]; }
415 this.checkClaimEligibility = function(li, callback, row) {
416 /* Assume always eligible, i.e. from this interface we don't care about
417 * claim eligibility any more. this is where the user would force a
419 this.clearEligibility(li);
420 this.claimEligibleLidByLi[li.id()] = li.lineitem_details().map(
421 function(lid) { return lid.id(); }
423 li.lineitem_details().forEach(
424 function(lid) { self.claimEligibleLid[lid.id()] = true; }
426 this.reconsiderClaimControl(li, row);
427 if (callback) callback(li);
429 this.clearEligibility(li);
430 fieldmapper.standardRequest(
431 ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
432 "params": [openils.User.authtoken, {"lineitem": li.id()}],
434 "onresponse": function(r) {
435 if (r = openils.Util.readResponse(r)) {
436 self.claimEligibleLidByLi[li.id()].push(
439 self.claimEligibleLid[r.lineitem_detail()] = true;
442 "oncomplete": function() {
443 self.reconsiderClaimControl(li, row);
444 if (typeof(callback) == "function")
452 this.updateLiNotesCount = function(li, row) {
453 if (!row) row = this._findLiRow(li);
455 var has_notes = (li.lineitem_notes().filter(
456 function(o) { return Boolean (o.alert_text()); }
459 /* U+2691 is the code point for a filled-in flag character */
460 nodeByName("notes_alert_flag", row).innerHTML =
461 has_notes ? "⚑" : "";
462 nodeByName("noteslink", row).style.fontStyle =
463 has_notes ? "italic" : "normal";
464 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
467 /* XXX NOT related to _updateLiState(). rethink */
468 this.updateLiState = function(li, row) {
469 if (!row) row = this._findLiRow(li);
471 var actReceive = nodeByName("action_mark_recv", row);
472 var actUnRecv = nodeByName("action_mark_unrecv", row);
473 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
474 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
476 var actNewInvoice = nodeByName('action_new_invoice', row);
477 var actLinkInvoice = nodeByName('action_link_invoice', row);
478 var actViewInvoice = nodeByName('action_view_invoice', row);
480 nodeByName('action_view_history', row).onclick =
481 function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
483 var state_cell = nodeByName("li_state", row);
485 if (li.state() == "cancelled") {
486 if (typeof li.cancel_reason() == "object") {
487 var holds_state = dojo.create(
489 "style": "border-bottom: 1px dashed #000;",
490 "innerHTML": li.state()
491 }, state_cell, "only"
495 "label": "<em>" + li.cancel_reason().label() +
496 "</em><br />" + li.cancel_reason().description(),
497 "connectId": [holds_state]
498 }, dojo.create("span", null, state_cell, "last")
501 state_cell.innerHTML = li.state(); // TODO i18n state labels
504 state_cell.innerHTML = li.state(); // TODO i18n state labels
508 /* handle row coloring for based on LI state */
509 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
510 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
512 /* handle links that appear/disappear based on whether LI is received */
516 actNewInvoice.onclick = function() {
517 location.href = oilsBasePath + '/acq/invoice/view?create=1&attach_li=' + li.id();
518 nodeByName("action_none", row).selected = true;
520 actLinkInvoice.onclick = function() {
521 if (!self.invoiceLinkDialogManager) {
522 self.invoiceLinkDialogManager =
523 new InvoiceLinkDialogManager("li");
525 self.invoiceLinkDialogManager.target = li;
526 acqLitLinkInvoiceDialog.show();
527 nodeByName("action_none", row).selected = true;
529 actViewInvoice.onclick = function() {
530 location.href = oilsBasePath +
531 "/acq/search/unified?so=" +
532 base64Encode({"jub":[{"id": li.id()}]}) +
534 nodeByName("action_none", row).selected = true;
537 actNewInvoice.disabled = false;
538 actLinkInvoice.disabled = false;
539 actViewInvoice.disabled = false;
543 actReceive.disabled = false;
544 actReceive.onclick = function() {
545 if (self.checkLiAlerts(li.id()))
546 self.issueReceive(li);
547 nodeByName("action_none", row).selected = true;
552 actUnRecv.disabled = false;
553 actUnRecv.onclick = function() {
554 if (confirm(localeStrings.UNRECEIVE_LI))
555 self.issueReceive(li, /* rollback */ true);
556 nodeByName("action_none", row).selected = true;
558 // TODO we should allow editing before receipt, in which case the
559 // test should be "if 1 or more real (acp) copies exist
560 actUpdateBarcodes.disabled = false;
561 actUpdateBarcodes.onclick = function() {
562 self.showRealCopyEditUI(li);
563 nodeByName("action_none", row).selected = true;
565 actHoldingsMaint.disabled = false;
566 actHoldingsMaint.onclick = self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
574 this._setAlertStore = function() {
575 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
577 "data": acqliat.toStoreData(
579 "acqliat", {"id": {"!=": null}}
584 acqLitAlertAlertText.setValue(); /* make the store "live" */
585 acqLitAlertAlertText._store_ready = true;
589 * Draws and shows the lineitem notes pane
591 this.drawLiNotes = function(li) {
594 if (!acqLitAlertAlertText._store_ready)
595 this._setAlertStore();
598 li.lineitem_notes().sort(
600 if(a.edit_time() < b.edit_time()) return 1;
606 while(this.liNotesTbody.childNodes[0])
607 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
610 acqLitCreateNoteSubmit.onClick = function() {
611 var value = acqLitCreateNoteText.attr('value');
613 var note = new fieldmapper.acqlin();
616 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
619 note.lineitem(li.id());
621 self.updateLiNotes(li, note);
622 acqLitCreateNoteVendorPublic.attr("checked", false);
623 acqLitCreateNoteText.attr("value", "");
626 acqLitCreateAlertSubmit.onClick = function() {
627 if (!acqLitAlertAlertText.item) {
628 alert(localeStrings.ALERT_UNSELECTED);
632 var alert_text = new fieldmapper.acqliat().fromStoreItem(
633 acqLitAlertAlertText.item
635 var value = acqLitAlertNoteValue.attr("value") || "";
637 var note = new fieldmapper.acqlin();
639 note.lineitem(li.id());
641 note.alert_text(alert_text);
643 self.updateLiNotes(li, note);
646 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
650 * Draws a single lineitem note in the notes pane
652 this.addLiNote = function(li, note) {
653 if(note.isdeleted()) return;
655 var row = self.liNotesRow.cloneNode(true);
656 nodeByName("value", row).innerHTML = note.value();
657 var alert_node = nodeByName("alert_code", row);
658 if (note.alert_text()) {
659 alert_node.innerHTML = note.alert_text().code();
660 if (note.alert_text().description()) {
663 "connectId": [alert_node],
664 "label": note.alert_text().description()
665 }, dojo.create("span", null, alert_node, "after")
670 if (openils.Util.isTrue(note.vendor_public()))
671 nodeByName("vendor_public", row).innerHTML =
672 localeStrings.VENDOR_PUBLIC;
674 nodeByName("delete", row).onclick = function() {
675 note.isdeleted(true);
676 self.liNotesTbody.removeChild(row);
677 self.updateLiNotes(li);
680 if(note.edit_time()) {
681 nodeByName("edit_time", row).innerHTML =
682 dojo.date.locale.format(
683 dojo.date.stamp.fromISOString(note.edit_time()),
684 {formatLength:'short'});
687 self.liNotesTbody.appendChild(row);
691 * Updates any new/changed/deleted notes on the server
693 this.updateLiNotes = function(li, newNote) {
699 notes = li.lineitem_notes().filter(
701 if(note.ischanged() || note.isnew() || note.isdeleted())
707 if(notes.length == 0) return;
708 progressDialog.show();
710 fieldmapper.standardRequest(
711 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
713 params : [this.authtoken, notes],
714 onresponse : function(r) {
715 var resp = openils.Util.readResponse(r);
720 // remove the old changed notes
722 dojo.forEach(li.lineitem_notes(),
724 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
728 li.lineitem_notes(list);
731 progressDialog.hide();
732 self.updateLiNotesCount(li);
733 self.drawLiNotes(li);
737 progressDialog.update(resp);
738 var newnote = resp.note;
740 if(!newnote.isdeleted()) {
741 newnote.isnew(false);
742 newnote.ischanged(false);
743 li.lineitem_notes().push(newnote);
750 this.updateLiPrice = function(input, li) {
752 var price = input.value;
753 if(Number(price) == Number(li.estimated_unit_price())) return;
755 fieldmapper.standardRequest(
756 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
757 { async : false, // redundant w/ timeout
759 params : [this.authtoken, li.id(), price],
760 oncomplete : function(r) {
761 openils.Util.readResponse(r);
762 li.estimated_unit_price(price); // update local copy
768 this.removeLineitem = function(liId) {
769 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
770 delete this.liCache[liId];
771 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
774 this.drawInfo = function(liId) {
775 if (!this._isRelatedViewer) {
776 var d = dojo.byId("acq-lit-info-related");
777 if (!this.relCache[liId]) {
778 fieldmapper.standardRequest(
781 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
784 "params": [openils.User.authtoken, liId],
785 "onresponse": function(r) {
786 self.relCache[liId] = openils.Util.readResponse(r);
787 nodeByName("related_number", d).innerHTML =
790 self.relCache[liId] >1 ? "show" : "hide"
796 nodeByName("related_number", d).innerHTML = this.relCache[liId];
797 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
802 openils.acq.Lineitem.fetchAttrDefs(
804 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
809 this._fetchLineitem = function(liId, handler, force) {
811 var li = this.liCache[liId];
812 if(li && li.marc() && li.lineitem_details() && !force)
815 fieldmapper.standardRequest(
816 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
819 params: [self.authtoken, liId, {
821 flesh_cancel_reason: true,
822 flesh_li_details: true,
824 flesh_fund_debit: true }],
826 oncomplete: function(r) {
827 var li = openils.Util.readResponse(r);
828 self.liCache[liId] = li;
835 this._drawInfo = function(li) {
837 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
840 openils.Util.hide('acq-lit-marc-order-record-label');
841 openils.Util.hide(acqLitEditOrderMarc.domNode);
842 openils.Util.show('acq-lit-marc-real-record-label');
844 openils.Util.show('acq-lit-marc-order-record-label');
845 openils.Util.show(acqLitEditOrderMarc.domNode);
846 openils.Util.hide('acq-lit-marc-real-record-label');
849 this.drawMarcHTML(li);
850 this.infoTbody = dojo.byId('acq-lit-info-tbody');
853 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
854 while(this.infoTbody.childNodes[0])
855 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
857 for(var i = 0; i < li.attributes().length; i++) {
858 var attr = li.attributes()[i];
859 var row = this.infoRow.cloneNode(true);
861 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
862 var name = openils.acq.Lineitem.attrDefs[type].filter(
864 return (a.code() == attr.attr_name());
866 ).pop().description();
868 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
869 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
870 this.infoTbody.appendChild(row);
873 if (!this._isRelatedViewer) {
874 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
875 oilsBasePath + "/acq/lineitem/related/" + li.id();
880 this.generateMakeRecTab = function(bib_id,default_view, row) {
884 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
887 show_nav_buttons : true,
888 show_print_button : true,
889 opac_url : xulG.url_prefix(xulG.urls.opac_rdetail + '?r=' + bib_id),
890 default_view : default_view
894 if(row) nodeByName("action_none", row).selected = true;
898 this.drawMarcHTML = function(li) {
899 var params = [null, true, li.marc()];
901 params = [li.eg_bib_id(), true];
903 fieldmapper.standardRequest(
904 ['open-ils.search', 'open-ils.search.biblio.record.html'],
907 oncomplete: function(r) {
908 dojo.byId('acq-lit-marc-div').innerHTML =
909 openils.Util.readResponse(r);
915 this.drawCopies = function(liId, force_fetch) {
916 if (typeof force_fetch == "undefined")
922 this.copyWidgetCache = {};
923 this.oldCopyWidgetCache = {};
924 this.virtDfaCounts = {};
925 this.realDfaCache = {};
928 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
929 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
930 acqLitCopyCountInput.attr('value', '0');
932 while(this.copyTbody.childNodes[0])
933 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
935 this._drawBatchCopyWidgets();
937 this._drawDistribApplied(liId);
939 this._fetchDistribFormulas(
941 openils.acq.Lineitem.fetchAttrDefs(
943 self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch);
950 this._saveDistribAppliedTemplates = function() {
951 if (!this._appliedDistribTemplate) {
952 this._appliedDistribTemplate =
953 dojo.byId("acq-lit-distrib-applied-tbody").
954 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
955 dojo.attr(this._appliedDistribTemplate, "id");
959 this._drawDistribApplied = function(liId) {
960 /* Build this table while hidden to prevent rendering artifacts */
961 openils.Util.hide("acq-lit-distrib-applied-tbody");
963 this._saveDistribAppliedTemplates();
965 /* Remove any rows in the table from previous populations */
966 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
967 forEach(dojo.destroy);
969 /* Unregister all dijits previously created (for some reason this isn't
970 * covered by the above destroy calls). */
971 dijit.registry.forEach(
972 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
975 /* Populate the table with our liId */
977 fieldmapper.standardRequest(
979 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
982 "params": [self.authtoken, liId],
983 "onresponse": function(r) {
984 var dfa = openils.Util.readResponse(r);
987 self.realDfaCache[dfa.id()] = dfa;
988 self._drawDistribAppliedUnit(dfa);
991 "oncomplete": function() {
992 /* Reveal built table */
995 "acq-lit-distrib-applied-tbody", "table-row-group"
1003 this._drawDistribAppliedUnit = function(dfa) {
1004 var new_row = false;
1005 var row = dojo.query(
1006 'tr[formula="' + dfa.formula().id() + '"]',
1007 "acq-lit-distrib-applied-tbody"
1012 row = dojo.clone(this._appliedDistribTemplate);
1013 dojo.attr(row, "formula", dfa.formula().id());
1014 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
1017 var td = dojo.query("td", row)[0];
1019 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1020 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1023 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1025 new dijit.form.Button(
1027 "onClick": function() {
1028 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1029 self.deleteDfa(dfa);
1032 /* XXX I /cannot/ make the following work in as a CSS class
1033 * for some reason. So frustrating... */
1034 "style": function(id) {
1036 "font-weight: bold; color: #c00;" :
1038 }(dfa.id()) + "margin: 0 6px;display: inline;"
1039 }, "dfa-button-" + dfa.id()
1043 "connectId": ["dfa-button-" + dfa.id()],
1044 "label": dojo.string.substitute(
1045 localeStrings.DFA_TIP, dfa.id() > 0 ? [
1046 openils.User.formalName(dfa.creator()),
1047 dojo.date.locale.format(
1048 dojo.date.stamp.fromISOString(dfa.create_time()),
1049 {"formatLength":"short"}
1051 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
1053 }, "dfa-tip-" + dfa.id()
1057 this.deleteDfa = function(dfa) {
1058 if (dfa.id() > 0) { /* real */
1059 this.pcrud.eliminate(
1062 "oncomplete": function() {
1063 self._removeDistribApplied(dfa.id());
1064 delete self.realDfaCache[dfa.id()];
1068 } else { /* virtual */
1069 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
1070 this.virtDfaCounts[dfa.formula().id()] = 0;
1071 /* hasn't been saved yet, so no need to do anything server side */
1072 this._removeDistribApplied(dfa.id());
1077 this._removeDistribApplied = function(dfaId) {
1078 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
1079 dijit.registry.forEach(
1080 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
1082 this._removeDistribAppliedEmptyRows();
1085 this._removeAllDistribAppliedVirtual = function() {
1086 /* Unregister dijits */
1087 dijit.registry.forEach(
1088 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
1090 this._removeDistribAppliedEmptyRows();
1093 this._removeDistribAppliedEmptyRows = function() {
1094 /* Remove any rows with no DFA at all */
1095 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
1097 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
1103 * Insert a new row into the distribution formula selection form
1105 this._addDistribFormulaRow = function() {
1108 if (!self.distribForms) {
1109 // no formulas, hide the form
1110 openils.Util.hide('acq-lit-distrib-formula-tbody');
1114 if(!this.distribFormulaTemplate)
1115 this.distribFormulaTemplate =
1116 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
1118 var row = this.distribFormulaTemplate.cloneNode(true);
1119 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
1121 this.dfSelector = new dijit.form.FilteringSelect(
1122 {"labelAttr": "dynLabel", "labelType": "html"},
1123 nodeByName("selector", row)
1125 this._updateFormulaStore();
1126 this.dfSelector.fetchProperties =
1127 {"sort": [{"attribute": "use_count", "descending": true}]};
1129 var apply = new dijit.form.Button(
1130 {"label": localeStrings.APPLY},
1131 nodeByName('set_button', row)
1134 var reset = new dijit.form.Button(
1135 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
1136 nodeByName("reset_button", row)
1139 dojo.connect(apply, 'onClick',
1141 var form_id = self.dfSelector.attr("value");
1142 if(!form_id) return;
1143 self._applyDistribFormula(form_id);
1144 reset.attr("disabled", false);
1148 dojo.connect(reset, 'onClick',
1150 self.restoreCopyFieldsBeforeDF();
1151 self.virtDfaCounts = {};
1152 self.virtDfaId = -1;
1154 self._updateFormulaStore();
1155 self._removeAllDistribAppliedVirtual();
1156 reset.attr("disabled", "true");
1163 * Applies a distrib formula to the current set of copies
1165 this._applyDistribFormula = function(formula) {
1166 if(!formula) return;
1168 formula = this.distribForms.filter(
1169 function(form) { return form.id() == formula; }
1172 var copyRows = dojo.query('tr', self.copyTbody);
1174 if (this.dfeOffset >= copyRows.length) {
1175 alert(localeStrings.OUT_OF_COPIES);
1179 var entries_applied = 0;
1181 var rowIndex = this.dfeOffset;
1182 rowIndex < copyRows.length;
1186 var row = copyRows[rowIndex];
1187 var copy_id = row.getAttribute('copy_id');
1188 var copyWidgets = this.copyWidgetCache[copy_id];
1189 var entryIndex = this.dfeOffset;
1192 // find the correct entry for the current row
1193 dojo.forEach(formula.entries(),
1196 entryIndex += e.item_count();
1197 if(entryIndex > rowIndex)
1205 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
1206 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
1209 this.saveCopyFieldsBeforeDF(copy_id);
1210 this._copy_fields_for_acqdf.forEach(
1212 if(entry[field]()) {
1213 copyWidgets[field].attr('value', (entry[field]()));
1220 if (entries_applied) {
1221 this.virtDfaCounts[formula.id()] =
1222 ++(this.virtDfaCounts[formula.id()]) || 1;
1223 this._updateFormulaStore();
1224 this._drawDistribAppliedUnit(
1226 var dfa = new acqdfa();
1227 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
1230 this.dfeOffset += entries_applied;
1235 * This function updates the DF store for the dropdown so that use_counts
1236 * can reflect DF applications from this session before they're saved
1239 this._updateFormulaStore = function() {
1240 this.dfSelector.store = new dojo.data.ItemFileReadStore(
1242 "data": self._labelFormulasWithCounts(
1243 acqdf.toStoreData(self.distribForms)
1249 this.saveCopyFieldsBeforeDF = function(copy_id) {
1251 if (!this.oldCopyWidgetCache[copy_id]) {
1252 var copyWidgets = this.copyWidgetCache[copy_id];
1254 this.oldCopyWidgetCache[copy_id] = {};
1255 this._copy_fields_for_acqdf.forEach(
1257 self.oldCopyWidgetCache[copy_id][f] =
1258 copyWidgets[f].attr("value");
1264 this.restoreCopyFieldsBeforeDF = function() {
1266 for (var copy_id in this.oldCopyWidgetCache) {
1267 this._copy_fields_for_acqdf.forEach(
1269 self.copyWidgetCache[copy_id][f].attr(
1270 "value", self.oldCopyWidgetCache[copy_id][f]
1277 this._labelFormulasWithCounts = function(store_data) {
1278 for (var key in store_data.items) {
1279 var obj = store_data.items[key];
1280 obj.use_count = Number(obj.use_count); /* needed for sorting */
1282 if (this.virtDfaCounts[obj.id])
1283 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
1285 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
1286 obj.use_count + "]</span> " + obj.name;
1292 * This method formerly would not refetch the DF formulas if they'd been
1293 * loaded already, but now it always re-fetches, since use_count changes.
1295 /** TODO: port distrib-formula selector to autofieldwidget+pcrud/dojo store */
1296 this._fetchDistribFormulas = function(onload) {
1297 fieldmapper.standardRequest(
1299 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
1302 "params": [openils.User.authtoken, 0, 500],
1303 "oncomplete": function(r) {
1304 self.distribForms = openils.Util.readResponse(r);
1305 if(!self.distribForms || self.distribForms.length == 0) {
1306 self.distribForms = [];
1308 self._addDistribFormulaRow();
1315 this._drawBatchCopyWidgets = function() {
1316 var row = this.copyBatchRow;
1317 dojo.forEach(liDetailBatchFields,
1319 if(self.copyBatchRowDrawn) {
1320 self.copyBatchWidgets[field].attr('value', null);
1322 var widget = new openils.widget.AutoFieldWidget({
1325 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1326 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1327 searchFilter : (field == 'fund') ? {"active": "t"} : null,
1328 parentNode : dojo.query('[name='+field+']', row)[0],
1329 orgLimitPerms : ['CREATE_PICKLIST'],
1332 "labelType": (field == "fund") ? "html" : null
1334 noCache: (field == "fund"),
1339 if (field == "fund" && w.store)
1340 self._ensureCSSFundClasses(w.store);
1341 self.copyBatchWidgets[field] = w;
1344 if (field == "fund") {
1346 widget.widget, "onChange", function(val) {
1347 self._updateFundSelectorStyle(widget, val);
1354 this.copyBatchRowDrawn = true;
1357 this.batchCopyUpdate = function() {
1359 for(var k in this.copyWidgetCache) {
1360 var cache = this.copyWidgetCache[k];
1361 dojo.forEach(liDetailBatchFields, function(f) {
1362 var newval = self.copyBatchWidgets[f].attr('value');
1363 if(newval) cache[f].attr('value', newval);
1368 this._drawCopies = function(li) {
1371 // this button sets the total number of copies for a given lineitem
1372 acqLitAddCopyCount.onClick = function() {
1373 var count = acqLitCopyCountInput.attr('value');
1376 while(self.copyCount() < count)
1379 // delete rows if necessary
1380 var diff = self.copyCount() - count;
1382 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
1383 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
1384 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
1386 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1392 if(li.lineitem_details().length > 0) {
1393 dojo.forEach(li.lineitem_details(),
1395 self.addCopy(li, copy);
1403 this.copyCount = function() {
1405 for(var id in this.copyCache) {
1406 if(!this.copyCache[id].isdeleted())
1412 this.virtCopyId = -1;
1413 this.addCopy = function(li, copy) {
1414 var row = this.copyRow.cloneNode(true);
1415 this.copyTbody.appendChild(row);
1419 copy = new fieldmapper.acqlid();
1421 copy.id(this.virtCopyId--);
1422 copy.lineitem(li.id());
1425 this.copyCache[copy.id()] = copy;
1426 row.setAttribute('copy_id', copy.id());
1427 self.copyWidgetCache[copy.id()] = {};
1429 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1431 dojo.forEach(liDetailFields,
1434 if (field == "fund") {
1435 searchFilter = (copy.fund() ?
1436 {"-or": {"active": "t", "id": copy.fund()}} :
1439 searchFilter = null;
1442 var readOnly = false;
1444 // TODO: Add support for changing the owning_lib after real copies have been made.
1445 // owning_lib is order data as much as its item data
1446 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
1450 // TODO: add support for changing the fund after debits have been created
1451 // Note: invoicing allows the change
1452 if(copy.fund_debit() && field == 'fund') {
1456 var widget = new openils.widget.AutoFieldWidget({
1459 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1460 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1461 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1462 searchFilter : searchFilter,
1463 noCache: (field == "fund"),
1465 parentNode : dojo.query('[name='+field+']', row)[0],
1466 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
1467 readOnly : readOnly,
1468 orgDefaultsToWs : true
1472 // make sure we capture the value from any async widgets
1475 if (field == "fund" && w.store)
1476 self._ensureCSSFundClasses(w.store);
1479 copy[field](ww.getFormattedValue())
1481 self.copyWidgetCache[copy.id()][field] = w;
1483 dojo.connect(w, 'onChange',
1485 if (field == "fund")
1486 self._updateFundSelectorStyle(widget, val);
1488 if (!readOnly && (copy.isnew() || val != copy[field]())) {
1489 // prevent setting ischanged() automatically on widget load for existing copies
1490 copy[field](widget.getFormattedValue())
1491 copy.ischanged(true);
1500 this.updateLidState(copy, row);
1503 this._ensureCSSFundClass = function(id) {
1504 if (!this.fundStyleSheet) {
1506 "style", {"type": "text/css"},
1507 document.getElementsByTagName("head")[0], "last"
1509 this.fundStyleSheet = document.styleSheets[
1510 document.styleSheets.length - 1
1514 var cn = "fund_" + id;
1515 if (!this.haveFundClass[cn]) {
1516 fieldmapper.standardRequest(
1517 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
1519 "params": [openils.User.authtoken, id],
1521 "oncomplete": function(r) {
1522 r = openils.Util.readResponse(r);
1523 self.fundBalanceState[id] = r;
1525 if (r[0] /* stop */)
1526 style = fundStyles.stop;
1527 else if (r[1] /* warning */)
1528 style = fundStyles.warning;
1529 self.fundStyleSheet.insertRule(
1530 "." + cn + " { " + style + " }",
1531 self.fundStyleSheet.cssRules.length
1533 self.haveFundClass[cn] = true;
1540 this._ensureCSSFundClasses = function(store) {
1542 "query": {"id": "*"},
1543 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
1547 this._updateFundSelectorStyle = function(widget, fund_id) {
1548 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
1549 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
1552 this.updateLidState = function(copy, row) {
1553 if (typeof(row) == "undefined") {
1555 'tr[copy_id="' + copy.id() + '"]', this.copyTbody
1560 var recv_link = nodeByName("receive", row);
1561 var unrecv_link = nodeByName("unreceive", row);
1562 var del_link = nodeByName("delete", row);
1563 var cxl_link = nodeByName("cancel", row);
1564 var claim_link = nodeByName("claim", row);
1565 var cxl_reason_link = nodeByName("cancel_reason", row);
1567 if (copy.cancel_reason()) {
1568 openils.Util.hide(del_link.parentNode);
1569 openils.Util.hide(recv_link);
1570 openils.Util.hide(unrecv_link);
1571 openils.Util.hide(cxl_link);
1572 openils.Util.hide(claim_link);
1574 /* XXX the following may leak memory in a long lived table: dijits may not get destroyed... not positive. revisit. */
1575 var holds_reason = dojo.create(
1577 "style": "border-bottom: 1px dashed #000;",
1578 "innerHTML": "Cancelled" /* XXX [sic] and i18n */
1579 }, cxl_reason_link, "only"
1583 "label": "<em>" + copy.cancel_reason().label() +
1584 "</em><br />" + copy.cancel_reason().description(),
1585 "connectId": [holds_reason]
1586 }, dojo.create("span", null, cxl_reason_link, "last")
1588 openils.Util.show(cxl_reason_link, "inline");
1589 } else if (this.isPO) {
1590 /* Only using this in one place so far, but may want it for better
1591 * decisions on when to display certain controls. */
1592 var li_state = this.liCache[copy.lineitem()].state();
1594 openils.Util.hide(del_link.parentNode);
1595 openils.Util.hide(cxl_reason_link);
1597 /* Avoid showing (un)receive links, cancel links, for virt copies */
1598 if (copy.id() > 0) {
1599 if (copy.recv_time()) {
1600 openils.Util.hide(cxl_link);
1601 openils.Util.hide(recv_link);
1602 openils.Util.hide(claim_link);
1604 openils.Util.show(unrecv_link, "inline");
1605 unrecv_link.onclick = function() {
1606 if (confirm(localeStrings.UNRECEIVE_LID))
1607 self.issueReceive(copy, /* rollback */ true);
1610 openils.Util.hide(unrecv_link);
1612 if (this.claimEligibleLid[copy.id()]) {
1613 openils.Util.show(claim_link, "inline");
1614 claim_link.onclick = function() {
1615 self.claimDialog.show(
1616 self.liCache[copy.lineitem()], copy.id()
1620 openils.Util.hide(claim_link);
1623 openils.Util[li_state == "on-order" ? "show" : "hide"](
1626 openils.Util.show(cxl_link, "inline");
1627 recv_link.onclick = function() {
1628 if (self.checkLiAlerts(copy.lineitem()))
1629 self.issueReceive(copy);
1631 cxl_link.onclick = function() {
1632 self.cancelLid(copy.id());
1636 openils.Util.hide(cxl_link);
1637 openils.Util.hide(unrecv_link);
1638 openils.Util.hide(recv_link);
1639 openils.Util.hide(claim_link);
1642 openils.Util.hide(unrecv_link);
1643 openils.Util.hide(recv_link);
1644 openils.Util.hide(cxl_reason_link);
1645 openils.Util.hide(claim_link);
1647 del_link.onclick = function() { self.deleteCopy(row) };
1648 openils.Util.show(del_link.parentNode);
1652 this.cancelLid = function(lid_id) {
1653 lidCancelDialog._lid_id = lid_id;
1654 openils.Util.show(lidCancelDialog.domNode.parentNode);
1655 lidCancelDialog.show();
1656 if (!lidCancelDialog._prepared) {
1657 var widget = new openils.widget.AutoFieldWidget({
1658 "fmField": "cancel_reason",
1659 "fmClass": "acqlid",
1660 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
1661 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1666 acqLidCancelButton.onClick = function() {
1667 if (w.attr("value")) {
1668 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
1670 lidCancelDialog._lid_id,
1674 lidCancelDialog.hide();
1677 lidCancelDialog._prepared = true;
1683 this._cancelLid = function(lid_id, reason) {
1684 fieldmapper.standardRequest(
1685 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
1686 "params": [openils.User.authtoken, lid_id, reason],
1688 "onresponse": function(r) {
1689 if (r = openils.Util.readResponse(r)) {
1691 for (var id in r.lid) {
1692 /* actually this should only iterate once */
1693 self.copyCache[id].cancel_reason(
1694 r.lid[id].cancel_reason
1696 self.updateLidState(self.copyCache[id]);
1705 this._confirmAlert = function(li, lin) {
1707 dojo.string.substitute(
1708 localeStrings.CONFIRM_LI_ALERT, [
1709 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1710 "title", "lineitem_marc_attr_definition"
1712 lin.alert_text().code(),
1713 lin.alert_text().description() || "",
1720 this.checkLiAlerts = function(li_id) {
1721 var li = this.liCache[li_id];
1723 var alert_notes = li.lineitem_notes().filter(
1724 function(o) { return Boolean(o.alert_text()); }
1727 /* this is _intentionally_ not done in a call to forEach() ... */
1728 for (var i = 0; i < alert_notes.length; i++) {
1729 if (this.noteAcks[alert_notes[i].id()])
1731 else if (!this._confirmAlert(li, alert_notes[i]))
1734 this.noteAcks[alert_notes[i].id()] = true;
1740 this.deleteCopy = function(row) {
1741 var copy = this.copyCache[row.getAttribute('copy_id')];
1742 copy.isdeleted(true);
1744 delete this.copyCache[copy.id()];
1745 this.copyTbody.removeChild(row);
1748 this._virtDfaCountsAsList = function() {
1750 for (var key in this.virtDfaCounts) {
1751 for (var i = 0; i < this.virtDfaCounts[key]; i++)
1757 this.confirmBreachedCopyFunds = function(copies) {
1758 var stop = 0, warning = 0;
1762 var state = self.fundBalanceState[o.fund()];
1763 if (state[0] /* stop */)
1765 else if (state[1] /* warning */)
1772 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
1773 } else if (warning) {
1774 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
1779 this.saveCopyChanges = function(liId) {
1785 for(var id in this.copyCache) {
1786 var c = this.copyCache[id];
1787 if(!c.isdeleted()) total++;
1788 if(c.isnew() || c.ischanged() || c.isdeleted()) {
1789 if(c.id() < 0) c.id(null);
1795 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
1798 if (copies.length > 0) {
1799 if (!this.confirmBreachedCopyFunds(copies))
1802 if (typeof(this._copy_count_cb) == "function")
1803 this._copy_count_cb(liId, total);
1805 openils.Util.show("acq-lit-update-copies-progress");
1806 fieldmapper.standardRequest(
1807 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1809 params: [openils.User.authtoken, copies],
1810 onresponse: function(r) {
1811 var res = openils.Util.readResponse(r);
1812 litUpdateCopiesProgress.update(res);
1814 oncomplete: function() {
1815 self.drawCopies(liId, true /* force_fetch */);
1816 openils.Util.hide("acq-lit-update-copies-progress");
1822 var dfa_list = this._virtDfaCountsAsList();
1823 if (dfa_list.length > 0) {
1824 fieldmapper.standardRequest(
1826 "open-ils.acq.distribution_formula.record_application"],
1829 "params": [openils.User.authtoken, dfa_list, liId],
1830 "onresponse": function(r) {
1831 var res = openils.Util.readResponse(r);
1832 if (res && res.length < dfa_list.length)
1833 alert(localeStrings.DFA_NOT_ALL);
1837 this.virtDfaCounts = {};
1841 this._updateCreatePoPrepayCheckbox = function(prepay) {
1842 var prepay = openils.Util.isTrue(prepay);
1843 this._prepayRequiredByVendor = prepay;
1844 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
1847 this._confirmPoPrepaySituation = function() {
1848 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
1849 if (want_prepay != this._prepayRequiredByVendor) {
1852 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
1853 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
1860 this.applySelectedLiAction = function(action) {
1864 case 'delete_selected':
1865 this._deleteLiList(self.getSelected());
1868 case 'create_order':
1869 this._loadPOSelect();
1870 acqLitPoCreateDialog.show();
1873 case 'save_picklist':
1874 acqLitSavePlDialog.show();
1877 case 'selector_ready':
1879 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
1880 acqLitChangeLiStateDialog.show();
1888 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
1895 case 'rollback_receive_po':
1896 this.rollbackPoReceive();
1899 case 'create_assets':
1900 this.createAssets();
1903 case 'export_attr_list':
1904 this.chooseExportAttr();
1907 case 'batch_apply_funds':
1908 this.applyBatchLiFunds();
1911 case 'add_brief_record':
1913 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
1915 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
1919 case "cancel_lineitems":
1920 this.maybeCancelLineitems();
1923 case "change_claim_policy":
1924 var li_list = this.getSelected();
1925 this.claimPolicyPicker.attr("value", null);
1926 liClaimPolicyDialog.show();
1927 liClaimPolicySave.onClick = function() {
1928 self.changeClaimPolicy(
1930 self.claimPolicyPicker.attr("value"),
1934 self.setClaimPolicyControl(li);
1935 self.reconsiderClaimControl(li);
1938 liClaimPolicyDialog.hide();
1946 this.changeClaimPolicy = function(li_list, value, callback) {
1948 function(li) { li.claim_policy(value); }
1950 fieldmapper.standardRequest(
1951 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
1952 "params": [openils.User.authtoken, li_list],
1954 "oncomplete": function(r) {
1955 r = openils.Util.readResponse(r);
1956 if (callback) callback(r);
1962 this.createAssets = function() {
1963 if(!this.isPO) return;
1964 if(!confirm(localeStrings.CREATE_PO_ASSETS_CONFIRM)) return;
1965 this.show('acq-lit-progress-numbers');
1967 fieldmapper.standardRequest(
1968 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
1970 params: [this.authtoken, this.isPO],
1971 onresponse: function(r) {
1972 var resp = openils.Util.readResponse(r);
1973 self._updateProgressNumbers(resp, true);
1979 this.maybeCancelLineitems = function() {
1980 openils.Util.show("acq-lit-cancel-reason", "inline");
1981 if (!acqLitCancelLineitemsButton._prepared) {
1982 var widget = new openils.widget.AutoFieldWidget({
1983 "fmField": "cancel_reason",
1985 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
1986 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1991 acqLitCancelLineitemsButton.onClick = function() {
1992 if (w.attr("value")) {
1993 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
1994 self._cancelLineitems(w.attr("value"));
1996 openils.Util.hide("acq-lit-cancel-reason");
1999 acqLitCancelLineitemsButton._prepared = true;
2005 this._cancelLineitems = function(reason) {
2006 var id_list = this.getSelected().map(function(o) { return o.id(); });
2007 fieldmapper.standardRequest(
2008 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
2009 "params": [openils.User.authtoken, id_list, reason],
2011 "onresponse": function(r) {
2012 if (r = openils.Util.readResponse(r)) {
2014 for (var id in r.li) {
2015 self.liCache[id].state(r.li[id].state);
2016 self.liCache[id].cancel_reason(
2017 r.li[id].cancel_reason
2019 self.updateLiState(self.liCache[id]);
2022 if (r.lid && self.copyCache) {
2023 for (var id in r.lid) {
2024 if (self.copyCache[id]) {
2025 self.copyCache[id].cancel_reason(
2026 r.lid[id].cancel_reason
2028 self.updateLidState(self.copyCache[id]);
2038 this.chooseExportAttr = function() {
2039 if (!acqLitExportAttrSelector._li_setup) {
2041 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
2043 "data": acqlimad.toStoreData(
2045 "acqlimad", {"code": li_exportable_attrs}
2050 acqLitExportAttrSelector.setValue();
2051 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
2052 acqLitExportAttrSelector._li_setup = true;
2054 openils.Util.show("acq-lit-export-attr-holder", "inline");
2057 this.exportAttrList = function() {
2058 var attr_def = acqLitExportAttrSelector.item;
2059 var li_list = this.getSelected();
2060 var value_list = li_list.map(
2062 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2063 attr_def.code, "lineitem_marc_attr_definition"
2066 ).filter(function(attr) { return Boolean(attr); });
2068 if (value_list.length > 0) {
2069 if (value_list.length < li_list.length) {
2071 dojo.string.substitute(
2072 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
2079 openils.XUL.contentToFileSaveDialog(
2080 value_list.join("\n"),
2081 localeStrings.EXPORT_SAVE_DIALOG_TITLE
2087 alert(dojo.string.substitute(
2088 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
2092 openils.Util.hide("acq-lit-export-attr-holder");
2095 this.printPO = function() {
2096 if(!this.isPO) return;
2097 progressDialog.show(true);
2098 fieldmapper.standardRequest(
2099 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
2101 params: [this.authtoken, this.isPO, 'html'],
2102 oncomplete: function(r) {
2103 progressDialog.hide();
2104 var evt = openils.Util.readResponse(r);
2105 if(evt && evt.template_output()) {
2106 openils.Util.printHtmlString(evt.template_output().data());
2114 this.receivePO = function() {
2115 if (!this.isPO) return;
2117 for (var id in this.liCache) {
2118 /* assumption: liCache reflects exactly the
2119 * set of LIs that belong to our PO */
2120 if (this.liCache[id].state() != "received" &&
2121 !this.checkLiAlerts(id)) return;
2124 this.show('acq-lit-progress-numbers');
2126 fieldmapper.standardRequest(
2127 ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
2129 params: [this.authtoken, this.isPO],
2130 onresponse : function(r) {
2131 var resp = openils.Util.readResponse(r);
2132 self._updateProgressNumbers(resp, true);
2138 this.issueReceive = function(obj, rollback) {
2139 /* (For now) there shall be no marking LI or LIDs (un)received
2140 * except from the actual "view PO" interface. */
2141 if (!this.isPO) return;
2144 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
2146 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
2148 progressDialog.show(true);
2149 fieldmapper.standardRequest(
2150 ["open-ils.acq", method], {
2152 "params": [this.authtoken, obj.id()],
2153 "onresponse": function(r) {
2154 if (r = openils.Util.readResponse(r)) {
2155 self.fetchClaimInfo(
2156 part == "lineitem" ? obj.id() : obj.lineitem(),
2158 function() { self.handleReceive(r); }
2160 progressDialog.hide();
2168 * Handles the responses from receive and rollback ML calls.
2170 this.handleReceive = function(resp) {
2173 for (var li_id in resp.li) {
2174 for (var key in resp.li[li_id])
2175 self.liCache[li_id][key](resp.li[li_id][key]);
2176 self.updateLiState(self.liCache[li_id]);
2180 if (typeof(self.poUpdateCallback) == "function")
2181 self.poUpdateCallback(resp.po);
2184 for (var lid_id in resp.lid) {
2185 for (var key in resp.lid[lid_id])
2186 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
2187 self.updateLidState(self.copyCache[lid_id]);
2193 this.rollbackPoReceive = function() {
2194 if(!this.isPO) return;
2195 if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
2196 this.show('acq-lit-progress-numbers');
2198 fieldmapper.standardRequest(
2199 ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
2201 params: [this.authtoken, this.isPO],
2202 onresponse : function(r) {
2203 var resp = openils.Util.readResponse(r);
2204 self._updateProgressNumbers(resp, true);
2210 this._updateProgressNumbers = function(resp, reloadOnComplete) {
2212 dojo.byId('acq-pl-lit-li-processed').innerHTML = resp.li;
2213 dojo.byId('acq-pl-lit-lid-processed').innerHTML = resp.lid;
2214 dojo.byId('acq-pl-lit-debits-processed').innerHTML = resp.debits_accrued;
2215 dojo.byId('acq-pl-lit-bibs-processed').innerHTML = resp.bibs;
2216 dojo.byId('acq-pl-lit-indexed-processed').innerHTML = resp.indexed;
2217 dojo.byId('acq-pl-lit-copies-processed').innerHTML = resp.copies;
2218 if(resp.complete && reloadOnComplete)
2219 location.href = location.href;
2223 this._createPO = function(fields) {
2224 this.show('acq-lit-progress-numbers');
2225 var po = new fieldmapper.acqpo();
2226 po.provider(this.createPoProviderSelector.attr('value'));
2227 po.ordering_agency(this.createPoAgencySelector.attr('value'));
2228 po.prepayment_required(fields.prepayment_required[0] ? true : false);
2230 var selected = this.getSelected( (fields.create_from == 'all') );
2231 if(selected.length == 0) return;
2233 var max = selected.length * 3;
2236 fieldmapper.standardRequest(
2237 ['open-ils.acq', 'open-ils.acq.purchase_order.create'],
2240 openils.User.authtoken,
2243 lineitems : selected.map(function(li) { return li.id() }),
2244 create_assets : fields.create_assets[0],
2248 onresponse : function(r) {
2249 var resp = openils.Util.readResponse(r);
2250 self._updateProgressNumbers(resp);
2252 location.href = oilsBasePath + '/acq/po/view/' + resp.purchase_order.id();
2258 this.batchFundWidget = null;
2260 this.applyBatchLiFunds = function() {
2262 var liIds = this.getSelected().map(function(li) { return li.id(); });
2263 if(liIds.length == 0) return; // warn?
2266 batchFundUpdateDialog.show();
2268 if(!this.batchFundWidget) {
2269 this.batchFundWidget = new openils.widget.AutoFieldWidget({
2271 selfReference : true,
2272 labelFormat : fundLabelFormat,
2273 searchFormat : fundSearchFormat,
2274 searchFilter : {"active": "t"},
2275 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
2276 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2277 dijitArgs : { "required": true, "labelType": "html" },
2280 this.batchFundWidget.build();
2283 dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
2284 dojo.connect(batchFundUpdateSubmit, 'onClick',
2287 // TODO: call .dry_run first to test thresholds
2288 fieldmapper.standardRequest(
2289 ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
2292 openils.User.authtoken,
2294 self.batchFundWidget.widget.attr('value')
2296 oncomplete : function(r) {
2297 var resp = openils.Util.readResponse(r);
2299 location.href = location.href;
2308 this._deleteLiList = function(list, idx) {
2309 if(idx == null) idx = 0;
2310 if(idx >= list.length) return;
2311 var liId = list[idx].id();
2312 fieldmapper.standardRequest(
2313 ['open-ils.acq', 'open-ils.acq.lineitem.delete'],
2315 params: [openils.User.authtoken, liId],
2316 oncomplete: function(r) {
2317 self.removeLineitem(liId);
2318 self._deleteLiList(list, ++idx);
2324 this.editOrderMarc = function(li) {
2326 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
2327 to true in about:config */
2329 if(!openils.XUL.enableXPConnect()) return;
2331 if(openils.XUL.isXUL()) {
2332 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
2334 win = window.open('/xul/server/cat/marcedit.xul');
2338 record : {marc : li.marc(), "rtype": "bre"},
2340 label: 'Save Record', // XXX I18N
2341 func: function(xmlString) {
2343 fieldmapper.standardRequest(
2344 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
2346 params: [openils.User.authtoken, li],
2347 oncomplete: function(r) {
2348 openils.Util.readResponse(r);
2350 self.drawInfo(li.id())
2356 'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
2357 'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
2361 this._savePl = function(values) {
2363 var selected = this.getSelected( (values.which == 'all') );
2364 openils.Util.show('acq-lit-generic-progress');
2366 if(values.new_name) {
2367 openils.acq.Picklist.create(
2368 {name: values.new_name},
2370 self._updateLiList(id, selected, 0,
2372 location.href = oilsBasePath + '/acq/picklist/view/' + id;
2376 } else if(values.existing_pl) {
2377 // update lineitems to use an existing picklist
2378 self._updateLiList(values.existing_pl, selected, 0,
2380 location.href = oilsBasePath + '/acq/picklist/view/' + values.existing_pl;
2385 this._updateLiState = function(values, state) {
2387 var selected = this.getSelected( (values.which == 'all') );
2388 if(!selected.length) return;
2389 dojo.forEach(selected, function(li) {li.state(state);});
2390 self._updateLiList(null, selected, 0,
2391 // TODO consider inline updates for efficiency
2392 function() { location.href = location.href }
2396 this._updateLiList = function(pl, list, idx, oncomplete) {
2397 if(idx >= list.length) return oncomplete();
2399 if(pl != null) li.picklist(pl);
2400 litGenericProgress.update({maximum: list.length, progress: idx});
2401 new openils.acq.Lineitem({lineitem:li}).update(
2403 self._updateLiList(pl, list, ++idx, oncomplete);
2408 this._loadPOSelect = function() {
2409 if (!this.createPoProviderSelector) {
2410 var widget = new openils.widget.AutoFieldWidget({
2411 "fmField": "provider",
2413 "searchFilter": {"active": "t"},
2414 "parentNode": dojo.byId("acq-lit-po-provider"),
2416 "onChange": function() {
2418 self._updateCreatePoPrepayCheckbox(
2419 this.item.prepayment_required
2425 widget.build(function(w) { self.createPoProviderSelector = w; });
2428 if (!this.createPoAgencySelector) {
2429 var widget = new openils.widget.AutoFieldWidget({
2430 "fmField": "ordering_agency",
2432 "parentNode": dojo.byId("acq-lit-po-agency"),
2433 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2435 widget.build(function(w) { self.createPoAgencySelector = w; });
2439 this.showRealCopyEditUI = function(li) {
2444 this._fetchLineitem(li.id(),
2446 li = self.liCache[li.id()] = fullLi;
2450 id : li.lineitem_details().map(
2451 function(item) { return item.eg_copy_id() }
2455 oncomplete : function(r) {
2457 var r_list = openils.Util.readResponse( r );
2458 for (var i = 0; i < r_list.length; i++) {
2459 var copy = r_list[i];
2460 var volId = copy.call_number();
2461 var volume = self.volCache[volId];
2463 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2465 copy.call_number(volume);
2466 copyList.push(copy);
2469 // If we need to, we can pass in an update_copy function to handle the update instead of volume_item_creator
2470 xulG.volume_item_creator( { 'existing_copies' : copyList } );
2473 alert('error in oncomplete: ' + E);
2482 this.drawBibFinder = function(li) {
2485 var liWrapper = new openils.acq.Lineitem({lineitem:li});
2488 ['isbn', 'upc', 'issn', 'title', 'author'],
2490 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
2492 if(field == 'title' || field == 'author') {
2493 query += field +':' + val + ' ';
2495 query += 'identifier|' + field + ':' + val + ' ';
2502 oilsBasePath + '/acq/lineitem/findbib?query=' + escape(query),
2503 '', 'resizable,scrollbars=1');
2505 win.window.recordFound = function(bibId) {
2508 var attrs = li.attributes();
2509 li.attributes(null);
2510 li.eg_bib_id(bibId);
2512 fieldmapper.standardRequest(
2513 ["open-ils.acq", "open-ils.acq.lineitem.update"],
2515 "params": [openils.User.authtoken, li],
2517 "oncomplete": function(r) {
2518 if(openils.Util.readResponse(r)) {
2519 location.href = location.href;