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());
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());
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(xulG.urls.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 openils.acq.Lineitem.fetchAndRender(liId, {},
1125 function(li, html) {
1126 dojo.byId('acq-lit-copies-li-summary').innerHTML = html;
1130 this.show('copies');
1132 this.copyCache = {};
1133 this.copyWidgetCache = {};
1134 this.oldCopyWidgetCache = {};
1135 this.virtDfaCounts = {};
1136 this.realDfaCache = {};
1139 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
1140 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
1141 acqLitCopyCountInput.attr('value', '0');
1143 while(this.copyTbody.childNodes[0])
1144 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
1146 this._drawBatchCopyWidgets();
1148 this._drawDistribApplied(liId);
1150 this._fetchDistribFormulas(
1152 openils.acq.Lineitem.fetchAttrDefs(
1154 self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch);
1161 this._saveDistribAppliedTemplates = function() {
1162 if (!this._appliedDistribTemplate) {
1163 this._appliedDistribTemplate =
1164 dojo.byId("acq-lit-distrib-applied-tbody").
1165 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
1166 dojo.attr(this._appliedDistribTemplate, "id");
1170 this._drawDistribApplied = function(liId) {
1171 /* Build this table while hidden to prevent rendering artifacts */
1172 openils.Util.hide("acq-lit-distrib-applied-tbody");
1174 this._saveDistribAppliedTemplates();
1176 /* Remove any rows in the table from previous populations */
1177 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
1178 forEach(dojo.destroy);
1180 /* Unregister all dijits previously created (for some reason this isn't
1181 * covered by the above destroy calls). */
1182 dijit.registry.forEach(
1183 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
1186 /* Populate the table with our liId */
1188 fieldmapper.standardRequest(
1190 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
1193 "params": [self.authtoken, liId],
1194 "onresponse": function(r) {
1195 var dfa = openils.Util.readResponse(r);
1198 self.realDfaCache[dfa.id()] = dfa;
1199 self._drawDistribAppliedUnit(dfa);
1202 "oncomplete": function() {
1203 /* Reveal built table */
1206 "acq-lit-distrib-applied-tbody", "table-row-group"
1214 this._drawDistribAppliedUnit = function(dfa) {
1215 var new_row = false;
1216 var row = dojo.query(
1217 'tr[formula="' + dfa.formula().id() + '"]',
1218 "acq-lit-distrib-applied-tbody"
1223 row = dojo.clone(this._appliedDistribTemplate);
1224 dojo.attr(row, "formula", dfa.formula().id());
1225 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
1228 var td = dojo.query("td", row)[0];
1230 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1231 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1234 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1236 new dijit.form.Button(
1238 "onClick": function() {
1239 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1240 self.deleteDfa(dfa);
1243 /* XXX I /cannot/ make the following work in as a CSS class
1244 * for some reason. So frustrating... */
1245 "style": function(id) {
1247 "font-weight: bold; color: #c00;" :
1249 }(dfa.id()) + "margin: 0 6px;display: inline;"
1250 }, "dfa-button-" + dfa.id()
1254 "connectId": ["dfa-button-" + dfa.id()],
1255 "label": dojo.string.substitute(
1256 localeStrings.DFA_TIP, dfa.id() > 0 ? [
1257 openils.User.formalName(dfa.creator()),
1258 dojo.date.locale.format(
1259 dojo.date.stamp.fromISOString(dfa.create_time()),
1260 {"formatLength":"short"}
1262 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
1264 }, "dfa-tip-" + dfa.id()
1268 this.deleteDfa = function(dfa) {
1269 if (dfa.id() > 0) { /* real */
1270 this.pcrud.eliminate(
1273 "oncomplete": function() {
1274 self._removeDistribApplied(dfa.id());
1275 delete self.realDfaCache[dfa.id()];
1279 } else { /* virtual */
1280 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
1281 this.virtDfaCounts[dfa.formula().id()] = 0;
1282 /* hasn't been saved yet, so no need to do anything server side */
1283 this._removeDistribApplied(dfa.id());
1288 this._removeDistribApplied = function(dfaId) {
1289 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
1290 dijit.registry.forEach(
1291 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
1293 this._removeDistribAppliedEmptyRows();
1296 this._removeAllDistribAppliedVirtual = function() {
1297 /* Unregister dijits */
1298 dijit.registry.forEach(
1299 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
1301 this._removeDistribAppliedEmptyRows();
1304 this._removeDistribAppliedEmptyRows = function() {
1305 /* Remove any rows with no DFA at all */
1306 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
1308 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
1314 * Insert a new row into the distribution formula selection form
1316 this._addDistribFormulaRow = function() {
1319 if (!self.distribForms) {
1320 // no formulas, hide the form
1321 openils.Util.hide('acq-lit-distrib-formula-table');
1325 if(!this.distribFormulaTemplate)
1326 this.distribFormulaTemplate =
1327 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
1329 var row = this.distribFormulaTemplate.cloneNode(true);
1330 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
1332 this.dfSelector = new dijit.form.FilteringSelect(
1333 {"labelAttr": "dynLabel", "labelType": "html"},
1334 nodeByName("selector", row)
1336 this._updateFormulaStore();
1337 this.dfSelector.fetchProperties =
1338 {"sort": [{"attribute": "use_count", "descending": true}]};
1340 var apply = new dijit.form.Button(
1341 {"label": localeStrings.APPLY},
1342 nodeByName('set_button', row)
1345 var reset = new dijit.form.Button(
1346 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
1347 nodeByName("reset_button", row)
1350 dojo.connect(apply, 'onClick',
1352 var form_id = self.dfSelector.attr("value");
1353 if(!form_id) return;
1354 self._applyDistribFormula(form_id);
1355 reset.attr("disabled", false);
1359 dojo.connect(reset, 'onClick',
1361 self.restoreCopyFieldsBeforeDF();
1362 self.virtDfaCounts = {};
1363 self.virtDfaId = -1;
1365 self._updateFormulaStore();
1366 self._removeAllDistribAppliedVirtual();
1367 reset.attr("disabled", "true");
1374 * Applies a distrib formula to the current set of copies
1376 this._applyDistribFormula = function(formula) {
1377 if(!formula) return;
1379 formula = this.distribForms.filter(
1380 function(form) { return form.id() == formula; }
1383 var copyRows = dojo.query('tr', self.copyTbody);
1385 if (this.dfeOffset >= copyRows.length) {
1386 alert(localeStrings.OUT_OF_COPIES);
1390 var entries_applied = 0;
1392 var rowIndex = this.dfeOffset;
1393 rowIndex < copyRows.length;
1397 var row = copyRows[rowIndex];
1398 var copy_id = row.getAttribute('copy_id');
1399 var copyWidgets = this.copyWidgetCache[copy_id];
1400 var entryIndex = this.dfeOffset;
1403 // find the correct entry for the current row
1404 dojo.forEach(formula.entries(),
1407 entryIndex += e.item_count();
1408 if(entryIndex > rowIndex)
1416 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
1417 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
1420 this.saveCopyFieldsBeforeDF(copy_id);
1421 this._copy_fields_for_acqdf.forEach(
1423 if(entry[field]()) {
1424 copyWidgets[field].attr('value', (entry[field]()));
1431 if (entries_applied) {
1432 this.virtDfaCounts[formula.id()] =
1433 ++(this.virtDfaCounts[formula.id()]) || 1;
1434 this._updateFormulaStore();
1435 this._drawDistribAppliedUnit(
1437 var dfa = new acqdfa();
1438 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
1441 this.dfeOffset += entries_applied;
1446 * This function updates the DF store for the dropdown so that use_counts
1447 * can reflect DF applications from this session before they're saved
1450 this._updateFormulaStore = function() {
1451 this.dfSelector.store = new dojo.data.ItemFileReadStore(
1453 "data": self._labelFormulasWithCounts(
1454 acqdf.toStoreData(self.distribForms)
1460 this.saveCopyFieldsBeforeDF = function(copy_id) {
1462 if (!this.oldCopyWidgetCache[copy_id]) {
1463 var copyWidgets = this.copyWidgetCache[copy_id];
1465 this.oldCopyWidgetCache[copy_id] = {};
1466 this._copy_fields_for_acqdf.forEach(
1468 self.oldCopyWidgetCache[copy_id][f] =
1469 copyWidgets[f].attr("value");
1475 this.restoreCopyFieldsBeforeDF = function() {
1477 for (var copy_id in this.oldCopyWidgetCache) {
1478 this._copy_fields_for_acqdf.forEach(
1480 self.copyWidgetCache[copy_id][f].attr(
1481 "value", self.oldCopyWidgetCache[copy_id][f]
1488 this._labelFormulasWithCounts = function(store_data) {
1489 for (var key in store_data.items) {
1490 var obj = store_data.items[key];
1491 obj.use_count = Number(obj.use_count); /* needed for sorting */
1493 if (this.virtDfaCounts[obj.id])
1494 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
1496 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
1497 obj.use_count + "]</span> " + obj.name;
1503 * This method formerly would not refetch the DF formulas if they'd been
1504 * loaded already, but now it always re-fetches, since use_count changes.
1506 /** TODO: port distrib-formula selector to autofieldwidget+pcrud/dojo store */
1507 this._fetchDistribFormulas = function(onload) {
1508 fieldmapper.standardRequest(
1510 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
1513 "params": [openils.User.authtoken, 0, 500],
1514 "oncomplete": function(r) {
1515 self.distribForms = openils.Util.readResponse(r);
1516 if(!self.distribForms || self.distribForms.length == 0) {
1517 self.distribForms = [];
1519 self._addDistribFormulaRow();
1526 this._drawBatchCopyWidgets = function() {
1527 var row = this.copyBatchRow;
1528 dojo.forEach(liDetailBatchFields,
1530 if(self.copyBatchRowDrawn) {
1531 self.copyBatchWidgets[field].attr('value', null);
1533 var widget = new openils.widget.AutoFieldWidget({
1536 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1537 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1538 searchFilter : (field == 'fund') ? {"active": "t"} : null,
1539 parentNode : dojo.query('[name='+field+']', row)[0],
1540 orgLimitPerms : ['CREATE_PICKLIST'],
1543 "labelType": (field == "fund") ? "html" : null
1545 noCache: (field == "fund"),
1550 if (field == "fund" && w.store)
1551 self._ensureCSSFundClasses(w.store);
1552 self.copyBatchWidgets[field] = w;
1555 if (field == "fund") {
1557 widget.widget, "onChange", function(val) {
1558 self._updateFundSelectorStyle(widget, val);
1565 this.copyBatchRowDrawn = true;
1568 this.batchCopyUpdate = function() {
1570 for(var k in this.copyWidgetCache) {
1571 var cache = this.copyWidgetCache[k];
1572 dojo.forEach(liDetailBatchFields, function(f) {
1573 var newval = self.copyBatchWidgets[f].attr('value');
1574 if(newval) cache[f].attr('value', newval);
1579 this._drawCopies = function(li) {
1582 // this button sets the total number of copies for a given lineitem
1583 acqLitAddCopyCount.onClick = function() {
1584 var count = acqLitCopyCountInput.attr('value');
1587 while(self.copyCount() < count)
1590 // delete rows if necessary
1591 var diff = self.copyCount() - count;
1593 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
1594 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
1595 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
1597 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1603 if(li.lineitem_details().length > 0) {
1604 dojo.forEach(li.lineitem_details(),
1606 self.addCopy(li, copy);
1614 this.copyCount = function() {
1616 for(var id in this.copyCache) {
1617 if(!this.copyCache[id].isdeleted())
1623 this.virtCopyId = -1;
1624 this.addCopy = function(li, copy) {
1625 var row = this.copyRow.cloneNode(true);
1626 this.copyTbody.appendChild(row);
1630 copy = new fieldmapper.acqlid();
1632 copy.id(this.virtCopyId--);
1633 copy.lineitem(li.id());
1636 this.copyCache[copy.id()] = copy;
1637 row.setAttribute('copy_id', copy.id());
1638 self.copyWidgetCache[copy.id()] = {};
1640 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1642 var rcvr = copy.receiver();
1644 if (!userCache[rcvr]) {
1645 if(rcvr == openils.User.user.id()) {
1646 userCache[rcvr] = openils.User.user;
1648 userCache[rcvr] = fieldmapper.standardRequest(
1649 ['open-ils.actor', 'open-ils.actor.user.retrieve'],
1650 {params: [openils.User.authtoken, rcvr]}
1654 dojo.query('[name=receiver]', row)[0].innerHTML = userCache[rcvr].usrname();
1657 dojo.forEach(liDetailFields,
1660 if (field == "fund") {
1661 searchFilter = (copy.fund() ?
1662 {"-or": {"active": "t", "id": copy.fund()}} :
1665 searchFilter = null;
1668 var readOnly = false;
1670 // TODO: Add support for changing the owning_lib after real copies have been made.
1671 // owning_lib is order data as much as its item data
1672 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
1676 // TODO: add support for changing the fund after debits have been created
1677 // Note: invoicing allows the change
1678 if(copy.fund_debit() && field == 'fund') {
1683 var widget = new openils.widget.AutoFieldWidget({
1686 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1687 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1688 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1689 searchFilter : searchFilter,
1690 noCache: (field == "fund"),
1692 parentNode : dojo.query('[name='+field+']', row)[0],
1693 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
1694 readOnly : readOnly,
1695 orgDefaultsToWs : true
1699 // make sure we capture the value from any async widgets
1702 if (field == "fund" && w.store)
1703 self._ensureCSSFundClasses(w.store);
1706 copy[field](ww.getFormattedValue())
1708 self.copyWidgetCache[copy.id()][field] = w;
1710 dojo.connect(w, 'onChange',
1712 if (field == "fund")
1713 self._updateFundSelectorStyle(widget, val);
1715 if (!readOnly && (copy.isnew() || val != copy[field]())) {
1716 // prevent setting ischanged() automatically on widget load for existing copies
1717 copy[field](widget.getFormattedValue())
1718 copy.ischanged(true);
1727 this.updateLidState(copy, row);
1730 this._ensureCSSFundClass = function(id) {
1731 if (!this.fundStyleSheet) {
1733 "style", {"type": "text/css"},
1734 document.getElementsByTagName("head")[0], "last"
1736 this.fundStyleSheet = document.styleSheets[
1737 document.styleSheets.length - 1
1741 var cn = "fund_" + id;
1742 if (!this.haveFundClass[cn]) {
1743 fieldmapper.standardRequest(
1744 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
1746 "params": [openils.User.authtoken, id],
1748 "oncomplete": function(r) {
1749 r = openils.Util.readResponse(r);
1750 self.fundBalanceState[id] = r;
1752 if (r[0] /* stop */)
1753 style = fundStyles.stop;
1754 else if (r[1] /* warning */)
1755 style = fundStyles.warning;
1756 self.fundStyleSheet.insertRule(
1757 "." + cn + " { " + style + " }",
1758 self.fundStyleSheet.cssRules.length
1760 self.haveFundClass[cn] = true;
1767 this._ensureCSSFundClasses = function(store) {
1769 "query": {"id": "*"},
1770 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
1774 this._updateFundSelectorStyle = function(widget, fund_id) {
1775 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
1776 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
1779 this.updateLidState = function(copy, row) {
1782 if (typeof(row) == "undefined") {
1783 row = dojo.query('tr[copy_id="' + copy.id() + '"]', this.copyTbody)[0];
1787 var recv_link = nodeByName("receive", row);
1788 var unrecv_link = nodeByName("unreceive", row);
1789 var del_link = nodeByName("delete", row);
1790 var cxl_link = nodeByName("cancel", row);
1791 var claim_link = nodeByName("claim", row);
1792 var cxl_reason_link = nodeByName("cancel_reason", row);
1794 // by default, hide all the actions
1795 openils.Util.hide(del_link.parentNode);
1796 openils.Util.hide(recv_link);
1797 openils.Util.hide(unrecv_link);
1798 openils.Util.hide(cxl_link);
1799 openils.Util.hide(claim_link);
1800 openils.Util.hide(cxl_reason_link);
1802 if (copy.id() > 0) { // real copies (LIDs)
1804 if (copy.cancel_reason()) {
1806 /* --------- cancelled -------------------------- */
1808 /* XXX the following may leak memory in a long lived table:
1809 * dijits may not get destroyed... not positive. revisit. */
1810 var holds_reason = dojo.create(
1812 "style": "border-bottom: 1px dashed #000;",
1813 "innerHTML": "Cancelled" /* XXX [sic] and i18n */
1814 }, cxl_reason_link, "only"
1818 "label": "<em>" + copy.cancel_reason().label() +
1819 "</em><br />" + copy.cancel_reason().description(),
1820 "connectId": [holds_reason]
1821 }, dojo.create("span", null, cxl_reason_link, "last")
1823 openils.Util.show(cxl_reason_link, "inline");
1825 } else if (copy.recv_time()) {
1827 /* --------- received -------------------------- */
1829 openils.Util.show(unrecv_link, "inline");
1830 unrecv_link.onclick = function() {
1831 if (confirm(localeStrings.UNRECEIVE_LID))
1832 self.issueReceive(copy, /* rollback */ true);
1835 } else if (this.liCache[copy.lineitem()].state() == 'on-order') {
1837 /* --------- on order -------------------------- */
1839 openils.Util.show(recv_link, 'inline');
1840 openils.Util.show(cxl_link, "inline");
1842 recv_link.onclick = function() {
1843 if (self.checkLiAlerts(copy.lineitem()))
1844 self.issueReceive(copy);
1847 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
1851 /* --------- pre-order copies -------------------------- */
1853 del_link.onclick = function() { self.deleteCopy(row) };
1854 openils.Util.show(del_link.parentNode);
1860 /* --------- virtual copies -------------------------- */
1862 del_link.onclick = function() { self.deleteCopy(row) };
1863 openils.Util.show(del_link.parentNode);
1867 this.cancelLid = function(lid_id) {
1868 lidCancelDialog._lid_id = lid_id;
1869 openils.Util.show(lidCancelDialog.domNode.parentNode);
1870 lidCancelDialog.show();
1871 if (!lidCancelDialog._prepared) {
1872 var widget = new openils.widget.AutoFieldWidget({
1873 "fmField": "cancel_reason",
1874 "fmClass": "acqlid",
1875 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
1876 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1881 acqLidCancelButton.onClick = function() {
1882 if (w.attr("value")) {
1883 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
1885 lidCancelDialog._lid_id,
1889 lidCancelDialog.hide();
1892 lidCancelDialog._prepared = true;
1898 this._cancelLid = function(lid_id, reason) {
1899 fieldmapper.standardRequest(
1900 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
1901 "params": [openils.User.authtoken, lid_id, reason],
1903 "onresponse": function(r) {
1904 if (r = openils.Util.readResponse(r)) {
1906 for (var id in r.lid) {
1907 /* actually this should only iterate once */
1908 self.copyCache[id].cancel_reason(
1909 r.lid[id].cancel_reason
1911 self.updateLidState(self.copyCache[id]);
1920 this._confirmAlert = function(li, lin) {
1922 dojo.string.substitute(
1923 localeStrings.CONFIRM_LI_ALERT, [
1924 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1925 "title", "lineitem_marc_attr_definition"
1927 /* XXX it's really better add a parameter and to adjust
1928 * the format string rather than do this concatenation
1929 * here, but if someone wants this for 2.2 in a hurry,
1930 * we can sidestep the problem of updating the strings
1931 * while the translators are working. */
1933 aou.findOrgUnit(lin.alert_text().owning_lib()).shortname() +
1935 lin.alert_text().code()
1937 lin.alert_text().description() || "",
1944 this.checkLiAlerts = function(li_id) {
1945 var li = this.liCache[li_id];
1947 var alert_notes = li.lineitem_notes().filter(
1948 function(o) { return Boolean(o.alert_text()); }
1951 /* this is _intentionally_ not done in a call to forEach() ... */
1952 for (var i = 0; i < alert_notes.length; i++) {
1953 if (this.noteAcks[alert_notes[i].id()])
1955 else if (!this._confirmAlert(li, alert_notes[i]))
1958 this.noteAcks[alert_notes[i].id()] = true;
1964 this.deleteCopy = function(row) {
1965 var copy = this.copyCache[row.getAttribute('copy_id')];
1966 copy.isdeleted(true);
1968 delete this.copyCache[copy.id()];
1969 this.copyTbody.removeChild(row);
1972 this._virtDfaCountsAsList = function() {
1974 for (var key in this.virtDfaCounts) {
1975 for (var i = 0; i < this.virtDfaCounts[key]; i++)
1981 this.confirmBreachedCopyFunds = function(copies) {
1982 var stop = 0, warning = 0;
1986 var state = self.fundBalanceState[o.fund()];
1987 if (state[0] /* stop */)
1989 else if (state[1] /* warning */)
1996 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
1997 } else if (warning) {
1998 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
2003 this.saveCopyChanges = function(liId) {
2009 for(var id in this.copyCache) {
2010 var c = this.copyCache[id];
2011 if(!c.isdeleted()) total++;
2012 if(c.isnew() || c.ischanged() || c.isdeleted()) {
2013 if(c.id() < 0) c.id(null);
2019 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
2022 if (copies.length > 0) {
2023 if (!this.confirmBreachedCopyFunds(copies))
2026 if (typeof(this._copy_count_cb) == "function")
2027 this._copy_count_cb(liId, total);
2029 openils.Util.show("acq-lit-update-copies-progress");
2030 fieldmapper.standardRequest(
2031 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
2033 params: [openils.User.authtoken, copies],
2034 onresponse: function(r) {
2035 var res = openils.Util.readResponse(r);
2036 litUpdateCopiesProgress.update(res);
2038 oncomplete: function() {
2039 self.drawCopies(liId, true /* force_fetch */);
2040 openils.Util.hide("acq-lit-update-copies-progress");
2046 var dfa_list = this._virtDfaCountsAsList();
2047 if (dfa_list.length > 0) {
2048 fieldmapper.standardRequest(
2050 "open-ils.acq.distribution_formula.record_application"],
2053 "params": [openils.User.authtoken, dfa_list, liId],
2054 "onresponse": function(r) {
2055 var res = openils.Util.readResponse(r);
2056 if (res && res.length < dfa_list.length)
2057 alert(localeStrings.DFA_NOT_ALL);
2061 this.virtDfaCounts = {};
2065 this._updateCreatePoPrepayCheckbox = function(prepay) {
2066 var prepay = openils.Util.isTrue(prepay);
2067 this._prepayRequiredByVendor = prepay;
2068 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
2071 this._confirmPoPrepaySituation = function() {
2072 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
2073 if (want_prepay != this._prepayRequiredByVendor) {
2076 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
2077 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
2084 this.applySelectedLiAction = function(action) {
2088 case 'delete_selected':
2089 this._deleteLiList(self.getSelected());
2092 case 'create_order':
2093 this._loadPOSelect();
2094 acqLitPoCreateDialog.show();
2097 case 'save_picklist':
2098 acqLitSavePlDialog.show();
2101 case 'selector_ready':
2103 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
2104 acqLitChangeLiStateDialog.show();
2112 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
2119 case 'rollback_receive_po':
2120 this.rollbackPoReceive();
2123 case 'create_assets':
2124 this.showAssetCreator();
2127 case 'export_attr_list':
2128 this.chooseExportAttr();
2131 case 'batch_apply_funds':
2132 this.applyBatchLiFunds();
2135 case 'add_brief_record':
2137 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
2139 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
2143 case "cancel_lineitems":
2144 this.maybeCancelLineitems();
2147 case "change_claim_policy":
2148 var li_list = this.getSelected();
2149 this.claimPolicyPicker.attr("value", null);
2150 liClaimPolicyDialog.show();
2151 liClaimPolicySave.onClick = function() {
2152 self.changeClaimPolicy(
2154 self.claimPolicyPicker.attr("value"),
2158 self.setClaimPolicyControl(li);
2159 self.reconsiderClaimControl(li);
2162 liClaimPolicyDialog.hide();
2170 this.changeClaimPolicy = function(li_list, value, callback) {
2172 function(li) { li.claim_policy(value); }
2174 fieldmapper.standardRequest(
2175 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
2176 "params": [openils.User.authtoken, li_list],
2178 "oncomplete": function(r) {
2179 r = openils.Util.readResponse(r);
2180 if (callback) callback(r);
2186 this.showAssetCreator = function(onAssetsCreated) {
2187 if(!this.isPO) return;
2190 // first, let's see if this PO has any LI's that need to be merged/imported
2191 self.pcrud.search('jub', {purchase_order : this.isPO, eg_bib_id : null}, {
2193 oncomplete : function(r) {
2194 var resp = openils.Util.readResponse(r);
2195 if (resp && resp.length) {
2196 // PO has some non-linked jubs.
2198 self.show('asset-creator');
2199 if(!self.vlAgent.loaded)
2200 self.vlAgent.init();
2202 dojo.connect(assetCreatorButton, 'onClick',
2203 function() { self.createAssets(onAssetsCreated) });
2207 // all jubs linked, move on to asset creation
2208 self.createAssets(onAssetsCreated, true);
2214 this.createAssets = function(onAssetsCreated, noVl) {
2215 this.show('acq-lit-progress-numbers');
2217 var vlArgs = (noVl) ? {} : {vandelay : this.vlAgent.values()};
2218 fieldmapper.standardRequest(
2219 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
2221 params: [this.authtoken, this.isPO, vlArgs],
2222 onresponse: function(r) {
2223 var resp = openils.Util.readResponse(r);
2224 self._updateProgressNumbers(resp, !Boolean(onAssetsCreated), onAssetsCreated);
2230 this.maybeCancelLineitems = function() {
2231 openils.Util.show("acq-lit-cancel-reason", "inline");
2232 if (!acqLitCancelLineitemsButton._prepared) {
2233 var widget = new openils.widget.AutoFieldWidget({
2234 "fmField": "cancel_reason",
2236 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
2237 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2242 acqLitCancelLineitemsButton.onClick = function() {
2243 if (w.attr("value")) {
2244 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
2245 self._cancelLineitems(w.attr("value"));
2247 openils.Util.hide("acq-lit-cancel-reason");
2250 acqLitCancelLineitemsButton._prepared = true;
2256 this._cancelLineitems = function(reason) {
2257 var id_list = this.getSelected().map(function(o) { return o.id(); });
2258 fieldmapper.standardRequest(
2259 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
2260 "params": [openils.User.authtoken, id_list, reason],
2262 "onresponse": function(r) {
2263 if (r = openils.Util.readResponse(r)) {
2265 for (var id in r.li) {
2266 self.liCache[id].state(r.li[id].state);
2267 self.liCache[id].cancel_reason(
2268 r.li[id].cancel_reason
2270 self.updateLiState(self.liCache[id]);
2273 if (r.lid && self.copyCache) {
2274 for (var id in r.lid) {
2275 if (self.copyCache[id]) {
2276 self.copyCache[id].cancel_reason(
2277 r.lid[id].cancel_reason
2279 self.updateLidState(self.copyCache[id]);
2289 this.chooseExportAttr = function() {
2290 if (!acqLitExportAttrSelector._li_setup) {
2292 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
2294 "data": acqlimad.toStoreData(
2296 "acqlimad", {"code": li_exportable_attrs}
2301 acqLitExportAttrSelector.setValue();
2302 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
2303 acqLitExportAttrSelector._li_setup = true;
2305 openils.Util.show("acq-lit-export-attr-holder", "inline");
2308 this.exportAttrList = function() {
2309 var attr_def = acqLitExportAttrSelector.item;
2310 var li_list = this.getSelected();
2311 var value_list = li_list.map(
2313 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2314 attr_def.code, "lineitem_marc_attr_definition"
2317 ).filter(function(attr) { return Boolean(attr); });
2319 if (value_list.length > 0) {
2320 if (value_list.length < li_list.length) {
2322 dojo.string.substitute(
2323 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
2330 openils.XUL.contentToFileSaveDialog(
2331 value_list.join("\n"),
2332 localeStrings.EXPORT_SAVE_DIALOG_TITLE
2338 alert(dojo.string.substitute(
2339 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
2343 openils.Util.hide("acq-lit-export-attr-holder");
2346 this.printPO = function() {
2347 if(!this.isPO) return;
2348 progressDialog.show(true);
2349 fieldmapper.standardRequest(
2350 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
2352 params: [this.authtoken, this.isPO, 'html'],
2353 oncomplete: function(r) {
2354 progressDialog.hide();
2355 var evt = openils.Util.readResponse(r);
2356 if(evt && evt.template_output()) {
2357 openils.Util.printHtmlString(evt.template_output().data());
2365 this.receivePO = function() {
2366 if (!this.isPO) return;
2368 for (var id in this.liCache) {
2369 /* assumption: liCache reflects exactly the
2370 * set of LIs that belong to our PO */
2371 if (this.liCache[id].state() != "received" &&
2372 !this.checkLiAlerts(id)) return;
2375 this.show('acq-lit-progress-numbers');
2377 fieldmapper.standardRequest(
2378 ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
2380 params: [this.authtoken, this.isPO],
2381 onresponse : function(r) {
2382 var resp = openils.Util.readResponse(r);
2383 self._updateProgressNumbers(resp, true);
2389 this.issueReceive = function(obj, rollback) {
2391 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
2393 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
2395 progressDialog.show(true);
2396 fieldmapper.standardRequest(
2397 ["open-ils.acq", method], {
2399 "params": [this.authtoken, obj.id()],
2400 "onresponse": function(r) {
2401 if (r = openils.Util.readResponse(r)) {
2402 self.fetchClaimInfo(
2403 part == "lineitem" ? obj.id() : obj.lineitem(),
2405 function() { self.handleReceive(r); }
2407 progressDialog.hide();
2415 * Handles the responses from receive and rollback ML calls.
2417 this.handleReceive = function(resp) {
2420 for (var li_id in resp.li) {
2421 for (var key in resp.li[li_id])
2422 self.liCache[li_id][key](resp.li[li_id][key]);
2423 self.updateLiState(self.liCache[li_id]);
2427 if (typeof(self.poUpdateCallback) == "function")
2428 self.poUpdateCallback(resp.po);
2431 for (var lid_id in resp.lid) {
2432 for (var key in resp.lid[lid_id])
2433 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
2434 self.updateLidState(self.copyCache[lid_id]);
2440 this.rollbackPoReceive = function() {
2441 if(!this.isPO) return;
2442 if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
2443 this.show('acq-lit-progress-numbers');
2445 fieldmapper.standardRequest(
2446 ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
2448 params: [this.authtoken, this.isPO],
2449 onresponse : function(r) {
2450 var resp = openils.Util.readResponse(r);
2451 self._updateProgressNumbers(resp, true);
2457 this._updateProgressNumbers = function(resp, reloadOnComplete, onComplete) {
2458 this.vlAgent.handleResponse(resp,
2459 function(resp, res) {
2460 if(reloadOnComplete)
2461 location.href = location.href;
2463 onComplete(resp, res);
2469 this._createPO = function(fields) {
2470 var wantall = (fields.create_from == "all");
2472 /* If we're a picklist or purchase order already and the user wants
2473 * all lineitems, we might have pages' worth of lineitems haven't all
2474 * been loaded yet, so getSelected() won't find them. The server,
2475 * however, should know about all our lineitems, so let's ask the
2476 * server for a complete list.
2481 true, function(list) {
2482 self._createPOFromLineitems(fields, list);
2483 }, /* id_list */ true
2486 this._createPOFromLineitems(fields, this.getSelected(false, null, true /* id_list */));
2490 this._createPOFromLineitems = function(fields, selected) {
2491 if (selected.length == 0) return;
2494 var po = new fieldmapper.acqpo();
2495 po.provider(this.createPoProviderSelector.attr("value"));
2496 po.ordering_agency(this.createPoAgencySelector.attr("value"));
2497 po.prepayment_required(fields.prepayment_required[0] ? true : false);
2499 // if we're creating assets, delay the asset creation
2500 // until after the PO is created. This will allow us to
2501 // use showAssetCreator() directly.
2503 fieldmapper.standardRequest(
2504 ["open-ils.acq", "open-ils.acq.purchase_order.create"],
2507 openils.User.authtoken,
2508 po, {lineitems : selected}
2510 onresponse : function(r) {
2511 var resp = openils.Util.readResponse(r);
2512 if (resp.complete) {
2513 // self.isPO is needed for showAssetCreator();
2514 self.isPO = resp.purchase_order.id();
2515 var redir = oilsBasePath + "/acq/po/view/" + self.isPO;
2516 if (fields.create_assets[0]) {
2517 self.showAssetCreator(
2518 function() {location.href = redir}
2521 location.href = redir;
2530 this.batchFundWidget = null;
2532 this.applyBatchLiFunds = function() {
2534 var liIds = this.getSelected().map(function(li) { return li.id(); });
2535 if(liIds.length == 0) return; // warn?
2538 batchFundUpdateDialog.show();
2540 if(!this.batchFundWidget) {
2541 this.batchFundWidget = new openils.widget.AutoFieldWidget({
2543 selfReference : true,
2544 labelFormat : fundLabelFormat,
2545 searchFormat : fundSearchFormat,
2546 searchFilter : {"active": "t"},
2547 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
2548 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2549 dijitArgs : { "required": true, "labelType": "html" },
2552 this.batchFundWidget.build();
2555 dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
2556 dojo.connect(batchFundUpdateSubmit, 'onClick',
2559 // TODO: call .dry_run first to test thresholds
2560 fieldmapper.standardRequest(
2561 ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
2564 openils.User.authtoken,
2566 self.batchFundWidget.widget.attr('value')
2568 oncomplete : function(r) {
2569 var resp = openils.Util.readResponse(r);
2571 location.href = location.href;
2580 this._deleteLiList = function(list, idx) {
2581 if(idx == null) idx = 0;
2582 if(idx >= list.length) return;
2587 if (this.isPO && (li.state() == "on-order" || li.state() == "received")) {
2588 /* It makes little sense to delete a lineitem from a PO that has
2589 * already been marked 'on-order'. Especially if EDI is in use,
2590 * such a purchase order will probably have already been shipped
2591 * off to a vendor, and mucking with it at this point could leave
2592 * your data in a bad state that doesn't jive with reality.
2594 * I could see making this restriction even firmer.
2596 * I could also see adjusting the li state comparisons, extending
2597 * the comparison to the PO's state, and/or providing functions
2598 * that house the logic for comparing states in a single location.
2600 * Yes, this will be really annoying if you have selected a lot
2601 * of lineitems to cancel that have been ordered. You'll get a
2602 * confirm dialog for each one.
2605 if (!confirm(localeStrings.DEL_LI_FROM_PO)) {
2606 self._deleteLiList(list, ++idx); /* move on to next in list */
2611 fieldmapper.standardRequest(
2613 this.isPO ? 'open-ils.acq.purchase_order.lineitem.delete' : 'open-ils.acq.picklist.lineitem.delete'],
2615 params: [openils.User.authtoken, liId],
2616 oncomplete: function(r) {
2617 self.removeLineitem(liId);
2618 self._deleteLiList(list, ++idx);
2624 this.editOrderMarc = function(li) {
2626 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
2627 to true in about:config */
2629 if(!openils.XUL.enableXPConnect()) return;
2631 if(openils.XUL.isXUL()) {
2632 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
2634 win = window.open('/xul/server/cat/marcedit.xul');
2638 record : {marc : li.marc(), "rtype": "bre"},
2640 label: 'Save Record', // XXX I18N
2641 func: function(xmlString) {
2643 fieldmapper.standardRequest(
2644 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
2646 params: [openils.User.authtoken, li],
2647 oncomplete: function(r) {
2648 openils.Util.readResponse(r);
2650 self.drawInfo(li.id())
2656 'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
2657 'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
2661 this._savePl = function(values) {
2663 (values.which == 'all'),
2664 function(list) { self._savePlFromLineitems(values, list); }
2668 this._savePlFromLineitems = function(values, selected) {
2669 openils.Util.show("acq-lit-generic-progress");
2671 if(values.new_name) {
2672 openils.acq.Picklist.create(
2673 {name: values.new_name},
2679 oilsBasePath + "/acq/picklist/view/" + id;
2684 } else if(values.existing_pl) {
2685 // update lineitems to use an existing picklist
2687 values.existing_pl, selected, 0,
2690 oilsBasePath + "/acq/picklist/view/" +
2697 this._updateLiState = function(values, state) {
2698 progressDialog.show(true);
2700 (values.which == 'all'),
2702 self._updateLiStateFromLineitems(values, state, list);
2707 this._updateLiStateFromLineitems = function(values, state, selected) {
2708 if(!selected.length) return;
2709 dojo.forEach(selected, function(li) {li.state(state);});
2710 self._updateLiList(null, selected, 0,
2711 // TODO consider inline updates for efficiency
2712 function() { location.href = location.href }
2716 this._updateLiList = function(pl, list, idx, oncomplete) {
2717 if(idx >= list.length) return oncomplete();
2719 if(pl != null) li.picklist(pl);
2720 litGenericProgress.update({maximum: list.length, progress: idx});
2721 new openils.acq.Lineitem({lineitem:li}).update(
2723 self._updateLiList(pl, list, ++idx, oncomplete);
2728 this._loadPOSelect = function() {
2729 if (!this.createPoProviderSelector) {
2730 var widget = new openils.widget.AutoFieldWidget({
2731 "fmField": "provider",
2733 "searchFilter": {"active": "t"},
2734 "parentNode": dojo.byId("acq-lit-po-provider"),
2736 "onChange": function() {
2738 self._updateCreatePoPrepayCheckbox(
2739 this.item.prepayment_required()
2745 widget.build(function(w) { self.createPoProviderSelector = w; });
2748 if (!this.createPoAgencySelector) {
2749 var widget = new openils.widget.AutoFieldWidget({
2750 "fmField": "ordering_agency",
2752 "parentNode": dojo.byId("acq-lit-po-agency"),
2753 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2755 widget.build(function(w) { self.createPoAgencySelector = w; });
2759 this.showRealCopyEditUI = function(li) {
2764 this._fetchLineitem(li.id(),
2766 li = self.liCache[li.id()] = fullLi;
2770 id : li.lineitem_details().map(
2771 function(item) { return item.eg_copy_id() }
2775 oncomplete : function(r) {
2777 var r_list = openils.Util.readResponse( r );
2778 for (var i = 0; i < r_list.length; i++) {
2779 var copy = r_list[i];
2780 var volId = copy.call_number();
2781 var volume = self.volCache[volId];
2783 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2785 copy.call_number(volume);
2786 copyList.push(copy);
2789 xulG.volume_item_creator( { 'existing_copies' : copyList } );
2792 alert('error in oncomplete: ' + E);
2801 this.drawBibFinder = function(li) {
2804 var liWrapper = new openils.acq.Lineitem({lineitem:li});
2807 ['isbn', 'upc', 'issn', 'title', 'author'],
2809 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
2811 if(field == 'title' || field == 'author') {
2812 query += field +':' + val + ' ';
2814 query += 'identifier|' + field + ':' + val + ' ';
2821 oilsBasePath + '/acq/lineitem/findbib?query=' + escape(query),
2822 '', 'resizable,scrollbars=1');
2824 win.window.recordFound = function(bibId) {
2827 var attrs = li.attributes();
2828 li.attributes(null);
2829 li.eg_bib_id(bibId);
2831 fieldmapper.standardRequest(
2832 ["open-ils.acq", "open-ils.acq.lineitem.update"],
2834 "params": [openils.User.authtoken, li],
2836 "oncomplete": function(r) {
2837 if(openils.Util.readResponse(r)) {
2838 location.href = location.href;