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 * TODO: move to dojo/i18n
355 option.innerHTML = option.innerHTML.replace(
356 /(^.+)(.*)( existing.+$)/, "$1" + String(count) + "$3"
358 option.onclick = function() { self.claimDialog.show(li); };
361 this.checkClaimEligibility = function(li, row) {
362 this.claimEligibleLidByLi[li.id()] = [];
363 fieldmapper.standardRequest(
364 ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
365 "params": [openils.User.authtoken, {"lineitem": li.id()}],
367 "onresponse": function(r) {
368 if (r = openils.Util.readResponse(r)) {
369 self.claimEligibleLidByLi[li.id()].push(
374 "oncomplete": function() {
375 self.reconsiderClaimControl(li, row);
381 this.updateLiNotesCount = function(li, row) {
382 if (typeof(row) == "undefined")
383 row = dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
385 var has_notes = (li.lineitem_notes().filter(
386 function(o) { return Boolean (o.alert_text()); }
389 /* U+2691 is the code point for a filled-in flag character */
390 nodeByName("notes_alert_flag", row).innerHTML =
391 has_notes ? "⚑" : "";
392 nodeByName("noteslink", row).style.fontStyle =
393 has_notes ? "italic" : "normal";
394 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
397 /* XXX NOT related to _updateLiState(). rethink */
398 this.updateLiState = function(li, row) {
399 if (typeof(row) == "undefined")
400 row = dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
402 var actReceive = nodeByName("action_mark_recv", row);
403 var actUnRecv = nodeByName("action_mark_unrecv", row);
404 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
405 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
407 var actNewInvoice = nodeByName('action_new_invoice', row);
408 var actLinkInvoice = nodeByName('action_link_invoice', row);
409 var actViewInvoice = nodeByName('action_view_invoice', row);
411 var state_cell = nodeByName("li_state", row);
413 if (li.state() == "cancelled") {
414 if (typeof li.cancel_reason() == "object") {
415 var holds_state = dojo.create(
417 "style": "border-bottom: 1px dashed #000;",
418 "innerHTML": li.state()
419 }, state_cell, "only"
423 "label": "<em>" + li.cancel_reason().label() +
424 "</em><br />" + li.cancel_reason().description(),
425 "connectId": [holds_state]
426 }, dojo.create("span", null, state_cell, "last")
429 state_cell.innerHTML = li.state(); // TODO i18n state labels
432 state_cell.innerHTML = li.state(); // TODO i18n state labels
436 /* handle row coloring for based on LI state */
437 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
438 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
440 /* handle links that appear/disappear based on whether LI is received */
444 actNewInvoice.onclick = function() {
445 location.href = oilsBasePath + '/acq/invoice/view?create=1&attach_li=' + li.id();
446 nodeByName("action_none", row).selected = true;
448 actLinkInvoice.onclick = function() {
449 self.invoiceLinkDialogManager.target = li;
450 acqLitLinkInvoiceDialog.show();
451 nodeByName("action_none", row).selected = true;
453 actViewInvoice.onclick = function() {
454 location.href = oilsBasePath +
455 "/acq/search/unified?so=" +
456 base64Encode({"jub":[{"id": li.id()}]}) +
458 nodeByName("action_none", row).selected = true;
461 actNewInvoice.disabled = false;
462 actLinkInvoice.disabled = false;
463 actViewInvoice.disabled = false;
467 actReceive.disabled = false;
468 actReceive.onclick = function() {
469 if (self.checkLiAlerts(li.id()))
470 self.issueReceive(li);
471 nodeByName("action_none", row).selected = true;
476 actUnRecv.disabled = false;
477 actUnRecv.onclick = function() {
478 if (confirm(localeStrings.UNRECEIVE_LI))
479 self.issueReceive(li, /* rollback */ true);
480 nodeByName("action_none", row).selected = true;
482 // TODO we should allow editing before receipt, in which case the
483 // test should be "if 1 or more real (acp) copies exist
484 actUpdateBarcodes.disabled = false;
485 actUpdateBarcodes.onclick = function() {
486 self.showRealCopyEditUI(li);
487 nodeByName("action_none", row).selected = true;
489 actHoldingsMaint.disabled = false;
490 actHoldingsMaint.onclick = self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
498 this._setAlertStore = function() {
499 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
501 "data": acqliat.toStoreData(
503 "acqliat", {"id": {"!=": null}}
508 acqLitAlertAlertText.setValue(); /* make the store "live" */
509 acqLitAlertAlertText._store_ready = true;
513 * Draws and shows the lineitem notes pane
515 this.drawLiNotes = function(li) {
518 if (!acqLitAlertAlertText._store_ready)
519 this._setAlertStore();
522 li.lineitem_notes().sort(
524 if(a.edit_time() < b.edit_time()) return 1;
530 while(this.liNotesTbody.childNodes[0])
531 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
534 acqLitCreateNoteSubmit.onClick = function() {
535 var value = acqLitCreateNoteText.attr('value');
537 var note = new fieldmapper.acqlin();
540 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
543 note.lineitem(li.id());
545 self.updateLiNotes(li, note);
546 acqLitCreateNoteVendorPublic.attr("checked", false);
547 acqLitCreateNoteText.attr("value", "");
550 acqLitCreateAlertSubmit.onClick = function() {
551 if (!acqLitAlertAlertText.item) {
552 alert(localeStrings.ALERT_UNSELECTED);
556 var alert_text = new fieldmapper.acqliat().fromStoreItem(
557 acqLitAlertAlertText.item
559 var value = acqLitAlertNoteValue.attr("value") || "";
561 var note = new fieldmapper.acqlin();
563 note.lineitem(li.id());
565 note.alert_text(alert_text);
567 self.updateLiNotes(li, note);
570 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
574 * Draws a single lineitem note in the notes pane
576 this.addLiNote = function(li, note) {
577 if(note.isdeleted()) return;
579 var row = self.liNotesRow.cloneNode(true);
580 nodeByName("value", row).innerHTML = note.value();
581 var alert_node = nodeByName("alert_code", row);
582 if (note.alert_text()) {
583 alert_node.innerHTML = note.alert_text().code();
584 if (note.alert_text().description()) {
587 "connectId": [alert_node],
588 "label": note.alert_text().description()
589 }, dojo.create("span", null, alert_node, "after")
594 if (openils.Util.isTrue(note.vendor_public()))
595 nodeByName("vendor_public", row).innerHTML =
596 localeStrings.VENDOR_PUBLIC;
598 nodeByName("delete", row).onclick = function() {
599 note.isdeleted(true);
600 self.liNotesTbody.removeChild(row);
601 self.updateLiNotes(li);
604 if(note.edit_time()) {
605 nodeByName("edit_time", row).innerHTML =
606 dojo.date.locale.format(
607 dojo.date.stamp.fromISOString(note.edit_time()),
608 {formatLength:'short'});
611 self.liNotesTbody.appendChild(row);
615 * Updates any new/changed/deleted notes on the server
617 this.updateLiNotes = function(li, newNote) {
623 notes = li.lineitem_notes().filter(
625 if(note.ischanged() || note.isnew() || note.isdeleted())
631 if(notes.length == 0) return;
632 progressDialog.show();
634 fieldmapper.standardRequest(
635 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
637 params : [this.authtoken, notes],
638 onresponse : function(r) {
639 var resp = openils.Util.readResponse(r);
644 // remove the old changed notes
646 dojo.forEach(li.lineitem_notes(),
648 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
652 li.lineitem_notes(list);
655 progressDialog.hide();
656 self.updateLiNotesCount(li);
657 self.drawLiNotes(li);
661 progressDialog.update(resp);
662 var newnote = resp.note;
664 if(!newnote.isdeleted()) {
665 newnote.isnew(false);
666 newnote.ischanged(false);
667 li.lineitem_notes().push(newnote);
674 this.updateLiPrice = function(input, li) {
676 var price = input.value;
677 if(Number(price) == Number(li.estimated_unit_price())) return;
679 fieldmapper.standardRequest(
680 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
682 params : [this.authtoken, li.id(), price],
683 oncomplete : function(r) {
684 openils.Util.readResponse(r);
685 li.estimated_unit_price(price); // update local copy
691 this.removeLineitem = function(liId) {
692 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
693 delete this.liCache[liId];
694 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
697 this.drawInfo = function(liId) {
698 if (!this._isRelatedViewer) {
699 var d = dojo.byId("acq-lit-info-related");
700 if (!this.relCache[liId]) {
701 fieldmapper.standardRequest(
704 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
707 "params": [openils.User.authtoken, liId],
708 "onresponse": function(r) {
709 self.relCache[liId] = openils.Util.readResponse(r);
710 nodeByName("related_number", d).innerHTML =
713 self.relCache[liId] >1 ? "show" : "hide"
719 nodeByName("related_number", d).innerHTML = this.relCache[liId];
720 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
725 openils.acq.Lineitem.fetchAttrDefs(
727 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
732 this._fetchLineitem = function(liId, handler) {
734 var li = this.liCache[liId];
735 if(li && li.marc() && li.lineitem_details())
738 fieldmapper.standardRequest(
739 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve'],
742 params: [self.authtoken, liId, {
744 flesh_cancel_reason: true,
745 flesh_li_details: true,
746 flesh_fund_debit: true }],
748 oncomplete: function(r) {
749 var li = openils.Util.readResponse(r);
756 this._drawInfo = function(li) {
758 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
761 openils.Util.hide('acq-lit-marc-order-record-label');
762 openils.Util.hide(acqLitEditOrderMarc.domNode);
763 openils.Util.show('acq-lit-marc-real-record-label');
765 openils.Util.show('acq-lit-marc-order-record-label');
766 openils.Util.show(acqLitEditOrderMarc.domNode);
767 openils.Util.hide('acq-lit-marc-real-record-label');
770 this.drawMarcHTML(li);
771 this.infoTbody = dojo.byId('acq-lit-info-tbody');
774 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
775 while(this.infoTbody.childNodes[0])
776 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
778 for(var i = 0; i < li.attributes().length; i++) {
779 var attr = li.attributes()[i];
780 var row = this.infoRow.cloneNode(true);
782 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
783 var name = openils.acq.Lineitem.attrDefs[type].filter(
785 return (a.code() == attr.attr_name());
787 ).pop().description();
789 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
790 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
791 this.infoTbody.appendChild(row);
794 if (!this._isRelatedViewer) {
795 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
796 oilsBasePath + "/acq/lineitem/related/" + li.id();
801 openils.Util.show('acq-lit-info-cat-link');
802 var link = dojo.byId('acq-lit-info-cat-link').getElementsByTagName('a')[0];
804 if(openils.XUL.isXUL()) {
806 link.setAttribute('href', 'javascript:void(0);');
807 link.onclick = this.generateMakeRecTab( li.eg_bib_id() );
810 var href = link.getAttribute('href');
812 link.setAttribute('href', href + li.eg_bib_id());
815 openils.Util.hide('acq-lit-info-cat-link');
819 this.generateMakeRecTab = function(bib_id,default_view, row) {
823 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
826 show_nav_buttons : true,
827 show_print_button : true,
828 opac_url : xulG.url_prefix(xulG.urls.opac_rdetail + '?r=' + bib_id),
829 default_view : default_view
833 if(row) nodeByName("action_none", row).selected = true;
837 this.drawMarcHTML = function(li) {
838 var params = [null, true, li.marc()];
840 params = [li.eg_bib_id(), true];
842 fieldmapper.standardRequest(
843 ['open-ils.search', 'open-ils.search.biblio.record.html'],
846 oncomplete: function(r) {
847 dojo.byId('acq-lit-marc-div').innerHTML =
848 openils.Util.readResponse(r);
854 this.drawCopies = function(liId) {
858 this.copyWidgetCache = {};
859 this.oldCopyWidgetCache = {};
860 this.virtDfaCounts = {};
861 this.realDfaCache = {};
864 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
865 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
866 acqLitCopyCountInput.attr('value', '0');
868 while(this.copyTbody.childNodes[0])
869 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
871 this._drawBatchCopyWidgets();
873 this._drawDistribApplied(liId);
875 this._fetchDistribFormulas(
877 openils.acq.Lineitem.fetchAttrDefs(
879 self._fetchLineitem(liId, function(li){self._drawCopies(li);});
886 this._saveDistribAppliedTemplates = function() {
887 if (!this._appliedDistribTemplate) {
888 this._appliedDistribTemplate =
889 dojo.byId("acq-lit-distrib-applied-tbody").
890 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
891 dojo.attr(this._appliedDistribTemplate, "id");
895 this._drawDistribApplied = function(liId) {
896 /* Build this table while hidden to prevent rendering artifacts */
897 openils.Util.hide("acq-lit-distrib-applied-tbody");
899 this._saveDistribAppliedTemplates();
901 /* Remove any rows in the table from previous populations */
902 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
903 forEach(dojo.destroy);
905 /* Unregister all dijits previously created (for some reason this isn't
906 * covered by the above destroy calls). */
907 dijit.registry.forEach(
908 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
911 /* Populate the table with our liId */
913 fieldmapper.standardRequest(
915 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
918 "params": [self.authtoken, liId],
919 "onresponse": function(r) {
920 var dfa = openils.Util.readResponse(r);
923 self.realDfaCache[dfa.id()] = dfa;
924 self._drawDistribAppliedUnit(dfa);
927 "oncomplete": function() {
928 /* Reveal built table */
931 "acq-lit-distrib-applied-tbody", "table-row-group"
939 this._drawDistribAppliedUnit = function(dfa) {
941 var row = dojo.query(
942 'tr[formula="' + dfa.formula().id() + '"]',
943 "acq-lit-distrib-applied-tbody"
948 row = dojo.clone(this._appliedDistribTemplate);
949 dojo.attr(row, "formula", dfa.formula().id());
950 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
953 var td = dojo.query("td", row)[0];
955 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
956 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
959 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
961 new dijit.form.Button(
963 "onClick": function() {
964 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
968 /* XXX I /cannot/ make the following work in as a CSS class
969 * for some reason. So frustrating... */
970 "style": function(id) {
972 "font-weight: bold; color: #c00;" :
974 }(dfa.id()) + "margin: 0 6px;display: inline;"
975 }, "dfa-button-" + dfa.id()
979 "connectId": ["dfa-button-" + dfa.id()],
980 "label": dojo.string.substitute(
981 localeStrings.DFA_TIP, dfa.id() > 0 ? [
982 openils.User.formalName(dfa.creator()),
983 dojo.date.locale.format(
984 dojo.date.stamp.fromISOString(dfa.create_time()),
985 {"formatLength":"short"}
987 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
989 }, "dfa-tip-" + dfa.id()
993 this.deleteDfa = function(dfa) {
994 if (dfa.id() > 0) { /* real */
995 this.pcrud.eliminate(
998 "oncomplete": function() {
999 self._removeDistribApplied(dfa.id());
1000 delete self.realDfaCache[dfa.id()];
1004 } else { /* virtual */
1005 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
1006 this.virtDfaCounts[dfa.formula().id()] = 0;
1007 /* hasn't been saved yet, so no need to do anything server side */
1008 this._removeDistribApplied(dfa.id());
1013 this._removeDistribApplied = function(dfaId) {
1014 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
1015 dijit.registry.forEach(
1016 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
1018 this._removeDistribAppliedEmptyRows();
1021 this._removeAllDistribAppliedVirtual = function() {
1022 /* Unregister dijits */
1023 dijit.registry.forEach(
1024 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
1026 this._removeDistribAppliedEmptyRows();
1029 this._removeDistribAppliedEmptyRows = function() {
1030 /* Remove any rows with no DFA at all */
1031 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
1033 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
1039 * Insert a new row into the distribution formula selection form
1041 this._addDistribFormulaRow = function() {
1044 if (!self.distribForms) {
1045 // no formulas, hide the form
1046 openils.Util.hide('acq-lit-distrib-formula-tbody');
1050 if(!this.distribFormulaTemplate)
1051 this.distribFormulaTemplate =
1052 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
1054 var row = this.distribFormulaTemplate.cloneNode(true);
1055 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
1057 this.dfSelector = new dijit.form.FilteringSelect(
1058 {"labelAttr": "dynLabel", "labelType": "html"},
1059 nodeByName("selector", row)
1061 this._updateFormulaStore();
1062 this.dfSelector.fetchProperties =
1063 {"sort": [{"attribute": "use_count", "descending": true}]};
1065 var apply = new dijit.form.Button(
1066 {"label": localeStrings.APPLY},
1067 nodeByName('set_button', row)
1070 var reset = new dijit.form.Button(
1071 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
1072 nodeByName("reset_button", row)
1075 dojo.connect(apply, 'onClick',
1077 var form_id = self.dfSelector.attr("value");
1078 if(!form_id) return;
1079 self._applyDistribFormula(form_id);
1080 reset.attr("disabled", false);
1084 dojo.connect(reset, 'onClick',
1086 self.restoreCopyFieldsBeforeDF();
1087 self.virtDfaCounts = {};
1088 self.virtDfaId = -1;
1090 self._updateFormulaStore();
1091 self._removeAllDistribAppliedVirtual();
1092 reset.attr("disabled", "true");
1099 * Applies a distrib formula to the current set of copies
1101 this._applyDistribFormula = function(formula) {
1102 if(!formula) return;
1104 formula = this.distribForms.filter(
1105 function(form) { return form.id() == formula; }
1108 var copyRows = dojo.query('tr', self.copyTbody);
1110 if (this.dfeOffset >= copyRows.length) {
1111 alert(localeStrings.OUT_OF_COPIES);
1115 var entries_applied = 0;
1117 var rowIndex = this.dfeOffset;
1118 rowIndex < copyRows.length;
1122 var row = copyRows[rowIndex];
1123 var copy_id = row.getAttribute('copy_id');
1124 var copyWidgets = this.copyWidgetCache[copy_id];
1125 var entryIndex = this.dfeOffset;
1128 // find the correct entry for the current row
1129 dojo.forEach(formula.entries(),
1132 entryIndex += e.item_count();
1133 if(entryIndex > rowIndex)
1141 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
1142 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
1145 this.saveCopyFieldsBeforeDF(copy_id);
1146 this._copy_fields_for_acqdf.forEach(
1148 if(entry[field]()) {
1149 copyWidgets[field].attr('value', (entry[field]()));
1156 if (entries_applied) {
1157 this.virtDfaCounts[formula.id()] =
1158 ++(this.virtDfaCounts[formula.id()]) || 1;
1159 this._updateFormulaStore();
1160 this._drawDistribAppliedUnit(
1162 var dfa = new acqdfa();
1163 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
1166 this.dfeOffset += entries_applied;
1171 * This function updates the DF store for the dropdown so that use_counts
1172 * can reflect DF applications from this session before they're saved
1175 this._updateFormulaStore = function() {
1176 this.dfSelector.store = new dojo.data.ItemFileReadStore(
1178 "data": self._labelFormulasWithCounts(
1179 acqdf.toStoreData(self.distribForms)
1185 this.saveCopyFieldsBeforeDF = function(copy_id) {
1187 if (!this.oldCopyWidgetCache[copy_id]) {
1188 var copyWidgets = this.copyWidgetCache[copy_id];
1190 this.oldCopyWidgetCache[copy_id] = {};
1191 this._copy_fields_for_acqdf.forEach(
1193 self.oldCopyWidgetCache[copy_id][f] =
1194 copyWidgets[f].attr("value");
1200 this.restoreCopyFieldsBeforeDF = function() {
1202 for (var copy_id in this.oldCopyWidgetCache) {
1203 this._copy_fields_for_acqdf.forEach(
1205 self.copyWidgetCache[copy_id][f].attr(
1206 "value", self.oldCopyWidgetCache[copy_id][f]
1213 this._labelFormulasWithCounts = function(store_data) {
1214 for (var key in store_data.items) {
1215 var obj = store_data.items[key];
1216 obj.use_count = Number(obj.use_count); /* needed for sorting */
1218 if (this.virtDfaCounts[obj.id])
1219 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
1221 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
1222 obj.use_count + "]</span> " + obj.name;
1228 * This method formerly would not refetch the DF formulas if they'd been
1229 * loaded already, but now it always re-fetches, since use_count changes.
1231 this._fetchDistribFormulas = function(onload) {
1232 fieldmapper.standardRequest(
1234 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
1237 "params": [openils.User.authtoken],
1238 "oncomplete": function(r) {
1239 self.distribForms = openils.Util.readResponse(r);
1240 if(!self.distribForms || self.distribForms.length == 0) {
1241 self.distribForms = [];
1243 self._addDistribFormulaRow();
1250 this._drawBatchCopyWidgets = function() {
1251 var row = this.copyBatchRow;
1252 dojo.forEach(liDetailBatchFields,
1254 if(self.copyBatchRowDrawn) {
1255 self.copyBatchWidgets[field].attr('value', null);
1257 var widget = new openils.widget.AutoFieldWidget({
1260 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1261 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1262 searchFilter : (field == 'fund') ? {"active": "t"} : null,
1263 parentNode : dojo.query('[name='+field+']', row)[0],
1264 orgLimitPerms : ['CREATE_PICKLIST'],
1267 "labelType": (field == "fund") ? "html" : null
1269 noCache: (field == "fund"),
1274 if (field == "fund" && w.store)
1275 self._ensureCSSFundClasses(w.store);
1276 self.copyBatchWidgets[field] = w;
1279 if (field == "fund") {
1281 widget.widget, "onChange", function(val) {
1282 self._updateFundSelectorStyle(widget, val);
1289 this.copyBatchRowDrawn = true;
1292 this.batchCopyUpdate = function() {
1294 for(var k in this.copyWidgetCache) {
1295 var cache = this.copyWidgetCache[k];
1296 dojo.forEach(liDetailBatchFields, function(f) {
1297 var newval = self.copyBatchWidgets[f].attr('value');
1298 if(newval) cache[f].attr('value', newval);
1303 this._drawCopies = function(li) {
1306 // this button sets the total number of copies for a given lineitem
1307 acqLitAddCopyCount.onClick = function() {
1308 var count = acqLitCopyCountInput.attr('value');
1311 while(self.copyCount() < count)
1314 // delete rows if necessary
1315 var diff = self.copyCount() - count;
1317 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
1318 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
1319 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
1321 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1327 if(li.lineitem_details().length > 0) {
1328 dojo.forEach(li.lineitem_details(),
1330 self.addCopy(li, copy);
1338 this.copyCount = function() {
1340 for(var id in this.copyCache) {
1341 if(!this.copyCache[id].isdeleted())
1347 this.virtCopyId = -1;
1348 this.addCopy = function(li, copy) {
1349 var row = this.copyRow.cloneNode(true);
1350 this.copyTbody.appendChild(row);
1354 copy = new fieldmapper.acqlid();
1356 copy.id(this.virtCopyId--);
1357 copy.lineitem(li.id());
1360 this.copyCache[copy.id()] = copy;
1361 row.setAttribute('copy_id', copy.id());
1362 self.copyWidgetCache[copy.id()] = {};
1364 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1366 dojo.forEach(liDetailFields,
1369 if (field == "fund") {
1370 searchFilter = (copy.fund() ?
1371 {"-or": {"active": "t", "id": copy.fund()}} :
1374 searchFilter = null;
1376 var widget = new openils.widget.AutoFieldWidget({
1379 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1380 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1381 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1382 searchFilter : searchFilter,
1383 noCache: (field == "fund"),
1385 parentNode : dojo.query('[name='+field+']', row)[0],
1386 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
1387 readOnly : Boolean(copy.eg_copy_id())
1390 // make sure we capture the value from any async widgets
1392 if (field == "fund" && w.store)
1393 self._ensureCSSFundClasses(w.store);
1394 copy[field](ww.getFormattedValue())
1395 self.copyWidgetCache[copy.id()][field] = w;
1398 dojo.connect(widget.widget, 'onChange',
1400 if (field == "fund")
1401 self._updateFundSelectorStyle(widget, val);
1403 if (copy.isnew() || val != copy[field]()) {
1404 // prevent setting ischanged() automatically on widget load for existing copies
1405 copy[field](widget.getFormattedValue())
1406 copy.ischanged(true);
1413 this.updateLidState(copy, row);
1416 this._ensureCSSFundClass = function(id) {
1417 if (!this.fundStyleSheet) {
1419 "style", {"type": "text/css"},
1420 document.getElementsByTagName("head")[0], "last"
1422 this.fundStyleSheet = document.styleSheets[
1423 document.styleSheets.length - 1
1427 var cn = "fund_" + id;
1428 if (!this.haveFundClass[cn]) {
1429 fieldmapper.standardRequest(
1430 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
1432 "params": [openils.User.authtoken, id],
1434 "oncomplete": function(r) {
1435 r = openils.Util.readResponse(r);
1436 self.fundBalanceState[id] = r;
1438 if (r[0] /* stop */)
1439 style = fundStyles.stop;
1440 else if (r[1] /* warning */)
1441 style = fundStyles.warning;
1442 self.fundStyleSheet.insertRule(
1443 "." + cn + " { " + style + " }",
1444 self.fundStyleSheet.cssRules.length
1446 self.haveFundClass[cn] = true;
1453 this._ensureCSSFundClasses = function(store) {
1455 "query": {"id": "*"},
1456 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
1460 this._updateFundSelectorStyle = function(widget, fund_id) {
1461 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
1462 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
1465 this.updateLidState = function(copy, row) {
1466 if (typeof(row) == "undefined") {
1468 'tr[copy_id="' + copy.id() + '"]', this.copyTbody
1473 var recv_link = nodeByName("receive", row);
1474 var unrecv_link = nodeByName("unreceive", row);
1475 var del_link = nodeByName("delete", row);
1476 var cxl_link = nodeByName("cancel", row);
1477 var cxl_reason_link = nodeByName("cancel_reason", row);
1479 if (copy.cancel_reason()) {
1480 openils.Util.hide(del_link.parentNode);
1481 openils.Util.hide(recv_link);
1482 openils.Util.hide(unrecv_link);
1483 openils.Util.hide(cxl_link);
1485 /* XXX the following may leak memory in a long lived table: dijits may not get destroyed... not positive. revisit. */
1486 var holds_reason = dojo.create(
1488 "style": "border-bottom: 1px dashed #000;",
1489 "innerHTML": "Cancelled" /* XXX [sic] and i18n */
1490 }, cxl_reason_link, "only"
1494 "label": "<em>" + copy.cancel_reason().label() +
1495 "</em><br />" + copy.cancel_reason().description(),
1496 "connectId": [holds_reason]
1497 }, dojo.create("span", null, cxl_reason_link, "last")
1499 openils.Util.show(cxl_reason_link, "inline");
1500 } else if (this.isPO) {
1501 openils.Util.hide(del_link.parentNode);
1502 openils.Util.hide(cxl_reason_link);
1504 /* Avoid showing (un)receive links, cancel links, for virt copies */
1505 if (copy.id() > 0) {
1506 if(copy.recv_time()) {
1507 openils.Util.hide(cxl_link);
1508 openils.Util.hide(recv_link);
1509 openils.Util.show(unrecv_link, "inline");
1510 unrecv_link.onclick = function() {
1511 if (confirm(localeStrings.UNRECEIVE_LID))
1512 self.issueReceive(copy, /* rollback */ true);
1515 openils.Util.hide(unrecv_link);
1516 openils.Util.show(recv_link, "inline");
1517 openils.Util.show(cxl_link, "inline");
1518 recv_link.onclick = function() {
1519 if (self.checkLiAlerts(copy.lineitem()))
1520 self.issueReceive(copy);
1522 cxl_link.onclick = function() {
1523 self.cancelLid(copy.id());
1527 openils.Util.hide(cxl_link);
1528 openils.Util.hide(unrecv_link);
1529 openils.Util.hide(recv_link);
1532 openils.Util.hide(unrecv_link);
1533 openils.Util.hide(recv_link);
1534 openils.Util.hide(cxl_reason_link);
1536 del_link.onclick = function() { self.deleteCopy(row) };
1537 openils.Util.show(del_link.parentNode);
1541 this.cancelLid = function(lid_id) {
1542 lidCancelDialog._lid_id = lid_id;
1543 openils.Util.show(lidCancelDialog.domNode.parentNode);
1544 lidCancelDialog.show();
1545 if (!lidCancelDialog._prepared) {
1546 var widget = new openils.widget.AutoFieldWidget({
1547 "fmField": "cancel_reason",
1548 "fmClass": "acqlid",
1549 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
1550 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1555 acqLidCancelButton.onClick = function() {
1556 if (w.attr("value")) {
1557 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
1559 lidCancelDialog._lid_id,
1563 lidCancelDialog.hide();
1566 lidCancelDialog._prepared = true;
1572 this._cancelLid = function(lid_id, reason) {
1573 fieldmapper.standardRequest(
1574 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
1575 "params": [openils.User.authtoken, lid_id, reason],
1577 "onresponse": function(r) {
1578 if (r = openils.Util.readResponse(r)) {
1580 for (var id in r.lid) {
1581 /* actually this should only iterate once */
1582 self.copyCache[id].cancel_reason(
1583 r.lid[id].cancel_reason
1585 self.updateLidState(self.copyCache[id]);
1594 this._confirmAlert = function(li, lin) {
1596 dojo.string.substitute(
1597 localeStrings.CONFIRM_LI_ALERT, [
1598 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1599 "title", "lineitem_marc_attr_definition"
1601 lin.alert_text().code(),
1602 lin.alert_text().description() || "",
1609 this.checkLiAlerts = function(li_id) {
1610 var li = this.liCache[li_id];
1612 var alert_notes = li.lineitem_notes().filter(
1613 function(o) { return Boolean(o.alert_text()); }
1616 /* this is _intentionally_ not done in a call to forEach() ... */
1617 for (var i = 0; i < alert_notes.length; i++) {
1618 if (this.noteAcks[alert_notes[i].id()])
1620 else if (!this._confirmAlert(li, alert_notes[i]))
1623 this.noteAcks[alert_notes[i].id()] = true;
1629 this.deleteCopy = function(row) {
1630 var copy = this.copyCache[row.getAttribute('copy_id')];
1631 copy.isdeleted(true);
1633 delete this.copyCache[copy.id()];
1634 this.copyTbody.removeChild(row);
1637 this._virtDfaCountsAsList = function() {
1639 for (var key in this.virtDfaCounts) {
1640 for (var i = 0; i < this.virtDfaCounts[key]; i++)
1646 this.confirmBreachedCopyFunds = function(copies) {
1647 var stop = 0, warning = 0;
1651 var state = self.fundBalanceState[o.fund()];
1652 if (state[0] /* stop */)
1654 else if (state[1] /* warning */)
1661 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
1662 } else if (warning) {
1663 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
1668 this.saveCopyChanges = function(liId) {
1674 for(var id in this.copyCache) {
1675 var c = this.copyCache[id];
1676 if(!c.isdeleted()) total++;
1677 if(c.isnew() || c.ischanged() || c.isdeleted()) {
1678 if(c.id() < 0) c.id(null);
1684 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
1687 if (copies.length > 0) {
1688 if (!this.confirmBreachedCopyFunds(copies))
1691 if (typeof(this._copy_count_cb) == "function")
1692 this._copy_count_cb(liId, total);
1694 openils.Util.show("acq-lit-update-copies-progress");
1695 fieldmapper.standardRequest(
1696 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1698 params: [openils.User.authtoken, copies],
1699 onresponse: function(r) {
1700 var res = openils.Util.readResponse(r);
1701 litUpdateCopiesProgress.update(res);
1703 oncomplete: function() {
1704 self.drawCopies(liId);
1705 openils.Util.hide("acq-lit-update-copies-progress");
1711 var dfa_list = this._virtDfaCountsAsList();
1712 if (dfa_list.length > 0) {
1713 fieldmapper.standardRequest(
1715 "open-ils.acq.distribution_formula.record_application"],
1718 "params": [openils.User.authtoken, dfa_list, liId],
1719 "onresponse": function(r) {
1720 var res = openils.Util.readResponse(r);
1721 if (res && res.length < dfa_list.length)
1722 alert(localeStrings.DFA_NOT_ALL);
1726 this.virtDfaCounts = {};
1730 this._updateCreatePoPrepayCheckbox = function(prepay) {
1731 var prepay = openils.Util.isTrue(prepay);
1732 this._prepayRequiredByVendor = prepay;
1733 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
1736 this._confirmPoPrepaySituation = function() {
1737 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
1738 if (want_prepay != this._prepayRequiredByVendor) {
1741 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
1742 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
1749 this.applySelectedLiAction = function(action) {
1753 case 'delete_selected':
1754 this._deleteLiList(self.getSelected());
1757 case 'create_order':
1759 if(!this.createPoProviderSelector) {
1760 var widget = new openils.widget.AutoFieldWidget({
1761 fmField : 'provider',
1763 searchFilter: {"active": "t"},
1764 parentNode : dojo.byId('acq-lit-po-provider'),
1766 "onChange": function() {
1768 self._updateCreatePoPrepayCheckbox(
1769 this.item.prepayment_required
1776 function(w) { self.createPoProviderSelector = w; }
1780 if(!this.createPoAgencySelector) {
1781 var widget = new openils.widget.AutoFieldWidget({
1782 fmField : 'ordering_agency',
1784 parentNode : dojo.byId('acq-lit-po-agency'),
1785 orgLimitPerms : ['CREATE_PURCHASE_ORDER'],
1788 function(w) { self.createPoAgencySelector = w; }
1793 acqLitPoCreateDialog.show();
1796 case 'save_picklist':
1797 this._loadPLSelect();
1798 acqLitSavePlDialog.show();
1801 case 'selector_ready':
1803 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
1804 acqLitChangeLiStateDialog.show();
1815 case 'rollback_receive_po':
1816 this.rollbackPoReceive();
1819 case 'create_assets':
1820 this.createAssets();
1823 case 'export_attr_list':
1824 this.chooseExportAttr();
1827 case 'add_brief_record':
1829 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
1831 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
1835 case "cancel_lineitems":
1836 this.maybeCancelLineitems();
1839 case "change_claim_policy":
1840 var li_list = this.getSelected();
1841 this.claimPolicyPicker.attr("value", null);
1842 liClaimPolicyDialog.show();
1843 liClaimPolicySave.onClick = function() {
1844 self.changeClaimPolicy(
1846 self.claimPolicyPicker.attr("value"),
1849 function(li) { self.setClaimPolicyControl(li); }
1851 liClaimPolicyDialog.hide();
1859 this.changeClaimPolicy = function(li_list, value, callback) {
1861 function(li) { li.claim_policy(value); }
1863 fieldmapper.standardRequest(
1864 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
1865 "params": [openils.User.authtoken, li_list],
1867 "oncomplete": function(r) {
1868 r = openils.Util.readResponse(r);
1869 if (callback) callback(r);
1875 this.createAssets = function() {
1876 if(!this.isPO) return;
1877 if(!confirm(localeStrings.CREATE_PO_ASSETS_CONFIRM)) return;
1878 this.show('acq-lit-progress-numbers');
1880 fieldmapper.standardRequest(
1881 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
1883 params: [this.authtoken, this.isPO],
1884 onresponse: function(r) {
1885 var resp = openils.Util.readResponse(r);
1886 self._updateProgressNumbers(resp, true);
1892 this.maybeCancelLineitems = function() {
1893 openils.Util.show("acq-lit-cancel-reason", "inline");
1894 if (!acqLitCancelLineitemsButton._prepared) {
1895 var widget = new openils.widget.AutoFieldWidget({
1896 "fmField": "cancel_reason",
1898 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
1899 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1904 acqLitCancelLineitemsButton.onClick = function() {
1905 if (w.attr("value")) {
1906 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
1907 self._cancelLineitems(w.attr("value"));
1909 openils.Util.hide("acq-lit-cancel-reason");
1912 acqLitCancelLineitemsButton._prepared = true;
1918 this._cancelLineitems = function(reason) {
1919 var id_list = this.getSelected().map(function(o) { return o.id(); });
1920 fieldmapper.standardRequest(
1921 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
1922 "params": [openils.User.authtoken, id_list, reason],
1924 "onresponse": function(r) {
1925 if (r = openils.Util.readResponse(r)) {
1927 for (var id in r.li) {
1928 self.liCache[id].state(r.li[id].state);
1929 self.liCache[id].cancel_reason(
1930 r.li[id].cancel_reason
1932 self.updateLiState(self.liCache[id]);
1935 if (r.lid && self.copyCache) {
1936 for (var id in r.lid) {
1937 if (self.copyCache[id]) {
1938 self.copyCache[id].cancel_reason(
1939 r.lid[id].cancel_reason
1941 self.updateLidState(self.copyCache[id]);
1951 this.chooseExportAttr = function() {
1952 if (!acqLitExportAttrSelector._li_setup) {
1954 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
1956 "data": acqliad.toStoreData(
1958 "acqliad", {"code": li_exportable_attrs}
1963 acqLitExportAttrSelector.setValue();
1964 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
1965 acqLitExportAttrSelector._li_setup = true;
1967 openils.Util.show("acq-lit-export-attr-holder", "inline");
1970 this.exportAttrList = function() {
1971 var attr_def = acqLitExportAttrSelector.item;
1972 var li_list = this.getSelected();
1973 var value_list = li_list.map(
1975 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1976 attr_def.code, "lineitem_marc_attr_definition"
1979 ).filter(function(attr) { return Boolean(attr); });
1981 if (value_list.length > 0) {
1982 if (value_list.length < li_list.length) {
1984 dojo.string.substitute(
1985 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
1992 openils.XUL.contentToFileSaveDialog(
1993 value_list.join("\n"),
1994 localeStrings.EXPORT_SAVE_DIALOG_TITLE
2000 alert(dojo.string.substitute(
2001 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
2005 openils.Util.hide("acq-lit-export-attr-holder");
2008 this.printPO = function() {
2009 if(!this.isPO) return;
2010 progressDialog.show(true);
2011 fieldmapper.standardRequest(
2012 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
2014 params: [this.authtoken, this.isPO, 'html'],
2015 oncomplete: function(r) {
2016 progressDialog.hide();
2017 var evt = openils.Util.readResponse(r);
2018 if(evt && evt.template_output()) {
2019 win = window.open('','', 'resizable,width=800,height=600,scrollbars=1');
2020 win.document.body.innerHTML = evt.template_output().data();
2028 this.receivePO = function() {
2029 if (!this.isPO) return;
2031 for (var id in this.liCache) {
2032 /* assumption: liCache reflects exactly the
2033 * set of LIs that belong to our PO */
2034 if (this.liCache[id].state() != "received" &&
2035 !this.checkLiAlerts(id)) return;
2038 this.show('acq-lit-progress-numbers');
2040 fieldmapper.standardRequest(
2041 ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
2043 params: [this.authtoken, this.isPO],
2044 onresponse : function(r) {
2045 var resp = openils.Util.readResponse(r);
2046 self._updateProgressNumbers(resp, true);
2052 this.issueReceive = function(obj, rollback) {
2053 /* (For now) there shall be no marking LI or LIDs (un)received
2054 * except from the actual "view PO" interface. */
2055 if (!this.isPO) return;
2058 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
2060 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
2062 progressDialog.show(true);
2063 fieldmapper.standardRequest(
2064 ["open-ils.acq", method], {
2066 "params": [this.authtoken, obj.id()],
2067 "onresponse": function(r) {
2068 self.handleReceive(openils.Util.readResponse(r));
2069 progressDialog.hide();
2076 * Handles the responses from receive and rollback ML calls.
2078 this.handleReceive = function(resp) {
2081 for (var li_id in resp.li) {
2082 for (var key in resp.li[li_id])
2083 self.liCache[li_id][key](resp.li[li_id][key]);
2084 self.updateLiState(self.liCache[li_id]);
2088 if (typeof(self.poUpdateCallback) == "function")
2089 self.poUpdateCallback(resp.po);
2092 for (var lid_id in resp.lid) {
2093 for (var key in resp.lid[lid_id])
2094 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
2095 self.updateLidState(self.copyCache[lid_id]);
2101 this.rollbackPoReceive = function() {
2102 if(!this.isPO) return;
2103 if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
2104 this.show('acq-lit-progress-numbers');
2106 fieldmapper.standardRequest(
2107 ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
2109 params: [this.authtoken, this.isPO],
2110 onresponse : function(r) {
2111 var resp = openils.Util.readResponse(r);
2112 self._updateProgressNumbers(resp, true);
2118 this._updateProgressNumbers = function(resp, reloadOnComplete) {
2120 dojo.byId('acq-pl-lit-li-processed').innerHTML = resp.li;
2121 dojo.byId('acq-pl-lit-lid-processed').innerHTML = resp.lid;
2122 dojo.byId('acq-pl-lit-debits-processed').innerHTML = resp.debits_accrued;
2123 dojo.byId('acq-pl-lit-bibs-processed').innerHTML = resp.bibs;
2124 dojo.byId('acq-pl-lit-indexed-processed').innerHTML = resp.indexed;
2125 dojo.byId('acq-pl-lit-copies-processed').innerHTML = resp.copies;
2126 if(resp.complete && reloadOnComplete)
2127 location.href = location.href;
2131 this._createPO = function(fields) {
2132 this.show('acq-lit-progress-numbers');
2133 var po = new fieldmapper.acqpo();
2134 po.provider(this.createPoProviderSelector.attr('value'));
2135 po.ordering_agency(this.createPoAgencySelector.attr('value'));
2136 po.prepayment_required(fields.prepayment_required[0] ? true : false);
2138 var selected = this.getSelected( (fields.create_from == 'all') );
2139 if(selected.length == 0) return;
2141 var max = selected.length * 3;
2144 fieldmapper.standardRequest(
2145 ['open-ils.acq', 'open-ils.acq.purchase_order.create'],
2148 openils.User.authtoken,
2151 lineitems : selected.map(function(li) { return li.id() }),
2152 create_assets : fields.create_assets[0],
2156 onresponse : function(r) {
2157 var resp = openils.Util.readResponse(r);
2158 self._updateProgressNumbers(resp);
2160 location.href = oilsBasePath + '/acq/po/view/' + resp.purchase_order.id();
2166 this._deleteLiList = function(list, idx) {
2167 if(idx == null) idx = 0;
2168 if(idx >= list.length) return;
2169 var liId = list[idx].id();
2170 fieldmapper.standardRequest(
2171 ['open-ils.acq', 'open-ils.acq.lineitem.delete'],
2173 params: [openils.User.authtoken, liId],
2174 oncomplete: function(r) {
2175 self.removeLineitem(liId);
2176 self._deleteLiList(list, ++idx);
2182 this.editOrderMarc = function(li) {
2184 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
2185 to true in about:config */
2187 if(!openils.XUL.enableXPConnect()) return;
2189 if(openils.XUL.isXUL()) {
2190 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
2192 win = window.open('/xul/server/cat/marcedit.xul');
2196 record : {marc : li.marc()},
2198 label: 'Save Record', // XXX I18N
2199 func: function(xmlString) {
2201 fieldmapper.standardRequest(
2202 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
2204 params: [openils.User.authtoken, li],
2205 oncomplete: function(r) {
2206 openils.Util.readResponse(r);
2208 self.drawInfo(li.id())
2217 this._savePl = function(values) {
2219 var selected = this.getSelected( (values.which == 'all') );
2220 openils.Util.show('acq-lit-generic-progress');
2222 if(values.new_name) {
2223 openils.acq.Picklist.create(
2224 {name: values.new_name},
2226 self._updateLiList(id, selected, 0,
2228 location.href = oilsBasePath + '/acq/picklist/view/' + id;
2232 } else if(values.existing_pl) {
2233 // update lineitems to use an existing picklist
2234 self._updateLiList(values.existing_pl, selected, 0,
2236 location.href = oilsBasePath + '/acq/picklist/view/' + values.existing_pl;
2241 this._updateLiState = function(values, state) {
2243 var selected = this.getSelected( (values.which == 'all') );
2244 if(!selected.length) return;
2245 dojo.forEach(selected, function(li) {li.state(state);});
2246 self._updateLiList(null, selected, 0,
2247 // TODO consider inline updates for efficiency
2248 function() { location.href = location.href }
2252 this._updateLiList = function(pl, list, idx, oncomplete) {
2253 if(idx >= list.length) return oncomplete();
2255 if(pl != null) li.picklist(pl);
2256 litGenericProgress.update({maximum: list.length, progress: idx});
2257 new openils.acq.Lineitem({lineitem:li}).update(
2259 self._updateLiList(pl, list, ++idx, oncomplete);
2264 this._loadPLSelect = function() {
2265 if(this._plSelectLoaded) return;
2267 function handleResponse(r) {
2268 plList.push(r.recv().content());
2270 var method = 'open-ils.acq.picklist.user.retrieve';
2271 fieldmapper.standardRequest(
2272 ['open-ils.acq', method],
2274 params: [this.authtoken],
2275 onresponse: handleResponse,
2276 oncomplete: function() {
2277 self._plSelectLoaded = true;
2278 acqLitAddExistingSelect.store =
2279 new dojo.data.ItemFileReadStore({data:acqpl.toStoreData(plList)});
2280 acqLitAddExistingSelect.setValue();
2286 this.showRealCopyEditUI = function(li) {
2291 this._fetchLineitem(li.id(),
2293 li = self.liCache[li.id()] = fullLi;
2297 id : li.lineitem_details().map(
2298 function(item) { return item.eg_copy_id() }
2302 oncomplete : function(r) {
2304 var r_list = openils.Util.readResponse( r );
2305 for (var i = 0; i < r_list.length; i++) {
2306 var copy = r_list[i];
2307 var volId = copy.call_number();
2308 var volume = self.volCache[volId];
2310 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2312 copy.call_number(volume);
2313 copyList.push(copy);
2316 // If we need to, we can pass in an update_copy function to handle the update instead of volume_item_creator
2317 xulG.volume_item_creator( { 'existing_copies' : copyList } );
2320 alert('error in oncomplete: ' + E);
2331 this.saveRealCopies = function() {
2332 progressDialog.show(true);
2333 var list = this.realCopyList.filter(function(copy) { return copy.ischanged(); });
2334 this.pcrud.update(list, {oncomplete: function() {
2335 progressDialog.hide();
2340 // grab the li-details for this lineitem, grab the linked copies and volumes, add them to the table
2341 this.showRealCopies = function(li) {
2342 while(this.realCopiesTbody.childNodes[0])
2343 this.realCopiesTbody.removeChild(this.realCopiesTbody.childNodes[0]);
2344 this.show('real-copies');
2346 this.realCopyList = [];
2348 var tabIndex = 1000;
2351 acqLitSaveRealCopies.onClick = function() {
2352 self.saveRealCopies();
2355 this._fetchLineitem(li.id(),
2357 li = self.liCache[li.id()] = fullLi;
2361 id : li.lineitem_details().map(
2362 function(item) { return item.eg_copy_id() }
2367 onresponse : function(r) {
2368 var copy = openils.Util.readResponse(r);
2369 var volId = copy.call_number();
2370 var volume = self.volCache[volId];
2372 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2374 self.addRealCopy(volume, copy, tabIndex++);
2382 this.addRealCopy = function(volume, copy, tabIndex) {
2383 var row = this.realCopiesRow.cloneNode(true);
2384 this.realCopyList.push(copy);
2388 ['owning_lib', 'location', 'circ_modifier', 'label', 'barcode'],
2391 var isvol = (field == 'owning_lib' || field == 'label');
2392 var widget = new openils.widget.AutoFieldWidget({
2394 fmObject : isvol ? volume : copy,
2395 parentNode : nodeByName(field, row),
2396 readOnly : (field != 'barcode'),
2399 var widgetDrawn = null;
2401 if(field == 'barcode') {
2403 widgetDrawn = function(w, ww) {
2404 var node = w.domNode;
2405 node.setAttribute('tabindex', ''+tabIndex);
2407 // on enter, select the next barcode input
2408 dojo.connect(w, 'onKeyDown',
2410 if(e.keyCode == dojo.keys.ENTER) {
2411 var ti = node.getAttribute('tabindex');
2412 var nextNode = dojo.query('[tabindex=' + String(Number(ti) + 1) + ']', self.realCopiesTbody)[0];
2413 if(nextNode) nextNode.select();
2418 dojo.connect(w, 'onChange',
2420 if(!val || val == copy.barcode()) return;
2421 copy.ischanged(true);
2427 if(self.realCopiesTbody.getElementsByTagName('TR').length == 0)
2432 widget.build(widgetDrawn);
2436 this.realCopiesTbody.appendChild(row);
2437 if(selectNode) selectNode.select();