1 dojo.require('dojo.date.locale');
2 dojo.require('dojo.date.stamp');
3 dojo.require('dijit.form.Button');
4 dojo.require('dijit.form.TextBox');
5 dojo.require('dijit.form.FilteringSelect');
6 dojo.require('dijit.form.Textarea');
7 dojo.require('dijit.Tooltip');
8 dojo.require('dijit.ProgressBar');
9 dojo.require('openils.acq.Lineitem');
10 dojo.require('openils.acq.PO');
11 dojo.require('openils.acq.Picklist');
12 dojo.require('openils.widget.AutoFieldWidget');
13 dojo.require('dojo.data.ItemFileReadStore');
14 dojo.require('openils.widget.ProgressDialog');
15 dojo.require('openils.PermaCrud');
17 dojo.requireLocalization('openils.acq', 'acq');
18 var localeStrings = dojo.i18n.getLocalization('openils.acq', 'acq');
19 const XUL_OPAC_WRAPPER = 'chrome://open_ils_staff_client/content/cat/opac.xul';
20 var li_exportable_attrs = ["issn", "isbn", "upc"];
22 var fundLabelFormat = [
23 '<span class="fund_${0}">${1} (${2})</span>', 'id', 'code', 'year'
25 var fundSearchFormat = ['${0} (${1})', 'code', 'year'];
27 function nodeByName(name, context) {
28 return dojo.query('[name='+name+']', context)[0];
32 var liDetailBatchFields = ['fund', 'owning_lib', 'location', 'collection_code', 'circ_modifier', 'cn_label'];
33 var liDetailFields = liDetailBatchFields.concat(['barcode', 'note']);
35 "stop": "color: #c00; font-weight: bold;",
36 "warning": "color: #c93;"
39 function AcqLiTable() {
46 this.haveFundClass = {}
47 this.fundBalanceState = {};
48 this.realDfaCache = {};
49 this.virtDfaCounts = {};
52 this.toggleState = false;
53 this.tbody = dojo.byId('acq-lit-tbody');
56 this.authtoken = openils.User.authtoken;
57 this.pcrud = new openils.PermaCrud();
58 this.rowTemplate = this.tbody.removeChild(dojo.byId('acq-lit-row'));
59 this.copyTbody = dojo.byId('acq-lit-li-details-tbody');
60 this.copyRow = this.copyTbody.removeChild(dojo.byId('acq-lit-li-details-row'));
61 this.copyBatchRow = dojo.byId('acq-lit-li-details-batch-row');
62 this.copyBatchWidgets = {};
63 this.liNotesTbody = dojo.byId('acq-lit-notes-tbody');
64 this.liNotesRow = this.liNotesTbody.removeChild(dojo.byId('acq-lit-notes-row'));
65 this.realCopiesTbody = dojo.byId('acq-lit-real-copies-tbody');
66 this.realCopiesRow = this.realCopiesTbody.removeChild(dojo.byId('acq-lit-real-copies-row'));
67 this._copy_fields_for_acqdf = ['owning_lib', 'location'];
68 this.invoiceLinkDialogManager = new InvoiceLinkDialogManager("li");
70 dojo.connect(acqLitLiActionsSelector, 'onChange',
72 self.applySelectedLiAction(this.attr('value'))
73 acqLitLiActionsSelector.attr('value', '_');
76 acqLitCreatePoSubmit.onClick = function() {
77 if (self._confirmPoPrepaySituation()) {
78 acqLitPoCreateDialog.hide();
79 self._createPO(acqLitPoCreateDialog.getValues());
85 acqLitSavePlButton.onClick = function() {
86 acqLitSavePlDialog.hide();
87 self._savePl(acqLitSavePlDialog.getValues());
90 acqLitCancelLiStateButton.onClick = function() {
91 acqLitChangeLiStateDialog.hide();
93 acqLitSaveLiStateButton.onClick = function() {
94 acqLitChangeLiStateDialog.hide();
95 self._updateLiState(acqLitChangeLiStateDialog.getValues(), acqLitChangeLiStateDialog.attr('state'));
99 dojo.byId('acq-lit-select-toggle').onclick = function(){self.toggleSelect()};
100 dojo.byId('acq-lit-info-back-button').onclick = function(){self.show('list')};
101 dojo.byId('acq-lit-copies-back-button').onclick = function(){self.show('list')};
102 dojo.byId('acq-lit-notes-back-button').onclick = function(){self.show('list')};
103 dojo.byId('acq-lit-real-copies-back-button').onclick = function(){self.show('list')};
105 this.reset = function() {
106 while(self.tbody.childNodes[0])
107 self.tbody.removeChild(self.tbody.childNodes[0]);
113 this.setNext = function(handler) {
114 var link = dojo.byId('acq-lit-next');
116 dojo.style(link, 'visibility', 'visible');
117 link.onclick = handler;
119 dojo.style(link, 'visibility', 'hidden');
123 this.setPrev = function(handler) {
124 var link = dojo.byId('acq-lit-prev');
126 dojo.style(link, 'visibility', 'visible');
127 link.onclick = handler;
129 dojo.style(link, 'visibility', 'hidden');
133 this.show = function(div) {
134 openils.Util.hide('acq-lit-table-div');
135 openils.Util.hide('acq-lit-info-div');
136 openils.Util.hide('acq-lit-li-details');
137 openils.Util.hide('acq-lit-notes-div');
138 openils.Util.hide('acq-lit-real-copies-div');
141 openils.Util.show('acq-lit-table-div');
144 openils.Util.show('acq-lit-info-div');
147 openils.Util.show('acq-lit-li-details');
150 openils.Util.show('acq-lit-real-copies-div');
153 openils.Util.show('acq-lit-notes-div');
157 openils.Util.show(div);
161 this.hide = function() {
165 this.toggleSelect = function() {
167 dojo.forEach(self.selectors, function(i){i.checked = false});
169 dojo.forEach(self.selectors, function(i){i.checked = true});
170 self.toggleState = !self.toggleState;
174 /** @param all If true, assume all are selected */
175 this.getSelected = function(all) {
177 dojo.forEach(self.selectors,
180 selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
186 this.setRowAttr = function(td, liWrapper, field, type) {
187 var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
188 td.appendChild(document.createTextNode(val));
192 * Inserts a single lineitem into the growing table of lineitems
193 * @param {Object} li The lineitem object to insert
195 this.addLineitem = function(li, skip_final_placement) {
196 this.liCache[li.id()] = li;
198 // sort the lineitem notes on edit_time
199 if(!li.lineitem_notes()) li.lineitem_notes([]);
201 var liWrapper = new openils.acq.Lineitem({lineitem:li});
202 var row = self.rowTemplate.cloneNode(true);
203 row.setAttribute('li', li.id());
204 var tds = dojo.query('[attr]', row);
205 dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
206 dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
208 var isbn = liWrapper.findAttr('isbn', 'lineitem_marc_attr_definition');
210 // XXX media prefix for added content
211 dojo.query('[name=jacket]', row)[0].setAttribute('src', '/opac/extras/ac/jacket/small/' + isbn);
214 nodeByName("worksheet_link", row).href =
215 "/eg/acq/lineitem/worksheet/" + li.id();
217 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
218 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
219 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
221 this.updateLiNotesCount(li, row);
223 // show which PO this lineitem is a member of
224 if(li.purchase_order() && !this.isPO) {
226 this.poCache[li.purchase_order()] =
227 this.poCache[li.purchase_order()] ||
228 fieldmapper.standardRequest(
229 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
231 this.authtoken, li.purchase_order(), {
232 "flesh_price_summary": true,
233 "flesh_lineitem_count": true
236 if(po && !this.isMeta) {
237 openils.Util.show(nodeByName('po', row), 'inline');
238 var link = nodeByName('po_link', row);
239 link.setAttribute('href', oilsBasePath + '/acq/po/view/' + li.purchase_order());
240 link.innerHTML = 'PO: ' + po.name(); // TODO i18n
244 // show which picklist this lineitem is a member of
245 if(li.picklist() && (this.isPO || this.isMeta)) {
247 this.plCache[li.picklist()] =
248 this.plCache[li.picklist()] ||
249 fieldmapper.standardRequest(
250 ['open-ils.acq', 'open-ils.acq.picklist.retrieve'],
251 {params: [this.authtoken, li.picklist()]});
253 openils.Util.show(nodeByName('pl', row), 'inline');
254 var link = nodeByName('pl_link', row);
255 link.setAttribute('href', oilsBasePath + '/acq/picklist/view/' + li.picklist());
256 link.innerHTML = 'PL: '+pl.name(); // TODO i18n
260 var countNode = nodeByName('count', row);
261 var count = li.item_count() || 0;
262 if (typeof(this._copy_count_cb) == "function") {
263 this._copy_count_cb(li.id(), count);
265 countNode.innerHTML = count;
266 countNode.id = 'acq-lit-copy-count-label-' + li.id();
269 var priceInput = dojo.query('[name=price]', row)[0];
270 priceInput.value = li.estimated_unit_price() || '';
271 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
273 // show either "mark received" or "unreceive" as appropriate
274 this.updateLiState(li, row);
276 if (!skip_final_placement) {
277 self.tbody.appendChild(row);
278 self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
284 this.updateLiNotesCount = function(li, row) {
285 if (typeof(row) == "undefined")
286 row = dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
288 var has_notes = (li.lineitem_notes().filter(
289 function(o) { return Boolean (o.alert_text()); }
292 /* U+2691 is the code point for a filled-in flag character */
293 nodeByName("notes_alert_flag", row).innerHTML =
294 has_notes ? "⚑" : "";
295 nodeByName("noteslink", row).style.fontStyle =
296 has_notes ? "italic" : "normal";
297 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
300 /* XXX NOT related to _updateLiState(). rethink */
301 this.updateLiState = function(li, row) {
302 if (typeof(row) == "undefined")
303 row = dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
305 var actReceive = nodeByName("action_mark_recv", row);
306 var actUnRecv = nodeByName("action_mark_unrecv", row);
307 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
308 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
310 var actNewInvoice = nodeByName('action_new_invoice', row);
311 var actLinkInvoice = nodeByName('action_link_invoice', row);
312 var actViewInvoice = nodeByName('action_view_invoice', row);
314 var state_cell = nodeByName("li_state", row);
316 if (li.state() == "cancelled") {
317 if (typeof li.cancel_reason() == "object") {
318 var holds_state = dojo.create(
320 "style": "border-bottom: 1px dashed #000;",
321 "innerHTML": li.state()
322 }, state_cell, "only"
326 "label": "<em>" + li.cancel_reason().label() +
327 "</em><br />" + li.cancel_reason().description(),
328 "connectId": [holds_state]
329 }, dojo.create("span", null, state_cell, "last")
332 state_cell.innerHTML = li.state(); // TODO i18n state labels
335 state_cell.innerHTML = li.state(); // TODO i18n state labels
339 /* handle row coloring for based on LI state */
340 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
341 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
343 /* handle links that appear/disappear based on whether LI is received */
348 actReceive.disabled = false;
349 actReceive.onclick = function() {
350 if (self.checkLiAlerts(li.id()))
351 self.issueReceive(li);
352 nodeByName("action_none", row).selected = true;
356 actUnRecv.disabled = false;
357 actUnRecv.onclick = function() {
358 if (confirm(localeStrings.UNRECEIVE_LI))
359 self.issueReceive(li, /* rollback */ true);
360 nodeByName("action_none", row).selected = true;
362 // TODO we should allow editing before receipt, in which case the
363 // test should be "if 1 or more real (acp) copies exist
364 actUpdateBarcodes.disabled = false;
365 actUpdateBarcodes.onclick = function() {
366 self.showRealCopyEditUI(li);
367 nodeByName("action_none", row).selected = true;
369 actHoldingsMaint.disabled = false;
370 actHoldingsMaint.onclick = self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
372 actNewInvoice.disabled = false;
373 actLinkInvoice.disabled = false;
374 actViewInvoice.disabled = false;
376 actNewInvoice.onclick = function() {
377 location.href = oilsBasePath + '/acq/invoice/view?create=1&attach_li=' + li.id();
378 nodeByName("action_none", row).selected = true;
380 actLinkInvoice.onclick = function() {
381 self.invoiceLinkDialogManager.target = li;
382 acqLitLinkInvoiceDialog.show();
383 nodeByName("action_none", row).selected = true;
385 actViewInvoice.onclick = function() {
386 location.href = oilsBasePath +
387 "/acq/search/unified?so=" +
388 base64Encode({"jub":[{"id": li.id()}]}) +
390 nodeByName("action_none", row).selected = true;
399 this._setAlertStore = function() {
400 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
402 "data": acqliat.toStoreData(
404 "acqliat", {"id": {"!=": null}}
409 acqLitAlertAlertText.setValue(); /* make the store "live" */
410 acqLitAlertAlertText._store_ready = true;
414 * Draws and shows the lineitem notes pane
416 this.drawLiNotes = function(li) {
419 if (!acqLitAlertAlertText._store_ready)
420 this._setAlertStore();
423 li.lineitem_notes().sort(
425 if(a.edit_time() < b.edit_time()) return 1;
431 while(this.liNotesTbody.childNodes[0])
432 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
435 acqLitCreateNoteSubmit.onClick = function() {
436 var value = acqLitCreateNoteText.attr('value');
438 var note = new fieldmapper.acqlin();
441 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
444 note.lineitem(li.id());
446 self.updateLiNotes(li, note);
447 acqLitCreateNoteVendorPublic.attr("checked", false);
448 acqLitCreateNoteText.attr("value", "");
451 acqLitCreateAlertSubmit.onClick = function() {
452 if (!acqLitAlertAlertText.item) {
453 alert(localeStrings.ALERT_UNSELECTED);
457 var alert_text = new fieldmapper.acqliat().fromStoreItem(
458 acqLitAlertAlertText.item
460 var value = acqLitAlertNoteValue.attr("value") || "";
462 var note = new fieldmapper.acqlin();
464 note.lineitem(li.id());
466 note.alert_text(alert_text);
468 self.updateLiNotes(li, note);
471 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
475 * Draws a single lineitem note in the notes pane
477 this.addLiNote = function(li, note) {
478 if(note.isdeleted()) return;
480 var row = self.liNotesRow.cloneNode(true);
481 nodeByName("value", row).innerHTML = note.value();
482 var alert_node = nodeByName("alert_code", row);
483 if (note.alert_text()) {
484 alert_node.innerHTML = note.alert_text().code();
485 if (note.alert_text().description()) {
488 "connectId": [alert_node],
489 "label": note.alert_text().description()
490 }, dojo.create("span", null, alert_node, "after")
495 if (openils.Util.isTrue(note.vendor_public()))
496 nodeByName("vendor_public", row).innerHTML =
497 localeStrings.VENDOR_PUBLIC;
499 nodeByName("delete", row).onclick = function() {
500 note.isdeleted(true);
501 self.liNotesTbody.removeChild(row);
502 self.updateLiNotes(li);
505 if(note.edit_time()) {
506 nodeByName("edit_time", row).innerHTML =
507 dojo.date.locale.format(
508 dojo.date.stamp.fromISOString(note.edit_time()),
509 {formatLength:'short'});
512 self.liNotesTbody.appendChild(row);
516 * Updates any new/changed/deleted notes on the server
518 this.updateLiNotes = function(li, newNote) {
524 notes = li.lineitem_notes().filter(
526 if(note.ischanged() || note.isnew() || note.isdeleted())
532 if(notes.length == 0) return;
533 progressDialog.show();
535 fieldmapper.standardRequest(
536 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
538 params : [this.authtoken, notes],
539 onresponse : function(r) {
540 var resp = openils.Util.readResponse(r);
545 // remove the old changed notes
547 dojo.forEach(li.lineitem_notes(),
549 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
553 li.lineitem_notes(list);
556 progressDialog.hide();
557 self.updateLiNotesCount(li);
558 self.drawLiNotes(li);
562 progressDialog.update(resp);
563 var newnote = resp.note;
565 if(!newnote.isdeleted()) {
566 newnote.isnew(false);
567 newnote.ischanged(false);
568 li.lineitem_notes().push(newnote);
575 this.updateLiPrice = function(input, li) {
577 var price = input.value;
578 if(Number(price) == Number(li.estimated_unit_price())) return;
580 fieldmapper.standardRequest(
581 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
583 params : [this.authtoken, li.id(), price],
584 oncomplete : function(r) {
585 openils.Util.readResponse(r);
586 li.estimated_unit_price(price); // update local copy
592 this.removeLineitem = function(liId) {
593 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
594 delete this.liCache[liId];
595 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
598 this.drawInfo = function(liId) {
599 if (!this._isRelatedViewer) {
600 var d = dojo.byId("acq-lit-info-related");
601 if (!this.relCache[liId]) {
602 fieldmapper.standardRequest(
605 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
608 "params": [openils.User.authtoken, liId],
609 "onresponse": function(r) {
610 self.relCache[liId] = openils.Util.readResponse(r);
611 nodeByName("related_number", d).innerHTML =
614 self.relCache[liId] >1 ? "show" : "hide"
620 nodeByName("related_number", d).innerHTML = this.relCache[liId];
621 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
626 openils.acq.Lineitem.fetchAttrDefs(
628 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
633 this._fetchLineitem = function(liId, handler) {
635 var li = this.liCache[liId];
636 if(li && li.marc() && li.lineitem_details())
639 fieldmapper.standardRequest(
640 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve'],
643 params: [self.authtoken, liId, {
645 flesh_cancel_reason: true,
646 flesh_li_details: true,
647 flesh_fund_debit: true }],
649 oncomplete: function(r) {
650 var li = openils.Util.readResponse(r);
657 this._drawInfo = function(li) {
659 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
662 openils.Util.hide('acq-lit-marc-order-record-label');
663 openils.Util.hide(acqLitEditOrderMarc.domNode);
664 openils.Util.show('acq-lit-marc-real-record-label');
666 openils.Util.show('acq-lit-marc-order-record-label');
667 openils.Util.show(acqLitEditOrderMarc.domNode);
668 openils.Util.hide('acq-lit-marc-real-record-label');
671 this.drawMarcHTML(li);
672 this.infoTbody = dojo.byId('acq-lit-info-tbody');
675 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
676 while(this.infoTbody.childNodes[0])
677 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
679 for(var i = 0; i < li.attributes().length; i++) {
680 var attr = li.attributes()[i];
681 var row = this.infoRow.cloneNode(true);
683 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
684 var name = openils.acq.Lineitem.attrDefs[type].filter(
686 return (a.code() == attr.attr_name());
688 ).pop().description();
690 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
691 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
692 this.infoTbody.appendChild(row);
695 if (!this._isRelatedViewer) {
696 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
697 "/eg/acq/lineitem/related/" + li.id();
702 openils.Util.show('acq-lit-info-cat-link');
703 var link = dojo.byId('acq-lit-info-cat-link').getElementsByTagName('a')[0];
705 if(openils.XUL.isXUL()) {
707 link.setAttribute('href', 'javascript:void(0);');
708 link.onclick = this.generateMakeRecTab( li.eg_bib_id() );
711 var href = link.getAttribute('href');
713 link.setAttribute('href', href + li.eg_bib_id());
716 openils.Util.hide('acq-lit-info-cat-link');
720 this.generateMakeRecTab = function(bib_id,default_view, row) {
724 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
727 show_nav_buttons : true,
728 show_print_button : true,
729 opac_url : xulG.url_prefix(xulG.urls.opac_rdetail + '?r=' + bib_id),
730 default_view : default_view
734 if(row) nodeByName("action_none", row).selected = true;
738 this.drawMarcHTML = function(li) {
739 var params = [null, true, li.marc()];
741 params = [li.eg_bib_id(), true];
743 fieldmapper.standardRequest(
744 ['open-ils.search', 'open-ils.search.biblio.record.html'],
747 oncomplete: function(r) {
748 dojo.byId('acq-lit-marc-div').innerHTML =
749 openils.Util.readResponse(r);
755 this.drawCopies = function(liId) {
759 this.copyWidgetCache = {};
760 this.oldCopyWidgetCache = {};
761 this.virtDfaCounts = {};
762 this.realDfaCache = {};
765 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
766 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
767 acqLitCopyCountInput.attr('value', '0');
769 while(this.copyTbody.childNodes[0])
770 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
772 this._drawBatchCopyWidgets();
774 this._drawDistribApplied(liId);
776 this._fetchDistribFormulas(
778 openils.acq.Lineitem.fetchAttrDefs(
780 self._fetchLineitem(liId, function(li){self._drawCopies(li);});
787 this._saveDistribAppliedTemplates = function() {
788 if (!this._appliedDistribTemplate) {
789 this._appliedDistribTemplate =
790 dojo.byId("acq-lit-distrib-applied-tbody").
791 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
792 dojo.attr(this._appliedDistribTemplate, "id");
796 this._drawDistribApplied = function(liId) {
797 /* Build this table while hidden to prevent rendering artifacts */
798 openils.Util.hide("acq-lit-distrib-applied-tbody");
800 this._saveDistribAppliedTemplates();
802 /* Remove any rows in the table from previous populations */
803 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
804 forEach(dojo.destroy);
806 /* Unregister all dijits previously created (for some reason this isn't
807 * covered by the above destroy calls). */
808 dijit.registry.forEach(
809 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
812 /* Populate the table with our liId */
814 fieldmapper.standardRequest(
816 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
819 "params": [self.authtoken, liId],
820 "onresponse": function(r) {
821 var dfa = openils.Util.readResponse(r);
824 self.realDfaCache[dfa.id()] = dfa;
825 self._drawDistribAppliedUnit(dfa);
828 "oncomplete": function() {
829 /* Reveal built table */
832 "acq-lit-distrib-applied-tbody", "table-row-group"
840 this._drawDistribAppliedUnit = function(dfa) {
842 var row = dojo.query(
843 'tr[formula="' + dfa.formula().id() + '"]',
844 "acq-lit-distrib-applied-tbody"
849 row = dojo.clone(this._appliedDistribTemplate);
850 dojo.attr(row, "formula", dfa.formula().id());
851 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
854 var td = dojo.query("td", row)[0];
856 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
857 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
860 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
862 new dijit.form.Button(
864 "onClick": function() {
865 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
869 /* XXX I /cannot/ make the following work in as a CSS class
870 * for some reason. So frustrating... */
871 "style": function(id) {
873 "font-weight: bold; color: #c00;" :
875 }(dfa.id()) + "margin: 0 6px;display: inline;"
876 }, "dfa-button-" + dfa.id()
880 "connectId": ["dfa-button-" + dfa.id()],
881 "label": dojo.string.substitute(
882 localeStrings.DFA_TIP, dfa.id() > 0 ? [
883 openils.User.formalName(dfa.creator()),
884 dojo.date.locale.format(
885 dojo.date.stamp.fromISOString(dfa.create_time()),
886 {"formatLength":"short"}
888 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
890 }, "dfa-tip-" + dfa.id()
894 this.deleteDfa = function(dfa) {
895 if (dfa.id() > 0) { /* real */
896 this.pcrud.eliminate(
899 "oncomplete": function() {
900 self._removeDistribApplied(dfa.id());
901 delete self.realDfaCache[dfa.id()];
905 } else { /* virtual */
906 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
907 this.virtDfaCounts[dfa.formula().id()] = 0;
908 /* hasn't been saved yet, so no need to do anything server side */
909 this._removeDistribApplied(dfa.id());
914 this._removeDistribApplied = function(dfaId) {
915 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
916 dijit.registry.forEach(
917 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
919 this._removeDistribAppliedEmptyRows();
922 this._removeAllDistribAppliedVirtual = function() {
923 /* Unregister dijits */
924 dijit.registry.forEach(
925 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
927 this._removeDistribAppliedEmptyRows();
930 this._removeDistribAppliedEmptyRows = function() {
931 /* Remove any rows with no DFA at all */
932 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
934 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
940 * Insert a new row into the distribution formula selection form
942 this._addDistribFormulaRow = function() {
945 if (!self.distribForms) {
946 // no formulas, hide the form
947 openils.Util.hide('acq-lit-distrib-formula-tbody');
951 if(!this.distribFormulaTemplate)
952 this.distribFormulaTemplate =
953 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
955 var row = this.distribFormulaTemplate.cloneNode(true);
956 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
958 this.dfSelector = new dijit.form.FilteringSelect(
959 {"labelAttr": "dynLabel", "labelType": "html"},
960 nodeByName("selector", row)
962 this._updateFormulaStore();
963 this.dfSelector.fetchProperties =
964 {"sort": [{"attribute": "use_count", "descending": true}]};
966 var apply = new dijit.form.Button(
967 {"label": localeStrings.APPLY},
968 nodeByName('set_button', row)
971 var reset = new dijit.form.Button(
972 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
973 nodeByName("reset_button", row)
976 dojo.connect(apply, 'onClick',
978 var form_id = self.dfSelector.attr("value");
980 self._applyDistribFormula(form_id);
981 reset.attr("disabled", false);
985 dojo.connect(reset, 'onClick',
987 self.restoreCopyFieldsBeforeDF();
988 self.virtDfaCounts = {};
991 self._updateFormulaStore();
992 self._removeAllDistribAppliedVirtual();
993 reset.attr("disabled", "true");
1000 * Applies a distrib formula to the current set of copies
1002 this._applyDistribFormula = function(formula) {
1003 if(!formula) return;
1005 formula = this.distribForms.filter(
1006 function(form) { return form.id() == formula; }
1009 var copyRows = dojo.query('tr', self.copyTbody);
1011 if (this.dfeOffset >= copyRows.length) {
1012 alert(localeStrings.OUT_OF_COPIES);
1016 var entries_applied = 0;
1018 var rowIndex = this.dfeOffset;
1019 rowIndex < copyRows.length;
1023 var row = copyRows[rowIndex];
1024 var copy_id = row.getAttribute('copy_id');
1025 var copyWidgets = this.copyWidgetCache[copy_id];
1026 var entryIndex = this.dfeOffset;
1029 // find the correct entry for the current row
1030 dojo.forEach(formula.entries(),
1033 entryIndex += e.item_count();
1034 if(entryIndex > rowIndex)
1042 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
1043 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
1046 this.saveCopyFieldsBeforeDF(copy_id);
1047 this._copy_fields_for_acqdf.forEach(
1049 if(entry[field]()) {
1050 copyWidgets[field].attr('value', (entry[field]()));
1057 if (entries_applied) {
1058 this.virtDfaCounts[formula.id()] =
1059 ++(this.virtDfaCounts[formula.id()]) || 1;
1060 this._updateFormulaStore();
1061 this._drawDistribAppliedUnit(
1063 var dfa = new acqdfa();
1064 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
1067 this.dfeOffset += entries_applied;
1072 * This function updates the DF store for the dropdown so that use_counts
1073 * can reflect DF applications from this session before they're saved
1076 this._updateFormulaStore = function() {
1077 this.dfSelector.store = new dojo.data.ItemFileReadStore(
1079 "data": self._labelFormulasWithCounts(
1080 acqdf.toStoreData(self.distribForms)
1086 this.saveCopyFieldsBeforeDF = function(copy_id) {
1088 if (!this.oldCopyWidgetCache[copy_id]) {
1089 var copyWidgets = this.copyWidgetCache[copy_id];
1091 this.oldCopyWidgetCache[copy_id] = {};
1092 this._copy_fields_for_acqdf.forEach(
1094 self.oldCopyWidgetCache[copy_id][f] =
1095 copyWidgets[f].attr("value");
1101 this.restoreCopyFieldsBeforeDF = function() {
1103 for (var copy_id in this.oldCopyWidgetCache) {
1104 this._copy_fields_for_acqdf.forEach(
1106 self.copyWidgetCache[copy_id][f].attr(
1107 "value", self.oldCopyWidgetCache[copy_id][f]
1114 this._labelFormulasWithCounts = function(store_data) {
1115 for (var key in store_data.items) {
1116 var obj = store_data.items[key];
1117 obj.use_count = Number(obj.use_count); /* needed for sorting */
1119 if (this.virtDfaCounts[obj.id])
1120 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
1122 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
1123 obj.use_count + "]</span> " + obj.name;
1129 * This method formerly would not refetch the DF formulas if they'd been
1130 * loaded already, but now it always re-fetches, since use_count changes.
1132 this._fetchDistribFormulas = function(onload) {
1133 fieldmapper.standardRequest(
1135 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
1138 "params": [openils.User.authtoken],
1139 "oncomplete": function(r) {
1140 self.distribForms = openils.Util.readResponse(r);
1141 if(!self.distribForms || self.distribForms.length == 0) {
1142 self.distribForms = [];
1144 self._addDistribFormulaRow();
1151 this._drawBatchCopyWidgets = function() {
1152 var row = this.copyBatchRow;
1153 dojo.forEach(liDetailBatchFields,
1155 if(self.copyBatchRowDrawn) {
1156 self.copyBatchWidgets[field].attr('value', null);
1158 var widget = new openils.widget.AutoFieldWidget({
1161 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1162 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1163 searchFilter : (field == 'fund') ? {"active": "t"} : null,
1164 parentNode : dojo.query('[name='+field+']', row)[0],
1165 orgLimitPerms : ['CREATE_PICKLIST'],
1168 "labelType": (field == "fund") ? "html" : null
1170 noCache: (field == "fund"),
1175 if (field == "fund" && w.store)
1176 self._ensureCSSFundClasses(w.store);
1177 self.copyBatchWidgets[field] = w;
1180 if (field == "fund") {
1182 widget.widget, "onChange", function(val) {
1183 self._updateFundSelectorStyle(widget, val);
1190 this.copyBatchRowDrawn = true;
1193 this.batchCopyUpdate = function() {
1195 for(var k in this.copyWidgetCache) {
1196 var cache = this.copyWidgetCache[k];
1197 dojo.forEach(liDetailBatchFields, function(f) {
1198 var newval = self.copyBatchWidgets[f].attr('value');
1199 if(newval) cache[f].attr('value', newval);
1204 this._drawCopies = function(li) {
1207 // this button sets the total number of copies for a given lineitem
1208 acqLitAddCopyCount.onClick = function() {
1209 var count = acqLitCopyCountInput.attr('value');
1212 while(self.copyCount() < count)
1215 // delete rows if necessary
1216 var diff = self.copyCount() - count;
1218 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
1219 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
1220 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
1222 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1228 if(li.lineitem_details().length > 0) {
1229 dojo.forEach(li.lineitem_details(),
1231 self.addCopy(li, copy);
1239 this.copyCount = function() {
1241 for(var id in this.copyCache) {
1242 if(!this.copyCache[id].isdeleted())
1248 this.virtCopyId = -1;
1249 this.addCopy = function(li, copy) {
1250 var row = this.copyRow.cloneNode(true);
1251 this.copyTbody.appendChild(row);
1255 copy = new fieldmapper.acqlid();
1257 copy.id(this.virtCopyId--);
1258 copy.lineitem(li.id());
1261 this.copyCache[copy.id()] = copy;
1262 row.setAttribute('copy_id', copy.id());
1263 self.copyWidgetCache[copy.id()] = {};
1265 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1267 dojo.forEach(liDetailFields,
1270 if (field == "fund") {
1271 searchFilter = (copy.fund() ?
1272 {"-or": {"active": "t", "id": copy.fund()}} :
1275 searchFilter = null;
1277 var widget = new openils.widget.AutoFieldWidget({
1280 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1281 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1282 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1283 searchFilter : searchFilter,
1284 noCache: (field == "fund"),
1286 parentNode : dojo.query('[name='+field+']', row)[0],
1287 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
1288 readOnly : Boolean(copy.eg_copy_id())
1291 // make sure we capture the value from any async widgets
1293 if (field == "fund" && w.store)
1294 self._ensureCSSFundClasses(w.store);
1295 copy[field](ww.getFormattedValue())
1296 self.copyWidgetCache[copy.id()][field] = w;
1299 dojo.connect(widget.widget, 'onChange',
1301 if (field == "fund")
1302 self._updateFundSelectorStyle(widget, val);
1304 if (copy.isnew() || val != copy[field]()) {
1305 // prevent setting ischanged() automatically on widget load for existing copies
1306 copy[field](widget.getFormattedValue())
1307 copy.ischanged(true);
1314 this.updateLidState(copy, row);
1317 this._ensureCSSFundClass = function(id) {
1318 if (!this.fundStyleSheet) {
1320 "style", {"type": "text/css"},
1321 document.getElementsByTagName("head")[0], "last"
1323 this.fundStyleSheet = document.styleSheets[
1324 document.styleSheets.length - 1
1328 var cn = "fund_" + id;
1329 if (!this.haveFundClass[cn]) {
1330 fieldmapper.standardRequest(
1331 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
1333 "params": [openils.User.authtoken, id],
1335 "oncomplete": function(r) {
1336 r = openils.Util.readResponse(r);
1337 self.fundBalanceState[id] = r;
1339 if (r[0] /* stop */)
1340 style = fundStyles.stop;
1341 else if (r[1] /* warning */)
1342 style = fundStyles.warning;
1343 self.fundStyleSheet.insertRule(
1344 "." + cn + " { " + style + " }",
1345 self.fundStyleSheet.cssRules.length
1347 self.haveFundClass[cn] = true;
1354 this._ensureCSSFundClasses = function(store) {
1356 "query": {"id": "*"},
1357 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
1361 this._updateFundSelectorStyle = function(widget, fund_id) {
1362 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
1363 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
1366 this.updateLidState = function(copy, row) {
1367 if (typeof(row) == "undefined") {
1369 'tr[copy_id="' + copy.id() + '"]', this.copyTbody
1374 var recv_link = nodeByName("receive", row);
1375 var unrecv_link = nodeByName("unreceive", row);
1376 var del_link = nodeByName("delete", row);
1377 var cxl_link = nodeByName("cancel", row);
1378 var cxl_reason_link = nodeByName("cancel_reason", row);
1380 if (copy.cancel_reason()) {
1381 openils.Util.hide(del_link.parentNode);
1382 openils.Util.hide(recv_link);
1383 openils.Util.hide(unrecv_link);
1384 openils.Util.hide(cxl_link);
1386 /* XXX the following may leak memory in a long lived table: dijits may not get destroyed... not positive. revisit. */
1387 var holds_reason = dojo.create(
1389 "style": "border-bottom: 1px dashed #000;",
1390 "innerHTML": "Cancelled" /* XXX [sic] and i18n */
1391 }, cxl_reason_link, "only"
1395 "label": "<em>" + copy.cancel_reason().label() +
1396 "</em><br />" + copy.cancel_reason().description(),
1397 "connectId": [holds_reason]
1398 }, dojo.create("span", null, cxl_reason_link, "last")
1400 openils.Util.show(cxl_reason_link, "inline");
1401 } else if (this.isPO) {
1402 openils.Util.hide(del_link.parentNode);
1403 openils.Util.hide(cxl_reason_link);
1405 /* Avoid showing (un)receive links, cancel links, for virt copies */
1406 if (copy.id() > 0) {
1407 if(copy.recv_time()) {
1408 openils.Util.hide(cxl_link);
1409 openils.Util.hide(recv_link);
1410 openils.Util.show(unrecv_link, "inline");
1411 unrecv_link.onclick = function() {
1412 if (confirm(localeStrings.UNRECEIVE_LID))
1413 self.issueReceive(copy, /* rollback */ true);
1416 openils.Util.hide(unrecv_link);
1417 openils.Util.show(recv_link, "inline");
1418 openils.Util.show(cxl_link, "inline");
1419 recv_link.onclick = function() {
1420 if (self.checkLiAlerts(copy.lineitem()))
1421 self.issueReceive(copy);
1423 cxl_link.onclick = function() {
1424 self.cancelLid(copy.id());
1428 openils.Util.hide(cxl_link);
1429 openils.Util.hide(unrecv_link);
1430 openils.Util.hide(recv_link);
1433 openils.Util.hide(unrecv_link);
1434 openils.Util.hide(recv_link);
1435 openils.Util.hide(cxl_reason_link);
1437 del_link.onclick = function() { self.deleteCopy(row) };
1438 openils.Util.show(del_link.parentNode);
1442 this.cancelLid = function(lid_id) {
1443 lidCancelDialog._lid_id = lid_id;
1444 openils.Util.show(lidCancelDialog.domNode.parentNode);
1445 lidCancelDialog.show();
1446 if (!lidCancelDialog._prepared) {
1447 var widget = new openils.widget.AutoFieldWidget({
1448 "fmField": "cancel_reason",
1449 "fmClass": "acqlid",
1450 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
1451 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1456 acqLidCancelButton.onClick = function() {
1457 if (w.attr("value")) {
1458 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
1460 lidCancelDialog._lid_id,
1464 lidCancelDialog.hide();
1467 lidCancelDialog._prepared = true;
1473 this._cancelLid = function(lid_id, reason) {
1474 fieldmapper.standardRequest(
1475 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
1476 "params": [openils.User.authtoken, lid_id, reason],
1478 "onresponse": function(r) {
1479 if (r = openils.Util.readResponse(r)) {
1481 for (var id in r.lid) {
1482 /* actually this should only iterate once */
1483 self.copyCache[id].cancel_reason(
1484 r.lid[id].cancel_reason
1486 self.updateLidState(self.copyCache[id]);
1495 this._confirmAlert = function(li, lin) {
1497 dojo.string.substitute(
1498 localeStrings.CONFIRM_LI_ALERT, [
1499 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1500 "title", "lineitem_marc_attr_definition"
1502 lin.alert_text().code(),
1503 lin.alert_text().description() || "",
1510 this.checkLiAlerts = function(li_id) {
1511 var li = this.liCache[li_id];
1513 var alert_notes = li.lineitem_notes().filter(
1514 function(o) { return Boolean(o.alert_text()); }
1517 /* this is _intentionally_ not done in a call to forEach() ... */
1518 for (var i = 0; i < alert_notes.length; i++) {
1519 if (this.noteAcks[alert_notes[i].id()])
1521 else if (!this._confirmAlert(li, alert_notes[i]))
1524 this.noteAcks[alert_notes[i].id()] = true;
1530 this.deleteCopy = function(row) {
1531 var copy = this.copyCache[row.getAttribute('copy_id')];
1532 copy.isdeleted(true);
1534 delete this.copyCache[copy.id()];
1535 this.copyTbody.removeChild(row);
1538 this._virtDfaCountsAsList = function() {
1540 for (var key in this.virtDfaCounts) {
1541 for (var i = 0; i < this.virtDfaCounts[key]; i++)
1547 this.confirmBreachedCopyFunds = function(copies) {
1548 var stop = 0, warning = 0;
1552 var state = self.fundBalanceState[o.fund()];
1553 if (state[0] /* stop */)
1555 else if (state[1] /* warning */)
1562 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
1563 } else if (warning) {
1564 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
1569 this.saveCopyChanges = function(liId) {
1575 for(var id in this.copyCache) {
1576 var c = this.copyCache[id];
1577 if(!c.isdeleted()) total++;
1578 if(c.isnew() || c.ischanged() || c.isdeleted()) {
1579 if(c.id() < 0) c.id(null);
1585 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
1588 if (copies.length > 0) {
1589 if (!this.confirmBreachedCopyFunds(copies))
1592 if (typeof(this._copy_count_cb) == "function")
1593 this._copy_count_cb(liId, total);
1595 openils.Util.show("acq-lit-update-copies-progress");
1596 fieldmapper.standardRequest(
1597 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1599 params: [openils.User.authtoken, copies],
1600 onresponse: function(r) {
1601 var res = openils.Util.readResponse(r);
1602 litUpdateCopiesProgress.update(res);
1604 oncomplete: function() {
1605 self.drawCopies(liId);
1606 openils.Util.hide("acq-lit-update-copies-progress");
1612 var dfa_list = this._virtDfaCountsAsList();
1613 if (dfa_list.length > 0) {
1614 fieldmapper.standardRequest(
1616 "open-ils.acq.distribution_formula.record_application"],
1619 "params": [openils.User.authtoken, dfa_list, liId],
1620 "onresponse": function(r) {
1621 var res = openils.Util.readResponse(r);
1622 if (res && res.length < dfa_list.length)
1623 alert(localeStrings.DFA_NOT_ALL);
1627 this.virtDfaCounts = {};
1631 this._updateCreatePoPrepayCheckbox = function(prepay) {
1632 var prepay = openils.Util.isTrue(prepay);
1633 this._prepayRequiredByVendor = prepay;
1634 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
1637 this._confirmPoPrepaySituation = function() {
1638 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
1639 if (want_prepay != this._prepayRequiredByVendor) {
1642 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
1643 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
1650 this.applySelectedLiAction = function(action) {
1654 case 'delete_selected':
1655 this._deleteLiList(self.getSelected());
1658 case 'create_order':
1660 if(!this.createPoProviderSelector) {
1661 var widget = new openils.widget.AutoFieldWidget({
1662 fmField : 'provider',
1664 searchFilter: {"active": "t"},
1665 parentNode : dojo.byId('acq-lit-po-provider'),
1667 "onChange": function() {
1669 self._updateCreatePoPrepayCheckbox(
1670 this.item.prepayment_required
1677 function(w) { self.createPoProviderSelector = w; }
1681 if(!this.createPoAgencySelector) {
1682 var widget = new openils.widget.AutoFieldWidget({
1683 fmField : 'ordering_agency',
1685 parentNode : dojo.byId('acq-lit-po-agency'),
1686 orgLimitPerms : ['CREATE_PURCHASE_ORDER'],
1689 function(w) { self.createPoAgencySelector = w; }
1694 acqLitPoCreateDialog.show();
1697 case 'save_picklist':
1698 this._loadPLSelect();
1699 acqLitSavePlDialog.show();
1702 case 'selector_ready':
1704 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
1705 acqLitChangeLiStateDialog.show();
1716 case 'rollback_receive_po':
1717 this.rollbackPoReceive();
1720 case 'create_assets':
1721 this.createAssets();
1724 case 'export_attr_list':
1725 this.chooseExportAttr();
1728 case 'add_brief_record':
1730 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
1732 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
1736 case "cancel_lineitems":
1737 this.maybeCancelLineitems();
1742 this.createAssets = function() {
1743 if(!this.isPO) return;
1744 if(!confirm(localeStrings.CREATE_PO_ASSETS_CONFIRM)) return;
1745 this.show('acq-lit-progress-numbers');
1747 fieldmapper.standardRequest(
1748 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
1750 params: [this.authtoken, this.isPO],
1751 onresponse: function(r) {
1752 var resp = openils.Util.readResponse(r);
1753 self._updateProgressNumbers(resp, true);
1759 this.maybeCancelLineitems = function() {
1760 openils.Util.show("acq-lit-cancel-reason", "inline");
1761 if (!acqLitCancelLineitemsButton._prepared) {
1762 var widget = new openils.widget.AutoFieldWidget({
1763 "fmField": "cancel_reason",
1765 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
1766 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1771 acqLitCancelLineitemsButton.onClick = function() {
1772 if (w.attr("value")) {
1773 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
1774 self._cancelLineitems(w.attr("value"));
1776 openils.Util.hide("acq-lit-cancel-reason");
1779 acqLitCancelLineitemsButton._prepared = true;
1785 this._cancelLineitems = function(reason) {
1786 var id_list = this.getSelected().map(function(o) { return o.id(); });
1787 fieldmapper.standardRequest(
1788 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
1789 "params": [openils.User.authtoken, id_list, reason],
1791 "onresponse": function(r) {
1792 if (r = openils.Util.readResponse(r)) {
1794 for (var id in r.li) {
1795 self.liCache[id].state(r.li[id].state);
1796 self.liCache[id].cancel_reason(
1797 r.li[id].cancel_reason
1799 self.updateLiState(self.liCache[id]);
1802 if (r.lid && self.copyCache) {
1803 for (var id in r.lid) {
1804 if (self.copyCache[id]) {
1805 self.copyCache[id].cancel_reason(
1806 r.lid[id].cancel_reason
1808 self.updateLidState(self.copyCache[id]);
1818 this.chooseExportAttr = function() {
1819 if (!acqLitExportAttrSelector._li_setup) {
1821 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
1823 "data": acqliad.toStoreData(
1825 "acqliad", {"code": li_exportable_attrs}
1830 acqLitExportAttrSelector.setValue();
1831 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
1832 acqLitExportAttrSelector._li_setup = true;
1834 openils.Util.show("acq-lit-export-attr-holder", "inline");
1837 this.exportAttrList = function() {
1838 var attr_def = acqLitExportAttrSelector.item;
1839 var li_list = this.getSelected();
1840 var value_list = li_list.map(
1842 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1843 attr_def.code, "lineitem_marc_attr_definition"
1846 ).filter(function(attr) { return Boolean(attr); });
1848 if (value_list.length > 0) {
1849 if (value_list.length < li_list.length) {
1851 dojo.string.substitute(
1852 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
1859 openils.XUL.contentToFileSaveDialog(
1860 value_list.join("\n"),
1861 localeStrings.EXPORT_SAVE_DIALOG_TITLE
1867 alert(dojo.string.substitute(
1868 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
1872 openils.Util.hide("acq-lit-export-attr-holder");
1875 this.printPO = function() {
1876 if(!this.isPO) return;
1877 progressDialog.show(true);
1878 fieldmapper.standardRequest(
1879 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
1881 params: [this.authtoken, this.isPO, 'html'],
1882 oncomplete: function(r) {
1883 progressDialog.hide();
1884 var evt = openils.Util.readResponse(r);
1885 if(evt && evt.template_output()) {
1886 win = window.open('','', 'resizable,width=800,height=600,scrollbars=1');
1887 win.document.body.innerHTML = evt.template_output().data();
1895 this.receivePO = function() {
1896 if (!this.isPO) return;
1898 for (var id in this.liCache) {
1899 /* assumption: liCache reflects exactly the
1900 * set of LIs that belong to our PO */
1901 if (this.liCache[id].state() != "received" &&
1902 !this.checkLiAlerts(id)) return;
1905 this.show('acq-lit-progress-numbers');
1907 fieldmapper.standardRequest(
1908 ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
1910 params: [this.authtoken, this.isPO],
1911 onresponse : function(r) {
1912 var resp = openils.Util.readResponse(r);
1913 self._updateProgressNumbers(resp, true);
1919 this.issueReceive = function(obj, rollback) {
1920 /* (For now) there shall be no marking LI or LIDs (un)received
1921 * except from the actual "view PO" interface. */
1922 if (!this.isPO) return;
1925 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
1927 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
1929 progressDialog.show(true);
1930 fieldmapper.standardRequest(
1931 ["open-ils.acq", method], {
1933 "params": [this.authtoken, obj.id()],
1934 "onresponse": function(r) {
1935 self.handleReceive(openils.Util.readResponse(r));
1936 progressDialog.hide();
1943 * Handles the responses from receive and rollback ML calls.
1945 this.handleReceive = function(resp) {
1948 for (var li_id in resp.li) {
1949 for (var key in resp.li[li_id])
1950 self.liCache[li_id][key](resp.li[li_id][key]);
1951 self.updateLiState(self.liCache[li_id]);
1955 if (typeof(self.poUpdateCallback) == "function")
1956 self.poUpdateCallback(resp.po);
1959 for (var lid_id in resp.lid) {
1960 for (var key in resp.lid[lid_id])
1961 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
1962 self.updateLidState(self.copyCache[lid_id]);
1968 this.rollbackPoReceive = function() {
1969 if(!this.isPO) return;
1970 if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
1971 this.show('acq-lit-progress-numbers');
1973 fieldmapper.standardRequest(
1974 ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
1976 params: [this.authtoken, this.isPO],
1977 onresponse : function(r) {
1978 var resp = openils.Util.readResponse(r);
1979 self._updateProgressNumbers(resp, true);
1985 this._updateProgressNumbers = function(resp, reloadOnComplete) {
1987 dojo.byId('acq-pl-lit-li-processed').innerHTML = resp.li;
1988 dojo.byId('acq-pl-lit-lid-processed').innerHTML = resp.lid;
1989 dojo.byId('acq-pl-lit-debits-processed').innerHTML = resp.debits_accrued;
1990 dojo.byId('acq-pl-lit-bibs-processed').innerHTML = resp.bibs;
1991 dojo.byId('acq-pl-lit-indexed-processed').innerHTML = resp.indexed;
1992 dojo.byId('acq-pl-lit-copies-processed').innerHTML = resp.copies;
1993 if(resp.complete && reloadOnComplete)
1994 location.href = location.href;
1998 this._createPO = function(fields) {
1999 this.show('acq-lit-progress-numbers');
2000 var po = new fieldmapper.acqpo();
2001 po.provider(this.createPoProviderSelector.attr('value'));
2002 po.ordering_agency(this.createPoAgencySelector.attr('value'));
2003 po.prepayment_required(fields.prepayment_required[0] ? true : false);
2005 var selected = this.getSelected( (fields.create_from == 'all') );
2006 if(selected.length == 0) return;
2008 var max = selected.length * 3;
2011 fieldmapper.standardRequest(
2012 ['open-ils.acq', 'open-ils.acq.purchase_order.create'],
2015 openils.User.authtoken,
2018 lineitems : selected.map(function(li) { return li.id() }),
2019 create_assets : fields.create_assets[0],
2023 onresponse : function(r) {
2024 var resp = openils.Util.readResponse(r);
2025 self._updateProgressNumbers(resp);
2027 location.href = oilsBasePath + '/eg/acq/po/view/' + resp.purchase_order.id();
2033 this._deleteLiList = function(list, idx) {
2034 if(idx == null) idx = 0;
2035 if(idx >= list.length) return;
2036 var liId = list[idx].id();
2037 fieldmapper.standardRequest(
2038 ['open-ils.acq', 'open-ils.acq.lineitem.delete'],
2040 params: [openils.User.authtoken, liId],
2041 oncomplete: function(r) {
2042 self.removeLineitem(liId);
2043 self._deleteLiList(list, ++idx);
2049 this.editOrderMarc = function(li) {
2051 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
2052 to true in about:config */
2054 if(!openils.XUL.enableXPConnect()) return;
2056 if(openils.XUL.isXUL()) {
2057 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
2059 win = window.open('/xul/server/cat/marcedit.xul');
2063 record : {marc : li.marc()},
2065 label: 'Save Record', // XXX I18N
2066 func: function(xmlString) {
2068 fieldmapper.standardRequest(
2069 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
2071 params: [openils.User.authtoken, li],
2072 oncomplete: function(r) {
2073 openils.Util.readResponse(r);
2075 self.drawInfo(li.id())
2084 this._savePl = function(values) {
2086 var selected = this.getSelected( (values.which == 'all') );
2087 openils.Util.show('acq-lit-generic-progress');
2089 if(values.new_name) {
2090 openils.acq.Picklist.create(
2091 {name: values.new_name},
2093 self._updateLiList(id, selected, 0,
2095 location.href = oilsBasePath + '/eg/acq/picklist/view/' + id;
2099 } else if(values.existing_pl) {
2100 // update lineitems to use an existing picklist
2101 self._updateLiList(values.existing_pl, selected, 0,
2103 location.href = oilsBasePath + '/eg/acq/picklist/view/' + values.existing_pl;
2108 this._updateLiState = function(values, state) {
2110 var selected = this.getSelected( (values.which == 'all') );
2111 if(!selected.length) return;
2112 dojo.forEach(selected, function(li) {li.state(state);});
2113 self._updateLiList(null, selected, 0,
2114 // TODO consider inline updates for efficiency
2115 function() { location.href = location.href }
2119 this._updateLiList = function(pl, list, idx, oncomplete) {
2120 if(idx >= list.length) return oncomplete();
2122 if(pl != null) li.picklist(pl);
2123 litGenericProgress.update({maximum: list.length, progress: idx});
2124 new openils.acq.Lineitem({lineitem:li}).update(
2126 self._updateLiList(pl, list, ++idx, oncomplete);
2131 this._loadPLSelect = function() {
2132 if(this._plSelectLoaded) return;
2134 function handleResponse(r) {
2135 plList.push(r.recv().content());
2137 var method = 'open-ils.acq.picklist.user.retrieve';
2138 fieldmapper.standardRequest(
2139 ['open-ils.acq', method],
2141 params: [this.authtoken],
2142 onresponse: handleResponse,
2143 oncomplete: function() {
2144 self._plSelectLoaded = true;
2145 acqLitAddExistingSelect.store =
2146 new dojo.data.ItemFileReadStore({data:acqpl.toStoreData(plList)});
2147 acqLitAddExistingSelect.setValue();
2153 this.showRealCopyEditUI = function(li) {
2158 this._fetchLineitem(li.id(),
2160 li = self.liCache[li.id()] = fullLi;
2164 id : li.lineitem_details().map(
2165 function(item) { return item.eg_copy_id() }
2169 oncomplete : function(r) {
2171 var r_list = openils.Util.readResponse( r );
2172 for (var i = 0; i < r_list.length; i++) {
2173 var copy = r_list[i];
2174 var volId = copy.call_number();
2175 var volume = self.volCache[volId];
2177 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2179 copy.call_number(volume);
2180 copyList.push(copy);
2183 // If we need to, we can pass in an update_copy function to handle the update instead of volume_item_creator
2184 xulG.volume_item_creator( { 'existing_copies' : copyList } );
2187 alert('error in oncomplete: ' + E);
2198 this.saveRealCopies = function() {
2199 progressDialog.show(true);
2200 var list = this.realCopyList.filter(function(copy) { return copy.ischanged(); });
2201 this.pcrud.update(list, {oncomplete: function() {
2202 progressDialog.hide();
2207 // grab the li-details for this lineitem, grab the linked copies and volumes, add them to the table
2208 this.showRealCopies = function(li) {
2209 while(this.realCopiesTbody.childNodes[0])
2210 this.realCopiesTbody.removeChild(this.realCopiesTbody.childNodes[0]);
2211 this.show('real-copies');
2213 this.realCopyList = [];
2215 var tabIndex = 1000;
2218 acqLitSaveRealCopies.onClick = function() {
2219 self.saveRealCopies();
2222 this._fetchLineitem(li.id(),
2224 li = self.liCache[li.id()] = fullLi;
2228 id : li.lineitem_details().map(
2229 function(item) { return item.eg_copy_id() }
2234 onresponse : function(r) {
2235 var copy = openils.Util.readResponse(r);
2236 var volId = copy.call_number();
2237 var volume = self.volCache[volId];
2239 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2241 self.addRealCopy(volume, copy, tabIndex++);
2249 this.addRealCopy = function(volume, copy, tabIndex) {
2250 var row = this.realCopiesRow.cloneNode(true);
2251 this.realCopyList.push(copy);
2255 ['owning_lib', 'location', 'circ_modifier', 'label', 'barcode'],
2258 var isvol = (field == 'owning_lib' || field == 'label');
2259 var widget = new openils.widget.AutoFieldWidget({
2261 fmObject : isvol ? volume : copy,
2262 parentNode : nodeByName(field, row),
2263 readOnly : (field != 'barcode'),
2266 var widgetDrawn = null;
2268 if(field == 'barcode') {
2270 widgetDrawn = function(w, ww) {
2271 var node = w.domNode;
2272 node.setAttribute('tabindex', ''+tabIndex);
2274 // on enter, select the next barcode input
2275 dojo.connect(w, 'onKeyDown',
2277 if(e.keyCode == dojo.keys.ENTER) {
2278 var ti = node.getAttribute('tabindex');
2279 var nextNode = dojo.query('[tabindex=' + String(Number(ti) + 1) + ']', self.realCopiesTbody)[0];
2280 if(nextNode) nextNode.select();
2285 dojo.connect(w, 'onChange',
2287 if(!val || val == copy.barcode()) return;
2288 copy.ischanged(true);
2294 if(self.realCopiesTbody.getElementsByTagName('TR').length == 0)
2299 widget.build(widgetDrawn);
2303 this.realCopiesTbody.appendChild(row);
2304 if(selectNode) selectNode.select();