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