1 dojo.require('dojo.date.locale');
2 dojo.require('dojo.date.stamp');
3 dojo.require('dijit.form.Button');
4 dojo.require('dijit.form.TextBox');
5 dojo.require('dijit.form.FilteringSelect');
6 dojo.require('dijit.form.Textarea');
7 dojo.require('dijit.Tooltip');
8 dojo.require('dijit.ProgressBar');
9 dojo.require('openils.acq.Lineitem');
10 dojo.require('openils.acq.PO');
11 dojo.require('openils.acq.Picklist');
12 dojo.require('openils.widget.AutoFieldWidget');
13 dojo.require('dojo.data.ItemFileReadStore');
14 dojo.require('openils.widget.ProgressDialog');
15 dojo.require('openils.PermaCrud');
16 dojo.require("openils.widget.PCrudAutocompleteBox");
18 dojo.requireLocalization('openils.acq', 'acq');
19 var localeStrings = dojo.i18n.getLocalization('openils.acq', 'acq');
20 const XUL_OPAC_WRAPPER = 'chrome://open_ils_staff_client/content/cat/opac.xul';
21 var li_exportable_attrs = ["issn", "isbn", "upc"];
23 var fundLabelFormat = [
24 '<span class="fund_${0}">${1} (${2})</span>', 'id', 'code', 'year'
26 var fundSearchFormat = ['${0} (${1})', 'code', 'year'];
28 function nodeByName(name, context) {
29 return dojo.query('[name='+name+']', context)[0];
32 // for caching linked users. e.g. lineitem_detail.receiver
35 var liDetailBatchFields = ['fund', 'owning_lib', 'location', 'collection_code', 'circ_modifier', 'cn_label'];
36 var liDetailFields = liDetailBatchFields.concat(['barcode', 'note']);
38 "stop": "color: #c00; font-weight: bold;",
39 "warning": "color: #c93;"
42 function AcqLiTable() {
49 this.haveFundClass = {}
50 this.fundBalanceState = {};
51 this.realDfaCache = {};
52 this.virtDfaCounts = {};
55 this.claimEligibleLidByLi = {};
56 this.claimEligibleLid = {};
57 this.toggleState = false;
58 this.tbody = dojo.byId('acq-lit-tbody');
61 this.authtoken = openils.User.authtoken;
62 this.pcrud = new openils.PermaCrud();
63 this.rowTemplate = this.tbody.removeChild(dojo.byId('acq-lit-row'));
64 this.copyTbody = dojo.byId('acq-lit-li-details-tbody');
65 this.copyRow = this.copyTbody.removeChild(dojo.byId('acq-lit-li-details-row'));
66 this.copyBatchRow = dojo.byId('acq-lit-li-details-batch-row');
67 this.copyBatchWidgets = {};
68 this.liNotesTbody = dojo.byId('acq-lit-notes-tbody');
69 this.liNotesRow = this.liNotesTbody.removeChild(dojo.byId('acq-lit-notes-row'));
70 this.realCopiesTbody = dojo.byId('acq-lit-real-copies-tbody');
71 this.realCopiesRow = this.realCopiesTbody.removeChild(dojo.byId('acq-lit-real-copies-row'));
72 this._copy_fields_for_acqdf = ['owning_lib', 'location'];
73 this.skipInitialEligibilityCheck = false;
74 this.claimDialog = new ClaimDialogManager(
75 liClaimDialog, finalClaimDialog, this.claimEligibleLidByLi,
76 function(li) { /* callback that fires when claims are made */
77 self.fetchClaimInfo(li.id(), /* force update */ true);
81 dojo.byId("acq-lit-li-actions-selector").onchange = function() {
82 self.applySelectedLiAction(this.options[this.selectedIndex].value);
83 this.selectedIndex = 0;
86 acqLitCreatePoSubmit.onClick = function() {
87 if (self._confirmPoPrepaySituation()) {
88 acqLitPoCreateDialog.hide();
89 self._createPO(acqLitPoCreateDialog.getValues());
95 acqLitSavePlButton.onClick = function() {
96 acqLitSavePlDialog.hide();
97 self._savePl(acqLitSavePlDialog.getValues());
100 acqLitCancelLiStateButton.onClick = function() {
101 acqLitChangeLiStateDialog.hide();
103 acqLitSaveLiStateButton.onClick = function() {
104 acqLitChangeLiStateDialog.hide();
105 self._updateLiState(acqLitChangeLiStateDialog.getValues(), acqLitChangeLiStateDialog.attr('state'));
109 dojo.byId('acq-lit-select-toggle').onclick = function(){self.toggleSelect()};
110 dojo.byId('acq-lit-info-back-button').onclick = function(){self.show('list')};
111 dojo.byId('acq-lit-copies-back-button').onclick = function(){self.show('list')};
112 dojo.byId('acq-lit-notes-back-button').onclick = function(){self.show('list')};
113 dojo.byId('acq-lit-real-copies-back-button').onclick = function(){self.show('list')};
115 this.reset = function(keep_selectors) {
116 while(self.tbody.childNodes[0])
117 self.tbody.removeChild(self.tbody.childNodes[0]);
125 this.setNext = function(handler) {
126 var link = dojo.byId('acq-lit-next');
128 dojo.style(link, 'visibility', 'visible');
129 link.onclick = handler;
131 dojo.style(link, 'visibility', 'hidden');
135 this.setPrev = function(handler) {
136 var link = dojo.byId('acq-lit-prev');
138 dojo.style(link, 'visibility', 'visible');
139 link.onclick = handler;
141 dojo.style(link, 'visibility', 'hidden');
145 this.show = function(div) {
146 openils.Util.hide('acq-lit-table-div');
147 openils.Util.hide('acq-lit-info-div');
148 openils.Util.hide('acq-lit-li-details');
149 openils.Util.hide('acq-lit-notes-div');
150 openils.Util.hide('acq-lit-real-copies-div');
153 openils.Util.show('acq-lit-table-div');
156 openils.Util.show('acq-lit-info-div');
159 openils.Util.show('acq-lit-li-details');
162 openils.Util.show('acq-lit-real-copies-div');
165 openils.Util.show('acq-lit-notes-div');
169 openils.Util.show(div);
173 this.hide = function() {
177 this.toggleSelect = function() {
179 dojo.forEach(self.selectors, function(i){i.checked = false});
181 dojo.forEach(self.selectors, function(i){i.checked = true});
182 self.toggleState = !self.toggleState;
186 /** @param all If true, assume all are selected */
187 this.getSelected = function(all) {
189 var indices = {}; /* use to uniqify. needed in paging situations. */
190 dojo.forEach(self.selectors,
193 indices[i.parentNode.parentNode.getAttribute('li')] = true;
196 return openils.Util.objectProperties(indices).map(
197 function(liId) { return self.liCache[liId]; }
201 this.setRowAttr = function(td, liWrapper, field, type) {
202 var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
203 td.appendChild(document.createTextNode(val));
206 this.setClaimPolicyControl = function(li, row) {
207 if (!self.claimPolicyPicker) {
208 self.claimPolicyPicker = true; /* prevents a race condition */
209 new openils.widget.AutoFieldWidget({
210 "parentNode": "acq-lit-li-claim-policy",
212 "selfReference": true,
213 "dijitArgs": {"required": true}
214 }).build(function(w) { self.claimPolicyPicker = w; });
217 if (!row) row = this._findLiRow(li);
219 var actViewPolicy = nodeByName("action_view_claim_policy", row);
220 if (li.claim_policy())
221 actViewPolicy.innerHTML = localeStrings.CHANGE_CLAIM_POLICY;
223 if (!actViewPolicy.onclick) {
224 actViewPolicy.onclick = function() {
225 if (li.claim_policy())
226 self.claimPolicyPicker.attr("value", li.claim_policy());
227 liClaimPolicyDialog.show();
228 liClaimPolicySave.onClick = function() {
229 self.changeClaimPolicy(
230 [li], self.claimPolicyPicker.attr("value"),
232 self.setClaimPolicyControl(li, row);
233 self.reconsiderClaimControl(li, row);
234 liClaimPolicyDialog.hide();
242 this.fetchClaimInfo = function(liId, force, callback, row) {
244 liId, function(full) {
245 self.liCache[full.id()] = full;
246 self.checkClaimEligibility(full, callback, row);
252 * Inserts a single lineitem into the growing table of lineitems
253 * @param {Object} li The lineitem object to insert
255 this.addLineitem = function(li, skip_final_placement) {
256 this.liCache[li.id()] = li;
258 // insert the row right away so that final order isn't
259 // dependent on how long subsequent async request take
260 // for a given line item
261 var row = self.rowTemplate.cloneNode(true);
262 if (!skip_final_placement) {
263 self.tbody.appendChild(row);
264 self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
267 // sort the lineitem notes on edit_time
268 if(!li.lineitem_notes()) li.lineitem_notes([]);
270 var liWrapper = new openils.acq.Lineitem({lineitem:li});
271 row.setAttribute('li', li.id());
272 var tds = dojo.query('[attr]', row);
273 dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
274 dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
277 liWrapper.findAttr("isbn", "lineitem_marc_attr_definition") ||
278 liWrapper.findAttr("upc", "lineitem_marc_attr_definition");
280 // XXX media prefix for added content
282 nodeByName("jacket", row).setAttribute(
283 "src", "/opac/extras/ac/jacket/small/" + identifier
287 nodeByName("liid", row).innerHTML += li.id();
290 openils.Util.show(nodeByName('catalog', row), 'inline');
291 nodeByName("catalog_link", row).onclick = this.generateMakeRecTab(li.eg_bib_id());
293 openils.Util.show(nodeByName('link_to_catalog', row), 'inline');
294 nodeByName("link_to_catalog_link", row).onclick = function() { self.drawBibFinder(li) };
297 nodeByName("worksheet_link", row).href =
298 oilsBasePath + "/acq/lineitem/worksheet/" + li.id();
300 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
301 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
302 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
304 if (!this.skipInitialEligibilityCheck)
308 function(full) { self.setClaimPolicyControl(full, row) },
312 this.updateLiNotesCount(li, row);
314 // show which PO this lineitem is a member of
315 if(li.purchase_order() && !this.isPO) {
317 this.poCache[li.purchase_order()] =
318 this.poCache[li.purchase_order()] ||
319 fieldmapper.standardRequest(
320 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
322 this.authtoken, li.purchase_order(), {
323 "flesh_price_summary": true,
324 "flesh_lineitem_count": true
327 if(po && !this.isMeta) {
328 openils.Util.show(nodeByName('po', row), 'inline');
329 var link = nodeByName('po_link', row);
330 link.setAttribute('href', oilsBasePath + '/acq/po/view/' + li.purchase_order());
331 link.innerHTML += po.name();
335 // show which picklist this lineitem is a member of
336 if(li.picklist() && (this.isPO || this.isMeta || this.isUni)) {
338 this.plCache[li.picklist()] =
339 this.plCache[li.picklist()] ||
340 fieldmapper.standardRequest(
341 ['open-ils.acq', 'open-ils.acq.picklist.retrieve.authoritative'],
342 {params: [this.authtoken, li.picklist()]});
344 if (pl.name() == "") {
345 openils.Util.show(nodeByName("bib_origin", row), "inline");
349 openils.Util.show(nodeByName('pl', row), 'inline');
350 var link = nodeByName('pl_link', row);
351 link.setAttribute('href', oilsBasePath + '/acq/picklist/view/' + li.picklist());
352 link.innerHTML += pl.name();
357 var countNode = nodeByName('count', row);
358 var count = li.item_count() || 0;
359 if (typeof(this._copy_count_cb) == "function") {
360 this._copy_count_cb(li.id(), count);
362 countNode.innerHTML = count;
363 countNode.id = 'acq-lit-copy-count-label-' + li.id();
366 var priceInput = dojo.query('[name=price]', row)[0];
367 priceInput.value = li.estimated_unit_price() || '';
368 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
370 // show either "mark received" or "unreceive" as appropriate
371 this.updateLiState(li, row);
373 if (skip_final_placement) {
378 this._liCountClaims = function(li) {
380 for (var i = 0; i < li.lineitem_details().length; i++)
381 total += li.lineitem_details()[i].claims().length;
385 this._findLiRow = function(li) {
386 return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
389 this.reconsiderClaimControl = function(li, row) {
390 if (!row) row = this._findLiRow(li);
391 var option = nodeByName("action_manage_claims", row);
392 var eligible = this.claimEligibleLidByLi[li.id()].length;
393 var count = this._liCountClaims(li);
395 option.disabled = !(count || eligible);
397 dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
398 option.onclick = function() { self.claimDialog.show(li); };
401 this.clearEligibility = function(li) {
402 this.claimEligibleLidByLi[li.id()] = [];
404 if (li.lineitem_details()) {
405 li.lineitem_details().forEach(
406 function(lid) { delete self.claimEligibleLid[lid.id()]; }
410 if (this.copyCache) {
412 for (var k in this.copyCache) {
413 if (this.copyCache[k].lineitem() == li.id())
417 function(k) { delete self.claimEligibleLid[k]; }
422 this.checkClaimEligibility = function(li, callback, row) {
423 /* Assume always eligible, i.e. from this interface we don't care about
424 * claim eligibility any more. this is where the user would force a
426 this.clearEligibility(li);
427 this.claimEligibleLidByLi[li.id()] = li.lineitem_details().map(
428 function(lid) { return lid.id(); }
430 li.lineitem_details().forEach(
431 function(lid) { self.claimEligibleLid[lid.id()] = true; }
433 this.reconsiderClaimControl(li, row);
434 if (callback) callback(li);
436 this.clearEligibility(li);
437 fieldmapper.standardRequest(
438 ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
439 "params": [openils.User.authtoken, {"lineitem": li.id()}],
441 "onresponse": function(r) {
442 if (r = openils.Util.readResponse(r)) {
443 self.claimEligibleLidByLi[li.id()].push(
446 self.claimEligibleLid[r.lineitem_detail()] = true;
449 "oncomplete": function() {
450 self.reconsiderClaimControl(li, row);
451 if (typeof(callback) == "function")
459 this.updateLiNotesCount = function(li, row) {
460 if (!row) row = this._findLiRow(li);
462 var has_notes = (li.lineitem_notes().filter(
463 function(o) { return Boolean (o.alert_text()); }
466 /* U+2691 is the code point for a filled-in flag character */
467 nodeByName("notes_alert_flag", row).innerHTML =
468 has_notes ? "⚑" : "";
469 nodeByName("noteslink", row).style.fontStyle =
470 has_notes ? "italic" : "normal";
471 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
474 /* XXX NOT related to _updateLiState(). rethink */
475 this.updateLiState = function(li, row) {
476 if (!row) row = this._findLiRow(li);
478 var actReceive = nodeByName("action_mark_recv", row);
479 var actUnRecv = nodeByName("action_mark_unrecv", row);
480 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
481 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
483 var actNewInvoice = nodeByName('action_new_invoice', row);
484 var actLinkInvoice = nodeByName('action_link_invoice', row);
485 var actViewInvoice = nodeByName('action_view_invoice', row);
487 nodeByName('action_view_history', row).onclick =
488 function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
490 var state_cell = nodeByName("li_state", row);
492 if (li.state() == "cancelled") {
493 if (typeof li.cancel_reason() == "object") {
494 var holds_state = dojo.create(
496 "style": "border-bottom: 1px dashed #000;",
497 "innerHTML": li.state()
498 }, state_cell, "only"
502 "label": "<em>" + li.cancel_reason().label() +
503 "</em><br />" + li.cancel_reason().description(),
504 "connectId": [holds_state]
505 }, dojo.create("span", null, state_cell, "last")
508 state_cell.innerHTML = li.state(); // TODO i18n state labels
511 state_cell.innerHTML = li.state(); // TODO i18n state labels
515 /* handle row coloring for based on LI state */
516 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
517 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
519 /* handle links that appear/disappear based on whether LI is received */
523 actNewInvoice.onclick = function() {
524 location.href = oilsBasePath + '/acq/invoice/view?create=1&attach_li=' + li.id();
525 nodeByName("action_none", row).selected = true;
527 actLinkInvoice.onclick = function() {
528 if (!self.invoiceLinkDialogManager) {
529 self.invoiceLinkDialogManager =
530 new InvoiceLinkDialogManager("li");
532 self.invoiceLinkDialogManager.target = li;
533 acqLitLinkInvoiceDialog.show();
534 nodeByName("action_none", row).selected = true;
536 actViewInvoice.onclick = function() {
537 location.href = oilsBasePath +
538 "/acq/search/unified?so=" +
539 base64Encode({"jub":[{"id": li.id()}]}) +
541 nodeByName("action_none", row).selected = true;
544 actNewInvoice.disabled = false;
545 actLinkInvoice.disabled = false;
546 actViewInvoice.disabled = false;
550 actReceive.disabled = false;
551 actReceive.onclick = function() {
552 if (self.checkLiAlerts(li.id()))
553 self.issueReceive(li);
554 nodeByName("action_none", row).selected = true;
559 actUnRecv.disabled = false;
560 actUnRecv.onclick = function() {
561 if (confirm(localeStrings.UNRECEIVE_LI))
562 self.issueReceive(li, /* rollback */ true);
563 nodeByName("action_none", row).selected = true;
565 // TODO we should allow editing before receipt, in which case the
566 // test should be "if 1 or more real (acp) copies exist
567 actUpdateBarcodes.disabled = false;
568 actUpdateBarcodes.onclick = function() {
569 self.showRealCopyEditUI(li);
570 nodeByName("action_none", row).selected = true;
572 actHoldingsMaint.disabled = false;
573 actHoldingsMaint.onclick = self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
581 this._setAlertStore = function() {
582 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
584 "data": acqliat.toStoreData(
586 "acqliat", {"id": {"!=": null}}
591 acqLitAlertAlertText.setValue(); /* make the store "live" */
592 acqLitAlertAlertText._store_ready = true;
596 * Draws and shows the lineitem notes pane
598 this.drawLiNotes = function(li) {
601 if (!acqLitAlertAlertText._store_ready)
602 this._setAlertStore();
605 li.lineitem_notes().sort(
607 if(a.edit_time() < b.edit_time()) return 1;
613 while(this.liNotesTbody.childNodes[0])
614 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
617 acqLitCreateNoteSubmit.onClick = function() {
618 var value = acqLitCreateNoteText.attr('value');
620 var note = new fieldmapper.acqlin();
623 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
626 note.lineitem(li.id());
628 self.updateLiNotes(li, note);
629 acqLitCreateNoteVendorPublic.attr("checked", false);
630 acqLitCreateNoteText.attr("value", "");
633 acqLitCreateAlertSubmit.onClick = function() {
634 if (!acqLitAlertAlertText.item) {
635 alert(localeStrings.ALERT_UNSELECTED);
639 var alert_text = new fieldmapper.acqliat().fromStoreItem(
640 acqLitAlertAlertText.item
642 var value = acqLitAlertNoteValue.attr("value") || "";
644 var note = new fieldmapper.acqlin();
646 note.lineitem(li.id());
648 note.alert_text(alert_text);
650 self.updateLiNotes(li, note);
653 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
657 * Draws a single lineitem note in the notes pane
659 this.addLiNote = function(li, note) {
660 if(note.isdeleted()) return;
662 var row = self.liNotesRow.cloneNode(true);
663 nodeByName("value", row).innerHTML = note.value();
664 var alert_node = nodeByName("alert_code", row);
665 if (note.alert_text()) {
666 alert_node.innerHTML = note.alert_text().code();
667 if (note.alert_text().description()) {
670 "connectId": [alert_node],
671 "label": note.alert_text().description()
672 }, dojo.create("span", null, alert_node, "after")
677 if (openils.Util.isTrue(note.vendor_public()))
678 nodeByName("vendor_public", row).innerHTML =
679 localeStrings.VENDOR_PUBLIC;
681 nodeByName("delete", row).onclick = function() {
682 note.isdeleted(true);
683 self.liNotesTbody.removeChild(row);
684 self.updateLiNotes(li);
687 if(note.edit_time()) {
688 nodeByName("edit_time", row).innerHTML =
689 dojo.date.locale.format(
690 dojo.date.stamp.fromISOString(note.edit_time()),
691 {formatLength:'short'});
694 self.liNotesTbody.appendChild(row);
698 * Updates any new/changed/deleted notes on the server
700 this.updateLiNotes = function(li, newNote) {
706 notes = li.lineitem_notes().filter(
708 if(note.ischanged() || note.isnew() || note.isdeleted())
714 if(notes.length == 0) return;
715 progressDialog.show();
717 fieldmapper.standardRequest(
718 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
720 params : [this.authtoken, notes],
721 onresponse : function(r) {
722 var resp = openils.Util.readResponse(r);
727 // remove the old changed notes
729 dojo.forEach(li.lineitem_notes(),
731 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
735 li.lineitem_notes(list);
738 progressDialog.hide();
739 self.updateLiNotesCount(li);
740 self.drawLiNotes(li);
744 progressDialog.update(resp);
745 var newnote = resp.note;
747 if(!newnote.isdeleted()) {
748 newnote.isnew(false);
749 newnote.ischanged(false);
750 li.lineitem_notes().push(newnote);
757 this.updateLiPrice = function(input, li) {
759 var price = input.value;
760 if(Number(price) == Number(li.estimated_unit_price())) return;
762 fieldmapper.standardRequest(
763 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
764 { async : false, // redundant w/ timeout
766 params : [this.authtoken, li.id(), price],
767 oncomplete : function(r) {
768 openils.Util.readResponse(r);
769 li.estimated_unit_price(price); // update local copy
775 this.removeLineitem = function(liId) {
776 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
777 delete this.liCache[liId];
778 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
781 this.drawInfo = function(liId) {
782 if (!this._isRelatedViewer) {
783 var d = dojo.byId("acq-lit-info-related");
784 if (!this.relCache[liId]) {
785 fieldmapper.standardRequest(
788 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
791 "params": [openils.User.authtoken, liId],
792 "onresponse": function(r) {
793 self.relCache[liId] = openils.Util.readResponse(r);
794 nodeByName("related_number", d).innerHTML =
797 self.relCache[liId] >1 ? "show" : "hide"
803 nodeByName("related_number", d).innerHTML = this.relCache[liId];
804 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
809 openils.acq.Lineitem.fetchAttrDefs(
811 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
816 this._fetchLineitem = function(liId, handler, force) {
818 var li = this.liCache[liId];
819 if(li && li.marc() && li.lineitem_details() && !force)
822 fieldmapper.standardRequest(
823 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
826 params: [self.authtoken, liId, {
828 flesh_cancel_reason: true,
829 flesh_li_details: true,
831 flesh_fund_debit: true }],
833 oncomplete: function(r) {
834 var li = openils.Util.readResponse(r);
835 self.liCache[liId] = li;
842 this._drawInfo = function(li) {
844 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
847 openils.Util.hide('acq-lit-marc-order-record-label');
848 openils.Util.hide(acqLitEditOrderMarc.domNode);
849 openils.Util.show('acq-lit-marc-real-record-label');
851 openils.Util.show('acq-lit-marc-order-record-label');
852 openils.Util.show(acqLitEditOrderMarc.domNode);
853 openils.Util.hide('acq-lit-marc-real-record-label');
856 this.drawMarcHTML(li);
857 this.infoTbody = dojo.byId('acq-lit-info-tbody');
860 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
861 while(this.infoTbody.childNodes[0])
862 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
864 for(var i = 0; i < li.attributes().length; i++) {
865 var attr = li.attributes()[i];
866 var row = this.infoRow.cloneNode(true);
868 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
869 var name = openils.acq.Lineitem.attrDefs[type].filter(
871 return (a.code() == attr.attr_name());
873 ).pop().description();
875 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
876 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
877 this.infoTbody.appendChild(row);
880 if (!this._isRelatedViewer) {
881 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
882 oilsBasePath + "/acq/lineitem/related/" + li.id();
887 this.generateMakeRecTab = function(bib_id,default_view, row) {
891 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
894 show_nav_buttons : true,
895 show_print_button : true,
896 opac_url : xulG.url_prefix(xulG.urls.opac_rdetail + '?r=' + bib_id),
897 default_view : default_view
901 if(row) nodeByName("action_none", row).selected = true;
905 this.drawMarcHTML = function(li) {
906 var params = [null, true, li.marc()];
908 params = [li.eg_bib_id(), true];
910 fieldmapper.standardRequest(
911 ['open-ils.search', 'open-ils.search.biblio.record.html'],
914 oncomplete: function(r) {
915 dojo.byId('acq-lit-marc-div').innerHTML =
916 openils.Util.readResponse(r);
922 this.drawCopies = function(liId, force_fetch) {
923 if (typeof force_fetch == "undefined")
926 openils.acq.Lineitem.fetchAndRender(liId, {},
928 dojo.byId('acq-lit-copies-li-summary').innerHTML = html;
935 this.copyWidgetCache = {};
936 this.oldCopyWidgetCache = {};
937 this.virtDfaCounts = {};
938 this.realDfaCache = {};
941 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
942 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
943 acqLitCopyCountInput.attr('value', '0');
945 while(this.copyTbody.childNodes[0])
946 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
948 this._drawBatchCopyWidgets();
950 this._drawDistribApplied(liId);
952 this._fetchDistribFormulas(
954 openils.acq.Lineitem.fetchAttrDefs(
956 self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch);
963 this._saveDistribAppliedTemplates = function() {
964 if (!this._appliedDistribTemplate) {
965 this._appliedDistribTemplate =
966 dojo.byId("acq-lit-distrib-applied-tbody").
967 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
968 dojo.attr(this._appliedDistribTemplate, "id");
972 this._drawDistribApplied = function(liId) {
973 /* Build this table while hidden to prevent rendering artifacts */
974 openils.Util.hide("acq-lit-distrib-applied-tbody");
976 this._saveDistribAppliedTemplates();
978 /* Remove any rows in the table from previous populations */
979 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
980 forEach(dojo.destroy);
982 /* Unregister all dijits previously created (for some reason this isn't
983 * covered by the above destroy calls). */
984 dijit.registry.forEach(
985 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
988 /* Populate the table with our liId */
990 fieldmapper.standardRequest(
992 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
995 "params": [self.authtoken, liId],
996 "onresponse": function(r) {
997 var dfa = openils.Util.readResponse(r);
1000 self.realDfaCache[dfa.id()] = dfa;
1001 self._drawDistribAppliedUnit(dfa);
1004 "oncomplete": function() {
1005 /* Reveal built table */
1008 "acq-lit-distrib-applied-tbody", "table-row-group"
1016 this._drawDistribAppliedUnit = function(dfa) {
1017 var new_row = false;
1018 var row = dojo.query(
1019 'tr[formula="' + dfa.formula().id() + '"]',
1020 "acq-lit-distrib-applied-tbody"
1025 row = dojo.clone(this._appliedDistribTemplate);
1026 dojo.attr(row, "formula", dfa.formula().id());
1027 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
1030 var td = dojo.query("td", row)[0];
1032 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1033 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1036 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1038 new dijit.form.Button(
1040 "onClick": function() {
1041 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1042 self.deleteDfa(dfa);
1045 /* XXX I /cannot/ make the following work in as a CSS class
1046 * for some reason. So frustrating... */
1047 "style": function(id) {
1049 "font-weight: bold; color: #c00;" :
1051 }(dfa.id()) + "margin: 0 6px;display: inline;"
1052 }, "dfa-button-" + dfa.id()
1056 "connectId": ["dfa-button-" + dfa.id()],
1057 "label": dojo.string.substitute(
1058 localeStrings.DFA_TIP, dfa.id() > 0 ? [
1059 openils.User.formalName(dfa.creator()),
1060 dojo.date.locale.format(
1061 dojo.date.stamp.fromISOString(dfa.create_time()),
1062 {"formatLength":"short"}
1064 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
1066 }, "dfa-tip-" + dfa.id()
1070 this.deleteDfa = function(dfa) {
1071 if (dfa.id() > 0) { /* real */
1072 this.pcrud.eliminate(
1075 "oncomplete": function() {
1076 self._removeDistribApplied(dfa.id());
1077 delete self.realDfaCache[dfa.id()];
1081 } else { /* virtual */
1082 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
1083 this.virtDfaCounts[dfa.formula().id()] = 0;
1084 /* hasn't been saved yet, so no need to do anything server side */
1085 this._removeDistribApplied(dfa.id());
1090 this._removeDistribApplied = function(dfaId) {
1091 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
1092 dijit.registry.forEach(
1093 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
1095 this._removeDistribAppliedEmptyRows();
1098 this._removeAllDistribAppliedVirtual = function() {
1099 /* Unregister dijits */
1100 dijit.registry.forEach(
1101 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
1103 this._removeDistribAppliedEmptyRows();
1106 this._removeDistribAppliedEmptyRows = function() {
1107 /* Remove any rows with no DFA at all */
1108 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
1110 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
1116 * Insert a new row into the distribution formula selection form
1118 this._addDistribFormulaRow = function() {
1121 if (!self.distribForms) {
1122 // no formulas, hide the form
1123 openils.Util.hide('acq-lit-distrib-formula-table');
1127 if(!this.distribFormulaTemplate)
1128 this.distribFormulaTemplate =
1129 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
1131 var row = this.distribFormulaTemplate.cloneNode(true);
1132 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
1134 this.dfSelector = new dijit.form.FilteringSelect(
1135 {"labelAttr": "dynLabel", "labelType": "html"},
1136 nodeByName("selector", row)
1138 this._updateFormulaStore();
1139 this.dfSelector.fetchProperties =
1140 {"sort": [{"attribute": "use_count", "descending": true}]};
1142 var apply = new dijit.form.Button(
1143 {"label": localeStrings.APPLY},
1144 nodeByName('set_button', row)
1147 var reset = new dijit.form.Button(
1148 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
1149 nodeByName("reset_button", row)
1152 dojo.connect(apply, 'onClick',
1154 var form_id = self.dfSelector.attr("value");
1155 if(!form_id) return;
1156 self._applyDistribFormula(form_id);
1157 reset.attr("disabled", false);
1161 dojo.connect(reset, 'onClick',
1163 self.restoreCopyFieldsBeforeDF();
1164 self.virtDfaCounts = {};
1165 self.virtDfaId = -1;
1167 self._updateFormulaStore();
1168 self._removeAllDistribAppliedVirtual();
1169 reset.attr("disabled", "true");
1176 * Applies a distrib formula to the current set of copies
1178 this._applyDistribFormula = function(formula) {
1179 if(!formula) return;
1181 formula = this.distribForms.filter(
1182 function(form) { return form.id() == formula; }
1185 var copyRows = dojo.query('tr', self.copyTbody);
1187 if (this.dfeOffset >= copyRows.length) {
1188 alert(localeStrings.OUT_OF_COPIES);
1192 var entries_applied = 0;
1194 var rowIndex = this.dfeOffset;
1195 rowIndex < copyRows.length;
1199 var row = copyRows[rowIndex];
1200 var copy_id = row.getAttribute('copy_id');
1201 var copyWidgets = this.copyWidgetCache[copy_id];
1202 var entryIndex = this.dfeOffset;
1205 // find the correct entry for the current row
1206 dojo.forEach(formula.entries(),
1209 entryIndex += e.item_count();
1210 if(entryIndex > rowIndex)
1218 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
1219 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
1222 this.saveCopyFieldsBeforeDF(copy_id);
1223 this._copy_fields_for_acqdf.forEach(
1225 if(entry[field]()) {
1226 copyWidgets[field].attr('value', (entry[field]()));
1233 if (entries_applied) {
1234 this.virtDfaCounts[formula.id()] =
1235 ++(this.virtDfaCounts[formula.id()]) || 1;
1236 this._updateFormulaStore();
1237 this._drawDistribAppliedUnit(
1239 var dfa = new acqdfa();
1240 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
1243 this.dfeOffset += entries_applied;
1248 * This function updates the DF store for the dropdown so that use_counts
1249 * can reflect DF applications from this session before they're saved
1252 this._updateFormulaStore = function() {
1253 this.dfSelector.store = new dojo.data.ItemFileReadStore(
1255 "data": self._labelFormulasWithCounts(
1256 acqdf.toStoreData(self.distribForms)
1262 this.saveCopyFieldsBeforeDF = function(copy_id) {
1264 if (!this.oldCopyWidgetCache[copy_id]) {
1265 var copyWidgets = this.copyWidgetCache[copy_id];
1267 this.oldCopyWidgetCache[copy_id] = {};
1268 this._copy_fields_for_acqdf.forEach(
1270 self.oldCopyWidgetCache[copy_id][f] =
1271 copyWidgets[f].attr("value");
1277 this.restoreCopyFieldsBeforeDF = function() {
1279 for (var copy_id in this.oldCopyWidgetCache) {
1280 this._copy_fields_for_acqdf.forEach(
1282 self.copyWidgetCache[copy_id][f].attr(
1283 "value", self.oldCopyWidgetCache[copy_id][f]
1290 this._labelFormulasWithCounts = function(store_data) {
1291 for (var key in store_data.items) {
1292 var obj = store_data.items[key];
1293 obj.use_count = Number(obj.use_count); /* needed for sorting */
1295 if (this.virtDfaCounts[obj.id])
1296 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
1298 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
1299 obj.use_count + "]</span> " + obj.name;
1305 * This method formerly would not refetch the DF formulas if they'd been
1306 * loaded already, but now it always re-fetches, since use_count changes.
1308 /** TODO: port distrib-formula selector to autofieldwidget+pcrud/dojo store */
1309 this._fetchDistribFormulas = function(onload) {
1310 fieldmapper.standardRequest(
1312 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
1315 "params": [openils.User.authtoken, 0, 500],
1316 "oncomplete": function(r) {
1317 self.distribForms = openils.Util.readResponse(r);
1318 if(!self.distribForms || self.distribForms.length == 0) {
1319 self.distribForms = [];
1321 self._addDistribFormulaRow();
1328 this._drawBatchCopyWidgets = function() {
1329 var row = this.copyBatchRow;
1330 dojo.forEach(liDetailBatchFields,
1332 if(self.copyBatchRowDrawn) {
1333 self.copyBatchWidgets[field].attr('value', null);
1335 var widget = new openils.widget.AutoFieldWidget({
1338 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1339 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1340 searchFilter : (field == 'fund') ? {"active": "t"} : null,
1341 parentNode : dojo.query('[name='+field+']', row)[0],
1342 orgLimitPerms : ['CREATE_PICKLIST'],
1345 "labelType": (field == "fund") ? "html" : null
1347 noCache: (field == "fund"),
1352 if (field == "fund" && w.store)
1353 self._ensureCSSFundClasses(w.store);
1354 self.copyBatchWidgets[field] = w;
1357 if (field == "fund") {
1359 widget.widget, "onChange", function(val) {
1360 self._updateFundSelectorStyle(widget, val);
1367 this.copyBatchRowDrawn = true;
1370 this.batchCopyUpdate = function() {
1372 for(var k in this.copyWidgetCache) {
1373 var cache = this.copyWidgetCache[k];
1374 dojo.forEach(liDetailBatchFields, function(f) {
1375 var newval = self.copyBatchWidgets[f].attr('value');
1376 if(newval) cache[f].attr('value', newval);
1381 this._drawCopies = function(li) {
1384 // this button sets the total number of copies for a given lineitem
1385 acqLitAddCopyCount.onClick = function() {
1386 var count = acqLitCopyCountInput.attr('value');
1389 while(self.copyCount() < count)
1392 // delete rows if necessary
1393 var diff = self.copyCount() - count;
1395 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
1396 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
1397 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
1399 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1405 if(li.lineitem_details().length > 0) {
1406 dojo.forEach(li.lineitem_details(),
1408 self.addCopy(li, copy);
1416 this.copyCount = function() {
1418 for(var id in this.copyCache) {
1419 if(!this.copyCache[id].isdeleted())
1425 this.virtCopyId = -1;
1426 this.addCopy = function(li, copy) {
1427 var row = this.copyRow.cloneNode(true);
1428 this.copyTbody.appendChild(row);
1432 copy = new fieldmapper.acqlid();
1434 copy.id(this.virtCopyId--);
1435 copy.lineitem(li.id());
1438 this.copyCache[copy.id()] = copy;
1439 row.setAttribute('copy_id', copy.id());
1440 self.copyWidgetCache[copy.id()] = {};
1442 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1444 var rcvr = copy.receiver();
1446 if (!userCache[rcvr]) {
1447 if(rcvr == openils.User.user.id()) {
1448 userCache[rcvr] = openils.User.user;
1450 userCache[rcvr] = fieldmapper.standardRequest(
1451 ['open-ils.actor', 'open-ils.actor.user.retrieve'],
1452 {params: [openils.User.authtoken, rcvr]}
1456 dojo.query('[name=receiver]', row)[0].innerHTML = userCache[rcvr].usrname();
1459 dojo.forEach(liDetailFields,
1462 if (field == "fund") {
1463 searchFilter = (copy.fund() ?
1464 {"-or": {"active": "t", "id": copy.fund()}} :
1467 searchFilter = null;
1470 var readOnly = false;
1472 // TODO: Add support for changing the owning_lib after real copies have been made.
1473 // owning_lib is order data as much as its item data
1474 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
1478 // TODO: add support for changing the fund after debits have been created
1479 // Note: invoicing allows the change
1480 if(copy.fund_debit() && field == 'fund') {
1485 var widget = new openils.widget.AutoFieldWidget({
1488 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1489 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1490 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1491 searchFilter : searchFilter,
1492 noCache: (field == "fund"),
1494 parentNode : dojo.query('[name='+field+']', row)[0],
1495 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
1496 readOnly : readOnly,
1497 orgDefaultsToWs : true
1501 // make sure we capture the value from any async widgets
1504 if (field == "fund" && w.store)
1505 self._ensureCSSFundClasses(w.store);
1508 copy[field](ww.getFormattedValue())
1510 self.copyWidgetCache[copy.id()][field] = w;
1512 dojo.connect(w, 'onChange',
1514 if (field == "fund")
1515 self._updateFundSelectorStyle(widget, val);
1517 if (!readOnly && (copy.isnew() || val != copy[field]())) {
1518 // prevent setting ischanged() automatically on widget load for existing copies
1519 copy[field](widget.getFormattedValue())
1520 copy.ischanged(true);
1529 this.updateLidState(copy, row);
1532 this._ensureCSSFundClass = function(id) {
1533 if (!this.fundStyleSheet) {
1535 "style", {"type": "text/css"},
1536 document.getElementsByTagName("head")[0], "last"
1538 this.fundStyleSheet = document.styleSheets[
1539 document.styleSheets.length - 1
1543 var cn = "fund_" + id;
1544 if (!this.haveFundClass[cn]) {
1545 fieldmapper.standardRequest(
1546 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
1548 "params": [openils.User.authtoken, id],
1550 "oncomplete": function(r) {
1551 r = openils.Util.readResponse(r);
1552 self.fundBalanceState[id] = r;
1554 if (r[0] /* stop */)
1555 style = fundStyles.stop;
1556 else if (r[1] /* warning */)
1557 style = fundStyles.warning;
1558 self.fundStyleSheet.insertRule(
1559 "." + cn + " { " + style + " }",
1560 self.fundStyleSheet.cssRules.length
1562 self.haveFundClass[cn] = true;
1569 this._ensureCSSFundClasses = function(store) {
1571 "query": {"id": "*"},
1572 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
1576 this._updateFundSelectorStyle = function(widget, fund_id) {
1577 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
1578 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
1581 this.updateLidState = function(copy, row) {
1582 if (typeof(row) == "undefined") {
1584 'tr[copy_id="' + copy.id() + '"]', this.copyTbody
1589 var recv_link = nodeByName("receive", row);
1590 var unrecv_link = nodeByName("unreceive", row);
1591 var del_link = nodeByName("delete", row);
1592 var cxl_link = nodeByName("cancel", row);
1593 var claim_link = nodeByName("claim", row);
1594 var cxl_reason_link = nodeByName("cancel_reason", row);
1596 if (copy.cancel_reason()) {
1597 openils.Util.hide(del_link.parentNode);
1598 openils.Util.hide(recv_link);
1599 openils.Util.hide(unrecv_link);
1600 openils.Util.hide(cxl_link);
1601 openils.Util.hide(claim_link);
1603 /* XXX the following may leak memory in a long lived table: dijits may not get destroyed... not positive. revisit. */
1604 var holds_reason = dojo.create(
1606 "style": "border-bottom: 1px dashed #000;",
1607 "innerHTML": "Cancelled" /* XXX [sic] and i18n */
1608 }, cxl_reason_link, "only"
1612 "label": "<em>" + copy.cancel_reason().label() +
1613 "</em><br />" + copy.cancel_reason().description(),
1614 "connectId": [holds_reason]
1615 }, dojo.create("span", null, cxl_reason_link, "last")
1617 openils.Util.show(cxl_reason_link, "inline");
1618 } else if (this.isPO) {
1619 /* Only using this in one place so far, but may want it for better
1620 * decisions on when to display certain controls. */
1621 var li_state = this.liCache[copy.lineitem()].state();
1623 openils.Util.hide(del_link.parentNode);
1624 openils.Util.hide(cxl_reason_link);
1626 /* Avoid showing (un)receive links, cancel links, for virt copies */
1627 if (copy.id() > 0) {
1628 if (copy.recv_time()) {
1629 openils.Util.hide(cxl_link);
1630 openils.Util.hide(recv_link);
1631 openils.Util.hide(claim_link);
1633 openils.Util.show(unrecv_link, "inline");
1634 unrecv_link.onclick = function() {
1635 if (confirm(localeStrings.UNRECEIVE_LID))
1636 self.issueReceive(copy, /* rollback */ true);
1639 openils.Util.hide(unrecv_link);
1641 if (this.claimEligibleLid[copy.id()]) {
1642 openils.Util.show(claim_link, "inline");
1643 claim_link.onclick = function() {
1644 self.claimDialog.show(
1645 self.liCache[copy.lineitem()], copy.id()
1649 openils.Util.hide(claim_link);
1652 openils.Util[li_state == "on-order" ? "show" : "hide"](
1655 openils.Util.show(cxl_link, "inline");
1656 recv_link.onclick = function() {
1657 if (self.checkLiAlerts(copy.lineitem()))
1658 self.issueReceive(copy);
1660 cxl_link.onclick = function() {
1661 self.cancelLid(copy.id());
1665 openils.Util.hide(cxl_link);
1666 openils.Util.hide(unrecv_link);
1667 openils.Util.hide(recv_link);
1668 openils.Util.hide(claim_link);
1671 openils.Util.hide(unrecv_link);
1672 openils.Util.hide(recv_link);
1673 openils.Util.hide(cxl_reason_link);
1674 openils.Util.hide(claim_link);
1676 del_link.onclick = function() { self.deleteCopy(row) };
1677 openils.Util.show(del_link.parentNode);
1681 this.cancelLid = function(lid_id) {
1682 lidCancelDialog._lid_id = lid_id;
1683 openils.Util.show(lidCancelDialog.domNode.parentNode);
1684 lidCancelDialog.show();
1685 if (!lidCancelDialog._prepared) {
1686 var widget = new openils.widget.AutoFieldWidget({
1687 "fmField": "cancel_reason",
1688 "fmClass": "acqlid",
1689 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
1690 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1695 acqLidCancelButton.onClick = function() {
1696 if (w.attr("value")) {
1697 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
1699 lidCancelDialog._lid_id,
1703 lidCancelDialog.hide();
1706 lidCancelDialog._prepared = true;
1712 this._cancelLid = function(lid_id, reason) {
1713 fieldmapper.standardRequest(
1714 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
1715 "params": [openils.User.authtoken, lid_id, reason],
1717 "onresponse": function(r) {
1718 if (r = openils.Util.readResponse(r)) {
1720 for (var id in r.lid) {
1721 /* actually this should only iterate once */
1722 self.copyCache[id].cancel_reason(
1723 r.lid[id].cancel_reason
1725 self.updateLidState(self.copyCache[id]);
1734 this._confirmAlert = function(li, lin) {
1736 dojo.string.substitute(
1737 localeStrings.CONFIRM_LI_ALERT, [
1738 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1739 "title", "lineitem_marc_attr_definition"
1741 lin.alert_text().code(),
1742 lin.alert_text().description() || "",
1749 this.checkLiAlerts = function(li_id) {
1750 var li = this.liCache[li_id];
1752 var alert_notes = li.lineitem_notes().filter(
1753 function(o) { return Boolean(o.alert_text()); }
1756 /* this is _intentionally_ not done in a call to forEach() ... */
1757 for (var i = 0; i < alert_notes.length; i++) {
1758 if (this.noteAcks[alert_notes[i].id()])
1760 else if (!this._confirmAlert(li, alert_notes[i]))
1763 this.noteAcks[alert_notes[i].id()] = true;
1769 this.deleteCopy = function(row) {
1770 var copy = this.copyCache[row.getAttribute('copy_id')];
1771 copy.isdeleted(true);
1773 delete this.copyCache[copy.id()];
1774 this.copyTbody.removeChild(row);
1777 this._virtDfaCountsAsList = function() {
1779 for (var key in this.virtDfaCounts) {
1780 for (var i = 0; i < this.virtDfaCounts[key]; i++)
1786 this.confirmBreachedCopyFunds = function(copies) {
1787 var stop = 0, warning = 0;
1791 var state = self.fundBalanceState[o.fund()];
1792 if (state[0] /* stop */)
1794 else if (state[1] /* warning */)
1801 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
1802 } else if (warning) {
1803 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
1808 this.saveCopyChanges = function(liId) {
1814 for(var id in this.copyCache) {
1815 var c = this.copyCache[id];
1816 if(!c.isdeleted()) total++;
1817 if(c.isnew() || c.ischanged() || c.isdeleted()) {
1818 if(c.id() < 0) c.id(null);
1824 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
1827 if (copies.length > 0) {
1828 if (!this.confirmBreachedCopyFunds(copies))
1831 if (typeof(this._copy_count_cb) == "function")
1832 this._copy_count_cb(liId, total);
1834 openils.Util.show("acq-lit-update-copies-progress");
1835 fieldmapper.standardRequest(
1836 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1838 params: [openils.User.authtoken, copies],
1839 onresponse: function(r) {
1840 var res = openils.Util.readResponse(r);
1841 litUpdateCopiesProgress.update(res);
1843 oncomplete: function() {
1844 self.drawCopies(liId, true /* force_fetch */);
1845 openils.Util.hide("acq-lit-update-copies-progress");
1851 var dfa_list = this._virtDfaCountsAsList();
1852 if (dfa_list.length > 0) {
1853 fieldmapper.standardRequest(
1855 "open-ils.acq.distribution_formula.record_application"],
1858 "params": [openils.User.authtoken, dfa_list, liId],
1859 "onresponse": function(r) {
1860 var res = openils.Util.readResponse(r);
1861 if (res && res.length < dfa_list.length)
1862 alert(localeStrings.DFA_NOT_ALL);
1866 this.virtDfaCounts = {};
1870 this._updateCreatePoPrepayCheckbox = function(prepay) {
1871 var prepay = openils.Util.isTrue(prepay);
1872 this._prepayRequiredByVendor = prepay;
1873 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
1876 this._confirmPoPrepaySituation = function() {
1877 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
1878 if (want_prepay != this._prepayRequiredByVendor) {
1881 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
1882 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
1889 this.applySelectedLiAction = function(action) {
1893 case 'delete_selected':
1894 this._deleteLiList(self.getSelected());
1897 case 'create_order':
1898 this._loadPOSelect();
1899 acqLitPoCreateDialog.show();
1902 case 'save_picklist':
1903 acqLitSavePlDialog.show();
1906 case 'selector_ready':
1908 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
1909 acqLitChangeLiStateDialog.show();
1917 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
1924 case 'rollback_receive_po':
1925 this.rollbackPoReceive();
1928 case 'create_assets':
1929 this.createAssets();
1932 case 'export_attr_list':
1933 this.chooseExportAttr();
1936 case 'batch_apply_funds':
1937 this.applyBatchLiFunds();
1940 case 'add_brief_record':
1942 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
1944 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
1948 case "cancel_lineitems":
1949 this.maybeCancelLineitems();
1952 case "change_claim_policy":
1953 var li_list = this.getSelected();
1954 this.claimPolicyPicker.attr("value", null);
1955 liClaimPolicyDialog.show();
1956 liClaimPolicySave.onClick = function() {
1957 self.changeClaimPolicy(
1959 self.claimPolicyPicker.attr("value"),
1963 self.setClaimPolicyControl(li);
1964 self.reconsiderClaimControl(li);
1967 liClaimPolicyDialog.hide();
1975 this.changeClaimPolicy = function(li_list, value, callback) {
1977 function(li) { li.claim_policy(value); }
1979 fieldmapper.standardRequest(
1980 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
1981 "params": [openils.User.authtoken, li_list],
1983 "oncomplete": function(r) {
1984 r = openils.Util.readResponse(r);
1985 if (callback) callback(r);
1991 this.createAssets = function() {
1992 if(!this.isPO) return;
1993 if(!confirm(localeStrings.CREATE_PO_ASSETS_CONFIRM)) return;
1994 this.show('acq-lit-progress-numbers');
1996 fieldmapper.standardRequest(
1997 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
1999 params: [this.authtoken, this.isPO],
2000 onresponse: function(r) {
2001 var resp = openils.Util.readResponse(r);
2002 self._updateProgressNumbers(resp, true);
2008 this.maybeCancelLineitems = function() {
2009 openils.Util.show("acq-lit-cancel-reason", "inline");
2010 if (!acqLitCancelLineitemsButton._prepared) {
2011 var widget = new openils.widget.AutoFieldWidget({
2012 "fmField": "cancel_reason",
2014 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
2015 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2020 acqLitCancelLineitemsButton.onClick = function() {
2021 if (w.attr("value")) {
2022 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
2023 self._cancelLineitems(w.attr("value"));
2025 openils.Util.hide("acq-lit-cancel-reason");
2028 acqLitCancelLineitemsButton._prepared = true;
2034 this._cancelLineitems = function(reason) {
2035 var id_list = this.getSelected().map(function(o) { return o.id(); });
2036 fieldmapper.standardRequest(
2037 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
2038 "params": [openils.User.authtoken, id_list, reason],
2040 "onresponse": function(r) {
2041 if (r = openils.Util.readResponse(r)) {
2043 for (var id in r.li) {
2044 self.liCache[id].state(r.li[id].state);
2045 self.liCache[id].cancel_reason(
2046 r.li[id].cancel_reason
2048 self.updateLiState(self.liCache[id]);
2051 if (r.lid && self.copyCache) {
2052 for (var id in r.lid) {
2053 if (self.copyCache[id]) {
2054 self.copyCache[id].cancel_reason(
2055 r.lid[id].cancel_reason
2057 self.updateLidState(self.copyCache[id]);
2067 this.chooseExportAttr = function() {
2068 if (!acqLitExportAttrSelector._li_setup) {
2070 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
2072 "data": acqlimad.toStoreData(
2074 "acqlimad", {"code": li_exportable_attrs}
2079 acqLitExportAttrSelector.setValue();
2080 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
2081 acqLitExportAttrSelector._li_setup = true;
2083 openils.Util.show("acq-lit-export-attr-holder", "inline");
2086 this.exportAttrList = function() {
2087 var attr_def = acqLitExportAttrSelector.item;
2088 var li_list = this.getSelected();
2089 var value_list = li_list.map(
2091 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2092 attr_def.code, "lineitem_marc_attr_definition"
2095 ).filter(function(attr) { return Boolean(attr); });
2097 if (value_list.length > 0) {
2098 if (value_list.length < li_list.length) {
2100 dojo.string.substitute(
2101 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
2108 openils.XUL.contentToFileSaveDialog(
2109 value_list.join("\n"),
2110 localeStrings.EXPORT_SAVE_DIALOG_TITLE
2116 alert(dojo.string.substitute(
2117 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
2121 openils.Util.hide("acq-lit-export-attr-holder");
2124 this.printPO = function() {
2125 if(!this.isPO) return;
2126 progressDialog.show(true);
2127 fieldmapper.standardRequest(
2128 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
2130 params: [this.authtoken, this.isPO, 'html'],
2131 oncomplete: function(r) {
2132 progressDialog.hide();
2133 var evt = openils.Util.readResponse(r);
2134 if(evt && evt.template_output()) {
2135 openils.Util.printHtmlString(evt.template_output().data());
2143 this.receivePO = function() {
2144 if (!this.isPO) return;
2146 for (var id in this.liCache) {
2147 /* assumption: liCache reflects exactly the
2148 * set of LIs that belong to our PO */
2149 if (this.liCache[id].state() != "received" &&
2150 !this.checkLiAlerts(id)) return;
2153 this.show('acq-lit-progress-numbers');
2155 fieldmapper.standardRequest(
2156 ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
2158 params: [this.authtoken, this.isPO],
2159 onresponse : function(r) {
2160 var resp = openils.Util.readResponse(r);
2161 self._updateProgressNumbers(resp, true);
2167 this.issueReceive = function(obj, rollback) {
2168 /* (For now) there shall be no marking LI or LIDs (un)received
2169 * except from the actual "view PO" interface. */
2170 if (!this.isPO) return;
2173 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
2175 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
2177 progressDialog.show(true);
2178 fieldmapper.standardRequest(
2179 ["open-ils.acq", method], {
2181 "params": [this.authtoken, obj.id()],
2182 "onresponse": function(r) {
2183 if (r = openils.Util.readResponse(r)) {
2184 self.fetchClaimInfo(
2185 part == "lineitem" ? obj.id() : obj.lineitem(),
2187 function() { self.handleReceive(r); }
2189 progressDialog.hide();
2197 * Handles the responses from receive and rollback ML calls.
2199 this.handleReceive = function(resp) {
2202 for (var li_id in resp.li) {
2203 for (var key in resp.li[li_id])
2204 self.liCache[li_id][key](resp.li[li_id][key]);
2205 self.updateLiState(self.liCache[li_id]);
2209 if (typeof(self.poUpdateCallback) == "function")
2210 self.poUpdateCallback(resp.po);
2213 for (var lid_id in resp.lid) {
2214 for (var key in resp.lid[lid_id])
2215 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
2216 self.updateLidState(self.copyCache[lid_id]);
2222 this.rollbackPoReceive = function() {
2223 if(!this.isPO) return;
2224 if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
2225 this.show('acq-lit-progress-numbers');
2227 fieldmapper.standardRequest(
2228 ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
2230 params: [this.authtoken, this.isPO],
2231 onresponse : function(r) {
2232 var resp = openils.Util.readResponse(r);
2233 self._updateProgressNumbers(resp, true);
2239 this._updateProgressNumbers = function(resp, reloadOnComplete) {
2241 dojo.byId('acq-pl-lit-li-processed').innerHTML = resp.li;
2242 dojo.byId('acq-pl-lit-lid-processed').innerHTML = resp.lid;
2243 dojo.byId('acq-pl-lit-debits-processed').innerHTML = resp.debits_accrued;
2244 dojo.byId('acq-pl-lit-bibs-processed').innerHTML = resp.bibs;
2245 dojo.byId('acq-pl-lit-indexed-processed').innerHTML = resp.indexed;
2246 dojo.byId('acq-pl-lit-copies-processed').innerHTML = resp.copies;
2247 if(resp.complete && reloadOnComplete)
2248 location.href = location.href;
2252 this._createPO = function(fields) {
2253 this.show('acq-lit-progress-numbers');
2254 var po = new fieldmapper.acqpo();
2255 po.provider(this.createPoProviderSelector.attr('value'));
2256 po.ordering_agency(this.createPoAgencySelector.attr('value'));
2257 po.prepayment_required(fields.prepayment_required[0] ? true : false);
2259 var selected = this.getSelected( (fields.create_from == 'all') );
2260 if(selected.length == 0) return;
2262 var max = selected.length * 3;
2265 fieldmapper.standardRequest(
2266 ['open-ils.acq', 'open-ils.acq.purchase_order.create'],
2269 openils.User.authtoken,
2272 lineitems : selected.map(function(li) { return li.id() }),
2273 create_assets : fields.create_assets[0],
2277 onresponse : function(r) {
2278 var resp = openils.Util.readResponse(r);
2279 self._updateProgressNumbers(resp);
2281 location.href = oilsBasePath + '/acq/po/view/' + resp.purchase_order.id();
2287 this.batchFundWidget = null;
2289 this.applyBatchLiFunds = function() {
2291 var liIds = this.getSelected().map(function(li) { return li.id(); });
2292 if(liIds.length == 0) return; // warn?
2295 batchFundUpdateDialog.show();
2297 if(!this.batchFundWidget) {
2298 this.batchFundWidget = new openils.widget.AutoFieldWidget({
2300 selfReference : true,
2301 labelFormat : fundLabelFormat,
2302 searchFormat : fundSearchFormat,
2303 searchFilter : {"active": "t"},
2304 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
2305 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2306 dijitArgs : { "required": true, "labelType": "html" },
2309 this.batchFundWidget.build();
2312 dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
2313 dojo.connect(batchFundUpdateSubmit, 'onClick',
2316 // TODO: call .dry_run first to test thresholds
2317 fieldmapper.standardRequest(
2318 ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
2321 openils.User.authtoken,
2323 self.batchFundWidget.widget.attr('value')
2325 oncomplete : function(r) {
2326 var resp = openils.Util.readResponse(r);
2328 location.href = location.href;
2337 this._deleteLiList = function(list, idx) {
2338 if(idx == null) idx = 0;
2339 if(idx >= list.length) return;
2344 if (this.isPO && (li.state() == "on-order" || li.state() == "received")) {
2345 /* It makes little sense to delete a lineitem from a PO that has
2346 * already been marked 'on-order'. Especially if EDI is in use,
2347 * such a purchase order will probably have already been shipped
2348 * off to a vendor, and mucking with it at this point could leave
2349 * your data in a bad state that doesn't jive with reality.
2351 * I could see making this restriction even firmer.
2353 * I could also see adjusting the li state comparisons, extending
2354 * the comparison to the PO's state, and/or providing functions
2355 * that house the logic for comparing states in a single location.
2357 * Yes, this will be really annoying if you have selected a lot
2358 * of lineitems to cancel that have been ordered. You'll get a
2359 * confirm dialog for each one.
2362 if (!confirm(localeStrings.DEL_LI_FROM_PO)) {
2363 self._deleteLiList(list, ++idx); /* move on to next in list */
2368 fieldmapper.standardRequest(
2370 this.isPO ? 'open-ils.acq.purchase_order.lineitem.delete' : 'open-ils.acq.picklist.lineitem.delete'],
2372 params: [openils.User.authtoken, liId],
2373 oncomplete: function(r) {
2374 self.removeLineitem(liId);
2375 self._deleteLiList(list, ++idx);
2381 this.editOrderMarc = function(li) {
2383 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
2384 to true in about:config */
2386 if(!openils.XUL.enableXPConnect()) return;
2388 if(openils.XUL.isXUL()) {
2389 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
2391 win = window.open('/xul/server/cat/marcedit.xul');
2395 record : {marc : li.marc(), "rtype": "bre"},
2397 label: 'Save Record', // XXX I18N
2398 func: function(xmlString) {
2400 fieldmapper.standardRequest(
2401 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
2403 params: [openils.User.authtoken, li],
2404 oncomplete: function(r) {
2405 openils.Util.readResponse(r);
2407 self.drawInfo(li.id())
2413 'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
2414 'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
2418 this._savePl = function(values) {
2420 var selected = this.getSelected( (values.which == 'all') );
2421 openils.Util.show('acq-lit-generic-progress');
2423 if(values.new_name) {
2424 openils.acq.Picklist.create(
2425 {name: values.new_name},
2427 self._updateLiList(id, selected, 0,
2429 location.href = oilsBasePath + '/acq/picklist/view/' + id;
2433 } else if(values.existing_pl) {
2434 // update lineitems to use an existing picklist
2435 self._updateLiList(values.existing_pl, selected, 0,
2437 location.href = oilsBasePath + '/acq/picklist/view/' + values.existing_pl;
2442 this._updateLiState = function(values, state) {
2444 var selected = this.getSelected( (values.which == 'all') );
2445 if(!selected.length) return;
2446 dojo.forEach(selected, function(li) {li.state(state);});
2447 self._updateLiList(null, selected, 0,
2448 // TODO consider inline updates for efficiency
2449 function() { location.href = location.href }
2453 this._updateLiList = function(pl, list, idx, oncomplete) {
2454 if(idx >= list.length) return oncomplete();
2456 if(pl != null) li.picklist(pl);
2457 litGenericProgress.update({maximum: list.length, progress: idx});
2458 new openils.acq.Lineitem({lineitem:li}).update(
2460 self._updateLiList(pl, list, ++idx, oncomplete);
2465 this._loadPOSelect = function() {
2466 if (!this.createPoProviderSelector) {
2467 var widget = new openils.widget.AutoFieldWidget({
2468 "fmField": "provider",
2470 "searchFilter": {"active": "t"},
2471 "parentNode": dojo.byId("acq-lit-po-provider"),
2473 "onChange": function() {
2475 self._updateCreatePoPrepayCheckbox(
2476 this.item.prepayment_required()
2482 widget.build(function(w) { self.createPoProviderSelector = w; });
2485 if (!this.createPoAgencySelector) {
2486 var widget = new openils.widget.AutoFieldWidget({
2487 "fmField": "ordering_agency",
2489 "parentNode": dojo.byId("acq-lit-po-agency"),
2490 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2492 widget.build(function(w) { self.createPoAgencySelector = w; });
2496 this.showRealCopyEditUI = function(li) {
2501 this._fetchLineitem(li.id(),
2503 li = self.liCache[li.id()] = fullLi;
2507 id : li.lineitem_details().map(
2508 function(item) { return item.eg_copy_id() }
2512 oncomplete : function(r) {
2514 var r_list = openils.Util.readResponse( r );
2515 for (var i = 0; i < r_list.length; i++) {
2516 var copy = r_list[i];
2517 var volId = copy.call_number();
2518 var volume = self.volCache[volId];
2520 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2522 copy.call_number(volume);
2523 copyList.push(copy);
2526 xulG.volume_item_creator( { 'existing_copies' : copyList } );
2529 alert('error in oncomplete: ' + E);
2538 this.drawBibFinder = function(li) {
2541 var liWrapper = new openils.acq.Lineitem({lineitem:li});
2544 ['isbn', 'upc', 'issn', 'title', 'author'],
2546 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
2548 if(field == 'title' || field == 'author') {
2549 query += field +':' + val + ' ';
2551 query += 'identifier|' + field + ':' + val + ' ';
2558 oilsBasePath + '/acq/lineitem/findbib?query=' + escape(query),
2559 '', 'resizable,scrollbars=1');
2561 win.window.recordFound = function(bibId) {
2564 var attrs = li.attributes();
2565 li.attributes(null);
2566 li.eg_bib_id(bibId);
2568 fieldmapper.standardRequest(
2569 ["open-ils.acq", "open-ils.acq.lineitem.update"],
2571 "params": [openils.User.authtoken, li],
2573 "oncomplete": function(r) {
2574 if(openils.Util.readResponse(r)) {
2575 location.href = location.href;