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();
428 nodeByName("show_requests_link", row).href =
429 oilsBasePath + "/acq/picklist/user_request?lineitem=" + li.id();
431 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
432 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
433 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
435 if (!this.skipInitialEligibilityCheck)
439 function(full) { self.setClaimPolicyControl(full, row) },
443 this.updateLiNotesCount(li, row);
445 // show which PO this lineitem is a member of
446 if(li.purchase_order() && !this.isPO) {
448 this.poCache[li.purchase_order()] =
449 this.poCache[li.purchase_order()] ||
450 fieldmapper.standardRequest(
451 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
453 this.authtoken, li.purchase_order(), {
454 "flesh_price_summary": true,
455 "flesh_provider" : true,
456 "flesh_lineitem_count": true
459 if(po && !this.isMeta) {
460 openils.Util.show(nodeByName('po', row), 'inline');
461 var link = nodeByName('po_link', row);
462 link.setAttribute('href', oilsBasePath + '/acq/po/view/' + li.purchase_order() + '?focus_li=' + li.id());
463 link.innerHTML += po.name();
465 openils.Util.show(nodeByName('pro', row), 'inline');
466 link = nodeByName('pro_link', row);
467 link.setAttribute('href', oilsBasePath + '/conify/global/acq/provider/' + po.provider().id())
468 link.innerHTML += po.provider().code();
472 // show which picklist this lineitem is a member of
473 if(li.picklist() && (this.isPO || this.isMeta || this.isUni)) {
475 this.plCache[li.picklist()] =
476 this.plCache[li.picklist()] ||
477 fieldmapper.standardRequest(
478 ['open-ils.acq', 'open-ils.acq.picklist.retrieve.authoritative'],
479 {params: [this.authtoken, li.picklist()]});
481 if (pl.name() == "") {
482 openils.Util.show(nodeByName("bib_origin", row), "inline");
486 openils.Util.show(nodeByName('pl', row), 'inline');
487 var link = nodeByName('pl_link', row);
488 link.setAttribute('href', oilsBasePath + '/acq/picklist/view/' + li.picklist() + '?focus_li=' + li.id());
489 link.innerHTML += pl.name();
494 var countNode = nodeByName('count', row);
495 var count = li.item_count() || 0;
496 if (typeof(this._copy_count_cb) == "function") {
497 this._copy_count_cb(li.id(), count);
499 countNode.innerHTML = count;
500 countNode.id = 'acq-lit-copy-count-label-' + li.id();
503 var priceInput = dojo.query('[name=price]', row)[0];
504 priceInput.value = li.estimated_unit_price() || '';
505 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
507 // show either "mark received" or "unreceive" as appropriate
508 this.updateLiState(li, row);
510 if (skip_final_placement) {
514 // the last LI may be rendered after the call to show('list'),
515 // so make sure it's focused if necessary.
516 if (this.focusLineitem == li.id())
520 this._liCountClaims = function(li) {
522 for (var i = 0; i < li.lineitem_details().length; i++)
523 total += li.lineitem_details()[i].claims().length;
527 this._findLiRow = function(li) {
528 return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
531 this.reconsiderClaimControl = function(li, row) {
532 if (!row) row = this._findLiRow(li);
533 var option = nodeByName("action_manage_claims", row);
534 var eligible = this.claimEligibleLidByLi[li.id()].length;
535 var count = this._liCountClaims(li);
537 option.disabled = !(count || eligible);
539 dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
540 option.onclick = function() { self.claimDialog.show(li); };
543 this.clearEligibility = function(li) {
544 this.claimEligibleLidByLi[li.id()] = [];
546 if (li.lineitem_details()) {
547 li.lineitem_details().forEach(
548 function(lid) { delete self.claimEligibleLid[lid.id()]; }
552 if (this.copyCache) {
554 for (var k in this.copyCache) {
555 if (this.copyCache[k].lineitem() == li.id())
559 function(k) { delete self.claimEligibleLid[k]; }
564 this.checkClaimEligibility = function(li, callback, row) {
565 /* Assume always eligible, i.e. from this interface we don't care about
566 * claim eligibility any more. this is where the user would force a
568 this.clearEligibility(li);
569 this.claimEligibleLidByLi[li.id()] = li.lineitem_details().map(
570 function(lid) { return lid.id(); }
572 li.lineitem_details().forEach(
573 function(lid) { self.claimEligibleLid[lid.id()] = true; }
575 this.reconsiderClaimControl(li, row);
576 if (callback) callback(li);
578 this.clearEligibility(li);
579 fieldmapper.standardRequest(
580 ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
581 "params": [openils.User.authtoken, {"lineitem": li.id()}],
583 "onresponse": function(r) {
584 if (r = openils.Util.readResponse(r)) {
585 self.claimEligibleLidByLi[li.id()].push(
588 self.claimEligibleLid[r.lineitem_detail()] = true;
591 "oncomplete": function() {
592 self.reconsiderClaimControl(li, row);
593 if (typeof(callback) == "function")
601 this.updateLiNotesCount = function(li, row) {
602 if (!row) row = this._findLiRow(li);
604 var has_notes = (li.lineitem_notes().filter(
605 function(o) { return Boolean (o.alert_text()); }
608 /* U+2691 is the code point for a filled-in flag character */
609 nodeByName("notes_alert_flag", row).innerHTML =
610 has_notes ? "⚑" : "";
611 nodeByName("noteslink", row).style.fontStyle =
612 has_notes ? "italic" : "normal";
613 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
616 /* XXX NOT related to _updateLiState(). rethink */
617 this.updateLiState = function(li, row) {
618 if (!row) row = this._findLiRow(li);
620 var actReceive = nodeByName("action_mark_recv", row);
621 var actUnRecv = nodeByName("action_mark_unrecv", row);
622 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
623 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
624 var actNewInvoice = nodeByName('action_new_invoice', row);
625 var actLinkInvoice = nodeByName('action_link_invoice', row);
626 var actViewInvoice = nodeByName('action_view_invoice', row);
628 // always allow access to LI history
629 nodeByName('action_view_history', row).onclick =
630 function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
632 /* handle row coloring for based on LI state */
633 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
634 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
636 // Expose invoice actions for any lineitem that is linked to a PO
637 if( li.purchase_order() ) {
639 actNewInvoice.disabled = false;
640 actLinkInvoice.disabled = false;
641 actViewInvoice.disabled = false;
643 actNewInvoice.onclick = function() {
644 location.href = oilsBasePath + '/acq/invoice/view?create=1&attach_li=' + li.id();
645 nodeByName("action_none", row).selected = true;
648 actLinkInvoice.onclick = function() {
649 if (!self.invoiceLinkDialogManager) {
650 self.invoiceLinkDialogManager =
651 new InvoiceLinkDialogManager("li");
653 self.invoiceLinkDialogManager.target = li;
654 acqLitLinkInvoiceDialog.show();
655 nodeByName("action_none", row).selected = true;
658 actViewInvoice.onclick = function() {
659 location.href = oilsBasePath +
660 "/acq/search/unified?so=" +
661 base64Encode({"jub":[{"id": li.id()}]}) +
663 nodeByName("action_none", row).selected = true;
669 * If we haven't fleshed the lineitem_details, default to allowing access to the
670 * holdings maintenence actions. The alternative is to flesh LIDs on every lineitem,
671 * but that will add to page render time. Let's see if this will suffice...
673 var lids = li.lineitem_details();
675 (lids && !lids.filter(function(lid) { return lid.eg_copy_id() })[0] )) {
677 actUpdateBarcodes.disabled = false;
678 actUpdateBarcodes.onclick = function() {
679 self.showRealCopyEditUI(li);
680 nodeByName("action_none", row).selected = true;
682 actHoldingsMaint.disabled = false;
683 actHoldingsMaint.onclick =
684 self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
687 var state_cell = nodeByName("li_state", row);
692 if(typeof li.cancel_reason() == "object") {
693 var holds_state = dojo.create(
695 "style": "border-bottom: 1px dashed #000;",
696 "innerHTML": li.state()
697 }, state_cell, "only"
701 "label": "<em>" + li.cancel_reason().label() +
702 "</em><br />" + li.cancel_reason().description(),
703 "connectId": [holds_state]
704 }, dojo.create("span", null, state_cell, "last")
710 actReceive.disabled = false;
711 actReceive.onclick = function() {
712 if (self.checkLiAlerts(li.id()))
713 self.issueReceive(li);
714 nodeByName("action_none", row).selected = true;
719 actUnRecv.disabled = false;
720 actUnRecv.onclick = function() {
721 if (confirm(localeStrings.UNRECEIVE_LI))
722 self.issueReceive(li, /* rollback */ true);
723 nodeByName("action_none", row).selected = true;
728 state_cell.innerHTML = li.state(); // TODO i18n state labels
732 this._setAlertStore = function() {
733 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
735 "data": acqliat.toStoreData(
738 "owning_lib": aou.orgNodeTrail(
739 aou.findOrgUnit(openils.User.user.ws_ou())
740 ).map(function(o) { return o.id(); })
746 acqLitAlertAlertText.setValue(); /* make the store "live" */
747 acqLitAlertAlertText._store_ready = true;
751 * Draws and shows the lineitem notes pane
753 this.drawLiNotes = function(li) {
755 this.focusLineitem = li.id();
757 if (!acqLitAlertAlertText._store_ready)
758 this._setAlertStore();
761 li.lineitem_notes().sort(
763 if(a.edit_time() < b.edit_time()) return 1;
769 while(this.liNotesTbody.childNodes[0])
770 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
773 acqLitCreateNoteSubmit.onClick = function() {
774 var value = acqLitCreateNoteText.attr('value');
776 var note = new fieldmapper.acqlin();
779 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
782 note.lineitem(li.id());
784 self.updateLiNotes(li, note);
785 acqLitCreateNoteVendorPublic.attr("checked", false);
786 acqLitCreateNoteText.attr("value", "");
789 acqLitCreateAlertSubmit.onClick = function() {
790 if (!acqLitAlertAlertText.item) {
791 alert(localeStrings.ALERT_UNSELECTED);
795 var alert_text = new fieldmapper.acqliat().fromStoreItem(
796 acqLitAlertAlertText.item
798 var value = acqLitAlertNoteValue.attr("value") || "";
800 var note = new fieldmapper.acqlin();
802 note.lineitem(li.id());
804 note.alert_text(alert_text);
806 self.updateLiNotes(li, note);
809 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
813 * Draws a single lineitem note in the notes pane
815 this.addLiNote = function(li, note) {
816 if(note.isdeleted()) return;
818 var row = self.liNotesRow.cloneNode(true);
819 nodeByName("value", row).innerHTML = note.value();
820 var alert_node = nodeByName("alert_code", row);
821 if (note.alert_text()) {
822 alert_node.innerHTML = dojo.string.substitute(
824 aou.findOrgUnit(note.alert_text().owning_lib()).shortname(),
825 note.alert_text().code()
828 if (note.alert_text().description()) {
831 "connectId": [alert_node],
832 "label": note.alert_text().description()
833 }, dojo.create("span", null, alert_node, "after")
838 if (openils.Util.isTrue(note.vendor_public()))
839 nodeByName("vendor_public", row).innerHTML =
840 localeStrings.VENDOR_PUBLIC;
842 nodeByName("delete", row).onclick = function() {
843 note.isdeleted(true);
844 self.liNotesTbody.removeChild(row);
845 self.updateLiNotes(li);
848 if(note.edit_time()) {
849 nodeByName("edit_time", row).innerHTML =
850 dojo.date.locale.format(
851 dojo.date.stamp.fromISOString(note.edit_time()),
852 {formatLength:'short'});
855 self.liNotesTbody.appendChild(row);
859 * Updates any new/changed/deleted notes on the server
861 this.updateLiNotes = function(li, newNote) {
867 notes = li.lineitem_notes().filter(
869 if(note.ischanged() || note.isnew() || note.isdeleted())
875 if(notes.length == 0) return;
876 progressDialog.show();
878 fieldmapper.standardRequest(
879 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
881 params : [this.authtoken, notes],
882 onresponse : function(r) {
883 var resp = openils.Util.readResponse(r);
888 // remove the old changed notes
890 dojo.forEach(li.lineitem_notes(),
892 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
896 li.lineitem_notes(list);
899 progressDialog.hide();
900 self.updateLiNotesCount(li);
901 self.drawLiNotes(li);
905 progressDialog.update(resp);
906 var newnote = resp.note;
908 if(!newnote.isdeleted()) {
909 newnote.isnew(false);
910 newnote.ischanged(false);
911 li.lineitem_notes().push(newnote);
918 this.updateLiPrice = function(input, li) {
920 var price = input.value;
921 if(Number(price) == Number(li.estimated_unit_price())) return;
923 fieldmapper.standardRequest(
924 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
925 { async : false, // redundant w/ timeout
927 params : [this.authtoken, li.id(), price],
928 oncomplete : function(r) {
929 openils.Util.readResponse(r);
930 li.estimated_unit_price(price); // update local copy
933 * If this is a PO and every visible lineitem has a price,
934 * check again to see if this PO can be activated. Note that
935 * every visible lineitem having a price does not guarantee it can
936 * be activated, which is why we still make the call. Having a price
937 * set for every visiable lineitem is just the lowest barrier to entry.
940 var priceNodes = dojo.query('[name=price]', dojo.byId('acq-lit-tbody'));
942 dojo.forEach(priceNodes, function(node) { if (node.value == '') allSet = false});
943 if (allSet) checkCouldActivatePo();
950 this.removeLineitem = function(liId) {
951 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
952 delete this.liCache[liId];
953 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
956 this.drawInfo = function(liId) {
957 this.focusLineitem = liId;
958 if (!this._isRelatedViewer) {
959 var d = dojo.byId("acq-lit-info-related");
960 if (!this.relCache[liId]) {
961 fieldmapper.standardRequest(
964 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
967 "params": [openils.User.authtoken, liId],
968 "onresponse": function(r) {
969 self.relCache[liId] = openils.Util.readResponse(r);
970 nodeByName("related_number", d).innerHTML =
973 self.relCache[liId] >1 ? "show" : "hide"
979 nodeByName("related_number", d).innerHTML = this.relCache[liId];
980 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
985 openils.acq.Lineitem.fetchAttrDefs(
987 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
992 /* For a given list of lineitem ids, build a list of full lineitems
993 * re-using the fetching logic that is otherwise typical to use in this
996 * If we've already got a lineitem in the cache, just use that.
998 * Once we've built a list of lineitems, call callback(thatlist).
1000 this.fetchLineitemsById = function(id_list, callback) {
1001 var total = id_list.length;
1002 var result_list = [];
1004 var inner = function(li) {
1005 result_list.push(li)
1007 callback(result_list);
1010 id_list.forEach(function(id) { self._fetchLineitem(id, inner); });
1013 this._fetchLineitem = function(liId, handler, force) {
1015 var li = this.liCache[liId];
1016 if(li && li.marc() && li.lineitem_details() && !force)
1019 fieldmapper.standardRequest(
1020 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
1023 params: [self.authtoken, liId, {
1025 flesh_cancel_reason: true,
1026 flesh_li_details: true,
1028 flesh_fund_debit: true }],
1030 oncomplete: function(r) {
1031 var li = openils.Util.readResponse(r);
1032 self.liCache[liId] = li;
1039 this._drawInfo = function(li) {
1041 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
1043 if(li.eg_bib_id()) {
1044 openils.Util.hide('acq-lit-marc-order-record-label');
1045 openils.Util.hide(acqLitEditOrderMarc.domNode);
1046 openils.Util.show('acq-lit-marc-real-record-label');
1048 openils.Util.show('acq-lit-marc-order-record-label');
1049 openils.Util.show(acqLitEditOrderMarc.domNode);
1050 openils.Util.hide('acq-lit-marc-real-record-label');
1053 this.drawMarcHTML(li);
1054 this.infoTbody = dojo.byId('acq-lit-info-tbody');
1057 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
1058 while(this.infoTbody.childNodes[0])
1059 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
1061 for(var i = 0; i < li.attributes().length; i++) {
1062 var attr = li.attributes()[i];
1063 var row = this.infoRow.cloneNode(true);
1065 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
1066 var name = openils.acq.Lineitem.attrDefs[type].filter(
1068 return (a.code() == attr.attr_name());
1070 ).pop().description();
1072 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
1073 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
1074 this.infoTbody.appendChild(row);
1077 if (!this._isRelatedViewer) {
1078 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
1079 oilsBasePath + "/acq/lineitem/related/" + li.id();
1084 this.generateMakeRecTab = function(bib_id,default_view, row) {
1088 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
1091 show_nav_buttons : true,
1092 show_print_button : true,
1093 opac_url : xulG.url_prefix('opac_rdetail|' + bib_id),
1094 default_view : default_view
1098 if(row) nodeByName("action_none", row).selected = true;
1102 this.drawMarcHTML = function(li) {
1103 var params = [null, true, li.marc()];
1105 params = [li.eg_bib_id(), true];
1107 fieldmapper.standardRequest(
1108 ['open-ils.search', 'open-ils.search.biblio.record.html'],
1111 oncomplete: function(r) {
1112 dojo.byId('acq-lit-marc-div').innerHTML =
1113 openils.Util.readResponse(r);
1119 this.drawCopies = function(liId, force_fetch) {
1120 this.focusLineitem = liId;
1121 if (typeof force_fetch == "undefined")
1122 force_fetch = false;
1124 if (document.referrer.match(/invoice/)) {
1125 // got here from the invoice page, show the 'return-to-invoice' button
1126 var cgi = new openils.CGI({url : document.referrer});
1127 cgi.param('focus_li', liId);
1128 openils.Util.show(dojo.byId('acq-lit-copies-back-to-invoice-button-wrapper'), 'inline');
1129 var button = dojo.byId('acq-lit-copies-back-to-invoice-button');
1130 button.onclick = function() { location.href = cgi.url() };
1133 openils.acq.Lineitem.fetchAndRender(liId, {},
1134 function(li, html) {
1135 dojo.byId('acq-lit-copies-li-summary').innerHTML = html;
1139 this.show('copies');
1141 this.copyCache = {};
1142 this.copyWidgetCache = {};
1143 this.oldCopyWidgetCache = {};
1144 this.virtDfaCounts = {};
1145 this.realDfaCache = {};
1148 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
1149 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
1150 acqLitCopyCountInput.attr('value', '0');
1152 while(this.copyTbody.childNodes[0])
1153 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
1155 this._drawBatchCopyWidgets();
1157 this._drawDistribApplied(liId);
1159 this._fetchDistribFormulas(
1161 openils.acq.Lineitem.fetchAttrDefs(
1163 self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch);
1170 this._saveDistribAppliedTemplates = function() {
1171 if (!this._appliedDistribTemplate) {
1172 this._appliedDistribTemplate =
1173 dojo.byId("acq-lit-distrib-applied-tbody").
1174 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
1175 dojo.attr(this._appliedDistribTemplate, "id");
1179 this._drawDistribApplied = function(liId) {
1180 /* Build this table while hidden to prevent rendering artifacts */
1181 openils.Util.hide("acq-lit-distrib-applied-tbody");
1183 this._saveDistribAppliedTemplates();
1185 /* Remove any rows in the table from previous populations */
1186 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
1187 forEach(dojo.destroy);
1189 /* Unregister all dijits previously created (for some reason this isn't
1190 * covered by the above destroy calls). */
1191 dijit.registry.forEach(
1192 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
1195 /* Populate the table with our liId */
1197 fieldmapper.standardRequest(
1199 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
1202 "params": [self.authtoken, liId],
1203 "onresponse": function(r) {
1204 var dfa = openils.Util.readResponse(r);
1207 self.realDfaCache[dfa.id()] = dfa;
1208 self._drawDistribAppliedUnit(dfa);
1211 "oncomplete": function() {
1212 /* Reveal built table */
1215 "acq-lit-distrib-applied-tbody", "table-row-group"
1223 this._drawDistribAppliedUnit = function(dfa) {
1224 var new_row = false;
1225 var row = dojo.query(
1226 'tr[formula="' + dfa.formula().id() + '"]',
1227 "acq-lit-distrib-applied-tbody"
1232 row = dojo.clone(this._appliedDistribTemplate);
1233 dojo.attr(row, "formula", dfa.formula().id());
1234 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
1237 var td = dojo.query("td", row)[0];
1239 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1240 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1243 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1245 new dijit.form.Button(
1247 "onClick": function() {
1248 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1249 self.deleteDfa(dfa);
1252 /* XXX I /cannot/ make the following work in as a CSS class
1253 * for some reason. So frustrating... */
1254 "style": function(id) {
1256 "font-weight: bold; color: #c00;" :
1258 }(dfa.id()) + "margin: 0 6px;display: inline;"
1259 }, "dfa-button-" + dfa.id()
1263 "connectId": ["dfa-button-" + dfa.id()],
1264 "label": dojo.string.substitute(
1265 localeStrings.DFA_TIP, dfa.id() > 0 ? [
1266 openils.User.formalName(dfa.creator()),
1267 dojo.date.locale.format(
1268 dojo.date.stamp.fromISOString(dfa.create_time()),
1269 {"formatLength":"short"}
1271 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
1273 }, "dfa-tip-" + dfa.id()
1277 this.deleteDfa = function(dfa) {
1278 if (dfa.id() > 0) { /* real */
1279 this.pcrud.eliminate(
1282 "oncomplete": function() {
1283 self._removeDistribApplied(dfa.id());
1284 delete self.realDfaCache[dfa.id()];
1288 } else { /* virtual */
1289 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
1290 this.virtDfaCounts[dfa.formula().id()] = 0;
1291 /* hasn't been saved yet, so no need to do anything server side */
1292 this._removeDistribApplied(dfa.id());
1297 this._removeDistribApplied = function(dfaId) {
1298 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
1299 dijit.registry.forEach(
1300 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
1302 this._removeDistribAppliedEmptyRows();
1305 this._removeAllDistribAppliedVirtual = function() {
1306 /* Unregister dijits */
1307 dijit.registry.forEach(
1308 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
1310 this._removeDistribAppliedEmptyRows();
1313 this._removeDistribAppliedEmptyRows = function() {
1314 /* Remove any rows with no DFA at all */
1315 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
1317 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
1323 * Insert a new row into the distribution formula selection form
1325 this._addDistribFormulaRow = function() {
1328 if (!self.distribForms) {
1329 // no formulas, hide the form
1330 openils.Util.hide('acq-lit-distrib-formula-table');
1334 if(!this.distribFormulaTemplate)
1335 this.distribFormulaTemplate =
1336 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
1338 var row = this.distribFormulaTemplate.cloneNode(true);
1339 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
1341 this.dfSelector = new dijit.form.FilteringSelect(
1342 {"labelAttr": "dynLabel", "labelType": "html"},
1343 nodeByName("selector", row)
1345 this._updateFormulaStore();
1346 this.dfSelector.fetchProperties =
1347 {"sort": [{"attribute": "use_count", "descending": true}]};
1349 var apply = new dijit.form.Button(
1350 {"label": localeStrings.APPLY},
1351 nodeByName('set_button', row)
1354 var reset = new dijit.form.Button(
1355 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
1356 nodeByName("reset_button", row)
1359 dojo.connect(apply, 'onClick',
1361 var form_id = self.dfSelector.attr("value");
1362 if(!form_id) return;
1363 self._applyDistribFormula(form_id);
1364 reset.attr("disabled", false);
1368 dojo.connect(reset, 'onClick',
1370 self.restoreCopyFieldsBeforeDF();
1371 self.virtDfaCounts = {};
1372 self.virtDfaId = -1;
1374 self._updateFormulaStore();
1375 self._removeAllDistribAppliedVirtual();
1376 reset.attr("disabled", "true");
1383 * Applies a distrib formula to the current set of copies
1385 this._applyDistribFormula = function(formula) {
1386 if(!formula) return;
1388 formula = this.distribForms.filter(
1389 function(form) { return form.id() == formula; }
1392 var copyRows = dojo.query('tr', self.copyTbody);
1394 if (this.dfeOffset >= copyRows.length) {
1395 alert(localeStrings.OUT_OF_COPIES);
1399 var entries_applied = 0;
1401 var rowIndex = this.dfeOffset;
1402 rowIndex < copyRows.length;
1406 var row = copyRows[rowIndex];
1407 var copy_id = row.getAttribute('copy_id');
1408 var copyWidgets = this.copyWidgetCache[copy_id];
1409 var entryIndex = this.dfeOffset;
1412 // find the correct entry for the current row
1413 dojo.forEach(formula.entries(),
1416 entryIndex += e.item_count();
1417 if(entryIndex > rowIndex)
1425 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
1426 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
1429 this.saveCopyFieldsBeforeDF(copy_id);
1430 this._copy_fields_for_acqdf.forEach(
1432 if(entry[field]()) {
1433 copyWidgets[field].attr('value', (entry[field]()));
1440 if (entries_applied) {
1441 this.virtDfaCounts[formula.id()] =
1442 ++(this.virtDfaCounts[formula.id()]) || 1;
1443 this._updateFormulaStore();
1444 this._drawDistribAppliedUnit(
1446 var dfa = new acqdfa();
1447 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
1450 this.dfeOffset += entries_applied;
1455 * This function updates the DF store for the dropdown so that use_counts
1456 * can reflect DF applications from this session before they're saved
1459 this._updateFormulaStore = function() {
1460 this.dfSelector.store = new dojo.data.ItemFileReadStore(
1462 "data": self._labelFormulasWithCounts(
1463 acqdf.toStoreData(self.distribForms)
1469 this.saveCopyFieldsBeforeDF = function(copy_id) {
1471 if (!this.oldCopyWidgetCache[copy_id]) {
1472 var copyWidgets = this.copyWidgetCache[copy_id];
1474 this.oldCopyWidgetCache[copy_id] = {};
1475 this._copy_fields_for_acqdf.forEach(
1477 self.oldCopyWidgetCache[copy_id][f] =
1478 copyWidgets[f].attr("value");
1484 this.restoreCopyFieldsBeforeDF = function() {
1486 for (var copy_id in this.oldCopyWidgetCache) {
1487 this._copy_fields_for_acqdf.forEach(
1489 self.copyWidgetCache[copy_id][f].attr(
1490 "value", self.oldCopyWidgetCache[copy_id][f]
1497 this._labelFormulasWithCounts = function(store_data) {
1498 for (var key in store_data.items) {
1499 var obj = store_data.items[key];
1500 obj.use_count = Number(obj.use_count); /* needed for sorting */
1502 if (this.virtDfaCounts[obj.id])
1503 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
1505 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
1506 obj.use_count + "]</span> " + obj.name;
1512 * This method formerly would not refetch the DF formulas if they'd been
1513 * loaded already, but now it always re-fetches, since use_count changes.
1515 /** TODO: port distrib-formula selector to autofieldwidget+pcrud/dojo store */
1516 this._fetchDistribFormulas = function(onload) {
1517 fieldmapper.standardRequest(
1519 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
1522 "params": [openils.User.authtoken, 0, 500],
1523 "oncomplete": function(r) {
1524 self.distribForms = openils.Util.readResponse(r);
1525 if(!self.distribForms || self.distribForms.length == 0) {
1526 self.distribForms = [];
1528 self._addDistribFormulaRow();
1535 this._drawBatchCopyWidgets = function() {
1536 var row = this.copyBatchRow;
1537 dojo.forEach(liDetailBatchFields,
1539 if(self.copyBatchRowDrawn) {
1540 self.copyBatchWidgets[field].attr('value', null);
1542 var widget = new openils.widget.AutoFieldWidget({
1545 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1546 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1547 searchFilter : (field == 'fund') ? {"active": "t"} : null,
1548 parentNode : dojo.query('[name='+field+']', row)[0],
1549 orgLimitPerms : ['CREATE_PICKLIST'],
1552 "labelType": (field == "fund") ? "html" : null
1554 noCache: (field == "fund"),
1559 if (field == "fund" && w.store)
1560 self._ensureCSSFundClasses(w.store);
1561 self.copyBatchWidgets[field] = w;
1564 if (field == "fund") {
1566 widget.widget, "onChange", function(val) {
1567 self._updateFundSelectorStyle(widget, val);
1574 this.copyBatchRowDrawn = true;
1577 this.batchCopyUpdate = function() {
1579 for(var k in this.copyWidgetCache) {
1580 var cache = this.copyWidgetCache[k];
1581 dojo.forEach(liDetailBatchFields, function(f) {
1582 var newval = self.copyBatchWidgets[f].attr('value');
1583 if(newval) cache[f].attr('value', newval);
1588 this._drawCopies = function(li) {
1591 // this button sets the total number of copies for a given lineitem
1592 acqLitAddCopyCount.onClick = function() {
1593 var count = acqLitCopyCountInput.attr('value');
1596 while(self.copyCount() < count)
1599 // delete rows if necessary
1600 var diff = self.copyCount() - count;
1602 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
1603 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
1604 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
1606 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1612 if(li.lineitem_details().length > 0) {
1613 dojo.forEach(li.lineitem_details(),
1615 self.addCopy(li, copy);
1623 this.copyCount = function() {
1625 for(var id in this.copyCache) {
1626 if(!this.copyCache[id].isdeleted())
1632 this.virtCopyId = -1;
1633 this.addCopy = function(li, copy) {
1634 var row = this.copyRow.cloneNode(true);
1635 this.copyTbody.appendChild(row);
1639 copy = new fieldmapper.acqlid();
1641 copy.id(this.virtCopyId--);
1642 copy.lineitem(li.id());
1645 this.copyCache[copy.id()] = copy;
1646 row.setAttribute('copy_id', copy.id());
1647 self.copyWidgetCache[copy.id()] = {};
1649 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1651 var rcvr = copy.receiver();
1653 if (!userCache[rcvr]) {
1654 if(rcvr == openils.User.user.id()) {
1655 userCache[rcvr] = openils.User.user;
1657 userCache[rcvr] = fieldmapper.standardRequest(
1658 ['open-ils.actor', 'open-ils.actor.user.retrieve'],
1659 {params: [openils.User.authtoken, rcvr]}
1663 dojo.query('[name=receiver]', row)[0].innerHTML = userCache[rcvr].usrname();
1666 dojo.forEach(liDetailFields,
1669 if (field == "fund") {
1670 searchFilter = (copy.fund() ?
1671 {"-or": {"active": "t", "id": copy.fund()}} :
1674 searchFilter = null;
1677 var readOnly = false;
1679 // TODO: Add support for changing the owning_lib after real copies have been made.
1680 // owning_lib is order data as much as its item data
1681 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
1685 // TODO: add support for changing the fund after debits have been created
1686 // Note: invoicing allows the change
1687 if(copy.fund_debit() && field == 'fund') {
1692 var widget = new openils.widget.AutoFieldWidget({
1695 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1696 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1697 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1698 searchFilter : searchFilter,
1699 noCache: (field == "fund"),
1701 parentNode : dojo.query('[name='+field+']', row)[0],
1702 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
1703 readOnly : readOnly,
1704 orgDefaultsToWs : true
1708 // make sure we capture the value from any async widgets
1711 if (field == "fund" && w.store)
1712 self._ensureCSSFundClasses(w.store);
1715 copy[field](ww.getFormattedValue())
1717 self.copyWidgetCache[copy.id()][field] = w;
1719 dojo.connect(w, 'onChange',
1721 if (field == "fund")
1722 self._updateFundSelectorStyle(widget, val);
1724 if (!readOnly && (copy.isnew() || val != copy[field]())) {
1725 // prevent setting ischanged() automatically on widget load for existing copies
1726 copy[field](widget.getFormattedValue())
1727 copy.ischanged(true);
1736 this.updateLidState(copy, row);
1739 this._ensureCSSFundClass = function(id) {
1740 if (!this.fundStyleSheet) {
1742 "style", {"type": "text/css"},
1743 document.getElementsByTagName("head")[0], "last"
1745 this.fundStyleSheet = document.styleSheets[
1746 document.styleSheets.length - 1
1750 var cn = "fund_" + id;
1751 if (!this.haveFundClass[cn]) {
1752 fieldmapper.standardRequest(
1753 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
1755 "params": [openils.User.authtoken, id],
1757 "oncomplete": function(r) {
1758 r = openils.Util.readResponse(r);
1759 self.fundBalanceState[id] = r;
1761 if (r[0] /* stop */)
1762 style = fundStyles.stop;
1763 else if (r[1] /* warning */)
1764 style = fundStyles.warning;
1765 self.fundStyleSheet.insertRule(
1766 "." + cn + " { " + style + " }",
1767 self.fundStyleSheet.cssRules.length
1769 self.haveFundClass[cn] = true;
1776 this._ensureCSSFundClasses = function(store) {
1778 "query": {"id": "*"},
1779 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
1783 this._updateFundSelectorStyle = function(widget, fund_id) {
1784 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
1785 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
1788 this.updateLidState = function(copy, row) {
1791 if (typeof(row) == "undefined") {
1792 row = dojo.query('tr[copy_id="' + copy.id() + '"]', this.copyTbody)[0];
1796 var recv_link = nodeByName("receive", row);
1797 var unrecv_link = nodeByName("unreceive", row);
1798 var del_link = nodeByName("delete", row);
1799 var cxl_link = nodeByName("cancel", row);
1800 var claim_link = nodeByName("claim", row);
1801 var cxl_reason_link = nodeByName("cancel_reason", row);
1803 // by default, hide all the actions
1804 openils.Util.hide(del_link.parentNode);
1805 openils.Util.hide(recv_link);
1806 openils.Util.hide(unrecv_link);
1807 openils.Util.hide(cxl_link);
1808 openils.Util.hide(claim_link);
1809 openils.Util.hide(cxl_reason_link);
1811 if (copy.id() > 0) { // real copies (LIDs)
1813 if (copy.cancel_reason()) {
1815 /* --------- cancelled -------------------------- */
1817 /* XXX the following may leak memory in a long lived table:
1818 * dijits may not get destroyed... not positive. revisit. */
1819 var holds_reason = dojo.create(
1821 "style": "border-bottom: 1px dashed #000;",
1822 "innerHTML": "Cancelled" /* XXX [sic] and i18n */
1823 }, cxl_reason_link, "only"
1827 "label": "<em>" + copy.cancel_reason().label() +
1828 "</em><br />" + copy.cancel_reason().description(),
1829 "connectId": [holds_reason]
1830 }, dojo.create("span", null, cxl_reason_link, "last")
1832 openils.Util.show(cxl_reason_link, "inline");
1834 } else if (copy.recv_time()) {
1836 /* --------- received -------------------------- */
1838 openils.Util.show(unrecv_link, "inline");
1839 unrecv_link.onclick = function() {
1840 if (confirm(localeStrings.UNRECEIVE_LID))
1841 self.issueReceive(copy, /* rollback */ true);
1844 } else if (this.liCache[copy.lineitem()].state() == 'on-order') {
1846 /* --------- on order -------------------------- */
1848 openils.Util.show(recv_link, 'inline');
1849 openils.Util.show(cxl_link, "inline");
1851 recv_link.onclick = function() {
1852 if (self.checkLiAlerts(copy.lineitem()))
1853 self.issueReceive(copy);
1856 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
1860 /* --------- pre-order copies -------------------------- */
1862 del_link.onclick = function() { self.deleteCopy(row) };
1863 openils.Util.show(del_link.parentNode);
1869 /* --------- virtual copies -------------------------- */
1871 del_link.onclick = function() { self.deleteCopy(row) };
1872 openils.Util.show(del_link.parentNode);
1876 this.cancelLid = function(lid_id) {
1877 lidCancelDialog._lid_id = lid_id;
1878 openils.Util.show(lidCancelDialog.domNode.parentNode);
1879 lidCancelDialog.show();
1880 if (!lidCancelDialog._prepared) {
1881 var widget = new openils.widget.AutoFieldWidget({
1882 "fmField": "cancel_reason",
1883 "fmClass": "acqlid",
1884 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
1885 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1890 acqLidCancelButton.onClick = function() {
1891 if (w.attr("value")) {
1892 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
1894 lidCancelDialog._lid_id,
1898 lidCancelDialog.hide();
1901 lidCancelDialog._prepared = true;
1907 this._cancelLid = function(lid_id, reason) {
1908 fieldmapper.standardRequest(
1909 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
1910 "params": [openils.User.authtoken, lid_id, reason],
1912 "onresponse": function(r) {
1913 if (r = openils.Util.readResponse(r)) {
1915 for (var id in r.lid) {
1916 /* actually this should only iterate once */
1917 self.copyCache[id].cancel_reason(
1918 r.lid[id].cancel_reason
1920 self.updateLidState(self.copyCache[id]);
1929 this._confirmAlert = function(li, lin) {
1931 dojo.string.substitute(
1932 localeStrings.CONFIRM_LI_ALERT, [
1933 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1934 "title", "lineitem_marc_attr_definition"
1936 /* XXX it's really better add a parameter and to adjust
1937 * the format string rather than do this concatenation
1938 * here, but if someone wants this for 2.2 in a hurry,
1939 * we can sidestep the problem of updating the strings
1940 * while the translators are working. */
1942 aou.findOrgUnit(lin.alert_text().owning_lib()).shortname() +
1944 lin.alert_text().code()
1946 lin.alert_text().description() || "",
1953 this.checkLiAlerts = function(li_id) {
1954 var li = this.liCache[li_id];
1956 var alert_notes = li.lineitem_notes().filter(
1957 function(o) { return Boolean(o.alert_text()); }
1960 /* this is _intentionally_ not done in a call to forEach() ... */
1961 for (var i = 0; i < alert_notes.length; i++) {
1962 if (this.noteAcks[alert_notes[i].id()])
1964 else if (!this._confirmAlert(li, alert_notes[i]))
1967 this.noteAcks[alert_notes[i].id()] = true;
1973 this.deleteCopy = function(row) {
1974 var copy = this.copyCache[row.getAttribute('copy_id')];
1975 copy.isdeleted(true);
1977 delete this.copyCache[copy.id()];
1978 this.copyTbody.removeChild(row);
1981 this._virtDfaCountsAsList = function() {
1983 for (var key in this.virtDfaCounts) {
1984 for (var i = 0; i < this.virtDfaCounts[key]; i++)
1990 this.confirmBreachedCopyFunds = function(copies) {
1991 var stop = 0, warning = 0;
1995 var state = self.fundBalanceState[o.fund()];
1996 if (state[0] /* stop */)
1998 else if (state[1] /* warning */)
2005 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
2006 } else if (warning) {
2007 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
2012 this.saveCopyChanges = function(liId) {
2018 for(var id in this.copyCache) {
2019 var c = this.copyCache[id];
2020 if(!c.isdeleted()) total++;
2021 if(c.isnew() || c.ischanged() || c.isdeleted()) {
2022 if(c.id() < 0) c.id(null);
2028 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
2031 if (copies.length > 0) {
2032 if (!this.confirmBreachedCopyFunds(copies))
2035 if (typeof(this._copy_count_cb) == "function")
2036 this._copy_count_cb(liId, total);
2038 openils.Util.show("acq-lit-update-copies-progress");
2039 fieldmapper.standardRequest(
2040 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
2042 params: [openils.User.authtoken, copies],
2043 onresponse: function(r) {
2044 var res = openils.Util.readResponse(r);
2045 litUpdateCopiesProgress.update(res);
2047 oncomplete: function() {
2048 self.drawCopies(liId, true /* force_fetch */);
2049 openils.Util.hide("acq-lit-update-copies-progress");
2055 var dfa_list = this._virtDfaCountsAsList();
2056 if (dfa_list.length > 0) {
2057 fieldmapper.standardRequest(
2059 "open-ils.acq.distribution_formula.record_application"],
2062 "params": [openils.User.authtoken, dfa_list, liId],
2063 "onresponse": function(r) {
2064 var res = openils.Util.readResponse(r);
2065 if (res && res.length < dfa_list.length)
2066 alert(localeStrings.DFA_NOT_ALL);
2070 this.virtDfaCounts = {};
2074 this._updateCreatePoPrepayCheckbox = function(prepay) {
2075 var prepay = openils.Util.isTrue(prepay);
2076 this._prepayRequiredByVendor = prepay;
2077 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
2080 this._confirmPoPrepaySituation = function() {
2081 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
2082 if (want_prepay != this._prepayRequiredByVendor) {
2085 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
2086 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
2093 this.applySelectedLiAction = function(action) {
2097 case 'delete_selected':
2098 this._deleteLiList(self.getSelected());
2101 case 'create_order':
2102 this._loadPOSelect();
2103 acqLitPoCreateDialog.show();
2106 case 'save_picklist':
2107 acqLitSavePlDialog.show();
2110 case 'selector_ready':
2112 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
2113 acqLitChangeLiStateDialog.show();
2121 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
2124 case 'batch_create_invoice':
2125 this.batchCreateInvoice();
2128 case 'batch_link_invoice':
2129 this.batchLinkInvoice();
2136 case 'rollback_receive_po':
2137 this.rollbackPoReceive();
2140 case 'create_assets':
2141 this.showAssetCreator();
2144 case 'export_attr_list':
2145 this.chooseExportAttr();
2148 case 'batch_apply_funds':
2149 this.applyBatchLiFunds();
2152 case 'add_brief_record':
2154 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
2156 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
2160 case "cancel_lineitems":
2161 this.maybeCancelLineitems();
2164 case "change_claim_policy":
2165 var li_list = this.getSelected();
2166 this.claimPolicyPicker.attr("value", null);
2167 liClaimPolicyDialog.show();
2168 liClaimPolicySave.onClick = function() {
2169 self.changeClaimPolicy(
2171 self.claimPolicyPicker.attr("value"),
2175 self.setClaimPolicyControl(li);
2176 self.reconsiderClaimControl(li);
2179 liClaimPolicyDialog.hide();
2187 this.changeClaimPolicy = function(li_list, value, callback) {
2189 function(li) { li.claim_policy(value); }
2191 fieldmapper.standardRequest(
2192 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
2193 "params": [openils.User.authtoken, li_list],
2195 "oncomplete": function(r) {
2196 r = openils.Util.readResponse(r);
2197 if (callback) callback(r);
2203 this.showAssetCreator = function(onAssetsCreated) {
2204 if(!this.isPO) return;
2207 // first, let's see if this PO has any LI's that need to be merged/imported
2208 self.pcrud.search('jub', {purchase_order : this.isPO, eg_bib_id : null}, {
2210 oncomplete : function(r) {
2211 var resp = openils.Util.readResponse(r);
2212 if (resp && resp.length) {
2213 // PO has some non-linked jubs.
2215 self.show('asset-creator');
2216 if(!self.vlAgent.loaded)
2217 self.vlAgent.init();
2219 dojo.connect(assetCreatorButton, 'onClick',
2220 function() { self.createAssets(onAssetsCreated) });
2224 // all jubs linked, move on to asset creation
2225 self.createAssets(onAssetsCreated, true);
2231 this.createAssets = function(onAssetsCreated, noVl) {
2232 this.show('acq-lit-progress-numbers');
2234 var vlArgs = (noVl) ? {} : {vandelay : this.vlAgent.values()};
2235 fieldmapper.standardRequest(
2236 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
2238 params: [this.authtoken, this.isPO, vlArgs],
2239 onresponse: function(r) {
2240 var resp = openils.Util.readResponse(r);
2241 self._updateProgressNumbers(resp, !Boolean(onAssetsCreated), onAssetsCreated);
2247 this.maybeCancelLineitems = function() {
2248 openils.Util.show("acq-lit-cancel-reason", "inline");
2249 if (!acqLitCancelLineitemsButton._prepared) {
2250 var widget = new openils.widget.AutoFieldWidget({
2251 "fmField": "cancel_reason",
2253 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
2254 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2259 acqLitCancelLineitemsButton.onClick = function() {
2260 if (w.attr("value")) {
2261 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
2262 self._cancelLineitems(w.attr("value"));
2264 openils.Util.hide("acq-lit-cancel-reason");
2267 acqLitCancelLineitemsButton._prepared = true;
2273 this._cancelLineitems = function(reason) {
2274 var id_list = this.getSelected().map(function(o) { return o.id(); });
2275 fieldmapper.standardRequest(
2276 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
2277 "params": [openils.User.authtoken, id_list, reason],
2279 "onresponse": function(r) {
2280 if (r = openils.Util.readResponse(r)) {
2282 for (var id in r.li) {
2283 self.liCache[id].state(r.li[id].state);
2284 self.liCache[id].cancel_reason(
2285 r.li[id].cancel_reason
2287 self.updateLiState(self.liCache[id]);
2290 if (r.lid && self.copyCache) {
2291 for (var id in r.lid) {
2292 if (self.copyCache[id]) {
2293 self.copyCache[id].cancel_reason(
2294 r.lid[id].cancel_reason
2296 self.updateLidState(self.copyCache[id]);
2306 this.chooseExportAttr = function() {
2307 if (!acqLitExportAttrSelector._li_setup) {
2309 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
2311 "data": acqlimad.toStoreData(
2313 "acqlimad", {"code": li_exportable_attrs}
2318 acqLitExportAttrSelector.setValue();
2319 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
2320 acqLitExportAttrSelector._li_setup = true;
2322 openils.Util.show("acq-lit-export-attr-holder", "inline");
2325 this.exportAttrList = function() {
2326 var attr_def = acqLitExportAttrSelector.item;
2327 var li_list = this.getSelected();
2328 var value_list = li_list.map(
2330 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2331 attr_def.code, "lineitem_marc_attr_definition"
2334 ).filter(function(attr) { return Boolean(attr); });
2336 if (value_list.length > 0) {
2337 if (value_list.length < li_list.length) {
2339 dojo.string.substitute(
2340 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
2347 openils.XUL.contentToFileSaveDialog(
2348 value_list.join("\n"),
2349 localeStrings.EXPORT_SAVE_DIALOG_TITLE
2355 alert(dojo.string.substitute(
2356 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
2360 openils.Util.hide("acq-lit-export-attr-holder");
2363 this.printPO = function() {
2364 if(!this.isPO) return;
2365 progressDialog.show(true);
2366 fieldmapper.standardRequest(
2367 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
2369 params: [this.authtoken, this.isPO, 'html'],
2370 oncomplete: function(r) {
2371 progressDialog.hide();
2372 var evt = openils.Util.readResponse(r);
2373 if(evt && evt.template_output()) {
2374 openils.Util.printHtmlString(evt.template_output().data());
2381 this.batchCreateInvoice = function() {
2382 var liIds = this.getSelected(false, null, true /* id_list */)
2383 if (!liIds.length) return;
2384 var path = oilsBasePath + '/acq/invoice/view?create=1';
2385 dojo.forEach(liIds, function(li, idx) { path += '&attach_li=' + li });
2386 location.href = path;
2389 this.batchLinkInvoice = function(create) {
2390 var liIds = this.getSelected(false, null, true /* id_list */)
2391 if (!liIds.length) return;
2392 if (!self.invoiceLinkDialogManager) {
2393 self.invoiceLinkDialogManager =
2394 new InvoiceLinkDialogManager("li");
2396 self.invoiceLinkDialogManager.target = liIds;
2397 acqLitLinkInvoiceDialog.show();
2400 this.receivePO = function() {
2401 if (!this.isPO) return;
2403 for (var id in this.liCache) {
2404 /* assumption: liCache reflects exactly the
2405 * set of LIs that belong to our PO */
2406 if (this.liCache[id].state() != "received" &&
2407 !this.checkLiAlerts(id)) return;
2410 this.show('acq-lit-progress-numbers');
2412 fieldmapper.standardRequest(
2413 ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
2415 params: [this.authtoken, this.isPO],
2416 onresponse : function(r) {
2417 var resp = openils.Util.readResponse(r);
2418 self._updateProgressNumbers(resp, true);
2424 this.issueReceive = function(obj, rollback) {
2426 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
2428 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
2430 progressDialog.show(true);
2431 fieldmapper.standardRequest(
2432 ["open-ils.acq", method], {
2434 "params": [this.authtoken, obj.id()],
2435 "onresponse": function(r) {
2436 if (r = openils.Util.readResponse(r)) {
2437 self.fetchClaimInfo(
2438 part == "lineitem" ? obj.id() : obj.lineitem(),
2440 function() { self.handleReceive(r); }
2442 progressDialog.hide();
2450 * Handles the responses from receive and rollback ML calls.
2452 this.handleReceive = function(resp) {
2455 for (var li_id in resp.li) {
2456 for (var key in resp.li[li_id])
2457 self.liCache[li_id][key](resp.li[li_id][key]);
2458 self.updateLiState(self.liCache[li_id]);
2462 if (typeof(self.poUpdateCallback) == "function")
2463 self.poUpdateCallback(resp.po);
2466 for (var lid_id in resp.lid) {
2467 for (var key in resp.lid[lid_id])
2468 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
2469 self.updateLidState(self.copyCache[lid_id]);
2475 this.rollbackPoReceive = function() {
2476 if(!this.isPO) return;
2477 if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
2478 this.show('acq-lit-progress-numbers');
2480 fieldmapper.standardRequest(
2481 ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
2483 params: [this.authtoken, this.isPO],
2484 onresponse : function(r) {
2485 var resp = openils.Util.readResponse(r);
2486 self._updateProgressNumbers(resp, true);
2492 this._updateProgressNumbers = function(resp, reloadOnComplete, onComplete) {
2493 this.vlAgent.handleResponse(resp,
2494 function(resp, res) {
2495 if(reloadOnComplete)
2496 location.href = location.href;
2498 onComplete(resp, res);
2504 this._createPO = function(fields) {
2505 var wantall = (fields.create_from == "all");
2507 /* If we're a picklist or purchase order already and the user wants
2508 * all lineitems, we might have pages' worth of lineitems haven't all
2509 * been loaded yet, so getSelected() won't find them. The server,
2510 * however, should know about all our lineitems, so let's ask the
2511 * server for a complete list.
2516 true, function(list) {
2517 self._createPOFromLineitems(fields, list);
2518 }, /* id_list */ true
2521 this._createPOFromLineitems(fields, this.getSelected(false, null, true /* id_list */));
2525 this._createPOFromLineitems = function(fields, selected) {
2526 if (selected.length == 0) return;
2529 var po = new fieldmapper.acqpo();
2530 po.provider(this.createPoProviderSelector.attr("value"));
2531 po.ordering_agency(this.createPoAgencySelector.attr("value"));
2532 po.prepayment_required(fields.prepayment_required[0] ? true : false);
2534 // if we're creating assets, delay the asset creation
2535 // until after the PO is created. This will allow us to
2536 // use showAssetCreator() directly.
2538 fieldmapper.standardRequest(
2539 ["open-ils.acq", "open-ils.acq.purchase_order.create"],
2542 openils.User.authtoken,
2543 po, {lineitems : selected}
2545 onresponse : function(r) {
2546 var resp = openils.Util.readResponse(r);
2547 if (resp.complete) {
2548 // self.isPO is needed for showAssetCreator();
2549 self.isPO = resp.purchase_order.id();
2550 var redir = oilsBasePath + "/acq/po/view/" + self.isPO;
2551 if (fields.create_assets[0]) {
2552 self.showAssetCreator(
2553 function() {location.href = redir}
2556 location.href = redir;
2565 this.batchFundWidget = null;
2567 this.applyBatchLiFunds = function() {
2569 var liIds = this.getSelected().map(function(li) { return li.id(); });
2570 if(liIds.length == 0) return; // warn?
2573 batchFundUpdateDialog.show();
2575 if(!this.batchFundWidget) {
2576 this.batchFundWidget = new openils.widget.AutoFieldWidget({
2578 selfReference : true,
2579 labelFormat : fundLabelFormat,
2580 searchFormat : fundSearchFormat,
2581 searchFilter : {"active": "t"},
2582 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
2583 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2584 dijitArgs : { "required": true, "labelType": "html" },
2587 this.batchFundWidget.build();
2590 dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
2591 dojo.connect(batchFundUpdateSubmit, 'onClick',
2594 // TODO: call .dry_run first to test thresholds
2595 fieldmapper.standardRequest(
2596 ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
2599 openils.User.authtoken,
2601 self.batchFundWidget.widget.attr('value')
2603 oncomplete : function(r) {
2604 var resp = openils.Util.readResponse(r);
2606 location.href = location.href;
2615 this._deleteLiList = function(list, idx) {
2616 if(idx == null) idx = 0;
2617 if(idx >= list.length) return;
2622 if (this.isPO && (li.state() == "on-order" || li.state() == "received")) {
2623 /* It makes little sense to delete a lineitem from a PO that has
2624 * already been marked 'on-order'. Especially if EDI is in use,
2625 * such a purchase order will probably have already been shipped
2626 * off to a vendor, and mucking with it at this point could leave
2627 * your data in a bad state that doesn't jive with reality.
2629 * I could see making this restriction even firmer.
2631 * I could also see adjusting the li state comparisons, extending
2632 * the comparison to the PO's state, and/or providing functions
2633 * that house the logic for comparing states in a single location.
2635 * Yes, this will be really annoying if you have selected a lot
2636 * of lineitems to cancel that have been ordered. You'll get a
2637 * confirm dialog for each one.
2640 if (!confirm(localeStrings.DEL_LI_FROM_PO)) {
2641 self._deleteLiList(list, ++idx); /* move on to next in list */
2646 fieldmapper.standardRequest(
2648 this.isPO ? 'open-ils.acq.purchase_order.lineitem.delete' : 'open-ils.acq.picklist.lineitem.delete'],
2650 params: [openils.User.authtoken, liId],
2651 oncomplete: function(r) {
2652 self.removeLineitem(liId);
2653 self._deleteLiList(list, ++idx);
2659 this.editOrderMarc = function(li) {
2661 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
2662 to true in about:config */
2664 if(openils.XUL.isXUL()) {
2665 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
2667 win = window.open('/xul/server/cat/marcedit.xul');
2671 record : {marc : li.marc(), "rtype": "bre"},
2673 label: 'Save Record', // XXX I18N
2674 func: function(xmlString) {
2676 fieldmapper.standardRequest(
2677 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
2679 params: [openils.User.authtoken, li],
2680 oncomplete: function(r) {
2681 openils.Util.readResponse(r);
2683 self.drawInfo(li.id())
2689 'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
2690 'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
2694 this._savePl = function(values) {
2696 (values.which == 'all'),
2697 function(list) { self._savePlFromLineitems(values, list); }
2701 this._savePlFromLineitems = function(values, selected) {
2702 openils.Util.show("acq-lit-generic-progress");
2704 if(values.new_name) {
2705 openils.acq.Picklist.create(
2706 {name: values.new_name},
2712 oilsBasePath + "/acq/picklist/view/" + id;
2717 } else if(values.existing_pl) {
2718 // update lineitems to use an existing picklist
2720 values.existing_pl, selected, 0,
2723 oilsBasePath + "/acq/picklist/view/" +
2730 this._updateLiState = function(values, state) {
2731 progressDialog.show(true);
2733 (values.which == 'all'),
2735 self._updateLiStateFromLineitems(values, state, list);
2740 this._updateLiStateFromLineitems = function(values, state, selected) {
2741 if(!selected.length) return;
2742 dojo.forEach(selected, function(li) {li.state(state);});
2743 self._updateLiList(null, selected, 0,
2744 // TODO consider inline updates for efficiency
2745 function() { location.href = location.href }
2749 this._updateLiList = function(pl, list, idx, oncomplete) {
2750 if(idx >= list.length) return oncomplete();
2752 if(pl != null) li.picklist(pl);
2753 litGenericProgress.update({maximum: list.length, progress: idx});
2754 new openils.acq.Lineitem({lineitem:li}).update(
2756 self._updateLiList(pl, list, ++idx, oncomplete);
2761 this._loadPOSelect = function() {
2762 if (!this.createPoProviderSelector) {
2763 var widget = new openils.widget.AutoFieldWidget({
2764 "fmField": "provider",
2766 "searchFilter": {"active": "t"},
2767 "parentNode": dojo.byId("acq-lit-po-provider"),
2769 "onChange": function() {
2771 self._updateCreatePoPrepayCheckbox(
2772 this.item.prepayment_required()
2778 widget.build(function(w) { self.createPoProviderSelector = w; });
2781 if (!this.createPoAgencySelector) {
2782 var widget = new openils.widget.AutoFieldWidget({
2783 "fmField": "ordering_agency",
2785 "parentNode": dojo.byId("acq-lit-po-agency"),
2786 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2788 widget.build(function(w) { self.createPoAgencySelector = w; });
2792 this.showRealCopyEditUI = function(li) {
2797 this._fetchLineitem(li.id(),
2799 li = self.liCache[li.id()] = fullLi;
2803 id : li.lineitem_details().map(
2804 function(item) { return item.eg_copy_id() }
2808 oncomplete : function(r) {
2810 var r_list = openils.Util.readResponse( r );
2811 for (var i = 0; i < r_list.length; i++) {
2812 var copy = r_list[i];
2813 var volId = copy.call_number();
2814 var volume = self.volCache[volId];
2816 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2818 copy.call_number(volume);
2819 copyList.push(copy);
2822 xulG.volume_item_creator( { 'existing_copies' : copyList } );
2825 alert('error in oncomplete: ' + E);
2834 this.drawBibFinder = function(li) {
2837 var liWrapper = new openils.acq.Lineitem({lineitem:li});
2840 ['isbn', 'upc', 'issn', 'title', 'author'],
2842 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
2844 if(field == 'title' || field == 'author') {
2845 query += field +':' + val + ' ';
2847 query += 'identifier|' + field + ':' + val + ' ';
2854 oilsBasePath + '/acq/lineitem/findbib?query=' + escape(query),
2855 '', 'resizable,scrollbars=1');
2857 win.window.recordFound = function(bibId) {
2860 var attrs = li.attributes();
2861 li.attributes(null);
2862 li.eg_bib_id(bibId);
2864 fieldmapper.standardRequest(
2865 ["open-ils.acq", "open-ils.acq.lineitem.update"],
2867 "params": [openils.User.authtoken, li],
2869 "oncomplete": function(r) {
2870 if(openils.Util.readResponse(r)) {
2871 location.href = location.href;