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