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.claimEligibleLidByLi = {};
53 this.claimEligibleLid = {};
54 this.toggleState = false;
55 this.tbody = dojo.byId('acq-lit-tbody');
58 this.authtoken = openils.User.authtoken;
59 this.pcrud = new openils.PermaCrud();
60 this.rowTemplate = this.tbody.removeChild(dojo.byId('acq-lit-row'));
61 this.copyTbody = dojo.byId('acq-lit-li-details-tbody');
62 this.copyRow = this.copyTbody.removeChild(dojo.byId('acq-lit-li-details-row'));
63 this.copyBatchRow = dojo.byId('acq-lit-li-details-batch-row');
64 this.copyBatchWidgets = {};
65 this.liNotesTbody = dojo.byId('acq-lit-notes-tbody');
66 this.liNotesRow = this.liNotesTbody.removeChild(dojo.byId('acq-lit-notes-row'));
67 this.realCopiesTbody = dojo.byId('acq-lit-real-copies-tbody');
68 this.realCopiesRow = this.realCopiesTbody.removeChild(dojo.byId('acq-lit-real-copies-row'));
69 this._copy_fields_for_acqdf = ['owning_lib', 'location'];
70 this.invoiceLinkDialogManager = new InvoiceLinkDialogManager("li");
71 this.claimDialog = new ClaimDialogManager(
72 liClaimDialog, finalClaimDialog, this.claimEligibleLidByLi,
73 function(li) { /* callback that fires when claims are made */
74 self.fetchClaimInfo(li.id(), /* force update */ true);
78 dojo.connect(acqLitLiActionsSelector, 'onChange',
80 self.applySelectedLiAction(this.attr('value'))
81 acqLitLiActionsSelector.attr('value', '_');
84 acqLitCreatePoSubmit.onClick = function() {
85 if (self._confirmPoPrepaySituation()) {
86 acqLitPoCreateDialog.hide();
87 self._createPO(acqLitPoCreateDialog.getValues());
93 acqLitSavePlButton.onClick = function() {
94 acqLitSavePlDialog.hide();
95 self._savePl(acqLitSavePlDialog.getValues());
98 acqLitCancelLiStateButton.onClick = function() {
99 acqLitChangeLiStateDialog.hide();
101 acqLitSaveLiStateButton.onClick = function() {
102 acqLitChangeLiStateDialog.hide();
103 self._updateLiState(acqLitChangeLiStateDialog.getValues(), acqLitChangeLiStateDialog.attr('state'));
107 dojo.byId('acq-lit-select-toggle').onclick = function(){self.toggleSelect()};
108 dojo.byId('acq-lit-info-back-button').onclick = function(){self.show('list')};
109 dojo.byId('acq-lit-copies-back-button').onclick = function(){self.show('list')};
110 dojo.byId('acq-lit-notes-back-button').onclick = function(){self.show('list')};
111 dojo.byId('acq-lit-real-copies-back-button').onclick = function(){self.show('list')};
113 this.reset = function() {
114 while(self.tbody.childNodes[0])
115 self.tbody.removeChild(self.tbody.childNodes[0]);
121 this.setNext = function(handler) {
122 var link = dojo.byId('acq-lit-next');
124 dojo.style(link, 'visibility', 'visible');
125 link.onclick = handler;
127 dojo.style(link, 'visibility', 'hidden');
131 this.setPrev = function(handler) {
132 var link = dojo.byId('acq-lit-prev');
134 dojo.style(link, 'visibility', 'visible');
135 link.onclick = handler;
137 dojo.style(link, 'visibility', 'hidden');
141 this.show = function(div) {
142 openils.Util.hide('acq-lit-table-div');
143 openils.Util.hide('acq-lit-info-div');
144 openils.Util.hide('acq-lit-li-details');
145 openils.Util.hide('acq-lit-notes-div');
146 openils.Util.hide('acq-lit-real-copies-div');
149 openils.Util.show('acq-lit-table-div');
152 openils.Util.show('acq-lit-info-div');
155 openils.Util.show('acq-lit-li-details');
158 openils.Util.show('acq-lit-real-copies-div');
161 openils.Util.show('acq-lit-notes-div');
165 openils.Util.show(div);
169 this.hide = function() {
173 this.toggleSelect = function() {
175 dojo.forEach(self.selectors, function(i){i.checked = false});
177 dojo.forEach(self.selectors, function(i){i.checked = true});
178 self.toggleState = !self.toggleState;
182 /** @param all If true, assume all are selected */
183 this.getSelected = function(all) {
185 dojo.forEach(self.selectors,
188 selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
194 this.setRowAttr = function(td, liWrapper, field, type) {
195 var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
196 td.appendChild(document.createTextNode(val));
199 this.setClaimPolicyControl = function(li, row) {
200 if (!self.claimPolicyPicker) {
201 self.claimPolicyPicker = true; /* prevents a race condition */
202 new openils.widget.AutoFieldWidget({
203 "parentNode": "acq-lit-li-claim-policy",
205 "selfReference": true,
206 "dijitArgs": {"required": true}
207 }).build(function(w) { self.claimPolicyPicker = w; });
210 if (!row) row = this._findLiRow(li);
212 var actViewPolicy = nodeByName("action_view_claim_policy", row);
213 if (li.claim_policy())
214 actViewPolicy.innerHTML = localeStrings.CHANGE_CLAIM_POLICY;
216 if (!actViewPolicy.onclick) {
217 actViewPolicy.onclick = function() {
218 if (li.claim_policy())
219 self.claimPolicyPicker.attr("value", li.claim_policy());
220 liClaimPolicyDialog.show();
221 liClaimPolicySave.onClick = function() {
222 self.changeClaimPolicy(
223 [li], self.claimPolicyPicker.attr("value"),
225 self.setClaimPolicyControl(li, row);
226 liClaimPolicyDialog.hide();
234 this.fetchClaimInfo = function(liId, force, callback, row) {
236 liId, function(full) {
237 self.liCache[full.id()] = full;
238 self.checkClaimEligibility(full, callback, row);
244 * Inserts a single lineitem into the growing table of lineitems
245 * @param {Object} li The lineitem object to insert
247 this.addLineitem = function(li, skip_final_placement) {
248 this.liCache[li.id()] = li;
250 // sort the lineitem notes on edit_time
251 if(!li.lineitem_notes()) li.lineitem_notes([]);
253 var liWrapper = new openils.acq.Lineitem({lineitem:li});
254 var row = self.rowTemplate.cloneNode(true);
255 row.setAttribute('li', li.id());
256 var tds = dojo.query('[attr]', row);
257 dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
258 dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
260 var isbn = liWrapper.findAttr('isbn', 'lineitem_marc_attr_definition');
262 // XXX media prefix for added content
263 dojo.query('[name=jacket]', row)[0].setAttribute('src', '/opac/extras/ac/jacket/small/' + isbn);
266 nodeByName("worksheet_link", row).href =
267 oilsBasePath + "/acq/lineitem/worksheet/" + li.id();
269 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
270 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
271 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
273 this.fetchClaimInfo(li.id(), false, null, row);
275 this.updateLiNotesCount(li, row);
277 this.setClaimPolicyControl(li, row);
279 // show which PO this lineitem is a member of
280 if(li.purchase_order() && !this.isPO) {
282 this.poCache[li.purchase_order()] =
283 this.poCache[li.purchase_order()] ||
284 fieldmapper.standardRequest(
285 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
287 this.authtoken, li.purchase_order(), {
288 "flesh_price_summary": true,
289 "flesh_lineitem_count": true
292 if(po && !this.isMeta) {
293 openils.Util.show(nodeByName('po', row), 'inline');
294 var link = nodeByName('po_link', row);
295 link.setAttribute('href', oilsBasePath + '/acq/po/view/' + li.purchase_order());
296 link.innerHTML = 'PO: ' + po.name(); // TODO i18n
300 // show which picklist this lineitem is a member of
301 if(li.picklist() && (this.isPO || this.isMeta)) {
303 this.plCache[li.picklist()] =
304 this.plCache[li.picklist()] ||
305 fieldmapper.standardRequest(
306 ['open-ils.acq', 'open-ils.acq.picklist.retrieve'],
307 {params: [this.authtoken, li.picklist()]});
309 openils.Util.show(nodeByName('pl', row), 'inline');
310 var link = nodeByName('pl_link', row);
311 link.setAttribute('href', oilsBasePath + '/acq/picklist/view/' + li.picklist());
312 link.innerHTML = 'PL: '+pl.name(); // TODO i18n
316 var countNode = nodeByName('count', row);
317 var count = li.item_count() || 0;
318 if (typeof(this._copy_count_cb) == "function") {
319 this._copy_count_cb(li.id(), count);
321 countNode.innerHTML = count;
322 countNode.id = 'acq-lit-copy-count-label-' + li.id();
325 var priceInput = dojo.query('[name=price]', row)[0];
326 priceInput.value = li.estimated_unit_price() || '';
327 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
329 // show either "mark received" or "unreceive" as appropriate
330 this.updateLiState(li, row);
332 if (!skip_final_placement) {
333 self.tbody.appendChild(row);
334 self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
340 this._liCountClaims = function(li) {
342 for (var i = 0; i < li.lineitem_details().length; i++)
343 total += li.lineitem_details()[i].claims().length;
347 this._findLiRow = function(li) {
348 return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
351 this.reconsiderClaimControl = function(li, row) {
352 var option = nodeByName("action_manage_claims", row);
353 var eligible = this.claimEligibleLidByLi[li.id()].length;
354 var count = this._liCountClaims(li);
355 if (!row) row = this._findLiRow(li);
357 option.disabled = !(count || eligible);
359 dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
360 option.onclick = function() { self.claimDialog.show(li); };
363 this.clearEligibility = function(li) {
364 this.claimEligibleLidByLi[li.id()] = [];
366 if (li.lineitem_details()) {
367 li.lineitem_details().forEach(
368 function(lid) { delete self.claimEligibleLid[lid.id()]; }
372 if (this.copyCache) {
374 for (var k in this.copyCache) {
375 if (this.copyCache[k].lineitem() == li.id())
379 function(k) { delete self.claimEligibleLid[k]; }
384 this.checkClaimEligibility = function(li, callback, row) {
385 this.clearEligibility(li);
386 fieldmapper.standardRequest(
387 ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
388 "params": [openils.User.authtoken, {"lineitem": li.id()}],
390 "onresponse": function(r) {
391 if (r = openils.Util.readResponse(r)) {
392 self.claimEligibleLidByLi[li.id()].push(
395 self.claimEligibleLid[r.lineitem_detail()] = true;
398 "oncomplete": function() {
399 self.reconsiderClaimControl(li, row);
400 if (typeof(callback) == "function")
407 this.updateLiNotesCount = function(li, row) {
408 if (!row) row = this._findLiRow(li);
410 var has_notes = (li.lineitem_notes().filter(
411 function(o) { return Boolean (o.alert_text()); }
414 /* U+2691 is the code point for a filled-in flag character */
415 nodeByName("notes_alert_flag", row).innerHTML =
416 has_notes ? "⚑" : "";
417 nodeByName("noteslink", row).style.fontStyle =
418 has_notes ? "italic" : "normal";
419 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
422 /* XXX NOT related to _updateLiState(). rethink */
423 this.updateLiState = function(li, row) {
424 if (!row) row = this._findLiRow(li);
426 var actReceive = nodeByName("action_mark_recv", row);
427 var actUnRecv = nodeByName("action_mark_unrecv", row);
428 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
429 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
431 var actNewInvoice = nodeByName('action_new_invoice', row);
432 var actLinkInvoice = nodeByName('action_link_invoice', row);
433 var actViewInvoice = nodeByName('action_view_invoice', row);
435 nodeByName('action_view_history', row).onclick =
436 function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
438 var state_cell = nodeByName("li_state", row);
440 if (li.state() == "cancelled") {
441 if (typeof li.cancel_reason() == "object") {
442 var holds_state = dojo.create(
444 "style": "border-bottom: 1px dashed #000;",
445 "innerHTML": li.state()
446 }, state_cell, "only"
450 "label": "<em>" + li.cancel_reason().label() +
451 "</em><br />" + li.cancel_reason().description(),
452 "connectId": [holds_state]
453 }, dojo.create("span", null, state_cell, "last")
456 state_cell.innerHTML = li.state(); // TODO i18n state labels
459 state_cell.innerHTML = li.state(); // TODO i18n state labels
463 /* handle row coloring for based on LI state */
464 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
465 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
467 /* handle links that appear/disappear based on whether LI is received */
471 actNewInvoice.onclick = function() {
472 location.href = oilsBasePath + '/acq/invoice/view?create=1&attach_li=' + li.id();
473 nodeByName("action_none", row).selected = true;
475 actLinkInvoice.onclick = function() {
476 self.invoiceLinkDialogManager.target = li;
477 acqLitLinkInvoiceDialog.show();
478 nodeByName("action_none", row).selected = true;
480 actViewInvoice.onclick = function() {
481 location.href = oilsBasePath +
482 "/acq/search/unified?so=" +
483 base64Encode({"jub":[{"id": li.id()}]}) +
485 nodeByName("action_none", row).selected = true;
488 actNewInvoice.disabled = false;
489 actLinkInvoice.disabled = false;
490 actViewInvoice.disabled = false;
494 actReceive.disabled = false;
495 actReceive.onclick = function() {
496 if (self.checkLiAlerts(li.id()))
497 self.issueReceive(li);
498 nodeByName("action_none", row).selected = true;
503 actUnRecv.disabled = false;
504 actUnRecv.onclick = function() {
505 if (confirm(localeStrings.UNRECEIVE_LI))
506 self.issueReceive(li, /* rollback */ true);
507 nodeByName("action_none", row).selected = true;
509 // TODO we should allow editing before receipt, in which case the
510 // test should be "if 1 or more real (acp) copies exist
511 actUpdateBarcodes.disabled = false;
512 actUpdateBarcodes.onclick = function() {
513 self.showRealCopyEditUI(li);
514 nodeByName("action_none", row).selected = true;
516 actHoldingsMaint.disabled = false;
517 actHoldingsMaint.onclick = self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
525 this._setAlertStore = function() {
526 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
528 "data": acqliat.toStoreData(
530 "acqliat", {"id": {"!=": null}}
535 acqLitAlertAlertText.setValue(); /* make the store "live" */
536 acqLitAlertAlertText._store_ready = true;
540 * Draws and shows the lineitem notes pane
542 this.drawLiNotes = function(li) {
545 if (!acqLitAlertAlertText._store_ready)
546 this._setAlertStore();
549 li.lineitem_notes().sort(
551 if(a.edit_time() < b.edit_time()) return 1;
557 while(this.liNotesTbody.childNodes[0])
558 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
561 acqLitCreateNoteSubmit.onClick = function() {
562 var value = acqLitCreateNoteText.attr('value');
564 var note = new fieldmapper.acqlin();
567 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
570 note.lineitem(li.id());
572 self.updateLiNotes(li, note);
573 acqLitCreateNoteVendorPublic.attr("checked", false);
574 acqLitCreateNoteText.attr("value", "");
577 acqLitCreateAlertSubmit.onClick = function() {
578 if (!acqLitAlertAlertText.item) {
579 alert(localeStrings.ALERT_UNSELECTED);
583 var alert_text = new fieldmapper.acqliat().fromStoreItem(
584 acqLitAlertAlertText.item
586 var value = acqLitAlertNoteValue.attr("value") || "";
588 var note = new fieldmapper.acqlin();
590 note.lineitem(li.id());
592 note.alert_text(alert_text);
594 self.updateLiNotes(li, note);
597 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
601 * Draws a single lineitem note in the notes pane
603 this.addLiNote = function(li, note) {
604 if(note.isdeleted()) return;
606 var row = self.liNotesRow.cloneNode(true);
607 nodeByName("value", row).innerHTML = note.value();
608 var alert_node = nodeByName("alert_code", row);
609 if (note.alert_text()) {
610 alert_node.innerHTML = note.alert_text().code();
611 if (note.alert_text().description()) {
614 "connectId": [alert_node],
615 "label": note.alert_text().description()
616 }, dojo.create("span", null, alert_node, "after")
621 if (openils.Util.isTrue(note.vendor_public()))
622 nodeByName("vendor_public", row).innerHTML =
623 localeStrings.VENDOR_PUBLIC;
625 nodeByName("delete", row).onclick = function() {
626 note.isdeleted(true);
627 self.liNotesTbody.removeChild(row);
628 self.updateLiNotes(li);
631 if(note.edit_time()) {
632 nodeByName("edit_time", row).innerHTML =
633 dojo.date.locale.format(
634 dojo.date.stamp.fromISOString(note.edit_time()),
635 {formatLength:'short'});
638 self.liNotesTbody.appendChild(row);
642 * Updates any new/changed/deleted notes on the server
644 this.updateLiNotes = function(li, newNote) {
650 notes = li.lineitem_notes().filter(
652 if(note.ischanged() || note.isnew() || note.isdeleted())
658 if(notes.length == 0) return;
659 progressDialog.show();
661 fieldmapper.standardRequest(
662 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
664 params : [this.authtoken, notes],
665 onresponse : function(r) {
666 var resp = openils.Util.readResponse(r);
671 // remove the old changed notes
673 dojo.forEach(li.lineitem_notes(),
675 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
679 li.lineitem_notes(list);
682 progressDialog.hide();
683 self.updateLiNotesCount(li);
684 self.drawLiNotes(li);
688 progressDialog.update(resp);
689 var newnote = resp.note;
691 if(!newnote.isdeleted()) {
692 newnote.isnew(false);
693 newnote.ischanged(false);
694 li.lineitem_notes().push(newnote);
701 this.updateLiPrice = function(input, li) {
703 var price = input.value;
704 if(Number(price) == Number(li.estimated_unit_price())) return;
706 fieldmapper.standardRequest(
707 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
709 params : [this.authtoken, li.id(), price],
710 oncomplete : function(r) {
711 openils.Util.readResponse(r);
712 li.estimated_unit_price(price); // update local copy
718 this.removeLineitem = function(liId) {
719 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
720 delete this.liCache[liId];
721 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
724 this.drawInfo = function(liId) {
725 if (!this._isRelatedViewer) {
726 var d = dojo.byId("acq-lit-info-related");
727 if (!this.relCache[liId]) {
728 fieldmapper.standardRequest(
731 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
734 "params": [openils.User.authtoken, liId],
735 "onresponse": function(r) {
736 self.relCache[liId] = openils.Util.readResponse(r);
737 nodeByName("related_number", d).innerHTML =
740 self.relCache[liId] >1 ? "show" : "hide"
746 nodeByName("related_number", d).innerHTML = this.relCache[liId];
747 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
752 openils.acq.Lineitem.fetchAttrDefs(
754 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
759 this._fetchLineitem = function(liId, handler, force) {
761 var li = this.liCache[liId];
762 if(li && li.marc() && li.lineitem_details() && !force)
765 fieldmapper.standardRequest(
766 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve'],
769 params: [self.authtoken, liId, {
771 flesh_cancel_reason: true,
772 flesh_li_details: true,
774 flesh_fund_debit: true }],
776 oncomplete: function(r) {
777 var li = openils.Util.readResponse(r);
784 this._drawInfo = function(li) {
786 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
789 openils.Util.hide('acq-lit-marc-order-record-label');
790 openils.Util.hide(acqLitEditOrderMarc.domNode);
791 openils.Util.show('acq-lit-marc-real-record-label');
793 openils.Util.show('acq-lit-marc-order-record-label');
794 openils.Util.show(acqLitEditOrderMarc.domNode);
795 openils.Util.hide('acq-lit-marc-real-record-label');
798 this.drawMarcHTML(li);
799 this.infoTbody = dojo.byId('acq-lit-info-tbody');
802 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
803 while(this.infoTbody.childNodes[0])
804 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
806 for(var i = 0; i < li.attributes().length; i++) {
807 var attr = li.attributes()[i];
808 var row = this.infoRow.cloneNode(true);
810 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
811 var name = openils.acq.Lineitem.attrDefs[type].filter(
813 return (a.code() == attr.attr_name());
815 ).pop().description();
817 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
818 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
819 this.infoTbody.appendChild(row);
822 if (!this._isRelatedViewer) {
823 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
824 oilsBasePath + "/acq/lineitem/related/" + li.id();
829 openils.Util.show('acq-lit-info-cat-link');
830 var link = dojo.byId('acq-lit-info-cat-link').getElementsByTagName('a')[0];
832 if(openils.XUL.isXUL()) {
834 link.setAttribute('href', 'javascript:void(0);');
835 link.onclick = this.generateMakeRecTab( li.eg_bib_id() );
838 var href = link.getAttribute('href');
840 link.setAttribute('href', href + li.eg_bib_id());
843 openils.Util.hide('acq-lit-info-cat-link');
847 this.generateMakeRecTab = function(bib_id,default_view, row) {
851 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
854 show_nav_buttons : true,
855 show_print_button : true,
856 opac_url : xulG.url_prefix(xulG.urls.opac_rdetail + '?r=' + bib_id),
857 default_view : default_view
861 if(row) nodeByName("action_none", row).selected = true;
865 this.drawMarcHTML = function(li) {
866 var params = [null, true, li.marc()];
868 params = [li.eg_bib_id(), true];
870 fieldmapper.standardRequest(
871 ['open-ils.search', 'open-ils.search.biblio.record.html'],
874 oncomplete: function(r) {
875 dojo.byId('acq-lit-marc-div').innerHTML =
876 openils.Util.readResponse(r);
882 this.drawCopies = function(liId) {
886 this.copyWidgetCache = {};
887 this.oldCopyWidgetCache = {};
888 this.virtDfaCounts = {};
889 this.realDfaCache = {};
892 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
893 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
894 acqLitCopyCountInput.attr('value', '0');
896 while(this.copyTbody.childNodes[0])
897 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
899 this._drawBatchCopyWidgets();
901 this._drawDistribApplied(liId);
903 this._fetchDistribFormulas(
905 openils.acq.Lineitem.fetchAttrDefs(
907 self._fetchLineitem(liId, function(li){self._drawCopies(li);});
914 this._saveDistribAppliedTemplates = function() {
915 if (!this._appliedDistribTemplate) {
916 this._appliedDistribTemplate =
917 dojo.byId("acq-lit-distrib-applied-tbody").
918 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
919 dojo.attr(this._appliedDistribTemplate, "id");
923 this._drawDistribApplied = function(liId) {
924 /* Build this table while hidden to prevent rendering artifacts */
925 openils.Util.hide("acq-lit-distrib-applied-tbody");
927 this._saveDistribAppliedTemplates();
929 /* Remove any rows in the table from previous populations */
930 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
931 forEach(dojo.destroy);
933 /* Unregister all dijits previously created (for some reason this isn't
934 * covered by the above destroy calls). */
935 dijit.registry.forEach(
936 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
939 /* Populate the table with our liId */
941 fieldmapper.standardRequest(
943 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
946 "params": [self.authtoken, liId],
947 "onresponse": function(r) {
948 var dfa = openils.Util.readResponse(r);
951 self.realDfaCache[dfa.id()] = dfa;
952 self._drawDistribAppliedUnit(dfa);
955 "oncomplete": function() {
956 /* Reveal built table */
959 "acq-lit-distrib-applied-tbody", "table-row-group"
967 this._drawDistribAppliedUnit = function(dfa) {
969 var row = dojo.query(
970 'tr[formula="' + dfa.formula().id() + '"]',
971 "acq-lit-distrib-applied-tbody"
976 row = dojo.clone(this._appliedDistribTemplate);
977 dojo.attr(row, "formula", dfa.formula().id());
978 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
981 var td = dojo.query("td", row)[0];
983 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
984 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
987 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
989 new dijit.form.Button(
991 "onClick": function() {
992 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
996 /* XXX I /cannot/ make the following work in as a CSS class
997 * for some reason. So frustrating... */
998 "style": function(id) {
1000 "font-weight: bold; color: #c00;" :
1002 }(dfa.id()) + "margin: 0 6px;display: inline;"
1003 }, "dfa-button-" + dfa.id()
1007 "connectId": ["dfa-button-" + dfa.id()],
1008 "label": dojo.string.substitute(
1009 localeStrings.DFA_TIP, dfa.id() > 0 ? [
1010 openils.User.formalName(dfa.creator()),
1011 dojo.date.locale.format(
1012 dojo.date.stamp.fromISOString(dfa.create_time()),
1013 {"formatLength":"short"}
1015 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
1017 }, "dfa-tip-" + dfa.id()
1021 this.deleteDfa = function(dfa) {
1022 if (dfa.id() > 0) { /* real */
1023 this.pcrud.eliminate(
1026 "oncomplete": function() {
1027 self._removeDistribApplied(dfa.id());
1028 delete self.realDfaCache[dfa.id()];
1032 } else { /* virtual */
1033 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
1034 this.virtDfaCounts[dfa.formula().id()] = 0;
1035 /* hasn't been saved yet, so no need to do anything server side */
1036 this._removeDistribApplied(dfa.id());
1041 this._removeDistribApplied = function(dfaId) {
1042 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
1043 dijit.registry.forEach(
1044 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
1046 this._removeDistribAppliedEmptyRows();
1049 this._removeAllDistribAppliedVirtual = function() {
1050 /* Unregister dijits */
1051 dijit.registry.forEach(
1052 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
1054 this._removeDistribAppliedEmptyRows();
1057 this._removeDistribAppliedEmptyRows = function() {
1058 /* Remove any rows with no DFA at all */
1059 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
1061 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
1067 * Insert a new row into the distribution formula selection form
1069 this._addDistribFormulaRow = function() {
1072 if (!self.distribForms) {
1073 // no formulas, hide the form
1074 openils.Util.hide('acq-lit-distrib-formula-tbody');
1078 if(!this.distribFormulaTemplate)
1079 this.distribFormulaTemplate =
1080 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
1082 var row = this.distribFormulaTemplate.cloneNode(true);
1083 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
1085 this.dfSelector = new dijit.form.FilteringSelect(
1086 {"labelAttr": "dynLabel", "labelType": "html"},
1087 nodeByName("selector", row)
1089 this._updateFormulaStore();
1090 this.dfSelector.fetchProperties =
1091 {"sort": [{"attribute": "use_count", "descending": true}]};
1093 var apply = new dijit.form.Button(
1094 {"label": localeStrings.APPLY},
1095 nodeByName('set_button', row)
1098 var reset = new dijit.form.Button(
1099 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
1100 nodeByName("reset_button", row)
1103 dojo.connect(apply, 'onClick',
1105 var form_id = self.dfSelector.attr("value");
1106 if(!form_id) return;
1107 self._applyDistribFormula(form_id);
1108 reset.attr("disabled", false);
1112 dojo.connect(reset, 'onClick',
1114 self.restoreCopyFieldsBeforeDF();
1115 self.virtDfaCounts = {};
1116 self.virtDfaId = -1;
1118 self._updateFormulaStore();
1119 self._removeAllDistribAppliedVirtual();
1120 reset.attr("disabled", "true");
1127 * Applies a distrib formula to the current set of copies
1129 this._applyDistribFormula = function(formula) {
1130 if(!formula) return;
1132 formula = this.distribForms.filter(
1133 function(form) { return form.id() == formula; }
1136 var copyRows = dojo.query('tr', self.copyTbody);
1138 if (this.dfeOffset >= copyRows.length) {
1139 alert(localeStrings.OUT_OF_COPIES);
1143 var entries_applied = 0;
1145 var rowIndex = this.dfeOffset;
1146 rowIndex < copyRows.length;
1150 var row = copyRows[rowIndex];
1151 var copy_id = row.getAttribute('copy_id');
1152 var copyWidgets = this.copyWidgetCache[copy_id];
1153 var entryIndex = this.dfeOffset;
1156 // find the correct entry for the current row
1157 dojo.forEach(formula.entries(),
1160 entryIndex += e.item_count();
1161 if(entryIndex > rowIndex)
1169 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
1170 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
1173 this.saveCopyFieldsBeforeDF(copy_id);
1174 this._copy_fields_for_acqdf.forEach(
1176 if(entry[field]()) {
1177 copyWidgets[field].attr('value', (entry[field]()));
1184 if (entries_applied) {
1185 this.virtDfaCounts[formula.id()] =
1186 ++(this.virtDfaCounts[formula.id()]) || 1;
1187 this._updateFormulaStore();
1188 this._drawDistribAppliedUnit(
1190 var dfa = new acqdfa();
1191 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
1194 this.dfeOffset += entries_applied;
1199 * This function updates the DF store for the dropdown so that use_counts
1200 * can reflect DF applications from this session before they're saved
1203 this._updateFormulaStore = function() {
1204 this.dfSelector.store = new dojo.data.ItemFileReadStore(
1206 "data": self._labelFormulasWithCounts(
1207 acqdf.toStoreData(self.distribForms)
1213 this.saveCopyFieldsBeforeDF = function(copy_id) {
1215 if (!this.oldCopyWidgetCache[copy_id]) {
1216 var copyWidgets = this.copyWidgetCache[copy_id];
1218 this.oldCopyWidgetCache[copy_id] = {};
1219 this._copy_fields_for_acqdf.forEach(
1221 self.oldCopyWidgetCache[copy_id][f] =
1222 copyWidgets[f].attr("value");
1228 this.restoreCopyFieldsBeforeDF = function() {
1230 for (var copy_id in this.oldCopyWidgetCache) {
1231 this._copy_fields_for_acqdf.forEach(
1233 self.copyWidgetCache[copy_id][f].attr(
1234 "value", self.oldCopyWidgetCache[copy_id][f]
1241 this._labelFormulasWithCounts = function(store_data) {
1242 for (var key in store_data.items) {
1243 var obj = store_data.items[key];
1244 obj.use_count = Number(obj.use_count); /* needed for sorting */
1246 if (this.virtDfaCounts[obj.id])
1247 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
1249 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
1250 obj.use_count + "]</span> " + obj.name;
1256 * This method formerly would not refetch the DF formulas if they'd been
1257 * loaded already, but now it always re-fetches, since use_count changes.
1259 this._fetchDistribFormulas = function(onload) {
1260 fieldmapper.standardRequest(
1262 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
1265 "params": [openils.User.authtoken],
1266 "oncomplete": function(r) {
1267 self.distribForms = openils.Util.readResponse(r);
1268 if(!self.distribForms || self.distribForms.length == 0) {
1269 self.distribForms = [];
1271 self._addDistribFormulaRow();
1278 this._drawBatchCopyWidgets = function() {
1279 var row = this.copyBatchRow;
1280 dojo.forEach(liDetailBatchFields,
1282 if(self.copyBatchRowDrawn) {
1283 self.copyBatchWidgets[field].attr('value', null);
1285 var widget = new openils.widget.AutoFieldWidget({
1288 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1289 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1290 searchFilter : (field == 'fund') ? {"active": "t"} : null,
1291 parentNode : dojo.query('[name='+field+']', row)[0],
1292 orgLimitPerms : ['CREATE_PICKLIST'],
1295 "labelType": (field == "fund") ? "html" : null
1297 noCache: (field == "fund"),
1302 if (field == "fund" && w.store)
1303 self._ensureCSSFundClasses(w.store);
1304 self.copyBatchWidgets[field] = w;
1307 if (field == "fund") {
1309 widget.widget, "onChange", function(val) {
1310 self._updateFundSelectorStyle(widget, val);
1317 this.copyBatchRowDrawn = true;
1320 this.batchCopyUpdate = function() {
1322 for(var k in this.copyWidgetCache) {
1323 var cache = this.copyWidgetCache[k];
1324 dojo.forEach(liDetailBatchFields, function(f) {
1325 var newval = self.copyBatchWidgets[f].attr('value');
1326 if(newval) cache[f].attr('value', newval);
1331 this._drawCopies = function(li) {
1334 // this button sets the total number of copies for a given lineitem
1335 acqLitAddCopyCount.onClick = function() {
1336 var count = acqLitCopyCountInput.attr('value');
1339 while(self.copyCount() < count)
1342 // delete rows if necessary
1343 var diff = self.copyCount() - count;
1345 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
1346 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
1347 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
1349 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1355 if(li.lineitem_details().length > 0) {
1356 dojo.forEach(li.lineitem_details(),
1358 self.addCopy(li, copy);
1366 this.copyCount = function() {
1368 for(var id in this.copyCache) {
1369 if(!this.copyCache[id].isdeleted())
1375 this.virtCopyId = -1;
1376 this.addCopy = function(li, copy) {
1377 var row = this.copyRow.cloneNode(true);
1378 this.copyTbody.appendChild(row);
1382 copy = new fieldmapper.acqlid();
1384 copy.id(this.virtCopyId--);
1385 copy.lineitem(li.id());
1388 this.copyCache[copy.id()] = copy;
1389 row.setAttribute('copy_id', copy.id());
1390 self.copyWidgetCache[copy.id()] = {};
1392 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1394 dojo.forEach(liDetailFields,
1397 if (field == "fund") {
1398 searchFilter = (copy.fund() ?
1399 {"-or": {"active": "t", "id": copy.fund()}} :
1402 searchFilter = null;
1405 var readOnly = false;
1407 // TODO: Add support for changing the owning_lib after real copies have been made.
1408 // owning_lib is order data as much as its item data
1409 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
1413 // TODO: add support for changing the fund after debits have been created
1414 // Note: invoicing allows the change
1415 if(copy.fund_debit() && field == 'fund') {
1419 var widget = new openils.widget.AutoFieldWidget({
1422 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1423 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1424 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1425 searchFilter : searchFilter,
1426 noCache: (field == "fund"),
1428 parentNode : dojo.query('[name='+field+']', row)[0],
1429 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
1430 readOnly : readOnly,
1433 // make sure we capture the value from any async widgets
1435 if (field == "fund" && w.store)
1436 self._ensureCSSFundClasses(w.store);
1437 copy[field](ww.getFormattedValue())
1438 self.copyWidgetCache[copy.id()][field] = w;
1441 dojo.connect(widget.widget, 'onChange',
1443 if (field == "fund")
1444 self._updateFundSelectorStyle(widget, val);
1446 if (copy.isnew() || val != copy[field]()) {
1447 // prevent setting ischanged() automatically on widget load for existing copies
1448 copy[field](widget.getFormattedValue())
1449 copy.ischanged(true);
1456 this.updateLidState(copy, row);
1459 this._ensureCSSFundClass = function(id) {
1460 if (!this.fundStyleSheet) {
1462 "style", {"type": "text/css"},
1463 document.getElementsByTagName("head")[0], "last"
1465 this.fundStyleSheet = document.styleSheets[
1466 document.styleSheets.length - 1
1470 var cn = "fund_" + id;
1471 if (!this.haveFundClass[cn]) {
1472 fieldmapper.standardRequest(
1473 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
1475 "params": [openils.User.authtoken, id],
1477 "oncomplete": function(r) {
1478 r = openils.Util.readResponse(r);
1479 self.fundBalanceState[id] = r;
1481 if (r[0] /* stop */)
1482 style = fundStyles.stop;
1483 else if (r[1] /* warning */)
1484 style = fundStyles.warning;
1485 self.fundStyleSheet.insertRule(
1486 "." + cn + " { " + style + " }",
1487 self.fundStyleSheet.cssRules.length
1489 self.haveFundClass[cn] = true;
1496 this._ensureCSSFundClasses = function(store) {
1498 "query": {"id": "*"},
1499 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
1503 this._updateFundSelectorStyle = function(widget, fund_id) {
1504 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
1505 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
1508 this.updateLidState = function(copy, row) {
1509 if (typeof(row) == "undefined") {
1511 'tr[copy_id="' + copy.id() + '"]', this.copyTbody
1516 var recv_link = nodeByName("receive", row);
1517 var unrecv_link = nodeByName("unreceive", row);
1518 var del_link = nodeByName("delete", row);
1519 var cxl_link = nodeByName("cancel", row);
1520 var claim_link = nodeByName("claim", row);
1521 var cxl_reason_link = nodeByName("cancel_reason", row);
1523 if (copy.cancel_reason()) {
1524 openils.Util.hide(del_link.parentNode);
1525 openils.Util.hide(recv_link);
1526 openils.Util.hide(unrecv_link);
1527 openils.Util.hide(cxl_link);
1528 openils.Util.hide(claim_link);
1530 /* XXX the following may leak memory in a long lived table: dijits may not get destroyed... not positive. revisit. */
1531 var holds_reason = dojo.create(
1533 "style": "border-bottom: 1px dashed #000;",
1534 "innerHTML": "Cancelled" /* XXX [sic] and i18n */
1535 }, cxl_reason_link, "only"
1539 "label": "<em>" + copy.cancel_reason().label() +
1540 "</em><br />" + copy.cancel_reason().description(),
1541 "connectId": [holds_reason]
1542 }, dojo.create("span", null, cxl_reason_link, "last")
1544 openils.Util.show(cxl_reason_link, "inline");
1545 } else if (this.isPO) {
1546 /* Only using this in one place so far, but may want it for better
1547 * decisions on when to display certain controls. */
1548 var li_state = this.liCache[copy.lineitem()].state();
1550 openils.Util.hide(del_link.parentNode);
1551 openils.Util.hide(cxl_reason_link);
1553 /* Avoid showing (un)receive links, cancel links, for virt copies */
1554 if (copy.id() > 0) {
1555 if (copy.recv_time()) {
1556 openils.Util.hide(cxl_link);
1557 openils.Util.hide(recv_link);
1558 openils.Util.hide(claim_link);
1560 openils.Util.show(unrecv_link, "inline");
1561 unrecv_link.onclick = function() {
1562 if (confirm(localeStrings.UNRECEIVE_LID))
1563 self.issueReceive(copy, /* rollback */ true);
1566 openils.Util.hide(unrecv_link);
1568 if (this.claimEligibleLid[copy.id()]) {
1569 openils.Util.show(claim_link, "inline");
1570 claim_link.onclick = function() {
1571 self.claimDialog.show(
1572 self.liCache[copy.lineitem()], copy.id()
1576 openils.Util.hide(claim_link);
1579 openils.Util[li_state == "on-order" ? "show" : "hide"](
1582 openils.Util.show(cxl_link, "inline");
1583 recv_link.onclick = function() {
1584 if (self.checkLiAlerts(copy.lineitem()))
1585 self.issueReceive(copy);
1587 cxl_link.onclick = function() {
1588 self.cancelLid(copy.id());
1592 openils.Util.hide(cxl_link);
1593 openils.Util.hide(unrecv_link);
1594 openils.Util.hide(recv_link);
1595 openils.Util.hide(claim_link);
1598 openils.Util.hide(unrecv_link);
1599 openils.Util.hide(recv_link);
1600 openils.Util.hide(cxl_reason_link);
1601 openils.Util.hide(claim_link);
1603 del_link.onclick = function() { self.deleteCopy(row) };
1604 openils.Util.show(del_link.parentNode);
1608 this.cancelLid = function(lid_id) {
1609 lidCancelDialog._lid_id = lid_id;
1610 openils.Util.show(lidCancelDialog.domNode.parentNode);
1611 lidCancelDialog.show();
1612 if (!lidCancelDialog._prepared) {
1613 var widget = new openils.widget.AutoFieldWidget({
1614 "fmField": "cancel_reason",
1615 "fmClass": "acqlid",
1616 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
1617 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1622 acqLidCancelButton.onClick = function() {
1623 if (w.attr("value")) {
1624 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
1626 lidCancelDialog._lid_id,
1630 lidCancelDialog.hide();
1633 lidCancelDialog._prepared = true;
1639 this._cancelLid = function(lid_id, reason) {
1640 fieldmapper.standardRequest(
1641 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
1642 "params": [openils.User.authtoken, lid_id, reason],
1644 "onresponse": function(r) {
1645 if (r = openils.Util.readResponse(r)) {
1647 for (var id in r.lid) {
1648 /* actually this should only iterate once */
1649 self.copyCache[id].cancel_reason(
1650 r.lid[id].cancel_reason
1652 self.updateLidState(self.copyCache[id]);
1661 this._confirmAlert = function(li, lin) {
1663 dojo.string.substitute(
1664 localeStrings.CONFIRM_LI_ALERT, [
1665 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1666 "title", "lineitem_marc_attr_definition"
1668 lin.alert_text().code(),
1669 lin.alert_text().description() || "",
1676 this.checkLiAlerts = function(li_id) {
1677 var li = this.liCache[li_id];
1679 var alert_notes = li.lineitem_notes().filter(
1680 function(o) { return Boolean(o.alert_text()); }
1683 /* this is _intentionally_ not done in a call to forEach() ... */
1684 for (var i = 0; i < alert_notes.length; i++) {
1685 if (this.noteAcks[alert_notes[i].id()])
1687 else if (!this._confirmAlert(li, alert_notes[i]))
1690 this.noteAcks[alert_notes[i].id()] = true;
1696 this.deleteCopy = function(row) {
1697 var copy = this.copyCache[row.getAttribute('copy_id')];
1698 copy.isdeleted(true);
1700 delete this.copyCache[copy.id()];
1701 this.copyTbody.removeChild(row);
1704 this._virtDfaCountsAsList = function() {
1706 for (var key in this.virtDfaCounts) {
1707 for (var i = 0; i < this.virtDfaCounts[key]; i++)
1713 this.confirmBreachedCopyFunds = function(copies) {
1714 var stop = 0, warning = 0;
1718 var state = self.fundBalanceState[o.fund()];
1719 if (state[0] /* stop */)
1721 else if (state[1] /* warning */)
1728 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
1729 } else if (warning) {
1730 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
1735 this.saveCopyChanges = function(liId) {
1741 for(var id in this.copyCache) {
1742 var c = this.copyCache[id];
1743 if(!c.isdeleted()) total++;
1744 if(c.isnew() || c.ischanged() || c.isdeleted()) {
1745 if(c.id() < 0) c.id(null);
1751 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
1754 if (copies.length > 0) {
1755 if (!this.confirmBreachedCopyFunds(copies))
1758 if (typeof(this._copy_count_cb) == "function")
1759 this._copy_count_cb(liId, total);
1761 openils.Util.show("acq-lit-update-copies-progress");
1762 fieldmapper.standardRequest(
1763 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1765 params: [openils.User.authtoken, copies],
1766 onresponse: function(r) {
1767 var res = openils.Util.readResponse(r);
1768 litUpdateCopiesProgress.update(res);
1770 oncomplete: function() {
1771 self.drawCopies(liId);
1772 openils.Util.hide("acq-lit-update-copies-progress");
1778 var dfa_list = this._virtDfaCountsAsList();
1779 if (dfa_list.length > 0) {
1780 fieldmapper.standardRequest(
1782 "open-ils.acq.distribution_formula.record_application"],
1785 "params": [openils.User.authtoken, dfa_list, liId],
1786 "onresponse": function(r) {
1787 var res = openils.Util.readResponse(r);
1788 if (res && res.length < dfa_list.length)
1789 alert(localeStrings.DFA_NOT_ALL);
1793 this.virtDfaCounts = {};
1797 this._updateCreatePoPrepayCheckbox = function(prepay) {
1798 var prepay = openils.Util.isTrue(prepay);
1799 this._prepayRequiredByVendor = prepay;
1800 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
1803 this._confirmPoPrepaySituation = function() {
1804 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
1805 if (want_prepay != this._prepayRequiredByVendor) {
1808 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
1809 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
1816 this.applySelectedLiAction = function(action) {
1820 case 'delete_selected':
1821 this._deleteLiList(self.getSelected());
1824 case 'create_order':
1826 if(!this.createPoProviderSelector) {
1827 var widget = new openils.widget.AutoFieldWidget({
1828 fmField : 'provider',
1830 searchFilter: {"active": "t"},
1831 parentNode : dojo.byId('acq-lit-po-provider'),
1833 "onChange": function() {
1835 self._updateCreatePoPrepayCheckbox(
1836 this.item.prepayment_required
1843 function(w) { self.createPoProviderSelector = w; }
1847 if(!this.createPoAgencySelector) {
1848 var widget = new openils.widget.AutoFieldWidget({
1849 fmField : 'ordering_agency',
1851 parentNode : dojo.byId('acq-lit-po-agency'),
1852 orgLimitPerms : ['CREATE_PURCHASE_ORDER'],
1855 function(w) { self.createPoAgencySelector = w; }
1860 acqLitPoCreateDialog.show();
1863 case 'save_picklist':
1864 this._loadPLSelect();
1865 acqLitSavePlDialog.show();
1868 case 'selector_ready':
1870 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
1871 acqLitChangeLiStateDialog.show();
1879 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
1886 case 'rollback_receive_po':
1887 this.rollbackPoReceive();
1890 case 'create_assets':
1891 this.createAssets();
1894 case 'export_attr_list':
1895 this.chooseExportAttr();
1898 case 'add_brief_record':
1900 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
1902 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
1906 case "cancel_lineitems":
1907 this.maybeCancelLineitems();
1910 case "change_claim_policy":
1911 var li_list = this.getSelected();
1912 this.claimPolicyPicker.attr("value", null);
1913 liClaimPolicyDialog.show();
1914 liClaimPolicySave.onClick = function() {
1915 self.changeClaimPolicy(
1917 self.claimPolicyPicker.attr("value"),
1920 function(li) { self.setClaimPolicyControl(li); }
1922 liClaimPolicyDialog.hide();
1930 this.changeClaimPolicy = function(li_list, value, callback) {
1932 function(li) { li.claim_policy(value); }
1934 fieldmapper.standardRequest(
1935 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
1936 "params": [openils.User.authtoken, li_list],
1938 "oncomplete": function(r) {
1939 r = openils.Util.readResponse(r);
1940 if (callback) callback(r);
1946 this.createAssets = function() {
1947 if(!this.isPO) return;
1948 if(!confirm(localeStrings.CREATE_PO_ASSETS_CONFIRM)) return;
1949 this.show('acq-lit-progress-numbers');
1951 fieldmapper.standardRequest(
1952 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
1954 params: [this.authtoken, this.isPO],
1955 onresponse: function(r) {
1956 var resp = openils.Util.readResponse(r);
1957 self._updateProgressNumbers(resp, true);
1963 this.maybeCancelLineitems = function() {
1964 openils.Util.show("acq-lit-cancel-reason", "inline");
1965 if (!acqLitCancelLineitemsButton._prepared) {
1966 var widget = new openils.widget.AutoFieldWidget({
1967 "fmField": "cancel_reason",
1969 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
1970 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1975 acqLitCancelLineitemsButton.onClick = function() {
1976 if (w.attr("value")) {
1977 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
1978 self._cancelLineitems(w.attr("value"));
1980 openils.Util.hide("acq-lit-cancel-reason");
1983 acqLitCancelLineitemsButton._prepared = true;
1989 this._cancelLineitems = function(reason) {
1990 var id_list = this.getSelected().map(function(o) { return o.id(); });
1991 fieldmapper.standardRequest(
1992 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
1993 "params": [openils.User.authtoken, id_list, reason],
1995 "onresponse": function(r) {
1996 if (r = openils.Util.readResponse(r)) {
1998 for (var id in r.li) {
1999 self.liCache[id].state(r.li[id].state);
2000 self.liCache[id].cancel_reason(
2001 r.li[id].cancel_reason
2003 self.updateLiState(self.liCache[id]);
2006 if (r.lid && self.copyCache) {
2007 for (var id in r.lid) {
2008 if (self.copyCache[id]) {
2009 self.copyCache[id].cancel_reason(
2010 r.lid[id].cancel_reason
2012 self.updateLidState(self.copyCache[id]);
2022 this.chooseExportAttr = function() {
2023 if (!acqLitExportAttrSelector._li_setup) {
2025 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
2027 "data": acqliad.toStoreData(
2029 "acqliad", {"code": li_exportable_attrs}
2034 acqLitExportAttrSelector.setValue();
2035 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
2036 acqLitExportAttrSelector._li_setup = true;
2038 openils.Util.show("acq-lit-export-attr-holder", "inline");
2041 this.exportAttrList = function() {
2042 var attr_def = acqLitExportAttrSelector.item;
2043 var li_list = this.getSelected();
2044 var value_list = li_list.map(
2046 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2047 attr_def.code, "lineitem_marc_attr_definition"
2050 ).filter(function(attr) { return Boolean(attr); });
2052 if (value_list.length > 0) {
2053 if (value_list.length < li_list.length) {
2055 dojo.string.substitute(
2056 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
2063 openils.XUL.contentToFileSaveDialog(
2064 value_list.join("\n"),
2065 localeStrings.EXPORT_SAVE_DIALOG_TITLE
2071 alert(dojo.string.substitute(
2072 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
2076 openils.Util.hide("acq-lit-export-attr-holder");
2079 this.printPO = function() {
2080 if(!this.isPO) return;
2081 progressDialog.show(true);
2082 fieldmapper.standardRequest(
2083 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
2085 params: [this.authtoken, this.isPO, 'html'],
2086 oncomplete: function(r) {
2087 progressDialog.hide();
2088 var evt = openils.Util.readResponse(r);
2089 if(evt && evt.template_output()) {
2090 win = window.open('','', 'resizable,width=800,height=600,scrollbars=1');
2091 win.document.body.innerHTML = evt.template_output().data();
2099 this.receivePO = function() {
2100 if (!this.isPO) return;
2102 for (var id in this.liCache) {
2103 /* assumption: liCache reflects exactly the
2104 * set of LIs that belong to our PO */
2105 if (this.liCache[id].state() != "received" &&
2106 !this.checkLiAlerts(id)) return;
2109 this.show('acq-lit-progress-numbers');
2111 fieldmapper.standardRequest(
2112 ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
2114 params: [this.authtoken, this.isPO],
2115 onresponse : function(r) {
2116 var resp = openils.Util.readResponse(r);
2117 self._updateProgressNumbers(resp, true);
2123 this.issueReceive = function(obj, rollback) {
2124 /* (For now) there shall be no marking LI or LIDs (un)received
2125 * except from the actual "view PO" interface. */
2126 if (!this.isPO) return;
2129 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
2131 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
2133 progressDialog.show(true);
2134 fieldmapper.standardRequest(
2135 ["open-ils.acq", method], {
2137 "params": [this.authtoken, obj.id()],
2138 "onresponse": function(r) {
2139 if (r = openils.Util.readResponse(r)) {
2140 self.fetchClaimInfo(
2141 part == "lineitem" ? obj.id() : obj.lineitem(),
2143 function() { self.handleReceive(r); }
2145 progressDialog.hide();
2153 * Handles the responses from receive and rollback ML calls.
2155 this.handleReceive = function(resp) {
2158 for (var li_id in resp.li) {
2159 for (var key in resp.li[li_id])
2160 self.liCache[li_id][key](resp.li[li_id][key]);
2161 self.updateLiState(self.liCache[li_id]);
2165 if (typeof(self.poUpdateCallback) == "function")
2166 self.poUpdateCallback(resp.po);
2169 for (var lid_id in resp.lid) {
2170 for (var key in resp.lid[lid_id])
2171 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
2172 self.updateLidState(self.copyCache[lid_id]);
2178 this.rollbackPoReceive = function() {
2179 if(!this.isPO) return;
2180 if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
2181 this.show('acq-lit-progress-numbers');
2183 fieldmapper.standardRequest(
2184 ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
2186 params: [this.authtoken, this.isPO],
2187 onresponse : function(r) {
2188 var resp = openils.Util.readResponse(r);
2189 self._updateProgressNumbers(resp, true);
2195 this._updateProgressNumbers = function(resp, reloadOnComplete) {
2197 dojo.byId('acq-pl-lit-li-processed').innerHTML = resp.li;
2198 dojo.byId('acq-pl-lit-lid-processed').innerHTML = resp.lid;
2199 dojo.byId('acq-pl-lit-debits-processed').innerHTML = resp.debits_accrued;
2200 dojo.byId('acq-pl-lit-bibs-processed').innerHTML = resp.bibs;
2201 dojo.byId('acq-pl-lit-indexed-processed').innerHTML = resp.indexed;
2202 dojo.byId('acq-pl-lit-copies-processed').innerHTML = resp.copies;
2203 if(resp.complete && reloadOnComplete)
2204 location.href = location.href;
2208 this._createPO = function(fields) {
2209 this.show('acq-lit-progress-numbers');
2210 var po = new fieldmapper.acqpo();
2211 po.provider(this.createPoProviderSelector.attr('value'));
2212 po.ordering_agency(this.createPoAgencySelector.attr('value'));
2213 po.prepayment_required(fields.prepayment_required[0] ? true : false);
2215 var selected = this.getSelected( (fields.create_from == 'all') );
2216 if(selected.length == 0) return;
2218 var max = selected.length * 3;
2221 fieldmapper.standardRequest(
2222 ['open-ils.acq', 'open-ils.acq.purchase_order.create'],
2225 openils.User.authtoken,
2228 lineitems : selected.map(function(li) { return li.id() }),
2229 create_assets : fields.create_assets[0],
2233 onresponse : function(r) {
2234 var resp = openils.Util.readResponse(r);
2235 self._updateProgressNumbers(resp);
2237 location.href = oilsBasePath + '/acq/po/view/' + resp.purchase_order.id();
2243 this._deleteLiList = function(list, idx) {
2244 if(idx == null) idx = 0;
2245 if(idx >= list.length) return;
2246 var liId = list[idx].id();
2247 fieldmapper.standardRequest(
2248 ['open-ils.acq', 'open-ils.acq.lineitem.delete'],
2250 params: [openils.User.authtoken, liId],
2251 oncomplete: function(r) {
2252 self.removeLineitem(liId);
2253 self._deleteLiList(list, ++idx);
2259 this.editOrderMarc = function(li) {
2261 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
2262 to true in about:config */
2264 if(!openils.XUL.enableXPConnect()) return;
2266 if(openils.XUL.isXUL()) {
2267 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
2269 win = window.open('/xul/server/cat/marcedit.xul');
2273 record : {marc : li.marc()},
2275 label: 'Save Record', // XXX I18N
2276 func: function(xmlString) {
2278 fieldmapper.standardRequest(
2279 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
2281 params: [openils.User.authtoken, li],
2282 oncomplete: function(r) {
2283 openils.Util.readResponse(r);
2285 self.drawInfo(li.id())
2294 this._savePl = function(values) {
2296 var selected = this.getSelected( (values.which == 'all') );
2297 openils.Util.show('acq-lit-generic-progress');
2299 if(values.new_name) {
2300 openils.acq.Picklist.create(
2301 {name: values.new_name},
2303 self._updateLiList(id, selected, 0,
2305 location.href = oilsBasePath + '/acq/picklist/view/' + id;
2309 } else if(values.existing_pl) {
2310 // update lineitems to use an existing picklist
2311 self._updateLiList(values.existing_pl, selected, 0,
2313 location.href = oilsBasePath + '/acq/picklist/view/' + values.existing_pl;
2318 this._updateLiState = function(values, state) {
2320 var selected = this.getSelected( (values.which == 'all') );
2321 if(!selected.length) return;
2322 dojo.forEach(selected, function(li) {li.state(state);});
2323 self._updateLiList(null, selected, 0,
2324 // TODO consider inline updates for efficiency
2325 function() { location.href = location.href }
2329 this._updateLiList = function(pl, list, idx, oncomplete) {
2330 if(idx >= list.length) return oncomplete();
2332 if(pl != null) li.picklist(pl);
2333 litGenericProgress.update({maximum: list.length, progress: idx});
2334 new openils.acq.Lineitem({lineitem:li}).update(
2336 self._updateLiList(pl, list, ++idx, oncomplete);
2341 this._loadPLSelect = function() {
2342 if(this._plSelectLoaded) return;
2344 function handleResponse(r) {
2345 plList.push(r.recv().content());
2347 var method = 'open-ils.acq.picklist.user.retrieve';
2348 fieldmapper.standardRequest(
2349 ['open-ils.acq', method],
2351 params: [this.authtoken],
2352 onresponse: handleResponse,
2353 oncomplete: function() {
2354 self._plSelectLoaded = true;
2355 acqLitAddExistingSelect.store =
2356 new dojo.data.ItemFileReadStore({data:acqpl.toStoreData(plList)});
2357 acqLitAddExistingSelect.setValue();
2363 this.showRealCopyEditUI = function(li) {
2368 this._fetchLineitem(li.id(),
2370 li = self.liCache[li.id()] = fullLi;
2374 id : li.lineitem_details().map(
2375 function(item) { return item.eg_copy_id() }
2379 oncomplete : function(r) {
2381 var r_list = openils.Util.readResponse( r );
2382 for (var i = 0; i < r_list.length; i++) {
2383 var copy = r_list[i];
2384 var volId = copy.call_number();
2385 var volume = self.volCache[volId];
2387 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2389 copy.call_number(volume);
2390 copyList.push(copy);
2393 // If we need to, we can pass in an update_copy function to handle the update instead of volume_item_creator
2394 xulG.volume_item_creator( { 'existing_copies' : copyList } );
2397 alert('error in oncomplete: ' + E);