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 = [
26 '<span class="fund_${0}">${1} (${2})</span>', 'id', 'code', 'year'
28 var fundSearchFormat = ['${0} (${1})', 'code', 'year'];
30 function nodeByName(name, context) {
31 return dojo.query('[name='+name+']', context)[0];
35 var liDetailBatchFields = ['fund', 'owning_lib', 'location', 'collection_code', 'circ_modifier', 'cn_label'];
36 var liDetailFields = liDetailBatchFields.concat(['barcode', 'note']);
38 "stop": "color: #c00; font-weight: bold;",
39 "warning": "color: #c93;"
42 function AcqLiTable() {
49 this.haveFundClass = {}
50 this.fundBalanceState = {};
51 this.realDfaCache = {};
52 this.virtDfaCounts = {};
55 this.toggleState = false;
56 this.tbody = dojo.byId('acq-lit-tbody');
59 this.authtoken = openils.User.authtoken;
60 this.pcrud = new openils.PermaCrud();
61 this.rowTemplate = this.tbody.removeChild(dojo.byId('acq-lit-row'));
62 this.copyTbody = dojo.byId('acq-lit-li-details-tbody');
63 this.copyRow = this.copyTbody.removeChild(dojo.byId('acq-lit-li-details-row'));
64 this.copyBatchRow = dojo.byId('acq-lit-li-details-batch-row');
65 this.copyBatchWidgets = {};
66 this.liNotesTbody = dojo.byId('acq-lit-notes-tbody');
67 this.liNotesRow = this.liNotesTbody.removeChild(dojo.byId('acq-lit-notes-row'));
68 this.realCopiesTbody = dojo.byId('acq-lit-real-copies-tbody');
69 this.realCopiesRow = this.realCopiesTbody.removeChild(dojo.byId('acq-lit-real-copies-row'));
70 this._copy_fields_for_acqdf = ['owning_lib', 'location'];
72 dojo.connect(acqLitLiActionsSelector, 'onChange',
74 self.applySelectedLiAction(this.attr('value'))
75 acqLitLiActionsSelector.attr('value', '_');
78 acqLitCreatePoSubmit.onClick = function() {
79 if (self._confirmPoPrepaySituation()) {
80 acqLitPoCreateDialog.hide();
81 self._createPO(acqLitPoCreateDialog.getValues());
87 acqLitSavePlButton.onClick = function() {
88 acqLitSavePlDialog.hide();
89 self._savePl(acqLitSavePlDialog.getValues());
92 acqLitCancelLiStateButton.onClick = function() {
93 acqLitChangeLiStateDialog.hide();
95 acqLitSaveLiStateButton.onClick = function() {
96 acqLitChangeLiStateDialog.hide();
97 self._updateLiState(acqLitChangeLiStateDialog.getValues(), acqLitChangeLiStateDialog.attr('state'));
101 dojo.byId('acq-lit-select-toggle').onclick = function(){self.toggleSelect()};
102 dojo.byId('acq-lit-info-back-button').onclick = function(){self.show('list')};
103 dojo.byId('acq-lit-copies-back-button').onclick = function(){self.show('list')};
104 dojo.byId('acq-lit-notes-back-button').onclick = function(){self.show('list')};
105 dojo.byId('acq-lit-real-copies-back-button').onclick = function(){self.show('list')};
107 this.reset = function() {
108 while(self.tbody.childNodes[0])
109 self.tbody.removeChild(self.tbody.childNodes[0]);
115 this.setNext = function(handler) {
116 var link = dojo.byId('acq-lit-next');
118 dojo.style(link, 'visibility', 'visible');
119 link.onclick = handler;
121 dojo.style(link, 'visibility', 'hidden');
125 this.setPrev = function(handler) {
126 var link = dojo.byId('acq-lit-prev');
128 dojo.style(link, 'visibility', 'visible');
129 link.onclick = handler;
131 dojo.style(link, 'visibility', 'hidden');
135 this.show = function(div) {
136 openils.Util.hide('acq-lit-table-div');
137 openils.Util.hide('acq-lit-info-div');
138 openils.Util.hide('acq-lit-li-details');
139 openils.Util.hide('acq-lit-notes-div');
140 openils.Util.hide('acq-lit-real-copies-div');
143 openils.Util.show('acq-lit-table-div');
146 openils.Util.show('acq-lit-info-div');
149 openils.Util.show('acq-lit-li-details');
152 openils.Util.show('acq-lit-real-copies-div');
155 openils.Util.show('acq-lit-notes-div');
159 openils.Util.show(div);
163 this.hide = function() {
167 this.toggleSelect = function() {
169 dojo.forEach(self.selectors, function(i){i.checked = false});
171 dojo.forEach(self.selectors, function(i){i.checked = true});
172 self.toggleState = !self.toggleState;
176 /** @param all If true, assume all are selected */
177 this.getSelected = function(all) {
179 dojo.forEach(self.selectors,
182 selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
188 this.setRowAttr = function(td, liWrapper, field, type) {
189 var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
190 td.appendChild(document.createTextNode(val));
194 * Inserts a single lineitem into the growing table of lineitems
195 * @param {Object} li The lineitem object to insert
197 this.addLineitem = function(li, skip_final_placement) {
198 this.liCache[li.id()] = li;
200 // sort the lineitem notes on edit_time
201 if(!li.lineitem_notes()) li.lineitem_notes([]);
203 var liWrapper = new openils.acq.Lineitem({lineitem:li});
204 var row = self.rowTemplate.cloneNode(true);
205 row.setAttribute('li', li.id());
206 var tds = dojo.query('[attr]', row);
207 dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
208 dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
210 var isbn = liWrapper.findAttr('isbn', 'lineitem_marc_attr_definition');
212 // XXX media prefix for added content
213 dojo.query('[name=jacket]', row)[0].setAttribute('src', '/opac/extras/ac/jacket/small/' + isbn);
216 nodeByName("worksheet_link", row).href =
217 "/eg/acq/lineitem/worksheet/" + li.id();
219 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
220 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
221 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
223 this.updateLiNotesCount(li, row);
225 // show which PO this lineitem is a member of
226 if(li.purchase_order() && !this.isPO) {
228 this.poCache[li.purchase_order()] =
229 this.poCache[li.purchase_order()] ||
230 fieldmapper.standardRequest(
231 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
233 this.authtoken, li.purchase_order(), {
234 "flesh_price_summary": true,
235 "flesh_lineitem_count": true
238 if(po && !this.isMeta) {
239 openils.Util.show(nodeByName('po', row), 'inline');
240 var link = nodeByName('po_link', row);
241 link.setAttribute('href', oilsBasePath + '/acq/po/view/' + li.purchase_order());
242 link.innerHTML = 'PO: ' + po.name(); // TODO i18n
246 // show which picklist this lineitem is a member of
247 if(li.picklist() && (this.isPO || this.isMeta)) {
249 this.plCache[li.picklist()] =
250 this.plCache[li.picklist()] ||
251 fieldmapper.standardRequest(
252 ['open-ils.acq', 'open-ils.acq.picklist.retrieve'],
253 {params: [this.authtoken, li.picklist()]});
255 openils.Util.show(nodeByName('pl', row), 'inline');
256 var link = nodeByName('pl_link', row);
257 link.setAttribute('href', oilsBasePath + '/acq/picklist/view/' + li.picklist());
258 link.innerHTML = 'PL: '+pl.name(); // TODO i18n
262 var countNode = nodeByName('count', row);
263 var count = li.item_count() || 0;
264 if (typeof(this._copy_count_cb) == "function") {
265 this._copy_count_cb(li.id(), count);
267 countNode.innerHTML = count;
268 countNode.id = 'acq-lit-copy-count-label-' + li.id();
271 var priceInput = dojo.query('[name=price]', row)[0];
272 priceInput.value = li.estimated_unit_price() || '';
273 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
275 // show either "mark received" or "unreceive" as appropriate
276 this.updateLiState(li, row);
278 if (!skip_final_placement) {
279 self.tbody.appendChild(row);
280 self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
286 this.updateLiNotesCount = function(li, row) {
287 if (typeof(row) == "undefined")
288 row = dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
290 var has_notes = (li.lineitem_notes().filter(
291 function(o) { return Boolean (o.alert_text()); }
294 /* U+2691 is the code point for a filled-in flag character */
295 nodeByName("notes_alert_flag", row).innerHTML =
296 has_notes ? "⚑" : "";
297 nodeByName("noteslink", row).style.fontStyle =
298 has_notes ? "italic" : "normal";
299 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
302 /* XXX NOT related to _updateLiState(). rethink */
303 this.updateLiState = function(li, row) {
304 if (typeof(row) == "undefined")
305 row = dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
307 var recv_link = nodeByName("receive_link", row);
308 var unrecv_link = nodeByName("unreceive_link", row);
309 var real_copies_link = nodeByName("real_copies_link", row);
310 var holdings_maintenance_link = nodeByName("holdings_maintenance_link", row);
311 var state_cell = nodeByName("li_state", row);
313 if (li.state() == "cancelled") {
314 if (typeof li.cancel_reason() == "object") {
315 var holds_state = dojo.create(
317 "style": "border-bottom: 1px dashed #000;",
318 "innerHTML": li.state()
319 }, state_cell, "only"
323 "label": "<em>" + li.cancel_reason().label() +
324 "</em><br />" + li.cancel_reason().description(),
325 "connectId": [holds_state]
326 }, dojo.create("span", null, state_cell, "last")
329 state_cell.innerHTML = li.state(); // TODO i18n state labels
332 state_cell.innerHTML = li.state(); // TODO i18n state labels
336 /* handle row coloring for based on LI state */
337 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
338 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
340 /* handle links that appear/disappear based on whether LI is received */
345 openils.Util.hide(real_copies_link);
346 openils.Util.hide(unrecv_link);
347 openils.Util.show(recv_link, "inline");
348 recv_link.onclick = function() {
349 if (self.checkLiAlerts(li.id()))
350 self.issueReceive(li);
354 openils.Util.hide(recv_link);
355 openils.Util.show(unrecv_link, "inline");
356 unrecv_link.onclick = function() {
357 if (confirm(localeStrings.UNRECEIVE_LI))
358 self.issueReceive(li, /* rollback */ true);
360 // TODO we should allow editing before receipt, in which case the
361 // test should be "if 1 or more real (acp) copies exist
362 openils.Util.show(real_copies_link, "inline");
363 real_copies_link.onclick = function() {
364 self.showRealCopyEditUI(li);
366 openils.Util.show(holdings_maintenance_link, "inline");
367 holdings_maintenance_link.onclick = self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser' );
372 openils.Util.hide(recv_link);
373 openils.Util.hide(unrecv_link);
374 openils.Util.hide(real_copies_link);
378 this._setAlertStore = function() {
379 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
381 "data": acqliat.toStoreData(
383 "acqliat", {"id": {"!=": null}}
388 acqLitAlertAlertText.setValue(); /* make the store "live" */
389 acqLitAlertAlertText._store_ready = true;
393 * Draws and shows the lineitem notes pane
395 this.drawLiNotes = function(li) {
398 if (!acqLitAlertAlertText._store_ready)
399 this._setAlertStore();
402 li.lineitem_notes().sort(
404 if(a.edit_time() < b.edit_time()) return 1;
410 while(this.liNotesTbody.childNodes[0])
411 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
414 acqLitCreateNoteSubmit.onClick = function() {
415 var value = acqLitCreateNoteText.attr('value');
417 var note = new fieldmapper.acqlin();
420 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
423 note.lineitem(li.id());
425 self.updateLiNotes(li, note);
426 acqLitCreateNoteVendorPublic.attr("checked", false);
427 acqLitCreateNoteText.attr("value", "");
430 acqLitCreateAlertSubmit.onClick = function() {
431 if (!acqLitAlertAlertText.item) {
432 alert(localeStrings.ALERT_UNSELECTED);
436 var alert_text = new fieldmapper.acqliat().fromStoreItem(
437 acqLitAlertAlertText.item
439 var value = acqLitAlertNoteValue.attr("value") || "";
441 var note = new fieldmapper.acqlin();
443 note.lineitem(li.id());
445 note.alert_text(alert_text);
447 self.updateLiNotes(li, note);
450 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
454 * Draws a single lineitem note in the notes pane
456 this.addLiNote = function(li, note) {
457 if(note.isdeleted()) return;
459 var row = self.liNotesRow.cloneNode(true);
460 nodeByName("value", row).innerHTML = note.value();
461 var alert_node = nodeByName("alert_code", row);
462 if (note.alert_text()) {
463 alert_node.innerHTML = note.alert_text().code();
464 if (note.alert_text().description()) {
467 "connectId": [alert_node],
468 "label": note.alert_text().description()
469 }, dojo.create("span", null, alert_node, "after")
474 if (openils.Util.isTrue(note.vendor_public()))
475 nodeByName("vendor_public", row).innerHTML =
476 localeStrings.VENDOR_PUBLIC;
478 nodeByName("delete", row).onclick = function() {
479 note.isdeleted(true);
480 self.liNotesTbody.removeChild(row);
481 self.updateLiNotes(li);
484 if(note.edit_time()) {
485 nodeByName("edit_time", row).innerHTML =
486 dojo.date.locale.format(
487 dojo.date.stamp.fromISOString(note.edit_time()),
488 {formatLength:'short'});
491 self.liNotesTbody.appendChild(row);
495 * Updates any new/changed/deleted notes on the server
497 this.updateLiNotes = function(li, newNote) {
503 notes = li.lineitem_notes().filter(
505 if(note.ischanged() || note.isnew() || note.isdeleted())
511 if(notes.length == 0) return;
512 progressDialog.show();
514 fieldmapper.standardRequest(
515 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
517 params : [this.authtoken, notes],
518 onresponse : function(r) {
519 var resp = openils.Util.readResponse(r);
524 // remove the old changed notes
526 dojo.forEach(li.lineitem_notes(),
528 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
532 li.lineitem_notes(list);
535 progressDialog.hide();
536 self.updateLiNotesCount(li);
537 self.drawLiNotes(li);
541 progressDialog.update(resp);
542 var newnote = resp.note;
544 if(!newnote.isdeleted()) {
545 newnote.isnew(false);
546 newnote.ischanged(false);
547 li.lineitem_notes().push(newnote);
554 this.updateLiPrice = function(input, li) {
556 var price = input.value;
557 if(Number(price) == Number(li.estimated_unit_price())) return;
559 fieldmapper.standardRequest(
560 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
562 params : [this.authtoken, li.id(), price],
563 oncomplete : function(r) {
564 openils.Util.readResponse(r);
570 this.removeLineitem = function(liId) {
571 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
572 delete this.liCache[liId];
573 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
576 this.drawInfo = function(liId) {
577 if (!this._isRelatedViewer) {
578 var d = dojo.byId("acq-lit-info-related");
579 if (!this.relCache[liId]) {
580 fieldmapper.standardRequest(
583 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
586 "params": [openils.User.authtoken, liId],
587 "onresponse": function(r) {
588 self.relCache[liId] = openils.Util.readResponse(r);
589 nodeByName("related_number", d).innerHTML =
592 self.relCache[liId] >1 ? "show" : "hide"
598 nodeByName("related_number", d).innerHTML = this.relCache[liId];
599 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
604 openils.acq.Lineitem.fetchAttrDefs(
606 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
611 this._fetchLineitem = function(liId, handler) {
613 var li = this.liCache[liId];
614 if(li && li.marc() && li.lineitem_details())
617 fieldmapper.standardRequest(
618 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve'],
621 params: [self.authtoken, liId, {
623 flesh_cancel_reason: true,
624 flesh_li_details: true,
625 flesh_fund_debit: true }],
627 oncomplete: function(r) {
628 var li = openils.Util.readResponse(r);
635 this._drawInfo = function(li) {
637 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
640 openils.Util.hide('acq-lit-marc-order-record-label');
641 openils.Util.hide(acqLitEditOrderMarc.domNode);
642 openils.Util.show('acq-lit-marc-real-record-label');
644 openils.Util.show('acq-lit-marc-order-record-label');
645 openils.Util.show(acqLitEditOrderMarc.domNode);
646 openils.Util.hide('acq-lit-marc-real-record-label');
649 this.drawMarcHTML(li);
650 this.infoTbody = dojo.byId('acq-lit-info-tbody');
653 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
654 while(this.infoTbody.childNodes[0])
655 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
657 if (!this._isRelatedViewer) {
658 for(var i = 0; i < li.attributes().length; i++) {
659 var attr = li.attributes()[i];
660 var row = this.infoRow.cloneNode(true);
662 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
663 var name = openils.acq.Lineitem.attrDefs[type].filter(
665 return (a.code() == attr.attr_name());
667 ).pop().description();
669 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
670 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
671 this.infoTbody.appendChild(row);
674 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
675 "/eg/acq/lineitem/related/" + li.id();
680 openils.Util.show('acq-lit-info-cat-link');
681 var link = dojo.byId('acq-lit-info-cat-link').getElementsByTagName('a')[0];
683 if(openils.XUL.isXUL()) {
685 link.setAttribute('href', 'javascript:void(0);');
686 link.onclick = this.generateMakeRecTab( li.eg_bib_id() );
689 var href = link.getAttribute('href');
691 link.setAttribute('href', href + li.eg_bib_id());
694 openils.Util.hide('acq-lit-info-cat-link');
698 this.generateMakeRecTab = function(bib_id,default_view) {
702 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
705 show_nav_buttons : true,
706 show_print_button : true,
707 opac_url : xulG.url_prefix(xulG.urls.opac_rdetail + '?r=' + bib_id),
708 default_view : default_view
714 this.drawMarcHTML = function(li) {
715 var params = [null, true, li.marc()];
717 params = [li.eg_bib_id(), true];
719 fieldmapper.standardRequest(
720 ['open-ils.search', 'open-ils.search.biblio.record.html'],
723 oncomplete: function(r) {
724 dojo.byId('acq-lit-marc-div').innerHTML =
725 openils.Util.readResponse(r);
731 this.drawCopies = function(liId) {
735 this.copyWidgetCache = {};
736 this.oldCopyWidgetCache = {};
737 this.virtDfaCounts = {};
738 this.realDfaCache = {};
741 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
742 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
743 acqLitCopyCountInput.attr('value', '0');
745 while(this.copyTbody.childNodes[0])
746 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
748 this._drawBatchCopyWidgets();
750 this._drawDistribApplied(liId);
752 this._fetchDistribFormulas(
754 openils.acq.Lineitem.fetchAttrDefs(
756 self._fetchLineitem(liId, function(li){self._drawCopies(li);});
763 this._saveDistribAppliedTemplates = function() {
764 if (!this._appliedDistribTemplate) {
765 this._appliedDistribTemplate =
766 dojo.byId("acq-lit-distrib-applied-tbody").
767 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
768 dojo.attr(this._appliedDistribTemplate, "id");
772 this._drawDistribApplied = function(liId) {
773 /* Build this table while hidden to prevent rendering artifacts */
774 openils.Util.hide("acq-lit-distrib-applied-tbody");
776 this._saveDistribAppliedTemplates();
778 /* Remove any rows in the table from previous populations */
779 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
780 forEach(dojo.destroy);
782 /* Unregister all dijits previously created (for some reason this isn't
783 * covered by the above destroy calls). */
784 dijit.registry.forEach(
785 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
788 /* Populate the table with our liId */
790 fieldmapper.standardRequest(
792 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
795 "params": [self.authtoken, liId],
796 "onresponse": function(r) {
797 var dfa = openils.Util.readResponse(r);
800 self.realDfaCache[dfa.id()] = dfa;
801 self._drawDistribAppliedUnit(dfa);
804 "oncomplete": function() {
805 /* Reveal built table */
808 "acq-lit-distrib-applied-tbody", "table-row-group"
816 this._drawDistribAppliedUnit = function(dfa) {
818 var row = dojo.query(
819 'tr[formula="' + dfa.formula().id() + '"]',
820 "acq-lit-distrib-applied-tbody"
825 row = dojo.clone(this._appliedDistribTemplate);
826 dojo.attr(row, "formula", dfa.formula().id());
827 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
830 var td = dojo.query("td", row)[0];
832 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
833 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
836 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
838 new dijit.form.Button(
840 "onClick": function() {
841 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
845 /* XXX I /cannot/ make the following work in as a CSS class
846 * for some reason. So frustrating... */
847 "style": function(id) {
849 "font-weight: bold; color: #c00;" :
851 }(dfa.id()) + "margin: 0 6px;display: inline;"
852 }, "dfa-button-" + dfa.id()
856 "connectId": ["dfa-button-" + dfa.id()],
857 "label": dojo.string.substitute(
858 localeStrings.DFA_TIP, dfa.id() > 0 ? [
859 openils.User.formalName(dfa.creator()),
860 dojo.date.locale.format(
861 dojo.date.stamp.fromISOString(dfa.create_time()),
862 {"formatLength":"short"}
864 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
866 }, "dfa-tip-" + dfa.id()
870 this.deleteDfa = function(dfa) {
871 if (dfa.id() > 0) { /* real */
872 this.pcrud.eliminate(
875 "oncomplete": function() {
876 self._removeDistribApplied(dfa.id());
877 delete self.realDfaCache[dfa.id()];
881 } else { /* virtual */
882 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
883 this.virtDfaCounts[dfa.formula().id()] = 0;
884 /* hasn't been saved yet, so no need to do anything server side */
885 this._removeDistribApplied(dfa.id());
890 this._removeDistribApplied = function(dfaId) {
891 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
892 dijit.registry.forEach(
893 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
895 this._removeDistribAppliedEmptyRows();
898 this._removeAllDistribAppliedVirtual = function() {
899 /* Unregister dijits */
900 dijit.registry.forEach(
901 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
903 this._removeDistribAppliedEmptyRows();
906 this._removeDistribAppliedEmptyRows = function() {
907 /* Remove any rows with no DFA at all */
908 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
910 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
916 * Insert a new row into the distribution formula selection form
918 this._addDistribFormulaRow = function() {
921 if (!self.distribForms) {
922 // no formulas, hide the form
923 openils.Util.hide('acq-lit-distrib-formula-tbody');
927 if(!this.distribFormulaTemplate)
928 this.distribFormulaTemplate =
929 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
931 var row = this.distribFormulaTemplate.cloneNode(true);
932 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
934 this.dfSelector = new dijit.form.FilteringSelect(
935 {"labelAttr": "dynLabel", "labelType": "html"},
936 nodeByName("selector", row)
938 this._updateFormulaStore();
939 this.dfSelector.fetchProperties =
940 {"sort": [{"attribute": "use_count", "descending": true}]};
942 var apply = new dijit.form.Button(
943 {"label": localeStrings.APPLY},
944 nodeByName('set_button', row)
947 var reset = new dijit.form.Button(
948 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
949 nodeByName("reset_button", row)
952 dojo.connect(apply, 'onClick',
954 var form_id = self.dfSelector.attr("value");
956 self._applyDistribFormula(form_id);
957 reset.attr("disabled", false);
961 dojo.connect(reset, 'onClick',
963 self.restoreCopyFieldsBeforeDF();
964 self.virtDfaCounts = {};
967 self._updateFormulaStore();
968 self._removeAllDistribAppliedVirtual();
969 reset.attr("disabled", "true");
976 * Applies a distrib formula to the current set of copies
978 this._applyDistribFormula = function(formula) {
981 formula = this.distribForms.filter(
982 function(form) { return form.id() == formula; }
985 var copyRows = dojo.query('tr', self.copyTbody);
987 if (this.dfeOffset >= copyRows.length) {
988 alert(localeStrings.OUT_OF_COPIES);
992 var entries_applied = 0;
994 var rowIndex = this.dfeOffset;
995 rowIndex < copyRows.length;
999 var row = copyRows[rowIndex];
1000 var copy_id = row.getAttribute('copy_id');
1001 var copyWidgets = this.copyWidgetCache[copy_id];
1002 var entryIndex = this.dfeOffset;
1005 // find the correct entry for the current row
1006 dojo.forEach(formula.entries(),
1009 entryIndex += e.item_count();
1010 if(entryIndex > rowIndex)
1018 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
1019 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
1022 this.saveCopyFieldsBeforeDF(copy_id);
1023 this._copy_fields_for_acqdf.forEach(
1025 if(entry[field]()) {
1026 copyWidgets[field].attr('value', (entry[field]()));
1033 if (entries_applied) {
1034 this.virtDfaCounts[formula.id()] =
1035 ++(this.virtDfaCounts[formula.id()]) || 1;
1036 this._updateFormulaStore();
1037 this._drawDistribAppliedUnit(
1039 var dfa = new acqdfa();
1040 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
1043 this.dfeOffset += entries_applied;
1048 * This function updates the DF store for the dropdown so that use_counts
1049 * can reflect DF applications from this session before they're saved
1052 this._updateFormulaStore = function() {
1053 this.dfSelector.store = new dojo.data.ItemFileReadStore(
1055 "data": self._labelFormulasWithCounts(
1056 acqdf.toStoreData(self.distribForms)
1062 this.saveCopyFieldsBeforeDF = function(copy_id) {
1064 if (!this.oldCopyWidgetCache[copy_id]) {
1065 var copyWidgets = this.copyWidgetCache[copy_id];
1067 this.oldCopyWidgetCache[copy_id] = {};
1068 this._copy_fields_for_acqdf.forEach(
1070 self.oldCopyWidgetCache[copy_id][f] =
1071 copyWidgets[f].attr("value");
1077 this.restoreCopyFieldsBeforeDF = function() {
1079 for (var copy_id in this.oldCopyWidgetCache) {
1080 this._copy_fields_for_acqdf.forEach(
1082 self.copyWidgetCache[copy_id][f].attr(
1083 "value", self.oldCopyWidgetCache[copy_id][f]
1090 this._labelFormulasWithCounts = function(store_data) {
1091 for (var key in store_data.items) {
1092 var obj = store_data.items[key];
1093 obj.use_count = Number(obj.use_count); /* needed for sorting */
1095 if (this.virtDfaCounts[obj.id])
1096 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
1098 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
1099 obj.use_count + "]</span> " + obj.name;
1105 * This method formerly would not refetch the DF formulas if they'd been
1106 * loaded already, but now it always re-fetches, since use_count changes.
1108 this._fetchDistribFormulas = function(onload) {
1109 fieldmapper.standardRequest(
1111 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
1114 "params": [openils.User.authtoken],
1115 "oncomplete": function(r) {
1116 self.distribForms = openils.Util.readResponse(r);
1117 if(!self.distribForms || self.distribForms.length == 0) {
1118 self.distribForms = [];
1120 self._addDistribFormulaRow();
1127 this._drawBatchCopyWidgets = function() {
1128 var row = this.copyBatchRow;
1129 dojo.forEach(liDetailBatchFields,
1131 if(self.copyBatchRowDrawn) {
1132 self.copyBatchWidgets[field].attr('value', null);
1134 var widget = new openils.widget.AutoFieldWidget({
1137 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1138 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1139 searchFilter : (field == 'fund') ? {"active": "t"} : null,
1140 parentNode : dojo.query('[name='+field+']', row)[0],
1141 orgLimitPerms : ['CREATE_PICKLIST'],
1144 "labelType": (field == "fund") ? "html" : null
1146 noCache: (field == "fund"),
1151 if (field == "fund" && w.store)
1152 self._ensureCSSFundClasses(w.store);
1153 self.copyBatchWidgets[field] = w;
1156 if (field == "fund") {
1158 widget.widget, "onChange", function(val) {
1159 self._updateFundSelectorStyle(widget, val);
1166 this.copyBatchRowDrawn = true;
1169 this.batchCopyUpdate = function() {
1171 for(var k in this.copyWidgetCache) {
1172 var cache = this.copyWidgetCache[k];
1173 dojo.forEach(liDetailBatchFields, function(f) {
1174 var newval = self.copyBatchWidgets[f].attr('value');
1175 if(newval) cache[f].attr('value', newval);
1180 this._drawCopies = function(li) {
1183 // this button sets the total number of copies for a given lineitem
1184 acqLitAddCopyCount.onClick = function() {
1185 var count = acqLitCopyCountInput.attr('value');
1188 while(self.copyCount() < count)
1191 // delete rows if necessary
1192 var diff = self.copyCount() - count;
1194 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
1195 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
1196 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
1198 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1204 if(li.lineitem_details().length > 0) {
1205 dojo.forEach(li.lineitem_details(),
1207 self.addCopy(li, copy);
1215 this.copyCount = function() {
1217 for(var id in this.copyCache) {
1218 if(!this.copyCache[id].isdeleted())
1224 this.virtCopyId = -1;
1225 this.addCopy = function(li, copy) {
1226 var row = this.copyRow.cloneNode(true);
1227 this.copyTbody.appendChild(row);
1231 copy = new fieldmapper.acqlid();
1233 copy.id(this.virtCopyId--);
1234 copy.lineitem(li.id());
1237 this.copyCache[copy.id()] = copy;
1238 row.setAttribute('copy_id', copy.id());
1239 self.copyWidgetCache[copy.id()] = {};
1241 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1243 dojo.forEach(liDetailFields,
1246 if (field == "fund") {
1247 searchFilter = (copy.fund() ?
1248 {"-or": {"active": "t", "id": copy.fund()}} :
1251 searchFilter = null;
1253 var widget = new openils.widget.AutoFieldWidget({
1256 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1257 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1258 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1259 searchFilter : searchFilter,
1260 noCache: (field == "fund"),
1262 parentNode : dojo.query('[name='+field+']', row)[0],
1263 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
1264 readOnly : Boolean(copy.eg_copy_id())
1267 // make sure we capture the value from any async widgets
1269 if (field == "fund" && w.store)
1270 self._ensureCSSFundClasses(w.store);
1271 copy[field](ww.getFormattedValue())
1272 self.copyWidgetCache[copy.id()][field] = w;
1275 dojo.connect(widget.widget, 'onChange',
1277 if (field == "fund")
1278 self._updateFundSelectorStyle(widget, val);
1280 if (copy.isnew() || val != copy[field]()) {
1281 // prevent setting ischanged() automatically on widget load for existing copies
1282 copy[field](widget.getFormattedValue())
1283 copy.ischanged(true);
1290 this.updateLidState(copy, row);
1293 this._ensureCSSFundClass = function(id) {
1294 if (!this.fundStyleSheet) {
1296 "style", {"type": "text/css"},
1297 document.getElementsByTagName("head")[0], "last"
1299 this.fundStyleSheet = document.styleSheets[
1300 document.styleSheets.length - 1
1304 var cn = "fund_" + id;
1305 if (!this.haveFundClass[cn]) {
1306 fieldmapper.standardRequest(
1307 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
1309 "params": [openils.User.authtoken, id],
1311 "oncomplete": function(r) {
1312 r = openils.Util.readResponse(r);
1313 self.fundBalanceState[id] = r;
1315 if (r[0] /* stop */)
1316 style = fundStyles.stop;
1317 else if (r[1] /* warning */)
1318 style = fundStyles.warning;
1319 self.fundStyleSheet.insertRule(
1320 "." + cn + " { " + style + " }",
1321 self.fundStyleSheet.cssRules.length
1323 self.haveFundClass[cn] = true;
1330 this._ensureCSSFundClasses = function(store) {
1332 "query": {"id": "*"},
1333 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
1337 this._updateFundSelectorStyle = function(widget, fund_id) {
1338 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
1339 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
1342 this.updateLidState = function(copy, row) {
1343 if (typeof(row) == "undefined") {
1345 'tr[copy_id="' + copy.id() + '"]', this.copyTbody
1350 var recv_link = nodeByName("receive", row);
1351 var unrecv_link = nodeByName("unreceive", row);
1352 var del_link = nodeByName("delete", row);
1353 var cxl_link = nodeByName("cancel", row);
1354 var cxl_reason_link = nodeByName("cancel_reason", row);
1356 if (copy.cancel_reason()) {
1357 openils.Util.hide(del_link.parentNode);
1358 openils.Util.hide(recv_link);
1359 openils.Util.hide(unrecv_link);
1360 openils.Util.hide(cxl_link);
1362 /* XXX the following may leak memory in a long lived table: dijits may not get destroyed... not positive. revisit. */
1363 var holds_reason = dojo.create(
1365 "style": "border-bottom: 1px dashed #000;",
1366 "innerHTML": "Cancelled" /* XXX [sic] and i18n */
1367 }, cxl_reason_link, "only"
1371 "label": "<em>" + copy.cancel_reason().label() +
1372 "</em><br />" + copy.cancel_reason().description(),
1373 "connectId": [holds_reason]
1374 }, dojo.create("span", null, cxl_reason_link, "last")
1376 openils.Util.show(cxl_reason_link, "inline");
1377 } else if (this.isPO) {
1378 openils.Util.hide(del_link.parentNode);
1379 openils.Util.hide(cxl_reason_link);
1381 /* Avoid showing (un)receive links, cancel links, for virt copies */
1382 if (copy.id() > 0) {
1383 if(copy.recv_time()) {
1384 openils.Util.hide(cxl_link);
1385 openils.Util.hide(recv_link);
1386 openils.Util.show(unrecv_link, "inline");
1387 unrecv_link.onclick = function() {
1388 if (confirm(localeStrings.UNRECEIVE_LID))
1389 self.issueReceive(copy, /* rollback */ true);
1392 openils.Util.hide(unrecv_link);
1393 openils.Util.show(recv_link, "inline");
1394 openils.Util.show(cxl_link, "inline");
1395 recv_link.onclick = function() {
1396 if (self.checkLiAlerts(copy.lineitem()))
1397 self.issueReceive(copy);
1399 cxl_link.onclick = function() {
1400 self.cancelLid(copy.id());
1404 openils.Util.hide(cxl_link);
1405 openils.Util.hide(unrecv_link);
1406 openils.Util.hide(recv_link);
1409 openils.Util.hide(unrecv_link);
1410 openils.Util.hide(recv_link);
1411 openils.Util.hide(cxl_reason_link);
1413 del_link.onclick = function() { self.deleteCopy(row) };
1414 openils.Util.show(del_link.parentNode);
1418 this.cancelLid = function(lid_id) {
1419 lidCancelDialog._lid_id = lid_id;
1420 openils.Util.show(lidCancelDialog.domNode.parentNode);
1421 lidCancelDialog.show();
1422 if (!lidCancelDialog._prepared) {
1423 var widget = new openils.widget.AutoFieldWidget({
1424 "fmField": "cancel_reason",
1425 "fmClass": "acqlid",
1426 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
1427 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1432 acqLidCancelButton.onClick = function() {
1433 if (w.attr("value")) {
1434 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
1436 lidCancelDialog._lid_id,
1440 lidCancelDialog.hide();
1443 lidCancelDialog._prepared = true;
1449 this._cancelLid = function(lid_id, reason) {
1450 fieldmapper.standardRequest(
1451 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
1452 "params": [openils.User.authtoken, lid_id, reason],
1454 "onresponse": function(r) {
1455 if (r = openils.Util.readResponse(r)) {
1457 for (var id in r.lid) {
1458 /* actually this should only iterate once */
1459 self.copyCache[id].cancel_reason(
1460 r.lid[id].cancel_reason
1462 self.updateLidState(self.copyCache[id]);
1471 this._confirmAlert = function(li, lin) {
1473 dojo.string.substitute(
1474 localeStrings.CONFIRM_LI_ALERT, [
1475 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1476 "title", "lineitem_marc_attr_definition"
1478 lin.alert_text().code(),
1479 lin.alert_text().description() || "",
1486 this.checkLiAlerts = function(li_id) {
1487 var li = this.liCache[li_id];
1489 var alert_notes = li.lineitem_notes().filter(
1490 function(o) { return Boolean(o.alert_text()); }
1493 /* this is _intentionally_ not done in a call to forEach() ... */
1494 for (var i = 0; i < alert_notes.length; i++) {
1495 if (this.noteAcks[alert_notes[i].id()])
1497 else if (!this._confirmAlert(li, alert_notes[i]))
1500 this.noteAcks[alert_notes[i].id()] = true;
1506 this.deleteCopy = function(row) {
1507 var copy = this.copyCache[row.getAttribute('copy_id')];
1508 copy.isdeleted(true);
1510 delete this.copyCache[copy.id()];
1511 this.copyTbody.removeChild(row);
1514 this._virtDfaCountsAsList = function() {
1516 for (var key in this.virtDfaCounts) {
1517 for (var i = 0; i < this.virtDfaCounts[key]; i++)
1523 this.confirmBreachedCopyFunds = function(copies) {
1524 var stop = 0, warning = 0;
1528 var state = self.fundBalanceState[o.fund()];
1529 if (state[0] /* stop */)
1531 else if (state[1] /* warning */)
1538 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
1539 } else if (warning) {
1540 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
1545 this.saveCopyChanges = function(liId) {
1551 for(var id in this.copyCache) {
1552 var c = this.copyCache[id];
1553 if(!c.isdeleted()) total++;
1554 if(c.isnew() || c.ischanged() || c.isdeleted()) {
1555 if(c.id() < 0) c.id(null);
1561 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
1564 if (copies.length > 0) {
1565 if (!this.confirmBreachedCopyFunds(copies))
1568 if (typeof(this._copy_count_cb) == "function")
1569 this._copy_count_cb(liId, total);
1571 openils.Util.show("acq-lit-update-copies-progress");
1572 fieldmapper.standardRequest(
1573 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1575 params: [openils.User.authtoken, copies],
1576 onresponse: function(r) {
1577 var res = openils.Util.readResponse(r);
1578 litUpdateCopiesProgress.update(res);
1580 oncomplete: function() {
1581 self.drawCopies(liId);
1582 openils.Util.hide("acq-lit-update-copies-progress");
1588 var dfa_list = this._virtDfaCountsAsList();
1589 if (dfa_list.length > 0) {
1590 fieldmapper.standardRequest(
1592 "open-ils.acq.distribution_formula.record_application"],
1595 "params": [openils.User.authtoken, dfa_list, liId],
1596 "onresponse": function(r) {
1597 var res = openils.Util.readResponse(r);
1598 if (res && res.length < dfa_list.length)
1599 alert(localeStrings.DFA_NOT_ALL);
1603 this.virtDfaCounts = {};
1607 this._updateCreatePoPrepayCheckbox = function(prepay) {
1608 var prepay = openils.Util.isTrue(prepay);
1609 this._prepayRequiredByVendor = prepay;
1610 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
1613 this._confirmPoPrepaySituation = function() {
1614 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
1615 if (want_prepay != this._prepayRequiredByVendor) {
1618 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
1619 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
1626 this.applySelectedLiAction = function(action) {
1630 case 'delete_selected':
1631 this._deleteLiList(self.getSelected());
1634 case 'create_order':
1636 if(!this.createPoProviderSelector) {
1637 var widget = new openils.widget.AutoFieldWidget({
1638 fmField : 'provider',
1640 searchFilter: {"active": "t"},
1641 parentNode : dojo.byId('acq-lit-po-provider'),
1643 "onChange": function() {
1645 self._updateCreatePoPrepayCheckbox(
1646 this.item.prepayment_required
1653 function(w) { self.createPoProviderSelector = w; }
1657 if(!this.createPoAgencySelector) {
1658 var widget = new openils.widget.AutoFieldWidget({
1659 fmField : 'ordering_agency',
1661 parentNode : dojo.byId('acq-lit-po-agency'),
1662 orgLimitPerms : ['CREATE_PURCHASE_ORDER'],
1665 function(w) { self.createPoAgencySelector = w; }
1670 acqLitPoCreateDialog.show();
1673 case 'save_picklist':
1674 this._loadPLSelect();
1675 acqLitSavePlDialog.show();
1678 case 'selector_ready':
1680 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
1681 acqLitChangeLiStateDialog.show();
1692 case 'rollback_receive_po':
1693 this.rollbackPoReceive();
1696 case 'create_assets':
1697 this.createAssets();
1700 case 'export_attr_list':
1701 this.chooseExportAttr();
1704 case 'add_brief_record':
1706 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
1708 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
1712 case "cancel_lineitems":
1713 this.maybeCancelLineitems();
1718 this.createAssets = function() {
1719 if(!this.isPO) return;
1720 if(!confirm(localeStrings.CREATE_PO_ASSETS_CONFIRM)) return;
1721 this.show('acq-lit-progress-numbers');
1723 fieldmapper.standardRequest(
1724 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
1726 params: [this.authtoken, this.isPO],
1727 onresponse: function(r) {
1728 var resp = openils.Util.readResponse(r);
1729 self._updateProgressNumbers(resp, true);
1735 this.maybeCancelLineitems = function() {
1736 openils.Util.show("acq-lit-cancel-reason", "inline");
1737 if (!acqLitCancelLineitemsButton._prepared) {
1738 var widget = new openils.widget.AutoFieldWidget({
1739 "fmField": "cancel_reason",
1741 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
1742 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1747 acqLitCancelLineitemsButton.onClick = function() {
1748 if (w.attr("value")) {
1749 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
1750 self._cancelLineitems(w.attr("value"));
1752 openils.Util.hide("acq-lit-cancel-reason");
1755 acqLitCancelLineitemsButton._prepared = true;
1761 this._cancelLineitems = function(reason) {
1762 var id_list = this.getSelected().map(function(o) { return o.id(); });
1763 fieldmapper.standardRequest(
1764 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
1765 "params": [openils.User.authtoken, id_list, reason],
1767 "onresponse": function(r) {
1768 if (r = openils.Util.readResponse(r)) {
1770 for (var id in r.li) {
1771 self.liCache[id].state(r.li[id].state);
1772 self.liCache[id].cancel_reason(
1773 r.li[id].cancel_reason
1775 self.updateLiState(self.liCache[id]);
1778 if (r.lid && self.copyCache) {
1779 for (var id in r.lid) {
1780 if (self.copyCache[id]) {
1781 self.copyCache[id].cancel_reason(
1782 r.lid[id].cancel_reason
1784 self.updateLidState(self.copyCache[id]);
1794 this.chooseExportAttr = function() {
1795 if (!acqLitExportAttrSelector._li_setup) {
1797 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
1799 "data": acqliad.toStoreData(
1801 "acqliad", {"code": li_exportable_attrs}
1806 acqLitExportAttrSelector.setValue();
1807 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
1808 acqLitExportAttrSelector._li_setup = true;
1810 openils.Util.show("acq-lit-export-attr-holder", "inline");
1813 this.exportAttrList = function() {
1814 var attr_def = acqLitExportAttrSelector.item;
1815 var li_list = this.getSelected();
1816 var value_list = li_list.map(
1818 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1819 attr_def.code, "lineitem_marc_attr_definition"
1822 ).filter(function(attr) { return Boolean(attr); });
1824 if (value_list.length > 0) {
1825 if (value_list.length < li_list.length) {
1827 dojo.string.substitute(
1828 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
1835 openils.XUL.contentToFileSaveDialog(
1836 value_list.join("\n"),
1837 localeStrings.EXPORT_SAVE_DIALOG_TITLE
1843 alert(dojo.string.substitute(
1844 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
1848 openils.Util.hide("acq-lit-export-attr-holder");
1851 this.printPO = function() {
1852 if(!this.isPO) return;
1853 progressDialog.show(true);
1854 fieldmapper.standardRequest(
1855 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
1857 params: [this.authtoken, this.isPO, 'html'],
1858 oncomplete: function(r) {
1859 progressDialog.hide();
1860 var evt = openils.Util.readResponse(r);
1861 if(evt && evt.template_output()) {
1862 win = window.open('','', 'resizable,width=800,height=600,scrollbars=1');
1863 win.document.body.innerHTML = evt.template_output().data();
1871 this.receivePO = function() {
1872 if (!this.isPO) return;
1874 for (var id in this.liCache) {
1875 /* assumption: liCache reflects exactly the
1876 * set of LIs that belong to our PO */
1877 if (this.liCache[id].state() != "received" &&
1878 !this.checkLiAlerts(id)) return;
1881 this.show('acq-lit-progress-numbers');
1883 fieldmapper.standardRequest(
1884 ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
1886 params: [this.authtoken, this.isPO],
1887 onresponse : function(r) {
1888 var resp = openils.Util.readResponse(r);
1889 self._updateProgressNumbers(resp, true);
1895 this.issueReceive = function(obj, rollback) {
1896 /* (For now) there shall be no marking LI or LIDs (un)received
1897 * except from the actual "view PO" interface. */
1898 if (!this.isPO) return;
1901 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
1903 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
1905 progressDialog.show(true);
1906 fieldmapper.standardRequest(
1907 ["open-ils.acq", method], {
1909 "params": [this.authtoken, obj.id()],
1910 "onresponse": function(r) {
1911 self.handleReceive(openils.Util.readResponse(r));
1912 progressDialog.hide();
1919 * Handles the responses from receive and rollback ML calls.
1921 this.handleReceive = function(resp) {
1924 for (var li_id in resp.li) {
1925 for (var key in resp.li[li_id])
1926 self.liCache[li_id][key](resp.li[li_id][key]);
1927 self.updateLiState(self.liCache[li_id]);
1931 if (typeof(self.poUpdateCallback) == "function")
1932 self.poUpdateCallback(resp.po);
1935 for (var lid_id in resp.lid) {
1936 for (var key in resp.lid[lid_id])
1937 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
1938 self.updateLidState(self.copyCache[lid_id]);
1944 this.rollbackPoReceive = function() {
1945 if(!this.isPO) return;
1946 if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
1947 this.show('acq-lit-progress-numbers');
1949 fieldmapper.standardRequest(
1950 ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
1952 params: [this.authtoken, this.isPO],
1953 onresponse : function(r) {
1954 var resp = openils.Util.readResponse(r);
1955 self._updateProgressNumbers(resp, true);
1961 this._updateProgressNumbers = function(resp, reloadOnComplete) {
1963 dojo.byId('acq-pl-lit-li-processed').innerHTML = resp.li;
1964 dojo.byId('acq-pl-lit-lid-processed').innerHTML = resp.lid;
1965 dojo.byId('acq-pl-lit-debits-processed').innerHTML = resp.debits_accrued;
1966 dojo.byId('acq-pl-lit-bibs-processed').innerHTML = resp.bibs;
1967 dojo.byId('acq-pl-lit-indexed-processed').innerHTML = resp.indexed;
1968 dojo.byId('acq-pl-lit-copies-processed').innerHTML = resp.copies;
1969 if(resp.complete && reloadOnComplete)
1970 location.href = location.href;
1974 this._createPO = function(fields) {
1975 this.show('acq-lit-progress-numbers');
1976 var po = new fieldmapper.acqpo();
1977 po.provider(this.createPoProviderSelector.attr('value'));
1978 po.ordering_agency(this.createPoAgencySelector.attr('value'));
1979 po.prepayment_required(fields.prepayment_required[0] ? true : false);
1981 var selected = this.getSelected( (fields.create_from == 'all') );
1982 if(selected.length == 0) return;
1984 var max = selected.length * 3;
1987 fieldmapper.standardRequest(
1988 ['open-ils.acq', 'open-ils.acq.purchase_order.create'],
1991 openils.User.authtoken,
1994 lineitems : selected.map(function(li) { return li.id() }),
1995 create_assets : fields.create_assets[0],
1999 onresponse : function(r) {
2000 var resp = openils.Util.readResponse(r);
2001 self._updateProgressNumbers(resp);
2003 location.href = oilsBasePath + '/eg/acq/po/view/' + resp.purchase_order.id();
2009 this._deleteLiList = function(list, idx) {
2010 if(idx == null) idx = 0;
2011 if(idx >= list.length) return;
2012 var liId = list[idx].id();
2013 fieldmapper.standardRequest(
2014 ['open-ils.acq', 'open-ils.acq.lineitem.delete'],
2016 params: [openils.User.authtoken, liId],
2017 oncomplete: function(r) {
2018 self.removeLineitem(liId);
2019 self._deleteLiList(list, ++idx);
2025 this.editOrderMarc = function(li) {
2027 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
2028 to true in about:config */
2030 if(!openils.XUL.enableXPConnect()) return;
2032 if(openils.XUL.isXUL()) {
2033 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
2035 win = window.open('/xul/server/cat/marcedit.xul');
2039 record : {marc : li.marc()},
2041 label: 'Save Record', // XXX I18N
2042 func: function(xmlString) {
2044 fieldmapper.standardRequest(
2045 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
2047 params: [openils.User.authtoken, li],
2048 oncomplete: function(r) {
2049 openils.Util.readResponse(r);
2051 self.drawInfo(li.id())
2060 this._savePl = function(values) {
2062 var selected = this.getSelected( (values.which == 'all') );
2063 openils.Util.show('acq-lit-generic-progress');
2065 if(values.new_name) {
2066 openils.acq.Picklist.create(
2067 {name: values.new_name},
2069 self._updateLiList(id, selected, 0,
2071 location.href = oilsBasePath + '/eg/acq/picklist/view/' + id;
2075 } else if(values.existing_pl) {
2076 // update lineitems to use an existing picklist
2077 self._updateLiList(values.existing_pl, selected, 0,
2079 location.href = oilsBasePath + '/eg/acq/picklist/view/' + values.existing_pl;
2084 this._updateLiState = function(values, state) {
2086 var selected = this.getSelected( (values.which == 'all') );
2087 if(!selected.length) return;
2088 dojo.forEach(selected, function(li) {li.state(state);});
2089 self._updateLiList(null, selected, 0,
2090 // TODO consider inline updates for efficiency
2091 function() { location.href = location.href }
2095 this._updateLiList = function(pl, list, idx, oncomplete) {
2096 if(idx >= list.length) return oncomplete();
2098 if(pl != null) li.picklist(pl);
2099 litGenericProgress.update({maximum: list.length, progress: idx});
2100 new openils.acq.Lineitem({lineitem:li}).update(
2102 self._updateLiList(pl, list, ++idx, oncomplete);
2107 this._loadPLSelect = function() {
2108 if(this._plSelectLoaded) return;
2110 function handleResponse(r) {
2111 plList.push(r.recv().content());
2113 var method = 'open-ils.acq.picklist.user.retrieve';
2114 fieldmapper.standardRequest(
2115 ['open-ils.acq', method],
2117 params: [this.authtoken],
2118 onresponse: handleResponse,
2119 oncomplete: function() {
2120 self._plSelectLoaded = true;
2121 acqLitAddExistingSelect.store =
2122 new dojo.data.ItemFileReadStore({data:acqpl.toStoreData(plList)});
2123 acqLitAddExistingSelect.setValue();
2129 this.showRealCopyEditUI = function(li) {
2134 this._fetchLineitem(li.id(),
2136 li = self.liCache[li.id()] = fullLi;
2140 id : li.lineitem_details().map(
2141 function(item) { return item.eg_copy_id() }
2145 oncomplete : function(r) {
2147 var r_list = openils.Util.readResponse( r );
2148 for (var i = 0; i < r_list.length; i++) {
2149 var copy = r_list[i];
2150 var volId = copy.call_number();
2151 var volume = self.volCache[volId];
2153 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2155 copy.call_number(volume);
2156 copyList.push(copy);
2159 // If we need to, we can pass in an update_copy function to handle the update instead of volume_item_creator
2160 xulG.volume_item_creator( { 'existing_copies' : copyList } );
2163 alert('error in oncomplete: ' + E);
2174 this.saveRealCopies = function() {
2175 progressDialog.show(true);
2176 var list = this.realCopyList.filter(function(copy) { return copy.ischanged(); });
2177 this.pcrud.update(list, {oncomplete: function() {
2178 progressDialog.hide();
2183 // grab the li-details for this lineitem, grab the linked copies and volumes, add them to the table
2184 this.showRealCopies = function(li) {
2185 while(this.realCopiesTbody.childNodes[0])
2186 this.realCopiesTbody.removeChild(this.realCopiesTbody.childNodes[0]);
2187 this.show('real-copies');
2189 this.realCopyList = [];
2191 var tabIndex = 1000;
2194 acqLitSaveRealCopies.onClick = function() {
2195 self.saveRealCopies();
2198 this._fetchLineitem(li.id(),
2200 li = self.liCache[li.id()] = fullLi;
2204 id : li.lineitem_details().map(
2205 function(item) { return item.eg_copy_id() }
2210 onresponse : function(r) {
2211 var copy = openils.Util.readResponse(r);
2212 var volId = copy.call_number();
2213 var volume = self.volCache[volId];
2215 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2217 self.addRealCopy(volume, copy, tabIndex++);
2225 this.addRealCopy = function(volume, copy, tabIndex) {
2226 var row = this.realCopiesRow.cloneNode(true);
2227 this.realCopyList.push(copy);
2231 ['owning_lib', 'location', 'circ_modifier', 'label', 'barcode'],
2234 var isvol = (field == 'owning_lib' || field == 'label');
2235 var widget = new openils.widget.AutoFieldWidget({
2237 fmObject : isvol ? volume : copy,
2238 parentNode : nodeByName(field, row),
2239 readOnly : (field != 'barcode'),
2242 var widgetDrawn = null;
2244 if(field == 'barcode') {
2246 widgetDrawn = function(w, ww) {
2247 var node = w.domNode;
2248 node.setAttribute('tabindex', ''+tabIndex);
2250 // on enter, select the next barcode input
2251 dojo.connect(w, 'onKeyDown',
2253 if(e.keyCode == dojo.keys.ENTER) {
2254 var ti = node.getAttribute('tabindex');
2255 var nextNode = dojo.query('[tabindex=' + String(Number(ti) + 1) + ']', self.realCopiesTbody)[0];
2256 if(nextNode) nextNode.select();
2261 dojo.connect(w, 'onChange',
2263 if(!val || val == copy.barcode()) return;
2264 copy.ischanged(true);
2270 if(self.realCopiesTbody.getElementsByTagName('TR').length == 0)
2275 widget.build(widgetDrawn);
2279 this.realCopiesTbody.appendChild(row);
2280 if(selectNode) selectNode.select();