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