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');
16 dojo.require("openils.widget.PCrudAutocompleteBox");
17 dojo.require('openils.CGI');
19 if (!localeStrings) { /* we can do this because javascript doesn't have block scope */
20 dojo.requireLocalization('openils.acq', 'acq');
21 var localeStrings = dojo.i18n.getLocalization('openils.acq', 'acq');
23 const XUL_OPAC_WRAPPER = 'chrome://open_ils_staff_client/content/cat/opac.xul';
24 var li_exportable_attrs = ["issn", "isbn", "upc"];
26 var fundLabelFormat = [
27 '<span class="fund_${0}">${1} (${2})</span>', 'id', 'code', 'year'
29 var fundSearchFormat = ['${0} (${1})', 'code', 'year'];
31 function nodeByName(name, context) {
32 return dojo.query('[name='+name+']', context)[0];
35 // for caching linked users. e.g. lineitem_detail.receiver
38 var liDetailBatchFields = ['fund', 'owning_lib', 'location', 'collection_code', 'circ_modifier', 'cn_label'];
39 var liDetailFields = liDetailBatchFields.concat(['barcode', 'note']);
41 "stop": "color: #c00; font-weight: bold;",
42 "warning": "color: #c93;"
45 function AcqLiTable() {
52 this.haveFundClass = {}
53 this.fundBalanceState = {};
54 this.realDfaCache = {};
55 this.virtDfaCounts = {};
58 this.claimEligibleLidByLi = {};
59 this.claimEligibleLid = {};
60 this.toggleState = false;
61 this.tbody = dojo.byId('acq-lit-tbody');
64 this.authtoken = openils.User.authtoken;
65 this.pcrud = new openils.PermaCrud();
66 this.rowTemplate = this.tbody.removeChild(dojo.byId('acq-lit-row'));
67 this.copyTbody = dojo.byId('acq-lit-li-details-tbody');
68 this.copyRow = this.copyTbody.removeChild(dojo.byId('acq-lit-li-details-row'));
69 this.copyBatchRow = dojo.byId('acq-lit-li-details-batch-row');
70 this.copyBatchWidgets = {};
71 this.liNotesTbody = dojo.byId('acq-lit-notes-tbody');
72 this.liNotesRow = this.liNotesTbody.removeChild(dojo.byId('acq-lit-notes-row'));
73 this.realCopiesTbody = dojo.byId('acq-lit-real-copies-tbody');
74 this.realCopiesRow = this.realCopiesTbody.removeChild(dojo.byId('acq-lit-real-copies-row'));
75 this._copy_fields_for_acqdf = ['owning_lib', 'location'];
76 this.skipInitialEligibilityCheck = false;
77 this.claimDialog = new ClaimDialogManager(
78 liClaimDialog, finalClaimDialog, this.claimEligibleLidByLi,
79 function(li) { /* callback that fires when claims are made */
80 self.fetchClaimInfo(li.id(), /* force update */ true);
83 this.vlAgent = new VLAgent();
85 this.focusLineitem = new openils.CGI().param('focus_li');
87 dojo.byId("acq-lit-li-actions-selector").onchange = function() {
88 self.applySelectedLiAction(this.options[this.selectedIndex].value);
89 this.selectedIndex = 0;
92 acqLitCreatePoSubmit.onClick = function() {
93 if (!self.createPoProviderSelector.attr("value") ||
94 !self.createPoAgencySelector.attr("value")) {
95 alert(localeStrings.CREATE_PO_INVALID);
97 } else if (self._confirmPoPrepaySituation()) {
98 acqLitPoCreateDialog.hide();
99 self._createPO(acqLitPoCreateDialog.getValues());
105 acqLitSavePlButton.onClick = function() {
106 acqLitSavePlDialog.hide();
107 self._savePl(acqLitSavePlDialog.getValues());
110 acqLitCancelLiStateButton.onClick = function() {
111 acqLitChangeLiStateDialog.hide();
113 acqLitSaveLiStateButton.onClick = function() {
114 acqLitChangeLiStateDialog.hide();
115 self._updateLiState(acqLitChangeLiStateDialog.getValues(), acqLitChangeLiStateDialog.attr('state'));
119 dojo.byId('acq-lit-select-toggle').onclick = function(){self.toggleSelect()};
120 dojo.byId('acq-lit-info-back-button').onclick = function(){self.show('list')};
121 dojo.byId('acq-lit-copies-back-button').onclick = function(){self.show('list')};
122 dojo.byId('acq-lit-notes-back-button').onclick = function(){self.show('list')};
123 dojo.byId('acq-lit-real-copies-back-button').onclick = function(){self.show('list')};
125 this.reset = function(keep_selectors) {
126 while(self.tbody.childNodes[0])
127 self.tbody.removeChild(self.tbody.childNodes[0]);
135 this.setNext = function(handler) {
136 var link = dojo.byId('acq-lit-next');
138 dojo.style(link, 'visibility', 'visible');
139 link.onclick = handler;
141 dojo.style(link, 'visibility', 'hidden');
145 this.setPrev = function(handler) {
146 var link = dojo.byId('acq-lit-prev');
148 dojo.style(link, 'visibility', 'visible');
149 link.onclick = handler;
151 dojo.style(link, 'visibility', 'hidden');
156 * Ensures this.focusLineitem is in view and causes a brief
157 * border around the lineitem to come to life then fade.
159 this.focusLi = function() {
160 if (!this.focusLineitem) return;
162 // set during addLineitem()
163 var node = dojo.byId('li-title-ref-' + this.focusLineitem);
165 // LI may not yet be rendered
168 // prevent numerous re-focuses
169 this.focusLineitem = null;
171 // causes the full row to be visible
172 dijit.scrollIntoView(node);
175 dojo.query('[attr=title]', node)[0].focus();
177 dojo.require('dojox.fx');
181 dojox.fx.highlight({color : '#BB4433', node : node, duration : 2000}).play();
186 this.show = function(div) {
187 openils.Util.hide('acq-lit-table-div');
188 openils.Util.hide('acq-lit-info-div');
189 openils.Util.hide('acq-lit-li-details');
190 openils.Util.hide('acq-lit-notes-div');
191 openils.Util.hide('acq-lit-real-copies-div');
192 openils.Util.hide('acq-lit-asset-creator');
195 openils.Util.show('acq-lit-table-div');
199 openils.Util.show('acq-lit-info-div');
202 openils.Util.show('acq-lit-li-details');
205 openils.Util.show('acq-lit-real-copies-div');
208 openils.Util.show('acq-lit-notes-div');
210 case 'asset-creator':
211 openils.Util.show('acq-lit-asset-creator');
215 openils.Util.show(div);
219 this.hide = function() {
223 this.toggleSelect = function() {
225 dojo.forEach(self.selectors, function(i){i.checked = false});
227 dojo.forEach(self.selectors, function(i){i.checked = true});
228 self.toggleState = !self.toggleState;
232 this.getAll = function(callback, id_only) {
233 /* For some uses of the li table, we may not really know about "all"
234 * the lineitems that the user thinks we know about. If we're a paged
235 * picklist, for example, we only know about the lineitems we've
236 * displayed, but not necessarily all the lineitems on the picklist.
237 * So we reach out to pcrud to inform us.
240 var oncomplete = function(r) {
241 var id_list = openils.Util.readResponse(r);
245 self.fetchLineitemsById(id_list, callback);
250 "jub", {"picklist": this.isPL}, {
251 "id_list": true, /* sic, even if id_only */
253 "oncomplete": oncomplete
257 } else if (this.isPO) {
259 "jub", {"purchase_order": this.isPO}, {
262 "oncomplete": oncomplete
266 } else if (this.isUni && this.pager) {
267 this.pager.getAllLineitemIDs(oncomplete);
271 /* If execution reaches this point, we don't need or can't perform
272 * any special tricks to find out the "real" list of "all" lineitems
273 * in this context, so we fall back to the old method.
275 callback(this.getSelected(true, null, id_only));
278 /** @param all If true, assume all are selected */
279 this.getSelected = function(
281 callback /* If you want a "good" idea of "all" lineitems, you must
282 provide a callback that accepts an array parameter, rather than
283 relying on the return value of this method itself. */,
287 return this.getAll(callback, id_only);
289 var indices = {}; /* use to uniqify. needed in paging situations. */
290 dojo.forEach(this.selectors,
293 indices[i.parentNode.parentNode.getAttribute('li')] = true;
297 var result = openils.Util.objectProperties(indices);
300 result = result.map(function(liId) { return self.liCache[liId]; });
308 this.setRowAttr = function(td, liWrapper, field, type) {
309 var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
310 td.appendChild(document.createTextNode(val));
313 this.setClaimPolicyControl = function(li, row) {
314 if (!self.claimPolicyPicker) {
315 self.claimPolicyPicker = true; /* prevents a race condition */
316 new openils.widget.AutoFieldWidget({
317 "parentNode": "acq-lit-li-claim-policy",
319 "selfReference": true,
320 "dijitArgs": {"required": true}
321 }).build(function(w) { self.claimPolicyPicker = w; });
324 if (!row) row = this._findLiRow(li);
326 var actViewPolicy = nodeByName("action_view_claim_policy", row);
327 if (li.claim_policy())
328 actViewPolicy.innerHTML = localeStrings.CHANGE_CLAIM_POLICY;
330 if (!actViewPolicy.onclick) {
331 actViewPolicy.onclick = function() {
332 if (li.claim_policy())
333 self.claimPolicyPicker.attr("value", li.claim_policy());
334 liClaimPolicyDialog.show();
335 liClaimPolicySave.onClick = function() {
336 self.changeClaimPolicy(
337 [li], self.claimPolicyPicker.attr("value"),
339 self.setClaimPolicyControl(li, row);
340 self.reconsiderClaimControl(li, row);
341 liClaimPolicyDialog.hide();
349 this.fetchClaimInfo = function(liId, force, callback, row) {
351 liId, function(full) {
352 self.liCache[full.id()] = full;
353 self.checkClaimEligibility(full, callback, row);
359 * Inserts a single lineitem into the growing table of lineitems
360 * @param {Object} li The lineitem object to insert
362 this.addLineitem = function(li, skip_final_placement) {
363 this.liCache[li.id()] = li;
365 // insert the row right away so that final order isn't
366 // dependent on how long subsequent async request take
367 // for a given line item
368 var row = self.rowTemplate.cloneNode(true);
369 if (!skip_final_placement) {
370 self.tbody.appendChild(row);
372 self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
374 // sort the lineitem notes on edit_time
375 if(!li.lineitem_notes()) li.lineitem_notes([]);
377 var liWrapper = new openils.acq.Lineitem({lineitem:li});
378 row.setAttribute('li', li.id());
379 var tds = dojo.query('[attr]', row);
380 dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
381 dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
383 // so we can scroll to it later
384 dojo.query('[name=bib-info-cell]', row)[0].id = 'li-title-ref-' + li.id();
387 liWrapper.findAttr("isbn", "lineitem_marc_attr_definition") ||
388 liWrapper.findAttr("upc", "lineitem_marc_attr_definition");
390 // XXX media prefix for added content
392 nodeByName("jacket", row).setAttribute(
393 "src", "/opac/extras/ac/jacket/small/" + identifier
397 nodeByName("liid", row).innerHTML += li.id();
400 openils.Util.show(nodeByName('catalog', row), 'inline');
401 nodeByName("catalog_link", row).onclick = this.generateMakeRecTab(li.eg_bib_id());
403 openils.Util.show(nodeByName('link_to_catalog', row), 'inline');
404 nodeByName("link_to_catalog_link", row).onclick = function() { self.drawBibFinder(li) };
407 if (li.queued_record()) {
408 this.pcrud.retrieve('vqbr', li.queued_record(),
410 oncomplete : function(r) {
411 var qrec = openils.Util.readResponse(r);
412 openils.Util.show(nodeByName('queue', row), 'inline');
413 var link = nodeByName("queue_link", row);
414 link.onclick = function() {
415 // open a new tab to the vandelay queue for this record
416 openils.XUL.newTabEasy(
417 oilsBasePath + '/vandelay/vandelay?qtype=bib&qid=' + qrec.queue()
425 nodeByName("worksheet_link", row).href =
426 oilsBasePath + "/acq/lineitem/worksheet/" + li.id() +
427 '?source=' + encodeURIComponent(location.pathname + location.search)
429 nodeByName("show_requests_link", row).href =
430 oilsBasePath + "/acq/picklist/user_request?lineitem=" + li.id() +
431 '?source=' + encodeURIComponent(location.pathname + location.search)
433 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
434 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
435 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
437 if (!this.skipInitialEligibilityCheck)
441 function(full) { self.setClaimPolicyControl(full, row) },
445 this.updateLiNotesCount(li, row);
447 // show which PO this lineitem is a member of
448 if(li.purchase_order() && !this.isPO) {
450 this.poCache[li.purchase_order()] =
451 this.poCache[li.purchase_order()] ||
452 fieldmapper.standardRequest(
453 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
455 this.authtoken, li.purchase_order(), {
456 "flesh_price_summary": true,
457 "flesh_provider" : true,
458 "flesh_lineitem_count": true
461 if(po && !this.isMeta) {
462 openils.Util.show(nodeByName('po', row), 'inline');
463 var link = nodeByName('po_link', row);
464 link.setAttribute('href', oilsBasePath +
465 '/acq/po/view/' + li.purchase_order() +
466 '?focus_li=' + li.id() +
467 '&source=' + encodeURIComponent(location.pathname + location.search)
469 link.innerHTML += po.name();
471 openils.Util.show(nodeByName('pro', row), 'inline');
472 link = nodeByName('pro_link', row);
473 link.setAttribute('href', oilsBasePath + '/conify/global/acq/provider/' + po.provider().id())
474 link.innerHTML += po.provider().code();
478 // show which picklist this lineitem is a member of
479 if(li.picklist() && (this.isPO || this.isMeta || this.isUni)) {
481 this.plCache[li.picklist()] =
482 this.plCache[li.picklist()] ||
483 fieldmapper.standardRequest(
484 ['open-ils.acq', 'open-ils.acq.picklist.retrieve.authoritative'],
485 {params: [this.authtoken, li.picklist()]});
487 if (pl.name() == "") {
488 openils.Util.show(nodeByName("bib_origin", row), "inline");
492 openils.Util.show(nodeByName('pl', row), 'inline');
493 var link = nodeByName('pl_link', row);
494 link.setAttribute('href', oilsBasePath +
495 '/acq/picklist/view/' + li.picklist() +
496 '?focus_li=' + li.id() +
497 '&source=' + encodeURIComponent(location.pathname + location.search)
499 link.innerHTML += pl.name();
504 var countNode = nodeByName('count', row);
505 var count = li.item_count() || 0;
506 if (typeof(this._copy_count_cb) == "function") {
507 this._copy_count_cb(li.id(), count);
509 countNode.innerHTML = count;
510 countNode.id = 'acq-lit-copy-count-label-' + li.id();
513 var priceInput = dojo.query('[name=price]', row)[0];
514 priceInput.value = li.estimated_unit_price() || '';
515 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
517 // show either "mark received" or "unreceive" as appropriate
518 this.updateLiState(li, row);
520 if (skip_final_placement) {
524 // the last LI may be rendered after the call to show('list'),
525 // so make sure it's focused if necessary.
526 if (this.focusLineitem == li.id())
530 this._liCountClaims = function(li) {
532 for (var i = 0; i < li.lineitem_details().length; i++)
533 total += li.lineitem_details()[i].claims().length;
537 this._findLiRow = function(li) {
538 return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
541 this.reconsiderClaimControl = function(li, row) {
542 if (!row) row = this._findLiRow(li);
543 var option = nodeByName("action_manage_claims", row);
544 var eligible = this.claimEligibleLidByLi[li.id()].length;
545 var count = this._liCountClaims(li);
547 option.disabled = !(count || eligible);
549 dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
550 option.onclick = function() { self.claimDialog.show(li); };
553 this.clearEligibility = function(li) {
554 this.claimEligibleLidByLi[li.id()] = [];
556 if (li.lineitem_details()) {
557 li.lineitem_details().forEach(
558 function(lid) { delete self.claimEligibleLid[lid.id()]; }
562 if (this.copyCache) {
564 for (var k in this.copyCache) {
565 if (this.copyCache[k].lineitem() == li.id())
569 function(k) { delete self.claimEligibleLid[k]; }
574 this.checkClaimEligibility = function(li, callback, row) {
575 /* Assume always eligible, i.e. from this interface we don't care about
576 * claim eligibility any more. this is where the user would force a
578 this.clearEligibility(li);
579 this.claimEligibleLidByLi[li.id()] = li.lineitem_details().map(
580 function(lid) { return lid.id(); }
582 li.lineitem_details().forEach(
583 function(lid) { self.claimEligibleLid[lid.id()] = true; }
585 this.reconsiderClaimControl(li, row);
586 if (callback) callback(li);
588 this.clearEligibility(li);
589 fieldmapper.standardRequest(
590 ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
591 "params": [openils.User.authtoken, {"lineitem": li.id()}],
593 "onresponse": function(r) {
594 if (r = openils.Util.readResponse(r)) {
595 self.claimEligibleLidByLi[li.id()].push(
598 self.claimEligibleLid[r.lineitem_detail()] = true;
601 "oncomplete": function() {
602 self.reconsiderClaimControl(li, row);
603 if (typeof(callback) == "function")
611 this.updateLiNotesCount = function(li, row) {
612 if (!row) row = this._findLiRow(li);
614 var has_notes = (li.lineitem_notes().filter(
615 function(o) { return Boolean (o.alert_text()); }
618 /* U+2691 is the code point for a filled-in flag character */
619 nodeByName("notes_alert_flag", row).innerHTML =
620 has_notes ? "⚑" : "";
621 nodeByName("noteslink", row).style.fontStyle =
622 has_notes ? "italic" : "normal";
623 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
626 /* XXX NOT related to _updateLiState(). rethink */
627 this.updateLiState = function(li, row) {
628 if (!row) row = this._findLiRow(li);
630 var actReceive = nodeByName("action_mark_recv", row);
631 var actUnRecv = nodeByName("action_mark_unrecv", row);
632 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
633 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
634 var actNewInvoice = nodeByName('action_new_invoice', row);
635 var actLinkInvoice = nodeByName('action_link_invoice', row);
636 var actViewInvoice = nodeByName('action_view_invoice', row);
638 // always allow access to LI history
639 nodeByName('action_view_history', row).onclick =
640 function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
642 /* handle row coloring for based on LI state */
643 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
644 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
646 // Expose invoice actions for any lineitem that is linked to a PO
647 if( li.purchase_order() ) {
649 actNewInvoice.disabled = false;
650 actLinkInvoice.disabled = false;
651 actViewInvoice.disabled = false;
653 actNewInvoice.onclick = function() {
654 location.href = oilsBasePath + '/acq/invoice/view?create=1&attach_li=' + li.id();
655 nodeByName("action_none", row).selected = true;
658 actLinkInvoice.onclick = function() {
659 if (!self.invoiceLinkDialogManager) {
660 self.invoiceLinkDialogManager =
661 new InvoiceLinkDialogManager("li");
663 self.invoiceLinkDialogManager.target = li;
664 acqLitLinkInvoiceDialog.show();
665 nodeByName("action_none", row).selected = true;
668 actViewInvoice.onclick = function() {
669 location.href = oilsBasePath +
670 "/acq/search/unified?so=" +
671 base64Encode({"jub":[{"id": li.id()}]}) +
673 nodeByName("action_none", row).selected = true;
679 * If we haven't fleshed the lineitem_details, default to allowing access to the
680 * holdings maintenence actions. The alternative is to flesh LIDs on every lineitem,
681 * but that will add to page render time. Let's see if this will suffice...
683 var lids = li.lineitem_details();
685 (lids && !lids.filter(function(lid) { return lid.eg_copy_id() })[0] )) {
687 actUpdateBarcodes.disabled = false;
688 actUpdateBarcodes.onclick = function() {
689 self.showRealCopyEditUI(li);
690 nodeByName("action_none", row).selected = true;
692 actHoldingsMaint.disabled = false;
693 actHoldingsMaint.onclick =
694 self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
697 var state_cell = nodeByName("li_state", row);
702 if(typeof li.cancel_reason() == "object") {
703 var holds_state = dojo.create(
705 "style": "border-bottom: 1px dashed #000;",
706 "innerHTML": li.state()
707 }, state_cell, "only"
711 "label": "<em>" + li.cancel_reason().label() +
712 "</em><br />" + li.cancel_reason().description(),
713 "connectId": [holds_state]
714 }, dojo.create("span", null, state_cell, "last")
720 actReceive.disabled = false;
721 actReceive.onclick = function() {
722 if (self.checkLiAlerts(li.id()))
723 self.issueReceive(li);
724 nodeByName("action_none", row).selected = true;
729 actUnRecv.disabled = false;
730 actUnRecv.onclick = function() {
731 if (confirm(localeStrings.UNRECEIVE_LI))
732 self.issueReceive(li, /* rollback */ true);
733 nodeByName("action_none", row).selected = true;
738 state_cell.innerHTML = li.state(); // TODO i18n state labels
742 this._setAlertStore = function() {
743 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
745 "data": acqliat.toStoreData(
748 "owning_lib": aou.orgNodeTrail(
749 aou.findOrgUnit(openils.User.user.ws_ou())
750 ).map(function(o) { return o.id(); })
756 acqLitAlertAlertText.setValue(); /* make the store "live" */
757 acqLitAlertAlertText._store_ready = true;
761 * Draws and shows the lineitem notes pane
763 this.drawLiNotes = function(li) {
765 this.focusLineitem = li.id();
767 if (!acqLitAlertAlertText._store_ready)
768 this._setAlertStore();
771 li.lineitem_notes().sort(
773 if(a.edit_time() < b.edit_time()) return 1;
779 while(this.liNotesTbody.childNodes[0])
780 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
783 acqLitCreateNoteSubmit.onClick = function() {
784 var value = acqLitCreateNoteText.attr('value');
786 var note = new fieldmapper.acqlin();
789 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
792 note.lineitem(li.id());
794 self.updateLiNotes(li, note);
795 acqLitCreateNoteVendorPublic.attr("checked", false);
796 acqLitCreateNoteText.attr("value", "");
799 acqLitCreateAlertSubmit.onClick = function() {
800 if (!acqLitAlertAlertText.item) {
801 alert(localeStrings.ALERT_UNSELECTED);
805 var alert_text = new fieldmapper.acqliat().fromStoreItem(
806 acqLitAlertAlertText.item
808 var value = acqLitAlertNoteValue.attr("value") || "";
810 var note = new fieldmapper.acqlin();
812 note.lineitem(li.id());
814 note.alert_text(alert_text);
816 self.updateLiNotes(li, note);
819 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
823 * Draws a single lineitem note in the notes pane
825 this.addLiNote = function(li, note) {
826 if(note.isdeleted()) return;
828 var row = self.liNotesRow.cloneNode(true);
829 nodeByName("value", row).innerHTML = note.value();
830 var alert_node = nodeByName("alert_code", row);
831 if (note.alert_text()) {
832 alert_node.innerHTML = dojo.string.substitute(
834 aou.findOrgUnit(note.alert_text().owning_lib()).shortname(),
835 note.alert_text().code()
838 if (note.alert_text().description()) {
841 "connectId": [alert_node],
842 "label": note.alert_text().description()
843 }, dojo.create("span", null, alert_node, "after")
848 if (openils.Util.isTrue(note.vendor_public()))
849 nodeByName("vendor_public", row).innerHTML =
850 localeStrings.VENDOR_PUBLIC;
852 nodeByName("delete", row).onclick = function() {
853 note.isdeleted(true);
854 self.liNotesTbody.removeChild(row);
855 self.updateLiNotes(li);
858 if(note.edit_time()) {
859 nodeByName("edit_time", row).innerHTML =
860 dojo.date.locale.format(
861 dojo.date.stamp.fromISOString(note.edit_time()),
862 {formatLength:'short'});
865 self.liNotesTbody.appendChild(row);
869 * Updates any new/changed/deleted notes on the server
871 this.updateLiNotes = function(li, newNote) {
877 notes = li.lineitem_notes().filter(
879 if(note.ischanged() || note.isnew() || note.isdeleted())
885 if(notes.length == 0) return;
886 progressDialog.show();
888 fieldmapper.standardRequest(
889 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
891 params : [this.authtoken, notes],
892 onresponse : function(r) {
893 var resp = openils.Util.readResponse(r);
898 // remove the old changed notes
900 dojo.forEach(li.lineitem_notes(),
902 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
906 li.lineitem_notes(list);
909 progressDialog.hide();
910 self.updateLiNotesCount(li);
911 self.drawLiNotes(li);
915 progressDialog.update(resp);
916 var newnote = resp.note;
918 if(!newnote.isdeleted()) {
919 newnote.isnew(false);
920 newnote.ischanged(false);
921 li.lineitem_notes().push(newnote);
928 this.updateLiPrice = function(input, li) {
930 var price = input.value;
931 if(Number(price) == Number(li.estimated_unit_price())) return;
933 fieldmapper.standardRequest(
934 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
935 { async : false, // redundant w/ timeout
937 params : [this.authtoken, li.id(), price],
938 oncomplete : function(r) {
939 openils.Util.readResponse(r);
940 li.estimated_unit_price(price); // update local copy
943 * If this is a PO and every visible lineitem has a price,
944 * check again to see if this PO can be activated. Note that
945 * every visible lineitem having a price does not guarantee it can
946 * be activated, which is why we still make the call. Having a price
947 * set for every visiable lineitem is just the lowest barrier to entry.
950 var priceNodes = dojo.query('[name=price]', dojo.byId('acq-lit-tbody'));
952 dojo.forEach(priceNodes, function(node) { if (node.value == '') allSet = false});
953 if (allSet) checkCouldActivatePo();
960 this.removeLineitem = function(liId) {
961 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
962 delete this.liCache[liId];
963 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
966 this.drawInfo = function(liId) {
967 this.focusLineitem = liId;
968 if (!this._isRelatedViewer) {
969 var d = dojo.byId("acq-lit-info-related");
970 if (!this.relCache[liId]) {
971 fieldmapper.standardRequest(
974 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
977 "params": [openils.User.authtoken, liId],
978 "onresponse": function(r) {
979 self.relCache[liId] = openils.Util.readResponse(r);
980 nodeByName("related_number", d).innerHTML =
983 self.relCache[liId] >1 ? "show" : "hide"
989 nodeByName("related_number", d).innerHTML = this.relCache[liId];
990 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
995 openils.acq.Lineitem.fetchAttrDefs(
997 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
1002 /* For a given list of lineitem ids, build a list of full lineitems
1003 * re-using the fetching logic that is otherwise typical to use in this
1006 * If we've already got a lineitem in the cache, just use that.
1008 * Once we've built a list of lineitems, call callback(thatlist).
1010 this.fetchLineitemsById = function(id_list, callback) {
1011 var total = id_list.length;
1012 var result_list = [];
1014 var inner = function(li) {
1015 result_list.push(li)
1017 callback(result_list);
1020 id_list.forEach(function(id) { self._fetchLineitem(id, inner); });
1023 this._fetchLineitem = function(liId, handler, force) {
1025 var li = this.liCache[liId];
1026 if(li && li.marc() && li.lineitem_details() && !force)
1029 fieldmapper.standardRequest(
1030 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
1033 params: [self.authtoken, liId, {
1035 flesh_cancel_reason: true,
1036 flesh_li_details: true,
1038 flesh_fund_debit: true }],
1040 oncomplete: function(r) {
1041 var li = openils.Util.readResponse(r);
1042 self.liCache[liId] = li;
1049 this._drawInfo = function(li) {
1051 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
1053 if(li.eg_bib_id()) {
1054 openils.Util.hide('acq-lit-marc-order-record-label');
1055 openils.Util.hide(acqLitEditOrderMarc.domNode);
1056 openils.Util.show('acq-lit-marc-real-record-label');
1058 openils.Util.show('acq-lit-marc-order-record-label');
1059 openils.Util.show(acqLitEditOrderMarc.domNode);
1060 openils.Util.hide('acq-lit-marc-real-record-label');
1063 this.drawMarcHTML(li);
1064 this.infoTbody = dojo.byId('acq-lit-info-tbody');
1067 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
1068 while(this.infoTbody.childNodes[0])
1069 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
1071 for(var i = 0; i < li.attributes().length; i++) {
1072 var attr = li.attributes()[i];
1073 var row = this.infoRow.cloneNode(true);
1075 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
1076 var name = openils.acq.Lineitem.attrDefs[type].filter(
1078 return (a.code() == attr.attr_name());
1080 ).pop().description();
1082 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
1083 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
1084 this.infoTbody.appendChild(row);
1087 if (!this._isRelatedViewer) {
1088 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
1089 oilsBasePath + "/acq/lineitem/related/" + li.id();
1092 // if a top scroll point is defined, jump up to it here
1093 var node = dojo.byId('oils-scroll-to-top');
1094 if (node) dijit.scrollIntoView(node);
1097 this.generateMakeRecTab = function(bib_id,default_view, row) {
1101 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
1104 show_nav_buttons : true,
1105 show_print_button : true,
1106 opac_url : xulG.url_prefix('opac_rdetail|' + bib_id),
1107 default_view : default_view
1111 if(row) nodeByName("action_none", row).selected = true;
1115 this.drawMarcHTML = function(li) {
1116 var params = [null, true, li.marc()];
1118 params = [li.eg_bib_id(), true];
1120 fieldmapper.standardRequest(
1121 ['open-ils.search', 'open-ils.search.biblio.record.html'],
1124 oncomplete: function(r) {
1125 dojo.byId('acq-lit-marc-div').innerHTML =
1126 openils.Util.readResponse(r);
1132 this.drawCopies = function(liId, force_fetch) {
1133 this.focusLineitem = liId;
1134 if (typeof force_fetch == "undefined")
1135 force_fetch = false;
1137 var cgi = new openils.CGI();
1138 var source = cgi.param('source');
1139 if (source && source.match(/invoice/)) {
1140 // got here from the invoice page, show the 'return-to-invoice' button
1141 var cgi = new openils.CGI({url : source});
1142 cgi.param('focus_li', liId);
1143 openils.Util.show(dojo.byId('acq-lit-copies-back-to-invoice-button-wrapper'), 'inline');
1144 var button = dojo.byId('acq-lit-copies-back-to-invoice-button');
1145 button.onclick = function() { location.href = cgi.url() };
1148 openils.acq.Lineitem.fetchAndRender(liId, {},
1149 function(li, html) {
1150 dojo.byId('acq-lit-copies-li-summary').innerHTML = html;
1154 this.show('copies');
1156 this.copyCache = {};
1157 this.copyWidgetCache = {};
1158 this.oldCopyWidgetCache = {};
1159 this.virtDfaCounts = {};
1160 this.realDfaCache = {};
1163 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
1164 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
1165 acqLitCopyCountInput.attr('value', '0');
1167 while(this.copyTbody.childNodes[0])
1168 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
1170 this._drawBatchCopyWidgets();
1172 this._drawDistribApplied(liId);
1174 this._fetchDistribFormulas(
1176 openils.acq.Lineitem.fetchAttrDefs(
1178 self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch);
1185 this._saveDistribAppliedTemplates = function() {
1186 if (!this._appliedDistribTemplate) {
1187 this._appliedDistribTemplate =
1188 dojo.byId("acq-lit-distrib-applied-tbody").
1189 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
1190 dojo.attr(this._appliedDistribTemplate, "id");
1194 this._drawDistribApplied = function(liId) {
1195 /* Build this table while hidden to prevent rendering artifacts */
1196 openils.Util.hide("acq-lit-distrib-applied-tbody");
1198 this._saveDistribAppliedTemplates();
1200 /* Remove any rows in the table from previous populations */
1201 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
1202 forEach(dojo.destroy);
1204 /* Unregister all dijits previously created (for some reason this isn't
1205 * covered by the above destroy calls). */
1206 dijit.registry.forEach(
1207 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
1210 /* Populate the table with our liId */
1212 fieldmapper.standardRequest(
1214 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
1217 "params": [self.authtoken, liId],
1218 "onresponse": function(r) {
1219 var dfa = openils.Util.readResponse(r);
1222 self.realDfaCache[dfa.id()] = dfa;
1223 self._drawDistribAppliedUnit(dfa);
1226 "oncomplete": function() {
1227 /* Reveal built table */
1230 "acq-lit-distrib-applied-tbody", "table-row-group"
1238 this._drawDistribAppliedUnit = function(dfa) {
1239 var new_row = false;
1240 var row = dojo.query(
1241 'tr[formula="' + dfa.formula().id() + '"]',
1242 "acq-lit-distrib-applied-tbody"
1247 row = dojo.clone(this._appliedDistribTemplate);
1248 dojo.attr(row, "formula", dfa.formula().id());
1249 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
1252 var td = dojo.query("td", row)[0];
1254 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1255 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1258 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1260 new dijit.form.Button(
1262 "onClick": function() {
1263 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1264 self.deleteDfa(dfa);
1267 /* XXX I /cannot/ make the following work in as a CSS class
1268 * for some reason. So frustrating... */
1269 "style": function(id) {
1271 "font-weight: bold; color: #c00;" :
1273 }(dfa.id()) + "margin: 0 6px;display: inline;"
1274 }, "dfa-button-" + dfa.id()
1278 "connectId": ["dfa-button-" + dfa.id()],
1279 "label": dojo.string.substitute(
1280 localeStrings.DFA_TIP, dfa.id() > 0 ? [
1281 openils.User.formalName(dfa.creator()),
1282 dojo.date.locale.format(
1283 dojo.date.stamp.fromISOString(dfa.create_time()),
1284 {"formatLength":"short"}
1286 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
1288 }, "dfa-tip-" + dfa.id()
1292 this.deleteDfa = function(dfa) {
1293 if (dfa.id() > 0) { /* real */
1294 this.pcrud.eliminate(
1297 "oncomplete": function() {
1298 self._removeDistribApplied(dfa.id());
1299 delete self.realDfaCache[dfa.id()];
1303 } else { /* virtual */
1304 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
1305 this.virtDfaCounts[dfa.formula().id()] = 0;
1306 /* hasn't been saved yet, so no need to do anything server side */
1307 this._removeDistribApplied(dfa.id());
1312 this._removeDistribApplied = function(dfaId) {
1313 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
1314 dijit.registry.forEach(
1315 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
1317 this._removeDistribAppliedEmptyRows();
1320 this._removeAllDistribAppliedVirtual = function() {
1321 /* Unregister dijits */
1322 dijit.registry.forEach(
1323 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
1325 this._removeDistribAppliedEmptyRows();
1328 this._removeDistribAppliedEmptyRows = function() {
1329 /* Remove any rows with no DFA at all */
1330 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
1332 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
1338 * Insert a new row into the distribution formula selection form
1340 this._addDistribFormulaRow = function() {
1343 if (!self.distribForms) {
1344 // no formulas, hide the form
1345 openils.Util.hide('acq-lit-distrib-formula-table');
1349 if(!this.distribFormulaTemplate)
1350 this.distribFormulaTemplate =
1351 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
1353 var row = this.distribFormulaTemplate.cloneNode(true);
1354 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
1356 this.dfSelector = new dijit.form.FilteringSelect(
1357 {"labelAttr": "dynLabel", "labelType": "html"},
1358 nodeByName("selector", row)
1360 this._updateFormulaStore();
1361 this.dfSelector.fetchProperties =
1362 {"sort": [{"attribute": "use_count", "descending": true}]};
1364 var apply = new dijit.form.Button(
1365 {"label": localeStrings.APPLY},
1366 nodeByName('set_button', row)
1369 var reset = new dijit.form.Button(
1370 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
1371 nodeByName("reset_button", row)
1374 dojo.connect(apply, 'onClick',
1376 var form_id = self.dfSelector.attr("value");
1377 if(!form_id) return;
1378 self._applyDistribFormula(form_id);
1379 reset.attr("disabled", false);
1383 dojo.connect(reset, 'onClick',
1385 self.restoreCopyFieldsBeforeDF();
1386 self.virtDfaCounts = {};
1387 self.virtDfaId = -1;
1389 self._updateFormulaStore();
1390 self._removeAllDistribAppliedVirtual();
1391 reset.attr("disabled", "true");
1398 * Applies a distrib formula to the current set of copies
1400 this._applyDistribFormula = function(formula) {
1401 if(!formula) return;
1403 formula = this.distribForms.filter(
1404 function(form) { return form.id() == formula; }
1407 var copyRows = dojo.query('tr', self.copyTbody);
1409 if (this.dfeOffset >= copyRows.length) {
1410 alert(localeStrings.OUT_OF_COPIES);
1414 var entries_applied = 0;
1416 var rowIndex = this.dfeOffset;
1417 rowIndex < copyRows.length;
1421 var row = copyRows[rowIndex];
1422 var copy_id = row.getAttribute('copy_id');
1423 var copyWidgets = this.copyWidgetCache[copy_id];
1424 var entryIndex = this.dfeOffset;
1427 // find the correct entry for the current row
1428 dojo.forEach(formula.entries(),
1431 entryIndex += e.item_count();
1432 if(entryIndex > rowIndex)
1440 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
1441 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
1444 this.saveCopyFieldsBeforeDF(copy_id);
1445 this._copy_fields_for_acqdf.forEach(
1447 if(entry[field]()) {
1448 copyWidgets[field].attr('value', (entry[field]()));
1455 if (entries_applied) {
1456 this.virtDfaCounts[formula.id()] =
1457 ++(this.virtDfaCounts[formula.id()]) || 1;
1458 this._updateFormulaStore();
1459 this._drawDistribAppliedUnit(
1461 var dfa = new acqdfa();
1462 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
1465 this.dfeOffset += entries_applied;
1470 * This function updates the DF store for the dropdown so that use_counts
1471 * can reflect DF applications from this session before they're saved
1474 this._updateFormulaStore = function() {
1475 this.dfSelector.store = new dojo.data.ItemFileReadStore(
1477 "data": self._labelFormulasWithCounts(
1478 acqdf.toStoreData(self.distribForms)
1484 this.saveCopyFieldsBeforeDF = function(copy_id) {
1486 if (!this.oldCopyWidgetCache[copy_id]) {
1487 var copyWidgets = this.copyWidgetCache[copy_id];
1489 this.oldCopyWidgetCache[copy_id] = {};
1490 this._copy_fields_for_acqdf.forEach(
1492 self.oldCopyWidgetCache[copy_id][f] =
1493 copyWidgets[f].attr("value");
1499 this.restoreCopyFieldsBeforeDF = function() {
1501 for (var copy_id in this.oldCopyWidgetCache) {
1502 this._copy_fields_for_acqdf.forEach(
1504 self.copyWidgetCache[copy_id][f].attr(
1505 "value", self.oldCopyWidgetCache[copy_id][f]
1512 this._labelFormulasWithCounts = function(store_data) {
1513 for (var key in store_data.items) {
1514 var obj = store_data.items[key];
1515 obj.use_count = Number(obj.use_count); /* needed for sorting */
1517 if (this.virtDfaCounts[obj.id])
1518 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
1520 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
1521 obj.use_count + "]</span> " + obj.name;
1527 * This method formerly would not refetch the DF formulas if they'd been
1528 * loaded already, but now it always re-fetches, since use_count changes.
1530 /** TODO: port distrib-formula selector to autofieldwidget+pcrud/dojo store */
1531 this._fetchDistribFormulas = function(onload) {
1532 fieldmapper.standardRequest(
1534 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
1537 "params": [openils.User.authtoken, 0, 500],
1538 "oncomplete": function(r) {
1539 self.distribForms = openils.Util.readResponse(r);
1540 if(!self.distribForms || self.distribForms.length == 0) {
1541 self.distribForms = [];
1543 self._addDistribFormulaRow();
1550 this._drawBatchCopyWidgets = function() {
1551 var row = this.copyBatchRow;
1552 dojo.forEach(liDetailBatchFields,
1554 if(self.copyBatchRowDrawn) {
1555 self.copyBatchWidgets[field].attr('value', null);
1557 var widget = new openils.widget.AutoFieldWidget({
1560 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1561 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1562 searchFilter : (field == 'fund') ? {"active": "t"} : null,
1563 parentNode : dojo.query('[name='+field+']', row)[0],
1564 orgLimitPerms : ['CREATE_PICKLIST'],
1567 "labelType": (field == "fund") ? "html" : null
1569 noCache: (field == "fund"),
1574 if (field == "fund" && w.store)
1575 self._ensureCSSFundClasses(w.store);
1576 self.copyBatchWidgets[field] = w;
1579 if (field == "fund") {
1581 widget.widget, "onChange", function(val) {
1582 self._updateFundSelectorStyle(widget, val);
1589 this.copyBatchRowDrawn = true;
1592 this.batchCopyUpdate = function() {
1594 for(var k in this.copyWidgetCache) {
1595 var cache = this.copyWidgetCache[k];
1596 dojo.forEach(liDetailBatchFields, function(f) {
1597 var newval = self.copyBatchWidgets[f].attr('value');
1598 if(newval) cache[f].attr('value', newval);
1603 this._drawCopies = function(li) {
1606 // this button sets the total number of copies for a given lineitem
1607 acqLitAddCopyCount.onClick = function() {
1608 var count = acqLitCopyCountInput.attr('value');
1611 while(self.copyCount() < count)
1614 // delete rows if necessary
1615 var diff = self.copyCount() - count;
1617 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
1618 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
1619 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
1621 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1627 if(li.lineitem_details().length > 0) {
1628 dojo.forEach(li.lineitem_details(),
1630 self.addCopy(li, copy);
1638 this.copyCount = function() {
1640 for(var id in this.copyCache) {
1641 if(!this.copyCache[id].isdeleted())
1647 this.virtCopyId = -1;
1648 this.addCopy = function(li, copy) {
1649 var row = this.copyRow.cloneNode(true);
1650 this.copyTbody.appendChild(row);
1654 copy = new fieldmapper.acqlid();
1656 copy.id(this.virtCopyId--);
1657 copy.lineitem(li.id());
1660 this.copyCache[copy.id()] = copy;
1661 row.setAttribute('copy_id', copy.id());
1662 self.copyWidgetCache[copy.id()] = {};
1664 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1666 var rcvr = copy.receiver();
1668 if (!userCache[rcvr]) {
1669 if(rcvr == openils.User.user.id()) {
1670 userCache[rcvr] = openils.User.user;
1672 userCache[rcvr] = fieldmapper.standardRequest(
1673 ['open-ils.actor', 'open-ils.actor.user.retrieve'],
1674 {params: [openils.User.authtoken, rcvr]}
1678 dojo.query('[name=receiver]', row)[0].innerHTML = userCache[rcvr].usrname();
1681 dojo.forEach(liDetailFields,
1684 if (field == "fund") {
1685 searchFilter = (copy.fund() ?
1686 {"-or": {"active": "t", "id": copy.fund()}} :
1689 searchFilter = null;
1692 var readOnly = false;
1694 // TODO: Add support for changing the owning_lib after real copies have been made.
1695 // owning_lib is order data as much as its item data
1696 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
1700 // TODO: add support for changing the fund after debits have been created
1701 // Note: invoicing allows the change
1702 if(copy.fund_debit() && field == 'fund') {
1707 var widget = new openils.widget.AutoFieldWidget({
1710 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1711 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1712 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1713 searchFilter : searchFilter,
1714 noCache: (field == "fund"),
1716 parentNode : dojo.query('[name='+field+']', row)[0],
1717 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
1718 readOnly : readOnly,
1719 orgDefaultsToWs : true
1723 // make sure we capture the value from any async widgets
1726 if (field == "fund" && w.store)
1727 self._ensureCSSFundClasses(w.store);
1730 copy[field](ww.getFormattedValue())
1732 self.copyWidgetCache[copy.id()][field] = w;
1734 dojo.connect(w, 'onChange',
1736 if (field == "fund")
1737 self._updateFundSelectorStyle(widget, val);
1739 if (!readOnly && (copy.isnew() || val != copy[field]())) {
1740 // prevent setting ischanged() automatically on widget load for existing copies
1741 copy[field](widget.getFormattedValue())
1742 copy.ischanged(true);
1751 this.updateLidState(copy, row);
1754 this._ensureCSSFundClass = function(id) {
1755 if (!this.fundStyleSheet) {
1757 "style", {"type": "text/css"},
1758 document.getElementsByTagName("head")[0], "last"
1760 this.fundStyleSheet = document.styleSheets[
1761 document.styleSheets.length - 1
1765 var cn = "fund_" + id;
1766 if (!this.haveFundClass[cn]) {
1767 fieldmapper.standardRequest(
1768 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
1770 "params": [openils.User.authtoken, id],
1772 "oncomplete": function(r) {
1773 r = openils.Util.readResponse(r);
1774 self.fundBalanceState[id] = r;
1776 if (r[0] /* stop */)
1777 style = fundStyles.stop;
1778 else if (r[1] /* warning */)
1779 style = fundStyles.warning;
1780 self.fundStyleSheet.insertRule(
1781 "." + cn + " { " + style + " }",
1782 self.fundStyleSheet.cssRules.length
1784 self.haveFundClass[cn] = true;
1791 this._ensureCSSFundClasses = function(store) {
1793 "query": {"id": "*"},
1794 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
1798 this._updateFundSelectorStyle = function(widget, fund_id) {
1799 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
1800 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
1803 this.updateLidState = function(copy, row) {
1806 if (typeof(row) == "undefined") {
1807 row = dojo.query('tr[copy_id="' + copy.id() + '"]', this.copyTbody)[0];
1811 var recv_link = nodeByName("receive", row);
1812 var unrecv_link = nodeByName("unreceive", row);
1813 var del_link = nodeByName("delete", row);
1814 var cxl_link = nodeByName("cancel", row);
1815 var claim_link = nodeByName("claim", row);
1816 var cxl_reason_link = nodeByName("cancel_reason", row);
1818 // by default, hide all the actions
1819 openils.Util.hide(del_link.parentNode);
1820 openils.Util.hide(recv_link);
1821 openils.Util.hide(unrecv_link);
1822 openils.Util.hide(cxl_link);
1823 openils.Util.hide(claim_link);
1824 openils.Util.hide(cxl_reason_link);
1826 if (copy.id() > 0) { // real copies (LIDs)
1828 if (copy.cancel_reason()) {
1830 /* --------- cancelled -------------------------- */
1832 /* XXX the following may leak memory in a long lived table:
1833 * dijits may not get destroyed... not positive. revisit. */
1834 var holds_reason = dojo.create(
1836 "style": "border-bottom: 1px dashed #000;",
1837 "innerHTML": "Cancelled" /* XXX [sic] and i18n */
1838 }, cxl_reason_link, "only"
1842 "label": "<em>" + copy.cancel_reason().label() +
1843 "</em><br />" + copy.cancel_reason().description(),
1844 "connectId": [holds_reason]
1845 }, dojo.create("span", null, cxl_reason_link, "last")
1847 openils.Util.show(cxl_reason_link, "inline");
1849 } else if (copy.recv_time()) {
1851 /* --------- received -------------------------- */
1853 openils.Util.show(unrecv_link, "inline");
1854 unrecv_link.onclick = function() {
1855 if (confirm(localeStrings.UNRECEIVE_LID))
1856 self.issueReceive(copy, /* rollback */ true);
1859 } else if (this.liCache[copy.lineitem()].state() == 'on-order') {
1861 /* --------- on order -------------------------- */
1863 openils.Util.show(recv_link, 'inline');
1864 openils.Util.show(cxl_link, "inline");
1866 recv_link.onclick = function() {
1867 if (self.checkLiAlerts(copy.lineitem()))
1868 self.issueReceive(copy);
1871 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
1875 /* --------- pre-order copies -------------------------- */
1877 del_link.onclick = function() { self.deleteCopy(row) };
1878 openils.Util.show(del_link.parentNode);
1884 /* --------- virtual copies -------------------------- */
1886 del_link.onclick = function() { self.deleteCopy(row) };
1887 openils.Util.show(del_link.parentNode);
1891 this.cancelLid = function(lid_id) {
1892 lidCancelDialog._lid_id = lid_id;
1893 openils.Util.show(lidCancelDialog.domNode.parentNode);
1894 lidCancelDialog.show();
1895 if (!lidCancelDialog._prepared) {
1896 var widget = new openils.widget.AutoFieldWidget({
1897 "fmField": "cancel_reason",
1898 "fmClass": "acqlid",
1899 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
1900 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1905 acqLidCancelButton.onClick = function() {
1906 if (w.attr("value")) {
1907 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
1909 lidCancelDialog._lid_id,
1913 lidCancelDialog.hide();
1916 lidCancelDialog._prepared = true;
1922 this._cancelLid = function(lid_id, reason) {
1923 fieldmapper.standardRequest(
1924 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
1925 "params": [openils.User.authtoken, lid_id, reason],
1927 "onresponse": function(r) {
1928 if (r = openils.Util.readResponse(r)) {
1930 for (var id in r.lid) {
1931 /* actually this should only iterate once */
1932 self.copyCache[id].cancel_reason(
1933 r.lid[id].cancel_reason
1935 self.updateLidState(self.copyCache[id]);
1944 this._confirmAlert = function(li, lin) {
1946 dojo.string.substitute(
1947 localeStrings.CONFIRM_LI_ALERT, [
1948 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1949 "title", "lineitem_marc_attr_definition"
1951 /* XXX it's really better add a parameter and to adjust
1952 * the format string rather than do this concatenation
1953 * here, but if someone wants this for 2.2 in a hurry,
1954 * we can sidestep the problem of updating the strings
1955 * while the translators are working. */
1957 aou.findOrgUnit(lin.alert_text().owning_lib()).shortname() +
1959 lin.alert_text().code()
1961 lin.alert_text().description() || "",
1968 this.checkLiAlerts = function(li_id) {
1969 var li = this.liCache[li_id];
1971 var alert_notes = li.lineitem_notes().filter(
1972 function(o) { return Boolean(o.alert_text()); }
1975 /* this is _intentionally_ not done in a call to forEach() ... */
1976 for (var i = 0; i < alert_notes.length; i++) {
1977 if (this.noteAcks[alert_notes[i].id()])
1979 else if (!this._confirmAlert(li, alert_notes[i]))
1982 this.noteAcks[alert_notes[i].id()] = true;
1988 this.deleteCopy = function(row) {
1989 var copy = this.copyCache[row.getAttribute('copy_id')];
1990 copy.isdeleted(true);
1992 delete this.copyCache[copy.id()];
1993 this.copyTbody.removeChild(row);
1996 this._virtDfaCountsAsList = function() {
1998 for (var key in this.virtDfaCounts) {
1999 for (var i = 0; i < this.virtDfaCounts[key]; i++)
2005 this.confirmBreachedCopyFunds = function(copies) {
2006 var stop = 0, warning = 0;
2010 var state = self.fundBalanceState[o.fund()];
2011 if (state[0] /* stop */)
2013 else if (state[1] /* warning */)
2020 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
2021 } else if (warning) {
2022 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
2027 this.saveCopyChanges = function(liId) {
2033 for(var id in this.copyCache) {
2034 var c = this.copyCache[id];
2035 if(!c.isdeleted()) total++;
2036 if(c.isnew() || c.ischanged() || c.isdeleted()) {
2037 if(c.id() < 0) c.id(null);
2043 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
2046 if (copies.length > 0) {
2047 if (!this.confirmBreachedCopyFunds(copies))
2050 if (typeof(this._copy_count_cb) == "function")
2051 this._copy_count_cb(liId, total);
2053 openils.Util.show("acq-lit-update-copies-progress");
2054 fieldmapper.standardRequest(
2055 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
2057 params: [openils.User.authtoken, copies],
2058 onresponse: function(r) {
2059 var res = openils.Util.readResponse(r);
2060 litUpdateCopiesProgress.update(res);
2062 oncomplete: function() {
2063 self.drawCopies(liId, true /* force_fetch */);
2064 openils.Util.hide("acq-lit-update-copies-progress");
2070 var dfa_list = this._virtDfaCountsAsList();
2071 if (dfa_list.length > 0) {
2072 fieldmapper.standardRequest(
2074 "open-ils.acq.distribution_formula.record_application"],
2077 "params": [openils.User.authtoken, dfa_list, liId],
2078 "onresponse": function(r) {
2079 var res = openils.Util.readResponse(r);
2080 if (res && res.length < dfa_list.length)
2081 alert(localeStrings.DFA_NOT_ALL);
2085 this.virtDfaCounts = {};
2089 this._updateCreatePoPrepayCheckbox = function(prepay) {
2090 var prepay = openils.Util.isTrue(prepay);
2091 this._prepayRequiredByVendor = prepay;
2092 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
2095 this._confirmPoPrepaySituation = function() {
2096 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
2097 if (want_prepay != this._prepayRequiredByVendor) {
2100 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
2101 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
2108 this.applySelectedLiAction = function(action) {
2112 case 'delete_selected':
2113 this._deleteLiList(self.getSelected());
2116 case 'create_order':
2117 this._loadPOSelect();
2118 acqLitPoCreateDialog.show();
2121 case 'save_picklist':
2122 acqLitSavePlDialog.show();
2125 case 'selector_ready':
2127 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
2128 acqLitChangeLiStateDialog.show();
2136 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
2139 case 'batch_create_invoice':
2140 this.batchCreateInvoice();
2143 case 'batch_link_invoice':
2144 this.batchLinkInvoice();
2151 case 'rollback_receive_po':
2152 this.rollbackPoReceive();
2155 case 'create_assets':
2156 this.showAssetCreator();
2159 case 'export_attr_list':
2160 this.chooseExportAttr();
2163 case 'batch_apply_funds':
2164 this.applyBatchLiFunds();
2167 case 'add_brief_record':
2169 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
2171 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
2175 case "cancel_lineitems":
2176 this.maybeCancelLineitems();
2179 case "change_claim_policy":
2180 var li_list = this.getSelected();
2181 this.claimPolicyPicker.attr("value", null);
2182 liClaimPolicyDialog.show();
2183 liClaimPolicySave.onClick = function() {
2184 self.changeClaimPolicy(
2186 self.claimPolicyPicker.attr("value"),
2190 self.setClaimPolicyControl(li);
2191 self.reconsiderClaimControl(li);
2194 liClaimPolicyDialog.hide();
2202 this.changeClaimPolicy = function(li_list, value, callback) {
2204 function(li) { li.claim_policy(value); }
2206 fieldmapper.standardRequest(
2207 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
2208 "params": [openils.User.authtoken, li_list],
2210 "oncomplete": function(r) {
2211 r = openils.Util.readResponse(r);
2212 if (callback) callback(r);
2218 this.showAssetCreator = function(onAssetsCreated) {
2219 if(!this.isPO) return;
2222 // first, let's see if this PO has any LI's that need to be merged/imported
2223 self.pcrud.search('jub', {purchase_order : this.isPO, eg_bib_id : null}, {
2225 oncomplete : function(r) {
2226 var resp = openils.Util.readResponse(r);
2227 if (resp && resp.length) {
2228 // PO has some non-linked jubs.
2230 self.show('asset-creator');
2231 if(!self.vlAgent.loaded)
2232 self.vlAgent.init();
2234 dojo.connect(assetCreatorButton, 'onClick',
2235 function() { self.createAssets(onAssetsCreated) });
2239 // all jubs linked, move on to asset creation
2240 self.createAssets(onAssetsCreated, true);
2246 this.createAssets = function(onAssetsCreated, noVl) {
2247 this.show('acq-lit-progress-numbers');
2249 var vlArgs = (noVl) ? {} : {vandelay : this.vlAgent.values()};
2250 fieldmapper.standardRequest(
2251 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
2253 params: [this.authtoken, this.isPO, vlArgs],
2254 onresponse: function(r) {
2255 var resp = openils.Util.readResponse(r);
2256 self._updateProgressNumbers(resp, !Boolean(onAssetsCreated), onAssetsCreated);
2262 this.maybeCancelLineitems = function() {
2263 openils.Util.show("acq-lit-cancel-reason", "inline");
2264 if (!acqLitCancelLineitemsButton._prepared) {
2265 var widget = new openils.widget.AutoFieldWidget({
2266 "fmField": "cancel_reason",
2268 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
2269 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2274 acqLitCancelLineitemsButton.onClick = function() {
2275 if (w.attr("value")) {
2276 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
2277 self._cancelLineitems(w.attr("value"));
2279 openils.Util.hide("acq-lit-cancel-reason");
2282 acqLitCancelLineitemsButton._prepared = true;
2288 this._cancelLineitems = function(reason) {
2289 var id_list = this.getSelected().map(function(o) { return o.id(); });
2290 fieldmapper.standardRequest(
2291 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
2292 "params": [openils.User.authtoken, id_list, reason],
2294 "onresponse": function(r) {
2295 if (r = openils.Util.readResponse(r)) {
2297 for (var id in r.li) {
2298 self.liCache[id].state(r.li[id].state);
2299 self.liCache[id].cancel_reason(
2300 r.li[id].cancel_reason
2302 self.updateLiState(self.liCache[id]);
2305 if (r.lid && self.copyCache) {
2306 for (var id in r.lid) {
2307 if (self.copyCache[id]) {
2308 self.copyCache[id].cancel_reason(
2309 r.lid[id].cancel_reason
2311 self.updateLidState(self.copyCache[id]);
2321 this.chooseExportAttr = function() {
2322 if (!acqLitExportAttrSelector._li_setup) {
2324 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
2326 "data": acqlimad.toStoreData(
2328 "acqlimad", {"code": li_exportable_attrs}
2333 acqLitExportAttrSelector.setValue();
2334 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
2335 acqLitExportAttrSelector._li_setup = true;
2337 openils.Util.show("acq-lit-export-attr-holder", "inline");
2340 this.exportAttrList = function() {
2341 var attr_def = acqLitExportAttrSelector.item;
2342 var li_list = this.getSelected();
2343 var value_list = li_list.map(
2345 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2346 attr_def.code, "lineitem_marc_attr_definition"
2349 ).filter(function(attr) { return Boolean(attr); });
2351 if (value_list.length > 0) {
2352 if (value_list.length < li_list.length) {
2354 dojo.string.substitute(
2355 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
2362 openils.XUL.contentToFileSaveDialog(
2363 value_list.join("\n"),
2364 localeStrings.EXPORT_SAVE_DIALOG_TITLE
2370 alert(dojo.string.substitute(
2371 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
2375 openils.Util.hide("acq-lit-export-attr-holder");
2378 this.printPO = function() {
2379 if(!this.isPO) return;
2380 progressDialog.show(true);
2381 fieldmapper.standardRequest(
2382 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
2384 params: [this.authtoken, this.isPO, 'html'],
2385 oncomplete: function(r) {
2386 progressDialog.hide();
2387 var evt = openils.Util.readResponse(r);
2388 if(evt && evt.template_output()) {
2389 openils.Util.printHtmlString(evt.template_output().data());
2396 this.batchCreateInvoice = function() {
2397 var liIds = this.getSelected(false, null, true /* id_list */)
2398 if (!liIds.length) return;
2399 var path = oilsBasePath + '/acq/invoice/view?create=1';
2400 dojo.forEach(liIds, function(li, idx) { path += '&attach_li=' + li });
2401 location.href = path;
2404 this.batchLinkInvoice = function(create) {
2405 var liIds = this.getSelected(false, null, true /* id_list */)
2406 if (!liIds.length) return;
2407 if (!self.invoiceLinkDialogManager) {
2408 self.invoiceLinkDialogManager =
2409 new InvoiceLinkDialogManager("li");
2411 self.invoiceLinkDialogManager.target = liIds;
2412 acqLitLinkInvoiceDialog.show();
2415 this.receivePO = function() {
2416 if (!this.isPO) return;
2418 for (var id in this.liCache) {
2419 /* assumption: liCache reflects exactly the
2420 * set of LIs that belong to our PO */
2421 if (this.liCache[id].state() != "received" &&
2422 !this.checkLiAlerts(id)) return;
2425 this.show('acq-lit-progress-numbers');
2427 fieldmapper.standardRequest(
2428 ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
2430 params: [this.authtoken, this.isPO],
2431 onresponse : function(r) {
2432 var resp = openils.Util.readResponse(r);
2433 self._updateProgressNumbers(resp, true);
2439 this.issueReceive = function(obj, rollback) {
2441 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
2443 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
2445 progressDialog.show(true);
2446 fieldmapper.standardRequest(
2447 ["open-ils.acq", method], {
2449 "params": [this.authtoken, obj.id()],
2450 "onresponse": function(r) {
2451 if (r = openils.Util.readResponse(r)) {
2452 self.fetchClaimInfo(
2453 part == "lineitem" ? obj.id() : obj.lineitem(),
2455 function() { self.handleReceive(r); }
2457 progressDialog.hide();
2465 * Handles the responses from receive and rollback ML calls.
2467 this.handleReceive = function(resp) {
2470 for (var li_id in resp.li) {
2471 for (var key in resp.li[li_id])
2472 self.liCache[li_id][key](resp.li[li_id][key]);
2473 self.updateLiState(self.liCache[li_id]);
2477 if (typeof(self.poUpdateCallback) == "function")
2478 self.poUpdateCallback(resp.po);
2481 for (var lid_id in resp.lid) {
2482 for (var key in resp.lid[lid_id])
2483 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
2484 self.updateLidState(self.copyCache[lid_id]);
2490 this.rollbackPoReceive = function() {
2491 if(!this.isPO) return;
2492 if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
2493 this.show('acq-lit-progress-numbers');
2495 fieldmapper.standardRequest(
2496 ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
2498 params: [this.authtoken, this.isPO],
2499 onresponse : function(r) {
2500 var resp = openils.Util.readResponse(r);
2501 self._updateProgressNumbers(resp, true);
2507 this._updateProgressNumbers = function(resp, reloadOnComplete, onComplete) {
2508 this.vlAgent.handleResponse(resp,
2509 function(resp, res) {
2510 if(reloadOnComplete)
2511 location.href = location.href;
2513 onComplete(resp, res);
2519 this._createPO = function(fields) {
2520 var wantall = (fields.create_from == "all");
2522 /* If we're a picklist or purchase order already and the user wants
2523 * all lineitems, we might have pages' worth of lineitems haven't all
2524 * been loaded yet, so getSelected() won't find them. The server,
2525 * however, should know about all our lineitems, so let's ask the
2526 * server for a complete list.
2531 true, function(list) {
2532 self._createPOFromLineitems(fields, list);
2533 }, /* id_list */ true
2536 this._createPOFromLineitems(fields, this.getSelected(false, null, true /* id_list */));
2540 this._createPOFromLineitems = function(fields, selected) {
2541 if (selected.length == 0) return;
2544 var po = new fieldmapper.acqpo();
2545 po.provider(this.createPoProviderSelector.attr("value"));
2546 po.ordering_agency(this.createPoAgencySelector.attr("value"));
2547 po.prepayment_required(fields.prepayment_required[0] ? true : false);
2549 // if we're creating assets, delay the asset creation
2550 // until after the PO is created. This will allow us to
2551 // use showAssetCreator() directly.
2553 fieldmapper.standardRequest(
2554 ["open-ils.acq", "open-ils.acq.purchase_order.create"],
2557 openils.User.authtoken,
2558 po, {lineitems : selected}
2560 onresponse : function(r) {
2561 var resp = openils.Util.readResponse(r);
2562 if (resp.complete) {
2563 // self.isPO is needed for showAssetCreator();
2564 self.isPO = resp.purchase_order.id();
2565 var redir = oilsBasePath + "/acq/po/view/" + self.isPO;
2566 if (fields.create_assets[0]) {
2567 self.showAssetCreator(
2568 function() {location.href = redir}
2571 location.href = redir;
2580 this.batchFundWidget = null;
2582 this.applyBatchLiFunds = function() {
2584 var liIds = this.getSelected().map(function(li) { return li.id(); });
2585 if(liIds.length == 0) return; // warn?
2588 batchFundUpdateDialog.show();
2590 if(!this.batchFundWidget) {
2591 this.batchFundWidget = new openils.widget.AutoFieldWidget({
2593 selfReference : true,
2594 labelFormat : fundLabelFormat,
2595 searchFormat : fundSearchFormat,
2596 searchFilter : {"active": "t"},
2597 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
2598 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2599 dijitArgs : { "required": true, "labelType": "html" },
2602 this.batchFundWidget.build();
2605 dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
2606 dojo.connect(batchFundUpdateSubmit, 'onClick',
2609 // TODO: call .dry_run first to test thresholds
2610 fieldmapper.standardRequest(
2611 ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
2614 openils.User.authtoken,
2616 self.batchFundWidget.widget.attr('value')
2618 oncomplete : function(r) {
2619 var resp = openils.Util.readResponse(r);
2621 location.href = location.href;
2630 this._deleteLiList = function(list, idx) {
2631 if(idx == null) idx = 0;
2632 if(idx >= list.length) return;
2637 if (this.isPO && (li.state() == "on-order" || li.state() == "received")) {
2638 /* It makes little sense to delete a lineitem from a PO that has
2639 * already been marked 'on-order'. Especially if EDI is in use,
2640 * such a purchase order will probably have already been shipped
2641 * off to a vendor, and mucking with it at this point could leave
2642 * your data in a bad state that doesn't jive with reality.
2644 * I could see making this restriction even firmer.
2646 * I could also see adjusting the li state comparisons, extending
2647 * the comparison to the PO's state, and/or providing functions
2648 * that house the logic for comparing states in a single location.
2650 * Yes, this will be really annoying if you have selected a lot
2651 * of lineitems to cancel that have been ordered. You'll get a
2652 * confirm dialog for each one.
2655 if (!confirm(localeStrings.DEL_LI_FROM_PO)) {
2656 self._deleteLiList(list, ++idx); /* move on to next in list */
2661 fieldmapper.standardRequest(
2663 this.isPO ? 'open-ils.acq.purchase_order.lineitem.delete' : 'open-ils.acq.picklist.lineitem.delete'],
2665 params: [openils.User.authtoken, liId],
2666 oncomplete: function(r) {
2667 self.removeLineitem(liId);
2668 self._deleteLiList(list, ++idx);
2674 this.editOrderMarc = function(li) {
2676 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
2677 to true in about:config */
2679 if(openils.XUL.isXUL()) {
2680 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul','','chrome');
2682 win = window.open('/xul/server/cat/marcedit.xul','','chrome');
2686 record : {marc : li.marc(), "rtype": "bre"},
2688 label: 'Save Record', // XXX I18N
2689 func: function(xmlString) {
2691 fieldmapper.standardRequest(
2692 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
2694 params: [openils.User.authtoken, li],
2695 oncomplete: function(r) {
2696 openils.Util.readResponse(r);
2698 self.drawInfo(li.id())
2704 'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
2705 'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
2709 this._savePl = function(values) {
2711 (values.which == 'all'),
2712 function(list) { self._savePlFromLineitems(values, list); }
2716 this._savePlFromLineitems = function(values, selected) {
2717 openils.Util.show("acq-lit-generic-progress");
2719 if(values.new_name) {
2720 openils.acq.Picklist.create(
2721 {name: values.new_name},
2727 oilsBasePath + "/acq/picklist/view/" + id;
2732 } else if(values.existing_pl) {
2733 // update lineitems to use an existing picklist
2735 values.existing_pl, selected, 0,
2738 oilsBasePath + "/acq/picklist/view/" +
2745 this._updateLiState = function(values, state) {
2746 progressDialog.show(true);
2748 (values.which == 'all'),
2750 self._updateLiStateFromLineitems(values, state, list);
2755 this._updateLiStateFromLineitems = function(values, state, selected) {
2756 if(!selected.length) return;
2757 dojo.forEach(selected, function(li) {li.state(state);});
2758 self._updateLiList(null, selected, 0,
2759 // TODO consider inline updates for efficiency
2760 function() { location.href = location.href }
2764 this._updateLiList = function(pl, list, idx, oncomplete) {
2765 if(idx >= list.length) return oncomplete();
2767 if(pl != null) li.picklist(pl);
2768 litGenericProgress.update({maximum: list.length, progress: idx});
2769 new openils.acq.Lineitem({lineitem:li}).update(
2771 self._updateLiList(pl, list, ++idx, oncomplete);
2776 this._loadPOSelect = function() {
2777 if (!this.createPoProviderSelector) {
2778 var widget = new openils.widget.AutoFieldWidget({
2779 "fmField": "provider",
2781 "searchFilter": {"active": "t"},
2782 "parentNode": dojo.byId("acq-lit-po-provider"),
2784 "onChange": function() {
2786 self._updateCreatePoPrepayCheckbox(
2787 this.item.prepayment_required()
2793 widget.build(function(w) { self.createPoProviderSelector = w; });
2796 if (!this.createPoAgencySelector) {
2797 var widget = new openils.widget.AutoFieldWidget({
2798 "fmField": "ordering_agency",
2800 "parentNode": dojo.byId("acq-lit-po-agency"),
2801 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2803 widget.build(function(w) { self.createPoAgencySelector = w; });
2807 this.showRealCopyEditUI = function(li) {
2812 this._fetchLineitem(li.id(),
2814 li = self.liCache[li.id()] = fullLi;
2818 id : li.lineitem_details().map(
2819 function(item) { return item.eg_copy_id() }
2823 oncomplete : function(r) {
2825 var r_list = openils.Util.readResponse( r );
2826 for (var i = 0; i < r_list.length; i++) {
2827 var copy = r_list[i];
2828 var volId = copy.call_number();
2829 var volume = self.volCache[volId];
2831 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2833 copy.call_number(volume);
2834 copyList.push(copy);
2837 xulG.volume_item_creator( { 'existing_copies' : copyList } );
2840 alert('error in oncomplete: ' + E);
2849 this.drawBibFinder = function(li) {
2852 var liWrapper = new openils.acq.Lineitem({lineitem:li});
2855 ['isbn', 'upc', 'issn', 'title', 'author'],
2857 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
2859 if(field == 'title' || field == 'author') {
2860 query += field +':' + val + ' ';
2862 query += 'identifier|' + field + ':' + val + ' ';
2869 oilsBasePath + '/acq/lineitem/findbib?query=' + escape(query),
2870 '', 'resizable,scrollbars=1,chrome');
2872 win.window.recordFound = function(bibId) {
2875 var attrs = li.attributes();
2876 li.attributes(null);
2877 li.eg_bib_id(bibId);
2879 fieldmapper.standardRequest(
2880 ["open-ils.acq", "open-ils.acq.lineitem.update"],
2882 "params": [openils.User.authtoken, li],
2884 "oncomplete": function(r) {
2885 if(openils.Util.readResponse(r)) {
2886 location.href = location.href;