]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/acq/common/li_table.js
added collection code. update copy count in li list when an li's copy count changes
[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.ProgressBar');
8 dojo.require('openils.User');
9 dojo.require('openils.Util');
10 dojo.require('openils.acq.Lineitem');
11 dojo.require('openils.acq.PO');
12 dojo.require('openils.acq.Picklist');
13 dojo.require('openils.widget.AutoFieldWidget');
14 dojo.require('dojo.data.ItemFileReadStore');
15 dojo.require('openils.widget.ProgressDialog');
16 dojo.require('openils.PermaCrud');
17 dojo.require('openils.XUL');
18
19 dojo.requireLocalization('openils.acq', 'acq');
20 var localeStrings = dojo.i18n.getLocalization('openils.acq', 'acq');
21 const XUL_OPAC_WRAPPER = 'chrome://open_ils_staff_client/content/cat/opac.xul';
22
23 function nodeByName(name, context) {
24     return dojo.query('[name='+name+']', context)[0];
25 }
26
27
28 var liDetailFields = ['fund', 'owning_lib', 'location', 'collection_code', 'circ_modifier', 'cn_label'];
29
30 function AcqLiTable() {
31
32     var self = this;
33     this.liCache = {};
34     this.toggleState = false;
35     this.tbody = dojo.byId('acq-lit-tbody');
36     this.selectors = [];
37     this.authtoken = openils.User.authtoken;
38     this.rowTemplate = this.tbody.removeChild(dojo.byId('acq-lit-row'));
39     this.copyTbody = dojo.byId('acq-lit-li-details-tbody');
40     this.copyRow = this.copyTbody.removeChild(dojo.byId('acq-lit-li-details-row'));
41     this.copyBatchRow = dojo.byId('acq-lit-li-details-batch-row');
42     this.copyBatchWidgets = {};
43     this.liNotesTbody = dojo.byId('acq-lit-notes-tbody');
44     this.liNotesRow = this.liNotesTbody.removeChild(dojo.byId('acq-lit-notes-row'));
45     this.realCopiesTbody = dojo.byId('acq-lit-real-copies-tbody');
46     this.realCopiesRow = this.realCopiesTbody.removeChild(dojo.byId('acq-lit-real-copies-row'));
47
48     dojo.connect(acqLitLiActionsSelector, 'onChange', 
49         function() { 
50             self.applySelectedLiAction(this.attr('value')) 
51             acqLitLiActionsSelector.attr('value', '_');
52         });
53
54     acqLitCreatePoSubmit.onClick = function() {
55         acqLitPoCreateDialog.hide();
56         self._createPO(acqLitPoCreateDialog.getValues());
57     }
58
59     acqLitSavePlButton.onClick = function() {
60         acqLitSavePlDialog.hide();
61         self._savePl(acqLitSavePlDialog.getValues());
62     }
63
64
65     //dojo.byId('acq-lit-notes-new-button').onclick = function(){acqLitCreateLiNoteDialog.show();}
66
67     dojo.byId('acq-lit-select-toggle').onclick = function(){self.toggleSelect()};
68     dojo.byId('acq-lit-info-back-button').onclick = function(){self.show('list')};
69     dojo.byId('acq-lit-copies-back-button').onclick = function(){self.show('list')};
70     dojo.byId('acq-lit-notes-back-button').onclick = function(){self.show('list')};
71     dojo.byId('acq-lit-real-copies-back-button').onclick = function(){self.show('list')};
72
73     this.reset = function() {
74         while(self.tbody.childNodes[0])
75             self.tbody.removeChild(self.tbody.childNodes[0]);
76         self.selectors = [];
77     };
78     
79     this.setNext = function(handler) {
80         var link = dojo.byId('acq-lit-next');
81         if(handler) {
82             dojo.style(link, 'visibility', 'visible');
83             link.onclick = handler;
84         } else {
85             dojo.style(link, 'visibility', 'hidden');
86         }
87     };
88
89     this.setPrev = function(handler) {
90         var link = dojo.byId('acq-lit-prev');
91         if(handler) {
92             dojo.style(link, 'visibility', 'visible'); 
93             link.onclick = handler; 
94         } else {
95             dojo.style(link, 'visibility', 'hidden');
96         }
97     };
98
99     this.show = function(div) {
100         openils.Util.hide('acq-lit-table-div');
101         openils.Util.hide('acq-lit-info-div');
102         openils.Util.hide('acq-lit-li-details');
103         openils.Util.hide('acq-lit-notes-div');
104         openils.Util.hide('acq-lit-real-copies-div');
105         switch(div) {
106             case 'list':
107                 openils.Util.show('acq-lit-table-div');
108                 break;
109             case 'info':
110                 openils.Util.show('acq-lit-info-div');
111                 break;
112             case 'copies':
113                 openils.Util.show('acq-lit-li-details');
114                 break;
115             case 'real-copies':
116                 openils.Util.show('acq-lit-real-copies-div');
117                 break;
118             case 'notes':
119                 openils.Util.show('acq-lit-notes-div');
120                 break;
121             default:
122                 if(div) 
123                     openils.Util.show(div);
124         }
125     }
126
127     this.hide = function() {
128         this.show(null);
129     }
130
131     this.toggleSelect = function() {
132         if(self.toggleState) 
133             dojo.forEach(self.selectors, function(i){i.checked = false});
134         else 
135             dojo.forEach(self.selectors, function(i){i.checked = true});
136         self.toggleState = !self.toggleState;
137     };
138
139
140     /** @param all If true, assume all are selected */
141     this.getSelected = function(all) {
142         var selected = [];
143         dojo.forEach(self.selectors, 
144             function(i) { 
145                 if(i.checked || all)
146                     selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
147             }
148         );
149         return selected;
150     };
151
152     this.setRowAttr = function(td, liWrapper, field, type) {
153         var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
154         td.appendChild(document.createTextNode(val));
155     };
156
157     this.addLineitem = function(li) {
158         this.liCache[li.id()] = li;
159
160         // sort the lineitem notes on edit_time
161         if(!li.lineitem_notes()) li.lineitem_notes([]);
162
163         var liWrapper = new openils.acq.Lineitem({lineitem:li});
164         var row = self.rowTemplate.cloneNode(true);
165         row.setAttribute('li', li.id());
166         var tds = dojo.query('[attr]', row);
167         dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
168         dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
169
170         var isbn = liWrapper.findAttr('isbn', 'lineitem_marc_attr_definition');
171         if(isbn) {
172             // XXX media prefix for added content
173             dojo.query('[name=jacket]', row)[0].setAttribute('src', '/opac/extras/ac/jacket/small/' + isbn);
174         }
175
176         dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
177         dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
178         dojo.query('[name=notes_count]', row)[0].innerHTML = li.lineitem_notes().length;
179         dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
180
181         var countNode = nodeByName('count', row);
182         countNode.innerHTML = li.item_count() || 0;
183         countNode.id = 'acq-lit-copy-count-label-' + li.id();
184
185         var priceInput = dojo.query('[name=price]', row)[0];
186         var priceData = liWrapper.getPrice();
187         priceInput.value = (priceData) ? priceData.price : '';
188         priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
189
190         var recv_link = dojo.query('[name=receive_link]', row)[0];
191
192         if(li.state() == 'received') {
193             // if the LI is received, hide the receive link and show the 'update barcodes' link
194             openils.Util.hide(recv_link)
195         } else {
196             recv_link.onclick = function() {
197                 self.receiveLi(li);
198                 openils.Util.hide(recv_link)
199             }
200         }
201
202         if(li.eg_bib_id()) {
203             var real_copies_link = dojo.query('[name=real_copies_link]', row)[0];
204             openils.Util.show(real_copies_link);
205             real_copies_link.onclick = function() {
206                 self.showRealCopies(li);
207             }
208         }
209
210         self.tbody.appendChild(row);
211         self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
212     };
213
214     this.drawLiNotes = function(li) {
215         var self = this;
216
217         li.lineitem_notes(
218             li.lineitem_notes().sort(
219                 function(a, b) { 
220                     if(a.edit_time() < b.edit_time()) return 1;
221                     return -1;
222                 }
223             )
224         );
225
226         while(this.liNotesTbody.childNodes[0])
227             this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
228         this.show('notes');
229
230         acqLitCreateLiNoteSubmit.onClick = function() {
231             var value = acqLitCreateNoteText.attr('value');
232             if(!value) return;
233             var note = new fieldmapper.acqlin();
234             note.isnew(true);
235             note.value(value);
236             note.lineitem(li.id());
237             self.updateLiNotes(li, note);
238         }
239
240         dojo.byId('acq-lit-notes-save-button').onclick = function() {
241             self.updateLiNotes(li);
242         }
243
244         dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
245     }
246
247     this.addLiNote = function(li, note) {
248         if(note.isdeleted()) return;
249         var self = this;
250         var row = self.liNotesRow.cloneNode(true);
251         dojo.query('[name=value]', row)[0].innerHTML = note.value();
252
253         dojo.query('[name=delete]', row)[0].onclick = function() {
254             note.isdeleted(true);
255             self.liNotesTbody.removeChild(row);
256         };
257
258         if(note.edit_time()) {
259             dojo.query('[name=edit_time]', row)[0].innerHTML = 
260                 dojo.date.locale.format(
261                     dojo.date.stamp.fromISOString(note.edit_time()), 
262                     {formatLength:'short'});
263         }
264
265         self.liNotesTbody.appendChild(row);
266     }
267
268     this.updateLiNotes = function(li, newNote) {
269
270         var notes;
271         if(newNote) {
272             notes = [newNote];
273         } else {
274             notes = li.lineitem_notes().filter(
275                 function(note) {
276                     if(note.ischanged() || note.isnew() || note.isdeleted())
277                         return note;
278                 }
279             );
280         }
281
282         if(notes.length == 0) return;
283         progressDialog.show();
284
285         fieldmapper.standardRequest(
286             ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
287             {   async : true,
288                 params : [this.authtoken, notes],
289                 onresponse : function(r) {
290                     var resp = openils.Util.readResponse(r);
291
292                     if(resp.complete) {
293
294                         if(!newNote) {
295                             // remove the old changed notes
296                             var list = [];
297                             dojo.forEach(li.lineitem_notes(), 
298                                 function(note) {
299                                     if(!(note.ischanged() || note.isnew() || note.isdeleted()))
300                                         list.push(note);
301                                 }
302                             );
303                             li.lineitem_notes(list);
304                         }
305
306                         progressDialog.hide();
307                         self.drawLiNotes(li);
308                         return;
309                     }
310
311                     progressDialog.update(resp);
312                     var newnote = resp.note;
313
314                     if(!newnote.isdeleted()) {
315                         newnote.isnew(false);
316                         newnote.ischanged(false);
317                         li.lineitem_notes().push(newnote);
318                     }
319                 },
320             }
321         );
322     }
323
324     this.updateLiPrice = function(input, li) {
325
326         var price = input.value;
327         var liWrapper = new openils.acq.Lineitem({lineitem:li});
328         var oldPrice = liWrapper.getPrice() || null;
329
330         if(oldPrice) oldPrice = oldPrice.price;
331         if(price == oldPrice) return;
332
333         fieldmapper.standardRequest(
334             ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
335             {   async : true,
336                 params : [this.authtoken, li.id(), price],
337                 oncomplete : function(r) {
338                     openils.Util.readResponse(r);
339                 }
340             }
341         );
342     }
343
344     this.removeLineitem = function(liId) {
345         this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
346         delete this.liCache[liId];
347         //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
348     }
349
350     this.drawInfo = function(liId) {
351         this.show('info');
352         openils.acq.Lineitem.fetchAttrDefs(
353             function() { 
354                 self._fetchLineitem(liId, function(li){self._drawInfo(li);}); 
355             } 
356         );
357     };
358
359     this._fetchLineitem = function(liId, handler) {
360
361         var li = this.liCache[liId];
362         if(li && li.marc() && li.lineitem_details())
363             return handler(li);
364         
365         fieldmapper.standardRequest(
366             ['open-ils.acq', 'open-ils.acq.lineitem.retrieve'],
367             {   async: true,
368
369                 params: [self.authtoken, liId, {
370                     flesh_attrs: true,
371                     flesh_li_details: true,
372                     flesh_fund_debit: true }],
373
374                 oncomplete: function(r) {
375                     var li = openils.Util.readResponse(r);
376                     handler(li)
377                 }
378             }
379         );
380     };
381
382     this._drawInfo = function(li) {
383
384         acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
385
386         if(li.eg_bib_id()) {
387             openils.Util.hide('acq-lit-marc-order-record-label');
388             openils.Util.hide(acqLitEditOrderMarc.domNode);
389             openils.Util.show('acq-lit-marc-real-record-label');
390         } else {
391             openils.Util.show('acq-lit-marc-order-record-label');
392             openils.Util.show(acqLitEditOrderMarc.domNode);
393             openils.Util.hide('acq-lit-marc-real-record-label');
394         }
395
396         this.drawMarcHTML(li);
397         this.infoTbody = dojo.byId('acq-lit-info-tbody');
398
399         if(!this.infoRow)
400             this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
401         while(this.infoTbody.childNodes[0])
402             this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
403
404         for(var i = 0; i < li.attributes().length; i++) {
405             var attr = li.attributes()[i];
406             var row = this.infoRow.cloneNode(true);
407
408             var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
409             var name = openils.acq.Lineitem.attrDefs[type].filter(
410                 function(a) {
411                     return (a.code() == attr.attr_name());
412                 }
413             ).pop().description();
414
415             dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
416             dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
417             this.infoTbody.appendChild(row);
418         }
419
420         if(li.eg_bib_id()) {
421             openils.Util.show('acq-lit-info-cat-link');
422             var link = dojo.byId('acq-lit-info-cat-link').getElementsByTagName('a')[0];
423
424             if(openils.XUL.isXUL()) {
425
426                 var makeRecTab = function() {
427                                     xulG.new_tab(
428                         XUL_OPAC_WRAPPER,
429                                             {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
430                                             {
431                             no_xulG : false, 
432                             show_nav_buttons : true, 
433                             show_print_button : true, 
434                             opac_url : xulG.url_prefix(xulG.urls.opac_rdetail + '?r=' + li.eg_bib_id())
435                         }
436                     );
437                 }
438                 link.setAttribute('href', 'javascript:void(0);');
439                 link.onclick = makeRecTab;
440
441             } else {
442                 var href = link.getAttribute('href');
443                 if(href.match(/=$/))
444                     link.setAttribute('href',  href + li.eg_bib_id());
445             }
446         } else {
447             openils.Util.hide('acq-lit-info-cat-link');
448         }
449     };
450
451     this.drawMarcHTML = function(li) {
452         var params = [null, true, li.marc()];
453         if(li.eg_bib_id()) 
454             params = [li.eg_bib_id(), true];
455
456         fieldmapper.standardRequest(
457             ['open-ils.search', 'open-ils.search.biblio.record.html'],
458             {   async: true,
459                 params: params,
460                 oncomplete: function(r) {
461                     dojo.byId('acq-lit-marc-div').innerHTML = 
462                         openils.Util.readResponse(r);
463                 }
464             }
465         );
466     }
467
468     this.drawCopies = function(liId) {
469         this.show('copies');
470         var self = this;
471         this.copyCache = {};
472         this.copyWidgetCache = {};
473
474         acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
475         acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
476
477         while(this.copyTbody.childNodes[0])
478             this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
479
480         this._drawBatchCopyWidgets();
481
482         this._fetchDistribFormulas(
483             function() {
484                 openils.acq.Lineitem.fetchAttrDefs(
485                     function() { 
486                         self._fetchLineitem(liId, function(li){self._drawCopies(li);}); 
487                     } 
488                 );
489             }
490         );
491     };
492
493     this._fetchDistribFormulas = function(onload) {
494         if(this.distribForms) {
495             onload();
496         } else {
497             var self = this;
498             fieldmapper.standardRequest(
499                 ['open-ils.acq', 'open-ils.acq.distribution_formula.ranged.retrieve.atomic'],
500                 {   async: true,
501                     params: [openils.User.authtoken],
502                     oncomplete: function(r) {
503                         self.distribForms = openils.Util.readResponse(r);
504                         if(!self.distribForms || self.distribForms.length == 0) {
505                             self.distribForms  = [];
506                             return onload();
507                         }
508                         self.distribFormulaStore = 
509                             new dojo.data.ItemFileReadStore(
510                                 {data:acqdf.toStoreData(self.distribForms)});
511                         onload();
512                     }
513                 }
514             );
515         }
516     }
517
518     this._drawBatchCopyWidgets = function() {
519         var row = this.copyBatchRow;
520         dojo.forEach(liDetailFields, 
521             function(field) {
522                 if(self.copyBatchRowDrawn) {
523                     self.copyBatchWidgets[field].attr('value', null);
524                 } else {
525                     var widget = new openils.widget.AutoFieldWidget({
526                         fmField : field,
527                         fmClass : 'acqlid',
528                         parentNode : dojo.query('[name='+field+']', row)[0],
529                         orgLimitPerms : ['CREATE_PICKLIST'],
530                         dijitArgs : {required:false}
531                     });
532                     widget.build(
533                         function(w, ww) {
534                             self.copyBatchWidgets[field] = w;
535                         }
536                     );
537                 }
538             }
539         );
540         this.copyBatchRowDrawn = true;
541     };
542
543     this.batchCopyUpdate = function() {
544         var self = this;
545         for(var k in this.copyWidgetCache) {
546             var cache = this.copyWidgetCache[k];
547             dojo.forEach(liDetailFields, function(f) {
548                 var newval = self.copyBatchWidgets[f].attr('value');
549                 if(newval) cache[f].attr('value', newval);
550             });
551         }
552     };
553
554     this._drawCopies = function(li) {
555         acqLitAddCopyCount.onClick = function() { 
556             var count = acqLitCopyCountInput.attr('value');
557             for(var i = 0; i < count; i++)
558                 self.addCopy(li); 
559         }
560         if(li.lineitem_details().length > 0) {
561             dojo.forEach(li.lineitem_details(),
562                 function(copy) {
563                     self.addCopy(li, copy);
564                 }
565             );
566         } else {
567             self.addCopy(li);
568         }
569     };
570
571     this.virtCopyId = -1;
572     this.addCopy = function(li, copy) {
573         var row = this.copyRow.cloneNode(true);
574         this.copyTbody.appendChild(row);
575         var self = this;
576
577         if(!copy) {
578             copy = new fieldmapper.acqlid();
579             copy.isnew(true);
580             copy.id(this.virtCopyId--);
581             copy.lineitem(li.id());
582         }
583
584         this.copyCache[copy.id()] = copy;
585         row.setAttribute('copy_id', copy.id());
586         self.copyWidgetCache[copy.id()] = {};
587
588         dojo.forEach(liDetailFields,
589             function(field) {
590                 var widget = new openils.widget.AutoFieldWidget({
591                     fmObject : copy,
592                     fmField : field,
593                     fmClass : 'acqlid',
594                     parentNode : dojo.query('[name='+field+']', row)[0],
595                     orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
596                     readOnly : self.isPO
597                 });
598                 widget.build(
599                     // make sure we capture the value from any async widgets
600                     function(w, ww) { 
601                         copy[field](ww.getFormattedValue()) 
602                         self.copyWidgetCache[copy.id()][field] = w;
603                     }
604                 );
605                 dojo.connect(widget.widget, 'onChange', 
606                     function(val) { 
607                         if(copy.isnew() || val != copy[field]()) {
608                             // prevent setting ischanged() automatically on widget load for existing copies
609                             copy[field](widget.getFormattedValue()) 
610                             copy.ischanged(true);
611                         }
612                     }
613                 );
614             }
615         );
616
617         var recv_link = dojo.query('[name=receive]', row)[0];
618         if(copy.recv_time()) {
619             openils.Util.hide(recv_link);
620         } else {
621             recv_link.onclick = function() {
622                 self.receiveLid(copy);
623                 openils.Util.hide(recv_link);
624             }
625         }
626
627         if(this.isPO) {
628             openils.Util.hide(dojo.query('[name=delete]', row)[0].parentNode);
629         } else {
630             dojo.query('[name=delete]', row)[0].onclick = 
631                 function() { self.deleteCopy(row) };
632         }
633     };
634
635     this.deleteCopy = function(row) {
636         var copy = this.copyCache[row.getAttribute('copy_id')];
637         copy.isdeleted(true);
638         if(copy.isnew())
639             delete this.copyCache[copy.id()];
640         this.copyTbody.removeChild(row);
641     }
642
643     this.saveCopyChanges = function(liId) {
644         var self = this;
645         var copies = [];
646
647
648         openils.Util.show('acq-lit-update-copies-progress');
649
650         var total = 0;
651         for(var id in this.copyCache) {
652             var c = this.copyCache[id];
653             if(!c.isdeleted()) total++;
654             if(c.isnew() || c.ischanged() || c.isdeleted()) {
655                 if(c.id() < 0) c.id(null);
656                 copies.push(c);
657             }
658         }
659
660         dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
661
662         if(copies.length == 0)
663             return;
664
665         fieldmapper.standardRequest(
666             ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
667             {   async: true,
668                 params: [openils.User.authtoken, copies],
669                 onresponse: function(r) {
670                     var res = openils.Util.readResponse(r);
671                     litUpdateCopiesProgress.update(res);
672                 },
673                 oncomplete: function() {
674                     openils.Util.hide('acq-lit-update-copies-progress');
675                     self.drawCopies(liId); 
676                 }
677             }
678         );
679     }
680
681     this.applySelectedLiAction = function(action) {
682         var self = this;
683         switch(action) {
684
685             case 'delete_selected':
686                 this._deleteLiList(self.getSelected());
687                 break;
688
689             case 'create_order':
690
691                 if(!this.createPoProviderSelector) {
692                     var widget = new openils.widget.AutoFieldWidget({
693                         fmField : 'provider',
694                         fmClass : 'acqpo',
695                         parentNode : dojo.byId('acq-lit-po-provider'),
696                     });
697                     widget.build(
698                         function(w) { self.createPoProviderSelector = w; }
699                     );
700                 }
701
702                 if(!this.createPoAgencySelector) {
703                     var widget = new openils.widget.AutoFieldWidget({
704                         fmField : 'ordering_agency',
705                         fmClass : 'acqpo',
706                         parentNode : dojo.byId('acq-lit-po-agency'),
707                         orgLimitPerms : ['CREATE_PURCHASE_ORDER'],
708                     });
709                     widget.build(
710                         function(w) { self.createPoAgencySelector = w; }
711                     );
712                 }
713
714          
715                 acqLitPoCreateDialog.show();
716                 break;
717
718             case 'save_picklist':
719                 this._loadPLSelect();
720                 acqLitSavePlDialog.show();
721                 break;
722
723             case 'print_po':
724                 this.printPO();
725                 break;
726
727             case 'receive_po':
728                 this.receivePO();
729                 break;
730
731             case 'rollback_receive_po':
732                 this.rollbackPoReceive();
733                 break;
734
735             case 'create_assets':
736                 this.createAssets();
737                 break;
738
739             case 'add_brief_record':
740                 if(this.isPO)
741                     location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
742                 else
743                     location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
744         }
745     }
746
747     this.createAssets = function() {
748         if(!this.isPO) return;
749         if(!confirm(localeStrings.CREATE_PO_ASSETS_CONFIRM)) return;
750         this.show('acq-lit-progress-numbers');
751         var self = this;
752         fieldmapper.standardRequest(
753             ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
754             {   async: true,
755                 params: [this.authtoken, this.isPO],
756                 onresponse: function(r) {
757                     var resp = openils.Util.readResponse(r);
758                     self._updateProgressNumbers(resp, true);
759                 }
760             }
761         );
762     }
763
764     this.printPO = function() {
765         if(!this.isPO) return;
766         progressDialog.show(true);
767         fieldmapper.standardRequest(
768             ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
769             {   async: true,
770                 params: [this.authtoken, this.isPO, 'html'],
771                 oncomplete: function(r) {
772                     progressDialog.hide();
773                     var evt = openils.Util.readResponse(r);
774                     if(evt && evt.template_output()) {
775                         win = window.open('','', 'resizable,width=800,height=600,scrollbars=1');
776                         win.document.body.innerHTML = evt.template_output().data();
777                     }
778                 }
779             }
780         );
781     }
782
783
784     this.receivePO = function() {
785         if(!this.isPO) return;
786         this.show('acq-lit-progress-numbers');
787         var self = this;
788         fieldmapper.standardRequest(
789             ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
790             {   async: true,
791                 params: [this.authtoken, this.isPO],
792                 onresponse : function(r) {
793                     var resp = openils.Util.readResponse(r);
794                     self._updateProgressNumbers(resp, true);
795                 },
796             }
797         );
798     }
799
800     this.receiveLi = function(li) {
801         if(!this.isPO) return;
802         progressDialog.show(true);
803         fieldmapper.standardRequest(
804             ['open-ils.acq', 'open-ils.acq.lineitem.receive'],
805             {   async: true,
806                 params: [this.authtoken, li.id()],
807                 onresponse : function(r) {
808                     var resp = openils.Util.readResponse(r);
809                     progressDialog.hide();
810                 },
811             }
812         );
813     }
814
815     this.receiveLid = function(li) {
816         if(!this.isPO) return;
817         progressDialog.show(true);
818         fieldmapper.standardRequest(
819             ['open-ils.acq', 'open-ils.acq.lineitem_detail.receive'],
820             {   async: true,
821                 params: [this.authtoken, li.id()],
822                 onresponse : function(r) {
823                     var resp = openils.Util.readResponse(r);
824                     progressDialog.hide();
825                 },
826             }
827         );
828     }
829
830     this.rollbackPoReceive = function() {
831         if(!this.isPO) return;
832         if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
833         this.show('acq-lit-progress-numbers');
834         var self = this;
835         fieldmapper.standardRequest(
836             ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
837             {   async: true,
838                 params: [this.authtoken, this.isPO],
839                 onresponse : function(r) {
840                     var resp = openils.Util.readResponse(r);
841                     self._updateProgressNumbers(resp, true);
842                 },
843             }
844         );
845     }
846
847     this._updateProgressNumbers = function(resp, reloadOnComplete) {
848         if(!resp) return;
849         dojo.byId('acq-pl-lit-li-processed').innerHTML = resp.li;
850         dojo.byId('acq-pl-lit-lid-processed').innerHTML = resp.lid;
851         dojo.byId('acq-pl-lit-debits-processed').innerHTML = resp.debits_accrued;
852         dojo.byId('acq-pl-lit-bibs-processed').innerHTML = resp.bibs;
853         dojo.byId('acq-pl-lit-indexed-processed').innerHTML = resp.indexed;
854         dojo.byId('acq-pl-lit-copies-processed').innerHTML = resp.copies;
855         if(resp.complete && reloadOnComplete) 
856             location.href = location.href;
857     }
858
859
860     this._createPO = function(fields) {
861         this.show('acq-lit-progress-numbers');
862         var po = new fieldmapper.acqpo();
863         po.provider(this.createPoProviderSelector.attr('value'));
864         po.ordering_agency(this.createPoAgencySelector.attr('value'));
865
866         var selected = this.getSelected( (fields.create_from == 'all') );
867         if(selected.length == 0) return;
868
869         var max = selected.length * 3;
870
871         var self = this;
872         fieldmapper.standardRequest(
873             ['open-ils.acq', 'open-ils.acq.purchase_order.create'],
874             {   async: true,
875                 params: [
876                     openils.User.authtoken, 
877                     po, 
878                     {
879                         lineitems : selected.map(function(li) { return li.id() }),
880                         create_assets : fields.create_assets[0],
881                     }
882                 ],
883
884                 onresponse : function(r) {
885                     var resp = openils.Util.readResponse(r);
886                     self._updateProgressNumbers(resp);
887                     if(resp.complete) 
888                         location.href = oilsBasePath + '/eg/acq/po/view/' + resp.purchase_order.id();
889                 }
890             }
891         );
892     }
893
894     this._deleteLiList = function(list, idx) {
895         if(idx == null) idx = 0;
896         if(idx >= list.length) return;
897         var liId = list[idx].id();
898         fieldmapper.standardRequest(
899             ['open-ils.acq', 'open-ils.acq.lineitem.delete'],
900             {   async: true,
901                 params: [openils.User.authtoken, liId],
902                 oncomplete: function(r) {
903                     self.removeLineitem(liId);
904                     self._deleteLiList(list, ++idx);
905                 }
906             }
907         );
908     }
909
910     this.editOrderMarc = function(li) {
911
912         /*  To run in Firefox directly, must set signed.applets.codebase_principal_support
913             to true in about:config */
914
915         if(!openils.XUL.enableXPConnect()) return;
916
917         if(openils.XUL.isXUL()) {
918             win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
919         } else {
920
921             win = window.open('/xul/server/cat/marcedit.xul'); 
922             var self = this;
923             win.xulG = {
924                 record : {marc : li.marc()},
925                 save : {
926                     label: 'Save Record', // XXX I18N
927                     func: function(xmlString) {
928                         li.marc(xmlString);
929                         fieldmapper.standardRequest(
930                             ['open-ils.acq', 'open-ils.acq.lineitem.update'],
931                             {   async: true,
932                                 params: [openils.User.authtoken, li],
933                                 oncomplete: function(r) {
934                                     openils.Util.readResponse(r);
935                                     win.close();
936                                     self.drawInfo(li.id())
937                                 }
938                             }
939                         );
940                     },
941                 }
942             };
943         }
944     }
945
946     this._savePl = function(values) {
947         var self = this;
948         var selected = this.getSelected( (values.which == 'all') );
949         openils.Util.show('acq-lit-generic-progress');
950
951         if(values.new_name) {
952             openils.acq.Picklist.create(
953                 {name: values.new_name}, 
954                 function(id) {
955                     self._updateLiList(id, selected, 0, 
956                         function(){
957                             location.href = oilsBasePath + '/eg/acq/picklist/view/' + id;
958                         });
959                 }
960             );
961         } else if(values.existing_pl) {
962             // update lineitems to use an existing picklist
963             self._updateLiList(values.existing_pl, selected, 0, 
964                 function(){
965                     location.href = oilsBasePath + '/eg/acq/picklist/view/' + values.existing_pl;
966                 });
967         }
968     }
969
970     this._updateLiList = function(pl, list, idx, oncomplete) {
971         if(idx >= list.length) return oncomplete();
972         var li = list[idx];
973         li.picklist(pl);
974         litGenericProgress.update({maximum: list.length, progress: idx});
975         new openils.acq.Lineitem({lineitem:li}).update(
976             function(r) {
977                 self._updateLiList(pl, list, ++idx, oncomplete);
978             }
979         );
980     }
981
982     this._loadPLSelect = function() {
983         if(this._plSelectLoaded) return;
984         var plList = [];
985         function handleResponse(r) {
986             plList.push(r.recv().content());
987         }
988         var method = 'open-ils.acq.picklist.user.retrieve';
989         fieldmapper.standardRequest(
990             ['open-ils.acq', method],
991             {   async: true,
992                 params: [this.authtoken],
993                 onresponse: handleResponse,
994                 oncomplete: function() {
995                     self._plSelectLoaded = true;
996                     acqLitAddExistingSelect.store = 
997                         new dojo.data.ItemFileReadStore({data:acqpl.toStoreData(plList)});
998                     acqLitAddExistingSelect.setValue();
999                 }
1000             }
1001         );
1002     }
1003
1004     // grab the li-details for this lineitem, grab the linked copies and volumes, add them to the table
1005     this.showRealCopies = function(li) {
1006         while(this.realCopiesTbody.childNodes[0])
1007             this.realCopiesTbody.removeChild(this.realCopiesTbody.childNodes[0]);
1008         this.show('real-copies');
1009
1010         var pcrud = new openils.PermaCrud({authtoken : this.authtoken});
1011         this.realCopyList = [];
1012         this.volCache = {};
1013         var tabIndex = 1000;
1014         var self = this;
1015
1016         acqLitSaveRealCopies.onClick = function() {
1017             self.saveRealCopies();
1018         }
1019
1020         this._fetchLineitem(li.id(), 
1021             function(fullLi) {
1022                 li = self.liCache[li.id()] = fullLi;
1023
1024                 pcrud.search(
1025                     'acp', {
1026                         id : li.lineitem_details().map(
1027                             function(item) { return item.eg_copy_id() }
1028                         )
1029                     }, {
1030                         async : true,
1031                         streaming : true,
1032                         onresponse : function(r) {
1033                             var copy = openils.Util.readResponse(r);
1034                             var volId = copy.call_number();
1035                             var volume = self.volCache[volId];
1036                             if(!volume) {
1037                                 volume = self.volCache[volId] = pcrud.retrieve('acn', volId);
1038                             }
1039                             self.addRealCopy(volume, copy, tabIndex++);
1040                         }
1041                     }
1042                 );
1043             }
1044         );
1045     }
1046
1047     this.addRealCopy = function(volume, copy, tabIndex) {
1048         var row = this.realCopiesRow.cloneNode(true);
1049         this.realCopyList.push(copy);
1050
1051         var selectNode;
1052         dojo.forEach(
1053             ['owning_lib', 'location', 'circ_modifier', 'label', 'barcode'],
1054
1055             function(field) {
1056                 var isvol = (field == 'owning_lib' || field == 'label');
1057                 var widget = new openils.widget.AutoFieldWidget({
1058                     fmField : field,
1059                     fmObject : isvol ? volume : copy,
1060                     parentNode : nodeByName(field, row),
1061                     readOnly : (field != 'barcode'),
1062                 });
1063
1064                 var widgetDrawn = null;
1065
1066                 if(field == 'barcode') {
1067
1068                     widgetDrawn = function(w, ww) {
1069                         var node = w.domNode;
1070                         node.setAttribute('tabindex', ''+tabIndex);
1071
1072                         // on enter, select the next barcode input
1073                         dojo.connect(w, 'onKeyDown',
1074                             function(e) {
1075                                 if(e.keyCode == dojo.keys.ENTER) {
1076                                     var ti = node.getAttribute('tabindex');
1077                                     var nextNode = dojo.query('[tabindex=' + String(Number(ti) + 1) + ']', self.realCopiesTbody)[0];
1078                                     if(nextNode) nextNode.select();
1079                                 }
1080                             }
1081                         );
1082
1083                         dojo.connect(w, 'onChange', 
1084                             function(val) { 
1085                                 if(!val || val == copy.barcode()) return;
1086                                 copy.ischanged(true);
1087                                 copy.barcode(val);
1088                             }
1089                         );
1090
1091
1092                         if(self.realCopiesTbody.getElementsByTagName('TR').length == 0)
1093                             selectNode = node;
1094                     }
1095                 }
1096
1097                 widget.build(widgetDrawn);
1098             }
1099         );
1100
1101         this.realCopiesTbody.appendChild(row);
1102         if(selectNode) selectNode.select();
1103     };
1104
1105     this.saveRealCopies = function() {
1106         var pcrud = new openils.PermaCrud({authtoken : this.authtoken});
1107         progressDialog.show(true);
1108         var list = this.realCopyList.filter(function(copy) { return copy.ischanged(); });
1109         pcrud.update(list, {oncomplete: function() { 
1110             progressDialog.hide();
1111             self.show('list');
1112         }});
1113     }
1114 }
1115
1116
1117