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