]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/acq/common/li_table.js
Acq: add a tooltip to show lineitem alert text description along with code
[working/Evergreen.git] / Open-ILS / web / js / ui / default / acq / common / li_table.js
1 dojo.require('dojo.date.locale');
2 dojo.require('dojo.date.stamp');
3 dojo.require('dijit.form.Button');
4 dojo.require('dijit.form.TextBox');
5 dojo.require('dijit.form.FilteringSelect');
6 dojo.require('dijit.form.Textarea');
7 dojo.require('dijit.Tooltip');
8 dojo.require('dijit.ProgressBar');
9 dojo.require('openils.User');
10 dojo.require('openils.Util');
11 dojo.require('openils.acq.Lineitem');
12 dojo.require('openils.acq.PO');
13 dojo.require('openils.acq.Picklist');
14 dojo.require('openils.widget.AutoFieldWidget');
15 dojo.require('dojo.data.ItemFileReadStore');
16 dojo.require('openils.widget.ProgressDialog');
17 dojo.require('openils.PermaCrud');
18 dojo.require('openils.XUL');
19
20 dojo.requireLocalization('openils.acq', 'acq');
21 var localeStrings = dojo.i18n.getLocalization('openils.acq', 'acq');
22 const XUL_OPAC_WRAPPER = 'chrome://open_ils_staff_client/content/cat/opac.xul';
23 var li_exportable_attrs = ["issn", "isbn", "upc"];
24
25 function nodeByName(name, context) {
26     return dojo.query('[name='+name+']', context)[0];
27 }
28
29
30 var liDetailBatchFields = ['fund', 'owning_lib', 'location', 'collection_code', 'circ_modifier', 'cn_label'];
31 var liDetailFields = liDetailBatchFields.concat(['barcode', 'note']);
32
33 function AcqLiTable() {
34
35     var self = this;
36     this.liCache = {};
37     this.plCache = {};
38     this.poCache = {};
39     this.realDfaCache = {};
40     this.virtDfaCounts = {};
41     this.virtDfaId = -1;
42     this.dfeOffset = 0;
43     this.toggleState = false;
44     this.tbody = dojo.byId('acq-lit-tbody');
45     this.selectors = [];
46     this.noteAcks = {};
47     this.authtoken = openils.User.authtoken;
48     this.pcrud = new openils.PermaCrud();
49     this.rowTemplate = this.tbody.removeChild(dojo.byId('acq-lit-row'));
50     this.copyTbody = dojo.byId('acq-lit-li-details-tbody');
51     this.copyRow = this.copyTbody.removeChild(dojo.byId('acq-lit-li-details-row'));
52     this.copyBatchRow = dojo.byId('acq-lit-li-details-batch-row');
53     this.copyBatchWidgets = {};
54     this.liNotesTbody = dojo.byId('acq-lit-notes-tbody');
55     this.liNotesRow = this.liNotesTbody.removeChild(dojo.byId('acq-lit-notes-row'));
56     this.realCopiesTbody = dojo.byId('acq-lit-real-copies-tbody');
57     this.realCopiesRow = this.realCopiesTbody.removeChild(dojo.byId('acq-lit-real-copies-row'));
58     this._copy_fields_for_acqdf = ['owning_lib', 'location'];
59
60     dojo.connect(acqLitLiActionsSelector, 'onChange', 
61         function() { 
62             self.applySelectedLiAction(this.attr('value')) 
63             acqLitLiActionsSelector.attr('value', '_');
64         });
65
66     acqLitCreatePoSubmit.onClick = function() {
67         acqLitPoCreateDialog.hide();
68         self._createPO(acqLitPoCreateDialog.getValues());
69     }
70
71     acqLitSavePlButton.onClick = function() {
72         acqLitSavePlDialog.hide();
73         self._savePl(acqLitSavePlDialog.getValues());
74     }
75
76     acqLitCancelLiStateButton.onClick = function() {
77         acqLitChangeLiStateDialog.hide();
78     }
79     acqLitSaveLiStateButton.onClick = function() {
80         acqLitChangeLiStateDialog.hide();
81         self._updateLiState(acqLitChangeLiStateDialog.getValues(), acqLitChangeLiStateDialog.attr('state'));
82     }
83
84
85     //dojo.byId('acq-lit-notes-new-button').onclick = function(){acqLitCreateLiNoteDialog.show();}
86
87     dojo.byId('acq-lit-select-toggle').onclick = function(){self.toggleSelect()};
88     dojo.byId('acq-lit-info-back-button').onclick = function(){self.show('list')};
89     dojo.byId('acq-lit-copies-back-button').onclick = function(){self.show('list')};
90     dojo.byId('acq-lit-notes-back-button').onclick = function(){self.show('list')};
91     dojo.byId('acq-lit-real-copies-back-button').onclick = function(){self.show('list')};
92
93     this.reset = function() {
94         while(self.tbody.childNodes[0])
95             self.tbody.removeChild(self.tbody.childNodes[0]);
96         self.selectors = [];
97         self.noteAcks = {};
98     };
99     
100     this.setNext = function(handler) {
101         var link = dojo.byId('acq-lit-next');
102         if(handler) {
103             dojo.style(link, 'visibility', 'visible');
104             link.onclick = handler;
105         } else {
106             dojo.style(link, 'visibility', 'hidden');
107         }
108     };
109
110     this.setPrev = function(handler) {
111         var link = dojo.byId('acq-lit-prev');
112         if(handler) {
113             dojo.style(link, 'visibility', 'visible'); 
114             link.onclick = handler; 
115         } else {
116             dojo.style(link, 'visibility', 'hidden');
117         }
118     };
119
120     this.show = function(div) {
121         openils.Util.hide('acq-lit-table-div');
122         openils.Util.hide('acq-lit-info-div');
123         openils.Util.hide('acq-lit-li-details');
124         openils.Util.hide('acq-lit-notes-div');
125         openils.Util.hide('acq-lit-real-copies-div');
126         switch(div) {
127             case 'list':
128                 openils.Util.show('acq-lit-table-div');
129                 break;
130             case 'info':
131                 openils.Util.show('acq-lit-info-div');
132                 break;
133             case 'copies':
134                 openils.Util.show('acq-lit-li-details');
135                 break;
136             case 'real-copies':
137                 openils.Util.show('acq-lit-real-copies-div');
138                 break;
139             case 'notes':
140                 openils.Util.show('acq-lit-notes-div');
141                 break;
142             default:
143                 if(div) 
144                     openils.Util.show(div);
145         }
146     }
147
148     this.hide = function() {
149         this.show(null);
150     }
151
152     this.toggleSelect = function() {
153         if(self.toggleState) 
154             dojo.forEach(self.selectors, function(i){i.checked = false});
155         else 
156             dojo.forEach(self.selectors, function(i){i.checked = true});
157         self.toggleState = !self.toggleState;
158     };
159
160
161     /** @param all If true, assume all are selected */
162     this.getSelected = function(all) {
163         var selected = [];
164         dojo.forEach(self.selectors, 
165             function(i) { 
166                 if(i.checked || all)
167                     selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
168             }
169         );
170         return selected;
171     };
172
173     this.setRowAttr = function(td, liWrapper, field, type) {
174         var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
175         td.appendChild(document.createTextNode(val));
176     };
177
178     /**
179      * Inserts a single lineitem into the growing table of lineitems
180      * @param {Object} li The lineitem object to insert
181      */
182     this.addLineitem = function(li, skip_final_placement) {
183         this.liCache[li.id()] = li;
184
185         // sort the lineitem notes on edit_time
186         if(!li.lineitem_notes()) li.lineitem_notes([]);
187
188         var liWrapper = new openils.acq.Lineitem({lineitem:li});
189         var row = self.rowTemplate.cloneNode(true);
190         row.setAttribute('li', li.id());
191         var tds = dojo.query('[attr]', row);
192         dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
193         dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
194
195         var isbn = liWrapper.findAttr('isbn', 'lineitem_marc_attr_definition');
196         if(isbn) {
197             // XXX media prefix for added content
198             dojo.query('[name=jacket]', row)[0].setAttribute('src', '/opac/extras/ac/jacket/small/' + isbn);
199         }
200
201         dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
202         dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
203         dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
204
205         this.updateLiNotesCount(li, row);
206
207         // show which PO this lineitem is a member of
208         if(li.purchase_order() && !this.isPO) {
209             var po = 
210                 this.poCache[li.purchase_order()] =
211                 this.poCache[li.purchase_order()] ||
212                 fieldmapper.standardRequest(
213                     ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
214                     {params: [
215                         this.authtoken, li.purchase_order(), {
216                             "flesh_price_summary": true,
217                             "flesh_lineitem_count": true
218                         }
219                     ]});
220             if(po && !this.isMeta) {
221                 openils.Util.show(nodeByName('po', row), 'inline');
222                 var link = nodeByName('po_link', row);
223                 link.setAttribute('href', oilsBasePath + '/acq/po/view/' + li.purchase_order());
224                 link.innerHTML = 'PO: ' + po.name(); // TODO i18n
225             }
226         }
227
228         // show which picklist this lineitem is a member of
229         if(li.picklist() && (this.isPO || this.isMeta)) {
230             var pl = 
231                 this.plCache[li.picklist()] = 
232                 this.plCache[li.picklist()] || 
233                 fieldmapper.standardRequest(
234                     ['open-ils.acq', 'open-ils.acq.picklist.retrieve'],
235                     {params: [this.authtoken, li.picklist()]});
236             if(pl) {
237                 openils.Util.show(nodeByName('pl', row), 'inline');
238                 var link = nodeByName('pl_link', row);
239                 link.setAttribute('href', oilsBasePath + '/acq/picklist/view/' + li.picklist());
240                 link.innerHTML = 'PL: '+pl.name(); // TODO i18n
241             }
242         }
243
244         var countNode = nodeByName('count', row);
245         var count = li.item_count() || 0;
246         if (typeof(this._copy_count_cb) == "function") {
247             this._copy_count_cb(li.id(), count);
248         }
249         countNode.innerHTML = count;
250         countNode.id = 'acq-lit-copy-count-label-' + li.id();
251
252         // lineitem state
253         nodeByName('li_state', row).innerHTML = li.state(); // TODO i18n state labels
254         // lineitem price
255         var priceInput = dojo.query('[name=price]', row)[0];
256         var priceData = liWrapper.getPrice();
257         priceInput.value = (priceData) ? priceData.price : '';
258         priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
259
260         // show either "mark received" or "unreceive" as appropriate
261         this.updateLiReceivedness(li, row);
262
263         if (!skip_final_placement) {
264             self.tbody.appendChild(row);
265             self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
266         } else {
267             return row;
268         }
269     };
270
271     this.updateLiNotesCount = function(li, row) {
272         if (typeof(row) == "undefined")
273             row = dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
274
275         var has_notes = (li.lineitem_notes().filter(
276                 function(o) { return Boolean (o.alert_text()); }
277             ).length > 0);
278
279         /* U+2691 is the code point for a filled-in flag character */
280         nodeByName("notes_alert_flag", row).innerHTML =
281              has_notes ? "⚑" : "";
282         nodeByName("noteslink", row).style.fontStyle =
283             has_notes ? "italic" : "normal";
284         nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
285     };
286
287     this.updateLiReceivedness = function(li, row) {
288         if (typeof(row) == "undefined")
289             row = dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
290
291         var recv_link = nodeByName("receive_link", row);
292         var unrecv_link = nodeByName("unreceive_link", row);
293         var real_copies_link = nodeByName("real_copies_link", row);
294
295         /* handle row coloring for based on LI state */
296         openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
297         openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
298
299         /* handle links that appear/disappear based on whether LI is received */
300         if (this.isPO) {
301             var self = this;
302             switch(li.state()) {
303                 case "on-order":
304                     openils.Util.hide(real_copies_link);
305                     openils.Util.hide(unrecv_link);
306                     openils.Util.show(recv_link, "inline");
307                     recv_link.onclick = function() {
308                         if (self.checkLiAlerts(li.id()))
309                             self.issueReceive(li);
310                     };
311                     return;
312                 case "received":
313                     openils.Util.hide(recv_link);
314                     openils.Util.show(unrecv_link, "inline");
315                     unrecv_link.onclick = function() {
316                         if (confirm(localeStrings.UNRECEIVE_LI))
317                             self.issueReceive(li, /* rollback */ true);
318                     };
319                     // TODO we should allow editing before receipt, in which case the
320                     // test should be "if 1 or more real (acp) copies exist
321                     openils.Util.show(real_copies_link);
322                     real_copies_link.onclick = function() {
323                         self.showRealCopies(li);
324                     }
325                     return;
326             }
327         }
328
329         openils.Util.hide(recv_link);
330         openils.Util.hide(unrecv_link);
331         openils.Util.hide(real_copies_link);
332     };
333
334
335     this._setAlertStore = function() {
336         acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
337             {
338                 "data": acqliat.toStoreData(
339                     this.pcrud.search(
340                         "acqliat", {"id": {"!=": null}}
341                     )
342                 )
343             }
344         );
345         acqLitAlertAlertText.setValue(); /* make the store "live" */
346         acqLitAlertAlertText._store_ready = true;
347     };
348
349     /**
350      * Draws and shows the lineitem notes pane
351      */
352     this.drawLiNotes = function(li) {
353         var self = this;
354
355         if (!acqLitAlertAlertText._store_ready)
356             this._setAlertStore();
357
358         li.lineitem_notes(
359             li.lineitem_notes().sort(
360                 function(a, b) { 
361                     if(a.edit_time() < b.edit_time()) return 1;
362                     return -1;
363                 }
364             )
365         );
366
367         while(this.liNotesTbody.childNodes[0])
368             this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
369         this.show('notes');
370
371         acqLitCreateLiNoteSubmit.onClick = function() {
372             var value = acqLitCreateNoteText.attr('value');
373             if(!value) return;
374             var note = new fieldmapper.acqlin();
375             note.isnew(true);
376             note.value(value);
377             note.lineitem(li.id());
378
379             self.updateLiNotes(li, note);
380         }
381
382         acqLitCreateAlertSubmit.onClick = function() {
383             if (!acqLitAlertAlertText.item) {
384                 alert(localeStrings.ALERT_UNSELECTED);
385                 return;
386             }
387
388             var alert_text = new fieldmapper.acqliat().fromStoreItem(
389                 acqLitAlertAlertText.item
390             );
391             var value = acqLitAlertNoteValue.attr("value") || "";
392
393             var note = new fieldmapper.acqlin();
394             note.isnew(true);
395             note.lineitem(li.id());
396             note.value(value);
397             note.alert_text(alert_text);
398
399             self.updateLiNotes(li, note);
400         }
401
402         dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
403     }
404
405     /**
406      * Draws a single lineitem note in the notes pane
407      */
408     this.addLiNote = function(li, note) {
409         if(note.isdeleted()) return;
410         var self = this;
411         var row = self.liNotesRow.cloneNode(true);
412         nodeByName("value", row).innerHTML = note.value();
413         var alert_node = nodeByName("alert_code", row);
414         if (note.alert_text()) {
415             alert_node.innerHTML = note.alert_text().code();
416             if (note.alert_text().description()) {
417                 new dijit.Tooltip(
418                     {
419                         "connectId": [alert_node],
420                         "label": note.alert_text().description()
421                     }, dojo.create("span", null, alert_node, "after")
422                 );
423             }
424         }
425
426         nodeByName("delete", row).onclick = function() {
427             note.isdeleted(true);
428             self.liNotesTbody.removeChild(row);
429             self.updateLiNotes(li);
430         };
431
432         if(note.edit_time()) {
433             nodeByName("edit_time", row).innerHTML =
434                 dojo.date.locale.format(
435                     dojo.date.stamp.fromISOString(note.edit_time()), 
436                     {formatLength:'short'});
437         }
438
439         self.liNotesTbody.appendChild(row);
440     }
441
442     /**
443      * Updates any new/changed/deleted notes on the server
444      */
445     this.updateLiNotes = function(li, newNote) {
446
447         var notes;
448         if(newNote) {
449             notes = [newNote];
450         } else {
451             notes = li.lineitem_notes().filter(
452                 function(note) {
453                     if(note.ischanged() || note.isnew() || note.isdeleted())
454                         return note;
455                 }
456             );
457         }
458
459         if(notes.length == 0) return;
460         progressDialog.show();
461
462         fieldmapper.standardRequest(
463             ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
464             {   async : true,
465                 params : [this.authtoken, notes],
466                 onresponse : function(r) {
467                     var resp = openils.Util.readResponse(r);
468
469                     if(resp.complete) {
470
471                         if(!newNote) {
472                             // remove the old changed notes
473                             var list = [];
474                             dojo.forEach(li.lineitem_notes(), 
475                                 function(note) {
476                                     if(!(note.ischanged() || note.isnew() || note.isdeleted()))
477                                         list.push(note);
478                                 }
479                             );
480                             li.lineitem_notes(list);
481                         }
482
483                         progressDialog.hide();
484                         self.updateLiNotesCount(li);
485                         self.drawLiNotes(li);
486                         return;
487                     }
488
489                     progressDialog.update(resp);
490                     var newnote = resp.note;
491
492                     if(!newnote.isdeleted()) {
493                         newnote.isnew(false);
494                         newnote.ischanged(false);
495                         li.lineitem_notes().push(newnote);
496                     }
497                 },
498             }
499         );
500     }
501
502     this.updateLiPrice = function(input, li) {
503
504         var price = input.value;
505         var liWrapper = new openils.acq.Lineitem({lineitem:li});
506         var oldPrice = liWrapper.getPrice() || null;
507
508         if(oldPrice) oldPrice = oldPrice.price;
509         if(price == oldPrice) return;
510
511         fieldmapper.standardRequest(
512             ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
513             {   async : true,
514                 params : [this.authtoken, li.id(), price],
515                 oncomplete : function(r) {
516                     openils.Util.readResponse(r);
517                 }
518             }
519         );
520     }
521
522     this.removeLineitem = function(liId) {
523         this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
524         delete this.liCache[liId];
525         //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
526     }
527
528     this.drawInfo = function(liId) {
529         this.show('info');
530         openils.acq.Lineitem.fetchAttrDefs(
531             function() { 
532                 self._fetchLineitem(liId, function(li){self._drawInfo(li);}); 
533             } 
534         );
535     };
536
537     this._fetchLineitem = function(liId, handler) {
538
539         var li = this.liCache[liId];
540         if(li && li.marc() && li.lineitem_details())
541             return handler(li);
542         
543         fieldmapper.standardRequest(
544             ['open-ils.acq', 'open-ils.acq.lineitem.retrieve'],
545             {   async: true,
546
547                 params: [self.authtoken, liId, {
548                     flesh_attrs: true,
549                     flesh_li_details: true,
550                     flesh_fund_debit: true }],
551
552                 oncomplete: function(r) {
553                     var li = openils.Util.readResponse(r);
554                     handler(li)
555                 }
556             }
557         );
558     };
559
560     this._drawInfo = function(li) {
561
562         acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
563
564         if(li.eg_bib_id()) {
565             openils.Util.hide('acq-lit-marc-order-record-label');
566             openils.Util.hide(acqLitEditOrderMarc.domNode);
567             openils.Util.show('acq-lit-marc-real-record-label');
568         } else {
569             openils.Util.show('acq-lit-marc-order-record-label');
570             openils.Util.show(acqLitEditOrderMarc.domNode);
571             openils.Util.hide('acq-lit-marc-real-record-label');
572         }
573
574         this.drawMarcHTML(li);
575         this.infoTbody = dojo.byId('acq-lit-info-tbody');
576
577         if(!this.infoRow)
578             this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
579         while(this.infoTbody.childNodes[0])
580             this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
581
582         for(var i = 0; i < li.attributes().length; i++) {
583             var attr = li.attributes()[i];
584             var row = this.infoRow.cloneNode(true);
585
586             var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
587             var name = openils.acq.Lineitem.attrDefs[type].filter(
588                 function(a) {
589                     return (a.code() == attr.attr_name());
590                 }
591             ).pop().description();
592
593             dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
594             dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
595             this.infoTbody.appendChild(row);
596         }
597
598         if(li.eg_bib_id()) {
599             openils.Util.show('acq-lit-info-cat-link');
600             var link = dojo.byId('acq-lit-info-cat-link').getElementsByTagName('a')[0];
601
602             if(openils.XUL.isXUL()) {
603
604                 var makeRecTab = function() {
605                                     xulG.new_tab(
606                         XUL_OPAC_WRAPPER,
607                                             {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
608                                             {
609                             no_xulG : false, 
610                             show_nav_buttons : true, 
611                             show_print_button : true, 
612                             opac_url : xulG.url_prefix(xulG.urls.opac_rdetail + '?r=' + li.eg_bib_id())
613                         }
614                     );
615                 }
616                 link.setAttribute('href', 'javascript:void(0);');
617                 link.onclick = makeRecTab;
618
619             } else {
620                 var href = link.getAttribute('href');
621                 if(href.match(/=$/))
622                     link.setAttribute('href',  href + li.eg_bib_id());
623             }
624         } else {
625             openils.Util.hide('acq-lit-info-cat-link');
626         }
627     };
628
629     this.drawMarcHTML = function(li) {
630         var params = [null, true, li.marc()];
631         if(li.eg_bib_id()) 
632             params = [li.eg_bib_id(), true];
633
634         fieldmapper.standardRequest(
635             ['open-ils.search', 'open-ils.search.biblio.record.html'],
636             {   async: true,
637                 params: params,
638                 oncomplete: function(r) {
639                     dojo.byId('acq-lit-marc-div').innerHTML = 
640                         openils.Util.readResponse(r);
641                 }
642             }
643         );
644     }
645
646     this.drawCopies = function(liId) {
647         this.show('copies');
648         var self = this;
649         this.copyCache = {};
650         this.copyWidgetCache = {};
651         this.oldCopyWidgetCache = {};
652         this.virtDfaCounts = {};
653         this.realDfaCache = {};
654         this.dfeOffset = 0;
655
656         acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
657         acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
658         acqLitCopyCountInput.attr('value', '0');
659
660         while(this.copyTbody.childNodes[0])
661             this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
662
663         this._drawBatchCopyWidgets();
664
665         this._drawDistribApplied(liId);
666
667         this._fetchDistribFormulas(
668             function() {
669                 openils.acq.Lineitem.fetchAttrDefs(
670                     function() { 
671                         self._fetchLineitem(liId, function(li){self._drawCopies(li);}); 
672                     } 
673                 );
674             }
675         );
676     };
677
678     this._saveDistribAppliedTemplates = function() {
679         if (!this._appliedDistribTemplate) {
680             this._appliedDistribTemplate =
681                 dojo.byId("acq-lit-distrib-applied-tbody").
682                     removeChild(dojo.byId("acq-lit-distrib-applied-row"));
683             dojo.attr(this._appliedDistribTemplate, "id");
684         }
685     };
686
687     this._drawDistribApplied = function(liId) {
688         /* Build this table while hidden to prevent rendering artifacts */
689         openils.Util.hide("acq-lit-distrib-applied-tbody");
690
691         this._saveDistribAppliedTemplates();
692
693         /* Remove any rows in the table from previous populations */
694         dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
695             forEach(dojo.destroy);
696
697         /* Unregister all dijits previously created (for some reason this isn't
698          * covered by the above destroy calls). */
699         dijit.registry.forEach(
700             function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
701         );
702
703         /* Populate the table with our liId */
704         var total = 0;
705         fieldmapper.standardRequest(
706             ["open-ils.acq",
707             "open-ils.acq.distribution_formula_application.ranged.retrieve"],
708             {
709                 "async": true,
710                 "params": [self.authtoken, liId],
711                 "onresponse": function(r) {
712                     var dfa = openils.Util.readResponse(r);
713                     if (dfa) {
714                         total++;
715                         self.realDfaCache[dfa.id()] = dfa;
716                         self._drawDistribAppliedUnit(dfa);
717                     }
718                 },
719                 "oncomplete": function() {
720                     /* Reveal built table */
721                     if (total) {
722                         openils.Util.show(
723                             "acq-lit-distrib-applied-tbody", "table-row-group"
724                         );
725                     }
726                 }
727             }
728         );
729     };
730
731     this._drawDistribAppliedUnit = function(dfa) {
732         var new_row = false;
733         var row = dojo.query(
734             'tr[formula="' + dfa.formula().id() + '"]',
735             "acq-lit-distrib-applied-tbody"
736         )[0];
737
738         if (!row) {
739             new_row = true;
740             row = dojo.clone(this._appliedDistribTemplate);
741             dojo.attr(row, "formula", dfa.formula().id());
742             dojo.query("th", row)[0].innerHTML = dfa.formula().name();
743         }
744
745         var td = dojo.query("td", row)[0];
746
747         dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
748         dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
749
750         if (new_row)
751             dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
752
753         new dijit.form.Button(
754             {
755                 "onClick": function() {
756                     if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
757                         self.deleteDfa(dfa);
758                 },
759                 "label": "X",
760                 /* XXX I /cannot/ make the following work in as a CSS class
761                  * for some reason. So frustrating... */
762                 "style": function(id) {
763                      return (id > 0 ?
764                         "font-weight: bold; color: #c00;" :
765                         "color: #666;");
766                      }(dfa.id()) + "margin: 0 6px;display: inline;"
767             }, "dfa-button-" + dfa.id()
768         );
769         new dijit.Tooltip(
770             {
771                 "connectId": ["dfa-button-" + dfa.id()],
772                 "label": dojo.string.substitute(
773                     localeStrings.DFA_TIP, dfa.id() > 0 ? [
774                         openils.User.formalName(dfa.creator()),
775                         dojo.date.locale.format(
776                             dojo.date.stamp.fromISOString(dfa.create_time()),
777                             {"formatLength":"short"}
778                         )
779                     ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
780                 )
781             }, "dfa-tip-" + dfa.id()
782         );
783     }
784
785     this.deleteDfa = function(dfa) {
786         if (dfa.id() > 0) { /* real */
787             this.pcrud.delete(
788                 dfa, {
789                     "async": true,
790                     "oncomplete": function() {
791                         self._removeDistribApplied(dfa.id());
792                         delete self.realDfaCache[dfa.id()];
793                     }
794                 }
795             );
796         } else { /* virtual */
797             if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
798             this.virtDfaCounts[dfa.formula().id()] = 0;
799             /* hasn't been saved yet, so no need to do anything server side */
800             this._removeDistribApplied(dfa.id());
801         }
802
803     };
804
805     this._removeDistribApplied = function(dfaId) {
806         var re = new RegExp("^dfa-\\w+-" + String(dfaId));
807         dijit.registry.forEach(
808             function(w) { if (re.test(w.id)) w.destroyRecursive(); }
809         );
810         this._removeDistribAppliedEmptyRows();
811     };
812
813     this._removeAllDistribAppliedVirtual = function() {
814         /* Unregister dijits */
815         dijit.registry.forEach(
816             function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
817         );
818         this._removeDistribAppliedEmptyRows();
819     };
820
821     this._removeDistribAppliedEmptyRows = function() {
822         /* Remove any rows with no DFA at all */
823         dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
824             function(o) {
825                 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
826             }
827         );
828     };
829
830     /**
831      * Insert a new row into the distribution formula selection form
832      */
833     this._addDistribFormulaRow = function() {
834         var self = this;
835
836         if (!self.distribForms) {
837             // no formulas, hide the form
838             openils.Util.hide('acq-lit-distrib-formula-tbody');
839             return;
840         }
841
842         if(!this.distribFormulaTemplate) 
843             this.distribFormulaTemplate = 
844                 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
845
846         var row = this.distribFormulaTemplate.cloneNode(true);
847         dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
848
849         this.dfSelector = new dijit.form.FilteringSelect(
850             {"labelAttr": "dynLabel", "labelType": "html"},
851             nodeByName("selector", row)
852         );
853         this._updateFormulaStore();
854         this.dfSelector.fetchProperties =
855             {"sort": [{"attribute": "use_count", "descending": true}]};
856
857         var apply = new dijit.form.Button(
858             {"label": localeStrings.APPLY},
859             nodeByName('set_button', row)
860         ); 
861
862         var reset = new dijit.form.Button(
863             {"label": localeStrings.RESET_FORMULAE, "disabled": true},
864             nodeByName("reset_button", row)  
865         );
866
867         dojo.connect(apply, 'onClick', 
868             function() {
869                 var form_id = self.dfSelector.attr("value");
870                 if(!form_id) return;
871                 self._applyDistribFormula(form_id);
872                 reset.attr("disabled", false);
873             }
874         );
875
876         dojo.connect(reset, 'onClick', 
877             function() {
878                 self.restoreCopyFieldsBeforeDF();
879                 self.virtDfaCounts = {};
880                 self.virtDfaId = -1;
881                 self.dfeOffset = 0;
882                 self._updateFormulaStore();
883                 self._removeAllDistribAppliedVirtual();
884                 reset.attr("disabled", "true");
885             }
886         );
887
888     };
889
890     /**
891      * Applies a distrib formula to the current set of copies
892      */
893     this._applyDistribFormula = function(formula) {
894         if(!formula) return;
895
896         formula = this.distribForms.filter(
897             function(form) { return form.id() == formula; }
898         )[0];
899
900         var copyRows = dojo.query('tr', self.copyTbody);
901
902         if (this.dfeOffset >= copyRows.length) {
903             alert(localeStrings.OUT_OF_COPIES);
904             return;
905         }
906
907         var entries_applied = 0;
908         for(
909             var rowIndex = this.dfeOffset;
910             rowIndex < copyRows.length;
911             rowIndex++
912         ) {
913             
914             var row = copyRows[rowIndex];
915             var copy_id = row.getAttribute('copy_id');
916             var copyWidgets = this.copyWidgetCache[copy_id];
917             var entryIndex = this.dfeOffset;
918             var entry = null;
919
920             // find the correct entry for the current row
921             dojo.forEach(formula.entries(), 
922                 function(e) {
923                     if(!entry) {
924                         entryIndex += e.item_count();
925                         if(entryIndex > rowIndex)
926                             entry = e;
927                     }
928                 }
929             );
930
931             if(entry) {
932                 
933                 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" + 
934                 //  entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
935     
936                 entries_applied++;
937                 this.saveCopyFieldsBeforeDF(copy_id);
938                 this._copy_fields_for_acqdf.forEach(
939                     function(field) {
940                         if(entry[field]()) {
941                             copyWidgets[field].attr('value', (entry[field]()));
942                         }
943                     }
944                 );
945             }
946         }
947
948         if (entries_applied) {
949             this.virtDfaCounts[formula.id()] =
950                 ++(this.virtDfaCounts[formula.id()]) || 1;
951             this._updateFormulaStore();
952             this._drawDistribAppliedUnit(
953                 function(df) {
954                     var dfa = new acqdfa();
955                     dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
956                 }(formula)
957             );
958             this.dfeOffset += entries_applied;
959         };
960     };
961
962     /**
963      * This function updates the DF store for the dropdown so that use_counts
964      * can reflect DF applications from this session before they're saved
965      * server-side.
966      */
967     this._updateFormulaStore = function() {
968         this.dfSelector.store = new dojo.data.ItemFileReadStore(
969             {
970                 "data": self._labelFormulasWithCounts(
971                     acqdf.toStoreData(self.distribForms)
972                 )
973             }
974         );
975     };
976
977     this.saveCopyFieldsBeforeDF = function(copy_id) {
978         var self = this;
979         if (!this.oldCopyWidgetCache[copy_id]) {
980             var copyWidgets = this.copyWidgetCache[copy_id];
981
982             this.oldCopyWidgetCache[copy_id] = {};
983             this._copy_fields_for_acqdf.forEach(
984                 function(f) {
985                     self.oldCopyWidgetCache[copy_id][f] =
986                         copyWidgets[f].attr("value");
987                 }
988             );
989         }
990     };
991
992     this.restoreCopyFieldsBeforeDF = function() {
993         var self = this;
994         for (var copy_id in this.oldCopyWidgetCache) {
995             this._copy_fields_for_acqdf.forEach(
996                 function(f) {
997                     self.copyWidgetCache[copy_id][f].attr(
998                         "value", self.oldCopyWidgetCache[copy_id][f]
999                     );
1000                 }
1001             );
1002         }
1003     };
1004
1005     this._labelFormulasWithCounts = function(store_data) {
1006         for (var key in store_data.items) {
1007             var obj = store_data.items[key];
1008             obj.use_count = Number(obj.use_count); /* needed for sorting */
1009
1010             if (this.virtDfaCounts[obj.id])
1011                 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
1012
1013             obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
1014                 obj.use_count + "]</span>&nbsp; " + obj.name;
1015         }
1016         return store_data;
1017     };
1018
1019     /**
1020      * This method formerly would not refetch the DF formulas if they'd been
1021      * loaded already, but now it always re-fetches, since use_count changes.
1022      */
1023     this._fetchDistribFormulas = function(onload) {
1024         fieldmapper.standardRequest(
1025             ["open-ils.acq",
1026                 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
1027             {
1028                 "async": true,
1029                 "params": [openils.User.authtoken],
1030                 "oncomplete": function(r) {
1031                     self.distribForms = openils.Util.readResponse(r);
1032                     if(!self.distribForms || self.distribForms.length == 0) {
1033                         self.distribForms = [];
1034                     }
1035                     self._addDistribFormulaRow();
1036                     onload();
1037                 }
1038             }
1039         );
1040     }
1041
1042     this._drawBatchCopyWidgets = function() {
1043         var row = this.copyBatchRow;
1044         dojo.forEach(liDetailBatchFields, 
1045             function(field) {
1046                 if(self.copyBatchRowDrawn) {
1047                     self.copyBatchWidgets[field].attr('value', null);
1048                 } else {
1049                     var widget = new openils.widget.AutoFieldWidget({
1050                         fmField : field,
1051                         fmClass : 'acqlid',
1052                         parentNode : dojo.query('[name='+field+']', row)[0],
1053                         orgLimitPerms : ['CREATE_PICKLIST'],
1054                         dijitArgs : {required:false},
1055                         forceSync : true
1056                     });
1057                     widget.build(
1058                         function(w, ww) {
1059                             self.copyBatchWidgets[field] = w;
1060                         }
1061                     );
1062                 }
1063             }
1064         );
1065         this.copyBatchRowDrawn = true;
1066     };
1067
1068     this.batchCopyUpdate = function() {
1069         var self = this;
1070         for(var k in this.copyWidgetCache) {
1071             var cache = this.copyWidgetCache[k];
1072             dojo.forEach(liDetailBatchFields, function(f) {
1073                 var newval = self.copyBatchWidgets[f].attr('value');
1074                 if(newval) cache[f].attr('value', newval);
1075             });
1076         }
1077     };
1078
1079     this._drawCopies = function(li) {
1080         var self = this;
1081
1082         // this button sets the total number of copies for a given lineitem
1083         acqLitAddCopyCount.onClick = function() { 
1084             var count = acqLitCopyCountInput.attr('value');
1085
1086             // add new rows
1087             while(self.copyCount() < count)
1088                 self.addCopy(li); 
1089             
1090             // delete rows if necessary
1091             var diff = self.copyCount() - count;
1092             if(diff > 0) {
1093                 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
1094                 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
1095                     dojo.forEach(rows, function(row) {self.deleteCopy(row); });
1096                 } else {
1097                     acqLitCopyCountInput.attr('value', self.copyCount()+'');
1098                 }
1099             }
1100         }
1101
1102
1103         if(li.lineitem_details().length > 0) {
1104             dojo.forEach(li.lineitem_details(),
1105                 function(copy) {
1106                     self.addCopy(li, copy);
1107                 }
1108             );
1109         } else {
1110             self.addCopy(li);
1111         }
1112     };
1113
1114     this.copyCount = function() {
1115         var count = 0;
1116         for(var id in this.copyCache) {
1117             if(!this.copyCache[id].isdeleted())
1118                 count++;
1119         }
1120         return count;
1121     }
1122
1123     this.virtCopyId = -1;
1124     this.addCopy = function(li, copy) {
1125         var row = this.copyRow.cloneNode(true);
1126         this.copyTbody.appendChild(row);
1127         var self = this;
1128
1129         if(!copy) {
1130             copy = new fieldmapper.acqlid();
1131             copy.isnew(true);
1132             copy.id(this.virtCopyId--);
1133             copy.lineitem(li.id());
1134         }
1135
1136         this.copyCache[copy.id()] = copy;
1137         row.setAttribute('copy_id', copy.id());
1138         self.copyWidgetCache[copy.id()] = {};
1139
1140         acqLitCopyCountInput.attr('value', self.copyCount()+'');
1141
1142         dojo.forEach(liDetailFields,
1143             function(field) {
1144                 var widget = new openils.widget.AutoFieldWidget({
1145                     fmObject : copy,
1146                     fmField : field,
1147                     fmClass : 'acqlid',
1148                     parentNode : dojo.query('[name='+field+']', row)[0],
1149                     orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
1150                     readOnly : Boolean(copy.eg_copy_id())
1151                 });
1152                 widget.build(
1153                     // make sure we capture the value from any async widgets
1154                     function(w, ww) { 
1155                         copy[field](ww.getFormattedValue()) 
1156                         self.copyWidgetCache[copy.id()][field] = w;
1157                     }
1158                 );
1159                 dojo.connect(widget.widget, 'onChange', 
1160                     function(val) { 
1161                         if(copy.isnew() || val != copy[field]()) {
1162                             // prevent setting ischanged() automatically on widget load for existing copies
1163                             copy[field](widget.getFormattedValue()) 
1164                             copy.ischanged(true);
1165                         }
1166                     }
1167                 );
1168             }
1169         );
1170
1171         this.updateLidReceivedness(copy, row);
1172     };
1173
1174     this.updateLidReceivedness = function(copy, row) {
1175         if (typeof(row) == "undefined") {
1176             row = dojo.query(
1177                 'tr[copy_id="' + copy.id() + '"]', this.copyTbody
1178             )[0];
1179         }
1180
1181         var self = this;
1182         var recv_link = nodeByName("receive", row);
1183         var unrecv_link = nodeByName("unreceive", row);
1184         var del_link = nodeByName("delete", row);
1185
1186         if (this.isPO) {
1187             openils.Util.hide(del_link.parentNode);
1188
1189             /* Avoid showing (un)receive links for virtual copies */
1190             if (copy.id() > 0) {
1191                 if(copy.recv_time()) {
1192                     openils.Util.hide(recv_link);
1193                     openils.Util.show(unrecv_link);
1194                     unrecv_link.onclick = function() {
1195                         if (confirm(localeStrings.UNRECEIVE_LID))
1196                             self.issueReceive(copy, /* rollback */ true);
1197                     };
1198                 } else {
1199                     openils.Util.hide(unrecv_link);
1200                     openils.Util.show(recv_link);
1201                     recv_link.onclick = function() {
1202                         if (self.checkLiAlerts(copy.lineitem()))
1203                             self.issueReceive(copy);
1204                     };
1205                 }
1206             } else {
1207                 openils.Util.hide(unrecv_link);
1208                 openils.Util.hide(recv_link);
1209             }
1210         } else {
1211             openils.Util.hide(unrecv_link);
1212             openils.Util.hide(recv_link);
1213
1214             del_link.onclick = function() { self.deleteCopy(row) };
1215             openils.Util.show(del_link.parentNode);
1216         }
1217     }
1218
1219     this._confirmAlert = function(li, lin) {
1220         return confirm(
1221             dojo.string.substitute(
1222                 localeStrings.CONFIRM_LI_ALERT, [
1223                     (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1224                         "title", "lineitem_marc_attr_definition"
1225                     ),
1226                     lin.alert_text().code(),
1227                     lin.alert_text().description() || "",
1228                     lin.value()
1229                 ]
1230             )
1231         );
1232     };
1233
1234     this.checkLiAlerts = function(li_id) {
1235         var li = this.liCache[li_id];
1236
1237         var alert_notes = li.lineitem_notes().filter(
1238             function(o) { return Boolean(o.alert_text()); }
1239         );
1240
1241         /* this is _intentionally_ not done in a call to forEach() ... */
1242         for (var i = 0; i < alert_notes.length; i++) {
1243             if (this.noteAcks[alert_notes[i].id()])
1244                 continue;
1245             else if (!this._confirmAlert(li, alert_notes[i]))
1246                 return false;
1247             else
1248                 this.noteAcks[alert_notes[i].id()] = true;
1249         }
1250
1251         return true;
1252     };
1253
1254     this.deleteCopy = function(row) {
1255         var copy = this.copyCache[row.getAttribute('copy_id')];
1256         copy.isdeleted(true);
1257         if(copy.isnew())
1258             delete this.copyCache[copy.id()];
1259         this.copyTbody.removeChild(row);
1260     }
1261
1262     this._virtDfaCountsAsList = function() {
1263         var L = [];
1264         for (var key in this.virtDfaCounts) {
1265             for (var i = 0; i < this.virtDfaCounts[key]; i++)
1266                 L.push(key);
1267         }
1268         return L;
1269     }
1270
1271     this.saveCopyChanges = function(liId) {
1272         var self = this;
1273         var copies = [];
1274
1275
1276         var total = 0;
1277         for(var id in this.copyCache) {
1278             var c = this.copyCache[id];
1279             if(!c.isdeleted()) total++;
1280             if(c.isnew() || c.ischanged() || c.isdeleted()) {
1281                 if(c.id() < 0) c.id(null);
1282                 copies.push(c);
1283             }
1284         }
1285
1286         if (typeof(this._copy_count_cb) == "function") {
1287             this._copy_count_cb(liId, total);
1288         }
1289
1290         dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
1291
1292
1293         if (copies.length > 0) {
1294             openils.Util.show("acq-lit-update-copies-progress");
1295             fieldmapper.standardRequest(
1296                 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1297                 {   async: true,
1298                     params: [openils.User.authtoken, copies],
1299                     onresponse: function(r) {
1300                         var res = openils.Util.readResponse(r);
1301                         litUpdateCopiesProgress.update(res);
1302                     },
1303                     oncomplete: function() {
1304                         self.drawCopies(liId);
1305                         openils.Util.hide("acq-lit-update-copies-progress");
1306                     }
1307                 }
1308             );
1309         }
1310
1311         var dfa_list = this._virtDfaCountsAsList();
1312         if (dfa_list.length > 0) {
1313             fieldmapper.standardRequest(
1314                 ["open-ils.acq",
1315                 "open-ils.acq.distribution_formula.record_application"],
1316                 {
1317                     "async": true,
1318                     "params": [openils.User.authtoken, dfa_list, liId],
1319                     "onresponse": function(r) {
1320                         var res = openils.Util.readResponse(r);
1321                         if (res && res.length < dfa_list.length)
1322                             alert(localeStrings.DFA_NOT_ALL);
1323                     }
1324                 }
1325             );
1326             this.virtDfaCounts = {};
1327         }
1328     }
1329
1330     this.applySelectedLiAction = function(action) {
1331         var self = this;
1332         switch(action) {
1333
1334             case 'delete_selected':
1335                 this._deleteLiList(self.getSelected());
1336                 break;
1337
1338             case 'create_order':
1339
1340                 if(!this.createPoProviderSelector) {
1341                     var widget = new openils.widget.AutoFieldWidget({
1342                         fmField : 'provider',
1343                         fmClass : 'acqpo',
1344                         searchFilter: {"active": "t"},
1345                         parentNode : dojo.byId('acq-lit-po-provider'),
1346                     });
1347                     widget.build(
1348                         function(w) { self.createPoProviderSelector = w; }
1349                     );
1350                 }
1351
1352                 if(!this.createPoAgencySelector) {
1353                     var widget = new openils.widget.AutoFieldWidget({
1354                         fmField : 'ordering_agency',
1355                         fmClass : 'acqpo',
1356                         parentNode : dojo.byId('acq-lit-po-agency'),
1357                         orgLimitPerms : ['CREATE_PURCHASE_ORDER'],
1358                     });
1359                     widget.build(
1360                         function(w) { self.createPoAgencySelector = w; }
1361                     );
1362                 }
1363
1364          
1365                 acqLitPoCreateDialog.show();
1366                 break;
1367
1368             case 'save_picklist':
1369                 this._loadPLSelect();
1370                 acqLitSavePlDialog.show();
1371                 break;
1372
1373             case 'selector_ready':
1374             case 'order_ready':
1375                 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
1376                 acqLitChangeLiStateDialog.show();
1377                 break;
1378
1379             case 'print_po':
1380                 this.printPO();
1381                 break;
1382
1383             case 'receive_po':
1384                 this.receivePO();
1385                 break;
1386
1387             case 'rollback_receive_po':
1388                 this.rollbackPoReceive();
1389                 break;
1390
1391             case 'create_assets':
1392                 this.createAssets();
1393                 break;
1394
1395             case 'export_attr_list':
1396                 this.chooseExportAttr();
1397                 break;
1398
1399             case 'add_brief_record':
1400                 if(this.isPO)
1401                     location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
1402                 else
1403                     location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
1404         }
1405     }
1406
1407     this.createAssets = function() {
1408         if(!this.isPO) return;
1409         if(!confirm(localeStrings.CREATE_PO_ASSETS_CONFIRM)) return;
1410         this.show('acq-lit-progress-numbers');
1411         var self = this;
1412         fieldmapper.standardRequest(
1413             ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
1414             {   async: true,
1415                 params: [this.authtoken, this.isPO],
1416                 onresponse: function(r) {
1417                     var resp = openils.Util.readResponse(r);
1418                     self._updateProgressNumbers(resp, true);
1419                 }
1420             }
1421         );
1422     }
1423
1424     this.chooseExportAttr = function() {
1425         if (!acqLitExportAttrSelector._li_setup) {
1426             var self = this;
1427             acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
1428                 {
1429                     "data": acqliad.toStoreData(
1430                         this.pcrud.search(
1431                             "acqliad", {"code": li_exportable_attrs}
1432                         )
1433                     )
1434                 }
1435             );
1436             acqLitExportAttrSelector.setValue();
1437             acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
1438             acqLitExportAttrSelector._li_setup = true;
1439         }
1440         openils.Util.show("acq-lit-export-attr-holder", "inline");
1441     };
1442
1443     this.exportAttrList = function() {
1444         var attr_def = acqLitExportAttrSelector.item;
1445         var li_list = this.getSelected();
1446         var value_list = li_list.map(
1447             function(li) {
1448                 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1449                     attr_def.code, "lineitem_marc_attr_definition"
1450                 );
1451             }
1452         ).filter(function(attr) { return Boolean(attr); });
1453
1454         if (value_list.length > 0) {
1455             if (value_list.length < li_list.length) {
1456                 if (!confirm(
1457                     dojo.string.substitute(
1458                         localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
1459                     )
1460                 )) {
1461                     return;
1462                 }
1463             }
1464             try {
1465                 openils.XUL.contentToFileSaveDialog(
1466                     value_list.join("\n"),
1467                     localeStrings.EXPORT_SAVE_DIALOG_TITLE
1468                 );
1469             } catch (E) {
1470                 alert(E);
1471             }
1472         } else {
1473             alert(dojo.string.substitute(
1474                 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
1475             ));
1476         }
1477
1478         openils.Util.hide("acq-lit-export-attr-holder");
1479     };
1480
1481     this.printPO = function() {
1482         if(!this.isPO) return;
1483         progressDialog.show(true);
1484         fieldmapper.standardRequest(
1485             ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
1486             {   async: true,
1487                 params: [this.authtoken, this.isPO, 'html'],
1488                 oncomplete: function(r) {
1489                     progressDialog.hide();
1490                     var evt = openils.Util.readResponse(r);
1491                     if(evt && evt.template_output()) {
1492                         win = window.open('','', 'resizable,width=800,height=600,scrollbars=1');
1493                         win.document.body.innerHTML = evt.template_output().data();
1494                     }
1495                 }
1496             }
1497         );
1498     }
1499
1500
1501     this.receivePO = function() {
1502         if (!this.isPO) return;
1503
1504         for (var id in this.liCache) {
1505             /* assumption: liCache reflects exactly the
1506              * set of LIs that belong to our PO */
1507             if (this.liCache[id].state() != "received" &&
1508                 !this.checkLiAlerts(id)) return;
1509         }
1510
1511         this.show('acq-lit-progress-numbers');
1512         var self = this;
1513         fieldmapper.standardRequest(
1514             ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
1515             {   async: true,
1516                 params: [this.authtoken, this.isPO],
1517                 onresponse : function(r) {
1518                     var resp = openils.Util.readResponse(r);
1519                     self._updateProgressNumbers(resp, true);
1520                 },
1521             }
1522         );
1523     }
1524
1525     this.issueReceive = function(obj, rollback) {
1526         /* (For now) there shall be no marking LI or LIDs (un)received
1527          * except from the actual "view PO" interface. */
1528         if (!this.isPO) return;
1529
1530         var part =
1531             {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
1532         var method =
1533             "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
1534
1535         progressDialog.show(true);
1536         fieldmapper.standardRequest(
1537             ["open-ils.acq", method], {
1538                 "async": true,
1539                 "params": [this.authtoken, obj.id()],
1540                 "onresponse": function(r) {
1541                     self.handleReceive(openils.Util.readResponse(r));
1542                 },
1543                 "oncomplete": function() { progressDialog.hide(); }
1544             }
1545         );
1546     };
1547
1548     /**
1549      * Handles the responses from receive and rollback ML calls.
1550      */
1551     this.handleReceive = function(resp) {
1552         if (resp) {
1553             if (resp.li) {
1554                 for (var li_id in resp.li) {
1555                     for (var key in resp.li[li_id])
1556                         self.liCache[li_id][key](resp.li[li_id][key]);
1557                     self.updateLiReceivedness(self.liCache[li_id]);
1558                 }
1559             }
1560             if (resp.po) {
1561                 if (typeof(self.poUpdateCallback) == "function")
1562                     self.poUpdateCallback(resp.po);
1563             }
1564             if (resp.lid) {
1565                 for (var lid_id in resp.lid) {
1566                     for (var key in resp.lid[lid_id])
1567                         self.copyCache[lid_id][key](resp.lid[lid_id][key]);
1568                     self.updateLidReceivedness(self.copyCache[lid_id]);
1569                 }
1570             }
1571         }
1572     };
1573
1574     this.rollbackPoReceive = function() {
1575         if(!this.isPO) return;
1576         if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
1577         this.show('acq-lit-progress-numbers');
1578         var self = this;
1579         fieldmapper.standardRequest(
1580             ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
1581             {   async: true,
1582                 params: [this.authtoken, this.isPO],
1583                 onresponse : function(r) {
1584                     var resp = openils.Util.readResponse(r);
1585                     self._updateProgressNumbers(resp, true);
1586                 },
1587             }
1588         );
1589     }
1590
1591     this._updateProgressNumbers = function(resp, reloadOnComplete) {
1592         if(!resp) return;
1593         dojo.byId('acq-pl-lit-li-processed').innerHTML = resp.li;
1594         dojo.byId('acq-pl-lit-lid-processed').innerHTML = resp.lid;
1595         dojo.byId('acq-pl-lit-debits-processed').innerHTML = resp.debits_accrued;
1596         dojo.byId('acq-pl-lit-bibs-processed').innerHTML = resp.bibs;
1597         dojo.byId('acq-pl-lit-indexed-processed').innerHTML = resp.indexed;
1598         dojo.byId('acq-pl-lit-copies-processed').innerHTML = resp.copies;
1599         if(resp.complete && reloadOnComplete) 
1600             location.href = location.href;
1601     }
1602
1603
1604     this._createPO = function(fields) {
1605         this.show('acq-lit-progress-numbers');
1606         var po = new fieldmapper.acqpo();
1607         po.provider(this.createPoProviderSelector.attr('value'));
1608         po.ordering_agency(this.createPoAgencySelector.attr('value'));
1609
1610         var selected = this.getSelected( (fields.create_from == 'all') );
1611         if(selected.length == 0) return;
1612
1613         var max = selected.length * 3;
1614
1615         var self = this;
1616         fieldmapper.standardRequest(
1617             ['open-ils.acq', 'open-ils.acq.purchase_order.create'],
1618             {   async: true,
1619                 params: [
1620                     openils.User.authtoken, 
1621                     po, 
1622                     {
1623                         lineitems : selected.map(function(li) { return li.id() }),
1624                         create_assets : fields.create_assets[0],
1625                     }
1626                 ],
1627
1628                 onresponse : function(r) {
1629                     var resp = openils.Util.readResponse(r);
1630                     self._updateProgressNumbers(resp);
1631                     if(resp.complete) 
1632                         location.href = oilsBasePath + '/eg/acq/po/view/' + resp.purchase_order.id();
1633                 }
1634             }
1635         );
1636     }
1637
1638     this._deleteLiList = function(list, idx) {
1639         if(idx == null) idx = 0;
1640         if(idx >= list.length) return;
1641         var liId = list[idx].id();
1642         fieldmapper.standardRequest(
1643             ['open-ils.acq', 'open-ils.acq.lineitem.delete'],
1644             {   async: true,
1645                 params: [openils.User.authtoken, liId],
1646                 oncomplete: function(r) {
1647                     self.removeLineitem(liId);
1648                     self._deleteLiList(list, ++idx);
1649                 }
1650             }
1651         );
1652     }
1653
1654     this.editOrderMarc = function(li) {
1655
1656         /*  To run in Firefox directly, must set signed.applets.codebase_principal_support
1657             to true in about:config */
1658
1659         if(!openils.XUL.enableXPConnect()) return;
1660
1661         if(openils.XUL.isXUL()) {
1662             win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
1663         } else {
1664             win = window.open('/xul/server/cat/marcedit.xul'); 
1665         }
1666         var self = this;
1667         win.xulG = {
1668             record : {marc : li.marc()},
1669             save : {
1670                 label: 'Save Record', // XXX I18N
1671                 func: function(xmlString) {
1672                     li.marc(xmlString);
1673                     fieldmapper.standardRequest(
1674                         ['open-ils.acq', 'open-ils.acq.lineitem.update'],
1675                         {   async: true,
1676                             params: [openils.User.authtoken, li],
1677                             oncomplete: function(r) {
1678                                 openils.Util.readResponse(r);
1679                                 win.close();
1680                                 self.drawInfo(li.id())
1681                             }
1682                         }
1683                     );
1684                 },
1685             }
1686         };
1687     }
1688
1689     this._savePl = function(values) {
1690         var self = this;
1691         var selected = this.getSelected( (values.which == 'all') );
1692         openils.Util.show('acq-lit-generic-progress');
1693
1694         if(values.new_name) {
1695             openils.acq.Picklist.create(
1696                 {name: values.new_name}, 
1697                 function(id) {
1698                     self._updateLiList(id, selected, 0, 
1699                         function(){
1700                             location.href = oilsBasePath + '/eg/acq/picklist/view/' + id;
1701                         });
1702                 }
1703             );
1704         } else if(values.existing_pl) {
1705             // update lineitems to use an existing picklist
1706             self._updateLiList(values.existing_pl, selected, 0, 
1707                 function(){
1708                     location.href = oilsBasePath + '/eg/acq/picklist/view/' + values.existing_pl;
1709                 });
1710         }
1711     }
1712
1713     this._updateLiState = function(values, state) {
1714         var self = this;
1715         var selected = this.getSelected( (values.which == 'all') );
1716         if(!selected.length) return;
1717         dojo.forEach(selected, function(li) {li.state(state);});
1718         self._updateLiList(null, selected, 0, 
1719             // TODO consider inline updates for efficiency
1720             function() { location.href = location.href }
1721         );
1722     }
1723
1724     this._updateLiList = function(pl, list, idx, oncomplete) {
1725         if(idx >= list.length) return oncomplete();
1726         var li = list[idx];
1727         if(pl != null) li.picklist(pl);
1728         litGenericProgress.update({maximum: list.length, progress: idx});
1729         new openils.acq.Lineitem({lineitem:li}).update(
1730             function(r) {
1731                 self._updateLiList(pl, list, ++idx, oncomplete);
1732             }
1733         );
1734     }
1735
1736     this._loadPLSelect = function() {
1737         if(this._plSelectLoaded) return;
1738         var plList = [];
1739         function handleResponse(r) {
1740             plList.push(r.recv().content());
1741         }
1742         var method = 'open-ils.acq.picklist.user.retrieve';
1743         fieldmapper.standardRequest(
1744             ['open-ils.acq', method],
1745             {   async: true,
1746                 params: [this.authtoken],
1747                 onresponse: handleResponse,
1748                 oncomplete: function() {
1749                     self._plSelectLoaded = true;
1750                     acqLitAddExistingSelect.store = 
1751                         new dojo.data.ItemFileReadStore({data:acqpl.toStoreData(plList)});
1752                     acqLitAddExistingSelect.setValue();
1753                 }
1754             }
1755         );
1756     }
1757
1758     // grab the li-details for this lineitem, grab the linked copies and volumes, add them to the table
1759     this.showRealCopies = function(li) {
1760         while(this.realCopiesTbody.childNodes[0])
1761             this.realCopiesTbody.removeChild(this.realCopiesTbody.childNodes[0]);
1762         this.show('real-copies');
1763
1764         this.realCopyList = [];
1765         this.volCache = {};
1766         var tabIndex = 1000;
1767         var self = this;
1768
1769         acqLitSaveRealCopies.onClick = function() {
1770             self.saveRealCopies();
1771         }
1772
1773         this._fetchLineitem(li.id(), 
1774             function(fullLi) {
1775                 li = self.liCache[li.id()] = fullLi;
1776
1777                 self.pcrud.search(
1778                     'acp', {
1779                         id : li.lineitem_details().map(
1780                             function(item) { return item.eg_copy_id() }
1781                         )
1782                     }, {
1783                         async : true,
1784                         streaming : true,
1785                         onresponse : function(r) {
1786                             var copy = openils.Util.readResponse(r);
1787                             var volId = copy.call_number();
1788                             var volume = self.volCache[volId];
1789                             if(!volume) {
1790                                 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
1791                             }
1792                             self.addRealCopy(volume, copy, tabIndex++);
1793                         }
1794                     }
1795                 );
1796             }
1797         );
1798     }
1799
1800     this.addRealCopy = function(volume, copy, tabIndex) {
1801         var row = this.realCopiesRow.cloneNode(true);
1802         this.realCopyList.push(copy);
1803
1804         var selectNode;
1805         dojo.forEach(
1806             ['owning_lib', 'location', 'circ_modifier', 'label', 'barcode'],
1807
1808             function(field) {
1809                 var isvol = (field == 'owning_lib' || field == 'label');
1810                 var widget = new openils.widget.AutoFieldWidget({
1811                     fmField : field,
1812                     fmObject : isvol ? volume : copy,
1813                     parentNode : nodeByName(field, row),
1814                     readOnly : (field != 'barcode'),
1815                 });
1816
1817                 var widgetDrawn = null;
1818
1819                 if(field == 'barcode') {
1820
1821                     widgetDrawn = function(w, ww) {
1822                         var node = w.domNode;
1823                         node.setAttribute('tabindex', ''+tabIndex);
1824
1825                         // on enter, select the next barcode input
1826                         dojo.connect(w, 'onKeyDown',
1827                             function(e) {
1828                                 if(e.keyCode == dojo.keys.ENTER) {
1829                                     var ti = node.getAttribute('tabindex');
1830                                     var nextNode = dojo.query('[tabindex=' + String(Number(ti) + 1) + ']', self.realCopiesTbody)[0];
1831                                     if(nextNode) nextNode.select();
1832                                 }
1833                             }
1834                         );
1835
1836                         dojo.connect(w, 'onChange', 
1837                             function(val) { 
1838                                 if(!val || val == copy.barcode()) return;
1839                                 copy.ischanged(true);
1840                                 copy.barcode(val);
1841                             }
1842                         );
1843
1844
1845                         if(self.realCopiesTbody.getElementsByTagName('TR').length == 0)
1846                             selectNode = node;
1847                     }
1848                 }
1849
1850                 widget.build(widgetDrawn);
1851             }
1852         );
1853
1854         this.realCopiesTbody.appendChild(row);
1855         if(selectNode) selectNode.select();
1856     };
1857
1858     this.saveRealCopies = function() {
1859         progressDialog.show(true);
1860         var list = this.realCopyList.filter(function(copy) { return copy.ischanged(); });
1861         this.pcrud.update(list, {oncomplete: function() { 
1862             progressDialog.hide();
1863             self.show('list');
1864         }});
1865     }
1866 }