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));
191 this.setClaimPolicyControl = function(li, row) {
192 if (!self.claimPolicyPicker) {
193 self.claimPolicyPicker = true; /* prevents a race condition */
194 new openils.widget.AutoFieldWidget({
195 "parentNode": "acq-lit-li-claim-policy",
197 "selfReference": true,
198 "dijitArgs": {"required": true}
199 }).build(function(w) { self.claimPolicyPicker = w; });
202 if (typeof(row) == "undefined")
203 row = dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
205 var actViewPolicy = nodeByName("action_view_claim_policy", row);
206 if (li.claim_policy())
207 actViewPolicy.innerHTML = localeStrings.CHANGE_CLAIM_POLICY;
209 if (!actViewPolicy.onclick) {
210 actViewPolicy.onclick = function() {
211 if (li.claim_policy())
212 self.claimPolicyPicker.attr("value", li.claim_policy());
213 liClaimPolicyDialog.show();
214 liClaimPolicySave.onClick = function() {
215 self.changeClaimPolicy(
216 [li], self.claimPolicyPicker.attr("value"),
218 self.setClaimPolicyControl(li, row);
219 liClaimPolicyDialog.hide();
228 * Inserts a single lineitem into the growing table of lineitems
229 * @param {Object} li The lineitem object to insert
231 this.addLineitem = function(li, skip_final_placement) {
232 this.liCache[li.id()] = li;
234 // sort the lineitem notes on edit_time
235 if(!li.lineitem_notes()) li.lineitem_notes([]);
237 var liWrapper = new openils.acq.Lineitem({lineitem:li});
238 var row = self.rowTemplate.cloneNode(true);
239 row.setAttribute('li', li.id());
240 var tds = dojo.query('[attr]', row);
241 dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
242 dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
244 var isbn = liWrapper.findAttr('isbn', 'lineitem_marc_attr_definition');
246 // XXX media prefix for added content
247 dojo.query('[name=jacket]', row)[0].setAttribute('src', '/opac/extras/ac/jacket/small/' + isbn);
250 nodeByName("worksheet_link", row).href =
251 oilsBasePath + "/acq/lineitem/worksheet/" + li.id();
253 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
254 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
255 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
257 this.updateLiNotesCount(li, row);
259 this.setClaimPolicyControl(li, row);
261 // show which PO this lineitem is a member of
262 if(li.purchase_order() && !this.isPO) {
264 this.poCache[li.purchase_order()] =
265 this.poCache[li.purchase_order()] ||
266 fieldmapper.standardRequest(
267 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
269 this.authtoken, li.purchase_order(), {
270 "flesh_price_summary": true,
271 "flesh_lineitem_count": true
274 if(po && !this.isMeta) {
275 openils.Util.show(nodeByName('po', row), 'inline');
276 var link = nodeByName('po_link', row);
277 link.setAttribute('href', oilsBasePath + '/acq/po/view/' + li.purchase_order());
278 link.innerHTML = 'PO: ' + po.name(); // TODO i18n
282 // show which picklist this lineitem is a member of
283 if(li.picklist() && (this.isPO || this.isMeta)) {
285 this.plCache[li.picklist()] =
286 this.plCache[li.picklist()] ||
287 fieldmapper.standardRequest(
288 ['open-ils.acq', 'open-ils.acq.picklist.retrieve'],
289 {params: [this.authtoken, li.picklist()]});
291 openils.Util.show(nodeByName('pl', row), 'inline');
292 var link = nodeByName('pl_link', row);
293 link.setAttribute('href', oilsBasePath + '/acq/picklist/view/' + li.picklist());
294 link.innerHTML = 'PL: '+pl.name(); // TODO i18n
298 var countNode = nodeByName('count', row);
299 var count = li.item_count() || 0;
300 if (typeof(this._copy_count_cb) == "function") {
301 this._copy_count_cb(li.id(), count);
303 countNode.innerHTML = count;
304 countNode.id = 'acq-lit-copy-count-label-' + li.id();
307 var priceInput = dojo.query('[name=price]', row)[0];
308 priceInput.value = li.estimated_unit_price() || '';
309 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
311 // show either "mark received" or "unreceive" as appropriate
312 this.updateLiState(li, row);
314 if (!skip_final_placement) {
315 self.tbody.appendChild(row);
316 self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
322 this.updateLiNotesCount = function(li, row) {
323 if (typeof(row) == "undefined")
324 row = dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
326 var has_notes = (li.lineitem_notes().filter(
327 function(o) { return Boolean (o.alert_text()); }
330 /* U+2691 is the code point for a filled-in flag character */
331 nodeByName("notes_alert_flag", row).innerHTML =
332 has_notes ? "⚑" : "";
333 nodeByName("noteslink", row).style.fontStyle =
334 has_notes ? "italic" : "normal";
335 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
338 /* XXX NOT related to _updateLiState(). rethink */
339 this.updateLiState = function(li, row) {
340 if (typeof(row) == "undefined")
341 row = dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
343 var actReceive = nodeByName("action_mark_recv", row);
344 var actUnRecv = nodeByName("action_mark_unrecv", row);
345 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
346 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
348 var actNewInvoice = nodeByName('action_new_invoice', row);
349 var actLinkInvoice = nodeByName('action_link_invoice', row);
350 var actViewInvoice = nodeByName('action_view_invoice', row);
352 var state_cell = nodeByName("li_state", row);
354 if (li.state() == "cancelled") {
355 if (typeof li.cancel_reason() == "object") {
356 var holds_state = dojo.create(
358 "style": "border-bottom: 1px dashed #000;",
359 "innerHTML": li.state()
360 }, state_cell, "only"
364 "label": "<em>" + li.cancel_reason().label() +
365 "</em><br />" + li.cancel_reason().description(),
366 "connectId": [holds_state]
367 }, dojo.create("span", null, state_cell, "last")
370 state_cell.innerHTML = li.state(); // TODO i18n state labels
373 state_cell.innerHTML = li.state(); // TODO i18n state labels
377 /* handle row coloring for based on LI state */
378 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
379 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
381 /* handle links that appear/disappear based on whether LI is received */
386 actReceive.disabled = false;
387 actReceive.onclick = function() {
388 if (self.checkLiAlerts(li.id()))
389 self.issueReceive(li);
390 nodeByName("action_none", row).selected = true;
394 actUnRecv.disabled = false;
395 actUnRecv.onclick = function() {
396 if (confirm(localeStrings.UNRECEIVE_LI))
397 self.issueReceive(li, /* rollback */ true);
398 nodeByName("action_none", row).selected = true;
400 // TODO we should allow editing before receipt, in which case the
401 // test should be "if 1 or more real (acp) copies exist
402 actUpdateBarcodes.disabled = false;
403 actUpdateBarcodes.onclick = function() {
404 self.showRealCopyEditUI(li);
405 nodeByName("action_none", row).selected = true;
407 actHoldingsMaint.disabled = false;
408 actHoldingsMaint.onclick = self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
410 actNewInvoice.disabled = false;
411 actLinkInvoice.disabled = false;
412 actViewInvoice.disabled = false;
414 actNewInvoice.onclick = function() {
415 location.href = oilsBasePath + '/acq/invoice/view?create=1&attach_li=' + li.id();
416 nodeByName("action_none", row).selected = true;
418 actLinkInvoice.onclick = function() {
419 self.invoiceLinkDialogManager.target = li;
420 acqLitLinkInvoiceDialog.show();
421 nodeByName("action_none", row).selected = true;
423 actViewInvoice.onclick = function() {
424 location.href = oilsBasePath +
425 "/acq/search/unified?so=" +
426 base64Encode({"jub":[{"id": li.id()}]}) +
428 nodeByName("action_none", row).selected = true;
437 this._setAlertStore = function() {
438 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
440 "data": acqliat.toStoreData(
442 "acqliat", {"id": {"!=": null}}
447 acqLitAlertAlertText.setValue(); /* make the store "live" */
448 acqLitAlertAlertText._store_ready = true;
452 * Draws and shows the lineitem notes pane
454 this.drawLiNotes = function(li) {
457 if (!acqLitAlertAlertText._store_ready)
458 this._setAlertStore();
461 li.lineitem_notes().sort(
463 if(a.edit_time() < b.edit_time()) return 1;
469 while(this.liNotesTbody.childNodes[0])
470 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
473 acqLitCreateNoteSubmit.onClick = function() {
474 var value = acqLitCreateNoteText.attr('value');
476 var note = new fieldmapper.acqlin();
479 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
482 note.lineitem(li.id());
484 self.updateLiNotes(li, note);
485 acqLitCreateNoteVendorPublic.attr("checked", false);
486 acqLitCreateNoteText.attr("value", "");
489 acqLitCreateAlertSubmit.onClick = function() {
490 if (!acqLitAlertAlertText.item) {
491 alert(localeStrings.ALERT_UNSELECTED);
495 var alert_text = new fieldmapper.acqliat().fromStoreItem(
496 acqLitAlertAlertText.item
498 var value = acqLitAlertNoteValue.attr("value") || "";
500 var note = new fieldmapper.acqlin();
502 note.lineitem(li.id());
504 note.alert_text(alert_text);
506 self.updateLiNotes(li, note);
509 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
513 * Draws a single lineitem note in the notes pane
515 this.addLiNote = function(li, note) {
516 if(note.isdeleted()) return;
518 var row = self.liNotesRow.cloneNode(true);
519 nodeByName("value", row).innerHTML = note.value();
520 var alert_node = nodeByName("alert_code", row);
521 if (note.alert_text()) {
522 alert_node.innerHTML = note.alert_text().code();
523 if (note.alert_text().description()) {
526 "connectId": [alert_node],
527 "label": note.alert_text().description()
528 }, dojo.create("span", null, alert_node, "after")
533 if (openils.Util.isTrue(note.vendor_public()))
534 nodeByName("vendor_public", row).innerHTML =
535 localeStrings.VENDOR_PUBLIC;
537 nodeByName("delete", row).onclick = function() {
538 note.isdeleted(true);
539 self.liNotesTbody.removeChild(row);
540 self.updateLiNotes(li);
543 if(note.edit_time()) {
544 nodeByName("edit_time", row).innerHTML =
545 dojo.date.locale.format(
546 dojo.date.stamp.fromISOString(note.edit_time()),
547 {formatLength:'short'});
550 self.liNotesTbody.appendChild(row);
554 * Updates any new/changed/deleted notes on the server
556 this.updateLiNotes = function(li, newNote) {
562 notes = li.lineitem_notes().filter(
564 if(note.ischanged() || note.isnew() || note.isdeleted())
570 if(notes.length == 0) return;
571 progressDialog.show();
573 fieldmapper.standardRequest(
574 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
576 params : [this.authtoken, notes],
577 onresponse : function(r) {
578 var resp = openils.Util.readResponse(r);
583 // remove the old changed notes
585 dojo.forEach(li.lineitem_notes(),
587 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
591 li.lineitem_notes(list);
594 progressDialog.hide();
595 self.updateLiNotesCount(li);
596 self.drawLiNotes(li);
600 progressDialog.update(resp);
601 var newnote = resp.note;
603 if(!newnote.isdeleted()) {
604 newnote.isnew(false);
605 newnote.ischanged(false);
606 li.lineitem_notes().push(newnote);
613 this.updateLiPrice = function(input, li) {
615 var price = input.value;
616 if(Number(price) == Number(li.estimated_unit_price())) return;
618 fieldmapper.standardRequest(
619 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
621 params : [this.authtoken, li.id(), price],
622 oncomplete : function(r) {
623 openils.Util.readResponse(r);
624 li.estimated_unit_price(price); // update local copy
630 this.removeLineitem = function(liId) {
631 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
632 delete this.liCache[liId];
633 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
636 this.drawInfo = function(liId) {
637 if (!this._isRelatedViewer) {
638 var d = dojo.byId("acq-lit-info-related");
639 if (!this.relCache[liId]) {
640 fieldmapper.standardRequest(
643 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
646 "params": [openils.User.authtoken, liId],
647 "onresponse": function(r) {
648 self.relCache[liId] = openils.Util.readResponse(r);
649 nodeByName("related_number", d).innerHTML =
652 self.relCache[liId] >1 ? "show" : "hide"
658 nodeByName("related_number", d).innerHTML = this.relCache[liId];
659 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
664 openils.acq.Lineitem.fetchAttrDefs(
666 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
671 this._fetchLineitem = function(liId, handler) {
673 var li = this.liCache[liId];
674 if(li && li.marc() && li.lineitem_details())
677 fieldmapper.standardRequest(
678 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve'],
681 params: [self.authtoken, liId, {
683 flesh_cancel_reason: true,
684 flesh_li_details: true,
685 flesh_fund_debit: true }],
687 oncomplete: function(r) {
688 var li = openils.Util.readResponse(r);
695 this._drawInfo = function(li) {
697 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
700 openils.Util.hide('acq-lit-marc-order-record-label');
701 openils.Util.hide(acqLitEditOrderMarc.domNode);
702 openils.Util.show('acq-lit-marc-real-record-label');
704 openils.Util.show('acq-lit-marc-order-record-label');
705 openils.Util.show(acqLitEditOrderMarc.domNode);
706 openils.Util.hide('acq-lit-marc-real-record-label');
709 this.drawMarcHTML(li);
710 this.infoTbody = dojo.byId('acq-lit-info-tbody');
713 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
714 while(this.infoTbody.childNodes[0])
715 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
717 for(var i = 0; i < li.attributes().length; i++) {
718 var attr = li.attributes()[i];
719 var row = this.infoRow.cloneNode(true);
721 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
722 var name = openils.acq.Lineitem.attrDefs[type].filter(
724 return (a.code() == attr.attr_name());
726 ).pop().description();
728 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
729 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
730 this.infoTbody.appendChild(row);
733 if (!this._isRelatedViewer) {
734 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
735 oilsBasePath + "/acq/lineitem/related/" + li.id();
740 openils.Util.show('acq-lit-info-cat-link');
741 var link = dojo.byId('acq-lit-info-cat-link').getElementsByTagName('a')[0];
743 if(openils.XUL.isXUL()) {
745 link.setAttribute('href', 'javascript:void(0);');
746 link.onclick = this.generateMakeRecTab( li.eg_bib_id() );
749 var href = link.getAttribute('href');
751 link.setAttribute('href', href + li.eg_bib_id());
754 openils.Util.hide('acq-lit-info-cat-link');
758 this.generateMakeRecTab = function(bib_id,default_view, row) {
762 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
765 show_nav_buttons : true,
766 show_print_button : true,
767 opac_url : xulG.url_prefix(xulG.urls.opac_rdetail + '?r=' + bib_id),
768 default_view : default_view
772 if(row) nodeByName("action_none", row).selected = true;
776 this.drawMarcHTML = function(li) {
777 var params = [null, true, li.marc()];
779 params = [li.eg_bib_id(), true];
781 fieldmapper.standardRequest(
782 ['open-ils.search', 'open-ils.search.biblio.record.html'],
785 oncomplete: function(r) {
786 dojo.byId('acq-lit-marc-div').innerHTML =
787 openils.Util.readResponse(r);
793 this.drawCopies = function(liId) {
797 this.copyWidgetCache = {};
798 this.oldCopyWidgetCache = {};
799 this.virtDfaCounts = {};
800 this.realDfaCache = {};
803 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
804 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
805 acqLitCopyCountInput.attr('value', '0');
807 while(this.copyTbody.childNodes[0])
808 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
810 this._drawBatchCopyWidgets();
812 this._drawDistribApplied(liId);
814 this._fetchDistribFormulas(
816 openils.acq.Lineitem.fetchAttrDefs(
818 self._fetchLineitem(liId, function(li){self._drawCopies(li);});
825 this._saveDistribAppliedTemplates = function() {
826 if (!this._appliedDistribTemplate) {
827 this._appliedDistribTemplate =
828 dojo.byId("acq-lit-distrib-applied-tbody").
829 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
830 dojo.attr(this._appliedDistribTemplate, "id");
834 this._drawDistribApplied = function(liId) {
835 /* Build this table while hidden to prevent rendering artifacts */
836 openils.Util.hide("acq-lit-distrib-applied-tbody");
838 this._saveDistribAppliedTemplates();
840 /* Remove any rows in the table from previous populations */
841 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
842 forEach(dojo.destroy);
844 /* Unregister all dijits previously created (for some reason this isn't
845 * covered by the above destroy calls). */
846 dijit.registry.forEach(
847 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
850 /* Populate the table with our liId */
852 fieldmapper.standardRequest(
854 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
857 "params": [self.authtoken, liId],
858 "onresponse": function(r) {
859 var dfa = openils.Util.readResponse(r);
862 self.realDfaCache[dfa.id()] = dfa;
863 self._drawDistribAppliedUnit(dfa);
866 "oncomplete": function() {
867 /* Reveal built table */
870 "acq-lit-distrib-applied-tbody", "table-row-group"
878 this._drawDistribAppliedUnit = function(dfa) {
880 var row = dojo.query(
881 'tr[formula="' + dfa.formula().id() + '"]',
882 "acq-lit-distrib-applied-tbody"
887 row = dojo.clone(this._appliedDistribTemplate);
888 dojo.attr(row, "formula", dfa.formula().id());
889 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
892 var td = dojo.query("td", row)[0];
894 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
895 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
898 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
900 new dijit.form.Button(
902 "onClick": function() {
903 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
907 /* XXX I /cannot/ make the following work in as a CSS class
908 * for some reason. So frustrating... */
909 "style": function(id) {
911 "font-weight: bold; color: #c00;" :
913 }(dfa.id()) + "margin: 0 6px;display: inline;"
914 }, "dfa-button-" + dfa.id()
918 "connectId": ["dfa-button-" + dfa.id()],
919 "label": dojo.string.substitute(
920 localeStrings.DFA_TIP, dfa.id() > 0 ? [
921 openils.User.formalName(dfa.creator()),
922 dojo.date.locale.format(
923 dojo.date.stamp.fromISOString(dfa.create_time()),
924 {"formatLength":"short"}
926 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
928 }, "dfa-tip-" + dfa.id()
932 this.deleteDfa = function(dfa) {
933 if (dfa.id() > 0) { /* real */
934 this.pcrud.eliminate(
937 "oncomplete": function() {
938 self._removeDistribApplied(dfa.id());
939 delete self.realDfaCache[dfa.id()];
943 } else { /* virtual */
944 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
945 this.virtDfaCounts[dfa.formula().id()] = 0;
946 /* hasn't been saved yet, so no need to do anything server side */
947 this._removeDistribApplied(dfa.id());
952 this._removeDistribApplied = function(dfaId) {
953 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
954 dijit.registry.forEach(
955 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
957 this._removeDistribAppliedEmptyRows();
960 this._removeAllDistribAppliedVirtual = function() {
961 /* Unregister dijits */
962 dijit.registry.forEach(
963 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
965 this._removeDistribAppliedEmptyRows();
968 this._removeDistribAppliedEmptyRows = function() {
969 /* Remove any rows with no DFA at all */
970 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
972 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
978 * Insert a new row into the distribution formula selection form
980 this._addDistribFormulaRow = function() {
983 if (!self.distribForms) {
984 // no formulas, hide the form
985 openils.Util.hide('acq-lit-distrib-formula-tbody');
989 if(!this.distribFormulaTemplate)
990 this.distribFormulaTemplate =
991 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
993 var row = this.distribFormulaTemplate.cloneNode(true);
994 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
996 this.dfSelector = new dijit.form.FilteringSelect(
997 {"labelAttr": "dynLabel", "labelType": "html"},
998 nodeByName("selector", row)
1000 this._updateFormulaStore();
1001 this.dfSelector.fetchProperties =
1002 {"sort": [{"attribute": "use_count", "descending": true}]};
1004 var apply = new dijit.form.Button(
1005 {"label": localeStrings.APPLY},
1006 nodeByName('set_button', row)
1009 var reset = new dijit.form.Button(
1010 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
1011 nodeByName("reset_button", row)
1014 dojo.connect(apply, 'onClick',
1016 var form_id = self.dfSelector.attr("value");
1017 if(!form_id) return;
1018 self._applyDistribFormula(form_id);
1019 reset.attr("disabled", false);
1023 dojo.connect(reset, 'onClick',
1025 self.restoreCopyFieldsBeforeDF();
1026 self.virtDfaCounts = {};
1027 self.virtDfaId = -1;
1029 self._updateFormulaStore();
1030 self._removeAllDistribAppliedVirtual();
1031 reset.attr("disabled", "true");
1038 * Applies a distrib formula to the current set of copies
1040 this._applyDistribFormula = function(formula) {
1041 if(!formula) return;
1043 formula = this.distribForms.filter(
1044 function(form) { return form.id() == formula; }
1047 var copyRows = dojo.query('tr', self.copyTbody);
1049 if (this.dfeOffset >= copyRows.length) {
1050 alert(localeStrings.OUT_OF_COPIES);
1054 var entries_applied = 0;
1056 var rowIndex = this.dfeOffset;
1057 rowIndex < copyRows.length;
1061 var row = copyRows[rowIndex];
1062 var copy_id = row.getAttribute('copy_id');
1063 var copyWidgets = this.copyWidgetCache[copy_id];
1064 var entryIndex = this.dfeOffset;
1067 // find the correct entry for the current row
1068 dojo.forEach(formula.entries(),
1071 entryIndex += e.item_count();
1072 if(entryIndex > rowIndex)
1080 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
1081 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
1084 this.saveCopyFieldsBeforeDF(copy_id);
1085 this._copy_fields_for_acqdf.forEach(
1087 if(entry[field]()) {
1088 copyWidgets[field].attr('value', (entry[field]()));
1095 if (entries_applied) {
1096 this.virtDfaCounts[formula.id()] =
1097 ++(this.virtDfaCounts[formula.id()]) || 1;
1098 this._updateFormulaStore();
1099 this._drawDistribAppliedUnit(
1101 var dfa = new acqdfa();
1102 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
1105 this.dfeOffset += entries_applied;
1110 * This function updates the DF store for the dropdown so that use_counts
1111 * can reflect DF applications from this session before they're saved
1114 this._updateFormulaStore = function() {
1115 this.dfSelector.store = new dojo.data.ItemFileReadStore(
1117 "data": self._labelFormulasWithCounts(
1118 acqdf.toStoreData(self.distribForms)
1124 this.saveCopyFieldsBeforeDF = function(copy_id) {
1126 if (!this.oldCopyWidgetCache[copy_id]) {
1127 var copyWidgets = this.copyWidgetCache[copy_id];
1129 this.oldCopyWidgetCache[copy_id] = {};
1130 this._copy_fields_for_acqdf.forEach(
1132 self.oldCopyWidgetCache[copy_id][f] =
1133 copyWidgets[f].attr("value");
1139 this.restoreCopyFieldsBeforeDF = function() {
1141 for (var copy_id in this.oldCopyWidgetCache) {
1142 this._copy_fields_for_acqdf.forEach(
1144 self.copyWidgetCache[copy_id][f].attr(
1145 "value", self.oldCopyWidgetCache[copy_id][f]
1152 this._labelFormulasWithCounts = function(store_data) {
1153 for (var key in store_data.items) {
1154 var obj = store_data.items[key];
1155 obj.use_count = Number(obj.use_count); /* needed for sorting */
1157 if (this.virtDfaCounts[obj.id])
1158 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
1160 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
1161 obj.use_count + "]</span> " + obj.name;
1167 * This method formerly would not refetch the DF formulas if they'd been
1168 * loaded already, but now it always re-fetches, since use_count changes.
1170 this._fetchDistribFormulas = function(onload) {
1171 fieldmapper.standardRequest(
1173 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
1176 "params": [openils.User.authtoken],
1177 "oncomplete": function(r) {
1178 self.distribForms = openils.Util.readResponse(r);
1179 if(!self.distribForms || self.distribForms.length == 0) {
1180 self.distribForms = [];
1182 self._addDistribFormulaRow();
1189 this._drawBatchCopyWidgets = function() {
1190 var row = this.copyBatchRow;
1191 dojo.forEach(liDetailBatchFields,
1193 if(self.copyBatchRowDrawn) {
1194 self.copyBatchWidgets[field].attr('value', null);
1196 var widget = new openils.widget.AutoFieldWidget({
1199 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1200 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1201 searchFilter : (field == 'fund') ? {"active": "t"} : null,
1202 parentNode : dojo.query('[name='+field+']', row)[0],
1203 orgLimitPerms : ['CREATE_PICKLIST'],
1206 "labelType": (field == "fund") ? "html" : null
1208 noCache: (field == "fund"),
1213 if (field == "fund" && w.store)
1214 self._ensureCSSFundClasses(w.store);
1215 self.copyBatchWidgets[field] = w;
1218 if (field == "fund") {
1220 widget.widget, "onChange", function(val) {
1221 self._updateFundSelectorStyle(widget, val);
1228 this.copyBatchRowDrawn = true;
1231 this.batchCopyUpdate = function() {
1233 for(var k in this.copyWidgetCache) {
1234 var cache = this.copyWidgetCache[k];
1235 dojo.forEach(liDetailBatchFields, function(f) {
1236 var newval = self.copyBatchWidgets[f].attr('value');
1237 if(newval) cache[f].attr('value', newval);
1242 this._drawCopies = function(li) {
1245 // this button sets the total number of copies for a given lineitem
1246 acqLitAddCopyCount.onClick = function() {
1247 var count = acqLitCopyCountInput.attr('value');
1250 while(self.copyCount() < count)
1253 // delete rows if necessary
1254 var diff = self.copyCount() - count;
1256 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
1257 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
1258 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
1260 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1266 if(li.lineitem_details().length > 0) {
1267 dojo.forEach(li.lineitem_details(),
1269 self.addCopy(li, copy);
1277 this.copyCount = function() {
1279 for(var id in this.copyCache) {
1280 if(!this.copyCache[id].isdeleted())
1286 this.virtCopyId = -1;
1287 this.addCopy = function(li, copy) {
1288 var row = this.copyRow.cloneNode(true);
1289 this.copyTbody.appendChild(row);
1293 copy = new fieldmapper.acqlid();
1295 copy.id(this.virtCopyId--);
1296 copy.lineitem(li.id());
1299 this.copyCache[copy.id()] = copy;
1300 row.setAttribute('copy_id', copy.id());
1301 self.copyWidgetCache[copy.id()] = {};
1303 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1305 dojo.forEach(liDetailFields,
1308 if (field == "fund") {
1309 searchFilter = (copy.fund() ?
1310 {"-or": {"active": "t", "id": copy.fund()}} :
1313 searchFilter = null;
1315 var widget = new openils.widget.AutoFieldWidget({
1318 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1319 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1320 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1321 searchFilter : searchFilter,
1322 noCache: (field == "fund"),
1324 parentNode : dojo.query('[name='+field+']', row)[0],
1325 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
1326 readOnly : Boolean(copy.eg_copy_id())
1329 // make sure we capture the value from any async widgets
1331 if (field == "fund" && w.store)
1332 self._ensureCSSFundClasses(w.store);
1333 copy[field](ww.getFormattedValue())
1334 self.copyWidgetCache[copy.id()][field] = w;
1337 dojo.connect(widget.widget, 'onChange',
1339 if (field == "fund")
1340 self._updateFundSelectorStyle(widget, val);
1342 if (copy.isnew() || val != copy[field]()) {
1343 // prevent setting ischanged() automatically on widget load for existing copies
1344 copy[field](widget.getFormattedValue())
1345 copy.ischanged(true);
1352 this.updateLidState(copy, row);
1355 this._ensureCSSFundClass = function(id) {
1356 if (!this.fundStyleSheet) {
1358 "style", {"type": "text/css"},
1359 document.getElementsByTagName("head")[0], "last"
1361 this.fundStyleSheet = document.styleSheets[
1362 document.styleSheets.length - 1
1366 var cn = "fund_" + id;
1367 if (!this.haveFundClass[cn]) {
1368 fieldmapper.standardRequest(
1369 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
1371 "params": [openils.User.authtoken, id],
1373 "oncomplete": function(r) {
1374 r = openils.Util.readResponse(r);
1375 self.fundBalanceState[id] = r;
1377 if (r[0] /* stop */)
1378 style = fundStyles.stop;
1379 else if (r[1] /* warning */)
1380 style = fundStyles.warning;
1381 self.fundStyleSheet.insertRule(
1382 "." + cn + " { " + style + " }",
1383 self.fundStyleSheet.cssRules.length
1385 self.haveFundClass[cn] = true;
1392 this._ensureCSSFundClasses = function(store) {
1394 "query": {"id": "*"},
1395 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
1399 this._updateFundSelectorStyle = function(widget, fund_id) {
1400 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
1401 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
1404 this.updateLidState = function(copy, row) {
1405 if (typeof(row) == "undefined") {
1407 'tr[copy_id="' + copy.id() + '"]', this.copyTbody
1412 var recv_link = nodeByName("receive", row);
1413 var unrecv_link = nodeByName("unreceive", row);
1414 var del_link = nodeByName("delete", row);
1415 var cxl_link = nodeByName("cancel", row);
1416 var cxl_reason_link = nodeByName("cancel_reason", row);
1418 if (copy.cancel_reason()) {
1419 openils.Util.hide(del_link.parentNode);
1420 openils.Util.hide(recv_link);
1421 openils.Util.hide(unrecv_link);
1422 openils.Util.hide(cxl_link);
1424 /* XXX the following may leak memory in a long lived table: dijits may not get destroyed... not positive. revisit. */
1425 var holds_reason = dojo.create(
1427 "style": "border-bottom: 1px dashed #000;",
1428 "innerHTML": "Cancelled" /* XXX [sic] and i18n */
1429 }, cxl_reason_link, "only"
1433 "label": "<em>" + copy.cancel_reason().label() +
1434 "</em><br />" + copy.cancel_reason().description(),
1435 "connectId": [holds_reason]
1436 }, dojo.create("span", null, cxl_reason_link, "last")
1438 openils.Util.show(cxl_reason_link, "inline");
1439 } else if (this.isPO) {
1440 openils.Util.hide(del_link.parentNode);
1441 openils.Util.hide(cxl_reason_link);
1443 /* Avoid showing (un)receive links, cancel links, for virt copies */
1444 if (copy.id() > 0) {
1445 if(copy.recv_time()) {
1446 openils.Util.hide(cxl_link);
1447 openils.Util.hide(recv_link);
1448 openils.Util.show(unrecv_link, "inline");
1449 unrecv_link.onclick = function() {
1450 if (confirm(localeStrings.UNRECEIVE_LID))
1451 self.issueReceive(copy, /* rollback */ true);
1454 openils.Util.hide(unrecv_link);
1455 openils.Util.show(recv_link, "inline");
1456 openils.Util.show(cxl_link, "inline");
1457 recv_link.onclick = function() {
1458 if (self.checkLiAlerts(copy.lineitem()))
1459 self.issueReceive(copy);
1461 cxl_link.onclick = function() {
1462 self.cancelLid(copy.id());
1466 openils.Util.hide(cxl_link);
1467 openils.Util.hide(unrecv_link);
1468 openils.Util.hide(recv_link);
1471 openils.Util.hide(unrecv_link);
1472 openils.Util.hide(recv_link);
1473 openils.Util.hide(cxl_reason_link);
1475 del_link.onclick = function() { self.deleteCopy(row) };
1476 openils.Util.show(del_link.parentNode);
1480 this.cancelLid = function(lid_id) {
1481 lidCancelDialog._lid_id = lid_id;
1482 openils.Util.show(lidCancelDialog.domNode.parentNode);
1483 lidCancelDialog.show();
1484 if (!lidCancelDialog._prepared) {
1485 var widget = new openils.widget.AutoFieldWidget({
1486 "fmField": "cancel_reason",
1487 "fmClass": "acqlid",
1488 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
1489 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1494 acqLidCancelButton.onClick = function() {
1495 if (w.attr("value")) {
1496 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
1498 lidCancelDialog._lid_id,
1502 lidCancelDialog.hide();
1505 lidCancelDialog._prepared = true;
1511 this._cancelLid = function(lid_id, reason) {
1512 fieldmapper.standardRequest(
1513 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
1514 "params": [openils.User.authtoken, lid_id, reason],
1516 "onresponse": function(r) {
1517 if (r = openils.Util.readResponse(r)) {
1519 for (var id in r.lid) {
1520 /* actually this should only iterate once */
1521 self.copyCache[id].cancel_reason(
1522 r.lid[id].cancel_reason
1524 self.updateLidState(self.copyCache[id]);
1533 this._confirmAlert = function(li, lin) {
1535 dojo.string.substitute(
1536 localeStrings.CONFIRM_LI_ALERT, [
1537 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1538 "title", "lineitem_marc_attr_definition"
1540 lin.alert_text().code(),
1541 lin.alert_text().description() || "",
1548 this.checkLiAlerts = function(li_id) {
1549 var li = this.liCache[li_id];
1551 var alert_notes = li.lineitem_notes().filter(
1552 function(o) { return Boolean(o.alert_text()); }
1555 /* this is _intentionally_ not done in a call to forEach() ... */
1556 for (var i = 0; i < alert_notes.length; i++) {
1557 if (this.noteAcks[alert_notes[i].id()])
1559 else if (!this._confirmAlert(li, alert_notes[i]))
1562 this.noteAcks[alert_notes[i].id()] = true;
1568 this.deleteCopy = function(row) {
1569 var copy = this.copyCache[row.getAttribute('copy_id')];
1570 copy.isdeleted(true);
1572 delete this.copyCache[copy.id()];
1573 this.copyTbody.removeChild(row);
1576 this._virtDfaCountsAsList = function() {
1578 for (var key in this.virtDfaCounts) {
1579 for (var i = 0; i < this.virtDfaCounts[key]; i++)
1585 this.confirmBreachedCopyFunds = function(copies) {
1586 var stop = 0, warning = 0;
1590 var state = self.fundBalanceState[o.fund()];
1591 if (state[0] /* stop */)
1593 else if (state[1] /* warning */)
1600 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
1601 } else if (warning) {
1602 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
1607 this.saveCopyChanges = function(liId) {
1613 for(var id in this.copyCache) {
1614 var c = this.copyCache[id];
1615 if(!c.isdeleted()) total++;
1616 if(c.isnew() || c.ischanged() || c.isdeleted()) {
1617 if(c.id() < 0) c.id(null);
1623 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
1626 if (copies.length > 0) {
1627 if (!this.confirmBreachedCopyFunds(copies))
1630 if (typeof(this._copy_count_cb) == "function")
1631 this._copy_count_cb(liId, total);
1633 openils.Util.show("acq-lit-update-copies-progress");
1634 fieldmapper.standardRequest(
1635 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1637 params: [openils.User.authtoken, copies],
1638 onresponse: function(r) {
1639 var res = openils.Util.readResponse(r);
1640 litUpdateCopiesProgress.update(res);
1642 oncomplete: function() {
1643 self.drawCopies(liId);
1644 openils.Util.hide("acq-lit-update-copies-progress");
1650 var dfa_list = this._virtDfaCountsAsList();
1651 if (dfa_list.length > 0) {
1652 fieldmapper.standardRequest(
1654 "open-ils.acq.distribution_formula.record_application"],
1657 "params": [openils.User.authtoken, dfa_list, liId],
1658 "onresponse": function(r) {
1659 var res = openils.Util.readResponse(r);
1660 if (res && res.length < dfa_list.length)
1661 alert(localeStrings.DFA_NOT_ALL);
1665 this.virtDfaCounts = {};
1669 this._updateCreatePoPrepayCheckbox = function(prepay) {
1670 var prepay = openils.Util.isTrue(prepay);
1671 this._prepayRequiredByVendor = prepay;
1672 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
1675 this._confirmPoPrepaySituation = function() {
1676 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
1677 if (want_prepay != this._prepayRequiredByVendor) {
1680 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
1681 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
1688 this.applySelectedLiAction = function(action) {
1692 case 'delete_selected':
1693 this._deleteLiList(self.getSelected());
1696 case 'create_order':
1698 if(!this.createPoProviderSelector) {
1699 var widget = new openils.widget.AutoFieldWidget({
1700 fmField : 'provider',
1702 searchFilter: {"active": "t"},
1703 parentNode : dojo.byId('acq-lit-po-provider'),
1705 "onChange": function() {
1707 self._updateCreatePoPrepayCheckbox(
1708 this.item.prepayment_required
1715 function(w) { self.createPoProviderSelector = w; }
1719 if(!this.createPoAgencySelector) {
1720 var widget = new openils.widget.AutoFieldWidget({
1721 fmField : 'ordering_agency',
1723 parentNode : dojo.byId('acq-lit-po-agency'),
1724 orgLimitPerms : ['CREATE_PURCHASE_ORDER'],
1727 function(w) { self.createPoAgencySelector = w; }
1732 acqLitPoCreateDialog.show();
1735 case 'save_picklist':
1736 this._loadPLSelect();
1737 acqLitSavePlDialog.show();
1740 case 'selector_ready':
1742 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
1743 acqLitChangeLiStateDialog.show();
1754 case 'rollback_receive_po':
1755 this.rollbackPoReceive();
1758 case 'create_assets':
1759 this.createAssets();
1762 case 'export_attr_list':
1763 this.chooseExportAttr();
1766 case 'add_brief_record':
1768 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
1770 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
1774 case "cancel_lineitems":
1775 this.maybeCancelLineitems();
1778 case "change_claim_policy":
1779 var li_list = this.getSelected();
1780 this.claimPolicyPicker.attr("value", null);
1781 liClaimPolicyDialog.show();
1782 liClaimPolicySave.onClick = function() {
1783 self.changeClaimPolicy(
1785 self.claimPolicyPicker.attr("value"),
1788 function(li) { self.setClaimPolicyControl(li); }
1790 liClaimPolicyDialog.hide();
1798 this.changeClaimPolicy = function(li_list, value, callback) {
1800 function(li) { li.claim_policy(value); }
1802 fieldmapper.standardRequest(
1803 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
1804 "params": [openils.User.authtoken, li_list],
1806 "oncomplete": function(r) {
1807 r = openils.Util.readResponse(r);
1808 if (callback) callback(r);
1814 this.createAssets = function() {
1815 if(!this.isPO) return;
1816 if(!confirm(localeStrings.CREATE_PO_ASSETS_CONFIRM)) return;
1817 this.show('acq-lit-progress-numbers');
1819 fieldmapper.standardRequest(
1820 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
1822 params: [this.authtoken, this.isPO],
1823 onresponse: function(r) {
1824 var resp = openils.Util.readResponse(r);
1825 self._updateProgressNumbers(resp, true);
1831 this.maybeCancelLineitems = function() {
1832 openils.Util.show("acq-lit-cancel-reason", "inline");
1833 if (!acqLitCancelLineitemsButton._prepared) {
1834 var widget = new openils.widget.AutoFieldWidget({
1835 "fmField": "cancel_reason",
1837 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
1838 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1843 acqLitCancelLineitemsButton.onClick = function() {
1844 if (w.attr("value")) {
1845 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
1846 self._cancelLineitems(w.attr("value"));
1848 openils.Util.hide("acq-lit-cancel-reason");
1851 acqLitCancelLineitemsButton._prepared = true;
1857 this._cancelLineitems = function(reason) {
1858 var id_list = this.getSelected().map(function(o) { return o.id(); });
1859 fieldmapper.standardRequest(
1860 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
1861 "params": [openils.User.authtoken, id_list, reason],
1863 "onresponse": function(r) {
1864 if (r = openils.Util.readResponse(r)) {
1866 for (var id in r.li) {
1867 self.liCache[id].state(r.li[id].state);
1868 self.liCache[id].cancel_reason(
1869 r.li[id].cancel_reason
1871 self.updateLiState(self.liCache[id]);
1874 if (r.lid && self.copyCache) {
1875 for (var id in r.lid) {
1876 if (self.copyCache[id]) {
1877 self.copyCache[id].cancel_reason(
1878 r.lid[id].cancel_reason
1880 self.updateLidState(self.copyCache[id]);
1890 this.chooseExportAttr = function() {
1891 if (!acqLitExportAttrSelector._li_setup) {
1893 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
1895 "data": acqliad.toStoreData(
1897 "acqliad", {"code": li_exportable_attrs}
1902 acqLitExportAttrSelector.setValue();
1903 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
1904 acqLitExportAttrSelector._li_setup = true;
1906 openils.Util.show("acq-lit-export-attr-holder", "inline");
1909 this.exportAttrList = function() {
1910 var attr_def = acqLitExportAttrSelector.item;
1911 var li_list = this.getSelected();
1912 var value_list = li_list.map(
1914 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1915 attr_def.code, "lineitem_marc_attr_definition"
1918 ).filter(function(attr) { return Boolean(attr); });
1920 if (value_list.length > 0) {
1921 if (value_list.length < li_list.length) {
1923 dojo.string.substitute(
1924 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
1931 openils.XUL.contentToFileSaveDialog(
1932 value_list.join("\n"),
1933 localeStrings.EXPORT_SAVE_DIALOG_TITLE
1939 alert(dojo.string.substitute(
1940 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
1944 openils.Util.hide("acq-lit-export-attr-holder");
1947 this.printPO = function() {
1948 if(!this.isPO) return;
1949 progressDialog.show(true);
1950 fieldmapper.standardRequest(
1951 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
1953 params: [this.authtoken, this.isPO, 'html'],
1954 oncomplete: function(r) {
1955 progressDialog.hide();
1956 var evt = openils.Util.readResponse(r);
1957 if(evt && evt.template_output()) {
1958 win = window.open('','', 'resizable,width=800,height=600,scrollbars=1');
1959 win.document.body.innerHTML = evt.template_output().data();
1967 this.receivePO = function() {
1968 if (!this.isPO) return;
1970 for (var id in this.liCache) {
1971 /* assumption: liCache reflects exactly the
1972 * set of LIs that belong to our PO */
1973 if (this.liCache[id].state() != "received" &&
1974 !this.checkLiAlerts(id)) return;
1977 this.show('acq-lit-progress-numbers');
1979 fieldmapper.standardRequest(
1980 ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
1982 params: [this.authtoken, this.isPO],
1983 onresponse : function(r) {
1984 var resp = openils.Util.readResponse(r);
1985 self._updateProgressNumbers(resp, true);
1991 this.issueReceive = function(obj, rollback) {
1992 /* (For now) there shall be no marking LI or LIDs (un)received
1993 * except from the actual "view PO" interface. */
1994 if (!this.isPO) return;
1997 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
1999 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
2001 progressDialog.show(true);
2002 fieldmapper.standardRequest(
2003 ["open-ils.acq", method], {
2005 "params": [this.authtoken, obj.id()],
2006 "onresponse": function(r) {
2007 self.handleReceive(openils.Util.readResponse(r));
2008 progressDialog.hide();
2015 * Handles the responses from receive and rollback ML calls.
2017 this.handleReceive = function(resp) {
2020 for (var li_id in resp.li) {
2021 for (var key in resp.li[li_id])
2022 self.liCache[li_id][key](resp.li[li_id][key]);
2023 self.updateLiState(self.liCache[li_id]);
2027 if (typeof(self.poUpdateCallback) == "function")
2028 self.poUpdateCallback(resp.po);
2031 for (var lid_id in resp.lid) {
2032 for (var key in resp.lid[lid_id])
2033 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
2034 self.updateLidState(self.copyCache[lid_id]);
2040 this.rollbackPoReceive = function() {
2041 if(!this.isPO) return;
2042 if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
2043 this.show('acq-lit-progress-numbers');
2045 fieldmapper.standardRequest(
2046 ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
2048 params: [this.authtoken, this.isPO],
2049 onresponse : function(r) {
2050 var resp = openils.Util.readResponse(r);
2051 self._updateProgressNumbers(resp, true);
2057 this._updateProgressNumbers = function(resp, reloadOnComplete) {
2059 dojo.byId('acq-pl-lit-li-processed').innerHTML = resp.li;
2060 dojo.byId('acq-pl-lit-lid-processed').innerHTML = resp.lid;
2061 dojo.byId('acq-pl-lit-debits-processed').innerHTML = resp.debits_accrued;
2062 dojo.byId('acq-pl-lit-bibs-processed').innerHTML = resp.bibs;
2063 dojo.byId('acq-pl-lit-indexed-processed').innerHTML = resp.indexed;
2064 dojo.byId('acq-pl-lit-copies-processed').innerHTML = resp.copies;
2065 if(resp.complete && reloadOnComplete)
2066 location.href = location.href;
2070 this._createPO = function(fields) {
2071 this.show('acq-lit-progress-numbers');
2072 var po = new fieldmapper.acqpo();
2073 po.provider(this.createPoProviderSelector.attr('value'));
2074 po.ordering_agency(this.createPoAgencySelector.attr('value'));
2075 po.prepayment_required(fields.prepayment_required[0] ? true : false);
2077 var selected = this.getSelected( (fields.create_from == 'all') );
2078 if(selected.length == 0) return;
2080 var max = selected.length * 3;
2083 fieldmapper.standardRequest(
2084 ['open-ils.acq', 'open-ils.acq.purchase_order.create'],
2087 openils.User.authtoken,
2090 lineitems : selected.map(function(li) { return li.id() }),
2091 create_assets : fields.create_assets[0],
2095 onresponse : function(r) {
2096 var resp = openils.Util.readResponse(r);
2097 self._updateProgressNumbers(resp);
2099 location.href = oilsBasePath + '/acq/po/view/' + resp.purchase_order.id();
2105 this._deleteLiList = function(list, idx) {
2106 if(idx == null) idx = 0;
2107 if(idx >= list.length) return;
2108 var liId = list[idx].id();
2109 fieldmapper.standardRequest(
2110 ['open-ils.acq', 'open-ils.acq.lineitem.delete'],
2112 params: [openils.User.authtoken, liId],
2113 oncomplete: function(r) {
2114 self.removeLineitem(liId);
2115 self._deleteLiList(list, ++idx);
2121 this.editOrderMarc = function(li) {
2123 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
2124 to true in about:config */
2126 if(!openils.XUL.enableXPConnect()) return;
2128 if(openils.XUL.isXUL()) {
2129 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
2131 win = window.open('/xul/server/cat/marcedit.xul');
2135 record : {marc : li.marc()},
2137 label: 'Save Record', // XXX I18N
2138 func: function(xmlString) {
2140 fieldmapper.standardRequest(
2141 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
2143 params: [openils.User.authtoken, li],
2144 oncomplete: function(r) {
2145 openils.Util.readResponse(r);
2147 self.drawInfo(li.id())
2156 this._savePl = function(values) {
2158 var selected = this.getSelected( (values.which == 'all') );
2159 openils.Util.show('acq-lit-generic-progress');
2161 if(values.new_name) {
2162 openils.acq.Picklist.create(
2163 {name: values.new_name},
2165 self._updateLiList(id, selected, 0,
2167 location.href = oilsBasePath + '/acq/picklist/view/' + id;
2171 } else if(values.existing_pl) {
2172 // update lineitems to use an existing picklist
2173 self._updateLiList(values.existing_pl, selected, 0,
2175 location.href = oilsBasePath + '/acq/picklist/view/' + values.existing_pl;
2180 this._updateLiState = function(values, state) {
2182 var selected = this.getSelected( (values.which == 'all') );
2183 if(!selected.length) return;
2184 dojo.forEach(selected, function(li) {li.state(state);});
2185 self._updateLiList(null, selected, 0,
2186 // TODO consider inline updates for efficiency
2187 function() { location.href = location.href }
2191 this._updateLiList = function(pl, list, idx, oncomplete) {
2192 if(idx >= list.length) return oncomplete();
2194 if(pl != null) li.picklist(pl);
2195 litGenericProgress.update({maximum: list.length, progress: idx});
2196 new openils.acq.Lineitem({lineitem:li}).update(
2198 self._updateLiList(pl, list, ++idx, oncomplete);
2203 this._loadPLSelect = function() {
2204 if(this._plSelectLoaded) return;
2206 function handleResponse(r) {
2207 plList.push(r.recv().content());
2209 var method = 'open-ils.acq.picklist.user.retrieve';
2210 fieldmapper.standardRequest(
2211 ['open-ils.acq', method],
2213 params: [this.authtoken],
2214 onresponse: handleResponse,
2215 oncomplete: function() {
2216 self._plSelectLoaded = true;
2217 acqLitAddExistingSelect.store =
2218 new dojo.data.ItemFileReadStore({data:acqpl.toStoreData(plList)});
2219 acqLitAddExistingSelect.setValue();
2225 this.showRealCopyEditUI = function(li) {
2230 this._fetchLineitem(li.id(),
2232 li = self.liCache[li.id()] = fullLi;
2236 id : li.lineitem_details().map(
2237 function(item) { return item.eg_copy_id() }
2241 oncomplete : function(r) {
2243 var r_list = openils.Util.readResponse( r );
2244 for (var i = 0; i < r_list.length; i++) {
2245 var copy = r_list[i];
2246 var volId = copy.call_number();
2247 var volume = self.volCache[volId];
2249 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2251 copy.call_number(volume);
2252 copyList.push(copy);
2255 // If we need to, we can pass in an update_copy function to handle the update instead of volume_item_creator
2256 xulG.volume_item_creator( { 'existing_copies' : copyList } );
2259 alert('error in oncomplete: ' + E);
2270 this.saveRealCopies = function() {
2271 progressDialog.show(true);
2272 var list = this.realCopyList.filter(function(copy) { return copy.ischanged(); });
2273 this.pcrud.update(list, {oncomplete: function() {
2274 progressDialog.hide();
2279 // grab the li-details for this lineitem, grab the linked copies and volumes, add them to the table
2280 this.showRealCopies = function(li) {
2281 while(this.realCopiesTbody.childNodes[0])
2282 this.realCopiesTbody.removeChild(this.realCopiesTbody.childNodes[0]);
2283 this.show('real-copies');
2285 this.realCopyList = [];
2287 var tabIndex = 1000;
2290 acqLitSaveRealCopies.onClick = function() {
2291 self.saveRealCopies();
2294 this._fetchLineitem(li.id(),
2296 li = self.liCache[li.id()] = fullLi;
2300 id : li.lineitem_details().map(
2301 function(item) { return item.eg_copy_id() }
2306 onresponse : function(r) {
2307 var copy = openils.Util.readResponse(r);
2308 var volId = copy.call_number();
2309 var volume = self.volCache[volId];
2311 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2313 self.addRealCopy(volume, copy, tabIndex++);
2321 this.addRealCopy = function(volume, copy, tabIndex) {
2322 var row = this.realCopiesRow.cloneNode(true);
2323 this.realCopyList.push(copy);
2327 ['owning_lib', 'location', 'circ_modifier', 'label', 'barcode'],
2330 var isvol = (field == 'owning_lib' || field == 'label');
2331 var widget = new openils.widget.AutoFieldWidget({
2333 fmObject : isvol ? volume : copy,
2334 parentNode : nodeByName(field, row),
2335 readOnly : (field != 'barcode'),
2338 var widgetDrawn = null;
2340 if(field == 'barcode') {
2342 widgetDrawn = function(w, ww) {
2343 var node = w.domNode;
2344 node.setAttribute('tabindex', ''+tabIndex);
2346 // on enter, select the next barcode input
2347 dojo.connect(w, 'onKeyDown',
2349 if(e.keyCode == dojo.keys.ENTER) {
2350 var ti = node.getAttribute('tabindex');
2351 var nextNode = dojo.query('[tabindex=' + String(Number(ti) + 1) + ']', self.realCopiesTbody)[0];
2352 if(nextNode) nextNode.select();
2357 dojo.connect(w, 'onChange',
2359 if(!val || val == copy.barcode()) return;
2360 copy.ischanged(true);
2366 if(self.realCopiesTbody.getElementsByTagName('TR').length == 0)
2371 widget.build(widgetDrawn);
2375 this.realCopiesTbody.appendChild(row);
2376 if(selectNode) selectNode.select();