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.skipInitialEligibilityCheck = false;
71 this.invoiceLinkDialogManager = new InvoiceLinkDialogManager("li");
72 this.claimDialog = new ClaimDialogManager(
73 liClaimDialog, finalClaimDialog, this.claimEligibleLidByLi,
74 function(li) { /* callback that fires when claims are made */
75 self.fetchClaimInfo(li.id(), /* force update */ true);
79 dojo.connect(acqLitLiActionsSelector, 'onChange',
81 self.applySelectedLiAction(this.attr('value'))
82 acqLitLiActionsSelector.attr('value', '_');
85 acqLitCreatePoSubmit.onClick = function() {
86 if (self._confirmPoPrepaySituation()) {
87 acqLitPoCreateDialog.hide();
88 self._createPO(acqLitPoCreateDialog.getValues());
94 acqLitSavePlButton.onClick = function() {
95 acqLitSavePlDialog.hide();
96 self._savePl(acqLitSavePlDialog.getValues());
99 acqLitCancelLiStateButton.onClick = function() {
100 acqLitChangeLiStateDialog.hide();
102 acqLitSaveLiStateButton.onClick = function() {
103 acqLitChangeLiStateDialog.hide();
104 self._updateLiState(acqLitChangeLiStateDialog.getValues(), acqLitChangeLiStateDialog.attr('state'));
108 dojo.byId('acq-lit-select-toggle').onclick = function(){self.toggleSelect()};
109 dojo.byId('acq-lit-info-back-button').onclick = function(){self.show('list')};
110 dojo.byId('acq-lit-copies-back-button').onclick = function(){self.show('list')};
111 dojo.byId('acq-lit-notes-back-button').onclick = function(){self.show('list')};
112 dojo.byId('acq-lit-real-copies-back-button').onclick = function(){self.show('list')};
114 this.reset = function(keep_selectors) {
115 while(self.tbody.childNodes[0])
116 self.tbody.removeChild(self.tbody.childNodes[0]);
124 this.setNext = function(handler) {
125 var link = dojo.byId('acq-lit-next');
127 dojo.style(link, 'visibility', 'visible');
128 link.onclick = handler;
130 dojo.style(link, 'visibility', 'hidden');
134 this.setPrev = function(handler) {
135 var link = dojo.byId('acq-lit-prev');
137 dojo.style(link, 'visibility', 'visible');
138 link.onclick = handler;
140 dojo.style(link, 'visibility', 'hidden');
144 this.show = function(div) {
145 openils.Util.hide('acq-lit-table-div');
146 openils.Util.hide('acq-lit-info-div');
147 openils.Util.hide('acq-lit-li-details');
148 openils.Util.hide('acq-lit-notes-div');
149 openils.Util.hide('acq-lit-real-copies-div');
152 openils.Util.show('acq-lit-table-div');
155 openils.Util.show('acq-lit-info-div');
158 openils.Util.show('acq-lit-li-details');
161 openils.Util.show('acq-lit-real-copies-div');
164 openils.Util.show('acq-lit-notes-div');
168 openils.Util.show(div);
172 this.hide = function() {
176 this.toggleSelect = function() {
178 dojo.forEach(self.selectors, function(i){i.checked = false});
180 dojo.forEach(self.selectors, function(i){i.checked = true});
181 self.toggleState = !self.toggleState;
185 /** @param all If true, assume all are selected */
186 this.getSelected = function(all) {
188 var indices = {}; /* use to uniqify. needed in paging situations. */
189 dojo.forEach(self.selectors,
192 indices[i.parentNode.parentNode.getAttribute('li')] = true;
195 return openils.Util.objectProperties(indices).map(
196 function(liId) { return self.liCache[liId]; }
200 this.setRowAttr = function(td, liWrapper, field, type) {
201 var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
202 td.appendChild(document.createTextNode(val));
205 this.setClaimPolicyControl = function(li, row) {
206 if (!self.claimPolicyPicker) {
207 self.claimPolicyPicker = true; /* prevents a race condition */
208 new openils.widget.AutoFieldWidget({
209 "parentNode": "acq-lit-li-claim-policy",
211 "selfReference": true,
212 "dijitArgs": {"required": true}
213 }).build(function(w) { self.claimPolicyPicker = w; });
216 if (!row) row = this._findLiRow(li);
218 var actViewPolicy = nodeByName("action_view_claim_policy", row);
219 if (li.claim_policy())
220 actViewPolicy.innerHTML = localeStrings.CHANGE_CLAIM_POLICY;
222 if (!actViewPolicy.onclick) {
223 actViewPolicy.onclick = function() {
224 if (li.claim_policy())
225 self.claimPolicyPicker.attr("value", li.claim_policy());
226 liClaimPolicyDialog.show();
227 liClaimPolicySave.onClick = function() {
228 self.changeClaimPolicy(
229 [li], self.claimPolicyPicker.attr("value"),
231 self.setClaimPolicyControl(li, row);
232 liClaimPolicyDialog.hide();
240 this.fetchClaimInfo = function(liId, force, callback, row) {
242 liId, function(full) {
243 self.liCache[full.id()] = full;
244 self.checkClaimEligibility(full, callback, row);
250 * Inserts a single lineitem into the growing table of lineitems
251 * @param {Object} li The lineitem object to insert
253 this.addLineitem = function(li, skip_final_placement) {
254 this.liCache[li.id()] = li;
256 // sort the lineitem notes on edit_time
257 if(!li.lineitem_notes()) li.lineitem_notes([]);
259 var liWrapper = new openils.acq.Lineitem({lineitem:li});
260 var row = self.rowTemplate.cloneNode(true);
261 row.setAttribute('li', li.id());
262 var tds = dojo.query('[attr]', row);
263 dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
264 dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
266 var isbn = liWrapper.findAttr('isbn', 'lineitem_marc_attr_definition');
268 // XXX media prefix for added content
269 dojo.query('[name=jacket]', row)[0].setAttribute('src', '/opac/extras/ac/jacket/small/' + isbn);
272 nodeByName("worksheet_link", row).href =
273 oilsBasePath + "/acq/lineitem/worksheet/" + li.id();
275 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
276 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
277 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
279 if (!this.skipInitialEligibilityCheck)
280 this.fetchClaimInfo(li.id(), false, null, row);
282 this.updateLiNotesCount(li, row);
284 this.setClaimPolicyControl(li, row);
286 // show which PO this lineitem is a member of
287 if(li.purchase_order() && !this.isPO) {
289 this.poCache[li.purchase_order()] =
290 this.poCache[li.purchase_order()] ||
291 fieldmapper.standardRequest(
292 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
294 this.authtoken, li.purchase_order(), {
295 "flesh_price_summary": true,
296 "flesh_lineitem_count": true
299 if(po && !this.isMeta) {
300 openils.Util.show(nodeByName('po', row), 'inline');
301 var link = nodeByName('po_link', row);
302 link.setAttribute('href', oilsBasePath + '/acq/po/view/' + li.purchase_order());
303 link.innerHTML = 'PO: ' + po.name(); // TODO i18n
307 // show which picklist this lineitem is a member of
308 if(li.picklist() && (this.isPO || this.isMeta || this.isUni)) {
310 this.plCache[li.picklist()] =
311 this.plCache[li.picklist()] ||
312 fieldmapper.standardRequest(
313 ['open-ils.acq', 'open-ils.acq.picklist.retrieve'],
314 {params: [this.authtoken, li.picklist()]});
317 openils.Util.show(nodeByName("bib_origin", row), "inline");
319 openils.Util.show(nodeByName('pl', row), 'inline');
320 var link = nodeByName('pl_link', row);
321 link.setAttribute('href', oilsBasePath + '/acq/picklist/view/' + li.picklist());
322 link.innerHTML = 'PL: '+pl.name(); // TODO i18n
326 var countNode = nodeByName('count', row);
327 var count = li.item_count() || 0;
328 if (typeof(this._copy_count_cb) == "function") {
329 this._copy_count_cb(li.id(), count);
331 countNode.innerHTML = count;
332 countNode.id = 'acq-lit-copy-count-label-' + li.id();
335 var priceInput = dojo.query('[name=price]', row)[0];
336 priceInput.value = li.estimated_unit_price() || '';
337 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
339 // show either "mark received" or "unreceive" as appropriate
340 this.updateLiState(li, row);
342 if (!skip_final_placement) {
343 self.tbody.appendChild(row);
344 self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
350 this._liCountClaims = function(li) {
352 for (var i = 0; i < li.lineitem_details().length; i++)
353 total += li.lineitem_details()[i].claims().length;
357 this._findLiRow = function(li) {
358 return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
361 this.reconsiderClaimControl = function(li, row) {
362 var option = nodeByName("action_manage_claims", row);
363 var eligible = this.claimEligibleLidByLi[li.id()].length;
364 var count = this._liCountClaims(li);
365 if (!row) row = this._findLiRow(li);
367 option.disabled = !(count || eligible);
369 dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
370 option.onclick = function() { self.claimDialog.show(li); };
373 this.clearEligibility = function(li) {
374 this.claimEligibleLidByLi[li.id()] = [];
376 if (li.lineitem_details()) {
377 li.lineitem_details().forEach(
378 function(lid) { delete self.claimEligibleLid[lid.id()]; }
382 if (this.copyCache) {
384 for (var k in this.copyCache) {
385 if (this.copyCache[k].lineitem() == li.id())
389 function(k) { delete self.claimEligibleLid[k]; }
394 this.checkClaimEligibility = function(li, callback, row) {
395 this.clearEligibility(li);
396 fieldmapper.standardRequest(
397 ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
398 "params": [openils.User.authtoken, {"lineitem": li.id()}],
400 "onresponse": function(r) {
401 if (r = openils.Util.readResponse(r)) {
402 self.claimEligibleLidByLi[li.id()].push(
405 self.claimEligibleLid[r.lineitem_detail()] = true;
408 "oncomplete": function() {
409 self.reconsiderClaimControl(li, row);
410 if (typeof(callback) == "function")
417 this.updateLiNotesCount = function(li, row) {
418 if (!row) row = this._findLiRow(li);
420 var has_notes = (li.lineitem_notes().filter(
421 function(o) { return Boolean (o.alert_text()); }
424 /* U+2691 is the code point for a filled-in flag character */
425 nodeByName("notes_alert_flag", row).innerHTML =
426 has_notes ? "⚑" : "";
427 nodeByName("noteslink", row).style.fontStyle =
428 has_notes ? "italic" : "normal";
429 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
432 /* XXX NOT related to _updateLiState(). rethink */
433 this.updateLiState = function(li, row) {
434 if (!row) row = this._findLiRow(li);
436 var actReceive = nodeByName("action_mark_recv", row);
437 var actUnRecv = nodeByName("action_mark_unrecv", row);
438 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
439 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
441 var actNewInvoice = nodeByName('action_new_invoice', row);
442 var actLinkInvoice = nodeByName('action_link_invoice', row);
443 var actViewInvoice = nodeByName('action_view_invoice', row);
445 nodeByName('action_view_history', row).onclick =
446 function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
448 var state_cell = nodeByName("li_state", row);
450 if (li.state() == "cancelled") {
451 if (typeof li.cancel_reason() == "object") {
452 var holds_state = dojo.create(
454 "style": "border-bottom: 1px dashed #000;",
455 "innerHTML": li.state()
456 }, state_cell, "only"
460 "label": "<em>" + li.cancel_reason().label() +
461 "</em><br />" + li.cancel_reason().description(),
462 "connectId": [holds_state]
463 }, dojo.create("span", null, state_cell, "last")
466 state_cell.innerHTML = li.state(); // TODO i18n state labels
469 state_cell.innerHTML = li.state(); // TODO i18n state labels
473 /* handle row coloring for based on LI state */
474 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
475 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
477 /* handle links that appear/disappear based on whether LI is received */
481 actNewInvoice.onclick = function() {
482 location.href = oilsBasePath + '/acq/invoice/view?create=1&attach_li=' + li.id();
483 nodeByName("action_none", row).selected = true;
485 actLinkInvoice.onclick = function() {
486 self.invoiceLinkDialogManager.target = li;
487 acqLitLinkInvoiceDialog.show();
488 nodeByName("action_none", row).selected = true;
490 actViewInvoice.onclick = function() {
491 location.href = oilsBasePath +
492 "/acq/search/unified?so=" +
493 base64Encode({"jub":[{"id": li.id()}]}) +
495 nodeByName("action_none", row).selected = true;
498 actNewInvoice.disabled = false;
499 actLinkInvoice.disabled = false;
500 actViewInvoice.disabled = false;
504 actReceive.disabled = false;
505 actReceive.onclick = function() {
506 if (self.checkLiAlerts(li.id()))
507 self.issueReceive(li);
508 nodeByName("action_none", row).selected = true;
513 actUnRecv.disabled = false;
514 actUnRecv.onclick = function() {
515 if (confirm(localeStrings.UNRECEIVE_LI))
516 self.issueReceive(li, /* rollback */ true);
517 nodeByName("action_none", row).selected = true;
519 // TODO we should allow editing before receipt, in which case the
520 // test should be "if 1 or more real (acp) copies exist
521 actUpdateBarcodes.disabled = false;
522 actUpdateBarcodes.onclick = function() {
523 self.showRealCopyEditUI(li);
524 nodeByName("action_none", row).selected = true;
526 actHoldingsMaint.disabled = false;
527 actHoldingsMaint.onclick = self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
535 this._setAlertStore = function() {
536 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
538 "data": acqliat.toStoreData(
540 "acqliat", {"id": {"!=": null}}
545 acqLitAlertAlertText.setValue(); /* make the store "live" */
546 acqLitAlertAlertText._store_ready = true;
550 * Draws and shows the lineitem notes pane
552 this.drawLiNotes = function(li) {
555 if (!acqLitAlertAlertText._store_ready)
556 this._setAlertStore();
559 li.lineitem_notes().sort(
561 if(a.edit_time() < b.edit_time()) return 1;
567 while(this.liNotesTbody.childNodes[0])
568 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
571 acqLitCreateNoteSubmit.onClick = function() {
572 var value = acqLitCreateNoteText.attr('value');
574 var note = new fieldmapper.acqlin();
577 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
580 note.lineitem(li.id());
582 self.updateLiNotes(li, note);
583 acqLitCreateNoteVendorPublic.attr("checked", false);
584 acqLitCreateNoteText.attr("value", "");
587 acqLitCreateAlertSubmit.onClick = function() {
588 if (!acqLitAlertAlertText.item) {
589 alert(localeStrings.ALERT_UNSELECTED);
593 var alert_text = new fieldmapper.acqliat().fromStoreItem(
594 acqLitAlertAlertText.item
596 var value = acqLitAlertNoteValue.attr("value") || "";
598 var note = new fieldmapper.acqlin();
600 note.lineitem(li.id());
602 note.alert_text(alert_text);
604 self.updateLiNotes(li, note);
607 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
611 * Draws a single lineitem note in the notes pane
613 this.addLiNote = function(li, note) {
614 if(note.isdeleted()) return;
616 var row = self.liNotesRow.cloneNode(true);
617 nodeByName("value", row).innerHTML = note.value();
618 var alert_node = nodeByName("alert_code", row);
619 if (note.alert_text()) {
620 alert_node.innerHTML = note.alert_text().code();
621 if (note.alert_text().description()) {
624 "connectId": [alert_node],
625 "label": note.alert_text().description()
626 }, dojo.create("span", null, alert_node, "after")
631 if (openils.Util.isTrue(note.vendor_public()))
632 nodeByName("vendor_public", row).innerHTML =
633 localeStrings.VENDOR_PUBLIC;
635 nodeByName("delete", row).onclick = function() {
636 note.isdeleted(true);
637 self.liNotesTbody.removeChild(row);
638 self.updateLiNotes(li);
641 if(note.edit_time()) {
642 nodeByName("edit_time", row).innerHTML =
643 dojo.date.locale.format(
644 dojo.date.stamp.fromISOString(note.edit_time()),
645 {formatLength:'short'});
648 self.liNotesTbody.appendChild(row);
652 * Updates any new/changed/deleted notes on the server
654 this.updateLiNotes = function(li, newNote) {
660 notes = li.lineitem_notes().filter(
662 if(note.ischanged() || note.isnew() || note.isdeleted())
668 if(notes.length == 0) return;
669 progressDialog.show();
671 fieldmapper.standardRequest(
672 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
674 params : [this.authtoken, notes],
675 onresponse : function(r) {
676 var resp = openils.Util.readResponse(r);
681 // remove the old changed notes
683 dojo.forEach(li.lineitem_notes(),
685 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
689 li.lineitem_notes(list);
692 progressDialog.hide();
693 self.updateLiNotesCount(li);
694 self.drawLiNotes(li);
698 progressDialog.update(resp);
699 var newnote = resp.note;
701 if(!newnote.isdeleted()) {
702 newnote.isnew(false);
703 newnote.ischanged(false);
704 li.lineitem_notes().push(newnote);
711 this.updateLiPrice = function(input, li) {
713 var price = input.value;
714 if(Number(price) == Number(li.estimated_unit_price())) return;
716 fieldmapper.standardRequest(
717 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
719 params : [this.authtoken, li.id(), price],
720 oncomplete : function(r) {
721 openils.Util.readResponse(r);
722 li.estimated_unit_price(price); // update local copy
728 this.removeLineitem = function(liId) {
729 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
730 delete this.liCache[liId];
731 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
734 this.drawInfo = function(liId) {
735 if (!this._isRelatedViewer) {
736 var d = dojo.byId("acq-lit-info-related");
737 if (!this.relCache[liId]) {
738 fieldmapper.standardRequest(
741 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
744 "params": [openils.User.authtoken, liId],
745 "onresponse": function(r) {
746 self.relCache[liId] = openils.Util.readResponse(r);
747 nodeByName("related_number", d).innerHTML =
750 self.relCache[liId] >1 ? "show" : "hide"
756 nodeByName("related_number", d).innerHTML = this.relCache[liId];
757 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
762 openils.acq.Lineitem.fetchAttrDefs(
764 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
769 this._fetchLineitem = function(liId, handler, force) {
771 var li = this.liCache[liId];
772 if(li && li.marc() && li.lineitem_details() && !force)
775 fieldmapper.standardRequest(
776 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve'],
779 params: [self.authtoken, liId, {
781 flesh_cancel_reason: true,
782 flesh_li_details: true,
784 flesh_fund_debit: true }],
786 oncomplete: function(r) {
787 var li = openils.Util.readResponse(r);
794 this._drawInfo = function(li) {
796 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
799 openils.Util.hide('acq-lit-marc-order-record-label');
800 openils.Util.hide(acqLitEditOrderMarc.domNode);
801 openils.Util.show('acq-lit-marc-real-record-label');
803 openils.Util.show('acq-lit-marc-order-record-label');
804 openils.Util.show(acqLitEditOrderMarc.domNode);
805 openils.Util.hide('acq-lit-marc-real-record-label');
808 this.drawMarcHTML(li);
809 this.infoTbody = dojo.byId('acq-lit-info-tbody');
812 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
813 while(this.infoTbody.childNodes[0])
814 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
816 for(var i = 0; i < li.attributes().length; i++) {
817 var attr = li.attributes()[i];
818 var row = this.infoRow.cloneNode(true);
820 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
821 var name = openils.acq.Lineitem.attrDefs[type].filter(
823 return (a.code() == attr.attr_name());
825 ).pop().description();
827 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
828 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
829 this.infoTbody.appendChild(row);
832 if (!this._isRelatedViewer) {
833 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
834 oilsBasePath + "/acq/lineitem/related/" + li.id();
839 openils.Util.show('acq-lit-info-cat-link');
840 var link = dojo.byId('acq-lit-info-cat-link').getElementsByTagName('a')[0];
842 if(openils.XUL.isXUL()) {
844 link.setAttribute('href', 'javascript:void(0);');
845 link.onclick = this.generateMakeRecTab( li.eg_bib_id() );
848 var href = link.getAttribute('href');
850 link.setAttribute('href', href + li.eg_bib_id());
853 openils.Util.hide('acq-lit-info-cat-link');
857 this.generateMakeRecTab = function(bib_id,default_view, row) {
861 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
864 show_nav_buttons : true,
865 show_print_button : true,
866 opac_url : xulG.url_prefix(xulG.urls.opac_rdetail + '?r=' + bib_id),
867 default_view : default_view
871 if(row) nodeByName("action_none", row).selected = true;
875 this.drawMarcHTML = function(li) {
876 var params = [null, true, li.marc()];
878 params = [li.eg_bib_id(), true];
880 fieldmapper.standardRequest(
881 ['open-ils.search', 'open-ils.search.biblio.record.html'],
884 oncomplete: function(r) {
885 dojo.byId('acq-lit-marc-div').innerHTML =
886 openils.Util.readResponse(r);
892 this.drawCopies = function(liId) {
896 this.copyWidgetCache = {};
897 this.oldCopyWidgetCache = {};
898 this.virtDfaCounts = {};
899 this.realDfaCache = {};
902 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
903 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
904 acqLitCopyCountInput.attr('value', '0');
906 while(this.copyTbody.childNodes[0])
907 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
909 this._drawBatchCopyWidgets();
911 this._drawDistribApplied(liId);
913 this._fetchDistribFormulas(
915 openils.acq.Lineitem.fetchAttrDefs(
917 self._fetchLineitem(liId, function(li){self._drawCopies(li);});
924 this._saveDistribAppliedTemplates = function() {
925 if (!this._appliedDistribTemplate) {
926 this._appliedDistribTemplate =
927 dojo.byId("acq-lit-distrib-applied-tbody").
928 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
929 dojo.attr(this._appliedDistribTemplate, "id");
933 this._drawDistribApplied = function(liId) {
934 /* Build this table while hidden to prevent rendering artifacts */
935 openils.Util.hide("acq-lit-distrib-applied-tbody");
937 this._saveDistribAppliedTemplates();
939 /* Remove any rows in the table from previous populations */
940 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
941 forEach(dojo.destroy);
943 /* Unregister all dijits previously created (for some reason this isn't
944 * covered by the above destroy calls). */
945 dijit.registry.forEach(
946 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
949 /* Populate the table with our liId */
951 fieldmapper.standardRequest(
953 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
956 "params": [self.authtoken, liId],
957 "onresponse": function(r) {
958 var dfa = openils.Util.readResponse(r);
961 self.realDfaCache[dfa.id()] = dfa;
962 self._drawDistribAppliedUnit(dfa);
965 "oncomplete": function() {
966 /* Reveal built table */
969 "acq-lit-distrib-applied-tbody", "table-row-group"
977 this._drawDistribAppliedUnit = function(dfa) {
979 var row = dojo.query(
980 'tr[formula="' + dfa.formula().id() + '"]',
981 "acq-lit-distrib-applied-tbody"
986 row = dojo.clone(this._appliedDistribTemplate);
987 dojo.attr(row, "formula", dfa.formula().id());
988 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
991 var td = dojo.query("td", row)[0];
993 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
994 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
997 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
999 new dijit.form.Button(
1001 "onClick": function() {
1002 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1003 self.deleteDfa(dfa);
1006 /* XXX I /cannot/ make the following work in as a CSS class
1007 * for some reason. So frustrating... */
1008 "style": function(id) {
1010 "font-weight: bold; color: #c00;" :
1012 }(dfa.id()) + "margin: 0 6px;display: inline;"
1013 }, "dfa-button-" + dfa.id()
1017 "connectId": ["dfa-button-" + dfa.id()],
1018 "label": dojo.string.substitute(
1019 localeStrings.DFA_TIP, dfa.id() > 0 ? [
1020 openils.User.formalName(dfa.creator()),
1021 dojo.date.locale.format(
1022 dojo.date.stamp.fromISOString(dfa.create_time()),
1023 {"formatLength":"short"}
1025 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
1027 }, "dfa-tip-" + dfa.id()
1031 this.deleteDfa = function(dfa) {
1032 if (dfa.id() > 0) { /* real */
1033 this.pcrud.eliminate(
1036 "oncomplete": function() {
1037 self._removeDistribApplied(dfa.id());
1038 delete self.realDfaCache[dfa.id()];
1042 } else { /* virtual */
1043 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
1044 this.virtDfaCounts[dfa.formula().id()] = 0;
1045 /* hasn't been saved yet, so no need to do anything server side */
1046 this._removeDistribApplied(dfa.id());
1051 this._removeDistribApplied = function(dfaId) {
1052 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
1053 dijit.registry.forEach(
1054 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
1056 this._removeDistribAppliedEmptyRows();
1059 this._removeAllDistribAppliedVirtual = function() {
1060 /* Unregister dijits */
1061 dijit.registry.forEach(
1062 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
1064 this._removeDistribAppliedEmptyRows();
1067 this._removeDistribAppliedEmptyRows = function() {
1068 /* Remove any rows with no DFA at all */
1069 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
1071 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
1077 * Insert a new row into the distribution formula selection form
1079 this._addDistribFormulaRow = function() {
1082 if (!self.distribForms) {
1083 // no formulas, hide the form
1084 openils.Util.hide('acq-lit-distrib-formula-tbody');
1088 if(!this.distribFormulaTemplate)
1089 this.distribFormulaTemplate =
1090 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
1092 var row = this.distribFormulaTemplate.cloneNode(true);
1093 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
1095 this.dfSelector = new dijit.form.FilteringSelect(
1096 {"labelAttr": "dynLabel", "labelType": "html"},
1097 nodeByName("selector", row)
1099 this._updateFormulaStore();
1100 this.dfSelector.fetchProperties =
1101 {"sort": [{"attribute": "use_count", "descending": true}]};
1103 var apply = new dijit.form.Button(
1104 {"label": localeStrings.APPLY},
1105 nodeByName('set_button', row)
1108 var reset = new dijit.form.Button(
1109 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
1110 nodeByName("reset_button", row)
1113 dojo.connect(apply, 'onClick',
1115 var form_id = self.dfSelector.attr("value");
1116 if(!form_id) return;
1117 self._applyDistribFormula(form_id);
1118 reset.attr("disabled", false);
1122 dojo.connect(reset, 'onClick',
1124 self.restoreCopyFieldsBeforeDF();
1125 self.virtDfaCounts = {};
1126 self.virtDfaId = -1;
1128 self._updateFormulaStore();
1129 self._removeAllDistribAppliedVirtual();
1130 reset.attr("disabled", "true");
1137 * Applies a distrib formula to the current set of copies
1139 this._applyDistribFormula = function(formula) {
1140 if(!formula) return;
1142 formula = this.distribForms.filter(
1143 function(form) { return form.id() == formula; }
1146 var copyRows = dojo.query('tr', self.copyTbody);
1148 if (this.dfeOffset >= copyRows.length) {
1149 alert(localeStrings.OUT_OF_COPIES);
1153 var entries_applied = 0;
1155 var rowIndex = this.dfeOffset;
1156 rowIndex < copyRows.length;
1160 var row = copyRows[rowIndex];
1161 var copy_id = row.getAttribute('copy_id');
1162 var copyWidgets = this.copyWidgetCache[copy_id];
1163 var entryIndex = this.dfeOffset;
1166 // find the correct entry for the current row
1167 dojo.forEach(formula.entries(),
1170 entryIndex += e.item_count();
1171 if(entryIndex > rowIndex)
1179 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
1180 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
1183 this.saveCopyFieldsBeforeDF(copy_id);
1184 this._copy_fields_for_acqdf.forEach(
1186 if(entry[field]()) {
1187 copyWidgets[field].attr('value', (entry[field]()));
1194 if (entries_applied) {
1195 this.virtDfaCounts[formula.id()] =
1196 ++(this.virtDfaCounts[formula.id()]) || 1;
1197 this._updateFormulaStore();
1198 this._drawDistribAppliedUnit(
1200 var dfa = new acqdfa();
1201 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
1204 this.dfeOffset += entries_applied;
1209 * This function updates the DF store for the dropdown so that use_counts
1210 * can reflect DF applications from this session before they're saved
1213 this._updateFormulaStore = function() {
1214 this.dfSelector.store = new dojo.data.ItemFileReadStore(
1216 "data": self._labelFormulasWithCounts(
1217 acqdf.toStoreData(self.distribForms)
1223 this.saveCopyFieldsBeforeDF = function(copy_id) {
1225 if (!this.oldCopyWidgetCache[copy_id]) {
1226 var copyWidgets = this.copyWidgetCache[copy_id];
1228 this.oldCopyWidgetCache[copy_id] = {};
1229 this._copy_fields_for_acqdf.forEach(
1231 self.oldCopyWidgetCache[copy_id][f] =
1232 copyWidgets[f].attr("value");
1238 this.restoreCopyFieldsBeforeDF = function() {
1240 for (var copy_id in this.oldCopyWidgetCache) {
1241 this._copy_fields_for_acqdf.forEach(
1243 self.copyWidgetCache[copy_id][f].attr(
1244 "value", self.oldCopyWidgetCache[copy_id][f]
1251 this._labelFormulasWithCounts = function(store_data) {
1252 for (var key in store_data.items) {
1253 var obj = store_data.items[key];
1254 obj.use_count = Number(obj.use_count); /* needed for sorting */
1256 if (this.virtDfaCounts[obj.id])
1257 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
1259 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
1260 obj.use_count + "]</span> " + obj.name;
1266 * This method formerly would not refetch the DF formulas if they'd been
1267 * loaded already, but now it always re-fetches, since use_count changes.
1269 this._fetchDistribFormulas = function(onload) {
1270 fieldmapper.standardRequest(
1272 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
1275 "params": [openils.User.authtoken],
1276 "oncomplete": function(r) {
1277 self.distribForms = openils.Util.readResponse(r);
1278 if(!self.distribForms || self.distribForms.length == 0) {
1279 self.distribForms = [];
1281 self._addDistribFormulaRow();
1288 this._drawBatchCopyWidgets = function() {
1289 var row = this.copyBatchRow;
1290 dojo.forEach(liDetailBatchFields,
1292 if(self.copyBatchRowDrawn) {
1293 self.copyBatchWidgets[field].attr('value', null);
1295 var widget = new openils.widget.AutoFieldWidget({
1298 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1299 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1300 searchFilter : (field == 'fund') ? {"active": "t"} : null,
1301 parentNode : dojo.query('[name='+field+']', row)[0],
1302 orgLimitPerms : ['CREATE_PICKLIST'],
1305 "labelType": (field == "fund") ? "html" : null
1307 noCache: (field == "fund"),
1312 if (field == "fund" && w.store)
1313 self._ensureCSSFundClasses(w.store);
1314 self.copyBatchWidgets[field] = w;
1317 if (field == "fund") {
1319 widget.widget, "onChange", function(val) {
1320 self._updateFundSelectorStyle(widget, val);
1327 this.copyBatchRowDrawn = true;
1330 this.batchCopyUpdate = function() {
1332 for(var k in this.copyWidgetCache) {
1333 var cache = this.copyWidgetCache[k];
1334 dojo.forEach(liDetailBatchFields, function(f) {
1335 var newval = self.copyBatchWidgets[f].attr('value');
1336 if(newval) cache[f].attr('value', newval);
1341 this._drawCopies = function(li) {
1344 // this button sets the total number of copies for a given lineitem
1345 acqLitAddCopyCount.onClick = function() {
1346 var count = acqLitCopyCountInput.attr('value');
1349 while(self.copyCount() < count)
1352 // delete rows if necessary
1353 var diff = self.copyCount() - count;
1355 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
1356 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
1357 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
1359 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1365 if(li.lineitem_details().length > 0) {
1366 dojo.forEach(li.lineitem_details(),
1368 self.addCopy(li, copy);
1376 this.copyCount = function() {
1378 for(var id in this.copyCache) {
1379 if(!this.copyCache[id].isdeleted())
1385 this.virtCopyId = -1;
1386 this.addCopy = function(li, copy) {
1387 var row = this.copyRow.cloneNode(true);
1388 this.copyTbody.appendChild(row);
1392 copy = new fieldmapper.acqlid();
1394 copy.id(this.virtCopyId--);
1395 copy.lineitem(li.id());
1398 this.copyCache[copy.id()] = copy;
1399 row.setAttribute('copy_id', copy.id());
1400 self.copyWidgetCache[copy.id()] = {};
1402 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1404 dojo.forEach(liDetailFields,
1407 if (field == "fund") {
1408 searchFilter = (copy.fund() ?
1409 {"-or": {"active": "t", "id": copy.fund()}} :
1412 searchFilter = null;
1415 var readOnly = false;
1417 // TODO: Add support for changing the owning_lib after real copies have been made.
1418 // owning_lib is order data as much as its item data
1419 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
1423 // TODO: add support for changing the fund after debits have been created
1424 // Note: invoicing allows the change
1425 if(copy.fund_debit() && field == 'fund') {
1429 var widget = new openils.widget.AutoFieldWidget({
1432 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1433 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1434 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1435 searchFilter : searchFilter,
1436 noCache: (field == "fund"),
1438 parentNode : dojo.query('[name='+field+']', row)[0],
1439 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
1440 readOnly : readOnly,
1444 // make sure we capture the value from any async widgets
1447 if (field == "fund" && w.store)
1448 self._ensureCSSFundClasses(w.store);
1451 copy[field](ww.getFormattedValue())
1453 self.copyWidgetCache[copy.id()][field] = w;
1455 dojo.connect(w, 'onChange',
1457 if (field == "fund")
1458 self._updateFundSelectorStyle(widget, val);
1460 if (!readOnly && (copy.isnew() || val != copy[field]())) {
1461 // prevent setting ischanged() automatically on widget load for existing copies
1462 copy[field](widget.getFormattedValue())
1463 copy.ischanged(true);
1472 this.updateLidState(copy, row);
1475 this._ensureCSSFundClass = function(id) {
1476 if (!this.fundStyleSheet) {
1478 "style", {"type": "text/css"},
1479 document.getElementsByTagName("head")[0], "last"
1481 this.fundStyleSheet = document.styleSheets[
1482 document.styleSheets.length - 1
1486 var cn = "fund_" + id;
1487 if (!this.haveFundClass[cn]) {
1488 fieldmapper.standardRequest(
1489 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
1491 "params": [openils.User.authtoken, id],
1493 "oncomplete": function(r) {
1494 r = openils.Util.readResponse(r);
1495 self.fundBalanceState[id] = r;
1497 if (r[0] /* stop */)
1498 style = fundStyles.stop;
1499 else if (r[1] /* warning */)
1500 style = fundStyles.warning;
1501 self.fundStyleSheet.insertRule(
1502 "." + cn + " { " + style + " }",
1503 self.fundStyleSheet.cssRules.length
1505 self.haveFundClass[cn] = true;
1512 this._ensureCSSFundClasses = function(store) {
1514 "query": {"id": "*"},
1515 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
1519 this._updateFundSelectorStyle = function(widget, fund_id) {
1520 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
1521 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
1524 this.updateLidState = function(copy, row) {
1525 if (typeof(row) == "undefined") {
1527 'tr[copy_id="' + copy.id() + '"]', this.copyTbody
1532 var recv_link = nodeByName("receive", row);
1533 var unrecv_link = nodeByName("unreceive", row);
1534 var del_link = nodeByName("delete", row);
1535 var cxl_link = nodeByName("cancel", row);
1536 var claim_link = nodeByName("claim", row);
1537 var cxl_reason_link = nodeByName("cancel_reason", row);
1539 if (copy.cancel_reason()) {
1540 openils.Util.hide(del_link.parentNode);
1541 openils.Util.hide(recv_link);
1542 openils.Util.hide(unrecv_link);
1543 openils.Util.hide(cxl_link);
1544 openils.Util.hide(claim_link);
1546 /* XXX the following may leak memory in a long lived table: dijits may not get destroyed... not positive. revisit. */
1547 var holds_reason = dojo.create(
1549 "style": "border-bottom: 1px dashed #000;",
1550 "innerHTML": "Cancelled" /* XXX [sic] and i18n */
1551 }, cxl_reason_link, "only"
1555 "label": "<em>" + copy.cancel_reason().label() +
1556 "</em><br />" + copy.cancel_reason().description(),
1557 "connectId": [holds_reason]
1558 }, dojo.create("span", null, cxl_reason_link, "last")
1560 openils.Util.show(cxl_reason_link, "inline");
1561 } else if (this.isPO) {
1562 /* Only using this in one place so far, but may want it for better
1563 * decisions on when to display certain controls. */
1564 var li_state = this.liCache[copy.lineitem()].state();
1566 openils.Util.hide(del_link.parentNode);
1567 openils.Util.hide(cxl_reason_link);
1569 /* Avoid showing (un)receive links, cancel links, for virt copies */
1570 if (copy.id() > 0) {
1571 if (copy.recv_time()) {
1572 openils.Util.hide(cxl_link);
1573 openils.Util.hide(recv_link);
1574 openils.Util.hide(claim_link);
1576 openils.Util.show(unrecv_link, "inline");
1577 unrecv_link.onclick = function() {
1578 if (confirm(localeStrings.UNRECEIVE_LID))
1579 self.issueReceive(copy, /* rollback */ true);
1582 openils.Util.hide(unrecv_link);
1584 if (this.claimEligibleLid[copy.id()]) {
1585 openils.Util.show(claim_link, "inline");
1586 claim_link.onclick = function() {
1587 self.claimDialog.show(
1588 self.liCache[copy.lineitem()], copy.id()
1592 openils.Util.hide(claim_link);
1595 openils.Util[li_state == "on-order" ? "show" : "hide"](
1598 openils.Util.show(cxl_link, "inline");
1599 recv_link.onclick = function() {
1600 if (self.checkLiAlerts(copy.lineitem()))
1601 self.issueReceive(copy);
1603 cxl_link.onclick = function() {
1604 self.cancelLid(copy.id());
1608 openils.Util.hide(cxl_link);
1609 openils.Util.hide(unrecv_link);
1610 openils.Util.hide(recv_link);
1611 openils.Util.hide(claim_link);
1614 openils.Util.hide(unrecv_link);
1615 openils.Util.hide(recv_link);
1616 openils.Util.hide(cxl_reason_link);
1617 openils.Util.hide(claim_link);
1619 del_link.onclick = function() { self.deleteCopy(row) };
1620 openils.Util.show(del_link.parentNode);
1624 this.cancelLid = function(lid_id) {
1625 lidCancelDialog._lid_id = lid_id;
1626 openils.Util.show(lidCancelDialog.domNode.parentNode);
1627 lidCancelDialog.show();
1628 if (!lidCancelDialog._prepared) {
1629 var widget = new openils.widget.AutoFieldWidget({
1630 "fmField": "cancel_reason",
1631 "fmClass": "acqlid",
1632 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
1633 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1638 acqLidCancelButton.onClick = function() {
1639 if (w.attr("value")) {
1640 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
1642 lidCancelDialog._lid_id,
1646 lidCancelDialog.hide();
1649 lidCancelDialog._prepared = true;
1655 this._cancelLid = function(lid_id, reason) {
1656 fieldmapper.standardRequest(
1657 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
1658 "params": [openils.User.authtoken, lid_id, reason],
1660 "onresponse": function(r) {
1661 if (r = openils.Util.readResponse(r)) {
1663 for (var id in r.lid) {
1664 /* actually this should only iterate once */
1665 self.copyCache[id].cancel_reason(
1666 r.lid[id].cancel_reason
1668 self.updateLidState(self.copyCache[id]);
1677 this._confirmAlert = function(li, lin) {
1679 dojo.string.substitute(
1680 localeStrings.CONFIRM_LI_ALERT, [
1681 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1682 "title", "lineitem_marc_attr_definition"
1684 lin.alert_text().code(),
1685 lin.alert_text().description() || "",
1692 this.checkLiAlerts = function(li_id) {
1693 var li = this.liCache[li_id];
1695 var alert_notes = li.lineitem_notes().filter(
1696 function(o) { return Boolean(o.alert_text()); }
1699 /* this is _intentionally_ not done in a call to forEach() ... */
1700 for (var i = 0; i < alert_notes.length; i++) {
1701 if (this.noteAcks[alert_notes[i].id()])
1703 else if (!this._confirmAlert(li, alert_notes[i]))
1706 this.noteAcks[alert_notes[i].id()] = true;
1712 this.deleteCopy = function(row) {
1713 var copy = this.copyCache[row.getAttribute('copy_id')];
1714 copy.isdeleted(true);
1716 delete this.copyCache[copy.id()];
1717 this.copyTbody.removeChild(row);
1720 this._virtDfaCountsAsList = function() {
1722 for (var key in this.virtDfaCounts) {
1723 for (var i = 0; i < this.virtDfaCounts[key]; i++)
1729 this.confirmBreachedCopyFunds = function(copies) {
1730 var stop = 0, warning = 0;
1734 var state = self.fundBalanceState[o.fund()];
1735 if (state[0] /* stop */)
1737 else if (state[1] /* warning */)
1744 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
1745 } else if (warning) {
1746 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
1751 this.saveCopyChanges = function(liId) {
1757 for(var id in this.copyCache) {
1758 var c = this.copyCache[id];
1759 if(!c.isdeleted()) total++;
1760 if(c.isnew() || c.ischanged() || c.isdeleted()) {
1761 if(c.id() < 0) c.id(null);
1767 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
1770 if (copies.length > 0) {
1771 if (!this.confirmBreachedCopyFunds(copies))
1774 if (typeof(this._copy_count_cb) == "function")
1775 this._copy_count_cb(liId, total);
1777 openils.Util.show("acq-lit-update-copies-progress");
1778 fieldmapper.standardRequest(
1779 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1781 params: [openils.User.authtoken, copies],
1782 onresponse: function(r) {
1783 var res = openils.Util.readResponse(r);
1784 litUpdateCopiesProgress.update(res);
1786 oncomplete: function() {
1787 self.drawCopies(liId);
1788 openils.Util.hide("acq-lit-update-copies-progress");
1794 var dfa_list = this._virtDfaCountsAsList();
1795 if (dfa_list.length > 0) {
1796 fieldmapper.standardRequest(
1798 "open-ils.acq.distribution_formula.record_application"],
1801 "params": [openils.User.authtoken, dfa_list, liId],
1802 "onresponse": function(r) {
1803 var res = openils.Util.readResponse(r);
1804 if (res && res.length < dfa_list.length)
1805 alert(localeStrings.DFA_NOT_ALL);
1809 this.virtDfaCounts = {};
1813 this._updateCreatePoPrepayCheckbox = function(prepay) {
1814 var prepay = openils.Util.isTrue(prepay);
1815 this._prepayRequiredByVendor = prepay;
1816 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
1819 this._confirmPoPrepaySituation = function() {
1820 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
1821 if (want_prepay != this._prepayRequiredByVendor) {
1824 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
1825 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
1832 this.applySelectedLiAction = function(action) {
1836 case 'delete_selected':
1837 this._deleteLiList(self.getSelected());
1840 case 'create_order':
1841 this._loadPOSelect();
1842 acqLitPoCreateDialog.show();
1845 case 'save_picklist':
1846 this._loadPLSelect();
1847 acqLitSavePlDialog.show();
1850 case 'selector_ready':
1852 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
1853 acqLitChangeLiStateDialog.show();
1861 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
1868 case 'rollback_receive_po':
1869 this.rollbackPoReceive();
1872 case 'create_assets':
1873 this.createAssets();
1876 case 'export_attr_list':
1877 this.chooseExportAttr();
1880 case 'batch_apply_funds':
1881 this.applyBatchLiFunds();
1884 case 'add_brief_record':
1886 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
1888 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
1892 case "cancel_lineitems":
1893 this.maybeCancelLineitems();
1896 case "change_claim_policy":
1897 var li_list = this.getSelected();
1898 this.claimPolicyPicker.attr("value", null);
1899 liClaimPolicyDialog.show();
1900 liClaimPolicySave.onClick = function() {
1901 self.changeClaimPolicy(
1903 self.claimPolicyPicker.attr("value"),
1906 function(li) { self.setClaimPolicyControl(li); }
1908 liClaimPolicyDialog.hide();
1916 this.changeClaimPolicy = function(li_list, value, callback) {
1918 function(li) { li.claim_policy(value); }
1920 fieldmapper.standardRequest(
1921 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
1922 "params": [openils.User.authtoken, li_list],
1924 "oncomplete": function(r) {
1925 r = openils.Util.readResponse(r);
1926 if (callback) callback(r);
1932 this.createAssets = function() {
1933 if(!this.isPO) return;
1934 if(!confirm(localeStrings.CREATE_PO_ASSETS_CONFIRM)) return;
1935 this.show('acq-lit-progress-numbers');
1937 fieldmapper.standardRequest(
1938 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
1940 params: [this.authtoken, this.isPO],
1941 onresponse: function(r) {
1942 var resp = openils.Util.readResponse(r);
1943 self._updateProgressNumbers(resp, true);
1949 this.maybeCancelLineitems = function() {
1950 openils.Util.show("acq-lit-cancel-reason", "inline");
1951 if (!acqLitCancelLineitemsButton._prepared) {
1952 var widget = new openils.widget.AutoFieldWidget({
1953 "fmField": "cancel_reason",
1955 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
1956 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1961 acqLitCancelLineitemsButton.onClick = function() {
1962 if (w.attr("value")) {
1963 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
1964 self._cancelLineitems(w.attr("value"));
1966 openils.Util.hide("acq-lit-cancel-reason");
1969 acqLitCancelLineitemsButton._prepared = true;
1975 this._cancelLineitems = function(reason) {
1976 var id_list = this.getSelected().map(function(o) { return o.id(); });
1977 fieldmapper.standardRequest(
1978 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
1979 "params": [openils.User.authtoken, id_list, reason],
1981 "onresponse": function(r) {
1982 if (r = openils.Util.readResponse(r)) {
1984 for (var id in r.li) {
1985 self.liCache[id].state(r.li[id].state);
1986 self.liCache[id].cancel_reason(
1987 r.li[id].cancel_reason
1989 self.updateLiState(self.liCache[id]);
1992 if (r.lid && self.copyCache) {
1993 for (var id in r.lid) {
1994 if (self.copyCache[id]) {
1995 self.copyCache[id].cancel_reason(
1996 r.lid[id].cancel_reason
1998 self.updateLidState(self.copyCache[id]);
2008 this.chooseExportAttr = function() {
2009 if (!acqLitExportAttrSelector._li_setup) {
2011 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
2013 "data": acqliad.toStoreData(
2015 "acqliad", {"code": li_exportable_attrs}
2020 acqLitExportAttrSelector.setValue();
2021 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
2022 acqLitExportAttrSelector._li_setup = true;
2024 openils.Util.show("acq-lit-export-attr-holder", "inline");
2027 this.exportAttrList = function() {
2028 var attr_def = acqLitExportAttrSelector.item;
2029 var li_list = this.getSelected();
2030 var value_list = li_list.map(
2032 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2033 attr_def.code, "lineitem_marc_attr_definition"
2036 ).filter(function(attr) { return Boolean(attr); });
2038 if (value_list.length > 0) {
2039 if (value_list.length < li_list.length) {
2041 dojo.string.substitute(
2042 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
2049 openils.XUL.contentToFileSaveDialog(
2050 value_list.join("\n"),
2051 localeStrings.EXPORT_SAVE_DIALOG_TITLE
2057 alert(dojo.string.substitute(
2058 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
2062 openils.Util.hide("acq-lit-export-attr-holder");
2065 this.printPO = function() {
2066 if(!this.isPO) return;
2067 progressDialog.show(true);
2068 fieldmapper.standardRequest(
2069 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
2071 params: [this.authtoken, this.isPO, 'html'],
2072 oncomplete: function(r) {
2073 progressDialog.hide();
2074 var evt = openils.Util.readResponse(r);
2075 if(evt && evt.template_output()) {
2076 win = window.open('','', 'resizable,width=800,height=600,scrollbars=1');
2077 win.document.body.innerHTML = evt.template_output().data();
2085 this.receivePO = function() {
2086 if (!this.isPO) return;
2088 for (var id in this.liCache) {
2089 /* assumption: liCache reflects exactly the
2090 * set of LIs that belong to our PO */
2091 if (this.liCache[id].state() != "received" &&
2092 !this.checkLiAlerts(id)) return;
2095 this.show('acq-lit-progress-numbers');
2097 fieldmapper.standardRequest(
2098 ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
2100 params: [this.authtoken, this.isPO],
2101 onresponse : function(r) {
2102 var resp = openils.Util.readResponse(r);
2103 self._updateProgressNumbers(resp, true);
2109 this.issueReceive = function(obj, rollback) {
2110 /* (For now) there shall be no marking LI or LIDs (un)received
2111 * except from the actual "view PO" interface. */
2112 if (!this.isPO) return;
2115 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
2117 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
2119 progressDialog.show(true);
2120 fieldmapper.standardRequest(
2121 ["open-ils.acq", method], {
2123 "params": [this.authtoken, obj.id()],
2124 "onresponse": function(r) {
2125 if (r = openils.Util.readResponse(r)) {
2126 self.fetchClaimInfo(
2127 part == "lineitem" ? obj.id() : obj.lineitem(),
2129 function() { self.handleReceive(r); }
2131 progressDialog.hide();
2139 * Handles the responses from receive and rollback ML calls.
2141 this.handleReceive = function(resp) {
2144 for (var li_id in resp.li) {
2145 for (var key in resp.li[li_id])
2146 self.liCache[li_id][key](resp.li[li_id][key]);
2147 self.updateLiState(self.liCache[li_id]);
2151 if (typeof(self.poUpdateCallback) == "function")
2152 self.poUpdateCallback(resp.po);
2155 for (var lid_id in resp.lid) {
2156 for (var key in resp.lid[lid_id])
2157 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
2158 self.updateLidState(self.copyCache[lid_id]);
2164 this.rollbackPoReceive = function() {
2165 if(!this.isPO) return;
2166 if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
2167 this.show('acq-lit-progress-numbers');
2169 fieldmapper.standardRequest(
2170 ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
2172 params: [this.authtoken, this.isPO],
2173 onresponse : function(r) {
2174 var resp = openils.Util.readResponse(r);
2175 self._updateProgressNumbers(resp, true);
2181 this._updateProgressNumbers = function(resp, reloadOnComplete) {
2183 dojo.byId('acq-pl-lit-li-processed').innerHTML = resp.li;
2184 dojo.byId('acq-pl-lit-lid-processed').innerHTML = resp.lid;
2185 dojo.byId('acq-pl-lit-debits-processed').innerHTML = resp.debits_accrued;
2186 dojo.byId('acq-pl-lit-bibs-processed').innerHTML = resp.bibs;
2187 dojo.byId('acq-pl-lit-indexed-processed').innerHTML = resp.indexed;
2188 dojo.byId('acq-pl-lit-copies-processed').innerHTML = resp.copies;
2189 if(resp.complete && reloadOnComplete)
2190 location.href = location.href;
2194 this._createPO = function(fields) {
2195 this.show('acq-lit-progress-numbers');
2196 var po = new fieldmapper.acqpo();
2197 po.provider(this.createPoProviderSelector.attr('value'));
2198 po.ordering_agency(this.createPoAgencySelector.attr('value'));
2199 po.prepayment_required(fields.prepayment_required[0] ? true : false);
2201 var selected = this.getSelected( (fields.create_from == 'all') );
2202 if(selected.length == 0) return;
2204 var max = selected.length * 3;
2207 fieldmapper.standardRequest(
2208 ['open-ils.acq', 'open-ils.acq.purchase_order.create'],
2211 openils.User.authtoken,
2214 lineitems : selected.map(function(li) { return li.id() }),
2215 create_assets : fields.create_assets[0],
2219 onresponse : function(r) {
2220 var resp = openils.Util.readResponse(r);
2221 self._updateProgressNumbers(resp);
2223 location.href = oilsBasePath + '/acq/po/view/' + resp.purchase_order.id();
2229 this.batchFundWidget = null;
2231 this.applyBatchLiFunds = function() {
2233 var liIds = this.getSelected().map(function(li) { return li.id(); });
2234 if(liIds.length == 0) return; // warn?
2237 batchFundUpdateDialog.show();
2239 if(!this.batchFundWidget) {
2240 this.batchFundWidget = new openils.widget.AutoFieldWidget({
2242 selfReference : true,
2243 labelFormat : fundLabelFormat,
2244 searchFormat : fundSearchFormat,
2245 searchFilter : {"active": "t"},
2246 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
2247 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2248 dijitArgs : { "required": true, "labelType": "html" },
2251 this.batchFundWidget.build();
2254 dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
2255 dojo.connect(batchFundUpdateSubmit, 'onClick',
2258 // TODO: call .dry_run first to test thresholds
2259 fieldmapper.standardRequest(
2260 ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
2263 openils.User.authtoken,
2265 self.batchFundWidget.widget.attr('value')
2267 oncomplete : function(r) {
2268 var resp = openils.Util.readResponse(r);
2270 location.href = location.href;
2279 this._deleteLiList = function(list, idx) {
2280 if(idx == null) idx = 0;
2281 if(idx >= list.length) return;
2282 var liId = list[idx].id();
2283 fieldmapper.standardRequest(
2284 ['open-ils.acq', 'open-ils.acq.lineitem.delete'],
2286 params: [openils.User.authtoken, liId],
2287 oncomplete: function(r) {
2288 self.removeLineitem(liId);
2289 self._deleteLiList(list, ++idx);
2295 this.editOrderMarc = function(li) {
2297 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
2298 to true in about:config */
2300 if(!openils.XUL.enableXPConnect()) return;
2302 if(openils.XUL.isXUL()) {
2303 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
2305 win = window.open('/xul/server/cat/marcedit.xul');
2309 record : {marc : li.marc()},
2311 label: 'Save Record', // XXX I18N
2312 func: function(xmlString) {
2314 fieldmapper.standardRequest(
2315 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
2317 params: [openils.User.authtoken, li],
2318 oncomplete: function(r) {
2319 openils.Util.readResponse(r);
2321 self.drawInfo(li.id())
2330 this._savePl = function(values) {
2332 var selected = this.getSelected( (values.which == 'all') );
2333 openils.Util.show('acq-lit-generic-progress');
2335 if(values.new_name) {
2336 openils.acq.Picklist.create(
2337 {name: values.new_name},
2339 self._updateLiList(id, selected, 0,
2341 location.href = oilsBasePath + '/acq/picklist/view/' + id;
2345 } else if(values.existing_pl) {
2346 // update lineitems to use an existing picklist
2347 self._updateLiList(values.existing_pl, selected, 0,
2349 location.href = oilsBasePath + '/acq/picklist/view/' + values.existing_pl;
2354 this._updateLiState = function(values, state) {
2356 var selected = this.getSelected( (values.which == 'all') );
2357 if(!selected.length) return;
2358 dojo.forEach(selected, function(li) {li.state(state);});
2359 self._updateLiList(null, selected, 0,
2360 // TODO consider inline updates for efficiency
2361 function() { location.href = location.href }
2365 this._updateLiList = function(pl, list, idx, oncomplete) {
2366 if(idx >= list.length) return oncomplete();
2368 if(pl != null) li.picklist(pl);
2369 litGenericProgress.update({maximum: list.length, progress: idx});
2370 new openils.acq.Lineitem({lineitem:li}).update(
2372 self._updateLiList(pl, list, ++idx, oncomplete);
2377 this._loadPOSelect = function() {
2378 if (!this.createPoProviderSelector) {
2379 var widget = new openils.widget.AutoFieldWidget({
2380 "fmField": "provider",
2382 "searchFilter": {"active": "t"},
2383 "parentNode": dojo.byId("acq-lit-po-provider"),
2385 "onChange": function() {
2387 self._updateCreatePoPrepayCheckbox(
2388 this.item.prepayment_required
2394 widget.build(function(w) { self.createPoProviderSelector = w; });
2397 if (!this.createPoAgencySelector) {
2398 var widget = new openils.widget.AutoFieldWidget({
2399 "fmField": "ordering_agency",
2401 "parentNode": dojo.byId("acq-lit-po-agency"),
2402 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2404 widget.build(function(w) { self.createPoAgencySelector = w; });
2408 this._loadPLSelect = function(preSel) {
2409 if(this._plSelectLoaded) return;
2411 function handleResponse(r) {
2412 plList.push(r.recv().content());
2414 var method = 'open-ils.acq.picklist.user.retrieve';
2415 fieldmapper.standardRequest(
2416 ['open-ils.acq', method],
2418 params: [this.authtoken],
2419 onresponse: handleResponse,
2420 oncomplete: function() {
2421 self._plSelectLoaded = true;
2422 acqLitAddExistingSelect.store =
2423 new dojo.data.ItemFileReadStore({data:acqpl.toStoreData(plList)});
2425 acqLitAddExistingSelect.setValue(preSel);
2431 this.showRealCopyEditUI = function(li) {
2436 this._fetchLineitem(li.id(),
2438 li = self.liCache[li.id()] = fullLi;
2442 id : li.lineitem_details().map(
2443 function(item) { return item.eg_copy_id() }
2447 oncomplete : function(r) {
2449 var r_list = openils.Util.readResponse( r );
2450 for (var i = 0; i < r_list.length; i++) {
2451 var copy = r_list[i];
2452 var volId = copy.call_number();
2453 var volume = self.volCache[volId];
2455 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2457 copy.call_number(volume);
2458 copyList.push(copy);
2461 // If we need to, we can pass in an update_copy function to handle the update instead of volume_item_creator
2462 xulG.volume_item_creator( { 'existing_copies' : copyList } );
2465 alert('error in oncomplete: ' + E);