]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/acq/common/li_table.js
Acq: Indicate presence of alerts among notes in lineitem table interface
[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         if (note.alert_text())
414             nodeByName("alert_code", row).innerHTML = note.alert_text().code();
415
416         nodeByName("delete", row).onclick = function() {
417             note.isdeleted(true);
418             self.liNotesTbody.removeChild(row);
419             self.updateLiNotes(li);
420         };
421
422         if(note.edit_time()) {
423             nodeByName("edit_time", row).innerHTML =
424                 dojo.date.locale.format(
425                     dojo.date.stamp.fromISOString(note.edit_time()), 
426                     {formatLength:'short'});
427         }
428
429         self.liNotesTbody.appendChild(row);
430     }
431
432     /**
433      * Updates any new/changed/deleted notes on the server
434      */
435     this.updateLiNotes = function(li, newNote) {
436
437         var notes;
438         if(newNote) {
439             notes = [newNote];
440         } else {
441             notes = li.lineitem_notes().filter(
442                 function(note) {
443                     if(note.ischanged() || note.isnew() || note.isdeleted())
444                         return note;
445                 }
446             );
447         }
448
449         if(notes.length == 0) return;
450         progressDialog.show();
451
452         fieldmapper.standardRequest(
453             ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
454             {   async : true,
455                 params : [this.authtoken, notes],
456                 onresponse : function(r) {
457                     var resp = openils.Util.readResponse(r);
458
459                     if(resp.complete) {
460
461                         if(!newNote) {
462                             // remove the old changed notes
463                             var list = [];
464                             dojo.forEach(li.lineitem_notes(), 
465                                 function(note) {
466                                     if(!(note.ischanged() || note.isnew() || note.isdeleted()))
467                                         list.push(note);
468                                 }
469                             );
470                             li.lineitem_notes(list);
471                         }
472
473                         progressDialog.hide();
474                         self.updateLiNotesCount(li);
475                         self.drawLiNotes(li);
476                         return;
477                     }
478
479                     progressDialog.update(resp);
480                     var newnote = resp.note;
481
482                     if(!newnote.isdeleted()) {
483                         newnote.isnew(false);
484                         newnote.ischanged(false);
485                         li.lineitem_notes().push(newnote);
486                     }
487                 },
488             }
489         );
490     }
491
492     this.updateLiPrice = function(input, li) {
493
494         var price = input.value;
495         var liWrapper = new openils.acq.Lineitem({lineitem:li});
496         var oldPrice = liWrapper.getPrice() || null;
497
498         if(oldPrice) oldPrice = oldPrice.price;
499         if(price == oldPrice) return;
500
501         fieldmapper.standardRequest(
502             ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
503             {   async : true,
504                 params : [this.authtoken, li.id(), price],
505                 oncomplete : function(r) {
506                     openils.Util.readResponse(r);
507                 }
508             }
509         );
510     }
511
512     this.removeLineitem = function(liId) {
513         this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
514         delete this.liCache[liId];
515         //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
516     }
517
518     this.drawInfo = function(liId) {
519         this.show('info');
520         openils.acq.Lineitem.fetchAttrDefs(
521             function() { 
522                 self._fetchLineitem(liId, function(li){self._drawInfo(li);}); 
523             } 
524         );
525     };
526
527     this._fetchLineitem = function(liId, handler) {
528
529         var li = this.liCache[liId];
530         if(li && li.marc() && li.lineitem_details())
531             return handler(li);
532         
533         fieldmapper.standardRequest(
534             ['open-ils.acq', 'open-ils.acq.lineitem.retrieve'],
535             {   async: true,
536
537                 params: [self.authtoken, liId, {
538                     flesh_attrs: true,
539                     flesh_li_details: true,
540                     flesh_fund_debit: true }],
541
542                 oncomplete: function(r) {
543                     var li = openils.Util.readResponse(r);
544                     handler(li)
545                 }
546             }
547         );
548     };
549
550     this._drawInfo = function(li) {
551
552         acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
553
554         if(li.eg_bib_id()) {
555             openils.Util.hide('acq-lit-marc-order-record-label');
556             openils.Util.hide(acqLitEditOrderMarc.domNode);
557             openils.Util.show('acq-lit-marc-real-record-label');
558         } else {
559             openils.Util.show('acq-lit-marc-order-record-label');
560             openils.Util.show(acqLitEditOrderMarc.domNode);
561             openils.Util.hide('acq-lit-marc-real-record-label');
562         }
563
564         this.drawMarcHTML(li);
565         this.infoTbody = dojo.byId('acq-lit-info-tbody');
566
567         if(!this.infoRow)
568             this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
569         while(this.infoTbody.childNodes[0])
570             this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
571
572         for(var i = 0; i < li.attributes().length; i++) {
573             var attr = li.attributes()[i];
574             var row = this.infoRow.cloneNode(true);
575
576             var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
577             var name = openils.acq.Lineitem.attrDefs[type].filter(
578                 function(a) {
579                     return (a.code() == attr.attr_name());
580                 }
581             ).pop().description();
582
583             dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
584             dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
585             this.infoTbody.appendChild(row);
586         }
587
588         if(li.eg_bib_id()) {
589             openils.Util.show('acq-lit-info-cat-link');
590             var link = dojo.byId('acq-lit-info-cat-link').getElementsByTagName('a')[0];
591
592             if(openils.XUL.isXUL()) {
593
594                 var makeRecTab = function() {
595                                     xulG.new_tab(
596                         XUL_OPAC_WRAPPER,
597                                             {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
598                                             {
599                             no_xulG : false, 
600                             show_nav_buttons : true, 
601                             show_print_button : true, 
602                             opac_url : xulG.url_prefix(xulG.urls.opac_rdetail + '?r=' + li.eg_bib_id())
603                         }
604                     );
605                 }
606                 link.setAttribute('href', 'javascript:void(0);');
607                 link.onclick = makeRecTab;
608
609             } else {
610                 var href = link.getAttribute('href');
611                 if(href.match(/=$/))
612                     link.setAttribute('href',  href + li.eg_bib_id());
613             }
614         } else {
615             openils.Util.hide('acq-lit-info-cat-link');
616         }
617     };
618
619     this.drawMarcHTML = function(li) {
620         var params = [null, true, li.marc()];
621         if(li.eg_bib_id()) 
622             params = [li.eg_bib_id(), true];
623
624         fieldmapper.standardRequest(
625             ['open-ils.search', 'open-ils.search.biblio.record.html'],
626             {   async: true,
627                 params: params,
628                 oncomplete: function(r) {
629                     dojo.byId('acq-lit-marc-div').innerHTML = 
630                         openils.Util.readResponse(r);
631                 }
632             }
633         );
634     }
635
636     this.drawCopies = function(liId) {
637         this.show('copies');
638         var self = this;
639         this.copyCache = {};
640         this.copyWidgetCache = {};
641         this.oldCopyWidgetCache = {};
642         this.virtDfaCounts = {};
643         this.realDfaCache = {};
644         this.dfeOffset = 0;
645
646         acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
647         acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
648         acqLitCopyCountInput.attr('value', '0');
649
650         while(this.copyTbody.childNodes[0])
651             this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
652
653         this._drawBatchCopyWidgets();
654
655         this._drawDistribApplied(liId);
656
657         this._fetchDistribFormulas(
658             function() {
659                 openils.acq.Lineitem.fetchAttrDefs(
660                     function() { 
661                         self._fetchLineitem(liId, function(li){self._drawCopies(li);}); 
662                     } 
663                 );
664             }
665         );
666     };
667
668     this._saveDistribAppliedTemplates = function() {
669         if (!this._appliedDistribTemplate) {
670             this._appliedDistribTemplate =
671                 dojo.byId("acq-lit-distrib-applied-tbody").
672                     removeChild(dojo.byId("acq-lit-distrib-applied-row"));
673             dojo.attr(this._appliedDistribTemplate, "id");
674         }
675     };
676
677     this._drawDistribApplied = function(liId) {
678         /* Build this table while hidden to prevent rendering artifacts */
679         openils.Util.hide("acq-lit-distrib-applied-tbody");
680
681         this._saveDistribAppliedTemplates();
682
683         /* Remove any rows in the table from previous populations */
684         dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
685             forEach(dojo.destroy);
686
687         /* Unregister all dijits previously created (for some reason this isn't
688          * covered by the above destroy calls). */
689         dijit.registry.forEach(
690             function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
691         );
692
693         /* Populate the table with our liId */
694         var total = 0;
695         fieldmapper.standardRequest(
696             ["open-ils.acq",
697             "open-ils.acq.distribution_formula_application.ranged.retrieve"],
698             {
699                 "async": true,
700                 "params": [self.authtoken, liId],
701                 "onresponse": function(r) {
702                     var dfa = openils.Util.readResponse(r);
703                     if (dfa) {
704                         total++;
705                         self.realDfaCache[dfa.id()] = dfa;
706                         self._drawDistribAppliedUnit(dfa);
707                     }
708                 },
709                 "oncomplete": function() {
710                     /* Reveal built table */
711                     if (total) {
712                         openils.Util.show(
713                             "acq-lit-distrib-applied-tbody", "table-row-group"
714                         );
715                     }
716                 }
717             }
718         );
719     };
720
721     this._drawDistribAppliedUnit = function(dfa) {
722         var new_row = false;
723         var row = dojo.query(
724             'tr[formula="' + dfa.formula().id() + '"]',
725             "acq-lit-distrib-applied-tbody"
726         )[0];
727
728         if (!row) {
729             new_row = true;
730             row = dojo.clone(this._appliedDistribTemplate);
731             dojo.attr(row, "formula", dfa.formula().id());
732             dojo.query("th", row)[0].innerHTML = dfa.formula().name();
733         }
734
735         var td = dojo.query("td", row)[0];
736
737         dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
738         dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
739
740         if (new_row)
741             dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
742
743         new dijit.form.Button(
744             {
745                 "onClick": function() {
746                     if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
747                         self.deleteDfa(dfa);
748                 },
749                 "label": "X",
750                 /* XXX I /cannot/ make the following work in as a CSS class
751                  * for some reason. So frustrating... */
752                 "style": function(id) {
753                      return (id > 0 ?
754                         "font-weight: bold; color: #c00;" :
755                         "color: #666;");
756                      }(dfa.id()) + "margin: 0 6px;display: inline;"
757             }, "dfa-button-" + dfa.id()
758         );
759         new dijit.Tooltip(
760             {
761                 "connectId": ["dfa-button-" + dfa.id()],
762                 "label": dojo.string.substitute(
763                     localeStrings.DFA_TIP, dfa.id() > 0 ? [
764                         openils.User.formalName(dfa.creator()),
765                         dojo.date.locale.format(
766                             dojo.date.stamp.fromISOString(dfa.create_time()),
767                             {"formatLength":"short"}
768                         )
769                     ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
770                 )
771             }, "dfa-tip-" + dfa.id()
772         );
773     }
774
775     this.deleteDfa = function(dfa) {
776         if (dfa.id() > 0) { /* real */
777             this.pcrud.delete(
778                 dfa, {
779                     "async": true,
780                     "oncomplete": function() {
781                         self._removeDistribApplied(dfa.id());
782                         delete self.realDfaCache[dfa.id()];
783                     }
784                 }
785             );
786         } else { /* virtual */
787             if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
788             this.virtDfaCounts[dfa.formula().id()] = 0;
789             /* hasn't been saved yet, so no need to do anything server side */
790             this._removeDistribApplied(dfa.id());
791         }
792
793     };
794
795     this._removeDistribApplied = function(dfaId) {
796         var re = new RegExp("^dfa-\\w+-" + String(dfaId));
797         dijit.registry.forEach(
798             function(w) { if (re.test(w.id)) w.destroyRecursive(); }
799         );
800         this._removeDistribAppliedEmptyRows();
801     };
802
803     this._removeAllDistribAppliedVirtual = function() {
804         /* Unregister dijits */
805         dijit.registry.forEach(
806             function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
807         );
808         this._removeDistribAppliedEmptyRows();
809     };
810
811     this._removeDistribAppliedEmptyRows = function() {
812         /* Remove any rows with no DFA at all */
813         dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
814             function(o) {
815                 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
816             }
817         );
818     };
819
820     /**
821      * Insert a new row into the distribution formula selection form
822      */
823     this._addDistribFormulaRow = function() {
824         var self = this;
825
826         if (!self.distribForms) {
827             // no formulas, hide the form
828             openils.Util.hide('acq-lit-distrib-formula-tbody');
829             return;
830         }
831
832         if(!this.distribFormulaTemplate) 
833             this.distribFormulaTemplate = 
834                 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
835
836         var row = this.distribFormulaTemplate.cloneNode(true);
837         dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
838
839         this.dfSelector = new dijit.form.FilteringSelect(
840             {"labelAttr": "dynLabel", "labelType": "html"},
841             nodeByName("selector", row)
842         );
843         this._updateFormulaStore();
844         this.dfSelector.fetchProperties =
845             {"sort": [{"attribute": "use_count", "descending": true}]};
846
847         var apply = new dijit.form.Button(
848             {"label": localeStrings.APPLY},
849             nodeByName('set_button', row)
850         ); 
851
852         var reset = new dijit.form.Button(
853             {"label": localeStrings.RESET_FORMULAE, "disabled": true},
854             nodeByName("reset_button", row)  
855         );
856
857         dojo.connect(apply, 'onClick', 
858             function() {
859                 var form_id = self.dfSelector.attr("value");
860                 if(!form_id) return;
861                 self._applyDistribFormula(form_id);
862                 reset.attr("disabled", false);
863             }
864         );
865
866         dojo.connect(reset, 'onClick', 
867             function() {
868                 self.restoreCopyFieldsBeforeDF();
869                 self.virtDfaCounts = {};
870                 self.virtDfaId = -1;
871                 self.dfeOffset = 0;
872                 self._updateFormulaStore();
873                 self._removeAllDistribAppliedVirtual();
874                 reset.attr("disabled", "true");
875             }
876         );
877
878     };
879
880     /**
881      * Applies a distrib formula to the current set of copies
882      */
883     this._applyDistribFormula = function(formula) {
884         if(!formula) return;
885
886         formula = this.distribForms.filter(
887             function(form) { return form.id() == formula; }
888         )[0];
889
890         var copyRows = dojo.query('tr', self.copyTbody);
891
892         if (this.dfeOffset >= copyRows.length) {
893             alert(localeStrings.OUT_OF_COPIES);
894             return;
895         }
896
897         var entries_applied = 0;
898         for(
899             var rowIndex = this.dfeOffset;
900             rowIndex < copyRows.length;
901             rowIndex++
902         ) {
903             
904             var row = copyRows[rowIndex];
905             var copy_id = row.getAttribute('copy_id');
906             var copyWidgets = this.copyWidgetCache[copy_id];
907             var entryIndex = this.dfeOffset;
908             var entry = null;
909
910             // find the correct entry for the current row
911             dojo.forEach(formula.entries(), 
912                 function(e) {
913                     if(!entry) {
914                         entryIndex += e.item_count();
915                         if(entryIndex > rowIndex)
916                             entry = e;
917                     }
918                 }
919             );
920
921             if(entry) {
922                 
923                 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" + 
924                 //  entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
925     
926                 entries_applied++;
927                 this.saveCopyFieldsBeforeDF(copy_id);
928                 this._copy_fields_for_acqdf.forEach(
929                     function(field) {
930                         if(entry[field]()) {
931                             copyWidgets[field].attr('value', (entry[field]()));
932                         }
933                     }
934                 );
935             }
936         }
937
938         if (entries_applied) {
939             this.virtDfaCounts[formula.id()] =
940                 ++(this.virtDfaCounts[formula.id()]) || 1;
941             this._updateFormulaStore();
942             this._drawDistribAppliedUnit(
943                 function(df) {
944                     var dfa = new acqdfa();
945                     dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
946                 }(formula)
947             );
948             this.dfeOffset += entries_applied;
949         };
950     };
951
952     /**
953      * This function updates the DF store for the dropdown so that use_counts
954      * can reflect DF applications from this session before they're saved
955      * server-side.
956      */
957     this._updateFormulaStore = function() {
958         this.dfSelector.store = new dojo.data.ItemFileReadStore(
959             {
960                 "data": self._labelFormulasWithCounts(
961                     acqdf.toStoreData(self.distribForms)
962                 )
963             }
964         );
965     };
966
967     this.saveCopyFieldsBeforeDF = function(copy_id) {
968         var self = this;
969         if (!this.oldCopyWidgetCache[copy_id]) {
970             var copyWidgets = this.copyWidgetCache[copy_id];
971
972             this.oldCopyWidgetCache[copy_id] = {};
973             this._copy_fields_for_acqdf.forEach(
974                 function(f) {
975                     self.oldCopyWidgetCache[copy_id][f] =
976                         copyWidgets[f].attr("value");
977                 }
978             );
979         }
980     };
981
982     this.restoreCopyFieldsBeforeDF = function() {
983         var self = this;
984         for (var copy_id in this.oldCopyWidgetCache) {
985             this._copy_fields_for_acqdf.forEach(
986                 function(f) {
987                     self.copyWidgetCache[copy_id][f].attr(
988                         "value", self.oldCopyWidgetCache[copy_id][f]
989                     );
990                 }
991             );
992         }
993     };
994
995     this._labelFormulasWithCounts = function(store_data) {
996         for (var key in store_data.items) {
997             var obj = store_data.items[key];
998             obj.use_count = Number(obj.use_count); /* needed for sorting */
999
1000             if (this.virtDfaCounts[obj.id])
1001                 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
1002
1003             obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
1004                 obj.use_count + "]</span>&nbsp; " + obj.name;
1005         }
1006         return store_data;
1007     };
1008
1009     /**
1010      * This method formerly would not refetch the DF formulas if they'd been
1011      * loaded already, but now it always re-fetches, since use_count changes.
1012      */
1013     this._fetchDistribFormulas = function(onload) {
1014         fieldmapper.standardRequest(
1015             ["open-ils.acq",
1016                 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
1017             {
1018                 "async": true,
1019                 "params": [openils.User.authtoken],
1020                 "oncomplete": function(r) {
1021                     self.distribForms = openils.Util.readResponse(r);
1022                     if(!self.distribForms || self.distribForms.length == 0) {
1023                         self.distribForms = [];
1024                     }
1025                     self._addDistribFormulaRow();
1026                     onload();
1027                 }
1028             }
1029         );
1030     }
1031
1032     this._drawBatchCopyWidgets = function() {
1033         var row = this.copyBatchRow;
1034         dojo.forEach(liDetailBatchFields, 
1035             function(field) {
1036                 if(self.copyBatchRowDrawn) {
1037                     self.copyBatchWidgets[field].attr('value', null);
1038                 } else {
1039                     var widget = new openils.widget.AutoFieldWidget({
1040                         fmField : field,
1041                         fmClass : 'acqlid',
1042                         parentNode : dojo.query('[name='+field+']', row)[0],
1043                         orgLimitPerms : ['CREATE_PICKLIST'],
1044                         dijitArgs : {required:false},
1045                         forceSync : true
1046                     });
1047                     widget.build(
1048                         function(w, ww) {
1049                             self.copyBatchWidgets[field] = w;
1050                         }
1051                     );
1052                 }
1053             }
1054         );
1055         this.copyBatchRowDrawn = true;
1056     };
1057
1058     this.batchCopyUpdate = function() {
1059         var self = this;
1060         for(var k in this.copyWidgetCache) {
1061             var cache = this.copyWidgetCache[k];
1062             dojo.forEach(liDetailBatchFields, function(f) {
1063                 var newval = self.copyBatchWidgets[f].attr('value');
1064                 if(newval) cache[f].attr('value', newval);
1065             });
1066         }
1067     };
1068
1069     this._drawCopies = function(li) {
1070         var self = this;
1071
1072         // this button sets the total number of copies for a given lineitem
1073         acqLitAddCopyCount.onClick = function() { 
1074             var count = acqLitCopyCountInput.attr('value');
1075
1076             // add new rows
1077             while(self.copyCount() < count)
1078                 self.addCopy(li); 
1079             
1080             // delete rows if necessary
1081             var diff = self.copyCount() - count;
1082             if(diff > 0) {
1083                 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
1084                 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
1085                     dojo.forEach(rows, function(row) {self.deleteCopy(row); });
1086                 } else {
1087                     acqLitCopyCountInput.attr('value', self.copyCount()+'');
1088                 }
1089             }
1090         }
1091
1092
1093         if(li.lineitem_details().length > 0) {
1094             dojo.forEach(li.lineitem_details(),
1095                 function(copy) {
1096                     self.addCopy(li, copy);
1097                 }
1098             );
1099         } else {
1100             self.addCopy(li);
1101         }
1102     };
1103
1104     this.copyCount = function() {
1105         var count = 0;
1106         for(var id in this.copyCache) {
1107             if(!this.copyCache[id].isdeleted())
1108                 count++;
1109         }
1110         return count;
1111     }
1112
1113     this.virtCopyId = -1;
1114     this.addCopy = function(li, copy) {
1115         var row = this.copyRow.cloneNode(true);
1116         this.copyTbody.appendChild(row);
1117         var self = this;
1118
1119         if(!copy) {
1120             copy = new fieldmapper.acqlid();
1121             copy.isnew(true);
1122             copy.id(this.virtCopyId--);
1123             copy.lineitem(li.id());
1124         }
1125
1126         this.copyCache[copy.id()] = copy;
1127         row.setAttribute('copy_id', copy.id());
1128         self.copyWidgetCache[copy.id()] = {};
1129
1130         acqLitCopyCountInput.attr('value', self.copyCount()+'');
1131
1132         dojo.forEach(liDetailFields,
1133             function(field) {
1134                 var widget = new openils.widget.AutoFieldWidget({
1135                     fmObject : copy,
1136                     fmField : field,
1137                     fmClass : 'acqlid',
1138                     parentNode : dojo.query('[name='+field+']', row)[0],
1139                     orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
1140                     readOnly : Boolean(copy.eg_copy_id())
1141                 });
1142                 widget.build(
1143                     // make sure we capture the value from any async widgets
1144                     function(w, ww) { 
1145                         copy[field](ww.getFormattedValue()) 
1146                         self.copyWidgetCache[copy.id()][field] = w;
1147                     }
1148                 );
1149                 dojo.connect(widget.widget, 'onChange', 
1150                     function(val) { 
1151                         if(copy.isnew() || val != copy[field]()) {
1152                             // prevent setting ischanged() automatically on widget load for existing copies
1153                             copy[field](widget.getFormattedValue()) 
1154                             copy.ischanged(true);
1155                         }
1156                     }
1157                 );
1158             }
1159         );
1160
1161         this.updateLidReceivedness(copy, row);
1162     };
1163
1164     this.updateLidReceivedness = function(copy, row) {
1165         if (typeof(row) == "undefined") {
1166             row = dojo.query(
1167                 'tr[copy_id="' + copy.id() + '"]', this.copyTbody
1168             )[0];
1169         }
1170
1171         var self = this;
1172         var recv_link = nodeByName("receive", row);
1173         var unrecv_link = nodeByName("unreceive", row);
1174         var del_link = nodeByName("delete", row);
1175
1176         if (this.isPO) {
1177             openils.Util.hide(del_link.parentNode);
1178
1179             /* Avoid showing (un)receive links for virtual copies */
1180             if (copy.id() > 0) {
1181                 if(copy.recv_time()) {
1182                     openils.Util.hide(recv_link);
1183                     openils.Util.show(unrecv_link);
1184                     unrecv_link.onclick = function() {
1185                         if (confirm(localeStrings.UNRECEIVE_LID))
1186                             self.issueReceive(copy, /* rollback */ true);
1187                     };
1188                 } else {
1189                     openils.Util.hide(unrecv_link);
1190                     openils.Util.show(recv_link);
1191                     recv_link.onclick = function() {
1192                         if (self.checkLiAlerts(copy.lineitem()))
1193                             self.issueReceive(copy);
1194                     };
1195                 }
1196             } else {
1197                 openils.Util.hide(unrecv_link);
1198                 openils.Util.hide(recv_link);
1199             }
1200         } else {
1201             openils.Util.hide(unrecv_link);
1202             openils.Util.hide(recv_link);
1203
1204             del_link.onclick = function() { self.deleteCopy(row) };
1205             openils.Util.show(del_link.parentNode);
1206         }
1207     }
1208
1209     this._confirmAlert = function(li, lin) {
1210         return confirm(
1211             dojo.string.substitute(
1212                 localeStrings.CONFIRM_LI_ALERT, [
1213                     (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1214                         "title", "lineitem_marc_attr_definition"
1215                     ),
1216                     lin.alert_text().code(),
1217                     lin.alert_text().description() || "",
1218                     lin.value()
1219                 ]
1220             )
1221         );
1222     };
1223
1224     this.checkLiAlerts = function(li_id) {
1225         var li = this.liCache[li_id];
1226
1227         var alert_notes = li.lineitem_notes().filter(
1228             function(o) { return Boolean(o.alert_text()); }
1229         );
1230
1231         /* this is _intentionally_ not done in a call to forEach() ... */
1232         for (var i = 0; i < alert_notes.length; i++) {
1233             if (this.noteAcks[alert_notes[i].id()])
1234                 continue;
1235             else if (!this._confirmAlert(li, alert_notes[i]))
1236                 return false;
1237             else
1238                 this.noteAcks[alert_notes[i].id()] = true;
1239         }
1240
1241         return true;
1242     };
1243
1244     this.deleteCopy = function(row) {
1245         var copy = this.copyCache[row.getAttribute('copy_id')];
1246         copy.isdeleted(true);
1247         if(copy.isnew())
1248             delete this.copyCache[copy.id()];
1249         this.copyTbody.removeChild(row);
1250     }
1251
1252     this._virtDfaCountsAsList = function() {
1253         var L = [];
1254         for (var key in this.virtDfaCounts) {
1255             for (var i = 0; i < this.virtDfaCounts[key]; i++)
1256                 L.push(key);
1257         }
1258         return L;
1259     }
1260
1261     this.saveCopyChanges = function(liId) {
1262         var self = this;
1263         var copies = [];
1264
1265
1266         var total = 0;
1267         for(var id in this.copyCache) {
1268             var c = this.copyCache[id];
1269             if(!c.isdeleted()) total++;
1270             if(c.isnew() || c.ischanged() || c.isdeleted()) {
1271                 if(c.id() < 0) c.id(null);
1272                 copies.push(c);
1273             }
1274         }
1275
1276         if (typeof(this._copy_count_cb) == "function") {
1277             this._copy_count_cb(liId, total);
1278         }
1279
1280         dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
1281
1282
1283         if (copies.length > 0) {
1284             openils.Util.show("acq-lit-update-copies-progress");
1285             fieldmapper.standardRequest(
1286                 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1287                 {   async: true,
1288                     params: [openils.User.authtoken, copies],
1289                     onresponse: function(r) {
1290                         var res = openils.Util.readResponse(r);
1291                         litUpdateCopiesProgress.update(res);
1292                     },
1293                     oncomplete: function() {
1294                         self.drawCopies(liId);
1295                         openils.Util.hide("acq-lit-update-copies-progress");
1296                     }
1297                 }
1298             );
1299         }
1300
1301         var dfa_list = this._virtDfaCountsAsList();
1302         if (dfa_list.length > 0) {
1303             fieldmapper.standardRequest(
1304                 ["open-ils.acq",
1305                 "open-ils.acq.distribution_formula.record_application"],
1306                 {
1307                     "async": true,
1308                     "params": [openils.User.authtoken, dfa_list, liId],
1309                     "onresponse": function(r) {
1310                         var res = openils.Util.readResponse(r);
1311                         if (res && res.length < dfa_list.length)
1312                             alert(localeStrings.DFA_NOT_ALL);
1313                     }
1314                 }
1315             );
1316             this.virtDfaCounts = {};
1317         }
1318     }
1319
1320     this.applySelectedLiAction = function(action) {
1321         var self = this;
1322         switch(action) {
1323
1324             case 'delete_selected':
1325                 this._deleteLiList(self.getSelected());
1326                 break;
1327
1328             case 'create_order':
1329
1330                 if(!this.createPoProviderSelector) {
1331                     var widget = new openils.widget.AutoFieldWidget({
1332                         fmField : 'provider',
1333                         fmClass : 'acqpo',
1334                         searchFilter: {"active": "t"},
1335                         parentNode : dojo.byId('acq-lit-po-provider'),
1336                     });
1337                     widget.build(
1338                         function(w) { self.createPoProviderSelector = w; }
1339                     );
1340                 }
1341
1342                 if(!this.createPoAgencySelector) {
1343                     var widget = new openils.widget.AutoFieldWidget({
1344                         fmField : 'ordering_agency',
1345                         fmClass : 'acqpo',
1346                         parentNode : dojo.byId('acq-lit-po-agency'),
1347                         orgLimitPerms : ['CREATE_PURCHASE_ORDER'],
1348                     });
1349                     widget.build(
1350                         function(w) { self.createPoAgencySelector = w; }
1351                     );
1352                 }
1353
1354          
1355                 acqLitPoCreateDialog.show();
1356                 break;
1357
1358             case 'save_picklist':
1359                 this._loadPLSelect();
1360                 acqLitSavePlDialog.show();
1361                 break;
1362
1363             case 'selector_ready':
1364             case 'order_ready':
1365                 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
1366                 acqLitChangeLiStateDialog.show();
1367                 break;
1368
1369             case 'print_po':
1370                 this.printPO();
1371                 break;
1372
1373             case 'receive_po':
1374                 this.receivePO();
1375                 break;
1376
1377             case 'rollback_receive_po':
1378                 this.rollbackPoReceive();
1379                 break;
1380
1381             case 'create_assets':
1382                 this.createAssets();
1383                 break;
1384
1385             case 'export_attr_list':
1386                 this.chooseExportAttr();
1387                 break;
1388
1389             case 'add_brief_record':
1390                 if(this.isPO)
1391                     location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
1392                 else
1393                     location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
1394         }
1395     }
1396
1397     this.createAssets = function() {
1398         if(!this.isPO) return;
1399         if(!confirm(localeStrings.CREATE_PO_ASSETS_CONFIRM)) return;
1400         this.show('acq-lit-progress-numbers');
1401         var self = this;
1402         fieldmapper.standardRequest(
1403             ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
1404             {   async: true,
1405                 params: [this.authtoken, this.isPO],
1406                 onresponse: function(r) {
1407                     var resp = openils.Util.readResponse(r);
1408                     self._updateProgressNumbers(resp, true);
1409                 }
1410             }
1411         );
1412     }
1413
1414     this.chooseExportAttr = function() {
1415         if (!acqLitExportAttrSelector._li_setup) {
1416             var self = this;
1417             acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
1418                 {
1419                     "data": acqliad.toStoreData(
1420                         this.pcrud.search(
1421                             "acqliad", {"code": li_exportable_attrs}
1422                         )
1423                     )
1424                 }
1425             );
1426             acqLitExportAttrSelector.setValue();
1427             acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
1428             acqLitExportAttrSelector._li_setup = true;
1429         }
1430         openils.Util.show("acq-lit-export-attr-holder", "inline");
1431     };
1432
1433     this.exportAttrList = function() {
1434         var attr_def = acqLitExportAttrSelector.item;
1435         var li_list = this.getSelected();
1436         var value_list = li_list.map(
1437             function(li) {
1438                 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1439                     attr_def.code, "lineitem_marc_attr_definition"
1440                 );
1441             }
1442         ).filter(function(attr) { return Boolean(attr); });
1443
1444         if (value_list.length > 0) {
1445             if (value_list.length < li_list.length) {
1446                 if (!confirm(
1447                     dojo.string.substitute(
1448                         localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
1449                     )
1450                 )) {
1451                     return;
1452                 }
1453             }
1454             try {
1455                 openils.XUL.contentToFileSaveDialog(
1456                     value_list.join("\n"),
1457                     localeStrings.EXPORT_SAVE_DIALOG_TITLE
1458                 );
1459             } catch (E) {
1460                 alert(E);
1461             }
1462         } else {
1463             alert(dojo.string.substitute(
1464                 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
1465             ));
1466         }
1467
1468         openils.Util.hide("acq-lit-export-attr-holder");
1469     };
1470
1471     this.printPO = function() {
1472         if(!this.isPO) return;
1473         progressDialog.show(true);
1474         fieldmapper.standardRequest(
1475             ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
1476             {   async: true,
1477                 params: [this.authtoken, this.isPO, 'html'],
1478                 oncomplete: function(r) {
1479                     progressDialog.hide();
1480                     var evt = openils.Util.readResponse(r);
1481                     if(evt && evt.template_output()) {
1482                         win = window.open('','', 'resizable,width=800,height=600,scrollbars=1');
1483                         win.document.body.innerHTML = evt.template_output().data();
1484                     }
1485                 }
1486             }
1487         );
1488     }
1489
1490
1491     this.receivePO = function() {
1492         if (!this.isPO) return;
1493
1494         for (var id in this.liCache) {
1495             /* assumption: liCache reflects exactly the
1496              * set of LIs that belong to our PO */
1497             if (this.liCache[id].state() != "received" &&
1498                 !this.checkLiAlerts(id)) return;
1499         }
1500
1501         this.show('acq-lit-progress-numbers');
1502         var self = this;
1503         fieldmapper.standardRequest(
1504             ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
1505             {   async: true,
1506                 params: [this.authtoken, this.isPO],
1507                 onresponse : function(r) {
1508                     var resp = openils.Util.readResponse(r);
1509                     self._updateProgressNumbers(resp, true);
1510                 },
1511             }
1512         );
1513     }
1514
1515     this.issueReceive = function(obj, rollback) {
1516         /* (For now) there shall be no marking LI or LIDs (un)received
1517          * except from the actual "view PO" interface. */
1518         if (!this.isPO) return;
1519
1520         var part =
1521             {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
1522         var method =
1523             "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
1524
1525         progressDialog.show(true);
1526         fieldmapper.standardRequest(
1527             ["open-ils.acq", method], {
1528                 "async": true,
1529                 "params": [this.authtoken, obj.id()],
1530                 "onresponse": function(r) {
1531                     self.handleReceive(openils.Util.readResponse(r));
1532                 },
1533                 "oncomplete": function() { progressDialog.hide(); }
1534             }
1535         );
1536     };
1537
1538     /**
1539      * Handles the responses from receive and rollback ML calls.
1540      */
1541     this.handleReceive = function(resp) {
1542         if (resp) {
1543             if (resp.li) {
1544                 for (var li_id in resp.li) {
1545                     for (var key in resp.li[li_id])
1546                         self.liCache[li_id][key](resp.li[li_id][key]);
1547                     self.updateLiReceivedness(self.liCache[li_id]);
1548                 }
1549             }
1550             if (resp.po) {
1551                 if (typeof(self.poUpdateCallback) == "function")
1552                     self.poUpdateCallback(resp.po);
1553             }
1554             if (resp.lid) {
1555                 for (var lid_id in resp.lid) {
1556                     for (var key in resp.lid[lid_id])
1557                         self.copyCache[lid_id][key](resp.lid[lid_id][key]);
1558                     self.updateLidReceivedness(self.copyCache[lid_id]);
1559                 }
1560             }
1561         }
1562     };
1563
1564     this.rollbackPoReceive = function() {
1565         if(!this.isPO) return;
1566         if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
1567         this.show('acq-lit-progress-numbers');
1568         var self = this;
1569         fieldmapper.standardRequest(
1570             ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
1571             {   async: true,
1572                 params: [this.authtoken, this.isPO],
1573                 onresponse : function(r) {
1574                     var resp = openils.Util.readResponse(r);
1575                     self._updateProgressNumbers(resp, true);
1576                 },
1577             }
1578         );
1579     }
1580
1581     this._updateProgressNumbers = function(resp, reloadOnComplete) {
1582         if(!resp) return;
1583         dojo.byId('acq-pl-lit-li-processed').innerHTML = resp.li;
1584         dojo.byId('acq-pl-lit-lid-processed').innerHTML = resp.lid;
1585         dojo.byId('acq-pl-lit-debits-processed').innerHTML = resp.debits_accrued;
1586         dojo.byId('acq-pl-lit-bibs-processed').innerHTML = resp.bibs;
1587         dojo.byId('acq-pl-lit-indexed-processed').innerHTML = resp.indexed;
1588         dojo.byId('acq-pl-lit-copies-processed').innerHTML = resp.copies;
1589         if(resp.complete && reloadOnComplete) 
1590             location.href = location.href;
1591     }
1592
1593
1594     this._createPO = function(fields) {
1595         this.show('acq-lit-progress-numbers');
1596         var po = new fieldmapper.acqpo();
1597         po.provider(this.createPoProviderSelector.attr('value'));
1598         po.ordering_agency(this.createPoAgencySelector.attr('value'));
1599
1600         var selected = this.getSelected( (fields.create_from == 'all') );
1601         if(selected.length == 0) return;
1602
1603         var max = selected.length * 3;
1604
1605         var self = this;
1606         fieldmapper.standardRequest(
1607             ['open-ils.acq', 'open-ils.acq.purchase_order.create'],
1608             {   async: true,
1609                 params: [
1610                     openils.User.authtoken, 
1611                     po, 
1612                     {
1613                         lineitems : selected.map(function(li) { return li.id() }),
1614                         create_assets : fields.create_assets[0],
1615                     }
1616                 ],
1617
1618                 onresponse : function(r) {
1619                     var resp = openils.Util.readResponse(r);
1620                     self._updateProgressNumbers(resp);
1621                     if(resp.complete) 
1622                         location.href = oilsBasePath + '/eg/acq/po/view/' + resp.purchase_order.id();
1623                 }
1624             }
1625         );
1626     }
1627
1628     this._deleteLiList = function(list, idx) {
1629         if(idx == null) idx = 0;
1630         if(idx >= list.length) return;
1631         var liId = list[idx].id();
1632         fieldmapper.standardRequest(
1633             ['open-ils.acq', 'open-ils.acq.lineitem.delete'],
1634             {   async: true,
1635                 params: [openils.User.authtoken, liId],
1636                 oncomplete: function(r) {
1637                     self.removeLineitem(liId);
1638                     self._deleteLiList(list, ++idx);
1639                 }
1640             }
1641         );
1642     }
1643
1644     this.editOrderMarc = function(li) {
1645
1646         /*  To run in Firefox directly, must set signed.applets.codebase_principal_support
1647             to true in about:config */
1648
1649         if(!openils.XUL.enableXPConnect()) return;
1650
1651         if(openils.XUL.isXUL()) {
1652             win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
1653         } else {
1654             win = window.open('/xul/server/cat/marcedit.xul'); 
1655         }
1656         var self = this;
1657         win.xulG = {
1658             record : {marc : li.marc()},
1659             save : {
1660                 label: 'Save Record', // XXX I18N
1661                 func: function(xmlString) {
1662                     li.marc(xmlString);
1663                     fieldmapper.standardRequest(
1664                         ['open-ils.acq', 'open-ils.acq.lineitem.update'],
1665                         {   async: true,
1666                             params: [openils.User.authtoken, li],
1667                             oncomplete: function(r) {
1668                                 openils.Util.readResponse(r);
1669                                 win.close();
1670                                 self.drawInfo(li.id())
1671                             }
1672                         }
1673                     );
1674                 },
1675             }
1676         };
1677     }
1678
1679     this._savePl = function(values) {
1680         var self = this;
1681         var selected = this.getSelected( (values.which == 'all') );
1682         openils.Util.show('acq-lit-generic-progress');
1683
1684         if(values.new_name) {
1685             openils.acq.Picklist.create(
1686                 {name: values.new_name}, 
1687                 function(id) {
1688                     self._updateLiList(id, selected, 0, 
1689                         function(){
1690                             location.href = oilsBasePath + '/eg/acq/picklist/view/' + id;
1691                         });
1692                 }
1693             );
1694         } else if(values.existing_pl) {
1695             // update lineitems to use an existing picklist
1696             self._updateLiList(values.existing_pl, selected, 0, 
1697                 function(){
1698                     location.href = oilsBasePath + '/eg/acq/picklist/view/' + values.existing_pl;
1699                 });
1700         }
1701     }
1702
1703     this._updateLiState = function(values, state) {
1704         var self = this;
1705         var selected = this.getSelected( (values.which == 'all') );
1706         if(!selected.length) return;
1707         dojo.forEach(selected, function(li) {li.state(state);});
1708         self._updateLiList(null, selected, 0, 
1709             // TODO consider inline updates for efficiency
1710             function() { location.href = location.href }
1711         );
1712     }
1713
1714     this._updateLiList = function(pl, list, idx, oncomplete) {
1715         if(idx >= list.length) return oncomplete();
1716         var li = list[idx];
1717         if(pl != null) li.picklist(pl);
1718         litGenericProgress.update({maximum: list.length, progress: idx});
1719         new openils.acq.Lineitem({lineitem:li}).update(
1720             function(r) {
1721                 self._updateLiList(pl, list, ++idx, oncomplete);
1722             }
1723         );
1724     }
1725
1726     this._loadPLSelect = function() {
1727         if(this._plSelectLoaded) return;
1728         var plList = [];
1729         function handleResponse(r) {
1730             plList.push(r.recv().content());
1731         }
1732         var method = 'open-ils.acq.picklist.user.retrieve';
1733         fieldmapper.standardRequest(
1734             ['open-ils.acq', method],
1735             {   async: true,
1736                 params: [this.authtoken],
1737                 onresponse: handleResponse,
1738                 oncomplete: function() {
1739                     self._plSelectLoaded = true;
1740                     acqLitAddExistingSelect.store = 
1741                         new dojo.data.ItemFileReadStore({data:acqpl.toStoreData(plList)});
1742                     acqLitAddExistingSelect.setValue();
1743                 }
1744             }
1745         );
1746     }
1747
1748     // grab the li-details for this lineitem, grab the linked copies and volumes, add them to the table
1749     this.showRealCopies = function(li) {
1750         while(this.realCopiesTbody.childNodes[0])
1751             this.realCopiesTbody.removeChild(this.realCopiesTbody.childNodes[0]);
1752         this.show('real-copies');
1753
1754         this.realCopyList = [];
1755         this.volCache = {};
1756         var tabIndex = 1000;
1757         var self = this;
1758
1759         acqLitSaveRealCopies.onClick = function() {
1760             self.saveRealCopies();
1761         }
1762
1763         this._fetchLineitem(li.id(), 
1764             function(fullLi) {
1765                 li = self.liCache[li.id()] = fullLi;
1766
1767                 self.pcrud.search(
1768                     'acp', {
1769                         id : li.lineitem_details().map(
1770                             function(item) { return item.eg_copy_id() }
1771                         )
1772                     }, {
1773                         async : true,
1774                         streaming : true,
1775                         onresponse : function(r) {
1776                             var copy = openils.Util.readResponse(r);
1777                             var volId = copy.call_number();
1778                             var volume = self.volCache[volId];
1779                             if(!volume) {
1780                                 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
1781                             }
1782                             self.addRealCopy(volume, copy, tabIndex++);
1783                         }
1784                     }
1785                 );
1786             }
1787         );
1788     }
1789
1790     this.addRealCopy = function(volume, copy, tabIndex) {
1791         var row = this.realCopiesRow.cloneNode(true);
1792         this.realCopyList.push(copy);
1793
1794         var selectNode;
1795         dojo.forEach(
1796             ['owning_lib', 'location', 'circ_modifier', 'label', 'barcode'],
1797
1798             function(field) {
1799                 var isvol = (field == 'owning_lib' || field == 'label');
1800                 var widget = new openils.widget.AutoFieldWidget({
1801                     fmField : field,
1802                     fmObject : isvol ? volume : copy,
1803                     parentNode : nodeByName(field, row),
1804                     readOnly : (field != 'barcode'),
1805                 });
1806
1807                 var widgetDrawn = null;
1808
1809                 if(field == 'barcode') {
1810
1811                     widgetDrawn = function(w, ww) {
1812                         var node = w.domNode;
1813                         node.setAttribute('tabindex', ''+tabIndex);
1814
1815                         // on enter, select the next barcode input
1816                         dojo.connect(w, 'onKeyDown',
1817                             function(e) {
1818                                 if(e.keyCode == dojo.keys.ENTER) {
1819                                     var ti = node.getAttribute('tabindex');
1820                                     var nextNode = dojo.query('[tabindex=' + String(Number(ti) + 1) + ']', self.realCopiesTbody)[0];
1821                                     if(nextNode) nextNode.select();
1822                                 }
1823                             }
1824                         );
1825
1826                         dojo.connect(w, 'onChange', 
1827                             function(val) { 
1828                                 if(!val || val == copy.barcode()) return;
1829                                 copy.ischanged(true);
1830                                 copy.barcode(val);
1831                             }
1832                         );
1833
1834
1835                         if(self.realCopiesTbody.getElementsByTagName('TR').length == 0)
1836                             selectNode = node;
1837                     }
1838                 }
1839
1840                 widget.build(widgetDrawn);
1841             }
1842         );
1843
1844         this.realCopiesTbody.appendChild(row);
1845         if(selectNode) selectNode.select();
1846     };
1847
1848     this.saveRealCopies = function() {
1849         progressDialog.show(true);
1850         var list = this.realCopyList.filter(function(copy) { return copy.ischanged(); });
1851         this.pcrud.update(list, {oncomplete: function() { 
1852             progressDialog.hide();
1853             self.show('list');
1854         }});
1855     }
1856 }