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');
17 dojo.requireLocalization('openils.acq', 'acq');
18 var localeStrings = dojo.i18n.getLocalization('openils.acq', 'acq');
19 const XUL_OPAC_WRAPPER = 'chrome://open_ils_staff_client/content/cat/opac.xul';
20 var li_exportable_attrs = ["issn", "isbn", "upc"];
22 var fundLabelFormat = [
23 '<span class="fund_${0}">${1} (${2})</span>', 'id', 'code', 'year'
25 var fundSearchFormat = ['${0} (${1})', 'code', 'year'];
27 function nodeByName(name, context) {
28 return dojo.query('[name='+name+']', context)[0];
32 var liDetailBatchFields = ['fund', 'owning_lib', 'location', 'collection_code', 'circ_modifier', 'cn_label'];
33 var liDetailFields = liDetailBatchFields.concat(['barcode', 'note']);
35 "stop": "color: #c00; font-weight: bold;",
36 "warning": "color: #c93;"
39 function AcqLiTable() {
46 this.haveFundClass = {}
47 this.fundBalanceState = {};
48 this.realDfaCache = {};
49 this.virtDfaCounts = {};
52 this.claimEligibleLidByLi = {};
53 this.claimEligibleLid = {};
54 this.toggleState = false;
55 this.tbody = dojo.byId('acq-lit-tbody');
58 this.authtoken = openils.User.authtoken;
59 this.pcrud = new openils.PermaCrud();
60 this.rowTemplate = this.tbody.removeChild(dojo.byId('acq-lit-row'));
61 this.copyTbody = dojo.byId('acq-lit-li-details-tbody');
62 this.copyRow = this.copyTbody.removeChild(dojo.byId('acq-lit-li-details-row'));
63 this.copyBatchRow = dojo.byId('acq-lit-li-details-batch-row');
64 this.copyBatchWidgets = {};
65 this.liNotesTbody = dojo.byId('acq-lit-notes-tbody');
66 this.liNotesRow = this.liNotesTbody.removeChild(dojo.byId('acq-lit-notes-row'));
67 this.realCopiesTbody = dojo.byId('acq-lit-real-copies-tbody');
68 this.realCopiesRow = this.realCopiesTbody.removeChild(dojo.byId('acq-lit-real-copies-row'));
69 this._copy_fields_for_acqdf = ['owning_lib', 'location'];
70 this.invoiceLinkDialogManager = new InvoiceLinkDialogManager("li");
71 this.claimDialog = new ClaimDialogManager(
72 liClaimDialog, finalClaimDialog, this.claimEligibleLidByLi,
73 function(li) { /* callback that fires when claims are made */
74 self.fetchClaimInfo(li.id(), /* force update */ true);
78 dojo.connect(acqLitLiActionsSelector, 'onChange',
80 self.applySelectedLiAction(this.attr('value'))
81 acqLitLiActionsSelector.attr('value', '_');
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() {
114 while(self.tbody.childNodes[0])
115 self.tbody.removeChild(self.tbody.childNodes[0]);
121 this.setNext = function(handler) {
122 var link = dojo.byId('acq-lit-next');
124 dojo.style(link, 'visibility', 'visible');
125 link.onclick = handler;
127 dojo.style(link, 'visibility', 'hidden');
131 this.setPrev = function(handler) {
132 var link = dojo.byId('acq-lit-prev');
134 dojo.style(link, 'visibility', 'visible');
135 link.onclick = handler;
137 dojo.style(link, 'visibility', 'hidden');
141 this.show = function(div) {
142 openils.Util.hide('acq-lit-table-div');
143 openils.Util.hide('acq-lit-info-div');
144 openils.Util.hide('acq-lit-li-details');
145 openils.Util.hide('acq-lit-notes-div');
146 openils.Util.hide('acq-lit-real-copies-div');
149 openils.Util.show('acq-lit-table-div');
152 openils.Util.show('acq-lit-info-div');
155 openils.Util.show('acq-lit-li-details');
158 openils.Util.show('acq-lit-real-copies-div');
161 openils.Util.show('acq-lit-notes-div');
165 openils.Util.show(div);
169 this.hide = function() {
173 this.toggleSelect = function() {
175 dojo.forEach(self.selectors, function(i){i.checked = false});
177 dojo.forEach(self.selectors, function(i){i.checked = true});
178 self.toggleState = !self.toggleState;
182 /** @param all If true, assume all are selected */
183 this.getSelected = function(all) {
185 dojo.forEach(self.selectors,
188 selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
194 this.setRowAttr = function(td, liWrapper, field, type) {
195 var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
196 td.appendChild(document.createTextNode(val));
199 this.setClaimPolicyControl = function(li, row) {
200 if (!self.claimPolicyPicker) {
201 self.claimPolicyPicker = true; /* prevents a race condition */
202 new openils.widget.AutoFieldWidget({
203 "parentNode": "acq-lit-li-claim-policy",
205 "selfReference": true,
206 "dijitArgs": {"required": true}
207 }).build(function(w) { self.claimPolicyPicker = w; });
210 if (!row) row = this._findLiRow(li);
212 var actViewPolicy = nodeByName("action_view_claim_policy", row);
213 if (li.claim_policy())
214 actViewPolicy.innerHTML = localeStrings.CHANGE_CLAIM_POLICY;
216 if (!actViewPolicy.onclick) {
217 actViewPolicy.onclick = function() {
218 if (li.claim_policy())
219 self.claimPolicyPicker.attr("value", li.claim_policy());
220 liClaimPolicyDialog.show();
221 liClaimPolicySave.onClick = function() {
222 self.changeClaimPolicy(
223 [li], self.claimPolicyPicker.attr("value"),
225 self.setClaimPolicyControl(li, row);
226 liClaimPolicyDialog.hide();
234 this.fetchClaimInfo = function(liId, force, callback, row) {
236 liId, function(full) {
237 self.liCache[full.id()] = full;
238 self.checkClaimEligibility(full, callback, row);
244 * Inserts a single lineitem into the growing table of lineitems
245 * @param {Object} li The lineitem object to insert
247 this.addLineitem = function(li, skip_final_placement) {
248 this.liCache[li.id()] = li;
250 // sort the lineitem notes on edit_time
251 if(!li.lineitem_notes()) li.lineitem_notes([]);
253 var liWrapper = new openils.acq.Lineitem({lineitem:li});
254 var row = self.rowTemplate.cloneNode(true);
255 row.setAttribute('li', li.id());
256 var tds = dojo.query('[attr]', row);
257 dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
258 dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
260 var isbn = liWrapper.findAttr('isbn', 'lineitem_marc_attr_definition');
262 // XXX media prefix for added content
263 dojo.query('[name=jacket]', row)[0].setAttribute('src', '/opac/extras/ac/jacket/small/' + isbn);
266 nodeByName("worksheet_link", row).href =
267 oilsBasePath + "/acq/lineitem/worksheet/" + li.id();
269 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
270 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
271 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
273 this.fetchClaimInfo(li.id(), false, null, row);
275 this.updateLiNotesCount(li, row);
277 this.setClaimPolicyControl(li, row);
279 // show which PO this lineitem is a member of
280 if(li.purchase_order() && !this.isPO) {
282 this.poCache[li.purchase_order()] =
283 this.poCache[li.purchase_order()] ||
284 fieldmapper.standardRequest(
285 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
287 this.authtoken, li.purchase_order(), {
288 "flesh_price_summary": true,
289 "flesh_lineitem_count": true
292 if(po && !this.isMeta) {
293 openils.Util.show(nodeByName('po', row), 'inline');
294 var link = nodeByName('po_link', row);
295 link.setAttribute('href', oilsBasePath + '/acq/po/view/' + li.purchase_order());
296 link.innerHTML = 'PO: ' + po.name(); // TODO i18n
300 // show which picklist this lineitem is a member of
301 if(li.picklist() && (this.isPO || this.isMeta)) {
303 this.plCache[li.picklist()] =
304 this.plCache[li.picklist()] ||
305 fieldmapper.standardRequest(
306 ['open-ils.acq', 'open-ils.acq.picklist.retrieve'],
307 {params: [this.authtoken, li.picklist()]});
309 openils.Util.show(nodeByName('pl', row), 'inline');
310 var link = nodeByName('pl_link', row);
311 link.setAttribute('href', oilsBasePath + '/acq/picklist/view/' + li.picklist());
312 link.innerHTML = 'PL: '+pl.name(); // TODO i18n
316 var countNode = nodeByName('count', row);
317 var count = li.item_count() || 0;
318 if (typeof(this._copy_count_cb) == "function") {
319 this._copy_count_cb(li.id(), count);
321 countNode.innerHTML = count;
322 countNode.id = 'acq-lit-copy-count-label-' + li.id();
325 var priceInput = dojo.query('[name=price]', row)[0];
326 priceInput.value = li.estimated_unit_price() || '';
327 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
329 // show either "mark received" or "unreceive" as appropriate
330 this.updateLiState(li, row);
332 if (!skip_final_placement) {
333 self.tbody.appendChild(row);
334 self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
340 this._liCountClaims = function(li) {
342 for (var i = 0; i < li.lineitem_details().length; i++)
343 total += li.lineitem_details()[i].claims().length;
347 this._findLiRow = function(li) {
348 return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
351 this.reconsiderClaimControl = function(li, row) {
352 var option = nodeByName("action_manage_claims", row);
353 var eligible = this.claimEligibleLidByLi[li.id()].length;
354 var count = this._liCountClaims(li);
355 if (!row) row = this._findLiRow(li);
357 option.disabled = !(count || eligible);
359 dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
360 option.onclick = function() { self.claimDialog.show(li); };
363 this.clearEligibility = function(li) {
364 this.claimEligibleLidByLi[li.id()] = [];
366 if (li.lineitem_details()) {
367 li.lineitem_details().forEach(
368 function(lid) { delete self.claimEligibleLid[lid.id()]; }
372 if (this.copyCache) {
374 for (var k in this.copyCache) {
375 if (this.copyCache[k].lineitem() == li.id())
379 function(k) { delete self.claimEligibleLid[k]; }
384 this.checkClaimEligibility = function(li, callback, row) {
385 this.clearEligibility(li);
386 fieldmapper.standardRequest(
387 ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
388 "params": [openils.User.authtoken, {"lineitem": li.id()}],
390 "onresponse": function(r) {
391 if (r = openils.Util.readResponse(r)) {
392 self.claimEligibleLidByLi[li.id()].push(
395 self.claimEligibleLid[r.lineitem_detail()] = true;
398 "oncomplete": function() {
399 self.reconsiderClaimControl(li, row);
400 if (typeof(callback) == "function")
407 this.updateLiNotesCount = function(li, row) {
408 if (!row) row = this._findLiRow(li);
410 var has_notes = (li.lineitem_notes().filter(
411 function(o) { return Boolean (o.alert_text()); }
414 /* U+2691 is the code point for a filled-in flag character */
415 nodeByName("notes_alert_flag", row).innerHTML =
416 has_notes ? "⚑" : "";
417 nodeByName("noteslink", row).style.fontStyle =
418 has_notes ? "italic" : "normal";
419 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
422 /* XXX NOT related to _updateLiState(). rethink */
423 this.updateLiState = function(li, row) {
424 if (!row) row = this._findLiRow(li);
426 var actReceive = nodeByName("action_mark_recv", row);
427 var actUnRecv = nodeByName("action_mark_unrecv", row);
428 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
429 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
431 var actNewInvoice = nodeByName('action_new_invoice', row);
432 var actLinkInvoice = nodeByName('action_link_invoice', row);
433 var actViewInvoice = nodeByName('action_view_invoice', row);
435 var state_cell = nodeByName("li_state", row);
437 if (li.state() == "cancelled") {
438 if (typeof li.cancel_reason() == "object") {
439 var holds_state = dojo.create(
441 "style": "border-bottom: 1px dashed #000;",
442 "innerHTML": li.state()
443 }, state_cell, "only"
447 "label": "<em>" + li.cancel_reason().label() +
448 "</em><br />" + li.cancel_reason().description(),
449 "connectId": [holds_state]
450 }, dojo.create("span", null, state_cell, "last")
453 state_cell.innerHTML = li.state(); // TODO i18n state labels
456 state_cell.innerHTML = li.state(); // TODO i18n state labels
460 /* handle row coloring for based on LI state */
461 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
462 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
464 /* handle links that appear/disappear based on whether LI is received */
468 actNewInvoice.onclick = function() {
469 location.href = oilsBasePath + '/acq/invoice/view?create=1&attach_li=' + li.id();
470 nodeByName("action_none", row).selected = true;
472 actLinkInvoice.onclick = function() {
473 self.invoiceLinkDialogManager.target = li;
474 acqLitLinkInvoiceDialog.show();
475 nodeByName("action_none", row).selected = true;
477 actViewInvoice.onclick = function() {
478 location.href = oilsBasePath +
479 "/acq/search/unified?so=" +
480 base64Encode({"jub":[{"id": li.id()}]}) +
482 nodeByName("action_none", row).selected = true;
485 actNewInvoice.disabled = false;
486 actLinkInvoice.disabled = false;
487 actViewInvoice.disabled = false;
491 actReceive.disabled = false;
492 actReceive.onclick = function() {
493 if (self.checkLiAlerts(li.id()))
494 self.issueReceive(li);
495 nodeByName("action_none", row).selected = true;
500 actUnRecv.disabled = false;
501 actUnRecv.onclick = function() {
502 if (confirm(localeStrings.UNRECEIVE_LI))
503 self.issueReceive(li, /* rollback */ true);
504 nodeByName("action_none", row).selected = true;
506 // TODO we should allow editing before receipt, in which case the
507 // test should be "if 1 or more real (acp) copies exist
508 actUpdateBarcodes.disabled = false;
509 actUpdateBarcodes.onclick = function() {
510 self.showRealCopyEditUI(li);
511 nodeByName("action_none", row).selected = true;
513 actHoldingsMaint.disabled = false;
514 actHoldingsMaint.onclick = self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
522 this._setAlertStore = function() {
523 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
525 "data": acqliat.toStoreData(
527 "acqliat", {"id": {"!=": null}}
532 acqLitAlertAlertText.setValue(); /* make the store "live" */
533 acqLitAlertAlertText._store_ready = true;
537 * Draws and shows the lineitem notes pane
539 this.drawLiNotes = function(li) {
542 if (!acqLitAlertAlertText._store_ready)
543 this._setAlertStore();
546 li.lineitem_notes().sort(
548 if(a.edit_time() < b.edit_time()) return 1;
554 while(this.liNotesTbody.childNodes[0])
555 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
558 acqLitCreateNoteSubmit.onClick = function() {
559 var value = acqLitCreateNoteText.attr('value');
561 var note = new fieldmapper.acqlin();
564 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
567 note.lineitem(li.id());
569 self.updateLiNotes(li, note);
570 acqLitCreateNoteVendorPublic.attr("checked", false);
571 acqLitCreateNoteText.attr("value", "");
574 acqLitCreateAlertSubmit.onClick = function() {
575 if (!acqLitAlertAlertText.item) {
576 alert(localeStrings.ALERT_UNSELECTED);
580 var alert_text = new fieldmapper.acqliat().fromStoreItem(
581 acqLitAlertAlertText.item
583 var value = acqLitAlertNoteValue.attr("value") || "";
585 var note = new fieldmapper.acqlin();
587 note.lineitem(li.id());
589 note.alert_text(alert_text);
591 self.updateLiNotes(li, note);
594 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
598 * Draws a single lineitem note in the notes pane
600 this.addLiNote = function(li, note) {
601 if(note.isdeleted()) return;
603 var row = self.liNotesRow.cloneNode(true);
604 nodeByName("value", row).innerHTML = note.value();
605 var alert_node = nodeByName("alert_code", row);
606 if (note.alert_text()) {
607 alert_node.innerHTML = note.alert_text().code();
608 if (note.alert_text().description()) {
611 "connectId": [alert_node],
612 "label": note.alert_text().description()
613 }, dojo.create("span", null, alert_node, "after")
618 if (openils.Util.isTrue(note.vendor_public()))
619 nodeByName("vendor_public", row).innerHTML =
620 localeStrings.VENDOR_PUBLIC;
622 nodeByName("delete", row).onclick = function() {
623 note.isdeleted(true);
624 self.liNotesTbody.removeChild(row);
625 self.updateLiNotes(li);
628 if(note.edit_time()) {
629 nodeByName("edit_time", row).innerHTML =
630 dojo.date.locale.format(
631 dojo.date.stamp.fromISOString(note.edit_time()),
632 {formatLength:'short'});
635 self.liNotesTbody.appendChild(row);
639 * Updates any new/changed/deleted notes on the server
641 this.updateLiNotes = function(li, newNote) {
647 notes = li.lineitem_notes().filter(
649 if(note.ischanged() || note.isnew() || note.isdeleted())
655 if(notes.length == 0) return;
656 progressDialog.show();
658 fieldmapper.standardRequest(
659 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
661 params : [this.authtoken, notes],
662 onresponse : function(r) {
663 var resp = openils.Util.readResponse(r);
668 // remove the old changed notes
670 dojo.forEach(li.lineitem_notes(),
672 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
676 li.lineitem_notes(list);
679 progressDialog.hide();
680 self.updateLiNotesCount(li);
681 self.drawLiNotes(li);
685 progressDialog.update(resp);
686 var newnote = resp.note;
688 if(!newnote.isdeleted()) {
689 newnote.isnew(false);
690 newnote.ischanged(false);
691 li.lineitem_notes().push(newnote);
698 this.updateLiPrice = function(input, li) {
700 var price = input.value;
701 if(Number(price) == Number(li.estimated_unit_price())) return;
703 fieldmapper.standardRequest(
704 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
706 params : [this.authtoken, li.id(), price],
707 oncomplete : function(r) {
708 openils.Util.readResponse(r);
709 li.estimated_unit_price(price); // update local copy
715 this.removeLineitem = function(liId) {
716 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
717 delete this.liCache[liId];
718 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
721 this.drawInfo = function(liId) {
722 if (!this._isRelatedViewer) {
723 var d = dojo.byId("acq-lit-info-related");
724 if (!this.relCache[liId]) {
725 fieldmapper.standardRequest(
728 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
731 "params": [openils.User.authtoken, liId],
732 "onresponse": function(r) {
733 self.relCache[liId] = openils.Util.readResponse(r);
734 nodeByName("related_number", d).innerHTML =
737 self.relCache[liId] >1 ? "show" : "hide"
743 nodeByName("related_number", d).innerHTML = this.relCache[liId];
744 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
749 openils.acq.Lineitem.fetchAttrDefs(
751 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
756 this._fetchLineitem = function(liId, handler, force) {
758 var li = this.liCache[liId];
759 if(li && li.marc() && li.lineitem_details() && !force)
762 fieldmapper.standardRequest(
763 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve'],
766 params: [self.authtoken, liId, {
768 flesh_cancel_reason: true,
769 flesh_li_details: true,
771 flesh_fund_debit: true }],
773 oncomplete: function(r) {
774 var li = openils.Util.readResponse(r);
781 this._drawInfo = function(li) {
783 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
786 openils.Util.hide('acq-lit-marc-order-record-label');
787 openils.Util.hide(acqLitEditOrderMarc.domNode);
788 openils.Util.show('acq-lit-marc-real-record-label');
790 openils.Util.show('acq-lit-marc-order-record-label');
791 openils.Util.show(acqLitEditOrderMarc.domNode);
792 openils.Util.hide('acq-lit-marc-real-record-label');
795 this.drawMarcHTML(li);
796 this.infoTbody = dojo.byId('acq-lit-info-tbody');
799 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
800 while(this.infoTbody.childNodes[0])
801 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
803 for(var i = 0; i < li.attributes().length; i++) {
804 var attr = li.attributes()[i];
805 var row = this.infoRow.cloneNode(true);
807 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
808 var name = openils.acq.Lineitem.attrDefs[type].filter(
810 return (a.code() == attr.attr_name());
812 ).pop().description();
814 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
815 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
816 this.infoTbody.appendChild(row);
819 if (!this._isRelatedViewer) {
820 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
821 oilsBasePath + "/acq/lineitem/related/" + li.id();
826 openils.Util.show('acq-lit-info-cat-link');
827 var link = dojo.byId('acq-lit-info-cat-link').getElementsByTagName('a')[0];
829 if(openils.XUL.isXUL()) {
831 link.setAttribute('href', 'javascript:void(0);');
832 link.onclick = this.generateMakeRecTab( li.eg_bib_id() );
835 var href = link.getAttribute('href');
837 link.setAttribute('href', href + li.eg_bib_id());
840 openils.Util.hide('acq-lit-info-cat-link');
844 this.generateMakeRecTab = function(bib_id,default_view, row) {
848 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
851 show_nav_buttons : true,
852 show_print_button : true,
853 opac_url : xulG.url_prefix(xulG.urls.opac_rdetail + '?r=' + bib_id),
854 default_view : default_view
858 if(row) nodeByName("action_none", row).selected = true;
862 this.drawMarcHTML = function(li) {
863 var params = [null, true, li.marc()];
865 params = [li.eg_bib_id(), true];
867 fieldmapper.standardRequest(
868 ['open-ils.search', 'open-ils.search.biblio.record.html'],
871 oncomplete: function(r) {
872 dojo.byId('acq-lit-marc-div').innerHTML =
873 openils.Util.readResponse(r);
879 this.drawCopies = function(liId) {
883 this.copyWidgetCache = {};
884 this.oldCopyWidgetCache = {};
885 this.virtDfaCounts = {};
886 this.realDfaCache = {};
889 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
890 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
891 acqLitCopyCountInput.attr('value', '0');
893 while(this.copyTbody.childNodes[0])
894 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
896 this._drawBatchCopyWidgets();
898 this._drawDistribApplied(liId);
900 this._fetchDistribFormulas(
902 openils.acq.Lineitem.fetchAttrDefs(
904 self._fetchLineitem(liId, function(li){self._drawCopies(li);});
911 this._saveDistribAppliedTemplates = function() {
912 if (!this._appliedDistribTemplate) {
913 this._appliedDistribTemplate =
914 dojo.byId("acq-lit-distrib-applied-tbody").
915 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
916 dojo.attr(this._appliedDistribTemplate, "id");
920 this._drawDistribApplied = function(liId) {
921 /* Build this table while hidden to prevent rendering artifacts */
922 openils.Util.hide("acq-lit-distrib-applied-tbody");
924 this._saveDistribAppliedTemplates();
926 /* Remove any rows in the table from previous populations */
927 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
928 forEach(dojo.destroy);
930 /* Unregister all dijits previously created (for some reason this isn't
931 * covered by the above destroy calls). */
932 dijit.registry.forEach(
933 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
936 /* Populate the table with our liId */
938 fieldmapper.standardRequest(
940 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
943 "params": [self.authtoken, liId],
944 "onresponse": function(r) {
945 var dfa = openils.Util.readResponse(r);
948 self.realDfaCache[dfa.id()] = dfa;
949 self._drawDistribAppliedUnit(dfa);
952 "oncomplete": function() {
953 /* Reveal built table */
956 "acq-lit-distrib-applied-tbody", "table-row-group"
964 this._drawDistribAppliedUnit = function(dfa) {
966 var row = dojo.query(
967 'tr[formula="' + dfa.formula().id() + '"]',
968 "acq-lit-distrib-applied-tbody"
973 row = dojo.clone(this._appliedDistribTemplate);
974 dojo.attr(row, "formula", dfa.formula().id());
975 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
978 var td = dojo.query("td", row)[0];
980 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
981 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
984 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
986 new dijit.form.Button(
988 "onClick": function() {
989 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
993 /* XXX I /cannot/ make the following work in as a CSS class
994 * for some reason. So frustrating... */
995 "style": function(id) {
997 "font-weight: bold; color: #c00;" :
999 }(dfa.id()) + "margin: 0 6px;display: inline;"
1000 }, "dfa-button-" + dfa.id()
1004 "connectId": ["dfa-button-" + dfa.id()],
1005 "label": dojo.string.substitute(
1006 localeStrings.DFA_TIP, dfa.id() > 0 ? [
1007 openils.User.formalName(dfa.creator()),
1008 dojo.date.locale.format(
1009 dojo.date.stamp.fromISOString(dfa.create_time()),
1010 {"formatLength":"short"}
1012 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
1014 }, "dfa-tip-" + dfa.id()
1018 this.deleteDfa = function(dfa) {
1019 if (dfa.id() > 0) { /* real */
1020 this.pcrud.eliminate(
1023 "oncomplete": function() {
1024 self._removeDistribApplied(dfa.id());
1025 delete self.realDfaCache[dfa.id()];
1029 } else { /* virtual */
1030 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
1031 this.virtDfaCounts[dfa.formula().id()] = 0;
1032 /* hasn't been saved yet, so no need to do anything server side */
1033 this._removeDistribApplied(dfa.id());
1038 this._removeDistribApplied = function(dfaId) {
1039 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
1040 dijit.registry.forEach(
1041 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
1043 this._removeDistribAppliedEmptyRows();
1046 this._removeAllDistribAppliedVirtual = function() {
1047 /* Unregister dijits */
1048 dijit.registry.forEach(
1049 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
1051 this._removeDistribAppliedEmptyRows();
1054 this._removeDistribAppliedEmptyRows = function() {
1055 /* Remove any rows with no DFA at all */
1056 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
1058 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
1064 * Insert a new row into the distribution formula selection form
1066 this._addDistribFormulaRow = function() {
1069 if (!self.distribForms) {
1070 // no formulas, hide the form
1071 openils.Util.hide('acq-lit-distrib-formula-tbody');
1075 if(!this.distribFormulaTemplate)
1076 this.distribFormulaTemplate =
1077 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
1079 var row = this.distribFormulaTemplate.cloneNode(true);
1080 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
1082 this.dfSelector = new dijit.form.FilteringSelect(
1083 {"labelAttr": "dynLabel", "labelType": "html"},
1084 nodeByName("selector", row)
1086 this._updateFormulaStore();
1087 this.dfSelector.fetchProperties =
1088 {"sort": [{"attribute": "use_count", "descending": true}]};
1090 var apply = new dijit.form.Button(
1091 {"label": localeStrings.APPLY},
1092 nodeByName('set_button', row)
1095 var reset = new dijit.form.Button(
1096 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
1097 nodeByName("reset_button", row)
1100 dojo.connect(apply, 'onClick',
1102 var form_id = self.dfSelector.attr("value");
1103 if(!form_id) return;
1104 self._applyDistribFormula(form_id);
1105 reset.attr("disabled", false);
1109 dojo.connect(reset, 'onClick',
1111 self.restoreCopyFieldsBeforeDF();
1112 self.virtDfaCounts = {};
1113 self.virtDfaId = -1;
1115 self._updateFormulaStore();
1116 self._removeAllDistribAppliedVirtual();
1117 reset.attr("disabled", "true");
1124 * Applies a distrib formula to the current set of copies
1126 this._applyDistribFormula = function(formula) {
1127 if(!formula) return;
1129 formula = this.distribForms.filter(
1130 function(form) { return form.id() == formula; }
1133 var copyRows = dojo.query('tr', self.copyTbody);
1135 if (this.dfeOffset >= copyRows.length) {
1136 alert(localeStrings.OUT_OF_COPIES);
1140 var entries_applied = 0;
1142 var rowIndex = this.dfeOffset;
1143 rowIndex < copyRows.length;
1147 var row = copyRows[rowIndex];
1148 var copy_id = row.getAttribute('copy_id');
1149 var copyWidgets = this.copyWidgetCache[copy_id];
1150 var entryIndex = this.dfeOffset;
1153 // find the correct entry for the current row
1154 dojo.forEach(formula.entries(),
1157 entryIndex += e.item_count();
1158 if(entryIndex > rowIndex)
1166 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
1167 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
1170 this.saveCopyFieldsBeforeDF(copy_id);
1171 this._copy_fields_for_acqdf.forEach(
1173 if(entry[field]()) {
1174 copyWidgets[field].attr('value', (entry[field]()));
1181 if (entries_applied) {
1182 this.virtDfaCounts[formula.id()] =
1183 ++(this.virtDfaCounts[formula.id()]) || 1;
1184 this._updateFormulaStore();
1185 this._drawDistribAppliedUnit(
1187 var dfa = new acqdfa();
1188 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
1191 this.dfeOffset += entries_applied;
1196 * This function updates the DF store for the dropdown so that use_counts
1197 * can reflect DF applications from this session before they're saved
1200 this._updateFormulaStore = function() {
1201 this.dfSelector.store = new dojo.data.ItemFileReadStore(
1203 "data": self._labelFormulasWithCounts(
1204 acqdf.toStoreData(self.distribForms)
1210 this.saveCopyFieldsBeforeDF = function(copy_id) {
1212 if (!this.oldCopyWidgetCache[copy_id]) {
1213 var copyWidgets = this.copyWidgetCache[copy_id];
1215 this.oldCopyWidgetCache[copy_id] = {};
1216 this._copy_fields_for_acqdf.forEach(
1218 self.oldCopyWidgetCache[copy_id][f] =
1219 copyWidgets[f].attr("value");
1225 this.restoreCopyFieldsBeforeDF = function() {
1227 for (var copy_id in this.oldCopyWidgetCache) {
1228 this._copy_fields_for_acqdf.forEach(
1230 self.copyWidgetCache[copy_id][f].attr(
1231 "value", self.oldCopyWidgetCache[copy_id][f]
1238 this._labelFormulasWithCounts = function(store_data) {
1239 for (var key in store_data.items) {
1240 var obj = store_data.items[key];
1241 obj.use_count = Number(obj.use_count); /* needed for sorting */
1243 if (this.virtDfaCounts[obj.id])
1244 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
1246 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
1247 obj.use_count + "]</span> " + obj.name;
1253 * This method formerly would not refetch the DF formulas if they'd been
1254 * loaded already, but now it always re-fetches, since use_count changes.
1256 this._fetchDistribFormulas = function(onload) {
1257 fieldmapper.standardRequest(
1259 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
1262 "params": [openils.User.authtoken],
1263 "oncomplete": function(r) {
1264 self.distribForms = openils.Util.readResponse(r);
1265 if(!self.distribForms || self.distribForms.length == 0) {
1266 self.distribForms = [];
1268 self._addDistribFormulaRow();
1275 this._drawBatchCopyWidgets = function() {
1276 var row = this.copyBatchRow;
1277 dojo.forEach(liDetailBatchFields,
1279 if(self.copyBatchRowDrawn) {
1280 self.copyBatchWidgets[field].attr('value', null);
1282 var widget = new openils.widget.AutoFieldWidget({
1285 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1286 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1287 searchFilter : (field == 'fund') ? {"active": "t"} : null,
1288 parentNode : dojo.query('[name='+field+']', row)[0],
1289 orgLimitPerms : ['CREATE_PICKLIST'],
1292 "labelType": (field == "fund") ? "html" : null
1294 noCache: (field == "fund"),
1299 if (field == "fund" && w.store)
1300 self._ensureCSSFundClasses(w.store);
1301 self.copyBatchWidgets[field] = w;
1304 if (field == "fund") {
1306 widget.widget, "onChange", function(val) {
1307 self._updateFundSelectorStyle(widget, val);
1314 this.copyBatchRowDrawn = true;
1317 this.batchCopyUpdate = function() {
1319 for(var k in this.copyWidgetCache) {
1320 var cache = this.copyWidgetCache[k];
1321 dojo.forEach(liDetailBatchFields, function(f) {
1322 var newval = self.copyBatchWidgets[f].attr('value');
1323 if(newval) cache[f].attr('value', newval);
1328 this._drawCopies = function(li) {
1331 // this button sets the total number of copies for a given lineitem
1332 acqLitAddCopyCount.onClick = function() {
1333 var count = acqLitCopyCountInput.attr('value');
1336 while(self.copyCount() < count)
1339 // delete rows if necessary
1340 var diff = self.copyCount() - count;
1342 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
1343 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
1344 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
1346 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1352 if(li.lineitem_details().length > 0) {
1353 dojo.forEach(li.lineitem_details(),
1355 self.addCopy(li, copy);
1363 this.copyCount = function() {
1365 for(var id in this.copyCache) {
1366 if(!this.copyCache[id].isdeleted())
1372 this.virtCopyId = -1;
1373 this.addCopy = function(li, copy) {
1374 var row = this.copyRow.cloneNode(true);
1375 this.copyTbody.appendChild(row);
1379 copy = new fieldmapper.acqlid();
1381 copy.id(this.virtCopyId--);
1382 copy.lineitem(li.id());
1385 this.copyCache[copy.id()] = copy;
1386 row.setAttribute('copy_id', copy.id());
1387 self.copyWidgetCache[copy.id()] = {};
1389 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1391 dojo.forEach(liDetailFields,
1394 if (field == "fund") {
1395 searchFilter = (copy.fund() ?
1396 {"-or": {"active": "t", "id": copy.fund()}} :
1399 searchFilter = null;
1402 var readOnly = false;
1404 // TODO: Add support for changing the owning_lib after real copies have been made.
1405 // owning_lib is order data as much as its item data
1406 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
1410 // TODO: add support for changing the fund after debits have been created
1411 // Note: invoicing allows the change
1412 if(copy.fund_debit() && field == 'fund') {
1416 var widget = new openils.widget.AutoFieldWidget({
1419 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1420 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1421 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1422 searchFilter : searchFilter,
1423 noCache: (field == "fund"),
1425 parentNode : dojo.query('[name='+field+']', row)[0],
1426 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
1427 readOnly : readOnly,
1430 // make sure we capture the value from any async widgets
1432 if (field == "fund" && w.store)
1433 self._ensureCSSFundClasses(w.store);
1434 copy[field](ww.getFormattedValue())
1435 self.copyWidgetCache[copy.id()][field] = w;
1438 dojo.connect(widget.widget, 'onChange',
1440 if (field == "fund")
1441 self._updateFundSelectorStyle(widget, val);
1443 if (copy.isnew() || val != copy[field]()) {
1444 // prevent setting ischanged() automatically on widget load for existing copies
1445 copy[field](widget.getFormattedValue())
1446 copy.ischanged(true);
1453 this.updateLidState(copy, row);
1456 this._ensureCSSFundClass = function(id) {
1457 if (!this.fundStyleSheet) {
1459 "style", {"type": "text/css"},
1460 document.getElementsByTagName("head")[0], "last"
1462 this.fundStyleSheet = document.styleSheets[
1463 document.styleSheets.length - 1
1467 var cn = "fund_" + id;
1468 if (!this.haveFundClass[cn]) {
1469 fieldmapper.standardRequest(
1470 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
1472 "params": [openils.User.authtoken, id],
1474 "oncomplete": function(r) {
1475 r = openils.Util.readResponse(r);
1476 self.fundBalanceState[id] = r;
1478 if (r[0] /* stop */)
1479 style = fundStyles.stop;
1480 else if (r[1] /* warning */)
1481 style = fundStyles.warning;
1482 self.fundStyleSheet.insertRule(
1483 "." + cn + " { " + style + " }",
1484 self.fundStyleSheet.cssRules.length
1486 self.haveFundClass[cn] = true;
1493 this._ensureCSSFundClasses = function(store) {
1495 "query": {"id": "*"},
1496 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
1500 this._updateFundSelectorStyle = function(widget, fund_id) {
1501 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
1502 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
1505 this.updateLidState = function(copy, row) {
1506 if (typeof(row) == "undefined") {
1508 'tr[copy_id="' + copy.id() + '"]', this.copyTbody
1513 var recv_link = nodeByName("receive", row);
1514 var unrecv_link = nodeByName("unreceive", row);
1515 var del_link = nodeByName("delete", row);
1516 var cxl_link = nodeByName("cancel", row);
1517 var claim_link = nodeByName("claim", row);
1518 var cxl_reason_link = nodeByName("cancel_reason", row);
1520 if (copy.cancel_reason()) {
1521 openils.Util.hide(del_link.parentNode);
1522 openils.Util.hide(recv_link);
1523 openils.Util.hide(unrecv_link);
1524 openils.Util.hide(cxl_link);
1525 openils.Util.hide(claim_link);
1527 /* XXX the following may leak memory in a long lived table: dijits may not get destroyed... not positive. revisit. */
1528 var holds_reason = dojo.create(
1530 "style": "border-bottom: 1px dashed #000;",
1531 "innerHTML": "Cancelled" /* XXX [sic] and i18n */
1532 }, cxl_reason_link, "only"
1536 "label": "<em>" + copy.cancel_reason().label() +
1537 "</em><br />" + copy.cancel_reason().description(),
1538 "connectId": [holds_reason]
1539 }, dojo.create("span", null, cxl_reason_link, "last")
1541 openils.Util.show(cxl_reason_link, "inline");
1542 } else if (this.isPO) {
1543 /* Only using this in one place so far, but may want it for better
1544 * decisions on when to display certain controls. */
1545 var li_state = this.liCache[copy.lineitem()].state();
1547 openils.Util.hide(del_link.parentNode);
1548 openils.Util.hide(cxl_reason_link);
1550 /* Avoid showing (un)receive links, cancel links, for virt copies */
1551 if (copy.id() > 0) {
1552 if (copy.recv_time()) {
1553 openils.Util.hide(cxl_link);
1554 openils.Util.hide(recv_link);
1555 openils.Util.hide(claim_link);
1557 openils.Util.show(unrecv_link, "inline");
1558 unrecv_link.onclick = function() {
1559 if (confirm(localeStrings.UNRECEIVE_LID))
1560 self.issueReceive(copy, /* rollback */ true);
1563 openils.Util.hide(unrecv_link);
1565 if (this.claimEligibleLid[copy.id()]) {
1566 openils.Util.show(claim_link, "inline");
1567 claim_link.onclick = function() {
1568 self.claimDialog.show(
1569 self.liCache[copy.lineitem()], copy.id()
1573 openils.Util.hide(claim_link);
1576 openils.Util[li_state == "on-order" ? "show" : "hide"](
1579 openils.Util.show(cxl_link, "inline");
1580 recv_link.onclick = function() {
1581 if (self.checkLiAlerts(copy.lineitem()))
1582 self.issueReceive(copy);
1584 cxl_link.onclick = function() {
1585 self.cancelLid(copy.id());
1589 openils.Util.hide(cxl_link);
1590 openils.Util.hide(unrecv_link);
1591 openils.Util.hide(recv_link);
1592 openils.Util.hide(claim_link);
1595 openils.Util.hide(unrecv_link);
1596 openils.Util.hide(recv_link);
1597 openils.Util.hide(cxl_reason_link);
1598 openils.Util.hide(claim_link);
1600 del_link.onclick = function() { self.deleteCopy(row) };
1601 openils.Util.show(del_link.parentNode);
1605 this.cancelLid = function(lid_id) {
1606 lidCancelDialog._lid_id = lid_id;
1607 openils.Util.show(lidCancelDialog.domNode.parentNode);
1608 lidCancelDialog.show();
1609 if (!lidCancelDialog._prepared) {
1610 var widget = new openils.widget.AutoFieldWidget({
1611 "fmField": "cancel_reason",
1612 "fmClass": "acqlid",
1613 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
1614 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1619 acqLidCancelButton.onClick = function() {
1620 if (w.attr("value")) {
1621 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
1623 lidCancelDialog._lid_id,
1627 lidCancelDialog.hide();
1630 lidCancelDialog._prepared = true;
1636 this._cancelLid = function(lid_id, reason) {
1637 fieldmapper.standardRequest(
1638 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
1639 "params": [openils.User.authtoken, lid_id, reason],
1641 "onresponse": function(r) {
1642 if (r = openils.Util.readResponse(r)) {
1644 for (var id in r.lid) {
1645 /* actually this should only iterate once */
1646 self.copyCache[id].cancel_reason(
1647 r.lid[id].cancel_reason
1649 self.updateLidState(self.copyCache[id]);
1658 this._confirmAlert = function(li, lin) {
1660 dojo.string.substitute(
1661 localeStrings.CONFIRM_LI_ALERT, [
1662 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1663 "title", "lineitem_marc_attr_definition"
1665 lin.alert_text().code(),
1666 lin.alert_text().description() || "",
1673 this.checkLiAlerts = function(li_id) {
1674 var li = this.liCache[li_id];
1676 var alert_notes = li.lineitem_notes().filter(
1677 function(o) { return Boolean(o.alert_text()); }
1680 /* this is _intentionally_ not done in a call to forEach() ... */
1681 for (var i = 0; i < alert_notes.length; i++) {
1682 if (this.noteAcks[alert_notes[i].id()])
1684 else if (!this._confirmAlert(li, alert_notes[i]))
1687 this.noteAcks[alert_notes[i].id()] = true;
1693 this.deleteCopy = function(row) {
1694 var copy = this.copyCache[row.getAttribute('copy_id')];
1695 copy.isdeleted(true);
1697 delete this.copyCache[copy.id()];
1698 this.copyTbody.removeChild(row);
1701 this._virtDfaCountsAsList = function() {
1703 for (var key in this.virtDfaCounts) {
1704 for (var i = 0; i < this.virtDfaCounts[key]; i++)
1710 this.confirmBreachedCopyFunds = function(copies) {
1711 var stop = 0, warning = 0;
1715 var state = self.fundBalanceState[o.fund()];
1716 if (state[0] /* stop */)
1718 else if (state[1] /* warning */)
1725 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
1726 } else if (warning) {
1727 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
1732 this.saveCopyChanges = function(liId) {
1738 for(var id in this.copyCache) {
1739 var c = this.copyCache[id];
1740 if(!c.isdeleted()) total++;
1741 if(c.isnew() || c.ischanged() || c.isdeleted()) {
1742 if(c.id() < 0) c.id(null);
1748 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
1751 if (copies.length > 0) {
1752 if (!this.confirmBreachedCopyFunds(copies))
1755 if (typeof(this._copy_count_cb) == "function")
1756 this._copy_count_cb(liId, total);
1758 openils.Util.show("acq-lit-update-copies-progress");
1759 fieldmapper.standardRequest(
1760 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1762 params: [openils.User.authtoken, copies],
1763 onresponse: function(r) {
1764 var res = openils.Util.readResponse(r);
1765 litUpdateCopiesProgress.update(res);
1767 oncomplete: function() {
1768 self.drawCopies(liId);
1769 openils.Util.hide("acq-lit-update-copies-progress");
1775 var dfa_list = this._virtDfaCountsAsList();
1776 if (dfa_list.length > 0) {
1777 fieldmapper.standardRequest(
1779 "open-ils.acq.distribution_formula.record_application"],
1782 "params": [openils.User.authtoken, dfa_list, liId],
1783 "onresponse": function(r) {
1784 var res = openils.Util.readResponse(r);
1785 if (res && res.length < dfa_list.length)
1786 alert(localeStrings.DFA_NOT_ALL);
1790 this.virtDfaCounts = {};
1794 this._updateCreatePoPrepayCheckbox = function(prepay) {
1795 var prepay = openils.Util.isTrue(prepay);
1796 this._prepayRequiredByVendor = prepay;
1797 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
1800 this._confirmPoPrepaySituation = function() {
1801 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
1802 if (want_prepay != this._prepayRequiredByVendor) {
1805 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
1806 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
1813 this.applySelectedLiAction = function(action) {
1817 case 'delete_selected':
1818 this._deleteLiList(self.getSelected());
1821 case 'create_order':
1823 if(!this.createPoProviderSelector) {
1824 var widget = new openils.widget.AutoFieldWidget({
1825 fmField : 'provider',
1827 searchFilter: {"active": "t"},
1828 parentNode : dojo.byId('acq-lit-po-provider'),
1830 "onChange": function() {
1832 self._updateCreatePoPrepayCheckbox(
1833 this.item.prepayment_required
1840 function(w) { self.createPoProviderSelector = w; }
1844 if(!this.createPoAgencySelector) {
1845 var widget = new openils.widget.AutoFieldWidget({
1846 fmField : 'ordering_agency',
1848 parentNode : dojo.byId('acq-lit-po-agency'),
1849 orgLimitPerms : ['CREATE_PURCHASE_ORDER'],
1852 function(w) { self.createPoAgencySelector = w; }
1857 acqLitPoCreateDialog.show();
1860 case 'save_picklist':
1861 this._loadPLSelect();
1862 acqLitSavePlDialog.show();
1865 case 'selector_ready':
1867 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
1868 acqLitChangeLiStateDialog.show();
1879 case 'rollback_receive_po':
1880 this.rollbackPoReceive();
1883 case 'create_assets':
1884 this.createAssets();
1887 case 'export_attr_list':
1888 this.chooseExportAttr();
1891 case 'add_brief_record':
1893 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
1895 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
1899 case "cancel_lineitems":
1900 this.maybeCancelLineitems();
1903 case "change_claim_policy":
1904 var li_list = this.getSelected();
1905 this.claimPolicyPicker.attr("value", null);
1906 liClaimPolicyDialog.show();
1907 liClaimPolicySave.onClick = function() {
1908 self.changeClaimPolicy(
1910 self.claimPolicyPicker.attr("value"),
1913 function(li) { self.setClaimPolicyControl(li); }
1915 liClaimPolicyDialog.hide();
1923 this.changeClaimPolicy = function(li_list, value, callback) {
1925 function(li) { li.claim_policy(value); }
1927 fieldmapper.standardRequest(
1928 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
1929 "params": [openils.User.authtoken, li_list],
1931 "oncomplete": function(r) {
1932 r = openils.Util.readResponse(r);
1933 if (callback) callback(r);
1939 this.createAssets = function() {
1940 if(!this.isPO) return;
1941 if(!confirm(localeStrings.CREATE_PO_ASSETS_CONFIRM)) return;
1942 this.show('acq-lit-progress-numbers');
1944 fieldmapper.standardRequest(
1945 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
1947 params: [this.authtoken, this.isPO],
1948 onresponse: function(r) {
1949 var resp = openils.Util.readResponse(r);
1950 self._updateProgressNumbers(resp, true);
1956 this.maybeCancelLineitems = function() {
1957 openils.Util.show("acq-lit-cancel-reason", "inline");
1958 if (!acqLitCancelLineitemsButton._prepared) {
1959 var widget = new openils.widget.AutoFieldWidget({
1960 "fmField": "cancel_reason",
1962 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
1963 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1968 acqLitCancelLineitemsButton.onClick = function() {
1969 if (w.attr("value")) {
1970 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
1971 self._cancelLineitems(w.attr("value"));
1973 openils.Util.hide("acq-lit-cancel-reason");
1976 acqLitCancelLineitemsButton._prepared = true;
1982 this._cancelLineitems = function(reason) {
1983 var id_list = this.getSelected().map(function(o) { return o.id(); });
1984 fieldmapper.standardRequest(
1985 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
1986 "params": [openils.User.authtoken, id_list, reason],
1988 "onresponse": function(r) {
1989 if (r = openils.Util.readResponse(r)) {
1991 for (var id in r.li) {
1992 self.liCache[id].state(r.li[id].state);
1993 self.liCache[id].cancel_reason(
1994 r.li[id].cancel_reason
1996 self.updateLiState(self.liCache[id]);
1999 if (r.lid && self.copyCache) {
2000 for (var id in r.lid) {
2001 if (self.copyCache[id]) {
2002 self.copyCache[id].cancel_reason(
2003 r.lid[id].cancel_reason
2005 self.updateLidState(self.copyCache[id]);
2015 this.chooseExportAttr = function() {
2016 if (!acqLitExportAttrSelector._li_setup) {
2018 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
2020 "data": acqliad.toStoreData(
2022 "acqliad", {"code": li_exportable_attrs}
2027 acqLitExportAttrSelector.setValue();
2028 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
2029 acqLitExportAttrSelector._li_setup = true;
2031 openils.Util.show("acq-lit-export-attr-holder", "inline");
2034 this.exportAttrList = function() {
2035 var attr_def = acqLitExportAttrSelector.item;
2036 var li_list = this.getSelected();
2037 var value_list = li_list.map(
2039 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2040 attr_def.code, "lineitem_marc_attr_definition"
2043 ).filter(function(attr) { return Boolean(attr); });
2045 if (value_list.length > 0) {
2046 if (value_list.length < li_list.length) {
2048 dojo.string.substitute(
2049 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
2056 openils.XUL.contentToFileSaveDialog(
2057 value_list.join("\n"),
2058 localeStrings.EXPORT_SAVE_DIALOG_TITLE
2064 alert(dojo.string.substitute(
2065 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
2069 openils.Util.hide("acq-lit-export-attr-holder");
2072 this.printPO = function() {
2073 if(!this.isPO) return;
2074 progressDialog.show(true);
2075 fieldmapper.standardRequest(
2076 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
2078 params: [this.authtoken, this.isPO, 'html'],
2079 oncomplete: function(r) {
2080 progressDialog.hide();
2081 var evt = openils.Util.readResponse(r);
2082 if(evt && evt.template_output()) {
2083 win = window.open('','', 'resizable,width=800,height=600,scrollbars=1');
2084 win.document.body.innerHTML = evt.template_output().data();
2092 this.receivePO = function() {
2093 if (!this.isPO) return;
2095 for (var id in this.liCache) {
2096 /* assumption: liCache reflects exactly the
2097 * set of LIs that belong to our PO */
2098 if (this.liCache[id].state() != "received" &&
2099 !this.checkLiAlerts(id)) return;
2102 this.show('acq-lit-progress-numbers');
2104 fieldmapper.standardRequest(
2105 ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
2107 params: [this.authtoken, this.isPO],
2108 onresponse : function(r) {
2109 var resp = openils.Util.readResponse(r);
2110 self._updateProgressNumbers(resp, true);
2116 this.issueReceive = function(obj, rollback) {
2117 /* (For now) there shall be no marking LI or LIDs (un)received
2118 * except from the actual "view PO" interface. */
2119 if (!this.isPO) return;
2122 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
2124 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
2126 progressDialog.show(true);
2127 fieldmapper.standardRequest(
2128 ["open-ils.acq", method], {
2130 "params": [this.authtoken, obj.id()],
2131 "onresponse": function(r) {
2132 if (r = openils.Util.readResponse(r)) {
2133 self.fetchClaimInfo(
2134 part == "lineitem" ? obj.id() : obj.lineitem(),
2136 function() { self.handleReceive(r); }
2138 progressDialog.hide();
2146 * Handles the responses from receive and rollback ML calls.
2148 this.handleReceive = function(resp) {
2151 for (var li_id in resp.li) {
2152 for (var key in resp.li[li_id])
2153 self.liCache[li_id][key](resp.li[li_id][key]);
2154 self.updateLiState(self.liCache[li_id]);
2158 if (typeof(self.poUpdateCallback) == "function")
2159 self.poUpdateCallback(resp.po);
2162 for (var lid_id in resp.lid) {
2163 for (var key in resp.lid[lid_id])
2164 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
2165 self.updateLidState(self.copyCache[lid_id]);
2171 this.rollbackPoReceive = function() {
2172 if(!this.isPO) return;
2173 if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
2174 this.show('acq-lit-progress-numbers');
2176 fieldmapper.standardRequest(
2177 ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
2179 params: [this.authtoken, this.isPO],
2180 onresponse : function(r) {
2181 var resp = openils.Util.readResponse(r);
2182 self._updateProgressNumbers(resp, true);
2188 this._updateProgressNumbers = function(resp, reloadOnComplete) {
2190 dojo.byId('acq-pl-lit-li-processed').innerHTML = resp.li;
2191 dojo.byId('acq-pl-lit-lid-processed').innerHTML = resp.lid;
2192 dojo.byId('acq-pl-lit-debits-processed').innerHTML = resp.debits_accrued;
2193 dojo.byId('acq-pl-lit-bibs-processed').innerHTML = resp.bibs;
2194 dojo.byId('acq-pl-lit-indexed-processed').innerHTML = resp.indexed;
2195 dojo.byId('acq-pl-lit-copies-processed').innerHTML = resp.copies;
2196 if(resp.complete && reloadOnComplete)
2197 location.href = location.href;
2201 this._createPO = function(fields) {
2202 this.show('acq-lit-progress-numbers');
2203 var po = new fieldmapper.acqpo();
2204 po.provider(this.createPoProviderSelector.attr('value'));
2205 po.ordering_agency(this.createPoAgencySelector.attr('value'));
2206 po.prepayment_required(fields.prepayment_required[0] ? true : false);
2208 var selected = this.getSelected( (fields.create_from == 'all') );
2209 if(selected.length == 0) return;
2211 var max = selected.length * 3;
2214 fieldmapper.standardRequest(
2215 ['open-ils.acq', 'open-ils.acq.purchase_order.create'],
2218 openils.User.authtoken,
2221 lineitems : selected.map(function(li) { return li.id() }),
2222 create_assets : fields.create_assets[0],
2226 onresponse : function(r) {
2227 var resp = openils.Util.readResponse(r);
2228 self._updateProgressNumbers(resp);
2230 location.href = oilsBasePath + '/acq/po/view/' + resp.purchase_order.id();
2236 this._deleteLiList = function(list, idx) {
2237 if(idx == null) idx = 0;
2238 if(idx >= list.length) return;
2239 var liId = list[idx].id();
2240 fieldmapper.standardRequest(
2241 ['open-ils.acq', 'open-ils.acq.lineitem.delete'],
2243 params: [openils.User.authtoken, liId],
2244 oncomplete: function(r) {
2245 self.removeLineitem(liId);
2246 self._deleteLiList(list, ++idx);
2252 this.editOrderMarc = function(li) {
2254 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
2255 to true in about:config */
2257 if(!openils.XUL.enableXPConnect()) return;
2259 if(openils.XUL.isXUL()) {
2260 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
2262 win = window.open('/xul/server/cat/marcedit.xul');
2266 record : {marc : li.marc()},
2268 label: 'Save Record', // XXX I18N
2269 func: function(xmlString) {
2271 fieldmapper.standardRequest(
2272 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
2274 params: [openils.User.authtoken, li],
2275 oncomplete: function(r) {
2276 openils.Util.readResponse(r);
2278 self.drawInfo(li.id())
2287 this._savePl = function(values) {
2289 var selected = this.getSelected( (values.which == 'all') );
2290 openils.Util.show('acq-lit-generic-progress');
2292 if(values.new_name) {
2293 openils.acq.Picklist.create(
2294 {name: values.new_name},
2296 self._updateLiList(id, selected, 0,
2298 location.href = oilsBasePath + '/acq/picklist/view/' + id;
2302 } else if(values.existing_pl) {
2303 // update lineitems to use an existing picklist
2304 self._updateLiList(values.existing_pl, selected, 0,
2306 location.href = oilsBasePath + '/acq/picklist/view/' + values.existing_pl;
2311 this._updateLiState = function(values, state) {
2313 var selected = this.getSelected( (values.which == 'all') );
2314 if(!selected.length) return;
2315 dojo.forEach(selected, function(li) {li.state(state);});
2316 self._updateLiList(null, selected, 0,
2317 // TODO consider inline updates for efficiency
2318 function() { location.href = location.href }
2322 this._updateLiList = function(pl, list, idx, oncomplete) {
2323 if(idx >= list.length) return oncomplete();
2325 if(pl != null) li.picklist(pl);
2326 litGenericProgress.update({maximum: list.length, progress: idx});
2327 new openils.acq.Lineitem({lineitem:li}).update(
2329 self._updateLiList(pl, list, ++idx, oncomplete);
2334 this._loadPLSelect = function() {
2335 if(this._plSelectLoaded) return;
2337 function handleResponse(r) {
2338 plList.push(r.recv().content());
2340 var method = 'open-ils.acq.picklist.user.retrieve';
2341 fieldmapper.standardRequest(
2342 ['open-ils.acq', method],
2344 params: [this.authtoken],
2345 onresponse: handleResponse,
2346 oncomplete: function() {
2347 self._plSelectLoaded = true;
2348 acqLitAddExistingSelect.store =
2349 new dojo.data.ItemFileReadStore({data:acqpl.toStoreData(plList)});
2350 acqLitAddExistingSelect.setValue();
2356 this.showRealCopyEditUI = function(li) {
2361 this._fetchLineitem(li.id(),
2363 li = self.liCache[li.id()] = fullLi;
2367 id : li.lineitem_details().map(
2368 function(item) { return item.eg_copy_id() }
2372 oncomplete : function(r) {
2374 var r_list = openils.Util.readResponse( r );
2375 for (var i = 0; i < r_list.length; i++) {
2376 var copy = r_list[i];
2377 var volId = copy.call_number();
2378 var volume = self.volCache[volId];
2380 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2382 copy.call_number(volume);
2383 copyList.push(copy);
2386 // If we need to, we can pass in an update_copy function to handle the update instead of volume_item_creator
2387 xulG.volume_item_creator( { 'existing_copies' : copyList } );
2390 alert('error in oncomplete: ' + E);