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 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
209 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
210 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
212 this.updateLiNotesCount(li, row);
214 // show which PO this lineitem is a member of
215 if(li.purchase_order() && !this.isPO) {
217 this.poCache[li.purchase_order()] =
218 this.poCache[li.purchase_order()] ||
219 fieldmapper.standardRequest(
220 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
222 this.authtoken, li.purchase_order(), {
223 "flesh_price_summary": true,
224 "flesh_lineitem_count": true
227 if(po && !this.isMeta) {
228 openils.Util.show(nodeByName('po', row), 'inline');
229 var link = nodeByName('po_link', row);
230 link.setAttribute('href', oilsBasePath + '/acq/po/view/' + li.purchase_order());
231 link.innerHTML = 'PO: ' + po.name(); // TODO i18n
235 // show which picklist this lineitem is a member of
236 if(li.picklist() && (this.isPO || this.isMeta)) {
238 this.plCache[li.picklist()] =
239 this.plCache[li.picklist()] ||
240 fieldmapper.standardRequest(
241 ['open-ils.acq', 'open-ils.acq.picklist.retrieve'],
242 {params: [this.authtoken, li.picklist()]});
244 openils.Util.show(nodeByName('pl', row), 'inline');
245 var link = nodeByName('pl_link', row);
246 link.setAttribute('href', oilsBasePath + '/acq/picklist/view/' + li.picklist());
247 link.innerHTML = 'PL: '+pl.name(); // TODO i18n
251 var countNode = nodeByName('count', row);
252 var count = li.item_count() || 0;
253 if (typeof(this._copy_count_cb) == "function") {
254 this._copy_count_cb(li.id(), count);
256 countNode.innerHTML = count;
257 countNode.id = 'acq-lit-copy-count-label-' + li.id();
260 var priceInput = dojo.query('[name=price]', row)[0];
261 priceInput.value = li.estimated_unit_price() || '';
262 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
264 // show either "mark received" or "unreceive" as appropriate
265 this.updateLiState(li, row);
267 if (!skip_final_placement) {
268 self.tbody.appendChild(row);
269 self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
275 this.updateLiNotesCount = function(li, row) {
276 if (typeof(row) == "undefined")
277 row = dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
279 var has_notes = (li.lineitem_notes().filter(
280 function(o) { return Boolean (o.alert_text()); }
283 /* U+2691 is the code point for a filled-in flag character */
284 nodeByName("notes_alert_flag", row).innerHTML =
285 has_notes ? "⚑" : "";
286 nodeByName("noteslink", row).style.fontStyle =
287 has_notes ? "italic" : "normal";
288 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
291 /* XXX NOT related to _updateLiState(). rethink */
292 this.updateLiState = function(li, row) {
293 if (typeof(row) == "undefined")
294 row = dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
296 var recv_link = nodeByName("receive_link", row);
297 var unrecv_link = nodeByName("unreceive_link", row);
298 var real_copies_link = nodeByName("real_copies_link", row);
299 var holdings_maintenance_link = nodeByName("holdings_maintenance_link", row);
300 var state_cell = nodeByName("li_state", row);
302 if (li.state() == "cancelled") {
303 if (typeof li.cancel_reason() == "object") {
304 var holds_state = dojo.create(
306 "style": "border-bottom: 1px dashed #000;",
307 "innerHTML": li.state()
308 }, state_cell, "only"
312 "label": "<em>" + li.cancel_reason().label() +
313 "</em><br />" + li.cancel_reason().description(),
314 "connectId": [holds_state]
315 }, dojo.create("span", null, state_cell, "last")
318 state_cell.innerHTML = li.state(); // TODO i18n state labels
321 state_cell.innerHTML = li.state(); // TODO i18n state labels
325 /* handle row coloring for based on LI state */
326 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
327 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
329 /* handle links that appear/disappear based on whether LI is received */
334 openils.Util.hide(real_copies_link);
335 openils.Util.hide(unrecv_link);
336 openils.Util.show(recv_link, "inline");
337 recv_link.onclick = function() {
338 if (self.checkLiAlerts(li.id()))
339 self.issueReceive(li);
343 openils.Util.hide(recv_link);
344 openils.Util.show(unrecv_link, "inline");
345 unrecv_link.onclick = function() {
346 if (confirm(localeStrings.UNRECEIVE_LI))
347 self.issueReceive(li, /* rollback */ true);
349 // TODO we should allow editing before receipt, in which case the
350 // test should be "if 1 or more real (acp) copies exist
351 openils.Util.show(real_copies_link, "inline");
352 real_copies_link.onclick = function() {
353 self.showRealCopyEditUI(li);
355 openils.Util.show(holdings_maintenance_link, "inline");
356 holdings_maintenance_link.onclick = self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser' );
361 openils.Util.hide(recv_link);
362 openils.Util.hide(unrecv_link);
363 openils.Util.hide(real_copies_link);
367 this._setAlertStore = function() {
368 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
370 "data": acqliat.toStoreData(
372 "acqliat", {"id": {"!=": null}}
377 acqLitAlertAlertText.setValue(); /* make the store "live" */
378 acqLitAlertAlertText._store_ready = true;
382 * Draws and shows the lineitem notes pane
384 this.drawLiNotes = function(li) {
387 if (!acqLitAlertAlertText._store_ready)
388 this._setAlertStore();
391 li.lineitem_notes().sort(
393 if(a.edit_time() < b.edit_time()) return 1;
399 while(this.liNotesTbody.childNodes[0])
400 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
403 acqLitCreateNoteSubmit.onClick = function() {
404 var value = acqLitCreateNoteText.attr('value');
406 var note = new fieldmapper.acqlin();
409 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
412 note.lineitem(li.id());
414 self.updateLiNotes(li, note);
415 acqLitCreateNoteVendorPublic.attr("checked", false);
416 acqLitCreateNoteText.attr("value", "");
419 acqLitCreateAlertSubmit.onClick = function() {
420 if (!acqLitAlertAlertText.item) {
421 alert(localeStrings.ALERT_UNSELECTED);
425 var alert_text = new fieldmapper.acqliat().fromStoreItem(
426 acqLitAlertAlertText.item
428 var value = acqLitAlertNoteValue.attr("value") || "";
430 var note = new fieldmapper.acqlin();
432 note.lineitem(li.id());
434 note.alert_text(alert_text);
436 self.updateLiNotes(li, note);
439 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
443 * Draws a single lineitem note in the notes pane
445 this.addLiNote = function(li, note) {
446 if(note.isdeleted()) return;
448 var row = self.liNotesRow.cloneNode(true);
449 nodeByName("value", row).innerHTML = note.value();
450 var alert_node = nodeByName("alert_code", row);
451 if (note.alert_text()) {
452 alert_node.innerHTML = note.alert_text().code();
453 if (note.alert_text().description()) {
456 "connectId": [alert_node],
457 "label": note.alert_text().description()
458 }, dojo.create("span", null, alert_node, "after")
463 if (openils.Util.isTrue(note.vendor_public()))
464 nodeByName("vendor_public", row).innerHTML =
465 localeStrings.VENDOR_PUBLIC;
467 nodeByName("delete", row).onclick = function() {
468 note.isdeleted(true);
469 self.liNotesTbody.removeChild(row);
470 self.updateLiNotes(li);
473 if(note.edit_time()) {
474 nodeByName("edit_time", row).innerHTML =
475 dojo.date.locale.format(
476 dojo.date.stamp.fromISOString(note.edit_time()),
477 {formatLength:'short'});
480 self.liNotesTbody.appendChild(row);
484 * Updates any new/changed/deleted notes on the server
486 this.updateLiNotes = function(li, newNote) {
492 notes = li.lineitem_notes().filter(
494 if(note.ischanged() || note.isnew() || note.isdeleted())
500 if(notes.length == 0) return;
501 progressDialog.show();
503 fieldmapper.standardRequest(
504 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
506 params : [this.authtoken, notes],
507 onresponse : function(r) {
508 var resp = openils.Util.readResponse(r);
513 // remove the old changed notes
515 dojo.forEach(li.lineitem_notes(),
517 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
521 li.lineitem_notes(list);
524 progressDialog.hide();
525 self.updateLiNotesCount(li);
526 self.drawLiNotes(li);
530 progressDialog.update(resp);
531 var newnote = resp.note;
533 if(!newnote.isdeleted()) {
534 newnote.isnew(false);
535 newnote.ischanged(false);
536 li.lineitem_notes().push(newnote);
543 this.updateLiPrice = function(input, li) {
545 var price = input.value;
546 if(Number(price) == Number(li.estimated_unit_price())) return;
548 fieldmapper.standardRequest(
549 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
551 params : [this.authtoken, li.id(), price],
552 oncomplete : function(r) {
553 openils.Util.readResponse(r);
559 this.removeLineitem = function(liId) {
560 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
561 delete this.liCache[liId];
562 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
565 this.drawInfo = function(liId) {
566 if (!this._isRelatedViewer) {
567 var d = dojo.byId("acq-lit-info-related");
568 if (!this.relCache[liId]) {
569 fieldmapper.standardRequest(
572 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
575 "params": [openils.User.authtoken, liId],
576 "onresponse": function(r) {
577 self.relCache[liId] = openils.Util.readResponse(r);
578 nodeByName("related_number", d).innerHTML =
581 self.relCache[liId] >1 ? "show" : "hide"
587 nodeByName("related_number", d).innerHTML = this.relCache[liId];
588 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
593 openils.acq.Lineitem.fetchAttrDefs(
595 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
600 this._fetchLineitem = function(liId, handler) {
602 var li = this.liCache[liId];
603 if(li && li.marc() && li.lineitem_details())
606 fieldmapper.standardRequest(
607 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve'],
610 params: [self.authtoken, liId, {
612 flesh_cancel_reason: true,
613 flesh_li_details: true,
614 flesh_fund_debit: true }],
616 oncomplete: function(r) {
617 var li = openils.Util.readResponse(r);
624 this._drawInfo = function(li) {
626 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
629 openils.Util.hide('acq-lit-marc-order-record-label');
630 openils.Util.hide(acqLitEditOrderMarc.domNode);
631 openils.Util.show('acq-lit-marc-real-record-label');
633 openils.Util.show('acq-lit-marc-order-record-label');
634 openils.Util.show(acqLitEditOrderMarc.domNode);
635 openils.Util.hide('acq-lit-marc-real-record-label');
638 this.drawMarcHTML(li);
639 this.infoTbody = dojo.byId('acq-lit-info-tbody');
642 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
643 while(this.infoTbody.childNodes[0])
644 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
646 if (!this._isRelatedViewer) {
647 for(var i = 0; i < li.attributes().length; i++) {
648 var attr = li.attributes()[i];
649 var row = this.infoRow.cloneNode(true);
651 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
652 var name = openils.acq.Lineitem.attrDefs[type].filter(
654 return (a.code() == attr.attr_name());
656 ).pop().description();
658 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
659 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
660 this.infoTbody.appendChild(row);
663 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
664 "/eg/acq/lineitem/related/" + li.id();
669 openils.Util.show('acq-lit-info-cat-link');
670 var link = dojo.byId('acq-lit-info-cat-link').getElementsByTagName('a')[0];
672 if(openils.XUL.isXUL()) {
674 link.setAttribute('href', 'javascript:void(0);');
675 link.onclick = this.generateMakeRecTab( li.eg_bib_id() );
678 var href = link.getAttribute('href');
680 link.setAttribute('href', href + li.eg_bib_id());
683 openils.Util.hide('acq-lit-info-cat-link');
687 this.generateMakeRecTab = function(bib_id,default_view) {
691 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
694 show_nav_buttons : true,
695 show_print_button : true,
696 opac_url : xulG.url_prefix(xulG.urls.opac_rdetail + '?r=' + bib_id),
697 default_view : default_view
703 this.drawMarcHTML = function(li) {
704 var params = [null, true, li.marc()];
706 params = [li.eg_bib_id(), true];
708 fieldmapper.standardRequest(
709 ['open-ils.search', 'open-ils.search.biblio.record.html'],
712 oncomplete: function(r) {
713 dojo.byId('acq-lit-marc-div').innerHTML =
714 openils.Util.readResponse(r);
720 this.drawCopies = function(liId) {
724 this.copyWidgetCache = {};
725 this.oldCopyWidgetCache = {};
726 this.virtDfaCounts = {};
727 this.realDfaCache = {};
730 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
731 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
732 acqLitCopyCountInput.attr('value', '0');
734 while(this.copyTbody.childNodes[0])
735 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
737 this._drawBatchCopyWidgets();
739 this._drawDistribApplied(liId);
741 this._fetchDistribFormulas(
743 openils.acq.Lineitem.fetchAttrDefs(
745 self._fetchLineitem(liId, function(li){self._drawCopies(li);});
752 this._saveDistribAppliedTemplates = function() {
753 if (!this._appliedDistribTemplate) {
754 this._appliedDistribTemplate =
755 dojo.byId("acq-lit-distrib-applied-tbody").
756 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
757 dojo.attr(this._appliedDistribTemplate, "id");
761 this._drawDistribApplied = function(liId) {
762 /* Build this table while hidden to prevent rendering artifacts */
763 openils.Util.hide("acq-lit-distrib-applied-tbody");
765 this._saveDistribAppliedTemplates();
767 /* Remove any rows in the table from previous populations */
768 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
769 forEach(dojo.destroy);
771 /* Unregister all dijits previously created (for some reason this isn't
772 * covered by the above destroy calls). */
773 dijit.registry.forEach(
774 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
777 /* Populate the table with our liId */
779 fieldmapper.standardRequest(
781 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
784 "params": [self.authtoken, liId],
785 "onresponse": function(r) {
786 var dfa = openils.Util.readResponse(r);
789 self.realDfaCache[dfa.id()] = dfa;
790 self._drawDistribAppliedUnit(dfa);
793 "oncomplete": function() {
794 /* Reveal built table */
797 "acq-lit-distrib-applied-tbody", "table-row-group"
805 this._drawDistribAppliedUnit = function(dfa) {
807 var row = dojo.query(
808 'tr[formula="' + dfa.formula().id() + '"]',
809 "acq-lit-distrib-applied-tbody"
814 row = dojo.clone(this._appliedDistribTemplate);
815 dojo.attr(row, "formula", dfa.formula().id());
816 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
819 var td = dojo.query("td", row)[0];
821 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
822 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
825 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
827 new dijit.form.Button(
829 "onClick": function() {
830 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
834 /* XXX I /cannot/ make the following work in as a CSS class
835 * for some reason. So frustrating... */
836 "style": function(id) {
838 "font-weight: bold; color: #c00;" :
840 }(dfa.id()) + "margin: 0 6px;display: inline;"
841 }, "dfa-button-" + dfa.id()
845 "connectId": ["dfa-button-" + dfa.id()],
846 "label": dojo.string.substitute(
847 localeStrings.DFA_TIP, dfa.id() > 0 ? [
848 openils.User.formalName(dfa.creator()),
849 dojo.date.locale.format(
850 dojo.date.stamp.fromISOString(dfa.create_time()),
851 {"formatLength":"short"}
853 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
855 }, "dfa-tip-" + dfa.id()
859 this.deleteDfa = function(dfa) {
860 if (dfa.id() > 0) { /* real */
861 this.pcrud.eliminate(
864 "oncomplete": function() {
865 self._removeDistribApplied(dfa.id());
866 delete self.realDfaCache[dfa.id()];
870 } else { /* virtual */
871 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
872 this.virtDfaCounts[dfa.formula().id()] = 0;
873 /* hasn't been saved yet, so no need to do anything server side */
874 this._removeDistribApplied(dfa.id());
879 this._removeDistribApplied = function(dfaId) {
880 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
881 dijit.registry.forEach(
882 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
884 this._removeDistribAppliedEmptyRows();
887 this._removeAllDistribAppliedVirtual = function() {
888 /* Unregister dijits */
889 dijit.registry.forEach(
890 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
892 this._removeDistribAppliedEmptyRows();
895 this._removeDistribAppliedEmptyRows = function() {
896 /* Remove any rows with no DFA at all */
897 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
899 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
905 * Insert a new row into the distribution formula selection form
907 this._addDistribFormulaRow = function() {
910 if (!self.distribForms) {
911 // no formulas, hide the form
912 openils.Util.hide('acq-lit-distrib-formula-tbody');
916 if(!this.distribFormulaTemplate)
917 this.distribFormulaTemplate =
918 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
920 var row = this.distribFormulaTemplate.cloneNode(true);
921 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
923 this.dfSelector = new dijit.form.FilteringSelect(
924 {"labelAttr": "dynLabel", "labelType": "html"},
925 nodeByName("selector", row)
927 this._updateFormulaStore();
928 this.dfSelector.fetchProperties =
929 {"sort": [{"attribute": "use_count", "descending": true}]};
931 var apply = new dijit.form.Button(
932 {"label": localeStrings.APPLY},
933 nodeByName('set_button', row)
936 var reset = new dijit.form.Button(
937 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
938 nodeByName("reset_button", row)
941 dojo.connect(apply, 'onClick',
943 var form_id = self.dfSelector.attr("value");
945 self._applyDistribFormula(form_id);
946 reset.attr("disabled", false);
950 dojo.connect(reset, 'onClick',
952 self.restoreCopyFieldsBeforeDF();
953 self.virtDfaCounts = {};
956 self._updateFormulaStore();
957 self._removeAllDistribAppliedVirtual();
958 reset.attr("disabled", "true");
965 * Applies a distrib formula to the current set of copies
967 this._applyDistribFormula = function(formula) {
970 formula = this.distribForms.filter(
971 function(form) { return form.id() == formula; }
974 var copyRows = dojo.query('tr', self.copyTbody);
976 if (this.dfeOffset >= copyRows.length) {
977 alert(localeStrings.OUT_OF_COPIES);
981 var entries_applied = 0;
983 var rowIndex = this.dfeOffset;
984 rowIndex < copyRows.length;
988 var row = copyRows[rowIndex];
989 var copy_id = row.getAttribute('copy_id');
990 var copyWidgets = this.copyWidgetCache[copy_id];
991 var entryIndex = this.dfeOffset;
994 // find the correct entry for the current row
995 dojo.forEach(formula.entries(),
998 entryIndex += e.item_count();
999 if(entryIndex > rowIndex)
1007 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
1008 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
1011 this.saveCopyFieldsBeforeDF(copy_id);
1012 this._copy_fields_for_acqdf.forEach(
1014 if(entry[field]()) {
1015 copyWidgets[field].attr('value', (entry[field]()));
1022 if (entries_applied) {
1023 this.virtDfaCounts[formula.id()] =
1024 ++(this.virtDfaCounts[formula.id()]) || 1;
1025 this._updateFormulaStore();
1026 this._drawDistribAppliedUnit(
1028 var dfa = new acqdfa();
1029 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
1032 this.dfeOffset += entries_applied;
1037 * This function updates the DF store for the dropdown so that use_counts
1038 * can reflect DF applications from this session before they're saved
1041 this._updateFormulaStore = function() {
1042 this.dfSelector.store = new dojo.data.ItemFileReadStore(
1044 "data": self._labelFormulasWithCounts(
1045 acqdf.toStoreData(self.distribForms)
1051 this.saveCopyFieldsBeforeDF = function(copy_id) {
1053 if (!this.oldCopyWidgetCache[copy_id]) {
1054 var copyWidgets = this.copyWidgetCache[copy_id];
1056 this.oldCopyWidgetCache[copy_id] = {};
1057 this._copy_fields_for_acqdf.forEach(
1059 self.oldCopyWidgetCache[copy_id][f] =
1060 copyWidgets[f].attr("value");
1066 this.restoreCopyFieldsBeforeDF = function() {
1068 for (var copy_id in this.oldCopyWidgetCache) {
1069 this._copy_fields_for_acqdf.forEach(
1071 self.copyWidgetCache[copy_id][f].attr(
1072 "value", self.oldCopyWidgetCache[copy_id][f]
1079 this._labelFormulasWithCounts = function(store_data) {
1080 for (var key in store_data.items) {
1081 var obj = store_data.items[key];
1082 obj.use_count = Number(obj.use_count); /* needed for sorting */
1084 if (this.virtDfaCounts[obj.id])
1085 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
1087 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
1088 obj.use_count + "]</span> " + obj.name;
1094 * This method formerly would not refetch the DF formulas if they'd been
1095 * loaded already, but now it always re-fetches, since use_count changes.
1097 this._fetchDistribFormulas = function(onload) {
1098 fieldmapper.standardRequest(
1100 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
1103 "params": [openils.User.authtoken],
1104 "oncomplete": function(r) {
1105 self.distribForms = openils.Util.readResponse(r);
1106 if(!self.distribForms || self.distribForms.length == 0) {
1107 self.distribForms = [];
1109 self._addDistribFormulaRow();
1116 this._drawBatchCopyWidgets = function() {
1117 var row = this.copyBatchRow;
1118 dojo.forEach(liDetailBatchFields,
1120 if(self.copyBatchRowDrawn) {
1121 self.copyBatchWidgets[field].attr('value', null);
1123 var widget = new openils.widget.AutoFieldWidget({
1126 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1127 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1128 parentNode : dojo.query('[name='+field+']', row)[0],
1129 orgLimitPerms : ['CREATE_PICKLIST'],
1130 dijitArgs : {required:false},
1135 self.copyBatchWidgets[field] = w;
1141 this.copyBatchRowDrawn = true;
1144 this.batchCopyUpdate = function() {
1146 for(var k in this.copyWidgetCache) {
1147 var cache = this.copyWidgetCache[k];
1148 dojo.forEach(liDetailBatchFields, function(f) {
1149 var newval = self.copyBatchWidgets[f].attr('value');
1150 if(newval) cache[f].attr('value', newval);
1155 this._drawCopies = function(li) {
1158 // this button sets the total number of copies for a given lineitem
1159 acqLitAddCopyCount.onClick = function() {
1160 var count = acqLitCopyCountInput.attr('value');
1163 while(self.copyCount() < count)
1166 // delete rows if necessary
1167 var diff = self.copyCount() - count;
1169 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
1170 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
1171 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
1173 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1179 if(li.lineitem_details().length > 0) {
1180 dojo.forEach(li.lineitem_details(),
1182 self.addCopy(li, copy);
1190 this.copyCount = function() {
1192 for(var id in this.copyCache) {
1193 if(!this.copyCache[id].isdeleted())
1199 this.virtCopyId = -1;
1200 this.addCopy = function(li, copy) {
1201 var row = this.copyRow.cloneNode(true);
1202 this.copyTbody.appendChild(row);
1206 copy = new fieldmapper.acqlid();
1208 copy.id(this.virtCopyId--);
1209 copy.lineitem(li.id());
1212 this.copyCache[copy.id()] = copy;
1213 row.setAttribute('copy_id', copy.id());
1214 self.copyWidgetCache[copy.id()] = {};
1216 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1218 dojo.forEach(liDetailFields,
1220 var widget = new openils.widget.AutoFieldWidget({
1223 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1224 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1226 parentNode : dojo.query('[name='+field+']', row)[0],
1227 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
1228 readOnly : Boolean(copy.eg_copy_id())
1231 // make sure we capture the value from any async widgets
1233 copy[field](ww.getFormattedValue())
1234 self.copyWidgetCache[copy.id()][field] = w;
1237 dojo.connect(widget.widget, 'onChange',
1239 if(copy.isnew() || val != copy[field]()) {
1240 // prevent setting ischanged() automatically on widget load for existing copies
1241 copy[field](widget.getFormattedValue())
1242 copy.ischanged(true);
1249 this.updateLidState(copy, row);
1252 this.updateLidState = function(copy, row) {
1253 if (typeof(row) == "undefined") {
1255 'tr[copy_id="' + copy.id() + '"]', this.copyTbody
1260 var recv_link = nodeByName("receive", row);
1261 var unrecv_link = nodeByName("unreceive", row);
1262 var del_link = nodeByName("delete", row);
1263 var cxl_link = nodeByName("cancel", row);
1264 var cxl_reason_link = nodeByName("cancel_reason", row);
1266 if (copy.cancel_reason()) {
1267 openils.Util.hide(del_link.parentNode);
1268 openils.Util.hide(recv_link);
1269 openils.Util.hide(unrecv_link);
1270 openils.Util.hide(cxl_link);
1272 /* XXX the following may leak memory in a long lived table: dijits may not get destroyed... not positive. revisit. */
1273 var holds_reason = dojo.create(
1275 "style": "border-bottom: 1px dashed #000;",
1276 "innerHTML": "Cancelled" /* XXX [sic] and i18n */
1277 }, cxl_reason_link, "only"
1281 "label": "<em>" + copy.cancel_reason().label() +
1282 "</em><br />" + copy.cancel_reason().description(),
1283 "connectId": [holds_reason]
1284 }, dojo.create("span", null, cxl_reason_link, "last")
1286 openils.Util.show(cxl_reason_link, "inline");
1287 } else if (this.isPO) {
1288 openils.Util.hide(del_link.parentNode);
1289 openils.Util.hide(cxl_reason_link);
1291 /* Avoid showing (un)receive links, cancel links, for virt copies */
1292 if (copy.id() > 0) {
1293 if(copy.recv_time()) {
1294 openils.Util.hide(cxl_link);
1295 openils.Util.hide(recv_link);
1296 openils.Util.show(unrecv_link, "inline");
1297 unrecv_link.onclick = function() {
1298 if (confirm(localeStrings.UNRECEIVE_LID))
1299 self.issueReceive(copy, /* rollback */ true);
1302 openils.Util.hide(unrecv_link);
1303 openils.Util.show(recv_link, "inline");
1304 openils.Util.show(cxl_link, "inline");
1305 recv_link.onclick = function() {
1306 if (self.checkLiAlerts(copy.lineitem()))
1307 self.issueReceive(copy);
1309 cxl_link.onclick = function() {
1310 self.cancelLid(copy.id());
1314 openils.Util.hide(cxl_link);
1315 openils.Util.hide(unrecv_link);
1316 openils.Util.hide(recv_link);
1319 openils.Util.hide(unrecv_link);
1320 openils.Util.hide(recv_link);
1321 openils.Util.hide(cxl_reason_link);
1323 del_link.onclick = function() { self.deleteCopy(row) };
1324 openils.Util.show(del_link.parentNode);
1328 this.cancelLid = function(lid_id) {
1329 lidCancelDialog._lid_id = lid_id;
1330 openils.Util.show(lidCancelDialog.domNode.parentNode);
1331 lidCancelDialog.show();
1332 if (!lidCancelDialog._prepared) {
1333 var widget = new openils.widget.AutoFieldWidget({
1334 "fmField": "cancel_reason",
1335 "fmClass": "acqlid",
1336 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
1337 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1342 acqLidCancelButton.onClick = function() {
1343 if (w.attr("value")) {
1344 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
1346 lidCancelDialog._lid_id,
1350 lidCancelDialog.hide();
1353 lidCancelDialog._prepared = true;
1359 this._cancelLid = function(lid_id, reason) {
1360 fieldmapper.standardRequest(
1361 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
1362 "params": [openils.User.authtoken, lid_id, reason],
1364 "onresponse": function(r) {
1365 if (r = openils.Util.readResponse(r)) {
1367 for (var id in r.lid) {
1368 /* actually this should only iterate once */
1369 self.copyCache[id].cancel_reason(
1370 r.lid[id].cancel_reason
1372 self.updateLidState(self.copyCache[id]);
1381 this._confirmAlert = function(li, lin) {
1383 dojo.string.substitute(
1384 localeStrings.CONFIRM_LI_ALERT, [
1385 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1386 "title", "lineitem_marc_attr_definition"
1388 lin.alert_text().code(),
1389 lin.alert_text().description() || "",
1396 this.checkLiAlerts = function(li_id) {
1397 var li = this.liCache[li_id];
1399 var alert_notes = li.lineitem_notes().filter(
1400 function(o) { return Boolean(o.alert_text()); }
1403 /* this is _intentionally_ not done in a call to forEach() ... */
1404 for (var i = 0; i < alert_notes.length; i++) {
1405 if (this.noteAcks[alert_notes[i].id()])
1407 else if (!this._confirmAlert(li, alert_notes[i]))
1410 this.noteAcks[alert_notes[i].id()] = true;
1416 this.deleteCopy = function(row) {
1417 var copy = this.copyCache[row.getAttribute('copy_id')];
1418 copy.isdeleted(true);
1420 delete this.copyCache[copy.id()];
1421 this.copyTbody.removeChild(row);
1424 this._virtDfaCountsAsList = function() {
1426 for (var key in this.virtDfaCounts) {
1427 for (var i = 0; i < this.virtDfaCounts[key]; i++)
1433 this.saveCopyChanges = function(liId) {
1439 for(var id in this.copyCache) {
1440 var c = this.copyCache[id];
1441 if(!c.isdeleted()) total++;
1442 if(c.isnew() || c.ischanged() || c.isdeleted()) {
1443 if(c.id() < 0) c.id(null);
1448 if (typeof(this._copy_count_cb) == "function") {
1449 this._copy_count_cb(liId, total);
1452 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
1455 if (copies.length > 0) {
1456 openils.Util.show("acq-lit-update-copies-progress");
1457 fieldmapper.standardRequest(
1458 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1460 params: [openils.User.authtoken, copies],
1461 onresponse: function(r) {
1462 var res = openils.Util.readResponse(r);
1463 litUpdateCopiesProgress.update(res);
1465 oncomplete: function() {
1466 self.drawCopies(liId);
1467 openils.Util.hide("acq-lit-update-copies-progress");
1473 var dfa_list = this._virtDfaCountsAsList();
1474 if (dfa_list.length > 0) {
1475 fieldmapper.standardRequest(
1477 "open-ils.acq.distribution_formula.record_application"],
1480 "params": [openils.User.authtoken, dfa_list, liId],
1481 "onresponse": function(r) {
1482 var res = openils.Util.readResponse(r);
1483 if (res && res.length < dfa_list.length)
1484 alert(localeStrings.DFA_NOT_ALL);
1488 this.virtDfaCounts = {};
1492 this._updateCreatePoPrepayCheckbox = function(prepay) {
1493 var prepay = openils.Util.isTrue(prepay);
1494 this._prepayRequiredByVendor = prepay;
1495 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
1498 this._confirmPoPrepaySituation = function() {
1499 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
1500 if (want_prepay != this._prepayRequiredByVendor) {
1503 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
1504 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
1511 this.applySelectedLiAction = function(action) {
1515 case 'delete_selected':
1516 this._deleteLiList(self.getSelected());
1519 case 'create_order':
1521 if(!this.createPoProviderSelector) {
1522 var widget = new openils.widget.AutoFieldWidget({
1523 fmField : 'provider',
1525 searchFilter: {"active": "t"},
1526 parentNode : dojo.byId('acq-lit-po-provider'),
1528 "onChange": function() {
1530 self._updateCreatePoPrepayCheckbox(
1531 this.item.prepayment_required
1538 function(w) { self.createPoProviderSelector = w; }
1542 if(!this.createPoAgencySelector) {
1543 var widget = new openils.widget.AutoFieldWidget({
1544 fmField : 'ordering_agency',
1546 parentNode : dojo.byId('acq-lit-po-agency'),
1547 orgLimitPerms : ['CREATE_PURCHASE_ORDER'],
1550 function(w) { self.createPoAgencySelector = w; }
1555 acqLitPoCreateDialog.show();
1558 case 'save_picklist':
1559 this._loadPLSelect();
1560 acqLitSavePlDialog.show();
1563 case 'selector_ready':
1565 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
1566 acqLitChangeLiStateDialog.show();
1577 case 'rollback_receive_po':
1578 this.rollbackPoReceive();
1581 case 'create_assets':
1582 this.createAssets();
1585 case 'export_attr_list':
1586 this.chooseExportAttr();
1589 case 'add_brief_record':
1591 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
1593 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
1597 case "cancel_lineitems":
1598 this.maybeCancelLineitems();
1603 this.createAssets = function() {
1604 if(!this.isPO) return;
1605 if(!confirm(localeStrings.CREATE_PO_ASSETS_CONFIRM)) return;
1606 this.show('acq-lit-progress-numbers');
1608 fieldmapper.standardRequest(
1609 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
1611 params: [this.authtoken, this.isPO],
1612 onresponse: function(r) {
1613 var resp = openils.Util.readResponse(r);
1614 self._updateProgressNumbers(resp, true);
1620 this.maybeCancelLineitems = function() {
1621 openils.Util.show("acq-lit-cancel-reason", "inline");
1622 if (!acqLitCancelLineitemsButton._prepared) {
1623 var widget = new openils.widget.AutoFieldWidget({
1624 "fmField": "cancel_reason",
1626 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
1627 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1632 acqLitCancelLineitemsButton.onClick = function() {
1633 if (w.attr("value")) {
1634 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
1635 self._cancelLineitems(w.attr("value"));
1637 openils.Util.hide("acq-lit-cancel-reason");
1640 acqLitCancelLineitemsButton._prepared = true;
1646 this._cancelLineitems = function(reason) {
1647 var id_list = this.getSelected().map(function(o) { return o.id(); });
1648 fieldmapper.standardRequest(
1649 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
1650 "params": [openils.User.authtoken, id_list, reason],
1652 "onresponse": function(r) {
1653 if (r = openils.Util.readResponse(r)) {
1655 for (var id in r.li) {
1656 self.liCache[id].state(r.li[id].state);
1657 self.liCache[id].cancel_reason(
1658 r.li[id].cancel_reason
1660 self.updateLiState(self.liCache[id]);
1663 if (r.lid && self.copyCache) {
1664 for (var id in r.lid) {
1665 if (self.copyCache[id]) {
1666 self.copyCache[id].cancel_reason(
1667 r.lid[id].cancel_reason
1669 self.updateLidState(self.copyCache[id]);
1679 this.chooseExportAttr = function() {
1680 if (!acqLitExportAttrSelector._li_setup) {
1682 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
1684 "data": acqliad.toStoreData(
1686 "acqliad", {"code": li_exportable_attrs}
1691 acqLitExportAttrSelector.setValue();
1692 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
1693 acqLitExportAttrSelector._li_setup = true;
1695 openils.Util.show("acq-lit-export-attr-holder", "inline");
1698 this.exportAttrList = function() {
1699 var attr_def = acqLitExportAttrSelector.item;
1700 var li_list = this.getSelected();
1701 var value_list = li_list.map(
1703 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1704 attr_def.code, "lineitem_marc_attr_definition"
1707 ).filter(function(attr) { return Boolean(attr); });
1709 if (value_list.length > 0) {
1710 if (value_list.length < li_list.length) {
1712 dojo.string.substitute(
1713 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
1720 openils.XUL.contentToFileSaveDialog(
1721 value_list.join("\n"),
1722 localeStrings.EXPORT_SAVE_DIALOG_TITLE
1728 alert(dojo.string.substitute(
1729 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
1733 openils.Util.hide("acq-lit-export-attr-holder");
1736 this.printPO = function() {
1737 if(!this.isPO) return;
1738 progressDialog.show(true);
1739 fieldmapper.standardRequest(
1740 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
1742 params: [this.authtoken, this.isPO, 'html'],
1743 oncomplete: function(r) {
1744 progressDialog.hide();
1745 var evt = openils.Util.readResponse(r);
1746 if(evt && evt.template_output()) {
1747 win = window.open('','', 'resizable,width=800,height=600,scrollbars=1');
1748 win.document.body.innerHTML = evt.template_output().data();
1756 this.receivePO = function() {
1757 if (!this.isPO) return;
1759 for (var id in this.liCache) {
1760 /* assumption: liCache reflects exactly the
1761 * set of LIs that belong to our PO */
1762 if (this.liCache[id].state() != "received" &&
1763 !this.checkLiAlerts(id)) return;
1766 this.show('acq-lit-progress-numbers');
1768 fieldmapper.standardRequest(
1769 ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
1771 params: [this.authtoken, this.isPO],
1772 onresponse : function(r) {
1773 var resp = openils.Util.readResponse(r);
1774 self._updateProgressNumbers(resp, true);
1780 this.issueReceive = function(obj, rollback) {
1781 /* (For now) there shall be no marking LI or LIDs (un)received
1782 * except from the actual "view PO" interface. */
1783 if (!this.isPO) return;
1786 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
1788 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
1790 progressDialog.show(true);
1791 fieldmapper.standardRequest(
1792 ["open-ils.acq", method], {
1794 "params": [this.authtoken, obj.id()],
1795 "onresponse": function(r) {
1796 self.handleReceive(openils.Util.readResponse(r));
1797 progressDialog.hide();
1804 * Handles the responses from receive and rollback ML calls.
1806 this.handleReceive = function(resp) {
1809 for (var li_id in resp.li) {
1810 for (var key in resp.li[li_id])
1811 self.liCache[li_id][key](resp.li[li_id][key]);
1812 self.updateLiState(self.liCache[li_id]);
1816 if (typeof(self.poUpdateCallback) == "function")
1817 self.poUpdateCallback(resp.po);
1820 for (var lid_id in resp.lid) {
1821 for (var key in resp.lid[lid_id])
1822 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
1823 self.updateLidState(self.copyCache[lid_id]);
1829 this.rollbackPoReceive = function() {
1830 if(!this.isPO) return;
1831 if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
1832 this.show('acq-lit-progress-numbers');
1834 fieldmapper.standardRequest(
1835 ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
1837 params: [this.authtoken, this.isPO],
1838 onresponse : function(r) {
1839 var resp = openils.Util.readResponse(r);
1840 self._updateProgressNumbers(resp, true);
1846 this._updateProgressNumbers = function(resp, reloadOnComplete) {
1848 dojo.byId('acq-pl-lit-li-processed').innerHTML = resp.li;
1849 dojo.byId('acq-pl-lit-lid-processed').innerHTML = resp.lid;
1850 dojo.byId('acq-pl-lit-debits-processed').innerHTML = resp.debits_accrued;
1851 dojo.byId('acq-pl-lit-bibs-processed').innerHTML = resp.bibs;
1852 dojo.byId('acq-pl-lit-indexed-processed').innerHTML = resp.indexed;
1853 dojo.byId('acq-pl-lit-copies-processed').innerHTML = resp.copies;
1854 if(resp.complete && reloadOnComplete)
1855 location.href = location.href;
1859 this._createPO = function(fields) {
1860 this.show('acq-lit-progress-numbers');
1861 var po = new fieldmapper.acqpo();
1862 po.provider(this.createPoProviderSelector.attr('value'));
1863 po.ordering_agency(this.createPoAgencySelector.attr('value'));
1864 po.prepayment_required(fields.prepayment_required[0] ? true : false);
1866 var selected = this.getSelected( (fields.create_from == 'all') );
1867 if(selected.length == 0) return;
1869 var max = selected.length * 3;
1872 fieldmapper.standardRequest(
1873 ['open-ils.acq', 'open-ils.acq.purchase_order.create'],
1876 openils.User.authtoken,
1879 lineitems : selected.map(function(li) { return li.id() }),
1880 create_assets : fields.create_assets[0],
1884 onresponse : function(r) {
1885 var resp = openils.Util.readResponse(r);
1886 self._updateProgressNumbers(resp);
1888 location.href = oilsBasePath + '/eg/acq/po/view/' + resp.purchase_order.id();
1894 this._deleteLiList = function(list, idx) {
1895 if(idx == null) idx = 0;
1896 if(idx >= list.length) return;
1897 var liId = list[idx].id();
1898 fieldmapper.standardRequest(
1899 ['open-ils.acq', 'open-ils.acq.lineitem.delete'],
1901 params: [openils.User.authtoken, liId],
1902 oncomplete: function(r) {
1903 self.removeLineitem(liId);
1904 self._deleteLiList(list, ++idx);
1910 this.editOrderMarc = function(li) {
1912 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
1913 to true in about:config */
1915 if(!openils.XUL.enableXPConnect()) return;
1917 if(openils.XUL.isXUL()) {
1918 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
1920 win = window.open('/xul/server/cat/marcedit.xul');
1924 record : {marc : li.marc()},
1926 label: 'Save Record', // XXX I18N
1927 func: function(xmlString) {
1929 fieldmapper.standardRequest(
1930 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
1932 params: [openils.User.authtoken, li],
1933 oncomplete: function(r) {
1934 openils.Util.readResponse(r);
1936 self.drawInfo(li.id())
1945 this._savePl = function(values) {
1947 var selected = this.getSelected( (values.which == 'all') );
1948 openils.Util.show('acq-lit-generic-progress');
1950 if(values.new_name) {
1951 openils.acq.Picklist.create(
1952 {name: values.new_name},
1954 self._updateLiList(id, selected, 0,
1956 location.href = oilsBasePath + '/eg/acq/picklist/view/' + id;
1960 } else if(values.existing_pl) {
1961 // update lineitems to use an existing picklist
1962 self._updateLiList(values.existing_pl, selected, 0,
1964 location.href = oilsBasePath + '/eg/acq/picklist/view/' + values.existing_pl;
1969 this._updateLiState = function(values, state) {
1971 var selected = this.getSelected( (values.which == 'all') );
1972 if(!selected.length) return;
1973 dojo.forEach(selected, function(li) {li.state(state);});
1974 self._updateLiList(null, selected, 0,
1975 // TODO consider inline updates for efficiency
1976 function() { location.href = location.href }
1980 this._updateLiList = function(pl, list, idx, oncomplete) {
1981 if(idx >= list.length) return oncomplete();
1983 if(pl != null) li.picklist(pl);
1984 litGenericProgress.update({maximum: list.length, progress: idx});
1985 new openils.acq.Lineitem({lineitem:li}).update(
1987 self._updateLiList(pl, list, ++idx, oncomplete);
1992 this._loadPLSelect = function() {
1993 if(this._plSelectLoaded) return;
1995 function handleResponse(r) {
1996 plList.push(r.recv().content());
1998 var method = 'open-ils.acq.picklist.user.retrieve';
1999 fieldmapper.standardRequest(
2000 ['open-ils.acq', method],
2002 params: [this.authtoken],
2003 onresponse: handleResponse,
2004 oncomplete: function() {
2005 self._plSelectLoaded = true;
2006 acqLitAddExistingSelect.store =
2007 new dojo.data.ItemFileReadStore({data:acqpl.toStoreData(plList)});
2008 acqLitAddExistingSelect.setValue();
2014 this.showRealCopyEditUI = function(li) {
2019 this._fetchLineitem(li.id(),
2021 li = self.liCache[li.id()] = fullLi;
2025 id : li.lineitem_details().map(
2026 function(item) { return item.eg_copy_id() }
2030 oncomplete : function(r) {
2032 var r_list = openils.Util.readResponse( r );
2033 for (var i = 0; i < r_list.length; i++) {
2034 var copy = r_list[i];
2035 var volId = copy.call_number();
2036 var volume = self.volCache[volId];
2038 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2040 copy.call_number(volume);
2041 copyList.push(copy);
2044 // If we need to, we can pass in an update_copy function to handle the update instead of volume_item_creator
2045 xulG.volume_item_creator( { 'existing_copies' : copyList } );
2048 alert('error in oncomplete: ' + E);
2059 this.saveRealCopies = function() {
2060 progressDialog.show(true);
2061 var list = this.realCopyList.filter(function(copy) { return copy.ischanged(); });
2062 this.pcrud.update(list, {oncomplete: function() {
2063 progressDialog.hide();
2068 // grab the li-details for this lineitem, grab the linked copies and volumes, add them to the table
2069 this.showRealCopies = function(li) {
2070 while(this.realCopiesTbody.childNodes[0])
2071 this.realCopiesTbody.removeChild(this.realCopiesTbody.childNodes[0]);
2072 this.show('real-copies');
2074 this.realCopyList = [];
2076 var tabIndex = 1000;
2079 acqLitSaveRealCopies.onClick = function() {
2080 self.saveRealCopies();
2083 this._fetchLineitem(li.id(),
2085 li = self.liCache[li.id()] = fullLi;
2089 id : li.lineitem_details().map(
2090 function(item) { return item.eg_copy_id() }
2095 onresponse : function(r) {
2096 var copy = openils.Util.readResponse(r);
2097 var volId = copy.call_number();
2098 var volume = self.volCache[volId];
2100 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2102 self.addRealCopy(volume, copy, tabIndex++);
2110 this.addRealCopy = function(volume, copy, tabIndex) {
2111 var row = this.realCopiesRow.cloneNode(true);
2112 this.realCopyList.push(copy);
2116 ['owning_lib', 'location', 'circ_modifier', 'label', 'barcode'],
2119 var isvol = (field == 'owning_lib' || field == 'label');
2120 var widget = new openils.widget.AutoFieldWidget({
2122 fmObject : isvol ? volume : copy,
2123 parentNode : nodeByName(field, row),
2124 readOnly : (field != 'barcode'),
2127 var widgetDrawn = null;
2129 if(field == 'barcode') {
2131 widgetDrawn = function(w, ww) {
2132 var node = w.domNode;
2133 node.setAttribute('tabindex', ''+tabIndex);
2135 // on enter, select the next barcode input
2136 dojo.connect(w, 'onKeyDown',
2138 if(e.keyCode == dojo.keys.ENTER) {
2139 var ti = node.getAttribute('tabindex');
2140 var nextNode = dojo.query('[tabindex=' + String(Number(ti) + 1) + ']', self.realCopiesTbody)[0];
2141 if(nextNode) nextNode.select();
2146 dojo.connect(w, 'onChange',
2148 if(!val || val == copy.barcode()) return;
2149 copy.ischanged(true);
2155 if(self.realCopiesTbody.getElementsByTagName('TR').length == 0)
2160 widget.build(widgetDrawn);
2164 this.realCopiesTbody.appendChild(row);
2165 if(selectNode) selectNode.select();