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 || this.isUni)) {
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()]});
310 openils.Util.show(nodeByName("bib_origin", row), "inline");
312 openils.Util.show(nodeByName('pl', row), 'inline');
313 var link = nodeByName('pl_link', row);
314 link.setAttribute('href', oilsBasePath + '/acq/picklist/view/' + li.picklist());
315 link.innerHTML = 'PL: '+pl.name(); // TODO i18n
319 var countNode = nodeByName('count', row);
320 var count = li.item_count() || 0;
321 if (typeof(this._copy_count_cb) == "function") {
322 this._copy_count_cb(li.id(), count);
324 countNode.innerHTML = count;
325 countNode.id = 'acq-lit-copy-count-label-' + li.id();
328 var priceInput = dojo.query('[name=price]', row)[0];
329 priceInput.value = li.estimated_unit_price() || '';
330 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
332 // show either "mark received" or "unreceive" as appropriate
333 this.updateLiState(li, row);
335 if (!skip_final_placement) {
336 self.tbody.appendChild(row);
337 self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
343 this._liCountClaims = function(li) {
345 for (var i = 0; i < li.lineitem_details().length; i++)
346 total += li.lineitem_details()[i].claims().length;
350 this._findLiRow = function(li) {
351 return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
354 this.reconsiderClaimControl = function(li, row) {
355 var option = nodeByName("action_manage_claims", row);
356 var eligible = this.claimEligibleLidByLi[li.id()].length;
357 var count = this._liCountClaims(li);
358 if (!row) row = this._findLiRow(li);
360 option.disabled = !(count || eligible);
362 dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
363 option.onclick = function() { self.claimDialog.show(li); };
366 this.clearEligibility = function(li) {
367 this.claimEligibleLidByLi[li.id()] = [];
369 if (li.lineitem_details()) {
370 li.lineitem_details().forEach(
371 function(lid) { delete self.claimEligibleLid[lid.id()]; }
375 if (this.copyCache) {
377 for (var k in this.copyCache) {
378 if (this.copyCache[k].lineitem() == li.id())
382 function(k) { delete self.claimEligibleLid[k]; }
387 this.checkClaimEligibility = function(li, callback, row) {
388 this.clearEligibility(li);
389 fieldmapper.standardRequest(
390 ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
391 "params": [openils.User.authtoken, {"lineitem": li.id()}],
393 "onresponse": function(r) {
394 if (r = openils.Util.readResponse(r)) {
395 self.claimEligibleLidByLi[li.id()].push(
398 self.claimEligibleLid[r.lineitem_detail()] = true;
401 "oncomplete": function() {
402 self.reconsiderClaimControl(li, row);
403 if (typeof(callback) == "function")
410 this.updateLiNotesCount = function(li, row) {
411 if (!row) row = this._findLiRow(li);
413 var has_notes = (li.lineitem_notes().filter(
414 function(o) { return Boolean (o.alert_text()); }
417 /* U+2691 is the code point for a filled-in flag character */
418 nodeByName("notes_alert_flag", row).innerHTML =
419 has_notes ? "⚑" : "";
420 nodeByName("noteslink", row).style.fontStyle =
421 has_notes ? "italic" : "normal";
422 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
425 /* XXX NOT related to _updateLiState(). rethink */
426 this.updateLiState = function(li, row) {
427 if (!row) row = this._findLiRow(li);
429 var actReceive = nodeByName("action_mark_recv", row);
430 var actUnRecv = nodeByName("action_mark_unrecv", row);
431 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
432 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
434 var actNewInvoice = nodeByName('action_new_invoice', row);
435 var actLinkInvoice = nodeByName('action_link_invoice', row);
436 var actViewInvoice = nodeByName('action_view_invoice', row);
438 nodeByName('action_view_history', row).onclick =
439 function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
441 var state_cell = nodeByName("li_state", row);
443 if (li.state() == "cancelled") {
444 if (typeof li.cancel_reason() == "object") {
445 var holds_state = dojo.create(
447 "style": "border-bottom: 1px dashed #000;",
448 "innerHTML": li.state()
449 }, state_cell, "only"
453 "label": "<em>" + li.cancel_reason().label() +
454 "</em><br />" + li.cancel_reason().description(),
455 "connectId": [holds_state]
456 }, dojo.create("span", null, state_cell, "last")
459 state_cell.innerHTML = li.state(); // TODO i18n state labels
462 state_cell.innerHTML = li.state(); // TODO i18n state labels
466 /* handle row coloring for based on LI state */
467 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
468 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
470 /* handle links that appear/disappear based on whether LI is received */
474 actNewInvoice.onclick = function() {
475 location.href = oilsBasePath + '/acq/invoice/view?create=1&attach_li=' + li.id();
476 nodeByName("action_none", row).selected = true;
478 actLinkInvoice.onclick = function() {
479 self.invoiceLinkDialogManager.target = li;
480 acqLitLinkInvoiceDialog.show();
481 nodeByName("action_none", row).selected = true;
483 actViewInvoice.onclick = function() {
484 location.href = oilsBasePath +
485 "/acq/search/unified?so=" +
486 base64Encode({"jub":[{"id": li.id()}]}) +
488 nodeByName("action_none", row).selected = true;
491 actNewInvoice.disabled = false;
492 actLinkInvoice.disabled = false;
493 actViewInvoice.disabled = false;
497 actReceive.disabled = false;
498 actReceive.onclick = function() {
499 if (self.checkLiAlerts(li.id()))
500 self.issueReceive(li);
501 nodeByName("action_none", row).selected = true;
506 actUnRecv.disabled = false;
507 actUnRecv.onclick = function() {
508 if (confirm(localeStrings.UNRECEIVE_LI))
509 self.issueReceive(li, /* rollback */ true);
510 nodeByName("action_none", row).selected = true;
512 // TODO we should allow editing before receipt, in which case the
513 // test should be "if 1 or more real (acp) copies exist
514 actUpdateBarcodes.disabled = false;
515 actUpdateBarcodes.onclick = function() {
516 self.showRealCopyEditUI(li);
517 nodeByName("action_none", row).selected = true;
519 actHoldingsMaint.disabled = false;
520 actHoldingsMaint.onclick = self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
528 this._setAlertStore = function() {
529 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
531 "data": acqliat.toStoreData(
533 "acqliat", {"id": {"!=": null}}
538 acqLitAlertAlertText.setValue(); /* make the store "live" */
539 acqLitAlertAlertText._store_ready = true;
543 * Draws and shows the lineitem notes pane
545 this.drawLiNotes = function(li) {
548 if (!acqLitAlertAlertText._store_ready)
549 this._setAlertStore();
552 li.lineitem_notes().sort(
554 if(a.edit_time() < b.edit_time()) return 1;
560 while(this.liNotesTbody.childNodes[0])
561 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
564 acqLitCreateNoteSubmit.onClick = function() {
565 var value = acqLitCreateNoteText.attr('value');
567 var note = new fieldmapper.acqlin();
570 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
573 note.lineitem(li.id());
575 self.updateLiNotes(li, note);
576 acqLitCreateNoteVendorPublic.attr("checked", false);
577 acqLitCreateNoteText.attr("value", "");
580 acqLitCreateAlertSubmit.onClick = function() {
581 if (!acqLitAlertAlertText.item) {
582 alert(localeStrings.ALERT_UNSELECTED);
586 var alert_text = new fieldmapper.acqliat().fromStoreItem(
587 acqLitAlertAlertText.item
589 var value = acqLitAlertNoteValue.attr("value") || "";
591 var note = new fieldmapper.acqlin();
593 note.lineitem(li.id());
595 note.alert_text(alert_text);
597 self.updateLiNotes(li, note);
600 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
604 * Draws a single lineitem note in the notes pane
606 this.addLiNote = function(li, note) {
607 if(note.isdeleted()) return;
609 var row = self.liNotesRow.cloneNode(true);
610 nodeByName("value", row).innerHTML = note.value();
611 var alert_node = nodeByName("alert_code", row);
612 if (note.alert_text()) {
613 alert_node.innerHTML = note.alert_text().code();
614 if (note.alert_text().description()) {
617 "connectId": [alert_node],
618 "label": note.alert_text().description()
619 }, dojo.create("span", null, alert_node, "after")
624 if (openils.Util.isTrue(note.vendor_public()))
625 nodeByName("vendor_public", row).innerHTML =
626 localeStrings.VENDOR_PUBLIC;
628 nodeByName("delete", row).onclick = function() {
629 note.isdeleted(true);
630 self.liNotesTbody.removeChild(row);
631 self.updateLiNotes(li);
634 if(note.edit_time()) {
635 nodeByName("edit_time", row).innerHTML =
636 dojo.date.locale.format(
637 dojo.date.stamp.fromISOString(note.edit_time()),
638 {formatLength:'short'});
641 self.liNotesTbody.appendChild(row);
645 * Updates any new/changed/deleted notes on the server
647 this.updateLiNotes = function(li, newNote) {
653 notes = li.lineitem_notes().filter(
655 if(note.ischanged() || note.isnew() || note.isdeleted())
661 if(notes.length == 0) return;
662 progressDialog.show();
664 fieldmapper.standardRequest(
665 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
667 params : [this.authtoken, notes],
668 onresponse : function(r) {
669 var resp = openils.Util.readResponse(r);
674 // remove the old changed notes
676 dojo.forEach(li.lineitem_notes(),
678 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
682 li.lineitem_notes(list);
685 progressDialog.hide();
686 self.updateLiNotesCount(li);
687 self.drawLiNotes(li);
691 progressDialog.update(resp);
692 var newnote = resp.note;
694 if(!newnote.isdeleted()) {
695 newnote.isnew(false);
696 newnote.ischanged(false);
697 li.lineitem_notes().push(newnote);
704 this.updateLiPrice = function(input, li) {
706 var price = input.value;
707 if(Number(price) == Number(li.estimated_unit_price())) return;
709 fieldmapper.standardRequest(
710 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
712 params : [this.authtoken, li.id(), price],
713 oncomplete : function(r) {
714 openils.Util.readResponse(r);
715 li.estimated_unit_price(price); // update local copy
721 this.removeLineitem = function(liId) {
722 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
723 delete this.liCache[liId];
724 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
727 this.drawInfo = function(liId) {
728 if (!this._isRelatedViewer) {
729 var d = dojo.byId("acq-lit-info-related");
730 if (!this.relCache[liId]) {
731 fieldmapper.standardRequest(
734 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
737 "params": [openils.User.authtoken, liId],
738 "onresponse": function(r) {
739 self.relCache[liId] = openils.Util.readResponse(r);
740 nodeByName("related_number", d).innerHTML =
743 self.relCache[liId] >1 ? "show" : "hide"
749 nodeByName("related_number", d).innerHTML = this.relCache[liId];
750 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
755 openils.acq.Lineitem.fetchAttrDefs(
757 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
762 this._fetchLineitem = function(liId, handler, force) {
764 var li = this.liCache[liId];
765 if(li && li.marc() && li.lineitem_details() && !force)
768 fieldmapper.standardRequest(
769 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve'],
772 params: [self.authtoken, liId, {
774 flesh_cancel_reason: true,
775 flesh_li_details: true,
777 flesh_fund_debit: true }],
779 oncomplete: function(r) {
780 var li = openils.Util.readResponse(r);
787 this._drawInfo = function(li) {
789 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
792 openils.Util.hide('acq-lit-marc-order-record-label');
793 openils.Util.hide(acqLitEditOrderMarc.domNode);
794 openils.Util.show('acq-lit-marc-real-record-label');
796 openils.Util.show('acq-lit-marc-order-record-label');
797 openils.Util.show(acqLitEditOrderMarc.domNode);
798 openils.Util.hide('acq-lit-marc-real-record-label');
801 this.drawMarcHTML(li);
802 this.infoTbody = dojo.byId('acq-lit-info-tbody');
805 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
806 while(this.infoTbody.childNodes[0])
807 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
809 for(var i = 0; i < li.attributes().length; i++) {
810 var attr = li.attributes()[i];
811 var row = this.infoRow.cloneNode(true);
813 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
814 var name = openils.acq.Lineitem.attrDefs[type].filter(
816 return (a.code() == attr.attr_name());
818 ).pop().description();
820 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
821 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
822 this.infoTbody.appendChild(row);
825 if (!this._isRelatedViewer) {
826 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
827 oilsBasePath + "/acq/lineitem/related/" + li.id();
832 openils.Util.show('acq-lit-info-cat-link');
833 var link = dojo.byId('acq-lit-info-cat-link').getElementsByTagName('a')[0];
835 if(openils.XUL.isXUL()) {
837 link.setAttribute('href', 'javascript:void(0);');
838 link.onclick = this.generateMakeRecTab( li.eg_bib_id() );
841 var href = link.getAttribute('href');
843 link.setAttribute('href', href + li.eg_bib_id());
846 openils.Util.hide('acq-lit-info-cat-link');
850 this.generateMakeRecTab = function(bib_id,default_view, row) {
854 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
857 show_nav_buttons : true,
858 show_print_button : true,
859 opac_url : xulG.url_prefix(xulG.urls.opac_rdetail + '?r=' + bib_id),
860 default_view : default_view
864 if(row) nodeByName("action_none", row).selected = true;
868 this.drawMarcHTML = function(li) {
869 var params = [null, true, li.marc()];
871 params = [li.eg_bib_id(), true];
873 fieldmapper.standardRequest(
874 ['open-ils.search', 'open-ils.search.biblio.record.html'],
877 oncomplete: function(r) {
878 dojo.byId('acq-lit-marc-div').innerHTML =
879 openils.Util.readResponse(r);
885 this.drawCopies = function(liId) {
889 this.copyWidgetCache = {};
890 this.oldCopyWidgetCache = {};
891 this.virtDfaCounts = {};
892 this.realDfaCache = {};
895 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
896 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
897 acqLitCopyCountInput.attr('value', '0');
899 while(this.copyTbody.childNodes[0])
900 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
902 this._drawBatchCopyWidgets();
904 this._drawDistribApplied(liId);
906 this._fetchDistribFormulas(
908 openils.acq.Lineitem.fetchAttrDefs(
910 self._fetchLineitem(liId, function(li){self._drawCopies(li);});
917 this._saveDistribAppliedTemplates = function() {
918 if (!this._appliedDistribTemplate) {
919 this._appliedDistribTemplate =
920 dojo.byId("acq-lit-distrib-applied-tbody").
921 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
922 dojo.attr(this._appliedDistribTemplate, "id");
926 this._drawDistribApplied = function(liId) {
927 /* Build this table while hidden to prevent rendering artifacts */
928 openils.Util.hide("acq-lit-distrib-applied-tbody");
930 this._saveDistribAppliedTemplates();
932 /* Remove any rows in the table from previous populations */
933 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
934 forEach(dojo.destroy);
936 /* Unregister all dijits previously created (for some reason this isn't
937 * covered by the above destroy calls). */
938 dijit.registry.forEach(
939 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
942 /* Populate the table with our liId */
944 fieldmapper.standardRequest(
946 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
949 "params": [self.authtoken, liId],
950 "onresponse": function(r) {
951 var dfa = openils.Util.readResponse(r);
954 self.realDfaCache[dfa.id()] = dfa;
955 self._drawDistribAppliedUnit(dfa);
958 "oncomplete": function() {
959 /* Reveal built table */
962 "acq-lit-distrib-applied-tbody", "table-row-group"
970 this._drawDistribAppliedUnit = function(dfa) {
972 var row = dojo.query(
973 'tr[formula="' + dfa.formula().id() + '"]',
974 "acq-lit-distrib-applied-tbody"
979 row = dojo.clone(this._appliedDistribTemplate);
980 dojo.attr(row, "formula", dfa.formula().id());
981 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
984 var td = dojo.query("td", row)[0];
986 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
987 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
990 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
992 new dijit.form.Button(
994 "onClick": function() {
995 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
999 /* XXX I /cannot/ make the following work in as a CSS class
1000 * for some reason. So frustrating... */
1001 "style": function(id) {
1003 "font-weight: bold; color: #c00;" :
1005 }(dfa.id()) + "margin: 0 6px;display: inline;"
1006 }, "dfa-button-" + dfa.id()
1010 "connectId": ["dfa-button-" + dfa.id()],
1011 "label": dojo.string.substitute(
1012 localeStrings.DFA_TIP, dfa.id() > 0 ? [
1013 openils.User.formalName(dfa.creator()),
1014 dojo.date.locale.format(
1015 dojo.date.stamp.fromISOString(dfa.create_time()),
1016 {"formatLength":"short"}
1018 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
1020 }, "dfa-tip-" + dfa.id()
1024 this.deleteDfa = function(dfa) {
1025 if (dfa.id() > 0) { /* real */
1026 this.pcrud.eliminate(
1029 "oncomplete": function() {
1030 self._removeDistribApplied(dfa.id());
1031 delete self.realDfaCache[dfa.id()];
1035 } else { /* virtual */
1036 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
1037 this.virtDfaCounts[dfa.formula().id()] = 0;
1038 /* hasn't been saved yet, so no need to do anything server side */
1039 this._removeDistribApplied(dfa.id());
1044 this._removeDistribApplied = function(dfaId) {
1045 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
1046 dijit.registry.forEach(
1047 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
1049 this._removeDistribAppliedEmptyRows();
1052 this._removeAllDistribAppliedVirtual = function() {
1053 /* Unregister dijits */
1054 dijit.registry.forEach(
1055 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
1057 this._removeDistribAppliedEmptyRows();
1060 this._removeDistribAppliedEmptyRows = function() {
1061 /* Remove any rows with no DFA at all */
1062 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
1064 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
1070 * Insert a new row into the distribution formula selection form
1072 this._addDistribFormulaRow = function() {
1075 if (!self.distribForms) {
1076 // no formulas, hide the form
1077 openils.Util.hide('acq-lit-distrib-formula-tbody');
1081 if(!this.distribFormulaTemplate)
1082 this.distribFormulaTemplate =
1083 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
1085 var row = this.distribFormulaTemplate.cloneNode(true);
1086 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
1088 this.dfSelector = new dijit.form.FilteringSelect(
1089 {"labelAttr": "dynLabel", "labelType": "html"},
1090 nodeByName("selector", row)
1092 this._updateFormulaStore();
1093 this.dfSelector.fetchProperties =
1094 {"sort": [{"attribute": "use_count", "descending": true}]};
1096 var apply = new dijit.form.Button(
1097 {"label": localeStrings.APPLY},
1098 nodeByName('set_button', row)
1101 var reset = new dijit.form.Button(
1102 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
1103 nodeByName("reset_button", row)
1106 dojo.connect(apply, 'onClick',
1108 var form_id = self.dfSelector.attr("value");
1109 if(!form_id) return;
1110 self._applyDistribFormula(form_id);
1111 reset.attr("disabled", false);
1115 dojo.connect(reset, 'onClick',
1117 self.restoreCopyFieldsBeforeDF();
1118 self.virtDfaCounts = {};
1119 self.virtDfaId = -1;
1121 self._updateFormulaStore();
1122 self._removeAllDistribAppliedVirtual();
1123 reset.attr("disabled", "true");
1130 * Applies a distrib formula to the current set of copies
1132 this._applyDistribFormula = function(formula) {
1133 if(!formula) return;
1135 formula = this.distribForms.filter(
1136 function(form) { return form.id() == formula; }
1139 var copyRows = dojo.query('tr', self.copyTbody);
1141 if (this.dfeOffset >= copyRows.length) {
1142 alert(localeStrings.OUT_OF_COPIES);
1146 var entries_applied = 0;
1148 var rowIndex = this.dfeOffset;
1149 rowIndex < copyRows.length;
1153 var row = copyRows[rowIndex];
1154 var copy_id = row.getAttribute('copy_id');
1155 var copyWidgets = this.copyWidgetCache[copy_id];
1156 var entryIndex = this.dfeOffset;
1159 // find the correct entry for the current row
1160 dojo.forEach(formula.entries(),
1163 entryIndex += e.item_count();
1164 if(entryIndex > rowIndex)
1172 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
1173 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
1176 this.saveCopyFieldsBeforeDF(copy_id);
1177 this._copy_fields_for_acqdf.forEach(
1179 if(entry[field]()) {
1180 copyWidgets[field].attr('value', (entry[field]()));
1187 if (entries_applied) {
1188 this.virtDfaCounts[formula.id()] =
1189 ++(this.virtDfaCounts[formula.id()]) || 1;
1190 this._updateFormulaStore();
1191 this._drawDistribAppliedUnit(
1193 var dfa = new acqdfa();
1194 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
1197 this.dfeOffset += entries_applied;
1202 * This function updates the DF store for the dropdown so that use_counts
1203 * can reflect DF applications from this session before they're saved
1206 this._updateFormulaStore = function() {
1207 this.dfSelector.store = new dojo.data.ItemFileReadStore(
1209 "data": self._labelFormulasWithCounts(
1210 acqdf.toStoreData(self.distribForms)
1216 this.saveCopyFieldsBeforeDF = function(copy_id) {
1218 if (!this.oldCopyWidgetCache[copy_id]) {
1219 var copyWidgets = this.copyWidgetCache[copy_id];
1221 this.oldCopyWidgetCache[copy_id] = {};
1222 this._copy_fields_for_acqdf.forEach(
1224 self.oldCopyWidgetCache[copy_id][f] =
1225 copyWidgets[f].attr("value");
1231 this.restoreCopyFieldsBeforeDF = function() {
1233 for (var copy_id in this.oldCopyWidgetCache) {
1234 this._copy_fields_for_acqdf.forEach(
1236 self.copyWidgetCache[copy_id][f].attr(
1237 "value", self.oldCopyWidgetCache[copy_id][f]
1244 this._labelFormulasWithCounts = function(store_data) {
1245 for (var key in store_data.items) {
1246 var obj = store_data.items[key];
1247 obj.use_count = Number(obj.use_count); /* needed for sorting */
1249 if (this.virtDfaCounts[obj.id])
1250 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
1252 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
1253 obj.use_count + "]</span> " + obj.name;
1259 * This method formerly would not refetch the DF formulas if they'd been
1260 * loaded already, but now it always re-fetches, since use_count changes.
1262 this._fetchDistribFormulas = function(onload) {
1263 fieldmapper.standardRequest(
1265 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
1268 "params": [openils.User.authtoken],
1269 "oncomplete": function(r) {
1270 self.distribForms = openils.Util.readResponse(r);
1271 if(!self.distribForms || self.distribForms.length == 0) {
1272 self.distribForms = [];
1274 self._addDistribFormulaRow();
1281 this._drawBatchCopyWidgets = function() {
1282 var row = this.copyBatchRow;
1283 dojo.forEach(liDetailBatchFields,
1285 if(self.copyBatchRowDrawn) {
1286 self.copyBatchWidgets[field].attr('value', null);
1288 var widget = new openils.widget.AutoFieldWidget({
1291 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1292 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1293 searchFilter : (field == 'fund') ? {"active": "t"} : null,
1294 parentNode : dojo.query('[name='+field+']', row)[0],
1295 orgLimitPerms : ['CREATE_PICKLIST'],
1298 "labelType": (field == "fund") ? "html" : null
1300 noCache: (field == "fund"),
1305 if (field == "fund" && w.store)
1306 self._ensureCSSFundClasses(w.store);
1307 self.copyBatchWidgets[field] = w;
1310 if (field == "fund") {
1312 widget.widget, "onChange", function(val) {
1313 self._updateFundSelectorStyle(widget, val);
1320 this.copyBatchRowDrawn = true;
1323 this.batchCopyUpdate = function() {
1325 for(var k in this.copyWidgetCache) {
1326 var cache = this.copyWidgetCache[k];
1327 dojo.forEach(liDetailBatchFields, function(f) {
1328 var newval = self.copyBatchWidgets[f].attr('value');
1329 if(newval) cache[f].attr('value', newval);
1334 this._drawCopies = function(li) {
1337 // this button sets the total number of copies for a given lineitem
1338 acqLitAddCopyCount.onClick = function() {
1339 var count = acqLitCopyCountInput.attr('value');
1342 while(self.copyCount() < count)
1345 // delete rows if necessary
1346 var diff = self.copyCount() - count;
1348 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
1349 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
1350 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
1352 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1358 if(li.lineitem_details().length > 0) {
1359 dojo.forEach(li.lineitem_details(),
1361 self.addCopy(li, copy);
1369 this.copyCount = function() {
1371 for(var id in this.copyCache) {
1372 if(!this.copyCache[id].isdeleted())
1378 this.virtCopyId = -1;
1379 this.addCopy = function(li, copy) {
1380 var row = this.copyRow.cloneNode(true);
1381 this.copyTbody.appendChild(row);
1385 copy = new fieldmapper.acqlid();
1387 copy.id(this.virtCopyId--);
1388 copy.lineitem(li.id());
1391 this.copyCache[copy.id()] = copy;
1392 row.setAttribute('copy_id', copy.id());
1393 self.copyWidgetCache[copy.id()] = {};
1395 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1397 dojo.forEach(liDetailFields,
1400 if (field == "fund") {
1401 searchFilter = (copy.fund() ?
1402 {"-or": {"active": "t", "id": copy.fund()}} :
1405 searchFilter = null;
1408 var readOnly = false;
1410 // TODO: Add support for changing the owning_lib after real copies have been made.
1411 // owning_lib is order data as much as its item data
1412 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
1416 // TODO: add support for changing the fund after debits have been created
1417 // Note: invoicing allows the change
1418 if(copy.fund_debit() && field == 'fund') {
1422 var widget = new openils.widget.AutoFieldWidget({
1425 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1426 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1427 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1428 searchFilter : searchFilter,
1429 noCache: (field == "fund"),
1431 parentNode : dojo.query('[name='+field+']', row)[0],
1432 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
1433 readOnly : readOnly,
1436 // make sure we capture the value from any async widgets
1438 if (field == "fund" && w.store)
1439 self._ensureCSSFundClasses(w.store);
1440 copy[field](ww.getFormattedValue())
1441 self.copyWidgetCache[copy.id()][field] = w;
1444 dojo.connect(widget.widget, 'onChange',
1446 if (field == "fund")
1447 self._updateFundSelectorStyle(widget, val);
1449 if (copy.isnew() || val != copy[field]()) {
1450 // prevent setting ischanged() automatically on widget load for existing copies
1451 copy[field](widget.getFormattedValue())
1452 copy.ischanged(true);
1459 this.updateLidState(copy, row);
1462 this._ensureCSSFundClass = function(id) {
1463 if (!this.fundStyleSheet) {
1465 "style", {"type": "text/css"},
1466 document.getElementsByTagName("head")[0], "last"
1468 this.fundStyleSheet = document.styleSheets[
1469 document.styleSheets.length - 1
1473 var cn = "fund_" + id;
1474 if (!this.haveFundClass[cn]) {
1475 fieldmapper.standardRequest(
1476 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
1478 "params": [openils.User.authtoken, id],
1480 "oncomplete": function(r) {
1481 r = openils.Util.readResponse(r);
1482 self.fundBalanceState[id] = r;
1484 if (r[0] /* stop */)
1485 style = fundStyles.stop;
1486 else if (r[1] /* warning */)
1487 style = fundStyles.warning;
1488 self.fundStyleSheet.insertRule(
1489 "." + cn + " { " + style + " }",
1490 self.fundStyleSheet.cssRules.length
1492 self.haveFundClass[cn] = true;
1499 this._ensureCSSFundClasses = function(store) {
1501 "query": {"id": "*"},
1502 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
1506 this._updateFundSelectorStyle = function(widget, fund_id) {
1507 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
1508 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
1511 this.updateLidState = function(copy, row) {
1512 if (typeof(row) == "undefined") {
1514 'tr[copy_id="' + copy.id() + '"]', this.copyTbody
1519 var recv_link = nodeByName("receive", row);
1520 var unrecv_link = nodeByName("unreceive", row);
1521 var del_link = nodeByName("delete", row);
1522 var cxl_link = nodeByName("cancel", row);
1523 var claim_link = nodeByName("claim", row);
1524 var cxl_reason_link = nodeByName("cancel_reason", row);
1526 if (copy.cancel_reason()) {
1527 openils.Util.hide(del_link.parentNode);
1528 openils.Util.hide(recv_link);
1529 openils.Util.hide(unrecv_link);
1530 openils.Util.hide(cxl_link);
1531 openils.Util.hide(claim_link);
1533 /* XXX the following may leak memory in a long lived table: dijits may not get destroyed... not positive. revisit. */
1534 var holds_reason = dojo.create(
1536 "style": "border-bottom: 1px dashed #000;",
1537 "innerHTML": "Cancelled" /* XXX [sic] and i18n */
1538 }, cxl_reason_link, "only"
1542 "label": "<em>" + copy.cancel_reason().label() +
1543 "</em><br />" + copy.cancel_reason().description(),
1544 "connectId": [holds_reason]
1545 }, dojo.create("span", null, cxl_reason_link, "last")
1547 openils.Util.show(cxl_reason_link, "inline");
1548 } else if (this.isPO) {
1549 /* Only using this in one place so far, but may want it for better
1550 * decisions on when to display certain controls. */
1551 var li_state = this.liCache[copy.lineitem()].state();
1553 openils.Util.hide(del_link.parentNode);
1554 openils.Util.hide(cxl_reason_link);
1556 /* Avoid showing (un)receive links, cancel links, for virt copies */
1557 if (copy.id() > 0) {
1558 if (copy.recv_time()) {
1559 openils.Util.hide(cxl_link);
1560 openils.Util.hide(recv_link);
1561 openils.Util.hide(claim_link);
1563 openils.Util.show(unrecv_link, "inline");
1564 unrecv_link.onclick = function() {
1565 if (confirm(localeStrings.UNRECEIVE_LID))
1566 self.issueReceive(copy, /* rollback */ true);
1569 openils.Util.hide(unrecv_link);
1571 if (this.claimEligibleLid[copy.id()]) {
1572 openils.Util.show(claim_link, "inline");
1573 claim_link.onclick = function() {
1574 self.claimDialog.show(
1575 self.liCache[copy.lineitem()], copy.id()
1579 openils.Util.hide(claim_link);
1582 openils.Util[li_state == "on-order" ? "show" : "hide"](
1585 openils.Util.show(cxl_link, "inline");
1586 recv_link.onclick = function() {
1587 if (self.checkLiAlerts(copy.lineitem()))
1588 self.issueReceive(copy);
1590 cxl_link.onclick = function() {
1591 self.cancelLid(copy.id());
1595 openils.Util.hide(cxl_link);
1596 openils.Util.hide(unrecv_link);
1597 openils.Util.hide(recv_link);
1598 openils.Util.hide(claim_link);
1601 openils.Util.hide(unrecv_link);
1602 openils.Util.hide(recv_link);
1603 openils.Util.hide(cxl_reason_link);
1604 openils.Util.hide(claim_link);
1606 del_link.onclick = function() { self.deleteCopy(row) };
1607 openils.Util.show(del_link.parentNode);
1611 this.cancelLid = function(lid_id) {
1612 lidCancelDialog._lid_id = lid_id;
1613 openils.Util.show(lidCancelDialog.domNode.parentNode);
1614 lidCancelDialog.show();
1615 if (!lidCancelDialog._prepared) {
1616 var widget = new openils.widget.AutoFieldWidget({
1617 "fmField": "cancel_reason",
1618 "fmClass": "acqlid",
1619 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
1620 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1625 acqLidCancelButton.onClick = function() {
1626 if (w.attr("value")) {
1627 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
1629 lidCancelDialog._lid_id,
1633 lidCancelDialog.hide();
1636 lidCancelDialog._prepared = true;
1642 this._cancelLid = function(lid_id, reason) {
1643 fieldmapper.standardRequest(
1644 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
1645 "params": [openils.User.authtoken, lid_id, reason],
1647 "onresponse": function(r) {
1648 if (r = openils.Util.readResponse(r)) {
1650 for (var id in r.lid) {
1651 /* actually this should only iterate once */
1652 self.copyCache[id].cancel_reason(
1653 r.lid[id].cancel_reason
1655 self.updateLidState(self.copyCache[id]);
1664 this._confirmAlert = function(li, lin) {
1666 dojo.string.substitute(
1667 localeStrings.CONFIRM_LI_ALERT, [
1668 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1669 "title", "lineitem_marc_attr_definition"
1671 lin.alert_text().code(),
1672 lin.alert_text().description() || "",
1679 this.checkLiAlerts = function(li_id) {
1680 var li = this.liCache[li_id];
1682 var alert_notes = li.lineitem_notes().filter(
1683 function(o) { return Boolean(o.alert_text()); }
1686 /* this is _intentionally_ not done in a call to forEach() ... */
1687 for (var i = 0; i < alert_notes.length; i++) {
1688 if (this.noteAcks[alert_notes[i].id()])
1690 else if (!this._confirmAlert(li, alert_notes[i]))
1693 this.noteAcks[alert_notes[i].id()] = true;
1699 this.deleteCopy = function(row) {
1700 var copy = this.copyCache[row.getAttribute('copy_id')];
1701 copy.isdeleted(true);
1703 delete this.copyCache[copy.id()];
1704 this.copyTbody.removeChild(row);
1707 this._virtDfaCountsAsList = function() {
1709 for (var key in this.virtDfaCounts) {
1710 for (var i = 0; i < this.virtDfaCounts[key]; i++)
1716 this.confirmBreachedCopyFunds = function(copies) {
1717 var stop = 0, warning = 0;
1721 var state = self.fundBalanceState[o.fund()];
1722 if (state[0] /* stop */)
1724 else if (state[1] /* warning */)
1731 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
1732 } else if (warning) {
1733 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
1738 this.saveCopyChanges = function(liId) {
1744 for(var id in this.copyCache) {
1745 var c = this.copyCache[id];
1746 if(!c.isdeleted()) total++;
1747 if(c.isnew() || c.ischanged() || c.isdeleted()) {
1748 if(c.id() < 0) c.id(null);
1754 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
1757 if (copies.length > 0) {
1758 if (!this.confirmBreachedCopyFunds(copies))
1761 if (typeof(this._copy_count_cb) == "function")
1762 this._copy_count_cb(liId, total);
1764 openils.Util.show("acq-lit-update-copies-progress");
1765 fieldmapper.standardRequest(
1766 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1768 params: [openils.User.authtoken, copies],
1769 onresponse: function(r) {
1770 var res = openils.Util.readResponse(r);
1771 litUpdateCopiesProgress.update(res);
1773 oncomplete: function() {
1774 self.drawCopies(liId);
1775 openils.Util.hide("acq-lit-update-copies-progress");
1781 var dfa_list = this._virtDfaCountsAsList();
1782 if (dfa_list.length > 0) {
1783 fieldmapper.standardRequest(
1785 "open-ils.acq.distribution_formula.record_application"],
1788 "params": [openils.User.authtoken, dfa_list, liId],
1789 "onresponse": function(r) {
1790 var res = openils.Util.readResponse(r);
1791 if (res && res.length < dfa_list.length)
1792 alert(localeStrings.DFA_NOT_ALL);
1796 this.virtDfaCounts = {};
1800 this._updateCreatePoPrepayCheckbox = function(prepay) {
1801 var prepay = openils.Util.isTrue(prepay);
1802 this._prepayRequiredByVendor = prepay;
1803 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
1806 this._confirmPoPrepaySituation = function() {
1807 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
1808 if (want_prepay != this._prepayRequiredByVendor) {
1811 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
1812 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
1819 this.applySelectedLiAction = function(action) {
1823 case 'delete_selected':
1824 this._deleteLiList(self.getSelected());
1827 case 'create_order':
1829 if(!this.createPoProviderSelector) {
1830 var widget = new openils.widget.AutoFieldWidget({
1831 fmField : 'provider',
1833 searchFilter: {"active": "t"},
1834 parentNode : dojo.byId('acq-lit-po-provider'),
1836 "onChange": function() {
1838 self._updateCreatePoPrepayCheckbox(
1839 this.item.prepayment_required
1846 function(w) { self.createPoProviderSelector = w; }
1850 if(!this.createPoAgencySelector) {
1851 var widget = new openils.widget.AutoFieldWidget({
1852 fmField : 'ordering_agency',
1854 parentNode : dojo.byId('acq-lit-po-agency'),
1855 orgLimitPerms : ['CREATE_PURCHASE_ORDER'],
1858 function(w) { self.createPoAgencySelector = w; }
1863 acqLitPoCreateDialog.show();
1866 case 'save_picklist':
1867 this._loadPLSelect();
1868 acqLitSavePlDialog.show();
1871 case 'selector_ready':
1873 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
1874 acqLitChangeLiStateDialog.show();
1882 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
1889 case 'rollback_receive_po':
1890 this.rollbackPoReceive();
1893 case 'create_assets':
1894 this.createAssets();
1897 case 'export_attr_list':
1898 this.chooseExportAttr();
1901 case 'batch_apply_funds':
1902 this.applyBatchLiFunds();
1905 case 'add_brief_record':
1907 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
1909 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
1913 case "cancel_lineitems":
1914 this.maybeCancelLineitems();
1917 case "change_claim_policy":
1918 var li_list = this.getSelected();
1919 this.claimPolicyPicker.attr("value", null);
1920 liClaimPolicyDialog.show();
1921 liClaimPolicySave.onClick = function() {
1922 self.changeClaimPolicy(
1924 self.claimPolicyPicker.attr("value"),
1927 function(li) { self.setClaimPolicyControl(li); }
1929 liClaimPolicyDialog.hide();
1937 this.changeClaimPolicy = function(li_list, value, callback) {
1939 function(li) { li.claim_policy(value); }
1941 fieldmapper.standardRequest(
1942 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
1943 "params": [openils.User.authtoken, li_list],
1945 "oncomplete": function(r) {
1946 r = openils.Util.readResponse(r);
1947 if (callback) callback(r);
1953 this.createAssets = function() {
1954 if(!this.isPO) return;
1955 if(!confirm(localeStrings.CREATE_PO_ASSETS_CONFIRM)) return;
1956 this.show('acq-lit-progress-numbers');
1958 fieldmapper.standardRequest(
1959 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
1961 params: [this.authtoken, this.isPO],
1962 onresponse: function(r) {
1963 var resp = openils.Util.readResponse(r);
1964 self._updateProgressNumbers(resp, true);
1970 this.maybeCancelLineitems = function() {
1971 openils.Util.show("acq-lit-cancel-reason", "inline");
1972 if (!acqLitCancelLineitemsButton._prepared) {
1973 var widget = new openils.widget.AutoFieldWidget({
1974 "fmField": "cancel_reason",
1976 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
1977 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1982 acqLitCancelLineitemsButton.onClick = function() {
1983 if (w.attr("value")) {
1984 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
1985 self._cancelLineitems(w.attr("value"));
1987 openils.Util.hide("acq-lit-cancel-reason");
1990 acqLitCancelLineitemsButton._prepared = true;
1996 this._cancelLineitems = function(reason) {
1997 var id_list = this.getSelected().map(function(o) { return o.id(); });
1998 fieldmapper.standardRequest(
1999 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
2000 "params": [openils.User.authtoken, id_list, reason],
2002 "onresponse": function(r) {
2003 if (r = openils.Util.readResponse(r)) {
2005 for (var id in r.li) {
2006 self.liCache[id].state(r.li[id].state);
2007 self.liCache[id].cancel_reason(
2008 r.li[id].cancel_reason
2010 self.updateLiState(self.liCache[id]);
2013 if (r.lid && self.copyCache) {
2014 for (var id in r.lid) {
2015 if (self.copyCache[id]) {
2016 self.copyCache[id].cancel_reason(
2017 r.lid[id].cancel_reason
2019 self.updateLidState(self.copyCache[id]);
2029 this.chooseExportAttr = function() {
2030 if (!acqLitExportAttrSelector._li_setup) {
2032 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
2034 "data": acqliad.toStoreData(
2036 "acqliad", {"code": li_exportable_attrs}
2041 acqLitExportAttrSelector.setValue();
2042 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
2043 acqLitExportAttrSelector._li_setup = true;
2045 openils.Util.show("acq-lit-export-attr-holder", "inline");
2048 this.exportAttrList = function() {
2049 var attr_def = acqLitExportAttrSelector.item;
2050 var li_list = this.getSelected();
2051 var value_list = li_list.map(
2053 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2054 attr_def.code, "lineitem_marc_attr_definition"
2057 ).filter(function(attr) { return Boolean(attr); });
2059 if (value_list.length > 0) {
2060 if (value_list.length < li_list.length) {
2062 dojo.string.substitute(
2063 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
2070 openils.XUL.contentToFileSaveDialog(
2071 value_list.join("\n"),
2072 localeStrings.EXPORT_SAVE_DIALOG_TITLE
2078 alert(dojo.string.substitute(
2079 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
2083 openils.Util.hide("acq-lit-export-attr-holder");
2086 this.printPO = function() {
2087 if(!this.isPO) return;
2088 progressDialog.show(true);
2089 fieldmapper.standardRequest(
2090 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
2092 params: [this.authtoken, this.isPO, 'html'],
2093 oncomplete: function(r) {
2094 progressDialog.hide();
2095 var evt = openils.Util.readResponse(r);
2096 if(evt && evt.template_output()) {
2097 win = window.open('','', 'resizable,width=800,height=600,scrollbars=1');
2098 win.document.body.innerHTML = evt.template_output().data();
2106 this.receivePO = function() {
2107 if (!this.isPO) return;
2109 for (var id in this.liCache) {
2110 /* assumption: liCache reflects exactly the
2111 * set of LIs that belong to our PO */
2112 if (this.liCache[id].state() != "received" &&
2113 !this.checkLiAlerts(id)) return;
2116 this.show('acq-lit-progress-numbers');
2118 fieldmapper.standardRequest(
2119 ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
2121 params: [this.authtoken, this.isPO],
2122 onresponse : function(r) {
2123 var resp = openils.Util.readResponse(r);
2124 self._updateProgressNumbers(resp, true);
2130 this.issueReceive = function(obj, rollback) {
2131 /* (For now) there shall be no marking LI or LIDs (un)received
2132 * except from the actual "view PO" interface. */
2133 if (!this.isPO) return;
2136 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
2138 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
2140 progressDialog.show(true);
2141 fieldmapper.standardRequest(
2142 ["open-ils.acq", method], {
2144 "params": [this.authtoken, obj.id()],
2145 "onresponse": function(r) {
2146 if (r = openils.Util.readResponse(r)) {
2147 self.fetchClaimInfo(
2148 part == "lineitem" ? obj.id() : obj.lineitem(),
2150 function() { self.handleReceive(r); }
2152 progressDialog.hide();
2160 * Handles the responses from receive and rollback ML calls.
2162 this.handleReceive = function(resp) {
2165 for (var li_id in resp.li) {
2166 for (var key in resp.li[li_id])
2167 self.liCache[li_id][key](resp.li[li_id][key]);
2168 self.updateLiState(self.liCache[li_id]);
2172 if (typeof(self.poUpdateCallback) == "function")
2173 self.poUpdateCallback(resp.po);
2176 for (var lid_id in resp.lid) {
2177 for (var key in resp.lid[lid_id])
2178 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
2179 self.updateLidState(self.copyCache[lid_id]);
2185 this.rollbackPoReceive = function() {
2186 if(!this.isPO) return;
2187 if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
2188 this.show('acq-lit-progress-numbers');
2190 fieldmapper.standardRequest(
2191 ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
2193 params: [this.authtoken, this.isPO],
2194 onresponse : function(r) {
2195 var resp = openils.Util.readResponse(r);
2196 self._updateProgressNumbers(resp, true);
2202 this._updateProgressNumbers = function(resp, reloadOnComplete) {
2204 dojo.byId('acq-pl-lit-li-processed').innerHTML = resp.li;
2205 dojo.byId('acq-pl-lit-lid-processed').innerHTML = resp.lid;
2206 dojo.byId('acq-pl-lit-debits-processed').innerHTML = resp.debits_accrued;
2207 dojo.byId('acq-pl-lit-bibs-processed').innerHTML = resp.bibs;
2208 dojo.byId('acq-pl-lit-indexed-processed').innerHTML = resp.indexed;
2209 dojo.byId('acq-pl-lit-copies-processed').innerHTML = resp.copies;
2210 if(resp.complete && reloadOnComplete)
2211 location.href = location.href;
2215 this._createPO = function(fields) {
2216 this.show('acq-lit-progress-numbers');
2217 var po = new fieldmapper.acqpo();
2218 po.provider(this.createPoProviderSelector.attr('value'));
2219 po.ordering_agency(this.createPoAgencySelector.attr('value'));
2220 po.prepayment_required(fields.prepayment_required[0] ? true : false);
2222 var selected = this.getSelected( (fields.create_from == 'all') );
2223 if(selected.length == 0) return;
2225 var max = selected.length * 3;
2228 fieldmapper.standardRequest(
2229 ['open-ils.acq', 'open-ils.acq.purchase_order.create'],
2232 openils.User.authtoken,
2235 lineitems : selected.map(function(li) { return li.id() }),
2236 create_assets : fields.create_assets[0],
2240 onresponse : function(r) {
2241 var resp = openils.Util.readResponse(r);
2242 self._updateProgressNumbers(resp);
2244 location.href = oilsBasePath + '/acq/po/view/' + resp.purchase_order.id();
2250 this.batchFundWidget = null;
2252 this.applyBatchLiFunds = function() {
2254 var liIds = this.getSelected().map(function(li) { return li.id(); });
2255 if(liIds.length == 0) return; // warn?
2258 batchFundUpdateDialog.show();
2260 if(!this.batchFundWidget) {
2261 this.batchFundWidget = new openils.widget.AutoFieldWidget({
2263 selfReference : true,
2264 labelFormat : fundLabelFormat,
2265 searchFormat : fundSearchFormat,
2266 searchFilter : {"active": "t"},
2267 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
2268 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2269 dijitArgs : { "required": true, "labelType": "html" },
2272 this.batchFundWidget.build();
2275 dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
2276 dojo.connect(batchFundUpdateSubmit, 'onClick',
2279 // TODO: call .dry_run first to test thresholds
2280 fieldmapper.standardRequest(
2281 ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
2284 openils.User.authtoken,
2286 self.batchFundWidget.widget.attr('value')
2288 oncomplete : function(r) {
2289 var resp = openils.Util.readResponse(r);
2291 location.href = location.href;
2300 this._deleteLiList = function(list, idx) {
2301 if(idx == null) idx = 0;
2302 if(idx >= list.length) return;
2303 var liId = list[idx].id();
2304 fieldmapper.standardRequest(
2305 ['open-ils.acq', 'open-ils.acq.lineitem.delete'],
2307 params: [openils.User.authtoken, liId],
2308 oncomplete: function(r) {
2309 self.removeLineitem(liId);
2310 self._deleteLiList(list, ++idx);
2316 this.editOrderMarc = function(li) {
2318 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
2319 to true in about:config */
2321 if(!openils.XUL.enableXPConnect()) return;
2323 if(openils.XUL.isXUL()) {
2324 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
2326 win = window.open('/xul/server/cat/marcedit.xul');
2330 record : {marc : li.marc()},
2332 label: 'Save Record', // XXX I18N
2333 func: function(xmlString) {
2335 fieldmapper.standardRequest(
2336 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
2338 params: [openils.User.authtoken, li],
2339 oncomplete: function(r) {
2340 openils.Util.readResponse(r);
2342 self.drawInfo(li.id())
2351 this._savePl = function(values) {
2353 var selected = this.getSelected( (values.which == 'all') );
2354 openils.Util.show('acq-lit-generic-progress');
2356 if(values.new_name) {
2357 openils.acq.Picklist.create(
2358 {name: values.new_name},
2360 self._updateLiList(id, selected, 0,
2362 location.href = oilsBasePath + '/acq/picklist/view/' + id;
2366 } else if(values.existing_pl) {
2367 // update lineitems to use an existing picklist
2368 self._updateLiList(values.existing_pl, selected, 0,
2370 location.href = oilsBasePath + '/acq/picklist/view/' + values.existing_pl;
2375 this._updateLiState = function(values, state) {
2377 var selected = this.getSelected( (values.which == 'all') );
2378 if(!selected.length) return;
2379 dojo.forEach(selected, function(li) {li.state(state);});
2380 self._updateLiList(null, selected, 0,
2381 // TODO consider inline updates for efficiency
2382 function() { location.href = location.href }
2386 this._updateLiList = function(pl, list, idx, oncomplete) {
2387 if(idx >= list.length) return oncomplete();
2389 if(pl != null) li.picklist(pl);
2390 litGenericProgress.update({maximum: list.length, progress: idx});
2391 new openils.acq.Lineitem({lineitem:li}).update(
2393 self._updateLiList(pl, list, ++idx, oncomplete);
2398 this._loadPLSelect = function() {
2399 if(this._plSelectLoaded) return;
2401 function handleResponse(r) {
2402 plList.push(r.recv().content());
2404 var method = 'open-ils.acq.picklist.user.retrieve';
2405 fieldmapper.standardRequest(
2406 ['open-ils.acq', method],
2408 params: [this.authtoken],
2409 onresponse: handleResponse,
2410 oncomplete: function() {
2411 self._plSelectLoaded = true;
2412 acqLitAddExistingSelect.store =
2413 new dojo.data.ItemFileReadStore({data:acqpl.toStoreData(plList)});
2414 acqLitAddExistingSelect.setValue();
2420 this.showRealCopyEditUI = function(li) {
2425 this._fetchLineitem(li.id(),
2427 li = self.liCache[li.id()] = fullLi;
2431 id : li.lineitem_details().map(
2432 function(item) { return item.eg_copy_id() }
2436 oncomplete : function(r) {
2438 var r_list = openils.Util.readResponse( r );
2439 for (var i = 0; i < r_list.length; i++) {
2440 var copy = r_list[i];
2441 var volId = copy.call_number();
2442 var volume = self.volCache[volId];
2444 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2446 copy.call_number(volume);
2447 copyList.push(copy);
2450 // If we need to, we can pass in an update_copy function to handle the update instead of volume_item_creator
2451 xulG.volume_item_creator( { 'existing_copies' : copyList } );
2454 alert('error in oncomplete: ' + E);