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.claimDialog = new ClaimDialogManager(
72 liClaimDialog, finalClaimDialog, this.claimEligibleLidByLi,
73 function(li) { /* callback that fires when claims are made */
74 self.fetchClaimInfo(li.id(), /* force update */ true);
78 dojo.byId("acq-lit-li-actions-selector").onchange = function() {
79 self.applySelectedLiAction(this.options[this.selectedIndex].value);
80 this.selectedIndex = 0;
83 acqLitCreatePoSubmit.onClick = function() {
84 if (self._confirmPoPrepaySituation()) {
85 acqLitPoCreateDialog.hide();
86 self._createPO(acqLitPoCreateDialog.getValues());
92 acqLitSavePlButton.onClick = function() {
93 acqLitSavePlDialog.hide();
94 self._savePl(acqLitSavePlDialog.getValues());
97 acqLitCancelLiStateButton.onClick = function() {
98 acqLitChangeLiStateDialog.hide();
100 acqLitSaveLiStateButton.onClick = function() {
101 acqLitChangeLiStateDialog.hide();
102 self._updateLiState(acqLitChangeLiStateDialog.getValues(), acqLitChangeLiStateDialog.attr('state'));
106 dojo.byId('acq-lit-select-toggle').onclick = function(){self.toggleSelect()};
107 dojo.byId('acq-lit-info-back-button').onclick = function(){self.show('list')};
108 dojo.byId('acq-lit-copies-back-button').onclick = function(){self.show('list')};
109 dojo.byId('acq-lit-notes-back-button').onclick = function(){self.show('list')};
110 dojo.byId('acq-lit-real-copies-back-button').onclick = function(){self.show('list')};
112 this.reset = function(keep_selectors) {
113 while(self.tbody.childNodes[0])
114 self.tbody.removeChild(self.tbody.childNodes[0]);
122 this.setNext = function(handler) {
123 var link = dojo.byId('acq-lit-next');
125 dojo.style(link, 'visibility', 'visible');
126 link.onclick = handler;
128 dojo.style(link, 'visibility', 'hidden');
132 this.setPrev = function(handler) {
133 var link = dojo.byId('acq-lit-prev');
135 dojo.style(link, 'visibility', 'visible');
136 link.onclick = handler;
138 dojo.style(link, 'visibility', 'hidden');
142 this.show = function(div) {
143 openils.Util.hide('acq-lit-table-div');
144 openils.Util.hide('acq-lit-info-div');
145 openils.Util.hide('acq-lit-li-details');
146 openils.Util.hide('acq-lit-notes-div');
147 openils.Util.hide('acq-lit-real-copies-div');
150 openils.Util.show('acq-lit-table-div');
153 openils.Util.show('acq-lit-info-div');
156 openils.Util.show('acq-lit-li-details');
159 openils.Util.show('acq-lit-real-copies-div');
162 openils.Util.show('acq-lit-notes-div');
166 openils.Util.show(div);
170 this.hide = function() {
174 this.toggleSelect = function() {
176 dojo.forEach(self.selectors, function(i){i.checked = false});
178 dojo.forEach(self.selectors, function(i){i.checked = true});
179 self.toggleState = !self.toggleState;
183 /** @param all If true, assume all are selected */
184 this.getSelected = function(all) {
186 var indices = {}; /* use to uniqify. needed in paging situations. */
187 dojo.forEach(self.selectors,
190 indices[i.parentNode.parentNode.getAttribute('li')] = true;
193 return openils.Util.objectProperties(indices).map(
194 function(liId) { return self.liCache[liId]; }
198 this.setRowAttr = function(td, liWrapper, field, type) {
199 var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
200 td.appendChild(document.createTextNode(val));
203 this.setClaimPolicyControl = function(li, row) {
204 if (!self.claimPolicyPicker) {
205 self.claimPolicyPicker = true; /* prevents a race condition */
206 new openils.widget.AutoFieldWidget({
207 "parentNode": "acq-lit-li-claim-policy",
209 "selfReference": true,
210 "dijitArgs": {"required": true}
211 }).build(function(w) { self.claimPolicyPicker = w; });
214 if (!row) row = this._findLiRow(li);
216 var actViewPolicy = nodeByName("action_view_claim_policy", row);
217 if (li.claim_policy())
218 actViewPolicy.innerHTML = localeStrings.CHANGE_CLAIM_POLICY;
220 if (!actViewPolicy.onclick) {
221 actViewPolicy.onclick = function() {
222 if (li.claim_policy())
223 self.claimPolicyPicker.attr("value", li.claim_policy());
224 liClaimPolicyDialog.show();
225 liClaimPolicySave.onClick = function() {
226 self.changeClaimPolicy(
227 [li], self.claimPolicyPicker.attr("value"),
229 self.setClaimPolicyControl(li, row);
230 liClaimPolicyDialog.hide();
238 this.fetchClaimInfo = function(liId, force, callback, row) {
240 liId, function(full) {
241 self.liCache[full.id()] = full;
242 self.checkClaimEligibility(full, callback, row);
248 * Inserts a single lineitem into the growing table of lineitems
249 * @param {Object} li The lineitem object to insert
251 this.addLineitem = function(li, skip_final_placement) {
252 this.liCache[li.id()] = li;
254 // sort the lineitem notes on edit_time
255 if(!li.lineitem_notes()) li.lineitem_notes([]);
257 var liWrapper = new openils.acq.Lineitem({lineitem:li});
258 var row = self.rowTemplate.cloneNode(true);
259 row.setAttribute('li', li.id());
260 var tds = dojo.query('[attr]', row);
261 dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
262 dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
265 liWrapper.findAttr("isbn", "lineitem_marc_attr_definition") ||
266 liWrapper.findAttr("upc", "lineitem_marc_attr_definition");
268 // XXX media prefix for added content
270 nodeByName("jacket", row).setAttribute(
271 "src", "/opac/extras/ac/jacket/small/" + identifier
275 nodeByName("liid", row).innerHTML += li.id();
278 openils.Util.show(nodeByName('catalog', row), 'inline');
279 nodeByName("catalog_link", row).onclick = this.generateMakeRecTab(li.eg_bib_id());
281 openils.Util.show(nodeByName('link_to_catalog', row), 'inline');
282 nodeByName("link_to_catalog_link", row).onclick = function() { self.drawBibFinder(li) };
285 nodeByName("worksheet_link", row).href =
286 oilsBasePath + "/acq/lineitem/worksheet/" + li.id();
288 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
289 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
290 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
292 if (!this.skipInitialEligibilityCheck)
293 this.fetchClaimInfo(li.id(), false, null, row);
295 this.updateLiNotesCount(li, row);
297 this.setClaimPolicyControl(li, row);
299 // show which PO this lineitem is a member of
300 if(li.purchase_order() && !this.isPO) {
302 this.poCache[li.purchase_order()] =
303 this.poCache[li.purchase_order()] ||
304 fieldmapper.standardRequest(
305 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
307 this.authtoken, li.purchase_order(), {
308 "flesh_price_summary": true,
309 "flesh_lineitem_count": true
312 if(po && !this.isMeta) {
313 openils.Util.show(nodeByName('po', row), 'inline');
314 var link = nodeByName('po_link', row);
315 link.setAttribute('href', oilsBasePath + '/acq/po/view/' + li.purchase_order());
316 link.innerHTML += po.name();
320 // show which picklist this lineitem is a member of
321 if(li.picklist() && (this.isPO || this.isMeta || this.isUni)) {
323 this.plCache[li.picklist()] =
324 this.plCache[li.picklist()] ||
325 fieldmapper.standardRequest(
326 ['open-ils.acq', 'open-ils.acq.picklist.retrieve.authoritative'],
327 {params: [this.authtoken, li.picklist()]});
329 if (pl.name() == "") {
330 openils.Util.show(nodeByName("bib_origin", row), "inline");
334 openils.Util.show(nodeByName('pl', row), 'inline');
335 var link = nodeByName('pl_link', row);
336 link.setAttribute('href', oilsBasePath + '/acq/picklist/view/' + li.picklist());
337 link.innerHTML += pl.name();
342 var countNode = nodeByName('count', row);
343 var count = li.item_count() || 0;
344 if (typeof(this._copy_count_cb) == "function") {
345 this._copy_count_cb(li.id(), count);
347 countNode.innerHTML = count;
348 countNode.id = 'acq-lit-copy-count-label-' + li.id();
351 var priceInput = dojo.query('[name=price]', row)[0];
352 priceInput.value = li.estimated_unit_price() || '';
353 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
355 // show either "mark received" or "unreceive" as appropriate
356 this.updateLiState(li, row);
358 if (!skip_final_placement) {
359 self.tbody.appendChild(row);
360 self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
366 this._liCountClaims = function(li) {
368 for (var i = 0; i < li.lineitem_details().length; i++)
369 total += li.lineitem_details()[i].claims().length;
373 this._findLiRow = function(li) {
374 return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
377 this.reconsiderClaimControl = function(li, row) {
378 var option = nodeByName("action_manage_claims", row);
379 var eligible = this.claimEligibleLidByLi[li.id()].length;
380 var count = this._liCountClaims(li);
381 if (!row) row = this._findLiRow(li);
383 option.disabled = !(count || eligible);
385 dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
386 option.onclick = function() { self.claimDialog.show(li); };
389 this.clearEligibility = function(li) {
390 this.claimEligibleLidByLi[li.id()] = [];
392 if (li.lineitem_details()) {
393 li.lineitem_details().forEach(
394 function(lid) { delete self.claimEligibleLid[lid.id()]; }
398 if (this.copyCache) {
400 for (var k in this.copyCache) {
401 if (this.copyCache[k].lineitem() == li.id())
405 function(k) { delete self.claimEligibleLid[k]; }
410 this.checkClaimEligibility = function(li, callback, row) {
411 this.clearEligibility(li);
412 fieldmapper.standardRequest(
413 ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
414 "params": [openils.User.authtoken, {"lineitem": li.id()}],
416 "onresponse": function(r) {
417 if (r = openils.Util.readResponse(r)) {
418 self.claimEligibleLidByLi[li.id()].push(
421 self.claimEligibleLid[r.lineitem_detail()] = true;
424 "oncomplete": function() {
425 self.reconsiderClaimControl(li, row);
426 if (typeof(callback) == "function")
433 this.updateLiNotesCount = function(li, row) {
434 if (!row) row = this._findLiRow(li);
436 var has_notes = (li.lineitem_notes().filter(
437 function(o) { return Boolean (o.alert_text()); }
440 /* U+2691 is the code point for a filled-in flag character */
441 nodeByName("notes_alert_flag", row).innerHTML =
442 has_notes ? "⚑" : "";
443 nodeByName("noteslink", row).style.fontStyle =
444 has_notes ? "italic" : "normal";
445 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
448 /* XXX NOT related to _updateLiState(). rethink */
449 this.updateLiState = function(li, row) {
450 if (!row) row = this._findLiRow(li);
452 var actReceive = nodeByName("action_mark_recv", row);
453 var actUnRecv = nodeByName("action_mark_unrecv", row);
454 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
455 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
457 var actNewInvoice = nodeByName('action_new_invoice', row);
458 var actLinkInvoice = nodeByName('action_link_invoice', row);
459 var actViewInvoice = nodeByName('action_view_invoice', row);
461 nodeByName('action_view_history', row).onclick =
462 function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
464 var state_cell = nodeByName("li_state", row);
466 if (li.state() == "cancelled") {
467 if (typeof li.cancel_reason() == "object") {
468 var holds_state = dojo.create(
470 "style": "border-bottom: 1px dashed #000;",
471 "innerHTML": li.state()
472 }, state_cell, "only"
476 "label": "<em>" + li.cancel_reason().label() +
477 "</em><br />" + li.cancel_reason().description(),
478 "connectId": [holds_state]
479 }, dojo.create("span", null, state_cell, "last")
482 state_cell.innerHTML = li.state(); // TODO i18n state labels
485 state_cell.innerHTML = li.state(); // TODO i18n state labels
489 /* handle row coloring for based on LI state */
490 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
491 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
493 /* handle links that appear/disappear based on whether LI is received */
497 actNewInvoice.onclick = function() {
498 location.href = oilsBasePath + '/acq/invoice/view?create=1&attach_li=' + li.id();
499 nodeByName("action_none", row).selected = true;
501 actLinkInvoice.onclick = function() {
502 if (!self.invoiceLinkDialogManager) {
503 self.invoiceLinkDialogManager =
504 new InvoiceLinkDialogManager("li");
506 self.invoiceLinkDialogManager.target = li;
507 acqLitLinkInvoiceDialog.show();
508 nodeByName("action_none", row).selected = true;
510 actViewInvoice.onclick = function() {
511 location.href = oilsBasePath +
512 "/acq/search/unified?so=" +
513 base64Encode({"jub":[{"id": li.id()}]}) +
515 nodeByName("action_none", row).selected = true;
518 actNewInvoice.disabled = false;
519 actLinkInvoice.disabled = false;
520 actViewInvoice.disabled = false;
524 actReceive.disabled = false;
525 actReceive.onclick = function() {
526 if (self.checkLiAlerts(li.id()))
527 self.issueReceive(li);
528 nodeByName("action_none", row).selected = true;
533 actUnRecv.disabled = false;
534 actUnRecv.onclick = function() {
535 if (confirm(localeStrings.UNRECEIVE_LI))
536 self.issueReceive(li, /* rollback */ true);
537 nodeByName("action_none", row).selected = true;
539 // TODO we should allow editing before receipt, in which case the
540 // test should be "if 1 or more real (acp) copies exist
541 actUpdateBarcodes.disabled = false;
542 actUpdateBarcodes.onclick = function() {
543 self.showRealCopyEditUI(li);
544 nodeByName("action_none", row).selected = true;
546 actHoldingsMaint.disabled = false;
547 actHoldingsMaint.onclick = self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
555 this._setAlertStore = function() {
556 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
558 "data": acqliat.toStoreData(
560 "acqliat", {"id": {"!=": null}}
565 acqLitAlertAlertText.setValue(); /* make the store "live" */
566 acqLitAlertAlertText._store_ready = true;
570 * Draws and shows the lineitem notes pane
572 this.drawLiNotes = function(li) {
575 if (!acqLitAlertAlertText._store_ready)
576 this._setAlertStore();
579 li.lineitem_notes().sort(
581 if(a.edit_time() < b.edit_time()) return 1;
587 while(this.liNotesTbody.childNodes[0])
588 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
591 acqLitCreateNoteSubmit.onClick = function() {
592 var value = acqLitCreateNoteText.attr('value');
594 var note = new fieldmapper.acqlin();
597 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
600 note.lineitem(li.id());
602 self.updateLiNotes(li, note);
603 acqLitCreateNoteVendorPublic.attr("checked", false);
604 acqLitCreateNoteText.attr("value", "");
607 acqLitCreateAlertSubmit.onClick = function() {
608 if (!acqLitAlertAlertText.item) {
609 alert(localeStrings.ALERT_UNSELECTED);
613 var alert_text = new fieldmapper.acqliat().fromStoreItem(
614 acqLitAlertAlertText.item
616 var value = acqLitAlertNoteValue.attr("value") || "";
618 var note = new fieldmapper.acqlin();
620 note.lineitem(li.id());
622 note.alert_text(alert_text);
624 self.updateLiNotes(li, note);
627 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
631 * Draws a single lineitem note in the notes pane
633 this.addLiNote = function(li, note) {
634 if(note.isdeleted()) return;
636 var row = self.liNotesRow.cloneNode(true);
637 nodeByName("value", row).innerHTML = note.value();
638 var alert_node = nodeByName("alert_code", row);
639 if (note.alert_text()) {
640 alert_node.innerHTML = note.alert_text().code();
641 if (note.alert_text().description()) {
644 "connectId": [alert_node],
645 "label": note.alert_text().description()
646 }, dojo.create("span", null, alert_node, "after")
651 if (openils.Util.isTrue(note.vendor_public()))
652 nodeByName("vendor_public", row).innerHTML =
653 localeStrings.VENDOR_PUBLIC;
655 nodeByName("delete", row).onclick = function() {
656 note.isdeleted(true);
657 self.liNotesTbody.removeChild(row);
658 self.updateLiNotes(li);
661 if(note.edit_time()) {
662 nodeByName("edit_time", row).innerHTML =
663 dojo.date.locale.format(
664 dojo.date.stamp.fromISOString(note.edit_time()),
665 {formatLength:'short'});
668 self.liNotesTbody.appendChild(row);
672 * Updates any new/changed/deleted notes on the server
674 this.updateLiNotes = function(li, newNote) {
680 notes = li.lineitem_notes().filter(
682 if(note.ischanged() || note.isnew() || note.isdeleted())
688 if(notes.length == 0) return;
689 progressDialog.show();
691 fieldmapper.standardRequest(
692 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
694 params : [this.authtoken, notes],
695 onresponse : function(r) {
696 var resp = openils.Util.readResponse(r);
701 // remove the old changed notes
703 dojo.forEach(li.lineitem_notes(),
705 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
709 li.lineitem_notes(list);
712 progressDialog.hide();
713 self.updateLiNotesCount(li);
714 self.drawLiNotes(li);
718 progressDialog.update(resp);
719 var newnote = resp.note;
721 if(!newnote.isdeleted()) {
722 newnote.isnew(false);
723 newnote.ischanged(false);
724 li.lineitem_notes().push(newnote);
731 this.updateLiPrice = function(input, li) {
733 var price = input.value;
734 if(Number(price) == Number(li.estimated_unit_price())) return;
736 fieldmapper.standardRequest(
737 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
738 { async : false, // redundant w/ timeout
740 params : [this.authtoken, li.id(), price],
741 oncomplete : function(r) {
742 openils.Util.readResponse(r);
743 li.estimated_unit_price(price); // update local copy
749 this.removeLineitem = function(liId) {
750 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
751 delete this.liCache[liId];
752 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
755 this.drawInfo = function(liId) {
756 if (!this._isRelatedViewer) {
757 var d = dojo.byId("acq-lit-info-related");
758 if (!this.relCache[liId]) {
759 fieldmapper.standardRequest(
762 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
765 "params": [openils.User.authtoken, liId],
766 "onresponse": function(r) {
767 self.relCache[liId] = openils.Util.readResponse(r);
768 nodeByName("related_number", d).innerHTML =
771 self.relCache[liId] >1 ? "show" : "hide"
777 nodeByName("related_number", d).innerHTML = this.relCache[liId];
778 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
783 openils.acq.Lineitem.fetchAttrDefs(
785 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
790 this._fetchLineitem = function(liId, handler, force) {
792 var li = this.liCache[liId];
793 if(li && li.marc() && li.lineitem_details() && !force)
796 fieldmapper.standardRequest(
797 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
800 params: [self.authtoken, liId, {
802 flesh_cancel_reason: true,
803 flesh_li_details: true,
805 flesh_fund_debit: true }],
807 oncomplete: function(r) {
808 var li = openils.Util.readResponse(r);
809 self.liCache[liId] = li;
816 this._drawInfo = function(li) {
818 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
821 openils.Util.hide('acq-lit-marc-order-record-label');
822 openils.Util.hide(acqLitEditOrderMarc.domNode);
823 openils.Util.show('acq-lit-marc-real-record-label');
825 openils.Util.show('acq-lit-marc-order-record-label');
826 openils.Util.show(acqLitEditOrderMarc.domNode);
827 openils.Util.hide('acq-lit-marc-real-record-label');
830 this.drawMarcHTML(li);
831 this.infoTbody = dojo.byId('acq-lit-info-tbody');
834 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
835 while(this.infoTbody.childNodes[0])
836 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
838 for(var i = 0; i < li.attributes().length; i++) {
839 var attr = li.attributes()[i];
840 var row = this.infoRow.cloneNode(true);
842 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
843 var name = openils.acq.Lineitem.attrDefs[type].filter(
845 return (a.code() == attr.attr_name());
847 ).pop().description();
849 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
850 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
851 this.infoTbody.appendChild(row);
854 if (!this._isRelatedViewer) {
855 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
856 oilsBasePath + "/acq/lineitem/related/" + li.id();
861 this.generateMakeRecTab = function(bib_id,default_view, row) {
865 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
868 show_nav_buttons : true,
869 show_print_button : true,
870 opac_url : xulG.url_prefix(xulG.urls.opac_rdetail + '?r=' + bib_id),
871 default_view : default_view
875 if(row) nodeByName("action_none", row).selected = true;
879 this.drawMarcHTML = function(li) {
880 var params = [null, true, li.marc()];
882 params = [li.eg_bib_id(), true];
884 fieldmapper.standardRequest(
885 ['open-ils.search', 'open-ils.search.biblio.record.html'],
888 oncomplete: function(r) {
889 dojo.byId('acq-lit-marc-div').innerHTML =
890 openils.Util.readResponse(r);
896 this.drawCopies = function(liId, force_fetch) {
897 if (typeof force_fetch == "undefined")
903 this.copyWidgetCache = {};
904 this.oldCopyWidgetCache = {};
905 this.virtDfaCounts = {};
906 this.realDfaCache = {};
909 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
910 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
911 acqLitCopyCountInput.attr('value', '0');
913 while(this.copyTbody.childNodes[0])
914 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
916 this._drawBatchCopyWidgets();
918 this._drawDistribApplied(liId);
920 this._fetchDistribFormulas(
922 openils.acq.Lineitem.fetchAttrDefs(
924 self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch);
931 this._saveDistribAppliedTemplates = function() {
932 if (!this._appliedDistribTemplate) {
933 this._appliedDistribTemplate =
934 dojo.byId("acq-lit-distrib-applied-tbody").
935 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
936 dojo.attr(this._appliedDistribTemplate, "id");
940 this._drawDistribApplied = function(liId) {
941 /* Build this table while hidden to prevent rendering artifacts */
942 openils.Util.hide("acq-lit-distrib-applied-tbody");
944 this._saveDistribAppliedTemplates();
946 /* Remove any rows in the table from previous populations */
947 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
948 forEach(dojo.destroy);
950 /* Unregister all dijits previously created (for some reason this isn't
951 * covered by the above destroy calls). */
952 dijit.registry.forEach(
953 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
956 /* Populate the table with our liId */
958 fieldmapper.standardRequest(
960 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
963 "params": [self.authtoken, liId],
964 "onresponse": function(r) {
965 var dfa = openils.Util.readResponse(r);
968 self.realDfaCache[dfa.id()] = dfa;
969 self._drawDistribAppliedUnit(dfa);
972 "oncomplete": function() {
973 /* Reveal built table */
976 "acq-lit-distrib-applied-tbody", "table-row-group"
984 this._drawDistribAppliedUnit = function(dfa) {
986 var row = dojo.query(
987 'tr[formula="' + dfa.formula().id() + '"]',
988 "acq-lit-distrib-applied-tbody"
993 row = dojo.clone(this._appliedDistribTemplate);
994 dojo.attr(row, "formula", dfa.formula().id());
995 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
998 var td = dojo.query("td", row)[0];
1000 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1001 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1004 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1006 new dijit.form.Button(
1008 "onClick": function() {
1009 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1010 self.deleteDfa(dfa);
1013 /* XXX I /cannot/ make the following work in as a CSS class
1014 * for some reason. So frustrating... */
1015 "style": function(id) {
1017 "font-weight: bold; color: #c00;" :
1019 }(dfa.id()) + "margin: 0 6px;display: inline;"
1020 }, "dfa-button-" + dfa.id()
1024 "connectId": ["dfa-button-" + dfa.id()],
1025 "label": dojo.string.substitute(
1026 localeStrings.DFA_TIP, dfa.id() > 0 ? [
1027 openils.User.formalName(dfa.creator()),
1028 dojo.date.locale.format(
1029 dojo.date.stamp.fromISOString(dfa.create_time()),
1030 {"formatLength":"short"}
1032 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
1034 }, "dfa-tip-" + dfa.id()
1038 this.deleteDfa = function(dfa) {
1039 if (dfa.id() > 0) { /* real */
1040 this.pcrud.eliminate(
1043 "oncomplete": function() {
1044 self._removeDistribApplied(dfa.id());
1045 delete self.realDfaCache[dfa.id()];
1049 } else { /* virtual */
1050 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
1051 this.virtDfaCounts[dfa.formula().id()] = 0;
1052 /* hasn't been saved yet, so no need to do anything server side */
1053 this._removeDistribApplied(dfa.id());
1058 this._removeDistribApplied = function(dfaId) {
1059 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
1060 dijit.registry.forEach(
1061 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
1063 this._removeDistribAppliedEmptyRows();
1066 this._removeAllDistribAppliedVirtual = function() {
1067 /* Unregister dijits */
1068 dijit.registry.forEach(
1069 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
1071 this._removeDistribAppliedEmptyRows();
1074 this._removeDistribAppliedEmptyRows = function() {
1075 /* Remove any rows with no DFA at all */
1076 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
1078 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
1084 * Insert a new row into the distribution formula selection form
1086 this._addDistribFormulaRow = function() {
1089 if (!self.distribForms) {
1090 // no formulas, hide the form
1091 openils.Util.hide('acq-lit-distrib-formula-tbody');
1095 if(!this.distribFormulaTemplate)
1096 this.distribFormulaTemplate =
1097 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
1099 var row = this.distribFormulaTemplate.cloneNode(true);
1100 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
1102 this.dfSelector = new dijit.form.FilteringSelect(
1103 {"labelAttr": "dynLabel", "labelType": "html"},
1104 nodeByName("selector", row)
1106 this._updateFormulaStore();
1107 this.dfSelector.fetchProperties =
1108 {"sort": [{"attribute": "use_count", "descending": true}]};
1110 var apply = new dijit.form.Button(
1111 {"label": localeStrings.APPLY},
1112 nodeByName('set_button', row)
1115 var reset = new dijit.form.Button(
1116 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
1117 nodeByName("reset_button", row)
1120 dojo.connect(apply, 'onClick',
1122 var form_id = self.dfSelector.attr("value");
1123 if(!form_id) return;
1124 self._applyDistribFormula(form_id);
1125 reset.attr("disabled", false);
1129 dojo.connect(reset, 'onClick',
1131 self.restoreCopyFieldsBeforeDF();
1132 self.virtDfaCounts = {};
1133 self.virtDfaId = -1;
1135 self._updateFormulaStore();
1136 self._removeAllDistribAppliedVirtual();
1137 reset.attr("disabled", "true");
1144 * Applies a distrib formula to the current set of copies
1146 this._applyDistribFormula = function(formula) {
1147 if(!formula) return;
1149 formula = this.distribForms.filter(
1150 function(form) { return form.id() == formula; }
1153 var copyRows = dojo.query('tr', self.copyTbody);
1155 if (this.dfeOffset >= copyRows.length) {
1156 alert(localeStrings.OUT_OF_COPIES);
1160 var entries_applied = 0;
1162 var rowIndex = this.dfeOffset;
1163 rowIndex < copyRows.length;
1167 var row = copyRows[rowIndex];
1168 var copy_id = row.getAttribute('copy_id');
1169 var copyWidgets = this.copyWidgetCache[copy_id];
1170 var entryIndex = this.dfeOffset;
1173 // find the correct entry for the current row
1174 dojo.forEach(formula.entries(),
1177 entryIndex += e.item_count();
1178 if(entryIndex > rowIndex)
1186 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
1187 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
1190 this.saveCopyFieldsBeforeDF(copy_id);
1191 this._copy_fields_for_acqdf.forEach(
1193 if(entry[field]()) {
1194 copyWidgets[field].attr('value', (entry[field]()));
1201 if (entries_applied) {
1202 this.virtDfaCounts[formula.id()] =
1203 ++(this.virtDfaCounts[formula.id()]) || 1;
1204 this._updateFormulaStore();
1205 this._drawDistribAppliedUnit(
1207 var dfa = new acqdfa();
1208 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
1211 this.dfeOffset += entries_applied;
1216 * This function updates the DF store for the dropdown so that use_counts
1217 * can reflect DF applications from this session before they're saved
1220 this._updateFormulaStore = function() {
1221 this.dfSelector.store = new dojo.data.ItemFileReadStore(
1223 "data": self._labelFormulasWithCounts(
1224 acqdf.toStoreData(self.distribForms)
1230 this.saveCopyFieldsBeforeDF = function(copy_id) {
1232 if (!this.oldCopyWidgetCache[copy_id]) {
1233 var copyWidgets = this.copyWidgetCache[copy_id];
1235 this.oldCopyWidgetCache[copy_id] = {};
1236 this._copy_fields_for_acqdf.forEach(
1238 self.oldCopyWidgetCache[copy_id][f] =
1239 copyWidgets[f].attr("value");
1245 this.restoreCopyFieldsBeforeDF = function() {
1247 for (var copy_id in this.oldCopyWidgetCache) {
1248 this._copy_fields_for_acqdf.forEach(
1250 self.copyWidgetCache[copy_id][f].attr(
1251 "value", self.oldCopyWidgetCache[copy_id][f]
1258 this._labelFormulasWithCounts = function(store_data) {
1259 for (var key in store_data.items) {
1260 var obj = store_data.items[key];
1261 obj.use_count = Number(obj.use_count); /* needed for sorting */
1263 if (this.virtDfaCounts[obj.id])
1264 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
1266 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
1267 obj.use_count + "]</span> " + obj.name;
1273 * This method formerly would not refetch the DF formulas if they'd been
1274 * loaded already, but now it always re-fetches, since use_count changes.
1276 this._fetchDistribFormulas = function(onload) {
1277 fieldmapper.standardRequest(
1279 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
1282 "params": [openils.User.authtoken],
1283 "oncomplete": function(r) {
1284 self.distribForms = openils.Util.readResponse(r);
1285 if(!self.distribForms || self.distribForms.length == 0) {
1286 self.distribForms = [];
1288 self._addDistribFormulaRow();
1295 this._drawBatchCopyWidgets = function() {
1296 var row = this.copyBatchRow;
1297 dojo.forEach(liDetailBatchFields,
1299 if(self.copyBatchRowDrawn) {
1300 self.copyBatchWidgets[field].attr('value', null);
1302 var widget = new openils.widget.AutoFieldWidget({
1305 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1306 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1307 searchFilter : (field == 'fund') ? {"active": "t"} : null,
1308 parentNode : dojo.query('[name='+field+']', row)[0],
1309 orgLimitPerms : ['CREATE_PICKLIST'],
1312 "labelType": (field == "fund") ? "html" : null
1314 noCache: (field == "fund"),
1319 if (field == "fund" && w.store)
1320 self._ensureCSSFundClasses(w.store);
1321 self.copyBatchWidgets[field] = w;
1324 if (field == "fund") {
1326 widget.widget, "onChange", function(val) {
1327 self._updateFundSelectorStyle(widget, val);
1334 this.copyBatchRowDrawn = true;
1337 this.batchCopyUpdate = function() {
1339 for(var k in this.copyWidgetCache) {
1340 var cache = this.copyWidgetCache[k];
1341 dojo.forEach(liDetailBatchFields, function(f) {
1342 var newval = self.copyBatchWidgets[f].attr('value');
1343 if(newval) cache[f].attr('value', newval);
1348 this._drawCopies = function(li) {
1351 // this button sets the total number of copies for a given lineitem
1352 acqLitAddCopyCount.onClick = function() {
1353 var count = acqLitCopyCountInput.attr('value');
1356 while(self.copyCount() < count)
1359 // delete rows if necessary
1360 var diff = self.copyCount() - count;
1362 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
1363 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
1364 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
1366 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1372 if(li.lineitem_details().length > 0) {
1373 dojo.forEach(li.lineitem_details(),
1375 self.addCopy(li, copy);
1383 this.copyCount = function() {
1385 for(var id in this.copyCache) {
1386 if(!this.copyCache[id].isdeleted())
1392 this.virtCopyId = -1;
1393 this.addCopy = function(li, copy) {
1394 var row = this.copyRow.cloneNode(true);
1395 this.copyTbody.appendChild(row);
1399 copy = new fieldmapper.acqlid();
1401 copy.id(this.virtCopyId--);
1402 copy.lineitem(li.id());
1405 this.copyCache[copy.id()] = copy;
1406 row.setAttribute('copy_id', copy.id());
1407 self.copyWidgetCache[copy.id()] = {};
1409 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1411 dojo.forEach(liDetailFields,
1414 if (field == "fund") {
1415 searchFilter = (copy.fund() ?
1416 {"-or": {"active": "t", "id": copy.fund()}} :
1419 searchFilter = null;
1422 var readOnly = false;
1424 // TODO: Add support for changing the owning_lib after real copies have been made.
1425 // owning_lib is order data as much as its item data
1426 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
1430 // TODO: add support for changing the fund after debits have been created
1431 // Note: invoicing allows the change
1432 if(copy.fund_debit() && field == 'fund') {
1436 var widget = new openils.widget.AutoFieldWidget({
1439 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1440 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1441 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1442 searchFilter : searchFilter,
1443 noCache: (field == "fund"),
1445 parentNode : dojo.query('[name='+field+']', row)[0],
1446 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
1447 readOnly : readOnly,
1448 orgDefaultsToWs : true
1452 // make sure we capture the value from any async widgets
1455 if (field == "fund" && w.store)
1456 self._ensureCSSFundClasses(w.store);
1459 copy[field](ww.getFormattedValue())
1461 self.copyWidgetCache[copy.id()][field] = w;
1463 dojo.connect(w, 'onChange',
1465 if (field == "fund")
1466 self._updateFundSelectorStyle(widget, val);
1468 if (!readOnly && (copy.isnew() || val != copy[field]())) {
1469 // prevent setting ischanged() automatically on widget load for existing copies
1470 copy[field](widget.getFormattedValue())
1471 copy.ischanged(true);
1480 this.updateLidState(copy, row);
1483 this._ensureCSSFundClass = function(id) {
1484 if (!this.fundStyleSheet) {
1486 "style", {"type": "text/css"},
1487 document.getElementsByTagName("head")[0], "last"
1489 this.fundStyleSheet = document.styleSheets[
1490 document.styleSheets.length - 1
1494 var cn = "fund_" + id;
1495 if (!this.haveFundClass[cn]) {
1496 fieldmapper.standardRequest(
1497 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
1499 "params": [openils.User.authtoken, id],
1501 "oncomplete": function(r) {
1502 r = openils.Util.readResponse(r);
1503 self.fundBalanceState[id] = r;
1505 if (r[0] /* stop */)
1506 style = fundStyles.stop;
1507 else if (r[1] /* warning */)
1508 style = fundStyles.warning;
1509 self.fundStyleSheet.insertRule(
1510 "." + cn + " { " + style + " }",
1511 self.fundStyleSheet.cssRules.length
1513 self.haveFundClass[cn] = true;
1520 this._ensureCSSFundClasses = function(store) {
1522 "query": {"id": "*"},
1523 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
1527 this._updateFundSelectorStyle = function(widget, fund_id) {
1528 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
1529 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
1532 this.updateLidState = function(copy, row) {
1533 if (typeof(row) == "undefined") {
1535 'tr[copy_id="' + copy.id() + '"]', this.copyTbody
1540 var recv_link = nodeByName("receive", row);
1541 var unrecv_link = nodeByName("unreceive", row);
1542 var del_link = nodeByName("delete", row);
1543 var cxl_link = nodeByName("cancel", row);
1544 var claim_link = nodeByName("claim", row);
1545 var cxl_reason_link = nodeByName("cancel_reason", row);
1547 if (copy.cancel_reason()) {
1548 openils.Util.hide(del_link.parentNode);
1549 openils.Util.hide(recv_link);
1550 openils.Util.hide(unrecv_link);
1551 openils.Util.hide(cxl_link);
1552 openils.Util.hide(claim_link);
1554 /* XXX the following may leak memory in a long lived table: dijits may not get destroyed... not positive. revisit. */
1555 var holds_reason = dojo.create(
1557 "style": "border-bottom: 1px dashed #000;",
1558 "innerHTML": "Cancelled" /* XXX [sic] and i18n */
1559 }, cxl_reason_link, "only"
1563 "label": "<em>" + copy.cancel_reason().label() +
1564 "</em><br />" + copy.cancel_reason().description(),
1565 "connectId": [holds_reason]
1566 }, dojo.create("span", null, cxl_reason_link, "last")
1568 openils.Util.show(cxl_reason_link, "inline");
1569 } else if (this.isPO) {
1570 /* Only using this in one place so far, but may want it for better
1571 * decisions on when to display certain controls. */
1572 var li_state = this.liCache[copy.lineitem()].state();
1574 openils.Util.hide(del_link.parentNode);
1575 openils.Util.hide(cxl_reason_link);
1577 /* Avoid showing (un)receive links, cancel links, for virt copies */
1578 if (copy.id() > 0) {
1579 if (copy.recv_time()) {
1580 openils.Util.hide(cxl_link);
1581 openils.Util.hide(recv_link);
1582 openils.Util.hide(claim_link);
1584 openils.Util.show(unrecv_link, "inline");
1585 unrecv_link.onclick = function() {
1586 if (confirm(localeStrings.UNRECEIVE_LID))
1587 self.issueReceive(copy, /* rollback */ true);
1590 openils.Util.hide(unrecv_link);
1592 if (this.claimEligibleLid[copy.id()]) {
1593 openils.Util.show(claim_link, "inline");
1594 claim_link.onclick = function() {
1595 self.claimDialog.show(
1596 self.liCache[copy.lineitem()], copy.id()
1600 openils.Util.hide(claim_link);
1603 openils.Util[li_state == "on-order" ? "show" : "hide"](
1606 openils.Util.show(cxl_link, "inline");
1607 recv_link.onclick = function() {
1608 if (self.checkLiAlerts(copy.lineitem()))
1609 self.issueReceive(copy);
1611 cxl_link.onclick = function() {
1612 self.cancelLid(copy.id());
1616 openils.Util.hide(cxl_link);
1617 openils.Util.hide(unrecv_link);
1618 openils.Util.hide(recv_link);
1619 openils.Util.hide(claim_link);
1622 openils.Util.hide(unrecv_link);
1623 openils.Util.hide(recv_link);
1624 openils.Util.hide(cxl_reason_link);
1625 openils.Util.hide(claim_link);
1627 del_link.onclick = function() { self.deleteCopy(row) };
1628 openils.Util.show(del_link.parentNode);
1632 this.cancelLid = function(lid_id) {
1633 lidCancelDialog._lid_id = lid_id;
1634 openils.Util.show(lidCancelDialog.domNode.parentNode);
1635 lidCancelDialog.show();
1636 if (!lidCancelDialog._prepared) {
1637 var widget = new openils.widget.AutoFieldWidget({
1638 "fmField": "cancel_reason",
1639 "fmClass": "acqlid",
1640 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
1641 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1646 acqLidCancelButton.onClick = function() {
1647 if (w.attr("value")) {
1648 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
1650 lidCancelDialog._lid_id,
1654 lidCancelDialog.hide();
1657 lidCancelDialog._prepared = true;
1663 this._cancelLid = function(lid_id, reason) {
1664 fieldmapper.standardRequest(
1665 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
1666 "params": [openils.User.authtoken, lid_id, reason],
1668 "onresponse": function(r) {
1669 if (r = openils.Util.readResponse(r)) {
1671 for (var id in r.lid) {
1672 /* actually this should only iterate once */
1673 self.copyCache[id].cancel_reason(
1674 r.lid[id].cancel_reason
1676 self.updateLidState(self.copyCache[id]);
1685 this._confirmAlert = function(li, lin) {
1687 dojo.string.substitute(
1688 localeStrings.CONFIRM_LI_ALERT, [
1689 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1690 "title", "lineitem_marc_attr_definition"
1692 lin.alert_text().code(),
1693 lin.alert_text().description() || "",
1700 this.checkLiAlerts = function(li_id) {
1701 var li = this.liCache[li_id];
1703 var alert_notes = li.lineitem_notes().filter(
1704 function(o) { return Boolean(o.alert_text()); }
1707 /* this is _intentionally_ not done in a call to forEach() ... */
1708 for (var i = 0; i < alert_notes.length; i++) {
1709 if (this.noteAcks[alert_notes[i].id()])
1711 else if (!this._confirmAlert(li, alert_notes[i]))
1714 this.noteAcks[alert_notes[i].id()] = true;
1720 this.deleteCopy = function(row) {
1721 var copy = this.copyCache[row.getAttribute('copy_id')];
1722 copy.isdeleted(true);
1724 delete this.copyCache[copy.id()];
1725 this.copyTbody.removeChild(row);
1728 this._virtDfaCountsAsList = function() {
1730 for (var key in this.virtDfaCounts) {
1731 for (var i = 0; i < this.virtDfaCounts[key]; i++)
1737 this.confirmBreachedCopyFunds = function(copies) {
1738 var stop = 0, warning = 0;
1742 var state = self.fundBalanceState[o.fund()];
1743 if (state[0] /* stop */)
1745 else if (state[1] /* warning */)
1752 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
1753 } else if (warning) {
1754 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
1759 this.saveCopyChanges = function(liId) {
1765 for(var id in this.copyCache) {
1766 var c = this.copyCache[id];
1767 if(!c.isdeleted()) total++;
1768 if(c.isnew() || c.ischanged() || c.isdeleted()) {
1769 if(c.id() < 0) c.id(null);
1775 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
1778 if (copies.length > 0) {
1779 if (!this.confirmBreachedCopyFunds(copies))
1782 if (typeof(this._copy_count_cb) == "function")
1783 this._copy_count_cb(liId, total);
1785 openils.Util.show("acq-lit-update-copies-progress");
1786 fieldmapper.standardRequest(
1787 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1789 params: [openils.User.authtoken, copies],
1790 onresponse: function(r) {
1791 var res = openils.Util.readResponse(r);
1792 litUpdateCopiesProgress.update(res);
1794 oncomplete: function() {
1795 self.drawCopies(liId, true /* force_fetch */);
1796 openils.Util.hide("acq-lit-update-copies-progress");
1802 var dfa_list = this._virtDfaCountsAsList();
1803 if (dfa_list.length > 0) {
1804 fieldmapper.standardRequest(
1806 "open-ils.acq.distribution_formula.record_application"],
1809 "params": [openils.User.authtoken, dfa_list, liId],
1810 "onresponse": function(r) {
1811 var res = openils.Util.readResponse(r);
1812 if (res && res.length < dfa_list.length)
1813 alert(localeStrings.DFA_NOT_ALL);
1817 this.virtDfaCounts = {};
1821 this._updateCreatePoPrepayCheckbox = function(prepay) {
1822 var prepay = openils.Util.isTrue(prepay);
1823 this._prepayRequiredByVendor = prepay;
1824 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
1827 this._confirmPoPrepaySituation = function() {
1828 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
1829 if (want_prepay != this._prepayRequiredByVendor) {
1832 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
1833 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
1840 this.applySelectedLiAction = function(action) {
1844 case 'delete_selected':
1845 this._deleteLiList(self.getSelected());
1848 case 'create_order':
1849 this._loadPOSelect();
1850 acqLitPoCreateDialog.show();
1853 case 'save_picklist':
1854 this._loadPLSelect();
1855 acqLitSavePlDialog.show();
1858 case 'selector_ready':
1860 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
1861 acqLitChangeLiStateDialog.show();
1869 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
1876 case 'rollback_receive_po':
1877 this.rollbackPoReceive();
1880 case 'create_assets':
1881 this.createAssets();
1884 case 'export_attr_list':
1885 this.chooseExportAttr();
1888 case 'batch_apply_funds':
1889 this.applyBatchLiFunds();
1892 case 'add_brief_record':
1894 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
1896 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
1900 case "cancel_lineitems":
1901 this.maybeCancelLineitems();
1904 case "change_claim_policy":
1905 var li_list = this.getSelected();
1906 this.claimPolicyPicker.attr("value", null);
1907 liClaimPolicyDialog.show();
1908 liClaimPolicySave.onClick = function() {
1909 self.changeClaimPolicy(
1911 self.claimPolicyPicker.attr("value"),
1914 function(li) { self.setClaimPolicyControl(li); }
1916 liClaimPolicyDialog.hide();
1924 this.changeClaimPolicy = function(li_list, value, callback) {
1926 function(li) { li.claim_policy(value); }
1928 fieldmapper.standardRequest(
1929 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
1930 "params": [openils.User.authtoken, li_list],
1932 "oncomplete": function(r) {
1933 r = openils.Util.readResponse(r);
1934 if (callback) callback(r);
1940 this.createAssets = function() {
1941 if(!this.isPO) return;
1942 if(!confirm(localeStrings.CREATE_PO_ASSETS_CONFIRM)) return;
1943 this.show('acq-lit-progress-numbers');
1945 fieldmapper.standardRequest(
1946 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
1948 params: [this.authtoken, this.isPO],
1949 onresponse: function(r) {
1950 var resp = openils.Util.readResponse(r);
1951 self._updateProgressNumbers(resp, true);
1957 this.maybeCancelLineitems = function() {
1958 openils.Util.show("acq-lit-cancel-reason", "inline");
1959 if (!acqLitCancelLineitemsButton._prepared) {
1960 var widget = new openils.widget.AutoFieldWidget({
1961 "fmField": "cancel_reason",
1963 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
1964 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1969 acqLitCancelLineitemsButton.onClick = function() {
1970 if (w.attr("value")) {
1971 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
1972 self._cancelLineitems(w.attr("value"));
1974 openils.Util.hide("acq-lit-cancel-reason");
1977 acqLitCancelLineitemsButton._prepared = true;
1983 this._cancelLineitems = function(reason) {
1984 var id_list = this.getSelected().map(function(o) { return o.id(); });
1985 fieldmapper.standardRequest(
1986 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
1987 "params": [openils.User.authtoken, id_list, reason],
1989 "onresponse": function(r) {
1990 if (r = openils.Util.readResponse(r)) {
1992 for (var id in r.li) {
1993 self.liCache[id].state(r.li[id].state);
1994 self.liCache[id].cancel_reason(
1995 r.li[id].cancel_reason
1997 self.updateLiState(self.liCache[id]);
2000 if (r.lid && self.copyCache) {
2001 for (var id in r.lid) {
2002 if (self.copyCache[id]) {
2003 self.copyCache[id].cancel_reason(
2004 r.lid[id].cancel_reason
2006 self.updateLidState(self.copyCache[id]);
2016 this.chooseExportAttr = function() {
2017 if (!acqLitExportAttrSelector._li_setup) {
2019 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
2021 "data": acqliad.toStoreData(
2023 "acqliad", {"code": li_exportable_attrs}
2028 acqLitExportAttrSelector.setValue();
2029 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
2030 acqLitExportAttrSelector._li_setup = true;
2032 openils.Util.show("acq-lit-export-attr-holder", "inline");
2035 this.exportAttrList = function() {
2036 var attr_def = acqLitExportAttrSelector.item;
2037 var li_list = this.getSelected();
2038 var value_list = li_list.map(
2040 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2041 attr_def.code, "lineitem_marc_attr_definition"
2044 ).filter(function(attr) { return Boolean(attr); });
2046 if (value_list.length > 0) {
2047 if (value_list.length < li_list.length) {
2049 dojo.string.substitute(
2050 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
2057 openils.XUL.contentToFileSaveDialog(
2058 value_list.join("\n"),
2059 localeStrings.EXPORT_SAVE_DIALOG_TITLE
2065 alert(dojo.string.substitute(
2066 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
2070 openils.Util.hide("acq-lit-export-attr-holder");
2073 this.printPO = function() {
2074 if(!this.isPO) return;
2075 progressDialog.show(true);
2076 fieldmapper.standardRequest(
2077 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
2079 params: [this.authtoken, this.isPO, 'html'],
2080 oncomplete: function(r) {
2081 progressDialog.hide();
2082 var evt = openils.Util.readResponse(r);
2083 if(evt && evt.template_output()) {
2084 openils.Util.printHtmlString(evt.template_output().data());
2092 this.receivePO = function() {
2093 if (!this.isPO) return;
2095 for (var id in this.liCache) {
2096 /* assumption: liCache reflects exactly the
2097 * set of LIs that belong to our PO */
2098 if (this.liCache[id].state() != "received" &&
2099 !this.checkLiAlerts(id)) return;
2102 this.show('acq-lit-progress-numbers');
2104 fieldmapper.standardRequest(
2105 ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
2107 params: [this.authtoken, this.isPO],
2108 onresponse : function(r) {
2109 var resp = openils.Util.readResponse(r);
2110 self._updateProgressNumbers(resp, true);
2116 this.issueReceive = function(obj, rollback) {
2117 /* (For now) there shall be no marking LI or LIDs (un)received
2118 * except from the actual "view PO" interface. */
2119 if (!this.isPO) return;
2122 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
2124 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
2126 progressDialog.show(true);
2127 fieldmapper.standardRequest(
2128 ["open-ils.acq", method], {
2130 "params": [this.authtoken, obj.id()],
2131 "onresponse": function(r) {
2132 if (r = openils.Util.readResponse(r)) {
2133 self.fetchClaimInfo(
2134 part == "lineitem" ? obj.id() : obj.lineitem(),
2136 function() { self.handleReceive(r); }
2138 progressDialog.hide();
2146 * Handles the responses from receive and rollback ML calls.
2148 this.handleReceive = function(resp) {
2151 for (var li_id in resp.li) {
2152 for (var key in resp.li[li_id])
2153 self.liCache[li_id][key](resp.li[li_id][key]);
2154 self.updateLiState(self.liCache[li_id]);
2158 if (typeof(self.poUpdateCallback) == "function")
2159 self.poUpdateCallback(resp.po);
2162 for (var lid_id in resp.lid) {
2163 for (var key in resp.lid[lid_id])
2164 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
2165 self.updateLidState(self.copyCache[lid_id]);
2171 this.rollbackPoReceive = function() {
2172 if(!this.isPO) return;
2173 if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
2174 this.show('acq-lit-progress-numbers');
2176 fieldmapper.standardRequest(
2177 ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
2179 params: [this.authtoken, this.isPO],
2180 onresponse : function(r) {
2181 var resp = openils.Util.readResponse(r);
2182 self._updateProgressNumbers(resp, true);
2188 this._updateProgressNumbers = function(resp, reloadOnComplete) {
2190 dojo.byId('acq-pl-lit-li-processed').innerHTML = resp.li;
2191 dojo.byId('acq-pl-lit-lid-processed').innerHTML = resp.lid;
2192 dojo.byId('acq-pl-lit-debits-processed').innerHTML = resp.debits_accrued;
2193 dojo.byId('acq-pl-lit-bibs-processed').innerHTML = resp.bibs;
2194 dojo.byId('acq-pl-lit-indexed-processed').innerHTML = resp.indexed;
2195 dojo.byId('acq-pl-lit-copies-processed').innerHTML = resp.copies;
2196 if(resp.complete && reloadOnComplete)
2197 location.href = location.href;
2201 this._createPO = function(fields) {
2202 this.show('acq-lit-progress-numbers');
2203 var po = new fieldmapper.acqpo();
2204 po.provider(this.createPoProviderSelector.attr('value'));
2205 po.ordering_agency(this.createPoAgencySelector.attr('value'));
2206 po.prepayment_required(fields.prepayment_required[0] ? true : false);
2208 var selected = this.getSelected( (fields.create_from == 'all') );
2209 if(selected.length == 0) return;
2211 var max = selected.length * 3;
2214 fieldmapper.standardRequest(
2215 ['open-ils.acq', 'open-ils.acq.purchase_order.create'],
2218 openils.User.authtoken,
2221 lineitems : selected.map(function(li) { return li.id() }),
2222 create_assets : fields.create_assets[0],
2226 onresponse : function(r) {
2227 var resp = openils.Util.readResponse(r);
2228 self._updateProgressNumbers(resp);
2230 location.href = oilsBasePath + '/acq/po/view/' + resp.purchase_order.id();
2236 this.batchFundWidget = null;
2238 this.applyBatchLiFunds = function() {
2240 var liIds = this.getSelected().map(function(li) { return li.id(); });
2241 if(liIds.length == 0) return; // warn?
2244 batchFundUpdateDialog.show();
2246 if(!this.batchFundWidget) {
2247 this.batchFundWidget = new openils.widget.AutoFieldWidget({
2249 selfReference : true,
2250 labelFormat : fundLabelFormat,
2251 searchFormat : fundSearchFormat,
2252 searchFilter : {"active": "t"},
2253 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
2254 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2255 dijitArgs : { "required": true, "labelType": "html" },
2258 this.batchFundWidget.build();
2261 dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
2262 dojo.connect(batchFundUpdateSubmit, 'onClick',
2265 // TODO: call .dry_run first to test thresholds
2266 fieldmapper.standardRequest(
2267 ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
2270 openils.User.authtoken,
2272 self.batchFundWidget.widget.attr('value')
2274 oncomplete : function(r) {
2275 var resp = openils.Util.readResponse(r);
2277 location.href = location.href;
2286 this._deleteLiList = function(list, idx) {
2287 if(idx == null) idx = 0;
2288 if(idx >= list.length) return;
2289 var liId = list[idx].id();
2290 fieldmapper.standardRequest(
2291 ['open-ils.acq', 'open-ils.acq.lineitem.delete'],
2293 params: [openils.User.authtoken, liId],
2294 oncomplete: function(r) {
2295 self.removeLineitem(liId);
2296 self._deleteLiList(list, ++idx);
2302 this.editOrderMarc = function(li) {
2304 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
2305 to true in about:config */
2307 if(!openils.XUL.enableXPConnect()) return;
2309 if(openils.XUL.isXUL()) {
2310 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
2312 win = window.open('/xul/server/cat/marcedit.xul');
2316 record : {marc : li.marc(), "rtype": "bre"},
2318 label: 'Save Record', // XXX I18N
2319 func: function(xmlString) {
2321 fieldmapper.standardRequest(
2322 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
2324 params: [openils.User.authtoken, li],
2325 oncomplete: function(r) {
2326 openils.Util.readResponse(r);
2328 self.drawInfo(li.id())
2337 this._savePl = function(values) {
2339 var selected = this.getSelected( (values.which == 'all') );
2340 openils.Util.show('acq-lit-generic-progress');
2342 if(values.new_name) {
2343 openils.acq.Picklist.create(
2344 {name: values.new_name},
2346 self._updateLiList(id, selected, 0,
2348 location.href = oilsBasePath + '/acq/picklist/view/' + id;
2352 } else if(values.existing_pl) {
2353 // update lineitems to use an existing picklist
2354 self._updateLiList(values.existing_pl, selected, 0,
2356 location.href = oilsBasePath + '/acq/picklist/view/' + values.existing_pl;
2361 this._updateLiState = function(values, state) {
2363 var selected = this.getSelected( (values.which == 'all') );
2364 if(!selected.length) return;
2365 dojo.forEach(selected, function(li) {li.state(state);});
2366 self._updateLiList(null, selected, 0,
2367 // TODO consider inline updates for efficiency
2368 function() { location.href = location.href }
2372 this._updateLiList = function(pl, list, idx, oncomplete) {
2373 if(idx >= list.length) return oncomplete();
2375 if(pl != null) li.picklist(pl);
2376 litGenericProgress.update({maximum: list.length, progress: idx});
2377 new openils.acq.Lineitem({lineitem:li}).update(
2379 self._updateLiList(pl, list, ++idx, oncomplete);
2384 this._loadPOSelect = function() {
2385 if (!this.createPoProviderSelector) {
2386 var widget = new openils.widget.AutoFieldWidget({
2387 "fmField": "provider",
2389 "searchFilter": {"active": "t"},
2390 "parentNode": dojo.byId("acq-lit-po-provider"),
2392 "onChange": function() {
2394 self._updateCreatePoPrepayCheckbox(
2395 this.item.prepayment_required
2401 widget.build(function(w) { self.createPoProviderSelector = w; });
2404 if (!this.createPoAgencySelector) {
2405 var widget = new openils.widget.AutoFieldWidget({
2406 "fmField": "ordering_agency",
2408 "parentNode": dojo.byId("acq-lit-po-agency"),
2409 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2411 widget.build(function(w) { self.createPoAgencySelector = w; });
2415 this._loadPLSelect = function(preSel) {
2416 if(this._plSelectLoaded) return;
2418 function handleResponse(r) {
2419 plList.push(r.recv().content());
2421 var method = 'open-ils.acq.picklist.user.retrieve';
2422 fieldmapper.standardRequest(
2423 ['open-ils.acq', method],
2425 params: [this.authtoken],
2426 onresponse: handleResponse,
2427 oncomplete: function() {
2428 self._plSelectLoaded = true;
2429 acqLitAddExistingSelect.store =
2430 new dojo.data.ItemFileReadStore({data:acqpl.toStoreData(plList)});
2432 acqLitAddExistingSelect.setValue(preSel);
2438 this.showRealCopyEditUI = function(li) {
2443 this._fetchLineitem(li.id(),
2445 li = self.liCache[li.id()] = fullLi;
2449 id : li.lineitem_details().map(
2450 function(item) { return item.eg_copy_id() }
2454 oncomplete : function(r) {
2456 var r_list = openils.Util.readResponse( r );
2457 for (var i = 0; i < r_list.length; i++) {
2458 var copy = r_list[i];
2459 var volId = copy.call_number();
2460 var volume = self.volCache[volId];
2462 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2464 copy.call_number(volume);
2465 copyList.push(copy);
2468 // If we need to, we can pass in an update_copy function to handle the update instead of volume_item_creator
2469 xulG.volume_item_creator( { 'existing_copies' : copyList } );
2472 alert('error in oncomplete: ' + E);
2481 this.drawBibFinder = function(li) {
2484 var liWrapper = new openils.acq.Lineitem({lineitem:li});
2487 ['isbn', 'upc', 'issn', 'title', 'author'],
2489 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
2491 if(field == 'title' || field == 'author') {
2492 query += field +':' + val + ' ';
2494 query += 'identifier|' + field + ':' + val + ' ';
2501 oilsBasePath + '/acq/lineitem/findbib?query=' + escape(query),
2502 '', 'resizable,scrollbars=1');
2504 win.window.recordFound = function(bibId) {
2507 var attrs = li.attributes();
2508 li.attributes(null);
2509 li.eg_bib_id(bibId);
2511 fieldmapper.standardRequest(
2512 ["open-ils.acq", "open-ils.acq.lineitem.update"],
2514 "params": [openils.User.authtoken, li],
2516 "oncomplete": function(r) {
2517 if(openils.Util.readResponse(r)) {
2518 location.href = location.href;