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.skipInitialEligibilityCheck = false;
71 this.invoiceLinkDialogManager = new InvoiceLinkDialogManager("li");
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.connect(acqLitLiActionsSelector, 'onChange',
81 self.applySelectedLiAction(this.attr('value'))
82 acqLitLiActionsSelector.attr('value', '_');
85 acqLitCreatePoSubmit.onClick = function() {
86 if (self._confirmPoPrepaySituation()) {
87 acqLitPoCreateDialog.hide();
88 self._createPO(acqLitPoCreateDialog.getValues());
94 acqLitSavePlButton.onClick = function() {
95 acqLitSavePlDialog.hide();
96 self._savePl(acqLitSavePlDialog.getValues());
99 acqLitCancelLiStateButton.onClick = function() {
100 acqLitChangeLiStateDialog.hide();
102 acqLitSaveLiStateButton.onClick = function() {
103 acqLitChangeLiStateDialog.hide();
104 self._updateLiState(acqLitChangeLiStateDialog.getValues(), acqLitChangeLiStateDialog.attr('state'));
108 dojo.byId('acq-lit-select-toggle').onclick = function(){self.toggleSelect()};
109 dojo.byId('acq-lit-info-back-button').onclick = function(){self.show('list')};
110 dojo.byId('acq-lit-copies-back-button').onclick = function(){self.show('list')};
111 dojo.byId('acq-lit-notes-back-button').onclick = function(){self.show('list')};
112 dojo.byId('acq-lit-real-copies-back-button').onclick = function(){self.show('list')};
114 this.reset = function(keep_selectors) {
115 while(self.tbody.childNodes[0])
116 self.tbody.removeChild(self.tbody.childNodes[0]);
124 this.setNext = function(handler) {
125 var link = dojo.byId('acq-lit-next');
127 dojo.style(link, 'visibility', 'visible');
128 link.onclick = handler;
130 dojo.style(link, 'visibility', 'hidden');
134 this.setPrev = function(handler) {
135 var link = dojo.byId('acq-lit-prev');
137 dojo.style(link, 'visibility', 'visible');
138 link.onclick = handler;
140 dojo.style(link, 'visibility', 'hidden');
144 this.show = function(div) {
145 openils.Util.hide('acq-lit-table-div');
146 openils.Util.hide('acq-lit-info-div');
147 openils.Util.hide('acq-lit-li-details');
148 openils.Util.hide('acq-lit-notes-div');
149 openils.Util.hide('acq-lit-real-copies-div');
152 openils.Util.show('acq-lit-table-div');
155 openils.Util.show('acq-lit-info-div');
158 openils.Util.show('acq-lit-li-details');
161 openils.Util.show('acq-lit-real-copies-div');
164 openils.Util.show('acq-lit-notes-div');
168 openils.Util.show(div);
172 this.hide = function() {
176 this.toggleSelect = function() {
178 dojo.forEach(self.selectors, function(i){i.checked = false});
180 dojo.forEach(self.selectors, function(i){i.checked = true});
181 self.toggleState = !self.toggleState;
185 /** @param all If true, assume all are selected */
186 this.getSelected = function(all) {
188 var indices = {}; /* use to uniqify. needed in paging situations. */
189 dojo.forEach(self.selectors,
192 indices[i.parentNode.parentNode.getAttribute('li')] = true;
195 return openils.Util.objectProperties(indices).map(
196 function(liId) { return self.liCache[liId]; }
200 this.setRowAttr = function(td, liWrapper, field, type) {
201 var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
202 td.appendChild(document.createTextNode(val));
205 this.setClaimPolicyControl = function(li, row) {
206 if (!self.claimPolicyPicker) {
207 self.claimPolicyPicker = true; /* prevents a race condition */
208 new openils.widget.AutoFieldWidget({
209 "parentNode": "acq-lit-li-claim-policy",
211 "selfReference": true,
212 "dijitArgs": {"required": true}
213 }).build(function(w) { self.claimPolicyPicker = w; });
216 if (!row) row = this._findLiRow(li);
218 var actViewPolicy = nodeByName("action_view_claim_policy", row);
219 if (li.claim_policy())
220 actViewPolicy.innerHTML = localeStrings.CHANGE_CLAIM_POLICY;
222 if (!actViewPolicy.onclick) {
223 actViewPolicy.onclick = function() {
224 if (li.claim_policy())
225 self.claimPolicyPicker.attr("value", li.claim_policy());
226 liClaimPolicyDialog.show();
227 liClaimPolicySave.onClick = function() {
228 self.changeClaimPolicy(
229 [li], self.claimPolicyPicker.attr("value"),
231 self.setClaimPolicyControl(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)
295 this.fetchClaimInfo(li.id(), false, null, row);
297 this.updateLiNotesCount(li, row);
299 this.setClaimPolicyControl(li, row);
301 // show which PO this lineitem is a member of
302 if(li.purchase_order() && !this.isPO) {
304 this.poCache[li.purchase_order()] =
305 this.poCache[li.purchase_order()] ||
306 fieldmapper.standardRequest(
307 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
309 this.authtoken, li.purchase_order(), {
310 "flesh_price_summary": true,
311 "flesh_lineitem_count": true
314 if(po && !this.isMeta) {
315 openils.Util.show(nodeByName('po', row), 'inline');
316 var link = nodeByName('po_link', row);
317 link.setAttribute('href', oilsBasePath + '/acq/po/view/' + li.purchase_order());
318 link.innerHTML += po.name();
322 // show which picklist this lineitem is a member of
323 if(li.picklist() && (this.isPO || this.isMeta || this.isUni)) {
325 this.plCache[li.picklist()] =
326 this.plCache[li.picklist()] ||
327 fieldmapper.standardRequest(
328 ['open-ils.acq', 'open-ils.acq.picklist.retrieve'],
329 {params: [this.authtoken, li.picklist()]});
331 if (pl.name() == "") {
332 openils.Util.show(nodeByName("bib_origin", row), "inline");
336 openils.Util.show(nodeByName('pl', row), 'inline');
337 var link = nodeByName('pl_link', row);
338 link.setAttribute('href', oilsBasePath + '/acq/picklist/view/' + li.picklist());
339 link.innerHTML += pl.name();
344 var countNode = nodeByName('count', row);
345 var count = li.item_count() || 0;
346 if (typeof(this._copy_count_cb) == "function") {
347 this._copy_count_cb(li.id(), count);
349 countNode.innerHTML = count;
350 countNode.id = 'acq-lit-copy-count-label-' + li.id();
353 var priceInput = dojo.query('[name=price]', row)[0];
354 priceInput.value = li.estimated_unit_price() || '';
355 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
357 // show either "mark received" or "unreceive" as appropriate
358 this.updateLiState(li, row);
360 if (!skip_final_placement) {
361 self.tbody.appendChild(row);
362 self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
368 this._liCountClaims = function(li) {
370 for (var i = 0; i < li.lineitem_details().length; i++)
371 total += li.lineitem_details()[i].claims().length;
375 this._findLiRow = function(li) {
376 return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
379 this.reconsiderClaimControl = function(li, row) {
380 var option = nodeByName("action_manage_claims", row);
381 var eligible = this.claimEligibleLidByLi[li.id()].length;
382 var count = this._liCountClaims(li);
383 if (!row) row = this._findLiRow(li);
385 option.disabled = !(count || eligible);
387 dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
388 option.onclick = function() { self.claimDialog.show(li); };
391 this.clearEligibility = function(li) {
392 this.claimEligibleLidByLi[li.id()] = [];
394 if (li.lineitem_details()) {
395 li.lineitem_details().forEach(
396 function(lid) { delete self.claimEligibleLid[lid.id()]; }
400 if (this.copyCache) {
402 for (var k in this.copyCache) {
403 if (this.copyCache[k].lineitem() == li.id())
407 function(k) { delete self.claimEligibleLid[k]; }
412 this.checkClaimEligibility = function(li, callback, row) {
413 this.clearEligibility(li);
414 fieldmapper.standardRequest(
415 ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
416 "params": [openils.User.authtoken, {"lineitem": li.id()}],
418 "onresponse": function(r) {
419 if (r = openils.Util.readResponse(r)) {
420 self.claimEligibleLidByLi[li.id()].push(
423 self.claimEligibleLid[r.lineitem_detail()] = true;
426 "oncomplete": function() {
427 self.reconsiderClaimControl(li, row);
428 if (typeof(callback) == "function")
435 this.updateLiNotesCount = function(li, row) {
436 if (!row) row = this._findLiRow(li);
438 var has_notes = (li.lineitem_notes().filter(
439 function(o) { return Boolean (o.alert_text()); }
442 /* U+2691 is the code point for a filled-in flag character */
443 nodeByName("notes_alert_flag", row).innerHTML =
444 has_notes ? "⚑" : "";
445 nodeByName("noteslink", row).style.fontStyle =
446 has_notes ? "italic" : "normal";
447 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
450 /* XXX NOT related to _updateLiState(). rethink */
451 this.updateLiState = function(li, row) {
452 if (!row) row = this._findLiRow(li);
454 var actReceive = nodeByName("action_mark_recv", row);
455 var actUnRecv = nodeByName("action_mark_unrecv", row);
456 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
457 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
459 var actNewInvoice = nodeByName('action_new_invoice', row);
460 var actLinkInvoice = nodeByName('action_link_invoice', row);
461 var actViewInvoice = nodeByName('action_view_invoice', row);
463 nodeByName('action_view_history', row).onclick =
464 function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
466 var state_cell = nodeByName("li_state", row);
468 if (li.state() == "cancelled") {
469 if (typeof li.cancel_reason() == "object") {
470 var holds_state = dojo.create(
472 "style": "border-bottom: 1px dashed #000;",
473 "innerHTML": li.state()
474 }, state_cell, "only"
478 "label": "<em>" + li.cancel_reason().label() +
479 "</em><br />" + li.cancel_reason().description(),
480 "connectId": [holds_state]
481 }, dojo.create("span", null, state_cell, "last")
484 state_cell.innerHTML = li.state(); // TODO i18n state labels
487 state_cell.innerHTML = li.state(); // TODO i18n state labels
491 /* handle row coloring for based on LI state */
492 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
493 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
495 /* handle links that appear/disappear based on whether LI is received */
499 actNewInvoice.onclick = function() {
500 location.href = oilsBasePath + '/acq/invoice/view?create=1&attach_li=' + li.id();
501 nodeByName("action_none", row).selected = true;
503 actLinkInvoice.onclick = function() {
504 self.invoiceLinkDialogManager.target = li;
505 acqLitLinkInvoiceDialog.show();
506 nodeByName("action_none", row).selected = true;
508 actViewInvoice.onclick = function() {
509 location.href = oilsBasePath +
510 "/acq/search/unified?so=" +
511 base64Encode({"jub":[{"id": li.id()}]}) +
513 nodeByName("action_none", row).selected = true;
516 actNewInvoice.disabled = false;
517 actLinkInvoice.disabled = false;
518 actViewInvoice.disabled = false;
522 actReceive.disabled = false;
523 actReceive.onclick = function() {
524 if (self.checkLiAlerts(li.id()))
525 self.issueReceive(li);
526 nodeByName("action_none", row).selected = true;
531 actUnRecv.disabled = false;
532 actUnRecv.onclick = function() {
533 if (confirm(localeStrings.UNRECEIVE_LI))
534 self.issueReceive(li, /* rollback */ true);
535 nodeByName("action_none", row).selected = true;
537 // TODO we should allow editing before receipt, in which case the
538 // test should be "if 1 or more real (acp) copies exist
539 actUpdateBarcodes.disabled = false;
540 actUpdateBarcodes.onclick = function() {
541 self.showRealCopyEditUI(li);
542 nodeByName("action_none", row).selected = true;
544 actHoldingsMaint.disabled = false;
545 actHoldingsMaint.onclick = self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
553 this._setAlertStore = function() {
554 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
556 "data": acqliat.toStoreData(
558 "acqliat", {"id": {"!=": null}}
563 acqLitAlertAlertText.setValue(); /* make the store "live" */
564 acqLitAlertAlertText._store_ready = true;
568 * Draws and shows the lineitem notes pane
570 this.drawLiNotes = function(li) {
573 if (!acqLitAlertAlertText._store_ready)
574 this._setAlertStore();
577 li.lineitem_notes().sort(
579 if(a.edit_time() < b.edit_time()) return 1;
585 while(this.liNotesTbody.childNodes[0])
586 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
589 acqLitCreateNoteSubmit.onClick = function() {
590 var value = acqLitCreateNoteText.attr('value');
592 var note = new fieldmapper.acqlin();
595 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
598 note.lineitem(li.id());
600 self.updateLiNotes(li, note);
601 acqLitCreateNoteVendorPublic.attr("checked", false);
602 acqLitCreateNoteText.attr("value", "");
605 acqLitCreateAlertSubmit.onClick = function() {
606 if (!acqLitAlertAlertText.item) {
607 alert(localeStrings.ALERT_UNSELECTED);
611 var alert_text = new fieldmapper.acqliat().fromStoreItem(
612 acqLitAlertAlertText.item
614 var value = acqLitAlertNoteValue.attr("value") || "";
616 var note = new fieldmapper.acqlin();
618 note.lineitem(li.id());
620 note.alert_text(alert_text);
622 self.updateLiNotes(li, note);
625 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
629 * Draws a single lineitem note in the notes pane
631 this.addLiNote = function(li, note) {
632 if(note.isdeleted()) return;
634 var row = self.liNotesRow.cloneNode(true);
635 nodeByName("value", row).innerHTML = note.value();
636 var alert_node = nodeByName("alert_code", row);
637 if (note.alert_text()) {
638 alert_node.innerHTML = note.alert_text().code();
639 if (note.alert_text().description()) {
642 "connectId": [alert_node],
643 "label": note.alert_text().description()
644 }, dojo.create("span", null, alert_node, "after")
649 if (openils.Util.isTrue(note.vendor_public()))
650 nodeByName("vendor_public", row).innerHTML =
651 localeStrings.VENDOR_PUBLIC;
653 nodeByName("delete", row).onclick = function() {
654 note.isdeleted(true);
655 self.liNotesTbody.removeChild(row);
656 self.updateLiNotes(li);
659 if(note.edit_time()) {
660 nodeByName("edit_time", row).innerHTML =
661 dojo.date.locale.format(
662 dojo.date.stamp.fromISOString(note.edit_time()),
663 {formatLength:'short'});
666 self.liNotesTbody.appendChild(row);
670 * Updates any new/changed/deleted notes on the server
672 this.updateLiNotes = function(li, newNote) {
678 notes = li.lineitem_notes().filter(
680 if(note.ischanged() || note.isnew() || note.isdeleted())
686 if(notes.length == 0) return;
687 progressDialog.show();
689 fieldmapper.standardRequest(
690 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
692 params : [this.authtoken, notes],
693 onresponse : function(r) {
694 var resp = openils.Util.readResponse(r);
699 // remove the old changed notes
701 dojo.forEach(li.lineitem_notes(),
703 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
707 li.lineitem_notes(list);
710 progressDialog.hide();
711 self.updateLiNotesCount(li);
712 self.drawLiNotes(li);
716 progressDialog.update(resp);
717 var newnote = resp.note;
719 if(!newnote.isdeleted()) {
720 newnote.isnew(false);
721 newnote.ischanged(false);
722 li.lineitem_notes().push(newnote);
729 this.updateLiPrice = function(input, li) {
731 var price = input.value;
732 if(Number(price) == Number(li.estimated_unit_price())) return;
734 fieldmapper.standardRequest(
735 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
736 { async : false, // redundant w/ timeout
738 params : [this.authtoken, li.id(), price],
739 oncomplete : function(r) {
740 openils.Util.readResponse(r);
741 li.estimated_unit_price(price); // update local copy
747 this.removeLineitem = function(liId) {
748 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
749 delete this.liCache[liId];
750 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
753 this.drawInfo = function(liId) {
754 if (!this._isRelatedViewer) {
755 var d = dojo.byId("acq-lit-info-related");
756 if (!this.relCache[liId]) {
757 fieldmapper.standardRequest(
760 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
763 "params": [openils.User.authtoken, liId],
764 "onresponse": function(r) {
765 self.relCache[liId] = openils.Util.readResponse(r);
766 nodeByName("related_number", d).innerHTML =
769 self.relCache[liId] >1 ? "show" : "hide"
775 nodeByName("related_number", d).innerHTML = this.relCache[liId];
776 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
781 openils.acq.Lineitem.fetchAttrDefs(
783 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
788 this._fetchLineitem = function(liId, handler, force) {
790 var li = this.liCache[liId];
791 if(li && li.marc() && li.lineitem_details() && !force)
794 fieldmapper.standardRequest(
795 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve'],
798 params: [self.authtoken, liId, {
800 flesh_cancel_reason: true,
801 flesh_li_details: true,
803 flesh_fund_debit: true }],
805 oncomplete: function(r) {
806 var li = openils.Util.readResponse(r);
807 self.liCache[liId] = li;
814 this._drawInfo = function(li) {
816 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
819 openils.Util.hide('acq-lit-marc-order-record-label');
820 openils.Util.hide(acqLitEditOrderMarc.domNode);
821 openils.Util.show('acq-lit-marc-real-record-label');
823 openils.Util.show('acq-lit-marc-order-record-label');
824 openils.Util.show(acqLitEditOrderMarc.domNode);
825 openils.Util.hide('acq-lit-marc-real-record-label');
828 this.drawMarcHTML(li);
829 this.infoTbody = dojo.byId('acq-lit-info-tbody');
832 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
833 while(this.infoTbody.childNodes[0])
834 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
836 for(var i = 0; i < li.attributes().length; i++) {
837 var attr = li.attributes()[i];
838 var row = this.infoRow.cloneNode(true);
840 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
841 var name = openils.acq.Lineitem.attrDefs[type].filter(
843 return (a.code() == attr.attr_name());
845 ).pop().description();
847 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
848 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
849 this.infoTbody.appendChild(row);
852 if (!this._isRelatedViewer) {
853 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
854 oilsBasePath + "/acq/lineitem/related/" + li.id();
859 this.generateMakeRecTab = function(bib_id,default_view, row) {
863 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
866 show_nav_buttons : true,
867 show_print_button : true,
868 opac_url : xulG.url_prefix(xulG.urls.opac_rdetail + '?r=' + bib_id),
869 default_view : default_view
873 if(row) nodeByName("action_none", row).selected = true;
877 this.drawMarcHTML = function(li) {
878 var params = [null, true, li.marc()];
880 params = [li.eg_bib_id(), true];
882 fieldmapper.standardRequest(
883 ['open-ils.search', 'open-ils.search.biblio.record.html'],
886 oncomplete: function(r) {
887 dojo.byId('acq-lit-marc-div').innerHTML =
888 openils.Util.readResponse(r);
894 this.drawCopies = function(liId, force_fetch) {
895 if (typeof force_fetch == "undefined")
901 this.copyWidgetCache = {};
902 this.oldCopyWidgetCache = {};
903 this.virtDfaCounts = {};
904 this.realDfaCache = {};
907 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
908 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
909 acqLitCopyCountInput.attr('value', '0');
911 while(this.copyTbody.childNodes[0])
912 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
914 this._drawBatchCopyWidgets();
916 this._drawDistribApplied(liId);
918 this._fetchDistribFormulas(
920 openils.acq.Lineitem.fetchAttrDefs(
922 self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch);
929 this._saveDistribAppliedTemplates = function() {
930 if (!this._appliedDistribTemplate) {
931 this._appliedDistribTemplate =
932 dojo.byId("acq-lit-distrib-applied-tbody").
933 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
934 dojo.attr(this._appliedDistribTemplate, "id");
938 this._drawDistribApplied = function(liId) {
939 /* Build this table while hidden to prevent rendering artifacts */
940 openils.Util.hide("acq-lit-distrib-applied-tbody");
942 this._saveDistribAppliedTemplates();
944 /* Remove any rows in the table from previous populations */
945 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
946 forEach(dojo.destroy);
948 /* Unregister all dijits previously created (for some reason this isn't
949 * covered by the above destroy calls). */
950 dijit.registry.forEach(
951 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
954 /* Populate the table with our liId */
956 fieldmapper.standardRequest(
958 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
961 "params": [self.authtoken, liId],
962 "onresponse": function(r) {
963 var dfa = openils.Util.readResponse(r);
966 self.realDfaCache[dfa.id()] = dfa;
967 self._drawDistribAppliedUnit(dfa);
970 "oncomplete": function() {
971 /* Reveal built table */
974 "acq-lit-distrib-applied-tbody", "table-row-group"
982 this._drawDistribAppliedUnit = function(dfa) {
984 var row = dojo.query(
985 'tr[formula="' + dfa.formula().id() + '"]',
986 "acq-lit-distrib-applied-tbody"
991 row = dojo.clone(this._appliedDistribTemplate);
992 dojo.attr(row, "formula", dfa.formula().id());
993 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
996 var td = dojo.query("td", row)[0];
998 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
999 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1002 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1004 new dijit.form.Button(
1006 "onClick": function() {
1007 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1008 self.deleteDfa(dfa);
1011 /* XXX I /cannot/ make the following work in as a CSS class
1012 * for some reason. So frustrating... */
1013 "style": function(id) {
1015 "font-weight: bold; color: #c00;" :
1017 }(dfa.id()) + "margin: 0 6px;display: inline;"
1018 }, "dfa-button-" + dfa.id()
1022 "connectId": ["dfa-button-" + dfa.id()],
1023 "label": dojo.string.substitute(
1024 localeStrings.DFA_TIP, dfa.id() > 0 ? [
1025 openils.User.formalName(dfa.creator()),
1026 dojo.date.locale.format(
1027 dojo.date.stamp.fromISOString(dfa.create_time()),
1028 {"formatLength":"short"}
1030 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
1032 }, "dfa-tip-" + dfa.id()
1036 this.deleteDfa = function(dfa) {
1037 if (dfa.id() > 0) { /* real */
1038 this.pcrud.eliminate(
1041 "oncomplete": function() {
1042 self._removeDistribApplied(dfa.id());
1043 delete self.realDfaCache[dfa.id()];
1047 } else { /* virtual */
1048 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
1049 this.virtDfaCounts[dfa.formula().id()] = 0;
1050 /* hasn't been saved yet, so no need to do anything server side */
1051 this._removeDistribApplied(dfa.id());
1056 this._removeDistribApplied = function(dfaId) {
1057 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
1058 dijit.registry.forEach(
1059 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
1061 this._removeDistribAppliedEmptyRows();
1064 this._removeAllDistribAppliedVirtual = function() {
1065 /* Unregister dijits */
1066 dijit.registry.forEach(
1067 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
1069 this._removeDistribAppliedEmptyRows();
1072 this._removeDistribAppliedEmptyRows = function() {
1073 /* Remove any rows with no DFA at all */
1074 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
1076 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
1082 * Insert a new row into the distribution formula selection form
1084 this._addDistribFormulaRow = function() {
1087 if (!self.distribForms) {
1088 // no formulas, hide the form
1089 openils.Util.hide('acq-lit-distrib-formula-tbody');
1093 if(!this.distribFormulaTemplate)
1094 this.distribFormulaTemplate =
1095 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
1097 var row = this.distribFormulaTemplate.cloneNode(true);
1098 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
1100 this.dfSelector = new dijit.form.FilteringSelect(
1101 {"labelAttr": "dynLabel", "labelType": "html"},
1102 nodeByName("selector", row)
1104 this._updateFormulaStore();
1105 this.dfSelector.fetchProperties =
1106 {"sort": [{"attribute": "use_count", "descending": true}]};
1108 var apply = new dijit.form.Button(
1109 {"label": localeStrings.APPLY},
1110 nodeByName('set_button', row)
1113 var reset = new dijit.form.Button(
1114 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
1115 nodeByName("reset_button", row)
1118 dojo.connect(apply, 'onClick',
1120 var form_id = self.dfSelector.attr("value");
1121 if(!form_id) return;
1122 self._applyDistribFormula(form_id);
1123 reset.attr("disabled", false);
1127 dojo.connect(reset, 'onClick',
1129 self.restoreCopyFieldsBeforeDF();
1130 self.virtDfaCounts = {};
1131 self.virtDfaId = -1;
1133 self._updateFormulaStore();
1134 self._removeAllDistribAppliedVirtual();
1135 reset.attr("disabled", "true");
1142 * Applies a distrib formula to the current set of copies
1144 this._applyDistribFormula = function(formula) {
1145 if(!formula) return;
1147 formula = this.distribForms.filter(
1148 function(form) { return form.id() == formula; }
1151 var copyRows = dojo.query('tr', self.copyTbody);
1153 if (this.dfeOffset >= copyRows.length) {
1154 alert(localeStrings.OUT_OF_COPIES);
1158 var entries_applied = 0;
1160 var rowIndex = this.dfeOffset;
1161 rowIndex < copyRows.length;
1165 var row = copyRows[rowIndex];
1166 var copy_id = row.getAttribute('copy_id');
1167 var copyWidgets = this.copyWidgetCache[copy_id];
1168 var entryIndex = this.dfeOffset;
1171 // find the correct entry for the current row
1172 dojo.forEach(formula.entries(),
1175 entryIndex += e.item_count();
1176 if(entryIndex > rowIndex)
1184 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
1185 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
1188 this.saveCopyFieldsBeforeDF(copy_id);
1189 this._copy_fields_for_acqdf.forEach(
1191 if(entry[field]()) {
1192 copyWidgets[field].attr('value', (entry[field]()));
1199 if (entries_applied) {
1200 this.virtDfaCounts[formula.id()] =
1201 ++(this.virtDfaCounts[formula.id()]) || 1;
1202 this._updateFormulaStore();
1203 this._drawDistribAppliedUnit(
1205 var dfa = new acqdfa();
1206 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
1209 this.dfeOffset += entries_applied;
1214 * This function updates the DF store for the dropdown so that use_counts
1215 * can reflect DF applications from this session before they're saved
1218 this._updateFormulaStore = function() {
1219 this.dfSelector.store = new dojo.data.ItemFileReadStore(
1221 "data": self._labelFormulasWithCounts(
1222 acqdf.toStoreData(self.distribForms)
1228 this.saveCopyFieldsBeforeDF = function(copy_id) {
1230 if (!this.oldCopyWidgetCache[copy_id]) {
1231 var copyWidgets = this.copyWidgetCache[copy_id];
1233 this.oldCopyWidgetCache[copy_id] = {};
1234 this._copy_fields_for_acqdf.forEach(
1236 self.oldCopyWidgetCache[copy_id][f] =
1237 copyWidgets[f].attr("value");
1243 this.restoreCopyFieldsBeforeDF = function() {
1245 for (var copy_id in this.oldCopyWidgetCache) {
1246 this._copy_fields_for_acqdf.forEach(
1248 self.copyWidgetCache[copy_id][f].attr(
1249 "value", self.oldCopyWidgetCache[copy_id][f]
1256 this._labelFormulasWithCounts = function(store_data) {
1257 for (var key in store_data.items) {
1258 var obj = store_data.items[key];
1259 obj.use_count = Number(obj.use_count); /* needed for sorting */
1261 if (this.virtDfaCounts[obj.id])
1262 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
1264 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
1265 obj.use_count + "]</span> " + obj.name;
1271 * This method formerly would not refetch the DF formulas if they'd been
1272 * loaded already, but now it always re-fetches, since use_count changes.
1274 this._fetchDistribFormulas = function(onload) {
1275 fieldmapper.standardRequest(
1277 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
1280 "params": [openils.User.authtoken],
1281 "oncomplete": function(r) {
1282 self.distribForms = openils.Util.readResponse(r);
1283 if(!self.distribForms || self.distribForms.length == 0) {
1284 self.distribForms = [];
1286 self._addDistribFormulaRow();
1293 this._drawBatchCopyWidgets = function() {
1294 var row = this.copyBatchRow;
1295 dojo.forEach(liDetailBatchFields,
1297 if(self.copyBatchRowDrawn) {
1298 self.copyBatchWidgets[field].attr('value', null);
1300 var widget = new openils.widget.AutoFieldWidget({
1303 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1304 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1305 searchFilter : (field == 'fund') ? {"active": "t"} : null,
1306 parentNode : dojo.query('[name='+field+']', row)[0],
1307 orgLimitPerms : ['CREATE_PICKLIST'],
1310 "labelType": (field == "fund") ? "html" : null
1312 noCache: (field == "fund"),
1317 if (field == "fund" && w.store)
1318 self._ensureCSSFundClasses(w.store);
1319 self.copyBatchWidgets[field] = w;
1322 if (field == "fund") {
1324 widget.widget, "onChange", function(val) {
1325 self._updateFundSelectorStyle(widget, val);
1332 this.copyBatchRowDrawn = true;
1335 this.batchCopyUpdate = function() {
1337 for(var k in this.copyWidgetCache) {
1338 var cache = this.copyWidgetCache[k];
1339 dojo.forEach(liDetailBatchFields, function(f) {
1340 var newval = self.copyBatchWidgets[f].attr('value');
1341 if(newval) cache[f].attr('value', newval);
1346 this._drawCopies = function(li) {
1349 // this button sets the total number of copies for a given lineitem
1350 acqLitAddCopyCount.onClick = function() {
1351 var count = acqLitCopyCountInput.attr('value');
1354 while(self.copyCount() < count)
1357 // delete rows if necessary
1358 var diff = self.copyCount() - count;
1360 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
1361 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
1362 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
1364 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1370 if(li.lineitem_details().length > 0) {
1371 dojo.forEach(li.lineitem_details(),
1373 self.addCopy(li, copy);
1381 this.copyCount = function() {
1383 for(var id in this.copyCache) {
1384 if(!this.copyCache[id].isdeleted())
1390 this.virtCopyId = -1;
1391 this.addCopy = function(li, copy) {
1392 var row = this.copyRow.cloneNode(true);
1393 this.copyTbody.appendChild(row);
1397 copy = new fieldmapper.acqlid();
1399 copy.id(this.virtCopyId--);
1400 copy.lineitem(li.id());
1403 this.copyCache[copy.id()] = copy;
1404 row.setAttribute('copy_id', copy.id());
1405 self.copyWidgetCache[copy.id()] = {};
1407 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1409 dojo.forEach(liDetailFields,
1412 if (field == "fund") {
1413 searchFilter = (copy.fund() ?
1414 {"-or": {"active": "t", "id": copy.fund()}} :
1417 searchFilter = null;
1420 var readOnly = false;
1422 // TODO: Add support for changing the owning_lib after real copies have been made.
1423 // owning_lib is order data as much as its item data
1424 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
1428 // TODO: add support for changing the fund after debits have been created
1429 // Note: invoicing allows the change
1430 if(copy.fund_debit() && field == 'fund') {
1434 var widget = new openils.widget.AutoFieldWidget({
1437 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1438 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1439 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1440 searchFilter : searchFilter,
1441 noCache: (field == "fund"),
1443 parentNode : dojo.query('[name='+field+']', row)[0],
1444 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
1445 readOnly : readOnly,
1449 // make sure we capture the value from any async widgets
1452 if (field == "fund" && w.store)
1453 self._ensureCSSFundClasses(w.store);
1456 copy[field](ww.getFormattedValue())
1458 self.copyWidgetCache[copy.id()][field] = w;
1460 dojo.connect(w, 'onChange',
1462 if (field == "fund")
1463 self._updateFundSelectorStyle(widget, val);
1465 if (!readOnly && (copy.isnew() || val != copy[field]())) {
1466 // prevent setting ischanged() automatically on widget load for existing copies
1467 copy[field](widget.getFormattedValue())
1468 copy.ischanged(true);
1477 this.updateLidState(copy, row);
1480 this._ensureCSSFundClass = function(id) {
1481 if (!this.fundStyleSheet) {
1483 "style", {"type": "text/css"},
1484 document.getElementsByTagName("head")[0], "last"
1486 this.fundStyleSheet = document.styleSheets[
1487 document.styleSheets.length - 1
1491 var cn = "fund_" + id;
1492 if (!this.haveFundClass[cn]) {
1493 fieldmapper.standardRequest(
1494 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
1496 "params": [openils.User.authtoken, id],
1498 "oncomplete": function(r) {
1499 r = openils.Util.readResponse(r);
1500 self.fundBalanceState[id] = r;
1502 if (r[0] /* stop */)
1503 style = fundStyles.stop;
1504 else if (r[1] /* warning */)
1505 style = fundStyles.warning;
1506 self.fundStyleSheet.insertRule(
1507 "." + cn + " { " + style + " }",
1508 self.fundStyleSheet.cssRules.length
1510 self.haveFundClass[cn] = true;
1517 this._ensureCSSFundClasses = function(store) {
1519 "query": {"id": "*"},
1520 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
1524 this._updateFundSelectorStyle = function(widget, fund_id) {
1525 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
1526 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
1529 this.updateLidState = function(copy, row) {
1530 if (typeof(row) == "undefined") {
1532 'tr[copy_id="' + copy.id() + '"]', this.copyTbody
1537 var recv_link = nodeByName("receive", row);
1538 var unrecv_link = nodeByName("unreceive", row);
1539 var del_link = nodeByName("delete", row);
1540 var cxl_link = nodeByName("cancel", row);
1541 var claim_link = nodeByName("claim", row);
1542 var cxl_reason_link = nodeByName("cancel_reason", row);
1544 if (copy.cancel_reason()) {
1545 openils.Util.hide(del_link.parentNode);
1546 openils.Util.hide(recv_link);
1547 openils.Util.hide(unrecv_link);
1548 openils.Util.hide(cxl_link);
1549 openils.Util.hide(claim_link);
1551 /* XXX the following may leak memory in a long lived table: dijits may not get destroyed... not positive. revisit. */
1552 var holds_reason = dojo.create(
1554 "style": "border-bottom: 1px dashed #000;",
1555 "innerHTML": "Cancelled" /* XXX [sic] and i18n */
1556 }, cxl_reason_link, "only"
1560 "label": "<em>" + copy.cancel_reason().label() +
1561 "</em><br />" + copy.cancel_reason().description(),
1562 "connectId": [holds_reason]
1563 }, dojo.create("span", null, cxl_reason_link, "last")
1565 openils.Util.show(cxl_reason_link, "inline");
1566 } else if (this.isPO) {
1567 /* Only using this in one place so far, but may want it for better
1568 * decisions on when to display certain controls. */
1569 var li_state = this.liCache[copy.lineitem()].state();
1571 openils.Util.hide(del_link.parentNode);
1572 openils.Util.hide(cxl_reason_link);
1574 /* Avoid showing (un)receive links, cancel links, for virt copies */
1575 if (copy.id() > 0) {
1576 if (copy.recv_time()) {
1577 openils.Util.hide(cxl_link);
1578 openils.Util.hide(recv_link);
1579 openils.Util.hide(claim_link);
1581 openils.Util.show(unrecv_link, "inline");
1582 unrecv_link.onclick = function() {
1583 if (confirm(localeStrings.UNRECEIVE_LID))
1584 self.issueReceive(copy, /* rollback */ true);
1587 openils.Util.hide(unrecv_link);
1589 if (this.claimEligibleLid[copy.id()]) {
1590 openils.Util.show(claim_link, "inline");
1591 claim_link.onclick = function() {
1592 self.claimDialog.show(
1593 self.liCache[copy.lineitem()], copy.id()
1597 openils.Util.hide(claim_link);
1600 openils.Util[li_state == "on-order" ? "show" : "hide"](
1603 openils.Util.show(cxl_link, "inline");
1604 recv_link.onclick = function() {
1605 if (self.checkLiAlerts(copy.lineitem()))
1606 self.issueReceive(copy);
1608 cxl_link.onclick = function() {
1609 self.cancelLid(copy.id());
1613 openils.Util.hide(cxl_link);
1614 openils.Util.hide(unrecv_link);
1615 openils.Util.hide(recv_link);
1616 openils.Util.hide(claim_link);
1619 openils.Util.hide(unrecv_link);
1620 openils.Util.hide(recv_link);
1621 openils.Util.hide(cxl_reason_link);
1622 openils.Util.hide(claim_link);
1624 del_link.onclick = function() { self.deleteCopy(row) };
1625 openils.Util.show(del_link.parentNode);
1629 this.cancelLid = function(lid_id) {
1630 lidCancelDialog._lid_id = lid_id;
1631 openils.Util.show(lidCancelDialog.domNode.parentNode);
1632 lidCancelDialog.show();
1633 if (!lidCancelDialog._prepared) {
1634 var widget = new openils.widget.AutoFieldWidget({
1635 "fmField": "cancel_reason",
1636 "fmClass": "acqlid",
1637 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
1638 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1643 acqLidCancelButton.onClick = function() {
1644 if (w.attr("value")) {
1645 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
1647 lidCancelDialog._lid_id,
1651 lidCancelDialog.hide();
1654 lidCancelDialog._prepared = true;
1660 this._cancelLid = function(lid_id, reason) {
1661 fieldmapper.standardRequest(
1662 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
1663 "params": [openils.User.authtoken, lid_id, reason],
1665 "onresponse": function(r) {
1666 if (r = openils.Util.readResponse(r)) {
1668 for (var id in r.lid) {
1669 /* actually this should only iterate once */
1670 self.copyCache[id].cancel_reason(
1671 r.lid[id].cancel_reason
1673 self.updateLidState(self.copyCache[id]);
1682 this._confirmAlert = function(li, lin) {
1684 dojo.string.substitute(
1685 localeStrings.CONFIRM_LI_ALERT, [
1686 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1687 "title", "lineitem_marc_attr_definition"
1689 lin.alert_text().code(),
1690 lin.alert_text().description() || "",
1697 this.checkLiAlerts = function(li_id) {
1698 var li = this.liCache[li_id];
1700 var alert_notes = li.lineitem_notes().filter(
1701 function(o) { return Boolean(o.alert_text()); }
1704 /* this is _intentionally_ not done in a call to forEach() ... */
1705 for (var i = 0; i < alert_notes.length; i++) {
1706 if (this.noteAcks[alert_notes[i].id()])
1708 else if (!this._confirmAlert(li, alert_notes[i]))
1711 this.noteAcks[alert_notes[i].id()] = true;
1717 this.deleteCopy = function(row) {
1718 var copy = this.copyCache[row.getAttribute('copy_id')];
1719 copy.isdeleted(true);
1721 delete this.copyCache[copy.id()];
1722 this.copyTbody.removeChild(row);
1725 this._virtDfaCountsAsList = function() {
1727 for (var key in this.virtDfaCounts) {
1728 for (var i = 0; i < this.virtDfaCounts[key]; i++)
1734 this.confirmBreachedCopyFunds = function(copies) {
1735 var stop = 0, warning = 0;
1739 var state = self.fundBalanceState[o.fund()];
1740 if (state[0] /* stop */)
1742 else if (state[1] /* warning */)
1749 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
1750 } else if (warning) {
1751 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
1756 this.saveCopyChanges = function(liId) {
1762 for(var id in this.copyCache) {
1763 var c = this.copyCache[id];
1764 if(!c.isdeleted()) total++;
1765 if(c.isnew() || c.ischanged() || c.isdeleted()) {
1766 if(c.id() < 0) c.id(null);
1772 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
1775 if (copies.length > 0) {
1776 if (!this.confirmBreachedCopyFunds(copies))
1779 if (typeof(this._copy_count_cb) == "function")
1780 this._copy_count_cb(liId, total);
1782 openils.Util.show("acq-lit-update-copies-progress");
1783 fieldmapper.standardRequest(
1784 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1786 params: [openils.User.authtoken, copies],
1787 onresponse: function(r) {
1788 var res = openils.Util.readResponse(r);
1789 litUpdateCopiesProgress.update(res);
1791 oncomplete: function() {
1792 self.drawCopies(liId, true /* force_fetch */);
1793 openils.Util.hide("acq-lit-update-copies-progress");
1799 var dfa_list = this._virtDfaCountsAsList();
1800 if (dfa_list.length > 0) {
1801 fieldmapper.standardRequest(
1803 "open-ils.acq.distribution_formula.record_application"],
1806 "params": [openils.User.authtoken, dfa_list, liId],
1807 "onresponse": function(r) {
1808 var res = openils.Util.readResponse(r);
1809 if (res && res.length < dfa_list.length)
1810 alert(localeStrings.DFA_NOT_ALL);
1814 this.virtDfaCounts = {};
1818 this._updateCreatePoPrepayCheckbox = function(prepay) {
1819 var prepay = openils.Util.isTrue(prepay);
1820 this._prepayRequiredByVendor = prepay;
1821 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
1824 this._confirmPoPrepaySituation = function() {
1825 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
1826 if (want_prepay != this._prepayRequiredByVendor) {
1829 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
1830 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
1837 this.applySelectedLiAction = function(action) {
1841 case 'delete_selected':
1842 this._deleteLiList(self.getSelected());
1845 case 'create_order':
1846 this._loadPOSelect();
1847 acqLitPoCreateDialog.show();
1850 case 'save_picklist':
1851 this._loadPLSelect();
1852 acqLitSavePlDialog.show();
1855 case 'selector_ready':
1857 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
1858 acqLitChangeLiStateDialog.show();
1866 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
1873 case 'rollback_receive_po':
1874 this.rollbackPoReceive();
1877 case 'create_assets':
1878 this.createAssets();
1881 case 'export_attr_list':
1882 this.chooseExportAttr();
1885 case 'batch_apply_funds':
1886 this.applyBatchLiFunds();
1889 case 'add_brief_record':
1891 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
1893 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
1897 case "cancel_lineitems":
1898 this.maybeCancelLineitems();
1901 case "change_claim_policy":
1902 var li_list = this.getSelected();
1903 this.claimPolicyPicker.attr("value", null);
1904 liClaimPolicyDialog.show();
1905 liClaimPolicySave.onClick = function() {
1906 self.changeClaimPolicy(
1908 self.claimPolicyPicker.attr("value"),
1911 function(li) { self.setClaimPolicyControl(li); }
1913 liClaimPolicyDialog.hide();
1921 this.changeClaimPolicy = function(li_list, value, callback) {
1923 function(li) { li.claim_policy(value); }
1925 fieldmapper.standardRequest(
1926 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
1927 "params": [openils.User.authtoken, li_list],
1929 "oncomplete": function(r) {
1930 r = openils.Util.readResponse(r);
1931 if (callback) callback(r);
1937 this.createAssets = function() {
1938 if(!this.isPO) return;
1939 if(!confirm(localeStrings.CREATE_PO_ASSETS_CONFIRM)) return;
1940 this.show('acq-lit-progress-numbers');
1942 fieldmapper.standardRequest(
1943 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
1945 params: [this.authtoken, this.isPO],
1946 onresponse: function(r) {
1947 var resp = openils.Util.readResponse(r);
1948 self._updateProgressNumbers(resp, true);
1954 this.maybeCancelLineitems = function() {
1955 openils.Util.show("acq-lit-cancel-reason", "inline");
1956 if (!acqLitCancelLineitemsButton._prepared) {
1957 var widget = new openils.widget.AutoFieldWidget({
1958 "fmField": "cancel_reason",
1960 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
1961 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1966 acqLitCancelLineitemsButton.onClick = function() {
1967 if (w.attr("value")) {
1968 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
1969 self._cancelLineitems(w.attr("value"));
1971 openils.Util.hide("acq-lit-cancel-reason");
1974 acqLitCancelLineitemsButton._prepared = true;
1980 this._cancelLineitems = function(reason) {
1981 var id_list = this.getSelected().map(function(o) { return o.id(); });
1982 fieldmapper.standardRequest(
1983 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
1984 "params": [openils.User.authtoken, id_list, reason],
1986 "onresponse": function(r) {
1987 if (r = openils.Util.readResponse(r)) {
1989 for (var id in r.li) {
1990 self.liCache[id].state(r.li[id].state);
1991 self.liCache[id].cancel_reason(
1992 r.li[id].cancel_reason
1994 self.updateLiState(self.liCache[id]);
1997 if (r.lid && self.copyCache) {
1998 for (var id in r.lid) {
1999 if (self.copyCache[id]) {
2000 self.copyCache[id].cancel_reason(
2001 r.lid[id].cancel_reason
2003 self.updateLidState(self.copyCache[id]);
2013 this.chooseExportAttr = function() {
2014 if (!acqLitExportAttrSelector._li_setup) {
2016 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
2018 "data": acqliad.toStoreData(
2020 "acqliad", {"code": li_exportable_attrs}
2025 acqLitExportAttrSelector.setValue();
2026 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
2027 acqLitExportAttrSelector._li_setup = true;
2029 openils.Util.show("acq-lit-export-attr-holder", "inline");
2032 this.exportAttrList = function() {
2033 var attr_def = acqLitExportAttrSelector.item;
2034 var li_list = this.getSelected();
2035 var value_list = li_list.map(
2037 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2038 attr_def.code, "lineitem_marc_attr_definition"
2041 ).filter(function(attr) { return Boolean(attr); });
2043 if (value_list.length > 0) {
2044 if (value_list.length < li_list.length) {
2046 dojo.string.substitute(
2047 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
2054 openils.XUL.contentToFileSaveDialog(
2055 value_list.join("\n"),
2056 localeStrings.EXPORT_SAVE_DIALOG_TITLE
2062 alert(dojo.string.substitute(
2063 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
2067 openils.Util.hide("acq-lit-export-attr-holder");
2070 this.printPO = function() {
2071 if(!this.isPO) return;
2072 progressDialog.show(true);
2073 fieldmapper.standardRequest(
2074 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
2076 params: [this.authtoken, this.isPO, 'html'],
2077 oncomplete: function(r) {
2078 progressDialog.hide();
2079 var evt = openils.Util.readResponse(r);
2080 if(evt && evt.template_output()) {
2081 openils.Util.printHtmlString(evt.template_output().data());
2089 this.receivePO = function() {
2090 if (!this.isPO) return;
2092 for (var id in this.liCache) {
2093 /* assumption: liCache reflects exactly the
2094 * set of LIs that belong to our PO */
2095 if (this.liCache[id].state() != "received" &&
2096 !this.checkLiAlerts(id)) return;
2099 this.show('acq-lit-progress-numbers');
2101 fieldmapper.standardRequest(
2102 ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
2104 params: [this.authtoken, this.isPO],
2105 onresponse : function(r) {
2106 var resp = openils.Util.readResponse(r);
2107 self._updateProgressNumbers(resp, true);
2113 this.issueReceive = function(obj, rollback) {
2114 /* (For now) there shall be no marking LI or LIDs (un)received
2115 * except from the actual "view PO" interface. */
2116 if (!this.isPO) return;
2119 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
2121 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
2123 progressDialog.show(true);
2124 fieldmapper.standardRequest(
2125 ["open-ils.acq", method], {
2127 "params": [this.authtoken, obj.id()],
2128 "onresponse": function(r) {
2129 if (r = openils.Util.readResponse(r)) {
2130 self.fetchClaimInfo(
2131 part == "lineitem" ? obj.id() : obj.lineitem(),
2133 function() { self.handleReceive(r); }
2135 progressDialog.hide();
2143 * Handles the responses from receive and rollback ML calls.
2145 this.handleReceive = function(resp) {
2148 for (var li_id in resp.li) {
2149 for (var key in resp.li[li_id])
2150 self.liCache[li_id][key](resp.li[li_id][key]);
2151 self.updateLiState(self.liCache[li_id]);
2155 if (typeof(self.poUpdateCallback) == "function")
2156 self.poUpdateCallback(resp.po);
2159 for (var lid_id in resp.lid) {
2160 for (var key in resp.lid[lid_id])
2161 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
2162 self.updateLidState(self.copyCache[lid_id]);
2168 this.rollbackPoReceive = function() {
2169 if(!this.isPO) return;
2170 if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
2171 this.show('acq-lit-progress-numbers');
2173 fieldmapper.standardRequest(
2174 ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
2176 params: [this.authtoken, this.isPO],
2177 onresponse : function(r) {
2178 var resp = openils.Util.readResponse(r);
2179 self._updateProgressNumbers(resp, true);
2185 this._updateProgressNumbers = function(resp, reloadOnComplete) {
2187 dojo.byId('acq-pl-lit-li-processed').innerHTML = resp.li;
2188 dojo.byId('acq-pl-lit-lid-processed').innerHTML = resp.lid;
2189 dojo.byId('acq-pl-lit-debits-processed').innerHTML = resp.debits_accrued;
2190 dojo.byId('acq-pl-lit-bibs-processed').innerHTML = resp.bibs;
2191 dojo.byId('acq-pl-lit-indexed-processed').innerHTML = resp.indexed;
2192 dojo.byId('acq-pl-lit-copies-processed').innerHTML = resp.copies;
2193 if(resp.complete && reloadOnComplete)
2194 location.href = location.href;
2198 this._createPO = function(fields) {
2199 this.show('acq-lit-progress-numbers');
2200 var po = new fieldmapper.acqpo();
2201 po.provider(this.createPoProviderSelector.attr('value'));
2202 po.ordering_agency(this.createPoAgencySelector.attr('value'));
2203 po.prepayment_required(fields.prepayment_required[0] ? true : false);
2205 var selected = this.getSelected( (fields.create_from == 'all') );
2206 if(selected.length == 0) return;
2208 var max = selected.length * 3;
2211 fieldmapper.standardRequest(
2212 ['open-ils.acq', 'open-ils.acq.purchase_order.create'],
2215 openils.User.authtoken,
2218 lineitems : selected.map(function(li) { return li.id() }),
2219 create_assets : fields.create_assets[0],
2223 onresponse : function(r) {
2224 var resp = openils.Util.readResponse(r);
2225 self._updateProgressNumbers(resp);
2227 location.href = oilsBasePath + '/acq/po/view/' + resp.purchase_order.id();
2233 this.batchFundWidget = null;
2235 this.applyBatchLiFunds = function() {
2237 var liIds = this.getSelected().map(function(li) { return li.id(); });
2238 if(liIds.length == 0) return; // warn?
2241 batchFundUpdateDialog.show();
2243 if(!this.batchFundWidget) {
2244 this.batchFundWidget = new openils.widget.AutoFieldWidget({
2246 selfReference : true,
2247 labelFormat : fundLabelFormat,
2248 searchFormat : fundSearchFormat,
2249 searchFilter : {"active": "t"},
2250 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
2251 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2252 dijitArgs : { "required": true, "labelType": "html" },
2255 this.batchFundWidget.build();
2258 dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
2259 dojo.connect(batchFundUpdateSubmit, 'onClick',
2262 // TODO: call .dry_run first to test thresholds
2263 fieldmapper.standardRequest(
2264 ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
2267 openils.User.authtoken,
2269 self.batchFundWidget.widget.attr('value')
2271 oncomplete : function(r) {
2272 var resp = openils.Util.readResponse(r);
2274 location.href = location.href;
2283 this._deleteLiList = function(list, idx) {
2284 if(idx == null) idx = 0;
2285 if(idx >= list.length) return;
2286 var liId = list[idx].id();
2287 fieldmapper.standardRequest(
2288 ['open-ils.acq', 'open-ils.acq.lineitem.delete'],
2290 params: [openils.User.authtoken, liId],
2291 oncomplete: function(r) {
2292 self.removeLineitem(liId);
2293 self._deleteLiList(list, ++idx);
2299 this.editOrderMarc = function(li) {
2301 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
2302 to true in about:config */
2304 if(!openils.XUL.enableXPConnect()) return;
2306 if(openils.XUL.isXUL()) {
2307 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
2309 win = window.open('/xul/server/cat/marcedit.xul');
2313 record : {marc : li.marc(), "rtype": "bre"},
2315 label: 'Save Record', // XXX I18N
2316 func: function(xmlString) {
2318 fieldmapper.standardRequest(
2319 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
2321 params: [openils.User.authtoken, li],
2322 oncomplete: function(r) {
2323 openils.Util.readResponse(r);
2325 self.drawInfo(li.id())
2334 this._savePl = function(values) {
2336 var selected = this.getSelected( (values.which == 'all') );
2337 openils.Util.show('acq-lit-generic-progress');
2339 if(values.new_name) {
2340 openils.acq.Picklist.create(
2341 {name: values.new_name},
2343 self._updateLiList(id, selected, 0,
2345 location.href = oilsBasePath + '/acq/picklist/view/' + id;
2349 } else if(values.existing_pl) {
2350 // update lineitems to use an existing picklist
2351 self._updateLiList(values.existing_pl, selected, 0,
2353 location.href = oilsBasePath + '/acq/picklist/view/' + values.existing_pl;
2358 this._updateLiState = function(values, state) {
2360 var selected = this.getSelected( (values.which == 'all') );
2361 if(!selected.length) return;
2362 dojo.forEach(selected, function(li) {li.state(state);});
2363 self._updateLiList(null, selected, 0,
2364 // TODO consider inline updates for efficiency
2365 function() { location.href = location.href }
2369 this._updateLiList = function(pl, list, idx, oncomplete) {
2370 if(idx >= list.length) return oncomplete();
2372 if(pl != null) li.picklist(pl);
2373 litGenericProgress.update({maximum: list.length, progress: idx});
2374 new openils.acq.Lineitem({lineitem:li}).update(
2376 self._updateLiList(pl, list, ++idx, oncomplete);
2381 this._loadPOSelect = function() {
2382 if (!this.createPoProviderSelector) {
2383 var widget = new openils.widget.AutoFieldWidget({
2384 "fmField": "provider",
2386 "searchFilter": {"active": "t"},
2387 "parentNode": dojo.byId("acq-lit-po-provider"),
2389 "onChange": function() {
2391 self._updateCreatePoPrepayCheckbox(
2392 this.item.prepayment_required
2398 widget.build(function(w) { self.createPoProviderSelector = w; });
2401 if (!this.createPoAgencySelector) {
2402 var widget = new openils.widget.AutoFieldWidget({
2403 "fmField": "ordering_agency",
2405 "parentNode": dojo.byId("acq-lit-po-agency"),
2406 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2408 widget.build(function(w) { self.createPoAgencySelector = w; });
2412 this._loadPLSelect = function(preSel) {
2413 if(this._plSelectLoaded) return;
2415 function handleResponse(r) {
2416 plList.push(r.recv().content());
2418 var method = 'open-ils.acq.picklist.user.retrieve';
2419 fieldmapper.standardRequest(
2420 ['open-ils.acq', method],
2422 params: [this.authtoken],
2423 onresponse: handleResponse,
2424 oncomplete: function() {
2425 self._plSelectLoaded = true;
2426 acqLitAddExistingSelect.store =
2427 new dojo.data.ItemFileReadStore({data:acqpl.toStoreData(plList)});
2429 acqLitAddExistingSelect.setValue(preSel);
2435 this.showRealCopyEditUI = function(li) {
2440 this._fetchLineitem(li.id(),
2442 li = self.liCache[li.id()] = fullLi;
2446 id : li.lineitem_details().map(
2447 function(item) { return item.eg_copy_id() }
2451 oncomplete : function(r) {
2453 var r_list = openils.Util.readResponse( r );
2454 for (var i = 0; i < r_list.length; i++) {
2455 var copy = r_list[i];
2456 var volId = copy.call_number();
2457 var volume = self.volCache[volId];
2459 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2461 copy.call_number(volume);
2462 copyList.push(copy);
2465 // If we need to, we can pass in an update_copy function to handle the update instead of volume_item_creator
2466 xulG.volume_item_creator( { 'existing_copies' : copyList } );
2469 alert('error in oncomplete: ' + E);
2478 this.drawBibFinder = function(li) {
2481 var liWrapper = new openils.acq.Lineitem({lineitem:li});
2484 ['isbn', 'upc', 'issn', 'title', 'author'],
2486 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
2488 if(field == 'title' || field == 'author') {
2489 query += field +':' + val + ' ';
2491 query += 'identifier|' + field + ':' + val + ' ';
2498 oilsBasePath + '/acq/lineitem/findbib?query=' + escape(query),
2499 '', 'resizable,scrollbars=1');
2501 win.window.recordFound = function(bibId) {
2504 var attrs = li.attributes();
2505 li.attributes(null);
2506 li.eg_bib_id(bibId);
2508 fieldmapper.standardRequest(
2509 ["open-ils.acq", "open-ils.acq.lineitem.update"],
2511 "params": [openils.User.authtoken, li],
2513 "oncomplete": function(r) {
2514 if(openils.Util.readResponse(r)) {
2515 location.href = location.href;