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,
1225 if (field == "fund") {
1226 searchFilter = (copy.fund() ?
1227 {"-or": {"active": "t", "id": copy.fund()}} :
1230 searchFilter = null;
1232 var widget = new openils.widget.AutoFieldWidget({
1235 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1236 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1237 searchFilter : searchFilter,
1240 parentNode : dojo.query('[name='+field+']', row)[0],
1241 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
1242 readOnly : Boolean(copy.eg_copy_id())
1245 // make sure we capture the value from any async widgets
1247 copy[field](ww.getFormattedValue())
1248 self.copyWidgetCache[copy.id()][field] = w;
1251 dojo.connect(widget.widget, 'onChange',
1253 if(copy.isnew() || val != copy[field]()) {
1254 // prevent setting ischanged() automatically on widget load for existing copies
1255 copy[field](widget.getFormattedValue())
1256 copy.ischanged(true);
1263 this.updateLidState(copy, row);
1266 this.updateLidState = function(copy, row) {
1267 if (typeof(row) == "undefined") {
1269 'tr[copy_id="' + copy.id() + '"]', this.copyTbody
1274 var recv_link = nodeByName("receive", row);
1275 var unrecv_link = nodeByName("unreceive", row);
1276 var del_link = nodeByName("delete", row);
1277 var cxl_link = nodeByName("cancel", row);
1278 var cxl_reason_link = nodeByName("cancel_reason", row);
1280 if (copy.cancel_reason()) {
1281 openils.Util.hide(del_link.parentNode);
1282 openils.Util.hide(recv_link);
1283 openils.Util.hide(unrecv_link);
1284 openils.Util.hide(cxl_link);
1286 /* XXX the following may leak memory in a long lived table: dijits may not get destroyed... not positive. revisit. */
1287 var holds_reason = dojo.create(
1289 "style": "border-bottom: 1px dashed #000;",
1290 "innerHTML": "Cancelled" /* XXX [sic] and i18n */
1291 }, cxl_reason_link, "only"
1295 "label": "<em>" + copy.cancel_reason().label() +
1296 "</em><br />" + copy.cancel_reason().description(),
1297 "connectId": [holds_reason]
1298 }, dojo.create("span", null, cxl_reason_link, "last")
1300 openils.Util.show(cxl_reason_link, "inline");
1301 } else if (this.isPO) {
1302 openils.Util.hide(del_link.parentNode);
1303 openils.Util.hide(cxl_reason_link);
1305 /* Avoid showing (un)receive links, cancel links, for virt copies */
1306 if (copy.id() > 0) {
1307 if(copy.recv_time()) {
1308 openils.Util.hide(cxl_link);
1309 openils.Util.hide(recv_link);
1310 openils.Util.show(unrecv_link, "inline");
1311 unrecv_link.onclick = function() {
1312 if (confirm(localeStrings.UNRECEIVE_LID))
1313 self.issueReceive(copy, /* rollback */ true);
1316 openils.Util.hide(unrecv_link);
1317 openils.Util.show(recv_link, "inline");
1318 openils.Util.show(cxl_link, "inline");
1319 recv_link.onclick = function() {
1320 if (self.checkLiAlerts(copy.lineitem()))
1321 self.issueReceive(copy);
1323 cxl_link.onclick = function() {
1324 self.cancelLid(copy.id());
1328 openils.Util.hide(cxl_link);
1329 openils.Util.hide(unrecv_link);
1330 openils.Util.hide(recv_link);
1333 openils.Util.hide(unrecv_link);
1334 openils.Util.hide(recv_link);
1335 openils.Util.hide(cxl_reason_link);
1337 del_link.onclick = function() { self.deleteCopy(row) };
1338 openils.Util.show(del_link.parentNode);
1342 this.cancelLid = function(lid_id) {
1343 lidCancelDialog._lid_id = lid_id;
1344 openils.Util.show(lidCancelDialog.domNode.parentNode);
1345 lidCancelDialog.show();
1346 if (!lidCancelDialog._prepared) {
1347 var widget = new openils.widget.AutoFieldWidget({
1348 "fmField": "cancel_reason",
1349 "fmClass": "acqlid",
1350 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
1351 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1356 acqLidCancelButton.onClick = function() {
1357 if (w.attr("value")) {
1358 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
1360 lidCancelDialog._lid_id,
1364 lidCancelDialog.hide();
1367 lidCancelDialog._prepared = true;
1373 this._cancelLid = function(lid_id, reason) {
1374 fieldmapper.standardRequest(
1375 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
1376 "params": [openils.User.authtoken, lid_id, reason],
1378 "onresponse": function(r) {
1379 if (r = openils.Util.readResponse(r)) {
1381 for (var id in r.lid) {
1382 /* actually this should only iterate once */
1383 self.copyCache[id].cancel_reason(
1384 r.lid[id].cancel_reason
1386 self.updateLidState(self.copyCache[id]);
1395 this._confirmAlert = function(li, lin) {
1397 dojo.string.substitute(
1398 localeStrings.CONFIRM_LI_ALERT, [
1399 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1400 "title", "lineitem_marc_attr_definition"
1402 lin.alert_text().code(),
1403 lin.alert_text().description() || "",
1410 this.checkLiAlerts = function(li_id) {
1411 var li = this.liCache[li_id];
1413 var alert_notes = li.lineitem_notes().filter(
1414 function(o) { return Boolean(o.alert_text()); }
1417 /* this is _intentionally_ not done in a call to forEach() ... */
1418 for (var i = 0; i < alert_notes.length; i++) {
1419 if (this.noteAcks[alert_notes[i].id()])
1421 else if (!this._confirmAlert(li, alert_notes[i]))
1424 this.noteAcks[alert_notes[i].id()] = true;
1430 this.deleteCopy = function(row) {
1431 var copy = this.copyCache[row.getAttribute('copy_id')];
1432 copy.isdeleted(true);
1434 delete this.copyCache[copy.id()];
1435 this.copyTbody.removeChild(row);
1438 this._virtDfaCountsAsList = function() {
1440 for (var key in this.virtDfaCounts) {
1441 for (var i = 0; i < this.virtDfaCounts[key]; i++)
1447 this.saveCopyChanges = function(liId) {
1453 for(var id in this.copyCache) {
1454 var c = this.copyCache[id];
1455 if(!c.isdeleted()) total++;
1456 if(c.isnew() || c.ischanged() || c.isdeleted()) {
1457 if(c.id() < 0) c.id(null);
1462 if (typeof(this._copy_count_cb) == "function") {
1463 this._copy_count_cb(liId, total);
1466 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
1469 if (copies.length > 0) {
1470 openils.Util.show("acq-lit-update-copies-progress");
1471 fieldmapper.standardRequest(
1472 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1474 params: [openils.User.authtoken, copies],
1475 onresponse: function(r) {
1476 var res = openils.Util.readResponse(r);
1477 litUpdateCopiesProgress.update(res);
1479 oncomplete: function() {
1480 self.drawCopies(liId);
1481 openils.Util.hide("acq-lit-update-copies-progress");
1487 var dfa_list = this._virtDfaCountsAsList();
1488 if (dfa_list.length > 0) {
1489 fieldmapper.standardRequest(
1491 "open-ils.acq.distribution_formula.record_application"],
1494 "params": [openils.User.authtoken, dfa_list, liId],
1495 "onresponse": function(r) {
1496 var res = openils.Util.readResponse(r);
1497 if (res && res.length < dfa_list.length)
1498 alert(localeStrings.DFA_NOT_ALL);
1502 this.virtDfaCounts = {};
1506 this._updateCreatePoPrepayCheckbox = function(prepay) {
1507 var prepay = openils.Util.isTrue(prepay);
1508 this._prepayRequiredByVendor = prepay;
1509 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
1512 this._confirmPoPrepaySituation = function() {
1513 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
1514 if (want_prepay != this._prepayRequiredByVendor) {
1517 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
1518 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
1525 this.applySelectedLiAction = function(action) {
1529 case 'delete_selected':
1530 this._deleteLiList(self.getSelected());
1533 case 'create_order':
1535 if(!this.createPoProviderSelector) {
1536 var widget = new openils.widget.AutoFieldWidget({
1537 fmField : 'provider',
1539 searchFilter: {"active": "t"},
1540 parentNode : dojo.byId('acq-lit-po-provider'),
1542 "onChange": function() {
1544 self._updateCreatePoPrepayCheckbox(
1545 this.item.prepayment_required
1552 function(w) { self.createPoProviderSelector = w; }
1556 if(!this.createPoAgencySelector) {
1557 var widget = new openils.widget.AutoFieldWidget({
1558 fmField : 'ordering_agency',
1560 parentNode : dojo.byId('acq-lit-po-agency'),
1561 orgLimitPerms : ['CREATE_PURCHASE_ORDER'],
1564 function(w) { self.createPoAgencySelector = w; }
1569 acqLitPoCreateDialog.show();
1572 case 'save_picklist':
1573 this._loadPLSelect();
1574 acqLitSavePlDialog.show();
1577 case 'selector_ready':
1579 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
1580 acqLitChangeLiStateDialog.show();
1591 case 'rollback_receive_po':
1592 this.rollbackPoReceive();
1595 case 'create_assets':
1596 this.createAssets();
1599 case 'export_attr_list':
1600 this.chooseExportAttr();
1603 case 'add_brief_record':
1605 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
1607 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
1611 case "cancel_lineitems":
1612 this.maybeCancelLineitems();
1617 this.createAssets = function() {
1618 if(!this.isPO) return;
1619 if(!confirm(localeStrings.CREATE_PO_ASSETS_CONFIRM)) return;
1620 this.show('acq-lit-progress-numbers');
1622 fieldmapper.standardRequest(
1623 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
1625 params: [this.authtoken, this.isPO],
1626 onresponse: function(r) {
1627 var resp = openils.Util.readResponse(r);
1628 self._updateProgressNumbers(resp, true);
1634 this.maybeCancelLineitems = function() {
1635 openils.Util.show("acq-lit-cancel-reason", "inline");
1636 if (!acqLitCancelLineitemsButton._prepared) {
1637 var widget = new openils.widget.AutoFieldWidget({
1638 "fmField": "cancel_reason",
1640 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
1641 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1646 acqLitCancelLineitemsButton.onClick = function() {
1647 if (w.attr("value")) {
1648 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
1649 self._cancelLineitems(w.attr("value"));
1651 openils.Util.hide("acq-lit-cancel-reason");
1654 acqLitCancelLineitemsButton._prepared = true;
1660 this._cancelLineitems = function(reason) {
1661 var id_list = this.getSelected().map(function(o) { return o.id(); });
1662 fieldmapper.standardRequest(
1663 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
1664 "params": [openils.User.authtoken, id_list, reason],
1666 "onresponse": function(r) {
1667 if (r = openils.Util.readResponse(r)) {
1669 for (var id in r.li) {
1670 self.liCache[id].state(r.li[id].state);
1671 self.liCache[id].cancel_reason(
1672 r.li[id].cancel_reason
1674 self.updateLiState(self.liCache[id]);
1677 if (r.lid && self.copyCache) {
1678 for (var id in r.lid) {
1679 if (self.copyCache[id]) {
1680 self.copyCache[id].cancel_reason(
1681 r.lid[id].cancel_reason
1683 self.updateLidState(self.copyCache[id]);
1693 this.chooseExportAttr = function() {
1694 if (!acqLitExportAttrSelector._li_setup) {
1696 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
1698 "data": acqliad.toStoreData(
1700 "acqliad", {"code": li_exportable_attrs}
1705 acqLitExportAttrSelector.setValue();
1706 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
1707 acqLitExportAttrSelector._li_setup = true;
1709 openils.Util.show("acq-lit-export-attr-holder", "inline");
1712 this.exportAttrList = function() {
1713 var attr_def = acqLitExportAttrSelector.item;
1714 var li_list = this.getSelected();
1715 var value_list = li_list.map(
1717 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1718 attr_def.code, "lineitem_marc_attr_definition"
1721 ).filter(function(attr) { return Boolean(attr); });
1723 if (value_list.length > 0) {
1724 if (value_list.length < li_list.length) {
1726 dojo.string.substitute(
1727 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
1734 openils.XUL.contentToFileSaveDialog(
1735 value_list.join("\n"),
1736 localeStrings.EXPORT_SAVE_DIALOG_TITLE
1742 alert(dojo.string.substitute(
1743 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
1747 openils.Util.hide("acq-lit-export-attr-holder");
1750 this.printPO = function() {
1751 if(!this.isPO) return;
1752 progressDialog.show(true);
1753 fieldmapper.standardRequest(
1754 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
1756 params: [this.authtoken, this.isPO, 'html'],
1757 oncomplete: function(r) {
1758 progressDialog.hide();
1759 var evt = openils.Util.readResponse(r);
1760 if(evt && evt.template_output()) {
1761 win = window.open('','', 'resizable,width=800,height=600,scrollbars=1');
1762 win.document.body.innerHTML = evt.template_output().data();
1770 this.receivePO = function() {
1771 if (!this.isPO) return;
1773 for (var id in this.liCache) {
1774 /* assumption: liCache reflects exactly the
1775 * set of LIs that belong to our PO */
1776 if (this.liCache[id].state() != "received" &&
1777 !this.checkLiAlerts(id)) return;
1780 this.show('acq-lit-progress-numbers');
1782 fieldmapper.standardRequest(
1783 ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
1785 params: [this.authtoken, this.isPO],
1786 onresponse : function(r) {
1787 var resp = openils.Util.readResponse(r);
1788 self._updateProgressNumbers(resp, true);
1794 this.issueReceive = function(obj, rollback) {
1795 /* (For now) there shall be no marking LI or LIDs (un)received
1796 * except from the actual "view PO" interface. */
1797 if (!this.isPO) return;
1800 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
1802 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
1804 progressDialog.show(true);
1805 fieldmapper.standardRequest(
1806 ["open-ils.acq", method], {
1808 "params": [this.authtoken, obj.id()],
1809 "onresponse": function(r) {
1810 self.handleReceive(openils.Util.readResponse(r));
1811 progressDialog.hide();
1818 * Handles the responses from receive and rollback ML calls.
1820 this.handleReceive = function(resp) {
1823 for (var li_id in resp.li) {
1824 for (var key in resp.li[li_id])
1825 self.liCache[li_id][key](resp.li[li_id][key]);
1826 self.updateLiState(self.liCache[li_id]);
1830 if (typeof(self.poUpdateCallback) == "function")
1831 self.poUpdateCallback(resp.po);
1834 for (var lid_id in resp.lid) {
1835 for (var key in resp.lid[lid_id])
1836 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
1837 self.updateLidState(self.copyCache[lid_id]);
1843 this.rollbackPoReceive = function() {
1844 if(!this.isPO) return;
1845 if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
1846 this.show('acq-lit-progress-numbers');
1848 fieldmapper.standardRequest(
1849 ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
1851 params: [this.authtoken, this.isPO],
1852 onresponse : function(r) {
1853 var resp = openils.Util.readResponse(r);
1854 self._updateProgressNumbers(resp, true);
1860 this._updateProgressNumbers = function(resp, reloadOnComplete) {
1862 dojo.byId('acq-pl-lit-li-processed').innerHTML = resp.li;
1863 dojo.byId('acq-pl-lit-lid-processed').innerHTML = resp.lid;
1864 dojo.byId('acq-pl-lit-debits-processed').innerHTML = resp.debits_accrued;
1865 dojo.byId('acq-pl-lit-bibs-processed').innerHTML = resp.bibs;
1866 dojo.byId('acq-pl-lit-indexed-processed').innerHTML = resp.indexed;
1867 dojo.byId('acq-pl-lit-copies-processed').innerHTML = resp.copies;
1868 if(resp.complete && reloadOnComplete)
1869 location.href = location.href;
1873 this._createPO = function(fields) {
1874 this.show('acq-lit-progress-numbers');
1875 var po = new fieldmapper.acqpo();
1876 po.provider(this.createPoProviderSelector.attr('value'));
1877 po.ordering_agency(this.createPoAgencySelector.attr('value'));
1878 po.prepayment_required(fields.prepayment_required[0] ? true : false);
1880 var selected = this.getSelected( (fields.create_from == 'all') );
1881 if(selected.length == 0) return;
1883 var max = selected.length * 3;
1886 fieldmapper.standardRequest(
1887 ['open-ils.acq', 'open-ils.acq.purchase_order.create'],
1890 openils.User.authtoken,
1893 lineitems : selected.map(function(li) { return li.id() }),
1894 create_assets : fields.create_assets[0],
1898 onresponse : function(r) {
1899 var resp = openils.Util.readResponse(r);
1900 self._updateProgressNumbers(resp);
1902 location.href = oilsBasePath + '/eg/acq/po/view/' + resp.purchase_order.id();
1908 this._deleteLiList = function(list, idx) {
1909 if(idx == null) idx = 0;
1910 if(idx >= list.length) return;
1911 var liId = list[idx].id();
1912 fieldmapper.standardRequest(
1913 ['open-ils.acq', 'open-ils.acq.lineitem.delete'],
1915 params: [openils.User.authtoken, liId],
1916 oncomplete: function(r) {
1917 self.removeLineitem(liId);
1918 self._deleteLiList(list, ++idx);
1924 this.editOrderMarc = function(li) {
1926 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
1927 to true in about:config */
1929 if(!openils.XUL.enableXPConnect()) return;
1931 if(openils.XUL.isXUL()) {
1932 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
1934 win = window.open('/xul/server/cat/marcedit.xul');
1938 record : {marc : li.marc()},
1940 label: 'Save Record', // XXX I18N
1941 func: function(xmlString) {
1943 fieldmapper.standardRequest(
1944 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
1946 params: [openils.User.authtoken, li],
1947 oncomplete: function(r) {
1948 openils.Util.readResponse(r);
1950 self.drawInfo(li.id())
1959 this._savePl = function(values) {
1961 var selected = this.getSelected( (values.which == 'all') );
1962 openils.Util.show('acq-lit-generic-progress');
1964 if(values.new_name) {
1965 openils.acq.Picklist.create(
1966 {name: values.new_name},
1968 self._updateLiList(id, selected, 0,
1970 location.href = oilsBasePath + '/eg/acq/picklist/view/' + id;
1974 } else if(values.existing_pl) {
1975 // update lineitems to use an existing picklist
1976 self._updateLiList(values.existing_pl, selected, 0,
1978 location.href = oilsBasePath + '/eg/acq/picklist/view/' + values.existing_pl;
1983 this._updateLiState = function(values, state) {
1985 var selected = this.getSelected( (values.which == 'all') );
1986 if(!selected.length) return;
1987 dojo.forEach(selected, function(li) {li.state(state);});
1988 self._updateLiList(null, selected, 0,
1989 // TODO consider inline updates for efficiency
1990 function() { location.href = location.href }
1994 this._updateLiList = function(pl, list, idx, oncomplete) {
1995 if(idx >= list.length) return oncomplete();
1997 if(pl != null) li.picklist(pl);
1998 litGenericProgress.update({maximum: list.length, progress: idx});
1999 new openils.acq.Lineitem({lineitem:li}).update(
2001 self._updateLiList(pl, list, ++idx, oncomplete);
2006 this._loadPLSelect = function() {
2007 if(this._plSelectLoaded) return;
2009 function handleResponse(r) {
2010 plList.push(r.recv().content());
2012 var method = 'open-ils.acq.picklist.user.retrieve';
2013 fieldmapper.standardRequest(
2014 ['open-ils.acq', method],
2016 params: [this.authtoken],
2017 onresponse: handleResponse,
2018 oncomplete: function() {
2019 self._plSelectLoaded = true;
2020 acqLitAddExistingSelect.store =
2021 new dojo.data.ItemFileReadStore({data:acqpl.toStoreData(plList)});
2022 acqLitAddExistingSelect.setValue();
2028 this.showRealCopyEditUI = function(li) {
2033 this._fetchLineitem(li.id(),
2035 li = self.liCache[li.id()] = fullLi;
2039 id : li.lineitem_details().map(
2040 function(item) { return item.eg_copy_id() }
2044 oncomplete : function(r) {
2046 var r_list = openils.Util.readResponse( r );
2047 for (var i = 0; i < r_list.length; i++) {
2048 var copy = r_list[i];
2049 var volId = copy.call_number();
2050 var volume = self.volCache[volId];
2052 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2054 copy.call_number(volume);
2055 copyList.push(copy);
2058 // If we need to, we can pass in an update_copy function to handle the update instead of volume_item_creator
2059 xulG.volume_item_creator( { 'existing_copies' : copyList } );
2062 alert('error in oncomplete: ' + E);
2073 this.saveRealCopies = function() {
2074 progressDialog.show(true);
2075 var list = this.realCopyList.filter(function(copy) { return copy.ischanged(); });
2076 this.pcrud.update(list, {oncomplete: function() {
2077 progressDialog.hide();
2082 // grab the li-details for this lineitem, grab the linked copies and volumes, add them to the table
2083 this.showRealCopies = function(li) {
2084 while(this.realCopiesTbody.childNodes[0])
2085 this.realCopiesTbody.removeChild(this.realCopiesTbody.childNodes[0]);
2086 this.show('real-copies');
2088 this.realCopyList = [];
2090 var tabIndex = 1000;
2093 acqLitSaveRealCopies.onClick = function() {
2094 self.saveRealCopies();
2097 this._fetchLineitem(li.id(),
2099 li = self.liCache[li.id()] = fullLi;
2103 id : li.lineitem_details().map(
2104 function(item) { return item.eg_copy_id() }
2109 onresponse : function(r) {
2110 var copy = openils.Util.readResponse(r);
2111 var volId = copy.call_number();
2112 var volume = self.volCache[volId];
2114 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2116 self.addRealCopy(volume, copy, tabIndex++);
2124 this.addRealCopy = function(volume, copy, tabIndex) {
2125 var row = this.realCopiesRow.cloneNode(true);
2126 this.realCopyList.push(copy);
2130 ['owning_lib', 'location', 'circ_modifier', 'label', 'barcode'],
2133 var isvol = (field == 'owning_lib' || field == 'label');
2134 var widget = new openils.widget.AutoFieldWidget({
2136 fmObject : isvol ? volume : copy,
2137 parentNode : nodeByName(field, row),
2138 readOnly : (field != 'barcode'),
2141 var widgetDrawn = null;
2143 if(field == 'barcode') {
2145 widgetDrawn = function(w, ww) {
2146 var node = w.domNode;
2147 node.setAttribute('tabindex', ''+tabIndex);
2149 // on enter, select the next barcode input
2150 dojo.connect(w, 'onKeyDown',
2152 if(e.keyCode == dojo.keys.ENTER) {
2153 var ti = node.getAttribute('tabindex');
2154 var nextNode = dojo.query('[tabindex=' + String(Number(ti) + 1) + ']', self.realCopiesTbody)[0];
2155 if(nextNode) nextNode.select();
2160 dojo.connect(w, 'onChange',
2162 if(!val || val == copy.barcode()) return;
2163 copy.ischanged(true);
2169 if(self.realCopiesTbody.getElementsByTagName('TR').length == 0)
2174 widget.build(widgetDrawn);
2178 this.realCopiesTbody.appendChild(row);
2179 if(selectNode) selectNode.select();