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.toggleState = false;
54 this.tbody = dojo.byId('acq-lit-tbody');
57 this.authtoken = openils.User.authtoken;
58 this.pcrud = new openils.PermaCrud();
59 this.rowTemplate = this.tbody.removeChild(dojo.byId('acq-lit-row'));
60 this.copyTbody = dojo.byId('acq-lit-li-details-tbody');
61 this.copyRow = this.copyTbody.removeChild(dojo.byId('acq-lit-li-details-row'));
62 this.copyBatchRow = dojo.byId('acq-lit-li-details-batch-row');
63 this.copyBatchWidgets = {};
64 this.liNotesTbody = dojo.byId('acq-lit-notes-tbody');
65 this.liNotesRow = this.liNotesTbody.removeChild(dojo.byId('acq-lit-notes-row'));
66 this.realCopiesTbody = dojo.byId('acq-lit-real-copies-tbody');
67 this.realCopiesRow = this.realCopiesTbody.removeChild(dojo.byId('acq-lit-real-copies-row'));
68 this._copy_fields_for_acqdf = ['owning_lib', 'location'];
69 this.invoiceLinkDialogManager = new InvoiceLinkDialogManager("li");
70 this.claimDialog = new ClaimDialogManager(
71 liClaimDialog, finalClaimDialog, this.claimEligibleLidByLi
74 dojo.connect(acqLitLiActionsSelector, 'onChange',
76 self.applySelectedLiAction(this.attr('value'))
77 acqLitLiActionsSelector.attr('value', '_');
80 acqLitCreatePoSubmit.onClick = function() {
81 if (self._confirmPoPrepaySituation()) {
82 acqLitPoCreateDialog.hide();
83 self._createPO(acqLitPoCreateDialog.getValues());
89 acqLitSavePlButton.onClick = function() {
90 acqLitSavePlDialog.hide();
91 self._savePl(acqLitSavePlDialog.getValues());
94 acqLitCancelLiStateButton.onClick = function() {
95 acqLitChangeLiStateDialog.hide();
97 acqLitSaveLiStateButton.onClick = function() {
98 acqLitChangeLiStateDialog.hide();
99 self._updateLiState(acqLitChangeLiStateDialog.getValues(), acqLitChangeLiStateDialog.attr('state'));
103 dojo.byId('acq-lit-select-toggle').onclick = function(){self.toggleSelect()};
104 dojo.byId('acq-lit-info-back-button').onclick = function(){self.show('list')};
105 dojo.byId('acq-lit-copies-back-button').onclick = function(){self.show('list')};
106 dojo.byId('acq-lit-notes-back-button').onclick = function(){self.show('list')};
107 dojo.byId('acq-lit-real-copies-back-button').onclick = function(){self.show('list')};
109 this.reset = function() {
110 while(self.tbody.childNodes[0])
111 self.tbody.removeChild(self.tbody.childNodes[0]);
117 this.setNext = function(handler) {
118 var link = dojo.byId('acq-lit-next');
120 dojo.style(link, 'visibility', 'visible');
121 link.onclick = handler;
123 dojo.style(link, 'visibility', 'hidden');
127 this.setPrev = function(handler) {
128 var link = dojo.byId('acq-lit-prev');
130 dojo.style(link, 'visibility', 'visible');
131 link.onclick = handler;
133 dojo.style(link, 'visibility', 'hidden');
137 this.show = function(div) {
138 openils.Util.hide('acq-lit-table-div');
139 openils.Util.hide('acq-lit-info-div');
140 openils.Util.hide('acq-lit-li-details');
141 openils.Util.hide('acq-lit-notes-div');
142 openils.Util.hide('acq-lit-real-copies-div');
145 openils.Util.show('acq-lit-table-div');
148 openils.Util.show('acq-lit-info-div');
151 openils.Util.show('acq-lit-li-details');
154 openils.Util.show('acq-lit-real-copies-div');
157 openils.Util.show('acq-lit-notes-div');
161 openils.Util.show(div);
165 this.hide = function() {
169 this.toggleSelect = function() {
171 dojo.forEach(self.selectors, function(i){i.checked = false});
173 dojo.forEach(self.selectors, function(i){i.checked = true});
174 self.toggleState = !self.toggleState;
178 /** @param all If true, assume all are selected */
179 this.getSelected = function(all) {
181 dojo.forEach(self.selectors,
184 selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
190 this.setRowAttr = function(td, liWrapper, field, type) {
191 var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
192 td.appendChild(document.createTextNode(val));
195 this.setClaimPolicyControl = function(li, row) {
196 if (!self.claimPolicyPicker) {
197 self.claimPolicyPicker = true; /* prevents a race condition */
198 new openils.widget.AutoFieldWidget({
199 "parentNode": "acq-lit-li-claim-policy",
201 "selfReference": true,
202 "dijitArgs": {"required": true}
203 }).build(function(w) { self.claimPolicyPicker = w; });
206 if (typeof(row) == "undefined")
207 row = dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
209 var actViewPolicy = nodeByName("action_view_claim_policy", row);
210 if (li.claim_policy())
211 actViewPolicy.innerHTML = localeStrings.CHANGE_CLAIM_POLICY;
213 if (!actViewPolicy.onclick) {
214 actViewPolicy.onclick = function() {
215 if (li.claim_policy())
216 self.claimPolicyPicker.attr("value", li.claim_policy());
217 liClaimPolicyDialog.show();
218 liClaimPolicySave.onClick = function() {
219 self.changeClaimPolicy(
220 [li], self.claimPolicyPicker.attr("value"),
222 self.setClaimPolicyControl(li, row);
223 liClaimPolicyDialog.hide();
232 * Inserts a single lineitem into the growing table of lineitems
233 * @param {Object} li The lineitem object to insert
235 this.addLineitem = function(li, skip_final_placement) {
236 this.liCache[li.id()] = li;
238 // sort the lineitem notes on edit_time
239 if(!li.lineitem_notes()) li.lineitem_notes([]);
241 var liWrapper = new openils.acq.Lineitem({lineitem:li});
242 var row = self.rowTemplate.cloneNode(true);
243 row.setAttribute('li', li.id());
244 var tds = dojo.query('[attr]', row);
245 dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
246 dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
248 var isbn = liWrapper.findAttr('isbn', 'lineitem_marc_attr_definition');
250 // XXX media prefix for added content
251 dojo.query('[name=jacket]', row)[0].setAttribute('src', '/opac/extras/ac/jacket/small/' + isbn);
254 nodeByName("worksheet_link", row).href =
255 oilsBasePath + "/acq/lineitem/worksheet/" + li.id();
257 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
258 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
259 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
261 /* XXX note how checkClaimEligibility() is getting called once per LI
262 * when in some use cases we should be able to do that job with one
263 * call per PO or per PL or whatever... */
265 li.id(), function(full) {
266 self.liCache[full.id()] = full;
267 self.checkClaimEligibility(full, row);
271 this.updateLiNotesCount(li, row);
273 this.setClaimPolicyControl(li, row);
275 // show which PO this lineitem is a member of
276 if(li.purchase_order() && !this.isPO) {
278 this.poCache[li.purchase_order()] =
279 this.poCache[li.purchase_order()] ||
280 fieldmapper.standardRequest(
281 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
283 this.authtoken, li.purchase_order(), {
284 "flesh_price_summary": true,
285 "flesh_lineitem_count": true
288 if(po && !this.isMeta) {
289 openils.Util.show(nodeByName('po', row), 'inline');
290 var link = nodeByName('po_link', row);
291 link.setAttribute('href', oilsBasePath + '/acq/po/view/' + li.purchase_order());
292 link.innerHTML = 'PO: ' + po.name(); // TODO i18n
296 // show which picklist this lineitem is a member of
297 if(li.picklist() && (this.isPO || this.isMeta)) {
299 this.plCache[li.picklist()] =
300 this.plCache[li.picklist()] ||
301 fieldmapper.standardRequest(
302 ['open-ils.acq', 'open-ils.acq.picklist.retrieve'],
303 {params: [this.authtoken, li.picklist()]});
305 openils.Util.show(nodeByName('pl', row), 'inline');
306 var link = nodeByName('pl_link', row);
307 link.setAttribute('href', oilsBasePath + '/acq/picklist/view/' + li.picklist());
308 link.innerHTML = 'PL: '+pl.name(); // TODO i18n
312 var countNode = nodeByName('count', row);
313 var count = li.item_count() || 0;
314 if (typeof(this._copy_count_cb) == "function") {
315 this._copy_count_cb(li.id(), count);
317 countNode.innerHTML = count;
318 countNode.id = 'acq-lit-copy-count-label-' + li.id();
321 var priceInput = dojo.query('[name=price]', row)[0];
322 priceInput.value = li.estimated_unit_price() || '';
323 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
325 // show either "mark received" or "unreceive" as appropriate
326 this.updateLiState(li, row);
328 if (!skip_final_placement) {
329 self.tbody.appendChild(row);
330 self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
336 this._liCountClaims = function(li) {
338 for (var i = 0; i < li.lineitem_details().length; i++)
339 total += li.lineitem_details()[i].claims().length;
343 this.reconsiderClaimControl = function(li, row) {
344 var option = nodeByName("action_manage_claims", row);
345 var eligible = this.claimEligibleLidByLi[li.id()].length;
346 var count = this._liCountClaims(li);
348 option.disabled = !(count || eligible);
350 /* of course I'd rather just populate a <span> element inside the
351 * option element, but it seems you can't actually have any elements
352 * inside option elements */
353 option.innerHTML = option.innerHTML.replace(
354 /(^.+)(.*)( existing.+$)/, "$1" + String(count) + "$3"
356 option.onclick = function() { self.claimDialog.show(li); };
359 this.checkClaimEligibility = function(li, row) {
360 this.claimEligibleLidByLi[li.id()] = [];
361 fieldmapper.standardRequest(
362 ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
363 "params": [openils.User.authtoken, {"lineitem": li.id()}],
365 "onresponse": function(r) {
366 if (r = openils.Util.readResponse(r)) {
367 self.claimEligibleLidByLi[li.id()].push(
372 "oncomplete": function() {
373 self.reconsiderClaimControl(li, row);
379 this.updateLiNotesCount = function(li, row) {
380 if (typeof(row) == "undefined")
381 row = dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
383 var has_notes = (li.lineitem_notes().filter(
384 function(o) { return Boolean (o.alert_text()); }
387 /* U+2691 is the code point for a filled-in flag character */
388 nodeByName("notes_alert_flag", row).innerHTML =
389 has_notes ? "⚑" : "";
390 nodeByName("noteslink", row).style.fontStyle =
391 has_notes ? "italic" : "normal";
392 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
395 /* XXX NOT related to _updateLiState(). rethink */
396 this.updateLiState = function(li, row) {
397 if (typeof(row) == "undefined")
398 row = dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
400 var actReceive = nodeByName("action_mark_recv", row);
401 var actUnRecv = nodeByName("action_mark_unrecv", row);
402 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
403 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
405 var actNewInvoice = nodeByName('action_new_invoice', row);
406 var actLinkInvoice = nodeByName('action_link_invoice', row);
407 var actViewInvoice = nodeByName('action_view_invoice', row);
409 var state_cell = nodeByName("li_state", row);
411 if (li.state() == "cancelled") {
412 if (typeof li.cancel_reason() == "object") {
413 var holds_state = dojo.create(
415 "style": "border-bottom: 1px dashed #000;",
416 "innerHTML": li.state()
417 }, state_cell, "only"
421 "label": "<em>" + li.cancel_reason().label() +
422 "</em><br />" + li.cancel_reason().description(),
423 "connectId": [holds_state]
424 }, dojo.create("span", null, state_cell, "last")
427 state_cell.innerHTML = li.state(); // TODO i18n state labels
430 state_cell.innerHTML = li.state(); // TODO i18n state labels
434 /* handle row coloring for based on LI state */
435 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
436 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
438 /* handle links that appear/disappear based on whether LI is received */
443 actReceive.disabled = false;
444 actReceive.onclick = function() {
445 if (self.checkLiAlerts(li.id()))
446 self.issueReceive(li);
447 nodeByName("action_none", row).selected = true;
451 actUnRecv.disabled = false;
452 actUnRecv.onclick = function() {
453 if (confirm(localeStrings.UNRECEIVE_LI))
454 self.issueReceive(li, /* rollback */ true);
455 nodeByName("action_none", row).selected = true;
457 // TODO we should allow editing before receipt, in which case the
458 // test should be "if 1 or more real (acp) copies exist
459 actUpdateBarcodes.disabled = false;
460 actUpdateBarcodes.onclick = function() {
461 self.showRealCopyEditUI(li);
462 nodeByName("action_none", row).selected = true;
464 actHoldingsMaint.disabled = false;
465 actHoldingsMaint.onclick = self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
467 actNewInvoice.disabled = false;
468 actLinkInvoice.disabled = false;
469 actViewInvoice.disabled = false;
471 actNewInvoice.onclick = function() {
472 location.href = oilsBasePath + '/acq/invoice/view?create=1&attach_li=' + li.id();
473 nodeByName("action_none", row).selected = true;
475 actLinkInvoice.onclick = function() {
476 self.invoiceLinkDialogManager.target = li;
477 acqLitLinkInvoiceDialog.show();
478 nodeByName("action_none", row).selected = true;
480 actViewInvoice.onclick = function() {
481 location.href = oilsBasePath +
482 "/acq/search/unified?so=" +
483 base64Encode({"jub":[{"id": li.id()}]}) +
485 nodeByName("action_none", row).selected = true;
494 this._setAlertStore = function() {
495 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
497 "data": acqliat.toStoreData(
499 "acqliat", {"id": {"!=": null}}
504 acqLitAlertAlertText.setValue(); /* make the store "live" */
505 acqLitAlertAlertText._store_ready = true;
509 * Draws and shows the lineitem notes pane
511 this.drawLiNotes = function(li) {
514 if (!acqLitAlertAlertText._store_ready)
515 this._setAlertStore();
518 li.lineitem_notes().sort(
520 if(a.edit_time() < b.edit_time()) return 1;
526 while(this.liNotesTbody.childNodes[0])
527 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
530 acqLitCreateNoteSubmit.onClick = function() {
531 var value = acqLitCreateNoteText.attr('value');
533 var note = new fieldmapper.acqlin();
536 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
539 note.lineitem(li.id());
541 self.updateLiNotes(li, note);
542 acqLitCreateNoteVendorPublic.attr("checked", false);
543 acqLitCreateNoteText.attr("value", "");
546 acqLitCreateAlertSubmit.onClick = function() {
547 if (!acqLitAlertAlertText.item) {
548 alert(localeStrings.ALERT_UNSELECTED);
552 var alert_text = new fieldmapper.acqliat().fromStoreItem(
553 acqLitAlertAlertText.item
555 var value = acqLitAlertNoteValue.attr("value") || "";
557 var note = new fieldmapper.acqlin();
559 note.lineitem(li.id());
561 note.alert_text(alert_text);
563 self.updateLiNotes(li, note);
566 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
570 * Draws a single lineitem note in the notes pane
572 this.addLiNote = function(li, note) {
573 if(note.isdeleted()) return;
575 var row = self.liNotesRow.cloneNode(true);
576 nodeByName("value", row).innerHTML = note.value();
577 var alert_node = nodeByName("alert_code", row);
578 if (note.alert_text()) {
579 alert_node.innerHTML = note.alert_text().code();
580 if (note.alert_text().description()) {
583 "connectId": [alert_node],
584 "label": note.alert_text().description()
585 }, dojo.create("span", null, alert_node, "after")
590 if (openils.Util.isTrue(note.vendor_public()))
591 nodeByName("vendor_public", row).innerHTML =
592 localeStrings.VENDOR_PUBLIC;
594 nodeByName("delete", row).onclick = function() {
595 note.isdeleted(true);
596 self.liNotesTbody.removeChild(row);
597 self.updateLiNotes(li);
600 if(note.edit_time()) {
601 nodeByName("edit_time", row).innerHTML =
602 dojo.date.locale.format(
603 dojo.date.stamp.fromISOString(note.edit_time()),
604 {formatLength:'short'});
607 self.liNotesTbody.appendChild(row);
611 * Updates any new/changed/deleted notes on the server
613 this.updateLiNotes = function(li, newNote) {
619 notes = li.lineitem_notes().filter(
621 if(note.ischanged() || note.isnew() || note.isdeleted())
627 if(notes.length == 0) return;
628 progressDialog.show();
630 fieldmapper.standardRequest(
631 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
633 params : [this.authtoken, notes],
634 onresponse : function(r) {
635 var resp = openils.Util.readResponse(r);
640 // remove the old changed notes
642 dojo.forEach(li.lineitem_notes(),
644 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
648 li.lineitem_notes(list);
651 progressDialog.hide();
652 self.updateLiNotesCount(li);
653 self.drawLiNotes(li);
657 progressDialog.update(resp);
658 var newnote = resp.note;
660 if(!newnote.isdeleted()) {
661 newnote.isnew(false);
662 newnote.ischanged(false);
663 li.lineitem_notes().push(newnote);
670 this.updateLiPrice = function(input, li) {
672 var price = input.value;
673 if(Number(price) == Number(li.estimated_unit_price())) return;
675 fieldmapper.standardRequest(
676 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
678 params : [this.authtoken, li.id(), price],
679 oncomplete : function(r) {
680 openils.Util.readResponse(r);
681 li.estimated_unit_price(price); // update local copy
687 this.removeLineitem = function(liId) {
688 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
689 delete this.liCache[liId];
690 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
693 this.drawInfo = function(liId) {
694 if (!this._isRelatedViewer) {
695 var d = dojo.byId("acq-lit-info-related");
696 if (!this.relCache[liId]) {
697 fieldmapper.standardRequest(
700 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
703 "params": [openils.User.authtoken, liId],
704 "onresponse": function(r) {
705 self.relCache[liId] = openils.Util.readResponse(r);
706 nodeByName("related_number", d).innerHTML =
709 self.relCache[liId] >1 ? "show" : "hide"
715 nodeByName("related_number", d).innerHTML = this.relCache[liId];
716 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
721 openils.acq.Lineitem.fetchAttrDefs(
723 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
728 this._fetchLineitem = function(liId, handler) {
730 var li = this.liCache[liId];
731 if(li && li.marc() && li.lineitem_details())
734 fieldmapper.standardRequest(
735 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve'],
738 params: [self.authtoken, liId, {
740 flesh_cancel_reason: true,
741 flesh_li_details: true,
742 flesh_fund_debit: true }],
744 oncomplete: function(r) {
745 var li = openils.Util.readResponse(r);
752 this._drawInfo = function(li) {
754 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
757 openils.Util.hide('acq-lit-marc-order-record-label');
758 openils.Util.hide(acqLitEditOrderMarc.domNode);
759 openils.Util.show('acq-lit-marc-real-record-label');
761 openils.Util.show('acq-lit-marc-order-record-label');
762 openils.Util.show(acqLitEditOrderMarc.domNode);
763 openils.Util.hide('acq-lit-marc-real-record-label');
766 this.drawMarcHTML(li);
767 this.infoTbody = dojo.byId('acq-lit-info-tbody');
770 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
771 while(this.infoTbody.childNodes[0])
772 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
774 for(var i = 0; i < li.attributes().length; i++) {
775 var attr = li.attributes()[i];
776 var row = this.infoRow.cloneNode(true);
778 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
779 var name = openils.acq.Lineitem.attrDefs[type].filter(
781 return (a.code() == attr.attr_name());
783 ).pop().description();
785 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
786 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
787 this.infoTbody.appendChild(row);
790 if (!this._isRelatedViewer) {
791 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
792 oilsBasePath + "/acq/lineitem/related/" + li.id();
797 openils.Util.show('acq-lit-info-cat-link');
798 var link = dojo.byId('acq-lit-info-cat-link').getElementsByTagName('a')[0];
800 if(openils.XUL.isXUL()) {
802 link.setAttribute('href', 'javascript:void(0);');
803 link.onclick = this.generateMakeRecTab( li.eg_bib_id() );
806 var href = link.getAttribute('href');
808 link.setAttribute('href', href + li.eg_bib_id());
811 openils.Util.hide('acq-lit-info-cat-link');
815 this.generateMakeRecTab = function(bib_id,default_view, row) {
819 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
822 show_nav_buttons : true,
823 show_print_button : true,
824 opac_url : xulG.url_prefix(xulG.urls.opac_rdetail + '?r=' + bib_id),
825 default_view : default_view
829 if(row) nodeByName("action_none", row).selected = true;
833 this.drawMarcHTML = function(li) {
834 var params = [null, true, li.marc()];
836 params = [li.eg_bib_id(), true];
838 fieldmapper.standardRequest(
839 ['open-ils.search', 'open-ils.search.biblio.record.html'],
842 oncomplete: function(r) {
843 dojo.byId('acq-lit-marc-div').innerHTML =
844 openils.Util.readResponse(r);
850 this.drawCopies = function(liId) {
854 this.copyWidgetCache = {};
855 this.oldCopyWidgetCache = {};
856 this.virtDfaCounts = {};
857 this.realDfaCache = {};
860 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
861 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
862 acqLitCopyCountInput.attr('value', '0');
864 while(this.copyTbody.childNodes[0])
865 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
867 this._drawBatchCopyWidgets();
869 this._drawDistribApplied(liId);
871 this._fetchDistribFormulas(
873 openils.acq.Lineitem.fetchAttrDefs(
875 self._fetchLineitem(liId, function(li){self._drawCopies(li);});
882 this._saveDistribAppliedTemplates = function() {
883 if (!this._appliedDistribTemplate) {
884 this._appliedDistribTemplate =
885 dojo.byId("acq-lit-distrib-applied-tbody").
886 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
887 dojo.attr(this._appliedDistribTemplate, "id");
891 this._drawDistribApplied = function(liId) {
892 /* Build this table while hidden to prevent rendering artifacts */
893 openils.Util.hide("acq-lit-distrib-applied-tbody");
895 this._saveDistribAppliedTemplates();
897 /* Remove any rows in the table from previous populations */
898 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
899 forEach(dojo.destroy);
901 /* Unregister all dijits previously created (for some reason this isn't
902 * covered by the above destroy calls). */
903 dijit.registry.forEach(
904 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
907 /* Populate the table with our liId */
909 fieldmapper.standardRequest(
911 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
914 "params": [self.authtoken, liId],
915 "onresponse": function(r) {
916 var dfa = openils.Util.readResponse(r);
919 self.realDfaCache[dfa.id()] = dfa;
920 self._drawDistribAppliedUnit(dfa);
923 "oncomplete": function() {
924 /* Reveal built table */
927 "acq-lit-distrib-applied-tbody", "table-row-group"
935 this._drawDistribAppliedUnit = function(dfa) {
937 var row = dojo.query(
938 'tr[formula="' + dfa.formula().id() + '"]',
939 "acq-lit-distrib-applied-tbody"
944 row = dojo.clone(this._appliedDistribTemplate);
945 dojo.attr(row, "formula", dfa.formula().id());
946 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
949 var td = dojo.query("td", row)[0];
951 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
952 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
955 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
957 new dijit.form.Button(
959 "onClick": function() {
960 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
964 /* XXX I /cannot/ make the following work in as a CSS class
965 * for some reason. So frustrating... */
966 "style": function(id) {
968 "font-weight: bold; color: #c00;" :
970 }(dfa.id()) + "margin: 0 6px;display: inline;"
971 }, "dfa-button-" + dfa.id()
975 "connectId": ["dfa-button-" + dfa.id()],
976 "label": dojo.string.substitute(
977 localeStrings.DFA_TIP, dfa.id() > 0 ? [
978 openils.User.formalName(dfa.creator()),
979 dojo.date.locale.format(
980 dojo.date.stamp.fromISOString(dfa.create_time()),
981 {"formatLength":"short"}
983 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
985 }, "dfa-tip-" + dfa.id()
989 this.deleteDfa = function(dfa) {
990 if (dfa.id() > 0) { /* real */
991 this.pcrud.eliminate(
994 "oncomplete": function() {
995 self._removeDistribApplied(dfa.id());
996 delete self.realDfaCache[dfa.id()];
1000 } else { /* virtual */
1001 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
1002 this.virtDfaCounts[dfa.formula().id()] = 0;
1003 /* hasn't been saved yet, so no need to do anything server side */
1004 this._removeDistribApplied(dfa.id());
1009 this._removeDistribApplied = function(dfaId) {
1010 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
1011 dijit.registry.forEach(
1012 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
1014 this._removeDistribAppliedEmptyRows();
1017 this._removeAllDistribAppliedVirtual = function() {
1018 /* Unregister dijits */
1019 dijit.registry.forEach(
1020 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
1022 this._removeDistribAppliedEmptyRows();
1025 this._removeDistribAppliedEmptyRows = function() {
1026 /* Remove any rows with no DFA at all */
1027 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
1029 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
1035 * Insert a new row into the distribution formula selection form
1037 this._addDistribFormulaRow = function() {
1040 if (!self.distribForms) {
1041 // no formulas, hide the form
1042 openils.Util.hide('acq-lit-distrib-formula-tbody');
1046 if(!this.distribFormulaTemplate)
1047 this.distribFormulaTemplate =
1048 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
1050 var row = this.distribFormulaTemplate.cloneNode(true);
1051 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
1053 this.dfSelector = new dijit.form.FilteringSelect(
1054 {"labelAttr": "dynLabel", "labelType": "html"},
1055 nodeByName("selector", row)
1057 this._updateFormulaStore();
1058 this.dfSelector.fetchProperties =
1059 {"sort": [{"attribute": "use_count", "descending": true}]};
1061 var apply = new dijit.form.Button(
1062 {"label": localeStrings.APPLY},
1063 nodeByName('set_button', row)
1066 var reset = new dijit.form.Button(
1067 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
1068 nodeByName("reset_button", row)
1071 dojo.connect(apply, 'onClick',
1073 var form_id = self.dfSelector.attr("value");
1074 if(!form_id) return;
1075 self._applyDistribFormula(form_id);
1076 reset.attr("disabled", false);
1080 dojo.connect(reset, 'onClick',
1082 self.restoreCopyFieldsBeforeDF();
1083 self.virtDfaCounts = {};
1084 self.virtDfaId = -1;
1086 self._updateFormulaStore();
1087 self._removeAllDistribAppliedVirtual();
1088 reset.attr("disabled", "true");
1095 * Applies a distrib formula to the current set of copies
1097 this._applyDistribFormula = function(formula) {
1098 if(!formula) return;
1100 formula = this.distribForms.filter(
1101 function(form) { return form.id() == formula; }
1104 var copyRows = dojo.query('tr', self.copyTbody);
1106 if (this.dfeOffset >= copyRows.length) {
1107 alert(localeStrings.OUT_OF_COPIES);
1111 var entries_applied = 0;
1113 var rowIndex = this.dfeOffset;
1114 rowIndex < copyRows.length;
1118 var row = copyRows[rowIndex];
1119 var copy_id = row.getAttribute('copy_id');
1120 var copyWidgets = this.copyWidgetCache[copy_id];
1121 var entryIndex = this.dfeOffset;
1124 // find the correct entry for the current row
1125 dojo.forEach(formula.entries(),
1128 entryIndex += e.item_count();
1129 if(entryIndex > rowIndex)
1137 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
1138 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
1141 this.saveCopyFieldsBeforeDF(copy_id);
1142 this._copy_fields_for_acqdf.forEach(
1144 if(entry[field]()) {
1145 copyWidgets[field].attr('value', (entry[field]()));
1152 if (entries_applied) {
1153 this.virtDfaCounts[formula.id()] =
1154 ++(this.virtDfaCounts[formula.id()]) || 1;
1155 this._updateFormulaStore();
1156 this._drawDistribAppliedUnit(
1158 var dfa = new acqdfa();
1159 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
1162 this.dfeOffset += entries_applied;
1167 * This function updates the DF store for the dropdown so that use_counts
1168 * can reflect DF applications from this session before they're saved
1171 this._updateFormulaStore = function() {
1172 this.dfSelector.store = new dojo.data.ItemFileReadStore(
1174 "data": self._labelFormulasWithCounts(
1175 acqdf.toStoreData(self.distribForms)
1181 this.saveCopyFieldsBeforeDF = function(copy_id) {
1183 if (!this.oldCopyWidgetCache[copy_id]) {
1184 var copyWidgets = this.copyWidgetCache[copy_id];
1186 this.oldCopyWidgetCache[copy_id] = {};
1187 this._copy_fields_for_acqdf.forEach(
1189 self.oldCopyWidgetCache[copy_id][f] =
1190 copyWidgets[f].attr("value");
1196 this.restoreCopyFieldsBeforeDF = function() {
1198 for (var copy_id in this.oldCopyWidgetCache) {
1199 this._copy_fields_for_acqdf.forEach(
1201 self.copyWidgetCache[copy_id][f].attr(
1202 "value", self.oldCopyWidgetCache[copy_id][f]
1209 this._labelFormulasWithCounts = function(store_data) {
1210 for (var key in store_data.items) {
1211 var obj = store_data.items[key];
1212 obj.use_count = Number(obj.use_count); /* needed for sorting */
1214 if (this.virtDfaCounts[obj.id])
1215 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
1217 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
1218 obj.use_count + "]</span> " + obj.name;
1224 * This method formerly would not refetch the DF formulas if they'd been
1225 * loaded already, but now it always re-fetches, since use_count changes.
1227 this._fetchDistribFormulas = function(onload) {
1228 fieldmapper.standardRequest(
1230 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
1233 "params": [openils.User.authtoken],
1234 "oncomplete": function(r) {
1235 self.distribForms = openils.Util.readResponse(r);
1236 if(!self.distribForms || self.distribForms.length == 0) {
1237 self.distribForms = [];
1239 self._addDistribFormulaRow();
1246 this._drawBatchCopyWidgets = function() {
1247 var row = this.copyBatchRow;
1248 dojo.forEach(liDetailBatchFields,
1250 if(self.copyBatchRowDrawn) {
1251 self.copyBatchWidgets[field].attr('value', null);
1253 var widget = new openils.widget.AutoFieldWidget({
1256 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1257 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1258 searchFilter : (field == 'fund') ? {"active": "t"} : null,
1259 parentNode : dojo.query('[name='+field+']', row)[0],
1260 orgLimitPerms : ['CREATE_PICKLIST'],
1263 "labelType": (field == "fund") ? "html" : null
1265 noCache: (field == "fund"),
1270 if (field == "fund" && w.store)
1271 self._ensureCSSFundClasses(w.store);
1272 self.copyBatchWidgets[field] = w;
1275 if (field == "fund") {
1277 widget.widget, "onChange", function(val) {
1278 self._updateFundSelectorStyle(widget, val);
1285 this.copyBatchRowDrawn = true;
1288 this.batchCopyUpdate = function() {
1290 for(var k in this.copyWidgetCache) {
1291 var cache = this.copyWidgetCache[k];
1292 dojo.forEach(liDetailBatchFields, function(f) {
1293 var newval = self.copyBatchWidgets[f].attr('value');
1294 if(newval) cache[f].attr('value', newval);
1299 this._drawCopies = function(li) {
1302 // this button sets the total number of copies for a given lineitem
1303 acqLitAddCopyCount.onClick = function() {
1304 var count = acqLitCopyCountInput.attr('value');
1307 while(self.copyCount() < count)
1310 // delete rows if necessary
1311 var diff = self.copyCount() - count;
1313 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
1314 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
1315 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
1317 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1323 if(li.lineitem_details().length > 0) {
1324 dojo.forEach(li.lineitem_details(),
1326 self.addCopy(li, copy);
1334 this.copyCount = function() {
1336 for(var id in this.copyCache) {
1337 if(!this.copyCache[id].isdeleted())
1343 this.virtCopyId = -1;
1344 this.addCopy = function(li, copy) {
1345 var row = this.copyRow.cloneNode(true);
1346 this.copyTbody.appendChild(row);
1350 copy = new fieldmapper.acqlid();
1352 copy.id(this.virtCopyId--);
1353 copy.lineitem(li.id());
1356 this.copyCache[copy.id()] = copy;
1357 row.setAttribute('copy_id', copy.id());
1358 self.copyWidgetCache[copy.id()] = {};
1360 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1362 dojo.forEach(liDetailFields,
1365 if (field == "fund") {
1366 searchFilter = (copy.fund() ?
1367 {"-or": {"active": "t", "id": copy.fund()}} :
1370 searchFilter = null;
1372 var widget = new openils.widget.AutoFieldWidget({
1375 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1376 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1377 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1378 searchFilter : searchFilter,
1379 noCache: (field == "fund"),
1381 parentNode : dojo.query('[name='+field+']', row)[0],
1382 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
1383 readOnly : Boolean(copy.eg_copy_id())
1386 // make sure we capture the value from any async widgets
1388 if (field == "fund" && w.store)
1389 self._ensureCSSFundClasses(w.store);
1390 copy[field](ww.getFormattedValue())
1391 self.copyWidgetCache[copy.id()][field] = w;
1394 dojo.connect(widget.widget, 'onChange',
1396 if (field == "fund")
1397 self._updateFundSelectorStyle(widget, val);
1399 if (copy.isnew() || val != copy[field]()) {
1400 // prevent setting ischanged() automatically on widget load for existing copies
1401 copy[field](widget.getFormattedValue())
1402 copy.ischanged(true);
1409 this.updateLidState(copy, row);
1412 this._ensureCSSFundClass = function(id) {
1413 if (!this.fundStyleSheet) {
1415 "style", {"type": "text/css"},
1416 document.getElementsByTagName("head")[0], "last"
1418 this.fundStyleSheet = document.styleSheets[
1419 document.styleSheets.length - 1
1423 var cn = "fund_" + id;
1424 if (!this.haveFundClass[cn]) {
1425 fieldmapper.standardRequest(
1426 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
1428 "params": [openils.User.authtoken, id],
1430 "oncomplete": function(r) {
1431 r = openils.Util.readResponse(r);
1432 self.fundBalanceState[id] = r;
1434 if (r[0] /* stop */)
1435 style = fundStyles.stop;
1436 else if (r[1] /* warning */)
1437 style = fundStyles.warning;
1438 self.fundStyleSheet.insertRule(
1439 "." + cn + " { " + style + " }",
1440 self.fundStyleSheet.cssRules.length
1442 self.haveFundClass[cn] = true;
1449 this._ensureCSSFundClasses = function(store) {
1451 "query": {"id": "*"},
1452 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
1456 this._updateFundSelectorStyle = function(widget, fund_id) {
1457 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
1458 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
1461 this.updateLidState = function(copy, row) {
1462 if (typeof(row) == "undefined") {
1464 'tr[copy_id="' + copy.id() + '"]', this.copyTbody
1469 var recv_link = nodeByName("receive", row);
1470 var unrecv_link = nodeByName("unreceive", row);
1471 var del_link = nodeByName("delete", row);
1472 var cxl_link = nodeByName("cancel", row);
1473 var cxl_reason_link = nodeByName("cancel_reason", row);
1475 if (copy.cancel_reason()) {
1476 openils.Util.hide(del_link.parentNode);
1477 openils.Util.hide(recv_link);
1478 openils.Util.hide(unrecv_link);
1479 openils.Util.hide(cxl_link);
1481 /* XXX the following may leak memory in a long lived table: dijits may not get destroyed... not positive. revisit. */
1482 var holds_reason = dojo.create(
1484 "style": "border-bottom: 1px dashed #000;",
1485 "innerHTML": "Cancelled" /* XXX [sic] and i18n */
1486 }, cxl_reason_link, "only"
1490 "label": "<em>" + copy.cancel_reason().label() +
1491 "</em><br />" + copy.cancel_reason().description(),
1492 "connectId": [holds_reason]
1493 }, dojo.create("span", null, cxl_reason_link, "last")
1495 openils.Util.show(cxl_reason_link, "inline");
1496 } else if (this.isPO) {
1497 openils.Util.hide(del_link.parentNode);
1498 openils.Util.hide(cxl_reason_link);
1500 /* Avoid showing (un)receive links, cancel links, for virt copies */
1501 if (copy.id() > 0) {
1502 if(copy.recv_time()) {
1503 openils.Util.hide(cxl_link);
1504 openils.Util.hide(recv_link);
1505 openils.Util.show(unrecv_link, "inline");
1506 unrecv_link.onclick = function() {
1507 if (confirm(localeStrings.UNRECEIVE_LID))
1508 self.issueReceive(copy, /* rollback */ true);
1511 openils.Util.hide(unrecv_link);
1512 openils.Util.show(recv_link, "inline");
1513 openils.Util.show(cxl_link, "inline");
1514 recv_link.onclick = function() {
1515 if (self.checkLiAlerts(copy.lineitem()))
1516 self.issueReceive(copy);
1518 cxl_link.onclick = function() {
1519 self.cancelLid(copy.id());
1523 openils.Util.hide(cxl_link);
1524 openils.Util.hide(unrecv_link);
1525 openils.Util.hide(recv_link);
1528 openils.Util.hide(unrecv_link);
1529 openils.Util.hide(recv_link);
1530 openils.Util.hide(cxl_reason_link);
1532 del_link.onclick = function() { self.deleteCopy(row) };
1533 openils.Util.show(del_link.parentNode);
1537 this.cancelLid = function(lid_id) {
1538 lidCancelDialog._lid_id = lid_id;
1539 openils.Util.show(lidCancelDialog.domNode.parentNode);
1540 lidCancelDialog.show();
1541 if (!lidCancelDialog._prepared) {
1542 var widget = new openils.widget.AutoFieldWidget({
1543 "fmField": "cancel_reason",
1544 "fmClass": "acqlid",
1545 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
1546 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1551 acqLidCancelButton.onClick = function() {
1552 if (w.attr("value")) {
1553 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
1555 lidCancelDialog._lid_id,
1559 lidCancelDialog.hide();
1562 lidCancelDialog._prepared = true;
1568 this._cancelLid = function(lid_id, reason) {
1569 fieldmapper.standardRequest(
1570 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
1571 "params": [openils.User.authtoken, lid_id, reason],
1573 "onresponse": function(r) {
1574 if (r = openils.Util.readResponse(r)) {
1576 for (var id in r.lid) {
1577 /* actually this should only iterate once */
1578 self.copyCache[id].cancel_reason(
1579 r.lid[id].cancel_reason
1581 self.updateLidState(self.copyCache[id]);
1590 this._confirmAlert = function(li, lin) {
1592 dojo.string.substitute(
1593 localeStrings.CONFIRM_LI_ALERT, [
1594 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1595 "title", "lineitem_marc_attr_definition"
1597 lin.alert_text().code(),
1598 lin.alert_text().description() || "",
1605 this.checkLiAlerts = function(li_id) {
1606 var li = this.liCache[li_id];
1608 var alert_notes = li.lineitem_notes().filter(
1609 function(o) { return Boolean(o.alert_text()); }
1612 /* this is _intentionally_ not done in a call to forEach() ... */
1613 for (var i = 0; i < alert_notes.length; i++) {
1614 if (this.noteAcks[alert_notes[i].id()])
1616 else if (!this._confirmAlert(li, alert_notes[i]))
1619 this.noteAcks[alert_notes[i].id()] = true;
1625 this.deleteCopy = function(row) {
1626 var copy = this.copyCache[row.getAttribute('copy_id')];
1627 copy.isdeleted(true);
1629 delete this.copyCache[copy.id()];
1630 this.copyTbody.removeChild(row);
1633 this._virtDfaCountsAsList = function() {
1635 for (var key in this.virtDfaCounts) {
1636 for (var i = 0; i < this.virtDfaCounts[key]; i++)
1642 this.confirmBreachedCopyFunds = function(copies) {
1643 var stop = 0, warning = 0;
1647 var state = self.fundBalanceState[o.fund()];
1648 if (state[0] /* stop */)
1650 else if (state[1] /* warning */)
1657 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
1658 } else if (warning) {
1659 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
1664 this.saveCopyChanges = function(liId) {
1670 for(var id in this.copyCache) {
1671 var c = this.copyCache[id];
1672 if(!c.isdeleted()) total++;
1673 if(c.isnew() || c.ischanged() || c.isdeleted()) {
1674 if(c.id() < 0) c.id(null);
1680 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
1683 if (copies.length > 0) {
1684 if (!this.confirmBreachedCopyFunds(copies))
1687 if (typeof(this._copy_count_cb) == "function")
1688 this._copy_count_cb(liId, total);
1690 openils.Util.show("acq-lit-update-copies-progress");
1691 fieldmapper.standardRequest(
1692 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1694 params: [openils.User.authtoken, copies],
1695 onresponse: function(r) {
1696 var res = openils.Util.readResponse(r);
1697 litUpdateCopiesProgress.update(res);
1699 oncomplete: function() {
1700 self.drawCopies(liId);
1701 openils.Util.hide("acq-lit-update-copies-progress");
1707 var dfa_list = this._virtDfaCountsAsList();
1708 if (dfa_list.length > 0) {
1709 fieldmapper.standardRequest(
1711 "open-ils.acq.distribution_formula.record_application"],
1714 "params": [openils.User.authtoken, dfa_list, liId],
1715 "onresponse": function(r) {
1716 var res = openils.Util.readResponse(r);
1717 if (res && res.length < dfa_list.length)
1718 alert(localeStrings.DFA_NOT_ALL);
1722 this.virtDfaCounts = {};
1726 this._updateCreatePoPrepayCheckbox = function(prepay) {
1727 var prepay = openils.Util.isTrue(prepay);
1728 this._prepayRequiredByVendor = prepay;
1729 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
1732 this._confirmPoPrepaySituation = function() {
1733 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
1734 if (want_prepay != this._prepayRequiredByVendor) {
1737 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
1738 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
1745 this.applySelectedLiAction = function(action) {
1749 case 'delete_selected':
1750 this._deleteLiList(self.getSelected());
1753 case 'create_order':
1755 if(!this.createPoProviderSelector) {
1756 var widget = new openils.widget.AutoFieldWidget({
1757 fmField : 'provider',
1759 searchFilter: {"active": "t"},
1760 parentNode : dojo.byId('acq-lit-po-provider'),
1762 "onChange": function() {
1764 self._updateCreatePoPrepayCheckbox(
1765 this.item.prepayment_required
1772 function(w) { self.createPoProviderSelector = w; }
1776 if(!this.createPoAgencySelector) {
1777 var widget = new openils.widget.AutoFieldWidget({
1778 fmField : 'ordering_agency',
1780 parentNode : dojo.byId('acq-lit-po-agency'),
1781 orgLimitPerms : ['CREATE_PURCHASE_ORDER'],
1784 function(w) { self.createPoAgencySelector = w; }
1789 acqLitPoCreateDialog.show();
1792 case 'save_picklist':
1793 this._loadPLSelect();
1794 acqLitSavePlDialog.show();
1797 case 'selector_ready':
1799 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
1800 acqLitChangeLiStateDialog.show();
1811 case 'rollback_receive_po':
1812 this.rollbackPoReceive();
1815 case 'create_assets':
1816 this.createAssets();
1819 case 'export_attr_list':
1820 this.chooseExportAttr();
1823 case 'add_brief_record':
1825 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
1827 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
1831 case "cancel_lineitems":
1832 this.maybeCancelLineitems();
1835 case "change_claim_policy":
1836 var li_list = this.getSelected();
1837 this.claimPolicyPicker.attr("value", null);
1838 liClaimPolicyDialog.show();
1839 liClaimPolicySave.onClick = function() {
1840 self.changeClaimPolicy(
1842 self.claimPolicyPicker.attr("value"),
1845 function(li) { self.setClaimPolicyControl(li); }
1847 liClaimPolicyDialog.hide();
1855 this.changeClaimPolicy = function(li_list, value, callback) {
1857 function(li) { li.claim_policy(value); }
1859 fieldmapper.standardRequest(
1860 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
1861 "params": [openils.User.authtoken, li_list],
1863 "oncomplete": function(r) {
1864 r = openils.Util.readResponse(r);
1865 if (callback) callback(r);
1871 this.createAssets = function() {
1872 if(!this.isPO) return;
1873 if(!confirm(localeStrings.CREATE_PO_ASSETS_CONFIRM)) return;
1874 this.show('acq-lit-progress-numbers');
1876 fieldmapper.standardRequest(
1877 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
1879 params: [this.authtoken, this.isPO],
1880 onresponse: function(r) {
1881 var resp = openils.Util.readResponse(r);
1882 self._updateProgressNumbers(resp, true);
1888 this.maybeCancelLineitems = function() {
1889 openils.Util.show("acq-lit-cancel-reason", "inline");
1890 if (!acqLitCancelLineitemsButton._prepared) {
1891 var widget = new openils.widget.AutoFieldWidget({
1892 "fmField": "cancel_reason",
1894 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
1895 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1900 acqLitCancelLineitemsButton.onClick = function() {
1901 if (w.attr("value")) {
1902 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
1903 self._cancelLineitems(w.attr("value"));
1905 openils.Util.hide("acq-lit-cancel-reason");
1908 acqLitCancelLineitemsButton._prepared = true;
1914 this._cancelLineitems = function(reason) {
1915 var id_list = this.getSelected().map(function(o) { return o.id(); });
1916 fieldmapper.standardRequest(
1917 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
1918 "params": [openils.User.authtoken, id_list, reason],
1920 "onresponse": function(r) {
1921 if (r = openils.Util.readResponse(r)) {
1923 for (var id in r.li) {
1924 self.liCache[id].state(r.li[id].state);
1925 self.liCache[id].cancel_reason(
1926 r.li[id].cancel_reason
1928 self.updateLiState(self.liCache[id]);
1931 if (r.lid && self.copyCache) {
1932 for (var id in r.lid) {
1933 if (self.copyCache[id]) {
1934 self.copyCache[id].cancel_reason(
1935 r.lid[id].cancel_reason
1937 self.updateLidState(self.copyCache[id]);
1947 this.chooseExportAttr = function() {
1948 if (!acqLitExportAttrSelector._li_setup) {
1950 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
1952 "data": acqliad.toStoreData(
1954 "acqliad", {"code": li_exportable_attrs}
1959 acqLitExportAttrSelector.setValue();
1960 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
1961 acqLitExportAttrSelector._li_setup = true;
1963 openils.Util.show("acq-lit-export-attr-holder", "inline");
1966 this.exportAttrList = function() {
1967 var attr_def = acqLitExportAttrSelector.item;
1968 var li_list = this.getSelected();
1969 var value_list = li_list.map(
1971 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1972 attr_def.code, "lineitem_marc_attr_definition"
1975 ).filter(function(attr) { return Boolean(attr); });
1977 if (value_list.length > 0) {
1978 if (value_list.length < li_list.length) {
1980 dojo.string.substitute(
1981 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
1988 openils.XUL.contentToFileSaveDialog(
1989 value_list.join("\n"),
1990 localeStrings.EXPORT_SAVE_DIALOG_TITLE
1996 alert(dojo.string.substitute(
1997 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
2001 openils.Util.hide("acq-lit-export-attr-holder");
2004 this.printPO = function() {
2005 if(!this.isPO) return;
2006 progressDialog.show(true);
2007 fieldmapper.standardRequest(
2008 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
2010 params: [this.authtoken, this.isPO, 'html'],
2011 oncomplete: function(r) {
2012 progressDialog.hide();
2013 var evt = openils.Util.readResponse(r);
2014 if(evt && evt.template_output()) {
2015 win = window.open('','', 'resizable,width=800,height=600,scrollbars=1');
2016 win.document.body.innerHTML = evt.template_output().data();
2024 this.receivePO = function() {
2025 if (!this.isPO) return;
2027 for (var id in this.liCache) {
2028 /* assumption: liCache reflects exactly the
2029 * set of LIs that belong to our PO */
2030 if (this.liCache[id].state() != "received" &&
2031 !this.checkLiAlerts(id)) return;
2034 this.show('acq-lit-progress-numbers');
2036 fieldmapper.standardRequest(
2037 ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
2039 params: [this.authtoken, this.isPO],
2040 onresponse : function(r) {
2041 var resp = openils.Util.readResponse(r);
2042 self._updateProgressNumbers(resp, true);
2048 this.issueReceive = function(obj, rollback) {
2049 /* (For now) there shall be no marking LI or LIDs (un)received
2050 * except from the actual "view PO" interface. */
2051 if (!this.isPO) return;
2054 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
2056 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
2058 progressDialog.show(true);
2059 fieldmapper.standardRequest(
2060 ["open-ils.acq", method], {
2062 "params": [this.authtoken, obj.id()],
2063 "onresponse": function(r) {
2064 self.handleReceive(openils.Util.readResponse(r));
2065 progressDialog.hide();
2072 * Handles the responses from receive and rollback ML calls.
2074 this.handleReceive = function(resp) {
2077 for (var li_id in resp.li) {
2078 for (var key in resp.li[li_id])
2079 self.liCache[li_id][key](resp.li[li_id][key]);
2080 self.updateLiState(self.liCache[li_id]);
2084 if (typeof(self.poUpdateCallback) == "function")
2085 self.poUpdateCallback(resp.po);
2088 for (var lid_id in resp.lid) {
2089 for (var key in resp.lid[lid_id])
2090 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
2091 self.updateLidState(self.copyCache[lid_id]);
2097 this.rollbackPoReceive = function() {
2098 if(!this.isPO) return;
2099 if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
2100 this.show('acq-lit-progress-numbers');
2102 fieldmapper.standardRequest(
2103 ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
2105 params: [this.authtoken, this.isPO],
2106 onresponse : function(r) {
2107 var resp = openils.Util.readResponse(r);
2108 self._updateProgressNumbers(resp, true);
2114 this._updateProgressNumbers = function(resp, reloadOnComplete) {
2116 dojo.byId('acq-pl-lit-li-processed').innerHTML = resp.li;
2117 dojo.byId('acq-pl-lit-lid-processed').innerHTML = resp.lid;
2118 dojo.byId('acq-pl-lit-debits-processed').innerHTML = resp.debits_accrued;
2119 dojo.byId('acq-pl-lit-bibs-processed').innerHTML = resp.bibs;
2120 dojo.byId('acq-pl-lit-indexed-processed').innerHTML = resp.indexed;
2121 dojo.byId('acq-pl-lit-copies-processed').innerHTML = resp.copies;
2122 if(resp.complete && reloadOnComplete)
2123 location.href = location.href;
2127 this._createPO = function(fields) {
2128 this.show('acq-lit-progress-numbers');
2129 var po = new fieldmapper.acqpo();
2130 po.provider(this.createPoProviderSelector.attr('value'));
2131 po.ordering_agency(this.createPoAgencySelector.attr('value'));
2132 po.prepayment_required(fields.prepayment_required[0] ? true : false);
2134 var selected = this.getSelected( (fields.create_from == 'all') );
2135 if(selected.length == 0) return;
2137 var max = selected.length * 3;
2140 fieldmapper.standardRequest(
2141 ['open-ils.acq', 'open-ils.acq.purchase_order.create'],
2144 openils.User.authtoken,
2147 lineitems : selected.map(function(li) { return li.id() }),
2148 create_assets : fields.create_assets[0],
2152 onresponse : function(r) {
2153 var resp = openils.Util.readResponse(r);
2154 self._updateProgressNumbers(resp);
2156 location.href = oilsBasePath + '/acq/po/view/' + resp.purchase_order.id();
2162 this._deleteLiList = function(list, idx) {
2163 if(idx == null) idx = 0;
2164 if(idx >= list.length) return;
2165 var liId = list[idx].id();
2166 fieldmapper.standardRequest(
2167 ['open-ils.acq', 'open-ils.acq.lineitem.delete'],
2169 params: [openils.User.authtoken, liId],
2170 oncomplete: function(r) {
2171 self.removeLineitem(liId);
2172 self._deleteLiList(list, ++idx);
2178 this.editOrderMarc = function(li) {
2180 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
2181 to true in about:config */
2183 if(!openils.XUL.enableXPConnect()) return;
2185 if(openils.XUL.isXUL()) {
2186 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
2188 win = window.open('/xul/server/cat/marcedit.xul');
2192 record : {marc : li.marc()},
2194 label: 'Save Record', // XXX I18N
2195 func: function(xmlString) {
2197 fieldmapper.standardRequest(
2198 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
2200 params: [openils.User.authtoken, li],
2201 oncomplete: function(r) {
2202 openils.Util.readResponse(r);
2204 self.drawInfo(li.id())
2213 this._savePl = function(values) {
2215 var selected = this.getSelected( (values.which == 'all') );
2216 openils.Util.show('acq-lit-generic-progress');
2218 if(values.new_name) {
2219 openils.acq.Picklist.create(
2220 {name: values.new_name},
2222 self._updateLiList(id, selected, 0,
2224 location.href = oilsBasePath + '/acq/picklist/view/' + id;
2228 } else if(values.existing_pl) {
2229 // update lineitems to use an existing picklist
2230 self._updateLiList(values.existing_pl, selected, 0,
2232 location.href = oilsBasePath + '/acq/picklist/view/' + values.existing_pl;
2237 this._updateLiState = function(values, state) {
2239 var selected = this.getSelected( (values.which == 'all') );
2240 if(!selected.length) return;
2241 dojo.forEach(selected, function(li) {li.state(state);});
2242 self._updateLiList(null, selected, 0,
2243 // TODO consider inline updates for efficiency
2244 function() { location.href = location.href }
2248 this._updateLiList = function(pl, list, idx, oncomplete) {
2249 if(idx >= list.length) return oncomplete();
2251 if(pl != null) li.picklist(pl);
2252 litGenericProgress.update({maximum: list.length, progress: idx});
2253 new openils.acq.Lineitem({lineitem:li}).update(
2255 self._updateLiList(pl, list, ++idx, oncomplete);
2260 this._loadPLSelect = function() {
2261 if(this._plSelectLoaded) return;
2263 function handleResponse(r) {
2264 plList.push(r.recv().content());
2266 var method = 'open-ils.acq.picklist.user.retrieve';
2267 fieldmapper.standardRequest(
2268 ['open-ils.acq', method],
2270 params: [this.authtoken],
2271 onresponse: handleResponse,
2272 oncomplete: function() {
2273 self._plSelectLoaded = true;
2274 acqLitAddExistingSelect.store =
2275 new dojo.data.ItemFileReadStore({data:acqpl.toStoreData(plList)});
2276 acqLitAddExistingSelect.setValue();
2282 this.showRealCopyEditUI = function(li) {
2287 this._fetchLineitem(li.id(),
2289 li = self.liCache[li.id()] = fullLi;
2293 id : li.lineitem_details().map(
2294 function(item) { return item.eg_copy_id() }
2298 oncomplete : function(r) {
2300 var r_list = openils.Util.readResponse( r );
2301 for (var i = 0; i < r_list.length; i++) {
2302 var copy = r_list[i];
2303 var volId = copy.call_number();
2304 var volume = self.volCache[volId];
2306 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2308 copy.call_number(volume);
2309 copyList.push(copy);
2312 // If we need to, we can pass in an update_copy function to handle the update instead of volume_item_creator
2313 xulG.volume_item_creator( { 'existing_copies' : copyList } );
2316 alert('error in oncomplete: ' + E);
2327 this.saveRealCopies = function() {
2328 progressDialog.show(true);
2329 var list = this.realCopyList.filter(function(copy) { return copy.ischanged(); });
2330 this.pcrud.update(list, {oncomplete: function() {
2331 progressDialog.hide();
2336 // grab the li-details for this lineitem, grab the linked copies and volumes, add them to the table
2337 this.showRealCopies = function(li) {
2338 while(this.realCopiesTbody.childNodes[0])
2339 this.realCopiesTbody.removeChild(this.realCopiesTbody.childNodes[0]);
2340 this.show('real-copies');
2342 this.realCopyList = [];
2344 var tabIndex = 1000;
2347 acqLitSaveRealCopies.onClick = function() {
2348 self.saveRealCopies();
2351 this._fetchLineitem(li.id(),
2353 li = self.liCache[li.id()] = fullLi;
2357 id : li.lineitem_details().map(
2358 function(item) { return item.eg_copy_id() }
2363 onresponse : function(r) {
2364 var copy = openils.Util.readResponse(r);
2365 var volId = copy.call_number();
2366 var volume = self.volCache[volId];
2368 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2370 self.addRealCopy(volume, copy, tabIndex++);
2378 this.addRealCopy = function(volume, copy, tabIndex) {
2379 var row = this.realCopiesRow.cloneNode(true);
2380 this.realCopyList.push(copy);
2384 ['owning_lib', 'location', 'circ_modifier', 'label', 'barcode'],
2387 var isvol = (field == 'owning_lib' || field == 'label');
2388 var widget = new openils.widget.AutoFieldWidget({
2390 fmObject : isvol ? volume : copy,
2391 parentNode : nodeByName(field, row),
2392 readOnly : (field != 'barcode'),
2395 var widgetDrawn = null;
2397 if(field == 'barcode') {
2399 widgetDrawn = function(w, ww) {
2400 var node = w.domNode;
2401 node.setAttribute('tabindex', ''+tabIndex);
2403 // on enter, select the next barcode input
2404 dojo.connect(w, 'onKeyDown',
2406 if(e.keyCode == dojo.keys.ENTER) {
2407 var ti = node.getAttribute('tabindex');
2408 var nextNode = dojo.query('[tabindex=' + String(Number(ti) + 1) + ']', self.realCopiesTbody)[0];
2409 if(nextNode) nextNode.select();
2414 dojo.connect(w, 'onChange',
2416 if(!val || val == copy.barcode()) return;
2417 copy.ischanged(true);
2423 if(self.realCopiesTbody.getElementsByTagName('TR').length == 0)
2428 widget.build(widgetDrawn);
2432 this.realCopiesTbody.appendChild(row);
2433 if(selectNode) selectNode.select();