]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/acq/common/li_table.js
Acq: fix a bug that sometimes prevents the general search page from loading
[Evergreen.git] / Open-ILS / web / js / ui / default / acq / common / li_table.js
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
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');
21 }
22 const XUL_OPAC_WRAPPER = 'chrome://open_ils_staff_client/content/cat/opac.xul';
23 var li_exportable_attrs = ["issn", "isbn", "upc"];
24
25 var fundLabelFormat = [
26     '<span class="fund_${0}">${1} (${2})</span>', 'id', 'code', 'year'
27 ];
28 var fundSearchFormat = ['${0} (${1})', 'code', 'year'];
29
30 function nodeByName(name, context) {
31     return dojo.query('[name='+name+']', context)[0];
32 }
33
34 // for caching linked users.  e.g. lineitem_detail.receiver
35 var userCache = {};
36
37 var liDetailBatchFields = ['fund', 'owning_lib', 'location', 'collection_code', 'circ_modifier', 'cn_label'];
38 var liDetailFields = liDetailBatchFields.concat(['barcode', 'note']);
39 var fundStyles = {
40     "stop": "color: #c00; font-weight: bold;",
41     "warning": "color: #c93;"
42 };
43
44 function AcqLiTable() {
45
46     var self = this;
47     this.liCache = {};
48     this.plCache = {};
49     this.poCache = {};
50     this.relCache = {};
51     this.haveFundClass = {}
52     this.fundBalanceState = {};
53     this.realDfaCache = {};
54     this.virtDfaCounts = {};
55     this.virtDfaId = -1;
56     this.dfeOffset = 0;
57     this.claimEligibleLidByLi = {};
58     this.claimEligibleLid = {};
59     this.toggleState = false;
60     this.tbody = dojo.byId('acq-lit-tbody');
61     this.selectors = [];
62     this.noteAcks = {};
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);
80         }
81     );
82
83     dojo.byId("acq-lit-li-actions-selector").onchange = function() { 
84         self.applySelectedLiAction(this.options[this.selectedIndex].value);
85         this.selectedIndex = 0;
86     };
87
88     acqLitCreatePoSubmit.onClick = function() {
89         if (self._confirmPoPrepaySituation()) {
90             acqLitPoCreateDialog.hide();
91             self._createPO(acqLitPoCreateDialog.getValues());
92         } else {
93             return false;
94         }
95     }
96
97     acqLitSavePlButton.onClick = function() {
98         acqLitSavePlDialog.hide();
99         self._savePl(acqLitSavePlDialog.getValues());
100     }
101
102     acqLitCancelLiStateButton.onClick = function() {
103         acqLitChangeLiStateDialog.hide();
104     }
105     acqLitSaveLiStateButton.onClick = function() {
106         acqLitChangeLiStateDialog.hide();
107         self._updateLiState(acqLitChangeLiStateDialog.getValues(), acqLitChangeLiStateDialog.attr('state'));
108     }
109
110
111     dojo.byId('acq-lit-select-toggle').onclick = function(){self.toggleSelect()};
112     dojo.byId('acq-lit-info-back-button').onclick = function(){self.show('list')};
113     dojo.byId('acq-lit-copies-back-button').onclick = function(){self.show('list')};
114     dojo.byId('acq-lit-notes-back-button').onclick = function(){self.show('list')};
115     dojo.byId('acq-lit-real-copies-back-button').onclick = function(){self.show('list')};
116
117     this.reset = function(keep_selectors) {
118         while(self.tbody.childNodes[0])
119             self.tbody.removeChild(self.tbody.childNodes[0]);
120         self.noteAcks = {};
121         self.relCache = {};
122
123         if (!keep_selectors)
124             self.selectors = [];
125     };
126     
127     this.setNext = function(handler) {
128         var link = dojo.byId('acq-lit-next');
129         if(handler) {
130             dojo.style(link, 'visibility', 'visible');
131             link.onclick = handler;
132         } else {
133             dojo.style(link, 'visibility', 'hidden');
134         }
135     };
136
137     this.setPrev = function(handler) {
138         var link = dojo.byId('acq-lit-prev');
139         if(handler) {
140             dojo.style(link, 'visibility', 'visible'); 
141             link.onclick = handler; 
142         } else {
143             dojo.style(link, 'visibility', 'hidden');
144         }
145     };
146
147     this.show = function(div) {
148         openils.Util.hide('acq-lit-table-div');
149         openils.Util.hide('acq-lit-info-div');
150         openils.Util.hide('acq-lit-li-details');
151         openils.Util.hide('acq-lit-notes-div');
152         openils.Util.hide('acq-lit-real-copies-div');
153         switch(div) {
154             case 'list':
155                 openils.Util.show('acq-lit-table-div');
156                 break;
157             case 'info':
158                 openils.Util.show('acq-lit-info-div');
159                 break;
160             case 'copies':
161                 openils.Util.show('acq-lit-li-details');
162                 break;
163             case 'real-copies':
164                 openils.Util.show('acq-lit-real-copies-div');
165                 break;
166             case 'notes':
167                 openils.Util.show('acq-lit-notes-div');
168                 break;
169             default:
170                 if(div) 
171                     openils.Util.show(div);
172         }
173     }
174
175     this.hide = function() {
176         this.show(null);
177     }
178
179     this.toggleSelect = function() {
180         if(self.toggleState) 
181             dojo.forEach(self.selectors, function(i){i.checked = false});
182         else 
183             dojo.forEach(self.selectors, function(i){i.checked = true});
184         self.toggleState = !self.toggleState;
185     };
186
187
188     this.getAll = function(callback, id_only) {
189         /* For some uses of the li table, we may not really know about "all"
190          * the lineitems that the user thinks we know about. If we're a paged
191          * picklist, for example, we only know about the lineitems we've
192          * displayed, but not necessarily all the lineitems on the picklist.
193          * So we reach out to pcrud to inform us.
194          */
195
196         var oncomplete = function(r) {
197             var id_list = openils.Util.readResponse(r);
198             if (id_only)
199                 callback(id_list);
200             else
201                 self.fetchLineitemsById(id_list, callback);
202         };
203
204         if (this.isPL) {
205             this.pcrud.search(
206                 "jub", {"picklist": this.isPL}, {
207                     "id_list": true,    /* sic, even if id_only */
208                     "async": true,
209                     "oncomplete": oncomplete
210                 }
211             );
212             return;
213         } else if (this.isPO) {
214             this.pcrud.search(
215                 "jub", {"purchase_order": this.isPO}, {
216                     "id_list": true,
217                     "async": true,
218                     "oncomplete": oncomplete
219                 }
220             );
221             return;
222         } else if (this.isUni && this.pager) {
223             this.pager.getAllLineitemIDs(oncomplete);
224             return;
225         }
226
227         /* If execution reaches this point, we don't need or can't perform
228          * any special tricks to find out the "real" list of "all" lineitems
229          * in this context, so we fall back to the old method.
230          */
231         callback(this.getSelected(true, null, id_only));
232     };
233
234     /** @param all If true, assume all are selected */
235     this.getSelected = function(
236         all,
237         callback /* If you want a "good" idea of "all" lineitems, you must
238         provide a callback that accepts an array parameter, rather than
239         relying on the return value of this method itself. */,
240         id_only
241     ) {
242         if (all && callback)
243             return this.getAll(callback, id_only);
244
245         var indices = {};   /* use to uniqify. needed in paging situations. */
246         dojo.forEach(this.selectors,
247             function(i) { 
248                 if(i.checked || all)
249                     indices[i.parentNode.parentNode.getAttribute('li')] = true;
250             }
251         );
252
253         var result = openils.Util.objectProperties(indices);
254
255         if (!id_only)
256             result = result.map(function(liId) { return self.liCache[liId]; });
257
258         if (callback)
259             callback(result);
260         else
261             return result;
262     };
263
264     this.setRowAttr = function(td, liWrapper, field, type) {
265         var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
266         td.appendChild(document.createTextNode(val));
267     };
268
269     this.setClaimPolicyControl = function(li, row) {
270         if (!self.claimPolicyPicker) {
271             self.claimPolicyPicker = true; /* prevents a race condition */
272             new openils.widget.AutoFieldWidget({
273                 "parentNode": "acq-lit-li-claim-policy",
274                 "fmClass": "acqclp",
275                 "selfReference": true,
276                 "dijitArgs": {"required": true}
277             }).build(function(w) { self.claimPolicyPicker = w; });
278         }
279
280         if (!row) row = this._findLiRow(li);
281
282         var actViewPolicy = nodeByName("action_view_claim_policy", row);
283         if (li.claim_policy())
284             actViewPolicy.innerHTML = localeStrings.CHANGE_CLAIM_POLICY;
285
286         if (!actViewPolicy.onclick) {
287             actViewPolicy.onclick = function() {
288                 if (li.claim_policy())
289                     self.claimPolicyPicker.attr("value", li.claim_policy());
290                 liClaimPolicyDialog.show();
291                 liClaimPolicySave.onClick = function() {
292                     self.changeClaimPolicy(
293                         [li], self.claimPolicyPicker.attr("value"),
294                         function() {
295                             self.setClaimPolicyControl(li, row);
296                             self.reconsiderClaimControl(li, row);
297                             liClaimPolicyDialog.hide();
298                         }
299                     );
300                 }
301             };
302         }
303     };
304
305     this.fetchClaimInfo = function(liId, force, callback, row) {
306         this._fetchLineitem(
307             liId, function(full) {
308                 self.liCache[full.id()] = full;
309                 self.checkClaimEligibility(full, callback, row);
310             }, force
311         );
312     }
313
314     /**
315      * Inserts a single lineitem into the growing table of lineitems
316      * @param {Object} li The lineitem object to insert
317      */
318     this.addLineitem = function(li, skip_final_placement) {
319         this.liCache[li.id()] = li;
320
321         // insert the row right away so that final order isn't
322         // dependent on how long subsequent async request take
323         // for a given line item
324         var row = self.rowTemplate.cloneNode(true);
325         if (!skip_final_placement) {
326             self.tbody.appendChild(row);
327         }
328         self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
329
330         // sort the lineitem notes on edit_time
331         if(!li.lineitem_notes()) li.lineitem_notes([]);
332
333         var liWrapper = new openils.acq.Lineitem({lineitem:li});
334         row.setAttribute('li', li.id());
335         var tds = dojo.query('[attr]', row);
336         dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
337         dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
338
339         var identifier =
340             liWrapper.findAttr("isbn", "lineitem_marc_attr_definition") ||
341             liWrapper.findAttr("upc", "lineitem_marc_attr_definition");
342
343         // XXX media prefix for added content
344         if (identifier) {
345             nodeByName("jacket", row).setAttribute(
346                 "src", "/opac/extras/ac/jacket/small/" + identifier
347             );
348         }
349
350         nodeByName("liid", row).innerHTML += li.id();
351
352         if(li.eg_bib_id()) {
353             openils.Util.show(nodeByName('catalog', row), 'inline');
354             nodeByName("catalog_link", row).onclick = this.generateMakeRecTab(li.eg_bib_id());
355         } else {
356             openils.Util.show(nodeByName('link_to_catalog', row), 'inline');
357             nodeByName("link_to_catalog_link", row).onclick = function() { self.drawBibFinder(li) };
358         }
359
360         nodeByName("worksheet_link", row).href =
361             oilsBasePath + "/acq/lineitem/worksheet/" + li.id();
362
363         nodeByName("show_requests_link", row).href =
364             oilsBasePath + "/acq/picklist/user_request?lineitem=" + li.id();
365
366         dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
367         dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
368         dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
369
370         if (!this.skipInitialEligibilityCheck)
371             this.fetchClaimInfo(
372                 li.id(),
373                 false,
374                 function(full) { self.setClaimPolicyControl(full, row) },
375                 row
376             );
377
378         this.updateLiNotesCount(li, row);
379
380         // show which PO this lineitem is a member of
381         if(li.purchase_order() && !this.isPO) {
382             var po = 
383                 this.poCache[li.purchase_order()] =
384                 this.poCache[li.purchase_order()] ||
385                 fieldmapper.standardRequest(
386                     ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
387                     {params: [
388                         this.authtoken, li.purchase_order(), {
389                             "flesh_price_summary": true,
390                             "flesh_lineitem_count": true
391                         }
392                     ]});
393             if(po && !this.isMeta) {
394                 openils.Util.show(nodeByName('po', row), 'inline');
395                 var link = nodeByName('po_link', row);
396                 link.setAttribute('href', oilsBasePath + '/acq/po/view/' + li.purchase_order());
397                 link.innerHTML += po.name();
398             }
399         }
400
401         // show which picklist this lineitem is a member of
402         if(li.picklist() && (this.isPO || this.isMeta || this.isUni)) {
403             var pl = 
404                 this.plCache[li.picklist()] = 
405                 this.plCache[li.picklist()] || 
406                 fieldmapper.standardRequest(
407                     ['open-ils.acq', 'open-ils.acq.picklist.retrieve.authoritative'],
408                     {params: [this.authtoken, li.picklist()]});
409             if (pl) {
410                 if (pl.name() == "") {
411                     openils.Util.show(nodeByName("bib_origin", row), "inline");
412
413                 } else {
414
415                     openils.Util.show(nodeByName('pl', row), 'inline');
416                     var link = nodeByName('pl_link', row);
417                     link.setAttribute('href', oilsBasePath + '/acq/picklist/view/' + li.picklist());
418                     link.innerHTML += pl.name();
419                 }
420             }
421         }
422
423         var countNode = nodeByName('count', row);
424         var count = li.item_count() || 0;
425         if (typeof(this._copy_count_cb) == "function") {
426             this._copy_count_cb(li.id(), count);
427         }
428         countNode.innerHTML = count;
429         countNode.id = 'acq-lit-copy-count-label-' + li.id();
430
431         // lineitem price
432         var priceInput = dojo.query('[name=price]', row)[0];
433         priceInput.value = li.estimated_unit_price() || '';
434         priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
435
436         // show either "mark received" or "unreceive" as appropriate
437         this.updateLiState(li, row);
438
439         if (skip_final_placement) {
440             return row;
441         }
442     };
443
444     this._liCountClaims = function(li) {
445         var total = 0;
446         for (var i = 0; i < li.lineitem_details().length; i++)
447             total += li.lineitem_details()[i].claims().length;
448         return total;
449     };
450
451     this._findLiRow = function(li) {
452         return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
453     };
454
455     this.reconsiderClaimControl = function(li, row) {
456         if (!row) row = this._findLiRow(li);
457         var option = nodeByName("action_manage_claims", row);
458         var eligible = this.claimEligibleLidByLi[li.id()].length;
459         var count = this._liCountClaims(li);
460
461         option.disabled = !(count || eligible);
462         option.innerHTML =
463             dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
464         option.onclick = function() { self.claimDialog.show(li); };
465     };
466
467     this.clearEligibility = function(li) {
468         this.claimEligibleLidByLi[li.id()] = [];
469
470         if (li.lineitem_details()) {
471             li.lineitem_details().forEach(
472                 function(lid) { delete self.claimEligibleLid[lid.id()]; }
473             );
474         }
475
476         if (this.copyCache) {
477             var to_del = [];
478             for (var k in this.copyCache) {
479                 if (this.copyCache[k].lineitem() == li.id())
480                     to_del.push(k);
481             }
482             to_del.forEach(
483                 function(k) { delete self.claimEligibleLid[k]; }
484             );
485         }
486     };
487
488     this.checkClaimEligibility = function(li, callback, row) {
489         /* Assume always eligible, i.e. from this interface we don't care about
490          * claim eligibility any more. this is where the user would force a
491          * claime. */
492         this.clearEligibility(li);
493         this.claimEligibleLidByLi[li.id()] = li.lineitem_details().map(
494             function(lid) { return lid.id(); }
495         );
496         li.lineitem_details().forEach(
497             function(lid) { self.claimEligibleLid[lid.id()] = true; }
498         );
499         this.reconsiderClaimControl(li, row);
500         if (callback) callback(li);
501         /*
502         this.clearEligibility(li);
503         fieldmapper.standardRequest(
504             ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
505                 "params": [openils.User.authtoken, {"lineitem": li.id()}],
506                 "async": true,
507                 "onresponse": function(r) {
508                     if (r = openils.Util.readResponse(r)) {
509                         self.claimEligibleLidByLi[li.id()].push(
510                             r.lineitem_detail()
511                         );
512                         self.claimEligibleLid[r.lineitem_detail()] = true;
513                     }
514                 },
515                 "oncomplete": function() {
516                     self.reconsiderClaimControl(li, row);
517                     if (typeof(callback) == "function")
518                         callback();
519                 }
520             }
521         );
522         */
523     };
524
525     this.updateLiNotesCount = function(li, row) {
526         if (!row) row = this._findLiRow(li);
527
528         var has_notes = (li.lineitem_notes().filter(
529                 function(o) { return Boolean (o.alert_text()); }
530             ).length > 0);
531
532         /* U+2691 is the code point for a filled-in flag character */
533         nodeByName("notes_alert_flag", row).innerHTML =
534              has_notes ? "&#x2691;" : "";
535         nodeByName("noteslink", row).style.fontStyle =
536             has_notes ? "italic" : "normal";
537         nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
538     };
539
540     /* XXX NOT related to _updateLiState(). rethink */
541     this.updateLiState = function(li, row) {
542         if (!row) row = this._findLiRow(li);
543
544         var actReceive = nodeByName("action_mark_recv", row);
545         var actUnRecv = nodeByName("action_mark_unrecv", row);
546         var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
547         var actHoldingsMaint = nodeByName("action_holdings_maint", row);
548
549         var actNewInvoice = nodeByName('action_new_invoice', row);
550         var actLinkInvoice = nodeByName('action_link_invoice', row);
551         var actViewInvoice = nodeByName('action_view_invoice', row);
552
553         nodeByName('action_view_history', row).onclick = 
554             function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
555
556         var state_cell = nodeByName("li_state", row);
557
558         if (li.state() == "cancelled") {
559             if (typeof li.cancel_reason() == "object") {
560                 var holds_state = dojo.create(
561                     "span", {
562                         "style": "border-bottom: 1px dashed #000;",
563                         "innerHTML": li.state()
564                     }, state_cell, "only"
565                 );
566                 new dijit.Tooltip(
567                     {
568                         "label": "<em>" + li.cancel_reason().label() +
569                             "</em><br />" + li.cancel_reason().description(),
570                         "connectId": [holds_state]
571                     }, dojo.create("span", null, state_cell, "last")
572                 );
573             } else {
574                 state_cell.innerHTML = li.state(); // TODO i18n state labels
575             }
576         } else {
577             state_cell.innerHTML = li.state(); // TODO i18n state labels
578         }
579
580
581         /* handle row coloring for based on LI state */
582         openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
583         openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
584
585         /* handle links that appear/disappear based on whether LI is received */
586         if (this.isPO) {
587             var self = this;
588
589             actNewInvoice.onclick = function() {
590                 location.href = oilsBasePath + '/acq/invoice/view?create=1&attach_li=' + li.id();
591                 nodeByName("action_none", row).selected = true;
592             };
593             actLinkInvoice.onclick = function() {
594                 if (!self.invoiceLinkDialogManager) {
595                     self.invoiceLinkDialogManager =
596                         new InvoiceLinkDialogManager("li");
597                 }
598                 self.invoiceLinkDialogManager.target = li;
599                 acqLitLinkInvoiceDialog.show();
600                 nodeByName("action_none", row).selected = true;
601             };
602             actViewInvoice.onclick = function() {
603                 location.href = oilsBasePath +
604                     "/acq/search/unified?so=" +
605                     base64Encode({"jub":[{"id": li.id()}]}) +
606                     "&rt=invoice";
607                 nodeByName("action_none", row).selected = true;
608             };
609
610             actNewInvoice.disabled = false;
611             actLinkInvoice.disabled = false;
612             actViewInvoice.disabled = false;
613
614             switch(li.state()) {
615                 case "on-order":
616                     actReceive.disabled = false;
617                     actReceive.onclick = function() {
618                         if (self.checkLiAlerts(li.id()))
619                             self.issueReceive(li);
620                         nodeByName("action_none", row).selected = true;
621                     };
622                     return;
623
624                 case "received":
625                     actUnRecv.disabled = false;
626                     actUnRecv.onclick = function() {
627                         if (confirm(localeStrings.UNRECEIVE_LI))
628                             self.issueReceive(li, /* rollback */ true);
629                         nodeByName("action_none", row).selected = true;
630                     };
631                     // TODO we should allow editing before receipt, in which case the
632                     // test should be "if 1 or more real (acp) copies exist
633                     actUpdateBarcodes.disabled = false;
634                     actUpdateBarcodes.onclick = function() {
635                         self.showRealCopyEditUI(li);
636                         nodeByName("action_none", row).selected = true;
637                     }
638                     actHoldingsMaint.disabled = false;
639                     actHoldingsMaint.onclick = self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
640
641                     return;
642             }
643         }
644     };
645
646
647     this._setAlertStore = function() {
648         acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
649             {
650                 "data": acqliat.toStoreData(
651                     this.pcrud.search(
652                         "acqliat", {"id": {"!=": null}}
653                     )
654                 )
655             }
656         );
657         acqLitAlertAlertText.setValue(); /* make the store "live" */
658         acqLitAlertAlertText._store_ready = true;
659     };
660
661     /**
662      * Draws and shows the lineitem notes pane
663      */
664     this.drawLiNotes = function(li) {
665         var self = this;
666
667         if (!acqLitAlertAlertText._store_ready)
668             this._setAlertStore();
669
670         li.lineitem_notes(
671             li.lineitem_notes().sort(
672                 function(a, b) { 
673                     if(a.edit_time() < b.edit_time()) return 1;
674                     return -1;
675                 }
676             )
677         );
678
679         while(this.liNotesTbody.childNodes[0])
680             this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
681         this.show('notes');
682
683         acqLitCreateNoteSubmit.onClick = function() {
684             var value = acqLitCreateNoteText.attr('value');
685             if(!value) return;
686             var note = new fieldmapper.acqlin();
687             note.isnew(true);
688             note.vendor_public(
689                 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
690             );
691             note.value(value);
692             note.lineitem(li.id());
693
694             self.updateLiNotes(li, note);
695             acqLitCreateNoteVendorPublic.attr("checked", false);
696             acqLitCreateNoteText.attr("value", "");
697         }
698
699         acqLitCreateAlertSubmit.onClick = function() {
700             if (!acqLitAlertAlertText.item) {
701                 alert(localeStrings.ALERT_UNSELECTED);
702                 return;
703             }
704
705             var alert_text = new fieldmapper.acqliat().fromStoreItem(
706                 acqLitAlertAlertText.item
707             );
708             var value = acqLitAlertNoteValue.attr("value") || "";
709
710             var note = new fieldmapper.acqlin();
711             note.isnew(true);
712             note.lineitem(li.id());
713             note.value(value);
714             note.alert_text(alert_text);
715
716             self.updateLiNotes(li, note);
717         }
718
719         dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
720     }
721
722     /**
723      * Draws a single lineitem note in the notes pane
724      */
725     this.addLiNote = function(li, note) {
726         if(note.isdeleted()) return;
727         var self = this;
728         var row = self.liNotesRow.cloneNode(true);
729         nodeByName("value", row).innerHTML = note.value();
730         var alert_node = nodeByName("alert_code", row);
731         if (note.alert_text()) {
732             alert_node.innerHTML = note.alert_text().code();
733             if (note.alert_text().description()) {
734                 new dijit.Tooltip(
735                     {
736                         "connectId": [alert_node],
737                         "label": note.alert_text().description()
738                     }, dojo.create("span", null, alert_node, "after")
739                 );
740             }
741         }
742
743         if (openils.Util.isTrue(note.vendor_public()))
744             nodeByName("vendor_public", row).innerHTML =
745                 localeStrings.VENDOR_PUBLIC;
746
747         nodeByName("delete", row).onclick = function() {
748             note.isdeleted(true);
749             self.liNotesTbody.removeChild(row);
750             self.updateLiNotes(li);
751         };
752
753         if(note.edit_time()) {
754             nodeByName("edit_time", row).innerHTML =
755                 dojo.date.locale.format(
756                     dojo.date.stamp.fromISOString(note.edit_time()), 
757                     {formatLength:'short'});
758         }
759
760         self.liNotesTbody.appendChild(row);
761     }
762
763     /**
764      * Updates any new/changed/deleted notes on the server
765      */
766     this.updateLiNotes = function(li, newNote) {
767
768         var notes;
769         if(newNote) {
770             notes = [newNote];
771         } else {
772             notes = li.lineitem_notes().filter(
773                 function(note) {
774                     if(note.ischanged() || note.isnew() || note.isdeleted())
775                         return note;
776                 }
777             );
778         }
779
780         if(notes.length == 0) return;
781         progressDialog.show();
782
783         fieldmapper.standardRequest(
784             ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
785             {   async : true,
786                 params : [this.authtoken, notes],
787                 onresponse : function(r) {
788                     var resp = openils.Util.readResponse(r);
789
790                     if(resp.complete) {
791
792                         if(!newNote) {
793                             // remove the old changed notes
794                             var list = [];
795                             dojo.forEach(li.lineitem_notes(), 
796                                 function(note) {
797                                     if(!(note.ischanged() || note.isnew() || note.isdeleted()))
798                                         list.push(note);
799                                 }
800                             );
801                             li.lineitem_notes(list);
802                         }
803
804                         progressDialog.hide();
805                         self.updateLiNotesCount(li);
806                         self.drawLiNotes(li);
807                         return;
808                     }
809
810                     progressDialog.update(resp);
811                     var newnote = resp.note;
812
813                     if(!newnote.isdeleted()) {
814                         newnote.isnew(false);
815                         newnote.ischanged(false);
816                         li.lineitem_notes().push(newnote);
817                     }
818                 },
819             }
820         );
821     }
822
823     this.updateLiPrice = function(input, li) {
824
825         var price = input.value;
826         if(Number(price) == Number(li.estimated_unit_price())) return;
827
828         fieldmapper.standardRequest(
829             ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
830             {   async : false, // redundant w/ timeout
831                 timeout : 10,
832                 params : [this.authtoken, li.id(), price],
833                 oncomplete : function(r) {
834                     openils.Util.readResponse(r);
835                     li.estimated_unit_price(price); // update local copy
836                 }
837             }
838         );
839     }
840
841     this.removeLineitem = function(liId) {
842         this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
843         delete this.liCache[liId];
844         //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
845     }
846
847     this.drawInfo = function(liId) {
848         if (!this._isRelatedViewer) {
849             var d = dojo.byId("acq-lit-info-related");
850             if (!this.relCache[liId]) {
851                 fieldmapper.standardRequest(
852                     [
853                         "open-ils.acq",
854                         "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
855                     ], {
856                         "async": true,
857                         "params": [openils.User.authtoken, liId],
858                         "onresponse": function(r) {
859                             self.relCache[liId] = openils.Util.readResponse(r);
860                             nodeByName("related_number", d).innerHTML =
861                                 self.relCache[liId];
862                             openils.Util[
863                                 self.relCache[liId] >1 ? "show" : "hide"
864                             ](d);
865                         }
866                     }
867                 );
868             } else {
869                 nodeByName("related_number", d).innerHTML = this.relCache[liId];
870                 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
871             }
872         }
873
874         this.show('info');
875         openils.acq.Lineitem.fetchAttrDefs(
876             function() { 
877                 self._fetchLineitem(liId, function(li){self._drawInfo(li);}); 
878             } 
879         );
880     };
881
882     /* For a given list of lineitem ids, build a list of full lineitems
883      * re-using the fetching logic that is otherwise typical to use in this
884      * module.
885      *
886      * If we've already got a lineitem in the cache, just use that.
887      *
888      * Once we've built a list of lineitems, call callback(thatlist).
889      */
890     this.fetchLineitemsById = function(id_list, callback) {
891         var total = id_list.length;
892         var result_list = [];
893
894         var inner = function(li) {
895             result_list.push(li)
896             if (--total <= 0)
897                 callback(result_list);
898         };
899
900         id_list.forEach(function(id) { self._fetchLineitem(id, inner); });
901     };
902
903     this._fetchLineitem = function(liId, handler, force) {
904
905         var li = this.liCache[liId];
906         if(li && li.marc() && li.lineitem_details() && !force)
907             return handler(li);
908         
909         fieldmapper.standardRequest(
910             ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
911             {   async: true,
912
913                 params: [self.authtoken, liId, {
914                     flesh_attrs: true,
915                     flesh_cancel_reason: true,
916                     flesh_li_details: true,
917                     flesh_notes: true,
918                     flesh_fund_debit: true }],
919
920                 oncomplete: function(r) {
921                     var li = openils.Util.readResponse(r);
922                     self.liCache[liId] = li;
923                     handler(li)
924                 }
925             }
926         );
927     };
928
929     this._drawInfo = function(li) {
930
931         acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
932
933         if(li.eg_bib_id()) {
934             openils.Util.hide('acq-lit-marc-order-record-label');
935             openils.Util.hide(acqLitEditOrderMarc.domNode);
936             openils.Util.show('acq-lit-marc-real-record-label');
937         } else {
938             openils.Util.show('acq-lit-marc-order-record-label');
939             openils.Util.show(acqLitEditOrderMarc.domNode);
940             openils.Util.hide('acq-lit-marc-real-record-label');
941         }
942
943         this.drawMarcHTML(li);
944         this.infoTbody = dojo.byId('acq-lit-info-tbody');
945
946         if(!this.infoRow)
947             this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
948         while(this.infoTbody.childNodes[0])
949             this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
950
951         for(var i = 0; i < li.attributes().length; i++) {
952             var attr = li.attributes()[i];
953             var row = this.infoRow.cloneNode(true);
954
955             var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
956             var name = openils.acq.Lineitem.attrDefs[type].filter(
957                 function(a) {
958                     return (a.code() == attr.attr_name());
959                 }
960             ).pop().description();
961
962             dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
963             dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
964             this.infoTbody.appendChild(row);
965         }
966
967         if (!this._isRelatedViewer) {
968             nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
969                 oilsBasePath + "/acq/lineitem/related/" + li.id();
970         }
971
972     };
973
974     this.generateMakeRecTab = function(bib_id,default_view, row) {
975         return function() {
976             xulG.new_tab(
977                 XUL_OPAC_WRAPPER,
978                 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
979                 {
980                     no_xulG : false, 
981                     show_nav_buttons : true, 
982                     show_print_button : true, 
983                     opac_url : xulG.url_prefix(xulG.urls.opac_rdetail + bib_id),
984                     default_view : default_view
985                 }
986             );
987
988             if(row) nodeByName("action_none", row).selected = true;
989         }
990     };
991
992     this.drawMarcHTML = function(li) {
993         var params = [null, true, li.marc()];
994         if(li.eg_bib_id()) 
995             params = [li.eg_bib_id(), true];
996
997         fieldmapper.standardRequest(
998             ['open-ils.search', 'open-ils.search.biblio.record.html'],
999             {   async: true,
1000                 params: params,
1001                 oncomplete: function(r) {
1002                     dojo.byId('acq-lit-marc-div').innerHTML = 
1003                         openils.Util.readResponse(r);
1004                 }
1005             }
1006         );
1007     }
1008
1009     this.drawCopies = function(liId, force_fetch) {
1010         if (typeof force_fetch == "undefined")
1011             force_fetch = false;
1012
1013         openils.acq.Lineitem.fetchAndRender(liId, {}, 
1014             function(li, html) {
1015                 dojo.byId('acq-lit-copies-li-summary').innerHTML = html;
1016             }
1017         );
1018
1019         this.show('copies');
1020         var self = this;
1021         this.copyCache = {};
1022         this.copyWidgetCache = {};
1023         this.oldCopyWidgetCache = {};
1024         this.virtDfaCounts = {};
1025         this.realDfaCache = {};
1026         this.dfeOffset = 0;
1027
1028         acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
1029         acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
1030         acqLitCopyCountInput.attr('value', '0');
1031
1032         while(this.copyTbody.childNodes[0])
1033             this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
1034
1035         this._drawBatchCopyWidgets();
1036
1037         this._drawDistribApplied(liId);
1038
1039         this._fetchDistribFormulas(
1040             function() {
1041                 openils.acq.Lineitem.fetchAttrDefs(
1042                     function() { 
1043                         self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch); 
1044                     } 
1045                 );
1046             }
1047         );
1048     };
1049
1050     this._saveDistribAppliedTemplates = function() {
1051         if (!this._appliedDistribTemplate) {
1052             this._appliedDistribTemplate =
1053                 dojo.byId("acq-lit-distrib-applied-tbody").
1054                     removeChild(dojo.byId("acq-lit-distrib-applied-row"));
1055             dojo.attr(this._appliedDistribTemplate, "id");
1056         }
1057     };
1058
1059     this._drawDistribApplied = function(liId) {
1060         /* Build this table while hidden to prevent rendering artifacts */
1061         openils.Util.hide("acq-lit-distrib-applied-tbody");
1062
1063         this._saveDistribAppliedTemplates();
1064
1065         /* Remove any rows in the table from previous populations */
1066         dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
1067             forEach(dojo.destroy);
1068
1069         /* Unregister all dijits previously created (for some reason this isn't
1070          * covered by the above destroy calls). */
1071         dijit.registry.forEach(
1072             function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
1073         );
1074
1075         /* Populate the table with our liId */
1076         var total = 0;
1077         fieldmapper.standardRequest(
1078             ["open-ils.acq",
1079             "open-ils.acq.distribution_formula_application.ranged.retrieve"],
1080             {
1081                 "async": true,
1082                 "params": [self.authtoken, liId],
1083                 "onresponse": function(r) {
1084                     var dfa = openils.Util.readResponse(r);
1085                     if (dfa) {
1086                         total++;
1087                         self.realDfaCache[dfa.id()] = dfa;
1088                         self._drawDistribAppliedUnit(dfa);
1089                     }
1090                 },
1091                 "oncomplete": function() {
1092                     /* Reveal built table */
1093                     if (total) {
1094                         openils.Util.show(
1095                             "acq-lit-distrib-applied-tbody", "table-row-group"
1096                         );
1097                     }
1098                 }
1099             }
1100         );
1101     };
1102
1103     this._drawDistribAppliedUnit = function(dfa) {
1104         var new_row = false;
1105         var row = dojo.query(
1106             'tr[formula="' + dfa.formula().id() + '"]',
1107             "acq-lit-distrib-applied-tbody"
1108         )[0];
1109
1110         if (!row) {
1111             new_row = true;
1112             row = dojo.clone(this._appliedDistribTemplate);
1113             dojo.attr(row, "formula", dfa.formula().id());
1114             dojo.query("th", row)[0].innerHTML = dfa.formula().name();
1115         }
1116
1117         var td = dojo.query("td", row)[0];
1118
1119         dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1120         dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1121
1122         if (new_row)
1123             dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1124
1125         new dijit.form.Button(
1126             {
1127                 "onClick": function() {
1128                     if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1129                         self.deleteDfa(dfa);
1130                 },
1131                 "label": "X",
1132                 /* XXX I /cannot/ make the following work in as a CSS class
1133                  * for some reason. So frustrating... */
1134                 "style": function(id) {
1135                      return (id > 0 ?
1136                         "font-weight: bold; color: #c00;" :
1137                         "color: #666;");
1138                      }(dfa.id()) + "margin: 0 6px;display: inline;"
1139             }, "dfa-button-" + dfa.id()
1140         );
1141         new dijit.Tooltip(
1142             {
1143                 "connectId": ["dfa-button-" + dfa.id()],
1144                 "label": dojo.string.substitute(
1145                     localeStrings.DFA_TIP, dfa.id() > 0 ? [
1146                         openils.User.formalName(dfa.creator()),
1147                         dojo.date.locale.format(
1148                             dojo.date.stamp.fromISOString(dfa.create_time()),
1149                             {"formatLength":"short"}
1150                         )
1151                     ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
1152                 )
1153             }, "dfa-tip-" + dfa.id()
1154         );
1155     }
1156
1157     this.deleteDfa = function(dfa) {
1158         if (dfa.id() > 0) { /* real */
1159             this.pcrud.eliminate(
1160                 dfa, {
1161                     "async": true,
1162                     "oncomplete": function() {
1163                         self._removeDistribApplied(dfa.id());
1164                         delete self.realDfaCache[dfa.id()];
1165                     }
1166                 }
1167             );
1168         } else { /* virtual */
1169             if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
1170             this.virtDfaCounts[dfa.formula().id()] = 0;
1171             /* hasn't been saved yet, so no need to do anything server side */
1172             this._removeDistribApplied(dfa.id());
1173         }
1174
1175     };
1176
1177     this._removeDistribApplied = function(dfaId) {
1178         var re = new RegExp("^dfa-\\w+-" + String(dfaId));
1179         dijit.registry.forEach(
1180             function(w) { if (re.test(w.id)) w.destroyRecursive(); }
1181         );
1182         this._removeDistribAppliedEmptyRows();
1183     };
1184
1185     this._removeAllDistribAppliedVirtual = function() {
1186         /* Unregister dijits */
1187         dijit.registry.forEach(
1188             function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
1189         );
1190         this._removeDistribAppliedEmptyRows();
1191     };
1192
1193     this._removeDistribAppliedEmptyRows = function() {
1194         /* Remove any rows with no DFA at all */
1195         dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
1196             function(o) {
1197                 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
1198             }
1199         );
1200     };
1201
1202     /**
1203      * Insert a new row into the distribution formula selection form
1204      */
1205     this._addDistribFormulaRow = function() {
1206         var self = this;
1207
1208         if (!self.distribForms) {
1209             // no formulas, hide the form
1210             openils.Util.hide('acq-lit-distrib-formula-table');
1211             return;
1212         }
1213
1214         if(!this.distribFormulaTemplate) 
1215             this.distribFormulaTemplate = 
1216                 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
1217
1218         var row = this.distribFormulaTemplate.cloneNode(true);
1219         dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
1220
1221         this.dfSelector = new dijit.form.FilteringSelect(
1222             {"labelAttr": "dynLabel", "labelType": "html"},
1223             nodeByName("selector", row)
1224         );
1225         this._updateFormulaStore();
1226         this.dfSelector.fetchProperties =
1227             {"sort": [{"attribute": "use_count", "descending": true}]};
1228
1229         var apply = new dijit.form.Button(
1230             {"label": localeStrings.APPLY},
1231             nodeByName('set_button', row)
1232         ); 
1233
1234         var reset = new dijit.form.Button(
1235             {"label": localeStrings.RESET_FORMULAE, "disabled": true},
1236             nodeByName("reset_button", row)  
1237         );
1238
1239         dojo.connect(apply, 'onClick', 
1240             function() {
1241                 var form_id = self.dfSelector.attr("value");
1242                 if(!form_id) return;
1243                 self._applyDistribFormula(form_id);
1244                 reset.attr("disabled", false);
1245             }
1246         );
1247
1248         dojo.connect(reset, 'onClick', 
1249             function() {
1250                 self.restoreCopyFieldsBeforeDF();
1251                 self.virtDfaCounts = {};
1252                 self.virtDfaId = -1;
1253                 self.dfeOffset = 0;
1254                 self._updateFormulaStore();
1255                 self._removeAllDistribAppliedVirtual();
1256                 reset.attr("disabled", "true");
1257             }
1258         );
1259
1260     };
1261
1262     /**
1263      * Applies a distrib formula to the current set of copies
1264      */
1265     this._applyDistribFormula = function(formula) {
1266         if(!formula) return;
1267
1268         formula = this.distribForms.filter(
1269             function(form) { return form.id() == formula; }
1270         )[0];
1271
1272         var copyRows = dojo.query('tr', self.copyTbody);
1273
1274         if (this.dfeOffset >= copyRows.length) {
1275             alert(localeStrings.OUT_OF_COPIES);
1276             return;
1277         }
1278
1279         var entries_applied = 0;
1280         for(
1281             var rowIndex = this.dfeOffset;
1282             rowIndex < copyRows.length;
1283             rowIndex++
1284         ) {
1285             
1286             var row = copyRows[rowIndex];
1287             var copy_id = row.getAttribute('copy_id');
1288             var copyWidgets = this.copyWidgetCache[copy_id];
1289             var entryIndex = this.dfeOffset;
1290             var entry = null;
1291
1292             // find the correct entry for the current row
1293             dojo.forEach(formula.entries(), 
1294                 function(e) {
1295                     if(!entry) {
1296                         entryIndex += e.item_count();
1297                         if(entryIndex > rowIndex)
1298                             entry = e;
1299                     }
1300                 }
1301             );
1302
1303             if(entry) {
1304                 
1305                 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" + 
1306                 //  entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
1307     
1308                 entries_applied++;
1309                 this.saveCopyFieldsBeforeDF(copy_id);
1310                 this._copy_fields_for_acqdf.forEach(
1311                     function(field) {
1312                         if(entry[field]()) {
1313                             copyWidgets[field].attr('value', (entry[field]()));
1314                         }
1315                     }
1316                 );
1317             }
1318         }
1319
1320         if (entries_applied) {
1321             this.virtDfaCounts[formula.id()] =
1322                 ++(this.virtDfaCounts[formula.id()]) || 1;
1323             this._updateFormulaStore();
1324             this._drawDistribAppliedUnit(
1325                 function(df) {
1326                     var dfa = new acqdfa();
1327                     dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
1328                 }(formula)
1329             );
1330             this.dfeOffset += entries_applied;
1331         };
1332     };
1333
1334     /**
1335      * This function updates the DF store for the dropdown so that use_counts
1336      * can reflect DF applications from this session before they're saved
1337      * server-side.
1338      */
1339     this._updateFormulaStore = function() {
1340         this.dfSelector.store = new dojo.data.ItemFileReadStore(
1341             {
1342                 "data": self._labelFormulasWithCounts(
1343                     acqdf.toStoreData(self.distribForms)
1344                 )
1345             }
1346         );
1347     };
1348
1349     this.saveCopyFieldsBeforeDF = function(copy_id) {
1350         var self = this;
1351         if (!this.oldCopyWidgetCache[copy_id]) {
1352             var copyWidgets = this.copyWidgetCache[copy_id];
1353
1354             this.oldCopyWidgetCache[copy_id] = {};
1355             this._copy_fields_for_acqdf.forEach(
1356                 function(f) {
1357                     self.oldCopyWidgetCache[copy_id][f] =
1358                         copyWidgets[f].attr("value");
1359                 }
1360             );
1361         }
1362     };
1363
1364     this.restoreCopyFieldsBeforeDF = function() {
1365         var self = this;
1366         for (var copy_id in this.oldCopyWidgetCache) {
1367             this._copy_fields_for_acqdf.forEach(
1368                 function(f) {
1369                     self.copyWidgetCache[copy_id][f].attr(
1370                         "value", self.oldCopyWidgetCache[copy_id][f]
1371                     );
1372                 }
1373             );
1374         }
1375     };
1376
1377     this._labelFormulasWithCounts = function(store_data) {
1378         for (var key in store_data.items) {
1379             var obj = store_data.items[key];
1380             obj.use_count = Number(obj.use_count); /* needed for sorting */
1381
1382             if (this.virtDfaCounts[obj.id])
1383                 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
1384
1385             obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
1386                 obj.use_count + "]</span>&nbsp; " + obj.name;
1387         }
1388         return store_data;
1389     };
1390
1391     /**
1392      * This method formerly would not refetch the DF formulas if they'd been
1393      * loaded already, but now it always re-fetches, since use_count changes.
1394      */
1395     /** TODO: port distrib-formula selector to autofieldwidget+pcrud/dojo store */
1396     this._fetchDistribFormulas = function(onload) {
1397         fieldmapper.standardRequest(
1398             ["open-ils.acq",
1399                 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
1400             {
1401                 "async": true,
1402                 "params": [openils.User.authtoken, 0, 500],
1403                 "oncomplete": function(r) {
1404                     self.distribForms = openils.Util.readResponse(r);
1405                     if(!self.distribForms || self.distribForms.length == 0) {
1406                         self.distribForms = [];
1407                     }
1408                     self._addDistribFormulaRow();
1409                     onload();
1410                 }
1411             }
1412         );
1413     }
1414
1415     this._drawBatchCopyWidgets = function() {
1416         var row = this.copyBatchRow;
1417         dojo.forEach(liDetailBatchFields, 
1418             function(field) {
1419                 if(self.copyBatchRowDrawn) {
1420                     self.copyBatchWidgets[field].attr('value', null);
1421                 } else {
1422                     var widget = new openils.widget.AutoFieldWidget({
1423                         fmField : field,
1424                         fmClass : 'acqlid',
1425                         labelFormat : (field == 'fund') ? fundLabelFormat : null,
1426                         searchFormat : (field == 'fund') ? fundSearchFormat : null,
1427                         searchFilter : (field == 'fund') ? {"active": "t"} : null,
1428                         parentNode : dojo.query('[name='+field+']', row)[0],
1429                         orgLimitPerms : ['CREATE_PICKLIST'],
1430                         dijitArgs : {
1431                             "required": false,
1432                             "labelType": (field == "fund") ? "html" : null
1433                         },
1434                         noCache: (field == "fund"),
1435                         forceSync : true
1436                     });
1437                     widget.build(
1438                         function(w, ww) {
1439                             if (field == "fund" && w.store)
1440                                 self._ensureCSSFundClasses(w.store);
1441                             self.copyBatchWidgets[field] = w;
1442                         }
1443                     );
1444                     if (field == "fund") {
1445                         dojo.connect(
1446                             widget.widget, "onChange", function(val) {
1447                                 self._updateFundSelectorStyle(widget, val);
1448                             }
1449                         );
1450                     }
1451                 }
1452             }
1453         );
1454         this.copyBatchRowDrawn = true;
1455     };
1456
1457     this.batchCopyUpdate = function() {
1458         var self = this;
1459         for(var k in this.copyWidgetCache) {
1460             var cache = this.copyWidgetCache[k];
1461             dojo.forEach(liDetailBatchFields, function(f) {
1462                 var newval = self.copyBatchWidgets[f].attr('value');
1463                 if(newval) cache[f].attr('value', newval);
1464             });
1465         }
1466     };
1467
1468     this._drawCopies = function(li) {
1469         var self = this;
1470
1471         // this button sets the total number of copies for a given lineitem
1472         acqLitAddCopyCount.onClick = function() { 
1473             var count = acqLitCopyCountInput.attr('value');
1474
1475             // add new rows
1476             while(self.copyCount() < count)
1477                 self.addCopy(li); 
1478             
1479             // delete rows if necessary
1480             var diff = self.copyCount() - count;
1481             if(diff > 0) {
1482                 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
1483                 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
1484                     dojo.forEach(rows, function(row) {self.deleteCopy(row); });
1485                 } else {
1486                     acqLitCopyCountInput.attr('value', self.copyCount()+'');
1487                 }
1488             }
1489         }
1490
1491
1492         if(li.lineitem_details().length > 0) {
1493             dojo.forEach(li.lineitem_details(),
1494                 function(copy) {
1495                     self.addCopy(li, copy);
1496                 }
1497             );
1498         } else {
1499             self.addCopy(li);
1500         }
1501     };
1502
1503     this.copyCount = function() {
1504         var count = 0;
1505         for(var id in this.copyCache) {
1506             if(!this.copyCache[id].isdeleted())
1507                 count++;
1508         }
1509         return count;
1510     }
1511
1512     this.virtCopyId = -1;
1513     this.addCopy = function(li, copy) {
1514         var row = this.copyRow.cloneNode(true);
1515         this.copyTbody.appendChild(row);
1516         var self = this;
1517
1518         if(!copy) {
1519             copy = new fieldmapper.acqlid();
1520             copy.isnew(true);
1521             copy.id(this.virtCopyId--);
1522             copy.lineitem(li.id());
1523         }
1524
1525         this.copyCache[copy.id()] = copy;
1526         row.setAttribute('copy_id', copy.id());
1527         self.copyWidgetCache[copy.id()] = {};
1528
1529         acqLitCopyCountInput.attr('value', self.copyCount()+'');
1530
1531         var rcvr = copy.receiver();
1532         if (rcvr) {
1533             if (!userCache[rcvr]) {
1534                 if(rcvr == openils.User.user.id()) {
1535                     userCache[rcvr] = openils.User.user;
1536                 } else {
1537                     userCache[rcvr] = fieldmapper.standardRequest(
1538                         ['open-ils.actor', 'open-ils.actor.user.retrieve'],
1539                         {params: [openils.User.authtoken, rcvr]}
1540                     );
1541                 }
1542             }
1543             dojo.query('[name=receiver]', row)[0].innerHTML =  userCache[rcvr].usrname();
1544         }
1545
1546         dojo.forEach(liDetailFields,
1547             function(field) {
1548                 var searchFilter;
1549                 if (field == "fund") {
1550                     searchFilter = (copy.fund() ?
1551                         {"-or": {"active": "t", "id": copy.fund()}} :
1552                         {"active" : "t"});
1553                 } else {
1554                     searchFilter = null;
1555                 }
1556
1557                 var readOnly = false;
1558                 
1559                 // TODO: Add support for changing the owning_lib after real copies have been made.  
1560                 // owning_lib is order data as much as its item data
1561                 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
1562                     readOnly = true;
1563                 }
1564
1565                 // TODO: add support for changing the fund after debits have been created
1566                 // Note: invoicing allows the change
1567                 if(copy.fund_debit() && field == 'fund') {
1568                     readOnly = true;
1569                 }
1570
1571
1572                 var widget = new openils.widget.AutoFieldWidget({
1573                     fmObject : copy,
1574                     fmField : field,
1575                     labelFormat : (field == 'fund') ? fundLabelFormat : null,
1576                     searchFormat : (field == 'fund') ? fundSearchFormat : null,
1577                     dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1578                     searchFilter : searchFilter,
1579                     noCache: (field == "fund"),
1580                     fmClass : 'acqlid',
1581                     parentNode : dojo.query('[name='+field+']', row)[0],
1582                     orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
1583                     readOnly : readOnly,
1584                     orgDefaultsToWs : true
1585                 });
1586
1587                 widget.build(
1588                     // make sure we capture the value from any async widgets
1589                     function(w, ww) { 
1590
1591                         if (field == "fund" && w.store)
1592                             self._ensureCSSFundClasses(w.store);
1593
1594                         if(!readOnly) 
1595                             copy[field](ww.getFormattedValue()) 
1596
1597                         self.copyWidgetCache[copy.id()][field] = w;
1598
1599                         dojo.connect(w, 'onChange', 
1600                             function(val) { 
1601                                 if (field == "fund")
1602                                     self._updateFundSelectorStyle(widget, val);
1603
1604                                 if (!readOnly && (copy.isnew() || val != copy[field]())) {
1605                                     // prevent setting ischanged() automatically on widget load for existing copies
1606                                     copy[field](widget.getFormattedValue()) 
1607                                     copy.ischanged(true);
1608                                 }
1609                             }
1610                         );
1611                     }
1612                 );
1613             }
1614         );
1615
1616         this.updateLidState(copy, row);
1617     };
1618
1619     this._ensureCSSFundClass = function(id) {
1620         if (!this.fundStyleSheet) {
1621             dojo.create(
1622                 "style", {"type": "text/css"},
1623                 document.getElementsByTagName("head")[0], "last"
1624             );
1625             this.fundStyleSheet = document.styleSheets[
1626                 document.styleSheets.length - 1
1627             ];
1628         }
1629
1630         var cn = "fund_" + id;
1631         if (!this.haveFundClass[cn]) {
1632             fieldmapper.standardRequest(
1633                 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
1634                 {
1635                     "params": [openils.User.authtoken, id],
1636                     "async": true,
1637                     "oncomplete": function(r) {
1638                         r = openils.Util.readResponse(r);
1639                         self.fundBalanceState[id] = r;
1640                         var style = "";
1641                         if (r[0] /* stop */)
1642                             style = fundStyles.stop;
1643                         else if (r[1] /* warning */)
1644                             style = fundStyles.warning;
1645                         self.fundStyleSheet.insertRule(
1646                             "." + cn + " { " + style + " }",
1647                             self.fundStyleSheet.cssRules.length
1648                         );
1649                         self.haveFundClass[cn] = true;
1650                     }
1651                 }
1652             );
1653         }
1654     };
1655
1656     this._ensureCSSFundClasses = function(store) {
1657         store.fetch({
1658             "query": {"id": "*"},
1659             "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
1660         });
1661     };
1662
1663     this._updateFundSelectorStyle = function(widget, fund_id) {
1664         openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
1665         openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
1666     };
1667
1668     this.updateLidState = function(copy, row) {
1669         if (typeof(row) == "undefined") {
1670             row = dojo.query(
1671                 'tr[copy_id="' + copy.id() + '"]', this.copyTbody
1672             )[0];
1673         }
1674
1675         var self = this;
1676         var recv_link = nodeByName("receive", row);
1677         var unrecv_link = nodeByName("unreceive", row);
1678         var del_link = nodeByName("delete", row);
1679         var cxl_link = nodeByName("cancel", row);
1680         var claim_link = nodeByName("claim", row);
1681         var cxl_reason_link = nodeByName("cancel_reason", row);
1682
1683         if (copy.cancel_reason()) {
1684             openils.Util.hide(del_link.parentNode);
1685             openils.Util.hide(recv_link);
1686             openils.Util.hide(unrecv_link);
1687             openils.Util.hide(cxl_link);
1688             openils.Util.hide(claim_link);
1689
1690             /* XXX the following may leak memory in a long lived table: dijits may not get destroyed... not positive. revisit. */
1691             var holds_reason = dojo.create(
1692                 "span", {
1693                     "style": "border-bottom: 1px dashed #000;",
1694                     "innerHTML": "Cancelled" /* XXX [sic] and i18n */
1695                 }, cxl_reason_link, "only"
1696             );
1697             new dijit.Tooltip(
1698                 {
1699                     "label": "<em>" + copy.cancel_reason().label() +
1700                         "</em><br />" + copy.cancel_reason().description(),
1701                     "connectId": [holds_reason]
1702                 }, dojo.create("span", null, cxl_reason_link, "last")
1703             );
1704             openils.Util.show(cxl_reason_link, "inline");
1705         } else if (this.isPO) {
1706             /* Only using this in one place so far, but may want it for better
1707              * decisions on when to display certain controls. */
1708             var li_state = this.liCache[copy.lineitem()].state();
1709
1710             openils.Util.hide(del_link.parentNode);
1711             openils.Util.hide(cxl_reason_link);
1712
1713             /* Avoid showing (un)receive links, cancel links, for virt copies */
1714             if (copy.id() > 0) {
1715                 if (copy.recv_time()) {
1716                     openils.Util.hide(cxl_link);
1717                     openils.Util.hide(recv_link);
1718                     openils.Util.hide(claim_link);
1719
1720                     openils.Util.show(unrecv_link, "inline");
1721                     unrecv_link.onclick = function() {
1722                         if (confirm(localeStrings.UNRECEIVE_LID))
1723                             self.issueReceive(copy, /* rollback */ true);
1724                     };
1725                 } else {
1726                     openils.Util.hide(unrecv_link);
1727
1728                     if (this.claimEligibleLid[copy.id()]) {
1729                         openils.Util.show(claim_link, "inline");
1730                         claim_link.onclick = function() {
1731                             self.claimDialog.show(
1732                                 self.liCache[copy.lineitem()], copy.id()
1733                             );
1734                         };
1735                     } else {
1736                         openils.Util.hide(claim_link);
1737                     }
1738
1739                     openils.Util[li_state == "on-order" ? "show" : "hide"](
1740                         recv_link, "inline"
1741                     );
1742                     openils.Util.show(cxl_link, "inline");
1743                     recv_link.onclick = function() {
1744                         if (self.checkLiAlerts(copy.lineitem()))
1745                             self.issueReceive(copy);
1746                     };
1747                     cxl_link.onclick = function() {
1748                         self.cancelLid(copy.id());
1749                     };
1750                 }
1751             } else {
1752                 openils.Util.hide(cxl_link);
1753                 openils.Util.hide(unrecv_link);
1754                 openils.Util.hide(recv_link);
1755                 openils.Util.hide(claim_link);
1756             }
1757         } else {
1758             openils.Util.hide(unrecv_link);
1759             openils.Util.hide(recv_link);
1760             openils.Util.hide(cxl_reason_link);
1761             openils.Util.hide(claim_link);
1762
1763             del_link.onclick = function() { self.deleteCopy(row) };
1764             openils.Util.show(del_link.parentNode);
1765         }
1766     }
1767
1768     this.cancelLid = function(lid_id) {
1769         lidCancelDialog._lid_id = lid_id;
1770         openils.Util.show(lidCancelDialog.domNode.parentNode);
1771         lidCancelDialog.show();
1772         if (!lidCancelDialog._prepared) {
1773             var widget = new openils.widget.AutoFieldWidget({
1774                 "fmField": "cancel_reason",
1775                 "fmClass": "acqlid",
1776                 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
1777                 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1778                 "forceSync": true
1779             });
1780             widget.build(
1781                 function(w, ww) {
1782                     acqLidCancelButton.onClick = function() {
1783                         if (w.attr("value")) {
1784                             if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
1785                                 self._cancelLid(
1786                                     lidCancelDialog._lid_id,
1787                                     w.attr("value")
1788                                 );
1789                             }
1790                             lidCancelDialog.hide();
1791                         }
1792                     };
1793                     lidCancelDialog._prepared = true;
1794                 }
1795             );
1796         }
1797     };
1798
1799     this._cancelLid = function(lid_id, reason) {
1800         fieldmapper.standardRequest(
1801             ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
1802                 "params": [openils.User.authtoken, lid_id, reason],
1803                 "async": true,
1804                 "onresponse": function(r) {
1805                     if (r = openils.Util.readResponse(r)) {
1806                         if (r.lid) {
1807                             for (var id in r.lid) {
1808                                 /* actually this should only iterate once */
1809                                 self.copyCache[id].cancel_reason(
1810                                     r.lid[id].cancel_reason
1811                                 );
1812                                 self.updateLidState(self.copyCache[id]);
1813                             }
1814                         }
1815                     }
1816                 }
1817             }
1818         );
1819     };
1820
1821     this._confirmAlert = function(li, lin) {
1822         return confirm(
1823             dojo.string.substitute(
1824                 localeStrings.CONFIRM_LI_ALERT, [
1825                     (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1826                         "title", "lineitem_marc_attr_definition"
1827                     ),
1828                     lin.alert_text().code(),
1829                     lin.alert_text().description() || "",
1830                     lin.value()
1831                 ]
1832             )
1833         );
1834     };
1835
1836     this.checkLiAlerts = function(li_id) {
1837         var li = this.liCache[li_id];
1838
1839         var alert_notes = li.lineitem_notes().filter(
1840             function(o) { return Boolean(o.alert_text()); }
1841         );
1842
1843         /* this is _intentionally_ not done in a call to forEach() ... */
1844         for (var i = 0; i < alert_notes.length; i++) {
1845             if (this.noteAcks[alert_notes[i].id()])
1846                 continue;
1847             else if (!this._confirmAlert(li, alert_notes[i]))
1848                 return false;
1849             else
1850                 this.noteAcks[alert_notes[i].id()] = true;
1851         }
1852
1853         return true;
1854     };
1855
1856     this.deleteCopy = function(row) {
1857         var copy = this.copyCache[row.getAttribute('copy_id')];
1858         copy.isdeleted(true);
1859         if(copy.isnew())
1860             delete this.copyCache[copy.id()];
1861         this.copyTbody.removeChild(row);
1862     }
1863
1864     this._virtDfaCountsAsList = function() {
1865         var L = [];
1866         for (var key in this.virtDfaCounts) {
1867             for (var i = 0; i < this.virtDfaCounts[key]; i++)
1868                 L.push(key);
1869         }
1870         return L;
1871     }
1872
1873     this.confirmBreachedCopyFunds = function(copies) {
1874         var stop = 0, warning = 0;
1875         copies.forEach(
1876             function(o) {
1877                 if (o.fund()) {
1878                     var state = self.fundBalanceState[o.fund()];
1879                     if (state[0] /* stop */)
1880                         stop++;
1881                     else if (state[1] /* warning */)
1882                         warning++;
1883                 }
1884             }
1885         );
1886
1887         if (stop) {
1888             return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
1889         } else if (warning) {
1890             return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
1891         }
1892         return true;
1893     };
1894
1895     this.saveCopyChanges = function(liId) {
1896         var self = this;
1897         var copies = [];
1898
1899
1900         var total = 0;
1901         for(var id in this.copyCache) {
1902             var c = this.copyCache[id];
1903             if(!c.isdeleted()) total++;
1904             if(c.isnew() || c.ischanged() || c.isdeleted()) {
1905                 if(c.id() < 0) c.id(null);
1906                 copies.push(c);
1907             }
1908         }
1909
1910
1911         dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
1912
1913
1914         if (copies.length > 0) {
1915             if (!this.confirmBreachedCopyFunds(copies))
1916                 return;
1917
1918             if (typeof(this._copy_count_cb) == "function")
1919                 this._copy_count_cb(liId, total);
1920
1921             openils.Util.show("acq-lit-update-copies-progress");
1922             fieldmapper.standardRequest(
1923                 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1924                 {   async: true,
1925                     params: [openils.User.authtoken, copies],
1926                     onresponse: function(r) {
1927                         var res = openils.Util.readResponse(r);
1928                         litUpdateCopiesProgress.update(res);
1929                     },
1930                     oncomplete: function() {
1931                         self.drawCopies(liId, true /* force_fetch */);
1932                         openils.Util.hide("acq-lit-update-copies-progress");
1933                     }
1934                 }
1935             );
1936         }
1937
1938         var dfa_list = this._virtDfaCountsAsList();
1939         if (dfa_list.length > 0) {
1940             fieldmapper.standardRequest(
1941                 ["open-ils.acq",
1942                 "open-ils.acq.distribution_formula.record_application"],
1943                 {
1944                     "async": true,
1945                     "params": [openils.User.authtoken, dfa_list, liId],
1946                     "onresponse": function(r) {
1947                         var res = openils.Util.readResponse(r);
1948                         if (res && res.length < dfa_list.length)
1949                             alert(localeStrings.DFA_NOT_ALL);
1950                     }
1951                 }
1952             );
1953             this.virtDfaCounts = {};
1954         }
1955     }
1956
1957     this._updateCreatePoPrepayCheckbox = function(prepay) {
1958         var prepay = openils.Util.isTrue(prepay);
1959         this._prepayRequiredByVendor = prepay;
1960         dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
1961     };
1962
1963     this._confirmPoPrepaySituation = function() {
1964         var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
1965         if (want_prepay != this._prepayRequiredByVendor) {
1966             return confirm(
1967                 want_prepay ?
1968                     localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
1969                     localeStrings.VENDOR_SAYS_PREPAY_NEEDED
1970             );
1971         } else {
1972             return true;
1973         }
1974     };
1975
1976     this.applySelectedLiAction = function(action) {
1977         var self = this;
1978         switch(action) {
1979
1980             case 'delete_selected':
1981                 this._deleteLiList(self.getSelected());
1982                 break;
1983
1984             case 'create_order':
1985                 this._loadPOSelect();
1986                 acqLitPoCreateDialog.show();
1987                 break;
1988
1989             case 'save_picklist':
1990                 acqLitSavePlDialog.show();
1991                 break;
1992
1993             case 'selector_ready':
1994             case 'order_ready':
1995                 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
1996                 acqLitChangeLiStateDialog.show();
1997                 break;
1998
1999             case 'print_po':
2000                 this.printPO();
2001                 break;
2002
2003             case 'po_history':
2004                 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
2005                 break;
2006
2007             case 'receive_po':
2008                 this.receivePO();
2009                 break;
2010
2011             case 'rollback_receive_po':
2012                 this.rollbackPoReceive();
2013                 break;
2014
2015             case 'create_assets':
2016                 this.createAssets();
2017                 break;
2018
2019             case 'export_attr_list':
2020                 this.chooseExportAttr();
2021                 break;
2022
2023             case 'batch_apply_funds':
2024                 this.applyBatchLiFunds();
2025                 break;
2026
2027             case 'add_brief_record':
2028                 if(this.isPO)
2029                     location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
2030                 else
2031                     location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
2032
2033                 break;
2034
2035             case "cancel_lineitems":
2036                 this.maybeCancelLineitems();
2037                 break;
2038
2039             case "change_claim_policy":
2040                 var li_list = this.getSelected();
2041                 this.claimPolicyPicker.attr("value", null);
2042                 liClaimPolicyDialog.show();
2043                 liClaimPolicySave.onClick = function() {
2044                     self.changeClaimPolicy(
2045                         li_list,
2046                         self.claimPolicyPicker.attr("value"),
2047                         function() {
2048                             li_list.forEach(
2049                                 function(li) {
2050                                     self.setClaimPolicyControl(li);
2051                                     self.reconsiderClaimControl(li);
2052                                 }
2053                             );
2054                             liClaimPolicyDialog.hide();
2055                         }
2056                     )
2057                 };
2058                 break;
2059         }
2060     };
2061
2062     this.changeClaimPolicy = function(li_list, value, callback) {
2063         li_list.forEach(
2064             function(li) { li.claim_policy(value); }
2065         );
2066         fieldmapper.standardRequest(
2067             ["open-ils.acq", "open-ils.acq.lineitem.update"], {
2068                 "params": [openils.User.authtoken, li_list],
2069                 "async": true,
2070                 "oncomplete": function(r) {
2071                     r = openils.Util.readResponse(r);
2072                     if (callback) callback(r);
2073                 }
2074             }
2075         );
2076     };
2077
2078     this.createAssets = function() {
2079         if(!this.isPO) return;
2080         if(!confirm(localeStrings.CREATE_PO_ASSETS_CONFIRM)) return;
2081         this.show('acq-lit-progress-numbers');
2082         var self = this;
2083         fieldmapper.standardRequest(
2084             ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
2085             {   async: true,
2086                 params: [this.authtoken, this.isPO],
2087                 onresponse: function(r) {
2088                     var resp = openils.Util.readResponse(r);
2089                     self._updateProgressNumbers(resp, true);
2090                 }
2091             }
2092         );
2093     }
2094
2095     this.maybeCancelLineitems = function() {
2096         openils.Util.show("acq-lit-cancel-reason", "inline");
2097         if (!acqLitCancelLineitemsButton._prepared) {
2098             var widget = new openils.widget.AutoFieldWidget({
2099                 "fmField": "cancel_reason",
2100                 "fmClass": "jub",
2101                 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
2102                 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2103                 "forceSync": true
2104             });
2105             widget.build(
2106                 function(w, ww) {
2107                     acqLitCancelLineitemsButton.onClick = function() {
2108                         if (w.attr("value")) {
2109                             if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
2110                                 self._cancelLineitems(w.attr("value"));
2111                             }
2112                             openils.Util.hide("acq-lit-cancel-reason");
2113                         }
2114                     };
2115                     acqLitCancelLineitemsButton._prepared = true;
2116                 }
2117             );
2118         }
2119     };
2120
2121     this._cancelLineitems = function(reason) {
2122         var id_list = this.getSelected().map(function(o) { return o.id(); });
2123         fieldmapper.standardRequest(
2124             ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
2125                 "params": [openils.User.authtoken, id_list, reason],
2126                 "async": true,
2127                 "onresponse": function(r) {
2128                     if (r = openils.Util.readResponse(r)) {
2129                         if (r.li) {
2130                             for (var id in r.li) {
2131                                 self.liCache[id].state(r.li[id].state);
2132                                 self.liCache[id].cancel_reason(
2133                                     r.li[id].cancel_reason
2134                                 );
2135                                 self.updateLiState(self.liCache[id]);
2136                             }
2137                         }
2138                         if (r.lid && self.copyCache) {
2139                             for (var id in r.lid) {
2140                                 if (self.copyCache[id]) {
2141                                     self.copyCache[id].cancel_reason(
2142                                         r.lid[id].cancel_reason
2143                                     );
2144                                     self.updateLidState(self.copyCache[id]);
2145                                 }
2146                             }
2147                         }
2148                     }
2149                 }
2150             }
2151         );
2152     };
2153
2154     this.chooseExportAttr = function() {
2155         if (!acqLitExportAttrSelector._li_setup) {
2156             var self = this;
2157             acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
2158                 {
2159                     "data": acqlimad.toStoreData(
2160                         this.pcrud.search(
2161                             "acqlimad", {"code": li_exportable_attrs}
2162                         )
2163                     )
2164                 }
2165             );
2166             acqLitExportAttrSelector.setValue();
2167             acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
2168             acqLitExportAttrSelector._li_setup = true;
2169         }
2170         openils.Util.show("acq-lit-export-attr-holder", "inline");
2171     };
2172
2173     this.exportAttrList = function() {
2174         var attr_def = acqLitExportAttrSelector.item;
2175         var li_list = this.getSelected();
2176         var value_list = li_list.map(
2177             function(li) {
2178                 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2179                     attr_def.code, "lineitem_marc_attr_definition"
2180                 );
2181             }
2182         ).filter(function(attr) { return Boolean(attr); });
2183
2184         if (value_list.length > 0) {
2185             if (value_list.length < li_list.length) {
2186                 if (!confirm(
2187                     dojo.string.substitute(
2188                         localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
2189                     )
2190                 )) {
2191                     return;
2192                 }
2193             }
2194             try {
2195                 openils.XUL.contentToFileSaveDialog(
2196                     value_list.join("\n"),
2197                     localeStrings.EXPORT_SAVE_DIALOG_TITLE
2198                 );
2199             } catch (E) {
2200                 alert(E);
2201             }
2202         } else {
2203             alert(dojo.string.substitute(
2204                 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
2205             ));
2206         }
2207
2208         openils.Util.hide("acq-lit-export-attr-holder");
2209     };
2210
2211     this.printPO = function() {
2212         if(!this.isPO) return;
2213         progressDialog.show(true);
2214         fieldmapper.standardRequest(
2215             ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
2216             {   async: true,
2217                 params: [this.authtoken, this.isPO, 'html'],
2218                 oncomplete: function(r) {
2219                     progressDialog.hide();
2220                     var evt = openils.Util.readResponse(r);
2221                     if(evt && evt.template_output()) {
2222                         openils.Util.printHtmlString(evt.template_output().data());
2223                     }
2224                 }
2225             }
2226         );
2227     }
2228
2229
2230     this.receivePO = function() {
2231         if (!this.isPO) return;
2232
2233         for (var id in this.liCache) {
2234             /* assumption: liCache reflects exactly the
2235              * set of LIs that belong to our PO */
2236             if (this.liCache[id].state() != "received" &&
2237                 !this.checkLiAlerts(id)) return;
2238         }
2239
2240         this.show('acq-lit-progress-numbers');
2241         var self = this;
2242         fieldmapper.standardRequest(
2243             ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
2244             {   async: true,
2245                 params: [this.authtoken, this.isPO],
2246                 onresponse : function(r) {
2247                     var resp = openils.Util.readResponse(r);
2248                     self._updateProgressNumbers(resp, true);
2249                 },
2250             }
2251         );
2252     }
2253
2254     this.issueReceive = function(obj, rollback) {
2255         /* (For now) there shall be no marking LI or LIDs (un)received
2256          * except from the actual "view PO" interface. */
2257         if (!this.isPO) return;
2258
2259         var part =
2260             {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
2261         var method =
2262             "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
2263
2264         progressDialog.show(true);
2265         fieldmapper.standardRequest(
2266             ["open-ils.acq", method], {
2267                 "async": true,
2268                 "params": [this.authtoken, obj.id()],
2269                 "onresponse": function(r) {
2270                     if (r = openils.Util.readResponse(r)) {
2271                         self.fetchClaimInfo(
2272                             part == "lineitem" ? obj.id() : obj.lineitem(),
2273                             /* force */ true,
2274                             function() { self.handleReceive(r); }
2275                         );
2276                         progressDialog.hide();
2277                     }
2278                 }
2279             }
2280         );
2281     };
2282
2283     /**
2284      * Handles the responses from receive and rollback ML calls.
2285      */
2286     this.handleReceive = function(resp) {
2287         if (resp) {
2288             if (resp.li) {
2289                 for (var li_id in resp.li) {
2290                     for (var key in resp.li[li_id])
2291                         self.liCache[li_id][key](resp.li[li_id][key]);
2292                     self.updateLiState(self.liCache[li_id]);
2293                 }
2294             }
2295             if (resp.po) {
2296                 if (typeof(self.poUpdateCallback) == "function")
2297                     self.poUpdateCallback(resp.po);
2298             }
2299             if (resp.lid) {
2300                 for (var lid_id in resp.lid) {
2301                     for (var key in resp.lid[lid_id])
2302                         self.copyCache[lid_id][key](resp.lid[lid_id][key]);
2303                     self.updateLidState(self.copyCache[lid_id]);
2304                 }
2305             }
2306         }
2307     };
2308
2309     this.rollbackPoReceive = function() {
2310         if(!this.isPO) return;
2311         if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
2312         this.show('acq-lit-progress-numbers');
2313         var self = this;
2314         fieldmapper.standardRequest(
2315             ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
2316             {   async: true,
2317                 params: [this.authtoken, this.isPO],
2318                 onresponse : function(r) {
2319                     var resp = openils.Util.readResponse(r);
2320                     self._updateProgressNumbers(resp, true);
2321                 },
2322             }
2323         );
2324     }
2325
2326     this._updateProgressNumbers = function(resp, reloadOnComplete) {
2327         if(!resp) return;
2328         dojo.byId('acq-pl-lit-li-processed').innerHTML = resp.li;
2329         dojo.byId('acq-pl-lit-lid-processed').innerHTML = resp.lid;
2330         dojo.byId('acq-pl-lit-debits-processed').innerHTML = resp.debits_accrued;
2331         dojo.byId('acq-pl-lit-bibs-processed').innerHTML = resp.bibs;
2332         dojo.byId('acq-pl-lit-indexed-processed').innerHTML = resp.indexed;
2333         dojo.byId('acq-pl-lit-copies-processed').innerHTML = resp.copies;
2334         if(resp.complete && reloadOnComplete) 
2335             location.href = location.href;
2336     }
2337
2338
2339     this._createPO = function(fields) {
2340         var wantall = (fields.create_from == "all");
2341
2342         /* If we're a picklist or purchase order already and the user wants
2343          * all lineitems, we might have pages' worth of lineitems haven't all
2344          * been loaded yet, so getSelected() won't find them.  The server,
2345          * however, should know about all our lineitems, so let's ask the
2346          * server for a complete list.
2347          */
2348
2349         if (wantall) {
2350             this.getSelected(
2351                 true, function(list) {
2352                     self._createPOFromLineitems(fields, list);
2353                 }, /* id_list */ true
2354             );
2355         } else {
2356             this._createPOFromLineitems(fields, this.getSelected(false, null, true /* id_list */));
2357         }
2358     };
2359
2360     this._createPOFromLineitems = function(fields, selected) {
2361         if (selected.length == 0) return;
2362
2363         this.show("acq-lit-progress-numbers");
2364         var po = new fieldmapper.acqpo();
2365         po.provider(this.createPoProviderSelector.attr("value"));
2366         po.ordering_agency(this.createPoAgencySelector.attr("value"));
2367         po.prepayment_required(fields.prepayment_required[0] ? true : false);
2368
2369         fieldmapper.standardRequest(
2370             ["open-ils.acq", "open-ils.acq.purchase_order.create"],
2371             {   async: true,
2372                 params: [
2373                     openils.User.authtoken, 
2374                     po, {
2375                         lineitems : selected,
2376                         create_assets : fields.create_assets[0],
2377                     }
2378                 ],
2379
2380                 onresponse : function(r) {
2381                     var resp = openils.Util.readResponse(r);
2382                     self._updateProgressNumbers(resp);
2383                     if (resp.complete) {
2384                         location.href = oilsBasePath + "/acq/po/view/" +
2385                             resp.purchase_order.id();
2386                     }
2387                 }
2388             }
2389         );
2390     };
2391
2392
2393     this.batchFundWidget = null;
2394
2395     this.applyBatchLiFunds = function() {
2396
2397         var liIds = this.getSelected().map(function(li) { return li.id(); });
2398         if(liIds.length == 0) return; // warn?
2399
2400         var self = this;
2401         batchFundUpdateDialog.show();
2402
2403         if(!this.batchFundWidget) {
2404             this.batchFundWidget = new openils.widget.AutoFieldWidget({
2405                 fmClass : 'acqf',
2406                 selfReference : true,
2407                 labelFormat : fundLabelFormat,
2408                 searchFormat : fundSearchFormat,
2409                 searchFilter : {"active": "t"},
2410                 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
2411                 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2412                 dijitArgs : { "required": true, "labelType": "html" },
2413                 forceSync : true
2414             });
2415             this.batchFundWidget.build();
2416         }
2417
2418         dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
2419         dojo.connect(batchFundUpdateSubmit, 'onClick', 
2420             function() { 
2421
2422                 // TODO: call .dry_run first to test thresholds
2423                 fieldmapper.standardRequest(
2424                     ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
2425                     {
2426                         params : [
2427                             openils.User.authtoken, 
2428                             liIds,
2429                             self.batchFundWidget.widget.attr('value')
2430                         ],
2431                         oncomplete : function(r) {
2432                             var resp = openils.Util.readResponse(r);
2433                             if(resp) {
2434                                 location.href = location.href;
2435                             }
2436                         }
2437                     }
2438                 )
2439             }
2440         );
2441     }
2442
2443     this._deleteLiList = function(list, idx) {
2444         if(idx == null) idx = 0;
2445         if(idx >= list.length) return;
2446
2447         var li = list[idx];
2448         var liId = li.id();
2449
2450         if (this.isPO && (li.state() == "on-order" || li.state() == "received")) {
2451             /* It makes little sense to delete a lineitem from a PO that has
2452              * already been marked 'on-order'.  Especially if EDI is in use,
2453              * such a purchase order will probably have already been shipped
2454              * off to a vendor, and mucking with it at this point could leave
2455              * your data in a bad state that doesn't jive with reality.
2456              *
2457              * I could see making this restriction even firmer.
2458              *
2459              * I could also see adjusting the li state comparisons, extending
2460              * the comparison to the PO's state, and/or providing functions
2461              * that house the logic for comparing states in a single location.
2462              *
2463              * Yes, this will be really annoying if you have selected a lot
2464              * of lineitems to cancel that have been ordered. You'll get a
2465              * confirm dialog for each one.
2466              */
2467
2468             if (!confirm(localeStrings.DEL_LI_FROM_PO)) {
2469                 self._deleteLiList(list, ++idx); /* move on to next in list */
2470                 return;
2471             }
2472         }
2473
2474         fieldmapper.standardRequest(
2475             ['open-ils.acq',
2476              this.isPO ? 'open-ils.acq.purchase_order.lineitem.delete' : 'open-ils.acq.picklist.lineitem.delete'],
2477             {   async: true,
2478                 params: [openils.User.authtoken, liId],
2479                 oncomplete: function(r) {
2480                     self.removeLineitem(liId);
2481                     self._deleteLiList(list, ++idx);
2482                 }
2483             }
2484         );
2485     }
2486
2487     this.editOrderMarc = function(li) {
2488
2489         /*  To run in Firefox directly, must set signed.applets.codebase_principal_support
2490             to true in about:config */
2491
2492         if(!openils.XUL.enableXPConnect()) return;
2493
2494         if(openils.XUL.isXUL()) {
2495             win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
2496         } else {
2497             win = window.open('/xul/server/cat/marcedit.xul'); 
2498         }
2499         var self = this;
2500         win.xulG = {
2501             record : {marc : li.marc(), "rtype": "bre"},
2502             save : {
2503                 label: 'Save Record', // XXX I18N
2504                 func: function(xmlString) {
2505                     li.marc(xmlString);
2506                     fieldmapper.standardRequest(
2507                         ['open-ils.acq', 'open-ils.acq.lineitem.update'],
2508                         {   async: true,
2509                             params: [openils.User.authtoken, li],
2510                             oncomplete: function(r) {
2511                                 openils.Util.readResponse(r);
2512                                 win.close();
2513                                 self.drawInfo(li.id())
2514                             }
2515                         }
2516                     );
2517                 },
2518             },
2519             'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
2520             'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
2521         };
2522     }
2523
2524     this._savePl = function(values) {
2525         this.getSelected(
2526             (values.which == 'all'),
2527             function(list) { self._savePlFromLineitems(values, list); }
2528         );
2529     };
2530
2531     this._savePlFromLineitems = function(values, selected) {
2532         openils.Util.show("acq-lit-generic-progress");
2533
2534         if(values.new_name) {
2535             openils.acq.Picklist.create(
2536                 {name: values.new_name},
2537                 function(id) {
2538                     self._updateLiList(
2539                         id, selected, 0,
2540                         function() {
2541                             location.href =
2542                                 oilsBasePath + "/acq/picklist/view/" + id;
2543                         }
2544                     );
2545                 }
2546             );
2547         } else if(values.existing_pl) {
2548             // update lineitems to use an existing picklist
2549             self._updateLiList(
2550                 values.existing_pl, selected, 0,
2551                 function(){
2552                     location.href =
2553                         oilsBasePath + "/acq/picklist/view/" +
2554                         values.existing_pl;
2555                 }
2556             );
2557         }
2558     };
2559
2560     this._updateLiState = function(values, state) {
2561         progressDialog.show(true);
2562         this.getSelected(
2563             (values.which == 'all'),
2564             function(list) {
2565                 self._updateLiStateFromLineitems(values, state, list);
2566             }
2567         );
2568     };
2569
2570     this._updateLiStateFromLineitems = function(values, state, selected) {
2571         if(!selected.length) return;
2572         dojo.forEach(selected, function(li) {li.state(state);});
2573         self._updateLiList(null, selected, 0,
2574             // TODO consider inline updates for efficiency
2575             function() { location.href = location.href }
2576         );
2577     };
2578
2579     this._updateLiList = function(pl, list, idx, oncomplete) {
2580         if(idx >= list.length) return oncomplete();
2581         var li = list[idx];
2582         if(pl != null) li.picklist(pl);
2583         litGenericProgress.update({maximum: list.length, progress: idx});
2584         new openils.acq.Lineitem({lineitem:li}).update(
2585             function(r) {
2586                 self._updateLiList(pl, list, ++idx, oncomplete);
2587             }
2588         );
2589     }
2590
2591     this._loadPOSelect = function() {
2592         if (!this.createPoProviderSelector) {
2593             var widget = new openils.widget.AutoFieldWidget({
2594                 "fmField": "provider",
2595                 "fmClass": "acqpo",
2596                 "searchFilter": {"active": "t"},
2597                 "parentNode": dojo.byId("acq-lit-po-provider"),
2598                 "dijitArgs": {
2599                     "onChange": function() {
2600                         if (this.item) {
2601                             self._updateCreatePoPrepayCheckbox(
2602                                 this.item.prepayment_required()
2603                             );
2604                         }
2605                     }
2606                 }
2607             });
2608             widget.build(function(w) { self.createPoProviderSelector = w; });
2609         }
2610
2611         if (!this.createPoAgencySelector) {
2612             var widget = new openils.widget.AutoFieldWidget({
2613                 "fmField": "ordering_agency",
2614                 "fmClass": "acqpo",
2615                 "parentNode": dojo.byId("acq-lit-po-agency"),
2616                 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2617             });
2618             widget.build(function(w) { self.createPoAgencySelector = w; });
2619         }
2620     };
2621
2622     this.showRealCopyEditUI = function(li) {
2623         copyList = [];
2624         var self = this;
2625         this.volCache = {};
2626
2627         this._fetchLineitem(li.id(), 
2628             function(fullLi) {
2629                 li = self.liCache[li.id()] = fullLi;
2630
2631                 self.pcrud.search(
2632                     'acp', {
2633                         id : li.lineitem_details().map(
2634                             function(item) { return item.eg_copy_id() }
2635                         )
2636                     }, {
2637                         async : true,
2638                         oncomplete : function(r) {
2639                             try {
2640                                 var r_list = openils.Util.readResponse( r );
2641                                 for (var i = 0; i < r_list.length; i++) {
2642                                     var copy = r_list[i];
2643                                     var volId = copy.call_number();
2644                                     var volume = self.volCache[volId];
2645                                     if(!volume) {
2646                                         volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2647                                     }
2648                                     copy.call_number(volume);
2649                                     copyList.push(copy);
2650                                 }
2651                                 if (xulG) {
2652                                     xulG.volume_item_creator( { 'existing_copies' : copyList } );
2653                                 }
2654                             } catch(E) {
2655                                 alert('error in oncomplete: ' + E);
2656                             }
2657                         }
2658                     }
2659                 );
2660             }
2661         );
2662     },
2663
2664     this.drawBibFinder = function(li) {
2665
2666         var query = '';
2667         var liWrapper = new openils.acq.Lineitem({lineitem:li});
2668
2669         dojo.forEach(
2670             ['isbn', 'upc', 'issn', 'title', 'author'],
2671             function(field) {
2672                 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
2673                 if(val) {
2674                     if(field == 'title' || field == 'author') {
2675                         query += field +':' + val + ' ';
2676                     } else {
2677                         query += 'identifier|' + field + ':' + val + ' ';
2678                     }
2679                 }
2680             }
2681         );
2682
2683         win = window.open(
2684             oilsBasePath + '/acq/lineitem/findbib?query=' + escape(query),
2685             '', 'resizable,scrollbars=1');
2686
2687         win.window.recordFound = function(bibId) { 
2688             win.close();
2689
2690             var attrs = li.attributes();
2691             li.attributes(null);
2692             li.eg_bib_id(bibId);
2693
2694             fieldmapper.standardRequest(
2695                 ["open-ils.acq", "open-ils.acq.lineitem.update"], 
2696                 {
2697                     "params": [openils.User.authtoken, li],
2698                     "async": true,
2699                     "oncomplete": function(r) {
2700                         if(openils.Util.readResponse(r)) {
2701                             location.href = location.href;
2702                         }
2703                     }
2704                 }
2705             );
2706         }
2707     }
2708 }
2709