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