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 oilsBasePath + "/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 if (li.claim_policy()) {
224 var actViewInvoice = nodeByName("action_view_claim_policy", row);
225 actViewInvoice.disabled = false;
226 actViewInvoice.onclick = function() {
227 location.href = oilsBasePath + "/conify/global/acq/claim_policy/" +
232 // show which PO this lineitem is a member of
233 if(li.purchase_order() && !this.isPO) {
235 this.poCache[li.purchase_order()] =
236 this.poCache[li.purchase_order()] ||
237 fieldmapper.standardRequest(
238 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
240 this.authtoken, li.purchase_order(), {
241 "flesh_price_summary": true,
242 "flesh_lineitem_count": true
245 if(po && !this.isMeta) {
246 openils.Util.show(nodeByName('po', row), 'inline');
247 var link = nodeByName('po_link', row);
248 link.setAttribute('href', oilsBasePath + '/acq/po/view/' + li.purchase_order());
249 link.innerHTML = 'PO: ' + po.name(); // TODO i18n
253 // show which picklist this lineitem is a member of
254 if(li.picklist() && (this.isPO || this.isMeta)) {
256 this.plCache[li.picklist()] =
257 this.plCache[li.picklist()] ||
258 fieldmapper.standardRequest(
259 ['open-ils.acq', 'open-ils.acq.picklist.retrieve'],
260 {params: [this.authtoken, li.picklist()]});
262 openils.Util.show(nodeByName('pl', row), 'inline');
263 var link = nodeByName('pl_link', row);
264 link.setAttribute('href', oilsBasePath + '/acq/picklist/view/' + li.picklist());
265 link.innerHTML = 'PL: '+pl.name(); // TODO i18n
269 var countNode = nodeByName('count', row);
270 var count = li.item_count() || 0;
271 if (typeof(this._copy_count_cb) == "function") {
272 this._copy_count_cb(li.id(), count);
274 countNode.innerHTML = count;
275 countNode.id = 'acq-lit-copy-count-label-' + li.id();
278 var priceInput = dojo.query('[name=price]', row)[0];
279 priceInput.value = li.estimated_unit_price() || '';
280 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
282 // show either "mark received" or "unreceive" as appropriate
283 this.updateLiState(li, row);
285 if (!skip_final_placement) {
286 self.tbody.appendChild(row);
287 self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
293 this.updateLiNotesCount = function(li, row) {
294 if (typeof(row) == "undefined")
295 row = dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
297 var has_notes = (li.lineitem_notes().filter(
298 function(o) { return Boolean (o.alert_text()); }
301 /* U+2691 is the code point for a filled-in flag character */
302 nodeByName("notes_alert_flag", row).innerHTML =
303 has_notes ? "⚑" : "";
304 nodeByName("noteslink", row).style.fontStyle =
305 has_notes ? "italic" : "normal";
306 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
309 /* XXX NOT related to _updateLiState(). rethink */
310 this.updateLiState = function(li, row) {
311 if (typeof(row) == "undefined")
312 row = dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
314 var actReceive = nodeByName("action_mark_recv", row);
315 var actUnRecv = nodeByName("action_mark_unrecv", row);
316 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
317 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
319 var actNewInvoice = nodeByName('action_new_invoice', row);
320 var actLinkInvoice = nodeByName('action_link_invoice', row);
321 var actViewInvoice = nodeByName('action_view_invoice', row);
323 var state_cell = nodeByName("li_state", row);
325 if (li.state() == "cancelled") {
326 if (typeof li.cancel_reason() == "object") {
327 var holds_state = dojo.create(
329 "style": "border-bottom: 1px dashed #000;",
330 "innerHTML": li.state()
331 }, state_cell, "only"
335 "label": "<em>" + li.cancel_reason().label() +
336 "</em><br />" + li.cancel_reason().description(),
337 "connectId": [holds_state]
338 }, dojo.create("span", null, state_cell, "last")
341 state_cell.innerHTML = li.state(); // TODO i18n state labels
344 state_cell.innerHTML = li.state(); // TODO i18n state labels
348 /* handle row coloring for based on LI state */
349 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
350 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
352 /* handle links that appear/disappear based on whether LI is received */
357 actReceive.disabled = false;
358 actReceive.onclick = function() {
359 if (self.checkLiAlerts(li.id()))
360 self.issueReceive(li);
361 nodeByName("action_none", row).selected = true;
365 actUnRecv.disabled = false;
366 actUnRecv.onclick = function() {
367 if (confirm(localeStrings.UNRECEIVE_LI))
368 self.issueReceive(li, /* rollback */ true);
369 nodeByName("action_none", row).selected = true;
371 // TODO we should allow editing before receipt, in which case the
372 // test should be "if 1 or more real (acp) copies exist
373 actUpdateBarcodes.disabled = false;
374 actUpdateBarcodes.onclick = function() {
375 self.showRealCopyEditUI(li);
376 nodeByName("action_none", row).selected = true;
378 actHoldingsMaint.disabled = false;
379 actHoldingsMaint.onclick = self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
381 actNewInvoice.disabled = false;
382 actLinkInvoice.disabled = false;
383 actViewInvoice.disabled = false;
385 actNewInvoice.onclick = function() {
386 location.href = oilsBasePath + '/acq/invoice/view?create=1&attach_li=' + li.id();
387 nodeByName("action_none", row).selected = true;
389 actLinkInvoice.onclick = function() {
390 self.invoiceLinkDialogManager.target = li;
391 acqLitLinkInvoiceDialog.show();
392 nodeByName("action_none", row).selected = true;
394 actViewInvoice.onclick = function() {
395 location.href = oilsBasePath +
396 "/acq/search/unified?so=" +
397 base64Encode({"jub":[{"id": li.id()}]}) +
399 nodeByName("action_none", row).selected = true;
408 this._setAlertStore = function() {
409 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
411 "data": acqliat.toStoreData(
413 "acqliat", {"id": {"!=": null}}
418 acqLitAlertAlertText.setValue(); /* make the store "live" */
419 acqLitAlertAlertText._store_ready = true;
423 * Draws and shows the lineitem notes pane
425 this.drawLiNotes = function(li) {
428 if (!acqLitAlertAlertText._store_ready)
429 this._setAlertStore();
432 li.lineitem_notes().sort(
434 if(a.edit_time() < b.edit_time()) return 1;
440 while(this.liNotesTbody.childNodes[0])
441 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
444 acqLitCreateNoteSubmit.onClick = function() {
445 var value = acqLitCreateNoteText.attr('value');
447 var note = new fieldmapper.acqlin();
450 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
453 note.lineitem(li.id());
455 self.updateLiNotes(li, note);
456 acqLitCreateNoteVendorPublic.attr("checked", false);
457 acqLitCreateNoteText.attr("value", "");
460 acqLitCreateAlertSubmit.onClick = function() {
461 if (!acqLitAlertAlertText.item) {
462 alert(localeStrings.ALERT_UNSELECTED);
466 var alert_text = new fieldmapper.acqliat().fromStoreItem(
467 acqLitAlertAlertText.item
469 var value = acqLitAlertNoteValue.attr("value") || "";
471 var note = new fieldmapper.acqlin();
473 note.lineitem(li.id());
475 note.alert_text(alert_text);
477 self.updateLiNotes(li, note);
480 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
484 * Draws a single lineitem note in the notes pane
486 this.addLiNote = function(li, note) {
487 if(note.isdeleted()) return;
489 var row = self.liNotesRow.cloneNode(true);
490 nodeByName("value", row).innerHTML = note.value();
491 var alert_node = nodeByName("alert_code", row);
492 if (note.alert_text()) {
493 alert_node.innerHTML = note.alert_text().code();
494 if (note.alert_text().description()) {
497 "connectId": [alert_node],
498 "label": note.alert_text().description()
499 }, dojo.create("span", null, alert_node, "after")
504 if (openils.Util.isTrue(note.vendor_public()))
505 nodeByName("vendor_public", row).innerHTML =
506 localeStrings.VENDOR_PUBLIC;
508 nodeByName("delete", row).onclick = function() {
509 note.isdeleted(true);
510 self.liNotesTbody.removeChild(row);
511 self.updateLiNotes(li);
514 if(note.edit_time()) {
515 nodeByName("edit_time", row).innerHTML =
516 dojo.date.locale.format(
517 dojo.date.stamp.fromISOString(note.edit_time()),
518 {formatLength:'short'});
521 self.liNotesTbody.appendChild(row);
525 * Updates any new/changed/deleted notes on the server
527 this.updateLiNotes = function(li, newNote) {
533 notes = li.lineitem_notes().filter(
535 if(note.ischanged() || note.isnew() || note.isdeleted())
541 if(notes.length == 0) return;
542 progressDialog.show();
544 fieldmapper.standardRequest(
545 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
547 params : [this.authtoken, notes],
548 onresponse : function(r) {
549 var resp = openils.Util.readResponse(r);
554 // remove the old changed notes
556 dojo.forEach(li.lineitem_notes(),
558 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
562 li.lineitem_notes(list);
565 progressDialog.hide();
566 self.updateLiNotesCount(li);
567 self.drawLiNotes(li);
571 progressDialog.update(resp);
572 var newnote = resp.note;
574 if(!newnote.isdeleted()) {
575 newnote.isnew(false);
576 newnote.ischanged(false);
577 li.lineitem_notes().push(newnote);
584 this.updateLiPrice = function(input, li) {
586 var price = input.value;
587 if(Number(price) == Number(li.estimated_unit_price())) return;
589 fieldmapper.standardRequest(
590 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
592 params : [this.authtoken, li.id(), price],
593 oncomplete : function(r) {
594 openils.Util.readResponse(r);
595 li.estimated_unit_price(price); // update local copy
601 this.removeLineitem = function(liId) {
602 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
603 delete this.liCache[liId];
604 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
607 this.drawInfo = function(liId) {
608 if (!this._isRelatedViewer) {
609 var d = dojo.byId("acq-lit-info-related");
610 if (!this.relCache[liId]) {
611 fieldmapper.standardRequest(
614 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
617 "params": [openils.User.authtoken, liId],
618 "onresponse": function(r) {
619 self.relCache[liId] = openils.Util.readResponse(r);
620 nodeByName("related_number", d).innerHTML =
623 self.relCache[liId] >1 ? "show" : "hide"
629 nodeByName("related_number", d).innerHTML = this.relCache[liId];
630 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
635 openils.acq.Lineitem.fetchAttrDefs(
637 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
642 this._fetchLineitem = function(liId, handler) {
644 var li = this.liCache[liId];
645 if(li && li.marc() && li.lineitem_details())
648 fieldmapper.standardRequest(
649 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve'],
652 params: [self.authtoken, liId, {
654 flesh_cancel_reason: true,
655 flesh_li_details: true,
656 flesh_fund_debit: true }],
658 oncomplete: function(r) {
659 var li = openils.Util.readResponse(r);
666 this._drawInfo = function(li) {
668 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
671 openils.Util.hide('acq-lit-marc-order-record-label');
672 openils.Util.hide(acqLitEditOrderMarc.domNode);
673 openils.Util.show('acq-lit-marc-real-record-label');
675 openils.Util.show('acq-lit-marc-order-record-label');
676 openils.Util.show(acqLitEditOrderMarc.domNode);
677 openils.Util.hide('acq-lit-marc-real-record-label');
680 this.drawMarcHTML(li);
681 this.infoTbody = dojo.byId('acq-lit-info-tbody');
684 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
685 while(this.infoTbody.childNodes[0])
686 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
688 for(var i = 0; i < li.attributes().length; i++) {
689 var attr = li.attributes()[i];
690 var row = this.infoRow.cloneNode(true);
692 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
693 var name = openils.acq.Lineitem.attrDefs[type].filter(
695 return (a.code() == attr.attr_name());
697 ).pop().description();
699 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
700 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
701 this.infoTbody.appendChild(row);
704 if (!this._isRelatedViewer) {
705 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
706 oilsBasePath + "/acq/lineitem/related/" + li.id();
711 openils.Util.show('acq-lit-info-cat-link');
712 var link = dojo.byId('acq-lit-info-cat-link').getElementsByTagName('a')[0];
714 if(openils.XUL.isXUL()) {
716 link.setAttribute('href', 'javascript:void(0);');
717 link.onclick = this.generateMakeRecTab( li.eg_bib_id() );
720 var href = link.getAttribute('href');
722 link.setAttribute('href', href + li.eg_bib_id());
725 openils.Util.hide('acq-lit-info-cat-link');
729 this.generateMakeRecTab = function(bib_id,default_view, row) {
733 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
736 show_nav_buttons : true,
737 show_print_button : true,
738 opac_url : xulG.url_prefix(xulG.urls.opac_rdetail + '?r=' + bib_id),
739 default_view : default_view
743 if(row) nodeByName("action_none", row).selected = true;
747 this.drawMarcHTML = function(li) {
748 var params = [null, true, li.marc()];
750 params = [li.eg_bib_id(), true];
752 fieldmapper.standardRequest(
753 ['open-ils.search', 'open-ils.search.biblio.record.html'],
756 oncomplete: function(r) {
757 dojo.byId('acq-lit-marc-div').innerHTML =
758 openils.Util.readResponse(r);
764 this.drawCopies = function(liId) {
768 this.copyWidgetCache = {};
769 this.oldCopyWidgetCache = {};
770 this.virtDfaCounts = {};
771 this.realDfaCache = {};
774 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
775 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
776 acqLitCopyCountInput.attr('value', '0');
778 while(this.copyTbody.childNodes[0])
779 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
781 this._drawBatchCopyWidgets();
783 this._drawDistribApplied(liId);
785 this._fetchDistribFormulas(
787 openils.acq.Lineitem.fetchAttrDefs(
789 self._fetchLineitem(liId, function(li){self._drawCopies(li);});
796 this._saveDistribAppliedTemplates = function() {
797 if (!this._appliedDistribTemplate) {
798 this._appliedDistribTemplate =
799 dojo.byId("acq-lit-distrib-applied-tbody").
800 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
801 dojo.attr(this._appliedDistribTemplate, "id");
805 this._drawDistribApplied = function(liId) {
806 /* Build this table while hidden to prevent rendering artifacts */
807 openils.Util.hide("acq-lit-distrib-applied-tbody");
809 this._saveDistribAppliedTemplates();
811 /* Remove any rows in the table from previous populations */
812 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
813 forEach(dojo.destroy);
815 /* Unregister all dijits previously created (for some reason this isn't
816 * covered by the above destroy calls). */
817 dijit.registry.forEach(
818 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
821 /* Populate the table with our liId */
823 fieldmapper.standardRequest(
825 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
828 "params": [self.authtoken, liId],
829 "onresponse": function(r) {
830 var dfa = openils.Util.readResponse(r);
833 self.realDfaCache[dfa.id()] = dfa;
834 self._drawDistribAppliedUnit(dfa);
837 "oncomplete": function() {
838 /* Reveal built table */
841 "acq-lit-distrib-applied-tbody", "table-row-group"
849 this._drawDistribAppliedUnit = function(dfa) {
851 var row = dojo.query(
852 'tr[formula="' + dfa.formula().id() + '"]',
853 "acq-lit-distrib-applied-tbody"
858 row = dojo.clone(this._appliedDistribTemplate);
859 dojo.attr(row, "formula", dfa.formula().id());
860 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
863 var td = dojo.query("td", row)[0];
865 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
866 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
869 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
871 new dijit.form.Button(
873 "onClick": function() {
874 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
878 /* XXX I /cannot/ make the following work in as a CSS class
879 * for some reason. So frustrating... */
880 "style": function(id) {
882 "font-weight: bold; color: #c00;" :
884 }(dfa.id()) + "margin: 0 6px;display: inline;"
885 }, "dfa-button-" + dfa.id()
889 "connectId": ["dfa-button-" + dfa.id()],
890 "label": dojo.string.substitute(
891 localeStrings.DFA_TIP, dfa.id() > 0 ? [
892 openils.User.formalName(dfa.creator()),
893 dojo.date.locale.format(
894 dojo.date.stamp.fromISOString(dfa.create_time()),
895 {"formatLength":"short"}
897 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
899 }, "dfa-tip-" + dfa.id()
903 this.deleteDfa = function(dfa) {
904 if (dfa.id() > 0) { /* real */
905 this.pcrud.eliminate(
908 "oncomplete": function() {
909 self._removeDistribApplied(dfa.id());
910 delete self.realDfaCache[dfa.id()];
914 } else { /* virtual */
915 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
916 this.virtDfaCounts[dfa.formula().id()] = 0;
917 /* hasn't been saved yet, so no need to do anything server side */
918 this._removeDistribApplied(dfa.id());
923 this._removeDistribApplied = function(dfaId) {
924 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
925 dijit.registry.forEach(
926 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
928 this._removeDistribAppliedEmptyRows();
931 this._removeAllDistribAppliedVirtual = function() {
932 /* Unregister dijits */
933 dijit.registry.forEach(
934 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
936 this._removeDistribAppliedEmptyRows();
939 this._removeDistribAppliedEmptyRows = function() {
940 /* Remove any rows with no DFA at all */
941 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
943 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
949 * Insert a new row into the distribution formula selection form
951 this._addDistribFormulaRow = function() {
954 if (!self.distribForms) {
955 // no formulas, hide the form
956 openils.Util.hide('acq-lit-distrib-formula-tbody');
960 if(!this.distribFormulaTemplate)
961 this.distribFormulaTemplate =
962 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
964 var row = this.distribFormulaTemplate.cloneNode(true);
965 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
967 this.dfSelector = new dijit.form.FilteringSelect(
968 {"labelAttr": "dynLabel", "labelType": "html"},
969 nodeByName("selector", row)
971 this._updateFormulaStore();
972 this.dfSelector.fetchProperties =
973 {"sort": [{"attribute": "use_count", "descending": true}]};
975 var apply = new dijit.form.Button(
976 {"label": localeStrings.APPLY},
977 nodeByName('set_button', row)
980 var reset = new dijit.form.Button(
981 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
982 nodeByName("reset_button", row)
985 dojo.connect(apply, 'onClick',
987 var form_id = self.dfSelector.attr("value");
989 self._applyDistribFormula(form_id);
990 reset.attr("disabled", false);
994 dojo.connect(reset, 'onClick',
996 self.restoreCopyFieldsBeforeDF();
997 self.virtDfaCounts = {};
1000 self._updateFormulaStore();
1001 self._removeAllDistribAppliedVirtual();
1002 reset.attr("disabled", "true");
1009 * Applies a distrib formula to the current set of copies
1011 this._applyDistribFormula = function(formula) {
1012 if(!formula) return;
1014 formula = this.distribForms.filter(
1015 function(form) { return form.id() == formula; }
1018 var copyRows = dojo.query('tr', self.copyTbody);
1020 if (this.dfeOffset >= copyRows.length) {
1021 alert(localeStrings.OUT_OF_COPIES);
1025 var entries_applied = 0;
1027 var rowIndex = this.dfeOffset;
1028 rowIndex < copyRows.length;
1032 var row = copyRows[rowIndex];
1033 var copy_id = row.getAttribute('copy_id');
1034 var copyWidgets = this.copyWidgetCache[copy_id];
1035 var entryIndex = this.dfeOffset;
1038 // find the correct entry for the current row
1039 dojo.forEach(formula.entries(),
1042 entryIndex += e.item_count();
1043 if(entryIndex > rowIndex)
1051 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
1052 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
1055 this.saveCopyFieldsBeforeDF(copy_id);
1056 this._copy_fields_for_acqdf.forEach(
1058 if(entry[field]()) {
1059 copyWidgets[field].attr('value', (entry[field]()));
1066 if (entries_applied) {
1067 this.virtDfaCounts[formula.id()] =
1068 ++(this.virtDfaCounts[formula.id()]) || 1;
1069 this._updateFormulaStore();
1070 this._drawDistribAppliedUnit(
1072 var dfa = new acqdfa();
1073 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
1076 this.dfeOffset += entries_applied;
1081 * This function updates the DF store for the dropdown so that use_counts
1082 * can reflect DF applications from this session before they're saved
1085 this._updateFormulaStore = function() {
1086 this.dfSelector.store = new dojo.data.ItemFileReadStore(
1088 "data": self._labelFormulasWithCounts(
1089 acqdf.toStoreData(self.distribForms)
1095 this.saveCopyFieldsBeforeDF = function(copy_id) {
1097 if (!this.oldCopyWidgetCache[copy_id]) {
1098 var copyWidgets = this.copyWidgetCache[copy_id];
1100 this.oldCopyWidgetCache[copy_id] = {};
1101 this._copy_fields_for_acqdf.forEach(
1103 self.oldCopyWidgetCache[copy_id][f] =
1104 copyWidgets[f].attr("value");
1110 this.restoreCopyFieldsBeforeDF = function() {
1112 for (var copy_id in this.oldCopyWidgetCache) {
1113 this._copy_fields_for_acqdf.forEach(
1115 self.copyWidgetCache[copy_id][f].attr(
1116 "value", self.oldCopyWidgetCache[copy_id][f]
1123 this._labelFormulasWithCounts = function(store_data) {
1124 for (var key in store_data.items) {
1125 var obj = store_data.items[key];
1126 obj.use_count = Number(obj.use_count); /* needed for sorting */
1128 if (this.virtDfaCounts[obj.id])
1129 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
1131 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
1132 obj.use_count + "]</span> " + obj.name;
1138 * This method formerly would not refetch the DF formulas if they'd been
1139 * loaded already, but now it always re-fetches, since use_count changes.
1141 this._fetchDistribFormulas = function(onload) {
1142 fieldmapper.standardRequest(
1144 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
1147 "params": [openils.User.authtoken],
1148 "oncomplete": function(r) {
1149 self.distribForms = openils.Util.readResponse(r);
1150 if(!self.distribForms || self.distribForms.length == 0) {
1151 self.distribForms = [];
1153 self._addDistribFormulaRow();
1160 this._drawBatchCopyWidgets = function() {
1161 var row = this.copyBatchRow;
1162 dojo.forEach(liDetailBatchFields,
1164 if(self.copyBatchRowDrawn) {
1165 self.copyBatchWidgets[field].attr('value', null);
1167 var widget = new openils.widget.AutoFieldWidget({
1170 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1171 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1172 searchFilter : (field == 'fund') ? {"active": "t"} : null,
1173 parentNode : dojo.query('[name='+field+']', row)[0],
1174 orgLimitPerms : ['CREATE_PICKLIST'],
1177 "labelType": (field == "fund") ? "html" : null
1179 noCache: (field == "fund"),
1184 if (field == "fund" && w.store)
1185 self._ensureCSSFundClasses(w.store);
1186 self.copyBatchWidgets[field] = w;
1189 if (field == "fund") {
1191 widget.widget, "onChange", function(val) {
1192 self._updateFundSelectorStyle(widget, val);
1199 this.copyBatchRowDrawn = true;
1202 this.batchCopyUpdate = function() {
1204 for(var k in this.copyWidgetCache) {
1205 var cache = this.copyWidgetCache[k];
1206 dojo.forEach(liDetailBatchFields, function(f) {
1207 var newval = self.copyBatchWidgets[f].attr('value');
1208 if(newval) cache[f].attr('value', newval);
1213 this._drawCopies = function(li) {
1216 // this button sets the total number of copies for a given lineitem
1217 acqLitAddCopyCount.onClick = function() {
1218 var count = acqLitCopyCountInput.attr('value');
1221 while(self.copyCount() < count)
1224 // delete rows if necessary
1225 var diff = self.copyCount() - count;
1227 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
1228 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
1229 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
1231 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1237 if(li.lineitem_details().length > 0) {
1238 dojo.forEach(li.lineitem_details(),
1240 self.addCopy(li, copy);
1248 this.copyCount = function() {
1250 for(var id in this.copyCache) {
1251 if(!this.copyCache[id].isdeleted())
1257 this.virtCopyId = -1;
1258 this.addCopy = function(li, copy) {
1259 var row = this.copyRow.cloneNode(true);
1260 this.copyTbody.appendChild(row);
1264 copy = new fieldmapper.acqlid();
1266 copy.id(this.virtCopyId--);
1267 copy.lineitem(li.id());
1270 this.copyCache[copy.id()] = copy;
1271 row.setAttribute('copy_id', copy.id());
1272 self.copyWidgetCache[copy.id()] = {};
1274 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1276 dojo.forEach(liDetailFields,
1279 if (field == "fund") {
1280 searchFilter = (copy.fund() ?
1281 {"-or": {"active": "t", "id": copy.fund()}} :
1284 searchFilter = null;
1286 var widget = new openils.widget.AutoFieldWidget({
1289 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1290 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1291 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1292 searchFilter : searchFilter,
1293 noCache: (field == "fund"),
1295 parentNode : dojo.query('[name='+field+']', row)[0],
1296 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
1297 readOnly : Boolean(copy.eg_copy_id())
1300 // make sure we capture the value from any async widgets
1302 if (field == "fund" && w.store)
1303 self._ensureCSSFundClasses(w.store);
1304 copy[field](ww.getFormattedValue())
1305 self.copyWidgetCache[copy.id()][field] = w;
1308 dojo.connect(widget.widget, 'onChange',
1310 if (field == "fund")
1311 self._updateFundSelectorStyle(widget, val);
1313 if (copy.isnew() || val != copy[field]()) {
1314 // prevent setting ischanged() automatically on widget load for existing copies
1315 copy[field](widget.getFormattedValue())
1316 copy.ischanged(true);
1323 this.updateLidState(copy, row);
1326 this._ensureCSSFundClass = function(id) {
1327 if (!this.fundStyleSheet) {
1329 "style", {"type": "text/css"},
1330 document.getElementsByTagName("head")[0], "last"
1332 this.fundStyleSheet = document.styleSheets[
1333 document.styleSheets.length - 1
1337 var cn = "fund_" + id;
1338 if (!this.haveFundClass[cn]) {
1339 fieldmapper.standardRequest(
1340 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
1342 "params": [openils.User.authtoken, id],
1344 "oncomplete": function(r) {
1345 r = openils.Util.readResponse(r);
1346 self.fundBalanceState[id] = r;
1348 if (r[0] /* stop */)
1349 style = fundStyles.stop;
1350 else if (r[1] /* warning */)
1351 style = fundStyles.warning;
1352 self.fundStyleSheet.insertRule(
1353 "." + cn + " { " + style + " }",
1354 self.fundStyleSheet.cssRules.length
1356 self.haveFundClass[cn] = true;
1363 this._ensureCSSFundClasses = function(store) {
1365 "query": {"id": "*"},
1366 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
1370 this._updateFundSelectorStyle = function(widget, fund_id) {
1371 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
1372 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
1375 this.updateLidState = function(copy, row) {
1376 if (typeof(row) == "undefined") {
1378 'tr[copy_id="' + copy.id() + '"]', this.copyTbody
1383 var recv_link = nodeByName("receive", row);
1384 var unrecv_link = nodeByName("unreceive", row);
1385 var del_link = nodeByName("delete", row);
1386 var cxl_link = nodeByName("cancel", row);
1387 var cxl_reason_link = nodeByName("cancel_reason", row);
1389 if (copy.cancel_reason()) {
1390 openils.Util.hide(del_link.parentNode);
1391 openils.Util.hide(recv_link);
1392 openils.Util.hide(unrecv_link);
1393 openils.Util.hide(cxl_link);
1395 /* XXX the following may leak memory in a long lived table: dijits may not get destroyed... not positive. revisit. */
1396 var holds_reason = dojo.create(
1398 "style": "border-bottom: 1px dashed #000;",
1399 "innerHTML": "Cancelled" /* XXX [sic] and i18n */
1400 }, cxl_reason_link, "only"
1404 "label": "<em>" + copy.cancel_reason().label() +
1405 "</em><br />" + copy.cancel_reason().description(),
1406 "connectId": [holds_reason]
1407 }, dojo.create("span", null, cxl_reason_link, "last")
1409 openils.Util.show(cxl_reason_link, "inline");
1410 } else if (this.isPO) {
1411 openils.Util.hide(del_link.parentNode);
1412 openils.Util.hide(cxl_reason_link);
1414 /* Avoid showing (un)receive links, cancel links, for virt copies */
1415 if (copy.id() > 0) {
1416 if(copy.recv_time()) {
1417 openils.Util.hide(cxl_link);
1418 openils.Util.hide(recv_link);
1419 openils.Util.show(unrecv_link, "inline");
1420 unrecv_link.onclick = function() {
1421 if (confirm(localeStrings.UNRECEIVE_LID))
1422 self.issueReceive(copy, /* rollback */ true);
1425 openils.Util.hide(unrecv_link);
1426 openils.Util.show(recv_link, "inline");
1427 openils.Util.show(cxl_link, "inline");
1428 recv_link.onclick = function() {
1429 if (self.checkLiAlerts(copy.lineitem()))
1430 self.issueReceive(copy);
1432 cxl_link.onclick = function() {
1433 self.cancelLid(copy.id());
1437 openils.Util.hide(cxl_link);
1438 openils.Util.hide(unrecv_link);
1439 openils.Util.hide(recv_link);
1442 openils.Util.hide(unrecv_link);
1443 openils.Util.hide(recv_link);
1444 openils.Util.hide(cxl_reason_link);
1446 del_link.onclick = function() { self.deleteCopy(row) };
1447 openils.Util.show(del_link.parentNode);
1451 this.cancelLid = function(lid_id) {
1452 lidCancelDialog._lid_id = lid_id;
1453 openils.Util.show(lidCancelDialog.domNode.parentNode);
1454 lidCancelDialog.show();
1455 if (!lidCancelDialog._prepared) {
1456 var widget = new openils.widget.AutoFieldWidget({
1457 "fmField": "cancel_reason",
1458 "fmClass": "acqlid",
1459 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
1460 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1465 acqLidCancelButton.onClick = function() {
1466 if (w.attr("value")) {
1467 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
1469 lidCancelDialog._lid_id,
1473 lidCancelDialog.hide();
1476 lidCancelDialog._prepared = true;
1482 this._cancelLid = function(lid_id, reason) {
1483 fieldmapper.standardRequest(
1484 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
1485 "params": [openils.User.authtoken, lid_id, reason],
1487 "onresponse": function(r) {
1488 if (r = openils.Util.readResponse(r)) {
1490 for (var id in r.lid) {
1491 /* actually this should only iterate once */
1492 self.copyCache[id].cancel_reason(
1493 r.lid[id].cancel_reason
1495 self.updateLidState(self.copyCache[id]);
1504 this._confirmAlert = function(li, lin) {
1506 dojo.string.substitute(
1507 localeStrings.CONFIRM_LI_ALERT, [
1508 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1509 "title", "lineitem_marc_attr_definition"
1511 lin.alert_text().code(),
1512 lin.alert_text().description() || "",
1519 this.checkLiAlerts = function(li_id) {
1520 var li = this.liCache[li_id];
1522 var alert_notes = li.lineitem_notes().filter(
1523 function(o) { return Boolean(o.alert_text()); }
1526 /* this is _intentionally_ not done in a call to forEach() ... */
1527 for (var i = 0; i < alert_notes.length; i++) {
1528 if (this.noteAcks[alert_notes[i].id()])
1530 else if (!this._confirmAlert(li, alert_notes[i]))
1533 this.noteAcks[alert_notes[i].id()] = true;
1539 this.deleteCopy = function(row) {
1540 var copy = this.copyCache[row.getAttribute('copy_id')];
1541 copy.isdeleted(true);
1543 delete this.copyCache[copy.id()];
1544 this.copyTbody.removeChild(row);
1547 this._virtDfaCountsAsList = function() {
1549 for (var key in this.virtDfaCounts) {
1550 for (var i = 0; i < this.virtDfaCounts[key]; i++)
1556 this.confirmBreachedCopyFunds = function(copies) {
1557 var stop = 0, warning = 0;
1561 var state = self.fundBalanceState[o.fund()];
1562 if (state[0] /* stop */)
1564 else if (state[1] /* warning */)
1571 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
1572 } else if (warning) {
1573 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
1578 this.saveCopyChanges = function(liId) {
1584 for(var id in this.copyCache) {
1585 var c = this.copyCache[id];
1586 if(!c.isdeleted()) total++;
1587 if(c.isnew() || c.ischanged() || c.isdeleted()) {
1588 if(c.id() < 0) c.id(null);
1594 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
1597 if (copies.length > 0) {
1598 if (!this.confirmBreachedCopyFunds(copies))
1601 if (typeof(this._copy_count_cb) == "function")
1602 this._copy_count_cb(liId, total);
1604 openils.Util.show("acq-lit-update-copies-progress");
1605 fieldmapper.standardRequest(
1606 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1608 params: [openils.User.authtoken, copies],
1609 onresponse: function(r) {
1610 var res = openils.Util.readResponse(r);
1611 litUpdateCopiesProgress.update(res);
1613 oncomplete: function() {
1614 self.drawCopies(liId);
1615 openils.Util.hide("acq-lit-update-copies-progress");
1621 var dfa_list = this._virtDfaCountsAsList();
1622 if (dfa_list.length > 0) {
1623 fieldmapper.standardRequest(
1625 "open-ils.acq.distribution_formula.record_application"],
1628 "params": [openils.User.authtoken, dfa_list, liId],
1629 "onresponse": function(r) {
1630 var res = openils.Util.readResponse(r);
1631 if (res && res.length < dfa_list.length)
1632 alert(localeStrings.DFA_NOT_ALL);
1636 this.virtDfaCounts = {};
1640 this._updateCreatePoPrepayCheckbox = function(prepay) {
1641 var prepay = openils.Util.isTrue(prepay);
1642 this._prepayRequiredByVendor = prepay;
1643 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
1646 this._confirmPoPrepaySituation = function() {
1647 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
1648 if (want_prepay != this._prepayRequiredByVendor) {
1651 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
1652 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
1659 this.applySelectedLiAction = function(action) {
1663 case 'delete_selected':
1664 this._deleteLiList(self.getSelected());
1667 case 'create_order':
1669 if(!this.createPoProviderSelector) {
1670 var widget = new openils.widget.AutoFieldWidget({
1671 fmField : 'provider',
1673 searchFilter: {"active": "t"},
1674 parentNode : dojo.byId('acq-lit-po-provider'),
1676 "onChange": function() {
1678 self._updateCreatePoPrepayCheckbox(
1679 this.item.prepayment_required
1686 function(w) { self.createPoProviderSelector = w; }
1690 if(!this.createPoAgencySelector) {
1691 var widget = new openils.widget.AutoFieldWidget({
1692 fmField : 'ordering_agency',
1694 parentNode : dojo.byId('acq-lit-po-agency'),
1695 orgLimitPerms : ['CREATE_PURCHASE_ORDER'],
1698 function(w) { self.createPoAgencySelector = w; }
1703 acqLitPoCreateDialog.show();
1706 case 'save_picklist':
1707 this._loadPLSelect();
1708 acqLitSavePlDialog.show();
1711 case 'selector_ready':
1713 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
1714 acqLitChangeLiStateDialog.show();
1725 case 'rollback_receive_po':
1726 this.rollbackPoReceive();
1729 case 'create_assets':
1730 this.createAssets();
1733 case 'export_attr_list':
1734 this.chooseExportAttr();
1737 case 'add_brief_record':
1739 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
1741 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
1745 case "cancel_lineitems":
1746 this.maybeCancelLineitems();
1751 this.createAssets = function() {
1752 if(!this.isPO) return;
1753 if(!confirm(localeStrings.CREATE_PO_ASSETS_CONFIRM)) return;
1754 this.show('acq-lit-progress-numbers');
1756 fieldmapper.standardRequest(
1757 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
1759 params: [this.authtoken, this.isPO],
1760 onresponse: function(r) {
1761 var resp = openils.Util.readResponse(r);
1762 self._updateProgressNumbers(resp, true);
1768 this.maybeCancelLineitems = function() {
1769 openils.Util.show("acq-lit-cancel-reason", "inline");
1770 if (!acqLitCancelLineitemsButton._prepared) {
1771 var widget = new openils.widget.AutoFieldWidget({
1772 "fmField": "cancel_reason",
1774 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
1775 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1780 acqLitCancelLineitemsButton.onClick = function() {
1781 if (w.attr("value")) {
1782 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
1783 self._cancelLineitems(w.attr("value"));
1785 openils.Util.hide("acq-lit-cancel-reason");
1788 acqLitCancelLineitemsButton._prepared = true;
1794 this._cancelLineitems = function(reason) {
1795 var id_list = this.getSelected().map(function(o) { return o.id(); });
1796 fieldmapper.standardRequest(
1797 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
1798 "params": [openils.User.authtoken, id_list, reason],
1800 "onresponse": function(r) {
1801 if (r = openils.Util.readResponse(r)) {
1803 for (var id in r.li) {
1804 self.liCache[id].state(r.li[id].state);
1805 self.liCache[id].cancel_reason(
1806 r.li[id].cancel_reason
1808 self.updateLiState(self.liCache[id]);
1811 if (r.lid && self.copyCache) {
1812 for (var id in r.lid) {
1813 if (self.copyCache[id]) {
1814 self.copyCache[id].cancel_reason(
1815 r.lid[id].cancel_reason
1817 self.updateLidState(self.copyCache[id]);
1827 this.chooseExportAttr = function() {
1828 if (!acqLitExportAttrSelector._li_setup) {
1830 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
1832 "data": acqliad.toStoreData(
1834 "acqliad", {"code": li_exportable_attrs}
1839 acqLitExportAttrSelector.setValue();
1840 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
1841 acqLitExportAttrSelector._li_setup = true;
1843 openils.Util.show("acq-lit-export-attr-holder", "inline");
1846 this.exportAttrList = function() {
1847 var attr_def = acqLitExportAttrSelector.item;
1848 var li_list = this.getSelected();
1849 var value_list = li_list.map(
1851 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1852 attr_def.code, "lineitem_marc_attr_definition"
1855 ).filter(function(attr) { return Boolean(attr); });
1857 if (value_list.length > 0) {
1858 if (value_list.length < li_list.length) {
1860 dojo.string.substitute(
1861 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
1868 openils.XUL.contentToFileSaveDialog(
1869 value_list.join("\n"),
1870 localeStrings.EXPORT_SAVE_DIALOG_TITLE
1876 alert(dojo.string.substitute(
1877 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
1881 openils.Util.hide("acq-lit-export-attr-holder");
1884 this.printPO = function() {
1885 if(!this.isPO) return;
1886 progressDialog.show(true);
1887 fieldmapper.standardRequest(
1888 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
1890 params: [this.authtoken, this.isPO, 'html'],
1891 oncomplete: function(r) {
1892 progressDialog.hide();
1893 var evt = openils.Util.readResponse(r);
1894 if(evt && evt.template_output()) {
1895 win = window.open('','', 'resizable,width=800,height=600,scrollbars=1');
1896 win.document.body.innerHTML = evt.template_output().data();
1904 this.receivePO = function() {
1905 if (!this.isPO) return;
1907 for (var id in this.liCache) {
1908 /* assumption: liCache reflects exactly the
1909 * set of LIs that belong to our PO */
1910 if (this.liCache[id].state() != "received" &&
1911 !this.checkLiAlerts(id)) return;
1914 this.show('acq-lit-progress-numbers');
1916 fieldmapper.standardRequest(
1917 ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
1919 params: [this.authtoken, this.isPO],
1920 onresponse : function(r) {
1921 var resp = openils.Util.readResponse(r);
1922 self._updateProgressNumbers(resp, true);
1928 this.issueReceive = function(obj, rollback) {
1929 /* (For now) there shall be no marking LI or LIDs (un)received
1930 * except from the actual "view PO" interface. */
1931 if (!this.isPO) return;
1934 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
1936 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
1938 progressDialog.show(true);
1939 fieldmapper.standardRequest(
1940 ["open-ils.acq", method], {
1942 "params": [this.authtoken, obj.id()],
1943 "onresponse": function(r) {
1944 self.handleReceive(openils.Util.readResponse(r));
1945 progressDialog.hide();
1952 * Handles the responses from receive and rollback ML calls.
1954 this.handleReceive = function(resp) {
1957 for (var li_id in resp.li) {
1958 for (var key in resp.li[li_id])
1959 self.liCache[li_id][key](resp.li[li_id][key]);
1960 self.updateLiState(self.liCache[li_id]);
1964 if (typeof(self.poUpdateCallback) == "function")
1965 self.poUpdateCallback(resp.po);
1968 for (var lid_id in resp.lid) {
1969 for (var key in resp.lid[lid_id])
1970 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
1971 self.updateLidState(self.copyCache[lid_id]);
1977 this.rollbackPoReceive = function() {
1978 if(!this.isPO) return;
1979 if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
1980 this.show('acq-lit-progress-numbers');
1982 fieldmapper.standardRequest(
1983 ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
1985 params: [this.authtoken, this.isPO],
1986 onresponse : function(r) {
1987 var resp = openils.Util.readResponse(r);
1988 self._updateProgressNumbers(resp, true);
1994 this._updateProgressNumbers = function(resp, reloadOnComplete) {
1996 dojo.byId('acq-pl-lit-li-processed').innerHTML = resp.li;
1997 dojo.byId('acq-pl-lit-lid-processed').innerHTML = resp.lid;
1998 dojo.byId('acq-pl-lit-debits-processed').innerHTML = resp.debits_accrued;
1999 dojo.byId('acq-pl-lit-bibs-processed').innerHTML = resp.bibs;
2000 dojo.byId('acq-pl-lit-indexed-processed').innerHTML = resp.indexed;
2001 dojo.byId('acq-pl-lit-copies-processed').innerHTML = resp.copies;
2002 if(resp.complete && reloadOnComplete)
2003 location.href = location.href;
2007 this._createPO = function(fields) {
2008 this.show('acq-lit-progress-numbers');
2009 var po = new fieldmapper.acqpo();
2010 po.provider(this.createPoProviderSelector.attr('value'));
2011 po.ordering_agency(this.createPoAgencySelector.attr('value'));
2012 po.prepayment_required(fields.prepayment_required[0] ? true : false);
2014 var selected = this.getSelected( (fields.create_from == 'all') );
2015 if(selected.length == 0) return;
2017 var max = selected.length * 3;
2020 fieldmapper.standardRequest(
2021 ['open-ils.acq', 'open-ils.acq.purchase_order.create'],
2024 openils.User.authtoken,
2027 lineitems : selected.map(function(li) { return li.id() }),
2028 create_assets : fields.create_assets[0],
2032 onresponse : function(r) {
2033 var resp = openils.Util.readResponse(r);
2034 self._updateProgressNumbers(resp);
2036 location.href = oilsBasePath + '/acq/po/view/' + resp.purchase_order.id();
2042 this._deleteLiList = function(list, idx) {
2043 if(idx == null) idx = 0;
2044 if(idx >= list.length) return;
2045 var liId = list[idx].id();
2046 fieldmapper.standardRequest(
2047 ['open-ils.acq', 'open-ils.acq.lineitem.delete'],
2049 params: [openils.User.authtoken, liId],
2050 oncomplete: function(r) {
2051 self.removeLineitem(liId);
2052 self._deleteLiList(list, ++idx);
2058 this.editOrderMarc = function(li) {
2060 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
2061 to true in about:config */
2063 if(!openils.XUL.enableXPConnect()) return;
2065 if(openils.XUL.isXUL()) {
2066 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
2068 win = window.open('/xul/server/cat/marcedit.xul');
2072 record : {marc : li.marc()},
2074 label: 'Save Record', // XXX I18N
2075 func: function(xmlString) {
2077 fieldmapper.standardRequest(
2078 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
2080 params: [openils.User.authtoken, li],
2081 oncomplete: function(r) {
2082 openils.Util.readResponse(r);
2084 self.drawInfo(li.id())
2093 this._savePl = function(values) {
2095 var selected = this.getSelected( (values.which == 'all') );
2096 openils.Util.show('acq-lit-generic-progress');
2098 if(values.new_name) {
2099 openils.acq.Picklist.create(
2100 {name: values.new_name},
2102 self._updateLiList(id, selected, 0,
2104 location.href = oilsBasePath + '/acq/picklist/view/' + id;
2108 } else if(values.existing_pl) {
2109 // update lineitems to use an existing picklist
2110 self._updateLiList(values.existing_pl, selected, 0,
2112 location.href = oilsBasePath + '/acq/picklist/view/' + values.existing_pl;
2117 this._updateLiState = function(values, state) {
2119 var selected = this.getSelected( (values.which == 'all') );
2120 if(!selected.length) return;
2121 dojo.forEach(selected, function(li) {li.state(state);});
2122 self._updateLiList(null, selected, 0,
2123 // TODO consider inline updates for efficiency
2124 function() { location.href = location.href }
2128 this._updateLiList = function(pl, list, idx, oncomplete) {
2129 if(idx >= list.length) return oncomplete();
2131 if(pl != null) li.picklist(pl);
2132 litGenericProgress.update({maximum: list.length, progress: idx});
2133 new openils.acq.Lineitem({lineitem:li}).update(
2135 self._updateLiList(pl, list, ++idx, oncomplete);
2140 this._loadPLSelect = function() {
2141 if(this._plSelectLoaded) return;
2143 function handleResponse(r) {
2144 plList.push(r.recv().content());
2146 var method = 'open-ils.acq.picklist.user.retrieve';
2147 fieldmapper.standardRequest(
2148 ['open-ils.acq', method],
2150 params: [this.authtoken],
2151 onresponse: handleResponse,
2152 oncomplete: function() {
2153 self._plSelectLoaded = true;
2154 acqLitAddExistingSelect.store =
2155 new dojo.data.ItemFileReadStore({data:acqpl.toStoreData(plList)});
2156 acqLitAddExistingSelect.setValue();
2162 this.showRealCopyEditUI = function(li) {
2167 this._fetchLineitem(li.id(),
2169 li = self.liCache[li.id()] = fullLi;
2173 id : li.lineitem_details().map(
2174 function(item) { return item.eg_copy_id() }
2178 oncomplete : function(r) {
2180 var r_list = openils.Util.readResponse( r );
2181 for (var i = 0; i < r_list.length; i++) {
2182 var copy = r_list[i];
2183 var volId = copy.call_number();
2184 var volume = self.volCache[volId];
2186 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2188 copy.call_number(volume);
2189 copyList.push(copy);
2192 // If we need to, we can pass in an update_copy function to handle the update instead of volume_item_creator
2193 xulG.volume_item_creator( { 'existing_copies' : copyList } );
2196 alert('error in oncomplete: ' + E);
2207 this.saveRealCopies = function() {
2208 progressDialog.show(true);
2209 var list = this.realCopyList.filter(function(copy) { return copy.ischanged(); });
2210 this.pcrud.update(list, {oncomplete: function() {
2211 progressDialog.hide();
2216 // grab the li-details for this lineitem, grab the linked copies and volumes, add them to the table
2217 this.showRealCopies = function(li) {
2218 while(this.realCopiesTbody.childNodes[0])
2219 this.realCopiesTbody.removeChild(this.realCopiesTbody.childNodes[0]);
2220 this.show('real-copies');
2222 this.realCopyList = [];
2224 var tabIndex = 1000;
2227 acqLitSaveRealCopies.onClick = function() {
2228 self.saveRealCopies();
2231 this._fetchLineitem(li.id(),
2233 li = self.liCache[li.id()] = fullLi;
2237 id : li.lineitem_details().map(
2238 function(item) { return item.eg_copy_id() }
2243 onresponse : function(r) {
2244 var copy = openils.Util.readResponse(r);
2245 var volId = copy.call_number();
2246 var volume = self.volCache[volId];
2248 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2250 self.addRealCopy(volume, copy, tabIndex++);
2258 this.addRealCopy = function(volume, copy, tabIndex) {
2259 var row = this.realCopiesRow.cloneNode(true);
2260 this.realCopyList.push(copy);
2264 ['owning_lib', 'location', 'circ_modifier', 'label', 'barcode'],
2267 var isvol = (field == 'owning_lib' || field == 'label');
2268 var widget = new openils.widget.AutoFieldWidget({
2270 fmObject : isvol ? volume : copy,
2271 parentNode : nodeByName(field, row),
2272 readOnly : (field != 'barcode'),
2275 var widgetDrawn = null;
2277 if(field == 'barcode') {
2279 widgetDrawn = function(w, ww) {
2280 var node = w.domNode;
2281 node.setAttribute('tabindex', ''+tabIndex);
2283 // on enter, select the next barcode input
2284 dojo.connect(w, 'onKeyDown',
2286 if(e.keyCode == dojo.keys.ENTER) {
2287 var ti = node.getAttribute('tabindex');
2288 var nextNode = dojo.query('[tabindex=' + String(Number(ti) + 1) + ']', self.realCopiesTbody)[0];
2289 if(nextNode) nextNode.select();
2294 dojo.connect(w, 'onChange',
2296 if(!val || val == copy.barcode()) return;
2297 copy.ischanged(true);
2303 if(self.realCopiesTbody.getElementsByTagName('TR').length == 0)
2308 widget.build(widgetDrawn);
2312 this.realCopiesTbody.appendChild(row);
2313 if(selectNode) selectNode.select();