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.User');
10 dojo.require('openils.Util');
11 dojo.require('openils.acq.Lineitem');
12 dojo.require('openils.acq.PO');
13 dojo.require('openils.acq.Picklist');
14 dojo.require('openils.widget.AutoFieldWidget');
15 dojo.require('dojo.data.ItemFileReadStore');
16 dojo.require('openils.widget.ProgressDialog');
17 dojo.require('openils.PermaCrud');
18 dojo.require('openils.XUL');
20 dojo.requireLocalization('openils.acq', 'acq');
21 var localeStrings = dojo.i18n.getLocalization('openils.acq', 'acq');
22 const XUL_OPAC_WRAPPER = 'chrome://open_ils_staff_client/content/cat/opac.xul';
23 var li_exportable_attrs = ["issn", "isbn", "upc"];
25 var fundLabelFormat = ['${0} (${1})', 'code', 'year'];
26 var fundSearchFormat = ['${0} (${1})', 'code', 'year'];
28 function nodeByName(name, context) {
29 return dojo.query('[name='+name+']', context)[0];
33 var liDetailBatchFields = ['fund', 'owning_lib', 'location', 'collection_code', 'circ_modifier', 'cn_label'];
34 var liDetailFields = liDetailBatchFields.concat(['barcode', 'note']);
36 function AcqLiTable() {
43 this.realDfaCache = {};
44 this.virtDfaCounts = {};
47 this.toggleState = false;
48 this.tbody = dojo.byId('acq-lit-tbody');
51 this.authtoken = openils.User.authtoken;
52 this.pcrud = new openils.PermaCrud();
53 this.rowTemplate = this.tbody.removeChild(dojo.byId('acq-lit-row'));
54 this.copyTbody = dojo.byId('acq-lit-li-details-tbody');
55 this.copyRow = this.copyTbody.removeChild(dojo.byId('acq-lit-li-details-row'));
56 this.copyBatchRow = dojo.byId('acq-lit-li-details-batch-row');
57 this.copyBatchWidgets = {};
58 this.liNotesTbody = dojo.byId('acq-lit-notes-tbody');
59 this.liNotesRow = this.liNotesTbody.removeChild(dojo.byId('acq-lit-notes-row'));
60 this.realCopiesTbody = dojo.byId('acq-lit-real-copies-tbody');
61 this.realCopiesRow = this.realCopiesTbody.removeChild(dojo.byId('acq-lit-real-copies-row'));
62 this._copy_fields_for_acqdf = ['owning_lib', 'location'];
64 dojo.connect(acqLitLiActionsSelector, 'onChange',
66 self.applySelectedLiAction(this.attr('value'))
67 acqLitLiActionsSelector.attr('value', '_');
70 acqLitCreatePoSubmit.onClick = function() {
71 if (self._confirmPoPrepaySituation()) {
72 acqLitPoCreateDialog.hide();
73 self._createPO(acqLitPoCreateDialog.getValues());
79 acqLitSavePlButton.onClick = function() {
80 acqLitSavePlDialog.hide();
81 self._savePl(acqLitSavePlDialog.getValues());
84 acqLitCancelLiStateButton.onClick = function() {
85 acqLitChangeLiStateDialog.hide();
87 acqLitSaveLiStateButton.onClick = function() {
88 acqLitChangeLiStateDialog.hide();
89 self._updateLiState(acqLitChangeLiStateDialog.getValues(), acqLitChangeLiStateDialog.attr('state'));
93 dojo.byId('acq-lit-select-toggle').onclick = function(){self.toggleSelect()};
94 dojo.byId('acq-lit-info-back-button').onclick = function(){self.show('list')};
95 dojo.byId('acq-lit-copies-back-button').onclick = function(){self.show('list')};
96 dojo.byId('acq-lit-notes-back-button').onclick = function(){self.show('list')};
97 dojo.byId('acq-lit-real-copies-back-button').onclick = function(){self.show('list')};
99 this.reset = function() {
100 while(self.tbody.childNodes[0])
101 self.tbody.removeChild(self.tbody.childNodes[0]);
107 this.setNext = function(handler) {
108 var link = dojo.byId('acq-lit-next');
110 dojo.style(link, 'visibility', 'visible');
111 link.onclick = handler;
113 dojo.style(link, 'visibility', 'hidden');
117 this.setPrev = function(handler) {
118 var link = dojo.byId('acq-lit-prev');
120 dojo.style(link, 'visibility', 'visible');
121 link.onclick = handler;
123 dojo.style(link, 'visibility', 'hidden');
127 this.show = function(div) {
128 openils.Util.hide('acq-lit-table-div');
129 openils.Util.hide('acq-lit-info-div');
130 openils.Util.hide('acq-lit-li-details');
131 openils.Util.hide('acq-lit-notes-div');
132 openils.Util.hide('acq-lit-real-copies-div');
135 openils.Util.show('acq-lit-table-div');
138 openils.Util.show('acq-lit-info-div');
141 openils.Util.show('acq-lit-li-details');
144 openils.Util.show('acq-lit-real-copies-div');
147 openils.Util.show('acq-lit-notes-div');
151 openils.Util.show(div);
155 this.hide = function() {
159 this.toggleSelect = function() {
161 dojo.forEach(self.selectors, function(i){i.checked = false});
163 dojo.forEach(self.selectors, function(i){i.checked = true});
164 self.toggleState = !self.toggleState;
168 /** @param all If true, assume all are selected */
169 this.getSelected = function(all) {
171 dojo.forEach(self.selectors,
174 selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
180 this.setRowAttr = function(td, liWrapper, field, type) {
181 var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
182 td.appendChild(document.createTextNode(val));
186 * Inserts a single lineitem into the growing table of lineitems
187 * @param {Object} li The lineitem object to insert
189 this.addLineitem = function(li, skip_final_placement) {
190 this.liCache[li.id()] = li;
192 // sort the lineitem notes on edit_time
193 if(!li.lineitem_notes()) li.lineitem_notes([]);
195 var liWrapper = new openils.acq.Lineitem({lineitem:li});
196 var row = self.rowTemplate.cloneNode(true);
197 row.setAttribute('li', li.id());
198 var tds = dojo.query('[attr]', row);
199 dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
200 dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
202 var isbn = liWrapper.findAttr('isbn', 'lineitem_marc_attr_definition');
204 // XXX media prefix for added content
205 dojo.query('[name=jacket]', row)[0].setAttribute('src', '/opac/extras/ac/jacket/small/' + isbn);
208 nodeByName("worksheet_link", row).href =
209 "/eg/acq/lineitem/worksheet/" + li.id();
211 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
212 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
213 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
215 this.updateLiNotesCount(li, row);
217 // show which PO this lineitem is a member of
218 if(li.purchase_order() && !this.isPO) {
220 this.poCache[li.purchase_order()] =
221 this.poCache[li.purchase_order()] ||
222 fieldmapper.standardRequest(
223 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
225 this.authtoken, li.purchase_order(), {
226 "flesh_price_summary": true,
227 "flesh_lineitem_count": true
230 if(po && !this.isMeta) {
231 openils.Util.show(nodeByName('po', row), 'inline');
232 var link = nodeByName('po_link', row);
233 link.setAttribute('href', oilsBasePath + '/acq/po/view/' + li.purchase_order());
234 link.innerHTML = 'PO: ' + po.name(); // TODO i18n
238 // show which picklist this lineitem is a member of
239 if(li.picklist() && (this.isPO || this.isMeta)) {
241 this.plCache[li.picklist()] =
242 this.plCache[li.picklist()] ||
243 fieldmapper.standardRequest(
244 ['open-ils.acq', 'open-ils.acq.picklist.retrieve'],
245 {params: [this.authtoken, li.picklist()]});
247 openils.Util.show(nodeByName('pl', row), 'inline');
248 var link = nodeByName('pl_link', row);
249 link.setAttribute('href', oilsBasePath + '/acq/picklist/view/' + li.picklist());
250 link.innerHTML = 'PL: '+pl.name(); // TODO i18n
254 var countNode = nodeByName('count', row);
255 var count = li.item_count() || 0;
256 if (typeof(this._copy_count_cb) == "function") {
257 this._copy_count_cb(li.id(), count);
259 countNode.innerHTML = count;
260 countNode.id = 'acq-lit-copy-count-label-' + li.id();
263 var priceInput = dojo.query('[name=price]', row)[0];
264 priceInput.value = li.estimated_unit_price() || '';
265 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
267 // show either "mark received" or "unreceive" as appropriate
268 this.updateLiState(li, row);
270 if (!skip_final_placement) {
271 self.tbody.appendChild(row);
272 self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
278 this.updateLiNotesCount = function(li, row) {
279 if (typeof(row) == "undefined")
280 row = dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
282 var has_notes = (li.lineitem_notes().filter(
283 function(o) { return Boolean (o.alert_text()); }
286 /* U+2691 is the code point for a filled-in flag character */
287 nodeByName("notes_alert_flag", row).innerHTML =
288 has_notes ? "⚑" : "";
289 nodeByName("noteslink", row).style.fontStyle =
290 has_notes ? "italic" : "normal";
291 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
294 /* XXX NOT related to _updateLiState(). rethink */
295 this.updateLiState = function(li, row) {
296 if (typeof(row) == "undefined")
297 row = dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
299 var recv_link = nodeByName("receive_link", row);
300 var unrecv_link = nodeByName("unreceive_link", row);
301 var real_copies_link = nodeByName("real_copies_link", row);
302 var holdings_maintenance_link = nodeByName("holdings_maintenance_link", row);
303 var state_cell = nodeByName("li_state", row);
305 if (li.state() == "cancelled") {
306 if (typeof li.cancel_reason() == "object") {
307 var holds_state = dojo.create(
309 "style": "border-bottom: 1px dashed #000;",
310 "innerHTML": li.state()
311 }, state_cell, "only"
315 "label": "<em>" + li.cancel_reason().label() +
316 "</em><br />" + li.cancel_reason().description(),
317 "connectId": [holds_state]
318 }, dojo.create("span", null, state_cell, "last")
321 state_cell.innerHTML = li.state(); // TODO i18n state labels
324 state_cell.innerHTML = li.state(); // TODO i18n state labels
328 /* handle row coloring for based on LI state */
329 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
330 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
332 /* handle links that appear/disappear based on whether LI is received */
337 openils.Util.hide(real_copies_link);
338 openils.Util.hide(unrecv_link);
339 openils.Util.show(recv_link, "inline");
340 recv_link.onclick = function() {
341 if (self.checkLiAlerts(li.id()))
342 self.issueReceive(li);
346 openils.Util.hide(recv_link);
347 openils.Util.show(unrecv_link, "inline");
348 unrecv_link.onclick = function() {
349 if (confirm(localeStrings.UNRECEIVE_LI))
350 self.issueReceive(li, /* rollback */ true);
352 // TODO we should allow editing before receipt, in which case the
353 // test should be "if 1 or more real (acp) copies exist
354 openils.Util.show(real_copies_link, "inline");
355 real_copies_link.onclick = function() {
356 self.showRealCopyEditUI(li);
358 openils.Util.show(holdings_maintenance_link, "inline");
359 holdings_maintenance_link.onclick = self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser' );
364 openils.Util.hide(recv_link);
365 openils.Util.hide(unrecv_link);
366 openils.Util.hide(real_copies_link);
370 this._setAlertStore = function() {
371 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
373 "data": acqliat.toStoreData(
375 "acqliat", {"id": {"!=": null}}
380 acqLitAlertAlertText.setValue(); /* make the store "live" */
381 acqLitAlertAlertText._store_ready = true;
385 * Draws and shows the lineitem notes pane
387 this.drawLiNotes = function(li) {
390 if (!acqLitAlertAlertText._store_ready)
391 this._setAlertStore();
394 li.lineitem_notes().sort(
396 if(a.edit_time() < b.edit_time()) return 1;
402 while(this.liNotesTbody.childNodes[0])
403 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
406 acqLitCreateNoteSubmit.onClick = function() {
407 var value = acqLitCreateNoteText.attr('value');
409 var note = new fieldmapper.acqlin();
412 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
415 note.lineitem(li.id());
417 self.updateLiNotes(li, note);
418 acqLitCreateNoteVendorPublic.attr("checked", false);
419 acqLitCreateNoteText.attr("value", "");
422 acqLitCreateAlertSubmit.onClick = function() {
423 if (!acqLitAlertAlertText.item) {
424 alert(localeStrings.ALERT_UNSELECTED);
428 var alert_text = new fieldmapper.acqliat().fromStoreItem(
429 acqLitAlertAlertText.item
431 var value = acqLitAlertNoteValue.attr("value") || "";
433 var note = new fieldmapper.acqlin();
435 note.lineitem(li.id());
437 note.alert_text(alert_text);
439 self.updateLiNotes(li, note);
442 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
446 * Draws a single lineitem note in the notes pane
448 this.addLiNote = function(li, note) {
449 if(note.isdeleted()) return;
451 var row = self.liNotesRow.cloneNode(true);
452 nodeByName("value", row).innerHTML = note.value();
453 var alert_node = nodeByName("alert_code", row);
454 if (note.alert_text()) {
455 alert_node.innerHTML = note.alert_text().code();
456 if (note.alert_text().description()) {
459 "connectId": [alert_node],
460 "label": note.alert_text().description()
461 }, dojo.create("span", null, alert_node, "after")
466 if (openils.Util.isTrue(note.vendor_public()))
467 nodeByName("vendor_public", row).innerHTML =
468 localeStrings.VENDOR_PUBLIC;
470 nodeByName("delete", row).onclick = function() {
471 note.isdeleted(true);
472 self.liNotesTbody.removeChild(row);
473 self.updateLiNotes(li);
476 if(note.edit_time()) {
477 nodeByName("edit_time", row).innerHTML =
478 dojo.date.locale.format(
479 dojo.date.stamp.fromISOString(note.edit_time()),
480 {formatLength:'short'});
483 self.liNotesTbody.appendChild(row);
487 * Updates any new/changed/deleted notes on the server
489 this.updateLiNotes = function(li, newNote) {
495 notes = li.lineitem_notes().filter(
497 if(note.ischanged() || note.isnew() || note.isdeleted())
503 if(notes.length == 0) return;
504 progressDialog.show();
506 fieldmapper.standardRequest(
507 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
509 params : [this.authtoken, notes],
510 onresponse : function(r) {
511 var resp = openils.Util.readResponse(r);
516 // remove the old changed notes
518 dojo.forEach(li.lineitem_notes(),
520 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
524 li.lineitem_notes(list);
527 progressDialog.hide();
528 self.updateLiNotesCount(li);
529 self.drawLiNotes(li);
533 progressDialog.update(resp);
534 var newnote = resp.note;
536 if(!newnote.isdeleted()) {
537 newnote.isnew(false);
538 newnote.ischanged(false);
539 li.lineitem_notes().push(newnote);
546 this.updateLiPrice = function(input, li) {
548 var price = input.value;
549 if(Number(price) == Number(li.estimated_unit_price())) return;
551 fieldmapper.standardRequest(
552 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
554 params : [this.authtoken, li.id(), price],
555 oncomplete : function(r) {
556 openils.Util.readResponse(r);
562 this.removeLineitem = function(liId) {
563 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
564 delete this.liCache[liId];
565 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
568 this.drawInfo = function(liId) {
569 if (!this._isRelatedViewer) {
570 var d = dojo.byId("acq-lit-info-related");
571 if (!this.relCache[liId]) {
572 fieldmapper.standardRequest(
575 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
578 "params": [openils.User.authtoken, liId],
579 "onresponse": function(r) {
580 self.relCache[liId] = openils.Util.readResponse(r);
581 nodeByName("related_number", d).innerHTML =
584 self.relCache[liId] >1 ? "show" : "hide"
590 nodeByName("related_number", d).innerHTML = this.relCache[liId];
591 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
596 openils.acq.Lineitem.fetchAttrDefs(
598 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
603 this._fetchLineitem = function(liId, handler) {
605 var li = this.liCache[liId];
606 if(li && li.marc() && li.lineitem_details())
609 fieldmapper.standardRequest(
610 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve'],
613 params: [self.authtoken, liId, {
615 flesh_cancel_reason: true,
616 flesh_li_details: true,
617 flesh_fund_debit: true }],
619 oncomplete: function(r) {
620 var li = openils.Util.readResponse(r);
627 this._drawInfo = function(li) {
629 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
632 openils.Util.hide('acq-lit-marc-order-record-label');
633 openils.Util.hide(acqLitEditOrderMarc.domNode);
634 openils.Util.show('acq-lit-marc-real-record-label');
636 openils.Util.show('acq-lit-marc-order-record-label');
637 openils.Util.show(acqLitEditOrderMarc.domNode);
638 openils.Util.hide('acq-lit-marc-real-record-label');
641 this.drawMarcHTML(li);
642 this.infoTbody = dojo.byId('acq-lit-info-tbody');
645 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
646 while(this.infoTbody.childNodes[0])
647 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
649 if (!this._isRelatedViewer) {
650 for(var i = 0; i < li.attributes().length; i++) {
651 var attr = li.attributes()[i];
652 var row = this.infoRow.cloneNode(true);
654 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
655 var name = openils.acq.Lineitem.attrDefs[type].filter(
657 return (a.code() == attr.attr_name());
659 ).pop().description();
661 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
662 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
663 this.infoTbody.appendChild(row);
666 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
667 "/eg/acq/lineitem/related/" + li.id();
672 openils.Util.show('acq-lit-info-cat-link');
673 var link = dojo.byId('acq-lit-info-cat-link').getElementsByTagName('a')[0];
675 if(openils.XUL.isXUL()) {
677 link.setAttribute('href', 'javascript:void(0);');
678 link.onclick = this.generateMakeRecTab( li.eg_bib_id() );
681 var href = link.getAttribute('href');
683 link.setAttribute('href', href + li.eg_bib_id());
686 openils.Util.hide('acq-lit-info-cat-link');
690 this.generateMakeRecTab = function(bib_id,default_view) {
694 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
697 show_nav_buttons : true,
698 show_print_button : true,
699 opac_url : xulG.url_prefix(xulG.urls.opac_rdetail + '?r=' + bib_id),
700 default_view : default_view
706 this.drawMarcHTML = function(li) {
707 var params = [null, true, li.marc()];
709 params = [li.eg_bib_id(), true];
711 fieldmapper.standardRequest(
712 ['open-ils.search', 'open-ils.search.biblio.record.html'],
715 oncomplete: function(r) {
716 dojo.byId('acq-lit-marc-div').innerHTML =
717 openils.Util.readResponse(r);
723 this.drawCopies = function(liId) {
727 this.copyWidgetCache = {};
728 this.oldCopyWidgetCache = {};
729 this.virtDfaCounts = {};
730 this.realDfaCache = {};
733 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
734 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
735 acqLitCopyCountInput.attr('value', '0');
737 while(this.copyTbody.childNodes[0])
738 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
740 this._drawBatchCopyWidgets();
742 this._drawDistribApplied(liId);
744 this._fetchDistribFormulas(
746 openils.acq.Lineitem.fetchAttrDefs(
748 self._fetchLineitem(liId, function(li){self._drawCopies(li);});
755 this._saveDistribAppliedTemplates = function() {
756 if (!this._appliedDistribTemplate) {
757 this._appliedDistribTemplate =
758 dojo.byId("acq-lit-distrib-applied-tbody").
759 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
760 dojo.attr(this._appliedDistribTemplate, "id");
764 this._drawDistribApplied = function(liId) {
765 /* Build this table while hidden to prevent rendering artifacts */
766 openils.Util.hide("acq-lit-distrib-applied-tbody");
768 this._saveDistribAppliedTemplates();
770 /* Remove any rows in the table from previous populations */
771 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
772 forEach(dojo.destroy);
774 /* Unregister all dijits previously created (for some reason this isn't
775 * covered by the above destroy calls). */
776 dijit.registry.forEach(
777 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
780 /* Populate the table with our liId */
782 fieldmapper.standardRequest(
784 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
787 "params": [self.authtoken, liId],
788 "onresponse": function(r) {
789 var dfa = openils.Util.readResponse(r);
792 self.realDfaCache[dfa.id()] = dfa;
793 self._drawDistribAppliedUnit(dfa);
796 "oncomplete": function() {
797 /* Reveal built table */
800 "acq-lit-distrib-applied-tbody", "table-row-group"
808 this._drawDistribAppliedUnit = function(dfa) {
810 var row = dojo.query(
811 'tr[formula="' + dfa.formula().id() + '"]',
812 "acq-lit-distrib-applied-tbody"
817 row = dojo.clone(this._appliedDistribTemplate);
818 dojo.attr(row, "formula", dfa.formula().id());
819 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
822 var td = dojo.query("td", row)[0];
824 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
825 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
828 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
830 new dijit.form.Button(
832 "onClick": function() {
833 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
837 /* XXX I /cannot/ make the following work in as a CSS class
838 * for some reason. So frustrating... */
839 "style": function(id) {
841 "font-weight: bold; color: #c00;" :
843 }(dfa.id()) + "margin: 0 6px;display: inline;"
844 }, "dfa-button-" + dfa.id()
848 "connectId": ["dfa-button-" + dfa.id()],
849 "label": dojo.string.substitute(
850 localeStrings.DFA_TIP, dfa.id() > 0 ? [
851 openils.User.formalName(dfa.creator()),
852 dojo.date.locale.format(
853 dojo.date.stamp.fromISOString(dfa.create_time()),
854 {"formatLength":"short"}
856 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
858 }, "dfa-tip-" + dfa.id()
862 this.deleteDfa = function(dfa) {
863 if (dfa.id() > 0) { /* real */
864 this.pcrud.eliminate(
867 "oncomplete": function() {
868 self._removeDistribApplied(dfa.id());
869 delete self.realDfaCache[dfa.id()];
873 } else { /* virtual */
874 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
875 this.virtDfaCounts[dfa.formula().id()] = 0;
876 /* hasn't been saved yet, so no need to do anything server side */
877 this._removeDistribApplied(dfa.id());
882 this._removeDistribApplied = function(dfaId) {
883 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
884 dijit.registry.forEach(
885 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
887 this._removeDistribAppliedEmptyRows();
890 this._removeAllDistribAppliedVirtual = function() {
891 /* Unregister dijits */
892 dijit.registry.forEach(
893 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
895 this._removeDistribAppliedEmptyRows();
898 this._removeDistribAppliedEmptyRows = function() {
899 /* Remove any rows with no DFA at all */
900 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
902 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
908 * Insert a new row into the distribution formula selection form
910 this._addDistribFormulaRow = function() {
913 if (!self.distribForms) {
914 // no formulas, hide the form
915 openils.Util.hide('acq-lit-distrib-formula-tbody');
919 if(!this.distribFormulaTemplate)
920 this.distribFormulaTemplate =
921 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
923 var row = this.distribFormulaTemplate.cloneNode(true);
924 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
926 this.dfSelector = new dijit.form.FilteringSelect(
927 {"labelAttr": "dynLabel", "labelType": "html"},
928 nodeByName("selector", row)
930 this._updateFormulaStore();
931 this.dfSelector.fetchProperties =
932 {"sort": [{"attribute": "use_count", "descending": true}]};
934 var apply = new dijit.form.Button(
935 {"label": localeStrings.APPLY},
936 nodeByName('set_button', row)
939 var reset = new dijit.form.Button(
940 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
941 nodeByName("reset_button", row)
944 dojo.connect(apply, 'onClick',
946 var form_id = self.dfSelector.attr("value");
948 self._applyDistribFormula(form_id);
949 reset.attr("disabled", false);
953 dojo.connect(reset, 'onClick',
955 self.restoreCopyFieldsBeforeDF();
956 self.virtDfaCounts = {};
959 self._updateFormulaStore();
960 self._removeAllDistribAppliedVirtual();
961 reset.attr("disabled", "true");
968 * Applies a distrib formula to the current set of copies
970 this._applyDistribFormula = function(formula) {
973 formula = this.distribForms.filter(
974 function(form) { return form.id() == formula; }
977 var copyRows = dojo.query('tr', self.copyTbody);
979 if (this.dfeOffset >= copyRows.length) {
980 alert(localeStrings.OUT_OF_COPIES);
984 var entries_applied = 0;
986 var rowIndex = this.dfeOffset;
987 rowIndex < copyRows.length;
991 var row = copyRows[rowIndex];
992 var copy_id = row.getAttribute('copy_id');
993 var copyWidgets = this.copyWidgetCache[copy_id];
994 var entryIndex = this.dfeOffset;
997 // find the correct entry for the current row
998 dojo.forEach(formula.entries(),
1001 entryIndex += e.item_count();
1002 if(entryIndex > rowIndex)
1010 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
1011 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
1014 this.saveCopyFieldsBeforeDF(copy_id);
1015 this._copy_fields_for_acqdf.forEach(
1017 if(entry[field]()) {
1018 copyWidgets[field].attr('value', (entry[field]()));
1025 if (entries_applied) {
1026 this.virtDfaCounts[formula.id()] =
1027 ++(this.virtDfaCounts[formula.id()]) || 1;
1028 this._updateFormulaStore();
1029 this._drawDistribAppliedUnit(
1031 var dfa = new acqdfa();
1032 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
1035 this.dfeOffset += entries_applied;
1040 * This function updates the DF store for the dropdown so that use_counts
1041 * can reflect DF applications from this session before they're saved
1044 this._updateFormulaStore = function() {
1045 this.dfSelector.store = new dojo.data.ItemFileReadStore(
1047 "data": self._labelFormulasWithCounts(
1048 acqdf.toStoreData(self.distribForms)
1054 this.saveCopyFieldsBeforeDF = function(copy_id) {
1056 if (!this.oldCopyWidgetCache[copy_id]) {
1057 var copyWidgets = this.copyWidgetCache[copy_id];
1059 this.oldCopyWidgetCache[copy_id] = {};
1060 this._copy_fields_for_acqdf.forEach(
1062 self.oldCopyWidgetCache[copy_id][f] =
1063 copyWidgets[f].attr("value");
1069 this.restoreCopyFieldsBeforeDF = function() {
1071 for (var copy_id in this.oldCopyWidgetCache) {
1072 this._copy_fields_for_acqdf.forEach(
1074 self.copyWidgetCache[copy_id][f].attr(
1075 "value", self.oldCopyWidgetCache[copy_id][f]
1082 this._labelFormulasWithCounts = function(store_data) {
1083 for (var key in store_data.items) {
1084 var obj = store_data.items[key];
1085 obj.use_count = Number(obj.use_count); /* needed for sorting */
1087 if (this.virtDfaCounts[obj.id])
1088 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
1090 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
1091 obj.use_count + "]</span> " + obj.name;
1097 * This method formerly would not refetch the DF formulas if they'd been
1098 * loaded already, but now it always re-fetches, since use_count changes.
1100 this._fetchDistribFormulas = function(onload) {
1101 fieldmapper.standardRequest(
1103 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
1106 "params": [openils.User.authtoken],
1107 "oncomplete": function(r) {
1108 self.distribForms = openils.Util.readResponse(r);
1109 if(!self.distribForms || self.distribForms.length == 0) {
1110 self.distribForms = [];
1112 self._addDistribFormulaRow();
1119 this._drawBatchCopyWidgets = function() {
1120 var row = this.copyBatchRow;
1121 dojo.forEach(liDetailBatchFields,
1123 if(self.copyBatchRowDrawn) {
1124 self.copyBatchWidgets[field].attr('value', null);
1126 var widget = new openils.widget.AutoFieldWidget({
1129 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1130 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1131 searchFilter : (field == 'fund') ? {"active": "t"} : null,
1132 parentNode : dojo.query('[name='+field+']', row)[0],
1133 orgLimitPerms : ['CREATE_PICKLIST'],
1134 dijitArgs : {required:false},
1139 self.copyBatchWidgets[field] = w;
1145 this.copyBatchRowDrawn = true;
1148 this.batchCopyUpdate = function() {
1150 for(var k in this.copyWidgetCache) {
1151 var cache = this.copyWidgetCache[k];
1152 dojo.forEach(liDetailBatchFields, function(f) {
1153 var newval = self.copyBatchWidgets[f].attr('value');
1154 if(newval) cache[f].attr('value', newval);
1159 this._drawCopies = function(li) {
1162 // this button sets the total number of copies for a given lineitem
1163 acqLitAddCopyCount.onClick = function() {
1164 var count = acqLitCopyCountInput.attr('value');
1167 while(self.copyCount() < count)
1170 // delete rows if necessary
1171 var diff = self.copyCount() - count;
1173 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
1174 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
1175 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
1177 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1183 if(li.lineitem_details().length > 0) {
1184 dojo.forEach(li.lineitem_details(),
1186 self.addCopy(li, copy);
1194 this.copyCount = function() {
1196 for(var id in this.copyCache) {
1197 if(!this.copyCache[id].isdeleted())
1203 this.virtCopyId = -1;
1204 this.addCopy = function(li, copy) {
1205 var row = this.copyRow.cloneNode(true);
1206 this.copyTbody.appendChild(row);
1210 copy = new fieldmapper.acqlid();
1212 copy.id(this.virtCopyId--);
1213 copy.lineitem(li.id());
1216 this.copyCache[copy.id()] = copy;
1217 row.setAttribute('copy_id', copy.id());
1218 self.copyWidgetCache[copy.id()] = {};
1220 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1222 dojo.forEach(liDetailFields,
1224 var widget = new openils.widget.AutoFieldWidget({
1227 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1228 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1229 searchFilter : (field == "fund" && copy.fund()) ?
1230 {"-or": {"active": "t", "id": copy.fund()}} : null,
1233 parentNode : dojo.query('[name='+field+']', row)[0],
1234 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
1235 readOnly : Boolean(copy.eg_copy_id())
1238 // make sure we capture the value from any async widgets
1240 copy[field](ww.getFormattedValue())
1241 self.copyWidgetCache[copy.id()][field] = w;
1244 dojo.connect(widget.widget, 'onChange',
1246 if(copy.isnew() || val != copy[field]()) {
1247 // prevent setting ischanged() automatically on widget load for existing copies
1248 copy[field](widget.getFormattedValue())
1249 copy.ischanged(true);
1256 this.updateLidState(copy, row);
1259 this.updateLidState = function(copy, row) {
1260 if (typeof(row) == "undefined") {
1262 'tr[copy_id="' + copy.id() + '"]', this.copyTbody
1267 var recv_link = nodeByName("receive", row);
1268 var unrecv_link = nodeByName("unreceive", row);
1269 var del_link = nodeByName("delete", row);
1270 var cxl_link = nodeByName("cancel", row);
1271 var cxl_reason_link = nodeByName("cancel_reason", row);
1273 if (copy.cancel_reason()) {
1274 openils.Util.hide(del_link.parentNode);
1275 openils.Util.hide(recv_link);
1276 openils.Util.hide(unrecv_link);
1277 openils.Util.hide(cxl_link);
1279 /* XXX the following may leak memory in a long lived table: dijits may not get destroyed... not positive. revisit. */
1280 var holds_reason = dojo.create(
1282 "style": "border-bottom: 1px dashed #000;",
1283 "innerHTML": "Cancelled" /* XXX [sic] and i18n */
1284 }, cxl_reason_link, "only"
1288 "label": "<em>" + copy.cancel_reason().label() +
1289 "</em><br />" + copy.cancel_reason().description(),
1290 "connectId": [holds_reason]
1291 }, dojo.create("span", null, cxl_reason_link, "last")
1293 openils.Util.show(cxl_reason_link, "inline");
1294 } else if (this.isPO) {
1295 openils.Util.hide(del_link.parentNode);
1296 openils.Util.hide(cxl_reason_link);
1298 /* Avoid showing (un)receive links, cancel links, for virt copies */
1299 if (copy.id() > 0) {
1300 if(copy.recv_time()) {
1301 openils.Util.hide(cxl_link);
1302 openils.Util.hide(recv_link);
1303 openils.Util.show(unrecv_link, "inline");
1304 unrecv_link.onclick = function() {
1305 if (confirm(localeStrings.UNRECEIVE_LID))
1306 self.issueReceive(copy, /* rollback */ true);
1309 openils.Util.hide(unrecv_link);
1310 openils.Util.show(recv_link, "inline");
1311 openils.Util.show(cxl_link, "inline");
1312 recv_link.onclick = function() {
1313 if (self.checkLiAlerts(copy.lineitem()))
1314 self.issueReceive(copy);
1316 cxl_link.onclick = function() {
1317 self.cancelLid(copy.id());
1321 openils.Util.hide(cxl_link);
1322 openils.Util.hide(unrecv_link);
1323 openils.Util.hide(recv_link);
1326 openils.Util.hide(unrecv_link);
1327 openils.Util.hide(recv_link);
1328 openils.Util.hide(cxl_reason_link);
1330 del_link.onclick = function() { self.deleteCopy(row) };
1331 openils.Util.show(del_link.parentNode);
1335 this.cancelLid = function(lid_id) {
1336 lidCancelDialog._lid_id = lid_id;
1337 openils.Util.show(lidCancelDialog.domNode.parentNode);
1338 lidCancelDialog.show();
1339 if (!lidCancelDialog._prepared) {
1340 var widget = new openils.widget.AutoFieldWidget({
1341 "fmField": "cancel_reason",
1342 "fmClass": "acqlid",
1343 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
1344 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1349 acqLidCancelButton.onClick = function() {
1350 if (w.attr("value")) {
1351 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
1353 lidCancelDialog._lid_id,
1357 lidCancelDialog.hide();
1360 lidCancelDialog._prepared = true;
1366 this._cancelLid = function(lid_id, reason) {
1367 fieldmapper.standardRequest(
1368 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
1369 "params": [openils.User.authtoken, lid_id, reason],
1371 "onresponse": function(r) {
1372 if (r = openils.Util.readResponse(r)) {
1374 for (var id in r.lid) {
1375 /* actually this should only iterate once */
1376 self.copyCache[id].cancel_reason(
1377 r.lid[id].cancel_reason
1379 self.updateLidState(self.copyCache[id]);
1388 this._confirmAlert = function(li, lin) {
1390 dojo.string.substitute(
1391 localeStrings.CONFIRM_LI_ALERT, [
1392 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1393 "title", "lineitem_marc_attr_definition"
1395 lin.alert_text().code(),
1396 lin.alert_text().description() || "",
1403 this.checkLiAlerts = function(li_id) {
1404 var li = this.liCache[li_id];
1406 var alert_notes = li.lineitem_notes().filter(
1407 function(o) { return Boolean(o.alert_text()); }
1410 /* this is _intentionally_ not done in a call to forEach() ... */
1411 for (var i = 0; i < alert_notes.length; i++) {
1412 if (this.noteAcks[alert_notes[i].id()])
1414 else if (!this._confirmAlert(li, alert_notes[i]))
1417 this.noteAcks[alert_notes[i].id()] = true;
1423 this.deleteCopy = function(row) {
1424 var copy = this.copyCache[row.getAttribute('copy_id')];
1425 copy.isdeleted(true);
1427 delete this.copyCache[copy.id()];
1428 this.copyTbody.removeChild(row);
1431 this._virtDfaCountsAsList = function() {
1433 for (var key in this.virtDfaCounts) {
1434 for (var i = 0; i < this.virtDfaCounts[key]; i++)
1440 this.saveCopyChanges = function(liId) {
1446 for(var id in this.copyCache) {
1447 var c = this.copyCache[id];
1448 if(!c.isdeleted()) total++;
1449 if(c.isnew() || c.ischanged() || c.isdeleted()) {
1450 if(c.id() < 0) c.id(null);
1455 if (typeof(this._copy_count_cb) == "function") {
1456 this._copy_count_cb(liId, total);
1459 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
1462 if (copies.length > 0) {
1463 openils.Util.show("acq-lit-update-copies-progress");
1464 fieldmapper.standardRequest(
1465 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1467 params: [openils.User.authtoken, copies],
1468 onresponse: function(r) {
1469 var res = openils.Util.readResponse(r);
1470 litUpdateCopiesProgress.update(res);
1472 oncomplete: function() {
1473 self.drawCopies(liId);
1474 openils.Util.hide("acq-lit-update-copies-progress");
1480 var dfa_list = this._virtDfaCountsAsList();
1481 if (dfa_list.length > 0) {
1482 fieldmapper.standardRequest(
1484 "open-ils.acq.distribution_formula.record_application"],
1487 "params": [openils.User.authtoken, dfa_list, liId],
1488 "onresponse": function(r) {
1489 var res = openils.Util.readResponse(r);
1490 if (res && res.length < dfa_list.length)
1491 alert(localeStrings.DFA_NOT_ALL);
1495 this.virtDfaCounts = {};
1499 this._updateCreatePoPrepayCheckbox = function(prepay) {
1500 var prepay = openils.Util.isTrue(prepay);
1501 this._prepayRequiredByVendor = prepay;
1502 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
1505 this._confirmPoPrepaySituation = function() {
1506 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
1507 if (want_prepay != this._prepayRequiredByVendor) {
1510 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
1511 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
1518 this.applySelectedLiAction = function(action) {
1522 case 'delete_selected':
1523 this._deleteLiList(self.getSelected());
1526 case 'create_order':
1528 if(!this.createPoProviderSelector) {
1529 var widget = new openils.widget.AutoFieldWidget({
1530 fmField : 'provider',
1532 searchFilter: {"active": "t"},
1533 parentNode : dojo.byId('acq-lit-po-provider'),
1535 "onChange": function() {
1537 self._updateCreatePoPrepayCheckbox(
1538 this.item.prepayment_required
1545 function(w) { self.createPoProviderSelector = w; }
1549 if(!this.createPoAgencySelector) {
1550 var widget = new openils.widget.AutoFieldWidget({
1551 fmField : 'ordering_agency',
1553 parentNode : dojo.byId('acq-lit-po-agency'),
1554 orgLimitPerms : ['CREATE_PURCHASE_ORDER'],
1557 function(w) { self.createPoAgencySelector = w; }
1562 acqLitPoCreateDialog.show();
1565 case 'save_picklist':
1566 this._loadPLSelect();
1567 acqLitSavePlDialog.show();
1570 case 'selector_ready':
1572 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
1573 acqLitChangeLiStateDialog.show();
1584 case 'rollback_receive_po':
1585 this.rollbackPoReceive();
1588 case 'create_assets':
1589 this.createAssets();
1592 case 'export_attr_list':
1593 this.chooseExportAttr();
1596 case 'add_brief_record':
1598 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
1600 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
1604 case "cancel_lineitems":
1605 this.maybeCancelLineitems();
1610 this.createAssets = function() {
1611 if(!this.isPO) return;
1612 if(!confirm(localeStrings.CREATE_PO_ASSETS_CONFIRM)) return;
1613 this.show('acq-lit-progress-numbers');
1615 fieldmapper.standardRequest(
1616 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
1618 params: [this.authtoken, this.isPO],
1619 onresponse: function(r) {
1620 var resp = openils.Util.readResponse(r);
1621 self._updateProgressNumbers(resp, true);
1627 this.maybeCancelLineitems = function() {
1628 openils.Util.show("acq-lit-cancel-reason", "inline");
1629 if (!acqLitCancelLineitemsButton._prepared) {
1630 var widget = new openils.widget.AutoFieldWidget({
1631 "fmField": "cancel_reason",
1633 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
1634 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1639 acqLitCancelLineitemsButton.onClick = function() {
1640 if (w.attr("value")) {
1641 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
1642 self._cancelLineitems(w.attr("value"));
1644 openils.Util.hide("acq-lit-cancel-reason");
1647 acqLitCancelLineitemsButton._prepared = true;
1653 this._cancelLineitems = function(reason) {
1654 var id_list = this.getSelected().map(function(o) { return o.id(); });
1655 fieldmapper.standardRequest(
1656 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
1657 "params": [openils.User.authtoken, id_list, reason],
1659 "onresponse": function(r) {
1660 if (r = openils.Util.readResponse(r)) {
1662 for (var id in r.li) {
1663 self.liCache[id].state(r.li[id].state);
1664 self.liCache[id].cancel_reason(
1665 r.li[id].cancel_reason
1667 self.updateLiState(self.liCache[id]);
1670 if (r.lid && self.copyCache) {
1671 for (var id in r.lid) {
1672 if (self.copyCache[id]) {
1673 self.copyCache[id].cancel_reason(
1674 r.lid[id].cancel_reason
1676 self.updateLidState(self.copyCache[id]);
1686 this.chooseExportAttr = function() {
1687 if (!acqLitExportAttrSelector._li_setup) {
1689 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
1691 "data": acqliad.toStoreData(
1693 "acqliad", {"code": li_exportable_attrs}
1698 acqLitExportAttrSelector.setValue();
1699 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
1700 acqLitExportAttrSelector._li_setup = true;
1702 openils.Util.show("acq-lit-export-attr-holder", "inline");
1705 this.exportAttrList = function() {
1706 var attr_def = acqLitExportAttrSelector.item;
1707 var li_list = this.getSelected();
1708 var value_list = li_list.map(
1710 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1711 attr_def.code, "lineitem_marc_attr_definition"
1714 ).filter(function(attr) { return Boolean(attr); });
1716 if (value_list.length > 0) {
1717 if (value_list.length < li_list.length) {
1719 dojo.string.substitute(
1720 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
1727 openils.XUL.contentToFileSaveDialog(
1728 value_list.join("\n"),
1729 localeStrings.EXPORT_SAVE_DIALOG_TITLE
1735 alert(dojo.string.substitute(
1736 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
1740 openils.Util.hide("acq-lit-export-attr-holder");
1743 this.printPO = function() {
1744 if(!this.isPO) return;
1745 progressDialog.show(true);
1746 fieldmapper.standardRequest(
1747 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
1749 params: [this.authtoken, this.isPO, 'html'],
1750 oncomplete: function(r) {
1751 progressDialog.hide();
1752 var evt = openils.Util.readResponse(r);
1753 if(evt && evt.template_output()) {
1754 win = window.open('','', 'resizable,width=800,height=600,scrollbars=1');
1755 win.document.body.innerHTML = evt.template_output().data();
1763 this.receivePO = function() {
1764 if (!this.isPO) return;
1766 for (var id in this.liCache) {
1767 /* assumption: liCache reflects exactly the
1768 * set of LIs that belong to our PO */
1769 if (this.liCache[id].state() != "received" &&
1770 !this.checkLiAlerts(id)) return;
1773 this.show('acq-lit-progress-numbers');
1775 fieldmapper.standardRequest(
1776 ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
1778 params: [this.authtoken, this.isPO],
1779 onresponse : function(r) {
1780 var resp = openils.Util.readResponse(r);
1781 self._updateProgressNumbers(resp, true);
1787 this.issueReceive = function(obj, rollback) {
1788 /* (For now) there shall be no marking LI or LIDs (un)received
1789 * except from the actual "view PO" interface. */
1790 if (!this.isPO) return;
1793 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
1795 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
1797 progressDialog.show(true);
1798 fieldmapper.standardRequest(
1799 ["open-ils.acq", method], {
1801 "params": [this.authtoken, obj.id()],
1802 "onresponse": function(r) {
1803 self.handleReceive(openils.Util.readResponse(r));
1804 progressDialog.hide();
1811 * Handles the responses from receive and rollback ML calls.
1813 this.handleReceive = function(resp) {
1816 for (var li_id in resp.li) {
1817 for (var key in resp.li[li_id])
1818 self.liCache[li_id][key](resp.li[li_id][key]);
1819 self.updateLiState(self.liCache[li_id]);
1823 if (typeof(self.poUpdateCallback) == "function")
1824 self.poUpdateCallback(resp.po);
1827 for (var lid_id in resp.lid) {
1828 for (var key in resp.lid[lid_id])
1829 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
1830 self.updateLidState(self.copyCache[lid_id]);
1836 this.rollbackPoReceive = function() {
1837 if(!this.isPO) return;
1838 if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
1839 this.show('acq-lit-progress-numbers');
1841 fieldmapper.standardRequest(
1842 ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
1844 params: [this.authtoken, this.isPO],
1845 onresponse : function(r) {
1846 var resp = openils.Util.readResponse(r);
1847 self._updateProgressNumbers(resp, true);
1853 this._updateProgressNumbers = function(resp, reloadOnComplete) {
1855 dojo.byId('acq-pl-lit-li-processed').innerHTML = resp.li;
1856 dojo.byId('acq-pl-lit-lid-processed').innerHTML = resp.lid;
1857 dojo.byId('acq-pl-lit-debits-processed').innerHTML = resp.debits_accrued;
1858 dojo.byId('acq-pl-lit-bibs-processed').innerHTML = resp.bibs;
1859 dojo.byId('acq-pl-lit-indexed-processed').innerHTML = resp.indexed;
1860 dojo.byId('acq-pl-lit-copies-processed').innerHTML = resp.copies;
1861 if(resp.complete && reloadOnComplete)
1862 location.href = location.href;
1866 this._createPO = function(fields) {
1867 this.show('acq-lit-progress-numbers');
1868 var po = new fieldmapper.acqpo();
1869 po.provider(this.createPoProviderSelector.attr('value'));
1870 po.ordering_agency(this.createPoAgencySelector.attr('value'));
1871 po.prepayment_required(fields.prepayment_required[0] ? true : false);
1873 var selected = this.getSelected( (fields.create_from == 'all') );
1874 if(selected.length == 0) return;
1876 var max = selected.length * 3;
1879 fieldmapper.standardRequest(
1880 ['open-ils.acq', 'open-ils.acq.purchase_order.create'],
1883 openils.User.authtoken,
1886 lineitems : selected.map(function(li) { return li.id() }),
1887 create_assets : fields.create_assets[0],
1891 onresponse : function(r) {
1892 var resp = openils.Util.readResponse(r);
1893 self._updateProgressNumbers(resp);
1895 location.href = oilsBasePath + '/eg/acq/po/view/' + resp.purchase_order.id();
1901 this._deleteLiList = function(list, idx) {
1902 if(idx == null) idx = 0;
1903 if(idx >= list.length) return;
1904 var liId = list[idx].id();
1905 fieldmapper.standardRequest(
1906 ['open-ils.acq', 'open-ils.acq.lineitem.delete'],
1908 params: [openils.User.authtoken, liId],
1909 oncomplete: function(r) {
1910 self.removeLineitem(liId);
1911 self._deleteLiList(list, ++idx);
1917 this.editOrderMarc = function(li) {
1919 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
1920 to true in about:config */
1922 if(!openils.XUL.enableXPConnect()) return;
1924 if(openils.XUL.isXUL()) {
1925 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
1927 win = window.open('/xul/server/cat/marcedit.xul');
1931 record : {marc : li.marc()},
1933 label: 'Save Record', // XXX I18N
1934 func: function(xmlString) {
1936 fieldmapper.standardRequest(
1937 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
1939 params: [openils.User.authtoken, li],
1940 oncomplete: function(r) {
1941 openils.Util.readResponse(r);
1943 self.drawInfo(li.id())
1952 this._savePl = function(values) {
1954 var selected = this.getSelected( (values.which == 'all') );
1955 openils.Util.show('acq-lit-generic-progress');
1957 if(values.new_name) {
1958 openils.acq.Picklist.create(
1959 {name: values.new_name},
1961 self._updateLiList(id, selected, 0,
1963 location.href = oilsBasePath + '/eg/acq/picklist/view/' + id;
1967 } else if(values.existing_pl) {
1968 // update lineitems to use an existing picklist
1969 self._updateLiList(values.existing_pl, selected, 0,
1971 location.href = oilsBasePath + '/eg/acq/picklist/view/' + values.existing_pl;
1976 this._updateLiState = function(values, state) {
1978 var selected = this.getSelected( (values.which == 'all') );
1979 if(!selected.length) return;
1980 dojo.forEach(selected, function(li) {li.state(state);});
1981 self._updateLiList(null, selected, 0,
1982 // TODO consider inline updates for efficiency
1983 function() { location.href = location.href }
1987 this._updateLiList = function(pl, list, idx, oncomplete) {
1988 if(idx >= list.length) return oncomplete();
1990 if(pl != null) li.picklist(pl);
1991 litGenericProgress.update({maximum: list.length, progress: idx});
1992 new openils.acq.Lineitem({lineitem:li}).update(
1994 self._updateLiList(pl, list, ++idx, oncomplete);
1999 this._loadPLSelect = function() {
2000 if(this._plSelectLoaded) return;
2002 function handleResponse(r) {
2003 plList.push(r.recv().content());
2005 var method = 'open-ils.acq.picklist.user.retrieve';
2006 fieldmapper.standardRequest(
2007 ['open-ils.acq', method],
2009 params: [this.authtoken],
2010 onresponse: handleResponse,
2011 oncomplete: function() {
2012 self._plSelectLoaded = true;
2013 acqLitAddExistingSelect.store =
2014 new dojo.data.ItemFileReadStore({data:acqpl.toStoreData(plList)});
2015 acqLitAddExistingSelect.setValue();
2021 this.showRealCopyEditUI = function(li) {
2026 this._fetchLineitem(li.id(),
2028 li = self.liCache[li.id()] = fullLi;
2032 id : li.lineitem_details().map(
2033 function(item) { return item.eg_copy_id() }
2037 oncomplete : function(r) {
2039 var r_list = openils.Util.readResponse( r );
2040 for (var i = 0; i < r_list.length; i++) {
2041 var copy = r_list[i];
2042 var volId = copy.call_number();
2043 var volume = self.volCache[volId];
2045 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2047 copy.call_number(volume);
2048 copyList.push(copy);
2051 // If we need to, we can pass in an update_copy function to handle the update instead of volume_item_creator
2052 xulG.volume_item_creator( { 'existing_copies' : copyList } );
2055 alert('error in oncomplete: ' + E);
2066 this.saveRealCopies = function() {
2067 progressDialog.show(true);
2068 var list = this.realCopyList.filter(function(copy) { return copy.ischanged(); });
2069 this.pcrud.update(list, {oncomplete: function() {
2070 progressDialog.hide();
2075 // grab the li-details for this lineitem, grab the linked copies and volumes, add them to the table
2076 this.showRealCopies = function(li) {
2077 while(this.realCopiesTbody.childNodes[0])
2078 this.realCopiesTbody.removeChild(this.realCopiesTbody.childNodes[0]);
2079 this.show('real-copies');
2081 this.realCopyList = [];
2083 var tabIndex = 1000;
2086 acqLitSaveRealCopies.onClick = function() {
2087 self.saveRealCopies();
2090 this._fetchLineitem(li.id(),
2092 li = self.liCache[li.id()] = fullLi;
2096 id : li.lineitem_details().map(
2097 function(item) { return item.eg_copy_id() }
2102 onresponse : function(r) {
2103 var copy = openils.Util.readResponse(r);
2104 var volId = copy.call_number();
2105 var volume = self.volCache[volId];
2107 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2109 self.addRealCopy(volume, copy, tabIndex++);
2117 this.addRealCopy = function(volume, copy, tabIndex) {
2118 var row = this.realCopiesRow.cloneNode(true);
2119 this.realCopyList.push(copy);
2123 ['owning_lib', 'location', 'circ_modifier', 'label', 'barcode'],
2126 var isvol = (field == 'owning_lib' || field == 'label');
2127 var widget = new openils.widget.AutoFieldWidget({
2129 fmObject : isvol ? volume : copy,
2130 parentNode : nodeByName(field, row),
2131 readOnly : (field != 'barcode'),
2134 var widgetDrawn = null;
2136 if(field == 'barcode') {
2138 widgetDrawn = function(w, ww) {
2139 var node = w.domNode;
2140 node.setAttribute('tabindex', ''+tabIndex);
2142 // on enter, select the next barcode input
2143 dojo.connect(w, 'onKeyDown',
2145 if(e.keyCode == dojo.keys.ENTER) {
2146 var ti = node.getAttribute('tabindex');
2147 var nextNode = dojo.query('[tabindex=' + String(Number(ti) + 1) + ']', self.realCopiesTbody)[0];
2148 if(nextNode) nextNode.select();
2153 dojo.connect(w, 'onChange',
2155 if(!val || val == copy.barcode()) return;
2156 copy.ischanged(true);
2162 if(self.realCopiesTbody.getElementsByTagName('TR').length == 0)
2167 widget.build(widgetDrawn);
2171 this.realCopiesTbody.appendChild(row);
2172 if(selectNode) selectNode.select();