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");
18 if (!localeStrings) { /* we can do this because javascript doesn't have block scope */
19 dojo.requireLocalization('openils.acq', 'acq');
20 var localeStrings = dojo.i18n.getLocalization('openils.acq', 'acq');
22 const XUL_OPAC_WRAPPER = 'chrome://open_ils_staff_client/content/cat/opac.xul';
23 var li_exportable_attrs = ["issn", "isbn", "upc"];
25 var fundLabelFormat = [
26 '<span class="fund_${0}">${1} (${2})</span>', 'id', 'code', 'year'
28 var fundSearchFormat = ['${0} (${1})', 'code', 'year'];
30 function nodeByName(name, context) {
31 return dojo.query('[name='+name+']', context)[0];
34 // for caching linked users. e.g. lineitem_detail.receiver
37 var liDetailBatchFields = ['fund', 'owning_lib', 'location', 'collection_code', 'circ_modifier', 'cn_label'];
38 var liDetailFields = liDetailBatchFields.concat(['barcode', 'note']);
40 "stop": "color: #c00; font-weight: bold;",
41 "warning": "color: #c93;"
44 function AcqLiTable() {
51 this.haveFundClass = {}
52 this.fundBalanceState = {};
53 this.realDfaCache = {};
54 this.virtDfaCounts = {};
57 this.claimEligibleLidByLi = {};
58 this.claimEligibleLid = {};
59 this.toggleState = false;
60 this.tbody = dojo.byId('acq-lit-tbody');
63 this.authtoken = openils.User.authtoken;
64 this.pcrud = new openils.PermaCrud();
65 this.rowTemplate = this.tbody.removeChild(dojo.byId('acq-lit-row'));
66 this.copyTbody = dojo.byId('acq-lit-li-details-tbody');
67 this.copyRow = this.copyTbody.removeChild(dojo.byId('acq-lit-li-details-row'));
68 this.copyBatchRow = dojo.byId('acq-lit-li-details-batch-row');
69 this.copyBatchWidgets = {};
70 this.liNotesTbody = dojo.byId('acq-lit-notes-tbody');
71 this.liNotesRow = this.liNotesTbody.removeChild(dojo.byId('acq-lit-notes-row'));
72 this.realCopiesTbody = dojo.byId('acq-lit-real-copies-tbody');
73 this.realCopiesRow = this.realCopiesTbody.removeChild(dojo.byId('acq-lit-real-copies-row'));
74 this._copy_fields_for_acqdf = ['owning_lib', 'location'];
75 this.skipInitialEligibilityCheck = false;
76 this.claimDialog = new ClaimDialogManager(
77 liClaimDialog, finalClaimDialog, this.claimEligibleLidByLi,
78 function(li) { /* callback that fires when claims are made */
79 self.fetchClaimInfo(li.id(), /* force update */ true);
82 this.vlAgent = new VLAgent();
84 dojo.byId("acq-lit-li-actions-selector").onchange = function() {
85 self.applySelectedLiAction(this.options[this.selectedIndex].value);
86 this.selectedIndex = 0;
89 acqLitCreatePoSubmit.onClick = function() {
90 if (!self.createPoProviderSelector.attr("value") ||
91 !self.createPoAgencySelector.attr("value")) {
92 alert(localeStrings.CREATE_PO_INVALID);
94 } else if (self._confirmPoPrepaySituation()) {
95 acqLitPoCreateDialog.hide();
96 self._createPO(acqLitPoCreateDialog.getValues());
102 acqLitSavePlButton.onClick = function() {
103 acqLitSavePlDialog.hide();
104 self._savePl(acqLitSavePlDialog.getValues());
107 acqLitCancelLiStateButton.onClick = function() {
108 acqLitChangeLiStateDialog.hide();
110 acqLitSaveLiStateButton.onClick = function() {
111 acqLitChangeLiStateDialog.hide();
112 self._updateLiState(acqLitChangeLiStateDialog.getValues(), acqLitChangeLiStateDialog.attr('state'));
116 dojo.byId('acq-lit-select-toggle').onclick = function(){self.toggleSelect()};
117 dojo.byId('acq-lit-info-back-button').onclick = function(){self.show('list')};
118 dojo.byId('acq-lit-copies-back-button').onclick = function(){self.show('list')};
119 dojo.byId('acq-lit-notes-back-button').onclick = function(){self.show('list')};
120 dojo.byId('acq-lit-real-copies-back-button').onclick = function(){self.show('list')};
122 this.reset = function(keep_selectors) {
123 while(self.tbody.childNodes[0])
124 self.tbody.removeChild(self.tbody.childNodes[0]);
132 this.setNext = function(handler) {
133 var link = dojo.byId('acq-lit-next');
135 dojo.style(link, 'visibility', 'visible');
136 link.onclick = handler;
138 dojo.style(link, 'visibility', 'hidden');
142 this.setPrev = function(handler) {
143 var link = dojo.byId('acq-lit-prev');
145 dojo.style(link, 'visibility', 'visible');
146 link.onclick = handler;
148 dojo.style(link, 'visibility', 'hidden');
152 this.show = function(div) {
153 openils.Util.hide('acq-lit-table-div');
154 openils.Util.hide('acq-lit-info-div');
155 openils.Util.hide('acq-lit-li-details');
156 openils.Util.hide('acq-lit-notes-div');
157 openils.Util.hide('acq-lit-real-copies-div');
158 openils.Util.hide('acq-lit-asset-creator');
161 openils.Util.show('acq-lit-table-div');
164 openils.Util.show('acq-lit-info-div');
167 openils.Util.show('acq-lit-li-details');
170 openils.Util.show('acq-lit-real-copies-div');
173 openils.Util.show('acq-lit-notes-div');
175 case 'asset-creator':
176 openils.Util.show('acq-lit-asset-creator');
180 openils.Util.show(div);
184 this.hide = function() {
188 this.toggleSelect = function() {
190 dojo.forEach(self.selectors, function(i){i.checked = false});
192 dojo.forEach(self.selectors, function(i){i.checked = true});
193 self.toggleState = !self.toggleState;
197 this.getAll = function(callback, id_only) {
198 /* For some uses of the li table, we may not really know about "all"
199 * the lineitems that the user thinks we know about. If we're a paged
200 * picklist, for example, we only know about the lineitems we've
201 * displayed, but not necessarily all the lineitems on the picklist.
202 * So we reach out to pcrud to inform us.
205 var oncomplete = function(r) {
206 var id_list = openils.Util.readResponse(r);
210 self.fetchLineitemsById(id_list, callback);
215 "jub", {"picklist": this.isPL}, {
216 "id_list": true, /* sic, even if id_only */
218 "oncomplete": oncomplete
222 } else if (this.isPO) {
224 "jub", {"purchase_order": this.isPO}, {
227 "oncomplete": oncomplete
231 } else if (this.isUni && this.pager) {
232 this.pager.getAllLineitemIDs(oncomplete);
236 /* If execution reaches this point, we don't need or can't perform
237 * any special tricks to find out the "real" list of "all" lineitems
238 * in this context, so we fall back to the old method.
240 callback(this.getSelected(true, null, id_only));
243 /** @param all If true, assume all are selected */
244 this.getSelected = function(
246 callback /* If you want a "good" idea of "all" lineitems, you must
247 provide a callback that accepts an array parameter, rather than
248 relying on the return value of this method itself. */,
252 return this.getAll(callback, id_only);
254 var indices = {}; /* use to uniqify. needed in paging situations. */
255 dojo.forEach(this.selectors,
258 indices[i.parentNode.parentNode.getAttribute('li')] = true;
262 var result = openils.Util.objectProperties(indices);
265 result = result.map(function(liId) { return self.liCache[liId]; });
273 this.setRowAttr = function(td, liWrapper, field, type) {
274 var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
275 td.appendChild(document.createTextNode(val));
278 this.setClaimPolicyControl = function(li, row) {
279 if (!self.claimPolicyPicker) {
280 self.claimPolicyPicker = true; /* prevents a race condition */
281 new openils.widget.AutoFieldWidget({
282 "parentNode": "acq-lit-li-claim-policy",
284 "selfReference": true,
285 "dijitArgs": {"required": true}
286 }).build(function(w) { self.claimPolicyPicker = w; });
289 if (!row) row = this._findLiRow(li);
291 var actViewPolicy = nodeByName("action_view_claim_policy", row);
292 if (li.claim_policy())
293 actViewPolicy.innerHTML = localeStrings.CHANGE_CLAIM_POLICY;
295 if (!actViewPolicy.onclick) {
296 actViewPolicy.onclick = function() {
297 if (li.claim_policy())
298 self.claimPolicyPicker.attr("value", li.claim_policy());
299 liClaimPolicyDialog.show();
300 liClaimPolicySave.onClick = function() {
301 self.changeClaimPolicy(
302 [li], self.claimPolicyPicker.attr("value"),
304 self.setClaimPolicyControl(li, row);
305 self.reconsiderClaimControl(li, row);
306 liClaimPolicyDialog.hide();
314 this.fetchClaimInfo = function(liId, force, callback, row) {
316 liId, function(full) {
317 self.liCache[full.id()] = full;
318 self.checkClaimEligibility(full, callback, row);
324 * Inserts a single lineitem into the growing table of lineitems
325 * @param {Object} li The lineitem object to insert
327 this.addLineitem = function(li, skip_final_placement) {
328 this.liCache[li.id()] = li;
330 // insert the row right away so that final order isn't
331 // dependent on how long subsequent async request take
332 // for a given line item
333 var row = self.rowTemplate.cloneNode(true);
334 if (!skip_final_placement) {
335 self.tbody.appendChild(row);
337 self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
339 // sort the lineitem notes on edit_time
340 if(!li.lineitem_notes()) li.lineitem_notes([]);
342 var liWrapper = new openils.acq.Lineitem({lineitem:li});
343 row.setAttribute('li', li.id());
344 var tds = dojo.query('[attr]', row);
345 dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
346 dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
349 liWrapper.findAttr("isbn", "lineitem_marc_attr_definition") ||
350 liWrapper.findAttr("upc", "lineitem_marc_attr_definition");
352 // XXX media prefix for added content
354 nodeByName("jacket", row).setAttribute(
355 "src", "/opac/extras/ac/jacket/small/" + identifier
359 nodeByName("liid", row).innerHTML += li.id();
362 openils.Util.show(nodeByName('catalog', row), 'inline');
363 nodeByName("catalog_link", row).onclick = this.generateMakeRecTab(li.eg_bib_id());
365 openils.Util.show(nodeByName('link_to_catalog', row), 'inline');
366 nodeByName("link_to_catalog_link", row).onclick = function() { self.drawBibFinder(li) };
369 if (li.queued_record()) {
370 this.pcrud.retrieve('vqbr', li.queued_record(),
372 oncomplete : function(r) {
373 var qrec = openils.Util.readResponse(r);
374 openils.Util.show(nodeByName('queue', row), 'inline');
375 var link = nodeByName("queue_link", row);
376 link.onclick = function() {
377 // open a new tab to the vandelay queue for this record
378 openils.XUL.newTabEasy(
379 oilsBasePath + '/vandelay/vandelay?qtype=bib&qid=' + qrec.queue()
387 nodeByName("worksheet_link", row).href =
388 oilsBasePath + "/acq/lineitem/worksheet/" + li.id();
390 nodeByName("show_requests_link", row).href =
391 oilsBasePath + "/acq/picklist/user_request?lineitem=" + li.id();
393 dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
394 dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
395 dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
397 if (!this.skipInitialEligibilityCheck)
401 function(full) { self.setClaimPolicyControl(full, row) },
405 this.updateLiNotesCount(li, row);
407 // show which PO this lineitem is a member of
408 if(li.purchase_order() && !this.isPO) {
410 this.poCache[li.purchase_order()] =
411 this.poCache[li.purchase_order()] ||
412 fieldmapper.standardRequest(
413 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
415 this.authtoken, li.purchase_order(), {
416 "flesh_price_summary": true,
417 "flesh_provider" : true,
418 "flesh_lineitem_count": true
421 if(po && !this.isMeta) {
422 openils.Util.show(nodeByName('po', row), 'inline');
423 var link = nodeByName('po_link', row);
424 link.setAttribute('href', oilsBasePath + '/acq/po/view/' + li.purchase_order());
425 link.innerHTML += po.name();
427 openils.Util.show(nodeByName('pro', row), 'inline');
428 link = nodeByName('pro_link', row);
429 link.setAttribute('href', oilsBasePath + '/conify/global/acq/provider/' + po.provider().id())
430 link.innerHTML += po.provider().code();
434 // show which picklist this lineitem is a member of
435 if(li.picklist() && (this.isPO || this.isMeta || this.isUni)) {
437 this.plCache[li.picklist()] =
438 this.plCache[li.picklist()] ||
439 fieldmapper.standardRequest(
440 ['open-ils.acq', 'open-ils.acq.picklist.retrieve.authoritative'],
441 {params: [this.authtoken, li.picklist()]});
443 if (pl.name() == "") {
444 openils.Util.show(nodeByName("bib_origin", row), "inline");
448 openils.Util.show(nodeByName('pl', row), 'inline');
449 var link = nodeByName('pl_link', row);
450 link.setAttribute('href', oilsBasePath + '/acq/picklist/view/' + li.picklist());
451 link.innerHTML += pl.name();
456 var countNode = nodeByName('count', row);
457 var count = li.item_count() || 0;
458 if (typeof(this._copy_count_cb) == "function") {
459 this._copy_count_cb(li.id(), count);
461 countNode.innerHTML = count;
462 countNode.id = 'acq-lit-copy-count-label-' + li.id();
465 var priceInput = dojo.query('[name=price]', row)[0];
466 priceInput.value = li.estimated_unit_price() || '';
467 priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
469 // show either "mark received" or "unreceive" as appropriate
470 this.updateLiState(li, row);
472 if (skip_final_placement) {
477 this._liCountClaims = function(li) {
479 for (var i = 0; i < li.lineitem_details().length; i++)
480 total += li.lineitem_details()[i].claims().length;
484 this._findLiRow = function(li) {
485 return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
488 this.reconsiderClaimControl = function(li, row) {
489 if (!row) row = this._findLiRow(li);
490 var option = nodeByName("action_manage_claims", row);
491 var eligible = this.claimEligibleLidByLi[li.id()].length;
492 var count = this._liCountClaims(li);
494 option.disabled = !(count || eligible);
496 dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
497 option.onclick = function() { self.claimDialog.show(li); };
500 this.clearEligibility = function(li) {
501 this.claimEligibleLidByLi[li.id()] = [];
503 if (li.lineitem_details()) {
504 li.lineitem_details().forEach(
505 function(lid) { delete self.claimEligibleLid[lid.id()]; }
509 if (this.copyCache) {
511 for (var k in this.copyCache) {
512 if (this.copyCache[k].lineitem() == li.id())
516 function(k) { delete self.claimEligibleLid[k]; }
521 this.checkClaimEligibility = function(li, callback, row) {
522 /* Assume always eligible, i.e. from this interface we don't care about
523 * claim eligibility any more. this is where the user would force a
525 this.clearEligibility(li);
526 this.claimEligibleLidByLi[li.id()] = li.lineitem_details().map(
527 function(lid) { return lid.id(); }
529 li.lineitem_details().forEach(
530 function(lid) { self.claimEligibleLid[lid.id()] = true; }
532 this.reconsiderClaimControl(li, row);
533 if (callback) callback(li);
535 this.clearEligibility(li);
536 fieldmapper.standardRequest(
537 ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
538 "params": [openils.User.authtoken, {"lineitem": li.id()}],
540 "onresponse": function(r) {
541 if (r = openils.Util.readResponse(r)) {
542 self.claimEligibleLidByLi[li.id()].push(
545 self.claimEligibleLid[r.lineitem_detail()] = true;
548 "oncomplete": function() {
549 self.reconsiderClaimControl(li, row);
550 if (typeof(callback) == "function")
558 this.updateLiNotesCount = function(li, row) {
559 if (!row) row = this._findLiRow(li);
561 var has_notes = (li.lineitem_notes().filter(
562 function(o) { return Boolean (o.alert_text()); }
565 /* U+2691 is the code point for a filled-in flag character */
566 nodeByName("notes_alert_flag", row).innerHTML =
567 has_notes ? "⚑" : "";
568 nodeByName("noteslink", row).style.fontStyle =
569 has_notes ? "italic" : "normal";
570 nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
573 /* XXX NOT related to _updateLiState(). rethink */
574 this.updateLiState = function(li, row) {
575 if (!row) row = this._findLiRow(li);
577 var actReceive = nodeByName("action_mark_recv", row);
578 var actUnRecv = nodeByName("action_mark_unrecv", row);
579 var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
580 var actHoldingsMaint = nodeByName("action_holdings_maint", row);
581 var actNewInvoice = nodeByName('action_new_invoice', row);
582 var actLinkInvoice = nodeByName('action_link_invoice', row);
583 var actViewInvoice = nodeByName('action_view_invoice', row);
585 // always allow access to LI history
586 nodeByName('action_view_history', row).onclick =
587 function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
589 /* handle row coloring for based on LI state */
590 openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
591 openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
593 // Expose invoice actions for any lineitem that is linked to a PO
594 if( li.purchase_order() ) {
596 actNewInvoice.disabled = false;
597 actLinkInvoice.disabled = false;
598 actViewInvoice.disabled = false;
600 actNewInvoice.onclick = function() {
601 location.href = oilsBasePath + '/acq/invoice/view?create=1&attach_li=' + li.id();
602 nodeByName("action_none", row).selected = true;
605 actLinkInvoice.onclick = function() {
606 if (!self.invoiceLinkDialogManager) {
607 self.invoiceLinkDialogManager =
608 new InvoiceLinkDialogManager("li");
610 self.invoiceLinkDialogManager.target = li;
611 acqLitLinkInvoiceDialog.show();
612 nodeByName("action_none", row).selected = true;
615 actViewInvoice.onclick = function() {
616 location.href = oilsBasePath +
617 "/acq/search/unified?so=" +
618 base64Encode({"jub":[{"id": li.id()}]}) +
620 nodeByName("action_none", row).selected = true;
626 * If we haven't fleshed the lineitem_details, default to allowing access to the
627 * holdings maintenence actions. The alternative is to flesh LIDs on every lineitem,
628 * but that will add to page render time. Let's see if this will suffice...
630 var lids = li.lineitem_details();
632 (lids && !lids.filter(function(lid) { return lid.eg_copy_id() })[0] )) {
634 actUpdateBarcodes.disabled = false;
635 actUpdateBarcodes.onclick = function() {
636 self.showRealCopyEditUI(li);
637 nodeByName("action_none", row).selected = true;
639 actHoldingsMaint.disabled = false;
640 actHoldingsMaint.onclick =
641 self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
644 var state_cell = nodeByName("li_state", row);
649 if(typeof li.cancel_reason() == "object") {
650 var holds_state = dojo.create(
652 "style": "border-bottom: 1px dashed #000;",
653 "innerHTML": li.state()
654 }, state_cell, "only"
658 "label": "<em>" + li.cancel_reason().label() +
659 "</em><br />" + li.cancel_reason().description(),
660 "connectId": [holds_state]
661 }, dojo.create("span", null, state_cell, "last")
667 actReceive.disabled = false;
668 actReceive.onclick = function() {
669 if (self.checkLiAlerts(li.id()))
670 self.issueReceive(li);
671 nodeByName("action_none", row).selected = true;
676 actUnRecv.disabled = false;
677 actUnRecv.onclick = function() {
678 if (confirm(localeStrings.UNRECEIVE_LI))
679 self.issueReceive(li, /* rollback */ true);
680 nodeByName("action_none", row).selected = true;
685 state_cell.innerHTML = li.state(); // TODO i18n state labels
689 this._setAlertStore = function() {
690 acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
692 "data": acqliat.toStoreData(
695 "owning_lib": aou.orgNodeTrail(
696 aou.findOrgUnit(openils.User.user.ws_ou())
697 ).map(function(o) { return o.id(); })
703 acqLitAlertAlertText.setValue(); /* make the store "live" */
704 acqLitAlertAlertText._store_ready = true;
708 * Draws and shows the lineitem notes pane
710 this.drawLiNotes = function(li) {
713 if (!acqLitAlertAlertText._store_ready)
714 this._setAlertStore();
717 li.lineitem_notes().sort(
719 if(a.edit_time() < b.edit_time()) return 1;
725 while(this.liNotesTbody.childNodes[0])
726 this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
729 acqLitCreateNoteSubmit.onClick = function() {
730 var value = acqLitCreateNoteText.attr('value');
732 var note = new fieldmapper.acqlin();
735 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
738 note.lineitem(li.id());
740 self.updateLiNotes(li, note);
741 acqLitCreateNoteVendorPublic.attr("checked", false);
742 acqLitCreateNoteText.attr("value", "");
745 acqLitCreateAlertSubmit.onClick = function() {
746 if (!acqLitAlertAlertText.item) {
747 alert(localeStrings.ALERT_UNSELECTED);
751 var alert_text = new fieldmapper.acqliat().fromStoreItem(
752 acqLitAlertAlertText.item
754 var value = acqLitAlertNoteValue.attr("value") || "";
756 var note = new fieldmapper.acqlin();
758 note.lineitem(li.id());
760 note.alert_text(alert_text);
762 self.updateLiNotes(li, note);
765 dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
769 * Draws a single lineitem note in the notes pane
771 this.addLiNote = function(li, note) {
772 if(note.isdeleted()) return;
774 var row = self.liNotesRow.cloneNode(true);
775 nodeByName("value", row).innerHTML = note.value();
776 var alert_node = nodeByName("alert_code", row);
777 if (note.alert_text()) {
778 alert_node.innerHTML = dojo.string.substitute(
780 aou.findOrgUnit(note.alert_text().owning_lib()).shortname(),
781 note.alert_text().code()
784 if (note.alert_text().description()) {
787 "connectId": [alert_node],
788 "label": note.alert_text().description()
789 }, dojo.create("span", null, alert_node, "after")
794 if (openils.Util.isTrue(note.vendor_public()))
795 nodeByName("vendor_public", row).innerHTML =
796 localeStrings.VENDOR_PUBLIC;
798 nodeByName("delete", row).onclick = function() {
799 note.isdeleted(true);
800 self.liNotesTbody.removeChild(row);
801 self.updateLiNotes(li);
804 if(note.edit_time()) {
805 nodeByName("edit_time", row).innerHTML =
806 dojo.date.locale.format(
807 dojo.date.stamp.fromISOString(note.edit_time()),
808 {formatLength:'short'});
811 self.liNotesTbody.appendChild(row);
815 * Updates any new/changed/deleted notes on the server
817 this.updateLiNotes = function(li, newNote) {
823 notes = li.lineitem_notes().filter(
825 if(note.ischanged() || note.isnew() || note.isdeleted())
831 if(notes.length == 0) return;
832 progressDialog.show();
834 fieldmapper.standardRequest(
835 ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
837 params : [this.authtoken, notes],
838 onresponse : function(r) {
839 var resp = openils.Util.readResponse(r);
844 // remove the old changed notes
846 dojo.forEach(li.lineitem_notes(),
848 if(!(note.ischanged() || note.isnew() || note.isdeleted()))
852 li.lineitem_notes(list);
855 progressDialog.hide();
856 self.updateLiNotesCount(li);
857 self.drawLiNotes(li);
861 progressDialog.update(resp);
862 var newnote = resp.note;
864 if(!newnote.isdeleted()) {
865 newnote.isnew(false);
866 newnote.ischanged(false);
867 li.lineitem_notes().push(newnote);
874 this.updateLiPrice = function(input, li) {
876 var price = input.value;
877 if(Number(price) == Number(li.estimated_unit_price())) return;
879 fieldmapper.standardRequest(
880 ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
881 { async : false, // redundant w/ timeout
883 params : [this.authtoken, li.id(), price],
884 oncomplete : function(r) {
885 openils.Util.readResponse(r);
886 li.estimated_unit_price(price); // update local copy
889 * If this is a PO and every visible lineitem has a price,
890 * check again to see if this PO can be activated. Note that
891 * every visible lineitem having a price does not guarantee it can
892 * be activated, which is why we still make the call. Having a price
893 * set for every visiable lineitem is just the lowest barrier to entry.
896 var priceNodes = dojo.query('[name=price]', dojo.byId('acq-lit-tbody'));
898 dojo.forEach(priceNodes, function(node) { if (node.value == '') allSet = false});
899 if (allSet) checkCouldActivatePo();
906 this.removeLineitem = function(liId) {
907 this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
908 delete this.liCache[liId];
909 //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
912 this.drawInfo = function(liId) {
913 if (!this._isRelatedViewer) {
914 var d = dojo.byId("acq-lit-info-related");
915 if (!this.relCache[liId]) {
916 fieldmapper.standardRequest(
919 "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
922 "params": [openils.User.authtoken, liId],
923 "onresponse": function(r) {
924 self.relCache[liId] = openils.Util.readResponse(r);
925 nodeByName("related_number", d).innerHTML =
928 self.relCache[liId] >1 ? "show" : "hide"
934 nodeByName("related_number", d).innerHTML = this.relCache[liId];
935 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
940 openils.acq.Lineitem.fetchAttrDefs(
942 self._fetchLineitem(liId, function(li){self._drawInfo(li);});
947 /* For a given list of lineitem ids, build a list of full lineitems
948 * re-using the fetching logic that is otherwise typical to use in this
951 * If we've already got a lineitem in the cache, just use that.
953 * Once we've built a list of lineitems, call callback(thatlist).
955 this.fetchLineitemsById = function(id_list, callback) {
956 var total = id_list.length;
957 var result_list = [];
959 var inner = function(li) {
962 callback(result_list);
965 id_list.forEach(function(id) { self._fetchLineitem(id, inner); });
968 this._fetchLineitem = function(liId, handler, force) {
970 var li = this.liCache[liId];
971 if(li && li.marc() && li.lineitem_details() && !force)
974 fieldmapper.standardRequest(
975 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
978 params: [self.authtoken, liId, {
980 flesh_cancel_reason: true,
981 flesh_li_details: true,
983 flesh_fund_debit: true }],
985 oncomplete: function(r) {
986 var li = openils.Util.readResponse(r);
987 self.liCache[liId] = li;
994 this._drawInfo = function(li) {
996 acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
999 openils.Util.hide('acq-lit-marc-order-record-label');
1000 openils.Util.hide(acqLitEditOrderMarc.domNode);
1001 openils.Util.show('acq-lit-marc-real-record-label');
1003 openils.Util.show('acq-lit-marc-order-record-label');
1004 openils.Util.show(acqLitEditOrderMarc.domNode);
1005 openils.Util.hide('acq-lit-marc-real-record-label');
1008 this.drawMarcHTML(li);
1009 this.infoTbody = dojo.byId('acq-lit-info-tbody');
1012 this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
1013 while(this.infoTbody.childNodes[0])
1014 this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
1016 for(var i = 0; i < li.attributes().length; i++) {
1017 var attr = li.attributes()[i];
1018 var row = this.infoRow.cloneNode(true);
1020 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
1021 var name = openils.acq.Lineitem.attrDefs[type].filter(
1023 return (a.code() == attr.attr_name());
1025 ).pop().description();
1027 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
1028 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
1029 this.infoTbody.appendChild(row);
1032 if (!this._isRelatedViewer) {
1033 nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
1034 oilsBasePath + "/acq/lineitem/related/" + li.id();
1039 this.generateMakeRecTab = function(bib_id,default_view, row) {
1043 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
1046 show_nav_buttons : true,
1047 show_print_button : true,
1048 opac_url : xulG.url_prefix(xulG.urls.opac_rdetail + bib_id),
1049 default_view : default_view
1053 if(row) nodeByName("action_none", row).selected = true;
1057 this.drawMarcHTML = function(li) {
1058 var params = [null, true, li.marc()];
1060 params = [li.eg_bib_id(), true];
1062 fieldmapper.standardRequest(
1063 ['open-ils.search', 'open-ils.search.biblio.record.html'],
1066 oncomplete: function(r) {
1067 dojo.byId('acq-lit-marc-div').innerHTML =
1068 openils.Util.readResponse(r);
1074 this.drawCopies = function(liId, force_fetch) {
1075 if (typeof force_fetch == "undefined")
1076 force_fetch = false;
1078 openils.acq.Lineitem.fetchAndRender(liId, {},
1079 function(li, html) {
1080 dojo.byId('acq-lit-copies-li-summary').innerHTML = html;
1084 this.show('copies');
1086 this.copyCache = {};
1087 this.copyWidgetCache = {};
1088 this.oldCopyWidgetCache = {};
1089 this.virtDfaCounts = {};
1090 this.realDfaCache = {};
1093 acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
1094 acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
1095 acqLitCopyCountInput.attr('value', '0');
1097 while(this.copyTbody.childNodes[0])
1098 this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
1100 this._drawBatchCopyWidgets();
1102 this._drawDistribApplied(liId);
1104 this._fetchDistribFormulas(
1106 openils.acq.Lineitem.fetchAttrDefs(
1108 self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch);
1115 this._saveDistribAppliedTemplates = function() {
1116 if (!this._appliedDistribTemplate) {
1117 this._appliedDistribTemplate =
1118 dojo.byId("acq-lit-distrib-applied-tbody").
1119 removeChild(dojo.byId("acq-lit-distrib-applied-row"));
1120 dojo.attr(this._appliedDistribTemplate, "id");
1124 this._drawDistribApplied = function(liId) {
1125 /* Build this table while hidden to prevent rendering artifacts */
1126 openils.Util.hide("acq-lit-distrib-applied-tbody");
1128 this._saveDistribAppliedTemplates();
1130 /* Remove any rows in the table from previous populations */
1131 dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
1132 forEach(dojo.destroy);
1134 /* Unregister all dijits previously created (for some reason this isn't
1135 * covered by the above destroy calls). */
1136 dijit.registry.forEach(
1137 function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
1140 /* Populate the table with our liId */
1142 fieldmapper.standardRequest(
1144 "open-ils.acq.distribution_formula_application.ranged.retrieve"],
1147 "params": [self.authtoken, liId],
1148 "onresponse": function(r) {
1149 var dfa = openils.Util.readResponse(r);
1152 self.realDfaCache[dfa.id()] = dfa;
1153 self._drawDistribAppliedUnit(dfa);
1156 "oncomplete": function() {
1157 /* Reveal built table */
1160 "acq-lit-distrib-applied-tbody", "table-row-group"
1168 this._drawDistribAppliedUnit = function(dfa) {
1169 var new_row = false;
1170 var row = dojo.query(
1171 'tr[formula="' + dfa.formula().id() + '"]',
1172 "acq-lit-distrib-applied-tbody"
1177 row = dojo.clone(this._appliedDistribTemplate);
1178 dojo.attr(row, "formula", dfa.formula().id());
1179 dojo.query("th", row)[0].innerHTML = dfa.formula().name();
1182 var td = dojo.query("td", row)[0];
1184 dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1185 dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1188 dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1190 new dijit.form.Button(
1192 "onClick": function() {
1193 if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1194 self.deleteDfa(dfa);
1197 /* XXX I /cannot/ make the following work in as a CSS class
1198 * for some reason. So frustrating... */
1199 "style": function(id) {
1201 "font-weight: bold; color: #c00;" :
1203 }(dfa.id()) + "margin: 0 6px;display: inline;"
1204 }, "dfa-button-" + dfa.id()
1208 "connectId": ["dfa-button-" + dfa.id()],
1209 "label": dojo.string.substitute(
1210 localeStrings.DFA_TIP, dfa.id() > 0 ? [
1211 openils.User.formalName(dfa.creator()),
1212 dojo.date.locale.format(
1213 dojo.date.stamp.fromISOString(dfa.create_time()),
1214 {"formatLength":"short"}
1216 ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
1218 }, "dfa-tip-" + dfa.id()
1222 this.deleteDfa = function(dfa) {
1223 if (dfa.id() > 0) { /* real */
1224 this.pcrud.eliminate(
1227 "oncomplete": function() {
1228 self._removeDistribApplied(dfa.id());
1229 delete self.realDfaCache[dfa.id()];
1233 } else { /* virtual */
1234 if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
1235 this.virtDfaCounts[dfa.formula().id()] = 0;
1236 /* hasn't been saved yet, so no need to do anything server side */
1237 this._removeDistribApplied(dfa.id());
1242 this._removeDistribApplied = function(dfaId) {
1243 var re = new RegExp("^dfa-\\w+-" + String(dfaId));
1244 dijit.registry.forEach(
1245 function(w) { if (re.test(w.id)) w.destroyRecursive(); }
1247 this._removeDistribAppliedEmptyRows();
1250 this._removeAllDistribAppliedVirtual = function() {
1251 /* Unregister dijits */
1252 dijit.registry.forEach(
1253 function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
1255 this._removeDistribAppliedEmptyRows();
1258 this._removeDistribAppliedEmptyRows = function() {
1259 /* Remove any rows with no DFA at all */
1260 dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
1262 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
1268 * Insert a new row into the distribution formula selection form
1270 this._addDistribFormulaRow = function() {
1273 if (!self.distribForms) {
1274 // no formulas, hide the form
1275 openils.Util.hide('acq-lit-distrib-formula-table');
1279 if(!this.distribFormulaTemplate)
1280 this.distribFormulaTemplate =
1281 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
1283 var row = this.distribFormulaTemplate.cloneNode(true);
1284 dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
1286 this.dfSelector = new dijit.form.FilteringSelect(
1287 {"labelAttr": "dynLabel", "labelType": "html"},
1288 nodeByName("selector", row)
1290 this._updateFormulaStore();
1291 this.dfSelector.fetchProperties =
1292 {"sort": [{"attribute": "use_count", "descending": true}]};
1294 var apply = new dijit.form.Button(
1295 {"label": localeStrings.APPLY},
1296 nodeByName('set_button', row)
1299 var reset = new dijit.form.Button(
1300 {"label": localeStrings.RESET_FORMULAE, "disabled": true},
1301 nodeByName("reset_button", row)
1304 dojo.connect(apply, 'onClick',
1306 var form_id = self.dfSelector.attr("value");
1307 if(!form_id) return;
1308 self._applyDistribFormula(form_id);
1309 reset.attr("disabled", false);
1313 dojo.connect(reset, 'onClick',
1315 self.restoreCopyFieldsBeforeDF();
1316 self.virtDfaCounts = {};
1317 self.virtDfaId = -1;
1319 self._updateFormulaStore();
1320 self._removeAllDistribAppliedVirtual();
1321 reset.attr("disabled", "true");
1328 * Applies a distrib formula to the current set of copies
1330 this._applyDistribFormula = function(formula) {
1331 if(!formula) return;
1333 formula = this.distribForms.filter(
1334 function(form) { return form.id() == formula; }
1337 var copyRows = dojo.query('tr', self.copyTbody);
1339 if (this.dfeOffset >= copyRows.length) {
1340 alert(localeStrings.OUT_OF_COPIES);
1344 var entries_applied = 0;
1346 var rowIndex = this.dfeOffset;
1347 rowIndex < copyRows.length;
1351 var row = copyRows[rowIndex];
1352 var copy_id = row.getAttribute('copy_id');
1353 var copyWidgets = this.copyWidgetCache[copy_id];
1354 var entryIndex = this.dfeOffset;
1357 // find the correct entry for the current row
1358 dojo.forEach(formula.entries(),
1361 entryIndex += e.item_count();
1362 if(entryIndex > rowIndex)
1370 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" +
1371 // entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
1374 this.saveCopyFieldsBeforeDF(copy_id);
1375 this._copy_fields_for_acqdf.forEach(
1377 if(entry[field]()) {
1378 copyWidgets[field].attr('value', (entry[field]()));
1385 if (entries_applied) {
1386 this.virtDfaCounts[formula.id()] =
1387 ++(this.virtDfaCounts[formula.id()]) || 1;
1388 this._updateFormulaStore();
1389 this._drawDistribAppliedUnit(
1391 var dfa = new acqdfa();
1392 dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
1395 this.dfeOffset += entries_applied;
1400 * This function updates the DF store for the dropdown so that use_counts
1401 * can reflect DF applications from this session before they're saved
1404 this._updateFormulaStore = function() {
1405 this.dfSelector.store = new dojo.data.ItemFileReadStore(
1407 "data": self._labelFormulasWithCounts(
1408 acqdf.toStoreData(self.distribForms)
1414 this.saveCopyFieldsBeforeDF = function(copy_id) {
1416 if (!this.oldCopyWidgetCache[copy_id]) {
1417 var copyWidgets = this.copyWidgetCache[copy_id];
1419 this.oldCopyWidgetCache[copy_id] = {};
1420 this._copy_fields_for_acqdf.forEach(
1422 self.oldCopyWidgetCache[copy_id][f] =
1423 copyWidgets[f].attr("value");
1429 this.restoreCopyFieldsBeforeDF = function() {
1431 for (var copy_id in this.oldCopyWidgetCache) {
1432 this._copy_fields_for_acqdf.forEach(
1434 self.copyWidgetCache[copy_id][f].attr(
1435 "value", self.oldCopyWidgetCache[copy_id][f]
1442 this._labelFormulasWithCounts = function(store_data) {
1443 for (var key in store_data.items) {
1444 var obj = store_data.items[key];
1445 obj.use_count = Number(obj.use_count); /* needed for sorting */
1447 if (this.virtDfaCounts[obj.id])
1448 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
1450 obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
1451 obj.use_count + "]</span> " + obj.name;
1457 * This method formerly would not refetch the DF formulas if they'd been
1458 * loaded already, but now it always re-fetches, since use_count changes.
1460 /** TODO: port distrib-formula selector to autofieldwidget+pcrud/dojo store */
1461 this._fetchDistribFormulas = function(onload) {
1462 fieldmapper.standardRequest(
1464 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
1467 "params": [openils.User.authtoken, 0, 500],
1468 "oncomplete": function(r) {
1469 self.distribForms = openils.Util.readResponse(r);
1470 if(!self.distribForms || self.distribForms.length == 0) {
1471 self.distribForms = [];
1473 self._addDistribFormulaRow();
1480 this._drawBatchCopyWidgets = function() {
1481 var row = this.copyBatchRow;
1482 dojo.forEach(liDetailBatchFields,
1484 if(self.copyBatchRowDrawn) {
1485 self.copyBatchWidgets[field].attr('value', null);
1487 var widget = new openils.widget.AutoFieldWidget({
1490 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1491 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1492 searchFilter : (field == 'fund') ? {"active": "t"} : null,
1493 parentNode : dojo.query('[name='+field+']', row)[0],
1494 orgLimitPerms : ['CREATE_PICKLIST'],
1497 "labelType": (field == "fund") ? "html" : null
1499 noCache: (field == "fund"),
1504 if (field == "fund" && w.store)
1505 self._ensureCSSFundClasses(w.store);
1506 self.copyBatchWidgets[field] = w;
1509 if (field == "fund") {
1511 widget.widget, "onChange", function(val) {
1512 self._updateFundSelectorStyle(widget, val);
1519 this.copyBatchRowDrawn = true;
1522 this.batchCopyUpdate = function() {
1524 for(var k in this.copyWidgetCache) {
1525 var cache = this.copyWidgetCache[k];
1526 dojo.forEach(liDetailBatchFields, function(f) {
1527 var newval = self.copyBatchWidgets[f].attr('value');
1528 if(newval) cache[f].attr('value', newval);
1533 this._drawCopies = function(li) {
1536 // this button sets the total number of copies for a given lineitem
1537 acqLitAddCopyCount.onClick = function() {
1538 var count = acqLitCopyCountInput.attr('value');
1541 while(self.copyCount() < count)
1544 // delete rows if necessary
1545 var diff = self.copyCount() - count;
1547 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
1548 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
1549 dojo.forEach(rows, function(row) {self.deleteCopy(row); });
1551 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1557 if(li.lineitem_details().length > 0) {
1558 dojo.forEach(li.lineitem_details(),
1560 self.addCopy(li, copy);
1568 this.copyCount = function() {
1570 for(var id in this.copyCache) {
1571 if(!this.copyCache[id].isdeleted())
1577 this.virtCopyId = -1;
1578 this.addCopy = function(li, copy) {
1579 var row = this.copyRow.cloneNode(true);
1580 this.copyTbody.appendChild(row);
1584 copy = new fieldmapper.acqlid();
1586 copy.id(this.virtCopyId--);
1587 copy.lineitem(li.id());
1590 this.copyCache[copy.id()] = copy;
1591 row.setAttribute('copy_id', copy.id());
1592 self.copyWidgetCache[copy.id()] = {};
1594 acqLitCopyCountInput.attr('value', self.copyCount()+'');
1596 var rcvr = copy.receiver();
1598 if (!userCache[rcvr]) {
1599 if(rcvr == openils.User.user.id()) {
1600 userCache[rcvr] = openils.User.user;
1602 userCache[rcvr] = fieldmapper.standardRequest(
1603 ['open-ils.actor', 'open-ils.actor.user.retrieve'],
1604 {params: [openils.User.authtoken, rcvr]}
1608 dojo.query('[name=receiver]', row)[0].innerHTML = userCache[rcvr].usrname();
1611 dojo.forEach(liDetailFields,
1614 if (field == "fund") {
1615 searchFilter = (copy.fund() ?
1616 {"-or": {"active": "t", "id": copy.fund()}} :
1619 searchFilter = null;
1622 var readOnly = false;
1624 // TODO: Add support for changing the owning_lib after real copies have been made.
1625 // owning_lib is order data as much as its item data
1626 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
1630 // TODO: add support for changing the fund after debits have been created
1631 // Note: invoicing allows the change
1632 if(copy.fund_debit() && field == 'fund') {
1637 var widget = new openils.widget.AutoFieldWidget({
1640 labelFormat : (field == 'fund') ? fundLabelFormat : null,
1641 searchFormat : (field == 'fund') ? fundSearchFormat : null,
1642 dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1643 searchFilter : searchFilter,
1644 noCache: (field == "fund"),
1646 parentNode : dojo.query('[name='+field+']', row)[0],
1647 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
1648 readOnly : readOnly,
1649 orgDefaultsToWs : true
1653 // make sure we capture the value from any async widgets
1656 if (field == "fund" && w.store)
1657 self._ensureCSSFundClasses(w.store);
1660 copy[field](ww.getFormattedValue())
1662 self.copyWidgetCache[copy.id()][field] = w;
1664 dojo.connect(w, 'onChange',
1666 if (field == "fund")
1667 self._updateFundSelectorStyle(widget, val);
1669 if (!readOnly && (copy.isnew() || val != copy[field]())) {
1670 // prevent setting ischanged() automatically on widget load for existing copies
1671 copy[field](widget.getFormattedValue())
1672 copy.ischanged(true);
1681 this.updateLidState(copy, row);
1684 this._ensureCSSFundClass = function(id) {
1685 if (!this.fundStyleSheet) {
1687 "style", {"type": "text/css"},
1688 document.getElementsByTagName("head")[0], "last"
1690 this.fundStyleSheet = document.styleSheets[
1691 document.styleSheets.length - 1
1695 var cn = "fund_" + id;
1696 if (!this.haveFundClass[cn]) {
1697 fieldmapper.standardRequest(
1698 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
1700 "params": [openils.User.authtoken, id],
1702 "oncomplete": function(r) {
1703 r = openils.Util.readResponse(r);
1704 self.fundBalanceState[id] = r;
1706 if (r[0] /* stop */)
1707 style = fundStyles.stop;
1708 else if (r[1] /* warning */)
1709 style = fundStyles.warning;
1710 self.fundStyleSheet.insertRule(
1711 "." + cn + " { " + style + " }",
1712 self.fundStyleSheet.cssRules.length
1714 self.haveFundClass[cn] = true;
1721 this._ensureCSSFundClasses = function(store) {
1723 "query": {"id": "*"},
1724 "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
1728 this._updateFundSelectorStyle = function(widget, fund_id) {
1729 openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
1730 openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
1733 this.updateLidState = function(copy, row) {
1736 if (typeof(row) == "undefined") {
1737 row = dojo.query('tr[copy_id="' + copy.id() + '"]', this.copyTbody)[0];
1741 var recv_link = nodeByName("receive", row);
1742 var unrecv_link = nodeByName("unreceive", row);
1743 var del_link = nodeByName("delete", row);
1744 var cxl_link = nodeByName("cancel", row);
1745 var claim_link = nodeByName("claim", row);
1746 var cxl_reason_link = nodeByName("cancel_reason", row);
1748 // by default, hide all the actions
1749 openils.Util.hide(del_link.parentNode);
1750 openils.Util.hide(recv_link);
1751 openils.Util.hide(unrecv_link);
1752 openils.Util.hide(cxl_link);
1753 openils.Util.hide(claim_link);
1754 openils.Util.hide(cxl_reason_link);
1756 if (copy.id() > 0) { // real copies (LIDs)
1758 if (copy.cancel_reason()) {
1760 /* --------- cancelled -------------------------- */
1762 /* XXX the following may leak memory in a long lived table:
1763 * dijits may not get destroyed... not positive. revisit. */
1764 var holds_reason = dojo.create(
1766 "style": "border-bottom: 1px dashed #000;",
1767 "innerHTML": "Cancelled" /* XXX [sic] and i18n */
1768 }, cxl_reason_link, "only"
1772 "label": "<em>" + copy.cancel_reason().label() +
1773 "</em><br />" + copy.cancel_reason().description(),
1774 "connectId": [holds_reason]
1775 }, dojo.create("span", null, cxl_reason_link, "last")
1777 openils.Util.show(cxl_reason_link, "inline");
1779 } else if (copy.recv_time()) {
1781 /* --------- received -------------------------- */
1783 openils.Util.show(unrecv_link, "inline");
1784 unrecv_link.onclick = function() {
1785 if (confirm(localeStrings.UNRECEIVE_LID))
1786 self.issueReceive(copy, /* rollback */ true);
1789 } else if (this.liCache[copy.lineitem()].state() == 'on-order') {
1791 /* --------- on order -------------------------- */
1793 openils.Util.show(recv_link, 'inline');
1794 openils.Util.show(cxl_link, "inline");
1796 recv_link.onclick = function() {
1797 if (self.checkLiAlerts(copy.lineitem()))
1798 self.issueReceive(copy);
1801 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
1805 /* --------- pre-order copies -------------------------- */
1807 del_link.onclick = function() { self.deleteCopy(row) };
1808 openils.Util.show(del_link.parentNode);
1814 /* --------- virtual copies -------------------------- */
1816 del_link.onclick = function() { self.deleteCopy(row) };
1817 openils.Util.show(del_link.parentNode);
1821 this.cancelLid = function(lid_id) {
1822 lidCancelDialog._lid_id = lid_id;
1823 openils.Util.show(lidCancelDialog.domNode.parentNode);
1824 lidCancelDialog.show();
1825 if (!lidCancelDialog._prepared) {
1826 var widget = new openils.widget.AutoFieldWidget({
1827 "fmField": "cancel_reason",
1828 "fmClass": "acqlid",
1829 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
1830 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1835 acqLidCancelButton.onClick = function() {
1836 if (w.attr("value")) {
1837 if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
1839 lidCancelDialog._lid_id,
1843 lidCancelDialog.hide();
1846 lidCancelDialog._prepared = true;
1852 this._cancelLid = function(lid_id, reason) {
1853 fieldmapper.standardRequest(
1854 ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
1855 "params": [openils.User.authtoken, lid_id, reason],
1857 "onresponse": function(r) {
1858 if (r = openils.Util.readResponse(r)) {
1860 for (var id in r.lid) {
1861 /* actually this should only iterate once */
1862 self.copyCache[id].cancel_reason(
1863 r.lid[id].cancel_reason
1865 self.updateLidState(self.copyCache[id]);
1874 this._confirmAlert = function(li, lin) {
1876 dojo.string.substitute(
1877 localeStrings.CONFIRM_LI_ALERT, [
1878 (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1879 "title", "lineitem_marc_attr_definition"
1881 /* XXX it's really better add a parameter and to adjust
1882 * the format string rather than do this concatenation
1883 * here, but if someone wants this for 2.2 in a hurry,
1884 * we can sidestep the problem of updating the strings
1885 * while the translators are working. */
1887 aou.findOrgUnit(lin.alert_text().owning_lib()).shortname() +
1889 lin.alert_text().code()
1891 lin.alert_text().description() || "",
1898 this.checkLiAlerts = function(li_id) {
1899 var li = this.liCache[li_id];
1901 var alert_notes = li.lineitem_notes().filter(
1902 function(o) { return Boolean(o.alert_text()); }
1905 /* this is _intentionally_ not done in a call to forEach() ... */
1906 for (var i = 0; i < alert_notes.length; i++) {
1907 if (this.noteAcks[alert_notes[i].id()])
1909 else if (!this._confirmAlert(li, alert_notes[i]))
1912 this.noteAcks[alert_notes[i].id()] = true;
1918 this.deleteCopy = function(row) {
1919 var copy = this.copyCache[row.getAttribute('copy_id')];
1920 copy.isdeleted(true);
1922 delete this.copyCache[copy.id()];
1923 this.copyTbody.removeChild(row);
1926 this._virtDfaCountsAsList = function() {
1928 for (var key in this.virtDfaCounts) {
1929 for (var i = 0; i < this.virtDfaCounts[key]; i++)
1935 this.confirmBreachedCopyFunds = function(copies) {
1936 var stop = 0, warning = 0;
1940 var state = self.fundBalanceState[o.fund()];
1941 if (state[0] /* stop */)
1943 else if (state[1] /* warning */)
1950 return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
1951 } else if (warning) {
1952 return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
1957 this.saveCopyChanges = function(liId) {
1963 for(var id in this.copyCache) {
1964 var c = this.copyCache[id];
1965 if(!c.isdeleted()) total++;
1966 if(c.isnew() || c.ischanged() || c.isdeleted()) {
1967 if(c.id() < 0) c.id(null);
1973 dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
1976 if (copies.length > 0) {
1977 if (!this.confirmBreachedCopyFunds(copies))
1980 if (typeof(this._copy_count_cb) == "function")
1981 this._copy_count_cb(liId, total);
1983 openils.Util.show("acq-lit-update-copies-progress");
1984 fieldmapper.standardRequest(
1985 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1987 params: [openils.User.authtoken, copies],
1988 onresponse: function(r) {
1989 var res = openils.Util.readResponse(r);
1990 litUpdateCopiesProgress.update(res);
1992 oncomplete: function() {
1993 self.drawCopies(liId, true /* force_fetch */);
1994 openils.Util.hide("acq-lit-update-copies-progress");
2000 var dfa_list = this._virtDfaCountsAsList();
2001 if (dfa_list.length > 0) {
2002 fieldmapper.standardRequest(
2004 "open-ils.acq.distribution_formula.record_application"],
2007 "params": [openils.User.authtoken, dfa_list, liId],
2008 "onresponse": function(r) {
2009 var res = openils.Util.readResponse(r);
2010 if (res && res.length < dfa_list.length)
2011 alert(localeStrings.DFA_NOT_ALL);
2015 this.virtDfaCounts = {};
2019 this._updateCreatePoPrepayCheckbox = function(prepay) {
2020 var prepay = openils.Util.isTrue(prepay);
2021 this._prepayRequiredByVendor = prepay;
2022 dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
2025 this._confirmPoPrepaySituation = function() {
2026 var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
2027 if (want_prepay != this._prepayRequiredByVendor) {
2030 localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
2031 localeStrings.VENDOR_SAYS_PREPAY_NEEDED
2038 this.applySelectedLiAction = function(action) {
2042 case 'delete_selected':
2043 this._deleteLiList(self.getSelected());
2046 case 'create_order':
2047 this._loadPOSelect();
2048 acqLitPoCreateDialog.show();
2051 case 'save_picklist':
2052 acqLitSavePlDialog.show();
2055 case 'selector_ready':
2057 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
2058 acqLitChangeLiStateDialog.show();
2066 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
2073 case 'rollback_receive_po':
2074 this.rollbackPoReceive();
2077 case 'create_assets':
2078 this.showAssetCreator();
2081 case 'export_attr_list':
2082 this.chooseExportAttr();
2085 case 'batch_apply_funds':
2086 this.applyBatchLiFunds();
2089 case 'add_brief_record':
2091 location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
2093 location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
2097 case "cancel_lineitems":
2098 this.maybeCancelLineitems();
2101 case "change_claim_policy":
2102 var li_list = this.getSelected();
2103 this.claimPolicyPicker.attr("value", null);
2104 liClaimPolicyDialog.show();
2105 liClaimPolicySave.onClick = function() {
2106 self.changeClaimPolicy(
2108 self.claimPolicyPicker.attr("value"),
2112 self.setClaimPolicyControl(li);
2113 self.reconsiderClaimControl(li);
2116 liClaimPolicyDialog.hide();
2124 this.changeClaimPolicy = function(li_list, value, callback) {
2126 function(li) { li.claim_policy(value); }
2128 fieldmapper.standardRequest(
2129 ["open-ils.acq", "open-ils.acq.lineitem.update"], {
2130 "params": [openils.User.authtoken, li_list],
2132 "oncomplete": function(r) {
2133 r = openils.Util.readResponse(r);
2134 if (callback) callback(r);
2140 this.showAssetCreator = function(onAssetsCreated) {
2141 if(!this.isPO) return;
2144 // first, let's see if this PO has any LI's that need to be merged/imported
2145 self.pcrud.search('jub', {purchase_order : this.isPO, eg_bib_id : null}, {
2147 oncomplete : function(r) {
2148 var resp = openils.Util.readResponse(r);
2149 if (resp && resp.length) {
2150 // PO has some non-linked jubs.
2152 self.show('asset-creator');
2153 if(!self.vlAgent.loaded)
2154 self.vlAgent.init();
2156 dojo.connect(assetCreatorButton, 'onClick',
2157 function() { self.createAssets(onAssetsCreated) });
2161 // all jubs linked, move on to asset creation
2162 self.createAssets(onAssetsCreated, true);
2168 this.createAssets = function(onAssetsCreated, noVl) {
2169 this.show('acq-lit-progress-numbers');
2171 var vlArgs = (noVl) ? {} : {vandelay : this.vlAgent.values()};
2172 fieldmapper.standardRequest(
2173 ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
2175 params: [this.authtoken, this.isPO, vlArgs],
2176 onresponse: function(r) {
2177 var resp = openils.Util.readResponse(r);
2178 self._updateProgressNumbers(resp, !Boolean(onAssetsCreated), onAssetsCreated);
2184 this.maybeCancelLineitems = function() {
2185 openils.Util.show("acq-lit-cancel-reason", "inline");
2186 if (!acqLitCancelLineitemsButton._prepared) {
2187 var widget = new openils.widget.AutoFieldWidget({
2188 "fmField": "cancel_reason",
2190 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
2191 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2196 acqLitCancelLineitemsButton.onClick = function() {
2197 if (w.attr("value")) {
2198 if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
2199 self._cancelLineitems(w.attr("value"));
2201 openils.Util.hide("acq-lit-cancel-reason");
2204 acqLitCancelLineitemsButton._prepared = true;
2210 this._cancelLineitems = function(reason) {
2211 var id_list = this.getSelected().map(function(o) { return o.id(); });
2212 fieldmapper.standardRequest(
2213 ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
2214 "params": [openils.User.authtoken, id_list, reason],
2216 "onresponse": function(r) {
2217 if (r = openils.Util.readResponse(r)) {
2219 for (var id in r.li) {
2220 self.liCache[id].state(r.li[id].state);
2221 self.liCache[id].cancel_reason(
2222 r.li[id].cancel_reason
2224 self.updateLiState(self.liCache[id]);
2227 if (r.lid && self.copyCache) {
2228 for (var id in r.lid) {
2229 if (self.copyCache[id]) {
2230 self.copyCache[id].cancel_reason(
2231 r.lid[id].cancel_reason
2233 self.updateLidState(self.copyCache[id]);
2243 this.chooseExportAttr = function() {
2244 if (!acqLitExportAttrSelector._li_setup) {
2246 acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
2248 "data": acqlimad.toStoreData(
2250 "acqlimad", {"code": li_exportable_attrs}
2255 acqLitExportAttrSelector.setValue();
2256 acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
2257 acqLitExportAttrSelector._li_setup = true;
2259 openils.Util.show("acq-lit-export-attr-holder", "inline");
2262 this.exportAttrList = function() {
2263 var attr_def = acqLitExportAttrSelector.item;
2264 var li_list = this.getSelected();
2265 var value_list = li_list.map(
2267 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2268 attr_def.code, "lineitem_marc_attr_definition"
2271 ).filter(function(attr) { return Boolean(attr); });
2273 if (value_list.length > 0) {
2274 if (value_list.length < li_list.length) {
2276 dojo.string.substitute(
2277 localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
2284 openils.XUL.contentToFileSaveDialog(
2285 value_list.join("\n"),
2286 localeStrings.EXPORT_SAVE_DIALOG_TITLE
2292 alert(dojo.string.substitute(
2293 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
2297 openils.Util.hide("acq-lit-export-attr-holder");
2300 this.printPO = function() {
2301 if(!this.isPO) return;
2302 progressDialog.show(true);
2303 fieldmapper.standardRequest(
2304 ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
2306 params: [this.authtoken, this.isPO, 'html'],
2307 oncomplete: function(r) {
2308 progressDialog.hide();
2309 var evt = openils.Util.readResponse(r);
2310 if(evt && evt.template_output()) {
2311 openils.Util.printHtmlString(evt.template_output().data());
2319 this.receivePO = function() {
2320 if (!this.isPO) return;
2322 for (var id in this.liCache) {
2323 /* assumption: liCache reflects exactly the
2324 * set of LIs that belong to our PO */
2325 if (this.liCache[id].state() != "received" &&
2326 !this.checkLiAlerts(id)) return;
2329 this.show('acq-lit-progress-numbers');
2331 fieldmapper.standardRequest(
2332 ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
2334 params: [this.authtoken, this.isPO],
2335 onresponse : function(r) {
2336 var resp = openils.Util.readResponse(r);
2337 self._updateProgressNumbers(resp, true);
2343 this.issueReceive = function(obj, rollback) {
2345 {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
2347 "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
2349 progressDialog.show(true);
2350 fieldmapper.standardRequest(
2351 ["open-ils.acq", method], {
2353 "params": [this.authtoken, obj.id()],
2354 "onresponse": function(r) {
2355 if (r = openils.Util.readResponse(r)) {
2356 self.fetchClaimInfo(
2357 part == "lineitem" ? obj.id() : obj.lineitem(),
2359 function() { self.handleReceive(r); }
2361 progressDialog.hide();
2369 * Handles the responses from receive and rollback ML calls.
2371 this.handleReceive = function(resp) {
2374 for (var li_id in resp.li) {
2375 for (var key in resp.li[li_id])
2376 self.liCache[li_id][key](resp.li[li_id][key]);
2377 self.updateLiState(self.liCache[li_id]);
2381 if (typeof(self.poUpdateCallback) == "function")
2382 self.poUpdateCallback(resp.po);
2385 for (var lid_id in resp.lid) {
2386 for (var key in resp.lid[lid_id])
2387 self.copyCache[lid_id][key](resp.lid[lid_id][key]);
2388 self.updateLidState(self.copyCache[lid_id]);
2394 this.rollbackPoReceive = function() {
2395 if(!this.isPO) return;
2396 if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
2397 this.show('acq-lit-progress-numbers');
2399 fieldmapper.standardRequest(
2400 ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
2402 params: [this.authtoken, this.isPO],
2403 onresponse : function(r) {
2404 var resp = openils.Util.readResponse(r);
2405 self._updateProgressNumbers(resp, true);
2411 this._updateProgressNumbers = function(resp, reloadOnComplete, onComplete) {
2412 this.vlAgent.handleResponse(resp,
2413 function(resp, res) {
2414 if(reloadOnComplete)
2415 location.href = location.href;
2417 onComplete(resp, res);
2423 this._createPO = function(fields) {
2424 var wantall = (fields.create_from == "all");
2426 /* If we're a picklist or purchase order already and the user wants
2427 * all lineitems, we might have pages' worth of lineitems haven't all
2428 * been loaded yet, so getSelected() won't find them. The server,
2429 * however, should know about all our lineitems, so let's ask the
2430 * server for a complete list.
2435 true, function(list) {
2436 self._createPOFromLineitems(fields, list);
2437 }, /* id_list */ true
2440 this._createPOFromLineitems(fields, this.getSelected(false, null, true /* id_list */));
2444 this._createPOFromLineitems = function(fields, selected) {
2445 if (selected.length == 0) return;
2448 var po = new fieldmapper.acqpo();
2449 po.provider(this.createPoProviderSelector.attr("value"));
2450 po.ordering_agency(this.createPoAgencySelector.attr("value"));
2451 po.prepayment_required(fields.prepayment_required[0] ? true : false);
2453 // if we're creating assets, delay the asset creation
2454 // until after the PO is created. This will allow us to
2455 // use showAssetCreator() directly.
2457 fieldmapper.standardRequest(
2458 ["open-ils.acq", "open-ils.acq.purchase_order.create"],
2461 openils.User.authtoken,
2462 po, {lineitems : selected}
2464 onresponse : function(r) {
2465 var resp = openils.Util.readResponse(r);
2466 if (resp.complete) {
2467 // self.isPO is needed for showAssetCreator();
2468 self.isPO = resp.purchase_order.id();
2469 var redir = oilsBasePath + "/acq/po/view/" + self.isPO;
2470 if (fields.create_assets[0]) {
2471 self.showAssetCreator(
2472 function() {location.href = redir}
2475 location.href = redir;
2484 this.batchFundWidget = null;
2486 this.applyBatchLiFunds = function() {
2488 var liIds = this.getSelected().map(function(li) { return li.id(); });
2489 if(liIds.length == 0) return; // warn?
2492 batchFundUpdateDialog.show();
2494 if(!this.batchFundWidget) {
2495 this.batchFundWidget = new openils.widget.AutoFieldWidget({
2497 selfReference : true,
2498 labelFormat : fundLabelFormat,
2499 searchFormat : fundSearchFormat,
2500 searchFilter : {"active": "t"},
2501 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
2502 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2503 dijitArgs : { "required": true, "labelType": "html" },
2506 this.batchFundWidget.build();
2509 dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
2510 dojo.connect(batchFundUpdateSubmit, 'onClick',
2513 // TODO: call .dry_run first to test thresholds
2514 fieldmapper.standardRequest(
2515 ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
2518 openils.User.authtoken,
2520 self.batchFundWidget.widget.attr('value')
2522 oncomplete : function(r) {
2523 var resp = openils.Util.readResponse(r);
2525 location.href = location.href;
2534 this._deleteLiList = function(list, idx) {
2535 if(idx == null) idx = 0;
2536 if(idx >= list.length) return;
2541 if (this.isPO && (li.state() == "on-order" || li.state() == "received")) {
2542 /* It makes little sense to delete a lineitem from a PO that has
2543 * already been marked 'on-order'. Especially if EDI is in use,
2544 * such a purchase order will probably have already been shipped
2545 * off to a vendor, and mucking with it at this point could leave
2546 * your data in a bad state that doesn't jive with reality.
2548 * I could see making this restriction even firmer.
2550 * I could also see adjusting the li state comparisons, extending
2551 * the comparison to the PO's state, and/or providing functions
2552 * that house the logic for comparing states in a single location.
2554 * Yes, this will be really annoying if you have selected a lot
2555 * of lineitems to cancel that have been ordered. You'll get a
2556 * confirm dialog for each one.
2559 if (!confirm(localeStrings.DEL_LI_FROM_PO)) {
2560 self._deleteLiList(list, ++idx); /* move on to next in list */
2565 fieldmapper.standardRequest(
2567 this.isPO ? 'open-ils.acq.purchase_order.lineitem.delete' : 'open-ils.acq.picklist.lineitem.delete'],
2569 params: [openils.User.authtoken, liId],
2570 oncomplete: function(r) {
2571 self.removeLineitem(liId);
2572 self._deleteLiList(list, ++idx);
2578 this.editOrderMarc = function(li) {
2580 /* To run in Firefox directly, must set signed.applets.codebase_principal_support
2581 to true in about:config */
2583 if(!openils.XUL.enableXPConnect()) return;
2585 if(openils.XUL.isXUL()) {
2586 win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
2588 win = window.open('/xul/server/cat/marcedit.xul');
2592 record : {marc : li.marc(), "rtype": "bre"},
2594 label: 'Save Record', // XXX I18N
2595 func: function(xmlString) {
2597 fieldmapper.standardRequest(
2598 ['open-ils.acq', 'open-ils.acq.lineitem.update'],
2600 params: [openils.User.authtoken, li],
2601 oncomplete: function(r) {
2602 openils.Util.readResponse(r);
2604 self.drawInfo(li.id())
2610 'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
2611 'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
2615 this._savePl = function(values) {
2617 (values.which == 'all'),
2618 function(list) { self._savePlFromLineitems(values, list); }
2622 this._savePlFromLineitems = function(values, selected) {
2623 openils.Util.show("acq-lit-generic-progress");
2625 if(values.new_name) {
2626 openils.acq.Picklist.create(
2627 {name: values.new_name},
2633 oilsBasePath + "/acq/picklist/view/" + id;
2638 } else if(values.existing_pl) {
2639 // update lineitems to use an existing picklist
2641 values.existing_pl, selected, 0,
2644 oilsBasePath + "/acq/picklist/view/" +
2651 this._updateLiState = function(values, state) {
2652 progressDialog.show(true);
2654 (values.which == 'all'),
2656 self._updateLiStateFromLineitems(values, state, list);
2661 this._updateLiStateFromLineitems = function(values, state, selected) {
2662 if(!selected.length) return;
2663 dojo.forEach(selected, function(li) {li.state(state);});
2664 self._updateLiList(null, selected, 0,
2665 // TODO consider inline updates for efficiency
2666 function() { location.href = location.href }
2670 this._updateLiList = function(pl, list, idx, oncomplete) {
2671 if(idx >= list.length) return oncomplete();
2673 if(pl != null) li.picklist(pl);
2674 litGenericProgress.update({maximum: list.length, progress: idx});
2675 new openils.acq.Lineitem({lineitem:li}).update(
2677 self._updateLiList(pl, list, ++idx, oncomplete);
2682 this._loadPOSelect = function() {
2683 if (!this.createPoProviderSelector) {
2684 var widget = new openils.widget.AutoFieldWidget({
2685 "fmField": "provider",
2687 "searchFilter": {"active": "t"},
2688 "parentNode": dojo.byId("acq-lit-po-provider"),
2690 "onChange": function() {
2692 self._updateCreatePoPrepayCheckbox(
2693 this.item.prepayment_required()
2699 widget.build(function(w) { self.createPoProviderSelector = w; });
2702 if (!this.createPoAgencySelector) {
2703 var widget = new openils.widget.AutoFieldWidget({
2704 "fmField": "ordering_agency",
2706 "parentNode": dojo.byId("acq-lit-po-agency"),
2707 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2709 widget.build(function(w) { self.createPoAgencySelector = w; });
2713 this.showRealCopyEditUI = function(li) {
2718 this._fetchLineitem(li.id(),
2720 li = self.liCache[li.id()] = fullLi;
2724 id : li.lineitem_details().map(
2725 function(item) { return item.eg_copy_id() }
2729 oncomplete : function(r) {
2731 var r_list = openils.Util.readResponse( r );
2732 for (var i = 0; i < r_list.length; i++) {
2733 var copy = r_list[i];
2734 var volId = copy.call_number();
2735 var volume = self.volCache[volId];
2737 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2739 copy.call_number(volume);
2740 copyList.push(copy);
2743 xulG.volume_item_creator( { 'existing_copies' : copyList } );
2746 alert('error in oncomplete: ' + E);
2755 this.drawBibFinder = function(li) {
2758 var liWrapper = new openils.acq.Lineitem({lineitem:li});
2761 ['isbn', 'upc', 'issn', 'title', 'author'],
2763 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
2765 if(field == 'title' || field == 'author') {
2766 query += field +':' + val + ' ';
2768 query += 'identifier|' + field + ':' + val + ' ';
2775 oilsBasePath + '/acq/lineitem/findbib?query=' + escape(query),
2776 '', 'resizable,scrollbars=1');
2778 win.window.recordFound = function(bibId) {
2781 var attrs = li.attributes();
2782 li.attributes(null);
2783 li.eg_bib_id(bibId);
2785 fieldmapper.standardRequest(
2786 ["open-ils.acq", "open-ils.acq.lineitem.update"],
2788 "params": [openils.User.authtoken, li],
2790 "oncomplete": function(r) {
2791 if(openils.Util.readResponse(r)) {
2792 location.href = location.href;