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