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
278 openils.Util.show(nodeByName('catalog', row), 'inline');
279 nodeByName("catalog_link", row).onclick = this.generateMakeRecTab(li.eg_bib_id());
281 // TODO: Add discovery mechanism for bib linking
282 openils.Util.show(nodeByName('link_to_catalog', row), 'inline');
283 nodeByName("link_to_catalog_link", row).onclick = function() { self.drawBibFinder(li) };
286 nodeByName("worksheet_link", row).href =
287 oilsBasePath + "/acq/lineitem/worksheet/" + li.id();
289 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
290 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
291 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
293 if (!this.skipInitialEligibilityCheck)
294 this.fetchClaimInfo(li.id(), false, null, row);
296 this.updateLiNotesCount(li, row);
298 this.setClaimPolicyControl(li, row);
300 // show which PO this lineitem is a member of
301 if(li.purchase_order() && !this.isPO) {
303 this.poCache[li.purchase_order()] =
304 this.poCache[li.purchase_order()] ||
305 fieldmapper.standardRequest(
306 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
308 this.authtoken, li.purchase_order(), {
309 "flesh_price_summary": true,
310 "flesh_lineitem_count": true
313 if(po && !this.isMeta) {
314 openils.Util.show(nodeByName('po', row), 'inline');
315 var link = nodeByName('po_link', row);
316 link.setAttribute('href', oilsBasePath + '/acq/po/view/' + li.purchase_order());
317 link.innerHTML += po.name();
321 // show which picklist this lineitem is a member of
322 if(li.picklist() && (this.isPO || this.isMeta || this.isUni)) {
324 this.plCache[li.picklist()] =
325 this.plCache[li.picklist()] ||
326 fieldmapper.standardRequest(
327 ['open-ils.acq', 'open-ils.acq.picklist.retrieve'],
328 {params: [this.authtoken, li.picklist()]});
330 if (pl.name() == "") {
331 openils.Util.show(nodeByName("bib_origin", row), "inline");
335 openils.Util.show(nodeByName('pl', row), 'inline');
336 var link = nodeByName('pl_link', row);
337 link.setAttribute('href', oilsBasePath + '/acq/picklist/view/' + li.picklist());
338 link.innerHTML += pl.name();
343 var countNode = nodeByName('count', row);
344 var count = li.item_count() || 0;
345 if (typeof(this._copy_count_cb) == "function") {
346 this._copy_count_cb(li.id(), count);
348 countNode.innerHTML = count;
349 countNode.id = 'acq-lit-copy-count-label-' + li.id();
352 var priceInput = dojo.query('[name=price]', row)[0];
353 priceInput.value = li.estimated_unit_price() || '';
354 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
356 // show either "mark received" or "unreceive" as appropriate
357 this.updateLiState(li, row);
359 if (!skip_final_placement) {
360 self.tbody.appendChild(row);
361 self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
367 this._liCountClaims = function(li) {
369 for (var i = 0; i < li.lineitem_details().length; i++)
370 total += li.lineitem_details()[i].claims().length;
374 this._findLiRow = function(li) {
375 return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
378 this.reconsiderClaimControl = function(li, row) {
379 var option = nodeByName("action_manage_claims", row);
380 var eligible = this.claimEligibleLidByLi[li.id()].length;
381 var count = this._liCountClaims(li);
382 if (!row) row = this._findLiRow(li);
384 option.disabled = !(count || eligible);
386 dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
387 option.onclick = function() { self.claimDialog.show(li); };
390 this.clearEligibility = function(li) {
391 this.claimEligibleLidByLi[li.id()] = [];
393 if (li.lineitem_details()) {
394 li.lineitem_details().forEach(
395 function(lid) { delete self.claimEligibleLid[lid.id()]; }
399 if (this.copyCache) {
401 for (var k in this.copyCache) {
402 if (this.copyCache[k].lineitem() == li.id())
406 function(k) { delete self.claimEligibleLid[k]; }
411 this.checkClaimEligibility = function(li, callback, row) {
412 this.clearEligibility(li);
413 fieldmapper.standardRequest(
414 ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
415 "params": [openils.User.authtoken, {"lineitem": li.id()}],
417 "onresponse": function(r) {
418 if (r = openils.Util.readResponse(r)) {
419 self.claimEligibleLidByLi[li.id()].push(
422 self.claimEligibleLid[r.lineitem_detail()] = true;
425 "oncomplete": function() {
426 self.reconsiderClaimControl(li, row);
427 if (typeof(callback) == "function")
434 this.updateLiNotesCount = function(li, row) {
435 if (!row) row = this._findLiRow(li);
437 var has_notes = (li.lineitem_notes().filter(
438 function(o) { return Boolean (o.alert_text()); }
441 /* U+2691 is the code point for a filled-in flag character */
442 nodeByName("notes_alert_flag", row).innerHTML =
443 has_notes ? "⚑" : "";
444 nodeByName("noteslink", row).style.fontStyle =
445 has_notes ? "italic" : "normal";
446 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
449 /* XXX NOT related to _updateLiState(). rethink */
450 this.updateLiState = function(li, row) {
451 if (!row) row = this._findLiRow(li);
453 var actReceive = nodeByName("action_mark_recv", row);
454 var actUnRecv = nodeByName("action_mark_unrecv", row);
455 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
456 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
458 var actNewInvoice = nodeByName('action_new_invoice', row);
459 var actLinkInvoice = nodeByName('action_link_invoice', row);
460 var actViewInvoice = nodeByName('action_view_invoice', row);
462 nodeByName('action_view_history', row).onclick =
463 function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
465 var state_cell = nodeByName("li_state", row);
467 if (li.state() == "cancelled") {
468 if (typeof li.cancel_reason() == "object") {
469 var holds_state = dojo.create(
471 "style": "border-bottom: 1px dashed #000;",
472 "innerHTML": li.state()
473 }, state_cell, "only"
477 "label": "<em>" + li.cancel_reason().label() +
478 "</em><br />" + li.cancel_reason().description(),
479 "connectId": [holds_state]
480 }, dojo.create("span", null, state_cell, "last")
483 state_cell.innerHTML = li.state(); // TODO i18n state labels
486 state_cell.innerHTML = li.state(); // TODO i18n state labels
490 /* handle row coloring for based on LI state */
491 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
492 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
494 /* handle links that appear/disappear based on whether LI is received */
498 actNewInvoice.onclick = function() {
499 location.href = oilsBasePath + '/acq/invoice/view?create=1&attach_li=' + li.id();
500 nodeByName("action_none", row).selected = true;
502 actLinkInvoice.onclick = function() {
503 self.invoiceLinkDialogManager.target = li;
504 acqLitLinkInvoiceDialog.show();
505 nodeByName("action_none", row).selected = true;
507 actViewInvoice.onclick = function() {
508 location.href = oilsBasePath +
509 "/acq/search/unified?so=" +
510 base64Encode({"jub":[{"id": li.id()}]}) +
512 nodeByName("action_none", row).selected = true;
515 actNewInvoice.disabled = false;
516 actLinkInvoice.disabled = false;
517 actViewInvoice.disabled = false;
521 actReceive.disabled = false;
522 actReceive.onclick = function() {
523 if (self.checkLiAlerts(li.id()))
524 self.issueReceive(li);
525 nodeByName("action_none", row).selected = true;
530 actUnRecv.disabled = false;
531 actUnRecv.onclick = function() {
532 if (confirm(localeStrings.UNRECEIVE_LI))
533 self.issueReceive(li, /* rollback */ true);
534 nodeByName("action_none", row).selected = true;
536 // TODO we should allow editing before receipt, in which case the
537 // test should be "if 1 or more real (acp) copies exist
538 actUpdateBarcodes.disabled = false;
539 actUpdateBarcodes.onclick = function() {
540 self.showRealCopyEditUI(li);
541 nodeByName("action_none", row).selected = true;
543 actHoldingsMaint.disabled = false;
544 actHoldingsMaint.onclick = self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
552 this._setAlertStore = function() {
553 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
555 "data": acqliat.toStoreData(
557 "acqliat", {"id": {"!=": null}}
562 acqLitAlertAlertText.setValue(); /* make the store "live" */
563 acqLitAlertAlertText._store_ready = true;
567 * Draws and shows the lineitem notes pane
569 this.drawLiNotes = function(li) {
572 if (!acqLitAlertAlertText._store_ready)
573 this._setAlertStore();
576 li.lineitem_notes().sort(
578 if(a.edit_time() < b.edit_time()) return 1;
584 while(this.liNotesTbody.childNodes[0])
585 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
588 acqLitCreateNoteSubmit.onClick = function() {
589 var value = acqLitCreateNoteText.attr('value');
591 var note = new fieldmapper.acqlin();
594 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
597 note.lineitem(li.id());
599 self.updateLiNotes(li, note);
600 acqLitCreateNoteVendorPublic.attr("checked", false);
601 acqLitCreateNoteText.attr("value", "");
604 acqLitCreateAlertSubmit.onClick = function() {
605 if (!acqLitAlertAlertText.item) {
606 alert(localeStrings.ALERT_UNSELECTED);
610 var alert_text = new fieldmapper.acqliat().fromStoreItem(
611 acqLitAlertAlertText.item
613 var value = acqLitAlertNoteValue.attr("value") || "";
615 var note = new fieldmapper.acqlin();
617 note.lineitem(li.id());
619 note.alert_text(alert_text);
621 self.updateLiNotes(li, note);
624 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
628 * Draws a single lineitem note in the notes pane
630 this.addLiNote = function(li, note) {
631 if(note.isdeleted()) return;
633 var row = self.liNotesRow.cloneNode(true);
634 nodeByName("value", row).innerHTML = note.value();
635 var alert_node = nodeByName("alert_code", row);
636 if (note.alert_text()) {
637 alert_node.innerHTML = note.alert_text().code();
638 if (note.alert_text().description()) {
641 "connectId": [alert_node],
642 "label": note.alert_text().description()
643 }, dojo.create("span", null, alert_node, "after")
648 if (openils.Util.isTrue(note.vendor_public()))
649 nodeByName("vendor_public", row).innerHTML =
650 localeStrings.VENDOR_PUBLIC;
652 nodeByName("delete", row).onclick = function() {
653 note.isdeleted(true);
654 self.liNotesTbody.removeChild(row);
655 self.updateLiNotes(li);
658 if(note.edit_time()) {
659 nodeByName("edit_time", row).innerHTML =
660 dojo.date.locale.format(
661 dojo.date.stamp.fromISOString(note.edit_time()),
662 {formatLength:'short'});
665 self.liNotesTbody.appendChild(row);
669 * Updates any new/changed/deleted notes on the server
671 this.updateLiNotes = function(li, newNote) {
677 notes = li.lineitem_notes().filter(
679 if(note.ischanged() || note.isnew() || note.isdeleted())
685 if(notes.length == 0) return;
686 progressDialog.show();
688 fieldmapper.standardRequest(
689 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
691 params : [this.authtoken, notes],
692 onresponse : function(r) {
693 var resp = openils.Util.readResponse(r);
698 // remove the old changed notes
700 dojo.forEach(li.lineitem_notes(),
702 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
706 li.lineitem_notes(list);
709 progressDialog.hide();
710 self.updateLiNotesCount(li);
711 self.drawLiNotes(li);
715 progressDialog.update(resp);
716 var newnote = resp.note;
718 if(!newnote.isdeleted()) {
719 newnote.isnew(false);
720 newnote.ischanged(false);
721 li.lineitem_notes().push(newnote);
728 this.updateLiPrice = function(input, li) {
730 var price = input.value;
731 if(Number(price) == Number(li.estimated_unit_price())) return;
733 fieldmapper.standardRequest(
734 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
736 params : [this.authtoken, li.id(), price],
737 oncomplete : function(r) {
738 openils.Util.readResponse(r);
739 li.estimated_unit_price(price); // update local copy
745 this.removeLineitem = function(liId) {
746 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
747 delete this.liCache[liId];
748 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
751 this.drawInfo = function(liId) {
752 if (!this._isRelatedViewer) {
753 var d = dojo.byId("acq-lit-info-related");
754 if (!this.relCache[liId]) {
755 fieldmapper.standardRequest(
758 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
761 "params": [openils.User.authtoken, liId],
762 "onresponse": function(r) {
763 self.relCache[liId] = openils.Util.readResponse(r);
764 nodeByName("related_number", d).innerHTML =
767 self.relCache[liId] >1 ? "show" : "hide"
773 nodeByName("related_number", d).innerHTML = this.relCache[liId];
774 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
779 openils.acq.Lineitem.fetchAttrDefs(
781 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
786 this._fetchLineitem = function(liId, handler, force) {
788 var li = this.liCache[liId];
789 if(li && li.marc() && li.lineitem_details() && !force)
792 fieldmapper.standardRequest(
793 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve'],
796 params: [self.authtoken, liId, {
798 flesh_cancel_reason: true,
799 flesh_li_details: true,
801 flesh_fund_debit: true }],
803 oncomplete: function(r) {
804 var li = openils.Util.readResponse(r);
805 self.liCache[liId] = li;
812 this._drawInfo = function(li) {
814 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
817 openils.Util.hide('acq-lit-marc-order-record-label');
818 openils.Util.hide(acqLitEditOrderMarc.domNode);
819 openils.Util.show('acq-lit-marc-real-record-label');
821 openils.Util.show('acq-lit-marc-order-record-label');
822 openils.Util.show(acqLitEditOrderMarc.domNode);
823 openils.Util.hide('acq-lit-marc-real-record-label');
826 this.drawMarcHTML(li);
827 this.infoTbody = dojo.byId('acq-lit-info-tbody');
830 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
831 while(this.infoTbody.childNodes[0])
832 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
834 for(var i = 0; i < li.attributes().length; i++) {
835 var attr = li.attributes()[i];
836 var row = this.infoRow.cloneNode(true);
838 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
839 var name = openils.acq.Lineitem.attrDefs[type].filter(
841 return (a.code() == attr.attr_name());
843 ).pop().description();
845 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
846 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
847 this.infoTbody.appendChild(row);
850 if (!this._isRelatedViewer) {
851 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
852 oilsBasePath + "/acq/lineitem/related/" + li.id();
857 this.generateMakeRecTab = function(bib_id,default_view, row) {
861 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
864 show_nav_buttons : true,
865 show_print_button : true,
866 opac_url : xulG.url_prefix(xulG.urls.opac_rdetail + '?r=' + bib_id),
867 default_view : default_view
871 if(row) nodeByName("action_none", row).selected = true;
875 this.drawMarcHTML = function(li) {
876 var params = [null, true, li.marc()];
878 params = [li.eg_bib_id(), true];
880 fieldmapper.standardRequest(
881 ['open-ils.search', 'open-ils.search.biblio.record.html'],
884 oncomplete: function(r) {
885 dojo.byId('acq-lit-marc-div').innerHTML =
886 openils.Util.readResponse(r);
892 this.drawCopies = function(liId, force_fetch) {
893 if (typeof force_fetch == "undefined")
899 this.copyWidgetCache = {};
900 this.oldCopyWidgetCache = {};
901 this.virtDfaCounts = {};
902 this.realDfaCache = {};
905 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
906 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
907 acqLitCopyCountInput.attr('value', '0');
909 while(this.copyTbody.childNodes[0])
910 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
912 this._drawBatchCopyWidgets();
914 this._drawDistribApplied(liId);
916 this._fetchDistribFormulas(
918 openils.acq.Lineitem.fetchAttrDefs(
920 self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch);
927 this._saveDistribAppliedTemplates = function() {
928 if (!this._appliedDistribTemplate) {
929 this._appliedDistribTemplate =
930 dojo.byId("acq-lit-distrib-applied-tbody").
931 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
932 dojo.attr(this._appliedDistribTemplate, "id");
936 this._drawDistribApplied = function(liId) {
937 /* Build this table while hidden to prevent rendering artifacts */
938 openils.Util.hide("acq-lit-distrib-applied-tbody");
940 this._saveDistribAppliedTemplates();
942 /* Remove any rows in the table from previous populations */
943 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
944 forEach(dojo.destroy);
946 /* Unregister all dijits previously created (for some reason this isn't
947 * covered by the above destroy calls). */
948 dijit.registry.forEach(
949 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
952 /* Populate the table with our liId */
954 fieldmapper.standardRequest(
956 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
959 "params": [self.authtoken, liId],
960 "onresponse": function(r) {
961 var dfa = openils.Util.readResponse(r);
964 self.realDfaCache[dfa.id()] = dfa;
965 self._drawDistribAppliedUnit(dfa);
968 "oncomplete": function() {
969 /* Reveal built table */
972 "acq-lit-distrib-applied-tbody", "table-row-group"
980 this._drawDistribAppliedUnit = function(dfa) {
982 var row = dojo.query(
983 'tr[formula="' + dfa.formula().id() + '"]',
984 "acq-lit-distrib-applied-tbody"
989 row = dojo.clone(this._appliedDistribTemplate);
990 dojo.attr(row, "formula", dfa.formula().id());
991 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
994 var td = dojo.query("td", row)[0];
996 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
997 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1000 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1002 new dijit.form.Button(
1004 "onClick": function() {
1005 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1006 self.deleteDfa(dfa);
1009 /* XXX I /cannot/ make the following work in as a CSS class
1010 * for some reason. So frustrating... */
1011 "style": function(id) {
1013 "font-weight: bold; color: #c00;" :
1015 }(dfa.id()) + "margin: 0 6px;display: inline;"
1016 }, "dfa-button-" + dfa.id()
1020 "connectId": ["dfa-button-" + dfa.id()],
1021 "label": dojo.string.substitute(
1022 localeStrings.DFA_TIP, dfa.id() > 0 ? [
1023 openils.User.formalName(dfa.creator()),
1024 dojo.date.locale.format(
1025 dojo.date.stamp.fromISOString(dfa.create_time()),
1026 {"formatLength":"short"}
1028 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
1030 }, "dfa-tip-" + dfa.id()
1034 this.deleteDfa = function(dfa) {
1035 if (dfa.id() > 0) { /* real */
1036 this.pcrud.eliminate(
1039 "oncomplete": function() {
1040 self._removeDistribApplied(dfa.id());
1041 delete self.realDfaCache[dfa.id()];
1045 } else { /* virtual */
1046 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
1047 this.virtDfaCounts[dfa.formula().id()] = 0;
1048 /* hasn't been saved yet, so no need to do anything server side */
1049 this._removeDistribApplied(dfa.id());
1054 this._removeDistribApplied = function(dfaId) {
1055 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
1056 dijit.registry.forEach(
1057 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
1059 this._removeDistribAppliedEmptyRows();
1062 this._removeAllDistribAppliedVirtual = function() {
1063 /* Unregister dijits */
1064 dijit.registry.forEach(
1065 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
1067 this._removeDistribAppliedEmptyRows();
1070 this._removeDistribAppliedEmptyRows = function() {
1071 /* Remove any rows with no DFA at all */
1072 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
1074 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
1080 * Insert a new row into the distribution formula selection form
1082 this._addDistribFormulaRow = function() {
1085 if (!self.distribForms) {
1086 // no formulas, hide the form
1087 openils.Util.hide('acq-lit-distrib-formula-tbody');
1091 if(!this.distribFormulaTemplate)
1092 this.distribFormulaTemplate =
1093 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
1095 var row = this.distribFormulaTemplate.cloneNode(true);
1096 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
1098 this.dfSelector = new dijit.form.FilteringSelect(
1099 {"labelAttr": "dynLabel", "labelType": "html"},
1100 nodeByName("selector", row)
1102 this._updateFormulaStore();
1103 this.dfSelector.fetchProperties =
1104 {"sort": [{"attribute": "use_count", "descending": true}]};
1106 var apply = new dijit.form.Button(
1107 {"label": localeStrings.APPLY},
1108 nodeByName('set_button', row)
1111 var reset = new dijit.form.Button(
1112 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
1113 nodeByName("reset_button", row)
1116 dojo.connect(apply, 'onClick',
1118 var form_id = self.dfSelector.attr("value");
1119 if(!form_id) return;
1120 self._applyDistribFormula(form_id);
1121 reset.attr("disabled", false);
1125 dojo.connect(reset, 'onClick',
1127 self.restoreCopyFieldsBeforeDF();
1128 self.virtDfaCounts = {};
1129 self.virtDfaId = -1;
1131 self._updateFormulaStore();
1132 self._removeAllDistribAppliedVirtual();
1133 reset.attr("disabled", "true");
1140 * Applies a distrib formula to the current set of copies
1142 this._applyDistribFormula = function(formula) {
1143 if(!formula) return;
1145 formula = this.distribForms.filter(
1146 function(form) { return form.id() == formula; }
1149 var copyRows = dojo.query('tr', self.copyTbody);
1151 if (this.dfeOffset >= copyRows.length) {
1152 alert(localeStrings.OUT_OF_COPIES);
1156 var entries_applied = 0;
1158 var rowIndex = this.dfeOffset;
1159 rowIndex < copyRows.length;
1163 var row = copyRows[rowIndex];
1164 var copy_id = row.getAttribute('copy_id');
1165 var copyWidgets = this.copyWidgetCache[copy_id];
1166 var entryIndex = this.dfeOffset;
1169 // find the correct entry for the current row
1170 dojo.forEach(formula.entries(),
1173 entryIndex += e.item_count();
1174 if(entryIndex > rowIndex)
1182 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
1183 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
1186 this.saveCopyFieldsBeforeDF(copy_id);
1187 this._copy_fields_for_acqdf.forEach(
1189 if(entry[field]()) {
1190 copyWidgets[field].attr('value', (entry[field]()));
1197 if (entries_applied) {
1198 this.virtDfaCounts[formula.id()] =
1199 ++(this.virtDfaCounts[formula.id()]) || 1;
1200 this._updateFormulaStore();
1201 this._drawDistribAppliedUnit(
1203 var dfa = new acqdfa();
1204 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
1207 this.dfeOffset += entries_applied;
1212 * This function updates the DF store for the dropdown so that use_counts
1213 * can reflect DF applications from this session before they're saved
1216 this._updateFormulaStore = function() {
1217 this.dfSelector.store = new dojo.data.ItemFileReadStore(
1219 "data": self._labelFormulasWithCounts(
1220 acqdf.toStoreData(self.distribForms)
1226 this.saveCopyFieldsBeforeDF = function(copy_id) {
1228 if (!this.oldCopyWidgetCache[copy_id]) {
1229 var copyWidgets = this.copyWidgetCache[copy_id];
1231 this.oldCopyWidgetCache[copy_id] = {};
1232 this._copy_fields_for_acqdf.forEach(
1234 self.oldCopyWidgetCache[copy_id][f] =
1235 copyWidgets[f].attr("value");
1241 this.restoreCopyFieldsBeforeDF = function() {
1243 for (var copy_id in this.oldCopyWidgetCache) {
1244 this._copy_fields_for_acqdf.forEach(
1246 self.copyWidgetCache[copy_id][f].attr(
1247 "value", self.oldCopyWidgetCache[copy_id][f]
1254 this._labelFormulasWithCounts = function(store_data) {
1255 for (var key in store_data.items) {
1256 var obj = store_data.items[key];
1257 obj.use_count = Number(obj.use_count); /* needed for sorting */
1259 if (this.virtDfaCounts[obj.id])
1260 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
1262 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
1263 obj.use_count + "]</span> " + obj.name;
1269 * This method formerly would not refetch the DF formulas if they'd been
1270 * loaded already, but now it always re-fetches, since use_count changes.
1272 this._fetchDistribFormulas = function(onload) {
1273 fieldmapper.standardRequest(
1275 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
1278 "params": [openils.User.authtoken],
1279 "oncomplete": function(r) {
1280 self.distribForms = openils.Util.readResponse(r);
1281 if(!self.distribForms || self.distribForms.length == 0) {
1282 self.distribForms = [];
1284 self._addDistribFormulaRow();
1291 this._drawBatchCopyWidgets = function() {
1292 var row = this.copyBatchRow;
1293 dojo.forEach(liDetailBatchFields,
1295 if(self.copyBatchRowDrawn) {
1296 self.copyBatchWidgets[field].attr('value', null);
1298 var widget = new openils.widget.AutoFieldWidget({
1301 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1302 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1303 searchFilter : (field == 'fund') ? {"active": "t"} : null,
1304 parentNode : dojo.query('[name='+field+']', row)[0],
1305 orgLimitPerms : ['CREATE_PICKLIST'],
1308 "labelType": (field == "fund") ? "html" : null
1310 noCache: (field == "fund"),
1315 if (field == "fund" && w.store)
1316 self._ensureCSSFundClasses(w.store);
1317 self.copyBatchWidgets[field] = w;
1320 if (field == "fund") {
1322 widget.widget, "onChange", function(val) {
1323 self._updateFundSelectorStyle(widget, val);
1330 this.copyBatchRowDrawn = true;
1333 this.batchCopyUpdate = function() {
1335 for(var k in this.copyWidgetCache) {
1336 var cache = this.copyWidgetCache[k];
1337 dojo.forEach(liDetailBatchFields, function(f) {
1338 var newval = self.copyBatchWidgets[f].attr('value');
1339 if(newval) cache[f].attr('value', newval);
1344 this._drawCopies = function(li) {
1347 // this button sets the total number of copies for a given lineitem
1348 acqLitAddCopyCount.onClick = function() {
1349 var count = acqLitCopyCountInput.attr('value');
1352 while(self.copyCount() < count)
1355 // delete rows if necessary
1356 var diff = self.copyCount() - count;
1358 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
1359 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
1360 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
1362 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1368 if(li.lineitem_details().length > 0) {
1369 dojo.forEach(li.lineitem_details(),
1371 self.addCopy(li, copy);
1379 this.copyCount = function() {
1381 for(var id in this.copyCache) {
1382 if(!this.copyCache[id].isdeleted())
1388 this.virtCopyId = -1;
1389 this.addCopy = function(li, copy) {
1390 var row = this.copyRow.cloneNode(true);
1391 this.copyTbody.appendChild(row);
1395 copy = new fieldmapper.acqlid();
1397 copy.id(this.virtCopyId--);
1398 copy.lineitem(li.id());
1401 this.copyCache[copy.id()] = copy;
1402 row.setAttribute('copy_id', copy.id());
1403 self.copyWidgetCache[copy.id()] = {};
1405 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1407 dojo.forEach(liDetailFields,
1410 if (field == "fund") {
1411 searchFilter = (copy.fund() ?
1412 {"-or": {"active": "t", "id": copy.fund()}} :
1415 searchFilter = null;
1418 var readOnly = false;
1420 // TODO: Add support for changing the owning_lib after real copies have been made.
1421 // owning_lib is order data as much as its item data
1422 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
1426 // TODO: add support for changing the fund after debits have been created
1427 // Note: invoicing allows the change
1428 if(copy.fund_debit() && field == 'fund') {
1432 var widget = new openils.widget.AutoFieldWidget({
1435 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1436 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1437 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1438 searchFilter : searchFilter,
1439 noCache: (field == "fund"),
1441 parentNode : dojo.query('[name='+field+']', row)[0],
1442 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
1443 readOnly : readOnly,
1447 // make sure we capture the value from any async widgets
1450 if (field == "fund" && w.store)
1451 self._ensureCSSFundClasses(w.store);
1454 copy[field](ww.getFormattedValue())
1456 self.copyWidgetCache[copy.id()][field] = w;
1458 dojo.connect(w, 'onChange',
1460 if (field == "fund")
1461 self._updateFundSelectorStyle(widget, val);
1463 if (!readOnly && (copy.isnew() || val != copy[field]())) {
1464 // prevent setting ischanged() automatically on widget load for existing copies
1465 copy[field](widget.getFormattedValue())
1466 copy.ischanged(true);
1475 this.updateLidState(copy, row);
1478 this._ensureCSSFundClass = function(id) {
1479 if (!this.fundStyleSheet) {
1481 "style", {"type": "text/css"},
1482 document.getElementsByTagName("head")[0], "last"
1484 this.fundStyleSheet = document.styleSheets[
1485 document.styleSheets.length - 1
1489 var cn = "fund_" + id;
1490 if (!this.haveFundClass[cn]) {
1491 fieldmapper.standardRequest(
1492 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
1494 "params": [openils.User.authtoken, id],
1496 "oncomplete": function(r) {
1497 r = openils.Util.readResponse(r);
1498 self.fundBalanceState[id] = r;
1500 if (r[0] /* stop */)
1501 style = fundStyles.stop;
1502 else if (r[1] /* warning */)
1503 style = fundStyles.warning;
1504 self.fundStyleSheet.insertRule(
1505 "." + cn + " { " + style + " }",
1506 self.fundStyleSheet.cssRules.length
1508 self.haveFundClass[cn] = true;
1515 this._ensureCSSFundClasses = function(store) {
1517 "query": {"id": "*"},
1518 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
1522 this._updateFundSelectorStyle = function(widget, fund_id) {
1523 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
1524 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
1527 this.updateLidState = function(copy, row) {
1528 if (typeof(row) == "undefined") {
1530 'tr[copy_id="' + copy.id() + '"]', this.copyTbody
1535 var recv_link = nodeByName("receive", row);
1536 var unrecv_link = nodeByName("unreceive", row);
1537 var del_link = nodeByName("delete", row);
1538 var cxl_link = nodeByName("cancel", row);
1539 var claim_link = nodeByName("claim", row);
1540 var cxl_reason_link = nodeByName("cancel_reason", row);
1542 if (copy.cancel_reason()) {
1543 openils.Util.hide(del_link.parentNode);
1544 openils.Util.hide(recv_link);
1545 openils.Util.hide(unrecv_link);
1546 openils.Util.hide(cxl_link);
1547 openils.Util.hide(claim_link);
1549 /* XXX the following may leak memory in a long lived table: dijits may not get destroyed... not positive. revisit. */
1550 var holds_reason = dojo.create(
1552 "style": "border-bottom: 1px dashed #000;",
1553 "innerHTML": "Cancelled" /* XXX [sic] and i18n */
1554 }, cxl_reason_link, "only"
1558 "label": "<em>" + copy.cancel_reason().label() +
1559 "</em><br />" + copy.cancel_reason().description(),
1560 "connectId": [holds_reason]
1561 }, dojo.create("span", null, cxl_reason_link, "last")
1563 openils.Util.show(cxl_reason_link, "inline");
1564 } else if (this.isPO) {
1565 /* Only using this in one place so far, but may want it for better
1566 * decisions on when to display certain controls. */
1567 var li_state = this.liCache[copy.lineitem()].state();
1569 openils.Util.hide(del_link.parentNode);
1570 openils.Util.hide(cxl_reason_link);
1572 /* Avoid showing (un)receive links, cancel links, for virt copies */
1573 if (copy.id() > 0) {
1574 if (copy.recv_time()) {
1575 openils.Util.hide(cxl_link);
1576 openils.Util.hide(recv_link);
1577 openils.Util.hide(claim_link);
1579 openils.Util.show(unrecv_link, "inline");
1580 unrecv_link.onclick = function() {
1581 if (confirm(localeStrings.UNRECEIVE_LID))
1582 self.issueReceive(copy, /* rollback */ true);
1585 openils.Util.hide(unrecv_link);
1587 if (this.claimEligibleLid[copy.id()]) {
1588 openils.Util.show(claim_link, "inline");
1589 claim_link.onclick = function() {
1590 self.claimDialog.show(
1591 self.liCache[copy.lineitem()], copy.id()
1595 openils.Util.hide(claim_link);
1598 openils.Util[li_state == "on-order" ? "show" : "hide"](
1601 openils.Util.show(cxl_link, "inline");
1602 recv_link.onclick = function() {
1603 if (self.checkLiAlerts(copy.lineitem()))
1604 self.issueReceive(copy);
1606 cxl_link.onclick = function() {
1607 self.cancelLid(copy.id());
1611 openils.Util.hide(cxl_link);
1612 openils.Util.hide(unrecv_link);
1613 openils.Util.hide(recv_link);
1614 openils.Util.hide(claim_link);
1617 openils.Util.hide(unrecv_link);
1618 openils.Util.hide(recv_link);
1619 openils.Util.hide(cxl_reason_link);
1620 openils.Util.hide(claim_link);
1622 del_link.onclick = function() { self.deleteCopy(row) };
1623 openils.Util.show(del_link.parentNode);
1627 this.cancelLid = function(lid_id) {
1628 lidCancelDialog._lid_id = lid_id;
1629 openils.Util.show(lidCancelDialog.domNode.parentNode);
1630 lidCancelDialog.show();
1631 if (!lidCancelDialog._prepared) {
1632 var widget = new openils.widget.AutoFieldWidget({
1633 "fmField": "cancel_reason",
1634 "fmClass": "acqlid",
1635 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
1636 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1641 acqLidCancelButton.onClick = function() {
1642 if (w.attr("value")) {
1643 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
1645 lidCancelDialog._lid_id,
1649 lidCancelDialog.hide();
1652 lidCancelDialog._prepared = true;
1658 this._cancelLid = function(lid_id, reason) {
1659 fieldmapper.standardRequest(
1660 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
1661 "params": [openils.User.authtoken, lid_id, reason],
1663 "onresponse": function(r) {
1664 if (r = openils.Util.readResponse(r)) {
1666 for (var id in r.lid) {
1667 /* actually this should only iterate once */
1668 self.copyCache[id].cancel_reason(
1669 r.lid[id].cancel_reason
1671 self.updateLidState(self.copyCache[id]);
1680 this._confirmAlert = function(li, lin) {
1682 dojo.string.substitute(
1683 localeStrings.CONFIRM_LI_ALERT, [
1684 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1685 "title", "lineitem_marc_attr_definition"
1687 lin.alert_text().code(),
1688 lin.alert_text().description() || "",
1695 this.checkLiAlerts = function(li_id) {
1696 var li = this.liCache[li_id];
1698 var alert_notes = li.lineitem_notes().filter(
1699 function(o) { return Boolean(o.alert_text()); }
1702 /* this is _intentionally_ not done in a call to forEach() ... */
1703 for (var i = 0; i < alert_notes.length; i++) {
1704 if (this.noteAcks[alert_notes[i].id()])
1706 else if (!this._confirmAlert(li, alert_notes[i]))
1709 this.noteAcks[alert_notes[i].id()] = true;
1715 this.deleteCopy = function(row) {
1716 var copy = this.copyCache[row.getAttribute('copy_id')];
1717 copy.isdeleted(true);
1719 delete this.copyCache[copy.id()];
1720 this.copyTbody.removeChild(row);
1723 this._virtDfaCountsAsList = function() {
1725 for (var key in this.virtDfaCounts) {
1726 for (var i = 0; i < this.virtDfaCounts[key]; i++)
1732 this.confirmBreachedCopyFunds = function(copies) {
1733 var stop = 0, warning = 0;
1737 var state = self.fundBalanceState[o.fund()];
1738 if (state[0] /* stop */)
1740 else if (state[1] /* warning */)
1747 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
1748 } else if (warning) {
1749 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
1754 this.saveCopyChanges = function(liId) {
1760 for(var id in this.copyCache) {
1761 var c = this.copyCache[id];
1762 if(!c.isdeleted()) total++;
1763 if(c.isnew() || c.ischanged() || c.isdeleted()) {
1764 if(c.id() < 0) c.id(null);
1770 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
1773 if (copies.length > 0) {
1774 if (!this.confirmBreachedCopyFunds(copies))
1777 if (typeof(this._copy_count_cb) == "function")
1778 this._copy_count_cb(liId, total);
1780 openils.Util.show("acq-lit-update-copies-progress");
1781 fieldmapper.standardRequest(
1782 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1784 params: [openils.User.authtoken, copies],
1785 onresponse: function(r) {
1786 var res = openils.Util.readResponse(r);
1787 litUpdateCopiesProgress.update(res);
1789 oncomplete: function() {
1790 self.drawCopies(liId, true /* force_fetch */);
1791 openils.Util.hide("acq-lit-update-copies-progress");
1797 var dfa_list = this._virtDfaCountsAsList();
1798 if (dfa_list.length > 0) {
1799 fieldmapper.standardRequest(
1801 "open-ils.acq.distribution_formula.record_application"],
1804 "params": [openils.User.authtoken, dfa_list, liId],
1805 "onresponse": function(r) {
1806 var res = openils.Util.readResponse(r);
1807 if (res && res.length < dfa_list.length)
1808 alert(localeStrings.DFA_NOT_ALL);
1812 this.virtDfaCounts = {};
1816 this._updateCreatePoPrepayCheckbox = function(prepay) {
1817 var prepay = openils.Util.isTrue(prepay);
1818 this._prepayRequiredByVendor = prepay;
1819 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
1822 this._confirmPoPrepaySituation = function() {
1823 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
1824 if (want_prepay != this._prepayRequiredByVendor) {
1827 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
1828 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
1835 this.applySelectedLiAction = function(action) {
1839 case 'delete_selected':
1840 this._deleteLiList(self.getSelected());
1843 case 'create_order':
1844 this._loadPOSelect();
1845 acqLitPoCreateDialog.show();
1848 case 'save_picklist':
1849 this._loadPLSelect();
1850 acqLitSavePlDialog.show();
1853 case 'selector_ready':
1855 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
1856 acqLitChangeLiStateDialog.show();
1864 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
1871 case 'rollback_receive_po':
1872 this.rollbackPoReceive();
1875 case 'create_assets':
1876 this.createAssets();
1879 case 'export_attr_list':
1880 this.chooseExportAttr();
1883 case 'batch_apply_funds':
1884 this.applyBatchLiFunds();
1887 case 'add_brief_record':
1889 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
1891 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
1895 case "cancel_lineitems":
1896 this.maybeCancelLineitems();
1899 case "change_claim_policy":
1900 var li_list = this.getSelected();
1901 this.claimPolicyPicker.attr("value", null);
1902 liClaimPolicyDialog.show();
1903 liClaimPolicySave.onClick = function() {
1904 self.changeClaimPolicy(
1906 self.claimPolicyPicker.attr("value"),
1909 function(li) { self.setClaimPolicyControl(li); }
1911 liClaimPolicyDialog.hide();
1919 this.changeClaimPolicy = function(li_list, value, callback) {
1921 function(li) { li.claim_policy(value); }
1923 fieldmapper.standardRequest(
1924 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
1925 "params": [openils.User.authtoken, li_list],
1927 "oncomplete": function(r) {
1928 r = openils.Util.readResponse(r);
1929 if (callback) callback(r);
1935 this.createAssets = function() {
1936 if(!this.isPO) return;
1937 if(!confirm(localeStrings.CREATE_PO_ASSETS_CONFIRM)) return;
1938 this.show('acq-lit-progress-numbers');
1940 fieldmapper.standardRequest(
1941 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
1943 params: [this.authtoken, this.isPO],
1944 onresponse: function(r) {
1945 var resp = openils.Util.readResponse(r);
1946 self._updateProgressNumbers(resp, true);
1952 this.maybeCancelLineitems = function() {
1953 openils.Util.show("acq-lit-cancel-reason", "inline");
1954 if (!acqLitCancelLineitemsButton._prepared) {
1955 var widget = new openils.widget.AutoFieldWidget({
1956 "fmField": "cancel_reason",
1958 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
1959 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1964 acqLitCancelLineitemsButton.onClick = function() {
1965 if (w.attr("value")) {
1966 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
1967 self._cancelLineitems(w.attr("value"));
1969 openils.Util.hide("acq-lit-cancel-reason");
1972 acqLitCancelLineitemsButton._prepared = true;
1978 this._cancelLineitems = function(reason) {
1979 var id_list = this.getSelected().map(function(o) { return o.id(); });
1980 fieldmapper.standardRequest(
1981 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
1982 "params": [openils.User.authtoken, id_list, reason],
1984 "onresponse": function(r) {
1985 if (r = openils.Util.readResponse(r)) {
1987 for (var id in r.li) {
1988 self.liCache[id].state(r.li[id].state);
1989 self.liCache[id].cancel_reason(
1990 r.li[id].cancel_reason
1992 self.updateLiState(self.liCache[id]);
1995 if (r.lid && self.copyCache) {
1996 for (var id in r.lid) {
1997 if (self.copyCache[id]) {
1998 self.copyCache[id].cancel_reason(
1999 r.lid[id].cancel_reason
2001 self.updateLidState(self.copyCache[id]);
2011 this.chooseExportAttr = function() {
2012 if (!acqLitExportAttrSelector._li_setup) {
2014 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
2016 "data": acqliad.toStoreData(
2018 "acqliad", {"code": li_exportable_attrs}
2023 acqLitExportAttrSelector.setValue();
2024 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
2025 acqLitExportAttrSelector._li_setup = true;
2027 openils.Util.show("acq-lit-export-attr-holder", "inline");
2030 this.exportAttrList = function() {
2031 var attr_def = acqLitExportAttrSelector.item;
2032 var li_list = this.getSelected();
2033 var value_list = li_list.map(
2035 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2036 attr_def.code, "lineitem_marc_attr_definition"
2039 ).filter(function(attr) { return Boolean(attr); });
2041 if (value_list.length > 0) {
2042 if (value_list.length < li_list.length) {
2044 dojo.string.substitute(
2045 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
2052 openils.XUL.contentToFileSaveDialog(
2053 value_list.join("\n"),
2054 localeStrings.EXPORT_SAVE_DIALOG_TITLE
2060 alert(dojo.string.substitute(
2061 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
2065 openils.Util.hide("acq-lit-export-attr-holder");
2068 this.printPO = function() {
2069 if(!this.isPO) return;
2070 progressDialog.show(true);
2071 fieldmapper.standardRequest(
2072 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
2074 params: [this.authtoken, this.isPO, 'html'],
2075 oncomplete: function(r) {
2076 progressDialog.hide();
2077 var evt = openils.Util.readResponse(r);
2078 if(evt && evt.template_output()) {
2079 win = window.open('','', 'resizable,width=800,height=600,scrollbars=1');
2080 win.document.body.innerHTML = evt.template_output().data();
2088 this.receivePO = function() {
2089 if (!this.isPO) return;
2091 for (var id in this.liCache) {
2092 /* assumption: liCache reflects exactly the
2093 * set of LIs that belong to our PO */
2094 if (this.liCache[id].state() != "received" &&
2095 !this.checkLiAlerts(id)) return;
2098 this.show('acq-lit-progress-numbers');
2100 fieldmapper.standardRequest(
2101 ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
2103 params: [this.authtoken, this.isPO],
2104 onresponse : function(r) {
2105 var resp = openils.Util.readResponse(r);
2106 self._updateProgressNumbers(resp, true);
2112 this.issueReceive = function(obj, rollback) {
2113 /* (For now) there shall be no marking LI or LIDs (un)received
2114 * except from the actual "view PO" interface. */
2115 if (!this.isPO) return;
2118 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
2120 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
2122 progressDialog.show(true);
2123 fieldmapper.standardRequest(
2124 ["open-ils.acq", method], {
2126 "params": [this.authtoken, obj.id()],
2127 "onresponse": function(r) {
2128 if (r = openils.Util.readResponse(r)) {
2129 self.fetchClaimInfo(
2130 part == "lineitem" ? obj.id() : obj.lineitem(),
2132 function() { self.handleReceive(r); }
2134 progressDialog.hide();
2142 * Handles the responses from receive and rollback ML calls.
2144 this.handleReceive = function(resp) {
2147 for (var li_id in resp.li) {
2148 for (var key in resp.li[li_id])
2149 self.liCache[li_id][key](resp.li[li_id][key]);
2150 self.updateLiState(self.liCache[li_id]);
2154 if (typeof(self.poUpdateCallback) == "function")
2155 self.poUpdateCallback(resp.po);
2158 for (var lid_id in resp.lid) {
2159 for (var key in resp.lid[lid_id])
2160 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
2161 self.updateLidState(self.copyCache[lid_id]);
2167 this.rollbackPoReceive = function() {
2168 if(!this.isPO) return;
2169 if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
2170 this.show('acq-lit-progress-numbers');
2172 fieldmapper.standardRequest(
2173 ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
2175 params: [this.authtoken, this.isPO],
2176 onresponse : function(r) {
2177 var resp = openils.Util.readResponse(r);
2178 self._updateProgressNumbers(resp, true);
2184 this._updateProgressNumbers = function(resp, reloadOnComplete) {
2186 dojo.byId('acq-pl-lit-li-processed').innerHTML = resp.li;
2187 dojo.byId('acq-pl-lit-lid-processed').innerHTML = resp.lid;
2188 dojo.byId('acq-pl-lit-debits-processed').innerHTML = resp.debits_accrued;
2189 dojo.byId('acq-pl-lit-bibs-processed').innerHTML = resp.bibs;
2190 dojo.byId('acq-pl-lit-indexed-processed').innerHTML = resp.indexed;
2191 dojo.byId('acq-pl-lit-copies-processed').innerHTML = resp.copies;
2192 if(resp.complete && reloadOnComplete)
2193 location.href = location.href;
2197 this._createPO = function(fields) {
2198 this.show('acq-lit-progress-numbers');
2199 var po = new fieldmapper.acqpo();
2200 po.provider(this.createPoProviderSelector.attr('value'));
2201 po.ordering_agency(this.createPoAgencySelector.attr('value'));
2202 po.prepayment_required(fields.prepayment_required[0] ? true : false);
2204 var selected = this.getSelected( (fields.create_from == 'all') );
2205 if(selected.length == 0) return;
2207 var max = selected.length * 3;
2210 fieldmapper.standardRequest(
2211 ['open-ils.acq', 'open-ils.acq.purchase_order.create'],
2214 openils.User.authtoken,
2217 lineitems : selected.map(function(li) { return li.id() }),
2218 create_assets : fields.create_assets[0],
2222 onresponse : function(r) {
2223 var resp = openils.Util.readResponse(r);
2224 self._updateProgressNumbers(resp);
2226 location.href = oilsBasePath + '/acq/po/view/' + resp.purchase_order.id();
2232 this.batchFundWidget = null;
2234 this.applyBatchLiFunds = function() {
2236 var liIds = this.getSelected().map(function(li) { return li.id(); });
2237 if(liIds.length == 0) return; // warn?
2240 batchFundUpdateDialog.show();
2242 if(!this.batchFundWidget) {
2243 this.batchFundWidget = new openils.widget.AutoFieldWidget({
2245 selfReference : true,
2246 labelFormat : fundLabelFormat,
2247 searchFormat : fundSearchFormat,
2248 searchFilter : {"active": "t"},
2249 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
2250 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2251 dijitArgs : { "required": true, "labelType": "html" },
2254 this.batchFundWidget.build();
2257 dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
2258 dojo.connect(batchFundUpdateSubmit, 'onClick',
2261 // TODO: call .dry_run first to test thresholds
2262 fieldmapper.standardRequest(
2263 ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
2266 openils.User.authtoken,
2268 self.batchFundWidget.widget.attr('value')
2270 oncomplete : function(r) {
2271 var resp = openils.Util.readResponse(r);
2273 location.href = location.href;
2282 this._deleteLiList = function(list, idx) {
2283 if(idx == null) idx = 0;
2284 if(idx >= list.length) return;
2285 var liId = list[idx].id();
2286 fieldmapper.standardRequest(
2287 ['open-ils.acq', 'open-ils.acq.lineitem.delete'],
2289 params: [openils.User.authtoken, liId],
2290 oncomplete: function(r) {
2291 self.removeLineitem(liId);
2292 self._deleteLiList(list, ++idx);
2298 this.editOrderMarc = function(li) {
2300 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
2301 to true in about:config */
2303 if(!openils.XUL.enableXPConnect()) return;
2305 if(openils.XUL.isXUL()) {
2306 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
2308 win = window.open('/xul/server/cat/marcedit.xul');
2312 record : {marc : li.marc()},
2314 label: 'Save Record', // XXX I18N
2315 func: function(xmlString) {
2317 fieldmapper.standardRequest(
2318 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
2320 params: [openils.User.authtoken, li],
2321 oncomplete: function(r) {
2322 openils.Util.readResponse(r);
2324 self.drawInfo(li.id())
2333 this._savePl = function(values) {
2335 var selected = this.getSelected( (values.which == 'all') );
2336 openils.Util.show('acq-lit-generic-progress');
2338 if(values.new_name) {
2339 openils.acq.Picklist.create(
2340 {name: values.new_name},
2342 self._updateLiList(id, selected, 0,
2344 location.href = oilsBasePath + '/acq/picklist/view/' + id;
2348 } else if(values.existing_pl) {
2349 // update lineitems to use an existing picklist
2350 self._updateLiList(values.existing_pl, selected, 0,
2352 location.href = oilsBasePath + '/acq/picklist/view/' + values.existing_pl;
2357 this._updateLiState = function(values, state) {
2359 var selected = this.getSelected( (values.which == 'all') );
2360 if(!selected.length) return;
2361 dojo.forEach(selected, function(li) {li.state(state);});
2362 self._updateLiList(null, selected, 0,
2363 // TODO consider inline updates for efficiency
2364 function() { location.href = location.href }
2368 this._updateLiList = function(pl, list, idx, oncomplete) {
2369 if(idx >= list.length) return oncomplete();
2371 if(pl != null) li.picklist(pl);
2372 litGenericProgress.update({maximum: list.length, progress: idx});
2373 new openils.acq.Lineitem({lineitem:li}).update(
2375 self._updateLiList(pl, list, ++idx, oncomplete);
2380 this._loadPOSelect = function() {
2381 if (!this.createPoProviderSelector) {
2382 var widget = new openils.widget.AutoFieldWidget({
2383 "fmField": "provider",
2385 "searchFilter": {"active": "t"},
2386 "parentNode": dojo.byId("acq-lit-po-provider"),
2388 "onChange": function() {
2390 self._updateCreatePoPrepayCheckbox(
2391 this.item.prepayment_required
2397 widget.build(function(w) { self.createPoProviderSelector = w; });
2400 if (!this.createPoAgencySelector) {
2401 var widget = new openils.widget.AutoFieldWidget({
2402 "fmField": "ordering_agency",
2404 "parentNode": dojo.byId("acq-lit-po-agency"),
2405 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2407 widget.build(function(w) { self.createPoAgencySelector = w; });
2411 this._loadPLSelect = function(preSel) {
2412 if(this._plSelectLoaded) return;
2414 function handleResponse(r) {
2415 plList.push(r.recv().content());
2417 var method = 'open-ils.acq.picklist.user.retrieve';
2418 fieldmapper.standardRequest(
2419 ['open-ils.acq', method],
2421 params: [this.authtoken],
2422 onresponse: handleResponse,
2423 oncomplete: function() {
2424 self._plSelectLoaded = true;
2425 acqLitAddExistingSelect.store =
2426 new dojo.data.ItemFileReadStore({data:acqpl.toStoreData(plList)});
2428 acqLitAddExistingSelect.setValue(preSel);
2434 this.showRealCopyEditUI = function(li) {
2439 this._fetchLineitem(li.id(),
2441 li = self.liCache[li.id()] = fullLi;
2445 id : li.lineitem_details().map(
2446 function(item) { return item.eg_copy_id() }
2450 oncomplete : function(r) {
2452 var r_list = openils.Util.readResponse( r );
2453 for (var i = 0; i < r_list.length; i++) {
2454 var copy = r_list[i];
2455 var volId = copy.call_number();
2456 var volume = self.volCache[volId];
2458 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2460 copy.call_number(volume);
2461 copyList.push(copy);
2464 // If we need to, we can pass in an update_copy function to handle the update instead of volume_item_creator
2465 xulG.volume_item_creator( { 'existing_copies' : copyList } );
2468 alert('error in oncomplete: ' + E);
2477 this.drawBibFinder = function(li) {
2480 var liWrapper = new openils.acq.Lineitem({lineitem:li});
2483 ['isbn', 'upc', 'issn', 'title', 'author'],
2485 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
2487 if(field == 'title' || field == 'author') {
2488 query += field +':' + val + ' ';
2490 query += 'identifier|' + field + ':' + val + ' ';
2497 oilsBasePath + '/acq/lineitem/findbib?query=' + escape(query),
2498 '', 'resizable,scrollbars=1');
2500 win.window.recordFound = function(bibId) {
2503 var attrs = li.attributes();
2504 li.attributes(null);
2505 li.eg_bib_id(bibId);
2507 fieldmapper.standardRequest(
2508 ["open-ils.acq", "open-ils.acq.lineitem.update"],
2510 "params": [openils.User.authtoken, li],
2512 "oncomplete": function(r) {
2513 if(openils.Util.readResponse(r)) {
2514 location.href = location.href;